VirtualBoxBase.h revision 0f44b962ad1a48f10941b03ebb4791ceac2a3c7a
1280N/A/** @file
1280N/A *
1280N/A * VirtualBox COM base classes definition
1280N/A */
1280N/A
1280N/A/*
1280N/A * Copyright (C) 2006-2009 Sun Microsystems, Inc.
1280N/A *
1280N/A * This file is part of VirtualBox Open Source Edition (OSE), as
1280N/A * available from http://www.virtualbox.org. This file is free software;
1280N/A * you can redistribute it and/or modify it under the terms of the GNU
1280N/A * General Public License (GPL) as published by the Free Software
1280N/A * Foundation, in version 2 as it comes in the "COPYING" file of the
1280N/A * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
1280N/A * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
1280N/A *
1280N/A * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
1280N/A * Clara, CA 95054 USA or visit http://www.sun.com if you need
1280N/A * additional information or have any questions.
1280N/A */
1280N/A
1280N/A#ifndef ____H_VIRTUALBOXBASEIMPL
1280N/A#define ____H_VIRTUALBOXBASEIMPL
1280N/A
4134N/A#include <iprt/cdefs.h>
1280N/A#include <iprt/thread.h>
1280N/A
2086N/A#include <list>
1280N/A#include <map>
1280N/A
1280N/A#include "VBox/com/ErrorInfo.h"
1280N/A#include "VBox/com/SupportErrorInfo.h"
1280N/A#include "VBox/com/AutoLock.h"
1280N/A
1280N/A#include "VBox/com/VirtualBox.h"
1280N/A
1280N/A// avoid including VBox/settings.h and VBox/xml.h;
1280N/A// only declare the classes
1280N/Anamespace xml
1280N/A{
3023N/Aclass File;
1280N/A}
1280N/A
1280N/Ausing namespace com;
1280N/Ausing namespace util;
1280N/A
1280N/Aclass AutoInitSpan;
2086N/Aclass AutoUninitSpan;
2086N/A
2602N/Aclass VirtualBox;
2602N/Aclass Machine;
3023N/Aclass Medium;
3023N/Aclass Host;
3023N/Atypedef std::list< ComObjPtr<Medium> > MediaList;
3023N/A
2086N/A////////////////////////////////////////////////////////////////////////////////
1280N/A//
1280N/A// COM helpers
1280N/A//
1280N/A////////////////////////////////////////////////////////////////////////////////
1280N/A
1280N/A#if !defined (VBOX_WITH_XPCOM)
1280N/A
1280N/A#include <atlcom.h>
1280N/A
1280N/A/* use a special version of the singleton class factory,
1280N/A * see KB811591 in msdn for more info. */
1280N/A
1280N/A#undef DECLARE_CLASSFACTORY_SINGLETON
1280N/A#define DECLARE_CLASSFACTORY_SINGLETON(obj) DECLARE_CLASSFACTORY_EX(CMyComClassFactorySingleton<obj>)
1280N/A
1280N/Atemplate <class T>
1280N/Aclass CMyComClassFactorySingleton : public CComClassFactory
1280N/A{
1280N/Apublic:
1280N/A CMyComClassFactorySingleton() : m_hrCreate(S_OK){}
1280N/A virtual ~CMyComClassFactorySingleton(){}
1280N/A // IClassFactory
1280N/A STDMETHOD(CreateInstance)(LPUNKNOWN pUnkOuter, REFIID riid, void** ppvObj)
1280N/A {
1280N/A HRESULT hRes = E_POINTER;
1280N/A if (ppvObj != NULL)
1280N/A {
1280N/A *ppvObj = NULL;
1280N/A // Aggregation is not supported in singleton objects.
1280N/A ATLASSERT(pUnkOuter == NULL);
1280N/A if (pUnkOuter != NULL)
1280N/A hRes = CLASS_E_NOAGGREGATION;
1280N/A else
1280N/A {
1280N/A if (m_hrCreate == S_OK && m_spObj == NULL)
1280N/A {
1280N/A Lock();
1280N/A __try
1280N/A {
1280N/A // Fix: The following If statement was moved inside the __try statement.
1280N/A // Did another thread arrive here first?
1280N/A if (m_hrCreate == S_OK && m_spObj == NULL)
1280N/A {
1280N/A // lock the module to indicate activity
1280N/A // (necessary for the monitor shutdown thread to correctly
1280N/A // terminate the module in case when CreateInstance() fails)
1280N/A _pAtlModule->Lock();
1280N/A CComObjectCached<T> *p;
1280N/A m_hrCreate = CComObjectCached<T>::CreateInstance(&p);
1280N/A if (SUCCEEDED(m_hrCreate))
1280N/A {
1280N/A m_hrCreate = p->QueryInterface(IID_IUnknown, (void**)&m_spObj);
1280N/A if (FAILED(m_hrCreate))
1280N/A {
1280N/A delete p;
1280N/A }
1280N/A }
1280N/A _pAtlModule->Unlock();
1280N/A }
1280N/A }
1280N/A __finally
1280N/A {
1280N/A Unlock();
1280N/A }
1280N/A }
1280N/A if (m_hrCreate == S_OK)
1280N/A {
1280N/A hRes = m_spObj->QueryInterface(riid, ppvObj);
1280N/A }
1280N/A else
1280N/A {
3023N/A hRes = m_hrCreate;
3023N/A }
3023N/A }
3023N/A }
3023N/A return hRes;
3023N/A }
3023N/A HRESULT m_hrCreate;
3023N/A CComPtr<IUnknown> m_spObj;
3023N/A};
3023N/A
3023N/A#endif /* !defined (VBOX_WITH_XPCOM) */
1280N/A
1280N/A////////////////////////////////////////////////////////////////////////////////
1280N/A//
1280N/A// Macros
1280N/A//
1280N/A////////////////////////////////////////////////////////////////////////////////
1280N/A
1280N/A/**
1280N/A * Special version of the Assert macro to be used within VirtualBoxBase
2624N/A * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
1280N/A *
1280N/A * In the debug build, this macro is equivalent to Assert.
1280N/A * In the release build, this macro uses |setError(E_FAIL, ...)| to set the
1280N/A * error info from the asserted expression.
1280N/A *
1280N/A * @see VirtualBoxSupportErrorInfoImpl::setError
1280N/A *
1280N/A * @param expr Expression which should be true.
1280N/A */
1280N/A#if defined (DEBUG)
1280N/A#define ComAssert(expr) Assert(expr)
1280N/A#else
1280N/A#define ComAssert(expr) \
1280N/A do { \
1280N/A if (RT_UNLIKELY(!(expr))) \
1280N/A setError(E_FAIL, "Assertion failed: [%s] at '%s' (%d) in %s.\n" \
1280N/A "Please contact the product vendor!", \
1280N/A #expr, __FILE__, __LINE__, __PRETTY_FUNCTION__); \
1280N/A } while (0)
1280N/A#endif
2624N/A
1280N/A/**
2624N/A * Special version of the AssertMsg macro to be used within VirtualBoxBase
1280N/A * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
2624N/A *
2624N/A * See ComAssert for more info.
1280N/A *
2624N/A * @param expr Expression which should be true.
1280N/A * @param a printf argument list (in parenthesis).
1280N/A */
1280N/A#if defined (DEBUG)
1280N/A#define ComAssertMsg(expr, a) AssertMsg(expr, a)
1280N/A#else
1280N/A#define ComAssertMsg(expr, a) \
1280N/A do { \
1280N/A if (RT_UNLIKELY(!(expr))) \
1280N/A setError(E_FAIL, "Assertion failed: [%s] at '%s' (%d) in %s.\n" \
1280N/A "%s.\n" \
1280N/A "Please contact the product vendor!", \
1280N/A #expr, __FILE__, __LINE__, __PRETTY_FUNCTION__, Utf8StrFmt a .raw()); \
1280N/A } while (0)
1280N/A#endif
1280N/A
2086N/A/**
2086N/A * Special version of the AssertRC macro to be used within VirtualBoxBase
2086N/A * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
1280N/A *
1280N/A * See ComAssert for more info.
1280N/A *
1280N/A * @param vrc VBox status code.
2602N/A */
2602N/A#if defined (DEBUG)
2086N/A#define ComAssertRC(vrc) AssertRC(vrc)
1280N/A#else
1280N/A#define ComAssertRC(vrc) ComAssertMsgRC(vrc, ("%Rra", vrc))
1280N/A#endif
1280N/A
1280N/A/**
1280N/A * Special version of the AssertMsgRC macro to be used within VirtualBoxBase
1280N/A * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
1280N/A *
1280N/A * See ComAssert for more info.
2049N/A *
1280N/A * @param vrc VBox status code.
1280N/A * @param msg printf argument list (in parenthesis).
1280N/A */
1280N/A#if defined (DEBUG)
1280N/A#define ComAssertMsgRC(vrc, msg) AssertMsgRC(vrc, msg)
1280N/A#else
1280N/A#define ComAssertMsgRC(vrc, msg) ComAssertMsg(RT_SUCCESS(vrc), msg)
1280N/A#endif
2049N/A
1280N/A/**
1280N/A * Special version of the AssertComRC macro to be used within VirtualBoxBase
1280N/A * subclasses that also inherit the VirtualBoxSupportErrorInfoImpl template.
1280N/A *
1280N/A * See ComAssert for more info.
1280N/A *
1280N/A * @param rc COM result code
1280N/A */
1280N/A#if defined (DEBUG)
1280N/A#define ComAssertComRC(rc) AssertComRC(rc)
1280N/A#else
1280N/A#define ComAssertComRC(rc) ComAssertMsg(SUCCEEDED(rc), ("COM RC = %Rhrc (0x%08X)", (rc), (rc)))
1280N/A#endif
1280N/A
1280N/A
1280N/A/** Special version of ComAssert that returns ret if expr fails */
1280N/A#define ComAssertRet(expr, ret) \
1280N/A do { ComAssert(expr); if (!(expr)) return (ret); } while (0)
1280N/A/** Special version of ComAssertMsg that returns ret if expr fails */
1280N/A#define ComAssertMsgRet(expr, a, ret) \
1280N/A do { ComAssertMsg(expr, a); if (!(expr)) return (ret); } while (0)
1280N/A/** Special version of ComAssertRC that returns ret if vrc does not succeed */
1280N/A#define ComAssertRCRet(vrc, ret) \
1280N/A do { ComAssertRC(vrc); if (!RT_SUCCESS(vrc)) return (ret); } while (0)
1787N/A/** Special version of ComAssertMsgRC that returns ret if vrc does not succeed */
1787N/A#define ComAssertMsgRCRet(vrc, msg, ret) \
1787N/A do { ComAssertMsgRC(vrc, msg); if (!RT_SUCCESS(vrc)) return (ret); } while (0)
1787N/A/** Special version of ComAssertFailed that returns ret */
1787N/A#define ComAssertFailedRet(ret) \
1280N/A do { ComAssertFailed(); return (ret); } while (0)
2086N/A/** Special version of ComAssertMsgFailed that returns ret */
1280N/A#define ComAssertMsgFailedRet(msg, ret) \
1280N/A do { ComAssertMsgFailed(msg); return (ret); } while (0)
1280N/A/** Special version of ComAssertComRC that returns ret if rc does not succeed */
1280N/A#define ComAssertComRCRet(rc, ret) \
3023N/A do { ComAssertComRC(rc); if (!SUCCEEDED(rc)) return (ret); } while (0)
3023N/A/** Special version of ComAssertComRC that returns rc if rc does not succeed */
3023N/A#define ComAssertComRCRetRC(rc) \
1280N/A do { ComAssertComRC(rc); if (!SUCCEEDED(rc)) return (rc); } while (0)
3023N/A
3023N/A
3023N/A/** Special version of ComAssert that evaluates eval and breaks if expr fails */
3023N/A#define ComAssertBreak(expr, eval) \
1280N/A if (1) { ComAssert(expr); if (!(expr)) { eval; break; } } else do {} while (0)
1280N/A/** Special version of ComAssertMsg that evaluates eval and breaks if expr fails */
3023N/A#define ComAssertMsgBreak(expr, a, eval) \
1280N/A if (1) { ComAssertMsg(expr, a); if (!(expr)) { eval; break; } } else do {} while (0)
3023N/A/** Special version of ComAssertRC that evaluates eval and breaks if vrc does not succeed */
3023N/A#define ComAssertRCBreak(vrc, eval) \
1280N/A if (1) { ComAssertRC(vrc); if (!RT_SUCCESS(vrc)) { eval; break; } } else do {} while (0)
1280N/A/** Special version of ComAssertMsgRC that evaluates eval and breaks if vrc does not succeed */
1280N/A#define ComAssertMsgRCBreak(vrc, msg, eval) \
1280N/A if (1) { ComAssertMsgRC(vrc, msg); if (!RT_SUCCESS(vrc)) { eval; break; } } else do {} while (0)
3023N/A/** Special version of ComAssertFailed that evaluates eval and breaks */
1280N/A#define ComAssertFailedBreak(eval) \
1280N/A if (1) { ComAssertFailed(); { eval; break; } } else do {} while (0)
1280N/A/** Special version of ComAssertMsgFailed that evaluates eval and breaks */
1280N/A#define ComAssertMsgFailedBreak(msg, eval) \
1280N/A if (1) { ComAssertMsgFailed (msg); { eval; break; } } else do {} while (0)
1280N/A/** Special version of ComAssertComRC that evaluates eval and breaks if rc does not succeed */
1280N/A#define ComAssertComRCBreak(rc, eval) \
1280N/A if (1) { ComAssertComRC(rc); if (!SUCCEEDED(rc)) { eval; break; } } else do {} while (0)
1280N/A/** Special version of ComAssertComRC that just breaks if rc does not succeed */
1280N/A#define ComAssertComRCBreakRC(rc) \
1280N/A if (1) { ComAssertComRC(rc); if (!SUCCEEDED(rc)) { break; } } else do {} while (0)
2086N/A
1280N/A
1280N/A/** Special version of ComAssert that evaluates eval and throws it if expr fails */
1280N/A#define ComAssertThrow(expr, eval) \
2049N/A if (1) { ComAssert(expr); if (!(expr)) { throw (eval); } } else do {} while (0)
1280N/A/** Special version of ComAssertMsg that evaluates eval and throws it if expr fails */
1280N/A#define ComAssertMsgThrow(expr, a, eval) \
1280N/A if (1) { ComAssertMsg(expr, a); if (!(expr)) { throw (eval); } } else do {} while (0)
1280N/A/** Special version of ComAssertRC that evaluates eval and throws it if vrc does not succeed */
1280N/A#define ComAssertRCThrow(vrc, eval) \
1280N/A if (1) { ComAssertRC(vrc); if (!RT_SUCCESS(vrc)) { throw (eval); } } else do {} while (0)
1280N/A/** Special version of ComAssertMsgRC that evaluates eval and throws it if vrc does not succeed */
1280N/A#define ComAssertMsgRCThrow(vrc, msg, eval) \
2049N/A if (1) { ComAssertMsgRC(vrc, msg); if (!RT_SUCCESS(vrc)) { throw (eval); } } else do {} while (0)
1280N/A/** Special version of ComAssertFailed that evaluates eval and throws it */
1280N/A#define ComAssertFailedThrow(eval) \
1280N/A if (1) { ComAssertFailed(); { throw (eval); } } else do {} while (0)
1280N/A/** Special version of ComAssertMsgFailed that evaluates eval and throws it */
1280N/A#define ComAssertMsgFailedThrow(msg, eval) \
1280N/A if (1) { ComAssertMsgFailed (msg); { throw (eval); } } else do {} while (0)
1280N/A/** Special version of ComAssertComRC that evaluates eval and throws it if rc does not succeed */
1280N/A#define ComAssertComRCThrow(rc, eval) \
1280N/A if (1) { ComAssertComRC(rc); if (!SUCCEEDED(rc)) { throw (eval); } } else do {} while (0)
1280N/A/** Special version of ComAssertComRC that just throws rc if rc does not succeed */
1280N/A#define ComAssertComRCThrowRC(rc) \
1280N/A if (1) { ComAssertComRC(rc); if (!SUCCEEDED(rc)) { throw rc; } } else do {} while (0)
1400N/A
1280N/A////////////////////////////////////////////////////////////////////////////////
1280N/A
1280N/A/**
1280N/A * Checks that the pointer argument is not NULL and returns E_INVALIDARG +
1280N/A * extended error info on failure.
1280N/A * @param arg Input pointer-type argument (strings, interface pointers...)
1280N/A */
2624N/A#define CheckComArgNotNull(arg) \
1280N/A do { \
1280N/A if (RT_UNLIKELY((arg) == NULL)) \
1280N/A return setError(E_INVALIDARG, tr("Argument %s is NULL"), #arg); \
1280N/A } while (0)
1280N/A
1280N/A/**
1280N/A * Checks that safe array argument is not NULL and returns E_INVALIDARG +
1280N/A * extended error info on failure.
1280N/A * @param arg Input safe array argument (strings, interface pointers...)
1280N/A */
1280N/A#define CheckComArgSafeArrayNotNull(arg) \
1280N/A do { \
1280N/A if (RT_UNLIKELY(ComSafeArrayInIsNull(arg))) \
1280N/A return setError(E_INVALIDARG, tr("Argument %s is NULL"), #arg); \
1280N/A } while (0)
1280N/A
1280N/A/**
1280N/A * Checks that the string argument is not a NULL or empty string and returns
1280N/A * E_INVALIDARG + extended error info on failure.
1280N/A * @param arg Input string argument (BSTR etc.).
1280N/A */
1280N/A#define CheckComArgStrNotEmptyOrNull(arg) \
1280N/A do { \
1280N/A if (RT_UNLIKELY((arg) == NULL || *(arg) == '\0')) \
1280N/A return setError(E_INVALIDARG, \
1280N/A tr("Argument %s is empty or NULL"), #arg); \
1280N/A } while (0)
1280N/A
1280N/A/**
1280N/A * Checks that the given expression (that must involve the argument) is true and
2624N/A * returns E_INVALIDARG + extended error info on failure.
1280N/A * @param arg Argument.
2624N/A * @param expr Expression to evaluate.
1280N/A */
1280N/A#define CheckComArgExpr(arg, expr) \
2624N/A do { \
2624N/A if (RT_UNLIKELY(!(expr))) \
2624N/A return setError(E_INVALIDARG, \
2624N/A tr("Argument %s is invalid (must be %s)"), #arg, #expr); \
1280N/A } while (0)
1280N/A
1280N/A/**
1280N/A * Checks that the given expression (that must involve the argument) is true and
1280N/A * returns E_INVALIDARG + extended error info on failure. The error message must
1280N/A * be customized.
1280N/A * @param arg Argument.
1280N/A * @param expr Expression to evaluate.
1280N/A * @param msg Parenthesized printf-like expression (must start with a verb,
1280N/A * like "must be one of...", "is not within...").
1280N/A */
1280N/A#define CheckComArgExprMsg(arg, expr, msg) \
1280N/A do { \
1280N/A if (RT_UNLIKELY(!(expr))) \
1280N/A return setError(E_INVALIDARG, tr ("Argument %s %s"), \
1280N/A #arg, Utf8StrFmt msg .raw()); \
1280N/A } while (0)
1280N/A
1280N/A/**
1280N/A * Checks that the given pointer to an output argument is valid and returns
1280N/A * E_POINTER + extended error info otherwise.
1280N/A * @param arg Pointer argument.
1280N/A */
1280N/A#define CheckComArgOutPointerValid(arg) \
1280N/A do { \
1280N/A if (RT_UNLIKELY(!VALID_PTR(arg))) \
1280N/A return setError(E_POINTER, \
1280N/A tr("Output argument %s points to invalid memory location (%p)"), \
1280N/A #arg, (void *) (arg)); \
1280N/A } while (0)
1280N/A
1280N/A/**
2086N/A * Checks that the given pointer to an output safe array argument is valid and
2086N/A * returns E_POINTER + extended error info otherwise.
2086N/A * @param arg Safe array argument.
1280N/A */
1280N/A#define CheckComArgOutSafeArrayPointerValid(arg) \
1280N/A do { \
1280N/A if (RT_UNLIKELY(ComSafeArrayOutIsNull(arg))) \
1280N/A return setError(E_POINTER, \
1280N/A tr("Output argument %s points to invalid memory location (%p)"), \
1280N/A #arg, (void *) (arg)); \
1280N/A } while (0)
1280N/A
1280N/A/**
1280N/A * Sets the extended error info and returns E_NOTIMPL.
1280N/A */
2086N/A#define ReturnComNotImplemented() \
1280N/A do { \
1280N/A return setError(E_NOTIMPL, tr("Method %s is not implemented"), __FUNCTION__); \
1280N/A } while (0)
1280N/A
1280N/A/**
1280N/A * Declares an empty constructor and destructor for the given class.
1280N/A * This is useful to prevent the compiler from generating the default
1280N/A * ctor and dtor, which in turn allows to use forward class statements
2086N/A * (instead of including their header files) when declaring data members of
1280N/A * non-fundamental types with constructors (which are always called implicitly
1280N/A * by constructors and by the destructor of the class).
1280N/A *
1280N/A * This macro is to be placed within (the public section of) the class
1280N/A * declaration. Its counterpart, DEFINE_EMPTY_CTOR_DTOR, must be placed
1280N/A * somewhere in one of the translation units (usually .cpp source files).
1280N/A *
1280N/A * @param cls class to declare a ctor and dtor for
1280N/A */
1280N/A#define DECLARE_EMPTY_CTOR_DTOR(cls) cls(); ~cls();
1280N/A
1280N/A/**
1280N/A * Defines an empty constructor and destructor for the given class.
2086N/A * See DECLARE_EMPTY_CTOR_DTOR for more info.
1280N/A */
1280N/A#define DEFINE_EMPTY_CTOR_DTOR(cls) \
1280N/A cls::cls () {}; cls::~cls () {};
1400N/A
1280N/A////////////////////////////////////////////////////////////////////////////////
1280N/A//
1280N/A// VirtualBoxBase
1280N/A//
1280N/A////////////////////////////////////////////////////////////////////////////////
1280N/A
1280N/A/**
1280N/A * This enum is used in the virtual method VirtualBoxBasePro::getClassID() to
1280N/A * allow VirtualBox classes to identify themselves. Subclasses can override
1280N/A * that method and return a value from this enum if run-time identification is
1280N/A * needed anywhere.
1280N/A */
2086N/Aenum VBoxClsID
1280N/A{
1280N/A clsidVirtualBox,
1280N/A clsidHost,
1400N/A clsidMachine,
1280N/A clsidSessionMachine,
1280N/A clsidSnapshotMachine,
1280N/A clsidSnapshot,
1280N/A clsidOther
1280N/A};
1280N/A
1280N/A/**
1280N/A * Abstract base class for all component classes implementing COM
1280N/A * interfaces of the VirtualBox COM library.
1280N/A *
1280N/A * Declares functionality that should be available in all components.
1400N/A *
1400N/A * Note that this class is always subclassed using the virtual keyword so
1280N/A * that only one instance of its VTBL and data is present in each derived class
1280N/A * even in case if VirtualBoxBaseProto appears more than once among base classes
1400N/A * of the particular component as a result of multiple inheritance.
1280N/A *
1400N/A * This makes it possible to have intermediate base classes used by several
1280N/A * components that implement some common interface functionality but still let
1280N/A * the final component classes choose what VirtualBoxBase variant it wants to
1280N/A * use.
1400N/A *
1400N/A * Among the basic functionality implemented by this class is the primary object
1400N/A * state that indicates if the object is ready to serve the calls, and if not,
1400N/A * what stage it is currently at. Here is the primary state diagram:
1400N/A *
1400N/A * +-------------------------------------------------------+
1400N/A * | |
1400N/A * | (InitFailed) -----------------------+ |
1280N/A * | ^ | |
1280N/A * v | v |
1280N/A * [*] ---> NotReady ----> (InInit) -----> Ready -----> (InUninit) ----+
1280N/A * ^ | ^ | ^
1280N/A * | v | v |
1400N/A * | Limited | (MayUninit) --> (WillUninit)
1400N/A * | | | |
1400N/A * +-------+ +-------+
1400N/A *
1400N/A * The object is fully operational only when its state is Ready. The Limited
1400N/A * state means that only some vital part of the object is operational, and it
1400N/A * requires some sort of reinitialization to become fully operational. The
1280N/A * NotReady state means the object is basically dead: it either was not yet
1280N/A * initialized after creation at all, or was uninitialized and is waiting to be
1280N/A * destroyed when the last reference to it is released. All other states are
1400N/A * transitional.
1280N/A *
1280N/A * The NotReady->InInit->Ready, NotReady->InInit->Limited and
1280N/A * NotReady->InInit->InitFailed transition is done by the AutoInitSpan smart
1400N/A * class.
1280N/A *
1400N/A * The Limited->InInit->Ready, Limited->InInit->Limited and
1400N/A * Limited->InInit->InitFailed transition is done by the AutoReinitSpan smart
1400N/A * class.
1400N/A *
1280N/A * The Ready->InUninit->NotReady, InitFailed->InUninit->NotReady and
1280N/A * WillUninit->InUninit->NotReady transitions are done by the AutoUninitSpan
1280N/A * smart class.
1280N/A *
1280N/A * The Ready->MayUninit->Ready and Ready->MayUninit->WillUninit transitions are
1280N/A * done by the AutoMayUninitSpan smart class.
1280N/A *
1280N/A * In order to maintain the primary state integrity and declared functionality
1280N/A * all subclasses must:
1280N/A *
1280N/A * 1) Use the above Auto*Span classes to perform state transitions. See the
1400N/A * individual class descriptions for details.
1400N/A *
1280N/A * 2) All public methods of subclasses (i.e. all methods that can be called
1280N/A * directly, not only from within other methods of the subclass) must have a
1280N/A * standard prolog as described in the AutoCaller and AutoLimitedCaller
1400N/A * documentation. Alternatively, they must use addCaller()/releaseCaller()
1280N/A * directly (and therefore have both the prolog and the epilog), but this is
1280N/A * not recommended.
1280N/A */
1400N/Aclass ATL_NO_VTABLE VirtualBoxBase
1280N/A : public Lockable,
1400N/A public CComObjectRootEx<CComMultiThreadModel>
1400N/A{
1400N/Apublic:
1400N/A enum State { NotReady, Ready, InInit, InUninit, InitFailed, Limited,
1280N/A MayUninit, WillUninit };
1280N/A
1280N/A VirtualBoxBase();
1280N/A virtual ~VirtualBoxBase();
1280N/A
1280N/A static const char *translate(const char *context, const char *sourceText,
1280N/A const char *comment = 0);
1280N/A
1280N/Apublic:
1280N/A
1280N/A /**
1400N/A * Unintialization method.
1400N/A *
1280N/A * Must be called by all final implementations (component classes) when the
1280N/A * last reference to the object is released, before calling the destructor.
1280N/A *
1400N/A * This method is also automatically called by the uninit() method of this
1280N/A * object's parent if this object is a dependent child of a class derived
1280N/A * from VirtualBoxBaseWithChildren (see
1280N/A * VirtualBoxBaseWithChildren::addDependentChild).
1280N/A *
1400N/A * @note Never call this method the AutoCaller scope or after the
1400N/A * #addCaller() call not paired by #releaseCaller() because it is a
1400N/A * guaranteed deadlock. See AutoUninitSpan for details.
1400N/A */
1400N/A virtual void uninit() {}
1400N/A
1400N/A virtual HRESULT addCaller(State *aState = NULL, bool aLimited = false);
1400N/A virtual void releaseCaller();
1280N/A
1280N/A /**
1280N/A * Adds a limited caller. This method is equivalent to doing
1280N/A * <tt>addCaller (aState, true)</tt>, but it is preferred because provides
1280N/A * better self-descriptiveness. See #addCaller() for more info.
1280N/A */
1280N/A HRESULT addLimitedCaller(State *aState = NULL)
1280N/A {
1280N/A return addCaller(aState, true /* aLimited */);
1400N/A }
1400N/A
1280N/A /**
1280N/A * Simple run-time type identification without having to enable C++ RTTI.
1280N/A * The class IDs are defined in VirtualBoxBase.h.
1280N/A * @return
1280N/A */
1280N/A virtual VBoxClsID getClassID() const
1400N/A {
1400N/A return clsidOther;
1400N/A }
1400N/A
1400N/A /**
1400N/A * Override of the default locking class to be used for validating lock
1280N/A * order with the standard member lock handle.
1280N/A */
1280N/A virtual VBoxLockingClass getLockingClass() const
1280N/A {
1280N/A return LOCKCLASS_OTHEROBJECT;
1280N/A }
1280N/A
1280N/A virtual RWLockHandle *lockHandle() const;
1280N/A
1280N/A /**
1280N/A * Returns a lock handle used to protect the primary state fields (used by
1400N/A * #addCaller(), AutoInitSpan, AutoUninitSpan, etc.). Only intended to be
1400N/A * used for similar purposes in subclasses. WARNING: NO any other locks may
1280N/A * be requested while holding this lock!
1280N/A */
1400N/A WriteLockHandle *stateLockHandle() { return &mStateLock; }
1400N/A
1400N/Aprivate:
1400N/A
1400N/A void setState(State aState)
1400N/A {
1400N/A Assert(mState != aState);
1400N/A mState = aState;
1280N/A mStateChangeThread = RTThreadSelf();
1280N/A }
1280N/A
1280N/A /** Primary state of this object */
1280N/A State mState;
1280N/A /** Thread that caused the last state change */
1280N/A RTTHREAD mStateChangeThread;
1280N/A /** Total number of active calls to this object */
1400N/A unsigned mCallers;
1400N/A /** Posted when the number of callers drops to zero */
1400N/A RTSEMEVENT mZeroCallersSem;
1280N/A /** Posted when the object goes from InInit/InUninit to some other state */
1280N/A RTSEMEVENTMULTI mInitUninitSem;
1280N/A /** Number of threads waiting for mInitUninitDoneSem */
1280N/A unsigned mInitUninitWaiters;
1280N/A
1400N/A /** Protects access to state related data members */
1400N/A WriteLockHandle mStateLock;
1400N/A
1400N/A /** User-level object lock for subclasses */
1400N/A mutable RWLockHandle *mObjectLock;
1400N/A
1400N/A friend class AutoInitSpan;
1400N/A friend class AutoReinitSpan;
1280N/A friend class AutoUninitSpan;
1280N/A friend class AutoMayUninitSpan;
1280N/A};
1280N/A
1280N/A////////////////////////////////////////////////////////////////////////////////
1280N/A//
1280N/A// VirtualBoxSupportTranslation, VirtualBoxSupportErrorInfoImpl
1280N/A//
1280N/A////////////////////////////////////////////////////////////////////////////////
1280N/A
1280N/A/**
1400N/A * This macro adds the error info support to methods of the VirtualBoxBase
1400N/A * class (by overriding them). Place it to the public section of the
1280N/A * VirtualBoxBase subclass and the following methods will set the extended
1280N/A * error info in case of failure instead of just returning the result code:
1280N/A *
1280N/A * <ul>
1280N/A * <li>VirtualBoxBase::addCaller()
1280N/A * </ul>
1280N/A *
1280N/A * @note The given VirtualBoxBase subclass must also inherit from both
1280N/A * VirtualBoxSupportErrorInfoImpl and VirtualBoxSupportTranslation templates!
1280N/A *
1280N/A * @param C VirtualBoxBase subclass to add the error info support to
1280N/A */
1280N/A#define VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT(C) \
1280N/A virtual HRESULT addCaller(VirtualBoxBase::State *aState = NULL, \
1280N/A bool aLimited = false) \
1280N/A { \
1280N/A VirtualBoxBase::State protoState; \
1280N/A HRESULT rc = VirtualBoxBase::addCaller(&protoState, aLimited); \
1280N/A if (FAILED(rc)) \
1280N/A { \
1280N/A if (protoState == VirtualBoxBase::Limited) \
1280N/A rc = setError(rc, tr("The object functionality is limited")); \
1280N/A else \
1280N/A rc = setError(rc, tr("The object is not ready")); \
1280N/A } \
1280N/A if (aState) \
1280N/A *aState = protoState; \
1280N/A return rc; \
1280N/A } \
1280N/A
1280N/A////////////////////////////////////////////////////////////////////////////////
1280N/A
1280N/A/** Helper for VirtualBoxSupportTranslation. */
1280N/Aclass VirtualBoxSupportTranslationBase
1280N/A{
1280N/Aprotected:
1280N/A static bool cutClassNameFrom__PRETTY_FUNCTION__(char *aPrettyFunctionName);
1280N/A};
1280N/A
1280N/A/**
1280N/A * The VirtualBoxSupportTranslation template implements the NLS string
1280N/A * translation support for the given class.
1280N/A *
1280N/A * Translation support is provided by the static #tr() function. This function,
1280N/A * given a string in UTF-8 encoding, looks up for a translation of the given
1280N/A * string by calling the VirtualBoxBase::translate() global function which
1280N/A * receives the name of the enclosing class ("context of translation") as the
1280N/A * additional argument and returns a translated string based on the currently
1280N/A * active language.
1280N/A *
1280N/A * @param C Class that needs to support the string translation.
1280N/A *
1280N/A * @note Every class that wants to use the #tr() function in its own methods
1280N/A * must inherit from this template, regardless of whether its base class
1280N/A * (if any) inherits from it or not. Otherwise, the translation service
1400N/A * will not work correctly. However, the declaration of the derived
1400N/A * class must contain
1400N/A * the <tt>COM_SUPPORTTRANSLATION_OVERRIDE (<ClassName>)</tt> macro if one
1400N/A * of its base classes also inherits from this template (to resolve the
1400N/A * ambiguity of the #tr() function).
1400N/A */
1400N/Atemplate<class C>
1400N/Aclass VirtualBoxSupportTranslation : virtual protected VirtualBoxSupportTranslationBase
1280N/A{
1280N/Apublic:
1280N/A
1280N/A /**
1280N/A * Translates the given text string by calling VirtualBoxBase::translate()
1280N/A * and passing the name of the C class as the first argument ("context of
1280N/A * translation") See VirtualBoxBase::translate() for more info.
1280N/A *
1280N/A * @param aSourceText String to translate.
1400N/A * @param aComment Comment to the string to resolve possible
1400N/A * ambiguities (NULL means no comment).
1280N/A *
1280N/A * @return Translated version of the source string in UTF-8 encoding, or
1280N/A * the source string itself if the translation is not found in the
1280N/A * specified context.
1280N/A */
1280N/A inline static const char *tr(const char *aSourceText,
1280N/A const char *aComment = NULL)
1280N/A {
1280N/A return VirtualBoxBase::translate(className(), aSourceText, aComment);
1280N/A }
1280N/A
1280N/Aprotected:
1400N/A
1400N/A static const char *className()
1400N/A {
1400N/A static char fn[sizeof(__PRETTY_FUNCTION__) + 1];
1400N/A if (!sClassName)
1400N/A {
1400N/A strcpy(fn, __PRETTY_FUNCTION__);
1400N/A cutClassNameFrom__PRETTY_FUNCTION__(fn);
1280N/A sClassName = fn;
1280N/A }
1280N/A return sClassName;
1280N/A }
1280N/A
1280N/Aprivate:
1280N/A
1280N/A static const char *sClassName;
1280N/A};
1280N/A
4134N/Atemplate<class C>
1400N/Aconst char *VirtualBoxSupportTranslation<C>::sClassName = NULL;
1280N/A
1280N/A/**
1400N/A * This macro must be invoked inside the public section of the declaration of
1400N/A * the class inherited from the VirtualBoxSupportTranslation template in case
1400N/A * if one of its other base classes also inherits from that template. This is
4134N/A * necessary to resolve the ambiguity of the #tr() function.
1400N/A *
1400N/A * @param C Class that inherits the VirtualBoxSupportTranslation template
1400N/A * more than once (through its other base clases).
1280N/A */
1400N/A#define VIRTUALBOXSUPPORTTRANSLATION_OVERRIDE(C) \
1400N/A inline static const char *tr(const char *aSourceText, \
1280N/A const char *aComment = NULL) \
1400N/A { \
1400N/A return VirtualBoxSupportTranslation<C>::tr(aSourceText, aComment); \
1280N/A }
1280N/A
1280N/A/**
1280N/A * Dummy macro that is used to shut down Qt's lupdate tool warnings in some
1280N/A * situations. This macro needs to be present inside (better at the very
1280N/A * beginning) of the declaration of the class that inherits from
1280N/A * VirtualBoxSupportTranslation template, to make lupdate happy.
1280N/A */
1280N/A#define Q_OBJECT
1280N/A
1280N/A////////////////////////////////////////////////////////////////////////////////
1280N/A
1280N/A/**
1280N/A * Helper for the VirtualBoxSupportErrorInfoImpl template.
1280N/A */
1280N/A/// @todo switch to com::SupportErrorInfo* and remove
1280N/Aclass VirtualBoxSupportErrorInfoImplBase
1280N/A{
1280N/A static HRESULT setErrorInternal(HRESULT aResultCode,
1280N/A const GUID &aIID,
1280N/A const wchar_t *aComponent,
1280N/A const Bstr &aText,
1280N/A bool aWarning,
1280N/A bool aLogIt);
1280N/A
1280N/Aprotected:
1280N/A
1280N/A /**
1280N/A * The MultiResult class is a com::FWResult enhancement that also acts as a
1280N/A * switch to turn on multi-error mode for #setError() or #setWarning()
1280N/A * calls.
1280N/A *
1280N/A * When an instance of this class is created, multi-error mode is turned on
1280N/A * for the current thread and the turn-on counter is increased by one. In
1280N/A * multi-error mode, a call to #setError() or #setWarning() does not
1280N/A * overwrite the current error or warning info object possibly set on the
1280N/A * current thread by other method calls, but instead it stores this old
1280N/A * object in the IVirtualBoxErrorInfo::next attribute of the new error
1280N/A * object being set.
1280N/A *
1280N/A * This way, error/warning objects are stacked together and form a chain of
1280N/A * errors where the most recent error is the first one retrieved by the
1280N/A * calling party, the preceding error is what the
1280N/A * IVirtualBoxErrorInfo::next attribute of the first error points to, and so
1280N/A * on, up to the first error or warning occurred which is the last in the
1280N/A * chain. See IVirtualBoxErrorInfo documentation for more info.
1280N/A *
1280N/A * When the instance of the MultiResult class goes out of scope and gets
1280N/A * destroyed, it automatically decreases the turn-on counter by one. If
1280N/A * the counter drops to zero, multi-error mode for the current thread is
1280N/A * turned off and the thread switches back to single-error mode where every
1280N/A * next error or warning object overwrites the previous one.
2624N/A *
2624N/A * Note that the caller of a COM method uses a non-S_OK result code to
1280N/A * decide if the method has returned an error (negative codes) or a warning
1280N/A * (positive non-zero codes) and will query extended error info only in
1280N/A * these two cases. However, since multi-error mode implies that the method
1280N/A * doesn't return control return to the caller immediately after the first
1280N/A * error or warning but continues its execution, the functionality provided
1280N/A * by the base com::FWResult class becomes very useful because it allows to
1280N/A * preserve the error or the warning result code even if it is later assigned
1280N/A * a S_OK value multiple times. See com::FWResult for details.
1280N/A *
1280N/A * Here is the typical usage pattern:
1280N/A * <code>
1280N/A
3017N/A HRESULT Bar::method()
1280N/A {
3017N/A // assume multi-errors are turned off here...
1280N/A
1280N/A if (something)
1280N/A {
1280N/A // Turn on multi-error mode and make sure severity is preserved
1280N/A MultiResult rc = foo->method1();
1280N/A
1280N/A // return on fatal error, but continue on warning or on success
1280N/A if (FAILED(rc)) return rc;
1280N/A
1280N/A rc = foo->method2();
1280N/A // no matter what result, stack it and continue
1280N/A
1280N/A // ...
1280N/A
1280N/A // return the last worst result code (it will be preserved even if
1280N/A // foo->method2() returns S_OK.
2446N/A return rc;
1280N/A }
1280N/A
1280N/A // multi-errors are turned off here again...
1280N/A
1280N/A return S_OK;
1280N/A }
1280N/A
1280N/A * </code>
1280N/A *
1280N/A *
1514N/A * @note This class is intended to be instantiated on the stack, therefore
1514N/A * You cannot create them using new(). Although it is possible to copy
1514N/A * instances of MultiResult or return them by value, please never do
1514N/A * that as it is breaks the class semantics (and will assert).
1514N/A */
1514N/A class MultiResult : public com::FWResult
1514N/A {
1514N/A public:
1514N/A
1514N/A /**
1514N/A * @copydoc com::FWResult::FWResult().
1514N/A */
1514N/A MultiResult(HRESULT aRC = E_FAIL) : FWResult(aRC) { init(); }
1514N/A
1514N/A MultiResult(const MultiResult &aThat) : FWResult(aThat)
1280N/A {
/* We need this copy constructor only for GCC that wants to have
* it in case of expressions like |MultiResult rc = E_FAIL;|. But
* we assert since the optimizer should actually avoid the
* temporary and call the other constructor directly instead. */
AssertFailed();
init();
}
~MultiResult();
MultiResult &operator=(HRESULT aRC)
{
com::FWResult::operator=(aRC);
return *this;
}
MultiResult &operator=(const MultiResult &aThat)
{
/* We need this copy constructor only for GCC that wants to have
* it in case of expressions like |MultiResult rc = E_FAIL;|. But
* we assert since the optimizer should actually avoid the
* temporary and call the other constructor directly instead. */
AssertFailed();
com::FWResult::operator=(aThat);
return *this;
}
private:
DECLARE_CLS_NEW_DELETE_NOOP(MultiResult)
void init();
static RTTLS sCounter;
friend class VirtualBoxSupportErrorInfoImplBase;
};
static HRESULT setError(HRESULT aResultCode,
const GUID &aIID,
const wchar_t *aComponent,
const Bstr &aText,
bool aLogIt = true)
{
return setErrorInternal(aResultCode, aIID, aComponent, aText,
false /* aWarning */, aLogIt);
}
static HRESULT setWarning(HRESULT aResultCode,
const GUID &aIID,
const wchar_t *aComponent,
const Bstr &aText)
{
return setErrorInternal(aResultCode, aIID, aComponent, aText,
true /* aWarning */, true /* aLogIt */);
}
static HRESULT setError(HRESULT aResultCode,
const GUID &aIID,
const wchar_t *aComponent,
const char *aText, va_list aArgs, bool aLogIt = true)
{
return setErrorInternal(aResultCode, aIID, aComponent,
Utf8StrFmtVA (aText, aArgs),
false /* aWarning */, aLogIt);
}
static HRESULT setWarning(HRESULT aResultCode,
const GUID &aIID,
const wchar_t *aComponent,
const char *aText, va_list aArgs)
{
return setErrorInternal(aResultCode, aIID, aComponent,
Utf8StrFmtVA (aText, aArgs),
true /* aWarning */, true /* aLogIt */);
}
};
/**
* This template implements ISupportErrorInfo for the given component class
* and provides the #setError() method to conveniently set the error information
* from within interface methods' implementations.
*
* On Windows, the template argument must define a COM interface map using
* BEGIN_COM_MAP / END_COM_MAP macros and this map must contain a
* COM_INTERFACE_ENTRY(ISupportErrorInfo) definition. All interface entries
* that follow it will be considered to support IErrorInfo, i.e. the
* InterfaceSupportsErrorInfo() implementation will return S_OK for the
* corresponding IID.
*
* On all platforms, the template argument must also define the following
* method: |public static const wchar_t *C::getComponentName()|. See
* #setError(HRESULT, const char *, ...) for a description on how it is
* used.
*
* @param C
* component class that implements one or more COM interfaces
* @param I
* default interface for the component. This interface's IID is used
* by the shortest form of #setError, for convenience.
*/
/// @todo switch to com::SupportErrorInfo* and remove
template<class C, class I>
class ATL_NO_VTABLE VirtualBoxSupportErrorInfoImpl
: protected VirtualBoxSupportErrorInfoImplBase
#if !defined (VBOX_WITH_XPCOM)
, public ISupportErrorInfo
#else
#endif
{
public:
#if !defined (VBOX_WITH_XPCOM)
STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid)
{
const _ATL_INTMAP_ENTRY* pEntries = C::_GetEntries();
Assert(pEntries);
if (!pEntries)
return S_FALSE;
BOOL bSupports = FALSE;
BOOL bISupportErrorInfoFound = FALSE;
while (pEntries->pFunc != NULL && !bSupports)
{
if (!bISupportErrorInfoFound)
{
// skip the com map entries until ISupportErrorInfo is found
bISupportErrorInfoFound =
InlineIsEqualGUID(*(pEntries->piid), IID_ISupportErrorInfo);
}
else
{
// look for the requested interface in the rest of the com map
bSupports = InlineIsEqualGUID(*(pEntries->piid), riid);
}
pEntries++;
}
Assert(bISupportErrorInfoFound);
return bSupports ? S_OK : S_FALSE;
}
#endif // !defined (VBOX_WITH_XPCOM)
protected:
/**
* Sets the error information for the current thread.
* This information can be retrieved by a caller of an interface method
* using IErrorInfo on Windows or nsIException on Linux, or the cross-platform
* IVirtualBoxErrorInfo interface that provides extended error info (only
* for components from the VirtualBox COM library). Alternatively, the
* platform-independent class com::ErrorInfo (defined in VBox[XP]COM.lib)
* can be used to retrieve error info in a convenient way.
*
* It is assumed that the interface method that uses this function returns
* an unsuccessful result code to the caller (otherwise, there is no reason
* for the caller to try to retrieve error info after method invocation).
*
* Here is a table of correspondence between this method's arguments
* and IErrorInfo/nsIException/IVirtualBoxErrorInfo attributes/methods:
*
* argument IErrorInfo nsIException IVirtualBoxErrorInfo
* ----------------------------------------------------------------
* resultCode -- result resultCode
* iid GetGUID -- interfaceID
* component GetSource -- component
* text GetDescription message text
*
* This method is rarely needs to be used though. There are more convenient
* overloaded versions, that automatically substitute some arguments
* taking their values from the template parameters. See
* #setError(HRESULT, const char *, ...) for an example.
*
* @param aResultCode result (error) code, must not be S_OK
* @param aIID IID of the interface that defines the error
* @param aComponent name of the component that generates the error
* @param aText error message (must not be null), an RTStrPrintf-like
* format string in UTF-8 encoding
* @param ... list of arguments for the format string
*
* @return
* the error argument, for convenience, If an error occurs while
* creating error info itself, that error is returned instead of the
* error argument.
*/
static HRESULT setError(HRESULT aResultCode, const GUID &aIID,
const wchar_t *aComponent,
const char *aText, ...)
{
va_list args;
va_start(args, aText);
HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError(aResultCode,
aIID,
aComponent,
aText,
args,
true /* aLogIt */);
va_end(args);
return rc;
}
/**
* This method is the same as #setError() except that it makes sure @a
* aResultCode doesn't have the error severity bit (31) set when passed
* down to the created IVirtualBoxErrorInfo object.
*
* The error severity bit is always cleared by this call, thereof you can
* use ordinary E_XXX result code constants, for convenience. However, this
* behavior may be non-standard on some COM platforms.
*/
static HRESULT setWarning(HRESULT aResultCode, const GUID &aIID,
const wchar_t *aComponent,
const char *aText, ...)
{
va_list args;
va_start(args, aText);
HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setWarning(
aResultCode, aIID, aComponent, aText, args);
va_end(args);
return rc;
}
/**
* Sets the error information for the current thread.
* A convenience method that automatically sets the default interface
* ID (taken from the I template argument) and the component name
* (a value of C::getComponentName()).
*
* See #setError(HRESULT, const GUID &, const wchar_t *, const char *text, ...)
* for details.
*
* This method is the most common (and convenient) way to set error
* information from within interface methods. A typical pattern of usage
* is looks like this:
*
* <code>
* return setError(E_FAIL, "Terrible Error");
* </code>
* or
* <code>
* HRESULT rc = setError(E_FAIL, "Terrible Error");
* ...
* return rc;
* </code>
*/
static HRESULT setError(HRESULT aResultCode, const char *aText, ...)
{
va_list args;
va_start(args, aText);
HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError(aResultCode,
COM_IIDOF(I),
C::getComponentName(),
aText,
args,
true /* aLogIt */);
va_end(args);
return rc;
}
/**
* This method is the same as #setError() except that it makes sure @a
* aResultCode doesn't have the error severity bit (31) set when passed
* down to the created IVirtualBoxErrorInfo object.
*
* The error severity bit is always cleared by this call, thereof you can
* use ordinary E_XXX result code constants, for convenience. However, this
* behavior may be non-standard on some COM platforms.
*/
static HRESULT setWarning(HRESULT aResultCode, const char *aText, ...)
{
va_list args;
va_start(args, aText);
HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setWarning(aResultCode,
COM_IIDOF(I),
C::getComponentName(),
aText,
args);
va_end(args);
return rc;
}
/**
* Sets the error information for the current thread, va_list variant.
* A convenience method that automatically sets the default interface
* ID (taken from the I template argument) and the component name
* (a value of C::getComponentName()).
*
* See #setError(HRESULT, const GUID &, const wchar_t *, const char *text, ...)
* and #setError(HRESULT, const char *, ...) for details.
*/
static HRESULT setErrorV(HRESULT aResultCode, const char *aText,
va_list aArgs)
{
HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError(aResultCode,
COM_IIDOF(I),
C::getComponentName(),
aText,
aArgs,
true /* aLogIt */);
return rc;
}
/**
* This method is the same as #setErrorV() except that it makes sure @a
* aResultCode doesn't have the error severity bit (31) set when passed
* down to the created IVirtualBoxErrorInfo object.
*
* The error severity bit is always cleared by this call, thereof you can
* use ordinary E_XXX result code constants, for convenience. However, this
* behavior may be non-standard on some COM platforms.
*/
static HRESULT setWarningV(HRESULT aResultCode, const char *aText,
va_list aArgs)
{
HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setWarning(aResultCode,
COM_IIDOF(I),
C::getComponentName(),
aText,
aArgs);
return rc;
}
/**
* Sets the error information for the current thread.
* A convenience method that automatically sets the component name
* (a value of C::getComponentName()), but allows to specify the interface
* id manually.
*
* See #setError(HRESULT, const GUID &, const wchar_t *, const char *text, ...)
* for details.
*/
static HRESULT setError(HRESULT aResultCode, const GUID &aIID,
const char *aText, ...)
{
va_list args;
va_start(args, aText);
HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError(aResultCode,
aIID,
C::getComponentName(),
aText,
args,
true /* aLogIt */);
va_end(args);
return rc;
}
/**
* This method is the same as #setError() except that it makes sure @a
* aResultCode doesn't have the error severity bit (31) set when passed
* down to the created IVirtualBoxErrorInfo object.
*
* The error severity bit is always cleared by this call, thereof you can
* use ordinary E_XXX result code constants, for convenience. However, this
* behavior may be non-standard on some COM platforms.
*/
static HRESULT setWarning(HRESULT aResultCode, const GUID &aIID,
const char *aText, ...)
{
va_list args;
va_start(args, aText);
HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setWarning(aResultCode,
aIID,
C::getComponentName(),
aText,
args);
va_end(args);
return rc;
}
/**
* Sets the error information for the current thread but doesn't put
* anything in the release log. This is very useful for avoiding
* harmless error from causing confusion.
*
* It is otherwise identical to #setError(HRESULT, const char *text, ...).
*/
static HRESULT setErrorNoLog(HRESULT aResultCode, const char *aText, ...)
{
va_list args;
va_start(args, aText);
HRESULT rc = VirtualBoxSupportErrorInfoImplBase::setError(aResultCode,
COM_IIDOF(I),
C::getComponentName(),
aText,
args,
false /* aLogIt */);
va_end(args);
return rc;
}
private:
};
/**
* Base class to track VirtualBoxBaseNEXT chlidren of the component.
*
* This class is a preferrable VirtualBoxBase replacement for components that
* operate with collections of child components. It gives two useful
* possibilities:
*
* <ol><li>
* Given an IUnknown instance, it's possible to quickly determine
* whether this instance represents a child object that belongs to the
* given component, and if so, get a valid VirtualBoxBase pointer to the
* child object. The returned pointer can be then safely casted to the
* actual class of the child object (to get access to its "internal"
* non-interface methods) provided that no other child components implement
* the same original COM interface IUnknown is queried from.
* </li><li>
* When the parent object uninitializes itself, it can easily unintialize
* all its VirtualBoxBase derived children (using their
* VirtualBoxBase::uninit() implementations). This is done simply by
* calling the #uninitDependentChildren() method.
* </li></ol>
*
* In order to let the above work, the following must be done:
* <ol><li>
* When a child object is initialized, it calls #addDependentChild() of
* its parent to register itself within the list of dependent children.
* </li><li>
* When the child object it is uninitialized, it calls
* #removeDependentChild() to unregister itself.
* </li></ol>
*
* Note that if the parent object does not call #uninitDependentChildren() when
* it gets uninitialized, it must call uninit() methods of individual children
* manually to disconnect them; a failure to do so will cause crashes in these
* methods when children get destroyed. The same applies to children not calling
* #removeDependentChild() when getting destroyed.
*
* Note that children added by #addDependentChild() are <b>weakly</b> referenced
* (i.e. AddRef() is not called), so when a child object is deleted externally
* (because it's reference count goes to zero), it will automatically remove
* itself from the map of dependent children provided that it follows the rules
* described here.
*
* Access to the child list is serialized using the #childrenLock() lock handle
* (which defaults to the general object lock handle (see
* VirtualBoxBase::lockHandle()). This lock is used by all add/remove methods of
* this class so be aware of the need to preserve the {parent, child} lock order
* when calling these methods.
*
* Read individual method descriptions to get further information.
*
* @todo This is a VirtualBoxBaseWithChildren equivalent that uses the
* VirtualBoxBaseNEXT implementation. Will completely supersede
* VirtualBoxBaseWithChildren after the old VirtualBoxBase implementation
* has gone.
*/
class VirtualBoxBaseWithChildrenNEXT : public VirtualBoxBase
{
public:
VirtualBoxBaseWithChildrenNEXT()
{}
virtual ~VirtualBoxBaseWithChildrenNEXT()
{}
/**
* Lock handle to use when adding/removing child objects from the list of
* children. It is guaranteed that no any other lock is requested in methods
* of this class while holding this lock.
*
* @warning By default, this simply returns the general object's lock handle
* (see VirtualBoxBase::lockHandle()) which is sufficient for most
* cases.
*/
virtual RWLockHandle *childrenLock() { return lockHandle(); }
/**
* Adds the given child to the list of dependent children.
*
* Usually gets called from the child's init() method.
*
* @note @a aChild (unless it is in InInit state) must be protected by
* VirtualBoxBase::AutoCaller to make sure it is not uninitialized on
* another thread during this method's call.
*
* @note When #childrenLock() is not overloaded (returns the general object
* lock) and this method is called from under the child's read or
* write lock, make sure the {parent, child} locking order is
* preserved by locking the callee (this object) for writing before
* the child's lock.
*
* @param aChild Child object to add (must inherit VirtualBoxBase AND
* implement some interface).
*
* @note Locks #childrenLock() for writing.
*/
template<class C>
void addDependentChild(C *aChild)
{
AssertReturnVoid(aChild != NULL);
doAddDependentChild(ComPtr<IUnknown>(aChild), aChild);
}
/**
* Equivalent to template <class C> void addDependentChild (C *aChild)
* but takes a ComObjPtr<C> argument.
*/
template<class C>
void addDependentChild(const ComObjPtr<C> &aChild)
{
AssertReturnVoid(!aChild.isNull());
doAddDependentChild(ComPtr<IUnknown>(static_cast<C *>(aChild)), aChild);
}
/**
* Removes the given child from the list of dependent children.
*
* Usually gets called from the child's uninit() method.
*
* Keep in mind that the called (parent) object may be no longer available
* (i.e. may be deleted deleted) after this method returns, so you must not
* call any other parent's methods after that!
*
* @note Locks #childrenLock() for writing.
*
* @note @a aChild (unless it is in InUninit state) must be protected by
* VirtualBoxBase::AutoCaller to make sure it is not uninitialized on
* another thread during this method's call.
*
* @note When #childrenLock() is not overloaded (returns the general object
* lock) and this method is called from under the child's read or
* write lock, make sure the {parent, child} locking order is
* preserved by locking the callee (this object) for writing before
* the child's lock. This is irrelevant when the method is called from
* under this object's VirtualBoxBaseProto::AutoUninitSpan (i.e. in
* InUninit state) since in this case no locking is done.
*
* @param aChild Child object to remove.
*
* @note Locks #childrenLock() for writing.
*/
template<class C>
void removeDependentChild(C *aChild)
{
AssertReturnVoid(aChild != NULL);
doRemoveDependentChild(ComPtr<IUnknown>(aChild));
}
/**
* Equivalent to template <class C> void removeDependentChild (C *aChild)
* but takes a ComObjPtr<C> argument.
*/
template<class C>
void removeDependentChild(const ComObjPtr<C> &aChild)
{
AssertReturnVoid(!aChild.isNull());
doRemoveDependentChild(ComPtr<IUnknown>(static_cast<C *>(aChild)));
}
protected:
void uninitDependentChildren();
VirtualBoxBase *getDependentChild(const ComPtr<IUnknown> &aUnk);
private:
void doAddDependentChild(IUnknown *aUnk, VirtualBoxBase *aChild);
void doRemoveDependentChild(IUnknown *aUnk);
typedef std::map<IUnknown*, VirtualBoxBase*> DependentChildren;
DependentChildren mDependentChildren;
};
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @todo (dmik) remove after we switch to VirtualBoxBaseNEXT completely
/**
* 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).
*/
template <class D>
class Shareable
{
public:
Shareable() : mData (NULL), mIsShared(FALSE) {}
~Shareable() { free(); }
void allocate() { attach(new D); }
virtual void free() {
if (mData) {
if (!mIsShared)
delete mData;
mData = NULL;
mIsShared = false;
}
}
void attach(D *d) {
AssertMsg(d, ("new data must not be NULL"));
if (d && mData != d) {
if (mData && !mIsShared)
delete mData;
mData = d;
mIsShared = false;
}
}
void attach(Shareable &d) {
AssertMsg(
d.mData == mData || !d.mIsShared,
("new data must not be shared")
);
if (this != &d && !d.mIsShared) {
attach(d.mData);
d.mIsShared = true;
}
}
void share(D *d) {
AssertMsg(d, ("new data must not be NULL"));
if (mData != d) {
if (mData && !mIsShared)
delete mData;
mData = d;
mIsShared = true;
}
}
void share(const Shareable &d) { share(d.mData); }
void attachCopy(const D *d) {
AssertMsg(d, ("data to copy must not be NULL"));
if (d)
attach(new D(*d));
}
void attachCopy(const Shareable &d) {
attachCopy(d.mData);
}
virtual D *detach() {
D *d = mData;
mData = NULL;
mIsShared = false;
return d;
}
D *data() const {
return mData;
}
D *operator->() const {
AssertMsg(mData, ("data must not be NULL"));
return mData;
}
bool isNull() const { return mData == NULL; }
bool operator!() const { return isNull(); }
bool isShared() const { return mIsShared; }
protected:
D *mData;
bool mIsShared;
};
/// @todo (dmik) remove after we switch to VirtualBoxBaseNEXT completely
/**
* Simple template that enhances Shareable<> and supports data
* backup/rollback/commit (using the copy constructor of the managed data
* structure).
*/
template<class D>
class Backupable : public Shareable<D>
{
public:
Backupable() : Shareable<D> (), mBackupData(NULL) {}
void free()
{
AssertMsg(this->mData || !mBackupData, ("backup must be NULL if data is NULL"));
rollback();
Shareable<D>::free();
}
D *detach()
{
AssertMsg(this->mData || !mBackupData, ("backup must be NULL if data is NULL"));
rollback();
return Shareable<D>::detach();
}
void share(const Backupable &d)
{
AssertMsg(!d.isBackedUp(), ("data to share must not be backed up"));
if (!d.isBackedUp())
Shareable<D>::share(d.mData);
}
/**
* Stores the current data pointer in the backup area, allocates new data
* using the copy constructor on current data and makes new data active.
*/
void backup()
{
AssertMsg(this->mData, ("data must not be NULL"));
if (this->mData && !mBackupData)
{
D *pNewData = new D(*this->mData);
mBackupData = this->mData;
this->mData = pNewData;
}
}
/**
* Deletes new data created by #backup() and restores previous data pointer
* stored in the backup area, making it active again.
*/
void rollback()
{
if (this->mData && mBackupData)
{
delete this->mData;
this->mData = mBackupData;
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()
{
if (this->mData && mBackupData)
{
if (!this->mIsShared)
delete mBackupData;
mBackupData = NULL;
this->mIsShared = false;
}
}
/**
* 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()
{
if (this->mData && mBackupData)
{
*mBackupData = *(this->mData);
delete this->mData;
this->mData = mBackupData;
mBackupData = NULL;
}
}
void assignCopy(const D *pData)
{
AssertMsg(this->mData, ("data must not be NULL"));
AssertMsg(pData, ("data to copy must not be NULL"));
if (this->mData && pData)
{
if (!mBackupData)
{
D *pNewData = new D(*pData);
mBackupData = this->mData;
this->mData = pNewData;
}
else
*this->mData = *pData;
}
}
void assignCopy(const Backupable &d)
{
assignCopy(d.mData);
}
bool isBackedUp() const
{
return mBackupData != NULL;
}
D *backedUpData() const
{
return mBackupData;
}
protected:
D *mBackupData;
};
#endif // !____H_VIRTUALBOXBASEIMPL