Source file src/cmd/go/internal/base/exec.go

     1  // Copyright 2023 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 !js && !wasip1
     6  
     7  package base
     8  
     9  import (
    10  	"internal/godebug"
    11  	"log"
    12  	"os"
    13  	"os/exec"
    14  	"runtime"
    15  	"syscall"
    16  )
    17  
    18  // Exec replaces the current process with an invocation of exe with the current
    19  // command-line arguments and environment, or runs it as a subprocess and exits
    20  // on platforms without syscall.Exec. name is used in error messages.
    21  func Exec(name, exe string) {
    22  	// On Windows, there is no syscall.Exec, so the best we can do
    23  	// is run a subprocess and exit with the same status.
    24  	// Doing the same on Unix would be a problem because it wouldn't
    25  	// propagate signals and such, but there are no signals on Windows.
    26  	// We also use the exec case when GODEBUG=gotoolchainexec=0,
    27  	// to allow testing this code even when not on Windows.
    28  	if godebug.New("#gotoolchainexec").Value() == "0" || runtime.GOOS == "windows" {
    29  		cmd := exec.Command(exe, os.Args[1:]...)
    30  		cmd.Stdin = os.Stdin
    31  		cmd.Stdout = os.Stdout
    32  		cmd.Stderr = os.Stderr
    33  		err := cmd.Run()
    34  		if err != nil {
    35  			if e, ok := err.(*exec.ExitError); ok && e.ProcessState != nil {
    36  				if e.ProcessState.Exited() {
    37  					os.Exit(e.ProcessState.ExitCode())
    38  				}
    39  				log.SetPrefix("go: ")
    40  				Fatalf("exec %s: %s", name, e.ProcessState)
    41  			}
    42  			log.SetPrefix("go: ")
    43  			Fatalf("exec %s: %s", exe, err)
    44  		}
    45  		os.Exit(0)
    46  	}
    47  	argv := os.Args
    48  	if runtime.GOOS == "aix" {
    49  		// On AIX, os.Executable derives the executable path from Args[0],
    50  		// so the child must see its own path as argv[0].
    51  		argv = append([]string{exe}, os.Args[1:]...)
    52  	}
    53  	err := syscall.Exec(exe, argv, os.Environ())
    54  	log.SetPrefix("go: ")
    55  	Fatalf("exec %s: %v", name, err)
    56  }
    57  

View as plain text