VirtualBox

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

Last change on this file since 4071 was 4071, checked in by vboxsync, 17 years ago

Biggest check-in ever. New source code headers for all (C) innotek files.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 65.6 KB
Line 
1/** @file
2 *
3 * VirtualBox COM base classes definition
4 */
5
6/*
7 * Copyright (C) 2006-2007 innotek GmbH
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 as published by the Free Software Foundation,
13 * in version 2 as it comes in the "COPYING" file of the VirtualBox OSE
14 * distribution. VirtualBox OSE is distributed in the hope that it will
15 * be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18#ifndef ____H_VIRTUALBOXBASEIMPL
19#define ____H_VIRTUALBOXBASEIMPL
20
21#include "VBox/com/string.h"
22#include "VBox/com/Guid.h"
23#include "VBox/com/ptr.h"
24#include "VBox/com/ErrorInfo.h"
25
26#include "VBox/com/VirtualBox.h"
27
28#include "AutoLock.h"
29
30using namespace com;
31using util::AutoLock;
32using util::AutoReaderLock;
33using util::AutoMultiLock;
34
35#include <iprt/cdefs.h>
36#include <iprt/critsect.h>
37
38#include <list>
39#include <map>
40
41#if defined (RT_OS_WINDOWS)
42
43#include <atlcom.h>
44
45// use a special version of the singleton class factory,
46// see KB811591 in msdn for more info.
47
48#undef DECLARE_CLASSFACTORY_SINGLETON
49#define DECLARE_CLASSFACTORY_SINGLETON(obj) DECLARE_CLASSFACTORY_EX(CMyComClassFactorySingleton<obj>)
50
51template <class T>
52class CMyComClassFactorySingleton : public CComClassFactory
53{
54public:
55 CMyComClassFactorySingleton() : m_hrCreate(S_OK){}
56 virtual ~CMyComClassFactorySingleton(){}
57 // IClassFactory
58 STDMETHOD(CreateInstance)(LPUNKNOWN pUnkOuter, REFIID riid, void** ppvObj)
59 {
60 HRESULT hRes = E_POINTER;
61 if (ppvObj != NULL)
62 {
63 *ppvObj = NULL;
64 // Aggregation is not supported in singleton objects.
65 ATLASSERT(pUnkOuter == NULL);
66 if (pUnkOuter != NULL)
67 hRes = CLASS_E_NOAGGREGATION;
68 else
69 {
70 if (m_hrCreate == S_OK && m_spObj == NULL)
71 {
72 Lock();
73 __try
74 {
75 // Fix: The following If statement was moved inside the __try statement.
76 // Did another thread arrive here first?
77 if (m_hrCreate == S_OK && m_spObj == NULL)
78 {
79 // lock the module to indicate activity
80 // (necessary for the monitor shutdown thread to correctly
81 // terminate the module in case when CreateInstance() fails)
82 _pAtlModule->Lock();
83 CComObjectCached<T> *p;
84 m_hrCreate = CComObjectCached<T>::CreateInstance(&p);
85 if (SUCCEEDED(m_hrCreate))
86 {
87 m_hrCreate = p->QueryInterface(IID_IUnknown, (void**)&m_spObj);
88 if (FAILED(m_hrCreate))
89 {
90 delete p;
91 }
92 }
93 _pAtlModule->Unlock();
94 }
95 }
96 __finally
97 {
98 Unlock();
99 }
100 }
101 if (m_hrCreate == S_OK)
102 {
103 hRes = m_spObj->QueryInterface(riid, ppvObj);
104 }
105 else
106 {
107 hRes = m_hrCreate;
108 }
109 }
110 }
111 return hRes;
112 }
113 HRESULT m_hrCreate;
114 CComPtr<IUnknown> m_spObj;
115};
116
117#endif // defined (RT_OS_WINDOWS)
118
119// macros
120////////////////////////////////////////////////////////////////////////////////
121
122/**
123 * A special version of the Assert macro to be used within VirtualBoxBase
124 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
125 *
126 * In the debug build, this macro is equivalent to Assert.
127 * In the release build, this macro uses |setError (E_FAIL, ...)| to set the
128 * error info from the asserted expression.
129 *
130 * @see VirtualBoxSupportErrorInfoImpl::setError
131 *
132 * @param expr Expression which should be true.
133 */
134#if defined (DEBUG)
135#define ComAssert(expr) Assert (expr)
136#else
137#define ComAssert(expr) \
138 do { \
139 if (!(expr)) \
140 setError (E_FAIL, "Assertion failed: [%s] at '%s' (%d) in %s.\n" \
141 "Please contact the product vendor!", \
142 #expr, __FILE__, __LINE__, __PRETTY_FUNCTION__); \
143 } while (0)
144#endif
145
146/**
147 * A special version of the AssertMsg macro to be used within VirtualBoxBase
148 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
149 *
150 * See ComAssert for more info.
151 *
152 * @param expr Expression which should be true.
153 * @param a printf argument list (in parenthesis).
154 */
155#if defined (DEBUG)
156#define ComAssertMsg(expr, a) AssertMsg (expr, a)
157#else
158#define ComAssertMsg(expr, a) \
159 do { \
160 if (!(expr)) \
161 setError (E_FAIL, "Assertion failed: [%s] at '%s' (%d) in %s.\n" \
162 "%s.\n" \
163 "Please contact the product vendor!", \
164 #expr, __FILE__, __LINE__, __PRETTY_FUNCTION__, Utf8StrFmt a .raw()); \
165 } while (0)
166#endif
167
168/**
169 * A special version of the AssertRC macro to be used within VirtualBoxBase
170 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
171 *
172 * See ComAssert for more info.
173 *
174 * @param vrc VBox status code.
175 */
176#if defined (DEBUG)
177#define ComAssertRC(vrc) AssertRC (vrc)
178#else
179#define ComAssertRC(vrc) ComAssertMsgRC (vrc, ("%Vra", vrc))
180#endif
181
182/**
183 * A special version of the AssertMsgRC macro to be used within VirtualBoxBase
184 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
185 *
186 * See ComAssert for more info.
187 *
188 * @param vrc VBox status code.
189 * @param msg printf argument list (in parenthesis).
190 */
191#if defined (DEBUG)
192#define ComAssertMsgRC(vrc, msg) AssertMsgRC (vrc, msg)
193#else
194#define ComAssertMsgRC(vrc, msg) ComAssertMsg (VBOX_SUCCESS (vrc), msg)
195#endif
196
197
198/**
199 * A special version of the AssertFailed macro to be used within VirtualBoxBase
200 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
201 *
202 * See ComAssert for more info.
203 */
204#if defined (DEBUG)
205#define ComAssertFailed() AssertFailed()
206#else
207#define ComAssertFailed() \
208 do { \
209 setError (E_FAIL, "Assertion failed at '%s' (%d) in %s.\n" \
210 "Please contact the product vendor!", \
211 __FILE__, __LINE__, __PRETTY_FUNCTION__); \
212 } while (0)
213#endif
214
215/**
216 * A special version of the AssertMsgFailed macro to be used within VirtualBoxBase
217 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
218 *
219 * See ComAssert for more info.
220 *
221 * @param a printf argument list (in parenthesis).
222 */
223#if defined (DEBUG)
224#define ComAssertMsgFailed(a) AssertMsgFailed(a)
225#else
226#define ComAssertMsgFailed(a) \
227 do { \
228 setError (E_FAIL, "Assertion failed at '%s' (%d) in %s.\n" \
229 "%s.\n" \
230 "Please contact the product vendor!", \
231 __FILE__, __LINE__, __PRETTY_FUNCTION__, Utf8StrFmt a .raw()); \
232 } while (0)
233#endif
234
235/**
236 * A special version of the AssertComRC macro to be used within VirtualBoxBase
237 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
238 *
239 * See ComAssert for more info.
240 *
241 * @param rc COM result code
242 */
243#if defined (DEBUG)
244#define ComAssertComRC(rc) AssertComRC (rc)
245#else
246#define ComAssertComRC(rc) ComAssertMsg (SUCCEEDED (rc), ("COM RC = 0x%08X\n", rc))
247#endif
248
249
250/** Special version of ComAssert that returns ret if expr fails */
251#define ComAssertRet(expr, ret) \
252 do { ComAssert (expr); if (!(expr)) return (ret); } while (0)
253/** Special version of ComAssertMsg that returns ret if expr fails */
254#define ComAssertMsgRet(expr, a, ret) \
255 do { ComAssertMsg (expr, a); if (!(expr)) return (ret); } while (0)
256/** Special version of ComAssertRC that returns ret if vrc does not succeed */
257#define ComAssertRCRet(vrc, ret) \
258 do { ComAssertRC (vrc); if (!VBOX_SUCCESS (vrc)) return (ret); } while (0)
259/** Special version of ComAssertMsgRC that returns ret if vrc does not succeed */
260#define ComAssertMsgRCRet(vrc, msg, ret) \
261 do { ComAssertMsgRC (vrc, msg); if (!VBOX_SUCCESS (vrc)) return (ret); } while (0)
262/** Special version of ComAssertFailed that returns ret */
263#define ComAssertFailedRet(ret) \
264 do { ComAssertFailed(); return (ret); } while (0)
265/** Special version of ComAssertMsgFailed that returns ret */
266#define ComAssertMsgFailedRet(msg, ret) \
267 do { ComAssertMsgFailed (msg); return (ret); } while (0)
268/** Special version of ComAssertComRC that returns ret if rc does not succeed */
269#define ComAssertComRCRet(rc, ret) \
270 do { ComAssertComRC (rc); if (!SUCCEEDED (rc)) return (ret); } while (0)
271/** Special version of ComAssertComRC that returns rc if rc does not succeed */
272#define ComAssertComRCRetRC(rc) \
273 do { ComAssertComRC (rc); if (!SUCCEEDED (rc)) return (rc); } while (0)
274
275
276/** Special version of ComAssert that evaulates eval and breaks if expr fails */
277#define ComAssertBreak(expr, eval) \
278 if (1) { ComAssert (expr); if (!(expr)) { eval; break; } } else do {} while (0)
279/** Special version of ComAssertMsg that evaulates eval and breaks if expr fails */
280#define ComAssertMsgBreak(expr, a, eval) \
281 if (1) { ComAssertMsg (expr, a); if (!(expr)) { eval; break; } } else do {} while (0)
282/** Special version of ComAssertRC that evaulates eval and breaks if vrc does not succeed */
283#define ComAssertRCBreak(vrc, eval) \
284 if (1) { ComAssertRC (vrc); if (!VBOX_SUCCESS (vrc)) { eval; break; } } else do {} while (0)
285/** Special version of ComAssertMsgRC that evaulates eval and breaks if vrc does not succeed */
286#define ComAssertMsgRCBreak(vrc, msg, eval) \
287 if (1) { ComAssertMsgRC (vrc, msg); if (!VBOX_SUCCESS (vrc)) { eval; break; } } else do {} while (0)
288/** Special version of ComAssertFailed that evaulates eval and breaks */
289#define ComAssertFailedBreak(eval) \
290 if (1) { ComAssertFailed(); { eval; break; } } else do {} while (0)
291/** Special version of ComAssertMsgFailed that evaulates eval and breaks */
292#define ComAssertMsgFailedBreak(msg, eval) \
293 if (1) { ComAssertMsgFailed (msg); { eval; break; } } else do {} while (0)
294/** Special version of ComAssertComRC that evaulates eval and breaks if rc does not succeed */
295#define ComAssertComRCBreak(rc, eval) \
296 if (1) { ComAssertComRC (rc); if (!SUCCEEDED (rc)) { eval; break; } } else do {} while (0)
297/** Special version of ComAssertComRC that just breaks if rc does not succeed */
298#define ComAssertComRCBreakRC(rc) \
299 if (1) { ComAssertComRC (rc); if (!SUCCEEDED (rc)) { break; } } else do {} while (0)
300
301/// @todo (dmik) remove after we switch to VirtualBoxBaseNEXT completely
302/**
303 * Checks whether this object is ready or not. Objects are typically ready
304 * after they are successfully created by their parent objects and become
305 * not ready when the respective parent itsef becomes not ready or gets
306 * destroyed while a reference to the child is still held by the caller
307 * (which prevents it from destruction).
308 *
309 * When this object is not ready, the macro sets error info and returns
310 * E_UNEXPECTED (the translatable error message is defined in null context).
311 * Otherwise, the macro does nothing.
312 *
313 * This macro <b>must</b> be used at the beginning of all interface methods
314 * (right after entering the class lock) in classes derived from both
315 * VirtualBoxBase and VirtualBoxSupportErrorInfoImpl.
316 */
317#define CHECK_READY() \
318 do { \
319 if (!isReady()) \
320 return setError (E_UNEXPECTED, tr ("The object is not ready")); \
321 } while (0)
322
323/**
324 * Declares an empty construtor and destructor for the given class.
325 * This is useful to prevent the compiler from generating the default
326 * ctor and dtor, which in turn allows to use forward class statements
327 * (instead of including their header files) when declaring data members of
328 * non-fundamental types with constructors (which are always called implicitly
329 * by constructors and by the destructor of the class).
330 *
331 * This macro is to be palced within (the public section of) the class
332 * declaration. Its counterpart, DEFINE_EMPTY_CTOR_DTOR, must be placed
333 * somewhere in one of the translation units (usually .cpp source files).
334 *
335 * @param cls class to declare a ctor and dtor for
336 */
337#define DECLARE_EMPTY_CTOR_DTOR(cls) cls(); ~cls();
338
339/**
340 * Defines an empty construtor and destructor for the given class.
341 * See DECLARE_EMPTY_CTOR_DTOR for more info.
342 */
343#define DEFINE_EMPTY_CTOR_DTOR(cls) \
344 cls::cls () {}; cls::~cls () {};
345
346////////////////////////////////////////////////////////////////////////////////
347
348namespace stdx
349{
350 /**
351 * A wrapper around the container that owns pointers it stores.
352 *
353 * @note
354 * Ownership is recognized only when destructing the container!
355 * Pointers are not deleted when erased using erase() etc.
356 *
357 * @param container
358 * class that meets Container requirements (for example, an instance of
359 * std::list<>, std::vector<> etc.). The given class must store
360 * pointers (for example, std::list <MyType *>).
361 */
362 template <typename container>
363 class ptr_container : public container
364 {
365 public:
366 ~ptr_container()
367 {
368 for (typename container::iterator it = container::begin();
369 it != container::end();
370 ++ it)
371 delete (*it);
372 }
373 };
374};
375
376////////////////////////////////////////////////////////////////////////////////
377
378class ATL_NO_VTABLE VirtualBoxBaseNEXT_base
379#ifdef RT_OS_WINDOWS
380 : public CComObjectRootEx <CComMultiThreadModel>
381#else
382 : public CComObjectRootEx
383#endif
384 , public AutoLock::Lockable
385{
386public:
387
388 enum State { NotReady, Ready, InInit, InUninit, InitFailed, Limited };
389
390protected:
391
392 VirtualBoxBaseNEXT_base();
393 virtual ~VirtualBoxBaseNEXT_base();
394
395public:
396
397 // AutoLock::Lockable interface
398 virtual AutoLock::Handle *lockHandle() const;
399
400 /**
401 * Virtual unintialization method.
402 * Must be called by all implementations (COM classes) when the last
403 * reference to the object is released, before calling the destructor.
404 * Also, this method is called automatically by the uninit() method of the
405 * parent of this object, when this object is a dependent child of a class
406 * derived from VirtualBoxBaseWithChildren (@sa
407 * VirtualBoxBaseWithChildren::addDependentChild).
408 */
409 virtual void uninit() {}
410
411 virtual HRESULT addCaller (State *aState = NULL, bool aLimited = false);
412 virtual void releaseCaller();
413
414 /**
415 * Adds a limited caller. This method is equivalent to doing
416 * <tt>addCaller (aState, true)</tt>, but it is preferred because
417 * provides better self-descriptiveness. See #addCaller() for more info.
418 */
419 HRESULT addLimitedCaller (State *aState = NULL)
420 {
421 return addCaller (aState, true /* aLimited */);
422 }
423
424 /**
425 * Smart class that automatically increases the number of callers of the
426 * given VirtualBoxBase object when an instance is constructed and decreases
427 * it back when the created instance goes out of scope (i.e. gets destroyed).
428 *
429 * If #rc() returns a failure after the instance creation, it means that
430 * the managed VirtualBoxBase object is not Ready, or in any other invalid
431 * state, so that the caller must not use the object and can return this
432 * failed result code to the upper level.
433 *
434 * See VirtualBoxBase::addCaller(), VirtualBoxBase::addLimitedCaller() and
435 * VirtualBoxBase::releaseCaller() for more details about object callers.
436 *
437 * @param aLimited |false| if this template should use
438 * VirtualiBoxBase::addCaller() calls to add callers, or
439 * |true| if VirtualiBoxBase::addLimitedCaller() should be
440 * used.
441 *
442 * @note It is preferrable to use the AutoCaller and AutoLimitedCaller
443 * classes than specify the @a aLimited argument, for better
444 * self-descriptiveness.
445 */
446 template <bool aLimited>
447 class AutoCallerBase
448 {
449 public:
450
451 /**
452 * Increases the number of callers of the given object
453 * by calling VirtualBoxBase::addCaller().
454 *
455 * @param aObj Object to add a caller to. If NULL, this
456 * instance is effectively turned to no-op (where
457 * rc() will return S_OK and state() will be
458 * NotReady).
459 */
460 AutoCallerBase (VirtualBoxBaseNEXT_base *aObj)
461 : mObj (aObj)
462 , mRC (S_OK)
463 , mState (NotReady)
464 {
465 if (mObj)
466 mRC = mObj->addCaller (&mState, aLimited);
467 }
468
469 /**
470 * If the number of callers was successfully increased,
471 * decreases it using VirtualBoxBase::releaseCaller(), otherwise
472 * does nothing.
473 */
474 ~AutoCallerBase()
475 {
476 if (mObj && SUCCEEDED (mRC))
477 mObj->releaseCaller();
478 }
479
480 /**
481 * Stores the result code returned by VirtualBoxBase::addCaller()
482 * after instance creation or after the last #add() call. A successful
483 * result code means the number of callers was successfully increased.
484 */
485 HRESULT rc() const { return mRC; }
486
487 /**
488 * Returns |true| if |SUCCEEDED (rc())| is |true|, for convenience.
489 * |true| means the number of callers was successfully increased.
490 */
491 bool isOk() const { return SUCCEEDED (mRC); }
492
493 /**
494 * Stores the object state returned by VirtualBoxBase::addCaller()
495 * after instance creation or after the last #add() call.
496 */
497 State state() const { return mState; }
498
499 /**
500 * Temporarily decreases the number of callers of the managed object.
501 * May only be called if #isOk() returns |true|. Note that #rc() will
502 * return E_FAIL after this method succeeds.
503 */
504 void release()
505 {
506 Assert (SUCCEEDED (mRC));
507 if (SUCCEEDED (mRC))
508 {
509 if (mObj)
510 mObj->releaseCaller();
511 mRC = E_FAIL;
512 }
513 }
514
515 /**
516 * Restores the number of callers decreased by #release(). May only
517 * be called after #release().
518 */
519 void add()
520 {
521 Assert (!SUCCEEDED (mRC));
522 if (mObj && !SUCCEEDED (mRC))
523 mRC = mObj->addCaller (&mState, aLimited);
524 }
525
526 private:
527
528 DECLARE_CLS_COPY_CTOR_ASSIGN_NOOP (AutoCallerBase)
529 DECLARE_CLS_NEW_DELETE_NOOP (AutoCallerBase)
530
531 VirtualBoxBaseNEXT_base *mObj;
532 HRESULT mRC;
533 State mState;
534 };
535
536 /**
537 * Smart class that automatically increases the number of normal
538 * (non-limited) callers of the given VirtualBoxBase object when an
539 * instance is constructed and decreases it back when the created instance
540 * goes out of scope (i.e. gets destroyed).
541 *
542 * A typical usage pattern to declare a normal method of some object
543 * (i.e. a method that is valid only when the object provides its
544 * full functionality) is:
545 * <code>
546 * STDMETHODIMP Component::Foo()
547 * {
548 * AutoCaller autoCaller (this);
549 * CheckComRCReturnRC (autoCaller.rc());
550 * ...
551 * </code>
552 *
553 * Using this class is equivalent to using the AutoCallerBase template
554 * with the @a aLimited argument set to |false|, but this class is
555 * preferred because provides better self-descriptiveness.
556 *
557 * See AutoCallerBase for more information about auto caller functionality.
558 */
559 typedef AutoCallerBase <false> AutoCaller;
560
561 /**
562 * Smart class that automatically increases the number of limited callers
563 * of the given VirtualBoxBase object when an instance is constructed and
564 * decreases it back when the created instance goes out of scope (i.e.
565 * gets destroyed).
566 *
567 * A typical usage pattern to declare a limited method of some object
568 * (i.e. a method that is valid even if the object doesn't provide its
569 * full functionality) is:
570 * <code>
571 * STDMETHODIMP Component::Bar()
572 * {
573 * AutoLimitedCaller autoCaller (this);
574 * CheckComRCReturnRC (autoCaller.rc());
575 * ...
576 * </code>
577 *
578 * Using this class is equivalent to using the AutoCallerBase template
579 * with the @a aLimited argument set to |true|, but this class is
580 * preferred because provides better self-descriptiveness.
581 *
582 * See AutoCallerBase for more information about auto caller functionality.
583 */
584 typedef AutoCallerBase <true> AutoLimitedCaller;
585
586protected:
587
588 /**
589 * Smart class to enclose the state transition NotReady->InInit->Ready.
590 *
591 * Instances must be created at the beginning of init() methods of
592 * VirtualBoxBase subclasses as a stack-based variable using |this| pointer
593 * as the argument. When this variable is created it automatically places
594 * the object to the InInit state.
595 *
596 * When the created variable goes out of scope (i.e. gets destroyed),
597 * depending on the success status of this initialization span, it either
598 * places the object to the Ready state or calls the object's
599 * VirtualBoxBase::uninit() method which is supposed to place the object
600 * back to the NotReady state using the AutoUninitSpan class.
601 *
602 * The initial success status of the initialization span is determined by
603 * the @a aSuccess argument of the AutoInitSpan constructor (|false| by
604 * default). Inside the initialization span, the success status can be set
605 * to |true| using #setSucceeded() or to |false| using #setFailed(). Please
606 * don't forget to set the correct success status before letting the
607 * AutoInitSpan variable go out of scope (for example, by performing an
608 * early return from the init() method)!
609 *
610 * Note that if an instance of this class gets constructed when the
611 * object is in the state other than NotReady, #isOk() returns |false| and
612 * methods of this class do nothing: the state transition is not performed.
613 *
614 * A typical usage pattern is:
615 * <code>
616 * HRESULT Component::init()
617 * {
618 * AutoInitSpan autoInitSpan (this);
619 * AssertReturn (autoInitSpan.isOk(), E_UNEXPECTED);
620 * ...
621 * if (FAILED (rc))
622 * return rc;
623 * ...
624 * if (SUCCEEDED (rc))
625 * autoInitSpan.setSucceeded();
626 * return rc;
627 * }
628 * </code>
629 *
630 * @note Never create instances of this class outside init() methods of
631 * VirtualBoxBase subclasses and never pass anything other than |this| as
632 * the argument to the constructor!
633 */
634 class AutoInitSpan
635 {
636 public:
637
638 enum Status { Failed = 0x0, Succeeded = 0x1, Limited = 0x2 };
639
640 AutoInitSpan (VirtualBoxBaseNEXT_base *aObj, Status aStatus = Failed);
641 ~AutoInitSpan();
642
643 /**
644 * Returns |true| if this instance has been created at the right moment
645 * (when the object was in the NotReady state) and |false| otherwise.
646 */
647 bool isOk() const { return mOk; }
648
649 /**
650 * Sets the initialization status to Succeeded to indicates successful
651 * initialization. The AutoInitSpan destructor will place the managed
652 * VirtualBoxBase object to the Ready state.
653 */
654 void setSucceeded() { mStatus = Succeeded; }
655
656 /**
657 * Sets the initialization status to Succeeded to indicate limited
658 * (partly successful) initialization. The AutoInitSpan destructor will
659 * place the managed VirtualBoxBase object to the Limited state.
660 */
661 void setLimited() { mStatus = Limited; }
662
663 /**
664 * Sets the initialization status to Failure to indicates failed
665 * initialization. The AutoInitSpan destructor will place the managed
666 * VirtualBoxBase object to the InitFailed state and will automatically
667 * call its uninit() method which is supposed to place the object back
668 * to the NotReady state using AutoUninitSpan.
669 */
670 void setFailed() { mStatus = Failed; }
671
672 /** Returns the current initialization status. */
673 Status status() { return mStatus; }
674
675 private:
676
677 DECLARE_CLS_COPY_CTOR_ASSIGN_NOOP (AutoInitSpan)
678 DECLARE_CLS_NEW_DELETE_NOOP (AutoInitSpan)
679
680 VirtualBoxBaseNEXT_base *mObj;
681 Status mStatus : 3; // must be at least total number of bits + 1 (sign)
682 bool mOk : 1;
683 };
684
685 /**
686 * Smart class to enclose the state transition Limited->InInit->Ready.
687 *
688 * Instances must be created at the beginning of methods of VirtualBoxBase
689 * subclasses that try to re-initialize the object to bring it to the
690 * Ready state (full functionality) after partial initialization
691 * (limited functionality)>, as a stack-based variable using |this| pointer
692 * as the argument. When this variable is created it automatically places
693 * the object to the InInit state.
694 *
695 * When the created variable goes out of scope (i.e. gets destroyed),
696 * depending on the success status of this initialization span, it either
697 * places the object to the Ready state or brings it back to the Limited
698 * state.
699 *
700 * The initial success status of the re-initialization span is |false|.
701 * In order to make it successful, #setSucceeded() must be called before
702 * the instance is destroyed.
703 *
704 * Note that if an instance of this class gets constructed when the
705 * object is in the state other than Limited, #isOk() returns |false| and
706 * methods of this class do nothing: the state transition is not performed.
707 *
708 * A typical usage pattern is:
709 * <code>
710 * HRESULT Component::reinit()
711 * {
712 * AutoReadySpan autoReadySpan (this);
713 * AssertReturn (autoReadySpan.isOk(), E_UNEXPECTED);
714 * ...
715 * if (FAILED (rc))
716 * return rc;
717 * ...
718 * if (SUCCEEDED (rc))
719 * autoReadySpan.setSucceeded();
720 * return rc;
721 * }
722 * </code>
723 *
724 * @note Never create instances of this class outside re-initialization
725 * methods of VirtualBoxBase subclasses and never pass anything other than
726 * |this| as the argument to the constructor!
727 */
728 class AutoReadySpan
729 {
730 public:
731
732 AutoReadySpan (VirtualBoxBaseNEXT_base *aObj);
733 ~AutoReadySpan();
734
735 /**
736 * Returns |true| if this instance has been created at the right moment
737 * (when the object was in the Limited state) and |false| otherwise.
738 */
739 bool isOk() const { return mOk; }
740
741 /**
742 * Sets the re-initialization status to Succeeded to indicates
743 * successful re-initialization. The AutoReadySpan destructor will
744 * place the managed VirtualBoxBase object to the Ready state.
745 */
746 void setSucceeded() { mSucceeded = true; }
747
748 private:
749
750 DECLARE_CLS_COPY_CTOR_ASSIGN_NOOP (AutoReadySpan)
751 DECLARE_CLS_NEW_DELETE_NOOP (AutoReadySpan)
752
753 VirtualBoxBaseNEXT_base *mObj;
754 bool mSucceeded : 1;
755 bool mOk : 1;
756 };
757
758 /**
759 * Smart class to enclose the state transition Ready->InUnnit->NotReady or
760 * InitFailed->InUnnit->NotReady.
761 *
762 * Must be created at the beginning of uninit() methods of VirtualBoxBase
763 * subclasses as a stack-based variable using |this| pointer as the argument.
764 * When this variable is created it automatically places the object to the
765 * InUninit state, unless it is already in the NotReady state as indicated
766 * by #uninitDone() returning |true|. In the latter case, the uninit()
767 * method must immediately return because there should be nothing to
768 * uninitialize.
769 *
770 * When this variable goes out of scope (i.e. gets destroyed), it places
771 * the object to the NotReady state.
772 *
773 * A typical usage pattern is:
774 * <code>
775 * void Component::uninit()
776 * {
777 * AutoUninitSpan autoUninitSpan (this);
778 * if (autoUninitSpan.uninitDone())
779 * retrun;
780 * ...
781 * </code>
782 *
783 * @note Never create instances of this class outside uninit() methods and
784 * never pass anything other than |this| as the argument to the constructor!
785 */
786 class AutoUninitSpan
787 {
788 public:
789
790 AutoUninitSpan (VirtualBoxBaseNEXT_base *aObj);
791 ~AutoUninitSpan();
792
793 /** |true| when uninit() is called as a result of init() failure */
794 bool initFailed() { return mInitFailed; }
795
796 /** |true| when uninit() has already been called (so the object is NotReady) */
797 bool uninitDone() { return mUninitDone; }
798
799 private:
800
801 DECLARE_CLS_COPY_CTOR_ASSIGN_NOOP (AutoUninitSpan)
802 DECLARE_CLS_NEW_DELETE_NOOP (AutoUninitSpan)
803
804 VirtualBoxBaseNEXT_base *mObj;
805 bool mInitFailed : 1;
806 bool mUninitDone : 1;
807 };
808
809private:
810
811 void setState (State aState)
812 {
813 Assert (mState != aState);
814 mState = aState;
815 mStateChangeThread = RTThreadSelf();
816 }
817
818 /** Primary state of this object */
819 State mState;
820 /** Thread that caused the last state change */
821 RTTHREAD mStateChangeThread;
822 /** Total number of active calls to this object */
823 unsigned mCallers;
824 /** Semaphore posted when the number of callers drops to zero */
825 RTSEMEVENT mZeroCallersSem;
826 /** Semaphore posted when the object goes from InInit some other state */
827 RTSEMEVENTMULTI mInitDoneSem;
828 /** Number of threads waiting for mInitDoneSem */
829 unsigned mInitDoneSemUsers;
830
831 /** Protects access to state related data members */
832 RTCRITSECT mStateLock;
833
834 /** User-level object lock for subclasses */
835 mutable AutoLock::Handle *mObjectLock;
836};
837
838/**
839 * This macro adds the error info support to methods of the VirtualBoxBase
840 * class (by overriding them). Place it to the public section of the
841 * VirtualBoxBase subclass and the following methods will set the extended
842 * error info in case of failure instead of just returning the result code:
843 *
844 * <ul>
845 * <li>VirtualBoxBase::addCaller()
846 * </ul>
847 *
848 * @note The given VirtualBoxBase subclass must also inherit from both
849 * VirtualBoxSupportErrorInfoImpl and VirtualBoxSupportTranslation templates!
850 *
851 * @param C VirtualBoxBase subclass to add the error info support to
852 */
853#define VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT(C) \
854 virtual HRESULT addCaller (VirtualBoxBaseNEXT_base::State *aState = NULL, \
855 bool aLimited = false) \
856 { \
857 VirtualBoxBaseNEXT_base::State state; \
858 HRESULT rc = VirtualBoxBaseNEXT_base::addCaller (&state, aLimited); \
859 if (FAILED (rc)) \
860 { \
861 if (state == VirtualBoxBaseNEXT_base::Limited) \
862 rc = setError (rc, tr ("The object functonality is limited")); \
863 else \
864 rc = setError (rc, tr ("The object is not ready")); \
865 } \
866 if (aState) \
867 *aState = state; \
868 return rc; \
869 } \
870
871////////////////////////////////////////////////////////////////////////////////
872
873/// @todo (dmik) remove after we switch to VirtualBoxBaseNEXT completely
874class ATL_NO_VTABLE VirtualBoxBase : public VirtualBoxBaseNEXT_base
875//#ifdef RT_OS_WINDOWS
876// : public CComObjectRootEx<CComMultiThreadModel>
877//#else
878// : public CComObjectRootEx
879//#endif
880{
881
882public:
883 VirtualBoxBase()
884 {
885 mReady = false;
886 }
887 virtual ~VirtualBoxBase()
888 {
889 }
890
891 /**
892 * Virtual unintialization method. Called during parent object's
893 * uninitialization, if the given subclass instance is a dependent child of
894 * a class dervived from VirtualBoxBaseWithChildren (@sa
895 * VirtualBoxBaseWithChildren::addDependentChild). In this case, this
896 * method's impelemtation must call setReady (false),
897 */
898 virtual void uninit() {}
899
900
901 // sets the ready state of the object
902 void setReady(bool isReady)
903 {
904 mReady = isReady;
905 }
906 // get the ready state of the object
907 bool isReady()
908 {
909 return mReady;
910 }
911
912 static const char *translate (const char *context, const char *sourceText,
913 const char *comment = 0);
914
915private:
916
917 // flag determining whether an object is ready
918 // for usage, i.e. methods may be called
919 bool mReady;
920 // mutex semaphore to lock the object
921};
922
923/**
924 * Temporary class to disable deprecated methods of VirtualBoxBase.
925 * Can be used as a base for components that are completely switched to
926 * the new locking scheme (VirtualBoxBaseNEXT_base).
927 *
928 * @todo remove after we switch to VirtualBoxBaseNEXT completely.
929 */
930class VirtualBoxBaseNEXT : public VirtualBoxBase
931{
932private:
933
934 void lock();
935 void unlock();
936 void setReady (bool isReady);
937 bool isReady();
938};
939
940////////////////////////////////////////////////////////////////////////////////
941
942/** Helper for VirtualBoxSupportTranslation */
943class VirtualBoxSupportTranslationBase
944{
945protected:
946 static bool cutClassNameFrom__PRETTY_FUNCTION__ (char *prettyFunctionName);
947};
948
949/**
950 * This template implements the NLS string translation support for the
951 * given class by providing a #tr() function.
952 *
953 * @param C class that needs to support the string translation
954 *
955 * @note
956 * Every class that wants to use the #tr() function in its own methods must
957 * inherit from this template, regardless of whether its base class (if any)
958 * inherits from it or not! Otherwise, the translation service will not
959 * work correctly. However, the declaration of the resulting class must
960 * contain the VIRTUALBOXSUPPORTTRANSLATION_OVERRIDE(<ClassName>) macro
961 * if one of its base classes also inherits from this template (to resolve
962 * the ambiguity of the #tr() function).
963 */
964template <class C>
965class VirtualBoxSupportTranslation : virtual protected VirtualBoxSupportTranslationBase
966{
967public:
968
969 /**
970 * Translates the given text string according to the currently installed
971 * translation table and current context, which is determined by the
972 * class name. See VirtualBoxBase::translate() for more info.
973 *
974 * @param sourceText the string to translate
975 * @param comment the comment to the string (NULL means no comment)
976 *
977 * @return
978 * the translated version of the source string in UTF-8 encoding,
979 * or the source string itself if the translation is not found in
980 * the current context.
981 */
982 inline static const char *tr (const char *sourceText, const char *comment = 0)
983 {
984 return VirtualBoxBase::translate (getClassName(), sourceText, comment);
985 }
986
987protected:
988
989 static const char *getClassName()
990 {
991 static char fn [sizeof (__PRETTY_FUNCTION__) + 1];
992 if (!className)
993 {
994 strcpy (fn, __PRETTY_FUNCTION__);
995 cutClassNameFrom__PRETTY_FUNCTION__ (fn);
996 className = fn;
997 }
998 return className;
999 }
1000
1001private:
1002
1003 static const char *className;
1004};
1005
1006template <class C>
1007const char *VirtualBoxSupportTranslation <C>::className = NULL;
1008
1009/**
1010 * This macro must be invoked inside the public section of the declaration of
1011 * the class inherited from the VirtualBoxSupportTranslation template, in case
1012 * when one of its other base classes also inherits from that template. This is
1013 * necessary to resolve the ambiguity of the #tr() function.
1014 *
1015 * @param C class that inherits from the VirtualBoxSupportTranslation template
1016 * more than once (through its other base clases)
1017 */
1018#define VIRTUALBOXSUPPORTTRANSLATION_OVERRIDE(C) \
1019 inline static const char *tr (const char *sourceText, const char *comment = 0) \
1020 { \
1021 return VirtualBoxSupportTranslation <C>::tr (sourceText, comment); \
1022 }
1023
1024/**
1025 * A dummy macro that is used to shut down Qt's lupdate tool warnings
1026 * in some situations. This macro needs to be present inside (better at the
1027 * very beginning) of the declaration of the class that inherits from
1028 * VirtualBoxSupportTranslation template, to make lupdate happy.
1029 */
1030#define Q_OBJECT
1031
1032////////////////////////////////////////////////////////////////////////////////
1033
1034/**
1035 * Helper for the VirtualBoxSupportErrorInfoImpl template.
1036 */
1037class VirtualBoxSupportErrorInfoImplBase
1038{
1039 static HRESULT setErrorInternal (HRESULT aResultCode, const GUID &aIID,
1040 const Bstr &aComponent, const Bstr &aText,
1041 bool aPreserve);
1042
1043protected:
1044
1045 inline static HRESULT setError (HRESULT aResultCode, const GUID &aIID,
1046 const Bstr &aComponent,
1047 const Bstr &aText)
1048 {
1049 return setErrorInternal (aResultCode, aIID, aComponent, aText,
1050 false /* aPreserve */);
1051 }
1052
1053 inline static HRESULT addError (HRESULT aResultCode, const GUID &aIID,
1054 const Bstr &aComponent,
1055 const Bstr &aText)
1056 {
1057 return setErrorInternal (aResultCode, aIID, aComponent, aText,
1058 true /* aPreserve */);
1059 }
1060
1061 static HRESULT setError (HRESULT aResultCode, const GUID &aIID,
1062 const Bstr &aComponent,
1063 const char *aText, va_list aArgs)
1064 {
1065 return setErrorInternal (aResultCode, aIID, aComponent,
1066 Utf8StrFmt (aText, aArgs),
1067 false /* aPreserve */);
1068 }
1069
1070 static HRESULT addError (HRESULT aResultCode, const GUID &aIID,
1071 const Bstr &aComponent,
1072 const char *aText, va_list aArgs)
1073 {
1074 return setErrorInternal (aResultCode, aIID, aComponent,
1075 Utf8StrFmt (aText, aArgs),
1076 true /* aPreserve */);
1077 }
1078};
1079
1080/**
1081 * This template implements ISupportErrorInfo for the given component class
1082 * and provides the #setError() method to conveniently set the error information
1083 * from within interface methods' implementations.
1084 *
1085 * On Windows, the template argument must define a COM interface map using
1086 * BEGIN_COM_MAP / END_COM_MAP macros and this map must contain a
1087 * COM_INTERFACE_ENTRY(ISupportErrorInfo) definition. All interface entries
1088 * that follow it will be considered to support IErrorInfo, i.e. the
1089 * InterfaceSupportsErrorInfo() implementation will return S_OK for the
1090 * corresponding IID.
1091 *
1092 * On all platforms, the template argument must also define the following
1093 * method: |public static const wchar_t *C::getComponentName()|. See
1094 * #setError (HRESULT, const char *, ...) for a description on how it is
1095 * used.
1096 *
1097 * @param C
1098 * component class that implements one or more COM interfaces
1099 * @param I
1100 * default interface for the component. This interface's IID is used
1101 * by the shortest form of #setError, for convenience.
1102 */
1103template <class C, class I>
1104class ATL_NO_VTABLE VirtualBoxSupportErrorInfoImpl
1105 : protected VirtualBoxSupportErrorInfoImplBase
1106#if defined (RT_OS_WINDOWS)
1107 , public ISupportErrorInfo
1108#else
1109#endif
1110{
1111public:
1112
1113#if defined (RT_OS_WINDOWS)
1114 STDMETHOD(InterfaceSupportsErrorInfo) (REFIID riid)
1115 {
1116 const _ATL_INTMAP_ENTRY* pEntries = C::_GetEntries();
1117 Assert (pEntries);
1118 if (!pEntries)
1119 return S_FALSE;
1120
1121 BOOL bSupports = FALSE;
1122 BOOL bISupportErrorInfoFound = FALSE;
1123
1124 while (pEntries->pFunc != NULL && !bSupports)
1125 {
1126 if (!bISupportErrorInfoFound)
1127 {
1128 // skip the com map entries until ISupportErrorInfo is found
1129 bISupportErrorInfoFound =
1130 InlineIsEqualGUID (*(pEntries->piid), IID_ISupportErrorInfo);
1131 }
1132 else
1133 {
1134 // look for the requested interface in the rest of the com map
1135 bSupports = InlineIsEqualGUID (*(pEntries->piid), riid);
1136 }
1137 pEntries++;
1138 }
1139
1140 Assert (bISupportErrorInfoFound);
1141
1142 return bSupports ? S_OK : S_FALSE;
1143 }
1144#endif // defined (RT_OS_WINDOWS)
1145
1146protected:
1147
1148 /**
1149 * Sets the error information for the current thread.
1150 * This information can be retrieved by a caller of an interface method
1151 * using IErrorInfo on Windows or nsIException on Linux, or the cross-platform
1152 * IVirtualBoxErrorInfo interface that provides extended error info (only
1153 * for components from the VirtualBox COM library). Alternatively, the
1154 * platform-independent class com::ErrorInfo (defined in VBox[XP]COM.lib)
1155 * can be used to retrieve error info in a convenient way.
1156 *
1157 * It is assumed that the interface method that uses this function returns
1158 * an unsuccessful result code to the caller (otherwise, there is no reason
1159 * for the caller to try to retrieve error info after method invocation).
1160 *
1161 * Here is a table of correspondence between this method's arguments
1162 * and IErrorInfo/nsIException/IVirtualBoxErrorInfo attributes/methods:
1163 *
1164 * argument IErrorInfo nsIException IVirtualBoxErrorInfo
1165 * ----------------------------------------------------------------
1166 * resultCode -- result resultCode
1167 * iid GetGUID -- interfaceID
1168 * component GetSource -- component
1169 * text GetDescription message text
1170 *
1171 * This method is rarely needs to be used though. There are more convenient
1172 * overloaded versions, that automatically substitute some arguments
1173 * taking their values from the template parameters. See
1174 * #setError (HRESULT, const char *, ...) for an example.
1175 *
1176 * @param aResultCode result (error) code, must not be S_OK
1177 * @param aIID IID of the intrface that defines the error
1178 * @param aComponent name of the component that generates the error
1179 * @param aText error message (must not be null), an RTStrPrintf-like
1180 * format string in UTF-8 encoding
1181 * @param ... list of arguments for the format string
1182 *
1183 * @return
1184 * the error argument, for convenience, If an error occures while
1185 * creating error info itself, that error is returned instead of the
1186 * error argument.
1187 */
1188 inline static HRESULT setError (HRESULT aResultCode, const GUID &aIID,
1189 const wchar_t *aComponent,
1190 const char *aText, ...)
1191 {
1192 va_list args;
1193 va_start (args, aText);
1194 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError
1195 (aResultCode, aIID, aComponent, aText, args);
1196 va_end (args);
1197 return rc;
1198 }
1199
1200 /**
1201 * This method is the same as #setError() except that it preserves the
1202 * error info object (if any) set for the current thread before this
1203 * method is called by storing it in the IVirtualBoxErrorInfo::next
1204 * attribute of the new error info object.
1205 */
1206 inline static HRESULT addError (HRESULT aResultCode, const GUID &aIID,
1207 const wchar_t *aComponent,
1208 const char *aText, ...)
1209 {
1210 va_list args;
1211 va_start (args, aText);
1212 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::addError
1213 (aResultCode, aIID, aComponent, aText, args);
1214 va_end (args);
1215 return rc;
1216 }
1217
1218 /**
1219 * Sets the error information for the current thread.
1220 * A convenience method that automatically sets the default interface
1221 * ID (taken from the I template argument) and the component name
1222 * (a value of C::getComponentName()).
1223 *
1224 * See #setError (HRESULT, const GUID &, const wchar_t *, const char *text, ...)
1225 * for details.
1226 *
1227 * This method is the most common (and convenient) way to set error
1228 * information from within interface methods. A typical pattern of usage
1229 * is looks like this:
1230 *
1231 * <code>
1232 * return setError (E_FAIL, "Terrible Error");
1233 * </code>
1234 * or
1235 * <code>
1236 * HRESULT rc = setError (E_FAIL, "Terrible Error");
1237 * ...
1238 * return rc;
1239 * </code>
1240 */
1241 inline static HRESULT setError (HRESULT aResultCode, const char *aText, ...)
1242 {
1243 va_list args;
1244 va_start (args, aText);
1245 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError
1246 (aResultCode, COM_IIDOF(I), C::getComponentName(), aText, args);
1247 va_end (args);
1248 return rc;
1249 }
1250
1251 /**
1252 * This method is the same as #setError() except that it preserves the
1253 * error info object (if any) set for the current thread before this
1254 * method is called by storing it in the IVirtualBoxErrorInfo::next
1255 * attribute of the new error info object.
1256 */
1257 inline static HRESULT addError (HRESULT aResultCode, const char *aText, ...)
1258 {
1259 va_list args;
1260 va_start (args, aText);
1261 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::addError
1262 (aResultCode, COM_IIDOF(I), C::getComponentName(), aText, args);
1263 va_end (args);
1264 return rc;
1265 }
1266
1267 /**
1268 * Sets the error information for the current thread, va_list variant.
1269 * A convenience method that automatically sets the default interface
1270 * ID (taken from the I template argument) and the component name
1271 * (a value of C::getComponentName()).
1272 *
1273 * See #setError (HRESULT, const GUID &, const wchar_t *, const char *text, ...)
1274 * and #setError (HRESULT, const char *, ...) for details.
1275 */
1276 inline static HRESULT setErrorV (HRESULT aResultCode, const char *aText,
1277 va_list aArgs)
1278 {
1279 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError
1280 (aResultCode, COM_IIDOF(I), C::getComponentName(), aText, aArgs);
1281 return rc;
1282 }
1283
1284 /**
1285 * This method is the same as #setErrorV() except that it preserves the
1286 * error info object (if any) set for the current thread before this
1287 * method is called by storing it in the IVirtualBoxErrorInfo::next
1288 * attribute of the new error info object.
1289 */
1290 inline static HRESULT addErrorV (HRESULT aResultCode, const char *aText,
1291 va_list aArgs)
1292 {
1293 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::addError
1294 (aResultCode, COM_IIDOF(I), C::getComponentName(), aText, aArgs);
1295 return rc;
1296 }
1297
1298 /**
1299 * Sets the error information for the current thread, BStr variant.
1300 * A convenience method that automatically sets the default interface
1301 * ID (taken from the I template argument) and the component name
1302 * (a value of C::getComponentName()).
1303 *
1304 * This method is preferred iy you have a ready (translated and formatted)
1305 * Bstr string, because it omits an extra conversion Utf8Str -> Bstr.
1306 *
1307 * See #setError (HRESULT, const GUID &, const wchar_t *, const char *text, ...)
1308 * and #setError (HRESULT, const char *, ...) for details.
1309 */
1310 inline static HRESULT setErrorBstr (HRESULT aResultCode, const Bstr &aText)
1311 {
1312 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError
1313 (aResultCode, COM_IIDOF(I), C::getComponentName(), aText);
1314 return rc;
1315 }
1316
1317 /**
1318 * This method is the same as #setErrorBstr() except that it preserves the
1319 * error info object (if any) set for the current thread before this
1320 * method is called by storing it in the IVirtualBoxErrorInfo::next
1321 * attribute of the new error info object.
1322 */
1323 inline static HRESULT addErrorBstr (HRESULT aResultCode, const Bstr &aText)
1324 {
1325 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::addError
1326 (aResultCode, COM_IIDOF(I), C::getComponentName(), aText);
1327 return rc;
1328 }
1329
1330 /**
1331 * Sets the error information for the current thread.
1332 * A convenience method that automatically sets the component name
1333 * (a value of C::getComponentName()), but allows to specify the interface
1334 * id manually.
1335 *
1336 * See #setError (HRESULT, const GUID &, const wchar_t *, const char *text, ...)
1337 * for details.
1338 */
1339 inline static HRESULT setError (HRESULT aResultCode, const GUID &aIID,
1340 const char *aText, ...)
1341 {
1342 va_list args;
1343 va_start (args, aText);
1344 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError
1345 (aResultCode, aIID, C::getComponentName(), aText, args);
1346 va_end (args);
1347 return rc;
1348 }
1349
1350 /**
1351 * This method is the same as #setError() except that it preserves the
1352 * error info object (if any) set for the current thread before this
1353 * method is called by storing it in the IVirtualBoxErrorInfo::next
1354 * attribute of the new error info object.
1355 */
1356 inline static HRESULT addError (HRESULT aResultCode, const GUID &aIID,
1357 const char *aText, ...)
1358 {
1359 va_list args;
1360 va_start (args, aText);
1361 HRESULT rc = VirtualBoxSupportErrorInfoImplBase::addError
1362 (aResultCode, aIID, C::getComponentName(), aText, args);
1363 va_end (args);
1364 return rc;
1365 }
1366
1367private:
1368
1369};
1370
1371////////////////////////////////////////////////////////////////////////////////
1372
1373/**
1374 * Base class to track VirtualBoxBase chlidren of the component.
1375 *
1376 * This class is a preferrable VirtualBoxBase replacement for components
1377 * that operate with collections of child components. It gives two useful
1378 * possibilities:
1379 *
1380 * <ol><li>
1381 * Given an IUnknown instance, it's possible to quickly determine
1382 * whether this instance represents a child object created by the given
1383 * component, and if so, get a valid VirtualBoxBase pointer to the child
1384 * object. The returned pointer can be then safely casted to the
1385 * actual class of the child object (to get access to its "internal"
1386 * non-interface methods) provided that no other child components implement
1387 * the same initial interface IUnknown is queried from.
1388 * </li><li>
1389 * When the parent object uninitializes itself, it can easily unintialize
1390 * all its VirtualBoxBase derived children (using their
1391 * VirtualBoxBase::uninit() implementations). This is done simply by
1392 * calling the #uninitDependentChildren() method.
1393 * </li><ol>
1394 *
1395 * In order to let the above work, the following must be done:
1396 * <ol><li>
1397 * When a child object is initialized, it calls #addDependentChild() of
1398 * its parent to register itself within the list of dependent children.
1399 * </li><li>
1400 * When a child object it is uninitialized, it calls #removeDependentChild()
1401 * to unregister itself. This must be done <b>after</b> the child has called
1402 * setReady(false) to indicate it is no more valid, and <b>not</b> from under
1403 * the child object's lock. Note also, that the first action the child's
1404 * uninit() implementation must do is to check for readiness after acquiring
1405 * the object's lock and return immediately if not ready.
1406 * </li><ol>
1407 *
1408 * Children added by #addDependentChild() are <b>weakly</b> referenced
1409 * (i.e. AddRef() is not called), so when a child is externally destructed
1410 * (i.e. its reference count goes to zero), it will automatically remove
1411 * itself from a map of dependent children, provided that it follows the
1412 * rules described here.
1413 *
1414 * @note
1415 * Because of weak referencing, deadlocks and assertions are very likely
1416 * if #addDependentChild() or #removeDependentChild() are used incorrectly
1417 * (called at inappropriate times). Check the above rules once more.
1418 */
1419class VirtualBoxBaseWithChildren : public VirtualBoxBase
1420{
1421public:
1422
1423 VirtualBoxBaseWithChildren()
1424 : mUninitDoneSem (NIL_RTSEMEVENT), mChildrenLeft (0)
1425 {
1426 RTCritSectInit (&mMapLock);
1427 }
1428
1429 virtual ~VirtualBoxBaseWithChildren()
1430 {
1431 RTCritSectDelete (&mMapLock);
1432 }
1433
1434 /**
1435 * Adds the given child to the map of dependent children.
1436 * Intended to be called from the child's init() method,
1437 * from under the child's lock.
1438 *
1439 * @param C the child object to add (must inherit VirtualBoxBase AND
1440 * implement some interface)
1441 */
1442 template <class C>
1443 void addDependentChild (C *child)
1444 {
1445 AssertReturn (child, (void) 0);
1446 addDependentChild (child, child);
1447 }
1448
1449 /**
1450 * Removes the given child from the map of dependent children.
1451 * Must be called <b>after<b> the child has called setReady(false), and
1452 * <b>not</b> from under the child object's lock.
1453 *
1454 * @param C the child object to remove (must inherit VirtualBoxBase AND
1455 * implement some interface)
1456 */
1457 template <class C>
1458 void removeDependentChild (C *child)
1459 {
1460 AssertReturn (child, (void) 0);
1461 /// @todo (r=dmik) the below check (and the relevant comment above)
1462 // seems to be not necessary any more once we completely switch to
1463 // the NEXT locking scheme. This requires altering removeDependentChild()
1464 // and uninitDependentChildren() as well (due to the new state scheme,
1465 // there is a separate mutex for state transition, so calling the
1466 // child's uninit() from under the children map lock should not produce
1467 // dead-locks any more).
1468 Assert (!child->isLockedOnCurrentThread());
1469 removeDependentChild (ComPtr <IUnknown> (child));
1470 }
1471
1472protected:
1473
1474 void uninitDependentChildren();
1475
1476 VirtualBoxBase *getDependentChild (const ComPtr <IUnknown> &unk);
1477
1478private:
1479
1480 void addDependentChild (const ComPtr <IUnknown> &unk, VirtualBoxBase *child);
1481 void removeDependentChild (const ComPtr <IUnknown> &unk);
1482
1483 typedef std::map <IUnknown *, VirtualBoxBase *> DependentChildren;
1484 DependentChildren mDependentChildren;
1485
1486 RTCRITSECT mMapLock;
1487 RTSEMEVENT mUninitDoneSem;
1488 unsigned mChildrenLeft;
1489};
1490
1491/**
1492 * Temporary class to disable deprecated methods of VirtualBoxBase.
1493 * Can be used as a base for components that are completely switched to
1494 * the new locking scheme (VirtualBoxBaseNEXT_base).
1495 *
1496 * @todo remove after we switch to VirtualBoxBaseNEXT completely.
1497 */
1498class VirtualBoxBaseWithChildrenNEXT : public VirtualBoxBaseWithChildren
1499{
1500private:
1501
1502 void lock();
1503 void unlock();
1504 void setReady (bool isReady);
1505 bool isReady();
1506};
1507
1508////////////////////////////////////////////////////////////////////////////////
1509
1510/**
1511 * Base class to track component's chlidren of some particular type.
1512 *
1513 * This class is similar to VirtualBoxBaseWithChildren, with the exception
1514 * that all children must be of the same type. For this reason, it's not
1515 * necessary to use a map to store children, so a list is used instead.
1516 *
1517 * As opposed to VirtualBoxBaseWithChildren, children added by
1518 * #addDependentChild() are <b>strongly</b> referenced, so that they cannot
1519 * be externally destructed until #removeDependentChild() is called.
1520 * For this reason, strict rules of calling #removeDependentChild() don't
1521 * apply to instances of this class -- it can be called anywhere in the
1522 * child's uninit() implementation.
1523 *
1524 * @param C type of child objects (must inherit VirtualBoxBase AND
1525 * implement some interface)
1526 */
1527template <class C>
1528class VirtualBoxBaseWithTypedChildren : public VirtualBoxBase
1529{
1530public:
1531
1532 typedef std::list <ComObjPtr <C> > DependentChildren;
1533
1534 VirtualBoxBaseWithTypedChildren() : mInUninit (false) {}
1535
1536 virtual ~VirtualBoxBaseWithTypedChildren() {}
1537
1538 /**
1539 * Adds the given child to the list of dependent children.
1540 * Must be called from the child's init() method,
1541 * from under the child's lock.
1542 *
1543 * @param C the child object to add (must inherit VirtualBoxBase AND
1544 * implement some interface)
1545 */
1546 void addDependentChild (C *child)
1547 {
1548 AssertReturn (child, (void) 0);
1549
1550 AutoLock alock (mMapLock);
1551 if (mInUninit)
1552 return;
1553
1554 mDependentChildren.push_back (child);
1555 }
1556
1557 /**
1558 * Removes the given child from the list of dependent children.
1559 * Must be called from the child's uninit() method,
1560 * under the child's lock.
1561 *
1562 * @param C the child object to remove (must inherit VirtualBoxBase AND
1563 * implement some interface)
1564 */
1565 void removeDependentChild (C *child)
1566 {
1567 AssertReturn (child, (void) 0);
1568
1569 AutoLock alock (mMapLock);
1570 if (mInUninit)
1571 return;
1572
1573 mDependentChildren.remove (child);
1574 }
1575
1576protected:
1577
1578 /**
1579 * Returns an internal lock handle to lock the list of children
1580 * returned by #dependentChildren() using AutoLock:
1581 * <code>
1582 * AutoLock alock (dependentChildrenLock());
1583 * </code>
1584 */
1585 AutoLock::Handle &dependentChildrenLock() const { return mMapLock; }
1586
1587 /**
1588 * Returns the read-only list of all dependent children.
1589 * @note
1590 * Access the returned list (iterate, get size etc.) only after
1591 * doing |AutoLock alock (dependentChildrenLock());|!
1592 */
1593 const DependentChildren &dependentChildren() const { return mDependentChildren; }
1594
1595 /**
1596 * Uninitializes all dependent children registered with #addDependentChild().
1597 *
1598 * @note
1599 * This method will call uninit() methods of children. If these methods
1600 * access the parent object, uninitDependentChildren() must be called
1601 * either at the beginning of the parent uninitialization sequence (when
1602 * it is still operational) or after setReady(false) is called to
1603 * indicate the parent is out of action.
1604 */
1605 void uninitDependentChildren()
1606 {
1607 AutoLock alock (this);
1608 AutoLock mapLock (mMapLock);
1609
1610 if (mDependentChildren.size())
1611 {
1612 // set flag to ignore #removeDependentChild() called from child->uninit()
1613 mInUninit = true;
1614
1615 // leave the locks to let children waiting for #removeDependentChild() run
1616 mapLock.leave();
1617 alock.leave();
1618
1619 for (typename DependentChildren::iterator it = mDependentChildren.begin();
1620 it != mDependentChildren.end(); ++ it)
1621 {
1622 C *child = (*it);
1623 Assert (child);
1624 if (child)
1625 child->uninit();
1626 }
1627 mDependentChildren.clear();
1628
1629 alock.enter();
1630 mapLock.enter();
1631
1632 mInUninit = false;
1633 }
1634 }
1635
1636 /**
1637 * Removes (detaches) all dependent children registered with
1638 * #addDependentChild(), without uninitializing them.
1639 *
1640 * @note This method must be called from under the main object's lock
1641 */
1642 void removeDependentChildren()
1643 {
1644 AutoLock alock (mMapLock);
1645 mDependentChildren.clear();
1646 }
1647
1648private:
1649
1650 DependentChildren mDependentChildren;
1651
1652 bool mInUninit;
1653 mutable AutoLock::Handle mMapLock;
1654};
1655
1656/**
1657 * Temporary class to disable deprecated methods of VirtualBoxBase.
1658 * Can be used as a base for components that are completely switched to
1659 * the new locking scheme (VirtualBoxBaseNEXT_base).
1660 *
1661 * @todo remove after we switch to VirtualBoxBaseNEXT completely.
1662 */
1663template <class C>
1664class VirtualBoxBaseWithTypedChildrenNEXT : public VirtualBoxBaseWithTypedChildren <C>
1665{
1666public:
1667
1668 typedef util::AutoLock AutoLock;
1669
1670private:
1671
1672 void lock();
1673 void unlock();
1674 bool isLockedOnCurrentThread();
1675 void setReady (bool isReady);
1676 bool isReady();
1677};
1678
1679////////////////////////////////////////////////////////////////////////////////
1680
1681/// @todo (dmik) remove after we switch to VirtualBoxBaseNEXT completely
1682/**
1683 * Simple template that manages data structure allocation/deallocation
1684 * and supports data pointer sharing (the instance that shares the pointer is
1685 * not responsible for memory deallocation as opposed to the instance that
1686 * owns it).
1687 */
1688template <class D>
1689class Shareable
1690{
1691public:
1692
1693 Shareable() : mData (NULL), mIsShared (FALSE) {}
1694 ~Shareable() { free(); }
1695
1696 void allocate() { attach (new D); }
1697
1698 virtual void free() {
1699 if (mData) {
1700 if (!mIsShared)
1701 delete mData;
1702 mData = NULL;
1703 mIsShared = false;
1704 }
1705 }
1706
1707 void attach (D *data) {
1708 AssertMsg (data, ("new data must not be NULL"));
1709 if (data && mData != data) {
1710 if (mData && !mIsShared)
1711 delete mData;
1712 mData = data;
1713 mIsShared = false;
1714 }
1715 }
1716
1717 void attach (Shareable &data) {
1718 AssertMsg (
1719 data.mData == mData || !data.mIsShared,
1720 ("new data must not be shared")
1721 );
1722 if (this != &data && !data.mIsShared) {
1723 attach (data.mData);
1724 data.mIsShared = true;
1725 }
1726 }
1727
1728 void share (D *data) {
1729 AssertMsg (data, ("new data must not be NULL"));
1730 if (mData != data) {
1731 if (mData && !mIsShared)
1732 delete mData;
1733 mData = data;
1734 mIsShared = true;
1735 }
1736 }
1737
1738 void share (const Shareable &data) { share (data.mData); }
1739
1740 void attachCopy (const D *data) {
1741 AssertMsg (data, ("data to copy must not be NULL"));
1742 if (data)
1743 attach (new D (*data));
1744 }
1745
1746 void attachCopy (const Shareable &data) {
1747 attachCopy (data.mData);
1748 }
1749
1750 virtual D *detach() {
1751 D *d = mData;
1752 mData = NULL;
1753 mIsShared = false;
1754 return d;
1755 }
1756
1757 D *data() const {
1758 return mData;
1759 }
1760
1761 D *operator->() const {
1762 AssertMsg (mData, ("data must not be NULL"));
1763 return mData;
1764 }
1765
1766 bool isNull() const { return mData == NULL; }
1767 bool operator!() const { return isNull(); }
1768
1769 bool isShared() const { return mIsShared; }
1770
1771protected:
1772
1773 D *mData;
1774 bool mIsShared;
1775};
1776
1777/// @todo (dmik) remove after we switch to VirtualBoxBaseNEXT completely
1778/**
1779 * Simple template that enhances Shareable<> and supports data
1780 * backup/rollback/commit (using the copy constructor of the managed data
1781 * structure).
1782 */
1783template <class D>
1784class Backupable : public Shareable <D>
1785{
1786public:
1787
1788 Backupable() : Shareable <D> (), mBackupData (NULL) {}
1789
1790 void free()
1791 {
1792 AssertMsg (this->mData || !mBackupData, ("backup must be NULL if data is NULL"));
1793 rollback();
1794 Shareable <D>::free();
1795 }
1796
1797 D *detach()
1798 {
1799 AssertMsg (this->mData || !mBackupData, ("backup must be NULL if data is NULL"));
1800 rollback();
1801 return Shareable <D>::detach();
1802 }
1803
1804 void share (const Backupable &data)
1805 {
1806 AssertMsg (!data.isBackedUp(), ("data to share must not be backed up"));
1807 if (!data.isBackedUp())
1808 Shareable <D>::share (data.mData);
1809 }
1810
1811 /**
1812 * Stores the current data pointer in the backup area, allocates new data
1813 * using the copy constructor on current data and makes new data active.
1814 */
1815 void backup()
1816 {
1817 AssertMsg (this->mData, ("data must not be NULL"));
1818 if (this->mData && !mBackupData)
1819 {
1820 mBackupData = this->mData;
1821 this->mData = new D (*mBackupData);
1822 }
1823 }
1824
1825 /**
1826 * Deletes new data created by #backup() and restores previous data pointer
1827 * stored in the backup area, making it active again.
1828 */
1829 void rollback()
1830 {
1831 if (this->mData && mBackupData)
1832 {
1833 delete this->mData;
1834 this->mData = mBackupData;
1835 mBackupData = NULL;
1836 }
1837 }
1838
1839 /**
1840 * Commits current changes by deleting backed up data and clearing up the
1841 * backup area. The new data pointer created by #backup() remains active
1842 * and becomes the only managed pointer.
1843 *
1844 * This method is much faster than #commitCopy() (just a single pointer
1845 * assignment operation), but makes the previous data pointer invalid
1846 * (because it is freed). For this reason, this method must not be
1847 * used if it's possible that data managed by this instance is shared with
1848 * some other Shareable instance. See #commitCopy().
1849 */
1850 void commit()
1851 {
1852 if (this->mData && mBackupData)
1853 {
1854 if (!this->mIsShared)
1855 delete mBackupData;
1856 mBackupData = NULL;
1857 this->mIsShared = false;
1858 }
1859 }
1860
1861 /**
1862 * Commits current changes by assigning new data to the previous data
1863 * pointer stored in the backup area using the assignment operator.
1864 * New data is deleted, the backup area is cleared and the previous data
1865 * pointer becomes active and the only managed pointer.
1866 *
1867 * This method is slower than #commit(), but it keeps the previous data
1868 * pointer valid (i.e. new data is copied to the same memory location).
1869 * For that reason it's safe to use this method on instances that share
1870 * managed data with other Shareable instances.
1871 */
1872 void commitCopy()
1873 {
1874 if (this->mData && mBackupData)
1875 {
1876 *mBackupData = *(this->mData);
1877 delete this->mData;
1878 this->mData = mBackupData;
1879 mBackupData = NULL;
1880 }
1881 }
1882
1883 void assignCopy (const D *data)
1884 {
1885 AssertMsg (this->mData, ("data must not be NULL"));
1886 AssertMsg (data, ("data to copy must not be NULL"));
1887 if (this->mData && data)
1888 {
1889 if (!mBackupData)
1890 {
1891 mBackupData = this->mData;
1892 this->mData = new D (*data);
1893 }
1894 else
1895 *this->mData = *data;
1896 }
1897 }
1898
1899 void assignCopy (const Backupable &data)
1900 {
1901 assignCopy (data.mData);
1902 }
1903
1904 bool isBackedUp() const
1905 {
1906 return mBackupData != NULL;
1907 }
1908
1909 bool hasActualChanges() const
1910 {
1911 AssertMsg (this->mData, ("data must not be NULL"));
1912 return this->mData != NULL && mBackupData != NULL &&
1913 !(*this->mData == *mBackupData);
1914 }
1915
1916 D *backedUpData() const
1917 {
1918 return mBackupData;
1919 }
1920
1921protected:
1922
1923 D *mBackupData;
1924};
1925
1926#endif // ____H_VIRTUALBOXBASEIMPL
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