VirtualBox

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

Last change on this file since 37423 was 37423, checked in by vboxsync, 13 years ago

Ran the source code massager (scm).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 35.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.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 the pointer argument is a valid pointer or NULL and returns
327 * E_INVALIDARG + extended error info on failure.
328 * @param arg Input pointer-type argument (strings, interface pointers...)
329 */
330#define CheckComArgMaybeNull(arg) \
331 do { \
332 if (RT_UNLIKELY(!RT_VALID_PTR(arg) && (arg) != NULL)) \
333 return setError(E_INVALIDARG, tr("Argument %s is an invalid pointer"), #arg); \
334 } while (0)
335
336/**
337 * Checks that safe array argument is not NULL and returns E_INVALIDARG +
338 * extended error info on failure.
339 * @param arg Input safe array argument (strings, interface pointers...)
340 */
341#define CheckComArgSafeArrayNotNull(arg) \
342 do { \
343 if (RT_UNLIKELY(ComSafeArrayInIsNull(arg))) \
344 return setError(E_INVALIDARG, tr("Argument %s is NULL"), #arg); \
345 } while (0)
346
347/**
348 * Checks that the string argument is not a NULL or empty string and returns
349 * E_INVALIDARG + extended error info on failure.
350 * @param arg Input string argument (BSTR etc.).
351 */
352#define CheckComArgStrNotEmptyOrNull(arg) \
353 do { \
354 if (RT_UNLIKELY((arg) == NULL || *(arg) == '\0')) \
355 return setError(E_INVALIDARG, \
356 tr("Argument %s is empty or NULL"), #arg); \
357 } while (0)
358
359/**
360 * Converts the Guid input argument (string) to a Guid object, returns with
361 * E_INVALIDARG and error message on failure.
362 *
363 * @param a_Arg Argument.
364 * @param a_GuidVar The Guid variable name.
365 */
366#define CheckComArgGuid(a_Arg, a_GuidVar) \
367 do { \
368 Guid tmpGuid(a_Arg); \
369 (a_GuidVar) = tmpGuid; \
370 if (RT_UNLIKELY((a_GuidVar).isEmpty())) \
371 return setError(E_INVALIDARG, \
372 tr("GUID argument %s is not valid (\"%ls\")"), #a_Arg, Bstr(a_Arg).raw()); \
373 } while (0)
374
375/**
376 * Checks that the given expression (that must involve the argument) is true and
377 * returns E_INVALIDARG + extended error info on failure.
378 * @param arg Argument.
379 * @param expr Expression to evaluate.
380 */
381#define CheckComArgExpr(arg, expr) \
382 do { \
383 if (RT_UNLIKELY(!(expr))) \
384 return setError(E_INVALIDARG, \
385 tr("Argument %s is invalid (must be %s)"), #arg, #expr); \
386 } while (0)
387
388/**
389 * Checks that the given expression (that must involve the argument) is true and
390 * returns E_INVALIDARG + extended error info on failure. The error message must
391 * be customized.
392 * @param arg Argument.
393 * @param expr Expression to evaluate.
394 * @param msg Parenthesized printf-like expression (must start with a verb,
395 * like "must be one of...", "is not within...").
396 */
397#define CheckComArgExprMsg(arg, expr, msg) \
398 do { \
399 if (RT_UNLIKELY(!(expr))) \
400 return setError(E_INVALIDARG, tr ("Argument %s %s"), \
401 #arg, Utf8StrFmt msg .c_str()); \
402 } while (0)
403
404/**
405 * Checks that the given pointer to an output argument is valid and returns
406 * E_POINTER + extended error info otherwise.
407 * @param arg Pointer argument.
408 */
409#define CheckComArgOutPointerValid(arg) \
410 do { \
411 if (RT_UNLIKELY(!VALID_PTR(arg))) \
412 return setError(E_POINTER, \
413 tr("Output argument %s points to invalid memory location (%p)"), \
414 #arg, (void *) (arg)); \
415 } while (0)
416
417/**
418 * Checks that the given pointer to an output safe array argument is valid and
419 * returns E_POINTER + extended error info otherwise.
420 * @param arg Safe array argument.
421 */
422#define CheckComArgOutSafeArrayPointerValid(arg) \
423 do { \
424 if (RT_UNLIKELY(ComSafeArrayOutIsNull(arg))) \
425 return setError(E_POINTER, \
426 tr("Output argument %s points to invalid memory location (%p)"), \
427 #arg, (void*)(arg)); \
428 } while (0)
429
430/**
431 * Sets the extended error info and returns E_NOTIMPL.
432 */
433#define ReturnComNotImplemented() \
434 do { \
435 return setError(E_NOTIMPL, tr("Method %s is not implemented"), __FUNCTION__); \
436 } while (0)
437
438/**
439 * Declares an empty constructor and destructor for the given class.
440 * This is useful to prevent the compiler from generating the default
441 * ctor and dtor, which in turn allows to use forward class statements
442 * (instead of including their header files) when declaring data members of
443 * non-fundamental types with constructors (which are always called implicitly
444 * by constructors and by the destructor of the class).
445 *
446 * This macro is to be placed within (the public section of) the class
447 * declaration. Its counterpart, DEFINE_EMPTY_CTOR_DTOR, must be placed
448 * somewhere in one of the translation units (usually .cpp source files).
449 *
450 * @param cls class to declare a ctor and dtor for
451 */
452#define DECLARE_EMPTY_CTOR_DTOR(cls) cls(); ~cls();
453
454/**
455 * Defines an empty constructor and destructor for the given class.
456 * See DECLARE_EMPTY_CTOR_DTOR for more info.
457 */
458#define DEFINE_EMPTY_CTOR_DTOR(cls) \
459 cls::cls() { /*empty*/ } \
460 cls::~cls() { /*empty*/ }
461
462/**
463 * A variant of 'throw' that hits a debug breakpoint first to make
464 * finding the actual thrower possible.
465 */
466#ifdef DEBUG
467#define DebugBreakThrow(a) \
468 do { \
469 RTAssertDebugBreak(); \
470 throw (a); \
471} while (0)
472#else
473#define DebugBreakThrow(a) throw (a)
474#endif
475
476/**
477 * Parent class of VirtualBoxBase which enables translation support (which
478 * Main doesn't have yet, but this provides the tr() function which will one
479 * day provide translations).
480 *
481 * This class sits in between Lockable and VirtualBoxBase only for the one
482 * reason that the USBProxyService wants translation support but is not
483 * implemented as a COM object, which VirtualBoxBase implies.
484 */
485class ATL_NO_VTABLE VirtualBoxTranslatable
486 : public Lockable
487{
488public:
489
490 /**
491 * Placeholder method with which translations can one day be implemented
492 * in Main. This gets called by the tr() function.
493 * @param context
494 * @param pcszSourceText
495 * @param comment
496 * @return
497 */
498 static const char *translate(const char *context,
499 const char *pcszSourceText,
500 const char *comment = 0)
501 {
502 NOREF(context);
503 NOREF(comment);
504 return pcszSourceText;
505 }
506
507 /**
508 * Translates the given text string by calling translate() and passing
509 * the name of the C class as the first argument ("context of
510 * translation"). See VirtualBoxBase::translate() for more info.
511 *
512 * @param aSourceText String to translate.
513 * @param aComment Comment to the string to resolve possible
514 * ambiguities (NULL means no comment).
515 *
516 * @return Translated version of the source string in UTF-8 encoding, or
517 * the source string itself if the translation is not found in the
518 * specified context.
519 */
520 inline static const char *tr(const char *pcszSourceText,
521 const char *aComment = NULL)
522 {
523 return VirtualBoxTranslatable::translate(NULL, // getComponentName(), eventually
524 pcszSourceText,
525 aComment);
526 }
527};
528
529////////////////////////////////////////////////////////////////////////////////
530//
531// VirtualBoxBase
532//
533////////////////////////////////////////////////////////////////////////////////
534
535#define VIRTUALBOXBASE_ADD_VIRTUAL_COMPONENT_METHODS(cls, iface) \
536 virtual const IID& getClassIID() const \
537 { \
538 return cls::getStaticClassIID(); \
539 } \
540 static const IID& getStaticClassIID() \
541 { \
542 return COM_IIDOF(iface); \
543 } \
544 virtual const char* getComponentName() const \
545 { \
546 return cls::getStaticComponentName(); \
547 } \
548 static const char* getStaticComponentName() \
549 { \
550 return #cls; \
551 }
552
553/**
554 * VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT:
555 * This macro must be used once in the declaration of any class derived
556 * from VirtualBoxBase. It implements the pure virtual getClassIID() and
557 * getComponentName() methods. If this macro is not present, instances
558 * of a class derived from VirtualBoxBase cannot be instantiated.
559 *
560 * @param X The class name, e.g. "Class".
561 * @param IX The interface name which this class implements, e.g. "IClass".
562 */
563#ifdef VBOX_WITH_XPCOM
564 #define VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT(cls, iface) \
565 VIRTUALBOXBASE_ADD_VIRTUAL_COMPONENT_METHODS(cls, iface)
566#else // #ifdef VBOX_WITH_XPCOM
567 #define VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT(cls, iface) \
568 VIRTUALBOXBASE_ADD_VIRTUAL_COMPONENT_METHODS(cls, iface) \
569 STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid) \
570 { \
571 const _ATL_INTMAP_ENTRY* pEntries = cls::_GetEntries(); \
572 Assert(pEntries); \
573 if (!pEntries) \
574 return S_FALSE; \
575 BOOL bSupports = FALSE; \
576 BOOL bISupportErrorInfoFound = FALSE; \
577 while (pEntries->pFunc != NULL && !bSupports) \
578 { \
579 if (!bISupportErrorInfoFound) \
580 bISupportErrorInfoFound = InlineIsEqualGUID(*(pEntries->piid), IID_ISupportErrorInfo); \
581 else \
582 bSupports = InlineIsEqualGUID(*(pEntries->piid), riid); \
583 pEntries++; \
584 } \
585 Assert(bISupportErrorInfoFound); \
586 return bSupports ? S_OK : S_FALSE; \
587 }
588#endif // #ifdef VBOX_WITH_XPCOM
589
590/**
591 * Abstract base class for all component classes implementing COM
592 * interfaces of the VirtualBox COM library.
593 *
594 * Declares functionality that should be available in all components.
595 *
596 * Among the basic functionality implemented by this class is the primary object
597 * state that indicates if the object is ready to serve the calls, and if not,
598 * what stage it is currently at. Here is the primary state diagram:
599 *
600 * +-------------------------------------------------------+
601 * | |
602 * | (InitFailed) -----------------------+ |
603 * | ^ | |
604 * v | v |
605 * [*] ---> NotReady ----> (InInit) -----> Ready -----> (InUninit) ----+
606 * ^ |
607 * | v
608 * | Limited
609 * | |
610 * +-------+
611 *
612 * The object is fully operational only when its state is Ready. The Limited
613 * state means that only some vital part of the object is operational, and it
614 * requires some sort of reinitialization to become fully operational. The
615 * NotReady state means the object is basically dead: it either was not yet
616 * initialized after creation at all, or was uninitialized and is waiting to be
617 * destroyed when the last reference to it is released. All other states are
618 * transitional.
619 *
620 * The NotReady->InInit->Ready, NotReady->InInit->Limited and
621 * NotReady->InInit->InitFailed transition is done by the AutoInitSpan smart
622 * class.
623 *
624 * The Limited->InInit->Ready, Limited->InInit->Limited and
625 * Limited->InInit->InitFailed transition is done by the AutoReinitSpan smart
626 * class.
627 *
628 * The Ready->InUninit->NotReady and InitFailed->InUninit->NotReady
629 * transitions are done by the AutoUninitSpan smart class.
630 *
631 * In order to maintain the primary state integrity and declared functionality
632 * all subclasses must:
633 *
634 * 1) Use the above Auto*Span classes to perform state transitions. See the
635 * individual class descriptions for details.
636 *
637 * 2) All public methods of subclasses (i.e. all methods that can be called
638 * directly, not only from within other methods of the subclass) must have a
639 * standard prolog as described in the AutoCaller and AutoLimitedCaller
640 * documentation. Alternatively, they must use addCaller()/releaseCaller()
641 * directly (and therefore have both the prolog and the epilog), but this is
642 * not recommended.
643 */
644class ATL_NO_VTABLE VirtualBoxBase
645 : public VirtualBoxTranslatable,
646 public CComObjectRootEx<CComMultiThreadModel>
647#if !defined (VBOX_WITH_XPCOM)
648 , public ISupportErrorInfo
649#endif
650{
651protected:
652#ifdef RT_OS_WINDOWS
653 CComPtr <IUnknown> m_pUnkMarshaler;
654#endif
655
656 HRESULT BaseFinalConstruct()
657 {
658#ifdef RT_OS_WINDOWS
659 return CoCreateFreeThreadedMarshaler(this, //GetControllingUnknown(),
660 &m_pUnkMarshaler.p);
661#else
662 return S_OK;
663#endif
664 }
665
666 void BaseFinalRelease()
667 {
668#ifdef RT_OS_WINDOWS
669 m_pUnkMarshaler.Release();
670#endif
671 }
672
673
674public:
675 enum State { NotReady, Ready, InInit, InUninit, InitFailed, Limited };
676
677 VirtualBoxBase();
678 virtual ~VirtualBoxBase();
679
680 /**
681 * Uninitialization method.
682 *
683 * Must be called by all final implementations (component classes) when the
684 * last reference to the object is released, before calling the destructor.
685 *
686 * @note Never call this method the AutoCaller scope or after the
687 * #addCaller() call not paired by #releaseCaller() because it is a
688 * guaranteed deadlock. See AutoUninitSpan for details.
689 */
690 virtual void uninit()
691 { }
692
693 virtual HRESULT addCaller(State *aState = NULL,
694 bool aLimited = false);
695 virtual void releaseCaller();
696
697 /**
698 * Adds a limited caller. This method is equivalent to doing
699 * <tt>addCaller (aState, true)</tt>, but it is preferred because provides
700 * better self-descriptiveness. See #addCaller() for more info.
701 */
702 HRESULT addLimitedCaller(State *aState = NULL)
703 {
704 return addCaller(aState, true /* aLimited */);
705 }
706
707 /**
708 * Pure virtual method for simple run-time type identification without
709 * having to enable C++ RTTI.
710 *
711 * This *must* be implemented by every subclass deriving from VirtualBoxBase;
712 * use the VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT macro to do that most easily.
713 */
714 virtual const IID& getClassIID() const = 0;
715
716 /**
717 * Pure virtual method for simple run-time type identification without
718 * having to enable C++ RTTI.
719 *
720 * This *must* be implemented by every subclass deriving from VirtualBoxBase;
721 * use the VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT macro to do that most easily.
722 */
723 virtual const char* getComponentName() const = 0;
724
725 /**
726 * Virtual method which determines the locking class to be used for validating
727 * lock order with the standard member lock handle. This method is overridden
728 * in a number of subclasses.
729 */
730 virtual VBoxLockingClass getLockingClass() const
731 {
732 return LOCKCLASS_OTHEROBJECT;
733 }
734
735 virtual RWLockHandle *lockHandle() const;
736
737 /**
738 * Returns a lock handle used to protect the primary state fields (used by
739 * #addCaller(), AutoInitSpan, AutoUninitSpan, etc.). Only intended to be
740 * used for similar purposes in subclasses. WARNING: NO any other locks may
741 * be requested while holding this lock!
742 */
743 WriteLockHandle *stateLockHandle() { return &mStateLock; }
744
745 static HRESULT setErrorInternal(HRESULT aResultCode,
746 const GUID &aIID,
747 const char *aComponent,
748 const Utf8Str &aText,
749 bool aWarning,
750 bool aLogIt);
751 static void clearError(void);
752
753 HRESULT setError(HRESULT aResultCode, const char *pcsz, ...);
754 HRESULT setWarning(HRESULT aResultCode, const char *pcsz, ...);
755 HRESULT setErrorNoLog(HRESULT aResultCode, const char *pcsz, ...);
756
757
758 /** Initialize COM for a new thread. */
759 static HRESULT initializeComForThread(void)
760 {
761#ifndef VBOX_WITH_XPCOM
762 HRESULT hrc = CoInitializeEx(NULL, COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE | COINIT_SPEED_OVER_MEMORY);
763 AssertComRCReturn(hrc, hrc);
764#endif
765 return S_OK;
766 }
767
768 /** Uninitializes COM for a dying thread. */
769 static void uninitializeComForThread(void)
770 {
771#ifndef VBOX_WITH_XPCOM
772 CoUninitialize();
773#endif
774 }
775
776
777private:
778
779 void setState(State aState)
780 {
781 Assert(mState != aState);
782 mState = aState;
783 mStateChangeThread = RTThreadSelf();
784 }
785
786 /** Primary state of this object */
787 State mState;
788 /** Thread that caused the last state change */
789 RTTHREAD mStateChangeThread;
790 /** Total number of active calls to this object */
791 unsigned mCallers;
792 /** Posted when the number of callers drops to zero */
793 RTSEMEVENT mZeroCallersSem;
794 /** Posted when the object goes from InInit/InUninit to some other state */
795 RTSEMEVENTMULTI mInitUninitSem;
796 /** Number of threads waiting for mInitUninitDoneSem */
797 unsigned mInitUninitWaiters;
798
799 /** Protects access to state related data members */
800 WriteLockHandle mStateLock;
801
802 /** User-level object lock for subclasses */
803 mutable RWLockHandle *mObjectLock;
804
805 friend class AutoInitSpan;
806 friend class AutoReinitSpan;
807 friend class AutoUninitSpan;
808};
809
810/**
811 * Dummy macro that is used to shut down Qt's lupdate tool warnings in some
812 * situations. This macro needs to be present inside (better at the very
813 * beginning) of the declaration of the class that inherits from
814 * VirtualBoxSupportTranslation template, to make lupdate happy.
815 */
816#define Q_OBJECT
817
818////////////////////////////////////////////////////////////////////////////////
819
820////////////////////////////////////////////////////////////////////////////////
821
822
823/**
824 * Simple template that manages data structure allocation/deallocation
825 * and supports data pointer sharing (the instance that shares the pointer is
826 * not responsible for memory deallocation as opposed to the instance that
827 * owns it).
828 */
829template <class D>
830class Shareable
831{
832public:
833
834 Shareable() : mData (NULL), mIsShared(FALSE) {}
835 ~Shareable() { free(); }
836
837 void allocate() { attach(new D); }
838
839 virtual void free() {
840 if (mData) {
841 if (!mIsShared)
842 delete mData;
843 mData = NULL;
844 mIsShared = false;
845 }
846 }
847
848 void attach(D *d) {
849 AssertMsg(d, ("new data must not be NULL"));
850 if (d && mData != d) {
851 if (mData && !mIsShared)
852 delete mData;
853 mData = d;
854 mIsShared = false;
855 }
856 }
857
858 void attach(Shareable &d) {
859 AssertMsg(
860 d.mData == mData || !d.mIsShared,
861 ("new data must not be shared")
862 );
863 if (this != &d && !d.mIsShared) {
864 attach(d.mData);
865 d.mIsShared = true;
866 }
867 }
868
869 void share(D *d) {
870 AssertMsg(d, ("new data must not be NULL"));
871 if (mData != d) {
872 if (mData && !mIsShared)
873 delete mData;
874 mData = d;
875 mIsShared = true;
876 }
877 }
878
879 void share(const Shareable &d) { share(d.mData); }
880
881 void attachCopy(const D *d) {
882 AssertMsg(d, ("data to copy must not be NULL"));
883 if (d)
884 attach(new D(*d));
885 }
886
887 void attachCopy(const Shareable &d) {
888 attachCopy(d.mData);
889 }
890
891 virtual D *detach() {
892 D *d = mData;
893 mData = NULL;
894 mIsShared = false;
895 return d;
896 }
897
898 D *data() const {
899 return mData;
900 }
901
902 D *operator->() const {
903 AssertMsg(mData, ("data must not be NULL"));
904 return mData;
905 }
906
907 bool isNull() const { return mData == NULL; }
908 bool operator!() const { return isNull(); }
909
910 bool isShared() const { return mIsShared; }
911
912protected:
913
914 D *mData;
915 bool mIsShared;
916};
917
918/**
919 * Simple template that enhances Shareable<> and supports data
920 * backup/rollback/commit (using the copy constructor of the managed data
921 * structure).
922 */
923template<class D>
924class Backupable : public Shareable<D>
925{
926public:
927
928 Backupable() : Shareable<D> (), mBackupData(NULL) {}
929
930 void free()
931 {
932 AssertMsg(this->mData || !mBackupData, ("backup must be NULL if data is NULL"));
933 rollback();
934 Shareable<D>::free();
935 }
936
937 D *detach()
938 {
939 AssertMsg(this->mData || !mBackupData, ("backup must be NULL if data is NULL"));
940 rollback();
941 return Shareable<D>::detach();
942 }
943
944 void share(const Backupable &d)
945 {
946 AssertMsg(!d.isBackedUp(), ("data to share must not be backed up"));
947 if (!d.isBackedUp())
948 Shareable<D>::share(d.mData);
949 }
950
951 /**
952 * Stores the current data pointer in the backup area, allocates new data
953 * using the copy constructor on current data and makes new data active.
954 */
955 void backup()
956 {
957 AssertMsg(this->mData, ("data must not be NULL"));
958 if (this->mData && !mBackupData)
959 {
960 D *pNewData = new D(*this->mData);
961 mBackupData = this->mData;
962 this->mData = pNewData;
963 }
964 }
965
966 /**
967 * Deletes new data created by #backup() and restores previous data pointer
968 * stored in the backup area, making it active again.
969 */
970 void rollback()
971 {
972 if (this->mData && mBackupData)
973 {
974 delete this->mData;
975 this->mData = mBackupData;
976 mBackupData = NULL;
977 }
978 }
979
980 /**
981 * Commits current changes by deleting backed up data and clearing up the
982 * backup area. The new data pointer created by #backup() remains active
983 * and becomes the only managed pointer.
984 *
985 * This method is much faster than #commitCopy() (just a single pointer
986 * assignment operation), but makes the previous data pointer invalid
987 * (because it is freed). For this reason, this method must not be
988 * used if it's possible that data managed by this instance is shared with
989 * some other Shareable instance. See #commitCopy().
990 */
991 void commit()
992 {
993 if (this->mData && mBackupData)
994 {
995 if (!this->mIsShared)
996 delete mBackupData;
997 mBackupData = NULL;
998 this->mIsShared = false;
999 }
1000 }
1001
1002 /**
1003 * Commits current changes by assigning new data to the previous data
1004 * pointer stored in the backup area using the assignment operator.
1005 * New data is deleted, the backup area is cleared and the previous data
1006 * pointer becomes active and the only managed pointer.
1007 *
1008 * This method is slower than #commit(), but it keeps the previous data
1009 * pointer valid (i.e. new data is copied to the same memory location).
1010 * For that reason it's safe to use this method on instances that share
1011 * managed data with other Shareable instances.
1012 */
1013 void commitCopy()
1014 {
1015 if (this->mData && mBackupData)
1016 {
1017 *mBackupData = *(this->mData);
1018 delete this->mData;
1019 this->mData = mBackupData;
1020 mBackupData = NULL;
1021 }
1022 }
1023
1024 void assignCopy(const D *pData)
1025 {
1026 AssertMsg(this->mData, ("data must not be NULL"));
1027 AssertMsg(pData, ("data to copy must not be NULL"));
1028 if (this->mData && pData)
1029 {
1030 if (!mBackupData)
1031 {
1032 D *pNewData = new D(*pData);
1033 mBackupData = this->mData;
1034 this->mData = pNewData;
1035 }
1036 else
1037 *this->mData = *pData;
1038 }
1039 }
1040
1041 void assignCopy(const Backupable &d)
1042 {
1043 assignCopy(d.mData);
1044 }
1045
1046 bool isBackedUp() const
1047 {
1048 return mBackupData != NULL;
1049 }
1050
1051 D *backedUpData() const
1052 {
1053 return mBackupData;
1054 }
1055
1056protected:
1057
1058 D *mBackupData;
1059};
1060
1061#endif // !____H_VIRTUALBOXBASEIMPL
1062
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