VirtualBox

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

Last change on this file since 46506 was 46506, checked in by vboxsync, 11 years ago

Additions/VBoxService: Don't use VBOX_WITH_PAGE_SHARING here as this is a global defined symbol (VBox/param.h). Fixed warning.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 74.2 KB
Line 
1/* $Id: VBoxServiceControlProcess.cpp 46506 2013-06-12 09:05:32Z 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
1455 /*
1456 * On Windows Vista (and up) sysprep is located in "system32\\sysprep\\sysprep.exe",
1457 * so detect the OS and use a different path.
1458 */
1459 OSVERSIONINFOEX OSInfoEx;
1460 RT_ZERO(OSInfoEx);
1461 OSInfoEx.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
1462 if ( GetVersionEx((LPOSVERSIONINFO) &OSInfoEx)
1463 && OSInfoEx.dwPlatformId == VER_PLATFORM_WIN32_NT
1464 && OSInfoEx.dwMajorVersion >= 6 /* Vista or later */)
1465 {
1466 rc = RTEnvGetEx(RTENV_DEFAULT, "windir", szSysprepCmd, sizeof(szSysprepCmd), NULL);
1467 if (RT_SUCCESS(rc))
1468 rc = RTPathAppend(szSysprepCmd, sizeof(szSysprepCmd), "system32\\sysprep\\sysprep.exe");
1469 }
1470
1471 if (RT_SUCCESS(rc))
1472 {
1473 char **papszArgsExp;
1474 rc = gstcntlProcessAllocateArgv(szSysprepCmd /* argv0 */, papszArgs,
1475 fExpandArgs, &papszArgsExp);
1476 if (RT_SUCCESS(rc))
1477 {
1478 rc = RTProcCreateEx(szSysprepCmd, papszArgsExp, hEnv, 0 /* fFlags */,
1479 phStdIn, phStdOut, phStdErr, NULL /* pszAsUser */,
1480 NULL /* pszPassword */, phProcess);
1481 gstcntlProcessFreeArgv(papszArgsExp);
1482 }
1483 }
1484
1485 if (RT_FAILURE(rc))
1486 VBoxServiceVerbose(3, "Starting sysprep returned rc=%Rrc\n", rc);
1487
1488 return rc;
1489 }
1490#endif /* RT_OS_WINDOWS */
1491
1492#ifdef VBOXSERVICE_TOOLBOX
1493 if (RTStrStr(pszExec, "vbox_") == pszExec)
1494 {
1495 /* We want to use the internal toolbox (all internal
1496 * tools are starting with "vbox_" (e.g. "vbox_cat"). */
1497 rc = gstcntlProcessResolveExecutable(VBOXSERVICE_NAME, szExecExp, sizeof(szExecExp));
1498 }
1499 else
1500 {
1501#endif
1502 /*
1503 * Do the environment variables expansion on executable and arguments.
1504 */
1505 rc = gstcntlProcessResolveExecutable(pszExec, szExecExp, sizeof(szExecExp));
1506#ifdef VBOXSERVICE_TOOLBOX
1507 }
1508#endif
1509 if (RT_SUCCESS(rc))
1510 {
1511 char **papszArgsExp;
1512 rc = gstcntlProcessAllocateArgv(pszExec /* Always use the unmodified executable name as argv0. */,
1513 papszArgs /* Append the rest of the argument vector (if any). */,
1514 fExpandArgs, &papszArgsExp);
1515 if (RT_FAILURE(rc))
1516 {
1517 /* Don't print any arguments -- may contain passwords or other sensible data! */
1518 VBoxServiceError("Could not prepare arguments, rc=%Rrc\n", rc);
1519 }
1520 else
1521 {
1522 uint32_t uProcFlags = 0;
1523 if (fFlags)
1524 {
1525 if (fFlags & EXECUTEPROCESSFLAG_HIDDEN)
1526 uProcFlags |= RTPROC_FLAGS_HIDDEN;
1527 if (fFlags & EXECUTEPROCESSFLAG_NO_PROFILE)
1528 uProcFlags |= RTPROC_FLAGS_NO_PROFILE;
1529 }
1530
1531 /* If no user name specified run with current credentials (e.g.
1532 * full service/system rights). This is prohibited via official Main API!
1533 *
1534 * Otherwise use the RTPROC_FLAGS_SERVICE to use some special authentication
1535 * code (at least on Windows) for running processes as different users
1536 * started from our system service. */
1537 if (pszAsUser && *pszAsUser)
1538 uProcFlags |= RTPROC_FLAGS_SERVICE;
1539#ifdef DEBUG
1540 VBoxServiceVerbose(3, "Command: %s\n", szExecExp);
1541 for (size_t i = 0; papszArgsExp[i]; i++)
1542 VBoxServiceVerbose(3, "\targv[%ld]: %s\n", i, papszArgsExp[i]);
1543#endif
1544 VBoxServiceVerbose(3, "Starting process \"%s\" ...\n", szExecExp);
1545
1546 /* Do normal execution. */
1547 rc = RTProcCreateEx(szExecExp, papszArgsExp, hEnv, uProcFlags,
1548 phStdIn, phStdOut, phStdErr,
1549 pszAsUser && *pszAsUser ? pszAsUser : NULL,
1550 pszPassword && *pszPassword ? pszPassword : NULL,
1551 phProcess);
1552
1553 VBoxServiceVerbose(3, "Starting process \"%s\" returned rc=%Rrc\n",
1554 szExecExp, rc);
1555
1556 gstcntlProcessFreeArgv(papszArgsExp);
1557 }
1558 }
1559 return rc;
1560}
1561
1562/**
1563 * The actual worker routine (loop) for a started guest process.
1564 *
1565 * @return IPRT status code.
1566 * @param PVBOXSERVICECTRLPROCESS Guest process.
1567 */
1568static int gstcntlProcessProcessWorker(PVBOXSERVICECTRLPROCESS pProcess)
1569{
1570 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
1571 VBoxServiceVerbose(3, "Thread of process pThread=0x%p = \"%s\" started\n",
1572 pProcess, pProcess->StartupInfo.szCmd);
1573
1574 int rc = GstCntlSessionListSet(pProcess->pSession,
1575 pProcess, VBOXSERVICECTRLTHREADLIST_RUNNING);
1576 AssertRC(rc);
1577
1578 rc = VbglR3GuestCtrlConnect(&pProcess->uClientID);
1579 if (RT_FAILURE(rc))
1580 {
1581 VBoxServiceError("Thread failed to connect to the guest control service, aborted! Error: %Rrc\n", rc);
1582 RTThreadUserSignal(RTThreadSelf());
1583 return rc;
1584 }
1585 VBoxServiceVerbose(3, "Guest process \"%s\" got client ID=%u, flags=0x%x\n",
1586 pProcess->StartupInfo.szCmd, pProcess->uClientID, pProcess->StartupInfo.uFlags);
1587
1588 bool fSignalled = false; /* Indicator whether we signalled the thread user event already. */
1589
1590 /*
1591 * Prepare argument list.
1592 */
1593 char **papszArgs;
1594 uint32_t uNumArgs = 0; /* Initialize in case of RTGetOptArgvFromString() is failing ... */
1595 rc = RTGetOptArgvFromString(&papszArgs, (int*)&uNumArgs,
1596 (pProcess->StartupInfo.uNumArgs > 0) ? pProcess->StartupInfo.szArgs : "", NULL);
1597 /* Did we get the same result? */
1598 Assert(pProcess->StartupInfo.uNumArgs == uNumArgs);
1599
1600 /*
1601 * Prepare environment variables list.
1602 */
1603 char **papszEnv = NULL;
1604 uint32_t uNumEnvVars = 0; /* Initialize in case of failing ... */
1605 if (RT_SUCCESS(rc))
1606 {
1607 /* Prepare environment list. */
1608 if (pProcess->StartupInfo.uNumEnvVars)
1609 {
1610 papszEnv = (char **)RTMemAlloc(pProcess->StartupInfo.uNumEnvVars * sizeof(char*));
1611 AssertPtr(papszEnv);
1612 uNumEnvVars = pProcess->StartupInfo.uNumEnvVars;
1613
1614 const char *pszCur = pProcess->StartupInfo.szEnv;
1615 uint32_t i = 0;
1616 uint32_t cbLen = 0;
1617 while (cbLen < pProcess->StartupInfo.cbEnv)
1618 {
1619 /* sanity check */
1620 if (i >= pProcess->StartupInfo.uNumEnvVars)
1621 {
1622 rc = VERR_INVALID_PARAMETER;
1623 break;
1624 }
1625 int cbStr = RTStrAPrintf(&papszEnv[i++], "%s", pszCur);
1626 if (cbStr < 0)
1627 {
1628 rc = VERR_NO_STR_MEMORY;
1629 break;
1630 }
1631 pszCur += cbStr + 1; /* Skip terminating '\0' */
1632 cbLen += cbStr + 1; /* Skip terminating '\0' */
1633 }
1634 Assert(i == pProcess->StartupInfo.uNumEnvVars);
1635 }
1636 }
1637
1638 /*
1639 * Create the environment.
1640 */
1641 RTENV hEnv;
1642 if (RT_SUCCESS(rc))
1643 rc = RTEnvClone(&hEnv, RTENV_DEFAULT);
1644 if (RT_SUCCESS(rc))
1645 {
1646 size_t i;
1647 for (i = 0; i < uNumEnvVars && papszEnv; i++)
1648 {
1649 rc = RTEnvPutEx(hEnv, papszEnv[i]);
1650 if (RT_FAILURE(rc))
1651 break;
1652 }
1653 if (RT_SUCCESS(rc))
1654 {
1655 /*
1656 * Setup the redirection of the standard stuff.
1657 */
1658 /** @todo consider supporting: gcc stuff.c >file 2>&1. */
1659 RTHANDLE hStdIn;
1660 PRTHANDLE phStdIn;
1661 rc = gstcntlProcessSetupPipe("|", 0 /*STDIN_FILENO*/,
1662 &hStdIn, &phStdIn, &pProcess->pipeStdInW);
1663 if (RT_SUCCESS(rc))
1664 {
1665 RTHANDLE hStdOut;
1666 PRTHANDLE phStdOut;
1667 RTPIPE pipeStdOutR;
1668 rc = gstcntlProcessSetupPipe( (pProcess->StartupInfo.uFlags & EXECUTEPROCESSFLAG_WAIT_STDOUT)
1669 ? "|" : "/dev/null",
1670 1 /*STDOUT_FILENO*/,
1671 &hStdOut, &phStdOut, &pipeStdOutR);
1672 if (RT_SUCCESS(rc))
1673 {
1674 RTHANDLE hStdErr;
1675 PRTHANDLE phStdErr;
1676 RTPIPE pipeStdErrR;
1677 rc = gstcntlProcessSetupPipe( (pProcess->StartupInfo.uFlags & EXECUTEPROCESSFLAG_WAIT_STDERR)
1678 ? "|" : "/dev/null",
1679 2 /*STDERR_FILENO*/,
1680 &hStdErr, &phStdErr, &pipeStdErrR);
1681 if (RT_SUCCESS(rc))
1682 {
1683 /*
1684 * Create a poll set for the pipes and let the
1685 * transport layer add stuff to it as well.
1686 */
1687 RTPOLLSET hPollSet;
1688 rc = RTPollSetCreate(&hPollSet);
1689 if (RT_SUCCESS(rc))
1690 {
1691 uint32_t uFlags = RTPOLL_EVT_ERROR;
1692#if 0
1693 /* Add reading event to pollset to get some more information. */
1694 uFlags |= RTPOLL_EVT_READ;
1695#endif
1696 /* Stdin. */
1697 if (RT_SUCCESS(rc))
1698 rc = RTPollSetAddPipe(hPollSet, pProcess->pipeStdInW, RTPOLL_EVT_ERROR, VBOXSERVICECTRLPIPEID_STDIN);
1699 /* Stdout. */
1700 if (RT_SUCCESS(rc))
1701 rc = RTPollSetAddPipe(hPollSet, pipeStdOutR, uFlags, VBOXSERVICECTRLPIPEID_STDOUT);
1702 /* Stderr. */
1703 if (RT_SUCCESS(rc))
1704 rc = RTPollSetAddPipe(hPollSet, pipeStdErrR, uFlags, VBOXSERVICECTRLPIPEID_STDERR);
1705 /* IPC notification pipe. */
1706 if (RT_SUCCESS(rc))
1707 rc = RTPipeCreate(&pProcess->hNotificationPipeR, &pProcess->hNotificationPipeW, 0 /* Flags */);
1708 if (RT_SUCCESS(rc))
1709 rc = RTPollSetAddPipe(hPollSet, pProcess->hNotificationPipeR, RTPOLL_EVT_READ, VBOXSERVICECTRLPIPEID_IPC_NOTIFY);
1710
1711 if (RT_SUCCESS(rc))
1712 {
1713 AssertPtr(pProcess->pSession);
1714 bool fNeedsImpersonation = !(pProcess->pSession->uFlags & VBOXSERVICECTRLSESSION_FLAG_FORK);
1715
1716 RTPROCESS hProcess;
1717 rc = gstcntlProcessCreateProcess(pProcess->StartupInfo.szCmd, papszArgs, hEnv, pProcess->StartupInfo.uFlags,
1718 phStdIn, phStdOut, phStdErr,
1719 fNeedsImpersonation ? pProcess->StartupInfo.szUser : NULL,
1720 fNeedsImpersonation ? pProcess->StartupInfo.szPassword : NULL,
1721 &hProcess);
1722 if (RT_FAILURE(rc))
1723 VBoxServiceError("Error starting process, rc=%Rrc\n", rc);
1724 /*
1725 * Tell the session thread that it can continue
1726 * spawning guest processes. This needs to be done after the new
1727 * process has been started because otherwise signal handling
1728 * on (Open) Solaris does not work correctly (see @bugref{5068}).
1729 */
1730 int rc2 = RTThreadUserSignal(RTThreadSelf());
1731 if (RT_SUCCESS(rc))
1732 rc = rc2;
1733 fSignalled = true;
1734
1735 if (RT_SUCCESS(rc))
1736 {
1737 /*
1738 * Close the child ends of any pipes and redirected files.
1739 */
1740 rc2 = RTHandleClose(phStdIn); AssertRC(rc2);
1741 phStdIn = NULL;
1742 rc2 = RTHandleClose(phStdOut); AssertRC(rc2);
1743 phStdOut = NULL;
1744 rc2 = RTHandleClose(phStdErr); AssertRC(rc2);
1745 phStdErr = NULL;
1746
1747 /* Enter the process loop. */
1748 rc = gstcntlProcessProcLoop(pProcess, hProcess, hPollSet,
1749 &pProcess->pipeStdInW, &pipeStdOutR, &pipeStdErrR);
1750
1751 /*
1752 * The handles that are no longer in the set have
1753 * been closed by the above call in order to prevent
1754 * the guest from getting stuck accessing them.
1755 * So, NIL the handles to avoid closing them again.
1756 */
1757 if (RT_FAILURE(RTPollSetQueryHandle(hPollSet, VBOXSERVICECTRLPIPEID_IPC_NOTIFY, NULL)))
1758 {
1759 pProcess->hNotificationPipeR = NIL_RTPIPE;
1760 pProcess->hNotificationPipeW = NIL_RTPIPE;
1761 }
1762 if (RT_FAILURE(RTPollSetQueryHandle(hPollSet, VBOXSERVICECTRLPIPEID_STDERR, NULL)))
1763 pipeStdErrR = NIL_RTPIPE;
1764 if (RT_FAILURE(RTPollSetQueryHandle(hPollSet, VBOXSERVICECTRLPIPEID_STDOUT, NULL)))
1765 pipeStdOutR = NIL_RTPIPE;
1766 if (RT_FAILURE(RTPollSetQueryHandle(hPollSet, VBOXSERVICECTRLPIPEID_STDIN, NULL)))
1767 pProcess->pipeStdInW = NIL_RTPIPE;
1768 }
1769 }
1770 RTPollSetDestroy(hPollSet);
1771
1772 RTPipeClose(pProcess->hNotificationPipeR);
1773 pProcess->hNotificationPipeR = NIL_RTPIPE;
1774 RTPipeClose(pProcess->hNotificationPipeW);
1775 pProcess->hNotificationPipeW = NIL_RTPIPE;
1776 }
1777 RTPipeClose(pipeStdErrR);
1778 pipeStdErrR = NIL_RTPIPE;
1779 RTHandleClose(phStdErr);
1780 if (phStdErr)
1781 RTHandleClose(phStdErr);
1782 }
1783 RTPipeClose(pipeStdOutR);
1784 pipeStdOutR = NIL_RTPIPE;
1785 RTHandleClose(&hStdOut);
1786 if (phStdOut)
1787 RTHandleClose(phStdOut);
1788 }
1789 RTPipeClose(pProcess->pipeStdInW);
1790 pProcess->pipeStdInW = NIL_RTPIPE;
1791 RTHandleClose(phStdIn);
1792 }
1793 }
1794 RTEnvDestroy(hEnv);
1795 }
1796
1797 /* Move thread to stopped thread list. */
1798 /*int rc2 = GstCntlSessionListSet(pProcess->pSession,
1799 pProcess, VBOXSERVICECTRLTHREADLIST_STOPPED);
1800 AssertRC(rc2);*/
1801
1802 if (pProcess->uClientID)
1803 {
1804 if (RT_FAILURE(rc))
1805 {
1806 VBGLR3GUESTCTRLCMDCTX ctx = { pProcess->uClientID, pProcess->uContextID };
1807 int rc2 = VbglR3GuestCtrlProcCbStatus(&ctx,
1808 pProcess->uPID, PROC_STS_ERROR, rc,
1809 NULL /* pvData */, 0 /* cbData */);
1810 if (RT_FAILURE(rc2))
1811 VBoxServiceError("Could not report process failure error; rc=%Rrc (process error %Rrc)\n",
1812 rc2, rc);
1813 }
1814
1815 /* Disconnect this client from the guest control service. This also cancels all
1816 * outstanding host requests. */
1817 VBoxServiceVerbose(3, "[PID %RU32]: Disconnecting (client ID=%u) ...\n",
1818 pProcess->uPID, pProcess->uClientID);
1819 VbglR3GuestCtrlDisconnect(pProcess->uClientID);
1820 pProcess->uClientID = 0;
1821 }
1822
1823 /* Free argument + environment variable lists. */
1824 if (uNumEnvVars)
1825 {
1826 for (uint32_t i = 0; i < uNumEnvVars; i++)
1827 RTStrFree(papszEnv[i]);
1828 RTMemFree(papszEnv);
1829 }
1830 if (uNumArgs)
1831 RTGetOptArgvFree(papszArgs);
1832
1833 /* Update stopped status. */
1834 ASMAtomicXchgBool(&pProcess->fStopped, true);
1835
1836 /*
1837 * If something went wrong signal the user event so that others don't wait
1838 * forever on this thread.
1839 */
1840 if (RT_FAILURE(rc) && !fSignalled)
1841 RTThreadUserSignal(RTThreadSelf());
1842
1843 VBoxServiceVerbose(3, "[PID %RU32]: Thread of process \"%s\" ended with rc=%Rrc\n",
1844 pProcess->uPID, pProcess->StartupInfo.szCmd, rc);
1845 return rc;
1846}
1847
1848
1849static int gstcntlProcessLock(PVBOXSERVICECTRLPROCESS pProcess)
1850{
1851 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
1852 int rc = RTCritSectEnter(&pProcess->CritSect);
1853 AssertRC(rc);
1854 return rc;
1855}
1856
1857
1858/**
1859 * Thread main routine for a started process.
1860 *
1861 * @return IPRT status code.
1862 * @param RTTHREAD Pointer to the thread's data.
1863 * @param void* User-supplied argument pointer.
1864 *
1865 */
1866static DECLCALLBACK(int) gstcntlProcessThread(RTTHREAD ThreadSelf, void *pvUser)
1867{
1868 PVBOXSERVICECTRLPROCESS pProcess = (VBOXSERVICECTRLPROCESS*)pvUser;
1869 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
1870 return gstcntlProcessProcessWorker(pProcess);
1871}
1872
1873
1874static int gstcntlProcessUnlock(PVBOXSERVICECTRLPROCESS pProcess)
1875{
1876 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
1877 int rc = RTCritSectLeave(&pProcess->CritSect);
1878 AssertRC(rc);
1879 return rc;
1880}
1881
1882
1883/**
1884 * Executes (starts) a process on the guest. This causes a new thread to be created
1885 * so that this function will not block the overall program execution.
1886 *
1887 * @return IPRT status code.
1888 * @param pSession Guest session.
1889 * @param pStartupInfo Startup info.
1890 * @param uContextID Context ID to associate the process to start with.
1891
1892 */
1893int GstCntlProcessStart(const PVBOXSERVICECTRLSESSION pSession,
1894 const PVBOXSERVICECTRLPROCSTARTUPINFO pStartupInfo,
1895 uint32_t uContextID)
1896{
1897 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1898 AssertPtrReturn(pStartupInfo, VERR_INVALID_POINTER);
1899
1900 /*
1901 * Allocate new thread data and assign it to our thread list.
1902 */
1903 PVBOXSERVICECTRLPROCESS pProcess = (PVBOXSERVICECTRLPROCESS)RTMemAlloc(sizeof(VBOXSERVICECTRLPROCESS));
1904 if (!pProcess)
1905 return VERR_NO_MEMORY;
1906
1907 int rc = gstcntlProcessInit(pProcess, pSession, pStartupInfo, uContextID);
1908 if (RT_SUCCESS(rc))
1909 {
1910 static uint32_t s_uCtrlExecThread = 0;
1911 if (s_uCtrlExecThread++ == UINT32_MAX)
1912 s_uCtrlExecThread = 0; /* Wrap around to not let IPRT freak out. */
1913 rc = RTThreadCreateF(&pProcess->Thread, gstcntlProcessThread,
1914 pProcess /*pvUser*/, 0 /*cbStack*/,
1915 RTTHREADTYPE_DEFAULT, RTTHREADFLAGS_WAITABLE, "gctl%u", s_uCtrlExecThread);
1916 if (RT_FAILURE(rc))
1917 {
1918 VBoxServiceError("Creating thread for guest process failed: rc=%Rrc, pProcess=%p\n",
1919 rc, pProcess);
1920 }
1921 else
1922 {
1923 VBoxServiceVerbose(4, "Waiting for thread to initialize ...\n");
1924
1925 /* Wait for the thread to initialize. */
1926 rc = RTThreadUserWait(pProcess->Thread, 60 * 1000 /* 60 seconds max. */);
1927 AssertRC(rc);
1928 if ( ASMAtomicReadBool(&pProcess->fShutdown)
1929 || RT_FAILURE(rc))
1930 {
1931 VBoxServiceError("Thread for process \"%s\" failed to start, rc=%Rrc\n",
1932 pStartupInfo->szCmd, rc);
1933 }
1934 else
1935 {
1936 ASMAtomicXchgBool(&pProcess->fStarted, true);
1937 }
1938 }
1939 }
1940
1941 if (RT_FAILURE(rc))
1942 GstCntlProcessFree(pProcess);
1943
1944 return rc;
1945}
1946
1947
1948/**
1949 * Performs a request to a specific (formerly started) guest process and waits
1950 * for its response.
1951 * Note: Caller is responsible for locking!
1952 *
1953 * @return IPRT status code.
1954 * @param pProcess Guest process to perform operation on.
1955 * @param pRequest Pointer to request to perform.
1956 */
1957int GstCntlProcessPerform(PVBOXSERVICECTRLPROCESS pProcess,
1958 PVBOXSERVICECTRLREQUEST pRequest,
1959 bool fAsync)
1960{
1961 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
1962 AssertPtrReturn(pRequest, VERR_INVALID_POINTER);
1963 AssertReturn(pRequest->enmType > VBOXSERVICECTRLREQUEST_UNKNOWN, VERR_INVALID_PARAMETER);
1964 /* Rest in pRequest is optional (based on the request type). */
1965
1966 int rc = VINF_SUCCESS;
1967
1968 if ( ASMAtomicReadBool(&pProcess->fShutdown)
1969 || ASMAtomicReadBool(&pProcess->fStopped))
1970 {
1971 rc = VERR_CANCELLED;
1972 }
1973 else
1974 {
1975 rc = gstcntlProcessLock(pProcess);
1976 if (RT_SUCCESS(rc))
1977 {
1978 AssertMsgReturn(pProcess->pRequest == NULL,
1979 ("Another request still is in progress (%p)\n", pProcess->pRequest),
1980 VERR_ALREADY_EXISTS);
1981
1982 VBoxServiceVerbose(3, "[PID %RU32]: Sending pRequest=%p\n",
1983 pProcess->uPID, pRequest);
1984
1985 /* Set request structure pointer. */
1986 pProcess->pRequest = pRequest;
1987
1988 /** @todo To speed up simultaneous guest process handling we could add a worker threads
1989 * or queue in order to wait for the request to happen. Later. */
1990 /* Wake up guest thread by sending a wakeup byte to the notification pipe so
1991 * that RTPoll unblocks (returns) and we then can do our requested operation. */
1992 Assert(pProcess->hNotificationPipeW != NIL_RTPIPE);
1993 size_t cbWritten = 0;
1994 if (RT_SUCCESS(rc))
1995 rc = RTPipeWrite(pProcess->hNotificationPipeW, "i", 1, &cbWritten);
1996
1997 int rcWait = VINF_SUCCESS;
1998 if (RT_SUCCESS(rc))
1999 {
2000 Assert(cbWritten);
2001 if (!fAsync)
2002 {
2003 VBoxServiceVerbose(3, "[PID %RU32]: Waiting for response on pRequest=%p, enmType=%u, pvData=0x%p, cbData=%u\n",
2004 pProcess->uPID, pRequest, pRequest->enmType, pRequest->pvData, pRequest->cbData);
2005
2006 rc = gstcntlProcessUnlock(pProcess);
2007 if (RT_SUCCESS(rc))
2008 rcWait = GstCntlProcessRequestWait(pRequest);
2009
2010 /* NULL current request in any case. */
2011 pProcess->pRequest = NULL;
2012 }
2013 }
2014
2015 if ( RT_FAILURE(rc)
2016 || fAsync)
2017 {
2018 int rc2 = gstcntlProcessUnlock(pProcess);
2019 AssertRC(rc2);
2020 }
2021
2022 if (RT_SUCCESS(rc))
2023 rc = rcWait;
2024 }
2025 }
2026
2027 VBoxServiceVerbose(3, "[PID %RU32]: Performed pRequest=%p, enmType=%u, uCID=%u, pvData=0x%p, cbData=%u, rc=%Rrc\n",
2028 pProcess->uPID, pRequest, pRequest->enmType, pRequest->uCID, pRequest->pvData, pRequest->cbData, rc);
2029 return rc;
2030}
2031
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