VirtualBox

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

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

Main: coding style fixes

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 61.8 KB
Line 
1/** @file
2 *
3 * VirtualBox COM base classes definition
4 */
5
6/*
7 * Copyright (C) 2006-2009 Sun Microsystems, Inc.
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
18 * Clara, CA 95054 USA or visit http://www.sun.com if you need
19 * additional information or have any questions.
20 */
21
22#ifndef ____H_VIRTUALBOXBASEIMPL
23#define ____H_VIRTUALBOXBASEIMPL
24
25#include <iprt/cdefs.h>
26#include <iprt/thread.h>
27
28#include <list>
29#include <map>
30
31#include "VBox/com/ErrorInfo.h"
32#include "VBox/com/SupportErrorInfo.h"
33#include "VBox/com/AutoLock.h"
34
35#include "VBox/com/VirtualBox.h"
36
37// avoid including VBox/settings.h and VBox/xml.h;
38// only declare the classes
39namespace xml
40{
41class File;
42}
43
44using namespace com;
45using namespace util;
46
47class AutoInitSpan;
48class AutoUninitSpan;
49
50class VirtualBox;
51class Machine;
52class Medium;
53class Host;
54typedef std::list< ComObjPtr<Medium> > MediaList;
55
56////////////////////////////////////////////////////////////////////////////////
57//
58// COM helpers
59//
60////////////////////////////////////////////////////////////////////////////////
61
62#if !defined (VBOX_WITH_XPCOM)
63
64#include <atlcom.h>
65
66/* use a special version of the singleton class factory,
67 * see KB811591 in msdn for more info. */
68
69#undef DECLARE_CLASSFACTORY_SINGLETON
70#define DECLARE_CLASSFACTORY_SINGLETON(obj) DECLARE_CLASSFACTORY_EX(CMyComClassFactorySingleton<obj>)
71
72template <class T>
73class CMyComClassFactorySingleton : public CComClassFactory
74{
75public:
76 CMyComClassFactorySingleton() : m_hrCreate(S_OK){}
77 virtual ~CMyComClassFactorySingleton(){}
78 // IClassFactory
79 STDMETHOD(CreateInstance)(LPUNKNOWN pUnkOuter, REFIID riid, void** ppvObj)
80 {
81 HRESULT hRes = E_POINTER;
82 if (ppvObj != NULL)
83 {
84 *ppvObj = NULL;
85 // Aggregation is not supported in singleton objects.
86 ATLASSERT(pUnkOuter == NULL);
87 if (pUnkOuter != NULL)
88 hRes = CLASS_E_NOAGGREGATION;
89 else
90 {
91 if (m_hrCreate == S_OK && m_spObj == NULL)
92 {
93 Lock();
94 __try
95 {
96 // Fix: The following If statement was moved inside the __try statement.
97 // Did another thread arrive here first?
98 if (m_hrCreate == S_OK && m_spObj == NULL)
99 {
100 // lock the module to indicate activity
101 // (necessary for the monitor shutdown thread to correctly
102 // terminate the module in case when CreateInstance() fails)
103 _pAtlModule->Lock();
104 CComObjectCached<T> *p;
105 m_hrCreate = CComObjectCached<T>::CreateInstance(&p);
106 if (SUCCEEDED(m_hrCreate))
107 {
108 m_hrCreate = p->QueryInterface(IID_IUnknown, (void**)&m_spObj);
109 if (FAILED(m_hrCreate))
110 {
111 delete p;
112 }
113 }
114 _pAtlModule->Unlock();
115 }
116 }
117 __finally
118 {
119 Unlock();
120 }
121 }
122 if (m_hrCreate == S_OK)
123 {
124 hRes = m_spObj->QueryInterface(riid, ppvObj);
125 }
126 else
127 {
128 hRes = m_hrCreate;
129 }
130 }
131 }
132 return hRes;
133 }
134 HRESULT m_hrCreate;
135 CComPtr<IUnknown> m_spObj;
136};
137
138#endif /* !defined (VBOX_WITH_XPCOM) */
139
140////////////////////////////////////////////////////////////////////////////////
141//
142// Macros
143//
144////////////////////////////////////////////////////////////////////////////////
145
146/**
147 * Special version of the Assert macro to be used within VirtualBoxBase
148 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
149 *
150 * In the debug build, this macro is equivalent to Assert.
151 * In the release build, this macro uses |setError(E_FAIL, ...)| to set the
152 * error info from the asserted expression.
153 *
154 * @see VirtualBoxSupportErrorInfoImpl::setError
155 *
156 * @param expr Expression which should be true.
157 */
158#if defined (DEBUG)
159#define ComAssert(expr) Assert(expr)
160#else
161#define ComAssert(expr) \
162 do { \
163 if (RT_UNLIKELY(!(expr))) \
164 setError(E_FAIL, "Assertion failed: [%s] at '%s' (%d) in %s.\n" \
165 "Please contact the product vendor!", \
166 #expr, __FILE__, __LINE__, __PRETTY_FUNCTION__); \
167 } while (0)
168#endif
169
170/**
171 * Special version of the AssertMsg macro to be used within VirtualBoxBase
172 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
173 *
174 * See ComAssert for more info.
175 *
176 * @param expr Expression which should be true.
177 * @param a printf argument list (in parenthesis).
178 */
179#if defined (DEBUG)
180#define ComAssertMsg(expr, a) AssertMsg(expr, a)
181#else
182#define ComAssertMsg(expr, a) \
183 do { \
184 if (RT_UNLIKELY(!(expr))) \
185 setError(E_FAIL, "Assertion failed: [%s] at '%s' (%d) in %s.\n" \
186 "%s.\n" \
187 "Please contact the product vendor!", \
188 #expr, __FILE__, __LINE__, __PRETTY_FUNCTION__, Utf8StrFmt a .raw()); \
189 } while (0)
190#endif
191
192/**
193 * Special version of the AssertRC macro to be used within VirtualBoxBase
194 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
195 *
196 * See ComAssert for more info.
197 *
198 * @param vrc VBox status code.
199 */
200#if defined (DEBUG)
201#define ComAssertRC(vrc) AssertRC(vrc)
202#else
203#define ComAssertRC(vrc) ComAssertMsgRC(vrc, ("%Rra", vrc))
204#endif
205
206/**
207 * Special version of the AssertMsgRC macro to be used within VirtualBoxBase
208 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
209 *
210 * See ComAssert for more info.
211 *
212 * @param vrc VBox status code.
213 * @param msg printf argument list (in parenthesis).
214 */
215#if defined (DEBUG)
216#define ComAssertMsgRC(vrc, msg) AssertMsgRC(vrc, msg)
217#else
218#define ComAssertMsgRC(vrc, msg) ComAssertMsg(RT_SUCCESS(vrc), msg)
219#endif
220
221/**
222 * Special version of the AssertComRC macro to be used within VirtualBoxBase
223 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
224 *
225 * See ComAssert for more info.
226 *
227 * @param rc COM result code
228 */
229#if defined (DEBUG)
230#define ComAssertComRC(rc) AssertComRC(rc)
231#else
232#define ComAssertComRC(rc) ComAssertMsg(SUCCEEDED(rc), ("COM RC = %Rhrc (0x%08X)", (rc), (rc)))
233#endif
234
235
236/** Special version of ComAssert that returns ret if expr fails */
237#define ComAssertRet(expr, ret) \
238 do { ComAssert(expr); if (!(expr)) return (ret); } while (0)
239/** Special version of ComAssertMsg that returns ret if expr fails */
240#define ComAssertMsgRet(expr, a, ret) \
241 do { ComAssertMsg(expr, a); if (!(expr)) return (ret); } while (0)
242/** Special version of ComAssertRC that returns ret if vrc does not succeed */
243#define ComAssertRCRet(vrc, ret) \
244 do { ComAssertRC(vrc); if (!RT_SUCCESS(vrc)) return (ret); } while (0)
245/** Special version of ComAssertMsgRC that returns ret if vrc does not succeed */
246#define ComAssertMsgRCRet(vrc, msg, ret) \
247 do { ComAssertMsgRC(vrc, msg); if (!RT_SUCCESS(vrc)) return (ret); } while (0)
248/** Special version of ComAssertFailed that returns ret */
249#define ComAssertFailedRet(ret) \
250 do { ComAssertFailed(); return (ret); } while (0)
251/** Special version of ComAssertMsgFailed that returns ret */
252#define ComAssertMsgFailedRet(msg, ret) \
253 do { ComAssertMsgFailed(msg); return (ret); } while (0)
254/** Special version of ComAssertComRC that returns ret if rc does not succeed */
255#define ComAssertComRCRet(rc, ret) \
256 do { ComAssertComRC(rc); if (!SUCCEEDED(rc)) return (ret); } while (0)
257/** Special version of ComAssertComRC that returns rc if rc does not succeed */
258#define ComAssertComRCRetRC(rc) \
259 do { ComAssertComRC(rc); if (!SUCCEEDED(rc)) return (rc); } while (0)
260
261
262/** Special version of ComAssert that evaluates eval and breaks if expr fails */
263#define ComAssertBreak(expr, eval) \
264 if (1) { ComAssert(expr); if (!(expr)) { eval; break; } } else do {} while (0)
265/** Special version of ComAssertMsg that evaluates eval and breaks if expr fails */
266#define ComAssertMsgBreak(expr, a, eval) \
267 if (1) { ComAssertMsg(expr, a); if (!(expr)) { eval; break; } } else do {} while (0)
268/** Special version of ComAssertRC that evaluates eval and breaks if vrc does not succeed */
269#define ComAssertRCBreak(vrc, eval) \
270 if (1) { ComAssertRC(vrc); if (!RT_SUCCESS(vrc)) { eval; break; } } else do {} while (0)
271/** Special version of ComAssertMsgRC that evaluates eval and breaks if vrc does not succeed */
272#define ComAssertMsgRCBreak(vrc, msg, eval) \
273 if (1) { ComAssertMsgRC(vrc, msg); if (!RT_SUCCESS(vrc)) { eval; break; } } else do {} while (0)
274/** Special version of ComAssertFailed that evaluates eval and breaks */
275#define ComAssertFailedBreak(eval) \
276 if (1) { ComAssertFailed(); { eval; break; } } else do {} while (0)
277/** Special version of ComAssertMsgFailed that evaluates eval and breaks */
278#define ComAssertMsgFailedBreak(msg, eval) \
279 if (1) { ComAssertMsgFailed (msg); { eval; break; } } else do {} while (0)
280/** Special version of ComAssertComRC that evaluates eval and breaks if rc does not succeed */
281#define ComAssertComRCBreak(rc, eval) \
282 if (1) { ComAssertComRC(rc); if (!SUCCEEDED(rc)) { eval; break; } } else do {} while (0)
283/** Special version of ComAssertComRC that just breaks if rc does not succeed */
284#define ComAssertComRCBreakRC(rc) \
285 if (1) { ComAssertComRC(rc); if (!SUCCEEDED(rc)) { break; } } else do {} while (0)
286
287
288/** Special version of ComAssert that evaluates eval and throws it if expr fails */
289#define ComAssertThrow(expr, eval) \
290 if (1) { ComAssert(expr); if (!(expr)) { throw (eval); } } else do {} while (0)
291/** Special version of ComAssertMsg that evaluates eval and throws it if expr fails */
292#define ComAssertMsgThrow(expr, a, eval) \
293 if (1) { ComAssertMsg(expr, a); if (!(expr)) { throw (eval); } } else do {} while (0)
294/** Special version of ComAssertRC that evaluates eval and throws it if vrc does not succeed */
295#define ComAssertRCThrow(vrc, eval) \
296 if (1) { ComAssertRC(vrc); if (!RT_SUCCESS(vrc)) { throw (eval); } } else do {} while (0)
297/** Special version of ComAssertMsgRC that evaluates eval and throws it if vrc does not succeed */
298#define ComAssertMsgRCThrow(vrc, msg, eval) \
299 if (1) { ComAssertMsgRC(vrc, msg); if (!RT_SUCCESS(vrc)) { throw (eval); } } else do {} while (0)
300/** Special version of ComAssertFailed that evaluates eval and throws it */
301#define ComAssertFailedThrow(eval) \
302 if (1) { ComAssertFailed(); { throw (eval); } } else do {} while (0)
303/** Special version of ComAssertMsgFailed that evaluates eval and throws it */
304#define ComAssertMsgFailedThrow(msg, eval) \
305 if (1) { ComAssertMsgFailed (msg); { throw (eval); } } else do {} while (0)
306/** Special version of ComAssertComRC that evaluates eval and throws it if rc does not succeed */
307#define ComAssertComRCThrow(rc, eval) \
308 if (1) { ComAssertComRC(rc); if (!SUCCEEDED(rc)) { throw (eval); } } else do {} while (0)
309/** Special version of ComAssertComRC that just throws rc if rc does not succeed */
310#define ComAssertComRCThrowRC(rc) \
311 if (1) { ComAssertComRC(rc); if (!SUCCEEDED(rc)) { throw rc; } } else do {} while (0)
312
313////////////////////////////////////////////////////////////////////////////////
314
315/**
316 * Checks that the pointer argument is not NULL and returns E_INVALIDARG +
317 * extended error info on failure.
318 * @param arg Input pointer-type argument (strings, interface pointers...)
319 */
320#define CheckComArgNotNull(arg) \
321 do { \
322 if (RT_UNLIKELY((arg) == NULL)) \
323 return setError(E_INVALIDARG, tr("Argument %s is NULL"), #arg); \
324 } while (0)
325
326/**
327 * Checks that safe array argument is not NULL and returns E_INVALIDARG +
328 * extended error info on failure.
329 * @param arg Input safe array argument (strings, interface pointers...)
330 */
331#define CheckComArgSafeArrayNotNull(arg) \
332 do { \
333 if (RT_UNLIKELY(ComSafeArrayInIsNull(arg))) \
334 return setError(E_INVALIDARG, tr("Argument %s is NULL"), #arg); \
335 } while (0)
336
337/**
338 * Checks that the string argument is not a NULL or empty string and returns
339 * E_INVALIDARG + extended error info on failure.
340 * @param arg Input string argument (BSTR etc.).
341 */
342#define CheckComArgStrNotEmptyOrNull(arg) \
343 do { \
344 if (RT_UNLIKELY((arg) == NULL || *(arg) == '\0')) \
345 return setError(E_INVALIDARG, \
346 tr("Argument %s is empty or NULL"), #arg); \
347 } while (0)
348
349/**
350 * Checks that the given expression (that must involve the argument) is true and
351 * returns E_INVALIDARG + extended error info on failure.
352 * @param arg Argument.
353 * @param expr Expression to evaluate.
354 */
355#define CheckComArgExpr(arg, expr) \
356 do { \
357 if (RT_UNLIKELY(!(expr))) \
358 return setError(E_INVALIDARG, \
359 tr("Argument %s is invalid (must be %s)"), #arg, #expr); \
360 } while (0)
361
362/**
363 * Checks that the given expression (that must involve the argument) is true and
364 * returns E_INVALIDARG + extended error info on failure. The error message must
365 * be customized.
366 * @param arg Argument.
367 * @param expr Expression to evaluate.
368 * @param msg Parenthesized printf-like expression (must start with a verb,
369 * like "must be one of...", "is not within...").
370 */
371#define CheckComArgExprMsg(arg, expr, msg) \
372 do { \
373 if (RT_UNLIKELY(!(expr))) \
374 return setError(E_INVALIDARG, tr ("Argument %s %s"), \
375 #arg, Utf8StrFmt msg .raw()); \
376 } while (0)
377
378/**
379 * Checks that the given pointer to an output argument is valid and returns
380 * E_POINTER + extended error info otherwise.
381 * @param arg Pointer argument.
382 */
383#define CheckComArgOutPointerValid(arg) \
384 do { \
385 if (RT_UNLIKELY(!VALID_PTR(arg))) \
386 return setError(E_POINTER, \
387 tr("Output argument %s points to invalid memory location (%p)"), \
388 #arg, (void *) (arg)); \
389 } while (0)
390
391/**
392 * Checks that the given pointer to an output safe array argument is valid and
393 * returns E_POINTER + extended error info otherwise.
394 * @param arg Safe array argument.
395 */
396#define CheckComArgOutSafeArrayPointerValid(arg) \
397 do { \
398 if (RT_UNLIKELY(ComSafeArrayOutIsNull(arg))) \
399 return setError(E_POINTER, \
400 tr("Output argument %s points to invalid memory location (%p)"), \
401 #arg, (void *) (arg)); \
402 } while (0)
403
404/**
405 * Sets the extended error info and returns E_NOTIMPL.
406 */
407#define ReturnComNotImplemented() \
408 do { \
409 return setError(E_NOTIMPL, tr("Method %s is not implemented"), __FUNCTION__); \
410 } while (0)
411
412/**
413 * Declares an empty constructor and destructor for the given class.
414 * This is useful to prevent the compiler from generating the default
415 * ctor and dtor, which in turn allows to use forward class statements
416 * (instead of including their header files) when declaring data members of
417 * non-fundamental types with constructors (which are always called implicitly
418 * by constructors and by the destructor of the class).
419 *
420 * This macro is to be placed within (the public section of) the class
421 * declaration. Its counterpart, DEFINE_EMPTY_CTOR_DTOR, must be placed
422 * somewhere in one of the translation units (usually .cpp source files).
423 *
424 * @param cls class to declare a ctor and dtor for
425 */
426#define DECLARE_EMPTY_CTOR_DTOR(cls) cls(); ~cls();
427
428/**
429 * Defines an empty constructor and destructor for the given class.
430 * See DECLARE_EMPTY_CTOR_DTOR for more info.
431 */
432#define DEFINE_EMPTY_CTOR_DTOR(cls) \
433 cls::cls () {}; cls::~cls () {};
434
435////////////////////////////////////////////////////////////////////////////////
436//
437// VirtualBoxBase
438//
439////////////////////////////////////////////////////////////////////////////////
440
441/**
442 * This enum is used in the virtual method VirtualBoxBasePro::getClassID() to
443 * allow VirtualBox classes to identify themselves. Subclasses can override
444 * that method and return a value from this enum if run-time identification is
445 * needed anywhere.
446 */
447enum VBoxClsID
448{
449 clsidVirtualBox,
450 clsidHost,
451 clsidMachine,
452 clsidSessionMachine,
453 clsidSnapshotMachine,
454 clsidSnapshot,
455 clsidOther
456};
457
458/**
459 * Abstract base class for all component classes implementing COM
460 * interfaces of the VirtualBox COM library.
461 *
462 * Declares functionality that should be available in all components.
463 *
464 * Note that this class is always subclassed using the virtual keyword so
465 * that only one instance of its VTBL and data is present in each derived class
466 * even in case if VirtualBoxBaseProto appears more than once among base classes
467 * of the particular component as a result of multiple inheritance.
468 *
469 * This makes it possible to have intermediate base classes used by several
470 * components that implement some common interface functionality but still let
471 * the final component classes choose what VirtualBoxBase variant it wants to
472 * use.
473 *
474 * Among the basic functionality implemented by this class is the primary object
475 * state that indicates if the object is ready to serve the calls, and if not,
476 * what stage it is currently at. Here is the primary state diagram:
477 *
478 * +-------------------------------------------------------+
479 * | |
480 * | (InitFailed) -----------------------+ |
481 * | ^ | |
482 * v | v |
483 * [*] ---> NotReady ----> (InInit) -----> Ready -----> (InUninit) ----+
484 * ^ | ^ | ^
485 * | v | v |
486 * | Limited | (MayUninit) --> (WillUninit)
487 * | | | |
488 * +-------+ +-------+
489 *
490 * The object is fully operational only when its state is Ready. The Limited
491 * state means that only some vital part of the object is operational, and it
492 * requires some sort of reinitialization to become fully operational. The
493 * NotReady state means the object is basically dead: it either was not yet
494 * initialized after creation at all, or was uninitialized and is waiting to be
495 * destroyed when the last reference to it is released. All other states are
496 * transitional.
497 *
498 * The NotReady->InInit->Ready, NotReady->InInit->Limited and
499 * NotReady->InInit->InitFailed transition is done by the AutoInitSpan smart
500 * class.
501 *
502 * The Limited->InInit->Ready, Limited->InInit->Limited and
503 * Limited->InInit->InitFailed transition is done by the AutoReinitSpan smart
504 * class.
505 *
506 * The Ready->InUninit->NotReady, InitFailed->InUninit->NotReady and
507 * WillUninit->InUninit->NotReady transitions are done by the AutoUninitSpan
508 * smart class.
509 *
510 * The Ready->MayUninit->Ready and Ready->MayUninit->WillUninit transitions are
511 * done by the AutoMayUninitSpan smart class.
512 *
513 * In order to maintain the primary state integrity and declared functionality
514 * all subclasses must:
515 *
516 * 1) Use the above Auto*Span classes to perform state transitions. See the
517 * individual class descriptions for details.
518 *
519 * 2) All public methods of subclasses (i.e. all methods that can be called
520 * directly, not only from within other methods of the subclass) must have a
521 * standard prolog as described in the AutoCaller and AutoLimitedCaller
522 * documentation. Alternatively, they must use addCaller()/releaseCaller()
523 * directly (and therefore have both the prolog and the epilog), but this is
524 * not recommended.
525 */
526class ATL_NO_VTABLE VirtualBoxBase
527 : public Lockable,
528 public CComObjectRootEx<CComMultiThreadModel>
529{
530public:
531 enum State { NotReady, Ready, InInit, InUninit, InitFailed, Limited,
532 MayUninit, WillUninit };
533
534 VirtualBoxBase();
535 virtual ~VirtualBoxBase();
536
537 static const char *translate(const char *context, const char *sourceText,
538 const char *comment = 0);
539
540public:
541
542 /**
543 * Unintialization method.
544 *
545 * Must be called by all final implementations (component classes) when the
546 * last reference to the object is released, before calling the destructor.
547 *
548 * This method is also automatically called by the uninit() method of this
549 * object's parent if this object is a dependent child of a class derived
550 * from VirtualBoxBaseWithChildren (see
551 * VirtualBoxBaseWithChildren::addDependentChild).
552 *
553 * @note Never call this method the AutoCaller scope or after the
554 * #addCaller() call not paired by #releaseCaller() because it is a
555 * guaranteed deadlock. See AutoUninitSpan for details.
556 */
557 virtual void uninit() {}
558
559 virtual HRESULT addCaller(State *aState = NULL, bool aLimited = false);
560 virtual void releaseCaller();
561
562 /**
563 * Adds a limited caller. This method is equivalent to doing
564 * <tt>addCaller (aState, true)</tt>, but it is preferred because provides
565 * better self-descriptiveness. See #addCaller() for more info.
566 */
567 HRESULT addLimitedCaller(State *aState = NULL)
568 {
569 return addCaller(aState, true /* aLimited */);
570 }
571
572 /**
573 * Simple run-time type identification without having to enable C++ RTTI.
574 * The class IDs are defined in VirtualBoxBase.h.
575 * @return
576 */
577 virtual VBoxClsID getClassID() const
578 {
579 return clsidOther;
580 }
581
582 /**
583 * Override of the default locking class to be used for validating lock
584 * order with the standard member lock handle.
585 */
586 virtual VBoxLockingClass getLockingClass() const
587 {
588 return LOCKCLASS_OTHEROBJECT;
589 }
590
591 virtual RWLockHandle *lockHandle() const;
592
593 /**
594 * Returns a lock handle used to protect the primary state fields (used by
595 * #addCaller(), AutoInitSpan, AutoUninitSpan, etc.). Only intended to be
596 * used for similar purposes in subclasses. WARNING: NO any other locks may
597 * be requested while holding this lock!
598 */
599 WriteLockHandle *stateLockHandle() { return &mStateLock; }
600
601private:
602
603 void setState(State aState)
604 {
605 Assert(mState != aState);
606 mState = aState;
607 mStateChangeThread = RTThreadSelf();
608 }
609
610 /** Primary state of this object */
611 State mState;
612 /** Thread that caused the last state change */
613 RTTHREAD mStateChangeThread;
614 /** Total number of active calls to this object */
615 unsigned mCallers;
616 /** Posted when the number of callers drops to zero */
617 RTSEMEVENT mZeroCallersSem;
618 /** Posted when the object goes from InInit/InUninit to some other state */
619 RTSEMEVENTMULTI mInitUninitSem;
620 /** Number of threads waiting for mInitUninitDoneSem */
621 unsigned mInitUninitWaiters;
622
623 /** Protects access to state related data members */
624 WriteLockHandle mStateLock;
625
626 /** User-level object lock for subclasses */
627 mutable RWLockHandle *mObjectLock;
628
629 friend class AutoInitSpan;
630 friend class AutoReinitSpan;
631 friend class AutoUninitSpan;
632 friend class AutoMayUninitSpan;
633};
634
635////////////////////////////////////////////////////////////////////////////////
636//
637// VirtualBoxSupportTranslation, VirtualBoxSupportErrorInfoImpl
638//
639////////////////////////////////////////////////////////////////////////////////
640
641/**
642 * This macro adds the error info support to methods of the VirtualBoxBase
643 * class (by overriding them). Place it to the public section of the
644 * VirtualBoxBase subclass and the following methods will set the extended
645 * error info in case of failure instead of just returning the result code:
646 *
647 * <ul>
648 * <li>VirtualBoxBase::addCaller()
649 * </ul>
650 *
651 * @note The given VirtualBoxBase subclass must also inherit from both
652 * VirtualBoxSupportErrorInfoImpl and VirtualBoxSupportTranslation templates!
653 *
654 * @param C VirtualBoxBase subclass to add the error info support to
655 */
656#define VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT(C) \
657 virtual HRESULT addCaller(VirtualBoxBase::State *aState = NULL, \
658 bool aLimited = false) \
659 { \
660 VirtualBoxBase::State protoState; \
661 HRESULT rc = VirtualBoxBase::addCaller(&protoState, aLimited); \
662 if (FAILED(rc)) \
663 { \
664 if (protoState == VirtualBoxBase::Limited) \
665 rc = setError(rc, tr("The object functionality is limited")); \
666 else \
667 rc = setError(rc, tr("The object is not ready")); \
668 } \
669 if (aState) \
670 *aState = protoState; \
671 return rc; \
672 } \
673
674////////////////////////////////////////////////////////////////////////////////
675
676/** Helper for VirtualBoxSupportTranslation. */
677class VirtualBoxSupportTranslationBase
678{
679protected:
680 static bool cutClassNameFrom__PRETTY_FUNCTION__(char *aPrettyFunctionName);
681};
682
683/**
684 * The VirtualBoxSupportTranslation template implements the NLS string
685 * translation support for the given class.
686 *
687 * Translation support is provided by the static #tr() function. This function,
688 * given a string in UTF-8 encoding, looks up for a translation of the given
689 * string by calling the VirtualBoxBase::translate() global function which
690 * receives the name of the enclosing class ("context of translation") as the
691 * additional argument and returns a translated string based on the currently
692 * active language.
693 *
694 * @param C Class that needs to support the string translation.
695 *
696 * @note Every class that wants to use the #tr() function in its own methods
697 * must inherit from this template, regardless of whether its base class
698 * (if any) inherits from it or not. Otherwise, the translation service
699 * will not work correctly. However, the declaration of the derived
700 * class must contain
701 * the <tt>COM_SUPPORTTRANSLATION_OVERRIDE (<ClassName>)</tt> macro if one
702 * of its base classes also inherits from this template (to resolve the
703 * ambiguity of the #tr() function).
704 */
705template<class C>
706class VirtualBoxSupportTranslation : virtual protected VirtualBoxSupportTranslationBase
707{
708public:
709
710 /**
711 * Translates the given text string by calling VirtualBoxBase::translate()
712 * and passing the name of the C class as the first argument ("context of
713 * translation") See VirtualBoxBase::translate() for more info.
714 *
715 * @param aSourceText String to translate.
716 * @param aComment Comment to the string to resolve possible
717 * ambiguities (NULL means no comment).
718 *
719 * @return Translated version of the source string in UTF-8 encoding, or
720 * the source string itself if the translation is not found in the
721 * specified context.
722 */
723 inline static const char *tr(const char *aSourceText,
724 const char *aComment = NULL)
725 {
726 return VirtualBoxBase::translate(className(), aSourceText, aComment);
727 }
728
729protected:
730
731 static const char *className()
732 {
733 static char fn[sizeof(__PRETTY_FUNCTION__) + 1];
734 if (!sClassName)
735 {
736 strcpy(fn, __PRETTY_FUNCTION__);
737 cutClassNameFrom__PRETTY_FUNCTION__(fn);
738 sClassName = fn;
739 }
740 return sClassName;
741 }
742
743private:
744
745 static const char *sClassName;
746};
747
748template<class C>
749const char *VirtualBoxSupportTranslation<C>::sClassName = NULL;
750
751/**
752 * This macro must be invoked inside the public section of the declaration of
753 * the class inherited from the VirtualBoxSupportTranslation template in case
754 * if one of its other base classes also inherits from that template. This is
755 * necessary to resolve the ambiguity of the #tr() function.
756 *
757 * @param C Class that inherits the VirtualBoxSupportTranslation template
758 * more than once (through its other base clases).
759 */
760#define VIRTUALBOXSUPPORTTRANSLATION_OVERRIDE(C) \
761 inline static const char *tr(const char *aSourceText, \
762 const char *aComment = NULL) \
763 { \
764 return VirtualBoxSupportTranslation<C>::tr(aSourceText, aComment); \
765 }
766
767/**
768 * Dummy macro that is used to shut down Qt's lupdate tool warnings in some
769 * situations. This macro needs to be present inside (better at the very
770 * beginning) of the declaration of the class that inherits from
771 * VirtualBoxSupportTranslation template, to make lupdate happy.
772 */
773#define Q_OBJECT
774
775////////////////////////////////////////////////////////////////////////////////
776
777/**
778 * Helper for the VirtualBoxSupportErrorInfoImpl template.
779 */
780/// @todo switch to com::SupportErrorInfo* and remove
781class VirtualBoxSupportErrorInfoImplBase
782{
783 static HRESULT setErrorInternal(HRESULT aResultCode, 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, BStr variant.
1178 * A convenience method that automatically sets the default interface
1179 * ID (taken from the I template argument) and the component name
1180 * (a value of C::getComponentName()).
1181 *
1182 * This method is preferred if you have a ready (translated and formatted)
1183 * Bstr string, because it omits an extra conversion Utf8Str -> Bstr.
1184 *
1185 * See #setError(HRESULT, const GUID &, const wchar_t *, const char *text, ...)
1186 * and #setError(HRESULT, const char *, ...) for details.
1187 */
1188 static HRESULT setErrorBstr(HRESULT aResultCode, const Bstr &aText)
1189 {
1190 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError(
1191 aResultCode, COM_IIDOF(I), C::getComponentName(), aText, true /* aLogIt */);
1192 return rc;
1193 }
1194
1195 /**
1196 * This method is the same as #setErrorBstr() except that it makes sure @a
1197 * aResultCode doesn't have the error severity bit (31) set when passed
1198 * down to the created IVirtualBoxErrorInfo object.
1199 *
1200 * The error severity bit is always cleared by this call, thereof you can
1201 * use ordinary E_XXX result code constants, for convenience. However, this
1202 * behavior may be non-standard on some COM platforms.
1203 */
1204 static HRESULT setWarningBstr(HRESULT aResultCode, const Bstr &aText)
1205 {
1206 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setWarning(
1207 aResultCode, COM_IIDOF(I), C::getComponentName(), aText);
1208 return rc;
1209 }
1210
1211 /**
1212 * Sets the error information for the current thread.
1213 * A convenience method that automatically sets the component name
1214 * (a value of C::getComponentName()), but allows to specify the interface
1215 * id manually.
1216 *
1217 * See #setError(HRESULT, const GUID &, const wchar_t *, const char *text, ...)
1218 * for details.
1219 */
1220 static HRESULT setError(HRESULT aResultCode, const GUID &aIID,
1221 const char *aText, ...)
1222 {
1223 va_list args;
1224 va_start(args, aText);
1225 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError(
1226 aResultCode, aIID, C::getComponentName(), aText, args, true /* aLogIt */);
1227 va_end(args);
1228 return rc;
1229 }
1230
1231 /**
1232 * This method is the same as #setError() except that it makes sure @a
1233 * aResultCode doesn't have the error severity bit (31) set when passed
1234 * down to the created IVirtualBoxErrorInfo object.
1235 *
1236 * The error severity bit is always cleared by this call, thereof you can
1237 * use ordinary E_XXX result code constants, for convenience. However, this
1238 * behavior may be non-standard on some COM platforms.
1239 */
1240 static HRESULT setWarning(HRESULT aResultCode, const GUID &aIID,
1241 const char *aText, ...)
1242 {
1243 va_list args;
1244 va_start(args, aText);
1245 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setWarning(
1246 aResultCode, aIID, C::getComponentName(), aText, args);
1247 va_end(args);
1248 return rc;
1249 }
1250
1251 /**
1252 * Sets the error information for the current thread but doesn't put
1253 * anything in the release log. This is very useful for avoiding
1254 * harmless error from causing confusion.
1255 *
1256 * It is otherwise identical to #setError(HRESULT, const char *text, ...).
1257 */
1258 static HRESULT setErrorNoLog(HRESULT aResultCode, const char *aText, ...)
1259 {
1260 va_list args;
1261 va_start(args, aText);
1262 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError(
1263 aResultCode, COM_IIDOF(I), C::getComponentName(), aText, args, false /* aLogIt */);
1264 va_end(args);
1265 return rc;
1266 }
1267
1268private:
1269
1270};
1271
1272
1273/**
1274 * Base class to track VirtualBoxBaseNEXT chlidren of the component.
1275 *
1276 * This class is a preferrable VirtualBoxBase replacement for components that
1277 * operate with collections of child components. It gives two useful
1278 * possibilities:
1279 *
1280 * <ol><li>
1281 * Given an IUnknown instance, it's possible to quickly determine
1282 * whether this instance represents a child object that belongs to the
1283 * given component, and if so, get a valid VirtualBoxBase pointer to the
1284 * child object. The returned pointer can be then safely casted to the
1285 * actual class of the child object (to get access to its "internal"
1286 * non-interface methods) provided that no other child components implement
1287 * the same original COM interface IUnknown is queried from.
1288 * </li><li>
1289 * When the parent object uninitializes itself, it can easily unintialize
1290 * all its VirtualBoxBase derived children (using their
1291 * VirtualBoxBase::uninit() implementations). This is done simply by
1292 * calling the #uninitDependentChildren() method.
1293 * </li></ol>
1294 *
1295 * In order to let the above work, the following must be done:
1296 * <ol><li>
1297 * When a child object is initialized, it calls #addDependentChild() of
1298 * its parent to register itself within the list of dependent children.
1299 * </li><li>
1300 * When the child object it is uninitialized, it calls
1301 * #removeDependentChild() to unregister itself.
1302 * </li></ol>
1303 *
1304 * Note that if the parent object does not call #uninitDependentChildren() when
1305 * it gets uninitialized, it must call uninit() methods of individual children
1306 * manually to disconnect them; a failure to do so will cause crashes in these
1307 * methods when children get destroyed. The same applies to children not calling
1308 * #removeDependentChild() when getting destroyed.
1309 *
1310 * Note that children added by #addDependentChild() are <b>weakly</b> referenced
1311 * (i.e. AddRef() is not called), so when a child object is deleted externally
1312 * (because it's reference count goes to zero), it will automatically remove
1313 * itself from the map of dependent children provided that it follows the rules
1314 * described here.
1315 *
1316 * Access to the child list is serialized using the #childrenLock() lock handle
1317 * (which defaults to the general object lock handle (see
1318 * VirtualBoxBase::lockHandle()). This lock is used by all add/remove methods of
1319 * this class so be aware of the need to preserve the {parent, child} lock order
1320 * when calling these methods.
1321 *
1322 * Read individual method descriptions to get further information.
1323 *
1324 * @todo This is a VirtualBoxBaseWithChildren equivalent that uses the
1325 * VirtualBoxBaseNEXT implementation. Will completely supersede
1326 * VirtualBoxBaseWithChildren after the old VirtualBoxBase implementation
1327 * has gone.
1328 */
1329class VirtualBoxBaseWithChildrenNEXT : public VirtualBoxBase
1330{
1331public:
1332
1333 VirtualBoxBaseWithChildrenNEXT()
1334 {}
1335
1336 virtual ~VirtualBoxBaseWithChildrenNEXT()
1337 {}
1338
1339 /**
1340 * Lock handle to use when adding/removing child objects from the list of
1341 * children. It is guaranteed that no any other lock is requested in methods
1342 * of this class while holding this lock.
1343 *
1344 * @warning By default, this simply returns the general object's lock handle
1345 * (see VirtualBoxBase::lockHandle()) which is sufficient for most
1346 * cases.
1347 */
1348 virtual RWLockHandle *childrenLock() { return lockHandle(); }
1349
1350 /**
1351 * Adds the given child to the list of dependent children.
1352 *
1353 * Usually gets called from the child's init() method.
1354 *
1355 * @note @a aChild (unless it is in InInit state) must be protected by
1356 * VirtualBoxBase::AutoCaller to make sure it is not uninitialized on
1357 * another thread during this method's call.
1358 *
1359 * @note When #childrenLock() is not overloaded (returns the general object
1360 * lock) and this method is called from under the child's read or
1361 * write lock, make sure the {parent, child} locking order is
1362 * preserved by locking the callee (this object) for writing before
1363 * the child's lock.
1364 *
1365 * @param aChild Child object to add (must inherit VirtualBoxBase AND
1366 * implement some interface).
1367 *
1368 * @note Locks #childrenLock() for writing.
1369 */
1370 template<class C>
1371 void addDependentChild(C *aChild)
1372 {
1373 AssertReturnVoid(aChild != NULL);
1374 doAddDependentChild(ComPtr<IUnknown>(aChild), aChild);
1375 }
1376
1377 /**
1378 * Equivalent to template <class C> void addDependentChild (C *aChild)
1379 * but takes a ComObjPtr<C> argument.
1380 */
1381 template<class C>
1382 void addDependentChild(const ComObjPtr<C> &aChild)
1383 {
1384 AssertReturnVoid(!aChild.isNull());
1385 doAddDependentChild(ComPtr<IUnknown>(static_cast<C *>(aChild)), aChild);
1386 }
1387
1388 /**
1389 * Removes the given child from the list of dependent children.
1390 *
1391 * Usually gets called from the child's uninit() method.
1392 *
1393 * Keep in mind that the called (parent) object may be no longer available
1394 * (i.e. may be deleted deleted) after this method returns, so you must not
1395 * call any other parent's methods after that!
1396 *
1397 * @note Locks #childrenLock() for writing.
1398 *
1399 * @note @a aChild (unless it is in InUninit state) must be protected by
1400 * VirtualBoxBase::AutoCaller to make sure it is not uninitialized on
1401 * another thread during this method's call.
1402 *
1403 * @note When #childrenLock() is not overloaded (returns the general object
1404 * lock) and this method is called from under the child's read or
1405 * write lock, make sure the {parent, child} locking order is
1406 * preserved by locking the callee (this object) for writing before
1407 * the child's lock. This is irrelevant when the method is called from
1408 * under this object's VirtualBoxBaseProto::AutoUninitSpan (i.e. in
1409 * InUninit state) since in this case no locking is done.
1410 *
1411 * @param aChild Child object to remove.
1412 *
1413 * @note Locks #childrenLock() for writing.
1414 */
1415 template<class C>
1416 void removeDependentChild(C *aChild)
1417 {
1418 AssertReturnVoid(aChild != NULL);
1419 doRemoveDependentChild(ComPtr<IUnknown>(aChild));
1420 }
1421
1422 /**
1423 * Equivalent to template <class C> void removeDependentChild (C *aChild)
1424 * but takes a ComObjPtr<C> argument.
1425 */
1426 template<class C>
1427 void removeDependentChild(const ComObjPtr<C> &aChild)
1428 {
1429 AssertReturnVoid(!aChild.isNull());
1430 doRemoveDependentChild(ComPtr<IUnknown>(static_cast<C *>(aChild)));
1431 }
1432
1433protected:
1434
1435 void uninitDependentChildren();
1436
1437 VirtualBoxBase *getDependentChild(const ComPtr<IUnknown> &aUnk);
1438
1439private:
1440 void doAddDependentChild(IUnknown *aUnk, VirtualBoxBase *aChild);
1441 void doRemoveDependentChild(IUnknown *aUnk);
1442
1443 typedef std::map<IUnknown*, VirtualBoxBase*> DependentChildren;
1444 DependentChildren mDependentChildren;
1445};
1446
1447////////////////////////////////////////////////////////////////////////////////
1448
1449////////////////////////////////////////////////////////////////////////////////
1450
1451
1452/// @todo (dmik) remove after we switch to VirtualBoxBaseNEXT completely
1453/**
1454 * Simple template that manages data structure allocation/deallocation
1455 * and supports data pointer sharing (the instance that shares the pointer is
1456 * not responsible for memory deallocation as opposed to the instance that
1457 * owns it).
1458 */
1459template <class D>
1460class Shareable
1461{
1462public:
1463
1464 Shareable() : mData (NULL), mIsShared(FALSE) {}
1465 ~Shareable() { free(); }
1466
1467 void allocate() { attach(new D); }
1468
1469 virtual void free() {
1470 if (mData) {
1471 if (!mIsShared)
1472 delete mData;
1473 mData = NULL;
1474 mIsShared = false;
1475 }
1476 }
1477
1478 void attach(D *d) {
1479 AssertMsg(d, ("new data must not be NULL"));
1480 if (d && mData != d) {
1481 if (mData && !mIsShared)
1482 delete mData;
1483 mData = d;
1484 mIsShared = false;
1485 }
1486 }
1487
1488 void attach(Shareable &d) {
1489 AssertMsg(
1490 d.mData == mData || !d.mIsShared,
1491 ("new data must not be shared")
1492 );
1493 if (this != &d && !d.mIsShared) {
1494 attach(d.mData);
1495 d.mIsShared = true;
1496 }
1497 }
1498
1499 void share(D *d) {
1500 AssertMsg(d, ("new data must not be NULL"));
1501 if (mData != d) {
1502 if (mData && !mIsShared)
1503 delete mData;
1504 mData = d;
1505 mIsShared = true;
1506 }
1507 }
1508
1509 void share(const Shareable &d) { share(d.mData); }
1510
1511 void attachCopy(const D *d) {
1512 AssertMsg(d, ("data to copy must not be NULL"));
1513 if (d)
1514 attach(new D(*d));
1515 }
1516
1517 void attachCopy(const Shareable &d) {
1518 attachCopy(d.mData);
1519 }
1520
1521 virtual D *detach() {
1522 D *d = mData;
1523 mData = NULL;
1524 mIsShared = false;
1525 return d;
1526 }
1527
1528 D *data() const {
1529 return mData;
1530 }
1531
1532 D *operator->() const {
1533 AssertMsg(mData, ("data must not be NULL"));
1534 return mData;
1535 }
1536
1537 bool isNull() const { return mData == NULL; }
1538 bool operator!() const { return isNull(); }
1539
1540 bool isShared() const { return mIsShared; }
1541
1542protected:
1543
1544 D *mData;
1545 bool mIsShared;
1546};
1547
1548/// @todo (dmik) remove after we switch to VirtualBoxBaseNEXT completely
1549/**
1550 * Simple template that enhances Shareable<> and supports data
1551 * backup/rollback/commit (using the copy constructor of the managed data
1552 * structure).
1553 */
1554template<class D>
1555class Backupable : public Shareable<D>
1556{
1557public:
1558
1559 Backupable() : Shareable<D> (), mBackupData(NULL) {}
1560
1561 void free()
1562 {
1563 AssertMsg(this->mData || !mBackupData, ("backup must be NULL if data is NULL"));
1564 rollback();
1565 Shareable<D>::free();
1566 }
1567
1568 D *detach()
1569 {
1570 AssertMsg(this->mData || !mBackupData, ("backup must be NULL if data is NULL"));
1571 rollback();
1572 return Shareable<D>::detach();
1573 }
1574
1575 void share(const Backupable &d)
1576 {
1577 AssertMsg(!d.isBackedUp(), ("data to share must not be backed up"));
1578 if (!d.isBackedUp())
1579 Shareable<D>::share(d.mData);
1580 }
1581
1582 /**
1583 * Stores the current data pointer in the backup area, allocates new data
1584 * using the copy constructor on current data and makes new data active.
1585 */
1586 void backup()
1587 {
1588 AssertMsg(this->mData, ("data must not be NULL"));
1589 if (this->mData && !mBackupData)
1590 {
1591 D *pNewData = new D(*this->mData);
1592 mBackupData = this->mData;
1593 this->mData = pNewData;
1594 }
1595 }
1596
1597 /**
1598 * Deletes new data created by #backup() and restores previous data pointer
1599 * stored in the backup area, making it active again.
1600 */
1601 void rollback()
1602 {
1603 if (this->mData && mBackupData)
1604 {
1605 delete this->mData;
1606 this->mData = mBackupData;
1607 mBackupData = NULL;
1608 }
1609 }
1610
1611 /**
1612 * Commits current changes by deleting backed up data and clearing up the
1613 * backup area. The new data pointer created by #backup() remains active
1614 * and becomes the only managed pointer.
1615 *
1616 * This method is much faster than #commitCopy() (just a single pointer
1617 * assignment operation), but makes the previous data pointer invalid
1618 * (because it is freed). For this reason, this method must not be
1619 * used if it's possible that data managed by this instance is shared with
1620 * some other Shareable instance. See #commitCopy().
1621 */
1622 void commit()
1623 {
1624 if (this->mData && mBackupData)
1625 {
1626 if (!this->mIsShared)
1627 delete mBackupData;
1628 mBackupData = NULL;
1629 this->mIsShared = false;
1630 }
1631 }
1632
1633 /**
1634 * Commits current changes by assigning new data to the previous data
1635 * pointer stored in the backup area using the assignment operator.
1636 * New data is deleted, the backup area is cleared and the previous data
1637 * pointer becomes active and the only managed pointer.
1638 *
1639 * This method is slower than #commit(), but it keeps the previous data
1640 * pointer valid (i.e. new data is copied to the same memory location).
1641 * For that reason it's safe to use this method on instances that share
1642 * managed data with other Shareable instances.
1643 */
1644 void commitCopy()
1645 {
1646 if (this->mData && mBackupData)
1647 {
1648 *mBackupData = *(this->mData);
1649 delete this->mData;
1650 this->mData = mBackupData;
1651 mBackupData = NULL;
1652 }
1653 }
1654
1655 void assignCopy(const D *pData)
1656 {
1657 AssertMsg(this->mData, ("data must not be NULL"));
1658 AssertMsg(pData, ("data to copy must not be NULL"));
1659 if (this->mData && pData)
1660 {
1661 if (!mBackupData)
1662 {
1663 D *pNewData = new D(*pData);
1664 mBackupData = this->mData;
1665 this->mData = pNewData;
1666 }
1667 else
1668 *this->mData = *pData;
1669 }
1670 }
1671
1672 void assignCopy(const Backupable &d)
1673 {
1674 assignCopy(d.mData);
1675 }
1676
1677 bool isBackedUp() const
1678 {
1679 return mBackupData != NULL;
1680 }
1681
1682 D *backedUpData() const
1683 {
1684 return mBackupData;
1685 }
1686
1687protected:
1688
1689 D *mBackupData;
1690};
1691
1692#endif // !____H_VIRTUALBOXBASEIMPL
1693
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette