VirtualBox

source: vbox/trunk/src/VBox/Additions/common/VBoxService/VBoxServiceControlProcess.cpp@ 85672

Last change on this file since 85672 was 84881, checked in by vboxsync, 5 years ago

Guest Control/VBoxServce: Fixed removing a (not yet started) process from a guest session's process list in case of early failures in the process thread. Needed in order to avoid process cleanup hangs. bugref:9320.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 85.2 KB
Line 
1/* $Id: VBoxServiceControlProcess.cpp 84881 2020-06-19 12:42:31Z vboxsync $ */
2/** @file
3 * VBoxServiceControlThread - Guest process handling.
4 */
5
6/*
7 * Copyright (C) 2012-2020 Oracle Corporation
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 (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#include <iprt/asm.h>
23#include <iprt/assert.h>
24#include <iprt/env.h>
25#include <iprt/file.h>
26#include <iprt/getopt.h>
27#include <iprt/handle.h>
28#include <iprt/mem.h>
29#include <iprt/path.h>
30#include <iprt/pipe.h>
31#include <iprt/poll.h>
32#include <iprt/process.h>
33#include <iprt/semaphore.h>
34#include <iprt/string.h>
35#include <iprt/string.h>
36#include <iprt/thread.h>
37
38#include <VBox/VBoxGuestLib.h>
39#include <VBox/HostServices/GuestControlSvc.h>
40
41#include "VBoxServiceInternal.h"
42#include "VBoxServiceControl.h"
43#include "VBoxServiceToolBox.h"
44
45using namespace guestControl;
46
47
48/*********************************************************************************************************************************
49* Internal Functions *
50*********************************************************************************************************************************/
51static int vgsvcGstCtrlProcessAssignPID(PVBOXSERVICECTRLPROCESS pThread, uint32_t uPID);
52static int vgsvcGstCtrlProcessLock(PVBOXSERVICECTRLPROCESS pProcess);
53static int vgsvcGstCtrlProcessSetupPipe(const char *pszHowTo, int fd, PRTHANDLE ph, PRTHANDLE *pph,
54 PRTPIPE phPipe);
55static int vgsvcGstCtrlProcessUnlock(PVBOXSERVICECTRLPROCESS pProcess);
56/* Request handlers. */
57static DECLCALLBACK(int) vgsvcGstCtrlProcessOnInput(PVBOXSERVICECTRLPROCESS pThis, const PVBGLR3GUESTCTRLCMDCTX pHostCtx,
58 bool fPendingClose, void *pvBuf, uint32_t cbBuf);
59static DECLCALLBACK(int) vgsvcGstCtrlProcessOnOutput(PVBOXSERVICECTRLPROCESS pThis, const PVBGLR3GUESTCTRLCMDCTX pHostCtx,
60 uint32_t uHandle, uint32_t cbToRead, uint32_t uFlags);
61
62
63
64/**
65 * Initialies the passed in thread data structure with the parameters given.
66 *
67 * @return IPRT status code.
68 * @param pProcess Process to initialize.
69 * @param pSession Guest session the process is bound to.
70 * @param pStartupInfo Startup information.
71 * @param u32ContextID The context ID bound to this request / command.
72 */
73static int vgsvcGstCtrlProcessInit(PVBOXSERVICECTRLPROCESS pProcess,
74 const PVBOXSERVICECTRLSESSION pSession,
75 const PVBGLR3GUESTCTRLPROCSTARTUPINFO pStartupInfo,
76 uint32_t u32ContextID)
77{
78 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
79 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
80 AssertPtrReturn(pStartupInfo, VERR_INVALID_POINTER);
81
82 /* General stuff. */
83 pProcess->hProcess = NIL_RTPROCESS;
84 pProcess->pSession = pSession;
85 pProcess->Node.pPrev = NULL;
86 pProcess->Node.pNext = NULL;
87
88 pProcess->fShutdown = false;
89 pProcess->fStarted = false;
90 pProcess->fStopped = false;
91
92 pProcess->uPID = 0; /* Don't have a PID yet. */
93 pProcess->cRefs = 0;
94 /*
95 * Use the initial context ID we got for starting
96 * the process to report back its status with the
97 * same context ID.
98 */
99 pProcess->uContextID = u32ContextID;
100 /*
101 * Note: pProcess->ClientID will be assigned when thread is started;
102 * every guest process has its own client ID to detect crashes on
103 * a per-guest-process level.
104 */
105
106 int rc = RTCritSectInit(&pProcess->CritSect);
107 if (RT_FAILURE(rc))
108 return rc;
109
110 pProcess->hPollSet = NIL_RTPOLLSET;
111 pProcess->hPipeStdInW = NIL_RTPIPE;
112 pProcess->hPipeStdOutR = NIL_RTPIPE;
113 pProcess->hPipeStdErrR = NIL_RTPIPE;
114 pProcess->hNotificationPipeW = NIL_RTPIPE;
115 pProcess->hNotificationPipeR = NIL_RTPIPE;
116
117 rc = RTReqQueueCreate(&pProcess->hReqQueue);
118 AssertReleaseRC(rc);
119
120 /* Duplicate startup info. */
121 pProcess->pStartupInfo = VbglR3GuestCtrlProcStartupInfoDup(pStartupInfo);
122 AssertPtrReturn(pProcess->pStartupInfo, VERR_NO_MEMORY);
123
124 /* Adjust timeout value. */
125 if ( pProcess->pStartupInfo->uTimeLimitMS == UINT32_MAX
126 || pProcess->pStartupInfo->uTimeLimitMS == 0)
127 pProcess->pStartupInfo->uTimeLimitMS = RT_INDEFINITE_WAIT;
128
129 if (RT_FAILURE(rc)) /* Clean up on failure. */
130 VGSvcGstCtrlProcessFree(pProcess);
131 return rc;
132}
133
134
135/**
136 * Frees a guest process. On success, pProcess will be
137 * free'd and thus won't be available anymore.
138 *
139 * @return IPRT status code.
140 * @param pProcess Guest process to free.
141 * The pointer will not be valid anymore after return.
142 */
143int VGSvcGstCtrlProcessFree(PVBOXSERVICECTRLPROCESS pProcess)
144{
145 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
146
147 int rc = RTCritSectEnter(&pProcess->CritSect);
148 if (RT_SUCCESS(rc))
149 {
150 VGSvcVerbose(3, "[PID %RU32]: Freeing (cRefs=%RU32)...\n", pProcess->uPID, pProcess->cRefs);
151
152 AssertReturn(pProcess->cRefs == 0, VERR_WRONG_ORDER);
153 AssertReturn(pProcess->fStopped, VERR_WRONG_ORDER);
154 AssertReturn(pProcess->fShutdown, VERR_WRONG_ORDER);
155
156 VbglR3GuestCtrlProcStartupInfoFree(pProcess->pStartupInfo);
157 pProcess->pStartupInfo = NULL;
158
159 /*
160 * Destroy other thread data.
161 */
162 rc = RTPollSetDestroy(pProcess->hPollSet);
163 AssertRC(rc);
164
165 rc = RTReqQueueDestroy(pProcess->hReqQueue);
166 AssertRC(rc);
167
168 rc = RTPipeClose(pProcess->hNotificationPipeR);
169 AssertRC(rc);
170 rc = RTPipeClose(pProcess->hNotificationPipeW);
171 AssertRC(rc);
172
173 rc = RTPipeClose(pProcess->hPipeStdInW);
174 AssertRC(rc);
175 rc = RTPipeClose(pProcess->hPipeStdErrR);
176 AssertRC(rc);
177 rc = RTPipeClose(pProcess->hPipeStdOutR);
178 AssertRC(rc);
179
180 rc = RTCritSectLeave(&pProcess->CritSect);
181 AssertRC(rc);
182
183 RTCritSectDelete(&pProcess->CritSect);
184
185 /*
186 * Destroy thread structure as final step.
187 */
188 RTMemFree(pProcess);
189 pProcess = NULL;
190 }
191
192 return rc;
193}
194
195
196/**
197 * Signals a guest process thread that we want it to shut down in
198 * a gentle way.
199 *
200 * @return IPRT status code.
201 * @param pProcess Process to stop.
202 */
203int VGSvcGstCtrlProcessStop(PVBOXSERVICECTRLPROCESS pProcess)
204{
205 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
206
207 VGSvcVerbose(3, "[PID %RU32]: Stopping ...\n", pProcess->uPID);
208
209 /* Do *not* set pThread->fShutdown or other stuff here!
210 * The guest thread loop will clean up itself. */
211
212 return VGSvcGstCtrlProcessHandleTerm(pProcess);
213}
214
215
216/**
217 * Releases a previously acquired guest process (decreases the refcount).
218 *
219 * @param pProcess Process to release.
220 */
221void VGSvcGstCtrlProcessRelease(PVBOXSERVICECTRLPROCESS pProcess)
222{
223 AssertPtrReturnVoid(pProcess);
224
225 int rc2 = RTCritSectEnter(&pProcess->CritSect);
226 if (RT_SUCCESS(rc2))
227 {
228 AssertReturnVoid(pProcess->cRefs);
229 pProcess->cRefs--;
230
231 VGSvcVerbose(3, "[PID %RU32]: cRefs=%RU32, fShutdown=%RTbool, fStopped=%RTbool\n",
232 pProcess->uPID, pProcess->cRefs, pProcess->fShutdown, pProcess->fStopped);
233
234 rc2 = RTCritSectLeave(&pProcess->CritSect);
235 AssertRC(rc2);
236 }
237}
238
239
240/**
241 * Wait for a guest process thread to shut down.
242 *
243 * @return IPRT status code.
244 * @param pProcess Process to wait shutting down for.
245 * @param msTimeout Timeout in ms to wait for shutdown.
246 * @param prc Where to store the thread's return code.
247 * Optional.
248 */
249int VGSvcGstCtrlProcessWait(const PVBOXSERVICECTRLPROCESS pProcess, RTMSINTERVAL msTimeout, int *prc)
250{
251 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
252 AssertPtrNullReturn(prc, VERR_INVALID_POINTER);
253
254 int rc = vgsvcGstCtrlProcessLock(pProcess);
255 if (RT_SUCCESS(rc))
256 {
257 if (RTThreadGetState(pProcess->Thread) != RTTHREADSTATE_INVALID) /* Is there a thread we can wait for? */
258 {
259 VGSvcVerbose(2, "[PID %RU32]: Waiting for shutdown (%RU32ms) ...\n", pProcess->uPID, msTimeout);
260
261 AssertMsgReturn(pProcess->fStarted,
262 ("Tried to wait on guest process=%p (PID %RU32) which has not been started yet\n",
263 pProcess, pProcess->uPID), VERR_INVALID_PARAMETER);
264
265 /* Unlock process before waiting. */
266 rc = vgsvcGstCtrlProcessUnlock(pProcess);
267 AssertRC(rc);
268
269 /* Do the actual waiting. */
270 int rcThread;
271 Assert(pProcess->Thread != NIL_RTTHREAD);
272 rc = RTThreadWait(pProcess->Thread, msTimeout, &rcThread);
273
274 int rc2 = vgsvcGstCtrlProcessLock(pProcess);
275 AssertRC(rc2);
276
277 if (RT_SUCCESS(rc))
278 {
279 pProcess->Thread = NIL_RTTHREAD;
280 VGSvcVerbose(3, "[PID %RU32]: Thread shutdown complete, thread rc=%Rrc\n", pProcess->uPID, rcThread);
281 if (prc)
282 *prc = rcThread;
283 }
284 }
285
286 int rc2 = vgsvcGstCtrlProcessUnlock(pProcess);
287 AssertRC(rc2);
288 }
289
290 if (RT_FAILURE(rc))
291 VGSvcError("[PID %RU32]: Waiting for shutting down thread returned error rc=%Rrc\n", pProcess->uPID, rc);
292
293 VGSvcVerbose(3, "[PID %RU32]: Waiting resulted in rc=%Rrc\n", pProcess->uPID, rc);
294 return rc;
295}
296
297
298/**
299 * Closes the stdin pipe of a guest process.
300 *
301 * @return IPRT status code.
302 * @param pProcess The process which input pipe we close.
303 * @param phStdInW The standard input pipe handle.
304 */
305static int vgsvcGstCtrlProcessPollsetCloseInput(PVBOXSERVICECTRLPROCESS pProcess, PRTPIPE phStdInW)
306{
307 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
308 AssertPtrReturn(phStdInW, VERR_INVALID_POINTER);
309
310 int rc = RTPollSetRemove(pProcess->hPollSet, VBOXSERVICECTRLPIPEID_STDIN);
311 if (rc != VERR_POLL_HANDLE_ID_NOT_FOUND)
312 AssertRC(rc);
313
314 if (*phStdInW != NIL_RTPIPE)
315 {
316 rc = RTPipeClose(*phStdInW);
317 AssertRC(rc);
318 *phStdInW = NIL_RTPIPE;
319 }
320
321 return rc;
322}
323
324
325#ifdef DEBUG
326/**
327 * Names a poll handle ID.
328 *
329 * @returns Pointer to read-only string.
330 * @param idPollHnd What to name.
331 */
332static const char *vgsvcGstCtrlProcessPollHandleToString(uint32_t idPollHnd)
333{
334 switch (idPollHnd)
335 {
336 case VBOXSERVICECTRLPIPEID_UNKNOWN:
337 return "unknown";
338 case VBOXSERVICECTRLPIPEID_STDIN:
339 return "stdin";
340 case VBOXSERVICECTRLPIPEID_STDIN_WRITABLE:
341 return "stdin_writable";
342 case VBOXSERVICECTRLPIPEID_STDOUT:
343 return "stdout";
344 case VBOXSERVICECTRLPIPEID_STDERR:
345 return "stderr";
346 case VBOXSERVICECTRLPIPEID_IPC_NOTIFY:
347 return "ipc_notify";
348 default:
349 return "unknown";
350 }
351}
352#endif /* DEBUG */
353
354
355/**
356 * Handle an error event on standard input.
357 *
358 * @return IPRT status code.
359 * @param pProcess Process to handle pollset for.
360 * @param fPollEvt The event mask returned by RTPollNoResume.
361 * @param phStdInW The standard input pipe handle.
362 */
363static int vgsvcGstCtrlProcessPollsetOnInput(PVBOXSERVICECTRLPROCESS pProcess, uint32_t fPollEvt, PRTPIPE phStdInW)
364{
365 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
366
367 NOREF(fPollEvt);
368
369 return vgsvcGstCtrlProcessPollsetCloseInput(pProcess, phStdInW);
370}
371
372
373/**
374 * Handle pending output data or error on standard out or standard error.
375 *
376 * @returns IPRT status code from client send.
377 * @param pProcess Process to handle pollset for.
378 * @param fPollEvt The event mask returned by RTPollNoResume.
379 * @param phPipeR The pipe handle.
380 * @param idPollHnd The pipe ID to handle.
381 */
382static int vgsvcGstCtrlProcessHandleOutputError(PVBOXSERVICECTRLPROCESS pProcess,
383 uint32_t fPollEvt, PRTPIPE phPipeR, uint32_t idPollHnd)
384{
385 RT_NOREF1(fPollEvt);
386 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
387
388 if (!phPipeR)
389 return VINF_SUCCESS;
390
391#ifdef DEBUG
392 VGSvcVerbose(4, "[PID %RU32]: Output error: idPollHnd=%s, fPollEvt=0x%x\n",
393 pProcess->uPID, vgsvcGstCtrlProcessPollHandleToString(idPollHnd), fPollEvt);
394#endif
395
396 /* Remove pipe from poll set. */
397 int rc2 = RTPollSetRemove(pProcess->hPollSet, idPollHnd);
398 AssertMsg(RT_SUCCESS(rc2) || rc2 == VERR_POLL_HANDLE_ID_NOT_FOUND, ("%Rrc\n", rc2));
399
400 bool fClosePipe = true; /* By default close the pipe. */
401
402 /* Check if there's remaining data to read from the pipe. */
403 if (*phPipeR != NIL_RTPIPE)
404 {
405 size_t cbReadable;
406 rc2 = RTPipeQueryReadable(*phPipeR, &cbReadable);
407 if ( RT_SUCCESS(rc2)
408 && cbReadable)
409 {
410#ifdef DEBUG
411 VGSvcVerbose(3, "[PID %RU32]: idPollHnd=%s has %zu bytes left, vetoing close\n",
412 pProcess->uPID, vgsvcGstCtrlProcessPollHandleToString(idPollHnd), cbReadable);
413#endif
414 /* Veto closing the pipe yet because there's still stuff to read
415 * from the pipe. This can happen on UNIX-y systems where on
416 * error/hangup there still can be data to be read out. */
417 fClosePipe = false;
418 }
419 }
420#ifdef DEBUG
421 else
422 VGSvcVerbose(3, "[PID %RU32]: idPollHnd=%s will be closed\n",
423 pProcess->uPID, vgsvcGstCtrlProcessPollHandleToString(idPollHnd));
424#endif
425
426 if ( *phPipeR != NIL_RTPIPE
427 && fClosePipe)
428 {
429 rc2 = RTPipeClose(*phPipeR);
430 AssertRC(rc2);
431 *phPipeR = NIL_RTPIPE;
432 }
433
434 return VINF_SUCCESS;
435}
436
437
438/**
439 * Handle pending output data or error on standard out or standard error.
440 *
441 * @returns IPRT status code from client send.
442 * @param pProcess Process to handle pollset for.
443 * @param fPollEvt The event mask returned by RTPollNoResume.
444 * @param phPipeR The pipe handle.
445 * @param idPollHnd The pipe ID to handle.
446 *
447 */
448static int vgsvcGstCtrlProcessPollsetOnOutput(PVBOXSERVICECTRLPROCESS pProcess,
449 uint32_t fPollEvt, PRTPIPE phPipeR, uint32_t idPollHnd)
450{
451 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
452
453#ifdef DEBUG
454 VGSvcVerbose(4, "[PID %RU32]: Output event phPipeR=%p, idPollHnd=%s, fPollEvt=0x%x\n",
455 pProcess->uPID, phPipeR, vgsvcGstCtrlProcessPollHandleToString(idPollHnd), fPollEvt);
456#endif
457
458 if (!phPipeR)
459 return VINF_SUCCESS;
460
461 int rc = VINF_SUCCESS;
462
463#ifdef DEBUG
464 if (*phPipeR != NIL_RTPIPE)
465 {
466 size_t cbReadable;
467 rc = RTPipeQueryReadable(*phPipeR, &cbReadable);
468 if ( RT_SUCCESS(rc)
469 && cbReadable)
470 {
471 VGSvcVerbose(4, "[PID %RU32]: Output event cbReadable=%zu\n", pProcess->uPID, cbReadable);
472 }
473 }
474#endif
475
476#if 0
477 /* Push output to the host. */
478 if (fPollEvt & RTPOLL_EVT_READ)
479 {
480 size_t cbRead = 0;
481 uint8_t byData[_64K];
482 rc = RTPipeRead(*phPipeR, byData, sizeof(byData), &cbRead);
483 VGSvcVerbose(4, "VGSvcGstCtrlProcessHandleOutputEvent cbRead=%u, rc=%Rrc\n", cbRead, rc);
484
485 /* Make sure we go another poll round in case there was too much data
486 for the buffer to hold. */
487 fPollEvt &= RTPOLL_EVT_ERROR;
488 }
489#endif
490
491 if (fPollEvt & RTPOLL_EVT_ERROR)
492 rc = vgsvcGstCtrlProcessHandleOutputError(pProcess, fPollEvt, phPipeR, idPollHnd);
493 return rc;
494}
495
496
497/**
498 * Execution loop which runs in a dedicated per-started-process thread and
499 * handles all pipe input/output and signalling stuff.
500 *
501 * @return IPRT status code.
502 * @param pProcess The guest process to handle.
503 */
504static int vgsvcGstCtrlProcessProcLoop(PVBOXSERVICECTRLPROCESS pProcess)
505{
506 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
507
508 int rc;
509 int rc2;
510 uint64_t const uMsStart = RTTimeMilliTS();
511 RTPROCSTATUS ProcessStatus = { 254, RTPROCEXITREASON_ABEND };
512 bool fProcessAlive = true;
513 bool fProcessTimedOut = false;
514 uint64_t MsProcessKilled = UINT64_MAX;
515 RTMSINTERVAL const cMsPollBase = pProcess->hPipeStdInW != NIL_RTPIPE
516 ? 100 /* Need to poll for input. */
517 : 1000; /* Need only poll for process exit and aborts. */
518 RTMSINTERVAL cMsPollCur = 0;
519
520 /*
521 * Assign PID to thread data.
522 * Also check if there already was a thread with the same PID and shut it down -- otherwise
523 * the first (stale) entry will be found and we get really weird results!
524 */
525 rc = vgsvcGstCtrlProcessAssignPID(pProcess, pProcess->hProcess /* Opaque PID handle */);
526 if (RT_FAILURE(rc))
527 {
528 VGSvcError("Unable to assign PID=%u, to new thread, rc=%Rrc\n", pProcess->hProcess, rc);
529 return rc;
530 }
531
532 /*
533 * Before entering the loop, tell the host that we've started the guest
534 * and that it's now OK to send input to the process.
535 */
536 VGSvcVerbose(2, "[PID %RU32]: Process '%s' started, CID=%u, User=%s, cMsTimeout=%RU32\n",
537 pProcess->uPID, pProcess->pStartupInfo->pszCmd, pProcess->uContextID,
538 pProcess->pStartupInfo->pszUser, pProcess->pStartupInfo->uTimeLimitMS);
539 VBGLR3GUESTCTRLCMDCTX ctxStart = { g_idControlSvcClient, pProcess->uContextID, 0 /* uProtocol */, 0 /* uNumParms */ };
540 rc = VbglR3GuestCtrlProcCbStatus(&ctxStart,
541 pProcess->uPID, PROC_STS_STARTED, 0 /* u32Flags */,
542 NULL /* pvData */, 0 /* cbData */);
543 if (rc == VERR_INTERRUPTED)
544 rc = VINF_SUCCESS; /* SIGCHLD send by quick childs! */
545 if (RT_FAILURE(rc))
546 VGSvcError("[PID %RU32]: Error reporting starting status to host, rc=%Rrc\n", pProcess->uPID, rc);
547
548 /*
549 * Process input, output, the test pipe and client requests.
550 */
551 while ( RT_SUCCESS(rc)
552 && RT_UNLIKELY(!pProcess->fShutdown))
553 {
554 /*
555 * Wait/Process all pending events.
556 */
557 uint32_t idPollHnd;
558 uint32_t fPollEvt;
559 rc2 = RTPollNoResume(pProcess->hPollSet, cMsPollCur, &fPollEvt, &idPollHnd);
560 if (pProcess->fShutdown)
561 continue;
562
563 cMsPollCur = 0; /* No rest until we've checked everything. */
564
565 if (RT_SUCCESS(rc2))
566 {
567 switch (idPollHnd)
568 {
569 case VBOXSERVICECTRLPIPEID_STDIN:
570 rc = vgsvcGstCtrlProcessPollsetOnInput(pProcess, fPollEvt, &pProcess->hPipeStdInW);
571 break;
572
573 case VBOXSERVICECTRLPIPEID_STDOUT:
574 rc = vgsvcGstCtrlProcessPollsetOnOutput(pProcess, fPollEvt, &pProcess->hPipeStdOutR, idPollHnd);
575 break;
576
577 case VBOXSERVICECTRLPIPEID_STDERR:
578 rc = vgsvcGstCtrlProcessPollsetOnOutput(pProcess, fPollEvt, &pProcess->hPipeStdErrR, idPollHnd);
579 break;
580
581 case VBOXSERVICECTRLPIPEID_IPC_NOTIFY:
582#ifdef DEBUG_andy
583 VGSvcVerbose(4, "[PID %RU32]: IPC notify\n", pProcess->uPID);
584#endif
585 rc2 = vgsvcGstCtrlProcessLock(pProcess);
586 if (RT_SUCCESS(rc2))
587 {
588 /* Drain the notification pipe. */
589 uint8_t abBuf[8];
590 size_t cbIgnore;
591 rc2 = RTPipeRead(pProcess->hNotificationPipeR, abBuf, sizeof(abBuf), &cbIgnore);
592 if (RT_FAILURE(rc2))
593 VGSvcError("Draining IPC notification pipe failed with rc=%Rrc\n", rc2);
594
595 /* Process all pending requests. */
596 VGSvcVerbose(4, "[PID %RU32]: Processing pending requests ...\n", pProcess->uPID);
597 Assert(pProcess->hReqQueue != NIL_RTREQQUEUE);
598 rc2 = RTReqQueueProcess(pProcess->hReqQueue,
599 0 /* Only process all pending requests, don't wait for new ones */);
600 if ( RT_FAILURE(rc2)
601 && rc2 != VERR_TIMEOUT)
602 VGSvcError("Processing requests failed with with rc=%Rrc\n", rc2);
603
604 int rc3 = vgsvcGstCtrlProcessUnlock(pProcess);
605 AssertRC(rc3);
606#ifdef DEBUG
607 VGSvcVerbose(4, "[PID %RU32]: Processing pending requests done, rc=%Rrc\n", pProcess->uPID, rc2);
608#endif
609 }
610
611 break;
612
613 default:
614 AssertMsgFailed(("Unknown idPollHnd=%RU32\n", idPollHnd));
615 break;
616 }
617
618 if (RT_FAILURE(rc) || rc == VINF_EOF)
619 break; /* Abort command, or client dead or something. */
620 }
621#if 0
622 VGSvcVerbose(4, "[PID %RU32]: Polling done, pollRc=%Rrc, pollCnt=%RU32, idPollHnd=%s, rc=%Rrc, fProcessAlive=%RTbool, fShutdown=%RTbool\n",
623 pProcess->uPID, rc2, RTPollSetGetCount(hPollSet), vgsvcGstCtrlProcessPollHandleToString(idPollHnd), rc, fProcessAlive, pProcess->fShutdown);
624 VGSvcVerbose(4, "[PID %RU32]: stdOut=%s, stdErrR=%s\n",
625 pProcess->uPID,
626 *phStdOutR == NIL_RTPIPE ? "closed" : "open",
627 *phStdErrR == NIL_RTPIPE ? "closed" : "open");
628#endif
629 if (RT_UNLIKELY(pProcess->fShutdown))
630 break; /* We were asked to shutdown. */
631
632 /*
633 * Check for process death.
634 */
635 if (fProcessAlive)
636 {
637 rc2 = RTProcWaitNoResume(pProcess->hProcess, RTPROCWAIT_FLAGS_NOBLOCK, &ProcessStatus);
638 if (RT_SUCCESS_NP(rc2))
639 {
640 fProcessAlive = false;
641 /* Note: Don't bail out here yet. First check in the next block below
642 * if all needed pipe outputs have been consumed. */
643 }
644 else
645 {
646 if (RT_UNLIKELY(rc2 == VERR_INTERRUPTED))
647 continue;
648 if (RT_UNLIKELY(rc2 == VERR_PROCESS_NOT_FOUND))
649 {
650 fProcessAlive = false;
651 ProcessStatus.enmReason = RTPROCEXITREASON_ABEND;
652 ProcessStatus.iStatus = 255;
653 AssertFailed();
654 }
655 else
656 AssertMsg(rc2 == VERR_PROCESS_RUNNING, ("%Rrc\n", rc2));
657 }
658 }
659
660 /*
661 * If the process has terminated and all output has been consumed,
662 * we should be heading out.
663 */
664 if (!fProcessAlive)
665 {
666 if ( fProcessTimedOut
667 || ( pProcess->hPipeStdOutR == NIL_RTPIPE
668 && pProcess->hPipeStdErrR == NIL_RTPIPE)
669 )
670 {
671 VGSvcVerbose(3, "[PID %RU32]: RTProcWaitNoResume=%Rrc\n", pProcess->uPID, rc2);
672 break;
673 }
674 }
675
676 /*
677 * Check for timed out, killing the process.
678 */
679 uint32_t cMilliesLeft = RT_INDEFINITE_WAIT;
680 if ( pProcess->pStartupInfo->uTimeLimitMS != RT_INDEFINITE_WAIT
681 && pProcess->pStartupInfo->uTimeLimitMS != 0)
682 {
683 uint64_t u64Now = RTTimeMilliTS();
684 uint64_t cMsElapsed = u64Now - uMsStart;
685 if (cMsElapsed >= pProcess->pStartupInfo->uTimeLimitMS)
686 {
687 fProcessTimedOut = true;
688 if ( MsProcessKilled == UINT64_MAX
689 || u64Now - MsProcessKilled > 1000)
690 {
691 if (u64Now - MsProcessKilled > 20*60*1000)
692 break; /* Give up after 20 mins. */
693
694 VGSvcVerbose(3, "[PID %RU32]: Timed out (%RU64ms elapsed > %RU32ms timeout), killing ...\n",
695 pProcess->uPID, cMsElapsed, pProcess->pStartupInfo->uTimeLimitMS);
696
697 rc2 = RTProcTerminate(pProcess->hProcess);
698 VGSvcVerbose(3, "[PID %RU32]: Killing process resulted in rc=%Rrc\n",
699 pProcess->uPID, rc2);
700 MsProcessKilled = u64Now;
701 continue;
702 }
703 cMilliesLeft = 10000;
704 }
705 else
706 cMilliesLeft = pProcess->pStartupInfo->uTimeLimitMS - (uint32_t)cMsElapsed;
707 }
708
709 /* Reset the polling interval since we've done all pending work. */
710 cMsPollCur = fProcessAlive
711 ? cMsPollBase
712 : RT_MS_1MIN;
713 if (cMilliesLeft < cMsPollCur)
714 cMsPollCur = cMilliesLeft;
715 }
716
717 VGSvcVerbose(3, "[PID %RU32]: Loop ended: rc=%Rrc, fShutdown=%RTbool, fProcessAlive=%RTbool, fProcessTimedOut=%RTbool, MsProcessKilled=%RU64 (%RX64)\n",
718 pProcess->uPID, rc, pProcess->fShutdown, fProcessAlive, fProcessTimedOut, MsProcessKilled, MsProcessKilled);
719 VGSvcVerbose(3, "[PID %RU32]: *phStdOutR=%s, *phStdErrR=%s\n",
720 pProcess->uPID,
721 pProcess->hPipeStdOutR == NIL_RTPIPE ? "closed" : "open",
722 pProcess->hPipeStdErrR == NIL_RTPIPE ? "closed" : "open");
723
724 /* Signal that this thread is in progress of shutting down. */
725 ASMAtomicWriteBool(&pProcess->fShutdown, true);
726
727 /*
728 * Try killing the process if it's still alive at this point.
729 */
730 if (fProcessAlive)
731 {
732 if (MsProcessKilled == UINT64_MAX)
733 {
734 VGSvcVerbose(2, "[PID %RU32]: Is still alive and not killed yet\n", pProcess->uPID);
735
736 MsProcessKilled = RTTimeMilliTS();
737 rc2 = RTProcTerminate(pProcess->hProcess);
738 if (rc2 == VERR_NOT_FOUND)
739 {
740 fProcessAlive = false;
741 }
742 else if (RT_FAILURE(rc2))
743 VGSvcError("[PID %RU32]: Killing process failed with rc=%Rrc\n", pProcess->uPID, rc2);
744 RTThreadSleep(500);
745 }
746
747 for (int i = 0; i < 10 && fProcessAlive; i++)
748 {
749 VGSvcVerbose(4, "[PID %RU32]: Kill attempt %d/10: Waiting to exit ...\n", pProcess->uPID, i + 1);
750 rc2 = RTProcWait(pProcess->hProcess, RTPROCWAIT_FLAGS_NOBLOCK, &ProcessStatus);
751 if (RT_SUCCESS(rc2))
752 {
753 VGSvcVerbose(4, "[PID %RU32]: Kill attempt %d/10: Exited\n", pProcess->uPID, i + 1);
754 fProcessAlive = false;
755 break;
756 }
757 if (i >= 5)
758 {
759 VGSvcVerbose(4, "[PID %RU32]: Kill attempt %d/10: Trying to terminate ...\n", pProcess->uPID, i + 1);
760 rc2 = RTProcTerminate(pProcess->hProcess);
761 if ( RT_FAILURE(rc)
762 && rc2 != VERR_NOT_FOUND)
763 VGSvcError("PID %RU32]: Killing process failed with rc=%Rrc\n",
764 pProcess->uPID, rc2);
765 }
766 RTThreadSleep(i >= 5 ? 2000 : 500);
767 }
768
769 if (fProcessAlive)
770 VGSvcError("[PID %RU32]: Could not be killed\n", pProcess->uPID);
771 }
772
773 /*
774 * Shutdown procedure:
775 * - Set the pProcess->fShutdown indicator to let others know we're
776 * not accepting any new requests anymore.
777 * - After setting the indicator, try to process all outstanding
778 * requests to make sure they're getting delivered.
779 *
780 * Note: After removing the process from the session's list it's not
781 * even possible for the session anymore to control what's
782 * happening to this thread, so be careful and don't mess it up.
783 */
784
785 rc2 = vgsvcGstCtrlProcessLock(pProcess);
786 if (RT_SUCCESS(rc2))
787 {
788 VGSvcVerbose(3, "[PID %RU32]: Processing outstanding requests ...\n", pProcess->uPID);
789
790 /* Process all pending requests (but don't wait for new ones). */
791 Assert(pProcess->hReqQueue != NIL_RTREQQUEUE);
792 rc2 = RTReqQueueProcess(pProcess->hReqQueue, 0 /* No timeout */);
793 if ( RT_FAILURE(rc2)
794 && rc2 != VERR_TIMEOUT)
795 VGSvcError("[PID %RU32]: Processing outstanding requests failed with with rc=%Rrc\n", pProcess->uPID, rc2);
796
797 VGSvcVerbose(3, "[PID %RU32]: Processing outstanding requests done, rc=%Rrc\n", pProcess->uPID, rc2);
798
799 rc2 = vgsvcGstCtrlProcessUnlock(pProcess);
800 AssertRC(rc2);
801 }
802
803 /*
804 * If we don't have a client problem (RT_FAILURE(rc)) we'll reply to the
805 * clients exec packet now.
806 */
807 if (RT_SUCCESS(rc))
808 {
809 uint32_t uStatus = PROC_STS_UNDEFINED;
810 uint32_t fFlags = 0;
811
812 if ( fProcessTimedOut && !fProcessAlive && MsProcessKilled != UINT64_MAX)
813 {
814 VGSvcVerbose(3, "[PID %RU32]: Timed out and got killed\n", pProcess->uPID);
815 uStatus = PROC_STS_TOK;
816 }
817 else if (fProcessTimedOut && fProcessAlive && MsProcessKilled != UINT64_MAX)
818 {
819 VGSvcVerbose(3, "[PID %RU32]: Timed out and did *not* get killed\n", pProcess->uPID);
820 uStatus = PROC_STS_TOA;
821 }
822 else if (pProcess->fShutdown && (fProcessAlive || MsProcessKilled != UINT64_MAX))
823 {
824 VGSvcVerbose(3, "[PID %RU32]: Got terminated because system/service is about to shutdown\n", pProcess->uPID);
825 uStatus = PROC_STS_DWN; /* Service is stopping, process was killed. */
826 fFlags = pProcess->pStartupInfo->fFlags; /* Return handed-in execution flags back to the host. */
827 }
828 else if (fProcessAlive)
829 VGSvcError("[PID %RU32]: Is alive when it should not!\n", pProcess->uPID);
830 else if (MsProcessKilled != UINT64_MAX)
831 VGSvcError("[PID %RU32]: Has been killed when it should not!\n", pProcess->uPID);
832 else if (ProcessStatus.enmReason == RTPROCEXITREASON_NORMAL)
833 {
834 VGSvcVerbose(3, "[PID %RU32]: Ended with RTPROCEXITREASON_NORMAL (Exit code: %d)\n",
835 pProcess->uPID, ProcessStatus.iStatus);
836 uStatus = PROC_STS_TEN;
837 fFlags = ProcessStatus.iStatus;
838 }
839 else if (ProcessStatus.enmReason == RTPROCEXITREASON_SIGNAL)
840 {
841 VGSvcVerbose(3, "[PID %RU32]: Ended with RTPROCEXITREASON_SIGNAL (Signal: %u)\n",
842 pProcess->uPID, ProcessStatus.iStatus);
843 uStatus = PROC_STS_TES;
844 fFlags = ProcessStatus.iStatus;
845 }
846 else if (ProcessStatus.enmReason == RTPROCEXITREASON_ABEND)
847 {
848 /* ProcessStatus.iStatus will be undefined. */
849 VGSvcVerbose(3, "[PID %RU32]: Ended with RTPROCEXITREASON_ABEND\n", pProcess->uPID);
850 uStatus = PROC_STS_TEA;
851 fFlags = ProcessStatus.iStatus;
852 }
853 else
854 VGSvcVerbose(1, "[PID %RU32]: Handling process status %u not implemented\n", pProcess->uPID, ProcessStatus.enmReason);
855 VBGLR3GUESTCTRLCMDCTX ctxEnd = { g_idControlSvcClient, pProcess->uContextID, 0 /* uProtocol */, 0 /* uNumParms */ };
856 VGSvcVerbose(2, "[PID %RU32]: Ended, ClientID=%u, CID=%u, Status=%u, Flags=0x%x\n",
857 pProcess->uPID, ctxEnd.uClientID, pProcess->uContextID, uStatus, fFlags);
858
859 rc2 = VbglR3GuestCtrlProcCbStatus(&ctxEnd, pProcess->uPID, uStatus, fFlags, NULL /* pvData */, 0 /* cbData */);
860 if ( RT_FAILURE(rc2)
861 && rc2 == VERR_NOT_FOUND)
862 VGSvcError("[PID %RU32]: Error reporting final status to host; rc=%Rrc\n", pProcess->uPID, rc2);
863 }
864
865 VGSvcVerbose(3, "[PID %RU32]: Process loop returned with rc=%Rrc\n", pProcess->uPID, rc);
866 return rc;
867}
868
869
870#if 0 /* unused */
871/**
872 * Initializes a pipe's handle and pipe object.
873 *
874 * @return IPRT status code.
875 * @param ph The pipe's handle to initialize.
876 * @param phPipe The pipe's object to initialize.
877 */
878static int vgsvcGstCtrlProcessInitPipe(PRTHANDLE ph, PRTPIPE phPipe)
879{
880 AssertPtrReturn(ph, VERR_INVALID_PARAMETER);
881 AssertPtrReturn(phPipe, VERR_INVALID_PARAMETER);
882
883 ph->enmType = RTHANDLETYPE_PIPE;
884 ph->u.hPipe = NIL_RTPIPE;
885 *phPipe = NIL_RTPIPE;
886
887 return VINF_SUCCESS;
888}
889#endif
890
891
892/**
893 * Sets up the redirection / pipe / nothing for one of the standard handles.
894 *
895 * @returns IPRT status code. No client replies made.
896 * @param pszHowTo How to set up this standard handle.
897 * @param fd Which standard handle it is (0 == stdin, 1 ==
898 * stdout, 2 == stderr).
899 * @param ph The generic handle that @a pph may be set
900 * pointing to. Always set.
901 * @param pph Pointer to the RTProcCreateExec argument.
902 * Always set.
903 * @param phPipe Where to return the end of the pipe that we
904 * should service.
905 */
906static int vgsvcGstCtrlProcessSetupPipe(const char *pszHowTo, int fd, PRTHANDLE ph, PRTHANDLE *pph, PRTPIPE phPipe)
907{
908 AssertPtrReturn(ph, VERR_INVALID_POINTER);
909 AssertPtrReturn(pph, VERR_INVALID_POINTER);
910 AssertPtrReturn(phPipe, VERR_INVALID_POINTER);
911
912 int rc;
913
914 ph->enmType = RTHANDLETYPE_PIPE;
915 ph->u.hPipe = NIL_RTPIPE;
916 *pph = NULL;
917 *phPipe = NIL_RTPIPE;
918
919 if (!strcmp(pszHowTo, "|"))
920 {
921 /*
922 * Setup a pipe for forwarding to/from the client.
923 * The ph union struct will be filled with a pipe read/write handle
924 * to represent the "other" end to phPipe.
925 */
926 if (fd == 0) /* stdin? */
927 {
928 /* Connect a wrtie pipe specified by phPipe to stdin. */
929 rc = RTPipeCreate(&ph->u.hPipe, phPipe, RTPIPE_C_INHERIT_READ);
930 }
931 else /* stdout or stderr. */
932 {
933 /* Connect a read pipe specified by phPipe to stdout or stderr. */
934 rc = RTPipeCreate(phPipe, &ph->u.hPipe, RTPIPE_C_INHERIT_WRITE);
935 }
936
937 if (RT_FAILURE(rc))
938 return rc;
939
940 ph->enmType = RTHANDLETYPE_PIPE;
941 *pph = ph;
942 }
943 else if (!strcmp(pszHowTo, "/dev/null"))
944 {
945 /*
946 * Redirect to/from /dev/null.
947 */
948 RTFILE hFile;
949 rc = RTFileOpenBitBucket(&hFile, fd == 0 ? RTFILE_O_READ : RTFILE_O_WRITE);
950 if (RT_FAILURE(rc))
951 return rc;
952
953 ph->enmType = RTHANDLETYPE_FILE;
954 ph->u.hFile = hFile;
955 *pph = ph;
956 }
957 else /* Add other piping stuff here. */
958 rc = VINF_SUCCESS; /* Same as parent (us). */
959
960 return rc;
961}
962
963
964/**
965 * Expands a file name / path to its real content. This only works on Windows
966 * for now (e.g. translating "%TEMP%\foo.exe" to "C:\Windows\Temp" when starting
967 * with system / administrative rights).
968 *
969 * @return IPRT status code.
970 * @param pszPath Path to resolve.
971 * @param pszExpanded Pointer to string to store the resolved path in.
972 * @param cbExpanded Size (in bytes) of string to store the resolved path.
973 */
974static int vgsvcGstCtrlProcessMakeFullPath(const char *pszPath, char *pszExpanded, size_t cbExpanded)
975{
976 int rc = VINF_SUCCESS;
977/** @todo r=bird: This feature shall be made optional, i.e. require a
978 * flag to be passed down. Further, it shall work on the environment
979 * block of the new process (i.e. include env changes passed down from
980 * the caller). I would also suggest using the unix variable expansion
981 * syntax, not the DOS one.
982 *
983 * Since this currently not available on non-windows guests, I suggest
984 * we disable it until such a time as it is implemented correctly. */
985#ifdef RT_OS_WINDOWS
986 if (!ExpandEnvironmentStrings(pszPath, pszExpanded, (DWORD)cbExpanded))
987 rc = RTErrConvertFromWin32(GetLastError());
988#else
989 /* No expansion for non-Windows yet. */
990 rc = RTStrCopy(pszExpanded, cbExpanded, pszPath);
991#endif
992#ifdef DEBUG
993 VGSvcVerbose(3, "vgsvcGstCtrlProcessMakeFullPath: %s -> %s\n", pszPath, pszExpanded);
994#endif
995 return rc;
996}
997
998
999/**
1000 * Resolves the full path of a specified executable name. This function also
1001 * resolves internal VBoxService tools to its appropriate executable path + name if
1002 * VBOXSERVICE_NAME is specified as pszFileName.
1003 *
1004 * @return IPRT status code.
1005 * @param pszFileName File name to resolve.
1006 * @param pszResolved Pointer to a string where the resolved file name will be stored.
1007 * @param cbResolved Size (in bytes) of resolved file name string.
1008 */
1009static int vgsvcGstCtrlProcessResolveExecutable(const char *pszFileName, char *pszResolved, size_t cbResolved)
1010{
1011 AssertPtrReturn(pszFileName, VERR_INVALID_POINTER);
1012 AssertPtrReturn(pszResolved, VERR_INVALID_POINTER);
1013 AssertReturn(cbResolved, VERR_INVALID_PARAMETER);
1014
1015 int rc = VINF_SUCCESS;
1016
1017 char szPathToResolve[RTPATH_MAX];
1018 if ( (g_pszProgName && (RTStrICmp(pszFileName, g_pszProgName) == 0))
1019 || !RTStrICmp(pszFileName, VBOXSERVICE_NAME))
1020 {
1021 /* Resolve executable name of this process. */
1022 if (!RTProcGetExecutablePath(szPathToResolve, sizeof(szPathToResolve)))
1023 rc = VERR_FILE_NOT_FOUND;
1024 }
1025 else
1026 {
1027 /* Take the raw argument to resolve. */
1028 rc = RTStrCopy(szPathToResolve, sizeof(szPathToResolve), pszFileName);
1029 }
1030
1031 if (RT_SUCCESS(rc))
1032 {
1033 rc = vgsvcGstCtrlProcessMakeFullPath(szPathToResolve, pszResolved, cbResolved);
1034 if (RT_SUCCESS(rc))
1035 VGSvcVerbose(3, "Looked up executable: %s -> %s\n", pszFileName, pszResolved);
1036 }
1037
1038 if (RT_FAILURE(rc))
1039 VGSvcError("Failed to lookup executable '%s' with rc=%Rrc\n", pszFileName, rc);
1040 return rc;
1041}
1042
1043
1044/**
1045 * Constructs the argv command line by resolving environment variables
1046 * and relative paths.
1047 *
1048 * @return IPRT status code.
1049 * @param pszArgv0 First argument (argv0), either original or modified version.
1050 * @param papszArgs Original argv command line from the host, starting at argv[1].
1051 * @param fFlags The process creation flags pass to us from the host.
1052 * @param ppapszArgv Pointer to a pointer with the new argv command line.
1053 * Needs to be freed with RTGetOptArgvFree.
1054 */
1055static int vgsvcGstCtrlProcessAllocateArgv(const char *pszArgv0, const char * const *papszArgs, uint32_t fFlags,
1056 char ***ppapszArgv)
1057{
1058 VGSvcVerbose(3, "VGSvcGstCtrlProcessPrepareArgv: pszArgv0=%p, papszArgs=%p, fFlags=%#x, ppapszArgv=%p\n",
1059 pszArgv0, papszArgs, fFlags, ppapszArgv);
1060
1061 AssertPtrReturn(pszArgv0, VERR_INVALID_POINTER);
1062 AssertPtrReturn(ppapszArgv, VERR_INVALID_POINTER);
1063
1064 int rc = VINF_SUCCESS;
1065 uint32_t cArgs;
1066 for (cArgs = 0; papszArgs[cArgs]; cArgs++)
1067 {
1068 if (cArgs >= UINT32_MAX - 2)
1069 return VERR_BUFFER_OVERFLOW;
1070 }
1071
1072 /* Allocate new argv vector (adding + 2 for argv0 + termination). */
1073 size_t cbSize = (cArgs + 2) * sizeof(char *);
1074 char **papszNewArgv = (char **)RTMemAlloc(cbSize);
1075 if (!papszNewArgv)
1076 return VERR_NO_MEMORY;
1077
1078 VGSvcVerbose(3, "VGSvcGstCtrlProcessAllocateArgv: pszArgv0 = '%s', cArgs=%RU32, cbSize=%zu\n", pszArgv0, cArgs, cbSize);
1079#ifdef DEBUG /* Never log this stuff in release mode! */
1080 if (cArgs)
1081 {
1082 for (uint32_t i = 0; i < cArgs; i++)
1083 VGSvcVerbose(3, "VGSvcGstCtrlProcessAllocateArgv: papszArgs[%RU32] = '%s'\n", i, papszArgs[i]);
1084 }
1085#endif
1086
1087 /* HACK ALERT! Older hosts (< VBox 6.1.x) did not allow the user to really specify the first
1088 argument separately from the executable image, so we have to fudge
1089 a little in the unquoted argument case to deal with executables
1090 containing spaces. */
1091 if ( !(fFlags & EXECUTEPROCESSFLAG_UNQUOTED_ARGS)
1092 || !strpbrk(pszArgv0, " \t\n\r")
1093 || pszArgv0[0] == '"')
1094 {
1095 rc = RTStrDupEx(&papszNewArgv[0], pszArgv0);
1096 }
1097 else
1098 {
1099 size_t cchArgv0 = strlen(pszArgv0);
1100 AssertReturn(cchArgv0, VERR_INVALID_PARAMETER); /* Paranoia. */
1101 rc = RTStrAllocEx(&papszNewArgv[0], 1 + cchArgv0 + 1 + 1);
1102 if (RT_SUCCESS(rc))
1103 {
1104 char *pszDst = papszNewArgv[0];
1105 *pszDst++ = '"';
1106 memcpy(pszDst, pszArgv0, cchArgv0);
1107 pszDst += cchArgv0;
1108 *pszDst++ = '"';
1109 *pszDst = '\0';
1110 }
1111 }
1112
1113 if (RT_SUCCESS(rc))
1114 {
1115 size_t i;
1116 for (i = 0; i < cArgs; i++)
1117 {
1118 char *pszArg;
1119#if 0 /* Arguments expansion -- untested. */
1120 if (fFlags & EXECUTEPROCESSFLAG_EXPAND_ARGUMENTS)
1121 {
1122/** @todo r=bird: If you want this, we need a generic implementation, preferably in RTEnv or somewhere like that. The marking
1123 * up of the variables must be the same on all platforms. */
1124 /* According to MSDN the limit on older Windows version is 32K, whereas
1125 * Vista+ there are no limits anymore. We still stick to 4K. */
1126 char szExpanded[_4K];
1127# ifdef RT_OS_WINDOWS
1128 if (!ExpandEnvironmentStrings(papszArgs[i], szExpanded, sizeof(szExpanded)))
1129 rc = RTErrConvertFromWin32(GetLastError());
1130# else
1131 /* No expansion for non-Windows yet. */
1132 rc = RTStrCopy(papszArgs[i], sizeof(szExpanded), szExpanded);
1133# endif
1134 if (RT_SUCCESS(rc))
1135 rc = RTStrDupEx(&pszArg, szExpanded);
1136 }
1137 else
1138#endif
1139 rc = RTStrDupEx(&pszArg, papszArgs[i]);
1140
1141 if (RT_FAILURE(rc))
1142 break;
1143
1144 papszNewArgv[i + 1] = pszArg;
1145 }
1146
1147 if (RT_SUCCESS(rc))
1148 {
1149 /* Terminate array. */
1150 papszNewArgv[cArgs + 1] = NULL;
1151
1152 *ppapszArgv = papszNewArgv;
1153 return VINF_SUCCESS;
1154 }
1155
1156 /* Failed, bail out. */
1157 for (; i > 0; i--)
1158 RTStrFree(papszNewArgv[i]);
1159 }
1160 RTMemFree(papszNewArgv);
1161 return rc;
1162}
1163
1164
1165/**
1166 * Assigns a valid PID to a guest control thread and also checks if there already was
1167 * another (stale) guest process which was using that PID before and destroys it.
1168 *
1169 * @return IPRT status code.
1170 * @param pProcess Process to assign PID to.
1171 * @param uPID PID to assign to the specified guest control execution thread.
1172 */
1173static int vgsvcGstCtrlProcessAssignPID(PVBOXSERVICECTRLPROCESS pProcess, uint32_t uPID)
1174{
1175 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
1176 AssertReturn(uPID, VERR_INVALID_PARAMETER);
1177
1178 AssertPtr(pProcess->pSession);
1179 int rc = RTCritSectEnter(&pProcess->pSession->CritSect);
1180 if (RT_SUCCESS(rc))
1181 {
1182 /* Search old threads using the desired PID and shut them down completely -- it's
1183 * not used anymore. */
1184 bool fTryAgain;
1185 do
1186 {
1187 fTryAgain = false;
1188 PVBOXSERVICECTRLPROCESS pProcessCur;
1189 RTListForEach(&pProcess->pSession->lstProcesses, pProcessCur, VBOXSERVICECTRLPROCESS, Node)
1190 {
1191 if (pProcessCur->uPID == uPID)
1192 {
1193 Assert(pProcessCur != pProcess); /* can't happen */
1194 uint32_t uTriedPID = uPID;
1195 uPID += 391939;
1196 VGSvcVerbose(2, "PID %RU32 was used before (process %p), trying again with %RU32 ...\n",
1197 uTriedPID, pProcessCur, uPID);
1198 fTryAgain = true;
1199 break;
1200 }
1201 }
1202 } while (fTryAgain);
1203
1204 /* Assign PID to current thread. */
1205 pProcess->uPID = uPID;
1206
1207 rc = RTCritSectLeave(&pProcess->pSession->CritSect);
1208 AssertRC(rc);
1209 }
1210
1211 return rc;
1212}
1213
1214
1215static void vgsvcGstCtrlProcessFreeArgv(char **papszArgv)
1216{
1217 if (papszArgv)
1218 {
1219 size_t i = 0;
1220 while (papszArgv[i])
1221 RTStrFree(papszArgv[i++]);
1222 RTMemFree(papszArgv);
1223 }
1224}
1225
1226
1227/**
1228 * Helper function to create/start a process on the guest.
1229 *
1230 * @return IPRT status code.
1231 * @param pszExec Full qualified path of process to start (without arguments).
1232 * @param papszArgs Pointer to array of command line arguments.
1233 * @param hEnv Handle to environment block to use.
1234 * @param fFlags Process execution flags.
1235 * @param phStdIn Handle for the process' stdin pipe.
1236 * @param phStdOut Handle for the process' stdout pipe.
1237 * @param phStdErr Handle for the process' stderr pipe.
1238 * @param pszAsUser User name (account) to start the process under.
1239 * @param pszPassword Password of the specified user.
1240 * @param pszDomain Domain to use for authentication.
1241 * @param phProcess Pointer which will receive the process handle after
1242 * successful process start.
1243 */
1244static int vgsvcGstCtrlProcessCreateProcess(const char *pszExec, const char * const *papszArgs, RTENV hEnv, uint32_t fFlags,
1245 PCRTHANDLE phStdIn, PCRTHANDLE phStdOut, PCRTHANDLE phStdErr,
1246 const char *pszAsUser, const char *pszPassword, const char *pszDomain,
1247 PRTPROCESS phProcess)
1248{
1249#ifndef RT_OS_WINDOWS
1250 RT_NOREF1(pszDomain);
1251#endif
1252 AssertPtrReturn(pszExec, VERR_INVALID_PARAMETER);
1253 AssertPtrReturn(papszArgs, VERR_INVALID_PARAMETER);
1254 /* phStdIn is optional. */
1255 /* phStdOut is optional. */
1256 /* phStdErr is optional. */
1257 /* pszPassword is optional. */
1258 /* pszDomain is optional. */
1259 AssertPtrReturn(phProcess, VERR_INVALID_PARAMETER);
1260
1261 int rc = VINF_SUCCESS;
1262 char szExecExp[RTPATH_MAX];
1263
1264#ifdef DEBUG
1265 /* Never log this in release mode! */
1266 VGSvcVerbose(4, "pszUser=%s, pszPassword=%s, pszDomain=%s\n", pszAsUser, pszPassword, pszDomain);
1267#endif
1268
1269#ifdef RT_OS_WINDOWS
1270 /*
1271 * If sysprep should be executed do this in the context of VBoxService, which
1272 * (usually, if started by SCM) has administrator rights. Because of that a UI
1273 * won't be shown (doesn't have a desktop).
1274 */
1275 if (!RTStrICmp(pszExec, "sysprep"))
1276 {
1277 /* Use a predefined sysprep path as default. */
1278 char szSysprepCmd[RTPATH_MAX] = "C:\\sysprep\\sysprep.exe";
1279 /** @todo Check digital signature of file above before executing it? */
1280
1281 /*
1282 * On Windows Vista (and up) sysprep is located in "system32\\Sysprep\\sysprep.exe",
1283 * so detect the OS and use a different path.
1284 */
1285 OSVERSIONINFOEX OSInfoEx;
1286 RT_ZERO(OSInfoEx);
1287 OSInfoEx.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
1288 BOOL fRet = GetVersionEx((LPOSVERSIONINFO) &OSInfoEx);
1289 if ( fRet
1290 && OSInfoEx.dwPlatformId == VER_PLATFORM_WIN32_NT
1291 && OSInfoEx.dwMajorVersion >= 6 /* Vista or later */)
1292 {
1293 rc = RTEnvGetEx(RTENV_DEFAULT, "windir", szSysprepCmd, sizeof(szSysprepCmd), NULL);
1294#ifndef RT_ARCH_AMD64
1295 /* Don't execute 64-bit sysprep from a 32-bit service host! */
1296 char szSysWow64[RTPATH_MAX];
1297 if (RTStrPrintf(szSysWow64, sizeof(szSysWow64), "%s", szSysprepCmd))
1298 {
1299 rc = RTPathAppend(szSysWow64, sizeof(szSysWow64), "SysWow64");
1300 AssertRC(rc);
1301 }
1302 if ( RT_SUCCESS(rc)
1303 && RTPathExists(szSysWow64))
1304 VGSvcVerbose(0, "Warning: This service is 32-bit; could not execute sysprep on 64-bit OS!\n");
1305#endif
1306 if (RT_SUCCESS(rc))
1307 rc = RTPathAppend(szSysprepCmd, sizeof(szSysprepCmd), "system32\\Sysprep\\sysprep.exe");
1308 if (RT_SUCCESS(rc))
1309 RTPathChangeToDosSlashes(szSysprepCmd, false /* No forcing necessary */);
1310
1311 if (RT_FAILURE(rc))
1312 VGSvcError("Failed to detect sysrep location, rc=%Rrc\n", rc);
1313 }
1314 else if (!fRet)
1315 VGSvcError("Failed to retrieve OS information, last error=%ld\n", GetLastError());
1316
1317 VGSvcVerbose(3, "Sysprep executable is: %s\n", szSysprepCmd);
1318
1319 if (RT_SUCCESS(rc))
1320 {
1321 char **papszArgsExp;
1322 rc = vgsvcGstCtrlProcessAllocateArgv(szSysprepCmd /* argv0 */, papszArgs, fFlags, &papszArgsExp);
1323 if (RT_SUCCESS(rc))
1324 {
1325 /* As we don't specify credentials for the sysprep process, it will
1326 * run under behalf of the account VBoxService was started under, most
1327 * likely local system. */
1328 rc = RTProcCreateEx(szSysprepCmd, papszArgsExp, hEnv, 0 /* fFlags */,
1329 phStdIn, phStdOut, phStdErr, NULL /* pszAsUser */,
1330 NULL /* pszPassword */, NULL, phProcess);
1331 vgsvcGstCtrlProcessFreeArgv(papszArgsExp);
1332 }
1333 }
1334
1335 if (RT_FAILURE(rc))
1336 VGSvcVerbose(3, "Starting sysprep returned rc=%Rrc\n", rc);
1337
1338 return rc;
1339 }
1340#endif /* RT_OS_WINDOWS */
1341
1342#ifdef VBOX_WITH_VBOXSERVICE_TOOLBOX
1343 if (RTStrStr(pszExec, "vbox_") == pszExec)
1344 {
1345 /* We want to use the internal toolbox (all internal
1346 * tools are starting with "vbox_" (e.g. "vbox_cat"). */
1347 rc = vgsvcGstCtrlProcessResolveExecutable(VBOXSERVICE_NAME, szExecExp, sizeof(szExecExp));
1348 }
1349 else
1350 {
1351#endif
1352 /*
1353 * Do the environment variables expansion on executable and arguments.
1354 */
1355 rc = vgsvcGstCtrlProcessResolveExecutable(pszExec, szExecExp, sizeof(szExecExp));
1356#ifdef VBOX_WITH_VBOXSERVICE_TOOLBOX
1357 }
1358#endif
1359 if (RT_SUCCESS(rc))
1360 {
1361 /**
1362 * This one is a bit tricky to also support older hosts:
1363 *
1364 * - If the host does not provide a dedicated argv[0] (< VBox 6.1.x), we use the
1365 * unmodified executable name (pszExec) as the (default) argv[0]. This is wrong, but we can't do
1366 * much about it. The rest (argv[1,2,n]) then gets set starting at papszArgs[0].
1367 *
1368 * - Newer hosts (>= VBox 6.1.x) provide a correct argv[0] independently of the actual
1369 * executable name though, so actually use argv[0] *and* argv[1,2,n] as intended.
1370 */
1371 const bool fHasArgv0 = RT_BOOL(g_fControlHostFeatures0 & VBOX_GUESTCTRL_HF_0_PROCESS_ARGV0);
1372
1373 const char *pcszArgv0 = (fHasArgv0 && papszArgs[0]) ? papszArgs[0] : pszExec;
1374 AssertPtrReturn(pcszArgv0, VERR_INVALID_POINTER); /* Paranoia. */
1375
1376 const uint32_t uArgvIdx = pcszArgv0 == papszArgs[0] ? 1 : 0;
1377
1378 VGSvcVerbose(3, "vgsvcGstCtrlProcessCreateProcess: fHasArgv0=%RTbool, pcszArgv0=%p, uArgvIdx=%RU32, "
1379 "g_fControlHostFeatures0=%#x\n",
1380 fHasArgv0, pcszArgv0, uArgvIdx, g_fControlHostFeatures0);
1381
1382 char **papszArgsExp;
1383 rc = vgsvcGstCtrlProcessAllocateArgv(pcszArgv0, &papszArgs[uArgvIdx], fFlags, &papszArgsExp);
1384 if (RT_FAILURE(rc))
1385 {
1386 /* Don't print any arguments -- may contain passwords or other sensible data! */
1387 VGSvcError("Could not prepare arguments, rc=%Rrc\n", rc);
1388 }
1389 else
1390 {
1391 uint32_t uProcFlags = 0;
1392 if (fFlags)
1393 {
1394 if (fFlags & EXECUTEPROCESSFLAG_HIDDEN)
1395 uProcFlags |= RTPROC_FLAGS_HIDDEN;
1396 if (fFlags & EXECUTEPROCESSFLAG_PROFILE)
1397 uProcFlags |= RTPROC_FLAGS_PROFILE;
1398 if (fFlags & EXECUTEPROCESSFLAG_UNQUOTED_ARGS)
1399 uProcFlags |= RTPROC_FLAGS_UNQUOTED_ARGS;
1400 }
1401
1402 /* If no user name specified run with current credentials (e.g.
1403 * full service/system rights). This is prohibited via official Main API!
1404 *
1405 * Otherwise use the RTPROC_FLAGS_SERVICE to use some special authentication
1406 * code (at least on Windows) for running processes as different users
1407 * started from our system service. */
1408 if (pszAsUser && *pszAsUser)
1409 uProcFlags |= RTPROC_FLAGS_SERVICE;
1410#ifdef DEBUG
1411 VGSvcVerbose(3, "Command: %s\n", szExecExp);
1412 for (size_t i = 0; papszArgsExp[i]; i++)
1413 VGSvcVerbose(3, "\targv[%ld]: %s\n", i, papszArgsExp[i]);
1414#endif
1415 VGSvcVerbose(3, "Starting process '%s' ...\n", szExecExp);
1416
1417 const char *pszUser = pszAsUser;
1418#ifdef RT_OS_WINDOWS
1419 /* If a domain name is given, construct an UPN (User Principle Name) with
1420 * the domain name built-in, e.g. "[email protected]". */
1421 char *pszUserUPN = NULL;
1422 if ( pszDomain
1423 && strlen(pszDomain))
1424 {
1425 int cbUserUPN = RTStrAPrintf(&pszUserUPN, "%s@%s", pszAsUser, pszDomain);
1426 if (cbUserUPN > 0)
1427 {
1428 pszUser = pszUserUPN;
1429 VGSvcVerbose(3, "Using UPN: %s\n", pszUserUPN);
1430 }
1431 }
1432#endif
1433
1434 /* Do normal execution. */
1435 rc = RTProcCreateEx(szExecExp, papszArgsExp, hEnv, uProcFlags,
1436 phStdIn, phStdOut, phStdErr,
1437 pszUser,
1438 pszPassword && *pszPassword ? pszPassword : NULL,
1439 NULL /*pvExtraData*/,
1440 phProcess);
1441#ifdef RT_OS_WINDOWS
1442 if (pszUserUPN)
1443 RTStrFree(pszUserUPN);
1444#endif
1445 VGSvcVerbose(3, "Starting process '%s' returned rc=%Rrc\n", szExecExp, rc);
1446
1447 vgsvcGstCtrlProcessFreeArgv(papszArgsExp);
1448 }
1449 }
1450 return rc;
1451}
1452
1453
1454#ifdef DEBUG
1455/**
1456 * Dumps content to a file in the OS temporary directory.
1457 *
1458 * @returns VBox status code.
1459 * @param pvBuf Buffer of content to dump.
1460 * @param cbBuf Size (in bytes) of content to dump.
1461 * @param pszFileNmFmt Pointer to the file name format string, @see pg_rt_str_format.
1462 * @param ... The format argument.
1463 */
1464static int vgsvcGstCtrlProcessDbgDumpToFileF(const void *pvBuf, size_t cbBuf, const char *pszFileNmFmt, ...)
1465{
1466 AssertPtrReturn(pszFileNmFmt, VERR_INVALID_POINTER);
1467 AssertPtrReturn(pvBuf, VERR_INVALID_POINTER);
1468
1469 if (!cbBuf)
1470 return VINF_SUCCESS;
1471
1472 va_list va;
1473 va_start(va, pszFileNmFmt);
1474
1475 char *pszFileName = NULL;
1476 const int cchFileName = RTStrAPrintfV(&pszFileName, pszFileNmFmt, va);
1477
1478 va_end(va);
1479
1480 if (!cchFileName)
1481 return VERR_NO_MEMORY;
1482
1483 char szPathFileAbs[RTPATH_MAX];
1484 int rc = RTPathTemp(szPathFileAbs, sizeof(szPathFileAbs));
1485 if (RT_SUCCESS(rc))
1486 rc = RTPathAppend(szPathFileAbs, sizeof(szPathFileAbs), pszFileName);
1487
1488 RTStrFree(pszFileName);
1489
1490 if (RT_SUCCESS(rc))
1491 {
1492 VGSvcVerbose(4, "Dumping %zu bytes to '%s'\n", cbBuf, szPathFileAbs);
1493
1494 RTFILE fh;
1495 rc = RTFileOpen(&fh, szPathFileAbs, RTFILE_O_OPEN_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_WRITE);
1496 if (RT_SUCCESS(rc))
1497 {
1498 rc = RTFileWrite(fh, pvBuf, cbBuf, NULL /* pcbWritten */);
1499 RTFileClose(fh);
1500 }
1501 }
1502
1503 return rc;
1504}
1505#endif /* DEBUG */
1506
1507
1508/**
1509 * The actual worker routine (loop) for a started guest process.
1510 *
1511 * @return IPRT status code.
1512 * @param pProcess The process we're servicing and monitoring.
1513 */
1514static int vgsvcGstCtrlProcessProcessWorker(PVBOXSERVICECTRLPROCESS pProcess)
1515{
1516 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
1517 VGSvcVerbose(3, "Thread of process pThread=0x%p = '%s' started\n", pProcess, pProcess->pStartupInfo->pszCmd);
1518
1519 VGSvcVerbose(3, "Guest process '%s', flags=0x%x\n", pProcess->pStartupInfo->pszCmd, pProcess->pStartupInfo->fFlags);
1520
1521 int rc = VGSvcGstCtrlSessionProcessAdd(pProcess->pSession, pProcess);
1522 if (RT_FAILURE(rc))
1523 {
1524 VGSvcError("Error while adding guest process '%s' (%p) to session process list, rc=%Rrc\n",
1525 pProcess->pStartupInfo->pszCmd, pProcess, rc);
1526 RTThreadUserSignal(RTThreadSelf());
1527 return rc;
1528 }
1529
1530 bool fSignalled = false; /* Indicator whether we signalled the thread user event already. */
1531
1532 /*
1533 * Prepare argument list.
1534 */
1535 VGSvcVerbose(3, "vgsvcGstCtrlProcessProcessWorker: fHostFeatures0 = %#x\n", g_fControlHostFeatures0);
1536 VGSvcVerbose(3, "vgsvcGstCtrlProcessProcessWorker: StartupInfo.szCmd = '%s'\n", pProcess->pStartupInfo->pszCmd);
1537 VGSvcVerbose(3, "vgsvcGstCtrlProcessProcessWorker: StartupInfo.uNumArgs = '%RU32'\n", pProcess->pStartupInfo->cArgs);
1538#ifdef DEBUG /* Never log this stuff in release mode! */
1539 VGSvcVerbose(3, "vgsvcGstCtrlProcessProcessWorker: StartupInfo.szArgs = '%s'\n", pProcess->pStartupInfo->pszArgs);
1540#endif
1541
1542 char **papszArgs;
1543 int cArgs = 0; /* Initialize in case of RTGetOptArgvFromString() is failing ... */
1544 rc = RTGetOptArgvFromString(&papszArgs, &cArgs,
1545 pProcess->pStartupInfo->cArgs > 0 ? pProcess->pStartupInfo->pszArgs : "",
1546 RTGETOPTARGV_CNV_QUOTE_BOURNE_SH, NULL);
1547
1548 VGSvcVerbose(3, "vgsvcGstCtrlProcessProcessWorker: cArgs = %d\n", cArgs);
1549#ifdef VBOX_STRICT
1550 for (int i = 0; i < cArgs; i++)
1551 VGSvcVerbose(3, "vgsvcGstCtrlProcessProcessWorker: papszArgs[%d] = '%s'\n", i, papszArgs[i] ? papszArgs[i] : "<NULL>");
1552
1553 const bool fHasArgv0 = RT_BOOL(g_fControlHostFeatures0 & VBOX_GUESTCTRL_HF_0_PROCESS_ARGV0); RT_NOREF(fHasArgv0);
1554 const int cArgsToCheck = cArgs + (fHasArgv0 ? 0 : 1);
1555
1556 /* Did we get the same result?
1557 * Take into account that we might not have supplied a (correct) argv[0] from the host. */
1558 AssertMsg((int)pProcess->pStartupInfo->cArgs == cArgsToCheck,
1559 ("rc=%Rrc, StartupInfo.uNumArgs=%RU32 != cArgsToCheck=%d, cArgs=%d, fHostFeatures0=%#x\n",
1560 rc, pProcess->pStartupInfo->cArgs, cArgsToCheck, cArgs, g_fControlHostFeatures0));
1561#endif
1562
1563 /*
1564 * Create the environment.
1565 */
1566 uint32_t const cbEnv = pProcess->pStartupInfo->cbEnv;
1567 if (RT_SUCCESS(rc))
1568 AssertStmt( cbEnv <= GUESTPROCESS_MAX_ENV_LEN
1569 || pProcess->pStartupInfo->cEnvVars == 0,
1570 rc = VERR_INVALID_PARAMETER);
1571 if (RT_SUCCESS(rc))
1572 {
1573 RTENV hEnv;
1574 rc = RTEnvClone(&hEnv, RTENV_DEFAULT);
1575 if (RT_SUCCESS(rc))
1576 {
1577 VGSvcVerbose(3, "Additional environment variables: %RU32 (%RU32 bytes)\n",
1578 pProcess->pStartupInfo->cEnvVars, cbEnv);
1579
1580 if ( pProcess->pStartupInfo->cEnvVars
1581 && cbEnv > 0)
1582 {
1583 size_t offCur = 0;
1584 while (offCur < cbEnv)
1585 {
1586 const char * const pszCur = &pProcess->pStartupInfo->pszEnv[offCur];
1587 size_t const cchCur = RTStrNLen(pszCur, cbEnv - offCur);
1588 AssertBreakStmt(cchCur < cbEnv - offCur, rc = VERR_INVALID_PARAMETER);
1589 VGSvcVerbose(3, "Setting environment variable: '%s'\n", pszCur);
1590 rc = RTEnvPutEx(hEnv, pszCur);
1591 if (RT_SUCCESS(rc))
1592 offCur += cchCur + 1;
1593 else
1594 {
1595 VGSvcError("Setting environment variable '%s' failed: %Rrc\n", pszCur, rc);
1596 break;
1597 }
1598 }
1599 }
1600
1601 if (RT_SUCCESS(rc))
1602 {
1603 /*
1604 * Setup the redirection of the standard stuff.
1605 */
1606 /** @todo consider supporting: gcc stuff.c >file 2>&1. */
1607 RTHANDLE hStdIn;
1608 PRTHANDLE phStdIn;
1609 rc = vgsvcGstCtrlProcessSetupPipe("|", 0 /*STDIN_FILENO*/,
1610 &hStdIn, &phStdIn, &pProcess->hPipeStdInW);
1611 if (RT_SUCCESS(rc))
1612 {
1613 RTHANDLE hStdOut;
1614 PRTHANDLE phStdOut;
1615 rc = vgsvcGstCtrlProcessSetupPipe( (pProcess->pStartupInfo->fFlags & EXECUTEPROCESSFLAG_WAIT_STDOUT)
1616 ? "|" : "/dev/null",
1617 1 /*STDOUT_FILENO*/,
1618 &hStdOut, &phStdOut, &pProcess->hPipeStdOutR);
1619 if (RT_SUCCESS(rc))
1620 {
1621 RTHANDLE hStdErr;
1622 PRTHANDLE phStdErr;
1623 rc = vgsvcGstCtrlProcessSetupPipe( (pProcess->pStartupInfo->fFlags & EXECUTEPROCESSFLAG_WAIT_STDERR)
1624 ? "|" : "/dev/null",
1625 2 /*STDERR_FILENO*/,
1626 &hStdErr, &phStdErr, &pProcess->hPipeStdErrR);
1627 if (RT_SUCCESS(rc))
1628 {
1629 /*
1630 * Create a poll set for the pipes and let the
1631 * transport layer add stuff to it as well.
1632 */
1633 rc = RTPollSetCreate(&pProcess->hPollSet);
1634 if (RT_SUCCESS(rc))
1635 {
1636 uint32_t uFlags = RTPOLL_EVT_ERROR;
1637#if 0
1638 /* Add reading event to pollset to get some more information. */
1639 uFlags |= RTPOLL_EVT_READ;
1640#endif
1641 /* Stdin. */
1642 if (RT_SUCCESS(rc))
1643 rc = RTPollSetAddPipe(pProcess->hPollSet,
1644 pProcess->hPipeStdInW, RTPOLL_EVT_ERROR, VBOXSERVICECTRLPIPEID_STDIN);
1645 /* Stdout. */
1646 if (RT_SUCCESS(rc))
1647 rc = RTPollSetAddPipe(pProcess->hPollSet,
1648 pProcess->hPipeStdOutR, uFlags, VBOXSERVICECTRLPIPEID_STDOUT);
1649 /* Stderr. */
1650 if (RT_SUCCESS(rc))
1651 rc = RTPollSetAddPipe(pProcess->hPollSet,
1652 pProcess->hPipeStdErrR, uFlags, VBOXSERVICECTRLPIPEID_STDERR);
1653 /* IPC notification pipe. */
1654 if (RT_SUCCESS(rc))
1655 rc = RTPipeCreate(&pProcess->hNotificationPipeR, &pProcess->hNotificationPipeW, 0 /* Flags */);
1656 if (RT_SUCCESS(rc))
1657 rc = RTPollSetAddPipe(pProcess->hPollSet,
1658 pProcess->hNotificationPipeR, RTPOLL_EVT_READ, VBOXSERVICECTRLPIPEID_IPC_NOTIFY);
1659 if (RT_SUCCESS(rc))
1660 {
1661 AssertPtr(pProcess->pSession);
1662 bool fNeedsImpersonation = !(pProcess->pSession->fFlags & VBOXSERVICECTRLSESSION_FLAG_SPAWN);
1663
1664 rc = vgsvcGstCtrlProcessCreateProcess(pProcess->pStartupInfo->pszCmd, papszArgs, hEnv,
1665 pProcess->pStartupInfo->fFlags,
1666 phStdIn, phStdOut, phStdErr,
1667 fNeedsImpersonation ? pProcess->pStartupInfo->pszUser : NULL,
1668 fNeedsImpersonation ? pProcess->pStartupInfo->pszPassword : NULL,
1669 fNeedsImpersonation ? pProcess->pStartupInfo->pszDomain : NULL,
1670 &pProcess->hProcess);
1671 if (RT_FAILURE(rc))
1672 VGSvcError("Error starting process, rc=%Rrc\n", rc);
1673 /*
1674 * Tell the session thread that it can continue
1675 * spawning guest processes. This needs to be done after the new
1676 * process has been started because otherwise signal handling
1677 * on (Open) Solaris does not work correctly (see @bugref{5068}).
1678 */
1679 int rc2 = RTThreadUserSignal(RTThreadSelf());
1680 if (RT_SUCCESS(rc))
1681 rc = rc2;
1682 fSignalled = true;
1683
1684 if (RT_SUCCESS(rc))
1685 {
1686 /*
1687 * Close the child ends of any pipes and redirected files.
1688 */
1689 rc2 = RTHandleClose(phStdIn); AssertRC(rc2);
1690 phStdIn = NULL;
1691 rc2 = RTHandleClose(phStdOut); AssertRC(rc2);
1692 phStdOut = NULL;
1693 rc2 = RTHandleClose(phStdErr); AssertRC(rc2);
1694 phStdErr = NULL;
1695
1696 /* Enter the process main loop. */
1697 rc = vgsvcGstCtrlProcessProcLoop(pProcess);
1698
1699 /*
1700 * The handles that are no longer in the set have
1701 * been closed by the above call in order to prevent
1702 * the guest from getting stuck accessing them.
1703 * So, NIL the handles to avoid closing them again.
1704 */
1705 if (RT_FAILURE(RTPollSetQueryHandle(pProcess->hPollSet,
1706 VBOXSERVICECTRLPIPEID_IPC_NOTIFY, NULL)))
1707 pProcess->hNotificationPipeW = NIL_RTPIPE;
1708 if (RT_FAILURE(RTPollSetQueryHandle(pProcess->hPollSet,
1709 VBOXSERVICECTRLPIPEID_STDERR, NULL)))
1710 pProcess->hPipeStdErrR = NIL_RTPIPE;
1711 if (RT_FAILURE(RTPollSetQueryHandle(pProcess->hPollSet,
1712 VBOXSERVICECTRLPIPEID_STDOUT, NULL)))
1713 pProcess->hPipeStdOutR = NIL_RTPIPE;
1714 if (RT_FAILURE(RTPollSetQueryHandle(pProcess->hPollSet,
1715 VBOXSERVICECTRLPIPEID_STDIN, NULL)))
1716 pProcess->hPipeStdInW = NIL_RTPIPE;
1717 }
1718 }
1719 RTPollSetDestroy(pProcess->hPollSet);
1720 pProcess->hPollSet = NIL_RTPOLLSET;
1721
1722 RTPipeClose(pProcess->hNotificationPipeR);
1723 pProcess->hNotificationPipeR = NIL_RTPIPE;
1724 RTPipeClose(pProcess->hNotificationPipeW);
1725 pProcess->hNotificationPipeW = NIL_RTPIPE;
1726 }
1727 RTPipeClose(pProcess->hPipeStdErrR);
1728 pProcess->hPipeStdErrR = NIL_RTPIPE;
1729 RTHandleClose(&hStdErr);
1730 if (phStdErr)
1731 RTHandleClose(phStdErr);
1732 }
1733 RTPipeClose(pProcess->hPipeStdOutR);
1734 pProcess->hPipeStdOutR = NIL_RTPIPE;
1735 RTHandleClose(&hStdOut);
1736 if (phStdOut)
1737 RTHandleClose(phStdOut);
1738 }
1739 RTPipeClose(pProcess->hPipeStdInW);
1740 pProcess->hPipeStdInW = NIL_RTPIPE;
1741 RTHandleClose(&hStdIn);
1742 if (phStdIn)
1743 RTHandleClose(phStdIn);
1744 }
1745 }
1746 RTEnvDestroy(hEnv);
1747 }
1748 }
1749
1750 if (RT_FAILURE(rc))
1751 {
1752 VBGLR3GUESTCTRLCMDCTX ctx = { g_idControlSvcClient, pProcess->uContextID, 0 /* uProtocol */, 0 /* uNumParms */ };
1753 int rc2 = VbglR3GuestCtrlProcCbStatus(&ctx,
1754 pProcess->uPID, PROC_STS_ERROR, rc,
1755 NULL /* pvData */, 0 /* cbData */);
1756 if ( RT_FAILURE(rc2)
1757 && rc2 != VERR_NOT_FOUND)
1758 VGSvcError("[PID %RU32]: Could not report process failure error; rc=%Rrc (process error %Rrc)\n",
1759 pProcess->uPID, rc2, rc);
1760 }
1761
1762 /* Update stopped status. */
1763 ASMAtomicWriteBool(&pProcess->fStopped, true);
1764
1765 if (cArgs)
1766 RTGetOptArgvFree(papszArgs);
1767
1768 /*
1769 * If something went wrong signal the user event so that others don't wait
1770 * forever on this thread.
1771 */
1772 if ( RT_FAILURE(rc)
1773 && !fSignalled)
1774 {
1775 RTThreadUserSignal(RTThreadSelf());
1776 }
1777
1778 /* Set shut down flag in case we've forgotten it. */
1779 ASMAtomicWriteBool(&pProcess->fShutdown, true);
1780
1781 VGSvcVerbose(3, "[PID %RU32]: Thread of process '%s' ended with rc=%Rrc (fSignalled=%RTbool)\n",
1782 pProcess->uPID, pProcess->pStartupInfo->pszCmd, rc, fSignalled);
1783
1784 return rc;
1785}
1786
1787
1788static int vgsvcGstCtrlProcessLock(PVBOXSERVICECTRLPROCESS pProcess)
1789{
1790 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
1791 int rc = RTCritSectEnter(&pProcess->CritSect);
1792 AssertRC(rc);
1793 return rc;
1794}
1795
1796
1797/**
1798 * Thread main routine for a started process.
1799 *
1800 * @return IPRT status code.
1801 * @param hThreadSelf The thread handle.
1802 * @param pvUser Pointer to a VBOXSERVICECTRLPROCESS structure.
1803 *
1804 */
1805static DECLCALLBACK(int) vgsvcGstCtrlProcessThread(RTTHREAD hThreadSelf, void *pvUser)
1806{
1807 RT_NOREF1(hThreadSelf);
1808 PVBOXSERVICECTRLPROCESS pProcess = (PVBOXSERVICECTRLPROCESS)pvUser;
1809 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
1810 return vgsvcGstCtrlProcessProcessWorker(pProcess);
1811}
1812
1813
1814static int vgsvcGstCtrlProcessUnlock(PVBOXSERVICECTRLPROCESS pProcess)
1815{
1816 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
1817 int rc = RTCritSectLeave(&pProcess->CritSect);
1818 AssertRC(rc);
1819 return rc;
1820}
1821
1822
1823/**
1824 * Executes (starts) a process on the guest. This causes a new thread to be created
1825 * so that this function will not block the overall program execution.
1826 *
1827 * @return IPRT status code.
1828 * @param pSession Guest session.
1829 * @param pStartupInfo Startup info.
1830 * @param uContextID Context ID to associate the process to start with.
1831 */
1832int VGSvcGstCtrlProcessStart(const PVBOXSERVICECTRLSESSION pSession,
1833 const PVBGLR3GUESTCTRLPROCSTARTUPINFO pStartupInfo, uint32_t uContextID)
1834{
1835 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1836 AssertPtrReturn(pStartupInfo, VERR_INVALID_POINTER);
1837
1838 /*
1839 * Allocate new thread data and assign it to our thread list.
1840 */
1841 PVBOXSERVICECTRLPROCESS pProcess = (PVBOXSERVICECTRLPROCESS)RTMemAlloc(sizeof(VBOXSERVICECTRLPROCESS));
1842 if (!pProcess)
1843 return VERR_NO_MEMORY;
1844
1845 int rc = vgsvcGstCtrlProcessInit(pProcess, pSession, pStartupInfo, uContextID);
1846 if (RT_SUCCESS(rc))
1847 {
1848 static uint32_t s_uCtrlExecThread = 0;
1849 rc = RTThreadCreateF(&pProcess->Thread, vgsvcGstCtrlProcessThread,
1850 pProcess /*pvUser*/, 0 /*cbStack*/,
1851 RTTHREADTYPE_DEFAULT, RTTHREADFLAGS_WAITABLE, "gctl%RU32", s_uCtrlExecThread++);
1852 if (RT_FAILURE(rc))
1853 {
1854 VGSvcError("Creating thread for guest process '%s' failed: rc=%Rrc, pProcess=%p\n",
1855 pStartupInfo->pszCmd, rc, pProcess);
1856
1857 /* Process has not been added to the session's process list yet, so skip VGSvcGstCtrlSessionProcessRemove() here. */
1858 VGSvcGstCtrlProcessFree(pProcess);
1859 }
1860 else
1861 {
1862 VGSvcVerbose(4, "Waiting for thread to initialize ...\n");
1863
1864 /* Wait for the thread to initialize. */
1865 rc = RTThreadUserWait(pProcess->Thread, 60 * 1000 /* 60 seconds max. */);
1866 AssertRC(rc);
1867 if ( ASMAtomicReadBool(&pProcess->fShutdown)
1868 || ASMAtomicReadBool(&pProcess->fStopped)
1869 || RT_FAILURE(rc))
1870 {
1871 VGSvcError("Thread for process '%s' failed to start, rc=%Rrc\n", pStartupInfo->pszCmd, rc);
1872 int rc2 = RTThreadWait(pProcess->Thread, RT_MS_1SEC * 30, NULL);
1873 if (RT_SUCCESS(rc2))
1874 pProcess->Thread = NIL_RTTHREAD;
1875
1876 VGSvcGstCtrlSessionProcessRemove(pSession, pProcess);
1877 VGSvcGstCtrlProcessFree(pProcess);
1878 }
1879 else
1880 {
1881 ASMAtomicXchgBool(&pProcess->fStarted, true);
1882 }
1883 }
1884 }
1885
1886 return rc;
1887}
1888
1889
1890static DECLCALLBACK(int) vgsvcGstCtrlProcessOnInput(PVBOXSERVICECTRLPROCESS pThis,
1891 const PVBGLR3GUESTCTRLCMDCTX pHostCtx,
1892 bool fPendingClose, void *pvBuf, uint32_t cbBuf)
1893{
1894 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
1895 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1896
1897 int rc;
1898
1899 size_t cbWritten = 0;
1900 if (pvBuf && cbBuf)
1901 {
1902 if (pThis->hPipeStdInW != NIL_RTPIPE)
1903 rc = RTPipeWrite(pThis->hPipeStdInW, pvBuf, cbBuf, &cbWritten);
1904 else
1905 rc = VINF_EOF;
1906 }
1907 else
1908 rc = VERR_INVALID_PARAMETER;
1909
1910 /*
1911 * If this is the last write + we have really have written all data
1912 * we need to close the stdin pipe on our end and remove it from
1913 * the poll set.
1914 */
1915 if ( fPendingClose
1916 && cbBuf == cbWritten)
1917 {
1918 int rc2 = vgsvcGstCtrlProcessPollsetCloseInput(pThis, &pThis->hPipeStdInW);
1919 if (RT_SUCCESS(rc))
1920 rc = rc2;
1921 }
1922
1923 uint32_t uStatus = INPUT_STS_UNDEFINED; /* Status to send back to the host. */
1924 uint32_t fFlags = 0; /* No flags at the moment. */
1925 if (RT_SUCCESS(rc))
1926 {
1927 VGSvcVerbose(4, "[PID %RU32]: Written %RU32 bytes input, CID=%RU32, fPendingClose=%RTbool\n",
1928 pThis->uPID, cbWritten, pHostCtx->uContextID, fPendingClose);
1929 uStatus = INPUT_STS_WRITTEN;
1930 }
1931 else
1932 {
1933 if (rc == VERR_BAD_PIPE)
1934 uStatus = INPUT_STS_TERMINATED;
1935 else if (rc == VERR_BUFFER_OVERFLOW)
1936 uStatus = INPUT_STS_OVERFLOW;
1937 /* else undefined */
1938 }
1939
1940 /*
1941 * If there was an error and we did not set the host status
1942 * yet, then do it now.
1943 */
1944 if ( RT_FAILURE(rc)
1945 && uStatus == INPUT_STS_UNDEFINED)
1946 {
1947 uStatus = INPUT_STS_ERROR;
1948 fFlags = rc; /* funny thing to call a "flag"... */
1949 }
1950 Assert(uStatus > INPUT_STS_UNDEFINED);
1951
1952 int rc2 = VbglR3GuestCtrlProcCbStatusInput(pHostCtx, pThis->uPID, uStatus, fFlags, (uint32_t)cbWritten);
1953 if (RT_SUCCESS(rc))
1954 rc = rc2;
1955
1956#ifdef DEBUG
1957 VGSvcVerbose(3, "[PID %RU32]: vgsvcGstCtrlProcessOnInput returned with rc=%Rrc\n", pThis->uPID, rc);
1958#endif
1959 return VINF_SUCCESS; /** @todo Return rc here as soon as RTReqQueue todos are fixed. */
1960}
1961
1962
1963static DECLCALLBACK(int) vgsvcGstCtrlProcessOnOutput(PVBOXSERVICECTRLPROCESS pThis,
1964 const PVBGLR3GUESTCTRLCMDCTX pHostCtx,
1965 uint32_t uHandle, uint32_t cbToRead, uint32_t fFlags)
1966{
1967 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
1968 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1969
1970 const PVBOXSERVICECTRLSESSION pSession = pThis->pSession;
1971 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1972
1973 int rc;
1974
1975 uint32_t cbBuf = cbToRead;
1976 uint8_t *pvBuf = (uint8_t *)RTMemAlloc(cbBuf);
1977 if (pvBuf)
1978 {
1979 PRTPIPE phPipe = uHandle == OUTPUT_HANDLE_ID_STDOUT
1980 ? &pThis->hPipeStdOutR
1981 : &pThis->hPipeStdErrR;
1982 AssertPtr(phPipe);
1983
1984 size_t cbRead = 0;
1985 if (*phPipe != NIL_RTPIPE)
1986 {
1987 rc = RTPipeRead(*phPipe, pvBuf, cbBuf, &cbRead);
1988 if (RT_FAILURE(rc))
1989 {
1990 RTPollSetRemove(pThis->hPollSet, uHandle == OUTPUT_HANDLE_ID_STDERR
1991 ? VBOXSERVICECTRLPIPEID_STDERR : VBOXSERVICECTRLPIPEID_STDOUT);
1992 RTPipeClose(*phPipe);
1993 *phPipe = NIL_RTPIPE;
1994 if (rc == VERR_BROKEN_PIPE)
1995 rc = VINF_EOF;
1996 }
1997 }
1998 else
1999 rc = VINF_EOF;
2000
2001#ifdef DEBUG
2002 if (RT_SUCCESS(rc))
2003 {
2004 if ( pSession->fFlags & VBOXSERVICECTRLSESSION_FLAG_DUMPSTDOUT
2005 && ( uHandle == OUTPUT_HANDLE_ID_STDOUT
2006 || uHandle == OUTPUT_HANDLE_ID_STDOUT_DEPRECATED)
2007 )
2008 {
2009 rc = vgsvcGstCtrlProcessDbgDumpToFileF(pvBuf, cbRead, "VBoxService_Session%RU32_PID%RU32_StdOut.txt",
2010 pSession->StartupInfo.uSessionID, pThis->uPID);
2011 AssertRC(rc);
2012 }
2013 else if ( pSession->fFlags & VBOXSERVICECTRLSESSION_FLAG_DUMPSTDERR
2014 && uHandle == OUTPUT_HANDLE_ID_STDERR)
2015 {
2016 rc = vgsvcGstCtrlProcessDbgDumpToFileF(pvBuf, cbRead, "VBoxService_Session%RU32_PID%RU32_StdErr.txt",
2017 pSession->StartupInfo.uSessionID, pThis->uPID);
2018 AssertRC(rc);
2019 }
2020 }
2021#endif
2022
2023 if (RT_SUCCESS(rc))
2024 {
2025#ifdef DEBUG
2026 VGSvcVerbose(3, "[PID %RU32]: Read %RU32 bytes output: uHandle=%RU32, CID=%RU32, fFlags=%x\n",
2027 pThis->uPID, cbRead, uHandle, pHostCtx->uContextID, fFlags);
2028#endif
2029 /** Note: Don't convert/touch/modify/whatever the output data here! This might be binary
2030 * data which the host needs to work with -- so just pass through all data unfiltered! */
2031
2032 /* Note: Since the context ID is unique the request *has* to be completed here,
2033 * regardless whether we got data or not! Otherwise the waiting events
2034 * on the host never will get completed! */
2035 Assert((uint32_t)cbRead == cbRead);
2036 rc = VbglR3GuestCtrlProcCbOutput(pHostCtx, pThis->uPID, uHandle, fFlags, pvBuf, (uint32_t)cbRead);
2037 if ( RT_FAILURE(rc)
2038 && rc == VERR_NOT_FOUND) /* Not critical if guest PID is not found on the host (anymore). */
2039 rc = VINF_SUCCESS;
2040 }
2041
2042 RTMemFree(pvBuf);
2043 }
2044 else
2045 rc = VERR_NO_MEMORY;
2046
2047#ifdef DEBUG
2048 VGSvcVerbose(3, "[PID %RU32]: Reading output returned with rc=%Rrc\n", pThis->uPID, rc);
2049#endif
2050 return VINF_SUCCESS; /** @todo Return rc here as soon as RTReqQueue todos are fixed. */
2051}
2052
2053
2054static DECLCALLBACK(int) vgsvcGstCtrlProcessOnTerm(PVBOXSERVICECTRLPROCESS pThis)
2055{
2056 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
2057
2058 if (!ASMAtomicXchgBool(&pThis->fShutdown, true))
2059 VGSvcVerbose(3, "[PID %RU32]: Setting shutdown flag ...\n", pThis->uPID);
2060
2061 return VINF_SUCCESS; /** @todo Return rc here as soon as RTReqQueue todos are fixed. */
2062}
2063
2064
2065static int vgsvcGstCtrlProcessRequestExV(PVBOXSERVICECTRLPROCESS pProcess, const PVBGLR3GUESTCTRLCMDCTX pHostCtx, bool fAsync,
2066 RTMSINTERVAL uTimeoutMS, PRTREQ pReq, PFNRT pfnFunction, unsigned cArgs, va_list Args)
2067{
2068 RT_NOREF1(pHostCtx);
2069 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
2070 /* pHostCtx is optional. */
2071 AssertPtrReturn(pfnFunction, VERR_INVALID_POINTER);
2072 if (!fAsync)
2073 AssertPtrReturn(pfnFunction, VERR_INVALID_POINTER);
2074
2075 int rc = vgsvcGstCtrlProcessLock(pProcess);
2076 if (RT_SUCCESS(rc))
2077 {
2078#ifdef DEBUG
2079 VGSvcVerbose(3, "[PID %RU32]: vgsvcGstCtrlProcessRequestExV fAsync=%RTbool, uTimeoutMS=%RU32, cArgs=%u\n",
2080 pProcess->uPID, fAsync, uTimeoutMS, cArgs);
2081#endif
2082 uint32_t fFlags = RTREQFLAGS_IPRT_STATUS;
2083 if (fAsync)
2084 {
2085 Assert(uTimeoutMS == 0);
2086 fFlags |= RTREQFLAGS_NO_WAIT;
2087 }
2088
2089 rc = RTReqQueueCallV(pProcess->hReqQueue, &pReq, uTimeoutMS, fFlags, pfnFunction, cArgs, Args);
2090 if (RT_SUCCESS(rc))
2091 {
2092 /* Wake up the process' notification pipe to get
2093 * the request being processed. */
2094 Assert(pProcess->hNotificationPipeW != NIL_RTPIPE || pProcess->fShutdown /* latter in case of race */);
2095 size_t cbWritten = 0;
2096 rc = RTPipeWrite(pProcess->hNotificationPipeW, "i", 1, &cbWritten);
2097 if ( RT_SUCCESS(rc)
2098 && cbWritten != 1)
2099 {
2100 VGSvcError("[PID %RU32]: Notification pipe got %zu bytes instead of 1\n",
2101 pProcess->uPID, cbWritten);
2102 }
2103 else if (RT_UNLIKELY(RT_FAILURE(rc)))
2104 VGSvcError("[PID %RU32]: Writing to notification pipe failed, rc=%Rrc\n",
2105 pProcess->uPID, rc);
2106 }
2107 else
2108 VGSvcError("[PID %RU32]: RTReqQueueCallV failed, rc=%Rrc\n",
2109 pProcess->uPID, rc);
2110
2111 int rc2 = vgsvcGstCtrlProcessUnlock(pProcess);
2112 if (RT_SUCCESS(rc))
2113 rc = rc2;
2114 }
2115
2116#ifdef DEBUG
2117 VGSvcVerbose(3, "[PID %RU32]: vgsvcGstCtrlProcessRequestExV returned rc=%Rrc\n", pProcess->uPID, rc);
2118#endif
2119 return rc;
2120}
2121
2122
2123static int vgsvcGstCtrlProcessRequestAsync(PVBOXSERVICECTRLPROCESS pProcess, const PVBGLR3GUESTCTRLCMDCTX pHostCtx,
2124 PFNRT pfnFunction, unsigned cArgs, ...)
2125{
2126 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
2127 /* pHostCtx is optional. */
2128 AssertPtrReturn(pfnFunction, VERR_INVALID_POINTER);
2129
2130 va_list va;
2131 va_start(va, cArgs);
2132 int rc = vgsvcGstCtrlProcessRequestExV(pProcess, pHostCtx, true /* fAsync */, 0 /* uTimeoutMS */,
2133 NULL /* pReq */, pfnFunction, cArgs, va);
2134 va_end(va);
2135
2136 return rc;
2137}
2138
2139
2140#if 0 /* unused */
2141static int vgsvcGstCtrlProcessRequestWait(PVBOXSERVICECTRLPROCESS pProcess, const PVBGLR3GUESTCTRLCMDCTX pHostCtx,
2142 RTMSINTERVAL uTimeoutMS, PRTREQ pReq, PFNRT pfnFunction, unsigned cArgs, ...)
2143{
2144 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
2145 /* pHostCtx is optional. */
2146 AssertPtrReturn(pfnFunction, VERR_INVALID_POINTER);
2147
2148 va_list va;
2149 va_start(va, cArgs);
2150 int rc = vgsvcGstCtrlProcessRequestExV(pProcess, pHostCtx, false /* fAsync */, uTimeoutMS,
2151 pReq, pfnFunction, cArgs, va);
2152 va_end(va);
2153
2154 return rc;
2155}
2156#endif
2157
2158
2159int VGSvcGstCtrlProcessHandleInput(PVBOXSERVICECTRLPROCESS pProcess, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
2160 bool fPendingClose, void *pvBuf, uint32_t cbBuf)
2161{
2162 if (!ASMAtomicReadBool(&pProcess->fShutdown) && !ASMAtomicReadBool(&pProcess->fStopped))
2163 return vgsvcGstCtrlProcessRequestAsync(pProcess, pHostCtx, (PFNRT)vgsvcGstCtrlProcessOnInput,
2164 5 /* cArgs */, pProcess, pHostCtx, fPendingClose, pvBuf, cbBuf);
2165
2166 return vgsvcGstCtrlProcessOnInput(pProcess, pHostCtx, fPendingClose, pvBuf, cbBuf);
2167}
2168
2169
2170int VGSvcGstCtrlProcessHandleOutput(PVBOXSERVICECTRLPROCESS pProcess, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
2171 uint32_t uHandle, uint32_t cbToRead, uint32_t fFlags)
2172{
2173 if (!ASMAtomicReadBool(&pProcess->fShutdown) && !ASMAtomicReadBool(&pProcess->fStopped))
2174 return vgsvcGstCtrlProcessRequestAsync(pProcess, pHostCtx, (PFNRT)vgsvcGstCtrlProcessOnOutput,
2175 5 /* cArgs */, pProcess, pHostCtx, uHandle, cbToRead, fFlags);
2176
2177 return vgsvcGstCtrlProcessOnOutput(pProcess, pHostCtx, uHandle, cbToRead, fFlags);
2178}
2179
2180
2181int VGSvcGstCtrlProcessHandleTerm(PVBOXSERVICECTRLPROCESS pProcess)
2182{
2183 if (!ASMAtomicReadBool(&pProcess->fShutdown) && !ASMAtomicReadBool(&pProcess->fStopped))
2184 return vgsvcGstCtrlProcessRequestAsync(pProcess, NULL /* pHostCtx */, (PFNRT)vgsvcGstCtrlProcessOnTerm,
2185 1 /* cArgs */, pProcess);
2186
2187 return vgsvcGstCtrlProcessOnTerm(pProcess);
2188}
2189
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