VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/MediumImpl.cpp@ 38695

Last change on this file since 38695 was 38695, checked in by vboxsync, 14 years ago

warnings

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 267.6 KB
Line 
1/* $Id: MediumImpl.cpp 38695 2011-09-09 06:25:57Z vboxsync $ */
2/** @file
3 * VirtualBox COM class implementation
4 */
5
6/*
7 * Copyright (C) 2008-2011 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.215389.xyz. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18#include "MediumImpl.h"
19#include "ProgressImpl.h"
20#include "SystemPropertiesImpl.h"
21#include "VirtualBoxImpl.h"
22
23#include "AutoCaller.h"
24#include "Logging.h"
25
26#include <VBox/com/array.h>
27#include "VBox/com/MultiResult.h"
28#include "VBox/com/ErrorInfo.h"
29
30#include <VBox/err.h>
31#include <VBox/settings.h>
32
33#include <iprt/param.h>
34#include <iprt/path.h>
35#include <iprt/file.h>
36#include <iprt/tcp.h>
37#include <iprt/cpp/utils.h>
38
39#include <VBox/vd.h>
40
41#include <algorithm>
42
43////////////////////////////////////////////////////////////////////////////////
44//
45// Medium data definition
46//
47////////////////////////////////////////////////////////////////////////////////
48
49/** Describes how a machine refers to this medium. */
50struct BackRef
51{
52 /** Equality predicate for stdc++. */
53 struct EqualsTo : public std::unary_function <BackRef, bool>
54 {
55 explicit EqualsTo(const Guid &aMachineId) : machineId(aMachineId) {}
56
57 bool operator()(const argument_type &aThat) const
58 {
59 return aThat.machineId == machineId;
60 }
61
62 const Guid machineId;
63 };
64
65 BackRef(const Guid &aMachineId,
66 const Guid &aSnapshotId = Guid::Empty)
67 : machineId(aMachineId),
68 fInCurState(aSnapshotId.isEmpty())
69 {
70 if (!aSnapshotId.isEmpty())
71 llSnapshotIds.push_back(aSnapshotId);
72 }
73
74 Guid machineId;
75 bool fInCurState : 1;
76 GuidList llSnapshotIds;
77};
78
79typedef std::list<BackRef> BackRefList;
80
81struct Medium::Data
82{
83 Data()
84 : pVirtualBox(NULL),
85 state(MediumState_NotCreated),
86 variant(MediumVariant_Standard),
87 size(0),
88 readers(0),
89 preLockState(MediumState_NotCreated),
90 queryInfoSem(NIL_RTSEMEVENTMULTI),
91 queryInfoRunning(false),
92 type(MediumType_Normal),
93 devType(DeviceType_HardDisk),
94 logicalSize(0),
95 hddOpenMode(OpenReadWrite),
96 autoReset(false),
97 hostDrive(false),
98 implicit(false),
99 numCreateDiffTasks(0),
100 vdDiskIfaces(NULL),
101 vdImageIfaces(NULL)
102 { }
103
104 /** weak VirtualBox parent */
105 VirtualBox * const pVirtualBox;
106
107 // pParent and llChildren are protected by VirtualBox::getMediaTreeLockHandle()
108 ComObjPtr<Medium> pParent;
109 MediaList llChildren; // to add a child, just call push_back; to remove a child, call child->deparent() which does a lookup
110
111 GuidList llRegistryIDs; // media registries in which this medium is listed
112
113 const Guid id;
114 Utf8Str strDescription;
115 MediumState_T state;
116 MediumVariant_T variant;
117 Utf8Str strLocationFull;
118 uint64_t size;
119 Utf8Str strLastAccessError;
120
121 BackRefList backRefs;
122
123 size_t readers;
124 MediumState_T preLockState;
125
126 RTSEMEVENTMULTI queryInfoSem;
127 bool queryInfoRunning : 1;
128
129 const Utf8Str strFormat;
130 ComObjPtr<MediumFormat> formatObj;
131
132 MediumType_T type;
133 DeviceType_T devType;
134 uint64_t logicalSize;
135
136 HDDOpenMode hddOpenMode;
137
138 bool autoReset : 1;
139
140 /** New UUID to be set on the next queryInfo() call. */
141 const Guid uuidImage;
142 /** New parent UUID to be set on the next queryInfo() call. */
143 const Guid uuidParentImage;
144
145 bool hostDrive : 1;
146
147 settings::StringsMap mapProperties;
148
149 bool implicit : 1;
150
151 uint32_t numCreateDiffTasks;
152
153 Utf8Str vdError; /*< Error remembered by the VD error callback. */
154
155 VDINTERFACEERROR vdIfError;
156
157 VDINTERFACECONFIG vdIfConfig;
158
159 VDINTERFACETCPNET vdIfTcpNet;
160
161 PVDINTERFACE vdDiskIfaces;
162 PVDINTERFACE vdImageIfaces;
163};
164
165typedef struct VDSOCKETINT
166{
167 /** Socket handle. */
168 RTSOCKET hSocket;
169} VDSOCKETINT, *PVDSOCKETINT;
170
171////////////////////////////////////////////////////////////////////////////////
172//
173// Globals
174//
175////////////////////////////////////////////////////////////////////////////////
176
177/**
178 * Medium::Task class for asynchronous operations.
179 *
180 * @note Instances of this class must be created using new() because the
181 * task thread function will delete them when the task is complete.
182 *
183 * @note The constructor of this class adds a caller on the managed Medium
184 * object which is automatically released upon destruction.
185 */
186class Medium::Task
187{
188public:
189 Task(Medium *aMedium, Progress *aProgress)
190 : mVDOperationIfaces(NULL),
191 m_pllRegistriesThatNeedSaving(NULL),
192 mMedium(aMedium),
193 mMediumCaller(aMedium),
194 mThread(NIL_RTTHREAD),
195 mProgress(aProgress),
196 mVirtualBoxCaller(NULL)
197 {
198 AssertReturnVoidStmt(aMedium, mRC = E_FAIL);
199 mRC = mMediumCaller.rc();
200 if (FAILED(mRC))
201 return;
202
203 /* Get strong VirtualBox reference, see below. */
204 VirtualBox *pVirtualBox = aMedium->m->pVirtualBox;
205 mVirtualBox = pVirtualBox;
206 mVirtualBoxCaller.attach(pVirtualBox);
207 mRC = mVirtualBoxCaller.rc();
208 if (FAILED(mRC))
209 return;
210
211 /* Set up a per-operation progress interface, can be used freely (for
212 * binary operations you can use it either on the source or target). */
213 mVDIfProgress.pfnProgress = vdProgressCall;
214 int vrc = VDInterfaceAdd(&mVDIfProgress.Core,
215 "Medium::Task::vdInterfaceProgress",
216 VDINTERFACETYPE_PROGRESS,
217 mProgress,
218 sizeof(VDINTERFACEPROGRESS),
219 &mVDOperationIfaces);
220 AssertRC(vrc);
221 if (RT_FAILURE(vrc))
222 mRC = E_FAIL;
223 }
224
225 // Make all destructors virtual. Just in case.
226 virtual ~Task()
227 {}
228
229 HRESULT rc() const { return mRC; }
230 bool isOk() const { return SUCCEEDED(rc()); }
231
232 static int fntMediumTask(RTTHREAD aThread, void *pvUser);
233
234 bool isAsync() { return mThread != NIL_RTTHREAD; }
235
236 PVDINTERFACE mVDOperationIfaces;
237
238 // Whether the caller needs to call VirtualBox::saveRegistries() after
239 // the task function returns. Only used in synchronous (wait) mode;
240 // otherwise the task will save the settings itself.
241 GuidList *m_pllRegistriesThatNeedSaving;
242
243 const ComObjPtr<Medium> mMedium;
244 AutoCaller mMediumCaller;
245
246 friend HRESULT Medium::runNow(Medium::Task*, GuidList *);
247
248protected:
249 HRESULT mRC;
250 RTTHREAD mThread;
251
252private:
253 virtual HRESULT handler() = 0;
254
255 const ComObjPtr<Progress> mProgress;
256
257 static DECLCALLBACK(int) vdProgressCall(void *pvUser, unsigned uPercent);
258
259 VDINTERFACEPROGRESS mVDIfProgress;
260
261 /* Must have a strong VirtualBox reference during a task otherwise the
262 * reference count might drop to 0 while a task is still running. This
263 * would result in weird behavior, including deadlocks due to uninit and
264 * locking order issues. The deadlock often is not detectable because the
265 * uninit uses event semaphores which sabotages deadlock detection. */
266 ComObjPtr<VirtualBox> mVirtualBox;
267 AutoCaller mVirtualBoxCaller;
268};
269
270class Medium::CreateBaseTask : public Medium::Task
271{
272public:
273 CreateBaseTask(Medium *aMedium,
274 Progress *aProgress,
275 uint64_t aSize,
276 MediumVariant_T aVariant)
277 : Medium::Task(aMedium, aProgress),
278 mSize(aSize),
279 mVariant(aVariant)
280 {}
281
282 uint64_t mSize;
283 MediumVariant_T mVariant;
284
285private:
286 virtual HRESULT handler();
287};
288
289class Medium::CreateDiffTask : public Medium::Task
290{
291public:
292 CreateDiffTask(Medium *aMedium,
293 Progress *aProgress,
294 Medium *aTarget,
295 MediumVariant_T aVariant,
296 MediumLockList *aMediumLockList,
297 bool fKeepMediumLockList = false)
298 : Medium::Task(aMedium, aProgress),
299 mpMediumLockList(aMediumLockList),
300 mTarget(aTarget),
301 mVariant(aVariant),
302 mTargetCaller(aTarget),
303 mfKeepMediumLockList(fKeepMediumLockList)
304 {
305 AssertReturnVoidStmt(aTarget != NULL, mRC = E_FAIL);
306 mRC = mTargetCaller.rc();
307 if (FAILED(mRC))
308 return;
309 }
310
311 ~CreateDiffTask()
312 {
313 if (!mfKeepMediumLockList && mpMediumLockList)
314 delete mpMediumLockList;
315 }
316
317 MediumLockList *mpMediumLockList;
318
319 const ComObjPtr<Medium> mTarget;
320 MediumVariant_T mVariant;
321
322private:
323 virtual HRESULT handler();
324
325 AutoCaller mTargetCaller;
326 bool mfKeepMediumLockList;
327};
328
329class Medium::CloneTask : public Medium::Task
330{
331public:
332 CloneTask(Medium *aMedium,
333 Progress *aProgress,
334 Medium *aTarget,
335 MediumVariant_T aVariant,
336 Medium *aParent,
337 uint32_t idxSrcImageSame,
338 uint32_t idxDstImageSame,
339 MediumLockList *aSourceMediumLockList,
340 MediumLockList *aTargetMediumLockList,
341 bool fKeepSourceMediumLockList = false,
342 bool fKeepTargetMediumLockList = false)
343 : Medium::Task(aMedium, aProgress),
344 mTarget(aTarget),
345 mParent(aParent),
346 mpSourceMediumLockList(aSourceMediumLockList),
347 mpTargetMediumLockList(aTargetMediumLockList),
348 mVariant(aVariant),
349 midxSrcImageSame(idxSrcImageSame),
350 midxDstImageSame(idxDstImageSame),
351 mTargetCaller(aTarget),
352 mParentCaller(aParent),
353 mfKeepSourceMediumLockList(fKeepSourceMediumLockList),
354 mfKeepTargetMediumLockList(fKeepTargetMediumLockList)
355 {
356 AssertReturnVoidStmt(aTarget != NULL, mRC = E_FAIL);
357 mRC = mTargetCaller.rc();
358 if (FAILED(mRC))
359 return;
360 /* aParent may be NULL */
361 mRC = mParentCaller.rc();
362 if (FAILED(mRC))
363 return;
364 AssertReturnVoidStmt(aSourceMediumLockList != NULL, mRC = E_FAIL);
365 AssertReturnVoidStmt(aTargetMediumLockList != NULL, mRC = E_FAIL);
366 }
367
368 ~CloneTask()
369 {
370 if (!mfKeepSourceMediumLockList && mpSourceMediumLockList)
371 delete mpSourceMediumLockList;
372 if (!mfKeepTargetMediumLockList && mpTargetMediumLockList)
373 delete mpTargetMediumLockList;
374 }
375
376 const ComObjPtr<Medium> mTarget;
377 const ComObjPtr<Medium> mParent;
378 MediumLockList *mpSourceMediumLockList;
379 MediumLockList *mpTargetMediumLockList;
380 MediumVariant_T mVariant;
381 uint32_t midxSrcImageSame;
382 uint32_t midxDstImageSame;
383
384private:
385 virtual HRESULT handler();
386
387 AutoCaller mTargetCaller;
388 AutoCaller mParentCaller;
389 bool mfKeepSourceMediumLockList;
390 bool mfKeepTargetMediumLockList;
391};
392
393class Medium::CompactTask : public Medium::Task
394{
395public:
396 CompactTask(Medium *aMedium,
397 Progress *aProgress,
398 MediumLockList *aMediumLockList,
399 bool fKeepMediumLockList = false)
400 : Medium::Task(aMedium, aProgress),
401 mpMediumLockList(aMediumLockList),
402 mfKeepMediumLockList(fKeepMediumLockList)
403 {
404 AssertReturnVoidStmt(aMediumLockList != NULL, mRC = E_FAIL);
405 }
406
407 ~CompactTask()
408 {
409 if (!mfKeepMediumLockList && mpMediumLockList)
410 delete mpMediumLockList;
411 }
412
413 MediumLockList *mpMediumLockList;
414
415private:
416 virtual HRESULT handler();
417
418 bool mfKeepMediumLockList;
419};
420
421class Medium::ResizeTask : public Medium::Task
422{
423public:
424 ResizeTask(Medium *aMedium,
425 uint64_t aSize,
426 Progress *aProgress,
427 MediumLockList *aMediumLockList,
428 bool fKeepMediumLockList = false)
429 : Medium::Task(aMedium, aProgress),
430 mSize(aSize),
431 mpMediumLockList(aMediumLockList),
432 mfKeepMediumLockList(fKeepMediumLockList)
433 {
434 AssertReturnVoidStmt(aMediumLockList != NULL, mRC = E_FAIL);
435 }
436
437 ~ResizeTask()
438 {
439 if (!mfKeepMediumLockList && mpMediumLockList)
440 delete mpMediumLockList;
441 }
442
443 uint64_t mSize;
444 MediumLockList *mpMediumLockList;
445
446private:
447 virtual HRESULT handler();
448
449 bool mfKeepMediumLockList;
450};
451
452class Medium::ResetTask : public Medium::Task
453{
454public:
455 ResetTask(Medium *aMedium,
456 Progress *aProgress,
457 MediumLockList *aMediumLockList,
458 bool fKeepMediumLockList = false)
459 : Medium::Task(aMedium, aProgress),
460 mpMediumLockList(aMediumLockList),
461 mfKeepMediumLockList(fKeepMediumLockList)
462 {}
463
464 ~ResetTask()
465 {
466 if (!mfKeepMediumLockList && mpMediumLockList)
467 delete mpMediumLockList;
468 }
469
470 MediumLockList *mpMediumLockList;
471
472private:
473 virtual HRESULT handler();
474
475 bool mfKeepMediumLockList;
476};
477
478class Medium::DeleteTask : public Medium::Task
479{
480public:
481 DeleteTask(Medium *aMedium,
482 Progress *aProgress,
483 MediumLockList *aMediumLockList,
484 bool fKeepMediumLockList = false)
485 : Medium::Task(aMedium, aProgress),
486 mpMediumLockList(aMediumLockList),
487 mfKeepMediumLockList(fKeepMediumLockList)
488 {}
489
490 ~DeleteTask()
491 {
492 if (!mfKeepMediumLockList && mpMediumLockList)
493 delete mpMediumLockList;
494 }
495
496 MediumLockList *mpMediumLockList;
497
498private:
499 virtual HRESULT handler();
500
501 bool mfKeepMediumLockList;
502};
503
504class Medium::MergeTask : public Medium::Task
505{
506public:
507 MergeTask(Medium *aMedium,
508 Medium *aTarget,
509 bool fMergeForward,
510 Medium *aParentForTarget,
511 const MediaList &aChildrenToReparent,
512 Progress *aProgress,
513 MediumLockList *aMediumLockList,
514 bool fKeepMediumLockList = false)
515 : Medium::Task(aMedium, aProgress),
516 mTarget(aTarget),
517 mfMergeForward(fMergeForward),
518 mParentForTarget(aParentForTarget),
519 mChildrenToReparent(aChildrenToReparent),
520 mpMediumLockList(aMediumLockList),
521 mTargetCaller(aTarget),
522 mParentForTargetCaller(aParentForTarget),
523 mfChildrenCaller(false),
524 mfKeepMediumLockList(fKeepMediumLockList)
525 {
526 AssertReturnVoidStmt(aMediumLockList != NULL, mRC = E_FAIL);
527 for (MediaList::const_iterator it = mChildrenToReparent.begin();
528 it != mChildrenToReparent.end();
529 ++it)
530 {
531 HRESULT rc2 = (*it)->addCaller();
532 if (FAILED(rc2))
533 {
534 mRC = E_FAIL;
535 for (MediaList::const_iterator it2 = mChildrenToReparent.begin();
536 it2 != it;
537 --it2)
538 {
539 (*it2)->releaseCaller();
540 }
541 return;
542 }
543 }
544 mfChildrenCaller = true;
545 }
546
547 ~MergeTask()
548 {
549 if (!mfKeepMediumLockList && mpMediumLockList)
550 delete mpMediumLockList;
551 if (mfChildrenCaller)
552 {
553 for (MediaList::const_iterator it = mChildrenToReparent.begin();
554 it != mChildrenToReparent.end();
555 ++it)
556 {
557 (*it)->releaseCaller();
558 }
559 }
560 }
561
562 const ComObjPtr<Medium> mTarget;
563 bool mfMergeForward;
564 /* When mChildrenToReparent is empty then mParentForTarget is non-null.
565 * In other words: they are used in different cases. */
566 const ComObjPtr<Medium> mParentForTarget;
567 MediaList mChildrenToReparent;
568 MediumLockList *mpMediumLockList;
569
570private:
571 virtual HRESULT handler();
572
573 AutoCaller mTargetCaller;
574 AutoCaller mParentForTargetCaller;
575 bool mfChildrenCaller;
576 bool mfKeepMediumLockList;
577};
578
579class Medium::ExportTask : public Medium::Task
580{
581public:
582 ExportTask(Medium *aMedium,
583 Progress *aProgress,
584 const char *aFilename,
585 MediumFormat *aFormat,
586 MediumVariant_T aVariant,
587 VDINTERFACEIO *aVDImageIOIf,
588 void *aVDImageIOUser,
589 MediumLockList *aSourceMediumLockList,
590 bool fKeepSourceMediumLockList = false)
591 : Medium::Task(aMedium, aProgress),
592 mpSourceMediumLockList(aSourceMediumLockList),
593 mFilename(aFilename),
594 mFormat(aFormat),
595 mVariant(aVariant),
596 mfKeepSourceMediumLockList(fKeepSourceMediumLockList)
597 {
598 AssertReturnVoidStmt(aSourceMediumLockList != NULL, mRC = E_FAIL);
599
600 mVDImageIfaces = aMedium->m->vdImageIfaces;
601 if (aVDImageIOIf)
602 {
603 int vrc = VDInterfaceAdd(&aVDImageIOIf->Core, "Medium::vdInterfaceIO",
604 VDINTERFACETYPE_IO, aVDImageIOUser,
605 sizeof(VDINTERFACEIO), &mVDImageIfaces);
606 AssertRCReturnVoidStmt(vrc, mRC = E_FAIL);
607 }
608 }
609
610 ~ExportTask()
611 {
612 if (!mfKeepSourceMediumLockList && mpSourceMediumLockList)
613 delete mpSourceMediumLockList;
614 }
615
616 MediumLockList *mpSourceMediumLockList;
617 Utf8Str mFilename;
618 ComObjPtr<MediumFormat> mFormat;
619 MediumVariant_T mVariant;
620 PVDINTERFACE mVDImageIfaces;
621
622private:
623 virtual HRESULT handler();
624
625 bool mfKeepSourceMediumLockList;
626};
627
628class Medium::ImportTask : public Medium::Task
629{
630public:
631 ImportTask(Medium *aMedium,
632 Progress *aProgress,
633 const char *aFilename,
634 MediumFormat *aFormat,
635 MediumVariant_T aVariant,
636 VDINTERFACEIO *aVDImageIOIf,
637 void *aVDImageIOUser,
638 Medium *aParent,
639 MediumLockList *aTargetMediumLockList,
640 bool fKeepTargetMediumLockList = false)
641 : Medium::Task(aMedium, aProgress),
642 mFilename(aFilename),
643 mFormat(aFormat),
644 mVariant(aVariant),
645 mParent(aParent),
646 mpTargetMediumLockList(aTargetMediumLockList),
647 mParentCaller(aParent),
648 mfKeepTargetMediumLockList(fKeepTargetMediumLockList)
649 {
650 AssertReturnVoidStmt(aTargetMediumLockList != NULL, mRC = E_FAIL);
651 /* aParent may be NULL */
652 mRC = mParentCaller.rc();
653 if (FAILED(mRC))
654 return;
655
656 mVDImageIfaces = aMedium->m->vdImageIfaces;
657 if (aVDImageIOIf)
658 {
659 int vrc = VDInterfaceAdd(&aVDImageIOIf->Core, "Medium::vdInterfaceIO",
660 VDINTERFACETYPE_IO, aVDImageIOUser,
661 sizeof(VDINTERFACEIO), &mVDImageIfaces);
662 AssertRCReturnVoidStmt(vrc, mRC = E_FAIL);
663 }
664 }
665
666 ~ImportTask()
667 {
668 if (!mfKeepTargetMediumLockList && mpTargetMediumLockList)
669 delete mpTargetMediumLockList;
670 }
671
672 Utf8Str mFilename;
673 ComObjPtr<MediumFormat> mFormat;
674 MediumVariant_T mVariant;
675 const ComObjPtr<Medium> mParent;
676 MediumLockList *mpTargetMediumLockList;
677 PVDINTERFACE mVDImageIfaces;
678
679private:
680 virtual HRESULT handler();
681
682 AutoCaller mParentCaller;
683 bool mfKeepTargetMediumLockList;
684};
685
686/**
687 * Thread function for time-consuming medium tasks.
688 *
689 * @param pvUser Pointer to the Medium::Task instance.
690 */
691/* static */
692DECLCALLBACK(int) Medium::Task::fntMediumTask(RTTHREAD aThread, void *pvUser)
693{
694 LogFlowFuncEnter();
695 AssertReturn(pvUser, (int)E_INVALIDARG);
696 Medium::Task *pTask = static_cast<Medium::Task *>(pvUser);
697
698 pTask->mThread = aThread;
699
700 HRESULT rc = pTask->handler();
701
702 /* complete the progress if run asynchronously */
703 if (pTask->isAsync())
704 {
705 if (!pTask->mProgress.isNull())
706 pTask->mProgress->notifyComplete(rc);
707 }
708
709 /* pTask is no longer needed, delete it. */
710 delete pTask;
711
712 LogFlowFunc(("rc=%Rhrc\n", rc));
713 LogFlowFuncLeave();
714
715 return (int)rc;
716}
717
718/**
719 * PFNVDPROGRESS callback handler for Task operations.
720 *
721 * @param pvUser Pointer to the Progress instance.
722 * @param uPercent Completion percentage (0-100).
723 */
724/*static*/
725DECLCALLBACK(int) Medium::Task::vdProgressCall(void *pvUser, unsigned uPercent)
726{
727 Progress *that = static_cast<Progress *>(pvUser);
728
729 if (that != NULL)
730 {
731 /* update the progress object, capping it at 99% as the final percent
732 * is used for additional operations like setting the UUIDs and similar. */
733 HRESULT rc = that->SetCurrentOperationProgress(uPercent * 99 / 100);
734 if (FAILED(rc))
735 {
736 if (rc == E_FAIL)
737 return VERR_CANCELLED;
738 else
739 return VERR_INVALID_STATE;
740 }
741 }
742
743 return VINF_SUCCESS;
744}
745
746/**
747 * Implementation code for the "create base" task.
748 */
749HRESULT Medium::CreateBaseTask::handler()
750{
751 return mMedium->taskCreateBaseHandler(*this);
752}
753
754/**
755 * Implementation code for the "create diff" task.
756 */
757HRESULT Medium::CreateDiffTask::handler()
758{
759 return mMedium->taskCreateDiffHandler(*this);
760}
761
762/**
763 * Implementation code for the "clone" task.
764 */
765HRESULT Medium::CloneTask::handler()
766{
767 return mMedium->taskCloneHandler(*this);
768}
769
770/**
771 * Implementation code for the "compact" task.
772 */
773HRESULT Medium::CompactTask::handler()
774{
775 return mMedium->taskCompactHandler(*this);
776}
777
778/**
779 * Implementation code for the "resize" task.
780 */
781HRESULT Medium::ResizeTask::handler()
782{
783 return mMedium->taskResizeHandler(*this);
784}
785
786
787/**
788 * Implementation code for the "reset" task.
789 */
790HRESULT Medium::ResetTask::handler()
791{
792 return mMedium->taskResetHandler(*this);
793}
794
795/**
796 * Implementation code for the "delete" task.
797 */
798HRESULT Medium::DeleteTask::handler()
799{
800 return mMedium->taskDeleteHandler(*this);
801}
802
803/**
804 * Implementation code for the "merge" task.
805 */
806HRESULT Medium::MergeTask::handler()
807{
808 return mMedium->taskMergeHandler(*this);
809}
810
811/**
812 * Implementation code for the "export" task.
813 */
814HRESULT Medium::ExportTask::handler()
815{
816 return mMedium->taskExportHandler(*this);
817}
818
819/**
820 * Implementation code for the "import" task.
821 */
822HRESULT Medium::ImportTask::handler()
823{
824 return mMedium->taskImportHandler(*this);
825}
826
827////////////////////////////////////////////////////////////////////////////////
828//
829// Medium constructor / destructor
830//
831////////////////////////////////////////////////////////////////////////////////
832
833DEFINE_EMPTY_CTOR_DTOR(Medium)
834
835HRESULT Medium::FinalConstruct()
836{
837 m = new Data;
838
839 /* Initialize the callbacks of the VD error interface */
840 m->vdIfError.pfnError = vdErrorCall;
841 m->vdIfError.pfnMessage = NULL;
842
843 /* Initialize the callbacks of the VD config interface */
844 m->vdIfConfig.pfnAreKeysValid = vdConfigAreKeysValid;
845 m->vdIfConfig.pfnQuerySize = vdConfigQuerySize;
846 m->vdIfConfig.pfnQuery = vdConfigQuery;
847
848 /* Initialize the callbacks of the VD TCP interface (we always use the host
849 * IP stack for now) */
850 m->vdIfTcpNet.pfnSocketCreate = vdTcpSocketCreate;
851 m->vdIfTcpNet.pfnSocketDestroy = vdTcpSocketDestroy;
852 m->vdIfTcpNet.pfnClientConnect = vdTcpClientConnect;
853 m->vdIfTcpNet.pfnClientClose = vdTcpClientClose;
854 m->vdIfTcpNet.pfnIsClientConnected = vdTcpIsClientConnected;
855 m->vdIfTcpNet.pfnSelectOne = vdTcpSelectOne;
856 m->vdIfTcpNet.pfnRead = vdTcpRead;
857 m->vdIfTcpNet.pfnWrite = vdTcpWrite;
858 m->vdIfTcpNet.pfnSgWrite = vdTcpSgWrite;
859 m->vdIfTcpNet.pfnFlush = vdTcpFlush;
860 m->vdIfTcpNet.pfnSetSendCoalescing = vdTcpSetSendCoalescing;
861 m->vdIfTcpNet.pfnGetLocalAddress = vdTcpGetLocalAddress;
862 m->vdIfTcpNet.pfnGetPeerAddress = vdTcpGetPeerAddress;
863 m->vdIfTcpNet.pfnSelectOneEx = NULL;
864 m->vdIfTcpNet.pfnPoke = NULL;
865
866 /* Initialize the per-disk interface chain (could be done more globally,
867 * but it's not wasting much time or space so it's not worth it). */
868 int vrc;
869 vrc = VDInterfaceAdd(&m->vdIfError.Core,
870 "Medium::vdInterfaceError",
871 VDINTERFACETYPE_ERROR, this,
872 sizeof(VDINTERFACEERROR), &m->vdDiskIfaces);
873 AssertRCReturn(vrc, E_FAIL);
874
875 /* Initialize the per-image interface chain */
876 vrc = VDInterfaceAdd(&m->vdIfConfig.Core,
877 "Medium::vdInterfaceConfig",
878 VDINTERFACETYPE_CONFIG, this,
879 sizeof(VDINTERFACECONFIG), &m->vdImageIfaces);
880 AssertRCReturn(vrc, E_FAIL);
881
882 vrc = VDInterfaceAdd(&m->vdIfTcpNet.Core,
883 "Medium::vdInterfaceTcpNet",
884 VDINTERFACETYPE_TCPNET, this,
885 sizeof(VDINTERFACETCPNET), &m->vdImageIfaces);
886 AssertRCReturn(vrc, E_FAIL);
887
888 vrc = RTSemEventMultiCreate(&m->queryInfoSem);
889 AssertRCReturn(vrc, E_FAIL);
890 vrc = RTSemEventMultiSignal(m->queryInfoSem);
891 AssertRCReturn(vrc, E_FAIL);
892
893 return BaseFinalConstruct();
894}
895
896void Medium::FinalRelease()
897{
898 uninit();
899
900 delete m;
901
902 BaseFinalRelease();
903}
904
905/**
906 * Initializes an empty hard disk object without creating or opening an associated
907 * storage unit.
908 *
909 * This gets called by VirtualBox::CreateHardDisk() in which case uuidMachineRegistry
910 * is empty since starting with VirtualBox 4.0, we no longer add opened media to a
911 * registry automatically (this is deferred until the medium is attached to a machine).
912 *
913 * This also gets called when VirtualBox creates diff images; in this case uuidMachineRegistry
914 * is set to the registry of the parent image to make sure they all end up in the same
915 * file.
916 *
917 * For hard disks that don't have the MediumFormatCapabilities_CreateFixed or
918 * MediumFormatCapabilities_CreateDynamic capability (and therefore cannot be created or deleted
919 * with the means of VirtualBox) the associated storage unit is assumed to be
920 * ready for use so the state of the hard disk object will be set to Created.
921 *
922 * @param aVirtualBox VirtualBox object.
923 * @param aFormat
924 * @param aLocation Storage unit location.
925 * @param uuidMachineRegistry The registry to which this medium should be added (global registry UUID or machine UUID or empty if none).
926 * @param pllRegistriesThatNeedSaving Optional list to receive the UUIDs of the media registries that need saving.
927 */
928HRESULT Medium::init(VirtualBox *aVirtualBox,
929 const Utf8Str &aFormat,
930 const Utf8Str &aLocation,
931 const Guid &uuidMachineRegistry,
932 GuidList *pllRegistriesThatNeedSaving)
933{
934 AssertReturn(aVirtualBox != NULL, E_FAIL);
935 AssertReturn(!aFormat.isEmpty(), E_FAIL);
936
937 /* Enclose the state transition NotReady->InInit->Ready */
938 AutoInitSpan autoInitSpan(this);
939 AssertReturn(autoInitSpan.isOk(), E_FAIL);
940
941 HRESULT rc = S_OK;
942
943 unconst(m->pVirtualBox) = aVirtualBox;
944
945 if (!uuidMachineRegistry.isEmpty())
946 m->llRegistryIDs.push_back(uuidMachineRegistry);
947
948 /* no storage yet */
949 m->state = MediumState_NotCreated;
950
951 /* cannot be a host drive */
952 m->hostDrive = false;
953
954 /* No storage unit is created yet, no need to queryInfo() */
955
956 rc = setFormat(aFormat);
957 if (FAILED(rc)) return rc;
958
959 rc = setLocation(aLocation);
960 if (FAILED(rc)) return rc;
961
962 if (!(m->formatObj->getCapabilities() & ( MediumFormatCapabilities_CreateFixed
963 | MediumFormatCapabilities_CreateDynamic))
964 )
965 {
966 /* Storage for hard disks of this format can neither be explicitly
967 * created by VirtualBox nor deleted, so we place the hard disk to
968 * Inaccessible state here and also add it to the registry. The
969 * state means that one has to use RefreshState() to update the
970 * medium format specific fields. */
971 m->state = MediumState_Inaccessible;
972 // create new UUID
973 unconst(m->id).create();
974
975 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
976 rc = m->pVirtualBox->registerHardDisk(this, pllRegistriesThatNeedSaving);
977 }
978
979 /* Confirm a successful initialization when it's the case */
980 if (SUCCEEDED(rc))
981 autoInitSpan.setSucceeded();
982
983 return rc;
984}
985
986/**
987 * Initializes the medium object by opening the storage unit at the specified
988 * location. The enOpenMode parameter defines whether the medium will be opened
989 * read/write or read-only.
990 *
991 * This gets called by VirtualBox::OpenMedium() and also by
992 * Machine::AttachDevice() and createImplicitDiffs() when new diff
993 * images are created.
994 *
995 * There is no registry for this case since starting with VirtualBox 4.0, we
996 * no longer add opened media to a registry automatically (this is deferred
997 * until the medium is attached to a machine).
998 *
999 * For hard disks, the UUID, format and the parent of this medium will be
1000 * determined when reading the medium storage unit. For DVD and floppy images,
1001 * which have no UUIDs in their storage units, new UUIDs are created.
1002 * If the detected or set parent is not known to VirtualBox, then this method
1003 * will fail.
1004 *
1005 * @param aVirtualBox VirtualBox object.
1006 * @param aLocation Storage unit location.
1007 * @param enOpenMode Whether to open the medium read/write or read-only.
1008 * @param fForceNewUuid Whether a new UUID should be set to avoid duplicates.
1009 * @param aDeviceType Device type of medium.
1010 */
1011HRESULT Medium::init(VirtualBox *aVirtualBox,
1012 const Utf8Str &aLocation,
1013 HDDOpenMode enOpenMode,
1014 bool fForceNewUuid,
1015 DeviceType_T aDeviceType)
1016{
1017 AssertReturn(aVirtualBox, E_INVALIDARG);
1018 AssertReturn(!aLocation.isEmpty(), E_INVALIDARG);
1019
1020 /* Enclose the state transition NotReady->InInit->Ready */
1021 AutoInitSpan autoInitSpan(this);
1022 AssertReturn(autoInitSpan.isOk(), E_FAIL);
1023
1024 HRESULT rc = S_OK;
1025
1026 unconst(m->pVirtualBox) = aVirtualBox;
1027
1028 /* there must be a storage unit */
1029 m->state = MediumState_Created;
1030
1031 /* remember device type for correct unregistering later */
1032 m->devType = aDeviceType;
1033
1034 /* cannot be a host drive */
1035 m->hostDrive = false;
1036
1037 /* remember the open mode (defaults to ReadWrite) */
1038 m->hddOpenMode = enOpenMode;
1039
1040 if (aDeviceType == DeviceType_DVD)
1041 m->type = MediumType_Readonly;
1042 else if (aDeviceType == DeviceType_Floppy)
1043 m->type = MediumType_Writethrough;
1044
1045 rc = setLocation(aLocation);
1046 if (FAILED(rc)) return rc;
1047
1048 /* get all the information about the medium from the storage unit */
1049 if (fForceNewUuid)
1050 unconst(m->uuidImage).create();
1051 rc = queryInfo(fForceNewUuid /* fSetImageId */, false /* fSetParentId */);
1052
1053 if (SUCCEEDED(rc))
1054 {
1055 /* if the storage unit is not accessible, it's not acceptable for the
1056 * newly opened media so convert this into an error */
1057 if (m->state == MediumState_Inaccessible)
1058 {
1059 Assert(!m->strLastAccessError.isEmpty());
1060 rc = setError(E_FAIL, "%s", m->strLastAccessError.c_str());
1061 }
1062 else
1063 {
1064 AssertReturn(!m->id.isEmpty(), E_FAIL);
1065
1066 /* storage format must be detected by queryInfo() if the medium is accessible */
1067 AssertReturn(!m->strFormat.isEmpty(), E_FAIL);
1068 }
1069 }
1070
1071 /* Confirm a successful initialization when it's the case */
1072 if (SUCCEEDED(rc))
1073 autoInitSpan.setSucceeded();
1074
1075 return rc;
1076}
1077
1078/**
1079 * Initializes the medium object by loading its data from the given settings
1080 * node. In this mode, the medium will always be opened read/write.
1081 *
1082 * In this case, since we're loading from a registry, uuidMachineRegistry is
1083 * always set: it's either the global registry UUID or a machine UUID when
1084 * loading from a per-machine registry.
1085 *
1086 * @param aVirtualBox VirtualBox object.
1087 * @param aParent Parent medium disk or NULL for a root (base) medium.
1088 * @param aDeviceType Device type of the medium.
1089 * @param uuidMachineRegistry The registry to which this medium should be added (global registry UUID or machine UUID).
1090 * @param aNode Configuration settings.
1091 * @param strMachineFolder The machine folder with which to resolve relative paths; if empty, then we use the VirtualBox home directory
1092 *
1093 * @note Locks the medium tree for writing.
1094 */
1095HRESULT Medium::init(VirtualBox *aVirtualBox,
1096 Medium *aParent,
1097 DeviceType_T aDeviceType,
1098 const Guid &uuidMachineRegistry,
1099 const settings::Medium &data,
1100 const Utf8Str &strMachineFolder)
1101{
1102 using namespace settings;
1103
1104 AssertReturn(aVirtualBox, E_INVALIDARG);
1105
1106 /* Enclose the state transition NotReady->InInit->Ready */
1107 AutoInitSpan autoInitSpan(this);
1108 AssertReturn(autoInitSpan.isOk(), E_FAIL);
1109
1110 HRESULT rc = S_OK;
1111
1112 unconst(m->pVirtualBox) = aVirtualBox;
1113
1114 if (!uuidMachineRegistry.isEmpty())
1115 m->llRegistryIDs.push_back(uuidMachineRegistry);
1116
1117 /* register with VirtualBox/parent early, since uninit() will
1118 * unconditionally unregister on failure */
1119 if (aParent)
1120 {
1121 // differencing medium: add to parent
1122 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
1123 m->pParent = aParent;
1124 aParent->m->llChildren.push_back(this);
1125 }
1126
1127 /* see below why we don't call queryInfo() (and therefore treat the medium
1128 * as inaccessible for now */
1129 m->state = MediumState_Inaccessible;
1130 m->strLastAccessError = tr("Accessibility check was not yet performed");
1131
1132 /* required */
1133 unconst(m->id) = data.uuid;
1134
1135 /* assume not a host drive */
1136 m->hostDrive = false;
1137
1138 /* optional */
1139 m->strDescription = data.strDescription;
1140
1141 /* required */
1142 if (aDeviceType == DeviceType_HardDisk)
1143 {
1144 AssertReturn(!data.strFormat.isEmpty(), E_FAIL);
1145 rc = setFormat(data.strFormat);
1146 if (FAILED(rc)) return rc;
1147 }
1148 else
1149 {
1150 /// @todo handle host drive settings here as well?
1151 if (!data.strFormat.isEmpty())
1152 rc = setFormat(data.strFormat);
1153 else
1154 rc = setFormat("RAW");
1155 if (FAILED(rc)) return rc;
1156 }
1157
1158 /* optional, only for diffs, default is false; we can only auto-reset
1159 * diff media so they must have a parent */
1160 if (aParent != NULL)
1161 m->autoReset = data.fAutoReset;
1162 else
1163 m->autoReset = false;
1164
1165 /* properties (after setting the format as it populates the map). Note that
1166 * if some properties are not supported but present in the settings file,
1167 * they will still be read and accessible (for possible backward
1168 * compatibility; we can also clean them up from the XML upon next
1169 * XML format version change if we wish) */
1170 for (settings::StringsMap::const_iterator it = data.properties.begin();
1171 it != data.properties.end();
1172 ++it)
1173 {
1174 const Utf8Str &name = it->first;
1175 const Utf8Str &value = it->second;
1176 m->mapProperties[name] = value;
1177 }
1178
1179 Utf8Str strFull;
1180 if (m->formatObj->getCapabilities() & MediumFormatCapabilities_File)
1181 {
1182 // compose full path of the medium, if it's not fully qualified...
1183 // slightly convoluted logic here. If the caller has given us a
1184 // machine folder, then a relative path will be relative to that:
1185 if ( !strMachineFolder.isEmpty()
1186 && !RTPathStartsWithRoot(data.strLocation.c_str())
1187 )
1188 {
1189 strFull = strMachineFolder;
1190 strFull += RTPATH_SLASH;
1191 strFull += data.strLocation;
1192 }
1193 else
1194 {
1195 // Otherwise use the old VirtualBox "make absolute path" logic:
1196 rc = m->pVirtualBox->calculateFullPath(data.strLocation, strFull);
1197 if (FAILED(rc)) return rc;
1198 }
1199 }
1200 else
1201 strFull = data.strLocation;
1202
1203 rc = setLocation(strFull);
1204 if (FAILED(rc)) return rc;
1205
1206 if (aDeviceType == DeviceType_HardDisk)
1207 {
1208 /* type is only for base hard disks */
1209 if (m->pParent.isNull())
1210 m->type = data.hdType;
1211 }
1212 else if (aDeviceType == DeviceType_DVD)
1213 m->type = MediumType_Readonly;
1214 else
1215 m->type = MediumType_Writethrough;
1216
1217 /* remember device type for correct unregistering later */
1218 m->devType = aDeviceType;
1219
1220 LogFlowThisFunc(("m->strLocationFull='%s', m->strFormat=%s, m->id={%RTuuid}\n",
1221 m->strLocationFull.c_str(), m->strFormat.c_str(), m->id.raw()));
1222
1223 /* Don't call queryInfo() for registered media to prevent the calling
1224 * thread (i.e. the VirtualBox server startup thread) from an unexpected
1225 * freeze but mark it as initially inaccessible instead. The vital UUID,
1226 * location and format properties are read from the registry file above; to
1227 * get the actual state and the rest of the data, the user will have to call
1228 * COMGETTER(State). */
1229
1230 AutoWriteLock treeLock(aVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
1231
1232 /* load all children */
1233 for (settings::MediaList::const_iterator it = data.llChildren.begin();
1234 it != data.llChildren.end();
1235 ++it)
1236 {
1237 const settings::Medium &med = *it;
1238
1239 ComObjPtr<Medium> pHD;
1240 pHD.createObject();
1241 rc = pHD->init(aVirtualBox,
1242 this, // parent
1243 aDeviceType,
1244 uuidMachineRegistry,
1245 med, // child data
1246 strMachineFolder);
1247 if (FAILED(rc)) break;
1248
1249 rc = m->pVirtualBox->registerHardDisk(pHD, NULL /* pllRegistriesThatNeedSaving */ );
1250 if (FAILED(rc)) break;
1251 }
1252
1253 /* Confirm a successful initialization when it's the case */
1254 if (SUCCEEDED(rc))
1255 autoInitSpan.setSucceeded();
1256
1257 return rc;
1258}
1259
1260/**
1261 * Initializes the medium object by providing the host drive information.
1262 * Not used for anything but the host floppy/host DVD case.
1263 *
1264 * There is no registry for this case.
1265 *
1266 * @param aVirtualBox VirtualBox object.
1267 * @param aDeviceType Device type of the medium.
1268 * @param aLocation Location of the host drive.
1269 * @param aDescription Comment for this host drive.
1270 *
1271 * @note Locks VirtualBox lock for writing.
1272 */
1273HRESULT Medium::init(VirtualBox *aVirtualBox,
1274 DeviceType_T aDeviceType,
1275 const Utf8Str &aLocation,
1276 const Utf8Str &aDescription /* = Utf8Str::Empty */)
1277{
1278 ComAssertRet(aDeviceType == DeviceType_DVD || aDeviceType == DeviceType_Floppy, E_INVALIDARG);
1279 ComAssertRet(!aLocation.isEmpty(), E_INVALIDARG);
1280
1281 /* Enclose the state transition NotReady->InInit->Ready */
1282 AutoInitSpan autoInitSpan(this);
1283 AssertReturn(autoInitSpan.isOk(), E_FAIL);
1284
1285 unconst(m->pVirtualBox) = aVirtualBox;
1286
1287 // We do not store host drives in VirtualBox.xml or anywhere else, so if we want
1288 // host drives to be identifiable by UUID and not give the drive a different UUID
1289 // every time VirtualBox starts, we need to fake a reproducible UUID here:
1290 RTUUID uuid;
1291 RTUuidClear(&uuid);
1292 if (aDeviceType == DeviceType_DVD)
1293 memcpy(&uuid.au8[0], "DVD", 3);
1294 else
1295 memcpy(&uuid.au8[0], "FD", 2);
1296 /* use device name, adjusted to the end of uuid, shortened if necessary */
1297 size_t lenLocation = aLocation.length();
1298 if (lenLocation > 12)
1299 memcpy(&uuid.au8[4], aLocation.c_str() + (lenLocation - 12), 12);
1300 else
1301 memcpy(&uuid.au8[4 + 12 - lenLocation], aLocation.c_str(), lenLocation);
1302 unconst(m->id) = uuid;
1303
1304 if (aDeviceType == DeviceType_DVD)
1305 m->type = MediumType_Readonly;
1306 else
1307 m->type = MediumType_Writethrough;
1308 m->devType = aDeviceType;
1309 m->state = MediumState_Created;
1310 m->hostDrive = true;
1311 HRESULT rc = setFormat("RAW");
1312 if (FAILED(rc)) return rc;
1313 rc = setLocation(aLocation);
1314 if (FAILED(rc)) return rc;
1315 m->strDescription = aDescription;
1316
1317 autoInitSpan.setSucceeded();
1318 return S_OK;
1319}
1320
1321/**
1322 * Uninitializes the instance.
1323 *
1324 * Called either from FinalRelease() or by the parent when it gets destroyed.
1325 *
1326 * @note All children of this medium get uninitialized by calling their
1327 * uninit() methods.
1328 *
1329 * @note Caller must hold the tree lock of the medium tree this medium is on.
1330 */
1331void Medium::uninit()
1332{
1333 /* Enclose the state transition Ready->InUninit->NotReady */
1334 AutoUninitSpan autoUninitSpan(this);
1335 if (autoUninitSpan.uninitDone())
1336 return;
1337
1338 if (!m->formatObj.isNull())
1339 {
1340 /* remove the caller reference we added in setFormat() */
1341 m->formatObj->releaseCaller();
1342 m->formatObj.setNull();
1343 }
1344
1345 if (m->state == MediumState_Deleting)
1346 {
1347 /* This medium has been already deleted (directly or as part of a
1348 * merge). Reparenting has already been done. */
1349 Assert(m->pParent.isNull());
1350 }
1351 else
1352 {
1353 MediaList::iterator it;
1354 for (it = m->llChildren.begin();
1355 it != m->llChildren.end();
1356 ++it)
1357 {
1358 Medium *pChild = *it;
1359 pChild->m->pParent.setNull();
1360 pChild->uninit();
1361 }
1362 m->llChildren.clear(); // this unsets all the ComPtrs and probably calls delete
1363
1364 if (m->pParent)
1365 {
1366 // this is a differencing disk: then remove it from the parent's children list
1367 deparent();
1368 }
1369 }
1370
1371 RTSemEventMultiSignal(m->queryInfoSem);
1372 RTSemEventMultiDestroy(m->queryInfoSem);
1373 m->queryInfoSem = NIL_RTSEMEVENTMULTI;
1374
1375 unconst(m->pVirtualBox) = NULL;
1376}
1377
1378/**
1379 * Internal helper that removes "this" from the list of children of its
1380 * parent. Used in uninit() and other places when reparenting is necessary.
1381 *
1382 * The caller must hold the medium tree lock!
1383 */
1384void Medium::deparent()
1385{
1386 MediaList &llParent = m->pParent->m->llChildren;
1387 for (MediaList::iterator it = llParent.begin();
1388 it != llParent.end();
1389 ++it)
1390 {
1391 Medium *pParentsChild = *it;
1392 if (this == pParentsChild)
1393 {
1394 llParent.erase(it);
1395 break;
1396 }
1397 }
1398 m->pParent.setNull();
1399}
1400
1401/**
1402 * Internal helper that removes "this" from the list of children of its
1403 * parent. Used in uninit() and other places when reparenting is necessary.
1404 *
1405 * The caller must hold the medium tree lock!
1406 */
1407void Medium::setParent(const ComObjPtr<Medium> &pParent)
1408{
1409 m->pParent = pParent;
1410 if (pParent)
1411 pParent->m->llChildren.push_back(this);
1412}
1413
1414
1415////////////////////////////////////////////////////////////////////////////////
1416//
1417// IMedium public methods
1418//
1419////////////////////////////////////////////////////////////////////////////////
1420
1421STDMETHODIMP Medium::COMGETTER(Id)(BSTR *aId)
1422{
1423 CheckComArgOutPointerValid(aId);
1424
1425 AutoCaller autoCaller(this);
1426 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1427
1428 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1429
1430 m->id.toUtf16().cloneTo(aId);
1431
1432 return S_OK;
1433}
1434
1435STDMETHODIMP Medium::COMGETTER(Description)(BSTR *aDescription)
1436{
1437 CheckComArgOutPointerValid(aDescription);
1438
1439 AutoCaller autoCaller(this);
1440 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1441
1442 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1443
1444 m->strDescription.cloneTo(aDescription);
1445
1446 return S_OK;
1447}
1448
1449STDMETHODIMP Medium::COMSETTER(Description)(IN_BSTR aDescription)
1450{
1451 AutoCaller autoCaller(this);
1452 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1453
1454// AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1455
1456 /// @todo update m->description and save the global registry (and local
1457 /// registries of portable VMs referring to this medium), this will also
1458 /// require to add the mRegistered flag to data
1459
1460 NOREF(aDescription);
1461
1462 ReturnComNotImplemented();
1463}
1464
1465STDMETHODIMP Medium::COMGETTER(State)(MediumState_T *aState)
1466{
1467 CheckComArgOutPointerValid(aState);
1468
1469 AutoCaller autoCaller(this);
1470 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1471
1472 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1473 *aState = m->state;
1474
1475 return S_OK;
1476}
1477
1478STDMETHODIMP Medium::COMGETTER(Variant)(ULONG *aVariant)
1479{
1480 CheckComArgOutPointerValid(aVariant);
1481
1482 AutoCaller autoCaller(this);
1483 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1484
1485 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1486 *aVariant = m->variant;
1487
1488 return S_OK;
1489}
1490
1491
1492STDMETHODIMP Medium::COMGETTER(Location)(BSTR *aLocation)
1493{
1494 CheckComArgOutPointerValid(aLocation);
1495
1496 AutoCaller autoCaller(this);
1497 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1498
1499 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1500
1501 m->strLocationFull.cloneTo(aLocation);
1502
1503 return S_OK;
1504}
1505
1506STDMETHODIMP Medium::COMSETTER(Location)(IN_BSTR aLocation)
1507{
1508 CheckComArgStrNotEmptyOrNull(aLocation);
1509
1510 AutoCaller autoCaller(this);
1511 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1512
1513 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1514
1515 /// @todo NEWMEDIA for file names, add the default extension if no extension
1516 /// is present (using the information from the VD backend which also implies
1517 /// that one more parameter should be passed to setLocation() requesting
1518 /// that functionality since it is only allowed when called from this method
1519
1520 /// @todo NEWMEDIA rename the file and set m->location on success, then save
1521 /// the global registry (and local registries of portable VMs referring to
1522 /// this medium), this will also require to add the mRegistered flag to data
1523
1524 ReturnComNotImplemented();
1525}
1526
1527STDMETHODIMP Medium::COMGETTER(Name)(BSTR *aName)
1528{
1529 CheckComArgOutPointerValid(aName);
1530
1531 AutoCaller autoCaller(this);
1532 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1533
1534 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1535
1536 getName().cloneTo(aName);
1537
1538 return S_OK;
1539}
1540
1541STDMETHODIMP Medium::COMGETTER(DeviceType)(DeviceType_T *aDeviceType)
1542{
1543 CheckComArgOutPointerValid(aDeviceType);
1544
1545 AutoCaller autoCaller(this);
1546 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1547
1548 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1549
1550 *aDeviceType = m->devType;
1551
1552 return S_OK;
1553}
1554
1555STDMETHODIMP Medium::COMGETTER(HostDrive)(BOOL *aHostDrive)
1556{
1557 CheckComArgOutPointerValid(aHostDrive);
1558
1559 AutoCaller autoCaller(this);
1560 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1561
1562 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1563
1564 *aHostDrive = m->hostDrive;
1565
1566 return S_OK;
1567}
1568
1569STDMETHODIMP Medium::COMGETTER(Size)(LONG64 *aSize)
1570{
1571 CheckComArgOutPointerValid(aSize);
1572
1573 AutoCaller autoCaller(this);
1574 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1575
1576 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1577
1578 *aSize = m->size;
1579
1580 return S_OK;
1581}
1582
1583STDMETHODIMP Medium::COMGETTER(Format)(BSTR *aFormat)
1584{
1585 CheckComArgOutPointerValid(aFormat);
1586
1587 AutoCaller autoCaller(this);
1588 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1589
1590 /* no need to lock, m->strFormat is const */
1591 m->strFormat.cloneTo(aFormat);
1592
1593 return S_OK;
1594}
1595
1596STDMETHODIMP Medium::COMGETTER(MediumFormat)(IMediumFormat **aMediumFormat)
1597{
1598 CheckComArgOutPointerValid(aMediumFormat);
1599
1600 AutoCaller autoCaller(this);
1601 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1602
1603 /* no need to lock, m->formatObj is const */
1604 m->formatObj.queryInterfaceTo(aMediumFormat);
1605
1606 return S_OK;
1607}
1608
1609STDMETHODIMP Medium::COMGETTER(Type)(MediumType_T *aType)
1610{
1611 CheckComArgOutPointerValid(aType);
1612
1613 AutoCaller autoCaller(this);
1614 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1615
1616 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1617
1618 *aType = m->type;
1619
1620 return S_OK;
1621}
1622
1623STDMETHODIMP Medium::COMSETTER(Type)(MediumType_T aType)
1624{
1625 AutoCaller autoCaller(this);
1626 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1627
1628 // we access mParent and members
1629 AutoMultiWriteLock2 mlock(&m->pVirtualBox->getMediaTreeLockHandle(),
1630 this->lockHandle() COMMA_LOCKVAL_SRC_POS);
1631
1632 switch (m->state)
1633 {
1634 case MediumState_Created:
1635 case MediumState_Inaccessible:
1636 break;
1637 default:
1638 return setStateError();
1639 }
1640
1641 if (m->type == aType)
1642 {
1643 /* Nothing to do */
1644 return S_OK;
1645 }
1646
1647 DeviceType_T devType = getDeviceType();
1648 // DVD media can only be readonly.
1649 if (devType == DeviceType_DVD && aType != MediumType_Readonly)
1650 return setError(VBOX_E_INVALID_OBJECT_STATE,
1651 tr("Cannot change the type of DVD medium '%s'"),
1652 m->strLocationFull.c_str());
1653 // Floppy media can only be writethrough or readonly.
1654 if ( devType == DeviceType_Floppy
1655 && aType != MediumType_Writethrough
1656 && aType != MediumType_Readonly)
1657 return setError(VBOX_E_INVALID_OBJECT_STATE,
1658 tr("Cannot change the type of floppy medium '%s'"),
1659 m->strLocationFull.c_str());
1660
1661 /* cannot change the type of a differencing medium */
1662 if (m->pParent)
1663 return setError(VBOX_E_INVALID_OBJECT_STATE,
1664 tr("Cannot change the type of medium '%s' because it is a differencing medium"),
1665 m->strLocationFull.c_str());
1666
1667 /* Cannot change the type of a medium being in use by more than one VM.
1668 * If the change is to Immutable or MultiAttach then it must not be
1669 * directly attached to any VM, otherwise the assumptions about indirect
1670 * attachment elsewhere are violated and the VM becomes inaccessible.
1671 * Attaching an immutable medium triggers the diff creation, and this is
1672 * vital for the correct operation. */
1673 if ( m->backRefs.size() > 1
1674 || ( ( aType == MediumType_Immutable
1675 || aType == MediumType_MultiAttach)
1676 && m->backRefs.size() > 0))
1677 return setError(VBOX_E_INVALID_OBJECT_STATE,
1678 tr("Cannot change the type of medium '%s' because it is attached to %d virtual machines"),
1679 m->strLocationFull.c_str(), m->backRefs.size());
1680
1681 switch (aType)
1682 {
1683 case MediumType_Normal:
1684 case MediumType_Immutable:
1685 case MediumType_MultiAttach:
1686 {
1687 /* normal can be easily converted to immutable and vice versa even
1688 * if they have children as long as they are not attached to any
1689 * machine themselves */
1690 break;
1691 }
1692 case MediumType_Writethrough:
1693 case MediumType_Shareable:
1694 case MediumType_Readonly:
1695 {
1696 /* cannot change to writethrough, shareable or readonly
1697 * if there are children */
1698 if (getChildren().size() != 0)
1699 return setError(VBOX_E_OBJECT_IN_USE,
1700 tr("Cannot change type for medium '%s' since it has %d child media"),
1701 m->strLocationFull.c_str(), getChildren().size());
1702 if (aType == MediumType_Shareable)
1703 {
1704 if (m->state == MediumState_Inaccessible)
1705 {
1706 HRESULT rc = queryInfo(false /* fSetImageId */, false /* fSetParentId */);
1707 if (FAILED(rc))
1708 return setError(rc,
1709 tr("Cannot change type for medium '%s' to 'Shareable' because the medium is inaccessible"),
1710 m->strLocationFull.c_str());
1711 }
1712
1713 MediumVariant_T variant = getVariant();
1714 if (!(variant & MediumVariant_Fixed))
1715 return setError(VBOX_E_INVALID_OBJECT_STATE,
1716 tr("Cannot change type for medium '%s' to 'Shareable' since it is a dynamic medium storage unit"),
1717 m->strLocationFull.c_str());
1718 }
1719 else if (aType == MediumType_Readonly && devType == DeviceType_HardDisk)
1720 {
1721 // Readonly hard disks are not allowed, this medium type is reserved for
1722 // DVDs and floppy images at the moment. Later we might allow readonly hard
1723 // disks, but that's extremely unusual and many guest OSes will have trouble.
1724 return setError(VBOX_E_INVALID_OBJECT_STATE,
1725 tr("Cannot change type for medium '%s' to 'Readonly' since it is a hard disk"),
1726 m->strLocationFull.c_str());
1727 }
1728 break;
1729 }
1730 default:
1731 AssertFailedReturn(E_FAIL);
1732 }
1733
1734 if (aType == MediumType_MultiAttach)
1735 {
1736 // This type is new with VirtualBox 4.0 and therefore requires settings
1737 // version 1.11 in the settings backend. Unfortunately it is not enough to do
1738 // the usual routine in MachineConfigFile::bumpSettingsVersionIfNeeded() for
1739 // two reasons: The medium type is a property of the media registry tree, which
1740 // can reside in the global config file (for pre-4.0 media); we would therefore
1741 // possibly need to bump the global config version. We don't want to do that though
1742 // because that might make downgrading to pre-4.0 impossible.
1743 // As a result, we can only use these two new types if the medium is NOT in the
1744 // global registry:
1745 const Guid &uuidGlobalRegistry = m->pVirtualBox->getGlobalRegistryId();
1746 if (isInRegistry(uuidGlobalRegistry))
1747 return setError(VBOX_E_INVALID_OBJECT_STATE,
1748 tr("Cannot change type for medium '%s': the media type 'MultiAttach' can only be used "
1749 "on media registered with a machine that was created with VirtualBox 4.0 or later"),
1750 m->strLocationFull.c_str());
1751 }
1752
1753 m->type = aType;
1754
1755 // save the settings
1756 GuidList llRegistriesThatNeedSaving;
1757 addToRegistryIDList(llRegistriesThatNeedSaving);
1758 mlock.release();
1759 HRESULT rc = m->pVirtualBox->saveRegistries(llRegistriesThatNeedSaving);
1760
1761 return rc;
1762}
1763
1764STDMETHODIMP Medium::COMGETTER(AllowedTypes)(ComSafeArrayOut(MediumType_T, aAllowedTypes))
1765{
1766 CheckComArgOutSafeArrayPointerValid(aAllowedTypes);
1767 NOREF(aAllowedTypes); NOREF(aAllowedTypesSize);
1768
1769 AutoCaller autoCaller(this);
1770 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1771
1772 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1773
1774 ReturnComNotImplemented();
1775}
1776
1777STDMETHODIMP Medium::COMGETTER(Parent)(IMedium **aParent)
1778{
1779 CheckComArgOutPointerValid(aParent);
1780
1781 AutoCaller autoCaller(this);
1782 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1783
1784 /* we access mParent */
1785 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
1786
1787 m->pParent.queryInterfaceTo(aParent);
1788
1789 return S_OK;
1790}
1791
1792STDMETHODIMP Medium::COMGETTER(Children)(ComSafeArrayOut(IMedium *, aChildren))
1793{
1794 CheckComArgOutSafeArrayPointerValid(aChildren);
1795
1796 AutoCaller autoCaller(this);
1797 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1798
1799 /* we access children */
1800 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
1801
1802 SafeIfaceArray<IMedium> children(this->getChildren());
1803 children.detachTo(ComSafeArrayOutArg(aChildren));
1804
1805 return S_OK;
1806}
1807
1808STDMETHODIMP Medium::COMGETTER(Base)(IMedium **aBase)
1809{
1810 CheckComArgOutPointerValid(aBase);
1811
1812 /* base() will do callers/locking */
1813
1814 getBase().queryInterfaceTo(aBase);
1815
1816 return S_OK;
1817}
1818
1819STDMETHODIMP Medium::COMGETTER(ReadOnly)(BOOL *aReadOnly)
1820{
1821 CheckComArgOutPointerValid(aReadOnly);
1822
1823 AutoCaller autoCaller(this);
1824 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1825
1826 /* isReadOnly() will do locking */
1827
1828 *aReadOnly = isReadOnly();
1829
1830 return S_OK;
1831}
1832
1833STDMETHODIMP Medium::COMGETTER(LogicalSize)(LONG64 *aLogicalSize)
1834{
1835 CheckComArgOutPointerValid(aLogicalSize);
1836
1837 {
1838 AutoCaller autoCaller(this);
1839 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1840
1841 /* we access mParent */
1842 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
1843
1844 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1845
1846 if (m->pParent.isNull())
1847 {
1848 *aLogicalSize = m->logicalSize;
1849
1850 return S_OK;
1851 }
1852 }
1853
1854 /* We assume that some backend may decide to return a meaningless value in
1855 * response to VDGetSize() for differencing media and therefore always
1856 * ask the base medium ourselves. */
1857
1858 /* base() will do callers/locking */
1859
1860 return getBase()->COMGETTER(LogicalSize)(aLogicalSize);
1861}
1862
1863STDMETHODIMP Medium::COMGETTER(AutoReset)(BOOL *aAutoReset)
1864{
1865 CheckComArgOutPointerValid(aAutoReset);
1866
1867 AutoCaller autoCaller(this);
1868 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1869
1870 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1871
1872 if (m->pParent.isNull())
1873 *aAutoReset = FALSE;
1874 else
1875 *aAutoReset = m->autoReset;
1876
1877 return S_OK;
1878}
1879
1880STDMETHODIMP Medium::COMSETTER(AutoReset)(BOOL aAutoReset)
1881{
1882 AutoCaller autoCaller(this);
1883 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1884
1885 AutoWriteLock mlock(this COMMA_LOCKVAL_SRC_POS);
1886
1887 if (m->pParent.isNull())
1888 return setError(VBOX_E_NOT_SUPPORTED,
1889 tr("Medium '%s' is not differencing"),
1890 m->strLocationFull.c_str());
1891
1892 HRESULT rc = S_OK;
1893
1894 if (m->autoReset != !!aAutoReset)
1895 {
1896 m->autoReset = !!aAutoReset;
1897
1898 // save the settings
1899 GuidList llRegistriesThatNeedSaving;
1900 addToRegistryIDList(llRegistriesThatNeedSaving);
1901 mlock.release();
1902 rc = m->pVirtualBox->saveRegistries(llRegistriesThatNeedSaving);
1903 }
1904
1905 return rc;
1906}
1907
1908STDMETHODIMP Medium::COMGETTER(LastAccessError)(BSTR *aLastAccessError)
1909{
1910 CheckComArgOutPointerValid(aLastAccessError);
1911
1912 AutoCaller autoCaller(this);
1913 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1914
1915 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1916
1917 m->strLastAccessError.cloneTo(aLastAccessError);
1918
1919 return S_OK;
1920}
1921
1922STDMETHODIMP Medium::COMGETTER(MachineIds)(ComSafeArrayOut(BSTR,aMachineIds))
1923{
1924 CheckComArgOutSafeArrayPointerValid(aMachineIds);
1925
1926 AutoCaller autoCaller(this);
1927 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1928
1929 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1930
1931 com::SafeArray<BSTR> machineIds;
1932
1933 if (m->backRefs.size() != 0)
1934 {
1935 machineIds.reset(m->backRefs.size());
1936
1937 size_t i = 0;
1938 for (BackRefList::const_iterator it = m->backRefs.begin();
1939 it != m->backRefs.end(); ++it, ++i)
1940 {
1941 it->machineId.toUtf16().detachTo(&machineIds[i]);
1942 }
1943 }
1944
1945 machineIds.detachTo(ComSafeArrayOutArg(aMachineIds));
1946
1947 return S_OK;
1948}
1949
1950STDMETHODIMP Medium::SetIDs(BOOL aSetImageId,
1951 IN_BSTR aImageId,
1952 BOOL aSetParentId,
1953 IN_BSTR aParentId)
1954{
1955 AutoCaller autoCaller(this);
1956 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1957
1958 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1959
1960 switch (m->state)
1961 {
1962 case MediumState_Created:
1963 break;
1964 default:
1965 return setStateError();
1966 }
1967
1968 Guid imageId, parentId;
1969 if (aSetImageId)
1970 {
1971 if (Bstr(aImageId).isEmpty())
1972 imageId.create();
1973 else
1974 {
1975 imageId = Guid(aImageId);
1976 if (imageId.isEmpty())
1977 return setError(E_INVALIDARG, tr("Argument %s is empty"), "aImageId");
1978 }
1979 }
1980 if (aSetParentId)
1981 {
1982 if (Bstr(aParentId).isEmpty())
1983 parentId.create();
1984 else
1985 parentId = Guid(aParentId);
1986 }
1987
1988 unconst(m->uuidImage) = imageId;
1989 unconst(m->uuidParentImage) = parentId;
1990
1991 HRESULT rc = queryInfo(!!aSetImageId /* fSetImageId */,
1992 !!aSetParentId /* fSetParentId */);
1993
1994 return rc;
1995}
1996
1997STDMETHODIMP Medium::RefreshState(MediumState_T *aState)
1998{
1999 CheckComArgOutPointerValid(aState);
2000
2001 AutoCaller autoCaller(this);
2002 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2003
2004 /* queryInfo() locks this for writing. */
2005 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2006
2007 HRESULT rc = S_OK;
2008
2009 switch (m->state)
2010 {
2011 case MediumState_Created:
2012 case MediumState_Inaccessible:
2013 case MediumState_LockedRead:
2014 {
2015 rc = queryInfo(false /* fSetImageId */, false /* fSetParentId */);
2016 break;
2017 }
2018 default:
2019 break;
2020 }
2021
2022 *aState = m->state;
2023
2024 return rc;
2025}
2026
2027STDMETHODIMP Medium::GetSnapshotIds(IN_BSTR aMachineId,
2028 ComSafeArrayOut(BSTR, aSnapshotIds))
2029{
2030 CheckComArgExpr(aMachineId, Guid(aMachineId).isEmpty() == false);
2031 CheckComArgOutSafeArrayPointerValid(aSnapshotIds);
2032
2033 AutoCaller autoCaller(this);
2034 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2035
2036 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2037
2038 com::SafeArray<BSTR> snapshotIds;
2039
2040 Guid id(aMachineId);
2041 for (BackRefList::const_iterator it = m->backRefs.begin();
2042 it != m->backRefs.end(); ++it)
2043 {
2044 if (it->machineId == id)
2045 {
2046 size_t size = it->llSnapshotIds.size();
2047
2048 /* if the medium is attached to the machine in the current state, we
2049 * return its ID as the first element of the array */
2050 if (it->fInCurState)
2051 ++size;
2052
2053 if (size > 0)
2054 {
2055 snapshotIds.reset(size);
2056
2057 size_t j = 0;
2058 if (it->fInCurState)
2059 it->machineId.toUtf16().detachTo(&snapshotIds[j++]);
2060
2061 for (GuidList::const_iterator jt = it->llSnapshotIds.begin();
2062 jt != it->llSnapshotIds.end();
2063 ++jt, ++j)
2064 {
2065 (*jt).toUtf16().detachTo(&snapshotIds[j]);
2066 }
2067 }
2068
2069 break;
2070 }
2071 }
2072
2073 snapshotIds.detachTo(ComSafeArrayOutArg(aSnapshotIds));
2074
2075 return S_OK;
2076}
2077
2078/**
2079 * @note @a aState may be NULL if the state value is not needed (only for
2080 * in-process calls).
2081 */
2082STDMETHODIMP Medium::LockRead(MediumState_T *aState)
2083{
2084 AutoCaller autoCaller(this);
2085 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2086
2087 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2088
2089 /* Wait for a concurrently running queryInfo() to complete */
2090 while (m->queryInfoRunning)
2091 {
2092 alock.leave();
2093 RTSemEventMultiWait(m->queryInfoSem, RT_INDEFINITE_WAIT);
2094 alock.enter();
2095 }
2096
2097 /* return the current state before */
2098 if (aState)
2099 *aState = m->state;
2100
2101 HRESULT rc = S_OK;
2102
2103 switch (m->state)
2104 {
2105 case MediumState_Created:
2106 case MediumState_Inaccessible:
2107 case MediumState_LockedRead:
2108 {
2109 ++m->readers;
2110
2111 ComAssertMsgBreak(m->readers != 0, ("Counter overflow"), rc = E_FAIL);
2112
2113 /* Remember pre-lock state */
2114 if (m->state != MediumState_LockedRead)
2115 m->preLockState = m->state;
2116
2117 LogFlowThisFunc(("Okay - prev state=%d readers=%d\n", m->state, m->readers));
2118 m->state = MediumState_LockedRead;
2119
2120 break;
2121 }
2122 default:
2123 {
2124 LogFlowThisFunc(("Failing - state=%d\n", m->state));
2125 rc = setStateError();
2126 break;
2127 }
2128 }
2129
2130 return rc;
2131}
2132
2133/**
2134 * @note @a aState may be NULL if the state value is not needed (only for
2135 * in-process calls).
2136 */
2137STDMETHODIMP Medium::UnlockRead(MediumState_T *aState)
2138{
2139 AutoCaller autoCaller(this);
2140 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2141
2142 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2143
2144 HRESULT rc = S_OK;
2145
2146 switch (m->state)
2147 {
2148 case MediumState_LockedRead:
2149 {
2150 Assert(m->readers != 0);
2151 --m->readers;
2152
2153 /* Reset the state after the last reader */
2154 if (m->readers == 0)
2155 {
2156 m->state = m->preLockState;
2157 /* There are cases where we inject the deleting state into
2158 * a medium locked for reading. Make sure #unmarkForDeletion()
2159 * gets the right state afterwards. */
2160 if (m->preLockState == MediumState_Deleting)
2161 m->preLockState = MediumState_Created;
2162 }
2163
2164 LogFlowThisFunc(("new state=%d\n", m->state));
2165 break;
2166 }
2167 default:
2168 {
2169 LogFlowThisFunc(("Failing - state=%d\n", m->state));
2170 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
2171 tr("Medium '%s' is not locked for reading"),
2172 m->strLocationFull.c_str());
2173 break;
2174 }
2175 }
2176
2177 /* return the current state after */
2178 if (aState)
2179 *aState = m->state;
2180
2181 return rc;
2182}
2183
2184/**
2185 * @note @a aState may be NULL if the state value is not needed (only for
2186 * in-process calls).
2187 */
2188STDMETHODIMP Medium::LockWrite(MediumState_T *aState)
2189{
2190 AutoCaller autoCaller(this);
2191 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2192
2193 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2194
2195 /* Wait for a concurrently running queryInfo() to complete */
2196 while (m->queryInfoRunning)
2197 {
2198 alock.leave();
2199 RTSemEventMultiWait(m->queryInfoSem, RT_INDEFINITE_WAIT);
2200 alock.enter();
2201 }
2202
2203 /* return the current state before */
2204 if (aState)
2205 *aState = m->state;
2206
2207 HRESULT rc = S_OK;
2208
2209 switch (m->state)
2210 {
2211 case MediumState_Created:
2212 case MediumState_Inaccessible:
2213 {
2214 m->preLockState = m->state;
2215
2216 LogFlowThisFunc(("Okay - prev state=%d locationFull=%s\n", m->state, getLocationFull().c_str()));
2217 m->state = MediumState_LockedWrite;
2218 break;
2219 }
2220 default:
2221 {
2222 LogFlowThisFunc(("Failing - state=%d locationFull=%s\n", m->state, getLocationFull().c_str()));
2223 rc = setStateError();
2224 break;
2225 }
2226 }
2227
2228 return rc;
2229}
2230
2231/**
2232 * @note @a aState may be NULL if the state value is not needed (only for
2233 * in-process calls).
2234 */
2235STDMETHODIMP Medium::UnlockWrite(MediumState_T *aState)
2236{
2237 AutoCaller autoCaller(this);
2238 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2239
2240 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2241
2242 HRESULT rc = S_OK;
2243
2244 switch (m->state)
2245 {
2246 case MediumState_LockedWrite:
2247 {
2248 m->state = m->preLockState;
2249 /* There are cases where we inject the deleting state into
2250 * a medium locked for writing. Make sure #unmarkForDeletion()
2251 * gets the right state afterwards. */
2252 if (m->preLockState == MediumState_Deleting)
2253 m->preLockState = MediumState_Created;
2254 LogFlowThisFunc(("new state=%d locationFull=%s\n", m->state, getLocationFull().c_str()));
2255 break;
2256 }
2257 default:
2258 {
2259 LogFlowThisFunc(("Failing - state=%d locationFull=%s\n", m->state, getLocationFull().c_str()));
2260 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
2261 tr("Medium '%s' is not locked for writing"),
2262 m->strLocationFull.c_str());
2263 break;
2264 }
2265 }
2266
2267 /* return the current state after */
2268 if (aState)
2269 *aState = m->state;
2270
2271 return rc;
2272}
2273
2274STDMETHODIMP Medium::Close()
2275{
2276 AutoCaller autoCaller(this);
2277 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2278
2279 // make a copy of VirtualBox pointer which gets nulled by uninit()
2280 ComObjPtr<VirtualBox> pVirtualBox(m->pVirtualBox);
2281
2282 GuidList llRegistriesThatNeedSaving;
2283 MultiResult mrc = close(&llRegistriesThatNeedSaving, autoCaller);
2284 /* Must save the registries, since an entry was most likely removed. */
2285 mrc = pVirtualBox->saveRegistries(llRegistriesThatNeedSaving);
2286
2287 return mrc;
2288}
2289
2290STDMETHODIMP Medium::GetProperty(IN_BSTR aName, BSTR *aValue)
2291{
2292 CheckComArgStrNotEmptyOrNull(aName);
2293 CheckComArgOutPointerValid(aValue);
2294
2295 AutoCaller autoCaller(this);
2296 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2297
2298 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2299
2300 settings::StringsMap::const_iterator it = m->mapProperties.find(Utf8Str(aName));
2301 if (it == m->mapProperties.end())
2302 return setError(VBOX_E_OBJECT_NOT_FOUND,
2303 tr("Property '%ls' does not exist"), aName);
2304
2305 it->second.cloneTo(aValue);
2306
2307 return S_OK;
2308}
2309
2310STDMETHODIMP Medium::SetProperty(IN_BSTR aName, IN_BSTR aValue)
2311{
2312 CheckComArgStrNotEmptyOrNull(aName);
2313
2314 AutoCaller autoCaller(this);
2315 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2316
2317 AutoWriteLock mlock(this COMMA_LOCKVAL_SRC_POS);
2318
2319 switch (m->state)
2320 {
2321 case MediumState_Created:
2322 case MediumState_Inaccessible:
2323 break;
2324 default:
2325 return setStateError();
2326 }
2327
2328 settings::StringsMap::iterator it = m->mapProperties.find(Utf8Str(aName));
2329 if (it == m->mapProperties.end())
2330 return setError(VBOX_E_OBJECT_NOT_FOUND,
2331 tr("Property '%ls' does not exist"),
2332 aName);
2333
2334 it->second = aValue;
2335
2336 // save the settings
2337 GuidList llRegistriesThatNeedSaving;
2338 addToRegistryIDList(llRegistriesThatNeedSaving);
2339 mlock.release();
2340 HRESULT rc = m->pVirtualBox->saveRegistries(llRegistriesThatNeedSaving);
2341
2342 return rc;
2343}
2344
2345STDMETHODIMP Medium::GetProperties(IN_BSTR aNames,
2346 ComSafeArrayOut(BSTR, aReturnNames),
2347 ComSafeArrayOut(BSTR, aReturnValues))
2348{
2349 CheckComArgOutSafeArrayPointerValid(aReturnNames);
2350 CheckComArgOutSafeArrayPointerValid(aReturnValues);
2351
2352 AutoCaller autoCaller(this);
2353 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2354
2355 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2356
2357 /// @todo make use of aNames according to the documentation
2358 NOREF(aNames);
2359
2360 com::SafeArray<BSTR> names(m->mapProperties.size());
2361 com::SafeArray<BSTR> values(m->mapProperties.size());
2362 size_t i = 0;
2363
2364 for (settings::StringsMap::const_iterator it = m->mapProperties.begin();
2365 it != m->mapProperties.end();
2366 ++it)
2367 {
2368 it->first.cloneTo(&names[i]);
2369 it->second.cloneTo(&values[i]);
2370 ++i;
2371 }
2372
2373 names.detachTo(ComSafeArrayOutArg(aReturnNames));
2374 values.detachTo(ComSafeArrayOutArg(aReturnValues));
2375
2376 return S_OK;
2377}
2378
2379STDMETHODIMP Medium::SetProperties(ComSafeArrayIn(IN_BSTR, aNames),
2380 ComSafeArrayIn(IN_BSTR, aValues))
2381{
2382 CheckComArgSafeArrayNotNull(aNames);
2383 CheckComArgSafeArrayNotNull(aValues);
2384
2385 AutoCaller autoCaller(this);
2386 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2387
2388 AutoWriteLock mlock(this COMMA_LOCKVAL_SRC_POS);
2389
2390 com::SafeArray<IN_BSTR> names(ComSafeArrayInArg(aNames));
2391 com::SafeArray<IN_BSTR> values(ComSafeArrayInArg(aValues));
2392
2393 /* first pass: validate names */
2394 for (size_t i = 0;
2395 i < names.size();
2396 ++i)
2397 {
2398 if (m->mapProperties.find(Utf8Str(names[i])) == m->mapProperties.end())
2399 return setError(VBOX_E_OBJECT_NOT_FOUND,
2400 tr("Property '%ls' does not exist"), names[i]);
2401 }
2402
2403 /* second pass: assign */
2404 for (size_t i = 0;
2405 i < names.size();
2406 ++i)
2407 {
2408 settings::StringsMap::iterator it = m->mapProperties.find(Utf8Str(names[i]));
2409 AssertReturn(it != m->mapProperties.end(), E_FAIL);
2410
2411 it->second = Utf8Str(values[i]);
2412 }
2413
2414 // save the settings
2415 GuidList llRegistriesThatNeedSaving;
2416 addToRegistryIDList(llRegistriesThatNeedSaving);
2417 mlock.release();
2418 HRESULT rc = m->pVirtualBox->saveRegistries(llRegistriesThatNeedSaving);
2419
2420 return rc;
2421}
2422
2423STDMETHODIMP Medium::CreateBaseStorage(LONG64 aLogicalSize,
2424 ULONG aVariant,
2425 IProgress **aProgress)
2426{
2427 CheckComArgOutPointerValid(aProgress);
2428 if (aLogicalSize < 0)
2429 return setError(E_INVALIDARG, tr("The medium size argument (%lld) is negative"), aLogicalSize);
2430
2431 AutoCaller autoCaller(this);
2432 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2433
2434 HRESULT rc = S_OK;
2435 ComObjPtr <Progress> pProgress;
2436 Medium::Task *pTask = NULL;
2437
2438 try
2439 {
2440 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2441
2442 aVariant = (MediumVariant_T)((unsigned)aVariant & (unsigned)~MediumVariant_Diff);
2443 if ( !(aVariant & MediumVariant_Fixed)
2444 && !(m->formatObj->getCapabilities() & MediumFormatCapabilities_CreateDynamic))
2445 throw setError(VBOX_E_NOT_SUPPORTED,
2446 tr("Medium format '%s' does not support dynamic storage creation"),
2447 m->strFormat.c_str());
2448 if ( (aVariant & MediumVariant_Fixed)
2449 && !(m->formatObj->getCapabilities() & MediumFormatCapabilities_CreateDynamic))
2450 throw setError(VBOX_E_NOT_SUPPORTED,
2451 tr("Medium format '%s' does not support fixed storage creation"),
2452 m->strFormat.c_str());
2453
2454 if (m->state != MediumState_NotCreated)
2455 throw setStateError();
2456
2457 pProgress.createObject();
2458 rc = pProgress->init(m->pVirtualBox,
2459 static_cast<IMedium*>(this),
2460 (aVariant & MediumVariant_Fixed)
2461 ? BstrFmt(tr("Creating fixed medium storage unit '%s'"), m->strLocationFull.c_str()).raw()
2462 : BstrFmt(tr("Creating dynamic medium storage unit '%s'"), m->strLocationFull.c_str()).raw(),
2463 TRUE /* aCancelable */);
2464 if (FAILED(rc))
2465 throw rc;
2466
2467 /* setup task object to carry out the operation asynchronously */
2468 pTask = new Medium::CreateBaseTask(this, pProgress, aLogicalSize,
2469 (MediumVariant_T)aVariant);
2470 rc = pTask->rc();
2471 AssertComRC(rc);
2472 if (FAILED(rc))
2473 throw rc;
2474
2475 m->state = MediumState_Creating;
2476 }
2477 catch (HRESULT aRC) { rc = aRC; }
2478
2479 if (SUCCEEDED(rc))
2480 {
2481 rc = startThread(pTask);
2482
2483 if (SUCCEEDED(rc))
2484 pProgress.queryInterfaceTo(aProgress);
2485 }
2486 else if (pTask != NULL)
2487 delete pTask;
2488
2489 return rc;
2490}
2491
2492STDMETHODIMP Medium::DeleteStorage(IProgress **aProgress)
2493{
2494 CheckComArgOutPointerValid(aProgress);
2495
2496 AutoCaller autoCaller(this);
2497 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2498
2499 ComObjPtr<Progress> pProgress;
2500
2501 GuidList llRegistriesThatNeedSaving;
2502 MultiResult mrc = deleteStorage(&pProgress,
2503 false /* aWait */,
2504 &llRegistriesThatNeedSaving);
2505 /* Must save the registries in any case, since an entry was removed. */
2506 mrc = m->pVirtualBox->saveRegistries(llRegistriesThatNeedSaving);
2507
2508 if (SUCCEEDED(mrc))
2509 pProgress.queryInterfaceTo(aProgress);
2510
2511 return mrc;
2512}
2513
2514STDMETHODIMP Medium::CreateDiffStorage(IMedium *aTarget,
2515 ULONG aVariant,
2516 IProgress **aProgress)
2517{
2518 CheckComArgNotNull(aTarget);
2519 CheckComArgOutPointerValid(aProgress);
2520
2521 AutoCaller autoCaller(this);
2522 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2523
2524 ComObjPtr<Medium> diff = static_cast<Medium*>(aTarget);
2525
2526 // locking: we need the tree lock first because we access parent pointers
2527 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
2528 AutoMultiWriteLock2 alock(this, diff COMMA_LOCKVAL_SRC_POS);
2529
2530 if (m->type == MediumType_Writethrough)
2531 return setError(VBOX_E_INVALID_OBJECT_STATE,
2532 tr("Medium type of '%s' is Writethrough"),
2533 m->strLocationFull.c_str());
2534 else if (m->type == MediumType_Shareable)
2535 return setError(VBOX_E_INVALID_OBJECT_STATE,
2536 tr("Medium type of '%s' is Shareable"),
2537 m->strLocationFull.c_str());
2538 else if (m->type == MediumType_Readonly)
2539 return setError(VBOX_E_INVALID_OBJECT_STATE,
2540 tr("Medium type of '%s' is Readonly"),
2541 m->strLocationFull.c_str());
2542
2543 /* Apply the normal locking logic to the entire chain. */
2544 MediumLockList *pMediumLockList(new MediumLockList());
2545 HRESULT rc = diff->createMediumLockList(true /* fFailIfInaccessible */,
2546 true /* fMediumLockWrite */,
2547 this,
2548 *pMediumLockList);
2549 if (FAILED(rc))
2550 {
2551 delete pMediumLockList;
2552 return rc;
2553 }
2554
2555 rc = pMediumLockList->Lock();
2556 if (FAILED(rc))
2557 {
2558 delete pMediumLockList;
2559
2560 return setError(rc, tr("Could not lock medium when creating diff '%s'"),
2561 diff->getLocationFull().c_str());
2562 }
2563
2564 Guid parentMachineRegistry;
2565 if (getFirstRegistryMachineId(parentMachineRegistry))
2566 {
2567 /* since this medium has been just created it isn't associated yet */
2568 diff->m->llRegistryIDs.push_back(parentMachineRegistry);
2569 }
2570
2571 treeLock.release();
2572 alock.release();
2573
2574 ComObjPtr <Progress> pProgress;
2575
2576 rc = createDiffStorage(diff, (MediumVariant_T)aVariant, pMediumLockList,
2577 &pProgress, false /* aWait */,
2578 NULL /* pfNeedsGlobalSaveSettings*/);
2579 if (FAILED(rc))
2580 delete pMediumLockList;
2581 else
2582 pProgress.queryInterfaceTo(aProgress);
2583
2584 return rc;
2585}
2586
2587STDMETHODIMP Medium::MergeTo(IMedium *aTarget, IProgress **aProgress)
2588{
2589 CheckComArgNotNull(aTarget);
2590 CheckComArgOutPointerValid(aProgress);
2591 ComAssertRet(aTarget != this, E_INVALIDARG);
2592
2593 AutoCaller autoCaller(this);
2594 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2595
2596 ComObjPtr<Medium> pTarget = static_cast<Medium*>(aTarget);
2597
2598 bool fMergeForward = false;
2599 ComObjPtr<Medium> pParentForTarget;
2600 MediaList childrenToReparent;
2601 MediumLockList *pMediumLockList = NULL;
2602
2603 HRESULT rc = S_OK;
2604
2605 rc = prepareMergeTo(pTarget, NULL, NULL, true, fMergeForward,
2606 pParentForTarget, childrenToReparent, pMediumLockList);
2607 if (FAILED(rc)) return rc;
2608
2609 ComObjPtr <Progress> pProgress;
2610
2611 rc = mergeTo(pTarget, fMergeForward, pParentForTarget, childrenToReparent,
2612 pMediumLockList, &pProgress, false /* aWait */,
2613 NULL /* pfNeedsGlobalSaveSettings */);
2614 if (FAILED(rc))
2615 cancelMergeTo(childrenToReparent, pMediumLockList);
2616 else
2617 pProgress.queryInterfaceTo(aProgress);
2618
2619 return rc;
2620}
2621
2622STDMETHODIMP Medium::CloneTo(IMedium *aTarget,
2623 ULONG aVariant,
2624 IMedium *aParent,
2625 IProgress **aProgress)
2626{
2627 CheckComArgNotNull(aTarget);
2628 CheckComArgOutPointerValid(aProgress);
2629 ComAssertRet(aTarget != this, E_INVALIDARG);
2630
2631 AutoCaller autoCaller(this);
2632 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2633
2634 ComObjPtr<Medium> pTarget = static_cast<Medium*>(aTarget);
2635 ComObjPtr<Medium> pParent;
2636 if (aParent)
2637 pParent = static_cast<Medium*>(aParent);
2638
2639 HRESULT rc = S_OK;
2640 ComObjPtr<Progress> pProgress;
2641 Medium::Task *pTask = NULL;
2642
2643 try
2644 {
2645 // locking: we need the tree lock first because we access parent pointers
2646 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
2647 // and we need to write-lock the media involved
2648 AutoMultiWriteLock3 alock(this, pTarget, pParent COMMA_LOCKVAL_SRC_POS);
2649
2650 if ( pTarget->m->state != MediumState_NotCreated
2651 && pTarget->m->state != MediumState_Created)
2652 throw pTarget->setStateError();
2653
2654 /* Build the source lock list. */
2655 MediumLockList *pSourceMediumLockList(new MediumLockList());
2656 rc = createMediumLockList(true /* fFailIfInaccessible */,
2657 false /* fMediumLockWrite */,
2658 NULL,
2659 *pSourceMediumLockList);
2660 if (FAILED(rc))
2661 {
2662 delete pSourceMediumLockList;
2663 throw rc;
2664 }
2665
2666 /* Build the target lock list (including the to-be parent chain). */
2667 MediumLockList *pTargetMediumLockList(new MediumLockList());
2668 rc = pTarget->createMediumLockList(true /* fFailIfInaccessible */,
2669 true /* fMediumLockWrite */,
2670 pParent,
2671 *pTargetMediumLockList);
2672 if (FAILED(rc))
2673 {
2674 delete pSourceMediumLockList;
2675 delete pTargetMediumLockList;
2676 throw rc;
2677 }
2678
2679 rc = pSourceMediumLockList->Lock();
2680 if (FAILED(rc))
2681 {
2682 delete pSourceMediumLockList;
2683 delete pTargetMediumLockList;
2684 throw setError(rc,
2685 tr("Failed to lock source media '%s'"),
2686 getLocationFull().c_str());
2687 }
2688 rc = pTargetMediumLockList->Lock();
2689 if (FAILED(rc))
2690 {
2691 delete pSourceMediumLockList;
2692 delete pTargetMediumLockList;
2693 throw setError(rc,
2694 tr("Failed to lock target media '%s'"),
2695 pTarget->getLocationFull().c_str());
2696 }
2697
2698 pProgress.createObject();
2699 rc = pProgress->init(m->pVirtualBox,
2700 static_cast <IMedium *>(this),
2701 BstrFmt(tr("Creating clone medium '%s'"), pTarget->m->strLocationFull.c_str()).raw(),
2702 TRUE /* aCancelable */);
2703 if (FAILED(rc))
2704 {
2705 delete pSourceMediumLockList;
2706 delete pTargetMediumLockList;
2707 throw rc;
2708 }
2709
2710 /* setup task object to carry out the operation asynchronously */
2711 pTask = new Medium::CloneTask(this, pProgress, pTarget,
2712 (MediumVariant_T)aVariant,
2713 pParent, UINT32_MAX, UINT32_MAX,
2714 pSourceMediumLockList, pTargetMediumLockList);
2715 rc = pTask->rc();
2716 AssertComRC(rc);
2717 if (FAILED(rc))
2718 throw rc;
2719
2720 if (pTarget->m->state == MediumState_NotCreated)
2721 pTarget->m->state = MediumState_Creating;
2722 }
2723 catch (HRESULT aRC) { rc = aRC; }
2724
2725 if (SUCCEEDED(rc))
2726 {
2727 rc = startThread(pTask);
2728
2729 if (SUCCEEDED(rc))
2730 pProgress.queryInterfaceTo(aProgress);
2731 }
2732 else if (pTask != NULL)
2733 delete pTask;
2734
2735 return rc;
2736}
2737
2738STDMETHODIMP Medium::Compact(IProgress **aProgress)
2739{
2740 CheckComArgOutPointerValid(aProgress);
2741
2742 AutoCaller autoCaller(this);
2743 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2744
2745 HRESULT rc = S_OK;
2746 ComObjPtr <Progress> pProgress;
2747 Medium::Task *pTask = NULL;
2748
2749 try
2750 {
2751 /* We need to lock both the current object, and the tree lock (would
2752 * cause a lock order violation otherwise) for createMediumLockList. */
2753 AutoMultiWriteLock2 multilock(&m->pVirtualBox->getMediaTreeLockHandle(),
2754 this->lockHandle()
2755 COMMA_LOCKVAL_SRC_POS);
2756
2757 /* Build the medium lock list. */
2758 MediumLockList *pMediumLockList(new MediumLockList());
2759 rc = createMediumLockList(true /* fFailIfInaccessible */ ,
2760 true /* fMediumLockWrite */,
2761 NULL,
2762 *pMediumLockList);
2763 if (FAILED(rc))
2764 {
2765 delete pMediumLockList;
2766 throw rc;
2767 }
2768
2769 rc = pMediumLockList->Lock();
2770 if (FAILED(rc))
2771 {
2772 delete pMediumLockList;
2773 throw setError(rc,
2774 tr("Failed to lock media when compacting '%s'"),
2775 getLocationFull().c_str());
2776 }
2777
2778 pProgress.createObject();
2779 rc = pProgress->init(m->pVirtualBox,
2780 static_cast <IMedium *>(this),
2781 BstrFmt(tr("Compacting medium '%s'"), m->strLocationFull.c_str()).raw(),
2782 TRUE /* aCancelable */);
2783 if (FAILED(rc))
2784 {
2785 delete pMediumLockList;
2786 throw rc;
2787 }
2788
2789 /* setup task object to carry out the operation asynchronously */
2790 pTask = new Medium::CompactTask(this, pProgress, pMediumLockList);
2791 rc = pTask->rc();
2792 AssertComRC(rc);
2793 if (FAILED(rc))
2794 throw rc;
2795 }
2796 catch (HRESULT aRC) { rc = aRC; }
2797
2798 if (SUCCEEDED(rc))
2799 {
2800 rc = startThread(pTask);
2801
2802 if (SUCCEEDED(rc))
2803 pProgress.queryInterfaceTo(aProgress);
2804 }
2805 else if (pTask != NULL)
2806 delete pTask;
2807
2808 return rc;
2809}
2810
2811STDMETHODIMP Medium::Resize(LONG64 aLogicalSize, IProgress **aProgress)
2812{
2813 CheckComArgOutPointerValid(aProgress);
2814
2815 AutoCaller autoCaller(this);
2816 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2817
2818 HRESULT rc = S_OK;
2819 ComObjPtr <Progress> pProgress;
2820 Medium::Task *pTask = NULL;
2821
2822 try
2823 {
2824 /* We need to lock both the current object, and the tree lock (would
2825 * cause a lock order violation otherwise) for createMediumLockList. */
2826 AutoMultiWriteLock2 multilock(&m->pVirtualBox->getMediaTreeLockHandle(),
2827 this->lockHandle()
2828 COMMA_LOCKVAL_SRC_POS);
2829
2830 /* Build the medium lock list. */
2831 MediumLockList *pMediumLockList(new MediumLockList());
2832 rc = createMediumLockList(true /* fFailIfInaccessible */ ,
2833 true /* fMediumLockWrite */,
2834 NULL,
2835 *pMediumLockList);
2836 if (FAILED(rc))
2837 {
2838 delete pMediumLockList;
2839 throw rc;
2840 }
2841
2842 rc = pMediumLockList->Lock();
2843 if (FAILED(rc))
2844 {
2845 delete pMediumLockList;
2846 throw setError(rc,
2847 tr("Failed to lock media when compacting '%s'"),
2848 getLocationFull().c_str());
2849 }
2850
2851 pProgress.createObject();
2852 rc = pProgress->init(m->pVirtualBox,
2853 static_cast <IMedium *>(this),
2854 BstrFmt(tr("Compacting medium '%s'"), m->strLocationFull.c_str()).raw(),
2855 TRUE /* aCancelable */);
2856 if (FAILED(rc))
2857 {
2858 delete pMediumLockList;
2859 throw rc;
2860 }
2861
2862 /* setup task object to carry out the operation asynchronously */
2863 pTask = new Medium::ResizeTask(this, aLogicalSize, pProgress, pMediumLockList);
2864 rc = pTask->rc();
2865 AssertComRC(rc);
2866 if (FAILED(rc))
2867 throw rc;
2868 }
2869 catch (HRESULT aRC) { rc = aRC; }
2870
2871 if (SUCCEEDED(rc))
2872 {
2873 rc = startThread(pTask);
2874
2875 if (SUCCEEDED(rc))
2876 pProgress.queryInterfaceTo(aProgress);
2877 }
2878 else if (pTask != NULL)
2879 delete pTask;
2880
2881 return rc;
2882}
2883
2884STDMETHODIMP Medium::Reset(IProgress **aProgress)
2885{
2886 CheckComArgOutPointerValid(aProgress);
2887
2888 AutoCaller autoCaller(this);
2889 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2890
2891 HRESULT rc = S_OK;
2892 ComObjPtr <Progress> pProgress;
2893 Medium::Task *pTask = NULL;
2894
2895 try
2896 {
2897 /* canClose() needs the tree lock */
2898 AutoMultiWriteLock2 multilock(&m->pVirtualBox->getMediaTreeLockHandle(),
2899 this->lockHandle()
2900 COMMA_LOCKVAL_SRC_POS);
2901
2902 LogFlowThisFunc(("ENTER for medium %s\n", m->strLocationFull.c_str()));
2903
2904 if (m->pParent.isNull())
2905 throw setError(VBOX_E_NOT_SUPPORTED,
2906 tr("Medium type of '%s' is not differencing"),
2907 m->strLocationFull.c_str());
2908
2909 rc = canClose();
2910 if (FAILED(rc))
2911 throw rc;
2912
2913 /* Build the medium lock list. */
2914 MediumLockList *pMediumLockList(new MediumLockList());
2915 rc = createMediumLockList(true /* fFailIfInaccessible */,
2916 true /* fMediumLockWrite */,
2917 NULL,
2918 *pMediumLockList);
2919 if (FAILED(rc))
2920 {
2921 delete pMediumLockList;
2922 throw rc;
2923 }
2924
2925 /* Temporary leave this lock, cause IMedium::LockWrite, will wait for
2926 * an running IMedium::queryInfo. If there is one running it might be
2927 * it tries to acquire a MediaTreeLock as well -> dead-lock. */
2928 multilock.leave();
2929 rc = pMediumLockList->Lock();
2930 multilock.enter();
2931 if (FAILED(rc))
2932 {
2933 delete pMediumLockList;
2934 throw setError(rc,
2935 tr("Failed to lock media when resetting '%s'"),
2936 getLocationFull().c_str());
2937 }
2938
2939 pProgress.createObject();
2940 rc = pProgress->init(m->pVirtualBox,
2941 static_cast<IMedium*>(this),
2942 BstrFmt(tr("Resetting differencing medium '%s'"), m->strLocationFull.c_str()).raw(),
2943 FALSE /* aCancelable */);
2944 if (FAILED(rc))
2945 throw rc;
2946
2947 /* setup task object to carry out the operation asynchronously */
2948 pTask = new Medium::ResetTask(this, pProgress, pMediumLockList);
2949 rc = pTask->rc();
2950 AssertComRC(rc);
2951 if (FAILED(rc))
2952 throw rc;
2953 }
2954 catch (HRESULT aRC) { rc = aRC; }
2955
2956 if (SUCCEEDED(rc))
2957 {
2958 rc = startThread(pTask);
2959
2960 if (SUCCEEDED(rc))
2961 pProgress.queryInterfaceTo(aProgress);
2962 }
2963 else
2964 {
2965 /* Note: on success, the task will unlock this */
2966 {
2967 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2968 HRESULT rc2 = UnlockWrite(NULL);
2969 AssertComRC(rc2);
2970 }
2971 if (pTask != NULL)
2972 delete pTask;
2973 }
2974
2975 LogFlowThisFunc(("LEAVE, rc=%Rhrc\n", rc));
2976
2977 return rc;
2978}
2979
2980////////////////////////////////////////////////////////////////////////////////
2981//
2982// Medium public internal methods
2983//
2984////////////////////////////////////////////////////////////////////////////////
2985
2986/**
2987 * Internal method to return the medium's parent medium. Must have caller + locking!
2988 * @return
2989 */
2990const ComObjPtr<Medium>& Medium::getParent() const
2991{
2992 return m->pParent;
2993}
2994
2995/**
2996 * Internal method to return the medium's list of child media. Must have caller + locking!
2997 * @return
2998 */
2999const MediaList& Medium::getChildren() const
3000{
3001 return m->llChildren;
3002}
3003
3004/**
3005 * Internal method to return the medium's GUID. Must have caller + locking!
3006 * @return
3007 */
3008const Guid& Medium::getId() const
3009{
3010 return m->id;
3011}
3012
3013/**
3014 * Internal method to return the medium's state. Must have caller + locking!
3015 * @return
3016 */
3017MediumState_T Medium::getState() const
3018{
3019 return m->state;
3020}
3021
3022/**
3023 * Internal method to return the medium's variant. Must have caller + locking!
3024 * @return
3025 */
3026MediumVariant_T Medium::getVariant() const
3027{
3028 return m->variant;
3029}
3030
3031/**
3032 * Internal method which returns true if this medium represents a host drive.
3033 * @return
3034 */
3035bool Medium::isHostDrive() const
3036{
3037 return m->hostDrive;
3038}
3039
3040/**
3041 * Internal method to return the medium's full location. Must have caller + locking!
3042 * @return
3043 */
3044const Utf8Str& Medium::getLocationFull() const
3045{
3046 return m->strLocationFull;
3047}
3048
3049/**
3050 * Internal method to return the medium's format string. Must have caller + locking!
3051 * @return
3052 */
3053const Utf8Str& Medium::getFormat() const
3054{
3055 return m->strFormat;
3056}
3057
3058/**
3059 * Internal method to return the medium's format object. Must have caller + locking!
3060 * @return
3061 */
3062const ComObjPtr<MediumFormat>& Medium::getMediumFormat() const
3063{
3064 return m->formatObj;
3065}
3066
3067/**
3068 * Internal method that returns true if the medium is represented by a file on the host disk
3069 * (and not iSCSI or something).
3070 * @return
3071 */
3072bool Medium::isMediumFormatFile() const
3073{
3074 if ( m->formatObj
3075 && (m->formatObj->getCapabilities() & MediumFormatCapabilities_File)
3076 )
3077 return true;
3078 return false;
3079}
3080
3081/**
3082 * Internal method to return the medium's size. Must have caller + locking!
3083 * @return
3084 */
3085uint64_t Medium::getSize() const
3086{
3087 return m->size;
3088}
3089
3090/**
3091 * Returns the medium device type. Must have caller + locking!
3092 * @return
3093 */
3094DeviceType_T Medium::getDeviceType() const
3095{
3096 return m->devType;
3097}
3098
3099/**
3100 * Returns the medium type. Must have caller + locking!
3101 * @return
3102 */
3103MediumType_T Medium::getType() const
3104{
3105 return m->type;
3106}
3107
3108/**
3109 * Returns a short version of the location attribute.
3110 *
3111 * @note Must be called from under this object's read or write lock.
3112 */
3113Utf8Str Medium::getName()
3114{
3115 Utf8Str name = RTPathFilename(m->strLocationFull.c_str());
3116 return name;
3117}
3118
3119/**
3120 * This adds the given UUID to the list of media registries in which this
3121 * medium should be registered. The UUID can either be a machine UUID,
3122 * to add a machine registry, or the global registry UUID as returned by
3123 * VirtualBox::getGlobalRegistryId().
3124 *
3125 * Note that for hard disks, this method does nothing if the medium is
3126 * already in another registry to avoid having hard disks in more than
3127 * one registry, which causes trouble with keeping diff images in sync.
3128 * See getFirstRegistryMachineId() for details.
3129 *
3130 * If fRecurse == true, then the media tree lock must be held for reading.
3131 *
3132 * @param id
3133 * @param fRecurse If true, recurses into child media to make sure the whole tree has registries in sync.
3134 * @return true if the registry was added; false if the given id was already on the list.
3135 */
3136bool Medium::addRegistry(const Guid& id, bool fRecurse)
3137{
3138 AutoCaller autoCaller(this);
3139 if (FAILED(autoCaller.rc()))
3140 return false;
3141 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3142
3143 bool fAdd = true;
3144
3145 // hard disks cannot be in more than one registry
3146 if ( m->devType == DeviceType_HardDisk
3147 && m->llRegistryIDs.size() > 0)
3148 fAdd = false;
3149
3150 // no need to add the UUID twice
3151 if (fAdd)
3152 {
3153 for (GuidList::const_iterator it = m->llRegistryIDs.begin();
3154 it != m->llRegistryIDs.end();
3155 ++it)
3156 {
3157 if ((*it) == id)
3158 {
3159 fAdd = false;
3160 break;
3161 }
3162 }
3163 }
3164
3165 if (fAdd)
3166 m->llRegistryIDs.push_back(id);
3167
3168 if (fRecurse)
3169 {
3170 // Get private list of children and release medium lock straight away.
3171 MediaList llChildren(m->llChildren);
3172 alock.release();
3173
3174 for (MediaList::iterator it = llChildren.begin();
3175 it != llChildren.end();
3176 ++it)
3177 {
3178 Medium *pChild = *it;
3179 fAdd |= pChild->addRegistry(id, true);
3180 }
3181 }
3182
3183 return fAdd;
3184}
3185
3186/**
3187 * Removes the given UUID from the list of media registry UUIDs. Returns true
3188 * if found or false if not.
3189 *
3190 * If fRecurse == true, then the media tree lock must be held for reading.
3191 *
3192 * @param id
3193 * @param fRecurse If true, recurses into child media to make sure the whole tree has registries in sync.
3194 * @return
3195 */
3196bool Medium::removeRegistry(const Guid& id, bool fRecurse)
3197{
3198 AutoCaller autoCaller(this);
3199 if (FAILED(autoCaller.rc()))
3200 return false;
3201 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3202
3203 bool fRemove = false;
3204
3205 for (GuidList::iterator it = m->llRegistryIDs.begin();
3206 it != m->llRegistryIDs.end();
3207 ++it)
3208 {
3209 if ((*it) == id)
3210 {
3211 m->llRegistryIDs.erase(it);
3212 fRemove = true;
3213 break;
3214 }
3215 }
3216
3217 if (fRecurse)
3218 {
3219 // Get private list of children and release medium lock straight away.
3220 MediaList llChildren(m->llChildren);
3221 alock.release();
3222
3223 for (MediaList::iterator it = llChildren.begin();
3224 it != llChildren.end();
3225 ++it)
3226 {
3227 Medium *pChild = *it;
3228 fRemove |= pChild->removeRegistry(id, true);
3229 }
3230 }
3231
3232 return fRemove;
3233}
3234
3235/**
3236 * Returns true if id is in the list of media registries for this medium.
3237 *
3238 * Must have caller + read locking!
3239 *
3240 * @param id
3241 * @return
3242 */
3243bool Medium::isInRegistry(const Guid& id)
3244{
3245 for (GuidList::const_iterator it = m->llRegistryIDs.begin();
3246 it != m->llRegistryIDs.end();
3247 ++it)
3248 {
3249 if (*it == id)
3250 return true;
3251 }
3252
3253 return false;
3254}
3255
3256/**
3257 * Internal method to return the medium's first registry machine (i.e. the machine in whose
3258 * machine XML this medium is listed).
3259 *
3260 * Every attached medium must now (4.0) reside in at least one media registry, which is identified
3261 * by a UUID. This is either a machine UUID if the machine is from 4.0 or newer, in which case
3262 * machines have their own media registries, or it is the pseudo-UUID of the VirtualBox
3263 * object if the machine is old and still needs the global registry in VirtualBox.xml.
3264 *
3265 * By definition, hard disks may only be in one media registry, in which all its children
3266 * will be stored as well. Otherwise we run into problems with having keep multiple registries
3267 * in sync. (This is the "cloned VM" case in which VM1 may link to the disks of VM2; in this
3268 * case, only VM2's registry is used for the disk in question.)
3269 *
3270 * If there is no medium registry, particularly if the medium has not been attached yet, this
3271 * does not modify uuid and returns false.
3272 *
3273 * ISOs and RAWs, by contrast, can be in more than one repository to make things easier for
3274 * the user.
3275 *
3276 * Must have caller + locking!
3277 *
3278 * @param uuid Receives first registry machine UUID, if available.
3279 * @return true if uuid was set.
3280 */
3281bool Medium::getFirstRegistryMachineId(Guid &uuid) const
3282{
3283 if (m->llRegistryIDs.size())
3284 {
3285 uuid = m->llRegistryIDs.front();
3286 return true;
3287 }
3288 return false;
3289}
3290
3291/**
3292 * Adds all the IDs of the registries in which this medium is registered to the given list
3293 * of UUIDs, but only if they are not on the list yet.
3294 * @param llRegistryIDs
3295 */
3296HRESULT Medium::addToRegistryIDList(GuidList &llRegistryIDs)
3297{
3298 AutoCaller autoCaller(this);
3299 if (FAILED(autoCaller.rc())) return false;
3300
3301 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3302
3303 for (GuidList::const_iterator it = m->llRegistryIDs.begin();
3304 it != m->llRegistryIDs.end();
3305 ++it)
3306 {
3307 VirtualBox::addGuidToListUniquely(llRegistryIDs, *it);
3308 }
3309
3310 return S_OK;
3311}
3312
3313/**
3314 * Adds the given machine and optionally the snapshot to the list of the objects
3315 * this medium is attached to.
3316 *
3317 * @param aMachineId Machine ID.
3318 * @param aSnapshotId Snapshot ID; when non-empty, adds a snapshot attachment.
3319 */
3320HRESULT Medium::addBackReference(const Guid &aMachineId,
3321 const Guid &aSnapshotId /*= Guid::Empty*/)
3322{
3323 AssertReturn(!aMachineId.isEmpty(), E_FAIL);
3324
3325 LogFlowThisFunc(("ENTER, aMachineId: {%RTuuid}, aSnapshotId: {%RTuuid}\n", aMachineId.raw(), aSnapshotId.raw()));
3326
3327 AutoCaller autoCaller(this);
3328 AssertComRCReturnRC(autoCaller.rc());
3329
3330 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3331
3332 switch (m->state)
3333 {
3334 case MediumState_Created:
3335 case MediumState_Inaccessible:
3336 case MediumState_LockedRead:
3337 case MediumState_LockedWrite:
3338 break;
3339
3340 default:
3341 return setStateError();
3342 }
3343
3344 if (m->numCreateDiffTasks > 0)
3345 return setError(VBOX_E_OBJECT_IN_USE,
3346 tr("Cannot attach medium '%s' {%RTuuid}: %u differencing child media are being created"),
3347 m->strLocationFull.c_str(),
3348 m->id.raw(),
3349 m->numCreateDiffTasks);
3350
3351 BackRefList::iterator it = std::find_if(m->backRefs.begin(),
3352 m->backRefs.end(),
3353 BackRef::EqualsTo(aMachineId));
3354 if (it == m->backRefs.end())
3355 {
3356 BackRef ref(aMachineId, aSnapshotId);
3357 m->backRefs.push_back(ref);
3358
3359 return S_OK;
3360 }
3361
3362 // if the caller has not supplied a snapshot ID, then we're attaching
3363 // to a machine a medium which represents the machine's current state,
3364 // so set the flag
3365 if (aSnapshotId.isEmpty())
3366 {
3367 /* sanity: no duplicate attachments */
3368 if (it->fInCurState)
3369 return setError(VBOX_E_OBJECT_IN_USE,
3370 tr("Cannot attach medium '%s' {%RTuuid}: medium is already associated with the current state of machine uuid {%RTuuid}!"),
3371 m->strLocationFull.c_str(),
3372 m->id.raw(),
3373 aMachineId.raw());
3374 it->fInCurState = true;
3375
3376 return S_OK;
3377 }
3378
3379 // otherwise: a snapshot medium is being attached
3380
3381 /* sanity: no duplicate attachments */
3382 for (GuidList::const_iterator jt = it->llSnapshotIds.begin();
3383 jt != it->llSnapshotIds.end();
3384 ++jt)
3385 {
3386 const Guid &idOldSnapshot = *jt;
3387
3388 if (idOldSnapshot == aSnapshotId)
3389 {
3390#ifdef DEBUG
3391 dumpBackRefs();
3392#endif
3393 return setError(VBOX_E_OBJECT_IN_USE,
3394 tr("Cannot attach medium '%s' {%RTuuid} from snapshot '%RTuuid': medium is already in use by this snapshot!"),
3395 m->strLocationFull.c_str(),
3396 m->id.raw(),
3397 aSnapshotId.raw());
3398 }
3399 }
3400
3401 it->llSnapshotIds.push_back(aSnapshotId);
3402 it->fInCurState = false;
3403
3404 LogFlowThisFuncLeave();
3405
3406 return S_OK;
3407}
3408
3409/**
3410 * Removes the given machine and optionally the snapshot from the list of the
3411 * objects this medium is attached to.
3412 *
3413 * @param aMachineId Machine ID.
3414 * @param aSnapshotId Snapshot ID; when non-empty, removes the snapshot
3415 * attachment.
3416 */
3417HRESULT Medium::removeBackReference(const Guid &aMachineId,
3418 const Guid &aSnapshotId /*= Guid::Empty*/)
3419{
3420 AssertReturn(!aMachineId.isEmpty(), E_FAIL);
3421
3422 AutoCaller autoCaller(this);
3423 AssertComRCReturnRC(autoCaller.rc());
3424
3425 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3426
3427 BackRefList::iterator it =
3428 std::find_if(m->backRefs.begin(), m->backRefs.end(),
3429 BackRef::EqualsTo(aMachineId));
3430 AssertReturn(it != m->backRefs.end(), E_FAIL);
3431
3432 if (aSnapshotId.isEmpty())
3433 {
3434 /* remove the current state attachment */
3435 it->fInCurState = false;
3436 }
3437 else
3438 {
3439 /* remove the snapshot attachment */
3440 GuidList::iterator jt = std::find(it->llSnapshotIds.begin(),
3441 it->llSnapshotIds.end(),
3442 aSnapshotId);
3443
3444 AssertReturn(jt != it->llSnapshotIds.end(), E_FAIL);
3445 it->llSnapshotIds.erase(jt);
3446 }
3447
3448 /* if the backref becomes empty, remove it */
3449 if (it->fInCurState == false && it->llSnapshotIds.size() == 0)
3450 m->backRefs.erase(it);
3451
3452 return S_OK;
3453}
3454
3455/**
3456 * Internal method to return the medium's list of backrefs. Must have caller + locking!
3457 * @return
3458 */
3459const Guid* Medium::getFirstMachineBackrefId() const
3460{
3461 if (!m->backRefs.size())
3462 return NULL;
3463
3464 return &m->backRefs.front().machineId;
3465}
3466
3467/**
3468 * Internal method which returns a machine that either this medium or one of its children
3469 * is attached to. This is used for finding a replacement media registry when an existing
3470 * media registry is about to be deleted in VirtualBox::unregisterMachine().
3471 *
3472 * Must have caller + locking, *and* caller must hold the media tree lock!
3473 * @return
3474 */
3475const Guid* Medium::getAnyMachineBackref() const
3476{
3477 if (m->backRefs.size())
3478 return &m->backRefs.front().machineId;
3479
3480 for (MediaList::iterator it = m->llChildren.begin();
3481 it != m->llChildren.end();
3482 ++it)
3483 {
3484 Medium *pChild = *it;
3485 // recurse for this child
3486 const Guid* puuid;
3487 if ((puuid = pChild->getAnyMachineBackref()))
3488 return puuid;
3489 }
3490
3491 return NULL;
3492}
3493
3494const Guid* Medium::getFirstMachineBackrefSnapshotId() const
3495{
3496 if (!m->backRefs.size())
3497 return NULL;
3498
3499 const BackRef &ref = m->backRefs.front();
3500 if (!ref.llSnapshotIds.size())
3501 return NULL;
3502
3503 return &ref.llSnapshotIds.front();
3504}
3505
3506size_t Medium::getMachineBackRefCount() const
3507{
3508 return m->backRefs.size();
3509}
3510
3511#ifdef DEBUG
3512/**
3513 * Debugging helper that gets called after VirtualBox initialization that writes all
3514 * machine backreferences to the debug log.
3515 */
3516void Medium::dumpBackRefs()
3517{
3518 AutoCaller autoCaller(this);
3519 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3520
3521 LogFlowThisFunc(("Dumping backrefs for medium '%s':\n", m->strLocationFull.c_str()));
3522
3523 for (BackRefList::iterator it2 = m->backRefs.begin();
3524 it2 != m->backRefs.end();
3525 ++it2)
3526 {
3527 const BackRef &ref = *it2;
3528 LogFlowThisFunc((" Backref from machine {%RTuuid} (fInCurState: %d)\n", ref.machineId.raw(), ref.fInCurState));
3529
3530 for (GuidList::const_iterator jt2 = it2->llSnapshotIds.begin();
3531 jt2 != it2->llSnapshotIds.end();
3532 ++jt2)
3533 {
3534 const Guid &id = *jt2;
3535 LogFlowThisFunc((" Backref from snapshot {%RTuuid}\n", id.raw()));
3536 }
3537 }
3538}
3539#endif
3540
3541/**
3542 * Checks if the given change of \a aOldPath to \a aNewPath affects the location
3543 * of this media and updates it if necessary to reflect the new location.
3544 *
3545 * @param aOldPath Old path (full).
3546 * @param aNewPath New path (full).
3547 *
3548 * @note Locks this object for writing.
3549 */
3550HRESULT Medium::updatePath(const Utf8Str &strOldPath, const Utf8Str &strNewPath)
3551{
3552 AssertReturn(!strOldPath.isEmpty(), E_FAIL);
3553 AssertReturn(!strNewPath.isEmpty(), E_FAIL);
3554
3555 AutoCaller autoCaller(this);
3556 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3557
3558 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3559
3560 LogFlowThisFunc(("locationFull.before='%s'\n", m->strLocationFull.c_str()));
3561
3562 const char *pcszMediumPath = m->strLocationFull.c_str();
3563
3564 if (RTPathStartsWith(pcszMediumPath, strOldPath.c_str()))
3565 {
3566 Utf8Str newPath(strNewPath);
3567 newPath.append(pcszMediumPath + strOldPath.length());
3568 unconst(m->strLocationFull) = newPath;
3569
3570 LogFlowThisFunc(("locationFull.after='%s'\n", m->strLocationFull.c_str()));
3571 }
3572
3573 return S_OK;
3574}
3575
3576/**
3577 * Returns the base medium of the media chain this medium is part of.
3578 *
3579 * The base medium is found by walking up the parent-child relationship axis.
3580 * If the medium doesn't have a parent (i.e. it's a base medium), it
3581 * returns itself in response to this method.
3582 *
3583 * @param aLevel Where to store the number of ancestors of this medium
3584 * (zero for the base), may be @c NULL.
3585 *
3586 * @note Locks medium tree for reading.
3587 */
3588ComObjPtr<Medium> Medium::getBase(uint32_t *aLevel /*= NULL*/)
3589{
3590 ComObjPtr<Medium> pBase;
3591 uint32_t level;
3592
3593 AutoCaller autoCaller(this);
3594 AssertReturn(autoCaller.isOk(), pBase);
3595
3596 /* we access mParent */
3597 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3598
3599 pBase = this;
3600 level = 0;
3601
3602 if (m->pParent)
3603 {
3604 for (;;)
3605 {
3606 AutoCaller baseCaller(pBase);
3607 AssertReturn(baseCaller.isOk(), pBase);
3608
3609 if (pBase->m->pParent.isNull())
3610 break;
3611
3612 pBase = pBase->m->pParent;
3613 ++level;
3614 }
3615 }
3616
3617 if (aLevel != NULL)
3618 *aLevel = level;
3619
3620 return pBase;
3621}
3622
3623/**
3624 * Returns @c true if this medium cannot be modified because it has
3625 * dependents (children) or is part of the snapshot. Related to the medium
3626 * type and posterity, not to the current media state.
3627 *
3628 * @note Locks this object and medium tree for reading.
3629 */
3630bool Medium::isReadOnly()
3631{
3632 AutoCaller autoCaller(this);
3633 AssertComRCReturn(autoCaller.rc(), false);
3634
3635 /* we access children */
3636 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3637
3638 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3639
3640 switch (m->type)
3641 {
3642 case MediumType_Normal:
3643 {
3644 if (getChildren().size() != 0)
3645 return true;
3646
3647 for (BackRefList::const_iterator it = m->backRefs.begin();
3648 it != m->backRefs.end(); ++it)
3649 if (it->llSnapshotIds.size() != 0)
3650 return true;
3651
3652 if (m->variant & MediumVariant_VmdkStreamOptimized)
3653 return true;
3654
3655 return false;
3656 }
3657 case MediumType_Immutable:
3658 case MediumType_MultiAttach:
3659 return true;
3660 case MediumType_Writethrough:
3661 case MediumType_Shareable:
3662 case MediumType_Readonly: /* explicit readonly media has no diffs */
3663 return false;
3664 default:
3665 break;
3666 }
3667
3668 AssertFailedReturn(false);
3669}
3670
3671/**
3672 * Internal method to return the medium's size. Must have caller + locking!
3673 * @return
3674 */
3675void Medium::updateId(const Guid &id)
3676{
3677 unconst(m->id) = id;
3678}
3679
3680/**
3681 * Saves medium data by appending a new child node to the given
3682 * parent XML settings node.
3683 *
3684 * @param data Settings struct to be updated.
3685 * @param strHardDiskFolder Folder for which paths should be relative.
3686 *
3687 * @note Locks this object, medium tree and children for reading.
3688 */
3689HRESULT Medium::saveSettings(settings::Medium &data,
3690 const Utf8Str &strHardDiskFolder)
3691{
3692 AutoCaller autoCaller(this);
3693 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3694
3695 /* we access mParent */
3696 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3697
3698 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3699
3700 data.uuid = m->id;
3701
3702 // make path relative if needed
3703 if ( !strHardDiskFolder.isEmpty()
3704 && RTPathStartsWith(m->strLocationFull.c_str(), strHardDiskFolder.c_str())
3705 )
3706 data.strLocation = m->strLocationFull.substr(strHardDiskFolder.length() + 1);
3707 else
3708 data.strLocation = m->strLocationFull;
3709 data.strFormat = m->strFormat;
3710
3711 /* optional, only for diffs, default is false */
3712 if (m->pParent)
3713 data.fAutoReset = m->autoReset;
3714 else
3715 data.fAutoReset = false;
3716
3717 /* optional */
3718 data.strDescription = m->strDescription;
3719
3720 /* optional properties */
3721 data.properties.clear();
3722 for (settings::StringsMap::const_iterator it = m->mapProperties.begin();
3723 it != m->mapProperties.end();
3724 ++it)
3725 {
3726 /* only save properties that have non-default values */
3727 if (!it->second.isEmpty())
3728 {
3729 const Utf8Str &name = it->first;
3730 const Utf8Str &value = it->second;
3731 data.properties[name] = value;
3732 }
3733 }
3734
3735 /* only for base media */
3736 if (m->pParent.isNull())
3737 data.hdType = m->type;
3738
3739 /* save all children */
3740 for (MediaList::const_iterator it = getChildren().begin();
3741 it != getChildren().end();
3742 ++it)
3743 {
3744 settings::Medium med;
3745 HRESULT rc = (*it)->saveSettings(med, strHardDiskFolder);
3746 AssertComRCReturnRC(rc);
3747 data.llChildren.push_back(med);
3748 }
3749
3750 return S_OK;
3751}
3752
3753/**
3754 * Constructs a medium lock list for this medium. The lock is not taken.
3755 *
3756 * @note Locks the medium tree for reading.
3757 *
3758 * @param fFailIfInaccessible If true, this fails with an error if a medium is inaccessible. If false,
3759 * inaccessible media are silently skipped and not locked (i.e. their state remains "Inaccessible");
3760 * this is necessary for a VM's removable media VM startup for which we do not want to fail.
3761 * @param fMediumLockWrite Whether to associate a write lock with this medium.
3762 * @param pToBeParent Medium which will become the parent of this medium.
3763 * @param mediumLockList Where to store the resulting list.
3764 */
3765HRESULT Medium::createMediumLockList(bool fFailIfInaccessible,
3766 bool fMediumLockWrite,
3767 Medium *pToBeParent,
3768 MediumLockList &mediumLockList)
3769{
3770 AutoCaller autoCaller(this);
3771 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3772
3773 HRESULT rc = S_OK;
3774
3775 /* we access parent medium objects */
3776 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3777
3778 /* paranoid sanity checking if the medium has a to-be parent medium */
3779 if (pToBeParent)
3780 {
3781 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3782 ComAssertRet(getParent().isNull(), E_FAIL);
3783 ComAssertRet(getChildren().size() == 0, E_FAIL);
3784 }
3785
3786 ErrorInfoKeeper eik;
3787 MultiResult mrc(S_OK);
3788
3789 ComObjPtr<Medium> pMedium = this;
3790 while (!pMedium.isNull())
3791 {
3792 // need write lock for RefreshState if medium is inaccessible
3793 AutoWriteLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
3794
3795 /* Accessibility check must be first, otherwise locking interferes
3796 * with getting the medium state. Lock lists are not created for
3797 * fun, and thus getting the medium status is no luxury. */
3798 MediumState_T mediumState = pMedium->getState();
3799 if (mediumState == MediumState_Inaccessible)
3800 {
3801 rc = pMedium->RefreshState(&mediumState);
3802 if (FAILED(rc)) return rc;
3803
3804 if (mediumState == MediumState_Inaccessible)
3805 {
3806 // ignore inaccessible ISO media and silently return S_OK,
3807 // otherwise VM startup (esp. restore) may fail without good reason
3808 if (!fFailIfInaccessible)
3809 return S_OK;
3810
3811 // otherwise report an error
3812 Bstr error;
3813 rc = pMedium->COMGETTER(LastAccessError)(error.asOutParam());
3814 if (FAILED(rc)) return rc;
3815
3816 /* collect multiple errors */
3817 eik.restore();
3818 Assert(!error.isEmpty());
3819 mrc = setError(E_FAIL,
3820 "%ls",
3821 error.raw());
3822 // error message will be something like
3823 // "Could not open the medium ... VD: error VERR_FILE_NOT_FOUND opening image file ... (VERR_FILE_NOT_FOUND).
3824 eik.fetch();
3825 }
3826 }
3827
3828 if (pMedium == this)
3829 mediumLockList.Prepend(pMedium, fMediumLockWrite);
3830 else
3831 mediumLockList.Prepend(pMedium, false);
3832
3833 pMedium = pMedium->getParent();
3834 if (pMedium.isNull() && pToBeParent)
3835 {
3836 pMedium = pToBeParent;
3837 pToBeParent = NULL;
3838 }
3839 }
3840
3841 return mrc;
3842}
3843
3844/**
3845 * Creates a new differencing storage unit using the format of the given target
3846 * medium and the location. Note that @c aTarget must be NotCreated.
3847 *
3848 * The @a aMediumLockList parameter contains the associated medium lock list,
3849 * which must be in locked state. If @a aWait is @c true then the caller is
3850 * responsible for unlocking.
3851 *
3852 * If @a aProgress is not NULL but the object it points to is @c null then a
3853 * new progress object will be created and assigned to @a *aProgress on
3854 * success, otherwise the existing progress object is used. If @a aProgress is
3855 * NULL, then no progress object is created/used at all.
3856 *
3857 * When @a aWait is @c false, this method will create a thread to perform the
3858 * create operation asynchronously and will return immediately. Otherwise, it
3859 * will perform the operation on the calling thread and will not return to the
3860 * caller until the operation is completed. Note that @a aProgress cannot be
3861 * NULL when @a aWait is @c false (this method will assert in this case).
3862 *
3863 * @param aTarget Target medium.
3864 * @param aVariant Precise medium variant to create.
3865 * @param aMediumLockList List of media which should be locked.
3866 * @param aProgress Where to find/store a Progress object to track
3867 * operation completion.
3868 * @param aWait @c true if this method should block instead of
3869 * creating an asynchronous thread.
3870 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs that will receive the registry IDs that need saving.
3871 * This only works in "wait" mode; otherwise saveRegistries is called automatically by the thread that
3872 * was created, and this parameter is ignored.
3873 *
3874 * @note Locks this object and @a aTarget for writing.
3875 */
3876HRESULT Medium::createDiffStorage(ComObjPtr<Medium> &aTarget,
3877 MediumVariant_T aVariant,
3878 MediumLockList *aMediumLockList,
3879 ComObjPtr<Progress> *aProgress,
3880 bool aWait,
3881 GuidList *pllRegistriesThatNeedSaving)
3882{
3883 AssertReturn(!aTarget.isNull(), E_FAIL);
3884 AssertReturn(aMediumLockList, E_FAIL);
3885 AssertReturn(aProgress != NULL || aWait == true, E_FAIL);
3886
3887 AutoCaller autoCaller(this);
3888 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3889
3890 AutoCaller targetCaller(aTarget);
3891 if (FAILED(targetCaller.rc())) return targetCaller.rc();
3892
3893 HRESULT rc = S_OK;
3894 ComObjPtr<Progress> pProgress;
3895 Medium::Task *pTask = NULL;
3896
3897 try
3898 {
3899 AutoMultiWriteLock2 alock(this, aTarget COMMA_LOCKVAL_SRC_POS);
3900
3901 ComAssertThrow( m->type != MediumType_Writethrough
3902 && m->type != MediumType_Shareable
3903 && m->type != MediumType_Readonly, E_FAIL);
3904 ComAssertThrow(m->state == MediumState_LockedRead, E_FAIL);
3905
3906 if (aTarget->m->state != MediumState_NotCreated)
3907 throw aTarget->setStateError();
3908
3909 /* Check that the medium is not attached to the current state of
3910 * any VM referring to it. */
3911 for (BackRefList::const_iterator it = m->backRefs.begin();
3912 it != m->backRefs.end();
3913 ++it)
3914 {
3915 if (it->fInCurState)
3916 {
3917 /* Note: when a VM snapshot is being taken, all normal media
3918 * attached to the VM in the current state will be, as an
3919 * exception, also associated with the snapshot which is about
3920 * to create (see SnapshotMachine::init()) before deassociating
3921 * them from the current state (which takes place only on
3922 * success in Machine::fixupHardDisks()), so that the size of
3923 * snapshotIds will be 1 in this case. The extra condition is
3924 * used to filter out this legal situation. */
3925 if (it->llSnapshotIds.size() == 0)
3926 throw setError(VBOX_E_INVALID_OBJECT_STATE,
3927 tr("Medium '%s' is attached to a virtual machine with UUID {%RTuuid}. No differencing media based on it may be created until it is detached"),
3928 m->strLocationFull.c_str(), it->machineId.raw());
3929
3930 Assert(it->llSnapshotIds.size() == 1);
3931 }
3932 }
3933
3934 if (aProgress != NULL)
3935 {
3936 /* use the existing progress object... */
3937 pProgress = *aProgress;
3938
3939 /* ...but create a new one if it is null */
3940 if (pProgress.isNull())
3941 {
3942 pProgress.createObject();
3943 rc = pProgress->init(m->pVirtualBox,
3944 static_cast<IMedium*>(this),
3945 BstrFmt(tr("Creating differencing medium storage unit '%s'"), aTarget->m->strLocationFull.c_str()).raw(),
3946 TRUE /* aCancelable */);
3947 if (FAILED(rc))
3948 throw rc;
3949 }
3950 }
3951
3952 /* setup task object to carry out the operation sync/async */
3953 pTask = new Medium::CreateDiffTask(this, pProgress, aTarget, aVariant,
3954 aMediumLockList,
3955 aWait /* fKeepMediumLockList */);
3956 rc = pTask->rc();
3957 AssertComRC(rc);
3958 if (FAILED(rc))
3959 throw rc;
3960
3961 /* register a task (it will deregister itself when done) */
3962 ++m->numCreateDiffTasks;
3963 Assert(m->numCreateDiffTasks != 0); /* overflow? */
3964
3965 aTarget->m->state = MediumState_Creating;
3966 }
3967 catch (HRESULT aRC) { rc = aRC; }
3968
3969 if (SUCCEEDED(rc))
3970 {
3971 if (aWait)
3972 rc = runNow(pTask, pllRegistriesThatNeedSaving);
3973 else
3974 rc = startThread(pTask);
3975
3976 if (SUCCEEDED(rc) && aProgress != NULL)
3977 *aProgress = pProgress;
3978 }
3979 else if (pTask != NULL)
3980 delete pTask;
3981
3982 return rc;
3983}
3984
3985/**
3986 * Returns a preferred format for differencing media.
3987 */
3988Utf8Str Medium::getPreferredDiffFormat()
3989{
3990 AutoCaller autoCaller(this);
3991 AssertComRCReturn(autoCaller.rc(), Utf8Str::Empty);
3992
3993 /* check that our own format supports diffs */
3994 if (!(m->formatObj->getCapabilities() & MediumFormatCapabilities_Differencing))
3995 {
3996 /* use the default format if not */
3997 Utf8Str tmp;
3998 m->pVirtualBox->getDefaultHardDiskFormat(tmp);
3999 return tmp;
4000 }
4001
4002 /* m->strFormat is const, no need to lock */
4003 return m->strFormat;
4004}
4005
4006/**
4007 * Implementation for the public Medium::Close() with the exception of calling
4008 * VirtualBox::saveRegistries(), in case someone wants to call this for several
4009 * media.
4010 *
4011 * After this returns with success, uninit() has been called on the medium, and
4012 * the object is no longer usable ("not ready" state).
4013 *
4014 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs that will receive the registry IDs that need saving.
4015 * @param autoCaller AutoCaller instance which must have been created on the caller's stack for this medium. This gets released here
4016 * upon which the Medium instance gets uninitialized.
4017 * @return
4018 */
4019HRESULT Medium::close(GuidList *pllRegistriesThatNeedSaving,
4020 AutoCaller &autoCaller)
4021{
4022 // we're accessing parent/child and backrefs, so lock the tree first, then ourselves
4023 AutoMultiWriteLock2 multilock(&m->pVirtualBox->getMediaTreeLockHandle(),
4024 this->lockHandle()
4025 COMMA_LOCKVAL_SRC_POS);
4026
4027 LogFlowFunc(("ENTER for %s\n", getLocationFull().c_str()));
4028
4029 bool wasCreated = true;
4030
4031 switch (m->state)
4032 {
4033 case MediumState_NotCreated:
4034 wasCreated = false;
4035 break;
4036 case MediumState_Created:
4037 case MediumState_Inaccessible:
4038 break;
4039 default:
4040 return setStateError();
4041 }
4042
4043 if (m->backRefs.size() != 0)
4044 return setError(VBOX_E_OBJECT_IN_USE,
4045 tr("Medium '%s' cannot be closed because it is still attached to %d virtual machines"),
4046 m->strLocationFull.c_str(), m->backRefs.size());
4047
4048 // perform extra media-dependent close checks
4049 HRESULT rc = canClose();
4050 if (FAILED(rc)) return rc;
4051
4052 if (wasCreated)
4053 {
4054 // remove from the list of known media before performing actual
4055 // uninitialization (to keep the media registry consistent on
4056 // failure to do so)
4057 rc = unregisterWithVirtualBox(pllRegistriesThatNeedSaving);
4058 if (FAILED(rc)) return rc;
4059 }
4060
4061 // leave the AutoCaller, as otherwise uninit() will simply hang
4062 autoCaller.release();
4063
4064 // Keep the locks held until after uninit, as otherwise the consistency
4065 // of the medium tree cannot be guaranteed.
4066 uninit();
4067
4068 LogFlowFuncLeave();
4069
4070 return rc;
4071}
4072
4073/**
4074 * Deletes the medium storage unit.
4075 *
4076 * If @a aProgress is not NULL but the object it points to is @c null then a new
4077 * progress object will be created and assigned to @a *aProgress on success,
4078 * otherwise the existing progress object is used. If Progress is NULL, then no
4079 * progress object is created/used at all.
4080 *
4081 * When @a aWait is @c false, this method will create a thread to perform the
4082 * delete operation asynchronously and will return immediately. Otherwise, it
4083 * will perform the operation on the calling thread and will not return to the
4084 * caller until the operation is completed. Note that @a aProgress cannot be
4085 * NULL when @a aWait is @c false (this method will assert in this case).
4086 *
4087 * @param aProgress Where to find/store a Progress object to track operation
4088 * completion.
4089 * @param aWait @c true if this method should block instead of creating
4090 * an asynchronous thread.
4091 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
4092 * by this function if the caller should invoke VirtualBox::saveRegistries() because the global settings have changed.
4093 * This only works in "wait" mode; otherwise saveRegistries gets called automatically by the thread that was created,
4094 * and this parameter is ignored.
4095 *
4096 * @note Locks mVirtualBox and this object for writing. Locks medium tree for
4097 * writing.
4098 */
4099HRESULT Medium::deleteStorage(ComObjPtr<Progress> *aProgress,
4100 bool aWait,
4101 GuidList *pllRegistriesThatNeedSaving)
4102{
4103 AssertReturn(aProgress != NULL || aWait == true, E_FAIL);
4104
4105 AutoCaller autoCaller(this);
4106 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4107
4108 HRESULT rc = S_OK;
4109 ComObjPtr<Progress> pProgress;
4110 Medium::Task *pTask = NULL;
4111
4112 try
4113 {
4114 /* we're accessing the media tree, and canClose() needs it too */
4115 AutoMultiWriteLock2 multilock(&m->pVirtualBox->getMediaTreeLockHandle(),
4116 this->lockHandle()
4117 COMMA_LOCKVAL_SRC_POS);
4118 LogFlowThisFunc(("aWait=%RTbool locationFull=%s\n", aWait, getLocationFull().c_str() ));
4119
4120 if ( !(m->formatObj->getCapabilities() & ( MediumFormatCapabilities_CreateDynamic
4121 | MediumFormatCapabilities_CreateFixed)))
4122 throw setError(VBOX_E_NOT_SUPPORTED,
4123 tr("Medium format '%s' does not support storage deletion"),
4124 m->strFormat.c_str());
4125
4126 /* Note that we are fine with Inaccessible state too: a) for symmetry
4127 * with create calls and b) because it doesn't really harm to try, if
4128 * it is really inaccessible, the delete operation will fail anyway.
4129 * Accepting Inaccessible state is especially important because all
4130 * registered media are initially Inaccessible upon VBoxSVC startup
4131 * until COMGETTER(RefreshState) is called. Accept Deleting state
4132 * because some callers need to put the medium in this state early
4133 * to prevent races. */
4134 switch (m->state)
4135 {
4136 case MediumState_Created:
4137 case MediumState_Deleting:
4138 case MediumState_Inaccessible:
4139 break;
4140 default:
4141 throw setStateError();
4142 }
4143
4144 if (m->backRefs.size() != 0)
4145 {
4146 Utf8Str strMachines;
4147 for (BackRefList::const_iterator it = m->backRefs.begin();
4148 it != m->backRefs.end();
4149 ++it)
4150 {
4151 const BackRef &b = *it;
4152 if (strMachines.length())
4153 strMachines.append(", ");
4154 strMachines.append(b.machineId.toString().c_str());
4155 }
4156#ifdef DEBUG
4157 dumpBackRefs();
4158#endif
4159 throw setError(VBOX_E_OBJECT_IN_USE,
4160 tr("Cannot delete storage: medium '%s' is still attached to the following %d virtual machine(s): %s"),
4161 m->strLocationFull.c_str(),
4162 m->backRefs.size(),
4163 strMachines.c_str());
4164 }
4165
4166 rc = canClose();
4167 if (FAILED(rc))
4168 throw rc;
4169
4170 /* go to Deleting state, so that the medium is not actually locked */
4171 if (m->state != MediumState_Deleting)
4172 {
4173 rc = markForDeletion();
4174 if (FAILED(rc))
4175 throw rc;
4176 }
4177
4178 /* Build the medium lock list. */
4179 MediumLockList *pMediumLockList(new MediumLockList());
4180 rc = createMediumLockList(true /* fFailIfInaccessible */,
4181 true /* fMediumLockWrite */,
4182 NULL,
4183 *pMediumLockList);
4184 if (FAILED(rc))
4185 {
4186 delete pMediumLockList;
4187 throw rc;
4188 }
4189
4190 rc = pMediumLockList->Lock();
4191 if (FAILED(rc))
4192 {
4193 delete pMediumLockList;
4194 throw setError(rc,
4195 tr("Failed to lock media when deleting '%s'"),
4196 getLocationFull().c_str());
4197 }
4198
4199 /* try to remove from the list of known media before performing
4200 * actual deletion (we favor the consistency of the media registry
4201 * which would have been broken if unregisterWithVirtualBox() failed
4202 * after we successfully deleted the storage) */
4203 rc = unregisterWithVirtualBox(pllRegistriesThatNeedSaving);
4204 if (FAILED(rc))
4205 throw rc;
4206 // no longer need lock
4207 multilock.release();
4208
4209 if (aProgress != NULL)
4210 {
4211 /* use the existing progress object... */
4212 pProgress = *aProgress;
4213
4214 /* ...but create a new one if it is null */
4215 if (pProgress.isNull())
4216 {
4217 pProgress.createObject();
4218 rc = pProgress->init(m->pVirtualBox,
4219 static_cast<IMedium*>(this),
4220 BstrFmt(tr("Deleting medium storage unit '%s'"), m->strLocationFull.c_str()).raw(),
4221 FALSE /* aCancelable */);
4222 if (FAILED(rc))
4223 throw rc;
4224 }
4225 }
4226
4227 /* setup task object to carry out the operation sync/async */
4228 pTask = new Medium::DeleteTask(this, pProgress, pMediumLockList);
4229 rc = pTask->rc();
4230 AssertComRC(rc);
4231 if (FAILED(rc))
4232 throw rc;
4233 }
4234 catch (HRESULT aRC) { rc = aRC; }
4235
4236 if (SUCCEEDED(rc))
4237 {
4238 if (aWait)
4239 rc = runNow(pTask, NULL /* pfNeedsGlobalSaveSettings*/);
4240 else
4241 rc = startThread(pTask);
4242
4243 if (SUCCEEDED(rc) && aProgress != NULL)
4244 *aProgress = pProgress;
4245
4246 }
4247 else
4248 {
4249 if (pTask)
4250 delete pTask;
4251
4252 /* Undo deleting state if necessary. */
4253 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4254 /* Make sure that any error signalled by unmarkForDeletion() is not
4255 * ending up in the error list (if the caller uses MultiResult). It
4256 * usually is spurious, as in most cases the medium hasn't been marked
4257 * for deletion when the error was thrown above. */
4258 ErrorInfoKeeper eik;
4259 unmarkForDeletion();
4260 }
4261
4262 return rc;
4263}
4264
4265/**
4266 * Mark a medium for deletion.
4267 *
4268 * @note Caller must hold the write lock on this medium!
4269 */
4270HRESULT Medium::markForDeletion()
4271{
4272 ComAssertRet(this->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
4273 switch (m->state)
4274 {
4275 case MediumState_Created:
4276 case MediumState_Inaccessible:
4277 m->preLockState = m->state;
4278 m->state = MediumState_Deleting;
4279 return S_OK;
4280 default:
4281 return setStateError();
4282 }
4283}
4284
4285/**
4286 * Removes the "mark for deletion".
4287 *
4288 * @note Caller must hold the write lock on this medium!
4289 */
4290HRESULT Medium::unmarkForDeletion()
4291{
4292 ComAssertRet(this->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
4293 switch (m->state)
4294 {
4295 case MediumState_Deleting:
4296 m->state = m->preLockState;
4297 return S_OK;
4298 default:
4299 return setStateError();
4300 }
4301}
4302
4303/**
4304 * Mark a medium for deletion which is in locked state.
4305 *
4306 * @note Caller must hold the write lock on this medium!
4307 */
4308HRESULT Medium::markLockedForDeletion()
4309{
4310 ComAssertRet(this->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
4311 if ( ( m->state == MediumState_LockedRead
4312 || m->state == MediumState_LockedWrite)
4313 && m->preLockState == MediumState_Created)
4314 {
4315 m->preLockState = MediumState_Deleting;
4316 return S_OK;
4317 }
4318 else
4319 return setStateError();
4320}
4321
4322/**
4323 * Removes the "mark for deletion" for a medium in locked state.
4324 *
4325 * @note Caller must hold the write lock on this medium!
4326 */
4327HRESULT Medium::unmarkLockedForDeletion()
4328{
4329 ComAssertRet(this->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
4330 if ( ( m->state == MediumState_LockedRead
4331 || m->state == MediumState_LockedWrite)
4332 && m->preLockState == MediumState_Deleting)
4333 {
4334 m->preLockState = MediumState_Created;
4335 return S_OK;
4336 }
4337 else
4338 return setStateError();
4339}
4340
4341/**
4342 * Prepares this (source) medium, target medium and all intermediate media
4343 * for the merge operation.
4344 *
4345 * This method is to be called prior to calling the #mergeTo() to perform
4346 * necessary consistency checks and place involved media to appropriate
4347 * states. If #mergeTo() is not called or fails, the state modifications
4348 * performed by this method must be undone by #cancelMergeTo().
4349 *
4350 * See #mergeTo() for more information about merging.
4351 *
4352 * @param pTarget Target medium.
4353 * @param aMachineId Allowed machine attachment. NULL means do not check.
4354 * @param aSnapshotId Allowed snapshot attachment. NULL or empty UUID means
4355 * do not check.
4356 * @param fLockMedia Flag whether to lock the medium lock list or not.
4357 * If set to false and the medium lock list locking fails
4358 * later you must call #cancelMergeTo().
4359 * @param fMergeForward Resulting merge direction (out).
4360 * @param pParentForTarget New parent for target medium after merge (out).
4361 * @param aChildrenToReparent List of children of the source which will have
4362 * to be reparented to the target after merge (out).
4363 * @param aMediumLockList Medium locking information (out).
4364 *
4365 * @note Locks medium tree for reading. Locks this object, aTarget and all
4366 * intermediate media for writing.
4367 */
4368HRESULT Medium::prepareMergeTo(const ComObjPtr<Medium> &pTarget,
4369 const Guid *aMachineId,
4370 const Guid *aSnapshotId,
4371 bool fLockMedia,
4372 bool &fMergeForward,
4373 ComObjPtr<Medium> &pParentForTarget,
4374 MediaList &aChildrenToReparent,
4375 MediumLockList * &aMediumLockList)
4376{
4377 AssertReturn(pTarget != NULL, E_FAIL);
4378 AssertReturn(pTarget != this, E_FAIL);
4379
4380 AutoCaller autoCaller(this);
4381 AssertComRCReturnRC(autoCaller.rc());
4382
4383 AutoCaller targetCaller(pTarget);
4384 AssertComRCReturnRC(targetCaller.rc());
4385
4386 HRESULT rc = S_OK;
4387 fMergeForward = false;
4388 pParentForTarget.setNull();
4389 aChildrenToReparent.clear();
4390 Assert(aMediumLockList == NULL);
4391 aMediumLockList = NULL;
4392
4393 try
4394 {
4395 // locking: we need the tree lock first because we access parent pointers
4396 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4397
4398 /* more sanity checking and figuring out the merge direction */
4399 ComObjPtr<Medium> pMedium = getParent();
4400 while (!pMedium.isNull() && pMedium != pTarget)
4401 pMedium = pMedium->getParent();
4402 if (pMedium == pTarget)
4403 fMergeForward = false;
4404 else
4405 {
4406 pMedium = pTarget->getParent();
4407 while (!pMedium.isNull() && pMedium != this)
4408 pMedium = pMedium->getParent();
4409 if (pMedium == this)
4410 fMergeForward = true;
4411 else
4412 {
4413 Utf8Str tgtLoc;
4414 {
4415 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
4416 tgtLoc = pTarget->getLocationFull();
4417 }
4418
4419 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4420 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4421 tr("Media '%s' and '%s' are unrelated"),
4422 m->strLocationFull.c_str(), tgtLoc.c_str());
4423 }
4424 }
4425
4426 /* Build the lock list. */
4427 aMediumLockList = new MediumLockList();
4428 if (fMergeForward)
4429 rc = pTarget->createMediumLockList(true /* fFailIfInaccessible */,
4430 true /* fMediumLockWrite */,
4431 NULL,
4432 *aMediumLockList);
4433 else
4434 rc = createMediumLockList(true /* fFailIfInaccessible */,
4435 false /* fMediumLockWrite */,
4436 NULL,
4437 *aMediumLockList);
4438 if (FAILED(rc))
4439 throw rc;
4440
4441 /* Sanity checking, must be after lock list creation as it depends on
4442 * valid medium states. The medium objects must be accessible. Only
4443 * do this if immediate locking is requested, otherwise it fails when
4444 * we construct a medium lock list for an already running VM. Snapshot
4445 * deletion uses this to simplify its life. */
4446 if (fLockMedia)
4447 {
4448 {
4449 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4450 if (m->state != MediumState_Created)
4451 throw setStateError();
4452 }
4453 {
4454 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
4455 if (pTarget->m->state != MediumState_Created)
4456 throw pTarget->setStateError();
4457 }
4458 }
4459
4460 /* check medium attachment and other sanity conditions */
4461 if (fMergeForward)
4462 {
4463 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4464 if (getChildren().size() > 1)
4465 {
4466 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4467 tr("Medium '%s' involved in the merge operation has more than one child medium (%d)"),
4468 m->strLocationFull.c_str(), getChildren().size());
4469 }
4470 /* One backreference is only allowed if the machine ID is not empty
4471 * and it matches the machine the medium is attached to (including
4472 * the snapshot ID if not empty). */
4473 if ( m->backRefs.size() != 0
4474 && ( !aMachineId
4475 || m->backRefs.size() != 1
4476 || aMachineId->isEmpty()
4477 || *getFirstMachineBackrefId() != *aMachineId
4478 || ( (!aSnapshotId || !aSnapshotId->isEmpty())
4479 && *getFirstMachineBackrefSnapshotId() != *aSnapshotId)))
4480 throw setError(VBOX_E_OBJECT_IN_USE,
4481 tr("Medium '%s' is attached to %d virtual machines"),
4482 m->strLocationFull.c_str(), m->backRefs.size());
4483 if (m->type == MediumType_Immutable)
4484 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4485 tr("Medium '%s' is immutable"),
4486 m->strLocationFull.c_str());
4487 if (m->type == MediumType_MultiAttach)
4488 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4489 tr("Medium '%s' is multi-attach"),
4490 m->strLocationFull.c_str());
4491 }
4492 else
4493 {
4494 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
4495 if (pTarget->getChildren().size() > 1)
4496 {
4497 throw setError(VBOX_E_OBJECT_IN_USE,
4498 tr("Medium '%s' involved in the merge operation has more than one child medium (%d)"),
4499 pTarget->m->strLocationFull.c_str(),
4500 pTarget->getChildren().size());
4501 }
4502 if (pTarget->m->type == MediumType_Immutable)
4503 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4504 tr("Medium '%s' is immutable"),
4505 pTarget->m->strLocationFull.c_str());
4506 if (pTarget->m->type == MediumType_MultiAttach)
4507 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4508 tr("Medium '%s' is multi-attach"),
4509 pTarget->m->strLocationFull.c_str());
4510 }
4511 ComObjPtr<Medium> pLast(fMergeForward ? (Medium *)pTarget : this);
4512 ComObjPtr<Medium> pLastIntermediate = pLast->getParent();
4513 for (pLast = pLastIntermediate;
4514 !pLast.isNull() && pLast != pTarget && pLast != this;
4515 pLast = pLast->getParent())
4516 {
4517 AutoReadLock alock(pLast COMMA_LOCKVAL_SRC_POS);
4518 if (pLast->getChildren().size() > 1)
4519 {
4520 throw setError(VBOX_E_OBJECT_IN_USE,
4521 tr("Medium '%s' involved in the merge operation has more than one child medium (%d)"),
4522 pLast->m->strLocationFull.c_str(),
4523 pLast->getChildren().size());
4524 }
4525 if (pLast->m->backRefs.size() != 0)
4526 throw setError(VBOX_E_OBJECT_IN_USE,
4527 tr("Medium '%s' is attached to %d virtual machines"),
4528 pLast->m->strLocationFull.c_str(),
4529 pLast->m->backRefs.size());
4530
4531 }
4532
4533 /* Update medium states appropriately */
4534 if (m->state == MediumState_Created)
4535 {
4536 rc = markForDeletion();
4537 if (FAILED(rc))
4538 throw rc;
4539 }
4540 else
4541 {
4542 if (fLockMedia)
4543 throw setStateError();
4544 else if ( m->state == MediumState_LockedWrite
4545 || m->state == MediumState_LockedRead)
4546 {
4547 /* Either mark it for deletion in locked state or allow
4548 * others to have done so. */
4549 if (m->preLockState == MediumState_Created)
4550 markLockedForDeletion();
4551 else if (m->preLockState != MediumState_Deleting)
4552 throw setStateError();
4553 }
4554 else
4555 throw setStateError();
4556 }
4557
4558 if (fMergeForward)
4559 {
4560 /* we will need parent to reparent target */
4561 pParentForTarget = m->pParent;
4562 }
4563 else
4564 {
4565 /* we will need to reparent children of the source */
4566 for (MediaList::const_iterator it = getChildren().begin();
4567 it != getChildren().end();
4568 ++it)
4569 {
4570 pMedium = *it;
4571 if (fLockMedia)
4572 {
4573 rc = pMedium->LockWrite(NULL);
4574 if (FAILED(rc))
4575 throw rc;
4576 }
4577
4578 aChildrenToReparent.push_back(pMedium);
4579 }
4580 }
4581 for (pLast = pLastIntermediate;
4582 !pLast.isNull() && pLast != pTarget && pLast != this;
4583 pLast = pLast->getParent())
4584 {
4585 AutoWriteLock alock(pLast COMMA_LOCKVAL_SRC_POS);
4586 if (pLast->m->state == MediumState_Created)
4587 {
4588 rc = pLast->markForDeletion();
4589 if (FAILED(rc))
4590 throw rc;
4591 }
4592 else
4593 throw pLast->setStateError();
4594 }
4595
4596 /* Tweak the lock list in the backward merge case, as the target
4597 * isn't marked to be locked for writing yet. */
4598 if (!fMergeForward)
4599 {
4600 MediumLockList::Base::iterator lockListBegin =
4601 aMediumLockList->GetBegin();
4602 MediumLockList::Base::iterator lockListEnd =
4603 aMediumLockList->GetEnd();
4604 lockListEnd--;
4605 for (MediumLockList::Base::iterator it = lockListBegin;
4606 it != lockListEnd;
4607 ++it)
4608 {
4609 MediumLock &mediumLock = *it;
4610 if (mediumLock.GetMedium() == pTarget)
4611 {
4612 HRESULT rc2 = mediumLock.UpdateLock(true);
4613 AssertComRC(rc2);
4614 break;
4615 }
4616 }
4617 }
4618
4619 if (fLockMedia)
4620 {
4621 rc = aMediumLockList->Lock();
4622 if (FAILED(rc))
4623 {
4624 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
4625 throw setError(rc,
4626 tr("Failed to lock media when merging to '%s'"),
4627 pTarget->getLocationFull().c_str());
4628 }
4629 }
4630 }
4631 catch (HRESULT aRC) { rc = aRC; }
4632
4633 if (FAILED(rc))
4634 {
4635 delete aMediumLockList;
4636 aMediumLockList = NULL;
4637 }
4638
4639 return rc;
4640}
4641
4642/**
4643 * Merges this medium to the specified medium which must be either its
4644 * direct ancestor or descendant.
4645 *
4646 * Given this medium is SOURCE and the specified medium is TARGET, we will
4647 * get two variants of the merge operation:
4648 *
4649 * forward merge
4650 * ------------------------->
4651 * [Extra] <- SOURCE <- Intermediate <- TARGET
4652 * Any Del Del LockWr
4653 *
4654 *
4655 * backward merge
4656 * <-------------------------
4657 * TARGET <- Intermediate <- SOURCE <- [Extra]
4658 * LockWr Del Del LockWr
4659 *
4660 * Each diagram shows the involved media on the media chain where
4661 * SOURCE and TARGET belong. Under each medium there is a state value which
4662 * the medium must have at a time of the mergeTo() call.
4663 *
4664 * The media in the square braces may be absent (e.g. when the forward
4665 * operation takes place and SOURCE is the base medium, or when the backward
4666 * merge operation takes place and TARGET is the last child in the chain) but if
4667 * they present they are involved too as shown.
4668 *
4669 * Neither the source medium nor intermediate media may be attached to
4670 * any VM directly or in the snapshot, otherwise this method will assert.
4671 *
4672 * The #prepareMergeTo() method must be called prior to this method to place all
4673 * involved to necessary states and perform other consistency checks.
4674 *
4675 * If @a aWait is @c true then this method will perform the operation on the
4676 * calling thread and will not return to the caller until the operation is
4677 * completed. When this method succeeds, all intermediate medium objects in
4678 * the chain will be uninitialized, the state of the target medium (and all
4679 * involved extra media) will be restored. @a aMediumLockList will not be
4680 * deleted, whether the operation is successful or not. The caller has to do
4681 * this if appropriate. Note that this (source) medium is not uninitialized
4682 * because of possible AutoCaller instances held by the caller of this method
4683 * on the current thread. It's therefore the responsibility of the caller to
4684 * call Medium::uninit() after releasing all callers.
4685 *
4686 * If @a aWait is @c false then this method will create a thread to perform the
4687 * operation asynchronously and will return immediately. If the operation
4688 * succeeds, the thread will uninitialize the source medium object and all
4689 * intermediate medium objects in the chain, reset the state of the target
4690 * medium (and all involved extra media) and delete @a aMediumLockList.
4691 * If the operation fails, the thread will only reset the states of all
4692 * involved media and delete @a aMediumLockList.
4693 *
4694 * When this method fails (regardless of the @a aWait mode), it is a caller's
4695 * responsibility to undo state changes and delete @a aMediumLockList using
4696 * #cancelMergeTo().
4697 *
4698 * If @a aProgress is not NULL but the object it points to is @c null then a new
4699 * progress object will be created and assigned to @a *aProgress on success,
4700 * otherwise the existing progress object is used. If Progress is NULL, then no
4701 * progress object is created/used at all. Note that @a aProgress cannot be
4702 * NULL when @a aWait is @c false (this method will assert in this case).
4703 *
4704 * @param pTarget Target medium.
4705 * @param fMergeForward Merge direction.
4706 * @param pParentForTarget New parent for target medium after merge.
4707 * @param aChildrenToReparent List of children of the source which will have
4708 * to be reparented to the target after merge.
4709 * @param aMediumLockList Medium locking information.
4710 * @param aProgress Where to find/store a Progress object to track operation
4711 * completion.
4712 * @param aWait @c true if this method should block instead of creating
4713 * an asynchronous thread.
4714 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
4715 * by this function if the caller should invoke VirtualBox::saveRegistries() because the global settings have changed.
4716 * This only works in "wait" mode; otherwise saveRegistries gets called automatically by the thread that was created,
4717 * and this parameter is ignored.
4718 *
4719 * @note Locks the tree lock for writing. Locks the media from the chain
4720 * for writing.
4721 */
4722HRESULT Medium::mergeTo(const ComObjPtr<Medium> &pTarget,
4723 bool fMergeForward,
4724 const ComObjPtr<Medium> &pParentForTarget,
4725 const MediaList &aChildrenToReparent,
4726 MediumLockList *aMediumLockList,
4727 ComObjPtr <Progress> *aProgress,
4728 bool aWait,
4729 GuidList *pllRegistriesThatNeedSaving)
4730{
4731 AssertReturn(pTarget != NULL, E_FAIL);
4732 AssertReturn(pTarget != this, E_FAIL);
4733 AssertReturn(aMediumLockList != NULL, E_FAIL);
4734 AssertReturn(aProgress != NULL || aWait == true, E_FAIL);
4735
4736 AutoCaller autoCaller(this);
4737 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4738
4739 AutoCaller targetCaller(pTarget);
4740 AssertComRCReturnRC(targetCaller.rc());
4741
4742 HRESULT rc = S_OK;
4743 ComObjPtr <Progress> pProgress;
4744 Medium::Task *pTask = NULL;
4745
4746 try
4747 {
4748 if (aProgress != NULL)
4749 {
4750 /* use the existing progress object... */
4751 pProgress = *aProgress;
4752
4753 /* ...but create a new one if it is null */
4754 if (pProgress.isNull())
4755 {
4756 Utf8Str tgtName;
4757 {
4758 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
4759 tgtName = pTarget->getName();
4760 }
4761
4762 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4763
4764 pProgress.createObject();
4765 rc = pProgress->init(m->pVirtualBox,
4766 static_cast<IMedium*>(this),
4767 BstrFmt(tr("Merging medium '%s' to '%s'"),
4768 getName().c_str(),
4769 tgtName.c_str()).raw(),
4770 TRUE /* aCancelable */);
4771 if (FAILED(rc))
4772 throw rc;
4773 }
4774 }
4775
4776 /* setup task object to carry out the operation sync/async */
4777 pTask = new Medium::MergeTask(this, pTarget, fMergeForward,
4778 pParentForTarget, aChildrenToReparent,
4779 pProgress, aMediumLockList,
4780 aWait /* fKeepMediumLockList */);
4781 rc = pTask->rc();
4782 AssertComRC(rc);
4783 if (FAILED(rc))
4784 throw rc;
4785 }
4786 catch (HRESULT aRC) { rc = aRC; }
4787
4788 if (SUCCEEDED(rc))
4789 {
4790 if (aWait)
4791 rc = runNow(pTask, pllRegistriesThatNeedSaving);
4792 else
4793 rc = startThread(pTask);
4794
4795 if (SUCCEEDED(rc) && aProgress != NULL)
4796 *aProgress = pProgress;
4797 }
4798 else if (pTask != NULL)
4799 delete pTask;
4800
4801 return rc;
4802}
4803
4804/**
4805 * Undoes what #prepareMergeTo() did. Must be called if #mergeTo() is not
4806 * called or fails. Frees memory occupied by @a aMediumLockList and unlocks
4807 * the medium objects in @a aChildrenToReparent.
4808 *
4809 * @param aChildrenToReparent List of children of the source which will have
4810 * to be reparented to the target after merge.
4811 * @param aMediumLockList Medium locking information.
4812 *
4813 * @note Locks the media from the chain for writing.
4814 */
4815void Medium::cancelMergeTo(const MediaList &aChildrenToReparent,
4816 MediumLockList *aMediumLockList)
4817{
4818 AutoCaller autoCaller(this);
4819 AssertComRCReturnVoid(autoCaller.rc());
4820
4821 AssertReturnVoid(aMediumLockList != NULL);
4822
4823 /* Revert media marked for deletion to previous state. */
4824 HRESULT rc;
4825 MediumLockList::Base::const_iterator mediumListBegin =
4826 aMediumLockList->GetBegin();
4827 MediumLockList::Base::const_iterator mediumListEnd =
4828 aMediumLockList->GetEnd();
4829 for (MediumLockList::Base::const_iterator it = mediumListBegin;
4830 it != mediumListEnd;
4831 ++it)
4832 {
4833 const MediumLock &mediumLock = *it;
4834 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
4835 AutoWriteLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
4836
4837 if (pMedium->m->state == MediumState_Deleting)
4838 {
4839 rc = pMedium->unmarkForDeletion();
4840 AssertComRC(rc);
4841 }
4842 }
4843
4844 /* the destructor will do the work */
4845 delete aMediumLockList;
4846
4847 /* unlock the children which had to be reparented */
4848 for (MediaList::const_iterator it = aChildrenToReparent.begin();
4849 it != aChildrenToReparent.end();
4850 ++it)
4851 {
4852 const ComObjPtr<Medium> &pMedium = *it;
4853
4854 AutoWriteLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
4855 pMedium->UnlockWrite(NULL);
4856 }
4857}
4858
4859/**
4860 * Fix the parent UUID of all children to point to this medium as their
4861 * parent.
4862 */
4863HRESULT Medium::fixParentUuidOfChildren(const MediaList &childrenToReparent)
4864{
4865 MediumLockList mediumLockList;
4866 HRESULT rc = createMediumLockList(true /* fFailIfInaccessible */,
4867 false /* fMediumLockWrite */,
4868 this,
4869 mediumLockList);
4870 AssertComRCReturnRC(rc);
4871
4872 try
4873 {
4874 PVBOXHDD hdd;
4875 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
4876 ComAssertRCThrow(vrc, E_FAIL);
4877
4878 try
4879 {
4880 MediumLockList::Base::iterator lockListBegin =
4881 mediumLockList.GetBegin();
4882 MediumLockList::Base::iterator lockListEnd =
4883 mediumLockList.GetEnd();
4884 for (MediumLockList::Base::iterator it = lockListBegin;
4885 it != lockListEnd;
4886 ++it)
4887 {
4888 MediumLock &mediumLock = *it;
4889 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
4890 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
4891
4892 // open the medium
4893 vrc = VDOpen(hdd,
4894 pMedium->m->strFormat.c_str(),
4895 pMedium->m->strLocationFull.c_str(),
4896 VD_OPEN_FLAGS_READONLY,
4897 pMedium->m->vdImageIfaces);
4898 if (RT_FAILURE(vrc))
4899 throw vrc;
4900 }
4901
4902 for (MediaList::const_iterator it = childrenToReparent.begin();
4903 it != childrenToReparent.end();
4904 ++it)
4905 {
4906 /* VD_OPEN_FLAGS_INFO since UUID is wrong yet */
4907 vrc = VDOpen(hdd,
4908 (*it)->m->strFormat.c_str(),
4909 (*it)->m->strLocationFull.c_str(),
4910 VD_OPEN_FLAGS_INFO,
4911 (*it)->m->vdImageIfaces);
4912 if (RT_FAILURE(vrc))
4913 throw vrc;
4914
4915 vrc = VDSetParentUuid(hdd, VD_LAST_IMAGE, m->id.raw());
4916 if (RT_FAILURE(vrc))
4917 throw vrc;
4918
4919 vrc = VDClose(hdd, false /* fDelete */);
4920 if (RT_FAILURE(vrc))
4921 throw vrc;
4922
4923 (*it)->UnlockWrite(NULL);
4924 }
4925 }
4926 catch (HRESULT aRC) { rc = aRC; }
4927 catch (int aVRC)
4928 {
4929 rc = setError(E_FAIL,
4930 tr("Could not update medium UUID references to parent '%s' (%s)"),
4931 m->strLocationFull.c_str(),
4932 vdError(aVRC).c_str());
4933 }
4934
4935 VDDestroy(hdd);
4936 }
4937 catch (HRESULT aRC) { rc = aRC; }
4938
4939 return rc;
4940}
4941
4942/**
4943 * Used by IAppliance to export disk images.
4944 *
4945 * @param aFilename Filename to create (UTF8).
4946 * @param aFormat Medium format for creating @a aFilename.
4947 * @param aVariant Which exact image format variant to use
4948 * for the destination image.
4949 * @param aVDImageIOCallbacks Pointer to the callback table for a
4950 * VDINTERFACEIO interface. May be NULL.
4951 * @param aVDImageIOUser Opaque data for the callbacks.
4952 * @param aProgress Progress object to use.
4953 * @return
4954 * @note The source format is defined by the Medium instance.
4955 */
4956HRESULT Medium::exportFile(const char *aFilename,
4957 const ComObjPtr<MediumFormat> &aFormat,
4958 MediumVariant_T aVariant,
4959 PVDINTERFACEIO aVDImageIOIf, void *aVDImageIOUser,
4960 const ComObjPtr<Progress> &aProgress)
4961{
4962 AssertPtrReturn(aFilename, E_INVALIDARG);
4963 AssertReturn(!aFormat.isNull(), E_INVALIDARG);
4964 AssertReturn(!aProgress.isNull(), E_INVALIDARG);
4965
4966 AutoCaller autoCaller(this);
4967 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4968
4969 HRESULT rc = S_OK;
4970 Medium::Task *pTask = NULL;
4971
4972 try
4973 {
4974 // locking: we need the tree lock first because we access parent pointers
4975 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4976 // and we need to write-lock the media involved
4977 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4978
4979 /* Build the source lock list. */
4980 MediumLockList *pSourceMediumLockList(new MediumLockList());
4981 rc = createMediumLockList(true /* fFailIfInaccessible */,
4982 false /* fMediumLockWrite */,
4983 NULL,
4984 *pSourceMediumLockList);
4985 if (FAILED(rc))
4986 {
4987 delete pSourceMediumLockList;
4988 throw rc;
4989 }
4990
4991 rc = pSourceMediumLockList->Lock();
4992 if (FAILED(rc))
4993 {
4994 delete pSourceMediumLockList;
4995 throw setError(rc,
4996 tr("Failed to lock source media '%s'"),
4997 getLocationFull().c_str());
4998 }
4999
5000 /* setup task object to carry out the operation asynchronously */
5001 pTask = new Medium::ExportTask(this, aProgress, aFilename, aFormat,
5002 aVariant, aVDImageIOIf,
5003 aVDImageIOUser, pSourceMediumLockList);
5004 rc = pTask->rc();
5005 AssertComRC(rc);
5006 if (FAILED(rc))
5007 throw rc;
5008 }
5009 catch (HRESULT aRC) { rc = aRC; }
5010
5011 if (SUCCEEDED(rc))
5012 rc = startThread(pTask);
5013 else if (pTask != NULL)
5014 delete pTask;
5015
5016 return rc;
5017}
5018
5019/**
5020 * Used by IAppliance to import disk images.
5021 *
5022 * @param aFilename Filename to read (UTF8).
5023 * @param aFormat Medium format for reading @a aFilename.
5024 * @param aVariant Which exact image format variant to use
5025 * for the destination image.
5026 * @param aVDImageIOCallbacks Pointer to the callback table for a
5027 * VDINTERFACEIO interface. May be NULL.
5028 * @param aVDImageIOUser Opaque data for the callbacks.
5029 * @param aParent Parent medium. May be NULL.
5030 * @param aProgress Progress object to use.
5031 * @return
5032 * @note The destination format is defined by the Medium instance.
5033 */
5034HRESULT Medium::importFile(const char *aFilename,
5035 const ComObjPtr<MediumFormat> &aFormat,
5036 MediumVariant_T aVariant,
5037 PVDINTERFACEIO aVDImageIOIf, void *aVDImageIOUser,
5038 const ComObjPtr<Medium> &aParent,
5039 const ComObjPtr<Progress> &aProgress)
5040{
5041 AssertPtrReturn(aFilename, E_INVALIDARG);
5042 AssertReturn(!aFormat.isNull(), E_INVALIDARG);
5043 AssertReturn(!aProgress.isNull(), E_INVALIDARG);
5044
5045 AutoCaller autoCaller(this);
5046 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5047
5048 HRESULT rc = S_OK;
5049 Medium::Task *pTask = NULL;
5050
5051 try
5052 {
5053 // locking: we need the tree lock first because we access parent pointers
5054 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5055 // and we need to write-lock the media involved
5056 AutoMultiWriteLock2 alock(this, aParent COMMA_LOCKVAL_SRC_POS);
5057
5058 if ( m->state != MediumState_NotCreated
5059 && m->state != MediumState_Created)
5060 throw setStateError();
5061
5062 /* Build the target lock list. */
5063 MediumLockList *pTargetMediumLockList(new MediumLockList());
5064 rc = createMediumLockList(true /* fFailIfInaccessible */,
5065 true /* fMediumLockWrite */,
5066 aParent,
5067 *pTargetMediumLockList);
5068 if (FAILED(rc))
5069 {
5070 delete pTargetMediumLockList;
5071 throw rc;
5072 }
5073
5074 rc = pTargetMediumLockList->Lock();
5075 if (FAILED(rc))
5076 {
5077 delete pTargetMediumLockList;
5078 throw setError(rc,
5079 tr("Failed to lock target media '%s'"),
5080 getLocationFull().c_str());
5081 }
5082
5083 /* setup task object to carry out the operation asynchronously */
5084 pTask = new Medium::ImportTask(this, aProgress, aFilename, aFormat,
5085 aVariant, aVDImageIOIf,
5086 aVDImageIOUser, aParent,
5087 pTargetMediumLockList);
5088 rc = pTask->rc();
5089 AssertComRC(rc);
5090 if (FAILED(rc))
5091 throw rc;
5092
5093 if (m->state == MediumState_NotCreated)
5094 m->state = MediumState_Creating;
5095 }
5096 catch (HRESULT aRC) { rc = aRC; }
5097
5098 if (SUCCEEDED(rc))
5099 rc = startThread(pTask);
5100 else if (pTask != NULL)
5101 delete pTask;
5102
5103 return rc;
5104}
5105
5106/**
5107 * Internal version of the public CloneTo API which allows to enable certain
5108 * optimizations to improve speed during VM cloning.
5109 *
5110 * @param aTarget Target medium
5111 * @param aVariant Which exact image format variant to use
5112 * for the destination image.
5113 * @param aParent Parent medium. May be NULL.
5114 * @param aProgress Progress object to use.
5115 * @param idxSrcImageSame The last image in the source chain which has the
5116 * same content as the given image in the destination
5117 * chain. Use UINT32_MAX to disable this optimization.
5118 * @param idxDstImageSame The last image in the destination chain which has the
5119 * same content as the given image in the source chain.
5120 * Use UINT32_MAX to disable this optimization.
5121 * @return
5122 */
5123HRESULT Medium::cloneToEx(const ComObjPtr<Medium> &aTarget, ULONG aVariant,
5124 const ComObjPtr<Medium> &aParent, IProgress **aProgress,
5125 uint32_t idxSrcImageSame, uint32_t idxDstImageSame)
5126{
5127 CheckComArgNotNull(aTarget);
5128 CheckComArgOutPointerValid(aProgress);
5129 ComAssertRet(aTarget != this, E_INVALIDARG);
5130
5131 AutoCaller autoCaller(this);
5132 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5133
5134 HRESULT rc = S_OK;
5135 ComObjPtr<Progress> pProgress;
5136 Medium::Task *pTask = NULL;
5137
5138 try
5139 {
5140 // locking: we need the tree lock first because we access parent pointers
5141 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5142 // and we need to write-lock the media involved
5143 AutoMultiWriteLock3 alock(this, aTarget, aParent COMMA_LOCKVAL_SRC_POS);
5144
5145 if ( aTarget->m->state != MediumState_NotCreated
5146 && aTarget->m->state != MediumState_Created)
5147 throw aTarget->setStateError();
5148
5149 /* Build the source lock list. */
5150 MediumLockList *pSourceMediumLockList(new MediumLockList());
5151 rc = createMediumLockList(true /* fFailIfInaccessible */,
5152 false /* fMediumLockWrite */,
5153 NULL,
5154 *pSourceMediumLockList);
5155 if (FAILED(rc))
5156 {
5157 delete pSourceMediumLockList;
5158 throw rc;
5159 }
5160
5161 /* Build the target lock list (including the to-be parent chain). */
5162 MediumLockList *pTargetMediumLockList(new MediumLockList());
5163 rc = aTarget->createMediumLockList(true /* fFailIfInaccessible */,
5164 true /* fMediumLockWrite */,
5165 aParent,
5166 *pTargetMediumLockList);
5167 if (FAILED(rc))
5168 {
5169 delete pSourceMediumLockList;
5170 delete pTargetMediumLockList;
5171 throw rc;
5172 }
5173
5174 rc = pSourceMediumLockList->Lock();
5175 if (FAILED(rc))
5176 {
5177 delete pSourceMediumLockList;
5178 delete pTargetMediumLockList;
5179 throw setError(rc,
5180 tr("Failed to lock source media '%s'"),
5181 getLocationFull().c_str());
5182 }
5183 rc = pTargetMediumLockList->Lock();
5184 if (FAILED(rc))
5185 {
5186 delete pSourceMediumLockList;
5187 delete pTargetMediumLockList;
5188 throw setError(rc,
5189 tr("Failed to lock target media '%s'"),
5190 aTarget->getLocationFull().c_str());
5191 }
5192
5193 pProgress.createObject();
5194 rc = pProgress->init(m->pVirtualBox,
5195 static_cast <IMedium *>(this),
5196 BstrFmt(tr("Creating clone medium '%s'"), aTarget->m->strLocationFull.c_str()).raw(),
5197 TRUE /* aCancelable */);
5198 if (FAILED(rc))
5199 {
5200 delete pSourceMediumLockList;
5201 delete pTargetMediumLockList;
5202 throw rc;
5203 }
5204
5205 /* setup task object to carry out the operation asynchronously */
5206 pTask = new Medium::CloneTask(this, pProgress, aTarget,
5207 (MediumVariant_T)aVariant,
5208 aParent, idxSrcImageSame,
5209 idxDstImageSame, pSourceMediumLockList,
5210 pTargetMediumLockList);
5211 rc = pTask->rc();
5212 AssertComRC(rc);
5213 if (FAILED(rc))
5214 throw rc;
5215
5216 if (aTarget->m->state == MediumState_NotCreated)
5217 aTarget->m->state = MediumState_Creating;
5218 }
5219 catch (HRESULT aRC) { rc = aRC; }
5220
5221 if (SUCCEEDED(rc))
5222 {
5223 rc = startThread(pTask);
5224
5225 if (SUCCEEDED(rc))
5226 pProgress.queryInterfaceTo(aProgress);
5227 }
5228 else if (pTask != NULL)
5229 delete pTask;
5230
5231 return rc;
5232}
5233
5234////////////////////////////////////////////////////////////////////////////////
5235//
5236// Private methods
5237//
5238////////////////////////////////////////////////////////////////////////////////
5239
5240/**
5241 * Queries information from the medium.
5242 *
5243 * As a result of this call, the accessibility state and data members such as
5244 * size and description will be updated with the current information.
5245 *
5246 * @note This method may block during a system I/O call that checks storage
5247 * accessibility.
5248 *
5249 * @note Locks medium tree for reading and writing (for new diff media checked
5250 * for the first time). Locks mParent for reading. Locks this object for
5251 * writing.
5252 *
5253 * @param fSetImageId Whether to reset the UUID contained in the image file to the UUID in the medium instance data (see SetIDs())
5254 * @param fSetParentId Whether to reset the parent UUID contained in the image file to the parent UUID in the medium instance data (see SetIDs())
5255 * @return
5256 */
5257HRESULT Medium::queryInfo(bool fSetImageId, bool fSetParentId)
5258{
5259 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5260
5261 if ( m->state != MediumState_Created
5262 && m->state != MediumState_Inaccessible
5263 && m->state != MediumState_LockedRead)
5264 return E_FAIL;
5265
5266 HRESULT rc = S_OK;
5267
5268 int vrc = VINF_SUCCESS;
5269
5270 /* check if a blocking queryInfo() call is in progress on some other thread,
5271 * and wait for it to finish if so instead of querying data ourselves */
5272 if (m->queryInfoRunning)
5273 {
5274 Assert( m->state == MediumState_LockedRead
5275 || m->state == MediumState_LockedWrite);
5276
5277 alock.leave();
5278 vrc = RTSemEventMultiWait(m->queryInfoSem, RT_INDEFINITE_WAIT);
5279 alock.enter();
5280
5281 AssertRC(vrc);
5282
5283 return S_OK;
5284 }
5285
5286 bool success = false;
5287 Utf8Str lastAccessError;
5288
5289 /* are we dealing with a new medium constructed using the existing
5290 * location? */
5291 bool isImport = m->id.isEmpty();
5292 unsigned uOpenFlags = VD_OPEN_FLAGS_INFO;
5293
5294 /* Note that we don't use VD_OPEN_FLAGS_READONLY when opening new
5295 * media because that would prevent necessary modifications
5296 * when opening media of some third-party formats for the first
5297 * time in VirtualBox (such as VMDK for which VDOpen() needs to
5298 * generate an UUID if it is missing) */
5299 if ( m->hddOpenMode == OpenReadOnly
5300 || m->type == MediumType_Readonly
5301 || (!isImport && !fSetImageId && !fSetParentId)
5302 )
5303 uOpenFlags |= VD_OPEN_FLAGS_READONLY;
5304
5305 /* Open shareable medium with the appropriate flags */
5306 if (m->type == MediumType_Shareable)
5307 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
5308
5309 /* Lock the medium, which makes the behavior much more consistent */
5310 if (uOpenFlags & (VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_SHAREABLE))
5311 rc = LockRead(NULL);
5312 else
5313 rc = LockWrite(NULL);
5314 if (FAILED(rc)) return rc;
5315
5316 /* Copies of the input state fields which are not read-only,
5317 * as we're dropping the lock. CAUTION: be extremely careful what
5318 * you do with the contents of this medium object, as you will
5319 * create races if there are concurrent changes. */
5320 Utf8Str format(m->strFormat);
5321 Utf8Str location(m->strLocationFull);
5322 ComObjPtr<MediumFormat> formatObj = m->formatObj;
5323
5324 /* "Output" values which can't be set because the lock isn't held
5325 * at the time the values are determined. */
5326 Guid mediumId = m->id;
5327 uint64_t mediumSize = 0;
5328 uint64_t mediumLogicalSize = 0;
5329
5330 /* Flag whether a base image has a non-zero parent UUID and thus
5331 * need repairing after it was closed again. */
5332 bool fRepairImageZeroParentUuid = false;
5333
5334 /* leave the lock before a lengthy operation */
5335 vrc = RTSemEventMultiReset(m->queryInfoSem);
5336 AssertRCReturn(vrc, E_FAIL);
5337 m->queryInfoRunning = true;
5338 alock.leave();
5339
5340 try
5341 {
5342 /* skip accessibility checks for host drives */
5343 if (m->hostDrive)
5344 {
5345 success = true;
5346 throw S_OK;
5347 }
5348
5349 PVBOXHDD hdd;
5350 vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
5351 ComAssertRCThrow(vrc, E_FAIL);
5352
5353 try
5354 {
5355 /** @todo This kind of opening of media is assuming that diff
5356 * media can be opened as base media. Should be documented that
5357 * it must work for all medium format backends. */
5358 vrc = VDOpen(hdd,
5359 format.c_str(),
5360 location.c_str(),
5361 uOpenFlags,
5362 m->vdImageIfaces);
5363 if (RT_FAILURE(vrc))
5364 {
5365 lastAccessError = Utf8StrFmt(tr("Could not open the medium '%s'%s"),
5366 location.c_str(), vdError(vrc).c_str());
5367 throw S_OK;
5368 }
5369
5370 if (formatObj->getCapabilities() & MediumFormatCapabilities_Uuid)
5371 {
5372 /* Modify the UUIDs if necessary. The associated fields are
5373 * not modified by other code, so no need to copy. */
5374 if (fSetImageId)
5375 {
5376 vrc = VDSetUuid(hdd, 0, m->uuidImage.raw());
5377 ComAssertRCThrow(vrc, E_FAIL);
5378 mediumId = m->uuidImage;
5379 }
5380 if (fSetParentId)
5381 {
5382 vrc = VDSetParentUuid(hdd, 0, m->uuidParentImage.raw());
5383 ComAssertRCThrow(vrc, E_FAIL);
5384 }
5385 /* zap the information, these are no long-term members */
5386 unconst(m->uuidImage).clear();
5387 unconst(m->uuidParentImage).clear();
5388
5389 /* check the UUID */
5390 RTUUID uuid;
5391 vrc = VDGetUuid(hdd, 0, &uuid);
5392 ComAssertRCThrow(vrc, E_FAIL);
5393
5394 if (isImport)
5395 {
5396 mediumId = uuid;
5397
5398 if (mediumId.isEmpty() && (m->hddOpenMode == OpenReadOnly))
5399 // only when importing a VDMK that has no UUID, create one in memory
5400 mediumId.create();
5401 }
5402 else
5403 {
5404 Assert(!mediumId.isEmpty());
5405
5406 if (mediumId != uuid)
5407 {
5408 /** @todo r=klaus this always refers to VirtualBox.xml as the medium registry, even for new VMs */
5409 lastAccessError = Utf8StrFmt(
5410 tr("UUID {%RTuuid} of the medium '%s' does not match the value {%RTuuid} stored in the media registry ('%s')"),
5411 &uuid,
5412 location.c_str(),
5413 mediumId.raw(),
5414 m->pVirtualBox->settingsFilePath().c_str());
5415 throw S_OK;
5416 }
5417 }
5418 }
5419 else
5420 {
5421 /* the backend does not support storing UUIDs within the
5422 * underlying storage so use what we store in XML */
5423
5424 if (fSetImageId)
5425 {
5426 /* set the UUID if an API client wants to change it */
5427 mediumId = m->uuidImage;
5428 }
5429 else if (isImport)
5430 {
5431 /* generate an UUID for an imported UUID-less medium */
5432 mediumId.create();
5433 }
5434 }
5435
5436 /* get the medium variant */
5437 unsigned uImageFlags;
5438 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
5439 ComAssertRCThrow(vrc, E_FAIL);
5440 m->variant = (MediumVariant_T)uImageFlags;
5441
5442 /* check/get the parent uuid and update corresponding state */
5443 if (uImageFlags & VD_IMAGE_FLAGS_DIFF)
5444 {
5445 RTUUID parentId;
5446 vrc = VDGetParentUuid(hdd, 0, &parentId);
5447 ComAssertRCThrow(vrc, E_FAIL);
5448
5449 /* streamOptimized VMDK images are only accepted as base
5450 * images, as this allows automatic repair of OVF appliances.
5451 * Since such images don't support random writes they will not
5452 * be created for diff images. Only an overly smart user might
5453 * manually create this case. Too bad for him. */
5454 if ( isImport
5455 && !(uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED))
5456 {
5457 /* the parent must be known to us. Note that we freely
5458 * call locking methods of mVirtualBox and parent, as all
5459 * relevant locks must be already held. There may be no
5460 * concurrent access to the just opened medium on other
5461 * threads yet (and init() will fail if this method reports
5462 * MediumState_Inaccessible) */
5463
5464 Guid id = parentId;
5465 ComObjPtr<Medium> pParent;
5466 rc = m->pVirtualBox->findHardDiskById(id, false /* aSetError */, &pParent);
5467 if (FAILED(rc))
5468 {
5469 lastAccessError = Utf8StrFmt(
5470 tr("Parent medium with UUID {%RTuuid} of the medium '%s' is not found in the media registry ('%s')"),
5471 &parentId, location.c_str(),
5472 m->pVirtualBox->settingsFilePath().c_str());
5473 throw S_OK;
5474 }
5475
5476 /* we set mParent & children() */
5477 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5478
5479 Assert(m->pParent.isNull());
5480 m->pParent = pParent;
5481 m->pParent->m->llChildren.push_back(this);
5482 }
5483 else
5484 {
5485 /* we access mParent */
5486 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5487
5488 /* check that parent UUIDs match. Note that there's no need
5489 * for the parent's AutoCaller (our lifetime is bound to
5490 * it) */
5491
5492 if (m->pParent.isNull())
5493 {
5494 /* Due to a bug in VDCopy() in VirtualBox 3.0.0-3.0.14
5495 * and 3.1.0-3.1.8 there are base images out there
5496 * which have a non-zero parent UUID. No point in
5497 * complaining about them, instead automatically
5498 * repair the problem. Later we can bring back the
5499 * error message, but we should wait until really
5500 * most users have repaired their images, either with
5501 * VBoxFixHdd or this way. */
5502#if 1
5503 fRepairImageZeroParentUuid = true;
5504#else /* 0 */
5505 lastAccessError = Utf8StrFmt(
5506 tr("Medium type of '%s' is differencing but it is not associated with any parent medium in the media registry ('%s')"),
5507 location.c_str(),
5508 m->pVirtualBox->settingsFilePath().c_str());
5509 throw S_OK;
5510#endif /* 0 */
5511 }
5512
5513 AutoReadLock parentLock(m->pParent COMMA_LOCKVAL_SRC_POS);
5514 if ( !fRepairImageZeroParentUuid
5515 && m->pParent->getState() != MediumState_Inaccessible
5516 && m->pParent->getId() != parentId)
5517 {
5518 /** @todo r=klaus this always refers to VirtualBox.xml as the medium registry, even for new VMs */
5519 lastAccessError = Utf8StrFmt(
5520 tr("Parent UUID {%RTuuid} of the medium '%s' does not match UUID {%RTuuid} of its parent medium stored in the media registry ('%s')"),
5521 &parentId, location.c_str(),
5522 m->pParent->getId().raw(),
5523 m->pVirtualBox->settingsFilePath().c_str());
5524 throw S_OK;
5525 }
5526
5527 /// @todo NEWMEDIA what to do if the parent is not
5528 /// accessible while the diff is? Probably nothing. The
5529 /// real code will detect the mismatch anyway.
5530 }
5531 }
5532
5533 mediumSize = VDGetFileSize(hdd, 0);
5534 mediumLogicalSize = VDGetSize(hdd, 0);
5535
5536 success = true;
5537 }
5538 catch (HRESULT aRC)
5539 {
5540 rc = aRC;
5541 }
5542
5543 VDDestroy(hdd);
5544 }
5545 catch (HRESULT aRC)
5546 {
5547 rc = aRC;
5548 }
5549
5550 alock.enter();
5551
5552 if (isImport || fSetImageId)
5553 unconst(m->id) = mediumId;
5554
5555 if (success)
5556 {
5557 m->size = mediumSize;
5558 m->logicalSize = mediumLogicalSize;
5559 m->strLastAccessError.setNull();
5560 }
5561 else
5562 {
5563 m->strLastAccessError = lastAccessError;
5564 LogWarningFunc(("'%s' is not accessible (error='%s', rc=%Rhrc, vrc=%Rrc)\n",
5565 location.c_str(), m->strLastAccessError.c_str(),
5566 rc, vrc));
5567 }
5568
5569 /* inform other callers if there are any */
5570 RTSemEventMultiSignal(m->queryInfoSem);
5571 m->queryInfoRunning = false;
5572
5573 /* Set the proper state according to the result of the check */
5574 if (success)
5575 m->preLockState = MediumState_Created;
5576 else
5577 m->preLockState = MediumState_Inaccessible;
5578
5579 HRESULT rc2;
5580 if (uOpenFlags & (VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_SHAREABLE))
5581 rc2 = UnlockRead(NULL);
5582 else
5583 rc2 = UnlockWrite(NULL);
5584 if (SUCCEEDED(rc) && FAILED(rc2))
5585 rc = rc2;
5586 if (FAILED(rc)) return rc;
5587
5588 /* If this is a base image which incorrectly has a parent UUID set,
5589 * repair the image now by zeroing the parent UUID. This is only done
5590 * when we have structural information from a config file, on import
5591 * this is not possible. If someone would accidentally call openMedium
5592 * with a diff image before the base is registered this would destroy
5593 * the diff. Not acceptable. */
5594 if (fRepairImageZeroParentUuid)
5595 {
5596 rc = LockWrite(NULL);
5597 if (FAILED(rc)) return rc;
5598
5599 alock.leave();
5600
5601 try
5602 {
5603 PVBOXHDD hdd;
5604 vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
5605 ComAssertRCThrow(vrc, E_FAIL);
5606
5607 try
5608 {
5609 vrc = VDOpen(hdd,
5610 format.c_str(),
5611 location.c_str(),
5612 uOpenFlags & ~VD_OPEN_FLAGS_READONLY,
5613 m->vdImageIfaces);
5614 if (RT_FAILURE(vrc))
5615 throw S_OK;
5616
5617 RTUUID zeroParentUuid;
5618 RTUuidClear(&zeroParentUuid);
5619 vrc = VDSetParentUuid(hdd, 0, &zeroParentUuid);
5620 ComAssertRCThrow(vrc, E_FAIL);
5621 }
5622 catch (HRESULT aRC)
5623 {
5624 rc = aRC;
5625 }
5626
5627 VDDestroy(hdd);
5628 }
5629 catch (HRESULT aRC)
5630 {
5631 rc = aRC;
5632 }
5633
5634 alock.enter();
5635
5636 rc = UnlockWrite(NULL);
5637 if (SUCCEEDED(rc) && FAILED(rc2))
5638 rc = rc2;
5639 if (FAILED(rc)) return rc;
5640 }
5641
5642 return rc;
5643}
5644
5645/**
5646 * Performs extra checks if the medium can be closed and returns S_OK in
5647 * this case. Otherwise, returns a respective error message. Called by
5648 * Close() under the medium tree lock and the medium lock.
5649 *
5650 * @note Also reused by Medium::Reset().
5651 *
5652 * @note Caller must hold the media tree write lock!
5653 */
5654HRESULT Medium::canClose()
5655{
5656 Assert(m->pVirtualBox->getMediaTreeLockHandle().isWriteLockOnCurrentThread());
5657
5658 if (getChildren().size() != 0)
5659 return setError(VBOX_E_OBJECT_IN_USE,
5660 tr("Cannot close medium '%s' because it has %d child media"),
5661 m->strLocationFull.c_str(), getChildren().size());
5662
5663 return S_OK;
5664}
5665
5666/**
5667 * Unregisters this medium with mVirtualBox. Called by close() under the medium tree lock.
5668 *
5669 * This calls either VirtualBox::unregisterImage or VirtualBox::unregisterHardDisk depending
5670 * on the device type of this medium.
5671 *
5672 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs that will receive the registry IDs that need saving.
5673 *
5674 * @note Caller must have locked the media tree lock for writing!
5675 */
5676HRESULT Medium::unregisterWithVirtualBox(GuidList *pllRegistriesThatNeedSaving)
5677{
5678 /* Note that we need to de-associate ourselves from the parent to let
5679 * unregisterHardDisk() properly save the registry */
5680
5681 /* we modify mParent and access children */
5682 Assert(m->pVirtualBox->getMediaTreeLockHandle().isWriteLockOnCurrentThread());
5683
5684 Medium *pParentBackup = m->pParent;
5685 AssertReturn(getChildren().size() == 0, E_FAIL);
5686 if (m->pParent)
5687 deparent();
5688
5689 HRESULT rc = E_FAIL;
5690 switch (m->devType)
5691 {
5692 case DeviceType_DVD:
5693 case DeviceType_Floppy:
5694 rc = m->pVirtualBox->unregisterImage(this,
5695 m->devType,
5696 pllRegistriesThatNeedSaving);
5697 break;
5698
5699 case DeviceType_HardDisk:
5700 rc = m->pVirtualBox->unregisterHardDisk(this, pllRegistriesThatNeedSaving);
5701 break;
5702
5703 default:
5704 break;
5705 }
5706
5707 if (FAILED(rc))
5708 {
5709 if (pParentBackup)
5710 {
5711 // re-associate with the parent as we are still relatives in the registry
5712 m->pParent = pParentBackup;
5713 m->pParent->m->llChildren.push_back(this);
5714 }
5715 }
5716
5717 return rc;
5718}
5719
5720/**
5721 * Sets the extended error info according to the current media state.
5722 *
5723 * @note Must be called from under this object's write or read lock.
5724 */
5725HRESULT Medium::setStateError()
5726{
5727 HRESULT rc = E_FAIL;
5728
5729 switch (m->state)
5730 {
5731 case MediumState_NotCreated:
5732 {
5733 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5734 tr("Storage for the medium '%s' is not created"),
5735 m->strLocationFull.c_str());
5736 break;
5737 }
5738 case MediumState_Created:
5739 {
5740 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5741 tr("Storage for the medium '%s' is already created"),
5742 m->strLocationFull.c_str());
5743 break;
5744 }
5745 case MediumState_LockedRead:
5746 {
5747 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5748 tr("Medium '%s' is locked for reading by another task"),
5749 m->strLocationFull.c_str());
5750 break;
5751 }
5752 case MediumState_LockedWrite:
5753 {
5754 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5755 tr("Medium '%s' is locked for writing by another task"),
5756 m->strLocationFull.c_str());
5757 break;
5758 }
5759 case MediumState_Inaccessible:
5760 {
5761 /* be in sync with Console::powerUpThread() */
5762 if (!m->strLastAccessError.isEmpty())
5763 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5764 tr("Medium '%s' is not accessible. %s"),
5765 m->strLocationFull.c_str(), m->strLastAccessError.c_str());
5766 else
5767 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5768 tr("Medium '%s' is not accessible"),
5769 m->strLocationFull.c_str());
5770 break;
5771 }
5772 case MediumState_Creating:
5773 {
5774 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5775 tr("Storage for the medium '%s' is being created"),
5776 m->strLocationFull.c_str());
5777 break;
5778 }
5779 case MediumState_Deleting:
5780 {
5781 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5782 tr("Storage for the medium '%s' is being deleted"),
5783 m->strLocationFull.c_str());
5784 break;
5785 }
5786 default:
5787 {
5788 AssertFailed();
5789 break;
5790 }
5791 }
5792
5793 return rc;
5794}
5795
5796/**
5797 * Sets the value of m->strLocationFull. The given location must be a fully
5798 * qualified path; relative paths are not supported here.
5799 *
5800 * As a special exception, if the specified location is a file path that ends with '/'
5801 * then the file name part will be generated by this method automatically in the format
5802 * '{<uuid>}.<ext>' where <uuid> is a fresh UUID that this method will generate
5803 * and assign to this medium, and <ext> is the default extension for this
5804 * medium's storage format. Note that this procedure requires the media state to
5805 * be NotCreated and will return a failure otherwise.
5806 *
5807 * @param aLocation Location of the storage unit. If the location is a FS-path,
5808 * then it can be relative to the VirtualBox home directory.
5809 * @param aFormat Optional fallback format if it is an import and the format
5810 * cannot be determined.
5811 *
5812 * @note Must be called from under this object's write lock.
5813 */
5814HRESULT Medium::setLocation(const Utf8Str &aLocation,
5815 const Utf8Str &aFormat /* = Utf8Str::Empty */)
5816{
5817 AssertReturn(!aLocation.isEmpty(), E_FAIL);
5818
5819 AutoCaller autoCaller(this);
5820 AssertComRCReturnRC(autoCaller.rc());
5821
5822 /* formatObj may be null only when initializing from an existing path and
5823 * no format is known yet */
5824 AssertReturn( (!m->strFormat.isEmpty() && !m->formatObj.isNull())
5825 || ( autoCaller.state() == InInit
5826 && m->state != MediumState_NotCreated
5827 && m->id.isEmpty()
5828 && m->strFormat.isEmpty()
5829 && m->formatObj.isNull()),
5830 E_FAIL);
5831
5832 /* are we dealing with a new medium constructed using the existing
5833 * location? */
5834 bool isImport = m->strFormat.isEmpty();
5835
5836 if ( isImport
5837 || ( (m->formatObj->getCapabilities() & MediumFormatCapabilities_File)
5838 && !m->hostDrive))
5839 {
5840 Guid id;
5841
5842 Utf8Str locationFull(aLocation);
5843
5844 if (m->state == MediumState_NotCreated)
5845 {
5846 /* must be a file (formatObj must be already known) */
5847 Assert(m->formatObj->getCapabilities() & MediumFormatCapabilities_File);
5848
5849 if (RTPathFilename(aLocation.c_str()) == NULL)
5850 {
5851 /* no file name is given (either an empty string or ends with a
5852 * slash), generate a new UUID + file name if the state allows
5853 * this */
5854
5855 ComAssertMsgRet(!m->formatObj->getFileExtensions().empty(),
5856 ("Must be at least one extension if it is MediumFormatCapabilities_File\n"),
5857 E_FAIL);
5858
5859 Utf8Str strExt = m->formatObj->getFileExtensions().front();
5860 ComAssertMsgRet(!strExt.isEmpty(),
5861 ("Default extension must not be empty\n"),
5862 E_FAIL);
5863
5864 id.create();
5865
5866 locationFull = Utf8StrFmt("%s{%RTuuid}.%s",
5867 aLocation.c_str(), id.raw(), strExt.c_str());
5868 }
5869 }
5870
5871 // we must always have full paths now (if it refers to a file)
5872 if ( ( m->formatObj.isNull()
5873 || m->formatObj->getCapabilities() & MediumFormatCapabilities_File)
5874 && !RTPathStartsWithRoot(locationFull.c_str()))
5875 return setError(VBOX_E_FILE_ERROR,
5876 tr("The given path '%s' is not fully qualified"),
5877 locationFull.c_str());
5878
5879 /* detect the backend from the storage unit if importing */
5880 if (isImport)
5881 {
5882 VDTYPE enmType = VDTYPE_INVALID;
5883 char *backendName = NULL;
5884
5885 int vrc = VINF_SUCCESS;
5886
5887 /* is it a file? */
5888 {
5889 RTFILE file;
5890 vrc = RTFileOpen(&file, locationFull.c_str(), RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
5891 if (RT_SUCCESS(vrc))
5892 RTFileClose(file);
5893 }
5894 if (RT_SUCCESS(vrc))
5895 {
5896 vrc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
5897 locationFull.c_str(), &backendName, &enmType);
5898 }
5899 else if (vrc != VERR_FILE_NOT_FOUND && vrc != VERR_PATH_NOT_FOUND)
5900 {
5901 /* assume it's not a file, restore the original location */
5902 locationFull = aLocation;
5903 vrc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
5904 locationFull.c_str(), &backendName, &enmType);
5905 }
5906
5907 if (RT_FAILURE(vrc))
5908 {
5909 if (vrc == VERR_FILE_NOT_FOUND || vrc == VERR_PATH_NOT_FOUND)
5910 return setError(VBOX_E_FILE_ERROR,
5911 tr("Could not find file for the medium '%s' (%Rrc)"),
5912 locationFull.c_str(), vrc);
5913 else if (aFormat.isEmpty())
5914 return setError(VBOX_E_IPRT_ERROR,
5915 tr("Could not get the storage format of the medium '%s' (%Rrc)"),
5916 locationFull.c_str(), vrc);
5917 else
5918 {
5919 HRESULT rc = setFormat(aFormat);
5920 /* setFormat() must not fail since we've just used the backend so
5921 * the format object must be there */
5922 AssertComRCReturnRC(rc);
5923 }
5924 }
5925 else if ( enmType == VDTYPE_INVALID
5926 || m->devType != convertToDeviceType(enmType))
5927 {
5928 /*
5929 * The user tried to use a image as a device which is not supported
5930 * by the backend.
5931 */
5932 return setError(E_FAIL,
5933 tr("The medium '%s' can't be used as the requested device type"),
5934 locationFull.c_str());
5935 }
5936 else
5937 {
5938 ComAssertRet(backendName != NULL && *backendName != '\0', E_FAIL);
5939
5940 HRESULT rc = setFormat(backendName);
5941 RTStrFree(backendName);
5942
5943 /* setFormat() must not fail since we've just used the backend so
5944 * the format object must be there */
5945 AssertComRCReturnRC(rc);
5946 }
5947 }
5948
5949 m->strLocationFull = locationFull;
5950
5951 /* is it still a file? */
5952 if ( (m->formatObj->getCapabilities() & MediumFormatCapabilities_File)
5953 && (m->state == MediumState_NotCreated)
5954 )
5955 /* assign a new UUID (this UUID will be used when calling
5956 * VDCreateBase/VDCreateDiff as a wanted UUID). Note that we
5957 * also do that if we didn't generate it to make sure it is
5958 * either generated by us or reset to null */
5959 unconst(m->id) = id;
5960 }
5961 else
5962 m->strLocationFull = aLocation;
5963
5964 return S_OK;
5965}
5966
5967/**
5968 * Checks that the format ID is valid and sets it on success.
5969 *
5970 * Note that this method will caller-reference the format object on success!
5971 * This reference must be released somewhere to let the MediumFormat object be
5972 * uninitialized.
5973 *
5974 * @note Must be called from under this object's write lock.
5975 */
5976HRESULT Medium::setFormat(const Utf8Str &aFormat)
5977{
5978 /* get the format object first */
5979 {
5980 SystemProperties *pSysProps = m->pVirtualBox->getSystemProperties();
5981 AutoReadLock propsLock(pSysProps COMMA_LOCKVAL_SRC_POS);
5982
5983 unconst(m->formatObj) = pSysProps->mediumFormat(aFormat);
5984 if (m->formatObj.isNull())
5985 return setError(E_INVALIDARG,
5986 tr("Invalid medium storage format '%s'"),
5987 aFormat.c_str());
5988
5989 /* reference the format permanently to prevent its unexpected
5990 * uninitialization */
5991 HRESULT rc = m->formatObj->addCaller();
5992 AssertComRCReturnRC(rc);
5993
5994 /* get properties (preinsert them as keys in the map). Note that the
5995 * map doesn't grow over the object life time since the set of
5996 * properties is meant to be constant. */
5997
5998 Assert(m->mapProperties.empty());
5999
6000 for (MediumFormat::PropertyList::const_iterator it = m->formatObj->getProperties().begin();
6001 it != m->formatObj->getProperties().end();
6002 ++it)
6003 {
6004 m->mapProperties.insert(std::make_pair(it->strName, Utf8Str::Empty));
6005 }
6006 }
6007
6008 unconst(m->strFormat) = aFormat;
6009
6010 return S_OK;
6011}
6012
6013/**
6014 * Converts the Medium device type to the VD type.
6015 */
6016VDTYPE Medium::convertDeviceType()
6017{
6018 VDTYPE enmType;
6019
6020 switch (m->devType)
6021 {
6022 case DeviceType_HardDisk:
6023 enmType = VDTYPE_HDD;
6024 break;
6025 case DeviceType_DVD:
6026 enmType = VDTYPE_DVD;
6027 break;
6028 case DeviceType_Floppy:
6029 enmType = VDTYPE_FLOPPY;
6030 break;
6031 default:
6032 ComAssertFailedRet(VDTYPE_INVALID);
6033 }
6034
6035 return enmType;
6036}
6037
6038/**
6039 * Converts from the VD type to the medium type.
6040 */
6041DeviceType_T Medium::convertToDeviceType(VDTYPE enmType)
6042{
6043 DeviceType_T devType;
6044
6045 switch (enmType)
6046 {
6047 case VDTYPE_HDD:
6048 devType = DeviceType_HardDisk;
6049 break;
6050 case VDTYPE_DVD:
6051 devType = DeviceType_DVD;
6052 break;
6053 case VDTYPE_FLOPPY:
6054 devType = DeviceType_Floppy;
6055 break;
6056 default:
6057 ComAssertFailedRet(DeviceType_Null);
6058 }
6059
6060 return devType;
6061}
6062
6063/**
6064 * Returns the last error message collected by the vdErrorCall callback and
6065 * resets it.
6066 *
6067 * The error message is returned prepended with a dot and a space, like this:
6068 * <code>
6069 * ". <error_text> (%Rrc)"
6070 * </code>
6071 * to make it easily appendable to a more general error message. The @c %Rrc
6072 * format string is given @a aVRC as an argument.
6073 *
6074 * If there is no last error message collected by vdErrorCall or if it is a
6075 * null or empty string, then this function returns the following text:
6076 * <code>
6077 * " (%Rrc)"
6078 * </code>
6079 *
6080 * @note Doesn't do any object locking; it is assumed that the caller makes sure
6081 * the callback isn't called by more than one thread at a time.
6082 *
6083 * @param aVRC VBox error code to use when no error message is provided.
6084 */
6085Utf8Str Medium::vdError(int aVRC)
6086{
6087 Utf8Str error;
6088
6089 if (m->vdError.isEmpty())
6090 error = Utf8StrFmt(" (%Rrc)", aVRC);
6091 else
6092 error = Utf8StrFmt(".\n%s", m->vdError.c_str());
6093
6094 m->vdError.setNull();
6095
6096 return error;
6097}
6098
6099/**
6100 * Error message callback.
6101 *
6102 * Puts the reported error message to the m->vdError field.
6103 *
6104 * @note Doesn't do any object locking; it is assumed that the caller makes sure
6105 * the callback isn't called by more than one thread at a time.
6106 *
6107 * @param pvUser The opaque data passed on container creation.
6108 * @param rc The VBox error code.
6109 * @param RT_SRC_POS_DECL Use RT_SRC_POS.
6110 * @param pszFormat Error message format string.
6111 * @param va Error message arguments.
6112 */
6113/*static*/
6114DECLCALLBACK(void) Medium::vdErrorCall(void *pvUser, int rc, RT_SRC_POS_DECL,
6115 const char *pszFormat, va_list va)
6116{
6117 NOREF(pszFile); NOREF(iLine); NOREF(pszFunction); /* RT_SRC_POS_DECL */
6118
6119 Medium *that = static_cast<Medium*>(pvUser);
6120 AssertReturnVoid(that != NULL);
6121
6122 if (that->m->vdError.isEmpty())
6123 that->m->vdError =
6124 Utf8StrFmt("%s (%Rrc)", Utf8Str(pszFormat, va).c_str(), rc);
6125 else
6126 that->m->vdError =
6127 Utf8StrFmt("%s.\n%s (%Rrc)", that->m->vdError.c_str(),
6128 Utf8Str(pszFormat, va).c_str(), rc);
6129}
6130
6131/* static */
6132DECLCALLBACK(bool) Medium::vdConfigAreKeysValid(void *pvUser,
6133 const char * /* pszzValid */)
6134{
6135 Medium *that = static_cast<Medium*>(pvUser);
6136 AssertReturn(that != NULL, false);
6137
6138 /* we always return true since the only keys we have are those found in
6139 * VDBACKENDINFO */
6140 return true;
6141}
6142
6143/* static */
6144DECLCALLBACK(int) Medium::vdConfigQuerySize(void *pvUser,
6145 const char *pszName,
6146 size_t *pcbValue)
6147{
6148 AssertReturn(VALID_PTR(pcbValue), VERR_INVALID_POINTER);
6149
6150 Medium *that = static_cast<Medium*>(pvUser);
6151 AssertReturn(that != NULL, VERR_GENERAL_FAILURE);
6152
6153 settings::StringsMap::const_iterator it = that->m->mapProperties.find(Utf8Str(pszName));
6154 if (it == that->m->mapProperties.end())
6155 return VERR_CFGM_VALUE_NOT_FOUND;
6156
6157 /* we interpret null values as "no value" in Medium */
6158 if (it->second.isEmpty())
6159 return VERR_CFGM_VALUE_NOT_FOUND;
6160
6161 *pcbValue = it->second.length() + 1 /* include terminator */;
6162
6163 return VINF_SUCCESS;
6164}
6165
6166/* static */
6167DECLCALLBACK(int) Medium::vdConfigQuery(void *pvUser,
6168 const char *pszName,
6169 char *pszValue,
6170 size_t cchValue)
6171{
6172 AssertReturn(VALID_PTR(pszValue), VERR_INVALID_POINTER);
6173
6174 Medium *that = static_cast<Medium*>(pvUser);
6175 AssertReturn(that != NULL, VERR_GENERAL_FAILURE);
6176
6177 settings::StringsMap::const_iterator it = that->m->mapProperties.find(Utf8Str(pszName));
6178 if (it == that->m->mapProperties.end())
6179 return VERR_CFGM_VALUE_NOT_FOUND;
6180
6181 /* we interpret null values as "no value" in Medium */
6182 if (it->second.isEmpty())
6183 return VERR_CFGM_VALUE_NOT_FOUND;
6184
6185 const Utf8Str &value = it->second;
6186 if (value.length() >= cchValue)
6187 return VERR_CFGM_NOT_ENOUGH_SPACE;
6188
6189 memcpy(pszValue, value.c_str(), value.length() + 1);
6190
6191 return VINF_SUCCESS;
6192}
6193
6194DECLCALLBACK(int) Medium::vdTcpSocketCreate(uint32_t fFlags, PVDSOCKET pSock)
6195{
6196 PVDSOCKETINT pSocketInt = NULL;
6197
6198 if ((fFlags & VD_INTERFACETCPNET_CONNECT_EXTENDED_SELECT) != 0)
6199 return VERR_NOT_SUPPORTED;
6200
6201 pSocketInt = (PVDSOCKETINT)RTMemAllocZ(sizeof(VDSOCKETINT));
6202 if (!pSocketInt)
6203 return VERR_NO_MEMORY;
6204
6205 pSocketInt->hSocket = NIL_RTSOCKET;
6206 *pSock = pSocketInt;
6207 return VINF_SUCCESS;
6208}
6209
6210DECLCALLBACK(int) Medium::vdTcpSocketDestroy(VDSOCKET Sock)
6211{
6212 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6213
6214 if (pSocketInt->hSocket != NIL_RTSOCKET)
6215 RTTcpClientCloseEx(pSocketInt->hSocket, false /*fGracefulShutdown*/);
6216
6217 RTMemFree(pSocketInt);
6218
6219 return VINF_SUCCESS;
6220}
6221
6222DECLCALLBACK(int) Medium::vdTcpClientConnect(VDSOCKET Sock, const char *pszAddress, uint32_t uPort)
6223{
6224 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6225
6226 return RTTcpClientConnect(pszAddress, uPort, &pSocketInt->hSocket);
6227}
6228
6229DECLCALLBACK(int) Medium::vdTcpClientClose(VDSOCKET Sock)
6230{
6231 int rc = VINF_SUCCESS;
6232 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6233
6234 rc = RTTcpClientCloseEx(pSocketInt->hSocket, false /*fGracefulShutdown*/);
6235 pSocketInt->hSocket = NIL_RTSOCKET;
6236 return rc;
6237}
6238
6239DECLCALLBACK(bool) Medium::vdTcpIsClientConnected(VDSOCKET Sock)
6240{
6241 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6242 return pSocketInt->hSocket != NIL_RTSOCKET;
6243}
6244
6245DECLCALLBACK(int) Medium::vdTcpSelectOne(VDSOCKET Sock, RTMSINTERVAL cMillies)
6246{
6247 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6248 return RTTcpSelectOne(pSocketInt->hSocket, cMillies);
6249}
6250
6251DECLCALLBACK(int) Medium::vdTcpRead(VDSOCKET Sock, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
6252{
6253 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6254 return RTTcpRead(pSocketInt->hSocket, pvBuffer, cbBuffer, pcbRead);
6255}
6256
6257DECLCALLBACK(int) Medium::vdTcpWrite(VDSOCKET Sock, const void *pvBuffer, size_t cbBuffer)
6258{
6259 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6260 return RTTcpWrite(pSocketInt->hSocket, pvBuffer, cbBuffer);
6261}
6262
6263DECLCALLBACK(int) Medium::vdTcpSgWrite(VDSOCKET Sock, PCRTSGBUF pSgBuf)
6264{
6265 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6266 return RTTcpSgWrite(pSocketInt->hSocket, pSgBuf);
6267}
6268
6269DECLCALLBACK(int) Medium::vdTcpFlush(VDSOCKET Sock)
6270{
6271 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6272 return RTTcpFlush(pSocketInt->hSocket);
6273}
6274
6275DECLCALLBACK(int) Medium::vdTcpSetSendCoalescing(VDSOCKET Sock, bool fEnable)
6276{
6277 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6278 return RTTcpSetSendCoalescing(pSocketInt->hSocket, fEnable);
6279}
6280
6281DECLCALLBACK(int) Medium::vdTcpGetLocalAddress(VDSOCKET Sock, PRTNETADDR pAddr)
6282{
6283 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6284 return RTTcpGetLocalAddress(pSocketInt->hSocket, pAddr);
6285}
6286
6287DECLCALLBACK(int) Medium::vdTcpGetPeerAddress(VDSOCKET Sock, PRTNETADDR pAddr)
6288{
6289 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6290 return RTTcpGetPeerAddress(pSocketInt->hSocket, pAddr);
6291}
6292
6293/**
6294 * Starts a new thread driven by the appropriate Medium::Task::handler() method.
6295 *
6296 * @note When the task is executed by this method, IProgress::notifyComplete()
6297 * is automatically called for the progress object associated with this
6298 * task when the task is finished to signal the operation completion for
6299 * other threads asynchronously waiting for it.
6300 */
6301HRESULT Medium::startThread(Medium::Task *pTask)
6302{
6303#ifdef VBOX_WITH_MAIN_LOCK_VALIDATION
6304 /* Extreme paranoia: The calling thread should not hold the medium
6305 * tree lock or any medium lock. Since there is no separate lock class
6306 * for medium objects be even more strict: no other object locks. */
6307 Assert(!AutoLockHoldsLocksInClass(LOCKCLASS_LISTOFMEDIA));
6308 Assert(!AutoLockHoldsLocksInClass(getLockingClass()));
6309#endif
6310
6311 /// @todo use a more descriptive task name
6312 int vrc = RTThreadCreate(NULL, Medium::Task::fntMediumTask, pTask,
6313 0, RTTHREADTYPE_MAIN_HEAVY_WORKER, 0,
6314 "Medium::Task");
6315 if (RT_FAILURE(vrc))
6316 {
6317 delete pTask;
6318 return setError(E_FAIL, "Could not create Medium::Task thread (%Rrc)\n", vrc);
6319 }
6320
6321 return S_OK;
6322}
6323
6324/**
6325 * Runs Medium::Task::handler() on the current thread instead of creating
6326 * a new one.
6327 *
6328 * This call implies that it is made on another temporary thread created for
6329 * some asynchronous task. Avoid calling it from a normal thread since the task
6330 * operations are potentially lengthy and will block the calling thread in this
6331 * case.
6332 *
6333 * @note When the task is executed by this method, IProgress::notifyComplete()
6334 * is not called for the progress object associated with this task when
6335 * the task is finished. Instead, the result of the operation is returned
6336 * by this method directly and it's the caller's responsibility to
6337 * complete the progress object in this case.
6338 */
6339HRESULT Medium::runNow(Medium::Task *pTask,
6340 GuidList *pllRegistriesThatNeedSaving)
6341{
6342#ifdef VBOX_WITH_MAIN_LOCK_VALIDATION
6343 /* Extreme paranoia: The calling thread should not hold the medium
6344 * tree lock or any medium lock. Since there is no separate lock class
6345 * for medium objects be even more strict: no other object locks. */
6346 Assert(!AutoLockHoldsLocksInClass(LOCKCLASS_LISTOFMEDIA));
6347 Assert(!AutoLockHoldsLocksInClass(getLockingClass()));
6348#endif
6349
6350 pTask->m_pllRegistriesThatNeedSaving = pllRegistriesThatNeedSaving;
6351
6352 /* NIL_RTTHREAD indicates synchronous call. */
6353 return (HRESULT)Medium::Task::fntMediumTask(NIL_RTTHREAD, pTask);
6354}
6355
6356/**
6357 * Implementation code for the "create base" task.
6358 *
6359 * This only gets started from Medium::CreateBaseStorage() and always runs
6360 * asynchronously. As a result, we always save the VirtualBox.xml file when
6361 * we're done here.
6362 *
6363 * @param task
6364 * @return
6365 */
6366HRESULT Medium::taskCreateBaseHandler(Medium::CreateBaseTask &task)
6367{
6368 HRESULT rc = S_OK;
6369
6370 /* these parameters we need after creation */
6371 uint64_t size = 0, logicalSize = 0;
6372 MediumVariant_T variant = MediumVariant_Standard;
6373 bool fGenerateUuid = false;
6374
6375 try
6376 {
6377 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6378
6379 /* The object may request a specific UUID (through a special form of
6380 * the setLocation() argument). Otherwise we have to generate it */
6381 Guid id = m->id;
6382 fGenerateUuid = id.isEmpty();
6383 if (fGenerateUuid)
6384 {
6385 id.create();
6386 /* VirtualBox::registerHardDisk() will need UUID */
6387 unconst(m->id) = id;
6388 }
6389
6390 Utf8Str format(m->strFormat);
6391 Utf8Str location(m->strLocationFull);
6392 uint64_t capabilities = m->formatObj->getCapabilities();
6393 ComAssertThrow(capabilities & ( MediumFormatCapabilities_CreateFixed
6394 | MediumFormatCapabilities_CreateDynamic), E_FAIL);
6395 Assert(m->state == MediumState_Creating);
6396
6397 PVBOXHDD hdd;
6398 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
6399 ComAssertRCThrow(vrc, E_FAIL);
6400
6401 /* unlock before the potentially lengthy operation */
6402 thisLock.release();
6403
6404 try
6405 {
6406 /* ensure the directory exists */
6407 if (capabilities & MediumFormatCapabilities_File)
6408 {
6409 rc = VirtualBox::ensureFilePathExists(location);
6410 if (FAILED(rc))
6411 throw rc;
6412 }
6413
6414 VDGEOMETRY geo = { 0, 0, 0 }; /* auto-detect */
6415
6416 vrc = VDCreateBase(hdd,
6417 format.c_str(),
6418 location.c_str(),
6419 task.mSize,
6420 task.mVariant,
6421 NULL,
6422 &geo,
6423 &geo,
6424 id.raw(),
6425 VD_OPEN_FLAGS_NORMAL,
6426 m->vdImageIfaces,
6427 task.mVDOperationIfaces);
6428 if (RT_FAILURE(vrc))
6429 throw setError(VBOX_E_FILE_ERROR,
6430 tr("Could not create the medium storage unit '%s'%s"),
6431 location.c_str(), vdError(vrc).c_str());
6432
6433 size = VDGetFileSize(hdd, 0);
6434 logicalSize = VDGetSize(hdd, 0);
6435 unsigned uImageFlags;
6436 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
6437 if (RT_SUCCESS(vrc))
6438 variant = (MediumVariant_T)uImageFlags;
6439 }
6440 catch (HRESULT aRC) { rc = aRC; }
6441
6442 VDDestroy(hdd);
6443 }
6444 catch (HRESULT aRC) { rc = aRC; }
6445
6446 if (SUCCEEDED(rc))
6447 {
6448 /* register with mVirtualBox as the last step and move to
6449 * Created state only on success (leaving an orphan file is
6450 * better than breaking media registry consistency) */
6451 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
6452 rc = m->pVirtualBox->registerHardDisk(this, NULL /* pllRegistriesThatNeedSaving */);
6453 }
6454
6455 // reenter the lock before changing state
6456 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6457
6458 if (SUCCEEDED(rc))
6459 {
6460 m->state = MediumState_Created;
6461
6462 m->size = size;
6463 m->logicalSize = logicalSize;
6464 m->variant = variant;
6465 }
6466 else
6467 {
6468 /* back to NotCreated on failure */
6469 m->state = MediumState_NotCreated;
6470
6471 /* reset UUID to prevent it from being reused next time */
6472 if (fGenerateUuid)
6473 unconst(m->id).clear();
6474 }
6475
6476 return rc;
6477}
6478
6479/**
6480 * Implementation code for the "create diff" task.
6481 *
6482 * This task always gets started from Medium::createDiffStorage() and can run
6483 * synchronously or asynchronously depending on the "wait" parameter passed to
6484 * that function. If we run synchronously, the caller expects the bool
6485 * *pfNeedsGlobalSaveSettings to be set before returning; otherwise (in asynchronous
6486 * mode), we save the settings ourselves.
6487 *
6488 * @param task
6489 * @return
6490 */
6491HRESULT Medium::taskCreateDiffHandler(Medium::CreateDiffTask &task)
6492{
6493 HRESULT rcTmp = S_OK;
6494
6495 const ComObjPtr<Medium> &pTarget = task.mTarget;
6496
6497 uint64_t size = 0, logicalSize = 0;
6498 MediumVariant_T variant = MediumVariant_Standard;
6499 bool fGenerateUuid = false;
6500
6501 GuidList llRegistriesThatNeedSaving; // gets copied to task pointer later in synchronous mode
6502
6503 try
6504 {
6505 /* Lock both in {parent,child} order. */
6506 AutoMultiWriteLock2 mediaLock(this, pTarget COMMA_LOCKVAL_SRC_POS);
6507
6508 /* The object may request a specific UUID (through a special form of
6509 * the setLocation() argument). Otherwise we have to generate it */
6510 Guid targetId = pTarget->m->id;
6511 fGenerateUuid = targetId.isEmpty();
6512 if (fGenerateUuid)
6513 {
6514 targetId.create();
6515 /* VirtualBox::registerHardDisk() will need UUID */
6516 unconst(pTarget->m->id) = targetId;
6517 }
6518
6519 Guid id = m->id;
6520
6521 Utf8Str targetFormat(pTarget->m->strFormat);
6522 Utf8Str targetLocation(pTarget->m->strLocationFull);
6523 uint64_t capabilities = pTarget->m->formatObj->getCapabilities();
6524 ComAssertThrow(capabilities & MediumFormatCapabilities_CreateDynamic, E_FAIL);
6525
6526 Assert(pTarget->m->state == MediumState_Creating);
6527 Assert(m->state == MediumState_LockedRead);
6528
6529 PVBOXHDD hdd;
6530 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
6531 ComAssertRCThrow(vrc, E_FAIL);
6532
6533 /* the two media are now protected by their non-default states;
6534 * unlock the media before the potentially lengthy operation */
6535 mediaLock.release();
6536
6537 try
6538 {
6539 /* Open all media in the target chain but the last. */
6540 MediumLockList::Base::const_iterator targetListBegin =
6541 task.mpMediumLockList->GetBegin();
6542 MediumLockList::Base::const_iterator targetListEnd =
6543 task.mpMediumLockList->GetEnd();
6544 for (MediumLockList::Base::const_iterator it = targetListBegin;
6545 it != targetListEnd;
6546 ++it)
6547 {
6548 const MediumLock &mediumLock = *it;
6549 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
6550
6551 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
6552
6553 /* Skip over the target diff medium */
6554 if (pMedium->m->state == MediumState_Creating)
6555 continue;
6556
6557 /* sanity check */
6558 Assert(pMedium->m->state == MediumState_LockedRead);
6559
6560 /* Open all media in appropriate mode. */
6561 vrc = VDOpen(hdd,
6562 pMedium->m->strFormat.c_str(),
6563 pMedium->m->strLocationFull.c_str(),
6564 VD_OPEN_FLAGS_READONLY,
6565 pMedium->m->vdImageIfaces);
6566 if (RT_FAILURE(vrc))
6567 throw setError(VBOX_E_FILE_ERROR,
6568 tr("Could not open the medium storage unit '%s'%s"),
6569 pMedium->m->strLocationFull.c_str(),
6570 vdError(vrc).c_str());
6571 }
6572
6573 /* ensure the target directory exists */
6574 if (capabilities & MediumFormatCapabilities_File)
6575 {
6576 HRESULT rc = VirtualBox::ensureFilePathExists(targetLocation);
6577 if (FAILED(rc))
6578 throw rc;
6579 }
6580
6581 vrc = VDCreateDiff(hdd,
6582 targetFormat.c_str(),
6583 targetLocation.c_str(),
6584 task.mVariant | VD_IMAGE_FLAGS_DIFF,
6585 NULL,
6586 targetId.raw(),
6587 id.raw(),
6588 VD_OPEN_FLAGS_NORMAL,
6589 pTarget->m->vdImageIfaces,
6590 task.mVDOperationIfaces);
6591 if (RT_FAILURE(vrc))
6592 throw setError(VBOX_E_FILE_ERROR,
6593 tr("Could not create the differencing medium storage unit '%s'%s"),
6594 targetLocation.c_str(), vdError(vrc).c_str());
6595
6596 size = VDGetFileSize(hdd, VD_LAST_IMAGE);
6597 logicalSize = VDGetSize(hdd, VD_LAST_IMAGE);
6598 unsigned uImageFlags;
6599 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
6600 if (RT_SUCCESS(vrc))
6601 variant = (MediumVariant_T)uImageFlags;
6602 }
6603 catch (HRESULT aRC) { rcTmp = aRC; }
6604
6605 VDDestroy(hdd);
6606 }
6607 catch (HRESULT aRC) { rcTmp = aRC; }
6608
6609 MultiResult mrc(rcTmp);
6610
6611 if (SUCCEEDED(mrc))
6612 {
6613 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
6614
6615 Assert(pTarget->m->pParent.isNull());
6616
6617 /* associate the child with the parent */
6618 pTarget->m->pParent = this;
6619 m->llChildren.push_back(pTarget);
6620
6621 /** @todo r=klaus neither target nor base() are locked,
6622 * potential race! */
6623 /* diffs for immutable media are auto-reset by default */
6624 pTarget->m->autoReset = (getBase()->m->type == MediumType_Immutable);
6625
6626 /* register with mVirtualBox as the last step and move to
6627 * Created state only on success (leaving an orphan file is
6628 * better than breaking media registry consistency) */
6629 mrc = m->pVirtualBox->registerHardDisk(pTarget, &llRegistriesThatNeedSaving);
6630
6631 if (FAILED(mrc))
6632 /* break the parent association on failure to register */
6633 deparent();
6634 }
6635
6636 AutoMultiWriteLock2 mediaLock(this, pTarget COMMA_LOCKVAL_SRC_POS);
6637
6638 if (SUCCEEDED(mrc))
6639 {
6640 pTarget->m->state = MediumState_Created;
6641
6642 pTarget->m->size = size;
6643 pTarget->m->logicalSize = logicalSize;
6644 pTarget->m->variant = variant;
6645 }
6646 else
6647 {
6648 /* back to NotCreated on failure */
6649 pTarget->m->state = MediumState_NotCreated;
6650
6651 pTarget->m->autoReset = false;
6652
6653 /* reset UUID to prevent it from being reused next time */
6654 if (fGenerateUuid)
6655 unconst(pTarget->m->id).clear();
6656 }
6657
6658 // deregister the task registered in createDiffStorage()
6659 Assert(m->numCreateDiffTasks != 0);
6660 --m->numCreateDiffTasks;
6661
6662 if (task.isAsync())
6663 {
6664 mediaLock.release();
6665 mrc = m->pVirtualBox->saveRegistries(llRegistriesThatNeedSaving);
6666 }
6667 else
6668 // synchronous mode: report save settings result to caller
6669 if (task.m_pllRegistriesThatNeedSaving)
6670 *task.m_pllRegistriesThatNeedSaving = llRegistriesThatNeedSaving;
6671
6672 /* Note that in sync mode, it's the caller's responsibility to
6673 * unlock the medium. */
6674
6675 return mrc;
6676}
6677
6678/**
6679 * Implementation code for the "merge" task.
6680 *
6681 * This task always gets started from Medium::mergeTo() and can run
6682 * synchronously or asynchronously depending on the "wait" parameter passed to
6683 * that function. If we run synchronously, the caller expects the bool
6684 * *pfNeedsGlobalSaveSettings to be set before returning; otherwise (in asynchronous
6685 * mode), we save the settings ourselves.
6686 *
6687 * @param task
6688 * @return
6689 */
6690HRESULT Medium::taskMergeHandler(Medium::MergeTask &task)
6691{
6692 HRESULT rcTmp = S_OK;
6693
6694 const ComObjPtr<Medium> &pTarget = task.mTarget;
6695
6696 try
6697 {
6698 PVBOXHDD hdd;
6699 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
6700 ComAssertRCThrow(vrc, E_FAIL);
6701
6702 try
6703 {
6704 // Similar code appears in SessionMachine::onlineMergeMedium, so
6705 // if you make any changes below check whether they are applicable
6706 // in that context as well.
6707
6708 unsigned uTargetIdx = VD_LAST_IMAGE;
6709 unsigned uSourceIdx = VD_LAST_IMAGE;
6710 /* Open all media in the chain. */
6711 MediumLockList::Base::iterator lockListBegin =
6712 task.mpMediumLockList->GetBegin();
6713 MediumLockList::Base::iterator lockListEnd =
6714 task.mpMediumLockList->GetEnd();
6715 unsigned i = 0;
6716 for (MediumLockList::Base::iterator it = lockListBegin;
6717 it != lockListEnd;
6718 ++it)
6719 {
6720 MediumLock &mediumLock = *it;
6721 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
6722
6723 if (pMedium == this)
6724 uSourceIdx = i;
6725 else if (pMedium == pTarget)
6726 uTargetIdx = i;
6727
6728 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
6729
6730 /*
6731 * complex sanity (sane complexity)
6732 *
6733 * The current medium must be in the Deleting (medium is merged)
6734 * or LockedRead (parent medium) state if it is not the target.
6735 * If it is the target it must be in the LockedWrite state.
6736 */
6737 Assert( ( pMedium != pTarget
6738 && ( pMedium->m->state == MediumState_Deleting
6739 || pMedium->m->state == MediumState_LockedRead))
6740 || ( pMedium == pTarget
6741 && pMedium->m->state == MediumState_LockedWrite));
6742
6743 /*
6744 * Medium must be the target, in the LockedRead state
6745 * or Deleting state where it is not allowed to be attached
6746 * to a virtual machine.
6747 */
6748 Assert( pMedium == pTarget
6749 || pMedium->m->state == MediumState_LockedRead
6750 || ( pMedium->m->backRefs.size() == 0
6751 && pMedium->m->state == MediumState_Deleting));
6752 /* The source medium must be in Deleting state. */
6753 Assert( pMedium != this
6754 || pMedium->m->state == MediumState_Deleting);
6755
6756 unsigned uOpenFlags = VD_OPEN_FLAGS_NORMAL;
6757
6758 if ( pMedium->m->state == MediumState_LockedRead
6759 || pMedium->m->state == MediumState_Deleting)
6760 uOpenFlags = VD_OPEN_FLAGS_READONLY;
6761 if (pMedium->m->type == MediumType_Shareable)
6762 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
6763
6764 /* Open the medium */
6765 vrc = VDOpen(hdd,
6766 pMedium->m->strFormat.c_str(),
6767 pMedium->m->strLocationFull.c_str(),
6768 uOpenFlags,
6769 pMedium->m->vdImageIfaces);
6770 if (RT_FAILURE(vrc))
6771 throw vrc;
6772
6773 i++;
6774 }
6775
6776 ComAssertThrow( uSourceIdx != VD_LAST_IMAGE
6777 && uTargetIdx != VD_LAST_IMAGE, E_FAIL);
6778
6779 vrc = VDMerge(hdd, uSourceIdx, uTargetIdx,
6780 task.mVDOperationIfaces);
6781 if (RT_FAILURE(vrc))
6782 throw vrc;
6783
6784 /* update parent UUIDs */
6785 if (!task.mfMergeForward)
6786 {
6787 /* we need to update UUIDs of all source's children
6788 * which cannot be part of the container at once so
6789 * add each one in there individually */
6790 if (task.mChildrenToReparent.size() > 0)
6791 {
6792 for (MediaList::const_iterator it = task.mChildrenToReparent.begin();
6793 it != task.mChildrenToReparent.end();
6794 ++it)
6795 {
6796 /* VD_OPEN_FLAGS_INFO since UUID is wrong yet */
6797 vrc = VDOpen(hdd,
6798 (*it)->m->strFormat.c_str(),
6799 (*it)->m->strLocationFull.c_str(),
6800 VD_OPEN_FLAGS_INFO,
6801 (*it)->m->vdImageIfaces);
6802 if (RT_FAILURE(vrc))
6803 throw vrc;
6804
6805 vrc = VDSetParentUuid(hdd, VD_LAST_IMAGE,
6806 pTarget->m->id.raw());
6807 if (RT_FAILURE(vrc))
6808 throw vrc;
6809
6810 vrc = VDClose(hdd, false /* fDelete */);
6811 if (RT_FAILURE(vrc))
6812 throw vrc;
6813
6814 (*it)->UnlockWrite(NULL);
6815 }
6816 }
6817 }
6818 }
6819 catch (HRESULT aRC) { rcTmp = aRC; }
6820 catch (int aVRC)
6821 {
6822 rcTmp = setError(VBOX_E_FILE_ERROR,
6823 tr("Could not merge the medium '%s' to '%s'%s"),
6824 m->strLocationFull.c_str(),
6825 pTarget->m->strLocationFull.c_str(),
6826 vdError(aVRC).c_str());
6827 }
6828
6829 VDDestroy(hdd);
6830 }
6831 catch (HRESULT aRC) { rcTmp = aRC; }
6832
6833 ErrorInfoKeeper eik;
6834 MultiResult mrc(rcTmp);
6835 HRESULT rc2;
6836
6837 if (SUCCEEDED(mrc))
6838 {
6839 /* all media but the target were successfully deleted by
6840 * VDMerge; reparent the last one and uninitialize deleted media. */
6841
6842 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
6843
6844 if (task.mfMergeForward)
6845 {
6846 /* first, unregister the target since it may become a base
6847 * medium which needs re-registration */
6848 rc2 = m->pVirtualBox->unregisterHardDisk(pTarget, NULL /*&fNeedsGlobalSaveSettings*/);
6849 AssertComRC(rc2);
6850
6851 /* then, reparent it and disconnect the deleted branch at
6852 * both ends (chain->parent() is source's parent) */
6853 pTarget->deparent();
6854 pTarget->m->pParent = task.mParentForTarget;
6855 if (pTarget->m->pParent)
6856 {
6857 pTarget->m->pParent->m->llChildren.push_back(pTarget);
6858 deparent();
6859 }
6860
6861 /* then, register again */
6862 rc2 = m->pVirtualBox->registerHardDisk(pTarget, NULL /* pllRegistriesThatNeedSaving */ );
6863 AssertComRC(rc2);
6864 }
6865 else
6866 {
6867 Assert(pTarget->getChildren().size() == 1);
6868 Medium *targetChild = pTarget->getChildren().front();
6869
6870 /* disconnect the deleted branch at the elder end */
6871 targetChild->deparent();
6872
6873 /* reparent source's children and disconnect the deleted
6874 * branch at the younger end */
6875 if (task.mChildrenToReparent.size() > 0)
6876 {
6877 /* obey {parent,child} lock order */
6878 AutoWriteLock sourceLock(this COMMA_LOCKVAL_SRC_POS);
6879
6880 for (MediaList::const_iterator it = task.mChildrenToReparent.begin();
6881 it != task.mChildrenToReparent.end();
6882 it++)
6883 {
6884 Medium *pMedium = *it;
6885 AutoWriteLock childLock(pMedium COMMA_LOCKVAL_SRC_POS);
6886
6887 pMedium->deparent(); // removes pMedium from source
6888 pMedium->setParent(pTarget);
6889 }
6890 }
6891 }
6892
6893 /* unregister and uninitialize all media removed by the merge */
6894 MediumLockList::Base::iterator lockListBegin =
6895 task.mpMediumLockList->GetBegin();
6896 MediumLockList::Base::iterator lockListEnd =
6897 task.mpMediumLockList->GetEnd();
6898 for (MediumLockList::Base::iterator it = lockListBegin;
6899 it != lockListEnd;
6900 )
6901 {
6902 MediumLock &mediumLock = *it;
6903 /* Create a real copy of the medium pointer, as the medium
6904 * lock deletion below would invalidate the referenced object. */
6905 const ComObjPtr<Medium> pMedium = mediumLock.GetMedium();
6906
6907 /* The target and all media not merged (readonly) are skipped */
6908 if ( pMedium == pTarget
6909 || pMedium->m->state == MediumState_LockedRead)
6910 {
6911 ++it;
6912 continue;
6913 }
6914
6915 rc2 = pMedium->m->pVirtualBox->unregisterHardDisk(pMedium,
6916 NULL /*pfNeedsGlobalSaveSettings*/);
6917 AssertComRC(rc2);
6918
6919 /* now, uninitialize the deleted medium (note that
6920 * due to the Deleting state, uninit() will not touch
6921 * the parent-child relationship so we need to
6922 * uninitialize each disk individually) */
6923
6924 /* note that the operation initiator medium (which is
6925 * normally also the source medium) is a special case
6926 * -- there is one more caller added by Task to it which
6927 * we must release. Also, if we are in sync mode, the
6928 * caller may still hold an AutoCaller instance for it
6929 * and therefore we cannot uninit() it (it's therefore
6930 * the caller's responsibility) */
6931 if (pMedium == this)
6932 {
6933 Assert(getChildren().size() == 0);
6934 Assert(m->backRefs.size() == 0);
6935 task.mMediumCaller.release();
6936 }
6937
6938 /* Delete the medium lock list entry, which also releases the
6939 * caller added by MergeChain before uninit() and updates the
6940 * iterator to point to the right place. */
6941 rc2 = task.mpMediumLockList->RemoveByIterator(it);
6942 AssertComRC(rc2);
6943
6944 if (task.isAsync() || pMedium != this)
6945 pMedium->uninit();
6946 }
6947 }
6948
6949 if (task.isAsync())
6950 {
6951 // in asynchronous mode, save settings now
6952 GuidList llRegistriesThatNeedSaving;
6953 addToRegistryIDList(llRegistriesThatNeedSaving);
6954 /* collect multiple errors */
6955 eik.restore();
6956 mrc = m->pVirtualBox->saveRegistries(llRegistriesThatNeedSaving);
6957 eik.fetch();
6958 }
6959 else
6960 // synchronous mode: report save settings result to caller
6961 if (task.m_pllRegistriesThatNeedSaving)
6962 pTarget->addToRegistryIDList(*task.m_pllRegistriesThatNeedSaving);
6963
6964 if (FAILED(mrc))
6965 {
6966 /* Here we come if either VDMerge() failed (in which case we
6967 * assume that it tried to do everything to make a further
6968 * retry possible -- e.g. not deleted intermediate media
6969 * and so on) or VirtualBox::saveRegistries() failed (where we
6970 * should have the original tree but with intermediate storage
6971 * units deleted by VDMerge()). We have to only restore states
6972 * (through the MergeChain dtor) unless we are run synchronously
6973 * in which case it's the responsibility of the caller as stated
6974 * in the mergeTo() docs. The latter also implies that we
6975 * don't own the merge chain, so release it in this case. */
6976 if (task.isAsync())
6977 {
6978 Assert(task.mChildrenToReparent.size() == 0);
6979 cancelMergeTo(task.mChildrenToReparent, task.mpMediumLockList);
6980 }
6981 }
6982
6983 return mrc;
6984}
6985
6986/**
6987 * Implementation code for the "clone" task.
6988 *
6989 * This only gets started from Medium::CloneTo() and always runs asynchronously.
6990 * As a result, we always save the VirtualBox.xml file when we're done here.
6991 *
6992 * @param task
6993 * @return
6994 */
6995HRESULT Medium::taskCloneHandler(Medium::CloneTask &task)
6996{
6997 HRESULT rcTmp = S_OK;
6998
6999 const ComObjPtr<Medium> &pTarget = task.mTarget;
7000 const ComObjPtr<Medium> &pParent = task.mParent;
7001
7002 bool fCreatingTarget = false;
7003
7004 uint64_t size = 0, logicalSize = 0;
7005 MediumVariant_T variant = MediumVariant_Standard;
7006 bool fGenerateUuid = false;
7007
7008 try
7009 {
7010 /* Lock all in {parent,child} order. The lock is also used as a
7011 * signal from the task initiator (which releases it only after
7012 * RTThreadCreate()) that we can start the job. */
7013 AutoMultiWriteLock3 thisLock(this, pTarget, pParent COMMA_LOCKVAL_SRC_POS);
7014
7015 fCreatingTarget = pTarget->m->state == MediumState_Creating;
7016
7017 /* The object may request a specific UUID (through a special form of
7018 * the setLocation() argument). Otherwise we have to generate it */
7019 Guid targetId = pTarget->m->id;
7020 fGenerateUuid = targetId.isEmpty();
7021 if (fGenerateUuid)
7022 {
7023 targetId.create();
7024 /* VirtualBox::registerHardDisk() will need UUID */
7025 unconst(pTarget->m->id) = targetId;
7026 }
7027
7028 PVBOXHDD hdd;
7029 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
7030 ComAssertRCThrow(vrc, E_FAIL);
7031
7032 try
7033 {
7034 /* Open all media in the source chain. */
7035 MediumLockList::Base::const_iterator sourceListBegin =
7036 task.mpSourceMediumLockList->GetBegin();
7037 MediumLockList::Base::const_iterator sourceListEnd =
7038 task.mpSourceMediumLockList->GetEnd();
7039 for (MediumLockList::Base::const_iterator it = sourceListBegin;
7040 it != sourceListEnd;
7041 ++it)
7042 {
7043 const MediumLock &mediumLock = *it;
7044 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
7045 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
7046
7047 /* sanity check */
7048 Assert(pMedium->m->state == MediumState_LockedRead);
7049
7050 /** Open all media in read-only mode. */
7051 vrc = VDOpen(hdd,
7052 pMedium->m->strFormat.c_str(),
7053 pMedium->m->strLocationFull.c_str(),
7054 VD_OPEN_FLAGS_READONLY,
7055 pMedium->m->vdImageIfaces);
7056 if (RT_FAILURE(vrc))
7057 throw setError(VBOX_E_FILE_ERROR,
7058 tr("Could not open the medium storage unit '%s'%s"),
7059 pMedium->m->strLocationFull.c_str(),
7060 vdError(vrc).c_str());
7061 }
7062
7063 Utf8Str targetFormat(pTarget->m->strFormat);
7064 Utf8Str targetLocation(pTarget->m->strLocationFull);
7065 uint64_t capabilities = pTarget->m->formatObj->getCapabilities();
7066
7067 Assert( pTarget->m->state == MediumState_Creating
7068 || pTarget->m->state == MediumState_LockedWrite);
7069 Assert(m->state == MediumState_LockedRead);
7070 Assert( pParent.isNull()
7071 || pParent->m->state == MediumState_LockedRead);
7072
7073 /* unlock before the potentially lengthy operation */
7074 thisLock.release();
7075
7076 /* ensure the target directory exists */
7077 if (capabilities & MediumFormatCapabilities_File)
7078 {
7079 HRESULT rc = VirtualBox::ensureFilePathExists(targetLocation);
7080 if (FAILED(rc))
7081 throw rc;
7082 }
7083
7084 PVBOXHDD targetHdd;
7085 vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &targetHdd);
7086 ComAssertRCThrow(vrc, E_FAIL);
7087
7088 try
7089 {
7090 /* Open all media in the target chain. */
7091 MediumLockList::Base::const_iterator targetListBegin =
7092 task.mpTargetMediumLockList->GetBegin();
7093 MediumLockList::Base::const_iterator targetListEnd =
7094 task.mpTargetMediumLockList->GetEnd();
7095 for (MediumLockList::Base::const_iterator it = targetListBegin;
7096 it != targetListEnd;
7097 ++it)
7098 {
7099 const MediumLock &mediumLock = *it;
7100 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
7101
7102 /* If the target medium is not created yet there's no
7103 * reason to open it. */
7104 if (pMedium == pTarget && fCreatingTarget)
7105 continue;
7106
7107 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
7108
7109 /* sanity check */
7110 Assert( pMedium->m->state == MediumState_LockedRead
7111 || pMedium->m->state == MediumState_LockedWrite);
7112
7113 unsigned uOpenFlags = VD_OPEN_FLAGS_NORMAL;
7114 if (pMedium->m->state != MediumState_LockedWrite)
7115 uOpenFlags = VD_OPEN_FLAGS_READONLY;
7116 if (pMedium->m->type == MediumType_Shareable)
7117 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
7118
7119 /* Open all media in appropriate mode. */
7120 vrc = VDOpen(targetHdd,
7121 pMedium->m->strFormat.c_str(),
7122 pMedium->m->strLocationFull.c_str(),
7123 uOpenFlags,
7124 pMedium->m->vdImageIfaces);
7125 if (RT_FAILURE(vrc))
7126 throw setError(VBOX_E_FILE_ERROR,
7127 tr("Could not open the medium storage unit '%s'%s"),
7128 pMedium->m->strLocationFull.c_str(),
7129 vdError(vrc).c_str());
7130 }
7131
7132 /** @todo r=klaus target isn't locked, race getting the state */
7133 if (task.midxSrcImageSame == UINT32_MAX)
7134 {
7135 vrc = VDCopy(hdd,
7136 VD_LAST_IMAGE,
7137 targetHdd,
7138 targetFormat.c_str(),
7139 (fCreatingTarget) ? targetLocation.c_str() : (char *)NULL,
7140 false /* fMoveByRename */,
7141 0 /* cbSize */,
7142 task.mVariant,
7143 targetId.raw(),
7144 VD_OPEN_FLAGS_NORMAL,
7145 NULL /* pVDIfsOperation */,
7146 pTarget->m->vdImageIfaces,
7147 task.mVDOperationIfaces);
7148 }
7149 else
7150 {
7151 vrc = VDCopyEx(hdd,
7152 VD_LAST_IMAGE,
7153 targetHdd,
7154 targetFormat.c_str(),
7155 (fCreatingTarget) ? targetLocation.c_str() : (char *)NULL,
7156 false /* fMoveByRename */,
7157 0 /* cbSize */,
7158 task.midxSrcImageSame,
7159 task.midxDstImageSame,
7160 task.mVariant,
7161 targetId.raw(),
7162 VD_OPEN_FLAGS_NORMAL,
7163 NULL /* pVDIfsOperation */,
7164 pTarget->m->vdImageIfaces,
7165 task.mVDOperationIfaces);
7166 }
7167 if (RT_FAILURE(vrc))
7168 throw setError(VBOX_E_FILE_ERROR,
7169 tr("Could not create the clone medium '%s'%s"),
7170 targetLocation.c_str(), vdError(vrc).c_str());
7171
7172 size = VDGetFileSize(targetHdd, VD_LAST_IMAGE);
7173 logicalSize = VDGetSize(targetHdd, VD_LAST_IMAGE);
7174 unsigned uImageFlags;
7175 vrc = VDGetImageFlags(targetHdd, 0, &uImageFlags);
7176 if (RT_SUCCESS(vrc))
7177 variant = (MediumVariant_T)uImageFlags;
7178 }
7179 catch (HRESULT aRC) { rcTmp = aRC; }
7180
7181 VDDestroy(targetHdd);
7182 }
7183 catch (HRESULT aRC) { rcTmp = aRC; }
7184
7185 VDDestroy(hdd);
7186 }
7187 catch (HRESULT aRC) { rcTmp = aRC; }
7188
7189 ErrorInfoKeeper eik;
7190 MultiResult mrc(rcTmp);
7191
7192 /* Only do the parent changes for newly created media. */
7193 if (SUCCEEDED(mrc) && fCreatingTarget)
7194 {
7195 /* we set mParent & children() */
7196 AutoWriteLock alock2(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
7197
7198 Assert(pTarget->m->pParent.isNull());
7199
7200 if (pParent)
7201 {
7202 /* associate the clone with the parent and deassociate
7203 * from VirtualBox */
7204 pTarget->m->pParent = pParent;
7205 pParent->m->llChildren.push_back(pTarget);
7206
7207 /* register with mVirtualBox as the last step and move to
7208 * Created state only on success (leaving an orphan file is
7209 * better than breaking media registry consistency) */
7210 eik.restore();
7211 mrc = pParent->m->pVirtualBox->registerHardDisk(pTarget, NULL /* pllRegistriesThatNeedSaving */);
7212 eik.fetch();
7213
7214 if (FAILED(mrc))
7215 /* break parent association on failure to register */
7216 pTarget->deparent(); // removes target from parent
7217 }
7218 else
7219 {
7220 /* just register */
7221 eik.restore();
7222 mrc = m->pVirtualBox->registerHardDisk(pTarget, NULL /* pllRegistriesThatNeedSaving */);
7223 eik.fetch();
7224 }
7225 }
7226
7227 if (fCreatingTarget)
7228 {
7229 AutoWriteLock mLock(pTarget COMMA_LOCKVAL_SRC_POS);
7230
7231 if (SUCCEEDED(mrc))
7232 {
7233 pTarget->m->state = MediumState_Created;
7234
7235 pTarget->m->size = size;
7236 pTarget->m->logicalSize = logicalSize;
7237 pTarget->m->variant = variant;
7238 }
7239 else
7240 {
7241 /* back to NotCreated on failure */
7242 pTarget->m->state = MediumState_NotCreated;
7243
7244 /* reset UUID to prevent it from being reused next time */
7245 if (fGenerateUuid)
7246 unconst(pTarget->m->id).clear();
7247 }
7248 }
7249
7250 // now, at the end of this task (always asynchronous), save the settings
7251 if (SUCCEEDED(mrc))
7252 {
7253 // save the settings
7254 GuidList llRegistriesThatNeedSaving;
7255 addToRegistryIDList(llRegistriesThatNeedSaving);
7256 /* collect multiple errors */
7257 eik.restore();
7258 mrc = m->pVirtualBox->saveRegistries(llRegistriesThatNeedSaving);
7259 eik.fetch();
7260 }
7261
7262 /* Everything is explicitly unlocked when the task exits,
7263 * as the task destruction also destroys the source chain. */
7264
7265 /* Make sure the source chain is released early. It could happen
7266 * that we get a deadlock in Appliance::Import when Medium::Close
7267 * is called & the source chain is released at the same time. */
7268 task.mpSourceMediumLockList->Clear();
7269
7270 return mrc;
7271}
7272
7273/**
7274 * Implementation code for the "delete" task.
7275 *
7276 * This task always gets started from Medium::deleteStorage() and can run
7277 * synchronously or asynchronously depending on the "wait" parameter passed to
7278 * that function.
7279 *
7280 * @param task
7281 * @return
7282 */
7283HRESULT Medium::taskDeleteHandler(Medium::DeleteTask &task)
7284{
7285 NOREF(task);
7286 HRESULT rc = S_OK;
7287
7288 try
7289 {
7290 /* The lock is also used as a signal from the task initiator (which
7291 * releases it only after RTThreadCreate()) that we can start the job */
7292 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
7293
7294 PVBOXHDD hdd;
7295 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
7296 ComAssertRCThrow(vrc, E_FAIL);
7297
7298 Utf8Str format(m->strFormat);
7299 Utf8Str location(m->strLocationFull);
7300
7301 /* unlock before the potentially lengthy operation */
7302 Assert(m->state == MediumState_Deleting);
7303 thisLock.release();
7304
7305 try
7306 {
7307 vrc = VDOpen(hdd,
7308 format.c_str(),
7309 location.c_str(),
7310 VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO,
7311 m->vdImageIfaces);
7312 if (RT_SUCCESS(vrc))
7313 vrc = VDClose(hdd, true /* fDelete */);
7314
7315 if (RT_FAILURE(vrc))
7316 throw setError(VBOX_E_FILE_ERROR,
7317 tr("Could not delete the medium storage unit '%s'%s"),
7318 location.c_str(), vdError(vrc).c_str());
7319
7320 }
7321 catch (HRESULT aRC) { rc = aRC; }
7322
7323 VDDestroy(hdd);
7324 }
7325 catch (HRESULT aRC) { rc = aRC; }
7326
7327 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
7328
7329 /* go to the NotCreated state even on failure since the storage
7330 * may have been already partially deleted and cannot be used any
7331 * more. One will be able to manually re-open the storage if really
7332 * needed to re-register it. */
7333 m->state = MediumState_NotCreated;
7334
7335 /* Reset UUID to prevent Create* from reusing it again */
7336 unconst(m->id).clear();
7337
7338 return rc;
7339}
7340
7341/**
7342 * Implementation code for the "reset" task.
7343 *
7344 * This always gets started asynchronously from Medium::Reset().
7345 *
7346 * @param task
7347 * @return
7348 */
7349HRESULT Medium::taskResetHandler(Medium::ResetTask &task)
7350{
7351 HRESULT rc = S_OK;
7352
7353 uint64_t size = 0, logicalSize = 0;
7354 MediumVariant_T variant = MediumVariant_Standard;
7355
7356 try
7357 {
7358 /* The lock is also used as a signal from the task initiator (which
7359 * releases it only after RTThreadCreate()) that we can start the job */
7360 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
7361
7362 /// @todo Below we use a pair of delete/create operations to reset
7363 /// the diff contents but the most efficient way will of course be
7364 /// to add a VDResetDiff() API call
7365
7366 PVBOXHDD hdd;
7367 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
7368 ComAssertRCThrow(vrc, E_FAIL);
7369
7370 Guid id = m->id;
7371 Utf8Str format(m->strFormat);
7372 Utf8Str location(m->strLocationFull);
7373
7374 Medium *pParent = m->pParent;
7375 Guid parentId = pParent->m->id;
7376 Utf8Str parentFormat(pParent->m->strFormat);
7377 Utf8Str parentLocation(pParent->m->strLocationFull);
7378
7379 Assert(m->state == MediumState_LockedWrite);
7380
7381 /* unlock before the potentially lengthy operation */
7382 thisLock.release();
7383
7384 try
7385 {
7386 /* Open all media in the target chain but the last. */
7387 MediumLockList::Base::const_iterator targetListBegin =
7388 task.mpMediumLockList->GetBegin();
7389 MediumLockList::Base::const_iterator targetListEnd =
7390 task.mpMediumLockList->GetEnd();
7391 for (MediumLockList::Base::const_iterator it = targetListBegin;
7392 it != targetListEnd;
7393 ++it)
7394 {
7395 const MediumLock &mediumLock = *it;
7396 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
7397
7398 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
7399
7400 /* sanity check, "this" is checked above */
7401 Assert( pMedium == this
7402 || pMedium->m->state == MediumState_LockedRead);
7403
7404 /* Open all media in appropriate mode. */
7405 vrc = VDOpen(hdd,
7406 pMedium->m->strFormat.c_str(),
7407 pMedium->m->strLocationFull.c_str(),
7408 VD_OPEN_FLAGS_READONLY,
7409 pMedium->m->vdImageIfaces);
7410 if (RT_FAILURE(vrc))
7411 throw setError(VBOX_E_FILE_ERROR,
7412 tr("Could not open the medium storage unit '%s'%s"),
7413 pMedium->m->strLocationFull.c_str(),
7414 vdError(vrc).c_str());
7415
7416 /* Done when we hit the media which should be reset */
7417 if (pMedium == this)
7418 break;
7419 }
7420
7421 /* first, delete the storage unit */
7422 vrc = VDClose(hdd, true /* fDelete */);
7423 if (RT_FAILURE(vrc))
7424 throw setError(VBOX_E_FILE_ERROR,
7425 tr("Could not delete the medium storage unit '%s'%s"),
7426 location.c_str(), vdError(vrc).c_str());
7427
7428 /* next, create it again */
7429 vrc = VDOpen(hdd,
7430 parentFormat.c_str(),
7431 parentLocation.c_str(),
7432 VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO,
7433 m->vdImageIfaces);
7434 if (RT_FAILURE(vrc))
7435 throw setError(VBOX_E_FILE_ERROR,
7436 tr("Could not open the medium storage unit '%s'%s"),
7437 parentLocation.c_str(), vdError(vrc).c_str());
7438
7439 vrc = VDCreateDiff(hdd,
7440 format.c_str(),
7441 location.c_str(),
7442 /// @todo use the same medium variant as before
7443 VD_IMAGE_FLAGS_NONE,
7444 NULL,
7445 id.raw(),
7446 parentId.raw(),
7447 VD_OPEN_FLAGS_NORMAL,
7448 m->vdImageIfaces,
7449 task.mVDOperationIfaces);
7450 if (RT_FAILURE(vrc))
7451 throw setError(VBOX_E_FILE_ERROR,
7452 tr("Could not create the differencing medium storage unit '%s'%s"),
7453 location.c_str(), vdError(vrc).c_str());
7454
7455 size = VDGetFileSize(hdd, VD_LAST_IMAGE);
7456 logicalSize = VDGetSize(hdd, VD_LAST_IMAGE);
7457 unsigned uImageFlags;
7458 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
7459 if (RT_SUCCESS(vrc))
7460 variant = (MediumVariant_T)uImageFlags;
7461 }
7462 catch (HRESULT aRC) { rc = aRC; }
7463
7464 VDDestroy(hdd);
7465 }
7466 catch (HRESULT aRC) { rc = aRC; }
7467
7468 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
7469
7470 m->size = size;
7471 m->logicalSize = logicalSize;
7472 m->variant = variant;
7473
7474 if (task.isAsync())
7475 {
7476 /* unlock ourselves when done */
7477 HRESULT rc2 = UnlockWrite(NULL);
7478 AssertComRC(rc2);
7479 }
7480
7481 /* Note that in sync mode, it's the caller's responsibility to
7482 * unlock the medium. */
7483
7484 return rc;
7485}
7486
7487/**
7488 * Implementation code for the "compact" task.
7489 *
7490 * @param task
7491 * @return
7492 */
7493HRESULT Medium::taskCompactHandler(Medium::CompactTask &task)
7494{
7495 HRESULT rc = S_OK;
7496
7497 /* Lock all in {parent,child} order. The lock is also used as a
7498 * signal from the task initiator (which releases it only after
7499 * RTThreadCreate()) that we can start the job. */
7500 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
7501
7502 try
7503 {
7504 PVBOXHDD hdd;
7505 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
7506 ComAssertRCThrow(vrc, E_FAIL);
7507
7508 try
7509 {
7510 /* Open all media in the chain. */
7511 MediumLockList::Base::const_iterator mediumListBegin =
7512 task.mpMediumLockList->GetBegin();
7513 MediumLockList::Base::const_iterator mediumListEnd =
7514 task.mpMediumLockList->GetEnd();
7515 MediumLockList::Base::const_iterator mediumListLast =
7516 mediumListEnd;
7517 mediumListLast--;
7518 for (MediumLockList::Base::const_iterator it = mediumListBegin;
7519 it != mediumListEnd;
7520 ++it)
7521 {
7522 const MediumLock &mediumLock = *it;
7523 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
7524 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
7525
7526 /* sanity check */
7527 if (it == mediumListLast)
7528 Assert(pMedium->m->state == MediumState_LockedWrite);
7529 else
7530 Assert(pMedium->m->state == MediumState_LockedRead);
7531
7532 /* Open all media but last in read-only mode. Do not handle
7533 * shareable media, as compaction and sharing are mutually
7534 * exclusive. */
7535 vrc = VDOpen(hdd,
7536 pMedium->m->strFormat.c_str(),
7537 pMedium->m->strLocationFull.c_str(),
7538 (it == mediumListLast) ? VD_OPEN_FLAGS_NORMAL : VD_OPEN_FLAGS_READONLY,
7539 pMedium->m->vdImageIfaces);
7540 if (RT_FAILURE(vrc))
7541 throw setError(VBOX_E_FILE_ERROR,
7542 tr("Could not open the medium storage unit '%s'%s"),
7543 pMedium->m->strLocationFull.c_str(),
7544 vdError(vrc).c_str());
7545 }
7546
7547 Assert(m->state == MediumState_LockedWrite);
7548
7549 Utf8Str location(m->strLocationFull);
7550
7551 /* unlock before the potentially lengthy operation */
7552 thisLock.release();
7553
7554 vrc = VDCompact(hdd, VD_LAST_IMAGE, task.mVDOperationIfaces);
7555 if (RT_FAILURE(vrc))
7556 {
7557 if (vrc == VERR_NOT_SUPPORTED)
7558 throw setError(VBOX_E_NOT_SUPPORTED,
7559 tr("Compacting is not yet supported for medium '%s'"),
7560 location.c_str());
7561 else if (vrc == VERR_NOT_IMPLEMENTED)
7562 throw setError(E_NOTIMPL,
7563 tr("Compacting is not implemented, medium '%s'"),
7564 location.c_str());
7565 else
7566 throw setError(VBOX_E_FILE_ERROR,
7567 tr("Could not compact medium '%s'%s"),
7568 location.c_str(),
7569 vdError(vrc).c_str());
7570 }
7571 }
7572 catch (HRESULT aRC) { rc = aRC; }
7573
7574 VDDestroy(hdd);
7575 }
7576 catch (HRESULT aRC) { rc = aRC; }
7577
7578 /* Everything is explicitly unlocked when the task exits,
7579 * as the task destruction also destroys the media chain. */
7580
7581 return rc;
7582}
7583
7584/**
7585 * Implementation code for the "resize" task.
7586 *
7587 * @param task
7588 * @return
7589 */
7590HRESULT Medium::taskResizeHandler(Medium::ResizeTask &task)
7591{
7592 HRESULT rc = S_OK;
7593
7594 /* Lock all in {parent,child} order. The lock is also used as a
7595 * signal from the task initiator (which releases it only after
7596 * RTThreadCreate()) that we can start the job. */
7597 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
7598
7599 try
7600 {
7601 PVBOXHDD hdd;
7602 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
7603 ComAssertRCThrow(vrc, E_FAIL);
7604
7605 try
7606 {
7607 /* Open all media in the chain. */
7608 MediumLockList::Base::const_iterator mediumListBegin =
7609 task.mpMediumLockList->GetBegin();
7610 MediumLockList::Base::const_iterator mediumListEnd =
7611 task.mpMediumLockList->GetEnd();
7612 MediumLockList::Base::const_iterator mediumListLast =
7613 mediumListEnd;
7614 mediumListLast--;
7615 for (MediumLockList::Base::const_iterator it = mediumListBegin;
7616 it != mediumListEnd;
7617 ++it)
7618 {
7619 const MediumLock &mediumLock = *it;
7620 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
7621 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
7622
7623 /* sanity check */
7624 if (it == mediumListLast)
7625 Assert(pMedium->m->state == MediumState_LockedWrite);
7626 else
7627 Assert(pMedium->m->state == MediumState_LockedRead);
7628
7629 /* Open all media but last in read-only mode. Do not handle
7630 * shareable media, as compaction and sharing are mutually
7631 * exclusive. */
7632 vrc = VDOpen(hdd,
7633 pMedium->m->strFormat.c_str(),
7634 pMedium->m->strLocationFull.c_str(),
7635 (it == mediumListLast) ? VD_OPEN_FLAGS_NORMAL : VD_OPEN_FLAGS_READONLY,
7636 pMedium->m->vdImageIfaces);
7637 if (RT_FAILURE(vrc))
7638 throw setError(VBOX_E_FILE_ERROR,
7639 tr("Could not open the medium storage unit '%s'%s"),
7640 pMedium->m->strLocationFull.c_str(),
7641 vdError(vrc).c_str());
7642 }
7643
7644 Assert(m->state == MediumState_LockedWrite);
7645
7646 Utf8Str location(m->strLocationFull);
7647
7648 /* unlock before the potentially lengthy operation */
7649 thisLock.release();
7650
7651 VDGEOMETRY geo = {0, 0, 0}; /* auto */
7652 vrc = VDResize(hdd, task.mSize, &geo, &geo, task.mVDOperationIfaces);
7653 if (RT_FAILURE(vrc))
7654 {
7655 if (vrc == VERR_NOT_SUPPORTED)
7656 throw setError(VBOX_E_NOT_SUPPORTED,
7657 tr("Compacting is not yet supported for medium '%s'"),
7658 location.c_str());
7659 else if (vrc == VERR_NOT_IMPLEMENTED)
7660 throw setError(E_NOTIMPL,
7661 tr("Compacting is not implemented, medium '%s'"),
7662 location.c_str());
7663 else
7664 throw setError(VBOX_E_FILE_ERROR,
7665 tr("Could not compact medium '%s'%s"),
7666 location.c_str(),
7667 vdError(vrc).c_str());
7668 }
7669 }
7670 catch (HRESULT aRC) { rc = aRC; }
7671
7672 VDDestroy(hdd);
7673 }
7674 catch (HRESULT aRC) { rc = aRC; }
7675
7676 /* Everything is explicitly unlocked when the task exits,
7677 * as the task destruction also destroys the media chain. */
7678
7679 return rc;
7680}
7681
7682/**
7683 * Implementation code for the "export" task.
7684 *
7685 * This only gets started from Medium::exportFile() and always runs
7686 * asynchronously. It doesn't touch anything configuration related, so
7687 * we never save the VirtualBox.xml file here.
7688 *
7689 * @param task
7690 * @return
7691 */
7692HRESULT Medium::taskExportHandler(Medium::ExportTask &task)
7693{
7694 HRESULT rc = S_OK;
7695
7696 try
7697 {
7698 /* Lock all in {parent,child} order. The lock is also used as a
7699 * signal from the task initiator (which releases it only after
7700 * RTThreadCreate()) that we can start the job. */
7701 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
7702
7703 PVBOXHDD hdd;
7704 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
7705 ComAssertRCThrow(vrc, E_FAIL);
7706
7707 try
7708 {
7709 /* Open all media in the source chain. */
7710 MediumLockList::Base::const_iterator sourceListBegin =
7711 task.mpSourceMediumLockList->GetBegin();
7712 MediumLockList::Base::const_iterator sourceListEnd =
7713 task.mpSourceMediumLockList->GetEnd();
7714 for (MediumLockList::Base::const_iterator it = sourceListBegin;
7715 it != sourceListEnd;
7716 ++it)
7717 {
7718 const MediumLock &mediumLock = *it;
7719 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
7720 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
7721
7722 /* sanity check */
7723 Assert(pMedium->m->state == MediumState_LockedRead);
7724
7725 /* Open all media in read-only mode. */
7726 vrc = VDOpen(hdd,
7727 pMedium->m->strFormat.c_str(),
7728 pMedium->m->strLocationFull.c_str(),
7729 VD_OPEN_FLAGS_READONLY,
7730 pMedium->m->vdImageIfaces);
7731 if (RT_FAILURE(vrc))
7732 throw setError(VBOX_E_FILE_ERROR,
7733 tr("Could not open the medium storage unit '%s'%s"),
7734 pMedium->m->strLocationFull.c_str(),
7735 vdError(vrc).c_str());
7736 }
7737
7738 Utf8Str targetFormat(task.mFormat->getId());
7739 Utf8Str targetLocation(task.mFilename);
7740 uint64_t capabilities = task.mFormat->getCapabilities();
7741
7742 Assert(m->state == MediumState_LockedRead);
7743
7744 /* unlock before the potentially lengthy operation */
7745 thisLock.release();
7746
7747 /* ensure the target directory exists */
7748 if (capabilities & MediumFormatCapabilities_File)
7749 {
7750 rc = VirtualBox::ensureFilePathExists(targetLocation);
7751 if (FAILED(rc))
7752 throw rc;
7753 }
7754
7755 PVBOXHDD targetHdd;
7756 vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &targetHdd);
7757 ComAssertRCThrow(vrc, E_FAIL);
7758
7759 try
7760 {
7761 vrc = VDCopy(hdd,
7762 VD_LAST_IMAGE,
7763 targetHdd,
7764 targetFormat.c_str(),
7765 targetLocation.c_str(),
7766 false /* fMoveByRename */,
7767 0 /* cbSize */,
7768 task.mVariant,
7769 NULL /* pDstUuid */,
7770 VD_OPEN_FLAGS_NORMAL | VD_OPEN_FLAGS_SEQUENTIAL,
7771 NULL /* pVDIfsOperation */,
7772 task.mVDImageIfaces,
7773 task.mVDOperationIfaces);
7774 if (RT_FAILURE(vrc))
7775 throw setError(VBOX_E_FILE_ERROR,
7776 tr("Could not create the clone medium '%s'%s"),
7777 targetLocation.c_str(), vdError(vrc).c_str());
7778 }
7779 catch (HRESULT aRC) { rc = aRC; }
7780
7781 VDDestroy(targetHdd);
7782 }
7783 catch (HRESULT aRC) { rc = aRC; }
7784
7785 VDDestroy(hdd);
7786 }
7787 catch (HRESULT aRC) { rc = aRC; }
7788
7789 /* Everything is explicitly unlocked when the task exits,
7790 * as the task destruction also destroys the source chain. */
7791
7792 /* Make sure the source chain is released early, otherwise it can
7793 * lead to deadlocks with concurrent IAppliance activities. */
7794 task.mpSourceMediumLockList->Clear();
7795
7796 return rc;
7797}
7798
7799/**
7800 * Implementation code for the "import" task.
7801 *
7802 * This only gets started from Medium::importFile() and always runs
7803 * asynchronously. It potentially touches the media registry, so we
7804 * always save the VirtualBox.xml file when we're done here.
7805 *
7806 * @param task
7807 * @return
7808 */
7809HRESULT Medium::taskImportHandler(Medium::ImportTask &task)
7810{
7811 HRESULT rcTmp = S_OK;
7812
7813 const ComObjPtr<Medium> &pParent = task.mParent;
7814
7815 bool fCreatingTarget = false;
7816
7817 uint64_t size = 0, logicalSize = 0;
7818 MediumVariant_T variant = MediumVariant_Standard;
7819 bool fGenerateUuid = false;
7820
7821 try
7822 {
7823 /* Lock all in {parent,child} order. The lock is also used as a
7824 * signal from the task initiator (which releases it only after
7825 * RTThreadCreate()) that we can start the job. */
7826 AutoMultiWriteLock2 thisLock(this, pParent COMMA_LOCKVAL_SRC_POS);
7827
7828 fCreatingTarget = m->state == MediumState_Creating;
7829
7830 /* The object may request a specific UUID (through a special form of
7831 * the setLocation() argument). Otherwise we have to generate it */
7832 Guid targetId = m->id;
7833 fGenerateUuid = targetId.isEmpty();
7834 if (fGenerateUuid)
7835 {
7836 targetId.create();
7837 /* VirtualBox::registerHardDisk() will need UUID */
7838 unconst(m->id) = targetId;
7839 }
7840
7841
7842 PVBOXHDD hdd;
7843 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
7844 ComAssertRCThrow(vrc, E_FAIL);
7845
7846 try
7847 {
7848 /* Open source medium. */
7849 vrc = VDOpen(hdd,
7850 task.mFormat->getId().c_str(),
7851 task.mFilename.c_str(),
7852 VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_SEQUENTIAL,
7853 task.mVDImageIfaces);
7854 if (RT_FAILURE(vrc))
7855 throw setError(VBOX_E_FILE_ERROR,
7856 tr("Could not open the medium storage unit '%s'%s"),
7857 task.mFilename.c_str(),
7858 vdError(vrc).c_str());
7859
7860 Utf8Str targetFormat(m->strFormat);
7861 Utf8Str targetLocation(m->strLocationFull);
7862 uint64_t capabilities = task.mFormat->getCapabilities();
7863
7864 Assert( m->state == MediumState_Creating
7865 || m->state == MediumState_LockedWrite);
7866 Assert( pParent.isNull()
7867 || pParent->m->state == MediumState_LockedRead);
7868
7869 /* unlock before the potentially lengthy operation */
7870 thisLock.release();
7871
7872 /* ensure the target directory exists */
7873 if (capabilities & MediumFormatCapabilities_File)
7874 {
7875 HRESULT rc = VirtualBox::ensureFilePathExists(targetLocation);
7876 if (FAILED(rc))
7877 throw rc;
7878 }
7879
7880 PVBOXHDD targetHdd;
7881 vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &targetHdd);
7882 ComAssertRCThrow(vrc, E_FAIL);
7883
7884 try
7885 {
7886 /* Open all media in the target chain. */
7887 MediumLockList::Base::const_iterator targetListBegin =
7888 task.mpTargetMediumLockList->GetBegin();
7889 MediumLockList::Base::const_iterator targetListEnd =
7890 task.mpTargetMediumLockList->GetEnd();
7891 for (MediumLockList::Base::const_iterator it = targetListBegin;
7892 it != targetListEnd;
7893 ++it)
7894 {
7895 const MediumLock &mediumLock = *it;
7896 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
7897
7898 /* If the target medium is not created yet there's no
7899 * reason to open it. */
7900 if (pMedium == this && fCreatingTarget)
7901 continue;
7902
7903 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
7904
7905 /* sanity check */
7906 Assert( pMedium->m->state == MediumState_LockedRead
7907 || pMedium->m->state == MediumState_LockedWrite);
7908
7909 unsigned uOpenFlags = VD_OPEN_FLAGS_NORMAL;
7910 if (pMedium->m->state != MediumState_LockedWrite)
7911 uOpenFlags = VD_OPEN_FLAGS_READONLY;
7912 if (pMedium->m->type == MediumType_Shareable)
7913 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
7914
7915 /* Open all media in appropriate mode. */
7916 vrc = VDOpen(targetHdd,
7917 pMedium->m->strFormat.c_str(),
7918 pMedium->m->strLocationFull.c_str(),
7919 uOpenFlags,
7920 pMedium->m->vdImageIfaces);
7921 if (RT_FAILURE(vrc))
7922 throw setError(VBOX_E_FILE_ERROR,
7923 tr("Could not open the medium storage unit '%s'%s"),
7924 pMedium->m->strLocationFull.c_str(),
7925 vdError(vrc).c_str());
7926 }
7927
7928 /** @todo r=klaus target isn't locked, race getting the state */
7929 vrc = VDCopy(hdd,
7930 VD_LAST_IMAGE,
7931 targetHdd,
7932 targetFormat.c_str(),
7933 (fCreatingTarget) ? targetLocation.c_str() : (char *)NULL,
7934 false /* fMoveByRename */,
7935 0 /* cbSize */,
7936 task.mVariant,
7937 targetId.raw(),
7938 VD_OPEN_FLAGS_NORMAL,
7939 NULL /* pVDIfsOperation */,
7940 m->vdImageIfaces,
7941 task.mVDOperationIfaces);
7942 if (RT_FAILURE(vrc))
7943 throw setError(VBOX_E_FILE_ERROR,
7944 tr("Could not create the clone medium '%s'%s"),
7945 targetLocation.c_str(), vdError(vrc).c_str());
7946
7947 size = VDGetFileSize(targetHdd, VD_LAST_IMAGE);
7948 logicalSize = VDGetSize(targetHdd, VD_LAST_IMAGE);
7949 unsigned uImageFlags;
7950 vrc = VDGetImageFlags(targetHdd, 0, &uImageFlags);
7951 if (RT_SUCCESS(vrc))
7952 variant = (MediumVariant_T)uImageFlags;
7953 }
7954 catch (HRESULT aRC) { rcTmp = aRC; }
7955
7956 VDDestroy(targetHdd);
7957 }
7958 catch (HRESULT aRC) { rcTmp = aRC; }
7959
7960 VDDestroy(hdd);
7961 }
7962 catch (HRESULT aRC) { rcTmp = aRC; }
7963
7964 ErrorInfoKeeper eik;
7965 MultiResult mrc(rcTmp);
7966
7967 /* Only do the parent changes for newly created media. */
7968 if (SUCCEEDED(mrc) && fCreatingTarget)
7969 {
7970 /* we set mParent & children() */
7971 AutoWriteLock alock2(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
7972
7973 Assert(m->pParent.isNull());
7974
7975 if (pParent)
7976 {
7977 /* associate the clone with the parent and deassociate
7978 * from VirtualBox */
7979 m->pParent = pParent;
7980 pParent->m->llChildren.push_back(this);
7981
7982 /* register with mVirtualBox as the last step and move to
7983 * Created state only on success (leaving an orphan file is
7984 * better than breaking media registry consistency) */
7985 eik.restore();
7986 mrc = pParent->m->pVirtualBox->registerHardDisk(this, NULL /* llRegistriesThatNeedSaving */);
7987 eik.fetch();
7988
7989 if (FAILED(mrc))
7990 /* break parent association on failure to register */
7991 this->deparent(); // removes target from parent
7992 }
7993 else
7994 {
7995 /* just register */
7996 eik.restore();
7997 mrc = m->pVirtualBox->registerHardDisk(this, NULL /* pllRegistriesThatNeedSaving */);
7998 eik.fetch();
7999 }
8000 }
8001
8002 if (fCreatingTarget)
8003 {
8004 AutoWriteLock mLock(this COMMA_LOCKVAL_SRC_POS);
8005
8006 if (SUCCEEDED(mrc))
8007 {
8008 m->state = MediumState_Created;
8009
8010 m->size = size;
8011 m->logicalSize = logicalSize;
8012 m->variant = variant;
8013 }
8014 else
8015 {
8016 /* back to NotCreated on failure */
8017 m->state = MediumState_NotCreated;
8018
8019 /* reset UUID to prevent it from being reused next time */
8020 if (fGenerateUuid)
8021 unconst(m->id).clear();
8022 }
8023 }
8024
8025 // now, at the end of this task (always asynchronous), save the settings
8026 {
8027 // save the settings
8028 GuidList llRegistriesThatNeedSaving;
8029 addToRegistryIDList(llRegistriesThatNeedSaving);
8030 /* collect multiple errors */
8031 eik.restore();
8032 mrc = m->pVirtualBox->saveRegistries(llRegistriesThatNeedSaving);
8033 eik.fetch();
8034 }
8035
8036 /* Everything is explicitly unlocked when the task exits,
8037 * as the task destruction also destroys the target chain. */
8038
8039 /* Make sure the target chain is released early, otherwise it can
8040 * lead to deadlocks with concurrent IAppliance activities. */
8041 task.mpTargetMediumLockList->Clear();
8042
8043 return mrc;
8044}
8045
8046/* vi: set tabstop=4 shiftwidth=4 expandtab: */
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette