VirtualBox

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

Last change on this file since 13538 was 13457, checked in by vboxsync, 16 years ago

Main: Implemented detection of the unexpected spawning session termination for Windows (#3128), optimized for other platforms.

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

© 2023 Oracle
ContactPrivacy policyTerms of Use