Debian Codegraph @

interp/runner.go

raw
1 // Copyright (c) 2017, Daniel Martí <[email protected]>
2 // See LICENSE for licensing information
3
4 package interp
5
6 import (
7 "bytes"
8 "cmp"
9 "context"
10 "errors"
11 "fmt"
12 "io"
13 "io/fs"
14 "iter"
15 "math"
16 mathrand "math/rand/v2"
17 "os"
18 "path/filepath"
19 "runtime"
20 "slices"
21 "strconv"
22 "strings"
23 "sync"
24 "time"
25
26 "mvdan.cc/sh/v3/expand"
27 "mvdan.cc/sh/v3/internal"
28 "mvdan.cc/sh/v3/pattern"
29 "mvdan.cc/sh/v3/syntax"
30 )
31
32 const (
33 // shellReplyPS3Var, or PS3, is a special variable in Bash used by the select command,
34 // while the shell is awaiting for input. the default value is [shellDefaultPS3]
35 shellReplyPS3Var = "PS3"
36 // shellDefaultPS3, or #?, is PS3's default value
37 shellDefaultPS3 = "#? "
38 // shellReplyVar, or REPLY, is a special variable in Bash that is used to store the result of
39 // the select command or of the read command, when no variable name is specified
40 shellReplyVar = "REPLY"
41
42 fifoNamePrefix = "sh-interp-"
43 )
44
45 func (r *Runner) fillExpandConfig(ctx context.Context) {
46 r.ectx = ctx
47 r.ecfg = &expand.Config{
48 Env: expandEnv{r},
49 CmdSubst: func(w io.Writer, cs *syntax.CmdSubst) error {
50 switch len(cs.Stmts) {
51 case 0: // nothing to do
52 return nil
53 case 1: // $(<file)
54 word := catShortcutArg(cs.Stmts[0])
55 if word == nil {
56 break
57 }
58 path := r.literal(word)
59 f, err := r.open(ctx, path, os.O_RDONLY, 0, true)
60 if err != nil {
61 return err
62 }
63 _, err = io.Copy(w, f)
64 f.Close()
65 return err
66 }
67 r2 := r.subshell(false)
68 r2.stdout = w
69 r2.stmts(ctx, cs.Stmts)
70 r2.exit.exiting = false // subshells don't exit the parent shell
71 r.lastExpandExit = r2.exit
72 if r2.exit.fatalExit {
73 return r2.exit.err // surface fatal errors immediately
74 }
75 return nil
76 },
77 ProcSubst: func(ps *syntax.ProcSubst) (string, error) {
78 if ps.Op == syntax.CmdInTemp { // zsh's =(...)
79 return "", fmt.Errorf("unsupported")
80 }
81 if runtime.GOOS == "windows" {
82 return "", fmt.Errorf("TODO: support process substitution on Windows")
83 }
84 if len(ps.Stmts) == 0 { // nothing to do
85 return os.DevNull, nil
86 }
87
88 // We can't atomically create a random unused temporary FIFO.
89 // Similar to [os.CreateTemp],
90 // keep trying new random paths until one does not exist.
91 // We use a uint64 because a uint32 easily runs into retries.
92 var path string
93 try := 0
94 for {
95 path = filepath.Join(r.tempDir, fifoNamePrefix+strconv.FormatUint(mathrand.Uint64(), 16))
96 err := mkfifo(path, 0o666)
97 if err == nil {
98 break
99 }
100 if !os.IsExist(err) {
101 return "", fmt.Errorf("cannot create fifo: %v", err)
102 }
103 if try++; try > 100 {
104 return "", fmt.Errorf("giving up at creating fifo: %v", err)
105 }
106 }
107
108 r2 := r.subshell(true)
109 stdout := r.origStdout
110 // TODO: note that `man bash` mentions that `wait` only waits for the last
111 // process substitution as long as it is $!; the logic here would mean we wait for all of them.
112 bg := bgProc{
113 done: make(chan struct{}),
114 exit: new(exitStatus),
115 }
116 r.bgProcs = append(r.bgProcs, bg)
117 go func() {
118 defer func() {
119 *bg.exit = r2.exit
120 close(bg.done)
121 }()
122 switch ps.Op {
123 case syntax.CmdIn:
124 f, err := os.OpenFile(path, os.O_WRONLY, 0)
125 if err != nil {
126 r.errf("cannot open fifo for stdout: %v\n", err)
127 return
128 }
129 r2.stdout = f
130 defer func() {
131 if err := f.Close(); err != nil {
132 r.errf("closing stdout fifo: %v\n", err)
133 }
134 os.Remove(path)
135 }()
136 case syntax.CmdOut:
137 f, err := os.OpenFile(path, os.O_RDONLY, 0)
138 if err != nil {
139 r.errf("cannot open fifo for stdin: %v\n", err)
140 return
141 }
142 r2.stdin = f
143 r2.stdout = stdout
144
145 defer func() {
146 f.Close()
147 os.Remove(path)
148 }()
149 default:
150 // Should only happen if we forgot a case above.
151 panic(fmt.Sprintf("unexpected process substitution operator: %q", ps.Op))
152 }
153 r2.stmts(ctx, ps.Stmts)
154 r2.exit.exiting = false // subshells don't exit the parent shell
155 }()
156 return path, nil
157 },
158 }
159 r.updateExpandOpts()
160 }
161
162 // catShortcutArg checks if a statement is of the form "$(<file)". The redirect
163 // word is returned if there's a match, and nil otherwise.
164 func catShortcutArg(stmt *syntax.Stmt) *syntax.Word {
165 if stmt.Cmd != nil || stmt.Negated || stmt.Background || stmt.Coprocess || stmt.Disown {
166 return nil
167 }
168 if len(stmt.Redirs) != 1 {
169 return nil
170 }
171 redir := stmt.Redirs[0]
172 if redir.Op != syntax.RdrIn {
173 return nil
174 }
175 return redir.Word
176 }
177
178 func (r *Runner) updateExpandOpts() {
179 if r.opts[optNoGlob] {
180 r.ecfg.ReadDir2 = nil
181 } else {
182 r.ecfg.ReadDir2 = func(s string) ([]fs.DirEntry, error) {
183 return r.readDirHandler(r.handlerCtx(r.ectx, handlerKindReadDir, todoPos), s)
184 }
185 }
186 r.ecfg.GlobStar = r.opts[optGlobStar]
187 r.ecfg.DotGlob = r.opts[optDotGlob]
188 r.ecfg.NoCaseGlob = r.opts[optNoCaseGlob]
189 r.ecfg.NullGlob = r.opts[optNullGlob]
190 r.ecfg.NoUnset = r.opts[optNoUnset]
191 r.ecfg.ExtGlob = r.opts[optExtGlob]
192 }
193
194 func (r *Runner) expandErr(err error) {
195 if err == nil {
196 return
197 }
198 errMsg := err.Error()
199 fmt.Fprintln(r.stderr, errMsg)
200 _, unsetParam := errors.AsType[expand.UnsetParameterError](err)
201 switch {
202 case unsetParam, errMsg == "invalid indirect expansion":
203 // TODO: These errors are treated as fatal by bash.
204 // Make the error type reflect that.
205 r.exit.code = 1
206 r.exit.exiting = true
207 case errors.Is(err, errReadOnly):
208 // Like in bash, assigning to a read-only variable fails
209 // the command at hand without exiting the shell.
210 r.exit.code = 1
211 }
212 }
213
214 func (r *Runner) arithm(expr syntax.ArithmExpr) int {
215 n, err := expand.Arithm(r.ecfg, expr)
216 r.expandErr(err)
217 return n
218 }
219
220 func (r *Runner) fields(words ...*syntax.Word) []string {
221 strs, err := expand.Fields(r.ecfg, words...)
222 r.expandErr(err)
223 return strs
224 }
225
226 func (r *Runner) literal(word *syntax.Word) string {
227 str, err := expand.Literal(r.ecfg, word)
228 r.expandErr(err)
229 return str
230 }
231
232 func (r *Runner) document(word *syntax.Word) string {
233 str, err := expand.Document(r.ecfg, word)
234 r.expandErr(err)
235 return str
236 }
237
238 func (r *Runner) pattern(word *syntax.Word) string {
239 str, err := expand.Pattern(r.ecfg, word)
240 r.expandErr(err)
241 return str
242 }
243
244 // expandEnviron exposes [Runner]'s variables to the expand package.
245 type expandEnv struct {
246 r *Runner
247 }
248
249 var _ expand.WriteEnviron = expandEnv{}
250
251 func (e expandEnv) Get(name string) expand.Variable {
252 return e.r.lookupVar(name)
253 }
254
255 func (e expandEnv) Set(name string, vr expand.Variable) error {
256 return e.r.setVarErr(name, vr)
257 }
258
259 func (e expandEnv) Each(fn func(name string, vr expand.Variable) bool) {
260 e.r.writeEnv.Each(fn)
261 }
262
263 var todoPos syntax.Pos // for handlerCtx callers where we don't yet have a position
264
265 func (r *Runner) handlerCtx(ctx context.Context, kind handlerKind, pos syntax.Pos) context.Context {
266 hc := HandlerContext{
267 runner: r,
268 kind: kind,
269 Env: &overlayEnviron{parent: r.writeEnv},
270 Dir: r.Dir,
271 Pos: pos,
272 Stdout: r.stdout,
273 Stderr: r.stderr,
274 LastExitStatus: int(r.lastExit.code),
275 }
276 if r.stdin != nil { // do not leave hc.Stdin as a typed nil
277 hc.Stdin = r.stdin
278 }
279 return context.WithValue(ctx, handlerCtxKey{}, hc)
280 }
281
282 func (r *Runner) out(s string) {
283 io.WriteString(r.stdout, s)
284 }
285
286 func (r *Runner) outf(format string, a ...any) {
287 fmt.Fprintf(r.stdout, format, a...)
288 }
289
290 func (r *Runner) errf(format string, a ...any) {
291 fmt.Fprintf(r.stderr, format, a...)
292 }
293
294 func (r *Runner) stop(ctx context.Context) bool {
295 // Some traps trigger on exit, so we do want those to run.
296 if !r.handlingTrap && (r.exit.returning || r.exit.exiting) {
297 return true
298 }
299 if err := ctx.Err(); err != nil {
300 r.exit.fatal(err)
301 return true
302 }
303 if r.opts[optNoExec] {
304 return true
305 }
306 return false
307 }
308
309 func (r *Runner) stmt(ctx context.Context, st *syntax.Stmt) {
310 if r.stop(ctx) {
311 return
312 }
313 r.exit = exitStatus{}
314 if st.Background || st.Disown {
315 r2 := r.subshell(true)
316 st2 := *st
317 st2.Background = false
318 st2.Disown = false
319 bg := bgProc{
320 done: make(chan struct{}),
321 exit: new(exitStatus),
322 }
323 r.bgProcs = append(r.bgProcs, bg)
324 go func() {
325 r2.Run(ctx, &st2)
326 r2.exit.exiting = false // subshells don't exit the parent shell
327 *bg.exit = r2.exit
328 close(bg.done)
329 }()
330 } else {
331 r.stmtSync(ctx, st)
332 }
333 r.lastExit = r.exit
334 }
335
336 func (r *Runner) stmtSync(ctx context.Context, st *syntax.Stmt) {
337 oldIn, oldOut, oldErr := r.stdin, r.stdout, r.stderr
338 var closers []io.Closer
339 for _, rd := range st.Redirs {
340 cls, err := r.redir(ctx, rd)
341 if err != nil {
342 if !r.exit.fatalExit {
343 // A fatal error from a handler is reported by [Runner.Run].
344 r.errf("%v\n", err)
345 }
346 r.exit.code = 1
347 break
348 }
349 if cls != nil {
350 closers = append(closers, cls)
351 }
352 }
353 if r.exit.ok() && st.Cmd != nil {
354 r.cmd(ctx, st.Cmd)
355 }
356 if st.Negated {
357 if r.exit.ok() {
358 r.exit.code = 1
359 } else {
360 r.exit.clear()
361 }
362 } else if b, ok := st.Cmd.(*syntax.BinaryCmd); ok && (b.Op == syntax.AndStmt || b.Op == syntax.OrStmt) {
363 } else if !r.exit.ok() && !r.noErrExit {
364 r.trapCallback(ctx, r.callbackErr, "error")
365 // If the "errexit" option is set and a command failed, exit the shell. Exceptions:
366 //
367 // conditions (if <cond>, while <cond>, etc)
368 // part of && or || lists; excluded via "else" above
369 // preceded by !; excluded via "else" above
370 if r.opts[optErrExit] {
371 r.exit.exiting = true
372 }
373 }
374 if r.keepRedirs {
375 // The exec builtin made this statement's redirections apply to the
376 // shell itself, so don't undo them and keep their files open.
377 r.keepRedirs = false
378 } else if len(st.Redirs) > 0 {
379 r.stdin, r.stdout, r.stderr = oldIn, oldOut, oldErr
380 for _, cls := range closers {
381 cls.Close()
382 }
383 }
384 }
385
386 func (r *Runner) cmd(ctx context.Context, cm syntax.Command) {
387 if r.stop(ctx) {
388 return
389 }
390
391 tracingEnabled := r.opts[optXTrace]
392 trace := r.tracer()
393
394 switch cm := cm.(type) {
395 case *syntax.Block:
396 r.stmts(ctx, cm.Stmts)
397 case *syntax.Subshell:
398 r2 := r.subshell(false)
399 r2.stmts(ctx, cm.Stmts)
400 r2.exit.exiting = false // subshells don't exit the parent shell
401 r.exit = r2.exit
402 case *syntax.CallExpr:
403 // Build new slices, to not modify the caller's AST
404 // nor the slices in the alias map.
405 args := cm.Args
406 for i := 0; i < len(args); {
407 if !r.opts[optExpandAliases] {
408 break
409 }
410 als, ok := r.alias[args[i].Lit()]
411 if !ok {
412 break
413 }
414 args = slices.Concat(args[:i], als.args, args[i+1:])
415 if !als.blank {
416 break
417 }
418 i += len(als.args)
419 }
420 r.lastExpandExit = exitStatus{}
421 fields := r.fields(args...)
422 if len(fields) == 0 {
423 for _, as := range cm.Assigns {
424 name := as.Name.Value
425
426 prev := r.lookupVar(name)
427 // Here we have a naked "foo=bar", so if we inherited a local var from a parent
428 // function we want to signal that we are modifying the parent var rather than
429 // creating a new local var via "local foo=bar".
430 // TODO: there is likely a better way to do this.
431 prev.Local = false
432
433 name, vr := r.assignVal(name, prev, as, "")
434 r.setVarWithIndex(prev, name, as.Index, vr)
435
436 if !tracingEnabled {
437 continue
438 }
439
440 // Strangely enough, it seems like Bash prints original
441 // source for arrays, but the expanded value otherwise.
442 // Note that, unlike bash, we print neither the subscript
443 // in `x[i]=y` nor just the appended value in `x+=y`.
444 if as.Array != nil {
445 trace.expr(as)
446 } else if as.Value != nil {
447 trace.stringf("%s=%s", name, quoteBash(vr.String()))
448 }
449 trace.newLineFlush()
450 }
451 // If interpreting the last expansion like $(foo) failed,
452 // and the expansion and assignments otherwise succeeded,
453 // we need to surface that last exit code.
454 if r.exit.ok() {
455 r.exit = r.lastExpandExit
456 }
457 break
458 }
459
460 type restoreVar struct {
461 name string
462 vr expand.Variable
463 }
464 var restores []restoreVar
465
466 for _, as := range cm.Assigns {
467 name := as.Name.Value
468 prev := r.lookupVar(name)
469 // Resolve any nameref so we can restore the original final value later on.
470 if n, v := prev.Resolve(r.writeEnv); n != "" {
471 name, prev = n, v
472 }
473
474 name, vr := r.assignVal(name, prev, as, "")
475 // Inline command vars are always exported.
476 vr.Exported = true
477
478 restores = append(restores, restoreVar{name, prev})
479
480 r.setVar(name, vr)
481 }
482
483 trace.call(fields[0], fields[1:]...)
484 trace.newLineFlush()
485
486 r.call(ctx, cm.Args[0].Pos(), fields)
487 for _, restore := range restores {
488 r.setVar(restore.name, restore.vr)
489 }
490 case *syntax.BinaryCmd:
491 switch cm.Op {
492 case syntax.AndStmt, syntax.OrStmt:
493 oldNoErrExit := r.noErrExit
494 r.noErrExit = true
495 r.stmt(ctx, cm.X)
496 r.noErrExit = oldNoErrExit
497 if r.exit.ok() == (cm.Op == syntax.AndStmt) {
498 r.stmt(ctx, cm.Y)
499 }
500 case syntax.Pipe, syntax.PipeAll:
501 pr, pw, err := newPipe()
502 if err != nil {
503 r.exit.fatal(err) // not being able to create a pipe is rare but critical
504 return
505 }
506 r2 := r.subshell(true)
507 r2.stdout = pw
508 if cm.Op == syntax.PipeAll {
509 r2.stderr = pw
510 } else {
511 r2.stderr = r.stderr
512 }
513 oldIn := r.stdin
514 r.stdin = pr
515 var wg sync.WaitGroup
516 wg.Go(func() {
517 r2.stmt(ctx, cm.X)
518 r2.exit.exiting = false // subshells don't exit the parent shell
519 pw.Close()
520 })
521 r.stmt(ctx, cm.Y)
522 pr.Close()
523 wg.Wait()
524 r.stdin = oldIn
525 if r.opts[optPipeFail] && !r2.exit.ok() && r.exit.ok() {
526 r.exit = r2.exit
527 }
528 if r2.exit.fatalExit {
529 r.exit.fatal(r2.exit.err) // surface fatal errors immediately
530 }
531 }
532 case *syntax.IfClause:
533 oldNoErrExit := r.noErrExit
534 r.noErrExit = true
535 r.stmts(ctx, cm.Cond)
536 r.noErrExit = oldNoErrExit
537
538 if r.exit.ok() {
539 r.stmts(ctx, cm.Then)
540 break
541 }
542 r.exit.clear()
543 if cm.Else != nil {
544 r.cmd(ctx, cm.Else)
545 }
546 case *syntax.WhileClause:
547 for !r.stop(ctx) {
548 oldNoErrExit := r.noErrExit
549 r.noErrExit = true
550 r.stmts(ctx, cm.Cond)
551 r.noErrExit = oldNoErrExit
552
553 stop := r.exit.ok() == cm.Until
554 r.exit.clear()
555 if stop || r.loopStmtsBroken(ctx, cm.Do) {
556 break
557 }
558 }
559 case *syntax.ForClause:
560 switch y := cm.Loop.(type) {
561 case *syntax.WordIter:
562 name := y.Name.Value
563 items := r.Params // for i; do ...
564
565 inToken := y.InPos.IsValid()
566 if inToken {
567 items = r.fields(y.Items...) // for i in ...; do ...
568 }
569
570 if cm.Select {
571 ps3 := cmp.Or(r.envGet(shellReplyPS3Var), shellDefaultPS3)
572
573 for menu := true; ; {
574 if menu {
575 // display menu
576 for i, word := range items {
577 r.errf("%d) %v\n", i+1, word)
578 }
579 menu = false
580 }
581 r.errf("%s", ps3)
582
583 line, err := r.readLine(ctx, true)
584 if err != nil {
585 r.errf("\n")
586 r.exit.code = 1
587 break
588 }
589 if len(line) == 0 {
590 menu = true // no reply; show the menu again
591 continue
592 }
593
594 reply := string(line)
595 r.setVarString(shellReplyVar, reply)
596
597 if c, _ := strconv.Atoi(reply); c > 0 && c <= len(items) {
598 r.setVarString(name, items[c-1])
599 } else {
600 r.setVarString(name, "")
601 }
602
603 // execute commands until break or return is encountered
604 if r.loopStmtsBroken(ctx, cm.Do) {
605 break
606 }
607 }
608 break
609 }
610
611 for _, field := range items {
612 r.setVarString(name, field)
613 trace.stringf("for %s in", y.Name.Value)
614 if inToken {
615 for _, item := range y.Items {
616 trace.string(" ")
617 trace.expr(item)
618 }
619 } else {
620 trace.string(` "$@"`)
621 }
622 trace.newLineFlush()
623 if r.loopStmtsBroken(ctx, cm.Do) {
624 break
625 }
626 }
627 case *syntax.CStyleLoop:
628 if y.Init != nil {
629 r.arithm(y.Init)
630 }
631 for y.Cond == nil || r.arithm(y.Cond) != 0 {
632 if !r.exit.ok() || r.loopStmtsBroken(ctx, cm.Do) {
633 break
634 }
635 if y.Post != nil {
636 r.arithm(y.Post)
637 }
638 }
639 }
640 case *syntax.FuncDecl:
641 if cm.Name == nil { // e.g. zsh's anonymous or multi-name functions
642 r.errf("unsupported\n")
643 r.exit.code = 1
644 break
645 }
646 r.setFunc(cm.Name.Value, cm.Body)
647 case *syntax.ArithmCmd:
648 r.exit.oneIf(r.arithm(cm.X) == 0)
649 case *syntax.LetClause:
650 if tracingEnabled {
651 trace.string("let")
652 for _, expr := range cm.Exprs {
653 trace.stringf(" %s", r.letArgString(trace.printer, expr))
654 }
655 trace.newLineFlush()
656 }
657 var val int
658 for _, expr := range cm.Exprs {
659 val = r.arithm(expr)
660 }
661 r.exit.oneIf(val == 0)
662 case *syntax.CaseClause:
663 trace.string("case ")
664 trace.expr(cm.Word)
665 trace.string(" in")
666 trace.newLineFlush()
667 str := r.literal(cm.Word)
668 runNext := false // whether the previous item ended with ";&"
669 for _, ci := range cm.Items {
670 if !runNext && !slices.ContainsFunc(ci.Patterns, func(word *syntax.Word) bool {
671 return r.match(r.pattern(word), str)
672 }) {
673 continue
674 }
675 r.stmts(ctx, ci.Stmts)
676 switch ci.Op {
677 case syntax.Fallthrough: // ";&" runs the next item unconditionally
678 runNext = true
679 case syntax.Resume, syntax.ResumeKorn: // ";;&" and ";|" resume matching
680 runNext = false
681 default: // ";;" or the last item stop
682 return
683 }
684 }
685 case *syntax.TestClause:
686 if r.bashTest(ctx, cm.X, false) == "" && r.exit.ok() {
687 // to preserve exit status code 2 for regex errors, etc
688 r.exit.code = 1
689 }
690 case *syntax.DeclClause:
691 local, global := false, false
692 var modes []string
693 valType := ""
694 declQuery := "" // "-f" or "-p" for query mode
695 switch cm.Variant.Value {
696 case "declare":
697 // When used in a function, "declare" acts as "local"
698 // unless the "-g" option is used.
699 local = r.inFunc
700 case "local":
701 if !r.inFunc {
702 r.errf("local: can only be used in a function\n")
703 r.exit.code = 1
704 return
705 }
706 local = true
707 case "export":
708 modes = append(modes, "-x")
709 case "readonly":
710 modes = append(modes, "-r")
711 case "nameref":
712 valType = "-n"
713 }
714 assignLoop:
715 for as := range r.flattenAssigns(cm.Args) {
716 fp := flagParser{remaining: []string{as.Name.Value}}
717 for fp.more() {
718 switch flag := fp.flag(); flag {
719 case "-x", "-r":
720 modes = append(modes, flag)
721 case "-a", "-A", "-n":
722 valType = flag
723 case "-g":
724 global = true
725 case "-f", "-p":
726 declQuery = flag
727 default:
728 r.errf("declare: invalid option %q\n", flag)
729 r.exit.code = 2
730 return
731 }
732 continue assignLoop
733 }
734 name := as.Name.Value
735 if !syntax.ValidName(name) {
736 r.errf("declare: invalid name %q\n", name)
737 r.exit.code = 1
738 return
739 }
740 if declQuery == "-f" {
741 // declare -f name: print function definition.
742 // Bash silently returns exit 1 for missing functions.
743 if body := r.Funcs[name]; body != nil {
744 r.outf("%s()\n", name)
745 printer := syntax.NewPrinter()
746 var buf bytes.Buffer
747 printer.Print(&buf, body)
748 r.outf("%s\n", buf.String())
749 } else {
750 r.exit.code = 1
751 }
752 continue
753 }
754 if declQuery == "-p" {
755 // declare -p name: print variable with attributes.
756 vr := r.lookupVar(name)
757 if !vr.Declared() {
758 r.errf("declare: %s: not found\n", name)
759 r.exit.code = 1
760 continue
761 }
762 flags := vr.Flags()
763 if flags == "" {
764 flags = "-"
765 }
766 switch vr.Kind {
767 case expand.Indexed:
768 r.outf("declare -%s %s=(", flags, name)
769 for i, v := range vr.List {
770 if i > 0 {
771 r.out(" ")
772 }
773 idx := i
774 if vr.Indexes != nil {
775 idx = vr.Indexes[i]
776 }
777 r.outf("[%d]=%q", idx, v)
778 }
779 r.out(")\n")
780 case expand.Associative:
781 r.outf("declare -%s %s=(", flags, name)
782 first := true
783 for k, v := range vr.Map {
784 if !first {
785 r.out(" ")
786 }
787 r.outf("[%s]=%q", k, v)
788 first = false
789 }
790 r.out(")\n")
791 default:
792 r.outf("declare -%s %s=%q\n", flags, name, vr.Str)
793 }
794 continue
795 }
796 vr := r.lookupVar(name)
797 if as.Naked {
798 if valType == "-A" {
799 vr.Kind = expand.Associative
800 } else {
801 vr.Kind = expand.KeepValue
802 }
803 } else {
804 name, vr = r.assignVal(name, vr, as, valType)
805 }
806 if global {
807 vr.Local = false
808 } else if local {
809 vr.Local = true
810 }
811 for _, mode := range modes {
812 switch mode {
813 case "-x":
814 vr.Exported = true
815 case "-r":
816 vr.ReadOnly = true
817 }
818 }
819 r.setVar(name, vr)
820 }
821 case *syntax.TimeClause:
822 start := time.Now()
823 if cm.Stmt != nil {
824 r.stmt(ctx, cm.Stmt)
825 }
826 format := "%s\t%s\n"
827 if cm.PosixFormat {
828 format = "%s %s\n"
829 } else {
830 r.outf("\n")
831 }
832 real := time.Since(start)
833 r.outf(format, "real", elapsedString(real, cm.PosixFormat))
834 // TODO: can we do these?
835 r.outf(format, "user", elapsedString(0, cm.PosixFormat))
836 r.outf(format, "sys", elapsedString(0, cm.PosixFormat))
837 default:
838 // Should only happen if we forgot a case above.
839 r.errf("unhandled command node: %T\n", cm)
840 r.exit.code = 1
841 }
842 }
843
844 func (r *Runner) trapCallback(ctx context.Context, callback, name string) {
845 if callback == "" {
846 return // nothing to do
847 }
848 if r.handlingTrap {
849 return // don't recurse, as that could lead to cycles
850 }
851 r.handlingTrap = true
852 defer func() { r.handlingTrap = false }()
853
854 p := syntax.NewParser()
855 // TODO: do this parsing when "trap" is called?
856 file, err := p.Parse(strings.NewReader(callback), name+" trap")
857 if err != nil {
858 r.errf(name+"trap: %v\n", err)
859 // ignore errors in the callback
860 return
861 }
862 oldExit, oldLastExit := r.exit, r.lastExit
863 r.lastExit = r.exit
864 r.stmts(ctx, file.Stmts)
865 r.exit, r.lastExit = oldExit, oldLastExit // traps on EXIT or ERR should not modify the result
866 }
867
868 func (r *Runner) flattenAssigns(args []*syntax.Assign) iter.Seq[*syntax.Assign] {
869 return func(yield func(*syntax.Assign) bool) {
870 for _, as := range args {
871 // Convert "declare $x" into "declare value".
872 // Don't use syntax.Parser here, as we only want the basic
873 // splitting by '='.
874 if as.Name != nil {
875 if !yield(as) {
876 return
877 }
878 continue
879 }
880 for _, field := range r.fields(as.Value) {
881 as := &syntax.Assign{}
882 name, val, ok := strings.Cut(field, "=")
883 as.Name = &syntax.Lit{Value: name}
884 if !ok {
885 as.Naked = true
886 } else {
887 as.Value = &syntax.Word{Parts: []syntax.WordPart{
888 &syntax.Lit{Value: val},
889 }}
890 }
891 if !yield(as) {
892 return
893 }
894 }
895 }
896 }
897 }
898
899 // letArgString reproduces one expression of a let clause as bash would print it
900 // when tracing, that is, as the single quoted word that bash's let receives.
901 func (r *Runner) letArgString(printer *syntax.Printer, expr syntax.ArithmExpr) string {
902 if word, ok := expr.(*syntax.Word); ok {
903 return quoteBash(r.literal(word))
904 }
905 // The printer only prints an arithmetic expression as part of a parent node,
906 // so print a let clause holding just this expression and drop the keyword.
907 // The keyword borrows the expression's position to stay on the same line.
908 // TODO: drop this workaround if [syntax.Printer.Print] learns to print
909 // an arithmetic expression on its own.
910 var sb strings.Builder
911 if err := printer.Print(&sb, &syntax.LetClause{
912 Let: expr.Pos(),
913 Exprs: []syntax.ArithmExpr{expr},
914 }); err != nil { // should never happen
915 panic(err)
916 }
917 return strings.TrimPrefix(sb.String(), "let ")
918 }
919
920 func (r *Runner) match(pat, name string) bool {
921 matcher, err := internal.ExtendedPatternMatcher(pat, pattern.EntireString|pattern.ExtendedOperators)
922 if err != nil {
923 // A malformed pattern simply does not match, like in bash.
924 // Any other error, such as an unsupported extended pattern, is reported.
925 if _, ok := errors.AsType[*pattern.SyntaxError](err); !ok {
926 r.expandErr(err)
927 }
928 return false
929 }
930 return matcher(name)
931 }
932
933 func elapsedString(d time.Duration, posix bool) string {
934 if posix {
935 return fmt.Sprintf("%.2f", d.Seconds())
936 }
937 mins := int(d.Minutes())
938 sec := math.Mod(d.Seconds(), 60.0)
939 return fmt.Sprintf("%dm%.3fs", mins, sec)
940 }
941
942 func (r *Runner) stmts(ctx context.Context, stmts []*syntax.Stmt) {
943 for _, stmt := range stmts {
944 r.stmt(ctx, stmt)
945 }
946 }
947
948 func (r *Runner) hdocReader(rd *syntax.Redirect) (stdinFile, error) {
949 pr, pw, err := newPipe()
950 if err != nil {
951 return nil, err
952 }
953 hdoc := r.hdocString(rd)
954 // We write to the pipe in a new goroutine,
955 // as pipe writes may block once the buffer gets full.
956 // We still construct and buffer the entire heredoc first,
957 // as doing it concurrently would lead to different semantics and be racy.
958 go func() {
959 io.WriteString(pw, hdoc)
960 pw.Close()
961 }()
962 return pr, nil
963 }
964
965 // hdocQuotedDelim reports whether a here-document delimiter word is quoted,
966 // as in "<<'EOF'" or "<<\EOF", which makes its body literal.
967 func hdocQuotedDelim(word *syntax.Word) bool {
968 for _, wp := range word.Parts {
969 switch wp := wp.(type) {
970 case *syntax.Lit:
971 if strings.Contains(wp.Value, "\\") {
972 return true
973 }
974 case *syntax.SglQuoted, *syntax.DblQuoted:
975 return true
976 }
977 }
978 return false
979 }
980
981 // hdocWord returns a here-document body, or one of its lines, as a string.
982 // A quoted delimiter, as in "<<'EOF'", makes the body literal,
983 // in which case the parser only gives us literal parts.
984 // Note that a partly quoted delimiter, such as "<<'A'B",
985 // is not spotted by the parser either, so we still expand its body.
986 func (r *Runner) hdocWord(word *syntax.Word, quoted bool) string {
987 if quoted {
988 if lit := word.Lit(); lit != "" {
989 return lit
990 }
991 }
992 return r.document(word)
993 }
994
995 // hdocString returns the body of a here-document as a string.
996 func (r *Runner) hdocString(rd *syntax.Redirect) string {
997 if rd.Hdoc == nil {
998 return "" // an empty here-document
999 }
1000 quoted := hdocQuotedDelim(rd.Word)
1001 if rd.Op != syntax.DashHdoc {
1002 return r.hdocWord(rd.Hdoc, quoted)
1003 }
1004 // Strip the leading tabs from each line.
1005 var buf strings.Builder
1006 var cur []syntax.WordPart
1007 flushLine := func() {
1008 if buf.Len() > 0 {
1009 buf.WriteByte('\n')
1010 }
1011 buf.WriteString(r.hdocWord(&syntax.Word{Parts: cur}, quoted))
1012 cur = cur[:0]
1013 }
1014 for _, wp := range rd.Hdoc.Parts {
1015 lit, ok := wp.(*syntax.Lit)
1016 if !ok {
1017 cur = append(cur, wp)
1018 continue
1019 }
1020 first := true
1021 for part := range strings.SplitSeq(lit.Value, "\n") {
1022 if !first {
1023 flushLine()
1024 }
1025 first = false
1026 part = strings.TrimLeft(part, "\t")
1027 cur = append(cur, &syntax.Lit{Value: part})
1028 }
1029 }
1030 flushLine()
1031 return buf.String()
1032 }
1033
1034 func (r *Runner) redir(ctx context.Context, rd *syntax.Redirect) (io.Closer, error) {
1035 // Note that Hdoc is nil for an empty here-document.
1036 if rd.Op == syntax.Hdoc || rd.Op == syntax.DashHdoc {
1037 pr, err := r.hdocReader(rd)
1038 if err != nil {
1039 return nil, err
1040 }
1041 r.stdin = pr
1042 return pr, nil
1043 }
1044
1045 orig := &r.stdout
1046 if rd.N != nil {
1047 switch rd.N.Value {
1048 case "0":
1049 // Note that the input redirects below always use stdin (0)
1050 // because we don't support anything else right now.
1051 case "1":
1052 // The default for the output redirects below.
1053 case "2":
1054 orig = &r.stderr
1055 default:
1056 return nil, fmt.Errorf("unsupported redirect fd: %v", rd.N.Value)
1057 }
1058 }
1059 arg := r.literal(rd.Word)
1060 switch rd.Op {
1061 case syntax.WordHdoc:
1062 pr, pw, err := newPipe()
1063 if err != nil {
1064 return nil, err
1065 }
1066 r.stdin = pr
1067 // We write to the pipe in a new goroutine,
1068 // as pipe writes may block once the buffer gets full.
1069 go func() {
1070 io.WriteString(pw, arg)
1071 io.WriteString(pw, "\n")
1072 pw.Close()
1073 }()
1074 return pr, nil
1075 case syntax.DplOut:
1076 switch arg {
1077 case "1":
1078 *orig = r.stdout
1079 case "2":
1080 *orig = r.stderr
1081 case "-":
1082 *orig = io.Discard // closing the output writer
1083 default:
1084 return nil, fmt.Errorf("unhandled %v arg: %q", rd.Op, arg)
1085 }
1086 return nil, nil
1087 case syntax.RdrIn, syntax.RdrOut, syntax.AppOut,
1088 syntax.RdrAll, syntax.AppAll:
1089 // done further below
1090 case syntax.DplIn:
1091 switch arg {
1092 case "-":
1093 r.stdin = nil // closing the input file
1094 default:
1095 return nil, fmt.Errorf("unhandled %v arg: %q", rd.Op, arg)
1096 }
1097 return nil, nil
1098 default:
1099 return nil, fmt.Errorf("unhandled redirect op: %v", rd.Op)
1100 }
1101 mode := os.O_RDONLY
1102 switch rd.Op {
1103 case syntax.AppOut, syntax.AppAll:
1104 mode = os.O_WRONLY | os.O_CREATE | os.O_APPEND
1105 case syntax.RdrOut, syntax.RdrAll:
1106 mode = os.O_WRONLY | os.O_CREATE | os.O_TRUNC
1107 }
1108 f, err := r.open(ctx, arg, mode, 0o644, false)
1109 if err != nil {
1110 return nil, err
1111 }
1112 switch rd.Op {
1113 case syntax.RdrIn:
1114 stdin, err := newStdinFile(f)
1115 if err != nil {
1116 return nil, err
1117 }
1118 r.stdin = stdin
1119 case syntax.RdrOut, syntax.AppOut:
1120 *orig = f
1121 case syntax.RdrAll, syntax.AppAll:
1122 r.stdout = f
1123 r.stderr = f
1124 default:
1125 return nil, fmt.Errorf("unhandled redirect op: %v", rd.Op)
1126 }
1127 return f, nil
1128 }
1129
1130 func (r *Runner) loopStmtsBroken(ctx context.Context, stmts []*syntax.Stmt) bool {
1131 oldInLoop := r.inLoop
1132 r.inLoop = true
1133 defer func() { r.inLoop = oldInLoop }()
1134 for _, stmt := range stmts {
1135 r.stmt(ctx, stmt)
1136 if r.contnEnclosing > 0 {
1137 r.contnEnclosing--
1138 return r.contnEnclosing > 0
1139 }
1140 if r.breakEnclosing > 0 {
1141 r.breakEnclosing--
1142 return true
1143 }
1144 }
1145 return false
1146 }
1147
1148 func (r *Runner) call(ctx context.Context, pos syntax.Pos, args []string) {
1149 if r.stop(ctx) {
1150 return
1151 }
1152 if r.callHandler != nil {
1153 var err error
1154 args, err = r.callHandler(r.handlerCtx(ctx, handlerKindCall, pos), args)
1155 if err != nil {
1156 // handler's custom fatal error
1157 r.exit.fatal(err)
1158 return
1159 }
1160 }
1161 name := args[0]
1162 if body := r.Funcs[name]; body != nil {
1163 // stack them to support nested func calls
1164 oldParams := r.Params
1165 r.Params = args[1:]
1166 oldInFunc := r.inFunc
1167 r.inFunc = true
1168
1169 // Functions run in a nested scope.
1170 // Note that [Runner.exec] below does something similar.
1171 origEnv := r.writeEnv
1172 r.writeEnv = &overlayEnviron{parent: r.writeEnv, funcScope: true}
1173
1174 r.stmt(ctx, body)
1175
1176 r.writeEnv = origEnv
1177
1178 r.Params = oldParams
1179 r.inFunc = oldInFunc
1180 r.exit.returning = false
1181 return
1182 }
1183 if IsBuiltin(name) {
1184 r.exit = r.builtin(ctx, pos, name, args[1:])
1185 return
1186 }
1187 r.exec(ctx, pos, args)
1188 }
1189
1190 func (r *Runner) exec(ctx context.Context, pos syntax.Pos, args []string) {
1191 r.exit.fromHandlerError(r.execHandler(r.handlerCtx(ctx, handlerKindExec, pos), args))
1192 }
1193
1194 func (r *Runner) open(ctx context.Context, path string, flags int, mode os.FileMode, print bool) (io.ReadWriteCloser, error) {
1195 // If we are opening a FIFO temporary file created by the interpreter itself,
1196 // don't pass this along to the open handler as it will not work at all
1197 // unless [os.OpenFile] is used directly with it.
1198 // Matching by directory and basename prefix isn't perfect, but works.
1199 //
1200 // If we want FIFOs to use a handler in the future, they probably
1201 // need their own separate handler API matching Unix-like semantics.
1202 dir, name := filepath.Split(path)
1203 dir = strings.TrimSuffix(dir, "/")
1204 if dir == r.tempDir && strings.HasPrefix(name, fifoNamePrefix) {
1205 return os.OpenFile(path, flags, mode)
1206 }
1207
1208 f, err := r.openHandler(r.handlerCtx(ctx, handlerKindOpen, todoPos), path, flags, mode)
1209 // TODO: support wrapped PathError returned from openHandler.
1210 switch err.(type) {
1211 case nil:
1212 return f, nil
1213 case *os.PathError:
1214 if print {
1215 r.errf("%v\n", err)
1216 }
1217 default: // handler's custom fatal error
1218 r.exit.fatal(err)
1219 }
1220 return nil, err
1221 }
1222
1223 func (r *Runner) stat(ctx context.Context, name string) (fs.FileInfo, error) {
1224 path := absPath(r.Dir, name)
1225 return r.statHandler(r.handlerCtx(ctx, handlerKindStat, todoPos), path, true)
1226 }
1227
1228 func (r *Runner) lstat(ctx context.Context, name string) (fs.FileInfo, error) {
1229 path := absPath(r.Dir, name)
1230 return r.statHandler(r.handlerCtx(ctx, handlerKindStat, todoPos), path, false)
1231 }
1232
1233 func (r *Runner) access(ctx context.Context, name string, mode AccessMode) error {
1234 path := absPath(r.Dir, name)
1235 return r.accessHandler(r.handlerCtx(ctx, handlerKindAccess, todoPos), path, mode)
1236 }