VirtualBox

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

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

Main: the big XML settings rework. Move XML reading/writing out of interface implementation code into separate layer so it can handle individual settings versions in the future.

  • 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#if !defined (VBOX_WITH_XPCOM)
1216 , public CComObjectRootEx <CComMultiThreadModel>
1217#else
1218 , public CComObjectRootEx
1219#endif
1220{
1221
1222public:
1223 VirtualBoxBase()
1224 {}
1225
1226 virtual ~VirtualBoxBase()
1227 {}
1228
1229 /**
1230 * Virtual unintialization method. Called during parent object's
1231 * uninitialization, if the given subclass instance is a dependent child of
1232 * a class derived from VirtualBoxBaseWithChildren (@sa
1233 * VirtualBoxBaseWithChildren::addDependentChild). In this case, this
1234 * method's implementation must call setReady (false),
1235 */
1236 virtual void uninit()
1237 {}
1238
1239 static const char *translate (const char *context, const char *sourceText,
1240 const char *comment = 0);
1241};
1242
1243////////////////////////////////////////////////////////////////////////////////
1244
1245/** Helper for VirtualBoxSupportTranslation. */
1246class VirtualBoxSupportTranslationBase
1247{
1248protected:
1249 static bool cutClassNameFrom__PRETTY_FUNCTION__ (char *aPrettyFunctionName);
1250};
1251
1252/**
1253 * The VirtualBoxSupportTranslation template implements the NLS string
1254 * translation support for the given class.
1255 *
1256 * Translation support is provided by the static #tr() function. This function,
1257 * given a string in UTF-8 encoding, looks up for a translation of the given
1258 * string by calling the VirtualBoxBase::translate() global function which
1259 * receives the name of the enclosing class ("context of translation") as the
1260 * additional argument and returns a translated string based on the currently
1261 * active language.
1262 *
1263 * @param C Class that needs to support the string translation.
1264 *
1265 * @note Every class that wants to use the #tr() function in its own methods
1266 * must inherit from this template, regardless of whether its base class
1267 * (if any) inherits from it or not. Otherwise, the translation service
1268 * will not work correctly. However, the declaration of the derived
1269 * class must contain
1270 * the <tt>COM_SUPPORTTRANSLATION_OVERRIDE (<ClassName>)</tt> macro if one
1271 * of its base classes also inherits from this template (to resolve the
1272 * ambiguity of the #tr() function).
1273 */
1274template <class C>
1275class VirtualBoxSupportTranslation : virtual protected VirtualBoxSupportTranslationBase
1276{
1277public:
1278
1279 /**
1280 * Translates the given text string by calling VirtualBoxBase::translate()
1281 * and passing the name of the C class as the first argument ("context of
1282 * translation") See VirtualBoxBase::translate() for more info.
1283 *
1284 * @param aSourceText String to translate.
1285 * @param aComment Comment to the string to resolve possible
1286 * ambiguities (NULL means no comment).
1287 *
1288 * @return Translated version of the source string in UTF-8 encoding, or
1289 * the source string itself if the translation is not found in the
1290 * specified context.
1291 */
1292 inline static const char *tr (const char *aSourceText,
1293 const char *aComment = NULL)
1294 {
1295 return VirtualBoxBase::translate (className(), aSourceText, aComment);
1296 }
1297
1298protected:
1299
1300 static const char *className()
1301 {
1302 static char fn [sizeof (__PRETTY_FUNCTION__) + 1];
1303 if (!sClassName)
1304 {
1305 strcpy (fn, __PRETTY_FUNCTION__);
1306 cutClassNameFrom__PRETTY_FUNCTION__ (fn);
1307 sClassName = fn;
1308 }
1309 return sClassName;
1310 }
1311
1312private:
1313
1314 static const char *sClassName;
1315};
1316
1317template <class C>
1318const char *VirtualBoxSupportTranslation<C>::sClassName = NULL;
1319
1320/**
1321 * This macro must be invoked inside the public section of the declaration of
1322 * the class inherited from the VirtualBoxSupportTranslation template in case
1323 * if one of its other base classes also inherits from that template. This is
1324 * necessary to resolve the ambiguity of the #tr() function.
1325 *
1326 * @param C Class that inherits the VirtualBoxSupportTranslation template
1327 * more than once (through its other base clases).
1328 */
1329#define VIRTUALBOXSUPPORTTRANSLATION_OVERRIDE(C) \
1330 inline static const char *tr (const char *aSourceText, \
1331 const char *aComment = NULL) \
1332 { \
1333 return VirtualBoxSupportTranslation<C>::tr (aSourceText, aComment); \
1334 }
1335
1336/**
1337 * Dummy macro that is used to shut down Qt's lupdate tool warnings in some
1338 * situations. This macro needs to be present inside (better at the very
1339 * beginning) of the declaration of the class that inherits from
1340 * VirtualBoxSupportTranslation template, to make lupdate happy.
1341 */
1342#define Q_OBJECT
1343
1344////////////////////////////////////////////////////////////////////////////////
1345
1346/**
1347 * Helper for the VirtualBoxSupportErrorInfoImpl template.
1348 */
1349/// @todo switch to com::SupportErrorInfo* and remove
1350class VirtualBoxSupportErrorInfoImplBase
1351{
1352 static HRESULT setErrorInternal (HRESULT aResultCode, const GUID &aIID,
1353 const Bstr &aComponent, const Bstr &aText,
1354 bool aWarning, bool aLogIt);
1355
1356protected:
1357
1358 /**
1359 * The MultiResult class is a com::FWResult enhancement that also acts as a
1360 * switch to turn on multi-error mode for #setError() or #setWarning()
1361 * calls.
1362 *
1363 * When an instance of this class is created, multi-error mode is turned on
1364 * for the current thread and the turn-on counter is increased by one. In
1365 * multi-error mode, a call to #setError() or #setWarning() does not
1366 * overwrite the current error or warning info object possibly set on the
1367 * current thread by other method calls, but instead it stores this old
1368 * object in the IVirtualBoxErrorInfo::next attribute of the new error
1369 * object being set.
1370 *
1371 * This way, error/warning objects are stacked together and form a chain of
1372 * errors where the most recent error is the first one retrieved by the
1373 * calling party, the preceding error is what the
1374 * IVirtualBoxErrorInfo::next attribute of the first error points to, and so
1375 * on, up to the first error or warning occurred which is the last in the
1376 * chain. See IVirtualBoxErrorInfo documentation for more info.
1377 *
1378 * When the instance of the MultiResult class goes out of scope and gets
1379 * destroyed, it automatically decreases the turn-on counter by one. If
1380 * the counter drops to zero, multi-error mode for the current thread is
1381 * turned off and the thread switches back to single-error mode where every
1382 * next error or warning object overwrites the previous one.
1383 *
1384 * Note that the caller of a COM method uses a non-S_OK result code to
1385 * decide if the method has returned an error (negative codes) or a warning
1386 * (positive non-zero codes) and will query extended error info only in
1387 * these two cases. However, since multi-error mode implies that the method
1388 * doesn't return control return to the caller immediately after the first
1389 * error or warning but continues its execution, the functionality provided
1390 * by the base com::FWResult class becomes very useful because it allows to
1391 * preserve the error or the warning result code even if it is later assigned
1392 * a S_OK value multiple times. See com::FWResult for details.
1393 *
1394 * Here is the typical usage pattern:
1395 * <code>
1396
1397 HRESULT Bar::method()
1398 {
1399 // assume multi-errors are turned off here...
1400
1401 if (something)
1402 {
1403 // Turn on multi-error mode and make sure severity is preserved
1404 MultiResult rc = foo->method1();
1405
1406 // return on fatal error, but continue on warning or on success
1407 CheckComRCReturnRC (rc);
1408
1409 rc = foo->method2();
1410 // no matter what result, stack it and continue
1411
1412 // ...
1413
1414 // return the last worst result code (it will be preserved even if
1415 // foo->method2() returns S_OK.
1416 return rc;
1417 }
1418
1419 // multi-errors are turned off here again...
1420
1421 return S_OK;
1422 }
1423
1424 * </code>
1425 *
1426 *
1427 * @note This class is intended to be instantiated on the stack, therefore
1428 * You cannot create them using new(). Although it is possible to copy
1429 * instances of MultiResult or return them by value, please never do
1430 * that as it is breaks the class semantics (and will assert).
1431 */
1432 class MultiResult : public com::FWResult
1433 {
1434 public:
1435
1436 /**
1437 * @copydoc com::FWResult::FWResult().
1438 */
1439 MultiResult (HRESULT aRC = E_FAIL) : FWResult (aRC) { init(); }
1440
1441 MultiResult (const MultiResult &aThat) : FWResult (aThat)
1442 {
1443 /* We need this copy constructor only for GCC that wants to have
1444 * it in case of expressions like |MultiResult rc = E_FAIL;|. But
1445 * we assert since the optimizer should actually avoid the
1446 * temporary and call the other constructor directly instead. */
1447 AssertFailed();
1448 init();
1449 }
1450
1451 ~MultiResult();
1452
1453 MultiResult &operator= (HRESULT aRC)
1454 {
1455 com::FWResult::operator= (aRC);
1456 return *this;
1457 }
1458
1459 MultiResult &operator= (const MultiResult &aThat)
1460 {
1461 /* We need this copy constructor only for GCC that wants to have
1462 * it in case of expressions like |MultiResult rc = E_FAIL;|. But
1463 * we assert since the optimizer should actually avoid the
1464 * temporary and call the other constructor directly instead. */
1465 AssertFailed();
1466 com::FWResult::operator= (aThat);
1467 return *this;
1468 }
1469
1470 private:
1471
1472 DECLARE_CLS_NEW_DELETE_NOOP (MultiResult)
1473
1474 void init();
1475
1476 static RTTLS sCounter;
1477
1478 friend class VirtualBoxSupportErrorInfoImplBase;
1479 };
1480
1481 static HRESULT setError (HRESULT aResultCode, const GUID &aIID,
1482 const Bstr &aComponent,
1483 const Bstr &aText,
1484 bool aLogIt = true)
1485 {
1486 return setErrorInternal (aResultCode, aIID, aComponent, aText,
1487 false /* aWarning */, aLogIt);
1488 }
1489
1490 static HRESULT setWarning (HRESULT aResultCode, const GUID &aIID,
1491 const Bstr &aComponent,
1492 const Bstr &aText)
1493 {
1494 return setErrorInternal (aResultCode, aIID, aComponent, aText,
1495 true /* aWarning */, true /* aLogIt */);
1496 }
1497
1498 static HRESULT setError (HRESULT aResultCode, const GUID &aIID,
1499 const Bstr &aComponent,
1500 const char *aText, va_list aArgs, bool aLogIt = true)
1501 {
1502 return setErrorInternal (aResultCode, aIID, aComponent,
1503 Utf8StrFmtVA (aText, aArgs),
1504 false /* aWarning */, aLogIt);
1505 }
1506
1507 static HRESULT setWarning (HRESULT aResultCode, const GUID &aIID,
1508 const Bstr &aComponent,
1509 const char *aText, va_list aArgs)
1510 {
1511 return setErrorInternal (aResultCode, aIID, aComponent,
1512 Utf8StrFmtVA (aText, aArgs),
1513 true /* aWarning */, true /* aLogIt */);
1514 }
1515};
1516
1517/**
1518 * This template implements ISupportErrorInfo for the given component class
1519 * and provides the #setError() method to conveniently set the error information
1520 * from within interface methods' implementations.
1521 *
1522 * On Windows, the template argument must define a COM interface map using
1523 * BEGIN_COM_MAP / END_COM_MAP macros and this map must contain a
1524 * COM_INTERFACE_ENTRY(ISupportErrorInfo) definition. All interface entries
1525 * that follow it will be considered to support IErrorInfo, i.e. the
1526 * InterfaceSupportsErrorInfo() implementation will return S_OK for the
1527 * corresponding IID.
1528 *
1529 * On all platforms, the template argument must also define the following
1530 * method: |public static const wchar_t *C::getComponentName()|. See
1531 * #setError (HRESULT, const char *, ...) for a description on how it is
1532 * used.
1533 *
1534 * @param C
1535 * component class that implements one or more COM interfaces
1536 * @param I
1537 * default interface for the component. This interface's IID is used
1538 * by the shortest form of #setError, for convenience.
1539 */
1540/// @todo switch to com::SupportErrorInfo* and remove
1541template <class C, class I>
1542class ATL_NO_VTABLE VirtualBoxSupportErrorInfoImpl
1543 : protected VirtualBoxSupportErrorInfoImplBase
1544#if !defined (VBOX_WITH_XPCOM)
1545 , public ISupportErrorInfo
1546#else
1547#endif
1548{
1549public:
1550
1551#if !defined (VBOX_WITH_XPCOM)
1552 STDMETHOD(InterfaceSupportsErrorInfo) (REFIID riid)
1553 {
1554 const _ATL_INTMAP_ENTRY* pEntries = C::_GetEntries();
1555 Assert (pEntries);
1556 if (!pEntries)
1557 return S_FALSE;
1558
1559 BOOL bSupports = FALSE;
1560 BOOL bISupportErrorInfoFound = FALSE;
1561
1562 while (pEntries->pFunc != NULL && !bSupports)
1563 {
1564 if (!bISupportErrorInfoFound)
1565 {
1566 // skip the com map entries until ISupportErrorInfo is found
1567 bISupportErrorInfoFound =
1568 InlineIsEqualGUID (*(pEntries->piid), IID_ISupportErrorInfo);
1569 }
1570 else
1571 {
1572 // look for the requested interface in the rest of the com map
1573 bSupports = InlineIsEqualGUID (*(pEntries->piid), riid);
1574 }
1575 pEntries++;
1576 }
1577
1578 Assert (bISupportErrorInfoFound);
1579
1580 return bSupports ? S_OK : S_FALSE;
1581 }
1582#endif // !defined (VBOX_WITH_XPCOM)
1583
1584protected:
1585
1586 /**
1587 * Sets the error information for the current thread.
1588 * This information can be retrieved by a caller of an interface method
1589 * using IErrorInfo on Windows or nsIException on Linux, or the cross-platform
1590 * IVirtualBoxErrorInfo interface that provides extended error info (only
1591 * for components from the VirtualBox COM library). Alternatively, the
1592 * platform-independent class com::ErrorInfo (defined in VBox[XP]COM.lib)
1593 * can be used to retrieve error info in a convenient way.
1594 *
1595 * It is assumed that the interface method that uses this function returns
1596 * an unsuccessful result code to the caller (otherwise, there is no reason
1597 * for the caller to try to retrieve error info after method invocation).
1598 *
1599 * Here is a table of correspondence between this method's arguments
1600 * and IErrorInfo/nsIException/IVirtualBoxErrorInfo attributes/methods:
1601 *
1602 * argument IErrorInfo nsIException IVirtualBoxErrorInfo
1603 * ----------------------------------------------------------------
1604 * resultCode -- result resultCode
1605 * iid GetGUID -- interfaceID
1606 * component GetSource -- component
1607 * text GetDescription message text
1608 *
1609 * This method is rarely needs to be used though. There are more convenient
1610 * overloaded versions, that automatically substitute some arguments
1611 * taking their values from the template parameters. See
1612 * #setError (HRESULT, const char *, ...) for an example.
1613 *
1614 * @param aResultCode result (error) code, must not be S_OK
1615 * @param aIID IID of the interface that defines the error
1616 * @param aComponent name of the component that generates the error
1617 * @param aText error message (must not be null), an RTStrPrintf-like
1618 * format string in UTF-8 encoding
1619 * @param ... list of arguments for the format string
1620 *
1621 * @return
1622 * the error argument, for convenience, If an error occurs while
1623 * creating error info itself, that error is returned instead of the
1624 * error argument.
1625 */
1626 static HRESULT setError (HRESULT aResultCode, const GUID &aIID,
1627 const wchar_t *aComponent,
1628 const char *aText, ...)
1629 {
1630 va_list args;
1631 va_start (args, aText);
1632 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError
1633 (aResultCode, aIID, aComponent, aText, args, true /* aLogIt */);
1634 va_end (args);
1635 return rc;
1636 }
1637
1638 /**
1639 * This method is the same as #setError() except that it makes sure @a
1640 * aResultCode doesn't have the error severity bit (31) set when passed
1641 * down to the created IVirtualBoxErrorInfo object.
1642 *
1643 * The error severity bit is always cleared by this call, thereof you can
1644 * use ordinary E_XXX result code constants, for convenience. However, this
1645 * behavior may be non-standard on some COM platforms.
1646 */
1647 static HRESULT setWarning (HRESULT aResultCode, const GUID &aIID,
1648 const wchar_t *aComponent,
1649 const char *aText, ...)
1650 {
1651 va_list args;
1652 va_start (args, aText);
1653 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setWarning
1654 (aResultCode, aIID, aComponent, aText, args);
1655 va_end (args);
1656 return rc;
1657 }
1658
1659 /**
1660 * Sets the error information for the current thread.
1661 * A convenience method that automatically sets the default interface
1662 * ID (taken from the I template argument) and the component name
1663 * (a value of C::getComponentName()).
1664 *
1665 * See #setError (HRESULT, const GUID &, const wchar_t *, const char *text, ...)
1666 * for details.
1667 *
1668 * This method is the most common (and convenient) way to set error
1669 * information from within interface methods. A typical pattern of usage
1670 * is looks like this:
1671 *
1672 * <code>
1673 * return setError (E_FAIL, "Terrible Error");
1674 * </code>
1675 * or
1676 * <code>
1677 * HRESULT rc = setError (E_FAIL, "Terrible Error");
1678 * ...
1679 * return rc;
1680 * </code>
1681 */
1682 static HRESULT setError (HRESULT aResultCode, const char *aText, ...)
1683 {
1684 va_list args;
1685 va_start (args, aText);
1686 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError
1687 (aResultCode, COM_IIDOF(I), C::getComponentName(), aText, args, true /* aLogIt */);
1688 va_end (args);
1689 return rc;
1690 }
1691
1692 /**
1693 * This method is the same as #setError() except that it makes sure @a
1694 * aResultCode doesn't have the error severity bit (31) set when passed
1695 * down to the created IVirtualBoxErrorInfo object.
1696 *
1697 * The error severity bit is always cleared by this call, thereof you can
1698 * use ordinary E_XXX result code constants, for convenience. However, this
1699 * behavior may be non-standard on some COM platforms.
1700 */
1701 static HRESULT setWarning (HRESULT aResultCode, const char *aText, ...)
1702 {
1703 va_list args;
1704 va_start (args, aText);
1705 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setWarning
1706 (aResultCode, COM_IIDOF(I), C::getComponentName(), aText, args);
1707 va_end (args);
1708 return rc;
1709 }
1710
1711 /**
1712 * Sets the error information for the current thread, va_list variant.
1713 * A convenience method that automatically sets the default interface
1714 * ID (taken from the I template argument) and the component name
1715 * (a value of C::getComponentName()).
1716 *
1717 * See #setError (HRESULT, const GUID &, const wchar_t *, const char *text, ...)
1718 * and #setError (HRESULT, const char *, ...) for details.
1719 */
1720 static HRESULT setErrorV (HRESULT aResultCode, const char *aText,
1721 va_list aArgs)
1722 {
1723 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError
1724 (aResultCode, COM_IIDOF(I), C::getComponentName(), aText, aArgs, true /* aLogIt */);
1725 return rc;
1726 }
1727
1728 /**
1729 * This method is the same as #setErrorV() except that it makes sure @a
1730 * aResultCode doesn't have the error severity bit (31) set when passed
1731 * down to the created IVirtualBoxErrorInfo object.
1732 *
1733 * The error severity bit is always cleared by this call, thereof you can
1734 * use ordinary E_XXX result code constants, for convenience. However, this
1735 * behavior may be non-standard on some COM platforms.
1736 */
1737 static HRESULT setWarningV (HRESULT aResultCode, const char *aText,
1738 va_list aArgs)
1739 {
1740 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setWarning
1741 (aResultCode, COM_IIDOF(I), C::getComponentName(), aText, aArgs);
1742 return rc;
1743 }
1744
1745 /**
1746 * Sets the error information for the current thread, BStr variant.
1747 * A convenience method that automatically sets the default interface
1748 * ID (taken from the I template argument) and the component name
1749 * (a value of C::getComponentName()).
1750 *
1751 * This method is preferred if you have a ready (translated and formatted)
1752 * Bstr string, because it omits an extra conversion Utf8Str -> Bstr.
1753 *
1754 * See #setError (HRESULT, const GUID &, const wchar_t *, const char *text, ...)
1755 * and #setError (HRESULT, const char *, ...) for details.
1756 */
1757 static HRESULT setErrorBstr (HRESULT aResultCode, const Bstr &aText)
1758 {
1759 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError
1760 (aResultCode, COM_IIDOF(I), C::getComponentName(), aText, true /* aLogIt */);
1761 return rc;
1762 }
1763
1764 /**
1765 * This method is the same as #setErrorBstr() except that it makes sure @a
1766 * aResultCode doesn't have the error severity bit (31) set when passed
1767 * down to the created IVirtualBoxErrorInfo object.
1768 *
1769 * The error severity bit is always cleared by this call, thereof you can
1770 * use ordinary E_XXX result code constants, for convenience. However, this
1771 * behavior may be non-standard on some COM platforms.
1772 */
1773 static HRESULT setWarningBstr (HRESULT aResultCode, const Bstr &aText)
1774 {
1775 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setWarning
1776 (aResultCode, COM_IIDOF(I), C::getComponentName(), aText);
1777 return rc;
1778 }
1779
1780 /**
1781 * Sets the error information for the current thread.
1782 * A convenience method that automatically sets the component name
1783 * (a value of C::getComponentName()), but allows to specify the interface
1784 * id manually.
1785 *
1786 * See #setError (HRESULT, const GUID &, const wchar_t *, const char *text, ...)
1787 * for details.
1788 */
1789 static HRESULT setError (HRESULT aResultCode, const GUID &aIID,
1790 const char *aText, ...)
1791 {
1792 va_list args;
1793 va_start (args, aText);
1794 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError
1795 (aResultCode, aIID, C::getComponentName(), aText, args, true /* aLogIt */);
1796 va_end (args);
1797 return rc;
1798 }
1799
1800 /**
1801 * This method is the same as #setError() except that it makes sure @a
1802 * aResultCode doesn't have the error severity bit (31) set when passed
1803 * down to the created IVirtualBoxErrorInfo object.
1804 *
1805 * The error severity bit is always cleared by this call, thereof you can
1806 * use ordinary E_XXX result code constants, for convenience. However, this
1807 * behavior may be non-standard on some COM platforms.
1808 */
1809 static HRESULT setWarning (HRESULT aResultCode, const GUID &aIID,
1810 const char *aText, ...)
1811 {
1812 va_list args;
1813 va_start (args, aText);
1814 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setWarning
1815 (aResultCode, aIID, C::getComponentName(), aText, args);
1816 va_end (args);
1817 return rc;
1818 }
1819
1820 /**
1821 * Sets the error information for the current thread but doesn't put
1822 * anything in the release log. This is very useful for avoiding
1823 * harmless error from causing confusion.
1824 *
1825 * It is otherwise identical to #setError (HRESULT, const char *text, ...).
1826 */
1827 static HRESULT setErrorNoLog (HRESULT aResultCode, const char *aText, ...)
1828 {
1829 va_list args;
1830 va_start (args, aText);
1831 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError
1832 (aResultCode, COM_IIDOF(I), C::getComponentName(), aText, args, false /* aLogIt */);
1833 va_end (args);
1834 return rc;
1835 }
1836
1837private:
1838
1839};
1840
1841////////////////////////////////////////////////////////////////////////////////
1842
1843/**
1844 * Base class to track VirtualBoxBase children of the component.
1845 *
1846 * This class is a preferable VirtualBoxBase replacement for components
1847 * that operate with collections of child components. It gives two useful
1848 * possibilities:
1849 *
1850 * <ol><li>
1851 * Given an IUnknown instance, it's possible to quickly determine
1852 * whether this instance represents a child object created by the given
1853 * component, and if so, get a valid VirtualBoxBase pointer to the child
1854 * object. The returned pointer can be then safely casted to the
1855 * actual class of the child object (to get access to its "internal"
1856 * non-interface methods) provided that no other child components implement
1857 * the same initial interface IUnknown is queried from.
1858 * </li><li>
1859 * When the parent object uninitializes itself, it can easily unintialize
1860 * all its VirtualBoxBase derived children (using their
1861 * VirtualBoxBase::uninit() implementations). This is done simply by
1862 * calling the #uninitDependentChildren() method.
1863 * </li></ol>
1864 *
1865 * In order to let the above work, the following must be done:
1866 * <ol><li>
1867 * When a child object is initialized, it calls #addDependentChild() of
1868 * its parent to register itself within the list of dependent children.
1869 * </li><li>
1870 * When a child object it is uninitialized, it calls #removeDependentChild()
1871 * to unregister itself. This must be done <b>after</b> the child has called
1872 * setReady(false) to indicate it is no more valid, and <b>not</b> from under
1873 * the child object's lock. Note also, that the first action the child's
1874 * uninit() implementation must do is to check for readiness after acquiring
1875 * the object's lock and return immediately if not ready.
1876 * </li></ol>
1877 *
1878 * Children added by #addDependentChild() are <b>weakly</b> referenced
1879 * (i.e. AddRef() is not called), so when a child is externally destructed
1880 * (i.e. its reference count goes to zero), it will automatically remove
1881 * itself from a map of dependent children, provided that it follows the
1882 * rules described here.
1883 *
1884 * @note
1885 * Because of weak referencing, deadlocks and assertions are very likely
1886 * if #addDependentChild() or #removeDependentChild() are used incorrectly
1887 * (called at inappropriate times). Check the above rules once more.
1888 *
1889 * @deprecated Use VirtualBoxBaseWithChildrenNEXT for new classes.
1890 */
1891class VirtualBoxBaseWithChildren : public VirtualBoxBase
1892{
1893public:
1894
1895 VirtualBoxBaseWithChildren()
1896 : mUninitDoneSem (NIL_RTSEMEVENT), mChildrenLeft (0)
1897 {}
1898
1899 virtual ~VirtualBoxBaseWithChildren()
1900 {}
1901
1902 /**
1903 * Adds the given child to the map of dependent children.
1904 * Intended to be called from the child's init() method,
1905 * from under the child's lock.
1906 *
1907 * @param C the child object to add (must inherit VirtualBoxBase AND
1908 * implement some interface)
1909 */
1910 template <class C>
1911 void addDependentChild (C *child)
1912 {
1913 AssertReturn (child, (void) 0);
1914 addDependentChild (child, child);
1915 }
1916
1917 /**
1918 * Removes the given child from the map of dependent children.
1919 * Must be called <b>after<b> the child has called setReady(false), and
1920 * <b>not</b> from under the child object's lock.
1921 *
1922 * @param C the child object to remove (must inherit VirtualBoxBase AND
1923 * implement some interface)
1924 */
1925 template <class C>
1926 void removeDependentChild (C *child)
1927 {
1928 AssertReturn (child, (void) 0);
1929 /// @todo (r=dmik) the below check (and the relevant comment above)
1930 // seems to be not necessary any more once we completely switch to
1931 // the NEXT locking scheme. This requires altering removeDependentChild()
1932 // and uninitDependentChildren() as well (due to the new state scheme,
1933 // there is a separate mutex for state transition, so calling the
1934 // child's uninit() from under the children map lock should not produce
1935 // dead-locks any more).
1936 Assert (!child->isWriteLockOnCurrentThread() || child->lockHandle() == lockHandle());
1937 removeDependentChild (ComPtr<IUnknown> (child));
1938 }
1939
1940protected:
1941
1942 void uninitDependentChildren();
1943
1944 VirtualBoxBase *getDependentChild (const ComPtr<IUnknown> &unk);
1945
1946private:
1947
1948 void addDependentChild (const ComPtr<IUnknown> &unk, VirtualBoxBase *child);
1949 void removeDependentChild (const ComPtr<IUnknown> &unk);
1950
1951 typedef std::map <IUnknown *, VirtualBoxBase *> DependentChildren;
1952 DependentChildren mDependentChildren;
1953
1954 WriteLockHandle mMapLock;
1955
1956 RTSEMEVENT mUninitDoneSem;
1957 unsigned mChildrenLeft;
1958};
1959
1960////////////////////////////////////////////////////////////////////////////////
1961
1962/**
1963 * Base class to track VirtualBoxBaseNEXT chlidren of the component.
1964 *
1965 * This class is a preferrable VirtualBoxBase replacement for components that
1966 * operate with collections of child components. It gives two useful
1967 * possibilities:
1968 *
1969 * <ol><li>
1970 * Given an IUnknown instance, it's possible to quickly determine
1971 * whether this instance represents a child object that belongs to the
1972 * given component, and if so, get a valid VirtualBoxBase pointer to the
1973 * child object. The returned pointer can be then safely casted to the
1974 * actual class of the child object (to get access to its "internal"
1975 * non-interface methods) provided that no other child components implement
1976 * the same original COM interface IUnknown is queried from.
1977 * </li><li>
1978 * When the parent object uninitializes itself, it can easily unintialize
1979 * all its VirtualBoxBase derived children (using their
1980 * VirtualBoxBase::uninit() implementations). This is done simply by
1981 * calling the #uninitDependentChildren() method.
1982 * </li></ol>
1983 *
1984 * In order to let the above work, the following must be done:
1985 * <ol><li>
1986 * When a child object is initialized, it calls #addDependentChild() of
1987 * its parent to register itself within the list of dependent children.
1988 * </li><li>
1989 * When the child object it is uninitialized, it calls
1990 * #removeDependentChild() to unregister itself.
1991 * </li></ol>
1992 *
1993 * Note that if the parent object does not call #uninitDependentChildren() when
1994 * it gets uninitialized, it must call uninit() methods of individual children
1995 * manually to disconnect them; a failure to do so will cause crashes in these
1996 * methods when children get destroyed. The same applies to children not calling
1997 * #removeDependentChild() when getting destroyed.
1998 *
1999 * Note that children added by #addDependentChild() are <b>weakly</b> referenced
2000 * (i.e. AddRef() is not called), so when a child object is deleted externally
2001 * (because it's reference count goes to zero), it will automatically remove
2002 * itself from the map of dependent children provided that it follows the rules
2003 * described here.
2004 *
2005 * Access to the child list is serialized using the #childrenLock() lock handle
2006 * (which defaults to the general object lock handle (see
2007 * VirtualBoxBase::lockHandle()). This lock is used by all add/remove methods of
2008 * this class so be aware of the need to preserve the {parent, child} lock order
2009 * when calling these methods.
2010 *
2011 * Read individual method descriptions to get further information.
2012 *
2013 * @todo This is a VirtualBoxBaseWithChildren equivalent that uses the
2014 * VirtualBoxBaseNEXT implementation. Will completely supersede
2015 * VirtualBoxBaseWithChildren after the old VirtualBoxBase implementation
2016 * has gone.
2017 */
2018class VirtualBoxBaseWithChildrenNEXT : public VirtualBoxBase
2019{
2020public:
2021
2022 VirtualBoxBaseWithChildrenNEXT()
2023 {}
2024
2025 virtual ~VirtualBoxBaseWithChildrenNEXT()
2026 {}
2027
2028 /**
2029 * Lock handle to use when adding/removing child objects from the list of
2030 * children. It is guaranteed that no any other lock is requested in methods
2031 * of this class while holding this lock.
2032 *
2033 * @warning By default, this simply returns the general object's lock handle
2034 * (see VirtualBoxBase::lockHandle()) which is sufficient for most
2035 * cases.
2036 */
2037 virtual RWLockHandle *childrenLock() { return lockHandle(); }
2038
2039 /**
2040 * Adds the given child to the list of dependent children.
2041 *
2042 * Usually gets called from the child's init() method.
2043 *
2044 * @note @a aChild (unless it is in InInit state) must be protected by
2045 * VirtualBoxBase::AutoCaller to make sure it is not uninitialized on
2046 * another thread during this method's call.
2047 *
2048 * @note When #childrenLock() is not overloaded (returns the general object
2049 * lock) and this method is called from under the child's read or
2050 * write lock, make sure the {parent, child} locking order is
2051 * preserved by locking the callee (this object) for writing before
2052 * the child's lock.
2053 *
2054 * @param aChild Child object to add (must inherit VirtualBoxBase AND
2055 * implement some interface).
2056 *
2057 * @note Locks #childrenLock() for writing.
2058 */
2059 template <class C>
2060 void addDependentChild (C *aChild)
2061 {
2062 AssertReturnVoid (aChild != NULL);
2063 doAddDependentChild (ComPtr<IUnknown> (aChild), aChild);
2064 }
2065
2066 /**
2067 * Equivalent to template <class C> void addDependentChild (C *aChild)
2068 * but takes a ComObjPtr<C> argument.
2069 */
2070 template <class C>
2071 void addDependentChild (const ComObjPtr<C> &aChild)
2072 {
2073 AssertReturnVoid (!aChild.isNull());
2074 doAddDependentChild (ComPtr<IUnknown> (static_cast <C *> (aChild)), aChild);
2075 }
2076
2077 /**
2078 * Removes the given child from the list of dependent children.
2079 *
2080 * Usually gets called from the child's uninit() method.
2081 *
2082 * Keep in mind that the called (parent) object may be no longer available
2083 * (i.e. may be deleted deleted) after this method returns, so you must not
2084 * call any other parent's methods after that!
2085 *
2086 * @note Locks #childrenLock() for writing.
2087 *
2088 * @note @a aChild (unless it is in InUninit state) must be protected by
2089 * VirtualBoxBase::AutoCaller to make sure it is not uninitialized on
2090 * another thread during this method's call.
2091 *
2092 * @note When #childrenLock() is not overloaded (returns the general object
2093 * lock) and this method is called from under the child's read or
2094 * write lock, make sure the {parent, child} locking order is
2095 * preserved by locking the callee (this object) for writing before
2096 * the child's lock. This is irrelevant when the method is called from
2097 * under this object's VirtualBoxBaseProto::AutoUninitSpan (i.e. in
2098 * InUninit state) since in this case no locking is done.
2099 *
2100 * @param aChild Child object to remove.
2101 *
2102 * @note Locks #childrenLock() for writing.
2103 */
2104 template <class C>
2105 void removeDependentChild (C *aChild)
2106 {
2107 AssertReturnVoid (aChild != NULL);
2108 doRemoveDependentChild (ComPtr<IUnknown> (aChild));
2109 }
2110
2111 /**
2112 * Equivalent to template <class C> void removeDependentChild (C *aChild)
2113 * but takes a ComObjPtr<C> argument.
2114 */
2115 template <class C>
2116 void removeDependentChild (const ComObjPtr<C> &aChild)
2117 {
2118 AssertReturnVoid (!aChild.isNull());
2119 doRemoveDependentChild (ComPtr<IUnknown> (static_cast <C *> (aChild)));
2120 }
2121
2122protected:
2123
2124 void uninitDependentChildren();
2125
2126 VirtualBoxBase *getDependentChild(const ComPtr<IUnknown> &aUnk);
2127
2128private:
2129 void doAddDependentChild(IUnknown *aUnk, VirtualBoxBase *aChild);
2130 void doRemoveDependentChild (IUnknown *aUnk);
2131
2132 typedef std::map<IUnknown*, VirtualBoxBase*> DependentChildren;
2133 DependentChildren mDependentChildren;
2134};
2135
2136////////////////////////////////////////////////////////////////////////////////
2137
2138////////////////////////////////////////////////////////////////////////////////
2139
2140/**
2141 * Base class to track component's children of the particular type.
2142 *
2143 * This class is similar to VirtualBoxBaseWithChildrenNEXT with the exception
2144 * that all children must be of the same type. For this reason, it's not
2145 * necessary to use a map to store children -- a list is used instead.
2146 *
2147 * Also, as opposed to VirtualBoxBaseWithChildren, children added by
2148 * #addDependentChild() are <b>strongly</b> referenced, so that they cannot be
2149 * deleted (even by a third party) until #removeDependentChild() is called on
2150 * them. This also means that a failure to call #removeDependentChild() and
2151 * #uninitDependentChildren() at appropriate times as described in
2152 * VirtualBoxBaseWithChildrenNEXT may cause stuck references that won't be able
2153 * uninitialize themselves.
2154 *
2155 * See individual method descriptions for further information.
2156 *
2157 * @param C Type of child objects (must inherit VirtualBoxBase AND implement
2158 * some interface).
2159 *
2160 * @todo This is a VirtualBoxBaseWithChildren equivalent that uses the
2161 * VirtualBoxBaseNEXT implementation. Will completely supersede
2162 * VirtualBoxBaseWithChildren after the old VirtualBoxBase implementation
2163 * has gone.
2164 */
2165template <class C>
2166class VirtualBoxBaseWithTypedChildren : public VirtualBoxBase
2167{
2168public:
2169
2170 typedef std::list <ComObjPtr<C> > DependentChildren;
2171
2172 VirtualBoxBaseWithTypedChildren()
2173 {}
2174
2175 virtual ~VirtualBoxBaseWithTypedChildren()
2176 {}
2177
2178 /**
2179 * Lock handle to use when adding/removing child objects from the list of
2180 * children. It is guaranteed that no any other lock is requested in methods
2181 * of this class while holding this lock.
2182 *
2183 * @warning By default, this simply returns the general object's lock handle
2184 * (see VirtualBoxBase::lockHandle()) which is sufficient for most
2185 * cases.
2186 */
2187 virtual RWLockHandle *childrenLock() { return lockHandle(); }
2188
2189 /**
2190 * Adds the given child to the list of dependent children.
2191 *
2192 * Usually gets called from the child's init() method.
2193 *
2194 * @note @a aChild (unless it is in InInit state) must be protected by
2195 * VirtualBoxBase::AutoCaller to make sure it is not uninitialized on
2196 * another thread during this method's call.
2197 *
2198 * @note When #childrenLock() is not overloaded (returns the general object
2199 * lock) and this method is called from under the child's read or
2200 * write lock, make sure the {parent, child} locking order is
2201 * preserved by locking the callee (this object) for writing before
2202 * the child's lock.
2203 *
2204 * @param aChild Child object to add.
2205 *
2206 * @note Locks #childrenLock() for writing.
2207 */
2208 void addDependentChild (C *aChild)
2209 {
2210 AssertReturnVoid (aChild != NULL);
2211
2212 AutoCaller autoCaller (this);
2213
2214 /* sanity */
2215 AssertReturnVoid (autoCaller.state() == InInit ||
2216 autoCaller.state() == Ready ||
2217 autoCaller.state() == Limited);
2218
2219 AutoWriteLock chLock (childrenLock());
2220 mDependentChildren.push_back (aChild);
2221 }
2222
2223 /**
2224 * Removes the given child from the list of dependent children.
2225 *
2226 * Usually gets called from the child's uninit() method.
2227 *
2228 * Keep in mind that the called (parent) object may be no longer available
2229 * (i.e. may be deleted deleted) after this method returns, so you must not
2230 * call any other parent's methods after that!
2231 *
2232 * @note @a aChild (unless it is in InUninit state) must be protected by
2233 * VirtualBoxBase::AutoCaller to make sure it is not uninitialized on
2234 * another thread during this method's call.
2235 *
2236 * @note When #childrenLock() is not overloaded (returns the general object
2237 * lock) and this method is called from under the child's read or
2238 * write lock, make sure the {parent, child} locking order is
2239 * preserved by locking the callee (this object) for writing before
2240 * the child's lock. This is irrelevant when the method is called from
2241 * under this object's AutoUninitSpan (i.e. in InUninit state) since
2242 * in this case no locking is done.
2243 *
2244 * @param aChild Child object to remove.
2245 *
2246 * @note Locks #childrenLock() for writing.
2247 */
2248 void removeDependentChild (C *aChild)
2249 {
2250 AssertReturnVoid (aChild);
2251
2252 AutoCaller autoCaller (this);
2253
2254 /* sanity */
2255 AssertReturnVoid (autoCaller.state() == InUninit ||
2256 autoCaller.state() == InInit ||
2257 autoCaller.state() == Ready ||
2258 autoCaller.state() == Limited);
2259
2260 /* return shortly; we are strongly referenced so the object won't get
2261 * deleted if it calls init() before uninitDependentChildren() does
2262 * and therefore the list will still contain a valid reference that will
2263 * be correctly processed by uninitDependentChildren() anyway */
2264 if (autoCaller.state() == InUninit)
2265 return;
2266
2267 AutoWriteLock chLock (childrenLock());
2268 mDependentChildren.remove (aChild);
2269 }
2270
2271protected:
2272
2273 /**
2274 * Returns the read-only list of all dependent children.
2275 *
2276 * @note Access the returned list (iterate, get size etc.) only after making
2277 * sure #childrenLock() is locked for reading or for writing!
2278 */
2279 const DependentChildren &dependentChildren() const { return mDependentChildren; }
2280
2281 /**
2282 * Uninitializes all dependent children registered on this object with
2283 * #addDependentChild().
2284 *
2285 * Must be called from within the VirtualBoxBaseProto::AutoUninitSpan (i.e.
2286 * typically from this object's uninit() method) to uninitialize children
2287 * before this object goes out of service and becomes unusable.
2288 *
2289 * Note that this method will call uninit() methods of child objects. If
2290 * these methods need to call the parent object during uninitialization,
2291 * #uninitDependentChildren() must be called before the relevant part of the
2292 * parent is uninitialized: usually at the beginning of the parent
2293 * uninitialization sequence.
2294 *
2295 * @note May lock something through the called children.
2296 */
2297 void uninitDependentChildren()
2298 {
2299 AutoCaller autoCaller (this);
2300
2301 /* We don't want to hold the childrenLock() write lock here (necessary
2302 * to protect mDependentChildren) when uninitializing children because
2303 * we want to avoid a possible deadlock where we could get stuck in
2304 * child->uninit() blocked by AutoUninitSpan waiting for the number of
2305 * child's callers to drop to zero (or for another AutoUninitSpan to
2306 * finish), while some other thread is stuck in our
2307 * removeDependentChild() method called for that child and waiting for
2308 * the childrenLock()'s write lock.
2309 *
2310 * The only safe place to not lock and keep accessing our data members
2311 * is the InUninit state (no active call to our object may exist on
2312 * another thread when we are in InUinint, provided that all such calls
2313 * use the AutoCaller class of course). InUinint is also used as a flag
2314 * by removeDependentChild() that prevents touching mDependentChildren
2315 * from outside. Therefore, we assert. Note that InInit is also fine
2316 * since no any object may access us by that time.
2317 */
2318 AssertReturnVoid (autoCaller.state() == InUninit ||
2319 autoCaller.state() == InInit);
2320
2321 if (mDependentChildren.size())
2322 {
2323 for (typename DependentChildren::iterator it = mDependentChildren.begin();
2324 it != mDependentChildren.end(); ++ it)
2325 {
2326 C *child = (*it);
2327 Assert (child);
2328
2329 /* Note that if child->uninit() happens to be called on another
2330 * thread right before us and is not yet finished, the second
2331 * uninit() call will wait until the first one has done so
2332 * (thanks to AutoUninitSpan). */
2333 if (child)
2334 child->uninit();
2335 }
2336
2337 /* release all strong references we hold */
2338 mDependentChildren.clear();
2339 }
2340 }
2341
2342 /**
2343 * Removes (detaches) all dependent children registered with
2344 * #addDependentChild(), without uninitializing them.
2345 *
2346 * @note @a |this| (unless it is in InUninit state) must be protected by
2347 * VirtualBoxBase::AutoCaller to make sure it is not uninitialized on
2348 * another thread during this method's call.
2349 *
2350 * @note Locks #childrenLock() for writing.
2351 */
2352 void removeDependentChildren()
2353 {
2354 AutoWriteLock chLock (childrenLock());
2355 mDependentChildren.clear();
2356 }
2357
2358private:
2359
2360 DependentChildren mDependentChildren;
2361};
2362
2363////////////////////////////////////////////////////////////////////////////////
2364
2365/// @todo (dmik) remove after we switch to VirtualBoxBaseNEXT completely
2366/**
2367 * Simple template that manages data structure allocation/deallocation
2368 * and supports data pointer sharing (the instance that shares the pointer is
2369 * not responsible for memory deallocation as opposed to the instance that
2370 * owns it).
2371 */
2372template <class D>
2373class Shareable
2374{
2375public:
2376
2377 Shareable() : mData (NULL), mIsShared (FALSE) {}
2378 ~Shareable() { free(); }
2379
2380 void allocate() { attach (new D); }
2381
2382 virtual void free() {
2383 if (mData) {
2384 if (!mIsShared)
2385 delete mData;
2386 mData = NULL;
2387 mIsShared = false;
2388 }
2389 }
2390
2391 void attach (D *data) {
2392 AssertMsg (data, ("new data must not be NULL"));
2393 if (data && mData != data) {
2394 if (mData && !mIsShared)
2395 delete mData;
2396 mData = data;
2397 mIsShared = false;
2398 }
2399 }
2400
2401 void attach (Shareable &data) {
2402 AssertMsg (
2403 data.mData == mData || !data.mIsShared,
2404 ("new data must not be shared")
2405 );
2406 if (this != &data && !data.mIsShared) {
2407 attach (data.mData);
2408 data.mIsShared = true;
2409 }
2410 }
2411
2412 void share (D *data) {
2413 AssertMsg (data, ("new data must not be NULL"));
2414 if (mData != data) {
2415 if (mData && !mIsShared)
2416 delete mData;
2417 mData = data;
2418 mIsShared = true;
2419 }
2420 }
2421
2422 void share (const Shareable &data) { share (data.mData); }
2423
2424 void attachCopy (const D *data) {
2425 AssertMsg (data, ("data to copy must not be NULL"));
2426 if (data)
2427 attach (new D (*data));
2428 }
2429
2430 void attachCopy (const Shareable &data) {
2431 attachCopy (data.mData);
2432 }
2433
2434 virtual D *detach() {
2435 D *d = mData;
2436 mData = NULL;
2437 mIsShared = false;
2438 return d;
2439 }
2440
2441 D *data() const {
2442 return mData;
2443 }
2444
2445 D *operator->() const {
2446 AssertMsg (mData, ("data must not be NULL"));
2447 return mData;
2448 }
2449
2450 bool isNull() const { return mData == NULL; }
2451 bool operator!() const { return isNull(); }
2452
2453 bool isShared() const { return mIsShared; }
2454
2455protected:
2456
2457 D *mData;
2458 bool mIsShared;
2459};
2460
2461/// @todo (dmik) remove after we switch to VirtualBoxBaseNEXT completely
2462/**
2463 * Simple template that enhances Shareable<> and supports data
2464 * backup/rollback/commit (using the copy constructor of the managed data
2465 * structure).
2466 */
2467template <class D>
2468class Backupable : public Shareable <D>
2469{
2470public:
2471
2472 Backupable() : Shareable <D> (), mBackupData (NULL) {}
2473
2474 void free()
2475 {
2476 AssertMsg (this->mData || !mBackupData, ("backup must be NULL if data is NULL"));
2477 rollback();
2478 Shareable <D>::free();
2479 }
2480
2481 D *detach()
2482 {
2483 AssertMsg (this->mData || !mBackupData, ("backup must be NULL if data is NULL"));
2484 rollback();
2485 return Shareable <D>::detach();
2486 }
2487
2488 void share (const Backupable &data)
2489 {
2490 AssertMsg (!data.isBackedUp(), ("data to share must not be backed up"));
2491 if (!data.isBackedUp())
2492 Shareable <D>::share (data.mData);
2493 }
2494
2495 /**
2496 * Stores the current data pointer in the backup area, allocates new data
2497 * using the copy constructor on current data and makes new data active.
2498 */
2499 void backup()
2500 {
2501 AssertMsg (this->mData, ("data must not be NULL"));
2502 if (this->mData && !mBackupData)
2503 {
2504 mBackupData = this->mData;
2505 this->mData = new D (*mBackupData);
2506 }
2507 }
2508
2509 /**
2510 * Deletes new data created by #backup() and restores previous data pointer
2511 * stored in the backup area, making it active again.
2512 */
2513 void rollback()
2514 {
2515 if (this->mData && mBackupData)
2516 {
2517 delete this->mData;
2518 this->mData = mBackupData;
2519 mBackupData = NULL;
2520 }
2521 }
2522
2523 /**
2524 * Commits current changes by deleting backed up data and clearing up the
2525 * backup area. The new data pointer created by #backup() remains active
2526 * and becomes the only managed pointer.
2527 *
2528 * This method is much faster than #commitCopy() (just a single pointer
2529 * assignment operation), but makes the previous data pointer invalid
2530 * (because it is freed). For this reason, this method must not be
2531 * used if it's possible that data managed by this instance is shared with
2532 * some other Shareable instance. See #commitCopy().
2533 */
2534 void commit()
2535 {
2536 if (this->mData && mBackupData)
2537 {
2538 if (!this->mIsShared)
2539 delete mBackupData;
2540 mBackupData = NULL;
2541 this->mIsShared = false;
2542 }
2543 }
2544
2545 /**
2546 * Commits current changes by assigning new data to the previous data
2547 * pointer stored in the backup area using the assignment operator.
2548 * New data is deleted, the backup area is cleared and the previous data
2549 * pointer becomes active and the only managed pointer.
2550 *
2551 * This method is slower than #commit(), but it keeps the previous data
2552 * pointer valid (i.e. new data is copied to the same memory location).
2553 * For that reason it's safe to use this method on instances that share
2554 * managed data with other Shareable instances.
2555 */
2556 void commitCopy()
2557 {
2558 if (this->mData && mBackupData)
2559 {
2560 *mBackupData = *(this->mData);
2561 delete this->mData;
2562 this->mData = mBackupData;
2563 mBackupData = NULL;
2564 }
2565 }
2566
2567 void assignCopy (const D *data)
2568 {
2569 AssertMsg (this->mData, ("data must not be NULL"));
2570 AssertMsg (data, ("data to copy must not be NULL"));
2571 if (this->mData && data)
2572 {
2573 if (!mBackupData)
2574 {
2575 mBackupData = this->mData;
2576 this->mData = new D (*data);
2577 }
2578 else
2579 *this->mData = *data;
2580 }
2581 }
2582
2583 void assignCopy (const Backupable &data)
2584 {
2585 assignCopy (data.mData);
2586 }
2587
2588 bool isBackedUp() const
2589 {
2590 return mBackupData != NULL;
2591 }
2592
2593 bool hasActualChanges() const
2594 {
2595 AssertMsg (this->mData, ("data must not be NULL"));
2596 return this->mData != NULL && mBackupData != NULL &&
2597 !(*this->mData == *mBackupData);
2598 }
2599
2600 D *backedUpData() const
2601 {
2602 return mBackupData;
2603 }
2604
2605protected:
2606
2607 D *mBackupData;
2608};
2609
2610#endif // ____H_VIRTUALBOXBASEIMPL
2611/* 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