VirtualBox

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

Last change on this file since 31751 was 31746, checked in by vboxsync, 14 years ago

Main: Added input validations missing in r64842.

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

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