VirtualBox

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

Last change on this file since 43677 was 43669, checked in by vboxsync, 12 years ago

Main/MediumImpl: Fix deadlock when two threads attempt to close the same medium object. Triggers lock order violation which is not detectable by the lock validator as only one lock is a RW semaphore, the other one is the AutoCaller event semaphore used for synchronizing callers and init/uninit.

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