VirtualBox

source: vbox/trunk/src/VBox/Main/VirtualBoxBase.cpp@ 30714

Last change on this file since 30714 was 30714, checked in by vboxsync, 15 years ago

Main: remove SupportErrorInfo template magic

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 33.1 KB
Line 
1/* $Id: VirtualBoxBase.cpp 30714 2010-07-07 16:20:03Z vboxsync $ */
2
3/** @file
4 *
5 * VirtualBox COM base classes implementation
6 */
7
8/*
9 * Copyright (C) 2006-2010 Oracle Corporation
10 *
11 * This file is part of VirtualBox Open Source Edition (OSE), as
12 * available from http://www.215389.xyz. This file is free software;
13 * you can redistribute it and/or modify it under the terms of the GNU
14 * General Public License (GPL) as published by the Free Software
15 * Foundation, in version 2 as it comes in the "COPYING" file of the
16 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
17 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
18 */
19
20#include <iprt/semaphore.h>
21#include <iprt/asm.h>
22
23#if !defined (VBOX_WITH_XPCOM)
24#include <windows.h>
25#include <dbghelp.h>
26#else /* !defined (VBOX_WITH_XPCOM) */
27/// @todo remove when VirtualBoxErrorInfo goes away from here
28#include <nsIServiceManager.h>
29#include <nsIExceptionService.h>
30#endif /* !defined (VBOX_WITH_XPCOM) */
31
32#include "VirtualBoxBase.h"
33#include "AutoCaller.h"
34#include "VirtualBoxErrorInfoImpl.h"
35#include "Logging.h"
36
37#include "objectslist.h"
38
39////////////////////////////////////////////////////////////////////////////////
40//
41// VirtualBoxBase
42//
43////////////////////////////////////////////////////////////////////////////////
44
45VirtualBoxBase::VirtualBoxBase()
46 : mStateLock(LOCKCLASS_OBJECTSTATE)
47{
48 mState = NotReady;
49 mStateChangeThread = NIL_RTTHREAD;
50 mCallers = 0;
51 mZeroCallersSem = NIL_RTSEMEVENT;
52 mInitUninitSem = NIL_RTSEMEVENTMULTI;
53 mInitUninitWaiters = 0;
54 mObjectLock = NULL;
55}
56
57VirtualBoxBase::~VirtualBoxBase()
58{
59 if (mObjectLock)
60 delete mObjectLock;
61 Assert(mInitUninitWaiters == 0);
62 Assert(mInitUninitSem == NIL_RTSEMEVENTMULTI);
63 if (mZeroCallersSem != NIL_RTSEMEVENT)
64 RTSemEventDestroy (mZeroCallersSem);
65 mCallers = 0;
66 mStateChangeThread = NIL_RTTHREAD;
67 mState = NotReady;
68}
69
70/**
71 * This virtual method returns an RWLockHandle that can be used to
72 * protect instance data. This RWLockHandle is generally referred to
73 * as the "object lock"; its locking class (for lock order validation)
74 * must be returned by another virtual method, getLockingClass(), which
75 * by default returns LOCKCLASS_OTHEROBJECT but is overridden by several
76 * subclasses such as VirtualBox, Host, Machine and others.
77 *
78 * On the first call this method lazily creates the RWLockHandle.
79 *
80 * @return
81 */
82/* virtual */
83RWLockHandle *VirtualBoxBase::lockHandle() const
84{
85 /* lazy initialization */
86 if (RT_UNLIKELY(!mObjectLock))
87 {
88 AssertCompile (sizeof (RWLockHandle *) == sizeof (void *));
89
90 // getLockingClass() is overridden by many subclasses to return
91 // one of the locking classes listed at the top of AutoLock.h
92 RWLockHandle *objLock = new RWLockHandle(getLockingClass());
93 if (!ASMAtomicCmpXchgPtr(&mObjectLock, objLock, NULL))
94 {
95 delete objLock;
96 objLock = ASMAtomicReadPtrT(&mObjectLock, RWLockHandle *);
97 }
98 return objLock;
99 }
100 return mObjectLock;
101}
102
103/**
104 * Increments the number of calls to this object by one.
105 *
106 * After this method succeeds, it is guaranted that the object will remain
107 * in the Ready (or in the Limited) state at least until #releaseCaller() is
108 * called.
109 *
110 * This method is intended to mark the beginning of sections of code within
111 * methods of COM objects that depend on the readiness (Ready) state. The
112 * Ready state is a primary "ready to serve" state. Usually all code that
113 * works with component's data depends on it. On practice, this means that
114 * almost every public method, setter or getter of the object should add
115 * itself as an object's caller at the very beginning, to protect from an
116 * unexpected uninitialization that may happen on a different thread.
117 *
118 * Besides the Ready state denoting that the object is fully functional,
119 * there is a special Limited state. The Limited state means that the object
120 * is still functional, but its functionality is limited to some degree, so
121 * not all operations are possible. The @a aLimited argument to this method
122 * determines whether the caller represents this limited functionality or
123 * not.
124 *
125 * This method succeeeds (and increments the number of callers) only if the
126 * current object's state is Ready. Otherwise, it will return E_ACCESSDENIED
127 * to indicate that the object is not operational. There are two exceptions
128 * from this rule:
129 * <ol>
130 * <li>If the @a aLimited argument is |true|, then this method will also
131 * succeeed if the object's state is Limited (or Ready, of course).
132 * </li>
133 * <li>If this method is called from the same thread that placed
134 * the object to InInit or InUninit state (i.e. either from within the
135 * AutoInitSpan or AutoUninitSpan scope), it will succeed as well (but
136 * will not increase the number of callers).
137 * </li>
138 * </ol>
139 *
140 * Normally, calling addCaller() never blocks. However, if this method is
141 * called by a thread created from within the AutoInitSpan scope and this
142 * scope is still active (i.e. the object state is InInit), it will block
143 * until the AutoInitSpan destructor signals that it has finished
144 * initialization.
145 *
146 * When this method returns a failure, the caller must not use the object
147 * and should return the failed result code to its own caller.
148 *
149 * @param aState Where to store the current object's state (can be
150 * used in overriden methods to determine the cause of
151 * the failure).
152 * @param aLimited |true| to add a limited caller.
153 *
154 * @return S_OK on success or E_ACCESSDENIED on failure.
155 *
156 * @note It is preferrable to use the #addLimitedCaller() rather than
157 * calling this method with @a aLimited = |true|, for better
158 * self-descriptiveness.
159 *
160 * @sa #addLimitedCaller()
161 * @sa #releaseCaller()
162 */
163HRESULT VirtualBoxBase::addCaller(State *aState /* = NULL */,
164 bool aLimited /* = false */)
165{
166 AutoWriteLock stateLock(mStateLock COMMA_LOCKVAL_SRC_POS);
167
168 HRESULT rc = E_ACCESSDENIED;
169
170 if (mState == Ready || (aLimited && mState == Limited))
171 {
172 /* if Ready or allows Limited, increase the number of callers */
173 ++ mCallers;
174 rc = S_OK;
175 }
176 else
177 if (mState == InInit || mState == InUninit)
178 {
179 if (mStateChangeThread == RTThreadSelf())
180 {
181 /* Called from the same thread that is doing AutoInitSpan or
182 * AutoUninitSpan, just succeed */
183 rc = S_OK;
184 }
185 else if (mState == InInit)
186 {
187 /* addCaller() is called by a "child" thread while the "parent"
188 * thread is still doing AutoInitSpan/AutoReinitSpan, so wait for
189 * the state to become either Ready/Limited or InitFailed (in
190 * case of init failure).
191 *
192 * Note that we increase the number of callers anyway -- to
193 * prevent AutoUninitSpan from early completion if we are
194 * still not scheduled to pick up the posted semaphore when
195 * uninit() is called.
196 */
197 ++ mCallers;
198
199 /* lazy semaphore creation */
200 if (mInitUninitSem == NIL_RTSEMEVENTMULTI)
201 {
202 RTSemEventMultiCreate (&mInitUninitSem);
203 Assert(mInitUninitWaiters == 0);
204 }
205
206 ++ mInitUninitWaiters;
207
208 LogFlowThisFunc(("Waiting for AutoInitSpan/AutoReinitSpan to finish...\n"));
209
210 stateLock.leave();
211 RTSemEventMultiWait (mInitUninitSem, RT_INDEFINITE_WAIT);
212 stateLock.enter();
213
214 if (-- mInitUninitWaiters == 0)
215 {
216 /* destroy the semaphore since no more necessary */
217 RTSemEventMultiDestroy (mInitUninitSem);
218 mInitUninitSem = NIL_RTSEMEVENTMULTI;
219 }
220
221 if (mState == Ready || (aLimited && mState == Limited))
222 rc = S_OK;
223 else
224 {
225 Assert(mCallers != 0);
226 -- mCallers;
227 if (mCallers == 0 && mState == InUninit)
228 {
229 /* inform AutoUninitSpan ctor there are no more callers */
230 RTSemEventSignal(mZeroCallersSem);
231 }
232 }
233 }
234 }
235
236 if (aState)
237 *aState = mState;
238
239 if (FAILED(rc))
240 {
241 if (mState == VirtualBoxBase::Limited)
242 rc = setError(rc, "The object functionality is limited");
243 else
244 rc = setError(rc, "The object is not ready");
245 }
246
247 return rc;
248}
249
250/**
251 * Decreases the number of calls to this object by one.
252 *
253 * Must be called after every #addCaller() or #addLimitedCaller() when
254 * protecting the object from uninitialization is no more necessary.
255 */
256void VirtualBoxBase::releaseCaller()
257{
258 AutoWriteLock stateLock(mStateLock COMMA_LOCKVAL_SRC_POS);
259
260 if (mState == Ready || mState == Limited)
261 {
262 /* if Ready or Limited, decrease the number of callers */
263 AssertMsgReturn(mCallers != 0, ("mCallers is ZERO!"), (void) 0);
264 --mCallers;
265
266 return;
267 }
268
269 if (mState == InInit || mState == InUninit)
270 {
271 if (mStateChangeThread == RTThreadSelf())
272 {
273 /* Called from the same thread that is doing AutoInitSpan or
274 * AutoUninitSpan: just succeed */
275 return;
276 }
277
278 if (mState == InUninit)
279 {
280 /* the caller is being released after AutoUninitSpan has begun */
281 AssertMsgReturn(mCallers != 0, ("mCallers is ZERO!"), (void) 0);
282 --mCallers;
283
284 if (mCallers == 0)
285 /* inform the Auto*UninitSpan ctor there are no more callers */
286 RTSemEventSignal(mZeroCallersSem);
287
288 return;
289 }
290 }
291
292 AssertMsgFailed (("mState = %d!", mState));
293}
294
295/**
296 * Translates the given text string according to the currently installed
297 * translation table and current context. The current context is determined
298 * by the context parameter. Additionally, a comment to the source text
299 * string text can be given. This comment (which is NULL by default)
300 * is helpful in situations where it is necessary to distinguish between
301 * two or more semantically different roles of the same source text in the
302 * same context.
303 *
304 * @param context the context of the translation (can be NULL
305 * to indicate the global context)
306 * @param sourceText the string to translate
307 * @param comment the comment to the string (NULL means no comment)
308 *
309 * @return
310 * the translated version of the source string in UTF-8 encoding,
311 * or the source string itself if the translation is not found
312 * in the given context.
313 */
314// static
315const char *VirtualBoxBase::translate(const char * /* context */, const char *sourceText,
316 const char * /* comment */)
317{
318#if 0
319 Log(("VirtualBoxBase::translate:\n"
320 " context={%s}\n"
321 " sourceT={%s}\n"
322 " comment={%s}\n",
323 context, sourceText, comment));
324#endif
325
326 /// @todo (dmik) incorporate Qt translation file parsing and lookup
327 return sourceText;
328}
329
330/**
331 * Sets error info for the current thread. This is an internal function that
332 * gets eventually called by all public variants. If @a aWarning is
333 * @c true, then the highest (31) bit in the @a aResultCode value which
334 * indicates the error severity is reset to zero to make sure the receiver will
335 * recognize that the created error info object represents a warning rather
336 * than an error.
337 */
338/* static */
339HRESULT VirtualBoxBase::setErrorInternal(HRESULT aResultCode,
340 const GUID &aIID,
341 const char *pcszComponent,
342 const Utf8Str &aText,
343 bool aWarning,
344 bool aLogIt)
345{
346 /* whether multi-error mode is turned on */
347 bool preserve = MultiResult::isMultiEnabled();
348
349 if (aLogIt)
350 LogRel(("ERROR [COM]: aRC=%Rhrc (%#08x) aIID={%RTuuid} aComponent={%s} aText={%s} aWarning=%RTbool, preserve=%RTbool\n",
351 aResultCode,
352 aResultCode,
353 &aIID,
354 pcszComponent,
355 aText.c_str(),
356 aWarning,
357 preserve));
358
359 /* these are mandatory, others -- not */
360 AssertReturn((!aWarning && FAILED(aResultCode)) ||
361 (aWarning && aResultCode != S_OK),
362 E_FAIL);
363 AssertReturn(!aText.isEmpty(), E_FAIL);
364
365 /* reset the error severity bit if it's a warning */
366 if (aWarning)
367 aResultCode &= ~0x80000000;
368
369 HRESULT rc = S_OK;
370
371 do
372 {
373 ComObjPtr<VirtualBoxErrorInfo> info;
374 rc = info.createObject();
375 if (FAILED(rc)) break;
376
377#if !defined (VBOX_WITH_XPCOM)
378
379 ComPtr<IVirtualBoxErrorInfo> curInfo;
380 if (preserve)
381 {
382 /* get the current error info if any */
383 ComPtr<IErrorInfo> err;
384 rc = ::GetErrorInfo (0, err.asOutParam());
385 if (FAILED(rc)) break;
386 rc = err.queryInterfaceTo(curInfo.asOutParam());
387 if (FAILED(rc))
388 {
389 /* create a IVirtualBoxErrorInfo wrapper for the native
390 * IErrorInfo object */
391 ComObjPtr<VirtualBoxErrorInfo> wrapper;
392 rc = wrapper.createObject();
393 if (SUCCEEDED(rc))
394 {
395 rc = wrapper->init (err);
396 if (SUCCEEDED(rc))
397 curInfo = wrapper;
398 }
399 }
400 }
401 /* On failure, curInfo will stay null */
402 Assert(SUCCEEDED(rc) || curInfo.isNull());
403
404 /* set the current error info and preserve the previous one if any */
405 rc = info->init(aResultCode, aIID, pcszComponent, aText, curInfo);
406 if (FAILED(rc)) break;
407
408 ComPtr<IErrorInfo> err;
409 rc = info.queryInterfaceTo(err.asOutParam());
410 if (SUCCEEDED(rc))
411 rc = ::SetErrorInfo (0, err);
412
413#else // !defined (VBOX_WITH_XPCOM)
414
415 nsCOMPtr <nsIExceptionService> es;
416 es = do_GetService (NS_EXCEPTIONSERVICE_CONTRACTID, &rc);
417 if (NS_SUCCEEDED(rc))
418 {
419 nsCOMPtr <nsIExceptionManager> em;
420 rc = es->GetCurrentExceptionManager (getter_AddRefs (em));
421 if (FAILED(rc)) break;
422
423 ComPtr<IVirtualBoxErrorInfo> curInfo;
424 if (preserve)
425 {
426 /* get the current error info if any */
427 ComPtr<nsIException> ex;
428 rc = em->GetCurrentException (ex.asOutParam());
429 if (FAILED(rc)) break;
430 rc = ex.queryInterfaceTo(curInfo.asOutParam());
431 if (FAILED(rc))
432 {
433 /* create a IVirtualBoxErrorInfo wrapper for the native
434 * nsIException object */
435 ComObjPtr<VirtualBoxErrorInfo> wrapper;
436 rc = wrapper.createObject();
437 if (SUCCEEDED(rc))
438 {
439 rc = wrapper->init (ex);
440 if (SUCCEEDED(rc))
441 curInfo = wrapper;
442 }
443 }
444 }
445 /* On failure, curInfo will stay null */
446 Assert(SUCCEEDED(rc) || curInfo.isNull());
447
448 /* set the current error info and preserve the previous one if any */
449 rc = info->init(aResultCode, aIID, pcszComponent, Bstr(aText), curInfo);
450 if (FAILED(rc)) break;
451
452 ComPtr<nsIException> ex;
453 rc = info.queryInterfaceTo(ex.asOutParam());
454 if (SUCCEEDED(rc))
455 rc = em->SetCurrentException (ex);
456 }
457 else if (rc == NS_ERROR_UNEXPECTED)
458 {
459 /*
460 * It is possible that setError() is being called by the object
461 * after the XPCOM shutdown sequence has been initiated
462 * (for example, when XPCOM releases all instances it internally
463 * references, which can cause object's FinalConstruct() and then
464 * uninit()). In this case, do_GetService() above will return
465 * NS_ERROR_UNEXPECTED and it doesn't actually make sense to
466 * set the exception (nobody will be able to read it).
467 */
468 LogWarningFunc(("Will not set an exception because nsIExceptionService is not available "
469 "(NS_ERROR_UNEXPECTED). XPCOM is being shutdown?\n"));
470 rc = NS_OK;
471 }
472
473#endif // !defined (VBOX_WITH_XPCOM)
474 }
475 while (0);
476
477 AssertComRC (rc);
478
479 return SUCCEEDED(rc) ? aResultCode : rc;
480}
481
482/**
483 * Shortcut instance method to calling the static setErrorInternal with the
484 * class interface ID and component name inserted correctly. This uses the
485 * virtual getClassIID() and getComponentName() methods which are automatically
486 * defined by the VIRTUALBOXBASE_ADD_ERRORINFO_SUPPORT macro.
487 * @param aResultCode
488 * @param pcsz
489 * @return
490 */
491HRESULT VirtualBoxBase::setError(HRESULT aResultCode, const char *pcsz, ...)
492{
493 va_list args;
494 va_start(args, pcsz);
495 HRESULT rc = setErrorInternal(aResultCode,
496 this->getClassIID(),
497 this->getComponentName(),
498 Utf8StrFmtVA(pcsz, args),
499 false /* aWarning */,
500 true /* aLogIt */);
501 va_end(args);
502 return rc;
503}
504
505/**
506 * Like setError(), but sets the "warning" bit in the call to setErrorInternal().
507 * @param aResultCode
508 * @param pcsz
509 * @return
510 */
511HRESULT VirtualBoxBase::setWarning(HRESULT aResultCode, const char *pcsz, ...)
512{
513 va_list args;
514 va_start(args, pcsz);
515 HRESULT rc = setErrorInternal(aResultCode,
516 this->getClassIID(),
517 this->getComponentName(),
518 Utf8StrFmtVA(pcsz, args),
519 true /* aWarning */,
520 true /* aLogIt */);
521 va_end(args);
522 return rc;
523}
524
525/**
526 * Like setError(), but disables the "log" flag in the call to setErrorInternal().
527 * @param aResultCode
528 * @param pcsz
529 * @return
530 */
531HRESULT VirtualBoxBase::setErrorNoLog(HRESULT aResultCode, const char *pcsz, ...)
532{
533 va_list args;
534 va_start(args, pcsz);
535 HRESULT rc = setErrorInternal(aResultCode,
536 this->getClassIID(),
537 this->getComponentName(),
538 Utf8StrFmtVA(pcsz, args),
539 false /* aWarning */,
540 false /* aLogIt */);
541 va_end(args);
542 return rc;
543}
544
545////////////////////////////////////////////////////////////////////////////////
546//
547// AutoInitSpan methods
548//
549////////////////////////////////////////////////////////////////////////////////
550
551/**
552 * Creates a smart initialization span object that places the object to
553 * InInit state.
554 *
555 * Please see the AutoInitSpan class description for more info.
556 *
557 * @param aObj |this| pointer of the managed VirtualBoxBase object whose
558 * init() method is being called.
559 * @param aResult Default initialization result.
560 */
561AutoInitSpan::AutoInitSpan(VirtualBoxBase *aObj,
562 Result aResult /* = Failed */)
563 : mObj(aObj),
564 mResult(aResult),
565 mOk(false)
566{
567 Assert(aObj);
568
569 AutoWriteLock stateLock(mObj->mStateLock COMMA_LOCKVAL_SRC_POS);
570
571 mOk = mObj->mState == VirtualBoxBase::NotReady;
572 AssertReturnVoid (mOk);
573
574 mObj->setState(VirtualBoxBase::InInit);
575}
576
577/**
578 * Places the managed VirtualBoxBase object to Ready/Limited state if the
579 * initialization succeeded or partly succeeded, or places it to InitFailed
580 * state and calls the object's uninit() method.
581 *
582 * Please see the AutoInitSpan class description for more info.
583 */
584AutoInitSpan::~AutoInitSpan()
585{
586 /* if the state was other than NotReady, do nothing */
587 if (!mOk)
588 return;
589
590 AutoWriteLock stateLock(mObj->mStateLock COMMA_LOCKVAL_SRC_POS);
591
592 Assert(mObj->mState == VirtualBoxBase::InInit);
593
594 if (mObj->mCallers > 0)
595 {
596 Assert(mObj->mInitUninitWaiters > 0);
597
598 /* We have some pending addCaller() calls on other threads (created
599 * during InInit), signal that InInit is finished and they may go on. */
600 RTSemEventMultiSignal(mObj->mInitUninitSem);
601 }
602
603 if (mResult == Succeeded)
604 {
605 mObj->setState(VirtualBoxBase::Ready);
606 }
607 else
608 if (mResult == Limited)
609 {
610 mObj->setState(VirtualBoxBase::Limited);
611 }
612 else
613 {
614 mObj->setState(VirtualBoxBase::InitFailed);
615 /* leave the lock to prevent nesting when uninit() is called */
616 stateLock.leave();
617 /* call uninit() to let the object uninit itself after failed init() */
618 mObj->uninit();
619 /* Note: the object may no longer exist here (for example, it can call
620 * the destructor in uninit()) */
621 }
622}
623
624// AutoReinitSpan methods
625////////////////////////////////////////////////////////////////////////////////
626
627/**
628 * Creates a smart re-initialization span object and places the object to
629 * InInit state.
630 *
631 * Please see the AutoInitSpan class description for more info.
632 *
633 * @param aObj |this| pointer of the managed VirtualBoxBase object whose
634 * re-initialization method is being called.
635 */
636AutoReinitSpan::AutoReinitSpan(VirtualBoxBase *aObj)
637 : mObj(aObj),
638 mSucceeded(false),
639 mOk(false)
640{
641 Assert(aObj);
642
643 AutoWriteLock stateLock(mObj->mStateLock COMMA_LOCKVAL_SRC_POS);
644
645 mOk = mObj->mState == VirtualBoxBase::Limited;
646 AssertReturnVoid (mOk);
647
648 mObj->setState(VirtualBoxBase::InInit);
649}
650
651/**
652 * Places the managed VirtualBoxBase object to Ready state if the
653 * re-initialization succeeded (i.e. #setSucceeded() has been called) or back to
654 * Limited state otherwise.
655 *
656 * Please see the AutoInitSpan class description for more info.
657 */
658AutoReinitSpan::~AutoReinitSpan()
659{
660 /* if the state was other than Limited, do nothing */
661 if (!mOk)
662 return;
663
664 AutoWriteLock stateLock(mObj->mStateLock COMMA_LOCKVAL_SRC_POS);
665
666 Assert(mObj->mState == VirtualBoxBase::InInit);
667
668 if (mObj->mCallers > 0 && mObj->mInitUninitWaiters > 0)
669 {
670 /* We have some pending addCaller() calls on other threads (created
671 * during InInit), signal that InInit is finished and they may go on. */
672 RTSemEventMultiSignal(mObj->mInitUninitSem);
673 }
674
675 if (mSucceeded)
676 {
677 mObj->setState(VirtualBoxBase::Ready);
678 }
679 else
680 {
681 mObj->setState(VirtualBoxBase::Limited);
682 }
683}
684
685// AutoUninitSpan methods
686////////////////////////////////////////////////////////////////////////////////
687
688/**
689 * Creates a smart uninitialization span object and places this object to
690 * InUninit state.
691 *
692 * Please see the AutoInitSpan class description for more info.
693 *
694 * @note This method blocks the current thread execution until the number of
695 * callers of the managed VirtualBoxBase object drops to zero!
696 *
697 * @param aObj |this| pointer of the VirtualBoxBase object whose uninit()
698 * method is being called.
699 */
700AutoUninitSpan::AutoUninitSpan(VirtualBoxBase *aObj)
701 : mObj(aObj),
702 mInitFailed(false),
703 mUninitDone(false)
704{
705 Assert(aObj);
706
707 AutoWriteLock stateLock(mObj->mStateLock COMMA_LOCKVAL_SRC_POS);
708
709 Assert(mObj->mState != VirtualBoxBase::InInit);
710
711 /* Set mUninitDone to |true| if this object is already uninitialized
712 * (NotReady) or if another AutoUninitSpan is currently active on some
713 * other thread (InUninit). */
714 mUninitDone = mObj->mState == VirtualBoxBase::NotReady
715 || mObj->mState == VirtualBoxBase::InUninit;
716
717 if (mObj->mState == VirtualBoxBase::InitFailed)
718 {
719 /* we've been called by init() on failure */
720 mInitFailed = true;
721 }
722 else
723 {
724 if (mUninitDone)
725 {
726 /* do nothing if already uninitialized */
727 if (mObj->mState == VirtualBoxBase::NotReady)
728 return;
729
730 /* otherwise, wait until another thread finishes uninitialization.
731 * This is necessary to make sure that when this method returns, the
732 * object is NotReady and therefore can be deleted (for example).
733 * In particular, this is used by
734 * VirtualBoxBaseWithTypedChildrenNEXT::uninitDependentChildren(). */
735
736 /* lazy semaphore creation */
737 if (mObj->mInitUninitSem == NIL_RTSEMEVENTMULTI)
738 {
739 RTSemEventMultiCreate(&mObj->mInitUninitSem);
740 Assert(mObj->mInitUninitWaiters == 0);
741 }
742 ++mObj->mInitUninitWaiters;
743
744 LogFlowFunc(("{%p}: Waiting for AutoUninitSpan to finish...\n",
745 mObj));
746
747 stateLock.leave();
748 RTSemEventMultiWait(mObj->mInitUninitSem, RT_INDEFINITE_WAIT);
749 stateLock.enter();
750
751 if (--mObj->mInitUninitWaiters == 0)
752 {
753 /* destroy the semaphore since no more necessary */
754 RTSemEventMultiDestroy(mObj->mInitUninitSem);
755 mObj->mInitUninitSem = NIL_RTSEMEVENTMULTI;
756 }
757
758 return;
759 }
760 }
761
762 /* go to InUninit to prevent from adding new callers */
763 mObj->setState(VirtualBoxBase::InUninit);
764
765 /* wait for already existing callers to drop to zero */
766 if (mObj->mCallers > 0)
767 {
768 /* lazy creation */
769 Assert(mObj->mZeroCallersSem == NIL_RTSEMEVENT);
770 RTSemEventCreate(&mObj->mZeroCallersSem);
771
772 /* wait until remaining callers release the object */
773 LogFlowFunc(("{%p}: Waiting for callers (%d) to drop to zero...\n",
774 mObj, mObj->mCallers));
775
776 stateLock.leave();
777 RTSemEventWait(mObj->mZeroCallersSem, RT_INDEFINITE_WAIT);
778 }
779}
780
781/**
782 * Places the managed VirtualBoxBase object to the NotReady state.
783 */
784AutoUninitSpan::~AutoUninitSpan()
785{
786 /* do nothing if already uninitialized */
787 if (mUninitDone)
788 return;
789
790 AutoWriteLock stateLock(mObj->mStateLock COMMA_LOCKVAL_SRC_POS);
791
792 Assert(mObj->mState == VirtualBoxBase::InUninit);
793
794 mObj->setState(VirtualBoxBase::NotReady);
795}
796
797////////////////////////////////////////////////////////////////////////////////
798//
799// VirtualBoxSupportTranslationBase
800//
801////////////////////////////////////////////////////////////////////////////////
802
803/**
804 * Modifies the given argument so that it will contain only a class name
805 * (null-terminated). The argument must point to a <b>non-constant</b>
806 * string containing a valid value, as it is generated by the
807 * __PRETTY_FUNCTION__ built-in macro of the GCC compiler, or by the
808 * __FUNCTION__ macro of any other compiler.
809 *
810 * The function assumes that the macro is used within the member of the
811 * class derived from the VirtualBoxSupportTranslation<> template.
812 *
813 * @param prettyFunctionName string to modify
814 * @return
815 * true on success and false otherwise
816 */
817bool VirtualBoxSupportTranslationBase::cutClassNameFrom__PRETTY_FUNCTION__ (char *fn)
818{
819 Assert(fn);
820 if (!fn)
821 return false;
822
823#if defined (__GNUC__)
824
825 // the format is like:
826 // VirtualBoxSupportTranslation<C>::VirtualBoxSupportTranslation() [with C = VirtualBox]
827
828 #define START " = "
829 #define END "]"
830
831#elif defined (_MSC_VER)
832
833 // the format is like:
834 // VirtualBoxSupportTranslation<class VirtualBox>::__ctor
835
836 #define START "<class "
837 #define END ">::"
838
839#endif
840
841 char *start = strstr(fn, START);
842 Assert(start);
843 if (start)
844 {
845 start += sizeof(START) - 1;
846 char *end = strstr(start, END);
847 Assert(end && (end > start));
848 if (end && (end > start))
849 {
850 size_t len = end - start;
851 memmove(fn, start, len);
852 fn[len] = 0;
853 return true;
854 }
855 }
856
857 #undef END
858 #undef START
859
860 return false;
861}
862
863////////////////////////////////////////////////////////////////////////////////
864//
865// VirtualBoxBaseWithChildrenNEXT methods
866//
867////////////////////////////////////////////////////////////////////////////////
868
869/**
870 * Uninitializes all dependent children registered on this object with
871 * #addDependentChild().
872 *
873 * Must be called from within the AutoUninitSpan (i.e.
874 * typically from this object's uninit() method) to uninitialize children
875 * before this object goes out of service and becomes unusable.
876 *
877 * Note that this method will call uninit() methods of child objects. If
878 * these methods need to call the parent object during uninitialization,
879 * #uninitDependentChildren() must be called before the relevant part of the
880 * parent is uninitialized: usually at the begnning of the parent
881 * uninitialization sequence.
882 *
883 * Keep in mind that the uninitialized child objects may be no longer available
884 * (i.e. may be deleted) after this method returns.
885 *
886 * @note Locks #childrenLock() for writing.
887 *
888 * @note May lock something else through the called children.
889 */
890void VirtualBoxBaseWithChildrenNEXT::uninitDependentChildren()
891{
892 AutoCaller autoCaller(this);
893
894 /* sanity */
895 AssertReturnVoid (autoCaller.state() == InUninit ||
896 autoCaller.state() == InInit);
897
898 AutoWriteLock chLock(childrenLock() COMMA_LOCKVAL_SRC_POS);
899
900 size_t count = mDependentChildren.size();
901
902 while (count != 0)
903 {
904 /* strongly reference the weak child from the map to make sure it won't
905 * be deleted while we've released the lock */
906 DependentChildren::iterator it = mDependentChildren.begin();
907 ComPtr<IUnknown> unk = it->first;
908 Assert(!unk.isNull());
909
910 VirtualBoxBase *child = it->second;
911
912 /* release the lock to let children stuck in removeDependentChild() go
913 * on (otherwise we'll deadlock in uninit() */
914 chLock.leave();
915
916 /* Note that if child->uninit() happens to be called on another
917 * thread right before us and is not yet finished, the second
918 * uninit() call will wait until the first one has done so
919 * (thanks to AutoUninitSpan). */
920 Assert(child);
921 if (child)
922 child->uninit();
923
924 chLock.enter();
925
926 /* uninit() is guaranteed to be done here so the child must be already
927 * deleted from the list by removeDependentChild() called from there.
928 * Do some checks to avoid endless loops when the user is forgetful */
929 -- count;
930 Assert(count == mDependentChildren.size());
931 if (count != mDependentChildren.size())
932 mDependentChildren.erase (it);
933
934 Assert(count == mDependentChildren.size());
935 }
936}
937
938/**
939 * Returns a pointer to the dependent child (registered using
940 * #addDependentChild()) corresponding to the given interface pointer or NULL if
941 * the given pointer is unrelated.
942 *
943 * The relation is checked by using the given interface pointer as a key in the
944 * map of dependent children.
945 *
946 * Note that ComPtr<IUnknown> is used as an argument instead of IUnknown * in
947 * order to guarantee IUnknown identity and disambiguation by doing
948 * QueryInterface (IUnknown) rather than a regular C cast.
949 *
950 * @param aUnk Pointer to map to the dependent child object.
951 * @return Pointer to the dependent VirtualBoxBase child object.
952 *
953 * @note Locks #childrenLock() for reading.
954 */
955VirtualBoxBase* VirtualBoxBaseWithChildrenNEXT::getDependentChild(const ComPtr<IUnknown> &aUnk)
956{
957 AssertReturn(!aUnk.isNull(), NULL);
958
959 AutoCaller autoCaller(this);
960
961 /* return NULL if uninitDependentChildren() is in action */
962 if (autoCaller.state() == InUninit)
963 return NULL;
964
965 AutoReadLock alock(childrenLock() COMMA_LOCKVAL_SRC_POS);
966
967 DependentChildren::const_iterator it = mDependentChildren.find (aUnk);
968 if (it == mDependentChildren.end())
969 return NULL;
970
971 return (*it).second;
972}
973
974/** Helper for addDependentChild(). */
975void VirtualBoxBaseWithChildrenNEXT::doAddDependentChild(IUnknown *aUnk,
976 VirtualBoxBase *aChild)
977{
978 AssertReturnVoid (aUnk != NULL);
979 AssertReturnVoid (aChild != NULL);
980
981 AutoCaller autoCaller(this);
982
983 /* sanity */
984 AssertReturnVoid (autoCaller.state() == InInit ||
985 autoCaller.state() == Ready ||
986 autoCaller.state() == Limited);
987
988 AutoWriteLock alock(childrenLock() COMMA_LOCKVAL_SRC_POS);
989
990 std::pair <DependentChildren::iterator, bool> result =
991 mDependentChildren.insert (DependentChildren::value_type (aUnk, aChild));
992 AssertMsg (result.second, ("Failed to insert child %p to the map\n", aUnk));
993}
994
995/** Helper for removeDependentChild(). */
996void VirtualBoxBaseWithChildrenNEXT::doRemoveDependentChild (IUnknown *aUnk)
997{
998 AssertReturnVoid (aUnk);
999
1000 AutoCaller autoCaller(this);
1001
1002 /* sanity */
1003 AssertReturnVoid (autoCaller.state() == InUninit ||
1004 autoCaller.state() == InInit ||
1005 autoCaller.state() == Ready ||
1006 autoCaller.state() == Limited);
1007
1008 AutoWriteLock alock(childrenLock() COMMA_LOCKVAL_SRC_POS);
1009
1010 DependentChildren::size_type result = mDependentChildren.erase (aUnk);
1011 AssertMsg (result == 1, ("Failed to remove child %p from the map\n", aUnk));
1012 NOREF (result);
1013}
1014
1015/* vi: set tabstop=4 shiftwidth=4 expandtab: */
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette