VirtualBox

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

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

Parallel port support. Contributed by: Alexander Eichner

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