Source file src/cmd/go/internal/work/shell.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  package work
     6  
     7  import (
     8  	"bytes"
     9  	"cmd/go/internal/base"
    10  	"cmd/go/internal/cache"
    11  	"cmd/go/internal/cfg"
    12  	"cmd/go/internal/load"
    13  	"cmd/go/internal/str"
    14  	"cmd/internal/par"
    15  	"cmd/internal/pathcache"
    16  	"errors"
    17  	"fmt"
    18  	"internal/lazyregexp"
    19  	"io"
    20  	"io/fs"
    21  	"os"
    22  	"os/exec"
    23  	"path/filepath"
    24  	"runtime"
    25  	"strconv"
    26  	"strings"
    27  	"sync"
    28  	"time"
    29  )
    30  
    31  // A Shell runs shell commands and performs shell-like file system operations.
    32  //
    33  // Shell tracks context related to running commands, and form a tree much like
    34  // context.Context.
    35  type Shell struct {
    36  	action       *Action // nil for the root shell
    37  	*shellShared         // per-Builder state shared across Shells
    38  }
    39  
    40  // shellShared is Shell state shared across all Shells derived from a single
    41  // root shell (generally a single Builder).
    42  type shellShared struct {
    43  	workDir string // $WORK, immutable
    44  
    45  	printLock sync.Mutex
    46  	printFunc func(args ...any) (int, error)
    47  	scriptDir string // current directory in printed script
    48  
    49  	mkdirCache par.Cache[string, error] // a cache of created directories
    50  }
    51  
    52  // NewShell returns a new Shell.
    53  //
    54  // Shell will internally serialize calls to the print function.
    55  // If print is nil, it defaults to printing to stderr.
    56  func NewShell(workDir string, print func(a ...any) (int, error)) *Shell {
    57  	if print == nil {
    58  		print = func(a ...any) (int, error) {
    59  			return fmt.Fprint(os.Stderr, a...)
    60  		}
    61  	}
    62  	shared := &shellShared{
    63  		workDir:   workDir,
    64  		printFunc: print,
    65  	}
    66  	return &Shell{shellShared: shared}
    67  }
    68  
    69  // Print emits a to this Shell's output stream, formatting it like fmt.Print.
    70  // It is safe to call concurrently.
    71  func (sh *Shell) Print(a ...any) {
    72  	sh.printLock.Lock()
    73  	defer sh.printLock.Unlock()
    74  	sh.printFunc(a...)
    75  }
    76  
    77  func (sh *Shell) printLocked(a ...any) {
    78  	sh.printFunc(a...)
    79  }
    80  
    81  // WithAction returns a Shell identical to sh, but bound to Action a.
    82  func (sh *Shell) WithAction(a *Action) *Shell {
    83  	sh2 := *sh
    84  	sh2.action = a
    85  	return &sh2
    86  }
    87  
    88  // Shell returns a shell for running commands on behalf of Action a.
    89  func (b *Builder) Shell(a *Action) *Shell {
    90  	if a == nil {
    91  		// The root shell has a nil Action. The point of this method is to
    92  		// create a Shell bound to an Action, so disallow nil Actions here.
    93  		panic("nil Action")
    94  	}
    95  	if a.sh == nil {
    96  		a.sh = b.backgroundSh.WithAction(a)
    97  	}
    98  	return a.sh
    99  }
   100  
   101  // BackgroundShell returns a Builder-wide Shell that's not bound to any Action.
   102  // Try not to use this unless there's really no sensible Action available.
   103  func (b *Builder) BackgroundShell() *Shell {
   104  	return b.backgroundSh
   105  }
   106  
   107  // moveOrCopyFile is like 'mv src dst' or 'cp src dst'.
   108  func (sh *Shell) moveOrCopyFile(dst, src string, perm fs.FileMode, force bool) error {
   109  	if cfg.BuildN {
   110  		sh.ShowCmd("", "mv %s %s", src, dst)
   111  		return nil
   112  	}
   113  
   114  	// If we can update the mode and rename to the dst, do it.
   115  	// Otherwise fall back to standard copy.
   116  
   117  	// If the source is in the build cache, we need to copy it.
   118  	dir, _ := cache.DefaultDir()
   119  	if strings.HasPrefix(src, dir) {
   120  		return sh.CopyFile(dst, src, perm, force)
   121  	}
   122  
   123  	// On Windows, always copy the file, so that we respect the NTFS
   124  	// permissions of the parent folder. https://golang.org/issue/22343.
   125  	// What matters here is not cfg.Goos (the system we are building
   126  	// for) but runtime.GOOS (the system we are building on).
   127  	if runtime.GOOS == "windows" {
   128  		return sh.CopyFile(dst, src, perm, force)
   129  	}
   130  
   131  	// If the destination directory has the group sticky bit set,
   132  	// we have to copy the file to retain the correct permissions.
   133  	// https://golang.org/issue/18878
   134  	if fi, err := os.Stat(filepath.Dir(dst)); err == nil {
   135  		if fi.IsDir() && (fi.Mode()&fs.ModeSetgid) != 0 {
   136  			return sh.CopyFile(dst, src, perm, force)
   137  		}
   138  	}
   139  
   140  	// The perm argument is meant to be adjusted according to umask,
   141  	// but we don't know what the umask is.
   142  	// Create a dummy file to find out.
   143  	// This avoids build tags and works even on systems like Plan 9
   144  	// where the file mask computation incorporates other information.
   145  	mode := perm
   146  	f, err := os.OpenFile(filepath.Clean(dst)+"-go-tmp-umask", os.O_WRONLY|os.O_CREATE|os.O_EXCL, perm)
   147  	if err == nil {
   148  		fi, err := f.Stat()
   149  		if err == nil {
   150  			mode = fi.Mode() & 0777
   151  		}
   152  		name := f.Name()
   153  		f.Close()
   154  		os.Remove(name)
   155  	}
   156  
   157  	if err := os.Chmod(src, mode); err == nil {
   158  		if err := os.Rename(src, dst); err == nil {
   159  			if cfg.BuildX {
   160  				sh.ShowCmd("", "mv %s %s", src, dst)
   161  			}
   162  			return nil
   163  		}
   164  	}
   165  
   166  	return sh.CopyFile(dst, src, perm, force)
   167  }
   168  
   169  // copyFile is like 'cp src dst'.
   170  func (sh *Shell) CopyFile(dst, src string, perm fs.FileMode, force bool) error {
   171  	if cfg.BuildN || cfg.BuildX {
   172  		sh.ShowCmd("", "cp %s %s", src, dst)
   173  		if cfg.BuildN {
   174  			return nil
   175  		}
   176  	}
   177  
   178  	sf, err := os.Open(src)
   179  	if err != nil {
   180  		return err
   181  	}
   182  	defer sf.Close()
   183  
   184  	// Be careful about removing/overwriting dst.
   185  	// Do not remove/overwrite if dst exists and is a directory
   186  	// or a non-empty non-object file.
   187  	if fi, err := os.Stat(dst); err == nil {
   188  		if fi.IsDir() {
   189  			return fmt.Errorf("build output %q already exists and is a directory", dst)
   190  		}
   191  		if !force && fi.Mode().IsRegular() && fi.Size() != 0 && !isObject(dst) {
   192  			return fmt.Errorf("build output %q already exists and is not an object file", dst)
   193  		}
   194  	}
   195  
   196  	// On Windows, remove lingering ~ file from last attempt.
   197  	if runtime.GOOS == "windows" {
   198  		if _, err := os.Stat(dst + "~"); err == nil {
   199  			os.Remove(dst + "~")
   200  		}
   201  	}
   202  
   203  	mayberemovefile(dst)
   204  	df, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
   205  	if err != nil && runtime.GOOS == "windows" {
   206  		// Windows does not allow deletion of a binary file
   207  		// while it is executing. Try to move it out of the way.
   208  		// If the move fails, which is likely, we'll try again the
   209  		// next time we do an install of this binary.
   210  		if err := os.Rename(dst, dst+"~"); err == nil {
   211  			os.Remove(dst + "~")
   212  		}
   213  		df, err = os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
   214  	}
   215  	if err != nil {
   216  		return fmt.Errorf("copying %s: %w", src, err) // err should already refer to dst
   217  	}
   218  
   219  	_, err = io.Copy(df, sf)
   220  	df.Close()
   221  	if err != nil {
   222  		mayberemovefile(dst)
   223  		return fmt.Errorf("copying %s to %s: %v", src, dst, err)
   224  	}
   225  	return nil
   226  }
   227  
   228  // mayberemovefile removes a file only if it is a regular file
   229  // When running as a user with sufficient privileges, we may delete
   230  // even device files, for example, which is not intended.
   231  func mayberemovefile(s string) {
   232  	if fi, err := os.Lstat(s); err == nil && !fi.Mode().IsRegular() {
   233  		return
   234  	}
   235  	os.Remove(s)
   236  }
   237  
   238  // writeFile writes the text to file.
   239  func (sh *Shell) writeFile(file string, text []byte) error {
   240  	if cfg.BuildN || cfg.BuildX {
   241  		switch {
   242  		case len(text) == 0:
   243  			sh.ShowCmd("", "echo -n > %s # internal", file)
   244  		case bytes.IndexByte(text, '\n') == len(text)-1:
   245  			// One line. Use a simpler "echo" command.
   246  			sh.ShowCmd("", "echo '%s' > %s # internal", bytes.TrimSuffix(text, []byte("\n")), file)
   247  		default:
   248  			// Use the most general form.
   249  			sh.ShowCmd("", "cat >%s << 'EOF' # internal\n%sEOF", file, text)
   250  		}
   251  	}
   252  	if cfg.BuildN {
   253  		return nil
   254  	}
   255  	return os.WriteFile(file, text, 0666)
   256  }
   257  
   258  // Mkdir makes the named directory.
   259  func (sh *Shell) Mkdir(dir string) error {
   260  	// Make Mkdir(a.Objdir) a no-op instead of an error when a.Objdir == "".
   261  	if dir == "" {
   262  		return nil
   263  	}
   264  
   265  	// We can be a little aggressive about being
   266  	// sure directories exist. Skip repeated calls.
   267  	return sh.mkdirCache.Do(dir, func() error {
   268  		if cfg.BuildN || cfg.BuildX {
   269  			sh.ShowCmd("", "mkdir -p %s", dir)
   270  			if cfg.BuildN {
   271  				return nil
   272  			}
   273  		}
   274  
   275  		return os.MkdirAll(dir, 0777)
   276  	})
   277  }
   278  
   279  // RemoveAll is like 'rm -rf'. It attempts to remove all paths even if there's
   280  // an error, and returns the first error.
   281  func (sh *Shell) RemoveAll(paths ...string) error {
   282  	if cfg.BuildN || cfg.BuildX {
   283  		// Don't say we are removing the directory if we never created it.
   284  		show := func() bool {
   285  			for _, path := range paths {
   286  				if _, ok := sh.mkdirCache.Get(path); ok {
   287  					return true
   288  				}
   289  				if _, err := os.Stat(path); !os.IsNotExist(err) {
   290  					return true
   291  				}
   292  			}
   293  			return false
   294  		}
   295  		if show() {
   296  			sh.ShowCmd("", "rm -rf %s", strings.Join(paths, " "))
   297  		}
   298  	}
   299  	if cfg.BuildN {
   300  		return nil
   301  	}
   302  
   303  	var err error
   304  	for _, path := range paths {
   305  		if err2 := os.RemoveAll(path); err2 != nil && err == nil {
   306  			err = err2
   307  		}
   308  	}
   309  	return err
   310  }
   311  
   312  // Symlink creates a symlink newname -> oldname.
   313  func (sh *Shell) Symlink(oldname, newname string) error {
   314  	// It's not an error to try to recreate an existing symlink.
   315  	if link, err := os.Readlink(newname); err == nil && link == oldname {
   316  		return nil
   317  	}
   318  
   319  	if cfg.BuildN || cfg.BuildX {
   320  		sh.ShowCmd("", "ln -s %s %s", oldname, newname)
   321  		if cfg.BuildN {
   322  			return nil
   323  		}
   324  	}
   325  	return os.Symlink(oldname, newname)
   326  }
   327  
   328  // fmtCmd formats a command in the manner of fmt.Sprintf but also:
   329  //
   330  //	fmtCmd replaces the value of b.WorkDir with $WORK.
   331  func (sh *Shell) fmtCmd(dir string, format string, args ...any) string {
   332  	cmd := fmt.Sprintf(format, args...)
   333  	if sh.workDir != "" && !strings.HasPrefix(cmd, "cat ") {
   334  		cmd = strings.ReplaceAll(cmd, sh.workDir, "$WORK")
   335  		escaped := strconv.Quote(sh.workDir)
   336  		escaped = escaped[1 : len(escaped)-1] // strip quote characters
   337  		if escaped != sh.workDir {
   338  			cmd = strings.ReplaceAll(cmd, escaped, "$WORK")
   339  		}
   340  	}
   341  	return cmd
   342  }
   343  
   344  // ShowCmd prints the given command to standard output
   345  // for the implementation of -n or -x.
   346  //
   347  // ShowCmd also replaces the name of the current script directory with dot (.)
   348  // but only when it is at the beginning of a space-separated token.
   349  //
   350  // If dir is not "" or "/" and not the current script directory, ShowCmd first
   351  // prints a "cd" command to switch to dir and updates the script directory.
   352  func (sh *Shell) ShowCmd(dir string, format string, args ...any) {
   353  	// Use the output lock directly so we can manage scriptDir.
   354  	sh.printLock.Lock()
   355  	defer sh.printLock.Unlock()
   356  
   357  	cmd := sh.fmtCmd(dir, format, args...)
   358  
   359  	if dir != "" && dir != "/" {
   360  		if dir != sh.scriptDir {
   361  			// Show changing to dir and update the current directory.
   362  			sh.printLocked(sh.fmtCmd("", "cd %s\n", dir))
   363  			sh.scriptDir = dir
   364  		}
   365  		// Replace scriptDir is our working directory. Replace it
   366  		// with "." in the command.
   367  		dot := " ."
   368  		if dir[len(dir)-1] == filepath.Separator {
   369  			dot += string(filepath.Separator)
   370  		}
   371  		cmd = strings.ReplaceAll(" "+cmd, " "+dir, dot)[1:]
   372  	}
   373  
   374  	sh.printLocked(cmd + "\n")
   375  }
   376  
   377  // reportCmd reports the output and exit status of a command. The cmdOut and
   378  // cmdErr arguments are the output and exit error of the command, respectively.
   379  //
   380  // The exact reporting behavior is as follows:
   381  //
   382  //	cmdOut  cmdErr  Result
   383  //	""      nil     print nothing, return nil
   384  //	!=""    nil     print output, return nil
   385  //	""      !=nil   print nothing, return cmdErr (later printed)
   386  //	!=""    !=nil   print nothing, ignore err, return output as error (later printed)
   387  //
   388  // reportCmd returns a non-nil error if and only if cmdErr != nil. It assumes
   389  // that the command output, if non-empty, is more detailed than the command
   390  // error (which is usually just an exit status), so prefers using the output as
   391  // the ultimate error. Typically, the caller should return this error from an
   392  // Action, which it will be printed by the Builder.
   393  //
   394  // reportCmd formats the output as "# desc" followed by the given output. The
   395  // output is expected to contain references to 'dir', usually the source
   396  // directory for the package that has failed to build. reportCmd rewrites
   397  // mentions of dir with a relative path to dir when the relative path is
   398  // shorter. This is usually more pleasant. For example, if fmt doesn't compile
   399  // and we are in src/html, the output is
   400  //
   401  //	$ go build
   402  //	# fmt
   403  //	../fmt/print.go:1090: undefined: asdf
   404  //	$
   405  //
   406  // instead of
   407  //
   408  //	$ go build
   409  //	# fmt
   410  //	/usr/gopher/go/src/fmt/print.go:1090: undefined: asdf
   411  //	$
   412  //
   413  // reportCmd also replaces references to the work directory with $WORK, replaces
   414  // cgo file paths with the original file path, and replaces cgo-mangled names
   415  // with "C.name".
   416  //
   417  // desc is optional. If "", a.Package.Desc() is used.
   418  //
   419  // dir is optional. If "", a.Package.Dir is used.
   420  func (sh *Shell) reportCmd(desc, dir string, cmdOut []byte, cmdErr error) error {
   421  	if len(cmdOut) == 0 && cmdErr == nil {
   422  		// Common case
   423  		return nil
   424  	}
   425  	if len(cmdOut) == 0 && cmdErr != nil {
   426  		// Just return the error.
   427  		//
   428  		// TODO: This is what we've done for a long time, but it may be a
   429  		// mistake because it loses all of the extra context and results in
   430  		// ultimately less descriptive output. We should probably just take the
   431  		// text of cmdErr as the output in this case and do everything we
   432  		// otherwise would. We could chain the errors if we feel like it.
   433  		return cmdErr
   434  	}
   435  
   436  	// Fetch defaults from the package.
   437  	var p *load.Package
   438  	a := sh.action
   439  	if a != nil {
   440  		p = a.Package
   441  	}
   442  	var importPath string
   443  	if p != nil {
   444  		importPath = p.ImportPath
   445  		if desc == "" {
   446  			desc = p.Desc()
   447  		}
   448  		if dir == "" {
   449  			dir = p.Dir
   450  		}
   451  	}
   452  
   453  	out := string(cmdOut)
   454  
   455  	if !strings.HasSuffix(out, "\n") {
   456  		out = out + "\n"
   457  	}
   458  
   459  	// Replace workDir with $WORK
   460  	out = replacePrefix(out, sh.workDir, "$WORK")
   461  
   462  	// Rewrite mentions of dir with a relative path to dir
   463  	// when the relative path is shorter.
   464  	for {
   465  		// Note that dir starts out long, something like
   466  		// /foo/bar/baz/root/a
   467  		// The target string to be reduced is something like
   468  		// (blah-blah-blah) /foo/bar/baz/root/sibling/whatever.go:blah:blah
   469  		// /foo/bar/baz/root/a doesn't match /foo/bar/baz/root/sibling, but the prefix
   470  		// /foo/bar/baz/root does.  And there may be other niblings sharing shorter
   471  		// prefixes, the only way to find them is to look.
   472  		// This doesn't always produce a relative path --
   473  		// /foo is shorter than ../../.., for example.
   474  		if reldir := base.ShortPath(dir); reldir != dir {
   475  			out = replacePrefix(out, dir, reldir)
   476  			if filepath.Separator == '\\' {
   477  				// Don't know why, sometimes this comes out with slashes, not backslashes.
   478  				wdir := strings.ReplaceAll(dir, "\\", "/")
   479  				out = replacePrefix(out, wdir, reldir)
   480  			}
   481  		}
   482  		dirP := filepath.Dir(dir)
   483  		if dir == dirP {
   484  			break
   485  		}
   486  		dir = dirP
   487  	}
   488  
   489  	// Fix up output referring to cgo-generated code to be more readable.
   490  	// Replace x.go:19[/tmp/.../x.cgo1.go:18] with x.go:19.
   491  	// Replace *[100]_Ctype_foo with *[100]C.foo.
   492  	// If we're using -x, assume we're debugging and want the full dump, so disable the rewrite.
   493  	if !cfg.BuildX && cgoLine.MatchString(out) {
   494  		out = cgoLine.ReplaceAllString(out, "")
   495  		out = cgoTypeSigRe.ReplaceAllString(out, "C.")
   496  	}
   497  
   498  	// Usually desc is already p.Desc(), but if not, signal cmdError.Error to
   499  	// add a line explicitly mentioning the import path.
   500  	needsPath := importPath != "" && p != nil && desc != p.Desc()
   501  
   502  	err := &cmdError{desc, out, importPath, needsPath}
   503  	if cmdErr != nil {
   504  		// The command failed. Report the output up as an error.
   505  		return err
   506  	}
   507  	// The command didn't fail, so just print the output as appropriate.
   508  	if a != nil && a.output != nil {
   509  		// The Action is capturing output.
   510  		a.output = append(a.output, err.Error()...)
   511  	} else {
   512  		// Write directly to the Builder output.
   513  		sh.Print(err.Error())
   514  	}
   515  	return nil
   516  }
   517  
   518  // replacePrefix is like strings.ReplaceAll, but only replaces instances of old
   519  // that are preceded by ' ', '\t', or appear at the beginning of a line.
   520  func replacePrefix(s, old, new string) string {
   521  	n := strings.Count(s, old)
   522  	if n == 0 {
   523  		return s
   524  	}
   525  
   526  	s = strings.ReplaceAll(s, " "+old, " "+new)
   527  	s = strings.ReplaceAll(s, "\n"+old, "\n"+new)
   528  	s = strings.ReplaceAll(s, "\n\t"+old, "\n\t"+new)
   529  	if strings.HasPrefix(s, old) {
   530  		s = new + s[len(old):]
   531  	}
   532  	return s
   533  }
   534  
   535  type cmdError struct {
   536  	desc       string
   537  	text       string
   538  	importPath string
   539  	needsPath  bool // Set if desc does not already include the import path
   540  }
   541  
   542  func (e *cmdError) Error() string {
   543  	var msg string
   544  	if e.needsPath {
   545  		// Ensure the import path is part of the message.
   546  		// Clearly distinguish the description from the import path.
   547  		msg = fmt.Sprintf("# %s\n# [%s]\n", e.importPath, e.desc)
   548  	} else {
   549  		msg = "# " + e.desc + "\n"
   550  	}
   551  	return msg + e.text
   552  }
   553  
   554  func (e *cmdError) ImportPath() string {
   555  	return e.importPath
   556  }
   557  
   558  var cgoLine = lazyregexp.New(`\[[^\[\]]+\.(cgo1|cover)\.go:[0-9]+(:[0-9]+)?\]`)
   559  var cgoTypeSigRe = lazyregexp.New(`\b_C2?(type|func|var|macro)_\B`)
   560  
   561  // run runs the command given by cmdline in the directory dir.
   562  // If the command fails, run prints information about the failure
   563  // and returns a non-nil error.
   564  func (sh *Shell) run(dir string, desc string, env []string, cmdargs ...any) error {
   565  	out, err := sh.runOut(dir, env, cmdargs...)
   566  	if desc == "" {
   567  		desc = sh.fmtCmd(dir, "%s", strings.Join(str.StringList(cmdargs...), " "))
   568  	}
   569  	return sh.reportCmd(desc, dir, out, err)
   570  }
   571  
   572  // runOut runs the command given by cmdline in the directory dir.
   573  // It returns the command output and any errors that occurred.
   574  // It accumulates execution time in a.
   575  func (sh *Shell) runOut(dir string, env []string, cmdargs ...any) ([]byte, error) {
   576  	a := sh.action
   577  
   578  	cmdline := str.StringList(cmdargs...)
   579  
   580  	for _, arg := range cmdline {
   581  		// GNU binutils commands, including gcc and gccgo, interpret an argument
   582  		// @foo anywhere in the command line (even following --) as meaning
   583  		// "read and insert arguments from the file named foo."
   584  		// Don't say anything that might be misinterpreted that way.
   585  		if strings.HasPrefix(arg, "@") {
   586  			return nil, fmt.Errorf("invalid command-line argument %s in command: %s", arg, joinUnambiguously(cmdline))
   587  		}
   588  	}
   589  
   590  	if cfg.BuildN || cfg.BuildX {
   591  		var envcmdline string
   592  		for _, e := range env {
   593  			if j := strings.IndexByte(e, '='); j != -1 {
   594  				if strings.ContainsRune(e[j+1:], '\'') {
   595  					envcmdline += fmt.Sprintf("%s=%q", e[:j], e[j+1:])
   596  				} else {
   597  					envcmdline += fmt.Sprintf("%s='%s'", e[:j], e[j+1:])
   598  				}
   599  				envcmdline += " "
   600  			}
   601  		}
   602  		envcmdline += joinUnambiguously(cmdline)
   603  		sh.ShowCmd(dir, "%s", envcmdline)
   604  		if cfg.BuildN {
   605  			return nil, nil
   606  		}
   607  	}
   608  
   609  	var buf bytes.Buffer
   610  	path, err := pathcache.LookPath(cmdline[0])
   611  	if err != nil {
   612  		return nil, err
   613  	}
   614  	cmd := exec.Command(path, cmdline[1:]...)
   615  	if cmd.Path != "" {
   616  		cmd.Args[0] = cmd.Path
   617  	}
   618  	cmd.Stdout = &buf
   619  	cmd.Stderr = &buf
   620  	cleanup := passLongArgsInResponseFiles(cmd)
   621  	defer cleanup()
   622  	if dir != "." {
   623  		cmd.Dir = dir
   624  	}
   625  	cmd.Env = cmd.Environ() // Pre-allocate with correct PWD.
   626  
   627  	// Add the TOOLEXEC_IMPORTPATH environment variable for -toolexec tools.
   628  	// It doesn't really matter if -toolexec isn't being used.
   629  	// Note that a.Package.Desc is not really an import path,
   630  	// but this is consistent with 'go list -f {{.ImportPath}}'.
   631  	// Plus, it is useful to uniquely identify packages in 'go list -json'.
   632  	if a != nil && a.Package != nil {
   633  		cmd.Env = append(cmd.Env, "TOOLEXEC_IMPORTPATH="+a.Package.Desc())
   634  	}
   635  
   636  	cmd.Env = append(cmd.Env, env...)
   637  	start := time.Now()
   638  	err = cmd.Run()
   639  	if a != nil && a.json != nil {
   640  		aj := a.json
   641  		aj.Cmd = append(aj.Cmd, joinUnambiguously(cmdline))
   642  		aj.CmdReal += time.Since(start)
   643  		if ps := cmd.ProcessState; ps != nil {
   644  			aj.CmdUser += ps.UserTime()
   645  			aj.CmdSys += ps.SystemTime()
   646  		}
   647  	}
   648  
   649  	// err can be something like 'exit status 1'.
   650  	// Add information about what program was running.
   651  	// Note that if buf.Bytes() is non-empty, the caller usually
   652  	// shows buf.Bytes() and does not print err at all, so the
   653  	// prefix here does not make most output any more verbose.
   654  	if err != nil {
   655  		err = errors.New(cmdline[0] + ": " + err.Error())
   656  	}
   657  	return buf.Bytes(), err
   658  }
   659  
   660  // joinUnambiguously prints the slice, quoting where necessary to make the
   661  // output unambiguous.
   662  // TODO: See issue 5279. The printing of commands needs a complete redo.
   663  func joinUnambiguously(a []string) string {
   664  	var buf strings.Builder
   665  	for i, s := range a {
   666  		if i > 0 {
   667  			buf.WriteByte(' ')
   668  		}
   669  		q := strconv.Quote(s)
   670  		// A gccgo command line can contain -( and -).
   671  		// Make sure we quote them since they are special to the shell.
   672  		// The trimpath argument can also contain > (part of =>) and ;. Quote those too.
   673  		if s == "" || strings.ContainsAny(s, " ()>;") || len(q) > len(s)+2 {
   674  			buf.WriteString(q)
   675  		} else {
   676  			buf.WriteString(s)
   677  		}
   678  	}
   679  	return buf.String()
   680  }
   681  

View as plain text