VirtualBox

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

Last change on this file since 33451 was 31539, checked in by vboxsync, 14 years ago

Main: use settings struct for machine user data; remove iprt::MiniString::raw() and change all occurences to c_str()

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 39.4 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.virtualbox.org. 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 .c_str()); \
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 * A variant of 'throw' that hits a debug breakpoint first to make
408 * finding the actual thrower possible.
409 */
410#ifdef DEBUG
411#define DebugBreakThrow(a) \
412 do { \
413 RTAssertDebugBreak(); \
414 throw (a); \
415} while (0)
416#else
417#define DebugBreakThrow(a) throw (a)
418#endif
419
420/**
421 * Parent class of VirtualBoxBase which enables translation support (which
422 * Main doesn't have yet, but this provides the tr() function which will one
423 * day provide translations).
424 *
425 * This class sits in between Lockable and VirtualBoxBase only for the one
426 * reason that the USBProxyService wants translation support but is not
427 * implemented as a COM object, which VirtualBoxBase implies.
428 */
429class ATL_NO_VTABLE VirtualBoxTranslatable
430 : public Lockable
431{
432public:
433
434 /**
435 * Placeholder method with which translations can one day be implemented
436 * in Main. This gets called by the tr() function.
437 * @param context
438 * @param pcszSourceText
439 * @param comment
440 * @return
441 */
442 static const char *translate(const char *context,
443 const char *pcszSourceText,
444 const char *comment = 0)
445 {
446 NOREF(context);
447 NOREF(comment);
448 return pcszSourceText;
449 }
450
451 /**
452 * Translates the given text string by calling translate() and passing
453 * the name of the C class as the first argument ("context of
454 * translation"). See VirtualBoxBase::translate() for more info.
455 *
456 * @param aSourceText String to translate.
457 * @param aComment Comment to the string to resolve possible
458 * ambiguities (NULL means no comment).
459 *
460 * @return Translated version of the source string in UTF-8 encoding, or
461 * the source string itself if the translation is not found in the
462 * specified context.
463 */
464 inline static const char *tr(const char *pcszSourceText,
465 const char *aComment = NULL)
466 {
467 return VirtualBoxTranslatable::translate(NULL, // getComponentName(), eventually
468 pcszSourceText,
469 aComment);
470 }
471};
472
473////////////////////////////////////////////////////////////////////////////////
474//
475// VirtualBoxBase
476//
477////////////////////////////////////////////////////////////////////////////////
478
479#define VIRTUALBOXBASE_ADD_VIRTUAL_COMPONENT_METHODS(cls, iface) \
480 virtual const IID& getClassIID() const \
481 { \
482 return cls::getStaticClassIID(); \
483 } \
484 static const IID& getStaticClassIID() \
485 { \
486 return COM_IIDOF(iface); \
487 } \
488 virtual const char* getComponentName() const \
489 { \
490 return cls::getStaticComponentName(); \
491 } \
492 static const char* getStaticComponentName() \
493 { \
494 return #cls; \
495 }
496
497/**
498 * VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT:
499 * This macro must be used once in the declaration of any class derived
500 * from VirtualBoxBase. It implements the pure virtual getClassIID() and
501 * getComponentName() methods. If this macro is not present, instances
502 * of a class derived from VirtualBoxBase cannot be instantiated.
503 *
504 * @param X The class name, e.g. "Class".
505 * @param IX The interface name which this class implements, e.g. "IClass".
506 */
507#ifdef VBOX_WITH_XPCOM
508 #define VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT(cls, iface) \
509 VIRTUALBOXBASE_ADD_VIRTUAL_COMPONENT_METHODS(cls, iface)
510#else // #ifdef VBOX_WITH_XPCOM
511 #define VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT(cls, iface) \
512 VIRTUALBOXBASE_ADD_VIRTUAL_COMPONENT_METHODS(cls, iface) \
513 STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid) \
514 { \
515 const _ATL_INTMAP_ENTRY* pEntries = cls::_GetEntries(); \
516 Assert(pEntries); \
517 if (!pEntries) \
518 return S_FALSE; \
519 BOOL bSupports = FALSE; \
520 BOOL bISupportErrorInfoFound = FALSE; \
521 while (pEntries->pFunc != NULL && !bSupports) \
522 { \
523 if (!bISupportErrorInfoFound) \
524 bISupportErrorInfoFound = InlineIsEqualGUID(*(pEntries->piid), IID_ISupportErrorInfo); \
525 else \
526 bSupports = InlineIsEqualGUID(*(pEntries->piid), riid); \
527 pEntries++; \
528 } \
529 Assert(bISupportErrorInfoFound); \
530 return bSupports ? S_OK : S_FALSE; \
531 }
532#endif // #ifdef VBOX_WITH_XPCOM
533
534/**
535 * Abstract base class for all component classes implementing COM
536 * interfaces of the VirtualBox COM library.
537 *
538 * Declares functionality that should be available in all components.
539 *
540 * Among the basic functionality implemented by this class is the primary object
541 * state that indicates if the object is ready to serve the calls, and if not,
542 * what stage it is currently at. Here is the primary state diagram:
543 *
544 * +-------------------------------------------------------+
545 * | |
546 * | (InitFailed) -----------------------+ |
547 * | ^ | |
548 * v | v |
549 * [*] ---> NotReady ----> (InInit) -----> Ready -----> (InUninit) ----+
550 * ^ |
551 * | v
552 * | Limited
553 * | |
554 * +-------+
555 *
556 * The object is fully operational only when its state is Ready. The Limited
557 * state means that only some vital part of the object is operational, and it
558 * requires some sort of reinitialization to become fully operational. The
559 * NotReady state means the object is basically dead: it either was not yet
560 * initialized after creation at all, or was uninitialized and is waiting to be
561 * destroyed when the last reference to it is released. All other states are
562 * transitional.
563 *
564 * The NotReady->InInit->Ready, NotReady->InInit->Limited and
565 * NotReady->InInit->InitFailed transition is done by the AutoInitSpan smart
566 * class.
567 *
568 * The Limited->InInit->Ready, Limited->InInit->Limited and
569 * Limited->InInit->InitFailed transition is done by the AutoReinitSpan smart
570 * class.
571 *
572 * The Ready->InUninit->NotReady and InitFailed->InUninit->NotReady
573 * transitions are done by the AutoUninitSpan smart class.
574 *
575 * In order to maintain the primary state integrity and declared functionality
576 * all subclasses must:
577 *
578 * 1) Use the above Auto*Span classes to perform state transitions. See the
579 * individual class descriptions for details.
580 *
581 * 2) All public methods of subclasses (i.e. all methods that can be called
582 * directly, not only from within other methods of the subclass) must have a
583 * standard prolog as described in the AutoCaller and AutoLimitedCaller
584 * documentation. Alternatively, they must use addCaller()/releaseCaller()
585 * directly (and therefore have both the prolog and the epilog), but this is
586 * not recommended.
587 */
588class ATL_NO_VTABLE VirtualBoxBase
589 : public VirtualBoxTranslatable,
590 public CComObjectRootEx<CComMultiThreadModel>
591#if !defined (VBOX_WITH_XPCOM)
592 , public ISupportErrorInfo
593#endif
594{
595public:
596 enum State { NotReady, Ready, InInit, InUninit, InitFailed, Limited };
597
598 VirtualBoxBase();
599 virtual ~VirtualBoxBase();
600
601 /**
602 * Unintialization method.
603 *
604 * Must be called by all final implementations (component classes) when the
605 * last reference to the object is released, before calling the destructor.
606 *
607 * This method is also automatically called by the uninit() method of this
608 * object's parent if this object is a dependent child of a class derived
609 * from VirtualBoxBaseWithChildren (see
610 * VirtualBoxBaseWithChildren::addDependentChild).
611 *
612 * @note Never call this method the AutoCaller scope or after the
613 * #addCaller() call not paired by #releaseCaller() because it is a
614 * guaranteed deadlock. See AutoUninitSpan for details.
615 */
616 virtual void uninit()
617 { }
618
619 virtual HRESULT addCaller(State *aState = NULL,
620 bool aLimited = false);
621 virtual void releaseCaller();
622
623 /**
624 * Adds a limited caller. This method is equivalent to doing
625 * <tt>addCaller (aState, true)</tt>, but it is preferred because provides
626 * better self-descriptiveness. See #addCaller() for more info.
627 */
628 HRESULT addLimitedCaller(State *aState = NULL)
629 {
630 return addCaller(aState, true /* aLimited */);
631 }
632
633 /**
634 * Pure virtual method for simple run-time type identification without
635 * having to enable C++ RTTI.
636 *
637 * This *must* be implemented by every subclass deriving from VirtualBoxBase;
638 * use the VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT macro to do that most easily.
639 */
640 virtual const IID& getClassIID() const = 0;
641
642 /**
643 * Pure virtual method for simple run-time type identification without
644 * having to enable C++ RTTI.
645 *
646 * This *must* be implemented by every subclass deriving from VirtualBoxBase;
647 * use the VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT macro to do that most easily.
648 */
649 virtual const char* getComponentName() const = 0;
650
651 /**
652 * Virtual method which determins the locking class to be used for validating
653 * lock order with the standard member lock handle. This method is overridden
654 * in a number of subclasses.
655 */
656 virtual VBoxLockingClass getLockingClass() const
657 {
658 return LOCKCLASS_OTHEROBJECT;
659 }
660
661 virtual RWLockHandle *lockHandle() const;
662
663 /**
664 * Returns a lock handle used to protect the primary state fields (used by
665 * #addCaller(), AutoInitSpan, AutoUninitSpan, etc.). Only intended to be
666 * used for similar purposes in subclasses. WARNING: NO any other locks may
667 * be requested while holding this lock!
668 */
669 WriteLockHandle *stateLockHandle() { return &mStateLock; }
670
671 static HRESULT setErrorInternal(HRESULT aResultCode,
672 const GUID &aIID,
673 const char *aComponent,
674 const Utf8Str &aText,
675 bool aWarning,
676 bool aLogIt);
677
678 HRESULT setError(HRESULT aResultCode, const char *pcsz, ...);
679 HRESULT setWarning(HRESULT aResultCode, const char *pcsz, ...);
680 HRESULT setErrorNoLog(HRESULT aResultCode, const char *pcsz, ...);
681
682private:
683
684 void setState(State aState)
685 {
686 Assert(mState != aState);
687 mState = aState;
688 mStateChangeThread = RTThreadSelf();
689 }
690
691 /** Primary state of this object */
692 State mState;
693 /** Thread that caused the last state change */
694 RTTHREAD mStateChangeThread;
695 /** Total number of active calls to this object */
696 unsigned mCallers;
697 /** Posted when the number of callers drops to zero */
698 RTSEMEVENT mZeroCallersSem;
699 /** Posted when the object goes from InInit/InUninit to some other state */
700 RTSEMEVENTMULTI mInitUninitSem;
701 /** Number of threads waiting for mInitUninitDoneSem */
702 unsigned mInitUninitWaiters;
703
704 /** Protects access to state related data members */
705 WriteLockHandle mStateLock;
706
707 /** User-level object lock for subclasses */
708 mutable RWLockHandle *mObjectLock;
709
710 friend class AutoInitSpan;
711 friend class AutoReinitSpan;
712 friend class AutoUninitSpan;
713};
714
715/**
716 * Dummy macro that is used to shut down Qt's lupdate tool warnings in some
717 * situations. This macro needs to be present inside (better at the very
718 * beginning) of the declaration of the class that inherits from
719 * VirtualBoxSupportTranslation template, to make lupdate happy.
720 */
721#define Q_OBJECT
722
723////////////////////////////////////////////////////////////////////////////////
724
725/**
726 * Base class to track VirtualBoxBaseNEXT chlidren of the component.
727 *
728 * This class is a preferrable VirtualBoxBase replacement for components that
729 * operate with collections of child components. It gives two useful
730 * possibilities:
731 *
732 * <ol><li>
733 * Given an IUnknown instance, it's possible to quickly determine
734 * whether this instance represents a child object that belongs to the
735 * given component, and if so, get a valid VirtualBoxBase pointer to the
736 * child object. The returned pointer can be then safely casted to the
737 * actual class of the child object (to get access to its "internal"
738 * non-interface methods) provided that no other child components implement
739 * the same original COM interface IUnknown is queried from.
740 * </li><li>
741 * When the parent object uninitializes itself, it can easily unintialize
742 * all its VirtualBoxBase derived children (using their
743 * VirtualBoxBase::uninit() implementations). This is done simply by
744 * calling the #uninitDependentChildren() method.
745 * </li></ol>
746 *
747 * In order to let the above work, the following must be done:
748 * <ol><li>
749 * When a child object is initialized, it calls #addDependentChild() of
750 * its parent to register itself within the list of dependent children.
751 * </li><li>
752 * When the child object it is uninitialized, it calls
753 * #removeDependentChild() to unregister itself.
754 * </li></ol>
755 *
756 * Note that if the parent object does not call #uninitDependentChildren() when
757 * it gets uninitialized, it must call uninit() methods of individual children
758 * manually to disconnect them; a failure to do so will cause crashes in these
759 * methods when children get destroyed. The same applies to children not calling
760 * #removeDependentChild() when getting destroyed.
761 *
762 * Note that children added by #addDependentChild() are <b>weakly</b> referenced
763 * (i.e. AddRef() is not called), so when a child object is deleted externally
764 * (because it's reference count goes to zero), it will automatically remove
765 * itself from the map of dependent children provided that it follows the rules
766 * described here.
767 *
768 * Access to the child list is serialized using the #childrenLock() lock handle
769 * (which defaults to the general object lock handle (see
770 * VirtualBoxBase::lockHandle()). This lock is used by all add/remove methods of
771 * this class so be aware of the need to preserve the {parent, child} lock order
772 * when calling these methods.
773 *
774 * Read individual method descriptions to get further information.
775 *
776 * @todo This is a VirtualBoxBaseWithChildren equivalent that uses the
777 * VirtualBoxBaseNEXT implementation. Will completely supersede
778 * VirtualBoxBaseWithChildren after the old VirtualBoxBase implementation
779 * has gone.
780 */
781class VirtualBoxBaseWithChildrenNEXT : public VirtualBoxBase
782{
783public:
784
785 VirtualBoxBaseWithChildrenNEXT()
786 {}
787
788 virtual ~VirtualBoxBaseWithChildrenNEXT()
789 {}
790
791 /**
792 * Lock handle to use when adding/removing child objects from the list of
793 * children. It is guaranteed that no any other lock is requested in methods
794 * of this class while holding this lock.
795 *
796 * @warning By default, this simply returns the general object's lock handle
797 * (see VirtualBoxBase::lockHandle()) which is sufficient for most
798 * cases.
799 */
800 virtual RWLockHandle *childrenLock() { return lockHandle(); }
801
802 /**
803 * Adds the given child to the list of dependent children.
804 *
805 * Usually gets called from the child's init() method.
806 *
807 * @note @a aChild (unless it is in InInit state) must be protected by
808 * VirtualBoxBase::AutoCaller to make sure it is not uninitialized on
809 * another thread during this method's call.
810 *
811 * @note When #childrenLock() is not overloaded (returns the general object
812 * lock) and this method is called from under the child's read or
813 * write lock, make sure the {parent, child} locking order is
814 * preserved by locking the callee (this object) for writing before
815 * the child's lock.
816 *
817 * @param aChild Child object to add (must inherit VirtualBoxBase AND
818 * implement some interface).
819 *
820 * @note Locks #childrenLock() for writing.
821 */
822 template<class C>
823 void addDependentChild(C *aChild)
824 {
825 AssertReturnVoid(aChild != NULL);
826 doAddDependentChild(ComPtr<IUnknown>(aChild), aChild);
827 }
828
829 /**
830 * Equivalent to template <class C> void addDependentChild (C *aChild)
831 * but takes a ComObjPtr<C> argument.
832 */
833 template<class C>
834 void addDependentChild(const ComObjPtr<C> &aChild)
835 {
836 AssertReturnVoid(!aChild.isNull());
837 doAddDependentChild(ComPtr<IUnknown>(static_cast<C *>(aChild)), aChild);
838 }
839
840 /**
841 * Removes the given child from the list of dependent children.
842 *
843 * Usually gets called from the child's uninit() method.
844 *
845 * Keep in mind that the called (parent) object may be no longer available
846 * (i.e. may be deleted deleted) after this method returns, so you must not
847 * call any other parent's methods after that!
848 *
849 * @note Locks #childrenLock() for writing.
850 *
851 * @note @a aChild (unless it is in InUninit state) must be protected by
852 * VirtualBoxBase::AutoCaller to make sure it is not uninitialized on
853 * another thread during this method's call.
854 *
855 * @note When #childrenLock() is not overloaded (returns the general object
856 * lock) and this method is called from under the child's read or
857 * write lock, make sure the {parent, child} locking order is
858 * preserved by locking the callee (this object) for writing before
859 * the child's lock. This is irrelevant when the method is called from
860 * under this object's VirtualBoxBaseProto::AutoUninitSpan (i.e. in
861 * InUninit state) since in this case no locking is done.
862 *
863 * @param aChild Child object to remove.
864 *
865 * @note Locks #childrenLock() for writing.
866 */
867 template<class C>
868 void removeDependentChild(C *aChild)
869 {
870 AssertReturnVoid(aChild != NULL);
871 doRemoveDependentChild(ComPtr<IUnknown>(aChild));
872 }
873
874 /**
875 * Equivalent to template <class C> void removeDependentChild (C *aChild)
876 * but takes a ComObjPtr<C> argument.
877 */
878 template<class C>
879 void removeDependentChild(const ComObjPtr<C> &aChild)
880 {
881 AssertReturnVoid(!aChild.isNull());
882 doRemoveDependentChild(ComPtr<IUnknown>(static_cast<C *>(aChild)));
883 }
884
885protected:
886
887 void uninitDependentChildren();
888
889 VirtualBoxBase *getDependentChild(const ComPtr<IUnknown> &aUnk);
890
891private:
892 void doAddDependentChild(IUnknown *aUnk, VirtualBoxBase *aChild);
893 void doRemoveDependentChild(IUnknown *aUnk);
894
895 typedef std::map<IUnknown*, VirtualBoxBase*> DependentChildren;
896 DependentChildren mDependentChildren;
897};
898
899////////////////////////////////////////////////////////////////////////////////
900
901////////////////////////////////////////////////////////////////////////////////
902
903
904/**
905 * Simple template that manages data structure allocation/deallocation
906 * and supports data pointer sharing (the instance that shares the pointer is
907 * not responsible for memory deallocation as opposed to the instance that
908 * owns it).
909 */
910template <class D>
911class Shareable
912{
913public:
914
915 Shareable() : mData (NULL), mIsShared(FALSE) {}
916 ~Shareable() { free(); }
917
918 void allocate() { attach(new D); }
919
920 virtual void free() {
921 if (mData) {
922 if (!mIsShared)
923 delete mData;
924 mData = NULL;
925 mIsShared = false;
926 }
927 }
928
929 void attach(D *d) {
930 AssertMsg(d, ("new data must not be NULL"));
931 if (d && mData != d) {
932 if (mData && !mIsShared)
933 delete mData;
934 mData = d;
935 mIsShared = false;
936 }
937 }
938
939 void attach(Shareable &d) {
940 AssertMsg(
941 d.mData == mData || !d.mIsShared,
942 ("new data must not be shared")
943 );
944 if (this != &d && !d.mIsShared) {
945 attach(d.mData);
946 d.mIsShared = true;
947 }
948 }
949
950 void share(D *d) {
951 AssertMsg(d, ("new data must not be NULL"));
952 if (mData != d) {
953 if (mData && !mIsShared)
954 delete mData;
955 mData = d;
956 mIsShared = true;
957 }
958 }
959
960 void share(const Shareable &d) { share(d.mData); }
961
962 void attachCopy(const D *d) {
963 AssertMsg(d, ("data to copy must not be NULL"));
964 if (d)
965 attach(new D(*d));
966 }
967
968 void attachCopy(const Shareable &d) {
969 attachCopy(d.mData);
970 }
971
972 virtual D *detach() {
973 D *d = mData;
974 mData = NULL;
975 mIsShared = false;
976 return d;
977 }
978
979 D *data() const {
980 return mData;
981 }
982
983 D *operator->() const {
984 AssertMsg(mData, ("data must not be NULL"));
985 return mData;
986 }
987
988 bool isNull() const { return mData == NULL; }
989 bool operator!() const { return isNull(); }
990
991 bool isShared() const { return mIsShared; }
992
993protected:
994
995 D *mData;
996 bool mIsShared;
997};
998
999/// @todo (dmik) remove after we switch to VirtualBoxBaseNEXT completely
1000/**
1001 * Simple template that enhances Shareable<> and supports data
1002 * backup/rollback/commit (using the copy constructor of the managed data
1003 * structure).
1004 */
1005template<class D>
1006class Backupable : public Shareable<D>
1007{
1008public:
1009
1010 Backupable() : Shareable<D> (), mBackupData(NULL) {}
1011
1012 void free()
1013 {
1014 AssertMsg(this->mData || !mBackupData, ("backup must be NULL if data is NULL"));
1015 rollback();
1016 Shareable<D>::free();
1017 }
1018
1019 D *detach()
1020 {
1021 AssertMsg(this->mData || !mBackupData, ("backup must be NULL if data is NULL"));
1022 rollback();
1023 return Shareable<D>::detach();
1024 }
1025
1026 void share(const Backupable &d)
1027 {
1028 AssertMsg(!d.isBackedUp(), ("data to share must not be backed up"));
1029 if (!d.isBackedUp())
1030 Shareable<D>::share(d.mData);
1031 }
1032
1033 /**
1034 * Stores the current data pointer in the backup area, allocates new data
1035 * using the copy constructor on current data and makes new data active.
1036 */
1037 void backup()
1038 {
1039 AssertMsg(this->mData, ("data must not be NULL"));
1040 if (this->mData && !mBackupData)
1041 {
1042 D *pNewData = new D(*this->mData);
1043 mBackupData = this->mData;
1044 this->mData = pNewData;
1045 }
1046 }
1047
1048 /**
1049 * Deletes new data created by #backup() and restores previous data pointer
1050 * stored in the backup area, making it active again.
1051 */
1052 void rollback()
1053 {
1054 if (this->mData && mBackupData)
1055 {
1056 delete this->mData;
1057 this->mData = mBackupData;
1058 mBackupData = NULL;
1059 }
1060 }
1061
1062 /**
1063 * Commits current changes by deleting backed up data and clearing up the
1064 * backup area. The new data pointer created by #backup() remains active
1065 * and becomes the only managed pointer.
1066 *
1067 * This method is much faster than #commitCopy() (just a single pointer
1068 * assignment operation), but makes the previous data pointer invalid
1069 * (because it is freed). For this reason, this method must not be
1070 * used if it's possible that data managed by this instance is shared with
1071 * some other Shareable instance. See #commitCopy().
1072 */
1073 void commit()
1074 {
1075 if (this->mData && mBackupData)
1076 {
1077 if (!this->mIsShared)
1078 delete mBackupData;
1079 mBackupData = NULL;
1080 this->mIsShared = false;
1081 }
1082 }
1083
1084 /**
1085 * Commits current changes by assigning new data to the previous data
1086 * pointer stored in the backup area using the assignment operator.
1087 * New data is deleted, the backup area is cleared and the previous data
1088 * pointer becomes active and the only managed pointer.
1089 *
1090 * This method is slower than #commit(), but it keeps the previous data
1091 * pointer valid (i.e. new data is copied to the same memory location).
1092 * For that reason it's safe to use this method on instances that share
1093 * managed data with other Shareable instances.
1094 */
1095 void commitCopy()
1096 {
1097 if (this->mData && mBackupData)
1098 {
1099 *mBackupData = *(this->mData);
1100 delete this->mData;
1101 this->mData = mBackupData;
1102 mBackupData = NULL;
1103 }
1104 }
1105
1106 void assignCopy(const D *pData)
1107 {
1108 AssertMsg(this->mData, ("data must not be NULL"));
1109 AssertMsg(pData, ("data to copy must not be NULL"));
1110 if (this->mData && pData)
1111 {
1112 if (!mBackupData)
1113 {
1114 D *pNewData = new D(*pData);
1115 mBackupData = this->mData;
1116 this->mData = pNewData;
1117 }
1118 else
1119 *this->mData = *pData;
1120 }
1121 }
1122
1123 void assignCopy(const Backupable &d)
1124 {
1125 assignCopy(d.mData);
1126 }
1127
1128 bool isBackedUp() const
1129 {
1130 return mBackupData != NULL;
1131 }
1132
1133 D *backedUpData() const
1134 {
1135 return mBackupData;
1136 }
1137
1138protected:
1139
1140 D *mBackupData;
1141};
1142
1143#endif // !____H_VIRTUALBOXBASEIMPL
1144
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