VirtualBox

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

Last change on this file since 46593 was 46513, checked in by vboxsync, 12 years ago

Forward ported / integrated r86363 (4.2: VBoxService/sysprep: Fixed slashes, more logging about looking up executable. Print warning when trying to execute sysprep on 64-bit OSes with 32-bit service executable).

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