]> Cypherpunks.ru repositories - gostls13.git/blob - src/syscall/exec_linux.go
cmd/compile/internal/inline: score call sites exposed by inlines
[gostls13.git] / src / syscall / exec_linux.go
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.
4
5 //go:build linux
6
7 package syscall
8
9 import (
10         "internal/itoa"
11         "runtime"
12         "unsafe"
13 )
14
15 // Linux unshare/clone/clone2/clone3 flags, architecture-independent,
16 // copied from linux/sched.h.
17 const (
18         CLONE_VM             = 0x00000100 // set if VM shared between processes
19         CLONE_FS             = 0x00000200 // set if fs info shared between processes
20         CLONE_FILES          = 0x00000400 // set if open files shared between processes
21         CLONE_SIGHAND        = 0x00000800 // set if signal handlers and blocked signals shared
22         CLONE_PIDFD          = 0x00001000 // set if a pidfd should be placed in parent
23         CLONE_PTRACE         = 0x00002000 // set if we want to let tracing continue on the child too
24         CLONE_VFORK          = 0x00004000 // set if the parent wants the child to wake it up on mm_release
25         CLONE_PARENT         = 0x00008000 // set if we want to have the same parent as the cloner
26         CLONE_THREAD         = 0x00010000 // Same thread group?
27         CLONE_NEWNS          = 0x00020000 // New mount namespace group
28         CLONE_SYSVSEM        = 0x00040000 // share system V SEM_UNDO semantics
29         CLONE_SETTLS         = 0x00080000 // create a new TLS for the child
30         CLONE_PARENT_SETTID  = 0x00100000 // set the TID in the parent
31         CLONE_CHILD_CLEARTID = 0x00200000 // clear the TID in the child
32         CLONE_DETACHED       = 0x00400000 // Unused, ignored
33         CLONE_UNTRACED       = 0x00800000 // set if the tracing process can't force CLONE_PTRACE on this clone
34         CLONE_CHILD_SETTID   = 0x01000000 // set the TID in the child
35         CLONE_NEWCGROUP      = 0x02000000 // New cgroup namespace
36         CLONE_NEWUTS         = 0x04000000 // New utsname namespace
37         CLONE_NEWIPC         = 0x08000000 // New ipc namespace
38         CLONE_NEWUSER        = 0x10000000 // New user namespace
39         CLONE_NEWPID         = 0x20000000 // New pid namespace
40         CLONE_NEWNET         = 0x40000000 // New network namespace
41         CLONE_IO             = 0x80000000 // Clone io context
42
43         // Flags for the clone3() syscall.
44
45         CLONE_CLEAR_SIGHAND = 0x100000000 // Clear any signal handler and reset to SIG_DFL.
46         CLONE_INTO_CGROUP   = 0x200000000 // Clone into a specific cgroup given the right permissions.
47
48         // Cloning flags intersect with CSIGNAL so can be used with unshare and clone3
49         // syscalls only:
50
51         CLONE_NEWTIME = 0x00000080 // New time namespace
52 )
53
54 // SysProcIDMap holds Container ID to Host ID mappings used for User Namespaces in Linux.
55 // See user_namespaces(7).
56 type SysProcIDMap struct {
57         ContainerID int // Container ID.
58         HostID      int // Host ID.
59         Size        int // Size.
60 }
61
62 type SysProcAttr struct {
63         Chroot     string      // Chroot.
64         Credential *Credential // Credential.
65         // Ptrace tells the child to call ptrace(PTRACE_TRACEME).
66         // Call runtime.LockOSThread before starting a process with this set,
67         // and don't call UnlockOSThread until done with PtraceSyscall calls.
68         Ptrace bool
69         Setsid bool // Create session.
70         // Setpgid sets the process group ID of the child to Pgid,
71         // or, if Pgid == 0, to the new child's process ID.
72         Setpgid bool
73         // Setctty sets the controlling terminal of the child to
74         // file descriptor Ctty. Ctty must be a descriptor number
75         // in the child process: an index into ProcAttr.Files.
76         // This is only meaningful if Setsid is true.
77         Setctty bool
78         Noctty  bool // Detach fd 0 from controlling terminal.
79         Ctty    int  // Controlling TTY fd.
80         // Foreground places the child process group in the foreground.
81         // This implies Setpgid. The Ctty field must be set to
82         // the descriptor of the controlling TTY.
83         // Unlike Setctty, in this case Ctty must be a descriptor
84         // number in the parent process.
85         Foreground bool
86         Pgid       int // Child's process group ID if Setpgid.
87         // Pdeathsig, if non-zero, is a signal that the kernel will send to
88         // the child process when the creating thread dies. Note that the signal
89         // is sent on thread termination, which may happen before process termination.
90         // There are more details at https://go.dev/issue/27505.
91         Pdeathsig    Signal
92         Cloneflags   uintptr        // Flags for clone calls.
93         Unshareflags uintptr        // Flags for unshare calls.
94         UidMappings  []SysProcIDMap // User ID mappings for user namespaces.
95         GidMappings  []SysProcIDMap // Group ID mappings for user namespaces.
96         // GidMappingsEnableSetgroups enabling setgroups syscall.
97         // If false, then setgroups syscall will be disabled for the child process.
98         // This parameter is no-op if GidMappings == nil. Otherwise for unprivileged
99         // users this should be set to false for mappings work.
100         GidMappingsEnableSetgroups bool
101         AmbientCaps                []uintptr // Ambient capabilities.
102         UseCgroupFD                bool      // Whether to make use of the CgroupFD field.
103         CgroupFD                   int       // File descriptor of a cgroup to put the new process into.
104         // PidFD, if not nil, is used to store the pidfd of a child, if the
105         // functionality is supported by the kernel, or -1. Note *PidFD is
106         // changed only if the process starts successfully.
107         PidFD *int
108 }
109
110 var (
111         none  = [...]byte{'n', 'o', 'n', 'e', 0}
112         slash = [...]byte{'/', 0}
113
114         forceClone3 = false // Used by unit tests only.
115 )
116
117 // Implemented in runtime package.
118 func runtime_BeforeFork()
119 func runtime_AfterFork()
120 func runtime_AfterForkInChild()
121
122 // Fork, dup fd onto 0..len(fd), and exec(argv0, argvv, envv) in child.
123 // If a dup or exec fails, write the errno error to pipe.
124 // (Pipe is close-on-exec so if exec succeeds, it will be closed.)
125 // In the child, this function must not acquire any locks, because
126 // they might have been locked at the time of the fork. This means
127 // no rescheduling, no malloc calls, and no new stack segments.
128 // For the same reason compiler does not race instrument it.
129 // The calls to RawSyscall are okay because they are assembly
130 // functions that do not grow the stack.
131 //
132 //go:norace
133 func forkAndExecInChild(argv0 *byte, argv, envv []*byte, chroot, dir *byte, attr *ProcAttr, sys *SysProcAttr, pipe int) (pid int, err Errno) {
134         // Set up and fork. This returns immediately in the parent or
135         // if there's an error.
136         upid, err, mapPipe, locked := forkAndExecInChild1(argv0, argv, envv, chroot, dir, attr, sys, pipe)
137         if locked {
138                 runtime_AfterFork()
139         }
140         if err != 0 {
141                 return 0, err
142         }
143
144         // parent; return PID
145         pid = int(upid)
146
147         if sys.UidMappings != nil || sys.GidMappings != nil {
148                 Close(mapPipe[0])
149                 var err2 Errno
150                 // uid/gid mappings will be written after fork and unshare(2) for user
151                 // namespaces.
152                 if sys.Unshareflags&CLONE_NEWUSER == 0 {
153                         if err := writeUidGidMappings(pid, sys); err != nil {
154                                 err2 = err.(Errno)
155                         }
156                 }
157                 RawSyscall(SYS_WRITE, uintptr(mapPipe[1]), uintptr(unsafe.Pointer(&err2)), unsafe.Sizeof(err2))
158                 Close(mapPipe[1])
159         }
160
161         return pid, 0
162 }
163
164 const _LINUX_CAPABILITY_VERSION_3 = 0x20080522
165
166 type capHeader struct {
167         version uint32
168         pid     int32
169 }
170
171 type capData struct {
172         effective   uint32
173         permitted   uint32
174         inheritable uint32
175 }
176 type caps struct {
177         hdr  capHeader
178         data [2]capData
179 }
180
181 // See CAP_TO_INDEX in linux/capability.h:
182 func capToIndex(cap uintptr) uintptr { return cap >> 5 }
183
184 // See CAP_TO_MASK in linux/capability.h:
185 func capToMask(cap uintptr) uint32 { return 1 << uint(cap&31) }
186
187 // cloneArgs holds arguments for clone3 Linux syscall.
188 type cloneArgs struct {
189         flags      uint64 // Flags bit mask
190         pidFD      uint64 // Where to store PID file descriptor (int *)
191         childTID   uint64 // Where to store child TID, in child's memory (pid_t *)
192         parentTID  uint64 // Where to store child TID, in parent's memory (pid_t *)
193         exitSignal uint64 // Signal to deliver to parent on child termination
194         stack      uint64 // Pointer to lowest byte of stack
195         stackSize  uint64 // Size of stack
196         tls        uint64 // Location of new TLS
197         setTID     uint64 // Pointer to a pid_t array (since Linux 5.5)
198         setTIDSize uint64 // Number of elements in set_tid (since Linux 5.5)
199         cgroup     uint64 // File descriptor for target cgroup of child (since Linux 5.7)
200 }
201
202 // forkAndExecInChild1 implements the body of forkAndExecInChild up to
203 // the parent's post-fork path. This is a separate function so we can
204 // separate the child's and parent's stack frames if we're using
205 // vfork.
206 //
207 // This is go:noinline because the point is to keep the stack frames
208 // of this and forkAndExecInChild separate.
209 //
210 //go:noinline
211 //go:norace
212 //go:nocheckptr
213 func forkAndExecInChild1(argv0 *byte, argv, envv []*byte, chroot, dir *byte, attr *ProcAttr, sys *SysProcAttr, pipe int) (pid uintptr, err1 Errno, mapPipe [2]int, locked bool) {
214         // Defined in linux/prctl.h starting with Linux 4.3.
215         const (
216                 PR_CAP_AMBIENT       = 0x2f
217                 PR_CAP_AMBIENT_RAISE = 0x2
218         )
219
220         // vfork requires that the child not touch any of the parent's
221         // active stack frames. Hence, the child does all post-fork
222         // processing in this stack frame and never returns, while the
223         // parent returns immediately from this frame and does all
224         // post-fork processing in the outer frame.
225         //
226         // Declare all variables at top in case any
227         // declarations require heap allocation (e.g., err2).
228         // ":=" should not be used to declare any variable after
229         // the call to runtime_BeforeFork.
230         //
231         // NOTE(bcmills): The allocation behavior described in the above comment
232         // seems to lack a corresponding test, and it may be rendered invalid
233         // by an otherwise-correct change in the compiler.
234         var (
235                 err2                      Errno
236                 nextfd                    int
237                 i                         int
238                 caps                      caps
239                 fd1, flags                uintptr
240                 puid, psetgroups, pgid    []byte
241                 uidmap, setgroups, gidmap []byte
242                 clone3                    *cloneArgs
243                 pgrp                      int32
244                 pidfd                     _C_int = -1
245                 dirfd                     int
246                 cred                      *Credential
247                 ngroups, groups           uintptr
248                 c                         uintptr
249         )
250
251         rlim := origRlimitNofile.Load()
252
253         if sys.UidMappings != nil {
254                 puid = []byte("/proc/self/uid_map\000")
255                 uidmap = formatIDMappings(sys.UidMappings)
256         }
257
258         if sys.GidMappings != nil {
259                 psetgroups = []byte("/proc/self/setgroups\000")
260                 pgid = []byte("/proc/self/gid_map\000")
261
262                 if sys.GidMappingsEnableSetgroups {
263                         setgroups = []byte("allow\000")
264                 } else {
265                         setgroups = []byte("deny\000")
266                 }
267                 gidmap = formatIDMappings(sys.GidMappings)
268         }
269
270         // Record parent PID so child can test if it has died.
271         ppid, _ := rawSyscallNoError(SYS_GETPID, 0, 0, 0)
272
273         // Guard against side effects of shuffling fds below.
274         // Make sure that nextfd is beyond any currently open files so
275         // that we can't run the risk of overwriting any of them.
276         fd := make([]int, len(attr.Files))
277         nextfd = len(attr.Files)
278         for i, ufd := range attr.Files {
279                 if nextfd < int(ufd) {
280                         nextfd = int(ufd)
281                 }
282                 fd[i] = int(ufd)
283         }
284         nextfd++
285
286         // Allocate another pipe for parent to child communication for
287         // synchronizing writing of User ID/Group ID mappings.
288         if sys.UidMappings != nil || sys.GidMappings != nil {
289                 if err := forkExecPipe(mapPipe[:]); err != nil {
290                         err1 = err.(Errno)
291                         return
292                 }
293         }
294
295         flags = sys.Cloneflags
296         if sys.Cloneflags&CLONE_NEWUSER == 0 && sys.Unshareflags&CLONE_NEWUSER == 0 {
297                 flags |= CLONE_VFORK | CLONE_VM
298         }
299         if sys.PidFD != nil {
300                 flags |= CLONE_PIDFD
301         }
302         // Whether to use clone3.
303         if sys.UseCgroupFD || flags&CLONE_NEWTIME != 0 || forceClone3 {
304                 clone3 = &cloneArgs{
305                         flags:      uint64(flags),
306                         exitSignal: uint64(SIGCHLD),
307                 }
308                 if sys.UseCgroupFD {
309                         clone3.flags |= CLONE_INTO_CGROUP
310                         clone3.cgroup = uint64(sys.CgroupFD)
311                 }
312                 if sys.PidFD != nil {
313                         clone3.pidFD = uint64(uintptr(unsafe.Pointer(&pidfd)))
314                 }
315         }
316
317         // About to call fork.
318         // No more allocation or calls of non-assembly functions.
319         runtime_BeforeFork()
320         locked = true
321         if clone3 != nil {
322                 pid, err1 = rawVforkSyscall(_SYS_clone3, uintptr(unsafe.Pointer(clone3)), unsafe.Sizeof(*clone3), 0)
323         } else {
324                 flags |= uintptr(SIGCHLD)
325                 if runtime.GOARCH == "s390x" {
326                         // On Linux/s390, the first two arguments of clone(2) are swapped.
327                         pid, err1 = rawVforkSyscall(SYS_CLONE, 0, flags, uintptr(unsafe.Pointer(&pidfd)))
328                 } else {
329                         pid, err1 = rawVforkSyscall(SYS_CLONE, flags, 0, uintptr(unsafe.Pointer(&pidfd)))
330                 }
331         }
332         if err1 != 0 || pid != 0 {
333                 // If we're in the parent, we must return immediately
334                 // so we're not in the same stack frame as the child.
335                 // This can at most use the return PC, which the child
336                 // will not modify, and the results of
337                 // rawVforkSyscall, which must have been written after
338                 // the child was replaced.
339                 return
340         }
341
342         // Fork succeeded, now in child.
343
344         if sys.PidFD != nil {
345                 *sys.PidFD = int(pidfd)
346         }
347
348         // Enable the "keep capabilities" flag to set ambient capabilities later.
349         if len(sys.AmbientCaps) > 0 {
350                 _, _, err1 = RawSyscall6(SYS_PRCTL, PR_SET_KEEPCAPS, 1, 0, 0, 0, 0)
351                 if err1 != 0 {
352                         goto childerror
353                 }
354         }
355
356         // Wait for User ID/Group ID mappings to be written.
357         if sys.UidMappings != nil || sys.GidMappings != nil {
358                 if _, _, err1 = RawSyscall(SYS_CLOSE, uintptr(mapPipe[1]), 0, 0); err1 != 0 {
359                         goto childerror
360                 }
361                 pid, _, err1 = RawSyscall(SYS_READ, uintptr(mapPipe[0]), uintptr(unsafe.Pointer(&err2)), unsafe.Sizeof(err2))
362                 if err1 != 0 {
363                         goto childerror
364                 }
365                 if pid != unsafe.Sizeof(err2) {
366                         err1 = EINVAL
367                         goto childerror
368                 }
369                 if err2 != 0 {
370                         err1 = err2
371                         goto childerror
372                 }
373         }
374
375         // Session ID
376         if sys.Setsid {
377                 _, _, err1 = RawSyscall(SYS_SETSID, 0, 0, 0)
378                 if err1 != 0 {
379                         goto childerror
380                 }
381         }
382
383         // Set process group
384         if sys.Setpgid || sys.Foreground {
385                 // Place child in process group.
386                 _, _, err1 = RawSyscall(SYS_SETPGID, 0, uintptr(sys.Pgid), 0)
387                 if err1 != 0 {
388                         goto childerror
389                 }
390         }
391
392         if sys.Foreground {
393                 pgrp = int32(sys.Pgid)
394                 if pgrp == 0 {
395                         pid, _ = rawSyscallNoError(SYS_GETPID, 0, 0, 0)
396
397                         pgrp = int32(pid)
398                 }
399
400                 // Place process group in foreground.
401                 _, _, err1 = RawSyscall(SYS_IOCTL, uintptr(sys.Ctty), uintptr(TIOCSPGRP), uintptr(unsafe.Pointer(&pgrp)))
402                 if err1 != 0 {
403                         goto childerror
404                 }
405         }
406
407         // Restore the signal mask. We do this after TIOCSPGRP to avoid
408         // having the kernel send a SIGTTOU signal to the process group.
409         runtime_AfterForkInChild()
410
411         // Unshare
412         if sys.Unshareflags != 0 {
413                 _, _, err1 = RawSyscall(SYS_UNSHARE, sys.Unshareflags, 0, 0)
414                 if err1 != 0 {
415                         goto childerror
416                 }
417
418                 if sys.Unshareflags&CLONE_NEWUSER != 0 && sys.GidMappings != nil {
419                         dirfd = int(_AT_FDCWD)
420                         if fd1, _, err1 = RawSyscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(&psetgroups[0])), uintptr(O_WRONLY), 0, 0, 0); err1 != 0 {
421                                 goto childerror
422                         }
423                         pid, _, err1 = RawSyscall(SYS_WRITE, fd1, uintptr(unsafe.Pointer(&setgroups[0])), uintptr(len(setgroups)))
424                         if err1 != 0 {
425                                 goto childerror
426                         }
427                         if _, _, err1 = RawSyscall(SYS_CLOSE, fd1, 0, 0); err1 != 0 {
428                                 goto childerror
429                         }
430
431                         if fd1, _, err1 = RawSyscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(&pgid[0])), uintptr(O_WRONLY), 0, 0, 0); err1 != 0 {
432                                 goto childerror
433                         }
434                         pid, _, err1 = RawSyscall(SYS_WRITE, fd1, uintptr(unsafe.Pointer(&gidmap[0])), uintptr(len(gidmap)))
435                         if err1 != 0 {
436                                 goto childerror
437                         }
438                         if _, _, err1 = RawSyscall(SYS_CLOSE, fd1, 0, 0); err1 != 0 {
439                                 goto childerror
440                         }
441                 }
442
443                 if sys.Unshareflags&CLONE_NEWUSER != 0 && sys.UidMappings != nil {
444                         dirfd = int(_AT_FDCWD)
445                         if fd1, _, err1 = RawSyscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(&puid[0])), uintptr(O_WRONLY), 0, 0, 0); err1 != 0 {
446                                 goto childerror
447                         }
448                         pid, _, err1 = RawSyscall(SYS_WRITE, fd1, uintptr(unsafe.Pointer(&uidmap[0])), uintptr(len(uidmap)))
449                         if err1 != 0 {
450                                 goto childerror
451                         }
452                         if _, _, err1 = RawSyscall(SYS_CLOSE, fd1, 0, 0); err1 != 0 {
453                                 goto childerror
454                         }
455                 }
456
457                 // The unshare system call in Linux doesn't unshare mount points
458                 // mounted with --shared. Systemd mounts / with --shared. For a
459                 // long discussion of the pros and cons of this see debian bug 739593.
460                 // The Go model of unsharing is more like Plan 9, where you ask
461                 // to unshare and the namespaces are unconditionally unshared.
462                 // To make this model work we must further mark / as MS_PRIVATE.
463                 // This is what the standard unshare command does.
464                 if sys.Unshareflags&CLONE_NEWNS == CLONE_NEWNS {
465                         _, _, err1 = RawSyscall6(SYS_MOUNT, uintptr(unsafe.Pointer(&none[0])), uintptr(unsafe.Pointer(&slash[0])), 0, MS_REC|MS_PRIVATE, 0, 0)
466                         if err1 != 0 {
467                                 goto childerror
468                         }
469                 }
470         }
471
472         // Chroot
473         if chroot != nil {
474                 _, _, err1 = RawSyscall(SYS_CHROOT, uintptr(unsafe.Pointer(chroot)), 0, 0)
475                 if err1 != 0 {
476                         goto childerror
477                 }
478         }
479
480         // User and groups
481         if cred = sys.Credential; cred != nil {
482                 ngroups = uintptr(len(cred.Groups))
483                 groups = uintptr(0)
484                 if ngroups > 0 {
485                         groups = uintptr(unsafe.Pointer(&cred.Groups[0]))
486                 }
487                 if !(sys.GidMappings != nil && !sys.GidMappingsEnableSetgroups && ngroups == 0) && !cred.NoSetGroups {
488                         _, _, err1 = RawSyscall(_SYS_setgroups, ngroups, groups, 0)
489                         if err1 != 0 {
490                                 goto childerror
491                         }
492                 }
493                 _, _, err1 = RawSyscall(sys_SETGID, uintptr(cred.Gid), 0, 0)
494                 if err1 != 0 {
495                         goto childerror
496                 }
497                 _, _, err1 = RawSyscall(sys_SETUID, uintptr(cred.Uid), 0, 0)
498                 if err1 != 0 {
499                         goto childerror
500                 }
501         }
502
503         if len(sys.AmbientCaps) != 0 {
504                 // Ambient capabilities were added in the 4.3 kernel,
505                 // so it is safe to always use _LINUX_CAPABILITY_VERSION_3.
506                 caps.hdr.version = _LINUX_CAPABILITY_VERSION_3
507
508                 if _, _, err1 = RawSyscall(SYS_CAPGET, uintptr(unsafe.Pointer(&caps.hdr)), uintptr(unsafe.Pointer(&caps.data[0])), 0); err1 != 0 {
509                         goto childerror
510                 }
511
512                 for _, c = range sys.AmbientCaps {
513                         // Add the c capability to the permitted and inheritable capability mask,
514                         // otherwise we will not be able to add it to the ambient capability mask.
515                         caps.data[capToIndex(c)].permitted |= capToMask(c)
516                         caps.data[capToIndex(c)].inheritable |= capToMask(c)
517                 }
518
519                 if _, _, err1 = RawSyscall(SYS_CAPSET, uintptr(unsafe.Pointer(&caps.hdr)), uintptr(unsafe.Pointer(&caps.data[0])), 0); err1 != 0 {
520                         goto childerror
521                 }
522
523                 for _, c = range sys.AmbientCaps {
524                         _, _, err1 = RawSyscall6(SYS_PRCTL, PR_CAP_AMBIENT, uintptr(PR_CAP_AMBIENT_RAISE), c, 0, 0, 0)
525                         if err1 != 0 {
526                                 goto childerror
527                         }
528                 }
529         }
530
531         // Chdir
532         if dir != nil {
533                 _, _, err1 = RawSyscall(SYS_CHDIR, uintptr(unsafe.Pointer(dir)), 0, 0)
534                 if err1 != 0 {
535                         goto childerror
536                 }
537         }
538
539         // Parent death signal
540         if sys.Pdeathsig != 0 {
541                 _, _, err1 = RawSyscall6(SYS_PRCTL, PR_SET_PDEATHSIG, uintptr(sys.Pdeathsig), 0, 0, 0, 0)
542                 if err1 != 0 {
543                         goto childerror
544                 }
545
546                 // Signal self if parent is already dead. This might cause a
547                 // duplicate signal in rare cases, but it won't matter when
548                 // using SIGKILL.
549                 pid, _ = rawSyscallNoError(SYS_GETPPID, 0, 0, 0)
550                 if pid != ppid {
551                         pid, _ = rawSyscallNoError(SYS_GETPID, 0, 0, 0)
552                         _, _, err1 = RawSyscall(SYS_KILL, pid, uintptr(sys.Pdeathsig), 0)
553                         if err1 != 0 {
554                                 goto childerror
555                         }
556                 }
557         }
558
559         // Pass 1: look for fd[i] < i and move those up above len(fd)
560         // so that pass 2 won't stomp on an fd it needs later.
561         if pipe < nextfd {
562                 _, _, err1 = RawSyscall(SYS_DUP3, uintptr(pipe), uintptr(nextfd), O_CLOEXEC)
563                 if err1 != 0 {
564                         goto childerror
565                 }
566                 pipe = nextfd
567                 nextfd++
568         }
569         for i = 0; i < len(fd); i++ {
570                 if fd[i] >= 0 && fd[i] < i {
571                         if nextfd == pipe { // don't stomp on pipe
572                                 nextfd++
573                         }
574                         _, _, err1 = RawSyscall(SYS_DUP3, uintptr(fd[i]), uintptr(nextfd), O_CLOEXEC)
575                         if err1 != 0 {
576                                 goto childerror
577                         }
578                         fd[i] = nextfd
579                         nextfd++
580                 }
581         }
582
583         // Pass 2: dup fd[i] down onto i.
584         for i = 0; i < len(fd); i++ {
585                 if fd[i] == -1 {
586                         RawSyscall(SYS_CLOSE, uintptr(i), 0, 0)
587                         continue
588                 }
589                 if fd[i] == i {
590                         // dup2(i, i) won't clear close-on-exec flag on Linux,
591                         // probably not elsewhere either.
592                         _, _, err1 = RawSyscall(fcntl64Syscall, uintptr(fd[i]), F_SETFD, 0)
593                         if err1 != 0 {
594                                 goto childerror
595                         }
596                         continue
597                 }
598                 // The new fd is created NOT close-on-exec,
599                 // which is exactly what we want.
600                 _, _, err1 = RawSyscall(SYS_DUP3, uintptr(fd[i]), uintptr(i), 0)
601                 if err1 != 0 {
602                         goto childerror
603                 }
604         }
605
606         // By convention, we don't close-on-exec the fds we are
607         // started with, so if len(fd) < 3, close 0, 1, 2 as needed.
608         // Programs that know they inherit fds >= 3 will need
609         // to set them close-on-exec.
610         for i = len(fd); i < 3; i++ {
611                 RawSyscall(SYS_CLOSE, uintptr(i), 0, 0)
612         }
613
614         // Detach fd 0 from tty
615         if sys.Noctty {
616                 _, _, err1 = RawSyscall(SYS_IOCTL, 0, uintptr(TIOCNOTTY), 0)
617                 if err1 != 0 {
618                         goto childerror
619                 }
620         }
621
622         // Set the controlling TTY to Ctty
623         if sys.Setctty {
624                 _, _, err1 = RawSyscall(SYS_IOCTL, uintptr(sys.Ctty), uintptr(TIOCSCTTY), 1)
625                 if err1 != 0 {
626                         goto childerror
627                 }
628         }
629
630         // Restore original rlimit.
631         if rlim != nil {
632                 rawSetrlimit(RLIMIT_NOFILE, rlim)
633         }
634
635         // Enable tracing if requested.
636         // Do this right before exec so that we don't unnecessarily trace the runtime
637         // setting up after the fork. See issue #21428.
638         if sys.Ptrace {
639                 _, _, err1 = RawSyscall(SYS_PTRACE, uintptr(PTRACE_TRACEME), 0, 0)
640                 if err1 != 0 {
641                         goto childerror
642                 }
643         }
644
645         // Time to exec.
646         _, _, err1 = RawSyscall(SYS_EXECVE,
647                 uintptr(unsafe.Pointer(argv0)),
648                 uintptr(unsafe.Pointer(&argv[0])),
649                 uintptr(unsafe.Pointer(&envv[0])))
650
651 childerror:
652         // send error code on pipe
653         RawSyscall(SYS_WRITE, uintptr(pipe), uintptr(unsafe.Pointer(&err1)), unsafe.Sizeof(err1))
654         for {
655                 RawSyscall(SYS_EXIT, 253, 0, 0)
656         }
657 }
658
659 func formatIDMappings(idMap []SysProcIDMap) []byte {
660         var data []byte
661         for _, im := range idMap {
662                 data = append(data, itoa.Itoa(im.ContainerID)+" "+itoa.Itoa(im.HostID)+" "+itoa.Itoa(im.Size)+"\n"...)
663         }
664         return data
665 }
666
667 // writeIDMappings writes the user namespace User ID or Group ID mappings to the specified path.
668 func writeIDMappings(path string, idMap []SysProcIDMap) error {
669         fd, err := Open(path, O_RDWR, 0)
670         if err != nil {
671                 return err
672         }
673
674         if _, err := Write(fd, formatIDMappings(idMap)); err != nil {
675                 Close(fd)
676                 return err
677         }
678
679         if err := Close(fd); err != nil {
680                 return err
681         }
682
683         return nil
684 }
685
686 // writeSetgroups writes to /proc/PID/setgroups "deny" if enable is false
687 // and "allow" if enable is true.
688 // This is needed since kernel 3.19, because you can't write gid_map without
689 // disabling setgroups() system call.
690 func writeSetgroups(pid int, enable bool) error {
691         sgf := "/proc/" + itoa.Itoa(pid) + "/setgroups"
692         fd, err := Open(sgf, O_RDWR, 0)
693         if err != nil {
694                 return err
695         }
696
697         var data []byte
698         if enable {
699                 data = []byte("allow")
700         } else {
701                 data = []byte("deny")
702         }
703
704         if _, err := Write(fd, data); err != nil {
705                 Close(fd)
706                 return err
707         }
708
709         return Close(fd)
710 }
711
712 // writeUidGidMappings writes User ID and Group ID mappings for user namespaces
713 // for a process and it is called from the parent process.
714 func writeUidGidMappings(pid int, sys *SysProcAttr) error {
715         if sys.UidMappings != nil {
716                 uidf := "/proc/" + itoa.Itoa(pid) + "/uid_map"
717                 if err := writeIDMappings(uidf, sys.UidMappings); err != nil {
718                         return err
719                 }
720         }
721
722         if sys.GidMappings != nil {
723                 // If the kernel is too old to support /proc/PID/setgroups, writeSetGroups will return ENOENT; this is OK.
724                 if err := writeSetgroups(pid, sys.GidMappingsEnableSetgroups); err != nil && err != ENOENT {
725                         return err
726                 }
727                 gidf := "/proc/" + itoa.Itoa(pid) + "/gid_map"
728                 if err := writeIDMappings(gidf, sys.GidMappings); err != nil {
729                         return err
730                 }
731         }
732
733         return nil
734 }