VirtualBox

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

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

Main: Renamed AutoLock => AutoWriteLock; AutoReaderLock => AutoReadLock.

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