VirtualBox

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

Last change on this file since 38729 was 38729, checked in by vboxsync, 14 years ago

Main/Medium+Machine: fix lock order issues when creating diff images, and eliminate a bit of redundant code.

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

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