VirtualBox

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

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

Main/Medium: fix object locks and medium lock state in createDiffStorage()

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