Debian Codegraph @

interp/api.go

raw
1 // Copyright (c) 2017, Daniel Martí <[email protected]>
2 // See LICENSE for licensing information
3
4 // Package interp implements an interpreter to execute shell programs
5 // parsed by the [syntax] package as either [syntax.LangBash]
6 // or [syntax.LangPOSIX], behaving like Bash as a result.
7 //
8 // The interpreter currently aims to behave like a non-interactive shell,
9 // which is how most shells run scripts, and is more useful to machines.
10 // In the future, it may gain an option to behave like an interactive shell.
11 package interp
12
13 import (
14 "context"
15 "errors"
16 "fmt"
17 "io"
18 "io/fs"
19 "maps"
20 mathrand "math/rand/v2"
21 "os"
22 "path/filepath"
23 "runtime"
24 "slices"
25 "strconv"
26 "time"
27
28 "mvdan.cc/sh/v3/expand"
29 "mvdan.cc/sh/v3/syntax"
30 )
31
32 // A Runner interprets shell programs. It can be reused, but it is not safe for
33 // concurrent use. Use [New] to build a new Runner.
34 //
35 // Note that writes to Stdout and Stderr may be concurrent if background
36 // commands are used. If you plan on using an [io.Writer] implementation that
37 // isn't safe for concurrent use, consider a workaround like hiding writes
38 // behind a mutex.
39 //
40 // Runner's exported fields are meant to be configured via [RunnerOption];
41 // once a Runner has been created, the fields should be treated as read-only.
42 type Runner struct {
43 // Env specifies the initial environment for the interpreter, which must
44 // not be nil. It can only be set via [Env].
45 //
46 // If it includes a TMPDIR variable describing an absolute directory,
47 // it is used as the directory in which to create temporary files needed
48 // for the interpreter's use, such as named pipes for process substitutions.
49 // Otherwise, [os.TempDir] is used.
50 Env expand.Environ
51
52 // writeEnv overlays [Runner.Env] so that we can write environment variables
53 // as an overlay.
54 writeEnv expand.WriteEnviron
55
56 // Dir specifies the working directory of the command, which must be an
57 // absolute path. It can only be set via [Dir].
58 Dir string
59
60 // tempDir is either $TMPDIR from [Runner.Env], or [os.TempDir].
61 tempDir string
62
63 // Params are the current shell parameters, e.g. from running a shell
64 // file or calling a function. Accessible via the $@/$* family of vars.
65 // It can only be set via [Params].
66 Params []string
67
68 // Separate maps - note that bash allows a name to be both a var and a
69 // func simultaneously.
70 // Vars is mostly superseded by Env at this point.
71 // TODO(v4): remove these
72
73 Vars map[string]expand.Variable
74 Funcs map[string]*syntax.Stmt
75
76 alias map[string]alias
77
78 // callHandler is a function allowing to replace a simple command's
79 // arguments. It may be nil.
80 callHandler CallHandlerFunc
81
82 // execHandler is responsible for executing programs. It must not be nil.
83 execHandler ExecHandlerFunc
84
85 // execMiddlewares grows with calls to [ExecHandlers],
86 // and is used to construct execHandler when Reset is first called.
87 // The slice is needed to preserve the relative order of middlewares.
88 execMiddlewares []func(ExecHandlerFunc) ExecHandlerFunc
89
90 // openHandler is a function responsible for opening files. It must not be nil.
91 openHandler OpenHandlerFunc
92
93 // readDirHandler is a function responsible for reading directories during
94 // glob expansion. It must be non-nil.
95 readDirHandler ReadDirHandlerFunc2
96
97 // statHandler is a function responsible for getting file stat. It must be non-nil.
98 statHandler StatHandlerFunc
99
100 // accessHandler is a function responsible for checking file access. It must be non-nil.
101 accessHandler AccessHandlerFunc
102
103 stdin stdinFile // e.g. the read end of a pipe
104 stdout io.Writer
105 stderr io.Writer
106
107 ecfg *expand.Config
108 ectx context.Context // just so that Runner.Subshell can use it again
109
110 // didReset remembers whether the runner has ever been reset. This is
111 // used so that Reset is automatically called when running any program
112 // or node for the first time on a Runner.
113 didReset bool
114
115 usedNew bool
116
117 filename string // only if Node was a File
118
119 // rand is the pseudo-random number generator behind the RANDOM variable,
120 // only set once RANDOM has been assigned to in order to seed it.
121 rand *mathrand.Rand
122
123 // >0 to break or continue out of N enclosing loops
124 breakEnclosing, contnEnclosing int
125
126 inLoop bool
127 inFunc bool
128 inSource bool
129 handlingTrap bool // whether we're currently in a trap callback
130
131 // track if a sourced script set positional parameters
132 sourceSetParams bool
133
134 // noErrExit prevents failing commands from triggering [optErrExit],
135 // such as the condition in a [syntax.IfClause].
136 noErrExit bool
137
138 // The current and last exit statuses. They can only be different if
139 // the interpreter is in the middle of running a statement. In that
140 // scenario, 'exit' is the status for the current statement being run,
141 // and 'lastExit' corresponds to the previous statement that was run.
142 exit exitStatus
143 lastExit exitStatus
144
145 lastExpandExit exitStatus // used to surface exit statuses while expanding fields
146
147 // bgProcs holds all background shells spawned by this runner.
148 // Their PIDs are 1-indexed, from 1 to len(bgProcs), with a "g" prefix
149 // to distinguish them from real PIDs on the host operating system.
150 //
151 // Note that each shell only tracks its direct children;
152 // subshells do not share nor inherit the background PIDs they can wait for.
153 bgProcs []bgProc
154
155 opts runnerOpts
156
157 origDir string
158 origParams []string
159 origOpts runnerOpts
160 origStdin stdinFile
161 origStdout io.Writer
162 origStderr io.Writer
163
164 // Most scripts don't use pushd/popd, so make space for the initial PWD
165 // without requiring an extra allocation.
166 dirStack []string
167 dirBootstrap [1]string
168
169 optState getopts
170
171 // keepRedirs is set by "exec" so that its statement's redirections
172 // apply to the current shell, and not just the command.
173 // It is consumed by the enclosing statement once it finishes.
174 keepRedirs bool
175
176 // Fake signal callbacks
177 callbackErr string
178 callbackExit string
179 }
180
181 // exitStatus holds the state of the shell after running one command.
182 // Beyond the exit status code, it also holds whether the shell should return or exit,
183 // as well as any Go error values that should be given back to the user.
184 //
185 // TODO(v4): consider replacing ExitStatus with a struct like this,
186 // so that an [ExecHandlerFunc] can e.g. mimic `exit 0` or fatal errors
187 // with specific exit codes.
188 type exitStatus struct {
189 // code is the exit status code.
190 // When code is zero, err must be nil.
191 code uint8
192
193 // TODO: consider an enum, as only one of these should be set at a time
194 returning bool // whether the current function `return`ed
195 exiting bool // whether the current shell is exiting
196 fatalExit bool // whether the current shell is exiting due to a fatal error; err below must not be nil
197
198 // err holds the error information for a non-zero exit status code or fatal error.
199 // Used so that running a single statement with a custom handler
200 // which returns a non-fatal Go error, such as a Go error wrapping [NewExitStatus],
201 // can be returned by [Runner.Run] without being lost entirely.
202 err error
203 }
204
205 // clear sets the exit status code and error to zero, as long as the exit status
206 // was not set by `return`, `exit`, or a fatal error.
207 func (e *exitStatus) clear() {
208 if e.returning || e.exiting || e.fatalExit {
209 return
210 }
211 e.code = 0
212 e.err = nil
213 }
214
215 func (e *exitStatus) ok() bool { return e.code == 0 }
216
217 // oneIf sets the exit status code to 1 if b is true.
218 // Note that it assumes the exit status hasn't been set yet,
219 // meaning that [exitStatus.code] and [exitStatus.err] are zero values.
220 func (e *exitStatus) oneIf(b bool) {
221 if b {
222 e.code = 1
223 }
224 }
225
226 func (e *exitStatus) fatal(err error) {
227 if e.fatalExit || err == nil {
228 return
229 }
230 e.exiting = true
231 e.fatalExit = true
232 e.err = err
233 if e.code == 0 {
234 e.code = 1
235 }
236 }
237
238 func (e *exitStatus) fromHandlerError(err error) {
239 if err == nil {
240 return
241 }
242 if exit, ok := errors.AsType[errBuiltinExitStatus](err); ok {
243 *e = exitStatus(exit)
244 } else if es, ok := errors.AsType[ExitStatus](err); ok {
245 e.err = err
246 e.code = uint8(es)
247 } else {
248 e.fatal(err) // handler's custom fatal error
249 }
250 }
251
252 type bgProc struct {
253 // closed when the background process finishes,
254 // after which point the result fields below are set.
255 done chan struct{}
256
257 exit *exitStatus
258 }
259
260 type alias struct {
261 args []*syntax.Word
262 blank bool
263 }
264
265 // New creates a new Runner, applying a number of options. If applying any of
266 // the options results in an error, it is returned.
267 //
268 // Any unset options fall back to their defaults. For example, not supplying the
269 // environment falls back to the process's environment, and not supplying the
270 // standard output writer means that the output will be discarded.
271 func New(opts ...RunnerOption) (*Runner, error) {
272 r := &Runner{
273 usedNew: true,
274 openHandler: DefaultOpenHandler(),
275 readDirHandler: DefaultReadDirHandler2(),
276 statHandler: DefaultStatHandler(),
277 accessHandler: DefaultAccessHandler(),
278 }
279 r.dirStack = r.dirBootstrap[:0]
280 // turn "on" the default Bash options
281 for i, opt := range bashOptsTable {
282 r.opts[len(posixOptsTable)+i] = opt.defaultState
283 }
284
285 for _, opt := range opts {
286 if err := opt(r); err != nil {
287 return nil, err
288 }
289 }
290
291 // Set the default fallbacks, if necessary.
292 if r.Env == nil {
293 Env(nil)(r)
294 }
295 if r.Dir == "" {
296 if err := Dir("")(r); err != nil {
297 return nil, err
298 }
299 }
300 if r.stdout == nil || r.stderr == nil {
301 StdIO(r.stdin, r.stdout, r.stderr)(r)
302 }
303 return r, nil
304 }
305
306 // RunnerOption can be passed to [New] to alter a [Runner]'s behaviour.
307 // It can also be applied directly on an existing Runner,
308 // such as interp.Params("-e")(runner) or interp.StdIO(nil, w, w)(runner).
309 //
310 // Note that [Env] and [Dir] only take effect the next time that the runner is
311 // reset, as [Runner.Reset] derives state from them, such as the variables and
312 // the value of PWD. Since running a node only resets a runner the first time
313 // around, applying either option after a run requires an explicit reset.
314 type RunnerOption func(*Runner) error
315
316 // TODO(v4): consider making [Env] and [Dir] fail when applied after a reset,
317 // rather than being silently held back until the next one.
318
319 // Env sets the interpreter's environment. If nil, a copy of the current
320 // process's environment is used.
321 func Env(env expand.Environ) RunnerOption {
322 return func(r *Runner) error {
323 if env == nil {
324 env = expand.ListEnviron(os.Environ()...)
325 }
326 r.Env = env
327 return nil
328 }
329 }
330
331 // Dir sets the interpreter's working directory. If empty, the process's current
332 // directory is used.
333 func Dir(path string) RunnerOption {
334 return func(r *Runner) error {
335 if path == "" {
336 path, err := os.Getwd()
337 if err != nil {
338 if runtime.GOOS == "js" {
339 // js/wasm has no working directory; virtual
340 // filesystems set Runner.Dir themselves
341 r.Dir = "/"
342 return nil
343 }
344 return fmt.Errorf("could not get current dir: %w", err)
345 }
346 r.Dir = path
347 return nil
348 }
349 path, err := filepath.Abs(path)
350 if err != nil {
351 return fmt.Errorf("could not get absolute dir: %w", err)
352 }
353 info, err := os.Stat(path)
354 if err != nil {
355 return fmt.Errorf("could not stat: %w", err)
356 }
357 if !info.IsDir() {
358 return fmt.Errorf("%s is not a directory", path)
359 }
360 r.Dir = path
361 return nil
362 }
363 }
364
365 // Interactive configures the interpreter to behave like an interactive shell,
366 // akin to Bash. Currently, this only enables the expansion of aliases,
367 // but later on it should also change other behavior.
368 func Interactive(enabled bool) RunnerOption {
369 return func(r *Runner) error {
370 r.opts[optExpandAliases] = enabled
371 return nil
372 }
373 }
374
375 // TODO(v4): split the "set" options into [PosixOpts], mirroring [BashOpts],
376 // leaving Params for the positional parameters alone. Accepting both means that
377 // Params with user-supplied arguments can set options by accident.
378
379 // Params populates the shell options and parameters. For example, Params("-e",
380 // "--", "foo") will set the "-e" option and the parameters ["foo"], and
381 // Params("+e") will unset the "-e" option and leave the parameters untouched.
382 //
383 // This is similar to what the interpreter's "set" builtin does.
384 // See [BashOpts] for the Bash options which "set" cannot change.
385 func Params(args ...string) RunnerOption {
386 return func(r *Runner) error {
387 fp := flagParser{remaining: args}
388 for fp.more() {
389 flag := fp.flag()
390 if flag == "-" || flag == "+" {
391 if flag == "-" {
392 // Bash turns off the -x and -v options; note that
393 // we don't support the -v option at all.
394 r.opts[optXTrace] = false
395 }
396 if args := fp.args(); len(args) > 0 {
397 r.Params = args
398 }
399 return nil
400 }
401 enable := flag[0] == '-'
402 if flag[1] != 'o' {
403 opt := r.posixOptByFlag(flag[1])
404 if opt == nil {
405 return fmt.Errorf("invalid option: %q", flag)
406 }
407 *opt = enable
408 continue
409 }
410 value := fp.value()
411 if value == "" && enable {
412 for i, opt := range &posixOptsTable {
413 r.printOptLine(opt.name, r.opts[i], true)
414 }
415 continue
416 }
417 if value == "" && !enable {
418 for i, opt := range &posixOptsTable {
419 setFlag := "+o"
420 if r.opts[i] {
421 setFlag = "-o"
422 }
423 r.outf("set %s %s\n", setFlag, opt.name)
424 }
425 continue
426 }
427 opt := r.posixOptByName(value)
428 if opt == nil {
429 return fmt.Errorf("invalid option: %q", value)
430 }
431 *opt = enable
432 }
433 if args := fp.args(); args != nil {
434 // If "--" wasn't given and there were zero arguments,
435 // we don't want to override the current parameters.
436 r.Params = args
437
438 // Record whether a sourced script sets the parameters.
439 if r.inSource {
440 r.sourceSetParams = true
441 }
442 }
443 return nil
444 }
445 }
446
447 // BashOpts sets or unsets Bash shell options. For example,
448 // BashOpts("-s", "extglob", "globstar") sets both the "extglob" and "globstar"
449 // options, and BashOpts("-u", "extglob") unsets "extglob" alone.
450 //
451 // Just like the builtin, "-o" restricts the names to the POSIX options,
452 // which [Params] can set as well.
453 //
454 // This is similar to what the interpreter's "shopt" builtin does, except that
455 // no arguments is a no-op rather than printing all options.
456 func BashOpts(args ...string) RunnerOption {
457 return func(r *Runner) error {
458 mode := ""
459 posixOpts := false
460 fp := flagParser{remaining: args}
461 for fp.more() {
462 switch flag := fp.flag(); flag {
463 case "-s", "-u":
464 mode = flag
465 case "-o":
466 posixOpts = true
467 default:
468 return fmt.Errorf("invalid option: %q", flag)
469 }
470 }
471 names := fp.args()
472 if len(names) > 0 && mode == "" {
473 return fmt.Errorf("either -s or -u must be given to set or unset options")
474 }
475 for _, name := range names {
476 opt, supported := (*bool)(nil), true
477 if posixOpts {
478 opt = r.posixOptByName(name)
479 } else {
480 opt, supported = r.bashOptByName(name)
481 }
482 if opt == nil {
483 return fmt.Errorf("invalid option name: %q", name)
484 }
485 if !supported {
486 return fmt.Errorf("unsupported option: %q", name)
487 }
488 *opt = mode == "-s"
489 }
490 if r.didReset {
491 // Some options affect expansion; before the first reset,
492 // the reset itself takes care of this.
493 r.updateExpandOpts()
494 }
495 return nil
496 }
497 }
498
499 // CallHandler sets the call handler. See [CallHandlerFunc] for more info.
500 func CallHandler(f CallHandlerFunc) RunnerOption {
501 return func(r *Runner) error {
502 r.callHandler = f
503 return nil
504 }
505 }
506
507 // ExecHandler sets one command execution handler,
508 // which replaces [DefaultExecHandler](2 * time.Second).
509 //
510 // Deprecated: use [ExecHandlers] instead, which allows chaining handlers more easily
511 // like middleware functions.
512 func ExecHandler(f ExecHandlerFunc) RunnerOption {
513 return func(r *Runner) error {
514 r.execHandler = f
515 return nil
516 }
517 }
518
519 // ExecHandlers appends middlewares to handle command execution.
520 // The middlewares are chained from first to last, and the first is called by the runner.
521 // Each middleware is expected to call the "next" middleware at most once.
522 //
523 // For example, a middleware may implement only some commands.
524 // For those commands, it can run its logic and avoid calling "next".
525 // For any other commands, it can call "next" with the original parameters.
526 //
527 // Another common example is a middleware which always calls "next",
528 // but runs custom logic either before or after that call.
529 // For instance, a middleware could change the arguments to the "next" call,
530 // or it could print log lines before or after the call to "next".
531 //
532 // The last exec handler is always [DefaultExecHandler](2 * time.Second).
533 func ExecHandlers(middlewares ...func(next ExecHandlerFunc) ExecHandlerFunc) RunnerOption {
534 return func(r *Runner) error {
535 r.execMiddlewares = append(r.execMiddlewares, middlewares...)
536 return nil
537 }
538 }
539
540 // TODO: consider porting the middleware API in [ExecHandlers] to [OpenHandler],
541 // [ReadDirHandler2], and [StatHandler].
542
543 // TODO(v4): now that [ExecHandlers] allows calling a next handler with changed
544 // arguments, one of the two advantages of [CallHandler] is gone. The other is the
545 // ability to work with builtins; if we make [ExecHandlers] work with builtins, we
546 // could join both APIs.
547
548 // OpenHandler sets file open handler. See [OpenHandlerFunc] for more info.
549 func OpenHandler(f OpenHandlerFunc) RunnerOption {
550 return func(r *Runner) error {
551 r.openHandler = f
552 return nil
553 }
554 }
555
556 // ReadDirHandler sets the read directory handler. See [ReadDirHandlerFunc] for more info.
557 //
558 // Deprecated: use [ReadDirHandler2].
559 func ReadDirHandler(f ReadDirHandlerFunc) RunnerOption {
560 return func(r *Runner) error {
561 r.readDirHandler = func(ctx context.Context, path string) ([]fs.DirEntry, error) {
562 infos, err := f(ctx, path)
563 if err != nil {
564 return nil, err
565 }
566 entries := make([]fs.DirEntry, len(infos))
567 for i, info := range infos {
568 entries[i] = fs.FileInfoToDirEntry(info)
569 }
570 return entries, nil
571 }
572 return nil
573 }
574 }
575
576 // ReadDirHandler2 sets the read directory handler. See [ReadDirHandlerFunc2] for more info.
577 func ReadDirHandler2(f ReadDirHandlerFunc2) RunnerOption {
578 return func(r *Runner) error {
579 r.readDirHandler = f
580 return nil
581 }
582 }
583
584 // StatHandler sets the stat handler. See [StatHandlerFunc] for more info.
585 func StatHandler(f StatHandlerFunc) RunnerOption {
586 return func(r *Runner) error {
587 r.statHandler = f
588 return nil
589 }
590 }
591
592 // AccessHandler sets the file access handler. See [AccessHandlerFunc] for more info.
593 func AccessHandler(f AccessHandlerFunc) RunnerOption {
594 return func(r *Runner) error {
595 r.accessHandler = f
596 return nil
597 }
598 }
599
600 // StdIO configures an interpreter's standard input, standard output, and
601 // standard error. If out or err are nil, they default to a writer that discards
602 // the output.
603 //
604 // Note that providing a non-nil standard input other than [*os.File] will require
605 // an [os.Pipe] and spawning a goroutine to copy into it,
606 // as an [os.File] is the only way to share a reader with subprocesses.
607 // This may cause the interpreter to consume the entire reader.
608 // See [os/exec.Cmd.Stdin].
609 //
610 // When providing an [*os.File] as standard input, consider using an [os.Pipe]
611 // as it has the best chance to support cancellable reads via [os.File.SetReadDeadline],
612 // so that cancelling the runner's context can stop a blocked standard input read.
613 //
614 // On js/wasm, where there are no subprocesses nor OS pipes, any reader is used
615 // directly, and read deadlines are not supported: cancelling the runner's
616 // context cannot stop a blocked standard input read.
617 func StdIO(in io.Reader, out, err io.Writer) RunnerOption {
618 return func(r *Runner) error {
619 stdin, _err := newStdinFile(in)
620 if _err != nil {
621 return _err
622 }
623 r.stdin = stdin
624 if out == nil {
625 out = io.Discard
626 }
627 r.stdout = out
628 if err == nil {
629 err = io.Discard
630 }
631 r.stderr = err
632 return nil
633 }
634 }
635
636 func (r *Runner) posixOptByName(name string) *bool {
637 for i, opt := range &posixOptsTable {
638 if opt.name == name {
639 return &r.opts[i]
640 }
641 }
642 return nil
643 }
644
645 // posixOptFlags returns the one-character flags of the enabled POSIX options,
646 // as held by the "$-" special parameter.
647 func (r *Runner) posixOptFlags() string {
648 // Note that some options, such as pipefail, have no one-character flag.
649 flags := make([]byte, 0, len(posixOptsTable))
650 for i, opt := range &posixOptsTable {
651 if opt.flag != ' ' && r.opts[i] {
652 flags = append(flags, opt.flag)
653 }
654 }
655 slices.Sort(flags) // posixOptsTable is sorted by name rather than by flag
656 return string(flags)
657 }
658
659 func (r *Runner) posixOptByFlag(flag byte) *bool {
660 for i, opt := range &posixOptsTable {
661 if opt.flag == flag {
662 return &r.opts[i]
663 }
664 }
665 return nil
666 }
667
668 func (r *Runner) bashOptByName(name string) (status *bool, supported bool) {
669 for i, opt := range bashOptsTable {
670 if opt.name == name {
671 index := len(posixOptsTable) + i
672 return &r.opts[index], opt.supported
673 }
674 }
675 return nil, false
676 }
677
678 // runnerOpts contains all POSIX Shell and Bash options as one contiguous table.
679 type runnerOpts [len(posixOptsTable) + len(bashOptsTable)]bool
680
681 type posixOpt struct {
682 flag byte // one-character flag form for this option; a space if none exists
683 name string // full name of the option
684 }
685
686 type bashOpt struct {
687 name string
688 defaultState bool // Bash's default value for this option
689 supported bool // whether we support the option's non-default state
690 }
691
692 var posixOptsTable = [...]posixOpt{
693 // sorted alphabetically by name
694 {'a', "allexport"},
695 {'e', "errexit"},
696 {'n', "noexec"},
697 {'f', "noglob"},
698 {'u', "nounset"},
699 {'x', "xtrace"},
700 {' ', "pipefail"},
701 }
702
703 var bashOptsTable = [...]bashOpt{
704 // supported options, sorted alphabetically by name
705 {
706 name: "dotglob",
707 defaultState: false,
708 supported: true,
709 },
710 {
711 name: "expand_aliases",
712 defaultState: false,
713 supported: true,
714 },
715 {
716 name: "extglob",
717 defaultState: false,
718 supported: true,
719 },
720 {
721 name: "globstar",
722 defaultState: false,
723 supported: true,
724 },
725 {
726 name: "nocaseglob",
727 defaultState: false,
728 supported: true,
729 },
730 {
731 name: "nullglob",
732 defaultState: false,
733 supported: true,
734 },
735 // unsupported options, sorted alphabetically by name
736 {name: "assoc_expand_once"},
737 {name: "autocd"},
738 {name: "cdable_vars"},
739 {name: "cdspell"},
740 {name: "checkhash"},
741 {name: "checkjobs"},
742 {
743 name: "checkwinsize",
744 defaultState: true,
745 },
746 {
747 name: "cmdhist",
748 defaultState: true,
749 },
750 {name: "compat31"},
751 {name: "compat32"},
752 {name: "compat40"},
753 {name: "compat41"},
754 {name: "compat42"},
755 {name: "compat43"},
756 {name: "compat44"},
757 {
758 name: "complete_fullquote",
759 defaultState: true,
760 },
761 {name: "direxpand"},
762 {name: "dirspell"},
763 {name: "execfail"},
764 {name: "extdebug"},
765 {
766 name: "extquote",
767 defaultState: true,
768 },
769 {name: "failglob"},
770 {
771 name: "force_fignore",
772 defaultState: true,
773 },
774 {name: "globasciiranges"},
775 {name: "gnu_errfmt"},
776 {name: "histappend"},
777 {name: "histreedit"},
778 {name: "histverify"},
779 {
780 name: "hostcomplete",
781 defaultState: true,
782 },
783 {name: "huponexit"},
784 {
785 name: "inherit_errexit",
786 defaultState: true,
787 },
788 {
789 name: "interactive_comments",
790 defaultState: true,
791 },
792 {name: "lastpipe"},
793 {name: "lithist"},
794 {name: "localvar_inherit"},
795 {name: "localvar_unset"},
796 {name: "login_shell"},
797 {name: "mailwarn"},
798 {name: "no_empty_cmd_completion"},
799 {name: "nocasematch"},
800 {
801 name: "progcomp",
802 defaultState: true,
803 },
804 {name: "progcomp_alias"},
805 {
806 name: "promptvars",
807 defaultState: true,
808 },
809 {name: "restricted_shell"},
810 {name: "shift_verbose"},
811 {
812 name: "sourcepath",
813 defaultState: true,
814 },
815 {name: "xpg_echo"},
816 }
817
818 // To access the shell options arrays without a linear search when we
819 // know which option we're after at compile time. First come the shell options,
820 // then the bash options.
821 const (
822 // These correspond to indexes in [shellOptsTable]
823 optAllExport = iota
824 optErrExit
825 optNoExec
826 optNoGlob
827 optNoUnset
828 optXTrace
829 optPipeFail
830
831 // These correspond to indexes (offset by the above seven items) of
832 // supported options in [bashOptsTable]
833 optDotGlob
834 optExpandAliases
835 optExtGlob
836 optGlobStar
837 optNoCaseGlob
838 optNullGlob
839 )
840
841 // Reset returns a runner to its initial state, right before the first call to
842 // Run or Reset.
843 //
844 // Typically, this function only needs to be called if a runner is reused to run
845 // multiple programs non-incrementally. Not calling Reset between each run will
846 // mean that the shell state will be kept, including variables, options, and the
847 // current directory.
848 func (r *Runner) Reset() {
849 if !r.usedNew {
850 panic("use interp.New to construct a Runner")
851 }
852 if !r.didReset {
853 r.origDir = r.Dir
854 r.origParams = r.Params
855 r.origOpts = r.opts
856 r.origStdin = r.stdin
857 r.origStdout = r.stdout
858 r.origStderr = r.stderr
859
860 if r.execHandler != nil && len(r.execMiddlewares) > 0 {
861 panic("interp.ExecHandler should be replaced with interp.ExecHandlers, not mixed")
862 }
863 if r.execHandler == nil {
864 r.execHandler = DefaultExecHandler(2 * time.Second)
865 }
866 // Middlewares are chained from first to last, and each can call the
867 // next in the chain, so we need to construct the chain backwards.
868 for _, mw := range slices.Backward(r.execMiddlewares) {
869 r.execHandler = mw(r.execHandler)
870 }
871 // Fill tempDir; only need to do this once given that Env will not change.
872 if dir := r.Env.Get("TMPDIR").String(); filepath.IsAbs(dir) {
873 r.tempDir = dir
874 } else {
875 r.tempDir = os.TempDir()
876 }
877 // Clean it as we will later do a string prefix match.
878 r.tempDir = filepath.Clean(r.tempDir)
879 }
880 // reset the internal state
881 *r = Runner{
882 Env: r.Env,
883 tempDir: r.tempDir,
884 callHandler: r.callHandler,
885 execHandler: r.execHandler,
886 openHandler: r.openHandler,
887 readDirHandler: r.readDirHandler,
888 statHandler: r.statHandler,
889 accessHandler: r.accessHandler,
890
891 // These can be set by functions like [Dir] or [Params], but
892 // builtins can overwrite them; reset the fields to whatever the
893 // constructor set up.
894 Dir: r.origDir,
895 Params: r.origParams,
896 opts: r.origOpts,
897 stdin: r.origStdin,
898 stdout: r.origStdout,
899 stderr: r.origStderr,
900
901 origDir: r.origDir,
902 origParams: r.origParams,
903 origOpts: r.origOpts,
904 origStdin: r.origStdin,
905 origStdout: r.origStdout,
906 origStderr: r.origStderr,
907
908 // emptied below, to reuse the space
909 Vars: r.Vars,
910
911 dirStack: r.dirStack[:0],
912 usedNew: r.usedNew,
913 }
914 // Ensure we stop referencing any pointers before we reuse bgProcs.
915 clear(r.bgProcs)
916 r.bgProcs = r.bgProcs[:0]
917
918 if r.Vars == nil {
919 r.Vars = make(map[string]expand.Variable)
920 } else {
921 clear(r.Vars)
922 }
923 // TODO(v4): Use the supplied Env directly if it implements enough methods.
924 r.writeEnv = &overlayEnviron{parent: r.Env}
925 if !r.writeEnv.Get("HOME").IsSet() {
926 home, _ := os.UserHomeDir()
927 r.setVarString("HOME", home)
928 }
929 if !r.writeEnv.Get("UID").IsSet() {
930 r.setVar("UID", expand.Variable{
931 Set: true,
932 Kind: expand.String,
933 ReadOnly: true,
934 Str: strconv.Itoa(os.Getuid()),
935 })
936 }
937 if !r.writeEnv.Get("EUID").IsSet() {
938 r.setVar("EUID", expand.Variable{
939 Set: true,
940 Kind: expand.String,
941 ReadOnly: true,
942 Str: strconv.Itoa(os.Geteuid()),
943 })
944 }
945 if !r.writeEnv.Get("GID").IsSet() {
946 r.setVar("GID", expand.Variable{
947 Set: true,
948 Kind: expand.String,
949 ReadOnly: true,
950 Str: strconv.Itoa(os.Getgid()),
951 })
952 }
953 r.setVarString("PWD", r.Dir)
954 r.setVarString("IFS", " \t\n")
955 r.setVarString("OPTIND", "1")
956
957 r.dirStack = append(r.dirStack, r.Dir)
958
959 r.didReset = true
960 }
961
962 // ExitStatus is a non-zero status code resulting from running a shell node.
963 type ExitStatus uint8
964
965 func (s ExitStatus) Error() string { return fmt.Sprintf("exit status %d", s) }
966
967 // NewExitStatus creates an error which contains the specified exit status code.
968 //
969 // Deprecated: use [ExitStatus] directly.
970 //
971 //go:fix inline
972 func NewExitStatus(status uint8) error {
973 return ExitStatus(status)
974 }
975
976 // IsExitStatus checks whether error contains an exit status and returns it.
977 //
978 // Deprecated: use [errors.As] with [ExitStatus] directly.
979 //
980 //go:fix inline
981 func IsExitStatus(err error) (status uint8, ok bool) {
982 if es, ok := errors.AsType[ExitStatus](err); ok {
983 return uint8(es), true
984 }
985 return 0, false
986 }
987
988 // Run interprets a node, which can be a [*File], [*Stmt], or [Command]. If a non-nil
989 // error is returned, it will typically contain a command's exit status, which
990 // can be retrieved with [IsExitStatus].
991 //
992 // Run can be called multiple times synchronously to interpret programs
993 // incrementally. To reuse a [Runner] without keeping the internal shell state,
994 // call Reset.
995 //
996 // Calling Run on an entire [*File] implies an exit, meaning that an exit trap may
997 // run.
998 func (r *Runner) Run(ctx context.Context, node syntax.Node) error {
999 if !r.didReset {
1000 r.Reset()
1001 }
1002 r.fillExpandConfig(ctx)
1003 r.exit = exitStatus{}
1004 r.filename = ""
1005 switch node := node.(type) {
1006 case *syntax.File:
1007 r.filename = node.Name
1008 r.stmts(ctx, node.Stmts)
1009 case *syntax.Stmt:
1010 r.stmt(ctx, node)
1011 case syntax.Command:
1012 r.cmd(ctx, node)
1013 default:
1014 return fmt.Errorf("node can only be File, Stmt, or Command: %T", node)
1015 }
1016 // A bare Command bypasses stmt, which normally updates lastExit.
1017 r.lastExit = r.exit
1018 // Running an entire file implies an exit; a statement or command
1019 // only exits the shell via the exit builtin, errexit, and so on.
1020 if _, ok := node.(*syntax.File); ok || r.exit.exiting {
1021 r.trapCallback(ctx, r.callbackExit, "exit")
1022 }
1023 maps.Insert(r.Vars, r.writeEnv.Each)
1024 // Return the first of: a fatal error, a non-fatal handler error, or the exit code.
1025 if err := r.exit.err; err != nil {
1026 if r.exit.code == 0 {
1027 // This should never happen; too much code relies on checking [exitStatus.code]
1028 // to see if the last command succeeded or failed. [exitStatus.err] should only be
1029 // additional information, so fail loudly if the invariant is broken.
1030 panic("ended up with a non-nil exitStatus.err but a zero exitStatus.code")
1031 }
1032 return err
1033 }
1034 if code := r.exit.code; code != 0 {
1035 return ExitStatus(code)
1036 }
1037 return nil
1038 }
1039
1040 // Exited reports whether the last Run call should exit an entire shell. This
1041 // can be triggered by the "exit" built-in command, for example.
1042 //
1043 // Note that this state is overwritten at every Run call, so it should be
1044 // checked immediately after each Run call.
1045 func (r *Runner) Exited() bool {
1046 return r.exit.exiting
1047 }
1048
1049 // Subshell makes a copy of the given [Runner], suitable for use concurrently
1050 // with the original. The copy will have the same environment, including
1051 // variables and functions, but they can all be modified without affecting the
1052 // original.
1053 //
1054 // Subshell is not safe to use concurrently with [Run]. Orchestrating this is
1055 // left up to the caller; no locking is performed.
1056 //
1057 // To replace e.g. stdin/out/err, do [StdIO](r.stdin, r.stdout, r.stderr)(r) on
1058 // the copy.
1059 func (r *Runner) Subshell() *Runner {
1060 return r.subshell(true)
1061 }
1062
1063 // subshell is like [Runner.subshell], but allows skipping some allocations and copies
1064 // when creating subshells which will not be used concurrently with the parent shell.
1065 // TODO(v4): we should expose this, e.g. SubshellForeground and SubshellBackground.
1066 func (r *Runner) subshell(background bool) *Runner {
1067 if !r.didReset {
1068 r.Reset()
1069 }
1070 // Keep in sync with the Runner type. Manually copy fields, to not copy
1071 // sensitive ones like [errgroup.Group], and to do deep copies of slices.
1072 r2 := &Runner{
1073 Dir: r.Dir,
1074 tempDir: r.tempDir,
1075 Params: r.Params,
1076 callHandler: r.callHandler,
1077 execHandler: r.execHandler,
1078 openHandler: r.openHandler,
1079 readDirHandler: r.readDirHandler,
1080 statHandler: r.statHandler,
1081 accessHandler: r.accessHandler,
1082 stdin: r.stdin,
1083 stdout: r.stdout,
1084 stderr: r.stderr,
1085 filename: r.filename,
1086 opts: r.opts,
1087 usedNew: r.usedNew,
1088 exit: r.exit,
1089 lastExit: r.lastExit,
1090
1091 origStdout: r.origStdout, // used for process substitutions
1092 }
1093 r2.writeEnv = newOverlayEnviron(r.writeEnv, background)
1094 // Funcs are copied, since they might be modified.
1095 r2.Funcs = maps.Clone(r.Funcs)
1096 r2.Vars = make(map[string]expand.Variable)
1097 r2.alias = maps.Clone(r.alias)
1098
1099 r2.dirStack = append(r2.dirBootstrap[:0], r.dirStack...)
1100 r2.fillExpandConfig(r.ectx)
1101 r2.didReset = true
1102 return r2
1103 }