VirtualBox

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

Last change on this file since 44413 was 44409, checked in by vboxsync, 12 years ago

Main/Medium: resizing needs to update the image size information, and finally rip out the useless and weird logic which always returned the capacity for the base medium for all diff images,

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

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