VirtualBox

Changeset 26046 in vbox for trunk/src/VBox/Main/include


Ignore:
Timestamp:
Jan 26, 2010 2:06:05 PM (15 years ago)
Author:
vboxsync
svn:sync-xref-src-repo-rev:
56959
Message:

Main: move Auto*StateDependency templates out of MachineImpl.h

Location:
trunk/src/VBox/Main/include
Files:
1 edited
1 copied

Legend:

Unmodified
Added
Removed
  • trunk/src/VBox/Main/include/AutoStateDep.h

    r26044 r26046  
    1 /* $Id$ */
     1#ifndef ____H_AUTOSTATEDEP
     2#define ____H_AUTOSTATEDEP
    23
    34/** @file
    45 *
    5  * VirtualBox COM class declaration
     6 * AutoStateDep template classes, formerly in MachineImpl.h. Use these if
     7 * you need to ensure that the machine state does not change over a certain
     8 * period of time.
    69 */
    710
     
    2124 * additional information or have any questions.
    2225 */
    23 
    24 #ifndef ____H_MACHINEIMPL
    25 #define ____H_MACHINEIMPL
    26 
    27 #include "VirtualBoxBase.h"
    28 #include "SnapshotImpl.h"
    29 #include "VRDPServerImpl.h"
    30 #include "MediumAttachmentImpl.h"
    31 #include "NetworkAdapterImpl.h"
    32 #include "AudioAdapterImpl.h"
    33 #include "SerialPortImpl.h"
    34 #include "ParallelPortImpl.h"
    35 #include "BIOSSettingsImpl.h"
    36 #include "StorageControllerImpl.h"          // required for MachineImpl.h to compile on Windows
    37 #include "VBox/settings.h"
    38 #ifdef VBOX_WITH_RESOURCE_USAGE_API
    39 #include "PerformanceImpl.h"
    40 #endif /* VBOX_WITH_RESOURCE_USAGE_API */
    41 
    42 // generated header
    43 #include "SchemaDefs.h"
    44 
    45 #include <VBox/types.h>
    46 
    47 #include <iprt/file.h>
    48 #include <iprt/thread.h>
    49 #include <iprt/time.h>
    50 
    51 #include <list>
    52 
    53 // defines
    54 ////////////////////////////////////////////////////////////////////////////////
    55 
    56 // helper declarations
    57 ////////////////////////////////////////////////////////////////////////////////
    58 
    59 class Progress;
    60 class Keyboard;
    61 class Mouse;
    62 class Display;
    63 class MachineDebugger;
    64 class USBController;
    65 class Snapshot;
    66 class SharedFolder;
    67 class HostUSBDevice;
    68 class StorageController;
    69 
    70 class SessionMachine;
    71 
    72 namespace settings
    73 {
    74     class MachineConfigFile;
    75     struct Snapshot;
    76     struct Hardware;
    77     struct Storage;
    78     struct StorageController;
    79     struct MachineRegistryEntry;
    80 }
    81 
    82 // Machine class
    83 ////////////////////////////////////////////////////////////////////////////////
    84 
    85 class ATL_NO_VTABLE Machine :
    86     public VirtualBoxBaseWithChildrenNEXT,
    87     public VirtualBoxSupportErrorInfoImpl<Machine, IMachine>,
    88     public VirtualBoxSupportTranslation<Machine>,
    89     VBOX_SCRIPTABLE_IMPL(IMachine)
    90 {
    91     Q_OBJECT
    92 
    93 public:
    94 
    95     enum InitMode { Init_New, Init_Import, Init_Registered };
    96 
    97     /**
    98      * Internal machine data.
    99      *
    100      * Only one instance of this data exists per every machine -- it is shared
    101      * by the Machine, SessionMachine and all SnapshotMachine instances
    102      * associated with the given machine using the util::Shareable template
    103      * through the mData variable.
    104      *
    105      * @note |const| members are persistent during lifetime so can be
    106      * accessed without locking.
    107      *
    108      * @note There is no need to lock anything inside init() or uninit()
    109      * methods, because they are always serialized (see AutoCaller).
    110      */
    111     struct Data
    112     {
    113         /**
    114          * Data structure to hold information about sessions opened for the
    115          * given machine.
    116          */
    117         struct Session
    118         {
    119             /** Control of the direct session opened by openSession() */
    120             ComPtr<IInternalSessionControl> mDirectControl;
    121 
    122             typedef std::list<ComPtr<IInternalSessionControl> > RemoteControlList;
    123 
    124             /** list of controls of all opened remote sessions */
    125             RemoteControlList mRemoteControls;
    126 
    127             /** openRemoteSession() and OnSessionEnd() progress indicator */
    128             ComObjPtr<Progress> mProgress;
    129 
    130             /**
    131              * PID of the session object that must be passed to openSession() to
    132              * finalize the openRemoteSession() request (i.e., PID of the
    133              * process created by openRemoteSession())
    134              */
    135             RTPROCESS mPid;
    136 
    137             /** Current session state */
    138             SessionState_T mState;
    139 
    140             /** Session type string (for indirect sessions) */
    141             Bstr mType;
    142 
    143             /** Session machine object */
    144             ComObjPtr<SessionMachine> mMachine;
    145 
    146             /**
    147              * Successfully locked media list. The 2nd value in the pair is true
    148              * if the medium is locked for writing and false if locked for
    149              * reading.
    150              */
    151             typedef std::list<std::pair<ComPtr<IMedium>, bool > > LockedMedia;
    152             LockedMedia mLockedMedia;
    153         };
    154 
    155         Data();
    156         ~Data();
    157 
    158         const Guid mUuid;
    159         BOOL mRegistered;
    160         InitMode mInitMode;
    161 
    162         /** Flag indicating that the config file is read-only. */
    163         BOOL mConfigFileReadonly;
    164         Utf8Str m_strConfigFile;
    165         Utf8Str m_strConfigFileFull;
    166 
    167         // machine settings XML file
    168         settings::MachineConfigFile *m_pMachineConfigFile;
    169 
    170         BOOL mAccessible;
    171         com::ErrorInfo mAccessError;
    172 
    173         MachineState_T mMachineState;
    174         RTTIMESPEC mLastStateChange;
    175 
    176         /* Note: These are guarded by VirtualBoxBase::stateLockHandle() */
    177         uint32_t mMachineStateDeps;
    178         RTSEMEVENTMULTI mMachineStateDepsSem;
    179         uint32_t mMachineStateChangePending;
    180 
    181         BOOL mCurrentStateModified;
    182 
    183         RTFILE mHandleCfgFile;
    184 
    185         Session mSession;
    186 
    187         ComObjPtr<Snapshot> mFirstSnapshot;
    188         ComObjPtr<Snapshot> mCurrentSnapshot;
    189     };
    190 
    191     /**
    192      *  Saved state data.
    193      *
    194      *  It's actually only the state file path string, but it needs to be
    195      *  separate from Data, because Machine and SessionMachine instances
    196      *  share it, while SnapshotMachine does not.
    197      *
    198      *  The data variable is |mSSData|.
    199      */
    200     struct SSData
    201     {
    202         Utf8Str mStateFilePath;
    203     };
    204 
    205     /**
    206      *  User changeable machine data.
    207      *
    208      *  This data is common for all machine snapshots, i.e. it is shared
    209      *  by all SnapshotMachine instances associated with the given machine
    210      *  using the util::Backupable template through the |mUserData| variable.
    211      *
    212      *  SessionMachine instances can alter this data and discard changes.
    213      *
    214      *  @note There is no need to lock anything inside init() or uninit()
    215      *  methods, because they are always serialized (see AutoCaller).
    216      */
    217     struct UserData
    218     {
    219         UserData();
    220         ~UserData();
    221 
    222         bool operator==(const UserData &that) const
    223         {
    224             return this == &that
    225                 || (   mName                 == that.mName
    226                     && mNameSync             == that.mNameSync
    227                     && mDescription          == that.mDescription
    228                     && mOSTypeId             == that.mOSTypeId
    229                     && mSnapshotFolderFull   == that.mSnapshotFolderFull
    230                     && mTeleporterEnabled    == that.mTeleporterEnabled
    231                     && mTeleporterPort       == that.mTeleporterPort
    232                     && mTeleporterAddress    == that.mTeleporterAddress
    233                     && mTeleporterPassword   == that.mTeleporterPassword
    234                     && mRTCUseUTC            == that.mRTCUseUTC);
    235         }
    236 
    237         Bstr    mName;
    238         BOOL    mNameSync;
    239         Bstr    mDescription;
    240         Bstr    mOSTypeId;
    241         Bstr    mSnapshotFolder;
    242         Bstr    mSnapshotFolderFull;
    243         BOOL    mTeleporterEnabled;
    244         ULONG   mTeleporterPort;
    245         Bstr    mTeleporterAddress;
    246         Bstr    mTeleporterPassword;
    247         BOOL    mRTCUseUTC;
    248     };
    249 
    250     /**
    251      *  Hardware data.
    252      *
    253      *  This data is unique for a machine and for every machine snapshot.
    254      *  Stored using the util::Backupable template in the |mHWData| variable.
    255      *
    256      *  SessionMachine instances can alter this data and discard changes.
    257      */
    258     struct HWData
    259     {
    260         /**
    261          * Data structure to hold information about a guest property.
    262          */
    263         struct GuestProperty {
    264             /** Property name */
    265             Utf8Str strName;
    266             /** Property value */
    267             Utf8Str strValue;
    268             /** Property timestamp */
    269             ULONG64 mTimestamp;
    270             /** Property flags */
    271             ULONG mFlags;
    272         };
    273 
    274         HWData();
    275         ~HWData();
    276 
    277         bool operator==(const HWData &that) const;
    278 
    279         Bstr           mHWVersion;
    280         Guid           mHardwareUUID;   /**< If Null, use mData.mUuid. */
    281         ULONG          mMemorySize;
    282         ULONG          mMemoryBalloonSize;
    283         ULONG          mStatisticsUpdateInterval;
    284         ULONG          mVRAMSize;
    285         ULONG          mMonitorCount;
    286         BOOL           mHWVirtExEnabled;
    287         BOOL           mHWVirtExExclusive;
    288         BOOL           mHWVirtExNestedPagingEnabled;
    289         BOOL           mHWVirtExVPIDEnabled;
    290         BOOL           mAccelerate2DVideoEnabled;
    291         BOOL           mPAEEnabled;
    292         BOOL           mSyntheticCpu;
    293         ULONG          mCPUCount;
    294         BOOL           mCPUHotPlugEnabled;
    295         BOOL           mAccelerate3DEnabled;
    296 
    297         BOOL           mCPUAttached[SchemaDefs::MaxCPUCount];
    298 
    299         settings::CpuIdLeaf mCpuIdStdLeafs[10];
    300         settings::CpuIdLeaf mCpuIdExtLeafs[10];
    301 
    302         DeviceType_T   mBootOrder[SchemaDefs::MaxBootPosition];
    303 
    304         typedef std::list< ComObjPtr<SharedFolder> > SharedFolderList;
    305         SharedFolderList mSharedFolders;
    306 
    307         ClipboardMode_T mClipboardMode;
    308 
    309         typedef std::list<GuestProperty> GuestPropertyList;
    310         GuestPropertyList mGuestProperties;
    311         BOOL           mPropertyServiceActive;
    312         Utf8Str        mGuestPropertyNotificationPatterns;
    313 
    314         FirmwareType_T mFirmwareType;
    315     };
    316 
    317     /**
    318      *  Hard disk and other media data.
    319      *
    320      *  The usage policy is the same as for HWData, but a separate structure
    321      *  is necessary because hard disk data requires different procedures when
    322      *  taking or discarding snapshots, etc.
    323      *
    324      *  The data variable is |mMediaData|.
    325      */
    326     struct MediaData
    327     {
    328         MediaData();
    329         ~MediaData();
    330 
    331         bool operator==(const MediaData &that) const;
    332 
    333         typedef std::list< ComObjPtr<MediumAttachment> > AttachmentList;
    334         AttachmentList mAttachments;
    335     };
    336 
    337     enum StateDependency
    338     {
    339         AnyStateDep = 0, MutableStateDep, MutableOrSavedStateDep
    340     };
    34126
    34227    /**
     
    36651     *  @param taDepType    Dependecy type to manage.
    36752     */
    368     template <StateDependency taDepType = AnyStateDep>
     53    template <Machine::StateDependency taDepType = Machine::AnyStateDep>
    36954    class AutoStateDependency
    37055    {
     
    443128     *  result code to the upper level.
    444129     */
    445     typedef AutoStateDependency<AnyStateDep> AutoAnyStateDependency;
     130    typedef AutoStateDependency<Machine::AnyStateDep> AutoAnyStateDependency;
    446131
    447132    /**
     
    460145     *  provide data protection and consistency.
    461146     */
    462     typedef AutoStateDependency<MutableStateDep> AutoMutableStateDependency;
     147    typedef AutoStateDependency<Machine::MutableStateDep> AutoMutableStateDependency;
    463148
    464149    /**
     
    476161     *  children objects that may also operate on Saved machines.
    477162     */
    478     typedef AutoStateDependency<MutableOrSavedStateDep> AutoMutableOrSavedStateDependency;
     163    typedef AutoStateDependency<Machine::MutableOrSavedStateDep> AutoMutableOrSavedStateDependency;
    479164
    480 
    481     VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT(Machine)
    482 
    483     DECLARE_NOT_AGGREGATABLE(Machine)
    484 
    485     DECLARE_PROTECT_FINAL_CONSTRUCT()
    486 
    487     BEGIN_COM_MAP(Machine)
    488         COM_INTERFACE_ENTRY(ISupportErrorInfo)
    489         COM_INTERFACE_ENTRY(IMachine)
    490         COM_INTERFACE_ENTRY(IDispatch)
    491     END_COM_MAP()
    492 
    493     DECLARE_EMPTY_CTOR_DTOR(Machine)
    494 
    495     HRESULT FinalConstruct();
    496     void FinalRelease();
    497 
    498     // public initializer/uninitializer for internal purposes only
    499     HRESULT init(VirtualBox *aParent,
    500                  const Utf8Str &strConfigFile,
    501                  InitMode aMode,
    502                  CBSTR aName = NULL,
    503                  GuestOSType *aOsType = NULL,
    504                  BOOL aNameSync = TRUE,
    505                  const Guid *aId = NULL);
    506     void uninit();
    507 
    508 protected:
    509     HRESULT initDataAndChildObjects();
    510     void uninitDataAndChildObjects();
    511 
    512 public:
    513     // IMachine properties
    514     STDMETHOD(COMGETTER(Parent))(IVirtualBox **aParent);
    515     STDMETHOD(COMGETTER(Accessible))(BOOL *aAccessible);
    516     STDMETHOD(COMGETTER(AccessError))(IVirtualBoxErrorInfo **aAccessError);
    517     STDMETHOD(COMGETTER(Name))(BSTR *aName);
    518     STDMETHOD(COMSETTER(Name))(IN_BSTR aName);
    519     STDMETHOD(COMGETTER(Description))(BSTR *aDescription);
    520     STDMETHOD(COMSETTER(Description))(IN_BSTR aDescription);
    521     STDMETHOD(COMGETTER(Id))(BSTR *aId);
    522     STDMETHOD(COMGETTER(OSTypeId))(BSTR *aOSTypeId);
    523     STDMETHOD(COMSETTER(OSTypeId))(IN_BSTR aOSTypeId);
    524     STDMETHOD(COMGETTER(HardwareVersion))(BSTR *aVersion);
    525     STDMETHOD(COMSETTER(HardwareVersion))(IN_BSTR aVersion);
    526     STDMETHOD(COMGETTER(HardwareUUID))(BSTR *aUUID);
    527     STDMETHOD(COMSETTER(HardwareUUID))(IN_BSTR aUUID);
    528     STDMETHOD(COMGETTER(MemorySize))(ULONG *memorySize);
    529     STDMETHOD(COMSETTER(MemorySize))(ULONG memorySize);
    530     STDMETHOD(COMGETTER(CPUCount))(ULONG *cpuCount);
    531     STDMETHOD(COMSETTER(CPUCount))(ULONG cpuCount);
    532     STDMETHOD(COMGETTER(CPUHotPlugEnabled))(BOOL *enabled);
    533     STDMETHOD(COMSETTER(CPUHotPlugEnabled))(BOOL enabled);
    534     STDMETHOD(COMGETTER(MemoryBalloonSize))(ULONG *memoryBalloonSize);
    535     STDMETHOD(COMSETTER(MemoryBalloonSize))(ULONG memoryBalloonSize);
    536     STDMETHOD(COMGETTER(StatisticsUpdateInterval))(ULONG *statisticsUpdateInterval);
    537     STDMETHOD(COMSETTER(StatisticsUpdateInterval))(ULONG statisticsUpdateInterval);
    538     STDMETHOD(COMGETTER(VRAMSize))(ULONG *memorySize);
    539     STDMETHOD(COMSETTER(VRAMSize))(ULONG memorySize);
    540     STDMETHOD(COMGETTER(MonitorCount))(ULONG *monitorCount);
    541     STDMETHOD(COMSETTER(MonitorCount))(ULONG monitorCount);
    542     STDMETHOD(COMGETTER(Accelerate3DEnabled))(BOOL *enabled);
    543     STDMETHOD(COMSETTER(Accelerate3DEnabled))(BOOL enabled);
    544     STDMETHOD(COMGETTER(Accelerate2DVideoEnabled))(BOOL *enabled);
    545     STDMETHOD(COMSETTER(Accelerate2DVideoEnabled))(BOOL enabled);
    546     STDMETHOD(COMGETTER(BIOSSettings))(IBIOSSettings **biosSettings);
    547     STDMETHOD(COMGETTER(SnapshotFolder))(BSTR *aSavedStateFolder);
    548     STDMETHOD(COMSETTER(SnapshotFolder))(IN_BSTR aSavedStateFolder);
    549     STDMETHOD(COMGETTER(MediumAttachments))(ComSafeArrayOut(IMediumAttachment *, aAttachments));
    550     STDMETHOD(COMGETTER(VRDPServer))(IVRDPServer **vrdpServer);
    551     STDMETHOD(COMGETTER(AudioAdapter))(IAudioAdapter **audioAdapter);
    552     STDMETHOD(COMGETTER(USBController))(IUSBController * *aUSBController);
    553     STDMETHOD(COMGETTER(SettingsFilePath))(BSTR *aFilePath);
    554     STDMETHOD(COMGETTER(SettingsModified))(BOOL *aModified);
    555     STDMETHOD(COMGETTER(SessionState))(SessionState_T *aSessionState);
    556     STDMETHOD(COMGETTER(SessionType))(BSTR *aSessionType);
    557     STDMETHOD(COMGETTER(SessionPid))(ULONG *aSessionPid);
    558     STDMETHOD(COMGETTER(State))(MachineState_T *machineState);
    559     STDMETHOD(COMGETTER(LastStateChange))(LONG64 *aLastStateChange);
    560     STDMETHOD(COMGETTER(StateFilePath))(BSTR *aStateFilePath);
    561     STDMETHOD(COMGETTER(LogFolder))(BSTR *aLogFolder);
    562     STDMETHOD(COMGETTER(CurrentSnapshot))(ISnapshot **aCurrentSnapshot);
    563     STDMETHOD(COMGETTER(SnapshotCount))(ULONG *aSnapshotCount);
    564     STDMETHOD(COMGETTER(CurrentStateModified))(BOOL *aCurrentStateModified);
    565     STDMETHOD(COMGETTER(SharedFolders))(ComSafeArrayOut(ISharedFolder *, aSharedFolders));
    566     STDMETHOD(COMGETTER(ClipboardMode))(ClipboardMode_T *aClipboardMode);
    567     STDMETHOD(COMSETTER(ClipboardMode))(ClipboardMode_T aClipboardMode);
    568     STDMETHOD(COMGETTER(GuestPropertyNotificationPatterns))(BSTR *aPattern);
    569     STDMETHOD(COMSETTER(GuestPropertyNotificationPatterns))(IN_BSTR aPattern);
    570     STDMETHOD(COMGETTER(StorageControllers))(ComSafeArrayOut(IStorageController *, aStorageControllers));
    571     STDMETHOD(COMGETTER(TeleporterEnabled))(BOOL *aEnabled);
    572     STDMETHOD(COMSETTER(TeleporterEnabled))(BOOL aEnabled);
    573     STDMETHOD(COMGETTER(TeleporterPort))(ULONG *aPort);
    574     STDMETHOD(COMSETTER(TeleporterPort))(ULONG aPort);
    575     STDMETHOD(COMGETTER(TeleporterAddress))(BSTR *aAddress);
    576     STDMETHOD(COMSETTER(TeleporterAddress))(IN_BSTR aAddress);
    577     STDMETHOD(COMGETTER(TeleporterPassword))(BSTR *aPassword);
    578     STDMETHOD(COMSETTER(TeleporterPassword))(IN_BSTR aPassword);
    579     STDMETHOD(COMGETTER(RTCUseUTC))(BOOL *aEnabled);
    580     STDMETHOD(COMSETTER(RTCUseUTC))(BOOL aEnabled);
    581 
    582     // IMachine methods
    583     STDMETHOD(SetBootOrder)(ULONG aPosition, DeviceType_T aDevice);
    584     STDMETHOD(GetBootOrder)(ULONG aPosition, DeviceType_T *aDevice);
    585     STDMETHOD(AttachDevice)(IN_BSTR aControllerName, LONG aControllerPort,
    586                             LONG aDevice, DeviceType_T aType, IN_BSTR aId);
    587     STDMETHOD(DetachDevice)(IN_BSTR aControllerName, LONG aControllerPort, LONG aDevice);
    588     STDMETHOD(PassthroughDevice)(IN_BSTR aControllerName, LONG aControllerPort, LONG aDevice, BOOL aPassthrough);
    589     STDMETHOD(MountMedium)(IN_BSTR aControllerName, LONG aControllerPort,
    590                            LONG aDevice, IN_BSTR aId, BOOL aForce);
    591     STDMETHOD(GetMedium)(IN_BSTR aControllerName, LONG aControllerPort, LONG aDevice,
    592                          IMedium **aMedium);
    593     STDMETHOD(GetSerialPort)(ULONG slot, ISerialPort **port);
    594     STDMETHOD(GetParallelPort)(ULONG slot, IParallelPort **port);
    595     STDMETHOD(GetNetworkAdapter)(ULONG slot, INetworkAdapter **adapter);
    596     STDMETHOD(GetExtraDataKeys)(ComSafeArrayOut(BSTR, aKeys));
    597     STDMETHOD(GetExtraData)(IN_BSTR aKey, BSTR *aValue);
    598     STDMETHOD(SetExtraData)(IN_BSTR aKey, IN_BSTR aValue);
    599     STDMETHOD(GetCpuProperty)(CpuPropertyType_T property, BOOL *aVal);
    600     STDMETHOD(SetCpuProperty)(CpuPropertyType_T property, BOOL aVal);
    601     STDMETHOD(GetCpuIdLeaf)(ULONG id, ULONG *aValEax, ULONG *aValEbx, ULONG *aValEcx, ULONG *aValEdx);
    602     STDMETHOD(SetCpuIdLeaf)(ULONG id, ULONG aValEax, ULONG aValEbx, ULONG aValEcx, ULONG aValEdx);
    603     STDMETHOD(RemoveCpuIdLeaf)(ULONG id);
    604     STDMETHOD(RemoveAllCpuIdLeafs)();
    605     STDMETHOD(GetHWVirtExProperty)(HWVirtExPropertyType_T property, BOOL *aVal);
    606     STDMETHOD(SetHWVirtExProperty)(HWVirtExPropertyType_T property, BOOL aVal);
    607     STDMETHOD(SaveSettings)();
    608     STDMETHOD(DiscardSettings)();
    609     STDMETHOD(DeleteSettings)();
    610     STDMETHOD(Export)(IAppliance *aAppliance, IVirtualSystemDescription **aDescription);
    611     STDMETHOD(GetSnapshot)(IN_BSTR aId, ISnapshot **aSnapshot);
    612     STDMETHOD(FindSnapshot)(IN_BSTR aName, ISnapshot **aSnapshot);
    613     STDMETHOD(SetCurrentSnapshot)(IN_BSTR aId);
    614     STDMETHOD(CreateSharedFolder)(IN_BSTR aName, IN_BSTR aHostPath, BOOL aWritable);
    615     STDMETHOD(RemoveSharedFolder)(IN_BSTR aName);
    616     STDMETHOD(CanShowConsoleWindow)(BOOL *aCanShow);
    617     STDMETHOD(ShowConsoleWindow)(ULONG64 *aWinId);
    618     STDMETHOD(GetGuestProperty)(IN_BSTR aName, BSTR *aValue, ULONG64 *aTimestamp, BSTR *aFlags);
    619     STDMETHOD(GetGuestPropertyValue)(IN_BSTR aName, BSTR *aValue);
    620     STDMETHOD(GetGuestPropertyTimestamp)(IN_BSTR aName, ULONG64 *aTimestamp);
    621     STDMETHOD(SetGuestProperty)(IN_BSTR aName, IN_BSTR aValue, IN_BSTR aFlags);
    622     STDMETHOD(SetGuestPropertyValue)(IN_BSTR aName, IN_BSTR aValue);
    623     STDMETHOD(EnumerateGuestProperties)(IN_BSTR aPattern, ComSafeArrayOut(BSTR, aNames), ComSafeArrayOut(BSTR, aValues), ComSafeArrayOut(ULONG64, aTimestamps), ComSafeArrayOut(BSTR, aFlags));
    624     STDMETHOD(GetMediumAttachmentsOfController)(IN_BSTR aName, ComSafeArrayOut(IMediumAttachment *, aAttachments));
    625     STDMETHOD(GetMediumAttachment)(IN_BSTR aConstrollerName, LONG aControllerPort, LONG aDevice, IMediumAttachment **aAttachment);
    626     STDMETHOD(AddStorageController)(IN_BSTR aName, StorageBus_T aConnectionType, IStorageController **controller);
    627     STDMETHOD(RemoveStorageController(IN_BSTR aName));
    628     STDMETHOD(GetStorageControllerByName(IN_BSTR aName, IStorageController **storageController));
    629     STDMETHOD(GetStorageControllerByInstance(ULONG aInstance, IStorageController **storageController));
    630     STDMETHOD(COMGETTER(FirmwareType)) (FirmwareType_T *aFirmware);
    631     STDMETHOD(COMSETTER(FirmwareType)) (FirmwareType_T  aFirmware);
    632 
    633     STDMETHOD(QuerySavedThumbnailSize)(ULONG *aSize, ULONG *aWidth, ULONG *aHeight);
    634     STDMETHOD(ReadSavedThumbnailToArray)(BOOL aBGR, ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData));
    635     STDMETHOD(QuerySavedScreenshotPNGSize)(ULONG *aSize, ULONG *aWidth, ULONG *aHeight);
    636     STDMETHOD(ReadSavedScreenshotPNGToArray)(ULONG *aWidth, ULONG *aHeight, ComSafeArrayOut(BYTE, aData));
    637     STDMETHOD(HotPlugCPU(ULONG aCpu));
    638     STDMETHOD(HotUnplugCPU(ULONG aCpu));
    639     STDMETHOD(GetCPUStatus(ULONG aCpu, BOOL *aCpuAttached));
    640 
    641     // public methods only for internal purposes
    642 
    643     /**
    644      * Simple run-time type identification without having to enable C++ RTTI.
    645      * The class IDs are defined in VirtualBoxBase.h.
    646      * @return
    647      */
    648     virtual VBoxClsID getClassID() const
    649     {
    650         return clsidMachine;
    651     }
    652 
    653     /**
    654      * Override of the default locking class to be used for validating lock
    655      * order with the standard member lock handle.
    656      */
    657     virtual VBoxLockingClass getLockingClass() const
    658     {
    659         return LOCKCLASS_MACHINEOBJECT;
    660     }
    661 
    662     /// @todo (dmik) add lock and make non-inlined after revising classes
    663     //  that use it. Note: they should enter Machine lock to keep the returned
    664     //  information valid!
    665     bool isRegistered() { return !!mData->mRegistered; }
    666 
    667     // unsafe inline public methods for internal purposes only (ensure there is
    668     // a caller and a read lock before calling them!)
    669 
    670     /**
    671      * Returns the VirtualBox object this machine belongs to.
    672      *
    673      * @note This method doesn't check this object's readiness. Intended to be
    674      * used by ready Machine children (whose readiness is bound to the parent's
    675      * one) or after doing addCaller() manually.
    676      */
    677     const ComObjPtr<VirtualBox, ComWeakRef>& getVirtualBox() const { return mParent; }
    678 
    679     /**
    680      * Returns this machine ID.
    681      *
    682      * @note This method doesn't check this object's readiness. Intended to be
    683      * used by ready Machine children (whose readiness is bound to the parent's
    684      * one) or after adding a caller manually.
    685      */
    686     const Guid& getId() const { return mData->mUuid; }
    687 
    688     /**
    689      * Returns the snapshot ID this machine represents or an empty UUID if this
    690      * instance is not SnapshotMachine.
    691      *
    692      * @note This method doesn't check this object's readiness. Intended to be
    693      * used by ready Machine children (whose readiness is bound to the parent's
    694      * one) or after adding a caller manually.
    695      */
    696     inline const Guid& getSnapshotId() const;
    697 
    698     /**
    699      * Returns this machine's full settings file path.
    700      *
    701      * @note This method doesn't lock this object or check its readiness.
    702      * Intended to be used only after doing addCaller() manually and locking it
    703      * for reading.
    704      */
    705     const Utf8Str& getSettingsFileFull() const { return mData->m_strConfigFileFull; }
    706 
    707     /**
    708      * Returns this machine name.
    709      *
    710      * @note This method doesn't lock this object or check its readiness.
    711      * Intended to be used only after doing addCaller() manually and locking it
    712      * for reading.
    713      */
    714     const Bstr& getName() const { return mUserData->mName; }
    715 
    716     // callback handlers
    717     virtual HRESULT onNetworkAdapterChange(INetworkAdapter * /* networkAdapter */, BOOL /* changeAdapter */) { return S_OK; }
    718     virtual HRESULT onSerialPortChange(ISerialPort * /* serialPort */) { return S_OK; }
    719     virtual HRESULT onParallelPortChange(IParallelPort * /* parallelPort */) { return S_OK; }
    720     virtual HRESULT onVRDPServerChange() { return S_OK; }
    721     virtual HRESULT onUSBControllerChange() { return S_OK; }
    722     virtual HRESULT onStorageControllerChange() { return S_OK; }
    723     virtual HRESULT onCPUChange(ULONG /* aCPU */, BOOL /* aRemove */) { return S_OK; }
    724     virtual HRESULT onMediumChange(IMediumAttachment * /* mediumAttachment */, BOOL /* force */) { return S_OK; }
    725     virtual HRESULT onSharedFolderChange() { return S_OK; }
    726 
    727     HRESULT saveRegistryEntry(settings::MachineRegistryEntry &data);
    728 
    729     int calculateFullPath(const Utf8Str &strPath, Utf8Str &aResult);
    730     void calculateRelativePath(const Utf8Str &strPath, Utf8Str &aResult);
    731 
    732     void getLogFolder(Utf8Str &aLogFolder);
    733 
    734     HRESULT openSession(IInternalSessionControl *aControl);
    735     HRESULT openRemoteSession(IInternalSessionControl *aControl,
    736                               IN_BSTR aType, IN_BSTR aEnvironment,
    737                               Progress *aProgress);
    738     HRESULT openExistingSession(IInternalSessionControl *aControl);
    739 
    740 #if defined(RT_OS_WINDOWS)
    741 
    742     bool isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
    743                        ComPtr<IInternalSessionControl> *aControl = NULL,
    744                        HANDLE *aIPCSem = NULL, bool aAllowClosing = false);
    745     bool isSessionSpawning(RTPROCESS *aPID = NULL);
    746 
    747     bool isSessionOpenOrClosing(ComObjPtr<SessionMachine> &aMachine,
    748                                 ComPtr<IInternalSessionControl> *aControl = NULL,
    749                                 HANDLE *aIPCSem = NULL)
    750     { return isSessionOpen(aMachine, aControl, aIPCSem, true /* aAllowClosing */); }
    751 
    752 #elif defined(RT_OS_OS2)
    753 
    754     bool isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
    755                        ComPtr<IInternalSessionControl> *aControl = NULL,
    756                        HMTX *aIPCSem = NULL, bool aAllowClosing = false);
    757 
    758     bool isSessionSpawning(RTPROCESS *aPID = NULL);
    759 
    760     bool isSessionOpenOrClosing(ComObjPtr<SessionMachine> &aMachine,
    761                                  ComPtr<IInternalSessionControl> *aControl = NULL,
    762                                  HMTX *aIPCSem = NULL)
    763     { return isSessionOpen(aMachine, aControl, aIPCSem, true /* aAllowClosing */); }
    764 
    765 #else
    766 
    767     bool isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
    768                        ComPtr<IInternalSessionControl> *aControl = NULL,
    769                        bool aAllowClosing = false);
    770     bool isSessionSpawning();
    771 
    772     bool isSessionOpenOrClosing(ComObjPtr<SessionMachine> &aMachine,
    773                                 ComPtr<IInternalSessionControl> *aControl = NULL)
    774     { return isSessionOpen(aMachine, aControl, true /* aAllowClosing */); }
    775 
    776 #endif
    777 
    778     bool checkForSpawnFailure();
    779 
    780     HRESULT trySetRegistered(BOOL aRegistered);
    781 
    782     HRESULT getSharedFolder(CBSTR aName,
    783                             ComObjPtr<SharedFolder> &aSharedFolder,
    784                             bool aSetError = false)
    785     {
    786         AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
    787         return findSharedFolder(aName, aSharedFolder, aSetError);
    788     }
    789 
    790     HRESULT addStateDependency(StateDependency aDepType = AnyStateDep,
    791                                MachineState_T *aState = NULL,
    792                                BOOL *aRegistered = NULL);
    793     void releaseStateDependency();
    794 
    795     // for VirtualBoxSupportErrorInfoImpl
    796     static const wchar_t *getComponentName() { return L"Machine"; }
    797 
    798 protected:
    799 
    800     HRESULT registeredInit();
    801 
    802     HRESULT checkStateDependency(StateDependency aDepType);
    803 
    804     inline Machine *getMachine();
    805 
    806     void ensureNoStateDependencies();
    807 
    808     virtual HRESULT setMachineState(MachineState_T aMachineState);
    809 
    810     HRESULT findSharedFolder(CBSTR aName,
    811                              ComObjPtr<SharedFolder> &aSharedFolder,
    812                              bool aSetError = false);
    813 
    814     HRESULT loadSettings(bool aRegistered);
    815     HRESULT loadSnapshot(const settings::Snapshot &data,
    816                          const Guid &aCurSnapshotId,
    817                          Snapshot *aParentSnapshot);
    818     HRESULT loadHardware(const settings::Hardware &data);
    819     HRESULT loadStorageControllers(const settings::Storage &data,
    820                                    bool aRegistered,
    821                                    const Guid *aSnapshotId = NULL);
    822     HRESULT loadStorageDevices(StorageController *aStorageController,
    823                                const settings::StorageController &data,
    824                                bool aRegistered,
    825                                const Guid *aSnapshotId = NULL);
    826 
    827     HRESULT findSnapshot(const Guid &aId, ComObjPtr<Snapshot> &aSnapshot,
    828                          bool aSetError = false);
    829     HRESULT findSnapshot(IN_BSTR aName, ComObjPtr<Snapshot> &aSnapshot,
    830                          bool aSetError = false);
    831 
    832     HRESULT getStorageControllerByName(const Utf8Str &aName,
    833                                        ComObjPtr<StorageController> &aStorageController,
    834                                        bool aSetError = false);
    835 
    836     HRESULT getMediumAttachmentsOfController(CBSTR aName,
    837                                              MediaData::AttachmentList &aAttachments);
    838 
    839     enum
    840     {
    841         /* flags for #saveSettings() */
    842         SaveS_ResetCurStateModified = 0x01,
    843         SaveS_InformCallbacksAnyway = 0x02,
    844         /* flags for #saveSnapshotSettings() */
    845         SaveSS_CurStateModified = 0x40,
    846         SaveSS_CurrentId = 0x80,
    847         /* flags for #saveStateSettings() */
    848         SaveSTS_CurStateModified = 0x20,
    849         SaveSTS_StateFilePath = 0x40,
    850         SaveSTS_StateTimeStamp = 0x80,
    851     };
    852 
    853     HRESULT prepareSaveSettings(bool &aRenamed, bool &aNew);
    854     HRESULT saveSettings(int aFlags = 0);
    855 
    856     HRESULT saveAllSnapshots();
    857 
    858     HRESULT saveHardware(settings::Hardware &data);
    859     HRESULT saveStorageControllers(settings::Storage &data);
    860     HRESULT saveStorageDevices(ComObjPtr<StorageController> aStorageController,
    861                                settings::StorageController &data);
    862 
    863     HRESULT saveStateSettings(int aFlags);
    864 
    865     HRESULT createImplicitDiffs(const Bstr &aFolder,
    866                                 IProgress *aProgress,
    867                                 ULONG aWeight,
    868                                 bool aOnline,
    869                                 bool *pfNeedsSaveSettings);
    870     HRESULT deleteImplicitDiffs(bool *pfNeedsSaveSettings);
    871 
    872     MediumAttachment* findAttachment(const MediaData::AttachmentList &ll,
    873                                      IN_BSTR aControllerName,
    874                                      LONG aControllerPort,
    875                                      LONG aDevice);
    876     MediumAttachment* findAttachment(const MediaData::AttachmentList &ll,
    877                                      ComObjPtr<Medium> pMedium);
    878     MediumAttachment* findAttachment(const MediaData::AttachmentList &ll,
    879                                      Guid &id);
    880 
    881     void commitMedia(bool aOnline = false);
    882     void rollbackMedia();
    883 
    884     bool isInOwnDir(Utf8Str *aSettingsDir = NULL);
    885 
    886     bool isModified();
    887     bool isReallyModified(bool aIgnoreUserData = false);
    888     void rollback(bool aNotify);
    889     void commit();
    890     void copyFrom(Machine *aThat);
    891 
    892 #ifdef VBOX_WITH_RESOURCE_USAGE_API
    893     void registerMetrics(PerformanceCollector *aCollector, Machine *aMachine, RTPROCESS pid);
    894     void unregisterMetrics(PerformanceCollector *aCollector, Machine *aMachine);
    895 #endif /* VBOX_WITH_RESOURCE_USAGE_API */
    896 
    897     const ComObjPtr<Machine, ComWeakRef> mPeer;
    898 
    899     const ComObjPtr<VirtualBox, ComWeakRef> mParent;
    900 
    901     Shareable<Data> mData;
    902     Shareable<SSData> mSSData;
    903 
    904     Backupable<UserData> mUserData;
    905     Backupable<HWData> mHWData;
    906     Backupable<MediaData> mMediaData;
    907 
    908     // the following fields need special backup/rollback/commit handling,
    909     // so they cannot be a part of HWData
    910 
    911     const ComObjPtr<VRDPServer>     mVRDPServer;
    912     const ComObjPtr<SerialPort>     mSerialPorts[SchemaDefs::SerialPortCount];
    913     const ComObjPtr<ParallelPort>   mParallelPorts[SchemaDefs::ParallelPortCount];
    914     const ComObjPtr<AudioAdapter>   mAudioAdapter;
    915     const ComObjPtr<USBController>  mUSBController;
    916     const ComObjPtr<BIOSSettings>   mBIOSSettings;
    917     const ComObjPtr<NetworkAdapter> mNetworkAdapters[SchemaDefs::NetworkAdapterCount];
    918 
    919     typedef std::list< ComObjPtr<StorageController> > StorageControllerList;
    920     Backupable<StorageControllerList> mStorageControllers;
    921 
    922     friend class SessionMachine;
    923     friend class SnapshotMachine;
    924 };
    925 
    926 // SessionMachine class
    927 ////////////////////////////////////////////////////////////////////////////////
    928 
    929 /**
    930  *  @note Notes on locking objects of this class:
    931  *  SessionMachine shares some data with the primary Machine instance (pointed
    932  *  to by the |mPeer| member). In order to provide data consistency it also
    933  *  shares its lock handle. This means that whenever you lock a SessionMachine
    934  *  instance using Auto[Reader]Lock or AutoMultiLock, the corresponding Machine
    935  *  instance is also locked in the same lock mode. Keep it in mind.
    936  */
    937 class ATL_NO_VTABLE SessionMachine :
    938     public VirtualBoxSupportTranslation<SessionMachine>,
    939     public Machine,
    940     VBOX_SCRIPTABLE_IMPL(IInternalMachineControl)
    941 {
    942 public:
    943 
    944     VIRTUALBOXSUPPORTTRANSLATION_OVERRIDE(SessionMachine)
    945 
    946     DECLARE_NOT_AGGREGATABLE(SessionMachine)
    947 
    948     DECLARE_PROTECT_FINAL_CONSTRUCT()
    949 
    950     BEGIN_COM_MAP(SessionMachine)
    951         COM_INTERFACE_ENTRY2(IDispatch, IMachine)
    952         COM_INTERFACE_ENTRY(ISupportErrorInfo)
    953         COM_INTERFACE_ENTRY(IMachine)
    954         COM_INTERFACE_ENTRY(IInternalMachineControl)
    955     END_COM_MAP()
    956 
    957     DECLARE_EMPTY_CTOR_DTOR(SessionMachine)
    958 
    959     HRESULT FinalConstruct();
    960     void FinalRelease();
    961 
    962     // public initializer/uninitializer for internal purposes only
    963     HRESULT init(Machine *aMachine);
    964     void uninit() { uninit(Uninit::Unexpected); }
    965 
    966     // util::Lockable interface
    967     RWLockHandle *lockHandle() const;
    968 
    969     // IInternalMachineControl methods
    970     STDMETHOD(SetRemoveSavedState)(BOOL aRemove);
    971     STDMETHOD(UpdateState)(MachineState_T machineState);
    972     STDMETHOD(GetIPCId)(BSTR *id);
    973     STDMETHOD(RunUSBDeviceFilters)(IUSBDevice *aUSBDevice, BOOL *aMatched, ULONG *aMaskedIfs);
    974     STDMETHOD(CaptureUSBDevice)(IN_BSTR aId);
    975     STDMETHOD(DetachUSBDevice)(IN_BSTR aId, BOOL aDone);
    976     STDMETHOD(AutoCaptureUSBDevices)();
    977     STDMETHOD(DetachAllUSBDevices)(BOOL aDone);
    978     STDMETHOD(OnSessionEnd)(ISession *aSession, IProgress **aProgress);
    979     STDMETHOD(BeginSavingState)(IProgress *aProgress, BSTR *aStateFilePath);
    980     STDMETHOD(EndSavingState)(BOOL aSuccess);
    981     STDMETHOD(AdoptSavedState)(IN_BSTR aSavedStateFile);
    982     STDMETHOD(BeginTakingSnapshot)(IConsole *aInitiator,
    983                                    IN_BSTR aName,
    984                                    IN_BSTR aDescription,
    985                                    IProgress *aConsoleProgress,
    986                                    BOOL fTakingSnapshotOnline,
    987                                    BSTR *aStateFilePath);
    988     STDMETHOD(EndTakingSnapshot)(BOOL aSuccess);
    989     STDMETHOD(DeleteSnapshot)(IConsole *aInitiator, IN_BSTR aId,
    990                               MachineState_T *aMachineState, IProgress **aProgress);
    991     STDMETHOD(RestoreSnapshot)(IConsole *aInitiator,
    992                                ISnapshot *aSnapshot,
    993                                MachineState_T *aMachineState,
    994                                IProgress **aProgress);
    995     STDMETHOD(PullGuestProperties)(ComSafeArrayOut(BSTR, aNames), ComSafeArrayOut(BSTR, aValues),
    996               ComSafeArrayOut(ULONG64, aTimestamps), ComSafeArrayOut(BSTR, aFlags));
    997     STDMETHOD(PushGuestProperties)(ComSafeArrayIn(IN_BSTR, aNames), ComSafeArrayIn(IN_BSTR, aValues),
    998               ComSafeArrayIn(ULONG64, aTimestamps), ComSafeArrayIn(IN_BSTR, aFlags));
    999     STDMETHOD(PushGuestProperty)(IN_BSTR aName, IN_BSTR aValue,
    1000                                   ULONG64 aTimestamp, IN_BSTR aFlags);
    1001     STDMETHOD(LockMedia)()   { return lockMedia(); }
    1002     STDMETHOD(UnlockMedia)() { unlockMedia(); return S_OK; }
    1003 
    1004     // public methods only for internal purposes
    1005 
    1006     /**
    1007      * Simple run-time type identification without having to enable C++ RTTI.
    1008      * The class IDs are defined in VirtualBoxBase.h.
    1009      * @return
    1010      */
    1011     virtual VBoxClsID getClassID() const
    1012     {
    1013         return clsidSessionMachine;
    1014     }
    1015 
    1016     bool checkForDeath();
    1017 
    1018     HRESULT onNetworkAdapterChange(INetworkAdapter *networkAdapter, BOOL changeAdapter);
    1019     HRESULT onStorageControllerChange();
    1020     HRESULT onMediumChange(IMediumAttachment *aMediumAttachment, BOOL aForce);
    1021     HRESULT onSerialPortChange(ISerialPort *serialPort);
    1022     HRESULT onParallelPortChange(IParallelPort *parallelPort);
    1023     HRESULT onCPUChange(ULONG aCPU, BOOL aRemove);
    1024     HRESULT onVRDPServerChange();
    1025     HRESULT onUSBControllerChange();
    1026     HRESULT onUSBDeviceAttach(IUSBDevice *aDevice,
    1027                               IVirtualBoxErrorInfo *aError,
    1028                               ULONG aMaskedIfs);
    1029     HRESULT onUSBDeviceDetach(IN_BSTR aId,
    1030                               IVirtualBoxErrorInfo *aError);
    1031     HRESULT onSharedFolderChange();
    1032 
    1033     bool hasMatchingUSBFilter(const ComObjPtr<HostUSBDevice> &aDevice, ULONG *aMaskedIfs);
    1034 
    1035 private:
    1036 
    1037     struct SnapshotData
    1038     {
    1039         SnapshotData() : mLastState(MachineState_Null) {}
    1040 
    1041         MachineState_T mLastState;
    1042 
    1043         // used when taking snapshot
    1044         ComObjPtr<Snapshot> mSnapshot;
    1045 
    1046         // used when saving state
    1047         Guid mProgressId;
    1048         Utf8Str mStateFilePath;
    1049     };
    1050 
    1051     struct Uninit
    1052     {
    1053         enum Reason { Unexpected, Abnormal, Normal };
    1054     };
    1055 
    1056     struct SnapshotTask;
    1057     struct DeleteSnapshotTask;
    1058     struct RestoreSnapshotTask;
    1059 
    1060     friend struct DeleteSnapshotTask;
    1061     friend struct RestoreSnapshotTask;
    1062 
    1063     void uninit(Uninit::Reason aReason);
    1064 
    1065     HRESULT endSavingState(BOOL aSuccess);
    1066 
    1067     typedef std::map<ComObjPtr<Machine>, MachineState_T> AffectedMachines;
    1068 
    1069     void deleteSnapshotHandler(DeleteSnapshotTask &aTask);
    1070     void restoreSnapshotHandler(RestoreSnapshotTask &aTask);
    1071 
    1072     HRESULT lockMedia();
    1073     void unlockMedia();
    1074 
    1075     HRESULT setMachineState(MachineState_T aMachineState);
    1076     HRESULT updateMachineStateOnClient();
    1077 
    1078     HRESULT mRemoveSavedState;
    1079 
    1080     SnapshotData mSnapshotData;
    1081 
    1082     /** interprocess semaphore handle for this machine */
    1083 #if defined(RT_OS_WINDOWS)
    1084     HANDLE mIPCSem;
    1085     Bstr mIPCSemName;
    1086     friend bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
    1087                                        ComPtr<IInternalSessionControl> *aControl,
    1088                                        HANDLE *aIPCSem, bool aAllowClosing);
    1089 #elif defined(RT_OS_OS2)
    1090     HMTX mIPCSem;
    1091     Bstr mIPCSemName;
    1092     friend bool Machine::isSessionOpen(ComObjPtr<SessionMachine> &aMachine,
    1093                                        ComPtr<IInternalSessionControl> *aControl,
    1094                                        HMTX *aIPCSem, bool aAllowClosing);
    1095 #elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
    1096     int mIPCSem;
    1097 # ifdef VBOX_WITH_NEW_SYS_V_KEYGEN
    1098     Bstr mIPCKey;
    1099 # endif /*VBOX_WITH_NEW_SYS_V_KEYGEN */
    1100 #else
    1101 # error "Port me!"
    1102 #endif
    1103 
    1104     static DECLCALLBACK(int) taskHandler(RTTHREAD thread, void *pvUser);
    1105 };
    1106 
    1107 // SnapshotMachine class
    1108 ////////////////////////////////////////////////////////////////////////////////
    1109 
    1110 /**
    1111  *  @note Notes on locking objects of this class:
    1112  *  SnapshotMachine shares some data with the primary Machine instance (pointed
    1113  *  to by the |mPeer| member). In order to provide data consistency it also
    1114  *  shares its lock handle. This means that whenever you lock a SessionMachine
    1115  *  instance using Auto[Reader]Lock or AutoMultiLock, the corresponding Machine
    1116  *  instance is also locked in the same lock mode. Keep it in mind.
    1117  */
    1118 class ATL_NO_VTABLE SnapshotMachine :
    1119     public VirtualBoxSupportTranslation<SnapshotMachine>,
    1120     public Machine
    1121 {
    1122 public:
    1123 
    1124     VIRTUALBOXSUPPORTTRANSLATION_OVERRIDE(SnapshotMachine)
    1125 
    1126     DECLARE_NOT_AGGREGATABLE(SnapshotMachine)
    1127 
    1128     DECLARE_PROTECT_FINAL_CONSTRUCT()
    1129 
    1130     BEGIN_COM_MAP(SnapshotMachine)
    1131         COM_INTERFACE_ENTRY2(IDispatch, IMachine)
    1132         COM_INTERFACE_ENTRY(ISupportErrorInfo)
    1133         COM_INTERFACE_ENTRY(IMachine)
    1134     END_COM_MAP()
    1135 
    1136     DECLARE_EMPTY_CTOR_DTOR(SnapshotMachine)
    1137 
    1138     HRESULT FinalConstruct();
    1139     void FinalRelease();
    1140 
    1141     // public initializer/uninitializer for internal purposes only
    1142     HRESULT init(SessionMachine *aSessionMachine,
    1143                  IN_GUID aSnapshotId,
    1144                  const Utf8Str &aStateFilePath);
    1145     HRESULT init(Machine *aMachine,
    1146                  const settings::Hardware &hardware,
    1147                  const settings::Storage &storage,
    1148                  IN_GUID aSnapshotId,
    1149                  const Utf8Str &aStateFilePath);
    1150     void uninit();
    1151 
    1152     // util::Lockable interface
    1153     RWLockHandle *lockHandle() const;
    1154 
    1155     // public methods only for internal purposes
    1156 
    1157     /**
    1158      * Simple run-time type identification without having to enable C++ RTTI.
    1159      * The class IDs are defined in VirtualBoxBase.h.
    1160      * @return
    1161      */
    1162     virtual VBoxClsID getClassID() const
    1163     {
    1164         return clsidSnapshotMachine;
    1165     }
    1166 
    1167     HRESULT onSnapshotChange(Snapshot *aSnapshot);
    1168 
    1169     // unsafe inline public methods for internal purposes only (ensure there is
    1170     // a caller and a read lock before calling them!)
    1171 
    1172     const Guid& getSnapshotId() const { return mSnapshotId; }
    1173 
    1174 private:
    1175 
    1176     Guid mSnapshotId;
    1177 
    1178     friend class Snapshot;
    1179 };
    1180 
    1181 // third party methods that depend on SnapshotMachine definiton
    1182 
    1183 inline const Guid &Machine::getSnapshotId() const
    1184 {
    1185     return getClassID() != clsidSnapshotMachine
    1186                 ? Guid::Empty
    1187                 : static_cast<const SnapshotMachine*>(this)->getSnapshotId();
    1188 }
    1189 
    1190 ////////////////////////////////////////////////////////////////////////////////
    1191 
    1192 /**
    1193  *  Returns a pointer to the Machine object for this machine that acts like a
    1194  *  parent for complex machine data objects such as shared folders, etc.
    1195  *
    1196  *  For primary Machine objects and for SnapshotMachine objects, returns this
    1197  *  object's pointer itself. For SessoinMachine objects, returns the peer
    1198  *  (primary) machine pointer.
    1199  */
    1200 inline Machine *Machine::getMachine()
    1201 {
    1202     if (getClassID() == clsidSessionMachine)
    1203         return mPeer;
    1204     return this;
    1205 }
    1206 
    1207 
    1208 #endif // ____H_MACHINEIMPL
    1209 /* vi: set tabstop=4 shiftwidth=4 expandtab: */
     165#endif // ____H_AUTOSTATEDEP
  • trunk/src/VBox/Main/include/MachineImpl.h

    r26044 r26046  
    9494
    9595    enum InitMode { Init_New, Init_Import, Init_Registered };
     96
     97    enum StateDependency
     98    {
     99        AnyStateDep = 0, MutableStateDep, MutableOrSavedStateDep
     100    };
    96101
    97102    /**
     
    334339        AttachmentList mAttachments;
    335340    };
    336 
    337     enum StateDependency
    338     {
    339         AnyStateDep = 0, MutableStateDep, MutableOrSavedStateDep
    340     };
    341 
    342     /**
    343      *  Helper class that safely manages the machine state dependency by
    344      *  calling Machine::addStateDependency() on construction and
    345      *  Machine::releaseStateDependency() on destruction. Intended for Machine
    346      *  children. The usage pattern is:
    347      *
    348      *  @code
    349      *      AutoCaller autoCaller(this);
    350      *      if (FAILED(autoCaller.rc())) return autoCaller.rc();
    351      *
    352      *      Machine::AutoStateDependency<MutableStateDep> adep(mParent);
    353      *      if (FAILED(stateDep.rc())) return stateDep.rc();
    354      *      ...
    355      *      // code that depends on the particular machine state
    356      *      ...
    357      *  @endcode
    358      *
    359      *  Note that it is more convenient to use the following individual
    360      *  shortcut classes instead of using this template directly:
    361      *  AutoAnyStateDependency, AutoMutableStateDependency and
    362      *  AutoMutableOrSavedStateDependency. The usage pattern is exactly the
    363      *  same as above except that there is no need to specify the template
    364      *  argument because it is already done by the shortcut class.
    365      *
    366      *  @param taDepType    Dependecy type to manage.
    367      */
    368     template <StateDependency taDepType = AnyStateDep>
    369     class AutoStateDependency
    370     {
    371     public:
    372 
    373         AutoStateDependency(Machine *aThat)
    374             : mThat(aThat), mRC(S_OK)
    375             , mMachineState(MachineState_Null)
    376             , mRegistered(FALSE)
    377         {
    378             Assert(aThat);
    379             mRC = aThat->addStateDependency(taDepType, &mMachineState,
    380                                             &mRegistered);
    381         }
    382         ~AutoStateDependency()
    383         {
    384             if (SUCCEEDED(mRC))
    385                 mThat->releaseStateDependency();
    386         }
    387 
    388         /** Decreases the number of dependencies before the instance is
    389          *  destroyed. Note that will reset #rc() to E_FAIL. */
    390         void release()
    391         {
    392             AssertReturnVoid(SUCCEEDED(mRC));
    393             mThat->releaseStateDependency();
    394             mRC = E_FAIL;
    395         }
    396 
    397         /** Restores the number of callers after by #release(). #rc() will be
    398          *  reset to the result of calling addStateDependency() and must be
    399          *  rechecked to ensure the operation succeeded. */
    400         void add()
    401         {
    402             AssertReturnVoid(!SUCCEEDED(mRC));
    403             mRC = mThat->addStateDependency(taDepType, &mMachineState,
    404                                             &mRegistered);
    405         }
    406 
    407         /** Returns the result of Machine::addStateDependency(). */
    408         HRESULT rc() const { return mRC; }
    409 
    410         /** Shortcut to SUCCEEDED(rc()). */
    411         bool isOk() const { return SUCCEEDED(mRC); }
    412 
    413         /** Returns the machine state value as returned by
    414          *  Machine::addStateDependency(). */
    415         MachineState_T machineState() const { return mMachineState; }
    416 
    417         /** Returns the machine state value as returned by
    418          *  Machine::addStateDependency(). */
    419         BOOL machineRegistered() const { return mRegistered; }
    420 
    421     protected:
    422 
    423         Machine *mThat;
    424         HRESULT mRC;
    425         MachineState_T mMachineState;
    426         BOOL mRegistered;
    427 
    428     private:
    429 
    430         DECLARE_CLS_COPY_CTOR_ASSIGN_NOOP(AutoStateDependency)
    431         DECLARE_CLS_NEW_DELETE_NOOP(AutoStateDependency)
    432     };
    433 
    434     /**
    435      *  Shortcut to AutoStateDependency<AnyStateDep>.
    436      *  See AutoStateDependency to get the usage pattern.
    437      *
    438      *  Accepts any machine state and guarantees the state won't change before
    439      *  this object is destroyed. If the machine state cannot be protected (as
    440      *  a result of the state change currently in progress), this instance's
    441      *  #rc() method will indicate a failure, and the caller is not allowed to
    442      *  rely on any particular machine state and should return the failed
    443      *  result code to the upper level.
    444      */
    445     typedef AutoStateDependency<AnyStateDep> AutoAnyStateDependency;
    446 
    447     /**
    448      *  Shortcut to AutoStateDependency<MutableStateDep>.
    449      *  See AutoStateDependency to get the usage pattern.
    450      *
    451      *  Succeeds only if the machine state is in one of the mutable states, and
    452      *  guarantees the given mutable state won't change before this object is
    453      *  destroyed. If the machine is not mutable, this instance's #rc() method
    454      *  will indicate a failure, and the caller is not allowed to rely on any
    455      *  particular machine state and should return the failed result code to
    456      *  the upper level.
    457      *
    458      *  Intended to be used within all setter methods of IMachine
    459      *  children objects (DVDDrive, NetworkAdapter, AudioAdapter, etc.) to
    460      *  provide data protection and consistency.
    461      */
    462     typedef AutoStateDependency<MutableStateDep> AutoMutableStateDependency;
    463 
    464     /**
    465      *  Shortcut to AutoStateDependency<MutableOrSavedStateDep>.
    466      *  See AutoStateDependency to get the usage pattern.
    467      *
    468      *  Succeeds only if the machine state is in one of the mutable states, or
    469      *  if the machine is in the Saved state, and guarantees the given mutable
    470      *  state won't change before this object is destroyed. If the machine is
    471      *  not mutable, this instance's #rc() method will indicate a failure, and
    472      *  the caller is not allowed to rely on any particular machine state and
    473      *  should return the failed result code to the upper level.
    474      *
    475      *  Intended to be used within setter methods of IMachine
    476      *  children objects that may also operate on Saved machines.
    477      */
    478     typedef AutoStateDependency<MutableOrSavedStateDep> AutoMutableOrSavedStateDependency;
    479 
    480341
    481342    VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT(Machine)
Note: See TracChangeset for help on using the changeset viewer.

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