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