VirtualBox

source: vbox/trunk/src/VBox/Main/include/MachineImpl.h@ 8083

Last change on this file since 8083 was 8083, checked in by vboxsync, 17 years ago

Main: Renamed AutoLock => AutoWriteLock; AutoReaderLock => AutoReadLock.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 34.3 KB
Line 
1/* $Id: MachineImpl.h 8083 2008-04-17 09:12:12Z vboxsync $ */
2
3/** @file
4 *
5 * VirtualBox COM class declaration
6 */
7
8/*
9 * Copyright (C) 2006-2007 innotek GmbH
10 *
11 * This file is part of VirtualBox Open Source Edition (OSE), as
12 * available from http://www.virtualbox.org. This file is free software;
13 * you can redistribute it and/or modify it under the terms of the GNU
14 * General Public License (GPL) as published by the Free Software
15 * Foundation, in version 2 as it comes in the "COPYING" file of the
16 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
17 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
18 */
19
20#ifndef ____H_MACHINEIMPL
21#define ____H_MACHINEIMPL
22
23#include "VirtualBoxBase.h"
24#include "ProgressImpl.h"
25#include "SnapshotImpl.h"
26#include "VRDPServerImpl.h"
27#include "DVDDriveImpl.h"
28#include "FloppyDriveImpl.h"
29#include "HardDiskAttachmentImpl.h"
30#include "Collection.h"
31#include "NetworkAdapterImpl.h"
32#include "AudioAdapterImpl.h"
33#include "SerialPortImpl.h"
34#include "ParallelPortImpl.h"
35#include "BIOSSettingsImpl.h"
36#include "SATAControllerImpl.h"
37
38// generated header
39#include "SchemaDefs.h"
40
41#include <VBox/types.h>
42
43#include <iprt/file.h>
44#include <iprt/thread.h>
45#include <iprt/time.h>
46
47#include <list>
48
49// defines
50////////////////////////////////////////////////////////////////////////////////
51
52// helper declarations
53////////////////////////////////////////////////////////////////////////////////
54
55class VirtualBox;
56class Progress;
57class CombinedProgress;
58class Keyboard;
59class Mouse;
60class Display;
61class MachineDebugger;
62class USBController;
63class Snapshot;
64class SharedFolder;
65class HostUSBDevice;
66
67class SessionMachine;
68
69// Machine class
70////////////////////////////////////////////////////////////////////////////////
71
72class ATL_NO_VTABLE Machine :
73 public VirtualBoxBaseWithChildrenNEXT,
74 public VirtualBoxSupportErrorInfoImpl <Machine, IMachine>,
75 public VirtualBoxSupportTranslation <Machine>,
76 public IMachine
77{
78 Q_OBJECT
79
80public:
81
82 /**
83 * Internal machine data.
84 *
85 * Only one instance of this data exists per every machine --
86 * it is shared by the Machine, SessionMachine and all SnapshotMachine
87 * instances associated with the given machine using the util::Shareable
88 * template through the mData variable.
89 *
90 * @note |const| members are persistent during lifetime so can be
91 * accessed without locking.
92 *
93 * @note There is no need to lock anything inside init() or uninit()
94 * methods, because they are always serialized (see AutoCaller).
95 */
96 struct Data
97 {
98 /**
99 * Data structure to hold information about sessions opened for the
100 * given machine.
101 */
102 struct Session
103 {
104 /** Control of the direct session opened by openSession() */
105 ComPtr <IInternalSessionControl> mDirectControl;
106
107 typedef std::list <ComPtr <IInternalSessionControl> > RemoteControlList;
108
109 /** list of controls of all opened remote sessions */
110 RemoteControlList mRemoteControls;
111
112 /** openRemoteSession() and OnSessionEnd() progress indicator */
113 ComObjPtr <Progress> mProgress;
114
115 /**
116 * PID of the session object that must be passed to openSession()
117 * to finalize the openRemoteSession() request
118 * (i.e., PID of the process created by openRemoteSession())
119 */
120 RTPROCESS mPid;
121
122 /** Current session state */
123 SessionState_T mState;
124
125 /** Session type string (for indirect sessions) */
126 Bstr mType;
127
128 /** Sesison machine object */
129 ComObjPtr <SessionMachine> mMachine;
130 };
131
132 Data();
133 ~Data();
134
135 const Guid mUuid;
136 BOOL mRegistered;
137
138 Bstr mConfigFile;
139 Bstr mConfigFileFull;
140
141 Utf8Str mSettingsFileVersion;
142
143 BOOL mAccessible;
144 com::ErrorInfo mAccessError;
145
146 MachineState_T mMachineState;
147 RTTIMESPEC mLastStateChange;
148
149 /* Note: These are guarded by VirtualBoxBase::stateLockHandle() */
150 uint32_t mMachineStateDeps;
151 RTSEMEVENTMULTI mMachineStateDepsSem;
152 uint32_t mMachineStateChangePending;
153
154 BOOL mCurrentStateModified;
155
156 RTFILE mHandleCfgFile;
157
158 Session mSession;
159
160 ComObjPtr <Snapshot> mFirstSnapshot;
161 ComObjPtr <Snapshot> mCurrentSnapshot;
162 };
163
164 /**
165 * Saved state data.
166 *
167 * It's actually only the state file path string, but it needs to be
168 * separate from Data, because Machine and SessionMachine instances
169 * share it, while SnapshotMachine does not.
170 *
171 * The data variable is |mSSData|.
172 */
173 struct SSData
174 {
175 Bstr mStateFilePath;
176 };
177
178 /**
179 * User changeable machine data.
180 *
181 * This data is common for all machine snapshots, i.e. it is shared
182 * by all SnapshotMachine instances associated with the given machine
183 * using the util::Backupable template through the |mUserData| variable.
184 *
185 * SessionMachine instances can alter this data and discard changes.
186 *
187 * @note There is no need to lock anything inside init() or uninit()
188 * methods, because they are always serialized (see AutoCaller).
189 */
190 struct UserData
191 {
192 UserData();
193 ~UserData();
194
195 bool operator== (const UserData &that) const
196 {
197 return this == &that ||
198 (mName == that.mName &&
199 mNameSync == that.mNameSync &&
200 mDescription == that.mDescription &&
201 mOSTypeId == that.mOSTypeId &&
202 mSnapshotFolderFull == that.mSnapshotFolderFull);
203 }
204
205 Bstr mName;
206 BOOL mNameSync;
207 Bstr mDescription;
208 Bstr mOSTypeId;
209 Bstr mSnapshotFolder;
210 Bstr mSnapshotFolderFull;
211 };
212
213 /**
214 * Hardware data.
215 *
216 * This data is unique for a machine and for every machine snapshot.
217 * Stored using the util::Backupable template in the |mHWData| variable.
218 *
219 * SessionMachine instances can alter this data and discard changes.
220 */
221 struct HWData
222 {
223 HWData();
224 ~HWData();
225
226 bool operator== (const HWData &that) const;
227
228 ULONG mMemorySize;
229 ULONG mMemoryBalloonSize;
230 ULONG mStatisticsUpdateInterval;
231 ULONG mVRAMSize;
232 ULONG mMonitorCount;
233 TSBool_T mHWVirtExEnabled;
234 BOOL mPAEEnabled;
235
236 DeviceType_T mBootOrder [SchemaDefs::MaxBootPosition];
237
238 typedef std::list <ComObjPtr <SharedFolder> > SharedFolderList;
239 SharedFolderList mSharedFolders;
240 ClipboardMode_T mClipboardMode;
241 };
242
243 /**
244 * Hard disk data.
245 *
246 * The usage policy is the same as for HWData, but a separate structure
247 * is necessarym because hard disk data requires different procedures when
248 * taking or discarding snapshots, etc.
249 *
250 * The data variable is |mHWData|.
251 */
252 struct HDData
253 {
254 HDData();
255 ~HDData();
256
257 bool operator== (const HDData &that) const;
258
259 typedef std::list <ComObjPtr <HardDiskAttachment> > HDAttachmentList;
260 HDAttachmentList mHDAttachments;
261
262 /**
263 * Right after Machine::fixupHardDisks(true): |true| if hard disks
264 * were actually changed, |false| otherwise
265 */
266 bool mHDAttachmentsChanged;
267 };
268
269 enum StateDependency
270 {
271 AnyStateDep = 0, MutableStateDep, MutableOrSavedStateDep
272 };
273
274 /**
275 * Helper class that safely manages the machine state dependency by
276 * calling Machine::addStateDependency() on construction and
277 * Machine::releaseStateDependency() on destruction. Intended for Machine
278 * children. The usage pattern is:
279 *
280 * @code
281 * AutoCaller autoCaller (this);
282 * CheckComRCReturnRC (autoCaller.rc());
283 *
284 * Machine::AutoStateDependency <MutableStateDep> adep (mParent);
285 * CheckComRCReturnRC (stateDep.rc());
286 * ...
287 * // code that depends on the particular machine state
288 * ...
289 * @endcode
290 *
291 * Note that it is more convenient to use the following individual
292 * shortcut classes instead of using this template directly:
293 * AutoAnyStateDependency, AutoMutableStateDependency and
294 * AutoMutableOrSavedStateDependency. The usage pattern is exactly the
295 * same as above except that there is no need to specify the template
296 * argument because it is already done by the shortcut class.
297 *
298 * @param taDepType Dependecy type to manage.
299 */
300 template <StateDependency taDepType = AnyStateDep>
301 class AutoStateDependency
302 {
303 public:
304
305 AutoStateDependency (Machine *aThat)
306 : mThat (aThat), mRC (S_OK)
307 , mMachineState (MachineState_Null)
308 , mRegistered (FALSE)
309 {
310 Assert (aThat);
311 mRC = aThat->addStateDependency (taDepType, &mMachineState,
312 &mRegistered);
313 }
314 ~AutoStateDependency()
315 {
316 if (SUCCEEDED (mRC))
317 mThat->releaseStateDependency();
318 }
319
320 /** Decreases the number of dependencies before the instance is
321 * destroyed. Note that will reset #rc() to E_FAIL. */
322 void release()
323 {
324 AssertReturnVoid (SUCCEEDED (mRC));
325 mThat->releaseStateDependency();
326 mRC = E_FAIL;
327 }
328
329 /** Restores the number of callers after by #release(). #rc() will be
330 * reset to the result of calling addStateDependency() and must be
331 * rechecked to ensure the operation succeeded. */
332 void add()
333 {
334 AssertReturnVoid (!SUCCEEDED (mRC));
335 mRC = mThat->addStateDependency (taDepType, &mMachineState,
336 &mRegistered);
337 }
338
339 /** Returns the result of Machine::addStateDependency(). */
340 HRESULT rc() const { return mRC; }
341
342 /** Shortcut to SUCCEEDED (rc()). */
343 bool isOk() const { return SUCCEEDED (mRC); }
344
345 /** Returns the machine state value as returned by
346 * Machine::addStateDependency(). */
347 MachineState_T machineState() const { return mMachineState; }
348
349 /** Returns the machine state value as returned by
350 * Machine::addStateDependency(). */
351 BOOL machineRegistered() const { return mRegistered; }
352
353 protected:
354
355 Machine *mThat;
356 HRESULT mRC;
357 MachineState_T mMachineState;
358 BOOL mRegistered;
359
360 private:
361
362 DECLARE_CLS_COPY_CTOR_ASSIGN_NOOP (AutoStateDependency)
363 DECLARE_CLS_NEW_DELETE_NOOP (AutoStateDependency)
364 };
365
366 /**
367 * Shortcut to AutoStateDependency <AnyStateDep>.
368 * See AutoStateDependency to get the usage pattern.
369 *
370 * Accepts any machine state and guarantees the state won't change before
371 * this object is destroyed. If the machine state cannot be protected (as
372 * a result of the state change currently in progress), this instance's
373 * #rc() method will indicate a failure, and the caller is not allowed to
374 * rely on any particular machine state and should return the failed
375 * result code to the upper level.
376 */
377 typedef AutoStateDependency <AnyStateDep> AutoAnyStateDependency;
378
379 /**
380 * Shortcut to AutoStateDependency <MutableStateDep>.
381 * See AutoStateDependency to get the usage pattern.
382 *
383 * Succeeds only if the machine state is in one of the mutable states, and
384 * guarantees the given mutable state won't change before this object is
385 * destroyed. If the machine is not mutable, this instance's #rc() method
386 * will indicate a failure, and the caller is not allowed to rely on any
387 * particular machine state and should return the failed result code to
388 * the upper level.
389 *
390 * Intended to be used within all setter methods of IMachine
391 * children objects (DVDDrive, NetworkAdapter, AudioAdapter, etc.) to
392 * provide data protection and consistency.
393 */
394 typedef AutoStateDependency <MutableStateDep> AutoMutableStateDependency;
395
396 /**
397 * Shortcut to AutoStateDependency <MutableOrSavedStateDep>.
398 * See AutoStateDependency to get the usage pattern.
399 *
400 * Succeeds only if the machine state is in one of the mutable states, or
401 * if the machine is in the Saved state, and guarantees the given mutable
402 * state won't change before this object is destroyed. If the machine is
403 * not mutable, this instance's #rc() method will indicate a failure, and
404 * the caller is not allowed to rely on any particular machine state and
405 * should return the failed result code to the upper level.
406 *
407 * Intended to be used within setter methods of IMachine
408 * children objects that may also operate on Saved machines.
409 */
410 typedef AutoStateDependency <MutableOrSavedStateDep> AutoMutableOrSavedStateDependency;
411
412
413 VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT (Machine)
414
415 DECLARE_NOT_AGGREGATABLE(Machine)
416
417 DECLARE_PROTECT_FINAL_CONSTRUCT()
418
419 BEGIN_COM_MAP(Machine)
420 COM_INTERFACE_ENTRY(ISupportErrorInfo)
421 COM_INTERFACE_ENTRY(IMachine)
422 END_COM_MAP()
423
424 NS_DECL_ISUPPORTS
425
426 DECLARE_EMPTY_CTOR_DTOR (Machine)
427
428 HRESULT FinalConstruct();
429 void FinalRelease();
430
431 enum InitMode { Init_New, Init_Existing, Init_Registered };
432
433 // public initializer/uninitializer for internal purposes only
434 HRESULT init (VirtualBox *aParent, const BSTR aConfigFile,
435 InitMode aMode, const BSTR aName = NULL,
436 BOOL aNameSync = TRUE, const Guid *aId = NULL);
437 void uninit();
438
439 // IMachine properties
440 STDMETHOD(COMGETTER(Parent))(IVirtualBox **aParent);
441 STDMETHOD(COMGETTER(Accessible)) (BOOL *aAccessible);
442 STDMETHOD(COMGETTER(AccessError)) (IVirtualBoxErrorInfo **aAccessError);
443 STDMETHOD(COMGETTER(Name))(BSTR *aName);
444 STDMETHOD(COMSETTER(Name))(INPTR BSTR aName);
445 STDMETHOD(COMGETTER(Description))(BSTR *aDescription);
446 STDMETHOD(COMSETTER(Description))(INPTR BSTR aDescription);
447 STDMETHOD(COMGETTER(Id))(GUIDPARAMOUT aId);
448 STDMETHOD(COMGETTER(OSTypeId)) (BSTR *aOSTypeId);
449 STDMETHOD(COMSETTER(OSTypeId)) (INPTR BSTR aOSTypeId);
450 STDMETHOD(COMGETTER(MemorySize))(ULONG *memorySize);
451 STDMETHOD(COMSETTER(MemorySize))(ULONG memorySize);
452 STDMETHOD(COMGETTER(MemoryBalloonSize))(ULONG *memoryBalloonSize);
453 STDMETHOD(COMSETTER(MemoryBalloonSize))(ULONG memoryBalloonSize);
454 STDMETHOD(COMGETTER(StatisticsUpdateInterval))(ULONG *statisticsUpdateInterval);
455 STDMETHOD(COMSETTER(StatisticsUpdateInterval))(ULONG statisticsUpdateInterval);
456 STDMETHOD(COMGETTER(VRAMSize))(ULONG *memorySize);
457 STDMETHOD(COMSETTER(VRAMSize))(ULONG memorySize);
458 STDMETHOD(COMGETTER(MonitorCount))(ULONG *monitorCount);
459 STDMETHOD(COMSETTER(MonitorCount))(ULONG monitorCount);
460 STDMETHOD(COMGETTER(BIOSSettings))(IBIOSSettings **biosSettings);
461 STDMETHOD(COMGETTER(HWVirtExEnabled))(TSBool_T *enabled);
462 STDMETHOD(COMSETTER(HWVirtExEnabled))(TSBool_T enabled);
463 STDMETHOD(COMGETTER(PAEEnabled))(BOOL *enabled);
464 STDMETHOD(COMSETTER(PAEEnabled))(BOOL enabled);
465 STDMETHOD(COMGETTER(SnapshotFolder))(BSTR *aSavedStateFolder);
466 STDMETHOD(COMSETTER(SnapshotFolder))(INPTR BSTR aSavedStateFolder);
467 STDMETHOD(COMGETTER(HardDiskAttachments))(IHardDiskAttachmentCollection **attachments);
468 STDMETHOD(COMGETTER(VRDPServer))(IVRDPServer **vrdpServer);
469 STDMETHOD(COMGETTER(DVDDrive))(IDVDDrive **dvdDrive);
470 STDMETHOD(COMGETTER(FloppyDrive))(IFloppyDrive **floppyDrive);
471 STDMETHOD(COMGETTER(AudioAdapter))(IAudioAdapter **audioAdapter);
472 STDMETHOD(COMGETTER(USBController)) (IUSBController * *aUSBController);
473 STDMETHOD(COMGETTER(SATAController)) (ISATAController **aSATAController);
474 STDMETHOD(COMGETTER(SettingsFilePath)) (BSTR *aFilePath);
475 STDMETHOD(COMGETTER(SettingsFileVersion)) (BSTR *aSettingsFileVersion);
476 STDMETHOD(COMGETTER(SettingsModified)) (BOOL *aModified);
477 STDMETHOD(COMGETTER(SessionState)) (SessionState_T *aSessionState);
478 STDMETHOD(COMGETTER(SessionType)) (BSTR *aSessionType);
479 STDMETHOD(COMGETTER(SessionPid)) (ULONG *aSessionPid);
480 STDMETHOD(COMGETTER(State)) (MachineState_T *machineState);
481 STDMETHOD(COMGETTER(LastStateChange)) (LONG64 *aLastStateChange);
482 STDMETHOD(COMGETTER(StateFilePath)) (BSTR *aStateFilePath);
483 STDMETHOD(COMGETTER(LogFolder)) (BSTR *aLogFolder);
484 STDMETHOD(COMGETTER(CurrentSnapshot)) (ISnapshot **aCurrentSnapshot);
485 STDMETHOD(COMGETTER(SnapshotCount)) (ULONG *aSnapshotCount);
486 STDMETHOD(COMGETTER(CurrentStateModified))(BOOL *aCurrentStateModified);
487 STDMETHOD(COMGETTER(SharedFolders)) (ISharedFolderCollection **aSharedFolders);
488 STDMETHOD(COMGETTER(ClipboardMode)) (ClipboardMode_T *aClipboardMode);
489 STDMETHOD(COMSETTER(ClipboardMode)) (ClipboardMode_T aClipboardMode);
490
491 // IMachine methods
492 STDMETHOD(SetBootOrder)(ULONG aPosition, DeviceType_T aDevice);
493 STDMETHOD(GetBootOrder)(ULONG aPosition, DeviceType_T *aDevice);
494 STDMETHOD(AttachHardDisk)(INPTR GUIDPARAM aId, StorageBus_T aBus, LONG aChannel, LONG aDevice);
495 STDMETHOD(GetHardDisk)(StorageBus_T aBus, LONG aChannel, LONG aDevice, IHardDisk **aHardDisk);
496 STDMETHOD(DetachHardDisk) (StorageBus_T aBus, LONG aChannel, LONG aDevice);
497 STDMETHOD(GetSerialPort) (ULONG slot, ISerialPort **port);
498 STDMETHOD(GetParallelPort) (ULONG slot, IParallelPort **port);
499 STDMETHOD(GetNetworkAdapter) (ULONG slot, INetworkAdapter **adapter);
500 STDMETHOD(GetNextExtraDataKey)(INPTR BSTR aKey, BSTR *aNextKey, BSTR *aNextValue);
501 STDMETHOD(GetExtraData)(INPTR BSTR aKey, BSTR *aValue);
502 STDMETHOD(SetExtraData)(INPTR BSTR aKey, INPTR BSTR aValue);
503 STDMETHOD(SaveSettings)();
504 STDMETHOD(SaveSettingsWithBackup) (BSTR *aBakFileName);
505 STDMETHOD(DiscardSettings)();
506 STDMETHOD(DeleteSettings)();
507 STDMETHOD(GetSnapshot) (INPTR GUIDPARAM aId, ISnapshot **aSnapshot);
508 STDMETHOD(FindSnapshot) (INPTR BSTR aName, ISnapshot **aSnapshot);
509 STDMETHOD(SetCurrentSnapshot) (INPTR GUIDPARAM aId);
510 STDMETHOD(CreateSharedFolder) (INPTR BSTR aName, INPTR BSTR aHostPath, BOOL aWritable);
511 STDMETHOD(RemoveSharedFolder) (INPTR BSTR aName);
512 STDMETHOD(CanShowConsoleWindow) (BOOL *aCanShow);
513 STDMETHOD(ShowConsoleWindow) (ULONG64 *aWinId);
514
515 // public methods only for internal purposes
516
517 /// @todo (dmik) add lock and make non-inlined after revising classes
518 // that use it. Note: they should enter Machine lock to keep the returned
519 // information valid!
520 bool isRegistered() { return !!mData->mRegistered; }
521
522 ComObjPtr <SessionMachine> sessionMachine();
523
524 /**
525 * Returns the VirtualBox object this machine belongs to.
526 *
527 * @note This method doesn't check this object's readiness as it is
528 * intended to be used only by Machine children where it is guaranteed
529 * that this object still exists in memory.
530 */
531 const ComObjPtr <VirtualBox, ComWeakRef> &virtualBox() const { return mParent; }
532
533 /**
534 * Returns this machine's name.
535 *
536 * @note This method doesn't check this object's readiness as it is
537 * intended to be used only after adding a caller to this object (that
538 * guarantees that the object is ready or at least limited).
539 */
540 const Guid &uuid() const { return mData->mUuid; }
541
542 /**
543 * Returns this machine's full settings file path.
544 *
545 * @note This method doesn't lock this object or check its readiness as
546 * it is intended to be used only after adding a caller to this object
547 * (that guarantees that the object is ready) and locking it for reading.
548 */
549 const Bstr &settingsFileFull() const { return mData->mConfigFileFull; }
550
551 /**
552 * Returns this machine's name.
553 *
554 * @note This method doesn't lock this object or check its readiness as
555 * it is intended to be used only after adding a caller to this object
556 * (that guarantees that the object is ready) and locking it for reading.
557 */
558 const Bstr &name() const { return mUserData->mName; }
559
560 // callback handlers
561 virtual HRESULT onDVDDriveChange() { return S_OK; }
562 virtual HRESULT onFloppyDriveChange() { return S_OK; }
563 virtual HRESULT onNetworkAdapterChange(INetworkAdapter *networkAdapter) { return S_OK; }
564 virtual HRESULT onSerialPortChange(ISerialPort *serialPort) { return S_OK; }
565 virtual HRESULT onParallelPortChange(IParallelPort *ParallelPort) { return S_OK; }
566 virtual HRESULT onVRDPServerChange() { return S_OK; }
567 virtual HRESULT onUSBControllerChange() { return S_OK; }
568 virtual HRESULT onSATAControllerChange() { return S_OK; }
569 virtual HRESULT onSharedFolderChange() { return S_OK; }
570
571 HRESULT saveRegistryEntry (settings::Key &aEntryNode);
572
573 int calculateFullPath (const char *aPath, Utf8Str &aResult);
574 void calculateRelativePath (const char *aPath, Utf8Str &aResult);
575
576 void getLogFolder (Utf8Str &aLogFolder);
577
578 bool isDVDImageUsed (const Guid &aId, ResourceUsage_T aUsage);
579 bool isFloppyImageUsed (const Guid &aId, ResourceUsage_T aUsage);
580
581 HRESULT openSession (IInternalSessionControl *aControl);
582 HRESULT openRemoteSession (IInternalSessionControl *aControl,
583 INPTR BSTR aType, INPTR BSTR aEnvironment,
584 Progress *aProgress);
585 HRESULT openExistingSession (IInternalSessionControl *aControl);
586
587 HRESULT trySetRegistered (BOOL aRegistered);
588
589 HRESULT getSharedFolder (const BSTR aName,
590 ComObjPtr <SharedFolder> &aSharedFolder,
591 bool aSetError = false)
592 {
593 AutoWriteLock alock (this);
594 return findSharedFolder (aName, aSharedFolder, aSetError);
595 }
596
597 HRESULT addStateDependency (StateDependency aDepType = AnyStateDep,
598 MachineState_T *aState = NULL,
599 BOOL *aRegistered = NULL);
600 void releaseStateDependency();
601
602 // for VirtualBoxSupportErrorInfoImpl
603 static const wchar_t *getComponentName() { return L"Machine"; }
604
605protected:
606
607 enum InstanceType { IsMachine, IsSessionMachine, IsSnapshotMachine };
608
609 HRESULT registeredInit();
610
611 HRESULT checkStateDependency (StateDependency aDepType);
612
613 inline Machine *machine();
614
615 HRESULT initDataAndChildObjects();
616 void uninitDataAndChildObjects();
617
618 void ensureNoStateDependencies (AutoWriteLock &aLock);
619
620 virtual HRESULT setMachineState (MachineState_T aMachineState);
621
622 HRESULT findSharedFolder (const BSTR aName,
623 ComObjPtr <SharedFolder> &aSharedFolder,
624 bool aSetError = false);
625
626 HRESULT loadSettings (bool aRegistered);
627 HRESULT loadSnapshot (const settings::Key &aNode, const Guid &aCurSnapshotId,
628 Snapshot *aParentSnapshot);
629 HRESULT loadHardware (const settings::Key &aNode);
630 HRESULT loadHardDisks (const settings::Key &aNode, bool aRegistered,
631 const Guid *aSnapshotId = NULL);
632
633 HRESULT findSnapshotNode (Snapshot *aSnapshot, settings::Key &aMachineNode,
634 settings::Key *aSnapshotsNode,
635 settings::Key *aSnapshotNode);
636
637 HRESULT findSnapshot (const Guid &aId, ComObjPtr <Snapshot> &aSnapshot,
638 bool aSetError = false);
639 HRESULT findSnapshot (const BSTR aName, ComObjPtr <Snapshot> &aSnapshot,
640 bool aSetError = false);
641
642 HRESULT findHardDiskAttachment (const ComObjPtr <HardDisk> &aHd,
643 ComObjPtr <Machine> *aMachine,
644 ComObjPtr <Snapshot> *aSnapshot,
645 ComObjPtr <HardDiskAttachment> *aHda);
646
647 HRESULT prepareSaveSettings (bool &aRenamed, bool &aNew);
648 HRESULT saveSettings (bool aMarkCurStateAsModified = true,
649 bool aInformCallbacksAnyway = false);
650
651 enum
652 {
653 // ops for #saveSnapshotSettings()
654 SaveSS_NoOp = 0x00, SaveSS_AddOp = 0x01,
655 SaveSS_UpdateAttrsOp = 0x02, SaveSS_UpdateAllOp = 0x03,
656 SaveSS_OpMask = 0xF,
657 // flags for #saveSnapshotSettings()
658 SaveSS_UpdateCurStateModified = 0x40,
659 SaveSS_UpdateCurrentId = 0x80,
660 // flags for #saveStateSettings()
661 SaveSTS_CurStateModified = 0x20,
662 SaveSTS_StateFilePath = 0x40,
663 SaveSTS_StateTimeStamp = 0x80,
664 };
665
666 HRESULT saveSnapshotSettings (Snapshot *aSnapshot, int aOpFlags);
667 HRESULT saveSnapshotSettingsWorker (settings::Key &aMachineNode,
668 Snapshot *aSnapshot, int aOpFlags);
669
670 HRESULT saveSnapshot (settings::Key &aNode, Snapshot *aSnapshot, bool aAttrsOnly);
671 HRESULT saveHardware (settings::Key &aNode);
672 HRESULT saveHardDisks (settings::Key &aNode);
673
674 HRESULT saveStateSettings (int aFlags);
675
676 HRESULT wipeOutImmutableDiffs();
677
678 HRESULT fixupHardDisks (bool aCommit);
679
680 HRESULT createSnapshotDiffs (const Guid *aSnapshotId,
681 const Bstr &aFolder,
682 const ComObjPtr <Progress> &aProgress,
683 bool aOnline);
684 HRESULT deleteSnapshotDiffs (const ComObjPtr <Snapshot> &aSnapshot);
685
686 HRESULT lockConfig();
687 HRESULT unlockConfig();
688
689 /** @note This method is not thread safe */
690 BOOL isConfigLocked()
691 {
692 return !!mData && mData->mHandleCfgFile != NIL_RTFILE;
693 }
694
695 bool isInOwnDir (Utf8Str *aSettingsDir = NULL);
696
697 bool isModified();
698 bool isReallyModified (bool aIgnoreUserData = false);
699 void rollback (bool aNotify);
700 HRESULT commit();
701 void copyFrom (Machine *aThat);
702
703 const InstanceType mType;
704
705 const ComObjPtr <Machine, ComWeakRef> mPeer;
706
707 const ComObjPtr <VirtualBox, ComWeakRef> mParent;
708
709 Shareable <Data> mData;
710 Shareable <SSData> mSSData;
711
712 Backupable <UserData> mUserData;
713 Backupable <HWData> mHWData;
714 Backupable <HDData> mHDData;
715
716 // the following fields need special backup/rollback/commit handling,
717 // so they cannot be a part of HWData
718
719 const ComObjPtr <VRDPServer> mVRDPServer;
720 const ComObjPtr <DVDDrive> mDVDDrive;
721 const ComObjPtr <FloppyDrive> mFloppyDrive;
722 const ComObjPtr <SerialPort>
723 mSerialPorts [SchemaDefs::SerialPortCount];
724 const ComObjPtr <ParallelPort>
725 mParallelPorts [SchemaDefs::ParallelPortCount];
726 const ComObjPtr <AudioAdapter> mAudioAdapter;
727 const ComObjPtr <USBController> mUSBController;
728 const ComObjPtr <SATAController> mSATAController;
729 const ComObjPtr <BIOSSettings> mBIOSSettings;
730 const ComObjPtr <NetworkAdapter>
731 mNetworkAdapters [SchemaDefs::NetworkAdapterCount];
732
733 friend class SessionMachine;
734 friend class SnapshotMachine;
735};
736
737// SessionMachine class
738////////////////////////////////////////////////////////////////////////////////
739
740/**
741 * @note Notes on locking objects of this class:
742 * SessionMachine shares some data with the primary Machine instance (pointed
743 * to by the |mPeer| member). In order to provide data consistency it also
744 * shares its lock handle. This means that whenever you lock a SessionMachine
745 * instance using Auto[Reader]Lock or AutoMultiLock, the corresponding Machine
746 * instance is also locked in the same lock mode. Keep it in mind.
747 */
748class ATL_NO_VTABLE SessionMachine :
749 public VirtualBoxSupportTranslation <SessionMachine>,
750 public Machine,
751 public IInternalMachineControl
752{
753public:
754
755 VIRTUALBOXSUPPORTTRANSLATION_OVERRIDE(SessionMachine)
756
757 DECLARE_NOT_AGGREGATABLE(SessionMachine)
758
759 DECLARE_PROTECT_FINAL_CONSTRUCT()
760
761 BEGIN_COM_MAP(SessionMachine)
762 COM_INTERFACE_ENTRY(ISupportErrorInfo)
763 COM_INTERFACE_ENTRY(IMachine)
764 COM_INTERFACE_ENTRY(IInternalMachineControl)
765 END_COM_MAP()
766
767 NS_DECL_ISUPPORTS
768
769 DECLARE_EMPTY_CTOR_DTOR (SessionMachine)
770
771 HRESULT FinalConstruct();
772 void FinalRelease();
773
774 // public initializer/uninitializer for internal purposes only
775 HRESULT init (Machine *aMachine);
776 void uninit() { uninit (Uninit::Unexpected); }
777
778 // util::Lockable interface
779 RWLockHandle *lockHandle() const;
780
781 // IInternalMachineControl methods
782 STDMETHOD(UpdateState)(MachineState_T machineState);
783 STDMETHOD(GetIPCId)(BSTR *id);
784 STDMETHOD(RunUSBDeviceFilters) (IUSBDevice *aUSBDevice, BOOL *aMatched, ULONG *aMaskedIfs);
785 STDMETHOD(CaptureUSBDevice) (INPTR GUIDPARAM aId);
786 STDMETHOD(DetachUSBDevice) (INPTR GUIDPARAM aId, BOOL aDone);
787 STDMETHOD(AutoCaptureUSBDevices)();
788 STDMETHOD(DetachAllUSBDevices)(BOOL aDone);
789 STDMETHOD(OnSessionEnd)(ISession *aSession, IProgress **aProgress);
790 STDMETHOD(BeginSavingState) (IProgress *aProgress, BSTR *aStateFilePath);
791 STDMETHOD(EndSavingState) (BOOL aSuccess);
792 STDMETHOD(AdoptSavedState) (INPTR BSTR aSavedStateFile);
793 STDMETHOD(BeginTakingSnapshot) (IConsole *aInitiator,
794 INPTR BSTR aName, INPTR BSTR aDescription,
795 IProgress *aProgress, BSTR *aStateFilePath,
796 IProgress **aServerProgress);
797 STDMETHOD(EndTakingSnapshot) (BOOL aSuccess);
798 STDMETHOD(DiscardSnapshot) (IConsole *aInitiator, INPTR GUIDPARAM aId,
799 MachineState_T *aMachineState, IProgress **aProgress);
800 STDMETHOD(DiscardCurrentState) (
801 IConsole *aInitiator, MachineState_T *aMachineState, IProgress **aProgress);
802 STDMETHOD(DiscardCurrentSnapshotAndState) (
803 IConsole *aInitiator, MachineState_T *aMachineState, IProgress **aProgress);
804
805 // public methods only for internal purposes
806
807 bool checkForDeath();
808
809#if defined (RT_OS_WINDOWS)
810 HANDLE ipcSem() { return mIPCSem; }
811#elif defined (RT_OS_OS2)
812 HMTX ipcSem() { return mIPCSem; }
813#endif
814
815 HRESULT onDVDDriveChange();
816 HRESULT onFloppyDriveChange();
817 HRESULT onNetworkAdapterChange(INetworkAdapter *networkAdapter);
818 HRESULT onSerialPortChange(ISerialPort *serialPort);
819 HRESULT onParallelPortChange(IParallelPort *parallelPort);
820 HRESULT onVRDPServerChange();
821 HRESULT onUSBControllerChange();
822 HRESULT onUSBDeviceAttach (IUSBDevice *aDevice,
823 IVirtualBoxErrorInfo *aError,
824 ULONG aMaskedIfs);
825 HRESULT onUSBDeviceDetach (INPTR GUIDPARAM aId,
826 IVirtualBoxErrorInfo *aError);
827 HRESULT onSharedFolderChange();
828
829 bool hasMatchingUSBFilter (const ComObjPtr <HostUSBDevice> &aDevice, ULONG *aMaskedIfs);
830
831private:
832
833 struct SnapshotData
834 {
835 SnapshotData() : mLastState (MachineState_Null) {}
836
837 MachineState_T mLastState;
838
839 // used when taking snapshot
840 ComObjPtr <Snapshot> mSnapshot;
841 ComObjPtr <Progress> mServerProgress;
842 ComObjPtr <CombinedProgress> mCombinedProgress;
843
844 // used when saving state
845 Guid mProgressId;
846 Bstr mStateFilePath;
847 };
848
849 struct Uninit {
850 enum Reason { Unexpected, Abnormal, Normal };
851 };
852
853 struct Task;
854 struct TakeSnapshotTask;
855 struct DiscardSnapshotTask;
856 struct DiscardCurrentStateTask;
857
858 friend struct TakeSnapshotTask;
859 friend struct DiscardSnapshotTask;
860 friend struct DiscardCurrentStateTask;
861
862 void uninit (Uninit::Reason aReason);
863
864 HRESULT endSavingState (BOOL aSuccess);
865 HRESULT endTakingSnapshot (BOOL aSuccess);
866
867 typedef std::map <ComObjPtr <Machine>, MachineState_T> AffectedMachines;
868
869 void takeSnapshotHandler (TakeSnapshotTask &aTask);
870 void discardSnapshotHandler (DiscardSnapshotTask &aTask);
871 void discardCurrentStateHandler (DiscardCurrentStateTask &aTask);
872
873 HRESULT setMachineState (MachineState_T aMachineState);
874 HRESULT updateMachineStateOnClient();
875
876 SnapshotData mSnapshotData;
877
878 /** interprocess semaphore handle (id) for this machine */
879#if defined(RT_OS_WINDOWS)
880 HANDLE mIPCSem;
881 Bstr mIPCSemName;
882#elif defined(RT_OS_OS2)
883 HMTX mIPCSem;
884 Bstr mIPCSemName;
885#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
886 int mIPCSem;
887#else
888# error "Port me!"
889#endif
890
891 static DECLCALLBACK(int) taskHandler (RTTHREAD thread, void *pvUser);
892};
893
894// SnapshotMachine class
895////////////////////////////////////////////////////////////////////////////////
896
897/**
898 * @note Notes on locking objects of this class:
899 * SnapshotMachine shares some data with the primary Machine instance (pointed
900 * to by the |mPeer| member). In order to provide data consistency it also
901 * shares its lock handle. This means that whenever you lock a SessionMachine
902 * instance using Auto[Reader]Lock or AutoMultiLock, the corresponding Machine
903 * instance is also locked in the same lock mode. Keep it in mind.
904 */
905class ATL_NO_VTABLE SnapshotMachine :
906 public VirtualBoxSupportTranslation <SnapshotMachine>,
907 public Machine
908{
909public:
910
911 VIRTUALBOXSUPPORTTRANSLATION_OVERRIDE(SnapshotMachine)
912
913 DECLARE_NOT_AGGREGATABLE(SnapshotMachine)
914
915 DECLARE_PROTECT_FINAL_CONSTRUCT()
916
917 BEGIN_COM_MAP(SnapshotMachine)
918 COM_INTERFACE_ENTRY(ISupportErrorInfo)
919 COM_INTERFACE_ENTRY(IMachine)
920 END_COM_MAP()
921
922 NS_DECL_ISUPPORTS
923
924 DECLARE_EMPTY_CTOR_DTOR (SnapshotMachine)
925
926 HRESULT FinalConstruct();
927 void FinalRelease();
928
929 // public initializer/uninitializer for internal purposes only
930 HRESULT init (SessionMachine *aSessionMachine,
931 INPTR GUIDPARAM aSnapshotId, INPTR BSTR aStateFilePath);
932 HRESULT init (Machine *aMachine,
933 const settings::Key &aHWNode, const settings::Key &aHDAsNode,
934 INPTR GUIDPARAM aSnapshotId, INPTR BSTR aStateFilePath);
935 void uninit();
936
937 // util::Lockable interface
938 RWLockHandle *lockHandle() const;
939
940 // public methods only for internal purposes
941
942 HRESULT onSnapshotChange (Snapshot *aSnapshot);
943
944private:
945
946 Guid mSnapshotId;
947
948 friend class Snapshot;
949};
950
951////////////////////////////////////////////////////////////////////////////////
952
953/**
954 * Returns a pointer to the Machine object for this machine that acts like a
955 * parent for complex machine data objects such as shared folders, etc.
956 *
957 * For primary Machine objects and for SnapshotMachine objects, returns this
958 * object's pointer itself. For SessoinMachine objects, returns the peer
959 * (primary) machine pointer.
960 */
961inline Machine *Machine::machine()
962{
963 if (mType == IsSessionMachine)
964 return mPeer;
965 return this;
966}
967
968COM_DECL_READONLY_ENUM_AND_COLLECTION (Machine)
969
970#endif // ____H_MACHINEIMPL
Note: See TracBrowser for help on using the repository browser.

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