VirtualBox

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

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

Main: cleaned up some pedantic warnings.

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