VirtualBox

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

Last change on this file since 51337 was 51337, checked in by vboxsync, 11 years ago

VirtualBoxBase.h: CheckComArgPointerValid

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