VirtualBox

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

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

Main: kill VirtualBoxBaseWithTypedChildren template and rework Medium to no longer use it; adjust Snapshot for consistency

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