VirtualBoxBase.h revision 501181107e73684ab109521ba371063734cd1d76
/** @file
* VirtualBox COM base classes definition
*/
/*
* Copyright (C) 2006-2012 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#ifndef ____H_VIRTUALBOXBASEIMPL
#define ____H_VIRTUALBOXBASEIMPL
#include <list>
#include <map>
#include "VBox/com/AutoLock.h"
#include "VBox/com/VirtualBox.h"
// avoid including VBox/settings.h and VBox/xml.h;
// only declare the classes
{
}
{
}
////////////////////////////////////////////////////////////////////////////////
//
// COM helpers
//
////////////////////////////////////////////////////////////////////////////////
#if !defined(VBOX_WITH_XPCOM)
#include <atlcom.h>
/* use a special version of the singleton class factory,
* see KB811591 in msdn for more info. */
#define DECLARE_CLASSFACTORY_SINGLETON(obj) DECLARE_CLASSFACTORY_EX(CMyComClassFactorySingleton<obj>)
{
// IClassFactory
{
{
// Aggregation is not supported in singleton objects.
else
{
{
Lock();
{
// Fix: The following If statement was moved inside the __try statement.
// Did another thread arrive here first?
{
// lock the module to indicate activity
// (necessary for the monitor shutdown thread to correctly
// terminate the module in case when CreateInstance() fails)
_pAtlModule->Lock();
CComObjectCached<T> *p;
if (SUCCEEDED(m_hrCreate))
{
if (FAILED(m_hrCreate))
{
delete p;
}
}
_pAtlModule->Unlock();
}
}
{
Unlock();
}
}
if (m_hrCreate == S_OK)
{
}
else
{
hRes = m_hrCreate;
}
}
}
return hRes;
}
};
#endif /* !defined(VBOX_WITH_XPCOM) */
////////////////////////////////////////////////////////////////////////////////
//
// Macros
//
////////////////////////////////////////////////////////////////////////////////
/**
* Special version of the Assert macro to be used within VirtualBoxBase
* subclasses.
*
* In the debug build, this macro is equivalent to Assert.
* In the release build, this macro uses |setError(E_FAIL, ...)| to set the
* error info from the asserted expression.
*
* @see VirtualBoxBase::setError
*
* @param expr Expression which should be true.
*/
#if defined(DEBUG)
#else
do { \
if (RT_UNLIKELY(!(expr))) \
"Assertion failed: [%s] at '%s' (%d) in %s.\nPlease contact the product vendor!", \
} while (0)
#endif
/**
* Special version of the AssertFailed macro to be used within VirtualBoxBase
* subclasses.
*
* In the debug build, this macro is equivalent to AssertFailed.
* In the release build, this macro uses |setError(E_FAIL, ...)| to set the
* error info from the asserted expression.
*
* @see VirtualBoxBase::setError
*
*/
#if defined(DEBUG)
#define ComAssertFailed() AssertFailed()
#else
#define ComAssertFailed() \
do { \
"Assertion failed: at '%s' (%d) in %s.\nPlease contact the product vendor!", \
} while (0)
#endif
/**
* Special version of the AssertMsg macro to be used within VirtualBoxBase
* subclasses.
*
* See ComAssert for more info.
*
* @param expr Expression which should be true.
* @param a printf argument list (in parenthesis).
*/
#if defined(DEBUG)
#else
#define ComAssertMsg(expr, a) \
do { \
if (RT_UNLIKELY(!(expr))) \
"Assertion failed: [%s] at '%s' (%d) in %s.\n%s.\nPlease contact the product vendor!", \
} while (0)
#endif
/**
* Special version of the AssertRC macro to be used within VirtualBoxBase
* subclasses.
*
* See ComAssert for more info.
*
* @param vrc VBox status code.
*/
#if defined(DEBUG)
#else
#endif
/**
* Special version of the AssertMsgRC macro to be used within VirtualBoxBase
* subclasses.
*
* See ComAssert for more info.
*
* @param vrc VBox status code.
* @param msg printf argument list (in parenthesis).
*/
#if defined(DEBUG)
#else
#endif
/**
* Special version of the AssertComRC macro to be used within VirtualBoxBase
* subclasses.
*
* See ComAssert for more info.
*
* @param rc COM result code
*/
#if defined(DEBUG)
#else
#endif
/** Special version of ComAssert that returns ret if expr fails */
/** Special version of ComAssertMsg that returns ret if expr fails */
/** Special version of ComAssertRC that returns ret if vrc does not succeed */
/** Special version of ComAssertComRC that returns ret if rc does not succeed */
/** Special version of ComAssertComRC that returns rc if rc does not succeed */
#define ComAssertComRCRetRC(rc) \
/** Special version of ComAssert that returns ret */
#define ComAssertFailedRet(ret) \
do { ComAssertFailed(); return (ret); } while (0)
/** Special version of ComAssert that evaluates eval and breaks if expr fails */
/** Special version of ComAssertMsg that evaluates eval and breaks if expr fails */
/** Special version of ComAssertRC that evaluates eval and breaks if vrc does not succeed */
/** Special version of ComAssertFailed that evaluates eval and breaks */
#define ComAssertFailedBreak(eval) \
/** Special version of ComAssertMsgFailed that evaluates eval and breaks */
/** Special version of ComAssertComRC that evaluates eval and breaks if rc does not succeed */
/** Special version of ComAssertComRC that just breaks if rc does not succeed */
#define ComAssertComRCBreakRC(rc) \
/** Special version of ComAssert that evaluates eval and throws it if expr fails */
/** Special version of ComAssertRC that evaluates eval and throws it if vrc does not succeed */
/** Special version of ComAssertComRC that evaluates eval and throws it if rc does not succeed */
/** Special version of ComAssertComRC that just throws rc if rc does not succeed */
#define ComAssertComRCThrowRC(rc) \
/** Special version of ComAssert that throws eval */
#define ComAssertFailedThrow(eval) \
////////////////////////////////////////////////////////////////////////////////
/**
* Checks that the pointer argument is not NULL and returns E_INVALIDARG +
* extended error info on failure.
* @param arg Input pointer-type argument (strings, interface pointers...)
*/
#define CheckComArgNotNull(arg) \
do { \
} while (0)
/**
* Checks that the pointer argument is a valid pointer or NULL and returns
* E_INVALIDARG + extended error info on failure.
* @param arg Input pointer-type argument (strings, interface pointers...)
*/
#define CheckComArgMaybeNull(arg) \
do { \
} while (0)
/**
* Checks that safe array argument is not NULL and returns E_INVALIDARG +
* extended error info on failure.
* @param arg Input safe array argument (strings, interface pointers...)
*/
#define CheckComArgSafeArrayNotNull(arg) \
do { \
} while (0)
/**
* Checks that a string input argument is valid (not NULL or obviously invalid
* pointer), returning E_INVALIDARG + extended error info if invalid.
* @param a_bstrIn Input string argument (IN_BSTR).
*/
#define CheckComArgStr(a_bstrIn) \
do { \
} while (0)
/**
* Checks that the string argument is not a NULL, a invalid pointer or an empty
* string, returning E_INVALIDARG + extended error info on failure.
* @param a_bstrIn Input string argument (BSTR etc.).
*/
#define CheckComArgStrNotEmptyOrNull(a_bstrIn) \
do { \
} while (0)
/**
* Converts the Guid input argument (string) to a Guid object, returns with
* E_INVALIDARG and error message on failure.
*
* @param a_Arg Argument.
* @param a_GuidVar The Guid variable name.
*/
do { \
return setError(E_INVALIDARG, \
} while (0)
/**
* Checks that the given expression (that must involve the argument) is true and
* returns E_INVALIDARG + extended error info on failure.
* @param arg Argument.
* @param expr Expression to evaluate.
*/
do { \
if (RT_UNLIKELY(!(expr))) \
return setError(E_INVALIDARG, \
} while (0)
/**
* Checks that the given expression (that must involve the argument) is true and
* returns E_INVALIDARG + extended error info on failure. The error message must
* be customized.
* @param arg Argument.
* @param expr Expression to evaluate.
* @param msg Parenthesized printf-like expression (must start with a verb,
* like "must be one of...", "is not within...").
*/
do { \
if (RT_UNLIKELY(!(expr))) \
} while (0)
/**
* Checks that the given pointer to an output argument is valid and returns
* E_POINTER + extended error info otherwise.
* @param arg Pointer argument.
*/
#define CheckComArgOutPointerValid(arg) \
do { \
tr("Output argument %s points to invalid memory location (%p)"), \
} while (0)
/**
* Checks that the given pointer to an output safe array argument is valid and
* returns E_POINTER + extended error info otherwise.
* @param arg Safe array argument.
*/
#define CheckComArgOutSafeArrayPointerValid(arg) \
do { \
tr("Output argument %s points to invalid memory location (%p)"), \
} while (0)
/**
* Sets the extended error info and returns E_NOTIMPL.
*/
#define ReturnComNotImplemented() \
do { \
} while (0)
/**
* Declares an empty constructor and destructor for the given class.
* This is useful to prevent the compiler from generating the default
* ctor and dtor, which in turn allows to use forward class statements
* (instead of including their header files) when declaring data members of
* non-fundamental types with constructors (which are always called implicitly
* by constructors and by the destructor of the class).
*
* This macro is to be placed within (the public section of) the class
* declaration. Its counterpart, DEFINE_EMPTY_CTOR_DTOR, must be placed
* somewhere in one of the translation units (usually .cpp source files).
*
* @param cls class to declare a ctor and dtor for
*/
/**
* Defines an empty constructor and destructor for the given class.
* See DECLARE_EMPTY_CTOR_DTOR for more info.
*/
#define DEFINE_EMPTY_CTOR_DTOR(cls) \
/**
* A variant of 'throw' that hits a debug breakpoint first to make
* finding the actual thrower possible.
*/
#ifdef DEBUG
#define DebugBreakThrow(a) \
do { \
RTAssertDebugBreak(); \
throw (a); \
} while (0)
#else
#define DebugBreakThrow(a) throw (a)
#endif
/**
* Parent class of VirtualBoxBase which enables translation support (which
* Main doesn't have yet, but this provides the tr() function which will one
* day provide translations).
*
* This class sits in between Lockable and VirtualBoxBase only for the one
* reason that the USBProxyService wants translation support but is not
* implemented as a COM object, which VirtualBoxBase implies.
*/
{
/**
* Placeholder method with which translations can one day be implemented
* in Main. This gets called by the tr() function.
* @param context
* @param pcszSourceText
* @param comment
* @return
*/
const char *pcszSourceText,
const char *comment = 0)
{
return pcszSourceText;
}
/**
* Translates the given text string by calling translate() and passing
* the name of the C class as the first argument ("context of
* translation"). See VirtualBoxBase::translate() for more info.
*
* @param aSourceText String to translate.
* @param aComment Comment to the string to resolve possible
* ambiguities (NULL means no comment).
*
* @return Translated version of the source string in UTF-8 encoding, or
* the source string itself if the translation is not found in the
* specified context.
*/
inline static const char *tr(const char *pcszSourceText,
{
aComment);
}
};
////////////////////////////////////////////////////////////////////////////////
//
// VirtualBoxBase
//
////////////////////////////////////////////////////////////////////////////////
{ \
return cls::getStaticClassIID(); \
} \
static const IID& getStaticClassIID() \
{ \
} \
virtual const char* getComponentName() const \
{ \
return cls::getStaticComponentName(); \
} \
static const char* getStaticComponentName() \
{ \
return #cls; \
}
/**
* VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT:
* This macro must be used once in the declaration of any class derived
* from VirtualBoxBase. It implements the pure virtual getClassIID() and
* getComponentName() methods. If this macro is not present, instances
* of a class derived from VirtualBoxBase cannot be instantiated.
*
* @param X The class name, e.g. "Class".
* @param IX The interface name which this class implements, e.g. "IClass".
*/
#ifdef VBOX_WITH_XPCOM
#else // #ifdef VBOX_WITH_XPCOM
{ \
if (!pEntries) \
return S_FALSE; \
{ \
if (!bISupportErrorInfoFound) \
else \
pEntries++; \
} \
}
#endif // #ifdef VBOX_WITH_XPCOM
/**
* Abstract base class for all component classes implementing COM
* interfaces of the VirtualBox COM library.
*
* Declares functionality that should be available in all components.
*
* Among the basic functionality implemented by this class is the primary object
* state that indicates if the object is ready to serve the calls, and if not,
* what stage it is currently at. Here is the primary state diagram:
*
* +-------------------------------------------------------+
* | |
* | (InitFailed) -----------------------+ |
* | ^ | |
* v | v |
* [*] ---> NotReady ----> (InInit) -----> Ready -----> (InUninit) ----+
* ^ |
* | v
* | Limited
* | |
* +-------+
*
* The object is fully operational only when its state is Ready. The Limited
* state means that only some vital part of the object is operational, and it
* requires some sort of reinitialization to become fully operational. The
* NotReady state means the object is basically dead: it either was not yet
* initialized after creation at all, or was uninitialized and is waiting to be
* destroyed when the last reference to it is released. All other states are
* transitional.
*
* The NotReady->InInit->Ready, NotReady->InInit->Limited and
* NotReady->InInit->InitFailed transition is done by the AutoInitSpan smart
* class.
*
* The Limited->InInit->Ready, Limited->InInit->Limited and
* Limited->InInit->InitFailed transition is done by the AutoReinitSpan smart
* class.
*
* The Ready->InUninit->NotReady and InitFailed->InUninit->NotReady
* transitions are done by the AutoUninitSpan smart class.
*
* In order to maintain the primary state integrity and declared functionality
* all subclasses must:
*
* 1) Use the above Auto*Span classes to perform state transitions. See the
* individual class descriptions for details.
*
* 2) All public methods of subclasses (i.e. all methods that can be called
* directly, not only from within other methods of the subclass) must have a
* standard prolog as described in the AutoCaller and AutoLimitedCaller
* documentation. Alternatively, they must use addCaller()/releaseCaller()
* directly (and therefore have both the prolog and the epilog), but this is
* not recommended.
*/
#if !defined (VBOX_WITH_XPCOM)
#endif
{
#ifdef RT_OS_WINDOWS
#endif
{
#ifdef RT_OS_WINDOWS
&m_pUnkMarshaler.p);
#else
return S_OK;
#endif
}
void BaseFinalRelease()
{
#ifdef RT_OS_WINDOWS
#endif
}
/**
* Uninitialization method.
*
* Must be called by all final implementations (component classes) when the
* last reference to the object is released, before calling the destructor.
*
* @note Never call this method the AutoCaller scope or after the
* #addCaller() call not paired by #releaseCaller() because it is a
* guaranteed deadlock. See AutoUninitSpan for details.
*/
{ }
bool aLimited = false);
virtual void releaseCaller();
/**
* Adds a limited caller. This method is equivalent to doing
* <tt>addCaller(aState, true)</tt>, but it is preferred because provides
* better self-descriptiveness. See #addCaller() for more info.
*/
{
}
/**
* Pure virtual method for simple run-time type identification without
* having to enable C++ RTTI.
*
* This *must* be implemented by every subclass deriving from VirtualBoxBase;
* use the VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT macro to do that most easily.
*/
/**
* Pure virtual method for simple run-time type identification without
* having to enable C++ RTTI.
*
* This *must* be implemented by every subclass deriving from VirtualBoxBase;
* use the VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT macro to do that most easily.
*/
virtual const char* getComponentName() const = 0;
/**
* Virtual method which determines the locking class to be used for validating
* lock order with the standard member lock handle. This method is overridden
* in a number of subclasses.
*/
{
return LOCKCLASS_OTHEROBJECT;
}
/**
* Returns a lock handle used to protect the primary state fields (used by
* #addCaller(), AutoInitSpan, AutoUninitSpan, etc.). Only intended to be
* used for similar purposes in subclasses. WARNING: NO any other locks may
* be requested while holding this lock!
*/
const char *aComponent,
bool aWarning,
bool aLogIt);
static void clearError(void);
/** Initialize COM for a new thread. */
static HRESULT initializeComForThread(void)
{
#ifndef VBOX_WITH_XPCOM
HRESULT hrc = CoInitializeEx(NULL, COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE | COINIT_SPEED_OVER_MEMORY);
#endif
return S_OK;
}
/** Uninitializes COM for a dying thread. */
static void uninitializeComForThread(void)
{
#ifndef VBOX_WITH_XPCOM
#endif
}
{
}
/** Primary state of this object */
/** Thread that caused the last state change */
/** Total number of active calls to this object */
unsigned mCallers;
/** Posted when the number of callers drops to zero */
/** Number of threads waiting for mInitUninitDoneSem */
unsigned mInitUninitWaiters;
/** Protects access to state related data members */
/** User-level object lock for subclasses */
};
/**
* Dummy macro that is used to shut down Qt's lupdate tool warnings in some
* situations. This macro needs to be present inside (better at the very
* beginning) of the declaration of the class that inherits from
* VirtualBoxTranslatable, to make lupdate happy.
*/
#define Q_OBJECT
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/**
* Simple template that manages data structure allocation/deallocation
* and supports data pointer sharing (the instance that shares the pointer is
* not responsible for memory deallocation as opposed to the instance that
* owns it).
*/
{
if (mData) {
if (!mIsShared)
mIsShared = false;
}
}
void attach(D *d) {
AssertMsg(d, ("new data must not be NULL"));
if (d && mData != d) {
mData = d;
mIsShared = false;
}
}
("new data must not be shared")
);
d.mIsShared = true;
}
}
void share(D *d) {
AssertMsg(d, ("new data must not be NULL"));
if (mData != d) {
mData = d;
mIsShared = true;
}
}
void attachCopy(const D *d) {
AssertMsg(d, ("data to copy must not be NULL"));
if (d)
}
void attachCopy(const Shareable &d) {
attachCopy(d.mData);
}
D *d = mData;
mIsShared = false;
return d;
}
D *data() const {
return mData;
}
D *operator->() const {
return mData;
}
D *mData;
bool mIsShared;
};
/**
* Simple template that enhances Shareable<> and supports data
* structure).
*/
{
void free()
{
rollback();
}
D *detach()
{
rollback();
}
void share(const Backupable &d)
{
if (!d.isBackedUp())
}
/**
* Stores the current data pointer in the backup area, allocates new data
* using the copy constructor on current data and makes new data active.
*
* @deprecated Use backupEx to avoid throwing wild out-of-memory exceptions.
*/
void backup()
{
{
}
}
/**
* Stores the current data pointer in the backup area, allocates new data
* using the copy constructor on current data and makes new data active.
*
* @returns S_OK, E_OUTOFMEMORY or E_FAIL (internal error).
*/
{
{
{
}
{
return E_OUTOFMEMORY;
}
}
return S_OK;
}
/**
* Deletes new data created by #backup() and restores previous data pointer
* stored in the backup area, making it active again.
*/
void rollback()
{
{
mBackupData = NULL;
}
}
/**
* Commits current changes by deleting backed up data and clearing up the
* backup area. The new data pointer created by #backup() remains active
* and becomes the only managed pointer.
*
* This method is much faster than #commitCopy() (just a single pointer
* assignment operation), but makes the previous data pointer invalid
* (because it is freed). For this reason, this method must not be
* used if it's possible that data managed by this instance is shared with
* some other Shareable instance. See #commitCopy().
*/
void commit()
{
{
mBackupData = NULL;
}
}
/**
* Commits current changes by assigning new data to the previous data
* pointer stored in the backup area using the assignment operator.
* New data is deleted, the backup area is cleared and the previous data
* pointer becomes active and the only managed pointer.
*
* This method is slower than #commit(), but it keeps the previous data
* pointer valid (i.e. new data is copied to the same memory location).
* For that reason it's safe to use this method on instances that share
* managed data with other Shareable instances.
*/
void commitCopy()
{
{
mBackupData = NULL;
}
}
void assignCopy(const D *pData)
{
{
if (!mBackupData)
{
}
else
}
}
void assignCopy(const Backupable &d)
{
assignCopy(d.mData);
}
bool isBackedUp() const
{
return mBackupData != NULL;
}
D *backedUpData() const
{
return mBackupData;
}
D *mBackupData;
};
#endif // !____H_VIRTUALBOXBASEIMPL