VirtualBox

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

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

VirtualBoxBase.h: Replaced RT_UNLIKELY with RT_LIKELY to improve our karma wrt MSC.

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