VirtualBox

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

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

Main: Bstr makeover (third attempt) -- make Bstr(NULL) and Bstr() behave the same; resulting cleanup; make some more internal methods use Utf8Str instead of Bstr; fix a lot of CheckComArgNotNull??() usage

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 62.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/thread.h>
27
28#include <list>
29#include <map>
30
31#include "VBox/com/ErrorInfo.h"
32#include "VBox/com/SupportErrorInfo.h"
33#include "VBox/com/AutoLock.h"
34
35#include "VBox/com/VirtualBox.h"
36
37// avoid including VBox/settings.h and VBox/xml.h;
38// only declare the classes
39namespace xml
40{
41class File;
42}
43
44using namespace com;
45using namespace util;
46
47class AutoInitSpan;
48class AutoUninitSpan;
49
50class VirtualBox;
51class Machine;
52class Medium;
53class Host;
54typedef std::list< ComObjPtr<Medium> > MediaList;
55
56////////////////////////////////////////////////////////////////////////////////
57//
58// COM helpers
59//
60////////////////////////////////////////////////////////////////////////////////
61
62#if !defined (VBOX_WITH_XPCOM)
63
64#include <atlcom.h>
65
66/* use a special version of the singleton class factory,
67 * see KB811591 in msdn for more info. */
68
69#undef DECLARE_CLASSFACTORY_SINGLETON
70#define DECLARE_CLASSFACTORY_SINGLETON(obj) DECLARE_CLASSFACTORY_EX(CMyComClassFactorySingleton<obj>)
71
72template <class T>
73class CMyComClassFactorySingleton : public CComClassFactory
74{
75public:
76 CMyComClassFactorySingleton() : m_hrCreate(S_OK){}
77 virtual ~CMyComClassFactorySingleton(){}
78 // IClassFactory
79 STDMETHOD(CreateInstance)(LPUNKNOWN pUnkOuter, REFIID riid, void** ppvObj)
80 {
81 HRESULT hRes = E_POINTER;
82 if (ppvObj != NULL)
83 {
84 *ppvObj = NULL;
85 // Aggregation is not supported in singleton objects.
86 ATLASSERT(pUnkOuter == NULL);
87 if (pUnkOuter != NULL)
88 hRes = CLASS_E_NOAGGREGATION;
89 else
90 {
91 if (m_hrCreate == S_OK && m_spObj == NULL)
92 {
93 Lock();
94 __try
95 {
96 // Fix: The following If statement was moved inside the __try statement.
97 // Did another thread arrive here first?
98 if (m_hrCreate == S_OK && m_spObj == NULL)
99 {
100 // lock the module to indicate activity
101 // (necessary for the monitor shutdown thread to correctly
102 // terminate the module in case when CreateInstance() fails)
103 _pAtlModule->Lock();
104 CComObjectCached<T> *p;
105 m_hrCreate = CComObjectCached<T>::CreateInstance(&p);
106 if (SUCCEEDED(m_hrCreate))
107 {
108 m_hrCreate = p->QueryInterface(IID_IUnknown, (void**)&m_spObj);
109 if (FAILED(m_hrCreate))
110 {
111 delete p;
112 }
113 }
114 _pAtlModule->Unlock();
115 }
116 }
117 __finally
118 {
119 Unlock();
120 }
121 }
122 if (m_hrCreate == S_OK)
123 {
124 hRes = m_spObj->QueryInterface(riid, ppvObj);
125 }
126 else
127 {
128 hRes = m_hrCreate;
129 }
130 }
131 }
132 return hRes;
133 }
134 HRESULT m_hrCreate;
135 CComPtr<IUnknown> m_spObj;
136};
137
138#endif /* !defined (VBOX_WITH_XPCOM) */
139
140////////////////////////////////////////////////////////////////////////////////
141//
142// Macros
143//
144////////////////////////////////////////////////////////////////////////////////
145
146/**
147 * Special version of the Assert macro to be used within VirtualBoxBase
148 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
149 *
150 * In the debug build, this macro is equivalent to Assert.
151 * In the release build, this macro uses |setError(E_FAIL, ...)| to set the
152 * error info from the asserted expression.
153 *
154 * @see VirtualBoxSupportErrorInfoImpl::setError
155 *
156 * @param expr Expression which should be true.
157 */
158#if defined (DEBUG)
159#define ComAssert(expr) Assert(expr)
160#else
161#define ComAssert(expr) \
162 do { \
163 if (RT_UNLIKELY(!(expr))) \
164 setError(E_FAIL, "Assertion failed: [%s] at '%s' (%d) in %s.\n" \
165 "Please contact the product vendor!", \
166 #expr, __FILE__, __LINE__, __PRETTY_FUNCTION__); \
167 } while (0)
168#endif
169
170/**
171 * Special version of the AssertMsg macro to be used within VirtualBoxBase
172 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
173 *
174 * See ComAssert for more info.
175 *
176 * @param expr Expression which should be true.
177 * @param a printf argument list (in parenthesis).
178 */
179#if defined (DEBUG)
180#define ComAssertMsg(expr, a) AssertMsg(expr, a)
181#else
182#define ComAssertMsg(expr, a) \
183 do { \
184 if (RT_UNLIKELY(!(expr))) \
185 setError(E_FAIL, "Assertion failed: [%s] at '%s' (%d) in %s.\n" \
186 "%s.\n" \
187 "Please contact the product vendor!", \
188 #expr, __FILE__, __LINE__, __PRETTY_FUNCTION__, Utf8StrFmt a .raw()); \
189 } while (0)
190#endif
191
192/**
193 * Special version of the AssertRC macro to be used within VirtualBoxBase
194 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
195 *
196 * See ComAssert for more info.
197 *
198 * @param vrc VBox status code.
199 */
200#if defined (DEBUG)
201#define ComAssertRC(vrc) AssertRC(vrc)
202#else
203#define ComAssertRC(vrc) ComAssertMsgRC(vrc, ("%Rra", vrc))
204#endif
205
206/**
207 * Special version of the AssertMsgRC macro to be used within VirtualBoxBase
208 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
209 *
210 * See ComAssert for more info.
211 *
212 * @param vrc VBox status code.
213 * @param msg printf argument list (in parenthesis).
214 */
215#if defined (DEBUG)
216#define ComAssertMsgRC(vrc, msg) AssertMsgRC(vrc, msg)
217#else
218#define ComAssertMsgRC(vrc, msg) ComAssertMsg(RT_SUCCESS(vrc), msg)
219#endif
220
221/**
222 * Special version of the AssertComRC macro to be used within VirtualBoxBase
223 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
224 *
225 * See ComAssert for more info.
226 *
227 * @param rc COM result code
228 */
229#if defined (DEBUG)
230#define ComAssertComRC(rc) AssertComRC(rc)
231#else
232#define ComAssertComRC(rc) ComAssertMsg(SUCCEEDED(rc), ("COM RC = %Rhrc (0x%08X)", (rc), (rc)))
233#endif
234
235
236/** Special version of ComAssert that returns ret if expr fails */
237#define ComAssertRet(expr, ret) \
238 do { ComAssert(expr); if (!(expr)) return (ret); } while (0)
239/** Special version of ComAssertMsg that returns ret if expr fails */
240#define ComAssertMsgRet(expr, a, ret) \
241 do { ComAssertMsg(expr, a); if (!(expr)) return (ret); } while (0)
242/** Special version of ComAssertRC that returns ret if vrc does not succeed */
243#define ComAssertRCRet(vrc, ret) \
244 do { ComAssertRC(vrc); if (!RT_SUCCESS(vrc)) return (ret); } while (0)
245/** Special version of ComAssertMsgRC that returns ret if vrc does not succeed */
246#define ComAssertMsgRCRet(vrc, msg, ret) \
247 do { ComAssertMsgRC(vrc, msg); if (!RT_SUCCESS(vrc)) return (ret); } while (0)
248/** Special version of ComAssertFailed that returns ret */
249#define ComAssertFailedRet(ret) \
250 do { ComAssertFailed(); return (ret); } while (0)
251/** Special version of ComAssertMsgFailed that returns ret */
252#define ComAssertMsgFailedRet(msg, ret) \
253 do { ComAssertMsgFailed(msg); return (ret); } while (0)
254/** Special version of ComAssertComRC that returns ret if rc does not succeed */
255#define ComAssertComRCRet(rc, ret) \
256 do { ComAssertComRC(rc); if (!SUCCEEDED(rc)) return (ret); } while (0)
257/** Special version of ComAssertComRC that returns rc if rc does not succeed */
258#define ComAssertComRCRetRC(rc) \
259 do { ComAssertComRC(rc); if (!SUCCEEDED(rc)) return (rc); } while (0)
260
261
262/** Special version of ComAssert that evaluates eval and breaks if expr fails */
263#define ComAssertBreak(expr, eval) \
264 if (1) { ComAssert(expr); if (!(expr)) { eval; break; } } else do {} while (0)
265/** Special version of ComAssertMsg that evaluates eval and breaks if expr fails */
266#define ComAssertMsgBreak(expr, a, eval) \
267 if (1) { ComAssertMsg(expr, a); if (!(expr)) { eval; break; } } else do {} while (0)
268/** Special version of ComAssertRC that evaluates eval and breaks if vrc does not succeed */
269#define ComAssertRCBreak(vrc, eval) \
270 if (1) { ComAssertRC(vrc); if (!RT_SUCCESS(vrc)) { eval; break; } } else do {} while (0)
271/** Special version of ComAssertMsgRC that evaluates eval and breaks if vrc does not succeed */
272#define ComAssertMsgRCBreak(vrc, msg, eval) \
273 if (1) { ComAssertMsgRC(vrc, msg); if (!RT_SUCCESS(vrc)) { eval; break; } } else do {} while (0)
274/** Special version of ComAssertFailed that evaluates eval and breaks */
275#define ComAssertFailedBreak(eval) \
276 if (1) { ComAssertFailed(); { eval; break; } } else do {} while (0)
277/** Special version of ComAssertMsgFailed that evaluates eval and breaks */
278#define ComAssertMsgFailedBreak(msg, eval) \
279 if (1) { ComAssertMsgFailed (msg); { eval; break; } } else do {} while (0)
280/** Special version of ComAssertComRC that evaluates eval and breaks if rc does not succeed */
281#define ComAssertComRCBreak(rc, eval) \
282 if (1) { ComAssertComRC(rc); if (!SUCCEEDED(rc)) { eval; break; } } else do {} while (0)
283/** Special version of ComAssertComRC that just breaks if rc does not succeed */
284#define ComAssertComRCBreakRC(rc) \
285 if (1) { ComAssertComRC(rc); if (!SUCCEEDED(rc)) { break; } } else do {} while (0)
286
287
288/** Special version of ComAssert that evaluates eval and throws it if expr fails */
289#define ComAssertThrow(expr, eval) \
290 if (1) { ComAssert(expr); if (!(expr)) { throw (eval); } } else do {} while (0)
291/** Special version of ComAssertMsg that evaluates eval and throws it if expr fails */
292#define ComAssertMsgThrow(expr, a, eval) \
293 if (1) { ComAssertMsg(expr, a); if (!(expr)) { throw (eval); } } else do {} while (0)
294/** Special version of ComAssertRC that evaluates eval and throws it if vrc does not succeed */
295#define ComAssertRCThrow(vrc, eval) \
296 if (1) { ComAssertRC(vrc); if (!RT_SUCCESS(vrc)) { throw (eval); } } else do {} while (0)
297/** Special version of ComAssertMsgRC that evaluates eval and throws it if vrc does not succeed */
298#define ComAssertMsgRCThrow(vrc, msg, eval) \
299 if (1) { ComAssertMsgRC(vrc, msg); if (!RT_SUCCESS(vrc)) { throw (eval); } } else do {} while (0)
300/** Special version of ComAssertFailed that evaluates eval and throws it */
301#define ComAssertFailedThrow(eval) \
302 if (1) { ComAssertFailed(); { throw (eval); } } else do {} while (0)
303/** Special version of ComAssertMsgFailed that evaluates eval and throws it */
304#define ComAssertMsgFailedThrow(msg, eval) \
305 if (1) { ComAssertMsgFailed (msg); { throw (eval); } } else do {} while (0)
306/** Special version of ComAssertComRC that evaluates eval and throws it if rc does not succeed */
307#define ComAssertComRCThrow(rc, eval) \
308 if (1) { ComAssertComRC(rc); if (!SUCCEEDED(rc)) { throw (eval); } } else do {} while (0)
309/** Special version of ComAssertComRC that just throws rc if rc does not succeed */
310#define ComAssertComRCThrowRC(rc) \
311 if (1) { ComAssertComRC(rc); if (!SUCCEEDED(rc)) { throw rc; } } else do {} while (0)
312
313////////////////////////////////////////////////////////////////////////////////
314
315/**
316 * Checks that the pointer argument is not NULL and returns E_INVALIDARG +
317 * extended error info on failure.
318 * @param arg Input pointer-type argument (strings, interface pointers...)
319 */
320#define CheckComArgNotNull(arg) \
321 do { \
322 if (RT_UNLIKELY((arg) == NULL)) \
323 return setError(E_INVALIDARG, tr("Argument %s is NULL"), #arg); \
324 } while (0)
325
326/**
327 * Checks that safe array argument is not NULL and returns E_INVALIDARG +
328 * extended error info on failure.
329 * @param arg Input safe array argument (strings, interface pointers...)
330 */
331#define CheckComArgSafeArrayNotNull(arg) \
332 do { \
333 if (RT_UNLIKELY(ComSafeArrayInIsNull(arg))) \
334 return setError(E_INVALIDARG, tr("Argument %s is NULL"), #arg); \
335 } while (0)
336
337/**
338 * Checks that the string argument is not a NULL or empty string and returns
339 * E_INVALIDARG + extended error info on failure.
340 * @param arg Input string argument (BSTR etc.).
341 */
342#define CheckComArgStrNotEmptyOrNull(arg) \
343 do { \
344 if (RT_UNLIKELY((arg) == NULL || *(arg) == '\0')) \
345 return setError(E_INVALIDARG, \
346 tr("Argument %s is empty or NULL"), #arg); \
347 } while (0)
348
349/**
350 * Checks that the given expression (that must involve the argument) is true and
351 * returns E_INVALIDARG + extended error info on failure.
352 * @param arg Argument.
353 * @param expr Expression to evaluate.
354 */
355#define CheckComArgExpr(arg, expr) \
356 do { \
357 if (RT_UNLIKELY(!(expr))) \
358 return setError(E_INVALIDARG, \
359 tr("Argument %s is invalid (must be %s)"), #arg, #expr); \
360 } while (0)
361
362/**
363 * Checks that the given expression (that must involve the argument) is true and
364 * returns E_INVALIDARG + extended error info on failure. The error message must
365 * be customized.
366 * @param arg Argument.
367 * @param expr Expression to evaluate.
368 * @param msg Parenthesized printf-like expression (must start with a verb,
369 * like "must be one of...", "is not within...").
370 */
371#define CheckComArgExprMsg(arg, expr, msg) \
372 do { \
373 if (RT_UNLIKELY(!(expr))) \
374 return setError(E_INVALIDARG, tr ("Argument %s %s"), \
375 #arg, Utf8StrFmt msg .raw()); \
376 } while (0)
377
378/**
379 * Checks that the given pointer to an output argument is valid and returns
380 * E_POINTER + extended error info otherwise.
381 * @param arg Pointer argument.
382 */
383#define CheckComArgOutPointerValid(arg) \
384 do { \
385 if (RT_UNLIKELY(!VALID_PTR(arg))) \
386 return setError(E_POINTER, \
387 tr("Output argument %s points to invalid memory location (%p)"), \
388 #arg, (void *) (arg)); \
389 } while (0)
390
391/**
392 * Checks that the given pointer to an output safe array argument is valid and
393 * returns E_POINTER + extended error info otherwise.
394 * @param arg Safe array argument.
395 */
396#define CheckComArgOutSafeArrayPointerValid(arg) \
397 do { \
398 if (RT_UNLIKELY(ComSafeArrayOutIsNull(arg))) \
399 return setError(E_POINTER, \
400 tr("Output argument %s points to invalid memory location (%p)"), \
401 #arg, (void *) (arg)); \
402 } while (0)
403
404/**
405 * Sets the extended error info and returns E_NOTIMPL.
406 */
407#define ReturnComNotImplemented() \
408 do { \
409 return setError(E_NOTIMPL, tr("Method %s is not implemented"), __FUNCTION__); \
410 } while (0)
411
412/**
413 * Declares an empty constructor and destructor for the given class.
414 * This is useful to prevent the compiler from generating the default
415 * ctor and dtor, which in turn allows to use forward class statements
416 * (instead of including their header files) when declaring data members of
417 * non-fundamental types with constructors (which are always called implicitly
418 * by constructors and by the destructor of the class).
419 *
420 * This macro is to be placed within (the public section of) the class
421 * declaration. Its counterpart, DEFINE_EMPTY_CTOR_DTOR, must be placed
422 * somewhere in one of the translation units (usually .cpp source files).
423 *
424 * @param cls class to declare a ctor and dtor for
425 */
426#define DECLARE_EMPTY_CTOR_DTOR(cls) cls(); ~cls();
427
428/**
429 * Defines an empty constructor and destructor for the given class.
430 * See DECLARE_EMPTY_CTOR_DTOR for more info.
431 */
432#define DEFINE_EMPTY_CTOR_DTOR(cls) \
433 cls::cls () {}; cls::~cls () {};
434
435////////////////////////////////////////////////////////////////////////////////
436//
437// VirtualBoxBase
438//
439////////////////////////////////////////////////////////////////////////////////
440
441/**
442 * This enum is used in the virtual method VirtualBoxBasePro::getClassID() to
443 * allow VirtualBox classes to identify themselves. Subclasses can override
444 * that method and return a value from this enum if run-time identification is
445 * needed anywhere.
446 */
447enum VBoxClsID
448{
449 clsidVirtualBox,
450 clsidHost,
451 clsidMachine,
452 clsidSessionMachine,
453 clsidSnapshotMachine,
454 clsidSnapshot,
455 clsidOther
456};
457
458/**
459 * Abstract base class for all component classes implementing COM
460 * interfaces of the VirtualBox COM library.
461 *
462 * Declares functionality that should be available in all components.
463 *
464 * Note that this class is always subclassed using the virtual keyword so
465 * that only one instance of its VTBL and data is present in each derived class
466 * even in case if VirtualBoxBaseProto appears more than once among base classes
467 * of the particular component as a result of multiple inheritance.
468 *
469 * This makes it possible to have intermediate base classes used by several
470 * components that implement some common interface functionality but still let
471 * the final component classes choose what VirtualBoxBase variant it wants to
472 * use.
473 *
474 * Among the basic functionality implemented by this class is the primary object
475 * state that indicates if the object is ready to serve the calls, and if not,
476 * what stage it is currently at. Here is the primary state diagram:
477 *
478 * +-------------------------------------------------------+
479 * | |
480 * | (InitFailed) -----------------------+ |
481 * | ^ | |
482 * v | v |
483 * [*] ---> NotReady ----> (InInit) -----> Ready -----> (InUninit) ----+
484 * ^ | ^ | ^
485 * | v | v |
486 * | Limited | (MayUninit) --> (WillUninit)
487 * | | | |
488 * +-------+ +-------+
489 *
490 * The object is fully operational only when its state is Ready. The Limited
491 * state means that only some vital part of the object is operational, and it
492 * requires some sort of reinitialization to become fully operational. The
493 * NotReady state means the object is basically dead: it either was not yet
494 * initialized after creation at all, or was uninitialized and is waiting to be
495 * destroyed when the last reference to it is released. All other states are
496 * transitional.
497 *
498 * The NotReady->InInit->Ready, NotReady->InInit->Limited and
499 * NotReady->InInit->InitFailed transition is done by the AutoInitSpan smart
500 * class.
501 *
502 * The Limited->InInit->Ready, Limited->InInit->Limited and
503 * Limited->InInit->InitFailed transition is done by the AutoReinitSpan smart
504 * class.
505 *
506 * The Ready->InUninit->NotReady, InitFailed->InUninit->NotReady and
507 * WillUninit->InUninit->NotReady transitions are done by the AutoUninitSpan
508 * smart class.
509 *
510 * The Ready->MayUninit->Ready and Ready->MayUninit->WillUninit transitions are
511 * done by the AutoMayUninitSpan smart class.
512 *
513 * In order to maintain the primary state integrity and declared functionality
514 * all subclasses must:
515 *
516 * 1) Use the above Auto*Span classes to perform state transitions. See the
517 * individual class descriptions for details.
518 *
519 * 2) All public methods of subclasses (i.e. all methods that can be called
520 * directly, not only from within other methods of the subclass) must have a
521 * standard prolog as described in the AutoCaller and AutoLimitedCaller
522 * documentation. Alternatively, they must use addCaller()/releaseCaller()
523 * directly (and therefore have both the prolog and the epilog), but this is
524 * not recommended.
525 */
526class ATL_NO_VTABLE VirtualBoxBase
527 : public Lockable,
528 public CComObjectRootEx<CComMultiThreadModel>
529{
530public:
531 enum State { NotReady, Ready, InInit, InUninit, InitFailed, Limited,
532 MayUninit, WillUninit };
533
534 VirtualBoxBase();
535 virtual ~VirtualBoxBase();
536
537 static const char *translate(const char *context, const char *sourceText,
538 const char *comment = 0);
539
540public:
541
542 /**
543 * Unintialization method.
544 *
545 * Must be called by all final implementations (component classes) when the
546 * last reference to the object is released, before calling the destructor.
547 *
548 * This method is also automatically called by the uninit() method of this
549 * object's parent if this object is a dependent child of a class derived
550 * from VirtualBoxBaseWithChildren (see
551 * VirtualBoxBaseWithChildren::addDependentChild).
552 *
553 * @note Never call this method the AutoCaller scope or after the
554 * #addCaller() call not paired by #releaseCaller() because it is a
555 * guaranteed deadlock. See AutoUninitSpan for details.
556 */
557 virtual void uninit() {}
558
559 virtual HRESULT addCaller(State *aState = NULL, bool aLimited = false);
560 virtual void releaseCaller();
561
562 /**
563 * Adds a limited caller. This method is equivalent to doing
564 * <tt>addCaller (aState, true)</tt>, but it is preferred because provides
565 * better self-descriptiveness. See #addCaller() for more info.
566 */
567 HRESULT addLimitedCaller(State *aState = NULL)
568 {
569 return addCaller(aState, true /* aLimited */);
570 }
571
572 /**
573 * Simple run-time type identification without having to enable C++ RTTI.
574 * The class IDs are defined in VirtualBoxBase.h.
575 * @return
576 */
577 virtual VBoxClsID getClassID() const
578 {
579 return clsidOther;
580 }
581
582 /**
583 * Override of the default locking class to be used for validating lock
584 * order with the standard member lock handle.
585 */
586 virtual VBoxLockingClass getLockingClass() const
587 {
588 return LOCKCLASS_OTHEROBJECT;
589 }
590
591 virtual RWLockHandle *lockHandle() const;
592
593 /**
594 * Returns a lock handle used to protect the primary state fields (used by
595 * #addCaller(), AutoInitSpan, AutoUninitSpan, etc.). Only intended to be
596 * used for similar purposes in subclasses. WARNING: NO any other locks may
597 * be requested while holding this lock!
598 */
599 WriteLockHandle *stateLockHandle() { return &mStateLock; }
600
601private:
602
603 void setState(State aState)
604 {
605 Assert(mState != aState);
606 mState = aState;
607 mStateChangeThread = RTThreadSelf();
608 }
609
610 /** Primary state of this object */
611 State mState;
612 /** Thread that caused the last state change */
613 RTTHREAD mStateChangeThread;
614 /** Total number of active calls to this object */
615 unsigned mCallers;
616 /** Posted when the number of callers drops to zero */
617 RTSEMEVENT mZeroCallersSem;
618 /** Posted when the object goes from InInit/InUninit to some other state */
619 RTSEMEVENTMULTI mInitUninitSem;
620 /** Number of threads waiting for mInitUninitDoneSem */
621 unsigned mInitUninitWaiters;
622
623 /** Protects access to state related data members */
624 WriteLockHandle mStateLock;
625
626 /** User-level object lock for subclasses */
627 mutable RWLockHandle *mObjectLock;
628
629 friend class AutoInitSpan;
630 friend class AutoReinitSpan;
631 friend class AutoUninitSpan;
632 friend class AutoMayUninitSpan;
633};
634
635////////////////////////////////////////////////////////////////////////////////
636//
637// VirtualBoxSupportTranslation, VirtualBoxSupportErrorInfoImpl
638//
639////////////////////////////////////////////////////////////////////////////////
640
641/**
642 * This macro adds the error info support to methods of the VirtualBoxBase
643 * class (by overriding them). Place it to the public section of the
644 * VirtualBoxBase subclass and the following methods will set the extended
645 * error info in case of failure instead of just returning the result code:
646 *
647 * <ul>
648 * <li>VirtualBoxBase::addCaller()
649 * </ul>
650 *
651 * @note The given VirtualBoxBase subclass must also inherit from both
652 * VirtualBoxSupportErrorInfoImpl and VirtualBoxSupportTranslation templates!
653 *
654 * @param C VirtualBoxBase subclass to add the error info support to
655 */
656#define VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT(C) \
657 virtual HRESULT addCaller(VirtualBoxBase::State *aState = NULL, \
658 bool aLimited = false) \
659 { \
660 VirtualBoxBase::State protoState; \
661 HRESULT rc = VirtualBoxBase::addCaller(&protoState, aLimited); \
662 if (FAILED(rc)) \
663 { \
664 if (protoState == VirtualBoxBase::Limited) \
665 rc = setError(rc, tr("The object functionality is limited")); \
666 else \
667 rc = setError(rc, tr("The object is not ready")); \
668 } \
669 if (aState) \
670 *aState = protoState; \
671 return rc; \
672 } \
673
674////////////////////////////////////////////////////////////////////////////////
675
676/** Helper for VirtualBoxSupportTranslation. */
677class VirtualBoxSupportTranslationBase
678{
679protected:
680 static bool cutClassNameFrom__PRETTY_FUNCTION__(char *aPrettyFunctionName);
681};
682
683/**
684 * The VirtualBoxSupportTranslation template implements the NLS string
685 * translation support for the given class.
686 *
687 * Translation support is provided by the static #tr() function. This function,
688 * given a string in UTF-8 encoding, looks up for a translation of the given
689 * string by calling the VirtualBoxBase::translate() global function which
690 * receives the name of the enclosing class ("context of translation") as the
691 * additional argument and returns a translated string based on the currently
692 * active language.
693 *
694 * @param C Class that needs to support the string translation.
695 *
696 * @note Every class that wants to use the #tr() function in its own methods
697 * must inherit from this template, regardless of whether its base class
698 * (if any) inherits from it or not. Otherwise, the translation service
699 * will not work correctly. However, the declaration of the derived
700 * class must contain
701 * the <tt>COM_SUPPORTTRANSLATION_OVERRIDE (<ClassName>)</tt> macro if one
702 * of its base classes also inherits from this template (to resolve the
703 * ambiguity of the #tr() function).
704 */
705template<class C>
706class VirtualBoxSupportTranslation : virtual protected VirtualBoxSupportTranslationBase
707{
708public:
709
710 /**
711 * Translates the given text string by calling VirtualBoxBase::translate()
712 * and passing the name of the C class as the first argument ("context of
713 * translation") See VirtualBoxBase::translate() for more info.
714 *
715 * @param aSourceText String to translate.
716 * @param aComment Comment to the string to resolve possible
717 * ambiguities (NULL means no comment).
718 *
719 * @return Translated version of the source string in UTF-8 encoding, or
720 * the source string itself if the translation is not found in the
721 * specified context.
722 */
723 inline static const char *tr(const char *aSourceText,
724 const char *aComment = NULL)
725 {
726 return VirtualBoxBase::translate(className(), aSourceText, aComment);
727 }
728
729protected:
730
731 static const char *className()
732 {
733 static char fn[sizeof(__PRETTY_FUNCTION__) + 1];
734 if (!sClassName)
735 {
736 strcpy(fn, __PRETTY_FUNCTION__);
737 cutClassNameFrom__PRETTY_FUNCTION__(fn);
738 sClassName = fn;
739 }
740 return sClassName;
741 }
742
743private:
744
745 static const char *sClassName;
746};
747
748template<class C>
749const char *VirtualBoxSupportTranslation<C>::sClassName = NULL;
750
751/**
752 * This macro must be invoked inside the public section of the declaration of
753 * the class inherited from the VirtualBoxSupportTranslation template in case
754 * if one of its other base classes also inherits from that template. This is
755 * necessary to resolve the ambiguity of the #tr() function.
756 *
757 * @param C Class that inherits the VirtualBoxSupportTranslation template
758 * more than once (through its other base clases).
759 */
760#define VIRTUALBOXSUPPORTTRANSLATION_OVERRIDE(C) \
761 inline static const char *tr(const char *aSourceText, \
762 const char *aComment = NULL) \
763 { \
764 return VirtualBoxSupportTranslation<C>::tr(aSourceText, aComment); \
765 }
766
767/**
768 * Dummy macro that is used to shut down Qt's lupdate tool warnings in some
769 * situations. This macro needs to be present inside (better at the very
770 * beginning) of the declaration of the class that inherits from
771 * VirtualBoxSupportTranslation template, to make lupdate happy.
772 */
773#define Q_OBJECT
774
775////////////////////////////////////////////////////////////////////////////////
776
777/**
778 * Helper for the VirtualBoxSupportErrorInfoImpl template.
779 */
780/// @todo switch to com::SupportErrorInfo* and remove
781class VirtualBoxSupportErrorInfoImplBase
782{
783 static HRESULT setErrorInternal(HRESULT aResultCode,
784 const GUID &aIID,
785 const wchar_t *aComponent,
786 const Bstr &aText,
787 bool aWarning,
788 bool aLogIt);
789
790protected:
791
792 /**
793 * The MultiResult class is a com::FWResult enhancement that also acts as a
794 * switch to turn on multi-error mode for #setError() or #setWarning()
795 * calls.
796 *
797 * When an instance of this class is created, multi-error mode is turned on
798 * for the current thread and the turn-on counter is increased by one. In
799 * multi-error mode, a call to #setError() or #setWarning() does not
800 * overwrite the current error or warning info object possibly set on the
801 * current thread by other method calls, but instead it stores this old
802 * object in the IVirtualBoxErrorInfo::next attribute of the new error
803 * object being set.
804 *
805 * This way, error/warning objects are stacked together and form a chain of
806 * errors where the most recent error is the first one retrieved by the
807 * calling party, the preceding error is what the
808 * IVirtualBoxErrorInfo::next attribute of the first error points to, and so
809 * on, up to the first error or warning occurred which is the last in the
810 * chain. See IVirtualBoxErrorInfo documentation for more info.
811 *
812 * When the instance of the MultiResult class goes out of scope and gets
813 * destroyed, it automatically decreases the turn-on counter by one. If
814 * the counter drops to zero, multi-error mode for the current thread is
815 * turned off and the thread switches back to single-error mode where every
816 * next error or warning object overwrites the previous one.
817 *
818 * Note that the caller of a COM method uses a non-S_OK result code to
819 * decide if the method has returned an error (negative codes) or a warning
820 * (positive non-zero codes) and will query extended error info only in
821 * these two cases. However, since multi-error mode implies that the method
822 * doesn't return control return to the caller immediately after the first
823 * error or warning but continues its execution, the functionality provided
824 * by the base com::FWResult class becomes very useful because it allows to
825 * preserve the error or the warning result code even if it is later assigned
826 * a S_OK value multiple times. See com::FWResult for details.
827 *
828 * Here is the typical usage pattern:
829 * <code>
830
831 HRESULT Bar::method()
832 {
833 // assume multi-errors are turned off here...
834
835 if (something)
836 {
837 // Turn on multi-error mode and make sure severity is preserved
838 MultiResult rc = foo->method1();
839
840 // return on fatal error, but continue on warning or on success
841 if (FAILED(rc)) return rc;
842
843 rc = foo->method2();
844 // no matter what result, stack it and continue
845
846 // ...
847
848 // return the last worst result code (it will be preserved even if
849 // foo->method2() returns S_OK.
850 return rc;
851 }
852
853 // multi-errors are turned off here again...
854
855 return S_OK;
856 }
857
858 * </code>
859 *
860 *
861 * @note This class is intended to be instantiated on the stack, therefore
862 * You cannot create them using new(). Although it is possible to copy
863 * instances of MultiResult or return them by value, please never do
864 * that as it is breaks the class semantics (and will assert).
865 */
866 class MultiResult : public com::FWResult
867 {
868 public:
869
870 /**
871 * @copydoc com::FWResult::FWResult().
872 */
873 MultiResult(HRESULT aRC = E_FAIL) : FWResult(aRC) { init(); }
874
875 MultiResult(const MultiResult &aThat) : FWResult(aThat)
876 {
877 /* We need this copy constructor only for GCC that wants to have
878 * it in case of expressions like |MultiResult rc = E_FAIL;|. But
879 * we assert since the optimizer should actually avoid the
880 * temporary and call the other constructor directly instead. */
881 AssertFailed();
882 init();
883 }
884
885 ~MultiResult();
886
887 MultiResult &operator=(HRESULT aRC)
888 {
889 com::FWResult::operator=(aRC);
890 return *this;
891 }
892
893 MultiResult &operator=(const MultiResult &aThat)
894 {
895 /* We need this copy constructor only for GCC that wants to have
896 * it in case of expressions like |MultiResult rc = E_FAIL;|. But
897 * we assert since the optimizer should actually avoid the
898 * temporary and call the other constructor directly instead. */
899 AssertFailed();
900 com::FWResult::operator=(aThat);
901 return *this;
902 }
903
904 private:
905
906 DECLARE_CLS_NEW_DELETE_NOOP(MultiResult)
907
908 void init();
909
910 static RTTLS sCounter;
911
912 friend class VirtualBoxSupportErrorInfoImplBase;
913 };
914
915 static HRESULT setError(HRESULT aResultCode,
916 const GUID &aIID,
917 const wchar_t *aComponent,
918 const Bstr &aText,
919 bool aLogIt = true)
920 {
921 return setErrorInternal(aResultCode, aIID, aComponent, aText,
922 false /* aWarning */, aLogIt);
923 }
924
925 static HRESULT setWarning(HRESULT aResultCode,
926 const GUID &aIID,
927 const wchar_t *aComponent,
928 const Bstr &aText)
929 {
930 return setErrorInternal(aResultCode, aIID, aComponent, aText,
931 true /* aWarning */, true /* aLogIt */);
932 }
933
934 static HRESULT setError(HRESULT aResultCode,
935 const GUID &aIID,
936 const wchar_t *aComponent,
937 const char *aText, va_list aArgs, bool aLogIt = true)
938 {
939 return setErrorInternal(aResultCode, aIID, aComponent,
940 Utf8StrFmtVA (aText, aArgs),
941 false /* aWarning */, aLogIt);
942 }
943
944 static HRESULT setWarning(HRESULT aResultCode,
945 const GUID &aIID,
946 const wchar_t *aComponent,
947 const char *aText, va_list aArgs)
948 {
949 return setErrorInternal(aResultCode, aIID, aComponent,
950 Utf8StrFmtVA (aText, aArgs),
951 true /* aWarning */, true /* aLogIt */);
952 }
953};
954
955/**
956 * This template implements ISupportErrorInfo for the given component class
957 * and provides the #setError() method to conveniently set the error information
958 * from within interface methods' implementations.
959 *
960 * On Windows, the template argument must define a COM interface map using
961 * BEGIN_COM_MAP / END_COM_MAP macros and this map must contain a
962 * COM_INTERFACE_ENTRY(ISupportErrorInfo) definition. All interface entries
963 * that follow it will be considered to support IErrorInfo, i.e. the
964 * InterfaceSupportsErrorInfo() implementation will return S_OK for the
965 * corresponding IID.
966 *
967 * On all platforms, the template argument must also define the following
968 * method: |public static const wchar_t *C::getComponentName()|. See
969 * #setError(HRESULT, const char *, ...) for a description on how it is
970 * used.
971 *
972 * @param C
973 * component class that implements one or more COM interfaces
974 * @param I
975 * default interface for the component. This interface's IID is used
976 * by the shortest form of #setError, for convenience.
977 */
978/// @todo switch to com::SupportErrorInfo* and remove
979template<class C, class I>
980class ATL_NO_VTABLE VirtualBoxSupportErrorInfoImpl
981 : protected VirtualBoxSupportErrorInfoImplBase
982#if !defined (VBOX_WITH_XPCOM)
983 , public ISupportErrorInfo
984#else
985#endif
986{
987public:
988
989#if !defined (VBOX_WITH_XPCOM)
990 STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid)
991 {
992 const _ATL_INTMAP_ENTRY* pEntries = C::_GetEntries();
993 Assert(pEntries);
994 if (!pEntries)
995 return S_FALSE;
996
997 BOOL bSupports = FALSE;
998 BOOL bISupportErrorInfoFound = FALSE;
999
1000 while (pEntries->pFunc != NULL && !bSupports)
1001 {
1002 if (!bISupportErrorInfoFound)
1003 {
1004 // skip the com map entries until ISupportErrorInfo is found
1005 bISupportErrorInfoFound =
1006 InlineIsEqualGUID(*(pEntries->piid), IID_ISupportErrorInfo);
1007 }
1008 else
1009 {
1010 // look for the requested interface in the rest of the com map
1011 bSupports = InlineIsEqualGUID(*(pEntries->piid), riid);
1012 }
1013 pEntries++;
1014 }
1015
1016 Assert(bISupportErrorInfoFound);
1017
1018 return bSupports ? S_OK : S_FALSE;
1019 }
1020#endif // !defined (VBOX_WITH_XPCOM)
1021
1022protected:
1023
1024 /**
1025 * Sets the error information for the current thread.
1026 * This information can be retrieved by a caller of an interface method
1027 * using IErrorInfo on Windows or nsIException on Linux, or the cross-platform
1028 * IVirtualBoxErrorInfo interface that provides extended error info (only
1029 * for components from the VirtualBox COM library). Alternatively, the
1030 * platform-independent class com::ErrorInfo (defined in VBox[XP]COM.lib)
1031 * can be used to retrieve error info in a convenient way.
1032 *
1033 * It is assumed that the interface method that uses this function returns
1034 * an unsuccessful result code to the caller (otherwise, there is no reason
1035 * for the caller to try to retrieve error info after method invocation).
1036 *
1037 * Here is a table of correspondence between this method's arguments
1038 * and IErrorInfo/nsIException/IVirtualBoxErrorInfo attributes/methods:
1039 *
1040 * argument IErrorInfo nsIException IVirtualBoxErrorInfo
1041 * ----------------------------------------------------------------
1042 * resultCode -- result resultCode
1043 * iid GetGUID -- interfaceID
1044 * component GetSource -- component
1045 * text GetDescription message text
1046 *
1047 * This method is rarely needs to be used though. There are more convenient
1048 * overloaded versions, that automatically substitute some arguments
1049 * taking their values from the template parameters. See
1050 * #setError(HRESULT, const char *, ...) for an example.
1051 *
1052 * @param aResultCode result (error) code, must not be S_OK
1053 * @param aIID IID of the interface that defines the error
1054 * @param aComponent name of the component that generates the error
1055 * @param aText error message (must not be null), an RTStrPrintf-like
1056 * format string in UTF-8 encoding
1057 * @param ... list of arguments for the format string
1058 *
1059 * @return
1060 * the error argument, for convenience, If an error occurs while
1061 * creating error info itself, that error is returned instead of the
1062 * error argument.
1063 */
1064 static HRESULT setError(HRESULT aResultCode, const GUID &aIID,
1065 const wchar_t *aComponent,
1066 const char *aText, ...)
1067 {
1068 va_list args;
1069 va_start(args, aText);
1070 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError(aResultCode,
1071 aIID,
1072 aComponent,
1073 aText,
1074 args,
1075 true /* aLogIt */);
1076 va_end(args);
1077 return rc;
1078 }
1079
1080 /**
1081 * This method is the same as #setError() except that it makes sure @a
1082 * aResultCode doesn't have the error severity bit (31) set when passed
1083 * down to the created IVirtualBoxErrorInfo object.
1084 *
1085 * The error severity bit is always cleared by this call, thereof you can
1086 * use ordinary E_XXX result code constants, for convenience. However, this
1087 * behavior may be non-standard on some COM platforms.
1088 */
1089 static HRESULT setWarning(HRESULT aResultCode, const GUID &aIID,
1090 const wchar_t *aComponent,
1091 const char *aText, ...)
1092 {
1093 va_list args;
1094 va_start(args, aText);
1095 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setWarning(
1096 aResultCode, aIID, aComponent, aText, args);
1097 va_end(args);
1098 return rc;
1099 }
1100
1101 /**
1102 * Sets the error information for the current thread.
1103 * A convenience method that automatically sets the default interface
1104 * ID (taken from the I template argument) and the component name
1105 * (a value of C::getComponentName()).
1106 *
1107 * See #setError(HRESULT, const GUID &, const wchar_t *, const char *text, ...)
1108 * for details.
1109 *
1110 * This method is the most common (and convenient) way to set error
1111 * information from within interface methods. A typical pattern of usage
1112 * is looks like this:
1113 *
1114 * <code>
1115 * return setError(E_FAIL, "Terrible Error");
1116 * </code>
1117 * or
1118 * <code>
1119 * HRESULT rc = setError(E_FAIL, "Terrible Error");
1120 * ...
1121 * return rc;
1122 * </code>
1123 */
1124 static HRESULT setError(HRESULT aResultCode, const char *aText, ...)
1125 {
1126 va_list args;
1127 va_start(args, aText);
1128 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError(aResultCode,
1129 COM_IIDOF(I),
1130 C::getComponentName(),
1131 aText,
1132 args,
1133 true /* aLogIt */);
1134 va_end(args);
1135 return rc;
1136 }
1137
1138 /**
1139 * This method is the same as #setError() except that it makes sure @a
1140 * aResultCode doesn't have the error severity bit (31) set when passed
1141 * down to the created IVirtualBoxErrorInfo object.
1142 *
1143 * The error severity bit is always cleared by this call, thereof you can
1144 * use ordinary E_XXX result code constants, for convenience. However, this
1145 * behavior may be non-standard on some COM platforms.
1146 */
1147 static HRESULT setWarning(HRESULT aResultCode, const char *aText, ...)
1148 {
1149 va_list args;
1150 va_start(args, aText);
1151 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setWarning(aResultCode,
1152 COM_IIDOF(I),
1153 C::getComponentName(),
1154 aText,
1155 args);
1156 va_end(args);
1157 return rc;
1158 }
1159
1160 /**
1161 * Sets the error information for the current thread, va_list variant.
1162 * A convenience method that automatically sets the default interface
1163 * ID (taken from the I template argument) and the component name
1164 * (a value of C::getComponentName()).
1165 *
1166 * See #setError(HRESULT, const GUID &, const wchar_t *, const char *text, ...)
1167 * and #setError(HRESULT, const char *, ...) for details.
1168 */
1169 static HRESULT setErrorV(HRESULT aResultCode, const char *aText,
1170 va_list aArgs)
1171 {
1172 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError(aResultCode,
1173 COM_IIDOF(I),
1174 C::getComponentName(),
1175 aText,
1176 aArgs,
1177 true /* aLogIt */);
1178 return rc;
1179 }
1180
1181 /**
1182 * This method is the same as #setErrorV() except that it makes sure @a
1183 * aResultCode doesn't have the error severity bit (31) set when passed
1184 * down to the created IVirtualBoxErrorInfo object.
1185 *
1186 * The error severity bit is always cleared by this call, thereof you can
1187 * use ordinary E_XXX result code constants, for convenience. However, this
1188 * behavior may be non-standard on some COM platforms.
1189 */
1190 static HRESULT setWarningV(HRESULT aResultCode, const char *aText,
1191 va_list aArgs)
1192 {
1193 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setWarning(aResultCode,
1194 COM_IIDOF(I),
1195 C::getComponentName(),
1196 aText,
1197 aArgs);
1198 return rc;
1199 }
1200
1201 /**
1202 * Sets the error information for the current thread.
1203 * A convenience method that automatically sets the component name
1204 * (a value of C::getComponentName()), but allows to specify the interface
1205 * id manually.
1206 *
1207 * See #setError(HRESULT, const GUID &, const wchar_t *, const char *text, ...)
1208 * for details.
1209 */
1210 static HRESULT setError(HRESULT aResultCode, const GUID &aIID,
1211 const char *aText, ...)
1212 {
1213 va_list args;
1214 va_start(args, aText);
1215 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError(aResultCode,
1216 aIID,
1217 C::getComponentName(),
1218 aText,
1219 args,
1220 true /* aLogIt */);
1221 va_end(args);
1222 return rc;
1223 }
1224
1225 /**
1226 * This method is the same as #setError() except that it makes sure @a
1227 * aResultCode doesn't have the error severity bit (31) set when passed
1228 * down to the created IVirtualBoxErrorInfo object.
1229 *
1230 * The error severity bit is always cleared by this call, thereof you can
1231 * use ordinary E_XXX result code constants, for convenience. However, this
1232 * behavior may be non-standard on some COM platforms.
1233 */
1234 static HRESULT setWarning(HRESULT aResultCode, const GUID &aIID,
1235 const char *aText, ...)
1236 {
1237 va_list args;
1238 va_start(args, aText);
1239 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setWarning(aResultCode,
1240 aIID,
1241 C::getComponentName(),
1242 aText,
1243 args);
1244 va_end(args);
1245 return rc;
1246 }
1247
1248 /**
1249 * Sets the error information for the current thread but doesn't put
1250 * anything in the release log. This is very useful for avoiding
1251 * harmless error from causing confusion.
1252 *
1253 * It is otherwise identical to #setError(HRESULT, const char *text, ...).
1254 */
1255 static HRESULT setErrorNoLog(HRESULT aResultCode, const char *aText, ...)
1256 {
1257 va_list args;
1258 va_start(args, aText);
1259 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError(aResultCode,
1260 COM_IIDOF(I),
1261 C::getComponentName(),
1262 aText,
1263 args,
1264 false /* aLogIt */);
1265 va_end(args);
1266 return rc;
1267 }
1268
1269private:
1270
1271};
1272
1273
1274/**
1275 * Base class to track VirtualBoxBaseNEXT chlidren of the component.
1276 *
1277 * This class is a preferrable VirtualBoxBase replacement for components that
1278 * operate with collections of child components. It gives two useful
1279 * possibilities:
1280 *
1281 * <ol><li>
1282 * Given an IUnknown instance, it's possible to quickly determine
1283 * whether this instance represents a child object that belongs to the
1284 * given component, and if so, get a valid VirtualBoxBase pointer to the
1285 * child object. The returned pointer can be then safely casted to the
1286 * actual class of the child object (to get access to its "internal"
1287 * non-interface methods) provided that no other child components implement
1288 * the same original COM interface IUnknown is queried from.
1289 * </li><li>
1290 * When the parent object uninitializes itself, it can easily unintialize
1291 * all its VirtualBoxBase derived children (using their
1292 * VirtualBoxBase::uninit() implementations). This is done simply by
1293 * calling the #uninitDependentChildren() method.
1294 * </li></ol>
1295 *
1296 * In order to let the above work, the following must be done:
1297 * <ol><li>
1298 * When a child object is initialized, it calls #addDependentChild() of
1299 * its parent to register itself within the list of dependent children.
1300 * </li><li>
1301 * When the child object it is uninitialized, it calls
1302 * #removeDependentChild() to unregister itself.
1303 * </li></ol>
1304 *
1305 * Note that if the parent object does not call #uninitDependentChildren() when
1306 * it gets uninitialized, it must call uninit() methods of individual children
1307 * manually to disconnect them; a failure to do so will cause crashes in these
1308 * methods when children get destroyed. The same applies to children not calling
1309 * #removeDependentChild() when getting destroyed.
1310 *
1311 * Note that children added by #addDependentChild() are <b>weakly</b> referenced
1312 * (i.e. AddRef() is not called), so when a child object is deleted externally
1313 * (because it's reference count goes to zero), it will automatically remove
1314 * itself from the map of dependent children provided that it follows the rules
1315 * described here.
1316 *
1317 * Access to the child list is serialized using the #childrenLock() lock handle
1318 * (which defaults to the general object lock handle (see
1319 * VirtualBoxBase::lockHandle()). This lock is used by all add/remove methods of
1320 * this class so be aware of the need to preserve the {parent, child} lock order
1321 * when calling these methods.
1322 *
1323 * Read individual method descriptions to get further information.
1324 *
1325 * @todo This is a VirtualBoxBaseWithChildren equivalent that uses the
1326 * VirtualBoxBaseNEXT implementation. Will completely supersede
1327 * VirtualBoxBaseWithChildren after the old VirtualBoxBase implementation
1328 * has gone.
1329 */
1330class VirtualBoxBaseWithChildrenNEXT : public VirtualBoxBase
1331{
1332public:
1333
1334 VirtualBoxBaseWithChildrenNEXT()
1335 {}
1336
1337 virtual ~VirtualBoxBaseWithChildrenNEXT()
1338 {}
1339
1340 /**
1341 * Lock handle to use when adding/removing child objects from the list of
1342 * children. It is guaranteed that no any other lock is requested in methods
1343 * of this class while holding this lock.
1344 *
1345 * @warning By default, this simply returns the general object's lock handle
1346 * (see VirtualBoxBase::lockHandle()) which is sufficient for most
1347 * cases.
1348 */
1349 virtual RWLockHandle *childrenLock() { return lockHandle(); }
1350
1351 /**
1352 * Adds the given child to the list of dependent children.
1353 *
1354 * Usually gets called from the child's init() method.
1355 *
1356 * @note @a aChild (unless it is in InInit state) must be protected by
1357 * VirtualBoxBase::AutoCaller to make sure it is not uninitialized on
1358 * another thread during this method's call.
1359 *
1360 * @note When #childrenLock() is not overloaded (returns the general object
1361 * lock) and this method is called from under the child's read or
1362 * write lock, make sure the {parent, child} locking order is
1363 * preserved by locking the callee (this object) for writing before
1364 * the child's lock.
1365 *
1366 * @param aChild Child object to add (must inherit VirtualBoxBase AND
1367 * implement some interface).
1368 *
1369 * @note Locks #childrenLock() for writing.
1370 */
1371 template<class C>
1372 void addDependentChild(C *aChild)
1373 {
1374 AssertReturnVoid(aChild != NULL);
1375 doAddDependentChild(ComPtr<IUnknown>(aChild), aChild);
1376 }
1377
1378 /**
1379 * Equivalent to template <class C> void addDependentChild (C *aChild)
1380 * but takes a ComObjPtr<C> argument.
1381 */
1382 template<class C>
1383 void addDependentChild(const ComObjPtr<C> &aChild)
1384 {
1385 AssertReturnVoid(!aChild.isNull());
1386 doAddDependentChild(ComPtr<IUnknown>(static_cast<C *>(aChild)), aChild);
1387 }
1388
1389 /**
1390 * Removes the given child from the list of dependent children.
1391 *
1392 * Usually gets called from the child's uninit() method.
1393 *
1394 * Keep in mind that the called (parent) object may be no longer available
1395 * (i.e. may be deleted deleted) after this method returns, so you must not
1396 * call any other parent's methods after that!
1397 *
1398 * @note Locks #childrenLock() for writing.
1399 *
1400 * @note @a aChild (unless it is in InUninit state) must be protected by
1401 * VirtualBoxBase::AutoCaller to make sure it is not uninitialized on
1402 * another thread during this method's call.
1403 *
1404 * @note When #childrenLock() is not overloaded (returns the general object
1405 * lock) and this method is called from under the child's read or
1406 * write lock, make sure the {parent, child} locking order is
1407 * preserved by locking the callee (this object) for writing before
1408 * the child's lock. This is irrelevant when the method is called from
1409 * under this object's VirtualBoxBaseProto::AutoUninitSpan (i.e. in
1410 * InUninit state) since in this case no locking is done.
1411 *
1412 * @param aChild Child object to remove.
1413 *
1414 * @note Locks #childrenLock() for writing.
1415 */
1416 template<class C>
1417 void removeDependentChild(C *aChild)
1418 {
1419 AssertReturnVoid(aChild != NULL);
1420 doRemoveDependentChild(ComPtr<IUnknown>(aChild));
1421 }
1422
1423 /**
1424 * Equivalent to template <class C> void removeDependentChild (C *aChild)
1425 * but takes a ComObjPtr<C> argument.
1426 */
1427 template<class C>
1428 void removeDependentChild(const ComObjPtr<C> &aChild)
1429 {
1430 AssertReturnVoid(!aChild.isNull());
1431 doRemoveDependentChild(ComPtr<IUnknown>(static_cast<C *>(aChild)));
1432 }
1433
1434protected:
1435
1436 void uninitDependentChildren();
1437
1438 VirtualBoxBase *getDependentChild(const ComPtr<IUnknown> &aUnk);
1439
1440private:
1441 void doAddDependentChild(IUnknown *aUnk, VirtualBoxBase *aChild);
1442 void doRemoveDependentChild(IUnknown *aUnk);
1443
1444 typedef std::map<IUnknown*, VirtualBoxBase*> DependentChildren;
1445 DependentChildren mDependentChildren;
1446};
1447
1448////////////////////////////////////////////////////////////////////////////////
1449
1450////////////////////////////////////////////////////////////////////////////////
1451
1452
1453/// @todo (dmik) remove after we switch to VirtualBoxBaseNEXT completely
1454/**
1455 * Simple template that manages data structure allocation/deallocation
1456 * and supports data pointer sharing (the instance that shares the pointer is
1457 * not responsible for memory deallocation as opposed to the instance that
1458 * owns it).
1459 */
1460template <class D>
1461class Shareable
1462{
1463public:
1464
1465 Shareable() : mData (NULL), mIsShared(FALSE) {}
1466 ~Shareable() { free(); }
1467
1468 void allocate() { attach(new D); }
1469
1470 virtual void free() {
1471 if (mData) {
1472 if (!mIsShared)
1473 delete mData;
1474 mData = NULL;
1475 mIsShared = false;
1476 }
1477 }
1478
1479 void attach(D *d) {
1480 AssertMsg(d, ("new data must not be NULL"));
1481 if (d && mData != d) {
1482 if (mData && !mIsShared)
1483 delete mData;
1484 mData = d;
1485 mIsShared = false;
1486 }
1487 }
1488
1489 void attach(Shareable &d) {
1490 AssertMsg(
1491 d.mData == mData || !d.mIsShared,
1492 ("new data must not be shared")
1493 );
1494 if (this != &d && !d.mIsShared) {
1495 attach(d.mData);
1496 d.mIsShared = true;
1497 }
1498 }
1499
1500 void share(D *d) {
1501 AssertMsg(d, ("new data must not be NULL"));
1502 if (mData != d) {
1503 if (mData && !mIsShared)
1504 delete mData;
1505 mData = d;
1506 mIsShared = true;
1507 }
1508 }
1509
1510 void share(const Shareable &d) { share(d.mData); }
1511
1512 void attachCopy(const D *d) {
1513 AssertMsg(d, ("data to copy must not be NULL"));
1514 if (d)
1515 attach(new D(*d));
1516 }
1517
1518 void attachCopy(const Shareable &d) {
1519 attachCopy(d.mData);
1520 }
1521
1522 virtual D *detach() {
1523 D *d = mData;
1524 mData = NULL;
1525 mIsShared = false;
1526 return d;
1527 }
1528
1529 D *data() const {
1530 return mData;
1531 }
1532
1533 D *operator->() const {
1534 AssertMsg(mData, ("data must not be NULL"));
1535 return mData;
1536 }
1537
1538 bool isNull() const { return mData == NULL; }
1539 bool operator!() const { return isNull(); }
1540
1541 bool isShared() const { return mIsShared; }
1542
1543protected:
1544
1545 D *mData;
1546 bool mIsShared;
1547};
1548
1549/// @todo (dmik) remove after we switch to VirtualBoxBaseNEXT completely
1550/**
1551 * Simple template that enhances Shareable<> and supports data
1552 * backup/rollback/commit (using the copy constructor of the managed data
1553 * structure).
1554 */
1555template<class D>
1556class Backupable : public Shareable<D>
1557{
1558public:
1559
1560 Backupable() : Shareable<D> (), mBackupData(NULL) {}
1561
1562 void free()
1563 {
1564 AssertMsg(this->mData || !mBackupData, ("backup must be NULL if data is NULL"));
1565 rollback();
1566 Shareable<D>::free();
1567 }
1568
1569 D *detach()
1570 {
1571 AssertMsg(this->mData || !mBackupData, ("backup must be NULL if data is NULL"));
1572 rollback();
1573 return Shareable<D>::detach();
1574 }
1575
1576 void share(const Backupable &d)
1577 {
1578 AssertMsg(!d.isBackedUp(), ("data to share must not be backed up"));
1579 if (!d.isBackedUp())
1580 Shareable<D>::share(d.mData);
1581 }
1582
1583 /**
1584 * Stores the current data pointer in the backup area, allocates new data
1585 * using the copy constructor on current data and makes new data active.
1586 */
1587 void backup()
1588 {
1589 AssertMsg(this->mData, ("data must not be NULL"));
1590 if (this->mData && !mBackupData)
1591 {
1592 D *pNewData = new D(*this->mData);
1593 mBackupData = this->mData;
1594 this->mData = pNewData;
1595 }
1596 }
1597
1598 /**
1599 * Deletes new data created by #backup() and restores previous data pointer
1600 * stored in the backup area, making it active again.
1601 */
1602 void rollback()
1603 {
1604 if (this->mData && mBackupData)
1605 {
1606 delete this->mData;
1607 this->mData = mBackupData;
1608 mBackupData = NULL;
1609 }
1610 }
1611
1612 /**
1613 * Commits current changes by deleting backed up data and clearing up the
1614 * backup area. The new data pointer created by #backup() remains active
1615 * and becomes the only managed pointer.
1616 *
1617 * This method is much faster than #commitCopy() (just a single pointer
1618 * assignment operation), but makes the previous data pointer invalid
1619 * (because it is freed). For this reason, this method must not be
1620 * used if it's possible that data managed by this instance is shared with
1621 * some other Shareable instance. See #commitCopy().
1622 */
1623 void commit()
1624 {
1625 if (this->mData && mBackupData)
1626 {
1627 if (!this->mIsShared)
1628 delete mBackupData;
1629 mBackupData = NULL;
1630 this->mIsShared = false;
1631 }
1632 }
1633
1634 /**
1635 * Commits current changes by assigning new data to the previous data
1636 * pointer stored in the backup area using the assignment operator.
1637 * New data is deleted, the backup area is cleared and the previous data
1638 * pointer becomes active and the only managed pointer.
1639 *
1640 * This method is slower than #commit(), but it keeps the previous data
1641 * pointer valid (i.e. new data is copied to the same memory location).
1642 * For that reason it's safe to use this method on instances that share
1643 * managed data with other Shareable instances.
1644 */
1645 void commitCopy()
1646 {
1647 if (this->mData && mBackupData)
1648 {
1649 *mBackupData = *(this->mData);
1650 delete this->mData;
1651 this->mData = mBackupData;
1652 mBackupData = NULL;
1653 }
1654 }
1655
1656 void assignCopy(const D *pData)
1657 {
1658 AssertMsg(this->mData, ("data must not be NULL"));
1659 AssertMsg(pData, ("data to copy must not be NULL"));
1660 if (this->mData && pData)
1661 {
1662 if (!mBackupData)
1663 {
1664 D *pNewData = new D(*pData);
1665 mBackupData = this->mData;
1666 this->mData = pNewData;
1667 }
1668 else
1669 *this->mData = *pData;
1670 }
1671 }
1672
1673 void assignCopy(const Backupable &d)
1674 {
1675 assignCopy(d.mData);
1676 }
1677
1678 bool isBackedUp() const
1679 {
1680 return mBackupData != NULL;
1681 }
1682
1683 D *backedUpData() const
1684 {
1685 return mBackupData;
1686 }
1687
1688protected:
1689
1690 D *mBackupData;
1691};
1692
1693#endif // !____H_VIRTUALBOXBASEIMPL
1694
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