VirtualBox

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

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

Main/Medium: Report errors detected when closing the medium in Medium::queryInfo. Otherwise failure to change the medium UUID goes unnoticed.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 273.2 KB
Line 
1/* $Id: MediumImpl.cpp 40259 2012-02-27 09:52:35Z 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 vrc = VDDestroy(hdd);
5672 if (RT_FAILURE(vrc))
5673 {
5674 lastAccessError = Utf8StrFmt(tr("Could not update and close the medium '%s'%s"),
5675 location.c_str(), vdError(vrc).c_str());
5676 success = false;
5677 throw S_OK;
5678 }
5679 }
5680 catch (HRESULT aRC)
5681 {
5682 rc = aRC;
5683 }
5684
5685 treeLock.acquire();
5686 alock.acquire();
5687
5688 if (isImport || fSetImageId)
5689 unconst(m->id) = mediumId;
5690
5691 if (success)
5692 {
5693 m->size = mediumSize;
5694 m->logicalSize = mediumLogicalSize;
5695 m->strLastAccessError.setNull();
5696 }
5697 else
5698 {
5699 m->strLastAccessError = lastAccessError;
5700 LogWarningFunc(("'%s' is not accessible (error='%s', rc=%Rhrc, vrc=%Rrc)\n",
5701 location.c_str(), m->strLastAccessError.c_str(),
5702 rc, vrc));
5703 }
5704
5705 /* unblock anyone waiting for the queryInfo results */
5706 qlock.release();
5707 m->queryInfoRunning = false;
5708
5709 /* Set the proper state according to the result of the check */
5710 if (success)
5711 m->preLockState = MediumState_Created;
5712 else
5713 m->preLockState = MediumState_Inaccessible;
5714
5715 HRESULT rc2;
5716 if (uOpenFlags & (VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_SHAREABLE))
5717 rc2 = UnlockRead(NULL);
5718 else
5719 rc2 = UnlockWrite(NULL);
5720 if (SUCCEEDED(rc) && FAILED(rc2))
5721 rc = rc2;
5722 if (FAILED(rc)) return rc;
5723
5724 /* If this is a base image which incorrectly has a parent UUID set,
5725 * repair the image now by zeroing the parent UUID. This is only done
5726 * when we have structural information from a config file, on import
5727 * this is not possible. If someone would accidentally call openMedium
5728 * with a diff image before the base is registered this would destroy
5729 * the diff. Not acceptable. */
5730 if (fRepairImageZeroParentUuid)
5731 {
5732 rc = LockWrite(NULL);
5733 if (FAILED(rc)) return rc;
5734
5735 alock.release();
5736
5737 try
5738 {
5739 PVBOXHDD hdd;
5740 vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
5741 ComAssertRCThrow(vrc, E_FAIL);
5742
5743 try
5744 {
5745 vrc = VDOpen(hdd,
5746 format.c_str(),
5747 location.c_str(),
5748 (uOpenFlags & ~VD_OPEN_FLAGS_READONLY) | m->uOpenFlagsDef,
5749 m->vdImageIfaces);
5750 if (RT_FAILURE(vrc))
5751 throw S_OK;
5752
5753 RTUUID zeroParentUuid;
5754 RTUuidClear(&zeroParentUuid);
5755 vrc = VDSetParentUuid(hdd, 0, &zeroParentUuid);
5756 ComAssertRCThrow(vrc, E_FAIL);
5757 }
5758 catch (HRESULT aRC)
5759 {
5760 rc = aRC;
5761 }
5762
5763 VDDestroy(hdd);
5764 }
5765 catch (HRESULT aRC)
5766 {
5767 rc = aRC;
5768 }
5769
5770 alock.acquire();
5771
5772 rc = UnlockWrite(NULL);
5773 if (SUCCEEDED(rc) && FAILED(rc2))
5774 rc = rc2;
5775 if (FAILED(rc)) return rc;
5776 }
5777
5778 return rc;
5779}
5780
5781/**
5782 * Performs extra checks if the medium can be closed and returns S_OK in
5783 * this case. Otherwise, returns a respective error message. Called by
5784 * Close() under the medium tree lock and the medium lock.
5785 *
5786 * @note Also reused by Medium::Reset().
5787 *
5788 * @note Caller must hold the media tree write lock!
5789 */
5790HRESULT Medium::canClose()
5791{
5792 Assert(m->pVirtualBox->getMediaTreeLockHandle().isWriteLockOnCurrentThread());
5793
5794 if (getChildren().size() != 0)
5795 return setError(VBOX_E_OBJECT_IN_USE,
5796 tr("Cannot close medium '%s' because it has %d child media"),
5797 m->strLocationFull.c_str(), getChildren().size());
5798
5799 return S_OK;
5800}
5801
5802/**
5803 * Unregisters this medium with mVirtualBox. Called by close() under the medium tree lock.
5804 *
5805 * @param pllRegistriesThatNeedSaving Optional pointer to a list of UUIDs that will receive the registry IDs that need saving.
5806 *
5807 * @note Caller must have locked the media tree lock for writing!
5808 */
5809HRESULT Medium::unregisterWithVirtualBox(GuidList *pllRegistriesThatNeedSaving)
5810{
5811 /* Note that we need to de-associate ourselves from the parent to let
5812 * unregisterHardDisk() properly save the registry */
5813
5814 /* we modify mParent and access children */
5815 Assert(m->pVirtualBox->getMediaTreeLockHandle().isWriteLockOnCurrentThread());
5816
5817 Medium *pParentBackup = m->pParent;
5818 AssertReturn(getChildren().size() == 0, E_FAIL);
5819 if (m->pParent)
5820 deparent();
5821
5822 HRESULT rc = m->pVirtualBox->unregisterMedium(this, pllRegistriesThatNeedSaving);
5823 if (FAILED(rc))
5824 {
5825 if (pParentBackup)
5826 {
5827 // re-associate with the parent as we are still relatives in the registry
5828 m->pParent = pParentBackup;
5829 m->pParent->m->llChildren.push_back(this);
5830 }
5831 }
5832
5833 return rc;
5834}
5835
5836/**
5837 * Sets the extended error info according to the current media state.
5838 *
5839 * @note Must be called from under this object's write or read lock.
5840 */
5841HRESULT Medium::setStateError()
5842{
5843 HRESULT rc = E_FAIL;
5844
5845 switch (m->state)
5846 {
5847 case MediumState_NotCreated:
5848 {
5849 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5850 tr("Storage for the medium '%s' is not created"),
5851 m->strLocationFull.c_str());
5852 break;
5853 }
5854 case MediumState_Created:
5855 {
5856 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5857 tr("Storage for the medium '%s' is already created"),
5858 m->strLocationFull.c_str());
5859 break;
5860 }
5861 case MediumState_LockedRead:
5862 {
5863 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5864 tr("Medium '%s' is locked for reading by another task"),
5865 m->strLocationFull.c_str());
5866 break;
5867 }
5868 case MediumState_LockedWrite:
5869 {
5870 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5871 tr("Medium '%s' is locked for writing by another task"),
5872 m->strLocationFull.c_str());
5873 break;
5874 }
5875 case MediumState_Inaccessible:
5876 {
5877 /* be in sync with Console::powerUpThread() */
5878 if (!m->strLastAccessError.isEmpty())
5879 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5880 tr("Medium '%s' is not accessible. %s"),
5881 m->strLocationFull.c_str(), m->strLastAccessError.c_str());
5882 else
5883 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5884 tr("Medium '%s' is not accessible"),
5885 m->strLocationFull.c_str());
5886 break;
5887 }
5888 case MediumState_Creating:
5889 {
5890 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5891 tr("Storage for the medium '%s' is being created"),
5892 m->strLocationFull.c_str());
5893 break;
5894 }
5895 case MediumState_Deleting:
5896 {
5897 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
5898 tr("Storage for the medium '%s' is being deleted"),
5899 m->strLocationFull.c_str());
5900 break;
5901 }
5902 default:
5903 {
5904 AssertFailed();
5905 break;
5906 }
5907 }
5908
5909 return rc;
5910}
5911
5912/**
5913 * Sets the value of m->strLocationFull. The given location must be a fully
5914 * qualified path; relative paths are not supported here.
5915 *
5916 * As a special exception, if the specified location is a file path that ends with '/'
5917 * then the file name part will be generated by this method automatically in the format
5918 * '{<uuid>}.<ext>' where <uuid> is a fresh UUID that this method will generate
5919 * and assign to this medium, and <ext> is the default extension for this
5920 * medium's storage format. Note that this procedure requires the media state to
5921 * be NotCreated and will return a failure otherwise.
5922 *
5923 * @param aLocation Location of the storage unit. If the location is a FS-path,
5924 * then it can be relative to the VirtualBox home directory.
5925 * @param aFormat Optional fallback format if it is an import and the format
5926 * cannot be determined.
5927 *
5928 * @note Must be called from under this object's write lock.
5929 */
5930HRESULT Medium::setLocation(const Utf8Str &aLocation,
5931 const Utf8Str &aFormat /* = Utf8Str::Empty */)
5932{
5933 AssertReturn(!aLocation.isEmpty(), E_FAIL);
5934
5935 AutoCaller autoCaller(this);
5936 AssertComRCReturnRC(autoCaller.rc());
5937
5938 /* formatObj may be null only when initializing from an existing path and
5939 * no format is known yet */
5940 AssertReturn( (!m->strFormat.isEmpty() && !m->formatObj.isNull())
5941 || ( autoCaller.state() == InInit
5942 && m->state != MediumState_NotCreated
5943 && m->id.isEmpty()
5944 && m->strFormat.isEmpty()
5945 && m->formatObj.isNull()),
5946 E_FAIL);
5947
5948 /* are we dealing with a new medium constructed using the existing
5949 * location? */
5950 bool isImport = m->strFormat.isEmpty();
5951
5952 if ( isImport
5953 || ( (m->formatObj->getCapabilities() & MediumFormatCapabilities_File)
5954 && !m->hostDrive))
5955 {
5956 Guid id;
5957
5958 Utf8Str locationFull(aLocation);
5959
5960 if (m->state == MediumState_NotCreated)
5961 {
5962 /* must be a file (formatObj must be already known) */
5963 Assert(m->formatObj->getCapabilities() & MediumFormatCapabilities_File);
5964
5965 if (RTPathFilename(aLocation.c_str()) == NULL)
5966 {
5967 /* no file name is given (either an empty string or ends with a
5968 * slash), generate a new UUID + file name if the state allows
5969 * this */
5970
5971 ComAssertMsgRet(!m->formatObj->getFileExtensions().empty(),
5972 ("Must be at least one extension if it is MediumFormatCapabilities_File\n"),
5973 E_FAIL);
5974
5975 Utf8Str strExt = m->formatObj->getFileExtensions().front();
5976 ComAssertMsgRet(!strExt.isEmpty(),
5977 ("Default extension must not be empty\n"),
5978 E_FAIL);
5979
5980 id.create();
5981
5982 locationFull = Utf8StrFmt("%s{%RTuuid}.%s",
5983 aLocation.c_str(), id.raw(), strExt.c_str());
5984 }
5985 }
5986
5987 // we must always have full paths now (if it refers to a file)
5988 if ( ( m->formatObj.isNull()
5989 || m->formatObj->getCapabilities() & MediumFormatCapabilities_File)
5990 && !RTPathStartsWithRoot(locationFull.c_str()))
5991 return setError(VBOX_E_FILE_ERROR,
5992 tr("The given path '%s' is not fully qualified"),
5993 locationFull.c_str());
5994
5995 /* detect the backend from the storage unit if importing */
5996 if (isImport)
5997 {
5998 VDTYPE enmType = VDTYPE_INVALID;
5999 char *backendName = NULL;
6000
6001 int vrc = VINF_SUCCESS;
6002
6003 /* is it a file? */
6004 {
6005 RTFILE file;
6006 vrc = RTFileOpen(&file, locationFull.c_str(), RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
6007 if (RT_SUCCESS(vrc))
6008 RTFileClose(file);
6009 }
6010 if (RT_SUCCESS(vrc))
6011 {
6012 vrc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
6013 locationFull.c_str(), &backendName, &enmType);
6014 }
6015 else if (vrc != VERR_FILE_NOT_FOUND && vrc != VERR_PATH_NOT_FOUND)
6016 {
6017 /* assume it's not a file, restore the original location */
6018 locationFull = aLocation;
6019 vrc = VDGetFormat(NULL /* pVDIfsDisk */, NULL /* pVDIfsImage */,
6020 locationFull.c_str(), &backendName, &enmType);
6021 }
6022
6023 if (RT_FAILURE(vrc))
6024 {
6025 if (vrc == VERR_FILE_NOT_FOUND || vrc == VERR_PATH_NOT_FOUND)
6026 return setError(VBOX_E_FILE_ERROR,
6027 tr("Could not find file for the medium '%s' (%Rrc)"),
6028 locationFull.c_str(), vrc);
6029 else if (aFormat.isEmpty())
6030 return setError(VBOX_E_IPRT_ERROR,
6031 tr("Could not get the storage format of the medium '%s' (%Rrc)"),
6032 locationFull.c_str(), vrc);
6033 else
6034 {
6035 HRESULT rc = setFormat(aFormat);
6036 /* setFormat() must not fail since we've just used the backend so
6037 * the format object must be there */
6038 AssertComRCReturnRC(rc);
6039 }
6040 }
6041 else if ( enmType == VDTYPE_INVALID
6042 || m->devType != convertToDeviceType(enmType))
6043 {
6044 /*
6045 * The user tried to use a image as a device which is not supported
6046 * by the backend.
6047 */
6048 return setError(E_FAIL,
6049 tr("The medium '%s' can't be used as the requested device type"),
6050 locationFull.c_str());
6051 }
6052 else
6053 {
6054 ComAssertRet(backendName != NULL && *backendName != '\0', E_FAIL);
6055
6056 HRESULT rc = setFormat(backendName);
6057 RTStrFree(backendName);
6058
6059 /* setFormat() must not fail since we've just used the backend so
6060 * the format object must be there */
6061 AssertComRCReturnRC(rc);
6062 }
6063 }
6064
6065 m->strLocationFull = locationFull;
6066
6067 /* is it still a file? */
6068 if ( (m->formatObj->getCapabilities() & MediumFormatCapabilities_File)
6069 && (m->state == MediumState_NotCreated)
6070 )
6071 /* assign a new UUID (this UUID will be used when calling
6072 * VDCreateBase/VDCreateDiff as a wanted UUID). Note that we
6073 * also do that if we didn't generate it to make sure it is
6074 * either generated by us or reset to null */
6075 unconst(m->id) = id;
6076 }
6077 else
6078 m->strLocationFull = aLocation;
6079
6080 return S_OK;
6081}
6082
6083/**
6084 * Checks that the format ID is valid and sets it on success.
6085 *
6086 * Note that this method will caller-reference the format object on success!
6087 * This reference must be released somewhere to let the MediumFormat object be
6088 * uninitialized.
6089 *
6090 * @note Must be called from under this object's write lock.
6091 */
6092HRESULT Medium::setFormat(const Utf8Str &aFormat)
6093{
6094 /* get the format object first */
6095 {
6096 SystemProperties *pSysProps = m->pVirtualBox->getSystemProperties();
6097 AutoReadLock propsLock(pSysProps COMMA_LOCKVAL_SRC_POS);
6098
6099 unconst(m->formatObj) = pSysProps->mediumFormat(aFormat);
6100 if (m->formatObj.isNull())
6101 return setError(E_INVALIDARG,
6102 tr("Invalid medium storage format '%s'"),
6103 aFormat.c_str());
6104
6105 /* reference the format permanently to prevent its unexpected
6106 * uninitialization */
6107 HRESULT rc = m->formatObj->addCaller();
6108 AssertComRCReturnRC(rc);
6109
6110 /* get properties (preinsert them as keys in the map). Note that the
6111 * map doesn't grow over the object life time since the set of
6112 * properties is meant to be constant. */
6113
6114 Assert(m->mapProperties.empty());
6115
6116 for (MediumFormat::PropertyList::const_iterator it = m->formatObj->getProperties().begin();
6117 it != m->formatObj->getProperties().end();
6118 ++it)
6119 {
6120 m->mapProperties.insert(std::make_pair(it->strName, Utf8Str::Empty));
6121 }
6122 }
6123
6124 unconst(m->strFormat) = aFormat;
6125
6126 return S_OK;
6127}
6128
6129/**
6130 * Converts the Medium device type to the VD type.
6131 */
6132VDTYPE Medium::convertDeviceType()
6133{
6134 VDTYPE enmType;
6135
6136 switch (m->devType)
6137 {
6138 case DeviceType_HardDisk:
6139 enmType = VDTYPE_HDD;
6140 break;
6141 case DeviceType_DVD:
6142 enmType = VDTYPE_DVD;
6143 break;
6144 case DeviceType_Floppy:
6145 enmType = VDTYPE_FLOPPY;
6146 break;
6147 default:
6148 ComAssertFailedRet(VDTYPE_INVALID);
6149 }
6150
6151 return enmType;
6152}
6153
6154/**
6155 * Converts from the VD type to the medium type.
6156 */
6157DeviceType_T Medium::convertToDeviceType(VDTYPE enmType)
6158{
6159 DeviceType_T devType;
6160
6161 switch (enmType)
6162 {
6163 case VDTYPE_HDD:
6164 devType = DeviceType_HardDisk;
6165 break;
6166 case VDTYPE_DVD:
6167 devType = DeviceType_DVD;
6168 break;
6169 case VDTYPE_FLOPPY:
6170 devType = DeviceType_Floppy;
6171 break;
6172 default:
6173 ComAssertFailedRet(DeviceType_Null);
6174 }
6175
6176 return devType;
6177}
6178
6179/**
6180 * Returns the last error message collected by the vdErrorCall callback and
6181 * resets it.
6182 *
6183 * The error message is returned prepended with a dot and a space, like this:
6184 * <code>
6185 * ". <error_text> (%Rrc)"
6186 * </code>
6187 * to make it easily appendable to a more general error message. The @c %Rrc
6188 * format string is given @a aVRC as an argument.
6189 *
6190 * If there is no last error message collected by vdErrorCall or if it is a
6191 * null or empty string, then this function returns the following text:
6192 * <code>
6193 * " (%Rrc)"
6194 * </code>
6195 *
6196 * @note Doesn't do any object locking; it is assumed that the caller makes sure
6197 * the callback isn't called by more than one thread at a time.
6198 *
6199 * @param aVRC VBox error code to use when no error message is provided.
6200 */
6201Utf8Str Medium::vdError(int aVRC)
6202{
6203 Utf8Str error;
6204
6205 if (m->vdError.isEmpty())
6206 error = Utf8StrFmt(" (%Rrc)", aVRC);
6207 else
6208 error = Utf8StrFmt(".\n%s", m->vdError.c_str());
6209
6210 m->vdError.setNull();
6211
6212 return error;
6213}
6214
6215/**
6216 * Error message callback.
6217 *
6218 * Puts the reported error message to the m->vdError field.
6219 *
6220 * @note Doesn't do any object locking; it is assumed that the caller makes sure
6221 * the callback isn't called by more than one thread at a time.
6222 *
6223 * @param pvUser The opaque data passed on container creation.
6224 * @param rc The VBox error code.
6225 * @param RT_SRC_POS_DECL Use RT_SRC_POS.
6226 * @param pszFormat Error message format string.
6227 * @param va Error message arguments.
6228 */
6229/*static*/
6230DECLCALLBACK(void) Medium::vdErrorCall(void *pvUser, int rc, RT_SRC_POS_DECL,
6231 const char *pszFormat, va_list va)
6232{
6233 NOREF(pszFile); NOREF(iLine); NOREF(pszFunction); /* RT_SRC_POS_DECL */
6234
6235 Medium *that = static_cast<Medium*>(pvUser);
6236 AssertReturnVoid(that != NULL);
6237
6238 if (that->m->vdError.isEmpty())
6239 that->m->vdError =
6240 Utf8StrFmt("%s (%Rrc)", Utf8Str(pszFormat, va).c_str(), rc);
6241 else
6242 that->m->vdError =
6243 Utf8StrFmt("%s.\n%s (%Rrc)", that->m->vdError.c_str(),
6244 Utf8Str(pszFormat, va).c_str(), rc);
6245}
6246
6247/* static */
6248DECLCALLBACK(bool) Medium::vdConfigAreKeysValid(void *pvUser,
6249 const char * /* pszzValid */)
6250{
6251 Medium *that = static_cast<Medium*>(pvUser);
6252 AssertReturn(that != NULL, false);
6253
6254 /* we always return true since the only keys we have are those found in
6255 * VDBACKENDINFO */
6256 return true;
6257}
6258
6259/* static */
6260DECLCALLBACK(int) Medium::vdConfigQuerySize(void *pvUser,
6261 const char *pszName,
6262 size_t *pcbValue)
6263{
6264 AssertReturn(VALID_PTR(pcbValue), VERR_INVALID_POINTER);
6265
6266 Medium *that = static_cast<Medium*>(pvUser);
6267 AssertReturn(that != NULL, VERR_GENERAL_FAILURE);
6268
6269 settings::StringsMap::const_iterator it = that->m->mapProperties.find(Utf8Str(pszName));
6270 if (it == that->m->mapProperties.end())
6271 return VERR_CFGM_VALUE_NOT_FOUND;
6272
6273 /* we interpret null values as "no value" in Medium */
6274 if (it->second.isEmpty())
6275 return VERR_CFGM_VALUE_NOT_FOUND;
6276
6277 *pcbValue = it->second.length() + 1 /* include terminator */;
6278
6279 return VINF_SUCCESS;
6280}
6281
6282/* static */
6283DECLCALLBACK(int) Medium::vdConfigQuery(void *pvUser,
6284 const char *pszName,
6285 char *pszValue,
6286 size_t cchValue)
6287{
6288 AssertReturn(VALID_PTR(pszValue), VERR_INVALID_POINTER);
6289
6290 Medium *that = static_cast<Medium*>(pvUser);
6291 AssertReturn(that != NULL, VERR_GENERAL_FAILURE);
6292
6293 settings::StringsMap::const_iterator it = that->m->mapProperties.find(Utf8Str(pszName));
6294 if (it == that->m->mapProperties.end())
6295 return VERR_CFGM_VALUE_NOT_FOUND;
6296
6297 /* we interpret null values as "no value" in Medium */
6298 if (it->second.isEmpty())
6299 return VERR_CFGM_VALUE_NOT_FOUND;
6300
6301 const Utf8Str &value = it->second;
6302 if (value.length() >= cchValue)
6303 return VERR_CFGM_NOT_ENOUGH_SPACE;
6304
6305 memcpy(pszValue, value.c_str(), value.length() + 1);
6306
6307 return VINF_SUCCESS;
6308}
6309
6310DECLCALLBACK(int) Medium::vdTcpSocketCreate(uint32_t fFlags, PVDSOCKET pSock)
6311{
6312 PVDSOCKETINT pSocketInt = NULL;
6313
6314 if ((fFlags & VD_INTERFACETCPNET_CONNECT_EXTENDED_SELECT) != 0)
6315 return VERR_NOT_SUPPORTED;
6316
6317 pSocketInt = (PVDSOCKETINT)RTMemAllocZ(sizeof(VDSOCKETINT));
6318 if (!pSocketInt)
6319 return VERR_NO_MEMORY;
6320
6321 pSocketInt->hSocket = NIL_RTSOCKET;
6322 *pSock = pSocketInt;
6323 return VINF_SUCCESS;
6324}
6325
6326DECLCALLBACK(int) Medium::vdTcpSocketDestroy(VDSOCKET Sock)
6327{
6328 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6329
6330 if (pSocketInt->hSocket != NIL_RTSOCKET)
6331 RTTcpClientCloseEx(pSocketInt->hSocket, false /*fGracefulShutdown*/);
6332
6333 RTMemFree(pSocketInt);
6334
6335 return VINF_SUCCESS;
6336}
6337
6338DECLCALLBACK(int) Medium::vdTcpClientConnect(VDSOCKET Sock, const char *pszAddress, uint32_t uPort)
6339{
6340 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6341
6342 return RTTcpClientConnect(pszAddress, uPort, &pSocketInt->hSocket);
6343}
6344
6345DECLCALLBACK(int) Medium::vdTcpClientClose(VDSOCKET Sock)
6346{
6347 int rc = VINF_SUCCESS;
6348 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6349
6350 rc = RTTcpClientCloseEx(pSocketInt->hSocket, false /*fGracefulShutdown*/);
6351 pSocketInt->hSocket = NIL_RTSOCKET;
6352 return rc;
6353}
6354
6355DECLCALLBACK(bool) Medium::vdTcpIsClientConnected(VDSOCKET Sock)
6356{
6357 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6358 return pSocketInt->hSocket != NIL_RTSOCKET;
6359}
6360
6361DECLCALLBACK(int) Medium::vdTcpSelectOne(VDSOCKET Sock, RTMSINTERVAL cMillies)
6362{
6363 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6364 return RTTcpSelectOne(pSocketInt->hSocket, cMillies);
6365}
6366
6367DECLCALLBACK(int) Medium::vdTcpRead(VDSOCKET Sock, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
6368{
6369 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6370 return RTTcpRead(pSocketInt->hSocket, pvBuffer, cbBuffer, pcbRead);
6371}
6372
6373DECLCALLBACK(int) Medium::vdTcpWrite(VDSOCKET Sock, const void *pvBuffer, size_t cbBuffer)
6374{
6375 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6376 return RTTcpWrite(pSocketInt->hSocket, pvBuffer, cbBuffer);
6377}
6378
6379DECLCALLBACK(int) Medium::vdTcpSgWrite(VDSOCKET Sock, PCRTSGBUF pSgBuf)
6380{
6381 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6382 return RTTcpSgWrite(pSocketInt->hSocket, pSgBuf);
6383}
6384
6385DECLCALLBACK(int) Medium::vdTcpFlush(VDSOCKET Sock)
6386{
6387 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6388 return RTTcpFlush(pSocketInt->hSocket);
6389}
6390
6391DECLCALLBACK(int) Medium::vdTcpSetSendCoalescing(VDSOCKET Sock, bool fEnable)
6392{
6393 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6394 return RTTcpSetSendCoalescing(pSocketInt->hSocket, fEnable);
6395}
6396
6397DECLCALLBACK(int) Medium::vdTcpGetLocalAddress(VDSOCKET Sock, PRTNETADDR pAddr)
6398{
6399 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6400 return RTTcpGetLocalAddress(pSocketInt->hSocket, pAddr);
6401}
6402
6403DECLCALLBACK(int) Medium::vdTcpGetPeerAddress(VDSOCKET Sock, PRTNETADDR pAddr)
6404{
6405 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
6406 return RTTcpGetPeerAddress(pSocketInt->hSocket, pAddr);
6407}
6408
6409/**
6410 * Starts a new thread driven by the appropriate Medium::Task::handler() method.
6411 *
6412 * @note When the task is executed by this method, IProgress::notifyComplete()
6413 * is automatically called for the progress object associated with this
6414 * task when the task is finished to signal the operation completion for
6415 * other threads asynchronously waiting for it.
6416 */
6417HRESULT Medium::startThread(Medium::Task *pTask)
6418{
6419#ifdef VBOX_WITH_MAIN_LOCK_VALIDATION
6420 /* Extreme paranoia: The calling thread should not hold the medium
6421 * tree lock or any medium lock. Since there is no separate lock class
6422 * for medium objects be even more strict: no other object locks. */
6423 Assert(!AutoLockHoldsLocksInClass(LOCKCLASS_LISTOFMEDIA));
6424 Assert(!AutoLockHoldsLocksInClass(getLockingClass()));
6425#endif
6426
6427 /// @todo use a more descriptive task name
6428 int vrc = RTThreadCreate(NULL, Medium::Task::fntMediumTask, pTask,
6429 0, RTTHREADTYPE_MAIN_HEAVY_WORKER, 0,
6430 "Medium::Task");
6431 if (RT_FAILURE(vrc))
6432 {
6433 delete pTask;
6434 return setError(E_FAIL, "Could not create Medium::Task thread (%Rrc)\n", vrc);
6435 }
6436
6437 return S_OK;
6438}
6439
6440/**
6441 * Runs Medium::Task::handler() on the current thread instead of creating
6442 * a new one.
6443 *
6444 * This call implies that it is made on another temporary thread created for
6445 * some asynchronous task. Avoid calling it from a normal thread since the task
6446 * operations are potentially lengthy and will block the calling thread in this
6447 * case.
6448 *
6449 * @note When the task is executed by this method, IProgress::notifyComplete()
6450 * is not called for the progress object associated with this task when
6451 * the task is finished. Instead, the result of the operation is returned
6452 * by this method directly and it's the caller's responsibility to
6453 * complete the progress object in this case.
6454 */
6455HRESULT Medium::runNow(Medium::Task *pTask,
6456 GuidList *pllRegistriesThatNeedSaving)
6457{
6458#ifdef VBOX_WITH_MAIN_LOCK_VALIDATION
6459 /* Extreme paranoia: The calling thread should not hold the medium
6460 * tree lock or any medium lock. Since there is no separate lock class
6461 * for medium objects be even more strict: no other object locks. */
6462 Assert(!AutoLockHoldsLocksInClass(LOCKCLASS_LISTOFMEDIA));
6463 Assert(!AutoLockHoldsLocksInClass(getLockingClass()));
6464#endif
6465
6466 pTask->m_pllRegistriesThatNeedSaving = pllRegistriesThatNeedSaving;
6467
6468 /* NIL_RTTHREAD indicates synchronous call. */
6469 return (HRESULT)Medium::Task::fntMediumTask(NIL_RTTHREAD, pTask);
6470}
6471
6472/**
6473 * Implementation code for the "create base" task.
6474 *
6475 * This only gets started from Medium::CreateBaseStorage() and always runs
6476 * asynchronously. As a result, we always save the VirtualBox.xml file when
6477 * we're done here.
6478 *
6479 * @param task
6480 * @return
6481 */
6482HRESULT Medium::taskCreateBaseHandler(Medium::CreateBaseTask &task)
6483{
6484 HRESULT rc = S_OK;
6485
6486 /* these parameters we need after creation */
6487 uint64_t size = 0, logicalSize = 0;
6488 MediumVariant_T variant = MediumVariant_Standard;
6489 bool fGenerateUuid = false;
6490
6491 try
6492 {
6493 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6494
6495 /* The object may request a specific UUID (through a special form of
6496 * the setLocation() argument). Otherwise we have to generate it */
6497 Guid id = m->id;
6498 fGenerateUuid = id.isEmpty();
6499 if (fGenerateUuid)
6500 {
6501 id.create();
6502 /* VirtualBox::registerMedium() will need UUID */
6503 unconst(m->id) = id;
6504 }
6505
6506 Utf8Str format(m->strFormat);
6507 Utf8Str location(m->strLocationFull);
6508 uint64_t capabilities = m->formatObj->getCapabilities();
6509 ComAssertThrow(capabilities & ( MediumFormatCapabilities_CreateFixed
6510 | MediumFormatCapabilities_CreateDynamic), E_FAIL);
6511 Assert(m->state == MediumState_Creating);
6512
6513 PVBOXHDD hdd;
6514 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
6515 ComAssertRCThrow(vrc, E_FAIL);
6516
6517 /* unlock before the potentially lengthy operation */
6518 thisLock.release();
6519
6520 try
6521 {
6522 /* ensure the directory exists */
6523 if (capabilities & MediumFormatCapabilities_File)
6524 {
6525 rc = VirtualBox::ensureFilePathExists(location, !(task.mVariant & MediumVariant_NoCreateDir) /* fCreate */);
6526 if (FAILED(rc))
6527 throw rc;
6528 }
6529
6530 VDGEOMETRY geo = { 0, 0, 0 }; /* auto-detect */
6531
6532 vrc = VDCreateBase(hdd,
6533 format.c_str(),
6534 location.c_str(),
6535 task.mSize,
6536 task.mVariant & ~MediumVariant_NoCreateDir,
6537 NULL,
6538 &geo,
6539 &geo,
6540 id.raw(),
6541 VD_OPEN_FLAGS_NORMAL | m->uOpenFlagsDef,
6542 m->vdImageIfaces,
6543 task.mVDOperationIfaces);
6544 if (RT_FAILURE(vrc))
6545 throw setError(VBOX_E_FILE_ERROR,
6546 tr("Could not create the medium storage unit '%s'%s"),
6547 location.c_str(), vdError(vrc).c_str());
6548
6549 size = VDGetFileSize(hdd, 0);
6550 logicalSize = VDGetSize(hdd, 0);
6551 unsigned uImageFlags;
6552 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
6553 if (RT_SUCCESS(vrc))
6554 variant = (MediumVariant_T)uImageFlags;
6555 }
6556 catch (HRESULT aRC) { rc = aRC; }
6557
6558 VDDestroy(hdd);
6559 }
6560 catch (HRESULT aRC) { rc = aRC; }
6561
6562 if (SUCCEEDED(rc))
6563 {
6564 /* register with mVirtualBox as the last step and move to
6565 * Created state only on success (leaving an orphan file is
6566 * better than breaking media registry consistency) */
6567 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
6568 ComObjPtr<Medium> pMedium;
6569 rc = m->pVirtualBox->registerMedium(this, &pMedium, DeviceType_HardDisk,
6570 NULL /* pllRegistriesThatNeedSaving */);
6571 Assert(this == pMedium);
6572 }
6573
6574 // re-acquire the lock before changing state
6575 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6576
6577 if (SUCCEEDED(rc))
6578 {
6579 m->state = MediumState_Created;
6580
6581 m->size = size;
6582 m->logicalSize = logicalSize;
6583 m->variant = variant;
6584 }
6585 else
6586 {
6587 /* back to NotCreated on failure */
6588 m->state = MediumState_NotCreated;
6589
6590 /* reset UUID to prevent it from being reused next time */
6591 if (fGenerateUuid)
6592 unconst(m->id).clear();
6593 }
6594
6595 return rc;
6596}
6597
6598/**
6599 * Implementation code for the "create diff" task.
6600 *
6601 * This task always gets started from Medium::createDiffStorage() and can run
6602 * synchronously or asynchronously depending on the "wait" parameter passed to
6603 * that function. If we run synchronously, the caller expects the bool
6604 * *pfNeedsGlobalSaveSettings to be set before returning; otherwise (in asynchronous
6605 * mode), we save the settings ourselves.
6606 *
6607 * @param task
6608 * @return
6609 */
6610HRESULT Medium::taskCreateDiffHandler(Medium::CreateDiffTask &task)
6611{
6612 HRESULT rcTmp = S_OK;
6613
6614 const ComObjPtr<Medium> &pTarget = task.mTarget;
6615
6616 uint64_t size = 0, logicalSize = 0;
6617 MediumVariant_T variant = MediumVariant_Standard;
6618 bool fGenerateUuid = false;
6619
6620 GuidList llRegistriesThatNeedSaving; // gets copied to task pointer later in synchronous mode
6621
6622 try
6623 {
6624 /* Lock both in {parent,child} order. */
6625 AutoMultiWriteLock2 mediaLock(this, pTarget COMMA_LOCKVAL_SRC_POS);
6626
6627 /* The object may request a specific UUID (through a special form of
6628 * the setLocation() argument). Otherwise we have to generate it */
6629 Guid targetId = pTarget->m->id;
6630 fGenerateUuid = targetId.isEmpty();
6631 if (fGenerateUuid)
6632 {
6633 targetId.create();
6634 /* VirtualBox::registerMedium() will need UUID */
6635 unconst(pTarget->m->id) = targetId;
6636 }
6637
6638 Guid id = m->id;
6639
6640 Utf8Str targetFormat(pTarget->m->strFormat);
6641 Utf8Str targetLocation(pTarget->m->strLocationFull);
6642 uint64_t capabilities = pTarget->m->formatObj->getCapabilities();
6643 ComAssertThrow(capabilities & MediumFormatCapabilities_CreateDynamic, E_FAIL);
6644
6645 Assert(pTarget->m->state == MediumState_Creating);
6646 Assert(m->state == MediumState_LockedRead);
6647
6648 PVBOXHDD hdd;
6649 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
6650 ComAssertRCThrow(vrc, E_FAIL);
6651
6652 /* the two media are now protected by their non-default states;
6653 * unlock the media before the potentially lengthy operation */
6654 mediaLock.release();
6655
6656 try
6657 {
6658 /* Open all media in the target chain but the last. */
6659 MediumLockList::Base::const_iterator targetListBegin =
6660 task.mpMediumLockList->GetBegin();
6661 MediumLockList::Base::const_iterator targetListEnd =
6662 task.mpMediumLockList->GetEnd();
6663 for (MediumLockList::Base::const_iterator it = targetListBegin;
6664 it != targetListEnd;
6665 ++it)
6666 {
6667 const MediumLock &mediumLock = *it;
6668 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
6669
6670 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
6671
6672 /* Skip over the target diff medium */
6673 if (pMedium->m->state == MediumState_Creating)
6674 continue;
6675
6676 /* sanity check */
6677 Assert(pMedium->m->state == MediumState_LockedRead);
6678
6679 /* Open all media in appropriate mode. */
6680 vrc = VDOpen(hdd,
6681 pMedium->m->strFormat.c_str(),
6682 pMedium->m->strLocationFull.c_str(),
6683 VD_OPEN_FLAGS_READONLY | m->uOpenFlagsDef,
6684 pMedium->m->vdImageIfaces);
6685 if (RT_FAILURE(vrc))
6686 throw setError(VBOX_E_FILE_ERROR,
6687 tr("Could not open the medium storage unit '%s'%s"),
6688 pMedium->m->strLocationFull.c_str(),
6689 vdError(vrc).c_str());
6690 }
6691
6692 /* ensure the target directory exists */
6693 if (capabilities & MediumFormatCapabilities_File)
6694 {
6695 HRESULT rc = VirtualBox::ensureFilePathExists(targetLocation, !(task.mVariant & MediumVariant_NoCreateDir) /* fCreate */);
6696 if (FAILED(rc))
6697 throw rc;
6698 }
6699
6700 vrc = VDCreateDiff(hdd,
6701 targetFormat.c_str(),
6702 targetLocation.c_str(),
6703 (task.mVariant & ~MediumVariant_NoCreateDir) | VD_IMAGE_FLAGS_DIFF,
6704 NULL,
6705 targetId.raw(),
6706 id.raw(),
6707 VD_OPEN_FLAGS_NORMAL | m->uOpenFlagsDef,
6708 pTarget->m->vdImageIfaces,
6709 task.mVDOperationIfaces);
6710 if (RT_FAILURE(vrc))
6711 throw setError(VBOX_E_FILE_ERROR,
6712 tr("Could not create the differencing medium storage unit '%s'%s"),
6713 targetLocation.c_str(), vdError(vrc).c_str());
6714
6715 size = VDGetFileSize(hdd, VD_LAST_IMAGE);
6716 logicalSize = VDGetSize(hdd, VD_LAST_IMAGE);
6717 unsigned uImageFlags;
6718 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
6719 if (RT_SUCCESS(vrc))
6720 variant = (MediumVariant_T)uImageFlags;
6721 }
6722 catch (HRESULT aRC) { rcTmp = aRC; }
6723
6724 VDDestroy(hdd);
6725 }
6726 catch (HRESULT aRC) { rcTmp = aRC; }
6727
6728 MultiResult mrc(rcTmp);
6729
6730 if (SUCCEEDED(mrc))
6731 {
6732 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
6733
6734 Assert(pTarget->m->pParent.isNull());
6735
6736 /* associate the child with the parent */
6737 pTarget->m->pParent = this;
6738 m->llChildren.push_back(pTarget);
6739
6740 /** @todo r=klaus neither target nor base() are locked,
6741 * potential race! */
6742 /* diffs for immutable media are auto-reset by default */
6743 pTarget->m->autoReset = (getBase()->m->type == MediumType_Immutable);
6744
6745 /* register with mVirtualBox as the last step and move to
6746 * Created state only on success (leaving an orphan file is
6747 * better than breaking media registry consistency) */
6748 ComObjPtr<Medium> pMedium;
6749 mrc = m->pVirtualBox->registerMedium(pTarget, &pMedium, DeviceType_HardDisk,
6750 &llRegistriesThatNeedSaving);
6751 Assert(pTarget == pMedium);
6752
6753 if (FAILED(mrc))
6754 /* break the parent association on failure to register */
6755 deparent();
6756 }
6757
6758 AutoMultiWriteLock2 mediaLock(this, pTarget COMMA_LOCKVAL_SRC_POS);
6759
6760 if (SUCCEEDED(mrc))
6761 {
6762 pTarget->m->state = MediumState_Created;
6763
6764 pTarget->m->size = size;
6765 pTarget->m->logicalSize = logicalSize;
6766 pTarget->m->variant = variant;
6767 }
6768 else
6769 {
6770 /* back to NotCreated on failure */
6771 pTarget->m->state = MediumState_NotCreated;
6772
6773 pTarget->m->autoReset = false;
6774
6775 /* reset UUID to prevent it from being reused next time */
6776 if (fGenerateUuid)
6777 unconst(pTarget->m->id).clear();
6778 }
6779
6780 // deregister the task registered in createDiffStorage()
6781 Assert(m->numCreateDiffTasks != 0);
6782 --m->numCreateDiffTasks;
6783
6784 if (task.isAsync())
6785 {
6786 mediaLock.release();
6787 mrc = m->pVirtualBox->saveRegistries(llRegistriesThatNeedSaving);
6788 }
6789 else
6790 // synchronous mode: report save settings result to caller
6791 if (task.m_pllRegistriesThatNeedSaving)
6792 *task.m_pllRegistriesThatNeedSaving = llRegistriesThatNeedSaving;
6793
6794 /* Note that in sync mode, it's the caller's responsibility to
6795 * unlock the medium. */
6796
6797 return mrc;
6798}
6799
6800/**
6801 * Implementation code for the "merge" task.
6802 *
6803 * This task always gets started from Medium::mergeTo() and can run
6804 * synchronously or asynchronously depending on the "wait" parameter passed to
6805 * that function. If we run synchronously, the caller expects the bool
6806 * *pfNeedsGlobalSaveSettings to be set before returning; otherwise (in asynchronous
6807 * mode), we save the settings ourselves.
6808 *
6809 * @param task
6810 * @return
6811 */
6812HRESULT Medium::taskMergeHandler(Medium::MergeTask &task)
6813{
6814 HRESULT rcTmp = S_OK;
6815
6816 const ComObjPtr<Medium> &pTarget = task.mTarget;
6817
6818 try
6819 {
6820 PVBOXHDD hdd;
6821 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
6822 ComAssertRCThrow(vrc, E_FAIL);
6823
6824 try
6825 {
6826 // Similar code appears in SessionMachine::onlineMergeMedium, so
6827 // if you make any changes below check whether they are applicable
6828 // in that context as well.
6829
6830 unsigned uTargetIdx = VD_LAST_IMAGE;
6831 unsigned uSourceIdx = VD_LAST_IMAGE;
6832 /* Open all media in the chain. */
6833 MediumLockList::Base::iterator lockListBegin =
6834 task.mpMediumLockList->GetBegin();
6835 MediumLockList::Base::iterator lockListEnd =
6836 task.mpMediumLockList->GetEnd();
6837 unsigned i = 0;
6838 for (MediumLockList::Base::iterator it = lockListBegin;
6839 it != lockListEnd;
6840 ++it)
6841 {
6842 MediumLock &mediumLock = *it;
6843 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
6844
6845 if (pMedium == this)
6846 uSourceIdx = i;
6847 else if (pMedium == pTarget)
6848 uTargetIdx = i;
6849
6850 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
6851
6852 /*
6853 * complex sanity (sane complexity)
6854 *
6855 * The current medium must be in the Deleting (medium is merged)
6856 * or LockedRead (parent medium) state if it is not the target.
6857 * If it is the target it must be in the LockedWrite state.
6858 */
6859 Assert( ( pMedium != pTarget
6860 && ( pMedium->m->state == MediumState_Deleting
6861 || pMedium->m->state == MediumState_LockedRead))
6862 || ( pMedium == pTarget
6863 && pMedium->m->state == MediumState_LockedWrite));
6864
6865 /*
6866 * Medium must be the target, in the LockedRead state
6867 * or Deleting state where it is not allowed to be attached
6868 * to a virtual machine.
6869 */
6870 Assert( pMedium == pTarget
6871 || pMedium->m->state == MediumState_LockedRead
6872 || ( pMedium->m->backRefs.size() == 0
6873 && pMedium->m->state == MediumState_Deleting));
6874 /* The source medium must be in Deleting state. */
6875 Assert( pMedium != this
6876 || pMedium->m->state == MediumState_Deleting);
6877
6878 unsigned uOpenFlags = VD_OPEN_FLAGS_NORMAL;
6879
6880 if ( pMedium->m->state == MediumState_LockedRead
6881 || pMedium->m->state == MediumState_Deleting)
6882 uOpenFlags = VD_OPEN_FLAGS_READONLY;
6883 if (pMedium->m->type == MediumType_Shareable)
6884 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
6885
6886 /* Open the medium */
6887 vrc = VDOpen(hdd,
6888 pMedium->m->strFormat.c_str(),
6889 pMedium->m->strLocationFull.c_str(),
6890 uOpenFlags | m->uOpenFlagsDef,
6891 pMedium->m->vdImageIfaces);
6892 if (RT_FAILURE(vrc))
6893 throw vrc;
6894
6895 i++;
6896 }
6897
6898 ComAssertThrow( uSourceIdx != VD_LAST_IMAGE
6899 && uTargetIdx != VD_LAST_IMAGE, E_FAIL);
6900
6901 vrc = VDMerge(hdd, uSourceIdx, uTargetIdx,
6902 task.mVDOperationIfaces);
6903 if (RT_FAILURE(vrc))
6904 throw vrc;
6905
6906 /* update parent UUIDs */
6907 if (!task.mfMergeForward)
6908 {
6909 /* we need to update UUIDs of all source's children
6910 * which cannot be part of the container at once so
6911 * add each one in there individually */
6912 if (task.mChildrenToReparent.size() > 0)
6913 {
6914 for (MediaList::const_iterator it = task.mChildrenToReparent.begin();
6915 it != task.mChildrenToReparent.end();
6916 ++it)
6917 {
6918 /* VD_OPEN_FLAGS_INFO since UUID is wrong yet */
6919 vrc = VDOpen(hdd,
6920 (*it)->m->strFormat.c_str(),
6921 (*it)->m->strLocationFull.c_str(),
6922 VD_OPEN_FLAGS_INFO | m->uOpenFlagsDef,
6923 (*it)->m->vdImageIfaces);
6924 if (RT_FAILURE(vrc))
6925 throw vrc;
6926
6927 vrc = VDSetParentUuid(hdd, VD_LAST_IMAGE,
6928 pTarget->m->id.raw());
6929 if (RT_FAILURE(vrc))
6930 throw vrc;
6931
6932 vrc = VDClose(hdd, false /* fDelete */);
6933 if (RT_FAILURE(vrc))
6934 throw vrc;
6935
6936 (*it)->UnlockWrite(NULL);
6937 }
6938 }
6939 }
6940 }
6941 catch (HRESULT aRC) { rcTmp = aRC; }
6942 catch (int aVRC)
6943 {
6944 rcTmp = setError(VBOX_E_FILE_ERROR,
6945 tr("Could not merge the medium '%s' to '%s'%s"),
6946 m->strLocationFull.c_str(),
6947 pTarget->m->strLocationFull.c_str(),
6948 vdError(aVRC).c_str());
6949 }
6950
6951 VDDestroy(hdd);
6952 }
6953 catch (HRESULT aRC) { rcTmp = aRC; }
6954
6955 ErrorInfoKeeper eik;
6956 MultiResult mrc(rcTmp);
6957 HRESULT rc2;
6958
6959 if (SUCCEEDED(mrc))
6960 {
6961 /* all media but the target were successfully deleted by
6962 * VDMerge; reparent the last one and uninitialize deleted media. */
6963
6964 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
6965
6966 if (task.mfMergeForward)
6967 {
6968 /* first, unregister the target since it may become a base
6969 * medium which needs re-registration */
6970 rc2 = m->pVirtualBox->unregisterMedium(pTarget, NULL /*pfNeedsGlobalSaveSettings*/);
6971 AssertComRC(rc2);
6972
6973 /* then, reparent it and disconnect the deleted branch at
6974 * both ends (chain->parent() is source's parent) */
6975 pTarget->deparent();
6976 pTarget->m->pParent = task.mParentForTarget;
6977 if (pTarget->m->pParent)
6978 {
6979 pTarget->m->pParent->m->llChildren.push_back(pTarget);
6980 deparent();
6981 }
6982
6983 /* then, register again */
6984 ComObjPtr<Medium> pMedium;
6985 rc2 = m->pVirtualBox->registerMedium(pTarget, &pMedium,
6986 DeviceType_HardDisk,
6987 NULL /* pllRegistriesThatNeedSaving */ );
6988 AssertComRC(rc2);
6989 }
6990 else
6991 {
6992 Assert(pTarget->getChildren().size() == 1);
6993 Medium *targetChild = pTarget->getChildren().front();
6994
6995 /* disconnect the deleted branch at the elder end */
6996 targetChild->deparent();
6997
6998 /* reparent source's children and disconnect the deleted
6999 * branch at the younger end */
7000 if (task.mChildrenToReparent.size() > 0)
7001 {
7002 /* obey {parent,child} lock order */
7003 AutoWriteLock sourceLock(this COMMA_LOCKVAL_SRC_POS);
7004
7005 for (MediaList::const_iterator it = task.mChildrenToReparent.begin();
7006 it != task.mChildrenToReparent.end();
7007 it++)
7008 {
7009 Medium *pMedium = *it;
7010 AutoWriteLock childLock(pMedium COMMA_LOCKVAL_SRC_POS);
7011
7012 pMedium->deparent(); // removes pMedium from source
7013 pMedium->setParent(pTarget);
7014 }
7015 }
7016 }
7017
7018 /* unregister and uninitialize all media removed by the merge */
7019 MediumLockList::Base::iterator lockListBegin =
7020 task.mpMediumLockList->GetBegin();
7021 MediumLockList::Base::iterator lockListEnd =
7022 task.mpMediumLockList->GetEnd();
7023 for (MediumLockList::Base::iterator it = lockListBegin;
7024 it != lockListEnd;
7025 )
7026 {
7027 MediumLock &mediumLock = *it;
7028 /* Create a real copy of the medium pointer, as the medium
7029 * lock deletion below would invalidate the referenced object. */
7030 const ComObjPtr<Medium> pMedium = mediumLock.GetMedium();
7031
7032 /* The target and all media not merged (readonly) are skipped */
7033 if ( pMedium == pTarget
7034 || pMedium->m->state == MediumState_LockedRead)
7035 {
7036 ++it;
7037 continue;
7038 }
7039
7040 rc2 = pMedium->m->pVirtualBox->unregisterMedium(pMedium,
7041 NULL /*pfNeedsGlobalSaveSettings*/);
7042 AssertComRC(rc2);
7043
7044 /* now, uninitialize the deleted medium (note that
7045 * due to the Deleting state, uninit() will not touch
7046 * the parent-child relationship so we need to
7047 * uninitialize each disk individually) */
7048
7049 /* note that the operation initiator medium (which is
7050 * normally also the source medium) is a special case
7051 * -- there is one more caller added by Task to it which
7052 * we must release. Also, if we are in sync mode, the
7053 * caller may still hold an AutoCaller instance for it
7054 * and therefore we cannot uninit() it (it's therefore
7055 * the caller's responsibility) */
7056 if (pMedium == this)
7057 {
7058 Assert(getChildren().size() == 0);
7059 Assert(m->backRefs.size() == 0);
7060 task.mMediumCaller.release();
7061 }
7062
7063 /* Delete the medium lock list entry, which also releases the
7064 * caller added by MergeChain before uninit() and updates the
7065 * iterator to point to the right place. */
7066 rc2 = task.mpMediumLockList->RemoveByIterator(it);
7067 AssertComRC(rc2);
7068
7069 if (task.isAsync() || pMedium != this)
7070 pMedium->uninit();
7071 }
7072 }
7073
7074 if (task.isAsync())
7075 {
7076 // in asynchronous mode, save settings now
7077 GuidList llRegistriesThatNeedSaving;
7078 addToRegistryIDList(llRegistriesThatNeedSaving);
7079 /* collect multiple errors */
7080 eik.restore();
7081 mrc = m->pVirtualBox->saveRegistries(llRegistriesThatNeedSaving);
7082 eik.fetch();
7083 }
7084 else
7085 // synchronous mode: report save settings result to caller
7086 if (task.m_pllRegistriesThatNeedSaving)
7087 pTarget->addToRegistryIDList(*task.m_pllRegistriesThatNeedSaving);
7088
7089 if (FAILED(mrc))
7090 {
7091 /* Here we come if either VDMerge() failed (in which case we
7092 * assume that it tried to do everything to make a further
7093 * retry possible -- e.g. not deleted intermediate media
7094 * and so on) or VirtualBox::saveRegistries() failed (where we
7095 * should have the original tree but with intermediate storage
7096 * units deleted by VDMerge()). We have to only restore states
7097 * (through the MergeChain dtor) unless we are run synchronously
7098 * in which case it's the responsibility of the caller as stated
7099 * in the mergeTo() docs. The latter also implies that we
7100 * don't own the merge chain, so release it in this case. */
7101 if (task.isAsync())
7102 {
7103 Assert(task.mChildrenToReparent.size() == 0);
7104 cancelMergeTo(task.mChildrenToReparent, task.mpMediumLockList);
7105 }
7106 }
7107
7108 return mrc;
7109}
7110
7111/**
7112 * Implementation code for the "clone" task.
7113 *
7114 * This only gets started from Medium::CloneTo() and always runs asynchronously.
7115 * As a result, we always save the VirtualBox.xml file when we're done here.
7116 *
7117 * @param task
7118 * @return
7119 */
7120HRESULT Medium::taskCloneHandler(Medium::CloneTask &task)
7121{
7122 HRESULT rcTmp = S_OK;
7123
7124 const ComObjPtr<Medium> &pTarget = task.mTarget;
7125 const ComObjPtr<Medium> &pParent = task.mParent;
7126
7127 bool fCreatingTarget = false;
7128
7129 uint64_t size = 0, logicalSize = 0;
7130 MediumVariant_T variant = MediumVariant_Standard;
7131 bool fGenerateUuid = false;
7132
7133 try
7134 {
7135 /* Lock all in {parent,child} order. The lock is also used as a
7136 * signal from the task initiator (which releases it only after
7137 * RTThreadCreate()) that we can start the job. */
7138 AutoMultiWriteLock3 thisLock(this, pTarget, pParent COMMA_LOCKVAL_SRC_POS);
7139
7140 fCreatingTarget = pTarget->m->state == MediumState_Creating;
7141
7142 /* The object may request a specific UUID (through a special form of
7143 * the setLocation() argument). Otherwise we have to generate it */
7144 Guid targetId = pTarget->m->id;
7145 fGenerateUuid = targetId.isEmpty();
7146 if (fGenerateUuid)
7147 {
7148 targetId.create();
7149 /* VirtualBox::registerHardDisk() will need UUID */
7150 unconst(pTarget->m->id) = targetId;
7151 }
7152
7153 PVBOXHDD hdd;
7154 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
7155 ComAssertRCThrow(vrc, E_FAIL);
7156
7157 try
7158 {
7159 /* Open all media in the source chain. */
7160 MediumLockList::Base::const_iterator sourceListBegin =
7161 task.mpSourceMediumLockList->GetBegin();
7162 MediumLockList::Base::const_iterator sourceListEnd =
7163 task.mpSourceMediumLockList->GetEnd();
7164 for (MediumLockList::Base::const_iterator it = sourceListBegin;
7165 it != sourceListEnd;
7166 ++it)
7167 {
7168 const MediumLock &mediumLock = *it;
7169 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
7170 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
7171
7172 /* sanity check */
7173 Assert(pMedium->m->state == MediumState_LockedRead);
7174
7175 /** Open all media in read-only mode. */
7176 vrc = VDOpen(hdd,
7177 pMedium->m->strFormat.c_str(),
7178 pMedium->m->strLocationFull.c_str(),
7179 VD_OPEN_FLAGS_READONLY | m->uOpenFlagsDef,
7180 pMedium->m->vdImageIfaces);
7181 if (RT_FAILURE(vrc))
7182 throw setError(VBOX_E_FILE_ERROR,
7183 tr("Could not open the medium storage unit '%s'%s"),
7184 pMedium->m->strLocationFull.c_str(),
7185 vdError(vrc).c_str());
7186 }
7187
7188 Utf8Str targetFormat(pTarget->m->strFormat);
7189 Utf8Str targetLocation(pTarget->m->strLocationFull);
7190 uint64_t capabilities = pTarget->m->formatObj->getCapabilities();
7191
7192 Assert( pTarget->m->state == MediumState_Creating
7193 || pTarget->m->state == MediumState_LockedWrite);
7194 Assert(m->state == MediumState_LockedRead);
7195 Assert( pParent.isNull()
7196 || pParent->m->state == MediumState_LockedRead);
7197
7198 /* unlock before the potentially lengthy operation */
7199 thisLock.release();
7200
7201 /* ensure the target directory exists */
7202 if (capabilities & MediumFormatCapabilities_File)
7203 {
7204 HRESULT rc = VirtualBox::ensureFilePathExists(targetLocation, !(task.mVariant & MediumVariant_NoCreateDir) /* fCreate */);
7205 if (FAILED(rc))
7206 throw rc;
7207 }
7208
7209 PVBOXHDD targetHdd;
7210 vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &targetHdd);
7211 ComAssertRCThrow(vrc, E_FAIL);
7212
7213 try
7214 {
7215 /* Open all media in the target chain. */
7216 MediumLockList::Base::const_iterator targetListBegin =
7217 task.mpTargetMediumLockList->GetBegin();
7218 MediumLockList::Base::const_iterator targetListEnd =
7219 task.mpTargetMediumLockList->GetEnd();
7220 for (MediumLockList::Base::const_iterator it = targetListBegin;
7221 it != targetListEnd;
7222 ++it)
7223 {
7224 const MediumLock &mediumLock = *it;
7225 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
7226
7227 /* If the target medium is not created yet there's no
7228 * reason to open it. */
7229 if (pMedium == pTarget && fCreatingTarget)
7230 continue;
7231
7232 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
7233
7234 /* sanity check */
7235 Assert( pMedium->m->state == MediumState_LockedRead
7236 || pMedium->m->state == MediumState_LockedWrite);
7237
7238 unsigned uOpenFlags = VD_OPEN_FLAGS_NORMAL;
7239 if (pMedium->m->state != MediumState_LockedWrite)
7240 uOpenFlags = VD_OPEN_FLAGS_READONLY;
7241 if (pMedium->m->type == MediumType_Shareable)
7242 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
7243
7244 /* Open all media in appropriate mode. */
7245 vrc = VDOpen(targetHdd,
7246 pMedium->m->strFormat.c_str(),
7247 pMedium->m->strLocationFull.c_str(),
7248 uOpenFlags | m->uOpenFlagsDef,
7249 pMedium->m->vdImageIfaces);
7250 if (RT_FAILURE(vrc))
7251 throw setError(VBOX_E_FILE_ERROR,
7252 tr("Could not open the medium storage unit '%s'%s"),
7253 pMedium->m->strLocationFull.c_str(),
7254 vdError(vrc).c_str());
7255 }
7256
7257 /** @todo r=klaus target isn't locked, race getting the state */
7258 if (task.midxSrcImageSame == UINT32_MAX)
7259 {
7260 vrc = VDCopy(hdd,
7261 VD_LAST_IMAGE,
7262 targetHdd,
7263 targetFormat.c_str(),
7264 (fCreatingTarget) ? targetLocation.c_str() : (char *)NULL,
7265 false /* fMoveByRename */,
7266 0 /* cbSize */,
7267 task.mVariant & ~MediumVariant_NoCreateDir,
7268 targetId.raw(),
7269 VD_OPEN_FLAGS_NORMAL | m->uOpenFlagsDef,
7270 NULL /* pVDIfsOperation */,
7271 pTarget->m->vdImageIfaces,
7272 task.mVDOperationIfaces);
7273 }
7274 else
7275 {
7276 vrc = VDCopyEx(hdd,
7277 VD_LAST_IMAGE,
7278 targetHdd,
7279 targetFormat.c_str(),
7280 (fCreatingTarget) ? targetLocation.c_str() : (char *)NULL,
7281 false /* fMoveByRename */,
7282 0 /* cbSize */,
7283 task.midxSrcImageSame,
7284 task.midxDstImageSame,
7285 task.mVariant & ~MediumVariant_NoCreateDir,
7286 targetId.raw(),
7287 VD_OPEN_FLAGS_NORMAL | m->uOpenFlagsDef,
7288 NULL /* pVDIfsOperation */,
7289 pTarget->m->vdImageIfaces,
7290 task.mVDOperationIfaces);
7291 }
7292 if (RT_FAILURE(vrc))
7293 throw setError(VBOX_E_FILE_ERROR,
7294 tr("Could not create the clone medium '%s'%s"),
7295 targetLocation.c_str(), vdError(vrc).c_str());
7296
7297 size = VDGetFileSize(targetHdd, VD_LAST_IMAGE);
7298 logicalSize = VDGetSize(targetHdd, VD_LAST_IMAGE);
7299 unsigned uImageFlags;
7300 vrc = VDGetImageFlags(targetHdd, 0, &uImageFlags);
7301 if (RT_SUCCESS(vrc))
7302 variant = (MediumVariant_T)uImageFlags;
7303 }
7304 catch (HRESULT aRC) { rcTmp = aRC; }
7305
7306 VDDestroy(targetHdd);
7307 }
7308 catch (HRESULT aRC) { rcTmp = aRC; }
7309
7310 VDDestroy(hdd);
7311 }
7312 catch (HRESULT aRC) { rcTmp = aRC; }
7313
7314 ErrorInfoKeeper eik;
7315 MultiResult mrc(rcTmp);
7316
7317 /* Only do the parent changes for newly created media. */
7318 if (SUCCEEDED(mrc) && fCreatingTarget)
7319 {
7320 /* we set mParent & children() */
7321 AutoWriteLock alock2(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
7322
7323 Assert(pTarget->m->pParent.isNull());
7324
7325 if (pParent)
7326 {
7327 /* associate the clone with the parent and deassociate
7328 * from VirtualBox */
7329 pTarget->m->pParent = pParent;
7330 pParent->m->llChildren.push_back(pTarget);
7331
7332 /* register with mVirtualBox as the last step and move to
7333 * Created state only on success (leaving an orphan file is
7334 * better than breaking media registry consistency) */
7335 eik.restore();
7336 ComObjPtr<Medium> pMedium;
7337 mrc = pParent->m->pVirtualBox->registerMedium(pTarget, &pMedium,
7338 DeviceType_HardDisk,
7339 NULL /* pllRegistriesThatNeedSaving */);
7340 Assert(pTarget == pMedium);
7341 eik.fetch();
7342
7343 if (FAILED(mrc))
7344 /* break parent association on failure to register */
7345 pTarget->deparent(); // removes target from parent
7346 }
7347 else
7348 {
7349 /* just register */
7350 eik.restore();
7351 ComObjPtr<Medium> pMedium;
7352 mrc = m->pVirtualBox->registerMedium(pTarget, &pMedium,
7353 DeviceType_HardDisk,
7354 NULL /* pllRegistriesThatNeedSaving */);
7355 Assert(pTarget == pMedium);
7356 eik.fetch();
7357 }
7358 }
7359
7360 if (fCreatingTarget)
7361 {
7362 AutoWriteLock mLock(pTarget COMMA_LOCKVAL_SRC_POS);
7363
7364 if (SUCCEEDED(mrc))
7365 {
7366 pTarget->m->state = MediumState_Created;
7367
7368 pTarget->m->size = size;
7369 pTarget->m->logicalSize = logicalSize;
7370 pTarget->m->variant = variant;
7371 }
7372 else
7373 {
7374 /* back to NotCreated on failure */
7375 pTarget->m->state = MediumState_NotCreated;
7376
7377 /* reset UUID to prevent it from being reused next time */
7378 if (fGenerateUuid)
7379 unconst(pTarget->m->id).clear();
7380 }
7381 }
7382
7383 // now, at the end of this task (always asynchronous), save the settings
7384 if (SUCCEEDED(mrc))
7385 {
7386 // save the settings
7387 GuidList llRegistriesThatNeedSaving;
7388 addToRegistryIDList(llRegistriesThatNeedSaving);
7389 /* collect multiple errors */
7390 eik.restore();
7391 mrc = m->pVirtualBox->saveRegistries(llRegistriesThatNeedSaving);
7392 eik.fetch();
7393 }
7394
7395 /* Everything is explicitly unlocked when the task exits,
7396 * as the task destruction also destroys the source chain. */
7397
7398 /* Make sure the source chain is released early. It could happen
7399 * that we get a deadlock in Appliance::Import when Medium::Close
7400 * is called & the source chain is released at the same time. */
7401 task.mpSourceMediumLockList->Clear();
7402
7403 return mrc;
7404}
7405
7406/**
7407 * Implementation code for the "delete" task.
7408 *
7409 * This task always gets started from Medium::deleteStorage() and can run
7410 * synchronously or asynchronously depending on the "wait" parameter passed to
7411 * that function.
7412 *
7413 * @param task
7414 * @return
7415 */
7416HRESULT Medium::taskDeleteHandler(Medium::DeleteTask &task)
7417{
7418 NOREF(task);
7419 HRESULT rc = S_OK;
7420
7421 try
7422 {
7423 /* The lock is also used as a signal from the task initiator (which
7424 * releases it only after RTThreadCreate()) that we can start the job */
7425 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
7426
7427 PVBOXHDD hdd;
7428 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
7429 ComAssertRCThrow(vrc, E_FAIL);
7430
7431 Utf8Str format(m->strFormat);
7432 Utf8Str location(m->strLocationFull);
7433
7434 /* unlock before the potentially lengthy operation */
7435 Assert(m->state == MediumState_Deleting);
7436 thisLock.release();
7437
7438 try
7439 {
7440 vrc = VDOpen(hdd,
7441 format.c_str(),
7442 location.c_str(),
7443 VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO | m->uOpenFlagsDef,
7444 m->vdImageIfaces);
7445 if (RT_SUCCESS(vrc))
7446 vrc = VDClose(hdd, true /* fDelete */);
7447
7448 if (RT_FAILURE(vrc))
7449 throw setError(VBOX_E_FILE_ERROR,
7450 tr("Could not delete the medium storage unit '%s'%s"),
7451 location.c_str(), vdError(vrc).c_str());
7452
7453 }
7454 catch (HRESULT aRC) { rc = aRC; }
7455
7456 VDDestroy(hdd);
7457 }
7458 catch (HRESULT aRC) { rc = aRC; }
7459
7460 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
7461
7462 /* go to the NotCreated state even on failure since the storage
7463 * may have been already partially deleted and cannot be used any
7464 * more. One will be able to manually re-open the storage if really
7465 * needed to re-register it. */
7466 m->state = MediumState_NotCreated;
7467
7468 /* Reset UUID to prevent Create* from reusing it again */
7469 unconst(m->id).clear();
7470
7471 return rc;
7472}
7473
7474/**
7475 * Implementation code for the "reset" task.
7476 *
7477 * This always gets started asynchronously from Medium::Reset().
7478 *
7479 * @param task
7480 * @return
7481 */
7482HRESULT Medium::taskResetHandler(Medium::ResetTask &task)
7483{
7484 HRESULT rc = S_OK;
7485
7486 uint64_t size = 0, logicalSize = 0;
7487 MediumVariant_T variant = MediumVariant_Standard;
7488
7489 try
7490 {
7491 /* The lock is also used as a signal from the task initiator (which
7492 * releases it only after RTThreadCreate()) that we can start the job */
7493 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
7494
7495 /// @todo Below we use a pair of delete/create operations to reset
7496 /// the diff contents but the most efficient way will of course be
7497 /// to add a VDResetDiff() API call
7498
7499 PVBOXHDD hdd;
7500 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
7501 ComAssertRCThrow(vrc, E_FAIL);
7502
7503 Guid id = m->id;
7504 Utf8Str format(m->strFormat);
7505 Utf8Str location(m->strLocationFull);
7506
7507 Medium *pParent = m->pParent;
7508 Guid parentId = pParent->m->id;
7509 Utf8Str parentFormat(pParent->m->strFormat);
7510 Utf8Str parentLocation(pParent->m->strLocationFull);
7511
7512 Assert(m->state == MediumState_LockedWrite);
7513
7514 /* unlock before the potentially lengthy operation */
7515 thisLock.release();
7516
7517 try
7518 {
7519 /* Open all media in the target chain but the last. */
7520 MediumLockList::Base::const_iterator targetListBegin =
7521 task.mpMediumLockList->GetBegin();
7522 MediumLockList::Base::const_iterator targetListEnd =
7523 task.mpMediumLockList->GetEnd();
7524 for (MediumLockList::Base::const_iterator it = targetListBegin;
7525 it != targetListEnd;
7526 ++it)
7527 {
7528 const MediumLock &mediumLock = *it;
7529 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
7530
7531 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
7532
7533 /* sanity check, "this" is checked above */
7534 Assert( pMedium == this
7535 || pMedium->m->state == MediumState_LockedRead);
7536
7537 /* Open all media in appropriate mode. */
7538 vrc = VDOpen(hdd,
7539 pMedium->m->strFormat.c_str(),
7540 pMedium->m->strLocationFull.c_str(),
7541 VD_OPEN_FLAGS_READONLY | m->uOpenFlagsDef,
7542 pMedium->m->vdImageIfaces);
7543 if (RT_FAILURE(vrc))
7544 throw setError(VBOX_E_FILE_ERROR,
7545 tr("Could not open the medium storage unit '%s'%s"),
7546 pMedium->m->strLocationFull.c_str(),
7547 vdError(vrc).c_str());
7548
7549 /* Done when we hit the media which should be reset */
7550 if (pMedium == this)
7551 break;
7552 }
7553
7554 /* first, delete the storage unit */
7555 vrc = VDClose(hdd, true /* fDelete */);
7556 if (RT_FAILURE(vrc))
7557 throw setError(VBOX_E_FILE_ERROR,
7558 tr("Could not delete the medium storage unit '%s'%s"),
7559 location.c_str(), vdError(vrc).c_str());
7560
7561 /* next, create it again */
7562 vrc = VDOpen(hdd,
7563 parentFormat.c_str(),
7564 parentLocation.c_str(),
7565 VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO | m->uOpenFlagsDef,
7566 m->vdImageIfaces);
7567 if (RT_FAILURE(vrc))
7568 throw setError(VBOX_E_FILE_ERROR,
7569 tr("Could not open the medium storage unit '%s'%s"),
7570 parentLocation.c_str(), vdError(vrc).c_str());
7571
7572 vrc = VDCreateDiff(hdd,
7573 format.c_str(),
7574 location.c_str(),
7575 /// @todo use the same medium variant as before
7576 VD_IMAGE_FLAGS_NONE,
7577 NULL,
7578 id.raw(),
7579 parentId.raw(),
7580 VD_OPEN_FLAGS_NORMAL,
7581 m->vdImageIfaces,
7582 task.mVDOperationIfaces);
7583 if (RT_FAILURE(vrc))
7584 throw setError(VBOX_E_FILE_ERROR,
7585 tr("Could not create the differencing medium storage unit '%s'%s"),
7586 location.c_str(), vdError(vrc).c_str());
7587
7588 size = VDGetFileSize(hdd, VD_LAST_IMAGE);
7589 logicalSize = VDGetSize(hdd, VD_LAST_IMAGE);
7590 unsigned uImageFlags;
7591 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
7592 if (RT_SUCCESS(vrc))
7593 variant = (MediumVariant_T)uImageFlags;
7594 }
7595 catch (HRESULT aRC) { rc = aRC; }
7596
7597 VDDestroy(hdd);
7598 }
7599 catch (HRESULT aRC) { rc = aRC; }
7600
7601 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
7602
7603 m->size = size;
7604 m->logicalSize = logicalSize;
7605 m->variant = variant;
7606
7607 if (task.isAsync())
7608 {
7609 /* unlock ourselves when done */
7610 HRESULT rc2 = UnlockWrite(NULL);
7611 AssertComRC(rc2);
7612 }
7613
7614 /* Note that in sync mode, it's the caller's responsibility to
7615 * unlock the medium. */
7616
7617 return rc;
7618}
7619
7620/**
7621 * Implementation code for the "compact" task.
7622 *
7623 * @param task
7624 * @return
7625 */
7626HRESULT Medium::taskCompactHandler(Medium::CompactTask &task)
7627{
7628 HRESULT rc = S_OK;
7629
7630 /* Lock all in {parent,child} order. The lock is also used as a
7631 * signal from the task initiator (which releases it only after
7632 * RTThreadCreate()) that we can start the job. */
7633 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
7634
7635 try
7636 {
7637 PVBOXHDD hdd;
7638 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
7639 ComAssertRCThrow(vrc, E_FAIL);
7640
7641 try
7642 {
7643 /* Open all media in the chain. */
7644 MediumLockList::Base::const_iterator mediumListBegin =
7645 task.mpMediumLockList->GetBegin();
7646 MediumLockList::Base::const_iterator mediumListEnd =
7647 task.mpMediumLockList->GetEnd();
7648 MediumLockList::Base::const_iterator mediumListLast =
7649 mediumListEnd;
7650 mediumListLast--;
7651 for (MediumLockList::Base::const_iterator it = mediumListBegin;
7652 it != mediumListEnd;
7653 ++it)
7654 {
7655 const MediumLock &mediumLock = *it;
7656 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
7657 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
7658
7659 /* sanity check */
7660 if (it == mediumListLast)
7661 Assert(pMedium->m->state == MediumState_LockedWrite);
7662 else
7663 Assert(pMedium->m->state == MediumState_LockedRead);
7664
7665 /* Open all media but last in read-only mode. Do not handle
7666 * shareable media, as compaction and sharing are mutually
7667 * exclusive. */
7668 vrc = VDOpen(hdd,
7669 pMedium->m->strFormat.c_str(),
7670 pMedium->m->strLocationFull.c_str(),
7671 m->uOpenFlagsDef | (it == mediumListLast) ? VD_OPEN_FLAGS_NORMAL : VD_OPEN_FLAGS_READONLY,
7672 pMedium->m->vdImageIfaces);
7673 if (RT_FAILURE(vrc))
7674 throw setError(VBOX_E_FILE_ERROR,
7675 tr("Could not open the medium storage unit '%s'%s"),
7676 pMedium->m->strLocationFull.c_str(),
7677 vdError(vrc).c_str());
7678 }
7679
7680 Assert(m->state == MediumState_LockedWrite);
7681
7682 Utf8Str location(m->strLocationFull);
7683
7684 /* unlock before the potentially lengthy operation */
7685 thisLock.release();
7686
7687 vrc = VDCompact(hdd, VD_LAST_IMAGE, task.mVDOperationIfaces);
7688 if (RT_FAILURE(vrc))
7689 {
7690 if (vrc == VERR_NOT_SUPPORTED)
7691 throw setError(VBOX_E_NOT_SUPPORTED,
7692 tr("Compacting is not yet supported for medium '%s'"),
7693 location.c_str());
7694 else if (vrc == VERR_NOT_IMPLEMENTED)
7695 throw setError(E_NOTIMPL,
7696 tr("Compacting is not implemented, medium '%s'"),
7697 location.c_str());
7698 else
7699 throw setError(VBOX_E_FILE_ERROR,
7700 tr("Could not compact medium '%s'%s"),
7701 location.c_str(),
7702 vdError(vrc).c_str());
7703 }
7704 }
7705 catch (HRESULT aRC) { rc = aRC; }
7706
7707 VDDestroy(hdd);
7708 }
7709 catch (HRESULT aRC) { rc = aRC; }
7710
7711 /* Everything is explicitly unlocked when the task exits,
7712 * as the task destruction also destroys the media chain. */
7713
7714 return rc;
7715}
7716
7717/**
7718 * Implementation code for the "resize" task.
7719 *
7720 * @param task
7721 * @return
7722 */
7723HRESULT Medium::taskResizeHandler(Medium::ResizeTask &task)
7724{
7725 HRESULT rc = S_OK;
7726
7727 /* Lock all in {parent,child} order. The lock is also used as a
7728 * signal from the task initiator (which releases it only after
7729 * RTThreadCreate()) that we can start the job. */
7730 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
7731
7732 try
7733 {
7734 PVBOXHDD hdd;
7735 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
7736 ComAssertRCThrow(vrc, E_FAIL);
7737
7738 try
7739 {
7740 /* Open all media in the chain. */
7741 MediumLockList::Base::const_iterator mediumListBegin =
7742 task.mpMediumLockList->GetBegin();
7743 MediumLockList::Base::const_iterator mediumListEnd =
7744 task.mpMediumLockList->GetEnd();
7745 MediumLockList::Base::const_iterator mediumListLast =
7746 mediumListEnd;
7747 mediumListLast--;
7748 for (MediumLockList::Base::const_iterator it = mediumListBegin;
7749 it != mediumListEnd;
7750 ++it)
7751 {
7752 const MediumLock &mediumLock = *it;
7753 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
7754 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
7755
7756 /* sanity check */
7757 if (it == mediumListLast)
7758 Assert(pMedium->m->state == MediumState_LockedWrite);
7759 else
7760 Assert(pMedium->m->state == MediumState_LockedRead);
7761
7762 /* Open all media but last in read-only mode. Do not handle
7763 * shareable media, as compaction and sharing are mutually
7764 * exclusive. */
7765 vrc = VDOpen(hdd,
7766 pMedium->m->strFormat.c_str(),
7767 pMedium->m->strLocationFull.c_str(),
7768 m->uOpenFlagsDef | (it == mediumListLast) ? VD_OPEN_FLAGS_NORMAL : VD_OPEN_FLAGS_READONLY,
7769 pMedium->m->vdImageIfaces);
7770 if (RT_FAILURE(vrc))
7771 throw setError(VBOX_E_FILE_ERROR,
7772 tr("Could not open the medium storage unit '%s'%s"),
7773 pMedium->m->strLocationFull.c_str(),
7774 vdError(vrc).c_str());
7775 }
7776
7777 Assert(m->state == MediumState_LockedWrite);
7778
7779 Utf8Str location(m->strLocationFull);
7780
7781 /* unlock before the potentially lengthy operation */
7782 thisLock.release();
7783
7784 VDGEOMETRY geo = {0, 0, 0}; /* auto */
7785 vrc = VDResize(hdd, task.mSize, &geo, &geo, task.mVDOperationIfaces);
7786 if (RT_FAILURE(vrc))
7787 {
7788 if (vrc == VERR_NOT_SUPPORTED)
7789 throw setError(VBOX_E_NOT_SUPPORTED,
7790 tr("Compacting is not yet supported for medium '%s'"),
7791 location.c_str());
7792 else if (vrc == VERR_NOT_IMPLEMENTED)
7793 throw setError(E_NOTIMPL,
7794 tr("Compacting is not implemented, medium '%s'"),
7795 location.c_str());
7796 else
7797 throw setError(VBOX_E_FILE_ERROR,
7798 tr("Could not compact medium '%s'%s"),
7799 location.c_str(),
7800 vdError(vrc).c_str());
7801 }
7802 }
7803 catch (HRESULT aRC) { rc = aRC; }
7804
7805 VDDestroy(hdd);
7806 }
7807 catch (HRESULT aRC) { rc = aRC; }
7808
7809 /* Everything is explicitly unlocked when the task exits,
7810 * as the task destruction also destroys the media chain. */
7811
7812 return rc;
7813}
7814
7815/**
7816 * Implementation code for the "export" task.
7817 *
7818 * This only gets started from Medium::exportFile() and always runs
7819 * asynchronously. It doesn't touch anything configuration related, so
7820 * we never save the VirtualBox.xml file here.
7821 *
7822 * @param task
7823 * @return
7824 */
7825HRESULT Medium::taskExportHandler(Medium::ExportTask &task)
7826{
7827 HRESULT rc = S_OK;
7828
7829 try
7830 {
7831 /* Lock all in {parent,child} order. The lock is also used as a
7832 * signal from the task initiator (which releases it only after
7833 * RTThreadCreate()) that we can start the job. */
7834 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
7835
7836 PVBOXHDD hdd;
7837 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
7838 ComAssertRCThrow(vrc, E_FAIL);
7839
7840 try
7841 {
7842 /* Open all media in the source chain. */
7843 MediumLockList::Base::const_iterator sourceListBegin =
7844 task.mpSourceMediumLockList->GetBegin();
7845 MediumLockList::Base::const_iterator sourceListEnd =
7846 task.mpSourceMediumLockList->GetEnd();
7847 for (MediumLockList::Base::const_iterator it = sourceListBegin;
7848 it != sourceListEnd;
7849 ++it)
7850 {
7851 const MediumLock &mediumLock = *it;
7852 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
7853 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
7854
7855 /* sanity check */
7856 Assert(pMedium->m->state == MediumState_LockedRead);
7857
7858 /* Open all media in read-only mode. */
7859 vrc = VDOpen(hdd,
7860 pMedium->m->strFormat.c_str(),
7861 pMedium->m->strLocationFull.c_str(),
7862 VD_OPEN_FLAGS_READONLY | m->uOpenFlagsDef,
7863 pMedium->m->vdImageIfaces);
7864 if (RT_FAILURE(vrc))
7865 throw setError(VBOX_E_FILE_ERROR,
7866 tr("Could not open the medium storage unit '%s'%s"),
7867 pMedium->m->strLocationFull.c_str(),
7868 vdError(vrc).c_str());
7869 }
7870
7871 Utf8Str targetFormat(task.mFormat->getId());
7872 Utf8Str targetLocation(task.mFilename);
7873 uint64_t capabilities = task.mFormat->getCapabilities();
7874
7875 Assert(m->state == MediumState_LockedRead);
7876
7877 /* unlock before the potentially lengthy operation */
7878 thisLock.release();
7879
7880 /* ensure the target directory exists */
7881 if (capabilities & MediumFormatCapabilities_File)
7882 {
7883 rc = VirtualBox::ensureFilePathExists(targetLocation, !(task.mVariant & MediumVariant_NoCreateDir) /* fCreate */);
7884 if (FAILED(rc))
7885 throw rc;
7886 }
7887
7888 PVBOXHDD targetHdd;
7889 vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &targetHdd);
7890 ComAssertRCThrow(vrc, E_FAIL);
7891
7892 try
7893 {
7894 vrc = VDCopy(hdd,
7895 VD_LAST_IMAGE,
7896 targetHdd,
7897 targetFormat.c_str(),
7898 targetLocation.c_str(),
7899 false /* fMoveByRename */,
7900 0 /* cbSize */,
7901 task.mVariant & ~MediumVariant_NoCreateDir,
7902 NULL /* pDstUuid */,
7903 VD_OPEN_FLAGS_NORMAL | VD_OPEN_FLAGS_SEQUENTIAL,
7904 NULL /* pVDIfsOperation */,
7905 task.mVDImageIfaces,
7906 task.mVDOperationIfaces);
7907 if (RT_FAILURE(vrc))
7908 throw setError(VBOX_E_FILE_ERROR,
7909 tr("Could not create the clone medium '%s'%s"),
7910 targetLocation.c_str(), vdError(vrc).c_str());
7911 }
7912 catch (HRESULT aRC) { rc = aRC; }
7913
7914 VDDestroy(targetHdd);
7915 }
7916 catch (HRESULT aRC) { rc = aRC; }
7917
7918 VDDestroy(hdd);
7919 }
7920 catch (HRESULT aRC) { rc = aRC; }
7921
7922 /* Everything is explicitly unlocked when the task exits,
7923 * as the task destruction also destroys the source chain. */
7924
7925 /* Make sure the source chain is released early, otherwise it can
7926 * lead to deadlocks with concurrent IAppliance activities. */
7927 task.mpSourceMediumLockList->Clear();
7928
7929 return rc;
7930}
7931
7932/**
7933 * Implementation code for the "import" task.
7934 *
7935 * This only gets started from Medium::importFile() and always runs
7936 * asynchronously. It potentially touches the media registry, so we
7937 * always save the VirtualBox.xml file when we're done here.
7938 *
7939 * @param task
7940 * @return
7941 */
7942HRESULT Medium::taskImportHandler(Medium::ImportTask &task)
7943{
7944 HRESULT rcTmp = S_OK;
7945
7946 const ComObjPtr<Medium> &pParent = task.mParent;
7947
7948 bool fCreatingTarget = false;
7949
7950 uint64_t size = 0, logicalSize = 0;
7951 MediumVariant_T variant = MediumVariant_Standard;
7952 bool fGenerateUuid = false;
7953
7954 try
7955 {
7956 /* Lock all in {parent,child} order. The lock is also used as a
7957 * signal from the task initiator (which releases it only after
7958 * RTThreadCreate()) that we can start the job. */
7959 AutoMultiWriteLock2 thisLock(this, pParent COMMA_LOCKVAL_SRC_POS);
7960
7961 fCreatingTarget = m->state == MediumState_Creating;
7962
7963 /* The object may request a specific UUID (through a special form of
7964 * the setLocation() argument). Otherwise we have to generate it */
7965 Guid targetId = m->id;
7966 fGenerateUuid = targetId.isEmpty();
7967 if (fGenerateUuid)
7968 {
7969 targetId.create();
7970 /* VirtualBox::registerHardDisk() will need UUID */
7971 unconst(m->id) = targetId;
7972 }
7973
7974
7975 PVBOXHDD hdd;
7976 int vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &hdd);
7977 ComAssertRCThrow(vrc, E_FAIL);
7978
7979 try
7980 {
7981 /* Open source medium. */
7982 vrc = VDOpen(hdd,
7983 task.mFormat->getId().c_str(),
7984 task.mFilename.c_str(),
7985 VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_SEQUENTIAL | m->uOpenFlagsDef,
7986 task.mVDImageIfaces);
7987 if (RT_FAILURE(vrc))
7988 throw setError(VBOX_E_FILE_ERROR,
7989 tr("Could not open the medium storage unit '%s'%s"),
7990 task.mFilename.c_str(),
7991 vdError(vrc).c_str());
7992
7993 Utf8Str targetFormat(m->strFormat);
7994 Utf8Str targetLocation(m->strLocationFull);
7995 uint64_t capabilities = task.mFormat->getCapabilities();
7996
7997 Assert( m->state == MediumState_Creating
7998 || m->state == MediumState_LockedWrite);
7999 Assert( pParent.isNull()
8000 || pParent->m->state == MediumState_LockedRead);
8001
8002 /* unlock before the potentially lengthy operation */
8003 thisLock.release();
8004
8005 /* ensure the target directory exists */
8006 if (capabilities & MediumFormatCapabilities_File)
8007 {
8008 HRESULT rc = VirtualBox::ensureFilePathExists(targetLocation, !(task.mVariant & MediumVariant_NoCreateDir) /* fCreate */);
8009 if (FAILED(rc))
8010 throw rc;
8011 }
8012
8013 PVBOXHDD targetHdd;
8014 vrc = VDCreate(m->vdDiskIfaces, convertDeviceType(), &targetHdd);
8015 ComAssertRCThrow(vrc, E_FAIL);
8016
8017 try
8018 {
8019 /* Open all media in the target chain. */
8020 MediumLockList::Base::const_iterator targetListBegin =
8021 task.mpTargetMediumLockList->GetBegin();
8022 MediumLockList::Base::const_iterator targetListEnd =
8023 task.mpTargetMediumLockList->GetEnd();
8024 for (MediumLockList::Base::const_iterator it = targetListBegin;
8025 it != targetListEnd;
8026 ++it)
8027 {
8028 const MediumLock &mediumLock = *it;
8029 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
8030
8031 /* If the target medium is not created yet there's no
8032 * reason to open it. */
8033 if (pMedium == this && fCreatingTarget)
8034 continue;
8035
8036 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
8037
8038 /* sanity check */
8039 Assert( pMedium->m->state == MediumState_LockedRead
8040 || pMedium->m->state == MediumState_LockedWrite);
8041
8042 unsigned uOpenFlags = VD_OPEN_FLAGS_NORMAL;
8043 if (pMedium->m->state != MediumState_LockedWrite)
8044 uOpenFlags = VD_OPEN_FLAGS_READONLY;
8045 if (pMedium->m->type == MediumType_Shareable)
8046 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
8047
8048 /* Open all media in appropriate mode. */
8049 vrc = VDOpen(targetHdd,
8050 pMedium->m->strFormat.c_str(),
8051 pMedium->m->strLocationFull.c_str(),
8052 uOpenFlags | m->uOpenFlagsDef,
8053 pMedium->m->vdImageIfaces);
8054 if (RT_FAILURE(vrc))
8055 throw setError(VBOX_E_FILE_ERROR,
8056 tr("Could not open the medium storage unit '%s'%s"),
8057 pMedium->m->strLocationFull.c_str(),
8058 vdError(vrc).c_str());
8059 }
8060
8061 /** @todo r=klaus target isn't locked, race getting the state */
8062 vrc = VDCopy(hdd,
8063 VD_LAST_IMAGE,
8064 targetHdd,
8065 targetFormat.c_str(),
8066 (fCreatingTarget) ? targetLocation.c_str() : (char *)NULL,
8067 false /* fMoveByRename */,
8068 0 /* cbSize */,
8069 task.mVariant & ~MediumVariant_NoCreateDir,
8070 targetId.raw(),
8071 VD_OPEN_FLAGS_NORMAL,
8072 NULL /* pVDIfsOperation */,
8073 m->vdImageIfaces,
8074 task.mVDOperationIfaces);
8075 if (RT_FAILURE(vrc))
8076 throw setError(VBOX_E_FILE_ERROR,
8077 tr("Could not create the clone medium '%s'%s"),
8078 targetLocation.c_str(), vdError(vrc).c_str());
8079
8080 size = VDGetFileSize(targetHdd, VD_LAST_IMAGE);
8081 logicalSize = VDGetSize(targetHdd, VD_LAST_IMAGE);
8082 unsigned uImageFlags;
8083 vrc = VDGetImageFlags(targetHdd, 0, &uImageFlags);
8084 if (RT_SUCCESS(vrc))
8085 variant = (MediumVariant_T)uImageFlags;
8086 }
8087 catch (HRESULT aRC) { rcTmp = aRC; }
8088
8089 VDDestroy(targetHdd);
8090 }
8091 catch (HRESULT aRC) { rcTmp = aRC; }
8092
8093 VDDestroy(hdd);
8094 }
8095 catch (HRESULT aRC) { rcTmp = aRC; }
8096
8097 ErrorInfoKeeper eik;
8098 MultiResult mrc(rcTmp);
8099
8100 /* Only do the parent changes for newly created media. */
8101 if (SUCCEEDED(mrc) && fCreatingTarget)
8102 {
8103 /* we set mParent & children() */
8104 AutoWriteLock alock2(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
8105
8106 Assert(m->pParent.isNull());
8107
8108 if (pParent)
8109 {
8110 /* associate the clone with the parent and deassociate
8111 * from VirtualBox */
8112 m->pParent = pParent;
8113 pParent->m->llChildren.push_back(this);
8114
8115 /* register with mVirtualBox as the last step and move to
8116 * Created state only on success (leaving an orphan file is
8117 * better than breaking media registry consistency) */
8118 eik.restore();
8119 ComObjPtr<Medium> pMedium;
8120 mrc = pParent->m->pVirtualBox->registerMedium(this, &pMedium,
8121 DeviceType_HardDisk,
8122 NULL /* llRegistriesThatNeedSaving */);
8123 Assert(this == pMedium);
8124 eik.fetch();
8125
8126 if (FAILED(mrc))
8127 /* break parent association on failure to register */
8128 this->deparent(); // removes target from parent
8129 }
8130 else
8131 {
8132 /* just register */
8133 eik.restore();
8134 ComObjPtr<Medium> pMedium;
8135 mrc = m->pVirtualBox->registerMedium(this, &pMedium, DeviceType_HardDisk,
8136 NULL /* pllRegistriesThatNeedSaving */);
8137 Assert(this == pMedium);
8138 eik.fetch();
8139 }
8140 }
8141
8142 if (fCreatingTarget)
8143 {
8144 AutoWriteLock mLock(this COMMA_LOCKVAL_SRC_POS);
8145
8146 if (SUCCEEDED(mrc))
8147 {
8148 m->state = MediumState_Created;
8149
8150 m->size = size;
8151 m->logicalSize = logicalSize;
8152 m->variant = variant;
8153 }
8154 else
8155 {
8156 /* back to NotCreated on failure */
8157 m->state = MediumState_NotCreated;
8158
8159 /* reset UUID to prevent it from being reused next time */
8160 if (fGenerateUuid)
8161 unconst(m->id).clear();
8162 }
8163 }
8164
8165 // now, at the end of this task (always asynchronous), save the settings
8166 {
8167 // save the settings
8168 GuidList llRegistriesThatNeedSaving;
8169 addToRegistryIDList(llRegistriesThatNeedSaving);
8170 /* collect multiple errors */
8171 eik.restore();
8172 mrc = m->pVirtualBox->saveRegistries(llRegistriesThatNeedSaving);
8173 eik.fetch();
8174 }
8175
8176 /* Everything is explicitly unlocked when the task exits,
8177 * as the task destruction also destroys the target chain. */
8178
8179 /* Make sure the target chain is released early, otherwise it can
8180 * lead to deadlocks with concurrent IAppliance activities. */
8181 task.mpTargetMediumLockList->Clear();
8182
8183 return mrc;
8184}
8185
8186/* vi: set tabstop=4 shiftwidth=4 expandtab: */
Note: See TracBrowser for help on using the repository browser.

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