VirtualBox

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

Last change on this file since 2676 was 2672, checked in by vboxsync, 17 years ago

Main: Ported latest dmik/exp branch changes (r21219:21226) into the trunk.

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

© 2023 Oracle
ContactPrivacy policyTerms of Use