1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // +build darwin freebsd linux openbsd
7 // Fork, exec, wait, etc.
16 //sysnb raw_fork() (pid Pid_t, errno int)
19 //sysnb raw_setsid() (errno int)
22 //sysnb raw_chroot(path *byte) (errno int)
23 //chroot(path *byte) int
25 //sysnb raw_chdir(path *byte) (errno int)
26 //chdir(path *byte) int
28 //sysnb raw_fcntl(fd int, cmd int, arg int) (val int, errno int)
29 //fcntl(fd int, cmd int, arg int) int
31 //sysnb raw_close(fd int) (errno int)
34 //sysnb raw_ioctl(fd int, cmd int, val int) (rval int, errno int)
35 //ioctl(fd int, cmd int, val int) int
37 //sysnb raw_execve(argv0 *byte, argv **byte, envv **byte) (errno int)
38 //execve(argv0 *byte, argv **byte, envv **byte) int
40 //sysnb raw_read(fd int, p *byte, np int) (n int, errno int)
41 //read(fd int, buf *byte, count Size_t) Ssize_t
43 //sysnb raw_write(fd int, buf *byte, count int) int
44 //write(fd int, buf *byte, count Size_t) Ssize_t
46 //sysnb raw_exit(status int)
49 // Lock synchronizing creation of new file descriptors with fork.
51 // We want the child in a fork/exec sequence to inherit only the
52 // file descriptors we intend. To do that, we mark all file
53 // descriptors close-on-exec and then, in the child, explicitly
54 // unmark the ones we want the exec'ed program to keep.
55 // Unix doesn't make this easy: there is, in general, no way to
56 // allocate a new file descriptor close-on-exec. Instead you
57 // have to allocate the descriptor and then mark it close-on-exec.
58 // If a fork happens between those two events, the child's exec
59 // will inherit an unwanted file descriptor.
61 // This lock solves that race: the create new fd/mark close-on-exec
62 // operation is done holding ForkLock for reading, and the fork itself
63 // is done holding ForkLock for writing. At least, that's the idea.
64 // There are some complications.
66 // Some system calls that create new file descriptors can block
67 // for arbitrarily long times: open on a hung NFS server or named
68 // pipe, accept on a socket, and so on. We can't reasonably grab
69 // the lock across those operations.
71 // It is worse to inherit some file descriptors than others.
72 // If a non-malicious child accidentally inherits an open ordinary file,
73 // that's not a big deal. On the other hand, if a long-lived child
74 // accidentally inherits the write end of a pipe, then the reader
75 // of that pipe will not see EOF until that child exits, potentially
76 // causing the parent program to hang. This is a common problem
77 // in threaded C programs that use popen.
79 // Luckily, the file descriptors that are most important not to
80 // inherit are not the ones that can take an arbitrarily long time
81 // to create: pipe returns instantly, and the net package uses
82 // non-blocking I/O to accept on a listening socket.
83 // The rules for which file descriptor-creating operations use the
84 // ForkLock are as follows:
86 // 1) Pipe. Does not block. Use the ForkLock.
87 // 2) Socket. Does not block. Use the ForkLock.
88 // 3) Accept. If using non-blocking mode, use the ForkLock.
89 // Otherwise, live with the race.
90 // 4) Open. Can block. Use O_CLOEXEC if available (Linux).
91 // Otherwise, live with the race.
92 // 5) Dup. Does not block. Use the ForkLock.
93 // On Linux, could use fcntl F_DUPFD_CLOEXEC
94 // instead of the ForkLock, but only for dup(fd, -1).
96 var ForkLock sync.RWMutex
98 // Convert array of string to array
99 // of NUL-terminated byte pointer.
100 func StringSlicePtr(ss []string) []*byte {
101 bb := make([]*byte, len(ss)+1)
102 for i := 0; i < len(ss); i++ {
103 bb[i] = StringBytePtr(ss[i])
109 func CloseOnExec(fd int) { fcntl(fd, F_SETFD, FD_CLOEXEC) }
111 func SetNonblock(fd int, nonblocking bool) (errno int) {
112 flag, err := fcntl(fd, F_GETFL, 0)
121 _, err = fcntl(fd, F_SETFL, flag)
125 // Fork, dup fd onto 0..len(fd), and exec(argv0, argvv, envv) in child.
126 // If a dup or exec fails, write the errno int to pipe.
127 // (Pipe is close-on-exec so if exec succeeds, it will be closed.)
128 // In the child, this function must not acquire any locks, because
129 // they might have been locked at the time of the fork. This means
130 // no rescheduling, no malloc calls, and no new stack segments.
131 // The calls to RawSyscall are okay because they are assembly
132 // functions that do not grow the stack.
133 func forkAndExecInChild(argv0 *byte, argv, envv []*byte, chroot, dir *byte, attr *ProcAttr, sys *SysProcAttr, pipe int) (pid int, err int) {
134 // Declare all variables at top in case any
135 // declarations require heap allocation (e.g., err1).
141 // guard against side effects of shuffling fds below.
142 fd := append([]int(nil), attr.Files...)
144 // About to call fork.
145 // No more allocation or calls of non-assembly functions.
146 r1, err1 = raw_fork()
152 // parent; return PID
156 // Fork succeeded, now in child.
158 // Enable tracing if requested.
160 err1 = raw_ptrace(_PTRACE_TRACEME, 0, nil, nil)
184 err1 = raw_chroot(chroot)
191 if cred := sys.Credential; cred != nil {
192 ngroups := len(cred.Groups)
194 err1 = setgroups(0, nil)
196 groups := make([]Gid_t, ngroups)
197 for i, v := range cred.Groups {
200 err1 = setgroups(ngroups, &groups[0])
205 err1 = Setgid(int(cred.Gid))
209 err1 = Setuid(int(cred.Uid))
217 err1 = raw_chdir(dir)
223 // Pass 1: look for fd[i] < i and move those up above len(fd)
224 // so that pass 2 won't stomp on an fd it needs later.
225 nextfd = int(len(fd))
227 _, err1 = Dup2(pipe, nextfd)
231 raw_fcntl(nextfd, F_SETFD, FD_CLOEXEC)
235 for i = 0; i < len(fd); i++ {
236 if fd[i] >= 0 && fd[i] < int(i) {
237 _, err1 = Dup2(fd[i], nextfd)
241 raw_fcntl(nextfd, F_SETFD, FD_CLOEXEC)
244 if nextfd == pipe { // don't stomp on pipe
250 // Pass 2: dup fd[i] down onto i.
251 for i = 0; i < len(fd); i++ {
257 // Dup2(i, i) won't clear close-on-exec flag on Linux,
258 // probably not elsewhere either.
259 _, err1 = raw_fcntl(fd[i], F_SETFD, 0)
265 // The new fd is created NOT close-on-exec,
266 // which is exactly what we want.
267 _, err1 = Dup2(fd[i], i)
273 // By convention, we don't close-on-exec the fds we are
274 // started with, so if len(fd) < 3, close 0, 1, 2 as needed.
275 // Programs that know they inherit fds >= 3 will need
276 // to set them close-on-exec.
277 for i = len(fd); i < 3; i++ {
281 // Detach fd 0 from tty
283 _, err1 = raw_ioctl(0, TIOCNOTTY, 0)
291 _, err1 = raw_ioctl(0, TIOCSCTTY, 0)
298 err1 = raw_execve(argv0, &argv[0], &envv[0])
301 // send error code on pipe
302 raw_write(pipe, (*byte)(unsafe.Pointer(&err1)), int(unsafe.Sizeof(err1)))
307 // Calling panic is not actually safe,
308 // but the for loop above won't break
309 // and this shuts up the compiler.
313 // Credential holds user and group identities to be assumed
314 // by a child process started by StartProcess.
315 type Credential struct {
316 Uid uint32 // User ID.
317 Gid uint32 // Group ID.
318 Groups []uint32 // Supplementary group IDs.
321 // ProcAttr holds attributes that will be applied to a new process started
323 type ProcAttr struct {
324 Dir string // Current working directory.
325 Env []string // Environment.
326 Files []int // File descriptors.
330 type SysProcAttr struct {
331 Chroot string // Chroot.
332 Credential *Credential // Credential.
333 Ptrace bool // Enable tracing.
334 Setsid bool // Create session.
335 Setpgid bool // Set process group ID to new pid (SYSV setpgrp)
336 Setctty bool // Set controlling terminal to fd 0
337 Noctty bool // Detach fd 0 from controlling terminal
340 var zeroProcAttr ProcAttr
341 var zeroSysProcAttr SysProcAttr
343 func forkExec(argv0 string, argv []string, attr *ProcAttr) (pid int, err int) {
347 var wstatus WaitStatus
354 sys = &zeroSysProcAttr
360 // Convert args to C form.
361 argv0p := StringBytePtr(argv0)
362 argvp := StringSlicePtr(argv)
363 envvp := StringSlicePtr(attr.Env)
365 if OS == "freebsd" && len(argv[0]) > len(argv0) {
370 if sys.Chroot != "" {
371 chroot = StringBytePtr(sys.Chroot)
375 dir = StringBytePtr(attr.Dir)
378 // Acquire the fork lock so that no other threads
379 // create new fds that are not yet close-on-exec
383 // Allocate child status pipe close on exec.
384 if err = Pipe(p[0:]); err != 0 {
387 if _, err = fcntl(p[0], F_SETFD, FD_CLOEXEC); err != 0 {
390 if _, err = fcntl(p[1], F_SETFD, FD_CLOEXEC); err != 0 {
395 pid, err = forkAndExecInChild(argv0p, argvp, envvp, chroot, dir, attr, sys, p[1])
401 // Read child error status from pipe.
403 n, err = raw_read(p[0], (*byte)(unsafe.Pointer(&err1)), int(unsafe.Sizeof(err1)))
405 if err != 0 || n != 0 {
406 if n == int(unsafe.Sizeof(err1)) {
413 // Child failed; wait for it to exit, to make sure
414 // the zombies don't accumulate.
415 _, err1 := Wait4(pid, &wstatus, 0, nil)
417 _, err1 = Wait4(pid, &wstatus, 0, nil)
422 // Read got EOF, so pipe closed on exec, so exec succeeded.
434 // Combination of fork and exec, careful to be thread safe.
435 func ForkExec(argv0 string, argv []string, attr *ProcAttr) (pid int, err int) {
436 return forkExec(argv0, argv, attr)
439 // StartProcess wraps ForkExec for package os.
440 func StartProcess(argv0 string, argv []string, attr *ProcAttr) (pid, handle int, err int) {
441 pid, err = forkExec(argv0, argv, attr)
446 func Exec(argv0 string, argv []string, envv []string) (err int) {
447 err1 := raw_execve(StringBytePtr(argv0),
448 &StringSlicePtr(argv)[0],
449 &StringSlicePtr(envv)[0])