MediumImpl.cpp revision 9bca36cba82fa91c1692aaa47828f0dde59fde74
/* $Id$ */
/** @file
* VirtualBox COM class implementation
*/
/*
* Copyright (C) 2008-2015 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#include "MediumImpl.h"
#include "TokenImpl.h"
#include "ProgressImpl.h"
#include "SystemPropertiesImpl.h"
#include "VirtualBoxImpl.h"
#include "ExtPackManagerImpl.h"
#include "AutoCaller.h"
#include "Logging.h"
#include "VBox/com/MultiResult.h"
#include "VBox/com/ErrorInfo.h"
#include <VBox/settings.h>
#include <iprt/memsafer.h>
#include <algorithm>
#include <list>
////////////////////////////////////////////////////////////////////////////////
//
// Medium data definition
//
////////////////////////////////////////////////////////////////////////////////
/** Describes how a machine refers to this medium. */
struct BackRef
{
/** Equality predicate for stdc++. */
{
bool operator()(const argument_type &aThat) const
{
}
};
: machineId(aMachineId),
{
}
bool fInCurState : 1;
};
{
Data()
: pVirtualBox(NULL),
size(0),
readers(0),
queryInfoRunning(false),
logicalSize(0),
autoReset(false),
hostDrive(false),
implicit(false),
fClosing(false),
{ }
/** weak VirtualBox parent */
VirtualBox * const pVirtualBox;
// pParent and llChildren are protected by VirtualBox::i_getMediaTreeLockHandle()
// a child, call child->deparent() which does a lookup
/** Special synchronization for operations which must wait for
* Medium::i_queryInfo in another thread to complete. Using a SemRW is
* not quite ideal, but at least it is subject to the lock validator,
* unlike the SemEventMulti which we had here for many years. Catching
* possible deadlocks is more important than a tiny bit of efficiency. */
bool queryInfoRunning : 1;
bool autoReset : 1;
/** New UUID to be set on the next Medium::i_queryInfo call. */
/** New parent UUID to be set on the next Medium::i_queryInfo call. */
const Guid uuidParentImage;
bool hostDrive : 1;
bool implicit : 1;
/** Flag whether the medium is in the process of being closed. */
bool fClosing: 1;
/** Default flags passed to VDOpen(). */
unsigned uOpenFlagsDef;
};
typedef struct VDSOCKETINT
{
/** Socket handle. */
} VDSOCKETINT, *PVDSOCKETINT;
////////////////////////////////////////////////////////////////////////////////
//
// Globals
//
////////////////////////////////////////////////////////////////////////////////
/**
* Medium::Task class for asynchronous operations.
*
* @note Instances of this class must be created using new() because the
* task thread function will delete them when the task is complete.
*
* @note The constructor of this class adds a caller on the managed Medium
* object which is automatically released upon destruction.
*/
{
public:
{
return;
/* Get strong VirtualBox reference, see below. */
return;
/* Set up a per-operation progress interface, can be used freely (for
* binary operations you can use it either on the source or target). */
"Medium::Task::vdInterfaceProgress",
sizeof(VDINTERFACEPROGRESS),
if (RT_FAILURE(vrc))
}
// Make all destructors virtual. Just in case.
virtual ~Task()
{}
protected:
private:
/* Must have a strong VirtualBox reference during a task otherwise the
* reference count might drop to 0 while a task is still running. This
* would result in weird behavior, including deadlocks due to uninit and
* locking order issues. The deadlock often is not detectable because the
* uninit uses event semaphores which sabotages deadlock detection. */
};
{
public:
{}
private:
};
{
public:
bool fKeepMediumLockList = false)
{
return;
}
{
if (!mfKeepMediumLockList && mpMediumLockList)
delete mpMediumLockList;
}
private:
bool mfKeepMediumLockList;
};
{
public:
bool fKeepSourceMediumLockList = false,
bool fKeepTargetMediumLockList = false)
{
return;
/* aParent may be NULL */
return;
}
~CloneTask()
{
delete mpSourceMediumLockList;
delete mpTargetMediumLockList;
}
private:
};
{
public:
bool fKeepMediumLockList = false)
{
}
~CompactTask()
{
if (!mfKeepMediumLockList && mpMediumLockList)
delete mpMediumLockList;
}
private:
bool mfKeepMediumLockList;
};
{
public:
bool fKeepMediumLockList = false)
{
}
~ResizeTask()
{
if (!mfKeepMediumLockList && mpMediumLockList)
delete mpMediumLockList;
}
private:
bool mfKeepMediumLockList;
};
{
public:
bool fKeepMediumLockList = false)
{}
~ResetTask()
{
if (!mfKeepMediumLockList && mpMediumLockList)
delete mpMediumLockList;
}
private:
bool mfKeepMediumLockList;
};
{
public:
bool fKeepMediumLockList = false)
{}
~DeleteTask()
{
if (!mfKeepMediumLockList && mpMediumLockList)
delete mpMediumLockList;
}
private:
bool mfKeepMediumLockList;
};
{
public:
bool fMergeForward,
bool fKeepMediumLockList = false)
{
}
~MergeTask()
{
if (!mfKeepMediumLockList && mpMediumLockList)
delete mpMediumLockList;
if (mpChildrenToReparent)
delete mpChildrenToReparent;
}
bool mfMergeForward;
/* When mpChildrenToReparent is null then mParentForTarget is non-null and
* vice versa. In other words: they are used in different cases. */
private:
bool mfKeepMediumLockList;
};
{
public:
const char *aFilename,
void *aVDImageIOUser,
bool fKeepSourceMediumLockList = false)
{
if (aVDImageIOIf)
{
sizeof(VDINTERFACEIO), &mVDImageIfaces);
}
}
~ExportTask()
{
delete mpSourceMediumLockList;
}
private:
};
{
public:
const char *aFilename,
void *aVDImageIOUser,
bool fKeepTargetMediumLockList = false)
{
/* aParent may be NULL */
return;
if (aVDImageIOIf)
{
sizeof(VDINTERFACEIO), &mVDImageIfaces);
}
}
~ImportTask()
{
delete mpTargetMediumLockList;
}
private:
};
{
public:
{
/* aParent may be NULL */
return;
}
~EncryptTask()
{
if (mstrNewPassword.length())
if (mstrOldPassword.length())
delete mpMediumLockList;
}
private:
};
/**
* Settings for a crypto filter instance.
*/
struct Medium::CryptoFilterSettings
{
: fCreateKeyStore(false),
cbDek(0),
{ }
bool fCreateKeyStore;
const char *pszPassword;
char *pszKeyStore;
const char *pszKeyStoreLoad;
const char *pszCipher;
};
/**
* Thread function for time-consuming medium tasks.
*
* @param pvUser Pointer to the Medium::Task instance.
*/
/* static */
{
/* complete the progress if run asynchronously */
/* pTask is no longer needed, delete it. */
delete pTask;
return (int)rc;
}
/**
* PFNVDPROGRESS callback handler for Task operations.
*
* @param pvUser Pointer to the Progress instance.
* @param uPercent Completion percentage (0-100).
*/
/*static*/
{
{
/* update the progress object, capping it at 99% as the final percent
* is used for additional operations like setting the UUIDs and similar. */
{
return VERR_CANCELLED;
else
return VERR_INVALID_STATE;
}
}
return VINF_SUCCESS;
}
/**
* Implementation code for the "create base" task.
*/
{
return mMedium->i_taskCreateBaseHandler(*this);
}
/**
* Implementation code for the "create diff" task.
*/
{
return mMedium->i_taskCreateDiffHandler(*this);
}
/**
* Implementation code for the "clone" task.
*/
{
return mMedium->i_taskCloneHandler(*this);
}
/**
* Implementation code for the "compact" task.
*/
{
return mMedium->i_taskCompactHandler(*this);
}
/**
* Implementation code for the "resize" task.
*/
{
return mMedium->i_taskResizeHandler(*this);
}
/**
* Implementation code for the "reset" task.
*/
{
return mMedium->i_taskResetHandler(*this);
}
/**
* Implementation code for the "delete" task.
*/
{
return mMedium->i_taskDeleteHandler(*this);
}
/**
* Implementation code for the "merge" task.
*/
{
return mMedium->i_taskMergeHandler(*this);
}
/**
* Implementation code for the "export" task.
*/
{
return mMedium->i_taskExportHandler(*this);
}
/**
* Implementation code for the "import" task.
*/
{
return mMedium->i_taskImportHandler(*this);
}
/**
* Implementation code for the "encrypt" task.
*/
{
return mMedium->i_taskEncryptHandler(*this);
}
////////////////////////////////////////////////////////////////////////////////
//
// Medium constructor / destructor
//
////////////////////////////////////////////////////////////////////////////////
{
m = new Data;
/* Initialize the callbacks of the VD error interface */
/* Initialize the callbacks of the VD config interface */
/* Initialize the callbacks of the VD TCP interface (we always use the host
* IP stack for now) */
/* Initialize the per-disk interface chain (could be done more globally,
* but it's not wasting much time or space so it's not worth it). */
int vrc;
"Medium::vdInterfaceError",
VDINTERFACETYPE_ERROR, this,
sizeof(VDINTERFACEERROR), &m->vdDiskIfaces);
/* Initialize the per-image interface chain */
"Medium::vdInterfaceConfig",
VDINTERFACETYPE_CONFIG, this,
sizeof(VDINTERFACECONFIG), &m->vdImageIfaces);
"Medium::vdInterfaceTcpNet",
VDINTERFACETYPE_TCPNET, this,
sizeof(VDINTERFACETCPNET), &m->vdImageIfaces);
return BaseFinalConstruct();
}
void Medium::FinalRelease()
{
uninit();
delete m;
}
/**
* Initializes an empty hard disk object without creating or opening an associated
* storage unit.
*
* This gets called by VirtualBox::CreateMedium() in which case uuidMachineRegistry
* is empty since starting with VirtualBox 4.0, we no longer add opened media to a
* registry automatically (this is deferred until the medium is attached to a machine).
*
* This also gets called when VirtualBox creates diff images; in this case uuidMachineRegistry
* is set to the registry of the parent image to make sure they all end up in the same
* file.
*
* For hard disks that don't have the MediumFormatCapabilities_CreateFixed or
* MediumFormatCapabilities_CreateDynamic capability (and therefore cannot be created or deleted
* with the means of VirtualBox) the associated storage unit is assumed to be
* ready for use so the state of the hard disk object will be set to Created.
*
* @param aVirtualBox VirtualBox object.
* @param aFormat
* @param aLocation Storage unit location.
* @param uuidMachineRegistry The registry to which this medium should be added
* (global registry UUID or machine UUID or empty if none).
* @param deviceType Device Type.
*/
const Guid &uuidMachineRegistry,
const DeviceType_T aDeviceType)
{
/* Enclose the state transition NotReady->InInit->Ready */
AutoInitSpan autoInitSpan(this);
/* no storage yet */
m->state = MediumState_NotCreated;
/* cannot be a host drive */
m->hostDrive = false;
m->devType = aDeviceType;
/* No storage unit is created yet, no need to call Medium::i_queryInfo */
)
{
/* Storage for mediums of this format can neither be explicitly
* created by VirtualBox nor deleted, so we place the medium to
* Inaccessible state here and also add it to the registry. The
* state means that one has to use RefreshState() to update the
* medium format specific fields. */
// create new UUID
/*
* Check whether the UUID is taken already and create a new one
* if required.
* Try this only a limited amount of times in case the PRNG is broken
* in some way to prevent an endless loop.
*/
for (unsigned i = 0; i < 5; i++)
{
bool fInUse;
if (fInUse)
{
// create new UUID
}
else
break;
}
}
/* Confirm a successful initialization when it's the case */
return rc;
}
/**
* Initializes the medium object by opening the storage unit at the specified
* location. The enOpenMode parameter defines whether the medium will be opened
*
* This gets called by VirtualBox::OpenMedium() and also by
* Machine::AttachDevice() and createImplicitDiffs() when new diff
* images are created.
*
* There is no registry for this case since starting with VirtualBox 4.0, we
* no longer add opened media to a registry automatically (this is deferred
* until the medium is attached to a machine).
*
* For hard disks, the UUID, format and the parent of this medium will be
* determined when reading the medium storage unit. For DVD and floppy images,
* which have no UUIDs in their storage units, new UUIDs are created.
* If the detected or set parent is not known to VirtualBox, then this method
* will fail.
*
* @param aVirtualBox VirtualBox object.
* @param aLocation Storage unit location.
* @param fForceNewUuid Whether a new UUID should be set to avoid duplicates.
* @param aDeviceType Device type of medium.
*/
bool fForceNewUuid,
{
{
/* Enclose the state transition NotReady->InInit->Ready */
AutoInitSpan autoInitSpan(this);
/* there must be a storage unit */
m->state = MediumState_Created;
/* remember device type for correct unregistering later */
m->devType = aDeviceType;
/* cannot be a host drive */
m->hostDrive = false;
/* remember the open mode (defaults to ReadWrite) */
m->hddOpenMode = enOpenMode;
if (aDeviceType == DeviceType_DVD)
m->type = MediumType_Readonly;
else if (aDeviceType == DeviceType_Floppy)
m->type = MediumType_Writethrough;
/* get all the information about the medium from the storage unit */
if (fForceNewUuid)
/* Confirm a successful initialization before the call to i_queryInfo.
* Otherwise we can end up with a AutoCaller deadlock because the
* medium becomes visible but is not marked as initialized. Causes
* locking trouble (e.g. trying to save media registries) which is
* hard to solve. */
}
/* we're normal code from now on, no longer init */
AutoCaller autoCaller(this);
return autoCaller.rc();
/* need to call i_queryInfo immediately to correctly place the medium in
* the respective media tree and update other information such as uuid */
{
/* if the storage unit is not accessible, it's not acceptable for the
* newly opened media so convert this into an error */
if (m->state == MediumState_Inaccessible)
{
uninit();
}
else
{
/* storage format must be detected by Medium::i_queryInfo if the
* medium is accessible */
}
}
else
{
/* opening this image failed, mark the object as dead */
uninit();
}
return rc;
}
/**
* Initializes the medium object by loading its data from the given settings
*
* In this case, since we're loading from a registry, uuidMachineRegistry is
* always set: it's either the global registry UUID or a machine UUID when
* loading from a per-machine registry.
*
* @param aVirtualBox VirtualBox object.
* @param aParent Parent medium disk or NULL for a root (base) medium.
* @param aDeviceType Device type of the medium.
* @param uuidMachineRegistry The registry to which this medium should be
* added (global registry UUID or machine UUID).
* @param aNode Configuration settings.
* @param strMachineFolder The machine folder with which to resolve relative paths;
* if empty, then we use the VirtualBox home directory
*
* @note Locks the medium tree for writing.
*/
const Guid &uuidMachineRegistry,
const Utf8Str &strMachineFolder)
{
using namespace settings;
/* Enclose the state transition NotReady->InInit->Ready */
AutoInitSpan autoInitSpan(this);
/* register with VirtualBox/parent early, since uninit() will
* unconditionally unregister on failure */
if (aParent)
{
// differencing medium: add to parent
}
/* see below why we don't call Medium::i_queryInfo (and therefore treat
* the medium as inaccessible for now */
/* required */
/* assume not a host drive */
m->hostDrive = false;
/* optional */
/* required */
if (aDeviceType == DeviceType_HardDisk)
{
}
else
{
/// @todo handle host drive settings here as well?
else
}
/* optional, only for diffs, default is false; we can only auto-reset
* diff media so they must have a parent */
else
m->autoReset = false;
/* properties (after setting the format as it populates the map). Note that
* if some properties are not supported but present in the settings file,
* they will still be read and accessible (for possible backward
* compatibility; we can also clean them up from the XML upon next
* XML format version change if we wish) */
++it)
{
}
/* try to decrypt an optional iSCSI initiator secret */
{
if (RT_SUCCESS(vrc))
}
{
// compose full path of the medium, if it's not fully qualified...
// slightly convoluted logic here. If the caller has given us a
// machine folder, then a relative path will be relative to that:
if ( !strMachineFolder.isEmpty()
)
{
strFull += RTPATH_SLASH;
}
else
{
// Otherwise use the old VirtualBox "make absolute path" logic:
}
}
else
if (aDeviceType == DeviceType_HardDisk)
{
/* type is only for base hard disks */
}
else if (aDeviceType == DeviceType_DVD)
m->type = MediumType_Readonly;
else
m->type = MediumType_Writethrough;
/* remember device type for correct unregistering later */
m->devType = aDeviceType;
LogFlowThisFunc(("m->strLocationFull='%s', m->strFormat=%s, m->id={%RTuuid}\n",
/* Don't call Medium::i_queryInfo for registered media to prevent the calling
* thread (i.e. the VirtualBox server startup thread) from an unexpected
* freeze but mark it as initially inaccessible instead. The vital UUID,
* location and format properties are read from the registry file above; to
* get the actual state and the rest of the data, the user will have to call
* COMGETTER(State). */
/* load all children */
++it)
{
this, // parent
med, // child data
}
/* Confirm a successful initialization when it's the case */
return rc;
}
/**
* Initializes the medium object by providing the host drive information.
*
* There is no registry for this case.
*
* @param aVirtualBox VirtualBox object.
* @param aDeviceType Device type of the medium.
* @param aLocation Location of the host drive.
* @param aDescription Comment for this host drive.
*
* @note Locks VirtualBox lock for writing.
*/
{
/* Enclose the state transition NotReady->InInit->Ready */
AutoInitSpan autoInitSpan(this);
// We do not store host drives in VirtualBox.xml or anywhere else, so if we want
// host drives to be identifiable by UUID and not give the drive a different UUID
// every time VirtualBox starts, we need to fake a reproducible UUID here:
RTUuidClear(&uuid);
if (aDeviceType == DeviceType_DVD)
else
/* use device name, adjusted to the end of uuid, shortened if necessary */
if (lenLocation > 12)
else
if (aDeviceType == DeviceType_DVD)
m->type = MediumType_Readonly;
else
m->type = MediumType_Writethrough;
m->devType = aDeviceType;
m->state = MediumState_Created;
m->hostDrive = true;
m->strDescription = aDescription;
return S_OK;
}
/**
* Uninitializes the instance.
*
* Called either from FinalRelease() or by the parent when it gets destroyed.
*
* @note All children of this medium get uninitialized by calling their
* uninit() methods.
*/
{
/* It is possible that some previous/concurrent uninit has already cleared
* the pVirtualBox reference, and in this case we don't need to continue.
* Normally this would be handled through the AutoUninitSpan magic,
* however this cannot be done at this point as the media tree must be
* locked before reaching the AutoUninitSpan, otherwise deadlocks can
* happen due to*/
if (!pVirtualBox)
return;
/* Caller must not hold the object or media tree lock over uninit(). */
/* Enclose the state transition Ready->InUninit->NotReady */
AutoUninitSpan autoUninitSpan(this);
if (autoUninitSpan.uninitDone())
return;
if (m->state == MediumState_Deleting)
{
/* This medium has been already deleted (directly or as part of a
* merge). Reparenting has already been done. */
}
else
{
m->llChildren.clear();
while (!llChildren.empty())
{
}
if (m->pParent)
{
// this is a differencing disk: then remove it from the parent's children list
i_deparent();
}
}
}
/**
* Internal helper that removes "this" from the list of children of its
* parent. Used in uninit() and other places when reparenting is necessary.
*
* The caller must hold the medium tree lock!
*/
void Medium::i_deparent()
{
++it)
{
if (this == pParentsChild)
{
break;
}
}
}
/**
* Internal helper that removes "this" from the list of children of its
* parent. Used in uninit() and other places when reparenting is necessary.
*
* The caller must hold the medium tree lock!
*/
{
if (pParent)
}
////////////////////////////////////////////////////////////////////////////////
//
// IMedium public methods
//
////////////////////////////////////////////////////////////////////////////////
{
return S_OK;
}
{
aDescription = m->strDescription;
return S_OK;
}
{
// AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
/// @todo update m->description and save the global registry (and local
/// registries of portable VMs referring to this medium), this will also
/// require to add the mRegistered flag to data
}
{
return S_OK;
}
{
return S_OK;
}
{
aLocation = m->strLocationFull;
return S_OK;
}
{
return S_OK;
}
{
*aDeviceType = m->devType;
return S_OK;
}
{
*aHostDrive = m->hostDrive;
return S_OK;
}
{
return S_OK;
}
{
/* no need to lock, m->strFormat is const */
return S_OK;
}
{
/* no need to lock, m->formatObj is const */
return S_OK;
}
{
return S_OK;
}
{
// we access mParent and members
switch (m->state)
{
case MediumState_Created:
case MediumState_Inaccessible:
break;
default:
return i_setStateError();
}
{
/* Nothing to do */
return S_OK;
}
// DVD media can only be readonly.
return setError(VBOX_E_INVALID_OBJECT_STATE,
tr("Cannot change the type of DVD medium '%s'"),
m->strLocationFull.c_str());
// Floppy media can only be writethrough or readonly.
if ( devType == DeviceType_Floppy
&& aType != MediumType_Writethrough
&& aType != MediumType_Readonly)
return setError(VBOX_E_INVALID_OBJECT_STATE,
tr("Cannot change the type of floppy medium '%s'"),
m->strLocationFull.c_str());
/* cannot change the type of a differencing medium */
if (m->pParent)
return setError(VBOX_E_INVALID_OBJECT_STATE,
tr("Cannot change the type of medium '%s' because it is a differencing medium"),
m->strLocationFull.c_str());
/* Cannot change the type of a medium being in use by more than one VM.
* If the change is to Immutable or MultiAttach then it must not be
* directly attached to any VM, otherwise the assumptions about indirect
* attachment elsewhere are violated and the VM becomes inaccessible.
* Attaching an immutable medium triggers the diff creation, and this is
* vital for the correct operation. */
|| ( ( aType == MediumType_Immutable
|| aType == MediumType_MultiAttach)
return setError(VBOX_E_INVALID_OBJECT_STATE,
tr("Cannot change the type of medium '%s' because it is attached to %d virtual machines"),
switch (aType)
{
case MediumType_Normal:
case MediumType_Immutable:
case MediumType_MultiAttach:
{
/* normal can be easily converted to immutable and vice versa even
* if they have children as long as they are not attached to any
* machine themselves */
break;
}
case MediumType_Writethrough:
case MediumType_Shareable:
case MediumType_Readonly:
{
/* cannot change to writethrough, shareable or readonly
* if there are children */
if (i_getChildren().size() != 0)
return setError(VBOX_E_OBJECT_IN_USE,
tr("Cannot change type for medium '%s' since it has %d child media"),
if (aType == MediumType_Shareable)
{
if (!(variant & MediumVariant_Fixed))
return setError(VBOX_E_INVALID_OBJECT_STATE,
tr("Cannot change type for medium '%s' to 'Shareable' since it is a dynamic medium storage unit"),
m->strLocationFull.c_str());
}
{
// Readonly hard disks are not allowed, this medium type is reserved for
// DVDs and floppy images at the moment. Later we might allow readonly hard
// disks, but that's extremely unusual and many guest OSes will have trouble.
return setError(VBOX_E_INVALID_OBJECT_STATE,
tr("Cannot change type for medium '%s' to 'Readonly' since it is a hard disk"),
m->strLocationFull.c_str());
}
break;
}
default:
}
if (aType == MediumType_MultiAttach)
{
// This type is new with VirtualBox 4.0 and therefore requires settings
// version 1.11 in the settings backend. Unfortunately it is not enough to do
// the usual routine in MachineConfigFile::bumpSettingsVersionIfNeeded() for
// two reasons: The medium type is a property of the media registry tree, which
// can reside in the global config file (for pre-4.0 media); we would therefore
// possibly need to bump the global config version. We don't want to do that though
// because that might make downgrading to pre-4.0 impossible.
// As a result, we can only use these two new types if the medium is NOT in the
// global registry:
return setError(VBOX_E_INVALID_OBJECT_STATE,
tr("Cannot change type for medium '%s': the media type 'MultiAttach' can only be used "
"on media registered with a machine that was created with VirtualBox 4.0 or later"),
m->strLocationFull.c_str());
}
// save the settings
return S_OK;
}
{
}
{
/* It is possible that some previous/concurrent uninit has already cleared
* the pVirtualBox reference, see #uninit(). */
/* we access mParent */
AutoReadLock treeLock(!pVirtualBox.isNull() ? &pVirtualBox->i_getMediaTreeLockHandle() : NULL COMMA_LOCKVAL_SRC_POS);
autoCaller.add();
return S_OK;
}
{
/* It is possible that some previous/concurrent uninit has already cleared
* the pVirtualBox reference, see #uninit(). */
/* we access children */
AutoReadLock treeLock(!pVirtualBox.isNull() ? &pVirtualBox->i_getMediaTreeLockHandle() : NULL COMMA_LOCKVAL_SRC_POS);
autoCaller.add();
size_t i = 0;
return S_OK;
}
{
return S_OK;
}
{
/* isReadOnly() will do locking */
*aReadOnly = i_isReadOnly();
return S_OK;
}
{
*aLogicalSize = m->logicalSize;
return S_OK;
}
{
*aAutoReset = FALSE;
else
*aAutoReset = m->autoReset;
return S_OK;
}
{
return setError(VBOX_E_NOT_SUPPORTED,
tr("Medium '%s' is not differencing"),
m->strLocationFull.c_str());
if (m->autoReset != !!aAutoReset)
{
m->autoReset = !!aAutoReset;
// save the settings
}
return S_OK;
}
{
return S_OK;
}
{
{
size_t i = 0;
}
return S_OK;
}
{
switch (m->state)
{
case MediumState_Created:
break;
default:
return i_setStateError();
}
if (aSetImageId)
{
else
{
}
}
if (aSetParentId)
{
else
}
// must not hold any locks before calling Medium::i_queryInfo
!!aSetParentId /* fSetParentId */,
return rc;
}
{
switch (m->state)
{
case MediumState_Created:
case MediumState_Inaccessible:
case MediumState_LockedRead:
{
// must not hold any locks before calling Medium::i_queryInfo
break;
}
default:
break;
}
return rc;
}
{
{
{
/* if the medium is attached to the machine in the current state, we
* return its ID as the first element of the array */
if (it->fInCurState)
++size;
if (size > 0)
{
size_t j = 0;
if (it->fInCurState)
for(GuidList::const_iterator jt = it->llSnapshotIds.begin(); jt != it->llSnapshotIds.end(); ++jt, ++j)
aSnapshotIds[j] = (*jt);
}
break;
}
}
return S_OK;
}
{
/* Wait for a concurrently running Medium::i_queryInfo to complete. */
if (m->queryInfoRunning)
{
/* Must not hold the media tree lock, as Medium::i_queryInfo needs this
* lock and thus we would run into a deadlock here. */
while (m->queryInfoRunning)
{
/* must not hold the object lock now */
{
}
}
}
switch (m->state)
{
case MediumState_Created:
case MediumState_Inaccessible:
case MediumState_LockedRead:
{
++m->readers;
/* Remember pre-lock state */
if (m->state != MediumState_LockedRead)
m->preLockState = m->state;
m->state = MediumState_LockedRead;
{
--m->readers;
if (m->readers == 0)
m->state = m->preLockState;
return rc;
}
break;
}
default:
{
rc = i_setStateError();
break;
}
}
return rc;
}
/**
* @note @a aState may be NULL if the state value is not needed (only for
* in-process calls).
*/
{
AutoCaller autoCaller(this);
switch (m->state)
{
case MediumState_LockedRead:
{
--m->readers;
/* Reset the state after the last reader */
if (m->readers == 0)
{
m->state = m->preLockState;
/* There are cases where we inject the deleting state into
* a medium locked for reading. Make sure #unmarkForDeletion()
* gets the right state afterwards. */
if (m->preLockState == MediumState_Deleting)
}
break;
}
default:
{
tr("Medium '%s' is not locked for reading"),
m->strLocationFull.c_str());
break;
}
}
/* return the current state after */
if (aState)
return rc;
}
{
/* Wait for a concurrently running Medium::i_queryInfo to complete. */
if (m->queryInfoRunning)
{
/* Must not hold the media tree lock, as Medium::i_queryInfo needs this
* lock and thus we would run into a deadlock here. */
while (m->queryInfoRunning)
{
/* must not hold the object lock now */
{
}
}
}
switch (m->state)
{
case MediumState_Created:
case MediumState_Inaccessible:
{
m->preLockState = m->state;
m->state = MediumState_LockedWrite;
{
m->state = m->preLockState;
return rc;
}
break;
}
default:
{
rc = i_setStateError();
break;
}
}
return rc;
}
/**
* @note @a aState may be NULL if the state value is not needed (only for
* in-process calls).
*/
{
AutoCaller autoCaller(this);
switch (m->state)
{
case MediumState_LockedWrite:
{
m->state = m->preLockState;
/* There are cases where we inject the deleting state into
* a medium locked for writing. Make sure #unmarkForDeletion()
* gets the right state afterwards. */
if (m->preLockState == MediumState_Deleting)
break;
}
default:
{
tr("Medium '%s' is not locked for writing"),
m->strLocationFull.c_str());
break;
}
}
/* return the current state after */
if (aState)
return rc;
}
{
// make a copy of VirtualBox pointer which gets nulled by uninit()
return mrc;
}
{
{
return setError(VBOX_E_OBJECT_NOT_FOUND,
else
/* be more silent here */
return VBOX_E_OBJECT_NOT_FOUND;
}
return S_OK;
}
{
switch (m->state)
{
case MediumState_Created:
case MediumState_Inaccessible:
break;
default:
return i_setStateError();
}
&& !i_isPropertyForFilter(aName))
{
return setError(VBOX_E_OBJECT_NOT_FOUND,
tr("Property '%s' does not exist"),
}
else
{
{
}
else
{
else
}
}
// save the settings
return S_OK;
}
{
/// @todo make use of aNames according to the documentation
size_t i = 0;
++it, ++i)
{
}
return S_OK;
}
{
/* first pass: validate names */
for (size_t i = 0;
++i)
{
return setError(VBOX_E_OBJECT_NOT_FOUND,
}
/* second pass: assign */
for (size_t i = 0;
++i)
{
&& !i_isPropertyForFilter(strName))
{
}
else
{
{
}
else
{
else
}
}
}
// save the settings
return S_OK;
}
{
if (aLogicalSize < 0)
try
{
ULONG mediumVariantFlags = 0;
{
}
mediumVariantFlags &= ((unsigned)~MediumVariant_Diff);
if ( !(mediumVariantFlags & MediumVariant_Fixed)
throw setError(VBOX_E_NOT_SUPPORTED,
tr("Medium format '%s' does not support dynamic storage creation"),
if ( (mediumVariantFlags & MediumVariant_Fixed)
throw setError(VBOX_E_NOT_SUPPORTED,
tr("Medium format '%s' does not support fixed storage creation"),
if (m->state != MediumState_NotCreated)
throw i_setStateError();
static_cast<IMedium*>(this),
TRUE /* aCancelable */);
throw rc;
/* setup task object to carry out the operation asynchronously */
//(MediumVariant_T)aVariant);
throw rc;
m->state = MediumState_Creating;
}
{
}
delete pTask;
return rc;
}
{
false /* aWait */);
/* Must save the registries in any case, since an entry was removed. */
return mrc;
}
{
// locking: we need the tree lock first because we access parent pointers
if (m->type == MediumType_Writethrough)
return setError(VBOX_E_INVALID_OBJECT_STATE,
tr("Medium type of '%s' is Writethrough"),
m->strLocationFull.c_str());
else if (m->type == MediumType_Shareable)
return setError(VBOX_E_INVALID_OBJECT_STATE,
tr("Medium type of '%s' is Shareable"),
m->strLocationFull.c_str());
else if (m->type == MediumType_Readonly)
return setError(VBOX_E_INVALID_OBJECT_STATE,
tr("Medium type of '%s' is Readonly"),
m->strLocationFull.c_str());
/* Apply the normal locking logic to the entire chain. */
true /* fMediumLockWrite */,
false /* fMediumLockWriteAll */,
this,
{
delete pMediumLockList;
return rc;
}
{
delete pMediumLockList;
}
{
/* since this medium has been just created it isn't associated yet */
}
ULONG mediumVariantFlags = 0;
{
}
&pProgress, false /* aWait */);
delete pMediumLockList;
else
return rc;
}
{
bool fMergeForward = false;
else
return rc;
}
{
return rc;
}
{
if (aParent)
{
}
try
{
// locking: we need the tree lock first because we access parent pointers
// and we need to write-lock the media involved
this->lockHandle(),
pTarget->lockHandle() };
/* Only add parent to the lock if it is not null */
throw pTarget->i_setStateError();
/* Build the source lock list. */
false /* fMediumLockWrite */,
false /* fMediumLockWriteAll */,
NULL,
{
delete pSourceMediumLockList;
throw rc;
}
/* Build the target lock list (including the to-be parent chain). */
true /* fMediumLockWrite */,
false /* fMediumLockWriteAll */,
{
delete pSourceMediumLockList;
delete pTargetMediumLockList;
throw rc;
}
{
delete pSourceMediumLockList;
delete pTargetMediumLockList;
tr("Failed to lock source media '%s'"),
i_getLocationFull().c_str());
}
{
delete pSourceMediumLockList;
delete pTargetMediumLockList;
tr("Failed to lock target media '%s'"),
}
static_cast <IMedium *>(this),
TRUE /* aCancelable */);
{
delete pSourceMediumLockList;
delete pTargetMediumLockList;
throw rc;
}
ULONG mediumVariantFlags = 0;
{
}
/* setup task object to carry out the operation asynchronously */
throw rc;
}
{
}
delete pTask;
return rc;
}
{
/// @todo NEWMEDIA for file names, add the default extension if no extension
/// is present (using the information from the VD backend which also implies
/// that one more parameter should be passed to setLocation() requesting
/// that functionality since it is only allowed when called from this method
/// @todo NEWMEDIA rename the file and set m->location on success, then save
/// the global registry (and local registries of portable VMs referring to
/// this medium), this will also require to add the mRegistered flag to data
}
{
try
{
/* Build the medium lock list. */
true /* fMediumLockWrite */,
false /* fMediumLockWriteAll */,
NULL,
{
delete pMediumLockList;
throw rc;
}
{
delete pMediumLockList;
tr("Failed to lock media when compacting '%s'"),
i_getLocationFull().c_str());
}
static_cast <IMedium *>(this),
TRUE /* aCancelable */);
{
delete pMediumLockList;
throw rc;
}
/* setup task object to carry out the operation asynchronously */
throw rc;
}
{
}
delete pTask;
return rc;
}
{
try
{
/* Build the medium lock list. */
true /* fMediumLockWrite */,
false /* fMediumLockWriteAll */,
NULL,
{
delete pMediumLockList;
throw rc;
}
{
delete pMediumLockList;
tr("Failed to lock media when compacting '%s'"),
i_getLocationFull().c_str());
}
static_cast <IMedium *>(this),
TRUE /* aCancelable */);
{
delete pMediumLockList;
throw rc;
}
/* setup task object to carry out the operation asynchronously */
throw rc;
}
{
}
delete pTask;
return rc;
}
{
try
{
/* canClose() needs the tree lock */
this->lockHandle()
throw setError(VBOX_E_NOT_SUPPORTED,
tr("Medium type of '%s' is not differencing"),
m->strLocationFull.c_str());
rc = i_canClose();
throw rc;
/* Build the medium lock list. */
true /* fMediumLockWrite */,
false /* fMediumLockWriteAll */,
NULL,
{
delete pMediumLockList;
throw rc;
}
{
delete pMediumLockList;
tr("Failed to lock media when resetting '%s'"),
i_getLocationFull().c_str());
}
static_cast<IMedium*>(this),
FALSE /* aCancelable */);
throw rc;
/* setup task object to carry out the operation asynchronously */
throw rc;
}
{
}
delete pTask;
return rc;
}
HRESULT Medium::changeEncryption(const com::Utf8Str &aNewPassword, const com::Utf8Str &aOldPassword,
{
try
{
/* Cannot encrypt DVD or floppy images so far. */
if ( devType == DeviceType_DVD
|| devType == DeviceType_Floppy)
return setError(VBOX_E_INVALID_OBJECT_STATE,
tr("Cannot encrypt DVD or Floppy medium '%s'"),
m->strLocationFull.c_str());
/* Cannot encrypt media which are attached to more than one virtual machine. */
return setError(VBOX_E_INVALID_OBJECT_STATE,
tr("Cannot encrypt medium '%s' because it is attached to %d virtual machines"),
if (m->llChildren.size() != 0)
return setError(VBOX_E_INVALID_OBJECT_STATE,
tr("Cannot encrypt medium '%s' because it has %d children"),
/* Build the medium lock list. */
true /* fMediumLockWrite */,
true /* fMediumLockAllWrite */,
NULL,
{
delete pMediumLockList;
throw rc;
}
{
delete pMediumLockList;
tr("Failed to lock media for encryption '%s'"),
i_getLocationFull().c_str());
}
/*
* Check all media in the chain to not contain any branches or references to
* other virtual machines, we support encrypting only a list of differencing media at the moment.
*/
it != mediumListEnd;
++it)
{
{
tr("Cannot encrypt medium '%s' because it is attached to %d virtual machines"),
break;
}
{
tr("Cannot encrypt medium '%s' because it has %d children"),
break;
}
}
{
delete pMediumLockList;
throw rc;
}
static_cast <IMedium *>(this),
TRUE /* aCancelable */);
{
delete pMediumLockList;
throw rc;
}
/* setup task object to carry out the operation asynchronously */
throw rc;
}
{
}
delete pTask;
return rc;
}
////////////////////////////////////////////////////////////////////////////////
//
// Medium public internal methods
//
////////////////////////////////////////////////////////////////////////////////
/**
* Internal method to return the medium's parent medium. Must have caller + locking!
* @return
*/
{
return m->pParent;
}
/**
* Internal method to return the medium's list of child media. Must have caller + locking!
* @return
*/
{
return m->llChildren;
}
/**
* Internal method to return the medium's GUID. Must have caller + locking!
* @return
*/
{
return m->id;
}
/**
* Internal method to return the medium's state. Must have caller + locking!
* @return
*/
{
return m->state;
}
/**
* Internal method to return the medium's variant. Must have caller + locking!
* @return
*/
{
return m->variant;
}
/**
* Internal method which returns true if this medium represents a host drive.
* @return
*/
bool Medium::i_isHostDrive() const
{
return m->hostDrive;
}
/**
* Internal method to return the medium's full location. Must have caller + locking!
* @return
*/
{
return m->strLocationFull;
}
/**
* Internal method to return the medium's format string. Must have caller + locking!
* @return
*/
{
return m->strFormat;
}
/**
* Internal method to return the medium's format object. Must have caller + locking!
* @return
*/
{
return m->formatObj;
}
/**
* Internal method that returns true if the medium is represented by a file on the host disk
* (and not iSCSI or something).
* @return
*/
bool Medium::i_isMediumFormatFile() const
{
if ( m->formatObj
)
return true;
return false;
}
/**
* Internal method to return the medium's size. Must have caller + locking!
* @return
*/
{
return m->size;
}
/**
* Returns the medium device type. Must have caller + locking!
* @return
*/
{
return m->devType;
}
/**
* Returns the medium type. Must have caller + locking!
* @return
*/
{
return m->type;
}
/**
* Returns a short version of the location attribute.
*
* @note Must be called from under this object's read or write lock.
*/
{
return name;
}
/**
* This adds the given UUID to the list of media registries in which this
* medium should be registered. The UUID can either be a machine UUID,
* to add a machine registry, or the global registry UUID as returned by
* VirtualBox::getGlobalRegistryId().
*
* Note that for hard disks, this method does nothing if the medium is
* already in another registry to avoid having hard disks in more than
* one registry, which causes trouble with keeping diff images in sync.
* See getFirstRegistryMachineId() for details.
*
* If fRecurse == true, then the media tree lock must be held for reading.
*
* @param id
* @param fRecurse If true, recurses into child media to make sure the whole tree has registries in sync.
* @return true if the registry was added; false if the given id was already on the list.
*/
{
AutoCaller autoCaller(this);
return false;
bool fAdd = true;
// hard disks cannot be in more than one registry
if ( m->devType == DeviceType_HardDisk
&& m->llRegistryIDs.size() > 0)
fAdd = false;
// no need to add the UUID twice
if (fAdd)
{
++it)
{
{
fAdd = false;
break;
}
}
}
if (fAdd)
if (fRecurse)
{
// Get private list of children and release medium lock straight away.
++it)
{
}
}
return fAdd;
}
/**
* Removes the given UUID from the list of media registry UUIDs. Returns true
* if found or false if not.
*
* If fRecurse == true, then the media tree lock must be held for reading.
*
* @param id
* @param fRecurse If true, recurses into child media to make sure the whole tree has registries in sync.
* @return
*/
{
AutoCaller autoCaller(this);
return false;
bool fRemove = false;
++it)
{
{
fRemove = true;
break;
}
}
if (fRecurse)
{
// Get private list of children and release medium lock straight away.
++it)
{
}
}
return fRemove;
}
/**
* Returns true if id is in the list of media registries for this medium.
*
* Must have caller + read locking!
*
* @param id
* @return
*/
{
++it)
{
return true;
}
return false;
}
/**
* Internal method to return the medium's first registry machine (i.e. the machine in whose
* machine XML this medium is listed).
*
* Every attached medium must now (4.0) reside in at least one media registry, which is identified
* by a UUID. This is either a machine UUID if the machine is from 4.0 or newer, in which case
* machines have their own media registries, or it is the pseudo-UUID of the VirtualBox
* object if the machine is old and still needs the global registry in VirtualBox.xml.
*
* By definition, hard disks may only be in one media registry, in which all its children
* will be stored as well. Otherwise we run into problems with having keep multiple registries
* in sync. (This is the "cloned VM" case in which VM1 may link to the disks of VM2; in this
* case, only VM2's registry is used for the disk in question.)
*
* If there is no medium registry, particularly if the medium has not been attached yet, this
* does not modify uuid and returns false.
*
* ISOs and RAWs, by contrast, can be in more than one repository to make things easier for
* the user.
*
* Must have caller + locking!
*
* @param uuid Receives first registry machine UUID, if available.
* @return true if uuid was set.
*/
{
if (m->llRegistryIDs.size())
{
return true;
}
return false;
}
/**
* Marks all the registries in which this medium is registered as modified.
*/
void Medium::i_markRegistriesModified()
{
AutoCaller autoCaller(this);
// Get local copy, as keeping the lock over VirtualBox::markRegistryModified
// causes trouble with the lock order
{
llRegistryIDs = m->llRegistryIDs;
}
/* Save the error information now, the implicit restore when this goes
* out of scope will throw away spurious additional errors created below. */
++it)
{
}
}
/**
* Adds the given machine and optionally the snapshot to the list of the objects
* this medium is attached to.
*
* @param aMachineId Machine ID.
* @param aSnapshotId Snapshot ID; when non-empty, adds a snapshot attachment.
*/
{
LogFlowThisFunc(("ENTER, aMachineId: {%RTuuid}, aSnapshotId: {%RTuuid}\n", aMachineId.raw(), aSnapshotId.raw()));
AutoCaller autoCaller(this);
switch (m->state)
{
case MediumState_Created:
case MediumState_Inaccessible:
case MediumState_LockedRead:
case MediumState_LockedWrite:
break;
default:
return i_setStateError();
}
if (m->numCreateDiffTasks > 0)
return setError(VBOX_E_OBJECT_IN_USE,
tr("Cannot attach medium '%s' {%RTuuid}: %u differencing child media are being created"),
m->strLocationFull.c_str(),
m->numCreateDiffTasks);
{
return S_OK;
}
// if the caller has not supplied a snapshot ID, then we're attaching
// to a machine a medium which represents the machine's current state,
// so set the flag
if (aSnapshotId.isZero())
{
/* sanity: no duplicate attachments */
if (it->fInCurState)
return setError(VBOX_E_OBJECT_IN_USE,
tr("Cannot attach medium '%s' {%RTuuid}: medium is already associated with the current state of machine uuid {%RTuuid}!"),
m->strLocationFull.c_str(),
aMachineId.raw());
it->fInCurState = true;
return S_OK;
}
// otherwise: a snapshot medium is being attached
/* sanity: no duplicate attachments */
++jt)
{
if (idOldSnapshot == aSnapshotId)
{
#ifdef DEBUG
#endif
return setError(VBOX_E_OBJECT_IN_USE,
tr("Cannot attach medium '%s' {%RTuuid} from snapshot '%RTuuid': medium is already in use by this snapshot!"),
m->strLocationFull.c_str(),
aSnapshotId.raw());
}
}
// Do not touch fInCurState, as the image may be attached to the current
// state *and* a snapshot, otherwise we lose the current state association!
return S_OK;
}
/**
* Removes the given machine and optionally the snapshot from the list of the
* objects this medium is attached to.
*
* @param aMachineId Machine ID.
* @param aSnapshotId Snapshot ID; when non-empty, removes the snapshot
* attachment.
*/
{
AutoCaller autoCaller(this);
if (aSnapshotId.isZero())
{
/* remove the current state attachment */
it->fInCurState = false;
}
else
{
/* remove the snapshot attachment */
}
/* if the backref becomes empty, remove it */
return S_OK;
}
/**
* Internal method to return the medium's list of backrefs. Must have caller + locking!
* @return
*/
{
return NULL;
}
/**
* Internal method which returns a machine that either this medium or one of its children
* is attached to. This is used for finding a replacement media registry when an existing
* media registry is about to be deleted in VirtualBox::unregisterMachine().
*
* Must have caller + locking, *and* caller must hold the media tree lock!
* @return
*/
{
++it)
{
// recurse for this child
return puuid;
}
return NULL;
}
{
return NULL;
return NULL;
}
{
}
#ifdef DEBUG
/**
* Debugging helper that gets called after VirtualBox initialization that writes all
* machine backreferences to the debug log.
*/
void Medium::i_dumpBackRefs()
{
AutoCaller autoCaller(this);
++it2)
{
LogFlowThisFunc((" Backref from machine {%RTuuid} (fInCurState: %d)\n", ref.machineId.raw(), ref.fInCurState));
++jt2)
{
}
}
}
#endif
/**
* Checks if the given change of \a aOldPath to \a aNewPath affects the location
* of this media and updates it if necessary to reflect the new location.
*
* @param aOldPath Old path (full).
* @param aNewPath New path (full).
*
* @note Locks this object for writing.
*/
{
AutoCaller autoCaller(this);
{
// we changed something
return S_OK;
}
// no change was necessary, signal error which the caller needs to interpret
return VBOX_E_FILE_ERROR;
}
/**
* Returns the base medium of the media chain this medium is part of.
*
* The base medium is found by walking up the parent-child relationship axis.
* If the medium doesn't have a parent (i.e. it's a base medium), it
* returns itself in response to this method.
*
* @param aLevel Where to store the number of ancestors of this medium
* (zero for the base), may be @c NULL.
*
* @note Locks medium tree for reading.
*/
{
/* it is possible that some previous/concurrent uninit has already cleared
* the pVirtualBox reference, and in this case we don't need to continue */
if (!pVirtualBox)
return pBase;
/* we access mParent */
AutoCaller autoCaller(this);
pBase = this;
if (m->pParent)
{
for (;;)
{
break;
++level;
}
}
return pBase;
}
/**
* Returns @c true if this medium cannot be modified because it has
* dependents (children) or is part of the snapshot. Related to the medium
* type and posterity, not to the current media state.
*
* @note Locks this object and medium tree for reading.
*/
bool Medium::i_isReadOnly()
{
AutoCaller autoCaller(this);
/* we access children */
switch (m->type)
{
case MediumType_Normal:
{
if (i_getChildren().size() != 0)
return true;
return true;
if (m->variant & MediumVariant_VmdkStreamOptimized)
return true;
return false;
}
case MediumType_Immutable:
case MediumType_MultiAttach:
return true;
case MediumType_Writethrough:
case MediumType_Shareable:
case MediumType_Readonly: /* explicit readonly media has no diffs */
return false;
default:
break;
}
AssertFailedReturn(false);
}
/**
* Internal method to return the medium's size. Must have caller + locking!
* @return
*/
{
}
/**
* Saves medium data by appending a new child node to the given
* parent XML settings node.
*
* @param data Settings struct to be updated.
* @param strHardDiskFolder Folder for which paths should be relative.
*
* @note Locks this object, medium tree and children for reading.
*/
const Utf8Str &strHardDiskFolder)
{
AutoCaller autoCaller(this);
/* we access mParent */
// make path relative if needed
if ( !strHardDiskFolder.isEmpty()
)
else
/* optional, only for diffs, default is false */
if (m->pParent)
else
data.fAutoReset = false;
/* optional */
/* optional properties */
/* handle iSCSI initiator secrets transparently */
bool fHaveInitiatorSecretEncrypted = false;
{
/* Encrypt the plain secret. If that does not work (i.e. no or wrong settings key
* specified), just use the encrypted secret (if there is any). */
if (RT_SUCCESS(rc))
fHaveInitiatorSecretEncrypted = true;
}
++it)
{
/* only save properties that have non-default values */
{
/* do NOT store the plain InitiatorSecret */
}
}
/* only for base media */
/* save all children */
++it)
{
}
return S_OK;
}
/**
* Constructs a medium lock list for this medium. The lock is not taken.
*
* @note Caller MUST NOT hold the media tree or medium lock.
*
* @param fFailIfInaccessible If true, this fails with an error if a medium is inaccessible. If false,
* inaccessible media are silently skipped and not locked (i.e. their state remains "Inaccessible");
* this is necessary for a VM's removable media VM startup for which we do not want to fail.
* @param fMediumLockWrite Whether to associate a write lock with this medium.
* @param fMediumLockWriteAll Whether to associate a write lock to all other media too.
* @param pToBeParent Medium which will become the parent of this medium.
* @param mediumLockList Where to store the resulting list.
*/
bool fMediumLockWrite,
bool fMediumLockWriteAll,
{
AutoCaller autoCaller(this);
/* paranoid sanity checking if the medium has a to-be parent medium */
if (pToBeParent)
{
}
{
/* Accessibility check must be first, otherwise locking interferes
* with getting the medium state. Lock lists are not created for
* fun, and thus getting the medium status is no luxury. */
if (mediumState == MediumState_Inaccessible)
{
if (mediumState == MediumState_Inaccessible)
{
// ignore inaccessible ISO media and silently return S_OK,
// otherwise VM startup (esp. restore) may fail without good reason
if (!fFailIfInaccessible)
return S_OK;
// otherwise report an error
/* collect multiple errors */
"%ls",
// error message will be something like
// "Could not open the medium ... VD: error VERR_FILE_NOT_FOUND opening image file ... (VERR_FILE_NOT_FOUND).
}
}
if (pMedium == this)
else
{
pToBeParent = NULL;
}
}
return mrc;
}
/**
* Creates a new differencing storage unit using the format of the given target
* medium and the location. Note that @c aTarget must be NotCreated.
*
* The @a aMediumLockList parameter contains the associated medium lock list,
* which must be in locked state. If @a aWait is @c true then the caller is
* responsible for unlocking.
*
* If @a aProgress is not NULL but the object it points to is @c null then a
* new progress object will be created and assigned to @a *aProgress on
* success, otherwise the existing progress object is used. If @a aProgress is
*
* When @a aWait is @c false, this method will create a thread to perform the
* create operation asynchronously and will return immediately. Otherwise, it
* will perform the operation on the calling thread and will not return to the
* caller until the operation is completed. Note that @a aProgress cannot be
* NULL when @a aWait is @c false (this method will assert in this case).
*
* @param aTarget Target medium.
* @param aVariant Precise medium variant to create.
* @param aMediumLockList List of media which should be locked.
* operation completion.
* @param aWait @c true if this method should block instead of
* creating an asynchronous thread.
*
* @note Locks this object and @a aTarget for writing.
*/
bool aWait)
{
AutoCaller autoCaller(this);
try
{
&& m->type != MediumType_Shareable
throw aTarget->i_setStateError();
/* Check that the medium is not attached to the current state of
* any VM referring to it. */
++it)
{
if (it->fInCurState)
{
/* Note: when a VM snapshot is being taken, all normal media
* attached to the VM in the current state will be, as an
* exception, also associated with the snapshot which is about
* to create (see SnapshotMachine::init()) before deassociating
* them from the current state (which takes place only on
* success in Machine::fixupHardDisks()), so that the size of
* snapshotIds will be 1 in this case. The extra condition is
* used to filter out this legal situation. */
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"),
}
}
{
/* use the existing progress object... */
/* ...but create a new one if it is null */
{
static_cast<IMedium*>(this),
TRUE /* aCancelable */);
throw rc;
}
}
aWait /* fKeepMediumLockList */);
throw rc;
/* register a task (it will deregister itself when done) */
++m->numCreateDiffTasks;
}
{
if (aWait)
else
}
delete pTask;
return rc;
}
/**
* Returns a preferred format for differencing media.
*/
{
AutoCaller autoCaller(this);
/* check that our own format supports diffs */
{
/* use the default format if not */
return tmp;
}
/* m->strFormat is const, no need to lock */
return m->strFormat;
}
/**
* Implementation for the public Medium::Close() with the exception of calling
* VirtualBox::saveRegistries(), in case someone wants to call this for several
* media.
*
* After this returns with success, uninit() has been called on the medium, and
* the object is no longer usable ("not ready" state).
*
* @param autoCaller AutoCaller instance which must have been created on the caller's
* stack for this medium. This gets released hereupon
* which the Medium instance gets uninitialized.
* @return
*/
{
// must temporarily drop the caller, need the tree lock first
this->lockHandle()
autoCaller.add();
bool wasCreated = true;
switch (m->state)
{
case MediumState_NotCreated:
wasCreated = false;
break;
case MediumState_Created:
case MediumState_Inaccessible:
break;
default:
return i_setStateError();
}
return setError(VBOX_E_OBJECT_IN_USE,
tr("Medium '%s' cannot be closed because it is still attached to %d virtual machines"),
// perform extra media-dependent close checks
m->fClosing = true;
if (wasCreated)
{
// remove from the list of known media before performing actual
// uninitialization (to keep the media registry consistent on
// failure to do so)
// Release the AutoCaller now, as otherwise uninit() will simply hang.
// Needs to be done before mark the registries as modified and saving
// the registry, as otherwise there may be a deadlock with someone else
// closing this object while we're in i_saveModifiedRegistries(), which
// needs the media tree lock, which the other thread holds until after
// uninit() below.
}
else
{
// release the AutoCaller, as otherwise uninit() will simply hang
}
// Keep the locks held until after uninit, as otherwise the consistency
// of the medium tree cannot be guaranteed.
uninit();
return rc;
}
/**
* Deletes the medium storage unit.
*
* If @a aProgress is not NULL but the object it points to is @c null then a new
* progress object will be created and assigned to @a *aProgress on success,
* otherwise the existing progress object is used. If Progress is NULL, then no
*
* When @a aWait is @c false, this method will create a thread to perform the
* delete operation asynchronously and will return immediately. Otherwise, it
* will perform the operation on the calling thread and will not return to the
* caller until the operation is completed. Note that @a aProgress cannot be
* NULL when @a aWait is @c false (this method will assert in this case).
*
* completion.
* @param aWait @c true if this method should block instead of creating
* an asynchronous thread.
*
* @note Locks mVirtualBox and this object for writing. Locks medium tree for
* writing.
*/
bool aWait)
{
AutoCaller autoCaller(this);
try
{
/* we're accessing the media tree, and canClose() needs it too */
this->lockHandle()
throw setError(VBOX_E_NOT_SUPPORTED,
tr("Medium format '%s' does not support storage deletion"),
/* Note that we are fine with Inaccessible state too: a) for symmetry
* with create calls and b) because it doesn't really harm to try, if
* it is really inaccessible, the delete operation will fail anyway.
* Accepting Inaccessible state is especially important because all
* registered media are initially Inaccessible upon VBoxSVC startup
* until COMGETTER(RefreshState) is called. Accept Deleting state
* because some callers need to put the medium in this state early
* to prevent races. */
switch (m->state)
{
case MediumState_Created:
case MediumState_Deleting:
case MediumState_Inaccessible:
break;
default:
throw i_setStateError();
}
{
++it)
{
if (strMachines.length())
}
#ifdef DEBUG
#endif
throw setError(VBOX_E_OBJECT_IN_USE,
tr("Cannot delete storage: medium '%s' is still attached to the following %d virtual machine(s): %s"),
m->strLocationFull.c_str(),
strMachines.c_str());
}
rc = i_canClose();
throw rc;
/* go to Deleting state, so that the medium is not actually locked */
if (m->state != MediumState_Deleting)
{
rc = i_markForDeletion();
throw rc;
}
/* Build the medium lock list. */
true /* fMediumLockWrite */,
false /* fMediumLockWriteAll */,
NULL,
{
delete pMediumLockList;
throw rc;
}
{
delete pMediumLockList;
tr("Failed to lock media when deleting '%s'"),
i_getLocationFull().c_str());
}
/* try to remove from the list of known media before performing
* actual deletion (we favor the consistency of the media registry
* which would have been broken if unregisterWithVirtualBox() failed
* after we successfully deleted the storage) */
throw rc;
// no longer need lock
{
/* use the existing progress object... */
/* ...but create a new one if it is null */
{
static_cast<IMedium*>(this),
FALSE /* aCancelable */);
throw rc;
}
}
throw rc;
}
{
if (aWait)
else
}
else
{
if (pTask)
delete pTask;
/* Undo deleting state if necessary. */
/* Make sure that any error signalled by unmarkForDeletion() is not
* ending up in the error list (if the caller uses MultiResult). It
* usually is spurious, as in most cases the medium hasn't been marked
* for deletion when the error was thrown above. */
}
return rc;
}
/**
* Mark a medium for deletion.
*
* @note Caller must hold the write lock on this medium!
*/
{
switch (m->state)
{
case MediumState_Created:
case MediumState_Inaccessible:
m->preLockState = m->state;
m->state = MediumState_Deleting;
return S_OK;
default:
return i_setStateError();
}
}
/**
* Removes the "mark for deletion".
*
* @note Caller must hold the write lock on this medium!
*/
{
switch (m->state)
{
case MediumState_Deleting:
m->state = m->preLockState;
return S_OK;
default:
return i_setStateError();
}
}
/**
* Mark a medium for deletion which is in locked state.
*
* @note Caller must hold the write lock on this medium!
*/
{
if ( ( m->state == MediumState_LockedRead
|| m->state == MediumState_LockedWrite)
&& m->preLockState == MediumState_Created)
{
return S_OK;
}
else
return i_setStateError();
}
/**
* Removes the "mark for deletion" for a medium in locked state.
*
* @note Caller must hold the write lock on this medium!
*/
{
if ( ( m->state == MediumState_LockedRead
|| m->state == MediumState_LockedWrite)
&& m->preLockState == MediumState_Deleting)
{
return S_OK;
}
else
return i_setStateError();
}
/**
* Queries the preferred merge direction from this to the other medium, i.e.
* the one which requires the least amount of I/O and therefore time and
* disk consumption.
*
* @returns Status code.
* @retval E_FAIL in case determining the merge direction fails for some reason,
* for example if getting the size of the media fails. There is no
* error set though and the caller is free to continue to find out
* what was going wrong later. Leaves fMergeForward unset.
* @retval VBOX_E_INVALID_OBJECT_STATE if both media are not related to each other
* An error is set.
* @param pOther The other medium to merge with.
* @param fMergeForward Resulting preferred merge direction (out).
*/
bool &fMergeForward)
{
AutoCaller autoCaller(this);
bool fThisParent = false; /**<< Flag whether this medium is the parent of pOther. */
try
{
// locking: we need the tree lock first because we access parent pointers
/* more sanity checking and figuring out the current merge direction */
fThisParent = false;
else
{
if (pMedium == this)
fThisParent = true;
else
{
{
}
tr("Media '%s' and '%s' are unrelated"),
}
}
/*
* Figure out the preferred merge direction. The current way is to
* get the current sizes of file based images and select the merge
* direction depending on the size.
*
* Can't use the VD API to get current size here as the media might
* be write locked by a running VM. Resort to RTFileQuerySize().
*/
int vrc = VINF_SUCCESS;
uint64_t cbMediumThis = 0;
uint64_t cbMediumOther = 0;
{
if (RT_SUCCESS(vrc))
{
}
if (RT_FAILURE(vrc))
else
{
/*
* Check which merge direction might be more optimal.
* This method is not bullet proof of course as there might
* be overlapping blocks in the images so the file size is
* not the best indicator but it is good enough for our purpose
* and everything else is too complicated, especially when the
* media are used by a running VM.
*/
}
}
}
return rc;
}
/**
* Prepares this (source) medium, target medium and all intermediate media
* for the merge operation.
*
* This method is to be called prior to calling the #mergeTo() to perform
* necessary consistency checks and place involved media to appropriate
* states. If #mergeTo() is not called or fails, the state modifications
* performed by this method must be undone by #cancelMergeTo().
*
* See #mergeTo() for more information about merging.
*
* @param pTarget Target medium.
* @param aMachineId Allowed machine attachment. NULL means do not check.
* @param aSnapshotId Allowed snapshot attachment. NULL or empty UUID means
* do not check.
* @param fLockMedia Flag whether to lock the medium lock list or not.
* If set to false and the medium lock list locking fails
* later you must call #cancelMergeTo().
* @param fMergeForward Resulting merge direction (out).
* @param pParentForTarget New parent for target medium after merge (out).
* @param aChildrenToReparent Medium lock list containing all children of the
* source which will have to be reparented to the target
* after merge (out).
* @param aMediumLockList Medium locking information (out).
*
* @note Locks medium tree for reading. Locks this object, aTarget and all
* intermediate media for writing.
*/
const Guid *aMachineId,
const Guid *aSnapshotId,
bool fLockMedia,
bool &fMergeForward,
{
AutoCaller autoCaller(this);
fMergeForward = false;
try
{
// locking: we need the tree lock first because we access parent pointers
/* more sanity checking and figuring out the merge direction */
fMergeForward = false;
else
{
if (pMedium == this)
fMergeForward = true;
else
{
{
}
tr("Media '%s' and '%s' are unrelated"),
}
}
/* Build the lock list. */
aMediumLockList = new MediumLockList();
if (fMergeForward)
true /* fMediumLockWrite */,
false /* fMediumLockWriteAll */,
NULL,
else
false /* fMediumLockWrite */,
false /* fMediumLockWriteAll */,
NULL,
throw rc;
/* Sanity checking, must be after lock list creation as it depends on
* valid medium states. The medium objects must be accessible. Only
* do this if immediate locking is requested, otherwise it fails when
* we construct a medium lock list for an already running VM. Snapshot
* deletion uses this to simplify its life. */
if (fLockMedia)
{
{
if (m->state != MediumState_Created)
throw i_setStateError();
}
{
throw pTarget->i_setStateError();
}
}
/* check medium attachment and other sanity conditions */
if (fMergeForward)
{
{
tr("Medium '%s' involved in the merge operation has more than one child medium (%d)"),
}
/* One backreference is only allowed if the machine ID is not empty
* and it matches the machine the medium is attached to (including
* the snapshot ID if not empty). */
&& ( !aMachineId
|| aMachineId->isZero()
|| *i_getFirstMachineBackrefId() != *aMachineId
&& *i_getFirstMachineBackrefSnapshotId() != *aSnapshotId)))
throw setError(VBOX_E_OBJECT_IN_USE,
tr("Medium '%s' is attached to %d virtual machines"),
if (m->type == MediumType_Immutable)
tr("Medium '%s' is immutable"),
m->strLocationFull.c_str());
if (m->type == MediumType_MultiAttach)
tr("Medium '%s' is multi-attach"),
m->strLocationFull.c_str());
}
else
{
{
throw setError(VBOX_E_OBJECT_IN_USE,
tr("Medium '%s' involved in the merge operation has more than one child medium (%d)"),
}
tr("Medium '%s' is immutable"),
tr("Medium '%s' is multi-attach"),
}
for (pLast = pLastIntermediate;
{
{
throw setError(VBOX_E_OBJECT_IN_USE,
tr("Medium '%s' involved in the merge operation has more than one child medium (%d)"),
}
throw setError(VBOX_E_OBJECT_IN_USE,
tr("Medium '%s' is attached to %d virtual machines"),
}
/* Update medium states appropriately */
{
if (m->state == MediumState_Created)
{
rc = i_markForDeletion();
throw rc;
}
else
{
if (fLockMedia)
throw i_setStateError();
else if ( m->state == MediumState_LockedWrite
|| m->state == MediumState_LockedRead)
{
/* Either mark it for deletion in locked state or allow
* others to have done so. */
if (m->preLockState == MediumState_Created)
else if (m->preLockState != MediumState_Deleting)
throw i_setStateError();
}
else
throw i_setStateError();
}
}
if (fMergeForward)
{
/* we will need parent to reparent target */
}
else
{
/* we will need to reparent children of the source */
aChildrenToReparent = new MediumLockList();
++it)
{
}
if (fLockMedia && aChildrenToReparent)
{
throw rc;
}
}
for (pLast = pLastIntermediate;
{
{
throw rc;
}
else
throw pLast->i_setStateError();
}
/* Tweak the lock list in the backward merge case, as the target
* isn't marked to be locked for writing yet. */
if (!fMergeForward)
{
lockListEnd--;
it != lockListEnd;
++it)
{
{
break;
}
}
}
if (fLockMedia)
{
{
tr("Failed to lock media when merging to '%s'"),
}
}
}
{
if (aMediumLockList)
{
delete aMediumLockList;
}
if (aChildrenToReparent)
{
delete aChildrenToReparent;
}
}
return rc;
}
/**
* Merges this medium to the specified medium which must be either its
* direct ancestor or descendant.
*
* Given this medium is SOURCE and the specified medium is TARGET, we will
* get two variants of the merge operation:
*
* forward merge
* ------------------------->
* [Extra] <- SOURCE <- Intermediate <- TARGET
* Any Del Del LockWr
*
*
* backward merge
* <-------------------------
* TARGET <- Intermediate <- SOURCE <- [Extra]
* LockWr Del Del LockWr
*
* Each diagram shows the involved media on the media chain where
* SOURCE and TARGET belong. Under each medium there is a state value which
* the medium must have at a time of the mergeTo() call.
*
* The media in the square braces may be absent (e.g. when the forward
* operation takes place and SOURCE is the base medium, or when the backward
* merge operation takes place and TARGET is the last child in the chain) but if
* they present they are involved too as shown.
*
* Neither the source medium nor intermediate media may be attached to
* any VM directly or in the snapshot, otherwise this method will assert.
*
* The #prepareMergeTo() method must be called prior to this method to place all
* involved to necessary states and perform other consistency checks.
*
* If @a aWait is @c true then this method will perform the operation on the
* calling thread and will not return to the caller until the operation is
* completed. When this method succeeds, all intermediate medium objects in
* the chain will be uninitialized, the state of the target medium (and all
* involved extra media) will be restored. @a aMediumLockList will not be
* deleted, whether the operation is successful or not. The caller has to do
* this if appropriate. Note that this (source) medium is not uninitialized
* because of possible AutoCaller instances held by the caller of this method
* on the current thread. It's therefore the responsibility of the caller to
* call Medium::uninit() after releasing all callers.
*
* If @a aWait is @c false then this method will create a thread to perform the
* operation asynchronously and will return immediately. If the operation
* succeeds, the thread will uninitialize the source medium object and all
* intermediate medium objects in the chain, reset the state of the target
* medium (and all involved extra media) and delete @a aMediumLockList.
* If the operation fails, the thread will only reset the states of all
* involved media and delete @a aMediumLockList.
*
* When this method fails (regardless of the @a aWait mode), it is a caller's
* responsibility to undo state changes and delete @a aMediumLockList using
* #cancelMergeTo().
*
* If @a aProgress is not NULL but the object it points to is @c null then a new
* progress object will be created and assigned to @a *aProgress on success,
* otherwise the existing progress object is used. If Progress is NULL, then no
* NULL when @a aWait is @c false (this method will assert in this case).
*
* @param pTarget Target medium.
* @param fMergeForward Merge direction.
* @param pParentForTarget New parent for target medium after merge.
* @param aChildrenToReparent List of children of the source which will have
* to be reparented to the target after merge.
* @param aMediumLockList Medium locking information.
* completion.
* @param aWait @c true if this method should block instead of creating
* an asynchronous thread.
*
* @note Locks the tree lock for writing. Locks the media from the chain
* for writing.
*/
bool fMergeForward,
bool aWait)
{
AutoCaller autoCaller(this);
try
{
{
/* use the existing progress object... */
/* ...but create a new one if it is null */
{
{
}
static_cast<IMedium*>(this),
TRUE /* aCancelable */);
throw rc;
}
}
aWait /* fKeepMediumLockList */);
throw rc;
}
{
if (aWait)
else
}
delete pTask;
return rc;
}
/**
* Undoes what #prepareMergeTo() did. Must be called if #mergeTo() is not
* called or fails. Frees memory occupied by @a aMediumLockList and unlocks
* the medium objects in @a aChildrenToReparent.
*
* @param aChildrenToReparent List of children of the source which will have
* to be reparented to the target after merge.
* @param aMediumLockList Medium locking information.
*
* @note Locks the media from the chain for writing.
*/
{
AutoCaller autoCaller(this);
/* Revert media marked for deletion to previous state. */
it != mediumListEnd;
++it)
{
{
}
}
/* the destructor will do the work */
delete aMediumLockList;
/* unlock the children which had to be reparented, the destructor will do
* the work */
if (aChildrenToReparent)
delete aChildrenToReparent;
}
/**
* Fix the parent UUID of all children to point to this medium as their
* parent.
*/
{
false /* fMediumLockWrite */,
false /* fMediumLockWriteAll */,
this,
try
{
try
{
it != lockListEnd;
++it)
{
// open the medium
pMedium->m->vdImageIfaces);
if (RT_FAILURE(vrc))
throw vrc;
}
it != childrenEnd;
++it)
{
/* VD_OPEN_FLAGS_INFO since UUID is wrong yet */
pMedium->m->vdImageIfaces);
if (RT_FAILURE(vrc))
throw vrc;
if (RT_FAILURE(vrc))
throw vrc;
if (RT_FAILURE(vrc))
throw vrc;
}
}
catch (int aVRC)
{
tr("Could not update medium UUID references to parent '%s' (%s)"),
m->strLocationFull.c_str(),
}
}
return rc;
}
/**
* Used by IAppliance to export disk images.
*
* @param aFilename Filename to create (UTF8).
* @param aFormat Medium format for creating @a aFilename.
* @param aVariant Which exact image format variant to use
* for the destination image.
* @param aVDImageIOCallbacks Pointer to the callback table for a
* VDINTERFACEIO interface. May be NULL.
* @param aVDImageIOUser Opaque data for the callbacks.
* @param aProgress Progress object to use.
* @return
* @note The source format is defined by the Medium instance.
*/
{
AutoCaller autoCaller(this);
try
{
// This needs no extra locks besides what is done in the called methods.
/* Build the source lock list. */
false /* fMediumLockWrite */,
false /* fMediumLockWriteAll */,
NULL,
{
delete pSourceMediumLockList;
throw rc;
}
{
delete pSourceMediumLockList;
tr("Failed to lock source media '%s'"),
i_getLocationFull().c_str());
}
/* setup task object to carry out the operation asynchronously */
throw rc;
}
delete pTask;
return rc;
}
/**
* Used by IAppliance to import disk images.
*
* @param aFilename Filename to read (UTF8).
* @param aFormat Medium format for reading @a aFilename.
* @param aVariant Which exact image format variant to use
* for the destination image.
* @param aVDImageIOCallbacks Pointer to the callback table for a
* VDINTERFACEIO interface. May be NULL.
* @param aVDImageIOUser Opaque data for the callbacks.
* @param aParent Parent medium. May be NULL.
* @param aProgress Progress object to use.
* @return
* @note The destination format is defined by the Medium instance.
*/
{
AutoCaller autoCaller(this);
try
{
// locking: we need the tree lock first because we access parent pointers
// and we need to write-lock the media involved
this->lockHandle() };
/* Only add parent to the lock if it is not null */
if ( m->state != MediumState_NotCreated
&& m->state != MediumState_Created)
throw i_setStateError();
/* Build the target lock list. */
true /* fMediumLockWrite */,
false /* fMediumLockWriteAll */,
{
delete pTargetMediumLockList;
throw rc;
}
{
delete pTargetMediumLockList;
tr("Failed to lock target media '%s'"),
i_getLocationFull().c_str());
}
/* setup task object to carry out the operation asynchronously */
throw rc;
if (m->state == MediumState_NotCreated)
m->state = MediumState_Creating;
}
delete pTask;
return rc;
}
/**
* Internal version of the public CloneTo API which allows to enable certain
* optimizations to improve speed during VM cloning.
*
* @param aTarget Target medium
* @param aVariant Which exact image format variant to use
* for the destination image.
* @param aParent Parent medium. May be NULL.
* @param aProgress Progress object to use.
* @param idxSrcImageSame The last image in the source chain which has the
* same content as the given image in the destination
* chain. Use UINT32_MAX to disable this optimization.
* @param idxDstImageSame The last image in the destination chain which has the
* same content as the given image in the source chain.
* Use UINT32_MAX to disable this optimization.
* @return
*/
{
AutoCaller autoCaller(this);
try
{
// locking: we need the tree lock first because we access parent pointers
// and we need to write-lock the media involved
this->lockHandle(),
aTarget->lockHandle() };
/* Only add parent to the lock if it is not null */
throw aTarget->i_setStateError();
/* Build the source lock list. */
false /* fMediumLockWrite */,
false /* fMediumLockWriteAll */,
NULL,
{
delete pSourceMediumLockList;
throw rc;
}
/* Build the target lock list (including the to-be parent chain). */
true /* fMediumLockWrite */,
false /* fMediumLockWriteAll */,
{
delete pSourceMediumLockList;
delete pTargetMediumLockList;
throw rc;
}
{
delete pSourceMediumLockList;
delete pTargetMediumLockList;
tr("Failed to lock source media '%s'"),
i_getLocationFull().c_str());
}
{
delete pSourceMediumLockList;
delete pTargetMediumLockList;
tr("Failed to lock target media '%s'"),
}
static_cast <IMedium *>(this),
TRUE /* aCancelable */);
{
delete pSourceMediumLockList;
delete pTargetMediumLockList;
throw rc;
}
/* setup task object to carry out the operation asynchronously */
throw rc;
}
{
}
delete pTask;
return rc;
}
////////////////////////////////////////////////////////////////////////////////
//
// Private methods
//
////////////////////////////////////////////////////////////////////////////////
/**
* Queries information from the medium.
*
* As a result of this call, the accessibility state and data members such as
* size and description will be updated with the current information.
*
* @note This method may block during a system I/O call that checks storage
* accessibility.
*
* @note Caller MUST NOT hold the media tree or medium lock.
*
* @note Locks mParent for reading. Locks this object for writing.
*
* @param fSetImageId Whether to reset the UUID contained in the image file to the UUID in the medium instance data (see SetIDs())
* @param fSetParentId Whether to reset the parent UUID contained in the image file to the parent
* UUID in the medium instance data (see SetIDs())
* @return
*/
{
if ( ( m->state != MediumState_Created
&& m->state != MediumState_Inaccessible
&& m->state != MediumState_LockedRead)
|| m->fClosing)
return E_FAIL;
int vrc = VINF_SUCCESS;
/* check if a blocking i_queryInfo() call is in progress on some other thread,
* and wait for it to finish if so instead of querying data ourselves */
if (m->queryInfoRunning)
{
|| m->state == MediumState_LockedWrite);
while (m->queryInfoRunning)
{
/* must not hold the object lock now */
{
}
}
return S_OK;
}
bool success = false;
/* are we dealing with a new medium constructed using the existing
* location? */
unsigned uOpenFlags = VD_OPEN_FLAGS_INFO;
/* Note that we don't use VD_OPEN_FLAGS_READONLY when opening new
* media because that would prevent necessary modifications
* when opening media of some third-party formats for the first
* time in VirtualBox (such as VMDK for which VDOpen() needs to
* generate an UUID if it is missing) */
if ( m->hddOpenMode == OpenReadOnly
|| m->type == MediumType_Readonly
)
/* Open shareable medium with the appropriate flags */
if (m->type == MediumType_Shareable)
/* Lock the medium, which makes the behavior much more consistent, must be
* done before dropping the object lock and setting queryInfoRunning. */
else
/* Copies of the input state fields which are not read-only,
* as we're dropping the lock. CAUTION: be extremely careful what
* you do with the contents of this medium object, as you will
* create races if there are concurrent changes. */
/* "Output" values which can't be set because the lock isn't held
* at the time the values are determined. */
uint64_t mediumSize = 0;
/* Flag whether a base image has a non-zero parent UUID and thus
* need repairing after it was closed again. */
bool fRepairImageZeroParentUuid = false;
/* must be set before leaving the object lock the first time */
m->queryInfoRunning = true;
/* must leave object lock now, because a lock from a higher lock class
* is needed and also a lengthy operation is coming */
/* Note that taking the queryInfoSem after leaving the object lock above
* can lead to short spinning of the loops waiting for i_queryInfo() to
* complete. This is unavoidable since the other order causes a lock order
* violation: here it would be requesting the object lock (at the beginning
* of the method), then queryInfoSem, and below the other way round. */
/* take the opportunity to have a media tree lock, released initially */
/* re-take the caller, but not the object lock, to keep uninit away */
autoCaller.add();
{
m->queryInfoRunning = false;
return autoCaller.rc();
}
try
{
/* skip accessibility checks for host drives */
if (m->hostDrive)
{
success = true;
throw S_OK;
}
try
{
/** @todo This kind of opening of media is assuming that diff
* media can be opened as base media. Should be documented that
* it must work for all medium format backends. */
uOpenFlags | m->uOpenFlagsDef,
m->vdImageIfaces);
if (RT_FAILURE(vrc))
{
throw S_OK;
}
{
/* Modify the UUIDs if necessary. The associated fields are
* not modified by other code, so no need to copy. */
if (fSetImageId)
{
if (RT_FAILURE(vrc))
{
throw S_OK;
}
}
if (fSetParentId)
{
if (RT_FAILURE(vrc))
{
throw S_OK;
}
}
/* zap the information, these are no long-term members */
/* check the UUID */
if (isImport)
{
// only when importing a VDMK that has no UUID, create one in memory
}
else
{
{
/** @todo r=klaus this always refers to VirtualBox.xml as the medium registry, even for new VMs */
tr("UUID {%RTuuid} of the medium '%s' does not match the value {%RTuuid} stored in the media registry ('%s')"),
&uuid,
throw S_OK;
}
}
}
else
{
/* the backend does not support storing UUIDs within the
* underlying storage so use what we store in XML */
if (fSetImageId)
{
/* set the UUID if an API client wants to change it */
}
else if (isImport)
{
/* generate an UUID for an imported UUID-less medium */
}
}
/* set the image uuid before the below parent uuid handling code
* might place it somewhere in the media tree, so that the medium
* UUID is valid at this point */
if (isImport || fSetImageId)
/* get the medium variant */
unsigned uImageFlags;
if (uImageFlags & VD_IMAGE_FLAGS_DIFF)
{
/* streamOptimized VMDK images are only accepted as base
* images, as this allows automatic repair of OVF appliances.
* Since such images don't support random writes they will not
* be created for diff images. Only an overly smart user might
* manually create this case. Too bad for him. */
if ( (isImport || fSetParentId)
{
/* the parent must be known to us. Note that we freely
* call locking methods of mVirtualBox and parent, as all
* relevant locks must be already held. There may be no
* concurrent access to the just opened medium on other
* threads yet (and init() will fail if this method reports
* MediumState_Inaccessible) */
if (RTUuidIsNull(&parentId))
else
{
if (fSetImageId && !fSetParentId)
{
/* If the image UUID gets changed for an existing
* image then the parent UUID can be stale. In such
* cases clear the parent information. The parent
* API client wants to adjust a complete medium
* hierarchy one by one. */
}
else
{
lastAccessError = Utf8StrFmt(tr("Parent medium with UUID {%RTuuid} of the medium '%s' is not found in the media registry ('%s')"),
throw S_OK;
}
}
/* must drop the caller before taking the tree lock */
/* we set mParent & children() */
autoCaller.add();
throw autoCaller.rc();
if (m->pParent)
i_deparent();
}
else
{
/* must drop the caller before taking the tree lock */
/* we access mParent */
autoCaller.add();
throw autoCaller.rc();
/* check that parent UUIDs match. Note that there's no need
* for the parent's AutoCaller (our lifetime is bound to
* it) */
{
/* Due to a bug in VDCopy() in VirtualBox 3.0.0-3.0.14
* and 3.1.0-3.1.8 there are base images out there
* which have a non-zero parent UUID. No point in
* complaining about them, instead automatically
* repair the problem. Later we can bring back the
* error message, but we should wait until really
* most users have repaired their images, either with
* VBoxFixHdd or this way. */
#if 1
fRepairImageZeroParentUuid = true;
#else /* 0 */
tr("Medium type of '%s' is differencing but it is not associated with any parent medium in the media registry ('%s')"),
throw S_OK;
#endif /* 0 */
}
{
autoCaller.add();
throw autoCaller.rc();
{
/** @todo r=klaus this always refers to VirtualBox.xml as the medium registry, even for new VMs */
tr("Parent UUID {%RTuuid} of the medium '%s' does not match UUID {%RTuuid} of its parent medium stored in the media registry ('%s')"),
throw S_OK;
}
}
/// @todo NEWMEDIA what to do if the parent is not
/// accessible while the diff is? Probably nothing. The
/// real code will detect the mismatch anyway.
}
}
success = true;
}
{
}
if (RT_FAILURE(vrc))
{
success = false;
throw S_OK;
}
}
{
}
autoCaller.add();
{
m->queryInfoRunning = false;
return autoCaller.rc();
}
if (success)
{
m->size = mediumSize;
m->logicalSize = mediumLogicalSize;
m->strLastAccessError.setNull();
}
else
{
LogWarningFunc(("'%s' is not accessible (error='%s', rc=%Rhrc, vrc=%Rrc)\n",
}
/* Set the proper state according to the result of the check */
if (success)
else
/* unblock anyone waiting for the i_queryInfo results */
m->queryInfoRunning = false;
/* If this is a base image which incorrectly has a parent UUID set,
* repair the image now by zeroing the parent UUID. This is only done
* when we have structural information from a config file, on import
* this is not possible. If someone would accidentally call openMedium
* with a diff image before the base is registered this would destroy
* the diff. Not acceptable. */
{
try
{
try
{
m->vdImageIfaces);
if (RT_FAILURE(vrc))
throw S_OK;
}
{
}
}
{
}
}
return rc;
}
/**
* Performs extra checks if the medium can be closed and returns S_OK in
* this case. Otherwise, returns a respective error message. Called by
* Close() under the medium tree lock and the medium lock.
*
* @note Also reused by Medium::Reset().
*
* @note Caller must hold the media tree write lock!
*/
{
if (i_getChildren().size() != 0)
return setError(VBOX_E_OBJECT_IN_USE,
tr("Cannot close medium '%s' because it has %d child media"),
return S_OK;
}
/**
* Unregisters this medium with mVirtualBox. Called by close() under the medium tree lock.
*
* @note Caller must have locked the media tree lock for writing!
*/
{
/* Note that we need to de-associate ourselves from the parent to let
* VirtualBox::i_unregisterMedium() properly save the registry */
/* we modify mParent and access children */
if (m->pParent)
i_deparent();
{
if (pParentBackup)
{
// re-associate with the parent as we are still relatives in the registry
m->pParent = pParentBackup;
}
}
return rc;
}
/**
* Like SetProperty but do not trigger a settings store. Only for internal use!
*/
{
AutoCaller autoCaller(this);
switch (m->state)
{
case MediumState_Created:
case MediumState_Inaccessible:
break;
default:
return i_setStateError();
}
return S_OK;
}
/**
* Sets the extended error info according to the current media state.
*
* @note Must be called from under this object's write or read lock.
*/
{
switch (m->state)
{
case MediumState_NotCreated:
{
tr("Storage for the medium '%s' is not created"),
m->strLocationFull.c_str());
break;
}
case MediumState_Created:
{
tr("Storage for the medium '%s' is already created"),
m->strLocationFull.c_str());
break;
}
case MediumState_LockedRead:
{
tr("Medium '%s' is locked for reading by another task"),
m->strLocationFull.c_str());
break;
}
case MediumState_LockedWrite:
{
tr("Medium '%s' is locked for writing by another task"),
m->strLocationFull.c_str());
break;
}
case MediumState_Inaccessible:
{
/* be in sync with Console::powerUpThread() */
if (!m->strLastAccessError.isEmpty())
tr("Medium '%s' is not accessible. %s"),
else
tr("Medium '%s' is not accessible"),
m->strLocationFull.c_str());
break;
}
case MediumState_Creating:
{
tr("Storage for the medium '%s' is being created"),
m->strLocationFull.c_str());
break;
}
case MediumState_Deleting:
{
tr("Storage for the medium '%s' is being deleted"),
m->strLocationFull.c_str());
break;
}
default:
{
AssertFailed();
break;
}
}
return rc;
}
/**
* Sets the value of m->strLocationFull. The given location must be a fully
* qualified path; relative paths are not supported here.
*
* As a special exception, if the specified location is a file path that ends with '/'
* then the file name part will be generated by this method automatically in the format
* '{<uuid>}.<ext>' where <uuid> is a fresh UUID that this method will generate
* and assign to this medium, and <ext> is the default extension for this
* medium's storage format. Note that this procedure requires the media state to
* be NotCreated and will return a failure otherwise.
*
* @param aLocation Location of the storage unit. If the location is a FS-path,
* then it can be relative to the VirtualBox home directory.
* @param aFormat Optional fallback format if it is an import and the format
* cannot be determined.
*
* @note Must be called from under this object's write lock.
*/
{
AutoCaller autoCaller(this);
/* formatObj may be null only when initializing from an existing path and
* no format is known yet */
&& m->state != MediumState_NotCreated
E_FAIL);
/* are we dealing with a new medium constructed using the existing
* location? */
if ( isImport
&& !m->hostDrive))
{
if (m->state == MediumState_NotCreated)
{
/* must be a file (formatObj must be already known) */
{
/* no file name is given (either an empty string or ends with a
* slash), generate a new UUID + file name if the state allows
* this */
("Must be at least one extension if it is MediumFormatCapabilities_File\n"),
E_FAIL);
("Default extension must not be empty\n"),
E_FAIL);
}
}
// we must always have full paths now (if it refers to a file)
return setError(VBOX_E_FILE_ERROR,
tr("The given path '%s' is not fully qualified"),
locationFull.c_str());
/* detect the backend from the storage unit if importing */
if (isImport)
{
char *backendName = NULL;
int vrc = VINF_SUCCESS;
/* is it a file? */
{
if (RT_SUCCESS(vrc))
}
if (RT_SUCCESS(vrc))
{
}
else if ( vrc != VERR_FILE_NOT_FOUND
&& vrc != VERR_PATH_NOT_FOUND
&& vrc != VERR_ACCESS_DENIED
&& locationFull != aLocation)
{
/* assume it's not a file, restore the original location */
}
if (RT_FAILURE(vrc))
{
if (vrc == VERR_ACCESS_DENIED)
return setError(VBOX_E_FILE_ERROR,
tr("Permission problem accessing the file for the medium '%s' (%Rrc)"),
return setError(VBOX_E_FILE_ERROR,
tr("Could not find file for the medium '%s' (%Rrc)"),
return setError(VBOX_E_IPRT_ERROR,
tr("Could not get the storage format of the medium '%s' (%Rrc)"),
else
{
/* setFormat() must not fail since we've just used the backend so
* the format object must be there */
}
}
else if ( enmType == VDTYPE_INVALID
{
/*
* The user tried to use a image as a device which is not supported
* by the backend.
*/
tr("The medium '%s' can't be used as the requested device type"),
locationFull.c_str());
}
else
{
/* setFormat() must not fail since we've just used the backend so
* the format object must be there */
}
}
m->strLocationFull = locationFull;
/* is it still a file? */
&& (m->state == MediumState_NotCreated)
)
/* assign a new UUID (this UUID will be used when calling
* VDCreateBase/VDCreateDiff as a wanted UUID). Note that we
* also do that if we didn't generate it to make sure it is
* either generated by us or reset to null */
}
else
m->strLocationFull = aLocation;
return S_OK;
}
/**
* Checks that the format ID is valid and sets it on success.
*
* Note that this method will caller-reference the format object on success!
* This reference must be released somewhere to let the MediumFormat object be
* uninitialized.
*
* @note Must be called from under this object's write lock.
*/
{
/* get the format object first */
{
return setError(E_INVALIDARG,
tr("Invalid medium storage format '%s'"),
/* get properties (preinsert them as keys in the map). Note that the
* map doesn't grow over the object life time since the set of
* properties is meant to be constant. */
++it)
{
}
}
return S_OK;
}
/**
* Converts the Medium device type to the VD type.
*/
{
switch (m->devType)
{
case DeviceType_HardDisk:
break;
case DeviceType_DVD:
break;
case DeviceType_Floppy:
break;
default:
}
return enmType;
}
/**
* Converts from the VD type to the medium type.
*/
{
switch (enmType)
{
case VDTYPE_HDD:
break;
case VDTYPE_DVD:
break;
case VDTYPE_FLOPPY:
break;
default:
}
return devType;
}
/**
* Internal method which checks whether a property name is for a filter plugin.
*/
{
/* If the name contains "/" use the part before as a filter name and lookup the filter. */
{
return false;
return false;
if (RT_SUCCESS(vrc))
{
/* Check that the property exists. */
{
return true;
paConfig++;
}
}
}
return false;
}
/**
* Returns the last error message collected by the i_vdErrorCall callback and
* resets it.
*
* The error message is returned prepended with a dot and a space, like this:
* <code>
* ". <error_text> (%Rrc)"
* </code>
* to make it easily appendable to a more general error message. The @c %Rrc
* format string is given @a aVRC as an argument.
*
* If there is no last error message collected by i_vdErrorCall or if it is a
* null or empty string, then this function returns the following text:
* <code>
* " (%Rrc)"
* </code>
*
* @note Doesn't do any object locking; it is assumed that the caller makes sure
* the callback isn't called by more than one thread at a time.
*
* @param aVRC VBox error code to use when no error message is provided.
*/
{
else
return error;
}
/**
* Error message callback.
*
* Puts the reported error message to the m->vdError field.
*
* @note Doesn't do any object locking; it is assumed that the caller makes sure
* the callback isn't called by more than one thread at a time.
*
* @param pvUser The opaque data passed on container creation.
* @param rc The VBox error code.
* @param RT_SRC_POS_DECL Use RT_SRC_POS.
* @param pszFormat Error message format string.
* @param va Error message arguments.
*/
/*static*/
{
else
}
/* static */
const char * /* pszzValid */)
{
/* we always return true since the only keys we have are those found in
* VDBACKENDINFO */
return true;
}
/* static */
const char *pszName,
{
return VERR_CFGM_VALUE_NOT_FOUND;
/* we interpret null values as "no value" in Medium */
return VERR_CFGM_VALUE_NOT_FOUND;
return VINF_SUCCESS;
}
/* static */
const char *pszName,
char *pszValue,
{
return VERR_CFGM_VALUE_NOT_FOUND;
/* we interpret null values as "no value" in Medium */
return VERR_CFGM_VALUE_NOT_FOUND;
return VERR_CFGM_NOT_ENOUGH_SPACE;
return VINF_SUCCESS;
}
{
if ((fFlags & VD_INTERFACETCPNET_CONNECT_EXTENDED_SELECT) != 0)
return VERR_NOT_SUPPORTED;
if (!pSocketInt)
return VERR_NO_MEMORY;
*pSock = pSocketInt;
return VINF_SUCCESS;
}
{
return VINF_SUCCESS;
}
DECLCALLBACK(int) Medium::i_vdTcpClientConnect(VDSOCKET Sock, const char *pszAddress, uint32_t uPort,
{
}
{
int rc = VINF_SUCCESS;
return rc;
}
{
}
{
}
DECLCALLBACK(int) Medium::i_vdTcpRead(VDSOCKET Sock, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
{
}
{
}
{
}
{
}
{
}
{
}
{
}
{
/* Just return always true here. */
return true;
}
DECLCALLBACK(int) Medium::i_vdCryptoConfigQuerySize(void *pvUser, const char *pszName, size_t *pcbValue)
{
cbValue = sizeof("irrelevant");
{
if (!pSettings->pszKeyStoreLoad)
return VERR_CFGM_VALUE_NOT_FOUND;
}
else
return VERR_CFGM_VALUE_NOT_FOUND;
return VINF_SUCCESS;
}
{
psz = "irrelevant";
{
if (pSettings->fCreateKeyStore)
psz = "1";
else
psz = "0";
}
else
return VERR_CFGM_VALUE_NOT_FOUND;
return VERR_CFGM_NOT_ENOUGH_SPACE;
return VINF_SUCCESS;
}
{
}
{
}
DECLCALLBACK(int) Medium::i_vdCryptoKeyStorePasswordRetain(void *pvUser, const char *pszId, const char **ppszPassword)
{
return VINF_SUCCESS;
}
{
return VINF_SUCCESS;
}
DECLCALLBACK(int) Medium::i_vdCryptoKeyStoreSave(void *pvUser, const void *pvKeyStore, size_t cbKeyStore)
{
if (!pSettings->pszKeyStore)
return VERR_NO_MEMORY;
return VINF_SUCCESS;
}
{
return VINF_SUCCESS;
}
/**
* Starts a new thread driven by the appropriate Medium::Task::handler() method.
*
* @note When the task is executed by this method, IProgress::notifyComplete()
* is automatically called for the progress object associated with this
* task when the task is finished to signal the operation completion for
* other threads asynchronously waiting for it.
*/
{
/* Extreme paranoia: The calling thread should not hold the medium
* tree lock or any medium lock. Since there is no separate lock class
* for medium objects be even more strict: no other object locks. */
#endif
/// @todo use a more descriptive task name
"Medium::Task");
if (RT_FAILURE(vrc))
{
delete pTask;
}
return S_OK;
}
/**
* Runs Medium::Task::handler() on the current thread instead of creating
* a new one.
*
* This call implies that it is made on another temporary thread created for
* some asynchronous task. Avoid calling it from a normal thread since the task
* operations are potentially lengthy and will block the calling thread in this
* case.
*
* @note When the task is executed by this method, IProgress::notifyComplete()
* is not called for the progress object associated with this task when
* the task is finished. Instead, the result of the operation is returned
* by this method directly and it's the caller's responsibility to
* complete the progress object in this case.
*/
{
/* Extreme paranoia: The calling thread should not hold the medium
* tree lock or any medium lock. Since there is no separate lock class
* for medium objects be even more strict: no other object locks. */
#endif
/* NIL_RTTHREAD indicates synchronous call. */
}
/**
* Implementation code for the "create base" task.
*
* This only gets started from Medium::CreateBaseStorage() and always runs
* asynchronously. As a result, we always save the VirtualBox.xml file when
* we're done here.
*
* @param task
* @return
*/
{
/* these parameters we need after creation */
bool fGenerateUuid = false;
try
{
/* The object may request a specific UUID (through a special form of
* the setLocation() argument). Otherwise we have to generate it */
if (fGenerateUuid)
{
/* VirtualBox::i_registerMedium() will need UUID */
}
/* unlock before the potentially lengthy operation */
try
{
/* ensure the directory exists */
{
rc = VirtualBox::i_ensureFilePathExists(location, !(task.mVariant & MediumVariant_NoCreateDir) /* fCreate */);
throw rc;
}
NULL,
&geo,
&geo,
m->vdImageIfaces,
if (RT_FAILURE(vrc))
{
if (vrc == VERR_VD_INVALID_TYPE)
throw setError(VBOX_E_FILE_ERROR,
tr("Parameters for creating the medium storage unit '%s' are invalid%s"),
else
throw setError(VBOX_E_FILE_ERROR,
tr("Could not create the medium storage unit '%s'%s"),
}
unsigned uImageFlags;
if (RT_SUCCESS(vrc))
}
}
{
/* register with mVirtualBox as the last step and move to
* Created state only on success (leaving an orphan file is
* better than breaking media registry consistency) */
}
// re-acquire the lock before changing state
{
m->state = MediumState_Created;
m->logicalSize = logicalSize;
{
// in asynchronous mode, save settings now
}
}
else
{
/* back to NotCreated on failure */
m->state = MediumState_NotCreated;
/* reset UUID to prevent it from being reused next time */
if (fGenerateUuid)
}
return rc;
}
/**
* Implementation code for the "create diff" task.
*
* This task always gets started from Medium::createDiffStorage() and can run
* synchronously or asynchronously depending on the "wait" parameter passed to
* that function. If we run synchronously, the caller expects the medium
* registry modification to be set before returning; otherwise (in asynchronous
* mode), we save the settings ourselves.
*
* @param task
* @return
*/
{
bool fGenerateUuid = false;
try
{
/* Lock both in {parent,child} order. */
/* The object may request a specific UUID (through a special form of
* the setLocation() argument). Otherwise we have to generate it */
if (fGenerateUuid)
{
/* VirtualBox::i_registerMedium() will need UUID */
}
/* the two media are now protected by their non-default states;
* unlock the media before the potentially lengthy operation */
try
{
/* Open all media in the target chain but the last. */
it != targetListEnd;
++it)
{
/* Skip over the target diff medium */
continue;
/* sanity check */
/* Open all media in appropriate mode. */
pMedium->m->vdImageIfaces);
if (RT_FAILURE(vrc))
throw setError(VBOX_E_FILE_ERROR,
tr("Could not open the medium storage unit '%s'%s"),
}
/* ensure the target directory exists */
{
throw rc;
}
NULL,
pTarget->m->vdImageIfaces,
if (RT_FAILURE(vrc))
{
if (vrc == VERR_VD_INVALID_TYPE)
throw setError(VBOX_E_FILE_ERROR,
tr("Parameters for creating the differencing medium storage unit '%s' are invalid%s"),
else
throw setError(VBOX_E_FILE_ERROR,
tr("Could not create the differencing medium storage unit '%s'%s"),
}
unsigned uImageFlags;
if (RT_SUCCESS(vrc))
}
}
{
/* associate the child with the parent */
/** @todo r=klaus neither target nor base() are locked,
* potential race! */
/* diffs for immutable media are auto-reset by default */
/* register with mVirtualBox as the last step and move to
* Created state only on success (leaving an orphan file is
* better than breaking media registry consistency) */
/* break the parent association on failure to register */
i_deparent();
}
{
}
else
{
/* back to NotCreated on failure */
/* reset UUID to prevent it from being reused next time */
if (fGenerateUuid)
}
// deregister the task registered in createDiffStorage()
Assert(m->numCreateDiffTasks != 0);
--m->numCreateDiffTasks;
{
// in asynchronous mode, save settings now
}
/* Note that in sync mode, it's the caller's responsibility to
* unlock the medium. */
return mrc;
}
/**
* Implementation code for the "merge" task.
*
* This task always gets started from Medium::mergeTo() and can run
* synchronously or asynchronously depending on the "wait" parameter passed to
* that function. If we run synchronously, the caller expects the medium
* registry modification to be set before returning; otherwise (in asynchronous
* mode), we save the settings ourselves.
*
* @param task
* @return
*/
{
try
{
try
{
// Similar code appears in SessionMachine::onlineMergeMedium, so
// if you make any changes below check whether they are applicable
// in that context as well.
unsigned uTargetIdx = VD_LAST_IMAGE;
unsigned uSourceIdx = VD_LAST_IMAGE;
/* Open all media in the chain. */
unsigned i = 0;
it != lockListEnd;
++it)
{
if (pMedium == this)
uSourceIdx = i;
uTargetIdx = i;
/*
* complex sanity (sane complexity)
*
* The current medium must be in the Deleting (medium is merged)
* or LockedRead (parent medium) state if it is not the target.
* If it is the target it must be in the LockedWrite state.
*/
/*
* Medium must be the target, in the LockedRead state
* or Deleting state where it is not allowed to be attached
* to a virtual machine.
*/
/* The source medium must be in Deleting state. */
unsigned uOpenFlags = VD_OPEN_FLAGS_NORMAL;
/* Open the medium */
uOpenFlags | m->uOpenFlagsDef,
pMedium->m->vdImageIfaces);
if (RT_FAILURE(vrc))
throw vrc;
i++;
}
if (RT_FAILURE(vrc))
throw vrc;
/* update parent UUIDs */
if (!task.mfMergeForward)
{
/* we need to update UUIDs of all source's children
* which cannot be part of the container at once so
* add each one in there individually */
if (task.mpChildrenToReparent)
{
it != childrenEnd;
++it)
{
/* VD_OPEN_FLAGS_INFO since UUID is wrong yet */
pMedium->m->vdImageIfaces);
if (RT_FAILURE(vrc))
throw vrc;
if (RT_FAILURE(vrc))
throw vrc;
if (RT_FAILURE(vrc))
throw vrc;
}
}
}
}
catch (int aVRC)
{
tr("Could not merge the medium '%s' to '%s'%s"),
m->strLocationFull.c_str(),
}
}
{
/* all media but the target were successfully deleted by
* VDMerge; reparent the last one and uninitialize deleted media. */
if (task.mfMergeForward)
{
/* first, unregister the target since it may become a base
* medium which needs re-registration */
/* then, reparent it and disconnect the deleted branch at
* both ends (chain->parent() is source's parent) */
pTarget->i_deparent();
{
i_deparent();
}
/* then, register again */
treeLock);
}
else
{
/* disconnect the deleted branch at the elder end */
/* reparent source's children and disconnect the deleted
* branch at the younger end */
if (task.mpChildrenToReparent)
{
/* obey {parent,child} lock order */
it != childrenEnd;
++it)
{
}
}
}
/* unregister and uninitialize all media removed by the merge */
it != lockListEnd;
)
{
/* Create a real copy of the medium pointer, as the medium
* lock deletion below would invalidate the referenced object. */
/* The target and all media not merged (readonly) are skipped */
{
++it;
continue;
}
/* now, uninitialize the deleted medium (note that
* due to the Deleting state, uninit() will not touch
* the parent-child relationship so we need to
* uninitialize each disk individually) */
/* note that the operation initiator medium (which is
* normally also the source medium) is a special case
* -- there is one more caller added by Task to it which
* we must release. Also, if we are in sync mode, the
* caller may still hold an AutoCaller instance for it
* and therefore we cannot uninit() it (it's therefore
* the caller's responsibility) */
if (pMedium == this)
{
}
/* Delete the medium lock list entry, which also releases the
* caller added by MergeChain before uninit() and updates the
* iterator to point to the right place. */
{
}
}
}
{
// in asynchronous mode, save settings now
}
{
/* Here we come if either VDMerge() failed (in which case we
* assume that it tried to do everything to make a further
* retry possible -- e.g. not deleted intermediate media
* and so on) or VirtualBox::saveRegistries() failed (where we
* should have the original tree but with intermediate storage
* units deleted by VDMerge()). We have to only restore states
* (through the MergeChain dtor) unless we are run synchronously
* in which case it's the responsibility of the caller as stated
* in the mergeTo() docs. The latter also implies that we
* don't own the merge chain, so release it in this case. */
}
return mrc;
}
/**
* Implementation code for the "clone" task.
*
* This only gets started from Medium::CloneTo() and always runs asynchronously.
* As a result, we always save the VirtualBox.xml file when we're done here.
*
* @param task
* @return
*/
{
bool fCreatingTarget = false;
bool fGenerateUuid = false;
try
{
/* Lock all in {parent,child} order. The lock is also used as a
* signal from the task initiator (which releases it only after
* RTThreadCreate()) that we can start the job. */
/* The object may request a specific UUID (through a special form of
* the setLocation() argument). Otherwise we have to generate it */
if (fGenerateUuid)
{
/* VirtualBox::registerMedium() will need UUID */
}
try
{
/* Open all media in the source chain. */
it != sourceListEnd;
++it)
{
/* sanity check */
/** Open all media in read-only mode. */
pMedium->m->vdImageIfaces);
if (RT_FAILURE(vrc))
throw setError(VBOX_E_FILE_ERROR,
tr("Could not open the medium storage unit '%s'%s"),
}
/* unlock before the potentially lengthy operation */
/* ensure the target directory exists */
{
throw rc;
}
try
{
/* Open all media in the target chain. */
it != targetListEnd;
++it)
{
/* If the target medium is not created yet there's no
* reason to open it. */
continue;
/* sanity check */
unsigned uOpenFlags = VD_OPEN_FLAGS_NORMAL;
/* Open all media in appropriate mode. */
uOpenFlags | m->uOpenFlagsDef,
pMedium->m->vdImageIfaces);
if (RT_FAILURE(vrc))
throw setError(VBOX_E_FILE_ERROR,
tr("Could not open the medium storage unit '%s'%s"),
}
/** @todo r=klaus target isn't locked, race getting the state */
{
false /* fMoveByRename */,
0 /* cbSize */,
NULL /* pVDIfsOperation */,
pTarget->m->vdImageIfaces,
}
else
{
false /* fMoveByRename */,
0 /* cbSize */,
NULL /* pVDIfsOperation */,
pTarget->m->vdImageIfaces,
}
if (RT_FAILURE(vrc))
throw setError(VBOX_E_FILE_ERROR,
tr("Could not create the clone medium '%s'%s"),
unsigned uImageFlags;
if (RT_SUCCESS(vrc))
}
}
}
/* Only do the parent changes for newly created media. */
{
/* we set mParent & children() */
if (pParent)
{
/* associate the clone with the parent and deassociate
* from VirtualBox */
/* register with mVirtualBox as the last step and move to
* Created state only on success (leaving an orphan file is
* better than breaking media registry consistency) */
treeLock);
/* break parent association on failure to register */
}
else
{
/* just register */
treeLock);
}
}
if (fCreatingTarget)
{
{
}
else
{
/* back to NotCreated on failure */
/* reset UUID to prevent it from being reused next time */
if (fGenerateUuid)
}
}
// now, at the end of this task (always asynchronous), save the settings
{
// save the settings
/* collect multiple errors */
}
/* Everything is explicitly unlocked when the task exits,
* as the task destruction also destroys the source chain. */
/* Make sure the source chain is released early. It could happen
* that we get a deadlock in Appliance::Import when Medium::Close
* is called & the source chain is released at the same time. */
return mrc;
}
/**
* Implementation code for the "delete" task.
*
* This task always gets started from Medium::deleteStorage() and can run
* synchronously or asynchronously depending on the "wait" parameter passed to
* that function.
*
* @param task
* @return
*/
{
try
{
/* The lock is also used as a signal from the task initiator (which
* releases it only after RTThreadCreate()) that we can start the job */
/* unlock before the potentially lengthy operation */
try
{
m->vdImageIfaces);
if (RT_SUCCESS(vrc))
if (RT_FAILURE(vrc))
throw setError(VBOX_E_FILE_ERROR,
tr("Could not delete the medium storage unit '%s'%s"),
}
}
/* go to the NotCreated state even on failure since the storage
* may have been already partially deleted and cannot be used any
* more. One will be able to manually re-open the storage if really
* needed to re-register it. */
m->state = MediumState_NotCreated;
/* Reset UUID to prevent Create* from reusing it again */
return rc;
}
/**
* Implementation code for the "reset" task.
*
* This always gets started asynchronously from Medium::Reset().
*
* @param task
* @return
*/
{
try
{
/* The lock is also used as a signal from the task initiator (which
* releases it only after RTThreadCreate()) that we can start the job */
/// the diff contents but the most efficient way will of course be
/// to add a VDResetDiff() API call
/* unlock before the potentially lengthy operation */
try
{
/* Open all media in the target chain but the last. */
it != targetListEnd;
++it)
{
/* sanity check, "this" is checked above */
/* Open all media in appropriate mode. */
pMedium->m->vdImageIfaces);
if (RT_FAILURE(vrc))
throw setError(VBOX_E_FILE_ERROR,
tr("Could not open the medium storage unit '%s'%s"),
/* Done when we hit the media which should be reset */
if (pMedium == this)
break;
}
/* first, delete the storage unit */
if (RT_FAILURE(vrc))
throw setError(VBOX_E_FILE_ERROR,
tr("Could not delete the medium storage unit '%s'%s"),
/* next, create it again */
m->vdImageIfaces);
if (RT_FAILURE(vrc))
throw setError(VBOX_E_FILE_ERROR,
tr("Could not open the medium storage unit '%s'%s"),
/// @todo use the same medium variant as before
NULL,
m->vdImageIfaces,
if (RT_FAILURE(vrc))
{
if (vrc == VERR_VD_INVALID_TYPE)
throw setError(VBOX_E_FILE_ERROR,
tr("Parameters for creating the differencing medium storage unit '%s' are invalid%s"),
else
throw setError(VBOX_E_FILE_ERROR,
tr("Could not create the differencing medium storage unit '%s'%s"),
}
unsigned uImageFlags;
if (RT_SUCCESS(vrc))
}
}
m->logicalSize = logicalSize;
/* Everything is explicitly unlocked when the task exits,
* as the task destruction also destroys the media chain. */
return rc;
}
/**
* Implementation code for the "compact" task.
*
* @param task
* @return
*/
{
/* Lock all in {parent,child} order. The lock is also used as a
* signal from the task initiator (which releases it only after
* RTThreadCreate()) that we can start the job. */
try
{
try
{
/* Open all media in the chain. */
it != mediumListEnd;
++it)
{
/* sanity check */
if (it == mediumListLast)
else
/* Open all media but last in read-only mode. Do not handle
* shareable media, as compaction and sharing are mutually
* exclusive. */
pMedium->m->vdImageIfaces);
if (RT_FAILURE(vrc))
throw setError(VBOX_E_FILE_ERROR,
tr("Could not open the medium storage unit '%s'%s"),
}
/* unlock before the potentially lengthy operation */
if (RT_FAILURE(vrc))
{
if (vrc == VERR_NOT_SUPPORTED)
throw setError(VBOX_E_NOT_SUPPORTED,
tr("Compacting is not yet supported for medium '%s'"),
else if (vrc == VERR_NOT_IMPLEMENTED)
tr("Compacting is not implemented, medium '%s'"),
else
throw setError(VBOX_E_FILE_ERROR,
tr("Could not compact medium '%s'%s"),
}
}
}
/* Everything is explicitly unlocked when the task exits,
* as the task destruction also destroys the media chain. */
return rc;
}
/**
* Implementation code for the "resize" task.
*
* @param task
* @return
*/
{
try
{
/* The lock is also used as a signal from the task initiator (which
* releases it only after RTThreadCreate()) that we can start the job */
try
{
/* Open all media in the chain. */
it != mediumListEnd;
++it)
{
/* sanity check */
if (it == mediumListLast)
else
/* Open all media but last in read-only mode. Do not handle
* shareable media, as compaction and sharing are mutually
* exclusive. */
pMedium->m->vdImageIfaces);
if (RT_FAILURE(vrc))
throw setError(VBOX_E_FILE_ERROR,
tr("Could not open the medium storage unit '%s'%s"),
}
/* unlock before the potentially lengthy operation */
if (RT_FAILURE(vrc))
{
if (vrc == VERR_NOT_SUPPORTED)
throw setError(VBOX_E_NOT_SUPPORTED,
tr("Resizing to new size %llu is not yet supported for medium '%s'"),
else if (vrc == VERR_NOT_IMPLEMENTED)
tr("Resiting is not implemented, medium '%s'"),
else
throw setError(VBOX_E_FILE_ERROR,
tr("Could not resize medium '%s'%s"),
}
}
}
{
m->logicalSize = logicalSize;
}
/* Everything is explicitly unlocked when the task exits,
* as the task destruction also destroys the media chain. */
return rc;
}
/**
* Implementation code for the "export" task.
*
* This only gets started from Medium::exportFile() and always runs
* asynchronously. It doesn't touch anything configuration related, so
* we never save the VirtualBox.xml file here.
*
* @param task
* @return
*/
{
try
{
/* Lock all in {parent,child} order. The lock is also used as a
* signal from the task initiator (which releases it only after
* RTThreadCreate()) that we can start the job. */
try
{
/* Open all media in the source chain. */
it != sourceListEnd;
++it)
{
/* sanity check */
/* Open all media in read-only mode. */
pMedium->m->vdImageIfaces);
if (RT_FAILURE(vrc))
throw setError(VBOX_E_FILE_ERROR,
tr("Could not open the medium storage unit '%s'%s"),
}
/* unlock before the potentially lengthy operation */
/* ensure the target directory exists */
{
throw rc;
}
try
{
false /* fMoveByRename */,
0 /* cbSize */,
NULL /* pDstUuid */,
NULL /* pVDIfsOperation */,
if (RT_FAILURE(vrc))
throw setError(VBOX_E_FILE_ERROR,
tr("Could not create the exported medium '%s'%s"),
}
}
}
/* Everything is explicitly unlocked when the task exits,
* as the task destruction also destroys the source chain. */
/* Make sure the source chain is released early, otherwise it can
* lead to deadlocks with concurrent IAppliance activities. */
return rc;
}
/**
* Implementation code for the "import" task.
*
* This only gets started from Medium::importFile() and always runs
* asynchronously. It potentially touches the media registry, so we
* always save the VirtualBox.xml file when we're done here.
*
* @param task
* @return
*/
{
bool fCreatingTarget = false;
bool fGenerateUuid = false;
try
{
/* Lock all in {parent,child} order. The lock is also used as a
* signal from the task initiator (which releases it only after
* RTThreadCreate()) that we can start the job. */
/* The object may request a specific UUID (through a special form of
* the setLocation() argument). Otherwise we have to generate it */
if (fGenerateUuid)
{
/* VirtualBox::i_registerMedium() will need UUID */
}
try
{
/* Open source medium. */
if (RT_FAILURE(vrc))
throw setError(VBOX_E_FILE_ERROR,
tr("Could not open the medium storage unit '%s'%s"),
|| m->state == MediumState_LockedWrite);
/* unlock before the potentially lengthy operation */
/* ensure the target directory exists */
{
throw rc;
}
try
{
/* Open all media in the target chain. */
it != targetListEnd;
++it)
{
/* If the target medium is not created yet there's no
* reason to open it. */
if (pMedium == this && fCreatingTarget)
continue;
/* sanity check */
unsigned uOpenFlags = VD_OPEN_FLAGS_NORMAL;
/* Open all media in appropriate mode. */
uOpenFlags | m->uOpenFlagsDef,
pMedium->m->vdImageIfaces);
if (RT_FAILURE(vrc))
throw setError(VBOX_E_FILE_ERROR,
tr("Could not open the medium storage unit '%s'%s"),
}
/** @todo r=klaus target isn't locked, race getting the state */
false /* fMoveByRename */,
0 /* cbSize */,
NULL /* pVDIfsOperation */,
m->vdImageIfaces,
if (RT_FAILURE(vrc))
throw setError(VBOX_E_FILE_ERROR,
tr("Could not create the imported medium '%s'%s"),
unsigned uImageFlags;
if (RT_SUCCESS(vrc))
}
}
}
/* Only do the parent changes for newly created media. */
{
/* we set mParent & children() */
if (pParent)
{
/* associate the imported medium with the parent and deassociate
* from VirtualBox */
/* register with mVirtualBox as the last step and move to
* Created state only on success (leaving an orphan file is
* better than breaking media registry consistency) */
treeLock);
/* break parent association on failure to register */
this->i_deparent(); // removes target from parent
}
else
{
/* just register */
}
}
if (fCreatingTarget)
{
{
m->state = MediumState_Created;
m->logicalSize = logicalSize;
}
else
{
/* back to NotCreated on failure */
m->state = MediumState_NotCreated;
/* reset UUID to prevent it from being reused next time */
if (fGenerateUuid)
}
}
// now, at the end of this task (always asynchronous), save the settings
{
// save the settings
/* collect multiple errors */
}
/* Everything is explicitly unlocked when the task exits,
* as the task destruction also destroys the target chain. */
/* Make sure the target chain is released early, otherwise it can
* lead to deadlocks with concurrent IAppliance activities. */
return mrc;
}
/**
* Sets up the encryption settings for a filter.
*/
const char *pszKeyStore, const char *pszPassword,
bool fCreateKeyStore)
{
"Medium::vdInterfaceCfgCrypto",
"Medium::vdInterfaceCrypto",
}
/**
* Implementation code for the "encrypt" task.
*
* @param task
* @return
*/
{
/* Lock all in {parent,child} order. The lock is also used as a
* signal from the task initiator (which releases it only after
* RTThreadCreate()) that we can start the job. */
try
{
# ifdef VBOX_WITH_EXTPACK
static const char *s_pszVDPlugin = "VDPluginCrypt";
{
/* Load the plugin */
{
if (RT_FAILURE(vrc))
throw setError(VBOX_E_NOT_SUPPORTED,
tr("Encrypting the image failed because the encryption plugin could not be loaded (%s)"),
}
else
throw setError(VBOX_E_NOT_SUPPORTED,
tr("Encryption is not supported because the extension pack '%s' is missing the encryption plugin (old extension pack installed?)"),
strExtPackPuel.c_str());
}
else
throw setError(VBOX_E_NOT_SUPPORTED,
tr("Encryption is not supported because the extension pack '%s' is missing"),
strExtPackPuel.c_str());
char *pszCipherOld = NULL;
char *pszKeyStoreEncNew = NULL;
try
{
/* Set up disk encryption filters. */
{
/*
* Query whether the medium property indicating that encryption is
* configured is existing.
*/
tr("The password given for the encrypted image is incorrect"));
}
else
{
tr("The image is not configured for encryption"));
i_taskEncryptSettingsSetup(&CryptoSettingsRead, NULL, it->second.c_str(), task.mstrOldPassword.c_str(),
false /* fCreateKeyStore */);
if (RT_FAILURE(vrc))
tr("Failed to load the decryption filter: %s"),
}
{
throw setError(VBOX_E_OBJECT_NOT_FOUND,
tr("No valid cipher identifier was given for encryption"));
tr("A new password must always have a valid identifier"));
if (RT_FAILURE(vrc))
tr("Failed to load the encryption filter: %s"),
}
tr("The password identifier must be empty if there is no new password set for encryption"));
/* Open all media in the chain. */
it != mediumListEnd;
++it)
{
/* Open all media but last in read-only mode. Do not handle
* shareable media, as compaction and sharing are mutually
* exclusive. */
pMedium->m->vdImageIfaces);
if (RT_FAILURE(vrc))
throw setError(VBOX_E_FILE_ERROR,
tr("Could not open the medium storage unit '%s'%s"),
}
/* unlock before the potentially lengthy operation */
if (RT_FAILURE(vrc))
throw setError(VBOX_E_FILE_ERROR,
tr("Could not prepare disk images for encryption (%Rrc)"),
/* If everything went well set the new key store. */
{
}
}
if (pvBuf)
# else
throw setError(VBOX_E_NOT_SUPPORTED,
tr("Encryption is not supported because extension pack support is not built in"));
# endif
}
/* Everything is explicitly unlocked when the task exits,
* as the task destruction also destroys the media chain. */
return rc;
}
/* vi: set tabstop=4 shiftwidth=4 expandtab: */