VirtualBox

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

Last change on this file since 44098 was 44091, checked in by vboxsync, 12 years ago

Main: make the code more readable. Places where the comparisons were of the form 'isValid() == true\false' or 'isZero() == true\false' were carved \ simplified.

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

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette