VirtualBox

source: vbox/trunk/src/VBox/Main/SessionImpl.cpp@ 3480

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

Main: Use named mutexes for watching client processes on OS/2.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 28.0 KB
Line 
1/** @file
2 *
3 * VBox Client Session COM Class implementation
4 */
5
6/*
7 * Copyright (C) 2006-2007 innotek GmbH
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License as published by the Free Software Foundation,
13 * in version 2 as it comes in the "COPYING" file of the VirtualBox OSE
14 * distribution. VirtualBox OSE is distributed in the hope that it will
15 * be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * If you received this file as part of a commercial VirtualBox
18 * distribution, then only the terms of your commercial VirtualBox
19 * license agreement apply instead of the previous paragraph.
20 */
21
22#if defined(__WIN__)
23#elif defined(__LINUX__)
24#endif
25
26#ifdef VBOX_WITH_SYS_V_IPC_SESSION_WATCHER
27# include <errno.h>
28# include <sys/types.h>
29# include <sys/stat.h>
30# include <sys/ipc.h>
31# include <sys/sem.h>
32#endif
33
34#include "SessionImpl.h"
35#include "ConsoleImpl.h"
36
37#include "Logging.h"
38
39#include <VBox/err.h>
40#include <iprt/process.h>
41
42#if defined(__WIN__) || defined (__OS2__)
43/** VM IPC mutex holder thread */
44static DECLCALLBACK(int) IPCMutexHolderThread (RTTHREAD Thread, void *pvUser);
45#endif
46
47/**
48 * Local macro to check whether the session is open and return an error if not.
49 * @note Don't forget to do |Auto[Reader]Lock alock (this);| before using this
50 * macro.
51 */
52#define CHECK_OPEN() \
53 do { \
54 if (mState != SessionState_SessionOpen) \
55 return setError (E_UNEXPECTED, \
56 tr ("The session is not open")); \
57 } while (0)
58
59// constructor / destructor
60/////////////////////////////////////////////////////////////////////////////
61
62HRESULT Session::FinalConstruct()
63{
64 LogFlowThisFunc (("\n"));
65
66 return init();
67}
68
69void Session::FinalRelease()
70{
71 LogFlowThisFunc (("\n"));
72
73 uninit (true /* aFinalRelease */);
74}
75
76// public initializer/uninitializer for internal purposes only
77/////////////////////////////////////////////////////////////////////////////
78
79/**
80 * Initializes the Session object.
81 */
82HRESULT Session::init()
83{
84 /* Enclose the state transition NotReady->InInit->Ready */
85 AutoInitSpan autoInitSpan (this);
86 AssertReturn (autoInitSpan.isOk(), E_UNEXPECTED);
87
88 LogFlowThisFuncEnter();
89
90 mState = SessionState_SessionClosed;
91 mType = SessionType_InvalidSessionType;
92
93#if defined(__WIN__)
94 mIPCSem = NULL;
95 mIPCThreadSem = NULL;
96#elif defined(__OS2__)
97 mIPCThread = NIL_RTTHREAD;
98 mIPCThreadSem = NIL_RTSEMEVENT;
99#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
100 mIPCSem = -1;
101#else
102# error "Port me!"
103#endif
104
105 /* Confirm a successful initialization when it's the case */
106 autoInitSpan.setSucceeded();
107
108 LogFlowThisFuncLeave();
109
110 return S_OK;
111}
112
113/**
114 * Uninitializes the Session object.
115 *
116 * @note Locks this object for writing.
117 */
118void Session::uninit (bool aFinalRelease)
119{
120 LogFlowThisFuncEnter();
121 LogFlowThisFunc (("aFinalRelease=%d\n", aFinalRelease));
122
123 /* Enclose the state transition Ready->InUninit->NotReady */
124 AutoUninitSpan autoUninitSpan (this);
125 if (autoUninitSpan.uninitDone())
126 {
127 LogFlowThisFunc (("Already uninitialized.\n"));
128 LogFlowThisFuncLeave();
129 return;
130 }
131
132 AutoLock alock (this);
133
134 if (mState != SessionState_SessionClosed)
135 {
136 Assert (mState == SessionState_SessionOpen ||
137 mState == SessionState_SessionSpawning);
138
139 HRESULT rc = close (aFinalRelease, false /* aFromServer */);
140 AssertComRC (rc);
141 }
142
143 LogFlowThisFuncLeave();
144}
145
146// ISession properties
147/////////////////////////////////////////////////////////////////////////////
148
149STDMETHODIMP Session::COMGETTER(State) (SessionState_T *aState)
150{
151 if (!aState)
152 return E_POINTER;
153
154 AutoCaller autoCaller (this);
155 CheckComRCReturnRC (autoCaller.rc());
156
157 AutoReaderLock alock (this);
158
159 *aState = mState;
160
161 return S_OK;
162}
163
164STDMETHODIMP Session::COMGETTER(Type) (SessionType_T *aType)
165{
166 if (!aType)
167 return E_POINTER;
168
169 AutoCaller autoCaller (this);
170 CheckComRCReturnRC (autoCaller.rc());
171
172 AutoReaderLock alock (this);
173
174 CHECK_OPEN();
175
176 *aType = mType;
177 return S_OK;
178}
179
180STDMETHODIMP Session::COMGETTER(Machine) (IMachine **aMachine)
181{
182 if (!aMachine)
183 return E_POINTER;
184
185 AutoCaller autoCaller (this);
186 CheckComRCReturnRC (autoCaller.rc());
187
188 AutoReaderLock alock (this);
189
190 CHECK_OPEN();
191
192 HRESULT rc = E_FAIL;
193
194 if (mConsole)
195 rc = mConsole->machine().queryInterfaceTo (aMachine);
196 else
197 rc = mRemoteMachine.queryInterfaceTo (aMachine);
198 ComAssertComRC (rc);
199
200 return rc;
201}
202
203STDMETHODIMP Session::COMGETTER(Console) (IConsole **aConsole)
204{
205 if (!aConsole)
206 return E_POINTER;
207
208 AutoCaller autoCaller (this);
209 CheckComRCReturnRC (autoCaller.rc());
210
211 AutoReaderLock alock (this);
212
213 CHECK_OPEN();
214
215 HRESULT rc = E_FAIL;
216
217 if (mConsole)
218 rc = mConsole.queryInterfaceTo (aConsole);
219 else
220 rc = mRemoteConsole.queryInterfaceTo (aConsole);
221 ComAssertComRC (rc);
222
223 return rc;
224}
225
226// ISession methods
227/////////////////////////////////////////////////////////////////////////////
228
229STDMETHODIMP Session::Close()
230{
231 LogFlowThisFunc (("mState=%d, mType=%d\n", mState, mType));
232
233 AutoCaller autoCaller (this);
234 CheckComRCReturnRC (autoCaller.rc());
235
236 /* close() needs write lock */
237 AutoLock alock (this);
238
239 CHECK_OPEN();
240
241 return close (false /* aFinalRelease */, false /* aFromServer */);
242}
243
244// IInternalSessionControl methods
245/////////////////////////////////////////////////////////////////////////////
246
247STDMETHODIMP Session::GetPID (ULONG *aPid)
248{
249 AssertReturn (aPid, E_POINTER);
250
251 AutoCaller autoCaller (this);
252 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
253
254 AutoReaderLock alock (this);
255
256 *aPid = (ULONG) RTProcSelf();
257 AssertCompile (sizeof (*aPid) == sizeof (RTPROCESS));
258
259 return S_OK;
260}
261
262STDMETHODIMP Session::GetRemoteConsole (IConsole **aConsole)
263{
264 AssertReturn (aConsole, E_POINTER);
265
266 AutoCaller autoCaller (this);
267 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
268
269 AutoReaderLock alock (this);
270
271 AssertReturn (mState == SessionState_SessionOpen, E_FAIL);
272
273 AssertMsgReturn (mType == SessionType_DirectSession && !!mConsole,
274 ("This is not a direct session!\n"), E_FAIL);
275
276 mConsole.queryInterfaceTo (aConsole);
277
278 return S_OK;
279}
280
281STDMETHODIMP Session::AssignMachine (IMachine *aMachine)
282{
283 LogFlowThisFuncEnter();
284 LogFlowThisFunc (("aMachine=%p\n", aMachine));
285
286 AutoCaller autoCaller (this);
287 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
288
289 AutoLock alock (this);
290
291 AssertReturn (mState == SessionState_SessionClosed, E_FAIL);
292
293 if (!aMachine)
294 {
295 /*
296 * A special case: the server informs us that this session has been
297 * passed to IVirtualBox::OpenRemoteSession() so this session will
298 * become remote (but not existing) when AssignRemoteMachine() is
299 * called.
300 */
301
302 AssertReturn (mType == SessionType_InvalidSessionType, E_FAIL);
303 mType = SessionType_RemoteSession;
304 mState = SessionState_SessionSpawning;
305
306 LogFlowThisFuncLeave();
307 return S_OK;
308 }
309
310 HRESULT rc = E_FAIL;
311
312 /* query IInternalMachineControl interface */
313 mControl = aMachine;
314 AssertReturn (!!mControl, E_FAIL);
315
316 rc = mConsole.createObject();
317 AssertComRCReturn (rc, rc);
318
319 rc = mConsole->init (aMachine, mControl);
320 AssertComRCReturn (rc, rc);
321
322 rc = grabIPCSemaphore();
323
324 /*
325 * Reference the VirtualBox object to ensure the server is up
326 * until the session is closed
327 */
328 if (SUCCEEDED (rc))
329 rc = aMachine->COMGETTER(Parent) (mVirtualBox.asOutParam());
330
331 if (SUCCEEDED (rc))
332 {
333 mType = SessionType_DirectSession;
334 mState = SessionState_SessionOpen;
335 }
336 else
337 {
338 /* some cleanup */
339 mControl.setNull();
340 mConsole->uninit();
341 mConsole.setNull();
342 }
343
344 LogFlowThisFunc (("rc=%08X\n", rc));
345 LogFlowThisFuncLeave();
346
347 return rc;
348}
349
350STDMETHODIMP Session::AssignRemoteMachine (IMachine *aMachine, IConsole *aConsole)
351{
352 LogFlowThisFuncEnter();
353 LogFlowThisFunc (("aMachine=%p, aConsole=%p\n", aMachine, aConsole));
354
355 AssertReturn (aMachine && aConsole, E_INVALIDARG);
356
357 AutoCaller autoCaller (this);
358 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
359
360 AutoLock alock (this);
361
362 AssertReturn (mState == SessionState_SessionClosed ||
363 mState == SessionState_SessionSpawning, E_FAIL);
364
365 HRESULT rc = E_FAIL;
366
367 /* query IInternalMachineControl interface */
368 mControl = aMachine;
369 AssertReturn (!!mControl, E_FAIL);
370
371 /// @todo (dmik)
372 // currently, the remote session returns the same machine and
373 // console objects as the direct session, thus giving the
374 // (remote) client full control over the direct session. For the
375 // console, it is the desired behavior (the ability to control
376 // VM execution is a must for the remote session). What about
377 // the machine object, we may want to prevent the remote client
378 // from modifying machine data. In this case, we must:
379 // 1) assign the Machine object (instead of the SessionMachine
380 // object that is passed to this method) to mRemoteMachine;
381 // 2) remove GetMachine() property from the IConsole interface
382 // because it always returns the SessionMachine object
383 // (alternatively, we can supply a separate IConsole
384 // implementation that will return the Machine object in
385 // response to GetMachine()).
386
387 mRemoteMachine = aMachine;
388 mRemoteConsole = aConsole;
389
390 /*
391 * Reference the VirtualBox object to ensure the server is up
392 * until the session is closed
393 */
394 rc = aMachine->COMGETTER(Parent) (mVirtualBox.asOutParam());
395
396 if (SUCCEEDED (rc))
397 {
398 /*
399 * RemoteSession type can be already set by AssignMachine() when its
400 * argument is NULL (a special case)
401 */
402 if (mType != SessionType_RemoteSession)
403 mType = SessionType_ExistingSession;
404 else
405 Assert (mState == SessionState_SessionSpawning);
406
407 mState = SessionState_SessionOpen;
408 }
409 else
410 {
411 /* some cleanup */
412 mControl.setNull();
413 mRemoteMachine.setNull();
414 mRemoteConsole.setNull();
415 }
416
417 LogFlowThisFunc (("rc=%08X\n", rc));
418 LogFlowThisFuncLeave();
419
420 return rc;
421}
422
423STDMETHODIMP Session::UpdateMachineState (MachineState_T aMachineState)
424{
425 AutoCaller autoCaller (this);
426
427 if (autoCaller.state() != Ready)
428 {
429 /*
430 * We might have already entered Session::uninit() at this point, so
431 * return silently (not interested in the state change during uninit)
432 */
433 LogFlowThisFunc (("Already uninitialized.\n"));
434 return S_OK;
435 }
436
437 AutoReaderLock alock (this);
438
439 if (mState == SessionState_SessionClosing)
440 {
441 LogFlowThisFunc (("Already being closed.\n"));
442 return S_OK;
443 }
444
445 AssertReturn (mState == SessionState_SessionOpen &&
446 mType == SessionType_DirectSession, E_FAIL);
447
448 AssertReturn (!mControl.isNull(), E_FAIL);
449 AssertReturn (!mConsole.isNull(), E_FAIL);
450
451 return mConsole->updateMachineState (aMachineState);
452}
453
454STDMETHODIMP Session::Uninitialize()
455{
456 LogFlowThisFuncEnter();
457
458 AutoCaller autoCaller (this);
459
460 HRESULT rc = S_OK;
461
462 if (autoCaller.state() == Ready)
463 {
464 AutoReaderLock alock (this);
465
466 LogFlowThisFunc (("mState=%d, mType=%d\n", mState, mType));
467
468 if (mState == SessionState_SessionClosing)
469 {
470 LogFlowThisFunc (("Already being closed.\n"));
471 return S_OK;
472 }
473
474 AssertReturn (mState == SessionState_SessionOpen, E_FAIL);
475
476 /* close ourselves */
477 rc = close (false /* aFinalRelease */, true /* aFromServer */);
478 }
479 else if (autoCaller.state() == InUninit)
480 {
481 /*
482 * We might have already entered Session::uninit() at this point,
483 * return silently
484 */
485 LogFlowThisFunc (("Already uninitialized.\n"));
486 }
487 else
488 {
489 LogWarningThisFunc (("UNEXPECTED uninitialization!\n"));
490 rc = autoCaller.rc();
491 }
492
493 LogFlowThisFunc (("rc=%08X\n", rc));
494 LogFlowThisFuncLeave();
495
496 return rc;
497}
498
499STDMETHODIMP Session::OnDVDDriveChange()
500{
501 LogFlowThisFunc (("\n"));
502
503 AutoCaller autoCaller (this);
504 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
505
506 AutoReaderLock alock (this);
507 AssertReturn (mState == SessionState_SessionOpen &&
508 mType == SessionType_DirectSession, E_FAIL);
509
510 return mConsole->onDVDDriveChange();
511}
512
513STDMETHODIMP Session::OnFloppyDriveChange()
514{
515 LogFlowThisFunc (("\n"));
516
517 AutoCaller autoCaller (this);
518 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
519
520 AutoReaderLock alock (this);
521 AssertReturn (mState == SessionState_SessionOpen &&
522 mType == SessionType_DirectSession, E_FAIL);
523
524 return mConsole->onFloppyDriveChange();
525}
526
527STDMETHODIMP Session::OnNetworkAdapterChange(INetworkAdapter *networkAdapter)
528{
529 LogFlowThisFunc (("\n"));
530
531 AutoCaller autoCaller (this);
532 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
533
534 AutoReaderLock alock (this);
535 AssertReturn (mState == SessionState_SessionOpen &&
536 mType == SessionType_DirectSession, E_FAIL);
537
538 return mConsole->onNetworkAdapterChange(networkAdapter);
539}
540
541STDMETHODIMP Session::OnVRDPServerChange()
542{
543 LogFlowThisFunc (("\n"));
544
545 AutoCaller autoCaller (this);
546 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
547
548 AutoReaderLock alock (this);
549 AssertReturn (mState == SessionState_SessionOpen &&
550 mType == SessionType_DirectSession, E_FAIL);
551
552 return mConsole->onVRDPServerChange();
553}
554
555STDMETHODIMP Session::OnUSBControllerChange()
556{
557 LogFlowThisFunc (("\n"));
558
559 AutoCaller autoCaller (this);
560 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
561
562 AutoReaderLock alock (this);
563 AssertReturn (mState == SessionState_SessionOpen &&
564 mType == SessionType_DirectSession, E_FAIL);
565
566 return mConsole->onUSBControllerChange();
567}
568
569STDMETHODIMP Session::OnUSBDeviceAttach (IUSBDevice *aDevice,
570 IVirtualBoxErrorInfo *aError)
571{
572 LogFlowThisFunc (("\n"));
573
574 AutoCaller autoCaller (this);
575 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
576
577 AutoReaderLock alock (this);
578 AssertReturn (mState == SessionState_SessionOpen &&
579 mType == SessionType_DirectSession, E_FAIL);
580
581 return mConsole->onUSBDeviceAttach (aDevice, aError);
582}
583
584STDMETHODIMP Session::OnUSBDeviceDetach (INPTR GUIDPARAM aId,
585 IVirtualBoxErrorInfo *aError)
586{
587 LogFlowThisFunc (("\n"));
588
589 AutoCaller autoCaller (this);
590 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
591
592 AutoReaderLock alock (this);
593 AssertReturn (mState == SessionState_SessionOpen &&
594 mType == SessionType_DirectSession, E_FAIL);
595
596 return mConsole->onUSBDeviceDetach (aId, aError);
597}
598
599STDMETHODIMP Session::OnShowWindow (BOOL aCheck, BOOL *aCanShow, ULONG64 *aWinId)
600{
601 AutoCaller autoCaller (this);
602 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
603
604 AutoReaderLock alock (this);
605 AssertReturn (mState == SessionState_SessionOpen &&
606 mType == SessionType_DirectSession, E_FAIL);
607
608 return mConsole->onShowWindow (aCheck, aCanShow, aWinId);
609}
610
611// private methods
612///////////////////////////////////////////////////////////////////////////////
613
614/**
615 * Closes the current session.
616 *
617 * @param aFinalRelease called as a result of FinalRelease()
618 * @param aFromServer called as a result of Uninitialize()
619 *
620 * @note To be called only from #uninit(), #Close() or #Uninitialize().
621 * @note Locks this object for writing.
622 */
623HRESULT Session::close (bool aFinalRelease, bool aFromServer)
624{
625 LogFlowThisFuncEnter();
626 LogFlowThisFunc (("aFinalRelease=%d, isFromServer=%d\n",
627 aFinalRelease, aFromServer));
628
629 AutoCaller autoCaller (this);
630 AssertComRCReturnRC (autoCaller.rc());
631
632 AutoLock alock (this);
633
634 LogFlowThisFunc (("mState=%d, mType=%d\n", mState, mType));
635
636 if (mState != SessionState_SessionOpen)
637 {
638 Assert (mState == SessionState_SessionSpawning);
639
640 /* The session object is going to be uninitialized by the client before
641 * it has been assigned a direct console of the machine the client
642 * requested to open a remote session to using IVirtualBox::
643 * openRemoteSession(). Theoretically it should not happen because
644 * openRemoteSession() doesn't return control to the client until the
645 * procedure is fully complete, so assert here. */
646 AssertFailed();
647
648 mState = SessionState_SessionClosed;
649 mType = SessionType_InvalidSessionType;
650#if defined(__WIN__)
651 Assert (!mIPCSem && !mIPCThreadSem);
652#elif defined(__OS2__)
653 Assert (mIPCThread == NIL_RTTHREAD &&
654 mIPCThreadSem == NIL_RTSEMEVENT);
655#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
656 Assert (mIPCSem == -1);
657#else
658# error "Port me!"
659#endif
660 LogFlowThisFuncLeave();
661 return S_OK;
662 }
663
664 /* go to the closing state */
665 mState = SessionState_SessionClosing;
666
667 if (mType == SessionType_DirectSession)
668 {
669 mConsole->uninit();
670 mConsole.setNull();
671 }
672 else
673 {
674 mRemoteMachine.setNull();
675 mRemoteConsole.setNull();
676 }
677
678 ComPtr <IProgress> progress;
679
680 if (!aFinalRelease && !aFromServer)
681 {
682 /*
683 * We trigger OnSessionEnd() only when the session closes itself using
684 * Close(). Note that if isFinalRelease = TRUE here, this means that
685 * the client process has already initialized the termination procedure
686 * without issuing Close() and the IPC channel is no more operational --
687 * so we cannot call the server's method (it will definitely fail). The
688 * server will instead simply detect the abnormal client death (since
689 * OnSessionEnd() is not called) and reset the machine state to Aborted.
690 */
691
692 /*
693 * while waiting for OnSessionEnd() to complete one of our methods
694 * can be called by the server (for example, Uninitialize(), if the
695 * direct session has initiated a closure just a bit before us) so
696 * we need to release the lock to avoid deadlocks. The state is already
697 * SessionState_SessionClosing here, so it's safe.
698 */
699 alock.leave();
700
701 LogFlowThisFunc (("Calling mControl->OnSessionEnd()...\n"));
702 HRESULT rc = mControl->OnSessionEnd (this, progress.asOutParam());
703 LogFlowThisFunc (("mControl->OnSessionEnd()=%08X\n", rc));
704
705 alock.enter();
706
707 /*
708 * If we get E_UNEXPECTED this means that the direct session has already
709 * been closed, we're just too late with our notification and nothing more
710 */
711 if (mType != SessionType_DirectSession && rc == E_UNEXPECTED)
712 rc = S_OK;
713
714 AssertComRC (rc);
715 }
716
717 mControl.setNull();
718
719 if (mType == SessionType_DirectSession)
720 {
721 releaseIPCSemaphore();
722 if (!aFinalRelease && !aFromServer)
723 {
724 /*
725 * Wait for the server to grab the semaphore and destroy the session
726 * machine (allowing us to open a new session with the same machine
727 * once this method returns)
728 */
729 Assert (!!progress);
730 if (progress)
731 progress->WaitForCompletion (-1);
732 }
733 }
734
735 mState = SessionState_SessionClosed;
736 mType = SessionType_InvalidSessionType;
737
738 /* release the VirtualBox instance as the very last step */
739 mVirtualBox.setNull();
740
741 LogFlowThisFuncLeave();
742 return S_OK;
743}
744
745/** @note To be called only from #AssignMachine() */
746HRESULT Session::grabIPCSemaphore()
747{
748 HRESULT rc = E_FAIL;
749
750 /* open the IPC semaphore based on the sessionId and try to grab it */
751 Bstr ipcId;
752 rc = mControl->GetIPCId (ipcId.asOutParam());
753 AssertComRCReturnRC (rc);
754
755 LogFlowThisFunc (("ipcId='%ls'\n", ipcId.raw()));
756
757#if defined(__WIN__)
758
759 /*
760 * Since Session is an MTA object, this method can be executed on
761 * any thread, and this thread will not necessarily match the thread on
762 * which close() will be called later. Therefore, we need a separate
763 * thread to hold the IPC mutex and then release it in close().
764 */
765
766 mIPCThreadSem = ::CreateEvent (NULL, FALSE, FALSE, NULL);
767 AssertMsgReturn (mIPCThreadSem,
768 ("Cannot create an event sem, err=%d", ::GetLastError()),
769 E_FAIL);
770
771 void *data [3];
772 data [0] = (void *) (BSTR) ipcId;
773 data [1] = (void *) mIPCThreadSem;
774 data [2] = 0; /* will get an output from the thread */
775
776 /* create a thread to hold the IPC mutex until signalled to release it */
777 RTTHREAD tid;
778 int vrc = RTThreadCreate (&tid, IPCMutexHolderThread, (void *) data,
779 0, RTTHREADTYPE_MAIN_WORKER, 0, "IPCHolder");
780 AssertRCReturn (vrc, E_FAIL);
781
782 /* wait until thread init is completed */
783 DWORD wrc = ::WaitForSingleObject (mIPCThreadSem, INFINITE);
784 AssertMsg (wrc == WAIT_OBJECT_0, ("Wait failed, err=%d\n", ::GetLastError()));
785 Assert (data [2]);
786
787 if (wrc == WAIT_OBJECT_0 && data [2])
788 {
789 /* memorize the event sem we should signal in close() */
790 mIPCSem = (HANDLE) data [2];
791 rc = S_OK;
792 }
793 else
794 {
795 ::CloseHandle (mIPCThreadSem);
796 mIPCThreadSem = NULL;
797 rc = E_FAIL;
798 }
799
800#elif defined(__OS2__)
801
802 /* We use XPCOM where any message (including close()) can arrive on any
803 * worker thread (which will not necessarily match this thread that opens
804 * the mutex). Therefore, we need a separate thread to hold the IPC mutex
805 * and then release it in close(). */
806
807 int vrc = RTSemEventCreate (&mIPCThreadSem);
808 AssertRCReturn (vrc, E_FAIL);
809
810 void *data [3];
811 data [0] = (void *) ipcId.raw();
812 data [1] = (void *) mIPCThreadSem;
813 data [2] = (void *) false; /* will get the thread result here */
814
815 /* create a thread to hold the IPC mutex until signalled to release it */
816 vrc = RTThreadCreate (&mIPCThread, IPCMutexHolderThread, (void *) data,
817 0, RTTHREADTYPE_MAIN_WORKER, 0, "IPCHolder");
818 AssertRCReturn (vrc, E_FAIL);
819
820 /* wait until thread init is completed */
821 vrc = RTThreadUserWait (mIPCThread, RT_INDEFINITE_WAIT);
822 AssertReturn (VBOX_SUCCESS (vrc) || vrc == VERR_INTERRUPTED, E_FAIL);
823
824 /* the thread must succeed */
825 AssertReturn ((bool) data [2], E_FAIL);
826
827#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
828
829 Utf8Str semName = ipcId;
830 char *pszSemName = NULL;
831 RTStrUtf8ToCurrentCP (&pszSemName, semName);
832 key_t key = ::ftok (pszSemName, 0);
833 RTStrFree (pszSemName);
834
835 mIPCSem = ::semget (key, 0, 0);
836 AssertMsgReturn (mIPCSem >= 0,
837 ("Cannot open IPC semaphore, errno=%d", errno),
838 E_FAIL);
839
840 /* grab the semaphore */
841 ::sembuf sop = { 0, -1, SEM_UNDO };
842 int rv = ::semop (mIPCSem, &sop, 1);
843 AssertMsgReturn (rv == 0,
844 ("Cannot grab IPC semaphore, errno=%d", errno),
845 E_FAIL);
846
847#else
848# error "Port me!"
849#endif
850
851 return rc;
852}
853
854/** @note To be called only from #close() */
855void Session::releaseIPCSemaphore()
856{
857 /* release the IPC semaphore */
858#if defined(__WIN__)
859
860 if (mIPCSem && mIPCThreadSem)
861 {
862 /*
863 * tell the thread holding the IPC mutex to release it;
864 * it will close mIPCSem handle
865 */
866 ::SetEvent (mIPCSem);
867 /* wait for the thread to finish */
868 ::WaitForSingleObject (mIPCThreadSem, INFINITE);
869 ::CloseHandle (mIPCThreadSem);
870 }
871
872#elif defined(__OS2__)
873
874 if (mIPCThread != NIL_RTTHREAD)
875 {
876 Assert (mIPCThreadSem != NIL_RTSEMEVENT);
877
878 /* tell the thread holding the IPC mutex to release it */
879 int vrc = RTSemEventSignal (mIPCThreadSem);
880 AssertRC (vrc == NO_ERROR);
881
882 /* wait for the thread to finish */
883 vrc = RTThreadUserWait (mIPCThread, RT_INDEFINITE_WAIT);
884 Assert (VBOX_SUCCESS (vrc) || vrc == VERR_INTERRUPTED);
885
886 mIPCThread = NIL_RTTHREAD;
887 }
888
889 if (mIPCThreadSem != NIL_RTSEMEVENT)
890 {
891 RTSemEventDestroy (mIPCThreadSem);
892 mIPCThreadSem = NIL_RTSEMEVENT;
893 }
894
895#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
896
897 if (mIPCSem >= 0)
898 {
899 ::sembuf sop = { 0, 1, SEM_UNDO };
900 ::semop (mIPCSem, &sop, 1);
901 }
902
903#else
904# error "Port me!"
905#endif
906}
907
908#if defined(__WIN__)
909/** VM IPC mutex holder thread */
910DECLCALLBACK(int) IPCMutexHolderThread (RTTHREAD Thread, void *pvUser)
911{
912 LogFlowFuncEnter();
913
914 Assert (pvUser);
915 void **data = (void **) pvUser;
916
917 BSTR sessionId = (BSTR) data [0];
918 HANDLE initDoneSem = (HANDLE) data [1];
919
920 HANDLE ipcMutex = ::OpenMutex (MUTEX_ALL_ACCESS, FALSE, sessionId);
921 AssertMsg (ipcMutex, ("cannot open IPC mutex, err=%d\n", ::GetLastError()));
922
923 if (ipcMutex)
924 {
925 /* grab the mutex */
926 DWORD wrc = ::WaitForSingleObject (ipcMutex, 0);
927 AssertMsg (wrc == WAIT_OBJECT_0, ("cannot grab IPC mutex, err=%d\n", wrc));
928 if (wrc == WAIT_OBJECT_0)
929 {
930 HANDLE finishSem = ::CreateEvent (NULL, FALSE, FALSE, NULL);
931 AssertMsg (finishSem, ("cannot create event sem, err=%d\n", ::GetLastError()));
932 if (finishSem)
933 {
934 data [2] = (void *) finishSem;
935 /* signal we're done with init */
936 ::SetEvent (initDoneSem);
937 /* wait until we're signaled to release the IPC mutex */
938 ::WaitForSingleObject (finishSem, INFINITE);
939 /* release the IPC mutex */
940 LogFlow (("IPCMutexHolderThread(): releasing IPC mutex...\n"));
941 BOOL success = ::ReleaseMutex (ipcMutex);
942 AssertMsg (success, ("cannot release mutex, err=%d\n", ::GetLastError()));
943 ::CloseHandle (ipcMutex);
944 ::CloseHandle (finishSem);
945 }
946 }
947 }
948
949 /* signal we're done */
950 ::SetEvent (initDoneSem);
951
952 LogFlowFuncLeave();
953
954 return 0;
955}
956#endif
957
958#if defined(__OS2__)
959/** VM IPC mutex holder thread */
960DECLCALLBACK(int) IPCMutexHolderThread (RTTHREAD Thread, void *pvUser)
961{
962 LogFlowFuncEnter();
963
964 Assert (pvUser);
965 void **data = (void **) pvUser;
966
967 Utf8Str ipcId = (BSTR) data [0];
968 RTSEMEVENT finishSem = (RTSEMEVENT) data [1];
969
970 LogFlowFunc (("ipcId='%s', finishSem=%p\n", ipcId.raw(), finishSem));
971
972 HMTX ipcMutex = NULLHANDLE;
973 APIRET arc = ::DosOpenMutexSem ((PSZ) ipcId.raw(), &ipcMutex);
974 AssertMsg (arc == NO_ERROR, ("cannot open IPC mutex, arc=%ld\n", arc));
975
976 if (arc == NO_ERROR)
977 {
978 /* grab the mutex */
979 LogFlowFunc (("grabbing IPC mutex...\n"));
980 arc = ::DosRequestMutexSem (ipcMutex, SEM_IMMEDIATE_RETURN);
981 AssertMsg (arc == NO_ERROR, ("cannot grab IPC mutex, arc=%ld\n", arc));
982 if (arc == NO_ERROR)
983 {
984 /* store the answer */
985 data [2] = (void *) true;
986 /* signal we're done */
987 int vrc = RTThreadUserSignal (Thread);
988 AssertRC (vrc);
989
990 /* wait until we're signaled to release the IPC mutex */
991 LogFlowFunc (("waiting for termination signal..\n"));
992 vrc = RTSemEventWait (finishSem, RT_INDEFINITE_WAIT);
993 Assert (arc == ERROR_INTERRUPT || ERROR_TIMEOUT);
994
995 /* release the IPC mutex */
996 LogFlowFunc (("releasing IPC mutex...\n"));
997 arc = ::DosReleaseMutexSem (ipcMutex);
998 AssertMsg (arc == NO_ERROR, ("cannot release mutex, arc=%ld\n", arc));
999 }
1000 }
1001
1002 /* store the answer */
1003 data [1] = (void *) false;
1004 /* signal we're done */
1005 int vrc = RTThreadUserSignal (Thread);
1006 AssertRC (vrc);
1007
1008 LogFlowFuncLeave();
1009
1010 return 0;
1011}
1012#endif
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