libgo: update to Go1.10beta1
[official-gcc.git] / libgo / go / syscall / exec_linux.go
blob4cc018b496142ab384afc44085e469cb3008f8ae
1 // Copyright 2011 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 linux
7 package syscall
9 import (
10 "unsafe"
13 //sysnb raw_prctl(option int, arg2 int, arg3 int, arg4 int, arg5 int) (ret int, err Errno)
14 //prctl(option _C_int, arg2 _C_long, arg3 _C_long, arg4 _C_long, arg5 _C_long) _C_int
16 //sysnb rawUnshare(flags int) (err Errno)
17 //unshare(flags _C_int) _C_int
19 //sysnb rawMount(source *byte, target *byte, fstype *byte, flags uintptr, data *byte) (err Errno)
20 //mount(source *byte, target *byte, fstype *byte, flags _C_long, data *byte) _C_int
22 // SysProcIDMap holds Container ID to Host ID mappings used for User Namespaces in Linux.
23 // See user_namespaces(7).
24 type SysProcIDMap struct {
25 ContainerID int // Container ID.
26 HostID int // Host ID.
27 Size int // Size.
30 type SysProcAttr struct {
31 Chroot string // Chroot.
32 Credential *Credential // Credential.
33 Ptrace bool // Enable tracing.
34 Setsid bool // Create session.
35 Setpgid bool // Set process group ID to Pgid, or, if Pgid == 0, to new pid.
36 Setctty bool // Set controlling terminal to fd Ctty (only meaningful if Setsid is set)
37 Noctty bool // Detach fd 0 from controlling terminal
38 Ctty int // Controlling TTY fd
39 Foreground bool // Place child's process group in foreground. (Implies Setpgid. Uses Ctty as fd of controlling TTY)
40 Pgid int // Child's process group ID if Setpgid.
41 Pdeathsig Signal // Signal that the process will get when its parent dies (Linux only)
42 Cloneflags uintptr // Flags for clone calls (Linux only)
43 Unshareflags uintptr // Flags for unshare calls (Linux only)
44 UidMappings []SysProcIDMap // User ID mappings for user namespaces.
45 GidMappings []SysProcIDMap // Group ID mappings for user namespaces.
46 // GidMappingsEnableSetgroups enabling setgroups syscall.
47 // If false, then setgroups syscall will be disabled for the child process.
48 // This parameter is no-op if GidMappings == nil. Otherwise for unprivileged
49 // users this should be set to false for mappings work.
50 GidMappingsEnableSetgroups bool
51 AmbientCaps []uintptr // Ambient capabilities (Linux only)
54 var (
55 none = [...]byte{'n', 'o', 'n', 'e', 0}
56 slash = [...]byte{'/', 0}
59 // Implemented in runtime package.
60 func runtime_BeforeFork()
61 func runtime_AfterFork()
62 func runtime_AfterForkInChild()
64 // Implemented in clone_linux.c
65 func rawClone(flags _C_ulong, child_stack *byte, ptid *Pid_t, ctid *Pid_t, regs unsafe.Pointer) _C_long
67 // Fork, dup fd onto 0..len(fd), and exec(argv0, argvv, envv) in child.
68 // If a dup or exec fails, write the errno error to pipe.
69 // (Pipe is close-on-exec so if exec succeeds, it will be closed.)
70 // In the child, this function must not acquire any locks, because
71 // they might have been locked at the time of the fork. This means
72 // no rescheduling, no malloc calls, and no new stack segments.
73 // For the same reason compiler does not race instrument it.
74 // The calls to RawSyscall are okay because they are assembly
75 // functions that do not grow the stack.
76 //go:norace
77 func forkAndExecInChild(argv0 *byte, argv, envv []*byte, chroot, dir *byte, attr *ProcAttr, sys *SysProcAttr, pipe int) (pid int, err Errno) {
78 // Set up and fork. This returns immediately in the parent or
79 // if there's an error.
80 r1, err1, p, locked := forkAndExecInChild1(argv0, argv, envv, chroot, dir, attr, sys, pipe)
81 if locked {
82 runtime_AfterFork()
84 if err1 != 0 {
85 return 0, err1
88 // parent; return PID
89 pid = int(r1)
91 if sys.UidMappings != nil || sys.GidMappings != nil {
92 Close(p[0])
93 err := writeUidGidMappings(pid, sys)
94 var err2 Errno
95 if err != nil {
96 err2 = err.(Errno)
98 RawSyscall(SYS_WRITE, uintptr(p[1]), uintptr(unsafe.Pointer(&err2)), unsafe.Sizeof(err2))
99 Close(p[1])
102 return pid, 0
105 // forkAndExecInChild1 implements the body of forkAndExecInChild up to
106 // the parent's post-fork path. This is a separate function so we can
107 // separate the child's and parent's stack frames if we're using
108 // vfork.
110 // This is go:noinline because the point is to keep the stack frames
111 // of this and forkAndExecInChild separate.
113 //go:noinline
114 //go:norace
115 func forkAndExecInChild1(argv0 *byte, argv, envv []*byte, chroot, dir *byte, attr *ProcAttr, sys *SysProcAttr, pipe int) (r1 uintptr, err1 Errno, p [2]int, locked bool) {
116 // Defined in linux/prctl.h starting with Linux 4.3.
117 const (
118 PR_CAP_AMBIENT = 0x2f
119 PR_CAP_AMBIENT_RAISE = 0x2
122 // vfork requires that the child not touch any of the parent's
123 // active stack frames. Hence, the child does all post-fork
124 // processing in this stack frame and never returns, while the
125 // parent returns immediately from this frame and does all
126 // post-fork processing in the outer frame.
127 // Declare all variables at top in case any
128 // declarations require heap allocation (e.g., err1).
129 var (
130 err2 Errno
131 nextfd int
132 i int
133 r2 int
136 // Record parent PID so child can test if it has died.
137 ppid := raw_getpid()
139 // Guard against side effects of shuffling fds below.
140 // Make sure that nextfd is beyond any currently open files so
141 // that we can't run the risk of overwriting any of them.
142 fd := make([]int, len(attr.Files))
143 nextfd = len(attr.Files)
144 for i, ufd := range attr.Files {
145 if nextfd < int(ufd) {
146 nextfd = int(ufd)
148 fd[i] = int(ufd)
150 nextfd++
152 // Allocate another pipe for parent to child communication for
153 // synchronizing writing of User ID/Group ID mappings.
154 if sys.UidMappings != nil || sys.GidMappings != nil {
155 if err := forkExecPipe(p[:]); err != nil {
156 err1 = err.(Errno)
157 return
161 // About to call fork.
162 // No more allocation or calls of non-assembly functions.
163 runtime_BeforeFork()
164 locked = true
165 r2 = int(rawClone(_C_ulong(uintptr(SIGCHLD)|sys.Cloneflags), nil, nil, nil, unsafe.Pointer(nil)))
166 if r2 < 0 {
167 err1 = GetErrno()
169 if r2 != 0 {
170 // If we're in the parent, we must return immediately
171 // so we're not in the same stack frame as the child.
172 // This can at most use the return PC, which the child
173 // will not modify, and the results of
174 // rawVforkSyscall, which must have been written after
175 // the child was replaced.
176 r1 = uintptr(r2)
177 return
180 // Fork succeeded, now in child.
182 runtime_AfterForkInChild()
184 // Enable the "keep capabilities" flag to set ambient capabilities later.
185 if len(sys.AmbientCaps) > 0 {
186 _, _, err1 = RawSyscall6(SYS_PRCTL, PR_SET_KEEPCAPS, 1, 0, 0, 0, 0)
187 if err1 != 0 {
188 goto childerror
192 // Wait for User ID/Group ID mappings to be written.
193 if sys.UidMappings != nil || sys.GidMappings != nil {
194 if _, _, err1 = RawSyscall(SYS_CLOSE, uintptr(p[1]), 0, 0); err1 != 0 {
195 goto childerror
197 r1, _, err1 = RawSyscall(SYS_READ, uintptr(p[0]), uintptr(unsafe.Pointer(&err2)), unsafe.Sizeof(err2))
198 if err1 != 0 {
199 goto childerror
201 if r1 != unsafe.Sizeof(err2) {
202 err1 = EINVAL
203 goto childerror
205 if err2 != 0 {
206 err1 = err2
207 goto childerror
211 // Session ID
212 if sys.Setsid {
213 err1 = raw_setsid()
214 if err1 != 0 {
215 goto childerror
219 // Set process group
220 if sys.Setpgid || sys.Foreground {
221 // Place child in process group.
222 err1 = raw_setpgid(0, sys.Pgid)
223 if err1 != 0 {
224 goto childerror
228 if sys.Foreground {
229 pgrp := Pid_t(sys.Pgid)
230 if pgrp == 0 {
231 pgrp = raw_getpid()
234 // Place process group in foreground.
235 _, err1 = raw_ioctl_ptr(sys.Ctty, TIOCSPGRP, unsafe.Pointer(&pgrp))
236 if err1 != 0 {
237 goto childerror
241 // Unshare
242 if sys.Unshareflags != 0 {
243 err1 = rawUnshare(int(sys.Unshareflags))
244 if err1 != 0 {
245 goto childerror
247 // The unshare system call in Linux doesn't unshare mount points
248 // mounted with --shared. Systemd mounts / with --shared. For a
249 // long discussion of the pros and cons of this see debian bug 739593.
250 // The Go model of unsharing is more like Plan 9, where you ask
251 // to unshare and the namespaces are unconditionally unshared.
252 // To make this model work we must further mark / as MS_PRIVATE.
253 // This is what the standard unshare command does.
254 if sys.Unshareflags&CLONE_NEWNS == CLONE_NEWNS {
255 err1 = rawMount(&none[0], &slash[0], nil, MS_REC|MS_PRIVATE, nil)
256 if err1 != 0 {
257 goto childerror
262 // Chroot
263 if chroot != nil {
264 err1 = raw_chroot(chroot)
265 if err1 != 0 {
266 goto childerror
270 // User and groups
271 if cred := sys.Credential; cred != nil {
272 ngroups := len(cred.Groups)
273 var groups unsafe.Pointer
274 if ngroups > 0 {
275 groups = unsafe.Pointer(&cred.Groups[0])
277 if !(sys.GidMappings != nil && !sys.GidMappingsEnableSetgroups && ngroups == 0) && !cred.NoSetGroups {
278 err1 = raw_setgroups(ngroups, groups)
279 if err1 != 0 {
280 goto childerror
283 _, _, err1 = RawSyscall(sys_SETGID, uintptr(cred.Gid), 0, 0)
284 if err1 != 0 {
285 goto childerror
287 _, _, err1 = RawSyscall(sys_SETUID, uintptr(cred.Uid), 0, 0)
288 if err1 != 0 {
289 goto childerror
293 for _, c := range sys.AmbientCaps {
294 _, _, err1 = RawSyscall6(SYS_PRCTL, PR_CAP_AMBIENT, uintptr(PR_CAP_AMBIENT_RAISE), c, 0, 0, 0)
295 if err1 != 0 {
296 goto childerror
300 // Chdir
301 if dir != nil {
302 err1 = raw_chdir(dir)
303 if err1 != 0 {
304 goto childerror
308 // Parent death signal
309 if sys.Pdeathsig != 0 {
310 _, err1 = raw_prctl(PR_SET_PDEATHSIG, int(sys.Pdeathsig), 0, 0, 0)
311 if err1 != 0 {
312 goto childerror
315 // Signal self if parent is already dead. This might cause a
316 // duplicate signal in rare cases, but it won't matter when
317 // using SIGKILL.
318 r1 := raw_getppid()
319 if r1 != ppid {
320 pid := raw_getpid()
321 err1 = raw_kill(pid, sys.Pdeathsig)
322 if err1 != 0 {
323 goto childerror
328 // Pass 1: look for fd[i] < i and move those up above len(fd)
329 // so that pass 2 won't stomp on an fd it needs later.
330 if pipe < nextfd {
331 err1 = raw_dup2(pipe, nextfd)
332 if err1 != 0 {
333 goto childerror
335 raw_fcntl(nextfd, F_SETFD, FD_CLOEXEC)
336 pipe = nextfd
337 nextfd++
339 for i = 0; i < len(fd); i++ {
340 if fd[i] >= 0 && fd[i] < int(i) {
341 if nextfd == pipe { // don't stomp on pipe
342 nextfd++
344 err1 = raw_dup2(fd[i], nextfd)
345 if err1 != 0 {
346 goto childerror
348 raw_fcntl(nextfd, F_SETFD, FD_CLOEXEC)
349 fd[i] = nextfd
350 nextfd++
354 // Pass 2: dup fd[i] down onto i.
355 for i = 0; i < len(fd); i++ {
356 if fd[i] == -1 {
357 raw_close(i)
358 continue
360 if fd[i] == int(i) {
361 // dup2(i, i) won't clear close-on-exec flag on Linux,
362 // probably not elsewhere either.
363 _, err1 = raw_fcntl(fd[i], F_SETFD, 0)
364 if err1 != 0 {
365 goto childerror
367 continue
369 // The new fd is created NOT close-on-exec,
370 // which is exactly what we want.
371 err1 = raw_dup2(fd[i], i)
372 if err1 != 0 {
373 goto childerror
377 // By convention, we don't close-on-exec the fds we are
378 // started with, so if len(fd) < 3, close 0, 1, 2 as needed.
379 // Programs that know they inherit fds >= 3 will need
380 // to set them close-on-exec.
381 for i = len(fd); i < 3; i++ {
382 raw_close(i)
385 // Detach fd 0 from tty
386 if sys.Noctty {
387 _, err1 = raw_ioctl(0, TIOCNOTTY, 0)
388 if err1 != 0 {
389 goto childerror
393 // Set the controlling TTY to Ctty
394 if sys.Setctty {
395 _, err1 = raw_ioctl(sys.Ctty, TIOCSCTTY, sys.Ctty)
396 if err1 != 0 {
397 goto childerror
401 // Enable tracing if requested.
402 // Do this right before exec so that we don't unnecessarily trace the runtime
403 // setting up after the fork. See issue #21428.
404 if sys.Ptrace {
405 err1 = raw_ptrace(_PTRACE_TRACEME, 0, nil, nil)
406 if err1 != 0 {
407 goto childerror
411 // Time to exec.
412 err1 = raw_execve(argv0, &argv[0], &envv[0])
414 childerror:
415 // send error code on pipe
416 raw_write(pipe, (*byte)(unsafe.Pointer(&err1)), int(unsafe.Sizeof(err1)))
417 for {
418 raw_exit(253)
422 // Try to open a pipe with O_CLOEXEC set on both file descriptors.
423 func forkExecPipe(p []int) (err error) {
424 err = Pipe2(p, O_CLOEXEC)
425 // pipe2 was added in 2.6.27 and our minimum requirement is 2.6.23, so it
426 // might not be implemented.
427 if err == ENOSYS {
428 if err = Pipe(p); err != nil {
429 return
431 if _, err = fcntl(p[0], F_SETFD, FD_CLOEXEC); err != nil {
432 return
434 _, err = fcntl(p[1], F_SETFD, FD_CLOEXEC)
436 return
439 // writeIDMappings writes the user namespace User ID or Group ID mappings to the specified path.
440 func writeIDMappings(path string, idMap []SysProcIDMap) error {
441 fd, err := Open(path, O_RDWR, 0)
442 if err != nil {
443 return err
446 data := ""
447 for _, im := range idMap {
448 data = data + itoa(im.ContainerID) + " " + itoa(im.HostID) + " " + itoa(im.Size) + "\n"
451 bytes, err := ByteSliceFromString(data)
452 if err != nil {
453 Close(fd)
454 return err
457 if _, err := Write(fd, bytes); err != nil {
458 Close(fd)
459 return err
462 if err := Close(fd); err != nil {
463 return err
466 return nil
469 // writeSetgroups writes to /proc/PID/setgroups "deny" if enable is false
470 // and "allow" if enable is true.
471 // This is needed since kernel 3.19, because you can't write gid_map without
472 // disabling setgroups() system call.
473 func writeSetgroups(pid int, enable bool) error {
474 sgf := "/proc/" + itoa(pid) + "/setgroups"
475 fd, err := Open(sgf, O_RDWR, 0)
476 if err != nil {
477 return err
480 var data []byte
481 if enable {
482 data = []byte("allow")
483 } else {
484 data = []byte("deny")
487 if _, err := Write(fd, data); err != nil {
488 Close(fd)
489 return err
492 return Close(fd)
495 // writeUidGidMappings writes User ID and Group ID mappings for user namespaces
496 // for a process and it is called from the parent process.
497 func writeUidGidMappings(pid int, sys *SysProcAttr) error {
498 if sys.UidMappings != nil {
499 uidf := "/proc/" + itoa(pid) + "/uid_map"
500 if err := writeIDMappings(uidf, sys.UidMappings); err != nil {
501 return err
505 if sys.GidMappings != nil {
506 // If the kernel is too old to support /proc/PID/setgroups, writeSetGroups will return ENOENT; this is OK.
507 if err := writeSetgroups(pid, sys.GidMappingsEnableSetgroups); err != nil && err != ENOENT {
508 return err
510 gidf := "/proc/" + itoa(pid) + "/gid_map"
511 if err := writeIDMappings(gidf, sys.GidMappings); err != nil {
512 return err
516 return nil