VirtualBox

source: vbox/trunk/src/VBox/Runtime/r3/posix/process-posix.cpp@ 29328

Last change on this file since 29328 was 29328, checked in by vboxsync, 15 years ago

process-posix.cpp: Unbroke VBoxService on non-windows guests.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 16.5 KB
Line 
1/* $Id: process-posix.cpp 29328 2010-05-11 10:14:47Z vboxsync $ */
2/** @file
3 * IPRT - Process, POSIX.
4 */
5
6/*
7 * Copyright (C) 2006-2010 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 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28
29/*******************************************************************************
30* Header Files *
31*******************************************************************************/
32#define LOG_GROUP RTLOGGROUP_PROCESS
33#include <unistd.h>
34#include <stdlib.h>
35#include <errno.h>
36#include <sys/types.h>
37#include <sys/stat.h>
38#include <sys/wait.h>
39#include <fcntl.h>
40#include <signal.h>
41#if defined(RT_OS_LINUX) || defined(RT_OS_OS2)
42# define HAVE_POSIX_SPAWN 1
43#endif
44#ifdef HAVE_POSIX_SPAWN
45# include <spawn.h>
46#endif
47#ifdef RT_OS_DARWIN
48# include <mach-o/dyld.h>
49#endif
50
51#include <iprt/process.h>
52#include "internal/iprt.h"
53
54#include <iprt/assert.h>
55#include <iprt/env.h>
56#include <iprt/err.h>
57#include <iprt/file.h>
58#include <iprt/pipe.h>
59#include <iprt/socket.h>
60#include <iprt/string.h>
61#include "internal/process.h"
62
63
64
65RTR3DECL(int) RTProcCreate(const char *pszExec, const char * const *papszArgs, RTENV Env, unsigned fFlags, PRTPROCESS pProcess)
66{
67 return RTProcCreateEx(pszExec, papszArgs, Env, fFlags,
68 NULL, NULL, NULL, /* standard handles */
69 NULL /*pszAsUser*/, NULL /* pszPassword*/,
70 pProcess);
71}
72
73
74RTR3DECL(int) RTProcCreateEx(const char *pszExec, const char * const *papszArgs, RTENV hEnv, uint32_t fFlags,
75 PCRTHANDLE phStdIn, PCRTHANDLE phStdOut, PCRTHANDLE phStdErr, const char *pszAsUser,
76 const char *pszPassword, PRTPROCESS phProcess)
77{
78 int rc;
79
80 /*
81 * Input validation
82 */
83 AssertPtrReturn(pszExec, VERR_INVALID_POINTER);
84 AssertReturn(*pszExec, VERR_INVALID_PARAMETER);
85 AssertReturn(!(fFlags & ~(RTPROC_FLAGS_DAEMONIZE_DEPRECATED | RTPROC_FLAGS_DETACHED | RTPROC_FLAGS_SERVICE)), VERR_INVALID_PARAMETER);
86 AssertReturn(!(fFlags & RTPROC_FLAGS_DETACHED) || !phProcess, VERR_INVALID_PARAMETER);
87 AssertReturn(hEnv != NIL_RTENV, VERR_INVALID_PARAMETER);
88 const char * const *papszEnv = RTEnvGetExecEnvP(hEnv);
89 AssertPtrReturn(papszEnv, VERR_INVALID_HANDLE);
90 AssertPtrReturn(papszArgs, VERR_INVALID_PARAMETER);
91 /** @todo search the PATH (add flag for this). */
92 AssertPtrNullReturn(pszAsUser, VERR_INVALID_POINTER);
93 AssertReturn(!pszAsUser || *pszAsUser, VERR_INVALID_PARAMETER);
94 AssertReturn(!pszPassword || pszAsUser, VERR_INVALID_PARAMETER);
95 AssertPtrNullReturn(pszPassword, VERR_INVALID_POINTER);
96
97 /*
98 * Get the file descriptors for the handles we've been passed.
99 */
100 PCRTHANDLE paHandles[3] = { phStdIn, phStdOut, phStdErr };
101 int aStdFds[3] = { -1, -1, -1 };
102 for (int i = 0; i < 3; i++)
103 {
104 if (paHandles[i])
105 {
106 AssertPtrReturn(paHandles[i], VERR_INVALID_POINTER);
107 switch (paHandles[i]->enmType)
108 {
109 case RTHANDLETYPE_FILE:
110 aStdFds[i] = paHandles[i]->u.hFile != NIL_RTFILE
111 ? (int)RTFileToNative(paHandles[i]->u.hFile)
112 : -2 /* close it */;
113 break;
114
115 case RTHANDLETYPE_PIPE:
116 aStdFds[i] = paHandles[i]->u.hPipe != NIL_RTPIPE
117 ? (int)RTPipeToNative(paHandles[i]->u.hPipe)
118 : -2 /* close it */;
119 break;
120
121 case RTHANDLETYPE_SOCKET:
122 aStdFds[i] = paHandles[i]->u.hSocket != NIL_RTSOCKET
123 ? (int)RTSocketToNative(paHandles[i]->u.hSocket)
124 : -2 /* close it */;
125 break;
126
127 default:
128 AssertMsgFailedReturn(("%d: %d\n", i, paHandles[i]->enmType), VERR_INVALID_PARAMETER);
129 }
130 /** @todo check the close-on-execness of these handles? */
131 }
132 }
133
134 for (int i = 0; i < 3; i++)
135 if (aStdFds[i] == i)
136 aStdFds[i] = -1;
137
138 for (int i = 0; i < 3; i++)
139 AssertMsgReturn(aStdFds[i] < 0 || aStdFds[i] > i,
140 ("%i := %i not possible because we're lazy\n", i, aStdFds[i]),
141 VERR_NOT_SUPPORTED);
142
143 /*
144 * Resolve the user id if specified.
145 */
146 uid_t uid = ~(uid_t)0;
147 gid_t gid = ~(gid_t)0;
148 if (pszAsUser)
149 {
150 AssertMsgFailed(("Implement get uid by name lookup\n"));
151 return VERR_NOT_IMPLEMENTED;
152 }
153
154 /*
155 * Check for execute access to the file.
156 */
157 if (access(pszExec, X_OK))
158 {
159 rc = RTErrConvertFromErrno(errno);
160 AssertMsgFailed(("'%s' %Rrc!\n", pszExec, rc));
161 return rc;
162 }
163
164 /*
165 * Spawn the child.
166 *
167 * HACK ALERT! Put the process into a new process group with pgid = pid
168 * to make sure it differs from that of the parent process to ensure that
169 * the IPRT waipit call doesn't race anyone (read XPCOM) doing group wide
170 * waits.
171 */
172 pid_t pid = -1;
173#ifdef HAVE_POSIX_SPAWN
174 /** @todo OS/2: implement DETACHED (BACKGROUND stuff), see VbglR3Daemonize. */
175 /** @todo Try do the detach thing with posix spawn. */
176 if ( !(fFlags & (RTPROC_FLAGS_DAEMONIZE_DEPRECATED | RTPROC_FLAGS_DETACHED))
177 && uid == ~(uid_t)0
178 && gid == ~(gid_t)0
179 )
180 {
181 /* Spawn attributes. */
182 posix_spawnattr_t Attr;
183 rc = posix_spawnattr_init(&Attr);
184 if (!rc)
185 {
186# ifndef RT_OS_OS2 /* We don't need this on OS/2 and I don't recall if it's actually implemented. */
187 rc = posix_spawnattr_setflags(&Attr, POSIX_SPAWN_SETPGROUP);
188 Assert(rc == 0);
189 if (!rc)
190 {
191 rc = posix_spawnattr_setpgroup(&Attr, 0 /* pg == child pid */);
192 Assert(rc == 0);
193 }
194# endif
195
196 /* File changes. */
197 posix_spawn_file_actions_t FileActions;
198 posix_spawn_file_actions_t *pFileActions = NULL;
199 if (aStdFds[0] != -1 || aStdFds[1] != -1 || aStdFds[2] != -1)
200 {
201 rc = posix_spawn_file_actions_init(&FileActions);
202 if (!rc)
203 {
204 pFileActions = &FileActions;
205 for (int i = 0; i < 3; i++)
206 {
207 int fd = aStdFds[i];
208 if (fd == -2)
209 rc = posix_spawn_file_actions_addclose(&FileActions, i);
210 else if (fd >= 0 && fd != i)
211 {
212 rc = posix_spawn_file_actions_adddup2(&FileActions, fd, i);
213 if (!rc)
214 {
215 for (int j = i + 1; j < 3; j++)
216 if (aStdFds[j] == fd)
217 {
218 fd = -1;
219 break;
220 }
221 if (fd >= 0)
222 rc = posix_spawn_file_actions_addclose(&FileActions, fd);
223 }
224 }
225 if (rc)
226 break;
227 }
228 }
229 }
230
231 if (!rc)
232 rc = posix_spawn(&pid, pszExec, pFileActions, &Attr, (char * const *)papszArgs,
233 (char * const *)papszEnv);
234
235 /* cleanup */
236 int rc2 = posix_spawnattr_destroy(&Attr); Assert(rc2 == 0); NOREF(rc2);
237 if (pFileActions)
238 {
239 rc2 = posix_spawn_file_actions_destroy(pFileActions);
240 Assert(rc2 == 0);
241 }
242
243 /* return on success.*/
244 if (!rc)
245 {
246 if (phProcess)
247 *phProcess = pid;
248 return VINF_SUCCESS;
249 }
250 }
251 }
252 else
253#endif
254 {
255 pid = fork();
256 if (!pid)
257 {
258 setpgid(0, 0); /* see comment above */
259
260 /*
261 * Change group and user if requested.
262 */
263#if 1 /** @todo This needs more work, see suplib/hardening. */
264 if (gid != ~(gid_t)0)
265 {
266 if (setgid(gid))
267 exit(126);
268 }
269
270 if (uid != ~(uid_t)0)
271 {
272 if (setuid(uid))
273 exit(126);
274 }
275#endif
276
277 /*
278 * Apply changes to the standard file descriptor and stuff.
279 */
280 for (int i = 0; i < 3; i++)
281 {
282 int fd = aStdFds[i];
283 if (fd == -2)
284 close(i);
285 else if (fd >= 0)
286 {
287 int rc2 = dup2(fd, i);
288 if (rc2 != i)
289 exit(125);
290 for (int j = i + 1; j < 3; j++)
291 if (aStdFds[j] == fd)
292 {
293 fd = -1;
294 break;
295 }
296 if (fd >= 0)
297 close(fd);
298 }
299 }
300
301 /*
302 * Daemonize the process if requested.
303 */
304 if (fFlags & (RTPROC_FLAGS_DAEMONIZE_DEPRECATED | RTPROC_FLAGS_DETACHED))
305 {
306 rc = RTProcDaemonizeUsingFork(true /*fNoChDir*/,
307 !(fFlags & RTPROC_FLAGS_DAEMONIZE_DEPRECATED) /*fNoClose*/,
308 NULL /* pszPidFile */);
309 if (RT_FAILURE(rc))
310 {
311 /* parent */
312 AssertReleaseMsgFailed(("RTProcDaemonize returns %Rrc errno=%d\n", rc, errno));
313 exit(127);
314 }
315 /* daemonized child */
316 }
317
318 /*
319 * Finally, execute the requested program.
320 */
321 rc = execve(pszExec, (char * const *)papszArgs, (char * const *)papszEnv);
322 AssertReleaseMsgFailed(("execve returns %d errno=%d\n", rc, errno));
323 exit(127);
324 }
325 if (pid > 0)
326 {
327 if (phProcess)
328 *phProcess = pid;
329 return VINF_SUCCESS;
330 }
331 rc = errno;
332 }
333
334
335 return VERR_NOT_IMPLEMENTED;
336}
337
338
339RTR3DECL(int) RTProcWait(RTPROCESS Process, unsigned fFlags, PRTPROCSTATUS pProcStatus)
340{
341 int rc;
342 do rc = RTProcWaitNoResume(Process, fFlags, pProcStatus);
343 while (rc == VERR_INTERRUPTED);
344 return rc;
345}
346
347RTR3DECL(int) RTProcWaitNoResume(RTPROCESS Process, unsigned fFlags, PRTPROCSTATUS pProcStatus)
348{
349 /*
350 * Validate input.
351 */
352 if (Process <= 0)
353 {
354 AssertMsgFailed(("Invalid Process=%d\n", Process));
355 return VERR_INVALID_PARAMETER;
356 }
357 if (fFlags & ~(RTPROCWAIT_FLAGS_NOBLOCK | RTPROCWAIT_FLAGS_BLOCK))
358 {
359 AssertMsgFailed(("Invalid flags %#x\n", fFlags));
360 return VERR_INVALID_PARAMETER;
361 }
362
363 /*
364 * Performe the wait.
365 */
366 int iStatus = 0;
367 int rc = waitpid(Process, &iStatus, fFlags & RTPROCWAIT_FLAGS_NOBLOCK ? WNOHANG : 0);
368 if (rc > 0)
369 {
370 /*
371 * Fill in the status structure.
372 */
373 if (pProcStatus)
374 {
375 if (WIFEXITED(iStatus))
376 {
377 pProcStatus->enmReason = RTPROCEXITREASON_NORMAL;
378 pProcStatus->iStatus = WEXITSTATUS(iStatus);
379 }
380 else if (WIFSIGNALED(iStatus))
381 {
382 pProcStatus->enmReason = RTPROCEXITREASON_SIGNAL;
383 pProcStatus->iStatus = WTERMSIG(iStatus);
384 }
385 else
386 {
387 Assert(!WIFSTOPPED(iStatus));
388 pProcStatus->enmReason = RTPROCEXITREASON_ABEND;
389 pProcStatus->iStatus = iStatus;
390 }
391 }
392 return VINF_SUCCESS;
393 }
394
395 /*
396 * Child running?
397 */
398 if (!rc)
399 {
400 Assert(fFlags & RTPROCWAIT_FLAGS_NOBLOCK);
401 return VERR_PROCESS_RUNNING;
402 }
403
404 /*
405 * Figure out which error to return.
406 */
407 int iErr = errno;
408 if (iErr == ECHILD)
409 return VERR_PROCESS_NOT_FOUND;
410 return RTErrConvertFromErrno(iErr);
411}
412
413
414RTR3DECL(int) RTProcTerminate(RTPROCESS Process)
415{
416 if (!kill(Process, SIGKILL))
417 return VINF_SUCCESS;
418 return RTErrConvertFromErrno(errno);
419}
420
421
422RTR3DECL(uint64_t) RTProcGetAffinityMask()
423{
424 // @todo
425 return 1;
426}
427
428
429RTR3DECL(int) RTProcDaemonizeUsingFork(bool fNoChDir, bool fNoClose, const char *pszPidfile)
430{
431 /*
432 * Fork the child process in a new session and quit the parent.
433 *
434 * - fork once and create a new session (setsid). This will detach us
435 * from the controlling tty meaning that we won't receive the SIGHUP
436 * (or any other signal) sent to that session.
437 * - The SIGHUP signal is ignored because the session/parent may throw
438 * us one before we get to the setsid.
439 * - When the parent exit(0) we will become an orphan and re-parented to
440 * the init process.
441 * - Because of the sometimes unexpected semantics of assigning the
442 * controlling tty automagically when a session leader first opens a tty,
443 * we will fork() once more to get rid of the session leadership role.
444 */
445
446 /* We start off by opening the pidfile, so that we can fail straight away
447 * if it already exists. */
448 int fdPidfile = -1;
449 if (pszPidfile != NULL)
450 {
451 /* @note the exclusive create is not guaranteed on all file
452 * systems (e.g. NFSv2) */
453 if ((fdPidfile = open(pszPidfile, O_RDWR | O_CREAT | O_EXCL, 0644)) == -1)
454 return RTErrConvertFromErrno(errno);
455 }
456
457 /* Ignore SIGHUP straight away. */
458 struct sigaction OldSigAct;
459 struct sigaction SigAct;
460 memset(&SigAct, 0, sizeof(SigAct));
461 SigAct.sa_handler = SIG_IGN;
462 int rcSigAct = sigaction(SIGHUP, &SigAct, &OldSigAct);
463
464 /* First fork, to become independent process. */
465 pid_t pid = fork();
466 if (pid == -1)
467 return RTErrConvertFromErrno(errno);
468 if (pid != 0)
469 {
470 /* Parent exits, no longer necessary. The child gets reparented
471 * to the init process. */
472 exit(0);
473 }
474
475 /* Create new session, fix up the standard file descriptors and the
476 * current working directory. */
477 pid_t newpgid = setsid();
478 int SavedErrno = errno;
479 if (rcSigAct != -1)
480 sigaction(SIGHUP, &OldSigAct, NULL);
481 if (newpgid == -1)
482 return RTErrConvertFromErrno(SavedErrno);
483
484 if (!fNoClose)
485 {
486 /* Open stdin(0), stdout(1) and stderr(2) as /dev/null. */
487 int fd = open("/dev/null", O_RDWR);
488 if (fd == -1) /* paranoia */
489 {
490 close(STDIN_FILENO);
491 close(STDOUT_FILENO);
492 close(STDERR_FILENO);
493 fd = open("/dev/null", O_RDWR);
494 }
495 if (fd != -1)
496 {
497 dup2(fd, STDIN_FILENO);
498 dup2(fd, STDOUT_FILENO);
499 dup2(fd, STDERR_FILENO);
500 if (fd > 2)
501 close(fd);
502 }
503 }
504
505 if (!fNoChDir)
506 {
507 int rcChdir = chdir("/");
508 }
509
510 /* Second fork to lose session leader status. */
511 pid = fork();
512 if (pid == -1)
513 return RTErrConvertFromErrno(errno);
514
515 if (pid != 0)
516 {
517 /* Write the pid file, this is done in the parent, before exiting. */
518 if (fdPidfile != -1)
519 {
520 char szBuf[256];
521 size_t cbPid = RTStrPrintf(szBuf, sizeof(szBuf), "%d\n", pid);
522 int rcWrite = write(fdPidfile, szBuf, cbPid);
523 close(fdPidfile);
524 }
525 exit(0);
526 }
527
528 return VINF_SUCCESS;
529}
530
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