VirtualBox

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

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

Main/Medium: rework locking scheme to solve lock order violations and long GUI start up time caused by too much locking
Main/all: Remove the enter and leave methods from write locks, they cause hard to find locking problems. Better solve them explicitly.

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

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