VirtualBox

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

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

Main/Medium: make CreateDiffMedium more convenient to use by associating the medium with a registry, and fix error handling in CloneTo by not attempting to save the config since this often causes spurious extra error messages

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