VirtualBox

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

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

Main/MediumImpl,VirtualBoxBase: eliminate AutoMayUninitSpan, as it leads to deadlocks in Medium::Close (lock order violation between medium tree lock and the eventmulti semaphore used in AutoCaller).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 62.5 KB
Line 
1/** @file
2 *
3 * VirtualBox COM base classes definition
4 */
5
6/*
7 * Copyright (C) 2006-2010 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
486 * | Limited
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 and InitFailed->InUninit->NotReady
507 * transitions are done by the AutoUninitSpan smart class.
508 *
509 * In order to maintain the primary state integrity and declared functionality
510 * all subclasses must:
511 *
512 * 1) Use the above Auto*Span classes to perform state transitions. See the
513 * individual class descriptions for details.
514 *
515 * 2) All public methods of subclasses (i.e. all methods that can be called
516 * directly, not only from within other methods of the subclass) must have a
517 * standard prolog as described in the AutoCaller and AutoLimitedCaller
518 * documentation. Alternatively, they must use addCaller()/releaseCaller()
519 * directly (and therefore have both the prolog and the epilog), but this is
520 * not recommended.
521 */
522class ATL_NO_VTABLE VirtualBoxBase
523 : public Lockable,
524 public CComObjectRootEx<CComMultiThreadModel>
525{
526public:
527 enum State { NotReady, Ready, InInit, InUninit, InitFailed, Limited };
528
529 VirtualBoxBase();
530 virtual ~VirtualBoxBase();
531
532 static const char *translate(const char *context, const char *sourceText,
533 const char *comment = 0);
534
535public:
536
537 /**
538 * Unintialization method.
539 *
540 * Must be called by all final implementations (component classes) when the
541 * last reference to the object is released, before calling the destructor.
542 *
543 * This method is also automatically called by the uninit() method of this
544 * object's parent if this object is a dependent child of a class derived
545 * from VirtualBoxBaseWithChildren (see
546 * VirtualBoxBaseWithChildren::addDependentChild).
547 *
548 * @note Never call this method the AutoCaller scope or after the
549 * #addCaller() call not paired by #releaseCaller() because it is a
550 * guaranteed deadlock. See AutoUninitSpan for details.
551 */
552 virtual void uninit() {}
553
554 virtual HRESULT addCaller(State *aState = NULL, bool aLimited = false);
555 virtual void releaseCaller();
556
557 /**
558 * Adds a limited caller. This method is equivalent to doing
559 * <tt>addCaller (aState, true)</tt>, but it is preferred because provides
560 * better self-descriptiveness. See #addCaller() for more info.
561 */
562 HRESULT addLimitedCaller(State *aState = NULL)
563 {
564 return addCaller(aState, true /* aLimited */);
565 }
566
567 /**
568 * Simple run-time type identification without having to enable C++ RTTI.
569 * The class IDs are defined in VirtualBoxBase.h.
570 * @return
571 */
572 virtual VBoxClsID getClassID() const
573 {
574 return clsidOther;
575 }
576
577 /**
578 * Override of the default locking class to be used for validating lock
579 * order with the standard member lock handle.
580 */
581 virtual VBoxLockingClass getLockingClass() const
582 {
583 return LOCKCLASS_OTHEROBJECT;
584 }
585
586 virtual RWLockHandle *lockHandle() const;
587
588 /**
589 * Returns a lock handle used to protect the primary state fields (used by
590 * #addCaller(), AutoInitSpan, AutoUninitSpan, etc.). Only intended to be
591 * used for similar purposes in subclasses. WARNING: NO any other locks may
592 * be requested while holding this lock!
593 */
594 WriteLockHandle *stateLockHandle() { return &mStateLock; }
595
596private:
597
598 void setState(State aState)
599 {
600 Assert(mState != aState);
601 mState = aState;
602 mStateChangeThread = RTThreadSelf();
603 }
604
605 /** Primary state of this object */
606 State mState;
607 /** Thread that caused the last state change */
608 RTTHREAD mStateChangeThread;
609 /** Total number of active calls to this object */
610 unsigned mCallers;
611 /** Posted when the number of callers drops to zero */
612 RTSEMEVENT mZeroCallersSem;
613 /** Posted when the object goes from InInit/InUninit to some other state */
614 RTSEMEVENTMULTI mInitUninitSem;
615 /** Number of threads waiting for mInitUninitDoneSem */
616 unsigned mInitUninitWaiters;
617
618 /** Protects access to state related data members */
619 WriteLockHandle mStateLock;
620
621 /** User-level object lock for subclasses */
622 mutable RWLockHandle *mObjectLock;
623
624 friend class AutoInitSpan;
625 friend class AutoReinitSpan;
626 friend class AutoUninitSpan;
627};
628
629////////////////////////////////////////////////////////////////////////////////
630//
631// VirtualBoxSupportTranslation, VirtualBoxSupportErrorInfoImpl
632//
633////////////////////////////////////////////////////////////////////////////////
634
635/**
636 * This macro adds the error info support to methods of the VirtualBoxBase
637 * class (by overriding them). Place it to the public section of the
638 * VirtualBoxBase subclass and the following methods will set the extended
639 * error info in case of failure instead of just returning the result code:
640 *
641 * <ul>
642 * <li>VirtualBoxBase::addCaller()
643 * </ul>
644 *
645 * @note The given VirtualBoxBase subclass must also inherit from both
646 * VirtualBoxSupportErrorInfoImpl and VirtualBoxSupportTranslation templates!
647 *
648 * @param C VirtualBoxBase subclass to add the error info support to
649 */
650#define VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT(C) \
651 virtual HRESULT addCaller(VirtualBoxBase::State *aState = NULL, \
652 bool aLimited = false) \
653 { \
654 VirtualBoxBase::State protoState; \
655 HRESULT rc = VirtualBoxBase::addCaller(&protoState, aLimited); \
656 if (FAILED(rc)) \
657 { \
658 if (protoState == VirtualBoxBase::Limited) \
659 rc = setError(rc, tr("The object functionality is limited")); \
660 else \
661 rc = setError(rc, tr("The object is not ready")); \
662 } \
663 if (aState) \
664 *aState = protoState; \
665 return rc; \
666 } \
667
668////////////////////////////////////////////////////////////////////////////////
669
670/** Helper for VirtualBoxSupportTranslation. */
671class VirtualBoxSupportTranslationBase
672{
673protected:
674 static bool cutClassNameFrom__PRETTY_FUNCTION__(char *aPrettyFunctionName);
675};
676
677/**
678 * The VirtualBoxSupportTranslation template implements the NLS string
679 * translation support for the given class.
680 *
681 * Translation support is provided by the static #tr() function. This function,
682 * given a string in UTF-8 encoding, looks up for a translation of the given
683 * string by calling the VirtualBoxBase::translate() global function which
684 * receives the name of the enclosing class ("context of translation") as the
685 * additional argument and returns a translated string based on the currently
686 * active language.
687 *
688 * @param C Class that needs to support the string translation.
689 *
690 * @note Every class that wants to use the #tr() function in its own methods
691 * must inherit from this template, regardless of whether its base class
692 * (if any) inherits from it or not. Otherwise, the translation service
693 * will not work correctly. However, the declaration of the derived
694 * class must contain
695 * the <tt>COM_SUPPORTTRANSLATION_OVERRIDE (<ClassName>)</tt> macro if one
696 * of its base classes also inherits from this template (to resolve the
697 * ambiguity of the #tr() function).
698 */
699template<class C>
700class VirtualBoxSupportTranslation : virtual protected VirtualBoxSupportTranslationBase
701{
702public:
703
704 /**
705 * Translates the given text string by calling VirtualBoxBase::translate()
706 * and passing the name of the C class as the first argument ("context of
707 * translation") See VirtualBoxBase::translate() for more info.
708 *
709 * @param aSourceText String to translate.
710 * @param aComment Comment to the string to resolve possible
711 * ambiguities (NULL means no comment).
712 *
713 * @return Translated version of the source string in UTF-8 encoding, or
714 * the source string itself if the translation is not found in the
715 * specified context.
716 */
717 inline static const char *tr(const char *aSourceText,
718 const char *aComment = NULL)
719 {
720 return VirtualBoxBase::translate(className(), aSourceText, aComment);
721 }
722
723protected:
724
725 static const char *className()
726 {
727 static char fn[sizeof(__PRETTY_FUNCTION__) + 1];
728 if (!sClassName)
729 {
730 strcpy(fn, __PRETTY_FUNCTION__);
731 cutClassNameFrom__PRETTY_FUNCTION__(fn);
732 sClassName = fn;
733 }
734 return sClassName;
735 }
736
737private:
738
739 static const char *sClassName;
740};
741
742template<class C>
743const char *VirtualBoxSupportTranslation<C>::sClassName = NULL;
744
745/**
746 * This macro must be invoked inside the public section of the declaration of
747 * the class inherited from the VirtualBoxSupportTranslation template in case
748 * if one of its other base classes also inherits from that template. This is
749 * necessary to resolve the ambiguity of the #tr() function.
750 *
751 * @param C Class that inherits the VirtualBoxSupportTranslation template
752 * more than once (through its other base clases).
753 */
754#define VIRTUALBOXSUPPORTTRANSLATION_OVERRIDE(C) \
755 inline static const char *tr(const char *aSourceText, \
756 const char *aComment = NULL) \
757 { \
758 return VirtualBoxSupportTranslation<C>::tr(aSourceText, aComment); \
759 }
760
761/**
762 * Dummy macro that is used to shut down Qt's lupdate tool warnings in some
763 * situations. This macro needs to be present inside (better at the very
764 * beginning) of the declaration of the class that inherits from
765 * VirtualBoxSupportTranslation template, to make lupdate happy.
766 */
767#define Q_OBJECT
768
769////////////////////////////////////////////////////////////////////////////////
770
771/**
772 * Helper for the VirtualBoxSupportErrorInfoImpl template.
773 */
774/// @todo switch to com::SupportErrorInfo* and remove
775class VirtualBoxSupportErrorInfoImplBase
776{
777 static HRESULT setErrorInternal(HRESULT aResultCode,
778 const GUID &aIID,
779 const wchar_t *aComponent,
780 const Bstr &aText,
781 bool aWarning,
782 bool aLogIt);
783
784protected:
785
786 /**
787 * The MultiResult class is a com::FWResult enhancement that also acts as a
788 * switch to turn on multi-error mode for #setError() or #setWarning()
789 * calls.
790 *
791 * When an instance of this class is created, multi-error mode is turned on
792 * for the current thread and the turn-on counter is increased by one. In
793 * multi-error mode, a call to #setError() or #setWarning() does not
794 * overwrite the current error or warning info object possibly set on the
795 * current thread by other method calls, but instead it stores this old
796 * object in the IVirtualBoxErrorInfo::next attribute of the new error
797 * object being set.
798 *
799 * This way, error/warning objects are stacked together and form a chain of
800 * errors where the most recent error is the first one retrieved by the
801 * calling party, the preceding error is what the
802 * IVirtualBoxErrorInfo::next attribute of the first error points to, and so
803 * on, up to the first error or warning occurred which is the last in the
804 * chain. See IVirtualBoxErrorInfo documentation for more info.
805 *
806 * When the instance of the MultiResult class goes out of scope and gets
807 * destroyed, it automatically decreases the turn-on counter by one. If
808 * the counter drops to zero, multi-error mode for the current thread is
809 * turned off and the thread switches back to single-error mode where every
810 * next error or warning object overwrites the previous one.
811 *
812 * Note that the caller of a COM method uses a non-S_OK result code to
813 * decide if the method has returned an error (negative codes) or a warning
814 * (positive non-zero codes) and will query extended error info only in
815 * these two cases. However, since multi-error mode implies that the method
816 * doesn't return control return to the caller immediately after the first
817 * error or warning but continues its execution, the functionality provided
818 * by the base com::FWResult class becomes very useful because it allows to
819 * preserve the error or the warning result code even if it is later assigned
820 * a S_OK value multiple times. See com::FWResult for details.
821 *
822 * Here is the typical usage pattern:
823 * <code>
824
825 HRESULT Bar::method()
826 {
827 // assume multi-errors are turned off here...
828
829 if (something)
830 {
831 // Turn on multi-error mode and make sure severity is preserved
832 MultiResult rc = foo->method1();
833
834 // return on fatal error, but continue on warning or on success
835 if (FAILED(rc)) return rc;
836
837 rc = foo->method2();
838 // no matter what result, stack it and continue
839
840 // ...
841
842 // return the last worst result code (it will be preserved even if
843 // foo->method2() returns S_OK.
844 return rc;
845 }
846
847 // multi-errors are turned off here again...
848
849 return S_OK;
850 }
851
852 * </code>
853 *
854 *
855 * @note This class is intended to be instantiated on the stack, therefore
856 * You cannot create them using new(). Although it is possible to copy
857 * instances of MultiResult or return them by value, please never do
858 * that as it is breaks the class semantics (and will assert).
859 */
860 class MultiResult : public com::FWResult
861 {
862 public:
863
864 /**
865 * @copydoc com::FWResult::FWResult().
866 */
867 MultiResult(HRESULT aRC = E_FAIL) : FWResult(aRC) { init(); }
868
869 MultiResult(const MultiResult &aThat) : FWResult(aThat)
870 {
871 /* We need this copy constructor only for GCC that wants to have
872 * it in case of expressions like |MultiResult rc = E_FAIL;|. But
873 * we assert since the optimizer should actually avoid the
874 * temporary and call the other constructor directly instead. */
875 AssertFailed();
876 init();
877 }
878
879 ~MultiResult();
880
881 MultiResult &operator=(HRESULT aRC)
882 {
883 com::FWResult::operator=(aRC);
884 return *this;
885 }
886
887 MultiResult &operator=(const MultiResult &aThat)
888 {
889 /* We need this copy constructor only for GCC that wants to have
890 * it in case of expressions like |MultiResult rc = E_FAIL;|. But
891 * we assert since the optimizer should actually avoid the
892 * temporary and call the other constructor directly instead. */
893 AssertFailed();
894 com::FWResult::operator=(aThat);
895 return *this;
896 }
897
898 private:
899
900 DECLARE_CLS_NEW_DELETE_NOOP(MultiResult)
901
902 void init();
903
904 static RTTLS sCounter;
905
906 friend class VirtualBoxSupportErrorInfoImplBase;
907 };
908
909 static HRESULT setError(HRESULT aResultCode,
910 const GUID &aIID,
911 const wchar_t *aComponent,
912 const Bstr &aText,
913 bool aLogIt = true)
914 {
915 return setErrorInternal(aResultCode, aIID, aComponent, aText,
916 false /* aWarning */, aLogIt);
917 }
918
919 static HRESULT setWarning(HRESULT aResultCode,
920 const GUID &aIID,
921 const wchar_t *aComponent,
922 const Bstr &aText)
923 {
924 return setErrorInternal(aResultCode, aIID, aComponent, aText,
925 true /* aWarning */, true /* aLogIt */);
926 }
927
928 static HRESULT setError(HRESULT aResultCode,
929 const GUID &aIID,
930 const wchar_t *aComponent,
931 const char *aText, va_list aArgs, bool aLogIt = true)
932 {
933 return setErrorInternal(aResultCode, aIID, aComponent,
934 Utf8StrFmtVA (aText, aArgs),
935 false /* aWarning */, aLogIt);
936 }
937
938 static HRESULT setWarning(HRESULT aResultCode,
939 const GUID &aIID,
940 const wchar_t *aComponent,
941 const char *aText, va_list aArgs)
942 {
943 return setErrorInternal(aResultCode, aIID, aComponent,
944 Utf8StrFmtVA (aText, aArgs),
945 true /* aWarning */, true /* aLogIt */);
946 }
947};
948
949/**
950 * This template implements ISupportErrorInfo for the given component class
951 * and provides the #setError() method to conveniently set the error information
952 * from within interface methods' implementations.
953 *
954 * On Windows, the template argument must define a COM interface map using
955 * BEGIN_COM_MAP / END_COM_MAP macros and this map must contain a
956 * COM_INTERFACE_ENTRY(ISupportErrorInfo) definition. All interface entries
957 * that follow it will be considered to support IErrorInfo, i.e. the
958 * InterfaceSupportsErrorInfo() implementation will return S_OK for the
959 * corresponding IID.
960 *
961 * On all platforms, the template argument must also define the following
962 * method: |public static const wchar_t *C::getComponentName()|. See
963 * #setError(HRESULT, const char *, ...) for a description on how it is
964 * used.
965 *
966 * @param C
967 * component class that implements one or more COM interfaces
968 * @param I
969 * default interface for the component. This interface's IID is used
970 * by the shortest form of #setError, for convenience.
971 */
972/// @todo switch to com::SupportErrorInfo* and remove
973template<class C, class I>
974class ATL_NO_VTABLE VirtualBoxSupportErrorInfoImpl
975 : protected VirtualBoxSupportErrorInfoImplBase
976#if !defined (VBOX_WITH_XPCOM)
977 , public ISupportErrorInfo
978#else
979#endif
980{
981public:
982
983#if !defined (VBOX_WITH_XPCOM)
984 STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid)
985 {
986 const _ATL_INTMAP_ENTRY* pEntries = C::_GetEntries();
987 Assert(pEntries);
988 if (!pEntries)
989 return S_FALSE;
990
991 BOOL bSupports = FALSE;
992 BOOL bISupportErrorInfoFound = FALSE;
993
994 while (pEntries->pFunc != NULL && !bSupports)
995 {
996 if (!bISupportErrorInfoFound)
997 {
998 // skip the com map entries until ISupportErrorInfo is found
999 bISupportErrorInfoFound =
1000 InlineIsEqualGUID(*(pEntries->piid), IID_ISupportErrorInfo);
1001 }
1002 else
1003 {
1004 // look for the requested interface in the rest of the com map
1005 bSupports = InlineIsEqualGUID(*(pEntries->piid), riid);
1006 }
1007 pEntries++;
1008 }
1009
1010 Assert(bISupportErrorInfoFound);
1011
1012 return bSupports ? S_OK : S_FALSE;
1013 }
1014#endif // !defined (VBOX_WITH_XPCOM)
1015
1016protected:
1017
1018 /**
1019 * Sets the error information for the current thread.
1020 * This information can be retrieved by a caller of an interface method
1021 * using IErrorInfo on Windows or nsIException on Linux, or the cross-platform
1022 * IVirtualBoxErrorInfo interface that provides extended error info (only
1023 * for components from the VirtualBox COM library). Alternatively, the
1024 * platform-independent class com::ErrorInfo (defined in VBox[XP]COM.lib)
1025 * can be used to retrieve error info in a convenient way.
1026 *
1027 * It is assumed that the interface method that uses this function returns
1028 * an unsuccessful result code to the caller (otherwise, there is no reason
1029 * for the caller to try to retrieve error info after method invocation).
1030 *
1031 * Here is a table of correspondence between this method's arguments
1032 * and IErrorInfo/nsIException/IVirtualBoxErrorInfo attributes/methods:
1033 *
1034 * argument IErrorInfo nsIException IVirtualBoxErrorInfo
1035 * ----------------------------------------------------------------
1036 * resultCode -- result resultCode
1037 * iid GetGUID -- interfaceID
1038 * component GetSource -- component
1039 * text GetDescription message text
1040 *
1041 * This method is rarely needs to be used though. There are more convenient
1042 * overloaded versions, that automatically substitute some arguments
1043 * taking their values from the template parameters. See
1044 * #setError(HRESULT, const char *, ...) for an example.
1045 *
1046 * @param aResultCode result (error) code, must not be S_OK
1047 * @param aIID IID of the interface that defines the error
1048 * @param aComponent name of the component that generates the error
1049 * @param aText error message (must not be null), an RTStrPrintf-like
1050 * format string in UTF-8 encoding
1051 * @param ... list of arguments for the format string
1052 *
1053 * @return
1054 * the error argument, for convenience, If an error occurs while
1055 * creating error info itself, that error is returned instead of the
1056 * error argument.
1057 */
1058 static HRESULT setError(HRESULT aResultCode, const GUID &aIID,
1059 const wchar_t *aComponent,
1060 const char *aText, ...)
1061 {
1062 va_list args;
1063 va_start(args, aText);
1064 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError(aResultCode,
1065 aIID,
1066 aComponent,
1067 aText,
1068 args,
1069 true /* aLogIt */);
1070 va_end(args);
1071 return rc;
1072 }
1073
1074 /**
1075 * This method is the same as #setError() except that it makes sure @a
1076 * aResultCode doesn't have the error severity bit (31) set when passed
1077 * down to the created IVirtualBoxErrorInfo object.
1078 *
1079 * The error severity bit is always cleared by this call, thereof you can
1080 * use ordinary E_XXX result code constants, for convenience. However, this
1081 * behavior may be non-standard on some COM platforms.
1082 */
1083 static HRESULT setWarning(HRESULT aResultCode, const GUID &aIID,
1084 const wchar_t *aComponent,
1085 const char *aText, ...)
1086 {
1087 va_list args;
1088 va_start(args, aText);
1089 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setWarning(
1090 aResultCode, aIID, aComponent, aText, args);
1091 va_end(args);
1092 return rc;
1093 }
1094
1095 /**
1096 * Sets the error information for the current thread.
1097 * A convenience method that automatically sets the default interface
1098 * ID (taken from the I template argument) and the component name
1099 * (a value of C::getComponentName()).
1100 *
1101 * See #setError(HRESULT, const GUID &, const wchar_t *, const char *text, ...)
1102 * for details.
1103 *
1104 * This method is the most common (and convenient) way to set error
1105 * information from within interface methods. A typical pattern of usage
1106 * is looks like this:
1107 *
1108 * <code>
1109 * return setError(E_FAIL, "Terrible Error");
1110 * </code>
1111 * or
1112 * <code>
1113 * HRESULT rc = setError(E_FAIL, "Terrible Error");
1114 * ...
1115 * return rc;
1116 * </code>
1117 */
1118 static HRESULT setError(HRESULT aResultCode, const char *aText, ...)
1119 {
1120 va_list args;
1121 va_start(args, aText);
1122 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError(aResultCode,
1123 COM_IIDOF(I),
1124 C::getComponentName(),
1125 aText,
1126 args,
1127 true /* aLogIt */);
1128 va_end(args);
1129 return rc;
1130 }
1131
1132 /**
1133 * This method is the same as #setError() except that it makes sure @a
1134 * aResultCode doesn't have the error severity bit (31) set when passed
1135 * down to the created IVirtualBoxErrorInfo object.
1136 *
1137 * The error severity bit is always cleared by this call, thereof you can
1138 * use ordinary E_XXX result code constants, for convenience. However, this
1139 * behavior may be non-standard on some COM platforms.
1140 */
1141 static HRESULT setWarning(HRESULT aResultCode, const char *aText, ...)
1142 {
1143 va_list args;
1144 va_start(args, aText);
1145 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setWarning(aResultCode,
1146 COM_IIDOF(I),
1147 C::getComponentName(),
1148 aText,
1149 args);
1150 va_end(args);
1151 return rc;
1152 }
1153
1154 /**
1155 * Sets the error information for the current thread, va_list variant.
1156 * A convenience method that automatically sets the default interface
1157 * ID (taken from the I template argument) and the component name
1158 * (a value of C::getComponentName()).
1159 *
1160 * See #setError(HRESULT, const GUID &, const wchar_t *, const char *text, ...)
1161 * and #setError(HRESULT, const char *, ...) for details.
1162 */
1163 static HRESULT setErrorV(HRESULT aResultCode, const char *aText,
1164 va_list aArgs)
1165 {
1166 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError(aResultCode,
1167 COM_IIDOF(I),
1168 C::getComponentName(),
1169 aText,
1170 aArgs,
1171 true /* aLogIt */);
1172 return rc;
1173 }
1174
1175 /**
1176 * This method is the same as #setErrorV() except that it makes sure @a
1177 * aResultCode doesn't have the error severity bit (31) set when passed
1178 * down to the created IVirtualBoxErrorInfo object.
1179 *
1180 * The error severity bit is always cleared by this call, thereof you can
1181 * use ordinary E_XXX result code constants, for convenience. However, this
1182 * behavior may be non-standard on some COM platforms.
1183 */
1184 static HRESULT setWarningV(HRESULT aResultCode, const char *aText,
1185 va_list aArgs)
1186 {
1187 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setWarning(aResultCode,
1188 COM_IIDOF(I),
1189 C::getComponentName(),
1190 aText,
1191 aArgs);
1192 return rc;
1193 }
1194
1195 /**
1196 * Sets the error information for the current thread.
1197 * A convenience method that automatically sets the component name
1198 * (a value of C::getComponentName()), but allows to specify the interface
1199 * id manually.
1200 *
1201 * See #setError(HRESULT, const GUID &, const wchar_t *, const char *text, ...)
1202 * for details.
1203 */
1204 static HRESULT setError(HRESULT aResultCode, const GUID &aIID,
1205 const char *aText, ...)
1206 {
1207 va_list args;
1208 va_start(args, aText);
1209 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError(aResultCode,
1210 aIID,
1211 C::getComponentName(),
1212 aText,
1213 args,
1214 true /* aLogIt */);
1215 va_end(args);
1216 return rc;
1217 }
1218
1219 /**
1220 * This method is the same as #setError() except that it makes sure @a
1221 * aResultCode doesn't have the error severity bit (31) set when passed
1222 * down to the created IVirtualBoxErrorInfo object.
1223 *
1224 * The error severity bit is always cleared by this call, thereof you can
1225 * use ordinary E_XXX result code constants, for convenience. However, this
1226 * behavior may be non-standard on some COM platforms.
1227 */
1228 static HRESULT setWarning(HRESULT aResultCode, const GUID &aIID,
1229 const char *aText, ...)
1230 {
1231 va_list args;
1232 va_start(args, aText);
1233 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setWarning(aResultCode,
1234 aIID,
1235 C::getComponentName(),
1236 aText,
1237 args);
1238 va_end(args);
1239 return rc;
1240 }
1241
1242 /**
1243 * Sets the error information for the current thread but doesn't put
1244 * anything in the release log. This is very useful for avoiding
1245 * harmless error from causing confusion.
1246 *
1247 * It is otherwise identical to #setError(HRESULT, const char *text, ...).
1248 */
1249 static HRESULT setErrorNoLog(HRESULT aResultCode, const char *aText, ...)
1250 {
1251 va_list args;
1252 va_start(args, aText);
1253 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError(aResultCode,
1254 COM_IIDOF(I),
1255 C::getComponentName(),
1256 aText,
1257 args,
1258 false /* aLogIt */);
1259 va_end(args);
1260 return rc;
1261 }
1262
1263private:
1264
1265};
1266
1267
1268/**
1269 * Base class to track VirtualBoxBaseNEXT chlidren of the component.
1270 *
1271 * This class is a preferrable VirtualBoxBase replacement for components that
1272 * operate with collections of child components. It gives two useful
1273 * possibilities:
1274 *
1275 * <ol><li>
1276 * Given an IUnknown instance, it's possible to quickly determine
1277 * whether this instance represents a child object that belongs to the
1278 * given component, and if so, get a valid VirtualBoxBase pointer to the
1279 * child object. The returned pointer can be then safely casted to the
1280 * actual class of the child object (to get access to its "internal"
1281 * non-interface methods) provided that no other child components implement
1282 * the same original COM interface IUnknown is queried from.
1283 * </li><li>
1284 * When the parent object uninitializes itself, it can easily unintialize
1285 * all its VirtualBoxBase derived children (using their
1286 * VirtualBoxBase::uninit() implementations). This is done simply by
1287 * calling the #uninitDependentChildren() method.
1288 * </li></ol>
1289 *
1290 * In order to let the above work, the following must be done:
1291 * <ol><li>
1292 * When a child object is initialized, it calls #addDependentChild() of
1293 * its parent to register itself within the list of dependent children.
1294 * </li><li>
1295 * When the child object it is uninitialized, it calls
1296 * #removeDependentChild() to unregister itself.
1297 * </li></ol>
1298 *
1299 * Note that if the parent object does not call #uninitDependentChildren() when
1300 * it gets uninitialized, it must call uninit() methods of individual children
1301 * manually to disconnect them; a failure to do so will cause crashes in these
1302 * methods when children get destroyed. The same applies to children not calling
1303 * #removeDependentChild() when getting destroyed.
1304 *
1305 * Note that children added by #addDependentChild() are <b>weakly</b> referenced
1306 * (i.e. AddRef() is not called), so when a child object is deleted externally
1307 * (because it's reference count goes to zero), it will automatically remove
1308 * itself from the map of dependent children provided that it follows the rules
1309 * described here.
1310 *
1311 * Access to the child list is serialized using the #childrenLock() lock handle
1312 * (which defaults to the general object lock handle (see
1313 * VirtualBoxBase::lockHandle()). This lock is used by all add/remove methods of
1314 * this class so be aware of the need to preserve the {parent, child} lock order
1315 * when calling these methods.
1316 *
1317 * Read individual method descriptions to get further information.
1318 *
1319 * @todo This is a VirtualBoxBaseWithChildren equivalent that uses the
1320 * VirtualBoxBaseNEXT implementation. Will completely supersede
1321 * VirtualBoxBaseWithChildren after the old VirtualBoxBase implementation
1322 * has gone.
1323 */
1324class VirtualBoxBaseWithChildrenNEXT : public VirtualBoxBase
1325{
1326public:
1327
1328 VirtualBoxBaseWithChildrenNEXT()
1329 {}
1330
1331 virtual ~VirtualBoxBaseWithChildrenNEXT()
1332 {}
1333
1334 /**
1335 * Lock handle to use when adding/removing child objects from the list of
1336 * children. It is guaranteed that no any other lock is requested in methods
1337 * of this class while holding this lock.
1338 *
1339 * @warning By default, this simply returns the general object's lock handle
1340 * (see VirtualBoxBase::lockHandle()) which is sufficient for most
1341 * cases.
1342 */
1343 virtual RWLockHandle *childrenLock() { return lockHandle(); }
1344
1345 /**
1346 * Adds the given child to the list of dependent children.
1347 *
1348 * Usually gets called from the child's init() method.
1349 *
1350 * @note @a aChild (unless it is in InInit state) must be protected by
1351 * VirtualBoxBase::AutoCaller to make sure it is not uninitialized on
1352 * another thread during this method's call.
1353 *
1354 * @note When #childrenLock() is not overloaded (returns the general object
1355 * lock) and this method is called from under the child's read or
1356 * write lock, make sure the {parent, child} locking order is
1357 * preserved by locking the callee (this object) for writing before
1358 * the child's lock.
1359 *
1360 * @param aChild Child object to add (must inherit VirtualBoxBase AND
1361 * implement some interface).
1362 *
1363 * @note Locks #childrenLock() for writing.
1364 */
1365 template<class C>
1366 void addDependentChild(C *aChild)
1367 {
1368 AssertReturnVoid(aChild != NULL);
1369 doAddDependentChild(ComPtr<IUnknown>(aChild), aChild);
1370 }
1371
1372 /**
1373 * Equivalent to template <class C> void addDependentChild (C *aChild)
1374 * but takes a ComObjPtr<C> argument.
1375 */
1376 template<class C>
1377 void addDependentChild(const ComObjPtr<C> &aChild)
1378 {
1379 AssertReturnVoid(!aChild.isNull());
1380 doAddDependentChild(ComPtr<IUnknown>(static_cast<C *>(aChild)), aChild);
1381 }
1382
1383 /**
1384 * Removes the given child from the list of dependent children.
1385 *
1386 * Usually gets called from the child's uninit() method.
1387 *
1388 * Keep in mind that the called (parent) object may be no longer available
1389 * (i.e. may be deleted deleted) after this method returns, so you must not
1390 * call any other parent's methods after that!
1391 *
1392 * @note Locks #childrenLock() for writing.
1393 *
1394 * @note @a aChild (unless it is in InUninit state) must be protected by
1395 * VirtualBoxBase::AutoCaller to make sure it is not uninitialized on
1396 * another thread during this method's call.
1397 *
1398 * @note When #childrenLock() is not overloaded (returns the general object
1399 * lock) and this method is called from under the child's read or
1400 * write lock, make sure the {parent, child} locking order is
1401 * preserved by locking the callee (this object) for writing before
1402 * the child's lock. This is irrelevant when the method is called from
1403 * under this object's VirtualBoxBaseProto::AutoUninitSpan (i.e. in
1404 * InUninit state) since in this case no locking is done.
1405 *
1406 * @param aChild Child object to remove.
1407 *
1408 * @note Locks #childrenLock() for writing.
1409 */
1410 template<class C>
1411 void removeDependentChild(C *aChild)
1412 {
1413 AssertReturnVoid(aChild != NULL);
1414 doRemoveDependentChild(ComPtr<IUnknown>(aChild));
1415 }
1416
1417 /**
1418 * Equivalent to template <class C> void removeDependentChild (C *aChild)
1419 * but takes a ComObjPtr<C> argument.
1420 */
1421 template<class C>
1422 void removeDependentChild(const ComObjPtr<C> &aChild)
1423 {
1424 AssertReturnVoid(!aChild.isNull());
1425 doRemoveDependentChild(ComPtr<IUnknown>(static_cast<C *>(aChild)));
1426 }
1427
1428protected:
1429
1430 void uninitDependentChildren();
1431
1432 VirtualBoxBase *getDependentChild(const ComPtr<IUnknown> &aUnk);
1433
1434private:
1435 void doAddDependentChild(IUnknown *aUnk, VirtualBoxBase *aChild);
1436 void doRemoveDependentChild(IUnknown *aUnk);
1437
1438 typedef std::map<IUnknown*, VirtualBoxBase*> DependentChildren;
1439 DependentChildren mDependentChildren;
1440};
1441
1442////////////////////////////////////////////////////////////////////////////////
1443
1444////////////////////////////////////////////////////////////////////////////////
1445
1446
1447/// @todo (dmik) remove after we switch to VirtualBoxBaseNEXT completely
1448/**
1449 * Simple template that manages data structure allocation/deallocation
1450 * and supports data pointer sharing (the instance that shares the pointer is
1451 * not responsible for memory deallocation as opposed to the instance that
1452 * owns it).
1453 */
1454template <class D>
1455class Shareable
1456{
1457public:
1458
1459 Shareable() : mData (NULL), mIsShared(FALSE) {}
1460 ~Shareable() { free(); }
1461
1462 void allocate() { attach(new D); }
1463
1464 virtual void free() {
1465 if (mData) {
1466 if (!mIsShared)
1467 delete mData;
1468 mData = NULL;
1469 mIsShared = false;
1470 }
1471 }
1472
1473 void attach(D *d) {
1474 AssertMsg(d, ("new data must not be NULL"));
1475 if (d && mData != d) {
1476 if (mData && !mIsShared)
1477 delete mData;
1478 mData = d;
1479 mIsShared = false;
1480 }
1481 }
1482
1483 void attach(Shareable &d) {
1484 AssertMsg(
1485 d.mData == mData || !d.mIsShared,
1486 ("new data must not be shared")
1487 );
1488 if (this != &d && !d.mIsShared) {
1489 attach(d.mData);
1490 d.mIsShared = true;
1491 }
1492 }
1493
1494 void share(D *d) {
1495 AssertMsg(d, ("new data must not be NULL"));
1496 if (mData != d) {
1497 if (mData && !mIsShared)
1498 delete mData;
1499 mData = d;
1500 mIsShared = true;
1501 }
1502 }
1503
1504 void share(const Shareable &d) { share(d.mData); }
1505
1506 void attachCopy(const D *d) {
1507 AssertMsg(d, ("data to copy must not be NULL"));
1508 if (d)
1509 attach(new D(*d));
1510 }
1511
1512 void attachCopy(const Shareable &d) {
1513 attachCopy(d.mData);
1514 }
1515
1516 virtual D *detach() {
1517 D *d = mData;
1518 mData = NULL;
1519 mIsShared = false;
1520 return d;
1521 }
1522
1523 D *data() const {
1524 return mData;
1525 }
1526
1527 D *operator->() const {
1528 AssertMsg(mData, ("data must not be NULL"));
1529 return mData;
1530 }
1531
1532 bool isNull() const { return mData == NULL; }
1533 bool operator!() const { return isNull(); }
1534
1535 bool isShared() const { return mIsShared; }
1536
1537protected:
1538
1539 D *mData;
1540 bool mIsShared;
1541};
1542
1543/// @todo (dmik) remove after we switch to VirtualBoxBaseNEXT completely
1544/**
1545 * Simple template that enhances Shareable<> and supports data
1546 * backup/rollback/commit (using the copy constructor of the managed data
1547 * structure).
1548 */
1549template<class D>
1550class Backupable : public Shareable<D>
1551{
1552public:
1553
1554 Backupable() : Shareable<D> (), mBackupData(NULL) {}
1555
1556 void free()
1557 {
1558 AssertMsg(this->mData || !mBackupData, ("backup must be NULL if data is NULL"));
1559 rollback();
1560 Shareable<D>::free();
1561 }
1562
1563 D *detach()
1564 {
1565 AssertMsg(this->mData || !mBackupData, ("backup must be NULL if data is NULL"));
1566 rollback();
1567 return Shareable<D>::detach();
1568 }
1569
1570 void share(const Backupable &d)
1571 {
1572 AssertMsg(!d.isBackedUp(), ("data to share must not be backed up"));
1573 if (!d.isBackedUp())
1574 Shareable<D>::share(d.mData);
1575 }
1576
1577 /**
1578 * Stores the current data pointer in the backup area, allocates new data
1579 * using the copy constructor on current data and makes new data active.
1580 */
1581 void backup()
1582 {
1583 AssertMsg(this->mData, ("data must not be NULL"));
1584 if (this->mData && !mBackupData)
1585 {
1586 D *pNewData = new D(*this->mData);
1587 mBackupData = this->mData;
1588 this->mData = pNewData;
1589 }
1590 }
1591
1592 /**
1593 * Deletes new data created by #backup() and restores previous data pointer
1594 * stored in the backup area, making it active again.
1595 */
1596 void rollback()
1597 {
1598 if (this->mData && mBackupData)
1599 {
1600 delete this->mData;
1601 this->mData = mBackupData;
1602 mBackupData = NULL;
1603 }
1604 }
1605
1606 /**
1607 * Commits current changes by deleting backed up data and clearing up the
1608 * backup area. The new data pointer created by #backup() remains active
1609 * and becomes the only managed pointer.
1610 *
1611 * This method is much faster than #commitCopy() (just a single pointer
1612 * assignment operation), but makes the previous data pointer invalid
1613 * (because it is freed). For this reason, this method must not be
1614 * used if it's possible that data managed by this instance is shared with
1615 * some other Shareable instance. See #commitCopy().
1616 */
1617 void commit()
1618 {
1619 if (this->mData && mBackupData)
1620 {
1621 if (!this->mIsShared)
1622 delete mBackupData;
1623 mBackupData = NULL;
1624 this->mIsShared = false;
1625 }
1626 }
1627
1628 /**
1629 * Commits current changes by assigning new data to the previous data
1630 * pointer stored in the backup area using the assignment operator.
1631 * New data is deleted, the backup area is cleared and the previous data
1632 * pointer becomes active and the only managed pointer.
1633 *
1634 * This method is slower than #commit(), but it keeps the previous data
1635 * pointer valid (i.e. new data is copied to the same memory location).
1636 * For that reason it's safe to use this method on instances that share
1637 * managed data with other Shareable instances.
1638 */
1639 void commitCopy()
1640 {
1641 if (this->mData && mBackupData)
1642 {
1643 *mBackupData = *(this->mData);
1644 delete this->mData;
1645 this->mData = mBackupData;
1646 mBackupData = NULL;
1647 }
1648 }
1649
1650 void assignCopy(const D *pData)
1651 {
1652 AssertMsg(this->mData, ("data must not be NULL"));
1653 AssertMsg(pData, ("data to copy must not be NULL"));
1654 if (this->mData && pData)
1655 {
1656 if (!mBackupData)
1657 {
1658 D *pNewData = new D(*pData);
1659 mBackupData = this->mData;
1660 this->mData = pNewData;
1661 }
1662 else
1663 *this->mData = *pData;
1664 }
1665 }
1666
1667 void assignCopy(const Backupable &d)
1668 {
1669 assignCopy(d.mData);
1670 }
1671
1672 bool isBackedUp() const
1673 {
1674 return mBackupData != NULL;
1675 }
1676
1677 D *backedUpData() const
1678 {
1679 return mBackupData;
1680 }
1681
1682protected:
1683
1684 D *mBackupData;
1685};
1686
1687#endif // !____H_VIRTUALBOXBASEIMPL
1688
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