VirtualBox

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

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

ExtPack: Fixes to IExtPack (QueryInterface can't be used for getting stuff from the ext pack, designed the plug-in interfaces). Bugfixes making 'VBoxManage list extpack' work when building with VBOX_WITH_EXTPACK_PUEL=1.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 33.7 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__); \
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{
640public:
641 enum State { NotReady, Ready, InInit, InUninit, InitFailed, Limited };
642
643 VirtualBoxBase();
644 virtual ~VirtualBoxBase();
645
646 /**
647 * Uninitialization method.
648 *
649 * Must be called by all final implementations (component classes) when the
650 * last reference to the object is released, before calling the destructor.
651 *
652 * @note Never call this method the AutoCaller scope or after the
653 * #addCaller() call not paired by #releaseCaller() because it is a
654 * guaranteed deadlock. See AutoUninitSpan for details.
655 */
656 virtual void uninit()
657 { }
658
659 virtual HRESULT addCaller(State *aState = NULL,
660 bool aLimited = false);
661 virtual void releaseCaller();
662
663 /**
664 * Adds a limited caller. This method is equivalent to doing
665 * <tt>addCaller (aState, true)</tt>, but it is preferred because provides
666 * better self-descriptiveness. See #addCaller() for more info.
667 */
668 HRESULT addLimitedCaller(State *aState = NULL)
669 {
670 return addCaller(aState, true /* aLimited */);
671 }
672
673 /**
674 * Pure virtual method for simple run-time type identification without
675 * having to enable C++ RTTI.
676 *
677 * This *must* be implemented by every subclass deriving from VirtualBoxBase;
678 * use the VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT macro to do that most easily.
679 */
680 virtual const IID& getClassIID() const = 0;
681
682 /**
683 * Pure virtual method for simple run-time type identification without
684 * having to enable C++ RTTI.
685 *
686 * This *must* be implemented by every subclass deriving from VirtualBoxBase;
687 * use the VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT macro to do that most easily.
688 */
689 virtual const char* getComponentName() const = 0;
690
691 /**
692 * Virtual method which determines the locking class to be used for validating
693 * lock order with the standard member lock handle. This method is overridden
694 * in a number of subclasses.
695 */
696 virtual VBoxLockingClass getLockingClass() const
697 {
698 return LOCKCLASS_OTHEROBJECT;
699 }
700
701 virtual RWLockHandle *lockHandle() const;
702
703 /**
704 * Returns a lock handle used to protect the primary state fields (used by
705 * #addCaller(), AutoInitSpan, AutoUninitSpan, etc.). Only intended to be
706 * used for similar purposes in subclasses. WARNING: NO any other locks may
707 * be requested while holding this lock!
708 */
709 WriteLockHandle *stateLockHandle() { return &mStateLock; }
710
711 static HRESULT setErrorInternal(HRESULT aResultCode,
712 const GUID &aIID,
713 const char *aComponent,
714 const Utf8Str &aText,
715 bool aWarning,
716 bool aLogIt);
717
718 HRESULT setError(HRESULT aResultCode, const char *pcsz, ...);
719 HRESULT setWarning(HRESULT aResultCode, const char *pcsz, ...);
720 HRESULT setErrorNoLog(HRESULT aResultCode, const char *pcsz, ...);
721
722private:
723
724 void setState(State aState)
725 {
726 Assert(mState != aState);
727 mState = aState;
728 mStateChangeThread = RTThreadSelf();
729 }
730
731 /** Primary state of this object */
732 State mState;
733 /** Thread that caused the last state change */
734 RTTHREAD mStateChangeThread;
735 /** Total number of active calls to this object */
736 unsigned mCallers;
737 /** Posted when the number of callers drops to zero */
738 RTSEMEVENT mZeroCallersSem;
739 /** Posted when the object goes from InInit/InUninit to some other state */
740 RTSEMEVENTMULTI mInitUninitSem;
741 /** Number of threads waiting for mInitUninitDoneSem */
742 unsigned mInitUninitWaiters;
743
744 /** Protects access to state related data members */
745 WriteLockHandle mStateLock;
746
747 /** User-level object lock for subclasses */
748 mutable RWLockHandle *mObjectLock;
749
750 friend class AutoInitSpan;
751 friend class AutoReinitSpan;
752 friend class AutoUninitSpan;
753};
754
755/**
756 * Dummy macro that is used to shut down Qt's lupdate tool warnings in some
757 * situations. This macro needs to be present inside (better at the very
758 * beginning) of the declaration of the class that inherits from
759 * VirtualBoxSupportTranslation template, to make lupdate happy.
760 */
761#define Q_OBJECT
762
763////////////////////////////////////////////////////////////////////////////////
764
765////////////////////////////////////////////////////////////////////////////////
766
767
768/**
769 * Simple template that manages data structure allocation/deallocation
770 * and supports data pointer sharing (the instance that shares the pointer is
771 * not responsible for memory deallocation as opposed to the instance that
772 * owns it).
773 */
774template <class D>
775class Shareable
776{
777public:
778
779 Shareable() : mData (NULL), mIsShared(FALSE) {}
780 ~Shareable() { free(); }
781
782 void allocate() { attach(new D); }
783
784 virtual void free() {
785 if (mData) {
786 if (!mIsShared)
787 delete mData;
788 mData = NULL;
789 mIsShared = false;
790 }
791 }
792
793 void attach(D *d) {
794 AssertMsg(d, ("new data must not be NULL"));
795 if (d && mData != d) {
796 if (mData && !mIsShared)
797 delete mData;
798 mData = d;
799 mIsShared = false;
800 }
801 }
802
803 void attach(Shareable &d) {
804 AssertMsg(
805 d.mData == mData || !d.mIsShared,
806 ("new data must not be shared")
807 );
808 if (this != &d && !d.mIsShared) {
809 attach(d.mData);
810 d.mIsShared = true;
811 }
812 }
813
814 void share(D *d) {
815 AssertMsg(d, ("new data must not be NULL"));
816 if (mData != d) {
817 if (mData && !mIsShared)
818 delete mData;
819 mData = d;
820 mIsShared = true;
821 }
822 }
823
824 void share(const Shareable &d) { share(d.mData); }
825
826 void attachCopy(const D *d) {
827 AssertMsg(d, ("data to copy must not be NULL"));
828 if (d)
829 attach(new D(*d));
830 }
831
832 void attachCopy(const Shareable &d) {
833 attachCopy(d.mData);
834 }
835
836 virtual D *detach() {
837 D *d = mData;
838 mData = NULL;
839 mIsShared = false;
840 return d;
841 }
842
843 D *data() const {
844 return mData;
845 }
846
847 D *operator->() const {
848 AssertMsg(mData, ("data must not be NULL"));
849 return mData;
850 }
851
852 bool isNull() const { return mData == NULL; }
853 bool operator!() const { return isNull(); }
854
855 bool isShared() const { return mIsShared; }
856
857protected:
858
859 D *mData;
860 bool mIsShared;
861};
862
863/**
864 * Simple template that enhances Shareable<> and supports data
865 * backup/rollback/commit (using the copy constructor of the managed data
866 * structure).
867 */
868template<class D>
869class Backupable : public Shareable<D>
870{
871public:
872
873 Backupable() : Shareable<D> (), mBackupData(NULL) {}
874
875 void free()
876 {
877 AssertMsg(this->mData || !mBackupData, ("backup must be NULL if data is NULL"));
878 rollback();
879 Shareable<D>::free();
880 }
881
882 D *detach()
883 {
884 AssertMsg(this->mData || !mBackupData, ("backup must be NULL if data is NULL"));
885 rollback();
886 return Shareable<D>::detach();
887 }
888
889 void share(const Backupable &d)
890 {
891 AssertMsg(!d.isBackedUp(), ("data to share must not be backed up"));
892 if (!d.isBackedUp())
893 Shareable<D>::share(d.mData);
894 }
895
896 /**
897 * Stores the current data pointer in the backup area, allocates new data
898 * using the copy constructor on current data and makes new data active.
899 */
900 void backup()
901 {
902 AssertMsg(this->mData, ("data must not be NULL"));
903 if (this->mData && !mBackupData)
904 {
905 D *pNewData = new D(*this->mData);
906 mBackupData = this->mData;
907 this->mData = pNewData;
908 }
909 }
910
911 /**
912 * Deletes new data created by #backup() and restores previous data pointer
913 * stored in the backup area, making it active again.
914 */
915 void rollback()
916 {
917 if (this->mData && mBackupData)
918 {
919 delete this->mData;
920 this->mData = mBackupData;
921 mBackupData = NULL;
922 }
923 }
924
925 /**
926 * Commits current changes by deleting backed up data and clearing up the
927 * backup area. The new data pointer created by #backup() remains active
928 * and becomes the only managed pointer.
929 *
930 * This method is much faster than #commitCopy() (just a single pointer
931 * assignment operation), but makes the previous data pointer invalid
932 * (because it is freed). For this reason, this method must not be
933 * used if it's possible that data managed by this instance is shared with
934 * some other Shareable instance. See #commitCopy().
935 */
936 void commit()
937 {
938 if (this->mData && mBackupData)
939 {
940 if (!this->mIsShared)
941 delete mBackupData;
942 mBackupData = NULL;
943 this->mIsShared = false;
944 }
945 }
946
947 /**
948 * Commits current changes by assigning new data to the previous data
949 * pointer stored in the backup area using the assignment operator.
950 * New data is deleted, the backup area is cleared and the previous data
951 * pointer becomes active and the only managed pointer.
952 *
953 * This method is slower than #commit(), but it keeps the previous data
954 * pointer valid (i.e. new data is copied to the same memory location).
955 * For that reason it's safe to use this method on instances that share
956 * managed data with other Shareable instances.
957 */
958 void commitCopy()
959 {
960 if (this->mData && mBackupData)
961 {
962 *mBackupData = *(this->mData);
963 delete this->mData;
964 this->mData = mBackupData;
965 mBackupData = NULL;
966 }
967 }
968
969 void assignCopy(const D *pData)
970 {
971 AssertMsg(this->mData, ("data must not be NULL"));
972 AssertMsg(pData, ("data to copy must not be NULL"));
973 if (this->mData && pData)
974 {
975 if (!mBackupData)
976 {
977 D *pNewData = new D(*pData);
978 mBackupData = this->mData;
979 this->mData = pNewData;
980 }
981 else
982 *this->mData = *pData;
983 }
984 }
985
986 void assignCopy(const Backupable &d)
987 {
988 assignCopy(d.mData);
989 }
990
991 bool isBackedUp() const
992 {
993 return mBackupData != NULL;
994 }
995
996 D *backedUpData() const
997 {
998 return mBackupData;
999 }
1000
1001protected:
1002
1003 D *mBackupData;
1004};
1005
1006#endif // !____H_VIRTUALBOXBASEIMPL
1007
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