VirtualBox

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

Last change on this file since 47469 was 46720, checked in by vboxsync, 11 years ago

Main/xml/Settings.cpp: limit snapshot depth to 250, avoiding crashes
Main/Snapshot: limit snapshot depth to 250
Main/Medium: eliminate some spurious error messages when saving a VM config

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

© 2023 Oracle
ContactPrivacy policyTerms of Use