github.com/4ad/go@v0.0.0-20161219182952-69a12818b605/src/os/exec/exec.go (about)

     1  // Copyright 2009 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 exec runs external commands. It wraps os.StartProcess to make it
     6  // easier to remap stdin and stdout, connect I/O with pipes, and do other
     7  // adjustments.
     8  //
     9  // Note that the examples in this package assume a Unix system.
    10  // They may not run on Windows, and they do not run in the Go Playground
    11  // used by golang.org and godoc.org.
    12  package exec
    13  
    14  import (
    15  	"bytes"
    16  	"context"
    17  	"errors"
    18  	"io"
    19  	"os"
    20  	"path/filepath"
    21  	"runtime"
    22  	"strconv"
    23  	"strings"
    24  	"sync"
    25  	"syscall"
    26  )
    27  
    28  // Error records the name of a binary that failed to be executed
    29  // and the reason it failed.
    30  type Error struct {
    31  	Name string
    32  	Err  error
    33  }
    34  
    35  func (e *Error) Error() string {
    36  	return "exec: " + strconv.Quote(e.Name) + ": " + e.Err.Error()
    37  }
    38  
    39  // Cmd represents an external command being prepared or run.
    40  //
    41  // A Cmd cannot be reused after calling its Run, Output or CombinedOutput
    42  // methods.
    43  type Cmd struct {
    44  	// Path is the path of the command to run.
    45  	//
    46  	// This is the only field that must be set to a non-zero
    47  	// value. If Path is relative, it is evaluated relative
    48  	// to Dir.
    49  	Path string
    50  
    51  	// Args holds command line arguments, including the command as Args[0].
    52  	// If the Args field is empty or nil, Run uses {Path}.
    53  	//
    54  	// In typical use, both Path and Args are set by calling Command.
    55  	Args []string
    56  
    57  	// Env specifies the environment of the process.
    58  	// If Env is nil, Run uses the current process's environment.
    59  	Env []string
    60  
    61  	// Dir specifies the working directory of the command.
    62  	// If Dir is the empty string, Run runs the command in the
    63  	// calling process's current directory.
    64  	Dir string
    65  
    66  	// Stdin specifies the process's standard input.
    67  	// If Stdin is nil, the process reads from the null device (os.DevNull).
    68  	// If Stdin is an *os.File, the process's standard input is connected
    69  	// directly to that file.
    70  	// Otherwise, during the execution of the command a separate
    71  	// goroutine reads from Stdin and delivers that data to the command
    72  	// over a pipe. In this case, Wait does not complete until the goroutine
    73  	// stops copying, either because it has reached the end of Stdin
    74  	// (EOF or a read error) or because writing to the pipe returned an error.
    75  	Stdin io.Reader
    76  
    77  	// Stdout and Stderr specify the process's standard output and error.
    78  	//
    79  	// If either is nil, Run connects the corresponding file descriptor
    80  	// to the null device (os.DevNull).
    81  	//
    82  	// If Stdout and Stderr are the same writer, at most one
    83  	// goroutine at a time will call Write.
    84  	Stdout io.Writer
    85  	Stderr io.Writer
    86  
    87  	// ExtraFiles specifies additional open files to be inherited by the
    88  	// new process. It does not include standard input, standard output, or
    89  	// standard error. If non-nil, entry i becomes file descriptor 3+i.
    90  	//
    91  	// BUG(rsc): On OS X 10.6, child processes may sometimes inherit unwanted fds.
    92  	// https://golang.org/issue/2603
    93  	ExtraFiles []*os.File
    94  
    95  	// SysProcAttr holds optional, operating system-specific attributes.
    96  	// Run passes it to os.StartProcess as the os.ProcAttr's Sys field.
    97  	SysProcAttr *syscall.SysProcAttr
    98  
    99  	// Process is the underlying process, once started.
   100  	Process *os.Process
   101  
   102  	// ProcessState contains information about an exited process,
   103  	// available after a call to Wait or Run.
   104  	ProcessState *os.ProcessState
   105  
   106  	ctx             context.Context // nil means none
   107  	lookPathErr     error           // LookPath error, if any.
   108  	finished        bool            // when Wait was called
   109  	childFiles      []*os.File
   110  	closeAfterStart []io.Closer
   111  	closeAfterWait  []io.Closer
   112  	goroutine       []func() error
   113  	errch           chan error // one send per goroutine
   114  	waitDone        chan struct{}
   115  }
   116  
   117  // Command returns the Cmd struct to execute the named program with
   118  // the given arguments.
   119  //
   120  // It sets only the Path and Args in the returned structure.
   121  //
   122  // If name contains no path separators, Command uses LookPath to
   123  // resolve the path to a complete name if possible. Otherwise it uses
   124  // name directly.
   125  //
   126  // The returned Cmd's Args field is constructed from the command name
   127  // followed by the elements of arg, so arg should not include the
   128  // command name itself. For example, Command("echo", "hello")
   129  func Command(name string, arg ...string) *Cmd {
   130  	cmd := &Cmd{
   131  		Path: name,
   132  		Args: append([]string{name}, arg...),
   133  	}
   134  	if filepath.Base(name) == name {
   135  		if lp, err := LookPath(name); err != nil {
   136  			cmd.lookPathErr = err
   137  		} else {
   138  			cmd.Path = lp
   139  		}
   140  	}
   141  	return cmd
   142  }
   143  
   144  // CommandContext is like Command but includes a context.
   145  //
   146  // The provided context is used to kill the process (by calling
   147  // os.Process.Kill) if the context becomes done before the command
   148  // completes on its own.
   149  func CommandContext(ctx context.Context, name string, arg ...string) *Cmd {
   150  	if ctx == nil {
   151  		panic("nil Context")
   152  	}
   153  	cmd := Command(name, arg...)
   154  	cmd.ctx = ctx
   155  	return cmd
   156  }
   157  
   158  // interfaceEqual protects against panics from doing equality tests on
   159  // two interfaces with non-comparable underlying types.
   160  func interfaceEqual(a, b interface{}) bool {
   161  	defer func() {
   162  		recover()
   163  	}()
   164  	return a == b
   165  }
   166  
   167  func (c *Cmd) envv() []string {
   168  	if c.Env != nil {
   169  		return c.Env
   170  	}
   171  	return os.Environ()
   172  }
   173  
   174  func (c *Cmd) argv() []string {
   175  	if len(c.Args) > 0 {
   176  		return c.Args
   177  	}
   178  	return []string{c.Path}
   179  }
   180  
   181  // skipStdinCopyError optionally specifies a function which reports
   182  // whether the provided the stdin copy error should be ignored.
   183  // It is non-nil everywhere but Plan 9, which lacks EPIPE. See exec_posix.go.
   184  var skipStdinCopyError func(error) bool
   185  
   186  func (c *Cmd) stdin() (f *os.File, err error) {
   187  	if c.Stdin == nil {
   188  		f, err = os.Open(os.DevNull)
   189  		if err != nil {
   190  			return
   191  		}
   192  		c.closeAfterStart = append(c.closeAfterStart, f)
   193  		return
   194  	}
   195  
   196  	if f, ok := c.Stdin.(*os.File); ok {
   197  		return f, nil
   198  	}
   199  
   200  	pr, pw, err := os.Pipe()
   201  	if err != nil {
   202  		return
   203  	}
   204  
   205  	c.closeAfterStart = append(c.closeAfterStart, pr)
   206  	c.closeAfterWait = append(c.closeAfterWait, pw)
   207  	c.goroutine = append(c.goroutine, func() error {
   208  		_, err := io.Copy(pw, c.Stdin)
   209  		if skip := skipStdinCopyError; skip != nil && skip(err) {
   210  			err = nil
   211  		}
   212  		if err1 := pw.Close(); err == nil {
   213  			err = err1
   214  		}
   215  		return err
   216  	})
   217  	return pr, nil
   218  }
   219  
   220  func (c *Cmd) stdout() (f *os.File, err error) {
   221  	return c.writerDescriptor(c.Stdout)
   222  }
   223  
   224  func (c *Cmd) stderr() (f *os.File, err error) {
   225  	if c.Stderr != nil && interfaceEqual(c.Stderr, c.Stdout) {
   226  		return c.childFiles[1], nil
   227  	}
   228  	return c.writerDescriptor(c.Stderr)
   229  }
   230  
   231  func (c *Cmd) writerDescriptor(w io.Writer) (f *os.File, err error) {
   232  	if w == nil {
   233  		f, err = os.OpenFile(os.DevNull, os.O_WRONLY, 0)
   234  		if err != nil {
   235  			return
   236  		}
   237  		c.closeAfterStart = append(c.closeAfterStart, f)
   238  		return
   239  	}
   240  
   241  	if f, ok := w.(*os.File); ok {
   242  		return f, nil
   243  	}
   244  
   245  	pr, pw, err := os.Pipe()
   246  	if err != nil {
   247  		return
   248  	}
   249  
   250  	c.closeAfterStart = append(c.closeAfterStart, pw)
   251  	c.closeAfterWait = append(c.closeAfterWait, pr)
   252  	c.goroutine = append(c.goroutine, func() error {
   253  		_, err := io.Copy(w, pr)
   254  		pr.Close() // in case io.Copy stopped due to write error
   255  		return err
   256  	})
   257  	return pw, nil
   258  }
   259  
   260  func (c *Cmd) closeDescriptors(closers []io.Closer) {
   261  	for _, fd := range closers {
   262  		fd.Close()
   263  	}
   264  }
   265  
   266  // Run starts the specified command and waits for it to complete.
   267  //
   268  // The returned error is nil if the command runs, has no problems
   269  // copying stdin, stdout, and stderr, and exits with a zero exit
   270  // status.
   271  //
   272  // If the command fails to run or doesn't complete successfully, the
   273  // error is of type *ExitError. Other error types may be
   274  // returned for I/O problems.
   275  func (c *Cmd) Run() error {
   276  	if err := c.Start(); err != nil {
   277  		return err
   278  	}
   279  	return c.Wait()
   280  }
   281  
   282  // lookExtensions finds windows executable by its dir and path.
   283  // It uses LookPath to try appropriate extensions.
   284  // lookExtensions does not search PATH, instead it converts `prog` into `.\prog`.
   285  func lookExtensions(path, dir string) (string, error) {
   286  	if filepath.Base(path) == path {
   287  		path = filepath.Join(".", path)
   288  	}
   289  	if dir == "" {
   290  		return LookPath(path)
   291  	}
   292  	if filepath.VolumeName(path) != "" {
   293  		return LookPath(path)
   294  	}
   295  	if len(path) > 1 && os.IsPathSeparator(path[0]) {
   296  		return LookPath(path)
   297  	}
   298  	dirandpath := filepath.Join(dir, path)
   299  	// We assume that LookPath will only add file extension.
   300  	lp, err := LookPath(dirandpath)
   301  	if err != nil {
   302  		return "", err
   303  	}
   304  	ext := strings.TrimPrefix(lp, dirandpath)
   305  	return path + ext, nil
   306  }
   307  
   308  // Start starts the specified command but does not wait for it to complete.
   309  //
   310  // The Wait method will return the exit code and release associated resources
   311  // once the command exits.
   312  func (c *Cmd) Start() error {
   313  	if c.lookPathErr != nil {
   314  		c.closeDescriptors(c.closeAfterStart)
   315  		c.closeDescriptors(c.closeAfterWait)
   316  		return c.lookPathErr
   317  	}
   318  	if runtime.GOOS == "windows" {
   319  		lp, err := lookExtensions(c.Path, c.Dir)
   320  		if err != nil {
   321  			c.closeDescriptors(c.closeAfterStart)
   322  			c.closeDescriptors(c.closeAfterWait)
   323  			return err
   324  		}
   325  		c.Path = lp
   326  	}
   327  	if c.Process != nil {
   328  		return errors.New("exec: already started")
   329  	}
   330  	if c.ctx != nil {
   331  		select {
   332  		case <-c.ctx.Done():
   333  			c.closeDescriptors(c.closeAfterStart)
   334  			c.closeDescriptors(c.closeAfterWait)
   335  			return c.ctx.Err()
   336  		default:
   337  		}
   338  	}
   339  
   340  	type F func(*Cmd) (*os.File, error)
   341  	for _, setupFd := range []F{(*Cmd).stdin, (*Cmd).stdout, (*Cmd).stderr} {
   342  		fd, err := setupFd(c)
   343  		if err != nil {
   344  			c.closeDescriptors(c.closeAfterStart)
   345  			c.closeDescriptors(c.closeAfterWait)
   346  			return err
   347  		}
   348  		c.childFiles = append(c.childFiles, fd)
   349  	}
   350  	c.childFiles = append(c.childFiles, c.ExtraFiles...)
   351  
   352  	var err error
   353  	c.Process, err = os.StartProcess(c.Path, c.argv(), &os.ProcAttr{
   354  		Dir:   c.Dir,
   355  		Files: c.childFiles,
   356  		Env:   c.envv(),
   357  		Sys:   c.SysProcAttr,
   358  	})
   359  	if err != nil {
   360  		c.closeDescriptors(c.closeAfterStart)
   361  		c.closeDescriptors(c.closeAfterWait)
   362  		return err
   363  	}
   364  
   365  	c.closeDescriptors(c.closeAfterStart)
   366  
   367  	c.errch = make(chan error, len(c.goroutine))
   368  	for _, fn := range c.goroutine {
   369  		go func(fn func() error) {
   370  			c.errch <- fn()
   371  		}(fn)
   372  	}
   373  
   374  	if c.ctx != nil {
   375  		c.waitDone = make(chan struct{})
   376  		go func() {
   377  			select {
   378  			case <-c.ctx.Done():
   379  				c.Process.Kill()
   380  			case <-c.waitDone:
   381  			}
   382  		}()
   383  	}
   384  
   385  	return nil
   386  }
   387  
   388  // An ExitError reports an unsuccessful exit by a command.
   389  type ExitError struct {
   390  	*os.ProcessState
   391  
   392  	// Stderr holds a subset of the standard error output from the
   393  	// Cmd.Output method if standard error was not otherwise being
   394  	// collected.
   395  	//
   396  	// If the error output is long, Stderr may contain only a prefix
   397  	// and suffix of the output, with the middle replaced with
   398  	// text about the number of omitted bytes.
   399  	//
   400  	// Stderr is provided for debugging, for inclusion in error messages.
   401  	// Users with other needs should redirect Cmd.Stderr as needed.
   402  	Stderr []byte
   403  }
   404  
   405  func (e *ExitError) Error() string {
   406  	return e.ProcessState.String()
   407  }
   408  
   409  // Wait waits for the command to exit.
   410  // It must have been started by Start.
   411  //
   412  // The returned error is nil if the command runs, has no problems
   413  // copying stdin, stdout, and stderr, and exits with a zero exit
   414  // status.
   415  //
   416  // If the command fails to run or doesn't complete successfully, the
   417  // error is of type *ExitError. Other error types may be
   418  // returned for I/O problems.
   419  //
   420  // If c.Stdin is not an *os.File, Wait also waits for the I/O loop
   421  // copying from c.Stdin into the process's standard input
   422  // to complete.
   423  //
   424  // Wait releases any resources associated with the Cmd.
   425  func (c *Cmd) Wait() error {
   426  	if c.Process == nil {
   427  		return errors.New("exec: not started")
   428  	}
   429  	if c.finished {
   430  		return errors.New("exec: Wait was already called")
   431  	}
   432  	c.finished = true
   433  
   434  	state, err := c.Process.Wait()
   435  	if c.waitDone != nil {
   436  		close(c.waitDone)
   437  	}
   438  	c.ProcessState = state
   439  
   440  	var copyError error
   441  	for range c.goroutine {
   442  		if err := <-c.errch; err != nil && copyError == nil {
   443  			copyError = err
   444  		}
   445  	}
   446  
   447  	c.closeDescriptors(c.closeAfterWait)
   448  
   449  	if err != nil {
   450  		return err
   451  	} else if !state.Success() {
   452  		return &ExitError{ProcessState: state}
   453  	}
   454  
   455  	return copyError
   456  }
   457  
   458  // Output runs the command and returns its standard output.
   459  // Any returned error will usually be of type *ExitError.
   460  // If c.Stderr was nil, Output populates ExitError.Stderr.
   461  func (c *Cmd) Output() ([]byte, error) {
   462  	if c.Stdout != nil {
   463  		return nil, errors.New("exec: Stdout already set")
   464  	}
   465  	var stdout bytes.Buffer
   466  	c.Stdout = &stdout
   467  
   468  	captureErr := c.Stderr == nil
   469  	if captureErr {
   470  		c.Stderr = &prefixSuffixSaver{N: 32 << 10}
   471  	}
   472  
   473  	err := c.Run()
   474  	if err != nil && captureErr {
   475  		if ee, ok := err.(*ExitError); ok {
   476  			ee.Stderr = c.Stderr.(*prefixSuffixSaver).Bytes()
   477  		}
   478  	}
   479  	return stdout.Bytes(), err
   480  }
   481  
   482  // CombinedOutput runs the command and returns its combined standard
   483  // output and standard error.
   484  func (c *Cmd) CombinedOutput() ([]byte, error) {
   485  	if c.Stdout != nil {
   486  		return nil, errors.New("exec: Stdout already set")
   487  	}
   488  	if c.Stderr != nil {
   489  		return nil, errors.New("exec: Stderr already set")
   490  	}
   491  	var b bytes.Buffer
   492  	c.Stdout = &b
   493  	c.Stderr = &b
   494  	err := c.Run()
   495  	return b.Bytes(), err
   496  }
   497  
   498  // StdinPipe returns a pipe that will be connected to the command's
   499  // standard input when the command starts.
   500  // The pipe will be closed automatically after Wait sees the command exit.
   501  // A caller need only call Close to force the pipe to close sooner.
   502  // For example, if the command being run will not exit until standard input
   503  // is closed, the caller must close the pipe.
   504  func (c *Cmd) StdinPipe() (io.WriteCloser, error) {
   505  	if c.Stdin != nil {
   506  		return nil, errors.New("exec: Stdin already set")
   507  	}
   508  	if c.Process != nil {
   509  		return nil, errors.New("exec: StdinPipe after process started")
   510  	}
   511  	pr, pw, err := os.Pipe()
   512  	if err != nil {
   513  		return nil, err
   514  	}
   515  	c.Stdin = pr
   516  	c.closeAfterStart = append(c.closeAfterStart, pr)
   517  	wc := &closeOnce{File: pw}
   518  	c.closeAfterWait = append(c.closeAfterWait, wc)
   519  	return wc, nil
   520  }
   521  
   522  type closeOnce struct {
   523  	*os.File
   524  
   525  	once sync.Once
   526  	err  error
   527  }
   528  
   529  func (c *closeOnce) Close() error {
   530  	c.once.Do(c.close)
   531  	return c.err
   532  }
   533  
   534  func (c *closeOnce) close() {
   535  	c.err = c.File.Close()
   536  }
   537  
   538  // StdoutPipe returns a pipe that will be connected to the command's
   539  // standard output when the command starts.
   540  //
   541  // Wait will close the pipe after seeing the command exit, so most callers
   542  // need not close the pipe themselves; however, an implication is that
   543  // it is incorrect to call Wait before all reads from the pipe have completed.
   544  // For the same reason, it is incorrect to call Run when using StdoutPipe.
   545  // See the example for idiomatic usage.
   546  func (c *Cmd) StdoutPipe() (io.ReadCloser, error) {
   547  	if c.Stdout != nil {
   548  		return nil, errors.New("exec: Stdout already set")
   549  	}
   550  	if c.Process != nil {
   551  		return nil, errors.New("exec: StdoutPipe after process started")
   552  	}
   553  	pr, pw, err := os.Pipe()
   554  	if err != nil {
   555  		return nil, err
   556  	}
   557  	c.Stdout = pw
   558  	c.closeAfterStart = append(c.closeAfterStart, pw)
   559  	c.closeAfterWait = append(c.closeAfterWait, pr)
   560  	return pr, nil
   561  }
   562  
   563  // StderrPipe returns a pipe that will be connected to the command's
   564  // standard error when the command starts.
   565  //
   566  // Wait will close the pipe after seeing the command exit, so most callers
   567  // need not close the pipe themselves; however, an implication is that
   568  // it is incorrect to call Wait before all reads from the pipe have completed.
   569  // For the same reason, it is incorrect to use Run when using StderrPipe.
   570  // See the StdoutPipe example for idiomatic usage.
   571  func (c *Cmd) StderrPipe() (io.ReadCloser, error) {
   572  	if c.Stderr != nil {
   573  		return nil, errors.New("exec: Stderr already set")
   574  	}
   575  	if c.Process != nil {
   576  		return nil, errors.New("exec: StderrPipe after process started")
   577  	}
   578  	pr, pw, err := os.Pipe()
   579  	if err != nil {
   580  		return nil, err
   581  	}
   582  	c.Stderr = pw
   583  	c.closeAfterStart = append(c.closeAfterStart, pw)
   584  	c.closeAfterWait = append(c.closeAfterWait, pr)
   585  	return pr, nil
   586  }
   587  
   588  // prefixSuffixSaver is an io.Writer which retains the first N bytes
   589  // and the last N bytes written to it. The Bytes() methods reconstructs
   590  // it with a pretty error message.
   591  type prefixSuffixSaver struct {
   592  	N         int // max size of prefix or suffix
   593  	prefix    []byte
   594  	suffix    []byte // ring buffer once len(suffix) == N
   595  	suffixOff int    // offset to write into suffix
   596  	skipped   int64
   597  
   598  	// TODO(bradfitz): we could keep one large []byte and use part of it for
   599  	// the prefix, reserve space for the '... Omitting N bytes ...' message,
   600  	// then the ring buffer suffix, and just rearrange the ring buffer
   601  	// suffix when Bytes() is called, but it doesn't seem worth it for
   602  	// now just for error messages. It's only ~64KB anyway.
   603  }
   604  
   605  func (w *prefixSuffixSaver) Write(p []byte) (n int, err error) {
   606  	lenp := len(p)
   607  	p = w.fill(&w.prefix, p)
   608  
   609  	// Only keep the last w.N bytes of suffix data.
   610  	if overage := len(p) - w.N; overage > 0 {
   611  		p = p[overage:]
   612  		w.skipped += int64(overage)
   613  	}
   614  	p = w.fill(&w.suffix, p)
   615  
   616  	// w.suffix is full now if p is non-empty. Overwrite it in a circle.
   617  	for len(p) > 0 { // 0, 1, or 2 iterations.
   618  		n := copy(w.suffix[w.suffixOff:], p)
   619  		p = p[n:]
   620  		w.skipped += int64(n)
   621  		w.suffixOff += n
   622  		if w.suffixOff == w.N {
   623  			w.suffixOff = 0
   624  		}
   625  	}
   626  	return lenp, nil
   627  }
   628  
   629  // fill appends up to len(p) bytes of p to *dst, such that *dst does not
   630  // grow larger than w.N. It returns the un-appended suffix of p.
   631  func (w *prefixSuffixSaver) fill(dst *[]byte, p []byte) (pRemain []byte) {
   632  	if remain := w.N - len(*dst); remain > 0 {
   633  		add := minInt(len(p), remain)
   634  		*dst = append(*dst, p[:add]...)
   635  		p = p[add:]
   636  	}
   637  	return p
   638  }
   639  
   640  func (w *prefixSuffixSaver) Bytes() []byte {
   641  	if w.suffix == nil {
   642  		return w.prefix
   643  	}
   644  	if w.skipped == 0 {
   645  		return append(w.prefix, w.suffix...)
   646  	}
   647  	var buf bytes.Buffer
   648  	buf.Grow(len(w.prefix) + len(w.suffix) + 50)
   649  	buf.Write(w.prefix)
   650  	buf.WriteString("\n... omitting ")
   651  	buf.WriteString(strconv.FormatInt(w.skipped, 10))
   652  	buf.WriteString(" bytes ...\n")
   653  	buf.Write(w.suffix[w.suffixOff:])
   654  	buf.Write(w.suffix[:w.suffixOff])
   655  	return buf.Bytes()
   656  }
   657  
   658  func minInt(a, b int) int {
   659  	if a < b {
   660  		return a
   661  	}
   662  	return b
   663  }