Skip to main content

aither_sandbox/
shell_syntax.rs

1//! Shell scripts parsed into the command lines they would run.
2//!
3//! [`ShellScript::parse`] walks the syntax tree rather than matching text, so
4//! a word that merely contains a program's name (`echo pkill`, `cat
5//! sleep.txt`) is not a command, while commands are found through pipelines,
6//! lists, compound commands, command and process substitutions, wrappers
7//! (`env`, `sudo`, `timeout`, `xargs`, `find -exec`, ...) and the script
8//! strings of `sh -c`, `eval` and shells fed through a here-document.
9//!
10//! Static analysis only sees names that are written out. A program name that
11//! is computed at run time (`$tool`, `$(echo pkill)`) or a script piped into a
12//! shell's stdin cannot be resolved and yields no command.
13
14use std::cell::{Cell, RefCell};
15use std::fmt::Display;
16
17use brush_parser::ast::{
18    self, AndOrList, Assignment, AssignmentValue, Command, CommandPrefixOrSuffixItem,
19    CompoundCommand, CompoundList, ExtendedTestExpr, IoFileRedirectTarget, IoRedirect, Pipeline,
20    SimpleCommand,
21};
22use brush_parser::word::{ParameterExpr, WordPiece, WordPieceWithSource};
23use brush_parser::{Parser, ParserOptions, SourceInfo};
24
25/// Deepest nesting of shell strings (`sh -c '... sh -c ...'`) and
26/// substitutions the parse follows before it gives up.
27const MAX_DEPTH: usize = 32;
28
29/// A script that is not valid shell, or nests shell strings and
30/// substitutions too deeply to follow.
31#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
32#[error("{reason}")]
33pub struct ShellParseError {
34    reason: String,
35}
36
37impl ShellParseError {
38    fn new(reason: impl Display) -> Self {
39        Self {
40            reason: reason.to_string(),
41        }
42    }
43
44    /// What the parser reported.
45    #[must_use]
46    pub fn reason(&self) -> &str {
47        &self.reason
48    }
49}
50
51/// Identifies one command of a [`ShellScript`].
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
53pub struct CommandId(usize);
54
55/// Identifies one simple command of a [`ShellScript`] as written: a program
56/// with its words, which may run further commands through wrappers.
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
58pub struct LineId(usize);
59
60/// Identifies one pipeline of a [`ShellScript`].
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
62pub struct PipelineId(usize);
63
64/// Where a command line sits in a pipeline of two or more commands.
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
66pub struct PipelineStage {
67    /// The pipeline.
68    pub pipeline: PipelineId,
69    /// The command's position in it, from 0 for the command that writes
70    /// first.
71    pub stage: usize,
72}
73
74/// One command line a script would run, with its words unquoted.
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct ShellCommand {
77    id: CommandId,
78    argv: Vec<String>,
79    program: String,
80    background: bool,
81    line: LineId,
82    wrapper: Option<CommandId>,
83    interpreter: Option<CommandId>,
84    substituted_into: Option<LineId>,
85    pipeline: Option<PipelineStage>,
86}
87
88impl ShellCommand {
89    /// This command's id.
90    #[must_use]
91    pub const fn id(&self) -> CommandId {
92        self.id
93    }
94
95    /// The program and its arguments, quotes removed. A word part computed
96    /// at run time contributes nothing to its word.
97    #[must_use]
98    pub fn argv(&self) -> &[String] {
99        &self.argv
100    }
101
102    /// The program's file name, lower-cased and without a Windows
103    /// executable suffix: `/usr/bin/PKILL.exe` is `pkill`.
104    #[must_use]
105    pub fn program(&self) -> &str {
106        &self.program
107    }
108
109    /// The arguments after the program.
110    #[must_use]
111    pub fn arguments(&self) -> &[String] {
112        &self.argv[1..]
113    }
114
115    /// Whether the command sits in an `&`-asynchronous position, so the
116    /// script does not wait on it. Everything nested in a detached command
117    /// is detached as well.
118    #[must_use]
119    pub const fn is_background(&self) -> bool {
120        self.background
121    }
122
123    /// The simple command, as written, this command belongs to: the
124    /// command itself, or the wrapper that runs it.
125    #[must_use]
126    pub const fn line(&self) -> LineId {
127        self.line
128    }
129
130    /// The command that runs this one from its own arguments: `env`,
131    /// `sudo`, `timeout`, `xargs`, `find -exec` and the like.
132    #[must_use]
133    pub const fn wrapper(&self) -> Option<CommandId> {
134        self.wrapper
135    }
136
137    /// The shell or `eval` command that runs this one from a script string
138    /// (`sh -c`, `eval`, or a shell reading a here-document).
139    #[must_use]
140    pub const fn interpreter(&self) -> Option<CommandId> {
141        self.interpreter
142    }
143
144    /// The command line whose words this command's output is substituted
145    /// into, through a command or process substitution, the nearest one when
146    /// substitutions nest: `kill $(pgrep foo)` substitutes `pgrep` into the
147    /// `kill` line.
148    #[must_use]
149    pub const fn substituted_into(&self) -> Option<LineId> {
150        self.substituted_into
151    }
152
153    /// Where the command's line sits in a pipeline of two or more commands;
154    /// a wrapped command shares its wrapper's stage.
155    #[must_use]
156    pub const fn pipeline(&self) -> Option<PipelineStage> {
157        self.pipeline
158    }
159}
160
161/// A shell script parsed into every command line it would run, in source
162/// order, a command's substitutions ahead of the command.
163#[derive(Debug, Clone, PartialEq, Eq)]
164pub struct ShellScript {
165    commands: Vec<ShellCommand>,
166}
167
168impl ShellScript {
169    /// Parses `script`.
170    ///
171    /// # Errors
172    /// Returns [`ShellParseError`] when the script, or a shell string inside
173    /// it, is not valid shell, or nests deeper than the parse follows.
174    pub fn parse(script: &str) -> Result<Self, ShellParseError> {
175        let walk = Walk::default();
176        script_walk(
177            script,
178            Cx {
179                walk: &walk,
180                depth: 0,
181                backgrounded: false,
182                substituted_into: None,
183                interpreter: None,
184            },
185        )?;
186        Ok(Self {
187            commands: walk.commands.into_inner(),
188        })
189    }
190
191    /// Every command the script would run.
192    #[must_use]
193    pub fn commands(&self) -> &[ShellCommand] {
194        &self.commands
195    }
196
197    /// The command `id` names.
198    ///
199    /// # Panics
200    /// Panics when `id` comes from another script.
201    #[must_use]
202    pub fn get(&self, id: CommandId) -> &ShellCommand {
203        &self.commands[id.0]
204    }
205
206    /// The commands of `line`: its program, then what it wraps.
207    pub fn line(&self, line: LineId) -> impl Iterator<Item = &ShellCommand> {
208        self.commands
209            .iter()
210            .filter(move |command| command.line == line)
211    }
212
213    /// The wrappers that run `command`, innermost first.
214    pub fn wrappers<'a>(
215        &'a self,
216        command: &'a ShellCommand,
217    ) -> impl Iterator<Item = &'a ShellCommand> + 'a {
218        std::iter::successors(command.wrapper.map(|id| self.get(id)), |wrapper| {
219            wrapper.wrapper.map(|id| self.get(id))
220        })
221    }
222}
223
224/// What the walk has found so far.
225#[derive(Default)]
226struct Walk {
227    commands: RefCell<Vec<ShellCommand>>,
228    lines: Cell<usize>,
229    pipelines: Cell<usize>,
230}
231
232impl Walk {
233    fn next_line(&self) -> LineId {
234        let line = self.lines.get();
235        self.lines.set(line + 1);
236        LineId(line)
237    }
238
239    fn next_pipeline(&self) -> PipelineId {
240        let pipeline = self.pipelines.get();
241        self.pipelines.set(pipeline + 1);
242        PipelineId(pipeline)
243    }
244}
245
246/// Traversal state: the findings, nesting depth, and what every command
247/// found below inherits.
248#[derive(Clone, Copy)]
249struct Cx<'a> {
250    walk: &'a Walk,
251    depth: usize,
252    /// Whether the commands below sit in an `&`-asynchronous position. Once
253    /// a list is detached, everything below it runs detached.
254    backgrounded: bool,
255    /// The line a substitution below feeds.
256    substituted_into: Option<LineId>,
257    /// The command whose script string is being walked.
258    interpreter: Option<CommandId>,
259}
260
261impl Cx<'_> {
262    const fn deeper(self) -> Self {
263        Self {
264            depth: self.depth + 1,
265            ..self
266        }
267    }
268}
269
270/// A command line found in a script, ahead of being recorded.
271struct Invocation<'a> {
272    argv: &'a [String],
273    /// The scripts its redirects feed to a shell reading stdin.
274    stdin_scripts: &'a [String],
275    line: LineId,
276    wrapper: Option<CommandId>,
277    pipeline: Option<PipelineStage>,
278}
279
280impl<'a> Invocation<'a> {
281    /// The command line `wrapper`, this invocation's command, runs from its
282    /// arguments: the same line, at the same pipeline stage.
283    const fn wrapped(&self, argv: &'a [String], wrapper: CommandId) -> Self {
284        Self {
285            argv,
286            stdin_scripts: self.stdin_scripts,
287            line: self.line,
288            wrapper: Some(wrapper),
289            pipeline: self.pipeline,
290        }
291    }
292}
293
294fn script_walk(script: &str, cx: Cx<'_>) -> Result<(), ShellParseError> {
295    if cx.depth > MAX_DEPTH {
296        return Err(ShellParseError::new(format!(
297            "shell strings are nested more than {MAX_DEPTH} levels deep"
298        )));
299    }
300    let program = Parser::new(
301        script.as_bytes(),
302        &ParserOptions::default(),
303        &SourceInfo::default(),
304    )
305    .parse_program()
306    .map_err(ShellParseError::new)?;
307    for list in &program.complete_commands {
308        compound_list(list, cx)?;
309    }
310    Ok(())
311}
312
313fn compound_list(list: &CompoundList, cx: Cx<'_>) -> Result<(), ShellParseError> {
314    for item in &list.0 {
315        // `cmd &` detaches the command: the script does not wait on it, and
316        // everything it nests runs detached as well.
317        let item_cx = Cx {
318            backgrounded: cx.backgrounded || matches!(item.1, ast::SeparatorOperator::Async),
319            ..cx
320        };
321        and_or_list(&item.0, item_cx)?;
322    }
323    Ok(())
324}
325
326fn and_or_list(list: &AndOrList, cx: Cx<'_>) -> Result<(), ShellParseError> {
327    pipeline(&list.first, cx)?;
328    for next in &list.additional {
329        match next {
330            ast::AndOr::And(next) | ast::AndOr::Or(next) => pipeline(next, cx)?,
331        }
332    }
333    Ok(())
334}
335
336fn pipeline(pipeline: &Pipeline, cx: Cx<'_>) -> Result<(), ShellParseError> {
337    let id = (pipeline.seq.len() > 1).then(|| cx.walk.next_pipeline());
338    for (stage, command) in pipeline.seq.iter().enumerate() {
339        let stage = id.map(|pipeline| PipelineStage { pipeline, stage });
340        self::command(command, stage, cx)?;
341    }
342    Ok(())
343}
344
345fn command(
346    command: &Command,
347    stage: Option<PipelineStage>,
348    cx: Cx<'_>,
349) -> Result<(), ShellParseError> {
350    match command {
351        Command::Simple(simple) => simple_command(simple, stage, cx),
352        Command::Compound(compound, redirects) => {
353            compound_command(compound, cx)?;
354            if let Some(redirects) = redirects {
355                for redirect in &redirects.0 {
356                    io_redirect(redirect, cx)?;
357                }
358            }
359            Ok(())
360        }
361        Command::Function(function) => {
362            word(&function.fname, cx)?;
363            compound_command(&function.body.0, cx)?;
364            if let Some(redirects) = &function.body.1 {
365                for redirect in &redirects.0 {
366                    io_redirect(redirect, cx)?;
367                }
368            }
369            Ok(())
370        }
371        Command::ExtendedTest(test) => extended_test(&test.expr, cx),
372    }
373}
374
375fn extended_test(expr: &ExtendedTestExpr, cx: Cx<'_>) -> Result<(), ShellParseError> {
376    match expr {
377        ExtendedTestExpr::And(left, right) | ExtendedTestExpr::Or(left, right) => {
378            extended_test(left, cx)?;
379            extended_test(right, cx)
380        }
381        ExtendedTestExpr::Not(inner) | ExtendedTestExpr::Parenthesized(inner) => {
382            extended_test(inner, cx)
383        }
384        ExtendedTestExpr::UnaryTest(_, operand) => word(operand, cx).map(drop),
385        ExtendedTestExpr::BinaryTest(_, left, right) => {
386            word(left, cx)?;
387            word(right, cx).map(drop)
388        }
389    }
390}
391
392fn compound_command(compound: &CompoundCommand, cx: Cx<'_>) -> Result<(), ShellParseError> {
393    match compound {
394        CompoundCommand::Arithmetic(arithmetic) => text(&arithmetic.expr.value, cx).map(drop),
395        CompoundCommand::ArithmeticForClause(clause) => {
396            for expr in [&clause.initializer, &clause.condition, &clause.updater]
397                .into_iter()
398                .flatten()
399            {
400                text(&expr.value, cx)?;
401            }
402            compound_list(&clause.body.list, cx)
403        }
404        CompoundCommand::BraceGroup(group) => compound_list(&group.list, cx),
405        CompoundCommand::Subshell(subshell) => compound_list(&subshell.list, cx),
406        CompoundCommand::ForClause(clause) => {
407            for value in clause.values.iter().flatten() {
408                word(value, cx)?;
409            }
410            compound_list(&clause.body.list, cx)
411        }
412        CompoundCommand::CaseClause(clause) => {
413            word(&clause.value, cx)?;
414            for item in &clause.cases {
415                for pattern in &item.patterns {
416                    word(pattern, cx)?;
417                }
418                if let Some(body) = &item.cmd {
419                    compound_list(body, cx)?;
420                }
421            }
422            Ok(())
423        }
424        CompoundCommand::IfClause(clause) => {
425            compound_list(&clause.condition, cx)?;
426            compound_list(&clause.then, cx)?;
427            for other in clause.elses.iter().flatten() {
428                if let Some(condition) = &other.condition {
429                    compound_list(condition, cx)?;
430                }
431                compound_list(&other.body, cx)?;
432            }
433            Ok(())
434        }
435        CompoundCommand::WhileClause(clause) | CompoundCommand::UntilClause(clause) => {
436            compound_list(&clause.0, cx)?;
437            compound_list(&clause.1.list, cx)
438        }
439    }
440}
441
442fn simple_command(
443    simple: &SimpleCommand,
444    stage: Option<PipelineStage>,
445    cx: Cx<'_>,
446) -> Result<(), ShellParseError> {
447    let line = cx.walk.next_line();
448    // A substitution in any of the line's words feeds the line.
449    let word_cx = Cx {
450        substituted_into: Some(line),
451        ..cx
452    };
453    let mut argv = Vec::new();
454    let mut stdin_scripts = Vec::new();
455    let prefix = simple.prefix.iter().flat_map(|prefix| &prefix.0);
456    let suffix = simple.suffix.iter().flat_map(|suffix| &suffix.0);
457    for item in prefix {
458        // Assignments before the program set its environment; they are not
459        // part of the command line.
460        if let CommandPrefixOrSuffixItem::AssignmentWord(assignment, _) = item {
461            assignment_value(assignment, word_cx)?;
462        } else {
463            affix_item(item, &mut argv, &mut stdin_scripts, word_cx)?;
464        }
465    }
466    if let Some(program) = &simple.word_or_name {
467        argv.push(word(program, word_cx)?);
468    }
469    for item in suffix {
470        affix_item(item, &mut argv, &mut stdin_scripts, word_cx)?;
471    }
472    invoked(
473        &Invocation {
474            argv: &argv,
475            stdin_scripts: &stdin_scripts,
476            line,
477            wrapper: None,
478            pipeline: stage,
479        },
480        cx,
481    )
482}
483
484fn affix_item(
485    item: &CommandPrefixOrSuffixItem,
486    argv: &mut Vec<String>,
487    stdin_scripts: &mut Vec<String>,
488    cx: Cx<'_>,
489) -> Result<(), ShellParseError> {
490    match item {
491        CommandPrefixOrSuffixItem::Word(argument) => {
492            argv.push(word(argument, cx)?);
493        }
494        CommandPrefixOrSuffixItem::AssignmentWord(assignment, argument) => {
495            assignment_value(assignment, cx)?;
496            // `declare x=1` style words keep their text as an argument.
497            argv.push(word(argument, cx)?);
498        }
499        CommandPrefixOrSuffixItem::IoRedirect(redirect) => {
500            if let Some(script) = stdin_script(redirect, cx)? {
501                stdin_scripts.push(script);
502            }
503            io_redirect(redirect, cx)?;
504        }
505        CommandPrefixOrSuffixItem::ProcessSubstitution(_, subshell) => {
506            compound_list(&subshell.list, cx)?;
507        }
508    }
509    Ok(())
510}
511
512/// The text a here-document or here-string feeds to stdin.
513fn stdin_script(redirect: &IoRedirect, cx: Cx<'_>) -> Result<Option<String>, ShellParseError> {
514    match redirect {
515        IoRedirect::HereDocument(_, document) => Ok(Some(document.doc.value.clone())),
516        IoRedirect::HereString(_, operand) => word(operand, cx).map(Some),
517        IoRedirect::File(..) | IoRedirect::OutputAndError(..) => Ok(None),
518    }
519}
520
521fn assignment_value(assignment: &Assignment, cx: Cx<'_>) -> Result<(), ShellParseError> {
522    match &assignment.value {
523        AssignmentValue::Scalar(value) => word(value, cx).map(drop),
524        AssignmentValue::Array(values) => {
525            for (key, value) in values {
526                if let Some(key) = key {
527                    word(key, cx)?;
528                }
529                word(value, cx)?;
530            }
531            Ok(())
532        }
533    }
534}
535
536fn io_redirect(redirect: &IoRedirect, cx: Cx<'_>) -> Result<(), ShellParseError> {
537    match redirect {
538        IoRedirect::File(_, _, target) => match target {
539            IoFileRedirectTarget::Filename(target) | IoFileRedirectTarget::Duplicate(target) => {
540                word(target, cx).map(drop)
541            }
542            IoFileRedirectTarget::Fd(_) => Ok(()),
543            IoFileRedirectTarget::ProcessSubstitution(_, subshell) => {
544                compound_list(&subshell.list, cx)
545            }
546        },
547        IoRedirect::HereDocument(_, document) => {
548            if document.requires_expansion {
549                // A here-document body is free text; one that is not a valid
550                // word cannot hold a substitution worth following, so the
551                // commands found before the parse failed are all it has.
552                let _ = text(&document.doc.value, cx);
553            }
554            Ok(())
555        }
556        IoRedirect::HereString(_, operand) | IoRedirect::OutputAndError(operand, _) => {
557            word(operand, cx).map(drop)
558        }
559    }
560}
561
562/// Follows the substitutions inside `word` and returns its text with quotes
563/// removed. A part computed at run time contributes nothing to the text.
564fn word(word: &ast::Word, cx: Cx<'_>) -> Result<String, ShellParseError> {
565    text(&word.value, cx)
566}
567
568fn text(source: &str, cx: Cx<'_>) -> Result<String, ShellParseError> {
569    let pieces = brush_parser::word::parse(source, &ParserOptions::default())
570        .map_err(ShellParseError::new)?;
571    let mut literal = String::new();
572    pieces_text(&pieces, &mut literal, cx)?;
573    Ok(literal)
574}
575
576fn pieces_text(
577    pieces: &[WordPieceWithSource],
578    literal: &mut String,
579    cx: Cx<'_>,
580) -> Result<(), ShellParseError> {
581    for WordPieceWithSource { piece, .. } in pieces {
582        match piece {
583            WordPiece::Text(part)
584            | WordPiece::SingleQuotedText(part)
585            | WordPiece::AnsiCQuotedText(part) => literal.push_str(part),
586            WordPiece::EscapeSequence(part) => {
587                literal.push_str(part.strip_prefix('\\').unwrap_or(part));
588            }
589            WordPiece::DoubleQuotedSequence(inner)
590            | WordPiece::GettextDoubleQuotedSequence(inner) => {
591                pieces_text(inner, literal, cx)?;
592            }
593            WordPiece::TildePrefix(_) => {}
594            WordPiece::CommandSubstitution(inner)
595            | WordPiece::BackquotedCommandSubstitution(inner) => script_walk(inner, cx.deeper())?,
596            WordPiece::ArithmeticExpression(expr) => {
597                text(&expr.value, cx.deeper())?;
598            }
599            WordPiece::ParameterExpansion(expansion) => parameter_text(expansion, cx)?,
600        }
601    }
602    Ok(())
603}
604
605/// Follows the words a parameter expansion carries (`${x:-$(cmd)}`).
606fn parameter_text(expansion: &ParameterExpr, cx: Cx<'_>) -> Result<(), ShellParseError> {
607    let embedded: [Option<&str>; 2] = match expansion {
608        ParameterExpr::UseDefaultValues { default_value, .. }
609        | ParameterExpr::AssignDefaultValues { default_value, .. } => {
610            [default_value.as_deref(), None]
611        }
612        ParameterExpr::IndicateErrorIfNullOrUnset { error_message, .. } => {
613            [error_message.as_deref(), None]
614        }
615        ParameterExpr::UseAlternativeValue {
616            alternative_value, ..
617        } => [alternative_value.as_deref(), None],
618        ParameterExpr::RemoveSmallestSuffixPattern { pattern, .. }
619        | ParameterExpr::RemoveLargestSuffixPattern { pattern, .. }
620        | ParameterExpr::RemoveSmallestPrefixPattern { pattern, .. }
621        | ParameterExpr::RemoveLargestPrefixPattern { pattern, .. }
622        | ParameterExpr::UppercaseFirstChar { pattern, .. }
623        | ParameterExpr::UppercasePattern { pattern, .. }
624        | ParameterExpr::LowercaseFirstChar { pattern, .. }
625        | ParameterExpr::LowercasePattern { pattern, .. } => [pattern.as_deref(), None],
626        ParameterExpr::Substring { offset, length, .. } => [
627            Some(&offset.value),
628            length.as_ref().map(|expr| &*expr.value),
629        ],
630        ParameterExpr::ReplaceSubstring {
631            pattern,
632            replacement,
633            ..
634        } => [Some(pattern), replacement.as_deref()],
635        ParameterExpr::Parameter { .. }
636        | ParameterExpr::ParameterLength { .. }
637        | ParameterExpr::Transform { .. }
638        | ParameterExpr::VariableNames { .. }
639        | ParameterExpr::MemberKeys { .. } => [None, None],
640    };
641    for source in embedded.into_iter().flatten() {
642        text(source, cx.deeper())?;
643    }
644    Ok(())
645}
646
647/// Lower-cased file name of `program` without a Windows executable suffix.
648fn file_name(program: &str) -> String {
649    let name = program.rsplit(['/', '\\']).next().unwrap_or(program);
650    let mut name = name.to_ascii_lowercase();
651    if let Some(extension_at) = name.len().checked_sub(".exe".len())
652        && name.is_char_boundary(extension_at)
653        && name[extension_at..] == *".exe"
654    {
655        name.truncate(extension_at);
656    }
657    name
658}
659
660/// Records one resolved command line and follows what it runs: the command
661/// a wrapper runs, `find -exec` commands, and the scripts of `eval` and of
662/// shells.
663fn invoked(invocation: &Invocation<'_>, cx: Cx<'_>) -> Result<(), ShellParseError> {
664    let Some((program, arguments)) = invocation.argv.split_first() else {
665        return Ok(());
666    };
667    let name = file_name(program);
668    let id = {
669        let mut commands = cx.walk.commands.borrow_mut();
670        let id = CommandId(commands.len());
671        commands.push(ShellCommand {
672            id,
673            argv: invocation.argv.to_vec(),
674            program: name.clone(),
675            background: cx.backgrounded,
676            line: invocation.line,
677            wrapper: invocation.wrapper,
678            interpreter: cx.interpreter,
679            substituted_into: cx.substituted_into,
680            pipeline: invocation.pipeline,
681        });
682        id
683    };
684    if let Some(inner) = wrapped(&name, arguments) {
685        invoked(&invocation.wrapped(inner, id), cx)?;
686    }
687    if name == "find" {
688        for inner in find_exec_commands(arguments) {
689            invoked(
690                &Invocation {
691                    stdin_scripts: &[],
692                    ..invocation.wrapped(inner, id)
693                },
694                cx,
695            )?;
696        }
697    }
698    let interpreted = Cx {
699        interpreter: Some(id),
700        ..cx.deeper()
701    };
702    if name == "eval" && !arguments.is_empty() {
703        script_walk(&arguments.join(" "), interpreted)?;
704    }
705    if is_shell(&name) {
706        match shell_script(arguments) {
707            ShellInput::Script(script) => script_walk(script, interpreted)?,
708            ShellInput::Stdin => {
709                for script in invocation.stdin_scripts {
710                    script_walk(script, interpreted)?;
711                }
712            }
713            ShellInput::File => {}
714        }
715    }
716    Ok(())
717}
718
719fn is_shell(name: &str) -> bool {
720    matches!(name, "sh" | "bash" | "dash" | "ash" | "ksh" | "zsh" | "su")
721}
722
723/// Where a shell takes its commands from.
724enum ShellInput<'a> {
725    /// A string given with `-c` (or `su -c`).
726    Script(&'a str),
727    /// Standard input.
728    Stdin,
729    /// A script file.
730    File,
731}
732
733fn shell_script(arguments: &[String]) -> ShellInput<'_> {
734    let mut remaining = arguments.iter();
735    let mut reads_stdin = false;
736    let mut script_file = false;
737    while let Some(argument) = remaining.next() {
738        if argument == "--command" {
739            return remaining
740                .next()
741                .map_or(ShellInput::Stdin, |script| ShellInput::Script(script));
742        }
743        if let Some(flags) = argument
744            .strip_prefix(['-', '+'])
745            .filter(|f| !f.starts_with('-'))
746        {
747            if argument.starts_with('-') && flags.contains('c') {
748                return remaining
749                    .next()
750                    .map_or(ShellInput::Stdin, |script| ShellInput::Script(script));
751            }
752            reads_stdin |= flags.contains('s');
753            if flags.ends_with(['o', 'O']) {
754                remaining.next();
755            }
756        } else if argument != "--" {
757            script_file = true;
758            break;
759        }
760    }
761    if script_file && !reads_stdin {
762        ShellInput::File
763    } else {
764        ShellInput::Stdin
765    }
766}
767
768/// How a command wrapper takes its own options before the command it runs.
769struct WrapperSyntax {
770    /// Short options that take a value.
771    short_values: &'static str,
772    /// Long options that take a value when it is not joined with `=`.
773    long_values: &'static [&'static str],
774    /// Positional arguments before the command.
775    positionals: usize,
776    /// Whether leading `NAME=value` words belong to the wrapper.
777    assignments: bool,
778}
779
780const fn wrapper(
781    short_values: &'static str,
782    long_values: &'static [&'static str],
783    positionals: usize,
784    assignments: bool,
785) -> WrapperSyntax {
786    WrapperSyntax {
787        short_values,
788        long_values,
789        positionals,
790        assignments,
791    }
792}
793
794/// What a command wrapper runs, or `None` when `name` is not a wrapper or
795/// runs nothing (`command -v pkill` only looks the name up).
796fn wrapped<'a>(name: &str, arguments: &'a [String]) -> Option<&'a [String]> {
797    let syntax = match name {
798        "env" => wrapper("uC", &["unset", "chdir"], 0, true),
799        "sudo" => wrapper(
800            "ughpCDRTU",
801            &["user", "group", "host", "prompt", "chdir", "chroot"],
802            0,
803            true,
804        ),
805        "doas" => wrapper("uC", &[], 0, true),
806        "nice" => wrapper("n", &["adjustment"], 0, false),
807        "ionice" => wrapper("cnp", &["class", "classdata", "pid"], 0, false),
808        "stdbuf" => wrapper("ioe", &["input", "output", "error"], 0, false),
809        "timeout" => wrapper("sk", &["signal", "kill-after"], 1, false),
810        "time" => wrapper("fo", &["format", "output"], 0, false),
811        "xargs" => wrapper(
812            "IinPLsdEa",
813            &[
814                "replace",
815                "max-args",
816                "max-procs",
817                "max-lines",
818                "max-chars",
819                "delimiter",
820                "eof",
821                "arg-file",
822            ],
823            0,
824            false,
825        ),
826        "exec" => wrapper("a", &[], 0, false),
827        "command" => {
828            if arguments
829                .iter()
830                .any(|argument| argument == "-v" || argument == "-V")
831            {
832                return None;
833            }
834            wrapper("", &[], 0, false)
835        }
836        "builtin" | "nohup" | "setsid" | "busybox" | "toybox" => wrapper("", &[], 0, false),
837        _ => return None,
838    };
839    let mut index = 0;
840    while let Some(argument) = arguments.get(index) {
841        index += 1;
842        if argument == "--" {
843            break;
844        }
845        if let Some(long) = argument.strip_prefix("--") {
846            if !long.contains('=') && syntax.long_values.contains(&long) {
847                index += 1;
848            }
849        } else if let Some(flags) = argument.strip_prefix('-').filter(|flags| !flags.is_empty()) {
850            // getopt: the first value option takes the rest of the cluster,
851            // or the next word when nothing follows it.
852            let value_at = flags
853                .char_indices()
854                .find(|(_, letter)| syntax.short_values.contains(*letter));
855            if let Some((at, letter)) = value_at
856                && at + letter.len_utf8() == flags.len()
857            {
858                index += 1;
859            }
860        } else if syntax.assignments && argument.contains('=') {
861        } else {
862            index -= 1;
863            break;
864        }
865    }
866    index += syntax.positionals;
867    arguments.get(index..).filter(|inner| !inner.is_empty())
868}
869
870/// The command lines `find` runs through `-exec`, `-execdir`, `-ok` and
871/// `-okdir`, each ending at a lone `;` or `+`.
872fn find_exec_commands(arguments: &[String]) -> Vec<&[String]> {
873    let mut commands = Vec::new();
874    let mut index = 0;
875    while index < arguments.len() {
876        if matches!(
877            arguments[index].as_str(),
878            "-exec" | "-execdir" | "-ok" | "-okdir"
879        ) {
880            let start = index + 1;
881            let end = arguments[start..]
882                .iter()
883                .position(|argument| argument == ";" || argument == "+")
884                .map_or(arguments.len(), |offset| start + offset);
885            commands.push(&arguments[start..end]);
886            index = end;
887        }
888        index += 1;
889    }
890    commands
891}
892
893#[cfg(test)]
894#[path = "shell_syntax/tests.rs"]
895mod tests;