Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 39 additions & 2 deletions tools/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
use crate::{error, Result};
use std::ffi::OsString;
use std::path::PathBuf;
use std::time::Duration;

/// Preserve native paths/argv. Only names and manifest text require UTF-8.
pub struct Args {
Expand Down Expand Up @@ -68,6 +69,23 @@ impl Args {
}
}

/// Timeout seconds beyond this bound are ordinary input errors: such values
/// cannot be turned into a deadline without overflowing `Instant` addition, and
/// the derived process deadlines stay inside `Duration` arithmetic.
pub const MAX_TIMEOUT_SECONDS: u64 = u32::MAX as u64;

/// Parse a timeout option once at the shared boundary so every timeout flag
/// rejects excessive values before any `Duration` or `Instant` arithmetic can
/// panic. Zero keeps the existing per-command meaning: the FreeBSD provider
/// rejects it, while `exec` and `test` time out immediately.
pub fn timeout(value: Option<String>, fallback: u64) -> Result<Duration> {
let seconds: u64 = value.map(|value| value.parse()).transpose()?.unwrap_or(fallback);
if seconds > MAX_TIMEOUT_SECONDS {
return Err(error(format!("timeout must be at most {MAX_TIMEOUT_SECONDS} seconds")));
}
Ok(Duration::from_secs(seconds))
}

pub fn main(arguments: &[OsString]) -> Result<i32> {
let Some((command, rest)) = arguments.split_first() else {
return Err(error("expected a wave-tools command"));
Expand Down Expand Up @@ -140,7 +158,7 @@ pub fn main(arguments: &[OsString]) -> Result<i32> {
}
if command == "exec" {
let mut args = Args::new(rest);
let timeout = args.text("--timeout")?.unwrap_or_else(|| "1800".into()).parse::<u64>()?;
let timeout = crate::cli::timeout(args.text("--timeout")?, 1800)?;
let limit =
args.text("--output-limit")?.unwrap_or_else(|| "67108864".into()).parse::<usize>()?;
let cwd = args.path("--cwd")?.map(Ok).unwrap_or_else(std::env::current_dir)?;
Expand All @@ -151,7 +169,7 @@ pub fn main(arguments: &[OsString]) -> Result<i32> {
}
let mut spec = crate::process::Spec::new(args.values);
spec.stack = stack;
spec.timeout = std::time::Duration::from_secs(timeout);
spec.timeout = timeout;
spec.output_limit = limit;
spec.cwd = cwd;
spec.stream = !capture;
Expand Down Expand Up @@ -182,3 +200,22 @@ pub fn main(arguments: &[OsString]) -> Result<i32> {
}
Err(error(format!("unknown command: {}", command.to_string_lossy())))
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn timeout_rejects_excessive_values_and_keeps_defined_results() {
assert_eq!(timeout(None, 30).unwrap(), Duration::from_secs(30));
assert_eq!(timeout(Some("45".into()), 30).unwrap(), Duration::from_secs(45));
assert_eq!(timeout(Some("0".into()), 30).unwrap(), Duration::ZERO);
let boundary = timeout(Some(MAX_TIMEOUT_SECONDS.to_string()), 30).unwrap();
assert_eq!(boundary, Duration::from_secs(MAX_TIMEOUT_SECONDS));
for value in [u64::MAX.to_string(), (MAX_TIMEOUT_SECONDS + 1).to_string()] {
let error = timeout(Some(value), 30).unwrap_err().to_string();
assert!(error.starts_with("timeout must be at most"), "{error}");
}
assert!(timeout(Some("not-a-number".into()), 30).is_err());
}
}
36 changes: 24 additions & 12 deletions tools/src/freebsd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,21 +31,29 @@ pub struct Console<S> {
echo_output: bool,
}

/// Checked deadline construction: a timeout that cannot be represented as an
/// instant is an ordinary input error instead of a panicking `Instant` add.
fn checked_deadline(timeout: Duration) -> Result<Instant> {
Instant::now().checked_add(timeout).ok_or_else(|| error("timeout is too large for a deadline"))
}

impl<S: Read + Write> Console<S> {
pub fn new(stream: S, log: File, timeout: Duration) -> Self {
Self {
pub fn new(stream: S, log: File, timeout: Duration) -> Result<Self> {
Ok(Self {
stream,
log,
buffer: String::new(),
boot_deadline: Instant::now() + timeout,
boot_deadline: checked_deadline(timeout)?,
echo_output: false,
}
})
}

pub fn expect(&mut self, pattern: &str, timeout: Option<Duration>) -> Result<Vec<String>> {
let expression = regex_lite::Regex::new(pattern)?;
let deadline =
timeout.map(|timeout| Instant::now() + timeout).unwrap_or(self.boot_deadline);
let deadline = match timeout {
Some(timeout) => checked_deadline(timeout)?,
None => self.boot_deadline,
};
loop {
if let Some(captures) = expression.captures(&self.buffer) {
let end = captures.get(0).unwrap().end();
Expand Down Expand Up @@ -206,7 +214,7 @@ impl Vm {
stream.set_write_timeout(Some(Duration::from_secs(10)))?;
let log = File::create(work.join("guest.log"))?;
Ok(Self {
console: Console::new(stream, log, boot.saturating_sub(started.elapsed())),
console: Console::new(stream, log, boot.saturating_sub(started.elapsed()))?,
owner,
})
}
Expand Down Expand Up @@ -318,11 +326,11 @@ fn provider_cases(args: &mut Args) -> Result<i32> {
let output = args.path("--out-dir")?.unwrap_or_else(|| crate::root().join(".tmp/freebsd-sys"));
let report = args.path("--report-json")?.unwrap_or_else(|| output.join("report.json"));
let seconds = |value: Option<String>, fallback: u64| -> Result<Duration> {
let seconds = value.map(|v| v.parse()).transpose()?.unwrap_or(fallback);
if seconds == 0 {
let seconds = crate::cli::timeout(value, fallback)?;
if seconds.is_zero() {
return Err(error("timeouts must be positive"));
}
Ok(Duration::from_secs(seconds))
Ok(seconds)
};
let command_timeout = seconds(args.text("--command-timeout")?, 120)?;
let boot_timeout = seconds(args.text("--boot-timeout")?, 240)?;
Expand Down Expand Up @@ -564,7 +572,10 @@ fn provider_cases(args: &mut Args) -> Result<i32> {
command,
&work,
boot_timeout,
boot_timeout + case_timeout * (cases.len() as u32) + Duration::from_secs(90),
boot_timeout
.checked_add(case_timeout.saturating_mul(cases.len() as u32))
.and_then(|timeout| timeout.checked_add(Duration::from_secs(90)))
.ok_or_else(|| error("combined boot and case timeouts exceed the maximum"))?,
)?;
vm.console.boot(&arch)?;
vm.console.send("mount -uw /\nmount -t cd9660 /dev/vtbd1 /mnt\nsh /mnt/run.sh\n")?;
Expand Down Expand Up @@ -1213,7 +1224,8 @@ mod tests {
})
});
let mut vm = Vm {
console: Console::new(stream, File::create(&log).unwrap(), Duration::from_secs(1)),
console: Console::new(stream, File::create(&log).unwrap(), Duration::from_secs(1))
.unwrap(),
owner: GuestOwner { stop: Arc::new(AtomicBool::new(false)), task: Some(task) },
};
vm.shutdown(Duration::from_secs(1)).unwrap();
Expand Down
6 changes: 3 additions & 3 deletions tools/src/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -863,7 +863,7 @@ pub fn main(arguments: &[OsString], corpus: bool) -> Result<i32> {
if !(1..=256).contains(&shards) || shard >= shards {
return Err(error("invalid case shard"));
}
let timeout = args.text("--timeout")?.unwrap_or_else(|| "30".into()).parse::<u64>()?;
let timeout = crate::cli::timeout(args.text("--timeout")?, 30)?;
let compile_only = args.flag("--compile-only");
let runtime_only = args.flag("--runtime-only");
if compile_only && runtime_only {
Expand Down Expand Up @@ -1051,8 +1051,8 @@ pub fn main(arguments: &[OsString], corpus: bool) -> Result<i32> {
let options = Options {
compiler,
target,
timeout: Duration::from_secs(timeout),
build_timeout: Duration::from_secs(timeout.max(30)),
timeout,
build_timeout: timeout.max(Duration::from_secs(30)),
qemu,
sysroot,
optimization,
Expand Down
52 changes: 49 additions & 3 deletions tools/tests/freebsd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ fn console_requires_the_entire_newline_terminated_guest_key_and_retains_followin
stream,
File::create(directory.path().join("log")).unwrap(),
Duration::from_secs(1),
);
)
.unwrap();
let result = console
.expect(r"(?:^|\r?\n)(ssh-ed25519 [A-Za-z0-9+/=]+)(?:[ \t]+[^\r\n]*)?\r?\n", None)
.unwrap();
Expand All @@ -76,7 +77,8 @@ fn loader_waits_for_each_echo_and_handles_read_errors_and_eof() {
stream,
File::create(directory.path().join("echo")).unwrap(),
Duration::from_secs(1),
);
)
.unwrap();
console.loader("set console=comconsole").unwrap();
assert_eq!(console.expect("\r", None).unwrap()[0], "\r");
for failure in [true, false] {
Expand All @@ -86,7 +88,8 @@ fn loader_waits_for_each_echo_and_handles_read_errors_and_eof() {
stream,
File::create(directory.path().join("failure")).unwrap(),
Duration::from_secs(1),
);
)
.unwrap();
let error = console.expect("never", None).unwrap_err().to_string();
assert!(error.contains(if failure { "serial read failed" } else { "console closed" }));
}
Expand Down Expand Up @@ -220,3 +223,46 @@ fn vm_validation_rejects_stale_sources_and_changed_archives_before_starting_qemu
assert!(!work.join("guest.qcow2").exists());
}
}

#[test]
fn console_rejects_out_of_range_timeouts_without_panicking() {
let directory = tempfile::tempdir().unwrap();
let stream = Stream { fragments: VecDeque::new(), writes: vec![], echo: false, fail: false };
let error = Console::new(
stream,
File::create(directory.path().join("huge")).unwrap(),
Duration::from_secs(u64::MAX),
)
.err()
.unwrap()
.to_string();
assert!(error.contains("too large for a deadline"), "{error}");
let mut console = Console::new(
Stream { fragments: VecDeque::new(), writes: vec![], echo: false, fail: false },
File::create(directory.path().join("small")).unwrap(),
Duration::from_secs(1),
)
.unwrap();
let error =
console.expect("never", Some(Duration::from_secs(u64::MAX))).unwrap_err().to_string();
assert!(error.contains("too large for a deadline"), "{error}");
}

#[test]
fn console_keeps_zero_and_boundary_timeouts_defined() {
let directory = tempfile::tempdir().unwrap();
let mut zero = Console::new(
Stream { fragments: VecDeque::new(), writes: vec![], echo: false, fail: false },
File::create(directory.path().join("zero")).unwrap(),
Duration::ZERO,
)
.unwrap();
let error = zero.expect("now", None).unwrap_err().to_string();
assert!(error.contains("before deadline"), "{error}");
let _boundary = Console::new(
Stream { fragments: VecDeque::new(), writes: vec![], echo: false, fail: false },
File::create(directory.path().join("boundary")).unwrap(),
Duration::from_secs(wave_tools::cli::MAX_TIMEOUT_SECONDS),
)
.unwrap();
}
37 changes: 37 additions & 0 deletions tools/tests/timeout_bounds.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// SPDX-License-Identifier: MPL-2.0
//! Timeout options reject out-of-range seconds before any deadline arithmetic.
use std::process::Command;

fn exec(timeout: &str, capture: bool) -> std::process::Output {
let mut command = Command::new(env!("CARGO_BIN_EXE_wave-tools"));
command.args(["exec", "--timeout", timeout]);
if capture {
command.arg("--capture");
}
command.arg("--");
if cfg!(windows) {
command.args(["cmd", "/c", "echo ok"]);
} else {
command.args(["sh", "-c", "echo ok"]);
}
command.output().unwrap()
}

#[test]
fn exec_rejects_excessive_timeouts_without_panicking() {
let result = exec(&u64::MAX.to_string(), false);
assert!(!result.status.success());
let stderr = String::from_utf8_lossy(&result.stderr);
assert!(stderr.contains("timeout must be at most"), "{stderr}");
assert!(!stderr.contains("panicked"), "{stderr}");
}

#[test]
fn exec_accepts_the_supported_boundary_and_normal_timeouts() {
let result = exec(&wave_tools::cli::MAX_TIMEOUT_SECONDS.to_string(), true);
assert!(result.status.success(), "{}", String::from_utf8_lossy(&result.stderr));
assert_eq!(String::from_utf8_lossy(&result.stdout).trim(), "ok");
let result = exec("30", true);
assert!(result.status.success(), "{}", String::from_utf8_lossy(&result.stderr));
assert_eq!(String::from_utf8_lossy(&result.stdout).trim(), "ok");
}
Loading