VirtualBox

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

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

Main: Added support for warning result codes and for multi-error mode (#2673).

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