VirtualBox

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

Last change on this file since 23223 was 23223, checked in by vboxsync, 15 years ago

API: big medium handling change and lots of assorted other cleanups and fixes

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 96.8 KB
Line 
1/** @file
2 *
3 * VirtualBox COM base classes definition
4 */
5
6/*
7 * Copyright (C) 2006-2009 Sun Microsystems, Inc.
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. 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 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
18 * Clara, CA 95054 USA or visit http://www.sun.com if you need
19 * additional information or have any questions.
20 */
21
22#ifndef ____H_VIRTUALBOXBASEIMPL
23#define ____H_VIRTUALBOXBASEIMPL
24
25#include <iprt/cdefs.h>
26#include <iprt/critsect.h>
27#include <iprt/thread.h>
28
29#include <list>
30#include <map>
31
32#include "VBox/com/ErrorInfo.h"
33
34#include "VBox/com/VirtualBox.h"
35
36// avoid including VBox/settings.h and VBox/xml.h;
37// only declare the classes
38namespace xml
39{
40class File;
41}
42
43#include "AutoLock.h"
44
45using namespace com;
46using namespace util;
47
48#if !defined (VBOX_WITH_XPCOM)
49
50#include <atlcom.h>
51
52/* use a special version of the singleton class factory,
53 * see KB811591 in msdn for more info. */
54
55#undef DECLARE_CLASSFACTORY_SINGLETON
56#define DECLARE_CLASSFACTORY_SINGLETON(obj) DECLARE_CLASSFACTORY_EX(CMyComClassFactorySingleton<obj>)
57
58template <class T>
59class CMyComClassFactorySingleton : public CComClassFactory
60{
61public:
62 CMyComClassFactorySingleton() : m_hrCreate(S_OK){}
63 virtual ~CMyComClassFactorySingleton(){}
64 // IClassFactory
65 STDMETHOD(CreateInstance)(LPUNKNOWN pUnkOuter, REFIID riid, void** ppvObj)
66 {
67 HRESULT hRes = E_POINTER;
68 if (ppvObj != NULL)
69 {
70 *ppvObj = NULL;
71 // Aggregation is not supported in singleton objects.
72 ATLASSERT(pUnkOuter == NULL);
73 if (pUnkOuter != NULL)
74 hRes = CLASS_E_NOAGGREGATION;
75 else
76 {
77 if (m_hrCreate == S_OK && m_spObj == NULL)
78 {
79 Lock();
80 __try
81 {
82 // Fix: The following If statement was moved inside the __try statement.
83 // Did another thread arrive here first?
84 if (m_hrCreate == S_OK && m_spObj == NULL)
85 {
86 // lock the module to indicate activity
87 // (necessary for the monitor shutdown thread to correctly
88 // terminate the module in case when CreateInstance() fails)
89 _pAtlModule->Lock();
90 CComObjectCached<T> *p;
91 m_hrCreate = CComObjectCached<T>::CreateInstance(&p);
92 if (SUCCEEDED(m_hrCreate))
93 {
94 m_hrCreate = p->QueryInterface(IID_IUnknown, (void**)&m_spObj);
95 if (FAILED(m_hrCreate))
96 {
97 delete p;
98 }
99 }
100 _pAtlModule->Unlock();
101 }
102 }
103 __finally
104 {
105 Unlock();
106 }
107 }
108 if (m_hrCreate == S_OK)
109 {
110 hRes = m_spObj->QueryInterface(riid, ppvObj);
111 }
112 else
113 {
114 hRes = m_hrCreate;
115 }
116 }
117 }
118 return hRes;
119 }
120 HRESULT m_hrCreate;
121 CComPtr<IUnknown> m_spObj;
122};
123
124#endif /* !defined (VBOX_WITH_XPCOM) */
125
126// macros
127////////////////////////////////////////////////////////////////////////////////
128
129/**
130 * Special version of the Assert macro to be used within VirtualBoxBase
131 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
132 *
133 * In the debug build, this macro is equivalent to Assert.
134 * In the release build, this macro uses |setError (E_FAIL, ...)| to set the
135 * error info from the asserted expression.
136 *
137 * @see VirtualBoxSupportErrorInfoImpl::setError
138 *
139 * @param expr Expression which should be true.
140 */
141#if defined (DEBUG)
142#define ComAssert(expr) Assert (expr)
143#else
144#define ComAssert(expr) \
145 do { \
146 if (!(expr)) \
147 setError (E_FAIL, "Assertion failed: [%s] at '%s' (%d) in %s.\n" \
148 "Please contact the product vendor!", \
149 #expr, __FILE__, __LINE__, __PRETTY_FUNCTION__); \
150 } while (0)
151#endif
152
153/**
154 * Special version of the AssertMsg macro to be used within VirtualBoxBase
155 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
156 *
157 * See ComAssert for more info.
158 *
159 * @param expr Expression which should be true.
160 * @param a printf argument list (in parenthesis).
161 */
162#if defined (DEBUG)
163#define ComAssertMsg(expr, a) AssertMsg (expr, a)
164#else
165#define ComAssertMsg(expr, a) \
166 do { \
167 if (!(expr)) \
168 setError (E_FAIL, "Assertion failed: [%s] at '%s' (%d) in %s.\n" \
169 "%s.\n" \
170 "Please contact the product vendor!", \
171 #expr, __FILE__, __LINE__, __PRETTY_FUNCTION__, Utf8StrFmt a .raw()); \
172 } while (0)
173#endif
174
175/**
176 * Special version of the AssertRC macro to be used within VirtualBoxBase
177 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
178 *
179 * See ComAssert for more info.
180 *
181 * @param vrc VBox status code.
182 */
183#if defined (DEBUG)
184#define ComAssertRC(vrc) AssertRC (vrc)
185#else
186#define ComAssertRC(vrc) ComAssertMsgRC (vrc, ("%Rra", vrc))
187#endif
188
189/**
190 * Special version of the AssertMsgRC macro to be used within VirtualBoxBase
191 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
192 *
193 * See ComAssert for more info.
194 *
195 * @param vrc VBox status code.
196 * @param msg printf argument list (in parenthesis).
197 */
198#if defined (DEBUG)
199#define ComAssertMsgRC(vrc, msg) AssertMsgRC (vrc, msg)
200#else
201#define ComAssertMsgRC(vrc, msg) ComAssertMsg (RT_SUCCESS (vrc), msg)
202#endif
203
204
205/**
206 * Special version of the AssertFailed macro to be used within VirtualBoxBase
207 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
208 *
209 * See ComAssert for more info.
210 */
211#if defined (DEBUG)
212#define ComAssertFailed() AssertFailed()
213#else
214#define ComAssertFailed() \
215 do { \
216 setError (E_FAIL, "Assertion failed at '%s' (%d) in %s.\n" \
217 "Please contact the product vendor!", \
218 __FILE__, __LINE__, __PRETTY_FUNCTION__); \
219 } while (0)
220#endif
221
222/**
223 * Special version of the AssertMsgFailed macro to be used within VirtualBoxBase
224 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
225 *
226 * See ComAssert for more info.
227 *
228 * @param a printf argument list (in parenthesis).
229 */
230#if defined (DEBUG)
231#define ComAssertMsgFailed(a) AssertMsgFailed(a)
232#else
233#define ComAssertMsgFailed(a) \
234 do { \
235 setError (E_FAIL, "Assertion failed at '%s' (%d) in %s.\n" \
236 "%s.\n" \
237 "Please contact the product vendor!", \
238 __FILE__, __LINE__, __PRETTY_FUNCTION__, Utf8StrFmt a .raw()); \
239 } while (0)
240#endif
241
242/**
243 * Special version of the ComAssertMsgFailed macro that additionally takes
244 * line number, file and function arguments to inject an assertion position
245 * that differs from the position where this macro is instantiated.
246 *
247 * @param a printf argument list (in parenthesis).
248 * @param file, line, func Line number (int), file and function (const char *).
249 */
250#if defined (DEBUG)
251#define ComAssertMsgFailedPos(a, file, line, func) \
252 do { \
253 AssertMsg1 ((const char *) 0, line, file, func); \
254 AssertMsg2 a; \
255 AssertBreakpoint(); \
256 } while (0)
257#else
258#define ComAssertMsgFailedPos(a, file, line, func) \
259 do { \
260 setError (E_FAIL, \
261 "Assertion failed at '%s' (%d) in %s.\n" \
262 "%s.\n" \
263 "Please contact the product vendor!", \
264 file, line, func, Utf8StrFmt a .raw()); \
265 } while (0)
266#endif
267
268/**
269 * Special version of the AssertComRC macro to be used within VirtualBoxBase
270 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
271 *
272 * See ComAssert for more info.
273 *
274 * @param rc COM result code
275 */
276#if defined (DEBUG)
277#define ComAssertComRC(rc) AssertComRC (rc)
278#else
279#define ComAssertComRC(rc) ComAssertMsg (SUCCEEDED (rc), ("COM RC = %Rhrc (0x%08X)", (rc), (rc)))
280#endif
281
282
283/** Special version of ComAssert that returns ret if expr fails */
284#define ComAssertRet(expr, ret) \
285 do { ComAssert (expr); if (!(expr)) return (ret); } while (0)
286/** Special version of ComAssertMsg that returns ret if expr fails */
287#define ComAssertMsgRet(expr, a, ret) \
288 do { ComAssertMsg (expr, a); if (!(expr)) return (ret); } while (0)
289/** Special version of ComAssertRC that returns ret if vrc does not succeed */
290#define ComAssertRCRet(vrc, ret) \
291 do { ComAssertRC (vrc); if (!RT_SUCCESS (vrc)) return (ret); } while (0)
292/** Special version of ComAssertMsgRC that returns ret if vrc does not succeed */
293#define ComAssertMsgRCRet(vrc, msg, ret) \
294 do { ComAssertMsgRC (vrc, msg); if (!RT_SUCCESS (vrc)) return (ret); } 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/** Special version of ComAssertComRC that returns ret if rc does not succeed */
302#define ComAssertComRCRet(rc, ret) \
303 do { ComAssertComRC (rc); if (!SUCCEEDED (rc)) return (ret); } while (0)
304/** Special version of ComAssertComRC that returns rc if rc does not succeed */
305#define ComAssertComRCRetRC(rc) \
306 do { ComAssertComRC (rc); if (!SUCCEEDED (rc)) return (rc); } while (0)
307
308
309/** Special version of ComAssert that evaluates eval and breaks if expr fails */
310#define ComAssertBreak(expr, eval) \
311 if (1) { ComAssert (expr); if (!(expr)) { eval; break; } } else do {} while (0)
312/** Special version of ComAssertMsg that evaluates eval and breaks if expr fails */
313#define ComAssertMsgBreak(expr, a, eval) \
314 if (1) { ComAssertMsg (expr, a); if (!(expr)) { eval; break; } } else do {} while (0)
315/** Special version of ComAssertRC that evaluates eval and breaks if vrc does not succeed */
316#define ComAssertRCBreak(vrc, eval) \
317 if (1) { ComAssertRC (vrc); if (!RT_SUCCESS (vrc)) { eval; break; } } else do {} while (0)
318/** Special version of ComAssertMsgRC that evaluates eval and breaks if vrc does not succeed */
319#define ComAssertMsgRCBreak(vrc, msg, eval) \
320 if (1) { ComAssertMsgRC (vrc, msg); if (!RT_SUCCESS (vrc)) { eval; break; } } else do {} while (0)
321/** Special version of ComAssertFailed that evaluates eval and breaks */
322#define ComAssertFailedBreak(eval) \
323 if (1) { ComAssertFailed(); { eval; break; } } else do {} while (0)
324/** Special version of ComAssertMsgFailed that evaluates eval and breaks */
325#define ComAssertMsgFailedBreak(msg, eval) \
326 if (1) { ComAssertMsgFailed (msg); { eval; break; } } else do {} while (0)
327/** Special version of ComAssertComRC that evaluates eval and breaks if rc does not succeed */
328#define ComAssertComRCBreak(rc, eval) \
329 if (1) { ComAssertComRC (rc); if (!SUCCEEDED (rc)) { eval; break; } } else do {} while (0)
330/** Special version of ComAssertComRC that just breaks if rc does not succeed */
331#define ComAssertComRCBreakRC(rc) \
332 if (1) { ComAssertComRC (rc); if (!SUCCEEDED (rc)) { break; } } else do {} while (0)
333
334
335/** Special version of ComAssert that evaluates eval and throws it if expr fails */
336#define ComAssertThrow(expr, eval) \
337 if (1) { ComAssert (expr); if (!(expr)) { throw (eval); } } else do {} while (0)
338/** Special version of ComAssertMsg that evaluates eval and throws it if expr fails */
339#define ComAssertMsgThrow(expr, a, eval) \
340 if (1) { ComAssertMsg (expr, a); if (!(expr)) { throw (eval); } } else do {} while (0)
341/** Special version of ComAssertRC that evaluates eval and throws it if vrc does not succeed */
342#define ComAssertRCThrow(vrc, eval) \
343 if (1) { ComAssertRC (vrc); if (!RT_SUCCESS (vrc)) { throw (eval); } } else do {} while (0)
344/** Special version of ComAssertMsgRC that evaluates eval and throws it if vrc does not succeed */
345#define ComAssertMsgRCThrow(vrc, msg, eval) \
346 if (1) { ComAssertMsgRC (vrc, msg); if (!RT_SUCCESS (vrc)) { throw (eval); } } else do {} while (0)
347/** Special version of ComAssertFailed that evaluates eval and throws it */
348#define ComAssertFailedThrow(eval) \
349 if (1) { ComAssertFailed(); { throw (eval); } } else do {} while (0)
350/** Special version of ComAssertMsgFailed that evaluates eval and throws it */
351#define ComAssertMsgFailedThrow(msg, eval) \
352 if (1) { ComAssertMsgFailed (msg); { throw (eval); } } else do {} while (0)
353/** Special version of ComAssertComRC that evaluates eval and throws it if rc does not succeed */
354#define ComAssertComRCThrow(rc, eval) \
355 if (1) { ComAssertComRC (rc); if (!SUCCEEDED (rc)) { throw (eval); } } else do {} while (0)
356/** Special version of ComAssertComRC that just throws rc if rc does not succeed */
357#define ComAssertComRCThrowRC(rc) \
358 if (1) { ComAssertComRC (rc); if (!SUCCEEDED (rc)) { throw rc; } } else do {} while (0)
359
360////////////////////////////////////////////////////////////////////////////////
361
362/**
363 * Checks that the pointer argument is not NULL and returns E_INVALIDARG +
364 * extended error info on failure.
365 * @param arg Input pointer-type argument (strings, interface pointers...)
366 */
367#define CheckComArgNotNull(arg) \
368 do { \
369 if ((arg) == NULL) \
370 return setError (E_INVALIDARG, tr ("Argument %s is NULL"), #arg); \
371 } while (0)
372
373/**
374 * Checks that safe array argument is not NULL and returns E_INVALIDARG +
375 * extended error info on failure.
376 * @param arg Input safe array argument (strings, interface pointers...)
377 */
378#define CheckComArgSafeArrayNotNull(arg) \
379 do { \
380 if (ComSafeArrayInIsNull (arg)) \
381 return setError (E_INVALIDARG, tr ("Argument %s is NULL"), #arg); \
382 } while (0)
383
384/**
385 * Checks that the string argument is not a NULL or empty string and returns
386 * E_INVALIDARG + extended error info on failure.
387 * @param arg Input string argument (BSTR etc.).
388 */
389#define CheckComArgStrNotEmptyOrNull(arg) \
390 do { \
391 if ((arg) == NULL || *(arg) == '\0') \
392 return setError (E_INVALIDARG, \
393 tr ("Argument %s is empty or NULL"), #arg); \
394 } while (0)
395
396/**
397 * Checks that the given expression (that must involve the argument) is true and
398 * returns E_INVALIDARG + extended error info on failure.
399 * @param arg Argument.
400 * @param expr Expression to evaluate.
401 */
402#define CheckComArgExpr(arg, expr) \
403 do { \
404 if (!(expr)) \
405 return setError (E_INVALIDARG, \
406 tr ("Argument %s is invalid (must be %s)"), #arg, #expr); \
407 } while (0)
408
409/**
410 * Checks that the given expression (that must involve the argument) is true and
411 * returns E_INVALIDARG + extended error info on failure. The error message must
412 * be customized.
413 * @param arg Argument.
414 * @param expr Expression to evaluate.
415 * @param msg Parenthesized printf-like expression (must start with a verb,
416 * like "must be one of...", "is not within...").
417 */
418#define CheckComArgExprMsg(arg, expr, msg) \
419 do { \
420 if (!(expr)) \
421 return setError (E_INVALIDARG, tr ("Argument %s %s"), \
422 #arg, Utf8StrFmt msg .raw()); \
423 } while (0)
424
425/**
426 * Checks that the given pointer to an output argument is valid and returns
427 * E_POINTER + extended error info otherwise.
428 * @param arg Pointer argument.
429 */
430#define CheckComArgOutPointerValid(arg) \
431 do { \
432 if (!VALID_PTR (arg)) \
433 return setError (E_POINTER, \
434 tr ("Output argument %s points to invalid memory location (%p)"), \
435 #arg, (void *) (arg)); \
436 } while (0)
437
438/**
439 * Checks that the given pointer to an output safe array argument is valid and
440 * returns E_POINTER + extended error info otherwise.
441 * @param arg Safe array argument.
442 */
443#define CheckComArgOutSafeArrayPointerValid(arg) \
444 do { \
445 if (ComSafeArrayOutIsNull (arg)) \
446 return setError (E_POINTER, \
447 tr ("Output argument %s points to invalid memory location (%p)"), \
448 #arg, (void *) (arg)); \
449 } while (0)
450
451/**
452 * Sets the extended error info and returns E_NOTIMPL.
453 */
454#define ReturnComNotImplemented() \
455 do { \
456 return setError (E_NOTIMPL, tr ("Method %s is not implemented"), __FUNCTION__); \
457 } while (0)
458
459////////////////////////////////////////////////////////////////////////////////
460
461/**
462 * Declares an empty constructor and destructor for the given class.
463 * This is useful to prevent the compiler from generating the default
464 * ctor and dtor, which in turn allows to use forward class statements
465 * (instead of including their header files) when declaring data members of
466 * non-fundamental types with constructors (which are always called implicitly
467 * by constructors and by the destructor of the class).
468 *
469 * This macro is to be placed within (the public section of) the class
470 * declaration. Its counterpart, DEFINE_EMPTY_CTOR_DTOR, must be placed
471 * somewhere in one of the translation units (usually .cpp source files).
472 *
473 * @param cls class to declare a ctor and dtor for
474 */
475#define DECLARE_EMPTY_CTOR_DTOR(cls) cls(); ~cls();
476
477/**
478 * Defines an empty constructor and destructor for the given class.
479 * See DECLARE_EMPTY_CTOR_DTOR for more info.
480 */
481#define DEFINE_EMPTY_CTOR_DTOR(cls) \
482 cls::cls () {}; cls::~cls () {};
483
484////////////////////////////////////////////////////////////////////////////////
485
486namespace stdx
487{
488 /**
489 * A wrapper around the container that owns pointers it stores.
490 *
491 * @note
492 * Ownership is recognized only when destructing the container!
493 * Pointers are not deleted when erased using erase() etc.
494 *
495 * @param container
496 * class that meets Container requirements (for example, an instance of
497 * std::list<>, std::vector<> etc.). The given class must store
498 * pointers (for example, std::list <MyType *>).
499 */
500 template <typename container>
501 class ptr_container : public container
502 {
503 public:
504 ~ptr_container()
505 {
506 for (typename container::iterator it = container::begin();
507 it != container::end();
508 ++ it)
509 delete (*it);
510 }
511 };
512}
513
514////////////////////////////////////////////////////////////////////////////////
515
516/**
517 * Abstract base class for all component classes implementing COM
518 * interfaces of the VirtualBox COM library.
519 *
520 * Declares functionality that should be available in all components.
521 *
522 * Note that this class is always subclassed using the virtual keyword so
523 * that only one instance of its VTBL and data is present in each derived class
524 * even in case if VirtualBoxBaseProto appears more than once among base classes
525 * of the particular component as a result of multiple inheritance.
526 *
527 * This makes it possible to have intermediate base classes used by several
528 * components that implement some common interface functionality but still let
529 * the final component classes choose what VirtualBoxBase variant it wants to
530 * use.
531 *
532 * Among the basic functionality implemented by this class is the primary object
533 * state that indicates if the object is ready to serve the calls, and if not,
534 * what stage it is currently at. Here is the primary state diagram:
535 *
536 * +-------------------------------------------------------+
537 * | |
538 * | (InitFailed) -----------------------+ |
539 * | ^ | |
540 * v | v |
541 * [*] ---> NotReady ----> (InInit) -----> Ready -----> (InUninit) ----+
542 * ^ | ^ | ^
543 * | v | v |
544 * | Limited | (MayUninit) --> (WillUninit)
545 * | | | |
546 * +-------+ +-------+
547 *
548 * The object is fully operational only when its state is Ready. The Limited
549 * state means that only some vital part of the object is operational, and it
550 * requires some sort of reinitialization to become fully operational. The
551 * NotReady state means the object is basically dead: it either was not yet
552 * initialized after creation at all, or was uninitialized and is waiting to be
553 * destroyed when the last reference to it is released. All other states are
554 * transitional.
555 *
556 * The NotReady->InInit->Ready, NotReady->InInit->Limited and
557 * NotReady->InInit->InitFailed transition is done by the AutoInitSpan smart
558 * class.
559 *
560 * The Limited->InInit->Ready, Limited->InInit->Limited and
561 * Limited->InInit->InitFailed transition is done by the AutoReinitSpan smart
562 * class.
563 *
564 * The Ready->InUninit->NotReady, InitFailed->InUninit->NotReady and
565 * WillUninit->InUninit->NotReady transitions are done by the AutoUninitSpan
566 * smart class.
567 *
568 * The Ready->MayUninit->Ready and Ready->MayUninit->WillUninit transitions are
569 * done by the AutoMayUninitSpan smart class.
570 *
571 * In order to maintain the primary state integrity and declared functionality
572 * all subclasses must:
573 *
574 * 1) Use the above Auto*Span classes to perform state transitions. See the
575 * individual class descriptions for details.
576 *
577 * 2) All public methods of subclasses (i.e. all methods that can be called
578 * directly, not only from within other methods of the subclass) must have a
579 * standard prolog as described in the AutoCaller and AutoLimitedCaller
580 * documentation. Alternatively, they must use addCaller()/releaseCaller()
581 * directly (and therefore have both the prolog and the epilog), but this is
582 * not recommended.
583 */
584class ATL_NO_VTABLE VirtualBoxBaseProto : public Lockable
585{
586public:
587
588 enum State { NotReady, Ready, InInit, InUninit, InitFailed, Limited,
589 MayUninit, WillUninit };
590
591protected:
592
593 VirtualBoxBaseProto();
594 virtual ~VirtualBoxBaseProto();
595
596public:
597
598 // util::Lockable interface
599 virtual RWLockHandle *lockHandle() const;
600
601 /**
602 * Unintialization method.
603 *
604 * Must be called by all final implementations (component classes) when the
605 * last reference to the object is released, before calling the destructor.
606 *
607 * This method is also automatically called by the uninit() method of this
608 * object's parent if this object is a dependent child of a class derived
609 * from VirtualBoxBaseWithChildren (see
610 * VirtualBoxBaseWithChildren::addDependentChild).
611 *
612 * @note Never call this method the AutoCaller scope or after the
613 * #addCaller() call not paired by #releaseCaller() because it is a
614 * guaranteed deadlock. See AutoUninitSpan for details.
615 */
616 virtual void uninit() {}
617
618 virtual HRESULT addCaller (State *aState = NULL, bool aLimited = false);
619 virtual void releaseCaller();
620
621 /**
622 * Adds a limited caller. This method is equivalent to doing
623 * <tt>addCaller (aState, true)</tt>, but it is preferred because provides
624 * better self-descriptiveness. See #addCaller() for more info.
625 */
626 HRESULT addLimitedCaller (State *aState = NULL)
627 {
628 return addCaller (aState, true /* aLimited */);
629 }
630
631 /**
632 * Smart class that automatically increases the number of callers of the
633 * given VirtualBoxBase object when an instance is constructed and decreases
634 * it back when the created instance goes out of scope (i.e. gets destroyed).
635 *
636 * If #rc() returns a failure after the instance creation, it means that
637 * the managed VirtualBoxBase object is not Ready, or in any other invalid
638 * state, so that the caller must not use the object and can return this
639 * failed result code to the upper level.
640 *
641 * See VirtualBoxBase::addCaller(), VirtualBoxBase::addLimitedCaller() and
642 * VirtualBoxBase::releaseCaller() for more details about object callers.
643 *
644 * @param aLimited |false| if this template should use
645 * VirtualiBoxBase::addCaller() calls to add callers, or
646 * |true| if VirtualiBoxBase::addLimitedCaller() should be
647 * used.
648 *
649 * @note It is preferable to use the AutoCaller and AutoLimitedCaller
650 * classes than specify the @a aLimited argument, for better
651 * self-descriptiveness.
652 */
653 template <bool aLimited>
654 class AutoCallerBase
655 {
656 public:
657
658 /**
659 * Increases the number of callers of the given object by calling
660 * VirtualBoxBase::addCaller().
661 *
662 * @param aObj Object to add a caller to. If NULL, this
663 * instance is effectively turned to no-op (where
664 * rc() will return S_OK and state() will be
665 * NotReady).
666 */
667 AutoCallerBase (VirtualBoxBaseProto *aObj)
668 : mObj (aObj)
669 , mRC (S_OK)
670 , mState (NotReady)
671 {
672 if (mObj)
673 mRC = mObj->addCaller (&mState, aLimited);
674 }
675
676 /**
677 * If the number of callers was successfully increased, decreases it
678 * using VirtualBoxBase::releaseCaller(), otherwise does nothing.
679 */
680 ~AutoCallerBase()
681 {
682 if (mObj && SUCCEEDED (mRC))
683 mObj->releaseCaller();
684 }
685
686 /**
687 * Stores the result code returned by VirtualBoxBase::addCaller() after
688 * instance creation or after the last #add() call. A successful result
689 * code means the number of callers was successfully increased.
690 */
691 HRESULT rc() const { return mRC; }
692
693 /**
694 * Returns |true| if |SUCCEEDED (rc())| is |true|, for convenience.
695 * |true| means the number of callers was successfully increased.
696 */
697 bool isOk() const { return SUCCEEDED (mRC); }
698
699 /**
700 * Stores the object state returned by VirtualBoxBase::addCaller() after
701 * instance creation or after the last #add() call.
702 */
703 State state() const { return mState; }
704
705 /**
706 * Temporarily decreases the number of callers of the managed object.
707 * May only be called if #isOk() returns |true|. Note that #rc() will
708 * return E_FAIL after this method succeeds.
709 */
710 void release()
711 {
712 Assert (SUCCEEDED (mRC));
713 if (SUCCEEDED (mRC))
714 {
715 if (mObj)
716 mObj->releaseCaller();
717 mRC = E_FAIL;
718 }
719 }
720
721 /**
722 * Restores the number of callers decreased by #release(). May only be
723 * called after #release().
724 */
725 void add()
726 {
727 Assert (!SUCCEEDED (mRC));
728 if (mObj && !SUCCEEDED (mRC))
729 mRC = mObj->addCaller (&mState, aLimited);
730 }
731
732 /**
733 * Attaches another object to this caller instance.
734 * The previous object's caller is released before the new one is added.
735 *
736 * @param aObj New object to attach, may be @c NULL.
737 */
738 void attach (VirtualBoxBaseProto *aObj)
739 {
740 /* detect simple self-reattachment */
741 if (mObj != aObj)
742 {
743 if (mObj && SUCCEEDED (mRC))
744 release();
745 mObj = aObj;
746 add();
747 }
748 }
749
750 /** Verbose equivalent to <tt>attach (NULL)</tt>. */
751 void detach() { attach (NULL); }
752
753 private:
754
755 DECLARE_CLS_COPY_CTOR_ASSIGN_NOOP (AutoCallerBase)
756 DECLARE_CLS_NEW_DELETE_NOOP (AutoCallerBase)
757
758 VirtualBoxBaseProto *mObj;
759 HRESULT mRC;
760 State mState;
761 };
762
763 /**
764 * Smart class that automatically increases the number of normal
765 * (non-limited) callers of the given VirtualBoxBase object when an instance
766 * is constructed and decreases it back when the created instance goes out
767 * of scope (i.e. gets destroyed).
768 *
769 * A typical usage pattern to declare a normal method of some object (i.e. a
770 * method that is valid only when the object provides its full
771 * functionality) is:
772 * <code>
773 * STDMETHODIMP Component::Foo()
774 * {
775 * AutoCaller autoCaller (this);
776 * CheckComRCReturnRC (autoCaller.rc());
777 * ...
778 * </code>
779 *
780 * Using this class is equivalent to using the AutoCallerBase template with
781 * the @a aLimited argument set to |false|, but this class is preferred
782 * because provides better self-descriptiveness.
783 *
784 * See AutoCallerBase for more information about auto caller functionality.
785 */
786 typedef AutoCallerBase <false> AutoCaller;
787
788 /**
789 * Smart class that automatically increases the number of limited callers of
790 * the given VirtualBoxBase object when an instance is constructed and
791 * decreases it back when the created instance goes out of scope (i.e. gets
792 * destroyed).
793 *
794 * A typical usage pattern to declare a limited method of some object (i.e.
795 * a method that is valid even if the object doesn't provide its full
796 * functionality) is:
797 * <code>
798 * STDMETHODIMP Component::Bar()
799 * {
800 * AutoLimitedCaller autoCaller (this);
801 * CheckComRCReturnRC (autoCaller.rc());
802 * ...
803 * </code>
804 *
805 * Using this class is equivalent to using the AutoCallerBase template with
806 * the @a aLimited argument set to |true|, but this class is preferred
807 * because provides better self-descriptiveness.
808 *
809 * See AutoCallerBase for more information about auto caller functionality.
810 */
811 typedef AutoCallerBase <true> AutoLimitedCaller;
812
813protected:
814
815 /**
816 * Smart class to enclose the state transition NotReady->InInit->Ready.
817 *
818 * The purpose of this span is to protect object initialization.
819 *
820 * Instances must be created as a stack-based variable taking |this| pointer
821 * as the argument at the beginning of init() methods of VirtualBoxBase
822 * subclasses. When this variable is created it automatically places the
823 * object to the InInit state.
824 *
825 * When the created variable goes out of scope (i.e. gets destroyed) then,
826 * depending on the result status of this initialization span, it either
827 * places the object to Ready or Limited state or calls the object's
828 * VirtualBoxBase::uninit() method which is supposed to place the object
829 * back to the NotReady state using the AutoUninitSpan class.
830 *
831 * The initial result status of the initialization span is determined by the
832 * @a aResult argument of the AutoInitSpan constructor (Result::Failed by
833 * default). Inside the initialization span, the success status can be set
834 * to Result::Succeeded using #setSucceeded(), to to Result::Limited using
835 * #setLimited() or to Result::Failed using #setFailed(). Please don't
836 * forget to set the correct success status before getting the AutoInitSpan
837 * variable destroyed (for example, by performing an early return from
838 * the init() method)!
839 *
840 * Note that if an instance of this class gets constructed when the object
841 * is in the state other than NotReady, #isOk() returns |false| and methods
842 * of this class do nothing: the state transition is not performed.
843 *
844 * A typical usage pattern is:
845 * <code>
846 * HRESULT Component::init()
847 * {
848 * AutoInitSpan autoInitSpan (this);
849 * AssertReturn (autoInitSpan.isOk(), E_FAIL);
850 * ...
851 * if (FAILED (rc))
852 * return rc;
853 * ...
854 * if (SUCCEEDED (rc))
855 * autoInitSpan.setSucceeded();
856 * return rc;
857 * }
858 * </code>
859 *
860 * @note Never create instances of this class outside init() methods of
861 * VirtualBoxBase subclasses and never pass anything other than |this|
862 * as the argument to the constructor!
863 */
864 class AutoInitSpan
865 {
866 public:
867
868 enum Result { Failed = 0x0, Succeeded = 0x1, Limited = 0x2 };
869
870 AutoInitSpan (VirtualBoxBaseProto *aObj, Result aResult = Failed);
871 ~AutoInitSpan();
872
873 /**
874 * Returns |true| if this instance has been created at the right moment
875 * (when the object was in the NotReady state) and |false| otherwise.
876 */
877 bool isOk() const { return mOk; }
878
879 /**
880 * Sets the initialization status to Succeeded to indicates successful
881 * initialization. The AutoInitSpan destructor will place the managed
882 * VirtualBoxBase object to the Ready state.
883 */
884 void setSucceeded() { mResult = Succeeded; }
885
886 /**
887 * Sets the initialization status to Succeeded to indicate limited
888 * (partly successful) initialization. The AutoInitSpan destructor will
889 * place the managed VirtualBoxBase object to the Limited state.
890 */
891 void setLimited() { mResult = Limited; }
892
893 /**
894 * Sets the initialization status to Failure to indicates failed
895 * initialization. The AutoInitSpan destructor will place the managed
896 * VirtualBoxBase object to the InitFailed state and will automatically
897 * call its uninit() method which is supposed to place the object back
898 * to the NotReady state using AutoUninitSpan.
899 */
900 void setFailed() { mResult = Failed; }
901
902 /** Returns the current initialization result. */
903 Result result() { return mResult; }
904
905 private:
906
907 DECLARE_CLS_COPY_CTOR_ASSIGN_NOOP (AutoInitSpan)
908 DECLARE_CLS_NEW_DELETE_NOOP (AutoInitSpan)
909
910 VirtualBoxBaseProto *mObj;
911 Result mResult : 3; // must be at least total number of bits + 1 (sign)
912 bool mOk : 1;
913 };
914
915 /**
916 * Smart class to enclose the state transition Limited->InInit->Ready.
917 *
918 * The purpose of this span is to protect object re-initialization.
919 *
920 * Instances must be created as a stack-based variable taking |this| pointer
921 * as the argument at the beginning of methods of VirtualBoxBase
922 * subclasses that try to re-initialize the object to bring it to the Ready
923 * state (full functionality) after partial initialization (limited
924 * functionality). When this variable is created, it automatically places
925 * the object to the InInit state.
926 *
927 * When the created variable goes out of scope (i.e. gets destroyed),
928 * depending on the success status of this initialization span, it either
929 * places the object to the Ready state or brings it back to the Limited
930 * state.
931 *
932 * The initial success status of the re-initialization span is |false|. In
933 * order to make it successful, #setSucceeded() must be called before the
934 * instance is destroyed.
935 *
936 * Note that if an instance of this class gets constructed when the object
937 * is in the state other than Limited, #isOk() returns |false| and methods
938 * of this class do nothing: the state transition is not performed.
939 *
940 * A typical usage pattern is:
941 * <code>
942 * HRESULT Component::reinit()
943 * {
944 * AutoReinitSpan autoReinitSpan (this);
945 * AssertReturn (autoReinitSpan.isOk(), E_FAIL);
946 * ...
947 * if (FAILED (rc))
948 * return rc;
949 * ...
950 * if (SUCCEEDED (rc))
951 * autoReinitSpan.setSucceeded();
952 * return rc;
953 * }
954 * </code>
955 *
956 * @note Never create instances of this class outside re-initialization
957 * methods of VirtualBoxBase subclasses and never pass anything other than
958 * |this| as the argument to the constructor!
959 */
960 class AutoReinitSpan
961 {
962 public:
963
964 AutoReinitSpan (VirtualBoxBaseProto *aObj);
965 ~AutoReinitSpan();
966
967 /**
968 * Returns |true| if this instance has been created at the right moment
969 * (when the object was in the Limited state) and |false| otherwise.
970 */
971 bool isOk() const { return mOk; }
972
973 /**
974 * Sets the re-initialization status to Succeeded to indicates
975 * successful re-initialization. The AutoReinitSpan destructor will place
976 * the managed VirtualBoxBase object to the Ready state.
977 */
978 void setSucceeded() { mSucceeded = true; }
979
980 private:
981
982 DECLARE_CLS_COPY_CTOR_ASSIGN_NOOP (AutoReinitSpan)
983 DECLARE_CLS_NEW_DELETE_NOOP (AutoReinitSpan)
984
985 VirtualBoxBaseProto *mObj;
986 bool mSucceeded : 1;
987 bool mOk : 1;
988 };
989
990 /**
991 * Smart class to enclose the state transition Ready->InUnnit->NotReady,
992 * InitFailed->InUnnit->NotReady or WillUninit->InUnnit->NotReady.
993 *
994 * The purpose of this span is to protect object uninitialization.
995 *
996 * Instances must be created as a stack-based variable taking |this| pointer
997 * as the argument at the beginning of uninit() methods of VirtualBoxBase
998 * subclasses. When this variable is created it automatically places the
999 * object to the InUninit state, unless it is already in the NotReady state
1000 * as indicated by #uninitDone() returning |true|. In the latter case, the
1001 * uninit() method must immediately return because there should be nothing
1002 * to uninitialize.
1003 *
1004 * When this variable goes out of scope (i.e. gets destroyed), it places the
1005 * object to NotReady state.
1006 *
1007 * A typical usage pattern is:
1008 * <code>
1009 * void Component::uninit()
1010 * {
1011 * AutoUninitSpan autoUninitSpan (this);
1012 * if (autoUninitSpan.uninitDone())
1013 * return;
1014 * ...
1015 * }
1016 * </code>
1017 *
1018 * @note The constructor of this class blocks the current thread execution
1019 * until the number of callers added to the object using #addCaller()
1020 * or AutoCaller drops to zero. For this reason, it is forbidden to
1021 * create instances of this class (or call uninit()) within the
1022 * AutoCaller or #addCaller() scope because it is a guaranteed
1023 * deadlock.
1024 *
1025 * @note Never create instances of this class outside uninit() methods and
1026 * never pass anything other than |this| as the argument to the
1027 * constructor!
1028 */
1029 class AutoUninitSpan
1030 {
1031 public:
1032
1033 AutoUninitSpan (VirtualBoxBaseProto *aObj);
1034 ~AutoUninitSpan();
1035
1036 /** |true| when uninit() is called as a result of init() failure */
1037 bool initFailed() { return mInitFailed; }
1038
1039 /** |true| when uninit() has already been called (so the object is NotReady) */
1040 bool uninitDone() { return mUninitDone; }
1041
1042 private:
1043
1044 DECLARE_CLS_COPY_CTOR_ASSIGN_NOOP (AutoUninitSpan)
1045 DECLARE_CLS_NEW_DELETE_NOOP (AutoUninitSpan)
1046
1047 VirtualBoxBaseProto *mObj;
1048 bool mInitFailed : 1;
1049 bool mUninitDone : 1;
1050 };
1051
1052 /**
1053 * Smart class to enclose the state transition Ready->MayUninit->NotReady or
1054 * Ready->MayUninit->WillUninit.
1055 *
1056 * The purpose of this span is to safely check if unintialization is
1057 * possible at the given moment and seamlessly perform it if so.
1058 *
1059 * Instances must be created as a stack-based variable taking |this| pointer
1060 * as the argument at the beginning of methods of VirtualBoxBase
1061 * subclasses that want to uninitialize the object if a necessary set of
1062 * criteria is met and leave it Ready otherwise.
1063 *
1064 * When this variable is created it automatically places the object to the
1065 * MayUninit state if it is Ready, does nothing but returns |true| in
1066 * response to #alreadyInProgress() if it is already in MayUninit, or
1067 * returns a failure in response to #rc() in any other case. The example
1068 * below shows how the user must react in latter two cases.
1069 *
1070 * When this variable goes out of scope (i.e. gets destroyed), it places the
1071 * object back to Ready state unless #acceptUninit() is called in which case
1072 * the object is placed to WillUninit state and uninit() is immediately
1073 * called after that.
1074 *
1075 * A typical usage pattern is:
1076 * <code>
1077 * void Component::uninit()
1078 * {
1079 * AutoMayUninitSpan mayUninitSpan (this);
1080 * CheckComRCReturnRC (mayUninitSpan.rc());
1081 * if (mayUninitSpan.alreadyInProgress())
1082 * return S_OK;
1083 * ...
1084 * if (FAILED (rc))
1085 * return rc; // will go back to Ready
1086 * ...
1087 * if (SUCCEEDED (rc))
1088 * mayUninitSpan.acceptUninit(); // will call uninit()
1089 * return rc;
1090 * }
1091 * </code>
1092 *
1093 * @note The constructor of this class blocks the current thread execution
1094 * until the number of callers added to the object using #addCaller()
1095 * or AutoCaller drops to zero. For this reason, it is forbidden to
1096 * create instances of this class (or call uninit()) within the
1097 * AutoCaller or #addCaller() scope because it is a guaranteed
1098 * deadlock.
1099 */
1100 class AutoMayUninitSpan
1101 {
1102 public:
1103
1104 AutoMayUninitSpan (VirtualBoxBaseProto *aObj);
1105 ~AutoMayUninitSpan();
1106
1107 /**
1108 * Returns a failure if the AutoMayUninitSpan variable was constructed
1109 * at an improper time. If there is a failure, do nothing but return
1110 * it to the caller.
1111 */
1112 HRESULT rc() { return mRC; }
1113
1114 /**
1115 * Returns |true| if AutoMayUninitSpan is already in progress on some
1116 * other thread. If it's the case, do nothing but return S_OK to
1117 * the caller.
1118 */
1119 bool alreadyInProgress() { return mAlreadyInProgress; }
1120
1121 /*
1122 * Accepts uninitialization and causes the destructor to go to
1123 * WillUninit state and call uninit() afterwards.
1124 */
1125 void acceptUninit() { mAcceptUninit = true; }
1126
1127 private:
1128
1129 DECLARE_CLS_COPY_CTOR_ASSIGN_NOOP (AutoMayUninitSpan)
1130 DECLARE_CLS_NEW_DELETE_NOOP (AutoMayUninitSpan)
1131
1132 VirtualBoxBaseProto *mObj;
1133
1134 HRESULT mRC;
1135 bool mAlreadyInProgress : 1;
1136 bool mAcceptUninit : 1;
1137 };
1138
1139 /**
1140 * Returns a lock handle used to protect the primary state fields (used by
1141 * #addCaller(), AutoInitSpan, AutoUninitSpan, etc.). Only intended to be
1142 * used for similar purposes in subclasses. WARNING: NO any other locks may
1143 * be requested while holding this lock!
1144 */
1145 WriteLockHandle *stateLockHandle() { return &mStateLock; }
1146
1147private:
1148
1149 void setState (State aState)
1150 {
1151 Assert (mState != aState);
1152 mState = aState;
1153 mStateChangeThread = RTThreadSelf();
1154 }
1155
1156 /** Primary state of this object */
1157 State mState;
1158 /** Thread that caused the last state change */
1159 RTTHREAD mStateChangeThread;
1160 /** Total number of active calls to this object */
1161 unsigned mCallers;
1162 /** Posted when the number of callers drops to zero */
1163 RTSEMEVENT mZeroCallersSem;
1164 /** Posted when the object goes from InInit/InUninit to some other state */
1165 RTSEMEVENTMULTI mInitUninitSem;
1166 /** Number of threads waiting for mInitUninitDoneSem */
1167 unsigned mInitUninitWaiters;
1168
1169 /** Protects access to state related data members */
1170 WriteLockHandle mStateLock;
1171
1172 /** User-level object lock for subclasses */
1173 mutable RWLockHandle *mObjectLock;
1174};
1175
1176////////////////////////////////////////////////////////////////////////////////
1177
1178/**
1179 * This macro adds the error info support to methods of the VirtualBoxBase
1180 * class (by overriding them). Place it to the public section of the
1181 * VirtualBoxBase subclass and the following methods will set the extended
1182 * error info in case of failure instead of just returning the result code:
1183 *
1184 * <ul>
1185 * <li>VirtualBoxBase::addCaller()
1186 * </ul>
1187 *
1188 * @note The given VirtualBoxBase subclass must also inherit from both
1189 * VirtualBoxSupportErrorInfoImpl and VirtualBoxSupportTranslation templates!
1190 *
1191 * @param C VirtualBoxBase subclass to add the error info support to
1192 */
1193#define VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT(C) \
1194 virtual HRESULT addCaller (VirtualBoxBaseProto::State *aState = NULL, \
1195 bool aLimited = false) \
1196 { \
1197 VirtualBoxBaseProto::State state; \
1198 HRESULT rc = VirtualBoxBaseProto::addCaller (&state, aLimited); \
1199 if (FAILED (rc)) \
1200 { \
1201 if (state == VirtualBoxBaseProto::Limited) \
1202 rc = setError (rc, tr ("The object functionality is limited")); \
1203 else \
1204 rc = setError (rc, tr ("The object is not ready")); \
1205 } \
1206 if (aState) \
1207 *aState = state; \
1208 return rc; \
1209 } \
1210
1211////////////////////////////////////////////////////////////////////////////////
1212
1213class ATL_NO_VTABLE VirtualBoxBase
1214 : virtual public VirtualBoxBaseProto
1215 , public CComObjectRootEx <CComMultiThreadModel>
1216{
1217
1218public:
1219 VirtualBoxBase()
1220 {}
1221
1222 virtual ~VirtualBoxBase()
1223 {}
1224
1225 /**
1226 * Virtual unintialization method. Called during parent object's
1227 * uninitialization, if the given subclass instance is a dependent child of
1228 * a class derived from VirtualBoxBaseWithChildren (@sa
1229 * VirtualBoxBaseWithChildren::addDependentChild). In this case, this
1230 * method's implementation must call setReady (false),
1231 */
1232 virtual void uninit()
1233 {}
1234
1235 static const char *translate (const char *context, const char *sourceText,
1236 const char *comment = 0);
1237};
1238
1239////////////////////////////////////////////////////////////////////////////////
1240
1241/** Helper for VirtualBoxSupportTranslation. */
1242class VirtualBoxSupportTranslationBase
1243{
1244protected:
1245 static bool cutClassNameFrom__PRETTY_FUNCTION__ (char *aPrettyFunctionName);
1246};
1247
1248/**
1249 * The VirtualBoxSupportTranslation template implements the NLS string
1250 * translation support for the given class.
1251 *
1252 * Translation support is provided by the static #tr() function. This function,
1253 * given a string in UTF-8 encoding, looks up for a translation of the given
1254 * string by calling the VirtualBoxBase::translate() global function which
1255 * receives the name of the enclosing class ("context of translation") as the
1256 * additional argument and returns a translated string based on the currently
1257 * active language.
1258 *
1259 * @param C Class that needs to support the string translation.
1260 *
1261 * @note Every class that wants to use the #tr() function in its own methods
1262 * must inherit from this template, regardless of whether its base class
1263 * (if any) inherits from it or not. Otherwise, the translation service
1264 * will not work correctly. However, the declaration of the derived
1265 * class must contain
1266 * the <tt>COM_SUPPORTTRANSLATION_OVERRIDE (<ClassName>)</tt> macro if one
1267 * of its base classes also inherits from this template (to resolve the
1268 * ambiguity of the #tr() function).
1269 */
1270template <class C>
1271class VirtualBoxSupportTranslation : virtual protected VirtualBoxSupportTranslationBase
1272{
1273public:
1274
1275 /**
1276 * Translates the given text string by calling VirtualBoxBase::translate()
1277 * and passing the name of the C class as the first argument ("context of
1278 * translation") See VirtualBoxBase::translate() for more info.
1279 *
1280 * @param aSourceText String to translate.
1281 * @param aComment Comment to the string to resolve possible
1282 * ambiguities (NULL means no comment).
1283 *
1284 * @return Translated version of the source string in UTF-8 encoding, or
1285 * the source string itself if the translation is not found in the
1286 * specified context.
1287 */
1288 inline static const char *tr (const char *aSourceText,
1289 const char *aComment = NULL)
1290 {
1291 return VirtualBoxBase::translate (className(), aSourceText, aComment);
1292 }
1293
1294protected:
1295
1296 static const char *className()
1297 {
1298 static char fn [sizeof (__PRETTY_FUNCTION__) + 1];
1299 if (!sClassName)
1300 {
1301 strcpy (fn, __PRETTY_FUNCTION__);
1302 cutClassNameFrom__PRETTY_FUNCTION__ (fn);
1303 sClassName = fn;
1304 }
1305 return sClassName;
1306 }
1307
1308private:
1309
1310 static const char *sClassName;
1311};
1312
1313template <class C>
1314const char *VirtualBoxSupportTranslation<C>::sClassName = NULL;
1315
1316/**
1317 * This macro must be invoked inside the public section of the declaration of
1318 * the class inherited from the VirtualBoxSupportTranslation template in case
1319 * if one of its other base classes also inherits from that template. This is
1320 * necessary to resolve the ambiguity of the #tr() function.
1321 *
1322 * @param C Class that inherits the VirtualBoxSupportTranslation template
1323 * more than once (through its other base clases).
1324 */
1325#define VIRTUALBOXSUPPORTTRANSLATION_OVERRIDE(C) \
1326 inline static const char *tr (const char *aSourceText, \
1327 const char *aComment = NULL) \
1328 { \
1329 return VirtualBoxSupportTranslation<C>::tr (aSourceText, aComment); \
1330 }
1331
1332/**
1333 * Dummy macro that is used to shut down Qt's lupdate tool warnings in some
1334 * situations. This macro needs to be present inside (better at the very
1335 * beginning) of the declaration of the class that inherits from
1336 * VirtualBoxSupportTranslation template, to make lupdate happy.
1337 */
1338#define Q_OBJECT
1339
1340////////////////////////////////////////////////////////////////////////////////
1341
1342/**
1343 * Helper for the VirtualBoxSupportErrorInfoImpl template.
1344 */
1345/// @todo switch to com::SupportErrorInfo* and remove
1346class VirtualBoxSupportErrorInfoImplBase
1347{
1348 static HRESULT setErrorInternal (HRESULT aResultCode, const GUID &aIID,
1349 const Bstr &aComponent, const Bstr &aText,
1350 bool aWarning, bool aLogIt);
1351
1352protected:
1353
1354 /**
1355 * The MultiResult class is a com::FWResult enhancement that also acts as a
1356 * switch to turn on multi-error mode for #setError() or #setWarning()
1357 * calls.
1358 *
1359 * When an instance of this class is created, multi-error mode is turned on
1360 * for the current thread and the turn-on counter is increased by one. In
1361 * multi-error mode, a call to #setError() or #setWarning() does not
1362 * overwrite the current error or warning info object possibly set on the
1363 * current thread by other method calls, but instead it stores this old
1364 * object in the IVirtualBoxErrorInfo::next attribute of the new error
1365 * object being set.
1366 *
1367 * This way, error/warning objects are stacked together and form a chain of
1368 * errors where the most recent error is the first one retrieved by the
1369 * calling party, the preceding error is what the
1370 * IVirtualBoxErrorInfo::next attribute of the first error points to, and so
1371 * on, up to the first error or warning occurred which is the last in the
1372 * chain. See IVirtualBoxErrorInfo documentation for more info.
1373 *
1374 * When the instance of the MultiResult class goes out of scope and gets
1375 * destroyed, it automatically decreases the turn-on counter by one. If
1376 * the counter drops to zero, multi-error mode for the current thread is
1377 * turned off and the thread switches back to single-error mode where every
1378 * next error or warning object overwrites the previous one.
1379 *
1380 * Note that the caller of a COM method uses a non-S_OK result code to
1381 * decide if the method has returned an error (negative codes) or a warning
1382 * (positive non-zero codes) and will query extended error info only in
1383 * these two cases. However, since multi-error mode implies that the method
1384 * doesn't return control return to the caller immediately after the first
1385 * error or warning but continues its execution, the functionality provided
1386 * by the base com::FWResult class becomes very useful because it allows to
1387 * preserve the error or the warning result code even if it is later assigned
1388 * a S_OK value multiple times. See com::FWResult for details.
1389 *
1390 * Here is the typical usage pattern:
1391 * <code>
1392
1393 HRESULT Bar::method()
1394 {
1395 // assume multi-errors are turned off here...
1396
1397 if (something)
1398 {
1399 // Turn on multi-error mode and make sure severity is preserved
1400 MultiResult rc = foo->method1();
1401
1402 // return on fatal error, but continue on warning or on success
1403 CheckComRCReturnRC (rc);
1404
1405 rc = foo->method2();
1406 // no matter what result, stack it and continue
1407
1408 // ...
1409
1410 // return the last worst result code (it will be preserved even if
1411 // foo->method2() returns S_OK.
1412 return rc;
1413 }
1414
1415 // multi-errors are turned off here again...
1416
1417 return S_OK;
1418 }
1419
1420 * </code>
1421 *
1422 *
1423 * @note This class is intended to be instantiated on the stack, therefore
1424 * You cannot create them using new(). Although it is possible to copy
1425 * instances of MultiResult or return them by value, please never do
1426 * that as it is breaks the class semantics (and will assert).
1427 */
1428 class MultiResult : public com::FWResult
1429 {
1430 public:
1431
1432 /**
1433 * @copydoc com::FWResult::FWResult().
1434 */
1435 MultiResult (HRESULT aRC = E_FAIL) : FWResult (aRC) { init(); }
1436
1437 MultiResult (const MultiResult &aThat) : FWResult (aThat)
1438 {
1439 /* We need this copy constructor only for GCC that wants to have
1440 * it in case of expressions like |MultiResult rc = E_FAIL;|. But
1441 * we assert since the optimizer should actually avoid the
1442 * temporary and call the other constructor directly instead. */
1443 AssertFailed();
1444 init();
1445 }
1446
1447 ~MultiResult();
1448
1449 MultiResult &operator= (HRESULT aRC)
1450 {
1451 com::FWResult::operator= (aRC);
1452 return *this;
1453 }
1454
1455 MultiResult &operator= (const MultiResult &aThat)
1456 {
1457 /* We need this copy constructor only for GCC that wants to have
1458 * it in case of expressions like |MultiResult rc = E_FAIL;|. But
1459 * we assert since the optimizer should actually avoid the
1460 * temporary and call the other constructor directly instead. */
1461 AssertFailed();
1462 com::FWResult::operator= (aThat);
1463 return *this;
1464 }
1465
1466 private:
1467
1468 DECLARE_CLS_NEW_DELETE_NOOP (MultiResult)
1469
1470 void init();
1471
1472 static RTTLS sCounter;
1473
1474 friend class VirtualBoxSupportErrorInfoImplBase;
1475 };
1476
1477 static HRESULT setError (HRESULT aResultCode, const GUID &aIID,
1478 const Bstr &aComponent,
1479 const Bstr &aText,
1480 bool aLogIt = true)
1481 {
1482 return setErrorInternal (aResultCode, aIID, aComponent, aText,
1483 false /* aWarning */, aLogIt);
1484 }
1485
1486 static HRESULT setWarning (HRESULT aResultCode, const GUID &aIID,
1487 const Bstr &aComponent,
1488 const Bstr &aText)
1489 {
1490 return setErrorInternal (aResultCode, aIID, aComponent, aText,
1491 true /* aWarning */, true /* aLogIt */);
1492 }
1493
1494 static HRESULT setError (HRESULT aResultCode, const GUID &aIID,
1495 const Bstr &aComponent,
1496 const char *aText, va_list aArgs, bool aLogIt = true)
1497 {
1498 return setErrorInternal (aResultCode, aIID, aComponent,
1499 Utf8StrFmtVA (aText, aArgs),
1500 false /* aWarning */, aLogIt);
1501 }
1502
1503 static HRESULT setWarning (HRESULT aResultCode, const GUID &aIID,
1504 const Bstr &aComponent,
1505 const char *aText, va_list aArgs)
1506 {
1507 return setErrorInternal (aResultCode, aIID, aComponent,
1508 Utf8StrFmtVA (aText, aArgs),
1509 true /* aWarning */, true /* aLogIt */);
1510 }
1511};
1512
1513/**
1514 * This template implements ISupportErrorInfo for the given component class
1515 * and provides the #setError() method to conveniently set the error information
1516 * from within interface methods' implementations.
1517 *
1518 * On Windows, the template argument must define a COM interface map using
1519 * BEGIN_COM_MAP / END_COM_MAP macros and this map must contain a
1520 * COM_INTERFACE_ENTRY(ISupportErrorInfo) definition. All interface entries
1521 * that follow it will be considered to support IErrorInfo, i.e. the
1522 * InterfaceSupportsErrorInfo() implementation will return S_OK for the
1523 * corresponding IID.
1524 *
1525 * On all platforms, the template argument must also define the following
1526 * method: |public static const wchar_t *C::getComponentName()|. See
1527 * #setError (HRESULT, const char *, ...) for a description on how it is
1528 * used.
1529 *
1530 * @param C
1531 * component class that implements one or more COM interfaces
1532 * @param I
1533 * default interface for the component. This interface's IID is used
1534 * by the shortest form of #setError, for convenience.
1535 */
1536/// @todo switch to com::SupportErrorInfo* and remove
1537template <class C, class I>
1538class ATL_NO_VTABLE VirtualBoxSupportErrorInfoImpl
1539 : protected VirtualBoxSupportErrorInfoImplBase
1540#if !defined (VBOX_WITH_XPCOM)
1541 , public ISupportErrorInfo
1542#else
1543#endif
1544{
1545public:
1546
1547#if !defined (VBOX_WITH_XPCOM)
1548 STDMETHOD(InterfaceSupportsErrorInfo) (REFIID riid)
1549 {
1550 const _ATL_INTMAP_ENTRY* pEntries = C::_GetEntries();
1551 Assert (pEntries);
1552 if (!pEntries)
1553 return S_FALSE;
1554
1555 BOOL bSupports = FALSE;
1556 BOOL bISupportErrorInfoFound = FALSE;
1557
1558 while (pEntries->pFunc != NULL && !bSupports)
1559 {
1560 if (!bISupportErrorInfoFound)
1561 {
1562 // skip the com map entries until ISupportErrorInfo is found
1563 bISupportErrorInfoFound =
1564 InlineIsEqualGUID (*(pEntries->piid), IID_ISupportErrorInfo);
1565 }
1566 else
1567 {
1568 // look for the requested interface in the rest of the com map
1569 bSupports = InlineIsEqualGUID (*(pEntries->piid), riid);
1570 }
1571 pEntries++;
1572 }
1573
1574 Assert (bISupportErrorInfoFound);
1575
1576 return bSupports ? S_OK : S_FALSE;
1577 }
1578#endif // !defined (VBOX_WITH_XPCOM)
1579
1580protected:
1581
1582 /**
1583 * Sets the error information for the current thread.
1584 * This information can be retrieved by a caller of an interface method
1585 * using IErrorInfo on Windows or nsIException on Linux, or the cross-platform
1586 * IVirtualBoxErrorInfo interface that provides extended error info (only
1587 * for components from the VirtualBox COM library). Alternatively, the
1588 * platform-independent class com::ErrorInfo (defined in VBox[XP]COM.lib)
1589 * can be used to retrieve error info in a convenient way.
1590 *
1591 * It is assumed that the interface method that uses this function returns
1592 * an unsuccessful result code to the caller (otherwise, there is no reason
1593 * for the caller to try to retrieve error info after method invocation).
1594 *
1595 * Here is a table of correspondence between this method's arguments
1596 * and IErrorInfo/nsIException/IVirtualBoxErrorInfo attributes/methods:
1597 *
1598 * argument IErrorInfo nsIException IVirtualBoxErrorInfo
1599 * ----------------------------------------------------------------
1600 * resultCode -- result resultCode
1601 * iid GetGUID -- interfaceID
1602 * component GetSource -- component
1603 * text GetDescription message text
1604 *
1605 * This method is rarely needs to be used though. There are more convenient
1606 * overloaded versions, that automatically substitute some arguments
1607 * taking their values from the template parameters. See
1608 * #setError (HRESULT, const char *, ...) for an example.
1609 *
1610 * @param aResultCode result (error) code, must not be S_OK
1611 * @param aIID IID of the interface that defines the error
1612 * @param aComponent name of the component that generates the error
1613 * @param aText error message (must not be null), an RTStrPrintf-like
1614 * format string in UTF-8 encoding
1615 * @param ... list of arguments for the format string
1616 *
1617 * @return
1618 * the error argument, for convenience, If an error occurs while
1619 * creating error info itself, that error is returned instead of the
1620 * error argument.
1621 */
1622 static HRESULT setError (HRESULT aResultCode, const GUID &aIID,
1623 const wchar_t *aComponent,
1624 const char *aText, ...)
1625 {
1626 va_list args;
1627 va_start (args, aText);
1628 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError
1629 (aResultCode, aIID, aComponent, aText, args, true /* aLogIt */);
1630 va_end (args);
1631 return rc;
1632 }
1633
1634 /**
1635 * This method is the same as #setError() except that it makes sure @a
1636 * aResultCode doesn't have the error severity bit (31) set when passed
1637 * down to the created IVirtualBoxErrorInfo object.
1638 *
1639 * The error severity bit is always cleared by this call, thereof you can
1640 * use ordinary E_XXX result code constants, for convenience. However, this
1641 * behavior may be non-standard on some COM platforms.
1642 */
1643 static HRESULT setWarning (HRESULT aResultCode, const GUID &aIID,
1644 const wchar_t *aComponent,
1645 const char *aText, ...)
1646 {
1647 va_list args;
1648 va_start (args, aText);
1649 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setWarning
1650 (aResultCode, aIID, aComponent, aText, args);
1651 va_end (args);
1652 return rc;
1653 }
1654
1655 /**
1656 * Sets the error information for the current thread.
1657 * A convenience method that automatically sets the default interface
1658 * ID (taken from the I template argument) and the component name
1659 * (a value of C::getComponentName()).
1660 *
1661 * See #setError (HRESULT, const GUID &, const wchar_t *, const char *text, ...)
1662 * for details.
1663 *
1664 * This method is the most common (and convenient) way to set error
1665 * information from within interface methods. A typical pattern of usage
1666 * is looks like this:
1667 *
1668 * <code>
1669 * return setError (E_FAIL, "Terrible Error");
1670 * </code>
1671 * or
1672 * <code>
1673 * HRESULT rc = setError (E_FAIL, "Terrible Error");
1674 * ...
1675 * return rc;
1676 * </code>
1677 */
1678 static HRESULT setError (HRESULT aResultCode, const char *aText, ...)
1679 {
1680 va_list args;
1681 va_start (args, aText);
1682 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError
1683 (aResultCode, COM_IIDOF(I), C::getComponentName(), aText, args, true /* aLogIt */);
1684 va_end (args);
1685 return rc;
1686 }
1687
1688 /**
1689 * This method is the same as #setError() except that it makes sure @a
1690 * aResultCode doesn't have the error severity bit (31) set when passed
1691 * down to the created IVirtualBoxErrorInfo object.
1692 *
1693 * The error severity bit is always cleared by this call, thereof you can
1694 * use ordinary E_XXX result code constants, for convenience. However, this
1695 * behavior may be non-standard on some COM platforms.
1696 */
1697 static HRESULT setWarning (HRESULT aResultCode, const char *aText, ...)
1698 {
1699 va_list args;
1700 va_start (args, aText);
1701 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setWarning
1702 (aResultCode, COM_IIDOF(I), C::getComponentName(), aText, args);
1703 va_end (args);
1704 return rc;
1705 }
1706
1707 /**
1708 * Sets the error information for the current thread, va_list variant.
1709 * A convenience method that automatically sets the default interface
1710 * ID (taken from the I template argument) and the component name
1711 * (a value of C::getComponentName()).
1712 *
1713 * See #setError (HRESULT, const GUID &, const wchar_t *, const char *text, ...)
1714 * and #setError (HRESULT, const char *, ...) for details.
1715 */
1716 static HRESULT setErrorV (HRESULT aResultCode, const char *aText,
1717 va_list aArgs)
1718 {
1719 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError
1720 (aResultCode, COM_IIDOF(I), C::getComponentName(), aText, aArgs, true /* aLogIt */);
1721 return rc;
1722 }
1723
1724 /**
1725 * This method is the same as #setErrorV() except that it makes sure @a
1726 * aResultCode doesn't have the error severity bit (31) set when passed
1727 * down to the created IVirtualBoxErrorInfo object.
1728 *
1729 * The error severity bit is always cleared by this call, thereof you can
1730 * use ordinary E_XXX result code constants, for convenience. However, this
1731 * behavior may be non-standard on some COM platforms.
1732 */
1733 static HRESULT setWarningV (HRESULT aResultCode, const char *aText,
1734 va_list aArgs)
1735 {
1736 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setWarning
1737 (aResultCode, COM_IIDOF(I), C::getComponentName(), aText, aArgs);
1738 return rc;
1739 }
1740
1741 /**
1742 * Sets the error information for the current thread, BStr variant.
1743 * A convenience method that automatically sets the default interface
1744 * ID (taken from the I template argument) and the component name
1745 * (a value of C::getComponentName()).
1746 *
1747 * This method is preferred if you have a ready (translated and formatted)
1748 * Bstr string, because it omits an extra conversion Utf8Str -> Bstr.
1749 *
1750 * See #setError (HRESULT, const GUID &, const wchar_t *, const char *text, ...)
1751 * and #setError (HRESULT, const char *, ...) for details.
1752 */
1753 static HRESULT setErrorBstr (HRESULT aResultCode, const Bstr &aText)
1754 {
1755 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError
1756 (aResultCode, COM_IIDOF(I), C::getComponentName(), aText, true /* aLogIt */);
1757 return rc;
1758 }
1759
1760 /**
1761 * This method is the same as #setErrorBstr() except that it makes sure @a
1762 * aResultCode doesn't have the error severity bit (31) set when passed
1763 * down to the created IVirtualBoxErrorInfo object.
1764 *
1765 * The error severity bit is always cleared by this call, thereof you can
1766 * use ordinary E_XXX result code constants, for convenience. However, this
1767 * behavior may be non-standard on some COM platforms.
1768 */
1769 static HRESULT setWarningBstr (HRESULT aResultCode, const Bstr &aText)
1770 {
1771 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setWarning
1772 (aResultCode, COM_IIDOF(I), C::getComponentName(), aText);
1773 return rc;
1774 }
1775
1776 /**
1777 * Sets the error information for the current thread.
1778 * A convenience method that automatically sets the component name
1779 * (a value of C::getComponentName()), but allows to specify the interface
1780 * id manually.
1781 *
1782 * See #setError (HRESULT, const GUID &, const wchar_t *, const char *text, ...)
1783 * for details.
1784 */
1785 static HRESULT setError (HRESULT aResultCode, const GUID &aIID,
1786 const char *aText, ...)
1787 {
1788 va_list args;
1789 va_start (args, aText);
1790 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError
1791 (aResultCode, aIID, C::getComponentName(), aText, args, true /* aLogIt */);
1792 va_end (args);
1793 return rc;
1794 }
1795
1796 /**
1797 * This method is the same as #setError() except that it makes sure @a
1798 * aResultCode doesn't have the error severity bit (31) set when passed
1799 * down to the created IVirtualBoxErrorInfo object.
1800 *
1801 * The error severity bit is always cleared by this call, thereof you can
1802 * use ordinary E_XXX result code constants, for convenience. However, this
1803 * behavior may be non-standard on some COM platforms.
1804 */
1805 static HRESULT setWarning (HRESULT aResultCode, const GUID &aIID,
1806 const char *aText, ...)
1807 {
1808 va_list args;
1809 va_start (args, aText);
1810 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setWarning
1811 (aResultCode, aIID, C::getComponentName(), aText, args);
1812 va_end (args);
1813 return rc;
1814 }
1815
1816 /**
1817 * Sets the error information for the current thread but doesn't put
1818 * anything in the release log. This is very useful for avoiding
1819 * harmless error from causing confusion.
1820 *
1821 * It is otherwise identical to #setError (HRESULT, const char *text, ...).
1822 */
1823 static HRESULT setErrorNoLog (HRESULT aResultCode, const char *aText, ...)
1824 {
1825 va_list args;
1826 va_start (args, aText);
1827 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError
1828 (aResultCode, COM_IIDOF(I), C::getComponentName(), aText, args, false /* aLogIt */);
1829 va_end (args);
1830 return rc;
1831 }
1832
1833private:
1834
1835};
1836
1837////////////////////////////////////////////////////////////////////////////////
1838
1839/**
1840 * Base class to track VirtualBoxBase children of the component.
1841 *
1842 * This class is a preferable VirtualBoxBase replacement for components
1843 * that operate with collections of child components. It gives two useful
1844 * possibilities:
1845 *
1846 * <ol><li>
1847 * Given an IUnknown instance, it's possible to quickly determine
1848 * whether this instance represents a child object created by the given
1849 * component, and if so, get a valid VirtualBoxBase pointer to the child
1850 * object. The returned pointer can be then safely casted to the
1851 * actual class of the child object (to get access to its "internal"
1852 * non-interface methods) provided that no other child components implement
1853 * the same initial interface IUnknown is queried from.
1854 * </li><li>
1855 * When the parent object uninitializes itself, it can easily unintialize
1856 * all its VirtualBoxBase derived children (using their
1857 * VirtualBoxBase::uninit() implementations). This is done simply by
1858 * calling the #uninitDependentChildren() method.
1859 * </li></ol>
1860 *
1861 * In order to let the above work, the following must be done:
1862 * <ol><li>
1863 * When a child object is initialized, it calls #addDependentChild() of
1864 * its parent to register itself within the list of dependent children.
1865 * </li><li>
1866 * When a child object it is uninitialized, it calls #removeDependentChild()
1867 * to unregister itself. This must be done <b>after</b> the child has called
1868 * setReady(false) to indicate it is no more valid, and <b>not</b> from under
1869 * the child object's lock. Note also, that the first action the child's
1870 * uninit() implementation must do is to check for readiness after acquiring
1871 * the object's lock and return immediately if not ready.
1872 * </li></ol>
1873 *
1874 * Children added by #addDependentChild() are <b>weakly</b> referenced
1875 * (i.e. AddRef() is not called), so when a child is externally destructed
1876 * (i.e. its reference count goes to zero), it will automatically remove
1877 * itself from a map of dependent children, provided that it follows the
1878 * rules described here.
1879 *
1880 * @note
1881 * Because of weak referencing, deadlocks and assertions are very likely
1882 * if #addDependentChild() or #removeDependentChild() are used incorrectly
1883 * (called at inappropriate times). Check the above rules once more.
1884 *
1885 * @deprecated Use VirtualBoxBaseWithChildrenNEXT for new classes.
1886 */
1887class VirtualBoxBaseWithChildren : public VirtualBoxBase
1888{
1889public:
1890
1891 VirtualBoxBaseWithChildren()
1892 : mUninitDoneSem (NIL_RTSEMEVENT), mChildrenLeft (0)
1893 {}
1894
1895 virtual ~VirtualBoxBaseWithChildren()
1896 {}
1897
1898 /**
1899 * Adds the given child to the map of dependent children.
1900 * Intended to be called from the child's init() method,
1901 * from under the child's lock.
1902 *
1903 * @param C the child object to add (must inherit VirtualBoxBase AND
1904 * implement some interface)
1905 */
1906 template <class C>
1907 void addDependentChild (C *child)
1908 {
1909 AssertReturn (child, (void) 0);
1910 addDependentChild (child, child);
1911 }
1912
1913 /**
1914 * Removes the given child from the map of dependent children.
1915 * Must be called <b>after<b> the child has called setReady(false), and
1916 * <b>not</b> from under the child object's lock.
1917 *
1918 * @param C the child object to remove (must inherit VirtualBoxBase AND
1919 * implement some interface)
1920 */
1921 template <class C>
1922 void removeDependentChild (C *child)
1923 {
1924 AssertReturn (child, (void) 0);
1925 /// @todo (r=dmik) the below check (and the relevant comment above)
1926 // seems to be not necessary any more once we completely switch to
1927 // the NEXT locking scheme. This requires altering removeDependentChild()
1928 // and uninitDependentChildren() as well (due to the new state scheme,
1929 // there is a separate mutex for state transition, so calling the
1930 // child's uninit() from under the children map lock should not produce
1931 // dead-locks any more).
1932 Assert (!child->isWriteLockOnCurrentThread() || child->lockHandle() == lockHandle());
1933 removeDependentChild (ComPtr<IUnknown> (child));
1934 }
1935
1936protected:
1937
1938 void uninitDependentChildren();
1939
1940 VirtualBoxBase *getDependentChild (const ComPtr<IUnknown> &unk);
1941
1942private:
1943
1944 void addDependentChild (const ComPtr<IUnknown> &unk, VirtualBoxBase *child);
1945 void removeDependentChild (const ComPtr<IUnknown> &unk);
1946
1947 typedef std::map <IUnknown *, VirtualBoxBase *> DependentChildren;
1948 DependentChildren mDependentChildren;
1949
1950 WriteLockHandle mMapLock;
1951
1952 RTSEMEVENT mUninitDoneSem;
1953 unsigned mChildrenLeft;
1954};
1955
1956////////////////////////////////////////////////////////////////////////////////
1957
1958/**
1959 * Base class to track VirtualBoxBaseNEXT chlidren of the component.
1960 *
1961 * This class is a preferrable VirtualBoxBase replacement for components that
1962 * operate with collections of child components. It gives two useful
1963 * possibilities:
1964 *
1965 * <ol><li>
1966 * Given an IUnknown instance, it's possible to quickly determine
1967 * whether this instance represents a child object that belongs to the
1968 * given component, and if so, get a valid VirtualBoxBase pointer to the
1969 * child object. The returned pointer can be then safely casted to the
1970 * actual class of the child object (to get access to its "internal"
1971 * non-interface methods) provided that no other child components implement
1972 * the same original COM interface IUnknown is queried from.
1973 * </li><li>
1974 * When the parent object uninitializes itself, it can easily unintialize
1975 * all its VirtualBoxBase derived children (using their
1976 * VirtualBoxBase::uninit() implementations). This is done simply by
1977 * calling the #uninitDependentChildren() method.
1978 * </li></ol>
1979 *
1980 * In order to let the above work, the following must be done:
1981 * <ol><li>
1982 * When a child object is initialized, it calls #addDependentChild() of
1983 * its parent to register itself within the list of dependent children.
1984 * </li><li>
1985 * When the child object it is uninitialized, it calls
1986 * #removeDependentChild() to unregister itself.
1987 * </li></ol>
1988 *
1989 * Note that if the parent object does not call #uninitDependentChildren() when
1990 * it gets uninitialized, it must call uninit() methods of individual children
1991 * manually to disconnect them; a failure to do so will cause crashes in these
1992 * methods when children get destroyed. The same applies to children not calling
1993 * #removeDependentChild() when getting destroyed.
1994 *
1995 * Note that children added by #addDependentChild() are <b>weakly</b> referenced
1996 * (i.e. AddRef() is not called), so when a child object is deleted externally
1997 * (because it's reference count goes to zero), it will automatically remove
1998 * itself from the map of dependent children provided that it follows the rules
1999 * described here.
2000 *
2001 * Access to the child list is serialized using the #childrenLock() lock handle
2002 * (which defaults to the general object lock handle (see
2003 * VirtualBoxBase::lockHandle()). This lock is used by all add/remove methods of
2004 * this class so be aware of the need to preserve the {parent, child} lock order
2005 * when calling these methods.
2006 *
2007 * Read individual method descriptions to get further information.
2008 *
2009 * @todo This is a VirtualBoxBaseWithChildren equivalent that uses the
2010 * VirtualBoxBaseNEXT implementation. Will completely supersede
2011 * VirtualBoxBaseWithChildren after the old VirtualBoxBase implementation
2012 * has gone.
2013 */
2014class VirtualBoxBaseWithChildrenNEXT : public VirtualBoxBase
2015{
2016public:
2017
2018 VirtualBoxBaseWithChildrenNEXT()
2019 {}
2020
2021 virtual ~VirtualBoxBaseWithChildrenNEXT()
2022 {}
2023
2024 /**
2025 * Lock handle to use when adding/removing child objects from the list of
2026 * children. It is guaranteed that no any other lock is requested in methods
2027 * of this class while holding this lock.
2028 *
2029 * @warning By default, this simply returns the general object's lock handle
2030 * (see VirtualBoxBase::lockHandle()) which is sufficient for most
2031 * cases.
2032 */
2033 virtual RWLockHandle *childrenLock() { return lockHandle(); }
2034
2035 /**
2036 * Adds the given child to the list of dependent children.
2037 *
2038 * Usually gets called from the child's init() method.
2039 *
2040 * @note @a aChild (unless it is in InInit state) must be protected by
2041 * VirtualBoxBase::AutoCaller to make sure it is not uninitialized on
2042 * another thread during this method's call.
2043 *
2044 * @note When #childrenLock() is not overloaded (returns the general object
2045 * lock) and this method is called from under the child's read or
2046 * write lock, make sure the {parent, child} locking order is
2047 * preserved by locking the callee (this object) for writing before
2048 * the child's lock.
2049 *
2050 * @param aChild Child object to add (must inherit VirtualBoxBase AND
2051 * implement some interface).
2052 *
2053 * @note Locks #childrenLock() for writing.
2054 */
2055 template <class C>
2056 void addDependentChild (C *aChild)
2057 {
2058 AssertReturnVoid (aChild != NULL);
2059 doAddDependentChild (ComPtr<IUnknown> (aChild), aChild);
2060 }
2061
2062 /**
2063 * Equivalent to template <class C> void addDependentChild (C *aChild)
2064 * but takes a ComObjPtr<C> argument.
2065 */
2066 template <class C>
2067 void addDependentChild (const ComObjPtr<C> &aChild)
2068 {
2069 AssertReturnVoid (!aChild.isNull());
2070 doAddDependentChild (ComPtr<IUnknown> (static_cast <C *> (aChild)), aChild);
2071 }
2072
2073 /**
2074 * Removes the given child from the list of dependent children.
2075 *
2076 * Usually gets called from the child's uninit() method.
2077 *
2078 * Keep in mind that the called (parent) object may be no longer available
2079 * (i.e. may be deleted deleted) after this method returns, so you must not
2080 * call any other parent's methods after that!
2081 *
2082 * @note Locks #childrenLock() for writing.
2083 *
2084 * @note @a aChild (unless it is in InUninit state) must be protected by
2085 * VirtualBoxBase::AutoCaller to make sure it is not uninitialized on
2086 * another thread during this method's call.
2087 *
2088 * @note When #childrenLock() is not overloaded (returns the general object
2089 * lock) and this method is called from under the child's read or
2090 * write lock, make sure the {parent, child} locking order is
2091 * preserved by locking the callee (this object) for writing before
2092 * the child's lock. This is irrelevant when the method is called from
2093 * under this object's VirtualBoxBaseProto::AutoUninitSpan (i.e. in
2094 * InUninit state) since in this case no locking is done.
2095 *
2096 * @param aChild Child object to remove.
2097 *
2098 * @note Locks #childrenLock() for writing.
2099 */
2100 template <class C>
2101 void removeDependentChild (C *aChild)
2102 {
2103 AssertReturnVoid (aChild != NULL);
2104 doRemoveDependentChild (ComPtr<IUnknown> (aChild));
2105 }
2106
2107 /**
2108 * Equivalent to template <class C> void removeDependentChild (C *aChild)
2109 * but takes a ComObjPtr<C> argument.
2110 */
2111 template <class C>
2112 void removeDependentChild (const ComObjPtr<C> &aChild)
2113 {
2114 AssertReturnVoid (!aChild.isNull());
2115 doRemoveDependentChild (ComPtr<IUnknown> (static_cast <C *> (aChild)));
2116 }
2117
2118protected:
2119
2120 void uninitDependentChildren();
2121
2122 VirtualBoxBase *getDependentChild(const ComPtr<IUnknown> &aUnk);
2123
2124private:
2125 void doAddDependentChild(IUnknown *aUnk, VirtualBoxBase *aChild);
2126 void doRemoveDependentChild (IUnknown *aUnk);
2127
2128 typedef std::map<IUnknown*, VirtualBoxBase*> DependentChildren;
2129 DependentChildren mDependentChildren;
2130};
2131
2132////////////////////////////////////////////////////////////////////////////////
2133
2134////////////////////////////////////////////////////////////////////////////////
2135
2136/**
2137 * Base class to track component's children of the particular type.
2138 *
2139 * This class is similar to VirtualBoxBaseWithChildrenNEXT with the exception
2140 * that all children must be of the same type. For this reason, it's not
2141 * necessary to use a map to store children -- a list is used instead.
2142 *
2143 * Also, as opposed to VirtualBoxBaseWithChildren, children added by
2144 * #addDependentChild() are <b>strongly</b> referenced, so that they cannot be
2145 * deleted (even by a third party) until #removeDependentChild() is called on
2146 * them. This also means that a failure to call #removeDependentChild() and
2147 * #uninitDependentChildren() at appropriate times as described in
2148 * VirtualBoxBaseWithChildrenNEXT may cause stuck references that won't be able
2149 * uninitialize themselves.
2150 *
2151 * See individual method descriptions for further information.
2152 *
2153 * @param C Type of child objects (must inherit VirtualBoxBase AND implement
2154 * some interface).
2155 *
2156 * @todo This is a VirtualBoxBaseWithChildren equivalent that uses the
2157 * VirtualBoxBaseNEXT implementation. Will completely supersede
2158 * VirtualBoxBaseWithChildren after the old VirtualBoxBase implementation
2159 * has gone.
2160 */
2161template <class C>
2162class VirtualBoxBaseWithTypedChildren : public VirtualBoxBase
2163{
2164public:
2165
2166 typedef std::list <ComObjPtr<C> > DependentChildren;
2167
2168 VirtualBoxBaseWithTypedChildren()
2169 {}
2170
2171 virtual ~VirtualBoxBaseWithTypedChildren()
2172 {}
2173
2174 /**
2175 * Lock handle to use when adding/removing child objects from the list of
2176 * children. It is guaranteed that no any other lock is requested in methods
2177 * of this class while holding this lock.
2178 *
2179 * @warning By default, this simply returns the general object's lock handle
2180 * (see VirtualBoxBase::lockHandle()) which is sufficient for most
2181 * cases.
2182 */
2183 virtual RWLockHandle *childrenLock() { return lockHandle(); }
2184
2185 /**
2186 * Adds the given child to the list of dependent children.
2187 *
2188 * Usually gets called from the child's init() method.
2189 *
2190 * @note @a aChild (unless it is in InInit state) must be protected by
2191 * VirtualBoxBase::AutoCaller to make sure it is not uninitialized on
2192 * another thread during this method's call.
2193 *
2194 * @note When #childrenLock() is not overloaded (returns the general object
2195 * lock) and this method is called from under the child's read or
2196 * write lock, make sure the {parent, child} locking order is
2197 * preserved by locking the callee (this object) for writing before
2198 * the child's lock.
2199 *
2200 * @param aChild Child object to add.
2201 *
2202 * @note Locks #childrenLock() for writing.
2203 */
2204 void addDependentChild (C *aChild)
2205 {
2206 AssertReturnVoid (aChild != NULL);
2207
2208 AutoCaller autoCaller (this);
2209
2210 /* sanity */
2211 AssertReturnVoid (autoCaller.state() == InInit ||
2212 autoCaller.state() == Ready ||
2213 autoCaller.state() == Limited);
2214
2215 AutoWriteLock chLock (childrenLock());
2216 mDependentChildren.push_back (aChild);
2217 }
2218
2219 /**
2220 * Removes the given child from the list of dependent children.
2221 *
2222 * Usually gets called from the child's uninit() method.
2223 *
2224 * Keep in mind that the called (parent) object may be no longer available
2225 * (i.e. may be deleted deleted) after this method returns, so you must not
2226 * call any other parent's methods after that!
2227 *
2228 * @note @a aChild (unless it is in InUninit state) must be protected by
2229 * VirtualBoxBase::AutoCaller to make sure it is not uninitialized on
2230 * another thread during this method's call.
2231 *
2232 * @note When #childrenLock() is not overloaded (returns the general object
2233 * lock) and this method is called from under the child's read or
2234 * write lock, make sure the {parent, child} locking order is
2235 * preserved by locking the callee (this object) for writing before
2236 * the child's lock. This is irrelevant when the method is called from
2237 * under this object's AutoUninitSpan (i.e. in InUninit state) since
2238 * in this case no locking is done.
2239 *
2240 * @param aChild Child object to remove.
2241 *
2242 * @note Locks #childrenLock() for writing.
2243 */
2244 void removeDependentChild (C *aChild)
2245 {
2246 AssertReturnVoid (aChild);
2247
2248 AutoCaller autoCaller (this);
2249
2250 /* sanity */
2251 AssertReturnVoid (autoCaller.state() == InUninit ||
2252 autoCaller.state() == InInit ||
2253 autoCaller.state() == Ready ||
2254 autoCaller.state() == Limited);
2255
2256 /* return shortly; we are strongly referenced so the object won't get
2257 * deleted if it calls init() before uninitDependentChildren() does
2258 * and therefore the list will still contain a valid reference that will
2259 * be correctly processed by uninitDependentChildren() anyway */
2260 if (autoCaller.state() == InUninit)
2261 return;
2262
2263 AutoWriteLock chLock (childrenLock());
2264 mDependentChildren.remove (aChild);
2265 }
2266
2267protected:
2268
2269 /**
2270 * Returns the read-only list of all dependent children.
2271 *
2272 * @note Access the returned list (iterate, get size etc.) only after making
2273 * sure #childrenLock() is locked for reading or for writing!
2274 */
2275 const DependentChildren &dependentChildren() const { return mDependentChildren; }
2276
2277 /**
2278 * Uninitializes all dependent children registered on this object with
2279 * #addDependentChild().
2280 *
2281 * Must be called from within the VirtualBoxBaseProto::AutoUninitSpan (i.e.
2282 * typically from this object's uninit() method) to uninitialize children
2283 * before this object goes out of service and becomes unusable.
2284 *
2285 * Note that this method will call uninit() methods of child objects. If
2286 * these methods need to call the parent object during uninitialization,
2287 * #uninitDependentChildren() must be called before the relevant part of the
2288 * parent is uninitialized: usually at the beginning of the parent
2289 * uninitialization sequence.
2290 *
2291 * @note May lock something through the called children.
2292 */
2293 void uninitDependentChildren()
2294 {
2295 AutoCaller autoCaller (this);
2296
2297 /* We don't want to hold the childrenLock() write lock here (necessary
2298 * to protect mDependentChildren) when uninitializing children because
2299 * we want to avoid a possible deadlock where we could get stuck in
2300 * child->uninit() blocked by AutoUninitSpan waiting for the number of
2301 * child's callers to drop to zero (or for another AutoUninitSpan to
2302 * finish), while some other thread is stuck in our
2303 * removeDependentChild() method called for that child and waiting for
2304 * the childrenLock()'s write lock.
2305 *
2306 * The only safe place to not lock and keep accessing our data members
2307 * is the InUninit state (no active call to our object may exist on
2308 * another thread when we are in InUinint, provided that all such calls
2309 * use the AutoCaller class of course). InUinint is also used as a flag
2310 * by removeDependentChild() that prevents touching mDependentChildren
2311 * from outside. Therefore, we assert. Note that InInit is also fine
2312 * since no any object may access us by that time.
2313 */
2314 AssertReturnVoid (autoCaller.state() == InUninit ||
2315 autoCaller.state() == InInit);
2316
2317 if (mDependentChildren.size())
2318 {
2319 for (typename DependentChildren::iterator it = mDependentChildren.begin();
2320 it != mDependentChildren.end(); ++ it)
2321 {
2322 C *child = (*it);
2323 Assert (child);
2324
2325 /* Note that if child->uninit() happens to be called on another
2326 * thread right before us and is not yet finished, the second
2327 * uninit() call will wait until the first one has done so
2328 * (thanks to AutoUninitSpan). */
2329 if (child)
2330 child->uninit();
2331 }
2332
2333 /* release all strong references we hold */
2334 mDependentChildren.clear();
2335 }
2336 }
2337
2338 /**
2339 * Removes (detaches) all dependent children registered with
2340 * #addDependentChild(), without uninitializing them.
2341 *
2342 * @note @a |this| (unless it is in InUninit state) must be protected by
2343 * VirtualBoxBase::AutoCaller to make sure it is not uninitialized on
2344 * another thread during this method's call.
2345 *
2346 * @note Locks #childrenLock() for writing.
2347 */
2348 void removeDependentChildren()
2349 {
2350 AutoWriteLock chLock (childrenLock());
2351 mDependentChildren.clear();
2352 }
2353
2354private:
2355
2356 DependentChildren mDependentChildren;
2357};
2358
2359////////////////////////////////////////////////////////////////////////////////
2360
2361/// @todo (dmik) remove after we switch to VirtualBoxBaseNEXT completely
2362/**
2363 * Simple template that manages data structure allocation/deallocation
2364 * and supports data pointer sharing (the instance that shares the pointer is
2365 * not responsible for memory deallocation as opposed to the instance that
2366 * owns it).
2367 */
2368template <class D>
2369class Shareable
2370{
2371public:
2372
2373 Shareable() : mData (NULL), mIsShared (FALSE) {}
2374 ~Shareable() { free(); }
2375
2376 void allocate() { attach (new D); }
2377
2378 virtual void free() {
2379 if (mData) {
2380 if (!mIsShared)
2381 delete mData;
2382 mData = NULL;
2383 mIsShared = false;
2384 }
2385 }
2386
2387 void attach (D *data) {
2388 AssertMsg (data, ("new data must not be NULL"));
2389 if (data && mData != data) {
2390 if (mData && !mIsShared)
2391 delete mData;
2392 mData = data;
2393 mIsShared = false;
2394 }
2395 }
2396
2397 void attach (Shareable &data) {
2398 AssertMsg (
2399 data.mData == mData || !data.mIsShared,
2400 ("new data must not be shared")
2401 );
2402 if (this != &data && !data.mIsShared) {
2403 attach (data.mData);
2404 data.mIsShared = true;
2405 }
2406 }
2407
2408 void share (D *data) {
2409 AssertMsg (data, ("new data must not be NULL"));
2410 if (mData != data) {
2411 if (mData && !mIsShared)
2412 delete mData;
2413 mData = data;
2414 mIsShared = true;
2415 }
2416 }
2417
2418 void share (const Shareable &data) { share (data.mData); }
2419
2420 void attachCopy (const D *data) {
2421 AssertMsg (data, ("data to copy must not be NULL"));
2422 if (data)
2423 attach (new D (*data));
2424 }
2425
2426 void attachCopy (const Shareable &data) {
2427 attachCopy (data.mData);
2428 }
2429
2430 virtual D *detach() {
2431 D *d = mData;
2432 mData = NULL;
2433 mIsShared = false;
2434 return d;
2435 }
2436
2437 D *data() const {
2438 return mData;
2439 }
2440
2441 D *operator->() const {
2442 AssertMsg (mData, ("data must not be NULL"));
2443 return mData;
2444 }
2445
2446 bool isNull() const { return mData == NULL; }
2447 bool operator!() const { return isNull(); }
2448
2449 bool isShared() const { return mIsShared; }
2450
2451protected:
2452
2453 D *mData;
2454 bool mIsShared;
2455};
2456
2457/// @todo (dmik) remove after we switch to VirtualBoxBaseNEXT completely
2458/**
2459 * Simple template that enhances Shareable<> and supports data
2460 * backup/rollback/commit (using the copy constructor of the managed data
2461 * structure).
2462 */
2463template <class D>
2464class Backupable : public Shareable <D>
2465{
2466public:
2467
2468 Backupable() : Shareable <D> (), mBackupData (NULL) {}
2469
2470 void free()
2471 {
2472 AssertMsg (this->mData || !mBackupData, ("backup must be NULL if data is NULL"));
2473 rollback();
2474 Shareable <D>::free();
2475 }
2476
2477 D *detach()
2478 {
2479 AssertMsg (this->mData || !mBackupData, ("backup must be NULL if data is NULL"));
2480 rollback();
2481 return Shareable <D>::detach();
2482 }
2483
2484 void share (const Backupable &data)
2485 {
2486 AssertMsg (!data.isBackedUp(), ("data to share must not be backed up"));
2487 if (!data.isBackedUp())
2488 Shareable <D>::share (data.mData);
2489 }
2490
2491 /**
2492 * Stores the current data pointer in the backup area, allocates new data
2493 * using the copy constructor on current data and makes new data active.
2494 */
2495 void backup()
2496 {
2497 AssertMsg (this->mData, ("data must not be NULL"));
2498 if (this->mData && !mBackupData)
2499 {
2500 mBackupData = this->mData;
2501 this->mData = new D (*mBackupData);
2502 }
2503 }
2504
2505 /**
2506 * Deletes new data created by #backup() and restores previous data pointer
2507 * stored in the backup area, making it active again.
2508 */
2509 void rollback()
2510 {
2511 if (this->mData && mBackupData)
2512 {
2513 delete this->mData;
2514 this->mData = mBackupData;
2515 mBackupData = NULL;
2516 }
2517 }
2518
2519 /**
2520 * Commits current changes by deleting backed up data and clearing up the
2521 * backup area. The new data pointer created by #backup() remains active
2522 * and becomes the only managed pointer.
2523 *
2524 * This method is much faster than #commitCopy() (just a single pointer
2525 * assignment operation), but makes the previous data pointer invalid
2526 * (because it is freed). For this reason, this method must not be
2527 * used if it's possible that data managed by this instance is shared with
2528 * some other Shareable instance. See #commitCopy().
2529 */
2530 void commit()
2531 {
2532 if (this->mData && mBackupData)
2533 {
2534 if (!this->mIsShared)
2535 delete mBackupData;
2536 mBackupData = NULL;
2537 this->mIsShared = false;
2538 }
2539 }
2540
2541 /**
2542 * Commits current changes by assigning new data to the previous data
2543 * pointer stored in the backup area using the assignment operator.
2544 * New data is deleted, the backup area is cleared and the previous data
2545 * pointer becomes active and the only managed pointer.
2546 *
2547 * This method is slower than #commit(), but it keeps the previous data
2548 * pointer valid (i.e. new data is copied to the same memory location).
2549 * For that reason it's safe to use this method on instances that share
2550 * managed data with other Shareable instances.
2551 */
2552 void commitCopy()
2553 {
2554 if (this->mData && mBackupData)
2555 {
2556 *mBackupData = *(this->mData);
2557 delete this->mData;
2558 this->mData = mBackupData;
2559 mBackupData = NULL;
2560 }
2561 }
2562
2563 void assignCopy (const D *data)
2564 {
2565 AssertMsg (this->mData, ("data must not be NULL"));
2566 AssertMsg (data, ("data to copy must not be NULL"));
2567 if (this->mData && data)
2568 {
2569 if (!mBackupData)
2570 {
2571 mBackupData = this->mData;
2572 this->mData = new D (*data);
2573 }
2574 else
2575 *this->mData = *data;
2576 }
2577 }
2578
2579 void assignCopy (const Backupable &data)
2580 {
2581 assignCopy (data.mData);
2582 }
2583
2584 bool isBackedUp() const
2585 {
2586 return mBackupData != NULL;
2587 }
2588
2589 bool hasActualChanges() const
2590 {
2591 AssertMsg (this->mData, ("data must not be NULL"));
2592 return this->mData != NULL && mBackupData != NULL &&
2593 !(*this->mData == *mBackupData);
2594 }
2595
2596 D *backedUpData() const
2597 {
2598 return mBackupData;
2599 }
2600
2601protected:
2602
2603 D *mBackupData;
2604};
2605
2606#endif // ____H_VIRTUALBOXBASEIMPL
2607/* vi: set tabstop=4 shiftwidth=4 expandtab: */
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