VirtualBox

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

Last change on this file since 35722 was 35722, checked in by vboxsync, 14 years ago

Main: reworked listener objects creation, fixes Win problems with events, few cleanups

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 34.2 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.virtualbox.org. 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// avoid including VBox/settings.h and VBox/xml.h;
33// only declare the classes
34namespace xml
35{
36class File;
37}
38
39using namespace com;
40using namespace util;
41
42class AutoInitSpan;
43class AutoUninitSpan;
44
45class VirtualBox;
46class Machine;
47class Medium;
48class Host;
49typedef std::list< ComObjPtr<Medium> > MediaList;
50typedef std::list<Guid> GuidList;
51
52////////////////////////////////////////////////////////////////////////////////
53//
54// COM helpers
55//
56////////////////////////////////////////////////////////////////////////////////
57
58#if !defined (VBOX_WITH_XPCOM)
59
60#include <atlcom.h>
61
62/* use a special version of the singleton class factory,
63 * see KB811591 in msdn for more info. */
64
65#undef DECLARE_CLASSFACTORY_SINGLETON
66#define DECLARE_CLASSFACTORY_SINGLETON(obj) DECLARE_CLASSFACTORY_EX(CMyComClassFactorySingleton<obj>)
67
68template <class T>
69class CMyComClassFactorySingleton : public CComClassFactory
70{
71public:
72 CMyComClassFactorySingleton() : m_hrCreate(S_OK){}
73 virtual ~CMyComClassFactorySingleton(){}
74 // IClassFactory
75 STDMETHOD(CreateInstance)(LPUNKNOWN pUnkOuter, REFIID riid, void** ppvObj)
76 {
77 HRESULT hRes = E_POINTER;
78 if (ppvObj != NULL)
79 {
80 *ppvObj = NULL;
81 // Aggregation is not supported in singleton objects.
82 ATLASSERT(pUnkOuter == NULL);
83 if (pUnkOuter != NULL)
84 hRes = CLASS_E_NOAGGREGATION;
85 else
86 {
87 if (m_hrCreate == S_OK && m_spObj == NULL)
88 {
89 Lock();
90 __try
91 {
92 // Fix: The following If statement was moved inside the __try statement.
93 // Did another thread arrive here first?
94 if (m_hrCreate == S_OK && m_spObj == NULL)
95 {
96 // lock the module to indicate activity
97 // (necessary for the monitor shutdown thread to correctly
98 // terminate the module in case when CreateInstance() fails)
99 _pAtlModule->Lock();
100 CComObjectCached<T> *p;
101 m_hrCreate = CComObjectCached<T>::CreateInstance(&p);
102 if (SUCCEEDED(m_hrCreate))
103 {
104 m_hrCreate = p->QueryInterface(IID_IUnknown, (void**)&m_spObj);
105 if (FAILED(m_hrCreate))
106 {
107 delete p;
108 }
109 }
110 _pAtlModule->Unlock();
111 }
112 }
113 __finally
114 {
115 Unlock();
116 }
117 }
118 if (m_hrCreate == S_OK)
119 {
120 hRes = m_spObj->QueryInterface(riid, ppvObj);
121 }
122 else
123 {
124 hRes = m_hrCreate;
125 }
126 }
127 }
128 return hRes;
129 }
130 HRESULT m_hrCreate;
131 CComPtr<IUnknown> m_spObj;
132};
133
134#endif /* !defined (VBOX_WITH_XPCOM) */
135
136////////////////////////////////////////////////////////////////////////////////
137//
138// Macros
139//
140////////////////////////////////////////////////////////////////////////////////
141
142/**
143 * Special version of the Assert macro to be used within VirtualBoxBase
144 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
145 *
146 * In the debug build, this macro is equivalent to Assert.
147 * In the release build, this macro uses |setError(E_FAIL, ...)| to set the
148 * error info from the asserted expression.
149 *
150 * @see VirtualBoxSupportErrorInfoImpl::setError
151 *
152 * @param expr Expression which should be true.
153 */
154#if defined (DEBUG)
155#define ComAssert(expr) Assert(expr)
156#else
157#define ComAssert(expr) \
158 do { \
159 if (RT_UNLIKELY(!(expr))) \
160 setError(E_FAIL, \
161 "Assertion failed: [%s] at '%s' (%d) in %s.\nPlease contact the product vendor!", \
162 #expr, __FILE__, __LINE__, __PRETTY_FUNCTION__); \
163 } while (0)
164#endif
165
166/**
167 * Special version of the AssertFailed macro to be used within VirtualBoxBase
168 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
169 *
170 * In the debug build, this macro is equivalent to AssertFailed.
171 * In the release build, this macro uses |setError(E_FAIL, ...)| to set the
172 * error info from the asserted expression.
173 *
174 * @see VirtualBoxSupportErrorInfoImpl::setError
175 *
176 */
177#if defined (DEBUG)
178#define ComAssertFailed() AssertFailed()
179#else
180#define ComAssertFailed() \
181 do { \
182 setError(E_FAIL, \
183 "Assertion failed: at '%s' (%d) in %s.\nPlease contact the product vendor!", \
184 __FILE__, __LINE__, __PRETTY_FUNCTION__); \
185 } while (0)
186#endif
187
188/**
189 * Special version of the AssertMsg macro to be used within VirtualBoxBase
190 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
191 *
192 * See ComAssert for more info.
193 *
194 * @param expr Expression which should be true.
195 * @param a printf argument list (in parenthesis).
196 */
197#if defined (DEBUG)
198#define ComAssertMsg(expr, a) AssertMsg(expr, a)
199#else
200#define ComAssertMsg(expr, a) \
201 do { \
202 if (RT_UNLIKELY(!(expr))) \
203 setError(E_FAIL, \
204 "Assertion failed: [%s] at '%s' (%d) in %s.\n%s.\nPlease contact the product vendor!", \
205 #expr, __FILE__, __LINE__, __PRETTY_FUNCTION__, Utf8StrFmt a .c_str()); \
206 } while (0)
207#endif
208
209/**
210 * Special version of the AssertRC macro to be used within VirtualBoxBase
211 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
212 *
213 * See ComAssert for more info.
214 *
215 * @param vrc VBox status code.
216 */
217#if defined (DEBUG)
218#define ComAssertRC(vrc) AssertRC(vrc)
219#else
220#define ComAssertRC(vrc) ComAssertMsgRC(vrc, ("%Rra", vrc))
221#endif
222
223/**
224 * Special version of the AssertMsgRC macro to be used within VirtualBoxBase
225 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
226 *
227 * See ComAssert for more info.
228 *
229 * @param vrc VBox status code.
230 * @param msg printf argument list (in parenthesis).
231 */
232#if defined (DEBUG)
233#define ComAssertMsgRC(vrc, msg) AssertMsgRC(vrc, msg)
234#else
235#define ComAssertMsgRC(vrc, msg) ComAssertMsg(RT_SUCCESS(vrc), msg)
236#endif
237
238/**
239 * Special version of the AssertComRC macro to be used within VirtualBoxBase
240 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
241 *
242 * See ComAssert for more info.
243 *
244 * @param rc COM result code
245 */
246#if defined (DEBUG)
247#define ComAssertComRC(rc) AssertComRC(rc)
248#else
249#define ComAssertComRC(rc) ComAssertMsg(SUCCEEDED(rc), ("COM RC = %Rhrc (0x%08X)", (rc), (rc)))
250#endif
251
252
253/** Special version of ComAssert that returns ret if expr fails */
254#define ComAssertRet(expr, ret) \
255 do { ComAssert(expr); if (!(expr)) return (ret); } while (0)
256/** Special version of ComAssertMsg that returns ret if expr fails */
257#define ComAssertMsgRet(expr, a, ret) \
258 do { ComAssertMsg(expr, a); if (!(expr)) return (ret); } while (0)
259/** Special version of ComAssertRC that returns ret if vrc does not succeed */
260#define ComAssertRCRet(vrc, ret) \
261 do { ComAssertRC(vrc); if (!RT_SUCCESS(vrc)) return (ret); } while (0)
262/** Special version of ComAssertComRC that returns ret if rc does not succeed */
263#define ComAssertComRCRet(rc, ret) \
264 do { ComAssertComRC(rc); if (!SUCCEEDED(rc)) return (ret); } while (0)
265/** Special version of ComAssertComRC that returns rc if rc does not succeed */
266#define ComAssertComRCRetRC(rc) \
267 do { ComAssertComRC(rc); if (!SUCCEEDED(rc)) return (rc); } while (0)
268/** Special version of ComAssert that returns ret */
269#define ComAssertFailedRet(ret) \
270 if (1) { ComAssertFailed(); { return (ret); } } else do {} while (0)
271
272
273/** Special version of ComAssert that evaluates eval and breaks if expr fails */
274#define ComAssertBreak(expr, eval) \
275 if (1) { ComAssert(expr); if (!(expr)) { eval; break; } } else do {} while (0)
276/** Special version of ComAssertMsg that evaluates eval and breaks if expr fails */
277#define ComAssertMsgBreak(expr, a, eval) \
278 if (1) { ComAssertMsg(expr, a); if (!(expr)) { eval; break; } } else do {} while (0)
279/** Special version of ComAssertRC that evaluates eval and breaks if vrc does not succeed */
280#define ComAssertRCBreak(vrc, eval) \
281 if (1) { ComAssertRC(vrc); if (!RT_SUCCESS(vrc)) { eval; break; } } else do {} while (0)
282/** Special version of ComAssertFailed that evaluates eval and breaks */
283#define ComAssertFailedBreak(eval) \
284 if (1) { ComAssertFailed(); { eval; break; } } else do {} while (0)
285/** Special version of ComAssertMsgFailed that evaluates eval and breaks */
286#define ComAssertMsgFailedBreak(msg, eval) \
287 if (1) { ComAssertMsgFailed (msg); { eval; break; } } else do {} while (0)
288/** Special version of ComAssertComRC that evaluates eval and breaks if rc does not succeed */
289#define ComAssertComRCBreak(rc, eval) \
290 if (1) { ComAssertComRC(rc); if (!SUCCEEDED(rc)) { eval; break; } } else do {} while (0)
291/** Special version of ComAssertComRC that just breaks if rc does not succeed */
292#define ComAssertComRCBreakRC(rc) \
293 if (1) { ComAssertComRC(rc); if (!SUCCEEDED(rc)) { break; } } else do {} while (0)
294
295
296/** Special version of ComAssert that evaluates eval and throws it if expr fails */
297#define ComAssertThrow(expr, eval) \
298 if (1) { ComAssert(expr); if (!(expr)) { throw (eval); } } else do {} while (0)
299/** Special version of ComAssertRC that evaluates eval and throws it if vrc does not succeed */
300#define ComAssertRCThrow(vrc, eval) \
301 if (1) { ComAssertRC(vrc); if (!RT_SUCCESS(vrc)) { throw (eval); } } else do {} while (0)
302/** Special version of ComAssertComRC that evaluates eval and throws it if rc does not succeed */
303#define ComAssertComRCThrow(rc, eval) \
304 if (1) { ComAssertComRC(rc); if (!SUCCEEDED(rc)) { throw (eval); } } else do {} while (0)
305/** Special version of ComAssertComRC that just throws rc if rc does not succeed */
306#define ComAssertComRCThrowRC(rc) \
307 if (1) { ComAssertComRC(rc); if (!SUCCEEDED(rc)) { throw rc; } } else do {} while (0)
308/** Special version of ComAssert that throws eval */
309#define ComAssertFailedThrow(eval) \
310 if (1) { ComAssertFailed(); { throw (eval); } } else do {} while (0)
311
312////////////////////////////////////////////////////////////////////////////////
313
314/**
315 * Checks that the pointer argument is not NULL and returns E_INVALIDARG +
316 * extended error info on failure.
317 * @param arg Input pointer-type argument (strings, interface pointers...)
318 */
319#define CheckComArgNotNull(arg) \
320 do { \
321 if (RT_UNLIKELY((arg) == NULL)) \
322 return setError(E_INVALIDARG, tr("Argument %s is NULL"), #arg); \
323 } while (0)
324
325/**
326 * Checks that safe array argument is not NULL and returns E_INVALIDARG +
327 * extended error info on failure.
328 * @param arg Input safe array argument (strings, interface pointers...)
329 */
330#define CheckComArgSafeArrayNotNull(arg) \
331 do { \
332 if (RT_UNLIKELY(ComSafeArrayInIsNull(arg))) \
333 return setError(E_INVALIDARG, tr("Argument %s is NULL"), #arg); \
334 } while (0)
335
336/**
337 * Checks that the string argument is not a NULL or empty string and returns
338 * E_INVALIDARG + extended error info on failure.
339 * @param arg Input string argument (BSTR etc.).
340 */
341#define CheckComArgStrNotEmptyOrNull(arg) \
342 do { \
343 if (RT_UNLIKELY((arg) == NULL || *(arg) == '\0')) \
344 return setError(E_INVALIDARG, \
345 tr("Argument %s is empty or NULL"), #arg); \
346 } while (0)
347
348/**
349 * Converts the Guid input argument (string) to a Guid object, returns with
350 * E_INVALIDARG and error message on failure.
351 *
352 * @param a_Arg Argument.
353 * @param a_GuidVar The Guid variable name.
354 */
355#define CheckComArgGuid(a_Arg, a_GuidVar) \
356 do { \
357 Guid tmpGuid(a_Arg); \
358 (a_GuidVar) = tmpGuid; \
359 if (RT_UNLIKELY((a_GuidVar).isEmpty())) \
360 return setError(E_INVALIDARG, \
361 tr("GUID argument %s is not valid (\"%ls\")"), #a_Arg, Bstr(a_Arg).raw()); \
362 } while (0)
363
364/**
365 * Checks that the given expression (that must involve the argument) is true and
366 * returns E_INVALIDARG + extended error info on failure.
367 * @param arg Argument.
368 * @param expr Expression to evaluate.
369 */
370#define CheckComArgExpr(arg, expr) \
371 do { \
372 if (RT_UNLIKELY(!(expr))) \
373 return setError(E_INVALIDARG, \
374 tr("Argument %s is invalid (must be %s)"), #arg, #expr); \
375 } while (0)
376
377/**
378 * Checks that the given expression (that must involve the argument) is true and
379 * returns E_INVALIDARG + extended error info on failure. The error message must
380 * be customized.
381 * @param arg Argument.
382 * @param expr Expression to evaluate.
383 * @param msg Parenthesized printf-like expression (must start with a verb,
384 * like "must be one of...", "is not within...").
385 */
386#define CheckComArgExprMsg(arg, expr, msg) \
387 do { \
388 if (RT_UNLIKELY(!(expr))) \
389 return setError(E_INVALIDARG, tr ("Argument %s %s"), \
390 #arg, Utf8StrFmt msg .c_str()); \
391 } while (0)
392
393/**
394 * Checks that the given pointer to an output argument is valid and returns
395 * E_POINTER + extended error info otherwise.
396 * @param arg Pointer argument.
397 */
398#define CheckComArgOutPointerValid(arg) \
399 do { \
400 if (RT_UNLIKELY(!VALID_PTR(arg))) \
401 return setError(E_POINTER, \
402 tr("Output argument %s points to invalid memory location (%p)"), \
403 #arg, (void *) (arg)); \
404 } while (0)
405
406/**
407 * Checks that the given pointer to an output safe array argument is valid and
408 * returns E_POINTER + extended error info otherwise.
409 * @param arg Safe array argument.
410 */
411#define CheckComArgOutSafeArrayPointerValid(arg) \
412 do { \
413 if (RT_UNLIKELY(ComSafeArrayOutIsNull(arg))) \
414 return setError(E_POINTER, \
415 tr("Output argument %s points to invalid memory location (%p)"), \
416 #arg, (void*)(arg)); \
417 } while (0)
418
419/**
420 * Sets the extended error info and returns E_NOTIMPL.
421 */
422#define ReturnComNotImplemented() \
423 do { \
424 return setError(E_NOTIMPL, tr("Method %s is not implemented"), __FUNCTION__); \
425 } while (0)
426
427/**
428 * Declares an empty constructor and destructor for the given class.
429 * This is useful to prevent the compiler from generating the default
430 * ctor and dtor, which in turn allows to use forward class statements
431 * (instead of including their header files) when declaring data members of
432 * non-fundamental types with constructors (which are always called implicitly
433 * by constructors and by the destructor of the class).
434 *
435 * This macro is to be placed within (the public section of) the class
436 * declaration. Its counterpart, DEFINE_EMPTY_CTOR_DTOR, must be placed
437 * somewhere in one of the translation units (usually .cpp source files).
438 *
439 * @param cls class to declare a ctor and dtor for
440 */
441#define DECLARE_EMPTY_CTOR_DTOR(cls) cls(); ~cls();
442
443/**
444 * Defines an empty constructor and destructor for the given class.
445 * See DECLARE_EMPTY_CTOR_DTOR for more info.
446 */
447#define DEFINE_EMPTY_CTOR_DTOR(cls) \
448 cls::cls() { /*empty*/ } \
449 cls::~cls() { /*empty*/ }
450
451/**
452 * A variant of 'throw' that hits a debug breakpoint first to make
453 * finding the actual thrower possible.
454 */
455#ifdef DEBUG
456#define DebugBreakThrow(a) \
457 do { \
458 RTAssertDebugBreak(); \
459 throw (a); \
460} while (0)
461#else
462#define DebugBreakThrow(a) throw (a)
463#endif
464
465/**
466 * Parent class of VirtualBoxBase which enables translation support (which
467 * Main doesn't have yet, but this provides the tr() function which will one
468 * day provide translations).
469 *
470 * This class sits in between Lockable and VirtualBoxBase only for the one
471 * reason that the USBProxyService wants translation support but is not
472 * implemented as a COM object, which VirtualBoxBase implies.
473 */
474class ATL_NO_VTABLE VirtualBoxTranslatable
475 : public Lockable
476{
477public:
478
479 /**
480 * Placeholder method with which translations can one day be implemented
481 * in Main. This gets called by the tr() function.
482 * @param context
483 * @param pcszSourceText
484 * @param comment
485 * @return
486 */
487 static const char *translate(const char *context,
488 const char *pcszSourceText,
489 const char *comment = 0)
490 {
491 NOREF(context);
492 NOREF(comment);
493 return pcszSourceText;
494 }
495
496 /**
497 * Translates the given text string by calling translate() and passing
498 * the name of the C class as the first argument ("context of
499 * translation"). See VirtualBoxBase::translate() for more info.
500 *
501 * @param aSourceText String to translate.
502 * @param aComment Comment to the string to resolve possible
503 * ambiguities (NULL means no comment).
504 *
505 * @return Translated version of the source string in UTF-8 encoding, or
506 * the source string itself if the translation is not found in the
507 * specified context.
508 */
509 inline static const char *tr(const char *pcszSourceText,
510 const char *aComment = NULL)
511 {
512 return VirtualBoxTranslatable::translate(NULL, // getComponentName(), eventually
513 pcszSourceText,
514 aComment);
515 }
516};
517
518////////////////////////////////////////////////////////////////////////////////
519//
520// VirtualBoxBase
521//
522////////////////////////////////////////////////////////////////////////////////
523
524#define VIRTUALBOXBASE_ADD_VIRTUAL_COMPONENT_METHODS(cls, iface) \
525 virtual const IID& getClassIID() const \
526 { \
527 return cls::getStaticClassIID(); \
528 } \
529 static const IID& getStaticClassIID() \
530 { \
531 return COM_IIDOF(iface); \
532 } \
533 virtual const char* getComponentName() const \
534 { \
535 return cls::getStaticComponentName(); \
536 } \
537 static const char* getStaticComponentName() \
538 { \
539 return #cls; \
540 }
541
542/**
543 * VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT:
544 * This macro must be used once in the declaration of any class derived
545 * from VirtualBoxBase. It implements the pure virtual getClassIID() and
546 * getComponentName() methods. If this macro is not present, instances
547 * of a class derived from VirtualBoxBase cannot be instantiated.
548 *
549 * @param X The class name, e.g. "Class".
550 * @param IX The interface name which this class implements, e.g. "IClass".
551 */
552#ifdef VBOX_WITH_XPCOM
553 #define VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT(cls, iface) \
554 VIRTUALBOXBASE_ADD_VIRTUAL_COMPONENT_METHODS(cls, iface)
555#else // #ifdef VBOX_WITH_XPCOM
556 #define VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT(cls, iface) \
557 VIRTUALBOXBASE_ADD_VIRTUAL_COMPONENT_METHODS(cls, iface) \
558 STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid) \
559 { \
560 const _ATL_INTMAP_ENTRY* pEntries = cls::_GetEntries(); \
561 Assert(pEntries); \
562 if (!pEntries) \
563 return S_FALSE; \
564 BOOL bSupports = FALSE; \
565 BOOL bISupportErrorInfoFound = FALSE; \
566 while (pEntries->pFunc != NULL && !bSupports) \
567 { \
568 if (!bISupportErrorInfoFound) \
569 bISupportErrorInfoFound = InlineIsEqualGUID(*(pEntries->piid), IID_ISupportErrorInfo); \
570 else \
571 bSupports = InlineIsEqualGUID(*(pEntries->piid), riid); \
572 pEntries++; \
573 } \
574 Assert(bISupportErrorInfoFound); \
575 return bSupports ? S_OK : S_FALSE; \
576 }
577#endif // #ifdef VBOX_WITH_XPCOM
578
579/**
580 * Abstract base class for all component classes implementing COM
581 * interfaces of the VirtualBox COM library.
582 *
583 * Declares functionality that should be available in all components.
584 *
585 * Among the basic functionality implemented by this class is the primary object
586 * state that indicates if the object is ready to serve the calls, and if not,
587 * what stage it is currently at. Here is the primary state diagram:
588 *
589 * +-------------------------------------------------------+
590 * | |
591 * | (InitFailed) -----------------------+ |
592 * | ^ | |
593 * v | v |
594 * [*] ---> NotReady ----> (InInit) -----> Ready -----> (InUninit) ----+
595 * ^ |
596 * | v
597 * | Limited
598 * | |
599 * +-------+
600 *
601 * The object is fully operational only when its state is Ready. The Limited
602 * state means that only some vital part of the object is operational, and it
603 * requires some sort of reinitialization to become fully operational. The
604 * NotReady state means the object is basically dead: it either was not yet
605 * initialized after creation at all, or was uninitialized and is waiting to be
606 * destroyed when the last reference to it is released. All other states are
607 * transitional.
608 *
609 * The NotReady->InInit->Ready, NotReady->InInit->Limited and
610 * NotReady->InInit->InitFailed transition is done by the AutoInitSpan smart
611 * class.
612 *
613 * The Limited->InInit->Ready, Limited->InInit->Limited and
614 * Limited->InInit->InitFailed transition is done by the AutoReinitSpan smart
615 * class.
616 *
617 * The Ready->InUninit->NotReady and InitFailed->InUninit->NotReady
618 * transitions are done by the AutoUninitSpan smart class.
619 *
620 * In order to maintain the primary state integrity and declared functionality
621 * all subclasses must:
622 *
623 * 1) Use the above Auto*Span classes to perform state transitions. See the
624 * individual class descriptions for details.
625 *
626 * 2) All public methods of subclasses (i.e. all methods that can be called
627 * directly, not only from within other methods of the subclass) must have a
628 * standard prolog as described in the AutoCaller and AutoLimitedCaller
629 * documentation. Alternatively, they must use addCaller()/releaseCaller()
630 * directly (and therefore have both the prolog and the epilog), but this is
631 * not recommended.
632 */
633class ATL_NO_VTABLE VirtualBoxBase
634 : public VirtualBoxTranslatable,
635 public CComObjectRootEx<CComMultiThreadModel>
636#if !defined (VBOX_WITH_XPCOM)
637 , public ISupportErrorInfo
638#endif
639{
640protected:
641#ifdef RT_OS_WINDOWS
642 CComPtr <IUnknown> m_pUnkMarshaler;
643#endif
644
645 HRESULT BaseFinalConstruct()
646 {
647#ifdef RT_OS_WINDOWS
648 return CoCreateFreeThreadedMarshaler(this, //GetControllingUnknown(),
649 &m_pUnkMarshaler.p);
650#else
651 return S_OK;
652#endif
653 }
654
655 void BaseFinalRelease()
656 {
657#ifdef RT_OS_WINDOWS
658 m_pUnkMarshaler.Release();
659#endif
660 }
661
662
663public:
664 enum State { NotReady, Ready, InInit, InUninit, InitFailed, Limited };
665
666 VirtualBoxBase();
667 virtual ~VirtualBoxBase();
668
669 /**
670 * Uninitialization method.
671 *
672 * Must be called by all final implementations (component classes) when the
673 * last reference to the object is released, before calling the destructor.
674 *
675 * @note Never call this method the AutoCaller scope or after the
676 * #addCaller() call not paired by #releaseCaller() because it is a
677 * guaranteed deadlock. See AutoUninitSpan for details.
678 */
679 virtual void uninit()
680 { }
681
682 virtual HRESULT addCaller(State *aState = NULL,
683 bool aLimited = false);
684 virtual void releaseCaller();
685
686 /**
687 * Adds a limited caller. This method is equivalent to doing
688 * <tt>addCaller (aState, true)</tt>, but it is preferred because provides
689 * better self-descriptiveness. See #addCaller() for more info.
690 */
691 HRESULT addLimitedCaller(State *aState = NULL)
692 {
693 return addCaller(aState, true /* aLimited */);
694 }
695
696 /**
697 * Pure virtual method for simple run-time type identification without
698 * having to enable C++ RTTI.
699 *
700 * This *must* be implemented by every subclass deriving from VirtualBoxBase;
701 * use the VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT macro to do that most easily.
702 */
703 virtual const IID& getClassIID() const = 0;
704
705 /**
706 * Pure virtual method for simple run-time type identification without
707 * having to enable C++ RTTI.
708 *
709 * This *must* be implemented by every subclass deriving from VirtualBoxBase;
710 * use the VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT macro to do that most easily.
711 */
712 virtual const char* getComponentName() const = 0;
713
714 /**
715 * Virtual method which determines the locking class to be used for validating
716 * lock order with the standard member lock handle. This method is overridden
717 * in a number of subclasses.
718 */
719 virtual VBoxLockingClass getLockingClass() const
720 {
721 return LOCKCLASS_OTHEROBJECT;
722 }
723
724 virtual RWLockHandle *lockHandle() const;
725
726 /**
727 * Returns a lock handle used to protect the primary state fields (used by
728 * #addCaller(), AutoInitSpan, AutoUninitSpan, etc.). Only intended to be
729 * used for similar purposes in subclasses. WARNING: NO any other locks may
730 * be requested while holding this lock!
731 */
732 WriteLockHandle *stateLockHandle() { return &mStateLock; }
733
734 static HRESULT setErrorInternal(HRESULT aResultCode,
735 const GUID &aIID,
736 const char *aComponent,
737 const Utf8Str &aText,
738 bool aWarning,
739 bool aLogIt);
740
741 HRESULT setError(HRESULT aResultCode, const char *pcsz, ...);
742 HRESULT setWarning(HRESULT aResultCode, const char *pcsz, ...);
743 HRESULT setErrorNoLog(HRESULT aResultCode, const char *pcsz, ...);
744
745private:
746
747 void setState(State aState)
748 {
749 Assert(mState != aState);
750 mState = aState;
751 mStateChangeThread = RTThreadSelf();
752 }
753
754 /** Primary state of this object */
755 State mState;
756 /** Thread that caused the last state change */
757 RTTHREAD mStateChangeThread;
758 /** Total number of active calls to this object */
759 unsigned mCallers;
760 /** Posted when the number of callers drops to zero */
761 RTSEMEVENT mZeroCallersSem;
762 /** Posted when the object goes from InInit/InUninit to some other state */
763 RTSEMEVENTMULTI mInitUninitSem;
764 /** Number of threads waiting for mInitUninitDoneSem */
765 unsigned mInitUninitWaiters;
766
767 /** Protects access to state related data members */
768 WriteLockHandle mStateLock;
769
770 /** User-level object lock for subclasses */
771 mutable RWLockHandle *mObjectLock;
772
773 friend class AutoInitSpan;
774 friend class AutoReinitSpan;
775 friend class AutoUninitSpan;
776};
777
778/**
779 * Dummy macro that is used to shut down Qt's lupdate tool warnings in some
780 * situations. This macro needs to be present inside (better at the very
781 * beginning) of the declaration of the class that inherits from
782 * VirtualBoxSupportTranslation template, to make lupdate happy.
783 */
784#define Q_OBJECT
785
786////////////////////////////////////////////////////////////////////////////////
787
788////////////////////////////////////////////////////////////////////////////////
789
790
791/**
792 * Simple template that manages data structure allocation/deallocation
793 * and supports data pointer sharing (the instance that shares the pointer is
794 * not responsible for memory deallocation as opposed to the instance that
795 * owns it).
796 */
797template <class D>
798class Shareable
799{
800public:
801
802 Shareable() : mData (NULL), mIsShared(FALSE) {}
803 ~Shareable() { free(); }
804
805 void allocate() { attach(new D); }
806
807 virtual void free() {
808 if (mData) {
809 if (!mIsShared)
810 delete mData;
811 mData = NULL;
812 mIsShared = false;
813 }
814 }
815
816 void attach(D *d) {
817 AssertMsg(d, ("new data must not be NULL"));
818 if (d && mData != d) {
819 if (mData && !mIsShared)
820 delete mData;
821 mData = d;
822 mIsShared = false;
823 }
824 }
825
826 void attach(Shareable &d) {
827 AssertMsg(
828 d.mData == mData || !d.mIsShared,
829 ("new data must not be shared")
830 );
831 if (this != &d && !d.mIsShared) {
832 attach(d.mData);
833 d.mIsShared = true;
834 }
835 }
836
837 void share(D *d) {
838 AssertMsg(d, ("new data must not be NULL"));
839 if (mData != d) {
840 if (mData && !mIsShared)
841 delete mData;
842 mData = d;
843 mIsShared = true;
844 }
845 }
846
847 void share(const Shareable &d) { share(d.mData); }
848
849 void attachCopy(const D *d) {
850 AssertMsg(d, ("data to copy must not be NULL"));
851 if (d)
852 attach(new D(*d));
853 }
854
855 void attachCopy(const Shareable &d) {
856 attachCopy(d.mData);
857 }
858
859 virtual D *detach() {
860 D *d = mData;
861 mData = NULL;
862 mIsShared = false;
863 return d;
864 }
865
866 D *data() const {
867 return mData;
868 }
869
870 D *operator->() const {
871 AssertMsg(mData, ("data must not be NULL"));
872 return mData;
873 }
874
875 bool isNull() const { return mData == NULL; }
876 bool operator!() const { return isNull(); }
877
878 bool isShared() const { return mIsShared; }
879
880protected:
881
882 D *mData;
883 bool mIsShared;
884};
885
886/**
887 * Simple template that enhances Shareable<> and supports data
888 * backup/rollback/commit (using the copy constructor of the managed data
889 * structure).
890 */
891template<class D>
892class Backupable : public Shareable<D>
893{
894public:
895
896 Backupable() : Shareable<D> (), mBackupData(NULL) {}
897
898 void free()
899 {
900 AssertMsg(this->mData || !mBackupData, ("backup must be NULL if data is NULL"));
901 rollback();
902 Shareable<D>::free();
903 }
904
905 D *detach()
906 {
907 AssertMsg(this->mData || !mBackupData, ("backup must be NULL if data is NULL"));
908 rollback();
909 return Shareable<D>::detach();
910 }
911
912 void share(const Backupable &d)
913 {
914 AssertMsg(!d.isBackedUp(), ("data to share must not be backed up"));
915 if (!d.isBackedUp())
916 Shareable<D>::share(d.mData);
917 }
918
919 /**
920 * Stores the current data pointer in the backup area, allocates new data
921 * using the copy constructor on current data and makes new data active.
922 */
923 void backup()
924 {
925 AssertMsg(this->mData, ("data must not be NULL"));
926 if (this->mData && !mBackupData)
927 {
928 D *pNewData = new D(*this->mData);
929 mBackupData = this->mData;
930 this->mData = pNewData;
931 }
932 }
933
934 /**
935 * Deletes new data created by #backup() and restores previous data pointer
936 * stored in the backup area, making it active again.
937 */
938 void rollback()
939 {
940 if (this->mData && mBackupData)
941 {
942 delete this->mData;
943 this->mData = mBackupData;
944 mBackupData = NULL;
945 }
946 }
947
948 /**
949 * Commits current changes by deleting backed up data and clearing up the
950 * backup area. The new data pointer created by #backup() remains active
951 * and becomes the only managed pointer.
952 *
953 * This method is much faster than #commitCopy() (just a single pointer
954 * assignment operation), but makes the previous data pointer invalid
955 * (because it is freed). For this reason, this method must not be
956 * used if it's possible that data managed by this instance is shared with
957 * some other Shareable instance. See #commitCopy().
958 */
959 void commit()
960 {
961 if (this->mData && mBackupData)
962 {
963 if (!this->mIsShared)
964 delete mBackupData;
965 mBackupData = NULL;
966 this->mIsShared = false;
967 }
968 }
969
970 /**
971 * Commits current changes by assigning new data to the previous data
972 * pointer stored in the backup area using the assignment operator.
973 * New data is deleted, the backup area is cleared and the previous data
974 * pointer becomes active and the only managed pointer.
975 *
976 * This method is slower than #commit(), but it keeps the previous data
977 * pointer valid (i.e. new data is copied to the same memory location).
978 * For that reason it's safe to use this method on instances that share
979 * managed data with other Shareable instances.
980 */
981 void commitCopy()
982 {
983 if (this->mData && mBackupData)
984 {
985 *mBackupData = *(this->mData);
986 delete this->mData;
987 this->mData = mBackupData;
988 mBackupData = NULL;
989 }
990 }
991
992 void assignCopy(const D *pData)
993 {
994 AssertMsg(this->mData, ("data must not be NULL"));
995 AssertMsg(pData, ("data to copy must not be NULL"));
996 if (this->mData && pData)
997 {
998 if (!mBackupData)
999 {
1000 D *pNewData = new D(*pData);
1001 mBackupData = this->mData;
1002 this->mData = pNewData;
1003 }
1004 else
1005 *this->mData = *pData;
1006 }
1007 }
1008
1009 void assignCopy(const Backupable &d)
1010 {
1011 assignCopy(d.mData);
1012 }
1013
1014 bool isBackedUp() const
1015 {
1016 return mBackupData != NULL;
1017 }
1018
1019 D *backedUpData() const
1020 {
1021 return mBackupData;
1022 }
1023
1024protected:
1025
1026 D *mBackupData;
1027};
1028
1029#endif // !____H_VIRTUALBOXBASEIMPL
1030
Note: See TracBrowser for help on using the repository browser.

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