VirtualBox

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

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

Main: rework 'save registries' logic to ensure that all media registries get saved, not just the global VirtualBox.xml file

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