VirtualBox

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

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

Main/Medium: public cloneToEx API for internal use which makes it possible to control certain optimizations during VM cloning

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