VirtualBox

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

Last change on this file since 45055 was 44433, checked in by vboxsync, 12 years ago

Main/Medium: improve the error handling for medium UUID change failures, e.g. when the medium is readonly.

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

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