VirtualBox

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

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

Main: remove more dead code

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