VirtualBox

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

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

Main/Medium: fix error message handling in the error cleanup code

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