use super::classify_budget::charge_classify_work;
use super::{Script, SimpleCmd};
use crate::verdict::{SafetyLevel, Verdict};
thread_local! {
static FUNCTIONS: std::cell::RefCell<Vec<(String, Script)>> =
const { std::cell::RefCell::new(Vec::new()) };
static POISONED_FUNCS: std::cell::RefCell<Vec<String>> =
const { std::cell::RefCell::new(Vec::new()) };
static RESOLVING: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
static DEFINED: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
}
const MAX_FUNC_DEPTH: usize = 32;
pub(super) struct FuncScope;
impl Drop for FuncScope {
fn drop(&mut self) {
FUNCTIONS.with(|f| {
f.borrow_mut().pop();
});
}
}
pub(super) fn define_function(name: String, body: Script) -> FuncScope {
DEFINED.with(|d| d.borrow_mut().push(name.clone()));
FUNCTIONS.with(|f| f.borrow_mut().push((name, body)));
FuncScope
}
pub(super) fn body_unknown(name: &str) -> bool {
POISONED_FUNCS.with(|p| p.borrow().iter().any(|n| n == name))
}
pub(super) fn lookup_function(name: &str) -> Option<Script> {
if body_unknown(name) {
return None;
}
FUNCTIONS.with(|f| f.borrow().iter().rev().find(|(n, _)| n == name).map(|(_, b)| b.clone()))
}
pub(super) fn forget_poisoned_functions() {
POISONED_FUNCS.with(|p| p.borrow_mut().clear());
DEFINED.with(|d| d.borrow_mut().clear());
}
pub(super) fn poison_function(name: String) {
POISONED_FUNCS.with(|p| p.borrow_mut().push(name));
}
struct ResolveScope;
impl Drop for ResolveScope {
fn drop(&mut self) {
RESOLVING.with(|r| {
r.borrow_mut().pop();
});
}
}
fn begin_resolving(name: &str) -> Option<ResolveScope> {
if !charge_classify_work(1) {
return None;
}
RESOLVING.with(|r| {
let mut stack = r.borrow_mut();
if stack.len() >= MAX_FUNC_DEPTH || stack.iter().any(|n| n == name) {
None
} else {
stack.push(name.to_string());
Some(ResolveScope)
}
})
}
pub(super) fn call_verdict(cmd: &SimpleCmd, name: &str) -> Option<Verdict> {
if body_unknown(name) || rebinds_a_name(cmd, name) {
return Some(Verdict::Denied);
}
let body = lookup_function(name)?;
let Some(_resolving) = begin_resolving(name) else {
return Some(Verdict::Denied);
};
let mut shifted = false;
let _args: Vec<crate::pathctx::VarGuard> = cmd.words[1..]
.iter()
.enumerate()
.map(|(i, w)| {
shifted |= may_split(w);
let value = if shifted { super::scope_budget::UNCERTAIN_VALUE.to_string() } else { super::check::certain_value(w) };
crate::pathctx::enter_var((i + 1).to_string(), value)
})
.collect();
Some(super::netargs::with_args(cmd, || super::check::script_verdict(&body)))
}
pub(crate) fn names_a_function(name: &str) -> bool {
body_unknown(name) || FUNCTIONS.with(|f| f.borrow().iter().any(|(n, _)| n == name))
}
pub(super) fn definition_verdict(name: &str, body: &Script) -> Verdict {
if runs_unnamed(name) { super::check::script_verdict(body) } else { Verdict::Allowed(SafetyLevel::Inert) }
}
fn runs_unnamed(name: &str) -> bool {
name.starts_with("TRAP")
|| matches!(
name,
"command_not_found_handler"
| "command_not_found_handle"
| "chpwd"
| "precmd"
| "preexec"
| "periodic"
| "zshexit"
| "zshaddhistory"
| "zsh_directory_name"
)
}
fn rebinds_a_name(cmd: &SimpleCmd, name: &str) -> bool {
let values = || cmd.words[1..].iter().map(super::check::certain_value);
let binds = || values().any(|v| v == super::scope_budget::UNCERTAIN_VALUE || v.contains('='));
match name {
"alias" => binds(),
"hash" => binds() || values().any(|v| v.starts_with('-') && !v.starts_with("--") && v.contains('p')),
_ => false,
}
}
fn may_split(word: &super::Word) -> bool {
use super::WordPart;
use crate::pathctx::item_shape::{Binding, binding};
let substitutes =
|part: &WordPart| matches!(part, WordPart::CmdSub(_) | WordPart::Backtick(_) | WordPart::Arith(_) | WordPart::ProcSub(_));
let one_known_word = || {
let value = super::check::certain_value(word);
!word.0.iter().any(substitutes)
&& value != super::scope_budget::UNCERTAIN_VALUE
&& !value.is_empty()
&& !value.contains([' ', '\t', '\n', '*', '?', '[', '^', '#', '<', '~', '@'])
&& matches!(binding("IFS"), Binding::Unbound)
};
word.expand().len() != 1
|| (!one_known_word()
&& word.0.iter().any(|part| match part {
WordPart::Lit(s) => s.contains(['$', '*', '?', '[', '^', '#', '<']),
WordPart::DQuote(inner) => inner.eval().contains('@'),
part if substitutes(part) => true,
_ => false,
}))
}
pub(crate) fn ever_defined(name: &str) -> bool {
DEFINED.with(|d| d.borrow().iter().any(|n| n == name)) || names_a_function(name)
}