VirtualBox

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

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

Main/OVF: add DebugThrow macro to ease debugging

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 41.4 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 * A variant of 'throw' that hits a debug breakpoint first to make
493 * finding the actual thrower possible.
494 */
495#if defined (DEBUG)
496#define DebugBreakThrow(a) throw (a)
497#else
498#define DebugBreakThrow(a) \
499 do { \
500 RTAssertDebugBreak(); \
501 throw (a); \
502 } while (0)
503#endif
504
505/**
506 * Parent class of VirtualBoxBase which enables translation support (which
507 * Main doesn't have yet, but this provides the tr() function which will one
508 * day provide translations).
509 *
510 * This class sits in between Lockable and VirtualBoxBase only for the one
511 * reason that the USBProxyService wants translation support but is not
512 * implemented as a COM object, which VirtualBoxBase implies.
513 */
514class ATL_NO_VTABLE VirtualBoxTranslatable
515 : public Lockable
516{
517public:
518
519 /**
520 * Placeholder method with which translations can one day be implemented
521 * in Main. This gets called by the tr() function.
522 * @param context
523 * @param pcszSourceText
524 * @param comment
525 * @return
526 */
527 static const char *translate(const char *context,
528 const char *pcszSourceText,
529 const char *comment = 0)
530 {
531 NOREF(context);
532 NOREF(comment);
533 return pcszSourceText;
534 }
535
536 /**
537 * Translates the given text string by calling translate() and passing
538 * the name of the C class as the first argument ("context of
539 * translation"). See VirtualBoxBase::translate() for more info.
540 *
541 * @param aSourceText String to translate.
542 * @param aComment Comment to the string to resolve possible
543 * ambiguities (NULL means no comment).
544 *
545 * @return Translated version of the source string in UTF-8 encoding, or
546 * the source string itself if the translation is not found in the
547 * specified context.
548 */
549 inline static const char *tr(const char *pcszSourceText,
550 const char *aComment = NULL)
551 {
552 return VirtualBoxTranslatable::translate(NULL, // getComponentName(), eventually
553 pcszSourceText,
554 aComment);
555 }
556};
557
558////////////////////////////////////////////////////////////////////////////////
559//
560// VirtualBoxBase
561//
562////////////////////////////////////////////////////////////////////////////////
563
564#define VIRTUALBOXBASE_ADD_VIRTUAL_COMPONENT_METHODS(cls, iface) \
565 virtual const IID& getClassIID() const \
566 { \
567 return cls::getStaticClassIID(); \
568 } \
569 static const IID& getStaticClassIID() \
570 { \
571 return COM_IIDOF(iface); \
572 } \
573 virtual const char* getComponentName() const \
574 { \
575 return cls::getStaticComponentName(); \
576 } \
577 static const char* getStaticComponentName() \
578 { \
579 return #cls; \
580 }
581
582/**
583 * VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT:
584 * This macro must be used once in the declaration of any class derived
585 * from VirtualBoxBase. It implements the pure virtual getClassIID() and
586 * getComponentName() methods. If this macro is not present, instances
587 * of a class derived from VirtualBoxBase cannot be instantiated.
588 *
589 * @param X The class name, e.g. "Class".
590 * @param IX The interface name which this class implements, e.g. "IClass".
591 */
592#ifdef VBOX_WITH_XPCOM
593 #define VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT(cls, iface) \
594 VIRTUALBOXBASE_ADD_VIRTUAL_COMPONENT_METHODS(cls, iface)
595#else // #ifdef VBOX_WITH_XPCOM
596 #define VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT(cls, iface) \
597 VIRTUALBOXBASE_ADD_VIRTUAL_COMPONENT_METHODS(cls, iface) \
598 STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid) \
599 { \
600 const _ATL_INTMAP_ENTRY* pEntries = cls::_GetEntries(); \
601 Assert(pEntries); \
602 if (!pEntries) \
603 return S_FALSE; \
604 BOOL bSupports = FALSE; \
605 BOOL bISupportErrorInfoFound = FALSE; \
606 while (pEntries->pFunc != NULL && !bSupports) \
607 { \
608 if (!bISupportErrorInfoFound) \
609 bISupportErrorInfoFound = InlineIsEqualGUID(*(pEntries->piid), IID_ISupportErrorInfo); \
610 else \
611 bSupports = InlineIsEqualGUID(*(pEntries->piid), riid); \
612 pEntries++; \
613 } \
614 Assert(bISupportErrorInfoFound); \
615 return bSupports ? S_OK : S_FALSE; \
616 }
617#endif // #ifdef VBOX_WITH_XPCOM
618
619/**
620 * Abstract base class for all component classes implementing COM
621 * interfaces of the VirtualBox COM library.
622 *
623 * Declares functionality that should be available in all components.
624 *
625 * Among the basic functionality implemented by this class is the primary object
626 * state that indicates if the object is ready to serve the calls, and if not,
627 * what stage it is currently at. Here is the primary state diagram:
628 *
629 * +-------------------------------------------------------+
630 * | |
631 * | (InitFailed) -----------------------+ |
632 * | ^ | |
633 * v | v |
634 * [*] ---> NotReady ----> (InInit) -----> Ready -----> (InUninit) ----+
635 * ^ |
636 * | v
637 * | Limited
638 * | |
639 * +-------+
640 *
641 * The object is fully operational only when its state is Ready. The Limited
642 * state means that only some vital part of the object is operational, and it
643 * requires some sort of reinitialization to become fully operational. The
644 * NotReady state means the object is basically dead: it either was not yet
645 * initialized after creation at all, or was uninitialized and is waiting to be
646 * destroyed when the last reference to it is released. All other states are
647 * transitional.
648 *
649 * The NotReady->InInit->Ready, NotReady->InInit->Limited and
650 * NotReady->InInit->InitFailed transition is done by the AutoInitSpan smart
651 * class.
652 *
653 * The Limited->InInit->Ready, Limited->InInit->Limited and
654 * Limited->InInit->InitFailed transition is done by the AutoReinitSpan smart
655 * class.
656 *
657 * The Ready->InUninit->NotReady and InitFailed->InUninit->NotReady
658 * transitions are done by the AutoUninitSpan smart class.
659 *
660 * In order to maintain the primary state integrity and declared functionality
661 * all subclasses must:
662 *
663 * 1) Use the above Auto*Span classes to perform state transitions. See the
664 * individual class descriptions for details.
665 *
666 * 2) All public methods of subclasses (i.e. all methods that can be called
667 * directly, not only from within other methods of the subclass) must have a
668 * standard prolog as described in the AutoCaller and AutoLimitedCaller
669 * documentation. Alternatively, they must use addCaller()/releaseCaller()
670 * directly (and therefore have both the prolog and the epilog), but this is
671 * not recommended.
672 */
673class ATL_NO_VTABLE VirtualBoxBase
674 : public VirtualBoxTranslatable,
675 public CComObjectRootEx<CComMultiThreadModel>
676#if !defined (VBOX_WITH_XPCOM)
677 , public ISupportErrorInfo
678#endif
679{
680public:
681 enum State { NotReady, Ready, InInit, InUninit, InitFailed, Limited };
682
683 VirtualBoxBase();
684 virtual ~VirtualBoxBase();
685
686 /**
687 * Unintialization method.
688 *
689 * Must be called by all final implementations (component classes) when the
690 * last reference to the object is released, before calling the destructor.
691 *
692 * This method is also automatically called by the uninit() method of this
693 * object's parent if this object is a dependent child of a class derived
694 * from VirtualBoxBaseWithChildren (see
695 * VirtualBoxBaseWithChildren::addDependentChild).
696 *
697 * @note Never call this method the AutoCaller scope or after the
698 * #addCaller() call not paired by #releaseCaller() because it is a
699 * guaranteed deadlock. See AutoUninitSpan for details.
700 */
701 virtual void uninit()
702 { }
703
704 virtual HRESULT addCaller(State *aState = NULL,
705 bool aLimited = false);
706 virtual void releaseCaller();
707
708 /**
709 * Adds a limited caller. This method is equivalent to doing
710 * <tt>addCaller (aState, true)</tt>, but it is preferred because provides
711 * better self-descriptiveness. See #addCaller() for more info.
712 */
713 HRESULT addLimitedCaller(State *aState = NULL)
714 {
715 return addCaller(aState, true /* aLimited */);
716 }
717
718 /**
719 * Pure virtual method for simple run-time type identification without
720 * having to enable C++ RTTI.
721 *
722 * This *must* be implemented by every subclass deriving from VirtualBoxBase;
723 * use the VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT macro to do that most easily.
724 */
725 virtual const IID& getClassIID() const = 0;
726
727 /**
728 * Pure virtual method for simple run-time type identification without
729 * having to enable C++ RTTI.
730 *
731 * This *must* be implemented by every subclass deriving from VirtualBoxBase;
732 * use the VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT macro to do that most easily.
733 */
734 virtual const char* getComponentName() const = 0;
735
736 /**
737 * Virtual method which determins the locking class to be used for validating
738 * lock order with the standard member lock handle. This method is overridden
739 * in a number of subclasses.
740 */
741 virtual VBoxLockingClass getLockingClass() const
742 {
743 return LOCKCLASS_OTHEROBJECT;
744 }
745
746 virtual RWLockHandle *lockHandle() const;
747
748 /**
749 * Returns a lock handle used to protect the primary state fields (used by
750 * #addCaller(), AutoInitSpan, AutoUninitSpan, etc.). Only intended to be
751 * used for similar purposes in subclasses. WARNING: NO any other locks may
752 * be requested while holding this lock!
753 */
754 WriteLockHandle *stateLockHandle() { return &mStateLock; }
755
756 static HRESULT setErrorInternal(HRESULT aResultCode,
757 const GUID &aIID,
758 const char *aComponent,
759 const Utf8Str &aText,
760 bool aWarning,
761 bool aLogIt);
762
763 HRESULT setError(HRESULT aResultCode, const char *pcsz, ...);
764 HRESULT setWarning(HRESULT aResultCode, const char *pcsz, ...);
765 HRESULT setErrorNoLog(HRESULT aResultCode, const char *pcsz, ...);
766
767private:
768
769 void setState(State aState)
770 {
771 Assert(mState != aState);
772 mState = aState;
773 mStateChangeThread = RTThreadSelf();
774 }
775
776 /** Primary state of this object */
777 State mState;
778 /** Thread that caused the last state change */
779 RTTHREAD mStateChangeThread;
780 /** Total number of active calls to this object */
781 unsigned mCallers;
782 /** Posted when the number of callers drops to zero */
783 RTSEMEVENT mZeroCallersSem;
784 /** Posted when the object goes from InInit/InUninit to some other state */
785 RTSEMEVENTMULTI mInitUninitSem;
786 /** Number of threads waiting for mInitUninitDoneSem */
787 unsigned mInitUninitWaiters;
788
789 /** Protects access to state related data members */
790 WriteLockHandle mStateLock;
791
792 /** User-level object lock for subclasses */
793 mutable RWLockHandle *mObjectLock;
794
795 friend class AutoInitSpan;
796 friend class AutoReinitSpan;
797 friend class AutoUninitSpan;
798};
799
800/**
801 * Dummy macro that is used to shut down Qt's lupdate tool warnings in some
802 * situations. This macro needs to be present inside (better at the very
803 * beginning) of the declaration of the class that inherits from
804 * VirtualBoxSupportTranslation template, to make lupdate happy.
805 */
806#define Q_OBJECT
807
808////////////////////////////////////////////////////////////////////////////////
809
810/**
811 * Base class to track VirtualBoxBaseNEXT chlidren of the component.
812 *
813 * This class is a preferrable VirtualBoxBase replacement for components that
814 * operate with collections of child components. It gives two useful
815 * possibilities:
816 *
817 * <ol><li>
818 * Given an IUnknown instance, it's possible to quickly determine
819 * whether this instance represents a child object that belongs to the
820 * given component, and if so, get a valid VirtualBoxBase pointer to the
821 * child object. The returned pointer can be then safely casted to the
822 * actual class of the child object (to get access to its "internal"
823 * non-interface methods) provided that no other child components implement
824 * the same original COM interface IUnknown is queried from.
825 * </li><li>
826 * When the parent object uninitializes itself, it can easily unintialize
827 * all its VirtualBoxBase derived children (using their
828 * VirtualBoxBase::uninit() implementations). This is done simply by
829 * calling the #uninitDependentChildren() method.
830 * </li></ol>
831 *
832 * In order to let the above work, the following must be done:
833 * <ol><li>
834 * When a child object is initialized, it calls #addDependentChild() of
835 * its parent to register itself within the list of dependent children.
836 * </li><li>
837 * When the child object it is uninitialized, it calls
838 * #removeDependentChild() to unregister itself.
839 * </li></ol>
840 *
841 * Note that if the parent object does not call #uninitDependentChildren() when
842 * it gets uninitialized, it must call uninit() methods of individual children
843 * manually to disconnect them; a failure to do so will cause crashes in these
844 * methods when children get destroyed. The same applies to children not calling
845 * #removeDependentChild() when getting destroyed.
846 *
847 * Note that children added by #addDependentChild() are <b>weakly</b> referenced
848 * (i.e. AddRef() is not called), so when a child object is deleted externally
849 * (because it's reference count goes to zero), it will automatically remove
850 * itself from the map of dependent children provided that it follows the rules
851 * described here.
852 *
853 * Access to the child list is serialized using the #childrenLock() lock handle
854 * (which defaults to the general object lock handle (see
855 * VirtualBoxBase::lockHandle()). This lock is used by all add/remove methods of
856 * this class so be aware of the need to preserve the {parent, child} lock order
857 * when calling these methods.
858 *
859 * Read individual method descriptions to get further information.
860 *
861 * @todo This is a VirtualBoxBaseWithChildren equivalent that uses the
862 * VirtualBoxBaseNEXT implementation. Will completely supersede
863 * VirtualBoxBaseWithChildren after the old VirtualBoxBase implementation
864 * has gone.
865 */
866class VirtualBoxBaseWithChildrenNEXT : public VirtualBoxBase
867{
868public:
869
870 VirtualBoxBaseWithChildrenNEXT()
871 {}
872
873 virtual ~VirtualBoxBaseWithChildrenNEXT()
874 {}
875
876 /**
877 * Lock handle to use when adding/removing child objects from the list of
878 * children. It is guaranteed that no any other lock is requested in methods
879 * of this class while holding this lock.
880 *
881 * @warning By default, this simply returns the general object's lock handle
882 * (see VirtualBoxBase::lockHandle()) which is sufficient for most
883 * cases.
884 */
885 virtual RWLockHandle *childrenLock() { return lockHandle(); }
886
887 /**
888 * Adds the given child to the list of dependent children.
889 *
890 * Usually gets called from the child's init() method.
891 *
892 * @note @a aChild (unless it is in InInit state) must be protected by
893 * VirtualBoxBase::AutoCaller to make sure it is not uninitialized on
894 * another thread during this method's call.
895 *
896 * @note When #childrenLock() is not overloaded (returns the general object
897 * lock) and this method is called from under the child's read or
898 * write lock, make sure the {parent, child} locking order is
899 * preserved by locking the callee (this object) for writing before
900 * the child's lock.
901 *
902 * @param aChild Child object to add (must inherit VirtualBoxBase AND
903 * implement some interface).
904 *
905 * @note Locks #childrenLock() for writing.
906 */
907 template<class C>
908 void addDependentChild(C *aChild)
909 {
910 AssertReturnVoid(aChild != NULL);
911 doAddDependentChild(ComPtr<IUnknown>(aChild), aChild);
912 }
913
914 /**
915 * Equivalent to template <class C> void addDependentChild (C *aChild)
916 * but takes a ComObjPtr<C> argument.
917 */
918 template<class C>
919 void addDependentChild(const ComObjPtr<C> &aChild)
920 {
921 AssertReturnVoid(!aChild.isNull());
922 doAddDependentChild(ComPtr<IUnknown>(static_cast<C *>(aChild)), aChild);
923 }
924
925 /**
926 * Removes the given child from the list of dependent children.
927 *
928 * Usually gets called from the child's uninit() method.
929 *
930 * Keep in mind that the called (parent) object may be no longer available
931 * (i.e. may be deleted deleted) after this method returns, so you must not
932 * call any other parent's methods after that!
933 *
934 * @note Locks #childrenLock() for writing.
935 *
936 * @note @a aChild (unless it is in InUninit state) must be protected by
937 * VirtualBoxBase::AutoCaller to make sure it is not uninitialized on
938 * another thread during this method's call.
939 *
940 * @note When #childrenLock() is not overloaded (returns the general object
941 * lock) and this method is called from under the child's read or
942 * write lock, make sure the {parent, child} locking order is
943 * preserved by locking the callee (this object) for writing before
944 * the child's lock. This is irrelevant when the method is called from
945 * under this object's VirtualBoxBaseProto::AutoUninitSpan (i.e. in
946 * InUninit state) since in this case no locking is done.
947 *
948 * @param aChild Child object to remove.
949 *
950 * @note Locks #childrenLock() for writing.
951 */
952 template<class C>
953 void removeDependentChild(C *aChild)
954 {
955 AssertReturnVoid(aChild != NULL);
956 doRemoveDependentChild(ComPtr<IUnknown>(aChild));
957 }
958
959 /**
960 * Equivalent to template <class C> void removeDependentChild (C *aChild)
961 * but takes a ComObjPtr<C> argument.
962 */
963 template<class C>
964 void removeDependentChild(const ComObjPtr<C> &aChild)
965 {
966 AssertReturnVoid(!aChild.isNull());
967 doRemoveDependentChild(ComPtr<IUnknown>(static_cast<C *>(aChild)));
968 }
969
970protected:
971
972 void uninitDependentChildren();
973
974 VirtualBoxBase *getDependentChild(const ComPtr<IUnknown> &aUnk);
975
976private:
977 void doAddDependentChild(IUnknown *aUnk, VirtualBoxBase *aChild);
978 void doRemoveDependentChild(IUnknown *aUnk);
979
980 typedef std::map<IUnknown*, VirtualBoxBase*> DependentChildren;
981 DependentChildren mDependentChildren;
982};
983
984////////////////////////////////////////////////////////////////////////////////
985
986////////////////////////////////////////////////////////////////////////////////
987
988
989/**
990 * Simple template that manages data structure allocation/deallocation
991 * and supports data pointer sharing (the instance that shares the pointer is
992 * not responsible for memory deallocation as opposed to the instance that
993 * owns it).
994 */
995template <class D>
996class Shareable
997{
998public:
999
1000 Shareable() : mData (NULL), mIsShared(FALSE) {}
1001 ~Shareable() { free(); }
1002
1003 void allocate() { attach(new D); }
1004
1005 virtual void free() {
1006 if (mData) {
1007 if (!mIsShared)
1008 delete mData;
1009 mData = NULL;
1010 mIsShared = false;
1011 }
1012 }
1013
1014 void attach(D *d) {
1015 AssertMsg(d, ("new data must not be NULL"));
1016 if (d && mData != d) {
1017 if (mData && !mIsShared)
1018 delete mData;
1019 mData = d;
1020 mIsShared = false;
1021 }
1022 }
1023
1024 void attach(Shareable &d) {
1025 AssertMsg(
1026 d.mData == mData || !d.mIsShared,
1027 ("new data must not be shared")
1028 );
1029 if (this != &d && !d.mIsShared) {
1030 attach(d.mData);
1031 d.mIsShared = true;
1032 }
1033 }
1034
1035 void share(D *d) {
1036 AssertMsg(d, ("new data must not be NULL"));
1037 if (mData != d) {
1038 if (mData && !mIsShared)
1039 delete mData;
1040 mData = d;
1041 mIsShared = true;
1042 }
1043 }
1044
1045 void share(const Shareable &d) { share(d.mData); }
1046
1047 void attachCopy(const D *d) {
1048 AssertMsg(d, ("data to copy must not be NULL"));
1049 if (d)
1050 attach(new D(*d));
1051 }
1052
1053 void attachCopy(const Shareable &d) {
1054 attachCopy(d.mData);
1055 }
1056
1057 virtual D *detach() {
1058 D *d = mData;
1059 mData = NULL;
1060 mIsShared = false;
1061 return d;
1062 }
1063
1064 D *data() const {
1065 return mData;
1066 }
1067
1068 D *operator->() const {
1069 AssertMsg(mData, ("data must not be NULL"));
1070 return mData;
1071 }
1072
1073 bool isNull() const { return mData == NULL; }
1074 bool operator!() const { return isNull(); }
1075
1076 bool isShared() const { return mIsShared; }
1077
1078protected:
1079
1080 D *mData;
1081 bool mIsShared;
1082};
1083
1084/// @todo (dmik) remove after we switch to VirtualBoxBaseNEXT completely
1085/**
1086 * Simple template that enhances Shareable<> and supports data
1087 * backup/rollback/commit (using the copy constructor of the managed data
1088 * structure).
1089 */
1090template<class D>
1091class Backupable : public Shareable<D>
1092{
1093public:
1094
1095 Backupable() : Shareable<D> (), mBackupData(NULL) {}
1096
1097 void free()
1098 {
1099 AssertMsg(this->mData || !mBackupData, ("backup must be NULL if data is NULL"));
1100 rollback();
1101 Shareable<D>::free();
1102 }
1103
1104 D *detach()
1105 {
1106 AssertMsg(this->mData || !mBackupData, ("backup must be NULL if data is NULL"));
1107 rollback();
1108 return Shareable<D>::detach();
1109 }
1110
1111 void share(const Backupable &d)
1112 {
1113 AssertMsg(!d.isBackedUp(), ("data to share must not be backed up"));
1114 if (!d.isBackedUp())
1115 Shareable<D>::share(d.mData);
1116 }
1117
1118 /**
1119 * Stores the current data pointer in the backup area, allocates new data
1120 * using the copy constructor on current data and makes new data active.
1121 */
1122 void backup()
1123 {
1124 AssertMsg(this->mData, ("data must not be NULL"));
1125 if (this->mData && !mBackupData)
1126 {
1127 D *pNewData = new D(*this->mData);
1128 mBackupData = this->mData;
1129 this->mData = pNewData;
1130 }
1131 }
1132
1133 /**
1134 * Deletes new data created by #backup() and restores previous data pointer
1135 * stored in the backup area, making it active again.
1136 */
1137 void rollback()
1138 {
1139 if (this->mData && mBackupData)
1140 {
1141 delete this->mData;
1142 this->mData = mBackupData;
1143 mBackupData = NULL;
1144 }
1145 }
1146
1147 /**
1148 * Commits current changes by deleting backed up data and clearing up the
1149 * backup area. The new data pointer created by #backup() remains active
1150 * and becomes the only managed pointer.
1151 *
1152 * This method is much faster than #commitCopy() (just a single pointer
1153 * assignment operation), but makes the previous data pointer invalid
1154 * (because it is freed). For this reason, this method must not be
1155 * used if it's possible that data managed by this instance is shared with
1156 * some other Shareable instance. See #commitCopy().
1157 */
1158 void commit()
1159 {
1160 if (this->mData && mBackupData)
1161 {
1162 if (!this->mIsShared)
1163 delete mBackupData;
1164 mBackupData = NULL;
1165 this->mIsShared = false;
1166 }
1167 }
1168
1169 /**
1170 * Commits current changes by assigning new data to the previous data
1171 * pointer stored in the backup area using the assignment operator.
1172 * New data is deleted, the backup area is cleared and the previous data
1173 * pointer becomes active and the only managed pointer.
1174 *
1175 * This method is slower than #commit(), but it keeps the previous data
1176 * pointer valid (i.e. new data is copied to the same memory location).
1177 * For that reason it's safe to use this method on instances that share
1178 * managed data with other Shareable instances.
1179 */
1180 void commitCopy()
1181 {
1182 if (this->mData && mBackupData)
1183 {
1184 *mBackupData = *(this->mData);
1185 delete this->mData;
1186 this->mData = mBackupData;
1187 mBackupData = NULL;
1188 }
1189 }
1190
1191 void assignCopy(const D *pData)
1192 {
1193 AssertMsg(this->mData, ("data must not be NULL"));
1194 AssertMsg(pData, ("data to copy must not be NULL"));
1195 if (this->mData && pData)
1196 {
1197 if (!mBackupData)
1198 {
1199 D *pNewData = new D(*pData);
1200 mBackupData = this->mData;
1201 this->mData = pNewData;
1202 }
1203 else
1204 *this->mData = *pData;
1205 }
1206 }
1207
1208 void assignCopy(const Backupable &d)
1209 {
1210 assignCopy(d.mData);
1211 }
1212
1213 bool isBackedUp() const
1214 {
1215 return mBackupData != NULL;
1216 }
1217
1218 D *backedUpData() const
1219 {
1220 return mBackupData;
1221 }
1222
1223protected:
1224
1225 D *mBackupData;
1226};
1227
1228#endif // !____H_VIRTUALBOXBASEIMPL
1229
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