VirtualBoxBase.cpp revision 7cec024c409b939108e8b7ef7085183f186accab
/* $Id$ */
/** @file
*
* VirtualBox COM base classes implementation
*/
/*
* Copyright (C) 2006-2007 Sun Microsystems, Inc.
*
* 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.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
* Clara, CA 95054 USA or visit http://www.sun.com if you need
* additional information or have any questions.
*/
#if !defined (VBOX_WITH_XPCOM)
#include <windows.h>
#include <dbghelp.h>
#else /* !defined (VBOX_WITH_XPCOM) */
#include <nsIServiceManager.h>
#include <nsIExceptionService.h>
#endif /* !defined (VBOX_WITH_XPCOM) */
#include "VirtualBoxBase.h"
#include "VirtualBoxErrorInfoImpl.h"
#include "Logging.h"
#include <iprt/semaphore.h>
// VirtualBoxBaseNEXT_base methods
////////////////////////////////////////////////////////////////////////////////
{
mCallers = 0;
mInitDoneSemUsers = 0;
mObjectLock = NULL;
}
{
if (mObjectLock)
delete mObjectLock;
Assert (mInitDoneSemUsers == 0);
if (mZeroCallersSem != NIL_RTSEMEVENT)
mCallers = 0;
}
// util::Lockable interface
{
/* lazy initialization */
if (RT_UNLIKELY(!mObjectLock))
{
AssertCompile (sizeof (RWLockHandle *) == sizeof (void *));
{
delete objLock;
}
return objLock;
}
return mObjectLock;
}
/**
* Increments the number of calls to this object by one.
*
* After this method succeeds, it is guaranted that the object will remain in
* the Ready (or in the Limited) state at least until #releaseCaller() is
* called.
*
* This method is intended to mark the beginning of sections of code within
* methods of COM objects that depend on the readiness (Ready) state. The
* Ready state is a primary "ready to serve" state. Usually all code that
* works with component's data depends on it. On practice, this means that
* almost every public method, setter or getter of the object should add
* itself as an object's caller at the very beginning, to protect from an
* unexpected uninitialization that may happen on a different thread.
*
* Besides the Ready state denoting that the object is fully functional,
* there is a special Limited state. The Limited state means that the object
* is still functional, but its functionality is limited to some degree, so
* not all operations are possible. The @a aLimited argument to this method
* determines whether the caller represents this limited functionality or not.
*
* This method succeeeds (and increments the number of callers) only if the
* current object's state is Ready. Otherwise, it will return E_UNEXPECTED to
* indicate that the object is not operational. There are two exceptions from
* this rule:
* <ol>
* <li>If the @a aLimited argument is |true|, then this method will also
* succeeed if the object's state is Limited (or Ready, of course).</li>
* <li>If this method is called from the same thread that placed the object
* to InInit or InUninit state (i.e. either from within the AutoInitSpan
* or AutoUninitSpan scope), it will succeed as well (but will not
* increase the number of callers).</li>
* </ol>
*
* Normally, calling addCaller() never blocks. However, if this method is
* called by a thread created from within the AutoInitSpan scope and this
* scope is still active (i.e. the object state is InInit), it will block
* until the AutoInitSpan destructor signals that it has finished
* initialization.
*
* When this method returns a failure, the caller must not use the object
* and can return the failed result code to his caller.
*
* @param aState where to store the current object's state
* (can be used in overriden methods to determine the
* cause of the failure)
* @param aLimited |true| to add a limited caller.
* @return S_OK on success or E_UNEXPECTED on failure
*
* @note It is preferrable to use the #addLimitedCaller() rather than calling
* this method with @a aLimited = |true|, for better
* self-descriptiveness.
*
* @sa #addLimitedCaller()
* @sa #releaseCaller()
*/
bool aLimited /* = false */)
{
{
/* if Ready or allows Limited, increase the number of callers */
++ mCallers;
}
else
{
if (mStateChangeThread == RTThreadSelf())
{
/*
* Called from the same thread that is doing AutoInitSpan or
* AutoUninitSpan, just succeed
*/
}
{
/* addCaller() is called by a "child" thread while the "parent"
* thread is still doing AutoInitSpan/AutoReadySpan. Wait for the
* state to become either Ready/Limited or InitFailed/InInit/NotReady
* (in case of init failure). Note that we increase the number of
* callers anyway to prevent AutoUninitSpan from early completion.
*/
++ mCallers;
/* lazy creation */
if (mInitDoneSem == NIL_RTSEMEVENTMULTI)
LogFlowThisFunc (("Waiting for AutoInitSpan/AutoReadySpan to finish...\n"));
if (-- mInitDoneSemUsers == 0)
{
/* destroy the semaphore since no more necessary */
}
else
{
-- mCallers;
{
/* inform AutoUninitSpan ctor there are no more callers */
}
}
}
}
if (aState)
return rc;
}
/**
* Decrements the number of calls to this object by one.
* Must be called after every #addCaller() or #addLimitedCaller() when the
* object is no more necessary.
*/
void VirtualBoxBaseNEXT_base::releaseCaller()
{
{
/* if Ready or Limited, decrease the number of callers */
-- mCallers;
return;
}
{
if (mStateChangeThread == RTThreadSelf())
{
/*
* Called from the same thread that is doing AutoInitSpan or
* AutoUninitSpan, just succeed
*/
return;
}
{
/* the caller is being released after AutoUninitSpan has begun */
-- mCallers;
if (mCallers == 0)
{
/* inform the AutoUninitSpan ctor there are no more callers */
}
return;
}
}
}
// VirtualBoxBaseNEXT_base::AutoInitSpan methods
////////////////////////////////////////////////////////////////////////////////
/**
* Creates a smart initialization span object and places the object to
* InInit state.
*
* @param aObj |this| pointer of the managed VirtualBoxBase object whose
* init() method is being called
* @param aStatus initial initialization status for this span
*/
{
if (!mOk)
return;
}
/**
* initialization succeeded or partly succeeded, or places it to InitFailed
* state and calls the object's uninit() method otherwise.
*/
{
/* if the state was other than NotReady, do nothing */
if (!mOk)
return;
{
/* We have some pending addCaller() calls on other threads (created
* during InInit), signal that InInit is finished. */
}
{
}
else
{
}
else
{
/* leave the lock to prevent nesting when uninit() is called */
/* call uninit() to let the object uninit itself after failed init() */
/* Note: the object may no longer exist here (for example, it can call
* the destructor in uninit()) */
}
}
// VirtualBoxBaseNEXT_base::AutoReadySpan methods
////////////////////////////////////////////////////////////////////////////////
/**
* Creates a smart re-initialization span object and places the object to
* InInit state.
*
* @param aObj |this| pointer of the managed VirtualBoxBase object whose
* re-initialization method is being called
*/
{
if (!mOk)
return;
}
/**
* Places the managed VirtualBoxBase object to Ready state if the
* re-initialization succeeded (i.e. #setSucceeded() has been called) or
* back to Limited state otherwise.
*/
{
/* if the state was other than Limited, do nothing */
if (!mOk)
return;
{
/* We have some pending addCaller() calls on other threads,
* signal that InInit is finished. */
}
if (mSucceeded)
{
}
else
{
}
}
// VirtualBoxBaseNEXT_base::AutoUninitSpan methods
////////////////////////////////////////////////////////////////////////////////
/**
* Creates a smart uninitialization span object and places this object to
* InUninit state.
*
* @note This method blocks the current thread execution until the number of
* callers of the managed VirtualBoxBase object drops to zero!
*
* @param aObj |this| pointer of the VirtualBoxBase object whose uninit()
* method is being called
*/
{
/*
* Set mUninitDone to |true| if this object is already uninitialized
* (NotReady) or if another AutoUninitSpan is currently active on some
* other thread (InUninit).
*/
{
/* we've been called by init() on failure */
mInitFailed = true;
}
else
{
/* do nothing if already uninitialized */
if (mUninitDone)
return;
}
/* go to InUninit to prevent from adding new callers */
{
/* lazy creation */
/* wait until remaining callers release the object */
LogFlowThisFunc (("Waiting for callers (%d) to drop to zero...\n",
}
}
/**
* Places the managed VirtualBoxBase object to the NotReady state.
*/
{
/* do nothing if already uninitialized */
if (mUninitDone)
return;
}
// VirtualBoxBase methods
////////////////////////////////////////////////////////////////////////////////
/**
* Translates the given text string according to the currently installed
* translation table and current context. The current context is determined
* by the context parameter. Additionally, a comment to the source text
* string text can be given. This comment (which is NULL by default)
* is helpful in sutuations where it is necessary to distinguish between
* two or more semantically different roles of the same source text in the
* same context.
*
* @param context the context of the the translation (can be NULL
* to indicate the global context)
* @param sourceText the string to translate
* @param comment the comment to the string (NULL means no comment)
*
* @return
* the translated version of the source string in UTF-8 encoding,
* or the source string itself if the translation is not found
* in the given context.
*/
// static
const char *comment)
{
#if 0
Log(("VirtualBoxBase::translate:\n"
" context={%s}\n"
" sourceT={%s}\n"
" comment={%s}\n",
#endif
/// @todo (dmik) incorporate Qt translation file parsing and lookup
return sourceText;
}
// VirtualBoxSupportTranslationBase methods
////////////////////////////////////////////////////////////////////////////////
/**
* Modifies the given argument so that it will contain only a class name
* (null-terminated). The argument must point to a <b>non-constant</b>
* string containing a valid value, as it is generated by the
* __PRETTY_FUNCTION__ built-in macro of the GCC compiler, or by the
* __FUNCTION__ macro of any other compiler.
*
* The function assumes that the macro is used within the member of the
* class derived from the VirtualBoxSupportTranslation<> template.
*
* @param prettyFunctionName string to modify
* @return
* true on success and false otherwise
*/
{
if (!fn)
return false;
#if defined (__GNUC__)
// the format is like:
// VirtualBoxSupportTranslation<C>::VirtualBoxSupportTranslation() [with C = VirtualBox]
#define START " = "
#define END "]"
// the format is like:
// VirtualBoxSupportTranslation<class VirtualBox>::__ctor
#define START "<class "
#define END ">::"
#endif
if (start)
{
{
return true;
}
}
return false;
}
// VirtualBoxSupportErrorInfoImplBase methods
////////////////////////////////////////////////////////////////////////////////
{
{
sCounter = RTTlsAlloc();
}
++ counter;
}
{
AssertReturnVoid (counter != 0);
-- counter;
}
/**
* Sets error info for the current thread. This is an internal function that
* gets eventually called by all public variants. If @a aWarning is
* @c true, then the highest (31) bit in the @a aResultCode value which
* indicates the error severity is reset to zero to make sure the receiver will
* recognize that the created error info object represents a warning rather
* than an error.
*/
/* static */
{
/* whether multi-error mode is turned on */
if (aLogIt)
LogRel (("ERROR [COM]: aRC=%Rhrc (%#08x) aIID={%RTuuid} aComponent={%ls} aText={%ls} "
"aWarning=%RTbool, preserve=%RTbool\n",
preserve));
/* these are mandatory, others -- not */
E_FAIL);
/* reset the error severity bit if it's a warning */
if (aWarning)
aResultCode &= ~0x80000000;
do
{
#if !defined (VBOX_WITH_XPCOM)
if (preserve)
{
/* get the current error info if any */
{
/* create a IVirtualBoxErrorInfo wrapper for the native
* IErrorInfo object */
{
}
}
}
/* On failure, curInfo will stay null */
/* set the current error info and preserve the previous one if any */
#else // !defined (VBOX_WITH_XPCOM)
if (NS_SUCCEEDED (rc))
{
if (preserve)
{
/* get the current error info if any */
{
/* create a IVirtualBoxErrorInfo wrapper for the native
* nsIException object */
{
}
}
}
/* On failure, curInfo will stay null */
/* set the current error info and preserve the previous one if any */
}
else if (rc == NS_ERROR_UNEXPECTED)
{
/*
* It is possible that setError() is being called by the object
* after the XPCOM shutdown sequence has been initiated
* (for example, when XPCOM releases all instances it internally
* references, which can cause object's FinalConstruct() and then
* uninit()). In this case, do_GetService() above will return
* NS_ERROR_UNEXPECTED and it doesn't actually make sense to
* set the exception (nobody will be able to read it).
*/
LogWarningFunc (("Will not set an exception because "
"nsIExceptionService is not available "
"(NS_ERROR_UNEXPECTED). "
"XPCOM is being shutdown?\n"));
}
#endif // !defined (VBOX_WITH_XPCOM)
}
while (0);
AssertComRC (rc);
}
// VirtualBoxBaseWithChildren methods
////////////////////////////////////////////////////////////////////////////////
/**
* Uninitializes all dependent children registered with #addDependentChild().
*
* @note
* This method will call uninit() methods of children. If these methods
* access the parent object, uninitDependentChildren() must be called
* either at the beginning of the parent uninitialization sequence (when
* it is still operational) or after setReady(false) is called to
* indicate the parent is out of action.
*/
{
/// @todo (r=dmik) see todo in VirtualBoxBase.h, in
// template <class C> void removeDependentChild (C *child)
AutoWriteLock alock (this);
if (mDependentChildren.size())
{
/* We keep the lock until we have enumerated all children.
* Those ones that will try to call #removeDependentChild() from
* a different thread will have to wait */
Assert (mChildrenLeft == 0);
{
if (child)
}
}
/* Wait until all children started uninitializing on their own
* (and therefore are waiting for some parent's method or for
* #removeDependentChild() to return) are finished uninitialization */
if (mUninitDoneSem != NIL_RTSEMEVENT)
{
/* let stuck children run */
LogFlowThisFunc (("Waiting for uninitialization of all children...\n"));
Assert (mChildrenLeft == 0);
}
}
/**
* Returns a pointer to the dependent child corresponding to the given
* interface pointer (used as a key in the map) or NULL if the interface
* pointer doesn't correspond to any child registered using
* #addDependentChild().
*
* @param unk
* Pointer to map to the dependent child object (it is ComPtr <IUnknown>
* rather than IUnknown *, to guarantee IUnknown * identity)
* @return
* Pointer to the dependent child object
*/
{
if (mUninitDoneSem != NIL_RTSEMEVENT)
return NULL;
return NULL;
}
/** Helper for addDependentChild() template method */
{
if (mUninitDoneSem != NIL_RTSEMEVENT)
{
// for this very unlikely case, we have to increase the number of
// children left, for symmetry with #removeDependentChild()
++ mChildrenLeft;
return;
}
}
/** Helper for removeDependentChild() template method */
{
/// @todo (r=dmik) see todo in VirtualBoxBase.h, in
// template <class C> void removeDependentChild (C *child)
AssertReturn (!!unk, (void) 0);
if (mUninitDoneSem != NIL_RTSEMEVENT)
{
// uninitDependentChildren() is in action, just increase the number
// of children left and signal a semaphore when it reaches zero
Assert (mChildrenLeft != 0);
-- mChildrenLeft;
if (mChildrenLeft == 0)
{
}
return;
}
}
// VirtualBoxBaseWithChildrenNEXT methods
////////////////////////////////////////////////////////////////////////////////
/**
* Uninitializes all dependent children registered with #addDependentChild().
*
* Typically called from the uninit() method. Note that this method will call
* uninit() methods of child objects. If these methods need to call the parent
* object during initialization, uninitDependentChildren() must be called before
* the relevant part of the parent is uninitialized, usually at the begnning of
* the parent uninitialization sequence.
*/
{
if (mDependentChildren.size())
{
/* We keep the lock until we have enumerated all children.
* Those ones that will try to call removeDependentChild() from a
* different thread will have to wait */
Assert (mChildrenLeft == 0);
{
if (child)
}
}
/* Wait until all children that called uninit() on their own on other
* threads but stuck waiting for the map lock in removeDependentChild() have
* finished uninitialization. */
if (mUninitDoneSem != NIL_RTSEMEVENT)
{
/* let stuck children run */
LogFlowThisFunc (("Waiting for uninitialization of all children...\n"));
Assert (mChildrenLeft == 0);
}
}
/**
* Returns a pointer to the dependent child corresponding to the given
* interface pointer (used as a key in the map of dependent children) or NULL
* if the interface pointer doesn't correspond to any child registered using
* #addDependentChild().
*
* Note that ComPtr <IUnknown> is used as an argument instead of IUnknown * in
* order to guarantee IUnknown identity and disambiguation by doing
* QueryInterface (IUnknown) rather than a regular C cast.
*
* @param aUnk Pointer to map to the dependent child object.
* @return Pointer to the dependent child object.
*/
{
/* return NULL if uninitDependentChildren() is in action */
if (mUninitDoneSem != NIL_RTSEMEVENT)
return NULL;
return NULL;
}
{
if (mUninitDoneSem != NIL_RTSEMEVENT)
{
/* uninitDependentChildren() is being run. For this very unlikely case,
* we have to increase the number of children left, for symmetry with
* a later #removeDependentChild() call. */
++ mChildrenLeft;
return;
}
}
{
if (mUninitDoneSem != NIL_RTSEMEVENT)
{
/* uninitDependentChildren() is being run. Just decrease the number of
* children left and signal a semaphore if it reaches zero. */
Assert (mChildrenLeft != 0);
-- mChildrenLeft;
if (mChildrenLeft == 0)
{
}
return;
}
aUnk));
}
// VirtualBoxBaseWithTypedChildrenNEXT methods
////////////////////////////////////////////////////////////////////////////////
/**
* Uninitializes all dependent children registered with
* #addDependentChild().
*
* @note This method will call uninit() methods of children. If these
* methods access the parent object, uninitDependentChildren() must be
* called either at the beginning of the parent uninitialization
* sequence (when it is still operational) or after setReady(false) is
* called to indicate the parent is out of action.
*/
template <class C>
{
if (mDependentChildren.size())
{
/* set flag to ignore #removeDependentChild() called from
* child->uninit() */
mInUninit = true;
/* leave the locks to let children waiting for
* #removeDependentChild() run */
{
if (child)
}
mInUninit = false;
}
}
// Settings API additions
////////////////////////////////////////////////////////////////////////////////
#if defined VBOX_MAIN_SETTINGS_ADDONS
namespace settings
{
template<> stdx::char_auto_ptr
{
throw ENoValue();
/* The only way to cause RTUtf16ToUtf8Ex return a number of bytes needed
* w/o allocating the result buffer itself is to provide that both cch
* and *ppsz are not NULL. */
char dummy [1];
if (RT_SUCCESS (vrc))
{
/* the string only contains '\0' :) */
return result;
}
if (vrc == VERR_BUFFER_OVERFLOW)
{
}
if (RT_FAILURE (vrc))
throw LogicError (RT_SRC_POS);
return result;
}
{
throw ENoValue();
/* For settings, the format is always {XXX...XXX} */
char buf [RTUUID_STR_LENGTH];
/* strip { and } */
/* we don't use Guid (const char *) because we want to throw
* ENoConversion on format error */
if (RT_FAILURE (vrc))
}
template<> stdx::char_auto_ptr
{
/* For settings, the format is always {XXX...XXX} */
if (RT_FAILURE (vrc))
throw LogicError (RT_SRC_POS);
return result;
}
} /* namespace settings */
#endif /* VBOX_MAIN_SETTINGS_ADDONS */