VirtualBox

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

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

Guest Control/VBoxService: Resolved another @todo: Added ability for guest processes to use argv[0] independently of the actual execution command (follow-up to r136802)). ​​​​bugref:9320

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette