VirtualBox

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

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

Main: fix possible dead-lock between IMedium::RefreshState and IMedium::Reset

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