Debian Codegraph @

libgo/go/syscall/exec_unix.go

raw
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.
4
5 //go:build aix || darwin || dragonfly || freebsd || hurd || linux || netbsd || openbsd || solaris
6
7 // Fork, exec, wait, etc.
8
9 package syscall
10
11 import (
12 errorspkg "errors"
13 "internal/bytealg"
14 "runtime"
15 "sync"
16 "unsafe"
17 )
18
19 //sysnb raw_fork() (pid Pid_t, err Errno)
20 //fork() Pid_t
21
22 //sysnb raw_getpid() (pid Pid_t)
23 //getpid() Pid_t
24
25 //sysnb raw_getppid() (pid Pid_t)
26 //getppid() Pid_t
27
28 //sysnb raw_setsid() (err Errno)
29 //setsid() Pid_t
30
31 //sysnb raw_setpgid(pid int, pgid int) (err Errno)
32 //setpgid(pid Pid_t, pgid Pid_t) _C_int
33
34 //sysnb raw_chroot(path *byte) (err Errno)
35 //chroot(path *byte) _C_int
36
37 //sysnb raw_chdir(path *byte) (err Errno)
38 //chdir(path *byte) _C_int
39
40 //sysnb raw_fcntl(fd int, cmd int, arg int) (val int, err Errno)
41 //__go_fcntl(fd _C_int, cmd _C_int, arg _C_int) _C_int
42
43 //sysnb raw_close(fd int) (err Errno)
44 //close(fd _C_int) _C_int
45
46 //sysnb raw_ioctl(fd int, cmd uintptr, val int) (rval int, err Errno)
47 //__go_ioctl(fd _C_int, cmd _C_int, val _C_int) _C_int
48
49 //sysnb raw_ioctl_ptr(fd int, cmd uintptr, val unsafe.Pointer) (rval int, err Errno)
50 //__go_ioctl_ptr(fd _C_int, cmd _C_int, val unsafe.Pointer) _C_int
51
52 //sysnb raw_execve(argv0 *byte, argv **byte, envv **byte) (err Errno)
53 //execve(argv0 *byte, argv **byte, envv **byte) _C_int
54
55 //sysnb raw_read(fd int, buf *byte, count int) (c int, err Errno)
56 //read(fd _C_int, buf *byte, count Size_t) Ssize_t
57
58 //sysnb raw_write(fd int, buf *byte, count int) (c int, err Errno)
59 //write(fd _C_int, buf *byte, count Size_t) Ssize_t
60
61 //sysnb raw_exit(status int)
62 //_exit(status _C_int)
63
64 //sysnb raw_dup2(oldfd int, newfd int) (err Errno)
65 //dup2(oldfd _C_int, newfd _C_int) _C_int
66
67 //sysnb raw_dup3(oldfd int, newfd int, flags int) (err Errno)
68 //dup3(oldfd _C_int, newfd _C_int, flags _C_int) _C_int
69
70 //sysnb raw_kill(pid Pid_t, sig Signal) (err Errno)
71 //kill(pid Pid_t, sig _C_int) _C_int
72
73 //sysnb raw_setgroups(size int, list unsafe.Pointer) (err Errno)
74 //setgroups(size Size_t, list *Gid_t) _C_int
75
76 // Lock synchronizing creation of new file descriptors with fork.
77 //
78 // We want the child in a fork/exec sequence to inherit only the
79 // file descriptors we intend. To do that, we mark all file
80 // descriptors close-on-exec and then, in the child, explicitly
81 // unmark the ones we want the exec'ed program to keep.
82 // Unix doesn't make this easy: there is, in general, no way to
83 // allocate a new file descriptor close-on-exec. Instead you
84 // have to allocate the descriptor and then mark it close-on-exec.
85 // If a fork happens between those two events, the child's exec
86 // will inherit an unwanted file descriptor.
87 //
88 // This lock solves that race: the create new fd/mark close-on-exec
89 // operation is done holding ForkLock for reading, and the fork itself
90 // is done holding ForkLock for writing. At least, that's the idea.
91 // There are some complications.
92 //
93 // Some system calls that create new file descriptors can block
94 // for arbitrarily long times: open on a hung NFS server or named
95 // pipe, accept on a socket, and so on. We can't reasonably grab
96 // the lock across those operations.
97 //
98 // It is worse to inherit some file descriptors than others.
99 // If a non-malicious child accidentally inherits an open ordinary file,
100 // that's not a big deal. On the other hand, if a long-lived child
101 // accidentally inherits the write end of a pipe, then the reader
102 // of that pipe will not see EOF until that child exits, potentially
103 // causing the parent program to hang. This is a common problem
104 // in threaded C programs that use popen.
105 //
106 // Luckily, the file descriptors that are most important not to
107 // inherit are not the ones that can take an arbitrarily long time
108 // to create: pipe returns instantly, and the net package uses
109 // non-blocking I/O to accept on a listening socket.
110 // The rules for which file descriptor-creating operations use the
111 // ForkLock are as follows:
112 //
113 // 1) Pipe. Does not block. Use the ForkLock.
114 // 2) Socket. Does not block. Use the ForkLock.
115 // 3) Accept. If using non-blocking mode, use the ForkLock.
116 // Otherwise, live with the race.
117 // 4) Open. Can block. Use O_CLOEXEC if available (GNU/Linux).
118 // Otherwise, live with the race.
119 // 5) Dup. Does not block. Use the ForkLock.
120 // On GNU/Linux, could use fcntl F_DUPFD_CLOEXEC
121 // instead of the ForkLock, but only for dup(fd, -1).
122
123 var ForkLock sync.RWMutex
124
125 // StringSlicePtr converts a slice of strings to a slice of pointers
126 // to NUL-terminated byte arrays. If any string contains a NUL byte
127 // this function panics instead of returning an error.
128 //
129 // Deprecated: Use SlicePtrFromStrings instead.
130 func StringSlicePtr(ss []string) []*byte {
131 bb := make([]*byte, len(ss)+1)
132 for i := 0; i < len(ss); i++ {
133 bb[i] = StringBytePtr(ss[i])
134 }
135 bb[len(ss)] = nil
136 return bb
137 }
138
139 // SlicePtrFromStrings converts a slice of strings to a slice of
140 // pointers to NUL-terminated byte arrays. If any string contains
141 // a NUL byte, it returns (nil, EINVAL).
142 func SlicePtrFromStrings(ss []string) ([]*byte, error) {
143 n := 0
144 for _, s := range ss {
145 if bytealg.IndexByteString(s, 0) != -1 {
146 return nil, EINVAL
147 }
148 n += len(s) + 1 // +1 for NUL
149 }
150 bb := make([]*byte, len(ss)+1)
151 b := make([]byte, n)
152 n = 0
153 for i, s := range ss {
154 bb[i] = &b[n]
155 copy(b[n:], s)
156 n += len(s) + 1
157 }
158 return bb, nil
159 }
160
161 func CloseOnExec(fd int) { fcntl(fd, F_SETFD, FD_CLOEXEC) }
162
163 func SetNonblock(fd int, nonblocking bool) (err error) {
164 flag, err := fcntl(fd, F_GETFL, 0)
165 if err != nil {
166 return err
167 }
168 if nonblocking {
169 flag |= O_NONBLOCK
170 } else {
171 flag &^= O_NONBLOCK
172 }
173 _, err = fcntl(fd, F_SETFL, flag)
174 return err
175 }
176
177 // Credential holds user and group identities to be assumed
178 // by a child process started by StartProcess.
179 type Credential struct {
180 Uid uint32 // User ID.
181 Gid uint32 // Group ID.
182 Groups []uint32 // Supplementary group IDs.
183 NoSetGroups bool // If true, don't set supplementary groups
184 }
185
186 // ProcAttr holds attributes that will be applied to a new process started
187 // by StartProcess.
188 type ProcAttr struct {
189 Dir string // Current working directory.
190 Env []string // Environment.
191 Files []uintptr // File descriptors.
192 Sys *SysProcAttr
193 }
194
195 var zeroProcAttr ProcAttr
196 var zeroSysProcAttr SysProcAttr
197
198 func forkExec(argv0 string, argv []string, attr *ProcAttr) (pid int, err error) {
199 var p [2]int
200 var n int
201 var err1 Errno
202 var wstatus WaitStatus
203
204 if attr == nil {
205 attr = &zeroProcAttr
206 }
207 sys := attr.Sys
208 if sys == nil {
209 sys = &zeroSysProcAttr
210 }
211
212 // Convert args to C form.
213 argv0p, err := BytePtrFromString(argv0)
214 if err != nil {
215 return 0, err
216 }
217 argvp, err := SlicePtrFromStrings(argv)
218 if err != nil {
219 return 0, err
220 }
221 envvp, err := SlicePtrFromStrings(attr.Env)
222 if err != nil {
223 return 0, err
224 }
225
226 if (runtime.GOOS == "freebsd" || runtime.GOOS == "dragonfly") && len(argv[0]) > len(argv0) {
227 argvp[0] = argv0p
228 }
229
230 var chroot *byte
231 if sys.Chroot != "" {
232 chroot, err = BytePtrFromString(sys.Chroot)
233 if err != nil {
234 return 0, err
235 }
236 }
237 var dir *byte
238 if attr.Dir != "" {
239 dir, err = BytePtrFromString(attr.Dir)
240 if err != nil {
241 return 0, err
242 }
243 }
244
245 // Both Setctty and Foreground use the Ctty field,
246 // but they give it slightly different meanings.
247 if sys.Setctty && sys.Foreground {
248 return 0, errorspkg.New("both Setctty and Foreground set in SysProcAttr")
249 }
250 if sys.Setctty && sys.Ctty >= len(attr.Files) {
251 return 0, errorspkg.New("Setctty set but Ctty not valid in child")
252 }
253
254 // Acquire the fork lock so that no other threads
255 // create new fds that are not yet close-on-exec
256 // before we fork.
257 ForkLock.Lock()
258
259 // Allocate child status pipe close on exec.
260 if err = forkExecPipe(p[:]); err != nil {
261 ForkLock.Unlock()
262 return 0, err
263 }
264
265 // Kick off child.
266 pid, err1 = forkAndExecInChild(argv0p, argvp, envvp, chroot, dir, attr, sys, p[1])
267 if err1 != 0 {
268 Close(p[0])
269 Close(p[1])
270 ForkLock.Unlock()
271 return 0, Errno(err1)
272 }
273 ForkLock.Unlock()
274
275 // Read child error status from pipe.
276 Close(p[1])
277 for {
278 n, err = readlen(p[0], (*byte)(unsafe.Pointer(&err1)), int(unsafe.Sizeof(err1)))
279 if err != EINTR {
280 break
281 }
282 }
283 Close(p[0])
284 if err != nil || n != 0 {
285 if n == int(unsafe.Sizeof(err1)) {
286 err = Errno(err1)
287 }
288 if err == nil {
289 err = EPIPE
290 }
291
292 // Child failed; wait for it to exit, to make sure
293 // the zombies don't accumulate.
294 _, err1 := Wait4(pid, &wstatus, 0, nil)
295 for err1 == EINTR {
296 _, err1 = Wait4(pid, &wstatus, 0, nil)
297 }
298 return 0, err
299 }
300
301 // Read got EOF, so pipe closed on exec, so exec succeeded.
302 return pid, nil
303 }
304
305 // Combination of fork and exec, careful to be thread safe.
306 func ForkExec(argv0 string, argv []string, attr *ProcAttr) (pid int, err error) {
307 return forkExec(argv0, argv, attr)
308 }
309
310 // StartProcess wraps ForkExec for package os.
311 func StartProcess(argv0 string, argv []string, attr *ProcAttr) (pid int, handle uintptr, err error) {
312 pid, err = forkExec(argv0, argv, attr)
313 return pid, 0, err
314 }
315
316 // Implemented in runtime package.
317 func runtime_BeforeExec()
318 func runtime_AfterExec()
319
320 // execveLibc is non-nil on OS using libc syscall, set to execve in exec_libc.go; this
321 // avoids a build dependency for other platforms.
322 var execveDarwin func(path *byte, argv **byte, envp **byte) error
323 var execveOpenBSD func(path *byte, argv **byte, envp **byte) error
324
325 // Exec invokes the execve(2) system call.
326 func Exec(argv0 string, argv []string, envv []string) (err error) {
327 argv0p, err := BytePtrFromString(argv0)
328 if err != nil {
329 return err
330 }
331 argvp, err := SlicePtrFromStrings(argv)
332 if err != nil {
333 return err
334 }
335 envvp, err := SlicePtrFromStrings(envv)
336 if err != nil {
337 return err
338 }
339 runtime_BeforeExec()
340
341 var err1 error
342 if runtime.GOOS == "solaris" || runtime.GOOS == "illumos" || runtime.GOOS == "aix" || runtime.GOOS == "hurd" {
343 // RawSyscall should never be used on Solaris, illumos, or AIX.
344 err1 = raw_execve(argv0p, &argvp[0], &envvp[0])
345 } else if runtime.GOOS == "darwin" || runtime.GOOS == "ios" {
346 // Similarly on Darwin.
347 err1 = execveDarwin(argv0p, &argvp[0], &envvp[0])
348 } else if runtime.GOOS == "openbsd" && (runtime.GOARCH == "386" || runtime.GOARCH == "amd64" || runtime.GOARCH == "arm" || runtime.GOARCH == "arm64") {
349 // Similarly on OpenBSD.
350 err1 = execveOpenBSD(argv0p, &argvp[0], &envvp[0])
351 } else {
352 _, _, err1 = RawSyscall(SYS_EXECVE,
353 uintptr(unsafe.Pointer(argv0p)),
354 uintptr(unsafe.Pointer(&argvp[0])),
355 uintptr(unsafe.Pointer(&envvp[0])))
356 }
357 runtime_AfterExec()
358 return err1
359 }