VirtualBox

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

Last change on this file since 92687 was 92687, checked in by vboxsync, 3 years ago

Guest Control/VBoxService: Removed debug assertion -- no longer holds true if VBOXSERVICE_ARG1_UTF8_ARGV is defined and fExecutingSelf is set. bugref:10153

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 86.2 KB
Line 
1/* $Id: VBoxServiceControlProcess.cpp 92687 2021-12-02 10:19:58Z 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.
966 *
967 * ~~This only works on Windows for now (e.g. translating "%TEMP%\foo.exe" to
968 * "C:\Windows\Temp" when starting with system / administrative rights).~~ See
969 * todo in code.
970 *
971 * @return IPRT status code.
972 * @param pszPath Path to resolve.
973 * @param pszExpanded Pointer to string to store the resolved path in.
974 * @param cbExpanded Size (in bytes) of string to store the resolved path.
975 */
976static int vgsvcGstCtrlProcessMakeFullPath(const char *pszPath, char *pszExpanded, size_t cbExpanded)
977{
978/** @todo r=bird: This feature shall be made optional, i.e. require a
979 * flag to be passed down. Further, it shall work on the environment
980 * block of the new process (i.e. include env changes passed down from
981 * the caller). I would also suggest using the unix variable expansion
982 * syntax, not the DOS one.
983 *
984 * Since this currently not available on non-windows guests, I suggest
985 * we disable it until such a time as it is implemented correctly. */
986#if 0 /*def RT_OS_WINDOWS - see above. Don't know why this wasn't disabled before 7.0, didn't see the @todo yet? */
987 int rc = VINF_SUCCESS;
988 if (!ExpandEnvironmentStrings(pszPath, pszExpanded, (DWORD)cbExpanded))
989 rc = RTErrConvertFromWin32(GetLastError());
990#else
991 /* There is no expansion anywhere yet, see above @todo. */
992 int rc = RTStrCopy(pszExpanded, cbExpanded, pszPath);
993#endif
994#ifdef DEBUG
995 VGSvcVerbose(3, "vgsvcGstCtrlProcessMakeFullPath: %s -> %s\n", pszPath, pszExpanded);
996#endif
997 return rc;
998}
999
1000
1001/**
1002 * Resolves the full path of a specified executable name.
1003 *
1004 * This function also resolves internal VBoxService tools to its appropriate
1005 * executable path + name if VBOXSERVICE_NAME is specified as pszFilename.
1006 *
1007 * @return IPRT status code.
1008 * @param pszFilename File name to resolve.
1009 * @param pszResolved Pointer to a string where the resolved file name will be stored.
1010 * @param cbResolved Size (in bytes) of resolved file name string.
1011 */
1012static int vgsvcGstCtrlProcessResolveExecutable(const char *pszFilename, char *pszResolved, size_t cbResolved)
1013{
1014 AssertPtrReturn(pszFilename, VERR_INVALID_POINTER);
1015 AssertPtrReturn(pszResolved, VERR_INVALID_POINTER);
1016 AssertReturn(cbResolved, VERR_INVALID_PARAMETER);
1017
1018 const char * const pszOrgFilename = pszFilename;
1019 if ( RTStrICmp(pszFilename, g_pszProgName) == 0
1020 || RTStrICmp(pszFilename, VBOXSERVICE_NAME) == 0)
1021 pszFilename = RTProcExecutablePath();
1022
1023 int rc = vgsvcGstCtrlProcessMakeFullPath(pszFilename, pszResolved, cbResolved);
1024 if (RT_SUCCESS(rc))
1025 VGSvcVerbose(3, "Looked up executable: %s -> %s\n", pszOrgFilename, pszResolved);
1026 return rc;
1027}
1028
1029
1030/**
1031 * Constructs the argv command line by resolving environment variables
1032 * and relative paths.
1033 *
1034 * @return IPRT status code.
1035 * @param pszArgv0 First argument (argv0), either original or modified version.
1036 * @param papszArgs Original argv command line from the host, starting at argv[1].
1037 * @param fFlags The process creation flags pass to us from the host.
1038 * @param fExecutingSelf Set if we're executing the VBoxService executable
1039 * and should inject the --utf8-argv trick.
1040 * @param ppapszArgv Pointer to a pointer with the new argv command line.
1041 * Needs to be freed with RTGetOptArgvFree.
1042 */
1043static int vgsvcGstCtrlProcessAllocateArgv(const char *pszArgv0, const char * const *papszArgs, uint32_t fFlags,
1044 bool fExecutingSelf, char ***ppapszArgv)
1045{
1046 VGSvcVerbose(3, "VGSvcGstCtrlProcessPrepareArgv: pszArgv0=%p, papszArgs=%p, fFlags=%#x, fExecutingSelf=%d, ppapszArgv=%p\n",
1047 pszArgv0, papszArgs, fFlags, fExecutingSelf, ppapszArgv);
1048
1049 AssertPtrReturn(pszArgv0, VERR_INVALID_POINTER);
1050 AssertPtrReturn(ppapszArgv, VERR_INVALID_POINTER);
1051 AssertReturn(!(fFlags & EXECUTEPROCESSFLAG_EXPAND_ARGUMENTS), VERR_INVALID_FLAGS); /** @todo implement me */
1052
1053#ifndef VBOXSERVICE_ARG1_UTF8_ARGV
1054 fExecutingSelf = false;
1055#endif
1056
1057 /* Count arguments: */
1058 int rc = VINF_SUCCESS;
1059 uint32_t cArgs;
1060 for (cArgs = 0; papszArgs[cArgs]; cArgs++)
1061 {
1062 if (cArgs >= UINT32_MAX - 2)
1063 return VERR_BUFFER_OVERFLOW;
1064 }
1065
1066 /* Allocate new argv vector (adding + 2 for argv0 + termination). */
1067 size_t cbSize = (fExecutingSelf + cArgs + 2) * sizeof(char *);
1068 char **papszNewArgv = (char **)RTMemAlloc(cbSize);
1069 if (!papszNewArgv)
1070 return VERR_NO_MEMORY;
1071
1072 VGSvcVerbose(3, "VGSvcGstCtrlProcessAllocateArgv: pszArgv0 = '%s', cArgs=%RU32, cbSize=%zu\n", pszArgv0, cArgs, cbSize);
1073#ifdef DEBUG /* Never log this stuff in release mode! */
1074 if (cArgs)
1075 {
1076 for (uint32_t i = 0; i < cArgs; i++)
1077 VGSvcVerbose(3, "VGSvcGstCtrlProcessAllocateArgv: papszArgs[%RU32] = '%s'\n", i, papszArgs[i]);
1078 }
1079#endif
1080
1081 /* HACK ALERT! Older hosts (< VBox 6.1.x) did not allow the user to really specify
1082 the first argument separately from the executable image, so we have
1083 to fudge a little in the unquoted argument case to deal with executables
1084 containing spaces. Windows only, as RTPROC_FLAGS_UNQUOTED_ARGS is
1085 ignored on all other hosts. */
1086#ifdef RT_OS_WINDOWS
1087 if ( (fFlags & EXECUTEPROCESSFLAG_UNQUOTED_ARGS)
1088 && strpbrk(pszArgv0, " \t\n\r")
1089 && pszArgv0[0] == '"')
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 else
1105#endif
1106 rc = RTStrDupEx(&papszNewArgv[0], pszArgv0);
1107 if (RT_SUCCESS(rc))
1108 {
1109 size_t iDst = 1;
1110
1111#ifdef VBOXSERVICE_ARG1_UTF8_ARGV
1112 /* Insert --utf8-argv as the first argument if executing the VBoxService binary. */
1113 if (fExecutingSelf)
1114 {
1115 rc = RTStrDupEx(&papszNewArgv[iDst], VBOXSERVICE_ARG1_UTF8_ARGV);
1116 if (RT_SUCCESS(rc))
1117 iDst++;
1118 }
1119#endif
1120 /* Copy over the other arguments. */
1121 if (RT_SUCCESS(rc))
1122 for (size_t iSrc = 0; iSrc < cArgs; iSrc++)
1123 {
1124#if 0 /* Arguments expansion -- untested. */
1125 if (fFlags & EXECUTEPROCESSFLAG_EXPAND_ARGUMENTS)
1126 {
1127/** @todo r=bird: If you want this, we need a generic implementation, preferably in RTEnv or somewhere like that. The marking
1128 * up of the variables must be the same on all platforms. */
1129 /* According to MSDN the limit on older Windows version is 32K, whereas
1130 * Vista+ there are no limits anymore. We still stick to 4K. */
1131 char szExpanded[_4K];
1132# ifdef RT_OS_WINDOWS
1133 if (!ExpandEnvironmentStrings(papszArgs[i], szExpanded, sizeof(szExpanded)))
1134 rc = RTErrConvertFromWin32(GetLastError());
1135# else
1136 /* No expansion for non-Windows yet. */
1137 rc = RTStrCopy(papszArgs[i], sizeof(szExpanded), szExpanded);
1138# endif
1139 if (RT_SUCCESS(rc))
1140 rc = RTStrDupEx(&pszArg, szExpanded);
1141 }
1142 else
1143#endif
1144 rc = RTStrDupEx(&papszNewArgv[iDst], papszArgs[iSrc]);
1145 if (RT_SUCCESS(rc))
1146 iDst++;
1147 else
1148 break;
1149 }
1150
1151 if (RT_SUCCESS(rc))
1152 {
1153 /* Terminate array. */
1154 papszNewArgv[iDst] = NULL;
1155
1156 *ppapszArgv = papszNewArgv;
1157 return VINF_SUCCESS;
1158 }
1159
1160 /* Failed, bail out. */
1161 while (iDst-- > 0)
1162 RTStrFree(papszNewArgv[iDst]);
1163 }
1164 RTMemFree(papszNewArgv);
1165 return rc;
1166}
1167
1168
1169/**
1170 * Assigns a valid PID to a guest control thread and also checks if there already was
1171 * another (stale) guest process which was using that PID before and destroys it.
1172 *
1173 * @return IPRT status code.
1174 * @param pProcess Process to assign PID to.
1175 * @param uPID PID to assign to the specified guest control execution thread.
1176 */
1177static int vgsvcGstCtrlProcessAssignPID(PVBOXSERVICECTRLPROCESS pProcess, uint32_t uPID)
1178{
1179 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
1180 AssertReturn(uPID, VERR_INVALID_PARAMETER);
1181
1182 AssertPtr(pProcess->pSession);
1183 int rc = RTCritSectEnter(&pProcess->pSession->CritSect);
1184 if (RT_SUCCESS(rc))
1185 {
1186 /* Search old threads using the desired PID and shut them down completely -- it's
1187 * not used anymore. */
1188 bool fTryAgain;
1189 do
1190 {
1191 fTryAgain = false;
1192 PVBOXSERVICECTRLPROCESS pProcessCur;
1193 RTListForEach(&pProcess->pSession->lstProcesses, pProcessCur, VBOXSERVICECTRLPROCESS, Node)
1194 {
1195 if (pProcessCur->uPID == uPID)
1196 {
1197 Assert(pProcessCur != pProcess); /* can't happen */
1198 uint32_t uTriedPID = uPID;
1199 uPID += 391939;
1200 VGSvcVerbose(2, "PID %RU32 was used before (process %p), trying again with %RU32 ...\n",
1201 uTriedPID, pProcessCur, uPID);
1202 fTryAgain = true;
1203 break;
1204 }
1205 }
1206 } while (fTryAgain);
1207
1208 /* Assign PID to current thread. */
1209 pProcess->uPID = uPID;
1210
1211 rc = RTCritSectLeave(&pProcess->pSession->CritSect);
1212 AssertRC(rc);
1213 }
1214
1215 return rc;
1216}
1217
1218
1219static void vgsvcGstCtrlProcessFreeArgv(char **papszArgv)
1220{
1221 if (papszArgv)
1222 {
1223 size_t i = 0;
1224 while (papszArgv[i])
1225 RTStrFree(papszArgv[i++]);
1226 RTMemFree(papszArgv);
1227 }
1228}
1229
1230
1231/**
1232 * Helper function to create/start a process on the guest.
1233 *
1234 * @return IPRT status code.
1235 * @param pszExec Full qualified path of process to start (without arguments).
1236 * @param papszArgs Pointer to array of command line arguments.
1237 * @param hEnv Handle to environment block to use.
1238 * @param fFlags Process execution flags.
1239 * @param phStdIn Handle for the process' stdin pipe.
1240 * @param phStdOut Handle for the process' stdout pipe.
1241 * @param phStdErr Handle for the process' stderr pipe.
1242 * @param pszAsUser User name (account) to start the process under.
1243 * @param pszPassword Password of the specified user.
1244 * @param pszDomain Domain to use for authentication.
1245 * @param phProcess Pointer which will receive the process handle after
1246 * successful process start.
1247 */
1248static int vgsvcGstCtrlProcessCreateProcess(const char *pszExec, const char * const *papszArgs, RTENV hEnv, uint32_t fFlags,
1249 PCRTHANDLE phStdIn, PCRTHANDLE phStdOut, PCRTHANDLE phStdErr,
1250 const char *pszAsUser, const char *pszPassword, const char *pszDomain,
1251 PRTPROCESS phProcess)
1252{
1253#ifndef RT_OS_WINDOWS
1254 RT_NOREF1(pszDomain);
1255#endif
1256 AssertPtrReturn(pszExec, VERR_INVALID_PARAMETER);
1257 AssertPtrReturn(papszArgs, VERR_INVALID_PARAMETER);
1258 /* phStdIn is optional. */
1259 /* phStdOut is optional. */
1260 /* phStdErr is optional. */
1261 /* pszPassword is optional. */
1262 /* pszDomain is optional. */
1263 AssertPtrReturn(phProcess, VERR_INVALID_PARAMETER);
1264
1265 int rc = VINF_SUCCESS;
1266 char szExecExp[RTPATH_MAX];
1267
1268#ifdef DEBUG
1269 /* Never log this in release mode! */
1270 VGSvcVerbose(4, "pszUser=%s, pszPassword=%s, pszDomain=%s\n", pszAsUser, pszPassword, pszDomain);
1271#endif
1272
1273#ifdef RT_OS_WINDOWS
1274 /*
1275 * If sysprep should be executed do this in the context of VBoxService, which
1276 * (usually, if started by SCM) has administrator rights. Because of that a UI
1277 * won't be shown (doesn't have a desktop).
1278 */
1279 if (!RTStrICmp(pszExec, "sysprep"))
1280 {
1281 /* Use a predefined sysprep path as default. */
1282 char szSysprepCmd[RTPATH_MAX] = "C:\\sysprep\\sysprep.exe";
1283 /** @todo Check digital signature of file above before executing it? */
1284
1285 /*
1286 * On Windows Vista (and up) sysprep is located in "system32\\Sysprep\\sysprep.exe",
1287 * so detect the OS and use a different path.
1288 */
1289 OSVERSIONINFOEX OSInfoEx;
1290 RT_ZERO(OSInfoEx);
1291 OSInfoEx.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
1292 BOOL fRet = GetVersionEx((LPOSVERSIONINFO) &OSInfoEx);
1293 if ( fRet
1294 && OSInfoEx.dwPlatformId == VER_PLATFORM_WIN32_NT
1295 && OSInfoEx.dwMajorVersion >= 6 /* Vista or later */)
1296 {
1297 rc = RTEnvGetEx(RTENV_DEFAULT, "windir", szSysprepCmd, sizeof(szSysprepCmd), NULL);
1298#ifndef RT_ARCH_AMD64
1299 /* Don't execute 64-bit sysprep from a 32-bit service host! */
1300 char szSysWow64[RTPATH_MAX];
1301 if (RTStrPrintf(szSysWow64, sizeof(szSysWow64), "%s", szSysprepCmd))
1302 {
1303 rc = RTPathAppend(szSysWow64, sizeof(szSysWow64), "SysWow64");
1304 AssertRC(rc);
1305 }
1306 if ( RT_SUCCESS(rc)
1307 && RTPathExists(szSysWow64))
1308 VGSvcVerbose(0, "Warning: This service is 32-bit; could not execute sysprep on 64-bit OS!\n");
1309#endif
1310 if (RT_SUCCESS(rc))
1311 rc = RTPathAppend(szSysprepCmd, sizeof(szSysprepCmd), "system32\\Sysprep\\sysprep.exe");
1312 if (RT_SUCCESS(rc))
1313 RTPathChangeToDosSlashes(szSysprepCmd, false /* No forcing necessary */);
1314
1315 if (RT_FAILURE(rc))
1316 VGSvcError("Failed to detect sysrep location, rc=%Rrc\n", rc);
1317 }
1318 else if (!fRet)
1319 VGSvcError("Failed to retrieve OS information, last error=%ld\n", GetLastError());
1320
1321 VGSvcVerbose(3, "Sysprep executable is: %s\n", szSysprepCmd);
1322
1323 if (RT_SUCCESS(rc))
1324 {
1325 char **papszArgsExp;
1326 rc = vgsvcGstCtrlProcessAllocateArgv(szSysprepCmd /* argv0 */, papszArgs, fFlags,
1327 false /*fExecutingSelf*/, &papszArgsExp);
1328 if (RT_SUCCESS(rc))
1329 {
1330 /* As we don't specify credentials for the sysprep process, it will
1331 * run under behalf of the account VBoxService was started under, most
1332 * likely local system. */
1333 rc = RTProcCreateEx(szSysprepCmd, papszArgsExp, hEnv, 0 /* fFlags */,
1334 phStdIn, phStdOut, phStdErr, NULL /* pszAsUser */,
1335 NULL /* pszPassword */, NULL, phProcess);
1336 vgsvcGstCtrlProcessFreeArgv(papszArgsExp);
1337 }
1338 }
1339
1340 if (RT_FAILURE(rc))
1341 VGSvcVerbose(3, "Starting sysprep returned rc=%Rrc\n", rc);
1342
1343 return rc;
1344 }
1345#endif /* RT_OS_WINDOWS */
1346
1347 bool fExecutingSelf = false;
1348#ifdef VBOX_WITH_VBOXSERVICE_TOOLBOX
1349 /* The "vbox_" prefix is reserved for the toolbox (vbox_cat, vbox_mkdir,
1350 et al.) and we will replace pszExec with the full VBoxService path instead. */
1351 if (RTStrStartsWith(pszExec, "vbox_"))
1352 {
1353 fExecutingSelf = true;
1354 rc = vgsvcGstCtrlProcessResolveExecutable(VBOXSERVICE_NAME, szExecExp, sizeof(szExecExp));
1355 }
1356 else
1357 {
1358#endif
1359 /*
1360 * Do the environment variables expansion on executable and arguments.
1361 */
1362 rc = vgsvcGstCtrlProcessResolveExecutable(pszExec, szExecExp, sizeof(szExecExp));
1363#ifdef VBOX_WITH_VBOXSERVICE_TOOLBOX
1364 }
1365#endif
1366 if (RT_SUCCESS(rc))
1367 {
1368 /*
1369 * This one is a bit tricky to also support older hosts:
1370 *
1371 * - If the host does not provide a dedicated argv[0] (< VBox 6.1.x), we use the
1372 * unmodified executable name (pszExec) as the (default) argv[0]. This is wrong, but we can't do
1373 * much about it. The rest (argv[1,2,n]) then gets set starting at papszArgs[0].
1374 *
1375 * - Newer hosts (>= VBox 6.1.x) provide a correct argv[0] independently of the actual
1376 * executable name though, so actually use argv[0] *and* argv[1,2,n] as intended.
1377 */
1378 const bool fHasArgv0 = RT_BOOL(g_fControlHostFeatures0 & VBOX_GUESTCTRL_HF_0_PROCESS_ARGV0);
1379
1380 const char *pcszArgv0 = (fHasArgv0 && papszArgs[0]) ? papszArgs[0] : pszExec;
1381 AssertPtrReturn(pcszArgv0, VERR_INVALID_POINTER); /* Paranoia. */
1382
1383 const uint32_t uArgvIdx = pcszArgv0 == papszArgs[0] ? 1 : 0;
1384
1385 VGSvcVerbose(3, "vgsvcGstCtrlProcessCreateProcess: fHasArgv0=%RTbool, pcszArgv0=%p, uArgvIdx=%RU32, "
1386 "g_fControlHostFeatures0=%#x\n",
1387 fHasArgv0, pcszArgv0, uArgvIdx, g_fControlHostFeatures0);
1388
1389 char **papszArgsExp;
1390 rc = vgsvcGstCtrlProcessAllocateArgv(pcszArgv0, &papszArgs[uArgvIdx], fFlags, fExecutingSelf, &papszArgsExp);
1391 if (RT_FAILURE(rc))
1392 {
1393 /* Don't print any arguments -- may contain passwords or other sensible data! */
1394 VGSvcError("Could not prepare arguments, rc=%Rrc\n", rc);
1395 }
1396 else
1397 {
1398 uint32_t fProcCreateFlags = 0;
1399 if (fExecutingSelf)
1400 fProcCreateFlags |= VBOXSERVICE_PROC_F_UTF8_ARGV;
1401 if (fFlags)
1402 {
1403 if (fFlags & EXECUTEPROCESSFLAG_HIDDEN)
1404 fProcCreateFlags |= RTPROC_FLAGS_HIDDEN;
1405 if (fFlags & EXECUTEPROCESSFLAG_PROFILE)
1406 fProcCreateFlags |= RTPROC_FLAGS_PROFILE;
1407 if (fFlags & EXECUTEPROCESSFLAG_UNQUOTED_ARGS)
1408 fProcCreateFlags |= RTPROC_FLAGS_UNQUOTED_ARGS;
1409 }
1410
1411 /* If no user name specified run with current credentials (e.g.
1412 * full service/system rights). This is prohibited via official Main API!
1413 *
1414 * Otherwise use the RTPROC_FLAGS_SERVICE to use some special authentication
1415 * code (at least on Windows) for running processes as different users
1416 * started from our system service. */
1417 if (pszAsUser && *pszAsUser)
1418 fProcCreateFlags |= RTPROC_FLAGS_SERVICE;
1419#ifdef DEBUG
1420 VGSvcVerbose(3, "Command: %s\n", szExecExp);
1421 for (size_t i = 0; papszArgsExp[i]; i++)
1422 VGSvcVerbose(3, " argv[%zu]: %s\n", i, papszArgsExp[i]);
1423#endif
1424 VGSvcVerbose(3, "Starting process '%s' ...\n", szExecExp);
1425
1426#ifdef RT_OS_WINDOWS
1427 /* If a domain name is given, construct an UPN (User Principle Name) with
1428 * the domain name built-in, e.g. "[email protected]". */
1429 char *pszUserUPN = NULL;
1430 if (pszDomain && *pszDomain != '\0')
1431 {
1432 pszAsUser = pszUserUPN = RTStrAPrintf2("%s@%s", pszAsUser, pszDomain);
1433 if (pszAsUser)
1434 VGSvcVerbose(3, "Using UPN: %s\n", pszAsUser);
1435 else
1436 rc = VERR_NO_STR_MEMORY;
1437 }
1438 if (RT_SUCCESS(rc))
1439#endif
1440 {
1441 /* Do normal execution. */
1442 rc = RTProcCreateEx(szExecExp, papszArgsExp, hEnv, fProcCreateFlags,
1443 phStdIn, phStdOut, phStdErr,
1444 pszAsUser,
1445 pszPassword && *pszPassword ? pszPassword : NULL,
1446 NULL /*pvExtraData*/,
1447 phProcess);
1448
1449#ifdef RT_OS_WINDOWS
1450 RTStrFree(pszUserUPN);
1451#endif
1452 VGSvcVerbose(3, "Starting process '%s' returned rc=%Rrc\n", szExecExp, rc);
1453 }
1454 vgsvcGstCtrlProcessFreeArgv(papszArgsExp);
1455 }
1456 }
1457 return rc;
1458}
1459
1460
1461#ifdef DEBUG
1462/**
1463 * Dumps content to a file in the OS temporary directory.
1464 *
1465 * @returns VBox status code.
1466 * @param pvBuf Buffer of content to dump.
1467 * @param cbBuf Size (in bytes) of content to dump.
1468 * @param pszFileNmFmt Pointer to the file name format string, @see pg_rt_str_format.
1469 * @param ... The format argument.
1470 */
1471static int vgsvcGstCtrlProcessDbgDumpToFileF(const void *pvBuf, size_t cbBuf, const char *pszFileNmFmt, ...)
1472{
1473 AssertPtrReturn(pszFileNmFmt, VERR_INVALID_POINTER);
1474 AssertPtrReturn(pvBuf, VERR_INVALID_POINTER);
1475
1476 if (!cbBuf)
1477 return VINF_SUCCESS;
1478
1479 va_list va;
1480 va_start(va, pszFileNmFmt);
1481
1482 char *pszFileName = NULL;
1483 const int cchFileName = RTStrAPrintfV(&pszFileName, pszFileNmFmt, va);
1484
1485 va_end(va);
1486
1487 if (!cchFileName)
1488 return VERR_NO_MEMORY;
1489
1490 char szPathFileAbs[RTPATH_MAX];
1491 int rc = RTPathTemp(szPathFileAbs, sizeof(szPathFileAbs));
1492 if (RT_SUCCESS(rc))
1493 rc = RTPathAppend(szPathFileAbs, sizeof(szPathFileAbs), pszFileName);
1494
1495 RTStrFree(pszFileName);
1496
1497 if (RT_SUCCESS(rc))
1498 {
1499 VGSvcVerbose(4, "Dumping %zu bytes to '%s'\n", cbBuf, szPathFileAbs);
1500
1501 RTFILE fh;
1502 rc = RTFileOpen(&fh, szPathFileAbs, RTFILE_O_OPEN_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_WRITE);
1503 if (RT_SUCCESS(rc))
1504 {
1505 rc = RTFileWrite(fh, pvBuf, cbBuf, NULL /* pcbWritten */);
1506 RTFileClose(fh);
1507 }
1508 }
1509
1510 return rc;
1511}
1512#endif /* DEBUG */
1513
1514
1515/**
1516 * The actual worker routine (loop) for a started guest process.
1517 *
1518 * @return IPRT status code.
1519 * @param pProcess The process we're servicing and monitoring.
1520 */
1521static int vgsvcGstCtrlProcessProcessWorker(PVBOXSERVICECTRLPROCESS pProcess)
1522{
1523 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
1524 VGSvcVerbose(3, "Thread of process pThread=0x%p = '%s' started\n", pProcess, pProcess->pStartupInfo->pszCmd);
1525
1526 VGSvcVerbose(3, "Guest process '%s', flags=0x%x\n", pProcess->pStartupInfo->pszCmd, pProcess->pStartupInfo->fFlags);
1527
1528 int rc = VGSvcGstCtrlSessionProcessAdd(pProcess->pSession, pProcess);
1529 if (RT_FAILURE(rc))
1530 {
1531 VGSvcError("Error while adding guest process '%s' (%p) to session process list, rc=%Rrc\n",
1532 pProcess->pStartupInfo->pszCmd, pProcess, rc);
1533 RTThreadUserSignal(RTThreadSelf());
1534 return rc;
1535 }
1536
1537 bool fSignalled = false; /* Indicator whether we signalled the thread user event already. */
1538
1539 /*
1540 * Prepare argument list.
1541 */
1542 VGSvcVerbose(3, "vgsvcGstCtrlProcessProcessWorker: fHostFeatures0 = %#x\n", g_fControlHostFeatures0);
1543 VGSvcVerbose(3, "vgsvcGstCtrlProcessProcessWorker: StartupInfo.szCmd = '%s'\n", pProcess->pStartupInfo->pszCmd);
1544 VGSvcVerbose(3, "vgsvcGstCtrlProcessProcessWorker: StartupInfo.uNumArgs = '%RU32'\n", pProcess->pStartupInfo->cArgs);
1545#ifdef DEBUG /* Never log this stuff in release mode! */
1546 VGSvcVerbose(3, "vgsvcGstCtrlProcessProcessWorker: StartupInfo.szArgs = '%s'\n", pProcess->pStartupInfo->pszArgs);
1547#endif
1548
1549 char **papszArgs;
1550 int cArgs = 0; /* Initialize in case of RTGetOptArgvFromString() is failing ... */
1551 rc = RTGetOptArgvFromString(&papszArgs, &cArgs,
1552 pProcess->pStartupInfo->cArgs > 0 ? pProcess->pStartupInfo->pszArgs : "",
1553 RTGETOPTARGV_CNV_QUOTE_BOURNE_SH, NULL);
1554
1555 VGSvcVerbose(3, "vgsvcGstCtrlProcessProcessWorker: cArgs = %d\n", cArgs);
1556#ifdef VBOX_STRICT
1557 for (int i = 0; i < cArgs; i++)
1558 VGSvcVerbose(3, "vgsvcGstCtrlProcessProcessWorker: papszArgs[%d] = '%s'\n", i, papszArgs[i] ? papszArgs[i] : "<NULL>");
1559
1560 const bool fHasArgv0 = RT_BOOL(g_fControlHostFeatures0 & VBOX_GUESTCTRL_HF_0_PROCESS_ARGV0); RT_NOREF(fHasArgv0);
1561 const int cArgsToCheck = cArgs + (fHasArgv0 ? 0 : 1);
1562
1563 /* Did we get the same result?
1564 * Take into account that we might not have supplied a (correct) argv[0] from the host. */
1565 AssertMsg((int)pProcess->pStartupInfo->cArgs == cArgsToCheck,
1566 ("rc=%Rrc, StartupInfo.uNumArgs=%RU32 != cArgsToCheck=%d, cArgs=%d, fHostFeatures0=%#x\n",
1567 rc, pProcess->pStartupInfo->cArgs, cArgsToCheck, cArgs, g_fControlHostFeatures0));
1568#endif
1569
1570 /*
1571 * Create the environment.
1572 */
1573 uint32_t const cbEnv = pProcess->pStartupInfo->cbEnv;
1574 if (RT_SUCCESS(rc))
1575 AssertStmt( cbEnv <= GUESTPROCESS_MAX_ENV_LEN
1576 || pProcess->pStartupInfo->cEnvVars == 0,
1577 rc = VERR_INVALID_PARAMETER);
1578 if (RT_SUCCESS(rc))
1579 {
1580 RTENV hEnv;
1581 rc = RTEnvClone(&hEnv, RTENV_DEFAULT);
1582 if (RT_SUCCESS(rc))
1583 {
1584 VGSvcVerbose(3, "Additional environment variables: %RU32 (%RU32 bytes)\n",
1585 pProcess->pStartupInfo->cEnvVars, cbEnv);
1586
1587 if ( pProcess->pStartupInfo->cEnvVars
1588 && cbEnv > 0)
1589 {
1590 size_t offCur = 0;
1591 while (offCur < cbEnv)
1592 {
1593 const char * const pszCur = &pProcess->pStartupInfo->pszEnv[offCur];
1594 size_t const cchCur = RTStrNLen(pszCur, cbEnv - offCur);
1595 AssertBreakStmt(cchCur < cbEnv - offCur, rc = VERR_INVALID_PARAMETER);
1596 VGSvcVerbose(3, "Setting environment variable: '%s'\n", pszCur);
1597 rc = RTEnvPutEx(hEnv, pszCur);
1598 if (RT_SUCCESS(rc))
1599 offCur += cchCur + 1;
1600 else
1601 {
1602 VGSvcError("Setting environment variable '%s' failed: %Rrc\n", pszCur, rc);
1603 break;
1604 }
1605 }
1606 }
1607
1608 if (RT_SUCCESS(rc))
1609 {
1610 /*
1611 * Setup the redirection of the standard stuff.
1612 */
1613 /** @todo consider supporting: gcc stuff.c >file 2>&1. */
1614 RTHANDLE hStdIn;
1615 PRTHANDLE phStdIn;
1616 rc = vgsvcGstCtrlProcessSetupPipe("|", 0 /*STDIN_FILENO*/,
1617 &hStdIn, &phStdIn, &pProcess->hPipeStdInW);
1618 if (RT_SUCCESS(rc))
1619 {
1620 RTHANDLE hStdOut;
1621 PRTHANDLE phStdOut;
1622 rc = vgsvcGstCtrlProcessSetupPipe( (pProcess->pStartupInfo->fFlags & EXECUTEPROCESSFLAG_WAIT_STDOUT)
1623 ? "|" : "/dev/null",
1624 1 /*STDOUT_FILENO*/,
1625 &hStdOut, &phStdOut, &pProcess->hPipeStdOutR);
1626 if (RT_SUCCESS(rc))
1627 {
1628 RTHANDLE hStdErr;
1629 PRTHANDLE phStdErr;
1630 rc = vgsvcGstCtrlProcessSetupPipe( (pProcess->pStartupInfo->fFlags & EXECUTEPROCESSFLAG_WAIT_STDERR)
1631 ? "|" : "/dev/null",
1632 2 /*STDERR_FILENO*/,
1633 &hStdErr, &phStdErr, &pProcess->hPipeStdErrR);
1634 if (RT_SUCCESS(rc))
1635 {
1636 /*
1637 * Create a poll set for the pipes and let the
1638 * transport layer add stuff to it as well.
1639 */
1640 rc = RTPollSetCreate(&pProcess->hPollSet);
1641 if (RT_SUCCESS(rc))
1642 {
1643 uint32_t uFlags = RTPOLL_EVT_ERROR;
1644#if 0
1645 /* Add reading event to pollset to get some more information. */
1646 uFlags |= RTPOLL_EVT_READ;
1647#endif
1648 /* Stdin. */
1649 if (RT_SUCCESS(rc))
1650 rc = RTPollSetAddPipe(pProcess->hPollSet,
1651 pProcess->hPipeStdInW, RTPOLL_EVT_ERROR, VBOXSERVICECTRLPIPEID_STDIN);
1652 /* Stdout. */
1653 if (RT_SUCCESS(rc))
1654 rc = RTPollSetAddPipe(pProcess->hPollSet,
1655 pProcess->hPipeStdOutR, uFlags, VBOXSERVICECTRLPIPEID_STDOUT);
1656 /* Stderr. */
1657 if (RT_SUCCESS(rc))
1658 rc = RTPollSetAddPipe(pProcess->hPollSet,
1659 pProcess->hPipeStdErrR, uFlags, VBOXSERVICECTRLPIPEID_STDERR);
1660 /* IPC notification pipe. */
1661 if (RT_SUCCESS(rc))
1662 rc = RTPipeCreate(&pProcess->hNotificationPipeR, &pProcess->hNotificationPipeW, 0 /* Flags */);
1663 if (RT_SUCCESS(rc))
1664 rc = RTPollSetAddPipe(pProcess->hPollSet,
1665 pProcess->hNotificationPipeR, RTPOLL_EVT_READ, VBOXSERVICECTRLPIPEID_IPC_NOTIFY);
1666 if (RT_SUCCESS(rc))
1667 {
1668 AssertPtr(pProcess->pSession);
1669 bool fNeedsImpersonation = !(pProcess->pSession->fFlags & VBOXSERVICECTRLSESSION_FLAG_SPAWN);
1670
1671 rc = vgsvcGstCtrlProcessCreateProcess(pProcess->pStartupInfo->pszCmd, papszArgs, hEnv,
1672 pProcess->pStartupInfo->fFlags,
1673 phStdIn, phStdOut, phStdErr,
1674 fNeedsImpersonation ? pProcess->pStartupInfo->pszUser : NULL,
1675 fNeedsImpersonation ? pProcess->pStartupInfo->pszPassword : NULL,
1676 fNeedsImpersonation ? pProcess->pStartupInfo->pszDomain : NULL,
1677 &pProcess->hProcess);
1678 if (RT_FAILURE(rc))
1679 VGSvcError("Error starting process, rc=%Rrc\n", rc);
1680 /*
1681 * Tell the session thread that it can continue
1682 * spawning guest processes. This needs to be done after the new
1683 * process has been started because otherwise signal handling
1684 * on (Open) Solaris does not work correctly (see @bugref{5068}).
1685 */
1686 int rc2 = RTThreadUserSignal(RTThreadSelf());
1687 if (RT_SUCCESS(rc))
1688 rc = rc2;
1689 fSignalled = true;
1690
1691 if (RT_SUCCESS(rc))
1692 {
1693 /*
1694 * Close the child ends of any pipes and redirected files.
1695 */
1696 rc2 = RTHandleClose(phStdIn); AssertRC(rc2);
1697 phStdIn = NULL;
1698 rc2 = RTHandleClose(phStdOut); AssertRC(rc2);
1699 phStdOut = NULL;
1700 rc2 = RTHandleClose(phStdErr); AssertRC(rc2);
1701 phStdErr = NULL;
1702
1703 /* Enter the process main loop. */
1704 rc = vgsvcGstCtrlProcessProcLoop(pProcess);
1705
1706 /*
1707 * The handles that are no longer in the set have
1708 * been closed by the above call in order to prevent
1709 * the guest from getting stuck accessing them.
1710 * So, NIL the handles to avoid closing them again.
1711 */
1712 if (RT_FAILURE(RTPollSetQueryHandle(pProcess->hPollSet,
1713 VBOXSERVICECTRLPIPEID_IPC_NOTIFY, NULL)))
1714 pProcess->hNotificationPipeW = NIL_RTPIPE;
1715 if (RT_FAILURE(RTPollSetQueryHandle(pProcess->hPollSet,
1716 VBOXSERVICECTRLPIPEID_STDERR, NULL)))
1717 pProcess->hPipeStdErrR = NIL_RTPIPE;
1718 if (RT_FAILURE(RTPollSetQueryHandle(pProcess->hPollSet,
1719 VBOXSERVICECTRLPIPEID_STDOUT, NULL)))
1720 pProcess->hPipeStdOutR = NIL_RTPIPE;
1721 if (RT_FAILURE(RTPollSetQueryHandle(pProcess->hPollSet,
1722 VBOXSERVICECTRLPIPEID_STDIN, NULL)))
1723 pProcess->hPipeStdInW = NIL_RTPIPE;
1724 }
1725 }
1726 RTPollSetDestroy(pProcess->hPollSet);
1727 pProcess->hPollSet = NIL_RTPOLLSET;
1728
1729 RTPipeClose(pProcess->hNotificationPipeR);
1730 pProcess->hNotificationPipeR = NIL_RTPIPE;
1731 RTPipeClose(pProcess->hNotificationPipeW);
1732 pProcess->hNotificationPipeW = NIL_RTPIPE;
1733 }
1734 RTPipeClose(pProcess->hPipeStdErrR);
1735 pProcess->hPipeStdErrR = NIL_RTPIPE;
1736 RTHandleClose(&hStdErr);
1737 if (phStdErr)
1738 RTHandleClose(phStdErr);
1739 }
1740 RTPipeClose(pProcess->hPipeStdOutR);
1741 pProcess->hPipeStdOutR = NIL_RTPIPE;
1742 RTHandleClose(&hStdOut);
1743 if (phStdOut)
1744 RTHandleClose(phStdOut);
1745 }
1746 RTPipeClose(pProcess->hPipeStdInW);
1747 pProcess->hPipeStdInW = NIL_RTPIPE;
1748 RTHandleClose(&hStdIn);
1749 if (phStdIn)
1750 RTHandleClose(phStdIn);
1751 }
1752 }
1753 RTEnvDestroy(hEnv);
1754 }
1755 }
1756
1757 if (RT_FAILURE(rc))
1758 {
1759 VBGLR3GUESTCTRLCMDCTX ctx = { g_idControlSvcClient, pProcess->uContextID, 0 /* uProtocol */, 0 /* uNumParms */ };
1760 int rc2 = VbglR3GuestCtrlProcCbStatus(&ctx,
1761 pProcess->uPID, PROC_STS_ERROR, rc,
1762 NULL /* pvData */, 0 /* cbData */);
1763 if ( RT_FAILURE(rc2)
1764 && rc2 != VERR_NOT_FOUND)
1765 VGSvcError("[PID %RU32]: Could not report process failure error; rc=%Rrc (process error %Rrc)\n",
1766 pProcess->uPID, rc2, rc);
1767 }
1768
1769 /* Update stopped status. */
1770 ASMAtomicWriteBool(&pProcess->fStopped, true);
1771
1772 if (cArgs)
1773 RTGetOptArgvFree(papszArgs);
1774
1775 /*
1776 * If something went wrong signal the user event so that others don't wait
1777 * forever on this thread.
1778 */
1779 if ( RT_FAILURE(rc)
1780 && !fSignalled)
1781 {
1782 RTThreadUserSignal(RTThreadSelf());
1783 }
1784
1785 /* Set shut down flag in case we've forgotten it. */
1786 ASMAtomicWriteBool(&pProcess->fShutdown, true);
1787
1788 VGSvcVerbose(3, "[PID %RU32]: Thread of process '%s' ended with rc=%Rrc (fSignalled=%RTbool)\n",
1789 pProcess->uPID, pProcess->pStartupInfo->pszCmd, rc, fSignalled);
1790
1791 return rc;
1792}
1793
1794
1795static int vgsvcGstCtrlProcessLock(PVBOXSERVICECTRLPROCESS pProcess)
1796{
1797 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
1798 int rc = RTCritSectEnter(&pProcess->CritSect);
1799 AssertRC(rc);
1800 return rc;
1801}
1802
1803
1804/**
1805 * Thread main routine for a started process.
1806 *
1807 * @return IPRT status code.
1808 * @param hThreadSelf The thread handle.
1809 * @param pvUser Pointer to a VBOXSERVICECTRLPROCESS structure.
1810 *
1811 */
1812static DECLCALLBACK(int) vgsvcGstCtrlProcessThread(RTTHREAD hThreadSelf, void *pvUser)
1813{
1814 RT_NOREF1(hThreadSelf);
1815 PVBOXSERVICECTRLPROCESS pProcess = (PVBOXSERVICECTRLPROCESS)pvUser;
1816 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
1817 return vgsvcGstCtrlProcessProcessWorker(pProcess);
1818}
1819
1820
1821static int vgsvcGstCtrlProcessUnlock(PVBOXSERVICECTRLPROCESS pProcess)
1822{
1823 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
1824 int rc = RTCritSectLeave(&pProcess->CritSect);
1825 AssertRC(rc);
1826 return rc;
1827}
1828
1829
1830/**
1831 * Executes (starts) a process on the guest. This causes a new thread to be created
1832 * so that this function will not block the overall program execution.
1833 *
1834 * @return IPRT status code.
1835 * @param pSession Guest session.
1836 * @param pStartupInfo Startup info.
1837 * @param uContextID Context ID to associate the process to start with.
1838 */
1839int VGSvcGstCtrlProcessStart(const PVBOXSERVICECTRLSESSION pSession,
1840 const PVBGLR3GUESTCTRLPROCSTARTUPINFO pStartupInfo, uint32_t uContextID)
1841{
1842 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1843 AssertPtrReturn(pStartupInfo, VERR_INVALID_POINTER);
1844
1845 /*
1846 * Allocate new thread data and assign it to our thread list.
1847 */
1848 PVBOXSERVICECTRLPROCESS pProcess = (PVBOXSERVICECTRLPROCESS)RTMemAlloc(sizeof(VBOXSERVICECTRLPROCESS));
1849 if (!pProcess)
1850 return VERR_NO_MEMORY;
1851
1852 int rc = vgsvcGstCtrlProcessInit(pProcess, pSession, pStartupInfo, uContextID);
1853 if (RT_SUCCESS(rc))
1854 {
1855 static uint32_t s_uCtrlExecThread = 0;
1856 rc = RTThreadCreateF(&pProcess->Thread, vgsvcGstCtrlProcessThread,
1857 pProcess /*pvUser*/, 0 /*cbStack*/,
1858 RTTHREADTYPE_DEFAULT, RTTHREADFLAGS_WAITABLE, "gctl%RU32", s_uCtrlExecThread++);
1859 if (RT_FAILURE(rc))
1860 {
1861 VGSvcError("Creating thread for guest process '%s' failed: rc=%Rrc, pProcess=%p\n",
1862 pStartupInfo->pszCmd, rc, pProcess);
1863
1864 /* Process has not been added to the session's process list yet, so skip VGSvcGstCtrlSessionProcessRemove() here. */
1865 VGSvcGstCtrlProcessFree(pProcess);
1866 }
1867 else
1868 {
1869 VGSvcVerbose(4, "Waiting for thread to initialize ...\n");
1870
1871 /* Wait for the thread to initialize. */
1872 rc = RTThreadUserWait(pProcess->Thread, 60 * 1000 /* 60 seconds max. */);
1873 AssertRC(rc);
1874 if ( ASMAtomicReadBool(&pProcess->fShutdown)
1875 || ASMAtomicReadBool(&pProcess->fStopped)
1876 || RT_FAILURE(rc))
1877 {
1878 VGSvcError("Thread for process '%s' failed to start, rc=%Rrc\n", pStartupInfo->pszCmd, rc);
1879 int rc2 = RTThreadWait(pProcess->Thread, RT_MS_1SEC * 30, NULL);
1880 if (RT_SUCCESS(rc2))
1881 pProcess->Thread = NIL_RTTHREAD;
1882
1883 VGSvcGstCtrlSessionProcessRemove(pSession, pProcess);
1884 VGSvcGstCtrlProcessFree(pProcess);
1885 }
1886 else
1887 {
1888 ASMAtomicXchgBool(&pProcess->fStarted, true);
1889 }
1890 }
1891 }
1892
1893 return rc;
1894}
1895
1896
1897static DECLCALLBACK(int) vgsvcGstCtrlProcessOnInput(PVBOXSERVICECTRLPROCESS pThis,
1898 const PVBGLR3GUESTCTRLCMDCTX pHostCtx,
1899 bool fPendingClose, void *pvBuf, uint32_t cbBuf)
1900{
1901 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
1902 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1903
1904 int rc;
1905
1906 size_t cbWritten = 0;
1907 if (pvBuf && cbBuf)
1908 {
1909 if (pThis->hPipeStdInW != NIL_RTPIPE)
1910 rc = RTPipeWrite(pThis->hPipeStdInW, pvBuf, cbBuf, &cbWritten);
1911 else
1912 rc = VINF_EOF;
1913 }
1914 else
1915 rc = VERR_INVALID_PARAMETER;
1916
1917 /*
1918 * If this is the last write + we have really have written all data
1919 * we need to close the stdin pipe on our end and remove it from
1920 * the poll set.
1921 */
1922 if ( fPendingClose
1923 && cbBuf == cbWritten)
1924 {
1925 int rc2 = vgsvcGstCtrlProcessPollsetCloseInput(pThis, &pThis->hPipeStdInW);
1926 if (RT_SUCCESS(rc))
1927 rc = rc2;
1928 }
1929
1930 uint32_t uStatus = INPUT_STS_UNDEFINED; /* Status to send back to the host. */
1931 uint32_t fFlags = 0; /* No flags at the moment. */
1932 if (RT_SUCCESS(rc))
1933 {
1934 VGSvcVerbose(4, "[PID %RU32]: Written %RU32 bytes input, CID=%RU32, fPendingClose=%RTbool\n",
1935 pThis->uPID, cbWritten, pHostCtx->uContextID, fPendingClose);
1936 uStatus = INPUT_STS_WRITTEN;
1937 }
1938 else
1939 {
1940 if (rc == VERR_BAD_PIPE)
1941 uStatus = INPUT_STS_TERMINATED;
1942 else if (rc == VERR_BUFFER_OVERFLOW)
1943 uStatus = INPUT_STS_OVERFLOW;
1944 /* else undefined */
1945 }
1946
1947 /*
1948 * If there was an error and we did not set the host status
1949 * yet, then do it now.
1950 */
1951 if ( RT_FAILURE(rc)
1952 && uStatus == INPUT_STS_UNDEFINED)
1953 {
1954 uStatus = INPUT_STS_ERROR;
1955 fFlags = rc; /* funny thing to call a "flag"... */
1956 }
1957 Assert(uStatus > INPUT_STS_UNDEFINED);
1958
1959 int rc2 = VbglR3GuestCtrlProcCbStatusInput(pHostCtx, pThis->uPID, uStatus, fFlags, (uint32_t)cbWritten);
1960 if (RT_SUCCESS(rc))
1961 rc = rc2;
1962
1963#ifdef DEBUG
1964 VGSvcVerbose(3, "[PID %RU32]: vgsvcGstCtrlProcessOnInput returned with rc=%Rrc\n", pThis->uPID, rc);
1965#endif
1966 return VINF_SUCCESS; /** @todo Return rc here as soon as RTReqQueue todos are fixed. */
1967}
1968
1969
1970static DECLCALLBACK(int) vgsvcGstCtrlProcessOnOutput(PVBOXSERVICECTRLPROCESS pThis,
1971 const PVBGLR3GUESTCTRLCMDCTX pHostCtx,
1972 uint32_t uHandle, uint32_t cbToRead, uint32_t fFlags)
1973{
1974 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
1975 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1976
1977 const PVBOXSERVICECTRLSESSION pSession = pThis->pSession;
1978 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1979
1980 int rc;
1981
1982 uint32_t cbBuf = cbToRead;
1983 uint8_t *pvBuf = (uint8_t *)RTMemAlloc(cbBuf);
1984 if (pvBuf)
1985 {
1986 PRTPIPE phPipe = uHandle == OUTPUT_HANDLE_ID_STDOUT
1987 ? &pThis->hPipeStdOutR
1988 : &pThis->hPipeStdErrR;
1989 AssertPtr(phPipe);
1990
1991 size_t cbRead = 0;
1992 if (*phPipe != NIL_RTPIPE)
1993 {
1994 rc = RTPipeRead(*phPipe, pvBuf, cbBuf, &cbRead);
1995 if (RT_FAILURE(rc))
1996 {
1997 RTPollSetRemove(pThis->hPollSet, uHandle == OUTPUT_HANDLE_ID_STDERR
1998 ? VBOXSERVICECTRLPIPEID_STDERR : VBOXSERVICECTRLPIPEID_STDOUT);
1999 RTPipeClose(*phPipe);
2000 *phPipe = NIL_RTPIPE;
2001 if (rc == VERR_BROKEN_PIPE)
2002 rc = VINF_EOF;
2003 }
2004 }
2005 else
2006 rc = VINF_EOF;
2007
2008#ifdef DEBUG
2009 if (RT_SUCCESS(rc))
2010 {
2011 if ( pSession->fFlags & VBOXSERVICECTRLSESSION_FLAG_DUMPSTDOUT
2012 && ( uHandle == OUTPUT_HANDLE_ID_STDOUT
2013 || uHandle == OUTPUT_HANDLE_ID_STDOUT_DEPRECATED)
2014 )
2015 {
2016 rc = vgsvcGstCtrlProcessDbgDumpToFileF(pvBuf, cbRead, "VBoxService_Session%RU32_PID%RU32_StdOut.txt",
2017 pSession->StartupInfo.uSessionID, pThis->uPID);
2018 AssertRC(rc);
2019 }
2020 else if ( pSession->fFlags & VBOXSERVICECTRLSESSION_FLAG_DUMPSTDERR
2021 && uHandle == OUTPUT_HANDLE_ID_STDERR)
2022 {
2023 rc = vgsvcGstCtrlProcessDbgDumpToFileF(pvBuf, cbRead, "VBoxService_Session%RU32_PID%RU32_StdErr.txt",
2024 pSession->StartupInfo.uSessionID, pThis->uPID);
2025 AssertRC(rc);
2026 }
2027 }
2028#endif
2029
2030 if (RT_SUCCESS(rc))
2031 {
2032#ifdef DEBUG
2033 VGSvcVerbose(3, "[PID %RU32]: Read %RU32 bytes output: uHandle=%RU32, CID=%RU32, fFlags=%x\n",
2034 pThis->uPID, cbRead, uHandle, pHostCtx->uContextID, fFlags);
2035#endif
2036 /** Note: Don't convert/touch/modify/whatever the output data here! This might be binary
2037 * data which the host needs to work with -- so just pass through all data unfiltered! */
2038
2039 /* Note: Since the context ID is unique the request *has* to be completed here,
2040 * regardless whether we got data or not! Otherwise the waiting events
2041 * on the host never will get completed! */
2042 Assert((uint32_t)cbRead == cbRead);
2043 rc = VbglR3GuestCtrlProcCbOutput(pHostCtx, pThis->uPID, uHandle, fFlags, pvBuf, (uint32_t)cbRead);
2044 if ( RT_FAILURE(rc)
2045 && rc == VERR_NOT_FOUND) /* Not critical if guest PID is not found on the host (anymore). */
2046 rc = VINF_SUCCESS;
2047 }
2048
2049 RTMemFree(pvBuf);
2050 }
2051 else
2052 rc = VERR_NO_MEMORY;
2053
2054#ifdef DEBUG
2055 VGSvcVerbose(3, "[PID %RU32]: Reading output returned with rc=%Rrc\n", pThis->uPID, rc);
2056#endif
2057 return VINF_SUCCESS; /** @todo Return rc here as soon as RTReqQueue todos are fixed. */
2058}
2059
2060
2061static DECLCALLBACK(int) vgsvcGstCtrlProcessOnTerm(PVBOXSERVICECTRLPROCESS pThis)
2062{
2063 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
2064
2065 if (!ASMAtomicXchgBool(&pThis->fShutdown, true))
2066 VGSvcVerbose(3, "[PID %RU32]: Setting shutdown flag ...\n", pThis->uPID);
2067
2068 return VINF_SUCCESS; /** @todo Return rc here as soon as RTReqQueue todos are fixed. */
2069}
2070
2071
2072static int vgsvcGstCtrlProcessRequestExV(PVBOXSERVICECTRLPROCESS pProcess, const PVBGLR3GUESTCTRLCMDCTX pHostCtx, bool fAsync,
2073 RTMSINTERVAL uTimeoutMS, PFNRT pfnFunction, unsigned cArgs, va_list Args)
2074{
2075 RT_NOREF1(pHostCtx);
2076 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
2077 /* pHostCtx is optional. */
2078 AssertPtrReturn(pfnFunction, VERR_INVALID_POINTER);
2079 if (!fAsync)
2080 AssertPtrReturn(pfnFunction, VERR_INVALID_POINTER);
2081
2082 int rc = vgsvcGstCtrlProcessLock(pProcess);
2083 if (RT_SUCCESS(rc))
2084 {
2085#ifdef DEBUG
2086 VGSvcVerbose(3, "[PID %RU32]: vgsvcGstCtrlProcessRequestExV fAsync=%RTbool, uTimeoutMS=%RU32, cArgs=%u\n",
2087 pProcess->uPID, fAsync, uTimeoutMS, cArgs);
2088#endif
2089 uint32_t fFlags = RTREQFLAGS_IPRT_STATUS;
2090 if (fAsync)
2091 {
2092 Assert(uTimeoutMS == 0);
2093 fFlags |= RTREQFLAGS_NO_WAIT;
2094 }
2095
2096 PRTREQ hReq = NIL_RTREQ;
2097 rc = RTReqQueueCallV(pProcess->hReqQueue, &hReq, uTimeoutMS, fFlags, pfnFunction, cArgs, Args);
2098 RTReqRelease(hReq);
2099 if (RT_SUCCESS(rc))
2100 {
2101 /* Wake up the process' notification pipe to get
2102 * the request being processed. */
2103 Assert(pProcess->hNotificationPipeW != NIL_RTPIPE || pProcess->fShutdown /* latter in case of race */);
2104 size_t cbWritten = 0;
2105 rc = RTPipeWrite(pProcess->hNotificationPipeW, "i", 1, &cbWritten);
2106 if ( RT_SUCCESS(rc)
2107 && cbWritten != 1)
2108 {
2109 VGSvcError("[PID %RU32]: Notification pipe got %zu bytes instead of 1\n",
2110 pProcess->uPID, cbWritten);
2111 }
2112 else if (RT_UNLIKELY(RT_FAILURE(rc)))
2113 VGSvcError("[PID %RU32]: Writing to notification pipe failed, rc=%Rrc\n",
2114 pProcess->uPID, rc);
2115 }
2116 else
2117 VGSvcError("[PID %RU32]: RTReqQueueCallV failed, rc=%Rrc\n",
2118 pProcess->uPID, rc);
2119
2120 int rc2 = vgsvcGstCtrlProcessUnlock(pProcess);
2121 if (RT_SUCCESS(rc))
2122 rc = rc2;
2123 }
2124
2125#ifdef DEBUG
2126 VGSvcVerbose(3, "[PID %RU32]: vgsvcGstCtrlProcessRequestExV returned rc=%Rrc\n", pProcess->uPID, rc);
2127#endif
2128 return rc;
2129}
2130
2131
2132static int vgsvcGstCtrlProcessRequestAsync(PVBOXSERVICECTRLPROCESS pProcess, const PVBGLR3GUESTCTRLCMDCTX pHostCtx,
2133 PFNRT pfnFunction, unsigned cArgs, ...)
2134{
2135 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
2136 /* pHostCtx is optional. */
2137 AssertPtrReturn(pfnFunction, VERR_INVALID_POINTER);
2138
2139 va_list va;
2140 va_start(va, cArgs);
2141 int rc = vgsvcGstCtrlProcessRequestExV(pProcess, pHostCtx, true /* fAsync */, 0 /* uTimeoutMS */,
2142 pfnFunction, cArgs, va);
2143 va_end(va);
2144
2145 return rc;
2146}
2147
2148
2149#if 0 /* unused */
2150static int vgsvcGstCtrlProcessRequestWait(PVBOXSERVICECTRLPROCESS pProcess, const PVBGLR3GUESTCTRLCMDCTX pHostCtx,
2151 RTMSINTERVAL uTimeoutMS, PFNRT pfnFunction, unsigned cArgs, ...)
2152{
2153 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
2154 /* pHostCtx is optional. */
2155 AssertPtrReturn(pfnFunction, VERR_INVALID_POINTER);
2156
2157 va_list va;
2158 va_start(va, cArgs);
2159 int rc = vgsvcGstCtrlProcessRequestExV(pProcess, pHostCtx, false /* fAsync */, uTimeoutMS,
2160 pfnFunction, cArgs, va);
2161 va_end(va);
2162
2163 return rc;
2164}
2165#endif
2166
2167
2168int VGSvcGstCtrlProcessHandleInput(PVBOXSERVICECTRLPROCESS pProcess, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
2169 bool fPendingClose, void *pvBuf, uint32_t cbBuf)
2170{
2171 if (!ASMAtomicReadBool(&pProcess->fShutdown) && !ASMAtomicReadBool(&pProcess->fStopped))
2172 return vgsvcGstCtrlProcessRequestAsync(pProcess, pHostCtx, (PFNRT)vgsvcGstCtrlProcessOnInput,
2173 5 /* cArgs */, pProcess, pHostCtx, fPendingClose, pvBuf, cbBuf);
2174
2175 return vgsvcGstCtrlProcessOnInput(pProcess, pHostCtx, fPendingClose, pvBuf, cbBuf);
2176}
2177
2178
2179int VGSvcGstCtrlProcessHandleOutput(PVBOXSERVICECTRLPROCESS pProcess, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
2180 uint32_t uHandle, uint32_t cbToRead, uint32_t fFlags)
2181{
2182 if (!ASMAtomicReadBool(&pProcess->fShutdown) && !ASMAtomicReadBool(&pProcess->fStopped))
2183 return vgsvcGstCtrlProcessRequestAsync(pProcess, pHostCtx, (PFNRT)vgsvcGstCtrlProcessOnOutput,
2184 5 /* cArgs */, pProcess, pHostCtx, uHandle, cbToRead, fFlags);
2185
2186 return vgsvcGstCtrlProcessOnOutput(pProcess, pHostCtx, uHandle, cbToRead, fFlags);
2187}
2188
2189
2190int VGSvcGstCtrlProcessHandleTerm(PVBOXSERVICECTRLPROCESS pProcess)
2191{
2192 if (!ASMAtomicReadBool(&pProcess->fShutdown) && !ASMAtomicReadBool(&pProcess->fStopped))
2193 return vgsvcGstCtrlProcessRequestAsync(pProcess, NULL /* pHostCtx */, (PFNRT)vgsvcGstCtrlProcessOnTerm,
2194 1 /* cArgs */, pProcess);
2195
2196 return vgsvcGstCtrlProcessOnTerm(pProcess);
2197}
2198
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