VirtualBox

source: vbox/trunk/src/VBox/Main/include/VirtualBoxImpl.h@ 16560

Last change on this file since 16560 was 16560, checked in by vboxsync, 15 years ago

Main: do not include include/VBox/settings.h from other header files but only from implementations that need it (save compile time)

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 19.7 KB
Line 
1/* $Id: VirtualBoxImpl.h 16560 2009-02-06 18:06:04Z vboxsync $ */
2
3/** @file
4 *
5 * VirtualBox COM class implementation
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_VIRTUALBOXIMPL
25#define ____H_VIRTUALBOXIMPL
26
27#include "VirtualBoxBase.h"
28
29#include "VBox/com/EventQueue.h"
30
31#include <list>
32#include <vector>
33#include <map>
34
35#ifdef RT_OS_WINDOWS
36# include "win/resource.h"
37#endif
38
39#ifdef VBOX_WITH_RESOURCE_USAGE_API
40#include "PerformanceImpl.h"
41#endif /* VBOX_WITH_RESOURCE_USAGE_API */
42
43class Machine;
44class SessionMachine;
45class HardDisk2;
46class DVDImage2;
47class FloppyImage2;
48class MachineCollection;
49class GuestOSType;
50class GuestOSTypeCollection;
51class SharedFolder;
52class Progress;
53class ProgressCollection;
54class Host;
55class SystemProperties;
56
57#ifdef RT_OS_WINDOWS
58class SVCHlpClient;
59#endif
60
61struct VMClientWatcherData;
62
63class ATL_NO_VTABLE VirtualBox :
64 public VirtualBoxBaseWithChildrenNEXT,
65 public VirtualBoxSupportErrorInfoImpl <VirtualBox, IVirtualBox>,
66 public VirtualBoxSupportTranslation <VirtualBox>,
67#ifdef RT_OS_WINDOWS
68 public IDispatchImpl<IVirtualBox, &IID_IVirtualBox, &LIBID_VirtualBox,
69 kTypeLibraryMajorVersion, kTypeLibraryMinorVersion>,
70 public CComCoClass<VirtualBox, &CLSID_VirtualBox>
71#else
72 public IVirtualBox
73#endif
74{
75
76public:
77
78 typedef std::list <ComPtr <IVirtualBoxCallback> > CallbackList;
79 typedef std::vector <ComPtr <IVirtualBoxCallback> > CallbackVector;
80
81 typedef std::vector <ComObjPtr <SessionMachine> > SessionMachineVector;
82 typedef std::vector <ComObjPtr <Machine> > MachineVector;
83
84 typedef std::vector <ComPtr <IInternalSessionControl> > InternalControlVector;
85
86 class CallbackEvent;
87 friend class CallbackEvent;
88
89 VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT (VirtualBox)
90
91 DECLARE_CLASSFACTORY_SINGLETON(VirtualBox)
92
93 DECLARE_REGISTRY_RESOURCEID(IDR_VIRTUALBOX)
94 DECLARE_NOT_AGGREGATABLE(VirtualBox)
95
96 DECLARE_PROTECT_FINAL_CONSTRUCT()
97
98 BEGIN_COM_MAP(VirtualBox)
99 COM_INTERFACE_ENTRY(IDispatch)
100 COM_INTERFACE_ENTRY(ISupportErrorInfo)
101 COM_INTERFACE_ENTRY(IVirtualBox)
102 END_COM_MAP()
103
104 NS_DECL_ISUPPORTS
105
106 /* to postpone generation of the default ctor/dtor */
107 VirtualBox();
108 ~VirtualBox();
109
110 HRESULT FinalConstruct();
111 void FinalRelease();
112
113 /* public initializer/uninitializer for internal purposes only */
114 HRESULT init();
115 void uninit();
116
117 /* IVirtualBox properties */
118 STDMETHOD(COMGETTER(Version)) (BSTR *aVersion);
119 STDMETHOD(COMGETTER(Revision)) (ULONG *aRevision);
120 STDMETHOD(COMGETTER(PackageType)) (BSTR *aPackageType);
121 STDMETHOD(COMGETTER(HomeFolder)) (BSTR *aHomeFolder);
122 STDMETHOD(COMGETTER(SettingsFilePath)) (BSTR *aSettingsFilePath);
123 STDMETHOD(COMGETTER(SettingsFileVersion)) (BSTR *aSettingsFileVersion);
124 STDMETHOD(COMGETTER(SettingsFormatVersion)) (BSTR *aSettingsFormatVersion);
125 STDMETHOD(COMGETTER(Host)) (IHost **aHost);
126 STDMETHOD(COMGETTER(SystemProperties)) (ISystemProperties **aSystemProperties);
127 STDMETHOD(COMGETTER(Machines2)) (ComSafeArrayOut (IMachine *, aMachines));
128 STDMETHOD(COMGETTER(HardDisks2)) (ComSafeArrayOut (IHardDisk2 *, aHardDisks));
129 STDMETHOD(COMGETTER(DVDImages)) (ComSafeArrayOut (IDVDImage2 *, aDVDImages));
130 STDMETHOD(COMGETTER(FloppyImages)) (ComSafeArrayOut (IFloppyImage2 *, aFloppyImages));
131 STDMETHOD(COMGETTER(ProgressOperations)) (IProgressCollection **aOperations);
132 STDMETHOD(COMGETTER(GuestOSTypes)) (IGuestOSTypeCollection **aGuestOSTypes);
133 STDMETHOD(COMGETTER(SharedFolders)) (ISharedFolderCollection **aSharedFolders);
134 STDMETHOD(COMGETTER(PerformanceCollector)) (IPerformanceCollector **aPerformanceCollector);
135
136 /* IVirtualBox methods */
137
138 STDMETHOD(CreateMachine) (IN_BSTR aName, IN_BSTR aOsTypeId, IN_BSTR aBaseFolder,
139 IN_GUID aId, IMachine **aMachine);
140 STDMETHOD(CreateLegacyMachine) (IN_BSTR aName, IN_BSTR aOsTypeId, IN_BSTR aSettingsFile,
141 IN_GUID aId, IMachine **aMachine);
142 STDMETHOD(OpenMachine) (IN_BSTR aSettingsFile, IMachine **aMachine);
143 STDMETHOD(RegisterMachine) (IMachine *aMachine);
144 STDMETHOD(GetMachine) (IN_GUID aId, IMachine **aMachine);
145 STDMETHOD(FindMachine) (IN_BSTR aName, IMachine **aMachine);
146 STDMETHOD(UnregisterMachine) (IN_GUID aId, IMachine **aMachine);
147 STDMETHOD(OpenAppliance) (IN_BSTR aName, IAppliance **anAppliance);
148
149 STDMETHOD(CreateHardDisk2) (IN_BSTR aFormat, IN_BSTR aLocation,
150 IHardDisk2 **aHardDisk);
151 STDMETHOD(OpenHardDisk2) (IN_BSTR aLocation, IHardDisk2 **aHardDisk);
152 STDMETHOD(GetHardDisk2) (IN_GUID aId, IHardDisk2 **aHardDisk);
153 STDMETHOD(FindHardDisk2) (IN_BSTR aLocation, IHardDisk2 **aHardDisk);
154
155 STDMETHOD(OpenDVDImage) (IN_BSTR aLocation, IN_GUID aId,
156 IDVDImage2 **aDVDImage);
157 STDMETHOD(GetDVDImage) (IN_GUID aId, IDVDImage2 **aDVDImage);
158 STDMETHOD(FindDVDImage) (IN_BSTR aLocation, IDVDImage2 **aDVDImage);
159
160 STDMETHOD(OpenFloppyImage) (IN_BSTR aLocation, IN_GUID aId,
161 IFloppyImage2 **aFloppyImage);
162 STDMETHOD(GetFloppyImage) (IN_GUID aId, IFloppyImage2 **aFloppyImage);
163 STDMETHOD(FindFloppyImage) (IN_BSTR aLocation, IFloppyImage2 **aFloppyImage);
164
165 STDMETHOD(GetGuestOSType) (IN_BSTR aId, IGuestOSType **aType);
166 STDMETHOD(CreateSharedFolder) (IN_BSTR aName, IN_BSTR aHostPath, BOOL aWritable);
167 STDMETHOD(RemoveSharedFolder) (IN_BSTR aName);
168 STDMETHOD(GetNextExtraDataKey) (IN_BSTR aKey, BSTR *aNextKey, BSTR *aNextValue);
169 STDMETHOD(GetExtraData) (IN_BSTR aKey, BSTR *aValue);
170 STDMETHOD(SetExtraData) (IN_BSTR aKey, IN_BSTR aValue);
171 STDMETHOD(OpenSession) (ISession *aSession, IN_GUID aMachineId);
172 STDMETHOD(OpenRemoteSession) (ISession *aSession, IN_GUID aMachineId,
173 IN_BSTR aType, IN_BSTR aEnvironment,
174 IProgress **aProgress);
175 STDMETHOD(OpenExistingSession) (ISession *aSession, IN_GUID aMachineId);
176
177 STDMETHOD(RegisterCallback) (IVirtualBoxCallback *aCallback);
178 STDMETHOD(UnregisterCallback) (IVirtualBoxCallback *aCallback);
179
180 STDMETHOD(WaitForPropertyChange) (IN_BSTR aWhat, ULONG aTimeout,
181 BSTR *aChanged, BSTR *aValues);
182
183 STDMETHOD(SaveSettings)();
184 STDMETHOD(SaveSettingsWithBackup) (BSTR *aBakFileName);
185
186 /* public methods only for internal purposes */
187
188 HRESULT postEvent (Event *event);
189
190 HRESULT addProgress (IProgress *aProgress);
191 HRESULT removeProgress (IN_GUID aId);
192
193#ifdef RT_OS_WINDOWS
194 typedef DECLCALLBACKPTR (HRESULT, SVCHelperClientFunc)
195 (SVCHlpClient *aClient, Progress *aProgress, void *aUser, int *aVrc);
196 HRESULT startSVCHelperClient (bool aPrivileged,
197 SVCHelperClientFunc aFunc,
198 void *aUser, Progress *aProgress);
199#endif
200
201 void addProcessToReap (RTPROCESS pid);
202 void updateClientWatcher();
203
204 void onMachineStateChange (const Guid &aId, MachineState_T aState);
205 void onMachineDataChange (const Guid &aId);
206 BOOL onExtraDataCanChange(const Guid &aId, IN_BSTR aKey, IN_BSTR aValue,
207 Bstr &aError);
208 void onExtraDataChange(const Guid &aId, IN_BSTR aKey, IN_BSTR aValue);
209 void onMachineRegistered (const Guid &aId, BOOL aRegistered);
210 void onSessionStateChange (const Guid &aId, SessionState_T aState);
211
212 void onSnapshotTaken (const Guid &aMachineId, const Guid &aSnapshotId);
213 void onSnapshotDiscarded (const Guid &aMachineId, const Guid &aSnapshotId);
214 void onSnapshotChange (const Guid &aMachineId, const Guid &aSnapshotId);
215 void onGuestPropertyChange (const Guid &aMachineId, IN_BSTR aName, IN_BSTR aValue,
216 IN_BSTR aFlags);
217
218 ComObjPtr <GuestOSType> getUnknownOSType();
219
220 void getOpenedMachines (SessionMachineVector &aMachines,
221 InternalControlVector *aControls = NULL);
222
223 /** Shortcut to #getOpenedMachines (aMachines, &aControls). */
224 void getOpenedMachinesAndControls (SessionMachineVector &aMachines,
225 InternalControlVector &aControls)
226 { getOpenedMachines (aMachines, &aControls); }
227
228 bool isMachineIdValid (const Guid &aId)
229 {
230 return SUCCEEDED (findMachine (aId, false /* aSetError */, NULL));
231 }
232
233 HRESULT findMachine (const Guid &aId, bool aSetError,
234 ComObjPtr <Machine> *machine = NULL);
235
236 HRESULT findHardDisk2 (const Guid *aId, CBSTR aLocation,
237 bool aSetError, ComObjPtr <HardDisk2> *aHardDisk = NULL);
238 HRESULT findDVDImage2 (const Guid *aId, CBSTR aLocation,
239 bool aSetError, ComObjPtr <DVDImage2> *aImage = NULL);
240 HRESULT findFloppyImage2 (const Guid *aId, CBSTR aLocation,
241 bool aSetError, ComObjPtr <FloppyImage2> *aImage = NULL);
242
243 const ComObjPtr <Host> &host() { return mData.mHost; }
244 const ComObjPtr <SystemProperties> &systemProperties()
245 { return mData.mSystemProperties; }
246#ifdef VBOX_WITH_RESOURCE_USAGE_API
247 const ComObjPtr <PerformanceCollector> &performanceCollector()
248 { return mData.mPerformanceCollector; }
249#endif /* VBOX_WITH_RESOURCE_USAGE_API */
250
251
252 /** Returns the VirtualBox home directory */
253 const Utf8Str &homeDir() { return mData.mHomeDir; }
254
255 int calculateFullPath (const char *aPath, Utf8Str &aResult);
256 void calculateRelativePath (const char *aPath, Utf8Str &aResult);
257
258 HRESULT registerHardDisk2 (HardDisk2 *aHardDisk, bool aSaveRegistry = true);
259 HRESULT unregisterHardDisk2 (HardDisk2 *aHardDisk, bool aSaveRegistry = true);
260
261 HRESULT registerDVDImage (DVDImage2 *aImage, bool aSaveRegistry = true);
262 HRESULT unregisterDVDImage (DVDImage2 *aImage, bool aSaveRegistry = true);
263
264 HRESULT registerFloppyImage (FloppyImage2 *aImage, bool aSaveRegistry = true);
265 HRESULT unregisterFloppyImage (FloppyImage2 *aImage, bool aSaveRegistry = true);
266
267 HRESULT cast (IHardDisk2 *aFrom, ComObjPtr <HardDisk2> &aTo);
268
269 HRESULT saveSettings();
270 HRESULT updateSettings (const char *aOldPath, const char *aNewPath);
271
272 const Bstr &settingsFileName() { return mData.mCfgFile.mName; }
273
274 static HRESULT ensureFilePathExists (const char *aFileName);
275
276 static HRESULT loadSettingsTree (settings::XmlTreeBackend &aTree,
277 xml::File &aFile,
278 bool aValidate,
279 bool aCatchLoadErrors,
280 bool aAddDefaults,
281 Utf8Str *aFormatVersion = NULL);
282
283 /**
284 * Shortcut to loadSettingsTree (aTree, aFile, true, true, true).
285 *
286 * Used when the settings file is to be loaded for the first time for the
287 * given object in order to recreate it from the stored settings.
288 *
289 * @param aFormatVersion Where to store the current format version of the
290 * loaded settings tree.
291 */
292 static HRESULT loadSettingsTree_FirstTime (settings::XmlTreeBackend &aTree,
293 xml::File &aFile,
294 Utf8Str &aFormatVersion)
295 {
296 return loadSettingsTree (aTree, aFile, true, true, true,
297 &aFormatVersion);
298 }
299
300 /**
301 * Shortcut to loadSettingsTree (aTree, aFile, true, false, true).
302 *
303 * Used when the settings file is loaded again (after it has been fully
304 * checked and validated by #loadSettingsTree_FirstTime()) in order to
305 * look at settings that don't have any representation within object's
306 * data fields.
307 */
308 static HRESULT loadSettingsTree_Again (settings::XmlTreeBackend &aTree,
309 xml::File &aFile)
310 {
311 return loadSettingsTree (aTree, aFile, true, false, true);
312 }
313
314 /**
315 * Shortcut to loadSettingsTree (aTree, aFile, true, false, false).
316 *
317 * Used when the settings file is loaded again (after it has been fully
318 * checked and validated by #loadSettingsTree_FirstTime()) in order to
319 * update some settings and then save them back.
320 */
321 static HRESULT loadSettingsTree_ForUpdate (settings::XmlTreeBackend &aTree,
322 xml::File &aFile)
323 {
324 return loadSettingsTree (aTree, aFile, true, false, false);
325 }
326
327 static HRESULT saveSettingsTree (settings::TreeBackend &aTree,
328 xml::File &aFile,
329 Utf8Str &aFormatVersion);
330
331 static HRESULT backupSettingsFile (const Bstr &aFileName,
332 const Utf8Str &aOldFormat,
333 Bstr &aBakFileName);
334
335 static HRESULT handleUnexpectedExceptions (RT_SRC_POS_DECL);
336
337 /**
338 * Returns a lock handle used to protect changes to the hard disk hierarchy
339 * (e.g. serialize access to the HardDisk2::mParent fields and methods
340 * adding/removing children). When using this lock, the following rules must
341 * be obeyed:
342 *
343 * 1. The write lock on this handle must be either held alone on the thread
344 * or requested *after* the VirtualBox object lock. Mixing with other
345 * locks is prohibited.
346 *
347 * 2. The read lock on this handle may be intermixed with any other lock
348 * with the exception that it must be requested *after* the VirtualBox
349 * object lock.
350 */
351 RWLockHandle *hardDiskTreeLockHandle() { return &mHardDiskTreeLockHandle; }
352
353 /* for VirtualBoxSupportErrorInfoImpl */
354 static const wchar_t *getComponentName() { return L"VirtualBox"; }
355
356private:
357
358 typedef std::list <ComObjPtr <Machine> > MachineList;
359 typedef std::list <ComObjPtr <GuestOSType> > GuestOSTypeList;
360
361 typedef std::map <Guid, ComPtr <IProgress> > ProgressMap;
362
363 typedef std::list <ComObjPtr <HardDisk2> > HardDisk2List;
364 typedef std::list <ComObjPtr <DVDImage2> > DVDImage2List;
365 typedef std::list <ComObjPtr <FloppyImage2> > FloppyImage2List;
366 typedef std::list <ComObjPtr <SharedFolder> > SharedFolderList;
367
368 typedef std::map <Guid, ComObjPtr <HardDisk2> > HardDisk2Map;
369
370 /**
371 * Reimplements VirtualBoxWithTypedChildren::childrenLock() to return a
372 * dedicated lock instead of the main object lock. The dedicated lock for
373 * child map operations frees callers of init() methods of these children
374 * from acquiring a write parent (VirtualBox) lock (which would be mandatory
375 * otherwise). Since VirtualBox has a lot of heterogenous children which
376 * init() methods are called here and there, it definitely makes sense.
377 */
378 RWLockHandle *childrenLock() { return &mChildrenMapLockHandle; }
379
380 HRESULT checkMediaForConflicts2 (const Guid &aId, const Bstr &aLocation,
381 Utf8Str &aConflictType);
382
383 HRESULT loadMachines (const settings::Key &aGlobal);
384 HRESULT loadMedia (const settings::Key &aGlobal);
385
386 HRESULT registerMachine (Machine *aMachine);
387
388 HRESULT lockConfig();
389 HRESULT unlockConfig();
390
391 /** @note This method is not thread safe */
392 bool isConfigLocked() { return mData.mCfgFile.mHandle != NIL_RTFILE; }
393
394 /**
395 * Main VirtualBox data structure.
396 * @note |const| members are persistent during lifetime so can be accessed
397 * without locking.
398 */
399 struct Data
400 {
401 Data();
402
403 struct CfgFile
404 {
405 CfgFile() : mHandle (NIL_RTFILE) {}
406
407 const Bstr mName;
408 RTFILE mHandle;
409 };
410
411 // const data members not requiring locking
412 const Utf8Str mHomeDir;
413
414 // const objects not requiring locking
415 const ComObjPtr <Host> mHost;
416 const ComObjPtr <SystemProperties> mSystemProperties;
417#ifdef VBOX_WITH_RESOURCE_USAGE_API
418 const ComObjPtr <PerformanceCollector> mPerformanceCollector;
419#endif /* VBOX_WITH_RESOURCE_USAGE_API */
420
421 CfgFile mCfgFile;
422
423 Utf8Str mSettingsFileVersion;
424
425 MachineList mMachines;
426 GuestOSTypeList mGuestOSTypes;
427
428 ProgressMap mProgressOperations;
429
430 HardDisk2List mHardDisks2;
431 DVDImage2List mDVDImages2;
432 FloppyImage2List mFloppyImages2;
433 SharedFolderList mSharedFolders;
434
435 /// @todo NEWMEDIA do we really need this map? Used only in
436 /// find() it seems
437 HardDisk2Map mHardDisk2Map;
438
439 CallbackList mCallbacks;
440 };
441
442 Data mData;
443
444 /** Client watcher thread data structure */
445 struct ClientWatcherData
446 {
447 ClientWatcherData()
448#if defined(RT_OS_WINDOWS)
449 : mUpdateReq (NULL)
450#elif defined(RT_OS_OS2)
451 : mUpdateReq (NIL_RTSEMEVENT)
452#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
453 : mUpdateReq (NIL_RTSEMEVENT)
454#else
455# error "Port me!"
456#endif
457 , mThread (NIL_RTTHREAD) {}
458
459 // const objects not requiring locking
460#if defined(RT_OS_WINDOWS)
461 const HANDLE mUpdateReq;
462#elif defined(RT_OS_OS2)
463 const RTSEMEVENT mUpdateReq;
464#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
465 const RTSEMEVENT mUpdateReq;
466#else
467# error "Port me!"
468#endif
469 const RTTHREAD mThread;
470
471 typedef std::list <RTPROCESS> ProcessList;
472 ProcessList mProcesses;
473 };
474
475 ClientWatcherData mWatcherData;
476
477 const RTTHREAD mAsyncEventThread;
478 EventQueue * const mAsyncEventQ;
479
480 /**
481 * "Safe" lock. May only be used if guaranteed that no other locks are
482 * requested while holding it and no functions that may do so are called.
483 * Currently, protects the following:
484 *
485 * - mProgressOperations
486 */
487 RWLockHandle mSafeLock;
488
489 RWLockHandle mHardDiskTreeLockHandle;
490 RWLockHandle mChildrenMapLockHandle;
491
492 static Bstr sVersion;
493 static ULONG sRevision;
494 static Bstr sPackageType;
495 static Bstr sSettingsFormatVersion;
496
497 static DECLCALLBACK(int) ClientWatcher (RTTHREAD thread, void *pvUser);
498 static DECLCALLBACK(int) AsyncEventHandler (RTTHREAD thread, void *pvUser);
499
500#ifdef RT_OS_WINDOWS
501 static DECLCALLBACK(int) SVCHelperClientThread (RTTHREAD aThread, void *aUser);
502#endif
503};
504
505////////////////////////////////////////////////////////////////////////////////
506
507/**
508 * Abstract callback event class to asynchronously call VirtualBox callbacks
509 * on a dedicated event thread. Subclasses reimplement #handleCallback()
510 * to call appropriate IVirtualBoxCallback methods depending on the event
511 * to be dispatched.
512 *
513 * @note The VirtualBox instance passed to the constructor is strongly
514 * referenced, so that the VirtualBox singleton won't be released until the
515 * event gets handled by the event thread.
516 */
517class VirtualBox::CallbackEvent : public Event
518{
519public:
520
521 CallbackEvent (VirtualBox *aVirtualBox) : mVirtualBox (aVirtualBox)
522 {
523 Assert (aVirtualBox);
524 }
525
526 void *handler();
527
528 virtual void handleCallback (const ComPtr <IVirtualBoxCallback> &aCallback) = 0;
529
530private:
531
532 /*
533 * Note that this is a weak ref -- the CallbackEvent handler thread
534 * is bound to the lifetime of the VirtualBox instance, so it's safe.
535 */
536 ComObjPtr <VirtualBox, ComWeakRef> mVirtualBox;
537};
538
539#endif // ____H_VIRTUALBOXIMPL
540/* vi: set tabstop=4 shiftwidth=4 expandtab: */
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use