VirtualBox

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

Last change on this file since 39694 was 38818, checked in by vboxsync, 13 years ago

Main/Medium+Snapshot+VirtualBox: extend the API in a compatible way to support skipping the automatic directory creation when creating new images.

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