VirtualBox

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

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

IPRT: RTTcpClientCloseEx - don't be nice to storage servers, they don't always repay the kindness.

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

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