VirtualBox

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

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

iprt/asm.h,*: Revised the ASMAtomic*Ptr functions and macros. The new saves lots of unsafe (void * volatile *) casts as well as adding some type safety when using GCC (typeof rulez).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 31.8 KB
Line 
1/* $Id: VirtualBoxBase.cpp 30111 2010-06-09 12:14:59Z 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.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
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 return rc;
240}
241
242/**
243 * Decreases the number of calls to this object by one.
244 *
245 * Must be called after every #addCaller() or #addLimitedCaller() when
246 * protecting the object from uninitialization is no more necessary.
247 */
248void VirtualBoxBase::releaseCaller()
249{
250 AutoWriteLock stateLock(mStateLock COMMA_LOCKVAL_SRC_POS);
251
252 if (mState == Ready || mState == Limited)
253 {
254 /* if Ready or Limited, decrease the number of callers */
255 AssertMsgReturn(mCallers != 0, ("mCallers is ZERO!"), (void) 0);
256 --mCallers;
257
258 return;
259 }
260
261 if (mState == InInit || mState == InUninit)
262 {
263 if (mStateChangeThread == RTThreadSelf())
264 {
265 /* Called from the same thread that is doing AutoInitSpan or
266 * AutoUninitSpan: just succeed */
267 return;
268 }
269
270 if (mState == InUninit)
271 {
272 /* the caller is being released after AutoUninitSpan has begun */
273 AssertMsgReturn(mCallers != 0, ("mCallers is ZERO!"), (void) 0);
274 --mCallers;
275
276 if (mCallers == 0)
277 /* inform the Auto*UninitSpan ctor there are no more callers */
278 RTSemEventSignal(mZeroCallersSem);
279
280 return;
281 }
282 }
283
284 AssertMsgFailed (("mState = %d!", mState));
285}
286
287////////////////////////////////////////////////////////////////////////////////
288//
289// AutoInitSpan methods
290//
291////////////////////////////////////////////////////////////////////////////////
292
293/**
294 * Creates a smart initialization span object that places the object to
295 * InInit state.
296 *
297 * Please see the AutoInitSpan class description for more info.
298 *
299 * @param aObj |this| pointer of the managed VirtualBoxBase object whose
300 * init() method is being called.
301 * @param aResult Default initialization result.
302 */
303AutoInitSpan::AutoInitSpan(VirtualBoxBase *aObj,
304 Result aResult /* = Failed */)
305 : mObj(aObj),
306 mResult(aResult),
307 mOk(false)
308{
309 Assert(aObj);
310
311 AutoWriteLock stateLock(mObj->mStateLock COMMA_LOCKVAL_SRC_POS);
312
313 mOk = mObj->mState == VirtualBoxBase::NotReady;
314 AssertReturnVoid (mOk);
315
316 mObj->setState(VirtualBoxBase::InInit);
317}
318
319/**
320 * Places the managed VirtualBoxBase object to Ready/Limited state if the
321 * initialization succeeded or partly succeeded, or places it to InitFailed
322 * state and calls the object's uninit() method.
323 *
324 * Please see the AutoInitSpan class description for more info.
325 */
326AutoInitSpan::~AutoInitSpan()
327{
328 /* if the state was other than NotReady, do nothing */
329 if (!mOk)
330 return;
331
332 AutoWriteLock stateLock(mObj->mStateLock COMMA_LOCKVAL_SRC_POS);
333
334 Assert(mObj->mState == VirtualBoxBase::InInit);
335
336 if (mObj->mCallers > 0)
337 {
338 Assert(mObj->mInitUninitWaiters > 0);
339
340 /* We have some pending addCaller() calls on other threads (created
341 * during InInit), signal that InInit is finished and they may go on. */
342 RTSemEventMultiSignal(mObj->mInitUninitSem);
343 }
344
345 if (mResult == Succeeded)
346 {
347 mObj->setState(VirtualBoxBase::Ready);
348 }
349 else
350 if (mResult == Limited)
351 {
352 mObj->setState(VirtualBoxBase::Limited);
353 }
354 else
355 {
356 mObj->setState(VirtualBoxBase::InitFailed);
357 /* leave the lock to prevent nesting when uninit() is called */
358 stateLock.leave();
359 /* call uninit() to let the object uninit itself after failed init() */
360 mObj->uninit();
361 /* Note: the object may no longer exist here (for example, it can call
362 * the destructor in uninit()) */
363 }
364}
365
366// AutoReinitSpan methods
367////////////////////////////////////////////////////////////////////////////////
368
369/**
370 * Creates a smart re-initialization span object and places the object to
371 * InInit state.
372 *
373 * Please see the AutoInitSpan class description for more info.
374 *
375 * @param aObj |this| pointer of the managed VirtualBoxBase object whose
376 * re-initialization method is being called.
377 */
378AutoReinitSpan::AutoReinitSpan(VirtualBoxBase *aObj)
379 : mObj(aObj),
380 mSucceeded(false),
381 mOk(false)
382{
383 Assert(aObj);
384
385 AutoWriteLock stateLock(mObj->mStateLock COMMA_LOCKVAL_SRC_POS);
386
387 mOk = mObj->mState == VirtualBoxBase::Limited;
388 AssertReturnVoid (mOk);
389
390 mObj->setState(VirtualBoxBase::InInit);
391}
392
393/**
394 * Places the managed VirtualBoxBase object to Ready state if the
395 * re-initialization succeeded (i.e. #setSucceeded() has been called) or back to
396 * Limited state otherwise.
397 *
398 * Please see the AutoInitSpan class description for more info.
399 */
400AutoReinitSpan::~AutoReinitSpan()
401{
402 /* if the state was other than Limited, do nothing */
403 if (!mOk)
404 return;
405
406 AutoWriteLock stateLock(mObj->mStateLock COMMA_LOCKVAL_SRC_POS);
407
408 Assert(mObj->mState == VirtualBoxBase::InInit);
409
410 if (mObj->mCallers > 0 && mObj->mInitUninitWaiters > 0)
411 {
412 /* We have some pending addCaller() calls on other threads (created
413 * during InInit), signal that InInit is finished and they may go on. */
414 RTSemEventMultiSignal(mObj->mInitUninitSem);
415 }
416
417 if (mSucceeded)
418 {
419 mObj->setState(VirtualBoxBase::Ready);
420 }
421 else
422 {
423 mObj->setState(VirtualBoxBase::Limited);
424 }
425}
426
427// AutoUninitSpan methods
428////////////////////////////////////////////////////////////////////////////////
429
430/**
431 * Creates a smart uninitialization span object and places this object to
432 * InUninit state.
433 *
434 * Please see the AutoInitSpan class description for more info.
435 *
436 * @note This method blocks the current thread execution until the number of
437 * callers of the managed VirtualBoxBase object drops to zero!
438 *
439 * @param aObj |this| pointer of the VirtualBoxBase object whose uninit()
440 * method is being called.
441 */
442AutoUninitSpan::AutoUninitSpan(VirtualBoxBase *aObj)
443 : mObj(aObj),
444 mInitFailed(false),
445 mUninitDone(false)
446{
447 Assert(aObj);
448
449 AutoWriteLock stateLock(mObj->mStateLock COMMA_LOCKVAL_SRC_POS);
450
451 Assert(mObj->mState != VirtualBoxBase::InInit);
452
453 /* Set mUninitDone to |true| if this object is already uninitialized
454 * (NotReady) or if another AutoUninitSpan is currently active on some
455 * other thread (InUninit). */
456 mUninitDone = mObj->mState == VirtualBoxBase::NotReady
457 || mObj->mState == VirtualBoxBase::InUninit;
458
459 if (mObj->mState == VirtualBoxBase::InitFailed)
460 {
461 /* we've been called by init() on failure */
462 mInitFailed = true;
463 }
464 else
465 {
466 if (mUninitDone)
467 {
468 /* do nothing if already uninitialized */
469 if (mObj->mState == VirtualBoxBase::NotReady)
470 return;
471
472 /* otherwise, wait until another thread finishes uninitialization.
473 * This is necessary to make sure that when this method returns, the
474 * object is NotReady and therefore can be deleted (for example).
475 * In particular, this is used by
476 * VirtualBoxBaseWithTypedChildrenNEXT::uninitDependentChildren(). */
477
478 /* lazy semaphore creation */
479 if (mObj->mInitUninitSem == NIL_RTSEMEVENTMULTI)
480 {
481 RTSemEventMultiCreate(&mObj->mInitUninitSem);
482 Assert(mObj->mInitUninitWaiters == 0);
483 }
484 ++mObj->mInitUninitWaiters;
485
486 LogFlowFunc(("{%p}: Waiting for AutoUninitSpan to finish...\n",
487 mObj));
488
489 stateLock.leave();
490 RTSemEventMultiWait(mObj->mInitUninitSem, RT_INDEFINITE_WAIT);
491 stateLock.enter();
492
493 if (--mObj->mInitUninitWaiters == 0)
494 {
495 /* destroy the semaphore since no more necessary */
496 RTSemEventMultiDestroy(mObj->mInitUninitSem);
497 mObj->mInitUninitSem = NIL_RTSEMEVENTMULTI;
498 }
499
500 return;
501 }
502 }
503
504 /* go to InUninit to prevent from adding new callers */
505 mObj->setState(VirtualBoxBase::InUninit);
506
507 /* wait for already existing callers to drop to zero */
508 if (mObj->mCallers > 0)
509 {
510 /* lazy creation */
511 Assert(mObj->mZeroCallersSem == NIL_RTSEMEVENT);
512 RTSemEventCreate(&mObj->mZeroCallersSem);
513
514 /* wait until remaining callers release the object */
515 LogFlowFunc(("{%p}: Waiting for callers (%d) to drop to zero...\n",
516 mObj, mObj->mCallers));
517
518 stateLock.leave();
519 RTSemEventWait(mObj->mZeroCallersSem, RT_INDEFINITE_WAIT);
520 }
521}
522
523/**
524 * Places the managed VirtualBoxBase object to the NotReady state.
525 */
526AutoUninitSpan::~AutoUninitSpan()
527{
528 /* do nothing if already uninitialized */
529 if (mUninitDone)
530 return;
531
532 AutoWriteLock stateLock(mObj->mStateLock COMMA_LOCKVAL_SRC_POS);
533
534 Assert(mObj->mState == VirtualBoxBase::InUninit);
535
536 mObj->setState(VirtualBoxBase::NotReady);
537}
538
539////////////////////////////////////////////////////////////////////////////////
540//
541// VirtualBoxBase
542//
543////////////////////////////////////////////////////////////////////////////////
544
545/**
546 * Translates the given text string according to the currently installed
547 * translation table and current context. The current context is determined
548 * by the context parameter. Additionally, a comment to the source text
549 * string text can be given. This comment (which is NULL by default)
550 * is helpful in situations where it is necessary to distinguish between
551 * two or more semantically different roles of the same source text in the
552 * same context.
553 *
554 * @param context the context of the translation (can be NULL
555 * to indicate the global context)
556 * @param sourceText the string to translate
557 * @param comment the comment to the string (NULL means no comment)
558 *
559 * @return
560 * the translated version of the source string in UTF-8 encoding,
561 * or the source string itself if the translation is not found
562 * in the given context.
563 */
564// static
565const char *VirtualBoxBase::translate (const char * /* context */, const char *sourceText,
566 const char * /* comment */)
567{
568#if 0
569 Log(("VirtualBoxBase::translate:\n"
570 " context={%s}\n"
571 " sourceT={%s}\n"
572 " comment={%s}\n",
573 context, sourceText, comment));
574#endif
575
576 /// @todo (dmik) incorporate Qt translation file parsing and lookup
577 return sourceText;
578}
579
580////////////////////////////////////////////////////////////////////////////////
581//
582// VirtualBoxSupportTranslationBase
583//
584////////////////////////////////////////////////////////////////////////////////
585
586/**
587 * Modifies the given argument so that it will contain only a class name
588 * (null-terminated). The argument must point to a <b>non-constant</b>
589 * string containing a valid value, as it is generated by the
590 * __PRETTY_FUNCTION__ built-in macro of the GCC compiler, or by the
591 * __FUNCTION__ macro of any other compiler.
592 *
593 * The function assumes that the macro is used within the member of the
594 * class derived from the VirtualBoxSupportTranslation<> template.
595 *
596 * @param prettyFunctionName string to modify
597 * @return
598 * true on success and false otherwise
599 */
600bool VirtualBoxSupportTranslationBase::cutClassNameFrom__PRETTY_FUNCTION__ (char *fn)
601{
602 Assert(fn);
603 if (!fn)
604 return false;
605
606#if defined (__GNUC__)
607
608 // the format is like:
609 // VirtualBoxSupportTranslation<C>::VirtualBoxSupportTranslation() [with C = VirtualBox]
610
611 #define START " = "
612 #define END "]"
613
614#elif defined (_MSC_VER)
615
616 // the format is like:
617 // VirtualBoxSupportTranslation<class VirtualBox>::__ctor
618
619 #define START "<class "
620 #define END ">::"
621
622#endif
623
624 char *start = strstr(fn, START);
625 Assert(start);
626 if (start)
627 {
628 start += sizeof(START) - 1;
629 char *end = strstr(start, END);
630 Assert(end && (end > start));
631 if (end && (end > start))
632 {
633 size_t len = end - start;
634 memmove(fn, start, len);
635 fn[len] = 0;
636 return true;
637 }
638 }
639
640 #undef END
641 #undef START
642
643 return false;
644}
645
646////////////////////////////////////////////////////////////////////////////////
647//
648// VirtualBoxSupportErrorInfoImplBase
649//
650////////////////////////////////////////////////////////////////////////////////
651
652RTTLS VirtualBoxSupportErrorInfoImplBase::MultiResult::sCounter = NIL_RTTLS;
653
654void VirtualBoxSupportErrorInfoImplBase::MultiResult::init()
655{
656 if (sCounter == NIL_RTTLS)
657 {
658 sCounter = RTTlsAlloc();
659 AssertReturnVoid (sCounter != NIL_RTTLS);
660 }
661
662 uintptr_t counter = (uintptr_t) RTTlsGet (sCounter);
663 ++ counter;
664 RTTlsSet (sCounter, (void *) counter);
665}
666
667VirtualBoxSupportErrorInfoImplBase::MultiResult::~MultiResult()
668{
669 uintptr_t counter = (uintptr_t) RTTlsGet (sCounter);
670 AssertReturnVoid (counter != 0);
671 -- counter;
672 RTTlsSet (sCounter, (void *) counter);
673}
674
675/**
676 * Sets error info for the current thread. This is an internal function that
677 * gets eventually called by all public variants. If @a aWarning is
678 * @c true, then the highest (31) bit in the @a aResultCode value which
679 * indicates the error severity is reset to zero to make sure the receiver will
680 * recognize that the created error info object represents a warning rather
681 * than an error.
682 */
683/* static */
684HRESULT VirtualBoxSupportErrorInfoImplBase::setErrorInternal(HRESULT aResultCode,
685 const GUID &aIID,
686 const wchar_t *aComponent,
687 const Bstr &aText,
688 bool aWarning,
689 bool aLogIt)
690{
691 /* whether multi-error mode is turned on */
692 bool preserve = ((uintptr_t)RTTlsGet(MultiResult::sCounter)) > 0;
693
694 Bstr bstrComponent((CBSTR)aComponent);
695
696 if (aLogIt)
697 LogRel(("ERROR [COM]: aRC=%Rhrc (%#08x) aIID={%RTuuid} aComponent={%ls} aText={%ls} "
698 "aWarning=%RTbool, preserve=%RTbool\n",
699 aResultCode, aResultCode, &aIID, bstrComponent.raw(), aText.raw(), aWarning,
700 preserve));
701
702 /* these are mandatory, others -- not */
703 AssertReturn((!aWarning && FAILED(aResultCode)) ||
704 (aWarning && aResultCode != S_OK),
705 E_FAIL);
706 AssertReturn(!aText.isEmpty(), E_FAIL);
707
708 /* reset the error severity bit if it's a warning */
709 if (aWarning)
710 aResultCode &= ~0x80000000;
711
712 HRESULT rc = S_OK;
713
714 do
715 {
716 ComObjPtr<VirtualBoxErrorInfo> info;
717 rc = info.createObject();
718 if (FAILED(rc)) break;
719
720#if !defined (VBOX_WITH_XPCOM)
721
722 ComPtr<IVirtualBoxErrorInfo> curInfo;
723 if (preserve)
724 {
725 /* get the current error info if any */
726 ComPtr<IErrorInfo> err;
727 rc = ::GetErrorInfo (0, err.asOutParam());
728 if (FAILED(rc)) break;
729 rc = err.queryInterfaceTo(curInfo.asOutParam());
730 if (FAILED(rc))
731 {
732 /* create a IVirtualBoxErrorInfo wrapper for the native
733 * IErrorInfo object */
734 ComObjPtr<VirtualBoxErrorInfo> wrapper;
735 rc = wrapper.createObject();
736 if (SUCCEEDED(rc))
737 {
738 rc = wrapper->init (err);
739 if (SUCCEEDED(rc))
740 curInfo = wrapper;
741 }
742 }
743 }
744 /* On failure, curInfo will stay null */
745 Assert(SUCCEEDED(rc) || curInfo.isNull());
746
747 /* set the current error info and preserve the previous one if any */
748 rc = info->init(aResultCode, aIID, bstrComponent, aText, curInfo);
749 if (FAILED(rc)) break;
750
751 ComPtr<IErrorInfo> err;
752 rc = info.queryInterfaceTo(err.asOutParam());
753 if (SUCCEEDED(rc))
754 rc = ::SetErrorInfo (0, err);
755
756#else // !defined (VBOX_WITH_XPCOM)
757
758 nsCOMPtr <nsIExceptionService> es;
759 es = do_GetService (NS_EXCEPTIONSERVICE_CONTRACTID, &rc);
760 if (NS_SUCCEEDED(rc))
761 {
762 nsCOMPtr <nsIExceptionManager> em;
763 rc = es->GetCurrentExceptionManager (getter_AddRefs (em));
764 if (FAILED(rc)) break;
765
766 ComPtr<IVirtualBoxErrorInfo> curInfo;
767 if (preserve)
768 {
769 /* get the current error info if any */
770 ComPtr<nsIException> ex;
771 rc = em->GetCurrentException (ex.asOutParam());
772 if (FAILED(rc)) break;
773 rc = ex.queryInterfaceTo(curInfo.asOutParam());
774 if (FAILED(rc))
775 {
776 /* create a IVirtualBoxErrorInfo wrapper for the native
777 * nsIException object */
778 ComObjPtr<VirtualBoxErrorInfo> wrapper;
779 rc = wrapper.createObject();
780 if (SUCCEEDED(rc))
781 {
782 rc = wrapper->init (ex);
783 if (SUCCEEDED(rc))
784 curInfo = wrapper;
785 }
786 }
787 }
788 /* On failure, curInfo will stay null */
789 Assert(SUCCEEDED(rc) || curInfo.isNull());
790
791 /* set the current error info and preserve the previous one if any */
792 rc = info->init(aResultCode, aIID, bstrComponent, aText, curInfo);
793 if (FAILED(rc)) break;
794
795 ComPtr<nsIException> ex;
796 rc = info.queryInterfaceTo(ex.asOutParam());
797 if (SUCCEEDED(rc))
798 rc = em->SetCurrentException (ex);
799 }
800 else if (rc == NS_ERROR_UNEXPECTED)
801 {
802 /*
803 * It is possible that setError() is being called by the object
804 * after the XPCOM shutdown sequence has been initiated
805 * (for example, when XPCOM releases all instances it internally
806 * references, which can cause object's FinalConstruct() and then
807 * uninit()). In this case, do_GetService() above will return
808 * NS_ERROR_UNEXPECTED and it doesn't actually make sense to
809 * set the exception (nobody will be able to read it).
810 */
811 LogWarningFunc (("Will not set an exception because "
812 "nsIExceptionService is not available "
813 "(NS_ERROR_UNEXPECTED). "
814 "XPCOM is being shutdown?\n"));
815 rc = NS_OK;
816 }
817
818#endif // !defined (VBOX_WITH_XPCOM)
819 }
820 while (0);
821
822 AssertComRC (rc);
823
824 return SUCCEEDED(rc) ? aResultCode : rc;
825}
826
827
828/**
829 * Uninitializes all dependent children registered on this object with
830 * #addDependentChild().
831 *
832 * Must be called from within the AutoUninitSpan (i.e.
833 * typically from this object's uninit() method) to uninitialize children
834 * before this object goes out of service and becomes unusable.
835 *
836 * Note that this method will call uninit() methods of child objects. If
837 * these methods need to call the parent object during uninitialization,
838 * #uninitDependentChildren() must be called before the relevant part of the
839 * parent is uninitialized: usually at the begnning of the parent
840 * uninitialization sequence.
841 *
842 * Keep in mind that the uninitialized child objects may be no longer available
843 * (i.e. may be deleted) after this method returns.
844 *
845 * @note Locks #childrenLock() for writing.
846 *
847 * @note May lock something else through the called children.
848 */
849void VirtualBoxBaseWithChildrenNEXT::uninitDependentChildren()
850{
851 AutoCaller autoCaller(this);
852
853 /* sanity */
854 AssertReturnVoid (autoCaller.state() == InUninit ||
855 autoCaller.state() == InInit);
856
857 AutoWriteLock chLock(childrenLock() COMMA_LOCKVAL_SRC_POS);
858
859 size_t count = mDependentChildren.size();
860
861 while (count != 0)
862 {
863 /* strongly reference the weak child from the map to make sure it won't
864 * be deleted while we've released the lock */
865 DependentChildren::iterator it = mDependentChildren.begin();
866 ComPtr<IUnknown> unk = it->first;
867 Assert(!unk.isNull());
868
869 VirtualBoxBase *child = it->second;
870
871 /* release the lock to let children stuck in removeDependentChild() go
872 * on (otherwise we'll deadlock in uninit() */
873 chLock.leave();
874
875 /* Note that if child->uninit() happens to be called on another
876 * thread right before us and is not yet finished, the second
877 * uninit() call will wait until the first one has done so
878 * (thanks to AutoUninitSpan). */
879 Assert(child);
880 if (child)
881 child->uninit();
882
883 chLock.enter();
884
885 /* uninit() is guaranteed to be done here so the child must be already
886 * deleted from the list by removeDependentChild() called from there.
887 * Do some checks to avoid endless loops when the user is forgetful */
888 -- count;
889 Assert(count == mDependentChildren.size());
890 if (count != mDependentChildren.size())
891 mDependentChildren.erase (it);
892
893 Assert(count == mDependentChildren.size());
894 }
895}
896
897/**
898 * Returns a pointer to the dependent child (registered using
899 * #addDependentChild()) corresponding to the given interface pointer or NULL if
900 * the given pointer is unrelated.
901 *
902 * The relation is checked by using the given interface pointer as a key in the
903 * map of dependent children.
904 *
905 * Note that ComPtr<IUnknown> is used as an argument instead of IUnknown * in
906 * order to guarantee IUnknown identity and disambiguation by doing
907 * QueryInterface (IUnknown) rather than a regular C cast.
908 *
909 * @param aUnk Pointer to map to the dependent child object.
910 * @return Pointer to the dependent VirtualBoxBase child object.
911 *
912 * @note Locks #childrenLock() for reading.
913 */
914VirtualBoxBase* VirtualBoxBaseWithChildrenNEXT::getDependentChild(const ComPtr<IUnknown> &aUnk)
915{
916 AssertReturn(!aUnk.isNull(), NULL);
917
918 AutoCaller autoCaller(this);
919
920 /* return NULL if uninitDependentChildren() is in action */
921 if (autoCaller.state() == InUninit)
922 return NULL;
923
924 AutoReadLock alock(childrenLock() COMMA_LOCKVAL_SRC_POS);
925
926 DependentChildren::const_iterator it = mDependentChildren.find (aUnk);
927 if (it == mDependentChildren.end())
928 return NULL;
929
930 return (*it).second;
931}
932
933/** Helper for addDependentChild(). */
934void VirtualBoxBaseWithChildrenNEXT::doAddDependentChild(IUnknown *aUnk,
935 VirtualBoxBase *aChild)
936{
937 AssertReturnVoid (aUnk != NULL);
938 AssertReturnVoid (aChild != NULL);
939
940 AutoCaller autoCaller(this);
941
942 /* sanity */
943 AssertReturnVoid (autoCaller.state() == InInit ||
944 autoCaller.state() == Ready ||
945 autoCaller.state() == Limited);
946
947 AutoWriteLock alock(childrenLock() COMMA_LOCKVAL_SRC_POS);
948
949 std::pair <DependentChildren::iterator, bool> result =
950 mDependentChildren.insert (DependentChildren::value_type (aUnk, aChild));
951 AssertMsg (result.second, ("Failed to insert child %p to the map\n", aUnk));
952}
953
954/** Helper for removeDependentChild(). */
955void VirtualBoxBaseWithChildrenNEXT::doRemoveDependentChild (IUnknown *aUnk)
956{
957 AssertReturnVoid (aUnk);
958
959 AutoCaller autoCaller(this);
960
961 /* sanity */
962 AssertReturnVoid (autoCaller.state() == InUninit ||
963 autoCaller.state() == InInit ||
964 autoCaller.state() == Ready ||
965 autoCaller.state() == Limited);
966
967 AutoWriteLock alock(childrenLock() COMMA_LOCKVAL_SRC_POS);
968
969 DependentChildren::size_type result = mDependentChildren.erase (aUnk);
970 AssertMsg (result == 1, ("Failed to remove child %p from the map\n", aUnk));
971 NOREF (result);
972}
973
974/* 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