VirtualBox

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

Last change on this file since 45706 was 45706, checked in by vboxsync, 12 years ago

more temporary debugging

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

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