github.com/ccccaoqing/test@v0.0.0-20220510085219-3985d23445c0/src/syscall/exec_linux.go (about)

     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  // +build linux
     6  
     7  package syscall
     8  
     9  import (
    10  	"unsafe"
    11  )
    12  
    13  // SysProcIDMap holds Container ID to Host ID mappings used for User Namespaces in Linux.
    14  // See user_namespaces(7).
    15  type SysProcIDMap struct {
    16  	ContainerID int // Container ID.
    17  	HostID      int // Host ID.
    18  	Size        int // Size.
    19  }
    20  
    21  type SysProcAttr struct {
    22  	Chroot      string         // Chroot.
    23  	Credential  *Credential    // Credential.
    24  	Ptrace      bool           // Enable tracing.
    25  	Setsid      bool           // Create session.
    26  	Setpgid     bool           // Set process group ID to new pid (SYSV setpgrp)
    27  	Setctty     bool           // Set controlling terminal to fd Ctty (only meaningful if Setsid is set)
    28  	Noctty      bool           // Detach fd 0 from controlling terminal
    29  	Ctty        int            // Controlling TTY fd (Linux only)
    30  	Pdeathsig   Signal         // Signal that the process will get when its parent dies (Linux only)
    31  	Cloneflags  uintptr        // Flags for clone calls (Linux only)
    32  	UidMappings []SysProcIDMap // User ID mappings for user namespaces.
    33  	GidMappings []SysProcIDMap // Group ID mappings for user namespaces.
    34  }
    35  
    36  // Implemented in runtime package.
    37  func runtime_BeforeFork()
    38  func runtime_AfterFork()
    39  
    40  // Fork, dup fd onto 0..len(fd), and exec(argv0, argvv, envv) in child.
    41  // If a dup or exec fails, write the errno error to pipe.
    42  // (Pipe is close-on-exec so if exec succeeds, it will be closed.)
    43  // In the child, this function must not acquire any locks, because
    44  // they might have been locked at the time of the fork.  This means
    45  // no rescheduling, no malloc calls, and no new stack segments.
    46  // For the same reason compiler does not race instrument it.
    47  // The calls to RawSyscall are okay because they are assembly
    48  // functions that do not grow the stack.
    49  func forkAndExecInChild(argv0 *byte, argv, envv []*byte, chroot, dir *byte, attr *ProcAttr, sys *SysProcAttr, pipe int) (pid int, err Errno) {
    50  	// Declare all variables at top in case any
    51  	// declarations require heap allocation (e.g., err1).
    52  	var (
    53  		r1     uintptr
    54  		err1   Errno
    55  		err2   Errno
    56  		nextfd int
    57  		i      int
    58  		p      [2]int
    59  	)
    60  
    61  	// Guard against side effects of shuffling fds below.
    62  	// Make sure that nextfd is beyond any currently open files so
    63  	// that we can't run the risk of overwriting any of them.
    64  	fd := make([]int, len(attr.Files))
    65  	nextfd = len(attr.Files)
    66  	for i, ufd := range attr.Files {
    67  		if nextfd < int(ufd) {
    68  			nextfd = int(ufd)
    69  		}
    70  		fd[i] = int(ufd)
    71  	}
    72  	nextfd++
    73  
    74  	// Allocate another pipe for parent to child communication for
    75  	// synchronizing writing of User ID/Group ID mappings.
    76  	if sys.UidMappings != nil || sys.GidMappings != nil {
    77  		if err := forkExecPipe(p[:]); err != nil {
    78  			return 0, err.(Errno)
    79  		}
    80  	}
    81  
    82  	// About to call fork.
    83  	// No more allocation or calls of non-assembly functions.
    84  	runtime_BeforeFork()
    85  	r1, _, err1 = RawSyscall6(SYS_CLONE, uintptr(SIGCHLD)|sys.Cloneflags, 0, 0, 0, 0, 0)
    86  	if err1 != 0 {
    87  		runtime_AfterFork()
    88  		return 0, err1
    89  	}
    90  
    91  	if r1 != 0 {
    92  		// parent; return PID
    93  		runtime_AfterFork()
    94  		pid = int(r1)
    95  
    96  		if sys.UidMappings != nil || sys.GidMappings != nil {
    97  			Close(p[0])
    98  			err := writeUidGidMappings(pid, sys)
    99  			if err != nil {
   100  				err2 = err.(Errno)
   101  			}
   102  			RawSyscall(SYS_WRITE, uintptr(p[1]), uintptr(unsafe.Pointer(&err2)), unsafe.Sizeof(err2))
   103  			Close(p[1])
   104  		}
   105  
   106  		return pid, 0
   107  	}
   108  
   109  	// Fork succeeded, now in child.
   110  
   111  	// Wait for User ID/Group ID mappings to be written.
   112  	if sys.UidMappings != nil || sys.GidMappings != nil {
   113  		if _, _, err1 = RawSyscall(SYS_CLOSE, uintptr(p[1]), 0, 0); err1 != 0 {
   114  			goto childerror
   115  		}
   116  		r1, _, err1 = RawSyscall(SYS_READ, uintptr(p[0]), uintptr(unsafe.Pointer(&err2)), unsafe.Sizeof(err2))
   117  		if err1 != 0 {
   118  			goto childerror
   119  		}
   120  		if r1 != unsafe.Sizeof(err2) {
   121  			err1 = EINVAL
   122  			goto childerror
   123  		}
   124  		if err2 != 0 {
   125  			err1 = err2
   126  			goto childerror
   127  		}
   128  	}
   129  
   130  	// Parent death signal
   131  	if sys.Pdeathsig != 0 {
   132  		_, _, err1 = RawSyscall6(SYS_PRCTL, PR_SET_PDEATHSIG, uintptr(sys.Pdeathsig), 0, 0, 0, 0)
   133  		if err1 != 0 {
   134  			goto childerror
   135  		}
   136  
   137  		// Signal self if parent is already dead. This might cause a
   138  		// duplicate signal in rare cases, but it won't matter when
   139  		// using SIGKILL.
   140  		r1, _, _ = RawSyscall(SYS_GETPPID, 0, 0, 0)
   141  		if r1 == 1 {
   142  			pid, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0)
   143  			_, _, err1 := RawSyscall(SYS_KILL, pid, uintptr(sys.Pdeathsig), 0)
   144  			if err1 != 0 {
   145  				goto childerror
   146  			}
   147  		}
   148  	}
   149  
   150  	// Enable tracing if requested.
   151  	if sys.Ptrace {
   152  		_, _, err1 = RawSyscall(SYS_PTRACE, uintptr(PTRACE_TRACEME), 0, 0)
   153  		if err1 != 0 {
   154  			goto childerror
   155  		}
   156  	}
   157  
   158  	// Session ID
   159  	if sys.Setsid {
   160  		_, _, err1 = RawSyscall(SYS_SETSID, 0, 0, 0)
   161  		if err1 != 0 {
   162  			goto childerror
   163  		}
   164  	}
   165  
   166  	// Set process group
   167  	if sys.Setpgid {
   168  		_, _, err1 = RawSyscall(SYS_SETPGID, 0, 0, 0)
   169  		if err1 != 0 {
   170  			goto childerror
   171  		}
   172  	}
   173  
   174  	// Chroot
   175  	if chroot != nil {
   176  		_, _, err1 = RawSyscall(SYS_CHROOT, uintptr(unsafe.Pointer(chroot)), 0, 0)
   177  		if err1 != 0 {
   178  			goto childerror
   179  		}
   180  	}
   181  
   182  	// User and groups
   183  	if cred := sys.Credential; cred != nil {
   184  		ngroups := uintptr(len(cred.Groups))
   185  		var groups unsafe.Pointer
   186  		if ngroups > 0 {
   187  			groups = unsafe.Pointer(&cred.Groups[0])
   188  		}
   189  		_, _, err1 = RawSyscall(SYS_SETGROUPS, ngroups, uintptr(groups), 0)
   190  		if err1 != 0 {
   191  			goto childerror
   192  		}
   193  		_, _, err1 = RawSyscall(SYS_SETGID, uintptr(cred.Gid), 0, 0)
   194  		if err1 != 0 {
   195  			goto childerror
   196  		}
   197  		_, _, err1 = RawSyscall(SYS_SETUID, uintptr(cred.Uid), 0, 0)
   198  		if err1 != 0 {
   199  			goto childerror
   200  		}
   201  	}
   202  
   203  	// Chdir
   204  	if dir != nil {
   205  		_, _, err1 = RawSyscall(SYS_CHDIR, uintptr(unsafe.Pointer(dir)), 0, 0)
   206  		if err1 != 0 {
   207  			goto childerror
   208  		}
   209  	}
   210  
   211  	// Pass 1: look for fd[i] < i and move those up above len(fd)
   212  	// so that pass 2 won't stomp on an fd it needs later.
   213  	if pipe < nextfd {
   214  		_, _, err1 = RawSyscall(SYS_DUP2, uintptr(pipe), uintptr(nextfd), 0)
   215  		if err1 != 0 {
   216  			goto childerror
   217  		}
   218  		RawSyscall(SYS_FCNTL, uintptr(nextfd), F_SETFD, FD_CLOEXEC)
   219  		pipe = nextfd
   220  		nextfd++
   221  	}
   222  	for i = 0; i < len(fd); i++ {
   223  		if fd[i] >= 0 && fd[i] < int(i) {
   224  			_, _, err1 = RawSyscall(SYS_DUP2, uintptr(fd[i]), uintptr(nextfd), 0)
   225  			if err1 != 0 {
   226  				goto childerror
   227  			}
   228  			RawSyscall(SYS_FCNTL, uintptr(nextfd), F_SETFD, FD_CLOEXEC)
   229  			fd[i] = nextfd
   230  			nextfd++
   231  			if nextfd == pipe { // don't stomp on pipe
   232  				nextfd++
   233  			}
   234  		}
   235  	}
   236  
   237  	// Pass 2: dup fd[i] down onto i.
   238  	for i = 0; i < len(fd); i++ {
   239  		if fd[i] == -1 {
   240  			RawSyscall(SYS_CLOSE, uintptr(i), 0, 0)
   241  			continue
   242  		}
   243  		if fd[i] == int(i) {
   244  			// dup2(i, i) won't clear close-on-exec flag on Linux,
   245  			// probably not elsewhere either.
   246  			_, _, err1 = RawSyscall(SYS_FCNTL, uintptr(fd[i]), F_SETFD, 0)
   247  			if err1 != 0 {
   248  				goto childerror
   249  			}
   250  			continue
   251  		}
   252  		// The new fd is created NOT close-on-exec,
   253  		// which is exactly what we want.
   254  		_, _, err1 = RawSyscall(SYS_DUP2, uintptr(fd[i]), uintptr(i), 0)
   255  		if err1 != 0 {
   256  			goto childerror
   257  		}
   258  	}
   259  
   260  	// By convention, we don't close-on-exec the fds we are
   261  	// started with, so if len(fd) < 3, close 0, 1, 2 as needed.
   262  	// Programs that know they inherit fds >= 3 will need
   263  	// to set them close-on-exec.
   264  	for i = len(fd); i < 3; i++ {
   265  		RawSyscall(SYS_CLOSE, uintptr(i), 0, 0)
   266  	}
   267  
   268  	// Detach fd 0 from tty
   269  	if sys.Noctty {
   270  		_, _, err1 = RawSyscall(SYS_IOCTL, 0, uintptr(TIOCNOTTY), 0)
   271  		if err1 != 0 {
   272  			goto childerror
   273  		}
   274  	}
   275  
   276  	// Set the controlling TTY to Ctty
   277  	if sys.Setctty && sys.Ctty >= 0 {
   278  		_, _, err1 = RawSyscall(SYS_IOCTL, uintptr(sys.Ctty), uintptr(TIOCSCTTY), 0)
   279  		if err1 != 0 {
   280  			goto childerror
   281  		}
   282  	}
   283  
   284  	// Time to exec.
   285  	_, _, err1 = RawSyscall(SYS_EXECVE,
   286  		uintptr(unsafe.Pointer(argv0)),
   287  		uintptr(unsafe.Pointer(&argv[0])),
   288  		uintptr(unsafe.Pointer(&envv[0])))
   289  
   290  childerror:
   291  	// send error code on pipe
   292  	RawSyscall(SYS_WRITE, uintptr(pipe), uintptr(unsafe.Pointer(&err1)), unsafe.Sizeof(err1))
   293  	for {
   294  		RawSyscall(SYS_EXIT, 253, 0, 0)
   295  	}
   296  }
   297  
   298  // Try to open a pipe with O_CLOEXEC set on both file descriptors.
   299  func forkExecPipe(p []int) (err error) {
   300  	err = Pipe2(p, O_CLOEXEC)
   301  	// pipe2 was added in 2.6.27 and our minimum requirement is 2.6.23, so it
   302  	// might not be implemented.
   303  	if err == ENOSYS {
   304  		if err = Pipe(p); err != nil {
   305  			return
   306  		}
   307  		if _, err = fcntl(p[0], F_SETFD, FD_CLOEXEC); err != nil {
   308  			return
   309  		}
   310  		_, err = fcntl(p[1], F_SETFD, FD_CLOEXEC)
   311  	}
   312  	return
   313  }
   314  
   315  // writeIDMappings writes the user namespace User ID or Group ID mappings to the specified path.
   316  func writeIDMappings(path string, idMap []SysProcIDMap) error {
   317  	fd, err := Open(path, O_RDWR, 0)
   318  	if err != nil {
   319  		return err
   320  	}
   321  
   322  	data := ""
   323  	for _, im := range idMap {
   324  		data = data + itoa(im.ContainerID) + " " + itoa(im.HostID) + " " + itoa(im.Size) + "\n"
   325  	}
   326  
   327  	bytes, err := ByteSliceFromString(data)
   328  	if err != nil {
   329  		Close(fd)
   330  		return err
   331  	}
   332  
   333  	if _, err := Write(fd, bytes); err != nil {
   334  		Close(fd)
   335  		return err
   336  	}
   337  
   338  	if err := Close(fd); err != nil {
   339  		return err
   340  	}
   341  
   342  	return nil
   343  }
   344  
   345  // writeUidGidMappings writes User ID and Group ID mappings for user namespaces
   346  // for a process and it is called from the parent process.
   347  func writeUidGidMappings(pid int, sys *SysProcAttr) error {
   348  	if sys.UidMappings != nil {
   349  		uidf := "/proc/" + itoa(pid) + "/uid_map"
   350  		if err := writeIDMappings(uidf, sys.UidMappings); err != nil {
   351  			return err
   352  		}
   353  	}
   354  
   355  	if sys.GidMappings != nil {
   356  		gidf := "/proc/" + itoa(pid) + "/gid_map"
   357  		if err := writeIDMappings(gidf, sys.GidMappings); err != nil {
   358  			return err
   359  		}
   360  	}
   361  
   362  	return nil
   363  }