VirtualBox

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

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

Main/Medium: only create the target path if the destination is file based

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

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