use std::collections::BTreeMap;
use std::io::Cursor;
use brush_parser::ast;
use brush_parser::ast::{
CaseClauseCommand, CaseItemPostAction, Command, CompoundCommand, IoFileRedirectKind,
IoFileRedirectTarget, IoRedirect,
};
use brush_parser::{Parser, ParserOptions, SourceInfo};
use engine::{BytesInput, BytesOutput, Input, Output, Pipe, Terminal, VirtualPath};
use crate::HISTORY_LIMIT;
const MAX_CALL_DEPTH: usize = 200;
use os::runtime::{
CommandResolution, CommandRuntime, Executable, ExitStatus, Launcher, ResolvedExecutable,
};
use os::unix::unix_os::UnixOs;
use os::{Credentials, Environment};
pub type BuiltinRunner = fn(
&mut ShellCore,
&str,
&[String],
&mut dyn Input,
&mut dyn Output,
&mut dyn Output,
) -> Option<ExitStatus>;
pub struct ShellDialect {
pub name: &'static str,
pub command_not_found: fn(&str) -> String,
pub run_builtin: BuiltinRunner,
pub system_rc: &'static str,
pub user_rc: &'static str,
pub echo_escapes_default: bool,
pub export_prefix: &'static str,
pub alias_prefix: &'static str,
}
pub struct NameResolution {
pub alias: Option<String>,
pub function: bool,
pub builtin: bool,
pub paths: Vec<String>,
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn run_interpreter_invocation(
os: &UnixOs,
credentials: Credentials,
dialect: ShellDialect,
cwd: &VirtualPath,
argv: &[String],
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> Result<ExitStatus, os::OsError> {
let mut shell = ShellCore::new(os, credentials, dialect)?;
shell.set_cwd(cwd.clone());
Ok(shell.run_script_invocation(argv, stdin, stdout, stderr))
}
pub(crate) fn interpret_escapes(text: &str) -> String {
let mut out = String::new();
let chars: Vec<char> = text.chars().collect();
let mut index = 0usize;
while index < chars.len() {
if chars[index] != '\\' || index + 1 >= chars.len() {
out.push(chars[index]);
index += 1;
continue;
}
let escaped = chars[index + 1];
index += 2;
match escaped {
'a' => out.push('\u{7}'),
'b' => out.push('\u{8}'),
'c' => break,
'e' => out.push('\u{1b}'),
'f' => out.push('\u{c}'),
'n' => out.push('\n'),
'r' => out.push('\r'),
't' => out.push('\t'),
'v' => out.push('\u{b}'),
'\\' => out.push('\\'),
'0'..='7' => {
let mut octal = String::from(escaped);
while index < chars.len() && octal.len() < 3 && ('0'..='7').contains(&chars[index])
{
octal.push(chars[index]);
index += 1;
}
if let Ok(value) = u8::from_str_radix(&octal, 8) {
out.push(value as char);
}
}
other => {
out.push('\\');
out.push(other);
}
}
}
out
}
struct PositionalFrame {
name: String,
args: Vec<String>,
}
pub struct ShellCore<'os> {
os: &'os UnixOs,
credentials: Credentials,
cwd: VirtualPath,
environment: Environment,
runtime: CommandRuntime<'os>,
history: Vec<String>,
aliases: BTreeMap<String, String>,
functions: BTreeMap<String, String>,
hash: BTreeMap<String, engine::ObjectId>,
loop_break: bool,
loop_continue: bool,
exit_request: Option<ExitStatus>,
positionals: Vec<PositionalFrame>,
dir_stack: Vec<VirtualPath>,
previous_cwd: Option<VirtualPath>,
expanding_aliases: Vec<String>,
call_depth: usize,
dialect: ShellDialect,
interpreter_objects: Vec<engine::ObjectId>,
}
impl<'os> ShellCore<'os> {
pub fn new(
os: &'os UnixOs,
credentials: Credentials,
dialect: ShellDialect,
) -> Result<Self, os::OsError> {
let environment = os.environment_for(&credentials);
let cwd = credentials
.user()
.home()
.parse::<VirtualPath>()
.unwrap_or_else(|_| VirtualPath::root());
let runtime = CommandRuntime::new(os)?;
let mut environment = environment;
environment.set("?", "0");
Ok(Self {
os,
credentials,
cwd,
environment,
runtime,
history: Vec::new(),
aliases: BTreeMap::new(),
functions: BTreeMap::new(),
hash: BTreeMap::new(),
loop_break: false,
loop_continue: false,
exit_request: None,
positionals: Vec::new(),
dir_stack: Vec::new(),
previous_cwd: None,
expanding_aliases: Vec::new(),
call_depth: 0,
dialect,
interpreter_objects: Vec::new(),
})
}
pub fn cwd(&self) -> &VirtualPath {
&self.cwd
}
pub fn set_cwd(&mut self, cwd: VirtualPath) {
self.cwd = cwd;
}
pub fn environment(&self) -> &Environment {
&self.environment
}
pub fn environment_mut(&mut self) -> &mut Environment {
&mut self.environment
}
pub fn credentials(&self) -> &Credentials {
&self.credentials
}
pub fn os(&self) -> &'os UnixOs {
self.os
}
pub fn history(&self) -> &[String] {
&self.history
}
pub fn record_history(&mut self, line: &str) {
if line.trim().is_empty() {
return;
}
self.history.push(line.to_owned());
if self.history.len() > HISTORY_LIMIT {
self.history.remove(0);
}
}
pub fn aliases(&self) -> &BTreeMap<String, String> {
&self.aliases
}
pub fn aliases_mut(&mut self) -> &mut BTreeMap<String, String> {
&mut self.aliases
}
pub fn functions_mut(&mut self) -> &mut BTreeMap<String, String> {
&mut self.functions
}
pub fn set_terminal_size(&mut self, rows: u16, cols: u16) {
self.environment.set("COLUMNS", cols.to_string());
self.environment.set("LINES", rows.to_string());
}
pub fn source_startup_files(&mut self) {
let mut paths: Vec<String> = Vec::new();
if !self.dialect.system_rc.is_empty() {
paths.push(self.dialect.system_rc.to_owned());
}
if !self.dialect.user_rc.is_empty()
&& let Some(home) = self.environment.get("HOME")
{
let user_rc = format!("{home}/{}", self.dialect.user_rc);
paths.push(user_rc);
}
let actor = Some(self.credentials.actor());
let engine = self.os.engine();
for path in paths {
let Ok(path) = path.parse::<engine::VirtualPath>() else {
continue;
};
let Some(object) = engine.lookup(actor, &path).ok() else {
continue;
};
let Some(bytes) = engine.read(actor, object).ok().flatten() else {
continue;
};
let source = String::from_utf8_lossy(&bytes).into_owned();
let mut stdin = engine::BytesInput::new(Vec::new());
let mut stdout = engine::BytesOutput::new();
let mut stderr = engine::BytesOutput::new();
let _ = self.execute(&source, &mut stdin, &mut stdout, &mut stderr);
}
}
pub fn install_shell_bindings(&mut self) {
let actor = Some(self.credentials.actor());
let interpreters: Vec<(&str, std::sync::Arc<dyn os::runtime::Command>)> = vec![
("/bin/sh", std::sync::Arc::new(crate::bash::BashInterpreter)),
(
"/bin/bash",
std::sync::Arc::new(crate::bash::BashInterpreter),
),
("/bin/zsh", std::sync::Arc::new(crate::zsh::ZshInterpreter)),
];
for (path, interpreter) in interpreters {
let Ok(path) = path.parse::<engine::VirtualPath>() else {
continue;
};
if let Ok(object) = self.os.engine().lookup(actor, &path) {
self.runtime.register(object, interpreter);
self.interpreter_objects.push(object);
}
}
}
pub fn execute(
&mut self,
line: &str,
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
self.execute_with_terminal(line, stdin, stdout, stderr, None)
}
pub fn execute_with_terminal(
&mut self,
line: &str,
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
terminal: Option<&mut dyn Terminal>,
) -> ExitStatus {
let (status, _terminal) =
self.execute_with_terminal_returning(line, stdin, stdout, stderr, terminal);
status
}
fn execute_with_terminal_returning<'t>(
&mut self,
line: &str,
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
terminal: Option<&'t mut dyn Terminal>,
) -> (ExitStatus, Option<&'t mut dyn Terminal>) {
if self.call_depth >= MAX_CALL_DEPTH {
let _ = stderr.write(b"vce: maximum recursion depth exceeded\n");
return (ExitStatus::FAILURE, terminal);
}
self.call_depth += 1;
let (status, terminal) = self.execute_at_depth(line, stdin, stdout, stderr, terminal);
self.call_depth -= 1;
(status, terminal)
}
fn execute_at_depth<'t>(
&mut self,
line: &str,
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
mut terminal: Option<&'t mut dyn Terminal>,
) -> (ExitStatus, Option<&'t mut dyn Terminal>) {
let line = line.trim();
if line.is_empty() {
return (ExitStatus::SUCCESS, terminal);
}
let program = match parse_program(line) {
Ok(program) => program,
Err(error) => {
let _ = stderr
.write(format!("{}: syntax error: {error}\n", self.dialect.name).as_bytes());
return (ExitStatus::USAGE, terminal);
}
};
let mut last_status = ExitStatus::SUCCESS;
'commands: for complete_command in program.complete_commands {
for item in complete_command.0 {
let background = matches!(item.1, ast::SeparatorOperator::Async);
let (status, returned) = self.execute_and_or_list(
&item.0,
stdin,
stdout,
stderr,
terminal.take(),
background,
);
terminal = returned;
last_status = status;
self.environment.set("?", last_status.code().to_string());
if self.exit_request.is_some() {
break 'commands;
}
}
}
(last_status, terminal)
}
pub(crate) fn positional_value(&self, key: &str) -> Option<String> {
let frame = self.positionals.last()?;
match key {
"0" => Some(frame.name.clone()),
"#" => Some(frame.args.len().to_string()),
"@" | "*" => Some(frame.args.join(" ")),
_ => key
.parse::<usize>()
.ok()
.and_then(|index| index.checked_sub(1))
.and_then(|index| frame.args.get(index).cloned()),
}
}
pub fn request_exit(&mut self, status_argument: Option<&str>) -> ExitStatus {
let code = status_argument
.and_then(|argument| argument.trim().parse::<i64>().ok())
.map_or(0, |value| u8::try_from(value & 0xFF).unwrap_or(0));
let status = ExitStatus::new(code);
self.exit_request = Some(status);
status
}
pub fn take_exit_request(&mut self) -> Option<ExitStatus> {
self.exit_request.take()
}
fn execute_and_or_list<'t>(
&mut self,
list: &ast::AndOrList,
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
terminal: Option<&'t mut dyn Terminal>,
background: bool,
) -> (ExitStatus, Option<&'t mut dyn Terminal>) {
let (mut status, mut terminal) =
self.execute_pipeline(&list.first, stdin, stdout, stderr, terminal, background);
for additional in &list.additional {
let (pipeline, should_run) = match additional {
ast::AndOr::And(pipeline) => (pipeline, status.is_success()),
ast::AndOr::Or(pipeline) => (pipeline, !status.is_success()),
};
if should_run {
(status, terminal) =
self.execute_pipeline(pipeline, stdin, stdout, stderr, terminal, background);
}
}
(status, terminal)
}
fn execute_pipeline<'t>(
&mut self,
pipeline: &ast::Pipeline,
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
terminal: Option<&'t mut dyn Terminal>,
background: bool,
) -> (ExitStatus, Option<&'t mut dyn Terminal>) {
let mut status = ExitStatus::SUCCESS;
let mut terminal = terminal;
if pipeline.seq.len() == 1 {
(status, terminal) = self.execute_command(
&pipeline.seq[0],
stdin,
stdout,
stderr,
terminal,
background,
);
} else {
let pipes: Vec<Pipe> = (0..pipeline.seq.len() - 1).map(|_| Pipe::new()).collect();
for (index, command) in pipeline.seq.iter().enumerate() {
let is_first = index == 0;
let is_last = index == pipeline.seq.len() - 1;
let stage_term = if is_last { terminal.take() } else { None };
let (stage_status, returned_terminal) = if is_first && !is_last {
let mut pipe_out = pipes[0].output();
self.execute_command(command, stdin, &mut pipe_out, stderr, None, false)
} else if is_last {
let mut pipe_in = pipes[index - 1].input();
self.execute_command(
command,
&mut pipe_in,
stdout,
stderr,
stage_term,
background,
)
} else {
let mut pipe_in = pipes[index - 1].input();
let mut pipe_out = pipes[index].output();
self.execute_command(command, &mut pipe_in, &mut pipe_out, stderr, None, false)
};
if is_last {
terminal = returned_terminal;
}
status = stage_status;
}
}
if pipeline.bang {
status = status.negated();
}
(status, terminal)
}
fn execute_command<'t>(
&mut self,
command: &Command,
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
terminal: Option<&'t mut dyn Terminal>,
background: bool,
) -> (ExitStatus, Option<&'t mut dyn Terminal>) {
match command {
Command::Simple(simple) => {
self.execute_simple(simple, stdin, stdout, stderr, terminal, background)
}
Command::Compound(compound, redirects) => self.execute_compound(
compound,
redirects.as_ref(),
stdin,
stdout,
stderr,
terminal,
background,
),
Command::Function(function) => {
self.functions
.insert(function.fname.clone(), function.body.0.to_string());
(ExitStatus::SUCCESS, terminal)
}
Command::ExtendedTest(expr) => {
let truth = self.evaluate_extended_test(expr);
(
if truth {
ExitStatus::SUCCESS
} else {
ExitStatus::FAILURE
},
terminal,
)
}
}
}
fn evaluate_extended_test(&mut self, expr: &ast::ExtendedTestExpr) -> bool {
use brush_parser::ast::{
BinaryPredicate as Bp, ExtendedTestExpr as E, UnaryPredicate as Up,
};
match expr {
E::And(left, right) => {
self.evaluate_extended_test(left) && self.evaluate_extended_test(right)
}
E::Or(left, right) => {
self.evaluate_extended_test(left) || self.evaluate_extended_test(right)
}
E::Not(inner) => !self.evaluate_extended_test(inner),
E::Parenthesized(inner) => self.evaluate_extended_test(inner),
E::UnaryTest(predicate, word) => {
let value = self.expand_word(&word.value);
match predicate {
Up::StringHasZeroLength => value.is_empty(),
Up::StringHasNonZeroLength => !value.is_empty(),
Up::ShellVariableIsSetAndAssigned => self.environment.get(&value).is_some(),
Up::FileExists => self.path_exists(&value),
Up::FileExistsAndIsDir => self
.resolve_path(&value)
.is_ok_and(|path| self.is_directory(&path)),
Up::FileExistsAndIsRegularFile => self.resolve_path(&value).is_ok_and(|path| {
self.os
.engine()
.lookup(Some(self.credentials.actor()), &path)
.is_ok_and(|object| {
self.os
.engine()
.read(Some(self.credentials.actor()), object)
.is_ok()
})
}),
Up::FileExistsAndIsReadable => self.resolve_path(&value).is_ok_and(|path| {
self.os
.engine()
.lookup(Some(self.credentials.actor()), &path)
.is_ok_and(|object| {
self.os
.engine()
.check(
Some(self.credentials.actor()),
engine::Operation::Read,
object,
)
.is_ok()
})
}),
Up::FileExistsAndIsWritable => self.resolve_path(&value).is_ok_and(|path| {
self.os
.engine()
.lookup(Some(self.credentials.actor()), &path)
.is_ok_and(|object| {
self.os
.engine()
.check(
Some(self.credentials.actor()),
engine::Operation::Write,
object,
)
.is_ok()
})
}),
Up::FileExistsAndIsExecutable => self
.resolve_path(&value)
.is_ok_and(|path| self.executable_path(&path).is_some()),
Up::FileExistsAndIsNotZeroLength => {
self.resolve_path(&value).is_ok_and(|path| {
self.os
.engine()
.lookup(Some(self.credentials.actor()), &path)
.is_ok_and(|object| {
self.os
.engine()
.size(Some(self.credentials.actor()), object)
.is_ok_and(|size| size > 0)
})
})
}
_ => false,
}
}
E::BinaryTest(predicate, left, right) => {
let left = self.expand_word(&left.value);
let right = self.expand_word(&right.value);
match predicate {
Bp::StringExactlyMatchesString => left == right,
Bp::StringDoesNotExactlyMatchString => left != right,
Bp::StringContainsSubstring => left.contains(&right),
Bp::LeftSortsBeforeRight => left < right,
Bp::LeftSortsAfterRight => left > right,
Bp::StringExactlyMatchesPattern => crate::expansion::glob_match(&left, &right),
Bp::StringDoesNotExactlyMatchPattern => {
!crate::expansion::glob_match(&left, &right)
}
Bp::ArithmeticEqualTo => {
self.arithmetic_operand(&left) == self.arithmetic_operand(&right)
}
Bp::ArithmeticNotEqualTo => {
self.arithmetic_operand(&left) != self.arithmetic_operand(&right)
}
Bp::ArithmeticLessThan => {
self.arithmetic_operand(&left) < self.arithmetic_operand(&right)
}
Bp::ArithmeticLessThanOrEqualTo => {
self.arithmetic_operand(&left) <= self.arithmetic_operand(&right)
}
Bp::ArithmeticGreaterThan => {
self.arithmetic_operand(&left) > self.arithmetic_operand(&right)
}
Bp::ArithmeticGreaterThanOrEqualTo => {
self.arithmetic_operand(&left) >= self.arithmetic_operand(&right)
}
_ => false,
}
}
}
}
fn path_exists(&self, value: &str) -> bool {
self.resolve_path(value).is_ok_and(|path| {
self.os
.engine()
.lookup(Some(self.credentials.actor()), &path)
.is_ok()
})
}
fn arithmetic_operand(&mut self, value: &str) -> i64 {
self.evaluate_arithmetic(value.trim()).unwrap_or(0)
}
#[allow(clippy::too_many_arguments)]
fn execute_compound<'t>(
&mut self,
compound: &CompoundCommand,
redirects: Option<&ast::RedirectList>,
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
terminal: Option<&'t mut dyn Terminal>,
background: bool,
) -> (ExitStatus, Option<&'t mut dyn Terminal>) {
let stdout_redirect = compound_stdout_redirect(redirects);
let mut captured = BytesOutput::new();
let effective_stdout: &mut dyn Output = if stdout_redirect.is_some() {
&mut captured
} else {
stdout
};
let (status, terminal) = match compound {
CompoundCommand::BraceGroup(group) => self.execute_compound_list(
&group.0,
stdin,
effective_stdout,
stderr,
terminal,
background,
),
CompoundCommand::IfClause(ifc) => {
let (condition_status, terminal) = self.execute_compound_list(
&ifc.condition,
stdin,
effective_stdout,
stderr,
terminal,
false,
);
if condition_status.is_success() {
self.execute_compound_list(
&ifc.then,
stdin,
effective_stdout,
stderr,
terminal,
background,
)
} else if let Some(elses) = &ifc.elses {
let mut terminal = terminal;
for else_clause in elses {
match &else_clause.condition {
Some(condition) => {
let (elif_status, returned) = self.execute_compound_list(
condition,
stdin,
effective_stdout,
stderr,
terminal.take(),
false,
);
terminal = returned;
if elif_status.is_success() {
return self.execute_compound_list(
&else_clause.body,
stdin,
effective_stdout,
stderr,
terminal.take(),
background,
);
}
}
None => {
return self.execute_compound_list(
&else_clause.body,
stdin,
effective_stdout,
stderr,
terminal.take(),
background,
);
}
}
}
(ExitStatus::SUCCESS, terminal)
} else {
(ExitStatus::SUCCESS, terminal)
}
}
CompoundCommand::WhileClause(clause) => self.execute_loop(
&clause.0,
&clause.1.0,
false,
stdin,
effective_stdout,
stderr,
terminal,
background,
),
CompoundCommand::UntilClause(clause) => self.execute_loop(
&clause.0,
&clause.1.0,
true,
stdin,
effective_stdout,
stderr,
terminal,
background,
),
CompoundCommand::ForClause(clause) => {
let mut last_status = ExitStatus::SUCCESS;
let mut terminal = terminal;
self.loop_break = false;
self.loop_continue = false;
let values: Vec<String> = match &clause.values {
Some(words) => words
.iter()
.map(|word| self.expand_word(&word.value))
.collect(),
None => Vec::new(),
};
for value in values {
self.environment.set(&clause.variable_name, value);
let (body_status, returned) = self.execute_compound_list(
&clause.body.0,
stdin,
stdout,
stderr,
terminal.take(),
background,
);
terminal = returned;
last_status = body_status;
self.environment.set("?", last_status.code().to_string());
if self.loop_break {
self.loop_break = false;
break;
}
if self.loop_continue {
self.loop_continue = false;
continue;
}
}
(last_status, terminal)
}
CompoundCommand::Subshell(subshell) => {
let saved_environment = self.environment.clone();
let saved_cwd = self.cwd.clone();
let saved_exit_request = self.exit_request;
let (status, terminal) = self.execute_compound_list(
&subshell.0,
stdin,
effective_stdout,
stderr,
terminal,
background,
);
self.environment = saved_environment;
self.cwd = saved_cwd;
self.exit_request = saved_exit_request;
(status, terminal)
}
CompoundCommand::CaseClause(clause) => self.execute_case_clause(
clause,
stdin,
effective_stdout,
stderr,
terminal,
background,
),
CompoundCommand::Arithmetic(command) => {
let prepared =
if command.expr.value.contains('$') || command.expr.value.contains('`') {
self.expand_word(&command.expr.value)
} else {
command.expr.value.clone()
};
match self.evaluate_arithmetic(&prepared) {
Some(value) if value != 0 => (ExitStatus::SUCCESS, terminal),
Some(_) => (ExitStatus::FAILURE, terminal),
None => {
let _ = stderr.write(
format!(
"{}: invalid arithmetic expression: {}\n",
self.dialect.name, command.expr.value
)
.as_bytes(),
);
(ExitStatus::USAGE, terminal)
}
}
}
_ => {
let _ = stderr.write(
format!(
"{}: this construct is not supported by this shell\n",
self.dialect.name
)
.as_bytes(),
);
(ExitStatus::USAGE, terminal)
}
};
if let Some((path, append)) = stdout_redirect
&& let Err(error) = self.write_redirect(&path, &captured.into_bytes(), append)
{
let _ = stderr.write(format!("{}: {error}\n", self.dialect.name).as_bytes());
return (ExitStatus::FAILURE, terminal);
}
(status, terminal)
}
#[allow(clippy::too_many_arguments)]
fn execute_loop<'t>(
&mut self,
condition: &ast::CompoundList,
body: &ast::CompoundList,
until: bool,
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
terminal: Option<&'t mut dyn Terminal>,
background: bool,
) -> (ExitStatus, Option<&'t mut dyn Terminal>) {
let mut last_status = ExitStatus::SUCCESS;
let mut terminal = terminal;
self.loop_break = false;
self.loop_continue = false;
loop {
let (condition_status, returned) = self.execute_compound_list(
condition,
stdin,
stdout,
stderr,
terminal.take(),
false,
);
terminal = returned;
let should_run = if until {
!condition_status.is_success()
} else {
condition_status.is_success()
};
if !should_run {
break;
}
(last_status, terminal) = self.execute_compound_list(
body,
stdin,
stdout,
stderr,
terminal.take(),
background,
);
self.environment.set("?", last_status.code().to_string());
if self.loop_break {
self.loop_break = false;
break;
}
if self.loop_continue {
self.loop_continue = false;
continue;
}
}
(last_status, terminal)
}
fn execute_compound_list<'t>(
&mut self,
list: &ast::CompoundList,
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
terminal: Option<&'t mut dyn Terminal>,
background: bool,
) -> (ExitStatus, Option<&'t mut dyn Terminal>) {
let mut last_status = ExitStatus::SUCCESS;
let mut terminal = terminal;
for item in &list.0 {
let item_background = background || matches!(item.1, ast::SeparatorOperator::Async);
let (status, returned) = self.execute_and_or_list(
&item.0,
stdin,
stdout,
stderr,
terminal.take(),
item_background,
);
terminal = returned;
last_status = status;
if self.loop_break || self.loop_continue {
break;
}
}
(last_status, terminal)
}
fn execute_simple<'t>(
&mut self,
simple: &ast::SimpleCommand,
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
terminal: Option<&'t mut dyn Terminal>,
background: bool,
) -> (ExitStatus, Option<&'t mut dyn Terminal>) {
let mut argv: Vec<String> = Vec::new();
let mut globs: Vec<bool> = Vec::new();
let mut assignments: Vec<(String, String)> = Vec::new();
let mut stdin_redirect: Option<String> = None;
let mut stdout_redirect: Option<(String, bool)> = None;
let mut stderr_redirect: Option<(String, bool)> = None;
let mut stderr_to_stdout = false;
let mut stdout_to_stderr = false;
let collect = |item: &ast::CommandPrefixOrSuffixItem,
argv: &mut Vec<String>,
globs: &mut Vec<bool>,
assignments: &mut Vec<(String, String)>,
stdin_redirect: &mut Option<String>,
stdout_redirect: &mut Option<(String, bool)>,
stderr_redirect: &mut Option<(String, bool)>,
stderr_to_stdout: &mut bool,
stdout_to_stderr: &mut bool|
-> Result<(), String> {
match item {
ast::CommandPrefixOrSuffixItem::Word(word) => {
argv.push(word.value.clone());
globs.push(true);
}
ast::CommandPrefixOrSuffixItem::AssignmentWord(assignment, _word) => {
let value = match &assignment.value {
ast::AssignmentValue::Scalar(word) => word.value.clone(),
ast::AssignmentValue::Array(_) => {
return Err("array assignments are not supported".to_owned());
}
};
assignments.push((assignment.name.name_string(), value));
}
ast::CommandPrefixOrSuffixItem::IoRedirect(io) => match io {
IoRedirect::File(fd, kind, target) => {
match target {
IoFileRedirectTarget::Duplicate(duplicate) => {
let duplicate = duplicate.value.parse::<u32>().unwrap_or(u32::MAX);
match (fd, duplicate) {
(Some(2), 1) => *stderr_to_stdout = true,
(Some(1), 2) => *stdout_to_stderr = true,
(_, 0) => {
return Err("stdin duplication is not supported".to_owned());
}
_ => return Err("this redirection is not supported".to_owned()),
}
return Ok(());
}
IoFileRedirectTarget::Fd(_) => {
return Err("fd redirections are not supported".to_owned());
}
IoFileRedirectTarget::ProcessSubstitution(_, _) => {
return Err("process substitution is not supported".to_owned());
}
IoFileRedirectTarget::Filename(_) => {}
}
let filename = match target {
IoFileRedirectTarget::Filename(word) => word.value.clone(),
_ => unreachable!(),
};
match kind {
IoFileRedirectKind::Read if fd.is_none_or(|n| n == 0) => {
*stdin_redirect = Some(filename);
}
IoFileRedirectKind::Write if fd.is_none_or(|n| n == 1) => {
*stdout_redirect = Some((filename, false));
}
IoFileRedirectKind::Append if fd.is_none_or(|n| n == 1) => {
*stdout_redirect = Some((filename, true));
}
IoFileRedirectKind::Write if fd.is_some_and(|n| n == 2) => {
*stderr_redirect = Some((filename, false));
}
IoFileRedirectKind::Append if fd.is_some_and(|n| n == 2) => {
*stderr_redirect = Some((filename, true));
}
_ => return Err("this redirection is not supported".to_owned()),
}
}
IoRedirect::HereDocument(fd, here) => {
if fd.is_some_and(|n| n != 0) {
return Err("this redirection is not supported".to_owned());
}
let content = here.doc.value.clone();
let marker = if here.requires_expansion {
"\0heredoc-expand:"
} else {
"\0heredoc:"
};
*stdin_redirect = Some(format!("{marker}{content}\0"));
}
IoRedirect::HereString(fd, word) => {
if fd.is_some_and(|n| n != 0) {
return Err("this redirection is not supported".to_owned());
}
*stdin_redirect = Some(format!("\0herestring:{}\0", word.value));
}
IoRedirect::OutputAndError(target, append) => {
*stdout_redirect = Some((target.value.clone(), *append));
}
},
ast::CommandPrefixOrSuffixItem::ProcessSubstitution(_, _) => {
return Err("process substitution is not supported".to_owned());
}
}
Ok(())
};
let mut result = Ok(());
if let Some(prefix) = &simple.prefix {
for item in &prefix.0 {
if let Err(error) = collect(
item,
&mut argv,
&mut globs,
&mut assignments,
&mut stdin_redirect,
&mut stdout_redirect,
&mut stderr_redirect,
&mut stderr_to_stdout,
&mut stdout_to_stderr,
) {
result = Err(error);
break;
}
}
}
if result.is_ok()
&& let Some(name) = &simple.word_or_name
{
argv.push(name.value.clone());
globs.push(true);
}
if result.is_ok()
&& let Some(suffix) = &simple.suffix
{
for item in &suffix.0 {
if let ast::CommandPrefixOrSuffixItem::AssignmentWord(assignment, word) = item {
argv.push(format!(
"{}={}",
assignment.name.name_string(),
match &assignment.value {
ast::AssignmentValue::Scalar(w) => w.value.clone(),
ast::AssignmentValue::Array(_) => word.value.clone(),
}
));
globs.push(false);
continue;
}
if let Err(error) = collect(
item,
&mut argv,
&mut globs,
&mut assignments,
&mut stdin_redirect,
&mut stdout_redirect,
&mut stderr_redirect,
&mut stderr_to_stdout,
&mut stdout_to_stderr,
) {
result = Err(error);
break;
}
}
}
if let Err(error) = result {
let _ = stderr.write(format!("{}: {error}\n", self.dialect.name).as_bytes());
return (ExitStatus::USAGE, terminal);
}
if argv.is_empty() {
for (name, value) in assignments {
let expanded = self.expand_word(&value);
self.environment.set(name, expanded);
}
return (ExitStatus::SUCCESS, terminal);
}
let command_environment = if assignments.is_empty() {
None
} else {
let mut environment = self.environment.clone();
for (name, value) in &assignments {
let expanded = self.expand_word(value);
environment.set(name.clone(), expanded);
}
Some(environment)
};
let mut expanded_argv: Vec<String> = Vec::new();
let mut expanded_globs: Vec<bool> = Vec::new();
for (raw, glob) in argv.iter().zip(globs.iter()) {
let (expanded, contains_unquoted_glob) = self.expand_word_with_glob(raw);
expanded_argv.push(expanded);
expanded_globs.push(*glob && contains_unquoted_glob);
}
let mut final_argv: Vec<String> = Vec::new();
for (arg, glob) in expanded_argv.iter().zip(expanded_globs.iter()) {
if *glob {
final_argv.extend(self.expand_glob(arg));
} else {
final_argv.push(arg.clone());
}
}
if final_argv.is_empty() {
return (ExitStatus::SUCCESS, terminal);
}
let name = final_argv[0].clone();
if !self.expanding_aliases.contains(&name)
&& let Some(expansion) = self.aliases.get(&name).cloned()
{
let rest: Vec<String> = final_argv[1..]
.iter()
.map(|word| shell_quote(word))
.collect();
let line = if rest.is_empty() {
expansion
} else {
format!("{expansion} {}", rest.join(" "))
};
self.expanding_aliases.push(name);
return self.execute_with_terminal_returning(&line, stdin, stdout, stderr, terminal);
}
let mut input: Box<dyn Input> = Box::new(BytesInput::new(Vec::new()));
let mut input_is_redirected = false;
if let Some(input_path) = stdin_redirect {
if let Some(content) = heredoc_content(&input_path) {
let content = if heredoc_expands(&input_path) {
self.expand_word(&String::from_utf8_lossy(&content))
.into_bytes()
} else {
content
};
input = Box::new(BytesInput::new(content));
} else {
let expanded = self.expand_word(&input_path);
let path = match self.resolve_path(&expanded) {
Ok(path) => path,
Err(error) => {
let _ = stderr.write(format!("{error}\n").as_bytes());
return (ExitStatus::FAILURE, terminal);
}
};
let object = match self
.os
.engine()
.lookup(Some(self.credentials.actor()), &path)
{
Ok(object) => object,
Err(error) => {
let _ = stderr.write(format!("{}: {error}\n", final_argv[0]).as_bytes());
return (ExitStatus::FAILURE, terminal);
}
};
let content = match self
.os
.engine()
.read(Some(self.credentials.actor()), object)
{
Ok(Some(bytes)) => bytes,
Ok(None) => Vec::new(),
Err(error) => {
let _ = stderr.write(format!("{}: {error}\n", final_argv[0]).as_bytes());
return (ExitStatus::FAILURE, terminal);
}
};
input = Box::new(BytesInput::new(content));
}
input_is_redirected = true;
}
let effective_stdin: &mut dyn Input = if input_is_redirected {
input.as_mut()
} else {
stdin
};
let has_redirect = stdout_redirect.is_some();
let has_stderr_redirect = stderr_redirect.is_some();
let mut captured = BytesOutput::new();
let mut captured_stderr = BytesOutput::new();
let mut captured_stdout = BytesOutput::new();
let effective_stdout: &mut dyn Output = if stdout_to_stderr {
&mut captured_stdout
} else if has_redirect {
&mut captured
} else {
stdout
};
let effective_stderr: &mut dyn Output =
if stderr_to_stdout || has_stderr_redirect || stdout_to_stderr {
&mut captured_stderr
} else {
stderr
};
if name == "break" {
self.loop_break = true;
return (ExitStatus::SUCCESS, terminal);
}
if name == "continue" {
self.loop_continue = true;
return (ExitStatus::SUCCESS, terminal);
}
let mut builtin_argv = final_argv.clone();
if !assignments.is_empty() && matches!(name.as_str(), "export" | "typeset" | "declare") {
for (key, value) in &assignments {
builtin_argv.push(format!("{key}={value}"));
}
}
let (builtin_status, terminal) = self.try_builtin(
&name,
&builtin_argv,
effective_stdin,
effective_stdout,
effective_stderr,
terminal,
);
if let Some(status) = builtin_status {
if background {
self.runtime
.record_background_job(final_argv.join(" "), name.clone());
}
if stderr_to_stdout && stderr_redirect.is_none() {
let merged = captured_stderr.bytes().to_vec();
if has_redirect {
let _ = captured.write(&merged);
} else {
let _ = stdout.write(&merged);
}
}
if stdout_to_stderr {
let merged = captured_stdout.bytes().to_vec();
let _ = stderr.write(&merged);
}
if let Some((path_str, append)) = &stdout_redirect {
let expanded = self.expand_word(path_str);
let bytes = captured.into_bytes();
if let Err(error) = self.write_redirect(&expanded, &bytes, *append) {
let _ = stderr.write(format!("{name}: {error}\n").as_bytes());
return (ExitStatus::FAILURE, terminal);
}
}
if let Some((path_str, append)) = &stderr_redirect {
let expanded = self.expand_word(path_str);
let bytes = captured_stderr.into_bytes();
if let Err(error) = self.write_redirect(&expanded, &bytes, *append) {
let _ = stderr.write(format!("{name}: {error}\n").as_bytes());
return (ExitStatus::FAILURE, terminal);
}
}
return (status, terminal);
}
let resolution = match self.resolve_with_hash(&name) {
Ok(resolution) => resolution,
Err(error) => {
let _ = stderr.write(format!("{name}: {error}\n").as_bytes());
return (ExitStatus::FAILURE, terminal);
}
};
let resolved = match resolution {
CommandResolution::Found(resolved) => resolved,
CommandResolution::NotFound => {
let _ = stderr.write((self.dialect.command_not_found)(&name).as_bytes());
return (ExitStatus::NOT_FOUND, terminal);
}
};
if let ResolvedExecutable::Bound(executable) = &resolved
&& self.interpreter_objects.contains(&executable.object)
{
let status = self.with_prefix_environment(command_environment.as_ref(), |shell| {
if background {
let pid = shell
.runtime
.record_background_job(final_argv.join(" "), executable.name.clone());
let _ = pid;
}
shell.run_script_invocation(
&final_argv,
effective_stdin,
effective_stdout,
effective_stderr,
)
});
return (status, terminal);
}
if let ResolvedExecutable::Script { shebang, .. } = &resolved {
let interpreter = if shebang.interpreter.ends_with("/env") {
shebang.argument.as_deref().unwrap_or("env")
} else {
shebang.interpreter.as_str()
};
let mut line = shell_quote(interpreter);
if !shebang.interpreter.ends_with("/env")
&& let Some(argument) = &shebang.argument
{
line.push(' ');
line.push_str(&shell_quote(argument));
}
for argument in &final_argv {
line.push(' ');
line.push_str(&shell_quote(argument));
}
let status = self.with_prefix_environment(command_environment.as_ref(), |shell| {
if background {
let pid = shell
.runtime
.record_background_job(final_argv.join(" "), interpreter.to_owned());
let _ = pid;
}
shell.execute(&line, effective_stdin, effective_stdout, effective_stderr)
});
return (status, terminal);
}
let environment = command_environment.as_ref().unwrap_or(&self.environment);
let (result, returned_terminal) = if background {
self.runtime.execute_background(
&resolved,
&final_argv,
&self.credentials,
&self.cwd,
environment,
effective_stdin,
effective_stdout,
effective_stderr,
terminal,
)
} else {
self.runtime.execute(
&resolved,
&final_argv,
&self.credentials,
&self.cwd,
environment,
effective_stdin,
effective_stdout,
effective_stderr,
terminal,
)
};
let status = match result {
Ok(status) => status,
Err(error) => {
let _ = stderr.write(format!("{name}: {error}\n").as_bytes());
return (ExitStatus::FAILURE, returned_terminal);
}
};
if stderr_to_stdout && stderr_redirect.is_none() {
let merged = captured_stderr.bytes().to_vec();
if has_redirect {
let _ = captured.write(&merged);
} else {
let _ = stdout.write(&merged);
}
}
if stdout_to_stderr {
let merged = captured_stdout.bytes().to_vec();
let _ = stderr.write(&merged);
}
if let Some((path_str, append)) = &stdout_redirect {
let expanded = self.expand_word(path_str);
let bytes = captured.into_bytes();
if let Err(error) = self.write_redirect(&expanded, &bytes, *append) {
let _ = stderr.write(format!("{name}: {error}\n").as_bytes());
return (ExitStatus::FAILURE, returned_terminal);
}
}
if let Some((path_str, append)) = &stderr_redirect {
let expanded = self.expand_word(path_str);
let bytes = captured_stderr.into_bytes();
if let Err(error) = self.write_redirect(&expanded, &bytes, *append) {
let _ = stderr.write(format!("{name}: {error}\n").as_bytes());
return (ExitStatus::FAILURE, returned_terminal);
}
}
(status, returned_terminal)
}
fn execute_case_clause<'t>(
&mut self,
clause: &CaseClauseCommand,
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
terminal: Option<&'t mut dyn Terminal>,
background: bool,
) -> (ExitStatus, Option<&'t mut dyn Terminal>) {
let subject = self.expand_word(&clause.value.value);
let mut status = ExitStatus::SUCCESS;
let mut terminal = terminal;
let mut forced = false;
for item in &clause.cases {
if !forced {
let matched = item.patterns.iter().any(|pattern| {
let pattern_text = self.expand_word(&pattern.value);
crate::expansion::glob_match(&subject, &pattern_text)
});
if !matched {
continue;
}
}
forced = false;
if let Some(body) = &item.cmd {
let (body_status, returned) = self.execute_compound_list(
body,
stdin,
stdout,
stderr,
terminal.take(),
background,
);
terminal = returned;
status = body_status;
}
match item.post_action {
CaseItemPostAction::ExitCase => break,
CaseItemPostAction::UnconditionallyExecuteNextCaseItem => forced = true,
CaseItemPostAction::ContinueEvaluatingCases => {}
}
}
(status, terminal)
}
fn with_prefix_environment<R>(
&mut self,
command_environment: Option<&os::Environment>,
f: impl FnOnce(&mut Self) -> R,
) -> R {
let Some(prefix) = command_environment else {
return f(self);
};
let mut prior: Vec<(String, Option<String>)> = Vec::new();
for (key, value) in prefix.iter() {
prior.push((key.to_owned(), self.environment.get(key).map(str::to_owned)));
self.environment.set(key, value);
}
let result = f(self);
for (key, value) in prior.into_iter().rev() {
match value {
Some(value) => self.environment.set(&key, value),
None => {
self.environment.remove(&key);
}
}
}
result
}
fn run_script_invocation(
&mut self,
argv: &[String],
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
if argv.get(1).is_some_and(|argument| argument == "-c") {
let script = argv.get(2).cloned().unwrap_or_default();
let mut rest = argv.iter().skip(3).cloned();
let name = rest.next().unwrap_or_else(|| self.dialect.name.to_owned());
self.positionals.push(PositionalFrame {
name,
args: rest.collect(),
});
let status = self.execute(&script, stdin, stdout, stderr);
self.positionals.pop();
return status;
}
let Some(path) = argv.get(1) else {
self.positionals.push(PositionalFrame {
name: self.dialect.name.to_owned(),
args: Vec::new(),
});
let mut line = String::new();
let mut status = ExitStatus::SUCCESS;
loop {
match stdin.read_line(&mut line) {
Ok(true) => {
status = self.execute(&line, stdin, stdout, stderr);
line.clear();
if self.exit_request.is_some() {
break;
}
}
Ok(false) => break,
Err(_) => {
let _ = stderr.write(b"sh: input error\n");
return ExitStatus::FAILURE;
}
}
}
self.positionals.pop();
return status;
};
self.positionals.push(PositionalFrame {
name: path.clone(),
args: argv.iter().skip(2).cloned().collect(),
});
let status = self.execute_script(path, stdin, stdout, stderr);
self.positionals.pop();
status
}
fn try_builtin<'t>(
&mut self,
name: &str,
argv: &[String],
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
terminal: Option<&'t mut dyn Terminal>,
) -> (Option<ExitStatus>, Option<&'t mut dyn Terminal>) {
if let Some(source) = self.functions.get(name).cloned() {
if self.call_depth >= MAX_CALL_DEPTH {
let _ = stderr
.write(format!("vce: {name}: maximum recursion depth exceeded\n").as_bytes());
return (Some(ExitStatus::FAILURE), terminal);
}
self.positionals.push(PositionalFrame {
name: name.to_owned(),
args: argv.iter().skip(1).cloned().collect(),
});
let (status, terminal) =
self.execute_with_terminal_returning(&source, stdin, stdout, stderr, terminal);
self.positionals.pop();
return (Some(status), terminal);
}
(
(self.dialect.run_builtin)(self, name, argv, stdin, stdout, stderr),
terminal,
)
}
pub fn resolve_with_hash(&mut self, name: &str) -> Result<CommandResolution, os::OsError> {
if let Some(object) = self.hash.get(name).copied() {
if self
.os
.engine()
.metadata(Some(self.credentials.actor()), object)
.is_ok()
&& let Some(behavior) = self.runtime.binding(object)
{
return Ok(CommandResolution::Found(ResolvedExecutable::Bound(
Executable {
object,
name: name.to_owned(),
behavior,
},
)));
}
self.hash.remove(name);
}
let resolution =
self.runtime
.resolve(name, &self.credentials, &self.cwd, &self.environment)?;
if let CommandResolution::Found(ResolvedExecutable::Bound(executable)) = &resolution {
self.hash.insert(name.to_owned(), executable.object);
}
Ok(resolution)
}
pub fn resolve_external_path(&mut self, name: &str) -> Option<String> {
self.resolve_external_paths(name).into_iter().next()
}
pub fn resolve_external_paths(&mut self, name: &str) -> Vec<String> {
if name.contains('/') {
let path = match self.resolve_path(name) {
Ok(path) => path,
Err(_) => return Vec::new(),
};
return self
.executable_path(&path)
.map(|path| vec![path.to_string()])
.unwrap_or_default();
}
let mut seen: std::collections::BTreeSet<engine::ObjectId> =
std::collections::BTreeSet::new();
let mut found = Vec::new();
for directory in self.environment.path_entries() {
let candidate = directory.join(&engine::Name::new(name).expect("valid name"));
if let Some(path) = self.executable_path(&candidate)
&& let Ok(object) = self
.os
.engine()
.lookup(Some(self.credentials.actor()), &path)
&& seen.insert(object)
{
found.push(path.to_string());
}
}
found
}
pub fn executable_path(&self, path: &engine::VirtualPath) -> Option<engine::VirtualPath> {
let actor = Some(self.credentials.actor());
let object = self.os.engine().lookup(actor, path).ok()?;
if self
.os
.engine()
.check(actor, engine::Operation::Execute, object)
.is_ok()
{
Some(path.clone())
} else {
None
}
}
pub fn display_path(&self, path: &engine::VirtualPath) -> String {
if let Some(home) = self.environment.get("HOME")
&& let Ok(home_path) = home.parse::<engine::VirtualPath>()
&& path.starts_with(&home_path)
{
let mut display = "~".to_owned();
for segment in path.segments().iter().skip(home_path.segments().len()) {
display.push('/');
display.push_str(segment);
}
return display;
}
path.to_string()
}
pub fn is_directory(&self, path: &engine::VirtualPath) -> bool {
let actor = Some(self.credentials.actor());
match self.os.engine().lookup(actor, path) {
Ok(object) => self.os.engine().children(actor, object).is_ok(),
Err(_) => false,
}
}
pub fn expand_glob(&self, pattern: &str) -> Vec<String> {
if !pattern.contains('*') && !pattern.contains('?') {
return vec![pattern.to_owned()];
}
let (directory_text, file_pattern) = match pattern.rfind('/') {
Some(index) => (&pattern[..index], &pattern[index + 1..]),
None => ("", pattern),
};
let directory = if directory_text.is_empty() {
self.cwd.clone()
} else {
match self.resolve_path(directory_text) {
Ok(path) => path,
Err(_) => return vec![pattern.to_owned()],
}
};
let actor = Some(self.credentials.actor());
let object = match self.os.engine().lookup(actor, &directory) {
Ok(object) => object,
Err(_) => return vec![pattern.to_owned()],
};
let mut matches = Vec::new();
if let Ok(entries) = self.os.engine().list(actor, object) {
for (name, _) in entries {
if crate::expansion::glob_match(name.as_str(), file_pattern) {
let display = if directory_text.is_empty() {
name.as_str().to_owned()
} else {
format!("{directory_text}/{}", name.as_str())
};
matches.push(display);
}
}
}
if matches.is_empty() {
vec![pattern.to_owned()]
} else {
matches
}
}
pub fn resolve_path(&self, argument: &str) -> Result<VirtualPath, os::OsError> {
if argument.is_empty() {
return Err(os::OsError::InvalidPathArgument(argument.to_owned()));
}
os::runtime::resolve_path_name(argument, &self.cwd)
}
pub fn write_redirect(
&mut self,
path_str: &str,
bytes: &[u8],
append: bool,
) -> Result<(), os::OsError> {
let path = self.resolve_path(path_str)?;
if os::fs_util::is_null_device(&path) {
return Ok(());
}
let engine = self.os.engine();
let actor = Some(self.credentials.actor());
if let Ok(object) = engine.lookup(actor, &path) {
if append {
engine.append(actor, object, bytes.to_vec())?;
} else {
engine.write(actor, object, bytes.to_vec())?;
}
return Ok(());
}
let parent_path = path
.parent()
.ok_or_else(|| os::OsError::InvalidPathArgument(path_str.to_owned()))?;
let name_str = path
.name()
.ok_or_else(|| os::OsError::InvalidPathArgument(path_str.to_owned()))?
.to_owned();
let parent = engine.lookup(actor, &parent_path)?;
let name = engine::Name::new(&name_str)?;
engine.create_file_with_options(
actor,
parent,
name,
Some(bytes.to_vec()),
os::unix::attrs::UnixAttrs {
mode: os::FileMode::FILE_644,
gid: self.credentials.effective_gid(),
}
.to_create_options(Some(self.credentials.actor())),
)?;
Ok(())
}
pub fn execute_script(
&mut self,
script_path: &str,
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
let path = match self.resolve_path(script_path) {
Ok(path) => path,
Err(error) => {
let _ = stderr.write(format!("{script_path}: {error}\n").as_bytes());
return ExitStatus::FAILURE;
}
};
let object = match self
.os
.engine()
.lookup(Some(self.credentials.actor()), &path)
{
Ok(object) => object,
Err(error) => {
let _ = stderr.write(format!("{script_path}: {error}\n").as_bytes());
return ExitStatus::FAILURE;
}
};
let content = match self
.os
.engine()
.read(Some(self.credentials.actor()), object)
{
Ok(Some(bytes)) => bytes,
Ok(None) => Vec::new(),
Err(error) => {
let _ = stderr.write(format!("{script_path}: {error}\n").as_bytes());
return ExitStatus::FAILURE;
}
};
let text = String::from_utf8_lossy(&content);
let mut last_status = ExitStatus::SUCCESS;
for line in text.lines() {
last_status = self.execute(line, stdin, stdout, stderr);
if self.exit_request.is_some() {
break;
}
}
last_status
}
pub fn cd_to(
&mut self,
argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
let target = if argv.len() < 2 {
self.environment.get("HOME").unwrap_or("/").to_owned()
} else if argv[1] == "-" {
match &self.previous_cwd {
Some(previous) => previous.to_string(),
None => {
let _ = stderr.write(b"cd: OLDPWD not set\n");
return ExitStatus::FAILURE;
}
}
} else {
argv[1].clone()
};
let path = match self.resolve_path(&target) {
Ok(path) => path,
Err(error) => {
let _ = stderr.write(format!("cd: {target}: {error}\n").as_bytes());
return ExitStatus::FAILURE;
}
};
let object = match self
.os
.engine()
.lookup(Some(self.credentials.actor()), &path)
{
Ok(object) => object,
Err(error) => {
let _ = stderr.write(format!("cd: {target}: {error}\n").as_bytes());
return ExitStatus::FAILURE;
}
};
if self
.os
.engine()
.children(Some(self.credentials.actor()), object)
.is_err()
{
let _ = stderr.write(format!("cd: {target}: Not a directory\n").as_bytes());
return ExitStatus::FAILURE;
}
let previous = std::mem::replace(&mut self.cwd, path);
self.previous_cwd = Some(previous);
if argv.get(1).is_some_and(|argument| argument == "-") {
let _ = stdout.write(format!("{}\n", self.cwd).as_bytes());
}
ExitStatus::SUCCESS
}
pub fn pwd_of(&self, stdout: &mut dyn Output) -> ExitStatus {
let line = format!("{}\n", self.cwd);
let _ = stdout.write(line.as_bytes());
ExitStatus::SUCCESS
}
pub fn list_jobs(&mut self, stdout: &mut dyn Output) -> ExitStatus {
self.runtime.reconcile();
let now = self.os.engine().time();
let mut index = 0;
for job in self.runtime.jobs().values() {
if !job.background {
continue;
}
index += 1;
let pending = now < job.completion_at;
let line = format!(
"[{}] {} {}{}\n",
index,
if pending { "Running" } else { "Done" },
job.command_line,
if pending { " &" } else { "" },
);
let _ = stdout.write(line.as_bytes());
}
ExitStatus::SUCCESS
}
fn resolve_job_spec(&self, argument: Option<&str>) -> Option<u32> {
let argument = argument?;
if let Some(index) = argument.strip_prefix('%') {
let index: usize = index.trim().parse().ok()?;
let pids: Vec<u32> = self
.runtime
.jobs()
.values()
.filter(|job| job.background)
.map(|job| job.pid)
.collect();
pids.get(index.checked_sub(1)?).copied()
} else {
argument.trim().parse().ok()
}
}
pub fn foreground_job(
&mut self,
argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
self.runtime.reconcile();
let spec = self.resolve_job_spec(argv.get(1).map(String::as_str));
let Some(job) = spec.and_then(|pid| self.runtime.jobs().get(&pid)) else {
let _ = stderr.write(b"fg: no such job\n");
return ExitStatus::FAILURE;
};
let line = job.command_line.clone();
let due = job.completion_at;
let status = job.exit_status;
if self.os.engine().time() < due {
let remaining = due
.as_nanos()
.saturating_sub(self.os.engine().time().as_nanos());
self.os
.engine()
.advance_time(std::time::Duration::from_nanos(remaining));
self.runtime.reconcile();
}
let _ = stdout.write(format!("{line}\n").as_bytes());
status.unwrap_or(ExitStatus::SUCCESS)
}
pub fn background_job(
&mut self,
argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
self.runtime.reconcile();
let spec = self.resolve_job_spec(argv.get(1).map(String::as_str));
let Some(job) = spec.and_then(|pid| self.runtime.jobs().get(&pid)) else {
let _ = stderr.write(b"bg: no such job\n");
return ExitStatus::FAILURE;
};
let line = job.command_line.clone();
let _ = stdout.write(format!("{line} &\n").as_bytes());
ExitStatus::SUCCESS
}
pub fn wait_for_jobs(&mut self, argv: &[String], stderr: &mut dyn Output) -> ExitStatus {
self.runtime.reconcile();
let targets: Vec<u32> = if argv.len() <= 1 {
self.runtime
.jobs()
.values()
.filter(|job| job.background && job.state == os::runtime::ProcessState::Running)
.map(|job| job.pid)
.collect()
} else {
let mut targets = Vec::new();
for argument in &argv[1..] {
match self.resolve_job_spec(Some(argument)) {
Some(pid) => targets.push(pid),
None => {
let _ = stderr.write(format!("wait: {argument}: no such job\n").as_bytes());
return ExitStatus::FAILURE;
}
}
}
targets
};
let mut last = ExitStatus::SUCCESS;
for pid in targets {
let Some(job) = self.runtime.jobs().get(&pid) else {
let _ = stderr.write(format!("wait: {pid}: no such job\n").as_bytes());
return ExitStatus::FAILURE;
};
let due = job.completion_at;
let status = job.exit_status;
if self.os.engine().time() < due {
let remaining = due
.as_nanos()
.saturating_sub(self.os.engine().time().as_nanos());
self.os
.engine()
.advance_time(std::time::Duration::from_nanos(remaining));
}
last = status.unwrap_or(ExitStatus::SUCCESS);
}
self.runtime.reconcile();
last
}
pub fn builtin_echo(&self, argv: &[String], stdout: &mut dyn Output) -> ExitStatus {
let mut no_newline = false;
let mut escapes = self.dialect.echo_escapes_default;
let mut start = 1;
while let Some(argument) = argv.get(start) {
if argument == "-n" && !no_newline {
no_newline = true;
start += 1;
} else if argument == "-e" {
escapes = true;
start += 1;
} else if argument == "-E" {
escapes = false;
start += 1;
} else {
break;
}
}
let mut output = String::new();
for (index, argument) in argv.iter().skip(start).enumerate() {
if index > 0 {
output.push(' ');
}
output.push_str(argument);
}
if escapes {
output = interpret_escapes(&output);
}
if !no_newline {
output.push('\n');
}
let _ = stdout.write(output.as_bytes());
ExitStatus::SUCCESS
}
pub fn builtin_export(
&mut self,
argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
if argv.len() < 2 {
for (key, value) in self.environment().iter() {
let line = format!("{}{key}={value}\n", self.dialect.export_prefix);
let _ = stdout.write(line.as_bytes());
}
return ExitStatus::SUCCESS;
}
for assignment in argv.iter().skip(1) {
if let Some((key, value)) = assignment.split_once('=') {
self.environment_mut().set(key, value);
} else {
let _ =
stderr.write(format!("export: invalid argument '{assignment}'\n").as_bytes());
return ExitStatus::FAILURE;
}
}
ExitStatus::SUCCESS
}
pub fn builtin_history(&self, stdout: &mut dyn Output) -> ExitStatus {
for (index, line) in self.history().iter().enumerate() {
let _ = stdout.write(format!("{:5} {}\n", index + 1, line).as_bytes());
}
ExitStatus::SUCCESS
}
pub fn builtin_alias(
&mut self,
argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
if argv.len() == 1 {
for (name, expansion) in self.aliases() {
let _ = stdout.write(
format!("{}{name}='{expansion}'\n", self.dialect.alias_prefix).as_bytes(),
);
}
return ExitStatus::SUCCESS;
}
for definition in argv.iter().skip(1) {
if let Some((name, expansion)) = definition.split_once('=') {
let expansion = expansion.trim_matches('\'').trim_matches('"').to_owned();
self.aliases_mut().insert(name.to_owned(), expansion);
} else if let Some(expansion) = self.aliases().get(definition) {
let _ = stdout.write(
format!("{}{definition}='{expansion}'\n", self.dialect.alias_prefix).as_bytes(),
);
} else {
let _ = stderr.write(format!("alias: {definition}: not found\n").as_bytes());
return ExitStatus::FAILURE;
}
}
ExitStatus::SUCCESS
}
pub fn builtin_unalias(&mut self, argv: &[String], stderr: &mut dyn Output) -> ExitStatus {
if argv.len() < 2 {
let _ = stderr.write(b"unalias: not enough arguments\n");
return ExitStatus::FAILURE;
}
for name in argv.iter().skip(1) {
if name == "-a" {
self.aliases_mut().clear();
continue;
}
if self.aliases_mut().remove(name).is_none() {
let _ = stderr.write(format!("unalias: {name}: not found\n").as_bytes());
return ExitStatus::FAILURE;
}
}
ExitStatus::SUCCESS
}
pub fn resolve_name(&mut self, name: &str, is_builtin: fn(&str) -> bool) -> NameResolution {
let alias = self.aliases().get(name).cloned();
let function = self.functions_mut().contains_key(name);
let builtin = is_builtin(name);
let paths = self.resolve_external_paths(name);
NameResolution {
alias,
function,
builtin,
paths,
}
}
pub fn hash_table(
&mut self,
argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
if argv.contains(&"-r".to_owned()) {
self.hash.clear();
return ExitStatus::SUCCESS;
}
if argv.len() == 1 {
for (name, object) in &self.hash {
let _ = stdout.write(format!("{name}={object}\n").as_bytes());
}
return ExitStatus::SUCCESS;
}
for name in argv.iter().skip(1) {
if let Some(stripped) = name.strip_prefix('-') {
let _ = stderr.write(format!("hash: invalid option -- '{stripped}'\n").as_bytes());
return ExitStatus::FAILURE;
}
match self
.runtime
.resolve(name, &self.credentials, &self.cwd, &self.environment)
{
Ok(CommandResolution::Found(ResolvedExecutable::Bound(executable))) => {
self.hash.insert(name.clone(), executable.object);
}
_ => {
let _ = stderr.write(format!("hash: {name}: not found\n").as_bytes());
return ExitStatus::FAILURE;
}
}
}
ExitStatus::SUCCESS
}
pub fn print_dirs(&self, stdout: &mut dyn Output) -> ExitStatus {
let mut parts: Vec<String> = vec![self.display_path(&self.cwd)];
for entry in &self.dir_stack {
parts.push(self.display_path(entry));
}
let _ = stdout.write(format!("{}\n", parts.join(" ")).as_bytes());
ExitStatus::SUCCESS
}
pub fn push_directory(
&mut self,
argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
if argv.len() < 2 {
let _ = stderr.write(b"pushd: no other directory\n");
return ExitStatus::FAILURE;
}
let target = &argv[1];
let path = match self.resolve_path(target) {
Ok(path) => path,
Err(error) => {
let _ = stderr.write(format!("pushd: {target}: {error}\n").as_bytes());
return ExitStatus::FAILURE;
}
};
if !self.is_directory(&path) {
let _ = stderr.write(format!("pushd: {target}: Not a directory\n").as_bytes());
return ExitStatus::FAILURE;
}
self.dir_stack.push(self.cwd.clone());
self.cwd = path;
self.print_dirs(stdout)
}
pub fn pop_directory(
&mut self,
_argv: &[String],
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
let Some(previous) = self.dir_stack.pop() else {
let _ = stderr.write(b"popd: directory stack empty\n");
return ExitStatus::FAILURE;
};
self.cwd = previous;
self.print_dirs(stdout)
}
pub fn unset_names(&mut self, argv: &[String], stderr: &mut dyn Output) -> ExitStatus {
let mut functions = false;
let mut names: Vec<&String> = Vec::new();
let mut index = 1usize;
while let Some(argument) = argv.get(index) {
if argument == "-f" {
functions = true;
} else if argument == "-v" {
functions = false;
} else {
names.push(argument);
}
index += 1;
}
if names.is_empty() {
let _ = stderr.write(b"unset: not enough arguments\n");
return ExitStatus::FAILURE;
}
for name in names {
if functions {
self.functions.remove(name.as_str());
} else {
self.environment.remove(name);
}
}
ExitStatus::SUCCESS
}
pub fn source_file(
&mut self,
argv: &[String],
stdin: &mut dyn Input,
stdout: &mut dyn Output,
stderr: &mut dyn Output,
) -> ExitStatus {
let Some(target) = argv.get(1) else {
let _ = stderr.write(b"source: filename argument required\n");
return ExitStatus::FAILURE;
};
let path = match self.resolve_path(target) {
Ok(path) => path,
Err(error) => {
let _ = stderr.write(format!("source: {target}: {error}\n").as_bytes());
return ExitStatus::FAILURE;
}
};
let object = match self
.os
.engine()
.lookup(Some(self.credentials.actor()), &path)
{
Ok(object) => object,
Err(error) => {
let _ = stderr.write(format!("source: {target}: {error}\n").as_bytes());
return ExitStatus::FAILURE;
}
};
let Some(bytes) = self
.os
.engine()
.read(Some(self.credentials.actor()), object)
.ok()
.flatten()
else {
let _ = stderr.write(format!("source: {target}: not readable\n").as_bytes());
return ExitStatus::FAILURE;
};
let source = String::from_utf8_lossy(&bytes);
self.positionals.push(PositionalFrame {
name: target.clone(),
args: argv.iter().skip(2).cloned().collect(),
});
let status = self.execute(source.trim_end(), stdin, stdout, stderr);
self.positionals.pop();
status
}
pub fn null_command(&self) -> ExitStatus {
ExitStatus::SUCCESS
}
pub fn clear_screen(&self, stdout: &mut dyn Output) -> ExitStatus {
let _ = stdout.write(b"\x1b[3J\x1b[H\x1b[2J");
ExitStatus::SUCCESS
}
}
fn parse_program(line: &str) -> Result<ast::Program, brush_parser::ParseError> {
let mut parser = Parser::new(
Cursor::new(line.as_bytes()),
&ParserOptions::default(),
&SourceInfo::default(),
);
parser.parse_program()
}
pub fn hostname_from_etc(os: &UnixOs) -> String {
os::unix::unix_os::hostname(os)
}
pub fn needs_continuation(input: &str) -> bool {
parse_program(input).is_err_and(|error| match error {
brush_parser::ParseError::ParsingAtEndOfInput => true,
brush_parser::ParseError::Tokenizing { inner, .. } => inner.is_incomplete(),
brush_parser::ParseError::ParsingNearToken(_) => false,
})
}
fn compound_stdout_redirect(redirects: Option<&ast::RedirectList>) -> Option<(String, bool)> {
let list = redirects?;
for redirect in &list.0 {
if let IoRedirect::File(fd, kind, target) = redirect {
let filename = match target {
IoFileRedirectTarget::Filename(word) => Some(word.value.clone()),
_ => None,
};
if let Some(filename) = filename {
let append = matches!(kind, IoFileRedirectKind::Append);
if fd.is_none_or(|n| n == 1) {
return Some((filename, append));
}
}
}
}
None
}
fn heredoc_content(redirect: &str) -> Option<Vec<u8>> {
redirect
.strip_prefix("\0heredoc:")
.or_else(|| redirect.strip_prefix("\0heredoc-expand:"))
.map(|content| content.trim_end_matches('\0').as_bytes().to_vec())
.or_else(|| {
redirect
.strip_prefix("\0herestring:")
.map(|content| content.trim_end_matches('\0').as_bytes().to_vec())
})
}
fn heredoc_expands(redirect: &str) -> bool {
redirect.starts_with("\0heredoc-expand:")
}
fn shell_quote(word: &str) -> String {
if word.is_empty()
|| word
.chars()
.any(|c| c.is_whitespace() || "\\'\"$`&|;<>()[]{}*?!#~=".contains(c))
{
format!("'{}'", word.replace('\'', "'\\''"))
} else {
word.to_owned()
}
}
trait AssignmentNameString {
fn name_string(&self) -> String;
}
impl AssignmentNameString for ast::AssignmentName {
fn name_string(&self) -> String {
match self {
ast::AssignmentName::VariableName(name) => name.clone(),
ast::AssignmentName::ArrayElementName(name, index) => {
format!("{name}[{index}]")
}
}
}
}
pub fn format_login_line(timestamp: engine::Timestamp) -> String {
os::datetime::format_timestamp(timestamp, "%a %b %d %H:%M:%S")
}