github.com/slayercat/go@v0.0.0-20170428012452-c51559813f61/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 // Each entry is of the form "key=value". 59 // If Env is nil, the new process uses the current process's 60 // environment. 61 // If Env contains duplicate environment keys, only the last 62 // value in the slice for each duplicate key is used. 63 Env []string 64 65 // Dir specifies the working directory of the command. 66 // If Dir is the empty string, Run runs the command in the 67 // calling process's current directory. 68 Dir string 69 70 // Stdin specifies the process's standard input. 71 // If Stdin is nil, the process reads from the null device (os.DevNull). 72 // If Stdin is an *os.File, the process's standard input is connected 73 // directly to that file. 74 // Otherwise, during the execution of the command a separate 75 // goroutine reads from Stdin and delivers that data to the command 76 // over a pipe. In this case, Wait does not complete until the goroutine 77 // stops copying, either because it has reached the end of Stdin 78 // (EOF or a read error) or because writing to the pipe returned an error. 79 Stdin io.Reader 80 81 // Stdout and Stderr specify the process's standard output and error. 82 // 83 // If either is nil, Run connects the corresponding file descriptor 84 // to the null device (os.DevNull). 85 // 86 // If Stdout and Stderr are the same writer, at most one 87 // goroutine at a time will call Write. 88 Stdout io.Writer 89 Stderr io.Writer 90 91 // ExtraFiles specifies additional open files to be inherited by the 92 // new process. It does not include standard input, standard output, or 93 // standard error. If non-nil, entry i becomes file descriptor 3+i. 94 // 95 // BUG(rsc): On OS X 10.6, child processes may sometimes inherit unwanted fds. 96 // https://golang.org/issue/2603 97 ExtraFiles []*os.File 98 99 // SysProcAttr holds optional, operating system-specific attributes. 100 // Run passes it to os.StartProcess as the os.ProcAttr's Sys field. 101 SysProcAttr *syscall.SysProcAttr 102 103 // Process is the underlying process, once started. 104 Process *os.Process 105 106 // ProcessState contains information about an exited process, 107 // available after a call to Wait or Run. 108 ProcessState *os.ProcessState 109 110 ctx context.Context // nil means none 111 lookPathErr error // LookPath error, if any. 112 finished bool // when Wait was called 113 childFiles []*os.File 114 closeAfterStart []io.Closer 115 closeAfterWait []io.Closer 116 goroutine []func() error 117 errch chan error // one send per goroutine 118 waitDone chan struct{} 119 } 120 121 // Command returns the Cmd struct to execute the named program with 122 // the given arguments. 123 // 124 // It sets only the Path and Args in the returned structure. 125 // 126 // If name contains no path separators, Command uses LookPath to 127 // resolve name to a complete path if possible. Otherwise it uses name 128 // directly as Path. 129 // 130 // The returned Cmd's Args field is constructed from the command name 131 // followed by the elements of arg, so arg should not include the 132 // command name itself. For example, Command("echo", "hello"). 133 // Args[0] is always name, not the possibly resolved Path. 134 func Command(name string, arg ...string) *Cmd { 135 cmd := &Cmd{ 136 Path: name, 137 Args: append([]string{name}, arg...), 138 } 139 if filepath.Base(name) == name { 140 if lp, err := LookPath(name); err != nil { 141 cmd.lookPathErr = err 142 } else { 143 cmd.Path = lp 144 } 145 } 146 return cmd 147 } 148 149 // CommandContext is like Command but includes a context. 150 // 151 // The provided context is used to kill the process (by calling 152 // os.Process.Kill) if the context becomes done before the command 153 // completes on its own. 154 func CommandContext(ctx context.Context, name string, arg ...string) *Cmd { 155 if ctx == nil { 156 panic("nil Context") 157 } 158 cmd := Command(name, arg...) 159 cmd.ctx = ctx 160 return cmd 161 } 162 163 // interfaceEqual protects against panics from doing equality tests on 164 // two interfaces with non-comparable underlying types. 165 func interfaceEqual(a, b interface{}) bool { 166 defer func() { 167 recover() 168 }() 169 return a == b 170 } 171 172 func (c *Cmd) envv() []string { 173 if c.Env != nil { 174 return c.Env 175 } 176 return os.Environ() 177 } 178 179 func (c *Cmd) argv() []string { 180 if len(c.Args) > 0 { 181 return c.Args 182 } 183 return []string{c.Path} 184 } 185 186 // skipStdinCopyError optionally specifies a function which reports 187 // whether the provided the stdin copy error should be ignored. 188 // It is non-nil everywhere but Plan 9, which lacks EPIPE. See exec_posix.go. 189 var skipStdinCopyError func(error) bool 190 191 func (c *Cmd) stdin() (f *os.File, err error) { 192 if c.Stdin == nil { 193 f, err = os.Open(os.DevNull) 194 if err != nil { 195 return 196 } 197 c.closeAfterStart = append(c.closeAfterStart, f) 198 return 199 } 200 201 if f, ok := c.Stdin.(*os.File); ok { 202 return f, nil 203 } 204 205 pr, pw, err := os.Pipe() 206 if err != nil { 207 return 208 } 209 210 c.closeAfterStart = append(c.closeAfterStart, pr) 211 c.closeAfterWait = append(c.closeAfterWait, pw) 212 c.goroutine = append(c.goroutine, func() error { 213 _, err := io.Copy(pw, c.Stdin) 214 if skip := skipStdinCopyError; skip != nil && skip(err) { 215 err = nil 216 } 217 if err1 := pw.Close(); err == nil { 218 err = err1 219 } 220 return err 221 }) 222 return pr, nil 223 } 224 225 func (c *Cmd) stdout() (f *os.File, err error) { 226 return c.writerDescriptor(c.Stdout) 227 } 228 229 func (c *Cmd) stderr() (f *os.File, err error) { 230 if c.Stderr != nil && interfaceEqual(c.Stderr, c.Stdout) { 231 return c.childFiles[1], nil 232 } 233 return c.writerDescriptor(c.Stderr) 234 } 235 236 func (c *Cmd) writerDescriptor(w io.Writer) (f *os.File, err error) { 237 if w == nil { 238 f, err = os.OpenFile(os.DevNull, os.O_WRONLY, 0) 239 if err != nil { 240 return 241 } 242 c.closeAfterStart = append(c.closeAfterStart, f) 243 return 244 } 245 246 if f, ok := w.(*os.File); ok { 247 return f, nil 248 } 249 250 pr, pw, err := os.Pipe() 251 if err != nil { 252 return 253 } 254 255 c.closeAfterStart = append(c.closeAfterStart, pw) 256 c.closeAfterWait = append(c.closeAfterWait, pr) 257 c.goroutine = append(c.goroutine, func() error { 258 _, err := io.Copy(w, pr) 259 pr.Close() // in case io.Copy stopped due to write error 260 return err 261 }) 262 return pw, nil 263 } 264 265 func (c *Cmd) closeDescriptors(closers []io.Closer) { 266 for _, fd := range closers { 267 fd.Close() 268 } 269 } 270 271 // Run starts the specified command and waits for it to complete. 272 // 273 // The returned error is nil if the command runs, has no problems 274 // copying stdin, stdout, and stderr, and exits with a zero exit 275 // status. 276 // 277 // If the command starts but does not complete successfully, the error is of 278 // type *ExitError. Other error types may be returned for other situations. 279 func (c *Cmd) Run() error { 280 if err := c.Start(); err != nil { 281 return err 282 } 283 return c.Wait() 284 } 285 286 // lookExtensions finds windows executable by its dir and path. 287 // It uses LookPath to try appropriate extensions. 288 // lookExtensions does not search PATH, instead it converts `prog` into `.\prog`. 289 func lookExtensions(path, dir string) (string, error) { 290 if filepath.Base(path) == path { 291 path = filepath.Join(".", path) 292 } 293 if dir == "" { 294 return LookPath(path) 295 } 296 if filepath.VolumeName(path) != "" { 297 return LookPath(path) 298 } 299 if len(path) > 1 && os.IsPathSeparator(path[0]) { 300 return LookPath(path) 301 } 302 dirandpath := filepath.Join(dir, path) 303 // We assume that LookPath will only add file extension. 304 lp, err := LookPath(dirandpath) 305 if err != nil { 306 return "", err 307 } 308 ext := strings.TrimPrefix(lp, dirandpath) 309 return path + ext, nil 310 } 311 312 // Start starts the specified command but does not wait for it to complete. 313 // 314 // The Wait method will return the exit code and release associated resources 315 // once the command exits. 316 func (c *Cmd) Start() error { 317 if c.lookPathErr != nil { 318 c.closeDescriptors(c.closeAfterStart) 319 c.closeDescriptors(c.closeAfterWait) 320 return c.lookPathErr 321 } 322 if runtime.GOOS == "windows" { 323 lp, err := lookExtensions(c.Path, c.Dir) 324 if err != nil { 325 c.closeDescriptors(c.closeAfterStart) 326 c.closeDescriptors(c.closeAfterWait) 327 return err 328 } 329 c.Path = lp 330 } 331 if c.Process != nil { 332 return errors.New("exec: already started") 333 } 334 if c.ctx != nil { 335 select { 336 case <-c.ctx.Done(): 337 c.closeDescriptors(c.closeAfterStart) 338 c.closeDescriptors(c.closeAfterWait) 339 return c.ctx.Err() 340 default: 341 } 342 } 343 344 type F func(*Cmd) (*os.File, error) 345 for _, setupFd := range []F{(*Cmd).stdin, (*Cmd).stdout, (*Cmd).stderr} { 346 fd, err := setupFd(c) 347 if err != nil { 348 c.closeDescriptors(c.closeAfterStart) 349 c.closeDescriptors(c.closeAfterWait) 350 return err 351 } 352 c.childFiles = append(c.childFiles, fd) 353 } 354 c.childFiles = append(c.childFiles, c.ExtraFiles...) 355 356 var err error 357 c.Process, err = os.StartProcess(c.Path, c.argv(), &os.ProcAttr{ 358 Dir: c.Dir, 359 Files: c.childFiles, 360 Env: dedupEnv(c.envv()), 361 Sys: c.SysProcAttr, 362 }) 363 if err != nil { 364 c.closeDescriptors(c.closeAfterStart) 365 c.closeDescriptors(c.closeAfterWait) 366 return err 367 } 368 369 c.closeDescriptors(c.closeAfterStart) 370 371 c.errch = make(chan error, len(c.goroutine)) 372 for _, fn := range c.goroutine { 373 go func(fn func() error) { 374 c.errch <- fn() 375 }(fn) 376 } 377 378 if c.ctx != nil { 379 c.waitDone = make(chan struct{}) 380 go func() { 381 select { 382 case <-c.ctx.Done(): 383 c.Process.Kill() 384 case <-c.waitDone: 385 } 386 }() 387 } 388 389 return nil 390 } 391 392 // An ExitError reports an unsuccessful exit by a command. 393 type ExitError struct { 394 *os.ProcessState 395 396 // Stderr holds a subset of the standard error output from the 397 // Cmd.Output method if standard error was not otherwise being 398 // collected. 399 // 400 // If the error output is long, Stderr may contain only a prefix 401 // and suffix of the output, with the middle replaced with 402 // text about the number of omitted bytes. 403 // 404 // Stderr is provided for debugging, for inclusion in error messages. 405 // Users with other needs should redirect Cmd.Stderr as needed. 406 Stderr []byte 407 } 408 409 func (e *ExitError) Error() string { 410 return e.ProcessState.String() 411 } 412 413 // Wait waits for the command to exit. 414 // It must have been started by Start. 415 // 416 // The returned error is nil if the command runs, has no problems 417 // copying stdin, stdout, and stderr, and exits with a zero exit 418 // status. 419 // 420 // If the command fails to run or doesn't complete successfully, the 421 // error is of type *ExitError. Other error types may be 422 // returned for I/O problems. 423 // 424 // If c.Stdin is not an *os.File, Wait also waits for the I/O loop 425 // copying from c.Stdin into the process's standard input 426 // to complete. 427 // 428 // Wait releases any resources associated with the Cmd. 429 func (c *Cmd) Wait() error { 430 if c.Process == nil { 431 return errors.New("exec: not started") 432 } 433 if c.finished { 434 return errors.New("exec: Wait was already called") 435 } 436 c.finished = true 437 438 state, err := c.Process.Wait() 439 if c.waitDone != nil { 440 close(c.waitDone) 441 } 442 c.ProcessState = state 443 444 var copyError error 445 for range c.goroutine { 446 if err := <-c.errch; err != nil && copyError == nil { 447 copyError = err 448 } 449 } 450 451 c.closeDescriptors(c.closeAfterWait) 452 453 if err != nil { 454 return err 455 } else if !state.Success() { 456 return &ExitError{ProcessState: state} 457 } 458 459 return copyError 460 } 461 462 // Output runs the command and returns its standard output. 463 // Any returned error will usually be of type *ExitError. 464 // If c.Stderr was nil, Output populates ExitError.Stderr. 465 func (c *Cmd) Output() ([]byte, error) { 466 if c.Stdout != nil { 467 return nil, errors.New("exec: Stdout already set") 468 } 469 var stdout bytes.Buffer 470 c.Stdout = &stdout 471 472 captureErr := c.Stderr == nil 473 if captureErr { 474 c.Stderr = &prefixSuffixSaver{N: 32 << 10} 475 } 476 477 err := c.Run() 478 if err != nil && captureErr { 479 if ee, ok := err.(*ExitError); ok { 480 ee.Stderr = c.Stderr.(*prefixSuffixSaver).Bytes() 481 } 482 } 483 return stdout.Bytes(), err 484 } 485 486 // CombinedOutput runs the command and returns its combined standard 487 // output and standard error. 488 func (c *Cmd) CombinedOutput() ([]byte, error) { 489 if c.Stdout != nil { 490 return nil, errors.New("exec: Stdout already set") 491 } 492 if c.Stderr != nil { 493 return nil, errors.New("exec: Stderr already set") 494 } 495 var b bytes.Buffer 496 c.Stdout = &b 497 c.Stderr = &b 498 err := c.Run() 499 return b.Bytes(), err 500 } 501 502 // StdinPipe returns a pipe that will be connected to the command's 503 // standard input when the command starts. 504 // The pipe will be closed automatically after Wait sees the command exit. 505 // A caller need only call Close to force the pipe to close sooner. 506 // For example, if the command being run will not exit until standard input 507 // is closed, the caller must close the pipe. 508 func (c *Cmd) StdinPipe() (io.WriteCloser, error) { 509 if c.Stdin != nil { 510 return nil, errors.New("exec: Stdin already set") 511 } 512 if c.Process != nil { 513 return nil, errors.New("exec: StdinPipe after process started") 514 } 515 pr, pw, err := os.Pipe() 516 if err != nil { 517 return nil, err 518 } 519 c.Stdin = pr 520 c.closeAfterStart = append(c.closeAfterStart, pr) 521 wc := &closeOnce{File: pw} 522 c.closeAfterWait = append(c.closeAfterWait, closerFunc(wc.safeClose)) 523 return wc, nil 524 } 525 526 type closeOnce struct { 527 *os.File 528 529 writers sync.RWMutex // coordinate safeClose and Write 530 once sync.Once 531 err error 532 } 533 534 func (c *closeOnce) Close() error { 535 c.once.Do(c.close) 536 return c.err 537 } 538 539 func (c *closeOnce) close() { 540 c.err = c.File.Close() 541 } 542 543 type closerFunc func() error 544 545 func (f closerFunc) Close() error { return f() } 546 547 // safeClose closes c being careful not to race with any calls to c.Write. 548 // See golang.org/issue/9307 and TestEchoFileRace in exec_test.go. 549 // In theory other calls could also be excluded (by writing appropriate 550 // wrappers like c.Write's implementation below), but since c is most 551 // commonly used as a WriteCloser, Write is the main one to worry about. 552 // See also #7970, for which this is a partial fix for this specific instance. 553 // The idea is that we return a WriteCloser, and so the caller can be 554 // relied upon not to call Write and Close simultaneously, but it's less 555 // obvious that cmd.Wait calls Close and that the caller must not call 556 // Write and cmd.Wait simultaneously. In fact that seems too onerous. 557 // So we change the use of Close in cmd.Wait to use safeClose, which will 558 // synchronize with any Write. 559 // 560 // It's important that we know this won't block forever waiting for the 561 // operations being excluded. At the point where this is called, 562 // the invoked command has exited and the parent copy of the read side 563 // of the pipe has also been closed, so there should really be no read side 564 // of the pipe left. Any active writes should return very shortly with an EPIPE, 565 // making it reasonable to wait for them. 566 // Technically it is possible that the child forked a sub-process or otherwise 567 // handed off the read side of the pipe before exiting and the current holder 568 // is not reading from the pipe, and the pipe is full, in which case the close here 569 // might block waiting for the write to complete. That's probably OK. 570 // It's a small enough problem to be outweighed by eliminating the race here. 571 func (c *closeOnce) safeClose() error { 572 c.writers.Lock() 573 err := c.Close() 574 c.writers.Unlock() 575 return err 576 } 577 578 func (c *closeOnce) Write(b []byte) (int, error) { 579 c.writers.RLock() 580 n, err := c.File.Write(b) 581 c.writers.RUnlock() 582 return n, err 583 } 584 585 func (c *closeOnce) WriteString(s string) (int, error) { 586 c.writers.RLock() 587 n, err := c.File.WriteString(s) 588 c.writers.RUnlock() 589 return n, err 590 } 591 592 // StdoutPipe returns a pipe that will be connected to the command's 593 // standard output when the command starts. 594 // 595 // Wait will close the pipe after seeing the command exit, so most callers 596 // need not close the pipe themselves; however, an implication is that 597 // it is incorrect to call Wait before all reads from the pipe have completed. 598 // For the same reason, it is incorrect to call Run when using StdoutPipe. 599 // See the example for idiomatic usage. 600 func (c *Cmd) StdoutPipe() (io.ReadCloser, error) { 601 if c.Stdout != nil { 602 return nil, errors.New("exec: Stdout already set") 603 } 604 if c.Process != nil { 605 return nil, errors.New("exec: StdoutPipe after process started") 606 } 607 pr, pw, err := os.Pipe() 608 if err != nil { 609 return nil, err 610 } 611 c.Stdout = pw 612 c.closeAfterStart = append(c.closeAfterStart, pw) 613 c.closeAfterWait = append(c.closeAfterWait, pr) 614 return pr, nil 615 } 616 617 // StderrPipe returns a pipe that will be connected to the command's 618 // standard error when the command starts. 619 // 620 // Wait will close the pipe after seeing the command exit, so most callers 621 // need not close the pipe themselves; however, an implication is that 622 // it is incorrect to call Wait before all reads from the pipe have completed. 623 // For the same reason, it is incorrect to use Run when using StderrPipe. 624 // See the StdoutPipe example for idiomatic usage. 625 func (c *Cmd) StderrPipe() (io.ReadCloser, error) { 626 if c.Stderr != nil { 627 return nil, errors.New("exec: Stderr already set") 628 } 629 if c.Process != nil { 630 return nil, errors.New("exec: StderrPipe after process started") 631 } 632 pr, pw, err := os.Pipe() 633 if err != nil { 634 return nil, err 635 } 636 c.Stderr = pw 637 c.closeAfterStart = append(c.closeAfterStart, pw) 638 c.closeAfterWait = append(c.closeAfterWait, pr) 639 return pr, nil 640 } 641 642 // prefixSuffixSaver is an io.Writer which retains the first N bytes 643 // and the last N bytes written to it. The Bytes() methods reconstructs 644 // it with a pretty error message. 645 type prefixSuffixSaver struct { 646 N int // max size of prefix or suffix 647 prefix []byte 648 suffix []byte // ring buffer once len(suffix) == N 649 suffixOff int // offset to write into suffix 650 skipped int64 651 652 // TODO(bradfitz): we could keep one large []byte and use part of it for 653 // the prefix, reserve space for the '... Omitting N bytes ...' message, 654 // then the ring buffer suffix, and just rearrange the ring buffer 655 // suffix when Bytes() is called, but it doesn't seem worth it for 656 // now just for error messages. It's only ~64KB anyway. 657 } 658 659 func (w *prefixSuffixSaver) Write(p []byte) (n int, err error) { 660 lenp := len(p) 661 p = w.fill(&w.prefix, p) 662 663 // Only keep the last w.N bytes of suffix data. 664 if overage := len(p) - w.N; overage > 0 { 665 p = p[overage:] 666 w.skipped += int64(overage) 667 } 668 p = w.fill(&w.suffix, p) 669 670 // w.suffix is full now if p is non-empty. Overwrite it in a circle. 671 for len(p) > 0 { // 0, 1, or 2 iterations. 672 n := copy(w.suffix[w.suffixOff:], p) 673 p = p[n:] 674 w.skipped += int64(n) 675 w.suffixOff += n 676 if w.suffixOff == w.N { 677 w.suffixOff = 0 678 } 679 } 680 return lenp, nil 681 } 682 683 // fill appends up to len(p) bytes of p to *dst, such that *dst does not 684 // grow larger than w.N. It returns the un-appended suffix of p. 685 func (w *prefixSuffixSaver) fill(dst *[]byte, p []byte) (pRemain []byte) { 686 if remain := w.N - len(*dst); remain > 0 { 687 add := minInt(len(p), remain) 688 *dst = append(*dst, p[:add]...) 689 p = p[add:] 690 } 691 return p 692 } 693 694 func (w *prefixSuffixSaver) Bytes() []byte { 695 if w.suffix == nil { 696 return w.prefix 697 } 698 if w.skipped == 0 { 699 return append(w.prefix, w.suffix...) 700 } 701 var buf bytes.Buffer 702 buf.Grow(len(w.prefix) + len(w.suffix) + 50) 703 buf.Write(w.prefix) 704 buf.WriteString("\n... omitting ") 705 buf.WriteString(strconv.FormatInt(w.skipped, 10)) 706 buf.WriteString(" bytes ...\n") 707 buf.Write(w.suffix[w.suffixOff:]) 708 buf.Write(w.suffix[:w.suffixOff]) 709 return buf.Bytes() 710 } 711 712 func minInt(a, b int) int { 713 if a < b { 714 return a 715 } 716 return b 717 } 718 719 // dedupEnv returns a copy of env with any duplicates removed, in favor of 720 // later values. 721 // Items not of the normal environment "key=value" form are preserved unchanged. 722 func dedupEnv(env []string) []string { 723 return dedupEnvCase(runtime.GOOS == "windows", env) 724 } 725 726 // dedupEnvCase is dedupEnv with a case option for testing. 727 // If caseInsensitive is true, the case of keys is ignored. 728 func dedupEnvCase(caseInsensitive bool, env []string) []string { 729 out := make([]string, 0, len(env)) 730 saw := map[string]int{} // key => index into out 731 for _, kv := range env { 732 eq := strings.Index(kv, "=") 733 if eq < 0 { 734 out = append(out, kv) 735 continue 736 } 737 k := kv[:eq] 738 if caseInsensitive { 739 k = strings.ToLower(k) 740 } 741 if dupIdx, isDup := saw[k]; isDup { 742 out[dupIdx] = kv 743 continue 744 } 745 saw[k] = len(out) 746 out = append(out, kv) 747 } 748 return out 749 }