返回 CodeWhale
shell_expand.rs
根目录 / crates / execpolicy / src / shell_expand.rs
1 //! Expand a shell command line into the set of commands a shell would run.
2 //!
3 //! Deny rules are the one gate that holds under `AskForApproval::Never`, so
4 //! they cannot be matched against the raw command string: the string a user
5 //! types and the set of commands the shell executes are different things. A
6 //! command substitution runs its body (`` `rm -rf /` ``, `$(rm -rf /)`), a
7 //! quoted argument executes with the quotes removed (`rm -rf "/"`), and a
8 //! wrapper hands its payload straight back to a shell (`bash -c '…'`,
9 //! `eval '…'`, `sudo …`).
10 //!
11 //! Matching one string pattern per metacharacter loses that race by
12 //! construction — every new quoting or wrapping form is another bypass. This
13 //! module instead tokenizes the command the way a POSIX shell word-splits it
14 //! and returns *every* command line that would actually be executed, so deny
15 //! rules can be matched against each one.
16 //!
17 //! Deliberately conservative in the deny direction: when a construct is
18 //! ambiguous the expander emits extra candidate command lines rather than
19 //! fewer. Over-emitting only makes deny matching stricter — `denied_prefix_matches`
20 //! stays anchored at the first positional token, so an extra candidate that no
21 //! rule names is inert. Under-emitting is a bypass.
22 //!
23 //! What it does *not* do is evaluate anything: `$VAR` is left as literal text,
24 //! and single-quoted text is never treated as code (`echo '` + "`" + `rm -rf /`" +
25 //! "`" + `'` really does just print). Fidelity to shell semantics is the point in
26 //! both directions.
27 //!
28 //! Because nothing is evaluated, some command words cannot be known without
29 //! running the shell: a parameter or command substitution (`$v`, `${v}`,
30 //! `$(…)`), a glob or brace expansion (`r[m]`, `{rm,-f,x}`), ANSI-C escapes,
31 //! a command word that is not a plain literal (`=rm`, `/bin/(r)m`), a builtin
32 //! that rebinds names (`alias`, `hash x=…`, `setopt`), and a shell that reads
33 //! its script from a pipe, a here-string, or a process substitution.
34 //! [`Expansion::dynamic`] reports that case so the policy engine
35 //! can fail closed instead of matching deny rules against text the shell will
36 //! rewrite. [`Expansion::nested`] reports that some code runs inside another
37 //! command (a substitution, `eval`, a `-c` payload, `find -exec`), which is
38 //! never covered by an allow rule written for the outer command.
39 //!
40 //! Known limits: a script *file* (`bash ./x.sh`, `. ./env.sh`) is opaque
41 //! (a descriptor path such as `/dev/stdin` is not a file: it is dynamic), as
42 //! is any program that interprets its arguments as code (`python -c`, `ssh
43 //! host cmd`, `git -c alias.x=!cmd`). Aliases and functions defined in an
44 //! earlier call are not tracked. Arithmetic contexts (`(( ))`, `$(( ))`,
45 //! `let`, `[[ … -eq … ]]`) evaluate the *values* of variables they name, so a
46 //! value holding `a[$(cmd)]` runs `cmd` without it appearing in the text.
47 //! `cmd /c` and PowerShell `-Command` payloads are scanned with this POSIX
48 //! grammar, which finds their command words but not every cmd.exe or
49 //! PowerShell construct.
50
51 use std::collections::{HashMap, HashSet};
52
53 /// Maximum nesting depth followed through substitutions and `-c` payloads.
54 const MAX_DEPTH: usize = 8;
55
56 /// Upper bound on emitted command lines, so a pathological input cannot turn
57 /// one policy check into unbounded work.
58 const MAX_COMMANDS: usize = 256;
59 const MAX_TMUX_WORK: usize = 4 * 1024 * 1024;
60 const TMUX_PROMPT_INPUTS: usize = 9;
61
62 /// Upper bound on the parser states explored while locating the real command
63 /// word behind wrapper words. Running out marks the command unresolved.
64 const MAX_HEAD_STATES: usize = 512;
65
66 const MAX_AWK_PROGRAM_BYTES: usize = 64 * 1024;
67 const MAX_AWK_SCAN_STEPS: usize = 8 * MAX_AWK_PROGRAM_BYTES;
68
69 /// A word that prefixes another command rather than being the command: the
70 /// real invocation is what follows. Stripping it keeps `sudo rm -rf /`
71 /// matchable by an `rm -rf /` rule.
72 ///
73 /// The option grammar matters: an option that takes a separate value
74 /// (`sudo -u root`, `timeout -s KILL`) and a required operand
75 /// (`chroot NEWROOT`, `timeout DURATION`) both sit between the wrapper and the
76 /// command it runs. An option missing from the table may or may not take a
77 /// value, so both readings are explored.
78 struct Wrapper {
79 name: &'static str,
80 /// Short options whose value is the rest of the word or the next word.
81 short_values: &'static str,
82 /// Short options known to take no value. Any other short option may or
83 /// may not take one, so both readings are explored.
84 short_switches: &'static str,
85 /// Long options whose value may be the next word.
86 long_values: &'static [&'static str],
87 /// Long options known to take no value.
88 long_switches: &'static [&'static str],
89 /// Required operands before the command (`chroot NEWROOT`).
90 operands: u8,
91 }
92
93 static WRAPPERS: &[Wrapper] = &[
94 Wrapper {
95 name: "sudo",
96 short_values: "ughpCDrtTRUac",
97 short_switches: "AbBEeHiKklNnPSsVv",
98 long_values: &[
99 "user",
100 "group",
101 "host",
102 "prompt",
103 "close-from",
104 "chdir",
105 "role",
106 "type",
107 "command-timeout",
108 "chroot",
109 "other-user",
110 "auth-type",
111 "login-class",
112 ],
113 long_switches: &[
114 "login",
115 "preserve-env",
116 "non-interactive",
117 "background",
118 "edit",
119 "shell",
120 "stdin",
121 "reset-timestamp",
122 "remove-timestamp",
123 "validate",
124 "list",
125 "set-home",
126 "bell",
127 "askpass",
128 "preserve-groups",
129 ],
130 operands: 0,
131 },
132 Wrapper {
133 name: "doas",
134 short_values: "uCa",
135 short_switches: "Lns",
136 long_values: &[],
137 long_switches: &[],
138 operands: 0,
139 },
140 Wrapper {
141 name: "env",
142 short_values: "uCSPa",
143 short_switches: "i0v",
144 long_values: &["unset", "chdir", "argv0"],
145 long_switches: &["ignore-environment", "null", "debug"],
146 operands: 0,
147 },
148 Wrapper {
149 name: "nohup",
150 short_values: "",
151 short_switches: "",
152 long_values: &[],
153 long_switches: &[],
154 operands: 0,
155 },
156 Wrapper {
157 name: "nice",
158 short_values: "n",
159 short_switches: "",
160 long_values: &["adjustment"],
161 long_switches: &[],
162 operands: 0,
163 },
164 Wrapper {
165 name: "ionice",
166 short_values: "cnpPu",
167 short_switches: "t",
168 long_values: &["class", "classdata", "pid", "pgid", "uid"],
169 long_switches: &["ignore"],
170 operands: 0,
171 },
172 Wrapper {
173 name: "time",
174 short_values: "fo",
175 short_switches: "aplqvh",
176 long_values: &["format", "output"],
177 long_switches: &["append", "portability", "verbose", "quiet"],
178 operands: 0,
179 },
180 Wrapper {
181 name: "timeout",
182 short_values: "sk",
183 short_switches: "fpv",
184 long_values: &["signal", "kill-after"],
185 long_switches: &["preserve-status", "foreground", "verbose"],
186 operands: 1,
187 },
188 Wrapper {
189 name: "stdbuf",
190 short_values: "ioe",
191 short_switches: "",
192 long_values: &["input", "output", "error"],
193 long_switches: &[],
194 operands: 0,
195 },
196 Wrapper {
197 name: "setsid",
198 short_values: "",
199 short_switches: "cfw",
200 long_values: &[],
201 long_switches: &["ctty", "fork", "wait"],
202 operands: 0,
203 },
204 Wrapper {
205 name: "command",
206 short_values: "",
207 short_switches: "pvV",
208 long_values: &[],
209 long_switches: &[],
210 operands: 0,
211 },
212 Wrapper {
213 name: "builtin",
214 short_values: "",
215 short_switches: "",
216 long_values: &[],
217 long_switches: &[],
218 operands: 0,
219 },
220 Wrapper {
221 name: "exec",
222 short_values: "a",
223 short_switches: "cl",
224 long_values: &[],
225 long_switches: &[],
226 operands: 0,
227 },
228 Wrapper {
229 name: "xargs",
230 short_values: "adEILnPsJSR",
231 short_switches: "0eiloprtx",
232 long_values: &[
233 "arg-file",
234 "delimiter",
235 "eof",
236 "replace",
237 "max-lines",
238 "max-args",
239 "max-procs",
240 "max-chars",
241 "process-slot-var",
242 ],
243 long_switches: &[
244 "null",
245 "no-run-if-empty",
246 "interactive",
247 "verbose",
248 "exit",
249 "open-tty",
250 "show-limits",
251 ],
252 operands: 0,
253 },
254 Wrapper {
255 name: "unbuffer",
256 short_values: "",
257 short_switches: "p",
258 long_values: &[],
259 long_switches: &[],
260 operands: 0,
261 },
262 Wrapper {
263 name: "busybox",
264 short_values: "",
265 short_switches: "",
266 long_values: &[],
267 long_switches: &[],
268 operands: 0,
269 },
270 Wrapper {
271 name: "chroot",
272 short_values: "ugG",
273 short_switches: "",
274 long_values: &["userspec", "groups"],
275 long_switches: &["skip-chdir"],
276 operands: 1,
277 },
278 Wrapper {
279 name: "proot",
280 short_values: "rbmwqkRSvi",
281 short_switches: "0Vh",
282 long_values: &[
283 "rootfs",
284 "bind",
285 "mount",
286 "cwd",
287 "pwd",
288 "qemu",
289 "kernel-release",
290 "verbose",
291 ],
292 long_switches: &[],
293 operands: 0,
294 },
295 Wrapper {
296 name: "caffeinate",
297 short_values: "tw",
298 short_switches: "dimsu",
299 long_values: &[],
300 long_switches: &[],
301 operands: 0,
302 },
303 Wrapper {
304 name: "arch",
305 short_values: "ed",
306 short_switches: "",
307 long_values: &[],
308 long_switches: &[],
309 operands: 0,
310 },
311 Wrapper {
312 name: "sandbox-exec",
313 short_values: "fnpD",
314 short_switches: "",
315 long_values: &[],
316 long_switches: &[],
317 operands: 0,
318 },
319 Wrapper {
320 name: "noglob",
321 short_values: "",
322 short_switches: "",
323 long_values: &[],
324 long_switches: &[],
325 operands: 0,
326 },
327 Wrapper {
328 name: "nocorrect",
329 short_values: "",
330 short_switches: "",
331 long_values: &[],
332 long_switches: &[],
333 operands: 0,
334 },
335 Wrapper {
336 name: "-",
337 short_values: "",
338 short_switches: "",
339 long_values: &[],
340 long_switches: &[],
341 operands: 0,
342 },
343 Wrapper {
344 name: "nsenter",
345 short_values: "tSG",
346 short_switches: "amuinpUCTrwFZcy",
347 long_values: &["target", "setuid", "setgid"],
348 long_switches: &["all", "preserve-credentials", "no-fork"],
349 operands: 0,
350 },
351 Wrapper {
352 name: "unshare",
353 short_values: "SGRw",
354 short_switches: "mupinUCTrcfk",
355 long_values: &["root", "wd", "setuid", "setgid", "propagation", "setgroups"],
356 long_switches: &[
357 "fork",
358 "mount-proc",
359 "map-root-user",
360 "map-current-user",
361 "kill-child",
362 ],
363 operands: 0,
364 },
365 Wrapper {
366 name: "runuser",
367 short_values: "ugGcswf",
368 short_switches: "lmpP",
369 long_values: &[
370 "user",
371 "group",
372 "supp-group",
373 "command",
374 "shell",
375 "whitelist-environment",
376 "session-command",
377 ],
378 long_switches: &["login", "preserve-environment", "pty"],
379 operands: 0,
380 },
381 Wrapper {
382 name: "flock",
383 short_values: "wEc",
384 short_switches: "sxunoFh",
385 long_values: &["timeout", "wait", "conflict-exit-code", "command"],
386 long_switches: &[
387 "shared",
388 "exclusive",
389 "unlock",
390 "nonblock",
391 "nb",
392 "close",
393 "no-fork",
394 "verbose",
395 ],
396 operands: 1,
397 },
398 Wrapper {
399 name: "watch",
400 short_values: "nq",
401 short_switches: "bcdeghprtwx",
402 long_values: &["interval", "equexit"],
403 long_switches: &[
404 "beep",
405 "color",
406 "no-color",
407 "differences",
408 "errexit",
409 "chgexit",
410 "precise",
411 "no-title",
412 "no-wrap",
413 "exec",
414 ],
415 operands: 0,
416 },
417 Wrapper {
418 name: "wsl",
419 short_values: "du",
420 short_switches: "e",
421 long_values: &["distribution", "user", "cd", "shell-type"],
422 long_switches: &["exec"],
423 operands: 0,
424 }, // Privilege, sandbox, scheduling and tracing launchers: each runs its
425 // operands as a command.
426 Wrapper {
427 name: "pkexec",
428 short_values: "",
429 short_switches: "",
430 long_values: &["user"],
431 long_switches: &["disable-internal-agent", "keep-cwd"],
432 operands: 0,
433 },
434 Wrapper {
435 name: "run0",
436 short_values: "ugD",
437 short_switches: "",
438 long_values: &[
439 "user",
440 "group",
441 "nice",
442 "chdir",
443 "setenv",
444 "unit",
445 "property",
446 "description",
447 "slice",
448 "machine",
449 ],
450 long_switches: &["no-ask-password", "background", "pty", "pipe"],
451 operands: 0,
452 },
453 Wrapper {
454 name: "fakeroot",
455 short_values: "lsib",
456 short_switches: "uhv",
457 long_values: &["lib", "faked"],
458 long_switches: &["unknown-is-real"],
459 operands: 0,
460 },
461 Wrapper {
462 name: "taskset",
463 short_values: "",
464 short_switches: "acpV",
465 long_values: &[],
466 long_switches: &["all-tasks", "cpu-list", "pid"],
467 operands: 1,
468 },
469 Wrapper {
470 name: "chrt",
471 short_values: "TPD",
472 short_switches: "abdefimoprRv",
473 long_values: &["sched-runtime", "sched-period", "sched-deadline"],
474 long_switches: &[
475 "all-tasks",
476 "batch",
477 "deadline",
478 "fifo",
479 "idle",
480 "other",
481 "pid",
482 "rr",
483 "reset-on-fork",
484 "verbose",
485 "max",
486 ],
487 operands: 1,
488 },
489 Wrapper {
490 name: "prlimit",
491 short_values: "po",
492 short_switches: "",
493 long_values: &["pid", "output"],
494 long_switches: &["noheadings", "raw", "verbose"],
495 operands: 0,
496 },
497 Wrapper {
498 name: "strace",
499 short_values: "abeIoOpPsSuEX",
500 short_switches: "cCdDfFhikNqrtTvVwxyYzZ",
501 long_values: &[
502 "output",
503 "expr",
504 "trace",
505 "signal",
506 "status",
507 "attach",
508 "user",
509 "env",
510 "string-limit",
511 "trace-path",
512 ],
513 long_switches: &[
514 "follow-forks",
515 "output-separately",
516 "summary-only",
517 "summary",
518 "no-abbrev",
519 "verbose",
520 ],
521 operands: 0,
522 },
523 Wrapper {
524 name: "ltrace",
525 short_values: "aAeDFlnopsuxwX",
526 short_switches: "bcCfhiLrStTV",
527 long_values: &["output", "library", "indent", "align"],
528 long_switches: &["demangle", "help", "version"],
529 operands: 0,
530 },
531 Wrapper {
532 name: "systemd-run",
533 short_values: "puEHM",
534 short_switches: "rtqGdPS",
535 long_values: &[
536 "property",
537 "unit",
538 "description",
539 "slice",
540 "setenv",
541 "uid",
542 "gid",
543 "nice",
544 "working-directory",
545 "host",
546 "machine",
547 "service-type",
548 "on-active",
549 "on-boot",
550 "on-startup",
551 "on-unit-active",
552 "on-unit-inactive",
553 "on-calendar",
554 "timer-property",
555 "path-property",
556 "socket-property",
557 ],
558 long_switches: &[
559 "user",
560 "system",
561 "scope",
562 "pty",
563 "pipe",
564 "wait",
565 "collect",
566 "quiet",
567 "no-ask-password",
568 "remain-after-exit",
569 "same-dir",
570 "no-block",
571 "send-sighup",
572 ],
573 operands: 0,
574 },
575 Wrapper {
576 name: "numactl",
577 short_values: "NmCipPw",
578 short_switches: "laHsS",
579 long_values: &[
580 "cpunodebind",
581 "membind",
582 "physcpubind",
583 "interleave",
584 "preferred",
585 "preferred-many",
586 "weighted-interleave",
587 "huge",
588 "offset",
589 "length",
590 "mode",
591 "shmmode",
592 "shmid",
593 "shm",
594 "file",
595 ],
596 long_switches: &["localalloc", "all", "hardware", "show", "touch", "strict"],
597 operands: 0,
598 },
599 Wrapper {
600 name: "firejail",
601 short_values: "",
602 short_switches: "",
603 long_values: &[],
604 long_switches: &[
605 "noprofile",
606 "quiet",
607 "private",
608 "private-dev",
609 "private-tmp",
610 "nonewprivs",
611 "noroot",
612 "seccomp",
613 "x11",
614 "appimage",
615 "allusers",
616 ],
617 operands: 0,
618 },
619 Wrapper {
620 name: "xvfb-run",
621 short_values: "efnpsw",
622 short_switches: "alh",
623 long_values: &[
624 "error-file",
625 "auth-file",
626 "server-num",
627 "xauth-protocol",
628 "server-args",
629 "wait",
630 ],
631 long_switches: &["auto-servernum", "listen-tcp", "help"],
632 operands: 0,
633 },
634 Wrapper {
635 name: "dbus-launch",
636 short_values: "",
637 short_switches: "",
638 long_values: &[],
639 long_switches: &[
640 "sh-syntax",
641 "csh-syntax",
642 "auto-syntax",
643 "binary-syntax",
644 "close-stderr",
645 "exit-with-session",
646 "exit-with-x11",
647 "version",
648 ],
649 operands: 0,
650 },
651 Wrapper {
652 name: "dbus-run-session",
653 short_values: "",
654 short_switches: "",
655 long_values: &["config-file", "dbus-daemon"],
656 long_switches: &["session", "version", "help"],
657 operands: 0,
658 },
659 Wrapper {
660 name: "sg",
661 short_values: "",
662 short_switches: "c",
663 long_values: &[],
664 long_switches: &[],
665 operands: 1,
666 },
667 Wrapper {
668 name: "proxychains",
669 short_values: "f",
670 short_switches: "q",
671 long_values: &[],
672 long_switches: &[],
673 operands: 0,
674 },
675 Wrapper {
676 name: "proxychains4",
677 short_values: "f",
678 short_switches: "q",
679 long_values: &[],
680 long_switches: &[],
681 operands: 0,
682 },
683 Wrapper {
684 name: "torsocks",
685 short_values: "uapP",
686 short_switches: "idqh",
687 long_values: &["user", "pass", "address", "port"],
688 long_switches: &["isolate", "debug", "quiet", "shell", "help", "version"],
689 operands: 0,
690 },
691 Wrapper {
692 name: "tsocks",
693 short_values: "",
694 short_switches: "",
695 long_values: &[],
696 long_switches: &[],
697 operands: 0,
698 },
699 Wrapper {
700 name: "eatmydata",
701 short_values: "",
702 short_switches: "",
703 long_values: &[],
704 long_switches: &[],
705 operands: 0,
706 },
707 Wrapper {
708 name: "cpulimit",
709 short_values: "lpe",
710 short_switches: "mzikvh",
711 long_values: &["limit", "pid", "exe", "cpu"],
712 long_switches: &[
713 "monitor-forks",
714 "lazy",
715 "include-children",
716 "kill",
717 "verbose",
718 "help",
719 ],
720 operands: 0,
721 },
722 Wrapper {
723 name: "setpriv",
724 short_values: "",
725 short_switches: "",
726 long_values: &[
727 "reuid",
728 "regid",
729 "groups",
730 "inh-caps",
731 "ambient-caps",
732 "bounding-set",
733 "securebits",
734 "pdeathsig",
735 "selinux-label",
736 "apparmor-profile",
737 "landlock-access",
738 "landlock-rule",
739 ],
740 long_switches: &[
741 "clear-groups",
742 "keep-groups",
743 "init-groups",
744 "nnp",
745 "no-new-privs",
746 "reset-env",
747 "dump",
748 "list-caps",
749 ],
750 operands: 0,
751 },
752 Wrapper {
753 name: "trickle",
754 short_values: "udwtlnL",
755 short_switches: "svh",
756 long_values: &[],
757 long_switches: &[],
758 operands: 0,
759 },
760 // GNU coreutils as installed on macOS (`brew install coreutils`).
761 Wrapper {
762 name: "gtimeout",
763 short_values: "sk",
764 short_switches: "fpv",
765 long_values: &["signal", "kill-after"],
766 long_switches: &["preserve-status", "foreground", "verbose"],
767 operands: 1,
768 },
769 Wrapper {
770 name: "gnice",
771 short_values: "n",
772 short_switches: "",
773 long_values: &["adjustment"],
774 long_switches: &[],
775 operands: 0,
776 },
777 Wrapper {
778 name: "gnohup",
779 short_values: "",
780 short_switches: "",
781 long_values: &[],
782 long_switches: &[],
783 operands: 0,
784 },
785 Wrapper {
786 name: "gstdbuf",
787 short_values: "ioe",
788 short_switches: "",
789 long_values: &["input", "output", "error"],
790 long_switches: &[],
791 operands: 0,
792 },
793 Wrapper {
794 name: "gchroot",
795 short_values: "ugG",
796 short_switches: "",
797 long_values: &["userspec", "groups"],
798 long_switches: &["skip-chdir"],
799 operands: 1,
800 },
801 Wrapper {
802 name: "toybox",
803 short_values: "",
804 short_switches: "",
805 long_values: &[],
806 long_switches: &[],
807 operands: 0,
808 },
809 Wrapper {
810 name: "script",
811 short_values: "cIOB",
812 short_switches: "adefkpqr",
813 long_values: &[
814 "command",
815 "log-in",
816 "log-out",
817 "log-io",
818 "log-timing",
819 "logging-format",
820 ],
821 long_switches: &[
822 "append", "echo", "flush", "force", "quiet", "return", "help", "version",
823 ],
824 operands: 1,
825 },
826 Wrapper {
827 name: "parallel",
828 short_values: "ajdnEILNPSts",
829 short_switches: "kmquX0",
830 long_values: &[
831 "arg-file",
832 "colsep",
833 "delay",
834 "delimiter",
835 "halt",
836 "header",
837 "jobs",
838 "load",
839 "max-args",
840 "memfree",
841 "nice",
842 "res",
843 "results",
844 "retries",
845 "slf",
846 "sshlogin",
847 "sshloginfile",
848 "tagstring",
849 "timeout",
850 "tmpdir",
851 "wd",
852 "workdir",
853 "block",
854 "recstart",
855 "recend",
856 ],
857 long_switches: &[
858 "bar",
859 "citation",
860 "dry-run",
861 "eta",
862 "files",
863 "gnu",
864 "group",
865 "help",
866 "keep-order",
867 "lb",
868 "line-buffer",
869 "noswap",
870 "null",
871 "pipe",
872 "pipepart",
873 "plain",
874 "progress",
875 "quote",
876 "regexp",
877 "remove-rec-sep",
878 "shebang",
879 "tag",
880 "ungroup",
881 "version",
882 "will-cite",
883 "xargs",
884 ],
885 operands: 0,
886 },
887 Wrapper {
888 name: "bwrap",
889 short_values: "",
890 short_switches: "",
891 long_values: &[
892 "remount-ro",
893 "proc",
894 "dev",
895 "tmpfs",
896 "mqueue",
897 "dir",
898 "unsetenv",
899 "chdir",
900 "hostname",
901 "uid",
902 "gid",
903 "seccomp",
904 "add-seccomp-fd",
905 "exec-label",
906 "file-label",
907 "block-fd",
908 "userns-block-fd",
909 "info-fd",
910 "json-status-fd",
911 "sync-fd",
912 "userns",
913 "userns2",
914 "pidns",
915 "cap-add",
916 "cap-drop",
917 "perms",
918 "size",
919 "argv0",
920 "lock-file",
921 "args",
922 ],
923 long_switches: &[
924 "help",
925 "version",
926 "level-prefix",
927 "clearenv",
928 "unshare-all",
929 "unshare-user",
930 "unshare-user-try",
931 "unshare-ipc",
932 "unshare-pid",
933 "unshare-net",
934 "unshare-uts",
935 "unshare-cgroup",
936 "unshare-cgroup-try",
937 "share-net",
938 "disable-userns",
939 "assert-userns-disabled",
940 "new-session",
941 "die-with-parent",
942 "as-pid-1",
943 ],
944 operands: 0,
945 },
946 Wrapper {
947 name: "setarch",
948 short_values: "",
949 short_switches: "vRFZLBI3SThV",
950 long_values: &[],
951 long_switches: &[
952 "verbose",
953 "addr-no-randomize",
954 "fdpic-funcptrs",
955 "mmap-page-zero",
956 "addr-compat-layout",
957 "read-implies-exec",
958 "32bit",
959 "short-inode",
960 "whole-seconds",
961 "unlimited",
962 "3gb",
963 "4gb",
964 "uname-2.6",
965 "list",
966 "help",
967 "version",
968 ],
969 operands: 1,
970 },
971 Wrapper {
972 name: "linux64",
973 short_values: "",
974 short_switches: "vRFZLBI3SThV",
975 long_values: &[],
976 long_switches: &[
977 "verbose",
978 "addr-no-randomize",
979 "fdpic-funcptrs",
980 "mmap-page-zero",
981 "addr-compat-layout",
982 "read-implies-exec",
983 "32bit",
984 "short-inode",
985 "whole-seconds",
986 "unlimited",
987 "3gb",
988 "4gb",
989 "uname-2.6",
990 "list",
991 "help",
992 "version",
993 ],
994 operands: 0,
995 },
996 Wrapper {
997 name: "faketime",
998 short_values: "",
999 short_switches: "fmv",
1000 long_values: &[],
1001 long_switches: &["help", "version", "exclude-monotonic"],
1002 operands: 1,
1003 },
1004 Wrapper {
1005 name: "rlwrap",
1006 short_values: "bCDefgHlMOPqsStwz",
1007 short_switches: "AcInNorRvWh",
1008 long_values: &[
1009 "break-chars",
1010 "command-name",
1011 "history-no-dupes",
1012 "extra-char-after-completion",
1013 "file",
1014 "forget-matching",
1015 "history-filename",
1016 "logfile",
1017 "multi-line-ext",
1018 "filter",
1019 "only-cook",
1020 "pre-given",
1021 "quote-characters",
1022 "histsize",
1023 "substitute-prompt",
1024 "set-term-name",
1025 "polling",
1026 ],
1027 long_switches: &[
1028 "ansi-colour-aware",
1029 "complete-filenames",
1030 "case-insensitive",
1031 "no-warnings",
1032 "pass-sigint-as-sigterm",
1033 "remember",
1034 "renice",
1035 "mirror-arguments",
1036 "version",
1037 "help",
1038 ],
1039 operands: 0,
1040 },
1041 Wrapper {
1042 name: "chronic",
1043 short_values: "",
1044 short_switches: "ev",
1045 long_values: &[],
1046 long_switches: &[],
1047 operands: 0,
1048 },
1049 Wrapper {
1050 name: "ifne",
1051 short_values: "",
1052 short_switches: "n",
1053 long_values: &[],
1054 long_switches: &[],
1055 operands: 0,
1056 },
1057 Wrapper {
1058 name: "runcon",
1059 short_values: "urtl",
1060 short_switches: "c",
1061 long_values: &["user", "role", "type", "range"],
1062 long_switches: &["compute", "help", "version"],
1063 operands: 1,
1064 },
1065 Wrapper {
1066 name: "chpst",
1067 short_values: "uUbe/nlLmdopfc",
1068 short_switches: "vP012",
1069 long_values: &[],
1070 long_switches: &[],
1071 operands: 0,
1072 },
1073 Wrapper {
1074 name: "softlimit",
1075 short_values: "mdopfcrsalt",
1076 short_switches: "",
1077 long_values: &[],
1078 long_switches: &[],
1079 operands: 0,
1080 },
1081 Wrapper {
1082 name: "valgrind",
1083 short_values: "",
1084 short_switches: "hqvd",
1085 long_values: &[],
1086 long_switches: &[],
1087 operands: 0,
1088 },
1089 Wrapper {
1090 name: "watchexec",
1091 short_values: "weifosd",
1092 short_switches: "rcpnqv",
1093 long_values: &[
1094 "watch",
1095 "exts",
1096 "ignore",
1097 "filter",
1098 "on-busy-update",
1099 "shell",
1100 "signal",
1101 "debounce",
1102 "wrap-process",
1103 "project-origin",
1104 "workdir",
1105 "poll",
1106 "stop-signal",
1107 "stop-timeout",
1108 "delay-run",
1109 "fs-events",
1110 ],
1111 long_switches: &[
1112 "restart",
1113 "clear",
1114 "postpone",
1115 "no-shell",
1116 "quiet",
1117 "verbose",
1118 "stdin-quit",
1119 "no-vcs-ignore",
1120 "no-project-ignore",
1121 "no-global-ignore",
1122 "no-default-ignore",
1123 "only-emit-events",
1124 "print-events",
1125 "no-meta",
1126 "no-process-group",
1127 "watch-file",
1128 "help",
1129 "version",
1130 ],
1131 operands: 0,
1132 },
1133 Wrapper {
1134 name: "entr",
1135 short_values: "",
1136 short_switches: "acdnprsxz",
1137 long_values: &[],
1138 long_switches: &[],
1139 operands: 0,
1140 },
1141 Wrapper {
1142 name: "systemd-inhibit",
1143 short_values: "",
1144 short_switches: "h",
1145 long_values: &["what", "who", "why", "mode"],
1146 long_switches: &["list", "no-legend", "no-pager", "help", "version"],
1147 operands: 0,
1148 },
1149 Wrapper {
1150 name: "cgexec",
1151 short_values: "g",
1152 short_switches: "h",
1153 long_values: &[],
1154 long_switches: &["sticky", "help"],
1155 operands: 0,
1156 },
1157 Wrapper {
1158 name: "daemonize",
1159 short_values: "ceoplu",
1160 short_switches: "av",
1161 long_values: &[],
1162 long_switches: &[],
1163 operands: 0,
1164 },
1165 Wrapper {
1166 name: "nsjail",
1167 short_values: "McRBTEugtlCDpH",
1168 short_switches: "eqQvdNi",
1169 long_values: &[
1170 "mode",
1171 "chroot",
1172 "bindmount_ro",
1173 "bindmount",
1174 "tmpfsmount",
1175 "env",
1176 "user",
1177 "group",
1178 "time_limit",
1179 "log",
1180 "config",
1181 "cwd",
1182 "port",
1183 "hostname",
1184 "max_cpus",
1185 "rlimit_as",
1186 "rlimit_cpu",
1187 "rlimit_fsize",
1188 "rlimit_nofile",
1189 "exec_file",
1190 ],
1191 long_switches: &[
1192 "keep_env",
1193 "quiet",
1194 "really_quiet",
1195 "verbose",
1196 "daemon",
1197 "keep_caps",
1198 "disable_clone_newnet",
1199 "disable_no_new_privs",
1200 "disable_proc",
1201 "skip_setsid",
1202 "help",
1203 ],
1204 operands: 0,
1205 },
1206 Wrapper {
1207 name: "torify",
1208 short_values: "Paup",
1209 short_switches: "idqh",
1210 long_values: &["port", "address", "user", "password"],
1211 long_switches: &["isolate", "debug", "quiet", "shell", "help", "version"],
1212 operands: 0,
1213 },
1214 Wrapper {
1215 name: "ld.so",
1216 short_values: "",
1217 short_switches: "",
1218 long_values: &[
1219 "library-path",
1220 "inhibit-rpath",
1221 "audit",
1222 "preload",
1223 "argv0",
1224 "glibc-hwcaps-prepend",
1225 "glibc-hwcaps-mask",
1226 ],
1227 long_switches: &["inhibit-cache", "help", "version", "list-diagnostics"],
1228 operands: 0,
1229 },
1230 ];
1231
1232 /// Shell reserved words that can lead a simple command without being it:
1233 /// `if rm x; then …`, `while rm x; do …`, `! rm x`.
1234 const RESERVED_PREFIXES: &[&str] = &[
1235 "if", "then", "elif", "else", "do", "while", "until", "!", "coproc",
1236 ];
1237
1238 const REBINDING_BUILTINS: &[&str] = &[
1239 "alias", "enable", "setopt", "unsetopt", "emulate", "shopt", "autoload", "zmodload",
1240 ];
1241
1242 /// Shells whose `-c` argument is a command line to be parsed, not an operand.
1243 const SHELL_NAMES: &[&str] = &[
1244 "sh", "bash", "zsh", "dash", "ksh", "ksh93", "mksh", "ash", "fish", "csh", "tcsh", "rbash",
1245 "yash", "elvish", "nu", "xonsh", "oksh", "posh", "osh", "oil", "ysh", "pdksh", "loksh", "rksh",
1246 "ion", "ngs",
1247 ];
1248
1249 /// The commands a shell line would run, plus what could not be resolved.
1250 #[derive(Debug, Clone, Default, PartialEq, Eq)]
1251 pub struct Expansion {
1252 /// Every command line found, as [`expanded_commands`] returns them.
1253 pub commands: Vec<String>,
1254 pub words: Vec<Vec<String>>,
1255 pub extra_deny_commands: Vec<String>,
1256 /// A command word (or a shell's script) is only known at run time, so no
1257 /// deny rule can be matched against it reliably.
1258 pub dynamic: bool,
1259 /// Some code runs nested inside another command: a command or process
1260 /// substitution, `eval`, a shell `-c` payload or stdin script, or a
1261 /// `find -exec` payload.
1262 pub nested: bool,
1263 /// An argument's value is resolved only at execution time. A prefix grant
1264 /// cannot check whether that value introduces a write/execute option.
1265 /// Unlike `dynamic`, this does not make the command head unknowable.
1266 pub arguments_dynamic: bool,
1267 /// Unquoted control operators or grouping. Recorded before command
1268 /// deduplication: `echo x; echo x` still contains a command list.
1269 pub control: bool,
1270 /// Unquoted redirection syntax, including descriptor duplication and
1271 /// heredocs. Quoted operator characters and heredoc body data are excluded.
1272 pub redirects: bool,
1273 }
1274
1275 impl Expansion {
1276 pub fn deny_commands(&self) -> impl Iterator<Item = &str> {
1277 self.commands
1278 .iter()
1279 .chain(&self.extra_deny_commands)
1280 .map(String::as_str)
1281 }
1282 }
1283
1284 /// Returns every command line the shell would execute for `command`.
1285 ///
1286 /// Results contain word-split commands, substitutions and wrapper payloads.
1287 /// Literal data, including quoted heredoc bodies, is not treated as code.
1288 /// Windows scans retain native path separators as well as POSIX candidates.
1289 pub fn expanded_commands(command: &str) -> Vec<String> {
1290 expand_command(command).commands
1291 }
1292
1293 /// [`expanded_commands`] plus the flags a policy needs to fail closed.
1294 pub fn expand_command(command: &str) -> Expansion {
1295 expand_for_platform(command, cfg!(windows))
1296 }
1297
1298 #[cfg(test)]
1299 fn expanded_commands_for_platform(command: &str, windows: bool) -> Vec<String> {
1300 expand_for_platform(command, windows).commands
1301 }
1302
1303 fn expand_for_platform(command: &str, windows: bool) -> Expansion {
1304 let mut expander = Expander {
1305 out: Vec::new(),
1306 out_words: Vec::new(),
1307 extra_deny: Vec::new(),
1308 seen: HashSet::new(),
1309 seen_extra_deny: HashSet::new(),
1310 extra_deny_dropped: false,
1311 extra_deny_cap_dropped: false,
1312 deny_suffix_depths: HashMap::new(),
1313 tmux_work_left: MAX_TMUX_WORK,
1314 literal_backslashes: windows,
1315 dynamic: false,
1316 nested: false,
1317 arguments_dynamic: false,
1318 control: false,
1319 redirects: false,
1320 deny_only: false,
1321 inherited_stdin: false,
1322 groups: Vec::new(),
1323 };
1324 // Native Windows shells preserve path separators. Also retain the POSIX
1325 // interpretation for Bash/WSL commands. Both passes use the same bounded,
1326 // heredoc-aware parser and only contribute deny targets, never grants.
1327 expander.expand(command, 0);
1328 if windows {
1329 expander.literal_backslashes = false;
1330 expander.expand(command, 0);
1331 }
1332 Expansion {
1333 commands: expander.out,
1334 words: expander.out_words,
1335 extra_deny_commands: expander.extra_deny,
1336 dynamic: expander.dynamic || expander.extra_deny_dropped,
1337 nested: expander.nested,
1338 arguments_dynamic: expander.arguments_dynamic,
1339 control: expander.control,
1340 redirects: expander.redirects,
1341 }
1342 }
1343
1344 struct Expander {
1345 out: Vec<String>,
1346 out_words: Vec<Vec<String>>,
1347 extra_deny: Vec<String>,
1348 seen: HashSet<String>,
1349 seen_extra_deny: HashSet<String>,
1350 extra_deny_dropped: bool,
1351 extra_deny_cap_dropped: bool,
1352 deny_suffix_depths: HashMap<u64, usize>,
1353 tmux_work_left: usize,
1354 literal_backslashes: bool,
1355 dynamic: bool,
1356 nested: bool,
1357 arguments_dynamic: bool,
1358 control: bool,
1359 redirects: bool,
1360 deny_only: bool,
1361 inherited_stdin: bool,
1362 groups: Vec<Group>,
1363 }
1364
1365 #[derive(Clone, Copy)]
1366 struct Group {
1367 kind: GroupKind,
1368 piped: bool,
1369 start_cmd: usize,
1370 }
1371
1372 #[derive(Clone, Copy, PartialEq, Eq)]
1373 enum GroupKind {
1374 Paren,
1375 Keyword,
1376 }
1377
1378 const KEYWORD_CONTINUES: &[&str] = &[
1379 "{", "}", "if", "then", "elif", "else", "do", "while", "until", "for", "select", "case", "in",
1380 "done", "fi", "esac", "!", "coproc", "time",
1381 ];
1382
1383 #[derive(Clone, Copy, Default, PartialEq, Eq, Hash)]
1384 enum WordQuote {
1385 #[default]
1386 Unquoted,
1387 Quoted,
1388 InlineScalar,
1389 }
1390
1391 /// The word being read, with what the parser learned about it.
1392 #[derive(Default)]
1393 struct WordBuf {
1394 text: String,
1395 started: bool,
1396 quoted: WordQuote,
1397 redirect_operand: bool,
1398 /// The word's final text depends on an expansion the parser does not run.
1399 dynamic: bool,
1400 /// An unquoted `{` appeared, so brace expansion may rewrite the word.
1401 brace: bool,
1402 /// An unquoted `[` appeared, so the word may be a bracket glob.
1403 bracket: bool,
1404 odd: bool,
1405 }
1406
1407 impl WordBuf {
1408 fn flush(
1409 &mut self,
1410 line: &mut Line,
1411 groups: &mut Vec<Group>,
1412 last_closed_group: &mut Option<usize>,
1413 cmd_count: usize,
1414 ) {
1415 if self.started || !self.text.is_empty() || self.dynamic {
1416 if self.redirect_operand {
1417 self.text.clear();
1418 self.redirect_operand = false;
1419 } else {
1420 // `[` alone is the test builtin and `{}` is a find
1421 // placeholder; only a closed bracket or a brace list expands.
1422 let dynamic = self.dynamic
1423 || (self.bracket && self.text.len() > 1 && self.text.contains(']'))
1424 || (self.brace && (self.text.contains(',') || self.text.contains("..")));
1425 let command_position = line
1426 .words
1427 .last()
1428 .is_none_or(|last| KEYWORD_CONTINUES.contains(&last.as_str()));
1429 let mut closed = false;
1430 if command_position && self.quoted == WordQuote::Unquoted {
1431 match self.text.as_str() {
1432 "{" | "while" | "until" | "for" | "if" | "case" | "select" => {
1433 groups.push(Group {
1434 kind: GroupKind::Keyword,
1435 piped: line.stdin_piped,
1436 start_cmd: cmd_count,
1437 });
1438 }
1439 "}" | "done" | "fi" | "esac" => {
1440 if matches!(groups.last(), Some(g) if g.kind == GroupKind::Keyword) {
1441 *last_closed_group = groups.pop().map(|g| g.start_cmd);
1442 closed = true;
1443 }
1444 }
1445 "coproc" => {
1446 line.stdin_piped = true;
1447 }
1448 _ => {}
1449 }
1450 }
1451 if !closed {
1452 *last_closed_group = None;
1453 }
1454 line.words.push(std::mem::take(&mut self.text));
1455 line.dynamic.push(dynamic);
1456 line.odd.push(self.odd);
1457 line.quoted.push(self.quoted);
1458 }
1459 self.started = false;
1460 }
1461 self.quoted = WordQuote::Unquoted;
1462 self.dynamic = false;
1463 self.brace = false;
1464 self.bracket = false;
1465 self.odd = false;
1466 }
1467 }
1468
1469 /// One simple command: its words, which of them are dynamic, and whether a
1470 /// heredoc or pipe/redirect feeds its stdin.
1471 #[derive(Default, Clone)]
1472 struct Line {
1473 words: Vec<String>,
1474 dynamic: Vec<bool>,
1475 odd: Vec<bool>,
1476 quoted: Vec<WordQuote>,
1477 heredoc: bool,
1478 stdin_piped: bool,
1479 }
1480
1481 fn inherit_group_stdin(commands: &mut [Line]) {
1482 for command in commands.iter_mut().filter(|command| !command.heredoc) {
1483 command.stdin_piped = true;
1484 }
1485 }
1486
1487 /// How a shell invocation receives its script.
1488 enum ShellInput {
1489 /// `-c` / `--command`: the word at each offset may be the command line.
1490 Command(Vec<usize>),
1491 Inline(String, bool),
1492 /// A script file operand at this offset.
1493 Script(usize),
1494 /// The script is read from stdin.
1495 Stdin,
1496 }
1497
1498 impl Expander {
1499 fn emit_extra_deny(&mut self, joined: String) {
1500 if joined.is_empty()
1501 || self.seen.contains(&joined)
1502 || self.seen_extra_deny.contains(&joined)
1503 {
1504 return;
1505 }
1506 if self.extra_deny.len() >= MAX_COMMANDS {
1507 self.extra_deny_dropped = true;
1508 self.extra_deny_cap_dropped = true;
1509 return;
1510 }
1511 self.seen_extra_deny.insert(joined.clone());
1512 self.extra_deny.push(joined);
1513 }
1514
1515 fn emit(&mut self, tokens: &[String]) {
1516 let joined = tokens
1517 .iter()
1518 .filter(|token| !token.is_empty())
1519 .cloned()
1520 .collect::<Vec<_>>()
1521 .join(" ");
1522 if self.deny_only {
1523 self.emit_extra_deny(joined);
1524 return;
1525 }
1526 if joined.is_empty() || self.seen.contains(&joined) {
1527 return;
1528 }
1529 if self.out.len() >= MAX_COMMANDS {
1530 // A dropped command line was never checked: unresolved.
1531 self.dynamic = true;
1532 return;
1533 }
1534 self.seen.insert(joined.clone());
1535 self.out.push(joined);
1536 self.out_words.push(
1537 tokens
1538 .iter()
1539 .filter(|token| !token.is_empty())
1540 .cloned()
1541 .collect(),
1542 );
1543 }
1544
1545 /// Word-split `input` into command lines and record each one, recursing
1546 /// into every nested command text found along the way.
1547 fn expand(&mut self, input: &str, depth: usize) {
1548 if depth > MAX_DEPTH || self.out.len() >= MAX_COMMANDS {
1549 // Unexamined code is unresolved code.
1550 self.dynamic = true;
1551 return;
1552 }
1553 if depth > 0 && !input.trim().is_empty() {
1554 self.nested = true;
1555 }
1556 // shlex does not implement ANSI-C/localized quoting or shell CR
1557 // semantics. Keep the conservative scan for those forms rather than
1558 // let an unrecognized heredoc delimiter hide following commands.
1559 if input.contains('\r') || input.contains("$'") || input.contains("$\"") {
1560 for segment in super::command_segments(input) {
1561 self.emit(&[segment]);
1562 }
1563 }
1564 let chars: Vec<char> = input.chars().collect();
1565 let n = chars.len();
1566 let mut i = 0usize;
1567 let prev_groups = std::mem::take(&mut self.groups);
1568 let mut commands: Vec<Line> = Vec::new();
1569 let mut line = Line {
1570 stdin_piped: self.inherited_stdin,
1571 ..Line::default()
1572 };
1573 let mut word = WordBuf::default();
1574 let mut nested: Vec<(String, bool)> = Vec::new();
1575 let mut heredocs = Vec::new();
1576 let mut last_closed_group: Option<usize> = None;
1577 let mut line_start_cmd = 0usize;
1578 let mut after_pipe = false;
1579 // Set when the text does not parse cleanly (an unterminated quote,
1580 // substitution or heredoc, a `case` inside a substitution): where
1581 // this parser ends a region may not be where the shell ends it.
1582 let mut uncertain = false;
1583
1584 while i < n {
1585 let c = chars[i];
1586 match c {
1587 '#' if !word.started && word.text.is_empty() => {
1588 while i < n && chars[i] != '\n' {
1589 i += 1;
1590 }
1591 }
1592 // A backslash outside quotes escapes exactly one character,
1593 // including an operator: `echo a\;b` is one word, not two
1594 // commands. A backslash-newline is a line continuation.
1595 '\\' if self.literal_backslashes => {
1596 after_pipe = false;
1597 word.text.push('\\');
1598 word.started = true;
1599 i += 1;
1600 }
1601 '\\' => {
1602 if i + 1 < n {
1603 if chars[i + 1] != '\n' {
1604 after_pipe = false;
1605 word.text.push(chars[i + 1]);
1606 word.started = true;
1607 word.quoted = WordQuote::Quoted;
1608 }
1609 i += 2;
1610 } else {
1611 i += 1;
1612 }
1613 }
1614 // Single quotes are fully literal: no substitution, no escapes.
1615 '\'' => {
1616 after_pipe = false;
1617 word.started = true;
1618 word.quoted = WordQuote::Quoted;
1619 i += 1;
1620 while i < n && chars[i] != '\'' {
1621 word.text.push(chars[i]);
1622 i += 1;
1623 }
1624 uncertain |= i >= n;
1625 i = (i + 1).min(n);
1626 }
1627 // Double quotes suppress word splitting but NOT substitution.
1628 '"' => {
1629 after_pipe = false;
1630 let mut inline_scalar = word.quoted == WordQuote::Unquoted
1631 && !word.dynamic
1632 && word
1633 .text
1634 .strip_prefix("--")
1635 .and_then(|prefix| prefix.strip_suffix('='))
1636 .is_some_and(|name| {
1637 !name.is_empty()
1638 && name.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-')
1639 });
1640 word.started = true;
1641 word.quoted = WordQuote::Quoted;
1642 i += 1;
1643 while i < n && chars[i] != '"' {
1644 match chars[i] {
1645 '\\' if self.literal_backslashes => {
1646 word.text.push('\\');
1647 i += 1;
1648 }
1649 '\\' if i + 1 < n => {
1650 word.text.push(chars[i + 1]);
1651 i += 2;
1652 }
1653 '`' => {
1654 inline_scalar = false;
1655 word.dynamic = true;
1656 let (inner, next, certain) = read_backtick(&chars, i);
1657 uncertain |= !certain;
1658 nested.push((inner, line.stdin_piped));
1659 i = next;
1660 }
1661 '$' if i + 1 < n && matches!(chars[i + 1], '(' | '{') => {
1662 inline_scalar = false;
1663 word.dynamic = true;
1664 let (inner, next, certain) = read_substitution(&chars, i + 1);
1665 uncertain |= !certain;
1666 nested.push((inner, line.stdin_piped));
1667 i = next;
1668 }
1669 ch => {
1670 if ch == '$' && starts_parameter(chars.get(i + 1)) {
1671 inline_scalar &=
1672 chars[i + 1].is_ascii_alphabetic() || chars[i + 1] == '_';
1673 word.dynamic = true;
1674 }
1675 word.text.push(ch);
1676 i += 1;
1677 }
1678 }
1679 }
1680 uncertain |= i >= n;
1681 if inline_scalar
1682 && word.dynamic
1683 && i < n
1684 && chars.get(i + 1).is_none_or(|ch| {
1685 matches!(
1686 ch,
1687 ' ' | '\t' | '\r' | '\n' | ';' | '|' | '&' | '(' | ')' | '<' | '>'
1688 )
1689 })
1690 {
1691 word.quoted = WordQuote::InlineScalar;
1692 }
1693 i = (i + 1).min(n);
1694 }
1695 '$' if i + 1 < n && chars[i + 1] == '\'' => {
1696 after_pipe = false;
1697 word.started = true;
1698 word.quoted = WordQuote::Quoted;
1699 word.dynamic = true;
1700 i += 2;
1701 while i < n && chars[i] != '\'' {
1702 if chars[i] == '\\' && i + 1 < n {
1703 i = push_ansi_c_escape(&chars, i, &mut word.text);
1704 } else {
1705 word.text.push(chars[i]);
1706 i += 1;
1707 }
1708 }
1709 uncertain |= i >= n;
1710 i = (i + 1).min(n);
1711 }
1712 // Command substitution, both spellings. The body is a command
1713 // line in its own right; the substitution contributes no text
1714 // to the enclosing word (we do not evaluate output).
1715 '`' => {
1716 after_pipe = false;
1717 word.started |= word.redirect_operand;
1718 word.dynamic = true;
1719 let (inner, next, certain) = read_backtick(&chars, i);
1720 uncertain |= !certain;
1721 nested.push((inner, line.stdin_piped));
1722 i = next;
1723 }
1724 // `$(…)`, and `${…}`: an expansion, not a command — but it can
1725 // *contain* one (`${x:-$(rm -rf /)}`), so the body is rescanned.
1726 // Process substitution `<(…)` / `>(…)` also runs its body.
1727 '$' | '<' | '>'
1728 if i + 1 < n && (chars[i + 1] == '(' || (c == '$' && chars[i + 1] == '{')) =>
1729 {
1730 after_pipe = false;
1731 word.started |= word.redirect_operand;
1732 word.dynamic = true;
1733 let (inner, next, certain) = read_substitution(&chars, i + 1);
1734 uncertain |= !certain;
1735 nested.push((inner, line.stdin_piped));
1736 i = next;
1737 }
1738 '<' if chars.get(i + 1) == Some(&'<') && chars.get(i + 2) != Some(&'<') => {
1739 self.redirects = true;
1740 after_pipe = false;
1741 let redirects_stdin = consume_redirect_descriptor(&mut word);
1742 word.flush(
1743 &mut line,
1744 &mut self.groups,
1745 &mut last_closed_group,
1746 commands.len(),
1747 );
1748 if redirects_stdin {
1749 line.heredoc = true;
1750 line.stdin_piped = false;
1751 }
1752 i += 2;
1753 let strip_tabs = chars.get(i) == Some(&'-');
1754 if strip_tabs {
1755 i += 1;
1756 }
1757 while i < n && matches!(chars[i], ' ' | '\t') {
1758 i += 1;
1759 }
1760 let start = i;
1761 let mut quote = None;
1762 let mut literal = false;
1763 while i < n {
1764 let ch = chars[i];
1765 if quote.is_none()
1766 && matches!(ch, ' ' | '\t' | '\n' | ';' | '|' | '&' | '<' | '>')
1767 {
1768 break;
1769 }
1770 if ch == '\\' && quote != Some('\'') {
1771 literal = true;
1772 i = (i + 2).min(n);
1773 continue;
1774 }
1775 if matches!(ch, '\'' | '"') {
1776 literal = true;
1777 if quote == Some(ch) {
1778 quote = None;
1779 } else if quote.is_none() {
1780 quote = Some(ch);
1781 }
1782 }
1783 i += 1;
1784 }
1785 let raw: String = chars[start..i].iter().collect();
1786 if let Some(delimiter) = shlex::split(&raw)
1787 .and_then(|mut words| (words.len() == 1).then(|| words.remove(0)))
1788 {
1789 let cmd_start = last_closed_group.unwrap_or(line_start_cmd);
1790 heredocs.push((delimiter, literal, strip_tabs, redirects_stdin, cmd_start));
1791 }
1792 }
1793 // Unquoted redirections are syntax, even without whitespace.
1794 // Keep the command words on both sides together, but omit the
1795 // descriptor and next operand. Parse that operand normally so
1796 // nested substitutions are still checked as commands.
1797 '<' | '>' | '&' if redirection_len(&chars[i..]) > 0 => {
1798 self.redirects = true;
1799 after_pipe = false;
1800 let redirects_stdin = consume_redirect_descriptor(&mut word);
1801 word.flush(
1802 &mut line,
1803 &mut self.groups,
1804 &mut last_closed_group,
1805 commands.len(),
1806 );
1807 word.redirect_operand = true;
1808 if c == '<' && redirects_stdin {
1809 line.stdin_piped = true;
1810 line.heredoc = false;
1811 if let Some(start) = last_closed_group {
1812 inherit_group_stdin(&mut commands[start..]);
1813 }
1814 }
1815 i += redirection_len(&chars[i..]);
1816 }
1817 ' ' | '\t' => {
1818 word.flush(
1819 &mut line,
1820 &mut self.groups,
1821 &mut last_closed_group,
1822 commands.len(),
1823 );
1824 i += 1;
1825 }
1826 // A subshell boundary. `$(`, `<(` and `>(` were consumed by the
1827 // arms above, so a bare paren here is grouping: the body is a
1828 // command list of its own, not part of the surrounding word.
1829 '(' | ')' => {
1830 self.control = true;
1831 after_pipe = false;
1832 let enclosing_stdin = line.stdin_piped;
1833 let glued = if c == '(' {
1834 (word.started || !word.text.is_empty())
1835 && chars.get(i + 1) != Some(&')')
1836 && !is_array_assignment_prefix(&word.text)
1837 } else {
1838 !(i > 0 && chars[i - 1] == '(')
1839 && chars.get(i + 1).is_some_and(|next| {
1840 !next.is_whitespace()
1841 && !matches!(next, ';' | '|' | '&' | '(' | ')' | '<' | '>')
1842 })
1843 };
1844 uncertain |= glued;
1845 word.flush(
1846 &mut line,
1847 &mut self.groups,
1848 &mut last_closed_group,
1849 commands.len(),
1850 );
1851 let subshell = c == '(' && !glued && chars.get(i + 1) != Some(&'(');
1852 if subshell {
1853 self.groups.push(Group {
1854 kind: GroupKind::Paren,
1855 piped: line.stdin_piped,
1856 start_cmd: commands.len(),
1857 });
1858 last_closed_group = None;
1859 }
1860 end_command(&mut commands, &mut line, self.fresh_stdin());
1861 if c == ')'
1862 && matches!(self.groups.last(), Some(g) if g.kind == GroupKind::Paren)
1863 {
1864 last_closed_group = self.groups.pop().map(|g| g.start_cmd);
1865 line.stdin_piped = self.fresh_stdin();
1866 } else if !subshell {
1867 last_closed_group = None;
1868 }
1869 word.redirect_operand = false;
1870 if c == '(' && chars.get(i + 1) == Some(&'(') {
1871 // `(( … ))` is arithmetic, where `<<` is a shift and
1872 // not a heredoc. Its substitutions still run, and
1873 // `((cmd) )` is two subshells, so the body is scanned
1874 // as code on its own; a heredoc it appears to open
1875 // cannot swallow the lines after it.
1876 let (inner, next, certain) = read_substitution(&chars, i);
1877 uncertain |= !certain;
1878 nested.push((inner, enclosing_stdin));
1879 i = next;
1880 } else {
1881 i += 1;
1882 }
1883 }
1884 // Control operators end the current command line. `&&`, `||`,
1885 // `;;`, `|&` and runs of newlines collapse into one break.
1886 '\n' | '\r' | ';' | '&' | '|' => {
1887 self.control = true;
1888 let preserve_pipe =
1889 matches!(c, '\n' | '\r') && after_pipe && heredocs.is_empty();
1890 word.flush(
1891 &mut line,
1892 &mut self.groups,
1893 &mut last_closed_group,
1894 commands.len(),
1895 );
1896 last_closed_group = None;
1897 let next_stdin = if preserve_pipe {
1898 line.stdin_piped
1899 } else {
1900 self.fresh_stdin()
1901 };
1902 end_command(&mut commands, &mut line, next_stdin);
1903 word.redirect_operand = false;
1904 if !preserve_pipe {
1905 after_pipe = false;
1906 }
1907 if c == '|' && chars.get(i + 1) == Some(&'|') {
1908 i += 1;
1909 } else if c == '|' {
1910 line.stdin_piped = true;
1911 after_pipe = true;
1912 if chars.get(i + 1) == Some(&'&') {
1913 i += 1;
1914 }
1915 }
1916 i += 1;
1917 if c == '\n' {
1918 if !heredocs.is_empty() {
1919 for (delimiter, literal, strip_tabs, redirects_stdin, cmd_start) in
1920 heredocs.drain(..)
1921 {
1922 let shell_stdin = redirects_stdin
1923 && commands[cmd_start..].iter().any(|line| {
1924 command_heads(&line.words, &line.dynamic).heads.iter().any(
1925 |&head| {
1926 let name = command_name(&line.words[head]);
1927 SHELL_NAMES.contains(&name.as_str())
1928 || matches!(
1929 name.as_str(),
1930 "source"
1931 | "."
1932 | "at"
1933 | "batch"
1934 | "pwsh"
1935 | "powershell"
1936 | "dbclient"
1937 | "mosh"
1938 )
1939 || (name == "ssh"
1940 && ssh_reads_stdin(
1941 &line.words,
1942 &line.dynamic,
1943 &line.quoted,
1944 head,
1945 ))
1946 },
1947 )
1948 });
1949 let mut body = String::new();
1950 // A body that runs to the end of the input may be
1951 // a misread `<<`; what it swallowed is unexamined.
1952 let mut terminated = false;
1953 while i < n {
1954 let start = i;
1955 while i < n && chars[i] != '\n' {
1956 i += 1;
1957 }
1958 let mut text: String = chars[start..i].iter().collect();
1959 if i < n {
1960 i += 1;
1961 }
1962 // An unquoted heredoc joins escaped newlines
1963 // before checking its delimiter (E\ + OF can
1964 // terminate EOF). Do not swallow later code.
1965 while !literal
1966 && text.chars().rev().take_while(|c| *c == '\\').count() % 2
1967 == 1
1968 && i < n
1969 {
1970 text.pop();
1971 let start = i;
1972 while i < n && chars[i] != '\n' {
1973 i += 1;
1974 }
1975 text.extend(chars[start..i].iter());
1976 if i < n {
1977 i += 1;
1978 }
1979 }
1980 let text = if strip_tabs {
1981 text.trim_start_matches('\t')
1982 } else {
1983 &text
1984 };
1985 if text == delimiter {
1986 terminated = true;
1987 break;
1988 }
1989 body.push_str(text);
1990 body.push('\n');
1991 }
1992 uncertain |= !terminated;
1993 if shell_stdin {
1994 nested.push((body, false));
1995 } else if !literal {
1996 let (bodies, certain) = heredoc_substitutions(&body);
1997 uncertain |= !certain;
1998 nested.extend(
1999 bodies.into_iter().map(|body| (body, line.stdin_piped)),
2000 );
2001 }
2002 }
2003 }
2004 line_start_cmd = commands.len();
2005 }
2006 }
2007 _ => {
2008 after_pipe = false;
2009 if c == '$' && starts_parameter(chars.get(i + 1)) {
2010 word.dynamic = true;
2011 }
2012 match c {
2013 '*' | '?' => word.dynamic = true,
2014 '[' => word.bracket = true,
2015 '{' => word.brace = true,
2016 _ => {}
2017 }
2018 if !is_plain_word_char(c, !word.started && word.text.is_empty()) {
2019 word.odd = true;
2020 }
2021 word.text.push(c);
2022 word.started = true;
2023 i += 1;
2024 }
2025 }
2026 }
2027 word.flush(
2028 &mut line,
2029 &mut self.groups,
2030 &mut last_closed_group,
2031 commands.len(),
2032 );
2033 end_command(&mut commands, &mut line, self.fresh_stdin());
2034 self.groups = prev_groups;
2035 self.dynamic |= uncertain;
2036
2037 for line in &commands {
2038 self.record(line, depth);
2039 }
2040 for (inner, piped) in nested {
2041 let prev_stdin = self.inherited_stdin;
2042 self.inherited_stdin |= piped;
2043 self.expand(&inner, depth + 1);
2044 self.inherited_stdin = prev_stdin;
2045 }
2046 }
2047
2048 fn fresh_stdin(&self) -> bool {
2049 self.inherited_stdin || self.groups.last().is_some_and(|group| group.piped)
2050 }
2051
2052 /// Record one word-split command line, plus the invocation hiding inside it
2053 /// when the head is a wrapper, and flag what cannot be resolved.
2054 fn record(&mut self, line: &Line, depth: usize) {
2055 let prev_stdin = self.inherited_stdin;
2056 self.inherited_stdin |= line.stdin_piped;
2057 self.record_line(line, depth);
2058 self.inherited_stdin = prev_stdin;
2059 }
2060
2061 fn record_line(&mut self, line: &Line, depth: usize) {
2062 let tokens = &line.words;
2063 if tokens.is_empty() {
2064 return;
2065 }
2066 if depth > MAX_DEPTH {
2067 self.dynamic = true;
2068 return;
2069 }
2070 self.emit(tokens);
2071
2072 let heads = command_heads(tokens, &line.dynamic);
2073 self.dynamic |= heads.truncated;
2074 for (payload, payload_dynamic) in &heads.split_payloads {
2075 // `env -S 'cmd args'` splits its value into a command line.
2076 self.code_payload(payload, *payload_dynamic, depth);
2077 }
2078 let mut dynamic = line.dynamic.clone();
2079 mark_replacement_operands(tokens, &heads.heads, &mut dynamic);
2080 for &head in &heads.heads {
2081 // `sudo rm -rf /` is an `rm -rf /`: emit the command the wrappers
2082 // run, with their options and operands removed.
2083 if head > 0 {
2084 self.emit(&tokens[head..]);
2085 }
2086 // Also keep a wrapper's options in front of the command it runs,
2087 // so a deny rule can still skip them as flags if the option table
2088 // misreads one. (`command -v NAME` runs nothing: no head follows.)
2089 if wrapper_index(&tokens[head]).is_some()
2090 && heads.heads.iter().any(|&inner| inner > head)
2091 {
2092 self.emit(&tokens[head + 1..]);
2093 }
2094 // A command word (or a wrapper word before it) that the shell
2095 // rewrites at run time cannot be matched against any rule.
2096 if tokens[..=head]
2097 .iter()
2098 .zip(&dynamic)
2099 .any(|(token, dynamic)| *dynamic && !is_env_assignment(token))
2100 {
2101 self.dynamic = true;
2102 }
2103 if line.odd[head] && !matches!(tokens[head].as_str(), "[" | "[[") {
2104 self.dynamic = true;
2105 }
2106 let name = command_name(&tokens[head]);
2107 let args_dynamic = dynamic[head + 1..].iter().any(|dynamic| *dynamic);
2108 self.arguments_dynamic |= args_dynamic;
2109 match name.as_str() {
2110 // `eval …` takes a *command line* as data. Parse it.
2111 "eval" | "iex" | "invoke-expression" => {
2112 self.dynamic |= name != "eval" && head + 1 == tokens.len();
2113 self.code_payload(&tokens[head + 1..].join(" "), args_dynamic, depth);
2114 }
2115 "alias" | "hash" => {
2116 if name == "alias" {
2117 self.dynamic = true;
2118 } else {
2119 self.dynamic |= tokens[head + 1..].iter().any(|token| token != "-r");
2120 }
2121 for at in head + 1..tokens.len() {
2122 if name == "hash"
2123 && let Some(flags) = tokens[at].strip_prefix('-')
2124 && !flags.starts_with('-')
2125 && let Some(offset) = flags.find('p')
2126 {
2127 let path = &flags[offset + 1..];
2128 if path.is_empty() {
2129 if let Some(path) = tokens.get(at + 1) {
2130 self.code_payload(path, dynamic[at + 1], depth);
2131 }
2132 } else {
2133 self.code_payload(path, dynamic[at], depth);
2134 }
2135 } else if let Some((_, value)) = tokens[at].split_once('=') {
2136 self.code_payload(value, dynamic[at], depth);
2137 }
2138 }
2139 }
2140 _ if REBINDING_BUILTINS.contains(&name.as_str()) => self.dynamic = true,
2141 "at" | "batch" => {
2142 self.dynamic |= !line.heredoc && !at_only_manages_jobs(tokens, head, &dynamic);
2143 }
2144 "source" | "." => match tokens.get(head + 1) {
2145 None if !line.heredoc => self.dynamic = true,
2146 Some(_) if dynamic[head + 1] => self.dynamic = true,
2147 Some(script) => self.dynamic |= script_read_at_run_time(script, line),
2148 _ => {}
2149 },
2150 "find" => self.record_find_exec(line, head, depth),
2151 // `trap 'code' SIGNAL…` runs its first operand later in this
2152 // shell.
2153 "trap" => {
2154 if let Some(at) =
2155 (head + 1..tokens.len()).find(|&at| !tokens[at].starts_with('-'))
2156 {
2157 self.code_payload(&tokens[at], dynamic[at], depth);
2158 }
2159 }
2160 // These hand the value of `-c` / `--command` to a shell.
2161 "su" | "runuser" | "flock" | "script" => {
2162 let flag_end = if name == "su" {
2163 tokens.len()
2164 } else {
2165 heads
2166 .heads
2167 .iter()
2168 .copied()
2169 .find(|&inner| inner > head)
2170 .unwrap_or(tokens.len())
2171 };
2172 for (payload, payload_dynamic) in
2173 command_option_payloads(tokens, head, &dynamic, flag_end)
2174 {
2175 self.code_payload(&payload, payload_dynamic, depth);
2176 }
2177 }
2178 // `watch` and `sg GROUP [-c]` join their operands and hand
2179 // them to `sh -c`.
2180 "watch" | "sg" => {
2181 for &inner in heads.heads.iter().filter(|&&inner| inner > head) {
2182 let inner_dynamic = dynamic[inner..].iter().any(|dynamic| *dynamic);
2183 self.code_payload(&tokens[inner..].join(" "), inner_dynamic, depth);
2184 }
2185 }
2186 "watchexec" => {
2187 let shell_off = tokens[head + 1..].iter().any(|t| {
2188 t == "--no-shell"
2189 || t == "--shell=none"
2190 || (t.starts_with('-') && !t.starts_with("--") && t.contains('n'))
2191 });
2192 if !shell_off {
2193 for &inner in heads.heads.iter().filter(|&&inner| inner > head) {
2194 let inner_dynamic = dynamic[inner..].iter().any(|dynamic| *dynamic);
2195 self.code_payload(&tokens[inner..].join(" "), inner_dynamic, depth);
2196 }
2197 }
2198 }
2199 "entr" => {
2200 for &inner in heads.heads.iter().filter(|&&inner| inner > head) {
2201 let has_s = tokens[head + 1..inner]
2202 .iter()
2203 .any(|t| t.starts_with('-') && !t.starts_with("--") && t.contains('s'));
2204 if has_s {
2205 self.code_payload(&tokens[inner], dynamic[inner], depth);
2206 }
2207 }
2208 }
2209 "parallel" => {
2210 for (payload, payload_dynamic) in option_payloads(
2211 tokens,
2212 head,
2213 &dynamic,
2214 None,
2215 &["compress-program", "decompress-program"],
2216 true,
2217 tokens.len(),
2218 ) {
2219 self.code_payload(&payload, payload_dynamic, depth);
2220 }
2221 let inner: Vec<usize> = heads
2222 .heads
2223 .iter()
2224 .copied()
2225 .filter(|&inner| inner > head && !is_parallel_separator(&tokens[inner]))
2226 .collect();
2227 self.dynamic |= inner.is_empty();
2228 let mut code = false;
2229 for at in head + 1..tokens.len() {
2230 if is_parallel_separator(&tokens[at]) {
2231 code = matches!(tokens[at].as_str(), ":::" | ":::+");
2232 } else if code {
2233 self.code_payload(&tokens[at], dynamic[at], depth);
2234 }
2235 }
2236 for inner in inner {
2237 let inner_dynamic = dynamic[inner..].iter().any(|dynamic| *dynamic);
2238 self.code_payload(&tokens[inner..].join(" "), inner_dynamic, depth);
2239 }
2240 }
2241 // `cmd /c …` parses the rest as a cmd.exe command line, which
2242 // expands `%VAR%` and `!VAR!` and strips `^` escapes itself.
2243 "cmd" => {
2244 if let Some(at) = (head + 1..tokens.len()).find(|&at| {
2245 matches!(tokens[at].to_ascii_lowercase().as_str(), "/c" | "/k" | "/r")
2246 }) {
2247 let payload = tokens[at + 1..].join(" ");
2248 let payload_dynamic = dynamic[head + 1..].iter().any(|dynamic| *dynamic)
2249 || payload.contains(['%', '!', '^']);
2250 self.code_payload(&payload, payload_dynamic, depth);
2251 } else if dynamic[head + 1..].iter().any(|dynamic| *dynamic) {
2252 self.dynamic = true;
2253 }
2254 }
2255 "powershell" | "pwsh" => {
2256 if line.stdin_piped {
2257 self.dynamic = true;
2258 }
2259 self.record_powershell(line, head, &dynamic, depth);
2260 }
2261 "awk" | "gawk" | "mawk" | "nawk" | "goawk" => {
2262 self.record_awk_program(tokens, head, &dynamic, depth);
2263 }
2264 "sed" | "gsed" | "ssed" => {
2265 self.record_sed_program(tokens, head, &dynamic, depth);
2266 }
2267 _ if SHELL_NAMES.contains(&name.as_str()) => {
2268 match shell_input(&name, &tokens[head..], &dynamic[head..]) {
2269 ShellInput::Command(offsets) => {
2270 for offset in offsets {
2271 self.code_payload(
2272 &tokens[head + offset],
2273 dynamic[head + offset],
2274 depth,
2275 );
2276 }
2277 }
2278 ShellInput::Inline(payload, payload_dynamic) => {
2279 self.code_payload(&payload, payload_dynamic, depth);
2280 }
2281 ShellInput::Script(offset) => {
2282 self.dynamic |= dynamic[head + offset]
2283 || script_read_at_run_time(&tokens[head + offset], line);
2284 }
2285 // A heredoc body was already expanded as the script;
2286 // any other stdin is only known at run time.
2287 ShellInput::Stdin => self.dynamic |= !line.heredoc,
2288 }
2289 }
2290 _ => self.record_launcher_commands(line, head, &dynamic, &name, depth),
2291 }
2292 }
2293 for at in 0..tokens.len() {
2294 if tokens[at] == "--" && line.quoted[at] == WordQuote::Unquoted && at + 1 < tokens.len()
2295 {
2296 let inert = heads
2297 .heads
2298 .iter()
2299 .rev()
2300 .find(|&&head| head < at)
2301 .is_some_and(|&head| {
2302 INERT_DASH_DASH_HEADS.contains(&command_name(&tokens[head]).as_str())
2303 });
2304 self.record_extra_deny(&slice_line(line, at + 1), inert, depth + 1);
2305 }
2306 }
2307 }
2308
2309 fn record_extra_deny(&mut self, sub: &Line, inert: bool, depth: usize) {
2310 if depth > MAX_DEPTH {
2311 self.extra_deny_dropped = true;
2312 return;
2313 }
2314 if self.extra_deny.len() >= MAX_COMMANDS {
2315 self.extra_deny_dropped = true;
2316 self.extra_deny_cap_dropped = true;
2317 return;
2318 }
2319 let mut key = std::collections::hash_map::DefaultHasher::new();
2320 std::hash::Hash::hash(&self.literal_backslashes, &mut key);
2321 std::hash::Hash::hash(&sub.words, &mut key);
2322 std::hash::Hash::hash(&sub.dynamic, &mut key);
2323 std::hash::Hash::hash(&sub.odd, &mut key);
2324 std::hash::Hash::hash(&sub.quoted, &mut key);
2325 let key = std::hash::Hasher::finish(&key);
2326 if self
2327 .deny_suffix_depths
2328 .get(&key)
2329 .is_some_and(|&seen| seen <= depth)
2330 {
2331 return;
2332 }
2333 self.deny_suffix_depths.insert(key, depth);
2334 let mut child = Expander {
2335 out: Vec::new(),
2336 out_words: Vec::new(),
2337 extra_deny: Vec::new(),
2338 seen: HashSet::new(),
2339 seen_extra_deny: HashSet::new(),
2340 extra_deny_dropped: false,
2341 extra_deny_cap_dropped: false,
2342 deny_suffix_depths: std::mem::take(&mut self.deny_suffix_depths),
2343 tmux_work_left: self.tmux_work_left,
2344 literal_backslashes: self.literal_backslashes,
2345 dynamic: false,
2346 nested: false,
2347 arguments_dynamic: false,
2348 control: false,
2349 redirects: false,
2350 deny_only: true,
2351 inherited_stdin: false,
2352 groups: Vec::new(),
2353 };
2354 child.record(sub, depth);
2355 self.tmux_work_left = child.tmux_work_left;
2356 self.deny_suffix_depths = std::mem::take(&mut child.deny_suffix_depths);
2357 let child_dropped = child.extra_deny_dropped;
2358 let child_cap_dropped = child.extra_deny_cap_dropped;
2359 self.dynamic |= child_dropped | (!inert && child.dynamic);
2360 for cmd in child.extra_deny {
2361 self.emit_extra_deny(cmd);
2362 }
2363 self.extra_deny_dropped |= child_dropped;
2364 self.extra_deny_cap_dropped |= child_cap_dropped;
2365 if self.extra_deny_cap_dropped {
2366 self.deny_suffix_depths.clear();
2367 }
2368 }
2369
2370 fn record_launcher_commands(
2371 &mut self,
2372 line: &Line,
2373 head: usize,
2374 dynamic: &[bool],
2375 name: &str,
2376 depth: usize,
2377 ) {
2378 let tokens = &line.words;
2379 let mut truncated = false;
2380 if name == "bwrap" {
2381 if tokens[head + 1..]
2382 .iter()
2383 .any(|token| token == "--args" || token.starts_with("--args="))
2384 {
2385 self.dynamic = true;
2386 }
2387 } else if matches!(name, "docker" | "podman")
2388 && tokens.iter().any(|token| token == "buildx")
2389 && tokens
2390 .iter()
2391 .any(|token| token == "--call" || token.starts_with("--call="))
2392 {
2393 self.dynamic = true;
2394 }
2395 match name {
2396 "nix" => {
2397 for verb_idx in launcher_verb_targets(
2398 tokens,
2399 dynamic,
2400 &line.quoted,
2401 head + 1,
2402 &NIX_GLOBAL_SPEC,
2403 &mut truncated,
2404 ) {
2405 let Some(verb) = tokens.get(verb_idx).map(String::as_str) else {
2406 continue;
2407 };
2408 if !matches!(verb, "develop" | "shell") {
2409 continue;
2410 }
2411 for at in verb_idx + 1..tokens.len() {
2412 if tokens[at] == "--" && !dynamic[at] {
2413 break;
2414 }
2415 let attached = if let Some(long) = tokens[at].strip_prefix("--") {
2416 match long.split_once('=') {
2417 Some(("command", value)) => Some(value),
2418 None if long == "command" => Some(""),
2419 _ => None,
2420 }
2421 } else if let Some(flags) = tokens[at].strip_prefix('-') {
2422 let mut found = None;
2423 for (off, ch) in flags.char_indices() {
2424 if ch == 'c' {
2425 found = Some(&flags[off + 1..]);
2426 break;
2427 }
2428 if matches!(ch, 'f' | 'I' | 'k' | 'u' | 'o' | 'j') {
2429 break;
2430 }
2431 }
2432 found
2433 } else {
2434 None
2435 };
2436 let Some(attached) = attached else {
2437 if dynamic[at] {
2438 self.dynamic = true;
2439 }
2440 continue;
2441 };
2442 self.dynamic |= dynamic[at];
2443 if attached.is_empty() {
2444 if at + 1 < tokens.len() {
2445 self.code_payload(&tokens[at + 1], dynamic[at + 1], depth);
2446 self.record(&slice_line(line, at + 1), depth + 1);
2447 }
2448 } else {
2449 self.code_payload(attached, dynamic[at], depth);
2450 let combined = build_prefixed_line(attached, at, line, at + 1);
2451 self.record(&combined, depth + 1);
2452 }
2453 break;
2454 }
2455 }
2456 }
2457 "nix-shell" => {
2458 for (payload, payload_dynamic) in option_payloads(
2459 tokens,
2460 head,
2461 dynamic,
2462 None,
2463 &["run", "command"],
2464 true,
2465 tokens.len(),
2466 ) {
2467 self.code_payload(&payload, payload_dynamic, depth);
2468 }
2469 }
2470 "npx" => {
2471 for (payload, payload_dynamic) in option_payloads(
2472 tokens,
2473 head,
2474 dynamic,
2475 Some('c'),
2476 &["call"],
2477 true,
2478 tokens.len(),
2479 ) {
2480 self.code_payload(&payload, payload_dynamic, depth);
2481 }
2482 }
2483 "npm" => {
2484 if let Some(sub) = tokens.get(head + 1)
2485 && matches!(sub.as_str(), "exec" | "x")
2486 {
2487 for (payload, payload_dynamic) in option_payloads(
2488 tokens,
2489 head + 1,
2490 dynamic,
2491 Some('c'),
2492 &["call"],
2493 true,
2494 tokens.len(),
2495 ) {
2496 self.code_payload(&payload, payload_dynamic, depth);
2497 }
2498 } else {
2499 for verb_idx in launcher_verb_targets(
2500 tokens,
2501 dynamic,
2502 &line.quoted,
2503 head + 1,
2504 &EMPTY_WRAPPER_SPEC,
2505 &mut truncated,
2506 ) {
2507 if tokens
2508 .get(verb_idx)
2509 .is_some_and(|verb| matches!(verb.as_str(), "exec" | "x"))
2510 {
2511 for (payload, payload_dynamic) in option_payloads(
2512 tokens,
2513 verb_idx,
2514 dynamic,
2515 Some('c'),
2516 &["call"],
2517 true,
2518 tokens.len(),
2519 ) {
2520 self.code_payload(&payload, payload_dynamic, depth);
2521 }
2522 }
2523 }
2524 }
2525 }
2526 "ssh" | "dbclient" | "mosh" => {
2527 for (payload, payload_dynamic) in
2528 ssh_option_payloads(&tokens[head + 1..], &dynamic[head + 1..])
2529 {
2530 self.code_payload(&payload, payload_dynamic, depth);
2531 }
2532 if name == "mosh" {
2533 for (payload, payload_dynamic) in option_payloads(
2534 tokens,
2535 head,
2536 dynamic,
2537 None,
2538 &["ssh", "server", "client"],
2539 true,
2540 tokens.len(),
2541 ) {
2542 self.code_payload(&payload, payload_dynamic, depth);
2543 }
2544 }
2545 if ssh_skips_remote_command(&tokens[head + 1..], &dynamic[head + 1..]) {
2546 return;
2547 }
2548 let landings = resolve_wrapper_targets(
2549 tokens,
2550 dynamic,
2551 &line.quoted,
2552 head + 1,
2553 &SSH_SPEC,
2554 &mut truncated,
2555 );
2556 let mut remote_command = false;
2557 let prev_stdin = self.inherited_stdin;
2558 self.inherited_stdin |= line.stdin_piped || line.heredoc;
2559 for &landing in &landings {
2560 if landing < tokens.len() {
2561 remote_command = true;
2562 let rest = &tokens[landing..];
2563 let rest_dynamic = dynamic[landing..].iter().any(|d| *d);
2564 self.code_payload(&rest.join(" "), rest_dynamic, depth);
2565 if rest.len() > 1 {
2566 self.record(&slice_line(line, landing), depth + 1);
2567 }
2568 }
2569 }
2570 self.inherited_stdin = prev_stdin;
2571 if (!remote_command || landings.contains(&tokens.len()) || truncated)
2572 && line.stdin_piped
2573 {
2574 self.dynamic = true;
2575 }
2576 }
2577 "screen" => {
2578 for at in head + 1..tokens.len() {
2579 if tokens[at] != "-X" && tokens[at] != "-Q" {
2580 continue;
2581 }
2582 let rest = &tokens[at + 1..];
2583 if rest.is_empty() {
2584 self.dynamic |= dynamic[at];
2585 continue;
2586 }
2587 let rest_dynamic = dynamic[at + 1..].iter().any(|d| *d);
2588 self.record_screen_x(&rest.join(" "), rest_dynamic, depth);
2589 }
2590 if screen_attaches_only(&tokens[head + 1..], &dynamic[head + 1..]) {
2591 return;
2592 }
2593 for landing in resolve_wrapper_targets(
2594 tokens,
2595 dynamic,
2596 &line.quoted,
2597 head + 1,
2598 &SCREEN_SPEC,
2599 &mut truncated,
2600 ) {
2601 if landing < tokens.len() {
2602 self.record(&slice_line(line, landing), depth + 1);
2603 }
2604 }
2605 }
2606 "start-stop-daemon" => {
2607 self.record_start_stop_daemon(line, head, depth);
2608 }
2609 "tmux" => {
2610 self.record_tmux(line, head, dynamic, depth, &mut truncated);
2611 }
2612 "vagrant" => {
2613 for verb_idx in launcher_verb_targets(
2614 tokens,
2615 dynamic,
2616 &line.quoted,
2617 head + 1,
2618 &VAGRANT_GLOBAL_SPEC,
2619 &mut truncated,
2620 ) {
2621 let Some(verb) = tokens.get(verb_idx).map(String::as_str) else {
2622 continue;
2623 };
2624 if !matches!(verb, "ssh" | "winrm") {
2625 continue;
2626 }
2627 for (payload, payload_dynamic) in option_payloads(
2628 tokens,
2629 verb_idx,
2630 dynamic,
2631 Some('c'),
2632 &["command"],
2633 true,
2634 tokens.len(),
2635 ) {
2636 self.code_payload(&payload, payload_dynamic, depth);
2637 }
2638 if verb == "ssh"
2639 && let Some(dash_dash) = (verb_idx + 1..tokens.len()).find(|&i| {
2640 tokens[i] == "--"
2641 && line.quoted[i] == WordQuote::Unquoted
2642 && !dynamic[i]
2643 })
2644 && !ssh_skips_remote_command(
2645 &tokens[dash_dash + 1..],
2646 &dynamic[dash_dash + 1..],
2647 )
2648 {
2649 let extra_spec = Wrapper {
2650 operands: 0,
2651 ..SSH_SPEC
2652 };
2653 for landing in resolve_wrapper_targets(
2654 tokens,
2655 dynamic,
2656 &line.quoted,
2657 dash_dash + 1,
2658 &extra_spec,
2659 &mut truncated,
2660 ) {
2661 if landing < tokens.len() {
2662 let rest = &tokens[landing..];
2663 let rest_dynamic = dynamic[landing..].iter().any(|d| *d);
2664 self.code_payload(&rest.join(" "), rest_dynamic, depth);
2665 if rest.len() > 1 {
2666 self.record(&slice_line(line, landing), depth + 1);
2667 }
2668 }
2669 }
2670 }
2671 }
2672 }
2673 "helm" => {
2674 self.record_helm(line, head, depth, &mut truncated);
2675 }
2676 _ => {
2677 if name == "launchctl" {
2678 for verb_idx in launcher_verb_targets(
2679 tokens,
2680 dynamic,
2681 &line.quoted,
2682 head + 1,
2683 &EMPTY_WRAPPER_SPEC,
2684 &mut truncated,
2685 ) {
2686 if tokens.get(verb_idx).map(String::as_str) == Some("submit") {
2687 self.record_exec_flag_command(line, verb_idx, &['p'], &[], depth);
2688 }
2689 }
2690 } else if name == "op" {
2691 for verb_idx in launcher_verb_targets(
2692 tokens,
2693 dynamic,
2694 &line.quoted,
2695 head + 1,
2696 &OP_GLOBAL_SPEC,
2697 &mut truncated,
2698 ) {
2699 if tokens.get(verb_idx).map(String::as_str) == Some("plugin") {
2700 for sub_idx in launcher_verb_targets(
2701 tokens,
2702 dynamic,
2703 &line.quoted,
2704 verb_idx + 1,
2705 &OP_GLOBAL_SPEC,
2706 &mut truncated,
2707 ) {
2708 if tokens.get(sub_idx).map(String::as_str) == Some("run") {
2709 for landing in resolve_wrapper_targets(
2710 tokens,
2711 dynamic,
2712 &line.quoted,
2713 sub_idx + 1,
2714 &OP_RUN_SPEC,
2715 &mut truncated,
2716 ) {
2717 if landing < tokens.len() {
2718 self.record(&slice_line(line, landing), depth + 1);
2719 }
2720 }
2721 }
2722 }
2723 }
2724 }
2725 }
2726 for launcher in VERB_LAUNCHERS {
2727 if launcher.program != name {
2728 continue;
2729 }
2730 for verb_idx in launcher_verb_targets(
2731 tokens,
2732 dynamic,
2733 &line.quoted,
2734 head + 1,
2735 launcher.global,
2736 &mut truncated,
2737 ) {
2738 let mut verb_idx = verb_idx;
2739 let mut verb = tokens.get(verb_idx).map(String::as_str);
2740 if let Some(group) = verb
2741 && launcher.groups.contains(&group)
2742 {
2743 verb_idx += 1;
2744 let value_opts: &[&str] = match group {
2745 "compose" => &[
2746 "f",
2747 "file",
2748 "p",
2749 "project-name",
2750 "env-file",
2751 "project-directory",
2752 "profile",
2753 "parallel",
2754 "ansi",
2755 "log-level",
2756 "config",
2757 "H",
2758 "host",
2759 "context",
2760 "tlscacert",
2761 "tlscert",
2762 "tlskey",
2763 "progress",
2764 "policy",
2765 "build-arg",
2766 "builder",
2767 ],
2768 _ => &[],
2769 };
2770 while let Some(word) = tokens.get(verb_idx) {
2771 if !word.starts_with('-') || word == "--" {
2772 break;
2773 }
2774 let opt_name =
2775 word.trim_start_matches('-').split('=').next().unwrap_or("");
2776 verb_idx += if !word.contains('=') && value_opts.contains(&opt_name)
2777 {
2778 2
2779 } else {
2780 1
2781 };
2782 }
2783 verb = tokens.get(verb_idx).map(String::as_str);
2784 }
2785 let Some(verb) = verb else {
2786 continue;
2787 };
2788 if !launcher.verbs.contains(&verb) {
2789 continue;
2790 }
2791 let is_container_run =
2792 matches!(name, "docker" | "podman") && matches!(verb, "run" | "create");
2793 if is_container_run {
2794 for at in verb_idx + 1..tokens.len() {
2795 if tokens[at] == "--" {
2796 break;
2797 }
2798 if let Some(value) = tokens[at].strip_prefix("--health-cmd=") {
2799 self.code_payload(value, dynamic[at], depth);
2800 } else if tokens[at] == "--health-cmd"
2801 && let Some(value) = tokens.get(at + 1)
2802 {
2803 self.code_payload(value, dynamic[at + 1], depth);
2804 }
2805 }
2806 }
2807 let entrypoints_before = |end: usize| {
2808 if !is_container_run {
2809 return Vec::new();
2810 }
2811 let end = end.min(tokens.len()).max(verb_idx + 1);
2812 find_entrypoints(
2813 &tokens[verb_idx + 1..end],
2814 dynamic,
2815 &line.quoted,
2816 verb_idx + 1,
2817 )
2818 };
2819 if is_container_run {
2820 let image_spec = Wrapper {
2821 operands: 0,
2822 ..*launcher.subcmd
2823 };
2824 for image in resolve_wrapper_targets(
2825 tokens,
2826 dynamic,
2827 &line.quoted,
2828 verb_idx + 1,
2829 &image_spec,
2830 &mut truncated,
2831 ) {
2832 if image >= tokens.len() {
2833 continue;
2834 }
2835 for (ep_val, ep_idx) in entrypoints_before(image) {
2836 if ep_val.is_empty() {
2837 self.dynamic |= dynamic[ep_idx];
2838 } else {
2839 let combined =
2840 build_prefixed_line(&ep_val, ep_idx, line, image + 1);
2841 self.record(&combined, depth + 1);
2842 }
2843 }
2844 }
2845 }
2846 for landing in resolve_wrapper_targets(
2847 tokens,
2848 dynamic,
2849 &line.quoted,
2850 verb_idx + 1,
2851 launcher.subcmd,
2852 &mut truncated,
2853 ) {
2854 for (ep_val, ep_idx) in entrypoints_before(landing) {
2855 if ep_val.is_empty() {
2856 self.dynamic |= dynamic[ep_idx];
2857 } else {
2858 let combined =
2859 build_prefixed_line(&ep_val, ep_idx, line, landing);
2860 self.record(&combined, depth + 1);
2861 }
2862 }
2863 if landing < tokens.len() {
2864 if launcher.shell_string {
2865 let rest = &tokens[landing..];
2866 let rest_dynamic = dynamic[landing..].iter().any(|d| *d);
2867 self.code_payload(&rest.join(" "), rest_dynamic, depth);
2868 if rest.len() > 1 {
2869 self.record(&slice_line(line, landing), depth + 1);
2870 }
2871 } else {
2872 self.record(&slice_line(line, landing), depth + 1);
2873 }
2874 }
2875 }
2876 }
2877 }
2878 }
2879 }
2880 self.dynamic |= truncated;
2881 }
2882
2883 fn mark_tmux_unresolved(&mut self) {
2884 self.dynamic = true;
2885 self.extra_deny_dropped |= self.deny_only;
2886 }
2887
2888 fn reserve_tmux_work(&mut self, amount: usize) -> bool {
2889 if charge_tmux_work(&mut self.tmux_work_left, amount) {
2890 return true;
2891 }
2892 self.mark_tmux_unresolved();
2893 false
2894 }
2895
2896 fn reserve_tmux_words(&mut self, words: &[String]) -> bool {
2897 self.reserve_tmux_work(words.len().saturating_add(1))
2898 && self.reserve_tmux_work(words.iter().map(String::len).fold(0, usize::saturating_add))
2899 }
2900
2901 fn record_tmux(
2902 &mut self,
2903 line: &Line,
2904 head: usize,
2905 dynamic: &[bool],
2906 depth: usize,
2907 truncated: &mut bool,
2908 ) {
2909 let tokens = &line.words;
2910 if !self.reserve_tmux_words(&tokens[head..]) {
2911 return;
2912 }
2913 for verb_idx in launcher_verb_targets(
2914 tokens,
2915 dynamic,
2916 &line.quoted,
2917 head + 1,
2918 &TMUX_GLOBAL_SPEC,
2919 truncated,
2920 ) {
2921 if verb_idx < tokens.len() {
2922 self.record_tmux_command_list(
2923 line,
2924 verb_idx,
2925 tokens.len(),
2926 dynamic,
2927 depth,
2928 truncated,
2929 );
2930 }
2931 }
2932 }
2933
2934 fn record_tmux_command_list(
2935 &mut self,
2936 line: &Line,
2937 start: usize,
2938 end: usize,
2939 dynamic: &[bool],
2940 depth: usize,
2941 truncated: &mut bool,
2942 ) {
2943 if depth > MAX_DEPTH || self.out.len() >= MAX_COMMANDS {
2944 self.mark_tmux_unresolved();
2945 return;
2946 }
2947 let tokens = &line.words;
2948 if !self.reserve_tmux_words(&tokens[start..end]) {
2949 return;
2950 }
2951 let mut seg_start = start;
2952 while seg_start < end && self.tmux_work_left > 0 {
2953 let mut seg_end = seg_start;
2954 while seg_end < end && tokens[seg_end] != ";" {
2955 seg_end += 1;
2956 }
2957 while seg_start < seg_end && tokens[seg_start].is_empty() {
2958 seg_start += 1;
2959 }
2960 if seg_start < seg_end {
2961 self.record_tmux_verb(line, seg_start, seg_end, dynamic, depth, truncated);
2962 }
2963 seg_start = seg_end + 1;
2964 }
2965 }
2966
2967 #[allow(clippy::too_many_arguments)]
2968 fn record_tmux_shell_verb(
2969 &mut self,
2970 line: &Line,
2971 verb_idx: usize,
2972 end: usize,
2973 spec: &Wrapper,
2974 dynamic: &[bool],
2975 depth: usize,
2976 truncated: &mut bool,
2977 ) {
2978 let tokens = &line.words;
2979 for landing in resolve_wrapper_targets(
2980 &tokens[..end],
2981 &dynamic[..end],
2982 &line.quoted[..end],
2983 verb_idx + 1,
2984 spec,
2985 truncated,
2986 ) {
2987 if landing < end {
2988 let rest = &tokens[landing..end];
2989 if !self.reserve_tmux_words(rest) {
2990 return;
2991 }
2992 let rest_dynamic = dynamic[landing..end].iter().any(|d| *d);
2993 self.code_payload(&rest.join(" "), rest_dynamic, depth);
2994 if rest.len() > 1 {
2995 self.record(&slice_line_range(line, landing, end), depth + 1);
2996 }
2997 }
2998 }
2999 }
3000
3001 fn record_tmux_verb(
3002 &mut self,
3003 line: &Line,
3004 verb_idx: usize,
3005 end: usize,
3006 dynamic: &[bool],
3007 depth: usize,
3008 truncated: &mut bool,
3009 ) {
3010 let tokens = &line.words;
3011 if !self.reserve_tmux_words(&tokens[verb_idx..end]) {
3012 return;
3013 }
3014 if dynamic[verb_idx] || line.odd[verb_idx] {
3015 self.dynamic = true;
3016 }
3017 match tokens[verb_idx].as_str() {
3018 "new-session" | "new" | "new-window" | "neww" | "split-window" | "splitw"
3019 | "respawn-pane" | "respawnp" | "respawn-window" | "respawnw" => {
3020 self.record_tmux_shell_verb(
3021 line,
3022 verb_idx,
3023 end,
3024 &TMUX_SUB_SPEC,
3025 dynamic,
3026 depth,
3027 truncated,
3028 );
3029 }
3030 "display-popup" | "popup" => {
3031 self.record_tmux_shell_verb(
3032 line,
3033 verb_idx,
3034 end,
3035 &TMUX_DISPLAY_POPUP_SPEC,
3036 dynamic,
3037 depth,
3038 truncated,
3039 );
3040 }
3041 "pipe-pane" | "pipep" => {
3042 self.record_tmux_shell_verb(
3043 line,
3044 verb_idx,
3045 end,
3046 &TMUX_PIPE_PANE_SPEC,
3047 dynamic,
3048 depth,
3049 truncated,
3050 );
3051 }
3052 "run-shell" | "run" => {
3053 for landing in resolve_wrapper_targets(
3054 &tokens[..end],
3055 &dynamic[..end],
3056 &line.quoted[..end],
3057 verb_idx + 1,
3058 &TMUX_RUN_SHELL_SPEC,
3059 truncated,
3060 ) {
3061 if landing < end {
3062 let rest = &tokens[landing..end];
3063 if !self.reserve_tmux_words(rest) {
3064 return;
3065 }
3066 let rest_dynamic = dynamic[landing..end].iter().any(|d| *d);
3067 self.expand_tmux_command_string(
3068 &rest.join(" "),
3069 rest_dynamic,
3070 true,
3071 depth,
3072 truncated,
3073 );
3074 if rest.len() > 1 {
3075 self.record(&slice_line_range(line, landing, end), depth + 1);
3076 }
3077 }
3078 }
3079 }
3080 "send-keys" | "send" => {
3081 for landing in resolve_wrapper_targets(
3082 &tokens[..end],
3083 &dynamic[..end],
3084 &line.quoted[..end],
3085 verb_idx + 1,
3086 &TMUX_SEND_KEYS_SPEC,
3087 truncated,
3088 ) {
3089 if landing < end {
3090 let rest = &tokens[landing..end];
3091 if !self.reserve_tmux_words(rest) {
3092 return;
3093 }
3094 for (offset, operand) in rest.iter().enumerate() {
3095 self.code_payload(operand, dynamic[landing + offset], depth);
3096 }
3097 if rest.len() > 1 {
3098 self.record(&slice_line_range(line, landing, end), depth + 1);
3099 }
3100 }
3101 }
3102 }
3103 "if-shell" | "if" => {
3104 for landing in resolve_wrapper_targets(
3105 &tokens[..end],
3106 &dynamic[..end],
3107 &line.quoted[..end],
3108 verb_idx + 1,
3109 &TMUX_IF_SHELL_SPEC,
3110 truncated,
3111 ) {
3112 if landing < end {
3113 if !self.reserve_tmux_words(&tokens[landing..end]) {
3114 return;
3115 }
3116 for at in landing..end {
3117 self.expand_tmux_command_string(
3118 &tokens[at],
3119 dynamic[at],
3120 true,
3121 depth,
3122 truncated,
3123 );
3124 }
3125 }
3126 }
3127 }
3128 "confirm-before" | "confirm" => {
3129 for landing in resolve_wrapper_targets(
3130 &tokens[..end],
3131 &dynamic[..end],
3132 &line.quoted[..end],
3133 verb_idx + 1,
3134 &TMUX_CONFIRM_BEFORE_SPEC,
3135 truncated,
3136 ) {
3137 if landing < end {
3138 let rest = &tokens[landing..end];
3139 if !self.reserve_tmux_words(rest) {
3140 return;
3141 }
3142 let rest_dynamic = dynamic[landing..end].iter().any(|d| *d);
3143 self.expand_tmux_command_string(
3144 &rest.join(" "),
3145 rest_dynamic,
3146 true,
3147 depth,
3148 truncated,
3149 );
3150 if rest.len() > 1 {
3151 self.record_tmux_command_list(
3152 line,
3153 landing,
3154 end,
3155 dynamic,
3156 depth + 1,
3157 truncated,
3158 );
3159 }
3160 }
3161 }
3162 }
3163 "command-prompt" => {
3164 self.record_tmux_command_prompt(line, verb_idx, end, dynamic, depth, truncated);
3165 }
3166 "bind-key" | "bind" => {
3167 for landing in resolve_wrapper_targets(
3168 &tokens[..end],
3169 &dynamic[..end],
3170 &line.quoted[..end],
3171 verb_idx + 1,
3172 &TMUX_BIND_KEY_SPEC,
3173 truncated,
3174 ) {
3175 if landing < end {
3176 self.record_tmux_command_list(
3177 line,
3178 landing,
3179 end,
3180 dynamic,
3181 depth + 1,
3182 truncated,
3183 );
3184 if end - landing == 1 {
3185 self.expand_tmux_command_string(
3186 &tokens[landing],
3187 dynamic[landing],
3188 false,
3189 depth,
3190 truncated,
3191 );
3192 }
3193 }
3194 }
3195 }
3196 "source-file" | "source"
3197 if !tmux_source_file_parse_only(tokens, verb_idx + 1, end, dynamic) =>
3198 {
3199 self.dynamic = true;
3200 }
3201 _ => {}
3202 }
3203 }
3204
3205 fn record_tmux_command_prompt(
3206 &mut self,
3207 line: &Line,
3208 verb_idx: usize,
3209 end: usize,
3210 dynamic: &[bool],
3211 depth: usize,
3212 truncated: &mut bool,
3213 ) {
3214 let tokens = &line.words;
3215 let mut inputs: Vec<(&str, bool)> = Vec::new();
3216 let mut literal_inputs = false;
3217 let mut at = verb_idx + 1;
3218 while at < end {
3219 let token = tokens[at].as_str();
3220 if token == "--" || !token.starts_with('-') || token.len() == 1 {
3221 break;
3222 }
3223 if token.starts_with("--") {
3224 at += 1;
3225 continue;
3226 }
3227 let flags = &token[1..];
3228 let mut consumes_next = false;
3229 for (offset, flag) in flags.char_indices() {
3230 if flag == 'l' {
3231 literal_inputs = true;
3232 continue;
3233 }
3234 if flag == 'I' {
3235 let rest = &flags[offset + flag.len_utf8()..];
3236 if rest.is_empty() {
3237 if at + 1 < end {
3238 inputs.push((&tokens[at + 1], dynamic[at + 1]));
3239 }
3240 consumes_next = true;
3241 } else {
3242 inputs.push((rest, dynamic[at]));
3243 }
3244 break;
3245 }
3246 if TMUX_COMMAND_PROMPT_SPEC.short_values.contains(flag) {
3247 consumes_next = offset + flag.len_utf8() == flags.len();
3248 break;
3249 }
3250 }
3251 at += if consumes_next { 2 } else { 1 };
3252 }
3253
3254 let landings: Vec<usize> = resolve_wrapper_targets(
3255 &tokens[..end],
3256 &dynamic[..end],
3257 &line.quoted[..end],
3258 verb_idx + 1,
3259 &TMUX_COMMAND_PROMPT_SPEC,
3260 truncated,
3261 )
3262 .into_iter()
3263 .filter(|&landing| landing < end)
3264 .collect();
3265
3266 if landings.is_empty() {
3267 for (input, input_dynamic) in &inputs {
3268 self.expand_tmux_command_string(input, *input_dynamic, true, depth, truncated);
3269 if self.tmux_work_left == 0 {
3270 return;
3271 }
3272 if !literal_inputs && input.contains(',') {
3273 for part in input.split(',') {
3274 if !part.is_empty() {
3275 self.expand_tmux_command_string(
3276 part,
3277 *input_dynamic,
3278 true,
3279 depth,
3280 truncated,
3281 );
3282 if self.tmux_work_left == 0 {
3283 return;
3284 }
3285 }
3286 }
3287 }
3288 }
3289 } else {
3290 for landing in landings {
3291 let template = &tokens[landing];
3292 let template_dynamic = dynamic[landing];
3293 self.expand_tmux_command_string(template, template_dynamic, true, depth, truncated);
3294 if self.tmux_work_left == 0 {
3295 return;
3296 }
3297 if template.contains('%') {
3298 for (input, input_dynamic) in &inputs {
3299 if !self.reserve_tmux_work(input.len().saturating_add(1)) {
3300 return;
3301 }
3302 if *input_dynamic {
3303 self.dynamic = true;
3304 }
3305 let parts: Vec<&str> = if literal_inputs {
3306 vec![input]
3307 } else {
3308 input.split(',').take(TMUX_PROMPT_INPUTS).collect()
3309 };
3310 let Some(substituted) = substitute_tmux_prompt_template(
3311 template,
3312 &parts,
3313 &mut self.tmux_work_left,
3314 ) else {
3315 self.mark_tmux_unresolved();
3316 return;
3317 };
3318 self.expand_tmux_command_string(
3319 &substituted,
3320 template_dynamic || *input_dynamic,
3321 true,
3322 depth,
3323 truncated,
3324 );
3325 }
3326 }
3327 }
3328 }
3329 }
3330
3331 fn expand_tmux_command_string(
3332 &mut self,
3333 payload: &str,
3334 payload_dynamic: bool,
3335 also_shell: bool,
3336 depth: usize,
3337 truncated: &mut bool,
3338 ) {
3339 if depth > MAX_DEPTH || self.out.len() >= MAX_COMMANDS {
3340 self.mark_tmux_unresolved();
3341 return;
3342 }
3343 if !self.reserve_tmux_work(payload.len().saturating_add(1)) {
3344 return;
3345 }
3346 if also_shell {
3347 self.code_payload(payload, payload_dynamic, depth);
3348 } else {
3349 self.dynamic |= payload_dynamic;
3350 if !payload.trim().is_empty() {
3351 self.nested = true;
3352 }
3353 }
3354 let (lines, uncertain) = tokenize_tmux_commands(payload);
3355 self.dynamic |= uncertain;
3356 for sub_line in &lines {
3357 self.record_tmux_command_list(
3358 sub_line,
3359 0,
3360 sub_line.words.len(),
3361 &sub_line.dynamic,
3362 depth + 1,
3363 truncated,
3364 );
3365 }
3366 }
3367
3368 fn record_start_stop_daemon(&mut self, line: &Line, head: usize, depth: usize) {
3369 let tokens = &line.words;
3370 let opt_end = (head + 1..tokens.len())
3371 .find(|&i| {
3372 tokens[i] == "--" && line.quoted[i] == WordQuote::Unquoted && !line.dynamic[i]
3373 })
3374 .unwrap_or(tokens.len());
3375 let has_dynamic = line.dynamic[head + 1..opt_end].iter().any(|&d| d);
3376 let stop = tokens[head + 1..opt_end].iter().any(|t| {
3377 matches!(t.as_str(), "--stop" | "--status" | "--help" | "--version")
3378 || (t.starts_with('-')
3379 && !t.starts_with("--")
3380 && t[1..].contains(['K', 'T', 'H', 'V']))
3381 });
3382 let explicit_start = tokens[head + 1..opt_end].iter().any(|t| {
3383 t == "--start" || (t.starts_with('-') && !t.starts_with("--") && t[1..].contains('S'))
3384 });
3385 if stop && !explicit_start && !has_dynamic {
3386 return;
3387 }
3388 self.record_exec_flag_command(line, head, &['x', 'a'], &["exec", "startas"], depth);
3389 }
3390
3391 fn record_exec_flag_command(
3392 &mut self,
3393 line: &Line,
3394 head: usize,
3395 short_flags: &[char],
3396 long_flags: &[&str],
3397 depth: usize,
3398 ) {
3399 let tokens = &line.words;
3400 let dash_dash = (head + 1..tokens.len()).find(|&i| {
3401 tokens[i] == "--" && line.quoted[i] == WordQuote::Unquoted && !line.dynamic[i]
3402 });
3403 let opt_end = dash_dash.unwrap_or(tokens.len());
3404 let args_start = dash_dash.map_or(tokens.len(), |i| i + 1);
3405 let mut found: Option<(String, usize)> = None;
3406 let mut i = head + 1;
3407 while i < opt_end {
3408 let token = tokens[i].as_str();
3409 let mut matched = false;
3410 if let Some(long) = token.strip_prefix("--") {
3411 let (name, inline) = match long.split_once('=') {
3412 Some((k, v)) => (k, Some(v)),
3413 None => (long, None),
3414 };
3415 if long_flags.contains(&name) {
3416 matched = true;
3417 if let Some(val) = inline {
3418 found = Some((val.to_string(), i));
3419 self.dynamic |= line.dynamic[i];
3420 } else if i + 1 < opt_end {
3421 found = Some((tokens[i + 1].clone(), i + 1));
3422 self.dynamic |= line.dynamic[i] || line.dynamic[i + 1];
3423 i += 1;
3424 } else {
3425 self.dynamic |= line.dynamic[i];
3426 }
3427 }
3428 } else if let Some(flags) = token.strip_prefix('-') {
3429 for (at, ch) in flags.char_indices() {
3430 if short_flags.contains(&ch) {
3431 matched = true;
3432 let rest = &flags[at + ch.len_utf8()..];
3433 if !rest.is_empty() {
3434 found = Some((rest.to_string(), i));
3435 self.dynamic |= line.dynamic[i];
3436 } else if i + 1 < opt_end {
3437 found = Some((tokens[i + 1].clone(), i + 1));
3438 self.dynamic |= line.dynamic[i] || line.dynamic[i + 1];
3439 i += 1;
3440 } else {
3441 self.dynamic |= line.dynamic[i];
3442 }
3443 break;
3444 }
3445 }
3446 }
3447 if !matched && line.dynamic[i] {
3448 self.dynamic = true;
3449 }
3450 i += 1;
3451 }
3452 if let Some((prog, prog_idx)) = found
3453 && !prog.is_empty()
3454 {
3455 let combined = build_prefixed_line(&prog, prog_idx, line, args_start);
3456 self.record(&combined, depth + 1);
3457 }
3458 }
3459
3460 fn record_helm(&mut self, line: &Line, head: usize, depth: usize, truncated: &mut bool) {
3461 let tokens = &line.words;
3462 let opt_end = (head + 1..tokens.len())
3463 .find(|&i| {
3464 tokens[i] == "--" && line.quoted[i] == WordQuote::Unquoted && !line.dynamic[i]
3465 })
3466 .unwrap_or(tokens.len());
3467 let mut renderers: Vec<(String, usize)> = Vec::new();
3468 let mut renderer_args: Vec<(String, usize)> = Vec::new();
3469 for i in head + 1..opt_end {
3470 let token = tokens[i].as_str();
3471 if line.dynamic[i]
3472 && line.quoted[i] != WordQuote::InlineScalar
3473 && (token.is_empty() || token.starts_with('-'))
3474 {
3475 self.dynamic = true;
3476 }
3477 if let Some(val) = token.strip_prefix("--post-renderer=") {
3478 renderers.push((val.to_string(), i));
3479 } else if token == "--post-renderer"
3480 && let Some(val) = tokens.get(i + 1).filter(|_| i + 1 < opt_end)
3481 {
3482 renderers.push((val.clone(), i + 1));
3483 } else if let Some(val) = token.strip_prefix("--post-renderer-args=") {
3484 renderer_args.push((val.to_string(), i));
3485 } else if token == "--post-renderer-args"
3486 && let Some(val) = tokens.get(i + 1).filter(|_| i + 1 < opt_end)
3487 {
3488 renderer_args.push((val.clone(), i + 1));
3489 }
3490 }
3491 let is_odd = |s: &str| {
3492 !s.chars()
3493 .enumerate()
3494 .all(|(idx, c)| is_plain_word_char(c, idx == 0))
3495 };
3496 let normalize_quote = |quote: WordQuote| match quote {
3497 WordQuote::InlineScalar => WordQuote::Quoted,
3498 quote => quote,
3499 };
3500 for (renderer, renderer_idx) in renderers {
3501 if line.dynamic[renderer_idx] {
3502 self.dynamic = true;
3503 }
3504 if renderer.is_empty() {
3505 continue;
3506 }
3507 let mut words = Vec::with_capacity(1 + renderer_args.len());
3508 let mut dynamic = Vec::with_capacity(1 + renderer_args.len());
3509 let mut odd = Vec::with_capacity(1 + renderer_args.len());
3510 let mut quoted = Vec::with_capacity(1 + renderer_args.len());
3511 words.push(renderer.clone());
3512 dynamic.push(line.dynamic[renderer_idx]);
3513 odd.push(is_odd(&renderer));
3514 quoted.push(normalize_quote(line.quoted[renderer_idx]));
3515 for (arg, arg_idx) in &renderer_args {
3516 words.push(arg.clone());
3517 dynamic.push(line.dynamic[*arg_idx]);
3518 odd.push(is_odd(arg));
3519 quoted.push(normalize_quote(line.quoted[*arg_idx]));
3520 }
3521 self.record(
3522 &Line {
3523 words,
3524 dynamic,
3525 odd,
3526 quoted,
3527 heredoc: false,
3528 stdin_piped: line.stdin_piped || line.heredoc,
3529 },
3530 depth + 1,
3531 );
3532 }
3533 for verb_idx in launcher_verb_targets(
3534 tokens,
3535 &line.dynamic,
3536 &line.quoted,
3537 head + 1,
3538 &HELM_GLOBAL_SPEC,
3539 truncated,
3540 ) {
3541 if tokens.get(verb_idx).map(String::as_str) == Some("plugin") {
3542 for sub_idx in launcher_verb_targets(
3543 tokens,
3544 &line.dynamic,
3545 &line.quoted,
3546 verb_idx + 1,
3547 &HELM_GLOBAL_SPEC,
3548 truncated,
3549 ) {
3550 if tokens.get(sub_idx).is_some_and(|sub| {
3551 matches!(sub.as_str(), "install" | "update" | "uninstall" | "remove")
3552 }) {
3553 self.dynamic = true;
3554 }
3555 }
3556 }
3557 }
3558 }
3559
3560 /// Code handed to another command as a string: parse it as a command line.
3561 fn code_payload(&mut self, payload: &str, dynamic: bool, depth: usize) {
3562 self.dynamic |= dynamic;
3563 self.expand(payload, depth + 1);
3564 }
3565
3566 /// `powershell` / `pwsh`: `-Command` (or any prefix of it) takes the rest
3567 /// of the line as code, `-EncodedCommand` cannot be read statically, and
3568 /// a bare operand may start code too (Windows PowerShell's default).
3569 /// PowerShell syntax is only approximated by the POSIX parser, which is
3570 /// enough to find the command words a deny rule names.
3571 fn record_powershell(&mut self, line: &Line, head: usize, dynamic: &[bool], depth: usize) {
3572 let tokens = &line.words;
3573 let rest = |at: usize| {
3574 (
3575 tokens[at..].join(" "),
3576 dynamic[at..].iter().any(|dynamic| *dynamic),
3577 )
3578 };
3579 let mut positional_seen = false;
3580 for at in head + 1..tokens.len() {
3581 let Some(option) = tokens[at].strip_prefix(['-', '/']) else {
3582 if !positional_seen {
3583 positional_seen = true;
3584 let (payload, payload_dynamic) = rest(at);
3585 self.code_payload(&payload, payload_dynamic, depth);
3586 }
3587 continue;
3588 };
3589 if dynamic[at] {
3590 self.dynamic = true;
3591 }
3592 let option = option.to_ascii_lowercase();
3593 if option.is_empty() {
3594 self.dynamic |= tokens[at] == "-";
3595 continue;
3596 }
3597 if "command".starts_with(option.as_str()) {
3598 if at + 1 >= tokens.len() || tokens[at + 1] == "-" {
3599 // The code arrives on stdin.
3600 self.dynamic = true;
3601 } else {
3602 let (payload, payload_dynamic) = rest(at + 1);
3603 self.code_payload(&payload, payload_dynamic, depth);
3604 }
3605 return;
3606 }
3607 if option == "ec" || "encodedcommand".starts_with(option.as_str()) {
3608 self.dynamic = true;
3609 return;
3610 }
3611 if "file".starts_with(option.as_str()) {
3612 match tokens.get(at + 1).map(String::as_str) {
3613 Some(operand)
3614 if is_runtime_script_file(
3615 operand,
3616 dynamic.get(at + 1).copied().unwrap_or(false),
3617 ) =>
3618 {
3619 self.dynamic = true;
3620 }
3621 None if line.stdin_piped || line.heredoc => self.dynamic = true,
3622 _ => {}
3623 }
3624 return;
3625 }
3626 }
3627 }
3628
3629 fn record_screen_x(&mut self, joined: &str, dynamic: bool, depth: usize) {
3630 if depth > MAX_DEPTH {
3631 self.dynamic = true;
3632 return;
3633 }
3634 let Some(words) = shlex::split(joined) else {
3635 self.dynamic = true;
3636 return;
3637 };
3638 let rest = |at: usize| words[at..].join(" ");
3639 match words.first().map(String::as_str) {
3640 Some("at") if words.len() > 2 => self.record_screen_x(&rest(2), dynamic, depth + 1),
3641 Some("stuff") | Some("exec") | Some("shell") | Some("screen") if words.len() > 1 => {
3642 self.code_payload(&rest(1), dynamic, depth);
3643 }
3644 Some("eval") | Some("command") if words.len() > 1 => {
3645 self.record_screen_x(&rest(1), dynamic, depth + 1);
3646 }
3647 Some("source") | Some("process") => {}
3648 Some(_) => self.code_payload(joined, dynamic, depth),
3649 None => {}
3650 }
3651 }
3652
3653 /// `find … -exec CMD … ;` runs `CMD` for every match.
3654 fn record_find_exec(&mut self, line: &Line, head: usize, depth: usize) {
3655 let tokens = &line.words;
3656 let mut index = head + 1;
3657 while index < tokens.len() {
3658 if line.dynamic[index] {
3659 if index + 1 < tokens.len() {
3660 self.record(&slice_line(line, index + 1), depth + 1);
3661 }
3662 if tokens[index].is_empty() || tokens[index].starts_with('-') {
3663 self.dynamic = true;
3664 }
3665 }
3666 if matches!(
3667 tokens[index].as_str(),
3668 "-exec" | "-execdir" | "-ok" | "-okdir" | "-delete"
3669 ) {
3670 // `-delete` is a standalone destructive action (equivalent to `-exec rm {} +`)
3671 // with no command payload. Treat it as a nested destructive action by creating
3672 // a synthetic `rm` payload.
3673 if tokens[index] == "-delete" {
3674 self.nested = true;
3675 let payload = Line {
3676 words: vec!["rm".to_string()],
3677 dynamic: vec![false],
3678 odd: vec![false],
3679 quoted: vec![WordQuote::Unquoted],
3680 heredoc: false,
3681 stdin_piped: line.stdin_piped || line.heredoc,
3682 };
3683 self.record(&payload, depth + 1);
3684 index += 1;
3685 continue;
3686 }
3687 let start = index + 1;
3688 let mut end = start;
3689 while end < tokens.len() && !matches!(tokens[end].as_str(), ";" | "+") {
3690 end += 1;
3691 }
3692 if start < end {
3693 self.nested = true;
3694 // `{}` is replaced by each file name found, so a word
3695 // holding it is only known at run time.
3696 let payload = Line {
3697 words: tokens[start..end].to_vec(),
3698 dynamic: (start..end)
3699 .map(|at| line.dynamic[at] || tokens[at].contains("{}"))
3700 .collect(),
3701 odd: line.odd[start..end].to_vec(),
3702 quoted: line.quoted[start..end].to_vec(),
3703 heredoc: false,
3704 stdin_piped: line.stdin_piped || line.heredoc,
3705 };
3706 self.record(&payload, depth + 1);
3707 }
3708 index = end;
3709 }
3710 index += 1;
3711 }
3712 }
3713
3714 fn record_awk_program(
3715 &mut self,
3716 tokens: &[String],
3717 head: usize,
3718 dynamic: &[bool],
3719 depth: usize,
3720 ) {
3721 let mut scripts: Vec<&str> = Vec::new();
3722 let mut has_script_option = false;
3723 let mut options_done = false;
3724 let mut first_operand: Option<usize> = None;
3725 let mut i = head + 1;
3726
3727 while i < tokens.len() {
3728 let token = tokens[i].as_str();
3729 if !options_done && token == "--" {
3730 options_done = true;
3731 i += 1;
3732 continue;
3733 }
3734 if !options_done && token.len() > 1 && token.starts_with('-') {
3735 if let Some(long) = token.strip_prefix("--") {
3736 let (opt, inline) = match long.split_once('=') {
3737 Some((k, v)) => (k, Some(v)),
3738 None => (long, None),
3739 };
3740 match opt {
3741 "source" => {
3742 has_script_option = true;
3743 if let Some((v, d)) = take_opt_val(inline, tokens, dynamic, &mut i) {
3744 push_script(&mut scripts, &mut self.dynamic, v, d);
3745 }
3746 }
3747 "file" | "exec" | "include" | "load" => {
3748 has_script_option = true;
3749 options_done |= opt == "exec";
3750 if let Some((v, d)) = take_opt_val(inline, tokens, dynamic, &mut i) {
3751 self.dynamic |= is_runtime_script_file(v, d);
3752 }
3753 }
3754 "field-separator" | "assign"
3755 if inline.is_none() && i + 1 < tokens.len() =>
3756 {
3757 i += 1;
3758 }
3759 _ => {}
3760 }
3761 } else {
3762 let flags = &token[1..];
3763 for (at, ch) in flags.char_indices() {
3764 let rest = &flags[at + ch.len_utf8()..];
3765 let inline = (!rest.is_empty()).then_some(rest);
3766 match ch {
3767 'e' => {
3768 has_script_option = true;
3769 if let Some((v, d)) = take_opt_val(inline, tokens, dynamic, &mut i)
3770 {
3771 push_script(&mut scripts, &mut self.dynamic, v, d);
3772 }
3773 break;
3774 }
3775 'f' | 'E' | 'i' | 'l' => {
3776 has_script_option = true;
3777 options_done |= ch == 'E';
3778 if let Some((v, d)) = take_opt_val(inline, tokens, dynamic, &mut i)
3779 {
3780 self.dynamic |= is_runtime_script_file(v, d);
3781 }
3782 break;
3783 }
3784 'W' => {
3785 if let Some((v, d)) = take_opt_val(inline, tokens, dynamic, &mut i)
3786 {
3787 if let Some(src) = v.strip_prefix("source=") {
3788 has_script_option = true;
3789 push_script(&mut scripts, &mut self.dynamic, src, d);
3790 } else if let Some(file) = v
3791 .strip_prefix("file=")
3792 .or_else(|| v.strip_prefix("exec="))
3793 .or_else(|| v.strip_prefix("include="))
3794 .or_else(|| v.strip_prefix("load="))
3795 {
3796 has_script_option = true;
3797 options_done |= v.starts_with("exec=");
3798 self.dynamic |= is_runtime_script_file(file, d);
3799 }
3800 }
3801 break;
3802 }
3803 'F' | 'v' => {
3804 if inline.is_none() && i + 1 < tokens.len() {
3805 i += 1;
3806 }
3807 break;
3808 }
3809 _ => {}
3810 }
3811 }
3812 }
3813 i += 1;
3814 continue;
3815 }
3816 if first_operand.is_none() {
3817 first_operand = Some(i);
3818 }
3819 i += 1;
3820 }
3821
3822 if !has_script_option && let Some(op) = first_operand {
3823 push_script(&mut scripts, &mut self.dynamic, &tokens[op], dynamic[op]);
3824 }
3825
3826 if !scripts.is_empty() {
3827 let program_bytes =
3828 scripts.iter().map(|script| script.len()).sum::<usize>() + scripts.len() - 1;
3829 if program_bytes > MAX_AWK_PROGRAM_BYTES {
3830 self.mark_awk_scan_incomplete();
3831 return;
3832 }
3833 let joined = scripts.join("\n");
3834 self.scan_awk_program(&joined, depth);
3835 }
3836 }
3837
3838 fn scan_awk_program(&mut self, program: &str, depth: usize) {
3839 let tokens = lex_awk_tokens(program);
3840 let mut closes = vec![None; tokens.len()];
3841 let mut opens = Vec::new();
3842 for (idx, token) in tokens.iter().enumerate() {
3843 match token {
3844 AwkToken::LParen => opens.push(idx),
3845 AwkToken::RParen => {
3846 if let Some(open) = opens.pop() {
3847 closes[open] = Some(idx);
3848 }
3849 }
3850 _ => {}
3851 }
3852 }
3853
3854 let mut remaining = MAX_AWK_SCAN_STEPS;
3855 for (idx, token) in tokens.iter().enumerate() {
3856 let expr = match token {
3857 AwkToken::Ident(name)
3858 if name == "system" && tokens.get(idx + 1) == Some(&AwkToken::LParen) =>
3859 {
3860 if let Some(close) = closes[idx + 1] {
3861 Some(&tokens[idx + 2..close])
3862 } else {
3863 self.dynamic = true;
3864 self.nested = true;
3865 continue;
3866 }
3867 }
3868 AwkToken::Pipe => {
3869 let mut after = idx + 1;
3870 while tokens.get(after) == Some(&AwkToken::Newline) {
3871 after += 1;
3872 }
3873 if matches!(tokens.get(after), Some(AwkToken::Ident(s)) if s == "getline") {
3874 awk_pipe_lhs(&tokens[..idx], &mut remaining)
3875 } else {
3876 awk_pipe_rhs(&tokens[after..], &mut remaining)
3877 }
3878 }
3879 _ => continue,
3880 };
3881 let Some(expr) = expr else {
3882 self.mark_awk_scan_incomplete();
3883 return;
3884 };
3885 let Some(next) = remaining.checked_sub(expr.len()) else {
3886 self.mark_awk_scan_incomplete();
3887 return;
3888 };
3889 remaining = next;
3890 if !self.emit_awk_command_expr(expr, depth, &mut remaining) {
3891 self.mark_awk_scan_incomplete();
3892 return;
3893 }
3894 }
3895 }
3896
3897 fn mark_awk_scan_incomplete(&mut self) {
3898 self.dynamic = true;
3899 self.nested = true;
3900 self.extra_deny_dropped |= self.deny_only;
3901 }
3902
3903 fn emit_awk_command_expr(
3904 &mut self,
3905 expr: &[AwkToken],
3906 depth: usize,
3907 remaining: &mut usize,
3908 ) -> bool {
3909 self.nested = true;
3910 if expr.is_empty() {
3911 self.dynamic = true;
3912 return true;
3913 }
3914 let mut joined = String::new();
3915 let mut paren_depth = 0usize;
3916 let mut has_str = false;
3917 let mut all_static = true;
3918 for tok in expr {
3919 match tok {
3920 AwkToken::Str(s) => {
3921 let Some(next) = remaining.checked_sub(s.len()) else {
3922 return false;
3923 };
3924 *remaining = next;
3925 has_str = true;
3926 joined.push_str(s);
3927 }
3928 AwkToken::LParen => paren_depth += 1,
3929 AwkToken::RParen if paren_depth > 0 => paren_depth -= 1,
3930 AwkToken::Newline => {}
3931 _ => {
3932 all_static = false;
3933 break;
3934 }
3935 }
3936 }
3937 if all_static && has_str && paren_depth == 0 {
3938 self.code_payload(&joined, false, depth);
3939 } else if let Some(AwkToken::Str(prefix)) = expr
3940 .iter()
3941 .find(|tok| !matches!(tok, AwkToken::LParen | AwkToken::Newline))
3942 {
3943 self.code_payload(prefix, true, depth);
3944 } else {
3945 self.dynamic = true;
3946 }
3947 true
3948 }
3949
3950 fn record_sed_program(
3951 &mut self,
3952 tokens: &[String],
3953 head: usize,
3954 dynamic: &[bool],
3955 depth: usize,
3956 ) {
3957 let mut scripts: Vec<&str> = Vec::new();
3958 let mut has_script_option = false;
3959 let mut bare_in_place = false;
3960 let mut options_done = false;
3961 let mut operands: Vec<usize> = Vec::new();
3962 let mut i = head + 1;
3963
3964 while i < tokens.len() {
3965 let token = tokens[i].as_str();
3966 if !options_done && token == "--" {
3967 options_done = true;
3968 i += 1;
3969 continue;
3970 }
3971 if !options_done && token.len() > 1 && token.starts_with('-') {
3972 if let Some(long) = token.strip_prefix("--") {
3973 let (opt, inline) = match long.split_once('=') {
3974 Some((k, v)) => (k, Some(v)),
3975 None => (long, None),
3976 };
3977 match opt {
3978 "expression" => {
3979 has_script_option = true;
3980 if let Some((v, d)) = take_opt_val(inline, tokens, dynamic, &mut i) {
3981 push_script(&mut scripts, &mut self.dynamic, v, d);
3982 }
3983 }
3984 "file" => {
3985 has_script_option = true;
3986 if let Some((v, d)) = take_opt_val(inline, tokens, dynamic, &mut i) {
3987 self.dynamic |= is_runtime_script_file(v, d);
3988 }
3989 }
3990 "line-length" if inline.is_none() && i + 1 < tokens.len() => {
3991 i += 1;
3992 }
3993 _ => {}
3994 }
3995 } else {
3996 let flags = &token[1..];
3997 for (at, ch) in flags.char_indices() {
3998 let rest = &flags[at + ch.len_utf8()..];
3999 let inline = (!rest.is_empty()).then_some(rest);
4000 match ch {
4001 'e' => {
4002 has_script_option = true;
4003 if let Some((v, d)) = take_opt_val(inline, tokens, dynamic, &mut i)
4004 {
4005 push_script(&mut scripts, &mut self.dynamic, v, d);
4006 }
4007 break;
4008 }
4009 'f' => {
4010 has_script_option = true;
4011 if let Some((v, d)) = take_opt_val(inline, tokens, dynamic, &mut i)
4012 {
4013 self.dynamic |= is_runtime_script_file(v, d);
4014 }
4015 break;
4016 }
4017 'l' => {
4018 if inline.is_none() && i + 1 < tokens.len() {
4019 i += 1;
4020 }
4021 break;
4022 }
4023 'i' => {
4024 bare_in_place |= inline.is_none();
4025 break;
4026 }
4027 _ => {}
4028 }
4029 }
4030 }
4031 i += 1;
4032 continue;
4033 }
4034 operands.push(i);
4035 i += 1;
4036 }
4037
4038 if !has_script_option && let Some(&first) = operands.first() {
4039 push_script(
4040 &mut scripts,
4041 &mut self.dynamic,
4042 &tokens[first],
4043 dynamic[first],
4044 );
4045 if bare_in_place
4046 && let Some(&second) = operands.get(1)
4047 && looks_like_bsd_sed_backup_suffix(&tokens[first])
4048 {
4049 push_script(
4050 &mut scripts,
4051 &mut self.dynamic,
4052 &tokens[second],
4053 dynamic[second],
4054 );
4055 }
4056 }
4057
4058 if !scripts.is_empty() {
4059 let joined = scripts.join("\n");
4060 self.scan_sed_script(&joined, depth);
4061 }
4062 }
4063
4064 fn scan_sed_script(&mut self, script: &str, depth: usize) {
4065 let chars: Vec<char> = script.chars().collect();
4066 let n = chars.len();
4067 let mut i = 0usize;
4068
4069 while i < n {
4070 while i < n && matches!(chars[i], ' ' | '\t' | '\r' | '\n' | ';' | '}') {
4071 i += 1;
4072 }
4073 if i >= n {
4074 break;
4075 }
4076 if chars[i] == '#' {
4077 while i < n && chars[i] != '\n' {
4078 i += 1;
4079 }
4080 continue;
4081 }
4082
4083 let (next_i, matched_addr) = skip_sed_address(&chars, i);
4084 i = next_i;
4085 if matched_addr {
4086 while i < n && matches!(chars[i], ' ' | '\t') {
4087 i += 1;
4088 }
4089 if i < n && chars[i] == ',' {
4090 (i, _) = skip_sed_address(&chars, i + 1);
4091 }
4092 }
4093 while i < n && matches!(chars[i], ' ' | '\t' | '!') {
4094 i += 1;
4095 }
4096 if i >= n {
4097 break;
4098 }
4099
4100 match chars[i] {
4101 ';' | '\n' | '\r' | '{' | '}' => i += 1,
4102 '#' => {
4103 while i < n && chars[i] != '\n' {
4104 i += 1;
4105 }
4106 }
4107 's' => {
4108 i += 1;
4109 if i >= n || matches!(chars[i], '\n' | '\\') {
4110 continue;
4111 }
4112 let delim = chars[i];
4113 i += 1;
4114 let pat_start = i;
4115 let pat_after = skip_sed_regex(&chars, pat_start, delim);
4116 if pat_after == 0 || pat_after > n || chars[pat_after - 1] != delim {
4117 i = pat_after;
4118 continue;
4119 }
4120 let pat_end = pat_after - 1;
4121 let (repl, repl_dynamic, after_repl) =
4122 parse_sed_replacement(&chars, pat_after, delim);
4123 i = after_repl;
4124 let mut has_e = false;
4125 while i < n {
4126 match chars[i] {
4127 'e' => {
4128 has_e = true;
4129 i += 1;
4130 }
4131 'w' | 'W' => {
4132 i += 1;
4133 while i < n && chars[i] != '\n' {
4134 i += 1;
4135 }
4136 break;
4137 }
4138 ';' | '\n' | '}' | '#' => break,
4139 _ => i += 1,
4140 }
4141 }
4142 if has_e {
4143 let pat: String = chars[pat_start..pat_end].iter().collect();
4144 let replaces_whole_line =
4145 matches!(pat.as_str(), ".*" | "^.*$" | "^.*" | ".*$");
4146 self.nested = true;
4147 if repl.trim().is_empty() {
4148 self.dynamic = true;
4149 } else {
4150 self.code_payload(&repl, !replaces_whole_line || repl_dynamic, depth);
4151 }
4152 }
4153 }
4154 'y' => {
4155 i += 1;
4156 if i < n && !matches!(chars[i], '\n' | '\\') {
4157 let delim = chars[i];
4158 i = skip_sed_delimited(&chars, i + 1, delim);
4159 i = skip_sed_delimited(&chars, i, delim);
4160 }
4161 }
4162 'e' => {
4163 i += 1;
4164 while i < n && matches!(chars[i], ' ' | '\t') {
4165 i += 1;
4166 }
4167 self.nested = true;
4168 if i >= n || matches!(chars[i], '\n' | '\r' | ';' | '}') {
4169 self.dynamic = true;
4170 } else {
4171 let mut cmd = String::new();
4172 while i < n && chars[i] != '\n' {
4173 if chars[i] == '\\' && i + 1 < n && chars[i + 1] == '\n' {
4174 i += 2;
4175 continue;
4176 }
4177 cmd.push(chars[i]);
4178 i += 1;
4179 }
4180 if cmd.trim().is_empty() {
4181 self.dynamic = true;
4182 } else {
4183 self.code_payload(&cmd, false, depth);
4184 }
4185 }
4186 }
4187 'a' | 'i' | 'c' => {
4188 i += 1;
4189 while i < n && matches!(chars[i], ' ' | '\t') {
4190 i += 1;
4191 }
4192 if i < n && chars[i] == '\\' && chars.get(i + 1) == Some(&'\n') {
4193 i += 2;
4194 }
4195 while i < n {
4196 let line_start = i;
4197 while i < n && chars[i] != '\n' {
4198 i += 1;
4199 }
4200 let trailing_bs = chars[line_start..i]
4201 .iter()
4202 .rev()
4203 .take_while(|&&c| c == '\\')
4204 .count();
4205 if i < n {
4206 i += 1;
4207 }
4208 if trailing_bs % 2 == 0 {
4209 break;
4210 }
4211 }
4212 }
4213 'r' | 'R' | 'w' | 'W' => {
4214 i += 1;
4215 while i < n && chars[i] != '\n' {
4216 i += 1;
4217 }
4218 }
4219 ':' | 'b' | 't' | 'T' | 'q' | 'Q' | 'l' | 'v' => {
4220 i += 1;
4221 while i < n && !matches!(chars[i], ';' | '\n' | '}' | '#') {
4222 i += 1;
4223 }
4224 }
4225 _ => i += 1,
4226 }
4227 }
4228 }
4229 }
4230
4231 fn take_opt_val<'a>(
4232 inline: Option<&'a str>,
4233 tokens: &'a [String],
4234 dynamic: &[bool],
4235 i: &mut usize,
4236 ) -> Option<(&'a str, bool)> {
4237 match inline {
4238 Some(v) => Some((v, dynamic[*i])),
4239 None if *i + 1 < tokens.len() => {
4240 *i += 1;
4241 Some((tokens[*i].as_str(), dynamic[*i]))
4242 }
4243 None => None,
4244 }
4245 }
4246
4247 fn push_script<'a>(scripts: &mut Vec<&'a str>, out_dynamic: &mut bool, val: &'a str, is_dyn: bool) {
4248 if is_dyn {
4249 *out_dynamic = true;
4250 } else {
4251 scripts.push(val);
4252 }
4253 }
4254
4255 fn is_runtime_script_file(val: &str, is_dynamic: bool) -> bool {
4256 is_dynamic || val == "-" || script_descriptor_fd(val).is_some()
4257 }
4258
4259 fn parse_hex_byte(chars: &[char], start: usize) -> Option<(char, usize)> {
4260 let mut val = 0u32;
4261 let mut end = start;
4262 while end < chars.len() && end < start + 2 {
4263 let Some(d) = chars[end].to_digit(16) else {
4264 break;
4265 };
4266 val = (val << 4) | d;
4267 end += 1;
4268 }
4269 (end > start).then_some((char::from((val & 0xff) as u8), end))
4270 }
4271
4272 #[derive(Debug, PartialEq, Eq)]
4273 enum AwkToken {
4274 Ident(String),
4275 Str(String),
4276 Number,
4277 Regex,
4278 LParen,
4279 RParen,
4280 LBracket,
4281 RBracket,
4282 LBrace,
4283 RBrace,
4284 Semi,
4285 Newline,
4286 Pipe,
4287 LogicalOr,
4288 IncDec,
4289 MultiOp,
4290 Other(char),
4291 }
4292
4293 fn lex_awk_tokens(input: &str) -> Vec<AwkToken> {
4294 let chars: Vec<char> = input.chars().collect();
4295 let n = chars.len();
4296 let mut tokens = Vec::new();
4297 let mut i = 0usize;
4298 let mut regex_allowed = true;
4299 let mut prev_cond_kw = false;
4300 let mut cond_parens: Vec<bool> = Vec::new();
4301
4302 while i < n {
4303 let ch = chars[i];
4304 match ch {
4305 ' ' | '\t' | '\r' => {
4306 i += 1;
4307 continue;
4308 }
4309 '\\' if chars.get(i + 1) == Some(&'\n') => {
4310 i += 2;
4311 continue;
4312 }
4313 '\\' if chars.get(i + 1) == Some(&'\r') && chars.get(i + 2) == Some(&'\n') => {
4314 i += 3;
4315 continue;
4316 }
4317 '#' => {
4318 while i < n && chars[i] != '\n' {
4319 i += 1;
4320 }
4321 continue;
4322 }
4323 '\n' => {
4324 tokens.push(AwkToken::Newline);
4325 regex_allowed = true;
4326 i += 1;
4327 continue;
4328 }
4329 _ => {}
4330 }
4331
4332 let mut next_cond_kw = false;
4333 match ch {
4334 '"' => {
4335 let (text, next) = lex_awk_string(&chars, i);
4336 tokens.push(AwkToken::Str(text));
4337 regex_allowed = false;
4338 i = next;
4339 }
4340 '/' if regex_allowed => {
4341 i = skip_sed_regex(&chars, i + 1, '/');
4342 tokens.push(AwkToken::Regex);
4343 regex_allowed = false;
4344 }
4345 '(' => {
4346 cond_parens.push(prev_cond_kw);
4347 tokens.push(AwkToken::LParen);
4348 regex_allowed = true;
4349 i += 1;
4350 }
4351 ')' => {
4352 tokens.push(AwkToken::RParen);
4353 regex_allowed = cond_parens.pop().unwrap_or(false);
4354 i += 1;
4355 }
4356 '[' | '{' | '}' | ';' => {
4357 tokens.push(match ch {
4358 '[' => AwkToken::LBracket,
4359 '{' => AwkToken::LBrace,
4360 '}' => AwkToken::RBrace,
4361 _ => AwkToken::Semi,
4362 });
4363 regex_allowed = true;
4364 i += 1;
4365 }
4366 ']' => {
4367 tokens.push(AwkToken::RBracket);
4368 regex_allowed = false;
4369 i += 1;
4370 }
4371 '|' => {
4372 if chars.get(i + 1) == Some(&'|') {
4373 tokens.push(AwkToken::LogicalOr);
4374 i += 2;
4375 } else {
4376 tokens.push(AwkToken::Pipe);
4377 i += if chars.get(i + 1) == Some(&'&') { 2 } else { 1 };
4378 }
4379 regex_allowed = true;
4380 }
4381 '+' | '-' if chars.get(i + 1) == Some(&ch) => {
4382 tokens.push(AwkToken::IncDec);
4383 regex_allowed = false;
4384 i += 2;
4385 }
4386 '&' if chars.get(i + 1) == Some(&'&') => {
4387 tokens.push(AwkToken::MultiOp);
4388 regex_allowed = true;
4389 i += 2;
4390 }
4391 '=' | '!' | '<' | '>' | '+' | '-' | '*' | '/' | '%' | '^'
4392 if chars.get(i + 1) == Some(&'=') =>
4393 {
4394 tokens.push(AwkToken::MultiOp);
4395 regex_allowed = true;
4396 i += 2;
4397 }
4398 '!' if chars.get(i + 1) == Some(&'~') => {
4399 tokens.push(AwkToken::MultiOp);
4400 regex_allowed = true;
4401 i += 2;
4402 }
4403 '0'..='9' => {
4404 i += 1;
4405 while i < n
4406 && (chars[i].is_ascii_alphanumeric() || chars[i] == '.' || chars[i] == '_')
4407 {
4408 i += 1;
4409 }
4410 tokens.push(AwkToken::Number);
4411 regex_allowed = false;
4412 }
4413 '.' if chars.get(i + 1).is_some_and(char::is_ascii_digit) => {
4414 i += 1;
4415 while i < n && (chars[i].is_ascii_alphanumeric() || chars[i] == '_') {
4416 i += 1;
4417 }
4418 tokens.push(AwkToken::Number);
4419 regex_allowed = false;
4420 }
4421 _ if ch.is_ascii_alphabetic() || ch == '_' => {
4422 let start = i;
4423 i += 1;
4424 while i < n && (chars[i].is_ascii_alphanumeric() || chars[i] == '_') {
4425 i += 1;
4426 }
4427 let word: String = chars[start..i].iter().collect();
4428 regex_allowed = matches!(
4429 word.as_str(),
4430 "if" | "else"
4431 | "do"
4432 | "while"
4433 | "for"
4434 | "return"
4435 | "print"
4436 | "printf"
4437 | "in"
4438 | "case"
4439 );
4440 next_cond_kw = matches!(word.as_str(), "if" | "while" | "for");
4441 tokens.push(AwkToken::Ident(word));
4442 }
4443 _ => {
4444 tokens.push(AwkToken::Other(ch));
4445 regex_allowed = true;
4446 i += 1;
4447 }
4448 }
4449 prev_cond_kw = next_cond_kw;
4450 }
4451 tokens
4452 }
4453
4454 fn lex_awk_string(chars: &[char], start: usize) -> (String, usize) {
4455 let n = chars.len();
4456 let mut i = start + 1;
4457 let mut out = String::new();
4458 while i < n {
4459 match chars[i] {
4460 '"' => return (out, i + 1),
4461 '\\' if i + 1 < n => {
4462 let next = chars[i + 1];
4463 match next {
4464 '\n' => i += 2,
4465 'a' | 'b' | 'f' | 'n' | 'r' | 't' | 'v' => {
4466 out.push(match next {
4467 'a' => '\x07',
4468 'b' => '\x08',
4469 'f' => '\x0c',
4470 'n' => '\n',
4471 'r' => '\r',
4472 't' => '\t',
4473 _ => '\x0b',
4474 });
4475 i += 2;
4476 }
4477 '0'..='7' => {
4478 let mut val = 0u32;
4479 let mut end = i + 1;
4480 while end < n && end < i + 4 && ('0'..='7').contains(&chars[end]) {
4481 val = (val << 3) | (chars[end] as u32 - '0' as u32);
4482 end += 1;
4483 }
4484 out.push(char::from((val & 0xff) as u8));
4485 i = end;
4486 }
4487 'x' => {
4488 if let Some((decoded, end)) = parse_hex_byte(chars, i + 2) {
4489 out.push(decoded);
4490 i = end;
4491 } else {
4492 out.push('x');
4493 i += 2;
4494 }
4495 }
4496 _ => {
4497 out.push(next);
4498 i += 2;
4499 }
4500 }
4501 }
4502 ch => {
4503 out.push(ch);
4504 i += 1;
4505 }
4506 }
4507 }
4508 (out, n)
4509 }
4510
4511 fn is_awk_lhs_stop(tok: &AwkToken) -> bool {
4512 match tok {
4513 AwkToken::LBrace
4514 | AwkToken::RBrace
4515 | AwkToken::Semi
4516 | AwkToken::Newline
4517 | AwkToken::Pipe
4518 | AwkToken::LogicalOr
4519 | AwkToken::MultiOp => true,
4520 AwkToken::Other(ch) => matches!(ch, ',' | '=' | '?' | ':' | '<' | '>' | '~' | '!'),
4521 AwkToken::Ident(w) => matches!(
4522 w.as_str(),
4523 "if" | "else" | "while" | "for" | "do" | "return" | "print" | "printf" | "in" | "case"
4524 ),
4525 _ => false,
4526 }
4527 }
4528
4529 fn awk_pipe_lhs<'a>(before: &'a [AwkToken], remaining: &mut usize) -> Option<&'a [AwkToken]> {
4530 let mut paren = 0usize;
4531 let mut bracket = 0usize;
4532 let mut start = before.len();
4533 while start > 0 {
4534 *remaining = remaining.checked_sub(1)?;
4535 let tok = &before[start - 1];
4536 match tok {
4537 AwkToken::RParen => paren += 1,
4538 AwkToken::LParen if paren > 0 => paren -= 1,
4539 AwkToken::LParen => break,
4540 AwkToken::RBracket => bracket += 1,
4541 AwkToken::LBracket if bracket > 0 => bracket -= 1,
4542 AwkToken::LBracket => break,
4543 _ if paren == 0 && bracket == 0 && is_awk_lhs_stop(tok) => break,
4544 _ => {}
4545 }
4546 start -= 1;
4547 }
4548 Some(&before[start..])
4549 }
4550
4551 fn awk_pipe_rhs<'a>(after: &'a [AwkToken], remaining: &mut usize) -> Option<&'a [AwkToken]> {
4552 let mut paren = 0usize;
4553 let mut bracket = 0usize;
4554 let mut end = 0usize;
4555 while end < after.len() {
4556 *remaining = remaining.checked_sub(1)?;
4557 match &after[end] {
4558 AwkToken::LParen => paren += 1,
4559 AwkToken::RParen if paren > 0 => paren -= 1,
4560 AwkToken::RParen => break,
4561 AwkToken::LBracket => bracket += 1,
4562 AwkToken::RBracket if bracket > 0 => bracket -= 1,
4563 AwkToken::RBracket => break,
4564 AwkToken::Semi
4565 | AwkToken::Newline
4566 | AwkToken::RBrace
4567 | AwkToken::LBrace
4568 | AwkToken::Pipe
4569 | AwkToken::LogicalOr
4570 if paren == 0 && bracket == 0 =>
4571 {
4572 break;
4573 }
4574 AwkToken::Ident(w) if paren == 0 && bracket == 0 && w == "else" => break,
4575 _ => {}
4576 }
4577 end += 1;
4578 }
4579 Some(&after[..end])
4580 }
4581
4582 fn looks_like_bsd_sed_backup_suffix(token: &str) -> bool {
4583 if token.is_empty() || token.starts_with('.') {
4584 return true;
4585 }
4586 token.len() > 1
4587 && !token.contains([
4588 '/', ';', '\n', '{', '}', ' ', '\t', ',', '!', '$', '\\', '#',
4589 ])
4590 && !token.starts_with(['s', 'e', 'y'])
4591 && !token.as_bytes()[0].is_ascii_digit()
4592 }
4593
4594 fn skip_sed_regex(chars: &[char], start: usize, delim: char) -> usize {
4595 let n = chars.len();
4596 let mut i = start;
4597 let mut in_class = false;
4598 while i < n {
4599 let ch = chars[i];
4600 if ch == '\\' && i + 1 < n {
4601 i += 2;
4602 continue;
4603 }
4604 if ch == '\n' {
4605 return i;
4606 }
4607 if !in_class {
4608 if ch == delim {
4609 return i + 1;
4610 }
4611 if ch == '[' {
4612 in_class = true;
4613 i += 1;
4614 if i < n && chars[i] == '^' {
4615 i += 1;
4616 }
4617 if i < n && chars[i] == ']' {
4618 i += 1;
4619 }
4620 continue;
4621 }
4622 } else if ch == '[' && i + 1 < n && matches!(chars[i + 1], ':' | '.' | '=') {
4623 let inner = chars[i + 1];
4624 i += 2;
4625 while i + 1 < n && !(chars[i] == inner && chars[i + 1] == ']') {
4626 i += 1;
4627 }
4628 i = (i + 2).min(n);
4629 continue;
4630 } else if ch == ']' {
4631 in_class = false;
4632 }
4633 i += 1;
4634 }
4635 n
4636 }
4637
4638 fn skip_sed_delimited(chars: &[char], start: usize, delim: char) -> usize {
4639 let n = chars.len();
4640 let mut i = start;
4641 while i < n {
4642 if chars[i] == '\\' && i + 1 < n {
4643 i += 2;
4644 continue;
4645 }
4646 if chars[i] == delim {
4647 return i + 1;
4648 }
4649 if chars[i] == '\n' {
4650 return i;
4651 }
4652 i += 1;
4653 }
4654 n
4655 }
4656
4657 fn skip_sed_address(chars: &[char], mut i: usize) -> (usize, bool) {
4658 let n = chars.len();
4659 while i < n && matches!(chars[i], ' ' | '\t') {
4660 i += 1;
4661 }
4662 if i >= n {
4663 return (i, false);
4664 }
4665 match chars[i] {
4666 '$' => (i + 1, true),
4667 '0'..='9' => {
4668 while i < n && chars[i].is_ascii_digit() {
4669 i += 1;
4670 }
4671 if i < n && chars[i] == '~' {
4672 i += 1;
4673 while i < n && chars[i].is_ascii_digit() {
4674 i += 1;
4675 }
4676 }
4677 (i, true)
4678 }
4679 '+' | '~' if chars.get(i + 1).is_some_and(char::is_ascii_digit) => {
4680 i += 1;
4681 while i < n && chars[i].is_ascii_digit() {
4682 i += 1;
4683 }
4684 (i, true)
4685 }
4686 '/' => {
4687 i = skip_sed_regex(chars, i + 1, '/');
4688 while i < n && matches!(chars[i], 'I' | 'i' | 'M' | 'm') {
4689 i += 1;
4690 }
4691 (i, true)
4692 }
4693 '\\' if i + 1 < n && chars[i + 1] != '\n' => {
4694 let delim = chars[i + 1];
4695 i = skip_sed_regex(chars, i + 2, delim);
4696 while i < n && matches!(chars[i], 'I' | 'i' | 'M' | 'm') {
4697 i += 1;
4698 }
4699 (i, true)
4700 }
4701 _ => (i, false),
4702 }
4703 }
4704
4705 fn parse_sed_replacement(chars: &[char], start: usize, delim: char) -> (String, bool, usize) {
4706 let n = chars.len();
4707 let mut i = start;
4708 let mut out = String::new();
4709 let mut has_dynamic = false;
4710 while i < n {
4711 let ch = chars[i];
4712 if ch == '\\' && i + 1 < n {
4713 let next = chars[i + 1];
4714 match next {
4715 '\n' | 'n' | 't' | 'r' | 'a' | 'f' | 'v' => {
4716 out.push(match next {
4717 '\n' | 'n' => '\n',
4718 't' => '\t',
4719 'r' => '\r',
4720 'a' => '\x07',
4721 'f' => '\x0c',
4722 _ => '\x0b',
4723 });
4724 i += 2;
4725 }
4726 '\\' | '&' => {
4727 out.push(next);
4728 i += 2;
4729 }
4730 c if c == delim => {
4731 out.push(delim);
4732 i += 2;
4733 }
4734 '0'..='9' | 'l' | 'L' | 'u' | 'U' | 'E' | 'c' | 'o' | 'd' => {
4735 has_dynamic = true;
4736 i += 2;
4737 }
4738 'x' => {
4739 has_dynamic = true;
4740 if let Some((decoded, end)) = parse_hex_byte(chars, i + 2) {
4741 out.push(decoded);
4742 i = end;
4743 } else {
4744 out.push('x');
4745 i += 2;
4746 }
4747 }
4748 _ => {
4749 out.push(next);
4750 i += 2;
4751 }
4752 }
4753 continue;
4754 }
4755 if ch == delim {
4756 return (out, has_dynamic, i + 1);
4757 }
4758 if ch == '\n' {
4759 return (out, true, i);
4760 }
4761 if ch == '&' {
4762 has_dynamic = true;
4763 }
4764 out.push(ch);
4765 i += 1;
4766 }
4767 (out, true, n)
4768 }
4769
4770 struct VerbLauncher {
4771 program: &'static str,
4772 groups: &'static [&'static str],
4773 verbs: &'static [&'static str],
4774 global: &'static Wrapper,
4775 subcmd: &'static Wrapper,
4776 shell_string: bool,
4777 }
4778
4779 const EMPTY_WRAPPER_SPEC: Wrapper = Wrapper {
4780 name: "",
4781 short_values: "",
4782 short_switches: "",
4783 long_values: &[],
4784 long_switches: &[],
4785 operands: 0,
4786 };
4787
4788 const ONE_OPERAND_SPEC: Wrapper = Wrapper {
4789 name: "",
4790 short_values: "",
4791 short_switches: "",
4792 long_values: &[],
4793 long_switches: &[],
4794 operands: 1,
4795 };
4796
4797 const NIX_GLOBAL_SPEC: Wrapper = Wrapper {
4798 name: "nix",
4799 short_values: "",
4800 short_switches: "v",
4801 long_values: &[
4802 "extra-experimental-features",
4803 "experimental-features",
4804 "accept-flake-config",
4805 "access-tokens",
4806 "builders",
4807 "cores",
4808 "eval-store",
4809 "extra-substituters",
4810 "extra-trusted-public-keys",
4811 "flake-registry",
4812 "keep-going",
4813 "log-format",
4814 "max-jobs",
4815 "override-input",
4816 "store",
4817 "substituters",
4818 "trusted-public-keys",
4819 ],
4820 long_switches: &[
4821 "debug",
4822 "help",
4823 "impure",
4824 "no-net",
4825 "offline",
4826 "quiet",
4827 "refresh",
4828 "show-trace",
4829 "verbose",
4830 "version",
4831 ],
4832 operands: 0,
4833 };
4834
4835 const UV_GLOBAL_SPEC: Wrapper = Wrapper {
4836 name: "uv",
4837 short_values: "Cpo",
4838 short_switches: "qvn",
4839 long_values: &[
4840 "cache-dir",
4841 "config-file",
4842 "python-preference",
4843 "directory",
4844 "project",
4845 "index-url",
4846 "default-index",
4847 "index",
4848 "extra-index-url",
4849 "find-links",
4850 "python",
4851 ],
4852 long_switches: &[
4853 "no-cache",
4854 "offline",
4855 "no-offline",
4856 "no-config",
4857 "quiet",
4858 "verbose",
4859 "no-progress",
4860 "managed-python",
4861 "no-managed-python",
4862 "native-tls",
4863 ],
4864 operands: 0,
4865 };
4866
4867 const UV_RUN_SPEC: Wrapper = Wrapper {
4868 name: "uv-run",
4869 short_values: "wpCm",
4870 short_switches: "sqvnU",
4871 long_values: &[
4872 "with",
4873 "with-editable",
4874 "with-requirements",
4875 "python",
4876 "module",
4877 "index-url",
4878 "default-index",
4879 "index",
4880 "extra-index-url",
4881 "find-links",
4882 "group",
4883 "only-group",
4884 "no-group",
4885 "extra",
4886 "package",
4887 "env-file",
4888 "directory",
4889 "project",
4890 "refresh-package",
4891 "upgrade-package",
4892 "config-setting",
4893 "index-strategy",
4894 "keyring-provider",
4895 "resolution",
4896 "prerelease",
4897 "exclude-newer",
4898 "link-mode",
4899 "python-platform",
4900 "cache-dir",
4901 "config-file",
4902 ],
4903 long_switches: &[
4904 "no-sync",
4905 "isolated",
4906 "no-project",
4907 "no-default-groups",
4908 "all-extras",
4909 "all-groups",
4910 "no-dev",
4911 "dev",
4912 "gui-script",
4913 "script",
4914 "frozen",
4915 "locked",
4916 "offline",
4917 "no-offline",
4918 "refresh",
4919 "upgrade",
4920 "no-build",
4921 "no-binary",
4922 "compile-bytecode",
4923 "no-config",
4924 "quiet",
4925 "verbose",
4926 "no-cache",
4927 "managed-python",
4928 "no-managed-python",
4929 "show-resolution",
4930 "no-env-file",
4931 ],
4932 operands: 0,
4933 };
4934
4935 const POETRY_SPEC: Wrapper = Wrapper {
4936 name: "poetry",
4937 short_values: "CP",
4938 short_switches: "qvnVh",
4939 long_values: &["directory", "project"],
4940 long_switches: &[
4941 "quiet",
4942 "verbose",
4943 "no-interaction",
4944 "ansi",
4945 "no-ansi",
4946 "version",
4947 "help",
4948 ],
4949 operands: 0,
4950 };
4951
4952 const PIPX_RUN_SPEC: Wrapper = Wrapper {
4953 name: "pipx-run",
4954 short_values: "i",
4955 short_switches: "qv",
4956 long_values: &["spec", "index-url", "pip-args", "python"],
4957 long_switches: &[
4958 "fetch-missing-python",
4959 "no-cache",
4960 "path",
4961 "verbose",
4962 "quiet",
4963 "help",
4964 ],
4965 operands: 0,
4966 };
4967
4968 const BUNDLE_GLOBAL_SPEC: Wrapper = Wrapper {
4969 name: "bundle",
4970 short_values: "",
4971 short_switches: "V",
4972 long_values: &[],
4973 long_switches: &["no-color", "verbose"],
4974 operands: 0,
4975 };
4976
4977 const BUNDLE_EXEC_SPEC: Wrapper = Wrapper {
4978 name: "bundle-exec",
4979 short_values: "",
4980 short_switches: "",
4981 long_values: &["gemfile"],
4982 long_switches: &["keep-file-descriptors"],
4983 operands: 0,
4984 };
4985
4986 const PERF_GLOBAL_SPEC: Wrapper = Wrapper {
4987 name: "perf",
4988 short_values: "",
4989 short_switches: "vhp",
4990 long_values: &["debug", "buildid-dir", "exec-path", "html-path"],
4991 long_switches: &[
4992 "version",
4993 "help",
4994 "paginate",
4995 "no-pager",
4996 "no-replace-objects",
4997 "bare",
4998 ],
4999 operands: 0,
5000 };
5001
5002 const PERF_SUB_SPEC: Wrapper = Wrapper {
5003 name: "perf-sub",
5004 short_values: "erIoptCuGFCcD",
5005 short_switches: "aABdgsTnvq",
5006 long_values: &[
5007 "event",
5008 "repeat",
5009 "interval-print",
5010 "output",
5011 "pid",
5012 "tid",
5013 "cpu",
5014 "cgroup",
5015 "uid",
5016 "delay",
5017 "freq",
5018 "count",
5019 "call-graph",
5020 "field-separator",
5021 "graph-opts",
5022 "sort",
5023 ],
5024 long_switches: &[
5025 "all-cpus",
5026 "append",
5027 "null",
5028 "sync",
5029 "metric-only",
5030 "json",
5031 "table",
5032 "per-core",
5033 "per-socket",
5034 "per-node",
5035 "per-thread",
5036 "topdown",
5037 "no-big-num",
5038 "detailed",
5039 "verbose",
5040 "quiet",
5041 ],
5042 operands: 0,
5043 };
5044
5045 const DOCKER_GLOBAL_SPEC: Wrapper = Wrapper {
5046 name: "docker",
5047 short_values: "Hcl",
5048 short_switches: "Dv",
5049 long_values: &[
5050 "host",
5051 "context",
5052 "config",
5053 "log-level",
5054 "tlscacert",
5055 "tlscert",
5056 "tlskey",
5057 ],
5058 long_switches: &["debug", "tls", "tlsverify"],
5059 operands: 0,
5060 };
5061
5062 const DOCKER_RUN_SPEC: Wrapper = Wrapper {
5063 name: "docker-run",
5064 short_values: "acelmpuvw",
5065 short_switches: "ditPq",
5066 long_values: &[
5067 "attach",
5068 "add-host",
5069 "blkio-weight",
5070 "cap-add",
5071 "cap-drop",
5072 "cgroupns",
5073 "cgroup-parent",
5074 "cidfile",
5075 "cpu-period",
5076 "cpu-quota",
5077 "cpu-rt-period",
5078 "cpu-rt-runtime",
5079 "cpu-shares",
5080 "cpus",
5081 "cpuset-cpus",
5082 "cpuset-mems",
5083 "detach-keys",
5084 "device",
5085 "device-cgroup-rule",
5086 "dns",
5087 "dns-option",
5088 "dns-search",
5089 "domainname",
5090 "entrypoint",
5091 "env",
5092 "env-file",
5093 "expose",
5094 "gpus",
5095 "group-add",
5096 "health-cmd",
5097 "health-interval",
5098 "health-retries",
5099 "health-start-interval",
5100 "health-start-period",
5101 "health-timeout",
5102 "hostname",
5103 "ip",
5104 "ip6",
5105 "ipc",
5106 "isolation",
5107 "kernel-memory",
5108 "label",
5109 "label-file",
5110 "link",
5111 "log-driver",
5112 "log-opt",
5113 "mac-address",
5114 "memory",
5115 "memory-reservation",
5116 "memory-swap",
5117 "memory-swappiness",
5118 "mount",
5119 "name",
5120 "network",
5121 "net",
5122 "network-alias",
5123 "oom-score-adj",
5124 "pid",
5125 "pids-limit",
5126 "platform",
5127 "publish",
5128 "pull",
5129 "restart",
5130 "runtime",
5131 "security-opt",
5132 "shm-size",
5133 "stop-signal",
5134 "stop-timeout",
5135 "storage-opt",
5136 "sysctl",
5137 "tmpfs",
5138 "user",
5139 "ulimit",
5140 "userns",
5141 "uts",
5142 "volume",
5143 "volume-driver",
5144 "volumes-from",
5145 "workdir",
5146 ],
5147 long_switches: &[
5148 "detach",
5149 "interactive",
5150 "tty",
5151 "publish-all",
5152 "rm",
5153 "privileged",
5154 "read-only",
5155 "init",
5156 "no-healthcheck",
5157 "oom-kill-disable",
5158 "sig-proxy",
5159 "help",
5160 "quiet",
5161 ],
5162 operands: 1,
5163 };
5164
5165 const DOCKER_EXEC_SPEC: Wrapper = Wrapper {
5166 name: "docker-exec",
5167 short_values: "euw",
5168 short_switches: "dit",
5169 long_values: &["detach-keys", "env", "env-file", "user", "workdir"],
5170 long_switches: &["detach", "interactive", "tty", "privileged"],
5171 operands: 1,
5172 };
5173
5174 const TMUX_GLOBAL_SPEC: Wrapper = Wrapper {
5175 name: "tmux",
5176 short_values: "cfLST",
5177 short_switches: "28CDhlNuvV",
5178 long_values: &[],
5179 long_switches: &[],
5180 operands: 0,
5181 };
5182
5183 const TMUX_SUB_SPEC: Wrapper = Wrapper {
5184 name: "tmux-sub",
5185 short_values: "ceFntxypP",
5186 short_switches: "AdDEPXhbkvI",
5187 long_values: &[],
5188 long_switches: &[],
5189 operands: 0,
5190 };
5191
5192 const TMUX_DISPLAY_POPUP_SPEC: Wrapper = Wrapper {
5193 name: "tmux-display-popup",
5194 short_values: "bcdehsStTwxy",
5195 short_switches: "BCEkKN",
5196 long_values: &[],
5197 long_switches: &[],
5198 operands: 0,
5199 };
5200
5201 const TMUX_CONFIRM_BEFORE_SPEC: Wrapper = Wrapper {
5202 name: "tmux-confirm-before",
5203 short_values: "cpt",
5204 short_switches: "by",
5205 long_values: &[],
5206 long_switches: &[],
5207 operands: 0,
5208 };
5209
5210 const TMUX_COMMAND_PROMPT_SPEC: Wrapper = Wrapper {
5211 name: "tmux-command-prompt",
5212 short_values: "IptT",
5213 short_switches: "1bFiklN",
5214 long_values: &[],
5215 long_switches: &[],
5216 operands: 0,
5217 };
5218
5219 const TMUX_BIND_KEY_SPEC: Wrapper = Wrapper {
5220 name: "tmux-bind-key",
5221 short_values: "NT",
5222 short_switches: "nr",
5223 long_values: &[],
5224 long_switches: &[],
5225 operands: 1,
5226 };
5227
5228 const TMUX_RUN_SHELL_SPEC: Wrapper = Wrapper {
5229 name: "tmux-run-shell",
5230 short_values: "cdt",
5231 short_switches: "bCE",
5232 long_values: &[],
5233 long_switches: &[],
5234 operands: 0,
5235 };
5236
5237 const TMUX_IF_SHELL_SPEC: Wrapper = Wrapper {
5238 name: "tmux-if-shell",
5239 short_values: "t",
5240 short_switches: "bF",
5241 long_values: &[],
5242 long_switches: &[],
5243 operands: 0,
5244 };
5245
5246 const TMUX_PIPE_PANE_SPEC: Wrapper = Wrapper {
5247 name: "tmux-pipe-pane",
5248 short_values: "t",
5249 short_switches: "IOo",
5250 long_values: &[],
5251 long_switches: &[],
5252 operands: 0,
5253 };
5254
5255 const TMUX_SEND_KEYS_SPEC: Wrapper = Wrapper {
5256 name: "tmux-send-keys",
5257 short_values: "cNt",
5258 short_switches: "FHKlMRX",
5259 long_values: &[],
5260 long_switches: &[],
5261 operands: 0,
5262 };
5263
5264 const SSH_SPEC: Wrapper = Wrapper {
5265 name: "ssh",
5266 short_values: "BbcDEeFIiJLlmOopQRSwW",
5267 short_switches: "46AaCfGgKkMNnqsTtVvXxYy",
5268 long_values: &[],
5269 long_switches: &[],
5270 operands: 1,
5271 };
5272
5273 const SCREEN_SPEC: Wrapper = Wrapper {
5274 name: "screen",
5275 short_values: "cehpsStT",
5276 short_switches: "aAdDfilmOqUvx46",
5277 long_values: &["Logfile"],
5278 long_switches: &["ls", "list", "wipe", "help", "version"],
5279 operands: 0,
5280 };
5281
5282 const OC_GLOBAL_SPEC: Wrapper = Wrapper {
5283 name: "oc",
5284 short_values: "nsv",
5285 short_switches: "h",
5286 long_values: &[
5287 "as",
5288 "as-group",
5289 "as-uid",
5290 "cache-dir",
5291 "certificate-authority",
5292 "client-certificate",
5293 "client-key",
5294 "cluster",
5295 "config",
5296 "context",
5297 "kubeconfig",
5298 "log-flush-frequency",
5299 "loglevel",
5300 "namespace",
5301 "password",
5302 "profile",
5303 "profile-output",
5304 "request-timeout",
5305 "server",
5306 "tls-server-name",
5307 "token",
5308 "user",
5309 "username",
5310 "v",
5311 "vmodule",
5312 ],
5313 long_switches: &[
5314 "disable-compression",
5315 "help",
5316 "insecure-skip-tls-verify",
5317 "match-server-version",
5318 "warnings-as-errors",
5319 ],
5320 operands: 0,
5321 };
5322
5323 const OC_EXEC_SPEC: Wrapper = Wrapper {
5324 name: "oc-exec",
5325 short_values: "cfnosv",
5326 short_switches: "itTqh",
5327 long_values: &[
5328 "as",
5329 "as-group",
5330 "as-uid",
5331 "as-user",
5332 "cache-dir",
5333 "certificate-authority",
5334 "client-certificate",
5335 "client-key",
5336 "cluster",
5337 "config",
5338 "container",
5339 "context",
5340 "env",
5341 "filename",
5342 "image",
5343 "image-stream",
5344 "kubeconfig",
5345 "log-flush-frequency",
5346 "loglevel",
5347 "namespace",
5348 "node-name",
5349 "output",
5350 "overrides",
5351 "password",
5352 "pod-running-timeout",
5353 "profile",
5354 "profile-output",
5355 "request-timeout",
5356 "server",
5357 "shell",
5358 "tls-server-name",
5359 "to-namespace",
5360 "token",
5361 "user",
5362 "username",
5363 "v",
5364 "vmodule",
5365 ],
5366 long_switches: &[
5367 "as-root",
5368 "command",
5369 "disable-compression",
5370 "help",
5371 "insecure-skip-tls-verify",
5372 "keep-annotations",
5373 "keep-init-containers",
5374 "keep-labels",
5375 "keep-liveness",
5376 "keep-readiness",
5377 "match-server-version",
5378 "no-tty",
5379 "one-container",
5380 "preserve-pod",
5381 "quiet",
5382 "rm",
5383 "stdin",
5384 "tty",
5385 "warnings-as-errors",
5386 ],
5387 operands: 1,
5388 };
5389
5390 const VAGRANT_GLOBAL_SPEC: Wrapper = Wrapper {
5391 name: "vagrant",
5392 short_values: "",
5393 short_switches: "vh",
5394 long_values: &[],
5395 long_switches: &[
5396 "version",
5397 "help",
5398 "color",
5399 "no-color",
5400 "machine-readable",
5401 "debug",
5402 "timestamp",
5403 "debug-timestamp",
5404 "no-tty",
5405 ],
5406 operands: 0,
5407 };
5408
5409 const OP_GLOBAL_SPEC: Wrapper = Wrapper {
5410 name: "op",
5411 short_values: "f",
5412 short_switches: "hv",
5413 long_values: &["account", "config", "encoding", "format", "session"],
5414 long_switches: &[
5415 "cache",
5416 "debug",
5417 "help",
5418 "iso-timestamps",
5419 "no-color",
5420 "omit-empty",
5421 "raw",
5422 "version",
5423 ],
5424 operands: 0,
5425 };
5426
5427 const OP_RUN_SPEC: Wrapper = Wrapper {
5428 name: "op-run",
5429 short_values: "f",
5430 short_switches: "hv",
5431 long_values: &[
5432 "env-file", "account", "config", "encoding", "format", "session",
5433 ],
5434 long_switches: &[
5435 "no-masking",
5436 "cache",
5437 "debug",
5438 "help",
5439 "iso-timestamps",
5440 "no-color",
5441 "omit-empty",
5442 "raw",
5443 "version",
5444 ],
5445 operands: 0,
5446 };
5447
5448 const OPAM_SPEC: Wrapper = Wrapper {
5449 name: "opam",
5450 short_values: "j",
5451 short_switches: "hqvyw",
5452 long_values: &[
5453 "cli",
5454 "color",
5455 "confirm-level",
5456 "debug-level",
5457 "git-version",
5458 "jobs",
5459 "root",
5460 "switch",
5461 ],
5462 long_switches: &[
5463 "best-effort",
5464 "check-path",
5465 "debug",
5466 "help",
5467 "inplace-path",
5468 "no",
5469 "no-switch",
5470 "quiet",
5471 "revert-env",
5472 "safe",
5473 "set-root",
5474 "set-switch",
5475 "strict",
5476 "update-env",
5477 "verbose",
5478 "version",
5479 "working-dir",
5480 "yes",
5481 ],
5482 operands: 0,
5483 };
5484
5485 const HELM_GLOBAL_SPEC: Wrapper = Wrapper {
5486 name: "helm",
5487 short_values: "n",
5488 short_switches: "h",
5489 long_values: &[
5490 "burst-limit",
5491 "kube-apiserver",
5492 "kube-as-group",
5493 "kube-as-user",
5494 "kube-ca-file",
5495 "kube-context",
5496 "kube-token",
5497 "kubeconfig",
5498 "namespace",
5499 "qps",
5500 "registry-config",
5501 "repository-cache",
5502 "repository-config",
5503 ],
5504 long_switches: &["debug", "help", "kube-insecure-skip-tls-verify"],
5505 operands: 0,
5506 };
5507
5508 const KUBECTL_GLOBAL_SPEC: Wrapper = Wrapper {
5509 name: "kubectl",
5510 short_values: "nsv",
5511 short_switches: "h",
5512 long_values: &[
5513 "as",
5514 "as-group",
5515 "as-uid",
5516 "certificate-authority",
5517 "client-certificate",
5518 "client-key",
5519 "cluster",
5520 "context",
5521 "kubeconfig",
5522 "namespace",
5523 "password",
5524 "profile",
5525 "profile-output",
5526 "request-timeout",
5527 "server",
5528 "token",
5529 "username",
5530 "vmodule",
5531 ],
5532 long_switches: &[
5533 "help",
5534 "insecure-skip-tls-verify",
5535 "show-managed-fields",
5536 "version",
5537 ],
5538 operands: 0,
5539 };
5540
5541 const KUBECTL_EXEC_SPEC: Wrapper = Wrapper {
5542 name: "kubectl-exec",
5543 short_values: "cfF",
5544 short_switches: "itqQ",
5545 long_values: &[
5546 "container",
5547 "filename",
5548 "pod-running-timeout",
5549 "context",
5550 "kubeconfig",
5551 "namespace",
5552 "server",
5553 "as",
5554 "token",
5555 "request-timeout",
5556 ],
5557 long_switches: &["stdin", "tty", "quiet"],
5558 operands: 1,
5559 };
5560
5561 const KUBECTL_RUN_SPEC: Wrapper = Wrapper {
5562 name: "kubectl-run",
5563 short_values: "cfF",
5564 short_switches: "itqQ",
5565 long_values: &[
5566 "container",
5567 "filename",
5568 "pod-running-timeout",
5569 "context",
5570 "kubeconfig",
5571 "namespace",
5572 "server",
5573 "as",
5574 "token",
5575 "request-timeout",
5576 "image",
5577 "image-pull-policy",
5578 "restart",
5579 "env",
5580 "port",
5581 "labels",
5582 "overrides",
5583 "serviceaccount",
5584 "annotations",
5585 "target",
5586 "profile",
5587 "set-image",
5588 "copy-to",
5589 "grace-period",
5590 "dry-run",
5591 "output",
5592 "sort-by",
5593 "template",
5594 "type",
5595 "vmodule",
5596 "field-manager",
5597 "field-validation",
5598 "cluster",
5599 "password",
5600 "username",
5601 "tls-server-name",
5602 "validate",
5603 "wait",
5604 "generator",
5605 "kustomize",
5606 "subresource",
5607 ],
5608 long_switches: &[
5609 "stdin",
5610 "tty",
5611 "quiet",
5612 "command",
5613 "attach",
5614 "cascade",
5615 "force",
5616 "leave-stdin-open",
5617 "privileged",
5618 "rm",
5619 "expose",
5620 "interactive",
5621 "now",
5622 "save-config",
5623 "ignore-not-found",
5624 "recursive",
5625 "insecure-skip-tls-verify",
5626 "disable-compression",
5627 "windows-line-endings",
5628 ],
5629 operands: 1,
5630 };
5631
5632 static VERB_LAUNCHERS: &[VerbLauncher] = &[
5633 VerbLauncher {
5634 program: "uv",
5635 groups: &[],
5636 verbs: &["run"],
5637 global: &UV_GLOBAL_SPEC,
5638 subcmd: &UV_RUN_SPEC,
5639 shell_string: false,
5640 },
5641 VerbLauncher {
5642 program: "poetry",
5643 groups: &[],
5644 verbs: &["run"],
5645 global: &POETRY_SPEC,
5646 subcmd: &POETRY_SPEC,
5647 shell_string: false,
5648 },
5649 VerbLauncher {
5650 program: "pipx",
5651 groups: &[],
5652 verbs: &["run"],
5653 global: &PIPX_RUN_SPEC,
5654 subcmd: &PIPX_RUN_SPEC,
5655 shell_string: false,
5656 },
5657 VerbLauncher {
5658 program: "bundle",
5659 groups: &[],
5660 verbs: &["exec"],
5661 global: &BUNDLE_GLOBAL_SPEC,
5662 subcmd: &BUNDLE_EXEC_SPEC,
5663 shell_string: false,
5664 },
5665 VerbLauncher {
5666 program: "bundler",
5667 groups: &[],
5668 verbs: &["exec"],
5669 global: &BUNDLE_GLOBAL_SPEC,
5670 subcmd: &BUNDLE_EXEC_SPEC,
5671 shell_string: false,
5672 },
5673 VerbLauncher {
5674 program: "perf",
5675 groups: &[],
5676 verbs: &["stat", "record", "trace", "ftrace"],
5677 global: &PERF_GLOBAL_SPEC,
5678 subcmd: &PERF_SUB_SPEC,
5679 shell_string: false,
5680 },
5681 VerbLauncher {
5682 program: "docker",
5683 groups: &["container", "compose"],
5684 verbs: &["run", "create"],
5685 global: &DOCKER_GLOBAL_SPEC,
5686 subcmd: &DOCKER_RUN_SPEC,
5687 shell_string: false,
5688 },
5689 VerbLauncher {
5690 program: "docker",
5691 groups: &["container", "compose"],
5692 verbs: &["exec"],
5693 global: &DOCKER_GLOBAL_SPEC,
5694 subcmd: &DOCKER_EXEC_SPEC,
5695 shell_string: false,
5696 },
5697 VerbLauncher {
5698 program: "podman",
5699 groups: &["container"],
5700 verbs: &["run", "create"],
5701 global: &DOCKER_GLOBAL_SPEC,
5702 subcmd: &DOCKER_RUN_SPEC,
5703 shell_string: false,
5704 },
5705 VerbLauncher {
5706 program: "podman",
5707 groups: &["container"],
5708 verbs: &["exec"],
5709 global: &DOCKER_GLOBAL_SPEC,
5710 subcmd: &DOCKER_EXEC_SPEC,
5711 shell_string: false,
5712 },
5713 VerbLauncher {
5714 program: "kubectl",
5715 groups: &[],
5716 verbs: &["exec"],
5717 global: &KUBECTL_GLOBAL_SPEC,
5718 subcmd: &KUBECTL_EXEC_SPEC,
5719 shell_string: false,
5720 },
5721 VerbLauncher {
5722 program: "kubectl",
5723 groups: &[],
5724 verbs: &["run", "debug"],
5725 global: &KUBECTL_GLOBAL_SPEC,
5726 subcmd: &KUBECTL_RUN_SPEC,
5727 shell_string: false,
5728 },
5729 VerbLauncher {
5730 program: "launchctl",
5731 groups: &[],
5732 verbs: &["asuser", "bsexec"],
5733 global: &EMPTY_WRAPPER_SPEC,
5734 subcmd: &ONE_OPERAND_SPEC,
5735 shell_string: false,
5736 },
5737 VerbLauncher {
5738 program: "oc",
5739 groups: &[],
5740 verbs: &["rsh", "exec", "debug", "run"],
5741 global: &OC_GLOBAL_SPEC,
5742 subcmd: &OC_EXEC_SPEC,
5743 shell_string: false,
5744 },
5745 VerbLauncher {
5746 program: "op",
5747 groups: &[],
5748 verbs: &["run"],
5749 global: &OP_GLOBAL_SPEC,
5750 subcmd: &OP_RUN_SPEC,
5751 shell_string: false,
5752 },
5753 VerbLauncher {
5754 program: "opam",
5755 groups: &[],
5756 verbs: &["exec"],
5757 global: &OPAM_SPEC,
5758 subcmd: &OPAM_SPEC,
5759 shell_string: false,
5760 },
5761 ];
5762
5763 const INERT_DASH_DASH_HEADS: &[&str] = &[
5764 "[",
5765 "basename",
5766 "base64",
5767 "cat",
5768 "chgrp",
5769 "chmod",
5770 "chown",
5771 "comm",
5772 "cp",
5773 "cut",
5774 "date",
5775 "dd",
5776 "df",
5777 "diff",
5778 "dirname",
5779 "du",
5780 "echo",
5781 "egrep",
5782 "fgrep",
5783 "file",
5784 "grep",
5785 "groups",
5786 "gunzip",
5787 "gzip",
5788 "head",
5789 "hexdump",
5790 "hostname",
5791 "id",
5792 "less",
5793 "ln",
5794 "ls",
5795 "md5sum",
5796 "mkdir",
5797 "more",
5798 "mv",
5799 "od",
5800 "printenv",
5801 "printf",
5802 "pwd",
5803 "readlink",
5804 "realpath",
5805 "rgrep",
5806 "rmdir",
5807 "seq",
5808 "sha1sum",
5809 "sha224sum",
5810 "sha256sum",
5811 "sha384sum",
5812 "sha512sum",
5813 "sort",
5814 "stat",
5815 "strings",
5816 "tail",
5817 "tar",
5818 "tee",
5819 "test",
5820 "touch",
5821 "tr",
5822 "uname",
5823 "uniq",
5824 "wc",
5825 "whoami",
5826 "xxd",
5827 "yes",
5828 ];
5829
5830 fn slice_line(line: &Line, start: usize) -> Line {
5831 slice_line_range(line, start, line.words.len())
5832 }
5833
5834 fn slice_line_range(line: &Line, start: usize, end: usize) -> Line {
5835 Line {
5836 words: line.words[start..end].to_vec(),
5837 dynamic: line.dynamic[start..end].to_vec(),
5838 odd: line.odd[start..end].to_vec(),
5839 quoted: line.quoted[start..end].to_vec(),
5840 heredoc: false,
5841 stdin_piped: line.stdin_piped || line.heredoc,
5842 }
5843 }
5844
5845 fn charge_tmux_work(work_left: &mut usize, amount: usize) -> bool {
5846 if amount >= *work_left {
5847 *work_left = 0;
5848 return false;
5849 }
5850 *work_left -= amount;
5851 true
5852 }
5853
5854 fn substitute_tmux_prompt_template(
5855 template: &str,
5856 inputs: &[&str],
5857 work_left: &mut usize,
5858 ) -> Option<String> {
5859 if !charge_tmux_work(work_left, template.len().saturating_add(1)) {
5860 return None;
5861 }
5862 let mut out = template.to_string();
5863 if let Some(first) = inputs.first()
5864 && let Some(pos) = out.find("%%")
5865 {
5866 let len = if out[pos + 2..].starts_with('%') {
5867 3
5868 } else {
5869 2
5870 };
5871 if !charge_tmux_work(
5872 work_left,
5873 input_replacement_len(out.len(), 1, len, first.len())?,
5874 ) {
5875 return None;
5876 }
5877 out.replace_range(pos..pos + len, first);
5878 }
5879 for (idx, input) in inputs.iter().take(TMUX_PROMPT_INPUTS).enumerate() {
5880 if !charge_tmux_work(work_left, out.len().saturating_add(1)) {
5881 return None;
5882 }
5883 let placeholder = format!("%{}", idx + 1);
5884 let count = out.matches(&placeholder).count();
5885 if count > 0 {
5886 let len = input_replacement_len(out.len(), count, placeholder.len(), input.len())?;
5887 if !charge_tmux_work(work_left, len) {
5888 return None;
5889 }
5890 out = out.replace(&placeholder, input);
5891 }
5892 }
5893 Some(out)
5894 }
5895
5896 fn input_replacement_len(
5897 source_bytes: usize,
5898 count: usize,
5899 placeholder_bytes: usize,
5900 replacement_bytes: usize,
5901 ) -> Option<usize> {
5902 source_bytes
5903 .checked_sub(count.checked_mul(placeholder_bytes)?)?
5904 .checked_add(count.checked_mul(replacement_bytes)?)
5905 }
5906
5907 fn tmux_source_file_parse_only(
5908 tokens: &[String],
5909 start: usize,
5910 end: usize,
5911 dynamic: &[bool],
5912 ) -> bool {
5913 let mut parse_only = false;
5914 let mut at = start;
5915 while at < end {
5916 if dynamic[at] {
5917 return false;
5918 }
5919 let token = tokens[at].as_str();
5920 if token == "--" {
5921 return parse_only && !dynamic[at + 1..end].iter().any(|&d| d);
5922 }
5923 if !token.starts_with('-') || token.len() == 1 {
5924 return parse_only && !dynamic[at..end].iter().any(|&d| d);
5925 }
5926 if token.starts_with("--") {
5927 return false;
5928 }
5929 let flags = &token[1..];
5930 let mut consumes_next = false;
5931 for (offset, flag) in flags.char_indices() {
5932 match flag {
5933 'n' => parse_only = true,
5934 'F' => return false,
5935 'q' | 'v' => {}
5936 't' => {
5937 if offset + flag.len_utf8() == flags.len() {
5938 if at + 1 >= end || dynamic[at + 1] {
5939 return false;
5940 }
5941 consumes_next = true;
5942 }
5943 break;
5944 }
5945 _ => return false,
5946 }
5947 }
5948 at += if consumes_next { 2 } else { 1 };
5949 }
5950 parse_only
5951 }
5952
5953 fn tokenize_tmux_commands(input: &str) -> (Vec<Line>, bool) {
5954 let chars: Vec<char> = input.chars().collect();
5955 let n = chars.len();
5956 let mut i = 0usize;
5957 let mut commands: Vec<Line> = Vec::new();
5958 let mut line = Line::default();
5959 let mut word = WordBuf::default();
5960 let mut uncertain = false;
5961 let mut groups: Vec<Group> = Vec::new();
5962 let mut last_closed_group: Option<usize> = None;
5963
5964 while i < n {
5965 let c = chars[i];
5966 match c {
5967 '#' if !word.started && word.text.is_empty() => {
5968 while i < n && chars[i] != '\n' {
5969 i += 1;
5970 }
5971 }
5972 '\\' => {
5973 if i + 1 < n {
5974 if chars[i + 1] != '\n' {
5975 word.text.push(chars[i + 1]);
5976 word.started = true;
5977 word.quoted = WordQuote::Quoted;
5978 }
5979 i += 2;
5980 } else {
5981 i += 1;
5982 }
5983 }
5984 '\'' => {
5985 word.started = true;
5986 word.quoted = WordQuote::Quoted;
5987 i += 1;
5988 while i < n && chars[i] != '\'' {
5989 word.text.push(chars[i]);
5990 i += 1;
5991 }
5992 uncertain |= i >= n;
5993 i = (i + 1).min(n);
5994 }
5995 '"' => {
5996 word.started = true;
5997 word.quoted = WordQuote::Quoted;
5998 i += 1;
5999 while i < n && chars[i] != '"' {
6000 if chars[i] == '\\' && i + 1 < n {
6001 word.text.push(chars[i + 1]);
6002 i += 2;
6003 } else {
6004 word.text.push(chars[i]);
6005 i += 1;
6006 }
6007 }
6008 uncertain |= i >= n;
6009 i = (i + 1).min(n);
6010 }
6011 ' ' | '\t' => {
6012 word.flush(
6013 &mut line,
6014 &mut groups,
6015 &mut last_closed_group,
6016 commands.len(),
6017 );
6018 i += 1;
6019 }
6020 ';' | '\n' | '\r' => {
6021 word.flush(
6022 &mut line,
6023 &mut groups,
6024 &mut last_closed_group,
6025 commands.len(),
6026 );
6027 push_command(&mut commands, &mut line);
6028 i += 1;
6029 }
6030 _ => {
6031 if !is_plain_word_char(c, !word.started && word.text.is_empty()) {
6032 word.odd = true;
6033 }
6034 word.text.push(c);
6035 word.started = true;
6036 i += 1;
6037 }
6038 }
6039 }
6040 word.flush(
6041 &mut line,
6042 &mut groups,
6043 &mut last_closed_group,
6044 commands.len(),
6045 );
6046 push_command(&mut commands, &mut line);
6047 (commands, uncertain)
6048 }
6049
6050 fn build_prefixed_line(prefix: &str, prefix_idx: usize, line: &Line, rest_start: usize) -> Line {
6051 let prefix_odd = !prefix
6052 .chars()
6053 .enumerate()
6054 .all(|(i, c)| is_plain_word_char(c, i == 0));
6055 let mut words = vec![prefix.to_string()];
6056 let mut dynamic = vec![line.dynamic[prefix_idx]];
6057 let mut odd = vec![prefix_odd];
6058 let mut quoted = vec![match line.quoted[prefix_idx] {
6059 WordQuote::InlineScalar => WordQuote::Quoted,
6060 quote => quote,
6061 }];
6062 if rest_start < line.words.len() {
6063 words.extend_from_slice(&line.words[rest_start..]);
6064 dynamic.extend_from_slice(&line.dynamic[rest_start..]);
6065 odd.extend_from_slice(&line.odd[rest_start..]);
6066 quoted.extend_from_slice(&line.quoted[rest_start..]);
6067 }
6068 Line {
6069 words,
6070 dynamic,
6071 odd,
6072 quoted,
6073 heredoc: false,
6074 stdin_piped: line.stdin_piped || line.heredoc,
6075 }
6076 }
6077
6078 fn docker_run_takes_value(token: &str) -> bool {
6079 if let Some(long) = token.strip_prefix("--") {
6080 match long.split_once('=') {
6081 Some(_) => false,
6082 None => DOCKER_RUN_SPEC.long_values.contains(&long),
6083 }
6084 } else {
6085 token.len() > 1
6086 && token.starts_with('-')
6087 && token
6088 .chars()
6089 .next_back()
6090 .is_some_and(|flag| DOCKER_RUN_SPEC.short_values.contains(flag))
6091 }
6092 }
6093
6094 fn find_entrypoints(
6095 tokens: &[String],
6096 dynamic: &[bool],
6097 quoted: &[WordQuote],
6098 base: usize,
6099 ) -> Vec<(String, usize)> {
6100 let mut found = Vec::new();
6101 let mut i = 0usize;
6102 while i < tokens.len() {
6103 let token = tokens[i].as_str();
6104 if token == "--" && !dynamic[base + i] {
6105 break;
6106 }
6107 if token == "--entrypoint"
6108 && let Some(value) = tokens.get(i + 1)
6109 {
6110 found.push((value.clone(), base + i + 1));
6111 }
6112 if let Some(val) = token.strip_prefix("--entrypoint=") {
6113 found.push((val.to_string(), base + i));
6114 } else if dynamic[base + i]
6115 && token != "--entrypoint"
6116 && !is_known_quoted_inline_value(token, quoted[base + i], &DOCKER_RUN_SPEC, false)
6117 {
6118 found.push((String::new(), base + i));
6119 }
6120 if !dynamic[base + i] && docker_run_takes_value(token) {
6121 i += 1;
6122 }
6123 i += 1;
6124 }
6125 found
6126 }
6127
6128 fn ssh_option_payloads(args: &[String], dynamic: &[bool]) -> Vec<(String, bool)> {
6129 let mut payloads = Vec::new();
6130 let mut local = Vec::new();
6131 let mut permit_local = false;
6132 let mut i = 0usize;
6133 while i < args.len() {
6134 let token = args[i].as_str();
6135 let option = if token == "-o" {
6136 i += 1;
6137 args.get(i)
6138 .map(|value| (value.as_str(), dynamic.get(i).copied().unwrap_or(false)))
6139 } else {
6140 token
6141 .strip_prefix("-o")
6142 .filter(|rest| !rest.is_empty())
6143 .map(|rest| (rest, dynamic[i]))
6144 };
6145 if let Some((option, option_dynamic)) = option {
6146 let option = option.trim_start_matches([' ', '\t']);
6147 let (name, value) = match option.find(['=', ' ', '\t']) {
6148 Some(at) => {
6149 let name = &option[..at];
6150 let mut value = option[at..].trim_start_matches([' ', '\t']);
6151 if let Some(rest) = value.strip_prefix('=') {
6152 value = rest.trim_start_matches([' ', '\t']);
6153 }
6154 (name, value)
6155 }
6156 None => (option, ""),
6157 };
6158 match name.to_ascii_lowercase().as_str() {
6159 "proxycommand" => payloads.push((value.to_string(), option_dynamic)),
6160 "localcommand" => local.push((value.to_string(), option_dynamic)),
6161 "permitlocalcommand" => {
6162 permit_local |= option_dynamic
6163 || value
6164 .split([' ', '\t'])
6165 .next()
6166 .is_some_and(|yes| yes.eq_ignore_ascii_case("yes"));
6167 }
6168 _ if option_dynamic => {
6169 payloads.push((String::new(), true));
6170 }
6171 _ => {}
6172 }
6173 }
6174 i += 1;
6175 }
6176 if permit_local {
6177 payloads.extend(local);
6178 }
6179 payloads
6180 }
6181
6182 fn ssh_reads_stdin(tokens: &[String], dynamic: &[bool], quoted: &[WordQuote], head: usize) -> bool {
6183 if ssh_skips_remote_command(&tokens[head + 1..], &dynamic[head + 1..]) {
6184 return false;
6185 }
6186 let mut truncated = false;
6187 let landings =
6188 resolve_wrapper_targets(tokens, dynamic, quoted, head + 1, &SSH_SPEC, &mut truncated);
6189 truncated || landings.is_empty() || landings.contains(&tokens.len())
6190 }
6191
6192 fn ssh_skips_remote_command(args: &[String], dynamic: &[bool]) -> bool {
6193 let mut i = 0usize;
6194 while i < args.len() {
6195 if dynamic[i] {
6196 return false;
6197 }
6198 let token = args[i].as_str();
6199 if token == "--" || !token.starts_with('-') || token.len() == 1 {
6200 return false;
6201 }
6202 let flags = &token[1..];
6203 let mut consumes_next = false;
6204 for (at, flag) in flags.char_indices() {
6205 if matches!(flag, 'N' | 'G' | 'V' | 'Q' | 'O') {
6206 return true;
6207 }
6208 if SSH_SPEC.short_values.contains(flag) {
6209 consumes_next = at + flag.len_utf8() == flags.len();
6210 break;
6211 }
6212 }
6213 i += if consumes_next { 2 } else { 1 };
6214 }
6215 false
6216 }
6217
6218 fn screen_attaches_only(args: &[String], dynamic: &[bool]) -> bool {
6219 let mut has_m = false;
6220 let mut attach = false;
6221 let mut i = 0usize;
6222 while i < args.len() {
6223 let token = args[i].as_str();
6224 if dynamic[i] && (token.is_empty() || token.starts_with('-')) {
6225 return false;
6226 }
6227 if token == "--" || !token.starts_with('-') || token.len() == 1 {
6228 break;
6229 }
6230 if let Some(long) = token.strip_prefix("--") {
6231 if matches!(long, "ls" | "list" | "wipe") {
6232 return true;
6233 }
6234 if SCREEN_SPEC.long_values.contains(&long) {
6235 i += 2;
6236 continue;
6237 }
6238 i += 1;
6239 continue;
6240 }
6241 if matches!(token, "-ls" | "-list" | "-wipe") {
6242 return true;
6243 }
6244 let flags = &token[1..];
6245 let mut consumes_next = false;
6246 for (at, flag) in flags.char_indices() {
6247 if flag == 'm' {
6248 has_m = true;
6249 } else if matches!(flag, 'r' | 'R') {
6250 attach = true;
6251 }
6252 if SCREEN_SPEC.short_values.contains(flag) {
6253 consumes_next = at + flag.len_utf8() == flags.len();
6254 break;
6255 }
6256 }
6257 i += if consumes_next { 2 } else { 1 };
6258 }
6259 attach && !has_m
6260 }
6261
6262 /// Values of `-c CMD`, `-cCMD`, `--command CMD`, `--command=CMD` and
6263 /// `--session-command` after `tokens[head]`, with whether each is dynamic:
6264 /// the code `su`, `runuser`, `flock` and `script` hand to a shell.
6265 fn command_option_payloads(
6266 tokens: &[String],
6267 head: usize,
6268 dynamic: &[bool],
6269 flag_end: usize,
6270 ) -> Vec<(String, bool)> {
6271 option_payloads(
6272 tokens,
6273 head,
6274 dynamic,
6275 Some('c'),
6276 &["command", "session-command"],
6277 false,
6278 flag_end,
6279 )
6280 }
6281
6282 fn option_payloads(
6283 tokens: &[String],
6284 head: usize,
6285 dynamic: &[bool],
6286 short_flag: Option<char>,
6287 long_names: &[&str],
6288 stop_at_double_dash: bool,
6289 flag_end: usize,
6290 ) -> Vec<(String, bool)> {
6291 let mut payloads = Vec::new();
6292 for (at, token) in tokens.iter().enumerate().skip(head + 1) {
6293 if stop_at_double_dash && token == "--" && !dynamic[at] {
6294 break;
6295 }
6296 let next = || match tokens.get(at + 1) {
6297 Some(value) => Some((value.clone(), dynamic[at] || dynamic[at + 1])),
6298 None if dynamic[at] => Some((String::new(), true)),
6299 None => None,
6300 };
6301 let mut matched = false;
6302 if let Some(long) = token.strip_prefix("--") {
6303 let (name, inline) = match long.split_once('=') {
6304 Some((name, value)) => (name, Some(value)),
6305 None => (long, None),
6306 };
6307 if long_names.contains(&name) {
6308 matched = true;
6309 payloads.extend(match inline {
6310 Some(value) => Some((value.to_string(), dynamic[at])),
6311 None => next(),
6312 });
6313 }
6314 } else if let Some(short) = short_flag
6315 && let Some(flags) = token.strip_prefix('-')
6316 && let Some(offset) = flags.find(short)
6317 {
6318 matched = true;
6319 let value = &flags[offset + 1..];
6320 payloads.extend(if value.is_empty() {
6321 next()
6322 } else {
6323 Some((value.to_string(), dynamic[at]))
6324 });
6325 }
6326 if !matched && dynamic[at] && at < flag_end {
6327 payloads.push((String::new(), true));
6328 }
6329 }
6330 payloads
6331 }
6332
6333 fn is_parallel_separator(token: &str) -> bool {
6334 matches!(token, ":::" | ":::+" | "::::" | "::::+")
6335 }
6336
6337 fn at_only_manages_jobs(tokens: &[String], head: usize, dynamic: &[bool]) -> bool {
6338 let mut manages = false;
6339 let mut at = head + 1;
6340 while at < tokens.len() {
6341 let token = tokens[at].as_str();
6342 if dynamic[at] {
6343 return false;
6344 }
6345 if token == "--" {
6346 break;
6347 }
6348 if token.len() < 2 || !token.starts_with('-') {
6349 if !manages {
6350 return false;
6351 }
6352 at += 1;
6353 continue;
6354 }
6355 if token.starts_with("--") {
6356 return false;
6357 }
6358 for (offset, flag) in token[1..].char_indices() {
6359 match flag {
6360 'f' => return false,
6361 'l' | 'r' | 'd' | 'c' => manages = true,
6362 'q' | 't' => {
6363 if token[1 + offset + 1..].is_empty() {
6364 at += 1;
6365 }
6366 break;
6367 }
6368 _ => {}
6369 }
6370 }
6371 at += 1;
6372 }
6373 manages
6374 }
6375
6376 /// Mark the operands of an `xargs` that contain its replacement string
6377 /// (`-I R`, `-J R`, `-i[R]`, `--replace[=R]`, `{}` by default) as known only
6378 /// at run time: `xargs -I{} sh -c {}` runs whatever arrives on stdin.
6379 fn mark_replacement_operands(tokens: &[String], heads: &[usize], dynamic: &mut [bool]) {
6380 let Some(xargs) = WRAPPERS.iter().find(|wrapper| wrapper.name == "xargs") else {
6381 return;
6382 };
6383 for &head in heads {
6384 if canonical_wrapper_name(&command_name(&tokens[head])) != "xargs" {
6385 continue;
6386 }
6387 let mut replacements: Vec<String> = Vec::new();
6388 let mut values = HashSet::new();
6389 let mut index = head + 1;
6390 while index < tokens.len() && tokens[index].starts_with('-') && tokens[index] != "--" {
6391 let token = tokens[index].as_str();
6392 if let Some(long) = token.strip_prefix("--") {
6393 match long.split_once('=') {
6394 Some(("replace", value)) => replacements.push(value.to_string()),
6395 None if long == "replace" => replacements.push("{}".to_string()),
6396 None if xargs.long_values.contains(&long) => {
6397 values.insert(index + 1);
6398 index += 1;
6399 }
6400 _ => {}
6401 }
6402 } else {
6403 for (at, flag) in token[1..].char_indices() {
6404 let rest = &token[1 + at + flag.len_utf8()..];
6405 if flag == 'i' {
6406 replacements.push(if rest.is_empty() { "{}" } else { rest }.to_string());
6407 break;
6408 }
6409 if xargs.short_values.contains(flag) {
6410 let value = if rest.is_empty() {
6411 values.insert(index + 1);
6412 index += 1;
6413 tokens.get(index).cloned()
6414 } else {
6415 Some(rest.to_string())
6416 };
6417 if matches!(flag, 'I' | 'J') {
6418 replacements.extend(value);
6419 }
6420 break;
6421 }
6422 }
6423 }
6424 index += 1;
6425 }
6426 for (at, token) in tokens.iter().enumerate().skip(head + 1) {
6427 if !values.contains(&at)
6428 && !token.starts_with('-')
6429 && replacements.iter().any(|replacement| {
6430 !replacement.is_empty() && token.contains(replacement.as_str())
6431 })
6432 {
6433 dynamic[at] = true;
6434 }
6435 }
6436 }
6437 }
6438
6439 /// True unless the `$` is a literal one: it ends the word or precedes a
6440 /// separator. Everything else (`$v`, `$1`, `$@`, `$=v`, `$~v`, `$^v`, `$"…"`,
6441 /// and any flag character a shell may add) is read as an expansion.
6442 fn starts_parameter(next: Option<&char>) -> bool {
6443 next.is_some_and(|c| !c.is_whitespace() && !matches!(c, ';' | '|' | '&' | ')' | '<' | '>'))
6444 }
6445
6446 fn is_plain_word_char(c: char, leading: bool) -> bool {
6447 c.is_alphanumeric()
6448 || matches!(c, '_' | '.' | '/' | '+' | ':' | '@' | ',' | '-')
6449 || (leading && c == '~')
6450 }
6451
6452 fn is_array_assignment_prefix(text: &str) -> bool {
6453 let name = text
6454 .strip_suffix("+=")
6455 .or_else(|| text.strip_suffix('='))
6456 .unwrap_or("");
6457 !name.is_empty()
6458 && name
6459 .chars()
6460 .all(|ch| ch.is_ascii_alphanumeric() || ch == '_')
6461 }
6462
6463 /// Unquoted heredocs expand substitutions, but quotes and ordinary lines are
6464 /// data. Also reports whether every substitution was read with certainty.
6465 fn heredoc_substitutions(body: &str) -> (Vec<String>, bool) {
6466 let chars: Vec<char> = body.chars().collect();
6467 let mut result = Vec::new();
6468 let mut all_certain = true;
6469 let mut i = 0;
6470 while i < chars.len() {
6471 match chars[i] {
6472 '\\' if chars
6473 .get(i + 1)
6474 .is_some_and(|c| matches!(c, '$' | '`' | '\\' | '\n')) =>
6475 {
6476 i += 2
6477 }
6478 '`' => {
6479 let (inner, next, certain) = read_backtick(&chars, i);
6480 all_certain &= certain;
6481 result.push(inner);
6482 i = next;
6483 }
6484 '$' if chars.get(i + 1) == Some(&'(') => {
6485 let (inner, next, certain) = read_substitution(&chars, i + 1);
6486 all_certain &= certain;
6487 result.push(inner);
6488 i = next;
6489 }
6490 _ => i += 1,
6491 }
6492 }
6493 (result, all_certain)
6494 }
6495
6496 fn redirection_len(chars: &[char]) -> usize {
6497 match chars {
6498 ['&', '>', '>', ..] | ['<', '<', '<' | '-', ..] => 3,
6499 ['&', '>', ..] | ['<', '<' | '>' | '&', ..] | ['>', '>' | '&' | '|', ..] => 2,
6500 ['<' | '>', ..] => 1,
6501 _ => 0,
6502 }
6503 }
6504
6505 fn consume_redirect_descriptor(word: &mut WordBuf) -> bool {
6506 if word.quoted == WordQuote::Unquoted && !word.dynamic && is_redirect_descriptor(&word.text) {
6507 let is_stdin = word.text.bytes().all(|b| b == b'0');
6508 word.text.clear();
6509 word.started = false;
6510 is_stdin
6511 } else {
6512 true
6513 }
6514 }
6515
6516 fn is_redirect_descriptor(word: &str) -> bool {
6517 if !word.is_empty() && word.bytes().all(|b| b.is_ascii_digit()) {
6518 return true;
6519 }
6520 // Bash also accepts an unquoted `{name}` in place of an IO number.
6521 word.strip_prefix('{')
6522 .and_then(|word| word.strip_suffix('}'))
6523 .is_some_and(|name| {
6524 let mut chars = name.chars();
6525 chars
6526 .next()
6527 .is_some_and(|c| c == '_' || c.is_ascii_alphabetic())
6528 && chars.all(|c| c == '_' || c.is_ascii_alphanumeric())
6529 })
6530 }
6531
6532 /// Close the current simple command.
6533 ///
6534 /// `{` and `}` stand alone as reserved words in `{ cmd; }` — they group a
6535 /// command rather than being part of one, so they split the line
6536 /// (`function f { rm x; }` runs `rm x`). Reserved words that lead a command
6537 /// (`if`, `then`, `while`, `do`, `!`, …) are dropped so the word after them is
6538 /// read as the command word. Every downstream consumer (wrapper detection,
6539 /// emission) then looks at real command words only.
6540 fn end_command(commands: &mut Vec<Line>, line: &mut Line, fresh_stdin: bool) {
6541 let line_old = std::mem::take(line);
6542 line.stdin_piped = fresh_stdin;
6543 let mut piece = Line {
6544 heredoc: line_old.heredoc,
6545 stdin_piped: line_old.stdin_piped,
6546 ..Line::default()
6547 };
6548 for (((word, dynamic), odd), quoted) in line_old
6549 .words
6550 .into_iter()
6551 .zip(line_old.dynamic)
6552 .zip(line_old.odd)
6553 .zip(line_old.quoted)
6554 {
6555 if matches!(word.as_str(), "{" | "}") {
6556 push_command(commands, &mut piece);
6557 continue;
6558 }
6559 if piece.words.is_empty() && RESERVED_PREFIXES.contains(&word.as_str()) {
6560 continue;
6561 }
6562 piece.words.push(word);
6563 piece.dynamic.push(dynamic);
6564 piece.odd.push(odd);
6565 piece.quoted.push(quoted);
6566 }
6567 push_command(commands, &mut piece);
6568 }
6569
6570 fn push_command(commands: &mut Vec<Line>, piece: &mut Line) {
6571 if !piece.words.is_empty() {
6572 let heredoc = piece.heredoc;
6573 let stdin_piped = piece.stdin_piped;
6574 commands.push(std::mem::take(piece));
6575 piece.heredoc = heredoc;
6576 piece.stdin_piped = stdin_piped;
6577 }
6578 }
6579
6580 /// Read a backtick substitution. `start` indexes the opening backtick; returns
6581 /// the body, the index just past the closing backtick, and whether a closing
6582 /// backtick was found.
6583 fn read_backtick(chars: &[char], start: usize) -> (String, usize, bool) {
6584 let mut i = start + 1;
6585 let mut inner = String::new();
6586 while i < chars.len() {
6587 match chars[i] {
6588 '\\' if i + 1 < chars.len() => {
6589 inner.push(chars[i]);
6590 inner.push(chars[i + 1]);
6591 i += 2;
6592 }
6593 '`' => return (inner, i + 1, true),
6594 c => {
6595 inner.push(c);
6596 i += 1;
6597 }
6598 }
6599 }
6600 (inner, i, false)
6601 }
6602
6603 /// Read a `( … )` or `{ … }` region. `open_at` indexes the opening delimiter;
6604 /// returns the body, the index just past the matching close, and whether the
6605 /// region was read with certainty.
6606 ///
6607 /// Quoted text, escapes, backticks and nested `$(`/`${` are skipped the way
6608 /// the shell skips them, so `$(echo ")"; rm x)` closes at the last paren. A
6609 /// `case` inside a `$( … )` is flagged uncertain rather than parsed: its
6610 /// `pattern)` closes no paren, so the shell may end the region elsewhere. An
6611 /// unterminated region is uncertain too.
6612 fn read_substitution(chars: &[char], open_at: usize) -> (String, usize, bool) {
6613 let n = chars.len();
6614 let (open, close) = if chars[open_at] == '{' {
6615 ('{', '}')
6616 } else {
6617 ('(', ')')
6618 };
6619 let start = open_at + 1;
6620 let mut depth = 1usize;
6621 let mut certain = true;
6622 let mut i = start;
6623 while i < n {
6624 let c = chars[i];
6625 match c {
6626 '\\' => i += 2,
6627 '$' if chars.get(i + 1) == Some(&'\'') => {
6628 i += 2;
6629 while i < n && chars[i] != '\'' {
6630 if chars[i] == '\\' && i + 1 < n {
6631 i += 2;
6632 } else {
6633 i += 1;
6634 }
6635 }
6636 certain &= i < n;
6637 i += 1;
6638 }
6639 '\'' => {
6640 i += 1;
6641 while i < n && chars[i] != '\'' {
6642 i += 1;
6643 }
6644 certain &= i < n;
6645 i += 1;
6646 }
6647 '"' => {
6648 i += 1;
6649 while i < n && chars[i] != '"' {
6650 match chars[i] {
6651 '\\' => i += 2,
6652 '`' => {
6653 let (_, next, inner_certain) = read_backtick(chars, i);
6654 certain &= inner_certain;
6655 i = next;
6656 }
6657 '$' if matches!(chars.get(i + 1), Some('(' | '{')) => {
6658 let (_, next, inner_certain) = read_substitution(chars, i + 1);
6659 certain &= inner_certain;
6660 i = next;
6661 }
6662 _ => i += 1,
6663 }
6664 }
6665 certain &= i < n;
6666 i += 1;
6667 }
6668 '`' => {
6669 let (_, next, inner_certain) = read_backtick(chars, i);
6670 certain &= inner_certain;
6671 i = next;
6672 }
6673 '$' if matches!(chars.get(i + 1), Some('(' | '{')) => {
6674 let (_, next, inner_certain) = read_substitution(chars, i + 1);
6675 certain &= inner_certain;
6676 i = next;
6677 }
6678 _ if c == close => {
6679 depth -= 1;
6680 if depth == 0 {
6681 return (chars[start..i].iter().collect(), i + 1, certain);
6682 }
6683 i += 1;
6684 }
6685 _ => {
6686 if c == open {
6687 depth += 1;
6688 } else if open == '('
6689 && c == 'c'
6690 && chars[i..].starts_with(&['c', 'a', 's', 'e'])
6691 && chars.get(i + 4).is_none_or(|next| next.is_whitespace())
6692 && (i == start
6693 || matches!(
6694 chars[i - 1],
6695 ' ' | '\t' | '\n' | ';' | '&' | '|' | '(' | '!'
6696 ))
6697 {
6698 certain = false;
6699 }
6700 i += 1;
6701 }
6702 }
6703 }
6704 (chars[start..n.max(start)].iter().collect(), n, false)
6705 }
6706
6707 fn push_ansi_c_escape(chars: &[char], backslash_idx: usize, out: &mut String) -> usize {
6708 let next = chars[backslash_idx + 1];
6709 match next {
6710 'a' => {
6711 out.push('\x07');
6712 backslash_idx + 2
6713 }
6714 'b' => {
6715 out.push('\x08');
6716 backslash_idx + 2
6717 }
6718 'e' | 'E' => {
6719 out.push('\x1b');
6720 backslash_idx + 2
6721 }
6722 'f' => {
6723 out.push('\x0c');
6724 backslash_idx + 2
6725 }
6726 'n' => {
6727 out.push('\n');
6728 backslash_idx + 2
6729 }
6730 'r' => {
6731 out.push('\r');
6732 backslash_idx + 2
6733 }
6734 't' => {
6735 out.push('\t');
6736 backslash_idx + 2
6737 }
6738 'v' => {
6739 out.push('\x0b');
6740 backslash_idx + 2
6741 }
6742 '\\' | '\'' | '"' | '?' => {
6743 out.push(next);
6744 backslash_idx + 2
6745 }
6746 '0'..='7' => {
6747 let mut val = 0u32;
6748 let mut end = backslash_idx + 1;
6749 while end < chars.len() && end < backslash_idx + 4 && ('0'..='7').contains(&chars[end])
6750 {
6751 val = (val << 3) | (chars[end] as u32 - '0' as u32);
6752 end += 1;
6753 }
6754 out.push(char::from((val & 0xff) as u8));
6755 end
6756 }
6757 'x' => {
6758 let mut val = 0u32;
6759 let mut end = backslash_idx + 2;
6760 while end < chars.len() && end < backslash_idx + 4 {
6761 if let Some(digit) = chars[end].to_digit(16) {
6762 val = (val << 4) | digit;
6763 end += 1;
6764 } else {
6765 break;
6766 }
6767 }
6768 if end > backslash_idx + 2 {
6769 out.push(char::from((val & 0xff) as u8));
6770 end
6771 } else {
6772 out.push('\\');
6773 out.push('x');
6774 backslash_idx + 2
6775 }
6776 }
6777 'u' | 'U' => {
6778 let max_digits = if next == 'u' { 4 } else { 8 };
6779 let mut val = 0u32;
6780 let mut end = backslash_idx + 2;
6781 while end < chars.len() && end < backslash_idx + 2 + max_digits {
6782 if let Some(digit) = chars[end].to_digit(16) {
6783 val = (val << 4) | digit;
6784 end += 1;
6785 } else {
6786 break;
6787 }
6788 }
6789 if end > backslash_idx + 2 {
6790 if let Some(ch) = char::from_u32(val) {
6791 out.push(ch);
6792 } else {
6793 out.extend(&chars[backslash_idx..end]);
6794 }
6795 end
6796 } else {
6797 out.push('\\');
6798 out.push(next);
6799 backslash_idx + 2
6800 }
6801 }
6802 'c' if backslash_idx + 2 < chars.len()
6803 && chars[backslash_idx + 2].is_ascii()
6804 && chars[backslash_idx + 2] != '\'' =>
6805 {
6806 out.push(char::from((chars[backslash_idx + 2] as u8) & 0x1f));
6807 backslash_idx + 3
6808 }
6809 _ => {
6810 out.push('\\');
6811 out.push(next);
6812 backslash_idx + 2
6813 }
6814 }
6815 }
6816
6817 pub(crate) fn split_ansi_c_shell_words(segment: &str) -> Option<Vec<String>> {
6818 let chars: Vec<char> = segment.chars().collect();
6819 let n = chars.len();
6820 let mut i = 0;
6821 let mut words = Vec::new();
6822 let mut current = String::new();
6823 let mut started = false;
6824 while i < n {
6825 let ch = chars[i];
6826 if ch.is_whitespace() {
6827 if started {
6828 words.push(std::mem::take(&mut current));
6829 started = false;
6830 }
6831 i += 1;
6832 continue;
6833 }
6834 if ch == '#' && !started {
6835 while i < n && chars[i] != '\n' {
6836 i += 1;
6837 }
6838 continue;
6839 }
6840 started = true;
6841 match ch {
6842 '$' if i + 1 < n && chars[i + 1] == '\'' => {
6843 i += 2;
6844 while i < n && chars[i] != '\'' {
6845 if chars[i] == '\\' && i + 1 < n {
6846 i = push_ansi_c_escape(&chars, i, &mut current);
6847 } else {
6848 current.push(chars[i]);
6849 i += 1;
6850 }
6851 }
6852 if i >= n {
6853 return None;
6854 }
6855 i += 1;
6856 }
6857 '\'' => {
6858 i += 1;
6859 while i < n && chars[i] != '\'' {
6860 current.push(chars[i]);
6861 i += 1;
6862 }
6863 if i >= n {
6864 return None;
6865 }
6866 i += 1;
6867 }
6868 '"' => {
6869 i += 1;
6870 while i < n && chars[i] != '"' {
6871 if chars[i] == '\\' {
6872 if i + 1 >= n {
6873 return None;
6874 }
6875 let next = chars[i + 1];
6876 if matches!(next, '"' | '\\' | '$' | '`') {
6877 current.push(next);
6878 i += 2;
6879 } else if next == '\n' {
6880 i += 2;
6881 } else {
6882 current.push('\\');
6883 current.push(next);
6884 i += 2;
6885 }
6886 } else {
6887 current.push(chars[i]);
6888 i += 1;
6889 }
6890 }
6891 if i >= n {
6892 return None;
6893 }
6894 i += 1;
6895 }
6896 '\\' => {
6897 if i + 1 >= n {
6898 return None;
6899 }
6900 if chars[i + 1] != '\n' {
6901 current.push(chars[i + 1]);
6902 }
6903 i += 2;
6904 }
6905 _ => {
6906 current.push(ch);
6907 i += 1;
6908 }
6909 }
6910 }
6911 if started {
6912 words.push(current);
6913 }
6914 Some(words)
6915 }
6916
6917 /// The final path component, so `/usr/bin/sudo` reads as `sudo`.
6918 fn basename(token: &str) -> &str {
6919 token
6920 .rsplit(['/', '\\'])
6921 .next()
6922 .filter(|part| !part.is_empty())
6923 .unwrap_or(token)
6924 }
6925
6926 fn is_env_assignment(token: &str) -> bool {
6927 match token.split_once('=') {
6928 Some((name, _)) => {
6929 let name = name.strip_suffix('+').unwrap_or(name);
6930 !name.is_empty()
6931 && !name.starts_with('-')
6932 && name
6933 .chars()
6934 .all(|ch| ch.is_ascii_alphanumeric() || ch == '_')
6935 }
6936 None => false,
6937 }
6938 }
6939
6940 /// True for a bare scalar operand that may belong to a wrapper word rather
6941 /// than start a command — `timeout 5`, `nice -n 10`, `timeout 1.5s`.
6942 fn is_scalar_operand(token: &str) -> bool {
6943 let body = token.trim_end_matches(['s', 'm', 'h', 'd']);
6944 !body.is_empty() && body.chars().all(|ch| ch.is_ascii_digit() || ch == '.')
6945 }
6946
6947 /// The command a word names, for comparing against a table of names: the
6948 /// lowercased basename with any `.exe` suffix removed, so `/usr/bin/sudo`,
6949 /// `bash.exe` and `C:\Git\bin\bash.EXE` read as `sudo` and `bash`.
6950 fn command_name(token: &str) -> String {
6951 let name = basename(token).to_ascii_lowercase();
6952 match name.strip_suffix(".exe") {
6953 Some(stem) if !stem.is_empty() => stem.to_string(),
6954 _ => name,
6955 }
6956 }
6957
6958 fn is_dynamic_loader(name: &str) -> bool {
6959 name == "ld.so"
6960 || name.starts_with("ld.so.")
6961 || name.starts_with("ld-linux")
6962 || name.starts_with("ld-musl")
6963 }
6964
6965 fn canonical_wrapper_name(name: &str) -> &str {
6966 match name {
6967 "genv" => "env",
6968 "gxargs" => "xargs",
6969 "gtime" => "time",
6970 "gsetsid" => "setsid",
6971 "gruncon" => "runcon",
6972 "linux32" | "uname26" => "linux64",
6973 _ if is_dynamic_loader(name) => "ld.so",
6974 _ => name,
6975 }
6976 }
6977
6978 fn long_option_extra_values(wrapper: &str, option: &str) -> usize {
6979 match wrapper {
6980 "bwrap"
6981 if matches!(
6982 option,
6983 "bind"
6984 | "bind-try"
6985 | "dev-bind"
6986 | "dev-bind-try"
6987 | "ro-bind"
6988 | "ro-bind-try"
6989 | "setenv"
6990 | "symlink"
6991 | "chmod"
6992 | "file"
6993 | "bind-data"
6994 | "ro-bind-data"
6995 ) =>
6996 {
6997 2
6998 }
6999 "nix" if option == "option" => 2,
7000 _ => 0,
7001 }
7002 }
7003
7004 enum WrapperStep {
7005 Advance {
7006 steps: [Option<usize>; 2],
7007 operands: u8,
7008 options_done: bool,
7009 },
7010 Stop,
7011 Landing,
7012 }
7013
7014 fn step_wrapper_option(
7015 tokens: &[String],
7016 dynamic: &[bool],
7017 index: usize,
7018 spec: &Wrapper,
7019 operands: u8,
7020 options_done: bool,
7021 payloads: Option<&mut Vec<(String, bool)>>,
7022 ) -> WrapperStep {
7023 let token = tokens[index].as_str();
7024 if !options_done && token == "--" && !dynamic[index] {
7025 return WrapperStep::Advance {
7026 steps: [Some(index + 1), None],
7027 operands: if spec.name == "oc-exec" { 0 } else { operands },
7028 options_done: true,
7029 };
7030 }
7031 if !options_done && token.len() > 1 && token.starts_with('-') {
7032 let mut next_operands = operands;
7033 if let Some(long) = token.strip_prefix("--") {
7034 let (name, inline) = match long.split_once('=') {
7035 Some((name, value)) => (name, Some(value)),
7036 None => (long, None),
7037 };
7038 if spec.name == "ld.so" && matches!(name, "list" | "verify") {
7039 return WrapperStep::Stop;
7040 }
7041 if (spec.name == "runcon"
7042 && matches!(name, "compute" | "user" | "role" | "type" | "range"))
7043 || (spec.name == "oc-exec" && name == "filename")
7044 {
7045 next_operands = 0;
7046 }
7047 if let Some(payloads) = payloads
7048 && spec.name == "env"
7049 && name == "split-string"
7050 {
7051 match inline {
7052 Some(value) => payloads.push((value.to_string(), dynamic[index])),
7053 None => match tokens.get(index + 1) {
7054 Some(value) => {
7055 payloads.push((value.clone(), dynamic[index] || dynamic[index + 1]));
7056 }
7057 None if dynamic[index] => payloads.push((String::new(), true)),
7058 None => {}
7059 },
7060 }
7061 }
7062 let extra = long_option_extra_values(spec.name, name);
7063 let steps = if inline.is_some() || spec.long_switches.contains(&name) {
7064 [Some(index + 1), None]
7065 } else if extra > 0 {
7066 [Some(index + 1 + extra), None]
7067 } else if spec.long_values.contains(&name) {
7068 [Some(index + 2), None]
7069 } else {
7070 [Some(index + 1), Some(index + 2)]
7071 };
7072 return WrapperStep::Advance {
7073 steps,
7074 operands: next_operands,
7075 options_done: false,
7076 };
7077 }
7078 let flags = &token[1..];
7079 if spec.name == "command" && flags.contains(['v', 'V']) {
7080 return WrapperStep::Stop;
7081 }
7082 if (spec.name == "runcon" && flags.contains(['c', 'u', 'r', 't', 'l']))
7083 || (spec.name == "oc-exec" && flags.contains('f'))
7084 {
7085 next_operands = 0;
7086 }
7087 if let Some(payloads) = payloads
7088 && spec.name == "env"
7089 && let Some(at) = flags.find('S')
7090 {
7091 let value = &flags[at + 1..];
7092 if value.is_empty() {
7093 match tokens.get(index + 1) {
7094 Some(next) => {
7095 payloads.push((next.clone(), dynamic[index] || dynamic[index + 1]));
7096 }
7097 None if dynamic[index] => payloads.push((String::new(), true)),
7098 None => {}
7099 }
7100 } else {
7101 payloads.push((value.to_string(), dynamic[index]));
7102 }
7103 }
7104 let mut step = Some(1);
7105 for (at, flag) in flags.char_indices() {
7106 if spec.short_values.contains(flag) {
7107 if at + flag.len_utf8() == flags.len() {
7108 step = Some(2);
7109 }
7110 break;
7111 }
7112 if !flag.is_ascii_digit() && !spec.short_switches.contains(flag) {
7113 step = None;
7114 break;
7115 }
7116 }
7117 let steps = match step {
7118 Some(step) => [Some(index + step), None],
7119 None => [Some(index + 1), Some(index + 2)],
7120 };
7121 return WrapperStep::Advance {
7122 steps,
7123 operands: next_operands,
7124 options_done: false,
7125 };
7126 }
7127 if operands > 0 {
7128 return WrapperStep::Advance {
7129 steps: [Some(index + 1), None],
7130 operands: operands - 1,
7131 options_done,
7132 };
7133 }
7134 WrapperStep::Landing
7135 }
7136
7137 fn is_known_quoted_inline_value(
7138 token: &str,
7139 quoted: WordQuote,
7140 spec: &Wrapper,
7141 options_done: bool,
7142 ) -> bool {
7143 if options_done || quoted != WordQuote::InlineScalar {
7144 return false;
7145 }
7146 let Some(long) = token.strip_prefix("--") else {
7147 return false;
7148 };
7149 let Some((name, _)) = long.split_once('=') else {
7150 return false;
7151 };
7152 name != "entrypoint" && spec.long_values.contains(&name)
7153 }
7154
7155 fn launcher_verb_targets(
7156 tokens: &[String],
7157 dynamic: &[bool],
7158 quoted: &[WordQuote],
7159 start: usize,
7160 spec: &Wrapper,
7161 truncated: &mut bool,
7162 ) -> Vec<usize> {
7163 let mut targets = resolve_wrapper_targets(tokens, dynamic, quoted, start, spec, truncated);
7164 let mut index = 0;
7165 while index < targets.len() {
7166 let at = targets[index];
7167 if tokens.get(at).is_some_and(String::is_empty) {
7168 for next in resolve_wrapper_targets(tokens, dynamic, quoted, at + 1, spec, truncated) {
7169 if !targets.contains(&next) {
7170 targets.push(next);
7171 }
7172 }
7173 }
7174 index += 1;
7175 }
7176 targets.sort_unstable();
7177 targets
7178 }
7179
7180 fn resolve_wrapper_targets(
7181 tokens: &[String],
7182 dynamic: &[bool],
7183 quoted: &[WordQuote],
7184 start: usize,
7185 spec: &Wrapper,
7186 truncated: &mut bool,
7187 ) -> Vec<usize> {
7188 let mut landings = Vec::new();
7189 let mut seen = HashSet::new();
7190 let mut stack = vec![(start, spec.operands, false)];
7191 while let Some((index, operands, options_done)) = stack.pop() {
7192 if !seen.insert((index, operands, options_done)) {
7193 continue;
7194 }
7195 if seen.len() >= MAX_HEAD_STATES {
7196 *truncated = true;
7197 continue;
7198 }
7199 if index >= tokens.len() {
7200 if operands == 0 && !landings.contains(&tokens.len()) {
7201 landings.push(tokens.len());
7202 }
7203 continue;
7204 }
7205 if dynamic[index]
7206 && !is_known_quoted_inline_value(
7207 tokens[index].as_str(),
7208 quoted[index],
7209 spec,
7210 options_done,
7211 )
7212 {
7213 *truncated = true;
7214 }
7215 match step_wrapper_option(tokens, dynamic, index, spec, operands, options_done, None) {
7216 WrapperStep::Advance {
7217 steps,
7218 operands,
7219 options_done,
7220 } => {
7221 for next_idx in steps.into_iter().flatten() {
7222 stack.push((next_idx, operands, options_done));
7223 }
7224 }
7225 WrapperStep::Stop => {}
7226 WrapperStep::Landing => {
7227 if !landings.contains(&index) {
7228 landings.push(index);
7229 }
7230 }
7231 }
7232 }
7233 landings.sort_unstable();
7234 landings
7235 }
7236
7237 /// Index into [`WRAPPERS`] when `token` names a wrapper word.
7238 fn wrapper_index(token: &str) -> Option<usize> {
7239 let raw = command_name(token);
7240 let name = canonical_wrapper_name(&raw);
7241 WRAPPERS.iter().position(|wrapper| wrapper.name == name)
7242 }
7243
7244 /// What [`command_heads`] found.
7245 struct Heads {
7246 /// Every index that may be a command word, ascending.
7247 heads: Vec<usize>,
7248 /// `env -S` values, which are command lines.
7249 split_payloads: Vec<(String, bool)>,
7250 /// The walk ran out of states before every reading was explored.
7251 truncated: bool,
7252 }
7253
7254 /// Every index in `tokens` that may be a command word, walking leading
7255 /// environment assignments and wrapper words together with the options and
7256 /// operands those wrappers take. Wrapper words are themselves command words
7257 /// and are included. Also returns `env -S` payloads, which are command lines.
7258 ///
7259 /// Where the grammar is ambiguous (an option missing from the table that may
7260 /// take a value, a bare number after a wrapper) both readings are kept,
7261 /// because an extra candidate only makes deny matching stricter while a
7262 /// missing one is a bypass.
7263 fn command_heads(tokens: &[String], dynamic: &[bool]) -> Heads {
7264 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
7265 enum State {
7266 /// At a command word position.
7267 Command,
7268 /// Inside the arguments of `WRAPPERS[wrapper]`.
7269 Wrapper {
7270 wrapper: usize,
7271 operands: u8,
7272 options_done: bool,
7273 },
7274 }
7275 let mut heads = Vec::new();
7276 let mut payloads = Vec::new();
7277 let mut truncated = false;
7278 let mut seen = HashSet::new();
7279 let mut stack = vec![(0usize, State::Command)];
7280 while let Some((index, state)) = stack.pop() {
7281 if index >= tokens.len() || seen.contains(&(index, state)) {
7282 continue;
7283 }
7284 if seen.len() >= MAX_HEAD_STATES {
7285 truncated = true;
7286 break;
7287 }
7288 seen.insert((index, state));
7289 let token = tokens[index].as_str();
7290 match state {
7291 State::Command => {
7292 if is_env_assignment(token) {
7293 stack.push((index + 1, State::Command));
7294 continue;
7295 }
7296 if !heads.contains(&index) {
7297 heads.push(index);
7298 }
7299 if let Some(position) = wrapper_index(token) {
7300 stack.push((
7301 index + 1,
7302 State::Wrapper {
7303 wrapper: position,
7304 operands: WRAPPERS[position].operands,
7305 options_done: false,
7306 },
7307 ));
7308 }
7309 }
7310 State::Wrapper {
7311 wrapper,
7312 operands,
7313 options_done,
7314 } => {
7315 let spec = &WRAPPERS[wrapper];
7316 match step_wrapper_option(
7317 tokens,
7318 dynamic,
7319 index,
7320 spec,
7321 operands,
7322 options_done,
7323 Some(&mut payloads),
7324 ) {
7325 WrapperStep::Advance {
7326 steps,
7327 operands,
7328 options_done,
7329 } => {
7330 if dynamic[index] {
7331 truncated = true;
7332 }
7333 for next_idx in steps.into_iter().flatten() {
7334 stack.push((
7335 next_idx,
7336 State::Wrapper {
7337 wrapper,
7338 operands,
7339 options_done,
7340 },
7341 ));
7342 }
7343 }
7344 WrapperStep::Stop => {
7345 if dynamic[index] {
7346 truncated = true;
7347 }
7348 }
7349 WrapperStep::Landing => {
7350 if is_scalar_operand(token) {
7351 stack.push((
7352 index + 1,
7353 State::Wrapper {
7354 wrapper,
7355 operands: 0,
7356 options_done,
7357 },
7358 ));
7359 }
7360 stack.push((index, State::Command));
7361 }
7362 }
7363 }
7364 }
7365 }
7366 heads.sort_unstable();
7367 Heads {
7368 heads,
7369 split_payloads: payloads,
7370 truncated,
7371 }
7372 }
7373
7374 fn script_descriptor_fd(script: &str) -> Option<&str> {
7375 if !script.starts_with('/') {
7376 return None;
7377 }
7378 let mut parts: Vec<&str> = Vec::new();
7379 for part in script.split('/') {
7380 match part {
7381 "" | "." => {}
7382 ".." => {
7383 parts.pop();
7384 }
7385 part => parts.push(part),
7386 }
7387 }
7388 match parts.as_slice() {
7389 ["dev", "stdin"] => Some("0"),
7390 ["dev", "fd", fd] => Some(*fd),
7391 ["proc", process, "fd", fd]
7392 if *process == "self"
7393 || *process == "thread-self"
7394 || process.chars().all(|ch| ch.is_ascii_digit()) =>
7395 {
7396 Some(*fd)
7397 }
7398 _ => None,
7399 }
7400 }
7401
7402 /// A script operand that names a file descriptor rather than a file:
7403 /// `/dev/stdin`, `/dev/fd/N` or `/proc/<pid>/fd/N`. Its text arrives through
7404 /// a pipe, a here-string or a redirect, so it is only known at run time —
7405 /// unless it is stdin and a heredoc body (already expanded as the script)
7406 /// feeds it.
7407 fn script_read_at_run_time(script: &str, line: &Line) -> bool {
7408 script_descriptor_fd(script).is_some_and(|fd| fd != "0" || !line.heredoc)
7409 }
7410
7411 /// How the shell invocation `tokens` (with `tokens[0]` the shell) gets its
7412 /// script.
7413 ///
7414 /// Combined short flags count (`bash -lc '…'`). The scan deliberately does
7415 /// NOT stop at the first non-flag operand: an earlier version did, and
7416 /// `bash -o vi -c 'payload'` walked straight past the deny expander because
7417 /// `vi` (the argument of `-o`) ended the scan before `-c` was seen
7418 /// (2026-08-04 review). Continuing the scan can over-read a `-c` that is
7419 /// really an argument to a script (`bash script.sh -c x`), but this
7420 /// expander's contract is explicit that over-emitting targets is safe and
7421 /// under-emitting is a bypass.
7422 ///
7423 /// `-c` only switches the shell into command mode: options may still follow
7424 /// it, and the command string is the first *operand* after option parsing
7425 /// (`bash -c -e 'cmd'`, `sh -c -- 'cmd'`, `bash -c -o pipefail 'cmd'` all run
7426 /// `cmd`). Shells that read `-c`'s value as the very next word (fish) run
7427 /// that word instead, so both candidates are reported when they differ.
7428 fn shell_input(shell: &str, tokens: &[String], dynamic: &[bool]) -> ShellInput {
7429 let mut script = None;
7430 let mut from_stdin = false;
7431 let mut options_done = false;
7432 let mut command = Vec::new();
7433 let mut index = 1usize;
7434 while index < tokens.len() {
7435 let token = tokens[index].as_str();
7436 if !options_done && command.is_empty() && script.is_none() && dynamic[index] {
7437 return ShellInput::Inline(String::new(), true);
7438 }
7439 if !options_done && token == "--" {
7440 options_done = true;
7441 } else if !options_done && token == "-" {
7442 // `bash -` reads the script from stdin; after `-c` it only ends
7443 // the options.
7444 from_stdin |= command.is_empty();
7445 options_done = true;
7446 } else if let Some(long) = token.strip_prefix("--").filter(|_| !options_done) {
7447 let (name, inline) = match long.split_once('=') {
7448 Some((name, value)) => (name, Some(value)),
7449 None => (long, None),
7450 };
7451 if name.eq_ignore_ascii_case("command")
7452 || (shell == "nu"
7453 && (name.eq_ignore_ascii_case("commands")
7454 || name.eq_ignore_ascii_case("execute")))
7455 {
7456 return match inline {
7457 Some(value) => ShellInput::Inline(value.to_string(), dynamic[index]),
7458 None => match tokens.get(index + 1) {
7459 Some(_) => ShellInput::Command(vec![index + 1]),
7460 None => ShellInput::Stdin,
7461 },
7462 };
7463 }
7464 if matches!(name, "rcfile" | "init-file") && inline.is_none() {
7465 index += 1;
7466 }
7467 } else if !options_done
7468 && token.len() > 1
7469 && (token.starts_with('-') || token.starts_with('+'))
7470 {
7471 let flags = &token[1..];
7472 if token.starts_with('-')
7473 && (flags.contains('c') || (shell == "nu" && flags.contains('e')))
7474 && command.is_empty()
7475 {
7476 command.push(index + 1);
7477 }
7478 from_stdin |= token.starts_with('-') && flags.contains('s');
7479 if flags.contains(['o', 'O']) {
7480 index += 1;
7481 }
7482 } else if !command.is_empty() {
7483 if command[0] != index {
7484 command.push(index);
7485 }
7486 return ShellInput::Command(command);
7487 } else if script.is_none() {
7488 script = Some(index);
7489 }
7490 index += 1;
7491 }
7492 command.retain(|&at| at < tokens.len());
7493 match script {
7494 _ if !command.is_empty() => ShellInput::Command(command),
7495 Some(index) if !from_stdin => ShellInput::Script(index),
7496 _ => ShellInput::Stdin,
7497 }
7498 }
7499
7500 #[cfg(test)]
7501 mod tests {
7502 use super::*;
7503
7504 #[test]
7505 fn awk_policy_scan_bounds_work_and_preserves_ordinary_programs() {
7506 let program = "BEGIN { print 1 }\n#";
7507 let padding = " ".repeat(MAX_AWK_PROGRAM_BYTES - program.len());
7508 assert!(!expand_for_platform(&format!("awk '{program}{padding}'"), false).dynamic);
7509 assert!(expand_for_platform(&format!("awk '{program}{padding} '"), false).dynamic);
7510
7511 let nested = expand_for_platform(r#"awk 'BEGIN { system(("printf ready")) }'"#, false);
7512 assert!(nested.nested);
7513 assert!(!nested.dynamic);
7514 assert!(
7515 nested
7516 .commands
7517 .iter()
7518 .any(|command| command == "printf ready")
7519 );
7520
7521 let tokens = lex_awk_tokens(r#"("printf ready")"#);
7522 assert_eq!(awk_pipe_lhs(&tokens, &mut 3), Some(tokens.as_slice()));
7523 assert_eq!(awk_pipe_rhs(&tokens, &mut 3), Some(tokens.as_slice()));
7524 assert_eq!(awk_pipe_lhs(&tokens, &mut 2), None);
7525 assert_eq!(awk_pipe_rhs(&tokens, &mut 2), None);
7526 }
7527
7528 #[test]
7529 fn group_input_preserves_command_owned_stdin() {
7530 let mut commands = [
7531 Line::default(),
7532 Line {
7533 stdin_piped: true,
7534 ..Line::default()
7535 },
7536 Line {
7537 heredoc: true,
7538 ..Line::default()
7539 },
7540 ];
7541
7542 inherit_group_stdin(&mut commands);
7543
7544 assert_eq!(
7545 commands.map(|command| (command.stdin_piped, command.heredoc)),
7546 [(true, false), (true, false), (false, true)]
7547 );
7548 }
7549
7550 #[test]
7551 fn launcher_inline_option_requires_value_local_quote_evidence() {
7552 let proven = expand_for_platform(r#"docker run --env="$SETTING" alpine ls"#, false);
7553 assert!(!proven.dynamic);
7554 assert!(proven.commands.iter().any(|command| command == "ls"));
7555
7556 let words = ["--env=VALUE", "alpine", "ls"].map(str::to_string);
7557 let mut unresolved = false;
7558 let targets = resolve_wrapper_targets(
7559 &words,
7560 &[true, false, false],
7561 &[WordQuote::Quoted, WordQuote::Unquoted, WordQuote::Unquoted],
7562 0,
7563 &DOCKER_RUN_SPEC,
7564 &mut unresolved,
7565 );
7566 assert_eq!(targets, [2]);
7567 assert!(unresolved);
7568 }
7569
7570 #[test]
7571 fn tmux_prompt_template_respects_work_in_utf8_bytes() {
7572 let mut work_left = 128;
7573 assert_eq!(
7574 substitute_tmux_prompt_template("%% / %2", &["é", "猫"], &mut work_left),
7575 Some("é / 猫".to_string())
7576 );
7577
7578 let mut work_left = 10;
7579 assert_eq!(
7580 substitute_tmux_prompt_template("%1", &["é猫"], &mut work_left),
7581 None
7582 );
7583 assert_eq!(work_left, 0);
7584 }
7585
7586 fn expand(command: &str) -> Vec<String> {
7587 // Exercise the POSIX grammar consistently on every test host.
7588 expanded_commands_for_platform(command, false)
7589 }
7590
7591 #[test]
7592 fn launcher_flag_only_commands_do_not_panic() {
7593 for command in [
7594 "npm --version",
7595 "npm -v",
7596 "nix --version",
7597 "nix --offline --version",
7598 "launchctl --help",
7599 "docker --version",
7600 "docker -D --tls",
7601 "podman --version",
7602 "uv --version",
7603 "poetry --version",
7604 "pipx --version",
7605 "bundle --version",
7606 "perf --version",
7607 "tmux -V",
7608 "oc --version",
7609 "vagrant --version",
7610 "op --version",
7611 "opam --version",
7612 "helm --version",
7613 "helm plugin --help",
7614 "cd /tmp && node --version && npm --version && ls node_modules/@deepseek-ai/",
7615 ] {
7616 let expansion = expand_for_platform(command, false);
7617 assert!(!expansion.commands.is_empty(), "{command}");
7618 }
7619 assert!(contains("npm --silent exec --call 'rm -rf /'", "rm -rf /"));
7620 assert!(contains("nix --offline develop -c rm -rf /", "rm -rf /"));
7621 assert!(contains("docker -D run alpine rm -rf /", "rm -rf /"));
7622 assert!(contains("oc rsh pod rm -rf /", "rm -rf /"));
7623 assert!(contains("oc '' -n prod exec pod -- rm -rf /", "rm -rf /"));
7624 assert!(contains(
7625 "oc debug node/n -- chroot /host rm -rf /",
7626 "rm -rf /"
7627 ));
7628 assert!(contains("vagrant '' ssh -c 'rm -rf /'", "rm -rf /"));
7629 assert!(contains("vagrant ssh -- -t 'ls; rm -rf /'", "rm -rf /"));
7630 assert!(contains("op run --env-file .env -- rm -rf /", "rm -rf /"));
7631 assert!(contains(
7632 "opam exec --switch default -- rm -rf /",
7633 "rm -rf /"
7634 ));
7635 assert!(contains("helm template . --post-renderer rm", "rm"));
7636 assert!(contains(
7637 "helm template . --set --post-renderer --post-renderer rm",
7638 "rm"
7639 ));
7640 assert!(contains(
7641 "helm template . --post-renderer sh --post-renderer-args -c --post-renderer-args 'rm -rf /'",
7642 "rm -rf /"
7643 ));
7644 assert!(expand_for_platform("helm template . --post-renderer \"$PR\"", false).dynamic);
7645 assert!(expand_for_platform("helm plugin install ./evil", false).dynamic);
7646 assert!(!expand_for_platform("helm plugin list", false).dynamic);
7647 assert!(!expand_for_platform("oc get pods", false).dynamic);
7648 assert!(!expand_for_platform("vagrant status", false).dynamic);
7649 assert!(!expand_for_platform("op item list", false).dynamic);
7650 assert!(!expand_for_platform("opam list", false).dynamic);
7651 }
7652
7653 #[test]
7654 fn launcher_option_walk_past_state_limit_is_dynamic() {
7655 for prefix in ["docker run", "npm", "nix"] {
7656 let flags = "-e A ".repeat(1000);
7657 let command = format!("{prefix} {flags}alpine rm -rf /");
7658 assert!(expand_for_platform(&command, false).dynamic, "{prefix}");
7659 }
7660 assert!(!expand_for_platform("docker run -e A alpine rm -rf /", false).dynamic);
7661 }
7662
7663 #[test]
7664 fn deny_suffix_truncation_is_fail_closed() {
7665 let suffixes = " -- a".repeat(260);
7666 let command = format!("x{suffixes} rm -rf /");
7667 let expansion = expand_for_platform(&command, false);
7668 assert!(
7669 expansion.dynamic,
7670 "truncated deny scan must not claim resolve"
7671 );
7672 assert_eq!(expansion.deny_commands().count(), 257);
7673 let nested = "x".to_string() + &" -- a".repeat(40);
7674 assert!(expand_for_platform(&nested, false).dynamic);
7675 }
7676
7677 #[test]
7678 fn flag_word_substitution_marks_expansion_dynamic() {
7679 for command in [
7680 "nix develop -c$(echo rm) x",
7681 "nix develop -c$(echo rm)",
7682 "nix develop --command=$(echo rm) x",
7683 "nix develop --command$(echo =rm) x",
7684 "nix shell -c$(echo rm) x",
7685 "nix shell --command=$(echo rm) x",
7686 "su -c$(echo rm) x",
7687 "npx -c$(echo rm) x",
7688 "npx -c$(echo rm)",
7689 "nix-shell --run$(echo =rm) x",
7690 "start-stop-daemon -S -x$(echo /bin/rm) -- x",
7691 "start-stop-daemon -S --exec=$(echo /bin/rm) -- x",
7692 "launchctl submit -p$(echo /bin/rm) -- x",
7693 "cmd /c$(echo rm) x",
7694 "pwsh -c$(echo rm) x",
7695 "find . -exec$(echo rm) x \\;",
7696 "sh -c$(echo rm) x",
7697 "nu --commands$(echo =rm) x",
7698 "docker run --entrypoint=$(echo /bin/rm) alpine x",
7699 "docker run --entrypoint$(echo =/bin/rm) alpine x",
7700 ] {
7701 assert!(
7702 expand_for_platform(command, false).dynamic,
7703 "{command:?} should be dynamic"
7704 );
7705 }
7706 for command in [
7707 "nix develop -c echo hi",
7708 "nix develop --command echo hi",
7709 "nix develop --command=echo hi",
7710 "nix shell -c echo hi",
7711 "su -c 'echo hi'",
7712 "npx -c 'echo hi'",
7713 "start-stop-daemon -S -x /bin/echo -- hi",
7714 "docker run --entrypoint /bin/echo alpine hi",
7715 ] {
7716 assert!(
7717 !expand_for_platform(command, false).dynamic,
7718 "{command:?} should stay static"
7719 );
7720 }
7721 }
7722
7723 #[test]
7724 fn launcher_payloads_survive_empty_words_and_entrypoint_args() {
7725 for (command, expected) in [
7726 ("npm '' exec -c 'rm -rf /'", "rm -rf /"),
7727 ("npm '' '' x --call 'rm -rf /'", "rm -rf /"),
7728 ("docker '' run alpine rm -rf /", "rm -rf /"),
7729 ("nix '' develop -c rm -rf /", "rm -rf /"),
7730 ("npm '' --silent exec -c 'rm -rf /'", "rm -rf /"),
7731 ("docker '' -D run alpine rm -rf /", "rm -rf /"),
7732 ("nix '' --offline develop -c rm -rf /", "rm -rf /"),
7733 ("docker -D run --entrypoint rm alpine -rf /", "rm -rf /"),
7734 ("docker run --entrypoint=rm alpine -rf /", "rm -rf /"),
7735 ("podman run -it --entrypoint rm alpine -rf /", "rm -rf /"),
7736 (
7737 "docker run --entrypoint true --entrypoint rm alpine -rf /",
7738 "rm -rf /",
7739 ),
7740 (
7741 "docker run --entrypoint=true --entrypoint=rm alpine -rf /",
7742 "rm -rf /",
7743 ),
7744 (
7745 "docker run --entrypoint rm alpine -rf / --entrypoint true",
7746 "rm -rf / --entrypoint true",
7747 ),
7748 (
7749 "podman run --entrypoint=rm alpine -rf / --entrypoint=true",
7750 "rm -rf / --entrypoint=true",
7751 ),
7752 (
7753 "docker run --entrypoint sh alpine -c 'rm -rf /' --entrypoint=true",
7754 "rm -rf /",
7755 ),
7756 (
7757 "docker run --entrypoint rm -e --entrypoint=true alpine -rf /",
7758 "rm -rf /",
7759 ),
7760 (
7761 "docker run --entrypoint rm --label --entrypoint=true alpine -rf /",
7762 "rm -rf /",
7763 ),
7764 (
7765 "docker run --entrypoint sh -e --entrypoint=true alpine -c 'rm -rf /'",
7766 "rm -rf /",
7767 ),
7768 (
7769 "podman run --entrypoint rm -e --entrypoint=true alpine -rf /",
7770 "rm -rf /",
7771 ),
7772 (
7773 "docker run -e --entrypoint --entrypoint rm alpine -rf /",
7774 "rm -rf /",
7775 ),
7776 (
7777 "podman run -l --entrypoint --entrypoint sh alpine -c 'rm -rf /'",
7778 "rm -rf /",
7779 ),
7780 ] {
7781 assert!(contains(command, expected), "{command}");
7782 }
7783 }
7784
7785 #[test]
7786 fn native_windows_command_words_are_plain_literals() {
7787 for command in [
7788 r"C:\Windows\System32\where.exe git",
7789 r"C:\Git\bin\bash.exe -lc ls",
7790 r".\build.bat --release",
7791 r"\\server\share\tool.exe /q",
7792 ] {
7793 assert!(
7794 !expand_for_platform(command, true).dynamic,
7795 "{command} was unresolved"
7796 );
7797 }
7798 assert!(expand_for_platform(r"%COMSPEC% /c dir", true).dynamic);
7799 }
7800
7801 #[test]
7802 fn windows_scan_retains_native_paths_and_posix_deny_candidates() {
7803 for (command, expected) in [
7804 (
7805 r"C:\Windows\System32\cat.exe ~/.ssh/id_rsa",
7806 r"C:\Windows\System32\cat.exe ~/.ssh/id_rsa",
7807 ),
7808 (r"del /f c:\users\x\file", r"del /f c:\users\x\file"),
7809 (
7810 r"echo safe & xcopy /e /y c:\src d:\dst",
7811 r"xcopy /e /y c:\src d:\dst",
7812 ),
7813 (
7814 r#""C:\Program Files\cat.exe" "c:\path with spaces\file""#,
7815 r"C:\Program Files\cat.exe c:\path with spaces\file",
7816 ),
7817 (r"del relative\file", r"del relative\file"),
7818 (
7819 r"\\server\share\cat.exe file",
7820 r"\\server\share\cat.exe file",
7821 ),
7822 (r"bash -c 'rm -rf \/'", "rm -rf /"),
7823 ] {
7824 let targets = expanded_commands_for_platform(command, true);
7825 assert!(
7826 targets.iter().any(|target| target == expected),
7827 "missing {expected:?} from {targets:?}"
7828 );
7829 assert!(targets.len() <= MAX_COMMANDS);
7830 }
7831 let targets =
7832 expanded_commands_for_platform("cat <<'EOF'\ndel c:\\users\\x\\file\nEOF", true);
7833 assert!(
7834 !targets.iter().any(|target| target.starts_with("del ")),
7835 "literal heredoc data must stay inert: {targets:?}"
7836 );
7837 }
7838
7839 fn contains(command: &str, expected: &str) -> bool {
7840 expand(command).iter().any(|target| target == expected)
7841 }
7842
7843 #[test]
7844 fn repeated_double_dash_expands_in_bounded_time() {
7845 for prefix in ["echo", "npm"] {
7846 let command = format!("{prefix} {}rm -rf /", "-- ".repeat(40));
7847 let started = std::time::Instant::now();
7848 let expansion = expand_for_platform(&command, false);
7849 assert!(
7850 started.elapsed() < std::time::Duration::from_secs(5),
7851 "{prefix}"
7852 );
7853 assert!(
7854 expansion.deny_commands().any(|cmd| cmd == "rm -rf /"),
7855 "{prefix}"
7856 );
7857 }
7858 }
7859
7860 #[test]
7861 fn capped_extra_deny_still_finds_deny_after_repeated_suffix() {
7862 let pads = (1..=253)
7863 .map(|i| format!("p{i}"))
7864 .collect::<Vec<_>>()
7865 .join(" ; ");
7866 let payload = format!("{pads} ; y -- sudo rm -rf /");
7867 let seeds = format!("\"bash -c {payload}\" ; {pads} ; \"y -- sudo rm -rf /\"");
7868 let command =
7869 format!("{seeds} ; x -- bash -c \"{payload}\" ; x -- bash -c 'w -- sudo rm -rf /'");
7870 let expansion = expand_for_platform(&command, false);
7871 assert!(
7872 expansion.deny_commands().any(|cmd| cmd == "rm -rf /"),
7873 "rm -rf / missing from {:?}",
7874 expansion.deny_commands().collect::<Vec<_>>()
7875 );
7876 }
7877
7878 #[test]
7879 fn backtick_body_is_a_command() {
7880 assert!(contains("`rm -rf /`", "rm -rf /"));
7881 assert!(contains("echo `rm -rf /`", "rm -rf /"));
7882 assert!(contains("echo `rm -rf /`", "echo"));
7883 }
7884
7885 #[test]
7886 fn dollar_paren_body_is_a_command() {
7887 assert!(contains("echo $(rm -rf /)", "rm -rf /"));
7888 assert!(contains("x=$(rm -rf /)", "rm -rf /"));
7889 assert!(contains("echo \"$(rm -rf /)\"", "rm -rf /"));
7890 }
7891
7892 #[test]
7893 fn nested_substitution_is_followed() {
7894 assert!(contains("echo $(echo `rm -rf /`)", "rm -rf /"));
7895 }
7896
7897 #[test]
7898 fn quotes_are_removed_from_operands() {
7899 assert!(contains("rm -rf \"/\"", "rm -rf /"));
7900 assert!(contains("rm -rf '/'", "rm -rf /"));
7901 assert!(contains("\"rm\" -rf /", "rm -rf /"));
7902 assert!(contains("rm -r\"f\" /", "rm -rf /"));
7903 }
7904
7905 #[test]
7906 fn single_quoted_text_is_not_a_command() {
7907 // A literal backtick inside single quotes is printed, not executed.
7908 let targets = expand("echo '`rm -rf /`'");
7909 assert!(
7910 !targets.iter().any(|t| t == "rm -rf /"),
7911 "single-quoted text must not become a command: {targets:?}"
7912 );
7913 }
7914
7915 #[test]
7916 fn escaped_operators_do_not_split() {
7917 let targets = expand("echo a\\;b");
7918 assert_eq!(targets, vec!["echo a;b".to_string()]);
7919 assert!(targets.contains(&"echo a;b".to_string()), "{targets:?}");
7920 }
7921
7922 #[test]
7923 fn control_operators_split_commands() {
7924 for command in [
7925 "ls && rm -rf /",
7926 "ls || rm -rf /",
7927 "ls ; rm -rf /",
7928 "ls | rm -rf /",
7929 "ls & rm -rf /",
7930 "ls\nrm -rf /",
7931 ] {
7932 assert!(contains(command, "rm -rf /"), "{command}");
7933 }
7934 }
7935
7936 #[test]
7937 fn wrappers_and_payloads_are_unwrapped() {
7938 for command in [
7939 "sudo rm -rf /",
7940 "env rm -rf /",
7941 "timeout 5 rm -rf /",
7942 "nohup rm -rf /",
7943 "xargs rm -rf /",
7944 "/usr/bin/sudo rm -rf /",
7945 "eval 'rm -rf /'",
7946 "bash -c 'rm -rf /'",
7947 "sh -lc \"rm -rf /\"",
7948 "sudo -u root bash -c 'rm -rf /'",
7949 // 2026-08-04: `-o vi` used to end the flag scan before `-c` was
7950 // seen, so the payload skipped deny expansion entirely.
7951 "bash -o vi -c 'rm -rf /'",
7952 "zsh --norcs -c 'rm -rf /'",
7953 ] {
7954 assert!(
7955 contains(command, "rm -rf /"),
7956 "{command}: {:?}",
7957 expand(command)
7958 );
7959 }
7960 }
7961
7962 #[test]
7963 fn options_after_dash_c_do_not_hide_the_command_string() {
7964 // The command string is the first operand once options end, so an
7965 // option between `-c` and it does not change what runs.
7966 for command in [
7967 "bash -c -e 'rm -rf /'",
7968 "bash -c -l 'rm -rf /'",
7969 "sh -c -x 'rm -rf /'",
7970 "bash -c -- 'rm -rf /'",
7971 "sh -c - 'rm -rf /'",
7972 "bash -c +e 'rm -rf /'",
7973 "bash -lc -e 'rm -rf /'",
7974 "bash -c -o pipefail 'rm -rf /'",
7975 "bash -c -O extglob -e 'rm -rf /'",
7976 "bash script.sh -c 'rm -rf /'",
7977 ] {
7978 assert!(
7979 contains(command, "rm -rf /"),
7980 "{command}: {:?}",
7981 expand(command)
7982 );
7983 }
7984 // Arguments after the command string are positional parameters.
7985 assert!(!contains("bash -c 'echo $0' 'rm -rf /'", "rm -rf /"));
7986 }
7987
7988 #[test]
7989 fn script_operand_naming_a_descriptor_is_read_at_run_time() {
7990 for command in [
7991 "echo 'rm -rf /' | bash /dev/stdin",
7992 "bash /dev/stdin <<< 'rm -rf /'",
7993 "sh /dev/fd/0 <<< 'rm -rf /'",
7994 "sh /proc/self/fd/0 <<< 'rm -rf /'",
7995 "bash //dev/./stdin <<< 'rm -rf /'",
7996 "bash /dev/fd/3 3< script",
7997 ". /dev/stdin <<< 'rm -rf /'",
7998 "source /proc/self/fd/0 <<< 'rm -rf /'",
7999 ] {
8000 assert!(expand_command(command).dynamic, "{command}");
8001 }
8002 // A heredoc on stdin was expanded as the script itself.
8003 let heredoc = expand_for_platform("bash /dev/stdin <<EOF\nrm -rf /\nEOF", false);
8004 assert!(!heredoc.dynamic);
8005 assert!(heredoc.commands.iter().any(|target| target == "rm -rf /"));
8006 // An ordinary script file is still opaque, not unresolved.
8007 assert!(!expand_command("bash ./dev/stdin").dynamic);
8008 assert!(!expand_command(". ./env.sh").dynamic);
8009 }
8010
8011 #[test]
8012 fn wrapper_head_scan_stops_at_a_real_command() {
8013 // `echo` prints its arguments; nothing here is executed as a shell.
8014 let targets = expand("echo bash -c 'rm -rf /'");
8015 assert!(
8016 !targets.iter().any(|t| t == "rm -rf /"),
8017 "arguments of a printing command must not be parsed as code: {targets:?}"
8018 );
8019 }
8020
8021 #[test]
8022 fn process_and_parameter_substitution_bodies_are_commands() {
8023 assert!(contains("diff <(rm -rf /) b", "rm -rf /"));
8024 assert!(contains("echo ${x:-$(rm -rf /)}", "rm -rf /"));
8025 }
8026
8027 #[test]
8028 fn expansion_is_bounded() {
8029 let deep = "$(".repeat(64) + "rm -rf /" + &")".repeat(64);
8030 let targets = expand(&deep);
8031 assert!(targets.len() <= MAX_COMMANDS);
8032 }
8033
8034 #[test]
8035 fn grouping_is_a_command_boundary() {
8036 assert!(contains("(rm -rf /)", "rm -rf /"));
8037 assert!(contains("{ rm -rf /; }", "rm -rf /"));
8038 assert!(contains("(cd /tmp && rm -rf /)", "rm -rf /"));
8039 // Escaped and quoted parens are operands, not grouping.
8040 assert!(contains(
8041 "find . \\( -name a \\) -print",
8042 "find . ( -name a ) -print"
8043 ));
8044 }
8045
8046 #[test]
8047 fn syntax_metadata_is_independent_of_candidates_and_literal_data() {
8048 for command in [
8049 "printf x; printf x",
8050 "git log | git log",
8051 "cargo test && cargo test",
8052 "(git log)",
8053 ] {
8054 let expansion = expand_for_platform(command, false);
8055 assert!(expansion.control, "{command}: {expansion:?}");
8056 }
8057 assert_eq!(
8058 expand_for_platform("printf x; printf x", false)
8059 .commands
8060 .len(),
8061 1
8062 );
8063 assert!(expand_for_platform("sudo git log", false).commands.len() > 1);
8064 assert!(!expand_for_platform("sudo git log", false).control);
8065 for command in [
8066 r#"grep -E "a|b" src"#,
8067 r#"git commit -m "fix: a & b; c""#,
8068 r"echo a\;b\&c\|d\>e",
8069 "echo '> < ; | &'",
8070 "echo ok # ; | > ignored",
8071 ] {
8072 let expansion = expand_for_platform(command, false);
8073 assert!(
8074 !expansion.control && !expansion.redirects,
8075 "{command}: {expansion:?}"
8076 );
8077 }
8078 for command in [
8079 "cargo test 2>&1",
8080 "cargo test &>result.log",
8081 "cat a<>out",
8082 "cat a>|out",
8083 "cat 3<&0",
8084 "cat<<<literal",
8085 ] {
8086 for windows in [false, true] {
8087 let expansion = expand_for_platform(command, windows);
8088 assert!(
8089 expansion.redirects && !expansion.control,
8090 "{command}: {expansion:?}"
8091 );
8092 }
8093 }
8094 for command in ["git log $FLAGS", r#"git log "$FLAGS""#] {
8095 let expansion = expand_for_platform(command, false);
8096 assert!(
8097 expansion.arguments_dynamic && !expansion.dynamic,
8098 "{command}: {expansion:?}"
8099 );
8100 }
8101 assert!(!expand_for_platform("git log '$FLAGS'", false).arguments_dynamic);
8102 assert!(!expand_for_platform(r"git log \$FLAGS", false).arguments_dynamic);
8103 let heredoc = expand_for_platform("cat <<'EOF'\n; | > $(not-code)\nEOF", false);
8104 assert!(heredoc.redirects);
8105 assert!(!heredoc.nested);
8106 assert_eq!(heredoc.commands, vec!["cat"]);
8107 }
8108
8109 #[test]
8110 fn plain_command_expands_to_itself() {
8111 assert_eq!(expand("git status -s"), vec!["git status -s".to_string()]);
8112 }
8113
8114 #[test]
8115 fn ansi_c_escapes_decode_control_and_newline_characters() {
8116 for (command, expected_head) in [
8117 (r#"sh -c $'echo x\nwipefs -a /dev/sda'"#, "wipefs"),
8118 (r#"sh -c $'echo x\nmkfs.ext4 /dev/sda1'"#, "mkfs.ext4"),
8119 (r#"sh -c $'echo x\rwipefs -a /dev/sda'"#, "wipefs"),
8120 (r#"sh -c $'echo x\x0amkfs.ext4 /dev/sda1'"#, "mkfs.ext4"),
8121 (r#"sh -c $'echo x\012shred /dev/sda'"#, "shred"),
8122 (r#"sh -c $'echo x\u000add if=/dev/zero of=/dev/sda'"#, "dd"),
8123 (r#"sh -c $'echo x\cJwipefs -a /dev/sda'"#, "wipefs"),
8124 (r#"$(sh -c $'echo \'x\'\nwipefs -a /dev/sda')"#, "wipefs"),
8125 ] {
8126 let expansion = expand_for_platform(command, false);
8127 assert!(
8128 expansion
8129 .words
8130 .iter()
8131 .any(|words| words.first().map(String::as_str) == Some(expected_head)),
8132 "{command}: {:?}",
8133 expansion.words
8134 );
8135 }
8136 assert!(
8137 expand_for_platform(r#"sh -c $'echo\ta\tb'"#, false)
8138 .words
8139 .iter()
8140 .any(|words| words == &["echo", "a", "b"])
8141 );
8142 assert!(expand_for_platform("$'rm' -f f", false).dynamic);
8143 assert!(expand_for_platform("$'\\x72m' f", false).dynamic);
8144 }
8145
8146 #[test]
8147 fn awk_static_and_dynamic_command_payloads_are_scanned() {
8148 for (command, expected) in [
8149 ("awk 'BEGIN{system(\"rm x\")}'", "rm x"),
8150 ("awk 'BEGIN{system(\"r\" \"m\" \" x\")}'", "rm x"),
8151 (r#"awk 'BEGIN{system("\162\155 x")}'"#, "rm x"),
8152 (r#"awk 'BEGIN{system("\x72\x6d x")}'"#, "rm x"),
8153 ("awk 'BEGIN{\"rm x\" | getline}'", "rm x"),
8154 (
8155 "awk 'BEGIN{while ((\"rm x\" | getline line) > 0) print line}'",
8156 "rm x",
8157 ),
8158 ("awk 'BEGIN{\"rm x\" |& getline}'", "rm x"),
8159 ("awk 'BEGIN{print \"a\" | \"rm x\"}'", "rm x"),
8160 ("awk 'BEGIN{printf \"%s\", \"a\" |& \"rm x\"}'", "rm x"),
8161 ("awk '{x = a / b; system(\"rm x\"); y = c / d}'", "rm x"),
8162 ("gawk -e 'BEGIN{system(\"rm x\")}' file.txt", "rm x"),
8163 ("gawk --source='BEGIN{system(\"rm x\")}' file.txt", "rm x"),
8164 ("mawk -F: 'BEGIN{system(\"rm x\")}' /etc/passwd", "rm x"),
8165 ("awk -- 'BEGIN{system(\"rm x\")}'", "rm x"),
8166 ("gawk -e 'BEGIN{system(\"rm\"' -e '\" x\")}'", "rm x"),
8167 ] {
8168 let expansion = expand_for_platform(command, false);
8169 assert!(
8170 expansion.commands.iter().any(|target| target == expected),
8171 "{command}: {:?}",
8172 expansion.commands
8173 );
8174 assert!(expansion.nested, "{command}");
8175 }
8176
8177 for command in [
8178 "awk 'BEGIN{c=\"rm x\"; system(c)}'",
8179 "awk -v c='rm x' 'BEGIN{system(c)}'",
8180 "awk 'BEGIN{system(\"rm \" $1)}'",
8181 "awk 'BEGIN{c=\"rm x\"; c | getline}'",
8182 "awk 'BEGIN{c=\"rm x\"; print \"a\" | c}'",
8183 "awk $PROG file.txt",
8184 "gawk -e \"$PROG\" file.txt",
8185 "awk -f - file.txt",
8186 "awk -f /dev/stdin file.txt",
8187 ] {
8188 assert!(expand_for_platform(command, false).dynamic, "{command}");
8189 }
8190
8191 for command in [
8192 "awk '{print}'",
8193 "awk '{print $1}'",
8194 "awk -F: '{print $1}' /etc/passwd",
8195 "awk '/foo|bar/ {print}' file.txt",
8196 "awk '$1 ~ /foo|bar/ {print}' file.txt",
8197 "awk '$1 == \"a\" || $2 == \"b\" {print}' file.txt",
8198 "awk '{print $1 / 2}' file.txt",
8199 "awk '{print \"system(\\\"rm x\\\")\"}'",
8200 "awk '# system(\"rm x\")\n{print $1}'",
8201 "awk '{my_system(\"rm x\")}'",
8202 "awk -f script.awk file.txt",
8203 ] {
8204 let expansion = expand_for_platform(command, false);
8205 assert!(
8206 !expansion.dynamic && !expansion.nested,
8207 "{command}: {expansion:?}"
8208 );
8209 }
8210 }
8211
8212 #[test]
8213 fn tmux_execution_verbs_expand_payloads_and_keep_inert_verbs_clean() {
8214 for command in [
8215 "tmux display-popup 'rm x'",
8216 "tmux popup -E -d /tmp -t s -w 80% -h 50% 'rm x'",
8217 "tmux confirm-before 'rm x'",
8218 "tmux confirm -b -c y -p 'ok?' -t s \"run-shell 'rm x'\"",
8219 "tmux command-prompt -I 'rm x'",
8220 "tmux command-prompt -I 'rm x' \"run-shell '%%'\"",
8221 "tmux bind-key k run-shell 'rm x'",
8222 "tmux bind -n -r -T root -N note F1 display-popup -E 'rm x'",
8223 "tmux bind-key k \"run-shell 'rm x'\"",
8224 "tmux '' display-popup 'rm x'",
8225 ] {
8226 assert!(
8227 contains(command, "rm x"),
8228 "{command}: {:?}",
8229 expand(command)
8230 );
8231 }
8232
8233 for command in [
8234 "tmux source-file f",
8235 "tmux source ~/.tmux.conf",
8236 "tmux source-file -n -F '#(rm x)'",
8237 "tmux source-file -t -n f",
8238 "tmux source-file -- -n",
8239 "tmux bind-key k '$CMD'",
8240 ] {
8241 assert!(expand_for_platform(command, false).dynamic, "{command}");
8242 }
8243
8244 for command in [
8245 "tmux list-sessions",
8246 "tmux ls",
8247 "tmux display-message hi",
8248 "tmux attach",
8249 "tmux display-popup -C",
8250 "tmux source-file -n ~/.tmux.conf",
8251 ] {
8252 let expansion = expand_for_platform(command, false);
8253 assert!(
8254 !expansion.dynamic && !expansion.nested,
8255 "{command}: {expansion:?}"
8256 );
8257 }
8258
8259 let bind_ls = expand_for_platform("tmux bind-key k ls", false);
8260 assert!(!bind_ls.dynamic);
8261 assert!(!bind_ls.commands.iter().any(|cmd| cmd == "ls"));
8262 }
8263
8264 #[test]
8265 fn sed_static_and_dynamic_command_payloads_are_scanned() {
8266 for (command, expected) in [
8267 ("sed 's/a/rm x/e'", "rm x"),
8268 ("sed 's#a#rm x#ge'", "rm x"),
8269 ("sed 's|a|rm x|2ep'", "rm x"),
8270 ("sed 's/.*/rm x/e'", "rm x"),
8271 ("sed 's/a/rm x/ew /tmp/out'", "rm x"),
8272 ("sed 'e rm x'", "rm x"),
8273 ("sed '1e rm x'", "rm x"),
8274 ("sed '/foo/e rm x'", "rm x"),
8275 ("sed 's/foo/bar/g; e rm x'", "rm x"),
8276 ("sed -e 's/a/b/' -e 's/c/rm x/e'", "rm x"),
8277 ("sed --expression='e rm x'", "rm x"),
8278 ("sed -ne 's/a/rm x/e'", "rm x"),
8279 ("sed -i '' 's/a/rm x/e' file.txt", "rm x"),
8280 ("sed -i .bak 's/a/rm x/e' file.txt", "rm x"),
8281 ("gsed '1{s/a/rm x/e}'", "rm x"),
8282 ("sed 'e echo hi; rm x'", "rm x"),
8283 ] {
8284 let expansion = expand_for_platform(command, false);
8285 assert!(
8286 expansion.commands.iter().any(|target| target == expected),
8287 "{command}: {:?}",
8288 expansion.commands
8289 );
8290 assert!(expansion.nested, "{command}");
8291 }
8292
8293 for command in [
8294 "sed 'e'",
8295 "sed '1e'",
8296 "sed '1{e}'",
8297 "sed 'e; p'",
8298 "sed 's/^//e'",
8299 "sed 's/a/b/e'",
8300 "sed $PROG file.txt",
8301 "sed -e \"$PROG\" file.txt",
8302 "sed -f - file.txt",
8303 "sed -f /dev/stdin file.txt",
8304 ] {
8305 assert!(expand_for_platform(command, false).dynamic, "{command}");
8306 }
8307
8308 for command in [
8309 "sed -n '/x/p'",
8310 "sed 's/foo/bar/g'",
8311 "sed -e 's/echo/echoed/g'",
8312 "sed 's/e/x/g'",
8313 "sed 's/a/b/w readme.txt'",
8314 "sed 'y/abcde/ABCDE/'",
8315 "sed ':end; s/a/b/; t end'",
8316 "sed '1i\\\nexample header'",
8317 "sed 's/[a/e]/b/g'",
8318 "sed 's/[[:alpha:]/]/e/g'",
8319 "sed -i 's/foo/bar/' file.txt",
8320 "sed -i '' 's/foo/bar/g' file.txt",
8321 "sed -f script.sed file.txt",
8322 ] {
8323 let expansion = expand_for_platform(command, false);
8324 assert!(
8325 !expansion.dynamic && !expansion.nested,
8326 "{command}: {expansion:?}"
8327 );
8328 }
8329 }
8330
8331 #[test]
8332 fn stdin_piped_propagation_and_numactl_strict() {
8333 for command in [
8334 "echo 'rm x' | ssh host",
8335 "echo 'rm x' |& ssh host",
8336 "echo 'rm x' |\nssh host",
8337 "ssh host < script",
8338 "ssh host 0< script",
8339 "ssh host <<< 'rm x'",
8340 "ssh host 0<<< 'rm x'",
8341 "ssh host sh <<EOF\nrm x\nEOF",
8342 "ssh host 'ssh host2' <<EOF\nrm x\nEOF",
8343 "echo 'rm x' | find . -exec ssh host \\;",
8344 "echo 'rm x' | { a; ssh host; }",
8345 "echo 'rm x' | { { a; }; ssh host; }",
8346 "echo 'rm x' | (a; ssh host)",
8347 "{ a; ssh host; } <<< 'rm x'",
8348 "(a; ssh host) < script",
8349 "echo 'rm x' | echo $(ssh host)",
8350 "echo 'rm x' | sh -c 'ssh host'",
8351 ] {
8352 assert!(expand_for_platform(command, false).dynamic, "{command}");
8353 }
8354 for command in [
8355 "x || ssh host",
8356 "echo x | y || ssh host",
8357 "echo x | y && ssh host",
8358 "echo x | y; ssh host",
8359 "ssh host 3< f",
8360 "ssh host {fd}< f",
8361 "ssh host 3<<< 'rm x'",
8362 "ssh host 3<&0",
8363 "ssh host 3<<EOF\nrm x\nEOF",
8364 "ssh host ls <<EOF\nrm x\nEOF",
8365 "ssh host <<EOF\nls\nEOF",
8366 "find . -exec ssh host \\;",
8367 "echo x | { a; b; }; ssh host",
8368 "echo x | (a; b); ssh host",
8369 "{ a; ssh host; } 3< f",
8370 ] {
8371 let expansion = expand_for_platform(command, false);
8372 assert!(!expansion.dynamic, "{command}: {expansion:?}");
8373 }
8374 assert!(contains("ssh host <<EOF\nrm x\nEOF", "rm x"));
8375 assert!(!contains("ssh host ls <<EOF\nrm x\nEOF", "rm x"));
8376 assert!(contains("ssh host ls <<EOF\n$(rm x)\nEOF", "rm x"));
8377 assert!(contains("numactl --strict rm", "rm"));
8378 assert!(!contains("numactl --strict echo rm", "rm"));
8379 }
8380 }
8381
8381 lines RUST