VirtualBox

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

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

Main: only add parent to the lock list if it isn't null

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