VirtualBox

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

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

Main: enable exportFile

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 231.6 KB
Line 
1/* $Id: MediumImpl.cpp 32849 2010-09-30 14:45:10Z vboxsync $ */
2/** @file
3 * VirtualBox COM class implementation
4 */
5
6/*
7 * Copyright (C) 2008-2010 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18#include "MediumImpl.h"
19#include "ProgressImpl.h"
20#include "SystemPropertiesImpl.h"
21#include "VirtualBoxImpl.h"
22
23#include "AutoCaller.h"
24#include "Logging.h"
25
26#include <VBox/com/array.h>
27#include "VBox/com/MultiResult.h"
28#include "VBox/com/ErrorInfo.h"
29
30#include <VBox/err.h>
31#include <VBox/settings.h>
32
33#include <iprt/param.h>
34#include <iprt/path.h>
35#include <iprt/file.h>
36#include <iprt/tcp.h>
37#include <iprt/cpp/utils.h>
38
39#include <VBox/VBoxHDD.h>
40
41#include <algorithm>
42
43////////////////////////////////////////////////////////////////////////////////
44//
45// Medium data definition
46//
47////////////////////////////////////////////////////////////////////////////////
48
49/** Describes how a machine refers to this medium. */
50struct BackRef
51{
52 /** Equality predicate for stdc++. */
53 struct EqualsTo : public std::unary_function <BackRef, bool>
54 {
55 explicit EqualsTo(const Guid &aMachineId) : machineId(aMachineId) {}
56
57 bool operator()(const argument_type &aThat) const
58 {
59 return aThat.machineId == machineId;
60 }
61
62 const Guid machineId;
63 };
64
65 typedef std::list<Guid> GuidList;
66
67 BackRef(const Guid &aMachineId,
68 const Guid &aSnapshotId = Guid::Empty)
69 : machineId(aMachineId),
70 fInCurState(aSnapshotId.isEmpty())
71 {
72 if (!aSnapshotId.isEmpty())
73 llSnapshotIds.push_back(aSnapshotId);
74 }
75
76 Guid machineId;
77 bool fInCurState : 1;
78 GuidList llSnapshotIds;
79};
80
81typedef std::list<BackRef> BackRefList;
82
83struct Medium::Data
84{
85 Data()
86 : pVirtualBox(NULL),
87 state(MediumState_NotCreated),
88 variant(MediumVariant_Standard),
89 size(0),
90 readers(0),
91 preLockState(MediumState_NotCreated),
92 queryInfoSem(NIL_RTSEMEVENTMULTI),
93 queryInfoRunning(false),
94 type(MediumType_Normal),
95 devType(DeviceType_HardDisk),
96 logicalSize(0),
97 hddOpenMode(OpenReadWrite),
98 autoReset(false),
99 hostDrive(false),
100 implicit(false),
101 numCreateDiffTasks(0),
102 vdDiskIfaces(NULL),
103 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 AssertPtrReturn(aFilename, E_INVALIDARG);
5122 AssertReturn(!aFormat.isNull(), E_INVALIDARG);
5123 AssertReturn(!aProgress.isNull(), E_INVALIDARG);
5124
5125 AutoCaller autoCaller(this);
5126 if (FAILED(autoCaller.rc())) return autoCaller.rc();
5127
5128 HRESULT rc = S_OK;
5129 Medium::Task *pTask = NULL;
5130
5131 try
5132 {
5133 // locking: we need the tree lock first because we access parent pointers
5134 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5135 // and we need to write-lock the media involved
5136 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
5137
5138 /* Build the source lock list. */
5139 MediumLockList *pSourceMediumLockList(new MediumLockList());
5140 rc = createMediumLockList(true /* fFailIfInaccessible */,
5141 false /* fMediumLockWrite */,
5142 NULL,
5143 *pSourceMediumLockList);
5144 if (FAILED(rc))
5145 {
5146 delete pSourceMediumLockList;
5147 throw rc;
5148 }
5149
5150 rc = pSourceMediumLockList->Lock();
5151 if (FAILED(rc))
5152 {
5153 delete pSourceMediumLockList;
5154 throw setError(rc,
5155 tr("Failed to lock source media '%s'"),
5156 getLocationFull().c_str());
5157 }
5158
5159 /* setup task object to carry out the operation asynchronously */
5160 pTask = new Medium::ExportTask(this, aProgress, aFilename, aFormat,
5161 aVariant, aVDImageIOCallbacks,
5162 aVDImageIOUser, pSourceMediumLockList);
5163 rc = pTask->rc();
5164 AssertComRC(rc);
5165 if (FAILED(rc))
5166 throw rc;
5167 }
5168 catch (HRESULT aRC) { rc = aRC; }
5169
5170 if (SUCCEEDED(rc))
5171 rc = startThread(pTask);
5172 else if (pTask != NULL)
5173 delete pTask;
5174
5175 return rc;
5176}
5177
5178////////////////////////////////////////////////////////////////////////////////
5179//
5180// Private methods
5181//
5182////////////////////////////////////////////////////////////////////////////////
5183
5184/**
5185 * Performs extra checks if the medium can be closed and returns S_OK in
5186 * this case. Otherwise, returns a respective error message. Called by
5187 * Close() under the medium tree lock and the medium lock.
5188 *
5189 * @note Also reused by Medium::Reset().
5190 *
5191 * @note Caller must hold the media tree write lock!
5192 */
5193HRESULT Medium::canClose()
5194{
5195 Assert(m->pVirtualBox->getMediaTreeLockHandle().isWriteLockOnCurrentThread());
5196
5197 if (getChildren().size() != 0)
5198 return setError(VBOX_E_OBJECT_IN_USE,
5199 tr("Cannot close medium '%s' because it has %d child media"),
5200 m->strLocationFull.c_str(), getChildren().size());
5201
5202 return S_OK;
5203}
5204
5205/**
5206 * Unregisters this medium with mVirtualBox. Called by close() under the medium tree lock.
5207 *
5208 * This calls either VirtualBox::unregisterImage or VirtualBox::unregisterHardDisk depending
5209 * on the device type of this medium.
5210 *
5211 * @param pfNeedsGlobalSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
5212 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
5213 *
5214 * @note Caller must have locked the media tree lock for writing!
5215 */
5216HRESULT Medium::unregisterWithVirtualBox(bool *pfNeedsGlobalSaveSettings)
5217{
5218 /* Note that we need to de-associate ourselves from the parent to let
5219 * unregisterHardDisk() properly save the registry */
5220
5221 /* we modify mParent and access children */
5222 Assert(m->pVirtualBox->getMediaTreeLockHandle().isWriteLockOnCurrentThread());
5223
5224 Medium *pParentBackup = m->pParent;
5225 AssertReturn(getChildren().size() == 0, E_FAIL);
5226 if (m->pParent)
5227 deparent();
5228
5229 HRESULT rc = E_FAIL;
5230 switch (m->devType)
5231 {
5232 case DeviceType_DVD:
5233 rc = m->pVirtualBox->unregisterImage(this, DeviceType_DVD, pfNeedsGlobalSaveSettings);
5234 break;
5235
5236 case DeviceType_Floppy:
5237 rc = m->pVirtualBox->unregisterImage(this, DeviceType_Floppy, pfNeedsGlobalSaveSettings);
5238 break;
5239
5240 case DeviceType_HardDisk:
5241 rc = m->pVirtualBox->unregisterHardDisk(this, pfNeedsGlobalSaveSettings);
5242 break;
5243
5244 default:
5245 break;
5246 }
5247
5248 if (FAILED(rc))
5249 {
5250 if (pParentBackup)
5251 {
5252 // re-associate with the parent as we are still relatives in the registry
5253 m->pParent = pParentBackup;
5254 m->pParent->m->llChildren.push_back(this);
5255 }
5256 }
5257
5258 return rc;
5259}
5260
5261/**
5262 * Checks that the format ID is valid and sets it on success.
5263 *
5264 * Note that this method will caller-reference the format object on success!
5265 * This reference must be released somewhere to let the MediumFormat object be
5266 * uninitialized.
5267 *
5268 * @note Must be called from under this object's write lock.
5269 */
5270HRESULT Medium::setFormat(const Utf8Str &aFormat)
5271{
5272 /* get the format object first */
5273 {
5274 SystemProperties *pSysProps = m->pVirtualBox->getSystemProperties();
5275 AutoReadLock propsLock(pSysProps COMMA_LOCKVAL_SRC_POS);
5276
5277 unconst(m->formatObj) = pSysProps->mediumFormat(aFormat);
5278 if (m->formatObj.isNull())
5279 return setError(E_INVALIDARG,
5280 tr("Invalid medium storage format '%s'"),
5281 aFormat.c_str());
5282
5283 /* reference the format permanently to prevent its unexpected
5284 * uninitialization */
5285 HRESULT rc = m->formatObj->addCaller();
5286 AssertComRCReturnRC(rc);
5287
5288 /* get properties (preinsert them as keys in the map). Note that the
5289 * map doesn't grow over the object life time since the set of
5290 * properties is meant to be constant. */
5291
5292 Assert(m->mapProperties.empty());
5293
5294 for (MediumFormat::PropertyList::const_iterator it = m->formatObj->getProperties().begin();
5295 it != m->formatObj->getProperties().end();
5296 ++it)
5297 {
5298 m->mapProperties.insert(std::make_pair(it->strName, Utf8Str::Empty));
5299 }
5300 }
5301
5302 unconst(m->strFormat) = aFormat;
5303
5304 return S_OK;
5305}
5306
5307/**
5308 * Returns the last error message collected by the vdErrorCall callback and
5309 * resets it.
5310 *
5311 * The error message is returned prepended with a dot and a space, like this:
5312 * <code>
5313 * ". <error_text> (%Rrc)"
5314 * </code>
5315 * to make it easily appendable to a more general error message. The @c %Rrc
5316 * format string is given @a aVRC as an argument.
5317 *
5318 * If there is no last error message collected by vdErrorCall or if it is a
5319 * null or empty string, then this function returns the following text:
5320 * <code>
5321 * " (%Rrc)"
5322 * </code>
5323 *
5324 * @note Doesn't do any object locking; it is assumed that the caller makes sure
5325 * the callback isn't called by more than one thread at a time.
5326 *
5327 * @param aVRC VBox error code to use when no error message is provided.
5328 */
5329Utf8Str Medium::vdError(int aVRC)
5330{
5331 Utf8Str error;
5332
5333 if (m->vdError.isEmpty())
5334 error = Utf8StrFmt(" (%Rrc)", aVRC);
5335 else
5336 error = Utf8StrFmt(".\n%s", m->vdError.c_str());
5337
5338 m->vdError.setNull();
5339
5340 return error;
5341}
5342
5343/**
5344 * Error message callback.
5345 *
5346 * Puts the reported error message to the m->vdError field.
5347 *
5348 * @note Doesn't do any object locking; it is assumed that the caller makes sure
5349 * the callback isn't called by more than one thread at a time.
5350 *
5351 * @param pvUser The opaque data passed on container creation.
5352 * @param rc The VBox error code.
5353 * @param RT_SRC_POS_DECL Use RT_SRC_POS.
5354 * @param pszFormat Error message format string.
5355 * @param va Error message arguments.
5356 */
5357/*static*/
5358DECLCALLBACK(void) Medium::vdErrorCall(void *pvUser, int rc, RT_SRC_POS_DECL,
5359 const char *pszFormat, va_list va)
5360{
5361 NOREF(pszFile); NOREF(iLine); NOREF(pszFunction); /* RT_SRC_POS_DECL */
5362
5363 Medium *that = static_cast<Medium*>(pvUser);
5364 AssertReturnVoid(that != NULL);
5365
5366 if (that->m->vdError.isEmpty())
5367 that->m->vdError =
5368 Utf8StrFmt("%s (%Rrc)", Utf8StrFmtVA(pszFormat, va).c_str(), rc);
5369 else
5370 that->m->vdError =
5371 Utf8StrFmt("%s.\n%s (%Rrc)", that->m->vdError.c_str(),
5372 Utf8StrFmtVA(pszFormat, va).c_str(), rc);
5373}
5374
5375/* static */
5376DECLCALLBACK(bool) Medium::vdConfigAreKeysValid(void *pvUser,
5377 const char * /* pszzValid */)
5378{
5379 Medium *that = static_cast<Medium*>(pvUser);
5380 AssertReturn(that != NULL, false);
5381
5382 /* we always return true since the only keys we have are those found in
5383 * VDBACKENDINFO */
5384 return true;
5385}
5386
5387/* static */
5388DECLCALLBACK(int) Medium::vdConfigQuerySize(void *pvUser,
5389 const char *pszName,
5390 size_t *pcbValue)
5391{
5392 AssertReturn(VALID_PTR(pcbValue), VERR_INVALID_POINTER);
5393
5394 Medium *that = static_cast<Medium*>(pvUser);
5395 AssertReturn(that != NULL, VERR_GENERAL_FAILURE);
5396
5397 settings::StringsMap::const_iterator it = that->m->mapProperties.find(Utf8Str(pszName));
5398 if (it == that->m->mapProperties.end())
5399 return VERR_CFGM_VALUE_NOT_FOUND;
5400
5401 /* we interpret null values as "no value" in Medium */
5402 if (it->second.isEmpty())
5403 return VERR_CFGM_VALUE_NOT_FOUND;
5404
5405 *pcbValue = it->second.length() + 1 /* include terminator */;
5406
5407 return VINF_SUCCESS;
5408}
5409
5410/* static */
5411DECLCALLBACK(int) Medium::vdConfigQuery(void *pvUser,
5412 const char *pszName,
5413 char *pszValue,
5414 size_t cchValue)
5415{
5416 AssertReturn(VALID_PTR(pszValue), VERR_INVALID_POINTER);
5417
5418 Medium *that = static_cast<Medium*>(pvUser);
5419 AssertReturn(that != NULL, VERR_GENERAL_FAILURE);
5420
5421 settings::StringsMap::const_iterator it = that->m->mapProperties.find(Utf8Str(pszName));
5422 if (it == that->m->mapProperties.end())
5423 return VERR_CFGM_VALUE_NOT_FOUND;
5424
5425 /* we interpret null values as "no value" in Medium */
5426 if (it->second.isEmpty())
5427 return VERR_CFGM_VALUE_NOT_FOUND;
5428
5429 const Utf8Str &value = it->second;
5430 if (value.length() >= cchValue)
5431 return VERR_CFGM_NOT_ENOUGH_SPACE;
5432
5433 memcpy(pszValue, value.c_str(), value.length() + 1);
5434
5435 return VINF_SUCCESS;
5436}
5437
5438DECLCALLBACK(int) Medium::vdTcpSocketCreate(uint32_t fFlags, PVDSOCKET pSock)
5439{
5440 PVDSOCKETINT pSocketInt = NULL;
5441
5442 if ((fFlags & VD_INTERFACETCPNET_CONNECT_EXTENDED_SELECT) != 0)
5443 return VERR_NOT_SUPPORTED;
5444
5445 pSocketInt = (PVDSOCKETINT)RTMemAllocZ(sizeof(VDSOCKETINT));
5446 if (!pSocketInt)
5447 return VERR_NO_MEMORY;
5448
5449 pSocketInt->hSocket = NIL_RTSOCKET;
5450 *pSock = pSocketInt;
5451 return VINF_SUCCESS;
5452}
5453
5454DECLCALLBACK(int) Medium::vdTcpSocketDestroy(VDSOCKET Sock)
5455{
5456 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5457
5458 if (pSocketInt->hSocket != NIL_RTSOCKET)
5459 RTTcpClientCloseEx(pSocketInt->hSocket, false /*fGracefulShutdown*/);
5460
5461 RTMemFree(pSocketInt);
5462
5463 return VINF_SUCCESS;
5464}
5465
5466DECLCALLBACK(int) Medium::vdTcpClientConnect(VDSOCKET Sock, const char *pszAddress, uint32_t uPort)
5467{
5468 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5469
5470 return RTTcpClientConnect(pszAddress, uPort, &pSocketInt->hSocket);
5471}
5472
5473DECLCALLBACK(int) Medium::vdTcpClientClose(VDSOCKET Sock)
5474{
5475 int rc = VINF_SUCCESS;
5476 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5477
5478 rc = RTTcpClientCloseEx(pSocketInt->hSocket, false /*fGracefulShutdown*/);
5479 pSocketInt->hSocket = NIL_RTSOCKET;
5480 return rc;
5481}
5482
5483DECLCALLBACK(bool) Medium::vdTcpIsClientConnected(VDSOCKET Sock)
5484{
5485 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5486 return pSocketInt->hSocket != NIL_RTSOCKET;
5487}
5488
5489DECLCALLBACK(int) Medium::vdTcpSelectOne(VDSOCKET Sock, RTMSINTERVAL cMillies)
5490{
5491 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5492 return RTTcpSelectOne(pSocketInt->hSocket, cMillies);
5493}
5494
5495DECLCALLBACK(int) Medium::vdTcpRead(VDSOCKET Sock, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
5496{
5497 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5498 return RTTcpRead(pSocketInt->hSocket, pvBuffer, cbBuffer, pcbRead);
5499}
5500
5501DECLCALLBACK(int) Medium::vdTcpWrite(VDSOCKET Sock, const void *pvBuffer, size_t cbBuffer)
5502{
5503 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5504 return RTTcpWrite(pSocketInt->hSocket, pvBuffer, cbBuffer);
5505}
5506
5507DECLCALLBACK(int) Medium::vdTcpSgWrite(VDSOCKET Sock, PCRTSGBUF pSgBuf)
5508{
5509 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5510 return RTTcpSgWrite(pSocketInt->hSocket, pSgBuf);
5511}
5512
5513DECLCALLBACK(int) Medium::vdTcpFlush(VDSOCKET Sock)
5514{
5515 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5516 return RTTcpFlush(pSocketInt->hSocket);
5517}
5518
5519DECLCALLBACK(int) Medium::vdTcpSetSendCoalescing(VDSOCKET Sock, bool fEnable)
5520{
5521 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5522 return RTTcpSetSendCoalescing(pSocketInt->hSocket, fEnable);
5523}
5524
5525DECLCALLBACK(int) Medium::vdTcpGetLocalAddress(VDSOCKET Sock, PRTNETADDR pAddr)
5526{
5527 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5528 return RTTcpGetLocalAddress(pSocketInt->hSocket, pAddr);
5529}
5530
5531DECLCALLBACK(int) Medium::vdTcpGetPeerAddress(VDSOCKET Sock, PRTNETADDR pAddr)
5532{
5533 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5534 return RTTcpGetPeerAddress(pSocketInt->hSocket, pAddr);
5535}
5536
5537
5538/**
5539 * Starts a new thread driven by the appropriate Medium::Task::handler() method.
5540 *
5541 * @note When the task is executed by this method, IProgress::notifyComplete()
5542 * is automatically called for the progress object associated with this
5543 * task when the task is finished to signal the operation completion for
5544 * other threads asynchronously waiting for it.
5545 */
5546HRESULT Medium::startThread(Medium::Task *pTask)
5547{
5548#ifdef VBOX_WITH_MAIN_LOCK_VALIDATION
5549 /* Extreme paranoia: The calling thread should not hold the medium
5550 * tree lock or any medium lock. Since there is no separate lock class
5551 * for medium objects be even more strict: no other object locks. */
5552 Assert(!AutoLockHoldsLocksInClass(LOCKCLASS_LISTOFMEDIA));
5553 Assert(!AutoLockHoldsLocksInClass(getLockingClass()));
5554#endif
5555
5556 /// @todo use a more descriptive task name
5557 int vrc = RTThreadCreate(NULL, Medium::Task::fntMediumTask, pTask,
5558 0, RTTHREADTYPE_MAIN_HEAVY_WORKER, 0,
5559 "Medium::Task");
5560 if (RT_FAILURE(vrc))
5561 {
5562 delete pTask;
5563 return setError(E_FAIL, "Could not create Medium::Task thread (%Rrc)\n", vrc);
5564 }
5565
5566 return S_OK;
5567}
5568
5569/**
5570 * Fix the parent UUID of all children to point to this medium as their
5571 * parent.
5572 */
5573HRESULT Medium::fixParentUuidOfChildren(const MediaList &childrenToReparent)
5574{
5575 MediumLockList mediumLockList;
5576 HRESULT rc = createMediumLockList(true /* fFailIfInaccessible */,
5577 false /* fMediumLockWrite */,
5578 this,
5579 mediumLockList);
5580 AssertComRCReturnRC(rc);
5581
5582 try
5583 {
5584 PVBOXHDD hdd;
5585 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
5586 ComAssertRCThrow(vrc, E_FAIL);
5587
5588 try
5589 {
5590 MediumLockList::Base::iterator lockListBegin =
5591 mediumLockList.GetBegin();
5592 MediumLockList::Base::iterator lockListEnd =
5593 mediumLockList.GetEnd();
5594 for (MediumLockList::Base::iterator it = lockListBegin;
5595 it != lockListEnd;
5596 ++it)
5597 {
5598 MediumLock &mediumLock = *it;
5599 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
5600 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
5601
5602 // open the medium
5603 vrc = VDOpen(hdd,
5604 pMedium->m->strFormat.c_str(),
5605 pMedium->m->strLocationFull.c_str(),
5606 VD_OPEN_FLAGS_READONLY,
5607 pMedium->m->vdImageIfaces);
5608 if (RT_FAILURE(vrc))
5609 throw vrc;
5610 }
5611
5612 for (MediaList::const_iterator it = childrenToReparent.begin();
5613 it != childrenToReparent.end();
5614 ++it)
5615 {
5616 /* VD_OPEN_FLAGS_INFO since UUID is wrong yet */
5617 vrc = VDOpen(hdd,
5618 (*it)->m->strFormat.c_str(),
5619 (*it)->m->strLocationFull.c_str(),
5620 VD_OPEN_FLAGS_INFO,
5621 (*it)->m->vdImageIfaces);
5622 if (RT_FAILURE(vrc))
5623 throw vrc;
5624
5625 vrc = VDSetParentUuid(hdd, VD_LAST_IMAGE, m->id.raw());
5626 if (RT_FAILURE(vrc))
5627 throw vrc;
5628
5629 vrc = VDClose(hdd, false /* fDelete */);
5630 if (RT_FAILURE(vrc))
5631 throw vrc;
5632
5633 (*it)->UnlockWrite(NULL);
5634 }
5635 }
5636 catch (HRESULT aRC) { rc = aRC; }
5637 catch (int aVRC)
5638 {
5639 throw setError(E_FAIL,
5640 tr("Could not update medium UUID references to parent '%s' (%s)"),
5641 m->strLocationFull.c_str(),
5642 vdError(aVRC).c_str());
5643 }
5644
5645 VDDestroy(hdd);
5646 }
5647 catch (HRESULT aRC) { rc = aRC; }
5648
5649 return rc;
5650}
5651
5652/**
5653 * Runs Medium::Task::handler() on the current thread instead of creating
5654 * a new one.
5655 *
5656 * This call implies that it is made on another temporary thread created for
5657 * some asynchronous task. Avoid calling it from a normal thread since the task
5658 * operations are potentially lengthy and will block the calling thread in this
5659 * case.
5660 *
5661 * @note When the task is executed by this method, IProgress::notifyComplete()
5662 * is not called for the progress object associated with this task when
5663 * the task is finished. Instead, the result of the operation is returned
5664 * by this method directly and it's the caller's responsibility to
5665 * complete the progress object in this case.
5666 */
5667HRESULT Medium::runNow(Medium::Task *pTask,
5668 bool *pfNeedsGlobalSaveSettings)
5669{
5670#ifdef VBOX_WITH_MAIN_LOCK_VALIDATION
5671 /* Extreme paranoia: The calling thread should not hold the medium
5672 * tree lock or any medium lock. Since there is no separate lock class
5673 * for medium objects be even more strict: no other object locks. */
5674 Assert(!AutoLockHoldsLocksInClass(LOCKCLASS_LISTOFMEDIA));
5675 Assert(!AutoLockHoldsLocksInClass(getLockingClass()));
5676#endif
5677
5678 pTask->m_pfNeedsGlobalSaveSettings = pfNeedsGlobalSaveSettings;
5679
5680 /* NIL_RTTHREAD indicates synchronous call. */
5681 return (HRESULT)Medium::Task::fntMediumTask(NIL_RTTHREAD, pTask);
5682}
5683
5684/**
5685 * Implementation code for the "create base" task.
5686 *
5687 * This only gets started from Medium::CreateBaseStorage() and always runs
5688 * asynchronously. As a result, we always save the VirtualBox.xml file when
5689 * we're done here.
5690 *
5691 * @param task
5692 * @return
5693 */
5694HRESULT Medium::taskCreateBaseHandler(Medium::CreateBaseTask &task)
5695{
5696 HRESULT rc = S_OK;
5697
5698 /* these parameters we need after creation */
5699 uint64_t size = 0, logicalSize = 0;
5700 MediumVariant_T variant = MediumVariant_Standard;
5701 bool fGenerateUuid = false;
5702
5703 try
5704 {
5705 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
5706
5707 /* The object may request a specific UUID (through a special form of
5708 * the setLocation() argument). Otherwise we have to generate it */
5709 Guid id = m->id;
5710 fGenerateUuid = id.isEmpty();
5711 if (fGenerateUuid)
5712 {
5713 id.create();
5714 /* VirtualBox::registerHardDisk() will need UUID */
5715 unconst(m->id) = id;
5716 }
5717
5718 Utf8Str format(m->strFormat);
5719 Utf8Str location(m->strLocationFull);
5720 uint64_t capabilities = m->formatObj->getCapabilities();
5721 ComAssertThrow(capabilities & ( VD_CAP_CREATE_FIXED
5722 | VD_CAP_CREATE_DYNAMIC), E_FAIL);
5723 Assert(m->state == MediumState_Creating);
5724
5725 PVBOXHDD hdd;
5726 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
5727 ComAssertRCThrow(vrc, E_FAIL);
5728
5729 /* unlock before the potentially lengthy operation */
5730 thisLock.release();
5731
5732 try
5733 {
5734 /* ensure the directory exists */
5735 rc = VirtualBox::ensureFilePathExists(location);
5736 if (FAILED(rc))
5737 throw rc;
5738
5739 VDGEOMETRY geo = { 0, 0, 0 }; /* auto-detect */
5740
5741 vrc = VDCreateBase(hdd,
5742 format.c_str(),
5743 location.c_str(),
5744 task.mSize,
5745 task.mVariant,
5746 NULL,
5747 &geo,
5748 &geo,
5749 id.raw(),
5750 VD_OPEN_FLAGS_NORMAL,
5751 m->vdImageIfaces,
5752 task.mVDOperationIfaces);
5753 if (RT_FAILURE(vrc))
5754 throw setError(VBOX_E_FILE_ERROR,
5755 tr("Could not create the medium storage unit '%s'%s"),
5756 location.c_str(), vdError(vrc).c_str());
5757
5758 size = VDGetFileSize(hdd, 0);
5759 logicalSize = VDGetSize(hdd, 0);
5760 unsigned uImageFlags;
5761 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
5762 if (RT_SUCCESS(vrc))
5763 variant = (MediumVariant_T)uImageFlags;
5764 }
5765 catch (HRESULT aRC) { rc = aRC; }
5766
5767 VDDestroy(hdd);
5768 }
5769 catch (HRESULT aRC) { rc = aRC; }
5770
5771 if (SUCCEEDED(rc))
5772 {
5773 /* register with mVirtualBox as the last step and move to
5774 * Created state only on success (leaving an orphan file is
5775 * better than breaking media registry consistency) */
5776 bool fNeedsGlobalSaveSettings = false;
5777 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5778 rc = m->pVirtualBox->registerHardDisk(this, &fNeedsGlobalSaveSettings);
5779 treeLock.release();
5780
5781 if (fNeedsGlobalSaveSettings)
5782 {
5783 AutoWriteLock vboxlock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
5784 m->pVirtualBox->saveSettings();
5785 }
5786 }
5787
5788 // reenter the lock before changing state
5789 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
5790
5791 if (SUCCEEDED(rc))
5792 {
5793 m->state = MediumState_Created;
5794
5795 m->size = size;
5796 m->logicalSize = logicalSize;
5797 m->variant = variant;
5798 }
5799 else
5800 {
5801 /* back to NotCreated on failure */
5802 m->state = MediumState_NotCreated;
5803
5804 /* reset UUID to prevent it from being reused next time */
5805 if (fGenerateUuid)
5806 unconst(m->id).clear();
5807 }
5808
5809 return rc;
5810}
5811
5812/**
5813 * Implementation code for the "create diff" task.
5814 *
5815 * This task always gets started from Medium::createDiffStorage() and can run
5816 * synchronously or asynchronously depending on the "wait" parameter passed to
5817 * that function. If we run synchronously, the caller expects the bool
5818 * *pfNeedsGlobalSaveSettings to be set before returning; otherwise (in asynchronous
5819 * mode), we save the settings ourselves.
5820 *
5821 * @param task
5822 * @return
5823 */
5824HRESULT Medium::taskCreateDiffHandler(Medium::CreateDiffTask &task)
5825{
5826 HRESULT rc = S_OK;
5827
5828 bool fNeedsGlobalSaveSettings = false;
5829
5830 const ComObjPtr<Medium> &pTarget = task.mTarget;
5831
5832 uint64_t size = 0, logicalSize = 0;
5833 MediumVariant_T variant = MediumVariant_Standard;
5834 bool fGenerateUuid = false;
5835
5836 try
5837 {
5838 /* Lock both in {parent,child} order. */
5839 AutoMultiWriteLock2 mediaLock(this, pTarget COMMA_LOCKVAL_SRC_POS);
5840
5841 /* The object may request a specific UUID (through a special form of
5842 * the setLocation() argument). Otherwise we have to generate it */
5843 Guid targetId = pTarget->m->id;
5844 fGenerateUuid = targetId.isEmpty();
5845 if (fGenerateUuid)
5846 {
5847 targetId.create();
5848 /* VirtualBox::registerHardDisk() will need UUID */
5849 unconst(pTarget->m->id) = targetId;
5850 }
5851
5852 Guid id = m->id;
5853
5854 Utf8Str targetFormat(pTarget->m->strFormat);
5855 Utf8Str targetLocation(pTarget->m->strLocationFull);
5856 uint64_t capabilities = m->formatObj->getCapabilities();
5857 ComAssertThrow(capabilities & VD_CAP_CREATE_DYNAMIC, E_FAIL);
5858
5859 Assert(pTarget->m->state == MediumState_Creating);
5860 Assert(m->state == MediumState_LockedRead);
5861
5862 PVBOXHDD hdd;
5863 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
5864 ComAssertRCThrow(vrc, E_FAIL);
5865
5866 /* the two media are now protected by their non-default states;
5867 * unlock the media before the potentially lengthy operation */
5868 mediaLock.release();
5869
5870 try
5871 {
5872 /* Open all media in the target chain but the last. */
5873 MediumLockList::Base::const_iterator targetListBegin =
5874 task.mpMediumLockList->GetBegin();
5875 MediumLockList::Base::const_iterator targetListEnd =
5876 task.mpMediumLockList->GetEnd();
5877 for (MediumLockList::Base::const_iterator it = targetListBegin;
5878 it != targetListEnd;
5879 ++it)
5880 {
5881 const MediumLock &mediumLock = *it;
5882 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
5883
5884 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
5885
5886 /* Skip over the target diff medium */
5887 if (pMedium->m->state == MediumState_Creating)
5888 continue;
5889
5890 /* sanity check */
5891 Assert(pMedium->m->state == MediumState_LockedRead);
5892
5893 /* Open all media in appropriate mode. */
5894 vrc = VDOpen(hdd,
5895 pMedium->m->strFormat.c_str(),
5896 pMedium->m->strLocationFull.c_str(),
5897 VD_OPEN_FLAGS_READONLY,
5898 pMedium->m->vdImageIfaces);
5899 if (RT_FAILURE(vrc))
5900 throw setError(VBOX_E_FILE_ERROR,
5901 tr("Could not open the medium storage unit '%s'%s"),
5902 pMedium->m->strLocationFull.c_str(),
5903 vdError(vrc).c_str());
5904 }
5905
5906 /* ensure the target directory exists */
5907 rc = VirtualBox::ensureFilePathExists(targetLocation);
5908 if (FAILED(rc))
5909 throw rc;
5910
5911 vrc = VDCreateDiff(hdd,
5912 targetFormat.c_str(),
5913 targetLocation.c_str(),
5914 task.mVariant | VD_IMAGE_FLAGS_DIFF,
5915 NULL,
5916 targetId.raw(),
5917 id.raw(),
5918 VD_OPEN_FLAGS_NORMAL,
5919 pTarget->m->vdImageIfaces,
5920 task.mVDOperationIfaces);
5921 if (RT_FAILURE(vrc))
5922 throw setError(VBOX_E_FILE_ERROR,
5923 tr("Could not create the differencing medium storage unit '%s'%s"),
5924 targetLocation.c_str(), vdError(vrc).c_str());
5925
5926 size = VDGetFileSize(hdd, VD_LAST_IMAGE);
5927 logicalSize = VDGetSize(hdd, VD_LAST_IMAGE);
5928 unsigned uImageFlags;
5929 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
5930 if (RT_SUCCESS(vrc))
5931 variant = (MediumVariant_T)uImageFlags;
5932 }
5933 catch (HRESULT aRC) { rc = aRC; }
5934
5935 VDDestroy(hdd);
5936 }
5937 catch (HRESULT aRC) { rc = aRC; }
5938
5939 if (SUCCEEDED(rc))
5940 {
5941 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5942
5943 Assert(pTarget->m->pParent.isNull());
5944
5945 /* associate the child with the parent */
5946 pTarget->m->pParent = this;
5947 m->llChildren.push_back(pTarget);
5948
5949 /** @todo r=klaus neither target nor base() are locked,
5950 * potential race! */
5951 /* diffs for immutable media are auto-reset by default */
5952 pTarget->m->autoReset = (getBase()->m->type == MediumType_Immutable);
5953
5954 /* register with mVirtualBox as the last step and move to
5955 * Created state only on success (leaving an orphan file is
5956 * better than breaking media registry consistency) */
5957 rc = m->pVirtualBox->registerHardDisk(pTarget, &fNeedsGlobalSaveSettings);
5958
5959 if (FAILED(rc))
5960 /* break the parent association on failure to register */
5961 deparent();
5962 }
5963
5964 AutoMultiWriteLock2 mediaLock(this, pTarget COMMA_LOCKVAL_SRC_POS);
5965
5966 if (SUCCEEDED(rc))
5967 {
5968 pTarget->m->state = MediumState_Created;
5969
5970 pTarget->m->size = size;
5971 pTarget->m->logicalSize = logicalSize;
5972 pTarget->m->variant = variant;
5973 }
5974 else
5975 {
5976 /* back to NotCreated on failure */
5977 pTarget->m->state = MediumState_NotCreated;
5978
5979 pTarget->m->autoReset = false;
5980
5981 /* reset UUID to prevent it from being reused next time */
5982 if (fGenerateUuid)
5983 unconst(pTarget->m->id).clear();
5984 }
5985
5986 // deregister the task registered in createDiffStorage()
5987 Assert(m->numCreateDiffTasks != 0);
5988 --m->numCreateDiffTasks;
5989
5990 if (task.isAsync())
5991 {
5992 if (fNeedsGlobalSaveSettings)
5993 {
5994 // save the global settings; for that we should hold only the VirtualBox lock
5995 mediaLock.release();
5996 AutoWriteLock vboxlock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
5997 m->pVirtualBox->saveSettings();
5998 }
5999 }
6000 else
6001 // synchronous mode: report save settings result to caller
6002 if (task.m_pfNeedsGlobalSaveSettings)
6003 *task.m_pfNeedsGlobalSaveSettings = fNeedsGlobalSaveSettings;
6004
6005 /* Note that in sync mode, it's the caller's responsibility to
6006 * unlock the medium. */
6007
6008 return rc;
6009}
6010
6011/**
6012 * Implementation code for the "merge" task.
6013 *
6014 * This task always gets started from Medium::mergeTo() and can run
6015 * synchronously or asynchrously depending on the "wait" parameter passed to
6016 * that function. If we run synchronously, the caller expects the bool
6017 * *pfNeedsGlobalSaveSettings to be set before returning; otherwise (in asynchronous
6018 * mode), we save the settings ourselves.
6019 *
6020 * @param task
6021 * @return
6022 */
6023HRESULT Medium::taskMergeHandler(Medium::MergeTask &task)
6024{
6025 HRESULT rc = S_OK;
6026
6027 const ComObjPtr<Medium> &pTarget = task.mTarget;
6028
6029 try
6030 {
6031 PVBOXHDD hdd;
6032 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
6033 ComAssertRCThrow(vrc, E_FAIL);
6034
6035 try
6036 {
6037 // Similar code appears in SessionMachine::onlineMergeMedium, so
6038 // if you make any changes below check whether they are applicable
6039 // in that context as well.
6040
6041 unsigned uTargetIdx = VD_LAST_IMAGE;
6042 unsigned uSourceIdx = VD_LAST_IMAGE;
6043 /* Open all media in the chain. */
6044 MediumLockList::Base::iterator lockListBegin =
6045 task.mpMediumLockList->GetBegin();
6046 MediumLockList::Base::iterator lockListEnd =
6047 task.mpMediumLockList->GetEnd();
6048 unsigned i = 0;
6049 for (MediumLockList::Base::iterator it = lockListBegin;
6050 it != lockListEnd;
6051 ++it)
6052 {
6053 MediumLock &mediumLock = *it;
6054 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
6055
6056 if (pMedium == this)
6057 uSourceIdx = i;
6058 else if (pMedium == pTarget)
6059 uTargetIdx = i;
6060
6061 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
6062
6063 /*
6064 * complex sanity (sane complexity)
6065 *
6066 * The current medium must be in the Deleting (medium is merged)
6067 * or LockedRead (parent medium) state if it is not the target.
6068 * If it is the target it must be in the LockedWrite state.
6069 */
6070 Assert( ( pMedium != pTarget
6071 && ( pMedium->m->state == MediumState_Deleting
6072 || pMedium->m->state == MediumState_LockedRead))
6073 || ( pMedium == pTarget
6074 && pMedium->m->state == MediumState_LockedWrite));
6075
6076 /*
6077 * Medium must be the target, in the LockedRead state
6078 * or Deleting state where it is not allowed to be attached
6079 * to a virtual machine.
6080 */
6081 Assert( pMedium == pTarget
6082 || pMedium->m->state == MediumState_LockedRead
6083 || ( pMedium->m->backRefs.size() == 0
6084 && pMedium->m->state == MediumState_Deleting));
6085 /* The source medium must be in Deleting state. */
6086 Assert( pMedium != this
6087 || pMedium->m->state == MediumState_Deleting);
6088
6089 unsigned uOpenFlags = VD_OPEN_FLAGS_NORMAL;
6090
6091 if ( pMedium->m->state == MediumState_LockedRead
6092 || pMedium->m->state == MediumState_Deleting)
6093 uOpenFlags = VD_OPEN_FLAGS_READONLY;
6094 if (pMedium->m->type == MediumType_Shareable)
6095 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
6096
6097 /* Open the medium */
6098 vrc = VDOpen(hdd,
6099 pMedium->m->strFormat.c_str(),
6100 pMedium->m->strLocationFull.c_str(),
6101 uOpenFlags,
6102 pMedium->m->vdImageIfaces);
6103 if (RT_FAILURE(vrc))
6104 throw vrc;
6105
6106 i++;
6107 }
6108
6109 ComAssertThrow( uSourceIdx != VD_LAST_IMAGE
6110 && uTargetIdx != VD_LAST_IMAGE, E_FAIL);
6111
6112 vrc = VDMerge(hdd, uSourceIdx, uTargetIdx,
6113 task.mVDOperationIfaces);
6114 if (RT_FAILURE(vrc))
6115 throw vrc;
6116
6117 /* update parent UUIDs */
6118 if (!task.mfMergeForward)
6119 {
6120 /* we need to update UUIDs of all source's children
6121 * which cannot be part of the container at once so
6122 * add each one in there individually */
6123 if (task.mChildrenToReparent.size() > 0)
6124 {
6125 for (MediaList::const_iterator it = task.mChildrenToReparent.begin();
6126 it != task.mChildrenToReparent.end();
6127 ++it)
6128 {
6129 /* VD_OPEN_FLAGS_INFO since UUID is wrong yet */
6130 vrc = VDOpen(hdd,
6131 (*it)->m->strFormat.c_str(),
6132 (*it)->m->strLocationFull.c_str(),
6133 VD_OPEN_FLAGS_INFO,
6134 (*it)->m->vdImageIfaces);
6135 if (RT_FAILURE(vrc))
6136 throw vrc;
6137
6138 vrc = VDSetParentUuid(hdd, VD_LAST_IMAGE,
6139 pTarget->m->id.raw());
6140 if (RT_FAILURE(vrc))
6141 throw vrc;
6142
6143 vrc = VDClose(hdd, false /* fDelete */);
6144 if (RT_FAILURE(vrc))
6145 throw vrc;
6146
6147 (*it)->UnlockWrite(NULL);
6148 }
6149 }
6150 }
6151 }
6152 catch (HRESULT aRC) { rc = aRC; }
6153 catch (int aVRC)
6154 {
6155 throw setError(VBOX_E_FILE_ERROR,
6156 tr("Could not merge the medium '%s' to '%s'%s"),
6157 m->strLocationFull.c_str(),
6158 pTarget->m->strLocationFull.c_str(),
6159 vdError(aVRC).c_str());
6160 }
6161
6162 VDDestroy(hdd);
6163 }
6164 catch (HRESULT aRC) { rc = aRC; }
6165
6166 HRESULT rc2;
6167
6168 if (SUCCEEDED(rc))
6169 {
6170 /* all media but the target were successfully deleted by
6171 * VDMerge; reparent the last one and uninitialize deleted media. */
6172
6173 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
6174
6175 if (task.mfMergeForward)
6176 {
6177 /* first, unregister the target since it may become a base
6178 * medium which needs re-registration */
6179 rc2 = m->pVirtualBox->unregisterHardDisk(pTarget, NULL /*&fNeedsGlobalSaveSettings*/);
6180 AssertComRC(rc2);
6181
6182 /* then, reparent it and disconnect the deleted branch at
6183 * both ends (chain->parent() is source's parent) */
6184 pTarget->deparent();
6185 pTarget->m->pParent = task.mParentForTarget;
6186 if (pTarget->m->pParent)
6187 {
6188 pTarget->m->pParent->m->llChildren.push_back(pTarget);
6189 deparent();
6190 }
6191
6192 /* then, register again */
6193 rc2 = m->pVirtualBox->registerHardDisk(pTarget, NULL /*&fNeedsGlobalSaveSettings*/);
6194 AssertComRC(rc2);
6195 }
6196 else
6197 {
6198 Assert(pTarget->getChildren().size() == 1);
6199 Medium *targetChild = pTarget->getChildren().front();
6200
6201 /* disconnect the deleted branch at the elder end */
6202 targetChild->deparent();
6203
6204 /* reparent source's children and disconnect the deleted
6205 * branch at the younger end */
6206 if (task.mChildrenToReparent.size() > 0)
6207 {
6208 /* obey {parent,child} lock order */
6209 AutoWriteLock sourceLock(this COMMA_LOCKVAL_SRC_POS);
6210
6211 for (MediaList::const_iterator it = task.mChildrenToReparent.begin();
6212 it != task.mChildrenToReparent.end();
6213 it++)
6214 {
6215 Medium *pMedium = *it;
6216 AutoWriteLock childLock(pMedium COMMA_LOCKVAL_SRC_POS);
6217
6218 pMedium->deparent(); // removes pMedium from source
6219 pMedium->setParent(pTarget);
6220 }
6221 }
6222 }
6223
6224 /* unregister and uninitialize all media removed by the merge */
6225 MediumLockList::Base::iterator lockListBegin =
6226 task.mpMediumLockList->GetBegin();
6227 MediumLockList::Base::iterator lockListEnd =
6228 task.mpMediumLockList->GetEnd();
6229 for (MediumLockList::Base::iterator it = lockListBegin;
6230 it != lockListEnd;
6231 )
6232 {
6233 MediumLock &mediumLock = *it;
6234 /* Create a real copy of the medium pointer, as the medium
6235 * lock deletion below would invalidate the referenced object. */
6236 const ComObjPtr<Medium> pMedium = mediumLock.GetMedium();
6237
6238 /* The target and all media not merged (readonly) are skipped */
6239 if ( pMedium == pTarget
6240 || pMedium->m->state == MediumState_LockedRead)
6241 {
6242 ++it;
6243 continue;
6244 }
6245
6246 rc2 = pMedium->m->pVirtualBox->unregisterHardDisk(pMedium,
6247 NULL /*pfNeedsGlobalSaveSettings*/);
6248 AssertComRC(rc2);
6249
6250 /* now, uninitialize the deleted medium (note that
6251 * due to the Deleting state, uninit() will not touch
6252 * the parent-child relationship so we need to
6253 * uninitialize each disk individually) */
6254
6255 /* note that the operation initiator medium (which is
6256 * normally also the source medium) is a special case
6257 * -- there is one more caller added by Task to it which
6258 * we must release. Also, if we are in sync mode, the
6259 * caller may still hold an AutoCaller instance for it
6260 * and therefore we cannot uninit() it (it's therefore
6261 * the caller's responsibility) */
6262 if (pMedium == this)
6263 {
6264 Assert(getChildren().size() == 0);
6265 Assert(m->backRefs.size() == 0);
6266 task.mMediumCaller.release();
6267 }
6268
6269 /* Delete the medium lock list entry, which also releases the
6270 * caller added by MergeChain before uninit() and updates the
6271 * iterator to point to the right place. */
6272 rc2 = task.mpMediumLockList->RemoveByIterator(it);
6273 AssertComRC(rc2);
6274
6275 if (task.isAsync() || pMedium != this)
6276 pMedium->uninit();
6277 }
6278 }
6279
6280 if (task.isAsync())
6281 {
6282 // in asynchronous mode, save settings now
6283 // for that we should hold only the VirtualBox lock
6284 AutoWriteLock vboxlock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
6285 m->pVirtualBox->saveSettings();
6286 }
6287 else
6288 // synchronous mode: report save settings result to caller
6289 if (task.m_pfNeedsGlobalSaveSettings)
6290 *task.m_pfNeedsGlobalSaveSettings = true;
6291
6292 if (FAILED(rc))
6293 {
6294 /* Here we come if either VDMerge() failed (in which case we
6295 * assume that it tried to do everything to make a further
6296 * retry possible -- e.g. not deleted intermediate media
6297 * and so on) or VirtualBox::saveSettings() failed (where we
6298 * should have the original tree but with intermediate storage
6299 * units deleted by VDMerge()). We have to only restore states
6300 * (through the MergeChain dtor) unless we are run synchronously
6301 * in which case it's the responsibility of the caller as stated
6302 * in the mergeTo() docs. The latter also implies that we
6303 * don't own the merge chain, so release it in this case. */
6304 if (task.isAsync())
6305 {
6306 Assert(task.mChildrenToReparent.size() == 0);
6307 cancelMergeTo(task.mChildrenToReparent, task.mpMediumLockList);
6308 }
6309 }
6310
6311 return rc;
6312}
6313
6314/**
6315 * Implementation code for the "clone" task.
6316 *
6317 * This only gets started from Medium::CloneTo() and always runs asynchronously.
6318 * As a result, we always save the VirtualBox.xml file when we're done here.
6319 *
6320 * @param task
6321 * @return
6322 */
6323HRESULT Medium::taskCloneHandler(Medium::CloneTask &task)
6324{
6325 HRESULT rc = S_OK;
6326
6327 const ComObjPtr<Medium> &pTarget = task.mTarget;
6328 const ComObjPtr<Medium> &pParent = task.mParent;
6329
6330 bool fCreatingTarget = false;
6331
6332 uint64_t size = 0, logicalSize = 0;
6333 MediumVariant_T variant = MediumVariant_Standard;
6334 bool fGenerateUuid = false;
6335
6336 try
6337 {
6338 /* Lock all in {parent,child} order. The lock is also used as a
6339 * signal from the task initiator (which releases it only after
6340 * RTThreadCreate()) that we can start the job. */
6341 AutoMultiWriteLock3 thisLock(this, pTarget, pParent COMMA_LOCKVAL_SRC_POS);
6342
6343 fCreatingTarget = pTarget->m->state == MediumState_Creating;
6344
6345 /* The object may request a specific UUID (through a special form of
6346 * the setLocation() argument). Otherwise we have to generate it */
6347 Guid targetId = pTarget->m->id;
6348 fGenerateUuid = targetId.isEmpty();
6349 if (fGenerateUuid)
6350 {
6351 targetId.create();
6352 /* VirtualBox::registerHardDisk() will need UUID */
6353 unconst(pTarget->m->id) = targetId;
6354 }
6355
6356 PVBOXHDD hdd;
6357 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
6358 ComAssertRCThrow(vrc, E_FAIL);
6359
6360 try
6361 {
6362 /* Open all media in the source chain. */
6363 MediumLockList::Base::const_iterator sourceListBegin =
6364 task.mpSourceMediumLockList->GetBegin();
6365 MediumLockList::Base::const_iterator sourceListEnd =
6366 task.mpSourceMediumLockList->GetEnd();
6367 for (MediumLockList::Base::const_iterator it = sourceListBegin;
6368 it != sourceListEnd;
6369 ++it)
6370 {
6371 const MediumLock &mediumLock = *it;
6372 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
6373 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
6374
6375 /* sanity check */
6376 Assert(pMedium->m->state == MediumState_LockedRead);
6377
6378 /** Open all media in read-only mode. */
6379 vrc = VDOpen(hdd,
6380 pMedium->m->strFormat.c_str(),
6381 pMedium->m->strLocationFull.c_str(),
6382 VD_OPEN_FLAGS_READONLY,
6383 pMedium->m->vdImageIfaces);
6384 if (RT_FAILURE(vrc))
6385 throw setError(VBOX_E_FILE_ERROR,
6386 tr("Could not open the medium storage unit '%s'%s"),
6387 pMedium->m->strLocationFull.c_str(),
6388 vdError(vrc).c_str());
6389 }
6390
6391 Utf8Str targetFormat(pTarget->m->strFormat);
6392 Utf8Str targetLocation(pTarget->m->strLocationFull);
6393
6394 Assert( pTarget->m->state == MediumState_Creating
6395 || pTarget->m->state == MediumState_LockedWrite);
6396 Assert(m->state == MediumState_LockedRead);
6397 Assert(pParent.isNull() || pParent->m->state == MediumState_LockedRead);
6398
6399 /* unlock before the potentially lengthy operation */
6400 thisLock.release();
6401
6402 /* ensure the target directory exists */
6403 rc = VirtualBox::ensureFilePathExists(targetLocation);
6404 if (FAILED(rc))
6405 throw rc;
6406
6407 PVBOXHDD targetHdd;
6408 vrc = VDCreate(m->vdDiskIfaces, &targetHdd);
6409 ComAssertRCThrow(vrc, E_FAIL);
6410
6411 try
6412 {
6413 /* Open all media in the target chain. */
6414 MediumLockList::Base::const_iterator targetListBegin =
6415 task.mpTargetMediumLockList->GetBegin();
6416 MediumLockList::Base::const_iterator targetListEnd =
6417 task.mpTargetMediumLockList->GetEnd();
6418 for (MediumLockList::Base::const_iterator it = targetListBegin;
6419 it != targetListEnd;
6420 ++it)
6421 {
6422 const MediumLock &mediumLock = *it;
6423 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
6424
6425 /* If the target medium is not created yet there's no
6426 * reason to open it. */
6427 if (pMedium == pTarget && fCreatingTarget)
6428 continue;
6429
6430 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
6431
6432 /* sanity check */
6433 Assert( pMedium->m->state == MediumState_LockedRead
6434 || pMedium->m->state == MediumState_LockedWrite);
6435
6436 unsigned uOpenFlags = VD_OPEN_FLAGS_NORMAL;
6437 if (pMedium->m->state != MediumState_LockedWrite)
6438 uOpenFlags = VD_OPEN_FLAGS_READONLY;
6439 if (pMedium->m->type == MediumType_Shareable)
6440 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
6441
6442 /* Open all media in appropriate mode. */
6443 vrc = VDOpen(targetHdd,
6444 pMedium->m->strFormat.c_str(),
6445 pMedium->m->strLocationFull.c_str(),
6446 uOpenFlags,
6447 pMedium->m->vdImageIfaces);
6448 if (RT_FAILURE(vrc))
6449 throw setError(VBOX_E_FILE_ERROR,
6450 tr("Could not open the medium storage unit '%s'%s"),
6451 pMedium->m->strLocationFull.c_str(),
6452 vdError(vrc).c_str());
6453 }
6454
6455 /** @todo r=klaus target isn't locked, race getting the state */
6456 vrc = VDCopy(hdd,
6457 VD_LAST_IMAGE,
6458 targetHdd,
6459 targetFormat.c_str(),
6460 (fCreatingTarget) ? targetLocation.c_str() : (char *)NULL,
6461 false /* fMoveByRename */,
6462 0 /* cbSize */,
6463 task.mVariant,
6464 targetId.raw(),
6465 NULL /* pVDIfsOperation */,
6466 pTarget->m->vdImageIfaces,
6467 task.mVDOperationIfaces);
6468 if (RT_FAILURE(vrc))
6469 throw setError(VBOX_E_FILE_ERROR,
6470 tr("Could not create the clone medium '%s'%s"),
6471 targetLocation.c_str(), vdError(vrc).c_str());
6472
6473 size = VDGetFileSize(targetHdd, VD_LAST_IMAGE);
6474 logicalSize = VDGetSize(targetHdd, VD_LAST_IMAGE);
6475 unsigned uImageFlags;
6476 vrc = VDGetImageFlags(targetHdd, 0, &uImageFlags);
6477 if (RT_SUCCESS(vrc))
6478 variant = (MediumVariant_T)uImageFlags;
6479 }
6480 catch (HRESULT aRC) { rc = aRC; }
6481
6482 VDDestroy(targetHdd);
6483 }
6484 catch (HRESULT aRC) { rc = aRC; }
6485
6486 VDDestroy(hdd);
6487 }
6488 catch (HRESULT aRC) { rc = aRC; }
6489
6490 /* Only do the parent changes for newly created media. */
6491 if (SUCCEEDED(rc) && fCreatingTarget)
6492 {
6493 /* we set mParent & children() */
6494 AutoWriteLock alock2(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
6495
6496 Assert(pTarget->m->pParent.isNull());
6497
6498 if (pParent)
6499 {
6500 /* associate the clone with the parent and deassociate
6501 * from VirtualBox */
6502 pTarget->m->pParent = pParent;
6503 pParent->m->llChildren.push_back(pTarget);
6504
6505 /* register with mVirtualBox as the last step and move to
6506 * Created state only on success (leaving an orphan file is
6507 * better than breaking media registry consistency) */
6508 rc = pParent->m->pVirtualBox->registerHardDisk(pTarget, NULL /* pfNeedsGlobalSaveSettings */);
6509
6510 if (FAILED(rc))
6511 /* break parent association on failure to register */
6512 pTarget->deparent(); // removes target from parent
6513 }
6514 else
6515 {
6516 /* just register */
6517 rc = m->pVirtualBox->registerHardDisk(pTarget, NULL /* pfNeedsGlobalSaveSettings */);
6518 }
6519 }
6520
6521 if (fCreatingTarget)
6522 {
6523 AutoWriteLock mLock(pTarget COMMA_LOCKVAL_SRC_POS);
6524
6525 if (SUCCEEDED(rc))
6526 {
6527 pTarget->m->state = MediumState_Created;
6528
6529 pTarget->m->size = size;
6530 pTarget->m->logicalSize = logicalSize;
6531 pTarget->m->variant = variant;
6532 }
6533 else
6534 {
6535 /* back to NotCreated on failure */
6536 pTarget->m->state = MediumState_NotCreated;
6537
6538 /* reset UUID to prevent it from being reused next time */
6539 if (fGenerateUuid)
6540 unconst(pTarget->m->id).clear();
6541 }
6542 }
6543
6544 // now, at the end of this task (always asynchronous), save the settings
6545 {
6546 AutoWriteLock vboxlock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
6547 m->pVirtualBox->saveSettings();
6548 }
6549
6550 /* Everything is explicitly unlocked when the task exits,
6551 * as the task destruction also destroys the source chain. */
6552
6553 /* Make sure the source chain is released early. It could happen
6554 * that we get a deadlock in Appliance::Import when Medium::Close
6555 * is called & the source chain is released at the same time. */
6556 task.mpSourceMediumLockList->Clear();
6557
6558 return rc;
6559}
6560
6561/**
6562 * Implementation code for the "delete" task.
6563 *
6564 * This task always gets started from Medium::deleteStorage() and can run
6565 * synchronously or asynchrously depending on the "wait" parameter passed to
6566 * that function.
6567 *
6568 * @param task
6569 * @return
6570 */
6571HRESULT Medium::taskDeleteHandler(Medium::DeleteTask &task)
6572{
6573 NOREF(task);
6574 HRESULT rc = S_OK;
6575
6576 try
6577 {
6578 /* The lock is also used as a signal from the task initiator (which
6579 * releases it only after RTThreadCreate()) that we can start the job */
6580 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6581
6582 PVBOXHDD hdd;
6583 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
6584 ComAssertRCThrow(vrc, E_FAIL);
6585
6586 Utf8Str format(m->strFormat);
6587 Utf8Str location(m->strLocationFull);
6588
6589 /* unlock before the potentially lengthy operation */
6590 Assert(m->state == MediumState_Deleting);
6591 thisLock.release();
6592
6593 try
6594 {
6595 vrc = VDOpen(hdd,
6596 format.c_str(),
6597 location.c_str(),
6598 VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO,
6599 m->vdImageIfaces);
6600 if (RT_SUCCESS(vrc))
6601 vrc = VDClose(hdd, true /* fDelete */);
6602
6603 if (RT_FAILURE(vrc))
6604 throw setError(VBOX_E_FILE_ERROR,
6605 tr("Could not delete the medium storage unit '%s'%s"),
6606 location.c_str(), vdError(vrc).c_str());
6607
6608 }
6609 catch (HRESULT aRC) { rc = aRC; }
6610
6611 VDDestroy(hdd);
6612 }
6613 catch (HRESULT aRC) { rc = aRC; }
6614
6615 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6616
6617 /* go to the NotCreated state even on failure since the storage
6618 * may have been already partially deleted and cannot be used any
6619 * more. One will be able to manually re-open the storage if really
6620 * needed to re-register it. */
6621 m->state = MediumState_NotCreated;
6622
6623 /* Reset UUID to prevent Create* from reusing it again */
6624 unconst(m->id).clear();
6625
6626 return rc;
6627}
6628
6629/**
6630 * Implementation code for the "reset" task.
6631 *
6632 * This always gets started asynchronously from Medium::Reset().
6633 *
6634 * @param task
6635 * @return
6636 */
6637HRESULT Medium::taskResetHandler(Medium::ResetTask &task)
6638{
6639 HRESULT rc = S_OK;
6640
6641 uint64_t size = 0, logicalSize = 0;
6642 MediumVariant_T variant = MediumVariant_Standard;
6643
6644 try
6645 {
6646 /* The lock is also used as a signal from the task initiator (which
6647 * releases it only after RTThreadCreate()) that we can start the job */
6648 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6649
6650 /// @todo Below we use a pair of delete/create operations to reset
6651 /// the diff contents but the most efficient way will of course be
6652 /// to add a VDResetDiff() API call
6653
6654 PVBOXHDD hdd;
6655 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
6656 ComAssertRCThrow(vrc, E_FAIL);
6657
6658 Guid id = m->id;
6659 Utf8Str format(m->strFormat);
6660 Utf8Str location(m->strLocationFull);
6661
6662 Medium *pParent = m->pParent;
6663 Guid parentId = pParent->m->id;
6664 Utf8Str parentFormat(pParent->m->strFormat);
6665 Utf8Str parentLocation(pParent->m->strLocationFull);
6666
6667 Assert(m->state == MediumState_LockedWrite);
6668
6669 /* unlock before the potentially lengthy operation */
6670 thisLock.release();
6671
6672 try
6673 {
6674 /* Open all media in the target chain but the last. */
6675 MediumLockList::Base::const_iterator targetListBegin =
6676 task.mpMediumLockList->GetBegin();
6677 MediumLockList::Base::const_iterator targetListEnd =
6678 task.mpMediumLockList->GetEnd();
6679 for (MediumLockList::Base::const_iterator it = targetListBegin;
6680 it != targetListEnd;
6681 ++it)
6682 {
6683 const MediumLock &mediumLock = *it;
6684 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
6685
6686 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
6687
6688 /* sanity check, "this" is checked above */
6689 Assert( pMedium == this
6690 || pMedium->m->state == MediumState_LockedRead);
6691
6692 /* Open all media in appropriate mode. */
6693 vrc = VDOpen(hdd,
6694 pMedium->m->strFormat.c_str(),
6695 pMedium->m->strLocationFull.c_str(),
6696 VD_OPEN_FLAGS_READONLY,
6697 pMedium->m->vdImageIfaces);
6698 if (RT_FAILURE(vrc))
6699 throw setError(VBOX_E_FILE_ERROR,
6700 tr("Could not open the medium storage unit '%s'%s"),
6701 pMedium->m->strLocationFull.c_str(),
6702 vdError(vrc).c_str());
6703
6704 /* Done when we hit the media which should be reset */
6705 if (pMedium == this)
6706 break;
6707 }
6708
6709 /* first, delete the storage unit */
6710 vrc = VDClose(hdd, true /* fDelete */);
6711 if (RT_FAILURE(vrc))
6712 throw setError(VBOX_E_FILE_ERROR,
6713 tr("Could not delete the medium storage unit '%s'%s"),
6714 location.c_str(), vdError(vrc).c_str());
6715
6716 /* next, create it again */
6717 vrc = VDOpen(hdd,
6718 parentFormat.c_str(),
6719 parentLocation.c_str(),
6720 VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO,
6721 m->vdImageIfaces);
6722 if (RT_FAILURE(vrc))
6723 throw setError(VBOX_E_FILE_ERROR,
6724 tr("Could not open the medium storage unit '%s'%s"),
6725 parentLocation.c_str(), vdError(vrc).c_str());
6726
6727 vrc = VDCreateDiff(hdd,
6728 format.c_str(),
6729 location.c_str(),
6730 /// @todo use the same medium variant as before
6731 VD_IMAGE_FLAGS_NONE,
6732 NULL,
6733 id.raw(),
6734 parentId.raw(),
6735 VD_OPEN_FLAGS_NORMAL,
6736 m->vdImageIfaces,
6737 task.mVDOperationIfaces);
6738 if (RT_FAILURE(vrc))
6739 throw setError(VBOX_E_FILE_ERROR,
6740 tr("Could not create the differencing medium storage unit '%s'%s"),
6741 location.c_str(), vdError(vrc).c_str());
6742
6743 size = VDGetFileSize(hdd, VD_LAST_IMAGE);
6744 logicalSize = VDGetSize(hdd, VD_LAST_IMAGE);
6745 unsigned uImageFlags;
6746 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
6747 if (RT_SUCCESS(vrc))
6748 variant = (MediumVariant_T)uImageFlags;
6749 }
6750 catch (HRESULT aRC) { rc = aRC; }
6751
6752 VDDestroy(hdd);
6753 }
6754 catch (HRESULT aRC) { rc = aRC; }
6755
6756 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6757
6758 m->size = size;
6759 m->logicalSize = logicalSize;
6760 m->variant = variant;
6761
6762 if (task.isAsync())
6763 {
6764 /* unlock ourselves when done */
6765 HRESULT rc2 = UnlockWrite(NULL);
6766 AssertComRC(rc2);
6767 }
6768
6769 /* Note that in sync mode, it's the caller's responsibility to
6770 * unlock the medium. */
6771
6772 return rc;
6773}
6774
6775/**
6776 * Implementation code for the "compact" task.
6777 *
6778 * @param task
6779 * @return
6780 */
6781HRESULT Medium::taskCompactHandler(Medium::CompactTask &task)
6782{
6783 HRESULT rc = S_OK;
6784
6785 /* Lock all in {parent,child} order. The lock is also used as a
6786 * signal from the task initiator (which releases it only after
6787 * RTThreadCreate()) that we can start the job. */
6788 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6789
6790 try
6791 {
6792 PVBOXHDD hdd;
6793 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
6794 ComAssertRCThrow(vrc, E_FAIL);
6795
6796 try
6797 {
6798 /* Open all media in the chain. */
6799 MediumLockList::Base::const_iterator mediumListBegin =
6800 task.mpMediumLockList->GetBegin();
6801 MediumLockList::Base::const_iterator mediumListEnd =
6802 task.mpMediumLockList->GetEnd();
6803 MediumLockList::Base::const_iterator mediumListLast =
6804 mediumListEnd;
6805 mediumListLast--;
6806 for (MediumLockList::Base::const_iterator it = mediumListBegin;
6807 it != mediumListEnd;
6808 ++it)
6809 {
6810 const MediumLock &mediumLock = *it;
6811 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
6812 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
6813
6814 /* sanity check */
6815 if (it == mediumListLast)
6816 Assert(pMedium->m->state == MediumState_LockedWrite);
6817 else
6818 Assert(pMedium->m->state == MediumState_LockedRead);
6819
6820 /* Open all media but last in read-only mode. Do not handle
6821 * shareable media, as compaction and sharing are mutually
6822 * exclusive. */
6823 vrc = VDOpen(hdd,
6824 pMedium->m->strFormat.c_str(),
6825 pMedium->m->strLocationFull.c_str(),
6826 (it == mediumListLast) ? VD_OPEN_FLAGS_NORMAL : VD_OPEN_FLAGS_READONLY,
6827 pMedium->m->vdImageIfaces);
6828 if (RT_FAILURE(vrc))
6829 throw setError(VBOX_E_FILE_ERROR,
6830 tr("Could not open the medium storage unit '%s'%s"),
6831 pMedium->m->strLocationFull.c_str(),
6832 vdError(vrc).c_str());
6833 }
6834
6835 Assert(m->state == MediumState_LockedWrite);
6836
6837 Utf8Str location(m->strLocationFull);
6838
6839 /* unlock before the potentially lengthy operation */
6840 thisLock.release();
6841
6842 vrc = VDCompact(hdd, VD_LAST_IMAGE, task.mVDOperationIfaces);
6843 if (RT_FAILURE(vrc))
6844 {
6845 if (vrc == VERR_NOT_SUPPORTED)
6846 throw setError(VBOX_E_NOT_SUPPORTED,
6847 tr("Compacting is not yet supported for medium '%s'"),
6848 location.c_str());
6849 else if (vrc == VERR_NOT_IMPLEMENTED)
6850 throw setError(E_NOTIMPL,
6851 tr("Compacting is not implemented, medium '%s'"),
6852 location.c_str());
6853 else
6854 throw setError(VBOX_E_FILE_ERROR,
6855 tr("Could not compact medium '%s'%s"),
6856 location.c_str(),
6857 vdError(vrc).c_str());
6858 }
6859 }
6860 catch (HRESULT aRC) { rc = aRC; }
6861
6862 VDDestroy(hdd);
6863 }
6864 catch (HRESULT aRC) { rc = aRC; }
6865
6866 /* Everything is explicitly unlocked when the task exits,
6867 * as the task destruction also destroys the media chain. */
6868
6869 return rc;
6870}
6871
6872/**
6873 * Implementation code for the "resize" task.
6874 *
6875 * @param task
6876 * @return
6877 */
6878HRESULT Medium::taskResizeHandler(Medium::ResizeTask &task)
6879{
6880 HRESULT rc = S_OK;
6881
6882 /* Lock all in {parent,child} order. The lock is also used as a
6883 * signal from the task initiator (which releases it only after
6884 * RTThreadCreate()) that we can start the job. */
6885 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6886
6887 try
6888 {
6889 PVBOXHDD hdd;
6890 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
6891 ComAssertRCThrow(vrc, E_FAIL);
6892
6893 try
6894 {
6895 /* Open all media in the chain. */
6896 MediumLockList::Base::const_iterator mediumListBegin =
6897 task.mpMediumLockList->GetBegin();
6898 MediumLockList::Base::const_iterator mediumListEnd =
6899 task.mpMediumLockList->GetEnd();
6900 MediumLockList::Base::const_iterator mediumListLast =
6901 mediumListEnd;
6902 mediumListLast--;
6903 for (MediumLockList::Base::const_iterator it = mediumListBegin;
6904 it != mediumListEnd;
6905 ++it)
6906 {
6907 const MediumLock &mediumLock = *it;
6908 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
6909 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
6910
6911 /* sanity check */
6912 if (it == mediumListLast)
6913 Assert(pMedium->m->state == MediumState_LockedWrite);
6914 else
6915 Assert(pMedium->m->state == MediumState_LockedRead);
6916
6917 /* Open all media but last in read-only mode. Do not handle
6918 * shareable media, as compaction and sharing are mutually
6919 * exclusive. */
6920 vrc = VDOpen(hdd,
6921 pMedium->m->strFormat.c_str(),
6922 pMedium->m->strLocationFull.c_str(),
6923 (it == mediumListLast) ? VD_OPEN_FLAGS_NORMAL : VD_OPEN_FLAGS_READONLY,
6924 pMedium->m->vdImageIfaces);
6925 if (RT_FAILURE(vrc))
6926 throw setError(VBOX_E_FILE_ERROR,
6927 tr("Could not open the medium storage unit '%s'%s"),
6928 pMedium->m->strLocationFull.c_str(),
6929 vdError(vrc).c_str());
6930 }
6931
6932 Assert(m->state == MediumState_LockedWrite);
6933
6934 Utf8Str location(m->strLocationFull);
6935
6936 /* unlock before the potentially lengthy operation */
6937 thisLock.release();
6938
6939 VDGEOMETRY geo = {0, 0, 0}; /* auto */
6940 vrc = VDResize(hdd, task.mSize, &geo, &geo, task.mVDOperationIfaces);
6941 if (RT_FAILURE(vrc))
6942 {
6943 if (vrc == VERR_NOT_SUPPORTED)
6944 throw setError(VBOX_E_NOT_SUPPORTED,
6945 tr("Compacting is not yet supported for medium '%s'"),
6946 location.c_str());
6947 else if (vrc == VERR_NOT_IMPLEMENTED)
6948 throw setError(E_NOTIMPL,
6949 tr("Compacting is not implemented, medium '%s'"),
6950 location.c_str());
6951 else
6952 throw setError(VBOX_E_FILE_ERROR,
6953 tr("Could not compact medium '%s'%s"),
6954 location.c_str(),
6955 vdError(vrc).c_str());
6956 }
6957 }
6958 catch (HRESULT aRC) { rc = aRC; }
6959
6960 VDDestroy(hdd);
6961 }
6962 catch (HRESULT aRC) { rc = aRC; }
6963
6964 /* Everything is explicitly unlocked when the task exits,
6965 * as the task destruction also destroys the media chain. */
6966
6967 return rc;
6968}
6969
6970/**
6971 * Implementation code for the "export" task.
6972 *
6973 * This only gets started from Medium::exportFile() and always runs
6974 * asynchronously. It doesn't touch anything configuration related, so
6975 * we never save the VirtualBox.xml file here.
6976 *
6977 * @param task
6978 * @return
6979 */
6980HRESULT Medium::taskExportHandler(Medium::ExportTask &task)
6981{
6982 HRESULT rc = S_OK;
6983
6984 try
6985 {
6986 /* Lock all in {parent,child} order. The lock is also used as a
6987 * signal from the task initiator (which releases it only after
6988 * RTThreadCreate()) that we can start the job. */
6989 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6990
6991 PVBOXHDD hdd;
6992 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
6993 ComAssertRCThrow(vrc, E_FAIL);
6994
6995 try
6996 {
6997 /* Open all media in the source chain. */
6998 MediumLockList::Base::const_iterator sourceListBegin =
6999 task.mpSourceMediumLockList->GetBegin();
7000 MediumLockList::Base::const_iterator sourceListEnd =
7001 task.mpSourceMediumLockList->GetEnd();
7002 for (MediumLockList::Base::const_iterator it = sourceListBegin;
7003 it != sourceListEnd;
7004 ++it)
7005 {
7006 const MediumLock &mediumLock = *it;
7007 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
7008 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
7009
7010 /* sanity check */
7011 Assert(pMedium->m->state == MediumState_LockedRead);
7012
7013 /** Open all media in read-only mode. */
7014 vrc = VDOpen(hdd,
7015 pMedium->m->strFormat.c_str(),
7016 pMedium->m->strLocationFull.c_str(),
7017 VD_OPEN_FLAGS_READONLY,
7018 pMedium->m->vdImageIfaces);
7019 if (RT_FAILURE(vrc))
7020 throw setError(VBOX_E_FILE_ERROR,
7021 tr("Could not open the medium storage unit '%s'%s"),
7022 pMedium->m->strLocationFull.c_str(),
7023 vdError(vrc).c_str());
7024 }
7025
7026 Utf8Str targetFormat(task.mFormat->getId());
7027 Utf8Str targetLocation(task.mFilename);
7028
7029 Assert(m->state == MediumState_LockedRead);
7030
7031 /* unlock before the potentially lengthy operation */
7032 thisLock.release();
7033
7034 /* ensure the target directory exists */
7035 rc = VirtualBox::ensureFilePathExists(targetLocation);
7036 if (FAILED(rc))
7037 throw rc;
7038
7039 PVBOXHDD targetHdd;
7040 vrc = VDCreate(m->vdDiskIfaces, &targetHdd);
7041 ComAssertRCThrow(vrc, E_FAIL);
7042
7043 try
7044 {
7045 vrc = VDCopy(hdd,
7046 VD_LAST_IMAGE,
7047 targetHdd,
7048 targetFormat.c_str(),
7049 targetLocation.c_str(),
7050 false /* fMoveByRename */,
7051 0 /* cbSize */,
7052 task.mVariant,
7053 NULL /* pDstUuid */,
7054 NULL /* pVDIfsOperation */,
7055 task.mVDImageIfaces,
7056 task.mVDOperationIfaces);
7057 if (RT_FAILURE(vrc))
7058 throw setError(VBOX_E_FILE_ERROR,
7059 tr("Could not create the clone medium '%s'%s"),
7060 targetLocation.c_str(), vdError(vrc).c_str());
7061 }
7062 catch (HRESULT aRC) { rc = aRC; }
7063
7064 VDDestroy(targetHdd);
7065 }
7066 catch (HRESULT aRC) { rc = aRC; }
7067
7068 VDDestroy(hdd);
7069 }
7070 catch (HRESULT aRC) { rc = aRC; }
7071
7072 /* Everything is explicitly unlocked when the task exits,
7073 * as the task destruction also destroys the source chain. */
7074
7075 /* Make sure the source chain is released early, otherwise it can
7076 * lead to deadlocks with concurrent IAppliance activities. */
7077 task.mpSourceMediumLockList->Clear();
7078
7079 return rc;
7080}
7081
7082/* vi: set tabstop=4 shiftwidth=4 expandtab: */
Note: See TracBrowser for help on using the repository browser.

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