VirtualBox

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

Last change on this file since 20988 was 17911, checked in by vboxsync, 16 years ago

#3686: “Main: fix unused var warnings”

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