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