VirtualBox

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

Last change on this file since 53390 was 51903, checked in by vboxsync, 10 years ago

Main: AutoCaller/VirtualBoxBase refactoring, cleanly splitting out the object state handling, and moving all caller synchronization to one file. Also eliminated a not so vital template (AutoCallerBase) by much simpler inheritance. Theoretically has no visible effects, the behavior should be identical. Done as a preparation for reimplementing the caller synchronization.

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