VirtualBox

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

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

build fix

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