VirtualBox

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

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

Main/Medium: lock typo

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 268.6 KB
Line 
1/* $Id: MediumImpl.cpp 38744 2011-09-13 15:00:42Z 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 // and we need to write-lock the media involved
2650 AutoMultiWriteLock4 alock(&m->pVirtualBox->getMediaTreeLockHandle(),
2651 this->lockHandle(),
2652 pTarget->lockHandle(),
2653 pParent->lockHandle() COMMA_LOCKVAL_SRC_POS);
2654
2655 if ( pTarget->m->state != MediumState_NotCreated
2656 && pTarget->m->state != MediumState_Created)
2657 throw pTarget->setStateError();
2658
2659 /* Build the source lock list. */
2660 MediumLockList *pSourceMediumLockList(new MediumLockList());
2661 rc = createMediumLockList(true /* fFailIfInaccessible */,
2662 false /* fMediumLockWrite */,
2663 NULL,
2664 *pSourceMediumLockList);
2665 if (FAILED(rc))
2666 {
2667 delete pSourceMediumLockList;
2668 throw rc;
2669 }
2670
2671 /* Build the target lock list (including the to-be parent chain). */
2672 MediumLockList *pTargetMediumLockList(new MediumLockList());
2673 rc = pTarget->createMediumLockList(true /* fFailIfInaccessible */,
2674 true /* fMediumLockWrite */,
2675 pParent,
2676 *pTargetMediumLockList);
2677 if (FAILED(rc))
2678 {
2679 delete pSourceMediumLockList;
2680 delete pTargetMediumLockList;
2681 throw rc;
2682 }
2683
2684 rc = pSourceMediumLockList->Lock();
2685 if (FAILED(rc))
2686 {
2687 delete pSourceMediumLockList;
2688 delete pTargetMediumLockList;
2689 throw setError(rc,
2690 tr("Failed to lock source media '%s'"),
2691 getLocationFull().c_str());
2692 }
2693 rc = pTargetMediumLockList->Lock();
2694 if (FAILED(rc))
2695 {
2696 delete pSourceMediumLockList;
2697 delete pTargetMediumLockList;
2698 throw setError(rc,
2699 tr("Failed to lock target media '%s'"),
2700 pTarget->getLocationFull().c_str());
2701 }
2702
2703 pProgress.createObject();
2704 rc = pProgress->init(m->pVirtualBox,
2705 static_cast <IMedium *>(this),
2706 BstrFmt(tr("Creating clone medium '%s'"), pTarget->m->strLocationFull.c_str()).raw(),
2707 TRUE /* aCancelable */);
2708 if (FAILED(rc))
2709 {
2710 delete pSourceMediumLockList;
2711 delete pTargetMediumLockList;
2712 throw rc;
2713 }
2714
2715 /* setup task object to carry out the operation asynchronously */
2716 pTask = new Medium::CloneTask(this, pProgress, pTarget,
2717 (MediumVariant_T)aVariant,
2718 pParent, UINT32_MAX, UINT32_MAX,
2719 pSourceMediumLockList, pTargetMediumLockList);
2720 rc = pTask->rc();
2721 AssertComRC(rc);
2722 if (FAILED(rc))
2723 throw rc;
2724
2725 if (pTarget->m->state == MediumState_NotCreated)
2726 pTarget->m->state = MediumState_Creating;
2727 }
2728 catch (HRESULT aRC) { rc = aRC; }
2729
2730 if (SUCCEEDED(rc))
2731 {
2732 rc = startThread(pTask);
2733
2734 if (SUCCEEDED(rc))
2735 pProgress.queryInterfaceTo(aProgress);
2736 }
2737 else if (pTask != NULL)
2738 delete pTask;
2739
2740 return rc;
2741}
2742
2743STDMETHODIMP Medium::Compact(IProgress **aProgress)
2744{
2745 CheckComArgOutPointerValid(aProgress);
2746
2747 AutoCaller autoCaller(this);
2748 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2749
2750 HRESULT rc = S_OK;
2751 ComObjPtr <Progress> pProgress;
2752 Medium::Task *pTask = NULL;
2753
2754 try
2755 {
2756 /* We need to lock both the current object, and the tree lock (would
2757 * cause a lock order violation otherwise) for createMediumLockList. */
2758 AutoMultiWriteLock2 multilock(&m->pVirtualBox->getMediaTreeLockHandle(),
2759 this->lockHandle()
2760 COMMA_LOCKVAL_SRC_POS);
2761
2762 /* Build the medium lock list. */
2763 MediumLockList *pMediumLockList(new MediumLockList());
2764 rc = createMediumLockList(true /* fFailIfInaccessible */ ,
2765 true /* fMediumLockWrite */,
2766 NULL,
2767 *pMediumLockList);
2768 if (FAILED(rc))
2769 {
2770 delete pMediumLockList;
2771 throw rc;
2772 }
2773
2774 rc = pMediumLockList->Lock();
2775 if (FAILED(rc))
2776 {
2777 delete pMediumLockList;
2778 throw setError(rc,
2779 tr("Failed to lock media when compacting '%s'"),
2780 getLocationFull().c_str());
2781 }
2782
2783 pProgress.createObject();
2784 rc = pProgress->init(m->pVirtualBox,
2785 static_cast <IMedium *>(this),
2786 BstrFmt(tr("Compacting medium '%s'"), m->strLocationFull.c_str()).raw(),
2787 TRUE /* aCancelable */);
2788 if (FAILED(rc))
2789 {
2790 delete pMediumLockList;
2791 throw rc;
2792 }
2793
2794 /* setup task object to carry out the operation asynchronously */
2795 pTask = new Medium::CompactTask(this, pProgress, pMediumLockList);
2796 rc = pTask->rc();
2797 AssertComRC(rc);
2798 if (FAILED(rc))
2799 throw rc;
2800 }
2801 catch (HRESULT aRC) { rc = aRC; }
2802
2803 if (SUCCEEDED(rc))
2804 {
2805 rc = startThread(pTask);
2806
2807 if (SUCCEEDED(rc))
2808 pProgress.queryInterfaceTo(aProgress);
2809 }
2810 else if (pTask != NULL)
2811 delete pTask;
2812
2813 return rc;
2814}
2815
2816STDMETHODIMP Medium::Resize(LONG64 aLogicalSize, IProgress **aProgress)
2817{
2818 CheckComArgOutPointerValid(aProgress);
2819
2820 AutoCaller autoCaller(this);
2821 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2822
2823 HRESULT rc = S_OK;
2824 ComObjPtr <Progress> pProgress;
2825 Medium::Task *pTask = NULL;
2826
2827 try
2828 {
2829 /* We need to lock both the current object, and the tree lock (would
2830 * cause a lock order violation otherwise) for createMediumLockList. */
2831 AutoMultiWriteLock2 multilock(&m->pVirtualBox->getMediaTreeLockHandle(),
2832 this->lockHandle()
2833 COMMA_LOCKVAL_SRC_POS);
2834
2835 /* Build the medium lock list. */
2836 MediumLockList *pMediumLockList(new MediumLockList());
2837 rc = createMediumLockList(true /* fFailIfInaccessible */ ,
2838 true /* fMediumLockWrite */,
2839 NULL,
2840 *pMediumLockList);
2841 if (FAILED(rc))
2842 {
2843 delete pMediumLockList;
2844 throw rc;
2845 }
2846
2847 rc = pMediumLockList->Lock();
2848 if (FAILED(rc))
2849 {
2850 delete pMediumLockList;
2851 throw setError(rc,
2852 tr("Failed to lock media when compacting '%s'"),
2853 getLocationFull().c_str());
2854 }
2855
2856 pProgress.createObject();
2857 rc = pProgress->init(m->pVirtualBox,
2858 static_cast <IMedium *>(this),
2859 BstrFmt(tr("Compacting medium '%s'"), m->strLocationFull.c_str()).raw(),
2860 TRUE /* aCancelable */);
2861 if (FAILED(rc))
2862 {
2863 delete pMediumLockList;
2864 throw rc;
2865 }
2866
2867 /* setup task object to carry out the operation asynchronously */
2868 pTask = new Medium::ResizeTask(this, aLogicalSize, pProgress, pMediumLockList);
2869 rc = pTask->rc();
2870 AssertComRC(rc);
2871 if (FAILED(rc))
2872 throw rc;
2873 }
2874 catch (HRESULT aRC) { rc = aRC; }
2875
2876 if (SUCCEEDED(rc))
2877 {
2878 rc = startThread(pTask);
2879
2880 if (SUCCEEDED(rc))
2881 pProgress.queryInterfaceTo(aProgress);
2882 }
2883 else if (pTask != NULL)
2884 delete pTask;
2885
2886 return rc;
2887}
2888
2889STDMETHODIMP Medium::Reset(IProgress **aProgress)
2890{
2891 CheckComArgOutPointerValid(aProgress);
2892
2893 AutoCaller autoCaller(this);
2894 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2895
2896 HRESULT rc = S_OK;
2897 ComObjPtr <Progress> pProgress;
2898 Medium::Task *pTask = NULL;
2899
2900 try
2901 {
2902 /* canClose() needs the tree lock */
2903 AutoMultiWriteLock2 multilock(&m->pVirtualBox->getMediaTreeLockHandle(),
2904 this->lockHandle()
2905 COMMA_LOCKVAL_SRC_POS);
2906
2907 LogFlowThisFunc(("ENTER for medium %s\n", m->strLocationFull.c_str()));
2908
2909 if (m->pParent.isNull())
2910 throw setError(VBOX_E_NOT_SUPPORTED,
2911 tr("Medium type of '%s' is not differencing"),
2912 m->strLocationFull.c_str());
2913
2914 rc = canClose();
2915 if (FAILED(rc))
2916 throw rc;
2917
2918 /* Build the medium lock list. */
2919 MediumLockList *pMediumLockList(new MediumLockList());
2920 rc = createMediumLockList(true /* fFailIfInaccessible */,
2921 true /* fMediumLockWrite */,
2922 NULL,
2923 *pMediumLockList);
2924 if (FAILED(rc))
2925 {
2926 delete pMediumLockList;
2927 throw rc;
2928 }
2929
2930 /* Temporary leave this lock, cause IMedium::LockWrite, will wait for
2931 * an running IMedium::queryInfo. If there is one running it might be
2932 * it tries to acquire a MediaTreeLock as well -> dead-lock. */
2933 multilock.leave();
2934 rc = pMediumLockList->Lock();
2935 multilock.enter();
2936 if (FAILED(rc))
2937 {
2938 delete pMediumLockList;
2939 throw setError(rc,
2940 tr("Failed to lock media when resetting '%s'"),
2941 getLocationFull().c_str());
2942 }
2943
2944 pProgress.createObject();
2945 rc = pProgress->init(m->pVirtualBox,
2946 static_cast<IMedium*>(this),
2947 BstrFmt(tr("Resetting differencing medium '%s'"), m->strLocationFull.c_str()).raw(),
2948 FALSE /* aCancelable */);
2949 if (FAILED(rc))
2950 throw rc;
2951
2952 /* setup task object to carry out the operation asynchronously */
2953 pTask = new Medium::ResetTask(this, pProgress, pMediumLockList);
2954 rc = pTask->rc();
2955 AssertComRC(rc);
2956 if (FAILED(rc))
2957 throw rc;
2958 }
2959 catch (HRESULT aRC) { rc = aRC; }
2960
2961 if (SUCCEEDED(rc))
2962 {
2963 rc = startThread(pTask);
2964
2965 if (SUCCEEDED(rc))
2966 pProgress.queryInterfaceTo(aProgress);
2967 }
2968 else
2969 {
2970 /* Note: on success, the task will unlock this */
2971 {
2972 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2973 HRESULT rc2 = UnlockWrite(NULL);
2974 AssertComRC(rc2);
2975 }
2976 if (pTask != NULL)
2977 delete pTask;
2978 }
2979
2980 LogFlowThisFunc(("LEAVE, rc=%Rhrc\n", rc));
2981
2982 return rc;
2983}
2984
2985////////////////////////////////////////////////////////////////////////////////
2986//
2987// Medium public internal methods
2988//
2989////////////////////////////////////////////////////////////////////////////////
2990
2991/**
2992 * Internal method to return the medium's parent medium. Must have caller + locking!
2993 * @return
2994 */
2995const ComObjPtr<Medium>& Medium::getParent() const
2996{
2997 return m->pParent;
2998}
2999
3000/**
3001 * Internal method to return the medium's list of child media. Must have caller + locking!
3002 * @return
3003 */
3004const MediaList& Medium::getChildren() const
3005{
3006 return m->llChildren;
3007}
3008
3009/**
3010 * Internal method to return the medium's GUID. Must have caller + locking!
3011 * @return
3012 */
3013const Guid& Medium::getId() const
3014{
3015 return m->id;
3016}
3017
3018/**
3019 * Internal method to return the medium's state. Must have caller + locking!
3020 * @return
3021 */
3022MediumState_T Medium::getState() const
3023{
3024 return m->state;
3025}
3026
3027/**
3028 * Internal method to return the medium's variant. Must have caller + locking!
3029 * @return
3030 */
3031MediumVariant_T Medium::getVariant() const
3032{
3033 return m->variant;
3034}
3035
3036/**
3037 * Internal method which returns true if this medium represents a host drive.
3038 * @return
3039 */
3040bool Medium::isHostDrive() const
3041{
3042 return m->hostDrive;
3043}
3044
3045/**
3046 * Internal method to return the medium's full location. Must have caller + locking!
3047 * @return
3048 */
3049const Utf8Str& Medium::getLocationFull() const
3050{
3051 return m->strLocationFull;
3052}
3053
3054/**
3055 * Internal method to return the medium's format string. Must have caller + locking!
3056 * @return
3057 */
3058const Utf8Str& Medium::getFormat() const
3059{
3060 return m->strFormat;
3061}
3062
3063/**
3064 * Internal method to return the medium's format object. Must have caller + locking!
3065 * @return
3066 */
3067const ComObjPtr<MediumFormat>& Medium::getMediumFormat() const
3068{
3069 return m->formatObj;
3070}
3071
3072/**
3073 * Internal method that returns true if the medium is represented by a file on the host disk
3074 * (and not iSCSI or something).
3075 * @return
3076 */
3077bool Medium::isMediumFormatFile() const
3078{
3079 if ( m->formatObj
3080 && (m->formatObj->getCapabilities() & MediumFormatCapabilities_File)
3081 )
3082 return true;
3083 return false;
3084}
3085
3086/**
3087 * Internal method to return the medium's size. Must have caller + locking!
3088 * @return
3089 */
3090uint64_t Medium::getSize() const
3091{
3092 return m->size;
3093}
3094
3095/**
3096 * Returns the medium device type. Must have caller + locking!
3097 * @return
3098 */
3099DeviceType_T Medium::getDeviceType() const
3100{
3101 return m->devType;
3102}
3103
3104/**
3105 * Returns the medium type. Must have caller + locking!
3106 * @return
3107 */
3108MediumType_T Medium::getType() const
3109{
3110 return m->type;
3111}
3112
3113/**
3114 * Returns a short version of the location attribute.
3115 *
3116 * @note Must be called from under this object's read or write lock.
3117 */
3118Utf8Str Medium::getName()
3119{
3120 Utf8Str name = RTPathFilename(m->strLocationFull.c_str());
3121 return name;
3122}
3123
3124/**
3125 * This adds the given UUID to the list of media registries in which this
3126 * medium should be registered. The UUID can either be a machine UUID,
3127 * to add a machine registry, or the global registry UUID as returned by
3128 * VirtualBox::getGlobalRegistryId().
3129 *
3130 * Note that for hard disks, this method does nothing if the medium is
3131 * already in another registry to avoid having hard disks in more than
3132 * one registry, which causes trouble with keeping diff images in sync.
3133 * See getFirstRegistryMachineId() for details.
3134 *
3135 * If fRecurse == true, then the media tree lock must be held for reading.
3136 *
3137 * @param id
3138 * @param fRecurse If true, recurses into child media to make sure the whole tree has registries in sync.
3139 * @return true if the registry was added; false if the given id was already on the list.
3140 */
3141bool Medium::addRegistry(const Guid& id, bool fRecurse)
3142{
3143 AutoCaller autoCaller(this);
3144 if (FAILED(autoCaller.rc()))
3145 return false;
3146 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3147
3148 bool fAdd = true;
3149
3150 // hard disks cannot be in more than one registry
3151 if ( m->devType == DeviceType_HardDisk
3152 && m->llRegistryIDs.size() > 0)
3153 fAdd = false;
3154
3155 // no need to add the UUID twice
3156 if (fAdd)
3157 {
3158 for (GuidList::const_iterator it = m->llRegistryIDs.begin();
3159 it != m->llRegistryIDs.end();
3160 ++it)
3161 {
3162 if ((*it) == id)
3163 {
3164 fAdd = false;
3165 break;
3166 }
3167 }
3168 }
3169
3170 if (fAdd)
3171 m->llRegistryIDs.push_back(id);
3172
3173 if (fRecurse)
3174 {
3175 // Get private list of children and release medium lock straight away.
3176 MediaList llChildren(m->llChildren);
3177 alock.release();
3178
3179 for (MediaList::iterator it = llChildren.begin();
3180 it != llChildren.end();
3181 ++it)
3182 {
3183 Medium *pChild = *it;
3184 fAdd |= pChild->addRegistry(id, true);
3185 }
3186 }
3187
3188 return fAdd;
3189}
3190
3191/**
3192 * Removes the given UUID from the list of media registry UUIDs. Returns true
3193 * if found or false if not.
3194 *
3195 * If fRecurse == true, then the media tree lock must be held for reading.
3196 *
3197 * @param id
3198 * @param fRecurse If true, recurses into child media to make sure the whole tree has registries in sync.
3199 * @return
3200 */
3201bool Medium::removeRegistry(const Guid& id, bool fRecurse)
3202{
3203 AutoCaller autoCaller(this);
3204 if (FAILED(autoCaller.rc()))
3205 return false;
3206 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3207
3208 bool fRemove = false;
3209
3210 for (GuidList::iterator it = m->llRegistryIDs.begin();
3211 it != m->llRegistryIDs.end();
3212 ++it)
3213 {
3214 if ((*it) == id)
3215 {
3216 m->llRegistryIDs.erase(it);
3217 fRemove = true;
3218 break;
3219 }
3220 }
3221
3222 if (fRecurse)
3223 {
3224 // Get private list of children and release medium lock straight away.
3225 MediaList llChildren(m->llChildren);
3226 alock.release();
3227
3228 for (MediaList::iterator it = llChildren.begin();
3229 it != llChildren.end();
3230 ++it)
3231 {
3232 Medium *pChild = *it;
3233 fRemove |= pChild->removeRegistry(id, true);
3234 }
3235 }
3236
3237 return fRemove;
3238}
3239
3240/**
3241 * Returns true if id is in the list of media registries for this medium.
3242 *
3243 * Must have caller + read locking!
3244 *
3245 * @param id
3246 * @return
3247 */
3248bool Medium::isInRegistry(const Guid& id)
3249{
3250 for (GuidList::const_iterator it = m->llRegistryIDs.begin();
3251 it != m->llRegistryIDs.end();
3252 ++it)
3253 {
3254 if (*it == id)
3255 return true;
3256 }
3257
3258 return false;
3259}
3260
3261/**
3262 * Internal method to return the medium's first registry machine (i.e. the machine in whose
3263 * machine XML this medium is listed).
3264 *
3265 * Every attached medium must now (4.0) reside in at least one media registry, which is identified
3266 * by a UUID. This is either a machine UUID if the machine is from 4.0 or newer, in which case
3267 * machines have their own media registries, or it is the pseudo-UUID of the VirtualBox
3268 * object if the machine is old and still needs the global registry in VirtualBox.xml.
3269 *
3270 * By definition, hard disks may only be in one media registry, in which all its children
3271 * will be stored as well. Otherwise we run into problems with having keep multiple registries
3272 * in sync. (This is the "cloned VM" case in which VM1 may link to the disks of VM2; in this
3273 * case, only VM2's registry is used for the disk in question.)
3274 *
3275 * If there is no medium registry, particularly if the medium has not been attached yet, this
3276 * does not modify uuid and returns false.
3277 *
3278 * ISOs and RAWs, by contrast, can be in more than one repository to make things easier for
3279 * the user.
3280 *
3281 * Must have caller + locking!
3282 *
3283 * @param uuid Receives first registry machine UUID, if available.
3284 * @return true if uuid was set.
3285 */
3286bool Medium::getFirstRegistryMachineId(Guid &uuid) const
3287{
3288 if (m->llRegistryIDs.size())
3289 {
3290 uuid = m->llRegistryIDs.front();
3291 return true;
3292 }
3293 return false;
3294}
3295
3296/**
3297 * Adds all the IDs of the registries in which this medium is registered to the given list
3298 * of UUIDs, but only if they are not on the list yet.
3299 * @param llRegistryIDs
3300 */
3301HRESULT Medium::addToRegistryIDList(GuidList &llRegistryIDs)
3302{
3303 AutoCaller autoCaller(this);
3304 if (FAILED(autoCaller.rc())) return false;
3305
3306 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3307
3308 for (GuidList::const_iterator it = m->llRegistryIDs.begin();
3309 it != m->llRegistryIDs.end();
3310 ++it)
3311 {
3312 VirtualBox::addGuidToListUniquely(llRegistryIDs, *it);
3313 }
3314
3315 return S_OK;
3316}
3317
3318/**
3319 * Adds the given machine and optionally the snapshot to the list of the objects
3320 * this medium is attached to.
3321 *
3322 * @param aMachineId Machine ID.
3323 * @param aSnapshotId Snapshot ID; when non-empty, adds a snapshot attachment.
3324 */
3325HRESULT Medium::addBackReference(const Guid &aMachineId,
3326 const Guid &aSnapshotId /*= Guid::Empty*/)
3327{
3328 AssertReturn(!aMachineId.isEmpty(), E_FAIL);
3329
3330 LogFlowThisFunc(("ENTER, aMachineId: {%RTuuid}, aSnapshotId: {%RTuuid}\n", aMachineId.raw(), aSnapshotId.raw()));
3331
3332 AutoCaller autoCaller(this);
3333 AssertComRCReturnRC(autoCaller.rc());
3334
3335 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3336
3337 switch (m->state)
3338 {
3339 case MediumState_Created:
3340 case MediumState_Inaccessible:
3341 case MediumState_LockedRead:
3342 case MediumState_LockedWrite:
3343 break;
3344
3345 default:
3346 return setStateError();
3347 }
3348
3349 if (m->numCreateDiffTasks > 0)
3350 return setError(VBOX_E_OBJECT_IN_USE,
3351 tr("Cannot attach medium '%s' {%RTuuid}: %u differencing child media are being created"),
3352 m->strLocationFull.c_str(),
3353 m->id.raw(),
3354 m->numCreateDiffTasks);
3355
3356 BackRefList::iterator it = std::find_if(m->backRefs.begin(),
3357 m->backRefs.end(),
3358 BackRef::EqualsTo(aMachineId));
3359 if (it == m->backRefs.end())
3360 {
3361 BackRef ref(aMachineId, aSnapshotId);
3362 m->backRefs.push_back(ref);
3363
3364 return S_OK;
3365 }
3366
3367 // if the caller has not supplied a snapshot ID, then we're attaching
3368 // to a machine a medium which represents the machine's current state,
3369 // so set the flag
3370 if (aSnapshotId.isEmpty())
3371 {
3372 /* sanity: no duplicate attachments */
3373 if (it->fInCurState)
3374 return setError(VBOX_E_OBJECT_IN_USE,
3375 tr("Cannot attach medium '%s' {%RTuuid}: medium is already associated with the current state of machine uuid {%RTuuid}!"),
3376 m->strLocationFull.c_str(),
3377 m->id.raw(),
3378 aMachineId.raw());
3379 it->fInCurState = true;
3380
3381 return S_OK;
3382 }
3383
3384 // otherwise: a snapshot medium is being attached
3385
3386 /* sanity: no duplicate attachments */
3387 for (GuidList::const_iterator jt = it->llSnapshotIds.begin();
3388 jt != it->llSnapshotIds.end();
3389 ++jt)
3390 {
3391 const Guid &idOldSnapshot = *jt;
3392
3393 if (idOldSnapshot == aSnapshotId)
3394 {
3395#ifdef DEBUG
3396 dumpBackRefs();
3397#endif
3398 return setError(VBOX_E_OBJECT_IN_USE,
3399 tr("Cannot attach medium '%s' {%RTuuid} from snapshot '%RTuuid': medium is already in use by this snapshot!"),
3400 m->strLocationFull.c_str(),
3401 m->id.raw(),
3402 aSnapshotId.raw());
3403 }
3404 }
3405
3406 it->llSnapshotIds.push_back(aSnapshotId);
3407 it->fInCurState = false;
3408
3409 LogFlowThisFuncLeave();
3410
3411 return S_OK;
3412}
3413
3414/**
3415 * Removes the given machine and optionally the snapshot from the list of the
3416 * objects this medium is attached to.
3417 *
3418 * @param aMachineId Machine ID.
3419 * @param aSnapshotId Snapshot ID; when non-empty, removes the snapshot
3420 * attachment.
3421 */
3422HRESULT Medium::removeBackReference(const Guid &aMachineId,
3423 const Guid &aSnapshotId /*= Guid::Empty*/)
3424{
3425 AssertReturn(!aMachineId.isEmpty(), E_FAIL);
3426
3427 AutoCaller autoCaller(this);
3428 AssertComRCReturnRC(autoCaller.rc());
3429
3430 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3431
3432 BackRefList::iterator it =
3433 std::find_if(m->backRefs.begin(), m->backRefs.end(),
3434 BackRef::EqualsTo(aMachineId));
3435 AssertReturn(it != m->backRefs.end(), E_FAIL);
3436
3437 if (aSnapshotId.isEmpty())
3438 {
3439 /* remove the current state attachment */
3440 it->fInCurState = false;
3441 }
3442 else
3443 {
3444 /* remove the snapshot attachment */
3445 GuidList::iterator jt = std::find(it->llSnapshotIds.begin(),
3446 it->llSnapshotIds.end(),
3447 aSnapshotId);
3448
3449 AssertReturn(jt != it->llSnapshotIds.end(), E_FAIL);
3450 it->llSnapshotIds.erase(jt);
3451 }
3452
3453 /* if the backref becomes empty, remove it */
3454 if (it->fInCurState == false && it->llSnapshotIds.size() == 0)
3455 m->backRefs.erase(it);
3456
3457 return S_OK;
3458}
3459
3460/**
3461 * Internal method to return the medium's list of backrefs. Must have caller + locking!
3462 * @return
3463 */
3464const Guid* Medium::getFirstMachineBackrefId() const
3465{
3466 if (!m->backRefs.size())
3467 return NULL;
3468
3469 return &m->backRefs.front().machineId;
3470}
3471
3472/**
3473 * Internal method which returns a machine that either this medium or one of its children
3474 * is attached to. This is used for finding a replacement media registry when an existing
3475 * media registry is about to be deleted in VirtualBox::unregisterMachine().
3476 *
3477 * Must have caller + locking, *and* caller must hold the media tree lock!
3478 * @return
3479 */
3480const Guid* Medium::getAnyMachineBackref() const
3481{
3482 if (m->backRefs.size())
3483 return &m->backRefs.front().machineId;
3484
3485 for (MediaList::iterator it = m->llChildren.begin();
3486 it != m->llChildren.end();
3487 ++it)
3488 {
3489 Medium *pChild = *it;
3490 // recurse for this child
3491 const Guid* puuid;
3492 if ((puuid = pChild->getAnyMachineBackref()))
3493 return puuid;
3494 }
3495
3496 return NULL;
3497}
3498
3499const Guid* Medium::getFirstMachineBackrefSnapshotId() const
3500{
3501 if (!m->backRefs.size())
3502 return NULL;
3503
3504 const BackRef &ref = m->backRefs.front();
3505 if (!ref.llSnapshotIds.size())
3506 return NULL;
3507
3508 return &ref.llSnapshotIds.front();
3509}
3510
3511size_t Medium::getMachineBackRefCount() const
3512{
3513 return m->backRefs.size();
3514}
3515
3516#ifdef DEBUG
3517/**
3518 * Debugging helper that gets called after VirtualBox initialization that writes all
3519 * machine backreferences to the debug log.
3520 */
3521void Medium::dumpBackRefs()
3522{
3523 AutoCaller autoCaller(this);
3524 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3525
3526 LogFlowThisFunc(("Dumping backrefs for medium '%s':\n", m->strLocationFull.c_str()));
3527
3528 for (BackRefList::iterator it2 = m->backRefs.begin();
3529 it2 != m->backRefs.end();
3530 ++it2)
3531 {
3532 const BackRef &ref = *it2;
3533 LogFlowThisFunc((" Backref from machine {%RTuuid} (fInCurState: %d)\n", ref.machineId.raw(), ref.fInCurState));
3534
3535 for (GuidList::const_iterator jt2 = it2->llSnapshotIds.begin();
3536 jt2 != it2->llSnapshotIds.end();
3537 ++jt2)
3538 {
3539 const Guid &id = *jt2;
3540 LogFlowThisFunc((" Backref from snapshot {%RTuuid}\n", id.raw()));
3541 }
3542 }
3543}
3544#endif
3545
3546/**
3547 * Checks if the given change of \a aOldPath to \a aNewPath affects the location
3548 * of this media and updates it if necessary to reflect the new location.
3549 *
3550 * @param aOldPath Old path (full).
3551 * @param aNewPath New path (full).
3552 *
3553 * @note Locks this object for writing.
3554 */
3555HRESULT Medium::updatePath(const Utf8Str &strOldPath, const Utf8Str &strNewPath)
3556{
3557 AssertReturn(!strOldPath.isEmpty(), E_FAIL);
3558 AssertReturn(!strNewPath.isEmpty(), E_FAIL);
3559
3560 AutoCaller autoCaller(this);
3561 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3562
3563 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3564
3565 LogFlowThisFunc(("locationFull.before='%s'\n", m->strLocationFull.c_str()));
3566
3567 const char *pcszMediumPath = m->strLocationFull.c_str();
3568
3569 if (RTPathStartsWith(pcszMediumPath, strOldPath.c_str()))
3570 {
3571 Utf8Str newPath(strNewPath);
3572 newPath.append(pcszMediumPath + strOldPath.length());
3573 unconst(m->strLocationFull) = newPath;
3574
3575 LogFlowThisFunc(("locationFull.after='%s'\n", m->strLocationFull.c_str()));
3576 }
3577
3578 return S_OK;
3579}
3580
3581/**
3582 * Returns the base medium of the media chain this medium is part of.
3583 *
3584 * The base medium is found by walking up the parent-child relationship axis.
3585 * If the medium doesn't have a parent (i.e. it's a base medium), it
3586 * returns itself in response to this method.
3587 *
3588 * @param aLevel Where to store the number of ancestors of this medium
3589 * (zero for the base), may be @c NULL.
3590 *
3591 * @note Locks medium tree for reading.
3592 */
3593ComObjPtr<Medium> Medium::getBase(uint32_t *aLevel /*= NULL*/)
3594{
3595 ComObjPtr<Medium> pBase;
3596 uint32_t level;
3597
3598 AutoCaller autoCaller(this);
3599 AssertReturn(autoCaller.isOk(), pBase);
3600
3601 /* we access mParent */
3602 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3603
3604 pBase = this;
3605 level = 0;
3606
3607 if (m->pParent)
3608 {
3609 for (;;)
3610 {
3611 AutoCaller baseCaller(pBase);
3612 AssertReturn(baseCaller.isOk(), pBase);
3613
3614 if (pBase->m->pParent.isNull())
3615 break;
3616
3617 pBase = pBase->m->pParent;
3618 ++level;
3619 }
3620 }
3621
3622 if (aLevel != NULL)
3623 *aLevel = level;
3624
3625 return pBase;
3626}
3627
3628/**
3629 * Returns @c true if this medium cannot be modified because it has
3630 * dependents (children) or is part of the snapshot. Related to the medium
3631 * type and posterity, not to the current media state.
3632 *
3633 * @note Locks this object and medium tree for reading.
3634 */
3635bool Medium::isReadOnly()
3636{
3637 AutoCaller autoCaller(this);
3638 AssertComRCReturn(autoCaller.rc(), false);
3639
3640 /* we access children */
3641 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3642
3643 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3644
3645 switch (m->type)
3646 {
3647 case MediumType_Normal:
3648 {
3649 if (getChildren().size() != 0)
3650 return true;
3651
3652 for (BackRefList::const_iterator it = m->backRefs.begin();
3653 it != m->backRefs.end(); ++it)
3654 if (it->llSnapshotIds.size() != 0)
3655 return true;
3656
3657 if (m->variant & MediumVariant_VmdkStreamOptimized)
3658 return true;
3659
3660 return false;
3661 }
3662 case MediumType_Immutable:
3663 case MediumType_MultiAttach:
3664 return true;
3665 case MediumType_Writethrough:
3666 case MediumType_Shareable:
3667 case MediumType_Readonly: /* explicit readonly media has no diffs */
3668 return false;
3669 default:
3670 break;
3671 }
3672
3673 AssertFailedReturn(false);
3674}
3675
3676/**
3677 * Internal method to return the medium's size. Must have caller + locking!
3678 * @return
3679 */
3680void Medium::updateId(const Guid &id)
3681{
3682 unconst(m->id) = id;
3683}
3684
3685/**
3686 * Saves medium data by appending a new child node to the given
3687 * parent XML settings node.
3688 *
3689 * @param data Settings struct to be updated.
3690 * @param strHardDiskFolder Folder for which paths should be relative.
3691 *
3692 * @note Locks this object, medium tree and children for reading.
3693 */
3694HRESULT Medium::saveSettings(settings::Medium &data,
3695 const Utf8Str &strHardDiskFolder)
3696{
3697 AutoCaller autoCaller(this);
3698 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3699
3700 /* we access mParent */
3701 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3702
3703 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3704
3705 data.uuid = m->id;
3706
3707 // make path relative if needed
3708 if ( !strHardDiskFolder.isEmpty()
3709 && RTPathStartsWith(m->strLocationFull.c_str(), strHardDiskFolder.c_str())
3710 )
3711 data.strLocation = m->strLocationFull.substr(strHardDiskFolder.length() + 1);
3712 else
3713 data.strLocation = m->strLocationFull;
3714 data.strFormat = m->strFormat;
3715
3716 /* optional, only for diffs, default is false */
3717 if (m->pParent)
3718 data.fAutoReset = m->autoReset;
3719 else
3720 data.fAutoReset = false;
3721
3722 /* optional */
3723 data.strDescription = m->strDescription;
3724
3725 /* optional properties */
3726 data.properties.clear();
3727 for (settings::StringsMap::const_iterator it = m->mapProperties.begin();
3728 it != m->mapProperties.end();
3729 ++it)
3730 {
3731 /* only save properties that have non-default values */
3732 if (!it->second.isEmpty())
3733 {
3734 const Utf8Str &name = it->first;
3735 const Utf8Str &value = it->second;
3736 data.properties[name] = value;
3737 }
3738 }
3739
3740 /* only for base media */
3741 if (m->pParent.isNull())
3742 data.hdType = m->type;
3743
3744 /* save all children */
3745 for (MediaList::const_iterator it = getChildren().begin();
3746 it != getChildren().end();
3747 ++it)
3748 {
3749 settings::Medium med;
3750 HRESULT rc = (*it)->saveSettings(med, strHardDiskFolder);
3751 AssertComRCReturnRC(rc);
3752 data.llChildren.push_back(med);
3753 }
3754
3755 return S_OK;
3756}
3757
3758/**
3759 * Constructs a medium lock list for this medium. The lock is not taken.
3760 *
3761 * @note Caller must lock the medium tree for writing.
3762 *
3763 * @param fFailIfInaccessible If true, this fails with an error if a medium is inaccessible. If false,
3764 * inaccessible media are silently skipped and not locked (i.e. their state remains "Inaccessible");
3765 * this is necessary for a VM's removable media VM startup for which we do not want to fail.
3766 * @param fMediumLockWrite Whether to associate a write lock with this medium.
3767 * @param pToBeParent Medium which will become the parent of this medium.
3768 * @param mediumLockList Where to store the resulting list.
3769 */
3770HRESULT Medium::createMediumLockList(bool fFailIfInaccessible,
3771 bool fMediumLockWrite,
3772 Medium *pToBeParent,
3773 MediumLockList &mediumLockList)
3774{
3775 // Medium::queryInfo needs write lock
3776 Assert(m->pVirtualBox->getMediaTreeLockHandle().isWriteLockOnCurrentThread());
3777
3778 AutoCaller autoCaller(this);
3779 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3780
3781 HRESULT rc = S_OK;
3782
3783 /* paranoid sanity checking if the medium has a to-be parent medium */
3784 if (pToBeParent)
3785 {
3786 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3787 ComAssertRet(getParent().isNull(), E_FAIL);
3788 ComAssertRet(getChildren().size() == 0, E_FAIL);
3789 }
3790
3791 ErrorInfoKeeper eik;
3792 MultiResult mrc(S_OK);
3793
3794 ComObjPtr<Medium> pMedium = this;
3795 while (!pMedium.isNull())
3796 {
3797 // need write lock for queryInfo if medium is inaccessible
3798 AutoWriteLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
3799
3800 /* Accessibility check must be first, otherwise locking interferes
3801 * with getting the medium state. Lock lists are not created for
3802 * fun, and thus getting the medium status is no luxury. */
3803 MediumState_T mediumState = pMedium->getState();
3804 if (mediumState == MediumState_Inaccessible)
3805 {
3806 rc = pMedium->queryInfo(false /* fSetImageId */, false /* fSetParentId */);
3807 if (FAILED(rc)) return rc;
3808
3809 mediumState = pMedium->getState();
3810 if (mediumState == MediumState_Inaccessible)
3811 {
3812 // ignore inaccessible ISO media and silently return S_OK,
3813 // otherwise VM startup (esp. restore) may fail without good reason
3814 if (!fFailIfInaccessible)
3815 return S_OK;
3816
3817 // otherwise report an error
3818 Bstr error;
3819 rc = pMedium->COMGETTER(LastAccessError)(error.asOutParam());
3820 if (FAILED(rc)) return rc;
3821
3822 /* collect multiple errors */
3823 eik.restore();
3824 Assert(!error.isEmpty());
3825 mrc = setError(E_FAIL,
3826 "%ls",
3827 error.raw());
3828 // error message will be something like
3829 // "Could not open the medium ... VD: error VERR_FILE_NOT_FOUND opening image file ... (VERR_FILE_NOT_FOUND).
3830 eik.fetch();
3831 }
3832 }
3833
3834 if (pMedium == this)
3835 mediumLockList.Prepend(pMedium, fMediumLockWrite);
3836 else
3837 mediumLockList.Prepend(pMedium, false);
3838
3839 pMedium = pMedium->getParent();
3840 if (pMedium.isNull() && pToBeParent)
3841 {
3842 pMedium = pToBeParent;
3843 pToBeParent = NULL;
3844 }
3845 }
3846
3847 return mrc;
3848}
3849
3850/**
3851 * Creates a new differencing storage unit using the format of the given target
3852 * medium and the location. Note that @c aTarget must be NotCreated.
3853 *
3854 * The @a aMediumLockList parameter contains the associated medium lock list,
3855 * which must be in locked state. If @a aWait is @c true then the caller is
3856 * responsible for unlocking.
3857 *
3858 * If @a aProgress is not NULL but the object it points to is @c null then a
3859 * new progress object will be created and assigned to @a *aProgress on
3860 * success, otherwise the existing progress object is used. If @a aProgress is
3861 * NULL, then no progress object is created/used at all.
3862 *
3863 * When @a aWait is @c false, this method will create a thread to perform the
3864 * create operation asynchronously and will return immediately. Otherwise, it
3865 * will perform the operation on the calling thread and will not return to the
3866 * caller until the operation is completed. Note that @a aProgress cannot be
3867 * NULL when @a aWait is @c false (this method will assert in this case).
3868 *
3869 * @param aTarget Target medium.
3870 * @param aVariant Precise medium variant to create.
3871 * @param aMediumLockList List of media which should be locked.
3872 * @param aProgress Where to find/store a Progress object to track
3873 * operation completion.
3874 * @param aWait @c true if this method should block instead of
3875 * creating an asynchronous thread.
3876 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs that will receive the registry IDs that need saving.
3877 * This only works in "wait" mode; otherwise saveRegistries is called automatically by the thread that
3878 * was created, and this parameter is ignored.
3879 *
3880 * @note Locks this object and @a aTarget for writing.
3881 */
3882HRESULT Medium::createDiffStorage(ComObjPtr<Medium> &aTarget,
3883 MediumVariant_T aVariant,
3884 MediumLockList *aMediumLockList,
3885 ComObjPtr<Progress> *aProgress,
3886 bool aWait,
3887 GuidList *pllRegistriesThatNeedSaving)
3888{
3889 AssertReturn(!aTarget.isNull(), E_FAIL);
3890 AssertReturn(aMediumLockList, E_FAIL);
3891 AssertReturn(aProgress != NULL || aWait == true, E_FAIL);
3892
3893 AutoCaller autoCaller(this);
3894 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3895
3896 AutoCaller targetCaller(aTarget);
3897 if (FAILED(targetCaller.rc())) return targetCaller.rc();
3898
3899 HRESULT rc = S_OK;
3900 ComObjPtr<Progress> pProgress;
3901 Medium::Task *pTask = NULL;
3902
3903 try
3904 {
3905 AutoMultiWriteLock2 alock(this, aTarget COMMA_LOCKVAL_SRC_POS);
3906
3907 ComAssertThrow( m->type != MediumType_Writethrough
3908 && m->type != MediumType_Shareable
3909 && m->type != MediumType_Readonly, E_FAIL);
3910 ComAssertThrow(m->state == MediumState_LockedRead, E_FAIL);
3911
3912 if (aTarget->m->state != MediumState_NotCreated)
3913 throw aTarget->setStateError();
3914
3915 /* Check that the medium is not attached to the current state of
3916 * any VM referring to it. */
3917 for (BackRefList::const_iterator it = m->backRefs.begin();
3918 it != m->backRefs.end();
3919 ++it)
3920 {
3921 if (it->fInCurState)
3922 {
3923 /* Note: when a VM snapshot is being taken, all normal media
3924 * attached to the VM in the current state will be, as an
3925 * exception, also associated with the snapshot which is about
3926 * to create (see SnapshotMachine::init()) before deassociating
3927 * them from the current state (which takes place only on
3928 * success in Machine::fixupHardDisks()), so that the size of
3929 * snapshotIds will be 1 in this case. The extra condition is
3930 * used to filter out this legal situation. */
3931 if (it->llSnapshotIds.size() == 0)
3932 throw setError(VBOX_E_INVALID_OBJECT_STATE,
3933 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"),
3934 m->strLocationFull.c_str(), it->machineId.raw());
3935
3936 Assert(it->llSnapshotIds.size() == 1);
3937 }
3938 }
3939
3940 if (aProgress != NULL)
3941 {
3942 /* use the existing progress object... */
3943 pProgress = *aProgress;
3944
3945 /* ...but create a new one if it is null */
3946 if (pProgress.isNull())
3947 {
3948 pProgress.createObject();
3949 rc = pProgress->init(m->pVirtualBox,
3950 static_cast<IMedium*>(this),
3951 BstrFmt(tr("Creating differencing medium storage unit '%s'"), aTarget->m->strLocationFull.c_str()).raw(),
3952 TRUE /* aCancelable */);
3953 if (FAILED(rc))
3954 throw rc;
3955 }
3956 }
3957
3958 /* setup task object to carry out the operation sync/async */
3959 pTask = new Medium::CreateDiffTask(this, pProgress, aTarget, aVariant,
3960 aMediumLockList,
3961 aWait /* fKeepMediumLockList */);
3962 rc = pTask->rc();
3963 AssertComRC(rc);
3964 if (FAILED(rc))
3965 throw rc;
3966
3967 /* register a task (it will deregister itself when done) */
3968 ++m->numCreateDiffTasks;
3969 Assert(m->numCreateDiffTasks != 0); /* overflow? */
3970
3971 aTarget->m->state = MediumState_Creating;
3972 }
3973 catch (HRESULT aRC) { rc = aRC; }
3974
3975 if (SUCCEEDED(rc))
3976 {
3977 if (aWait)
3978 rc = runNow(pTask, pllRegistriesThatNeedSaving);
3979 else
3980 rc = startThread(pTask);
3981
3982 if (SUCCEEDED(rc) && aProgress != NULL)
3983 *aProgress = pProgress;
3984 }
3985 else if (pTask != NULL)
3986 delete pTask;
3987
3988 return rc;
3989}
3990
3991/**
3992 * Returns a preferred format for differencing media.
3993 */
3994Utf8Str Medium::getPreferredDiffFormat()
3995{
3996 AutoCaller autoCaller(this);
3997 AssertComRCReturn(autoCaller.rc(), Utf8Str::Empty);
3998
3999 /* check that our own format supports diffs */
4000 if (!(m->formatObj->getCapabilities() & MediumFormatCapabilities_Differencing))
4001 {
4002 /* use the default format if not */
4003 Utf8Str tmp;
4004 m->pVirtualBox->getDefaultHardDiskFormat(tmp);
4005 return tmp;
4006 }
4007
4008 /* m->strFormat is const, no need to lock */
4009 return m->strFormat;
4010}
4011
4012/**
4013 * Implementation for the public Medium::Close() with the exception of calling
4014 * VirtualBox::saveRegistries(), in case someone wants to call this for several
4015 * media.
4016 *
4017 * After this returns with success, uninit() has been called on the medium, and
4018 * the object is no longer usable ("not ready" state).
4019 *
4020 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs that will receive the registry IDs that need saving.
4021 * @param autoCaller AutoCaller instance which must have been created on the caller's stack for this medium. This gets released here
4022 * upon which the Medium instance gets uninitialized.
4023 * @return
4024 */
4025HRESULT Medium::close(GuidList *pllRegistriesThatNeedSaving,
4026 AutoCaller &autoCaller)
4027{
4028 // we're accessing parent/child and backrefs, so lock the tree first, then ourselves
4029 AutoMultiWriteLock2 multilock(&m->pVirtualBox->getMediaTreeLockHandle(),
4030 this->lockHandle()
4031 COMMA_LOCKVAL_SRC_POS);
4032
4033 LogFlowFunc(("ENTER for %s\n", getLocationFull().c_str()));
4034
4035 bool wasCreated = true;
4036
4037 switch (m->state)
4038 {
4039 case MediumState_NotCreated:
4040 wasCreated = false;
4041 break;
4042 case MediumState_Created:
4043 case MediumState_Inaccessible:
4044 break;
4045 default:
4046 return setStateError();
4047 }
4048
4049 if (m->backRefs.size() != 0)
4050 return setError(VBOX_E_OBJECT_IN_USE,
4051 tr("Medium '%s' cannot be closed because it is still attached to %d virtual machines"),
4052 m->strLocationFull.c_str(), m->backRefs.size());
4053
4054 // perform extra media-dependent close checks
4055 HRESULT rc = canClose();
4056 if (FAILED(rc)) return rc;
4057
4058 if (wasCreated)
4059 {
4060 // remove from the list of known media before performing actual
4061 // uninitialization (to keep the media registry consistent on
4062 // failure to do so)
4063 rc = unregisterWithVirtualBox(pllRegistriesThatNeedSaving);
4064 if (FAILED(rc)) return rc;
4065 }
4066
4067 // leave the AutoCaller, as otherwise uninit() will simply hang
4068 autoCaller.release();
4069
4070 // Keep the locks held until after uninit, as otherwise the consistency
4071 // of the medium tree cannot be guaranteed.
4072 uninit();
4073
4074 LogFlowFuncLeave();
4075
4076 return rc;
4077}
4078
4079/**
4080 * Deletes the medium storage unit.
4081 *
4082 * If @a aProgress is not NULL but the object it points to is @c null then a new
4083 * progress object will be created and assigned to @a *aProgress on success,
4084 * otherwise the existing progress object is used. If Progress is NULL, then no
4085 * progress object is created/used at all.
4086 *
4087 * When @a aWait is @c false, this method will create a thread to perform the
4088 * delete operation asynchronously and will return immediately. Otherwise, it
4089 * will perform the operation on the calling thread and will not return to the
4090 * caller until the operation is completed. Note that @a aProgress cannot be
4091 * NULL when @a aWait is @c false (this method will assert in this case).
4092 *
4093 * @param aProgress Where to find/store a Progress object to track operation
4094 * completion.
4095 * @param aWait @c true if this method should block instead of creating
4096 * an asynchronous thread.
4097 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
4098 * by this function if the caller should invoke VirtualBox::saveRegistries() because the global settings have changed.
4099 * This only works in "wait" mode; otherwise saveRegistries gets called automatically by the thread that was created,
4100 * and this parameter is ignored.
4101 *
4102 * @note Locks mVirtualBox and this object for writing. Locks medium tree for
4103 * writing.
4104 */
4105HRESULT Medium::deleteStorage(ComObjPtr<Progress> *aProgress,
4106 bool aWait,
4107 GuidList *pllRegistriesThatNeedSaving)
4108{
4109 AssertReturn(aProgress != NULL || aWait == true, E_FAIL);
4110
4111 AutoCaller autoCaller(this);
4112 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4113
4114 HRESULT rc = S_OK;
4115 ComObjPtr<Progress> pProgress;
4116 Medium::Task *pTask = NULL;
4117
4118 try
4119 {
4120 /* we're accessing the media tree, and canClose() needs it too */
4121 AutoMultiWriteLock2 multilock(&m->pVirtualBox->getMediaTreeLockHandle(),
4122 this->lockHandle()
4123 COMMA_LOCKVAL_SRC_POS);
4124 LogFlowThisFunc(("aWait=%RTbool locationFull=%s\n", aWait, getLocationFull().c_str() ));
4125
4126 if ( !(m->formatObj->getCapabilities() & ( MediumFormatCapabilities_CreateDynamic
4127 | MediumFormatCapabilities_CreateFixed)))
4128 throw setError(VBOX_E_NOT_SUPPORTED,
4129 tr("Medium format '%s' does not support storage deletion"),
4130 m->strFormat.c_str());
4131
4132 /* Note that we are fine with Inaccessible state too: a) for symmetry
4133 * with create calls and b) because it doesn't really harm to try, if
4134 * it is really inaccessible, the delete operation will fail anyway.
4135 * Accepting Inaccessible state is especially important because all
4136 * registered media are initially Inaccessible upon VBoxSVC startup
4137 * until COMGETTER(RefreshState) is called. Accept Deleting state
4138 * because some callers need to put the medium in this state early
4139 * to prevent races. */
4140 switch (m->state)
4141 {
4142 case MediumState_Created:
4143 case MediumState_Deleting:
4144 case MediumState_Inaccessible:
4145 break;
4146 default:
4147 throw setStateError();
4148 }
4149
4150 if (m->backRefs.size() != 0)
4151 {
4152 Utf8Str strMachines;
4153 for (BackRefList::const_iterator it = m->backRefs.begin();
4154 it != m->backRefs.end();
4155 ++it)
4156 {
4157 const BackRef &b = *it;
4158 if (strMachines.length())
4159 strMachines.append(", ");
4160 strMachines.append(b.machineId.toString().c_str());
4161 }
4162#ifdef DEBUG
4163 dumpBackRefs();
4164#endif
4165 throw setError(VBOX_E_OBJECT_IN_USE,
4166 tr("Cannot delete storage: medium '%s' is still attached to the following %d virtual machine(s): %s"),
4167 m->strLocationFull.c_str(),
4168 m->backRefs.size(),
4169 strMachines.c_str());
4170 }
4171
4172 rc = canClose();
4173 if (FAILED(rc))
4174 throw rc;
4175
4176 /* go to Deleting state, so that the medium is not actually locked */
4177 if (m->state != MediumState_Deleting)
4178 {
4179 rc = markForDeletion();
4180 if (FAILED(rc))
4181 throw rc;
4182 }
4183
4184 /* Build the medium lock list. */
4185 MediumLockList *pMediumLockList(new MediumLockList());
4186 rc = createMediumLockList(true /* fFailIfInaccessible */,
4187 true /* fMediumLockWrite */,
4188 NULL,
4189 *pMediumLockList);
4190 if (FAILED(rc))
4191 {
4192 delete pMediumLockList;
4193 throw rc;
4194 }
4195
4196 rc = pMediumLockList->Lock();
4197 if (FAILED(rc))
4198 {
4199 delete pMediumLockList;
4200 throw setError(rc,
4201 tr("Failed to lock media when deleting '%s'"),
4202 getLocationFull().c_str());
4203 }
4204
4205 /* try to remove from the list of known media before performing
4206 * actual deletion (we favor the consistency of the media registry
4207 * which would have been broken if unregisterWithVirtualBox() failed
4208 * after we successfully deleted the storage) */
4209 rc = unregisterWithVirtualBox(pllRegistriesThatNeedSaving);
4210 if (FAILED(rc))
4211 throw rc;
4212 // no longer need lock
4213 multilock.release();
4214
4215 if (aProgress != NULL)
4216 {
4217 /* use the existing progress object... */
4218 pProgress = *aProgress;
4219
4220 /* ...but create a new one if it is null */
4221 if (pProgress.isNull())
4222 {
4223 pProgress.createObject();
4224 rc = pProgress->init(m->pVirtualBox,
4225 static_cast<IMedium*>(this),
4226 BstrFmt(tr("Deleting medium storage unit '%s'"), m->strLocationFull.c_str()).raw(),
4227 FALSE /* aCancelable */);
4228 if (FAILED(rc))
4229 throw rc;
4230 }
4231 }
4232
4233 /* setup task object to carry out the operation sync/async */
4234 pTask = new Medium::DeleteTask(this, pProgress, pMediumLockList);
4235 rc = pTask->rc();
4236 AssertComRC(rc);
4237 if (FAILED(rc))
4238 throw rc;
4239 }
4240 catch (HRESULT aRC) { rc = aRC; }
4241
4242 if (SUCCEEDED(rc))
4243 {
4244 if (aWait)
4245 rc = runNow(pTask, NULL /* pfNeedsGlobalSaveSettings*/);
4246 else
4247 rc = startThread(pTask);
4248
4249 if (SUCCEEDED(rc) && aProgress != NULL)
4250 *aProgress = pProgress;
4251
4252 }
4253 else
4254 {
4255 if (pTask)
4256 delete pTask;
4257
4258 /* Undo deleting state if necessary. */
4259 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4260 /* Make sure that any error signalled by unmarkForDeletion() is not
4261 * ending up in the error list (if the caller uses MultiResult). It
4262 * usually is spurious, as in most cases the medium hasn't been marked
4263 * for deletion when the error was thrown above. */
4264 ErrorInfoKeeper eik;
4265 unmarkForDeletion();
4266 }
4267
4268 return rc;
4269}
4270
4271/**
4272 * Mark a medium for deletion.
4273 *
4274 * @note Caller must hold the write lock on this medium!
4275 */
4276HRESULT Medium::markForDeletion()
4277{
4278 ComAssertRet(this->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
4279 switch (m->state)
4280 {
4281 case MediumState_Created:
4282 case MediumState_Inaccessible:
4283 m->preLockState = m->state;
4284 m->state = MediumState_Deleting;
4285 return S_OK;
4286 default:
4287 return setStateError();
4288 }
4289}
4290
4291/**
4292 * Removes the "mark for deletion".
4293 *
4294 * @note Caller must hold the write lock on this medium!
4295 */
4296HRESULT Medium::unmarkForDeletion()
4297{
4298 ComAssertRet(this->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
4299 switch (m->state)
4300 {
4301 case MediumState_Deleting:
4302 m->state = m->preLockState;
4303 return S_OK;
4304 default:
4305 return setStateError();
4306 }
4307}
4308
4309/**
4310 * Mark a medium for deletion which is in locked state.
4311 *
4312 * @note Caller must hold the write lock on this medium!
4313 */
4314HRESULT Medium::markLockedForDeletion()
4315{
4316 ComAssertRet(this->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
4317 if ( ( m->state == MediumState_LockedRead
4318 || m->state == MediumState_LockedWrite)
4319 && m->preLockState == MediumState_Created)
4320 {
4321 m->preLockState = MediumState_Deleting;
4322 return S_OK;
4323 }
4324 else
4325 return setStateError();
4326}
4327
4328/**
4329 * Removes the "mark for deletion" for a medium in locked state.
4330 *
4331 * @note Caller must hold the write lock on this medium!
4332 */
4333HRESULT Medium::unmarkLockedForDeletion()
4334{
4335 ComAssertRet(this->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
4336 if ( ( m->state == MediumState_LockedRead
4337 || m->state == MediumState_LockedWrite)
4338 && m->preLockState == MediumState_Deleting)
4339 {
4340 m->preLockState = MediumState_Created;
4341 return S_OK;
4342 }
4343 else
4344 return setStateError();
4345}
4346
4347/**
4348 * Prepares this (source) medium, target medium and all intermediate media
4349 * for the merge operation.
4350 *
4351 * This method is to be called prior to calling the #mergeTo() to perform
4352 * necessary consistency checks and place involved media to appropriate
4353 * states. If #mergeTo() is not called or fails, the state modifications
4354 * performed by this method must be undone by #cancelMergeTo().
4355 *
4356 * See #mergeTo() for more information about merging.
4357 *
4358 * @param pTarget Target medium.
4359 * @param aMachineId Allowed machine attachment. NULL means do not check.
4360 * @param aSnapshotId Allowed snapshot attachment. NULL or empty UUID means
4361 * do not check.
4362 * @param fLockMedia Flag whether to lock the medium lock list or not.
4363 * If set to false and the medium lock list locking fails
4364 * later you must call #cancelMergeTo().
4365 * @param fMergeForward Resulting merge direction (out).
4366 * @param pParentForTarget New parent for target medium after merge (out).
4367 * @param aChildrenToReparent List of children of the source which will have
4368 * to be reparented to the target after merge (out).
4369 * @param aMediumLockList Medium locking information (out).
4370 *
4371 * @note Locks medium tree for reading. Locks this object, aTarget and all
4372 * intermediate media for writing.
4373 */
4374HRESULT Medium::prepareMergeTo(const ComObjPtr<Medium> &pTarget,
4375 const Guid *aMachineId,
4376 const Guid *aSnapshotId,
4377 bool fLockMedia,
4378 bool &fMergeForward,
4379 ComObjPtr<Medium> &pParentForTarget,
4380 MediaList &aChildrenToReparent,
4381 MediumLockList * &aMediumLockList)
4382{
4383 AssertReturn(pTarget != NULL, E_FAIL);
4384 AssertReturn(pTarget != this, E_FAIL);
4385
4386 AutoCaller autoCaller(this);
4387 AssertComRCReturnRC(autoCaller.rc());
4388
4389 AutoCaller targetCaller(pTarget);
4390 AssertComRCReturnRC(targetCaller.rc());
4391
4392 HRESULT rc = S_OK;
4393 fMergeForward = false;
4394 pParentForTarget.setNull();
4395 aChildrenToReparent.clear();
4396 Assert(aMediumLockList == NULL);
4397 aMediumLockList = NULL;
4398
4399 try
4400 {
4401 // locking: we need the tree lock first because we access parent pointers
4402 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4403
4404 /* more sanity checking and figuring out the merge direction */
4405 ComObjPtr<Medium> pMedium = getParent();
4406 while (!pMedium.isNull() && pMedium != pTarget)
4407 pMedium = pMedium->getParent();
4408 if (pMedium == pTarget)
4409 fMergeForward = false;
4410 else
4411 {
4412 pMedium = pTarget->getParent();
4413 while (!pMedium.isNull() && pMedium != this)
4414 pMedium = pMedium->getParent();
4415 if (pMedium == this)
4416 fMergeForward = true;
4417 else
4418 {
4419 Utf8Str tgtLoc;
4420 {
4421 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
4422 tgtLoc = pTarget->getLocationFull();
4423 }
4424
4425 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4426 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4427 tr("Media '%s' and '%s' are unrelated"),
4428 m->strLocationFull.c_str(), tgtLoc.c_str());
4429 }
4430 }
4431
4432 /* Build the lock list. */
4433 aMediumLockList = new MediumLockList();
4434 if (fMergeForward)
4435 rc = pTarget->createMediumLockList(true /* fFailIfInaccessible */,
4436 true /* fMediumLockWrite */,
4437 NULL,
4438 *aMediumLockList);
4439 else
4440 rc = createMediumLockList(true /* fFailIfInaccessible */,
4441 false /* fMediumLockWrite */,
4442 NULL,
4443 *aMediumLockList);
4444 if (FAILED(rc))
4445 throw rc;
4446
4447 /* Sanity checking, must be after lock list creation as it depends on
4448 * valid medium states. The medium objects must be accessible. Only
4449 * do this if immediate locking is requested, otherwise it fails when
4450 * we construct a medium lock list for an already running VM. Snapshot
4451 * deletion uses this to simplify its life. */
4452 if (fLockMedia)
4453 {
4454 {
4455 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4456 if (m->state != MediumState_Created)
4457 throw setStateError();
4458 }
4459 {
4460 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
4461 if (pTarget->m->state != MediumState_Created)
4462 throw pTarget->setStateError();
4463 }
4464 }
4465
4466 /* check medium attachment and other sanity conditions */
4467 if (fMergeForward)
4468 {
4469 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4470 if (getChildren().size() > 1)
4471 {
4472 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4473 tr("Medium '%s' involved in the merge operation has more than one child medium (%d)"),
4474 m->strLocationFull.c_str(), getChildren().size());
4475 }
4476 /* One backreference is only allowed if the machine ID is not empty
4477 * and it matches the machine the medium is attached to (including
4478 * the snapshot ID if not empty). */
4479 if ( m->backRefs.size() != 0
4480 && ( !aMachineId
4481 || m->backRefs.size() != 1
4482 || aMachineId->isEmpty()
4483 || *getFirstMachineBackrefId() != *aMachineId
4484 || ( (!aSnapshotId || !aSnapshotId->isEmpty())
4485 && *getFirstMachineBackrefSnapshotId() != *aSnapshotId)))
4486 throw setError(VBOX_E_OBJECT_IN_USE,
4487 tr("Medium '%s' is attached to %d virtual machines"),
4488 m->strLocationFull.c_str(), m->backRefs.size());
4489 if (m->type == MediumType_Immutable)
4490 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4491 tr("Medium '%s' is immutable"),
4492 m->strLocationFull.c_str());
4493 if (m->type == MediumType_MultiAttach)
4494 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4495 tr("Medium '%s' is multi-attach"),
4496 m->strLocationFull.c_str());
4497 }
4498 else
4499 {
4500 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
4501 if (pTarget->getChildren().size() > 1)
4502 {
4503 throw setError(VBOX_E_OBJECT_IN_USE,
4504 tr("Medium '%s' involved in the merge operation has more than one child medium (%d)"),
4505 pTarget->m->strLocationFull.c_str(),
4506 pTarget->getChildren().size());
4507 }
4508 if (pTarget->m->type == MediumType_Immutable)
4509 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4510 tr("Medium '%s' is immutable"),
4511 pTarget->m->strLocationFull.c_str());
4512 if (pTarget->m->type == MediumType_MultiAttach)
4513 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4514 tr("Medium '%s' is multi-attach"),
4515 pTarget->m->strLocationFull.c_str());
4516 }
4517 ComObjPtr<Medium> pLast(fMergeForward ? (Medium *)pTarget : this);
4518 ComObjPtr<Medium> pLastIntermediate = pLast->getParent();
4519 for (pLast = pLastIntermediate;
4520 !pLast.isNull() && pLast != pTarget && pLast != this;
4521 pLast = pLast->getParent())
4522 {
4523 AutoReadLock alock(pLast COMMA_LOCKVAL_SRC_POS);
4524 if (pLast->getChildren().size() > 1)
4525 {
4526 throw setError(VBOX_E_OBJECT_IN_USE,
4527 tr("Medium '%s' involved in the merge operation has more than one child medium (%d)"),
4528 pLast->m->strLocationFull.c_str(),
4529 pLast->getChildren().size());
4530 }
4531 if (pLast->m->backRefs.size() != 0)
4532 throw setError(VBOX_E_OBJECT_IN_USE,
4533 tr("Medium '%s' is attached to %d virtual machines"),
4534 pLast->m->strLocationFull.c_str(),
4535 pLast->m->backRefs.size());
4536
4537 }
4538
4539 /* Update medium states appropriately */
4540 if (m->state == MediumState_Created)
4541 {
4542 rc = markForDeletion();
4543 if (FAILED(rc))
4544 throw rc;
4545 }
4546 else
4547 {
4548 if (fLockMedia)
4549 throw setStateError();
4550 else if ( m->state == MediumState_LockedWrite
4551 || m->state == MediumState_LockedRead)
4552 {
4553 /* Either mark it for deletion in locked state or allow
4554 * others to have done so. */
4555 if (m->preLockState == MediumState_Created)
4556 markLockedForDeletion();
4557 else if (m->preLockState != MediumState_Deleting)
4558 throw setStateError();
4559 }
4560 else
4561 throw setStateError();
4562 }
4563
4564 if (fMergeForward)
4565 {
4566 /* we will need parent to reparent target */
4567 pParentForTarget = m->pParent;
4568 }
4569 else
4570 {
4571 /* we will need to reparent children of the source */
4572 for (MediaList::const_iterator it = getChildren().begin();
4573 it != getChildren().end();
4574 ++it)
4575 {
4576 pMedium = *it;
4577 if (fLockMedia)
4578 {
4579 rc = pMedium->LockWrite(NULL);
4580 if (FAILED(rc))
4581 throw rc;
4582 }
4583
4584 aChildrenToReparent.push_back(pMedium);
4585 }
4586 }
4587 for (pLast = pLastIntermediate;
4588 !pLast.isNull() && pLast != pTarget && pLast != this;
4589 pLast = pLast->getParent())
4590 {
4591 AutoWriteLock alock(pLast COMMA_LOCKVAL_SRC_POS);
4592 if (pLast->m->state == MediumState_Created)
4593 {
4594 rc = pLast->markForDeletion();
4595 if (FAILED(rc))
4596 throw rc;
4597 }
4598 else
4599 throw pLast->setStateError();
4600 }
4601
4602 /* Tweak the lock list in the backward merge case, as the target
4603 * isn't marked to be locked for writing yet. */
4604 if (!fMergeForward)
4605 {
4606 MediumLockList::Base::iterator lockListBegin =
4607 aMediumLockList->GetBegin();
4608 MediumLockList::Base::iterator lockListEnd =
4609 aMediumLockList->GetEnd();
4610 lockListEnd--;
4611 for (MediumLockList::Base::iterator it = lockListBegin;
4612 it != lockListEnd;
4613 ++it)
4614 {
4615 MediumLock &mediumLock = *it;
4616 if (mediumLock.GetMedium() == pTarget)
4617 {
4618 HRESULT rc2 = mediumLock.UpdateLock(true);
4619 AssertComRC(rc2);
4620 break;
4621 }
4622 }
4623 }
4624
4625 if (fLockMedia)
4626 {
4627 rc = aMediumLockList->Lock();
4628 if (FAILED(rc))
4629 {
4630 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
4631 throw setError(rc,
4632 tr("Failed to lock media when merging to '%s'"),
4633 pTarget->getLocationFull().c_str());
4634 }
4635 }
4636 }
4637 catch (HRESULT aRC) { rc = aRC; }
4638
4639 if (FAILED(rc))
4640 {
4641 delete aMediumLockList;
4642 aMediumLockList = NULL;
4643 }
4644
4645 return rc;
4646}
4647
4648/**
4649 * Merges this medium to the specified medium which must be either its
4650 * direct ancestor or descendant.
4651 *
4652 * Given this medium is SOURCE and the specified medium is TARGET, we will
4653 * get two variants of the merge operation:
4654 *
4655 * forward merge
4656 * ------------------------->
4657 * [Extra] <- SOURCE <- Intermediate <- TARGET
4658 * Any Del Del LockWr
4659 *
4660 *
4661 * backward merge
4662 * <-------------------------
4663 * TARGET <- Intermediate <- SOURCE <- [Extra]
4664 * LockWr Del Del LockWr
4665 *
4666 * Each diagram shows the involved media on the media chain where
4667 * SOURCE and TARGET belong. Under each medium there is a state value which
4668 * the medium must have at a time of the mergeTo() call.
4669 *
4670 * The media in the square braces may be absent (e.g. when the forward
4671 * operation takes place and SOURCE is the base medium, or when the backward
4672 * merge operation takes place and TARGET is the last child in the chain) but if
4673 * they present they are involved too as shown.
4674 *
4675 * Neither the source medium nor intermediate media may be attached to
4676 * any VM directly or in the snapshot, otherwise this method will assert.
4677 *
4678 * The #prepareMergeTo() method must be called prior to this method to place all
4679 * involved to necessary states and perform other consistency checks.
4680 *
4681 * If @a aWait is @c true then this method will perform the operation on the
4682 * calling thread and will not return to the caller until the operation is
4683 * completed. When this method succeeds, all intermediate medium objects in
4684 * the chain will be uninitialized, the state of the target medium (and all
4685 * involved extra media) will be restored. @a aMediumLockList will not be
4686 * deleted, whether the operation is successful or not. The caller has to do
4687 * this if appropriate. Note that this (source) medium is not uninitialized
4688 * because of possible AutoCaller instances held by the caller of this method
4689 * on the current thread. It's therefore the responsibility of the caller to
4690 * call Medium::uninit() after releasing all callers.
4691 *
4692 * If @a aWait is @c false then this method will create a thread to perform the
4693 * operation asynchronously and will return immediately. If the operation
4694 * succeeds, the thread will uninitialize the source medium object and all
4695 * intermediate medium objects in the chain, reset the state of the target
4696 * medium (and all involved extra media) and delete @a aMediumLockList.
4697 * If the operation fails, the thread will only reset the states of all
4698 * involved media and delete @a aMediumLockList.
4699 *
4700 * When this method fails (regardless of the @a aWait mode), it is a caller's
4701 * responsibility to undo state changes and delete @a aMediumLockList using
4702 * #cancelMergeTo().
4703 *
4704 * If @a aProgress is not NULL but the object it points to is @c null then a new
4705 * progress object will be created and assigned to @a *aProgress on success,
4706 * otherwise the existing progress object is used. If Progress is NULL, then no
4707 * progress object is created/used at all. Note that @a aProgress cannot be
4708 * NULL when @a aWait is @c false (this method will assert in this case).
4709 *
4710 * @param pTarget Target medium.
4711 * @param fMergeForward Merge direction.
4712 * @param pParentForTarget New parent for target medium after merge.
4713 * @param aChildrenToReparent List of children of the source which will have
4714 * to be reparented to the target after merge.
4715 * @param aMediumLockList Medium locking information.
4716 * @param aProgress Where to find/store a Progress object to track operation
4717 * completion.
4718 * @param aWait @c true if this method should block instead of creating
4719 * an asynchronous thread.
4720 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
4721 * by this function if the caller should invoke VirtualBox::saveRegistries() because the global settings have changed.
4722 * This only works in "wait" mode; otherwise saveRegistries gets called automatically by the thread that was created,
4723 * and this parameter is ignored.
4724 *
4725 * @note Locks the tree lock for writing. Locks the media from the chain
4726 * for writing.
4727 */
4728HRESULT Medium::mergeTo(const ComObjPtr<Medium> &pTarget,
4729 bool fMergeForward,
4730 const ComObjPtr<Medium> &pParentForTarget,
4731 const MediaList &aChildrenToReparent,
4732 MediumLockList *aMediumLockList,
4733 ComObjPtr <Progress> *aProgress,
4734 bool aWait,
4735 GuidList *pllRegistriesThatNeedSaving)
4736{
4737 AssertReturn(pTarget != NULL, E_FAIL);
4738 AssertReturn(pTarget != this, E_FAIL);
4739 AssertReturn(aMediumLockList != NULL, E_FAIL);
4740 AssertReturn(aProgress != NULL || aWait == true, E_FAIL);
4741
4742 AutoCaller autoCaller(this);
4743 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4744
4745 AutoCaller targetCaller(pTarget);
4746 AssertComRCReturnRC(targetCaller.rc());
4747
4748 HRESULT rc = S_OK;
4749 ComObjPtr <Progress> pProgress;
4750 Medium::Task *pTask = NULL;
4751
4752 try
4753 {
4754 if (aProgress != NULL)
4755 {
4756 /* use the existing progress object... */
4757 pProgress = *aProgress;
4758
4759 /* ...but create a new one if it is null */
4760 if (pProgress.isNull())
4761 {
4762 Utf8Str tgtName;
4763 {
4764 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
4765 tgtName = pTarget->getName();
4766 }
4767
4768 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4769
4770 pProgress.createObject();
4771 rc = pProgress->init(m->pVirtualBox,
4772 static_cast<IMedium*>(this),
4773 BstrFmt(tr("Merging medium '%s' to '%s'"),
4774 getName().c_str(),
4775 tgtName.c_str()).raw(),
4776 TRUE /* aCancelable */);
4777 if (FAILED(rc))
4778 throw rc;
4779 }
4780 }
4781
4782 /* setup task object to carry out the operation sync/async */
4783 pTask = new Medium::MergeTask(this, pTarget, fMergeForward,
4784 pParentForTarget, aChildrenToReparent,
4785 pProgress, aMediumLockList,
4786 aWait /* fKeepMediumLockList */);
4787 rc = pTask->rc();
4788 AssertComRC(rc);
4789 if (FAILED(rc))
4790 throw rc;
4791 }
4792 catch (HRESULT aRC) { rc = aRC; }
4793
4794 if (SUCCEEDED(rc))
4795 {
4796 if (aWait)
4797 rc = runNow(pTask, pllRegistriesThatNeedSaving);
4798 else
4799 rc = startThread(pTask);
4800
4801 if (SUCCEEDED(rc) && aProgress != NULL)
4802 *aProgress = pProgress;
4803 }
4804 else if (pTask != NULL)
4805 delete pTask;
4806
4807 return rc;
4808}
4809
4810/**
4811 * Undoes what #prepareMergeTo() did. Must be called if #mergeTo() is not
4812 * called or fails. Frees memory occupied by @a aMediumLockList and unlocks
4813 * the medium objects in @a aChildrenToReparent.
4814 *
4815 * @param aChildrenToReparent List of children of the source which will have
4816 * to be reparented to the target after merge.
4817 * @param aMediumLockList Medium locking information.
4818 *
4819 * @note Locks the media from the chain for writing.
4820 */
4821void Medium::cancelMergeTo(const MediaList &aChildrenToReparent,
4822 MediumLockList *aMediumLockList)
4823{
4824 AutoCaller autoCaller(this);
4825 AssertComRCReturnVoid(autoCaller.rc());
4826
4827 AssertReturnVoid(aMediumLockList != NULL);
4828
4829 /* Revert media marked for deletion to previous state. */
4830 HRESULT rc;
4831 MediumLockList::Base::const_iterator mediumListBegin =
4832 aMediumLockList->GetBegin();
4833 MediumLockList::Base::const_iterator mediumListEnd =
4834 aMediumLockList->GetEnd();
4835 for (MediumLockList::Base::const_iterator it = mediumListBegin;
4836 it != mediumListEnd;
4837 ++it)
4838 {
4839 const MediumLock &mediumLock = *it;
4840 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
4841 AutoWriteLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
4842
4843 if (pMedium->m->state == MediumState_Deleting)
4844 {
4845 rc = pMedium->unmarkForDeletion();
4846 AssertComRC(rc);
4847 }
4848 }
4849
4850 /* the destructor will do the work */
4851 delete aMediumLockList;
4852
4853 /* unlock the children which had to be reparented */
4854 for (MediaList::const_iterator it = aChildrenToReparent.begin();
4855 it != aChildrenToReparent.end();
4856 ++it)
4857 {
4858 const ComObjPtr<Medium> &pMedium = *it;
4859
4860 AutoWriteLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
4861 pMedium->UnlockWrite(NULL);
4862 }
4863}
4864
4865/**
4866 * Fix the parent UUID of all children to point to this medium as their
4867 * parent.
4868 */
4869HRESULT Medium::fixParentUuidOfChildren(const MediaList &childrenToReparent)
4870{
4871 MediumLockList mediumLockList;
4872 HRESULT rc = createMediumLockList(true /* fFailIfInaccessible */,
4873 false /* fMediumLockWrite */,
4874 this,
4875 mediumLockList);
4876 AssertComRCReturnRC(rc);
4877
4878 try
4879 {
4880 PVBOXHDD hdd;
4881 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
4882 ComAssertRCThrow(vrc, E_FAIL);
4883
4884 try
4885 {
4886 MediumLockList::Base::iterator lockListBegin =
4887 mediumLockList.GetBegin();
4888 MediumLockList::Base::iterator lockListEnd =
4889 mediumLockList.GetEnd();
4890 for (MediumLockList::Base::iterator it = lockListBegin;
4891 it != lockListEnd;
4892 ++it)
4893 {
4894 MediumLock &mediumLock = *it;
4895 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
4896 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
4897
4898 // open the medium
4899 vrc = VDOpen(hdd,
4900 pMedium->m->strFormat.c_str(),
4901 pMedium->m->strLocationFull.c_str(),
4902 VD_OPEN_FLAGS_READONLY,
4903 pMedium->m->vdImageIfaces);
4904 if (RT_FAILURE(vrc))
4905 throw vrc;
4906 }
4907
4908 for (MediaList::const_iterator it = childrenToReparent.begin();
4909 it != childrenToReparent.end();
4910 ++it)
4911 {
4912 /* VD_OPEN_FLAGS_INFO since UUID is wrong yet */
4913 vrc = VDOpen(hdd,
4914 (*it)->m->strFormat.c_str(),
4915 (*it)->m->strLocationFull.c_str(),
4916 VD_OPEN_FLAGS_INFO,
4917 (*it)->m->vdImageIfaces);
4918 if (RT_FAILURE(vrc))
4919 throw vrc;
4920
4921 vrc = VDSetParentUuid(hdd, VD_LAST_IMAGE, m->id.raw());
4922 if (RT_FAILURE(vrc))
4923 throw vrc;
4924
4925 vrc = VDClose(hdd, false /* fDelete */);
4926 if (RT_FAILURE(vrc))
4927 throw vrc;
4928
4929 (*it)->UnlockWrite(NULL);
4930 }
4931 }
4932 catch (HRESULT aRC) { rc = aRC; }
4933 catch (int aVRC)
4934 {
4935 rc = setError(E_FAIL,
4936 tr("Could not update medium UUID references to parent '%s' (%s)"),
4937 m->strLocationFull.c_str(),
4938 vdError(aVRC).c_str());
4939 }
4940
4941 VDDestroy(hdd);
4942 }
4943 catch (HRESULT aRC) { rc = aRC; }
4944
4945 return rc;
4946}
4947
4948/**
4949 * Used by IAppliance to export disk images.
4950 *
4951 * @param aFilename Filename to create (UTF8).
4952 * @param aFormat Medium format for creating @a aFilename.
4953 * @param aVariant Which exact image format variant to use
4954 * for the destination image.
4955 * @param aVDImageIOCallbacks Pointer to the callback table for a
4956 * VDINTERFACEIO interface. May be NULL.
4957 * @param aVDImageIOUser Opaque data for the callbacks.
4958 * @param aProgress Progress object to use.
4959 * @return
4960 * @note The source format is defined by the Medium instance.
4961 */
4962HRESULT Medium::exportFile(const char *aFilename,
4963 const ComObjPtr<MediumFormat> &aFormat,
4964 MediumVariant_T aVariant,
4965 PVDINTERFACEIO aVDImageIOIf, void *aVDImageIOUser,
4966 const ComObjPtr<Progress> &aProgress)
4967{
4968 AssertPtrReturn(aFilename, E_INVALIDARG);
4969 AssertReturn(!aFormat.isNull(), E_INVALIDARG);
4970 AssertReturn(!aProgress.isNull(), E_INVALIDARG);
4971
4972 AutoCaller autoCaller(this);
4973 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4974
4975 HRESULT rc = S_OK;
4976 Medium::Task *pTask = NULL;
4977
4978 try
4979 {
4980 // locking: we need the tree lock first because we access parent pointers
4981 // and we need to write-lock the media involved
4982 AutoMultiWriteLock2 alock(&m->pVirtualBox->getMediaTreeLockHandle(),
4983 this->lockHandle() COMMA_LOCKVAL_SRC_POS);
4984
4985 /* Build the source lock list. */
4986 MediumLockList *pSourceMediumLockList(new MediumLockList());
4987 rc = createMediumLockList(true /* fFailIfInaccessible */,
4988 false /* fMediumLockWrite */,
4989 NULL,
4990 *pSourceMediumLockList);
4991 if (FAILED(rc))
4992 {
4993 delete pSourceMediumLockList;
4994 throw rc;
4995 }
4996
4997 rc = pSourceMediumLockList->Lock();
4998 if (FAILED(rc))
4999 {
5000 delete pSourceMediumLockList;
5001 throw setError(rc,
5002 tr("Failed to lock source media '%s'"),
5003 getLocationFull().c_str());
5004 }
5005
5006 /* setup task object to carry out the operation asynchronously */
5007 pTask = new Medium::ExportTask(this, aProgress, aFilename, aFormat,
5008 aVariant, aVDImageIOIf,
5009 aVDImageIOUser, pSourceMediumLockList);
5010 rc = pTask->rc();
5011 AssertComRC(rc);
5012 if (FAILED(rc))
5013 throw rc;
5014 }
5015 catch (HRESULT aRC) { rc = aRC; }
5016
5017 if (SUCCEEDED(rc))
5018 rc = startThread(pTask);
5019 else if (pTask != NULL)
5020 delete pTask;
5021
5022 return rc;
5023}
5024
5025/**
5026 * Used by IAppliance to import disk images.
5027 *
5028 * @param aFilename Filename to read (UTF8).
5029 * @param aFormat Medium format for reading @a aFilename.
5030 * @param aVariant Which exact image format variant to use
5031 * for the destination image.
5032 * @param aVDImageIOCallbacks Pointer to the callback table for a
5033 * VDINTERFACEIO interface. May be NULL.
5034 * @param aVDImageIOUser Opaque data for the callbacks.
5035 * @param aParent Parent medium. May be NULL.
5036 * @param aProgress Progress object to use.
5037 * @return
5038 * @note The destination format is defined by the Medium instance.
5039 */
5040HRESULT Medium::importFile(const char *aFilename,
5041 const ComObjPtr<MediumFormat> &aFormat,
5042 MediumVariant_T aVariant,
5043 PVDINTERFACEIO aVDImageIOIf, void *aVDImageIOUser,
5044 const ComObjPtr<Medium> &aParent,
5045 const ComObjPtr<Progress> &aProgress)
5046{
5047 AssertPtrReturn(aFilename, E_INVALIDARG);
5048 AssertReturn(!aFormat.isNull(), E_INVALIDARG);
5049 AssertReturn(!aProgress.isNull(), E_INVALIDARG);
5050
5051 AutoCaller autoCaller(this);
5052 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5053
5054 HRESULT rc = S_OK;
5055 Medium::Task *pTask = NULL;
5056
5057 try
5058 {
5059 // locking: we need the tree lock first because we access parent pointers
5060 // and we need to write-lock the media involved
5061 AutoMultiWriteLock3 alock(&m->pVirtualBox->getMediaTreeLockHandle(),
5062 this->lockHandle(),
5063 aParent->lockHandle() COMMA_LOCKVAL_SRC_POS);
5064
5065 if ( m->state != MediumState_NotCreated
5066 && m->state != MediumState_Created)
5067 throw setStateError();
5068
5069 /* Build the target lock list. */
5070 MediumLockList *pTargetMediumLockList(new MediumLockList());
5071 rc = createMediumLockList(true /* fFailIfInaccessible */,
5072 true /* fMediumLockWrite */,
5073 aParent,
5074 *pTargetMediumLockList);
5075 if (FAILED(rc))
5076 {
5077 delete pTargetMediumLockList;
5078 throw rc;
5079 }
5080
5081 rc = pTargetMediumLockList->Lock();
5082 if (FAILED(rc))
5083 {
5084 delete pTargetMediumLockList;
5085 throw setError(rc,
5086 tr("Failed to lock target media '%s'"),
5087 getLocationFull().c_str());
5088 }
5089
5090 /* setup task object to carry out the operation asynchronously */
5091 pTask = new Medium::ImportTask(this, aProgress, aFilename, aFormat,
5092 aVariant, aVDImageIOIf,
5093 aVDImageIOUser, aParent,
5094 pTargetMediumLockList);
5095 rc = pTask->rc();
5096 AssertComRC(rc);
5097 if (FAILED(rc))
5098 throw rc;
5099
5100 if (m->state == MediumState_NotCreated)
5101 m->state = MediumState_Creating;
5102 }
5103 catch (HRESULT aRC) { rc = aRC; }
5104
5105 if (SUCCEEDED(rc))
5106 rc = startThread(pTask);
5107 else if (pTask != NULL)
5108 delete pTask;
5109
5110 return rc;
5111}
5112
5113/**
5114 * Internal version of the public CloneTo API which allows to enable certain
5115 * optimizations to improve speed during VM cloning.
5116 *
5117 * @param aTarget Target medium
5118 * @param aVariant Which exact image format variant to use
5119 * for the destination image.
5120 * @param aParent Parent medium. May be NULL.
5121 * @param aProgress Progress object to use.
5122 * @param idxSrcImageSame The last image in the source chain which has the
5123 * same content as the given image in the destination
5124 * chain. Use UINT32_MAX to disable this optimization.
5125 * @param idxDstImageSame The last image in the destination chain which has the
5126 * same content as the given image in the source chain.
5127 * Use UINT32_MAX to disable this optimization.
5128 * @return
5129 */
5130HRESULT Medium::cloneToEx(const ComObjPtr<Medium> &aTarget, ULONG aVariant,
5131 const ComObjPtr<Medium> &aParent, IProgress **aProgress,
5132 uint32_t idxSrcImageSame, uint32_t idxDstImageSame)
5133{
5134 CheckComArgNotNull(aTarget);
5135 CheckComArgOutPointerValid(aProgress);
5136 ComAssertRet(aTarget != this, E_INVALIDARG);
5137
5138 AutoCaller autoCaller(this);
5139 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5140
5141 HRESULT rc = S_OK;
5142 ComObjPtr<Progress> pProgress;
5143 Medium::Task *pTask = NULL;
5144
5145 try
5146 {
5147 // locking: we need the tree lock first because we access parent pointers
5148 // and we need to write-lock the media involved
5149 AutoMultiWriteLock4 alock(&m->pVirtualBox->getMediaTreeLockHandle(),
5150 this->lockHandle(),
5151 aTarget->lockHandle(),
5152 aParent->lockHandle() COMMA_LOCKVAL_SRC_POS);
5153
5154 if ( aTarget->m->state != MediumState_NotCreated
5155 && aTarget->m->state != MediumState_Created)
5156 throw aTarget->setStateError();
5157
5158 /* Build the source lock list. */
5159 MediumLockList *pSourceMediumLockList(new MediumLockList());
5160 rc = createMediumLockList(true /* fFailIfInaccessible */,
5161 false /* fMediumLockWrite */,
5162 NULL,
5163 *pSourceMediumLockList);
5164 if (FAILED(rc))
5165 {
5166 delete pSourceMediumLockList;
5167 throw rc;
5168 }
5169
5170 /* Build the target lock list (including the to-be parent chain). */
5171 MediumLockList *pTargetMediumLockList(new MediumLockList());
5172 rc = aTarget->createMediumLockList(true /* fFailIfInaccessible */,
5173 true /* fMediumLockWrite */,
5174 aParent,
5175 *pTargetMediumLockList);
5176 if (FAILED(rc))
5177 {
5178 delete pSourceMediumLockList;
5179 delete pTargetMediumLockList;
5180 throw rc;
5181 }
5182
5183 rc = pSourceMediumLockList->Lock();
5184 if (FAILED(rc))
5185 {
5186 delete pSourceMediumLockList;
5187 delete pTargetMediumLockList;
5188 throw setError(rc,
5189 tr("Failed to lock source media '%s'"),
5190 getLocationFull().c_str());
5191 }
5192 rc = pTargetMediumLockList->Lock();
5193 if (FAILED(rc))
5194 {
5195 delete pSourceMediumLockList;
5196 delete pTargetMediumLockList;
5197 throw setError(rc,
5198 tr("Failed to lock target media '%s'"),
5199 aTarget->getLocationFull().c_str());
5200 }
5201
5202 pProgress.createObject();
5203 rc = pProgress->init(m->pVirtualBox,
5204 static_cast <IMedium *>(this),
5205 BstrFmt(tr("Creating clone medium '%s'"), aTarget->m->strLocationFull.c_str()).raw(),
5206 TRUE /* aCancelable */);
5207 if (FAILED(rc))
5208 {
5209 delete pSourceMediumLockList;
5210 delete pTargetMediumLockList;
5211 throw rc;
5212 }
5213
5214 /* setup task object to carry out the operation asynchronously */
5215 pTask = new Medium::CloneTask(this, pProgress, aTarget,
5216 (MediumVariant_T)aVariant,
5217 aParent, idxSrcImageSame,
5218 idxDstImageSame, pSourceMediumLockList,
5219 pTargetMediumLockList);
5220 rc = pTask->rc();
5221 AssertComRC(rc);
5222 if (FAILED(rc))
5223 throw rc;
5224
5225 if (aTarget->m->state == MediumState_NotCreated)
5226 aTarget->m->state = MediumState_Creating;
5227 }
5228 catch (HRESULT aRC) { rc = aRC; }
5229
5230 if (SUCCEEDED(rc))
5231 {
5232 rc = startThread(pTask);
5233
5234 if (SUCCEEDED(rc))
5235 pProgress.queryInterfaceTo(aProgress);
5236 }
5237 else if (pTask != NULL)
5238 delete pTask;
5239
5240 return rc;
5241}
5242
5243////////////////////////////////////////////////////////////////////////////////
5244//
5245// Private methods
5246//
5247////////////////////////////////////////////////////////////////////////////////
5248
5249/**
5250 * Queries information from the medium.
5251 *
5252 * As a result of this call, the accessibility state and data members such as
5253 * size and description will be updated with the current information.
5254 *
5255 * @note This method may block during a system I/O call that checks storage
5256 * accessibility.
5257 *
5258 * @note Caller must hold medium tree for writing.
5259 *
5260 * @note Locks mParent for reading. Locks this object for writing.
5261 *
5262 * @param fSetImageId Whether to reset the UUID contained in the image file to the UUID in the medium instance data (see SetIDs())
5263 * @param fSetParentId Whether to reset the parent UUID contained in the image file to the parent UUID in the medium instance data (see SetIDs())
5264 * @return
5265 */
5266HRESULT Medium::queryInfo(bool fSetImageId, bool fSetParentId)
5267{
5268 Assert(m->pVirtualBox->getMediaTreeLockHandle().isWriteLockOnCurrentThread());
5269 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5270
5271 if ( m->state != MediumState_Created
5272 && m->state != MediumState_Inaccessible
5273 && m->state != MediumState_LockedRead)
5274 return E_FAIL;
5275
5276 HRESULT rc = S_OK;
5277
5278 int vrc = VINF_SUCCESS;
5279
5280 /* check if a blocking queryInfo() call is in progress on some other thread,
5281 * and wait for it to finish if so instead of querying data ourselves */
5282 if (m->queryInfoRunning)
5283 {
5284 Assert( m->state == MediumState_LockedRead
5285 || m->state == MediumState_LockedWrite);
5286
5287 while (m->queryInfoRunning)
5288 {
5289 alock.leave();
5290 {
5291 AutoReadLock qlock(m->queryInfoSem COMMA_LOCKVAL_SRC_POS);
5292 }
5293 alock.enter();
5294 }
5295
5296 return S_OK;
5297 }
5298
5299 bool success = false;
5300 Utf8Str lastAccessError;
5301
5302 /* are we dealing with a new medium constructed using the existing
5303 * location? */
5304 bool isImport = m->id.isEmpty();
5305 unsigned uOpenFlags = VD_OPEN_FLAGS_INFO;
5306
5307 /* Note that we don't use VD_OPEN_FLAGS_READONLY when opening new
5308 * media because that would prevent necessary modifications
5309 * when opening media of some third-party formats for the first
5310 * time in VirtualBox (such as VMDK for which VDOpen() needs to
5311 * generate an UUID if it is missing) */
5312 if ( m->hddOpenMode == OpenReadOnly
5313 || m->type == MediumType_Readonly
5314 || (!isImport && !fSetImageId && !fSetParentId)
5315 )
5316 uOpenFlags |= VD_OPEN_FLAGS_READONLY;
5317
5318 /* Open shareable medium with the appropriate flags */
5319 if (m->type == MediumType_Shareable)
5320 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
5321
5322 /* Lock the medium, which makes the behavior much more consistent */
5323 if (uOpenFlags & (VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_SHAREABLE))
5324 rc = LockRead(NULL);
5325 else
5326 rc = LockWrite(NULL);
5327 if (FAILED(rc)) return rc;
5328
5329 /* Copies of the input state fields which are not read-only,
5330 * as we're dropping the lock. CAUTION: be extremely careful what
5331 * you do with the contents of this medium object, as you will
5332 * create races if there are concurrent changes. */
5333 Utf8Str format(m->strFormat);
5334 Utf8Str location(m->strLocationFull);
5335 ComObjPtr<MediumFormat> formatObj = m->formatObj;
5336
5337 /* "Output" values which can't be set because the lock isn't held
5338 * at the time the values are determined. */
5339 Guid mediumId = m->id;
5340 uint64_t mediumSize = 0;
5341 uint64_t mediumLogicalSize = 0;
5342
5343 /* Flag whether a base image has a non-zero parent UUID and thus
5344 * need repairing after it was closed again. */
5345 bool fRepairImageZeroParentUuid = false;
5346
5347 /* leave the object lock before a lengthy operation */
5348 m->queryInfoRunning = true;
5349 alock.leave();
5350 /* Note that taking the queryInfoSem after leaving the object lock above
5351 * can lead to short spinning of the loops waiting for queryInfo() to
5352 * complete. This is unavoidable since the other order causes a lock order
5353 * violation: here it would be requesting the object lock (at the beginning
5354 * of the method), then SemRW, and below the other way round. */
5355 AutoWriteLock qlock(m->queryInfoSem COMMA_LOCKVAL_SRC_POS);
5356
5357 try
5358 {
5359 /* skip accessibility checks for host drives */
5360 if (m->hostDrive)
5361 {
5362 success = true;
5363 throw S_OK;
5364 }
5365
5366 PVBOXHDD hdd;
5367 vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
5368 ComAssertRCThrow(vrc, E_FAIL);
5369
5370 try
5371 {
5372 /** @todo This kind of opening of media is assuming that diff
5373 * media can be opened as base media. Should be documented that
5374 * it must work for all medium format backends. */
5375 vrc = VDOpen(hdd,
5376 format.c_str(),
5377 location.c_str(),
5378 uOpenFlags,
5379 m->vdImageIfaces);
5380 if (RT_FAILURE(vrc))
5381 {
5382 lastAccessError = Utf8StrFmt(tr("Could not open the medium '%s'%s"),
5383 location.c_str(), vdError(vrc).c_str());
5384 throw S_OK;
5385 }
5386
5387 if (formatObj->getCapabilities() & MediumFormatCapabilities_Uuid)
5388 {
5389 /* Modify the UUIDs if necessary. The associated fields are
5390 * not modified by other code, so no need to copy. */
5391 if (fSetImageId)
5392 {
5393 vrc = VDSetUuid(hdd, 0, m->uuidImage.raw());
5394 ComAssertRCThrow(vrc, E_FAIL);
5395 mediumId = m->uuidImage;
5396 }
5397 if (fSetParentId)
5398 {
5399 vrc = VDSetParentUuid(hdd, 0, m->uuidParentImage.raw());
5400 ComAssertRCThrow(vrc, E_FAIL);
5401 }
5402 /* zap the information, these are no long-term members */
5403 unconst(m->uuidImage).clear();
5404 unconst(m->uuidParentImage).clear();
5405
5406 /* check the UUID */
5407 RTUUID uuid;
5408 vrc = VDGetUuid(hdd, 0, &uuid);
5409 ComAssertRCThrow(vrc, E_FAIL);
5410
5411 if (isImport)
5412 {
5413 mediumId = uuid;
5414
5415 if (mediumId.isEmpty() && (m->hddOpenMode == OpenReadOnly))
5416 // only when importing a VDMK that has no UUID, create one in memory
5417 mediumId.create();
5418 }
5419 else
5420 {
5421 Assert(!mediumId.isEmpty());
5422
5423 if (mediumId != uuid)
5424 {
5425 /** @todo r=klaus this always refers to VirtualBox.xml as the medium registry, even for new VMs */
5426 lastAccessError = Utf8StrFmt(
5427 tr("UUID {%RTuuid} of the medium '%s' does not match the value {%RTuuid} stored in the media registry ('%s')"),
5428 &uuid,
5429 location.c_str(),
5430 mediumId.raw(),
5431 m->pVirtualBox->settingsFilePath().c_str());
5432 throw S_OK;
5433 }
5434 }
5435 }
5436 else
5437 {
5438 /* the backend does not support storing UUIDs within the
5439 * underlying storage so use what we store in XML */
5440
5441 if (fSetImageId)
5442 {
5443 /* set the UUID if an API client wants to change it */
5444 mediumId = m->uuidImage;
5445 }
5446 else if (isImport)
5447 {
5448 /* generate an UUID for an imported UUID-less medium */
5449 mediumId.create();
5450 }
5451 }
5452
5453 /* get the medium variant */
5454 unsigned uImageFlags;
5455 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
5456 ComAssertRCThrow(vrc, E_FAIL);
5457 m->variant = (MediumVariant_T)uImageFlags;
5458
5459 /* check/get the parent uuid and update corresponding state */
5460 if (uImageFlags & VD_IMAGE_FLAGS_DIFF)
5461 {
5462 RTUUID parentId;
5463 vrc = VDGetParentUuid(hdd, 0, &parentId);
5464 ComAssertRCThrow(vrc, E_FAIL);
5465
5466 /* streamOptimized VMDK images are only accepted as base
5467 * images, as this allows automatic repair of OVF appliances.
5468 * Since such images don't support random writes they will not
5469 * be created for diff images. Only an overly smart user might
5470 * manually create this case. Too bad for him. */
5471 if ( isImport
5472 && !(uImageFlags & VD_VMDK_IMAGE_FLAGS_STREAM_OPTIMIZED))
5473 {
5474 /* the parent must be known to us. Note that we freely
5475 * call locking methods of mVirtualBox and parent, as all
5476 * relevant locks must be already held. There may be no
5477 * concurrent access to the just opened medium on other
5478 * threads yet (and init() will fail if this method reports
5479 * MediumState_Inaccessible) */
5480
5481 Guid id = parentId;
5482 ComObjPtr<Medium> pParent;
5483 rc = m->pVirtualBox->findHardDiskById(id, false /* aSetError */, &pParent);
5484 if (FAILED(rc))
5485 {
5486 lastAccessError = Utf8StrFmt(
5487 tr("Parent medium with UUID {%RTuuid} of the medium '%s' is not found in the media registry ('%s')"),
5488 &parentId, location.c_str(),
5489 m->pVirtualBox->settingsFilePath().c_str());
5490 throw S_OK;
5491 }
5492
5493 /* we set mParent & children() */
5494 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5495
5496 Assert(m->pParent.isNull());
5497 m->pParent = pParent;
5498 m->pParent->m->llChildren.push_back(this);
5499 }
5500 else
5501 {
5502 /* we access mParent */
5503 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5504
5505 /* check that parent UUIDs match. Note that there's no need
5506 * for the parent's AutoCaller (our lifetime is bound to
5507 * it) */
5508
5509 if (m->pParent.isNull())
5510 {
5511 /* Due to a bug in VDCopy() in VirtualBox 3.0.0-3.0.14
5512 * and 3.1.0-3.1.8 there are base images out there
5513 * which have a non-zero parent UUID. No point in
5514 * complaining about them, instead automatically
5515 * repair the problem. Later we can bring back the
5516 * error message, but we should wait until really
5517 * most users have repaired their images, either with
5518 * VBoxFixHdd or this way. */
5519#if 1
5520 fRepairImageZeroParentUuid = true;
5521#else /* 0 */
5522 lastAccessError = Utf8StrFmt(
5523 tr("Medium type of '%s' is differencing but it is not associated with any parent medium in the media registry ('%s')"),
5524 location.c_str(),
5525 m->pVirtualBox->settingsFilePath().c_str());
5526 throw S_OK;
5527#endif /* 0 */
5528 }
5529
5530 AutoReadLock parentLock(m->pParent COMMA_LOCKVAL_SRC_POS);
5531 if ( !fRepairImageZeroParentUuid
5532 && m->pParent->getState() != MediumState_Inaccessible
5533 && m->pParent->getId() != parentId)
5534 {
5535 /** @todo r=klaus this always refers to VirtualBox.xml as the medium registry, even for new VMs */
5536 lastAccessError = Utf8StrFmt(
5537 tr("Parent UUID {%RTuuid} of the medium '%s' does not match UUID {%RTuuid} of its parent medium stored in the media registry ('%s')"),
5538 &parentId, location.c_str(),
5539 m->pParent->getId().raw(),
5540 m->pVirtualBox->settingsFilePath().c_str());
5541 throw S_OK;
5542 }
5543
5544 /// @todo NEWMEDIA what to do if the parent is not
5545 /// accessible while the diff is? Probably nothing. The
5546 /// real code will detect the mismatch anyway.
5547 }
5548 }
5549
5550 mediumSize = VDGetFileSize(hdd, 0);
5551 mediumLogicalSize = VDGetSize(hdd, 0);
5552
5553 success = true;
5554 }
5555 catch (HRESULT aRC)
5556 {
5557 rc = aRC;
5558 }
5559
5560 VDDestroy(hdd);
5561 }
5562 catch (HRESULT aRC)
5563 {
5564 rc = aRC;
5565 }
5566
5567 alock.enter();
5568
5569 if (isImport || fSetImageId)
5570 unconst(m->id) = mediumId;
5571
5572 if (success)
5573 {
5574 m->size = mediumSize;
5575 m->logicalSize = mediumLogicalSize;
5576 m->strLastAccessError.setNull();
5577 }
5578 else
5579 {
5580 m->strLastAccessError = lastAccessError;
5581 LogWarningFunc(("'%s' is not accessible (error='%s', rc=%Rhrc, vrc=%Rrc)\n",
5582 location.c_str(), m->strLastAccessError.c_str(),
5583 rc, vrc));
5584 }
5585
5586 /* unblock anyone waiting for the queryInfo results */
5587 qlock.release();
5588 m->queryInfoRunning = false;
5589
5590 /* Set the proper state according to the result of the check */
5591 if (success)
5592 m->preLockState = MediumState_Created;
5593 else
5594 m->preLockState = MediumState_Inaccessible;
5595
5596 HRESULT rc2;
5597 if (uOpenFlags & (VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_SHAREABLE))
5598 rc2 = UnlockRead(NULL);
5599 else
5600 rc2 = UnlockWrite(NULL);
5601 if (SUCCEEDED(rc) && FAILED(rc2))
5602 rc = rc2;
5603 if (FAILED(rc)) return rc;
5604
5605 /* If this is a base image which incorrectly has a parent UUID set,
5606 * repair the image now by zeroing the parent UUID. This is only done
5607 * when we have structural information from a config file, on import
5608 * this is not possible. If someone would accidentally call openMedium
5609 * with a diff image before the base is registered this would destroy
5610 * the diff. Not acceptable. */
5611 if (fRepairImageZeroParentUuid)
5612 {
5613 rc = LockWrite(NULL);
5614 if (FAILED(rc)) return rc;
5615
5616 alock.leave();
5617
5618 try
5619 {
5620 PVBOXHDD hdd;
5621 vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
5622 ComAssertRCThrow(vrc, E_FAIL);
5623
5624 try
5625 {
5626 vrc = VDOpen(hdd,
5627 format.c_str(),
5628 location.c_str(),
5629 uOpenFlags & ~VD_OPEN_FLAGS_READONLY,
5630 m->vdImageIfaces);
5631 if (RT_FAILURE(vrc))
5632 throw S_OK;
5633
5634 RTUUID zeroParentUuid;
5635 RTUuidClear(&zeroParentUuid);
5636 vrc = VDSetParentUuid(hdd, 0, &zeroParentUuid);
5637 ComAssertRCThrow(vrc, E_FAIL);
5638 }
5639 catch (HRESULT aRC)
5640 {
5641 rc = aRC;
5642 }
5643
5644 VDDestroy(hdd);
5645 }
5646 catch (HRESULT aRC)
5647 {
5648 rc = aRC;
5649 }
5650
5651 alock.enter();
5652
5653 rc = UnlockWrite(NULL);
5654 if (SUCCEEDED(rc) && FAILED(rc2))
5655 rc = rc2;
5656 if (FAILED(rc)) return rc;
5657 }
5658
5659 return rc;
5660}
5661
5662/**
5663 * Performs extra checks if the medium can be closed and returns S_OK in
5664 * this case. Otherwise, returns a respective error message. Called by
5665 * Close() under the medium tree lock and the medium lock.
5666 *
5667 * @note Also reused by Medium::Reset().
5668 *
5669 * @note Caller must hold the media tree write lock!
5670 */
5671HRESULT Medium::canClose()
5672{
5673 Assert(m->pVirtualBox->getMediaTreeLockHandle().isWriteLockOnCurrentThread());
5674
5675 if (getChildren().size() != 0)
5676 return setError(VBOX_E_OBJECT_IN_USE,
5677 tr("Cannot close medium '%s' because it has %d child media"),
5678 m->strLocationFull.c_str(), getChildren().size());
5679
5680 return S_OK;
5681}
5682
5683/**
5684 * Unregisters this medium with mVirtualBox. Called by close() under the medium tree lock.
5685 *
5686 * This calls either VirtualBox::unregisterImage or VirtualBox::unregisterHardDisk depending
5687 * on the device type of this medium.
5688 *
5689 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs that will receive the registry IDs that need saving.
5690 *
5691 * @note Caller must have locked the media tree lock for writing!
5692 */
5693HRESULT Medium::unregisterWithVirtualBox(GuidList *pllRegistriesThatNeedSaving)
5694{
5695 /* Note that we need to de-associate ourselves from the parent to let
5696 * unregisterHardDisk() properly save the registry */
5697
5698 /* we modify mParent and access children */
5699 Assert(m->pVirtualBox->getMediaTreeLockHandle().isWriteLockOnCurrentThread());
5700
5701 Medium *pParentBackup = m->pParent;
5702 AssertReturn(getChildren().size() == 0, E_FAIL);
5703 if (m->pParent)
5704 deparent();
5705
5706 HRESULT rc = E_FAIL;
5707 switch (m->devType)
5708 {
5709 case DeviceType_DVD:
5710 case DeviceType_Floppy:
5711 rc = m->pVirtualBox->unregisterImage(this,
5712 m->devType,
5713 pllRegistriesThatNeedSaving);
5714 break;
5715
5716 case DeviceType_HardDisk:
5717 rc = m->pVirtualBox->unregisterHardDisk(this, pllRegistriesThatNeedSaving);
5718 break;
5719
5720 default:
5721 break;
5722 }
5723
5724 if (FAILED(rc))
5725 {
5726 if (pParentBackup)
5727 {
5728 // re-associate with the parent as we are still relatives in the registry
5729 m->pParent = pParentBackup;
5730 m->pParent->m->llChildren.push_back(this);
5731 }
5732 }
5733
5734 return rc;
5735}
5736
5737/**
5738 * Sets the extended error info according to the current media state.
5739 *
5740 * @note Must be called from under this object's write or read lock.
5741 */
5742HRESULT Medium::setStateError()
5743{
5744 HRESULT rc = E_FAIL;
5745
5746 switch (m->state)
5747 {
5748 case MediumState_NotCreated:
5749 {
5750 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5751 tr("Storage for the medium '%s' is not created"),
5752 m->strLocationFull.c_str());
5753 break;
5754 }
5755 case MediumState_Created:
5756 {
5757 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5758 tr("Storage for the medium '%s' is already created"),
5759 m->strLocationFull.c_str());
5760 break;
5761 }
5762 case MediumState_LockedRead:
5763 {
5764 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5765 tr("Medium '%s' is locked for reading by another task"),
5766 m->strLocationFull.c_str());
5767 break;
5768 }
5769 case MediumState_LockedWrite:
5770 {
5771 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5772 tr("Medium '%s' is locked for writing by another task"),
5773 m->strLocationFull.c_str());
5774 break;
5775 }
5776 case MediumState_Inaccessible:
5777 {
5778 /* be in sync with Console::powerUpThread() */
5779 if (!m->strLastAccessError.isEmpty())
5780 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5781 tr("Medium '%s' is not accessible. %s"),
5782 m->strLocationFull.c_str(), m->strLastAccessError.c_str());
5783 else
5784 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5785 tr("Medium '%s' is not accessible"),
5786 m->strLocationFull.c_str());
5787 break;
5788 }
5789 case MediumState_Creating:
5790 {
5791 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5792 tr("Storage for the medium '%s' is being created"),
5793 m->strLocationFull.c_str());
5794 break;
5795 }
5796 case MediumState_Deleting:
5797 {
5798 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5799 tr("Storage for the medium '%s' is being deleted"),
5800 m->strLocationFull.c_str());
5801 break;
5802 }
5803 default:
5804 {
5805 AssertFailed();
5806 break;
5807 }
5808 }
5809
5810 return rc;
5811}
5812
5813/**
5814 * Sets the value of m->strLocationFull. The given location must be a fully
5815 * qualified path; relative paths are not supported here.
5816 *
5817 * As a special exception, if the specified location is a file path that ends with '/'
5818 * then the file name part will be generated by this method automatically in the format
5819 * '{<uuid>}.<ext>' where <uuid> is a fresh UUID that this method will generate
5820 * and assign to this medium, and <ext> is the default extension for this
5821 * medium's storage format. Note that this procedure requires the media state to
5822 * be NotCreated and will return a failure otherwise.
5823 *
5824 * @param aLocation Location of the storage unit. If the location is a FS-path,
5825 * then it can be relative to the VirtualBox home directory.
5826 * @param aFormat Optional fallback format if it is an import and the format
5827 * cannot be determined.
5828 *
5829 * @note Must be called from under this object's write lock.
5830 */
5831HRESULT Medium::setLocation(const Utf8Str &aLocation,
5832 const Utf8Str &aFormat /* = Utf8Str::Empty */)
5833{
5834 AssertReturn(!aLocation.isEmpty(), E_FAIL);
5835
5836 AutoCaller autoCaller(this);
5837 AssertComRCReturnRC(autoCaller.rc());
5838
5839 /* formatObj may be null only when initializing from an existing path and
5840 * no format is known yet */
5841 AssertReturn( (!m->strFormat.isEmpty() && !m->formatObj.isNull())
5842 || ( autoCaller.state() == InInit
5843 && m->state != MediumState_NotCreated
5844 && m->id.isEmpty()
5845 && m->strFormat.isEmpty()
5846 && m->formatObj.isNull()),
5847 E_FAIL);
5848
5849 /* are we dealing with a new medium constructed using the existing
5850 * location? */
5851 bool isImport = m->strFormat.isEmpty();
5852
5853 if ( isImport
5854 || ( (m->formatObj->getCapabilities() & MediumFormatCapabilities_File)
5855 && !m->hostDrive))
5856 {
5857 Guid id;
5858
5859 Utf8Str locationFull(aLocation);
5860
5861 if (m->state == MediumState_NotCreated)
5862 {
5863 /* must be a file (formatObj must be already known) */
5864 Assert(m->formatObj->getCapabilities() & MediumFormatCapabilities_File);
5865
5866 if (RTPathFilename(aLocation.c_str()) == NULL)
5867 {
5868 /* no file name is given (either an empty string or ends with a
5869 * slash), generate a new UUID + file name if the state allows
5870 * this */
5871
5872 ComAssertMsgRet(!m->formatObj->getFileExtensions().empty(),
5873 ("Must be at least one extension if it is MediumFormatCapabilities_File\n"),
5874 E_FAIL);
5875
5876 Utf8Str strExt = m->formatObj->getFileExtensions().front();
5877 ComAssertMsgRet(!strExt.isEmpty(),
5878 ("Default extension must not be empty\n"),
5879 E_FAIL);
5880
5881 id.create();
5882
5883 locationFull = Utf8StrFmt("%s{%RTuuid}.%s",
5884 aLocation.c_str(), id.raw(), strExt.c_str());
5885 }
5886 }
5887
5888 // we must always have full paths now (if it refers to a file)
5889 if ( ( m->formatObj.isNull()
5890 || m->formatObj->getCapabilities() & MediumFormatCapabilities_File)
5891 && !RTPathStartsWithRoot(locationFull.c_str()))
5892 return setError(VBOX_E_FILE_ERROR,
5893 tr("The given path '%s' is not fully qualified"),
5894 locationFull.c_str());
5895
5896 /* detect the backend from the storage unit if importing */
5897 if (isImport)
5898 {
5899 VDTYPE enmType = VDTYPE_INVALID;
5900 char *backendName = NULL;
5901
5902 int vrc = VINF_SUCCESS;
5903
5904 /* is it a file? */
5905 {
5906 RTFILE file;
5907 vrc = RTFileOpen(&file, locationFull.c_str(), RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
5908 if (RT_SUCCESS(vrc))
5909 RTFileClose(file);
5910 }
5911 if (RT_SUCCESS(vrc))
5912 {
5913 vrc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
5914 locationFull.c_str(), &backendName, &enmType);
5915 }
5916 else if (vrc != VERR_FILE_NOT_FOUND && vrc != VERR_PATH_NOT_FOUND)
5917 {
5918 /* assume it's not a file, restore the original location */
5919 locationFull = aLocation;
5920 vrc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
5921 locationFull.c_str(), &backendName, &enmType);
5922 }
5923
5924 if (RT_FAILURE(vrc))
5925 {
5926 if (vrc == VERR_FILE_NOT_FOUND || vrc == VERR_PATH_NOT_FOUND)
5927 return setError(VBOX_E_FILE_ERROR,
5928 tr("Could not find file for the medium '%s' (%Rrc)"),
5929 locationFull.c_str(), vrc);
5930 else if (aFormat.isEmpty())
5931 return setError(VBOX_E_IPRT_ERROR,
5932 tr("Could not get the storage format of the medium '%s' (%Rrc)"),
5933 locationFull.c_str(), vrc);
5934 else
5935 {
5936 HRESULT rc = setFormat(aFormat);
5937 /* setFormat() must not fail since we've just used the backend so
5938 * the format object must be there */
5939 AssertComRCReturnRC(rc);
5940 }
5941 }
5942 else if ( enmType == VDTYPE_INVALID
5943 || m->devType != convertToDeviceType(enmType))
5944 {
5945 /*
5946 * The user tried to use a image as a device which is not supported
5947 * by the backend.
5948 */
5949 return setError(E_FAIL,
5950 tr("The medium '%s' can't be used as the requested device type"),
5951 locationFull.c_str());
5952 }
5953 else
5954 {
5955 ComAssertRet(backendName != NULL && *backendName != '\0', E_FAIL);
5956
5957 HRESULT rc = setFormat(backendName);
5958 RTStrFree(backendName);
5959
5960 /* setFormat() must not fail since we've just used the backend so
5961 * the format object must be there */
5962 AssertComRCReturnRC(rc);
5963 }
5964 }
5965
5966 m->strLocationFull = locationFull;
5967
5968 /* is it still a file? */
5969 if ( (m->formatObj->getCapabilities() & MediumFormatCapabilities_File)
5970 && (m->state == MediumState_NotCreated)
5971 )
5972 /* assign a new UUID (this UUID will be used when calling
5973 * VDCreateBase/VDCreateDiff as a wanted UUID). Note that we
5974 * also do that if we didn't generate it to make sure it is
5975 * either generated by us or reset to null */
5976 unconst(m->id) = id;
5977 }
5978 else
5979 m->strLocationFull = aLocation;
5980
5981 return S_OK;
5982}
5983
5984/**
5985 * Checks that the format ID is valid and sets it on success.
5986 *
5987 * Note that this method will caller-reference the format object on success!
5988 * This reference must be released somewhere to let the MediumFormat object be
5989 * uninitialized.
5990 *
5991 * @note Must be called from under this object's write lock.
5992 */
5993HRESULT Medium::setFormat(const Utf8Str &aFormat)
5994{
5995 /* get the format object first */
5996 {
5997 SystemProperties *pSysProps = m->pVirtualBox->getSystemProperties();
5998 AutoReadLock propsLock(pSysProps COMMA_LOCKVAL_SRC_POS);
5999
6000 unconst(m->formatObj) = pSysProps->mediumFormat(aFormat);
6001 if (m->formatObj.isNull())
6002 return setError(E_INVALIDARG,
6003 tr("Invalid medium storage format '%s'"),
6004 aFormat.c_str());
6005
6006 /* reference the format permanently to prevent its unexpected
6007 * uninitialization */
6008 HRESULT rc = m->formatObj->addCaller();
6009 AssertComRCReturnRC(rc);
6010
6011 /* get properties (preinsert them as keys in the map). Note that the
6012 * map doesn't grow over the object life time since the set of
6013 * properties is meant to be constant. */
6014
6015 Assert(m->mapProperties.empty());
6016
6017 for (MediumFormat::PropertyList::const_iterator it = m->formatObj->getProperties().begin();
6018 it != m->formatObj->getProperties().end();
6019 ++it)
6020 {
6021 m->mapProperties.insert(std::make_pair(it->strName, Utf8Str::Empty));
6022 }
6023 }
6024
6025 unconst(m->strFormat) = aFormat;
6026
6027 return S_OK;
6028}
6029
6030/**
6031 * Converts the Medium device type to the VD type.
6032 */
6033VDTYPE Medium::convertDeviceType()
6034{
6035 VDTYPE enmType;
6036
6037 switch (m->devType)
6038 {
6039 case DeviceType_HardDisk:
6040 enmType = VDTYPE_HDD;
6041 break;
6042 case DeviceType_DVD:
6043 enmType = VDTYPE_DVD;
6044 break;
6045 case DeviceType_Floppy:
6046 enmType = VDTYPE_FLOPPY;
6047 break;
6048 default:
6049 ComAssertFailedRet(VDTYPE_INVALID);
6050 }
6051
6052 return enmType;
6053}
6054
6055/**
6056 * Converts from the VD type to the medium type.
6057 */
6058DeviceType_T Medium::convertToDeviceType(VDTYPE enmType)
6059{
6060 DeviceType_T devType;
6061
6062 switch (enmType)
6063 {
6064 case VDTYPE_HDD:
6065 devType = DeviceType_HardDisk;
6066 break;
6067 case VDTYPE_DVD:
6068 devType = DeviceType_DVD;
6069 break;
6070 case VDTYPE_FLOPPY:
6071 devType = DeviceType_Floppy;
6072 break;
6073 default:
6074 ComAssertFailedRet(DeviceType_Null);
6075 }
6076
6077 return devType;
6078}
6079
6080/**
6081 * Returns the last error message collected by the vdErrorCall callback and
6082 * resets it.
6083 *
6084 * The error message is returned prepended with a dot and a space, like this:
6085 * <code>
6086 * ". <error_text> (%Rrc)"
6087 * </code>
6088 * to make it easily appendable to a more general error message. The @c %Rrc
6089 * format string is given @a aVRC as an argument.
6090 *
6091 * If there is no last error message collected by vdErrorCall or if it is a
6092 * null or empty string, then this function returns the following text:
6093 * <code>
6094 * " (%Rrc)"
6095 * </code>
6096 *
6097 * @note Doesn't do any object locking; it is assumed that the caller makes sure
6098 * the callback isn't called by more than one thread at a time.
6099 *
6100 * @param aVRC VBox error code to use when no error message is provided.
6101 */
6102Utf8Str Medium::vdError(int aVRC)
6103{
6104 Utf8Str error;
6105
6106 if (m->vdError.isEmpty())
6107 error = Utf8StrFmt(" (%Rrc)", aVRC);
6108 else
6109 error = Utf8StrFmt(".\n%s", m->vdError.c_str());
6110
6111 m->vdError.setNull();
6112
6113 return error;
6114}
6115
6116/**
6117 * Error message callback.
6118 *
6119 * Puts the reported error message to the m->vdError field.
6120 *
6121 * @note Doesn't do any object locking; it is assumed that the caller makes sure
6122 * the callback isn't called by more than one thread at a time.
6123 *
6124 * @param pvUser The opaque data passed on container creation.
6125 * @param rc The VBox error code.
6126 * @param RT_SRC_POS_DECL Use RT_SRC_POS.
6127 * @param pszFormat Error message format string.
6128 * @param va Error message arguments.
6129 */
6130/*static*/
6131DECLCALLBACK(void) Medium::vdErrorCall(void *pvUser, int rc, RT_SRC_POS_DECL,
6132 const char *pszFormat, va_list va)
6133{
6134 NOREF(pszFile); NOREF(iLine); NOREF(pszFunction); /* RT_SRC_POS_DECL */
6135
6136 Medium *that = static_cast<Medium*>(pvUser);
6137 AssertReturnVoid(that != NULL);
6138
6139 if (that->m->vdError.isEmpty())
6140 that->m->vdError =
6141 Utf8StrFmt("%s (%Rrc)", Utf8Str(pszFormat, va).c_str(), rc);
6142 else
6143 that->m->vdError =
6144 Utf8StrFmt("%s.\n%s (%Rrc)", that->m->vdError.c_str(),
6145 Utf8Str(pszFormat, va).c_str(), rc);
6146}
6147
6148/* static */
6149DECLCALLBACK(bool) Medium::vdConfigAreKeysValid(void *pvUser,
6150 const char * /* pszzValid */)
6151{
6152 Medium *that = static_cast<Medium*>(pvUser);
6153 AssertReturn(that != NULL, false);
6154
6155 /* we always return true since the only keys we have are those found in
6156 * VDBACKENDINFO */
6157 return true;
6158}
6159
6160/* static */
6161DECLCALLBACK(int) Medium::vdConfigQuerySize(void *pvUser,
6162 const char *pszName,
6163 size_t *pcbValue)
6164{
6165 AssertReturn(VALID_PTR(pcbValue), VERR_INVALID_POINTER);
6166
6167 Medium *that = static_cast<Medium*>(pvUser);
6168 AssertReturn(that != NULL, VERR_GENERAL_FAILURE);
6169
6170 settings::StringsMap::const_iterator it = that->m->mapProperties.find(Utf8Str(pszName));
6171 if (it == that->m->mapProperties.end())
6172 return VERR_CFGM_VALUE_NOT_FOUND;
6173
6174 /* we interpret null values as "no value" in Medium */
6175 if (it->second.isEmpty())
6176 return VERR_CFGM_VALUE_NOT_FOUND;
6177
6178 *pcbValue = it->second.length() + 1 /* include terminator */;
6179
6180 return VINF_SUCCESS;
6181}
6182
6183/* static */
6184DECLCALLBACK(int) Medium::vdConfigQuery(void *pvUser,
6185 const char *pszName,
6186 char *pszValue,
6187 size_t cchValue)
6188{
6189 AssertReturn(VALID_PTR(pszValue), VERR_INVALID_POINTER);
6190
6191 Medium *that = static_cast<Medium*>(pvUser);
6192 AssertReturn(that != NULL, VERR_GENERAL_FAILURE);
6193
6194 settings::StringsMap::const_iterator it = that->m->mapProperties.find(Utf8Str(pszName));
6195 if (it == that->m->mapProperties.end())
6196 return VERR_CFGM_VALUE_NOT_FOUND;
6197
6198 /* we interpret null values as "no value" in Medium */
6199 if (it->second.isEmpty())
6200 return VERR_CFGM_VALUE_NOT_FOUND;
6201
6202 const Utf8Str &value = it->second;
6203 if (value.length() >= cchValue)
6204 return VERR_CFGM_NOT_ENOUGH_SPACE;
6205
6206 memcpy(pszValue, value.c_str(), value.length() + 1);
6207
6208 return VINF_SUCCESS;
6209}
6210
6211DECLCALLBACK(int) Medium::vdTcpSocketCreate(uint32_t fFlags, PVDSOCKET pSock)
6212{
6213 PVDSOCKETINT pSocketInt = NULL;
6214
6215 if ((fFlags & VD_INTERFACETCPNET_CONNECT_EXTENDED_SELECT) != 0)
6216 return VERR_NOT_SUPPORTED;
6217
6218 pSocketInt = (PVDSOCKETINT)RTMemAllocZ(sizeof(VDSOCKETINT));
6219 if (!pSocketInt)
6220 return VERR_NO_MEMORY;
6221
6222 pSocketInt->hSocket = NIL_RTSOCKET;
6223 *pSock = pSocketInt;
6224 return VINF_SUCCESS;
6225}
6226
6227DECLCALLBACK(int) Medium::vdTcpSocketDestroy(VDSOCKET Sock)
6228{
6229 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6230
6231 if (pSocketInt->hSocket != NIL_RTSOCKET)
6232 RTTcpClientCloseEx(pSocketInt->hSocket, false /*fGracefulShutdown*/);
6233
6234 RTMemFree(pSocketInt);
6235
6236 return VINF_SUCCESS;
6237}
6238
6239DECLCALLBACK(int) Medium::vdTcpClientConnect(VDSOCKET Sock, const char *pszAddress, uint32_t uPort)
6240{
6241 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6242
6243 return RTTcpClientConnect(pszAddress, uPort, &pSocketInt->hSocket);
6244}
6245
6246DECLCALLBACK(int) Medium::vdTcpClientClose(VDSOCKET Sock)
6247{
6248 int rc = VINF_SUCCESS;
6249 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6250
6251 rc = RTTcpClientCloseEx(pSocketInt->hSocket, false /*fGracefulShutdown*/);
6252 pSocketInt->hSocket = NIL_RTSOCKET;
6253 return rc;
6254}
6255
6256DECLCALLBACK(bool) Medium::vdTcpIsClientConnected(VDSOCKET Sock)
6257{
6258 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6259 return pSocketInt->hSocket != NIL_RTSOCKET;
6260}
6261
6262DECLCALLBACK(int) Medium::vdTcpSelectOne(VDSOCKET Sock, RTMSINTERVAL cMillies)
6263{
6264 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6265 return RTTcpSelectOne(pSocketInt->hSocket, cMillies);
6266}
6267
6268DECLCALLBACK(int) Medium::vdTcpRead(VDSOCKET Sock, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
6269{
6270 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6271 return RTTcpRead(pSocketInt->hSocket, pvBuffer, cbBuffer, pcbRead);
6272}
6273
6274DECLCALLBACK(int) Medium::vdTcpWrite(VDSOCKET Sock, const void *pvBuffer, size_t cbBuffer)
6275{
6276 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6277 return RTTcpWrite(pSocketInt->hSocket, pvBuffer, cbBuffer);
6278}
6279
6280DECLCALLBACK(int) Medium::vdTcpSgWrite(VDSOCKET Sock, PCRTSGBUF pSgBuf)
6281{
6282 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6283 return RTTcpSgWrite(pSocketInt->hSocket, pSgBuf);
6284}
6285
6286DECLCALLBACK(int) Medium::vdTcpFlush(VDSOCKET Sock)
6287{
6288 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6289 return RTTcpFlush(pSocketInt->hSocket);
6290}
6291
6292DECLCALLBACK(int) Medium::vdTcpSetSendCoalescing(VDSOCKET Sock, bool fEnable)
6293{
6294 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6295 return RTTcpSetSendCoalescing(pSocketInt->hSocket, fEnable);
6296}
6297
6298DECLCALLBACK(int) Medium::vdTcpGetLocalAddress(VDSOCKET Sock, PRTNETADDR pAddr)
6299{
6300 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6301 return RTTcpGetLocalAddress(pSocketInt->hSocket, pAddr);
6302}
6303
6304DECLCALLBACK(int) Medium::vdTcpGetPeerAddress(VDSOCKET Sock, PRTNETADDR pAddr)
6305{
6306 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6307 return RTTcpGetPeerAddress(pSocketInt->hSocket, pAddr);
6308}
6309
6310/**
6311 * Starts a new thread driven by the appropriate Medium::Task::handler() method.
6312 *
6313 * @note When the task is executed by this method, IProgress::notifyComplete()
6314 * is automatically called for the progress object associated with this
6315 * task when the task is finished to signal the operation completion for
6316 * other threads asynchronously waiting for it.
6317 */
6318HRESULT Medium::startThread(Medium::Task *pTask)
6319{
6320#ifdef VBOX_WITH_MAIN_LOCK_VALIDATION
6321 /* Extreme paranoia: The calling thread should not hold the medium
6322 * tree lock or any medium lock. Since there is no separate lock class
6323 * for medium objects be even more strict: no other object locks. */
6324 Assert(!AutoLockHoldsLocksInClass(LOCKCLASS_LISTOFMEDIA));
6325 Assert(!AutoLockHoldsLocksInClass(getLockingClass()));
6326#endif
6327
6328 /// @todo use a more descriptive task name
6329 int vrc = RTThreadCreate(NULL, Medium::Task::fntMediumTask, pTask,
6330 0, RTTHREADTYPE_MAIN_HEAVY_WORKER, 0,
6331 "Medium::Task");
6332 if (RT_FAILURE(vrc))
6333 {
6334 delete pTask;
6335 return setError(E_FAIL, "Could not create Medium::Task thread (%Rrc)\n", vrc);
6336 }
6337
6338 return S_OK;
6339}
6340
6341/**
6342 * Runs Medium::Task::handler() on the current thread instead of creating
6343 * a new one.
6344 *
6345 * This call implies that it is made on another temporary thread created for
6346 * some asynchronous task. Avoid calling it from a normal thread since the task
6347 * operations are potentially lengthy and will block the calling thread in this
6348 * case.
6349 *
6350 * @note When the task is executed by this method, IProgress::notifyComplete()
6351 * is not called for the progress object associated with this task when
6352 * the task is finished. Instead, the result of the operation is returned
6353 * by this method directly and it's the caller's responsibility to
6354 * complete the progress object in this case.
6355 */
6356HRESULT Medium::runNow(Medium::Task *pTask,
6357 GuidList *pllRegistriesThatNeedSaving)
6358{
6359#ifdef VBOX_WITH_MAIN_LOCK_VALIDATION
6360 /* Extreme paranoia: The calling thread should not hold the medium
6361 * tree lock or any medium lock. Since there is no separate lock class
6362 * for medium objects be even more strict: no other object locks. */
6363 Assert(!AutoLockHoldsLocksInClass(LOCKCLASS_LISTOFMEDIA));
6364 Assert(!AutoLockHoldsLocksInClass(getLockingClass()));
6365#endif
6366
6367 pTask->m_pllRegistriesThatNeedSaving = pllRegistriesThatNeedSaving;
6368
6369 /* NIL_RTTHREAD indicates synchronous call. */
6370 return (HRESULT)Medium::Task::fntMediumTask(NIL_RTTHREAD, pTask);
6371}
6372
6373/**
6374 * Implementation code for the "create base" task.
6375 *
6376 * This only gets started from Medium::CreateBaseStorage() and always runs
6377 * asynchronously. As a result, we always save the VirtualBox.xml file when
6378 * we're done here.
6379 *
6380 * @param task
6381 * @return
6382 */
6383HRESULT Medium::taskCreateBaseHandler(Medium::CreateBaseTask &task)
6384{
6385 HRESULT rc = S_OK;
6386
6387 /* these parameters we need after creation */
6388 uint64_t size = 0, logicalSize = 0;
6389 MediumVariant_T variant = MediumVariant_Standard;
6390 bool fGenerateUuid = false;
6391
6392 try
6393 {
6394 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6395
6396 /* The object may request a specific UUID (through a special form of
6397 * the setLocation() argument). Otherwise we have to generate it */
6398 Guid id = m->id;
6399 fGenerateUuid = id.isEmpty();
6400 if (fGenerateUuid)
6401 {
6402 id.create();
6403 /* VirtualBox::registerHardDisk() will need UUID */
6404 unconst(m->id) = id;
6405 }
6406
6407 Utf8Str format(m->strFormat);
6408 Utf8Str location(m->strLocationFull);
6409 uint64_t capabilities = m->formatObj->getCapabilities();
6410 ComAssertThrow(capabilities & ( MediumFormatCapabilities_CreateFixed
6411 | MediumFormatCapabilities_CreateDynamic), E_FAIL);
6412 Assert(m->state == MediumState_Creating);
6413
6414 PVBOXHDD hdd;
6415 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
6416 ComAssertRCThrow(vrc, E_FAIL);
6417
6418 /* unlock before the potentially lengthy operation */
6419 thisLock.release();
6420
6421 try
6422 {
6423 /* ensure the directory exists */
6424 if (capabilities & MediumFormatCapabilities_File)
6425 {
6426 rc = VirtualBox::ensureFilePathExists(location);
6427 if (FAILED(rc))
6428 throw rc;
6429 }
6430
6431 VDGEOMETRY geo = { 0, 0, 0 }; /* auto-detect */
6432
6433 vrc = VDCreateBase(hdd,
6434 format.c_str(),
6435 location.c_str(),
6436 task.mSize,
6437 task.mVariant,
6438 NULL,
6439 &geo,
6440 &geo,
6441 id.raw(),
6442 VD_OPEN_FLAGS_NORMAL,
6443 m->vdImageIfaces,
6444 task.mVDOperationIfaces);
6445 if (RT_FAILURE(vrc))
6446 throw setError(VBOX_E_FILE_ERROR,
6447 tr("Could not create the medium storage unit '%s'%s"),
6448 location.c_str(), vdError(vrc).c_str());
6449
6450 size = VDGetFileSize(hdd, 0);
6451 logicalSize = VDGetSize(hdd, 0);
6452 unsigned uImageFlags;
6453 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
6454 if (RT_SUCCESS(vrc))
6455 variant = (MediumVariant_T)uImageFlags;
6456 }
6457 catch (HRESULT aRC) { rc = aRC; }
6458
6459 VDDestroy(hdd);
6460 }
6461 catch (HRESULT aRC) { rc = aRC; }
6462
6463 if (SUCCEEDED(rc))
6464 {
6465 /* register with mVirtualBox as the last step and move to
6466 * Created state only on success (leaving an orphan file is
6467 * better than breaking media registry consistency) */
6468 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
6469 rc = m->pVirtualBox->registerHardDisk(this, NULL /* pllRegistriesThatNeedSaving */);
6470 }
6471
6472 // reenter the lock before changing state
6473 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6474
6475 if (SUCCEEDED(rc))
6476 {
6477 m->state = MediumState_Created;
6478
6479 m->size = size;
6480 m->logicalSize = logicalSize;
6481 m->variant = variant;
6482 }
6483 else
6484 {
6485 /* back to NotCreated on failure */
6486 m->state = MediumState_NotCreated;
6487
6488 /* reset UUID to prevent it from being reused next time */
6489 if (fGenerateUuid)
6490 unconst(m->id).clear();
6491 }
6492
6493 return rc;
6494}
6495
6496/**
6497 * Implementation code for the "create diff" task.
6498 *
6499 * This task always gets started from Medium::createDiffStorage() and can run
6500 * synchronously or asynchronously depending on the "wait" parameter passed to
6501 * that function. If we run synchronously, the caller expects the bool
6502 * *pfNeedsGlobalSaveSettings to be set before returning; otherwise (in asynchronous
6503 * mode), we save the settings ourselves.
6504 *
6505 * @param task
6506 * @return
6507 */
6508HRESULT Medium::taskCreateDiffHandler(Medium::CreateDiffTask &task)
6509{
6510 HRESULT rcTmp = S_OK;
6511
6512 const ComObjPtr<Medium> &pTarget = task.mTarget;
6513
6514 uint64_t size = 0, logicalSize = 0;
6515 MediumVariant_T variant = MediumVariant_Standard;
6516 bool fGenerateUuid = false;
6517
6518 GuidList llRegistriesThatNeedSaving; // gets copied to task pointer later in synchronous mode
6519
6520 try
6521 {
6522 /* Lock both in {parent,child} order. */
6523 AutoMultiWriteLock2 mediaLock(this, pTarget COMMA_LOCKVAL_SRC_POS);
6524
6525 /* The object may request a specific UUID (through a special form of
6526 * the setLocation() argument). Otherwise we have to generate it */
6527 Guid targetId = pTarget->m->id;
6528 fGenerateUuid = targetId.isEmpty();
6529 if (fGenerateUuid)
6530 {
6531 targetId.create();
6532 /* VirtualBox::registerHardDisk() will need UUID */
6533 unconst(pTarget->m->id) = targetId;
6534 }
6535
6536 Guid id = m->id;
6537
6538 Utf8Str targetFormat(pTarget->m->strFormat);
6539 Utf8Str targetLocation(pTarget->m->strLocationFull);
6540 uint64_t capabilities = pTarget->m->formatObj->getCapabilities();
6541 ComAssertThrow(capabilities & MediumFormatCapabilities_CreateDynamic, E_FAIL);
6542
6543 Assert(pTarget->m->state == MediumState_Creating);
6544 Assert(m->state == MediumState_LockedRead);
6545
6546 PVBOXHDD hdd;
6547 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
6548 ComAssertRCThrow(vrc, E_FAIL);
6549
6550 /* the two media are now protected by their non-default states;
6551 * unlock the media before the potentially lengthy operation */
6552 mediaLock.release();
6553
6554 try
6555 {
6556 /* Open all media in the target chain but the last. */
6557 MediumLockList::Base::const_iterator targetListBegin =
6558 task.mpMediumLockList->GetBegin();
6559 MediumLockList::Base::const_iterator targetListEnd =
6560 task.mpMediumLockList->GetEnd();
6561 for (MediumLockList::Base::const_iterator it = targetListBegin;
6562 it != targetListEnd;
6563 ++it)
6564 {
6565 const MediumLock &mediumLock = *it;
6566 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
6567
6568 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
6569
6570 /* Skip over the target diff medium */
6571 if (pMedium->m->state == MediumState_Creating)
6572 continue;
6573
6574 /* sanity check */
6575 Assert(pMedium->m->state == MediumState_LockedRead);
6576
6577 /* Open all media in appropriate mode. */
6578 vrc = VDOpen(hdd,
6579 pMedium->m->strFormat.c_str(),
6580 pMedium->m->strLocationFull.c_str(),
6581 VD_OPEN_FLAGS_READONLY,
6582 pMedium->m->vdImageIfaces);
6583 if (RT_FAILURE(vrc))
6584 throw setError(VBOX_E_FILE_ERROR,
6585 tr("Could not open the medium storage unit '%s'%s"),
6586 pMedium->m->strLocationFull.c_str(),
6587 vdError(vrc).c_str());
6588 }
6589
6590 /* ensure the target directory exists */
6591 if (capabilities & MediumFormatCapabilities_File)
6592 {
6593 HRESULT rc = VirtualBox::ensureFilePathExists(targetLocation);
6594 if (FAILED(rc))
6595 throw rc;
6596 }
6597
6598 vrc = VDCreateDiff(hdd,
6599 targetFormat.c_str(),
6600 targetLocation.c_str(),
6601 task.mVariant | VD_IMAGE_FLAGS_DIFF,
6602 NULL,
6603 targetId.raw(),
6604 id.raw(),
6605 VD_OPEN_FLAGS_NORMAL,
6606 pTarget->m->vdImageIfaces,
6607 task.mVDOperationIfaces);
6608 if (RT_FAILURE(vrc))
6609 throw setError(VBOX_E_FILE_ERROR,
6610 tr("Could not create the differencing medium storage unit '%s'%s"),
6611 targetLocation.c_str(), vdError(vrc).c_str());
6612
6613 size = VDGetFileSize(hdd, VD_LAST_IMAGE);
6614 logicalSize = VDGetSize(hdd, VD_LAST_IMAGE);
6615 unsigned uImageFlags;
6616 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
6617 if (RT_SUCCESS(vrc))
6618 variant = (MediumVariant_T)uImageFlags;
6619 }
6620 catch (HRESULT aRC) { rcTmp = aRC; }
6621
6622 VDDestroy(hdd);
6623 }
6624 catch (HRESULT aRC) { rcTmp = aRC; }
6625
6626 MultiResult mrc(rcTmp);
6627
6628 if (SUCCEEDED(mrc))
6629 {
6630 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
6631
6632 Assert(pTarget->m->pParent.isNull());
6633
6634 /* associate the child with the parent */
6635 pTarget->m->pParent = this;
6636 m->llChildren.push_back(pTarget);
6637
6638 /** @todo r=klaus neither target nor base() are locked,
6639 * potential race! */
6640 /* diffs for immutable media are auto-reset by default */
6641 pTarget->m->autoReset = (getBase()->m->type == MediumType_Immutable);
6642
6643 /* register with mVirtualBox as the last step and move to
6644 * Created state only on success (leaving an orphan file is
6645 * better than breaking media registry consistency) */
6646 mrc = m->pVirtualBox->registerHardDisk(pTarget, &llRegistriesThatNeedSaving);
6647
6648 if (FAILED(mrc))
6649 /* break the parent association on failure to register */
6650 deparent();
6651 }
6652
6653 AutoMultiWriteLock2 mediaLock(this, pTarget COMMA_LOCKVAL_SRC_POS);
6654
6655 if (SUCCEEDED(mrc))
6656 {
6657 pTarget->m->state = MediumState_Created;
6658
6659 pTarget->m->size = size;
6660 pTarget->m->logicalSize = logicalSize;
6661 pTarget->m->variant = variant;
6662 }
6663 else
6664 {
6665 /* back to NotCreated on failure */
6666 pTarget->m->state = MediumState_NotCreated;
6667
6668 pTarget->m->autoReset = false;
6669
6670 /* reset UUID to prevent it from being reused next time */
6671 if (fGenerateUuid)
6672 unconst(pTarget->m->id).clear();
6673 }
6674
6675 // deregister the task registered in createDiffStorage()
6676 Assert(m->numCreateDiffTasks != 0);
6677 --m->numCreateDiffTasks;
6678
6679 if (task.isAsync())
6680 {
6681 mediaLock.release();
6682 mrc = m->pVirtualBox->saveRegistries(llRegistriesThatNeedSaving);
6683 }
6684 else
6685 // synchronous mode: report save settings result to caller
6686 if (task.m_pllRegistriesThatNeedSaving)
6687 *task.m_pllRegistriesThatNeedSaving = llRegistriesThatNeedSaving;
6688
6689 /* Note that in sync mode, it's the caller's responsibility to
6690 * unlock the medium. */
6691
6692 return mrc;
6693}
6694
6695/**
6696 * Implementation code for the "merge" task.
6697 *
6698 * This task always gets started from Medium::mergeTo() and can run
6699 * synchronously or asynchronously depending on the "wait" parameter passed to
6700 * that function. If we run synchronously, the caller expects the bool
6701 * *pfNeedsGlobalSaveSettings to be set before returning; otherwise (in asynchronous
6702 * mode), we save the settings ourselves.
6703 *
6704 * @param task
6705 * @return
6706 */
6707HRESULT Medium::taskMergeHandler(Medium::MergeTask &task)
6708{
6709 HRESULT rcTmp = S_OK;
6710
6711 const ComObjPtr<Medium> &pTarget = task.mTarget;
6712
6713 try
6714 {
6715 PVBOXHDD hdd;
6716 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
6717 ComAssertRCThrow(vrc, E_FAIL);
6718
6719 try
6720 {
6721 // Similar code appears in SessionMachine::onlineMergeMedium, so
6722 // if you make any changes below check whether they are applicable
6723 // in that context as well.
6724
6725 unsigned uTargetIdx = VD_LAST_IMAGE;
6726 unsigned uSourceIdx = VD_LAST_IMAGE;
6727 /* Open all media in the chain. */
6728 MediumLockList::Base::iterator lockListBegin =
6729 task.mpMediumLockList->GetBegin();
6730 MediumLockList::Base::iterator lockListEnd =
6731 task.mpMediumLockList->GetEnd();
6732 unsigned i = 0;
6733 for (MediumLockList::Base::iterator it = lockListBegin;
6734 it != lockListEnd;
6735 ++it)
6736 {
6737 MediumLock &mediumLock = *it;
6738 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
6739
6740 if (pMedium == this)
6741 uSourceIdx = i;
6742 else if (pMedium == pTarget)
6743 uTargetIdx = i;
6744
6745 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
6746
6747 /*
6748 * complex sanity (sane complexity)
6749 *
6750 * The current medium must be in the Deleting (medium is merged)
6751 * or LockedRead (parent medium) state if it is not the target.
6752 * If it is the target it must be in the LockedWrite state.
6753 */
6754 Assert( ( pMedium != pTarget
6755 && ( pMedium->m->state == MediumState_Deleting
6756 || pMedium->m->state == MediumState_LockedRead))
6757 || ( pMedium == pTarget
6758 && pMedium->m->state == MediumState_LockedWrite));
6759
6760 /*
6761 * Medium must be the target, in the LockedRead state
6762 * or Deleting state where it is not allowed to be attached
6763 * to a virtual machine.
6764 */
6765 Assert( pMedium == pTarget
6766 || pMedium->m->state == MediumState_LockedRead
6767 || ( pMedium->m->backRefs.size() == 0
6768 && pMedium->m->state == MediumState_Deleting));
6769 /* The source medium must be in Deleting state. */
6770 Assert( pMedium != this
6771 || pMedium->m->state == MediumState_Deleting);
6772
6773 unsigned uOpenFlags = VD_OPEN_FLAGS_NORMAL;
6774
6775 if ( pMedium->m->state == MediumState_LockedRead
6776 || pMedium->m->state == MediumState_Deleting)
6777 uOpenFlags = VD_OPEN_FLAGS_READONLY;
6778 if (pMedium->m->type == MediumType_Shareable)
6779 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
6780
6781 /* Open the medium */
6782 vrc = VDOpen(hdd,
6783 pMedium->m->strFormat.c_str(),
6784 pMedium->m->strLocationFull.c_str(),
6785 uOpenFlags,
6786 pMedium->m->vdImageIfaces);
6787 if (RT_FAILURE(vrc))
6788 throw vrc;
6789
6790 i++;
6791 }
6792
6793 ComAssertThrow( uSourceIdx != VD_LAST_IMAGE
6794 && uTargetIdx != VD_LAST_IMAGE, E_FAIL);
6795
6796 vrc = VDMerge(hdd, uSourceIdx, uTargetIdx,
6797 task.mVDOperationIfaces);
6798 if (RT_FAILURE(vrc))
6799 throw vrc;
6800
6801 /* update parent UUIDs */
6802 if (!task.mfMergeForward)
6803 {
6804 /* we need to update UUIDs of all source's children
6805 * which cannot be part of the container at once so
6806 * add each one in there individually */
6807 if (task.mChildrenToReparent.size() > 0)
6808 {
6809 for (MediaList::const_iterator it = task.mChildrenToReparent.begin();
6810 it != task.mChildrenToReparent.end();
6811 ++it)
6812 {
6813 /* VD_OPEN_FLAGS_INFO since UUID is wrong yet */
6814 vrc = VDOpen(hdd,
6815 (*it)->m->strFormat.c_str(),
6816 (*it)->m->strLocationFull.c_str(),
6817 VD_OPEN_FLAGS_INFO,
6818 (*it)->m->vdImageIfaces);
6819 if (RT_FAILURE(vrc))
6820 throw vrc;
6821
6822 vrc = VDSetParentUuid(hdd, VD_LAST_IMAGE,
6823 pTarget->m->id.raw());
6824 if (RT_FAILURE(vrc))
6825 throw vrc;
6826
6827 vrc = VDClose(hdd, false /* fDelete */);
6828 if (RT_FAILURE(vrc))
6829 throw vrc;
6830
6831 (*it)->UnlockWrite(NULL);
6832 }
6833 }
6834 }
6835 }
6836 catch (HRESULT aRC) { rcTmp = aRC; }
6837 catch (int aVRC)
6838 {
6839 rcTmp = setError(VBOX_E_FILE_ERROR,
6840 tr("Could not merge the medium '%s' to '%s'%s"),
6841 m->strLocationFull.c_str(),
6842 pTarget->m->strLocationFull.c_str(),
6843 vdError(aVRC).c_str());
6844 }
6845
6846 VDDestroy(hdd);
6847 }
6848 catch (HRESULT aRC) { rcTmp = aRC; }
6849
6850 ErrorInfoKeeper eik;
6851 MultiResult mrc(rcTmp);
6852 HRESULT rc2;
6853
6854 if (SUCCEEDED(mrc))
6855 {
6856 /* all media but the target were successfully deleted by
6857 * VDMerge; reparent the last one and uninitialize deleted media. */
6858
6859 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
6860
6861 if (task.mfMergeForward)
6862 {
6863 /* first, unregister the target since it may become a base
6864 * medium which needs re-registration */
6865 rc2 = m->pVirtualBox->unregisterHardDisk(pTarget, NULL /*&fNeedsGlobalSaveSettings*/);
6866 AssertComRC(rc2);
6867
6868 /* then, reparent it and disconnect the deleted branch at
6869 * both ends (chain->parent() is source's parent) */
6870 pTarget->deparent();
6871 pTarget->m->pParent = task.mParentForTarget;
6872 if (pTarget->m->pParent)
6873 {
6874 pTarget->m->pParent->m->llChildren.push_back(pTarget);
6875 deparent();
6876 }
6877
6878 /* then, register again */
6879 rc2 = m->pVirtualBox->registerHardDisk(pTarget, NULL /* pllRegistriesThatNeedSaving */ );
6880 AssertComRC(rc2);
6881 }
6882 else
6883 {
6884 Assert(pTarget->getChildren().size() == 1);
6885 Medium *targetChild = pTarget->getChildren().front();
6886
6887 /* disconnect the deleted branch at the elder end */
6888 targetChild->deparent();
6889
6890 /* reparent source's children and disconnect the deleted
6891 * branch at the younger end */
6892 if (task.mChildrenToReparent.size() > 0)
6893 {
6894 /* obey {parent,child} lock order */
6895 AutoWriteLock sourceLock(this COMMA_LOCKVAL_SRC_POS);
6896
6897 for (MediaList::const_iterator it = task.mChildrenToReparent.begin();
6898 it != task.mChildrenToReparent.end();
6899 it++)
6900 {
6901 Medium *pMedium = *it;
6902 AutoWriteLock childLock(pMedium COMMA_LOCKVAL_SRC_POS);
6903
6904 pMedium->deparent(); // removes pMedium from source
6905 pMedium->setParent(pTarget);
6906 }
6907 }
6908 }
6909
6910 /* unregister and uninitialize all media removed by the merge */
6911 MediumLockList::Base::iterator lockListBegin =
6912 task.mpMediumLockList->GetBegin();
6913 MediumLockList::Base::iterator lockListEnd =
6914 task.mpMediumLockList->GetEnd();
6915 for (MediumLockList::Base::iterator it = lockListBegin;
6916 it != lockListEnd;
6917 )
6918 {
6919 MediumLock &mediumLock = *it;
6920 /* Create a real copy of the medium pointer, as the medium
6921 * lock deletion below would invalidate the referenced object. */
6922 const ComObjPtr<Medium> pMedium = mediumLock.GetMedium();
6923
6924 /* The target and all media not merged (readonly) are skipped */
6925 if ( pMedium == pTarget
6926 || pMedium->m->state == MediumState_LockedRead)
6927 {
6928 ++it;
6929 continue;
6930 }
6931
6932 rc2 = pMedium->m->pVirtualBox->unregisterHardDisk(pMedium,
6933 NULL /*pfNeedsGlobalSaveSettings*/);
6934 AssertComRC(rc2);
6935
6936 /* now, uninitialize the deleted medium (note that
6937 * due to the Deleting state, uninit() will not touch
6938 * the parent-child relationship so we need to
6939 * uninitialize each disk individually) */
6940
6941 /* note that the operation initiator medium (which is
6942 * normally also the source medium) is a special case
6943 * -- there is one more caller added by Task to it which
6944 * we must release. Also, if we are in sync mode, the
6945 * caller may still hold an AutoCaller instance for it
6946 * and therefore we cannot uninit() it (it's therefore
6947 * the caller's responsibility) */
6948 if (pMedium == this)
6949 {
6950 Assert(getChildren().size() == 0);
6951 Assert(m->backRefs.size() == 0);
6952 task.mMediumCaller.release();
6953 }
6954
6955 /* Delete the medium lock list entry, which also releases the
6956 * caller added by MergeChain before uninit() and updates the
6957 * iterator to point to the right place. */
6958 rc2 = task.mpMediumLockList->RemoveByIterator(it);
6959 AssertComRC(rc2);
6960
6961 if (task.isAsync() || pMedium != this)
6962 pMedium->uninit();
6963 }
6964 }
6965
6966 if (task.isAsync())
6967 {
6968 // in asynchronous mode, save settings now
6969 GuidList llRegistriesThatNeedSaving;
6970 addToRegistryIDList(llRegistriesThatNeedSaving);
6971 /* collect multiple errors */
6972 eik.restore();
6973 mrc = m->pVirtualBox->saveRegistries(llRegistriesThatNeedSaving);
6974 eik.fetch();
6975 }
6976 else
6977 // synchronous mode: report save settings result to caller
6978 if (task.m_pllRegistriesThatNeedSaving)
6979 pTarget->addToRegistryIDList(*task.m_pllRegistriesThatNeedSaving);
6980
6981 if (FAILED(mrc))
6982 {
6983 /* Here we come if either VDMerge() failed (in which case we
6984 * assume that it tried to do everything to make a further
6985 * retry possible -- e.g. not deleted intermediate media
6986 * and so on) or VirtualBox::saveRegistries() failed (where we
6987 * should have the original tree but with intermediate storage
6988 * units deleted by VDMerge()). We have to only restore states
6989 * (through the MergeChain dtor) unless we are run synchronously
6990 * in which case it's the responsibility of the caller as stated
6991 * in the mergeTo() docs. The latter also implies that we
6992 * don't own the merge chain, so release it in this case. */
6993 if (task.isAsync())
6994 {
6995 Assert(task.mChildrenToReparent.size() == 0);
6996 cancelMergeTo(task.mChildrenToReparent, task.mpMediumLockList);
6997 }
6998 }
6999
7000 return mrc;
7001}
7002
7003/**
7004 * Implementation code for the "clone" task.
7005 *
7006 * This only gets started from Medium::CloneTo() and always runs asynchronously.
7007 * As a result, we always save the VirtualBox.xml file when we're done here.
7008 *
7009 * @param task
7010 * @return
7011 */
7012HRESULT Medium::taskCloneHandler(Medium::CloneTask &task)
7013{
7014 HRESULT rcTmp = S_OK;
7015
7016 const ComObjPtr<Medium> &pTarget = task.mTarget;
7017 const ComObjPtr<Medium> &pParent = task.mParent;
7018
7019 bool fCreatingTarget = false;
7020
7021 uint64_t size = 0, logicalSize = 0;
7022 MediumVariant_T variant = MediumVariant_Standard;
7023 bool fGenerateUuid = false;
7024
7025 try
7026 {
7027 /* Lock all in {parent,child} order. The lock is also used as a
7028 * signal from the task initiator (which releases it only after
7029 * RTThreadCreate()) that we can start the job. */
7030 AutoMultiWriteLock3 thisLock(this, pTarget, pParent COMMA_LOCKVAL_SRC_POS);
7031
7032 fCreatingTarget = pTarget->m->state == MediumState_Creating;
7033
7034 /* The object may request a specific UUID (through a special form of
7035 * the setLocation() argument). Otherwise we have to generate it */
7036 Guid targetId = pTarget->m->id;
7037 fGenerateUuid = targetId.isEmpty();
7038 if (fGenerateUuid)
7039 {
7040 targetId.create();
7041 /* VirtualBox::registerHardDisk() will need UUID */
7042 unconst(pTarget->m->id) = targetId;
7043 }
7044
7045 PVBOXHDD hdd;
7046 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
7047 ComAssertRCThrow(vrc, E_FAIL);
7048
7049 try
7050 {
7051 /* Open all media in the source chain. */
7052 MediumLockList::Base::const_iterator sourceListBegin =
7053 task.mpSourceMediumLockList->GetBegin();
7054 MediumLockList::Base::const_iterator sourceListEnd =
7055 task.mpSourceMediumLockList->GetEnd();
7056 for (MediumLockList::Base::const_iterator it = sourceListBegin;
7057 it != sourceListEnd;
7058 ++it)
7059 {
7060 const MediumLock &mediumLock = *it;
7061 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
7062 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
7063
7064 /* sanity check */
7065 Assert(pMedium->m->state == MediumState_LockedRead);
7066
7067 /** Open all media in read-only mode. */
7068 vrc = VDOpen(hdd,
7069 pMedium->m->strFormat.c_str(),
7070 pMedium->m->strLocationFull.c_str(),
7071 VD_OPEN_FLAGS_READONLY,
7072 pMedium->m->vdImageIfaces);
7073 if (RT_FAILURE(vrc))
7074 throw setError(VBOX_E_FILE_ERROR,
7075 tr("Could not open the medium storage unit '%s'%s"),
7076 pMedium->m->strLocationFull.c_str(),
7077 vdError(vrc).c_str());
7078 }
7079
7080 Utf8Str targetFormat(pTarget->m->strFormat);
7081 Utf8Str targetLocation(pTarget->m->strLocationFull);
7082 uint64_t capabilities = pTarget->m->formatObj->getCapabilities();
7083
7084 Assert( pTarget->m->state == MediumState_Creating
7085 || pTarget->m->state == MediumState_LockedWrite);
7086 Assert(m->state == MediumState_LockedRead);
7087 Assert( pParent.isNull()
7088 || pParent->m->state == MediumState_LockedRead);
7089
7090 /* unlock before the potentially lengthy operation */
7091 thisLock.release();
7092
7093 /* ensure the target directory exists */
7094 if (capabilities & MediumFormatCapabilities_File)
7095 {
7096 HRESULT rc = VirtualBox::ensureFilePathExists(targetLocation);
7097 if (FAILED(rc))
7098 throw rc;
7099 }
7100
7101 PVBOXHDD targetHdd;
7102 vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &targetHdd);
7103 ComAssertRCThrow(vrc, E_FAIL);
7104
7105 try
7106 {
7107 /* Open all media in the target chain. */
7108 MediumLockList::Base::const_iterator targetListBegin =
7109 task.mpTargetMediumLockList->GetBegin();
7110 MediumLockList::Base::const_iterator targetListEnd =
7111 task.mpTargetMediumLockList->GetEnd();
7112 for (MediumLockList::Base::const_iterator it = targetListBegin;
7113 it != targetListEnd;
7114 ++it)
7115 {
7116 const MediumLock &mediumLock = *it;
7117 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
7118
7119 /* If the target medium is not created yet there's no
7120 * reason to open it. */
7121 if (pMedium == pTarget && fCreatingTarget)
7122 continue;
7123
7124 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
7125
7126 /* sanity check */
7127 Assert( pMedium->m->state == MediumState_LockedRead
7128 || pMedium->m->state == MediumState_LockedWrite);
7129
7130 unsigned uOpenFlags = VD_OPEN_FLAGS_NORMAL;
7131 if (pMedium->m->state != MediumState_LockedWrite)
7132 uOpenFlags = VD_OPEN_FLAGS_READONLY;
7133 if (pMedium->m->type == MediumType_Shareable)
7134 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
7135
7136 /* Open all media in appropriate mode. */
7137 vrc = VDOpen(targetHdd,
7138 pMedium->m->strFormat.c_str(),
7139 pMedium->m->strLocationFull.c_str(),
7140 uOpenFlags,
7141 pMedium->m->vdImageIfaces);
7142 if (RT_FAILURE(vrc))
7143 throw setError(VBOX_E_FILE_ERROR,
7144 tr("Could not open the medium storage unit '%s'%s"),
7145 pMedium->m->strLocationFull.c_str(),
7146 vdError(vrc).c_str());
7147 }
7148
7149 /** @todo r=klaus target isn't locked, race getting the state */
7150 if (task.midxSrcImageSame == UINT32_MAX)
7151 {
7152 vrc = VDCopy(hdd,
7153 VD_LAST_IMAGE,
7154 targetHdd,
7155 targetFormat.c_str(),
7156 (fCreatingTarget) ? targetLocation.c_str() : (char *)NULL,
7157 false /* fMoveByRename */,
7158 0 /* cbSize */,
7159 task.mVariant,
7160 targetId.raw(),
7161 VD_OPEN_FLAGS_NORMAL,
7162 NULL /* pVDIfsOperation */,
7163 pTarget->m->vdImageIfaces,
7164 task.mVDOperationIfaces);
7165 }
7166 else
7167 {
7168 vrc = VDCopyEx(hdd,
7169 VD_LAST_IMAGE,
7170 targetHdd,
7171 targetFormat.c_str(),
7172 (fCreatingTarget) ? targetLocation.c_str() : (char *)NULL,
7173 false /* fMoveByRename */,
7174 0 /* cbSize */,
7175 task.midxSrcImageSame,
7176 task.midxDstImageSame,
7177 task.mVariant,
7178 targetId.raw(),
7179 VD_OPEN_FLAGS_NORMAL,
7180 NULL /* pVDIfsOperation */,
7181 pTarget->m->vdImageIfaces,
7182 task.mVDOperationIfaces);
7183 }
7184 if (RT_FAILURE(vrc))
7185 throw setError(VBOX_E_FILE_ERROR,
7186 tr("Could not create the clone medium '%s'%s"),
7187 targetLocation.c_str(), vdError(vrc).c_str());
7188
7189 size = VDGetFileSize(targetHdd, VD_LAST_IMAGE);
7190 logicalSize = VDGetSize(targetHdd, VD_LAST_IMAGE);
7191 unsigned uImageFlags;
7192 vrc = VDGetImageFlags(targetHdd, 0, &uImageFlags);
7193 if (RT_SUCCESS(vrc))
7194 variant = (MediumVariant_T)uImageFlags;
7195 }
7196 catch (HRESULT aRC) { rcTmp = aRC; }
7197
7198 VDDestroy(targetHdd);
7199 }
7200 catch (HRESULT aRC) { rcTmp = aRC; }
7201
7202 VDDestroy(hdd);
7203 }
7204 catch (HRESULT aRC) { rcTmp = aRC; }
7205
7206 ErrorInfoKeeper eik;
7207 MultiResult mrc(rcTmp);
7208
7209 /* Only do the parent changes for newly created media. */
7210 if (SUCCEEDED(mrc) && fCreatingTarget)
7211 {
7212 /* we set mParent & children() */
7213 AutoWriteLock alock2(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
7214
7215 Assert(pTarget->m->pParent.isNull());
7216
7217 if (pParent)
7218 {
7219 /* associate the clone with the parent and deassociate
7220 * from VirtualBox */
7221 pTarget->m->pParent = pParent;
7222 pParent->m->llChildren.push_back(pTarget);
7223
7224 /* register with mVirtualBox as the last step and move to
7225 * Created state only on success (leaving an orphan file is
7226 * better than breaking media registry consistency) */
7227 eik.restore();
7228 mrc = pParent->m->pVirtualBox->registerHardDisk(pTarget, NULL /* pllRegistriesThatNeedSaving */);
7229 eik.fetch();
7230
7231 if (FAILED(mrc))
7232 /* break parent association on failure to register */
7233 pTarget->deparent(); // removes target from parent
7234 }
7235 else
7236 {
7237 /* just register */
7238 eik.restore();
7239 mrc = m->pVirtualBox->registerHardDisk(pTarget, NULL /* pllRegistriesThatNeedSaving */);
7240 eik.fetch();
7241 }
7242 }
7243
7244 if (fCreatingTarget)
7245 {
7246 AutoWriteLock mLock(pTarget COMMA_LOCKVAL_SRC_POS);
7247
7248 if (SUCCEEDED(mrc))
7249 {
7250 pTarget->m->state = MediumState_Created;
7251
7252 pTarget->m->size = size;
7253 pTarget->m->logicalSize = logicalSize;
7254 pTarget->m->variant = variant;
7255 }
7256 else
7257 {
7258 /* back to NotCreated on failure */
7259 pTarget->m->state = MediumState_NotCreated;
7260
7261 /* reset UUID to prevent it from being reused next time */
7262 if (fGenerateUuid)
7263 unconst(pTarget->m->id).clear();
7264 }
7265 }
7266
7267 // now, at the end of this task (always asynchronous), save the settings
7268 if (SUCCEEDED(mrc))
7269 {
7270 // save the settings
7271 GuidList llRegistriesThatNeedSaving;
7272 addToRegistryIDList(llRegistriesThatNeedSaving);
7273 /* collect multiple errors */
7274 eik.restore();
7275 mrc = m->pVirtualBox->saveRegistries(llRegistriesThatNeedSaving);
7276 eik.fetch();
7277 }
7278
7279 /* Everything is explicitly unlocked when the task exits,
7280 * as the task destruction also destroys the source chain. */
7281
7282 /* Make sure the source chain is released early. It could happen
7283 * that we get a deadlock in Appliance::Import when Medium::Close
7284 * is called & the source chain is released at the same time. */
7285 task.mpSourceMediumLockList->Clear();
7286
7287 return mrc;
7288}
7289
7290/**
7291 * Implementation code for the "delete" task.
7292 *
7293 * This task always gets started from Medium::deleteStorage() and can run
7294 * synchronously or asynchronously depending on the "wait" parameter passed to
7295 * that function.
7296 *
7297 * @param task
7298 * @return
7299 */
7300HRESULT Medium::taskDeleteHandler(Medium::DeleteTask &task)
7301{
7302 NOREF(task);
7303 HRESULT rc = S_OK;
7304
7305 try
7306 {
7307 /* The lock is also used as a signal from the task initiator (which
7308 * releases it only after RTThreadCreate()) that we can start the job */
7309 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
7310
7311 PVBOXHDD hdd;
7312 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
7313 ComAssertRCThrow(vrc, E_FAIL);
7314
7315 Utf8Str format(m->strFormat);
7316 Utf8Str location(m->strLocationFull);
7317
7318 /* unlock before the potentially lengthy operation */
7319 Assert(m->state == MediumState_Deleting);
7320 thisLock.release();
7321
7322 try
7323 {
7324 vrc = VDOpen(hdd,
7325 format.c_str(),
7326 location.c_str(),
7327 VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO,
7328 m->vdImageIfaces);
7329 if (RT_SUCCESS(vrc))
7330 vrc = VDClose(hdd, true /* fDelete */);
7331
7332 if (RT_FAILURE(vrc))
7333 throw setError(VBOX_E_FILE_ERROR,
7334 tr("Could not delete the medium storage unit '%s'%s"),
7335 location.c_str(), vdError(vrc).c_str());
7336
7337 }
7338 catch (HRESULT aRC) { rc = aRC; }
7339
7340 VDDestroy(hdd);
7341 }
7342 catch (HRESULT aRC) { rc = aRC; }
7343
7344 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
7345
7346 /* go to the NotCreated state even on failure since the storage
7347 * may have been already partially deleted and cannot be used any
7348 * more. One will be able to manually re-open the storage if really
7349 * needed to re-register it. */
7350 m->state = MediumState_NotCreated;
7351
7352 /* Reset UUID to prevent Create* from reusing it again */
7353 unconst(m->id).clear();
7354
7355 return rc;
7356}
7357
7358/**
7359 * Implementation code for the "reset" task.
7360 *
7361 * This always gets started asynchronously from Medium::Reset().
7362 *
7363 * @param task
7364 * @return
7365 */
7366HRESULT Medium::taskResetHandler(Medium::ResetTask &task)
7367{
7368 HRESULT rc = S_OK;
7369
7370 uint64_t size = 0, logicalSize = 0;
7371 MediumVariant_T variant = MediumVariant_Standard;
7372
7373 try
7374 {
7375 /* The lock is also used as a signal from the task initiator (which
7376 * releases it only after RTThreadCreate()) that we can start the job */
7377 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
7378
7379 /// @todo Below we use a pair of delete/create operations to reset
7380 /// the diff contents but the most efficient way will of course be
7381 /// to add a VDResetDiff() API call
7382
7383 PVBOXHDD hdd;
7384 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
7385 ComAssertRCThrow(vrc, E_FAIL);
7386
7387 Guid id = m->id;
7388 Utf8Str format(m->strFormat);
7389 Utf8Str location(m->strLocationFull);
7390
7391 Medium *pParent = m->pParent;
7392 Guid parentId = pParent->m->id;
7393 Utf8Str parentFormat(pParent->m->strFormat);
7394 Utf8Str parentLocation(pParent->m->strLocationFull);
7395
7396 Assert(m->state == MediumState_LockedWrite);
7397
7398 /* unlock before the potentially lengthy operation */
7399 thisLock.release();
7400
7401 try
7402 {
7403 /* Open all media in the target chain but the last. */
7404 MediumLockList::Base::const_iterator targetListBegin =
7405 task.mpMediumLockList->GetBegin();
7406 MediumLockList::Base::const_iterator targetListEnd =
7407 task.mpMediumLockList->GetEnd();
7408 for (MediumLockList::Base::const_iterator it = targetListBegin;
7409 it != targetListEnd;
7410 ++it)
7411 {
7412 const MediumLock &mediumLock = *it;
7413 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
7414
7415 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
7416
7417 /* sanity check, "this" is checked above */
7418 Assert( pMedium == this
7419 || pMedium->m->state == MediumState_LockedRead);
7420
7421 /* Open all media in appropriate mode. */
7422 vrc = VDOpen(hdd,
7423 pMedium->m->strFormat.c_str(),
7424 pMedium->m->strLocationFull.c_str(),
7425 VD_OPEN_FLAGS_READONLY,
7426 pMedium->m->vdImageIfaces);
7427 if (RT_FAILURE(vrc))
7428 throw setError(VBOX_E_FILE_ERROR,
7429 tr("Could not open the medium storage unit '%s'%s"),
7430 pMedium->m->strLocationFull.c_str(),
7431 vdError(vrc).c_str());
7432
7433 /* Done when we hit the media which should be reset */
7434 if (pMedium == this)
7435 break;
7436 }
7437
7438 /* first, delete the storage unit */
7439 vrc = VDClose(hdd, true /* fDelete */);
7440 if (RT_FAILURE(vrc))
7441 throw setError(VBOX_E_FILE_ERROR,
7442 tr("Could not delete the medium storage unit '%s'%s"),
7443 location.c_str(), vdError(vrc).c_str());
7444
7445 /* next, create it again */
7446 vrc = VDOpen(hdd,
7447 parentFormat.c_str(),
7448 parentLocation.c_str(),
7449 VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO,
7450 m->vdImageIfaces);
7451 if (RT_FAILURE(vrc))
7452 throw setError(VBOX_E_FILE_ERROR,
7453 tr("Could not open the medium storage unit '%s'%s"),
7454 parentLocation.c_str(), vdError(vrc).c_str());
7455
7456 vrc = VDCreateDiff(hdd,
7457 format.c_str(),
7458 location.c_str(),
7459 /// @todo use the same medium variant as before
7460 VD_IMAGE_FLAGS_NONE,
7461 NULL,
7462 id.raw(),
7463 parentId.raw(),
7464 VD_OPEN_FLAGS_NORMAL,
7465 m->vdImageIfaces,
7466 task.mVDOperationIfaces);
7467 if (RT_FAILURE(vrc))
7468 throw setError(VBOX_E_FILE_ERROR,
7469 tr("Could not create the differencing medium storage unit '%s'%s"),
7470 location.c_str(), vdError(vrc).c_str());
7471
7472 size = VDGetFileSize(hdd, VD_LAST_IMAGE);
7473 logicalSize = VDGetSize(hdd, VD_LAST_IMAGE);
7474 unsigned uImageFlags;
7475 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
7476 if (RT_SUCCESS(vrc))
7477 variant = (MediumVariant_T)uImageFlags;
7478 }
7479 catch (HRESULT aRC) { rc = aRC; }
7480
7481 VDDestroy(hdd);
7482 }
7483 catch (HRESULT aRC) { rc = aRC; }
7484
7485 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
7486
7487 m->size = size;
7488 m->logicalSize = logicalSize;
7489 m->variant = variant;
7490
7491 if (task.isAsync())
7492 {
7493 /* unlock ourselves when done */
7494 HRESULT rc2 = UnlockWrite(NULL);
7495 AssertComRC(rc2);
7496 }
7497
7498 /* Note that in sync mode, it's the caller's responsibility to
7499 * unlock the medium. */
7500
7501 return rc;
7502}
7503
7504/**
7505 * Implementation code for the "compact" task.
7506 *
7507 * @param task
7508 * @return
7509 */
7510HRESULT Medium::taskCompactHandler(Medium::CompactTask &task)
7511{
7512 HRESULT rc = S_OK;
7513
7514 /* Lock all in {parent,child} order. The lock is also used as a
7515 * signal from the task initiator (which releases it only after
7516 * RTThreadCreate()) that we can start the job. */
7517 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
7518
7519 try
7520 {
7521 PVBOXHDD hdd;
7522 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
7523 ComAssertRCThrow(vrc, E_FAIL);
7524
7525 try
7526 {
7527 /* Open all media in the chain. */
7528 MediumLockList::Base::const_iterator mediumListBegin =
7529 task.mpMediumLockList->GetBegin();
7530 MediumLockList::Base::const_iterator mediumListEnd =
7531 task.mpMediumLockList->GetEnd();
7532 MediumLockList::Base::const_iterator mediumListLast =
7533 mediumListEnd;
7534 mediumListLast--;
7535 for (MediumLockList::Base::const_iterator it = mediumListBegin;
7536 it != mediumListEnd;
7537 ++it)
7538 {
7539 const MediumLock &mediumLock = *it;
7540 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
7541 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
7542
7543 /* sanity check */
7544 if (it == mediumListLast)
7545 Assert(pMedium->m->state == MediumState_LockedWrite);
7546 else
7547 Assert(pMedium->m->state == MediumState_LockedRead);
7548
7549 /* Open all media but last in read-only mode. Do not handle
7550 * shareable media, as compaction and sharing are mutually
7551 * exclusive. */
7552 vrc = VDOpen(hdd,
7553 pMedium->m->strFormat.c_str(),
7554 pMedium->m->strLocationFull.c_str(),
7555 (it == mediumListLast) ? VD_OPEN_FLAGS_NORMAL : VD_OPEN_FLAGS_READONLY,
7556 pMedium->m->vdImageIfaces);
7557 if (RT_FAILURE(vrc))
7558 throw setError(VBOX_E_FILE_ERROR,
7559 tr("Could not open the medium storage unit '%s'%s"),
7560 pMedium->m->strLocationFull.c_str(),
7561 vdError(vrc).c_str());
7562 }
7563
7564 Assert(m->state == MediumState_LockedWrite);
7565
7566 Utf8Str location(m->strLocationFull);
7567
7568 /* unlock before the potentially lengthy operation */
7569 thisLock.release();
7570
7571 vrc = VDCompact(hdd, VD_LAST_IMAGE, task.mVDOperationIfaces);
7572 if (RT_FAILURE(vrc))
7573 {
7574 if (vrc == VERR_NOT_SUPPORTED)
7575 throw setError(VBOX_E_NOT_SUPPORTED,
7576 tr("Compacting is not yet supported for medium '%s'"),
7577 location.c_str());
7578 else if (vrc == VERR_NOT_IMPLEMENTED)
7579 throw setError(E_NOTIMPL,
7580 tr("Compacting is not implemented, medium '%s'"),
7581 location.c_str());
7582 else
7583 throw setError(VBOX_E_FILE_ERROR,
7584 tr("Could not compact medium '%s'%s"),
7585 location.c_str(),
7586 vdError(vrc).c_str());
7587 }
7588 }
7589 catch (HRESULT aRC) { rc = aRC; }
7590
7591 VDDestroy(hdd);
7592 }
7593 catch (HRESULT aRC) { rc = aRC; }
7594
7595 /* Everything is explicitly unlocked when the task exits,
7596 * as the task destruction also destroys the media chain. */
7597
7598 return rc;
7599}
7600
7601/**
7602 * Implementation code for the "resize" task.
7603 *
7604 * @param task
7605 * @return
7606 */
7607HRESULT Medium::taskResizeHandler(Medium::ResizeTask &task)
7608{
7609 HRESULT rc = S_OK;
7610
7611 /* Lock all in {parent,child} order. The lock is also used as a
7612 * signal from the task initiator (which releases it only after
7613 * RTThreadCreate()) that we can start the job. */
7614 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
7615
7616 try
7617 {
7618 PVBOXHDD hdd;
7619 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
7620 ComAssertRCThrow(vrc, E_FAIL);
7621
7622 try
7623 {
7624 /* Open all media in the chain. */
7625 MediumLockList::Base::const_iterator mediumListBegin =
7626 task.mpMediumLockList->GetBegin();
7627 MediumLockList::Base::const_iterator mediumListEnd =
7628 task.mpMediumLockList->GetEnd();
7629 MediumLockList::Base::const_iterator mediumListLast =
7630 mediumListEnd;
7631 mediumListLast--;
7632 for (MediumLockList::Base::const_iterator it = mediumListBegin;
7633 it != mediumListEnd;
7634 ++it)
7635 {
7636 const MediumLock &mediumLock = *it;
7637 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
7638 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
7639
7640 /* sanity check */
7641 if (it == mediumListLast)
7642 Assert(pMedium->m->state == MediumState_LockedWrite);
7643 else
7644 Assert(pMedium->m->state == MediumState_LockedRead);
7645
7646 /* Open all media but last in read-only mode. Do not handle
7647 * shareable media, as compaction and sharing are mutually
7648 * exclusive. */
7649 vrc = VDOpen(hdd,
7650 pMedium->m->strFormat.c_str(),
7651 pMedium->m->strLocationFull.c_str(),
7652 (it == mediumListLast) ? VD_OPEN_FLAGS_NORMAL : VD_OPEN_FLAGS_READONLY,
7653 pMedium->m->vdImageIfaces);
7654 if (RT_FAILURE(vrc))
7655 throw setError(VBOX_E_FILE_ERROR,
7656 tr("Could not open the medium storage unit '%s'%s"),
7657 pMedium->m->strLocationFull.c_str(),
7658 vdError(vrc).c_str());
7659 }
7660
7661 Assert(m->state == MediumState_LockedWrite);
7662
7663 Utf8Str location(m->strLocationFull);
7664
7665 /* unlock before the potentially lengthy operation */
7666 thisLock.release();
7667
7668 VDGEOMETRY geo = {0, 0, 0}; /* auto */
7669 vrc = VDResize(hdd, task.mSize, &geo, &geo, task.mVDOperationIfaces);
7670 if (RT_FAILURE(vrc))
7671 {
7672 if (vrc == VERR_NOT_SUPPORTED)
7673 throw setError(VBOX_E_NOT_SUPPORTED,
7674 tr("Compacting is not yet supported for medium '%s'"),
7675 location.c_str());
7676 else if (vrc == VERR_NOT_IMPLEMENTED)
7677 throw setError(E_NOTIMPL,
7678 tr("Compacting is not implemented, medium '%s'"),
7679 location.c_str());
7680 else
7681 throw setError(VBOX_E_FILE_ERROR,
7682 tr("Could not compact medium '%s'%s"),
7683 location.c_str(),
7684 vdError(vrc).c_str());
7685 }
7686 }
7687 catch (HRESULT aRC) { rc = aRC; }
7688
7689 VDDestroy(hdd);
7690 }
7691 catch (HRESULT aRC) { rc = aRC; }
7692
7693 /* Everything is explicitly unlocked when the task exits,
7694 * as the task destruction also destroys the media chain. */
7695
7696 return rc;
7697}
7698
7699/**
7700 * Implementation code for the "export" task.
7701 *
7702 * This only gets started from Medium::exportFile() and always runs
7703 * asynchronously. It doesn't touch anything configuration related, so
7704 * we never save the VirtualBox.xml file here.
7705 *
7706 * @param task
7707 * @return
7708 */
7709HRESULT Medium::taskExportHandler(Medium::ExportTask &task)
7710{
7711 HRESULT rc = S_OK;
7712
7713 try
7714 {
7715 /* Lock all in {parent,child} order. The lock is also used as a
7716 * signal from the task initiator (which releases it only after
7717 * RTThreadCreate()) that we can start the job. */
7718 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
7719
7720 PVBOXHDD hdd;
7721 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
7722 ComAssertRCThrow(vrc, E_FAIL);
7723
7724 try
7725 {
7726 /* Open all media in the source chain. */
7727 MediumLockList::Base::const_iterator sourceListBegin =
7728 task.mpSourceMediumLockList->GetBegin();
7729 MediumLockList::Base::const_iterator sourceListEnd =
7730 task.mpSourceMediumLockList->GetEnd();
7731 for (MediumLockList::Base::const_iterator it = sourceListBegin;
7732 it != sourceListEnd;
7733 ++it)
7734 {
7735 const MediumLock &mediumLock = *it;
7736 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
7737 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
7738
7739 /* sanity check */
7740 Assert(pMedium->m->state == MediumState_LockedRead);
7741
7742 /* Open all media in read-only mode. */
7743 vrc = VDOpen(hdd,
7744 pMedium->m->strFormat.c_str(),
7745 pMedium->m->strLocationFull.c_str(),
7746 VD_OPEN_FLAGS_READONLY,
7747 pMedium->m->vdImageIfaces);
7748 if (RT_FAILURE(vrc))
7749 throw setError(VBOX_E_FILE_ERROR,
7750 tr("Could not open the medium storage unit '%s'%s"),
7751 pMedium->m->strLocationFull.c_str(),
7752 vdError(vrc).c_str());
7753 }
7754
7755 Utf8Str targetFormat(task.mFormat->getId());
7756 Utf8Str targetLocation(task.mFilename);
7757 uint64_t capabilities = task.mFormat->getCapabilities();
7758
7759 Assert(m->state == MediumState_LockedRead);
7760
7761 /* unlock before the potentially lengthy operation */
7762 thisLock.release();
7763
7764 /* ensure the target directory exists */
7765 if (capabilities & MediumFormatCapabilities_File)
7766 {
7767 rc = VirtualBox::ensureFilePathExists(targetLocation);
7768 if (FAILED(rc))
7769 throw rc;
7770 }
7771
7772 PVBOXHDD targetHdd;
7773 vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &targetHdd);
7774 ComAssertRCThrow(vrc, E_FAIL);
7775
7776 try
7777 {
7778 vrc = VDCopy(hdd,
7779 VD_LAST_IMAGE,
7780 targetHdd,
7781 targetFormat.c_str(),
7782 targetLocation.c_str(),
7783 false /* fMoveByRename */,
7784 0 /* cbSize */,
7785 task.mVariant,
7786 NULL /* pDstUuid */,
7787 VD_OPEN_FLAGS_NORMAL | VD_OPEN_FLAGS_SEQUENTIAL,
7788 NULL /* pVDIfsOperation */,
7789 task.mVDImageIfaces,
7790 task.mVDOperationIfaces);
7791 if (RT_FAILURE(vrc))
7792 throw setError(VBOX_E_FILE_ERROR,
7793 tr("Could not create the clone medium '%s'%s"),
7794 targetLocation.c_str(), vdError(vrc).c_str());
7795 }
7796 catch (HRESULT aRC) { rc = aRC; }
7797
7798 VDDestroy(targetHdd);
7799 }
7800 catch (HRESULT aRC) { rc = aRC; }
7801
7802 VDDestroy(hdd);
7803 }
7804 catch (HRESULT aRC) { rc = aRC; }
7805
7806 /* Everything is explicitly unlocked when the task exits,
7807 * as the task destruction also destroys the source chain. */
7808
7809 /* Make sure the source chain is released early, otherwise it can
7810 * lead to deadlocks with concurrent IAppliance activities. */
7811 task.mpSourceMediumLockList->Clear();
7812
7813 return rc;
7814}
7815
7816/**
7817 * Implementation code for the "import" task.
7818 *
7819 * This only gets started from Medium::importFile() and always runs
7820 * asynchronously. It potentially touches the media registry, so we
7821 * always save the VirtualBox.xml file when we're done here.
7822 *
7823 * @param task
7824 * @return
7825 */
7826HRESULT Medium::taskImportHandler(Medium::ImportTask &task)
7827{
7828 HRESULT rcTmp = S_OK;
7829
7830 const ComObjPtr<Medium> &pParent = task.mParent;
7831
7832 bool fCreatingTarget = false;
7833
7834 uint64_t size = 0, logicalSize = 0;
7835 MediumVariant_T variant = MediumVariant_Standard;
7836 bool fGenerateUuid = false;
7837
7838 try
7839 {
7840 /* Lock all in {parent,child} order. The lock is also used as a
7841 * signal from the task initiator (which releases it only after
7842 * RTThreadCreate()) that we can start the job. */
7843 AutoMultiWriteLock2 thisLock(this, pParent COMMA_LOCKVAL_SRC_POS);
7844
7845 fCreatingTarget = m->state == MediumState_Creating;
7846
7847 /* The object may request a specific UUID (through a special form of
7848 * the setLocation() argument). Otherwise we have to generate it */
7849 Guid targetId = m->id;
7850 fGenerateUuid = targetId.isEmpty();
7851 if (fGenerateUuid)
7852 {
7853 targetId.create();
7854 /* VirtualBox::registerHardDisk() will need UUID */
7855 unconst(m->id) = targetId;
7856 }
7857
7858
7859 PVBOXHDD hdd;
7860 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
7861 ComAssertRCThrow(vrc, E_FAIL);
7862
7863 try
7864 {
7865 /* Open source medium. */
7866 vrc = VDOpen(hdd,
7867 task.mFormat->getId().c_str(),
7868 task.mFilename.c_str(),
7869 VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_SEQUENTIAL,
7870 task.mVDImageIfaces);
7871 if (RT_FAILURE(vrc))
7872 throw setError(VBOX_E_FILE_ERROR,
7873 tr("Could not open the medium storage unit '%s'%s"),
7874 task.mFilename.c_str(),
7875 vdError(vrc).c_str());
7876
7877 Utf8Str targetFormat(m->strFormat);
7878 Utf8Str targetLocation(m->strLocationFull);
7879 uint64_t capabilities = task.mFormat->getCapabilities();
7880
7881 Assert( m->state == MediumState_Creating
7882 || m->state == MediumState_LockedWrite);
7883 Assert( pParent.isNull()
7884 || pParent->m->state == MediumState_LockedRead);
7885
7886 /* unlock before the potentially lengthy operation */
7887 thisLock.release();
7888
7889 /* ensure the target directory exists */
7890 if (capabilities & MediumFormatCapabilities_File)
7891 {
7892 HRESULT rc = VirtualBox::ensureFilePathExists(targetLocation);
7893 if (FAILED(rc))
7894 throw rc;
7895 }
7896
7897 PVBOXHDD targetHdd;
7898 vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &targetHdd);
7899 ComAssertRCThrow(vrc, E_FAIL);
7900
7901 try
7902 {
7903 /* Open all media in the target chain. */
7904 MediumLockList::Base::const_iterator targetListBegin =
7905 task.mpTargetMediumLockList->GetBegin();
7906 MediumLockList::Base::const_iterator targetListEnd =
7907 task.mpTargetMediumLockList->GetEnd();
7908 for (MediumLockList::Base::const_iterator it = targetListBegin;
7909 it != targetListEnd;
7910 ++it)
7911 {
7912 const MediumLock &mediumLock = *it;
7913 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
7914
7915 /* If the target medium is not created yet there's no
7916 * reason to open it. */
7917 if (pMedium == this && fCreatingTarget)
7918 continue;
7919
7920 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
7921
7922 /* sanity check */
7923 Assert( pMedium->m->state == MediumState_LockedRead
7924 || pMedium->m->state == MediumState_LockedWrite);
7925
7926 unsigned uOpenFlags = VD_OPEN_FLAGS_NORMAL;
7927 if (pMedium->m->state != MediumState_LockedWrite)
7928 uOpenFlags = VD_OPEN_FLAGS_READONLY;
7929 if (pMedium->m->type == MediumType_Shareable)
7930 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
7931
7932 /* Open all media in appropriate mode. */
7933 vrc = VDOpen(targetHdd,
7934 pMedium->m->strFormat.c_str(),
7935 pMedium->m->strLocationFull.c_str(),
7936 uOpenFlags,
7937 pMedium->m->vdImageIfaces);
7938 if (RT_FAILURE(vrc))
7939 throw setError(VBOX_E_FILE_ERROR,
7940 tr("Could not open the medium storage unit '%s'%s"),
7941 pMedium->m->strLocationFull.c_str(),
7942 vdError(vrc).c_str());
7943 }
7944
7945 /** @todo r=klaus target isn't locked, race getting the state */
7946 vrc = VDCopy(hdd,
7947 VD_LAST_IMAGE,
7948 targetHdd,
7949 targetFormat.c_str(),
7950 (fCreatingTarget) ? targetLocation.c_str() : (char *)NULL,
7951 false /* fMoveByRename */,
7952 0 /* cbSize */,
7953 task.mVariant,
7954 targetId.raw(),
7955 VD_OPEN_FLAGS_NORMAL,
7956 NULL /* pVDIfsOperation */,
7957 m->vdImageIfaces,
7958 task.mVDOperationIfaces);
7959 if (RT_FAILURE(vrc))
7960 throw setError(VBOX_E_FILE_ERROR,
7961 tr("Could not create the clone medium '%s'%s"),
7962 targetLocation.c_str(), vdError(vrc).c_str());
7963
7964 size = VDGetFileSize(targetHdd, VD_LAST_IMAGE);
7965 logicalSize = VDGetSize(targetHdd, VD_LAST_IMAGE);
7966 unsigned uImageFlags;
7967 vrc = VDGetImageFlags(targetHdd, 0, &uImageFlags);
7968 if (RT_SUCCESS(vrc))
7969 variant = (MediumVariant_T)uImageFlags;
7970 }
7971 catch (HRESULT aRC) { rcTmp = aRC; }
7972
7973 VDDestroy(targetHdd);
7974 }
7975 catch (HRESULT aRC) { rcTmp = aRC; }
7976
7977 VDDestroy(hdd);
7978 }
7979 catch (HRESULT aRC) { rcTmp = aRC; }
7980
7981 ErrorInfoKeeper eik;
7982 MultiResult mrc(rcTmp);
7983
7984 /* Only do the parent changes for newly created media. */
7985 if (SUCCEEDED(mrc) && fCreatingTarget)
7986 {
7987 /* we set mParent & children() */
7988 AutoWriteLock alock2(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
7989
7990 Assert(m->pParent.isNull());
7991
7992 if (pParent)
7993 {
7994 /* associate the clone with the parent and deassociate
7995 * from VirtualBox */
7996 m->pParent = pParent;
7997 pParent->m->llChildren.push_back(this);
7998
7999 /* register with mVirtualBox as the last step and move to
8000 * Created state only on success (leaving an orphan file is
8001 * better than breaking media registry consistency) */
8002 eik.restore();
8003 mrc = pParent->m->pVirtualBox->registerHardDisk(this, NULL /* llRegistriesThatNeedSaving */);
8004 eik.fetch();
8005
8006 if (FAILED(mrc))
8007 /* break parent association on failure to register */
8008 this->deparent(); // removes target from parent
8009 }
8010 else
8011 {
8012 /* just register */
8013 eik.restore();
8014 mrc = m->pVirtualBox->registerHardDisk(this, NULL /* pllRegistriesThatNeedSaving */);
8015 eik.fetch();
8016 }
8017 }
8018
8019 if (fCreatingTarget)
8020 {
8021 AutoWriteLock mLock(this COMMA_LOCKVAL_SRC_POS);
8022
8023 if (SUCCEEDED(mrc))
8024 {
8025 m->state = MediumState_Created;
8026
8027 m->size = size;
8028 m->logicalSize = logicalSize;
8029 m->variant = variant;
8030 }
8031 else
8032 {
8033 /* back to NotCreated on failure */
8034 m->state = MediumState_NotCreated;
8035
8036 /* reset UUID to prevent it from being reused next time */
8037 if (fGenerateUuid)
8038 unconst(m->id).clear();
8039 }
8040 }
8041
8042 // now, at the end of this task (always asynchronous), save the settings
8043 {
8044 // save the settings
8045 GuidList llRegistriesThatNeedSaving;
8046 addToRegistryIDList(llRegistriesThatNeedSaving);
8047 /* collect multiple errors */
8048 eik.restore();
8049 mrc = m->pVirtualBox->saveRegistries(llRegistriesThatNeedSaving);
8050 eik.fetch();
8051 }
8052
8053 /* Everything is explicitly unlocked when the task exits,
8054 * as the task destruction also destroys the target chain. */
8055
8056 /* Make sure the target chain is released early, otherwise it can
8057 * lead to deadlocks with concurrent IAppliance activities. */
8058 task.mpTargetMediumLockList->Clear();
8059
8060 return mrc;
8061}
8062
8063/* 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