VirtualBox

source: vbox/trunk/src/VBox/Main/include/VirtualBoxBase.h@ 30760

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

Main: separate internal machine data structs into MachineImplPrivate.h to significantly speed up compilation and for better interface separation; remove obsolete ConsoleEvents.h file

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 41.1 KB
Line 
1/** @file
2 * VirtualBox COM base classes definition
3 */
4
5/*
6 * Copyright (C) 2006-2010 Oracle Corporation
7 *
8 * This file is part of VirtualBox Open Source Edition (OSE), as
9 * available from http://www.215389.xyz. This file is free software;
10 * you can redistribute it and/or modify it under the terms of the GNU
11 * General Public License (GPL) as published by the Free Software
12 * Foundation, in version 2 as it comes in the "COPYING" file of the
13 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
14 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
15 */
16
17#ifndef ____H_VIRTUALBOXBASEIMPL
18#define ____H_VIRTUALBOXBASEIMPL
19
20#include <iprt/cdefs.h>
21#include <iprt/thread.h>
22
23#include <list>
24#include <map>
25
26#include "VBox/com/AutoLock.h"
27#include "VBox/com/string.h"
28#include "VBox/com/Guid.h"
29
30#include "VBox/com/VirtualBox.h"
31
32// empty-declare a bunch of classes that are commonly used in VirtualBox
33// headers; this avoids having to include all the headers in every
34// single implementation .cpp file
35
36namespace xml
37{
38 class ElementNode;
39 class File;
40}
41
42using namespace com;
43using namespace util;
44
45class AutoInitSpan;
46class AutoUninitSpan;
47
48class AudioSniffer;
49class AudioAdapter;
50class Appliance;
51class BIOSSettings;
52class Console;
53class ConsoleCallbackRegistration;
54class ConsoleVRDPServer;
55class DHCPServer;
56class Display;
57class Guest;
58class GuestOSType;
59class Host;
60class HostUSBDevice;
61class HostUSBDeviceFilter;
62class Keyboard;
63class Machine;
64class MachineDebugger;
65class Medium;
66class MediumAttachment;
67class MediumFormat;
68class MediumLockList;
69class Mouse;
70class NetworkAdapter;
71class NATEngine;
72class OUSBDevice;
73class ParallelPort;
74class PerformanceCollector;
75class Progress;
76class ProgressProxy;
77class RemoteDisplayInfo;
78class RemoteUSBDevice;
79class SerialPort;
80class SessionMachine;
81class SharedFolder;
82class Snapshot;
83class SnapshotMachine;
84class StorageController;
85class SystemProperties;
86class USBController;
87class USBDeviceFilter;
88class USBProxyService;
89class TeleporterStateSrc;
90class VMMDev;
91class VirtualBox;
92class VirtualSystemDescription;
93struct VirtualSystemDescriptionEntry;
94class VRDPServer;
95
96typedef std::list< ComObjPtr<Medium> > MediaList;
97typedef std::list< ComObjPtr<MediumAttachment> > MediumAttachmentsList;
98
99namespace settings
100{
101 struct AudioAdapter;
102 struct Hardware;
103 struct Host;
104 class MainConfigFile;
105 class MachineConfigFile;
106 struct MachineRegistryEntry;
107 struct Medium;
108 struct NAT;
109 struct NetworkAdapter;
110 struct ParallelPort;
111 struct SerialPort;
112 struct Snapshot;
113 struct Storage;
114 struct StorageController;
115 struct SystemProperties;
116 struct USBController;
117}
118
119namespace pm
120{
121 class Metric;
122 class BaseMetric;
123 class CollectorHAL;
124 class CollectorGuestHAL;
125}
126
127////////////////////////////////////////////////////////////////////////////////
128//
129// COM helpers
130//
131////////////////////////////////////////////////////////////////////////////////
132
133#if !defined (VBOX_WITH_XPCOM)
134
135#include <atlcom.h>
136
137/* use a special version of the singleton class factory,
138 * see KB811591 in msdn for more info. */
139
140#undef DECLARE_CLASSFACTORY_SINGLETON
141#define DECLARE_CLASSFACTORY_SINGLETON(obj) DECLARE_CLASSFACTORY_EX(CMyComClassFactorySingleton<obj>)
142
143template <class T>
144class CMyComClassFactorySingleton : public CComClassFactory
145{
146public:
147 CMyComClassFactorySingleton() : m_hrCreate(S_OK){}
148 virtual ~CMyComClassFactorySingleton(){}
149 // IClassFactory
150 STDMETHOD(CreateInstance)(LPUNKNOWN pUnkOuter, REFIID riid, void** ppvObj)
151 {
152 HRESULT hRes = E_POINTER;
153 if (ppvObj != NULL)
154 {
155 *ppvObj = NULL;
156 // Aggregation is not supported in singleton objects.
157 ATLASSERT(pUnkOuter == NULL);
158 if (pUnkOuter != NULL)
159 hRes = CLASS_E_NOAGGREGATION;
160 else
161 {
162 if (m_hrCreate == S_OK && m_spObj == NULL)
163 {
164 Lock();
165 __try
166 {
167 // Fix: The following If statement was moved inside the __try statement.
168 // Did another thread arrive here first?
169 if (m_hrCreate == S_OK && m_spObj == NULL)
170 {
171 // lock the module to indicate activity
172 // (necessary for the monitor shutdown thread to correctly
173 // terminate the module in case when CreateInstance() fails)
174 _pAtlModule->Lock();
175 CComObjectCached<T> *p;
176 m_hrCreate = CComObjectCached<T>::CreateInstance(&p);
177 if (SUCCEEDED(m_hrCreate))
178 {
179 m_hrCreate = p->QueryInterface(IID_IUnknown, (void**)&m_spObj);
180 if (FAILED(m_hrCreate))
181 {
182 delete p;
183 }
184 }
185 _pAtlModule->Unlock();
186 }
187 }
188 __finally
189 {
190 Unlock();
191 }
192 }
193 if (m_hrCreate == S_OK)
194 {
195 hRes = m_spObj->QueryInterface(riid, ppvObj);
196 }
197 else
198 {
199 hRes = m_hrCreate;
200 }
201 }
202 }
203 return hRes;
204 }
205 HRESULT m_hrCreate;
206 CComPtr<IUnknown> m_spObj;
207};
208
209#endif /* !defined (VBOX_WITH_XPCOM) */
210
211////////////////////////////////////////////////////////////////////////////////
212//
213// Macros
214//
215////////////////////////////////////////////////////////////////////////////////
216
217#ifndef DEBUG
218 // the following two are defined in glue/errorprint.cpp because they are included
219 // in the ComAssert macro below thousands of times in release builds
220extern const char *g_pcszComAssertFailedString;
221 // "Assertion failed: [%s] at '%s' (%d) in %s.\nPlease contact the product vendor!"
222extern const char *g_pcszComAssertMsgFailedString;
223 // "Assertion failed: [%s] at '%s' (%d) in %s.\n%s\nPlease contact the product vendor!"
224#endif
225
226/**
227 * Special version of the Assert macro to be used within VirtualBoxBase
228 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
229 *
230 * In the debug build, this macro is equivalent to Assert.
231 * In the release build, this macro uses |setError(E_FAIL, ...)| to set the
232 * error info from the asserted expression.
233 *
234 * @see VirtualBoxSupportErrorInfoImpl::setError
235 *
236 * @param expr Expression which should be true.
237 */
238#if defined (DEBUG)
239#define ComAssert(expr) Assert(expr)
240#else
241#define ComAssert(expr) \
242 do { \
243 if (RT_UNLIKELY(!(expr))) \
244 setError(E_FAIL, \
245 g_pcszComAssertFailedString, \
246 #expr, __FILE__, __LINE__, __PRETTY_FUNCTION__); \
247 } while (0)
248#endif
249
250/**
251 * Special version of the AssertMsg macro to be used within VirtualBoxBase
252 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
253 *
254 * See ComAssert for more info.
255 *
256 * @param expr Expression which should be true.
257 * @param a printf argument list (in parenthesis).
258 */
259#if defined (DEBUG)
260#define ComAssertMsg(expr, a) AssertMsg(expr, a)
261#else
262#define ComAssertMsg(expr, a) \
263 do { \
264 if (RT_UNLIKELY(!(expr))) \
265 setError(E_FAIL, \
266 g_pcszComAssertMsgFailedString, \
267 #expr, __FILE__, __LINE__, __PRETTY_FUNCTION__, Utf8StrFmt a .c_str()); \
268 } while (0)
269#endif
270
271/**
272 * Special version of the AssertRC macro to be used within VirtualBoxBase
273 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
274 *
275 * See ComAssert for more info.
276 *
277 * @param vrc VBox status code.
278 */
279#if defined (DEBUG)
280#define ComAssertRC(vrc) AssertRC(vrc)
281#else
282#define ComAssertRC(vrc) ComAssertMsgRC(vrc, ("%Rra", vrc))
283#endif
284
285/**
286 * Special version of the AssertMsgRC macro to be used within VirtualBoxBase
287 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
288 *
289 * See ComAssert for more info.
290 *
291 * @param vrc VBox status code.
292 * @param msg printf argument list (in parenthesis).
293 */
294#if defined (DEBUG)
295#define ComAssertMsgRC(vrc, msg) AssertMsgRC(vrc, msg)
296#else
297#define ComAssertMsgRC(vrc, msg) ComAssertMsg(RT_SUCCESS(vrc), msg)
298#endif
299
300/**
301 * Special version of the AssertComRC macro to be used within VirtualBoxBase
302 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
303 *
304 * See ComAssert for more info.
305 *
306 * @param rc COM result code
307 */
308#if defined (DEBUG)
309#define ComAssertComRC(rc) AssertComRC(rc)
310#else
311#define ComAssertComRC(rc) ComAssertMsg(SUCCEEDED(rc), ("COM RC = %Rhrc (0x%08X)", (rc), (rc)))
312#endif
313
314
315/** Special version of ComAssert that returns ret if expr fails */
316#define ComAssertRet(expr, ret) \
317 do { ComAssert(expr); if (!(expr)) return (ret); } while (0)
318/** Special version of ComAssertMsg that returns ret if expr fails */
319#define ComAssertMsgRet(expr, a, ret) \
320 do { ComAssertMsg(expr, a); if (!(expr)) return (ret); } while (0)
321/** Special version of ComAssertRC that returns ret if vrc does not succeed */
322#define ComAssertRCRet(vrc, ret) \
323 do { ComAssertRC(vrc); if (!RT_SUCCESS(vrc)) return (ret); } while (0)
324/** Special version of ComAssertComRC that returns ret if rc does not succeed */
325#define ComAssertComRCRet(rc, ret) \
326 do { ComAssertComRC(rc); if (!SUCCEEDED(rc)) return (ret); } while (0)
327/** Special version of ComAssertComRC that returns rc if rc does not succeed */
328#define ComAssertComRCRetRC(rc) \
329 do { ComAssertComRC(rc); if (!SUCCEEDED(rc)) return (rc); } while (0)
330
331
332/** Special version of ComAssert that evaluates eval and breaks if expr fails */
333#define ComAssertBreak(expr, eval) \
334 if (1) { ComAssert(expr); if (!(expr)) { eval; break; } } else do {} while (0)
335/** Special version of ComAssertMsg that evaluates eval and breaks if expr fails */
336#define ComAssertMsgBreak(expr, a, eval) \
337 if (1) { ComAssertMsg(expr, a); if (!(expr)) { eval; break; } } else do {} while (0)
338/** Special version of ComAssertRC that evaluates eval and breaks if vrc does not succeed */
339#define ComAssertRCBreak(vrc, eval) \
340 if (1) { ComAssertRC(vrc); if (!RT_SUCCESS(vrc)) { eval; break; } } else do {} while (0)
341/** Special version of ComAssertFailed that evaluates eval and breaks */
342#define ComAssertFailedBreak(eval) \
343 if (1) { ComAssertFailed(); { eval; break; } } else do {} while (0)
344/** Special version of ComAssertMsgFailed that evaluates eval and breaks */
345#define ComAssertMsgFailedBreak(msg, eval) \
346 if (1) { ComAssertMsgFailed (msg); { eval; break; } } else do {} while (0)
347/** Special version of ComAssertComRC that evaluates eval and breaks if rc does not succeed */
348#define ComAssertComRCBreak(rc, eval) \
349 if (1) { ComAssertComRC(rc); if (!SUCCEEDED(rc)) { eval; break; } } else do {} while (0)
350/** Special version of ComAssertComRC that just breaks if rc does not succeed */
351#define ComAssertComRCBreakRC(rc) \
352 if (1) { ComAssertComRC(rc); if (!SUCCEEDED(rc)) { break; } } else do {} while (0)
353
354
355/** Special version of ComAssert that evaluates eval and throws it if expr fails */
356#define ComAssertThrow(expr, eval) \
357 if (1) { ComAssert(expr); if (!(expr)) { throw (eval); } } else do {} while (0)
358/** Special version of ComAssertRC that evaluates eval and throws it if vrc does not succeed */
359#define ComAssertRCThrow(vrc, eval) \
360 if (1) { ComAssertRC(vrc); if (!RT_SUCCESS(vrc)) { throw (eval); } } else do {} while (0)
361/** Special version of ComAssertComRC that evaluates eval and throws it if rc does not succeed */
362#define ComAssertComRCThrow(rc, eval) \
363 if (1) { ComAssertComRC(rc); if (!SUCCEEDED(rc)) { throw (eval); } } else do {} while (0)
364/** Special version of ComAssertComRC that just throws rc if rc does not succeed */
365#define ComAssertComRCThrowRC(rc) \
366 if (1) { ComAssertComRC(rc); if (!SUCCEEDED(rc)) { throw rc; } } else do {} while (0)
367
368////////////////////////////////////////////////////////////////////////////////
369
370/**
371 * Checks that the pointer argument is not NULL and returns E_INVALIDARG +
372 * extended error info on failure.
373 * @param arg Input pointer-type argument (strings, interface pointers...)
374 */
375#define CheckComArgNotNull(arg) \
376 do { \
377 if (RT_UNLIKELY((arg) == NULL)) \
378 return setError(E_INVALIDARG, tr("Argument %s is NULL"), #arg); \
379 } while (0)
380
381/**
382 * Checks that safe array argument is not NULL and returns E_INVALIDARG +
383 * extended error info on failure.
384 * @param arg Input safe array argument (strings, interface pointers...)
385 */
386#define CheckComArgSafeArrayNotNull(arg) \
387 do { \
388 if (RT_UNLIKELY(ComSafeArrayInIsNull(arg))) \
389 return setError(E_INVALIDARG, tr("Argument %s is NULL"), #arg); \
390 } while (0)
391
392/**
393 * Checks that the string argument is not a NULL or empty string and returns
394 * E_INVALIDARG + extended error info on failure.
395 * @param arg Input string argument (BSTR etc.).
396 */
397#define CheckComArgStrNotEmptyOrNull(arg) \
398 do { \
399 if (RT_UNLIKELY((arg) == NULL || *(arg) == '\0')) \
400 return setError(E_INVALIDARG, \
401 tr("Argument %s is empty or NULL"), #arg); \
402 } while (0)
403
404/**
405 * Checks that the given expression (that must involve the argument) is true and
406 * returns E_INVALIDARG + extended error info on failure.
407 * @param arg Argument.
408 * @param expr Expression to evaluate.
409 */
410#define CheckComArgExpr(arg, expr) \
411 do { \
412 if (RT_UNLIKELY(!(expr))) \
413 return setError(E_INVALIDARG, \
414 tr("Argument %s is invalid (must be %s)"), #arg, #expr); \
415 } while (0)
416
417/**
418 * Checks that the given expression (that must involve the argument) is true and
419 * returns E_INVALIDARG + extended error info on failure. The error message must
420 * be customized.
421 * @param arg Argument.
422 * @param expr Expression to evaluate.
423 * @param msg Parenthesized printf-like expression (must start with a verb,
424 * like "must be one of...", "is not within...").
425 */
426#define CheckComArgExprMsg(arg, expr, msg) \
427 do { \
428 if (RT_UNLIKELY(!(expr))) \
429 return setError(E_INVALIDARG, tr ("Argument %s %s"), \
430 #arg, Utf8StrFmt msg .raw()); \
431 } while (0)
432
433/**
434 * Checks that the given pointer to an output argument is valid and returns
435 * E_POINTER + extended error info otherwise.
436 * @param arg Pointer argument.
437 */
438#define CheckComArgOutPointerValid(arg) \
439 do { \
440 if (RT_UNLIKELY(!VALID_PTR(arg))) \
441 return setError(E_POINTER, \
442 tr("Output argument %s points to invalid memory location (%p)"), \
443 #arg, (void *) (arg)); \
444 } while (0)
445
446/**
447 * Checks that the given pointer to an output safe array argument is valid and
448 * returns E_POINTER + extended error info otherwise.
449 * @param arg Safe array argument.
450 */
451#define CheckComArgOutSafeArrayPointerValid(arg) \
452 do { \
453 if (RT_UNLIKELY(ComSafeArrayOutIsNull(arg))) \
454 return setError(E_POINTER, \
455 tr("Output argument %s points to invalid memory location (%p)"), \
456 #arg, (void*)(arg)); \
457 } while (0)
458
459/**
460 * Sets the extended error info and returns E_NOTIMPL.
461 */
462#define ReturnComNotImplemented() \
463 do { \
464 return setError(E_NOTIMPL, tr("Method %s is not implemented"), __FUNCTION__); \
465 } while (0)
466
467/**
468 * Declares an empty constructor and destructor for the given class.
469 * This is useful to prevent the compiler from generating the default
470 * ctor and dtor, which in turn allows to use forward class statements
471 * (instead of including their header files) when declaring data members of
472 * non-fundamental types with constructors (which are always called implicitly
473 * by constructors and by the destructor of the class).
474 *
475 * This macro is to be placed within (the public section of) the class
476 * declaration. Its counterpart, DEFINE_EMPTY_CTOR_DTOR, must be placed
477 * somewhere in one of the translation units (usually .cpp source files).
478 *
479 * @param cls class to declare a ctor and dtor for
480 */
481#define DECLARE_EMPTY_CTOR_DTOR(cls) cls(); ~cls();
482
483/**
484 * Defines an empty constructor and destructor for the given class.
485 * See DECLARE_EMPTY_CTOR_DTOR for more info.
486 */
487#define DEFINE_EMPTY_CTOR_DTOR(cls) \
488 cls::cls() { /*empty*/ } \
489 cls::~cls() { /*empty*/ }
490
491/**
492 * Parent class of VirtualBoxBase which enables translation support (which
493 * Main doesn't have yet, but this provides the tr() function which will one
494 * day provide translations).
495 *
496 * This class sits in between Lockable and VirtualBoxBase only for the one
497 * reason that the USBProxyService wants translation support but is not
498 * implemented as a COM object, which VirtualBoxBase implies.
499 */
500class ATL_NO_VTABLE VirtualBoxTranslatable
501 : public Lockable
502{
503public:
504
505 /**
506 * Placeholder method with which translations can one day be implemented
507 * in Main. This gets called by the tr() function.
508 * @param context
509 * @param pcszSourceText
510 * @param comment
511 * @return
512 */
513 static const char *translate(const char *context,
514 const char *pcszSourceText,
515 const char *comment = 0)
516 {
517 NOREF(context);
518 NOREF(comment);
519 return pcszSourceText;
520 }
521
522 /**
523 * Translates the given text string by calling translate() and passing
524 * the name of the C class as the first argument ("context of
525 * translation"). See VirtualBoxBase::translate() for more info.
526 *
527 * @param aSourceText String to translate.
528 * @param aComment Comment to the string to resolve possible
529 * ambiguities (NULL means no comment).
530 *
531 * @return Translated version of the source string in UTF-8 encoding, or
532 * the source string itself if the translation is not found in the
533 * specified context.
534 */
535 inline static const char *tr(const char *pcszSourceText,
536 const char *aComment = NULL)
537 {
538 return VirtualBoxTranslatable::translate(NULL, // getComponentName(), eventually
539 pcszSourceText,
540 aComment);
541 }
542};
543
544////////////////////////////////////////////////////////////////////////////////
545//
546// VirtualBoxBase
547//
548////////////////////////////////////////////////////////////////////////////////
549
550#define VIRTUALBOXBASE_ADD_VIRTUAL_COMPONENT_METHODS(cls, iface) \
551 virtual const IID& getClassIID() const \
552 { \
553 return cls::getStaticClassIID(); \
554 } \
555 static const IID& getStaticClassIID() \
556 { \
557 return COM_IIDOF(iface); \
558 } \
559 virtual const char* getComponentName() const \
560 { \
561 return cls::getStaticComponentName(); \
562 } \
563 static const char* getStaticComponentName() \
564 { \
565 return #cls; \
566 }
567
568/**
569 * VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT:
570 * This macro must be used once in the declaration of any class derived
571 * from VirtualBoxBase. It implements the pure virtual getClassIID() and
572 * getComponentName() methods. If this macro is not present, instances
573 * of a class derived from VirtualBoxBase cannot be instantiated.
574 *
575 * @param X The class name, e.g. "Class".
576 * @param IX The interface name which this class implements, e.g. "IClass".
577 */
578#ifdef VBOX_WITH_XPCOM
579 #define VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT(cls, iface) \
580 VIRTUALBOXBASE_ADD_VIRTUAL_COMPONENT_METHODS(cls, iface)
581#else // #ifdef VBOX_WITH_XPCOM
582 #define VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT(cls, iface) \
583 VIRTUALBOXBASE_ADD_VIRTUAL_COMPONENT_METHODS(cls, iface) \
584 STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid) \
585 { \
586 const _ATL_INTMAP_ENTRY* pEntries = cls::_GetEntries(); \
587 Assert(pEntries); \
588 if (!pEntries) \
589 return S_FALSE; \
590 BOOL bSupports = FALSE; \
591 BOOL bISupportErrorInfoFound = FALSE; \
592 while (pEntries->pFunc != NULL && !bSupports) \
593 { \
594 if (!bISupportErrorInfoFound) \
595 bISupportErrorInfoFound = InlineIsEqualGUID(*(pEntries->piid), IID_ISupportErrorInfo); \
596 else \
597 bSupports = InlineIsEqualGUID(*(pEntries->piid), riid); \
598 pEntries++; \
599 } \
600 Assert(bISupportErrorInfoFound); \
601 return bSupports ? S_OK : S_FALSE; \
602 }
603#endif // #ifdef VBOX_WITH_XPCOM
604
605/**
606 * Abstract base class for all component classes implementing COM
607 * interfaces of the VirtualBox COM library.
608 *
609 * Declares functionality that should be available in all components.
610 *
611 * Among the basic functionality implemented by this class is the primary object
612 * state that indicates if the object is ready to serve the calls, and if not,
613 * what stage it is currently at. Here is the primary state diagram:
614 *
615 * +-------------------------------------------------------+
616 * | |
617 * | (InitFailed) -----------------------+ |
618 * | ^ | |
619 * v | v |
620 * [*] ---> NotReady ----> (InInit) -----> Ready -----> (InUninit) ----+
621 * ^ |
622 * | v
623 * | Limited
624 * | |
625 * +-------+
626 *
627 * The object is fully operational only when its state is Ready. The Limited
628 * state means that only some vital part of the object is operational, and it
629 * requires some sort of reinitialization to become fully operational. The
630 * NotReady state means the object is basically dead: it either was not yet
631 * initialized after creation at all, or was uninitialized and is waiting to be
632 * destroyed when the last reference to it is released. All other states are
633 * transitional.
634 *
635 * The NotReady->InInit->Ready, NotReady->InInit->Limited and
636 * NotReady->InInit->InitFailed transition is done by the AutoInitSpan smart
637 * class.
638 *
639 * The Limited->InInit->Ready, Limited->InInit->Limited and
640 * Limited->InInit->InitFailed transition is done by the AutoReinitSpan smart
641 * class.
642 *
643 * The Ready->InUninit->NotReady and InitFailed->InUninit->NotReady
644 * transitions are done by the AutoUninitSpan smart class.
645 *
646 * In order to maintain the primary state integrity and declared functionality
647 * all subclasses must:
648 *
649 * 1) Use the above Auto*Span classes to perform state transitions. See the
650 * individual class descriptions for details.
651 *
652 * 2) All public methods of subclasses (i.e. all methods that can be called
653 * directly, not only from within other methods of the subclass) must have a
654 * standard prolog as described in the AutoCaller and AutoLimitedCaller
655 * documentation. Alternatively, they must use addCaller()/releaseCaller()
656 * directly (and therefore have both the prolog and the epilog), but this is
657 * not recommended.
658 */
659class ATL_NO_VTABLE VirtualBoxBase
660 : public VirtualBoxTranslatable,
661 public CComObjectRootEx<CComMultiThreadModel>
662#if !defined (VBOX_WITH_XPCOM)
663 , public ISupportErrorInfo
664#endif
665{
666public:
667 enum State { NotReady, Ready, InInit, InUninit, InitFailed, Limited };
668
669 VirtualBoxBase();
670 virtual ~VirtualBoxBase();
671
672 /**
673 * Unintialization method.
674 *
675 * Must be called by all final implementations (component classes) when the
676 * last reference to the object is released, before calling the destructor.
677 *
678 * This method is also automatically called by the uninit() method of this
679 * object's parent if this object is a dependent child of a class derived
680 * from VirtualBoxBaseWithChildren (see
681 * VirtualBoxBaseWithChildren::addDependentChild).
682 *
683 * @note Never call this method the AutoCaller scope or after the
684 * #addCaller() call not paired by #releaseCaller() because it is a
685 * guaranteed deadlock. See AutoUninitSpan for details.
686 */
687 virtual void uninit()
688 { }
689
690 virtual HRESULT addCaller(State *aState = NULL,
691 bool aLimited = false);
692 virtual void releaseCaller();
693
694 /**
695 * Adds a limited caller. This method is equivalent to doing
696 * <tt>addCaller (aState, true)</tt>, but it is preferred because provides
697 * better self-descriptiveness. See #addCaller() for more info.
698 */
699 HRESULT addLimitedCaller(State *aState = NULL)
700 {
701 return addCaller(aState, true /* aLimited */);
702 }
703
704 /**
705 * Pure virtual method for simple run-time type identification without
706 * having to enable C++ RTTI.
707 *
708 * This *must* be implemented by every subclass deriving from VirtualBoxBase;
709 * use the VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT macro to do that most easily.
710 */
711 virtual const IID& getClassIID() const = 0;
712
713 /**
714 * Pure virtual method for simple run-time type identification without
715 * having to enable C++ RTTI.
716 *
717 * This *must* be implemented by every subclass deriving from VirtualBoxBase;
718 * use the VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT macro to do that most easily.
719 */
720 virtual const char* getComponentName() const = 0;
721
722 /**
723 * Virtual method which determins the locking class to be used for validating
724 * lock order with the standard member lock handle. This method is overridden
725 * in a number of subclasses.
726 */
727 virtual VBoxLockingClass getLockingClass() const
728 {
729 return LOCKCLASS_OTHEROBJECT;
730 }
731
732 virtual RWLockHandle *lockHandle() const;
733
734 /**
735 * Returns a lock handle used to protect the primary state fields (used by
736 * #addCaller(), AutoInitSpan, AutoUninitSpan, etc.). Only intended to be
737 * used for similar purposes in subclasses. WARNING: NO any other locks may
738 * be requested while holding this lock!
739 */
740 WriteLockHandle *stateLockHandle() { return &mStateLock; }
741
742 static HRESULT setErrorInternal(HRESULT aResultCode,
743 const GUID &aIID,
744 const char *aComponent,
745 const Utf8Str &aText,
746 bool aWarning,
747 bool aLogIt);
748
749 HRESULT setError(HRESULT aResultCode, const char *pcsz, ...);
750 HRESULT setWarning(HRESULT aResultCode, const char *pcsz, ...);
751 HRESULT setErrorNoLog(HRESULT aResultCode, const char *pcsz, ...);
752
753private:
754
755 void setState(State aState)
756 {
757 Assert(mState != aState);
758 mState = aState;
759 mStateChangeThread = RTThreadSelf();
760 }
761
762 /** Primary state of this object */
763 State mState;
764 /** Thread that caused the last state change */
765 RTTHREAD mStateChangeThread;
766 /** Total number of active calls to this object */
767 unsigned mCallers;
768 /** Posted when the number of callers drops to zero */
769 RTSEMEVENT mZeroCallersSem;
770 /** Posted when the object goes from InInit/InUninit to some other state */
771 RTSEMEVENTMULTI mInitUninitSem;
772 /** Number of threads waiting for mInitUninitDoneSem */
773 unsigned mInitUninitWaiters;
774
775 /** Protects access to state related data members */
776 WriteLockHandle mStateLock;
777
778 /** User-level object lock for subclasses */
779 mutable RWLockHandle *mObjectLock;
780
781 friend class AutoInitSpan;
782 friend class AutoReinitSpan;
783 friend class AutoUninitSpan;
784};
785
786/**
787 * Dummy macro that is used to shut down Qt's lupdate tool warnings in some
788 * situations. This macro needs to be present inside (better at the very
789 * beginning) of the declaration of the class that inherits from
790 * VirtualBoxSupportTranslation template, to make lupdate happy.
791 */
792#define Q_OBJECT
793
794////////////////////////////////////////////////////////////////////////////////
795
796/**
797 * Base class to track VirtualBoxBaseNEXT chlidren of the component.
798 *
799 * This class is a preferrable VirtualBoxBase replacement for components that
800 * operate with collections of child components. It gives two useful
801 * possibilities:
802 *
803 * <ol><li>
804 * Given an IUnknown instance, it's possible to quickly determine
805 * whether this instance represents a child object that belongs to the
806 * given component, and if so, get a valid VirtualBoxBase pointer to the
807 * child object. The returned pointer can be then safely casted to the
808 * actual class of the child object (to get access to its "internal"
809 * non-interface methods) provided that no other child components implement
810 * the same original COM interface IUnknown is queried from.
811 * </li><li>
812 * When the parent object uninitializes itself, it can easily unintialize
813 * all its VirtualBoxBase derived children (using their
814 * VirtualBoxBase::uninit() implementations). This is done simply by
815 * calling the #uninitDependentChildren() method.
816 * </li></ol>
817 *
818 * In order to let the above work, the following must be done:
819 * <ol><li>
820 * When a child object is initialized, it calls #addDependentChild() of
821 * its parent to register itself within the list of dependent children.
822 * </li><li>
823 * When the child object it is uninitialized, it calls
824 * #removeDependentChild() to unregister itself.
825 * </li></ol>
826 *
827 * Note that if the parent object does not call #uninitDependentChildren() when
828 * it gets uninitialized, it must call uninit() methods of individual children
829 * manually to disconnect them; a failure to do so will cause crashes in these
830 * methods when children get destroyed. The same applies to children not calling
831 * #removeDependentChild() when getting destroyed.
832 *
833 * Note that children added by #addDependentChild() are <b>weakly</b> referenced
834 * (i.e. AddRef() is not called), so when a child object is deleted externally
835 * (because it's reference count goes to zero), it will automatically remove
836 * itself from the map of dependent children provided that it follows the rules
837 * described here.
838 *
839 * Access to the child list is serialized using the #childrenLock() lock handle
840 * (which defaults to the general object lock handle (see
841 * VirtualBoxBase::lockHandle()). This lock is used by all add/remove methods of
842 * this class so be aware of the need to preserve the {parent, child} lock order
843 * when calling these methods.
844 *
845 * Read individual method descriptions to get further information.
846 *
847 * @todo This is a VirtualBoxBaseWithChildren equivalent that uses the
848 * VirtualBoxBaseNEXT implementation. Will completely supersede
849 * VirtualBoxBaseWithChildren after the old VirtualBoxBase implementation
850 * has gone.
851 */
852class VirtualBoxBaseWithChildrenNEXT : public VirtualBoxBase
853{
854public:
855
856 VirtualBoxBaseWithChildrenNEXT()
857 {}
858
859 virtual ~VirtualBoxBaseWithChildrenNEXT()
860 {}
861
862 /**
863 * Lock handle to use when adding/removing child objects from the list of
864 * children. It is guaranteed that no any other lock is requested in methods
865 * of this class while holding this lock.
866 *
867 * @warning By default, this simply returns the general object's lock handle
868 * (see VirtualBoxBase::lockHandle()) which is sufficient for most
869 * cases.
870 */
871 virtual RWLockHandle *childrenLock() { return lockHandle(); }
872
873 /**
874 * Adds the given child to the list of dependent children.
875 *
876 * Usually gets called from the child's init() method.
877 *
878 * @note @a aChild (unless it is in InInit state) must be protected by
879 * VirtualBoxBase::AutoCaller to make sure it is not uninitialized on
880 * another thread during this method's call.
881 *
882 * @note When #childrenLock() is not overloaded (returns the general object
883 * lock) and this method is called from under the child's read or
884 * write lock, make sure the {parent, child} locking order is
885 * preserved by locking the callee (this object) for writing before
886 * the child's lock.
887 *
888 * @param aChild Child object to add (must inherit VirtualBoxBase AND
889 * implement some interface).
890 *
891 * @note Locks #childrenLock() for writing.
892 */
893 template<class C>
894 void addDependentChild(C *aChild)
895 {
896 AssertReturnVoid(aChild != NULL);
897 doAddDependentChild(ComPtr<IUnknown>(aChild), aChild);
898 }
899
900 /**
901 * Equivalent to template <class C> void addDependentChild (C *aChild)
902 * but takes a ComObjPtr<C> argument.
903 */
904 template<class C>
905 void addDependentChild(const ComObjPtr<C> &aChild)
906 {
907 AssertReturnVoid(!aChild.isNull());
908 doAddDependentChild(ComPtr<IUnknown>(static_cast<C *>(aChild)), aChild);
909 }
910
911 /**
912 * Removes the given child from the list of dependent children.
913 *
914 * Usually gets called from the child's uninit() method.
915 *
916 * Keep in mind that the called (parent) object may be no longer available
917 * (i.e. may be deleted deleted) after this method returns, so you must not
918 * call any other parent's methods after that!
919 *
920 * @note Locks #childrenLock() for writing.
921 *
922 * @note @a aChild (unless it is in InUninit state) must be protected by
923 * VirtualBoxBase::AutoCaller to make sure it is not uninitialized on
924 * another thread during this method's call.
925 *
926 * @note When #childrenLock() is not overloaded (returns the general object
927 * lock) and this method is called from under the child's read or
928 * write lock, make sure the {parent, child} locking order is
929 * preserved by locking the callee (this object) for writing before
930 * the child's lock. This is irrelevant when the method is called from
931 * under this object's VirtualBoxBaseProto::AutoUninitSpan (i.e. in
932 * InUninit state) since in this case no locking is done.
933 *
934 * @param aChild Child object to remove.
935 *
936 * @note Locks #childrenLock() for writing.
937 */
938 template<class C>
939 void removeDependentChild(C *aChild)
940 {
941 AssertReturnVoid(aChild != NULL);
942 doRemoveDependentChild(ComPtr<IUnknown>(aChild));
943 }
944
945 /**
946 * Equivalent to template <class C> void removeDependentChild (C *aChild)
947 * but takes a ComObjPtr<C> argument.
948 */
949 template<class C>
950 void removeDependentChild(const ComObjPtr<C> &aChild)
951 {
952 AssertReturnVoid(!aChild.isNull());
953 doRemoveDependentChild(ComPtr<IUnknown>(static_cast<C *>(aChild)));
954 }
955
956protected:
957
958 void uninitDependentChildren();
959
960 VirtualBoxBase *getDependentChild(const ComPtr<IUnknown> &aUnk);
961
962private:
963 void doAddDependentChild(IUnknown *aUnk, VirtualBoxBase *aChild);
964 void doRemoveDependentChild(IUnknown *aUnk);
965
966 typedef std::map<IUnknown*, VirtualBoxBase*> DependentChildren;
967 DependentChildren mDependentChildren;
968};
969
970////////////////////////////////////////////////////////////////////////////////
971
972////////////////////////////////////////////////////////////////////////////////
973
974
975/**
976 * Simple template that manages data structure allocation/deallocation
977 * and supports data pointer sharing (the instance that shares the pointer is
978 * not responsible for memory deallocation as opposed to the instance that
979 * owns it).
980 */
981template <class D>
982class Shareable
983{
984public:
985
986 Shareable() : mData (NULL), mIsShared(FALSE) {}
987 ~Shareable() { free(); }
988
989 void allocate() { attach(new D); }
990
991 virtual void free() {
992 if (mData) {
993 if (!mIsShared)
994 delete mData;
995 mData = NULL;
996 mIsShared = false;
997 }
998 }
999
1000 void attach(D *d) {
1001 AssertMsg(d, ("new data must not be NULL"));
1002 if (d && mData != d) {
1003 if (mData && !mIsShared)
1004 delete mData;
1005 mData = d;
1006 mIsShared = false;
1007 }
1008 }
1009
1010 void attach(Shareable &d) {
1011 AssertMsg(
1012 d.mData == mData || !d.mIsShared,
1013 ("new data must not be shared")
1014 );
1015 if (this != &d && !d.mIsShared) {
1016 attach(d.mData);
1017 d.mIsShared = true;
1018 }
1019 }
1020
1021 void share(D *d) {
1022 AssertMsg(d, ("new data must not be NULL"));
1023 if (mData != d) {
1024 if (mData && !mIsShared)
1025 delete mData;
1026 mData = d;
1027 mIsShared = true;
1028 }
1029 }
1030
1031 void share(const Shareable &d) { share(d.mData); }
1032
1033 void attachCopy(const D *d) {
1034 AssertMsg(d, ("data to copy must not be NULL"));
1035 if (d)
1036 attach(new D(*d));
1037 }
1038
1039 void attachCopy(const Shareable &d) {
1040 attachCopy(d.mData);
1041 }
1042
1043 virtual D *detach() {
1044 D *d = mData;
1045 mData = NULL;
1046 mIsShared = false;
1047 return d;
1048 }
1049
1050 D *data() const {
1051 return mData;
1052 }
1053
1054 D *operator->() const {
1055 AssertMsg(mData, ("data must not be NULL"));
1056 return mData;
1057 }
1058
1059 bool isNull() const { return mData == NULL; }
1060 bool operator!() const { return isNull(); }
1061
1062 bool isShared() const { return mIsShared; }
1063
1064protected:
1065
1066 D *mData;
1067 bool mIsShared;
1068};
1069
1070/// @todo (dmik) remove after we switch to VirtualBoxBaseNEXT completely
1071/**
1072 * Simple template that enhances Shareable<> and supports data
1073 * backup/rollback/commit (using the copy constructor of the managed data
1074 * structure).
1075 */
1076template<class D>
1077class Backupable : public Shareable<D>
1078{
1079public:
1080
1081 Backupable() : Shareable<D> (), mBackupData(NULL) {}
1082
1083 void free()
1084 {
1085 AssertMsg(this->mData || !mBackupData, ("backup must be NULL if data is NULL"));
1086 rollback();
1087 Shareable<D>::free();
1088 }
1089
1090 D *detach()
1091 {
1092 AssertMsg(this->mData || !mBackupData, ("backup must be NULL if data is NULL"));
1093 rollback();
1094 return Shareable<D>::detach();
1095 }
1096
1097 void share(const Backupable &d)
1098 {
1099 AssertMsg(!d.isBackedUp(), ("data to share must not be backed up"));
1100 if (!d.isBackedUp())
1101 Shareable<D>::share(d.mData);
1102 }
1103
1104 /**
1105 * Stores the current data pointer in the backup area, allocates new data
1106 * using the copy constructor on current data and makes new data active.
1107 */
1108 void backup()
1109 {
1110 AssertMsg(this->mData, ("data must not be NULL"));
1111 if (this->mData && !mBackupData)
1112 {
1113 D *pNewData = new D(*this->mData);
1114 mBackupData = this->mData;
1115 this->mData = pNewData;
1116 }
1117 }
1118
1119 /**
1120 * Deletes new data created by #backup() and restores previous data pointer
1121 * stored in the backup area, making it active again.
1122 */
1123 void rollback()
1124 {
1125 if (this->mData && mBackupData)
1126 {
1127 delete this->mData;
1128 this->mData = mBackupData;
1129 mBackupData = NULL;
1130 }
1131 }
1132
1133 /**
1134 * Commits current changes by deleting backed up data and clearing up the
1135 * backup area. The new data pointer created by #backup() remains active
1136 * and becomes the only managed pointer.
1137 *
1138 * This method is much faster than #commitCopy() (just a single pointer
1139 * assignment operation), but makes the previous data pointer invalid
1140 * (because it is freed). For this reason, this method must not be
1141 * used if it's possible that data managed by this instance is shared with
1142 * some other Shareable instance. See #commitCopy().
1143 */
1144 void commit()
1145 {
1146 if (this->mData && mBackupData)
1147 {
1148 if (!this->mIsShared)
1149 delete mBackupData;
1150 mBackupData = NULL;
1151 this->mIsShared = false;
1152 }
1153 }
1154
1155 /**
1156 * Commits current changes by assigning new data to the previous data
1157 * pointer stored in the backup area using the assignment operator.
1158 * New data is deleted, the backup area is cleared and the previous data
1159 * pointer becomes active and the only managed pointer.
1160 *
1161 * This method is slower than #commit(), but it keeps the previous data
1162 * pointer valid (i.e. new data is copied to the same memory location).
1163 * For that reason it's safe to use this method on instances that share
1164 * managed data with other Shareable instances.
1165 */
1166 void commitCopy()
1167 {
1168 if (this->mData && mBackupData)
1169 {
1170 *mBackupData = *(this->mData);
1171 delete this->mData;
1172 this->mData = mBackupData;
1173 mBackupData = NULL;
1174 }
1175 }
1176
1177 void assignCopy(const D *pData)
1178 {
1179 AssertMsg(this->mData, ("data must not be NULL"));
1180 AssertMsg(pData, ("data to copy must not be NULL"));
1181 if (this->mData && pData)
1182 {
1183 if (!mBackupData)
1184 {
1185 D *pNewData = new D(*pData);
1186 mBackupData = this->mData;
1187 this->mData = pNewData;
1188 }
1189 else
1190 *this->mData = *pData;
1191 }
1192 }
1193
1194 void assignCopy(const Backupable &d)
1195 {
1196 assignCopy(d.mData);
1197 }
1198
1199 bool isBackedUp() const
1200 {
1201 return mBackupData != NULL;
1202 }
1203
1204 D *backedUpData() const
1205 {
1206 return mBackupData;
1207 }
1208
1209protected:
1210
1211 D *mBackupData;
1212};
1213
1214#endif // !____H_VIRTUALBOXBASEIMPL
1215
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