VirtualBox

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

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

Main/OS2: Close the mutex on session close.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 28.5 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::OnSerialPortChange(ISerialPort *serialPort)
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->onSerialPortChange(serialPort);
553}
554
555STDMETHODIMP Session::OnVRDPServerChange()
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->onVRDPServerChange();
567}
568
569STDMETHODIMP Session::OnUSBControllerChange()
570{
571 LogFlowThisFunc (("\n"));
572
573 AutoCaller autoCaller (this);
574 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
575
576 AutoReaderLock alock (this);
577 AssertReturn (mState == SessionState_SessionOpen &&
578 mType == SessionType_DirectSession, E_FAIL);
579
580 return mConsole->onUSBControllerChange();
581}
582
583STDMETHODIMP Session::OnUSBDeviceAttach (IUSBDevice *aDevice,
584 IVirtualBoxErrorInfo *aError)
585{
586 LogFlowThisFunc (("\n"));
587
588 AutoCaller autoCaller (this);
589 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
590
591 AutoReaderLock alock (this);
592 AssertReturn (mState == SessionState_SessionOpen &&
593 mType == SessionType_DirectSession, E_FAIL);
594
595 return mConsole->onUSBDeviceAttach (aDevice, aError);
596}
597
598STDMETHODIMP Session::OnUSBDeviceDetach (INPTR GUIDPARAM aId,
599 IVirtualBoxErrorInfo *aError)
600{
601 LogFlowThisFunc (("\n"));
602
603 AutoCaller autoCaller (this);
604 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
605
606 AutoReaderLock alock (this);
607 AssertReturn (mState == SessionState_SessionOpen &&
608 mType == SessionType_DirectSession, E_FAIL);
609
610 return mConsole->onUSBDeviceDetach (aId, aError);
611}
612
613STDMETHODIMP Session::OnShowWindow (BOOL aCheck, BOOL *aCanShow, ULONG64 *aWinId)
614{
615 AutoCaller autoCaller (this);
616 AssertComRCReturn (autoCaller.rc(), autoCaller.rc());
617
618 AutoReaderLock alock (this);
619 AssertReturn (mState == SessionState_SessionOpen &&
620 mType == SessionType_DirectSession, E_FAIL);
621
622 return mConsole->onShowWindow (aCheck, aCanShow, aWinId);
623}
624
625// private methods
626///////////////////////////////////////////////////////////////////////////////
627
628/**
629 * Closes the current session.
630 *
631 * @param aFinalRelease called as a result of FinalRelease()
632 * @param aFromServer called as a result of Uninitialize()
633 *
634 * @note To be called only from #uninit(), #Close() or #Uninitialize().
635 * @note Locks this object for writing.
636 */
637HRESULT Session::close (bool aFinalRelease, bool aFromServer)
638{
639 LogFlowThisFuncEnter();
640 LogFlowThisFunc (("aFinalRelease=%d, isFromServer=%d\n",
641 aFinalRelease, aFromServer));
642
643 AutoCaller autoCaller (this);
644 AssertComRCReturnRC (autoCaller.rc());
645
646 AutoLock alock (this);
647
648 LogFlowThisFunc (("mState=%d, mType=%d\n", mState, mType));
649
650 if (mState != SessionState_SessionOpen)
651 {
652 Assert (mState == SessionState_SessionSpawning);
653
654 /* The session object is going to be uninitialized by the client before
655 * it has been assigned a direct console of the machine the client
656 * requested to open a remote session to using IVirtualBox::
657 * openRemoteSession(). Theoretically it should not happen because
658 * openRemoteSession() doesn't return control to the client until the
659 * procedure is fully complete, so assert here. */
660 AssertFailed();
661
662 mState = SessionState_SessionClosed;
663 mType = SessionType_InvalidSessionType;
664#if defined(__WIN__)
665 Assert (!mIPCSem && !mIPCThreadSem);
666#elif defined(__OS2__)
667 Assert (mIPCThread == NIL_RTTHREAD &&
668 mIPCThreadSem == NIL_RTSEMEVENT);
669#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
670 Assert (mIPCSem == -1);
671#else
672# error "Port me!"
673#endif
674 LogFlowThisFuncLeave();
675 return S_OK;
676 }
677
678 /* go to the closing state */
679 mState = SessionState_SessionClosing;
680
681 if (mType == SessionType_DirectSession)
682 {
683 mConsole->uninit();
684 mConsole.setNull();
685 }
686 else
687 {
688 mRemoteMachine.setNull();
689 mRemoteConsole.setNull();
690 }
691
692 ComPtr <IProgress> progress;
693
694 if (!aFinalRelease && !aFromServer)
695 {
696 /*
697 * We trigger OnSessionEnd() only when the session closes itself using
698 * Close(). Note that if isFinalRelease = TRUE here, this means that
699 * the client process has already initialized the termination procedure
700 * without issuing Close() and the IPC channel is no more operational --
701 * so we cannot call the server's method (it will definitely fail). The
702 * server will instead simply detect the abnormal client death (since
703 * OnSessionEnd() is not called) and reset the machine state to Aborted.
704 */
705
706 /*
707 * while waiting for OnSessionEnd() to complete one of our methods
708 * can be called by the server (for example, Uninitialize(), if the
709 * direct session has initiated a closure just a bit before us) so
710 * we need to release the lock to avoid deadlocks. The state is already
711 * SessionState_SessionClosing here, so it's safe.
712 */
713 alock.leave();
714
715 LogFlowThisFunc (("Calling mControl->OnSessionEnd()...\n"));
716 HRESULT rc = mControl->OnSessionEnd (this, progress.asOutParam());
717 LogFlowThisFunc (("mControl->OnSessionEnd()=%08X\n", rc));
718
719 alock.enter();
720
721 /*
722 * If we get E_UNEXPECTED this means that the direct session has already
723 * been closed, we're just too late with our notification and nothing more
724 */
725 if (mType != SessionType_DirectSession && rc == E_UNEXPECTED)
726 rc = S_OK;
727
728 AssertComRC (rc);
729 }
730
731 mControl.setNull();
732
733 if (mType == SessionType_DirectSession)
734 {
735 releaseIPCSemaphore();
736 if (!aFinalRelease && !aFromServer)
737 {
738 /*
739 * Wait for the server to grab the semaphore and destroy the session
740 * machine (allowing us to open a new session with the same machine
741 * once this method returns)
742 */
743 Assert (!!progress);
744 if (progress)
745 progress->WaitForCompletion (-1);
746 }
747 }
748
749 mState = SessionState_SessionClosed;
750 mType = SessionType_InvalidSessionType;
751
752 /* release the VirtualBox instance as the very last step */
753 mVirtualBox.setNull();
754
755 LogFlowThisFuncLeave();
756 return S_OK;
757}
758
759/** @note To be called only from #AssignMachine() */
760HRESULT Session::grabIPCSemaphore()
761{
762 HRESULT rc = E_FAIL;
763
764 /* open the IPC semaphore based on the sessionId and try to grab it */
765 Bstr ipcId;
766 rc = mControl->GetIPCId (ipcId.asOutParam());
767 AssertComRCReturnRC (rc);
768
769 LogFlowThisFunc (("ipcId='%ls'\n", ipcId.raw()));
770
771#if defined(__WIN__)
772
773 /*
774 * Since Session is an MTA object, this method can be executed on
775 * any thread, and this thread will not necessarily match the thread on
776 * which close() will be called later. Therefore, we need a separate
777 * thread to hold the IPC mutex and then release it in close().
778 */
779
780 mIPCThreadSem = ::CreateEvent (NULL, FALSE, FALSE, NULL);
781 AssertMsgReturn (mIPCThreadSem,
782 ("Cannot create an event sem, err=%d", ::GetLastError()),
783 E_FAIL);
784
785 void *data [3];
786 data [0] = (void *) (BSTR) ipcId;
787 data [1] = (void *) mIPCThreadSem;
788 data [2] = 0; /* will get an output from the thread */
789
790 /* create a thread to hold the IPC mutex until signalled to release it */
791 RTTHREAD tid;
792 int vrc = RTThreadCreate (&tid, IPCMutexHolderThread, (void *) data,
793 0, RTTHREADTYPE_MAIN_WORKER, 0, "IPCHolder");
794 AssertRCReturn (vrc, E_FAIL);
795
796 /* wait until thread init is completed */
797 DWORD wrc = ::WaitForSingleObject (mIPCThreadSem, INFINITE);
798 AssertMsg (wrc == WAIT_OBJECT_0, ("Wait failed, err=%d\n", ::GetLastError()));
799 Assert (data [2]);
800
801 if (wrc == WAIT_OBJECT_0 && data [2])
802 {
803 /* memorize the event sem we should signal in close() */
804 mIPCSem = (HANDLE) data [2];
805 rc = S_OK;
806 }
807 else
808 {
809 ::CloseHandle (mIPCThreadSem);
810 mIPCThreadSem = NULL;
811 rc = E_FAIL;
812 }
813
814#elif defined(__OS2__)
815
816 /* We use XPCOM where any message (including close()) can arrive on any
817 * worker thread (which will not necessarily match this thread that opens
818 * the mutex). Therefore, we need a separate thread to hold the IPC mutex
819 * and then release it in close(). */
820
821 int vrc = RTSemEventCreate (&mIPCThreadSem);
822 AssertRCReturn (vrc, E_FAIL);
823
824 void *data [3];
825 data [0] = (void *) ipcId.raw();
826 data [1] = (void *) mIPCThreadSem;
827 data [2] = (void *) false; /* will get the thread result here */
828
829 /* create a thread to hold the IPC mutex until signalled to release it */
830 vrc = RTThreadCreate (&mIPCThread, IPCMutexHolderThread, (void *) data,
831 0, RTTHREADTYPE_MAIN_WORKER, 0, "IPCHolder");
832 AssertRCReturn (vrc, E_FAIL);
833
834 /* wait until thread init is completed */
835 vrc = RTThreadUserWait (mIPCThread, RT_INDEFINITE_WAIT);
836 AssertReturn (VBOX_SUCCESS (vrc) || vrc == VERR_INTERRUPTED, E_FAIL);
837
838 /* the thread must succeed */
839 AssertReturn ((bool) data [2], E_FAIL);
840
841#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
842
843 Utf8Str semName = ipcId;
844 char *pszSemName = NULL;
845 RTStrUtf8ToCurrentCP (&pszSemName, semName);
846 key_t key = ::ftok (pszSemName, 0);
847 RTStrFree (pszSemName);
848
849 mIPCSem = ::semget (key, 0, 0);
850 AssertMsgReturn (mIPCSem >= 0,
851 ("Cannot open IPC semaphore, errno=%d", errno),
852 E_FAIL);
853
854 /* grab the semaphore */
855 ::sembuf sop = { 0, -1, SEM_UNDO };
856 int rv = ::semop (mIPCSem, &sop, 1);
857 AssertMsgReturn (rv == 0,
858 ("Cannot grab IPC semaphore, errno=%d", errno),
859 E_FAIL);
860
861#else
862# error "Port me!"
863#endif
864
865 return rc;
866}
867
868/** @note To be called only from #close() */
869void Session::releaseIPCSemaphore()
870{
871 /* release the IPC semaphore */
872#if defined(__WIN__)
873
874 if (mIPCSem && mIPCThreadSem)
875 {
876 /*
877 * tell the thread holding the IPC mutex to release it;
878 * it will close mIPCSem handle
879 */
880 ::SetEvent (mIPCSem);
881 /* wait for the thread to finish */
882 ::WaitForSingleObject (mIPCThreadSem, INFINITE);
883 ::CloseHandle (mIPCThreadSem);
884 }
885
886#elif defined(__OS2__)
887
888 if (mIPCThread != NIL_RTTHREAD)
889 {
890 Assert (mIPCThreadSem != NIL_RTSEMEVENT);
891
892 /* tell the thread holding the IPC mutex to release it */
893 int vrc = RTSemEventSignal (mIPCThreadSem);
894 AssertRC (vrc == NO_ERROR);
895
896 /* wait for the thread to finish */
897 vrc = RTThreadUserWait (mIPCThread, RT_INDEFINITE_WAIT);
898 Assert (VBOX_SUCCESS (vrc) || vrc == VERR_INTERRUPTED);
899
900 mIPCThread = NIL_RTTHREAD;
901 }
902
903 if (mIPCThreadSem != NIL_RTSEMEVENT)
904 {
905 RTSemEventDestroy (mIPCThreadSem);
906 mIPCThreadSem = NIL_RTSEMEVENT;
907 }
908
909#elif defined(VBOX_WITH_SYS_V_IPC_SESSION_WATCHER)
910
911 if (mIPCSem >= 0)
912 {
913 ::sembuf sop = { 0, 1, SEM_UNDO };
914 ::semop (mIPCSem, &sop, 1);
915 }
916
917#else
918# error "Port me!"
919#endif
920}
921
922#if defined(__WIN__)
923/** VM IPC mutex holder thread */
924DECLCALLBACK(int) IPCMutexHolderThread (RTTHREAD Thread, void *pvUser)
925{
926 LogFlowFuncEnter();
927
928 Assert (pvUser);
929 void **data = (void **) pvUser;
930
931 BSTR sessionId = (BSTR) data [0];
932 HANDLE initDoneSem = (HANDLE) data [1];
933
934 HANDLE ipcMutex = ::OpenMutex (MUTEX_ALL_ACCESS, FALSE, sessionId);
935 AssertMsg (ipcMutex, ("cannot open IPC mutex, err=%d\n", ::GetLastError()));
936
937 if (ipcMutex)
938 {
939 /* grab the mutex */
940 DWORD wrc = ::WaitForSingleObject (ipcMutex, 0);
941 AssertMsg (wrc == WAIT_OBJECT_0, ("cannot grab IPC mutex, err=%d\n", wrc));
942 if (wrc == WAIT_OBJECT_0)
943 {
944 HANDLE finishSem = ::CreateEvent (NULL, FALSE, FALSE, NULL);
945 AssertMsg (finishSem, ("cannot create event sem, err=%d\n", ::GetLastError()));
946 if (finishSem)
947 {
948 data [2] = (void *) finishSem;
949 /* signal we're done with init */
950 ::SetEvent (initDoneSem);
951 /* wait until we're signaled to release the IPC mutex */
952 ::WaitForSingleObject (finishSem, INFINITE);
953 /* release the IPC mutex */
954 LogFlow (("IPCMutexHolderThread(): releasing IPC mutex...\n"));
955 BOOL success = ::ReleaseMutex (ipcMutex);
956 AssertMsg (success, ("cannot release mutex, err=%d\n", ::GetLastError()));
957 ::CloseHandle (ipcMutex);
958 ::CloseHandle (finishSem);
959 }
960 }
961 }
962
963 /* signal we're done */
964 ::SetEvent (initDoneSem);
965
966 LogFlowFuncLeave();
967
968 return 0;
969}
970#endif
971
972#if defined(__OS2__)
973/** VM IPC mutex holder thread */
974DECLCALLBACK(int) IPCMutexHolderThread (RTTHREAD Thread, void *pvUser)
975{
976 LogFlowFuncEnter();
977
978 Assert (pvUser);
979 void **data = (void **) pvUser;
980
981 Utf8Str ipcId = (BSTR) data [0];
982 RTSEMEVENT finishSem = (RTSEMEVENT) data [1];
983
984 LogFlowFunc (("ipcId='%s', finishSem=%p\n", ipcId.raw(), finishSem));
985
986 HMTX ipcMutex = NULLHANDLE;
987 APIRET arc = ::DosOpenMutexSem ((PSZ) ipcId.raw(), &ipcMutex);
988 AssertMsg (arc == NO_ERROR, ("cannot open IPC mutex, arc=%ld\n", arc));
989
990 if (arc == NO_ERROR)
991 {
992 /* grab the mutex */
993 LogFlowFunc (("grabbing IPC mutex...\n"));
994 arc = ::DosRequestMutexSem (ipcMutex, SEM_IMMEDIATE_RETURN);
995 AssertMsg (arc == NO_ERROR, ("cannot grab IPC mutex, arc=%ld\n", arc));
996 if (arc == NO_ERROR)
997 {
998 /* store the answer */
999 data [2] = (void *) true;
1000 /* signal we're done */
1001 int vrc = RTThreadUserSignal (Thread);
1002 AssertRC (vrc);
1003
1004 /* wait until we're signaled to release the IPC mutex */
1005 LogFlowFunc (("waiting for termination signal..\n"));
1006 vrc = RTSemEventWait (finishSem, RT_INDEFINITE_WAIT);
1007 Assert (arc == ERROR_INTERRUPT || ERROR_TIMEOUT);
1008
1009 /* release the IPC mutex */
1010 LogFlowFunc (("releasing IPC mutex...\n"));
1011 arc = ::DosReleaseMutexSem (ipcMutex);
1012 AssertMsg (arc == NO_ERROR, ("cannot release mutex, arc=%ld\n", arc));
1013 }
1014
1015 ::DosCloseMutexSem (ipcMutex);
1016 }
1017
1018 /* store the answer */
1019 data [1] = (void *) false;
1020 /* signal we're done */
1021 int vrc = RTThreadUserSignal (Thread);
1022 AssertRC (vrc);
1023
1024 LogFlowFuncLeave();
1025
1026 return 0;
1027}
1028#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