| // Copyright 2026 The Fuchsia Authors | |
| // | |
| // Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 | |
| // <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT | |
| // license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. | |
| // This file may not be copied, modified, or distributed except according to | |
| // those terms. | |
| //! Native compiler / UBSan / ASan execution leg (`clang`/`clang++` and | |
| //! optional `gcc`/`g++`). | |
| use std::{ | |
| fmt::Write as _, | |
| fs, | |
| path::{Path, PathBuf}, | |
| process::{Command, Output}, | |
| }; | |
| use crate::{ | |
| corpus::{CorpusCase, Language, ReturnType}, | |
| verdict::{CppScalarValue, LegOutcome}, | |
| }; | |
| /// Prefix emitted by the generated C/C++ harness for normal scalar returns. | |
| pub const COMPILER_RESULT_PREFIX: &str = "ANNEAL_CPP_DIFF_RET:"; | |
| /// Configuration for one native compiler leg (e.g. Clang+UBSan+ASan or | |
| /// GCC+UBSan). | |
| #[derive(Clone, Debug)] | |
| pub struct CompilerLegConfig { | |
| pub label: String, | |
| pub c_compiler: PathBuf, | |
| pub cxx_compiler: PathBuf, | |
| pub enable_asan: bool, | |
| } | |
| /// Render a standalone C11 or C++20 harness that embeds `case.source`, invokes | |
| /// `case.entry` with `case.args`, and prints a tagged canonical scalar value. | |
| pub fn render_harness(case: &CorpusCase) -> Result<String, String> { | |
| let mut out = String::new(); | |
| match case.language { | |
| Language::C11 => { | |
| out.push_str("#include <inttypes.h>\n"); | |
| out.push_str("#include <stdbool.h>\n"); | |
| out.push_str("#include <stdint.h>\n"); | |
| out.push_str("#include <stdio.h>\n\n"); | |
| } | |
| Language::Cpp20 => { | |
| out.push_str("#include <cinttypes>\n"); | |
| out.push_str("#include <cstdint>\n"); | |
| out.push_str("#include <cstdio>\n\n"); | |
| } | |
| } | |
| out.push_str(&case.source); | |
| if !case.source.ends_with('\n') { | |
| out.push('\n'); | |
| } | |
| let mut arg_exprs = Vec::with_capacity(case.args.len()); | |
| for arg in &case.args { | |
| arg_exprs.push(arg.to_c_expr()?); | |
| } | |
| let call_expr = format!("{}({})", case.entry, arg_exprs.join(", ")); | |
| let printf = match case.language { | |
| Language::C11 => "printf", | |
| Language::Cpp20 => "std::printf", | |
| }; | |
| out.push_str("\nint main(void) {\n"); | |
| match case.return_type { | |
| ReturnType::Void => { | |
| let _ = writeln!(out, " {call_expr};"); | |
| let _ = writeln!(out, " {printf}(\"{COMPILER_RESULT_PREFIX}void\\n\");"); | |
| } | |
| ReturnType::Bool => { | |
| let _ = writeln!(out, " bool ret = {call_expr};"); | |
| let _ = writeln!( | |
| out, | |
| " {printf}(\"{COMPILER_RESULT_PREFIX}bool:%s\\n\", ret ? \"true\" : \"false\");" | |
| ); | |
| } | |
| ReturnType::I8 => { | |
| let _ = writeln!(out, " int8_t ret = {call_expr};"); | |
| let _ = writeln!( | |
| out, | |
| " {printf}(\"{COMPILER_RESULT_PREFIX}int:w8:signed:%\" PRIu8 \"\\n\", (uint8_t)ret);" | |
| ); | |
| } | |
| ReturnType::U8 => { | |
| let _ = writeln!(out, " uint8_t ret = {call_expr};"); | |
| let _ = writeln!( | |
| out, | |
| " {printf}(\"{COMPILER_RESULT_PREFIX}int:w8:unsigned:%\" PRIu8 \"\\n\", ret);" | |
| ); | |
| } | |
| ReturnType::U16 => { | |
| let _ = writeln!(out, " uint16_t ret = {call_expr};"); | |
| let _ = writeln!( | |
| out, | |
| " {printf}(\"{COMPILER_RESULT_PREFIX}int:w16:unsigned:%\" PRIu16 \"\\n\", ret);" | |
| ); | |
| } | |
| ReturnType::I32 => { | |
| let _ = writeln!(out, " int32_t ret = {call_expr};"); | |
| let _ = writeln!( | |
| out, | |
| " {printf}(\"{COMPILER_RESULT_PREFIX}int:w32:signed:%\" PRIu32 \"\\n\", (uint32_t)ret);" | |
| ); | |
| } | |
| ReturnType::U32 => { | |
| let _ = writeln!(out, " uint32_t ret = {call_expr};"); | |
| let _ = writeln!( | |
| out, | |
| " {printf}(\"{COMPILER_RESULT_PREFIX}int:w32:unsigned:%\" PRIu32 \"\\n\", ret);" | |
| ); | |
| } | |
| ReturnType::I64 => { | |
| let _ = writeln!(out, " int64_t ret = {call_expr};"); | |
| let _ = writeln!( | |
| out, | |
| " {printf}(\"{COMPILER_RESULT_PREFIX}int:w64:signed:%\" PRIu64 \"\\n\", (uint64_t)ret);" | |
| ); | |
| } | |
| ReturnType::U64 => { | |
| let _ = writeln!(out, " uint64_t ret = {call_expr};"); | |
| let _ = writeln!( | |
| out, | |
| " {printf}(\"{COMPILER_RESULT_PREFIX}int:w64:unsigned:%\" PRIu64 \"\\n\", ret);" | |
| ); | |
| } | |
| } | |
| out.push_str(" return 0;\n}\n"); | |
| Ok(out) | |
| } | |
| /// Classify raw process execution output from a sanitizer-instrumented binary. | |
| pub fn classify_run_output(output: &Output) -> LegOutcome { | |
| let stdout = String::from_utf8_lossy(&output.stdout); | |
| let stderr = String::from_utf8_lossy(&output.stderr); | |
| #[cfg(unix)] | |
| let signal = { | |
| use std::os::unix::process::ExitStatusExt; | |
| output.status.signal() | |
| }; | |
| #[cfg(not(unix))] | |
| let signal: Option<i32> = None; | |
| classify_exit(output.status.code(), signal, &stdout, &stderr) | |
| } | |
| /// Hardware fault signals that directly witness C/C++ UB traps without relying | |
| /// on `SIGABRT` (which sanitizer startup failures can also raise under | |
| /// `ASAN_OPTIONS=abort_on_error=1`) or external kills (`SIGKILL`/`SIGTERM`). | |
| fn is_ub_fault_signal(sig: i32) -> bool { | |
| // POSIX x86_64/Linux signal numbers: | |
| // 4=SIGILL, 5=SIGTRAP, 7=SIGBUS, 8=SIGFPE, 11=SIGSEGV. | |
| matches!(sig, 4 | 5 | 7 | 8 | 11) | |
| } | |
| /// Detect sanitizer initialization, shadow-memory, or internal-check failures | |
| /// that represent host/environment failures rather than program UB. | |
| pub fn is_sanitizer_startup_error(stderr: &str) -> bool { | |
| stderr.lines().any(|line| { | |
| line.contains("Shadow memory range interleaves") | |
| || line.contains("failed to allocate") | |
| || line.contains("CHECK failed") | |
| || line.contains("failed to initialize") | |
| }) | |
| } | |
| /// Classify a native harness exit from its exit code, optional Unix signal, | |
| /// stdout, and stderr. | |
| pub fn classify_exit( | |
| exit_code: Option<i32>, | |
| signal: Option<i32>, | |
| stdout: &str, | |
| stderr: &str, | |
| ) -> LegOutcome { | |
| // Fail closed on sanitizer startup/internal errors before checking signals | |
| // so `ASAN_OPTIONS=abort_on_error=1` (`SIGABRT`) never looks like UB. | |
| if is_sanitizer_startup_error(stderr) { | |
| return LegOutcome::ToolError { | |
| detail: format!("sanitizer startup/internal failure: {}", first_lines(stderr, 4)), | |
| }; | |
| } | |
| if let Some(diag) = detect_sanitizer_ub(stderr) { | |
| return LegOutcome::UndefinedBehavior { detail: diag }; | |
| } | |
| if exit_code != Some(0) { | |
| if let Some(sig) = signal { | |
| let sig_info = format!("terminated by signal {sig}"); | |
| if is_ub_fault_signal(sig) { | |
| let detail = if stderr.trim().is_empty() { | |
| sig_info | |
| } else { | |
| format!("{sig_info}: {}", first_nonempty_line(stderr)) | |
| }; | |
| return LegOutcome::UndefinedBehavior { detail }; | |
| } | |
| return LegOutcome::ToolError { | |
| detail: format!( | |
| "harness killed by non-UB signal ({sig_info}): {}", | |
| first_lines(stderr, 4) | |
| ), | |
| }; | |
| } | |
| let code_info = match exit_code { | |
| Some(c) => format!("exit code {c}"), | |
| None => "abnormal termination".to_owned(), | |
| }; | |
| return LegOutcome::ToolError { | |
| detail: format!("harness exited abnormally ({code_info}): {}", first_lines(stderr, 4)), | |
| }; | |
| } | |
| for line in stdout.lines() { | |
| if let Some(rest) = line.strip_prefix(COMPILER_RESULT_PREFIX) { | |
| return match CppScalarValue::parse_tagged(rest) { | |
| Ok(value) => LegOutcome::Returned { value }, | |
| Err(e) => LegOutcome::ToolError { | |
| detail: format!("failed to parse compiler output {rest:?}: {e}"), | |
| }, | |
| }; | |
| } | |
| } | |
| LegOutcome::ToolError { | |
| detail: format!( | |
| "harness succeeded without {COMPILER_RESULT_PREFIX} line (stdout={:?})", | |
| first_lines(stdout, 3) | |
| ), | |
| } | |
| } | |
| /// Detect confirmed UBSan or ASan runtime bug diagnostics in stderr. | |
| /// | |
| /// Startup, shadow-memory, and internal sanitizer check failures return `None` | |
| /// so callers fail closed as `LegOutcome::ToolError` rather than mistaking | |
| /// environment failures for UB. | |
| pub fn detect_sanitizer_ub(stderr: &str) -> Option<String> { | |
| if is_sanitizer_startup_error(stderr) { | |
| return None; | |
| } | |
| for line in stderr.lines() { | |
| if line.contains("runtime error:") | |
| || line.contains("ERROR: AddressSanitizer:") | |
| || line.contains("ERROR: UndefinedBehaviorSanitizer:") | |
| { | |
| return Some(line.trim().to_owned()); | |
| } | |
| } | |
| None | |
| } | |
| /// Compile and execute one corpus case under `cfg` inside `work_dir`. | |
| pub fn run_compiler_case( | |
| cfg: &CompilerLegConfig, | |
| case: &CorpusCase, | |
| work_dir: &Path, | |
| ) -> LegOutcome { | |
| let leg_dir = work_dir.join(format!("cc_{}", cfg.label)); | |
| if let Err(e) = fs::create_dir_all(&leg_dir) { | |
| return LegOutcome::ToolError { | |
| detail: format!("cannot create {}: {e}", leg_dir.display()), | |
| }; | |
| } | |
| let harness_src = match render_harness(case) { | |
| Ok(s) => s, | |
| Err(detail) => return LegOutcome::ToolError { detail }, | |
| }; | |
| let src_path = leg_dir.join(format!("{}.{}", case.id, case.language.extension())); | |
| let bin_path = leg_dir.join(format!("{}.bin", case.id)); | |
| if let Err(e) = fs::write(&src_path, &harness_src) { | |
| return LegOutcome::ToolError { | |
| detail: format!("cannot write {}: {e}", src_path.display()), | |
| }; | |
| } | |
| let compiler = match case.language { | |
| Language::C11 => &cfg.c_compiler, | |
| Language::Cpp20 => &cfg.cxx_compiler, | |
| }; | |
| let sanitizer_flag = | |
| if cfg.enable_asan { "-fsanitize=undefined,address" } else { "-fsanitize=undefined" }; | |
| let mut compile_cmd = Command::new(compiler); | |
| compile_cmd.args(["-O0", "-g", sanitizer_flag, "-fno-sanitize-recover=all"]); | |
| for flag in case.all_flags() { | |
| compile_cmd.arg(flag); | |
| } | |
| compile_cmd.arg(&src_path).arg("-o").arg(&bin_path); | |
| let compile_out = match compile_cmd.output() { | |
| Ok(o) => o, | |
| Err(e) => { | |
| return LegOutcome::ToolError { | |
| detail: format!("failed to spawn {}: {e}", compiler.display()), | |
| }; | |
| } | |
| }; | |
| if !compile_out.status.success() { | |
| let stderr = String::from_utf8_lossy(&compile_out.stderr); | |
| return LegOutcome::CompileError { detail: first_lines(&stderr, 6) }; | |
| } | |
| let run_out = match Command::new(&bin_path) | |
| .env("UBSAN_OPTIONS", "print_stacktrace=0:halt_on_error=1") | |
| .env("ASAN_OPTIONS", "detect_leaks=0:abort_on_error=1") | |
| .output() | |
| { | |
| Ok(o) => o, | |
| Err(e) => { | |
| return LegOutcome::ToolError { | |
| detail: format!("failed to execute {}: {e}", bin_path.display()), | |
| }; | |
| } | |
| }; | |
| classify_run_output(&run_out) | |
| } | |
| fn first_nonempty_line(s: &str) -> String { | |
| s.lines().find(|l| !l.trim().is_empty()).unwrap_or("").trim().to_owned() | |
| } | |
| fn first_lines(s: &str, max_lines: usize) -> String { | |
| s.lines().take(max_lines).collect::<Vec<_>>().join(" | ") | |
| } |