use crate::compiler::Compiler;
use crate::info_file::ExerciseInfo;
use anyhow::Result;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
pub(crate) const RUN_TIMEOUT: Duration = Duration::from_secs(10);
const MAX_CAPTURED_OUTPUT: usize = 1_048_576;
pub(crate) const OWN_TEST_MARKERS: [&str; 2] = ["cmetal_test.h", "clings_test.h"];
pub(crate) fn holds_tests(path: &Path) -> bool {
let Ok(bytes) = std::fs::read(path) else {
return false;
};
String::from_utf8_lossy(&bytes).lines().any(|line| {
line.trim_start()
.strip_prefix('#')
.is_some_and(|rest| rest.trim_start().starts_with("include"))
&& OWN_TEST_MARKERS.iter().any(|marker| line.contains(marker))
})
}
pub(crate) fn legacy_marker(base_dir: &Path, name: &str) -> PathBuf {
base_dir.join(".cmetal").join("legacy").join(name)
}
struct TestPlan {
own: bool,
shipped: bool,
}
pub struct Exercise {
pub info: ExerciseInfo,
pub path: PathBuf,
pub test_path: PathBuf,
pub pristine_path: PathBuf,
pub legacy_marker: PathBuf,
pub solution_path: PathBuf,
pub reveal_path: PathBuf,
pub supported: bool,
}
#[derive(Debug)]
pub struct VerifyResult {
pub success: bool,
pub stage: &'static str,
pub output: String,
}
impl Exercise {
pub fn new(
info: ExerciseInfo,
exercises_dir: &Path,
solutions_dir: &Path,
compiler: &str,
) -> Self {
let rel = info.rel_path();
let path = exercises_dir.join(&rel);
let solution_path = solutions_dir.join(&rel);
let base_dir = solutions_dir.parent().unwrap_or(solutions_dir);
let reveal_path = base_dir.join("my_solutions").join(&rel);
let test_path = base_dir.join("exercises").join(info.test_rel_path());
let pristine_path = base_dir.join("exercises").join(&rel);
let legacy_marker = legacy_marker(base_dir, &info.name);
let supported = info.supports_compiler(compiler);
Self {
info,
path,
test_path,
pristine_path,
legacy_marker,
solution_path,
reveal_path,
supported,
}
}
pub fn required_compilers(&self) -> String {
self.info
.compilers
.as_deref()
.unwrap_or_default()
.join(", ")
}
pub fn reveal_solution(&self) -> Result<PathBuf> {
let enc_path = self.solution_path.with_extension("c.enc");
let content = if enc_path.exists() {
crate::solutions::decode(&std::fs::read_to_string(&enc_path)?)?
} else if self.solution_path.exists() {
std::fs::read_to_string(&self.solution_path)?
} else {
anyhow::bail!("No solution available for {}", self.name());
};
if let Some(parent) = self.reveal_path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(&self.reveal_path, content)?;
Ok(self.reveal_path.clone())
}
pub fn name(&self) -> &str {
&self.info.name
}
pub fn hints(&self) -> Vec<&str> {
self.info.get_hints()
}
pub fn exists(&self) -> bool {
self.path.exists()
}
fn test_plan(&self) -> std::result::Result<TestPlan, String> {
let own = holds_tests(&self.path);
if self.test_path.exists() {
let legacy_copy = own && self.legacy_marker.exists();
return Ok(TestPlan {
own,
shipped: !legacy_copy,
});
}
if holds_tests(&self.pristine_path) {
if own {
return Ok(TestPlan {
own: true,
shipped: false,
});
}
return Err(format!(
"This workspace holds the curriculum of an earlier version of \
cmetal, which kept the tests inside the exercise file, and \
{} has no tests.\n\
Run `cmetal update` to get the current curriculum, or \
`cmetal reset {}` to get the exercise with its tests back.",
self.path.display(),
self.name()
));
}
let repair = if self.legacy_marker.parent().is_some_and(|legacy| {
legacy
.parent()
.is_some_and(|meta| meta.join("manifest.json").exists())
}) {
"Create a complete workspace with `cmetal init <new directory>` \
and copy my_exercises/ and .cmetal-state.txt into it."
} else {
"In a git checkout, `git restore exercises` brings the file back."
};
Err(format!(
"The tests of this exercise are missing: {}\n\
The curriculum files are incomplete. {repair}",
self.test_path.display()
))
}
fn earlier_version_note(&self) -> String {
format!(
"\nNote: {} holds tests of its own. If you started it with an \
earlier version of cmetal, the exercise has changed since then: \
`cmetal diff {name}` shows the differences, and \
`cmetal reset {name}` takes the new exercise (it discards your \
edits).",
self.path.display(),
name = self.name()
)
}
pub fn verify(&self, compiler: &Compiler, build_dir: &Path) -> Result<VerifyResult> {
std::fs::create_dir_all(build_dir)?;
let bin_path = build_dir.join(&self.info.name);
let result = compiler.compile(&self.path, &bin_path, &self.info.flags)?;
if !result.success {
return Ok(VerifyResult {
success: false,
stage: "compilation",
output: result.output,
});
}
let run_result = run_binary(&bin_path)?;
if !run_result.success {
return Ok(VerifyResult {
success: false,
stage: "execution",
output: run_result.output,
});
}
let run_output = run_result.output.clone();
let mut shipped_tests = false;
if self.info.test {
let plan = match self.test_plan() {
Ok(plan) => plan,
Err(message) => {
return Ok(VerifyResult {
success: false,
stage: "test compilation",
output: message,
});
}
};
shipped_tests = plan.shipped;
let note = if plan.own {
self.earlier_version_note()
} else {
String::new()
};
if plan.own {
let own_bin = build_dir.join(format!("{}_own_test", self.info.name));
let result = compiler.compile_with_tests(&self.path, &own_bin, &self.info.flags)?;
if !result.success {
return Ok(VerifyResult {
success: false,
stage: "own test compilation",
output: result.output,
});
}
let own_result = run_binary(&own_bin)?;
if !own_result.success {
return Ok(VerifyResult {
success: false,
stage: "own tests",
output: own_result.output,
});
}
}
if shipped_tests {
let test_bin = build_dir.join(format!("{}_test", self.info.name));
let result = compiler.compile_shipped_tests(
&self.test_path,
&self.path,
&test_bin,
&self.info.flags,
)?;
if !result.success {
return Ok(VerifyResult {
success: false,
stage: "test compilation",
output: result.output + ¬e,
});
}
let test_result = run_binary(&test_bin)?;
if !test_result.success {
return Ok(VerifyResult {
success: false,
stage: "tests",
output: test_result.output + ¬e,
});
}
}
}
if self.info.sanitizers {
let san_bin = build_dir.join(format!("{}_san", self.info.name));
let result =
compiler.compile_with_sanitizers(&self.path, &san_bin, &self.info.flags)?;
if !result.success {
return Ok(VerifyResult {
success: false,
stage: "sanitizer compilation",
output: result.output,
});
}
let san_result = run_binary(&san_bin)?;
if !san_result.success {
return Ok(VerifyResult {
success: false,
stage: "sanitizer check",
output: san_result.output,
});
}
if shipped_tests {
let san_test_bin = build_dir.join(format!("{}_san_test", self.info.name));
let result = compiler.compile_shipped_tests_with_sanitizers(
&self.test_path,
&self.path,
&san_test_bin,
&self.info.flags,
)?;
if !result.success {
return Ok(VerifyResult {
success: false,
stage: "sanitizer compilation",
output: result.output,
});
}
let san_test_result = run_binary(&san_test_bin)?;
if !san_test_result.success {
return Ok(VerifyResult {
success: false,
stage: "sanitizer check",
output: san_test_result.output,
});
}
}
}
Ok(VerifyResult {
success: true,
stage: "complete",
output: run_output,
})
}
}
struct RunResult {
success: bool,
output: String,
}
fn run_binary(path: &Path) -> Result<RunResult> {
run_binary_with_timeout(path, RUN_TIMEOUT)
}
fn run_binary_with_timeout(path: &Path, timeout: Duration) -> Result<RunResult> {
let mut child = Command::new(path)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
let stdout_reader = spawn_pipe_reader(child.stdout.take());
let stderr_reader = spawn_pipe_reader(child.stderr.take());
let deadline = Instant::now() + timeout;
let (status, timed_out) = loop {
if let Some(status) = child.try_wait()? {
break (Some(status), false);
}
if Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
break (None, true);
}
std::thread::sleep(Duration::from_millis(20));
};
let stdout = stdout_reader.join().unwrap_or_default();
let stderr = stderr_reader.join().unwrap_or_default();
let mut combined = String::new();
if !stdout.bytes.is_empty() {
combined.push_str(&String::from_utf8_lossy(&stdout.bytes));
}
if !stderr.bytes.is_empty() {
if !combined.is_empty() {
combined.push('\n');
}
combined.push_str(&String::from_utf8_lossy(&stderr.bytes));
}
if stdout.truncated || stderr.truncated {
if !combined.is_empty() {
combined.push('\n');
}
combined.push_str("[output truncated at 1 MiB per stream]");
}
if timed_out {
if !combined.is_empty() {
combined.push('\n');
}
combined.push_str(&format!(
"Timed out after {} seconds and was killed. \
Is there an infinite loop?",
timeout.as_secs()
));
return Ok(RunResult {
success: false,
output: combined,
});
}
if let Some(signal) = status.and_then(terminating_signal) {
if !combined.is_empty() && !combined.ends_with('\n') {
combined.push('\n');
}
combined.push_str(&describe_signal(signal));
}
Ok(RunResult {
success: status.map(|s| s.success()).unwrap_or(false),
output: combined,
})
}
#[cfg(unix)]
fn terminating_signal(status: std::process::ExitStatus) -> Option<i32> {
std::os::unix::process::ExitStatusExt::signal(&status)
}
#[cfg(not(unix))]
fn terminating_signal(_status: std::process::ExitStatus) -> Option<i32> {
None
}
fn describe_signal(signal: i32) -> String {
let name = match signal {
4 => " (SIGILL, illegal instruction)",
6 => " (SIGABRT, the program called abort)",
8 => " (SIGFPE, arithmetic error such as a division by zero)",
11 => " (SIGSEGV, invalid memory access)",
_ => "",
};
format!("The program crashed: it was killed by signal {signal}{name}.")
}
#[derive(Default)]
struct CapturedOutput {
bytes: Vec<u8>,
truncated: bool,
}
fn spawn_pipe_reader<R: Read + Send + 'static>(
pipe: Option<R>,
) -> std::thread::JoinHandle<CapturedOutput> {
std::thread::spawn(move || {
let mut captured = CapturedOutput::default();
let Some(mut pipe) = pipe else {
return captured;
};
let mut chunk = [0u8; 8192];
loop {
match pipe.read(&mut chunk) {
Ok(0) | Err(_) => break,
Ok(n) => {
let remaining = MAX_CAPTURED_OUTPUT.saturating_sub(captured.bytes.len());
let keep = remaining.min(n);
captured.bytes.extend_from_slice(&chunk[..keep]);
if keep < n {
captured.truncated = true;
}
}
}
}
captured
})
}
#[cfg(test)]
mod tests {
use super::*;
fn find_cc() -> Option<String> {
let candidates = match std::env::var("CC") {
Ok(cc) if !cc.is_empty() => vec![cc],
_ => vec!["gcc".to_string(), "clang".to_string()],
};
candidates.into_iter().find(|cc| {
Command::new(cc)
.arg("--version")
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.map(|s| s.success())
.unwrap_or(false)
})
}
fn compile_snippet(cc: &str, dir: &Path, name: &str, code: &str) -> PathBuf {
let src = dir.join(format!("{name}.c"));
let bin = dir.join(name);
std::fs::write(&src, code).unwrap();
let status = Command::new(cc)
.arg(&src)
.arg("-o")
.arg(&bin)
.status()
.unwrap();
assert!(status.success());
bin
}
macro_rules! require_cc {
() => {
match find_cc() {
Some(cc) => cc,
None => {
eprintln!("skipping: no C compiler available");
return;
}
}
};
}
#[test]
fn infinite_loop_is_killed_and_reported() {
let cc = require_cc!();
let tmp = tempfile::TempDir::new().unwrap();
let bin = compile_snippet(
&cc,
tmp.path(),
"spin",
"int main(void) { volatile int x = 1; while (x) {} }",
);
let start = Instant::now();
let result = run_binary_with_timeout(&bin, Duration::from_secs(1)).unwrap();
assert!(!result.success);
assert!(result.output.contains("Timed out"));
assert!(start.elapsed() < Duration::from_secs(5));
}
#[test]
fn normal_exit_and_output_are_captured() {
let cc = require_cc!();
let tmp = tempfile::TempDir::new().unwrap();
let bin = compile_snippet(
&cc,
tmp.path(),
"hello",
"#include <stdio.h>\nint main(void) { puts(\"hi\"); return 0; }",
);
let result = run_binary(&bin).unwrap();
assert!(result.success);
assert!(result.output.contains("hi"));
}
#[test]
fn large_output_does_not_deadlock() {
let cc = require_cc!();
let tmp = tempfile::TempDir::new().unwrap();
let bin = compile_snippet(
&cc,
tmp.path(),
"chatty",
"#include <stdio.h>\nint main(void) {\n\
for (int i = 0; i < 40000; i++) printf(\"0123456789abcdef\\n\");\n\
return 0; }",
);
let result = run_binary(&bin).unwrap();
assert!(result.success);
assert!(result.output.len() > 500_000);
assert!(!result.output.contains("output truncated"));
}
#[test]
fn output_flood_is_bounded_and_drained() {
let cc = require_cc!();
let tmp = tempfile::TempDir::new().unwrap();
let bin = compile_snippet(
&cc,
tmp.path(),
"flood",
"#include <stdio.h>\nint main(void) {\n\
while (1) puts(\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\");\n\
}",
);
let result = run_binary_with_timeout(&bin, Duration::from_secs(1)).unwrap();
assert!(!result.success);
assert!(result.output.contains("Timed out"));
assert!(result.output.contains("output truncated"));
assert!(result.output.len() <= 2 * MAX_CAPTURED_OUTPUT + 1024);
}
}