VirtualBox

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

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

Main: Made it build on OS/2.

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