VirtualBox

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

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

Main: remove VirtualBoxSupportTranslation template, add translation support to generic base class, clean up COM headers more, remove SupportErrorInfo.cpp|h

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 39.1 KB
Line 
1/** @file
2 * VirtualBox COM base classes definition
3 */
4
5/*
6 * Copyright (C) 2006-2010 Oracle Corporation
7 *
8 * This file is part of VirtualBox Open Source Edition (OSE), as
9 * available from http://www.215389.xyz. This file is free software;
10 * you can redistribute it and/or modify it under the terms of the GNU
11 * General Public License (GPL) as published by the Free Software
12 * Foundation, in version 2 as it comes in the "COPYING" file of the
13 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
14 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
15 */
16
17#ifndef ____H_VIRTUALBOXBASEIMPL
18#define ____H_VIRTUALBOXBASEIMPL
19
20#include <iprt/cdefs.h>
21#include <iprt/thread.h>
22
23#include <list>
24#include <map>
25
26#include "VBox/com/AutoLock.h"
27#include "VBox/com/string.h"
28#include "VBox/com/Guid.h"
29
30#include "VBox/com/VirtualBox.h"
31
32// avoid including VBox/settings.h and VBox/xml.h;
33// only declare the classes
34namespace xml
35{
36class File;
37}
38
39using namespace com;
40using namespace util;
41
42class AutoInitSpan;
43class AutoUninitSpan;
44
45class VirtualBox;
46class Machine;
47class Medium;
48class Host;
49typedef std::list< ComObjPtr<Medium> > MediaList;
50
51////////////////////////////////////////////////////////////////////////////////
52//
53// COM helpers
54//
55////////////////////////////////////////////////////////////////////////////////
56
57#if !defined (VBOX_WITH_XPCOM)
58
59#include <atlcom.h>
60
61/* use a special version of the singleton class factory,
62 * see KB811591 in msdn for more info. */
63
64#undef DECLARE_CLASSFACTORY_SINGLETON
65#define DECLARE_CLASSFACTORY_SINGLETON(obj) DECLARE_CLASSFACTORY_EX(CMyComClassFactorySingleton<obj>)
66
67template <class T>
68class CMyComClassFactorySingleton : public CComClassFactory
69{
70public:
71 CMyComClassFactorySingleton() : m_hrCreate(S_OK){}
72 virtual ~CMyComClassFactorySingleton(){}
73 // IClassFactory
74 STDMETHOD(CreateInstance)(LPUNKNOWN pUnkOuter, REFIID riid, void** ppvObj)
75 {
76 HRESULT hRes = E_POINTER;
77 if (ppvObj != NULL)
78 {
79 *ppvObj = NULL;
80 // Aggregation is not supported in singleton objects.
81 ATLASSERT(pUnkOuter == NULL);
82 if (pUnkOuter != NULL)
83 hRes = CLASS_E_NOAGGREGATION;
84 else
85 {
86 if (m_hrCreate == S_OK && m_spObj == NULL)
87 {
88 Lock();
89 __try
90 {
91 // Fix: The following If statement was moved inside the __try statement.
92 // Did another thread arrive here first?
93 if (m_hrCreate == S_OK && m_spObj == NULL)
94 {
95 // lock the module to indicate activity
96 // (necessary for the monitor shutdown thread to correctly
97 // terminate the module in case when CreateInstance() fails)
98 _pAtlModule->Lock();
99 CComObjectCached<T> *p;
100 m_hrCreate = CComObjectCached<T>::CreateInstance(&p);
101 if (SUCCEEDED(m_hrCreate))
102 {
103 m_hrCreate = p->QueryInterface(IID_IUnknown, (void**)&m_spObj);
104 if (FAILED(m_hrCreate))
105 {
106 delete p;
107 }
108 }
109 _pAtlModule->Unlock();
110 }
111 }
112 __finally
113 {
114 Unlock();
115 }
116 }
117 if (m_hrCreate == S_OK)
118 {
119 hRes = m_spObj->QueryInterface(riid, ppvObj);
120 }
121 else
122 {
123 hRes = m_hrCreate;
124 }
125 }
126 }
127 return hRes;
128 }
129 HRESULT m_hrCreate;
130 CComPtr<IUnknown> m_spObj;
131};
132
133#endif /* !defined (VBOX_WITH_XPCOM) */
134
135////////////////////////////////////////////////////////////////////////////////
136//
137// Macros
138//
139////////////////////////////////////////////////////////////////////////////////
140
141/**
142 * Special version of the Assert macro to be used within VirtualBoxBase
143 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
144 *
145 * In the debug build, this macro is equivalent to Assert.
146 * In the release build, this macro uses |setError(E_FAIL, ...)| to set the
147 * error info from the asserted expression.
148 *
149 * @see VirtualBoxSupportErrorInfoImpl::setError
150 *
151 * @param expr Expression which should be true.
152 */
153#if defined (DEBUG)
154#define ComAssert(expr) Assert(expr)
155#else
156#define ComAssert(expr) \
157 do { \
158 if (RT_UNLIKELY(!(expr))) \
159 setError(E_FAIL, \
160 "Assertion failed: [%s] at '%s' (%d) in %s.\nPlease contact the product vendor!", \
161 #expr, __FILE__, __LINE__, __PRETTY_FUNCTION__); \
162 } while (0)
163#endif
164
165/**
166 * Special version of the AssertMsg macro to be used within VirtualBoxBase
167 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
168 *
169 * See ComAssert for more info.
170 *
171 * @param expr Expression which should be true.
172 * @param a printf argument list (in parenthesis).
173 */
174#if defined (DEBUG)
175#define ComAssertMsg(expr, a) AssertMsg(expr, a)
176#else
177#define ComAssertMsg(expr, a) \
178 do { \
179 if (RT_UNLIKELY(!(expr))) \
180 setError(E_FAIL, \
181 "Assertion failed: [%s] at '%s' (%d) in %s.\n%s.\nPlease contact the product vendor!", \
182 #expr, __FILE__, __LINE__, __PRETTY_FUNCTION__); \
183 } while (0)
184#endif
185
186/**
187 * Special version of the AssertRC macro to be used within VirtualBoxBase
188 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
189 *
190 * See ComAssert for more info.
191 *
192 * @param vrc VBox status code.
193 */
194#if defined (DEBUG)
195#define ComAssertRC(vrc) AssertRC(vrc)
196#else
197#define ComAssertRC(vrc) ComAssertMsgRC(vrc, ("%Rra", vrc))
198#endif
199
200/**
201 * Special version of the AssertMsgRC macro to be used within VirtualBoxBase
202 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
203 *
204 * See ComAssert for more info.
205 *
206 * @param vrc VBox status code.
207 * @param msg printf argument list (in parenthesis).
208 */
209#if defined (DEBUG)
210#define ComAssertMsgRC(vrc, msg) AssertMsgRC(vrc, msg)
211#else
212#define ComAssertMsgRC(vrc, msg) ComAssertMsg(RT_SUCCESS(vrc), msg)
213#endif
214
215/**
216 * Special version of the AssertComRC macro to be used within VirtualBoxBase
217 * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
218 *
219 * See ComAssert for more info.
220 *
221 * @param rc COM result code
222 */
223#if defined (DEBUG)
224#define ComAssertComRC(rc) AssertComRC(rc)
225#else
226#define ComAssertComRC(rc) ComAssertMsg(SUCCEEDED(rc), ("COM RC = %Rhrc (0x%08X)", (rc), (rc)))
227#endif
228
229
230/** Special version of ComAssert that returns ret if expr fails */
231#define ComAssertRet(expr, ret) \
232 do { ComAssert(expr); if (!(expr)) return (ret); } while (0)
233/** Special version of ComAssertMsg that returns ret if expr fails */
234#define ComAssertMsgRet(expr, a, ret) \
235 do { ComAssertMsg(expr, a); if (!(expr)) return (ret); } while (0)
236/** Special version of ComAssertRC that returns ret if vrc does not succeed */
237#define ComAssertRCRet(vrc, ret) \
238 do { ComAssertRC(vrc); if (!RT_SUCCESS(vrc)) return (ret); } while (0)
239/** Special version of ComAssertComRC that returns ret if rc does not succeed */
240#define ComAssertComRCRet(rc, ret) \
241 do { ComAssertComRC(rc); if (!SUCCEEDED(rc)) return (ret); } while (0)
242/** Special version of ComAssertComRC that returns rc if rc does not succeed */
243#define ComAssertComRCRetRC(rc) \
244 do { ComAssertComRC(rc); if (!SUCCEEDED(rc)) return (rc); } while (0)
245
246
247/** Special version of ComAssert that evaluates eval and breaks if expr fails */
248#define ComAssertBreak(expr, eval) \
249 if (1) { ComAssert(expr); if (!(expr)) { eval; break; } } else do {} while (0)
250/** Special version of ComAssertMsg that evaluates eval and breaks if expr fails */
251#define ComAssertMsgBreak(expr, a, eval) \
252 if (1) { ComAssertMsg(expr, a); if (!(expr)) { eval; break; } } else do {} while (0)
253/** Special version of ComAssertRC that evaluates eval and breaks if vrc does not succeed */
254#define ComAssertRCBreak(vrc, eval) \
255 if (1) { ComAssertRC(vrc); if (!RT_SUCCESS(vrc)) { eval; break; } } else do {} while (0)
256/** Special version of ComAssertFailed that evaluates eval and breaks */
257#define ComAssertFailedBreak(eval) \
258 if (1) { ComAssertFailed(); { eval; break; } } else do {} while (0)
259/** Special version of ComAssertMsgFailed that evaluates eval and breaks */
260#define ComAssertMsgFailedBreak(msg, eval) \
261 if (1) { ComAssertMsgFailed (msg); { eval; break; } } else do {} while (0)
262/** Special version of ComAssertComRC that evaluates eval and breaks if rc does not succeed */
263#define ComAssertComRCBreak(rc, eval) \
264 if (1) { ComAssertComRC(rc); if (!SUCCEEDED(rc)) { eval; break; } } else do {} while (0)
265/** Special version of ComAssertComRC that just breaks if rc does not succeed */
266#define ComAssertComRCBreakRC(rc) \
267 if (1) { ComAssertComRC(rc); if (!SUCCEEDED(rc)) { break; } } else do {} while (0)
268
269
270/** Special version of ComAssert that evaluates eval and throws it if expr fails */
271#define ComAssertThrow(expr, eval) \
272 if (1) { ComAssert(expr); if (!(expr)) { throw (eval); } } else do {} while (0)
273/** Special version of ComAssertRC that evaluates eval and throws it if vrc does not succeed */
274#define ComAssertRCThrow(vrc, eval) \
275 if (1) { ComAssertRC(vrc); if (!RT_SUCCESS(vrc)) { throw (eval); } } else do {} while (0)
276/** Special version of ComAssertComRC that evaluates eval and throws it if rc does not succeed */
277#define ComAssertComRCThrow(rc, eval) \
278 if (1) { ComAssertComRC(rc); if (!SUCCEEDED(rc)) { throw (eval); } } else do {} while (0)
279/** Special version of ComAssertComRC that just throws rc if rc does not succeed */
280#define ComAssertComRCThrowRC(rc) \
281 if (1) { ComAssertComRC(rc); if (!SUCCEEDED(rc)) { throw rc; } } else do {} while (0)
282
283////////////////////////////////////////////////////////////////////////////////
284
285/**
286 * Checks that the pointer argument is not NULL and returns E_INVALIDARG +
287 * extended error info on failure.
288 * @param arg Input pointer-type argument (strings, interface pointers...)
289 */
290#define CheckComArgNotNull(arg) \
291 do { \
292 if (RT_UNLIKELY((arg) == NULL)) \
293 return setError(E_INVALIDARG, tr("Argument %s is NULL"), #arg); \
294 } while (0)
295
296/**
297 * Checks that safe array argument is not NULL and returns E_INVALIDARG +
298 * extended error info on failure.
299 * @param arg Input safe array argument (strings, interface pointers...)
300 */
301#define CheckComArgSafeArrayNotNull(arg) \
302 do { \
303 if (RT_UNLIKELY(ComSafeArrayInIsNull(arg))) \
304 return setError(E_INVALIDARG, tr("Argument %s is NULL"), #arg); \
305 } while (0)
306
307/**
308 * Checks that the string argument is not a NULL or empty string and returns
309 * E_INVALIDARG + extended error info on failure.
310 * @param arg Input string argument (BSTR etc.).
311 */
312#define CheckComArgStrNotEmptyOrNull(arg) \
313 do { \
314 if (RT_UNLIKELY((arg) == NULL || *(arg) == '\0')) \
315 return setError(E_INVALIDARG, \
316 tr("Argument %s is empty or NULL"), #arg); \
317 } while (0)
318
319/**
320 * Checks that the given expression (that must involve the argument) is true and
321 * returns E_INVALIDARG + extended error info on failure.
322 * @param arg Argument.
323 * @param expr Expression to evaluate.
324 */
325#define CheckComArgExpr(arg, expr) \
326 do { \
327 if (RT_UNLIKELY(!(expr))) \
328 return setError(E_INVALIDARG, \
329 tr("Argument %s is invalid (must be %s)"), #arg, #expr); \
330 } while (0)
331
332/**
333 * Checks that the given expression (that must involve the argument) is true and
334 * returns E_INVALIDARG + extended error info on failure. The error message must
335 * be customized.
336 * @param arg Argument.
337 * @param expr Expression to evaluate.
338 * @param msg Parenthesized printf-like expression (must start with a verb,
339 * like "must be one of...", "is not within...").
340 */
341#define CheckComArgExprMsg(arg, expr, msg) \
342 do { \
343 if (RT_UNLIKELY(!(expr))) \
344 return setError(E_INVALIDARG, tr ("Argument %s %s"), \
345 #arg, Utf8StrFmt msg .raw()); \
346 } while (0)
347
348/**
349 * Checks that the given pointer to an output argument is valid and returns
350 * E_POINTER + extended error info otherwise.
351 * @param arg Pointer argument.
352 */
353#define CheckComArgOutPointerValid(arg) \
354 do { \
355 if (RT_UNLIKELY(!VALID_PTR(arg))) \
356 return setError(E_POINTER, \
357 tr("Output argument %s points to invalid memory location (%p)"), \
358 #arg, (void *) (arg)); \
359 } while (0)
360
361/**
362 * Checks that the given pointer to an output safe array argument is valid and
363 * returns E_POINTER + extended error info otherwise.
364 * @param arg Safe array argument.
365 */
366#define CheckComArgOutSafeArrayPointerValid(arg) \
367 do { \
368 if (RT_UNLIKELY(ComSafeArrayOutIsNull(arg))) \
369 return setError(E_POINTER, \
370 tr("Output argument %s points to invalid memory location (%p)"), \
371 #arg, (void*)(arg)); \
372 } while (0)
373
374/**
375 * Sets the extended error info and returns E_NOTIMPL.
376 */
377#define ReturnComNotImplemented() \
378 do { \
379 return setError(E_NOTIMPL, tr("Method %s is not implemented"), __FUNCTION__); \
380 } while (0)
381
382/**
383 * Declares an empty constructor and destructor for the given class.
384 * This is useful to prevent the compiler from generating the default
385 * ctor and dtor, which in turn allows to use forward class statements
386 * (instead of including their header files) when declaring data members of
387 * non-fundamental types with constructors (which are always called implicitly
388 * by constructors and by the destructor of the class).
389 *
390 * This macro is to be placed within (the public section of) the class
391 * declaration. Its counterpart, DEFINE_EMPTY_CTOR_DTOR, must be placed
392 * somewhere in one of the translation units (usually .cpp source files).
393 *
394 * @param cls class to declare a ctor and dtor for
395 */
396#define DECLARE_EMPTY_CTOR_DTOR(cls) cls(); ~cls();
397
398/**
399 * Defines an empty constructor and destructor for the given class.
400 * See DECLARE_EMPTY_CTOR_DTOR for more info.
401 */
402#define DEFINE_EMPTY_CTOR_DTOR(cls) \
403 cls::cls() { /*empty*/ } \
404 cls::~cls() { /*empty*/ }
405
406/**
407 * Parent class of VirtualBoxBase which enables translation support (which
408 * Main doesn't have yet, but this provides the tr() function which will one
409 * day provide translations).
410 *
411 * This class sits in between Lockable and VirtualBoxBase only for the one
412 * reason that the USBProxyService wants translation support but is not
413 * implemented as a COM object, which VirtualBoxBase implies.
414 */
415class ATL_NO_VTABLE VirtualBoxTranslatable
416 : public Lockable
417{
418public:
419
420 /**
421 * Placeholder method with which translations can one day be implemented
422 * in Main. This gets called by the tr() function.
423 * @param context
424 * @param pcszSourceText
425 * @param comment
426 * @return
427 */
428 static const char *translate(const char *context,
429 const char *pcszSourceText,
430 const char *comment = 0)
431 {
432 NOREF(context);
433 NOREF(comment);
434 return pcszSourceText;
435 }
436
437 /**
438 * Translates the given text string by calling translate() and passing
439 * the name of the C class as the first argument ("context of
440 * translation"). See VirtualBoxBase::translate() for more info.
441 *
442 * @param aSourceText String to translate.
443 * @param aComment Comment to the string to resolve possible
444 * ambiguities (NULL means no comment).
445 *
446 * @return Translated version of the source string in UTF-8 encoding, or
447 * the source string itself if the translation is not found in the
448 * specified context.
449 */
450 inline static const char *tr(const char *pcszSourceText,
451 const char *aComment = NULL)
452 {
453 return VirtualBoxTranslatable::translate(NULL, // getComponentName(), eventually
454 pcszSourceText,
455 aComment);
456 }
457};
458
459////////////////////////////////////////////////////////////////////////////////
460//
461// VirtualBoxBase
462//
463////////////////////////////////////////////////////////////////////////////////
464
465#define VIRTUALBOXBASE_ADD_VIRTUAL_COMPONENT_METHODS(cls, iface) \
466 virtual const IID& getClassIID() const \
467 { \
468 return cls::getStaticClassIID(); \
469 } \
470 static const IID& getStaticClassIID() \
471 { \
472 return COM_IIDOF(iface); \
473 } \
474 virtual const char* getComponentName() const \
475 { \
476 return cls::getStaticComponentName(); \
477 } \
478 static const char* getStaticComponentName() \
479 { \
480 return #cls; \
481 }
482
483/**
484 * VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT:
485 * This macro must be used once in the declaration of any class derived
486 * from VirtualBoxBase. It implements the pure virtual getClassIID() and
487 * getComponentName() methods. If this macro is not present, instances
488 * of a class derived from VirtualBoxBase cannot be instantiated.
489 *
490 * @param X The class name, e.g. "Class".
491 * @param IX The interface name which this class implements, e.g. "IClass".
492 */
493#ifdef VBOX_WITH_XPCOM
494 #define VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT(cls, iface) \
495 VIRTUALBOXBASE_ADD_VIRTUAL_COMPONENT_METHODS(cls, iface)
496#else // #ifdef VBOX_WITH_XPCOM
497 #define VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT(cls, iface) \
498 VIRTUALBOXBASE_ADD_VIRTUAL_COMPONENT_METHODS(cls, iface) \
499 STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid) \
500 { \
501 const _ATL_INTMAP_ENTRY* pEntries = cls::_GetEntries(); \
502 Assert(pEntries); \
503 if (!pEntries) \
504 return S_FALSE; \
505 BOOL bSupports = FALSE; \
506 BOOL bISupportErrorInfoFound = FALSE; \
507 while (pEntries->pFunc != NULL && !bSupports) \
508 { \
509 if (!bISupportErrorInfoFound) \
510 bISupportErrorInfoFound = InlineIsEqualGUID(*(pEntries->piid), IID_ISupportErrorInfo); \
511 else \
512 bSupports = InlineIsEqualGUID(*(pEntries->piid), riid); \
513 pEntries++; \
514 } \
515 Assert(bISupportErrorInfoFound); \
516 return bSupports ? S_OK : S_FALSE; \
517 }
518#endif // #ifdef VBOX_WITH_XPCOM
519
520/**
521 * Abstract base class for all component classes implementing COM
522 * interfaces of the VirtualBox COM library.
523 *
524 * Declares functionality that should be available in all components.
525 *
526 * Among the basic functionality implemented by this class is the primary object
527 * state that indicates if the object is ready to serve the calls, and if not,
528 * what stage it is currently at. Here is the primary state diagram:
529 *
530 * +-------------------------------------------------------+
531 * | |
532 * | (InitFailed) -----------------------+ |
533 * | ^ | |
534 * v | v |
535 * [*] ---> NotReady ----> (InInit) -----> Ready -----> (InUninit) ----+
536 * ^ |
537 * | v
538 * | Limited
539 * | |
540 * +-------+
541 *
542 * The object is fully operational only when its state is Ready. The Limited
543 * state means that only some vital part of the object is operational, and it
544 * requires some sort of reinitialization to become fully operational. The
545 * NotReady state means the object is basically dead: it either was not yet
546 * initialized after creation at all, or was uninitialized and is waiting to be
547 * destroyed when the last reference to it is released. All other states are
548 * transitional.
549 *
550 * The NotReady->InInit->Ready, NotReady->InInit->Limited and
551 * NotReady->InInit->InitFailed transition is done by the AutoInitSpan smart
552 * class.
553 *
554 * The Limited->InInit->Ready, Limited->InInit->Limited and
555 * Limited->InInit->InitFailed transition is done by the AutoReinitSpan smart
556 * class.
557 *
558 * The Ready->InUninit->NotReady and InitFailed->InUninit->NotReady
559 * transitions are done by the AutoUninitSpan smart class.
560 *
561 * In order to maintain the primary state integrity and declared functionality
562 * all subclasses must:
563 *
564 * 1) Use the above Auto*Span classes to perform state transitions. See the
565 * individual class descriptions for details.
566 *
567 * 2) All public methods of subclasses (i.e. all methods that can be called
568 * directly, not only from within other methods of the subclass) must have a
569 * standard prolog as described in the AutoCaller and AutoLimitedCaller
570 * documentation. Alternatively, they must use addCaller()/releaseCaller()
571 * directly (and therefore have both the prolog and the epilog), but this is
572 * not recommended.
573 */
574class ATL_NO_VTABLE VirtualBoxBase
575 : public VirtualBoxTranslatable,
576 public CComObjectRootEx<CComMultiThreadModel>
577#if !defined (VBOX_WITH_XPCOM)
578 , public ISupportErrorInfo
579#endif
580{
581public:
582 enum State { NotReady, Ready, InInit, InUninit, InitFailed, Limited };
583
584 VirtualBoxBase();
585 virtual ~VirtualBoxBase();
586
587 /**
588 * Unintialization method.
589 *
590 * Must be called by all final implementations (component classes) when the
591 * last reference to the object is released, before calling the destructor.
592 *
593 * This method is also automatically called by the uninit() method of this
594 * object's parent if this object is a dependent child of a class derived
595 * from VirtualBoxBaseWithChildren (see
596 * VirtualBoxBaseWithChildren::addDependentChild).
597 *
598 * @note Never call this method the AutoCaller scope or after the
599 * #addCaller() call not paired by #releaseCaller() because it is a
600 * guaranteed deadlock. See AutoUninitSpan for details.
601 */
602 virtual void uninit()
603 { }
604
605 virtual HRESULT addCaller(State *aState = NULL,
606 bool aLimited = false);
607 virtual void releaseCaller();
608
609 /**
610 * Adds a limited caller. This method is equivalent to doing
611 * <tt>addCaller (aState, true)</tt>, but it is preferred because provides
612 * better self-descriptiveness. See #addCaller() for more info.
613 */
614 HRESULT addLimitedCaller(State *aState = NULL)
615 {
616 return addCaller(aState, true /* aLimited */);
617 }
618
619 /**
620 * Pure virtual method for simple run-time type identification without
621 * having to enable C++ RTTI.
622 *
623 * This *must* be implemented by every subclass deriving from VirtualBoxBase;
624 * use the VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT macro to do that most easily.
625 */
626 virtual const IID& getClassIID() const = 0;
627
628 /**
629 * Pure virtual method for simple run-time type identification without
630 * having to enable C++ RTTI.
631 *
632 * This *must* be implemented by every subclass deriving from VirtualBoxBase;
633 * use the VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT macro to do that most easily.
634 */
635 virtual const char* getComponentName() const = 0;
636
637 /**
638 * Virtual method which determins the locking class to be used for validating
639 * lock order with the standard member lock handle. This method is overridden
640 * in a number of subclasses.
641 */
642 virtual VBoxLockingClass getLockingClass() const
643 {
644 return LOCKCLASS_OTHEROBJECT;
645 }
646
647 virtual RWLockHandle *lockHandle() const;
648
649 /**
650 * Returns a lock handle used to protect the primary state fields (used by
651 * #addCaller(), AutoInitSpan, AutoUninitSpan, etc.). Only intended to be
652 * used for similar purposes in subclasses. WARNING: NO any other locks may
653 * be requested while holding this lock!
654 */
655 WriteLockHandle *stateLockHandle() { return &mStateLock; }
656
657 static HRESULT setErrorInternal(HRESULT aResultCode,
658 const GUID &aIID,
659 const char *aComponent,
660 const Utf8Str &aText,
661 bool aWarning,
662 bool aLogIt);
663
664 HRESULT setError(HRESULT aResultCode, const char *pcsz, ...);
665 HRESULT setWarning(HRESULT aResultCode, const char *pcsz, ...);
666 HRESULT setErrorNoLog(HRESULT aResultCode, const char *pcsz, ...);
667
668private:
669
670 void setState(State aState)
671 {
672 Assert(mState != aState);
673 mState = aState;
674 mStateChangeThread = RTThreadSelf();
675 }
676
677 /** Primary state of this object */
678 State mState;
679 /** Thread that caused the last state change */
680 RTTHREAD mStateChangeThread;
681 /** Total number of active calls to this object */
682 unsigned mCallers;
683 /** Posted when the number of callers drops to zero */
684 RTSEMEVENT mZeroCallersSem;
685 /** Posted when the object goes from InInit/InUninit to some other state */
686 RTSEMEVENTMULTI mInitUninitSem;
687 /** Number of threads waiting for mInitUninitDoneSem */
688 unsigned mInitUninitWaiters;
689
690 /** Protects access to state related data members */
691 WriteLockHandle mStateLock;
692
693 /** User-level object lock for subclasses */
694 mutable RWLockHandle *mObjectLock;
695
696 friend class AutoInitSpan;
697 friend class AutoReinitSpan;
698 friend class AutoUninitSpan;
699};
700
701/**
702 * Dummy macro that is used to shut down Qt's lupdate tool warnings in some
703 * situations. This macro needs to be present inside (better at the very
704 * beginning) of the declaration of the class that inherits from
705 * VirtualBoxSupportTranslation template, to make lupdate happy.
706 */
707#define Q_OBJECT
708
709////////////////////////////////////////////////////////////////////////////////
710
711/**
712 * Base class to track VirtualBoxBaseNEXT chlidren of the component.
713 *
714 * This class is a preferrable VirtualBoxBase replacement for components that
715 * operate with collections of child components. It gives two useful
716 * possibilities:
717 *
718 * <ol><li>
719 * Given an IUnknown instance, it's possible to quickly determine
720 * whether this instance represents a child object that belongs to the
721 * given component, and if so, get a valid VirtualBoxBase pointer to the
722 * child object. The returned pointer can be then safely casted to the
723 * actual class of the child object (to get access to its "internal"
724 * non-interface methods) provided that no other child components implement
725 * the same original COM interface IUnknown is queried from.
726 * </li><li>
727 * When the parent object uninitializes itself, it can easily unintialize
728 * all its VirtualBoxBase derived children (using their
729 * VirtualBoxBase::uninit() implementations). This is done simply by
730 * calling the #uninitDependentChildren() method.
731 * </li></ol>
732 *
733 * In order to let the above work, the following must be done:
734 * <ol><li>
735 * When a child object is initialized, it calls #addDependentChild() of
736 * its parent to register itself within the list of dependent children.
737 * </li><li>
738 * When the child object it is uninitialized, it calls
739 * #removeDependentChild() to unregister itself.
740 * </li></ol>
741 *
742 * Note that if the parent object does not call #uninitDependentChildren() when
743 * it gets uninitialized, it must call uninit() methods of individual children
744 * manually to disconnect them; a failure to do so will cause crashes in these
745 * methods when children get destroyed. The same applies to children not calling
746 * #removeDependentChild() when getting destroyed.
747 *
748 * Note that children added by #addDependentChild() are <b>weakly</b> referenced
749 * (i.e. AddRef() is not called), so when a child object is deleted externally
750 * (because it's reference count goes to zero), it will automatically remove
751 * itself from the map of dependent children provided that it follows the rules
752 * described here.
753 *
754 * Access to the child list is serialized using the #childrenLock() lock handle
755 * (which defaults to the general object lock handle (see
756 * VirtualBoxBase::lockHandle()). This lock is used by all add/remove methods of
757 * this class so be aware of the need to preserve the {parent, child} lock order
758 * when calling these methods.
759 *
760 * Read individual method descriptions to get further information.
761 *
762 * @todo This is a VirtualBoxBaseWithChildren equivalent that uses the
763 * VirtualBoxBaseNEXT implementation. Will completely supersede
764 * VirtualBoxBaseWithChildren after the old VirtualBoxBase implementation
765 * has gone.
766 */
767class VirtualBoxBaseWithChildrenNEXT : public VirtualBoxBase
768{
769public:
770
771 VirtualBoxBaseWithChildrenNEXT()
772 {}
773
774 virtual ~VirtualBoxBaseWithChildrenNEXT()
775 {}
776
777 /**
778 * Lock handle to use when adding/removing child objects from the list of
779 * children. It is guaranteed that no any other lock is requested in methods
780 * of this class while holding this lock.
781 *
782 * @warning By default, this simply returns the general object's lock handle
783 * (see VirtualBoxBase::lockHandle()) which is sufficient for most
784 * cases.
785 */
786 virtual RWLockHandle *childrenLock() { return lockHandle(); }
787
788 /**
789 * Adds the given child to the list of dependent children.
790 *
791 * Usually gets called from the child's init() method.
792 *
793 * @note @a aChild (unless it is in InInit state) must be protected by
794 * VirtualBoxBase::AutoCaller to make sure it is not uninitialized on
795 * another thread during this method's call.
796 *
797 * @note When #childrenLock() is not overloaded (returns the general object
798 * lock) and this method is called from under the child's read or
799 * write lock, make sure the {parent, child} locking order is
800 * preserved by locking the callee (this object) for writing before
801 * the child's lock.
802 *
803 * @param aChild Child object to add (must inherit VirtualBoxBase AND
804 * implement some interface).
805 *
806 * @note Locks #childrenLock() for writing.
807 */
808 template<class C>
809 void addDependentChild(C *aChild)
810 {
811 AssertReturnVoid(aChild != NULL);
812 doAddDependentChild(ComPtr<IUnknown>(aChild), aChild);
813 }
814
815 /**
816 * Equivalent to template <class C> void addDependentChild (C *aChild)
817 * but takes a ComObjPtr<C> argument.
818 */
819 template<class C>
820 void addDependentChild(const ComObjPtr<C> &aChild)
821 {
822 AssertReturnVoid(!aChild.isNull());
823 doAddDependentChild(ComPtr<IUnknown>(static_cast<C *>(aChild)), aChild);
824 }
825
826 /**
827 * Removes the given child from the list of dependent children.
828 *
829 * Usually gets called from the child's uninit() method.
830 *
831 * Keep in mind that the called (parent) object may be no longer available
832 * (i.e. may be deleted deleted) after this method returns, so you must not
833 * call any other parent's methods after that!
834 *
835 * @note Locks #childrenLock() for writing.
836 *
837 * @note @a aChild (unless it is in InUninit state) must be protected by
838 * VirtualBoxBase::AutoCaller to make sure it is not uninitialized on
839 * another thread during this method's call.
840 *
841 * @note When #childrenLock() is not overloaded (returns the general object
842 * lock) and this method is called from under the child's read or
843 * write lock, make sure the {parent, child} locking order is
844 * preserved by locking the callee (this object) for writing before
845 * the child's lock. This is irrelevant when the method is called from
846 * under this object's VirtualBoxBaseProto::AutoUninitSpan (i.e. in
847 * InUninit state) since in this case no locking is done.
848 *
849 * @param aChild Child object to remove.
850 *
851 * @note Locks #childrenLock() for writing.
852 */
853 template<class C>
854 void removeDependentChild(C *aChild)
855 {
856 AssertReturnVoid(aChild != NULL);
857 doRemoveDependentChild(ComPtr<IUnknown>(aChild));
858 }
859
860 /**
861 * Equivalent to template <class C> void removeDependentChild (C *aChild)
862 * but takes a ComObjPtr<C> argument.
863 */
864 template<class C>
865 void removeDependentChild(const ComObjPtr<C> &aChild)
866 {
867 AssertReturnVoid(!aChild.isNull());
868 doRemoveDependentChild(ComPtr<IUnknown>(static_cast<C *>(aChild)));
869 }
870
871protected:
872
873 void uninitDependentChildren();
874
875 VirtualBoxBase *getDependentChild(const ComPtr<IUnknown> &aUnk);
876
877private:
878 void doAddDependentChild(IUnknown *aUnk, VirtualBoxBase *aChild);
879 void doRemoveDependentChild(IUnknown *aUnk);
880
881 typedef std::map<IUnknown*, VirtualBoxBase*> DependentChildren;
882 DependentChildren mDependentChildren;
883};
884
885////////////////////////////////////////////////////////////////////////////////
886
887////////////////////////////////////////////////////////////////////////////////
888
889
890/**
891 * Simple template that manages data structure allocation/deallocation
892 * and supports data pointer sharing (the instance that shares the pointer is
893 * not responsible for memory deallocation as opposed to the instance that
894 * owns it).
895 */
896template <class D>
897class Shareable
898{
899public:
900
901 Shareable() : mData (NULL), mIsShared(FALSE) {}
902 ~Shareable() { free(); }
903
904 void allocate() { attach(new D); }
905
906 virtual void free() {
907 if (mData) {
908 if (!mIsShared)
909 delete mData;
910 mData = NULL;
911 mIsShared = false;
912 }
913 }
914
915 void attach(D *d) {
916 AssertMsg(d, ("new data must not be NULL"));
917 if (d && mData != d) {
918 if (mData && !mIsShared)
919 delete mData;
920 mData = d;
921 mIsShared = false;
922 }
923 }
924
925 void attach(Shareable &d) {
926 AssertMsg(
927 d.mData == mData || !d.mIsShared,
928 ("new data must not be shared")
929 );
930 if (this != &d && !d.mIsShared) {
931 attach(d.mData);
932 d.mIsShared = true;
933 }
934 }
935
936 void share(D *d) {
937 AssertMsg(d, ("new data must not be NULL"));
938 if (mData != d) {
939 if (mData && !mIsShared)
940 delete mData;
941 mData = d;
942 mIsShared = true;
943 }
944 }
945
946 void share(const Shareable &d) { share(d.mData); }
947
948 void attachCopy(const D *d) {
949 AssertMsg(d, ("data to copy must not be NULL"));
950 if (d)
951 attach(new D(*d));
952 }
953
954 void attachCopy(const Shareable &d) {
955 attachCopy(d.mData);
956 }
957
958 virtual D *detach() {
959 D *d = mData;
960 mData = NULL;
961 mIsShared = false;
962 return d;
963 }
964
965 D *data() const {
966 return mData;
967 }
968
969 D *operator->() const {
970 AssertMsg(mData, ("data must not be NULL"));
971 return mData;
972 }
973
974 bool isNull() const { return mData == NULL; }
975 bool operator!() const { return isNull(); }
976
977 bool isShared() const { return mIsShared; }
978
979protected:
980
981 D *mData;
982 bool mIsShared;
983};
984
985/// @todo (dmik) remove after we switch to VirtualBoxBaseNEXT completely
986/**
987 * Simple template that enhances Shareable<> and supports data
988 * backup/rollback/commit (using the copy constructor of the managed data
989 * structure).
990 */
991template<class D>
992class Backupable : public Shareable<D>
993{
994public:
995
996 Backupable() : Shareable<D> (), mBackupData(NULL) {}
997
998 void free()
999 {
1000 AssertMsg(this->mData || !mBackupData, ("backup must be NULL if data is NULL"));
1001 rollback();
1002 Shareable<D>::free();
1003 }
1004
1005 D *detach()
1006 {
1007 AssertMsg(this->mData || !mBackupData, ("backup must be NULL if data is NULL"));
1008 rollback();
1009 return Shareable<D>::detach();
1010 }
1011
1012 void share(const Backupable &d)
1013 {
1014 AssertMsg(!d.isBackedUp(), ("data to share must not be backed up"));
1015 if (!d.isBackedUp())
1016 Shareable<D>::share(d.mData);
1017 }
1018
1019 /**
1020 * Stores the current data pointer in the backup area, allocates new data
1021 * using the copy constructor on current data and makes new data active.
1022 */
1023 void backup()
1024 {
1025 AssertMsg(this->mData, ("data must not be NULL"));
1026 if (this->mData && !mBackupData)
1027 {
1028 D *pNewData = new D(*this->mData);
1029 mBackupData = this->mData;
1030 this->mData = pNewData;
1031 }
1032 }
1033
1034 /**
1035 * Deletes new data created by #backup() and restores previous data pointer
1036 * stored in the backup area, making it active again.
1037 */
1038 void rollback()
1039 {
1040 if (this->mData && mBackupData)
1041 {
1042 delete this->mData;
1043 this->mData = mBackupData;
1044 mBackupData = NULL;
1045 }
1046 }
1047
1048 /**
1049 * Commits current changes by deleting backed up data and clearing up the
1050 * backup area. The new data pointer created by #backup() remains active
1051 * and becomes the only managed pointer.
1052 *
1053 * This method is much faster than #commitCopy() (just a single pointer
1054 * assignment operation), but makes the previous data pointer invalid
1055 * (because it is freed). For this reason, this method must not be
1056 * used if it's possible that data managed by this instance is shared with
1057 * some other Shareable instance. See #commitCopy().
1058 */
1059 void commit()
1060 {
1061 if (this->mData && mBackupData)
1062 {
1063 if (!this->mIsShared)
1064 delete mBackupData;
1065 mBackupData = NULL;
1066 this->mIsShared = false;
1067 }
1068 }
1069
1070 /**
1071 * Commits current changes by assigning new data to the previous data
1072 * pointer stored in the backup area using the assignment operator.
1073 * New data is deleted, the backup area is cleared and the previous data
1074 * pointer becomes active and the only managed pointer.
1075 *
1076 * This method is slower than #commit(), but it keeps the previous data
1077 * pointer valid (i.e. new data is copied to the same memory location).
1078 * For that reason it's safe to use this method on instances that share
1079 * managed data with other Shareable instances.
1080 */
1081 void commitCopy()
1082 {
1083 if (this->mData && mBackupData)
1084 {
1085 *mBackupData = *(this->mData);
1086 delete this->mData;
1087 this->mData = mBackupData;
1088 mBackupData = NULL;
1089 }
1090 }
1091
1092 void assignCopy(const D *pData)
1093 {
1094 AssertMsg(this->mData, ("data must not be NULL"));
1095 AssertMsg(pData, ("data to copy must not be NULL"));
1096 if (this->mData && pData)
1097 {
1098 if (!mBackupData)
1099 {
1100 D *pNewData = new D(*pData);
1101 mBackupData = this->mData;
1102 this->mData = pNewData;
1103 }
1104 else
1105 *this->mData = *pData;
1106 }
1107 }
1108
1109 void assignCopy(const Backupable &d)
1110 {
1111 assignCopy(d.mData);
1112 }
1113
1114 bool isBackedUp() const
1115 {
1116 return mBackupData != NULL;
1117 }
1118
1119 D *backedUpData() const
1120 {
1121 return mBackupData;
1122 }
1123
1124protected:
1125
1126 D *mBackupData;
1127};
1128
1129#endif // !____H_VIRTUALBOXBASEIMPL
1130
Note: See TracBrowser for help on using the repository browser.

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