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