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 // 22 // # Executables in the current directory 23 // 24 // The functions Command and LookPath look for a program 25 // in the directories listed in the current path, following the 26 // conventions of the host operating system. 27 // Operating systems have for decades included the current 28 // directory in this search, sometimes implicitly and sometimes 29 // configured explicitly that way by default. 30 // Modern practice is that including the current directory 31 // is usually unexpected and often leads to security problems. 32 // 33 // To avoid those security problems, as of Go 1.19, this package will not resolve a program 34 // using an implicit or explicit path entry relative to the current directory. 35 // That is, if you run exec.LookPath("go"), it will not successfully return 36 // ./go on Unix nor .\go.exe on Windows, no matter how the path is configured. 37 // Instead, if the usual path algorithms would result in that answer, 38 // these functions return an error err satisfying errors.Is(err, ErrDot). 39 // 40 // For example, consider these two program snippets: 41 // 42 // path, err := exec.LookPath("prog") 43 // if err != nil { 44 // log.Fatal(err) 45 // } 46 // use(path) 47 // 48 // and 49 // 50 // cmd := exec.Command("prog") 51 // if err := cmd.Run(); err != nil { 52 // log.Fatal(err) 53 // } 54 // 55 // These will not find and run ./prog or .\prog.exe, 56 // no matter how the current path is configured. 57 // 58 // Code that always wants to run a program from the current directory 59 // can be rewritten to say "./prog" instead of "prog". 60 // 61 // Code that insists on including results from relative path entries 62 // can instead override the error using an errors.Is check: 63 // 64 // path, err := exec.LookPath("prog") 65 // if errors.Is(err, exec.ErrDot) { 66 // err = nil 67 // } 68 // if err != nil { 69 // log.Fatal(err) 70 // } 71 // use(path) 72 // 73 // and 74 // 75 // cmd := exec.Command("prog") 76 // if errors.Is(cmd.Err, exec.ErrDot) { 77 // cmd.Err = nil 78 // } 79 // if err := cmd.Run(); err != nil { 80 // log.Fatal(err) 81 // } 82 // 83 // Setting the environment variable GODEBUG=execerrdot=0 84 // disables generation of ErrDot entirely, temporarily restoring the pre-Go 1.19 85 // behavior for programs that are unable to apply more targeted fixes. 86 // A future version of Go may remove support for this variable. 87 // 88 // Before adding such overrides, make sure you understand the 89 // security implications of doing so. 90 // See https://go.dev/blog/path-security for more information. 91 package exec 92 93 import ( 94 "bytes" 95 "context" 96 "errors" 97 "internal/godebug" 98 "internal/syscall/execenv" 99 "io" 100 "os" 101 "path/filepath" 102 "runtime" 103 "strconv" 104 "strings" 105 "syscall" 106 "time" 107 ) 108 109 // Error is returned by LookPath when it fails to classify a file as an 110 // executable. 111 type Error struct { 112 // Name is the file name for which the error occurred. 113 Name string 114 // Err is the underlying error. 115 Err error 116 } 117 118 func (e *Error) Error() string { 119 return "exec: " + strconv.Quote(e.Name) + ": " + e.Err.Error() 120 } 121 122 func (e *Error) Unwrap() error { return e.Err } 123 124 // ErrWaitDelay is returned by (*Cmd).Wait if the process exits with a 125 // successful status code but its output pipes are not closed before the 126 // command's WaitDelay expires. 127 var ErrWaitDelay = errors.New("exec: WaitDelay expired before I/O complete") 128 129 // wrappedError wraps an error without relying on fmt.Errorf. 130 type wrappedError struct { 131 prefix string 132 err error 133 } 134 135 func (w wrappedError) Error() string { 136 return w.prefix + ": " + w.err.Error() 137 } 138 139 func (w wrappedError) Unwrap() error { 140 return w.err 141 } 142 143 // Cmd represents an external command being prepared or run. 144 // 145 // A Cmd cannot be reused after calling its Run, Output or CombinedOutput 146 // methods. 147 type Cmd struct { 148 // Path is the path of the command to run. 149 // 150 // This is the only field that must be set to a non-zero 151 // value. If Path is relative, it is evaluated relative 152 // to Dir. 153 Path string 154 155 // Args holds command line arguments, including the command as Args[0]. 156 // If the Args field is empty or nil, Run uses {Path}. 157 // 158 // In typical use, both Path and Args are set by calling Command. 159 Args []string 160 161 // Env specifies the environment of the process. 162 // Each entry is of the form "key=value". 163 // If Env is nil, the new process uses the current process's 164 // environment. 165 // If Env contains duplicate environment keys, only the last 166 // value in the slice for each duplicate key is used. 167 // As a special case on Windows, SYSTEMROOT is always added if 168 // missing and not explicitly set to the empty string. 169 Env []string 170 171 // Dir specifies the working directory of the command. 172 // If Dir is the empty string, Run runs the command in the 173 // calling process's current directory. 174 Dir string 175 176 // Stdin specifies the process's standard input. 177 // 178 // If Stdin is nil, the process reads from the null device (os.DevNull). 179 // 180 // If Stdin is an *os.File, the process's standard input is connected 181 // directly to that file. 182 // 183 // Otherwise, during the execution of the command a separate 184 // goroutine reads from Stdin and delivers that data to the command 185 // over a pipe. In this case, Wait does not complete until the goroutine 186 // stops copying, either because it has reached the end of Stdin 187 // (EOF or a read error), or because writing to the pipe returned an error, 188 // or because a nonzero WaitDelay was set and expired. 189 Stdin io.Reader 190 191 // Stdout and Stderr specify the process's standard output and error. 192 // 193 // If either is nil, Run connects the corresponding file descriptor 194 // to the null device (os.DevNull). 195 // 196 // If either is an *os.File, the corresponding output from the process 197 // is connected directly to that file. 198 // 199 // Otherwise, during the execution of the command a separate goroutine 200 // reads from the process over a pipe and delivers that data to the 201 // corresponding Writer. In this case, Wait does not complete until the 202 // goroutine reaches EOF or encounters an error or a nonzero WaitDelay 203 // expires. 204 // 205 // If Stdout and Stderr are the same writer, and have a type that can 206 // be compared with ==, at most one goroutine at a time will call Write. 207 Stdout io.Writer 208 Stderr io.Writer 209 210 // ExtraFiles specifies additional open files to be inherited by the 211 // new process. It does not include standard input, standard output, or 212 // standard error. If non-nil, entry i becomes file descriptor 3+i. 213 // 214 // ExtraFiles is not supported on Windows. 215 ExtraFiles []*os.File 216 217 // SysProcAttr holds optional, operating system-specific attributes. 218 // Run passes it to os.StartProcess as the os.ProcAttr's Sys field. 219 SysProcAttr *syscall.SysProcAttr 220 221 // Process is the underlying process, once started. 222 Process *os.Process 223 224 // ProcessState contains information about an exited process. 225 // If the process was started successfully, Wait or Run will 226 // populate its ProcessState when the command completes. 227 ProcessState *os.ProcessState 228 229 // ctx is the context passed to CommandContext, if any. 230 ctx context.Context 231 232 Err error // LookPath error, if any. 233 234 // If Cancel is non-nil, the command must have been created with 235 // CommandContext and Cancel will be called when the command's 236 // Context is done. By default, CommandContext sets Cancel to 237 // call the Kill method on the command's Process. 238 // 239 // Typically a custom Cancel will send a signal to the command's 240 // Process, but it may instead take other actions to initiate cancellation, 241 // such as closing a stdin or stdout pipe or sending a shutdown request on a 242 // network socket. 243 // 244 // If the command exits with a success status after Cancel is 245 // called, and Cancel does not return an error equivalent to 246 // os.ErrProcessDone, then Wait and similar methods will return a non-nil 247 // error: either an error wrapping the one returned by Cancel, 248 // or the error from the Context. 249 // (If the command exits with a non-success status, or Cancel 250 // returns an error that wraps os.ErrProcessDone, Wait and similar methods 251 // continue to return the command's usual exit status.) 252 // 253 // If Cancel is set to nil, nothing will happen immediately when the command's 254 // Context is done, but a nonzero WaitDelay will still take effect. That may 255 // be useful, for example, to work around deadlocks in commands that do not 256 // support shutdown signals but are expected to always finish quickly. 257 // 258 // Cancel will not be called if Start returns a non-nil error. 259 Cancel func() error 260 261 // If WaitDelay is non-zero, it bounds the time spent waiting on two sources 262 // of unexpected delay in Wait: a child process that fails to exit after the 263 // associated Context is canceled, and a child process that exits but leaves 264 // its I/O pipes unclosed. 265 // 266 // The WaitDelay timer starts when either the associated Context is done or a 267 // call to Wait observes that the child process has exited, whichever occurs 268 // first. When the delay has elapsed, the command shuts down the child process 269 // and/or its I/O pipes. 270 // 271 // If the child process has failed to exit — perhaps because it ignored or 272 // failed to receive a shutdown signal from a Cancel function, or because no 273 // Cancel function was set — then it will be terminated using os.Process.Kill. 274 // 275 // Then, if the I/O pipes communicating with the child process are still open, 276 // those pipes are closed in order to unblock any goroutines currently blocked 277 // on Read or Write calls. 278 // 279 // If pipes are closed due to WaitDelay, no Cancel call has occurred, 280 // and the command has otherwise exited with a successful status, Wait and 281 // similar methods will return ErrWaitDelay instead of nil. 282 // 283 // If WaitDelay is zero (the default), I/O pipes will be read until EOF, 284 // which might not occur until orphaned subprocesses of the command have 285 // also closed their descriptors for the pipes. 286 WaitDelay time.Duration 287 288 // childIOFiles holds closers for any of the child process's 289 // stdin, stdout, and/or stderr files that were opened by the Cmd itself 290 // (not supplied by the caller). These should be closed as soon as they 291 // are inherited by the child process. 292 childIOFiles []io.Closer 293 294 // parentIOPipes holds closers for the parent's end of any pipes 295 // connected to the child's stdin, stdout, and/or stderr streams 296 // that were opened by the Cmd itself (not supplied by the caller). 297 // These should be closed after Wait sees the command and copying 298 // goroutines exit, or after WaitDelay has expired. 299 parentIOPipes []io.Closer 300 301 // goroutine holds a set of closures to execute to copy data 302 // to and/or from the command's I/O pipes. 303 goroutine []func() error 304 305 // If goroutineErr is non-nil, it receives the first error from a copying 306 // goroutine once all such goroutines have completed. 307 // goroutineErr is set to nil once its error has been received. 308 goroutineErr <-chan error 309 310 // If ctxResult is non-nil, it receives the result of watchCtx exactly once. 311 ctxResult <-chan ctxResult 312 313 // The stack saved when the Command was created, if GODEBUG contains 314 // execwait=2. Used for debugging leaks. 315 createdByStack []byte 316 317 // For a security release long ago, we created x/sys/execabs, 318 // which manipulated the unexported lookPathErr error field 319 // in this struct. For Go 1.19 we exported the field as Err error, 320 // above, but we have to keep lookPathErr around for use by 321 // old programs building against new toolchains. 322 // The String and Start methods look for an error in lookPathErr 323 // in preference to Err, to preserve the errors that execabs sets. 324 // 325 // In general we don't guarantee misuse of reflect like this, 326 // but the misuse of reflect was by us, the best of various bad 327 // options to fix the security problem, and people depend on 328 // those old copies of execabs continuing to work. 329 // The result is that we have to leave this variable around for the 330 // rest of time, a compatibility scar. 331 // 332 // See https://go.dev/blog/path-security 333 // and https://go.dev/issue/43724 for more context. 334 lookPathErr error 335 } 336 337 // A ctxResult reports the result of watching the Context associated with a 338 // running command (and sending corresponding signals if needed). 339 type ctxResult struct { 340 err error 341 342 // If timer is non-nil, it expires after WaitDelay has elapsed after 343 // the Context is done. 344 // 345 // (If timer is nil, that means that the Context was not done before the 346 // command completed, or no WaitDelay was set, or the WaitDelay already 347 // expired and its effect was already applied.) 348 timer *time.Timer 349 } 350 351 var execwait = godebug.New("#execwait") 352 var execerrdot = godebug.New("execerrdot") 353 354 // Command returns the Cmd struct to execute the named program with 355 // the given arguments. 356 // 357 // It sets only the Path and Args in the returned structure. 358 // 359 // If name contains no path separators, Command uses LookPath to 360 // resolve name to a complete path if possible. Otherwise it uses name 361 // directly as Path. 362 // 363 // The returned Cmd's Args field is constructed from the command name 364 // followed by the elements of arg, so arg should not include the 365 // command name itself. For example, Command("echo", "hello"). 366 // Args[0] is always name, not the possibly resolved Path. 367 // 368 // On Windows, processes receive the whole command line as a single string 369 // and do their own parsing. Command combines and quotes Args into a command 370 // line string with an algorithm compatible with applications using 371 // CommandLineToArgvW (which is the most common way). Notable exceptions are 372 // msiexec.exe and cmd.exe (and thus, all batch files), which have a different 373 // unquoting algorithm. In these or other similar cases, you can do the 374 // quoting yourself and provide the full command line in SysProcAttr.CmdLine, 375 // leaving Args empty. 376 func Command(name string, arg ...string) *Cmd { 377 cmd := &Cmd{ 378 Path: name, 379 Args: append([]string{name}, arg...), 380 } 381 382 if v := execwait.Value(); v != "" { 383 if v == "2" { 384 // Obtain the caller stack. (This is equivalent to runtime/debug.Stack, 385 // copied to avoid importing the whole package.) 386 stack := make([]byte, 1024) 387 for { 388 n := runtime.Stack(stack, false) 389 if n < len(stack) { 390 stack = stack[:n] 391 break 392 } 393 stack = make([]byte, 2*len(stack)) 394 } 395 396 if i := bytes.Index(stack, []byte("\nos/exec.Command(")); i >= 0 { 397 stack = stack[i+1:] 398 } 399 cmd.createdByStack = stack 400 } 401 402 runtime.SetFinalizer(cmd, func(c *Cmd) { 403 if c.Process != nil && c.ProcessState == nil { 404 debugHint := "" 405 if c.createdByStack == nil { 406 debugHint = " (set GODEBUG=execwait=2 to capture stacks for debugging)" 407 } else { 408 os.Stderr.WriteString("GODEBUG=execwait=2 detected a leaked exec.Cmd created by:\n") 409 os.Stderr.Write(c.createdByStack) 410 os.Stderr.WriteString("\n") 411 debugHint = "" 412 } 413 panic("exec: Cmd started a Process but leaked without a call to Wait" + debugHint) 414 } 415 }) 416 } 417 418 if filepath.Base(name) == name { 419 lp, err := LookPath(name) 420 if lp != "" { 421 // Update cmd.Path even if err is non-nil. 422 // If err is ErrDot (especially on Windows), lp may include a resolved 423 // extension (like .exe or .bat) that should be preserved. 424 cmd.Path = lp 425 } 426 if err != nil { 427 cmd.Err = err 428 } 429 } else if runtime.GOOS == "windows" && filepath.IsAbs(name) { 430 // We may need to add a filename extension from PATHEXT 431 // or verify an extension that is already present. 432 // Since the path is absolute, its extension should be unambiguous 433 // and independent of cmd.Dir, and we can go ahead and update cmd.Path to 434 // reflect it. 435 // 436 // Note that we cannot add an extension here for relative paths, because 437 // cmd.Dir may be set after we return from this function and that may cause 438 // the command to resolve to a different extension. 439 lp, err := lookExtensions(name, "") 440 if lp != "" { 441 cmd.Path = lp 442 } 443 if err != nil { 444 cmd.Err = err 445 } 446 } 447 return cmd 448 } 449 450 // CommandContext is like Command but includes a context. 451 // 452 // The provided context is used to interrupt the process 453 // (by calling cmd.Cancel or os.Process.Kill) 454 // if the context becomes done before the command completes on its own. 455 // 456 // CommandContext sets the command's Cancel function to invoke the Kill method 457 // on its Process, and leaves its WaitDelay unset. The caller may change the 458 // cancellation behavior by modifying those fields before starting the command. 459 func CommandContext(ctx context.Context, name string, arg ...string) *Cmd { 460 if ctx == nil { 461 panic("nil Context") 462 } 463 cmd := Command(name, arg...) 464 cmd.ctx = ctx 465 cmd.Cancel = func() error { 466 return cmd.Process.Kill() 467 } 468 return cmd 469 } 470 471 // String returns a human-readable description of c. 472 // It is intended only for debugging. 473 // In particular, it is not suitable for use as input to a shell. 474 // The output of String may vary across Go releases. 475 func (c *Cmd) String() string { 476 if c.Err != nil || c.lookPathErr != nil { 477 // failed to resolve path; report the original requested path (plus args) 478 return strings.Join(c.Args, " ") 479 } 480 // report the exact executable path (plus args) 481 b := new(strings.Builder) 482 b.WriteString(c.Path) 483 for _, a := range c.Args[1:] { 484 b.WriteByte(' ') 485 b.WriteString(a) 486 } 487 return b.String() 488 } 489 490 // interfaceEqual protects against panics from doing equality tests on 491 // two interfaces with non-comparable underlying types. 492 func interfaceEqual(a, b any) bool { 493 defer func() { 494 recover() 495 }() 496 return a == b 497 } 498 499 func (c *Cmd) argv() []string { 500 if len(c.Args) > 0 { 501 return c.Args 502 } 503 return []string{c.Path} 504 } 505 506 func (c *Cmd) childStdin() (*os.File, error) { 507 if c.Stdin == nil { 508 f, err := os.Open(os.DevNull) 509 if err != nil { 510 return nil, err 511 } 512 c.childIOFiles = append(c.childIOFiles, f) 513 return f, nil 514 } 515 516 if f, ok := c.Stdin.(*os.File); ok { 517 return f, nil 518 } 519 520 pr, pw, err := os.Pipe() 521 if err != nil { 522 return nil, err 523 } 524 525 c.childIOFiles = append(c.childIOFiles, pr) 526 c.parentIOPipes = append(c.parentIOPipes, pw) 527 c.goroutine = append(c.goroutine, func() error { 528 _, err := io.Copy(pw, c.Stdin) 529 if skipStdinCopyError(err) { 530 err = nil 531 } 532 if err1 := pw.Close(); err == nil { 533 err = err1 534 } 535 return err 536 }) 537 return pr, nil 538 } 539 540 func (c *Cmd) childStdout() (*os.File, error) { 541 return c.writerDescriptor(c.Stdout) 542 } 543 544 func (c *Cmd) childStderr(childStdout *os.File) (*os.File, error) { 545 if c.Stderr != nil && interfaceEqual(c.Stderr, c.Stdout) { 546 return childStdout, nil 547 } 548 return c.writerDescriptor(c.Stderr) 549 } 550 551 // writerDescriptor returns an os.File to which the child process 552 // can write to send data to w. 553 // 554 // If w is nil, writerDescriptor returns a File that writes to os.DevNull. 555 func (c *Cmd) writerDescriptor(w io.Writer) (*os.File, error) { 556 if w == nil { 557 f, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0) 558 if err != nil { 559 return nil, err 560 } 561 c.childIOFiles = append(c.childIOFiles, f) 562 return f, nil 563 } 564 565 if f, ok := w.(*os.File); ok { 566 return f, nil 567 } 568 569 pr, pw, err := os.Pipe() 570 if err != nil { 571 return nil, err 572 } 573 574 c.childIOFiles = append(c.childIOFiles, pw) 575 c.parentIOPipes = append(c.parentIOPipes, pr) 576 c.goroutine = append(c.goroutine, func() error { 577 _, err := io.Copy(w, pr) 578 pr.Close() // in case io.Copy stopped due to write error 579 return err 580 }) 581 return pw, nil 582 } 583 584 func closeDescriptors(closers []io.Closer) { 585 for _, fd := range closers { 586 fd.Close() 587 } 588 } 589 590 // Run starts the specified command and waits for it to complete. 591 // 592 // The returned error is nil if the command runs, has no problems 593 // copying stdin, stdout, and stderr, and exits with a zero exit 594 // status. 595 // 596 // If the command starts but does not complete successfully, the error is of 597 // type *ExitError. Other error types may be returned for other situations. 598 // 599 // If the calling goroutine has locked the operating system thread 600 // with runtime.LockOSThread and modified any inheritable OS-level 601 // thread state (for example, Linux or Plan 9 name spaces), the new 602 // process will inherit the caller's thread state. 603 func (c *Cmd) Run() error { 604 if err := c.Start(); err != nil { 605 return err 606 } 607 return c.Wait() 608 } 609 610 // Start starts the specified command but does not wait for it to complete. 611 // 612 // If Start returns successfully, the c.Process field will be set. 613 // 614 // After a successful call to Start the Wait method must be called in 615 // order to release associated system resources. 616 func (c *Cmd) Start() error { 617 // Check for doubled Start calls before we defer failure cleanup. If the prior 618 // call to Start succeeded, we don't want to spuriously close its pipes. 619 if c.Process != nil { 620 return errors.New("exec: already started") 621 } 622 623 started := false 624 defer func() { 625 closeDescriptors(c.childIOFiles) 626 c.childIOFiles = nil 627 628 if !started { 629 closeDescriptors(c.parentIOPipes) 630 c.parentIOPipes = nil 631 } 632 }() 633 634 if c.Path == "" && c.Err == nil && c.lookPathErr == nil { 635 c.Err = errors.New("exec: no command") 636 } 637 if c.Err != nil || c.lookPathErr != nil { 638 if c.lookPathErr != nil { 639 return c.lookPathErr 640 } 641 return c.Err 642 } 643 lp := c.Path 644 if runtime.GOOS == "windows" && !filepath.IsAbs(c.Path) { 645 // If c.Path is relative, we had to wait until now 646 // to resolve it in case c.Dir was changed. 647 // (If it is absolute, we already resolved its extension in Command 648 // and shouldn't need to do so again.) 649 // 650 // Unfortunately, we cannot write the result back to c.Path because programs 651 // may assume that they can call Start concurrently with reading the path. 652 // (It is safe and non-racy to do so on Unix platforms, and users might not 653 // test with the race detector on all platforms; 654 // see https://go.dev/issue/62596.) 655 // 656 // So we will pass the fully resolved path to os.StartProcess, but leave 657 // c.Path as is: missing a bit of logging information seems less harmful 658 // than triggering a surprising data race, and if the user really cares 659 // about that bit of logging they can always use LookPath to resolve it. 660 var err error 661 lp, err = lookExtensions(c.Path, c.Dir) 662 if err != nil { 663 return err 664 } 665 } 666 if c.Cancel != nil && c.ctx == nil { 667 return errors.New("exec: command with a non-nil Cancel was not created with CommandContext") 668 } 669 if c.ctx != nil { 670 select { 671 case <-c.ctx.Done(): 672 return c.ctx.Err() 673 default: 674 } 675 } 676 677 childFiles := make([]*os.File, 0, 3+len(c.ExtraFiles)) 678 stdin, err := c.childStdin() 679 if err != nil { 680 return err 681 } 682 childFiles = append(childFiles, stdin) 683 stdout, err := c.childStdout() 684 if err != nil { 685 return err 686 } 687 childFiles = append(childFiles, stdout) 688 stderr, err := c.childStderr(stdout) 689 if err != nil { 690 return err 691 } 692 childFiles = append(childFiles, stderr) 693 childFiles = append(childFiles, c.ExtraFiles...) 694 695 env, err := c.environ() 696 if err != nil { 697 return err 698 } 699 700 c.Process, err = os.StartProcess(lp, c.argv(), &os.ProcAttr{ 701 Dir: c.Dir, 702 Files: childFiles, 703 Env: env, 704 Sys: c.SysProcAttr, 705 }) 706 if err != nil { 707 return err 708 } 709 started = true 710 711 // Don't allocate the goroutineErr channel unless there are goroutines to start. 712 if len(c.goroutine) > 0 { 713 goroutineErr := make(chan error, 1) 714 c.goroutineErr = goroutineErr 715 716 type goroutineStatus struct { 717 running int 718 firstErr error 719 } 720 statusc := make(chan goroutineStatus, 1) 721 statusc <- goroutineStatus{running: len(c.goroutine)} 722 for _, fn := range c.goroutine { 723 go func(fn func() error) { 724 err := fn() 725 726 status := <-statusc 727 if status.firstErr == nil { 728 status.firstErr = err 729 } 730 status.running-- 731 if status.running == 0 { 732 goroutineErr <- status.firstErr 733 } else { 734 statusc <- status 735 } 736 }(fn) 737 } 738 c.goroutine = nil // Allow the goroutines' closures to be GC'd when they complete. 739 } 740 741 // If we have anything to do when the command's Context expires, 742 // start a goroutine to watch for cancellation. 743 // 744 // (Even if the command was created by CommandContext, a helper library may 745 // have explicitly set its Cancel field back to nil, indicating that it should 746 // be allowed to continue running after cancellation after all.) 747 if (c.Cancel != nil || c.WaitDelay != 0) && c.ctx != nil && c.ctx.Done() != nil { 748 resultc := make(chan ctxResult) 749 c.ctxResult = resultc 750 go c.watchCtx(resultc) 751 } 752 753 return nil 754 } 755 756 // watchCtx watches c.ctx until it is able to send a result to resultc. 757 // 758 // If c.ctx is done before a result can be sent, watchCtx calls c.Cancel, 759 // and/or kills cmd.Process it after c.WaitDelay has elapsed. 760 // 761 // watchCtx manipulates c.goroutineErr, so its result must be received before 762 // c.awaitGoroutines is called. 763 func (c *Cmd) watchCtx(resultc chan<- ctxResult) { 764 select { 765 case resultc <- ctxResult{}: 766 return 767 case <-c.ctx.Done(): 768 } 769 770 var err error 771 if c.Cancel != nil { 772 if interruptErr := c.Cancel(); interruptErr == nil { 773 // We appear to have successfully interrupted the command, so any 774 // program behavior from this point may be due to ctx even if the 775 // command exits with code 0. 776 err = c.ctx.Err() 777 } else if errors.Is(interruptErr, os.ErrProcessDone) { 778 // The process already finished: we just didn't notice it yet. 779 // (Perhaps c.Wait hadn't been called, or perhaps it happened to race with 780 // c.ctx being cancelled.) Don't inject a needless error. 781 } else { 782 err = wrappedError{ 783 prefix: "exec: canceling Cmd", 784 err: interruptErr, 785 } 786 } 787 } 788 if c.WaitDelay == 0 { 789 resultc <- ctxResult{err: err} 790 return 791 } 792 793 timer := time.NewTimer(c.WaitDelay) 794 select { 795 case resultc <- ctxResult{err: err, timer: timer}: 796 // c.Process.Wait returned and we've handed the timer off to c.Wait. 797 // It will take care of goroutine shutdown from here. 798 return 799 case <-timer.C: 800 } 801 802 killed := false 803 if killErr := c.Process.Kill(); killErr == nil { 804 // We appear to have killed the process. c.Process.Wait should return a 805 // non-nil error to c.Wait unless the Kill signal races with a successful 806 // exit, and if that does happen we shouldn't report a spurious error, 807 // so don't set err to anything here. 808 killed = true 809 } else if !errors.Is(killErr, os.ErrProcessDone) { 810 err = wrappedError{ 811 prefix: "exec: killing Cmd", 812 err: killErr, 813 } 814 } 815 816 if c.goroutineErr != nil { 817 select { 818 case goroutineErr := <-c.goroutineErr: 819 // Forward goroutineErr only if we don't have reason to believe it was 820 // caused by a call to Cancel or Kill above. 821 if err == nil && !killed { 822 err = goroutineErr 823 } 824 default: 825 // Close the child process's I/O pipes, in case it abandoned some 826 // subprocess that inherited them and is still holding them open 827 // (see https://go.dev/issue/23019). 828 // 829 // We close the goroutine pipes only after we have sent any signals we're 830 // going to send to the process (via Signal or Kill above): if we send 831 // SIGKILL to the process, we would prefer for it to die of SIGKILL, not 832 // SIGPIPE. (However, this may still cause any orphaned subprocesses to 833 // terminate with SIGPIPE.) 834 closeDescriptors(c.parentIOPipes) 835 // Wait for the copying goroutines to finish, but report ErrWaitDelay for 836 // the error: any other error here could result from closing the pipes. 837 _ = <-c.goroutineErr 838 if err == nil { 839 err = ErrWaitDelay 840 } 841 } 842 843 // Since we have already received the only result from c.goroutineErr, 844 // set it to nil to prevent awaitGoroutines from blocking on it. 845 c.goroutineErr = nil 846 } 847 848 resultc <- ctxResult{err: err} 849 } 850 851 // An ExitError reports an unsuccessful exit by a command. 852 type ExitError struct { 853 *os.ProcessState 854 855 // Stderr holds a subset of the standard error output from the 856 // Cmd.Output method if standard error was not otherwise being 857 // collected. 858 // 859 // If the error output is long, Stderr may contain only a prefix 860 // and suffix of the output, with the middle replaced with 861 // text about the number of omitted bytes. 862 // 863 // Stderr is provided for debugging, for inclusion in error messages. 864 // Users with other needs should redirect Cmd.Stderr as needed. 865 Stderr []byte 866 } 867 868 func (e *ExitError) Error() string { 869 return e.ProcessState.String() 870 } 871 872 // Wait waits for the command to exit and waits for any copying to 873 // stdin or copying from stdout or stderr to complete. 874 // 875 // The command must have been started by Start. 876 // 877 // The returned error is nil if the command runs, has no problems 878 // copying stdin, stdout, and stderr, and exits with a zero exit 879 // status. 880 // 881 // If the command fails to run or doesn't complete successfully, the 882 // error is of type *ExitError. Other error types may be 883 // returned for I/O problems. 884 // 885 // If any of c.Stdin, c.Stdout or c.Stderr are not an *os.File, Wait also waits 886 // for the respective I/O loop copying to or from the process to complete. 887 // 888 // Wait releases any resources associated with the Cmd. 889 func (c *Cmd) Wait() error { 890 if c.Process == nil { 891 return errors.New("exec: not started") 892 } 893 if c.ProcessState != nil { 894 return errors.New("exec: Wait was already called") 895 } 896 897 state, err := c.Process.Wait() 898 if err == nil && !state.Success() { 899 err = &ExitError{ProcessState: state} 900 } 901 c.ProcessState = state 902 903 var timer *time.Timer 904 if c.ctxResult != nil { 905 watch := <-c.ctxResult 906 timer = watch.timer 907 // If c.Process.Wait returned an error, prefer that. 908 // Otherwise, report any error from the watchCtx goroutine, 909 // such as a Context cancellation or a WaitDelay overrun. 910 if err == nil && watch.err != nil { 911 err = watch.err 912 } 913 } 914 915 if goroutineErr := c.awaitGoroutines(timer); err == nil { 916 // Report an error from the copying goroutines only if the program otherwise 917 // exited normally on its own. Otherwise, the copying error may be due to the 918 // abnormal termination. 919 err = goroutineErr 920 } 921 closeDescriptors(c.parentIOPipes) 922 c.parentIOPipes = nil 923 924 return err 925 } 926 927 // awaitGoroutines waits for the results of the goroutines copying data to or 928 // from the command's I/O pipes. 929 // 930 // If c.WaitDelay elapses before the goroutines complete, awaitGoroutines 931 // forcibly closes their pipes and returns ErrWaitDelay. 932 // 933 // If timer is non-nil, it must send to timer.C at the end of c.WaitDelay. 934 func (c *Cmd) awaitGoroutines(timer *time.Timer) error { 935 defer func() { 936 if timer != nil { 937 timer.Stop() 938 } 939 c.goroutineErr = nil 940 }() 941 942 if c.goroutineErr == nil { 943 return nil // No running goroutines to await. 944 } 945 946 if timer == nil { 947 if c.WaitDelay == 0 { 948 return <-c.goroutineErr 949 } 950 951 select { 952 case err := <-c.goroutineErr: 953 // Avoid the overhead of starting a timer. 954 return err 955 default: 956 } 957 958 // No existing timer was started: either there is no Context associated with 959 // the command, or c.Process.Wait completed before the Context was done. 960 timer = time.NewTimer(c.WaitDelay) 961 } 962 963 select { 964 case <-timer.C: 965 closeDescriptors(c.parentIOPipes) 966 // Wait for the copying goroutines to finish, but ignore any error 967 // (since it was probably caused by closing the pipes). 968 _ = <-c.goroutineErr 969 return ErrWaitDelay 970 971 case err := <-c.goroutineErr: 972 return err 973 } 974 } 975 976 // Output runs the command and returns its standard output. 977 // Any returned error will usually be of type *ExitError. 978 // If c.Stderr was nil, Output populates ExitError.Stderr. 979 func (c *Cmd) Output() ([]byte, error) { 980 if c.Stdout != nil { 981 return nil, errors.New("exec: Stdout already set") 982 } 983 var stdout bytes.Buffer 984 c.Stdout = &stdout 985 986 captureErr := c.Stderr == nil 987 if captureErr { 988 c.Stderr = &prefixSuffixSaver{N: 32 << 10} 989 } 990 991 err := c.Run() 992 if err != nil && captureErr { 993 if ee, ok := err.(*ExitError); ok { 994 ee.Stderr = c.Stderr.(*prefixSuffixSaver).Bytes() 995 } 996 } 997 return stdout.Bytes(), err 998 } 999 1000 // CombinedOutput runs the command and returns its combined standard 1001 // output and standard error. 1002 func (c *Cmd) CombinedOutput() ([]byte, error) { 1003 if c.Stdout != nil { 1004 return nil, errors.New("exec: Stdout already set") 1005 } 1006 if c.Stderr != nil { 1007 return nil, errors.New("exec: Stderr already set") 1008 } 1009 var b bytes.Buffer 1010 c.Stdout = &b 1011 c.Stderr = &b 1012 err := c.Run() 1013 return b.Bytes(), err 1014 } 1015 1016 // StdinPipe returns a pipe that will be connected to the command's 1017 // standard input when the command starts. 1018 // The pipe will be closed automatically after Wait sees the command exit. 1019 // A caller need only call Close to force the pipe to close sooner. 1020 // For example, if the command being run will not exit until standard input 1021 // is closed, the caller must close the pipe. 1022 func (c *Cmd) StdinPipe() (io.WriteCloser, error) { 1023 if c.Stdin != nil { 1024 return nil, errors.New("exec: Stdin already set") 1025 } 1026 if c.Process != nil { 1027 return nil, errors.New("exec: StdinPipe after process started") 1028 } 1029 pr, pw, err := os.Pipe() 1030 if err != nil { 1031 return nil, err 1032 } 1033 c.Stdin = pr 1034 c.childIOFiles = append(c.childIOFiles, pr) 1035 c.parentIOPipes = append(c.parentIOPipes, pw) 1036 return pw, nil 1037 } 1038 1039 // StdoutPipe returns a pipe that will be connected to the command's 1040 // standard output when the command starts. 1041 // 1042 // Wait will close the pipe after seeing the command exit, so most callers 1043 // need not close the pipe themselves. It is thus incorrect to call Wait 1044 // before all reads from the pipe have completed. 1045 // For the same reason, it is incorrect to call Run when using StdoutPipe. 1046 // See the example for idiomatic usage. 1047 func (c *Cmd) StdoutPipe() (io.ReadCloser, error) { 1048 if c.Stdout != nil { 1049 return nil, errors.New("exec: Stdout already set") 1050 } 1051 if c.Process != nil { 1052 return nil, errors.New("exec: StdoutPipe after process started") 1053 } 1054 pr, pw, err := os.Pipe() 1055 if err != nil { 1056 return nil, err 1057 } 1058 c.Stdout = pw 1059 c.childIOFiles = append(c.childIOFiles, pw) 1060 c.parentIOPipes = append(c.parentIOPipes, pr) 1061 return pr, nil 1062 } 1063 1064 // StderrPipe returns a pipe that will be connected to the command's 1065 // standard error when the command starts. 1066 // 1067 // Wait will close the pipe after seeing the command exit, so most callers 1068 // need not close the pipe themselves. It is thus incorrect to call Wait 1069 // before all reads from the pipe have completed. 1070 // For the same reason, it is incorrect to use Run when using StderrPipe. 1071 // See the StdoutPipe example for idiomatic usage. 1072 func (c *Cmd) StderrPipe() (io.ReadCloser, error) { 1073 if c.Stderr != nil { 1074 return nil, errors.New("exec: Stderr already set") 1075 } 1076 if c.Process != nil { 1077 return nil, errors.New("exec: StderrPipe after process started") 1078 } 1079 pr, pw, err := os.Pipe() 1080 if err != nil { 1081 return nil, err 1082 } 1083 c.Stderr = pw 1084 c.childIOFiles = append(c.childIOFiles, pw) 1085 c.parentIOPipes = append(c.parentIOPipes, pr) 1086 return pr, nil 1087 } 1088 1089 // prefixSuffixSaver is an io.Writer which retains the first N bytes 1090 // and the last N bytes written to it. The Bytes() methods reconstructs 1091 // it with a pretty error message. 1092 type prefixSuffixSaver struct { 1093 N int // max size of prefix or suffix 1094 prefix []byte 1095 suffix []byte // ring buffer once len(suffix) == N 1096 suffixOff int // offset to write into suffix 1097 skipped int64 1098 1099 // TODO(bradfitz): we could keep one large []byte and use part of it for 1100 // the prefix, reserve space for the '... Omitting N bytes ...' message, 1101 // then the ring buffer suffix, and just rearrange the ring buffer 1102 // suffix when Bytes() is called, but it doesn't seem worth it for 1103 // now just for error messages. It's only ~64KB anyway. 1104 } 1105 1106 func (w *prefixSuffixSaver) Write(p []byte) (n int, err error) { 1107 lenp := len(p) 1108 p = w.fill(&w.prefix, p) 1109 1110 // Only keep the last w.N bytes of suffix data. 1111 if overage := len(p) - w.N; overage > 0 { 1112 p = p[overage:] 1113 w.skipped += int64(overage) 1114 } 1115 p = w.fill(&w.suffix, p) 1116 1117 // w.suffix is full now if p is non-empty. Overwrite it in a circle. 1118 for len(p) > 0 { // 0, 1, or 2 iterations. 1119 n := copy(w.suffix[w.suffixOff:], p) 1120 p = p[n:] 1121 w.skipped += int64(n) 1122 w.suffixOff += n 1123 if w.suffixOff == w.N { 1124 w.suffixOff = 0 1125 } 1126 } 1127 return lenp, nil 1128 } 1129 1130 // fill appends up to len(p) bytes of p to *dst, such that *dst does not 1131 // grow larger than w.N. It returns the un-appended suffix of p. 1132 func (w *prefixSuffixSaver) fill(dst *[]byte, p []byte) (pRemain []byte) { 1133 if remain := w.N - len(*dst); remain > 0 { 1134 add := min(len(p), remain) 1135 *dst = append(*dst, p[:add]...) 1136 p = p[add:] 1137 } 1138 return p 1139 } 1140 1141 func (w *prefixSuffixSaver) Bytes() []byte { 1142 if w.suffix == nil { 1143 return w.prefix 1144 } 1145 if w.skipped == 0 { 1146 return append(w.prefix, w.suffix...) 1147 } 1148 var buf bytes.Buffer 1149 buf.Grow(len(w.prefix) + len(w.suffix) + 50) 1150 buf.Write(w.prefix) 1151 buf.WriteString("\n... omitting ") 1152 buf.WriteString(strconv.FormatInt(w.skipped, 10)) 1153 buf.WriteString(" bytes ...\n") 1154 buf.Write(w.suffix[w.suffixOff:]) 1155 buf.Write(w.suffix[:w.suffixOff]) 1156 return buf.Bytes() 1157 } 1158 1159 // environ returns a best-effort copy of the environment in which the command 1160 // would be run as it is currently configured. If an error occurs in computing 1161 // the environment, it is returned alongside the best-effort copy. 1162 func (c *Cmd) environ() ([]string, error) { 1163 var err error 1164 1165 env := c.Env 1166 if env == nil { 1167 env, err = execenv.Default(c.SysProcAttr) 1168 if err != nil { 1169 env = os.Environ() 1170 // Note that the non-nil err is preserved despite env being overridden. 1171 } 1172 1173 if c.Dir != "" { 1174 switch runtime.GOOS { 1175 case "windows", "plan9": 1176 // Windows and Plan 9 do not use the PWD variable, so we don't need to 1177 // keep it accurate. 1178 default: 1179 // On POSIX platforms, PWD represents “an absolute pathname of the 1180 // current working directory.” Since we are changing the working 1181 // directory for the command, we should also update PWD to reflect that. 1182 // 1183 // Unfortunately, we didn't always do that, so (as proposed in 1184 // https://go.dev/issue/50599) to avoid unintended collateral damage we 1185 // only implicitly update PWD when Env is nil. That way, we're much 1186 // less likely to override an intentional change to the variable. 1187 if pwd, absErr := filepath.Abs(c.Dir); absErr == nil { 1188 env = append(env, "PWD="+pwd) 1189 } else if err == nil { 1190 err = absErr 1191 } 1192 } 1193 } 1194 } 1195 1196 env, dedupErr := dedupEnv(env) 1197 if err == nil { 1198 err = dedupErr 1199 } 1200 return addCriticalEnv(env), err 1201 } 1202 1203 // Environ returns a copy of the environment in which the command would be run 1204 // as it is currently configured. 1205 func (c *Cmd) Environ() []string { 1206 // Intentionally ignore errors: environ returns a best-effort environment no matter what. 1207 env, _ := c.environ() 1208 return env 1209 } 1210 1211 // dedupEnv returns a copy of env with any duplicates removed, in favor of 1212 // later values. 1213 // Items not of the normal environment "key=value" form are preserved unchanged. 1214 // Except on Plan 9, items containing NUL characters are removed, and 1215 // an error is returned along with the remaining values. 1216 func dedupEnv(env []string) ([]string, error) { 1217 return dedupEnvCase(runtime.GOOS == "windows", runtime.GOOS == "plan9", env) 1218 } 1219 1220 // dedupEnvCase is dedupEnv with a case option for testing. 1221 // If caseInsensitive is true, the case of keys is ignored. 1222 // If nulOK is false, items containing NUL characters are allowed. 1223 func dedupEnvCase(caseInsensitive, nulOK bool, env []string) ([]string, error) { 1224 // Construct the output in reverse order, to preserve the 1225 // last occurrence of each key. 1226 var err error 1227 out := make([]string, 0, len(env)) 1228 saw := make(map[string]bool, len(env)) 1229 for n := len(env); n > 0; n-- { 1230 kv := env[n-1] 1231 1232 // Reject NUL in environment variables to prevent security issues (#56284); 1233 // except on Plan 9, which uses NUL as os.PathListSeparator (#56544). 1234 if !nulOK && strings.IndexByte(kv, 0) != -1 { 1235 err = errors.New("exec: environment variable contains NUL") 1236 continue 1237 } 1238 1239 i := strings.Index(kv, "=") 1240 if i == 0 { 1241 // We observe in practice keys with a single leading "=" on Windows. 1242 // TODO(#49886): Should we consume only the first leading "=" as part 1243 // of the key, or parse through arbitrarily many of them until a non-"="? 1244 i = strings.Index(kv[1:], "=") + 1 1245 } 1246 if i < 0 { 1247 if kv != "" { 1248 // The entry is not of the form "key=value" (as it is required to be). 1249 // Leave it as-is for now. 1250 // TODO(#52436): should we strip or reject these bogus entries? 1251 out = append(out, kv) 1252 } 1253 continue 1254 } 1255 k := kv[:i] 1256 if caseInsensitive { 1257 k = strings.ToLower(k) 1258 } 1259 if saw[k] { 1260 continue 1261 } 1262 1263 saw[k] = true 1264 out = append(out, kv) 1265 } 1266 1267 // Now reverse the slice to restore the original order. 1268 for i := 0; i < len(out)/2; i++ { 1269 j := len(out) - i - 1 1270 out[i], out[j] = out[j], out[i] 1271 } 1272 1273 return out, err 1274 } 1275 1276 // addCriticalEnv adds any critical environment variables that are required 1277 // (or at least almost always required) on the operating system. 1278 // Currently this is only used for Windows. 1279 func addCriticalEnv(env []string) []string { 1280 if runtime.GOOS != "windows" { 1281 return env 1282 } 1283 for _, kv := range env { 1284 k, _, ok := strings.Cut(kv, "=") 1285 if !ok { 1286 continue 1287 } 1288 if strings.EqualFold(k, "SYSTEMROOT") { 1289 // We already have it. 1290 return env 1291 } 1292 } 1293 return append(env, "SYSTEMROOT="+os.Getenv("SYSTEMROOT")) 1294 } 1295 1296 // ErrDot indicates that a path lookup resolved to an executable 1297 // in the current directory due to ‘.’ being in the path, either 1298 // implicitly or explicitly. See the package documentation for details. 1299 // 1300 // Note that functions in this package do not return ErrDot directly. 1301 // Code should use errors.Is(err, ErrDot), not err == ErrDot, 1302 // to test whether a returned error err is due to this condition. 1303 var ErrDot = errors.New("cannot run executable found relative to current directory") 1304