VirtualBox

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

最後變更 在這個檔案從42163是 42125,由 vboxsync 提交於 13 年 前

optional encrypted store of the iSCSI initiator secret

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

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