VirtualBox

source: vbox/trunk/src/VBox/Main/MediumImpl.cpp@ 33289

最後變更 在這個檔案從33289是 33250,由 vboxsync 提交於 14 年 前

Main: fix finding snapshot diffs in new-vm machine folders (yesterday's regression)

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

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