VirtualBox

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

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

Main/MediumImpl,VirtualBoxBase: eliminate AutoMayUninitSpan, as it leads to deadlocks in Medium::Close (lock order violation between medium tree lock and the eventmulti semaphore used in AutoCaller).

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

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