VirtualBox

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

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

Main/Machine+Medium: fix medium registry association when attaching a device or mounting a medium, when there is a chain of parent images which are not associated with any media registry, including the necessary locking adjustments

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 267.3 KB
Line 
1/* $Id: MediumImpl.cpp 38499 2011-08-19 12:02:55Z 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.virtualbox.org. 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
1768 AutoCaller autoCaller(this);
1769 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1770
1771 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1772
1773 ReturnComNotImplemented();
1774}
1775
1776STDMETHODIMP Medium::COMGETTER(Parent)(IMedium **aParent)
1777{
1778 CheckComArgOutPointerValid(aParent);
1779
1780 AutoCaller autoCaller(this);
1781 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1782
1783 /* we access mParent */
1784 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
1785
1786 m->pParent.queryInterfaceTo(aParent);
1787
1788 return S_OK;
1789}
1790
1791STDMETHODIMP Medium::COMGETTER(Children)(ComSafeArrayOut(IMedium *, aChildren))
1792{
1793 CheckComArgOutSafeArrayPointerValid(aChildren);
1794
1795 AutoCaller autoCaller(this);
1796 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1797
1798 /* we access children */
1799 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
1800
1801 SafeIfaceArray<IMedium> children(this->getChildren());
1802 children.detachTo(ComSafeArrayOutArg(aChildren));
1803
1804 return S_OK;
1805}
1806
1807STDMETHODIMP Medium::COMGETTER(Base)(IMedium **aBase)
1808{
1809 CheckComArgOutPointerValid(aBase);
1810
1811 /* base() will do callers/locking */
1812
1813 getBase().queryInterfaceTo(aBase);
1814
1815 return S_OK;
1816}
1817
1818STDMETHODIMP Medium::COMGETTER(ReadOnly)(BOOL *aReadOnly)
1819{
1820 CheckComArgOutPointerValid(aReadOnly);
1821
1822 AutoCaller autoCaller(this);
1823 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1824
1825 /* isReadOnly() will do locking */
1826
1827 *aReadOnly = isReadOnly();
1828
1829 return S_OK;
1830}
1831
1832STDMETHODIMP Medium::COMGETTER(LogicalSize)(LONG64 *aLogicalSize)
1833{
1834 CheckComArgOutPointerValid(aLogicalSize);
1835
1836 {
1837 AutoCaller autoCaller(this);
1838 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1839
1840 /* we access mParent */
1841 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
1842
1843 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1844
1845 if (m->pParent.isNull())
1846 {
1847 *aLogicalSize = m->logicalSize;
1848
1849 return S_OK;
1850 }
1851 }
1852
1853 /* We assume that some backend may decide to return a meaningless value in
1854 * response to VDGetSize() for differencing media and therefore always
1855 * ask the base medium ourselves. */
1856
1857 /* base() will do callers/locking */
1858
1859 return getBase()->COMGETTER(LogicalSize)(aLogicalSize);
1860}
1861
1862STDMETHODIMP Medium::COMGETTER(AutoReset)(BOOL *aAutoReset)
1863{
1864 CheckComArgOutPointerValid(aAutoReset);
1865
1866 AutoCaller autoCaller(this);
1867 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1868
1869 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1870
1871 if (m->pParent.isNull())
1872 *aAutoReset = FALSE;
1873 else
1874 *aAutoReset = m->autoReset;
1875
1876 return S_OK;
1877}
1878
1879STDMETHODIMP Medium::COMSETTER(AutoReset)(BOOL aAutoReset)
1880{
1881 AutoCaller autoCaller(this);
1882 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1883
1884 AutoWriteLock mlock(this COMMA_LOCKVAL_SRC_POS);
1885
1886 if (m->pParent.isNull())
1887 return setError(VBOX_E_NOT_SUPPORTED,
1888 tr("Medium '%s' is not differencing"),
1889 m->strLocationFull.c_str());
1890
1891 HRESULT rc = S_OK;
1892
1893 if (m->autoReset != !!aAutoReset)
1894 {
1895 m->autoReset = !!aAutoReset;
1896
1897 // save the settings
1898 GuidList llRegistriesThatNeedSaving;
1899 addToRegistryIDList(llRegistriesThatNeedSaving);
1900 mlock.release();
1901 rc = m->pVirtualBox->saveRegistries(llRegistriesThatNeedSaving);
1902 }
1903
1904 return rc;
1905}
1906
1907STDMETHODIMP Medium::COMGETTER(LastAccessError)(BSTR *aLastAccessError)
1908{
1909 CheckComArgOutPointerValid(aLastAccessError);
1910
1911 AutoCaller autoCaller(this);
1912 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1913
1914 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1915
1916 m->strLastAccessError.cloneTo(aLastAccessError);
1917
1918 return S_OK;
1919}
1920
1921STDMETHODIMP Medium::COMGETTER(MachineIds)(ComSafeArrayOut(BSTR,aMachineIds))
1922{
1923 CheckComArgOutSafeArrayPointerValid(aMachineIds);
1924
1925 AutoCaller autoCaller(this);
1926 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1927
1928 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1929
1930 com::SafeArray<BSTR> machineIds;
1931
1932 if (m->backRefs.size() != 0)
1933 {
1934 machineIds.reset(m->backRefs.size());
1935
1936 size_t i = 0;
1937 for (BackRefList::const_iterator it = m->backRefs.begin();
1938 it != m->backRefs.end(); ++it, ++i)
1939 {
1940 it->machineId.toUtf16().detachTo(&machineIds[i]);
1941 }
1942 }
1943
1944 machineIds.detachTo(ComSafeArrayOutArg(aMachineIds));
1945
1946 return S_OK;
1947}
1948
1949STDMETHODIMP Medium::SetIDs(BOOL aSetImageId,
1950 IN_BSTR aImageId,
1951 BOOL aSetParentId,
1952 IN_BSTR aParentId)
1953{
1954 AutoCaller autoCaller(this);
1955 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1956
1957 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1958
1959 switch (m->state)
1960 {
1961 case MediumState_Created:
1962 break;
1963 default:
1964 return setStateError();
1965 }
1966
1967 Guid imageId, parentId;
1968 if (aSetImageId)
1969 {
1970 if (Bstr(aImageId).isEmpty())
1971 imageId.create();
1972 else
1973 {
1974 imageId = Guid(aImageId);
1975 if (imageId.isEmpty())
1976 return setError(E_INVALIDARG, tr("Argument %s is empty"), "aImageId");
1977 }
1978 }
1979 if (aSetParentId)
1980 {
1981 if (Bstr(aParentId).isEmpty())
1982 parentId.create();
1983 else
1984 parentId = Guid(aParentId);
1985 }
1986
1987 unconst(m->uuidImage) = imageId;
1988 unconst(m->uuidParentImage) = parentId;
1989
1990 HRESULT rc = queryInfo(!!aSetImageId /* fSetImageId */,
1991 !!aSetParentId /* fSetParentId */);
1992
1993 return rc;
1994}
1995
1996STDMETHODIMP Medium::RefreshState(MediumState_T *aState)
1997{
1998 CheckComArgOutPointerValid(aState);
1999
2000 AutoCaller autoCaller(this);
2001 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2002
2003 /* queryInfo() locks this for writing. */
2004 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2005
2006 HRESULT rc = S_OK;
2007
2008 switch (m->state)
2009 {
2010 case MediumState_Created:
2011 case MediumState_Inaccessible:
2012 case MediumState_LockedRead:
2013 {
2014 rc = queryInfo(false /* fSetImageId */, false /* fSetParentId */);
2015 break;
2016 }
2017 default:
2018 break;
2019 }
2020
2021 *aState = m->state;
2022
2023 return rc;
2024}
2025
2026STDMETHODIMP Medium::GetSnapshotIds(IN_BSTR aMachineId,
2027 ComSafeArrayOut(BSTR, aSnapshotIds))
2028{
2029 CheckComArgExpr(aMachineId, Guid(aMachineId).isEmpty() == false);
2030 CheckComArgOutSafeArrayPointerValid(aSnapshotIds);
2031
2032 AutoCaller autoCaller(this);
2033 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2034
2035 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2036
2037 com::SafeArray<BSTR> snapshotIds;
2038
2039 Guid id(aMachineId);
2040 for (BackRefList::const_iterator it = m->backRefs.begin();
2041 it != m->backRefs.end(); ++it)
2042 {
2043 if (it->machineId == id)
2044 {
2045 size_t size = it->llSnapshotIds.size();
2046
2047 /* if the medium is attached to the machine in the current state, we
2048 * return its ID as the first element of the array */
2049 if (it->fInCurState)
2050 ++size;
2051
2052 if (size > 0)
2053 {
2054 snapshotIds.reset(size);
2055
2056 size_t j = 0;
2057 if (it->fInCurState)
2058 it->machineId.toUtf16().detachTo(&snapshotIds[j++]);
2059
2060 for (GuidList::const_iterator jt = it->llSnapshotIds.begin();
2061 jt != it->llSnapshotIds.end();
2062 ++jt, ++j)
2063 {
2064 (*jt).toUtf16().detachTo(&snapshotIds[j]);
2065 }
2066 }
2067
2068 break;
2069 }
2070 }
2071
2072 snapshotIds.detachTo(ComSafeArrayOutArg(aSnapshotIds));
2073
2074 return S_OK;
2075}
2076
2077/**
2078 * @note @a aState may be NULL if the state value is not needed (only for
2079 * in-process calls).
2080 */
2081STDMETHODIMP Medium::LockRead(MediumState_T *aState)
2082{
2083 AutoCaller autoCaller(this);
2084 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2085
2086 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2087
2088 /* Wait for a concurrently running queryInfo() to complete */
2089 while (m->queryInfoRunning)
2090 {
2091 alock.leave();
2092 RTSemEventMultiWait(m->queryInfoSem, RT_INDEFINITE_WAIT);
2093 alock.enter();
2094 }
2095
2096 /* return the current state before */
2097 if (aState)
2098 *aState = m->state;
2099
2100 HRESULT rc = S_OK;
2101
2102 switch (m->state)
2103 {
2104 case MediumState_Created:
2105 case MediumState_Inaccessible:
2106 case MediumState_LockedRead:
2107 {
2108 ++m->readers;
2109
2110 ComAssertMsgBreak(m->readers != 0, ("Counter overflow"), rc = E_FAIL);
2111
2112 /* Remember pre-lock state */
2113 if (m->state != MediumState_LockedRead)
2114 m->preLockState = m->state;
2115
2116 LogFlowThisFunc(("Okay - prev state=%d readers=%d\n", m->state, m->readers));
2117 m->state = MediumState_LockedRead;
2118
2119 break;
2120 }
2121 default:
2122 {
2123 LogFlowThisFunc(("Failing - state=%d\n", m->state));
2124 rc = setStateError();
2125 break;
2126 }
2127 }
2128
2129 return rc;
2130}
2131
2132/**
2133 * @note @a aState may be NULL if the state value is not needed (only for
2134 * in-process calls).
2135 */
2136STDMETHODIMP Medium::UnlockRead(MediumState_T *aState)
2137{
2138 AutoCaller autoCaller(this);
2139 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2140
2141 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2142
2143 HRESULT rc = S_OK;
2144
2145 switch (m->state)
2146 {
2147 case MediumState_LockedRead:
2148 {
2149 Assert(m->readers != 0);
2150 --m->readers;
2151
2152 /* Reset the state after the last reader */
2153 if (m->readers == 0)
2154 {
2155 m->state = m->preLockState;
2156 /* There are cases where we inject the deleting state into
2157 * a medium locked for reading. Make sure #unmarkForDeletion()
2158 * gets the right state afterwards. */
2159 if (m->preLockState == MediumState_Deleting)
2160 m->preLockState = MediumState_Created;
2161 }
2162
2163 LogFlowThisFunc(("new state=%d\n", m->state));
2164 break;
2165 }
2166 default:
2167 {
2168 LogFlowThisFunc(("Failing - state=%d\n", m->state));
2169 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
2170 tr("Medium '%s' is not locked for reading"),
2171 m->strLocationFull.c_str());
2172 break;
2173 }
2174 }
2175
2176 /* return the current state after */
2177 if (aState)
2178 *aState = m->state;
2179
2180 return rc;
2181}
2182
2183/**
2184 * @note @a aState may be NULL if the state value is not needed (only for
2185 * in-process calls).
2186 */
2187STDMETHODIMP Medium::LockWrite(MediumState_T *aState)
2188{
2189 AutoCaller autoCaller(this);
2190 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2191
2192 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2193
2194 /* Wait for a concurrently running queryInfo() to complete */
2195 while (m->queryInfoRunning)
2196 {
2197 alock.leave();
2198 RTSemEventMultiWait(m->queryInfoSem, RT_INDEFINITE_WAIT);
2199 alock.enter();
2200 }
2201
2202 /* return the current state before */
2203 if (aState)
2204 *aState = m->state;
2205
2206 HRESULT rc = S_OK;
2207
2208 switch (m->state)
2209 {
2210 case MediumState_Created:
2211 case MediumState_Inaccessible:
2212 {
2213 m->preLockState = m->state;
2214
2215 LogFlowThisFunc(("Okay - prev state=%d locationFull=%s\n", m->state, getLocationFull().c_str()));
2216 m->state = MediumState_LockedWrite;
2217 break;
2218 }
2219 default:
2220 {
2221 LogFlowThisFunc(("Failing - state=%d locationFull=%s\n", m->state, getLocationFull().c_str()));
2222 rc = setStateError();
2223 break;
2224 }
2225 }
2226
2227 return rc;
2228}
2229
2230/**
2231 * @note @a aState may be NULL if the state value is not needed (only for
2232 * in-process calls).
2233 */
2234STDMETHODIMP Medium::UnlockWrite(MediumState_T *aState)
2235{
2236 AutoCaller autoCaller(this);
2237 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2238
2239 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2240
2241 HRESULT rc = S_OK;
2242
2243 switch (m->state)
2244 {
2245 case MediumState_LockedWrite:
2246 {
2247 m->state = m->preLockState;
2248 /* There are cases where we inject the deleting state into
2249 * a medium locked for writing. Make sure #unmarkForDeletion()
2250 * gets the right state afterwards. */
2251 if (m->preLockState == MediumState_Deleting)
2252 m->preLockState = MediumState_Created;
2253 LogFlowThisFunc(("new state=%d locationFull=%s\n", m->state, getLocationFull().c_str()));
2254 break;
2255 }
2256 default:
2257 {
2258 LogFlowThisFunc(("Failing - state=%d locationFull=%s\n", m->state, getLocationFull().c_str()));
2259 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
2260 tr("Medium '%s' is not locked for writing"),
2261 m->strLocationFull.c_str());
2262 break;
2263 }
2264 }
2265
2266 /* return the current state after */
2267 if (aState)
2268 *aState = m->state;
2269
2270 return rc;
2271}
2272
2273STDMETHODIMP Medium::Close()
2274{
2275 AutoCaller autoCaller(this);
2276 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2277
2278 // make a copy of VirtualBox pointer which gets nulled by uninit()
2279 ComObjPtr<VirtualBox> pVirtualBox(m->pVirtualBox);
2280
2281 GuidList llRegistriesThatNeedSaving;
2282 MultiResult mrc = close(&llRegistriesThatNeedSaving, autoCaller);
2283 /* Must save the registries, since an entry was most likely removed. */
2284 mrc = pVirtualBox->saveRegistries(llRegistriesThatNeedSaving);
2285
2286 return mrc;
2287}
2288
2289STDMETHODIMP Medium::GetProperty(IN_BSTR aName, BSTR *aValue)
2290{
2291 CheckComArgStrNotEmptyOrNull(aName);
2292 CheckComArgOutPointerValid(aValue);
2293
2294 AutoCaller autoCaller(this);
2295 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2296
2297 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2298
2299 settings::StringsMap::const_iterator it = m->mapProperties.find(Utf8Str(aName));
2300 if (it == m->mapProperties.end())
2301 return setError(VBOX_E_OBJECT_NOT_FOUND,
2302 tr("Property '%ls' does not exist"), aName);
2303
2304 it->second.cloneTo(aValue);
2305
2306 return S_OK;
2307}
2308
2309STDMETHODIMP Medium::SetProperty(IN_BSTR aName, IN_BSTR aValue)
2310{
2311 CheckComArgStrNotEmptyOrNull(aName);
2312
2313 AutoCaller autoCaller(this);
2314 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2315
2316 AutoWriteLock mlock(this COMMA_LOCKVAL_SRC_POS);
2317
2318 switch (m->state)
2319 {
2320 case MediumState_Created:
2321 case MediumState_Inaccessible:
2322 break;
2323 default:
2324 return setStateError();
2325 }
2326
2327 settings::StringsMap::iterator it = m->mapProperties.find(Utf8Str(aName));
2328 if (it == m->mapProperties.end())
2329 return setError(VBOX_E_OBJECT_NOT_FOUND,
2330 tr("Property '%ls' does not exist"),
2331 aName);
2332
2333 it->second = aValue;
2334
2335 // save the settings
2336 GuidList llRegistriesThatNeedSaving;
2337 addToRegistryIDList(llRegistriesThatNeedSaving);
2338 mlock.release();
2339 HRESULT rc = m->pVirtualBox->saveRegistries(llRegistriesThatNeedSaving);
2340
2341 return rc;
2342}
2343
2344STDMETHODIMP Medium::GetProperties(IN_BSTR aNames,
2345 ComSafeArrayOut(BSTR, aReturnNames),
2346 ComSafeArrayOut(BSTR, aReturnValues))
2347{
2348 CheckComArgOutSafeArrayPointerValid(aReturnNames);
2349 CheckComArgOutSafeArrayPointerValid(aReturnValues);
2350
2351 AutoCaller autoCaller(this);
2352 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2353
2354 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2355
2356 /// @todo make use of aNames according to the documentation
2357 NOREF(aNames);
2358
2359 com::SafeArray<BSTR> names(m->mapProperties.size());
2360 com::SafeArray<BSTR> values(m->mapProperties.size());
2361 size_t i = 0;
2362
2363 for (settings::StringsMap::const_iterator it = m->mapProperties.begin();
2364 it != m->mapProperties.end();
2365 ++it)
2366 {
2367 it->first.cloneTo(&names[i]);
2368 it->second.cloneTo(&values[i]);
2369 ++i;
2370 }
2371
2372 names.detachTo(ComSafeArrayOutArg(aReturnNames));
2373 values.detachTo(ComSafeArrayOutArg(aReturnValues));
2374
2375 return S_OK;
2376}
2377
2378STDMETHODIMP Medium::SetProperties(ComSafeArrayIn(IN_BSTR, aNames),
2379 ComSafeArrayIn(IN_BSTR, aValues))
2380{
2381 CheckComArgSafeArrayNotNull(aNames);
2382 CheckComArgSafeArrayNotNull(aValues);
2383
2384 AutoCaller autoCaller(this);
2385 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2386
2387 AutoWriteLock mlock(this COMMA_LOCKVAL_SRC_POS);
2388
2389 com::SafeArray<IN_BSTR> names(ComSafeArrayInArg(aNames));
2390 com::SafeArray<IN_BSTR> values(ComSafeArrayInArg(aValues));
2391
2392 /* first pass: validate names */
2393 for (size_t i = 0;
2394 i < names.size();
2395 ++i)
2396 {
2397 if (m->mapProperties.find(Utf8Str(names[i])) == m->mapProperties.end())
2398 return setError(VBOX_E_OBJECT_NOT_FOUND,
2399 tr("Property '%ls' does not exist"), names[i]);
2400 }
2401
2402 /* second pass: assign */
2403 for (size_t i = 0;
2404 i < names.size();
2405 ++i)
2406 {
2407 settings::StringsMap::iterator it = m->mapProperties.find(Utf8Str(names[i]));
2408 AssertReturn(it != m->mapProperties.end(), E_FAIL);
2409
2410 it->second = Utf8Str(values[i]);
2411 }
2412
2413 // save the settings
2414 GuidList llRegistriesThatNeedSaving;
2415 addToRegistryIDList(llRegistriesThatNeedSaving);
2416 mlock.release();
2417 HRESULT rc = m->pVirtualBox->saveRegistries(llRegistriesThatNeedSaving);
2418
2419 return rc;
2420}
2421
2422STDMETHODIMP Medium::CreateBaseStorage(LONG64 aLogicalSize,
2423 ULONG aVariant,
2424 IProgress **aProgress)
2425{
2426 CheckComArgOutPointerValid(aProgress);
2427 if (aLogicalSize < 0)
2428 return setError(E_INVALIDARG, tr("The medium size argument (%lld) is negative"), aLogicalSize);
2429
2430 AutoCaller autoCaller(this);
2431 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2432
2433 HRESULT rc = S_OK;
2434 ComObjPtr <Progress> pProgress;
2435 Medium::Task *pTask = NULL;
2436
2437 try
2438 {
2439 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2440
2441 aVariant = (MediumVariant_T)((unsigned)aVariant & (unsigned)~MediumVariant_Diff);
2442 if ( !(aVariant & MediumVariant_Fixed)
2443 && !(m->formatObj->getCapabilities() & MediumFormatCapabilities_CreateDynamic))
2444 throw setError(VBOX_E_NOT_SUPPORTED,
2445 tr("Medium format '%s' does not support dynamic storage creation"),
2446 m->strFormat.c_str());
2447 if ( (aVariant & MediumVariant_Fixed)
2448 && !(m->formatObj->getCapabilities() & MediumFormatCapabilities_CreateDynamic))
2449 throw setError(VBOX_E_NOT_SUPPORTED,
2450 tr("Medium format '%s' does not support fixed storage creation"),
2451 m->strFormat.c_str());
2452
2453 if (m->state != MediumState_NotCreated)
2454 throw setStateError();
2455
2456 pProgress.createObject();
2457 rc = pProgress->init(m->pVirtualBox,
2458 static_cast<IMedium*>(this),
2459 (aVariant & MediumVariant_Fixed)
2460 ? BstrFmt(tr("Creating fixed medium storage unit '%s'"), m->strLocationFull.c_str()).raw()
2461 : BstrFmt(tr("Creating dynamic medium storage unit '%s'"), m->strLocationFull.c_str()).raw(),
2462 TRUE /* aCancelable */);
2463 if (FAILED(rc))
2464 throw rc;
2465
2466 /* setup task object to carry out the operation asynchronously */
2467 pTask = new Medium::CreateBaseTask(this, pProgress, aLogicalSize,
2468 (MediumVariant_T)aVariant);
2469 rc = pTask->rc();
2470 AssertComRC(rc);
2471 if (FAILED(rc))
2472 throw rc;
2473
2474 m->state = MediumState_Creating;
2475 }
2476 catch (HRESULT aRC) { rc = aRC; }
2477
2478 if (SUCCEEDED(rc))
2479 {
2480 rc = startThread(pTask);
2481
2482 if (SUCCEEDED(rc))
2483 pProgress.queryInterfaceTo(aProgress);
2484 }
2485 else if (pTask != NULL)
2486 delete pTask;
2487
2488 return rc;
2489}
2490
2491STDMETHODIMP Medium::DeleteStorage(IProgress **aProgress)
2492{
2493 CheckComArgOutPointerValid(aProgress);
2494
2495 AutoCaller autoCaller(this);
2496 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2497
2498 ComObjPtr<Progress> pProgress;
2499
2500 GuidList llRegistriesThatNeedSaving;
2501 MultiResult mrc = deleteStorage(&pProgress,
2502 false /* aWait */,
2503 &llRegistriesThatNeedSaving);
2504 /* Must save the registries in any case, since an entry was removed. */
2505 mrc = m->pVirtualBox->saveRegistries(llRegistriesThatNeedSaving);
2506
2507 if (SUCCEEDED(mrc))
2508 pProgress.queryInterfaceTo(aProgress);
2509
2510 return mrc;
2511}
2512
2513STDMETHODIMP Medium::CreateDiffStorage(IMedium *aTarget,
2514 ULONG aVariant,
2515 IProgress **aProgress)
2516{
2517 CheckComArgNotNull(aTarget);
2518 CheckComArgOutPointerValid(aProgress);
2519
2520 AutoCaller autoCaller(this);
2521 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2522
2523 ComObjPtr<Medium> diff = static_cast<Medium*>(aTarget);
2524
2525 // locking: we need the tree lock first because we access parent pointers
2526 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
2527 AutoMultiWriteLock2 alock(this, diff COMMA_LOCKVAL_SRC_POS);
2528
2529 if (m->type == MediumType_Writethrough)
2530 return setError(VBOX_E_INVALID_OBJECT_STATE,
2531 tr("Medium type of '%s' is Writethrough"),
2532 m->strLocationFull.c_str());
2533 else if (m->type == MediumType_Shareable)
2534 return setError(VBOX_E_INVALID_OBJECT_STATE,
2535 tr("Medium type of '%s' is Shareable"),
2536 m->strLocationFull.c_str());
2537 else if (m->type == MediumType_Readonly)
2538 return setError(VBOX_E_INVALID_OBJECT_STATE,
2539 tr("Medium type of '%s' is Readonly"),
2540 m->strLocationFull.c_str());
2541
2542 /* Apply the normal locking logic to the entire chain. */
2543 MediumLockList *pMediumLockList(new MediumLockList());
2544 HRESULT rc = diff->createMediumLockList(true /* fFailIfInaccessible */,
2545 true /* fMediumLockWrite */,
2546 this,
2547 *pMediumLockList);
2548 if (FAILED(rc))
2549 {
2550 delete pMediumLockList;
2551 return rc;
2552 }
2553
2554 rc = pMediumLockList->Lock();
2555 if (FAILED(rc))
2556 {
2557 delete pMediumLockList;
2558
2559 return setError(rc, tr("Could not lock medium when creating diff '%s'"),
2560 diff->getLocationFull().c_str());
2561 }
2562
2563 Guid parentMachineRegistry;
2564 if (getFirstRegistryMachineId(parentMachineRegistry))
2565 {
2566 /* since this medium has been just created it isn't associated yet */
2567 diff->m->llRegistryIDs.push_back(parentMachineRegistry);
2568 }
2569
2570 treeLock.release();
2571 alock.release();
2572
2573 ComObjPtr <Progress> pProgress;
2574
2575 rc = createDiffStorage(diff, (MediumVariant_T)aVariant, pMediumLockList,
2576 &pProgress, false /* aWait */,
2577 NULL /* pfNeedsGlobalSaveSettings*/);
2578 if (FAILED(rc))
2579 delete pMediumLockList;
2580 else
2581 pProgress.queryInterfaceTo(aProgress);
2582
2583 return rc;
2584}
2585
2586STDMETHODIMP Medium::MergeTo(IMedium *aTarget, IProgress **aProgress)
2587{
2588 CheckComArgNotNull(aTarget);
2589 CheckComArgOutPointerValid(aProgress);
2590 ComAssertRet(aTarget != this, E_INVALIDARG);
2591
2592 AutoCaller autoCaller(this);
2593 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2594
2595 ComObjPtr<Medium> pTarget = static_cast<Medium*>(aTarget);
2596
2597 bool fMergeForward = false;
2598 ComObjPtr<Medium> pParentForTarget;
2599 MediaList childrenToReparent;
2600 MediumLockList *pMediumLockList = NULL;
2601
2602 HRESULT rc = S_OK;
2603
2604 rc = prepareMergeTo(pTarget, NULL, NULL, true, fMergeForward,
2605 pParentForTarget, childrenToReparent, pMediumLockList);
2606 if (FAILED(rc)) return rc;
2607
2608 ComObjPtr <Progress> pProgress;
2609
2610 rc = mergeTo(pTarget, fMergeForward, pParentForTarget, childrenToReparent,
2611 pMediumLockList, &pProgress, false /* aWait */,
2612 NULL /* pfNeedsGlobalSaveSettings */);
2613 if (FAILED(rc))
2614 cancelMergeTo(childrenToReparent, pMediumLockList);
2615 else
2616 pProgress.queryInterfaceTo(aProgress);
2617
2618 return rc;
2619}
2620
2621STDMETHODIMP Medium::CloneTo(IMedium *aTarget,
2622 ULONG aVariant,
2623 IMedium *aParent,
2624 IProgress **aProgress)
2625{
2626 CheckComArgNotNull(aTarget);
2627 CheckComArgOutPointerValid(aProgress);
2628 ComAssertRet(aTarget != this, E_INVALIDARG);
2629
2630 AutoCaller autoCaller(this);
2631 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2632
2633 ComObjPtr<Medium> pTarget = static_cast<Medium*>(aTarget);
2634 ComObjPtr<Medium> pParent;
2635 if (aParent)
2636 pParent = static_cast<Medium*>(aParent);
2637
2638 HRESULT rc = S_OK;
2639 ComObjPtr<Progress> pProgress;
2640 Medium::Task *pTask = NULL;
2641
2642 try
2643 {
2644 // locking: we need the tree lock first because we access parent pointers
2645 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
2646 // and we need to write-lock the media involved
2647 AutoMultiWriteLock3 alock(this, pTarget, pParent COMMA_LOCKVAL_SRC_POS);
2648
2649 if ( pTarget->m->state != MediumState_NotCreated
2650 && pTarget->m->state != MediumState_Created)
2651 throw pTarget->setStateError();
2652
2653 /* Build the source lock list. */
2654 MediumLockList *pSourceMediumLockList(new MediumLockList());
2655 rc = createMediumLockList(true /* fFailIfInaccessible */,
2656 false /* fMediumLockWrite */,
2657 NULL,
2658 *pSourceMediumLockList);
2659 if (FAILED(rc))
2660 {
2661 delete pSourceMediumLockList;
2662 throw rc;
2663 }
2664
2665 /* Build the target lock list (including the to-be parent chain). */
2666 MediumLockList *pTargetMediumLockList(new MediumLockList());
2667 rc = pTarget->createMediumLockList(true /* fFailIfInaccessible */,
2668 true /* fMediumLockWrite */,
2669 pParent,
2670 *pTargetMediumLockList);
2671 if (FAILED(rc))
2672 {
2673 delete pSourceMediumLockList;
2674 delete pTargetMediumLockList;
2675 throw rc;
2676 }
2677
2678 rc = pSourceMediumLockList->Lock();
2679 if (FAILED(rc))
2680 {
2681 delete pSourceMediumLockList;
2682 delete pTargetMediumLockList;
2683 throw setError(rc,
2684 tr("Failed to lock source media '%s'"),
2685 getLocationFull().c_str());
2686 }
2687 rc = pTargetMediumLockList->Lock();
2688 if (FAILED(rc))
2689 {
2690 delete pSourceMediumLockList;
2691 delete pTargetMediumLockList;
2692 throw setError(rc,
2693 tr("Failed to lock target media '%s'"),
2694 pTarget->getLocationFull().c_str());
2695 }
2696
2697 pProgress.createObject();
2698 rc = pProgress->init(m->pVirtualBox,
2699 static_cast <IMedium *>(this),
2700 BstrFmt(tr("Creating clone medium '%s'"), pTarget->m->strLocationFull.c_str()).raw(),
2701 TRUE /* aCancelable */);
2702 if (FAILED(rc))
2703 {
2704 delete pSourceMediumLockList;
2705 delete pTargetMediumLockList;
2706 throw rc;
2707 }
2708
2709 /* setup task object to carry out the operation asynchronously */
2710 pTask = new Medium::CloneTask(this, pProgress, pTarget,
2711 (MediumVariant_T)aVariant,
2712 pParent, UINT32_MAX, UINT32_MAX,
2713 pSourceMediumLockList, pTargetMediumLockList);
2714 rc = pTask->rc();
2715 AssertComRC(rc);
2716 if (FAILED(rc))
2717 throw rc;
2718
2719 if (pTarget->m->state == MediumState_NotCreated)
2720 pTarget->m->state = MediumState_Creating;
2721 }
2722 catch (HRESULT aRC) { rc = aRC; }
2723
2724 if (SUCCEEDED(rc))
2725 {
2726 rc = startThread(pTask);
2727
2728 if (SUCCEEDED(rc))
2729 pProgress.queryInterfaceTo(aProgress);
2730 }
2731 else if (pTask != NULL)
2732 delete pTask;
2733
2734 return rc;
2735}
2736
2737STDMETHODIMP Medium::Compact(IProgress **aProgress)
2738{
2739 CheckComArgOutPointerValid(aProgress);
2740
2741 AutoCaller autoCaller(this);
2742 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2743
2744 HRESULT rc = S_OK;
2745 ComObjPtr <Progress> pProgress;
2746 Medium::Task *pTask = NULL;
2747
2748 try
2749 {
2750 /* We need to lock both the current object, and the tree lock (would
2751 * cause a lock order violation otherwise) for createMediumLockList. */
2752 AutoMultiWriteLock2 multilock(&m->pVirtualBox->getMediaTreeLockHandle(),
2753 this->lockHandle()
2754 COMMA_LOCKVAL_SRC_POS);
2755
2756 /* Build the medium lock list. */
2757 MediumLockList *pMediumLockList(new MediumLockList());
2758 rc = createMediumLockList(true /* fFailIfInaccessible */ ,
2759 true /* fMediumLockWrite */,
2760 NULL,
2761 *pMediumLockList);
2762 if (FAILED(rc))
2763 {
2764 delete pMediumLockList;
2765 throw rc;
2766 }
2767
2768 rc = pMediumLockList->Lock();
2769 if (FAILED(rc))
2770 {
2771 delete pMediumLockList;
2772 throw setError(rc,
2773 tr("Failed to lock media when compacting '%s'"),
2774 getLocationFull().c_str());
2775 }
2776
2777 pProgress.createObject();
2778 rc = pProgress->init(m->pVirtualBox,
2779 static_cast <IMedium *>(this),
2780 BstrFmt(tr("Compacting medium '%s'"), m->strLocationFull.c_str()).raw(),
2781 TRUE /* aCancelable */);
2782 if (FAILED(rc))
2783 {
2784 delete pMediumLockList;
2785 throw rc;
2786 }
2787
2788 /* setup task object to carry out the operation asynchronously */
2789 pTask = new Medium::CompactTask(this, pProgress, pMediumLockList);
2790 rc = pTask->rc();
2791 AssertComRC(rc);
2792 if (FAILED(rc))
2793 throw rc;
2794 }
2795 catch (HRESULT aRC) { rc = aRC; }
2796
2797 if (SUCCEEDED(rc))
2798 {
2799 rc = startThread(pTask);
2800
2801 if (SUCCEEDED(rc))
2802 pProgress.queryInterfaceTo(aProgress);
2803 }
2804 else if (pTask != NULL)
2805 delete pTask;
2806
2807 return rc;
2808}
2809
2810STDMETHODIMP Medium::Resize(LONG64 aLogicalSize, IProgress **aProgress)
2811{
2812 CheckComArgOutPointerValid(aProgress);
2813
2814 AutoCaller autoCaller(this);
2815 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2816
2817 HRESULT rc = S_OK;
2818 ComObjPtr <Progress> pProgress;
2819 Medium::Task *pTask = NULL;
2820
2821 try
2822 {
2823 /* We need to lock both the current object, and the tree lock (would
2824 * cause a lock order violation otherwise) for createMediumLockList. */
2825 AutoMultiWriteLock2 multilock(&m->pVirtualBox->getMediaTreeLockHandle(),
2826 this->lockHandle()
2827 COMMA_LOCKVAL_SRC_POS);
2828
2829 /* Build the medium lock list. */
2830 MediumLockList *pMediumLockList(new MediumLockList());
2831 rc = createMediumLockList(true /* fFailIfInaccessible */ ,
2832 true /* fMediumLockWrite */,
2833 NULL,
2834 *pMediumLockList);
2835 if (FAILED(rc))
2836 {
2837 delete pMediumLockList;
2838 throw rc;
2839 }
2840
2841 rc = pMediumLockList->Lock();
2842 if (FAILED(rc))
2843 {
2844 delete pMediumLockList;
2845 throw setError(rc,
2846 tr("Failed to lock media when compacting '%s'"),
2847 getLocationFull().c_str());
2848 }
2849
2850 pProgress.createObject();
2851 rc = pProgress->init(m->pVirtualBox,
2852 static_cast <IMedium *>(this),
2853 BstrFmt(tr("Compacting medium '%s'"), m->strLocationFull.c_str()).raw(),
2854 TRUE /* aCancelable */);
2855 if (FAILED(rc))
2856 {
2857 delete pMediumLockList;
2858 throw rc;
2859 }
2860
2861 /* setup task object to carry out the operation asynchronously */
2862 pTask = new Medium::ResizeTask(this, aLogicalSize, pProgress, pMediumLockList);
2863 rc = pTask->rc();
2864 AssertComRC(rc);
2865 if (FAILED(rc))
2866 throw rc;
2867 }
2868 catch (HRESULT aRC) { rc = aRC; }
2869
2870 if (SUCCEEDED(rc))
2871 {
2872 rc = startThread(pTask);
2873
2874 if (SUCCEEDED(rc))
2875 pProgress.queryInterfaceTo(aProgress);
2876 }
2877 else if (pTask != NULL)
2878 delete pTask;
2879
2880 return rc;
2881}
2882
2883STDMETHODIMP Medium::Reset(IProgress **aProgress)
2884{
2885 CheckComArgOutPointerValid(aProgress);
2886
2887 AutoCaller autoCaller(this);
2888 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2889
2890 HRESULT rc = S_OK;
2891 ComObjPtr <Progress> pProgress;
2892 Medium::Task *pTask = NULL;
2893
2894 try
2895 {
2896 /* canClose() needs the tree lock */
2897 AutoMultiWriteLock2 multilock(&m->pVirtualBox->getMediaTreeLockHandle(),
2898 this->lockHandle()
2899 COMMA_LOCKVAL_SRC_POS);
2900
2901 LogFlowThisFunc(("ENTER for medium %s\n", m->strLocationFull.c_str()));
2902
2903 if (m->pParent.isNull())
2904 throw setError(VBOX_E_NOT_SUPPORTED,
2905 tr("Medium type of '%s' is not differencing"),
2906 m->strLocationFull.c_str());
2907
2908 rc = canClose();
2909 if (FAILED(rc))
2910 throw rc;
2911
2912 /* Build the medium lock list. */
2913 MediumLockList *pMediumLockList(new MediumLockList());
2914 rc = createMediumLockList(true /* fFailIfInaccessible */,
2915 true /* fMediumLockWrite */,
2916 NULL,
2917 *pMediumLockList);
2918 if (FAILED(rc))
2919 {
2920 delete pMediumLockList;
2921 throw rc;
2922 }
2923
2924 rc = pMediumLockList->Lock();
2925 if (FAILED(rc))
2926 {
2927 delete pMediumLockList;
2928 throw setError(rc,
2929 tr("Failed to lock media when resetting '%s'"),
2930 getLocationFull().c_str());
2931 }
2932
2933 pProgress.createObject();
2934 rc = pProgress->init(m->pVirtualBox,
2935 static_cast<IMedium*>(this),
2936 BstrFmt(tr("Resetting differencing medium '%s'"), m->strLocationFull.c_str()).raw(),
2937 FALSE /* aCancelable */);
2938 if (FAILED(rc))
2939 throw rc;
2940
2941 /* setup task object to carry out the operation asynchronously */
2942 pTask = new Medium::ResetTask(this, pProgress, pMediumLockList);
2943 rc = pTask->rc();
2944 AssertComRC(rc);
2945 if (FAILED(rc))
2946 throw rc;
2947 }
2948 catch (HRESULT aRC) { rc = aRC; }
2949
2950 if (SUCCEEDED(rc))
2951 {
2952 rc = startThread(pTask);
2953
2954 if (SUCCEEDED(rc))
2955 pProgress.queryInterfaceTo(aProgress);
2956 }
2957 else
2958 {
2959 /* Note: on success, the task will unlock this */
2960 {
2961 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2962 HRESULT rc2 = UnlockWrite(NULL);
2963 AssertComRC(rc2);
2964 }
2965 if (pTask != NULL)
2966 delete pTask;
2967 }
2968
2969 LogFlowThisFunc(("LEAVE, rc=%Rhrc\n", rc));
2970
2971 return rc;
2972}
2973
2974////////////////////////////////////////////////////////////////////////////////
2975//
2976// Medium public internal methods
2977//
2978////////////////////////////////////////////////////////////////////////////////
2979
2980/**
2981 * Internal method to return the medium's parent medium. Must have caller + locking!
2982 * @return
2983 */
2984const ComObjPtr<Medium>& Medium::getParent() const
2985{
2986 return m->pParent;
2987}
2988
2989/**
2990 * Internal method to return the medium's list of child media. Must have caller + locking!
2991 * @return
2992 */
2993const MediaList& Medium::getChildren() const
2994{
2995 return m->llChildren;
2996}
2997
2998/**
2999 * Internal method to return the medium's GUID. Must have caller + locking!
3000 * @return
3001 */
3002const Guid& Medium::getId() const
3003{
3004 return m->id;
3005}
3006
3007/**
3008 * Internal method to return the medium's state. Must have caller + locking!
3009 * @return
3010 */
3011MediumState_T Medium::getState() const
3012{
3013 return m->state;
3014}
3015
3016/**
3017 * Internal method to return the medium's variant. Must have caller + locking!
3018 * @return
3019 */
3020MediumVariant_T Medium::getVariant() const
3021{
3022 return m->variant;
3023}
3024
3025/**
3026 * Internal method which returns true if this medium represents a host drive.
3027 * @return
3028 */
3029bool Medium::isHostDrive() const
3030{
3031 return m->hostDrive;
3032}
3033
3034/**
3035 * Internal method to return the medium's full location. Must have caller + locking!
3036 * @return
3037 */
3038const Utf8Str& Medium::getLocationFull() const
3039{
3040 return m->strLocationFull;
3041}
3042
3043/**
3044 * Internal method to return the medium's format string. Must have caller + locking!
3045 * @return
3046 */
3047const Utf8Str& Medium::getFormat() const
3048{
3049 return m->strFormat;
3050}
3051
3052/**
3053 * Internal method to return the medium's format object. Must have caller + locking!
3054 * @return
3055 */
3056const ComObjPtr<MediumFormat>& Medium::getMediumFormat() const
3057{
3058 return m->formatObj;
3059}
3060
3061/**
3062 * Internal method that returns true if the medium is represented by a file on the host disk
3063 * (and not iSCSI or something).
3064 * @return
3065 */
3066bool Medium::isMediumFormatFile() const
3067{
3068 if ( m->formatObj
3069 && (m->formatObj->getCapabilities() & MediumFormatCapabilities_File)
3070 )
3071 return true;
3072 return false;
3073}
3074
3075/**
3076 * Internal method to return the medium's size. Must have caller + locking!
3077 * @return
3078 */
3079uint64_t Medium::getSize() const
3080{
3081 return m->size;
3082}
3083
3084/**
3085 * Returns the medium device type. Must have caller + locking!
3086 * @return
3087 */
3088DeviceType_T Medium::getDeviceType() const
3089{
3090 return m->devType;
3091}
3092
3093/**
3094 * Returns the medium type. Must have caller + locking!
3095 * @return
3096 */
3097MediumType_T Medium::getType() const
3098{
3099 return m->type;
3100}
3101
3102/**
3103 * Returns a short version of the location attribute.
3104 *
3105 * @note Must be called from under this object's read or write lock.
3106 */
3107Utf8Str Medium::getName()
3108{
3109 Utf8Str name = RTPathFilename(m->strLocationFull.c_str());
3110 return name;
3111}
3112
3113/**
3114 * This adds the given UUID to the list of media registries in which this
3115 * medium should be registered. The UUID can either be a machine UUID,
3116 * to add a machine registry, or the global registry UUID as returned by
3117 * VirtualBox::getGlobalRegistryId().
3118 *
3119 * Note that for hard disks, this method does nothing if the medium is
3120 * already in another registry to avoid having hard disks in more than
3121 * one registry, which causes trouble with keeping diff images in sync.
3122 * See getFirstRegistryMachineId() for details.
3123 *
3124 * If fRecurse == true, then the media tree lock must be held for reading.
3125 *
3126 * @param id
3127 * @param fRecurse If true, recurses into child media to make sure the whole tree has registries in sync.
3128 * @return true if the registry was added; false if the given id was already on the list.
3129 */
3130bool Medium::addRegistry(const Guid& id, bool fRecurse)
3131{
3132 AutoCaller autoCaller(this);
3133 if (FAILED(autoCaller.rc()))
3134 return false;
3135 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3136
3137 bool fAdd = true;
3138
3139 // hard disks cannot be in more than one registry
3140 if ( m->devType == DeviceType_HardDisk
3141 && m->llRegistryIDs.size() > 0)
3142 fAdd = false;
3143
3144 // no need to add the UUID twice
3145 if (fAdd)
3146 {
3147 for (GuidList::const_iterator it = m->llRegistryIDs.begin();
3148 it != m->llRegistryIDs.end();
3149 ++it)
3150 {
3151 if ((*it) == id)
3152 {
3153 fAdd = false;
3154 break;
3155 }
3156 }
3157 }
3158
3159 if (fAdd)
3160 m->llRegistryIDs.push_back(id);
3161
3162 if (fRecurse)
3163 {
3164 // Get private list of children and release medium lock straight away.
3165 MediaList llChildren(m->llChildren);
3166 alock.release();
3167
3168 for (MediaList::iterator it = llChildren.begin();
3169 it != llChildren.end();
3170 ++it)
3171 {
3172 Medium *pChild = *it;
3173 fAdd |= pChild->addRegistry(id, true);
3174 }
3175 }
3176
3177 return fAdd;
3178}
3179
3180/**
3181 * Removes the given UUID from the list of media registry UUIDs. Returns true
3182 * if found or false if not.
3183 *
3184 * If fRecurse == true, then the media tree lock must be held for reading.
3185 *
3186 * @param id
3187 * @param fRecurse If true, recurses into child media to make sure the whole tree has registries in sync.
3188 * @return
3189 */
3190bool Medium::removeRegistry(const Guid& id, bool fRecurse)
3191{
3192 AutoCaller autoCaller(this);
3193 if (FAILED(autoCaller.rc()))
3194 return false;
3195 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3196
3197 bool fRemove = false;
3198
3199 for (GuidList::iterator it = m->llRegistryIDs.begin();
3200 it != m->llRegistryIDs.end();
3201 ++it)
3202 {
3203 if ((*it) == id)
3204 {
3205 m->llRegistryIDs.erase(it);
3206 fRemove = true;
3207 break;
3208 }
3209 }
3210
3211 if (fRecurse)
3212 {
3213 // Get private list of children and release medium lock straight away.
3214 MediaList llChildren(m->llChildren);
3215 alock.release();
3216
3217 for (MediaList::iterator it = llChildren.begin();
3218 it != llChildren.end();
3219 ++it)
3220 {
3221 Medium *pChild = *it;
3222 fRemove |= pChild->removeRegistry(id, true);
3223 }
3224 }
3225
3226 return fRemove;
3227}
3228
3229/**
3230 * Returns true if id is in the list of media registries for this medium.
3231 *
3232 * Must have caller + read locking!
3233 *
3234 * @param id
3235 * @return
3236 */
3237bool Medium::isInRegistry(const Guid& id)
3238{
3239 for (GuidList::const_iterator it = m->llRegistryIDs.begin();
3240 it != m->llRegistryIDs.end();
3241 ++it)
3242 {
3243 if (*it == id)
3244 return true;
3245 }
3246
3247 return false;
3248}
3249
3250/**
3251 * Internal method to return the medium's first registry machine (i.e. the machine in whose
3252 * machine XML this medium is listed).
3253 *
3254 * Every attached medium must now (4.0) reside in at least one media registry, which is identified
3255 * by a UUID. This is either a machine UUID if the machine is from 4.0 or newer, in which case
3256 * machines have their own media registries, or it is the pseudo-UUID of the VirtualBox
3257 * object if the machine is old and still needs the global registry in VirtualBox.xml.
3258 *
3259 * By definition, hard disks may only be in one media registry, in which all its children
3260 * will be stored as well. Otherwise we run into problems with having keep multiple registries
3261 * in sync. (This is the "cloned VM" case in which VM1 may link to the disks of VM2; in this
3262 * case, only VM2's registry is used for the disk in question.)
3263 *
3264 * If there is no medium registry, particularly if the medium has not been attached yet, this
3265 * does not modify uuid and returns false.
3266 *
3267 * ISOs and RAWs, by contrast, can be in more than one repository to make things easier for
3268 * the user.
3269 *
3270 * Must have caller + locking!
3271 *
3272 * @param uuid Receives first registry machine UUID, if available.
3273 * @return true if uuid was set.
3274 */
3275bool Medium::getFirstRegistryMachineId(Guid &uuid) const
3276{
3277 if (m->llRegistryIDs.size())
3278 {
3279 uuid = m->llRegistryIDs.front();
3280 return true;
3281 }
3282 return false;
3283}
3284
3285/**
3286 * Adds all the IDs of the registries in which this medium is registered to the given list
3287 * of UUIDs, but only if they are not on the list yet.
3288 * @param llRegistryIDs
3289 */
3290HRESULT Medium::addToRegistryIDList(GuidList &llRegistryIDs)
3291{
3292 AutoCaller autoCaller(this);
3293 if (FAILED(autoCaller.rc())) return false;
3294
3295 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3296
3297 for (GuidList::const_iterator it = m->llRegistryIDs.begin();
3298 it != m->llRegistryIDs.end();
3299 ++it)
3300 {
3301 VirtualBox::addGuidToListUniquely(llRegistryIDs, *it);
3302 }
3303
3304 return S_OK;
3305}
3306
3307/**
3308 * Adds the given machine and optionally the snapshot to the list of the objects
3309 * this medium is attached to.
3310 *
3311 * @param aMachineId Machine ID.
3312 * @param aSnapshotId Snapshot ID; when non-empty, adds a snapshot attachment.
3313 */
3314HRESULT Medium::addBackReference(const Guid &aMachineId,
3315 const Guid &aSnapshotId /*= Guid::Empty*/)
3316{
3317 AssertReturn(!aMachineId.isEmpty(), E_FAIL);
3318
3319 LogFlowThisFunc(("ENTER, aMachineId: {%RTuuid}, aSnapshotId: {%RTuuid}\n", aMachineId.raw(), aSnapshotId.raw()));
3320
3321 AutoCaller autoCaller(this);
3322 AssertComRCReturnRC(autoCaller.rc());
3323
3324 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3325
3326 switch (m->state)
3327 {
3328 case MediumState_Created:
3329 case MediumState_Inaccessible:
3330 case MediumState_LockedRead:
3331 case MediumState_LockedWrite:
3332 break;
3333
3334 default:
3335 return setStateError();
3336 }
3337
3338 if (m->numCreateDiffTasks > 0)
3339 return setError(VBOX_E_OBJECT_IN_USE,
3340 tr("Cannot attach medium '%s' {%RTuuid}: %u differencing child media are being created"),
3341 m->strLocationFull.c_str(),
3342 m->id.raw(),
3343 m->numCreateDiffTasks);
3344
3345 BackRefList::iterator it = std::find_if(m->backRefs.begin(),
3346 m->backRefs.end(),
3347 BackRef::EqualsTo(aMachineId));
3348 if (it == m->backRefs.end())
3349 {
3350 BackRef ref(aMachineId, aSnapshotId);
3351 m->backRefs.push_back(ref);
3352
3353 return S_OK;
3354 }
3355
3356 // if the caller has not supplied a snapshot ID, then we're attaching
3357 // to a machine a medium which represents the machine's current state,
3358 // so set the flag
3359 if (aSnapshotId.isEmpty())
3360 {
3361 /* sanity: no duplicate attachments */
3362 if (it->fInCurState)
3363 return setError(VBOX_E_OBJECT_IN_USE,
3364 tr("Cannot attach medium '%s' {%RTuuid}: medium is already associated with the current state of machine uuid {%RTuuid}!"),
3365 m->strLocationFull.c_str(),
3366 m->id.raw(),
3367 aMachineId.raw());
3368 it->fInCurState = true;
3369
3370 return S_OK;
3371 }
3372
3373 // otherwise: a snapshot medium is being attached
3374
3375 /* sanity: no duplicate attachments */
3376 for (GuidList::const_iterator jt = it->llSnapshotIds.begin();
3377 jt != it->llSnapshotIds.end();
3378 ++jt)
3379 {
3380 const Guid &idOldSnapshot = *jt;
3381
3382 if (idOldSnapshot == aSnapshotId)
3383 {
3384#ifdef DEBUG
3385 dumpBackRefs();
3386#endif
3387 return setError(VBOX_E_OBJECT_IN_USE,
3388 tr("Cannot attach medium '%s' {%RTuuid} from snapshot '%RTuuid': medium is already in use by this snapshot!"),
3389 m->strLocationFull.c_str(),
3390 m->id.raw(),
3391 aSnapshotId.raw());
3392 }
3393 }
3394
3395 it->llSnapshotIds.push_back(aSnapshotId);
3396 it->fInCurState = false;
3397
3398 LogFlowThisFuncLeave();
3399
3400 return S_OK;
3401}
3402
3403/**
3404 * Removes the given machine and optionally the snapshot from the list of the
3405 * objects this medium is attached to.
3406 *
3407 * @param aMachineId Machine ID.
3408 * @param aSnapshotId Snapshot ID; when non-empty, removes the snapshot
3409 * attachment.
3410 */
3411HRESULT Medium::removeBackReference(const Guid &aMachineId,
3412 const Guid &aSnapshotId /*= Guid::Empty*/)
3413{
3414 AssertReturn(!aMachineId.isEmpty(), E_FAIL);
3415
3416 AutoCaller autoCaller(this);
3417 AssertComRCReturnRC(autoCaller.rc());
3418
3419 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3420
3421 BackRefList::iterator it =
3422 std::find_if(m->backRefs.begin(), m->backRefs.end(),
3423 BackRef::EqualsTo(aMachineId));
3424 AssertReturn(it != m->backRefs.end(), E_FAIL);
3425
3426 if (aSnapshotId.isEmpty())
3427 {
3428 /* remove the current state attachment */
3429 it->fInCurState = false;
3430 }
3431 else
3432 {
3433 /* remove the snapshot attachment */
3434 GuidList::iterator jt = std::find(it->llSnapshotIds.begin(),
3435 it->llSnapshotIds.end(),
3436 aSnapshotId);
3437
3438 AssertReturn(jt != it->llSnapshotIds.end(), E_FAIL);
3439 it->llSnapshotIds.erase(jt);
3440 }
3441
3442 /* if the backref becomes empty, remove it */
3443 if (it->fInCurState == false && it->llSnapshotIds.size() == 0)
3444 m->backRefs.erase(it);
3445
3446 return S_OK;
3447}
3448
3449/**
3450 * Internal method to return the medium's list of backrefs. Must have caller + locking!
3451 * @return
3452 */
3453const Guid* Medium::getFirstMachineBackrefId() const
3454{
3455 if (!m->backRefs.size())
3456 return NULL;
3457
3458 return &m->backRefs.front().machineId;
3459}
3460
3461/**
3462 * Internal method which returns a machine that either this medium or one of its children
3463 * is attached to. This is used for finding a replacement media registry when an existing
3464 * media registry is about to be deleted in VirtualBox::unregisterMachine().
3465 *
3466 * Must have caller + locking, *and* caller must hold the media tree lock!
3467 * @return
3468 */
3469const Guid* Medium::getAnyMachineBackref() const
3470{
3471 if (m->backRefs.size())
3472 return &m->backRefs.front().machineId;
3473
3474 for (MediaList::iterator it = m->llChildren.begin();
3475 it != m->llChildren.end();
3476 ++it)
3477 {
3478 Medium *pChild = *it;
3479 // recurse for this child
3480 const Guid* puuid;
3481 if ((puuid = pChild->getAnyMachineBackref()))
3482 return puuid;
3483 }
3484
3485 return NULL;
3486}
3487
3488const Guid* Medium::getFirstMachineBackrefSnapshotId() const
3489{
3490 if (!m->backRefs.size())
3491 return NULL;
3492
3493 const BackRef &ref = m->backRefs.front();
3494 if (!ref.llSnapshotIds.size())
3495 return NULL;
3496
3497 return &ref.llSnapshotIds.front();
3498}
3499
3500size_t Medium::getMachineBackRefCount() const
3501{
3502 return m->backRefs.size();
3503}
3504
3505#ifdef DEBUG
3506/**
3507 * Debugging helper that gets called after VirtualBox initialization that writes all
3508 * machine backreferences to the debug log.
3509 */
3510void Medium::dumpBackRefs()
3511{
3512 AutoCaller autoCaller(this);
3513 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3514
3515 LogFlowThisFunc(("Dumping backrefs for medium '%s':\n", m->strLocationFull.c_str()));
3516
3517 for (BackRefList::iterator it2 = m->backRefs.begin();
3518 it2 != m->backRefs.end();
3519 ++it2)
3520 {
3521 const BackRef &ref = *it2;
3522 LogFlowThisFunc((" Backref from machine {%RTuuid} (fInCurState: %d)\n", ref.machineId.raw(), ref.fInCurState));
3523
3524 for (GuidList::const_iterator jt2 = it2->llSnapshotIds.begin();
3525 jt2 != it2->llSnapshotIds.end();
3526 ++jt2)
3527 {
3528 const Guid &id = *jt2;
3529 LogFlowThisFunc((" Backref from snapshot {%RTuuid}\n", id.raw()));
3530 }
3531 }
3532}
3533#endif
3534
3535/**
3536 * Checks if the given change of \a aOldPath to \a aNewPath affects the location
3537 * of this media and updates it if necessary to reflect the new location.
3538 *
3539 * @param aOldPath Old path (full).
3540 * @param aNewPath New path (full).
3541 *
3542 * @note Locks this object for writing.
3543 */
3544HRESULT Medium::updatePath(const Utf8Str &strOldPath, const Utf8Str &strNewPath)
3545{
3546 AssertReturn(!strOldPath.isEmpty(), E_FAIL);
3547 AssertReturn(!strNewPath.isEmpty(), E_FAIL);
3548
3549 AutoCaller autoCaller(this);
3550 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3551
3552 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3553
3554 LogFlowThisFunc(("locationFull.before='%s'\n", m->strLocationFull.c_str()));
3555
3556 const char *pcszMediumPath = m->strLocationFull.c_str();
3557
3558 if (RTPathStartsWith(pcszMediumPath, strOldPath.c_str()))
3559 {
3560 Utf8Str newPath(strNewPath);
3561 newPath.append(pcszMediumPath + strOldPath.length());
3562 unconst(m->strLocationFull) = newPath;
3563
3564 LogFlowThisFunc(("locationFull.after='%s'\n", m->strLocationFull.c_str()));
3565 }
3566
3567 return S_OK;
3568}
3569
3570/**
3571 * Returns the base medium of the media chain this medium is part of.
3572 *
3573 * The base medium is found by walking up the parent-child relationship axis.
3574 * If the medium doesn't have a parent (i.e. it's a base medium), it
3575 * returns itself in response to this method.
3576 *
3577 * @param aLevel Where to store the number of ancestors of this medium
3578 * (zero for the base), may be @c NULL.
3579 *
3580 * @note Locks medium tree for reading.
3581 */
3582ComObjPtr<Medium> Medium::getBase(uint32_t *aLevel /*= NULL*/)
3583{
3584 ComObjPtr<Medium> pBase;
3585 uint32_t level;
3586
3587 AutoCaller autoCaller(this);
3588 AssertReturn(autoCaller.isOk(), pBase);
3589
3590 /* we access mParent */
3591 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3592
3593 pBase = this;
3594 level = 0;
3595
3596 if (m->pParent)
3597 {
3598 for (;;)
3599 {
3600 AutoCaller baseCaller(pBase);
3601 AssertReturn(baseCaller.isOk(), pBase);
3602
3603 if (pBase->m->pParent.isNull())
3604 break;
3605
3606 pBase = pBase->m->pParent;
3607 ++level;
3608 }
3609 }
3610
3611 if (aLevel != NULL)
3612 *aLevel = level;
3613
3614 return pBase;
3615}
3616
3617/**
3618 * Returns @c true if this medium cannot be modified because it has
3619 * dependents (children) or is part of the snapshot. Related to the medium
3620 * type and posterity, not to the current media state.
3621 *
3622 * @note Locks this object and medium tree for reading.
3623 */
3624bool Medium::isReadOnly()
3625{
3626 AutoCaller autoCaller(this);
3627 AssertComRCReturn(autoCaller.rc(), false);
3628
3629 /* we access children */
3630 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3631
3632 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3633
3634 switch (m->type)
3635 {
3636 case MediumType_Normal:
3637 {
3638 if (getChildren().size() != 0)
3639 return true;
3640
3641 for (BackRefList::const_iterator it = m->backRefs.begin();
3642 it != m->backRefs.end(); ++it)
3643 if (it->llSnapshotIds.size() != 0)
3644 return true;
3645
3646 if (m->variant & MediumVariant_VmdkStreamOptimized)
3647 return true;
3648
3649 return false;
3650 }
3651 case MediumType_Immutable:
3652 case MediumType_MultiAttach:
3653 return true;
3654 case MediumType_Writethrough:
3655 case MediumType_Shareable:
3656 case MediumType_Readonly: /* explicit readonly media has no diffs */
3657 return false;
3658 default:
3659 break;
3660 }
3661
3662 AssertFailedReturn(false);
3663}
3664
3665/**
3666 * Internal method to return the medium's size. Must have caller + locking!
3667 * @return
3668 */
3669void Medium::updateId(const Guid &id)
3670{
3671 unconst(m->id) = id;
3672}
3673
3674/**
3675 * Saves medium data by appending a new child node to the given
3676 * parent XML settings node.
3677 *
3678 * @param data Settings struct to be updated.
3679 * @param strHardDiskFolder Folder for which paths should be relative.
3680 *
3681 * @note Locks this object, medium tree and children for reading.
3682 */
3683HRESULT Medium::saveSettings(settings::Medium &data,
3684 const Utf8Str &strHardDiskFolder)
3685{
3686 AutoCaller autoCaller(this);
3687 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3688
3689 /* we access mParent */
3690 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3691
3692 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3693
3694 data.uuid = m->id;
3695
3696 // make path relative if needed
3697 if ( !strHardDiskFolder.isEmpty()
3698 && RTPathStartsWith(m->strLocationFull.c_str(), strHardDiskFolder.c_str())
3699 )
3700 data.strLocation = m->strLocationFull.substr(strHardDiskFolder.length() + 1);
3701 else
3702 data.strLocation = m->strLocationFull;
3703 data.strFormat = m->strFormat;
3704
3705 /* optional, only for diffs, default is false */
3706 if (m->pParent)
3707 data.fAutoReset = m->autoReset;
3708 else
3709 data.fAutoReset = false;
3710
3711 /* optional */
3712 data.strDescription = m->strDescription;
3713
3714 /* optional properties */
3715 data.properties.clear();
3716 for (settings::StringsMap::const_iterator it = m->mapProperties.begin();
3717 it != m->mapProperties.end();
3718 ++it)
3719 {
3720 /* only save properties that have non-default values */
3721 if (!it->second.isEmpty())
3722 {
3723 const Utf8Str &name = it->first;
3724 const Utf8Str &value = it->second;
3725 data.properties[name] = value;
3726 }
3727 }
3728
3729 /* only for base media */
3730 if (m->pParent.isNull())
3731 data.hdType = m->type;
3732
3733 /* save all children */
3734 for (MediaList::const_iterator it = getChildren().begin();
3735 it != getChildren().end();
3736 ++it)
3737 {
3738 settings::Medium med;
3739 HRESULT rc = (*it)->saveSettings(med, strHardDiskFolder);
3740 AssertComRCReturnRC(rc);
3741 data.llChildren.push_back(med);
3742 }
3743
3744 return S_OK;
3745}
3746
3747/**
3748 * Constructs a medium lock list for this medium. The lock is not taken.
3749 *
3750 * @note Locks the medium tree for reading.
3751 *
3752 * @param fFailIfInaccessible If true, this fails with an error if a medium is inaccessible. If false,
3753 * inaccessible media are silently skipped and not locked (i.e. their state remains "Inaccessible");
3754 * this is necessary for a VM's removable media VM startup for which we do not want to fail.
3755 * @param fMediumLockWrite Whether to associate a write lock with this medium.
3756 * @param pToBeParent Medium which will become the parent of this medium.
3757 * @param mediumLockList Where to store the resulting list.
3758 */
3759HRESULT Medium::createMediumLockList(bool fFailIfInaccessible,
3760 bool fMediumLockWrite,
3761 Medium *pToBeParent,
3762 MediumLockList &mediumLockList)
3763{
3764 AutoCaller autoCaller(this);
3765 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3766
3767 HRESULT rc = S_OK;
3768
3769 /* we access parent medium objects */
3770 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3771
3772 /* paranoid sanity checking if the medium has a to-be parent medium */
3773 if (pToBeParent)
3774 {
3775 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3776 ComAssertRet(getParent().isNull(), E_FAIL);
3777 ComAssertRet(getChildren().size() == 0, E_FAIL);
3778 }
3779
3780 ErrorInfoKeeper eik;
3781 MultiResult mrc(S_OK);
3782
3783 ComObjPtr<Medium> pMedium = this;
3784 while (!pMedium.isNull())
3785 {
3786 // need write lock for RefreshState if medium is inaccessible
3787 AutoWriteLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
3788
3789 /* Accessibility check must be first, otherwise locking interferes
3790 * with getting the medium state. Lock lists are not created for
3791 * fun, and thus getting the medium status is no luxury. */
3792 MediumState_T mediumState = pMedium->getState();
3793 if (mediumState == MediumState_Inaccessible)
3794 {
3795 rc = pMedium->RefreshState(&mediumState);
3796 if (FAILED(rc)) return rc;
3797
3798 if (mediumState == MediumState_Inaccessible)
3799 {
3800 // ignore inaccessible ISO media and silently return S_OK,
3801 // otherwise VM startup (esp. restore) may fail without good reason
3802 if (!fFailIfInaccessible)
3803 return S_OK;
3804
3805 // otherwise report an error
3806 Bstr error;
3807 rc = pMedium->COMGETTER(LastAccessError)(error.asOutParam());
3808 if (FAILED(rc)) return rc;
3809
3810 /* collect multiple errors */
3811 eik.restore();
3812 Assert(!error.isEmpty());
3813 mrc = setError(E_FAIL,
3814 "%ls",
3815 error.raw());
3816 // error message will be something like
3817 // "Could not open the medium ... VD: error VERR_FILE_NOT_FOUND opening image file ... (VERR_FILE_NOT_FOUND).
3818 eik.fetch();
3819 }
3820 }
3821
3822 if (pMedium == this)
3823 mediumLockList.Prepend(pMedium, fMediumLockWrite);
3824 else
3825 mediumLockList.Prepend(pMedium, false);
3826
3827 pMedium = pMedium->getParent();
3828 if (pMedium.isNull() && pToBeParent)
3829 {
3830 pMedium = pToBeParent;
3831 pToBeParent = NULL;
3832 }
3833 }
3834
3835 return mrc;
3836}
3837
3838/**
3839 * Creates a new differencing storage unit using the format of the given target
3840 * medium and the location. Note that @c aTarget must be NotCreated.
3841 *
3842 * The @a aMediumLockList parameter contains the associated medium lock list,
3843 * which must be in locked state. If @a aWait is @c true then the caller is
3844 * responsible for unlocking.
3845 *
3846 * If @a aProgress is not NULL but the object it points to is @c null then a
3847 * new progress object will be created and assigned to @a *aProgress on
3848 * success, otherwise the existing progress object is used. If @a aProgress is
3849 * NULL, then no progress object is created/used at all.
3850 *
3851 * When @a aWait is @c false, this method will create a thread to perform the
3852 * create operation asynchronously and will return immediately. Otherwise, it
3853 * will perform the operation on the calling thread and will not return to the
3854 * caller until the operation is completed. Note that @a aProgress cannot be
3855 * NULL when @a aWait is @c false (this method will assert in this case).
3856 *
3857 * @param aTarget Target medium.
3858 * @param aVariant Precise medium variant to create.
3859 * @param aMediumLockList List of media which should be locked.
3860 * @param aProgress Where to find/store a Progress object to track
3861 * operation completion.
3862 * @param aWait @c true if this method should block instead of
3863 * creating an asynchronous thread.
3864 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs that will receive the registry IDs that need saving.
3865 * This only works in "wait" mode; otherwise saveRegistries is called automatically by the thread that
3866 * was created, and this parameter is ignored.
3867 *
3868 * @note Locks this object and @a aTarget for writing.
3869 */
3870HRESULT Medium::createDiffStorage(ComObjPtr<Medium> &aTarget,
3871 MediumVariant_T aVariant,
3872 MediumLockList *aMediumLockList,
3873 ComObjPtr<Progress> *aProgress,
3874 bool aWait,
3875 GuidList *pllRegistriesThatNeedSaving)
3876{
3877 AssertReturn(!aTarget.isNull(), E_FAIL);
3878 AssertReturn(aMediumLockList, E_FAIL);
3879 AssertReturn(aProgress != NULL || aWait == true, E_FAIL);
3880
3881 AutoCaller autoCaller(this);
3882 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3883
3884 AutoCaller targetCaller(aTarget);
3885 if (FAILED(targetCaller.rc())) return targetCaller.rc();
3886
3887 HRESULT rc = S_OK;
3888 ComObjPtr<Progress> pProgress;
3889 Medium::Task *pTask = NULL;
3890
3891 try
3892 {
3893 AutoMultiWriteLock2 alock(this, aTarget COMMA_LOCKVAL_SRC_POS);
3894
3895 ComAssertThrow( m->type != MediumType_Writethrough
3896 && m->type != MediumType_Shareable
3897 && m->type != MediumType_Readonly, E_FAIL);
3898 ComAssertThrow(m->state == MediumState_LockedRead, E_FAIL);
3899
3900 if (aTarget->m->state != MediumState_NotCreated)
3901 throw aTarget->setStateError();
3902
3903 /* Check that the medium is not attached to the current state of
3904 * any VM referring to it. */
3905 for (BackRefList::const_iterator it = m->backRefs.begin();
3906 it != m->backRefs.end();
3907 ++it)
3908 {
3909 if (it->fInCurState)
3910 {
3911 /* Note: when a VM snapshot is being taken, all normal media
3912 * attached to the VM in the current state will be, as an
3913 * exception, also associated with the snapshot which is about
3914 * to create (see SnapshotMachine::init()) before deassociating
3915 * them from the current state (which takes place only on
3916 * success in Machine::fixupHardDisks()), so that the size of
3917 * snapshotIds will be 1 in this case. The extra condition is
3918 * used to filter out this legal situation. */
3919 if (it->llSnapshotIds.size() == 0)
3920 throw setError(VBOX_E_INVALID_OBJECT_STATE,
3921 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"),
3922 m->strLocationFull.c_str(), it->machineId.raw());
3923
3924 Assert(it->llSnapshotIds.size() == 1);
3925 }
3926 }
3927
3928 if (aProgress != NULL)
3929 {
3930 /* use the existing progress object... */
3931 pProgress = *aProgress;
3932
3933 /* ...but create a new one if it is null */
3934 if (pProgress.isNull())
3935 {
3936 pProgress.createObject();
3937 rc = pProgress->init(m->pVirtualBox,
3938 static_cast<IMedium*>(this),
3939 BstrFmt(tr("Creating differencing medium storage unit '%s'"), aTarget->m->strLocationFull.c_str()).raw(),
3940 TRUE /* aCancelable */);
3941 if (FAILED(rc))
3942 throw rc;
3943 }
3944 }
3945
3946 /* setup task object to carry out the operation sync/async */
3947 pTask = new Medium::CreateDiffTask(this, pProgress, aTarget, aVariant,
3948 aMediumLockList,
3949 aWait /* fKeepMediumLockList */);
3950 rc = pTask->rc();
3951 AssertComRC(rc);
3952 if (FAILED(rc))
3953 throw rc;
3954
3955 /* register a task (it will deregister itself when done) */
3956 ++m->numCreateDiffTasks;
3957 Assert(m->numCreateDiffTasks != 0); /* overflow? */
3958
3959 aTarget->m->state = MediumState_Creating;
3960 }
3961 catch (HRESULT aRC) { rc = aRC; }
3962
3963 if (SUCCEEDED(rc))
3964 {
3965 if (aWait)
3966 rc = runNow(pTask, pllRegistriesThatNeedSaving);
3967 else
3968 rc = startThread(pTask);
3969
3970 if (SUCCEEDED(rc) && aProgress != NULL)
3971 *aProgress = pProgress;
3972 }
3973 else if (pTask != NULL)
3974 delete pTask;
3975
3976 return rc;
3977}
3978
3979/**
3980 * Returns a preferred format for differencing media.
3981 */
3982Utf8Str Medium::getPreferredDiffFormat()
3983{
3984 AutoCaller autoCaller(this);
3985 AssertComRCReturn(autoCaller.rc(), Utf8Str::Empty);
3986
3987 /* check that our own format supports diffs */
3988 if (!(m->formatObj->getCapabilities() & MediumFormatCapabilities_Differencing))
3989 {
3990 /* use the default format if not */
3991 Utf8Str tmp;
3992 m->pVirtualBox->getDefaultHardDiskFormat(tmp);
3993 return tmp;
3994 }
3995
3996 /* m->strFormat is const, no need to lock */
3997 return m->strFormat;
3998}
3999
4000/**
4001 * Implementation for the public Medium::Close() with the exception of calling
4002 * VirtualBox::saveRegistries(), in case someone wants to call this for several
4003 * media.
4004 *
4005 * After this returns with success, uninit() has been called on the medium, and
4006 * the object is no longer usable ("not ready" state).
4007 *
4008 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs that will receive the registry IDs that need saving.
4009 * @param autoCaller AutoCaller instance which must have been created on the caller's stack for this medium. This gets released here
4010 * upon which the Medium instance gets uninitialized.
4011 * @return
4012 */
4013HRESULT Medium::close(GuidList *pllRegistriesThatNeedSaving,
4014 AutoCaller &autoCaller)
4015{
4016 // we're accessing parent/child and backrefs, so lock the tree first, then ourselves
4017 AutoMultiWriteLock2 multilock(&m->pVirtualBox->getMediaTreeLockHandle(),
4018 this->lockHandle()
4019 COMMA_LOCKVAL_SRC_POS);
4020
4021 LogFlowFunc(("ENTER for %s\n", getLocationFull().c_str()));
4022
4023 bool wasCreated = true;
4024
4025 switch (m->state)
4026 {
4027 case MediumState_NotCreated:
4028 wasCreated = false;
4029 break;
4030 case MediumState_Created:
4031 case MediumState_Inaccessible:
4032 break;
4033 default:
4034 return setStateError();
4035 }
4036
4037 if (m->backRefs.size() != 0)
4038 return setError(VBOX_E_OBJECT_IN_USE,
4039 tr("Medium '%s' cannot be closed because it is still attached to %d virtual machines"),
4040 m->strLocationFull.c_str(), m->backRefs.size());
4041
4042 // perform extra media-dependent close checks
4043 HRESULT rc = canClose();
4044 if (FAILED(rc)) return rc;
4045
4046 if (wasCreated)
4047 {
4048 // remove from the list of known media before performing actual
4049 // uninitialization (to keep the media registry consistent on
4050 // failure to do so)
4051 rc = unregisterWithVirtualBox(pllRegistriesThatNeedSaving);
4052 if (FAILED(rc)) return rc;
4053 }
4054
4055 // leave the AutoCaller, as otherwise uninit() will simply hang
4056 autoCaller.release();
4057
4058 // Keep the locks held until after uninit, as otherwise the consistency
4059 // of the medium tree cannot be guaranteed.
4060 uninit();
4061
4062 LogFlowFuncLeave();
4063
4064 return rc;
4065}
4066
4067/**
4068 * Deletes the medium storage unit.
4069 *
4070 * If @a aProgress is not NULL but the object it points to is @c null then a new
4071 * progress object will be created and assigned to @a *aProgress on success,
4072 * otherwise the existing progress object is used. If Progress is NULL, then no
4073 * progress object is created/used at all.
4074 *
4075 * When @a aWait is @c false, this method will create a thread to perform the
4076 * delete operation asynchronously and will return immediately. Otherwise, it
4077 * will perform the operation on the calling thread and will not return to the
4078 * caller until the operation is completed. Note that @a aProgress cannot be
4079 * NULL when @a aWait is @c false (this method will assert in this case).
4080 *
4081 * @param aProgress Where to find/store a Progress object to track operation
4082 * completion.
4083 * @param aWait @c true if this method should block instead of creating
4084 * an asynchronous thread.
4085 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
4086 * by this function if the caller should invoke VirtualBox::saveRegistries() because the global settings have changed.
4087 * This only works in "wait" mode; otherwise saveRegistries gets called automatically by the thread that was created,
4088 * and this parameter is ignored.
4089 *
4090 * @note Locks mVirtualBox and this object for writing. Locks medium tree for
4091 * writing.
4092 */
4093HRESULT Medium::deleteStorage(ComObjPtr<Progress> *aProgress,
4094 bool aWait,
4095 GuidList *pllRegistriesThatNeedSaving)
4096{
4097 AssertReturn(aProgress != NULL || aWait == true, E_FAIL);
4098
4099 AutoCaller autoCaller(this);
4100 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4101
4102 HRESULT rc = S_OK;
4103 ComObjPtr<Progress> pProgress;
4104 Medium::Task *pTask = NULL;
4105
4106 try
4107 {
4108 /* we're accessing the media tree, and canClose() needs it too */
4109 AutoMultiWriteLock2 multilock(&m->pVirtualBox->getMediaTreeLockHandle(),
4110 this->lockHandle()
4111 COMMA_LOCKVAL_SRC_POS);
4112 LogFlowThisFunc(("aWait=%RTbool locationFull=%s\n", aWait, getLocationFull().c_str() ));
4113
4114 if ( !(m->formatObj->getCapabilities() & ( MediumFormatCapabilities_CreateDynamic
4115 | MediumFormatCapabilities_CreateFixed)))
4116 throw setError(VBOX_E_NOT_SUPPORTED,
4117 tr("Medium format '%s' does not support storage deletion"),
4118 m->strFormat.c_str());
4119
4120 /* Note that we are fine with Inaccessible state too: a) for symmetry
4121 * with create calls and b) because it doesn't really harm to try, if
4122 * it is really inaccessible, the delete operation will fail anyway.
4123 * Accepting Inaccessible state is especially important because all
4124 * registered media are initially Inaccessible upon VBoxSVC startup
4125 * until COMGETTER(RefreshState) is called. Accept Deleting state
4126 * because some callers need to put the medium in this state early
4127 * to prevent races. */
4128 switch (m->state)
4129 {
4130 case MediumState_Created:
4131 case MediumState_Deleting:
4132 case MediumState_Inaccessible:
4133 break;
4134 default:
4135 throw setStateError();
4136 }
4137
4138 if (m->backRefs.size() != 0)
4139 {
4140 Utf8Str strMachines;
4141 for (BackRefList::const_iterator it = m->backRefs.begin();
4142 it != m->backRefs.end();
4143 ++it)
4144 {
4145 const BackRef &b = *it;
4146 if (strMachines.length())
4147 strMachines.append(", ");
4148 strMachines.append(b.machineId.toString().c_str());
4149 }
4150#ifdef DEBUG
4151 dumpBackRefs();
4152#endif
4153 throw setError(VBOX_E_OBJECT_IN_USE,
4154 tr("Cannot delete storage: medium '%s' is still attached to the following %d virtual machine(s): %s"),
4155 m->strLocationFull.c_str(),
4156 m->backRefs.size(),
4157 strMachines.c_str());
4158 }
4159
4160 rc = canClose();
4161 if (FAILED(rc))
4162 throw rc;
4163
4164 /* go to Deleting state, so that the medium is not actually locked */
4165 if (m->state != MediumState_Deleting)
4166 {
4167 rc = markForDeletion();
4168 if (FAILED(rc))
4169 throw rc;
4170 }
4171
4172 /* Build the medium lock list. */
4173 MediumLockList *pMediumLockList(new MediumLockList());
4174 rc = createMediumLockList(true /* fFailIfInaccessible */,
4175 true /* fMediumLockWrite */,
4176 NULL,
4177 *pMediumLockList);
4178 if (FAILED(rc))
4179 {
4180 delete pMediumLockList;
4181 throw rc;
4182 }
4183
4184 rc = pMediumLockList->Lock();
4185 if (FAILED(rc))
4186 {
4187 delete pMediumLockList;
4188 throw setError(rc,
4189 tr("Failed to lock media when deleting '%s'"),
4190 getLocationFull().c_str());
4191 }
4192
4193 /* try to remove from the list of known media before performing
4194 * actual deletion (we favor the consistency of the media registry
4195 * which would have been broken if unregisterWithVirtualBox() failed
4196 * after we successfully deleted the storage) */
4197 rc = unregisterWithVirtualBox(pllRegistriesThatNeedSaving);
4198 if (FAILED(rc))
4199 throw rc;
4200 // no longer need lock
4201 multilock.release();
4202
4203 if (aProgress != NULL)
4204 {
4205 /* use the existing progress object... */
4206 pProgress = *aProgress;
4207
4208 /* ...but create a new one if it is null */
4209 if (pProgress.isNull())
4210 {
4211 pProgress.createObject();
4212 rc = pProgress->init(m->pVirtualBox,
4213 static_cast<IMedium*>(this),
4214 BstrFmt(tr("Deleting medium storage unit '%s'"), m->strLocationFull.c_str()).raw(),
4215 FALSE /* aCancelable */);
4216 if (FAILED(rc))
4217 throw rc;
4218 }
4219 }
4220
4221 /* setup task object to carry out the operation sync/async */
4222 pTask = new Medium::DeleteTask(this, pProgress, pMediumLockList);
4223 rc = pTask->rc();
4224 AssertComRC(rc);
4225 if (FAILED(rc))
4226 throw rc;
4227 }
4228 catch (HRESULT aRC) { rc = aRC; }
4229
4230 if (SUCCEEDED(rc))
4231 {
4232 if (aWait)
4233 rc = runNow(pTask, NULL /* pfNeedsGlobalSaveSettings*/);
4234 else
4235 rc = startThread(pTask);
4236
4237 if (SUCCEEDED(rc) && aProgress != NULL)
4238 *aProgress = pProgress;
4239
4240 }
4241 else
4242 {
4243 if (pTask)
4244 delete pTask;
4245
4246 /* Undo deleting state if necessary. */
4247 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4248 /* Make sure that any error signalled by unmarkForDeletion() is not
4249 * ending up in the error list (if the caller uses MultiResult). It
4250 * usually is spurious, as in most cases the medium hasn't been marked
4251 * for deletion when the error was thrown above. */
4252 ErrorInfoKeeper eik;
4253 unmarkForDeletion();
4254 }
4255
4256 return rc;
4257}
4258
4259/**
4260 * Mark a medium for deletion.
4261 *
4262 * @note Caller must hold the write lock on this medium!
4263 */
4264HRESULT Medium::markForDeletion()
4265{
4266 ComAssertRet(this->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
4267 switch (m->state)
4268 {
4269 case MediumState_Created:
4270 case MediumState_Inaccessible:
4271 m->preLockState = m->state;
4272 m->state = MediumState_Deleting;
4273 return S_OK;
4274 default:
4275 return setStateError();
4276 }
4277}
4278
4279/**
4280 * Removes the "mark for deletion".
4281 *
4282 * @note Caller must hold the write lock on this medium!
4283 */
4284HRESULT Medium::unmarkForDeletion()
4285{
4286 ComAssertRet(this->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
4287 switch (m->state)
4288 {
4289 case MediumState_Deleting:
4290 m->state = m->preLockState;
4291 return S_OK;
4292 default:
4293 return setStateError();
4294 }
4295}
4296
4297/**
4298 * Mark a medium for deletion which is in locked state.
4299 *
4300 * @note Caller must hold the write lock on this medium!
4301 */
4302HRESULT Medium::markLockedForDeletion()
4303{
4304 ComAssertRet(this->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
4305 if ( ( m->state == MediumState_LockedRead
4306 || m->state == MediumState_LockedWrite)
4307 && m->preLockState == MediumState_Created)
4308 {
4309 m->preLockState = MediumState_Deleting;
4310 return S_OK;
4311 }
4312 else
4313 return setStateError();
4314}
4315
4316/**
4317 * Removes the "mark for deletion" for a medium in locked state.
4318 *
4319 * @note Caller must hold the write lock on this medium!
4320 */
4321HRESULT Medium::unmarkLockedForDeletion()
4322{
4323 ComAssertRet(this->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
4324 if ( ( m->state == MediumState_LockedRead
4325 || m->state == MediumState_LockedWrite)
4326 && m->preLockState == MediumState_Deleting)
4327 {
4328 m->preLockState = MediumState_Created;
4329 return S_OK;
4330 }
4331 else
4332 return setStateError();
4333}
4334
4335/**
4336 * Prepares this (source) medium, target medium and all intermediate media
4337 * for the merge operation.
4338 *
4339 * This method is to be called prior to calling the #mergeTo() to perform
4340 * necessary consistency checks and place involved media to appropriate
4341 * states. If #mergeTo() is not called or fails, the state modifications
4342 * performed by this method must be undone by #cancelMergeTo().
4343 *
4344 * See #mergeTo() for more information about merging.
4345 *
4346 * @param pTarget Target medium.
4347 * @param aMachineId Allowed machine attachment. NULL means do not check.
4348 * @param aSnapshotId Allowed snapshot attachment. NULL or empty UUID means
4349 * do not check.
4350 * @param fLockMedia Flag whether to lock the medium lock list or not.
4351 * If set to false and the medium lock list locking fails
4352 * later you must call #cancelMergeTo().
4353 * @param fMergeForward Resulting merge direction (out).
4354 * @param pParentForTarget New parent for target medium after merge (out).
4355 * @param aChildrenToReparent List of children of the source which will have
4356 * to be reparented to the target after merge (out).
4357 * @param aMediumLockList Medium locking information (out).
4358 *
4359 * @note Locks medium tree for reading. Locks this object, aTarget and all
4360 * intermediate media for writing.
4361 */
4362HRESULT Medium::prepareMergeTo(const ComObjPtr<Medium> &pTarget,
4363 const Guid *aMachineId,
4364 const Guid *aSnapshotId,
4365 bool fLockMedia,
4366 bool &fMergeForward,
4367 ComObjPtr<Medium> &pParentForTarget,
4368 MediaList &aChildrenToReparent,
4369 MediumLockList * &aMediumLockList)
4370{
4371 AssertReturn(pTarget != NULL, E_FAIL);
4372 AssertReturn(pTarget != this, E_FAIL);
4373
4374 AutoCaller autoCaller(this);
4375 AssertComRCReturnRC(autoCaller.rc());
4376
4377 AutoCaller targetCaller(pTarget);
4378 AssertComRCReturnRC(targetCaller.rc());
4379
4380 HRESULT rc = S_OK;
4381 fMergeForward = false;
4382 pParentForTarget.setNull();
4383 aChildrenToReparent.clear();
4384 Assert(aMediumLockList == NULL);
4385 aMediumLockList = NULL;
4386
4387 try
4388 {
4389 // locking: we need the tree lock first because we access parent pointers
4390 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4391
4392 /* more sanity checking and figuring out the merge direction */
4393 ComObjPtr<Medium> pMedium = getParent();
4394 while (!pMedium.isNull() && pMedium != pTarget)
4395 pMedium = pMedium->getParent();
4396 if (pMedium == pTarget)
4397 fMergeForward = false;
4398 else
4399 {
4400 pMedium = pTarget->getParent();
4401 while (!pMedium.isNull() && pMedium != this)
4402 pMedium = pMedium->getParent();
4403 if (pMedium == this)
4404 fMergeForward = true;
4405 else
4406 {
4407 Utf8Str tgtLoc;
4408 {
4409 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
4410 tgtLoc = pTarget->getLocationFull();
4411 }
4412
4413 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4414 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4415 tr("Media '%s' and '%s' are unrelated"),
4416 m->strLocationFull.c_str(), tgtLoc.c_str());
4417 }
4418 }
4419
4420 /* Build the lock list. */
4421 aMediumLockList = new MediumLockList();
4422 if (fMergeForward)
4423 rc = pTarget->createMediumLockList(true /* fFailIfInaccessible */,
4424 true /* fMediumLockWrite */,
4425 NULL,
4426 *aMediumLockList);
4427 else
4428 rc = createMediumLockList(true /* fFailIfInaccessible */,
4429 false /* fMediumLockWrite */,
4430 NULL,
4431 *aMediumLockList);
4432 if (FAILED(rc))
4433 throw rc;
4434
4435 /* Sanity checking, must be after lock list creation as it depends on
4436 * valid medium states. The medium objects must be accessible. Only
4437 * do this if immediate locking is requested, otherwise it fails when
4438 * we construct a medium lock list for an already running VM. Snapshot
4439 * deletion uses this to simplify its life. */
4440 if (fLockMedia)
4441 {
4442 {
4443 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4444 if (m->state != MediumState_Created)
4445 throw setStateError();
4446 }
4447 {
4448 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
4449 if (pTarget->m->state != MediumState_Created)
4450 throw pTarget->setStateError();
4451 }
4452 }
4453
4454 /* check medium attachment and other sanity conditions */
4455 if (fMergeForward)
4456 {
4457 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4458 if (getChildren().size() > 1)
4459 {
4460 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4461 tr("Medium '%s' involved in the merge operation has more than one child medium (%d)"),
4462 m->strLocationFull.c_str(), getChildren().size());
4463 }
4464 /* One backreference is only allowed if the machine ID is not empty
4465 * and it matches the machine the medium is attached to (including
4466 * the snapshot ID if not empty). */
4467 if ( m->backRefs.size() != 0
4468 && ( !aMachineId
4469 || m->backRefs.size() != 1
4470 || aMachineId->isEmpty()
4471 || *getFirstMachineBackrefId() != *aMachineId
4472 || ( (!aSnapshotId || !aSnapshotId->isEmpty())
4473 && *getFirstMachineBackrefSnapshotId() != *aSnapshotId)))
4474 throw setError(VBOX_E_OBJECT_IN_USE,
4475 tr("Medium '%s' is attached to %d virtual machines"),
4476 m->strLocationFull.c_str(), m->backRefs.size());
4477 if (m->type == MediumType_Immutable)
4478 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4479 tr("Medium '%s' is immutable"),
4480 m->strLocationFull.c_str());
4481 if (m->type == MediumType_MultiAttach)
4482 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4483 tr("Medium '%s' is multi-attach"),
4484 m->strLocationFull.c_str());
4485 }
4486 else
4487 {
4488 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
4489 if (pTarget->getChildren().size() > 1)
4490 {
4491 throw setError(VBOX_E_OBJECT_IN_USE,
4492 tr("Medium '%s' involved in the merge operation has more than one child medium (%d)"),
4493 pTarget->m->strLocationFull.c_str(),
4494 pTarget->getChildren().size());
4495 }
4496 if (pTarget->m->type == MediumType_Immutable)
4497 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4498 tr("Medium '%s' is immutable"),
4499 pTarget->m->strLocationFull.c_str());
4500 if (pTarget->m->type == MediumType_MultiAttach)
4501 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4502 tr("Medium '%s' is multi-attach"),
4503 pTarget->m->strLocationFull.c_str());
4504 }
4505 ComObjPtr<Medium> pLast(fMergeForward ? (Medium *)pTarget : this);
4506 ComObjPtr<Medium> pLastIntermediate = pLast->getParent();
4507 for (pLast = pLastIntermediate;
4508 !pLast.isNull() && pLast != pTarget && pLast != this;
4509 pLast = pLast->getParent())
4510 {
4511 AutoReadLock alock(pLast COMMA_LOCKVAL_SRC_POS);
4512 if (pLast->getChildren().size() > 1)
4513 {
4514 throw setError(VBOX_E_OBJECT_IN_USE,
4515 tr("Medium '%s' involved in the merge operation has more than one child medium (%d)"),
4516 pLast->m->strLocationFull.c_str(),
4517 pLast->getChildren().size());
4518 }
4519 if (pLast->m->backRefs.size() != 0)
4520 throw setError(VBOX_E_OBJECT_IN_USE,
4521 tr("Medium '%s' is attached to %d virtual machines"),
4522 pLast->m->strLocationFull.c_str(),
4523 pLast->m->backRefs.size());
4524
4525 }
4526
4527 /* Update medium states appropriately */
4528 if (m->state == MediumState_Created)
4529 {
4530 rc = markForDeletion();
4531 if (FAILED(rc))
4532 throw rc;
4533 }
4534 else
4535 {
4536 if (fLockMedia)
4537 throw setStateError();
4538 else if ( m->state == MediumState_LockedWrite
4539 || m->state == MediumState_LockedRead)
4540 {
4541 /* Either mark it for deletion in locked state or allow
4542 * others to have done so. */
4543 if (m->preLockState == MediumState_Created)
4544 markLockedForDeletion();
4545 else if (m->preLockState != MediumState_Deleting)
4546 throw setStateError();
4547 }
4548 else
4549 throw setStateError();
4550 }
4551
4552 if (fMergeForward)
4553 {
4554 /* we will need parent to reparent target */
4555 pParentForTarget = m->pParent;
4556 }
4557 else
4558 {
4559 /* we will need to reparent children of the source */
4560 for (MediaList::const_iterator it = getChildren().begin();
4561 it != getChildren().end();
4562 ++it)
4563 {
4564 pMedium = *it;
4565 if (fLockMedia)
4566 {
4567 rc = pMedium->LockWrite(NULL);
4568 if (FAILED(rc))
4569 throw rc;
4570 }
4571
4572 aChildrenToReparent.push_back(pMedium);
4573 }
4574 }
4575 for (pLast = pLastIntermediate;
4576 !pLast.isNull() && pLast != pTarget && pLast != this;
4577 pLast = pLast->getParent())
4578 {
4579 AutoWriteLock alock(pLast COMMA_LOCKVAL_SRC_POS);
4580 if (pLast->m->state == MediumState_Created)
4581 {
4582 rc = pLast->markForDeletion();
4583 if (FAILED(rc))
4584 throw rc;
4585 }
4586 else
4587 throw pLast->setStateError();
4588 }
4589
4590 /* Tweak the lock list in the backward merge case, as the target
4591 * isn't marked to be locked for writing yet. */
4592 if (!fMergeForward)
4593 {
4594 MediumLockList::Base::iterator lockListBegin =
4595 aMediumLockList->GetBegin();
4596 MediumLockList::Base::iterator lockListEnd =
4597 aMediumLockList->GetEnd();
4598 lockListEnd--;
4599 for (MediumLockList::Base::iterator it = lockListBegin;
4600 it != lockListEnd;
4601 ++it)
4602 {
4603 MediumLock &mediumLock = *it;
4604 if (mediumLock.GetMedium() == pTarget)
4605 {
4606 HRESULT rc2 = mediumLock.UpdateLock(true);
4607 AssertComRC(rc2);
4608 break;
4609 }
4610 }
4611 }
4612
4613 if (fLockMedia)
4614 {
4615 rc = aMediumLockList->Lock();
4616 if (FAILED(rc))
4617 {
4618 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
4619 throw setError(rc,
4620 tr("Failed to lock media when merging to '%s'"),
4621 pTarget->getLocationFull().c_str());
4622 }
4623 }
4624 }
4625 catch (HRESULT aRC) { rc = aRC; }
4626
4627 if (FAILED(rc))
4628 {
4629 delete aMediumLockList;
4630 aMediumLockList = NULL;
4631 }
4632
4633 return rc;
4634}
4635
4636/**
4637 * Merges this medium to the specified medium which must be either its
4638 * direct ancestor or descendant.
4639 *
4640 * Given this medium is SOURCE and the specified medium is TARGET, we will
4641 * get two variants of the merge operation:
4642 *
4643 * forward merge
4644 * ------------------------->
4645 * [Extra] <- SOURCE <- Intermediate <- TARGET
4646 * Any Del Del LockWr
4647 *
4648 *
4649 * backward merge
4650 * <-------------------------
4651 * TARGET <- Intermediate <- SOURCE <- [Extra]
4652 * LockWr Del Del LockWr
4653 *
4654 * Each diagram shows the involved media on the media chain where
4655 * SOURCE and TARGET belong. Under each medium there is a state value which
4656 * the medium must have at a time of the mergeTo() call.
4657 *
4658 * The media in the square braces may be absent (e.g. when the forward
4659 * operation takes place and SOURCE is the base medium, or when the backward
4660 * merge operation takes place and TARGET is the last child in the chain) but if
4661 * they present they are involved too as shown.
4662 *
4663 * Neither the source medium nor intermediate media may be attached to
4664 * any VM directly or in the snapshot, otherwise this method will assert.
4665 *
4666 * The #prepareMergeTo() method must be called prior to this method to place all
4667 * involved to necessary states and perform other consistency checks.
4668 *
4669 * If @a aWait is @c true then this method will perform the operation on the
4670 * calling thread and will not return to the caller until the operation is
4671 * completed. When this method succeeds, all intermediate medium objects in
4672 * the chain will be uninitialized, the state of the target medium (and all
4673 * involved extra media) will be restored. @a aMediumLockList will not be
4674 * deleted, whether the operation is successful or not. The caller has to do
4675 * this if appropriate. Note that this (source) medium is not uninitialized
4676 * because of possible AutoCaller instances held by the caller of this method
4677 * on the current thread. It's therefore the responsibility of the caller to
4678 * call Medium::uninit() after releasing all callers.
4679 *
4680 * If @a aWait is @c false then this method will create a thread to perform the
4681 * operation asynchronously and will return immediately. If the operation
4682 * succeeds, the thread will uninitialize the source medium object and all
4683 * intermediate medium objects in the chain, reset the state of the target
4684 * medium (and all involved extra media) and delete @a aMediumLockList.
4685 * If the operation fails, the thread will only reset the states of all
4686 * involved media and delete @a aMediumLockList.
4687 *
4688 * When this method fails (regardless of the @a aWait mode), it is a caller's
4689 * responsibility to undo state changes and delete @a aMediumLockList using
4690 * #cancelMergeTo().
4691 *
4692 * If @a aProgress is not NULL but the object it points to is @c null then a new
4693 * progress object will be created and assigned to @a *aProgress on success,
4694 * otherwise the existing progress object is used. If Progress is NULL, then no
4695 * progress object is created/used at all. Note that @a aProgress cannot be
4696 * NULL when @a aWait is @c false (this method will assert in this case).
4697 *
4698 * @param pTarget Target medium.
4699 * @param fMergeForward Merge direction.
4700 * @param pParentForTarget New parent for target medium after merge.
4701 * @param aChildrenToReparent List of children of the source which will have
4702 * to be reparented to the target after merge.
4703 * @param aMediumLockList Medium locking information.
4704 * @param aProgress Where to find/store a Progress object to track operation
4705 * completion.
4706 * @param aWait @c true if this method should block instead of creating
4707 * an asynchronous thread.
4708 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
4709 * by this function if the caller should invoke VirtualBox::saveRegistries() because the global settings have changed.
4710 * This only works in "wait" mode; otherwise saveRegistries gets called automatically by the thread that was created,
4711 * and this parameter is ignored.
4712 *
4713 * @note Locks the tree lock for writing. Locks the media from the chain
4714 * for writing.
4715 */
4716HRESULT Medium::mergeTo(const ComObjPtr<Medium> &pTarget,
4717 bool fMergeForward,
4718 const ComObjPtr<Medium> &pParentForTarget,
4719 const MediaList &aChildrenToReparent,
4720 MediumLockList *aMediumLockList,
4721 ComObjPtr <Progress> *aProgress,
4722 bool aWait,
4723 GuidList *pllRegistriesThatNeedSaving)
4724{
4725 AssertReturn(pTarget != NULL, E_FAIL);
4726 AssertReturn(pTarget != this, E_FAIL);
4727 AssertReturn(aMediumLockList != NULL, E_FAIL);
4728 AssertReturn(aProgress != NULL || aWait == true, E_FAIL);
4729
4730 AutoCaller autoCaller(this);
4731 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4732
4733 AutoCaller targetCaller(pTarget);
4734 AssertComRCReturnRC(targetCaller.rc());
4735
4736 HRESULT rc = S_OK;
4737 ComObjPtr <Progress> pProgress;
4738 Medium::Task *pTask = NULL;
4739
4740 try
4741 {
4742 if (aProgress != NULL)
4743 {
4744 /* use the existing progress object... */
4745 pProgress = *aProgress;
4746
4747 /* ...but create a new one if it is null */
4748 if (pProgress.isNull())
4749 {
4750 Utf8Str tgtName;
4751 {
4752 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
4753 tgtName = pTarget->getName();
4754 }
4755
4756 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4757
4758 pProgress.createObject();
4759 rc = pProgress->init(m->pVirtualBox,
4760 static_cast<IMedium*>(this),
4761 BstrFmt(tr("Merging medium '%s' to '%s'"),
4762 getName().c_str(),
4763 tgtName.c_str()).raw(),
4764 TRUE /* aCancelable */);
4765 if (FAILED(rc))
4766 throw rc;
4767 }
4768 }
4769
4770 /* setup task object to carry out the operation sync/async */
4771 pTask = new Medium::MergeTask(this, pTarget, fMergeForward,
4772 pParentForTarget, aChildrenToReparent,
4773 pProgress, aMediumLockList,
4774 aWait /* fKeepMediumLockList */);
4775 rc = pTask->rc();
4776 AssertComRC(rc);
4777 if (FAILED(rc))
4778 throw rc;
4779 }
4780 catch (HRESULT aRC) { rc = aRC; }
4781
4782 if (SUCCEEDED(rc))
4783 {
4784 if (aWait)
4785 rc = runNow(pTask, pllRegistriesThatNeedSaving);
4786 else
4787 rc = startThread(pTask);
4788
4789 if (SUCCEEDED(rc) && aProgress != NULL)
4790 *aProgress = pProgress;
4791 }
4792 else if (pTask != NULL)
4793 delete pTask;
4794
4795 return rc;
4796}
4797
4798/**
4799 * Undoes what #prepareMergeTo() did. Must be called if #mergeTo() is not
4800 * called or fails. Frees memory occupied by @a aMediumLockList and unlocks
4801 * the medium objects in @a aChildrenToReparent.
4802 *
4803 * @param aChildrenToReparent List of children of the source which will have
4804 * to be reparented to the target after merge.
4805 * @param aMediumLockList Medium locking information.
4806 *
4807 * @note Locks the media from the chain for writing.
4808 */
4809void Medium::cancelMergeTo(const MediaList &aChildrenToReparent,
4810 MediumLockList *aMediumLockList)
4811{
4812 AutoCaller autoCaller(this);
4813 AssertComRCReturnVoid(autoCaller.rc());
4814
4815 AssertReturnVoid(aMediumLockList != NULL);
4816
4817 /* Revert media marked for deletion to previous state. */
4818 HRESULT rc;
4819 MediumLockList::Base::const_iterator mediumListBegin =
4820 aMediumLockList->GetBegin();
4821 MediumLockList::Base::const_iterator mediumListEnd =
4822 aMediumLockList->GetEnd();
4823 for (MediumLockList::Base::const_iterator it = mediumListBegin;
4824 it != mediumListEnd;
4825 ++it)
4826 {
4827 const MediumLock &mediumLock = *it;
4828 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
4829 AutoWriteLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
4830
4831 if (pMedium->m->state == MediumState_Deleting)
4832 {
4833 rc = pMedium->unmarkForDeletion();
4834 AssertComRC(rc);
4835 }
4836 }
4837
4838 /* the destructor will do the work */
4839 delete aMediumLockList;
4840
4841 /* unlock the children which had to be reparented */
4842 for (MediaList::const_iterator it = aChildrenToReparent.begin();
4843 it != aChildrenToReparent.end();
4844 ++it)
4845 {
4846 const ComObjPtr<Medium> &pMedium = *it;
4847
4848 AutoWriteLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
4849 pMedium->UnlockWrite(NULL);
4850 }
4851}
4852
4853/**
4854 * Fix the parent UUID of all children to point to this medium as their
4855 * parent.
4856 */
4857HRESULT Medium::fixParentUuidOfChildren(const MediaList &childrenToReparent)
4858{
4859 MediumLockList mediumLockList;
4860 HRESULT rc = createMediumLockList(true /* fFailIfInaccessible */,
4861 false /* fMediumLockWrite */,
4862 this,
4863 mediumLockList);
4864 AssertComRCReturnRC(rc);
4865
4866 try
4867 {
4868 PVBOXHDD hdd;
4869 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
4870 ComAssertRCThrow(vrc, E_FAIL);
4871
4872 try
4873 {
4874 MediumLockList::Base::iterator lockListBegin =
4875 mediumLockList.GetBegin();
4876 MediumLockList::Base::iterator lockListEnd =
4877 mediumLockList.GetEnd();
4878 for (MediumLockList::Base::iterator it = lockListBegin;
4879 it != lockListEnd;
4880 ++it)
4881 {
4882 MediumLock &mediumLock = *it;
4883 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
4884 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
4885
4886 // open the medium
4887 vrc = VDOpen(hdd,
4888 pMedium->m->strFormat.c_str(),
4889 pMedium->m->strLocationFull.c_str(),
4890 VD_OPEN_FLAGS_READONLY,
4891 pMedium->m->vdImageIfaces);
4892 if (RT_FAILURE(vrc))
4893 throw vrc;
4894 }
4895
4896 for (MediaList::const_iterator it = childrenToReparent.begin();
4897 it != childrenToReparent.end();
4898 ++it)
4899 {
4900 /* VD_OPEN_FLAGS_INFO since UUID is wrong yet */
4901 vrc = VDOpen(hdd,
4902 (*it)->m->strFormat.c_str(),
4903 (*it)->m->strLocationFull.c_str(),
4904 VD_OPEN_FLAGS_INFO,
4905 (*it)->m->vdImageIfaces);
4906 if (RT_FAILURE(vrc))
4907 throw vrc;
4908
4909 vrc = VDSetParentUuid(hdd, VD_LAST_IMAGE, m->id.raw());
4910 if (RT_FAILURE(vrc))
4911 throw vrc;
4912
4913 vrc = VDClose(hdd, false /* fDelete */);
4914 if (RT_FAILURE(vrc))
4915 throw vrc;
4916
4917 (*it)->UnlockWrite(NULL);
4918 }
4919 }
4920 catch (HRESULT aRC) { rc = aRC; }
4921 catch (int aVRC)
4922 {
4923 rc = setError(E_FAIL,
4924 tr("Could not update medium UUID references to parent '%s' (%s)"),
4925 m->strLocationFull.c_str(),
4926 vdError(aVRC).c_str());
4927 }
4928
4929 VDDestroy(hdd);
4930 }
4931 catch (HRESULT aRC) { rc = aRC; }
4932
4933 return rc;
4934}
4935
4936/**
4937 * Used by IAppliance to export disk images.
4938 *
4939 * @param aFilename Filename to create (UTF8).
4940 * @param aFormat Medium format for creating @a aFilename.
4941 * @param aVariant Which exact image format variant to use
4942 * for the destination image.
4943 * @param aVDImageIOCallbacks Pointer to the callback table for a
4944 * VDINTERFACEIO interface. May be NULL.
4945 * @param aVDImageIOUser Opaque data for the callbacks.
4946 * @param aProgress Progress object to use.
4947 * @return
4948 * @note The source format is defined by the Medium instance.
4949 */
4950HRESULT Medium::exportFile(const char *aFilename,
4951 const ComObjPtr<MediumFormat> &aFormat,
4952 MediumVariant_T aVariant,
4953 PVDINTERFACEIO aVDImageIOIf, void *aVDImageIOUser,
4954 const ComObjPtr<Progress> &aProgress)
4955{
4956 AssertPtrReturn(aFilename, E_INVALIDARG);
4957 AssertReturn(!aFormat.isNull(), E_INVALIDARG);
4958 AssertReturn(!aProgress.isNull(), E_INVALIDARG);
4959
4960 AutoCaller autoCaller(this);
4961 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4962
4963 HRESULT rc = S_OK;
4964 Medium::Task *pTask = NULL;
4965
4966 try
4967 {
4968 // locking: we need the tree lock first because we access parent pointers
4969 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4970 // and we need to write-lock the media involved
4971 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4972
4973 /* Build the source lock list. */
4974 MediumLockList *pSourceMediumLockList(new MediumLockList());
4975 rc = createMediumLockList(true /* fFailIfInaccessible */,
4976 false /* fMediumLockWrite */,
4977 NULL,
4978 *pSourceMediumLockList);
4979 if (FAILED(rc))
4980 {
4981 delete pSourceMediumLockList;
4982 throw rc;
4983 }
4984
4985 rc = pSourceMediumLockList->Lock();
4986 if (FAILED(rc))
4987 {
4988 delete pSourceMediumLockList;
4989 throw setError(rc,
4990 tr("Failed to lock source media '%s'"),
4991 getLocationFull().c_str());
4992 }
4993
4994 /* setup task object to carry out the operation asynchronously */
4995 pTask = new Medium::ExportTask(this, aProgress, aFilename, aFormat,
4996 aVariant, aVDImageIOIf,
4997 aVDImageIOUser, pSourceMediumLockList);
4998 rc = pTask->rc();
4999 AssertComRC(rc);
5000 if (FAILED(rc))
5001 throw rc;
5002 }
5003 catch (HRESULT aRC) { rc = aRC; }
5004
5005 if (SUCCEEDED(rc))
5006 rc = startThread(pTask);
5007 else if (pTask != NULL)
5008 delete pTask;
5009
5010 return rc;
5011}
5012
5013/**
5014 * Used by IAppliance to import disk images.
5015 *
5016 * @param aFilename Filename to read (UTF8).
5017 * @param aFormat Medium format for reading @a aFilename.
5018 * @param aVariant Which exact image format variant to use
5019 * for the destination image.
5020 * @param aVDImageIOCallbacks Pointer to the callback table for a
5021 * VDINTERFACEIO interface. May be NULL.
5022 * @param aVDImageIOUser Opaque data for the callbacks.
5023 * @param aParent Parent medium. May be NULL.
5024 * @param aProgress Progress object to use.
5025 * @return
5026 * @note The destination format is defined by the Medium instance.
5027 */
5028HRESULT Medium::importFile(const char *aFilename,
5029 const ComObjPtr<MediumFormat> &aFormat,
5030 MediumVariant_T aVariant,
5031 PVDINTERFACEIO aVDImageIOIf, void *aVDImageIOUser,
5032 const ComObjPtr<Medium> &aParent,
5033 const ComObjPtr<Progress> &aProgress)
5034{
5035 AssertPtrReturn(aFilename, E_INVALIDARG);
5036 AssertReturn(!aFormat.isNull(), E_INVALIDARG);
5037 AssertReturn(!aProgress.isNull(), E_INVALIDARG);
5038
5039 AutoCaller autoCaller(this);
5040 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5041
5042 HRESULT rc = S_OK;
5043 Medium::Task *pTask = NULL;
5044
5045 try
5046 {
5047 // locking: we need the tree lock first because we access parent pointers
5048 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5049 // and we need to write-lock the media involved
5050 AutoMultiWriteLock2 alock(this, aParent COMMA_LOCKVAL_SRC_POS);
5051
5052 if ( m->state != MediumState_NotCreated
5053 && m->state != MediumState_Created)
5054 throw setStateError();
5055
5056 /* Build the target lock list. */
5057 MediumLockList *pTargetMediumLockList(new MediumLockList());
5058 rc = createMediumLockList(true /* fFailIfInaccessible */,
5059 true /* fMediumLockWrite */,
5060 aParent,
5061 *pTargetMediumLockList);
5062 if (FAILED(rc))
5063 {
5064 delete pTargetMediumLockList;
5065 throw rc;
5066 }
5067
5068 rc = pTargetMediumLockList->Lock();
5069 if (FAILED(rc))
5070 {
5071 delete pTargetMediumLockList;
5072 throw setError(rc,
5073 tr("Failed to lock target media '%s'"),
5074 getLocationFull().c_str());
5075 }
5076
5077 /* setup task object to carry out the operation asynchronously */
5078 pTask = new Medium::ImportTask(this, aProgress, aFilename, aFormat,
5079 aVariant, aVDImageIOIf,
5080 aVDImageIOUser, aParent,
5081 pTargetMediumLockList);
5082 rc = pTask->rc();
5083 AssertComRC(rc);
5084 if (FAILED(rc))
5085 throw rc;
5086
5087 if (m->state == MediumState_NotCreated)
5088 m->state = MediumState_Creating;
5089 }
5090 catch (HRESULT aRC) { rc = aRC; }
5091
5092 if (SUCCEEDED(rc))
5093 rc = startThread(pTask);
5094 else if (pTask != NULL)
5095 delete pTask;
5096
5097 return rc;
5098}
5099
5100/**
5101 * Internal version of the public CloneTo API which allows to enable certain
5102 * optimizations to improve speed during VM cloning.
5103 *
5104 * @param aTarget Target medium
5105 * @param aVariant Which exact image format variant to use
5106 * for the destination image.
5107 * @param aParent Parent medium. May be NULL.
5108 * @param aProgress Progress object to use.
5109 * @param idxSrcImageSame The last image in the source chain which has the
5110 * same content as the given image in the destination
5111 * chain. Use UINT32_MAX to disable this optimization.
5112 * @param idxDstImageSame The last image in the destination chain which has the
5113 * same content as the given image in the source chain.
5114 * Use UINT32_MAX to disable this optimization.
5115 * @return
5116 */
5117HRESULT Medium::cloneToEx(const ComObjPtr<Medium> &aTarget, ULONG aVariant,
5118 const ComObjPtr<Medium> &aParent, IProgress **aProgress,
5119 uint32_t idxSrcImageSame, uint32_t idxDstImageSame)
5120{
5121 CheckComArgNotNull(aTarget);
5122 CheckComArgOutPointerValid(aProgress);
5123 ComAssertRet(aTarget != this, E_INVALIDARG);
5124
5125 AutoCaller autoCaller(this);
5126 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5127
5128 HRESULT rc = S_OK;
5129 ComObjPtr<Progress> pProgress;
5130 Medium::Task *pTask = NULL;
5131
5132 try
5133 {
5134 // locking: we need the tree lock first because we access parent pointers
5135 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5136 // and we need to write-lock the media involved
5137 AutoMultiWriteLock3 alock(this, aTarget, aParent COMMA_LOCKVAL_SRC_POS);
5138
5139 if ( aTarget->m->state != MediumState_NotCreated
5140 && aTarget->m->state != MediumState_Created)
5141 throw aTarget->setStateError();
5142
5143 /* Build the source lock list. */
5144 MediumLockList *pSourceMediumLockList(new MediumLockList());
5145 rc = createMediumLockList(true /* fFailIfInaccessible */,
5146 false /* fMediumLockWrite */,
5147 NULL,
5148 *pSourceMediumLockList);
5149 if (FAILED(rc))
5150 {
5151 delete pSourceMediumLockList;
5152 throw rc;
5153 }
5154
5155 /* Build the target lock list (including the to-be parent chain). */
5156 MediumLockList *pTargetMediumLockList(new MediumLockList());
5157 rc = aTarget->createMediumLockList(true /* fFailIfInaccessible */,
5158 true /* fMediumLockWrite */,
5159 aParent,
5160 *pTargetMediumLockList);
5161 if (FAILED(rc))
5162 {
5163 delete pSourceMediumLockList;
5164 delete pTargetMediumLockList;
5165 throw rc;
5166 }
5167
5168 rc = pSourceMediumLockList->Lock();
5169 if (FAILED(rc))
5170 {
5171 delete pSourceMediumLockList;
5172 delete pTargetMediumLockList;
5173 throw setError(rc,
5174 tr("Failed to lock source media '%s'"),
5175 getLocationFull().c_str());
5176 }
5177 rc = pTargetMediumLockList->Lock();
5178 if (FAILED(rc))
5179 {
5180 delete pSourceMediumLockList;
5181 delete pTargetMediumLockList;
5182 throw setError(rc,
5183 tr("Failed to lock target media '%s'"),
5184 aTarget->getLocationFull().c_str());
5185 }
5186
5187 pProgress.createObject();
5188 rc = pProgress->init(m->pVirtualBox,
5189 static_cast <IMedium *>(this),
5190 BstrFmt(tr("Creating clone medium '%s'"), aTarget->m->strLocationFull.c_str()).raw(),
5191 TRUE /* aCancelable */);
5192 if (FAILED(rc))
5193 {
5194 delete pSourceMediumLockList;
5195 delete pTargetMediumLockList;
5196 throw rc;
5197 }
5198
5199 /* setup task object to carry out the operation asynchronously */
5200 pTask = new Medium::CloneTask(this, pProgress, aTarget,
5201 (MediumVariant_T)aVariant,
5202 aParent, idxSrcImageSame,
5203 idxDstImageSame, pSourceMediumLockList,
5204 pTargetMediumLockList);
5205 rc = pTask->rc();
5206 AssertComRC(rc);
5207 if (FAILED(rc))
5208 throw rc;
5209
5210 if (aTarget->m->state == MediumState_NotCreated)
5211 aTarget->m->state = MediumState_Creating;
5212 }
5213 catch (HRESULT aRC) { rc = aRC; }
5214
5215 if (SUCCEEDED(rc))
5216 {
5217 rc = startThread(pTask);
5218
5219 if (SUCCEEDED(rc))
5220 pProgress.queryInterfaceTo(aProgress);
5221 }
5222 else if (pTask != NULL)
5223 delete pTask;
5224
5225 return rc;
5226}
5227
5228////////////////////////////////////////////////////////////////////////////////
5229//
5230// Private methods
5231//
5232////////////////////////////////////////////////////////////////////////////////
5233
5234/**
5235 * Queries information from the medium.
5236 *
5237 * As a result of this call, the accessibility state and data members such as
5238 * size and description will be updated with the current information.
5239 *
5240 * @note This method may block during a system I/O call that checks storage
5241 * accessibility.
5242 *
5243 * @note Locks medium tree for reading and writing (for new diff media checked
5244 * for the first time). Locks mParent for reading. Locks this object for
5245 * writing.
5246 *
5247 * @param fSetImageId Whether to reset the UUID contained in the image file to the UUID in the medium instance data (see SetIDs())
5248 * @param fSetParentId Whether to reset the parent UUID contained in the image file to the parent UUID in the medium instance data (see SetIDs())
5249 * @return
5250 */
5251HRESULT Medium::queryInfo(bool fSetImageId, bool fSetParentId)
5252{
5253 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5254
5255 if ( m->state != MediumState_Created
5256 && m->state != MediumState_Inaccessible
5257 && m->state != MediumState_LockedRead)
5258 return E_FAIL;
5259
5260 HRESULT rc = S_OK;
5261
5262 int vrc = VINF_SUCCESS;
5263
5264 /* check if a blocking queryInfo() call is in progress on some other thread,
5265 * and wait for it to finish if so instead of querying data ourselves */
5266 if (m->queryInfoRunning)
5267 {
5268 Assert( m->state == MediumState_LockedRead
5269 || m->state == MediumState_LockedWrite);
5270
5271 alock.leave();
5272 vrc = RTSemEventMultiWait(m->queryInfoSem, RT_INDEFINITE_WAIT);
5273 alock.enter();
5274
5275 AssertRC(vrc);
5276
5277 return S_OK;
5278 }
5279
5280 bool success = false;
5281 Utf8Str lastAccessError;
5282
5283 /* are we dealing with a new medium constructed using the existing
5284 * location? */
5285 bool isImport = m->id.isEmpty();
5286 unsigned uOpenFlags = VD_OPEN_FLAGS_INFO;
5287
5288 /* Note that we don't use VD_OPEN_FLAGS_READONLY when opening new
5289 * media because that would prevent necessary modifications
5290 * when opening media of some third-party formats for the first
5291 * time in VirtualBox (such as VMDK for which VDOpen() needs to
5292 * generate an UUID if it is missing) */
5293 if ( m->hddOpenMode == OpenReadOnly
5294 || m->type == MediumType_Readonly
5295 || (!isImport && !fSetImageId && !fSetParentId)
5296 )
5297 uOpenFlags |= VD_OPEN_FLAGS_READONLY;
5298
5299 /* Open shareable medium with the appropriate flags */
5300 if (m->type == MediumType_Shareable)
5301 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
5302
5303 /* Lock the medium, which makes the behavior much more consistent */
5304 if (uOpenFlags & (VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_SHAREABLE))
5305 rc = LockRead(NULL);
5306 else
5307 rc = LockWrite(NULL);
5308 if (FAILED(rc)) return rc;
5309
5310 /* Copies of the input state fields which are not read-only,
5311 * as we're dropping the lock. CAUTION: be extremely careful what
5312 * you do with the contents of this medium object, as you will
5313 * create races if there are concurrent changes. */
5314 Utf8Str format(m->strFormat);
5315 Utf8Str location(m->strLocationFull);
5316 ComObjPtr<MediumFormat> formatObj = m->formatObj;
5317
5318 /* "Output" values which can't be set because the lock isn't held
5319 * at the time the values are determined. */
5320 Guid mediumId = m->id;
5321 uint64_t mediumSize = 0;
5322 uint64_t mediumLogicalSize = 0;
5323
5324 /* Flag whether a base image has a non-zero parent UUID and thus
5325 * need repairing after it was closed again. */
5326 bool fRepairImageZeroParentUuid = false;
5327
5328 /* leave the lock before a lengthy operation */
5329 vrc = RTSemEventMultiReset(m->queryInfoSem);
5330 AssertRCReturn(vrc, E_FAIL);
5331 m->queryInfoRunning = true;
5332 alock.leave();
5333
5334 try
5335 {
5336 /* skip accessibility checks for host drives */
5337 if (m->hostDrive)
5338 {
5339 success = true;
5340 throw S_OK;
5341 }
5342
5343 PVBOXHDD hdd;
5344 vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
5345 ComAssertRCThrow(vrc, E_FAIL);
5346
5347 try
5348 {
5349 /** @todo This kind of opening of media is assuming that diff
5350 * media can be opened as base media. Should be documented that
5351 * it must work for all medium format backends. */
5352 vrc = VDOpen(hdd,
5353 format.c_str(),
5354 location.c_str(),
5355 uOpenFlags,
5356 m->vdImageIfaces);
5357 if (RT_FAILURE(vrc))
5358 {
5359 lastAccessError = Utf8StrFmt(tr("Could not open the medium '%s'%s"),
5360 location.c_str(), vdError(vrc).c_str());
5361 throw S_OK;
5362 }
5363
5364 if (formatObj->getCapabilities() & MediumFormatCapabilities_Uuid)
5365 {
5366 /* Modify the UUIDs if necessary. The associated fields are
5367 * not modified by other code, so no need to copy. */
5368 if (fSetImageId)
5369 {
5370 vrc = VDSetUuid(hdd, 0, m->uuidImage.raw());
5371 ComAssertRCThrow(vrc, E_FAIL);
5372 mediumId = m->uuidImage;
5373 }
5374 if (fSetParentId)
5375 {
5376 vrc = VDSetParentUuid(hdd, 0, m->uuidParentImage.raw());
5377 ComAssertRCThrow(vrc, E_FAIL);
5378 }
5379 /* zap the information, these are no long-term members */
5380 unconst(m->uuidImage).clear();
5381 unconst(m->uuidParentImage).clear();
5382
5383 /* check the UUID */
5384 RTUUID uuid;
5385 vrc = VDGetUuid(hdd, 0, &uuid);
5386 ComAssertRCThrow(vrc, E_FAIL);
5387
5388 if (isImport)
5389 {
5390 mediumId = uuid;
5391
5392 if (mediumId.isEmpty() && (m->hddOpenMode == OpenReadOnly))
5393 // only when importing a VDMK that has no UUID, create one in memory
5394 mediumId.create();
5395 }
5396 else
5397 {
5398 Assert(!mediumId.isEmpty());
5399
5400 if (mediumId != uuid)
5401 {
5402 /** @todo r=klaus this always refers to VirtualBox.xml as the medium registry, even for new VMs */
5403 lastAccessError = Utf8StrFmt(
5404 tr("UUID {%RTuuid} of the medium '%s' does not match the value {%RTuuid} stored in the media registry ('%s')"),
5405 &uuid,
5406 location.c_str(),
5407 mediumId.raw(),
5408 m->pVirtualBox->settingsFilePath().c_str());
5409 throw S_OK;
5410 }
5411 }
5412 }
5413 else
5414 {
5415 /* the backend does not support storing UUIDs within the
5416 * underlying storage so use what we store in XML */
5417
5418 if (fSetImageId)
5419 {
5420 /* set the UUID if an API client wants to change it */
5421 mediumId = m->uuidImage;
5422 }
5423 else if (isImport)
5424 {
5425 /* generate an UUID for an imported UUID-less medium */
5426 mediumId.create();
5427 }
5428 }
5429
5430 /* get the medium variant */
5431 unsigned uImageFlags;
5432 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
5433 ComAssertRCThrow(vrc, E_FAIL);
5434 m->variant = (MediumVariant_T)uImageFlags;
5435
5436 /* check/get the parent uuid and update corresponding state */
5437 if (uImageFlags & VD_IMAGE_FLAGS_DIFF)
5438 {
5439 RTUUID parentId;
5440 vrc = VDGetParentUuid(hdd, 0, &parentId);
5441 ComAssertRCThrow(vrc, E_FAIL);
5442
5443 /* streamOptimized VMDK images are only accepted as base
5444 * images, as this allows automatic repair of OVF appliances.
5445 * Since such images don't support random writes they will not
5446 * be created for diff images. Only an overly smart user might
5447 * manually create this case. Too bad for him. */
5448 if ( isImport
5449 && !(uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED))
5450 {
5451 /* the parent must be known to us. Note that we freely
5452 * call locking methods of mVirtualBox and parent, as all
5453 * relevant locks must be already held. There may be no
5454 * concurrent access to the just opened medium on other
5455 * threads yet (and init() will fail if this method reports
5456 * MediumState_Inaccessible) */
5457
5458 Guid id = parentId;
5459 ComObjPtr<Medium> pParent;
5460 rc = m->pVirtualBox->findHardDiskById(id, false /* aSetError */, &pParent);
5461 if (FAILED(rc))
5462 {
5463 lastAccessError = Utf8StrFmt(
5464 tr("Parent medium with UUID {%RTuuid} of the medium '%s' is not found in the media registry ('%s')"),
5465 &parentId, location.c_str(),
5466 m->pVirtualBox->settingsFilePath().c_str());
5467 throw S_OK;
5468 }
5469
5470 /* we set mParent & children() */
5471 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5472
5473 Assert(m->pParent.isNull());
5474 m->pParent = pParent;
5475 m->pParent->m->llChildren.push_back(this);
5476 }
5477 else
5478 {
5479 /* we access mParent */
5480 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5481
5482 /* check that parent UUIDs match. Note that there's no need
5483 * for the parent's AutoCaller (our lifetime is bound to
5484 * it) */
5485
5486 if (m->pParent.isNull())
5487 {
5488 /* Due to a bug in VDCopy() in VirtualBox 3.0.0-3.0.14
5489 * and 3.1.0-3.1.8 there are base images out there
5490 * which have a non-zero parent UUID. No point in
5491 * complaining about them, instead automatically
5492 * repair the problem. Later we can bring back the
5493 * error message, but we should wait until really
5494 * most users have repaired their images, either with
5495 * VBoxFixHdd or this way. */
5496#if 1
5497 fRepairImageZeroParentUuid = true;
5498#else /* 0 */
5499 lastAccessError = Utf8StrFmt(
5500 tr("Medium type of '%s' is differencing but it is not associated with any parent medium in the media registry ('%s')"),
5501 location.c_str(),
5502 m->pVirtualBox->settingsFilePath().c_str());
5503 throw S_OK;
5504#endif /* 0 */
5505 }
5506
5507 AutoReadLock parentLock(m->pParent COMMA_LOCKVAL_SRC_POS);
5508 if ( !fRepairImageZeroParentUuid
5509 && m->pParent->getState() != MediumState_Inaccessible
5510 && m->pParent->getId() != parentId)
5511 {
5512 /** @todo r=klaus this always refers to VirtualBox.xml as the medium registry, even for new VMs */
5513 lastAccessError = Utf8StrFmt(
5514 tr("Parent UUID {%RTuuid} of the medium '%s' does not match UUID {%RTuuid} of its parent medium stored in the media registry ('%s')"),
5515 &parentId, location.c_str(),
5516 m->pParent->getId().raw(),
5517 m->pVirtualBox->settingsFilePath().c_str());
5518 throw S_OK;
5519 }
5520
5521 /// @todo NEWMEDIA what to do if the parent is not
5522 /// accessible while the diff is? Probably nothing. The
5523 /// real code will detect the mismatch anyway.
5524 }
5525 }
5526
5527 mediumSize = VDGetFileSize(hdd, 0);
5528 mediumLogicalSize = VDGetSize(hdd, 0);
5529
5530 success = true;
5531 }
5532 catch (HRESULT aRC)
5533 {
5534 rc = aRC;
5535 }
5536
5537 VDDestroy(hdd);
5538 }
5539 catch (HRESULT aRC)
5540 {
5541 rc = aRC;
5542 }
5543
5544 alock.enter();
5545
5546 if (isImport || fSetImageId)
5547 unconst(m->id) = mediumId;
5548
5549 if (success)
5550 {
5551 m->size = mediumSize;
5552 m->logicalSize = mediumLogicalSize;
5553 m->strLastAccessError.setNull();
5554 }
5555 else
5556 {
5557 m->strLastAccessError = lastAccessError;
5558 LogWarningFunc(("'%s' is not accessible (error='%s', rc=%Rhrc, vrc=%Rrc)\n",
5559 location.c_str(), m->strLastAccessError.c_str(),
5560 rc, vrc));
5561 }
5562
5563 /* inform other callers if there are any */
5564 RTSemEventMultiSignal(m->queryInfoSem);
5565 m->queryInfoRunning = false;
5566
5567 /* Set the proper state according to the result of the check */
5568 if (success)
5569 m->preLockState = MediumState_Created;
5570 else
5571 m->preLockState = MediumState_Inaccessible;
5572
5573 HRESULT rc2;
5574 if (uOpenFlags & (VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_SHAREABLE))
5575 rc2 = UnlockRead(NULL);
5576 else
5577 rc2 = UnlockWrite(NULL);
5578 if (SUCCEEDED(rc) && FAILED(rc2))
5579 rc = rc2;
5580 if (FAILED(rc)) return rc;
5581
5582 /* If this is a base image which incorrectly has a parent UUID set,
5583 * repair the image now by zeroing the parent UUID. This is only done
5584 * when we have structural information from a config file, on import
5585 * this is not possible. If someone would accidentally call openMedium
5586 * with a diff image before the base is registered this would destroy
5587 * the diff. Not acceptable. */
5588 if (fRepairImageZeroParentUuid)
5589 {
5590 rc = LockWrite(NULL);
5591 if (FAILED(rc)) return rc;
5592
5593 alock.leave();
5594
5595 try
5596 {
5597 PVBOXHDD hdd;
5598 vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
5599 ComAssertRCThrow(vrc, E_FAIL);
5600
5601 try
5602 {
5603 vrc = VDOpen(hdd,
5604 format.c_str(),
5605 location.c_str(),
5606 uOpenFlags & ~VD_OPEN_FLAGS_READONLY,
5607 m->vdImageIfaces);
5608 if (RT_FAILURE(vrc))
5609 throw S_OK;
5610
5611 RTUUID zeroParentUuid;
5612 RTUuidClear(&zeroParentUuid);
5613 vrc = VDSetParentUuid(hdd, 0, &zeroParentUuid);
5614 ComAssertRCThrow(vrc, E_FAIL);
5615 }
5616 catch (HRESULT aRC)
5617 {
5618 rc = aRC;
5619 }
5620
5621 VDDestroy(hdd);
5622 }
5623 catch (HRESULT aRC)
5624 {
5625 rc = aRC;
5626 }
5627
5628 alock.enter();
5629
5630 rc = UnlockWrite(NULL);
5631 if (SUCCEEDED(rc) && FAILED(rc2))
5632 rc = rc2;
5633 if (FAILED(rc)) return rc;
5634 }
5635
5636 return rc;
5637}
5638
5639/**
5640 * Performs extra checks if the medium can be closed and returns S_OK in
5641 * this case. Otherwise, returns a respective error message. Called by
5642 * Close() under the medium tree lock and the medium lock.
5643 *
5644 * @note Also reused by Medium::Reset().
5645 *
5646 * @note Caller must hold the media tree write lock!
5647 */
5648HRESULT Medium::canClose()
5649{
5650 Assert(m->pVirtualBox->getMediaTreeLockHandle().isWriteLockOnCurrentThread());
5651
5652 if (getChildren().size() != 0)
5653 return setError(VBOX_E_OBJECT_IN_USE,
5654 tr("Cannot close medium '%s' because it has %d child media"),
5655 m->strLocationFull.c_str(), getChildren().size());
5656
5657 return S_OK;
5658}
5659
5660/**
5661 * Unregisters this medium with mVirtualBox. Called by close() under the medium tree lock.
5662 *
5663 * This calls either VirtualBox::unregisterImage or VirtualBox::unregisterHardDisk depending
5664 * on the device type of this medium.
5665 *
5666 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs that will receive the registry IDs that need saving.
5667 *
5668 * @note Caller must have locked the media tree lock for writing!
5669 */
5670HRESULT Medium::unregisterWithVirtualBox(GuidList *pllRegistriesThatNeedSaving)
5671{
5672 /* Note that we need to de-associate ourselves from the parent to let
5673 * unregisterHardDisk() properly save the registry */
5674
5675 /* we modify mParent and access children */
5676 Assert(m->pVirtualBox->getMediaTreeLockHandle().isWriteLockOnCurrentThread());
5677
5678 Medium *pParentBackup = m->pParent;
5679 AssertReturn(getChildren().size() == 0, E_FAIL);
5680 if (m->pParent)
5681 deparent();
5682
5683 HRESULT rc = E_FAIL;
5684 switch (m->devType)
5685 {
5686 case DeviceType_DVD:
5687 case DeviceType_Floppy:
5688 rc = m->pVirtualBox->unregisterImage(this,
5689 m->devType,
5690 pllRegistriesThatNeedSaving);
5691 break;
5692
5693 case DeviceType_HardDisk:
5694 rc = m->pVirtualBox->unregisterHardDisk(this, pllRegistriesThatNeedSaving);
5695 break;
5696
5697 default:
5698 break;
5699 }
5700
5701 if (FAILED(rc))
5702 {
5703 if (pParentBackup)
5704 {
5705 // re-associate with the parent as we are still relatives in the registry
5706 m->pParent = pParentBackup;
5707 m->pParent->m->llChildren.push_back(this);
5708 }
5709 }
5710
5711 return rc;
5712}
5713
5714/**
5715 * Sets the extended error info according to the current media state.
5716 *
5717 * @note Must be called from under this object's write or read lock.
5718 */
5719HRESULT Medium::setStateError()
5720{
5721 HRESULT rc = E_FAIL;
5722
5723 switch (m->state)
5724 {
5725 case MediumState_NotCreated:
5726 {
5727 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5728 tr("Storage for the medium '%s' is not created"),
5729 m->strLocationFull.c_str());
5730 break;
5731 }
5732 case MediumState_Created:
5733 {
5734 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5735 tr("Storage for the medium '%s' is already created"),
5736 m->strLocationFull.c_str());
5737 break;
5738 }
5739 case MediumState_LockedRead:
5740 {
5741 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5742 tr("Medium '%s' is locked for reading by another task"),
5743 m->strLocationFull.c_str());
5744 break;
5745 }
5746 case MediumState_LockedWrite:
5747 {
5748 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5749 tr("Medium '%s' is locked for writing by another task"),
5750 m->strLocationFull.c_str());
5751 break;
5752 }
5753 case MediumState_Inaccessible:
5754 {
5755 /* be in sync with Console::powerUpThread() */
5756 if (!m->strLastAccessError.isEmpty())
5757 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5758 tr("Medium '%s' is not accessible. %s"),
5759 m->strLocationFull.c_str(), m->strLastAccessError.c_str());
5760 else
5761 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5762 tr("Medium '%s' is not accessible"),
5763 m->strLocationFull.c_str());
5764 break;
5765 }
5766 case MediumState_Creating:
5767 {
5768 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5769 tr("Storage for the medium '%s' is being created"),
5770 m->strLocationFull.c_str());
5771 break;
5772 }
5773 case MediumState_Deleting:
5774 {
5775 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5776 tr("Storage for the medium '%s' is being deleted"),
5777 m->strLocationFull.c_str());
5778 break;
5779 }
5780 default:
5781 {
5782 AssertFailed();
5783 break;
5784 }
5785 }
5786
5787 return rc;
5788}
5789
5790/**
5791 * Sets the value of m->strLocationFull. The given location must be a fully
5792 * qualified path; relative paths are not supported here.
5793 *
5794 * As a special exception, if the specified location is a file path that ends with '/'
5795 * then the file name part will be generated by this method automatically in the format
5796 * '{<uuid>}.<ext>' where <uuid> is a fresh UUID that this method will generate
5797 * and assign to this medium, and <ext> is the default extension for this
5798 * medium's storage format. Note that this procedure requires the media state to
5799 * be NotCreated and will return a failure otherwise.
5800 *
5801 * @param aLocation Location of the storage unit. If the location is a FS-path,
5802 * then it can be relative to the VirtualBox home directory.
5803 * @param aFormat Optional fallback format if it is an import and the format
5804 * cannot be determined.
5805 *
5806 * @note Must be called from under this object's write lock.
5807 */
5808HRESULT Medium::setLocation(const Utf8Str &aLocation,
5809 const Utf8Str &aFormat /* = Utf8Str::Empty */)
5810{
5811 AssertReturn(!aLocation.isEmpty(), E_FAIL);
5812
5813 AutoCaller autoCaller(this);
5814 AssertComRCReturnRC(autoCaller.rc());
5815
5816 /* formatObj may be null only when initializing from an existing path and
5817 * no format is known yet */
5818 AssertReturn( (!m->strFormat.isEmpty() && !m->formatObj.isNull())
5819 || ( autoCaller.state() == InInit
5820 && m->state != MediumState_NotCreated
5821 && m->id.isEmpty()
5822 && m->strFormat.isEmpty()
5823 && m->formatObj.isNull()),
5824 E_FAIL);
5825
5826 /* are we dealing with a new medium constructed using the existing
5827 * location? */
5828 bool isImport = m->strFormat.isEmpty();
5829
5830 if ( isImport
5831 || ( (m->formatObj->getCapabilities() & MediumFormatCapabilities_File)
5832 && !m->hostDrive))
5833 {
5834 Guid id;
5835
5836 Utf8Str locationFull(aLocation);
5837
5838 if (m->state == MediumState_NotCreated)
5839 {
5840 /* must be a file (formatObj must be already known) */
5841 Assert(m->formatObj->getCapabilities() & MediumFormatCapabilities_File);
5842
5843 if (RTPathFilename(aLocation.c_str()) == NULL)
5844 {
5845 /* no file name is given (either an empty string or ends with a
5846 * slash), generate a new UUID + file name if the state allows
5847 * this */
5848
5849 ComAssertMsgRet(!m->formatObj->getFileExtensions().empty(),
5850 ("Must be at least one extension if it is MediumFormatCapabilities_File\n"),
5851 E_FAIL);
5852
5853 Utf8Str strExt = m->formatObj->getFileExtensions().front();
5854 ComAssertMsgRet(!strExt.isEmpty(),
5855 ("Default extension must not be empty\n"),
5856 E_FAIL);
5857
5858 id.create();
5859
5860 locationFull = Utf8StrFmt("%s{%RTuuid}.%s",
5861 aLocation.c_str(), id.raw(), strExt.c_str());
5862 }
5863 }
5864
5865 // we must always have full paths now (if it refers to a file)
5866 if ( ( m->formatObj.isNull()
5867 || m->formatObj->getCapabilities() & MediumFormatCapabilities_File)
5868 && !RTPathStartsWithRoot(locationFull.c_str()))
5869 return setError(VBOX_E_FILE_ERROR,
5870 tr("The given path '%s' is not fully qualified"),
5871 locationFull.c_str());
5872
5873 /* detect the backend from the storage unit if importing */
5874 if (isImport)
5875 {
5876 VDTYPE enmType = VDTYPE_INVALID;
5877 char *backendName = NULL;
5878
5879 int vrc = VINF_SUCCESS;
5880
5881 /* is it a file? */
5882 {
5883 RTFILE file;
5884 vrc = RTFileOpen(&file, locationFull.c_str(), RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
5885 if (RT_SUCCESS(vrc))
5886 RTFileClose(file);
5887 }
5888 if (RT_SUCCESS(vrc))
5889 {
5890 vrc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
5891 locationFull.c_str(), &backendName, &enmType);
5892 }
5893 else if (vrc != VERR_FILE_NOT_FOUND && vrc != VERR_PATH_NOT_FOUND)
5894 {
5895 /* assume it's not a file, restore the original location */
5896 locationFull = aLocation;
5897 vrc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
5898 locationFull.c_str(), &backendName, &enmType);
5899 }
5900
5901 if (RT_FAILURE(vrc))
5902 {
5903 if (vrc == VERR_FILE_NOT_FOUND || vrc == VERR_PATH_NOT_FOUND)
5904 return setError(VBOX_E_FILE_ERROR,
5905 tr("Could not find file for the medium '%s' (%Rrc)"),
5906 locationFull.c_str(), vrc);
5907 else if (aFormat.isEmpty())
5908 return setError(VBOX_E_IPRT_ERROR,
5909 tr("Could not get the storage format of the medium '%s' (%Rrc)"),
5910 locationFull.c_str(), vrc);
5911 else
5912 {
5913 HRESULT rc = setFormat(aFormat);
5914 /* setFormat() must not fail since we've just used the backend so
5915 * the format object must be there */
5916 AssertComRCReturnRC(rc);
5917 }
5918 }
5919 else if ( enmType == VDTYPE_INVALID
5920 || m->devType != convertToDeviceType(enmType))
5921 {
5922 /*
5923 * The user tried to use a image as a device which is not supported
5924 * by the backend.
5925 */
5926 return setError(E_FAIL,
5927 tr("The medium '%s' can't be used as the requested device type"),
5928 locationFull.c_str());
5929 }
5930 else
5931 {
5932 ComAssertRet(backendName != NULL && *backendName != '\0', E_FAIL);
5933
5934 HRESULT rc = setFormat(backendName);
5935 RTStrFree(backendName);
5936
5937 /* setFormat() must not fail since we've just used the backend so
5938 * the format object must be there */
5939 AssertComRCReturnRC(rc);
5940 }
5941 }
5942
5943 m->strLocationFull = locationFull;
5944
5945 /* is it still a file? */
5946 if ( (m->formatObj->getCapabilities() & MediumFormatCapabilities_File)
5947 && (m->state == MediumState_NotCreated)
5948 )
5949 /* assign a new UUID (this UUID will be used when calling
5950 * VDCreateBase/VDCreateDiff as a wanted UUID). Note that we
5951 * also do that if we didn't generate it to make sure it is
5952 * either generated by us or reset to null */
5953 unconst(m->id) = id;
5954 }
5955 else
5956 m->strLocationFull = aLocation;
5957
5958 return S_OK;
5959}
5960
5961/**
5962 * Checks that the format ID is valid and sets it on success.
5963 *
5964 * Note that this method will caller-reference the format object on success!
5965 * This reference must be released somewhere to let the MediumFormat object be
5966 * uninitialized.
5967 *
5968 * @note Must be called from under this object's write lock.
5969 */
5970HRESULT Medium::setFormat(const Utf8Str &aFormat)
5971{
5972 /* get the format object first */
5973 {
5974 SystemProperties *pSysProps = m->pVirtualBox->getSystemProperties();
5975 AutoReadLock propsLock(pSysProps COMMA_LOCKVAL_SRC_POS);
5976
5977 unconst(m->formatObj) = pSysProps->mediumFormat(aFormat);
5978 if (m->formatObj.isNull())
5979 return setError(E_INVALIDARG,
5980 tr("Invalid medium storage format '%s'"),
5981 aFormat.c_str());
5982
5983 /* reference the format permanently to prevent its unexpected
5984 * uninitialization */
5985 HRESULT rc = m->formatObj->addCaller();
5986 AssertComRCReturnRC(rc);
5987
5988 /* get properties (preinsert them as keys in the map). Note that the
5989 * map doesn't grow over the object life time since the set of
5990 * properties is meant to be constant. */
5991
5992 Assert(m->mapProperties.empty());
5993
5994 for (MediumFormat::PropertyList::const_iterator it = m->formatObj->getProperties().begin();
5995 it != m->formatObj->getProperties().end();
5996 ++it)
5997 {
5998 m->mapProperties.insert(std::make_pair(it->strName, Utf8Str::Empty));
5999 }
6000 }
6001
6002 unconst(m->strFormat) = aFormat;
6003
6004 return S_OK;
6005}
6006
6007/**
6008 * Converts the Medium device type to the VD type.
6009 */
6010VDTYPE Medium::convertDeviceType()
6011{
6012 VDTYPE enmType;
6013
6014 switch (m->devType)
6015 {
6016 case DeviceType_HardDisk:
6017 enmType = VDTYPE_HDD;
6018 break;
6019 case DeviceType_DVD:
6020 enmType = VDTYPE_DVD;
6021 break;
6022 case DeviceType_Floppy:
6023 enmType = VDTYPE_FLOPPY;
6024 break;
6025 default:
6026 ComAssertFailedRet(VDTYPE_INVALID);
6027 }
6028
6029 return enmType;
6030}
6031
6032/**
6033 * Converts from the VD type to the medium type.
6034 */
6035DeviceType_T Medium::convertToDeviceType(VDTYPE enmType)
6036{
6037 DeviceType_T devType;
6038
6039 switch (enmType)
6040 {
6041 case VDTYPE_HDD:
6042 devType = DeviceType_HardDisk;
6043 break;
6044 case VDTYPE_DVD:
6045 devType = DeviceType_DVD;
6046 break;
6047 case VDTYPE_FLOPPY:
6048 devType = DeviceType_Floppy;
6049 break;
6050 default:
6051 ComAssertFailedRet(DeviceType_Null);
6052 }
6053
6054 return devType;
6055}
6056
6057/**
6058 * Returns the last error message collected by the vdErrorCall callback and
6059 * resets it.
6060 *
6061 * The error message is returned prepended with a dot and a space, like this:
6062 * <code>
6063 * ". <error_text> (%Rrc)"
6064 * </code>
6065 * to make it easily appendable to a more general error message. The @c %Rrc
6066 * format string is given @a aVRC as an argument.
6067 *
6068 * If there is no last error message collected by vdErrorCall or if it is a
6069 * null or empty string, then this function returns the following text:
6070 * <code>
6071 * " (%Rrc)"
6072 * </code>
6073 *
6074 * @note Doesn't do any object locking; it is assumed that the caller makes sure
6075 * the callback isn't called by more than one thread at a time.
6076 *
6077 * @param aVRC VBox error code to use when no error message is provided.
6078 */
6079Utf8Str Medium::vdError(int aVRC)
6080{
6081 Utf8Str error;
6082
6083 if (m->vdError.isEmpty())
6084 error = Utf8StrFmt(" (%Rrc)", aVRC);
6085 else
6086 error = Utf8StrFmt(".\n%s", m->vdError.c_str());
6087
6088 m->vdError.setNull();
6089
6090 return error;
6091}
6092
6093/**
6094 * Error message callback.
6095 *
6096 * Puts the reported error message to the m->vdError field.
6097 *
6098 * @note Doesn't do any object locking; it is assumed that the caller makes sure
6099 * the callback isn't called by more than one thread at a time.
6100 *
6101 * @param pvUser The opaque data passed on container creation.
6102 * @param rc The VBox error code.
6103 * @param RT_SRC_POS_DECL Use RT_SRC_POS.
6104 * @param pszFormat Error message format string.
6105 * @param va Error message arguments.
6106 */
6107/*static*/
6108DECLCALLBACK(void) Medium::vdErrorCall(void *pvUser, int rc, RT_SRC_POS_DECL,
6109 const char *pszFormat, va_list va)
6110{
6111 NOREF(pszFile); NOREF(iLine); NOREF(pszFunction); /* RT_SRC_POS_DECL */
6112
6113 Medium *that = static_cast<Medium*>(pvUser);
6114 AssertReturnVoid(that != NULL);
6115
6116 if (that->m->vdError.isEmpty())
6117 that->m->vdError =
6118 Utf8StrFmt("%s (%Rrc)", Utf8Str(pszFormat, va).c_str(), rc);
6119 else
6120 that->m->vdError =
6121 Utf8StrFmt("%s.\n%s (%Rrc)", that->m->vdError.c_str(),
6122 Utf8Str(pszFormat, va).c_str(), rc);
6123}
6124
6125/* static */
6126DECLCALLBACK(bool) Medium::vdConfigAreKeysValid(void *pvUser,
6127 const char * /* pszzValid */)
6128{
6129 Medium *that = static_cast<Medium*>(pvUser);
6130 AssertReturn(that != NULL, false);
6131
6132 /* we always return true since the only keys we have are those found in
6133 * VDBACKENDINFO */
6134 return true;
6135}
6136
6137/* static */
6138DECLCALLBACK(int) Medium::vdConfigQuerySize(void *pvUser,
6139 const char *pszName,
6140 size_t *pcbValue)
6141{
6142 AssertReturn(VALID_PTR(pcbValue), VERR_INVALID_POINTER);
6143
6144 Medium *that = static_cast<Medium*>(pvUser);
6145 AssertReturn(that != NULL, VERR_GENERAL_FAILURE);
6146
6147 settings::StringsMap::const_iterator it = that->m->mapProperties.find(Utf8Str(pszName));
6148 if (it == that->m->mapProperties.end())
6149 return VERR_CFGM_VALUE_NOT_FOUND;
6150
6151 /* we interpret null values as "no value" in Medium */
6152 if (it->second.isEmpty())
6153 return VERR_CFGM_VALUE_NOT_FOUND;
6154
6155 *pcbValue = it->second.length() + 1 /* include terminator */;
6156
6157 return VINF_SUCCESS;
6158}
6159
6160/* static */
6161DECLCALLBACK(int) Medium::vdConfigQuery(void *pvUser,
6162 const char *pszName,
6163 char *pszValue,
6164 size_t cchValue)
6165{
6166 AssertReturn(VALID_PTR(pszValue), VERR_INVALID_POINTER);
6167
6168 Medium *that = static_cast<Medium*>(pvUser);
6169 AssertReturn(that != NULL, VERR_GENERAL_FAILURE);
6170
6171 settings::StringsMap::const_iterator it = that->m->mapProperties.find(Utf8Str(pszName));
6172 if (it == that->m->mapProperties.end())
6173 return VERR_CFGM_VALUE_NOT_FOUND;
6174
6175 /* we interpret null values as "no value" in Medium */
6176 if (it->second.isEmpty())
6177 return VERR_CFGM_VALUE_NOT_FOUND;
6178
6179 const Utf8Str &value = it->second;
6180 if (value.length() >= cchValue)
6181 return VERR_CFGM_NOT_ENOUGH_SPACE;
6182
6183 memcpy(pszValue, value.c_str(), value.length() + 1);
6184
6185 return VINF_SUCCESS;
6186}
6187
6188DECLCALLBACK(int) Medium::vdTcpSocketCreate(uint32_t fFlags, PVDSOCKET pSock)
6189{
6190 PVDSOCKETINT pSocketInt = NULL;
6191
6192 if ((fFlags & VD_INTERFACETCPNET_CONNECT_EXTENDED_SELECT) != 0)
6193 return VERR_NOT_SUPPORTED;
6194
6195 pSocketInt = (PVDSOCKETINT)RTMemAllocZ(sizeof(VDSOCKETINT));
6196 if (!pSocketInt)
6197 return VERR_NO_MEMORY;
6198
6199 pSocketInt->hSocket = NIL_RTSOCKET;
6200 *pSock = pSocketInt;
6201 return VINF_SUCCESS;
6202}
6203
6204DECLCALLBACK(int) Medium::vdTcpSocketDestroy(VDSOCKET Sock)
6205{
6206 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6207
6208 if (pSocketInt->hSocket != NIL_RTSOCKET)
6209 RTTcpClientCloseEx(pSocketInt->hSocket, false /*fGracefulShutdown*/);
6210
6211 RTMemFree(pSocketInt);
6212
6213 return VINF_SUCCESS;
6214}
6215
6216DECLCALLBACK(int) Medium::vdTcpClientConnect(VDSOCKET Sock, const char *pszAddress, uint32_t uPort)
6217{
6218 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6219
6220 return RTTcpClientConnect(pszAddress, uPort, &pSocketInt->hSocket);
6221}
6222
6223DECLCALLBACK(int) Medium::vdTcpClientClose(VDSOCKET Sock)
6224{
6225 int rc = VINF_SUCCESS;
6226 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6227
6228 rc = RTTcpClientCloseEx(pSocketInt->hSocket, false /*fGracefulShutdown*/);
6229 pSocketInt->hSocket = NIL_RTSOCKET;
6230 return rc;
6231}
6232
6233DECLCALLBACK(bool) Medium::vdTcpIsClientConnected(VDSOCKET Sock)
6234{
6235 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6236 return pSocketInt->hSocket != NIL_RTSOCKET;
6237}
6238
6239DECLCALLBACK(int) Medium::vdTcpSelectOne(VDSOCKET Sock, RTMSINTERVAL cMillies)
6240{
6241 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6242 return RTTcpSelectOne(pSocketInt->hSocket, cMillies);
6243}
6244
6245DECLCALLBACK(int) Medium::vdTcpRead(VDSOCKET Sock, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
6246{
6247 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6248 return RTTcpRead(pSocketInt->hSocket, pvBuffer, cbBuffer, pcbRead);
6249}
6250
6251DECLCALLBACK(int) Medium::vdTcpWrite(VDSOCKET Sock, const void *pvBuffer, size_t cbBuffer)
6252{
6253 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6254 return RTTcpWrite(pSocketInt->hSocket, pvBuffer, cbBuffer);
6255}
6256
6257DECLCALLBACK(int) Medium::vdTcpSgWrite(VDSOCKET Sock, PCRTSGBUF pSgBuf)
6258{
6259 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6260 return RTTcpSgWrite(pSocketInt->hSocket, pSgBuf);
6261}
6262
6263DECLCALLBACK(int) Medium::vdTcpFlush(VDSOCKET Sock)
6264{
6265 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6266 return RTTcpFlush(pSocketInt->hSocket);
6267}
6268
6269DECLCALLBACK(int) Medium::vdTcpSetSendCoalescing(VDSOCKET Sock, bool fEnable)
6270{
6271 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6272 return RTTcpSetSendCoalescing(pSocketInt->hSocket, fEnable);
6273}
6274
6275DECLCALLBACK(int) Medium::vdTcpGetLocalAddress(VDSOCKET Sock, PRTNETADDR pAddr)
6276{
6277 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6278 return RTTcpGetLocalAddress(pSocketInt->hSocket, pAddr);
6279}
6280
6281DECLCALLBACK(int) Medium::vdTcpGetPeerAddress(VDSOCKET Sock, PRTNETADDR pAddr)
6282{
6283 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6284 return RTTcpGetPeerAddress(pSocketInt->hSocket, pAddr);
6285}
6286
6287/**
6288 * Starts a new thread driven by the appropriate Medium::Task::handler() method.
6289 *
6290 * @note When the task is executed by this method, IProgress::notifyComplete()
6291 * is automatically called for the progress object associated with this
6292 * task when the task is finished to signal the operation completion for
6293 * other threads asynchronously waiting for it.
6294 */
6295HRESULT Medium::startThread(Medium::Task *pTask)
6296{
6297#ifdef VBOX_WITH_MAIN_LOCK_VALIDATION
6298 /* Extreme paranoia: The calling thread should not hold the medium
6299 * tree lock or any medium lock. Since there is no separate lock class
6300 * for medium objects be even more strict: no other object locks. */
6301 Assert(!AutoLockHoldsLocksInClass(LOCKCLASS_LISTOFMEDIA));
6302 Assert(!AutoLockHoldsLocksInClass(getLockingClass()));
6303#endif
6304
6305 /// @todo use a more descriptive task name
6306 int vrc = RTThreadCreate(NULL, Medium::Task::fntMediumTask, pTask,
6307 0, RTTHREADTYPE_MAIN_HEAVY_WORKER, 0,
6308 "Medium::Task");
6309 if (RT_FAILURE(vrc))
6310 {
6311 delete pTask;
6312 return setError(E_FAIL, "Could not create Medium::Task thread (%Rrc)\n", vrc);
6313 }
6314
6315 return S_OK;
6316}
6317
6318/**
6319 * Runs Medium::Task::handler() on the current thread instead of creating
6320 * a new one.
6321 *
6322 * This call implies that it is made on another temporary thread created for
6323 * some asynchronous task. Avoid calling it from a normal thread since the task
6324 * operations are potentially lengthy and will block the calling thread in this
6325 * case.
6326 *
6327 * @note When the task is executed by this method, IProgress::notifyComplete()
6328 * is not called for the progress object associated with this task when
6329 * the task is finished. Instead, the result of the operation is returned
6330 * by this method directly and it's the caller's responsibility to
6331 * complete the progress object in this case.
6332 */
6333HRESULT Medium::runNow(Medium::Task *pTask,
6334 GuidList *pllRegistriesThatNeedSaving)
6335{
6336#ifdef VBOX_WITH_MAIN_LOCK_VALIDATION
6337 /* Extreme paranoia: The calling thread should not hold the medium
6338 * tree lock or any medium lock. Since there is no separate lock class
6339 * for medium objects be even more strict: no other object locks. */
6340 Assert(!AutoLockHoldsLocksInClass(LOCKCLASS_LISTOFMEDIA));
6341 Assert(!AutoLockHoldsLocksInClass(getLockingClass()));
6342#endif
6343
6344 pTask->m_pllRegistriesThatNeedSaving = pllRegistriesThatNeedSaving;
6345
6346 /* NIL_RTTHREAD indicates synchronous call. */
6347 return (HRESULT)Medium::Task::fntMediumTask(NIL_RTTHREAD, pTask);
6348}
6349
6350/**
6351 * Implementation code for the "create base" task.
6352 *
6353 * This only gets started from Medium::CreateBaseStorage() and always runs
6354 * asynchronously. As a result, we always save the VirtualBox.xml file when
6355 * we're done here.
6356 *
6357 * @param task
6358 * @return
6359 */
6360HRESULT Medium::taskCreateBaseHandler(Medium::CreateBaseTask &task)
6361{
6362 HRESULT rc = S_OK;
6363
6364 /* these parameters we need after creation */
6365 uint64_t size = 0, logicalSize = 0;
6366 MediumVariant_T variant = MediumVariant_Standard;
6367 bool fGenerateUuid = false;
6368
6369 try
6370 {
6371 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6372
6373 /* The object may request a specific UUID (through a special form of
6374 * the setLocation() argument). Otherwise we have to generate it */
6375 Guid id = m->id;
6376 fGenerateUuid = id.isEmpty();
6377 if (fGenerateUuid)
6378 {
6379 id.create();
6380 /* VirtualBox::registerHardDisk() will need UUID */
6381 unconst(m->id) = id;
6382 }
6383
6384 Utf8Str format(m->strFormat);
6385 Utf8Str location(m->strLocationFull);
6386 uint64_t capabilities = m->formatObj->getCapabilities();
6387 ComAssertThrow(capabilities & ( MediumFormatCapabilities_CreateFixed
6388 | MediumFormatCapabilities_CreateDynamic), E_FAIL);
6389 Assert(m->state == MediumState_Creating);
6390
6391 PVBOXHDD hdd;
6392 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
6393 ComAssertRCThrow(vrc, E_FAIL);
6394
6395 /* unlock before the potentially lengthy operation */
6396 thisLock.release();
6397
6398 try
6399 {
6400 /* ensure the directory exists */
6401 if (capabilities & MediumFormatCapabilities_File)
6402 {
6403 rc = VirtualBox::ensureFilePathExists(location);
6404 if (FAILED(rc))
6405 throw rc;
6406 }
6407
6408 VDGEOMETRY geo = { 0, 0, 0 }; /* auto-detect */
6409
6410 vrc = VDCreateBase(hdd,
6411 format.c_str(),
6412 location.c_str(),
6413 task.mSize,
6414 task.mVariant,
6415 NULL,
6416 &geo,
6417 &geo,
6418 id.raw(),
6419 VD_OPEN_FLAGS_NORMAL,
6420 m->vdImageIfaces,
6421 task.mVDOperationIfaces);
6422 if (RT_FAILURE(vrc))
6423 throw setError(VBOX_E_FILE_ERROR,
6424 tr("Could not create the medium storage unit '%s'%s"),
6425 location.c_str(), vdError(vrc).c_str());
6426
6427 size = VDGetFileSize(hdd, 0);
6428 logicalSize = VDGetSize(hdd, 0);
6429 unsigned uImageFlags;
6430 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
6431 if (RT_SUCCESS(vrc))
6432 variant = (MediumVariant_T)uImageFlags;
6433 }
6434 catch (HRESULT aRC) { rc = aRC; }
6435
6436 VDDestroy(hdd);
6437 }
6438 catch (HRESULT aRC) { rc = aRC; }
6439
6440 if (SUCCEEDED(rc))
6441 {
6442 /* register with mVirtualBox as the last step and move to
6443 * Created state only on success (leaving an orphan file is
6444 * better than breaking media registry consistency) */
6445 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
6446 rc = m->pVirtualBox->registerHardDisk(this, NULL /* pllRegistriesThatNeedSaving */);
6447 }
6448
6449 // reenter the lock before changing state
6450 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6451
6452 if (SUCCEEDED(rc))
6453 {
6454 m->state = MediumState_Created;
6455
6456 m->size = size;
6457 m->logicalSize = logicalSize;
6458 m->variant = variant;
6459 }
6460 else
6461 {
6462 /* back to NotCreated on failure */
6463 m->state = MediumState_NotCreated;
6464
6465 /* reset UUID to prevent it from being reused next time */
6466 if (fGenerateUuid)
6467 unconst(m->id).clear();
6468 }
6469
6470 return rc;
6471}
6472
6473/**
6474 * Implementation code for the "create diff" task.
6475 *
6476 * This task always gets started from Medium::createDiffStorage() and can run
6477 * synchronously or asynchronously depending on the "wait" parameter passed to
6478 * that function. If we run synchronously, the caller expects the bool
6479 * *pfNeedsGlobalSaveSettings to be set before returning; otherwise (in asynchronous
6480 * mode), we save the settings ourselves.
6481 *
6482 * @param task
6483 * @return
6484 */
6485HRESULT Medium::taskCreateDiffHandler(Medium::CreateDiffTask &task)
6486{
6487 HRESULT rcTmp = S_OK;
6488
6489 const ComObjPtr<Medium> &pTarget = task.mTarget;
6490
6491 uint64_t size = 0, logicalSize = 0;
6492 MediumVariant_T variant = MediumVariant_Standard;
6493 bool fGenerateUuid = false;
6494
6495 GuidList llRegistriesThatNeedSaving; // gets copied to task pointer later in synchronous mode
6496
6497 try
6498 {
6499 /* Lock both in {parent,child} order. */
6500 AutoMultiWriteLock2 mediaLock(this, pTarget COMMA_LOCKVAL_SRC_POS);
6501
6502 /* The object may request a specific UUID (through a special form of
6503 * the setLocation() argument). Otherwise we have to generate it */
6504 Guid targetId = pTarget->m->id;
6505 fGenerateUuid = targetId.isEmpty();
6506 if (fGenerateUuid)
6507 {
6508 targetId.create();
6509 /* VirtualBox::registerHardDisk() will need UUID */
6510 unconst(pTarget->m->id) = targetId;
6511 }
6512
6513 Guid id = m->id;
6514
6515 Utf8Str targetFormat(pTarget->m->strFormat);
6516 Utf8Str targetLocation(pTarget->m->strLocationFull);
6517 uint64_t capabilities = pTarget->m->formatObj->getCapabilities();
6518 ComAssertThrow(capabilities & MediumFormatCapabilities_CreateDynamic, E_FAIL);
6519
6520 Assert(pTarget->m->state == MediumState_Creating);
6521 Assert(m->state == MediumState_LockedRead);
6522
6523 PVBOXHDD hdd;
6524 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
6525 ComAssertRCThrow(vrc, E_FAIL);
6526
6527 /* the two media are now protected by their non-default states;
6528 * unlock the media before the potentially lengthy operation */
6529 mediaLock.release();
6530
6531 try
6532 {
6533 /* Open all media in the target chain but the last. */
6534 MediumLockList::Base::const_iterator targetListBegin =
6535 task.mpMediumLockList->GetBegin();
6536 MediumLockList::Base::const_iterator targetListEnd =
6537 task.mpMediumLockList->GetEnd();
6538 for (MediumLockList::Base::const_iterator it = targetListBegin;
6539 it != targetListEnd;
6540 ++it)
6541 {
6542 const MediumLock &mediumLock = *it;
6543 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
6544
6545 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
6546
6547 /* Skip over the target diff medium */
6548 if (pMedium->m->state == MediumState_Creating)
6549 continue;
6550
6551 /* sanity check */
6552 Assert(pMedium->m->state == MediumState_LockedRead);
6553
6554 /* Open all media in appropriate mode. */
6555 vrc = VDOpen(hdd,
6556 pMedium->m->strFormat.c_str(),
6557 pMedium->m->strLocationFull.c_str(),
6558 VD_OPEN_FLAGS_READONLY,
6559 pMedium->m->vdImageIfaces);
6560 if (RT_FAILURE(vrc))
6561 throw setError(VBOX_E_FILE_ERROR,
6562 tr("Could not open the medium storage unit '%s'%s"),
6563 pMedium->m->strLocationFull.c_str(),
6564 vdError(vrc).c_str());
6565 }
6566
6567 /* ensure the target directory exists */
6568 if (capabilities & MediumFormatCapabilities_File)
6569 {
6570 HRESULT rc = VirtualBox::ensureFilePathExists(targetLocation);
6571 if (FAILED(rc))
6572 throw rc;
6573 }
6574
6575 vrc = VDCreateDiff(hdd,
6576 targetFormat.c_str(),
6577 targetLocation.c_str(),
6578 task.mVariant | VD_IMAGE_FLAGS_DIFF,
6579 NULL,
6580 targetId.raw(),
6581 id.raw(),
6582 VD_OPEN_FLAGS_NORMAL,
6583 pTarget->m->vdImageIfaces,
6584 task.mVDOperationIfaces);
6585 if (RT_FAILURE(vrc))
6586 throw setError(VBOX_E_FILE_ERROR,
6587 tr("Could not create the differencing medium storage unit '%s'%s"),
6588 targetLocation.c_str(), vdError(vrc).c_str());
6589
6590 size = VDGetFileSize(hdd, VD_LAST_IMAGE);
6591 logicalSize = VDGetSize(hdd, VD_LAST_IMAGE);
6592 unsigned uImageFlags;
6593 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
6594 if (RT_SUCCESS(vrc))
6595 variant = (MediumVariant_T)uImageFlags;
6596 }
6597 catch (HRESULT aRC) { rcTmp = aRC; }
6598
6599 VDDestroy(hdd);
6600 }
6601 catch (HRESULT aRC) { rcTmp = aRC; }
6602
6603 MultiResult mrc(rcTmp);
6604
6605 if (SUCCEEDED(mrc))
6606 {
6607 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
6608
6609 Assert(pTarget->m->pParent.isNull());
6610
6611 /* associate the child with the parent */
6612 pTarget->m->pParent = this;
6613 m->llChildren.push_back(pTarget);
6614
6615 /** @todo r=klaus neither target nor base() are locked,
6616 * potential race! */
6617 /* diffs for immutable media are auto-reset by default */
6618 pTarget->m->autoReset = (getBase()->m->type == MediumType_Immutable);
6619
6620 /* register with mVirtualBox as the last step and move to
6621 * Created state only on success (leaving an orphan file is
6622 * better than breaking media registry consistency) */
6623 mrc = m->pVirtualBox->registerHardDisk(pTarget, &llRegistriesThatNeedSaving);
6624
6625 if (FAILED(mrc))
6626 /* break the parent association on failure to register */
6627 deparent();
6628 }
6629
6630 AutoMultiWriteLock2 mediaLock(this, pTarget COMMA_LOCKVAL_SRC_POS);
6631
6632 if (SUCCEEDED(mrc))
6633 {
6634 pTarget->m->state = MediumState_Created;
6635
6636 pTarget->m->size = size;
6637 pTarget->m->logicalSize = logicalSize;
6638 pTarget->m->variant = variant;
6639 }
6640 else
6641 {
6642 /* back to NotCreated on failure */
6643 pTarget->m->state = MediumState_NotCreated;
6644
6645 pTarget->m->autoReset = false;
6646
6647 /* reset UUID to prevent it from being reused next time */
6648 if (fGenerateUuid)
6649 unconst(pTarget->m->id).clear();
6650 }
6651
6652 // deregister the task registered in createDiffStorage()
6653 Assert(m->numCreateDiffTasks != 0);
6654 --m->numCreateDiffTasks;
6655
6656 if (task.isAsync())
6657 {
6658 mediaLock.release();
6659 mrc = m->pVirtualBox->saveRegistries(llRegistriesThatNeedSaving);
6660 }
6661 else
6662 // synchronous mode: report save settings result to caller
6663 if (task.m_pllRegistriesThatNeedSaving)
6664 *task.m_pllRegistriesThatNeedSaving = llRegistriesThatNeedSaving;
6665
6666 /* Note that in sync mode, it's the caller's responsibility to
6667 * unlock the medium. */
6668
6669 return mrc;
6670}
6671
6672/**
6673 * Implementation code for the "merge" task.
6674 *
6675 * This task always gets started from Medium::mergeTo() and can run
6676 * synchronously or asynchronously depending on the "wait" parameter passed to
6677 * that function. If we run synchronously, the caller expects the bool
6678 * *pfNeedsGlobalSaveSettings to be set before returning; otherwise (in asynchronous
6679 * mode), we save the settings ourselves.
6680 *
6681 * @param task
6682 * @return
6683 */
6684HRESULT Medium::taskMergeHandler(Medium::MergeTask &task)
6685{
6686 HRESULT rcTmp = S_OK;
6687
6688 const ComObjPtr<Medium> &pTarget = task.mTarget;
6689
6690 try
6691 {
6692 PVBOXHDD hdd;
6693 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
6694 ComAssertRCThrow(vrc, E_FAIL);
6695
6696 try
6697 {
6698 // Similar code appears in SessionMachine::onlineMergeMedium, so
6699 // if you make any changes below check whether they are applicable
6700 // in that context as well.
6701
6702 unsigned uTargetIdx = VD_LAST_IMAGE;
6703 unsigned uSourceIdx = VD_LAST_IMAGE;
6704 /* Open all media in the chain. */
6705 MediumLockList::Base::iterator lockListBegin =
6706 task.mpMediumLockList->GetBegin();
6707 MediumLockList::Base::iterator lockListEnd =
6708 task.mpMediumLockList->GetEnd();
6709 unsigned i = 0;
6710 for (MediumLockList::Base::iterator it = lockListBegin;
6711 it != lockListEnd;
6712 ++it)
6713 {
6714 MediumLock &mediumLock = *it;
6715 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
6716
6717 if (pMedium == this)
6718 uSourceIdx = i;
6719 else if (pMedium == pTarget)
6720 uTargetIdx = i;
6721
6722 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
6723
6724 /*
6725 * complex sanity (sane complexity)
6726 *
6727 * The current medium must be in the Deleting (medium is merged)
6728 * or LockedRead (parent medium) state if it is not the target.
6729 * If it is the target it must be in the LockedWrite state.
6730 */
6731 Assert( ( pMedium != pTarget
6732 && ( pMedium->m->state == MediumState_Deleting
6733 || pMedium->m->state == MediumState_LockedRead))
6734 || ( pMedium == pTarget
6735 && pMedium->m->state == MediumState_LockedWrite));
6736
6737 /*
6738 * Medium must be the target, in the LockedRead state
6739 * or Deleting state where it is not allowed to be attached
6740 * to a virtual machine.
6741 */
6742 Assert( pMedium == pTarget
6743 || pMedium->m->state == MediumState_LockedRead
6744 || ( pMedium->m->backRefs.size() == 0
6745 && pMedium->m->state == MediumState_Deleting));
6746 /* The source medium must be in Deleting state. */
6747 Assert( pMedium != this
6748 || pMedium->m->state == MediumState_Deleting);
6749
6750 unsigned uOpenFlags = VD_OPEN_FLAGS_NORMAL;
6751
6752 if ( pMedium->m->state == MediumState_LockedRead
6753 || pMedium->m->state == MediumState_Deleting)
6754 uOpenFlags = VD_OPEN_FLAGS_READONLY;
6755 if (pMedium->m->type == MediumType_Shareable)
6756 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
6757
6758 /* Open the medium */
6759 vrc = VDOpen(hdd,
6760 pMedium->m->strFormat.c_str(),
6761 pMedium->m->strLocationFull.c_str(),
6762 uOpenFlags,
6763 pMedium->m->vdImageIfaces);
6764 if (RT_FAILURE(vrc))
6765 throw vrc;
6766
6767 i++;
6768 }
6769
6770 ComAssertThrow( uSourceIdx != VD_LAST_IMAGE
6771 && uTargetIdx != VD_LAST_IMAGE, E_FAIL);
6772
6773 vrc = VDMerge(hdd, uSourceIdx, uTargetIdx,
6774 task.mVDOperationIfaces);
6775 if (RT_FAILURE(vrc))
6776 throw vrc;
6777
6778 /* update parent UUIDs */
6779 if (!task.mfMergeForward)
6780 {
6781 /* we need to update UUIDs of all source's children
6782 * which cannot be part of the container at once so
6783 * add each one in there individually */
6784 if (task.mChildrenToReparent.size() > 0)
6785 {
6786 for (MediaList::const_iterator it = task.mChildrenToReparent.begin();
6787 it != task.mChildrenToReparent.end();
6788 ++it)
6789 {
6790 /* VD_OPEN_FLAGS_INFO since UUID is wrong yet */
6791 vrc = VDOpen(hdd,
6792 (*it)->m->strFormat.c_str(),
6793 (*it)->m->strLocationFull.c_str(),
6794 VD_OPEN_FLAGS_INFO,
6795 (*it)->m->vdImageIfaces);
6796 if (RT_FAILURE(vrc))
6797 throw vrc;
6798
6799 vrc = VDSetParentUuid(hdd, VD_LAST_IMAGE,
6800 pTarget->m->id.raw());
6801 if (RT_FAILURE(vrc))
6802 throw vrc;
6803
6804 vrc = VDClose(hdd, false /* fDelete */);
6805 if (RT_FAILURE(vrc))
6806 throw vrc;
6807
6808 (*it)->UnlockWrite(NULL);
6809 }
6810 }
6811 }
6812 }
6813 catch (HRESULT aRC) { rcTmp = aRC; }
6814 catch (int aVRC)
6815 {
6816 rcTmp = setError(VBOX_E_FILE_ERROR,
6817 tr("Could not merge the medium '%s' to '%s'%s"),
6818 m->strLocationFull.c_str(),
6819 pTarget->m->strLocationFull.c_str(),
6820 vdError(aVRC).c_str());
6821 }
6822
6823 VDDestroy(hdd);
6824 }
6825 catch (HRESULT aRC) { rcTmp = aRC; }
6826
6827 ErrorInfoKeeper eik;
6828 MultiResult mrc(rcTmp);
6829 HRESULT rc2;
6830
6831 if (SUCCEEDED(mrc))
6832 {
6833 /* all media but the target were successfully deleted by
6834 * VDMerge; reparent the last one and uninitialize deleted media. */
6835
6836 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
6837
6838 if (task.mfMergeForward)
6839 {
6840 /* first, unregister the target since it may become a base
6841 * medium which needs re-registration */
6842 rc2 = m->pVirtualBox->unregisterHardDisk(pTarget, NULL /*&fNeedsGlobalSaveSettings*/);
6843 AssertComRC(rc2);
6844
6845 /* then, reparent it and disconnect the deleted branch at
6846 * both ends (chain->parent() is source's parent) */
6847 pTarget->deparent();
6848 pTarget->m->pParent = task.mParentForTarget;
6849 if (pTarget->m->pParent)
6850 {
6851 pTarget->m->pParent->m->llChildren.push_back(pTarget);
6852 deparent();
6853 }
6854
6855 /* then, register again */
6856 rc2 = m->pVirtualBox->registerHardDisk(pTarget, NULL /* pllRegistriesThatNeedSaving */ );
6857 AssertComRC(rc2);
6858 }
6859 else
6860 {
6861 Assert(pTarget->getChildren().size() == 1);
6862 Medium *targetChild = pTarget->getChildren().front();
6863
6864 /* disconnect the deleted branch at the elder end */
6865 targetChild->deparent();
6866
6867 /* reparent source's children and disconnect the deleted
6868 * branch at the younger end */
6869 if (task.mChildrenToReparent.size() > 0)
6870 {
6871 /* obey {parent,child} lock order */
6872 AutoWriteLock sourceLock(this COMMA_LOCKVAL_SRC_POS);
6873
6874 for (MediaList::const_iterator it = task.mChildrenToReparent.begin();
6875 it != task.mChildrenToReparent.end();
6876 it++)
6877 {
6878 Medium *pMedium = *it;
6879 AutoWriteLock childLock(pMedium COMMA_LOCKVAL_SRC_POS);
6880
6881 pMedium->deparent(); // removes pMedium from source
6882 pMedium->setParent(pTarget);
6883 }
6884 }
6885 }
6886
6887 /* unregister and uninitialize all media removed by the merge */
6888 MediumLockList::Base::iterator lockListBegin =
6889 task.mpMediumLockList->GetBegin();
6890 MediumLockList::Base::iterator lockListEnd =
6891 task.mpMediumLockList->GetEnd();
6892 for (MediumLockList::Base::iterator it = lockListBegin;
6893 it != lockListEnd;
6894 )
6895 {
6896 MediumLock &mediumLock = *it;
6897 /* Create a real copy of the medium pointer, as the medium
6898 * lock deletion below would invalidate the referenced object. */
6899 const ComObjPtr<Medium> pMedium = mediumLock.GetMedium();
6900
6901 /* The target and all media not merged (readonly) are skipped */
6902 if ( pMedium == pTarget
6903 || pMedium->m->state == MediumState_LockedRead)
6904 {
6905 ++it;
6906 continue;
6907 }
6908
6909 rc2 = pMedium->m->pVirtualBox->unregisterHardDisk(pMedium,
6910 NULL /*pfNeedsGlobalSaveSettings*/);
6911 AssertComRC(rc2);
6912
6913 /* now, uninitialize the deleted medium (note that
6914 * due to the Deleting state, uninit() will not touch
6915 * the parent-child relationship so we need to
6916 * uninitialize each disk individually) */
6917
6918 /* note that the operation initiator medium (which is
6919 * normally also the source medium) is a special case
6920 * -- there is one more caller added by Task to it which
6921 * we must release. Also, if we are in sync mode, the
6922 * caller may still hold an AutoCaller instance for it
6923 * and therefore we cannot uninit() it (it's therefore
6924 * the caller's responsibility) */
6925 if (pMedium == this)
6926 {
6927 Assert(getChildren().size() == 0);
6928 Assert(m->backRefs.size() == 0);
6929 task.mMediumCaller.release();
6930 }
6931
6932 /* Delete the medium lock list entry, which also releases the
6933 * caller added by MergeChain before uninit() and updates the
6934 * iterator to point to the right place. */
6935 rc2 = task.mpMediumLockList->RemoveByIterator(it);
6936 AssertComRC(rc2);
6937
6938 if (task.isAsync() || pMedium != this)
6939 pMedium->uninit();
6940 }
6941 }
6942
6943 if (task.isAsync())
6944 {
6945 // in asynchronous mode, save settings now
6946 GuidList llRegistriesThatNeedSaving;
6947 addToRegistryIDList(llRegistriesThatNeedSaving);
6948 /* collect multiple errors */
6949 eik.restore();
6950 mrc = m->pVirtualBox->saveRegistries(llRegistriesThatNeedSaving);
6951 eik.fetch();
6952 }
6953 else
6954 // synchronous mode: report save settings result to caller
6955 if (task.m_pllRegistriesThatNeedSaving)
6956 pTarget->addToRegistryIDList(*task.m_pllRegistriesThatNeedSaving);
6957
6958 if (FAILED(mrc))
6959 {
6960 /* Here we come if either VDMerge() failed (in which case we
6961 * assume that it tried to do everything to make a further
6962 * retry possible -- e.g. not deleted intermediate media
6963 * and so on) or VirtualBox::saveRegistries() failed (where we
6964 * should have the original tree but with intermediate storage
6965 * units deleted by VDMerge()). We have to only restore states
6966 * (through the MergeChain dtor) unless we are run synchronously
6967 * in which case it's the responsibility of the caller as stated
6968 * in the mergeTo() docs. The latter also implies that we
6969 * don't own the merge chain, so release it in this case. */
6970 if (task.isAsync())
6971 {
6972 Assert(task.mChildrenToReparent.size() == 0);
6973 cancelMergeTo(task.mChildrenToReparent, task.mpMediumLockList);
6974 }
6975 }
6976
6977 return mrc;
6978}
6979
6980/**
6981 * Implementation code for the "clone" task.
6982 *
6983 * This only gets started from Medium::CloneTo() and always runs asynchronously.
6984 * As a result, we always save the VirtualBox.xml file when we're done here.
6985 *
6986 * @param task
6987 * @return
6988 */
6989HRESULT Medium::taskCloneHandler(Medium::CloneTask &task)
6990{
6991 HRESULT rcTmp = S_OK;
6992
6993 const ComObjPtr<Medium> &pTarget = task.mTarget;
6994 const ComObjPtr<Medium> &pParent = task.mParent;
6995
6996 bool fCreatingTarget = false;
6997
6998 uint64_t size = 0, logicalSize = 0;
6999 MediumVariant_T variant = MediumVariant_Standard;
7000 bool fGenerateUuid = false;
7001
7002 try
7003 {
7004 /* Lock all in {parent,child} order. The lock is also used as a
7005 * signal from the task initiator (which releases it only after
7006 * RTThreadCreate()) that we can start the job. */
7007 AutoMultiWriteLock3 thisLock(this, pTarget, pParent COMMA_LOCKVAL_SRC_POS);
7008
7009 fCreatingTarget = pTarget->m->state == MediumState_Creating;
7010
7011 /* The object may request a specific UUID (through a special form of
7012 * the setLocation() argument). Otherwise we have to generate it */
7013 Guid targetId = pTarget->m->id;
7014 fGenerateUuid = targetId.isEmpty();
7015 if (fGenerateUuid)
7016 {
7017 targetId.create();
7018 /* VirtualBox::registerHardDisk() will need UUID */
7019 unconst(pTarget->m->id) = targetId;
7020 }
7021
7022 PVBOXHDD hdd;
7023 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
7024 ComAssertRCThrow(vrc, E_FAIL);
7025
7026 try
7027 {
7028 /* Open all media in the source chain. */
7029 MediumLockList::Base::const_iterator sourceListBegin =
7030 task.mpSourceMediumLockList->GetBegin();
7031 MediumLockList::Base::const_iterator sourceListEnd =
7032 task.mpSourceMediumLockList->GetEnd();
7033 for (MediumLockList::Base::const_iterator it = sourceListBegin;
7034 it != sourceListEnd;
7035 ++it)
7036 {
7037 const MediumLock &mediumLock = *it;
7038 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
7039 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
7040
7041 /* sanity check */
7042 Assert(pMedium->m->state == MediumState_LockedRead);
7043
7044 /** Open all media in read-only mode. */
7045 vrc = VDOpen(hdd,
7046 pMedium->m->strFormat.c_str(),
7047 pMedium->m->strLocationFull.c_str(),
7048 VD_OPEN_FLAGS_READONLY,
7049 pMedium->m->vdImageIfaces);
7050 if (RT_FAILURE(vrc))
7051 throw setError(VBOX_E_FILE_ERROR,
7052 tr("Could not open the medium storage unit '%s'%s"),
7053 pMedium->m->strLocationFull.c_str(),
7054 vdError(vrc).c_str());
7055 }
7056
7057 Utf8Str targetFormat(pTarget->m->strFormat);
7058 Utf8Str targetLocation(pTarget->m->strLocationFull);
7059 uint64_t capabilities = pTarget->m->formatObj->getCapabilities();
7060
7061 Assert( pTarget->m->state == MediumState_Creating
7062 || pTarget->m->state == MediumState_LockedWrite);
7063 Assert(m->state == MediumState_LockedRead);
7064 Assert( pParent.isNull()
7065 || pParent->m->state == MediumState_LockedRead);
7066
7067 /* unlock before the potentially lengthy operation */
7068 thisLock.release();
7069
7070 /* ensure the target directory exists */
7071 if (capabilities & MediumFormatCapabilities_File)
7072 {
7073 HRESULT rc = VirtualBox::ensureFilePathExists(targetLocation);
7074 if (FAILED(rc))
7075 throw rc;
7076 }
7077
7078 PVBOXHDD targetHdd;
7079 vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &targetHdd);
7080 ComAssertRCThrow(vrc, E_FAIL);
7081
7082 try
7083 {
7084 /* Open all media in the target chain. */
7085 MediumLockList::Base::const_iterator targetListBegin =
7086 task.mpTargetMediumLockList->GetBegin();
7087 MediumLockList::Base::const_iterator targetListEnd =
7088 task.mpTargetMediumLockList->GetEnd();
7089 for (MediumLockList::Base::const_iterator it = targetListBegin;
7090 it != targetListEnd;
7091 ++it)
7092 {
7093 const MediumLock &mediumLock = *it;
7094 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
7095
7096 /* If the target medium is not created yet there's no
7097 * reason to open it. */
7098 if (pMedium == pTarget && fCreatingTarget)
7099 continue;
7100
7101 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
7102
7103 /* sanity check */
7104 Assert( pMedium->m->state == MediumState_LockedRead
7105 || pMedium->m->state == MediumState_LockedWrite);
7106
7107 unsigned uOpenFlags = VD_OPEN_FLAGS_NORMAL;
7108 if (pMedium->m->state != MediumState_LockedWrite)
7109 uOpenFlags = VD_OPEN_FLAGS_READONLY;
7110 if (pMedium->m->type == MediumType_Shareable)
7111 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
7112
7113 /* Open all media in appropriate mode. */
7114 vrc = VDOpen(targetHdd,
7115 pMedium->m->strFormat.c_str(),
7116 pMedium->m->strLocationFull.c_str(),
7117 uOpenFlags,
7118 pMedium->m->vdImageIfaces);
7119 if (RT_FAILURE(vrc))
7120 throw setError(VBOX_E_FILE_ERROR,
7121 tr("Could not open the medium storage unit '%s'%s"),
7122 pMedium->m->strLocationFull.c_str(),
7123 vdError(vrc).c_str());
7124 }
7125
7126 /** @todo r=klaus target isn't locked, race getting the state */
7127 if (task.midxSrcImageSame == UINT32_MAX)
7128 {
7129 vrc = VDCopy(hdd,
7130 VD_LAST_IMAGE,
7131 targetHdd,
7132 targetFormat.c_str(),
7133 (fCreatingTarget) ? targetLocation.c_str() : (char *)NULL,
7134 false /* fMoveByRename */,
7135 0 /* cbSize */,
7136 task.mVariant,
7137 targetId.raw(),
7138 VD_OPEN_FLAGS_NORMAL,
7139 NULL /* pVDIfsOperation */,
7140 pTarget->m->vdImageIfaces,
7141 task.mVDOperationIfaces);
7142 }
7143 else
7144 {
7145 vrc = VDCopyEx(hdd,
7146 VD_LAST_IMAGE,
7147 targetHdd,
7148 targetFormat.c_str(),
7149 (fCreatingTarget) ? targetLocation.c_str() : (char *)NULL,
7150 false /* fMoveByRename */,
7151 0 /* cbSize */,
7152 task.midxSrcImageSame,
7153 task.midxDstImageSame,
7154 task.mVariant,
7155 targetId.raw(),
7156 VD_OPEN_FLAGS_NORMAL,
7157 NULL /* pVDIfsOperation */,
7158 pTarget->m->vdImageIfaces,
7159 task.mVDOperationIfaces);
7160 }
7161 if (RT_FAILURE(vrc))
7162 throw setError(VBOX_E_FILE_ERROR,
7163 tr("Could not create the clone medium '%s'%s"),
7164 targetLocation.c_str(), vdError(vrc).c_str());
7165
7166 size = VDGetFileSize(targetHdd, VD_LAST_IMAGE);
7167 logicalSize = VDGetSize(targetHdd, VD_LAST_IMAGE);
7168 unsigned uImageFlags;
7169 vrc = VDGetImageFlags(targetHdd, 0, &uImageFlags);
7170 if (RT_SUCCESS(vrc))
7171 variant = (MediumVariant_T)uImageFlags;
7172 }
7173 catch (HRESULT aRC) { rcTmp = aRC; }
7174
7175 VDDestroy(targetHdd);
7176 }
7177 catch (HRESULT aRC) { rcTmp = aRC; }
7178
7179 VDDestroy(hdd);
7180 }
7181 catch (HRESULT aRC) { rcTmp = aRC; }
7182
7183 ErrorInfoKeeper eik;
7184 MultiResult mrc(rcTmp);
7185
7186 /* Only do the parent changes for newly created media. */
7187 if (SUCCEEDED(mrc) && fCreatingTarget)
7188 {
7189 /* we set mParent & children() */
7190 AutoWriteLock alock2(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
7191
7192 Assert(pTarget->m->pParent.isNull());
7193
7194 if (pParent)
7195 {
7196 /* associate the clone with the parent and deassociate
7197 * from VirtualBox */
7198 pTarget->m->pParent = pParent;
7199 pParent->m->llChildren.push_back(pTarget);
7200
7201 /* register with mVirtualBox as the last step and move to
7202 * Created state only on success (leaving an orphan file is
7203 * better than breaking media registry consistency) */
7204 eik.restore();
7205 mrc = pParent->m->pVirtualBox->registerHardDisk(pTarget, NULL /* pllRegistriesThatNeedSaving */);
7206 eik.fetch();
7207
7208 if (FAILED(mrc))
7209 /* break parent association on failure to register */
7210 pTarget->deparent(); // removes target from parent
7211 }
7212 else
7213 {
7214 /* just register */
7215 eik.restore();
7216 mrc = m->pVirtualBox->registerHardDisk(pTarget, NULL /* pllRegistriesThatNeedSaving */);
7217 eik.fetch();
7218 }
7219 }
7220
7221 if (fCreatingTarget)
7222 {
7223 AutoWriteLock mLock(pTarget COMMA_LOCKVAL_SRC_POS);
7224
7225 if (SUCCEEDED(mrc))
7226 {
7227 pTarget->m->state = MediumState_Created;
7228
7229 pTarget->m->size = size;
7230 pTarget->m->logicalSize = logicalSize;
7231 pTarget->m->variant = variant;
7232 }
7233 else
7234 {
7235 /* back to NotCreated on failure */
7236 pTarget->m->state = MediumState_NotCreated;
7237
7238 /* reset UUID to prevent it from being reused next time */
7239 if (fGenerateUuid)
7240 unconst(pTarget->m->id).clear();
7241 }
7242 }
7243
7244 // now, at the end of this task (always asynchronous), save the settings
7245 if (SUCCEEDED(mrc))
7246 {
7247 // save the settings
7248 GuidList llRegistriesThatNeedSaving;
7249 addToRegistryIDList(llRegistriesThatNeedSaving);
7250 /* collect multiple errors */
7251 eik.restore();
7252 mrc = m->pVirtualBox->saveRegistries(llRegistriesThatNeedSaving);
7253 eik.fetch();
7254 }
7255
7256 /* Everything is explicitly unlocked when the task exits,
7257 * as the task destruction also destroys the source chain. */
7258
7259 /* Make sure the source chain is released early. It could happen
7260 * that we get a deadlock in Appliance::Import when Medium::Close
7261 * is called & the source chain is released at the same time. */
7262 task.mpSourceMediumLockList->Clear();
7263
7264 return mrc;
7265}
7266
7267/**
7268 * Implementation code for the "delete" task.
7269 *
7270 * This task always gets started from Medium::deleteStorage() and can run
7271 * synchronously or asynchronously depending on the "wait" parameter passed to
7272 * that function.
7273 *
7274 * @param task
7275 * @return
7276 */
7277HRESULT Medium::taskDeleteHandler(Medium::DeleteTask &task)
7278{
7279 NOREF(task);
7280 HRESULT rc = S_OK;
7281
7282 try
7283 {
7284 /* The lock is also used as a signal from the task initiator (which
7285 * releases it only after RTThreadCreate()) that we can start the job */
7286 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
7287
7288 PVBOXHDD hdd;
7289 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
7290 ComAssertRCThrow(vrc, E_FAIL);
7291
7292 Utf8Str format(m->strFormat);
7293 Utf8Str location(m->strLocationFull);
7294
7295 /* unlock before the potentially lengthy operation */
7296 Assert(m->state == MediumState_Deleting);
7297 thisLock.release();
7298
7299 try
7300 {
7301 vrc = VDOpen(hdd,
7302 format.c_str(),
7303 location.c_str(),
7304 VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO,
7305 m->vdImageIfaces);
7306 if (RT_SUCCESS(vrc))
7307 vrc = VDClose(hdd, true /* fDelete */);
7308
7309 if (RT_FAILURE(vrc))
7310 throw setError(VBOX_E_FILE_ERROR,
7311 tr("Could not delete the medium storage unit '%s'%s"),
7312 location.c_str(), vdError(vrc).c_str());
7313
7314 }
7315 catch (HRESULT aRC) { rc = aRC; }
7316
7317 VDDestroy(hdd);
7318 }
7319 catch (HRESULT aRC) { rc = aRC; }
7320
7321 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
7322
7323 /* go to the NotCreated state even on failure since the storage
7324 * may have been already partially deleted and cannot be used any
7325 * more. One will be able to manually re-open the storage if really
7326 * needed to re-register it. */
7327 m->state = MediumState_NotCreated;
7328
7329 /* Reset UUID to prevent Create* from reusing it again */
7330 unconst(m->id).clear();
7331
7332 return rc;
7333}
7334
7335/**
7336 * Implementation code for the "reset" task.
7337 *
7338 * This always gets started asynchronously from Medium::Reset().
7339 *
7340 * @param task
7341 * @return
7342 */
7343HRESULT Medium::taskResetHandler(Medium::ResetTask &task)
7344{
7345 HRESULT rc = S_OK;
7346
7347 uint64_t size = 0, logicalSize = 0;
7348 MediumVariant_T variant = MediumVariant_Standard;
7349
7350 try
7351 {
7352 /* The lock is also used as a signal from the task initiator (which
7353 * releases it only after RTThreadCreate()) that we can start the job */
7354 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
7355
7356 /// @todo Below we use a pair of delete/create operations to reset
7357 /// the diff contents but the most efficient way will of course be
7358 /// to add a VDResetDiff() API call
7359
7360 PVBOXHDD hdd;
7361 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
7362 ComAssertRCThrow(vrc, E_FAIL);
7363
7364 Guid id = m->id;
7365 Utf8Str format(m->strFormat);
7366 Utf8Str location(m->strLocationFull);
7367
7368 Medium *pParent = m->pParent;
7369 Guid parentId = pParent->m->id;
7370 Utf8Str parentFormat(pParent->m->strFormat);
7371 Utf8Str parentLocation(pParent->m->strLocationFull);
7372
7373 Assert(m->state == MediumState_LockedWrite);
7374
7375 /* unlock before the potentially lengthy operation */
7376 thisLock.release();
7377
7378 try
7379 {
7380 /* Open all media in the target chain but the last. */
7381 MediumLockList::Base::const_iterator targetListBegin =
7382 task.mpMediumLockList->GetBegin();
7383 MediumLockList::Base::const_iterator targetListEnd =
7384 task.mpMediumLockList->GetEnd();
7385 for (MediumLockList::Base::const_iterator it = targetListBegin;
7386 it != targetListEnd;
7387 ++it)
7388 {
7389 const MediumLock &mediumLock = *it;
7390 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
7391
7392 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
7393
7394 /* sanity check, "this" is checked above */
7395 Assert( pMedium == this
7396 || pMedium->m->state == MediumState_LockedRead);
7397
7398 /* Open all media in appropriate mode. */
7399 vrc = VDOpen(hdd,
7400 pMedium->m->strFormat.c_str(),
7401 pMedium->m->strLocationFull.c_str(),
7402 VD_OPEN_FLAGS_READONLY,
7403 pMedium->m->vdImageIfaces);
7404 if (RT_FAILURE(vrc))
7405 throw setError(VBOX_E_FILE_ERROR,
7406 tr("Could not open the medium storage unit '%s'%s"),
7407 pMedium->m->strLocationFull.c_str(),
7408 vdError(vrc).c_str());
7409
7410 /* Done when we hit the media which should be reset */
7411 if (pMedium == this)
7412 break;
7413 }
7414
7415 /* first, delete the storage unit */
7416 vrc = VDClose(hdd, true /* fDelete */);
7417 if (RT_FAILURE(vrc))
7418 throw setError(VBOX_E_FILE_ERROR,
7419 tr("Could not delete the medium storage unit '%s'%s"),
7420 location.c_str(), vdError(vrc).c_str());
7421
7422 /* next, create it again */
7423 vrc = VDOpen(hdd,
7424 parentFormat.c_str(),
7425 parentLocation.c_str(),
7426 VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO,
7427 m->vdImageIfaces);
7428 if (RT_FAILURE(vrc))
7429 throw setError(VBOX_E_FILE_ERROR,
7430 tr("Could not open the medium storage unit '%s'%s"),
7431 parentLocation.c_str(), vdError(vrc).c_str());
7432
7433 vrc = VDCreateDiff(hdd,
7434 format.c_str(),
7435 location.c_str(),
7436 /// @todo use the same medium variant as before
7437 VD_IMAGE_FLAGS_NONE,
7438 NULL,
7439 id.raw(),
7440 parentId.raw(),
7441 VD_OPEN_FLAGS_NORMAL,
7442 m->vdImageIfaces,
7443 task.mVDOperationIfaces);
7444 if (RT_FAILURE(vrc))
7445 throw setError(VBOX_E_FILE_ERROR,
7446 tr("Could not create the differencing medium storage unit '%s'%s"),
7447 location.c_str(), vdError(vrc).c_str());
7448
7449 size = VDGetFileSize(hdd, VD_LAST_IMAGE);
7450 logicalSize = VDGetSize(hdd, VD_LAST_IMAGE);
7451 unsigned uImageFlags;
7452 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
7453 if (RT_SUCCESS(vrc))
7454 variant = (MediumVariant_T)uImageFlags;
7455 }
7456 catch (HRESULT aRC) { rc = aRC; }
7457
7458 VDDestroy(hdd);
7459 }
7460 catch (HRESULT aRC) { rc = aRC; }
7461
7462 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
7463
7464 m->size = size;
7465 m->logicalSize = logicalSize;
7466 m->variant = variant;
7467
7468 if (task.isAsync())
7469 {
7470 /* unlock ourselves when done */
7471 HRESULT rc2 = UnlockWrite(NULL);
7472 AssertComRC(rc2);
7473 }
7474
7475 /* Note that in sync mode, it's the caller's responsibility to
7476 * unlock the medium. */
7477
7478 return rc;
7479}
7480
7481/**
7482 * Implementation code for the "compact" task.
7483 *
7484 * @param task
7485 * @return
7486 */
7487HRESULT Medium::taskCompactHandler(Medium::CompactTask &task)
7488{
7489 HRESULT rc = S_OK;
7490
7491 /* Lock all in {parent,child} order. The lock is also used as a
7492 * signal from the task initiator (which releases it only after
7493 * RTThreadCreate()) that we can start the job. */
7494 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
7495
7496 try
7497 {
7498 PVBOXHDD hdd;
7499 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
7500 ComAssertRCThrow(vrc, E_FAIL);
7501
7502 try
7503 {
7504 /* Open all media in the chain. */
7505 MediumLockList::Base::const_iterator mediumListBegin =
7506 task.mpMediumLockList->GetBegin();
7507 MediumLockList::Base::const_iterator mediumListEnd =
7508 task.mpMediumLockList->GetEnd();
7509 MediumLockList::Base::const_iterator mediumListLast =
7510 mediumListEnd;
7511 mediumListLast--;
7512 for (MediumLockList::Base::const_iterator it = mediumListBegin;
7513 it != mediumListEnd;
7514 ++it)
7515 {
7516 const MediumLock &mediumLock = *it;
7517 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
7518 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
7519
7520 /* sanity check */
7521 if (it == mediumListLast)
7522 Assert(pMedium->m->state == MediumState_LockedWrite);
7523 else
7524 Assert(pMedium->m->state == MediumState_LockedRead);
7525
7526 /* Open all media but last in read-only mode. Do not handle
7527 * shareable media, as compaction and sharing are mutually
7528 * exclusive. */
7529 vrc = VDOpen(hdd,
7530 pMedium->m->strFormat.c_str(),
7531 pMedium->m->strLocationFull.c_str(),
7532 (it == mediumListLast) ? VD_OPEN_FLAGS_NORMAL : VD_OPEN_FLAGS_READONLY,
7533 pMedium->m->vdImageIfaces);
7534 if (RT_FAILURE(vrc))
7535 throw setError(VBOX_E_FILE_ERROR,
7536 tr("Could not open the medium storage unit '%s'%s"),
7537 pMedium->m->strLocationFull.c_str(),
7538 vdError(vrc).c_str());
7539 }
7540
7541 Assert(m->state == MediumState_LockedWrite);
7542
7543 Utf8Str location(m->strLocationFull);
7544
7545 /* unlock before the potentially lengthy operation */
7546 thisLock.release();
7547
7548 vrc = VDCompact(hdd, VD_LAST_IMAGE, task.mVDOperationIfaces);
7549 if (RT_FAILURE(vrc))
7550 {
7551 if (vrc == VERR_NOT_SUPPORTED)
7552 throw setError(VBOX_E_NOT_SUPPORTED,
7553 tr("Compacting is not yet supported for medium '%s'"),
7554 location.c_str());
7555 else if (vrc == VERR_NOT_IMPLEMENTED)
7556 throw setError(E_NOTIMPL,
7557 tr("Compacting is not implemented, medium '%s'"),
7558 location.c_str());
7559 else
7560 throw setError(VBOX_E_FILE_ERROR,
7561 tr("Could not compact medium '%s'%s"),
7562 location.c_str(),
7563 vdError(vrc).c_str());
7564 }
7565 }
7566 catch (HRESULT aRC) { rc = aRC; }
7567
7568 VDDestroy(hdd);
7569 }
7570 catch (HRESULT aRC) { rc = aRC; }
7571
7572 /* Everything is explicitly unlocked when the task exits,
7573 * as the task destruction also destroys the media chain. */
7574
7575 return rc;
7576}
7577
7578/**
7579 * Implementation code for the "resize" task.
7580 *
7581 * @param task
7582 * @return
7583 */
7584HRESULT Medium::taskResizeHandler(Medium::ResizeTask &task)
7585{
7586 HRESULT rc = S_OK;
7587
7588 /* Lock all in {parent,child} order. The lock is also used as a
7589 * signal from the task initiator (which releases it only after
7590 * RTThreadCreate()) that we can start the job. */
7591 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
7592
7593 try
7594 {
7595 PVBOXHDD hdd;
7596 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
7597 ComAssertRCThrow(vrc, E_FAIL);
7598
7599 try
7600 {
7601 /* Open all media in the chain. */
7602 MediumLockList::Base::const_iterator mediumListBegin =
7603 task.mpMediumLockList->GetBegin();
7604 MediumLockList::Base::const_iterator mediumListEnd =
7605 task.mpMediumLockList->GetEnd();
7606 MediumLockList::Base::const_iterator mediumListLast =
7607 mediumListEnd;
7608 mediumListLast--;
7609 for (MediumLockList::Base::const_iterator it = mediumListBegin;
7610 it != mediumListEnd;
7611 ++it)
7612 {
7613 const MediumLock &mediumLock = *it;
7614 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
7615 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
7616
7617 /* sanity check */
7618 if (it == mediumListLast)
7619 Assert(pMedium->m->state == MediumState_LockedWrite);
7620 else
7621 Assert(pMedium->m->state == MediumState_LockedRead);
7622
7623 /* Open all media but last in read-only mode. Do not handle
7624 * shareable media, as compaction and sharing are mutually
7625 * exclusive. */
7626 vrc = VDOpen(hdd,
7627 pMedium->m->strFormat.c_str(),
7628 pMedium->m->strLocationFull.c_str(),
7629 (it == mediumListLast) ? VD_OPEN_FLAGS_NORMAL : VD_OPEN_FLAGS_READONLY,
7630 pMedium->m->vdImageIfaces);
7631 if (RT_FAILURE(vrc))
7632 throw setError(VBOX_E_FILE_ERROR,
7633 tr("Could not open the medium storage unit '%s'%s"),
7634 pMedium->m->strLocationFull.c_str(),
7635 vdError(vrc).c_str());
7636 }
7637
7638 Assert(m->state == MediumState_LockedWrite);
7639
7640 Utf8Str location(m->strLocationFull);
7641
7642 /* unlock before the potentially lengthy operation */
7643 thisLock.release();
7644
7645 VDGEOMETRY geo = {0, 0, 0}; /* auto */
7646 vrc = VDResize(hdd, task.mSize, &geo, &geo, task.mVDOperationIfaces);
7647 if (RT_FAILURE(vrc))
7648 {
7649 if (vrc == VERR_NOT_SUPPORTED)
7650 throw setError(VBOX_E_NOT_SUPPORTED,
7651 tr("Compacting is not yet supported for medium '%s'"),
7652 location.c_str());
7653 else if (vrc == VERR_NOT_IMPLEMENTED)
7654 throw setError(E_NOTIMPL,
7655 tr("Compacting is not implemented, medium '%s'"),
7656 location.c_str());
7657 else
7658 throw setError(VBOX_E_FILE_ERROR,
7659 tr("Could not compact medium '%s'%s"),
7660 location.c_str(),
7661 vdError(vrc).c_str());
7662 }
7663 }
7664 catch (HRESULT aRC) { rc = aRC; }
7665
7666 VDDestroy(hdd);
7667 }
7668 catch (HRESULT aRC) { rc = aRC; }
7669
7670 /* Everything is explicitly unlocked when the task exits,
7671 * as the task destruction also destroys the media chain. */
7672
7673 return rc;
7674}
7675
7676/**
7677 * Implementation code for the "export" task.
7678 *
7679 * This only gets started from Medium::exportFile() and always runs
7680 * asynchronously. It doesn't touch anything configuration related, so
7681 * we never save the VirtualBox.xml file here.
7682 *
7683 * @param task
7684 * @return
7685 */
7686HRESULT Medium::taskExportHandler(Medium::ExportTask &task)
7687{
7688 HRESULT rc = S_OK;
7689
7690 try
7691 {
7692 /* Lock all in {parent,child} order. The lock is also used as a
7693 * signal from the task initiator (which releases it only after
7694 * RTThreadCreate()) that we can start the job. */
7695 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
7696
7697 PVBOXHDD hdd;
7698 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
7699 ComAssertRCThrow(vrc, E_FAIL);
7700
7701 try
7702 {
7703 /* Open all media in the source chain. */
7704 MediumLockList::Base::const_iterator sourceListBegin =
7705 task.mpSourceMediumLockList->GetBegin();
7706 MediumLockList::Base::const_iterator sourceListEnd =
7707 task.mpSourceMediumLockList->GetEnd();
7708 for (MediumLockList::Base::const_iterator it = sourceListBegin;
7709 it != sourceListEnd;
7710 ++it)
7711 {
7712 const MediumLock &mediumLock = *it;
7713 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
7714 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
7715
7716 /* sanity check */
7717 Assert(pMedium->m->state == MediumState_LockedRead);
7718
7719 /* Open all media in read-only mode. */
7720 vrc = VDOpen(hdd,
7721 pMedium->m->strFormat.c_str(),
7722 pMedium->m->strLocationFull.c_str(),
7723 VD_OPEN_FLAGS_READONLY,
7724 pMedium->m->vdImageIfaces);
7725 if (RT_FAILURE(vrc))
7726 throw setError(VBOX_E_FILE_ERROR,
7727 tr("Could not open the medium storage unit '%s'%s"),
7728 pMedium->m->strLocationFull.c_str(),
7729 vdError(vrc).c_str());
7730 }
7731
7732 Utf8Str targetFormat(task.mFormat->getId());
7733 Utf8Str targetLocation(task.mFilename);
7734 uint64_t capabilities = task.mFormat->getCapabilities();
7735
7736 Assert(m->state == MediumState_LockedRead);
7737
7738 /* unlock before the potentially lengthy operation */
7739 thisLock.release();
7740
7741 /* ensure the target directory exists */
7742 if (capabilities & MediumFormatCapabilities_File)
7743 {
7744 rc = VirtualBox::ensureFilePathExists(targetLocation);
7745 if (FAILED(rc))
7746 throw rc;
7747 }
7748
7749 PVBOXHDD targetHdd;
7750 vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &targetHdd);
7751 ComAssertRCThrow(vrc, E_FAIL);
7752
7753 try
7754 {
7755 vrc = VDCopy(hdd,
7756 VD_LAST_IMAGE,
7757 targetHdd,
7758 targetFormat.c_str(),
7759 targetLocation.c_str(),
7760 false /* fMoveByRename */,
7761 0 /* cbSize */,
7762 task.mVariant,
7763 NULL /* pDstUuid */,
7764 VD_OPEN_FLAGS_NORMAL | VD_OPEN_FLAGS_SEQUENTIAL,
7765 NULL /* pVDIfsOperation */,
7766 task.mVDImageIfaces,
7767 task.mVDOperationIfaces);
7768 if (RT_FAILURE(vrc))
7769 throw setError(VBOX_E_FILE_ERROR,
7770 tr("Could not create the clone medium '%s'%s"),
7771 targetLocation.c_str(), vdError(vrc).c_str());
7772 }
7773 catch (HRESULT aRC) { rc = aRC; }
7774
7775 VDDestroy(targetHdd);
7776 }
7777 catch (HRESULT aRC) { rc = aRC; }
7778
7779 VDDestroy(hdd);
7780 }
7781 catch (HRESULT aRC) { rc = aRC; }
7782
7783 /* Everything is explicitly unlocked when the task exits,
7784 * as the task destruction also destroys the source chain. */
7785
7786 /* Make sure the source chain is released early, otherwise it can
7787 * lead to deadlocks with concurrent IAppliance activities. */
7788 task.mpSourceMediumLockList->Clear();
7789
7790 return rc;
7791}
7792
7793/**
7794 * Implementation code for the "import" task.
7795 *
7796 * This only gets started from Medium::importFile() and always runs
7797 * asynchronously. It potentially touches the media registry, so we
7798 * always save the VirtualBox.xml file when we're done here.
7799 *
7800 * @param task
7801 * @return
7802 */
7803HRESULT Medium::taskImportHandler(Medium::ImportTask &task)
7804{
7805 HRESULT rcTmp = S_OK;
7806
7807 const ComObjPtr<Medium> &pParent = task.mParent;
7808
7809 bool fCreatingTarget = false;
7810
7811 uint64_t size = 0, logicalSize = 0;
7812 MediumVariant_T variant = MediumVariant_Standard;
7813 bool fGenerateUuid = false;
7814
7815 try
7816 {
7817 /* Lock all in {parent,child} order. The lock is also used as a
7818 * signal from the task initiator (which releases it only after
7819 * RTThreadCreate()) that we can start the job. */
7820 AutoMultiWriteLock2 thisLock(this, pParent COMMA_LOCKVAL_SRC_POS);
7821
7822 fCreatingTarget = m->state == MediumState_Creating;
7823
7824 /* The object may request a specific UUID (through a special form of
7825 * the setLocation() argument). Otherwise we have to generate it */
7826 Guid targetId = m->id;
7827 fGenerateUuid = targetId.isEmpty();
7828 if (fGenerateUuid)
7829 {
7830 targetId.create();
7831 /* VirtualBox::registerHardDisk() will need UUID */
7832 unconst(m->id) = targetId;
7833 }
7834
7835
7836 PVBOXHDD hdd;
7837 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
7838 ComAssertRCThrow(vrc, E_FAIL);
7839
7840 try
7841 {
7842 /* Open source medium. */
7843 vrc = VDOpen(hdd,
7844 task.mFormat->getId().c_str(),
7845 task.mFilename.c_str(),
7846 VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_SEQUENTIAL,
7847 task.mVDImageIfaces);
7848 if (RT_FAILURE(vrc))
7849 throw setError(VBOX_E_FILE_ERROR,
7850 tr("Could not open the medium storage unit '%s'%s"),
7851 task.mFilename.c_str(),
7852 vdError(vrc).c_str());
7853
7854 Utf8Str targetFormat(m->strFormat);
7855 Utf8Str targetLocation(m->strLocationFull);
7856 uint64_t capabilities = task.mFormat->getCapabilities();
7857
7858 Assert( m->state == MediumState_Creating
7859 || m->state == MediumState_LockedWrite);
7860 Assert( pParent.isNull()
7861 || pParent->m->state == MediumState_LockedRead);
7862
7863 /* unlock before the potentially lengthy operation */
7864 thisLock.release();
7865
7866 /* ensure the target directory exists */
7867 if (capabilities & MediumFormatCapabilities_File)
7868 {
7869 HRESULT rc = VirtualBox::ensureFilePathExists(targetLocation);
7870 if (FAILED(rc))
7871 throw rc;
7872 }
7873
7874 PVBOXHDD targetHdd;
7875 vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &targetHdd);
7876 ComAssertRCThrow(vrc, E_FAIL);
7877
7878 try
7879 {
7880 /* Open all media in the target chain. */
7881 MediumLockList::Base::const_iterator targetListBegin =
7882 task.mpTargetMediumLockList->GetBegin();
7883 MediumLockList::Base::const_iterator targetListEnd =
7884 task.mpTargetMediumLockList->GetEnd();
7885 for (MediumLockList::Base::const_iterator it = targetListBegin;
7886 it != targetListEnd;
7887 ++it)
7888 {
7889 const MediumLock &mediumLock = *it;
7890 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
7891
7892 /* If the target medium is not created yet there's no
7893 * reason to open it. */
7894 if (pMedium == this && fCreatingTarget)
7895 continue;
7896
7897 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
7898
7899 /* sanity check */
7900 Assert( pMedium->m->state == MediumState_LockedRead
7901 || pMedium->m->state == MediumState_LockedWrite);
7902
7903 unsigned uOpenFlags = VD_OPEN_FLAGS_NORMAL;
7904 if (pMedium->m->state != MediumState_LockedWrite)
7905 uOpenFlags = VD_OPEN_FLAGS_READONLY;
7906 if (pMedium->m->type == MediumType_Shareable)
7907 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
7908
7909 /* Open all media in appropriate mode. */
7910 vrc = VDOpen(targetHdd,
7911 pMedium->m->strFormat.c_str(),
7912 pMedium->m->strLocationFull.c_str(),
7913 uOpenFlags,
7914 pMedium->m->vdImageIfaces);
7915 if (RT_FAILURE(vrc))
7916 throw setError(VBOX_E_FILE_ERROR,
7917 tr("Could not open the medium storage unit '%s'%s"),
7918 pMedium->m->strLocationFull.c_str(),
7919 vdError(vrc).c_str());
7920 }
7921
7922 /** @todo r=klaus target isn't locked, race getting the state */
7923 vrc = VDCopy(hdd,
7924 VD_LAST_IMAGE,
7925 targetHdd,
7926 targetFormat.c_str(),
7927 (fCreatingTarget) ? targetLocation.c_str() : (char *)NULL,
7928 false /* fMoveByRename */,
7929 0 /* cbSize */,
7930 task.mVariant,
7931 targetId.raw(),
7932 VD_OPEN_FLAGS_NORMAL,
7933 NULL /* pVDIfsOperation */,
7934 m->vdImageIfaces,
7935 task.mVDOperationIfaces);
7936 if (RT_FAILURE(vrc))
7937 throw setError(VBOX_E_FILE_ERROR,
7938 tr("Could not create the clone medium '%s'%s"),
7939 targetLocation.c_str(), vdError(vrc).c_str());
7940
7941 size = VDGetFileSize(targetHdd, VD_LAST_IMAGE);
7942 logicalSize = VDGetSize(targetHdd, VD_LAST_IMAGE);
7943 unsigned uImageFlags;
7944 vrc = VDGetImageFlags(targetHdd, 0, &uImageFlags);
7945 if (RT_SUCCESS(vrc))
7946 variant = (MediumVariant_T)uImageFlags;
7947 }
7948 catch (HRESULT aRC) { rcTmp = aRC; }
7949
7950 VDDestroy(targetHdd);
7951 }
7952 catch (HRESULT aRC) { rcTmp = aRC; }
7953
7954 VDDestroy(hdd);
7955 }
7956 catch (HRESULT aRC) { rcTmp = aRC; }
7957
7958 ErrorInfoKeeper eik;
7959 MultiResult mrc(rcTmp);
7960
7961 /* Only do the parent changes for newly created media. */
7962 if (SUCCEEDED(mrc) && fCreatingTarget)
7963 {
7964 /* we set mParent & children() */
7965 AutoWriteLock alock2(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
7966
7967 Assert(m->pParent.isNull());
7968
7969 if (pParent)
7970 {
7971 /* associate the clone with the parent and deassociate
7972 * from VirtualBox */
7973 m->pParent = pParent;
7974 pParent->m->llChildren.push_back(this);
7975
7976 /* register with mVirtualBox as the last step and move to
7977 * Created state only on success (leaving an orphan file is
7978 * better than breaking media registry consistency) */
7979 eik.restore();
7980 mrc = pParent->m->pVirtualBox->registerHardDisk(this, NULL /* llRegistriesThatNeedSaving */);
7981 eik.fetch();
7982
7983 if (FAILED(mrc))
7984 /* break parent association on failure to register */
7985 this->deparent(); // removes target from parent
7986 }
7987 else
7988 {
7989 /* just register */
7990 eik.restore();
7991 mrc = m->pVirtualBox->registerHardDisk(this, NULL /* pllRegistriesThatNeedSaving */);
7992 eik.fetch();
7993 }
7994 }
7995
7996 if (fCreatingTarget)
7997 {
7998 AutoWriteLock mLock(this COMMA_LOCKVAL_SRC_POS);
7999
8000 if (SUCCEEDED(mrc))
8001 {
8002 m->state = MediumState_Created;
8003
8004 m->size = size;
8005 m->logicalSize = logicalSize;
8006 m->variant = variant;
8007 }
8008 else
8009 {
8010 /* back to NotCreated on failure */
8011 m->state = MediumState_NotCreated;
8012
8013 /* reset UUID to prevent it from being reused next time */
8014 if (fGenerateUuid)
8015 unconst(m->id).clear();
8016 }
8017 }
8018
8019 // now, at the end of this task (always asynchronous), save the settings
8020 {
8021 // save the settings
8022 GuidList llRegistriesThatNeedSaving;
8023 addToRegistryIDList(llRegistriesThatNeedSaving);
8024 /* collect multiple errors */
8025 eik.restore();
8026 mrc = m->pVirtualBox->saveRegistries(llRegistriesThatNeedSaving);
8027 eik.fetch();
8028 }
8029
8030 /* Everything is explicitly unlocked when the task exits,
8031 * as the task destruction also destroys the target chain. */
8032
8033 /* Make sure the target chain is released early, otherwise it can
8034 * lead to deadlocks with concurrent IAppliance activities. */
8035 task.mpTargetMediumLockList->Clear();
8036
8037 return mrc;
8038}
8039
8040/* 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