Debian Codegraph @

interp/builtin.go

raw
1 // Copyright (c) 2017, Daniel Martí <[email protected]>
2 // See LICENSE for licensing information
3
4 package interp
5
6 import (
7 "bufio"
8 "bytes"
9 "context"
10 "errors"
11 "fmt"
12 "os"
13 "path/filepath"
14 "slices"
15 "strconv"
16 "strings"
17 "time"
18
19 "golang.org/x/term"
20
21 "mvdan.cc/sh/v3/expand"
22 "mvdan.cc/sh/v3/syntax"
23 )
24
25 // TODO: given the categories below, perhaps this should be more like:
26 //
27 // func IsBuiltin(lang syntax.LangVariant, name string) bool
28 //
29 // or perhaps some API that also lets the user iterate through the builtins?
30 //
31 // Also, should we move this to the syntax package too?
32 // It's not a syntactical property strictly speaking,
33 // but it's also odd to require importing the interp package for it.
34
35 // IsBuiltin returns true if the given word is a POSIX Shell
36 // or Bash builtin.
37 func IsBuiltin(name string) bool {
38 switch name {
39 case
40 // POSIX Shell regular built-ins, that is, the utilities which the shell
41 // must provide as built-ins, from section 1.d obtained in September 2025 from:
42 // https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_01_01
43 "alias",
44 "bg",
45 "cd",
46 "command",
47 "false",
48 "fc",
49 "fg",
50 "getopts",
51 "hash",
52 "jobs",
53 "kill",
54 "newgrp",
55 "pwd",
56 "read",
57 "true",
58 "umask",
59 "unalias",
60 "wait",
61
62 // POSIX Shell special built-ins, obtained in September 2025 from:
63 // https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_14
64 "break",
65 ":",
66 "continue",
67 ".",
68 "eval",
69 "exec",
70 "exit",
71 "export", // NOTE: our parser treats this as a keyword
72 "readonly", // NOTE: our parser treats this as a keyword
73 "return",
74 "set",
75 "shift",
76 "times",
77 "trap",
78 "unset",
79
80 // Bash built-ins which are not present in POSIX, obtained in September 2025 from:
81 // https://man.archlinux.org/man/bash.1.en#SHELL_BUILTIN_COMMANDS
82 "source",
83 "bind",
84 "builtin",
85 "caller",
86 "compgen",
87 "complete",
88 "compopt",
89 "declare", // NOTE: our parser treats this as a keyword
90 "typeset", // NOTE: our parser treats this as a keyword
91 "dirs",
92 "disown",
93 "enable",
94 "history",
95 "help",
96 "let", // NOTE: our parser treats this as a keyword
97 "local",
98 "logout",
99 "mapfile",
100 "readarray",
101 "popd",
102 "pushd",
103 "shopt",
104 "suspend",
105 "type",
106 "ulimit",
107
108 // POSIX utilities which the shell need not provide as built-ins,
109 // so they are separate executables found via PATH, but which we
110 // implement as built-ins just like Bash does. Obtained in September
111 // 2025 from https://pubs.opengroup.org/onlinepubs/9699919799/utilities/contents.html
112 "echo",
113 "printf",
114 "test",
115 "[": // NOTE: an alias for "test", not documented separately
116 return true
117 }
118 return false
119 }
120
121 // TODO: atoi is duplicated in the expand package.
122
123 // atoi is like [strconv.ParseInt](s, 10, 64), but it ignores errors and trims whitespace.
124 func atoi(s string) int64 {
125 s = strings.TrimSpace(s)
126 n, _ := strconv.ParseInt(s, 10, 64)
127 return n
128 }
129
130 type errBuiltinExitStatus exitStatus
131
132 func (e errBuiltinExitStatus) Error() string {
133 return fmt.Sprintf("builtin exit status %d", e.code)
134 }
135
136 // Builtin allows [ExecHandlerFunc] implementations to execute any builtin,
137 // which can be useful for an exec handler to wrap or combine builtin calls.
138 //
139 // Note that a non-nil error may be returned in cases where the builtin
140 // alters the control flow of the runner, even if the builtin did not fail.
141 // For example, this is the case with `exit 0` or `return`.
142 func (hc HandlerContext) Builtin(ctx context.Context, args []string) error {
143 if hc.kind != handlerKindExec {
144 return fmt.Errorf("HandlerContext.Builtin can only be called via an ExecHandlerFunc")
145 }
146 exit := hc.runner.builtin(ctx, hc.Pos, args[0], args[1:])
147 if exit != (exitStatus{}) {
148 return errBuiltinExitStatus(exit)
149 }
150 return nil
151 }
152
153 func (r *Runner) builtin(ctx context.Context, pos syntax.Pos, name string, args []string) (exit exitStatus) {
154 failf := func(code uint8, format string, args ...any) exitStatus {
155 r.errf(format, args...)
156 exit.code = code
157 return exit
158 }
159 switch name {
160 case ":", "true":
161 case "false":
162 exit.code = 1
163 case "help":
164 return r.runHelp(args)
165 case "times":
166 // js/wasm has no per-process CPU accounting at all, so report zeros
167 // in bash's format — shell user/sys, then children user/sys — rather
168 // than fail.
169 // TODO: report real times on platforms that can, via os/exec's
170 // ProcessState or syscall.Getrusage. Not urgent; nothing depends on
171 // the values being non-zero.
172 r.out("0m0.000s 0m0.000s\n0m0.000s 0m0.000s\n")
173 case "exit":
174 switch len(args) {
175 case 0:
176 exit = r.lastExit
177 case 1:
178 n, err := strconv.Atoi(args[0])
179 if err != nil {
180 return failf(2, "invalid exit status code: %q\n", args[0])
181 }
182 exit.code = uint8(n)
183 default:
184 return failf(1, "exit cannot take multiple arguments\n")
185 }
186 exit.exiting = true
187 case "set":
188 if err := Params(args...)(r); err != nil {
189 return failf(2, "set: %v\n", err)
190 }
191 r.updateExpandOpts()
192 case "shift":
193 n := 1
194 switch len(args) {
195 case 0:
196 case 1:
197 if n2, err := strconv.Atoi(args[0]); err == nil {
198 n = n2
199 break
200 }
201 fallthrough
202 default:
203 return failf(2, "usage: shift [n]\n")
204 }
205 if n >= len(r.Params) {
206 r.Params = nil
207 } else {
208 r.Params = r.Params[n:]
209 }
210 case "unset":
211 vars := true
212 funcs := true
213 unsetOpts:
214 for i, arg := range args {
215 switch arg {
216 case "-v":
217 funcs = false
218 case "-f":
219 vars = false
220 default:
221 args = args[i:]
222 break unsetOpts
223 }
224 }
225
226 for _, arg := range args {
227 if name, sub, ok := cutElemSubscript(arg); vars && ok {
228 r.unsetElem(name, sub)
229 } else if vars && r.lookupVar(arg).IsSet() {
230 r.delVar(arg)
231 } else if _, ok := r.Funcs[arg]; ok && funcs {
232 delete(r.Funcs, arg)
233 }
234 }
235 case "echo":
236 newline, doExpand := true, false
237 echoOpts:
238 for len(args) > 0 {
239 switch args[0] {
240 case "-n":
241 newline = false
242 case "-e":
243 doExpand = true
244 case "-E": // default
245 default:
246 break echoOpts
247 }
248 args = args[1:]
249 }
250 for i, arg := range args {
251 if i > 0 {
252 r.out(" ")
253 }
254 if doExpand {
255 arg, _, _ = expand.Format(r.ecfg, arg, nil)
256 }
257 r.out(arg)
258 }
259 if newline {
260 r.out("\n")
261 }
262 case "printf":
263 if len(args) == 0 {
264 return failf(2, "usage: printf format [arguments]\n")
265 }
266 format, args := args[0], args[1:]
267 for {
268 s, n, err := expand.Format(r.ecfg, format, args)
269 if err != nil {
270 return failf(1, "%v\n", err)
271 }
272 r.out(s)
273 args = args[n:]
274 if n == 0 || len(args) == 0 {
275 break
276 }
277 }
278 case "break", "continue":
279 if !r.inLoop {
280 return failf(0, "%s is only useful in a loop\n", name)
281 }
282 enclosing := &r.breakEnclosing
283 if name == "continue" {
284 enclosing = &r.contnEnclosing
285 }
286 switch len(args) {
287 case 0:
288 *enclosing = 1
289 case 1:
290 if n, err := strconv.Atoi(args[0]); err == nil {
291 *enclosing = n
292 break
293 }
294 fallthrough
295 default:
296 return failf(2, "usage: %s [n]\n", name)
297 }
298 case "pwd":
299 evalSymlinks := false
300 for len(args) > 0 {
301 switch args[0] {
302 case "-L":
303 evalSymlinks = false
304 case "-P":
305 evalSymlinks = true
306 default:
307 return failf(2, "invalid option: %q\n", args[0])
308 }
309 args = args[1:]
310 }
311 pwd := r.envGet("PWD")
312 if evalSymlinks {
313 var err error
314 pwd, err = filepath.EvalSymlinks(pwd)
315 if err != nil {
316 exit.fatal(err) // perhaps overly dramatic?
317 return exit
318 }
319 }
320 r.outf("%s\n", pwd)
321 case "cd":
322 var path string
323 switch len(args) {
324 case 0:
325 path = r.envGet("HOME")
326 case 1:
327 path = args[0]
328
329 // replicate the commonly implemented behavior of `cd -`
330 // ref: https://www.man7.org/linux/man-pages/man1/cd.1p.html#OPERANDS
331 if path == "-" {
332 path = r.envGet("OLDPWD")
333 r.outf("%s\n", path)
334 }
335 default:
336 return failf(2, "usage: cd [dir]\n")
337 }
338 exit.code = r.changeDir(ctx, "cd", path)
339 case "wait":
340 fp := flagParser{remaining: args}
341 for fp.more() {
342 switch flag := fp.flag(); flag {
343 case "-n", "-p":
344 return failf(2, "wait: unsupported option %q\n", flag)
345 default:
346 return failf(2, "wait: invalid option %q\n", flag)
347 }
348 }
349 if len(args) == 0 {
350 // Note that "wait" without arguments always returns exit status zero.
351 for _, bg := range r.bgProcs {
352 <-bg.done
353 }
354 break
355 }
356 for _, arg := range args {
357 arg, ok := strings.CutPrefix(arg, "g")
358 pid := atoi(arg)
359 if !ok || pid <= 0 || pid > int64(len(r.bgProcs)) {
360 return failf(1, "wait: pid %s is not a child of this shell\n", arg)
361 }
362 bg := r.bgProcs[pid-1]
363 <-bg.done
364 exit = *bg.exit
365 }
366 case "builtin":
367 if len(args) < 1 {
368 break
369 }
370 if !IsBuiltin(args[0]) {
371 exit.code = 1
372 return exit
373 }
374 exit = r.builtin(ctx, pos, args[0], args[1:])
375 case "type":
376 anyNotFound := false
377 mode := ""
378 fp := flagParser{remaining: args}
379 for fp.more() {
380 switch flag := fp.flag(); flag {
381 case "-a", "-f", "--help":
382 return failf(3, "type: NOT IMPLEMENTED\n")
383 case "-p", "-P", "-t":
384 mode = flag
385 default:
386 return failf(2, "type: invalid option %q\n", flag)
387 }
388 }
389 args := fp.args()
390 for _, arg := range args {
391 if mode == "-p" || mode == "-P" {
392 if path, err := LookPathDir(r.Dir, r.writeEnv, arg); err == nil {
393 r.outf("%s\n", path)
394 } else {
395 anyNotFound = true
396 }
397 continue
398 }
399 if syntax.IsKeyword(arg) {
400 if mode == "-t" {
401 r.out("keyword\n")
402 } else {
403 r.outf("%s is a shell keyword\n", arg)
404 }
405 continue
406 }
407 if als, ok := r.alias[arg]; ok && r.opts[optExpandAliases] {
408 var buf bytes.Buffer
409 if len(als.args) > 0 {
410 printer := syntax.NewPrinter()
411 printer.Print(&buf, &syntax.CallExpr{
412 Args: als.args,
413 })
414 }
415 if als.blank {
416 buf.WriteByte(' ')
417 }
418 if mode == "-t" {
419 r.out("alias\n")
420 } else {
421 r.outf("%s is aliased to `%s'\n", arg, &buf)
422 }
423 continue
424 }
425 if _, ok := r.Funcs[arg]; ok {
426 if mode == "-t" {
427 r.out("function\n")
428 } else {
429 r.outf("%s is a function\n", arg)
430 }
431 continue
432 }
433 if IsBuiltin(arg) {
434 if mode == "-t" {
435 r.out("builtin\n")
436 } else {
437 r.outf("%s is a shell builtin\n", arg)
438 }
439 continue
440 }
441 if path, err := LookPathDir(r.Dir, r.writeEnv, arg); err == nil {
442 if mode == "-t" {
443 r.out("file\n")
444 } else {
445 r.outf("%s is %s\n", arg, path)
446 }
447 continue
448 }
449 if mode != "-t" {
450 r.errf("type: %s: not found\n", arg)
451 }
452 anyNotFound = true
453 }
454 if anyNotFound {
455 exit.code = 1
456 }
457 case "hash":
458 // TODO: implement. for now, having this as a no-op is better than nothing.
459 case "eval":
460 src := strings.Join(args, " ")
461 p := syntax.NewParser()
462 file, err := p.Parse(strings.NewReader(src), "")
463 if err != nil {
464 return failf(1, "eval: %v\n", err)
465 }
466 r.stmts(ctx, file.Stmts)
467 exit = r.exit
468 case "source", ".":
469 if len(args) < 1 {
470 return failf(2, "%v: source: need filename\n", pos)
471 }
472 path, err := scriptFromPathDir(r.Dir, r.writeEnv, args[0])
473 if err != nil {
474 // If the script was not found in PATH or there was any error, pass
475 // the source path to the open handler so it has a chance to look
476 // at files it manages (eg: virtual filesystem), and also allow
477 // it to look for the sourced script in the current directory.
478 path = args[0]
479 }
480 f, err := r.open(ctx, path, os.O_RDONLY, 0, false)
481 if err != nil {
482 return failf(1, "source: %v\n", err)
483 }
484 defer f.Close()
485 p := syntax.NewParser()
486 file, err := p.Parse(f, path)
487 if err != nil {
488 return failf(1, "source: %v\n", err)
489 }
490
491 // Keep the current versions of some fields we might modify.
492 oldParams := r.Params
493 oldSourceSetParams := r.sourceSetParams
494 oldInSource := r.inSource
495
496 // If we run "source file args...", set said args as parameters.
497 // Otherwise, keep the current parameters.
498 sourceArgs := len(args[1:]) > 0
499 if sourceArgs {
500 r.Params = args[1:]
501 r.sourceSetParams = false
502 }
503 // We want to track if the sourced file explicitly sets the
504 // parameters.
505 r.sourceSetParams = false
506 r.inSource = true // know that we're inside a sourced script.
507 r.stmts(ctx, file.Stmts)
508
509 // If we modified the parameters and the sourced file didn't
510 // explicitly set them, we restore the old ones.
511 if sourceArgs && !r.sourceSetParams {
512 r.Params = oldParams
513 }
514 r.sourceSetParams = oldSourceSetParams
515 r.inSource = oldInSource
516
517 exit = r.exit
518 exit.returning = false
519 case "[":
520 if len(args) == 0 || args[len(args)-1] != "]" {
521 return failf(2, "%v: [: missing matching ]\n", pos)
522 }
523 args = args[:len(args)-1]
524 fallthrough
525 case "test":
526 parseErr := false
527 p := testParser{
528 rem: args,
529 err: func(err error) {
530 r.errf("%v: %v\n", pos, err)
531 parseErr = true
532 },
533 }
534 p.next()
535 expr := p.classicTest("[", false)
536 if parseErr {
537 exit.code = 2
538 return exit
539 }
540 exit.oneIf(r.bashTest(ctx, expr, true) == "")
541 case "exec":
542 // TODO: Consider unix.Exec, i.e. actually replacing
543 // the process. It's in theory what a shell should do,
544 // but in practice it would kill the entire Go process
545 // and it's not available on Windows.
546 if len(args) == 0 {
547 r.keepRedirs = true
548 break
549 }
550 r.exit.exiting = true
551 r.exec(ctx, pos, args)
552 exit = r.exit
553 case "command":
554 show := false
555 fp := flagParser{remaining: args}
556 for fp.more() {
557 switch flag := fp.flag(); flag {
558 case "-v":
559 show = true
560 default:
561 return failf(2, "command: invalid option %q\n", flag)
562 }
563 }
564 args := fp.args()
565 if len(args) == 0 {
566 break
567 }
568 if !show {
569 if IsBuiltin(args[0]) {
570 return r.builtin(ctx, pos, args[0], args[1:])
571 }
572 r.exec(ctx, pos, args)
573 exit = r.exit
574 return exit
575 }
576 last := uint8(0)
577 for _, arg := range args {
578 last = 0
579 if r.Funcs[arg] != nil || IsBuiltin(arg) {
580 r.outf("%s\n", arg)
581 } else if path, err := LookPathDir(r.Dir, r.writeEnv, arg); err == nil {
582 r.outf("%s\n", path)
583 } else {
584 last = 1
585 }
586 }
587 exit.code = last
588 case "dirs":
589 for i, dir := range slices.Backward(r.dirStack) {
590 r.outf("%s", dir)
591 if i > 0 {
592 r.out(" ")
593 }
594 }
595 r.out("\n")
596 case "pushd":
597 change := true
598 if len(args) > 0 && args[0] == "-n" {
599 change = false
600 args = args[1:]
601 }
602 swap := func() string {
603 oldtop := r.dirStack[len(r.dirStack)-1]
604 top := r.dirStack[len(r.dirStack)-2]
605 r.dirStack[len(r.dirStack)-1] = top
606 r.dirStack[len(r.dirStack)-2] = oldtop
607 return top
608 }
609 switch len(args) {
610 case 0:
611 if !change {
612 break
613 }
614 if len(r.dirStack) < 2 {
615 return failf(1, "pushd: no other directory\n")
616 }
617 newtop := swap()
618 if code := r.changeDir(ctx, "pushd", newtop); code != 0 {
619 exit.code = code
620 return exit
621 }
622 r.builtin(ctx, syntax.Pos{}, "dirs", nil)
623 case 1:
624 if change {
625 if code := r.changeDir(ctx, "pushd", args[0]); code != 0 {
626 exit.code = code
627 return exit
628 }
629 r.dirStack = append(r.dirStack, r.Dir)
630 } else {
631 r.dirStack = append(r.dirStack, args[0])
632 swap()
633 }
634 r.builtin(ctx, syntax.Pos{}, "dirs", nil)
635 default:
636 return failf(2, "pushd: too many arguments\n")
637 }
638 case "popd":
639 change := true
640 if len(args) > 0 && args[0] == "-n" {
641 change = false
642 args = args[1:]
643 }
644 switch len(args) {
645 case 0:
646 if len(r.dirStack) < 2 {
647 return failf(1, "popd: directory stack empty\n")
648 }
649 oldtop := r.dirStack[len(r.dirStack)-1]
650 r.dirStack = r.dirStack[:len(r.dirStack)-1]
651 if change {
652 newtop := r.dirStack[len(r.dirStack)-1]
653 if code := r.changeDir(ctx, "popd", newtop); code != 0 {
654 exit.code = code
655 return exit
656 }
657 } else {
658 r.dirStack[len(r.dirStack)-1] = oldtop
659 }
660 r.builtin(ctx, syntax.Pos{}, "dirs", nil)
661 default:
662 return failf(2, "popd: invalid argument\n")
663 }
664 case "return":
665 if !r.inFunc && !r.inSource {
666 return failf(1, "return: can only be done from a func or sourced script\n")
667 }
668 switch len(args) {
669 case 0:
670 case 1:
671 n, err := strconv.Atoi(args[0])
672 if err != nil {
673 return failf(2, "invalid return status code: %q\n", args[0])
674 }
675 exit.code = uint8(n)
676 default:
677 return failf(2, "return: too many arguments\n")
678 }
679 exit.returning = true
680 case "read":
681 var prompt string
682 raw := false
683 silent := false
684 readArray := false
685 fp := flagParser{remaining: args}
686 for fp.more() {
687 switch flag := fp.flag(); flag {
688 case "-s":
689 silent = true
690 case "-r":
691 raw = true
692 case "-a":
693 readArray = true
694 case "-p":
695 prompt = fp.value()
696 if prompt == "" {
697 return failf(2, "read: -p: option requires an argument\n")
698 }
699 default:
700 return failf(2, "read: invalid option %q\n", flag)
701 }
702 }
703
704 args := fp.args()
705 for _, name := range args {
706 if !syntax.ValidName(name) {
707 return failf(2, "read: invalid identifier %q\n", name)
708 }
709 }
710
711 if prompt != "" {
712 r.out(prompt)
713 }
714
715 var line []byte
716 var err error
717 fd, terminal := -1, false
718 if silent {
719 fd, terminal = stdinTerminal(r.stdin)
720 }
721 if terminal {
722 // Only a terminal echoes what we read, so it is the only case
723 // where we need to read without echoing.
724 line, err = term.ReadPassword(fd)
725 } else {
726 line, err = r.readLine(ctx, raw)
727 }
728 if readArray {
729 // read -a arrayname: split line into fields and assign to indexed array.
730 arrayName := shellReplyVar
731 if len(args) > 0 {
732 arrayName = args[0]
733 }
734 // Use -1 as max to get all fields without joining the last ones.
735 values := expand.ReadFields(r.ecfg, string(line), -1, raw)
736 r.setVar(arrayName, expand.Variable{
737 Set: true,
738 Kind: expand.Indexed,
739 List: values,
740 })
741 } else if len(args) == 0 {
742 // Bare "read" assigns the whole line to REPLY without any
743 // trimming, only discarding backslash escapes unless raw.
744 val := string(line)
745 if !raw {
746 var sb strings.Builder
747 esc := false
748 for i := range len(val) {
749 if val[i] == '\\' && !esc {
750 esc = true
751 continue
752 }
753 sb.WriteByte(val[i])
754 esc = false
755 }
756 val = sb.String()
757 }
758 r.setVarString(shellReplyVar, val)
759 } else {
760 values := expand.ReadFields(r.ecfg, string(line), len(args), raw)
761 for i, name := range args {
762 val := ""
763 if i < len(values) {
764 val = values[i]
765 }
766 r.setVarString(name, val)
767 }
768 }
769
770 // We can get data back from readLine and an error at the same time, so
771 // check err after we process the data.
772 if err != nil {
773 exit.code = 1
774 return exit
775 }
776
777 case "getopts":
778 if len(args) < 2 {
779 return failf(2, "getopts: usage: getopts optstring name [arg ...]\n")
780 }
781 optind, _ := strconv.Atoi(r.envGet("OPTIND"))
782 if optind-1 != r.optState.argidx {
783 if optind < 1 {
784 optind = 1
785 }
786 r.optState = getopts{argidx: optind - 1}
787 }
788 optstr := args[0]
789 name := args[1]
790 if !syntax.ValidName(name) {
791 return failf(2, "getopts: invalid identifier: %q\n", name)
792 }
793 args = args[2:]
794 if len(args) == 0 {
795 args = r.Params
796 }
797 diagnostics := !strings.HasPrefix(optstr, ":")
798
799 opt, optarg, done := r.optState.next(optstr, args)
800
801 r.setVarString(name, string(opt))
802 r.delVar("OPTARG")
803 switch {
804 case opt == '?' && diagnostics && !done:
805 r.errf("getopts: illegal option -- %q\n", optarg)
806 case opt == ':' && diagnostics:
807 r.errf("getopts: option requires an argument -- %q\n", optarg)
808 default:
809 if optarg != "" {
810 r.setVarString("OPTARG", optarg)
811 }
812 }
813 if optind-1 != r.optState.argidx {
814 r.setVarString("OPTIND", strconv.FormatInt(int64(r.optState.argidx+1), 10))
815 }
816
817 exit.oneIf(done)
818
819 case "shopt":
820 mode := ""
821 posixOpts := false
822 fp := flagParser{remaining: args}
823 for fp.more() {
824 switch flag := fp.flag(); flag {
825 case "-s", "-u":
826 mode = flag
827 case "-o":
828 posixOpts = true
829 case "-p", "-q":
830 return failf(2, "shopt: unsupported option %q\n", flag)
831 default:
832 return failf(2, "shopt: invalid option %q\n", flag)
833 }
834 }
835 args := fp.args()
836 if len(args) == 0 {
837 if posixOpts {
838 for i, opt := range &posixOptsTable {
839 r.printOptLine(opt.name, r.opts[i], true)
840 }
841 } else {
842 for i, opt := range bashOptsTable {
843 r.printOptLine(opt.name, r.opts[len(posixOptsTable)+i], opt.supported)
844 }
845 }
846 break
847 }
848 for _, arg := range args {
849 opt, supported := (*bool)(nil), true
850 if posixOpts {
851 opt = r.posixOptByName(arg)
852 } else {
853 opt, supported = r.bashOptByName(arg)
854 }
855 if opt == nil {
856 return failf(1, "shopt: invalid option name %q\n", arg)
857 }
858
859 switch mode {
860 case "-s", "-u":
861 if !supported {
862 return failf(1, "shopt: unsupported option %q\n", arg)
863 }
864 *opt = mode == "-s"
865 default: // ""
866 r.printOptLine(arg, *opt, supported)
867 }
868 }
869 r.updateExpandOpts()
870
871 case "alias":
872 show := func(name string, als alias) {
873 var buf bytes.Buffer
874 if len(als.args) > 0 {
875 printer := syntax.NewPrinter()
876 printer.Print(&buf, &syntax.CallExpr{
877 Args: als.args,
878 })
879 }
880 if als.blank {
881 buf.WriteByte(' ')
882 }
883 r.outf("alias %s='%s'\n", name, &buf)
884 }
885
886 if len(args) == 0 {
887 for name, als := range r.alias {
888 show(name, als)
889 }
890 }
891 argsLoop:
892 for _, arg := range args {
893 name, src, ok := strings.Cut(arg, "=")
894 if !ok {
895 als, ok := r.alias[name]
896 if !ok {
897 r.errf("alias: %q not found\n", name)
898 continue
899 }
900 show(name, als)
901 continue
902 }
903
904 // TODO: parse any CallExpr perhaps, or even any Stmt
905 parser := syntax.NewParser()
906 var words []*syntax.Word
907 for w, err := range parser.WordsSeq(strings.NewReader(src)) {
908 if err != nil {
909 r.errf("alias: could not parse %q: %v\n", src, err)
910 continue argsLoop
911 }
912 words = append(words, w)
913 }
914
915 if r.alias == nil {
916 r.alias = make(map[string]alias)
917 }
918 r.alias[name] = alias{
919 args: words,
920 blank: strings.TrimRight(src, " \t") != src,
921 }
922 }
923 case "unalias":
924 for _, name := range args {
925 delete(r.alias, name)
926 }
927
928 case "trap":
929 fp := flagParser{remaining: args}
930 callback := "-"
931 for fp.more() {
932 switch flag := fp.flag(); flag {
933 case "-l", "-p":
934 return failf(2, "trap: %q: NOT IMPLEMENTED flag\n", flag)
935 case "-":
936 // default signal
937 default:
938 r.errf("trap: %q: invalid option\n", flag)
939 r.errf("trap: usage: trap [-lp] [[arg] signal_spec ...]\n")
940 exit.code = 2
941 return exit
942 }
943 }
944 args := fp.args()
945 switch len(args) {
946 case 0:
947 // Print non-default signals
948 if r.callbackExit != "" {
949 r.outf("trap -- %q EXIT\n", r.callbackExit)
950 }
951 if r.callbackErr != "" {
952 r.outf("trap -- %q ERR\n", r.callbackErr)
953 }
954 case 1:
955 // assume it's a signal, the default will be restored
956 default:
957 callback = args[0]
958 args = args[1:]
959 }
960 // For now, treat both empty and - the same since ERR and EXIT have no
961 // default callback.
962 if callback == "-" {
963 callback = ""
964 }
965 for _, arg := range args {
966 switch arg {
967 case "ERR":
968 r.callbackErr = callback
969 case "EXIT":
970 r.callbackExit = callback
971 default:
972 return failf(2, "trap: %s: invalid signal specification\n", arg)
973 }
974 }
975
976 case "readarray", "mapfile":
977 dropDelim := false
978 delim := "\n"
979 fp := flagParser{remaining: args}
980 for fp.more() {
981 switch flag := fp.flag(); flag {
982 case "-t":
983 // Remove the delim from each line read
984 dropDelim = true
985 case "-d":
986 if len(fp.remaining) == 0 {
987 return failf(2, "%s: -d: option requires an argument\n", name)
988 }
989 delim = fp.value()
990 if delim == "" {
991 // Bash sets the delim to an ASCII NUL if provided with an empty
992 // string.
993 delim = "\x00"
994 }
995 default:
996 return failf(2, "%s: invalid option %q\n", name, flag)
997 }
998 }
999
1000 args := fp.args()
1001 var arrayName string
1002 switch len(args) {
1003 case 0:
1004 arrayName = "MAPFILE"
1005 case 1:
1006 if !syntax.ValidName(args[0]) {
1007 return failf(2, "%s: invalid identifier %q\n", name, args[0])
1008 }
1009 arrayName = args[0]
1010 default:
1011 return failf(2, "%s: Only one array name may be specified, %v\n", name, args)
1012 }
1013
1014 var vr expand.Variable
1015 vr.Kind = expand.Indexed
1016 scanner := bufio.NewScanner(r.stdin)
1017 scanner.Split(mapfileSplit(delim[0], dropDelim))
1018 for scanner.Scan() {
1019 vr.List = append(vr.List, scanner.Text())
1020 }
1021 if err := scanner.Err(); err != nil {
1022 return failf(2, "%s: unable to read, %v\n", name, err)
1023 }
1024 r.setVar(arrayName, vr)
1025
1026 default:
1027 return failf(2, "%s: unsupported builtin\n", name)
1028 }
1029 return exit
1030 }
1031
1032 // mapfileSplit returns a suitable Split function for a [bufio.Scanner];
1033 // the code is mostly stolen from [bufio.ScanLines].
1034 func mapfileSplit(delim byte, dropDelim bool) bufio.SplitFunc {
1035 return func(data []byte, atEOF bool) (advance int, token []byte, err error) {
1036 if atEOF && len(data) == 0 {
1037 return 0, nil, nil
1038 }
1039 if i := bytes.IndexByte(data, delim); i >= 0 {
1040 // We have a full newline-terminated line.
1041 if dropDelim {
1042 return i + 1, data[0:i], nil
1043 } else {
1044 return i + 1, data[0 : i+1], nil
1045 }
1046 }
1047 // If we're at EOF, we have a final, non-terminated line. Return it.
1048 if atEOF {
1049 return len(data), data, nil
1050 }
1051 // Request more data.
1052 return 0, nil, nil
1053 }
1054 }
1055
1056 func (r *Runner) printOptLine(name string, enabled, supported bool) {
1057 state := r.optStatusText(enabled)
1058 if supported {
1059 r.outf("%s\t%s\n", name, state)
1060 return
1061 }
1062 r.outf("%s\t%s\t(%q not supported)\n", name, state, r.optStatusText(!enabled))
1063 }
1064
1065 func (r *Runner) readLine(ctx context.Context, raw bool) ([]byte, error) {
1066 if r.stdin == nil {
1067 return nil, errors.New("interp: can't read, there's no stdin")
1068 }
1069
1070 var line []byte
1071 esc := false
1072
1073 stopc := make(chan struct{})
1074 stop := context.AfterFunc(ctx, func() {
1075 r.stdin.SetReadDeadline(time.Now())
1076 close(stopc)
1077 })
1078 defer func() {
1079 if !stop() {
1080 // The AfterFunc was started.
1081 // Wait for it to complete, and reset the file's deadline.
1082 <-stopc
1083 r.stdin.SetReadDeadline(time.Time{})
1084 }
1085 }()
1086 for {
1087 var buf [1]byte
1088 n, err := r.stdin.Read(buf[:])
1089 if n > 0 {
1090 b := buf[0]
1091 switch {
1092 case !raw && b == '\\':
1093 line = append(line, b)
1094 esc = !esc
1095 case !raw && b == '\n' && esc:
1096 // line continuation; drop the trailing backslash
1097 line = line[:len(line)-1]
1098 esc = false
1099 case b == '\n':
1100 return line, nil
1101 default:
1102 line = append(line, b)
1103 esc = false
1104 }
1105 }
1106 if err != nil {
1107 return line, err
1108 }
1109 }
1110 }
1111
1112 func (r *Runner) changeDir(ctx context.Context, cmd, path string) uint8 {
1113 if path == "" {
1114 r.errf("%s: empty directory path\n", cmd)
1115 return 1
1116 }
1117 apath := r.absPath(path)
1118 info, err := r.stat(ctx, apath)
1119 if err != nil || !info.IsDir() {
1120 r.errf("%s: no such file or directory: %q\n", cmd, path)
1121 return 1
1122 }
1123 if r.access(ctx, apath, AccessExec) != nil {
1124 r.errf("%s: permission denied: %q\n", cmd, path)
1125 return 1
1126 }
1127 r.Dir = apath
1128 r.setVarString("OLDPWD", r.envGet("PWD"))
1129 r.setVarString("PWD", apath)
1130 return 0
1131 }
1132
1133 func absPath(dir, path string) string {
1134 if path == "" {
1135 return ""
1136 }
1137 if !filepath.IsAbs(path) {
1138 path = filepath.Join(dir, path)
1139 }
1140 // Note that [filepath.Join] cleans its result, but an already absolute
1141 // path needs cleaning too, such as turning "/a/../b" into "/b".
1142 return filepath.Clean(path)
1143 }
1144
1145 func (r *Runner) absPath(path string) string {
1146 return absPath(r.Dir, path)
1147 }
1148
1149 // flagParser is used to parse builtin flags.
1150 //
1151 // It's similar to the getopts implementation, but with some key differences.
1152 // First, the API is designed for Go loops, making it easier to use directly.
1153 // Second, it doesn't require the awkward ":ab" syntax that getopts uses.
1154 // Third, it supports "-a" flags as well as "+a".
1155 type flagParser struct {
1156 current string
1157 remaining []string
1158 }
1159
1160 func (p *flagParser) more() bool {
1161 if p.current != "" {
1162 // We're still parsing part of "-ab".
1163 return true
1164 }
1165 if len(p.remaining) == 0 {
1166 // Nothing left.
1167 p.remaining = nil
1168 return false
1169 }
1170 arg := p.remaining[0]
1171 if arg == "--" {
1172 // We explicitly stop parsing flags.
1173 p.remaining = p.remaining[1:]
1174 return false
1175 }
1176 if len(arg) == 0 || (arg[0] != '-' && arg[0] != '+') {
1177 // The next argument is not a flag.
1178 return false
1179 }
1180 // More flags to come.
1181 return true
1182 }
1183
1184 func (p *flagParser) flag() string {
1185 arg := p.current
1186 if arg == "" {
1187 arg = p.remaining[0]
1188 p.remaining = p.remaining[1:]
1189 } else {
1190 p.current = ""
1191 }
1192 if len(arg) > 2 {
1193 // We have "-ab", so return "-a" and keep "-b".
1194 p.current = arg[:1] + arg[2:]
1195 arg = arg[:2]
1196 }
1197 return arg
1198 }
1199
1200 func (p *flagParser) value() string {
1201 if len(p.remaining) == 0 {
1202 return ""
1203 }
1204 arg := p.remaining[0]
1205 p.remaining = p.remaining[1:]
1206 return arg
1207 }
1208
1209 func (p *flagParser) args() []string { return p.remaining }
1210
1211 type getopts struct {
1212 argidx int
1213 runeidx int
1214 }
1215
1216 func (g *getopts) next(optstr string, args []string) (opt rune, optarg string, done bool) {
1217 if len(args) == 0 || g.argidx >= len(args) {
1218 return '?', "", true
1219 }
1220 arg := []rune(args[g.argidx])
1221 if len(arg) < 2 || arg[0] != '-' || arg[1] == '-' {
1222 return '?', "", true
1223 }
1224
1225 opts := arg[1:]
1226 opt = opts[g.runeidx]
1227
1228 i := strings.IndexRune(optstr, opt)
1229 if i >= 0 && i+1 < len(optstr) && optstr[i+1] == ':' {
1230 // the option requires an argument
1231 if g.runeidx+1 < len(opts) {
1232 // attached to the option in the same word, like -bval
1233 optarg = string(opts[g.runeidx+1:])
1234 } else if g.argidx+1 < len(args) {
1235 // the word that follows
1236 optarg = args[g.argidx+1]
1237 g.argidx++
1238 } else {
1239 // missing argument
1240 g.argidx++
1241 g.runeidx = 0
1242 return ':', string(opt), false
1243 }
1244 g.argidx++
1245 g.runeidx = 0
1246 return opt, optarg, false
1247 }
1248
1249 if g.runeidx+1 < len(opts) {
1250 g.runeidx++
1251 } else {
1252 g.argidx++
1253 g.runeidx = 0
1254 }
1255 if i < 0 {
1256 // invalid option
1257 return '?', string(opt), false
1258 }
1259 return opt, "", false
1260 }
1261
1262 // optStatusText returns a shell option's status text display
1263 func (r *Runner) optStatusText(status bool) string {
1264 if status {
1265 return "on"
1266 }
1267 return "off"
1268 }