From a4466cc726f1abfbcdefbf34ea84cb10f7e7b45f Mon Sep 17 00:00:00 2001 From: LunaStev Date: Wed, 21 Oct 2026 19:43:49 +0900 Subject: [PATCH 1/8] fix(cli): handle reporting failures and preserve diagnostic context Handle broken stdout without panicking or hiding artifact command failures, escape control characters only at the diagnostic rendering boundary, and identify each link byte-limit flag correctly. Refs #310, #316, #322 Signed-off-by: LunaStev --- README.md | 6 +- diagnostic/src/lib.rs | 63 ++++++++++++++++- src/cli.rs | 2 + src/commands/asm.rs | 11 +-- src/commands/debug.rs | 2 + src/commands/input.rs | 6 +- src/commands/linker.rs | 12 ++-- src/commands/mod.rs | 2 + src/commands/object.rs | 11 +-- src/commands/report.rs | 30 ++++++++ tests/cli_io.rs | 147 +++++++++++++++++++++++++++++++++++++++ tests/static_link_cli.rs | 40 +++++++++++ 12 files changed, 308 insertions(+), 24 deletions(-) create mode 100644 src/commands/report.rs diff --git a/README.md b/README.md index 4e87455..c3c8666 100644 --- a/README.md +++ b/README.md @@ -156,8 +156,10 @@ The reader consumes at most N + 1 bytes, including for growing or streamed files. This budget is independent of assembly reservation and ELF output limits. Oversized or invalid UTF-8 assembly input preserves an existing output file. -IR stdout writes are fallible: a closed pipe exits successfully, and other write -errors exit with status 1 and a diagnostic. Canonical IR and scalar results +CLI stdout writes are fallible: a closed pipe does not cause a panic, and other +write errors exit with status 1 and a diagnostic. Assembly, object and link +reporting continues after a closed pipe, preserving completed artifacts and +real command failures. Successful IR output also treats a closed pipe as success. Canonical IR and scalar results retain their normal stdout format. `-o` still publishes atomically. The optional Wave bootstrap likewise replaces its archive only after successful creation, preserving the previous archive on an archiver failure. diff --git a/diagnostic/src/lib.rs b/diagnostic/src/lib.rs index 16f6cad..c0a68ff 100644 --- a/diagnostic/src/lib.rs +++ b/diagnostic/src/lib.rs @@ -66,16 +66,36 @@ impl ToDiagnostic for Diagnostic { } } +// Keep ordinary Unicode paths readable while preventing names from creating +// new terminal lines or control sequences. Structured contexts stay lossless. +struct ContextName<'a>(&'a str); + +impl fmt::Display for ContextName<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + use fmt::Write; + for character in self.0.chars() { + if character.is_control() { + write!(f, "{}", character.escape_debug())?; + } else { + f.write_char(character)?; + } + } + Ok(()) + } +} + impl fmt::Display for Diagnostic { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}: {}", self.code, self.message)?; for context in &self.contexts { match context { - Context::Source(s) => write!(f, " at {}:{}:{}", s.source, s.line, s.column)?, + Context::Source(s) => { + write!(f, " at {}:{}:{}", ContextName(&s.source), s.line, s.column)? + }, Context::Object { name, member } => { - write!(f, " in {name}")?; + write!(f, " in {}", ContextName(name))?; if let Some(m) = member { - write!(f, "({m})")?; + write!(f, "({})", ContextName(m))?; } }, Context::Input(i) => write!(f, " input {i}")?, @@ -118,3 +138,40 @@ mod tests { assert_eq!(d.code, "invalid-index"); } } + +#[cfg(test)] +mod control_tests { + use super::*; + + #[test] + fn context_names_escape_controls_without_changing_structured_fields() { + for control in ['\n', '\r', '\t', '\x1b'] { + let name = format!("경로/{control}file"); + let d = Diagnostic::new("audit", "read", "audit.invalid", "invalid") + .with_context(Context::Source(SourceLocation { + source: name.clone(), + line: 2, + column: 3, + ..Default::default() + })) + .with_context(Context::Object { name: name.clone(), member: Some(name.clone()) }); + let original = d.clone(); + let rendered = d.to_string(); + assert!(!rendered.contains(control), "{rendered:?}"); + assert!(rendered.contains("경로/")); + assert!(rendered.contains(":2:3")); + assert!(rendered.contains(&control.escape_debug().to_string())); + assert_eq!(d, original); + assert_eq!(d.diagnostic(), original); + } + let d = Diagnostic::new("audit", "read", "audit.invalid", "invalid").with_context( + Context::Source(SourceLocation { + source: "경로/café.s".into(), + line: 4, + column: 5, + ..Default::default() + }), + ); + assert_eq!(d.to_string(), "audit.invalid: invalid at 경로/café.s:4:5"); + } +} diff --git a/src/cli.rs b/src/cli.rs index 751a0f2..0425de7 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -1,3 +1,5 @@ +use crate::commands::report::println; + use std::env; use crate::commands; diff --git a/src/commands/asm.rs b/src/commands/asm.rs index 02041ec..55d05cd 100644 --- a/src/commands/asm.rs +++ b/src/commands/asm.rs @@ -1,3 +1,5 @@ +use super::report::println; + use std::process; use std::time::Instant; @@ -93,10 +95,11 @@ pub fn run(args: Vec) { eprintln!("Error: --max-input requires a decimal byte count"); process::exit(1); }); - max_input = Some(super::input::byte_limit(limit).unwrap_or_else(|e| { - eprintln!("Error: {e}"); - process::exit(1); - })); + max_input = + Some(super::input::byte_limit(limit, "--max-input").unwrap_or_else(|e| { + eprintln!("Error: {e}"); + process::exit(1); + })); i += 1; }, diff --git a/src/commands/debug.rs b/src/commands/debug.rs index b2f1cb3..89ae9f2 100644 --- a/src/commands/debug.rs +++ b/src/commands/debug.rs @@ -1,3 +1,5 @@ +use super::report::{print, println}; + pub(super) fn dump_bytes( label: &str, bytes: &[u8], diff --git a/src/commands/input.rs b/src/commands/input.rs index b8e9edd..fdd2b1f 100644 --- a/src/commands/input.rs +++ b/src/commands/input.rs @@ -8,15 +8,15 @@ pub(super) const ASM_INPUT_BYTES: u64 = 8 * 1024 * 1024; pub(super) const OBJECT_INPUT_BYTES: u64 = 256 * 1024 * 1024; -pub(super) fn byte_limit(value: &str) -> Result { +pub(super) fn byte_limit(value: &str, flag: &str) -> Result { if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) { - return Err("--max-input requires a decimal byte count"); + return Err(format!("{flag} requires a decimal byte count")); } value .parse::() .ok() .filter(|v| *v < usize::MAX as u64) - .ok_or("--max-input byte count exceeds host capacity") + .ok_or_else(|| format!("{flag} byte count exceeds host capacity")) } pub(super) fn read(path: &Path, limit: u64) -> io::Result> { diff --git a/src/commands/linker.rs b/src/commands/linker.rs index 97d8e13..aec530b 100644 --- a/src/commands/linker.rs +++ b/src/commands/linker.rs @@ -1,3 +1,5 @@ +use super::report::println; + use linker::{core::linker::OutputFormat, Linker}; use std::{path::Path, process}; @@ -40,18 +42,12 @@ fn execute(args: Vec) -> Result<(), String> { } }, "--max-input" => { - if input_limit - .replace(super::input::byte_limit(&value).map_err(str::to_owned)?) - .is_some() - { + if input_limit.replace(super::input::byte_limit(&value, flag)?).is_some() { return Err("duplicate --max-input".into()); } }, _ => { - if output_limit - .replace(super::input::byte_limit(&value).map_err(str::to_owned)?) - .is_some() - { + if output_limit.replace(super::input::byte_limit(&value, flag)?).is_some() { return Err("duplicate --max-output".into()); } }, diff --git a/src/commands/mod.rs b/src/commands/mod.rs index c9f972e..d663360 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -17,3 +17,5 @@ pub mod reverse; mod reverse_graph; mod reverse_render; + +pub(crate) mod report; diff --git a/src/commands/object.rs b/src/commands/object.rs index c815b11..3ae5482 100644 --- a/src/commands/object.rs +++ b/src/commands/object.rs @@ -1,3 +1,5 @@ +use super::report::println; + use object::{ObjectFile, ObjectFormat, ObjectSymbol, SectionKind, SymbolBinding}; use std::process; @@ -53,10 +55,11 @@ pub fn run(args: Vec) { eprintln!("Error: --max-input requires a decimal byte count"); process::exit(1); }); - max_input = Some(super::input::byte_limit(limit).unwrap_or_else(|e| { - eprintln!("Error: {e}"); - process::exit(1); - })); + max_input = + Some(super::input::byte_limit(limit, "--max-input").unwrap_or_else(|e| { + eprintln!("Error: {e}"); + process::exit(1); + })); i += 1; }, "--bytes" => show_bytes = true, diff --git a/src/commands/report.rs b/src/commands/report.rs new file mode 100644 index 0000000..9627c54 --- /dev/null +++ b/src/commands/report.rs @@ -0,0 +1,30 @@ +//! Fallible stdout boundary for CLI status, help and debug reporting. +use std::{ + fmt, + io::{self, Write}, +}; + +pub(crate) fn write(arguments: fmt::Arguments<'_>) { + let mut stdout = io::stdout().lock(); + if let Err(error) = stdout.write_fmt(arguments).and_then(|_| stdout.flush()) { + // Reporting is optional when the reader closes its pipe. Continue the + // command so artifacts and genuine command failures keep their policy. + if error.kind() != io::ErrorKind::BrokenPipe { + eprintln!("Error: failed to write stdout: {error}"); + std::process::exit(1); + } + } +} + +macro_rules! print { + ($($argument:tt)*) => { $crate::commands::report::write(format_args!($($argument)*)) }; +} + +macro_rules! println { + () => { $crate::commands::report::write(format_args!("\n")) }; + ($($argument:tt)*) => { $crate::commands::report::write(format_args!("{}\n", format_args!($($argument)*))) }; +} + +pub(crate) use print; + +pub(crate) use println; diff --git a/tests/cli_io.rs b/tests/cli_io.rs index 09bd60d..fdc4beb 100644 --- a/tests/cli_io.rs +++ b/tests/cli_io.rs @@ -151,3 +151,150 @@ fn ordinary_ir_stdout_failure_is_a_diagnostic() { assert!(diagnostic.contains("failed to write stdout"), "{diagnostic}"); assert!(!diagnostic.contains("panicked")); } + +#[cfg(unix)] +fn closed_stdout(command: &mut Command) -> std::process::Output { + use std::{os::fd::OwnedFd, os::unix::net::UnixStream}; + let (reader, writer) = UnixStream::pair().unwrap(); + drop(reader); + command.stdout(Stdio::from(OwnedFd::from(writer))).output().unwrap() +} + +#[cfg(unix)] +#[test] +fn closed_artifact_stdout_preserves_completed_output_without_panicking() { + let directory = tempfile::tempdir().unwrap(); + let input = directory.path().join("input"); + let object = directory.path().join("out.o"); + let executable = directory.path().join("app"); + fs::write(&input, "section .text\nglobal _start\n_start: ret\n").unwrap(); + for mode in ["asm", "object"] { + for debug in [false, true] { + let mut command = Command::new(env!("CARGO_BIN_EXE_whale")); + command.arg(mode); + if mode == "asm" { + command.arg("--amd64"); + } + command.arg(&input).arg("-o").arg(&object); + if debug { + command.args([ + "--debug-whale", + "--bytes", + "--dump-hex", + "--dump-bin", + "--dump-json", + "--stats", + "--trace", + ]); + if mode == "asm" { + command.arg("--ast"); + } + } + let result = closed_stdout(&mut command); + assert!(result.status.success(), "{mode} debug={debug}: {result:?}"); + assert!(result.stderr.is_empty(), "{result:?}"); + assert!(fs::read(&object).unwrap().starts_with(b"\x7fELF")); + } + } + // Reassemble the entry after the raw-object cases before testing linking. + assert!(Command::new(env!("CARGO_BIN_EXE_whale")) + .args(["asm", "--amd64"]) + .arg(&input) + .arg("-o") + .arg(&object) + .output() + .unwrap() + .status + .success()); + let result = closed_stdout( + Command::new(env!("CARGO_BIN_EXE_whale")) + .arg("link") + .arg(&object) + .arg("-o") + .arg(&executable), + ); + assert!(result.status.success(), "{result:?}"); + assert!(result.stderr.is_empty(), "{result:?}"); + assert!(fs::read(executable).unwrap().starts_with(b"\x7fELF")); +} + +#[cfg(unix)] +#[test] +fn closed_help_stdout_and_real_command_failures_keep_their_exit_policy() { + for arguments in [ + vec!["--help"], + vec!["--version"], + vec!["asm", "--help"], + vec!["object", "--help"], + vec!["link", "--help"], + ] { + let result = closed_stdout(Command::new(env!("CARGO_BIN_EXE_whale")).args(&arguments)); + assert!(result.status.success(), "{arguments:?}: {result:?}"); + assert!(result.stderr.is_empty(), "{result:?}"); + } + let directory = tempfile::tempdir().unwrap(); + let input = directory.path().join("invalid"); + let output = directory.path().join("existing.o"); + fs::write(&input, "not_an_instruction\n").unwrap(); + fs::write(&output, b"previous").unwrap(); + for arguments in [vec!["asm", "--amd64", "--trace"], vec!["link"], vec!["unknown"]] { + let result = closed_stdout( + Command::new(env!("CARGO_BIN_EXE_whale")) + .args(&arguments) + .arg(&input) + .arg("-o") + .arg(&output), + ); + assert!(!result.status.success(), "{arguments:?}: {result:?}"); + let diagnostic = String::from_utf8_lossy(&result.stderr); + assert!(!diagnostic.contains("panicked"), "{diagnostic}"); + assert!(!diagnostic.contains("Broken pipe"), "{diagnostic}"); + assert_eq!(fs::read(&output).unwrap(), b"previous"); + } +} + +#[cfg(target_os = "linux")] +#[test] +fn ordinary_artifact_stdout_failures_are_diagnostics() { + for command in ["asm", "object", "link"] { + let full = fs::OpenOptions::new().write(true).open("/dev/full").unwrap(); + let result = Command::new(env!("CARGO_BIN_EXE_whale")) + .args([command, "--help"]) + .stdout(full) + .output() + .unwrap(); + assert_eq!(result.status.code(), Some(1)); + let diagnostic = String::from_utf8_lossy(&result.stderr); + assert!(diagnostic.contains("failed to write stdout"), "{diagnostic}"); + assert!(!diagnostic.contains("panicked"), "{diagnostic}"); + } +} + +#[test] +fn assembly_and_object_limit_errors_still_name_max_input() { + let directory = tempfile::tempdir().unwrap(); + let output = directory.path().join("previous.o"); + fs::write(&output, b"previous").unwrap(); + for mode in ["asm", "object"] { + for (value, message) in [ + ("nope", "--max-input requires a decimal byte count"), + ("18446744073709551615", "--max-input byte count exceeds host capacity"), + ] { + let mut command = Command::new(env!("CARGO_BIN_EXE_whale")); + command.arg(mode); + if mode == "asm" { + command.arg("--amd64"); + } + let result = command + .arg("missing") + .arg("-o") + .arg(&output) + .args(["--max-input", value]) + .output() + .unwrap(); + assert_eq!(result.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&result.stderr).contains(message), "{result:?}"); + assert_eq!(fs::read(&output).unwrap(), b"previous"); + } + } +} diff --git a/tests/static_link_cli.rs b/tests/static_link_cli.rs index 2f377ef..2891502 100644 --- a/tests/static_link_cli.rs +++ b/tests/static_link_cli.rs @@ -119,3 +119,43 @@ fn unsupported_user_address_extent_fails_before_output_publication() { assert!(String::from_utf8_lossy(&result.stderr).contains("user address"), "{result:?}"); assert_eq!(fs::read(&output).unwrap(), b"old executable"); } + +#[test] +fn byte_limit_diagnostics_name_the_offending_flag_before_publication() { + let dir = tempfile::tempdir().unwrap(); + let output = dir.path().join("existing"); + fs::write(&output, b"previous").unwrap(); + for flag in ["--max-input", "--max-output"] { + for (value, message) in [ + ("nope", "requires a decimal byte count"), + ("18446744073709551615", "byte count exceeds host capacity"), + ] { + let result = whale() + .args(["link", "missing.o", "-o"]) + .arg(&output) + .args([flag, value]) + .output() + .unwrap(); + assert_eq!(result.status.code(), Some(1)); + assert!( + String::from_utf8_lossy(&result.stderr).contains(&format!("{flag} {message}")), + "{result:?}" + ); + assert_eq!(fs::read(&output).unwrap(), b"previous"); + } + } + let input = assemble(dir.path(), "entry", "section .text\nglobal _start\n_start: ret\n"); + let result = whale() + .arg("link") + .arg(input) + .arg("-o") + .arg(&output) + .args(["--max-output", "0"]) + .output() + .unwrap(); + assert!(!result.status.success()); + let diagnostic = String::from_utf8_lossy(&result.stderr); + assert!(!diagnostic.contains("decimal byte count"), "{diagnostic}"); + assert!(!diagnostic.contains("host capacity"), "{diagnostic}"); + assert_eq!(fs::read(output).unwrap(), b"previous"); +} From af18a598624d9f4a0288e2ae15a959c750ebc8f1 Mon Sep 17 00:00:00 2001 From: LunaStev Date: Wed, 21 Oct 2026 19:40:47 +0900 Subject: [PATCH 2/8] fix(backend-api): enforce portable artifact path sets Reject component ancestor conflicts and ASCII case collisions in either order, and validate Windows-compatible path components before returning artifacts. Preserve valid Unicode paths and original display spelling. Refs #311, #312, #313 Signed-off-by: LunaStev --- backend-api/src/lib.rs | 155 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 145 insertions(+), 10 deletions(-) diff --git a/backend-api/src/lib.rs b/backend-api/src/lib.rs index 1eb1023..4a814bc 100644 --- a/backend-api/src/lib.rs +++ b/backend-api/src/lib.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: MPL-2.0 //! Statically linked, out-of-tree code generation. This is a Rust API, not a dylib ABI. use diagnostic::{Context, Diagnostic, ToDiagnostic}; -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; use target_spec::TargetSpec; pub enum Requirement<'a> { @@ -22,7 +22,10 @@ pub enum Support { } pub struct Artifact { - /// Relative portable path. Validated before returning artifacts to callers. + /// Relative portable path, with Windows-compatible components. Paths in one + /// artifact set must be distinct under ASCII case folding and cannot be + /// component-wise ancestors of one another. Unicode case folding is not applied. + /// Validated before returning artifacts to callers. pub name: String, pub bytes: Vec, } @@ -155,23 +158,63 @@ pub fn compile( ) -> Result, Vec> { let checked = check(backend, module, target, limits)?; let artifacts = backend.emit(&checked)?; - let mut names = BTreeSet::new(); if artifacts.is_empty() { return Err(vec![artifact_error("backend emitted no artifacts")]); } + let mut names = BTreeMap::::new(); for artifact in &artifacts { - if artifact.name.is_empty() - || artifact.name.contains(['\\', ':']) - || artifact.name.chars().any(char::is_control) - || artifact.name.split('/').any(|part| part.is_empty() || part == "." || part == "..") - || !names.insert(&artifact.name) - { - return Err(vec![artifact_error("invalid or duplicate artifact path")]); + if !artifact.name.split('/').all(portable_component) { + return Err(vec![artifact_error(&format!( + "invalid artifact path {:?}", + artifact.name + ))]); + } + let folded = artifact.name.to_ascii_lowercase(); + // Prefixes must end at a component boundary: `out` and `out2/a.o` + // are independent files. Check both orders without comparing every pair. + let ancestor = folded.match_indices('/').find_map(|(at, _)| names.get(&folded[..at])); + let prefix = format!("{folded}/"); + let descendant = names + .range(prefix.clone()..) + .next() + .filter(|(name, _)| name.starts_with(&prefix)) + .map(|(_, name)| name); + if let Some(other) = names.get(&folded).or(ancestor).or(descendant) { + return Err(vec![artifact_error(&format!( + "artifact path {:?} conflicts with {:?}", + artifact.name, other + ))]); } + names.insert(folded, &artifact.name); } Ok(artifacts) } +fn portable_component(part: &str) -> bool { + if part.is_empty() + || part == "." + || part == ".." + || part.ends_with(['.', ' ']) + || part + .chars() + .any(|c| c.is_control() || matches!(c, '\\' | ':' | '<' | '>' | '"' | '|' | '?' | '*')) + { + return false; + } + // Windows also ignores spaces before the extension when recognizing devices. + let basename = part.split('.').next().expect("nonempty component").trim_end_matches(' '); + let reserved = ["CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$"] + .iter() + .any(|name| basename.eq_ignore_ascii_case(name)); + let numbered = basename.get(..3).is_some_and(|prefix| { + prefix.eq_ignore_ascii_case("COM") || prefix.eq_ignore_ascii_case("LPT") + }) && matches!( + basename.get(3..), + Some("1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³") + ); + !reserved && !numbered +} + fn artifact_error(message: &str) -> Diagnostic { Diagnostic::new("backend", "emit", "backend.artifact", message) } @@ -268,4 +311,96 @@ mod tests { let p = probe(Support::Expanded); assert_eq!(compile(&p, &m, &t, ir::IrLimits::default()).unwrap()[0].bytes, [42]); } + fn compile_names(names: &[&str]) -> Result, Vec> { + let m = module(); + let t = ir::Target::X86_64WhaleLinux.specification(); + let mut p = probe(Support::Direct); + p.names = names.iter().map(|s| (*s).to_owned()).collect(); + compile(&p, &m, &t, ir::IrLimits::default()) + } + + #[test] + fn artifact_ancestors_and_ascii_case_collisions_fail_in_either_order() { + for (a, b) in [ + ("out", "out/module.o"), + ("a/b", "a/b/c.o"), + ("OUT.o", "out.o"), + ("Dir/a.o", "dir/A.o"), + ("Dir", "dir/module.o"), + ] { + for names in [[a, b], [b, a]] { + let errors = compile_names(&names).err().unwrap(); + assert_eq!(errors[0].code, "backend.artifact"); + assert!(errors[0].message.contains(a), "{}", errors[0]); + assert!(errors[0].message.contains(b), "{}", errors[0]); + } + } + // A non-ancestor sorting between a path and its child must not hide it. + assert!(compile_names(&["a", "a-b", "a/b.o"]).is_err()); + assert!(compile_names(&["a/b.o", "a-b", "a"]).is_err()); + } + + #[test] + fn every_artifact_component_must_be_portable() { + for part in [ + "CON", + "con.txt", + "CON .txt", + "COM1 .o", + "LPT9 .obj", + "NUL .txt", + "PrN", + "NUL.txt", + "AUX", + "COM1.obj", + "lpt9", + "COM¹", + "lpt².txt", + "CONIN$", + "CONOUT$.txt", + "out?.o", + "a|b.o", + "ab", + "a*b", + "a\"b", + "a:b", + "out.o.", + "out.o ", + "bad\nname", + "bad\0name", + "bad\u{85}name", + ] { + for name in [part.to_owned(), format!("valid/{part}/file.o")] { + let errors = compile_names(&[&name]).err().unwrap(); + assert_eq!(errors[0].code, "backend.artifact", "{name:?}"); + } + } + for number in 1..=9 { + for prefix in ["COM", "lPt"] { + assert!(compile_names(&[&format!("{prefix}{number}.obj")]).is_err()); + } + } + } + + #[test] + fn valid_artifact_names_keep_their_original_spelling() { + let names = [ + "out", + "out2/module.o", + "Dir/a.o", + "dir/B.o", + "한글/λ.o", + "Ä.o", + "ä.o", + "COM0", + "COM10", + "LPT0.txt", + "NULled.o", + "CON name.txt", + "COM10 .o", + ]; + let artifacts = compile_names(&names).unwrap(); + assert_eq!(artifacts.iter().map(|a| a.name.as_str()).collect::>(), names); + } } From b0f09839a4390f93d57bfc3d43b859ab07fe7d21 Mon Sep 17 00:00:00 2001 From: LunaStev Date: Wed, 21 Oct 2026 19:41:33 +0900 Subject: [PATCH 3/8] fix(linker): preserve archive objects and account for member names Resolve #320 and #321 by recognizing exact BSD index names and charging member-name inspection plus ownership to cumulative reader limits. Signed-off-by: LunaStev --- linker/src/core/archive.rs | 25 +++++++-- linker/tests/archives.rs | 112 +++++++++++++++++++++++++++++++++++++ 2 files changed, 133 insertions(+), 4 deletions(-) diff --git a/linker/src/core/archive.rs b/linker/src/core/archive.rs index 21ba4c9..4268ce6 100644 --- a/linker/src/core/archive.rs +++ b/linker/src/core/archive.rs @@ -8,7 +8,7 @@ pub struct ArchiveMember<'a> { } pub fn read_archive(bytes: &[u8]) -> Result>, String> { - parse_archive(bytes, 1024 * 1024, 512 * 1024 * 1024).map(|(members, _, _)| members) + parse_archive(bytes, 1024 * 1024, usize::MAX, 512 * 1024 * 1024).map(|(members, _, _)| members) } fn charge_archive(work: &mut usize, amount: usize, limit: usize) -> Result<(), String> { @@ -22,6 +22,7 @@ fn charge_archive(work: &mut usize, amount: usize, limit: usize) -> Result<(), S fn parse_archive( bytes: &[u8], max_names: usize, + max_strings: usize, max_work: usize, ) -> Result<(Vec>, usize, usize), String> { if !bytes.starts_with(b"!\n") { @@ -35,6 +36,7 @@ fn parse_archive( let mut cursor = 8usize; let mut members = Vec::new(); let mut names = 0usize; + let mut strings = 0usize; let mut long_names = None; while cursor < bytes.len() { charge_archive(&mut work, 60, max_work)?; @@ -50,6 +52,7 @@ fn parse_archive( let mut payload = bytes.get(start..end).ok_or("archive member exceeds input")?; let raw = std::str::from_utf8(&header[..16]).map_err(|_| "archive name is not UTF-8")?.trim_end(); + let mut inspected = None; let name = if raw == "//" { long_names = Some(payload); None @@ -60,6 +63,7 @@ fn parse_archive( charge_archive(&mut work, length, max_work)?; let name = payload.get(..length).ok_or("BSD archive name exceeds member")?; payload = &payload[length..]; + inspected = Some(length); Some( std::str::from_utf8(name) .map_err(|_| "archive name is not UTF-8")? @@ -79,6 +83,7 @@ fn parse_archive( None => return Err("unterminated archive long name".into()), }; charge_archive(&mut work, length + 1, max_work)?; + inspected = Some(length + 1); Some( std::str::from_utf8(&suffix[..length]) .map_err(|_| "archive name is not UTF-8")? @@ -88,11 +93,18 @@ fn parse_archive( Some(raw.trim_end_matches('/')) }; if let Some(name) = name { - if !name.starts_with("__.SYMDEF") { + if !is_bsd_index(name) { names = names .checked_add(name.len()) .filter(|n| *n <= max_names) .ok_or("archive name byte budget exceeded")?; + // Keep the owned-name cap independent from the shared reader + // budget, which includes both inspected bytes and the copy. + strings = strings + .checked_add(inspected.unwrap_or(name.len())) + .and_then(|n| n.checked_add(name.len())) + .filter(|n| *n <= max_strings) + .ok_or("archive name byte budget exceeded")?; charge_archive( &mut work, name.len().saturating_mul(2).saturating_add(1), @@ -115,7 +127,11 @@ fn parse_archive( cursor += 1; } } - Ok((members, names, work)) + Ok((members, strings, work)) +} + +fn is_bsd_index(name: &str) -> bool { + matches!(name, "__.SYMDEF" | "__.SYMDEF SORTED" | "__.SYMDEF_64" | "__.SYMDEF_64 SORTED") } fn decimal(bytes: &[u8]) -> Result { @@ -198,7 +214,8 @@ impl ReadBudget { next.input(bytes.len()).map_err(input_error)?; let (members, names, work) = parse_archive( bytes, - next.remaining.max_string_bytes.min(1024 * 1024), + 1024 * 1024, + next.remaining.max_string_bytes, next.remaining.max_work, ) .map_err(|message| match message.as_str() { diff --git a/linker/tests/archives.rs b/linker/tests/archives.rs index 60adb49..d103033 100644 --- a/linker/tests/archives.rs +++ b/linker/tests/archives.rs @@ -326,3 +326,115 @@ fn archive_names_and_parser_work_are_preflighted_with_shared_reader_limits() { assert!(read_archive(&bytes).unwrap_err().contains("name byte budget")); } } + +fn named_member(out: &mut Vec, encoding: &str, name: &str, payload: &[u8]) { + match encoding { + "short" => member(out, &format!("{name}/"), payload), + "BSD" => { + let mut bytes = name.as_bytes().to_vec(); + bytes.extend_from_slice(payload); + member(out, &format!("#1/{}", name.len()), &bytes); + }, + "GNU" => { + member(out, "//", format!("{name}/\n").as_bytes()); + member(out, "/0", payload); + }, + _ => unreachable!(), + } +} + +#[test] +fn only_exact_bsd_symbol_indexes_are_skipped_and_prefix_objects_are_extracted() { + let helper = object("helper", &[0xb8, 42, 0, 0, 0, 0xc3]).write().unwrap(); + for encoding in ["short", "BSD", "GNU"] { + let mut bytes = b"!\n".to_vec(); + named_member(&mut bytes, encoding, "__.SYMDEF_x.o", &helper); + let parsed = read_archive(&bytes).unwrap(); + assert_eq!(parsed.len(), 1, "{encoding}"); + assert_eq!(parsed[0].name, "__.SYMDEF_x.o"); + let mut linker = Linker::new(OutputFormat::ELF64Executable); + linker.add_object(entry()); + linker.add_archive(&bytes).unwrap(); + assert!(linker.link().is_ok(), "{encoding}"); + } + let mut bytes = b"!\n".to_vec(); + for name in ["__.SYMDEF", "__.SYMDEF SORTED", "__.SYMDEF_64", "__.SYMDEF_64 SORTED"] { + named_member(&mut bytes, "BSD", name, b"not an ELF payload"); + } + assert!(read_archive(&bytes).unwrap().is_empty()); + assert!(linker::core::archive::read_objects(&bytes).unwrap().is_empty()); +} + +#[test] +fn archive_inspection_and_name_copies_have_exact_shared_string_boundaries() { + use linker::core::archive::read_objects_with_limits; + let bytes = ObjectFile::new(ObjectFormat::ELF64).write().unwrap(); + let (_, usage) = ObjectFile::read_with_usage(&bytes, ObjectReadLimits::default()).unwrap(); + for (encoding, name, inspected) in [ + ("short", "short.o", 7), + ("BSD", "twenty-byte-member.o", 20), + // GNU names include the slash and newline inspected to find the end. + ("GNU", "twenty-byte-member.o", 22), + ] { + let mut archive = b"!\n".to_vec(); + named_member(&mut archive, encoding, name, &bytes); + let exact = usage.string_bytes + inspected + name.len(); + for max_string_bytes in [usage.string_bytes + name.len(), exact - 1] { + let error = read_objects_with_limits( + &archive, + ObjectReadLimits { max_string_bytes, ..ObjectReadLimits::default() }, + ) + .err() + .expect("inspection and copying must both be charged"); + assert_eq!(reader_resource(error), ObjectResource::StringBytes, "{encoding}"); + } + assert_eq!( + read_objects_with_limits( + &archive, + ObjectReadLimits { max_string_bytes: exact, ..ObjectReadLimits::default() }, + ) + .unwrap() + .len(), + 1, + "{encoding}" + ); + } +} + +#[test] +fn string_charges_span_archives_objects_and_rollback_a_rejected_input() { + let start = entry().write().unwrap(); + let helper = object("helper", &[0xc3]).write().unwrap(); + let (_, start_usage) = + ObjectFile::read_with_usage(&start, ObjectReadLimits::default()).unwrap(); + let (_, helper_usage) = + ObjectFile::read_with_usage(&helper, ObjectReadLimits::default()).unwrap(); + let name = "helper.o"; + let archive_strings = helper_usage.string_bytes + name.len() * 2; + let empty = ObjectFile::new(ObjectFormat::ELF64).write().unwrap(); + let (_, empty_usage) = + ObjectFile::read_with_usage(&empty, ObjectReadLimits::default()).unwrap(); + let mut bytes = b"!\n".to_vec(); + named_member(&mut bytes, "short", name, &helper); + let mut linker = Linker::with_read_limits( + OutputFormat::ELF64Executable, + ObjectReadLimits { + max_string_bytes: start_usage.string_bytes + archive_strings + empty_usage.string_bytes, + ..ObjectReadLimits::default() + }, + ); + linker.add_object_bytes(&start).unwrap(); + linker.add_archive(&bytes).unwrap(); + // A second archive cannot fit; neither its names nor its nested objects may + // consume the budget left for a subsequent ordinary object. + for _ in 0..2 { + assert_eq!( + reader_resource(linker.add_archive(&bytes).unwrap_err()), + ObjectResource::StringBytes + ); + } + // An empty object consumes exactly the remaining allowance and contributes + // no duplicate; even a partial name charge on failure would make it fail. + linker.add_object_bytes(&empty).unwrap(); + assert!(linker.link().is_ok()); +} From be6a77b822ca3693e145bb8fb9eaf70b9cb8ec7c Mon Sep 17 00:00:00 2001 From: LunaStev Date: Wed, 21 Oct 2026 19:42:50 +0900 Subject: [PATCH 4/8] fix(object): accept inactive ELF headers and clarify target contracts Resolve #314 and #329 while retaining raw reader limits and AMD64-only consumer validation. Signed-off-by: LunaStev --- object/src/formats/elf_read.rs | 6 +++- object/tests/elf_reader.rs | 49 +++++++++++++++++++++++++++++++++ object/tests/target_identity.rs | 30 ++++++++++++++++++++ target-spec/src/lib.rs | 10 +++++-- 4 files changed, 91 insertions(+), 4 deletions(-) diff --git a/object/src/formats/elf_read.rs b/object/src/formats/elf_read.rs index 8d9c50f..cf8f8dd 100644 --- a/object/src/formats/elf_read.rs +++ b/object/src/formats/elf_read.rs @@ -415,7 +415,8 @@ pub fn read_elf_with_usage( if view.range(h.section_offset, 64)?.iter().any(|b| *b != 0) { return Err(error(Kind::InvalidSection, "section zero is not null").section(0)); } - } else { + } else if section.kind != 0 { + // SHT_NULL is inactive; all other fields are undefined by the gABI. if section.align != 0 && !section.align.is_power_of_two() { return Err(error( Kind::InvalidAlignment, @@ -447,6 +448,9 @@ pub fn read_elf_with_usage( mapping.resize(h.section_count, None); let mut symbol_table = None; for (index, §ion) in headers.iter().enumerate().skip(1) { + if section.kind == 0 { + continue; + } let name = budget.name(view, names, section.name).map_err(|e| e.section(index))?; match section.kind { 1 | 8 => { diff --git a/object/tests/elf_reader.rs b/object/tests/elf_reader.rs index a6154d7..5d8e345 100644 --- a/object/tests/elf_reader.rs +++ b/object/tests/elf_reader.rs @@ -431,3 +431,52 @@ fn sparse_nobits_alignment_may_put_conceptual_file_offset_beyond_eof() { assert!(imported.sections[0].data.is_empty()); } } + +#[test] +fn inactive_headers_ignore_undefined_fields_but_keep_raw_resource_charges() { + let original = sample(); + let mut bytes = original.write().unwrap(); + let (_, before) = ObjectFile::read_with_usage(&bytes, ObjectReadLimits::default()).unwrap(); + let inactive = before.sections; + // Writer places the section-header table at EOF. Only sh_type has meaning + // for an inactive header; deliberately make all other fields nonsensical. + bytes.extend_from_slice(&[0xff; 64]); + let inactive_at = bytes.len() - 64; + put32(&mut bytes, inactive_at + 4, 0); + put16(&mut bytes, 60, (inactive + 1) as u16); + let (imported, after) = + ObjectFile::read_with_usage(&bytes, ObjectReadLimits::default()).unwrap(); + assert_semantics(&original, &imported); + assert_eq!(after.sections, before.sections + 1); + assert_eq!(after.work, before.work + 1); + assert_eq!(after.string_bytes, before.string_bytes); + assert_eq!(after.payload_bytes, before.payload_bytes); + for limits in [ + ObjectReadLimits { max_sections: after.sections - 1, ..ObjectReadLimits::default() }, + ObjectReadLimits { max_work: after.work - 1, ..ObjectReadLimits::default() }, + ] { + let error = ObjectFile::read_with_limits(&bytes, limits).err().expect("resource limit"); + assert_eq!(error.kind, ObjectErrorKind::ResourceLimit); + } + // Symbols and relocations may not use the inactive header as payload. + let view = ElfView::parse(&bytes, ObjectReadLimits::default()).unwrap(); + let table = (1..view.header.section_count) + .find_map(|index| { + let header = view.section(index).unwrap(); + (header.kind == 2).then_some(header) + }) + .unwrap(); + let mut bad_symbol = bytes.clone(); + put16(&mut bad_symbol, table.offset as usize + 24 + 6, inactive as u16); + assert!(ObjectFile::read(&bad_symbol).is_err()); + let relocation = (1..view.header.section_count) + .find(|&index| view.section(index).unwrap().kind == 4) + .unwrap(); + let mut bad_relocation = bytes.clone(); + put32( + &mut bad_relocation, + view.header.section_offset as usize + relocation * 64 + 44, + inactive as u32, + ); + assert_eq!(rejected(&bad_relocation).kind, ObjectErrorKind::InvalidRelocation); +} diff --git a/object/tests/target_identity.rs b/object/tests/target_identity.rs index c41b9d4..3c44297 100644 --- a/object/tests/target_identity.rs +++ b/object/tests/target_identity.rs @@ -46,3 +46,33 @@ fn multi_isa_writer_preserves_machine_and_abi_without_enabling_amd64_linking() { assert!(ObjectFile::read(&bytes).is_err(), "AMD64 reader must reject another ISA"); } } + +#[test] +fn invalid_encoding_diagnostics_describe_serialization_and_consumer_contracts() { + for machine in [Machine::X86_64, Machine::AArch64, Machine::RiscV64, Machine::LoongArch64] { + let valid = ObjectTarget::elf64(machine); + assert!(valid.validate().is_ok()); + for invalid in [ + ObjectTarget { endian: Endian::Big, ..valid }, + ObjectTarget { address_bits: 32, ..valid }, + ] { + let message = invalid.validate().unwrap_err().to_string(); + for expected in [ + "ELF64", + "little endian", + "64-bit addresses", + "X86_64", + "AArch64", + "RiscV64", + "LoongArch64", + ] { + assert!(message.contains(expected), "missing {expected}: {message}"); + } + } + if machine != Machine::X86_64 { + let message = valid.validate_amd64().unwrap_err().to_string(); + assert!(message.contains("this operation requires")); + assert!(message.contains("AMD64")); + } + } +} diff --git a/target-spec/src/lib.rs b/target-spec/src/lib.rs index 8e0daaa..c5ec63a 100644 --- a/target-spec/src/lib.rs +++ b/target-spec/src/lib.rs @@ -64,7 +64,7 @@ impl ObjectTarget { if self == Target::X86_64WhaleLinux.object_target() { Ok(()) } else { - Err(TargetError::UnsupportedObjectTarget(self)) + Err(TargetError::UnsupportedAmd64ObjectTarget(self)) } } @@ -142,6 +142,7 @@ pub enum TargetError { UnsupportedTarget(String), LayoutMismatch { target: Target, actual: DataLayout }, UnsupportedObjectTarget(ObjectTarget), + UnsupportedAmd64ObjectTarget(ObjectTarget), } impl fmt::Display for TargetError { @@ -166,8 +167,11 @@ impl fmt::Display for TargetError { ), Self::UnsupportedObjectTarget(target) => write!( f, - "unsupported object target {target:?}; supported object target: {:?}", - Target::X86_64WhaleLinux.object_target() + "unsupported object target {target:?}; supported serialization contract: ELF64, little endian, 64-bit addresses; machines: X86_64, AArch64, RiscV64, LoongArch64" + ), + Self::UnsupportedAmd64ObjectTarget(target) => write!( + f, + "unsupported object target {target:?}; this operation requires ELF64, little endian, 64-bit AMD64" ), } } From ea9535344dc2059548750156cdf189b516f3c3ed Mon Sep 17 00:00:00 2001 From: LunaStev Date: Wed, 21 Oct 2026 19:48:08 +0900 Subject: [PATCH 5/8] fix(reverse): preserve static image metadata and stack prefix semantics Resolve #323, #324, #325 and #326 with effective REX.W stack decoding, non-code boundary metadata, explicit TLS symbol omission and zero-file-size PT_LOAD handling. Signed-off-by: LunaStev --- reverse/README.md | 9 ++- reverse/examples/fuzz_reverse.rs | 1 + reverse/src/image.rs | 26 +++++++- reverse/tests/cfg.rs | 8 +++ reverse/tests/decode.rs | 30 +++++++++ reverse/tests/images.rs | 103 +++++++++++++++++++++++++++++++ reverse/wave/amd64.wave | 4 +- tests/reverse_cli.rs | 91 +++++++++++++++++++++++++++ 8 files changed, 265 insertions(+), 7 deletions(-) diff --git a/reverse/README.md b/reverse/README.md index c69187b..f998b5e 100644 --- a/reverse/README.md +++ b/reverse/README.md @@ -52,7 +52,8 @@ Missing bytes in a recognized form are `Truncated`; a known required field that cannot fit inside 15 bytes is `Overlong`. Fifteen prefix bytes are overlong even if no sixteenth input byte is available. Legacy prefixes after REX cancel the earlier REX, and only the effective REX changes AH/CH/DH/BH to SPL/BPL/SIL/DIL. -Stack-register operations default to 64 bits, with 66 selecting 16 bits. SIB and +Stack operations default to 64 bits. An effective REX.W takes precedence over +66; 66 selects 16 bits when REX.W is absent or cancelled by a later legacy prefix. SIB and RIP-relative no-base sentinels do not turn into R13 merely because REX.B is set. `Instruction` retains the exact original bytes, operand/condition identities, @@ -70,7 +71,11 @@ implied by this crate. The archive is generated through Wave's LLVM bootstrap. file offsets and virtual addresses. ET_REL uses the bounded object importer and retains symbolic RELA annotations. ET_EXEC uses checked ELF header access and executable PT_LOAD file ranges, including files without section tables. Memory-only -BSS tails are never copied or decoded. Dynamic/PIE images are outside this subset. +BSS tails and pure-BSS segments are never copied or decoded; zero file sizes +require no file-backed range. Zero-sized NOTYPE linker boundary markers remain +non-code metadata when outside their defining section. TLS symbol metadata is +omitted because TLS offsets are not process virtual addresses. Dynamic/PIE images +are outside this subset. `whale reverse inspect file --json` works without the Wave archive. `whale disasm` requires the linked Wave core, emits typed facts as JSON or a human listing, and diff --git a/reverse/examples/fuzz_reverse.rs b/reverse/examples/fuzz_reverse.rs index 5ab3b5f..f4d6300 100644 --- a/reverse/examples/fuzz_reverse.rs +++ b/reverse/examples/fuzz_reverse.rs @@ -25,6 +25,7 @@ const FIXTURES: &[&[u8]] = &[ &[0xff, 0xd0, 0xff, 0xe0], &[0x40, 0xb4, 1, 0xc3], &[0x66, 0x68, 0, 0x80, 0xc3], + &[0x66, 0x48, 0x68, 0x34, 0x12, 0xc3, 0x56, 0xc3], ]; fn require(ok: bool, reason: &str) -> Result<(), String> { diff --git a/reverse/src/image.rs b/reverse/src/image.rs index 64ef146..613e838 100644 --- a/reverse/src/image.rs +++ b/reverse/src/image.rs @@ -174,7 +174,13 @@ impl<'a> Image<'a> { .virtual_address .checked_add(p.memory_size) .ok_or("PT_LOAD virtual address overflow")?; - let bytes = view.range(p.offset, p.file_size).map_err(|e| e.to_string())?; + // A pure BSS segment has only a conceptual file offset. It must + // participate in virtual validation without requiring file bytes. + let bytes = if p.file_size == 0 { + &[] + } else { + view.range(p.offset, p.file_size).map_err(|e| e.to_string())? + }; charge(&mut work, mappings.len())?; if mappings.iter().any(|&(start, stop)| p.virtual_address < stop && start < end) { return Err("overlapping PT_LOAD virtual ranges are unsupported".into()); @@ -293,6 +299,12 @@ impl<'a> Image<'a> { if section as usize >= view.header.section_count && section < 0xff00 { return Err("symbol section index outside table".into()); } + let symbol_kind = view.range(at + 4, 1).map_err(|e| e.to_string())?[0] & 15; + // STT_TLS values are offsets within a TLS block, not process + // addresses. TLS metadata is outside this static code model. + if symbol_kind == 6 { + continue; + } let value = view.u64(at + 8).map_err(|e| e.to_string())?; let size = view.u64(at + 16).map_err(|e| e.to_string())?; let symbol_end = value.checked_add(size).ok_or("symbol address range overflow")?; @@ -307,10 +319,18 @@ impl<'a> Image<'a> { .address .checked_add(owner.size) .ok_or("symbol defining section overflow")?; - if value < owner.address || symbol_end > owner_end { + let outside_owner = value < owner.address || symbol_end > owner_end; + // Linkers emit zero-sized NOTYPE boundary markers beyond + // their nominal owner. Retain their addresses as metadata + // without assigning an unrelated executable region. + if outside_owner && !(symbol_kind == 0 && size == 0) { return Err("symbol range exceeds its defining section".into()); } - if owner.kind == 1 && owner.flags & 4 != 0 && value < owner_end { + if !outside_owner + && owner.kind == 1 + && owner.flags & 4 != 0 + && value < owner_end + { charge(&mut work, image.regions.len())?; let found = image.regions.iter().find(|r| { value >= r.address diff --git a/reverse/tests/cfg.rs b/reverse/tests/cfg.rs index 2ba3279..e260ac9 100644 --- a/reverse/tests/cfg.rs +++ b/reverse/tests/cfg.rs @@ -45,6 +45,14 @@ mod native { ); } + #[test] + fn rex_w_push_immediate_bytes_do_not_become_fake_return_boundaries() { + let g = graph(&[0x66, 0x48, 0x68, 0x34, 0x12, 0xc3, 0x56, 0xc3], &[0]); + assert_eq!(offsets(&g), [0, 7]); + assert_eq!(g.blocks.iter().map(|b| (b.offset, b.end)).collect::>(), [(0, 8)]); + assert!(g.stops.is_empty()); + } + #[test] fn diamond_and_late_backward_leaders_split_existing_blocks_in_wave() { let g = graph(&[0x75, 3, 0x90, 0xeb, 1, 0x90, 0xc3], &[0]); diff --git a/reverse/tests/decode.rs b/reverse/tests/decode.rs index 94c05af..cc0304f 100644 --- a/reverse/tests/decode.rs +++ b/reverse/tests/decode.rs @@ -94,6 +94,36 @@ mod native { )); } + #[test] + fn stack_operand_size_honors_effective_rex_w_and_legacy_cancellation() { + for opcode in [0x50, 0x58] { + for (prefix, name, width) in [ + (vec![0x66, 0x48], "rax", 64), + (vec![0x66, 0x49], "r8", 64), + (vec![0x66], "ax", 16), + (vec![0x48, 0x66], "ax", 16), + (vec![0x66, 0x40], "ax", 16), + ] { + let mut bytes = prefix; + bytes.push(opcode); + let x = one(&bytes); + reg(x.operands[0], name); + assert!(matches!(x.operands[0], Operand::Register(r) if r.width == width)); + } + } + for (bytes, width, encoded_width, sign_extended) in [ + (vec![0x66, 0x48, 0x68, 0x34, 0x12, 0xc3, 0x56], 64, 32, true), + (vec![0x66, 0x48, 0x6a, 0xff], 64, 8, true), + (vec![0x48, 0x66, 0x68, 0x34, 0x12], 16, 16, false), + (vec![0x66, 0x40, 0x68, 0x34, 0x12], 16, 16, false), + (vec![0x66, 0x6a, 0xff], 16, 8, true), + ] { + let x = one(&bytes); + assert!(matches!(x.operands[0], Operand::Immediate(i) if + (i.width, i.encoded_width, i.sign_extended) == (width, encoded_width, sign_extended))); + } + } + #[test] fn manual_sib_rip_absolute_and_rex_sentinels_are_distinct() { let x = one(&[0x4b, 0x8b, 0x44, 0xcc, 0x80]); diff --git a/reverse/tests/images.rs b/reverse/tests/images.rs index 820200f..a858408 100644 --- a/reverse/tests/images.rs +++ b/reverse/tests/images.rs @@ -239,3 +239,106 @@ fn relocatable_inspection_shares_actual_reader_work_instead_of_reserving_half() assert_eq!(image.relocations[0].offset, 1); assert_eq!(image.relocations[0].width, 4); } + +fn write64(bytes: &mut [u8], at: usize, value: u64) { + bytes[at..at + 8].copy_from_slice(&value.to_le_bytes()); +} + +fn metadata_executable(kind: u8, value: u64, size: u64) -> Vec { + let mut bytes = symbol_executable(1); + bytes.resize(0x1191, 0); + bytes[60..62].copy_from_slice(&5u16.to_le_bytes()); + // Retain the code function and add a separate data/TLS owner plus metadata. + let owner = 128 + 4 * 64; + bytes[owner + 4..owner + 8].copy_from_slice(&1u32.to_le_bytes()); + for (offset, value) in [(8, 0x403), (16, 0x402000), (24, 0x1008), (32, 16), (48, 8)] { + write64(&mut bytes, owner + offset, value); + } + let symtab = 128 + 2 * 64; + write64(&mut bytes, symtab + 24, 0x1100); + write64(&mut bytes, symtab + 32, 72); + bytes[symtab + 44..symtab + 48].copy_from_slice(&1u32.to_le_bytes()); + let strings = 128 + 3 * 64; + write64(&mut bytes, strings + 24, 0x1180); + write64(&mut bytes, strings + 32, 17); + bytes[0x1180..].copy_from_slice(b"\0start\0metadata\0\0"); + for (at, name, info, section, address, length) in + [(0x1118, 1u32, 0x12u8, 1u16, 0x401000u64, 1u64), (0x1130, 7, 0x10 | kind, 4, value, size)] + { + bytes[at..at + 4].copy_from_slice(&name.to_le_bytes()); + bytes[at + 4] = info; + bytes[at + 6..at + 8].copy_from_slice(§ion.to_le_bytes()); + write64(&mut bytes, at + 8, address); + write64(&mut bytes, at + 16, length); + } + bytes +} + +#[test] +fn zero_sized_notype_boundary_markers_remain_non_code_metadata() { + for address in [0x403000, 0x401000] { + let bytes = metadata_executable(0, address, 0); + let image = Image::elf(&bytes, ObjectReadLimits::default()).unwrap(); + assert_eq!(image.symbols[0].name, "start"); + assert_eq!(image.symbols[0].region, Some(0)); + let marker = &image.symbols[1]; + assert_eq!(marker.name, "metadata"); + assert_eq!(marker.address, Some(address)); + assert_eq!(marker.region, None); + assert_eq!(image.entry_offset(&image.regions[0]), 0); + } + for (kind, size) in [(2, 0), (0, 1), (1, 0)] { + assert!(Image::elf( + &metadata_executable(kind, 0x403000, size), + ObjectReadLimits::default() + ) + .unwrap_err() + .contains("defining section")); + } +} + +#[test] +fn tls_offsets_are_omitted_without_losing_static_code_or_claiming_process_addresses() { + for offset in [0, 8] { + let bytes = metadata_executable(6, offset, 8); + let image = Image::elf(&bytes, ObjectReadLimits::default()).unwrap(); + assert_eq!(image.symbols.len(), 1); + assert_eq!(image.symbols[0].name, "start"); + assert_eq!(image.symbols[0].address, Some(0x401000)); + assert_eq!(image.symbols[0].region, Some(0)); + assert_eq!(image.regions[0].bytes, [0xc3]); + } + // Non-TLS symbols with the same invalid VA still fail owner validation. + assert!(Image::elf(&metadata_executable(1, 0, 8), ObjectReadLimits::default()).is_err()); +} + +#[test] +fn pure_bss_load_segments_need_no_file_range_but_preserve_virtual_validation() { + let mut bytes = executable(); + bytes.resize(177, 0); + bytes[176] = 0xc3; + bytes[56..58].copy_from_slice(&2u16.to_le_bytes()); + write64(&mut bytes, 24, 0x4000b0); + write64(&mut bytes, 96, 177); + write64(&mut bytes, 104, 177); + bytes[120..124].copy_from_slice(&1u32.to_le_bytes()); + bytes[124..128].copy_from_slice(&6u32.to_le_bytes()); + write64(&mut bytes, 128, 0x100000); + write64(&mut bytes, 136, 0x500000); + write64(&mut bytes, 144, 0x500000); + write64(&mut bytes, 152, 0); + write64(&mut bytes, 160, 1 << 40); + write64(&mut bytes, 168, 4096); + for offset in [0, 0x100000] { + write64(&mut bytes, 128, offset); + let image = Image::elf(&bytes, ObjectReadLimits::default()).unwrap(); + assert_eq!(image.regions.len(), 1); + assert_eq!(image.regions[0].bytes.len(), 177); + assert_eq!(image.entry_offset(&image.regions[0]), 176); + } + for (at, value) in [(152, 1), (128, 0x100001), (136, 0x400000), (136, u64::MAX - 1)] { + let mut bad = bytes.clone(); + write64(&mut bad, at, value); + assert!(Image::elf(&bad, ObjectReadLimits::default()).is_err(), "at {at}"); + } +} diff --git a/reverse/wave/amd64.wave b/reverse/wave/amd64.wave index 904c86c..7130c1b 100644 --- a/reverse/wave/amd64.wave +++ b/reverse/wave/amd64.wave @@ -234,7 +234,7 @@ fun reverse_decode_body(state: ptr) -> i32 { opcode = 12; } width = 64; - if (operand16) { + if (operand16 && (state.rex & 8) == 0) { width = 16; } format = 6; @@ -243,7 +243,7 @@ fun reverse_decode_body(state: ptr) -> i32 { format = 13; width = 64; immediate_bytes = 4; - if (operand16) { + if (operand16 && (state.rex & 8) == 0) { width = 16; immediate_bytes = 2; } diff --git a/tests/reverse_cli.rs b/tests/reverse_cli.rs index 1ab6e90..af1cf02 100644 --- a/tests/reverse_cli.rs +++ b/tests/reverse_cli.rs @@ -450,3 +450,94 @@ fn graph_budget_options_are_validated_and_enforced_before_output_publication() { } } } + +#[test] +fn static_inspection_preserves_boundary_markers_and_omits_tls_offsets() { + let mut bytes = vec![0; 0x294]; + bytes[..7].copy_from_slice(b"\x7fELF\x02\x01\x01"); + for (at, value) in [(16, 2u16), (18, 62), (52, 64), (54, 56), (56, 1), (58, 64), (60, 5)] { + bytes[at..at + 2].copy_from_slice(&value.to_le_bytes()); + } + for (at, value) in [(20, 1u32), (64, 1), (68, 5)] { + bytes[at..at + 4].copy_from_slice(&value.to_le_bytes()); + } + for (at, value) in [ + (24, 0x400200u64), + (32, 64), + (40, 128), + (80, 0x400000), + (96, 0x294), + (104, 0x294), + (112, 4096), + ] { + bytes[at..at + 8].copy_from_slice(&value.to_le_bytes()); + } + for (index, kind, flags, address, offset, size, link, stride) in [ + (1, 1u32, 6u64, 0x400200u64, 0x200u64, 1u64, 0u32, 0u64), + (2, 2, 0, 0, 0x210, 96, 3, 24), + (3, 3, 0, 0, 0x280, 20, 0, 0), + (4, 1, 0x403, 0x400201, 0x201, 16, 0, 0), + ] { + let at = 128 + index * 64; + bytes[at + 4..at + 8].copy_from_slice(&kind.to_le_bytes()); + bytes[at + 40..at + 44].copy_from_slice(&link.to_le_bytes()); + for (field, value) in + [(8, flags), (16, address), (24, offset), (32, size), (48, 1), (56, stride)] + { + bytes[at + field..at + field + 8].copy_from_slice(&value.to_le_bytes()); + } + } + bytes[128 + 2 * 64 + 44..128 + 2 * 64 + 48].copy_from_slice(&1u32.to_le_bytes()); + bytes[0x200] = 0xc3; + bytes[0x280..].copy_from_slice(b"\0start\0boundary\0tls\0"); + for (index, name, kind, section, value, size) in [ + (1, 1u32, 0x12u8, 1u16, 0x400200u64, 1u64), + (2, 7, 0x10, 1, 0x500000, 0), + (3, 16, 0x16, 4, 8, 8), + ] { + let at = 0x210 + index * 24; + bytes[at..at + 4].copy_from_slice(&name.to_le_bytes()); + bytes[at + 4] = kind; + bytes[at + 6..at + 8].copy_from_slice(§ion.to_le_bytes()); + bytes[at + 8..at + 16].copy_from_slice(&value.to_le_bytes()); + bytes[at + 16..at + 24].copy_from_slice(&size.to_le_bytes()); + } + let dir = tempfile::tempdir().unwrap(); + let input = dir.path().join("metadata-exec"); + fs::write(&input, bytes).unwrap(); + let result = whale().args(["reverse", "inspect"]).arg(&input).arg("--json").output().unwrap(); + assert!(result.status.success(), "{}", String::from_utf8_lossy(&result.stderr)); + let image: serde_json::Value = serde_json::from_slice(&result.stdout).unwrap(); + let symbols = image["symbols"].as_array().unwrap(); + assert_eq!(symbols.len(), 2); + assert_eq!(symbols[0]["name"], "start"); + assert_eq!(symbols[0]["region"], 0); + assert_eq!(symbols[1]["name"], "boundary"); + assert!(symbols[1]["region"].is_null()); + assert_eq!(symbols[1]["address"], 0x500000); +} + +#[test] +fn stack_rex_w_immediate_boundary_is_preserved_by_public_listing_and_cfg() { + if !reverse::backend_available() { + return; + } + let dir = tempfile::tempdir().unwrap(); + let input = dir.path().join("stack-prefix"); + fs::write(&input, [0x66, 0x48, 0x68, 0x34, 0x12, 0xc3, 0x56, 0xc3]).unwrap(); + let listing = whale() + .arg("disasm") + .arg(&input) + .args(["--raw", "--amd64", "--base", "0", "--json"]) + .output() + .unwrap(); + assert!(listing.status.success(), "{}", String::from_utf8_lossy(&listing.stderr)); + let listing: serde_json::Value = serde_json::from_slice(&listing.stdout).unwrap(); + assert_eq!(listing["records"].as_array().unwrap().len(), 2); + assert_eq!(listing["records"][0]["instruction"]["length"], 7); + let graph = graph_json( + whale().args(["reverse", "cfg"]).arg(input).args(["--raw", "--amd64", "--base", "0"]), + ); + assert_eq!(graph_offsets(&graph), [0, 7]); + assert_eq!(graph["blocks"][0]["end"], 8); +} From 0fca7f86a53d8311601d3360fb09f317f033f0ff Mon Sep 17 00:00:00 2001 From: LunaStev Date: Wed, 21 Oct 2026 19:44:09 +0900 Subject: [PATCH 6/8] fix(ir): align parser and builder validation contracts Keep function body, declaration, and global diagnostic locations in their own namespaces. Reject pointer division/remainder and function link names already used by global storage without consuming identities. Refs #315, #327, #328 Signed-off-by: LunaStev --- ir/src/builder.rs | 4 ++- ir/src/parser/syntax.rs | 44 +++++++++++++++++------- ir/src/verifier/operands.rs | 4 +-- ir/tests/builder_checked.rs | 62 ++++++++++++++++++++++++++++++++++ ir/tests/operand_validation.rs | 31 +++++++++++++++++ ir/tests/text_parser.rs | 41 ++++++++++++++++++++++ 6 files changed, 170 insertions(+), 16 deletions(-) diff --git a/ir/src/builder.rs b/ir/src/builder.rs index d8a2ae6..22de347 100644 --- a/ir/src/builder.rs +++ b/ir/src/builder.rs @@ -293,7 +293,9 @@ impl ModuleBuilder { }; } if let Some(link) = &candidate.link_name { - if self.module.declarations.iter().any(|d| d.link_name.as_ref() == Some(link)) { + if self.module.declarations.iter().any(|d| d.link_name.as_ref() == Some(link)) + || self.module.global_storage.iter().any(|g| g.link_name.as_ref() == Some(link)) + { return Err(crate::CallError::LinkNameCollision(link.clone())); } } diff --git a/ir/src/parser/syntax.rs b/ir/src/parser/syntax.rs index 77a0f0a..b1b5866 100644 --- a/ir/src/parser/syntax.rs +++ b/ir/src/parser/syntax.rs @@ -12,7 +12,10 @@ pub(super) struct Parser<'a> { pub limits: IrLimits, nodes: usize, pub(super) format_version: u32, - locations: std::collections::HashMap, + function_locations: std::collections::HashMap, + declaration_locations: std::collections::HashMap, + global_locations: std::collections::HashMap, + global_constant_locations: std::collections::HashMap, } impl<'a> Parser<'a> { @@ -23,13 +26,22 @@ impl<'a> Parser<'a> { limits, nodes: 0, format_version: 0, - locations: std::collections::HashMap::new(), + function_locations: std::collections::HashMap::new(), + declaration_locations: std::collections::HashMap::new(), + global_locations: std::collections::HashMap::new(), + global_constant_locations: std::collections::HashMap::new(), } } pub fn verification_location(&self, e: &VerifyError) -> super::SourceLocation { use VerifyError::*; - let name = match e { + let function = |name: &String| { + self.function_locations.get(name).or_else(|| self.declaration_locations.get(name)) + }; + let location = match e { + InvalidMemoryLayout { func, operation: "global storage", .. } => { + self.global_locations.get(func) + }, ForbiddenUndef { func, .. } | InvalidMemoryLayout { func, .. } | InvalidCast { func, .. } @@ -56,16 +68,21 @@ impl<'a> Parser<'a> { | VoidParameter { func, .. } | UnterminatedBlock { func, .. } | RetTypeMismatch { func, .. } - | UseOfUndefinedValue { func, .. } => Some(func), - DuplicateFunction { name } - | DuplicateGlobal { name } + | UseOfUndefinedValue { func, .. } => function(func), + DuplicateFunction { name } => function(name), + DuplicateGlobal { name } | InvalidGlobalInitializer { name, .. } | InvalidGlobalAlignment { name, .. } - | GlobalStorage { name, .. } => Some(name), - InvalidConstExpression { scope, .. } => Some(scope), + | GlobalStorage { name, .. } => self.global_locations.get(name), + InvalidConstExpression { declaration: ConstRef::Global(id), .. } => { + self.global_constant_locations.get(id) + }, + InvalidConstExpression { scope, declaration: ConstRef::Local(_), .. } => { + function(scope) + }, _ => None, }; - name.and_then(|n| self.locations.get(n)).copied().unwrap_or(self.tokens[0].location) + location.copied().unwrap_or(self.tokens[0].location) } pub fn error(&self, s: &str) -> ParseError { @@ -517,7 +534,8 @@ impl<'a> Parser<'a> { let id = GlobalId(self.id("@g")?); let location = self.tokens[self.at].location; let name = self.string()?; - self.locations.entry(name.clone()).or_insert(location); + self.global_locations.entry(name.clone()).or_insert(location); + self.global_constant_locations.entry(id).or_insert(location); self.expect(":")?; let ty = self.ty(0)?; self.expect("=")?; @@ -540,7 +558,7 @@ impl<'a> Parser<'a> { let id = GlobalId(self.id("@g")?); let location = self.location(); let name = self.string()?; - self.locations.entry(name.clone()).or_insert(location); + self.global_locations.entry(name.clone()).or_insert(location); self.expect(":")?; let ty = self.ty(0)?; self.expect("=")?; @@ -592,7 +610,7 @@ impl<'a> Parser<'a> { let id = FunctionId(self.id("@f")?); let location = self.tokens[self.at].location; let name = self.string()?; - self.locations.entry(name.clone()).or_insert(location); + self.declaration_locations.entry(name.clone()).or_insert(location); self.expect(":")?; let signature = self.signature(0)?; self.comma()?; @@ -627,7 +645,7 @@ impl<'a> Parser<'a> { let id = FunctionId(self.id("@f")?); let location = self.tokens[self.at].location; let name = self.string()?; - self.locations.entry(name.clone()).or_insert(location); + self.function_locations.entry(name.clone()).or_insert(location); self.expect("(")?; let mut params = Vec::new(); let mut value_types = Vec::new(); diff --git a/ir/src/verifier/operands.rs b/ir/src/verifier/operands.rs index 14690e6..5f9f156 100644 --- a/ir/src/verifier/operands.rs +++ b/ir/src/verifier/operands.rs @@ -238,8 +238,8 @@ pub(super) fn verify_instruction( Instruction::Bin { op, ty, lhs, rhs, .. } => { let valid = match op { BinOp::FAdd | BinOp::FSub | BinOp::FMul | BinOp::FDiv | BinOp::FRem => is_float(ty), - BinOp::SDiv | BinOp::SRem => is_signed(ty) || matches!(ty, Type::Ptr(_)), - BinOp::UDiv | BinOp::URem => is_unsigned(ty) || matches!(ty, Type::Ptr(_)), + BinOp::SDiv | BinOp::SRem => is_signed(ty), + BinOp::UDiv | BinOp::URem => is_unsigned(ty), _ => is_integer(ty), }; verify_type_category(f, "binary operation", ty, valid)?; diff --git a/ir/tests/builder_checked.rs b/ir/tests/builder_checked.rs index eb05952..7827b58 100644 --- a/ir/tests/builder_checked.rs +++ b/ir/tests/builder_checked.rs @@ -75,3 +75,65 @@ fn checked_calls_report_terminated_blocks_and_can_build_neighbors() { f.finish(); verify_module(&m.finish()).unwrap(); } + +#[test] +fn function_and_storage_link_collisions_fail_atomically_in_both_orders() { + fn storage(link: &str) -> GlobalStorage { + let mut g = GlobalStorage::internal( + "data", + Type::U32, + GlobalStorageInit::Value(ConstValue::U(0)), + false, + 4, + ); + g.linkage = Linkage::External; + g.link_name = Some(link.into()); + g + } + fn declare( + m: &mut ModuleBuilder, + name: &str, + link: &str, + with_limits: bool, + ) -> Result { + let signature = FunctionSignature::whale(vec![], Type::Void); + if with_limits { + m.declare_function_with_limits( + name, + signature, + Linkage::External, + Some(link.into()), + IrLimits::default(), + ) + } else { + m.declare_function(name, signature, Linkage::External, Some(link.into())) + } + } + for with_limits in [false, true] { + let mut m = ModuleBuilder::new("x86_64-whale-linux", DataLayout::default_64bit_le()); + assert_eq!(m.try_add_global_storage(storage("exported")), Ok(GlobalId(0))); + assert_eq!( + declare(&mut m, "function", "exported", with_limits), + Err(CallError::LinkNameCollision("exported".into())) + ); + assert_eq!(declare(&mut m, "function", "different", with_limits), Ok(FunctionId(0))); + assert_eq!(declare(&mut m, "function", "different", with_limits), Ok(FunctionId(0))); + assert_eq!(declare(&mut m, "other", "another", with_limits), Ok(FunctionId(1))); + let m = m.finish(); + assert_eq!(m.declarations.len(), 2); + assert_eq!(m.global_storage.len(), 1); + verify_module(&m).unwrap(); + + let mut m = ModuleBuilder::new("x86_64-whale-linux", DataLayout::default_64bit_le()); + assert_eq!(declare(&mut m, "function", "exported", with_limits), Ok(FunctionId(0))); + assert_eq!( + m.try_add_global_storage(storage("exported")), + Err(GlobalStorageError::LinkNameCollision) + ); + assert_eq!(m.try_add_global_storage(storage("different")), Ok(GlobalId(0))); + let m = m.finish(); + assert_eq!(m.declarations.len(), 1); + assert_eq!(m.global_storage.len(), 1); + verify_module(&m).unwrap(); + } +} diff --git a/ir/tests/operand_validation.rs b/ir/tests/operand_validation.rs index c8f1fe0..47f7629 100644 --- a/ir/tests/operand_validation.rs +++ b/ir/tests/operand_validation.rs @@ -224,3 +224,34 @@ fn load_store_and_alloca_check_access_types_and_explicit_alignments() { assert_eq!(verify_module(&m).is_ok(), valid, "{m:?}"); } } + +#[test] +fn integer_division_and_remainder_reject_pointers_in_api_and_text() { + let ptr = Type::ptr_to(Type::U8); + for (op, spelling, ty) in [ + (BinOp::SDiv, "sdiv", Type::I32), + (BinOp::SRem, "srem", Type::I32), + (BinOp::UDiv, "udiv", Type::U32), + (BinOp::URem, "urem", Type::U32), + ] { + for (ty, valid) in [(ptr.clone(), false), (ty, true)] { + let m = module(vec![ty.clone(), ty.clone()], Some(ty.clone()), |dst| { + Instruction::Bin { dst, op: op.clone(), ty, lhs: ValueId(0), rhs: ValueId(1) } + }); + if valid { + verify_module(&m).unwrap(); + parse_module(&print_module(&m)).unwrap(); + } else { + assert!( + matches!(verify_module(&m), Err(VerifyError::InvalidInstructionType { .. })), + "{spelling}" + ); + let error = parse_module(&print_module(&m)).unwrap_err(); + assert!( + matches!(error.kind, ParseErrorKind::Verification(ref e) if matches!(**e, VerifyError::InvalidInstructionType { .. })), + "{spelling}: {error}" + ); + } + } + } +} diff --git a/ir/tests/text_parser.rs b/ir/tests/text_parser.rs index 61243d3..2a38ba4 100644 --- a/ir/tests/text_parser.rs +++ b/ir/tests/text_parser.rs @@ -241,3 +241,44 @@ fn parser_resource_limits_and_truncated_inputs_never_panic() { } } } + +#[test] +fn verification_locations_respect_function_and_global_namespaces() { + fn assert_location(source: &str, prefix: &str) -> ParseError { + let error = parse_module(source).unwrap_err(); + let offset = source.find(prefix).unwrap() + prefix.find('"').unwrap(); + assert_eq!(error.location.byte_offset, offset, "{error}"); + assert_eq!( + error.location.line, + source[..offset].bytes().filter(|&b| b == b'\n').count() + 1 + ); + error + } + let header = HEADER.replace("format_version 3", "format_version 7"); + let storage = + "storage @g0 \"shared\": i32 = value i32 0, align 4, access readwrite, linkage internal\n"; + let declaration = "declare @f0 \"shared\": whale () -> i32, linkage internal\n"; + let body = + "fn @f0 \"shared\"() -> i32, entry %b0 {\n%b0 \"entry\":\n%v0: i32 = const i32 42\n}\n"; + for before in [format!("{storage}{declaration}"), format!("{declaration}{storage}")] { + let text = format!("{header}{before}{body}}}\n"); + let error = assert_location(&text, "fn @f0 \"shared\""); + assert!( + matches!(error.kind, ParseErrorKind::Verification(e) if matches!(*e, VerifyError::UnterminatedBlock { .. })) + ); + let good = text.replace("const i32 42\n", "const i32 42\nret i32 %v0\n"); + parse_module(&good).unwrap(); + let bad_global = good.replace("align 4, access", "align 3, access"); + let error = assert_location(&bad_global, "storage @g0 \"shared\""); + assert!( + matches!(error.kind, ParseErrorKind::Verification(e) if matches!(*e, VerifyError::GlobalStorage { .. })) + ); + } + // Constant-expression errors carry a global identity, independent of their + // textual "module" scope and any function with that name. + let text = format!("{header}declare @f0 \"module\": whale () -> void, linkage internal\nfn @f0 \"module\"() -> void, entry %b0 {{ %b0 \"entry\": ret void }}\nglobal @g9 \"module\": i32 = const i32 0, align 4, init_expr i32 1\n}}\n"); + let error = assert_location(&text, "global @g9 \"module\""); + assert!( + matches!(error.kind, ParseErrorKind::Verification(e) if matches!(*e, VerifyError::InvalidConstExpression { .. })) + ); +} From 855276be17ca904665079229200c21a5003c32cf Mon Sep 17 00:00:00 2001 From: LunaStev Date: Wed, 21 Oct 2026 19:45:28 +0900 Subject: [PATCH 7/8] feat(ir): execute exact floating values, storage and bitcasts Preserve f16/f32/f64 storage bits through runtime values, tracked memory, globals and Whale calls. Execute equal-width integer/float bitcasts without changing NaN payloads or pointer authority; expose exact hexadecimal CLI arguments and results. Closes #263 Closes #268 Signed-off-by: LunaStev --- README.md | 39 ++++- ir/src/interpreter/memory.rs | 25 ++- ir/src/interpreter/mod.rs | 29 +++- ir/src/interpreter/scalar.rs | 25 +++ ir/tests/fixtures/float-storage-v7.wir | 35 ++++ ir/tests/interpreted_calls.rs | 10 +- ir/tests/interpreted_floats.rs | 226 +++++++++++++++++++++++++ ir/tests/interpreter.rs | 20 ++- ir/tests/runtime_storage.rs | 7 +- src/commands/ir.rs | 9 +- tests/float_storage_cli.rs | 38 +++++ 11 files changed, 424 insertions(+), 39 deletions(-) create mode 100644 ir/src/interpreter/scalar.rs create mode 100644 ir/tests/fixtures/float-storage-v7.wir create mode 100644 ir/tests/interpreted_floats.rs create mode 100644 tests/float_storage_cli.rs diff --git a/README.md b/README.md index c3c8666..bb79cbb 100644 --- a/README.md +++ b/README.md @@ -191,24 +191,48 @@ cargo run --locked -- ir run answer.wir --function @f7 ``` The output is `i32 42`. The default build verifies the whole module and runs -one explicit Whale-convention function with integer/bool parameters and scalar -or void return. Use repeated `--arg` decimal literals (`true`/`false` for Bool) +one explicit Whale-convention function with integer/bool/float parameters and scalar +or void return. Use repeated `--arg` decimal integer literals (`true`/`false` for Bool, +exact-width hexadecimal storage bits for floats) and `--max-steps` to set the instruction/terminator budget (default 1,000,000). Zero division/remainder and explicit traps return structured errors; unused executed operations still trap. Loops evaluate phi inputs simultaneously. This oracle supports integer constants, arithmetic, comparisons, bit casts, -checked pairs, select and control flow. It also supports tracked stack allocations, integer/Bool/data-pointer storage, +checked pairs, select and control flow. It also supports bit-exact f16/f32/f64 constants, mov/phi/select and tracked +stack allocations, integer/Bool/float/data-pointer storage, typed GEP, byte copies and fills, with initialization and capability checks. -It executes direct and signature-checked indirect Whale calls with integer/Bool, +It executes direct and signature-checked indirect Whale calls with integer/Bool/float, data-pointer and function-pointer arguments/results, using one shared fuel and memory arena. Function pointers retain their full signature and calling convention through mov/phi/select, storage and complete or split byte copies. It rejects -floating point, external/SysV execution and general aggregate values in every +floating arithmetic/comparisons/numerical conversions, external/SysV execution and general aggregate values in every block of the entry and reachable callees, including unreachable blocks. Native code generation remains unfinished. Legacy `undef` is a verification error. See the Rust `interpret_with_options` API for adjustable verification limits and trap IR identities. +### Execute exact floating storage and bitcasts + +`f16`, `f32` and `f64` use exactly 4, 8 and 16 hexadecimal storage digits. +Constants, arguments/returns, mov/phi/select, stack/global loads and stores, and +byte copies preserve every bit, including signaling/quiet NaN payloads and +signed zero. These operations perform no host floating-point conversion. +Equal-width integer/float `bitcast` reinterprets those bits; `fext`, `ftrunc` and +numeric integer/float conversions remain unsupported during execution. Bitcasts +cannot recover pointer or function-pointer authority from numerical bits. + +```sh +cargo run --locked -- ir run ir/tests/fixtures/float-storage-v7.wir --function @f0 --arg 0x7c01 +cargo run --locked -- ir run ir/tests/fixtures/float-storage-v7.wir --function @f3 +``` + +These print `f16 0x7c01` and `u64 9218868437227405603`. Floating storage obeys +the same bounds, explicit alignment, permissions, initialization masks and work +budgets as integer storage. A typed field load checks its value bytes without +requiring surrounding aggregate padding to be initialized. Plain storage and +copies never canonicalize a NaN; arithmetic and width-changing conversions have +separate semantics. + ### Execute tracked stack memory Save [the complete memory fixture](ir/tests/fixtures/tracked-memory-v4.wir) @@ -271,9 +295,8 @@ with existing compile-time `Global` declarations, while functions have their own source-name namespace. `ConstRef` still refers only to compile-time declarations; it never becomes a runtime address. Initialized storage accepts exact scalar literal values; pointer/function-pointer cells can start explicitly uninitialized. -Read-only uninitialized declarations and aggregate storage are rejected. Floating -storage literals round-trip, but the current integer interpreter rejects their -instantiation. Integer/Bool initializers initialize their value bytes; physical +Read-only uninitialized declarations and aggregate storage are rejected. Integer/Bool/float +initializers initialize their value bytes; physical zero-fill of uninitialized storage does not initialize a value. External storage definitions require an explicit nonempty `link_name`; internal diff --git a/ir/src/interpreter/memory.rs b/ir/src/interpreter/memory.rs index 1e527ea..c72bcf0 100644 --- a/ir/src/interpreter/memory.rs +++ b/ir/src/interpreter/memory.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MPL-2.0 //! Synthetic 64-bit addresses, byte initialization and separately copied capabilities. -use super::{integer, FunctionPointer, FunctionTarget, Value}; +use super::{scalar, FunctionPointer, FunctionTarget, Value}; use crate::{ConstValue, Target, Type, TypeLayout}; @@ -620,7 +620,7 @@ impl Memory { } let mut bits = [0u8; 16]; bits[..n].copy_from_slice(bytes); - Ok(Value::Scalar(integer::pack(ty, u128::from_le_bytes(bits)))) + Ok(Value::Scalar(scalar::pack(ty, u128::from_le_bytes(bits)))) } pub fn store(&mut self, pointer: Pointer, ty: &Type, value: &Value, align: u32) -> Result<()> { @@ -682,9 +682,7 @@ impl Memory { } u128::from(p.bits()).to_le_bytes() }, - Value::Scalar(v) => { - integer::raw(v, integer::shape(ty).map_or(1, |s| s.0)).to_le_bytes() - }, + Value::Scalar(v) => scalar::raw(ty, v).to_le_bytes(), _ => unreachable!("verified scalar or checked storage"), }; bytes.extend(data[..n].iter().enumerate().map(|(i, b)| (start + i, *b))); @@ -714,6 +712,23 @@ impl Memory { mod tests { use super::*; + #[test] + fn every_binary16_pattern_survives_typed_storage_and_copy() { + let mut memory = Memory::new(MemoryLimits::default()); + let source = memory.allocate(2, 2, 2).unwrap(); + let dest = memory.allocate(2, 2, 2).unwrap(); + for bits in 0..=u16::MAX { + let value = Value::Scalar(ConstValue::F(crate::FloatBits::F16(bits))); + memory.store(source, &Type::F16, &value, 2).unwrap(); + memory.copy(dest, source, 2, 2).unwrap(); + assert_eq!(memory.load(dest, &Type::F16, 2).unwrap().scalar(), value.scalar()); + assert_eq!( + memory.load(dest, &Type::U16, 2).unwrap().scalar(), + &ConstValue::U(bits.into()) + ); + } + } + fn trapped(result: Result, expected: MemoryTrap) { assert!(matches!(result, Err(Fault::Trap(t)) if t == expected)); } diff --git a/ir/src/interpreter/mod.rs b/ir/src/interpreter/mod.rs index c44c505..29a0fe5 100644 --- a/ir/src/interpreter/mod.rs +++ b/ir/src/interpreter/mod.rs @@ -1,9 +1,11 @@ // SPDX-License-Identifier: MPL-2.0 -//! A bounded oracle for verified scalar integer/control-flow IR. +//! A bounded oracle for verified scalar/control-flow IR. //! Tracked stack memory and bounded direct/indirect Whale calls are supported. mod integer; +mod scalar; + mod memory; pub use memory::{MemoryLimits, MemoryResource, MemoryTrap}; @@ -224,7 +226,7 @@ impl fmt::Display for InterpreterError { Self::GlobalMemory { global, reason } => write!(f, "global storage @g{}: {reason}", global.0), Self::GlobalMemoryLimit { global, resource, limit } => write!(f, "global storage @g{} memory {resource:?} limit {limit}", global.0), Self::UnknownFunction(id) => write!(f, "no body for function @f{}", id.0), - Self::UnsupportedSignature(id) => write!(f, "unsupported interpreter signature for @f{} (requires Whale convention and supported integer/bool/pointer parameters and scalar/pointer or void return)", id.0), + Self::UnsupportedSignature(id) => write!(f, "unsupported interpreter signature for @f{} (requires Whale convention and supported integer/bool/float/pointer parameters and scalar/pointer or void return)", id.0), Self::ArgumentCount { expected, got } => write!(f, "expected {expected} arguments, got {got}"), Self::ArgumentType { index, expected } => write!(f, "argument {index} must be a valid {expected} runtime value"), Self::UnsupportedInstruction { site, operation } => write!(f, "unsupported interpreter operation {operation} at {site}"), @@ -450,7 +452,7 @@ impl Value { } fn scalar_type(ty: &Type) -> bool { - *ty == Type::Bool || integer::shape(ty).is_some() + *ty == Type::Bool || integer::shape(ty).is_some() || scalar::float_type(ty) } fn value_type(ty: &Type) -> bool { @@ -496,22 +498,30 @@ fn destination(inst: &Instruction) -> Option { fn supported(inst: &Instruction) -> Result<(), &'static str> { use Instruction::*; let unsupported = match inst { - ConstDecl { value, .. } if !matches!(value, ConstValue::F(_)) => return Ok(()), + ConstDecl { .. } => return Ok(()), Const { ty, .. } if scalar_type(ty) => return Ok(()), Mov { ty, .. } | Phi { ty, .. } | Select { ty, .. } if value_type(ty) => return Ok(()), Bin { ty, .. } | Not { ty, .. } | Checked { ty, .. } if integer::shape(ty).is_some() => { return Ok(()) }, - Cmp { ty, .. } | ICmp { ty, .. } if scalar_type(ty) || matches!(ty, Type::Ptr(_)) => { + Cmp { ty, .. } | ICmp { ty, .. } + if *ty == Type::Bool || integer::shape(ty).is_some() || matches!(ty, Type::Ptr(_)) => + { return Ok(()) }, Cast { op, src_ty, dst_ty, .. } - if matches!(op, CastOp::ZExt | CastOp::SExt | CastOp::Trunc | CastOp::Bitcast) - && scalar_type(src_ty) + if matches!(op, CastOp::ZExt | CastOp::SExt | CastOp::Trunc) + && (*src_ty == Type::Bool || integer::shape(src_ty).is_some()) && integer::shape(dst_ty).is_some() => { return Ok(()) }, + Cast { op: CastOp::Bitcast, src_ty, dst_ty, .. } + if (integer::shape(src_ty).is_some() || scalar::float_type(src_ty)) + && (integer::shape(dst_ty).is_some() || scalar::float_type(dst_ty)) => + { + return Ok(()) + }, Extract { dst_ty, .. } if scalar_type(dst_ty) => return Ok(()), Alloca { ty, .. } | Uninit { ty, .. } if allocation_type(ty) => return Ok(()), Load { ty, .. } | Store { ty, .. } if value_type(ty) => return Ok(()), @@ -525,7 +535,7 @@ fn supported(inst: &Instruction) -> Result<(), &'static str> { | Memcpy { .. } | Memset { .. } => return Ok(()), Undef { .. } => "undef", - ConstDecl { .. } | Const { .. } => "non-integer constant", + Const { .. } => "non-scalar constant", Mov { .. } | Phi { .. } | Select { .. } | Extract { .. } => "non-scalar value", Bin { .. } | Not { .. } | Checked { .. } | Cmp { .. } | ICmp { .. } | FCmp { .. } => { "non-integer arithmetic/comparison" @@ -1442,6 +1452,9 @@ fn run_inner<'module>( u128::from(get(src).pointer().address), )), CastOp::Bitcast if matches!(src_ty, Type::Ptr(_)) => get(src).clone(), + CastOp::Bitcast => { + Value::Scalar(scalar::pack(dst_ty, scalar::raw(src_ty, scalar(src)))) + }, _ => Value::Scalar(integer::cast(op, src_ty, dst_ty, scalar(src))), }, Instruction::Alloca { align, .. } => { diff --git a/ir/src/interpreter/scalar.rs b/ir/src/interpreter/scalar.rs new file mode 100644 index 0000000..36cfd59 --- /dev/null +++ b/ir/src/interpreter/scalar.rs @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Storage reinterpretation only: no floating-point arithmetic or conversion. +use super::integer; +use crate::{ConstValue, FloatBits, Type}; + +pub(super) fn float_type(ty: &Type) -> bool { + matches!(ty, Type::F16 | Type::F32 | Type::F64) +} + +pub(super) fn raw(ty: &Type, value: &ConstValue) -> u128 { + match value { + ConstValue::F(bits) => u128::from(bits.bits()), + _ => integer::raw(value, integer::shape(ty).map_or(1, |s| s.0)), + } +} + +pub(super) fn pack(ty: &Type, bits: u128) -> ConstValue { + let float = match ty { + Type::F16 => FloatBits::F16(bits as u16), + Type::F32 => FloatBits::F32(bits as u32), + Type::F64 => FloatBits::F64(bits as u64), + _ => return integer::pack(ty, bits), + }; + ConstValue::F(float) +} diff --git a/ir/tests/fixtures/float-storage-v7.wir b/ir/tests/fixtures/float-storage-v7.wir new file mode 100644 index 0000000..8fcf5b4 --- /dev/null +++ b/ir/tests/fixtures/float-storage-v7.wir @@ -0,0 +1,35 @@ +module { + format_version 7 + semantics_version 1 + target "x86_64-whale-linux" + datalayout { ptr=64, endian=little } + + storage @g0 "payload": f64 = value f64 0x7ff0000000000123, align 8, access readonly, linkage internal + declare @f0 "identity_f16": whale (f16) -> f16, linkage internal + declare @f1 "identity_f32": whale (f32) -> f32, linkage internal + declare @f2 "identity_f64": whale (f64) -> f64, linkage internal + declare @f3 "stored_payload": whale () -> u64, linkage internal + + fn @f0 "identity_f16"(%v0 "bits": f16) -> f16, entry %b0 { + %b0 "entry": + ret f16 %v0 + } + fn @f1 "identity_f32"(%v0 "bits": f32) -> f32, entry %b0 { + %b0 "entry": + ret f32 %v0 + } + fn @f2 "identity_f64"(%v0 "bits": f64) -> f64, entry %b0 { + %b0 "entry": + ret f64 %v0 + } + fn @f3 "stored_payload"() -> u64, entry %b0 { + %b0 "entry": + %v0: ptr = global_addr @g0 + %v1: f64 = load f64, ptr %v0, align 8 + %v2: ptr = alloca f64, align 8 + store f64 %v1, ptr %v2, align 8 + %v3: f64 = load f64, ptr %v2, align 8 + %v4: u64 = bitcast f64 %v3 to u64 + ret u64 %v4 + } +} diff --git a/ir/tests/interpreted_calls.rs b/ir/tests/interpreted_calls.rs index e57d3d1..2dc49e7 100644 --- a/ir/tests/interpreted_calls.rs +++ b/ir/tests/interpreted_calls.rs @@ -118,10 +118,10 @@ fn direct_and_indirect_recursion_share_fuel_depth_and_total_frame_budgets() { #[test] fn reachable_unsupported_callees_are_preflighted_before_an_earlier_runtime_trap() { - let source = format!("{HEADER} declare @f0 \"entry\": whale () -> void, linkage internal declare @f1 \"bad\": whale () -> void, linkage internal fn @f0 \"entry\"() -> void, entry %b0 {{ %b0 \"entry\": trap reason=\"must not execute\" %b1 \"dead\": call whale void @f1() ret void }} fn @f1 \"bad\"() -> void, entry %b0 {{ %b0 \"entry\": %v0: f32 = const f32 0x00000000 ret void }} }}"); + let source = format!("{HEADER} declare @f0 \"entry\": whale () -> void, linkage internal declare @f1 \"bad\": whale () -> void, linkage internal fn @f0 \"entry\"() -> void, entry %b0 {{ %b0 \"entry\": trap reason=\"must not execute\" %b1 \"dead\": call whale void @f1() ret void }} fn @f1 \"bad\"() -> void, entry %b0 {{ %b0 \"entry\": %v0: f32 = const f32 0x00000000 %v1: f32 = fadd f32 %v0, %v0 ret void }} }}"); let m = parse_module(&source).unwrap(); assert!( - matches!(interpret(&m, FunctionId(0), &[]), Err(InterpreterError::UnsupportedInstruction { site, operation: "non-integer constant" }) if site.function == FunctionId(1)) + matches!(interpret(&m, FunctionId(0), &[]), Err(InterpreterError::UnsupportedInstruction { site, operation: "non-integer arithmetic/comparison" }) if site.function == FunctionId(1)) ); let source = source.replace( "call whale void @f1()", @@ -129,7 +129,7 @@ fn reachable_unsupported_callees_are_preflighted_before_an_earlier_runtime_trap( ); let m = parse_module(&source).unwrap(); assert!( - matches!(interpret(&m, FunctionId(0), &[]), Err(InterpreterError::UnsupportedInstruction { site, operation: "non-integer constant" }) if site.function == FunctionId(1)) + matches!(interpret(&m, FunctionId(0), &[]), Err(InterpreterError::UnsupportedInstruction { site, operation: "non-integer arithmetic/comparison" }) if site.function == FunctionId(1)) ); } @@ -283,7 +283,7 @@ fn indirect_preflight_ignores_unrelated_external_and_unsupported_same_signature_ 9, &["i32"], "i32", - "%b0 \"entry\": %v1: f32 = const f32 0x00000000 ret i32 %v0", + "%b0 \"entry\": %v1: f32 = const f32 0x00000000 %v2: f32 = fadd f32 %v1, %v1 ret i32 %v0", ); m.declarations.push(FunctionDecl { id: FunctionId(10), @@ -317,7 +317,7 @@ fn indirect_preflight_ignores_unrelated_external_and_unsupported_same_signature_ (ValueId(4), Type::I32), ]); assert!( - matches!(interpret(&m, FunctionId(8), &[]), Err(InterpreterError::UnsupportedInstruction { site, operation: "non-integer constant" }) if site.function == FunctionId(9)) + matches!(interpret(&m, FunctionId(8), &[]), Err(InterpreterError::UnsupportedInstruction { site, operation: "non-integer arithmetic/comparison" }) if site.function == FunctionId(9)) ); } diff --git a/ir/tests/interpreted_floats.rs b/ir/tests/interpreted_floats.rs new file mode 100644 index 0000000..7d4caf1 --- /dev/null +++ b/ir/tests/interpreted_floats.rs @@ -0,0 +1,226 @@ +use ir::*; + +const HEADER: &str = "module { format_version 7 semantics_version 1 target \"x86_64-whale-linux\" datalayout { ptr=64, endian=little }"; + +fn program(types: &[&str], ret: &str, body: &str) -> Module { + let params = types + .iter() + .enumerate() + .map(|(i, t)| format!("%v{i} \"p{i}\": {t}")) + .collect::>() + .join(", "); + parse_module(&format!("{HEADER} declare @f0 \"test\": whale ({}) -> {ret}, linkage internal fn @f0 \"test\"({params}) -> {ret}, entry %b0 {{ {body} }} }}", types.join(", "))).unwrap() +} + +fn execute(types: &[&str], ret: &str, body: &str, args: &[ConstValue]) -> ConstValue { + interpret(&program(types, ret, body), FunctionId(0), args).unwrap().value.unwrap() +} + +fn vectors() -> Vec<(&'static str, FloatBits)> { + [ + ("f16", vec![0, 0x8000, 1, 0x8001, 0x3c00, 0x7bff, 0x7c00, 0xfc00, 0x7c01, 0x7e01, 0xffff]), + ( + "f32", + vec![ + 0, 0x80000000, 1, 0x80000001, 0x3f800000, 0x7f7fffff, 0x7f800000, 0xff800000, + 0x7f800001, 0x7fc01234, 0xffffffff, + ], + ), + ( + "f64", + vec![ + 0, + 0x8000000000000000, + 1, + 0x8000000000000001, + 0x3ff0000000000000, + 0x7fefffffffffffff, + 0x7ff0000000000000, + 0xfff0000000000000, + 0x7ff0000000000001, + 0x7ff8123456789abc, + 0xffffffffffffffff, + ], + ), + ] + .into_iter() + .flat_map(|(ty, bits)| { + bits.into_iter().map(move |b| { + ( + ty, + match ty { + "f16" => FloatBits::F16(b as u16), + "f32" => FloatBits::F32(b as u32), + _ => FloatBits::F64(b), + }, + ) + }) + }) + .collect() +} + +#[test] +fn exact_constants_declarations_arguments_and_control_flow_retain_storage_bits() { + for (ty, bits) in vectors() { + let value = ConstValue::F(bits); + for source in [ + format!("const {ty} {bits}"), + format!("const_decl \"bits\" {ty} {bits} => const {ty} {bits}"), + ] { + assert_eq!( + execute(&[], ty, &format!("%b0 \"entry\": %v1: {ty} = {source} ret {ty} %v1"), &[]), + value + ); + } + let body=format!("%b0 \"entry\": %v2: {ty} = mov {ty} %v0 cbr bool %v1, label %b1, label %b2 %b1 \"true\": br label %b3 %b2 \"false\": br label %b3 %b3 \"join\": %v3: {ty} = phi {ty} [ %v0, %b1 ], [ %v2, %b2 ] %v4: {ty} = select bool %v1, {ty} %v3, {ty} %v2 ret {ty} %v4"); + for condition in [false, true] { + assert_eq!( + execute(&[ty, "bool"], ty, &body, &[value.clone(), ConstValue::Bool(condition)]), + value + ); + } + let runtime = RuntimeValue::scalar( + match bits { + FloatBits::F16(_) => Type::F16, + FloatBits::F32(_) => Type::F32, + FloatBits::F64(_) => Type::F64, + }, + value.clone(), + ) + .unwrap(); + let module = program(&[ty], ty, &format!("%b0 \"entry\": ret {ty} %v0")); + let result = interpret_values(&module, FunctionId(0), &[runtime]).unwrap(); + assert_eq!(result.value.unwrap().scalar_value(), Some(&value)); + } +} + +#[test] +fn signed_unsigned_bitcasts_and_storage_roundtrips_preserve_every_edge_pattern() { + for (ty, bits) in vectors() { + let width = bits.width(); + for int in [format!("i{width}"), format!("u{width}")] { + let body=format!("%b0 \"entry\": %v1: {int} = bitcast {ty} %v0 to {int} %v2: ptr<{int}> = alloca {int}, align 1 store {int} %v1, ptr<{int}> %v2, align 1 %v3: {int} = load {int}, ptr<{int}> %v2, align 1 %v4: {ty} = bitcast {int} %v3 to {ty} %v5: ptr<{ty}> = alloca {ty}, align 1 store {ty} %v4, ptr<{ty}> %v5, align 1 %v6: {ty} = load {ty}, ptr<{ty}> %v5, align 1 ret {ty} %v6"); + assert_eq!(execute(&[ty], ty, &body, &[ConstValue::F(bits)]), ConstValue::F(bits)); + // Independently check the integer result, including its sign bit. + let result = execute( + &[ty], + &int, + &format!("%b0 \"entry\": %v1: {int} = bitcast {ty} %v0 to {int} ret {int} %v1"), + &[ConstValue::F(bits)], + ); + let expected = if int.starts_with('u') { + ConstValue::U(bits.bits().into()) + } else { + let shift = 128 - u32::from(width); + ConstValue::I(((i128::from(bits.bits())) << shift) >> shift) + }; + assert_eq!(result, expected); + } + } +} + +#[test] +fn tracked_float_globals_and_split_copies_preserve_bits() { + for (ty, bits) in vectors() { + let n = bits.width() / 8; + let source=format!("{HEADER} storage @g0 \"bits\": {ty} = value {ty} {bits}, align 1, access readwrite, linkage internal declare @f0 \"test\": whale () -> {ty}, linkage internal fn @f0 \"test\"() -> {ty}, entry %b0 {{ %b0 \"entry\": %v0: ptr<{ty}> = global_addr @g0 %v1: ptr<{ty}> = alloca {ty}, align 1 %v2: ptr = bitcast ptr<{ty}> %v0 to ptr %v3: ptr = bitcast ptr<{ty}> %v1 to ptr %v4: u64 = const u64 1 memcpy ptr %v3, ptr %v2, u64 %v4, align 1 %v5: ptr = gep %v2, %v4 %v6: ptr = gep %v3, %v4 %v7: u64 = const u64 {} memcpy ptr %v6, ptr %v5, u64 %v7, align 1 %v8: {ty} = load {ty}, ptr<{ty}> %v1, align 1 ret {ty} %v8 }} }}",n-1); + let module = parse_module(&source).unwrap(); + for _ in 0..2 { + assert_eq!( + interpret(&module, FunctionId(0), &[]).unwrap().value, + Some(ConstValue::F(bits)) + ); + } + } +} + +#[test] +fn floating_fields_skip_padding_but_value_bytes_require_initialization() { + for (ty, bits) in vectors() { + let body=format!("%b0 \"entry\": %v0: ptr = alloca struct{{u8, {ty}}}, align 8 %v1: u64 = const u64 0 %v2: u64 = const u64 1 %v3: ptr<{ty}> = gep %v0, %v1, %v2 %v4: {ty} = const {ty} {bits} store {ty} %v4, ptr<{ty}> %v3, align 1 %v5: {ty} = load {ty}, ptr<{ty}> %v3, align 1 ret {ty} %v5"); + assert_eq!(execute(&[], ty, &body, &[]), ConstValue::F(bits)); + let unset = body.replace( + &format!("store {ty} %v4, ptr<{ty}> %v3, align 1"), + &format!("uninit {ty}, ptr<{ty}> %v3, align 1"), + ); + assert!(matches!( + interpret(&program(&[], ty, &unset), FunctionId(0), &[]), + Err(InterpreterError::Trap(InterpreterTrap { + reason: TrapReason::Memory(MemoryTrap::Uninitialized { .. }), + .. + })) + )); + } + let body="%b0 \"entry\": %v0: ptr> = alloca array, align 8 %v1: ptr = bitcast ptr> %v0 to ptr %v2: u64 = const u64 1 %v3: ptr = gep %v1, %v2 %v4: ptr = bitcast ptr %v3 to ptr %v5: f64 = load f64, ptr %v4, align 8 ret f64 %v5"; + assert!(matches!( + interpret(&program(&[], "f64", body), FunctionId(0), &[]), + Err(InterpreterError::Trap(InterpreterTrap { + reason: TrapReason::Memory(MemoryTrap::Misaligned { alignment: 8, .. }), + .. + })) + )); +} + +#[test] +fn partial_float_copy_transfers_initialization_masks() { + let body="%b0 \"entry\": %v0: ptr = alloca f64, align 8 %v1: ptr = alloca f64, align 8 %v2: ptr = bitcast ptr %v0 to ptr %v3: ptr = bitcast ptr %v1 to ptr %v4: u8 = const u8 255 store u8 %v4, ptr %v2, align 1 %v5: u64 = const u64 8 memcpy ptr %v3, ptr %v2, u64 %v5, align 8 %v6: f64 = load f64, ptr %v1, align 8 ret f64 %v6"; + assert!(matches!( + interpret(&program(&[], "f64", body), FunctionId(0), &[]), + Err(InterpreterError::Trap(InterpreterTrap { + reason: TrapReason::Memory(MemoryTrap::Uninitialized { offset: 1 }), + .. + })) + )); +} + +#[test] +fn float_bits_do_not_recreate_pointer_authority() { + let body="%b0 \"entry\": %v0: ptr = alloca u32, align 4 %v1: u64 = ptrtoint ptr %v0 to u64 %v2: f64 = bitcast u64 %v1 to f64 %v3: u64 = bitcast f64 %v2 to u64 %v4: ptr = inttoptr u64 %v3 to ptr %v5: u32 = load u32, ptr %v4, align 4 ret u32 %v5"; + assert!(matches!( + interpret(&program(&[], "u32", body), FunctionId(0), &[]), + Err(InterpreterError::Trap(InterpreterTrap { + reason: TrapReason::Memory(MemoryTrap::MissingProvenance), + .. + })) + )); + // A floating store clears pointer metadata even when all address bits agree. + let body=body.replace("%v4: ptr = inttoptr u64 %v3 to ptr","%v6: ptr> = alloca ptr, align 8 store ptr %v0, ptr> %v6, align 8 %v7: ptr = bitcast ptr> %v6 to ptr store f64 %v2, ptr %v7, align 8 %v4: ptr = load ptr, ptr> %v6, align 8"); + assert!(matches!( + interpret(&program(&[], "u32", &body), FunctionId(0), &[]), + Err(InterpreterError::Trap(InterpreterTrap { + reason: TrapReason::Memory(MemoryTrap::MissingProvenance), + .. + })) + )); +} + +#[test] +fn direct_and_indirect_float_calls_share_storage_without_rounding() { + for (ty, bits) in vectors() { + let source=format!("{HEADER} declare @f0 \"entry\": whale ({ty}) -> {ty}, linkage internal declare @f1 \"identity\": whale ({ty}) -> {ty}, linkage internal fn @f0 \"entry\"(%v0 \"value\": {ty}) -> {ty}, entry %b0 {{ %b0 \"entry\": %v1: {ty} = call whale {ty} @f1(%v0) %v2: fnptr {ty}> = function_addr @f1 %v3: {ty} = call whale {ty} indirect %v2(%v1) ret {ty} %v3 }} fn @f1 \"identity\"(%v0 \"value\": {ty}) -> {ty}, entry %b0 {{ %b0 \"entry\": %v1: ptr<{ty}> = alloca {ty}, align 1 store {ty} %v0, ptr<{ty}> %v1, align 1 %v2: {ty} = load {ty}, ptr<{ty}> %v1, align 1 ret {ty} %v2 }} }}"); + assert_eq!( + interpret(&parse_module(&source).unwrap(), FunctionId(0), &[ConstValue::F(bits)]) + .unwrap() + .value, + Some(ConstValue::F(bits)) + ); + } +} + +#[test] +fn invalid_bitcasts_and_float_numeric_operations_remain_rejected() { + for (src, dst, value) in [ + ("f16", "u32", "0x7e01"), + ("bool", "f16", "true"), + ("f64", "ptr", "0x0000000000000000"), + ] { + let source=format!("{HEADER} declare @f0 \"bad\": whale () -> {dst}, linkage internal fn @f0 \"bad\"() -> {dst}, entry %b0 {{ %b0 \"entry\": %v0: {src} = const {src} {value} %v1: {dst} = bitcast {src} %v0 to {dst} ret {dst} %v1 }} }}"); + assert!(parse_module(&source).is_err()); + } + let module = + program(&["f32"], "f32", "%b0 \"entry\": %v1: f32 = fadd f32 %v0, %v0 ret f32 %v1"); + assert!(matches!( + interpret(&module, FunctionId(0), &[ConstValue::F(FloatBits::F32(0))]), + Err(InterpreterError::UnsupportedInstruction { .. }) + )); +} diff --git a/ir/tests/interpreter.rs b/ir/tests/interpreter.rs index a1f60cb..15a3b27 100644 --- a/ir/tests/interpreter.rs +++ b/ir/tests/interpreter.rs @@ -357,8 +357,11 @@ fn invalid_arguments_modules_and_unsupported_dead_instructions_fail_before_execu Err(InterpreterError::Verification(_)) )); for (body, operation) in [ - ("%v8: ptr = alloca f32, align 4", "alloca"), - ("%v8: f32 = const f32 0x00000000", "non-integer constant"), + ( + "%v8: f32 = const f32 0x00000000 %v9: f32 = fadd f32 %v8, %v8", + "non-integer arithmetic/comparison", + ), + ("%v8: f32 = const f32 0x00000000 %v9: f64 = fext f32 %v8 to f64", "unsupported cast"), ] { let m = program( &[], @@ -372,7 +375,7 @@ fn invalid_arguments_modules_and_unsupported_dead_instructions_fail_before_execu let m = program(&["f32"], "f32", "%b11 \"entry\": ret f32 %v0"); assert!(matches!( interpret(&m, FunctionId(7), &[ConstValue::F(FloatBits::F32(0))]), - Err(InterpreterError::UnsupportedSignature(_)) + Ok(InterpreterResult { value: Some(ConstValue::F(FloatBits::F32(0))), .. }) )); let m = parse_module(include_str!("fixtures/calls-v3.wir")).unwrap(); assert!(matches!( @@ -401,7 +404,11 @@ fn published_integer_fixture_returns_values_and_explicit_overflow_trap() { #[test] fn verification_checks_other_functions_but_execution_restricts_only_the_selected_body() { let mut m = program(&[], "void", "%b11 \"entry\": ret void"); - let other = program(&[], "void", "%b11 \"entry\": %v8: f32 = const f32 0x00000000 ret void"); + let other = program( + &[], + "void", + "%b11 \"entry\": %v8: f32 = const f32 0x00000000 %v9: f32 = fadd f32 %v8, %v8 ret void", + ); let mut function = other.functions[0].clone(); function.id = FunctionId(8); function.name = "other".into(); @@ -413,7 +420,10 @@ fn verification_checks_other_functions_but_execution_restricts_only_the_selected assert_eq!(interpret(&m, FunctionId(7), &[]).unwrap().value, None); assert!(matches!( interpret(&m, FunctionId(8), &[]), - Err(InterpreterError::UnsupportedInstruction { operation: "non-integer constant", .. }) + Err(InterpreterError::UnsupportedInstruction { + operation: "non-integer arithmetic/comparison", + .. + }) )); m.functions[1].blocks[0].terminator = None; assert!(matches!(interpret(&m, FunctionId(7), &[]), Err(InterpreterError::Verification(_)))); diff --git a/ir/tests/runtime_storage.rs b/ir/tests/runtime_storage.rs index 50322b5..cb9e152 100644 --- a/ir/tests/runtime_storage.rs +++ b/ir/tests/runtime_storage.rs @@ -398,14 +398,11 @@ fn global_addresses_keep_identity_through_indirect_calls_and_returns() { } #[test] -fn floating_storage_representation_remains_bit_exact_but_execution_is_explicitly_unsupported() { +fn floating_storage_instantiates_without_losing_payload_bits() { let m=with_storage("storage @g0 \"bits\": f32 = value f32 0xffc01234, align 4, access readonly, linkage internal", "void", "ret void"); canonical(&m); assert!(print_module(&m).contains("0xffc01234")); - assert!(matches!( - interpret(&m, FunctionId(0), &[]), - Err(InterpreterError::UnsupportedGlobal(GlobalId(0))) - )); + assert_eq!(interpret(&m, FunctionId(0), &[]).unwrap().value, None); } // Existing semantic assertions intentionally inspect the preserved leaf cause. diff --git a/src/commands/ir.rs b/src/commands/ir.rs index bfd40f3..28c2178 100644 --- a/src/commands/ir.rs +++ b/src/commands/ir.rs @@ -184,7 +184,7 @@ fn print_help() { " verify Read and verify format 3/4/5/6/7 typed IR", "\n", " print [-o ] Verify and write canonical typed IR", "\n", " run --function @fN [--arg ...] [--max-steps ] [--max-memory ]", "\n", - " Execute integer/bool, control flow and tracked stack memory; default 1000000 steps, 64 MiB storage.", "\n", + " Execute integer/bool/float values, control flow and tracked stack memory; default 1000000 steps, 64 MiB storage.", "\n", " lower [-o ] Lower AST JSON (requires socket-cli)", "\n", " lower options: --target x86_64-whale-linux, --no-verify", "\n", " AST envelope: reads format_version 2/3/4, writes 4; semantics_version: 1, features: [], program: AST", "\n", @@ -212,7 +212,7 @@ fn execute( } let arguments: Vec<_> = fun.params.iter().zip(literals).enumerate().map(|(index, (param, literal))| { scalar_argument(¶m.ty, literal).unwrap_or_else(|| { - fail(format!("{input}: argument {index} must be an exact decimal {} literal (bool uses true/false)", param.ty)) + fail(format!("{input}: argument {index} must be an exact {} literal (integers use decimal, bool true/false, floats exact-width 0x bits)", param.ty)) }) }).collect(); let mut options = ir::InterpreterOptions::default(); @@ -229,13 +229,16 @@ fn execute( Some(ir::ConstValue::U(v)) => stdout(format!("{} {v}\n", fun.ret_ty)), Some(ir::ConstValue::Bool(v)) => stdout(format!("bool {v}\n")), None => stdout("void\n"), - Some(ir::ConstValue::F(_)) => unreachable!("interpreter scalar subset"), + Some(ir::ConstValue::F(v)) => stdout(format!("{} {v}\n", fun.ret_ty)), } } fn scalar_argument(ty: &ir::Type, literal: &str) -> Option { let decimal = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()); match ty { + ir::Type::F16 => ir::FloatBits::parse(16, literal).ok().map(ir::ConstValue::F), + ir::Type::F32 => ir::FloatBits::parse(32, literal).ok().map(ir::ConstValue::F), + ir::Type::F64 => ir::FloatBits::parse(64, literal).ok().map(ir::ConstValue::F), ir::Type::Bool => match literal { "true" => Some(ir::ConstValue::Bool(true)), "false" => Some(ir::ConstValue::Bool(false)), diff --git a/tests/float_storage_cli.rs b/tests/float_storage_cli.rs new file mode 100644 index 0000000..a18f87f --- /dev/null +++ b/tests/float_storage_cli.rs @@ -0,0 +1,38 @@ +use std::{path::PathBuf, process::Command}; + +fn run(function: &str, literal: Option<&str>) -> std::process::Output { + let input = + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("ir/tests/fixtures/float-storage-v7.wir"); + let mut command = Command::new(env!("CARGO_BIN_EXE_whale")); + command.args(["ir", "run"]).arg(input).args(["--function", function]); + if let Some(value) = literal { + command.args(["--arg", value]); + } + command.output().unwrap() +} + +#[test] +fn float_arguments_results_and_storage_use_exact_width_hexadecimal_bits() { + for (function, literal, expected) in [ + ("@f0", Some("0x7c01"), "f16 0x7c01\n"), + ("@f1", Some("0x80000000"), "f32 0x80000000\n"), + ("@f2", Some("0xfff0000000000123"), "f64 0xfff0000000000123\n"), + ("@f3", None, "u64 9218868437227405603\n"), + ] { + let output = run(function, literal); + assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); + assert_eq!(output.stdout, expected.as_bytes()); + } +} + +#[test] +fn malformed_float_arguments_fail_without_panicking_or_printing_a_value() { + for literal in ["0x0000", "0x000000000", "0xgggggggg", "NaN", "-0.0", "0X80000000"] { + let output = run("@f1", Some(literal)); + assert!(!output.status.success()); + assert!(output.stdout.is_empty()); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("floats exact-width 0x bits"), "{stderr}"); + assert!(!stderr.contains("panicked")); + } +} From 3c4219ddd0295de88d257d076475a87d2a4806d6 Mon Sep 17 00:00:00 2001 From: LunaStev Date: Wed, 21 Oct 2026 19:49:46 +0900 Subject: [PATCH 8/8] feat(ir): define and execute NaN-aware floating comparisons Map generic equality and ordering to ordered predicates, and generic inequality to unordered-or-not-equal. Share this contract between constant evaluation and runtime execution, with integer IEEE comparison that preserves NaN payloads and avoids host floating exceptions. Execute all explicit ordered/unordered predicates and document the public mapping and executable examples. Closes #198 Closes #265 Signed-off-by: LunaStev --- README.md | 38 +++- ir/src/const_expr.rs | 20 +- ir/src/float.rs | 54 +++++ ir/src/instr.rs | 21 +- ir/src/interpreter/mod.rs | 12 +- ir/src/interpreter/scalar.rs | 7 + ir/tests/fixtures/float-comparisons-v7.wir | 26 +++ ir/tests/float_comparisons.rs | 252 +++++++++++++++++++++ tests/float_comparisons_cli.rs | 24 ++ 9 files changed, 442 insertions(+), 12 deletions(-) create mode 100644 ir/tests/fixtures/float-comparisons-v7.wir create mode 100644 ir/tests/float_comparisons.rs create mode 100644 tests/float_comparisons_cli.rs diff --git a/README.md b/README.md index bb79cbb..90c9131 100644 --- a/README.md +++ b/README.md @@ -206,7 +206,7 @@ It executes direct and signature-checked indirect Whale calls with integer/Bool/ data-pointer and function-pointer arguments/results, using one shared fuel and memory arena. Function pointers retain their full signature and calling convention through mov/phi/select, storage and complete or split byte copies. It rejects -floating arithmetic/comparisons/numerical conversions, external/SysV execution and general aggregate values in every +floating arithmetic/numerical conversions, external/SysV execution and general aggregate values in every block of the entry and reachable callees, including unreachable blocks. Native code generation remains unfinished. Legacy `undef` is a verification error. See the Rust `interpret_with_options` API for adjustable verification limits and trap IR identities. @@ -233,6 +233,42 @@ requiring surrounding aggregate padding to be initialized. Plain storage and copies never canonicalize a NaN; arithmetic and width-changing conversions have separate semantics. +### Compare floating values + +Generic floating comparisons have the following scalar contract in both +constant evaluation and interpreted IR. Every result has type `bool`. + +| Generic operator | Explicit `fcmp` predicate | Result if either operand is NaN | +| --- | --- | --- | +| `cmp feq` | `oeq` | false | +| `cmp fne` | `une` | true | +| `cmp flt` | `olt` | false | +| `cmp fle` | `ole` | false | +| `cmp fgt` | `ogt` | false | +| `cmp fge` | `oge` | false | + +Thus generic `!=` is always the logical negation of generic `==`, including +NaN on either side. `+0` and `-0` compare equal; infinities follow numerical +ordering. All NaNs, including signaling NaNs and every sign/payload, make the +operands unordered. Comparisons do not change their original storage bits or +raise floating-point traps. + +Explicit `fcmp` supports `oeq`, `one`, `olt`, `ole`, `ogt`, `oge`, `ord`, `uno`, +`ueq`, `une`, `ult`, `ule`, `ugt` and `uge`. Ordered relational predicates +require neither operand to be NaN; unordered relational predicates also return +true if either operand is NaN. `ord` tests that neither is NaN, and `uno` tests +that at least one is NaN. In particular, explicit `one` returns false for NaN, +while generic `fne` maps to `une` and returns true. `CmpOp::float_predicate` +exposes this mapping and `FloatBits::compare` evaluates equal-width predicates. +Runtime execution preserves instruction/trap order, including unused comparisons. + +```sh +cargo run --locked -- ir run ir/tests/fixtures/float-comparisons-v7.wir --function @f0 --arg 0x7ff0000000000001 --arg 0x3ff0000000000000 +cargo run --locked -- ir run ir/tests/fixtures/float-comparisons-v7.wir --function @f1 --arg 0x7ff0000000000001 --arg 0x3ff0000000000000 +``` + +These print `bool true` (generic inequality) and `bool false` (ordered inequality). + ### Execute tracked stack memory Save [the complete memory fixture](ir/tests/fixtures/tracked-memory-v4.wir) diff --git a/ir/src/const_expr.rs b/ir/src/const_expr.rs index 38b3aa9..a2c6f44 100644 --- a/ir/src/const_expr.rs +++ b/ir/src/const_expr.rs @@ -412,15 +412,17 @@ fn const_cmp( let (ConstValue::F(a), ConstValue::F(b)) = (l, r) else { return Err(ConstEvalError::UnsupportedOperation); }; - let (a, b) = (a.to_f64(), b.to_f64()); - return Ok(match op { - ConstCompareOp::Eq => a == b, - ConstCompareOp::Ne => a != b, - ConstCompareOp::Lt => a < b, - ConstCompareOp::Le => a <= b, - ConstCompareOp::Gt => a > b, - ConstCompareOp::Ge => a >= b, - }); + let generic = match op { + ConstCompareOp::Eq => crate::CmpOp::FEq, + ConstCompareOp::Ne => crate::CmpOp::FNe, + ConstCompareOp::Lt => crate::CmpOp::FLt, + ConstCompareOp::Le => crate::CmpOp::FLe, + ConstCompareOp::Gt => crate::CmpOp::FGt, + ConstCompareOp::Ge => crate::CmpOp::FGe, + }; + return a + .compare(*b, &generic.float_predicate().unwrap()) + .ok_or(ConstEvalError::TypeMismatch); } // bool은 eq/ne만 diff --git a/ir/src/float.rs b/ir/src/float.rs index 431b969..721d867 100644 --- a/ir/src/float.rs +++ b/ir/src/float.rs @@ -25,6 +25,60 @@ impl FloatBits { } } + /// Compare equal-width IEEE values using an explicit ordered/unordered + /// predicate. Returns `None` for mismatched widths. Integer bit ordering + /// avoids host floating exceptions/conversions and treats both zeros equal; + /// any quiet or signaling NaN makes the operands unordered. + pub fn compare(self, rhs: Self, predicate: &crate::FCmpPred) -> Option { + use crate::FCmpPred::*; + use std::cmp::Ordering; + if self.width() != rhs.width() { + return None; + } + let (exponent, fraction) = match self { + Self::F16(_) => (0x7c00, 0x03ff), + Self::F32(_) => (0x7f800000, 0x007fffff), + Self::F64(_) => (0x7ff0000000000000, 0x000fffffffffffff), + }; + let (a, b) = (self.bits(), rhs.bits()); + let nan = |bits| bits & exponent == exponent && bits & fraction != 0; + let ordered = !nan(a) && !nan(b); + let sign = 1u64 << (self.width() - 1); + let magnitude = sign - 1; + let order = if a & magnitude == 0 && b & magnitude == 0 { + Ordering::Equal + } else if (a ^ b) & sign != 0 { + if a & sign != 0 { + Ordering::Less + } else { + Ordering::Greater + } + } else if a & sign != 0 { + b.cmp(&a) + } else { + a.cmp(&b) + }; + let equal = order.is_eq(); + let less = order.is_lt(); + let greater = order.is_gt(); + Some(match predicate { + Oeq => ordered && equal, + One => ordered && !equal, + Olt => ordered && less, + Ole => ordered && !greater, + Ogt => ordered && greater, + Oge => ordered && !less, + Ord => ordered, + Uno => !ordered, + Ueq => !ordered || equal, + Une => !ordered || !equal, + Ult => !ordered || less, + Ule => !ordered || !greater, + Ugt => !ordered || greater, + Uge => !ordered || !less, + }) + } + /// Exact-width hexadecimal storage, not a decimal floating-point number. pub fn parse(width: u16, text: &str) -> Result { let digits = match width { diff --git a/ir/src/instr.rs b/ir/src/instr.rs index 1ee2487..759ae44 100644 --- a/ir/src/instr.rs +++ b/ir/src/instr.rs @@ -24,6 +24,8 @@ pub enum ICmpPred { Sge, } +/// IEEE scalar predicates. `O*` require ordered operands; `U*` also accept +/// unordered operands (at least one NaN). Comparisons never modify storage bits. #[derive(Clone, Debug, PartialEq, Eq)] pub enum FCmpPred { Oeq, @@ -335,7 +337,7 @@ pub enum CmpOp { UGt, UGe, - // float ordering + // Floating comparisons use `float_predicate`, including unordered FNe. FEq, FNe, FLt, @@ -343,3 +345,20 @@ pub enum CmpOp { FGt, FGe, } + +impl CmpOp { + /// The generic scalar floating contract: equality/order are ordered, while + /// inequality is unordered-or-not-equal, exactly the negation of equality. + /// Integer and pointer operators have no floating predicate. + pub fn float_predicate(self) -> Option { + Some(match self { + Self::FEq => FCmpPred::Oeq, + Self::FNe => FCmpPred::Une, + Self::FLt => FCmpPred::Olt, + Self::FLe => FCmpPred::Ole, + Self::FGt => FCmpPred::Ogt, + Self::FGe => FCmpPred::Oge, + _ => return None, + }) + } +} diff --git a/ir/src/interpreter/mod.rs b/ir/src/interpreter/mod.rs index 29a0fe5..f19e84d 100644 --- a/ir/src/interpreter/mod.rs +++ b/ir/src/interpreter/mod.rs @@ -509,6 +509,7 @@ fn supported(inst: &Instruction) -> Result<(), &'static str> { { return Ok(()) }, + Cmp { ty, .. } | FCmp { ty, .. } if scalar::float_type(ty) => return Ok(()), Cast { op, src_ty, dst_ty, .. } if matches!(op, CastOp::ZExt | CastOp::SExt | CastOp::Trunc) && (*src_ty == Type::Bool || integer::shape(src_ty).is_some()) @@ -1416,7 +1417,13 @@ fn run_inner<'module>( !integer::raw(scalar(src), integer::shape(ty).unwrap().0), )), Instruction::Cmp { op, ty, lhs, rhs, .. } => { - let result = if matches!(ty, Type::Ptr(_)) { + let result = if scalar::float_type(ty) { + scalar::compare( + &op.float_predicate().unwrap(), + scalar(lhs), + scalar(rhs), + ) + } else if matches!(ty, Type::Ptr(_)) { pointer_compare( &memory, &cmp_pred(*op), @@ -1438,6 +1445,9 @@ fn run_inner<'module>( }; Value::Scalar(ConstValue::Bool(result)) }, + Instruction::FCmp { pred, lhs, rhs, .. } => Value::Scalar(ConstValue::Bool( + scalar::compare(pred, scalar(lhs), scalar(rhs)), + )), Instruction::Select { cond, on_true, on_false, .. } => { get(if get(cond).boolean() { on_true } else { on_false }).clone() }, diff --git a/ir/src/interpreter/scalar.rs b/ir/src/interpreter/scalar.rs index 36cfd59..3fb82c2 100644 --- a/ir/src/interpreter/scalar.rs +++ b/ir/src/interpreter/scalar.rs @@ -23,3 +23,10 @@ pub(super) fn pack(ty: &Type, bits: u128) -> ConstValue { }; ConstValue::F(float) } + +pub(super) fn compare(predicate: &crate::FCmpPred, lhs: &ConstValue, rhs: &ConstValue) -> bool { + let (ConstValue::F(lhs), ConstValue::F(rhs)) = (lhs, rhs) else { + unreachable!("verified floating operands") + }; + lhs.compare(*rhs, predicate).expect("verified matching floating widths") +} diff --git a/ir/tests/fixtures/float-comparisons-v7.wir b/ir/tests/fixtures/float-comparisons-v7.wir new file mode 100644 index 0000000..a7e53be --- /dev/null +++ b/ir/tests/fixtures/float-comparisons-v7.wir @@ -0,0 +1,26 @@ +module { + format_version 7 + semantics_version 1 + target "x86_64-whale-linux" + datalayout { ptr=64, endian=little } + + declare @f0 "generic_ne": whale (f64, f64) -> bool, linkage internal + declare @f1 "ordered_ne": whale (f64, f64) -> bool, linkage internal + declare @f2 "zero_eq": whale (f16, f16) -> bool, linkage internal + + fn @f0 "generic_ne"(%v0 "a": f64, %v1 "b": f64) -> bool, entry %b0 { + %b0 "entry": + %v2: bool = cmp fne f64 %v0, %v1 + ret bool %v2 + } + fn @f1 "ordered_ne"(%v0 "a": f64, %v1 "b": f64) -> bool, entry %b0 { + %b0 "entry": + %v2: bool = fcmp one f64 %v0, %v1 + ret bool %v2 + } + fn @f2 "zero_eq"(%v0 "a": f16, %v1 "b": f16) -> bool, entry %b0 { + %b0 "entry": + %v2: bool = cmp feq f16 %v0, %v1 + ret bool %v2 + } +} diff --git a/ir/tests/float_comparisons.rs b/ir/tests/float_comparisons.rs new file mode 100644 index 0000000..7b1a387 --- /dev/null +++ b/ir/tests/float_comparisons.rs @@ -0,0 +1,252 @@ +use ir::*; + +// Independent IEEE truth table: columns less/equal/greater/unordered. The +// literal ranks below are human-assigned, rather than using production compare. +const PREDICATES: [(&str, FCmpPred, [bool; 4]); 14] = [ + ("oeq", FCmpPred::Oeq, [false, true, false, false]), + ("one", FCmpPred::One, [true, false, true, false]), + ("olt", FCmpPred::Olt, [true, false, false, false]), + ("ole", FCmpPred::Ole, [true, true, false, false]), + ("ogt", FCmpPred::Ogt, [false, false, true, false]), + ("oge", FCmpPred::Oge, [false, true, true, false]), + ("ord", FCmpPred::Ord, [true, true, true, false]), + ("uno", FCmpPred::Uno, [false, false, false, true]), + ("ueq", FCmpPred::Ueq, [false, true, false, true]), + ("une", FCmpPred::Une, [true, false, true, true]), + ("ult", FCmpPred::Ult, [true, false, false, true]), + ("ule", FCmpPred::Ule, [true, true, false, true]), + ("ugt", FCmpPred::Ugt, [false, false, true, true]), + ("uge", FCmpPred::Uge, [false, true, true, true]), +]; +const GENERIC: [(&str, CmpOp, ConstCompareOp, usize); 6] = [ + ("feq", CmpOp::FEq, ConstCompareOp::Eq, 0), + ("fne", CmpOp::FNe, ConstCompareOp::Ne, 9), + ("flt", CmpOp::FLt, ConstCompareOp::Lt, 2), + ("fle", CmpOp::FLe, ConstCompareOp::Le, 3), + ("fgt", CmpOp::FGt, ConstCompareOp::Gt, 4), + ("fge", CmpOp::FGe, ConstCompareOp::Ge, 5), +]; + +fn samples(ty: &Type) -> Vec<(FloatBits, Option)> { + let bits: [u64; 14] = match ty { + Type::F16 => [ + 0xfc00, 0xfbff, 0xbc00, 0x8001, 0x8000, 0, 1, 0x3c00, 0x7bff, 0x7c00, 0x7c01, 0x7e55, + 0xfe01, 0xfc01, + ], + Type::F32 => [ + 0xff800000, 0xff7fffff, 0xbf800000, 0x80000001, 0x80000000, 0, 1, 0x3f800000, + 0x7f7fffff, 0x7f800000, 0x7f800001, 0x7fc01234, 0xffc00001, 0xff800001, + ], + Type::F64 => [ + 0xfff0000000000000, + 0xffefffffffffffff, + 0xbff0000000000000, + 0x8000000000000001, + 0x8000000000000000, + 0, + 1, + 0x3ff0000000000000, + 0x7fefffffffffffff, + 0x7ff0000000000000, + 0x7ff0000000000001, + 0x7ff8123456789abc, + 0xfff8000000000001, + 0xfff0000000000001, + ], + _ => unreachable!(), + }; + let ranks = [ + Some(-4), + Some(-3), + Some(-2), + Some(-1), + Some(0), + Some(0), + Some(1), + Some(2), + Some(3), + Some(4), + None, + None, + None, + None, + ]; + bits.into_iter() + .zip(ranks) + .map(|(bits, rank)| { + ( + match ty { + Type::F16 => FloatBits::F16(bits as u16), + Type::F32 => FloatBits::F32(bits as u32), + _ => FloatBits::F64(bits), + }, + rank, + ) + }) + .collect() +} + +fn relation(a: Option, b: Option) -> usize { + match a.zip(b).map(|(a, b)| a.cmp(&b)) { + Some(std::cmp::Ordering::Less) => 0, + Some(std::cmp::Ordering::Equal) => 1, + Some(std::cmp::Ordering::Greater) => 2, + None => 3, + } +} + +fn module(ty: &Type, family: &str, predicate: &str) -> Module { + parse_module(&format!("module {{ format_version 7 semantics_version 1 target \"x86_64-whale-linux\" datalayout {{ ptr=64, endian=little }} declare @f0 \"cmp\": whale ({ty}, {ty}) -> bool, linkage internal fn @f0 \"cmp\"(%v0 \"a\": {ty}, %v1 \"b\": {ty}) -> bool, entry %b0 {{ %b0 \"entry\": %v2: bool = {family} {predicate} {ty} %v0, %v1 ret bool %v2 }} }}")).unwrap() +} + +#[test] +fn all_explicit_predicates_execute_the_independent_shared_ieee_vectors() { + for ty in [Type::F16, Type::F32, Type::F64] { + for (name, predicate, expected) in &PREDICATES { + let module = module(&ty, "fcmp", name); + let text = print_module(&module); + assert_eq!(print_module(&parse_module(&text).unwrap()), text); + for (lhs, arank) in samples(&ty) { + for (rhs, brank) in samples(&ty) { + let expected = expected[relation(arank, brank)]; + assert_eq!( + lhs.compare(rhs, predicate), + Some(expected), + "{ty} {name} {lhs} {rhs}" + ); + let result = interpret( + &module, + FunctionId(0), + &[ConstValue::F(lhs), ConstValue::F(rhs)], + ) + .unwrap(); + assert_eq!( + result.value, + Some(ConstValue::Bool(expected)), + "{ty} {name} {lhs} {rhs}" + ); + assert_eq!(result.steps, 2); + } + } + } + } +} + +#[test] +fn generic_operators_and_constant_evaluation_share_the_explicit_mapping_and_vectors() { + for ty in [Type::F16, Type::F32, Type::F64] { + for (name, op, constant, index) in GENERIC { + assert_eq!(op.float_predicate(), Some(PREDICATES[index].1.clone())); + let module = module(&ty, "cmp", name); + for (lhs, arank) in samples(&ty) { + for (rhs, brank) in samples(&ty) { + let expected = PREDICATES[index].2[relation(arank, brank)]; + let expr = ConstExpr { + ty: Type::Bool, + kind: ConstExprKind::Compare { + op: constant, + left: Box::new(ConstExpr::literal(ty.clone(), ConstValue::F(lhs))), + right: Box::new(ConstExpr::literal(ty.clone(), ConstValue::F(rhs))), + }, + }; + assert_eq!( + expr.evaluate(&|_| None), + Ok(ConstValue::Bool(expected)), + "constant {ty} {name} {lhs} {rhs}" + ); + assert_eq!( + interpret( + &module, + FunctionId(0), + &[ConstValue::F(lhs), ConstValue::F(rhs)] + ) + .unwrap() + .value, + Some(ConstValue::Bool(expected)), + "runtime {ty} {name} {lhs} {rhs}" + ); + let equal = lhs.compare(rhs, &FCmpPred::Oeq).unwrap(); + let unequal = lhs.compare(rhs, &FCmpPred::Une).unwrap(); + assert_eq!(unequal, !equal); + } + } + } + } + assert_eq!(CmpOp::Eq.float_predicate(), None); + assert_eq!(CmpOp::SLt.float_predicate(), None); + assert_eq!(FloatBits::F16(0).compare(FloatBits::F32(0), &FCmpPred::Oeq), None); +} + +#[test] +fn every_binary16_encoding_agrees_with_an_independent_numeric_oracle() { + // f16 -> f64 is exact for finite values. This test-only host oracle is + // independent of production's integer comparison implementation. + let rhs = [ + FloatBits::F16(0), + FloatBits::F16(0x3c00), + FloatBits::F16(0xbc00), + FloatBits::F16(0x7c00), + FloatBits::F16(0xfc00), + ]; + for bits in 0..=u16::MAX { + let lhs = FloatBits::F16(bits); + for rhs in rhs { + let (a, b) = (lhs.to_f64(), rhs.to_f64()); + for (pred, expected) in [ + (FCmpPred::Oeq, a == b), + (FCmpPred::Une, a != b), + (FCmpPred::Olt, a < b), + (FCmpPred::Ole, a <= b), + (FCmpPred::Ogt, a > b), + (FCmpPred::Oge, a >= b), + ] { + assert_eq!(lhs.compare(rhs, &pred), Some(expected)); + } + } + } +} + +#[test] +fn comparisons_keep_unused_o0_instructions_and_prior_trap_order() { + let source="module { format_version 7 semantics_version 1 target \"x86_64-whale-linux\" datalayout { ptr=64, endian=little } declare @f0 \"order\": whale () -> void, linkage internal fn @f0 \"order\"() -> void, entry %b0 { %b0 \"entry\": %v0: f32 = const f32 0x7f800001 %v1: bool = fcmp uno f32 %v0, %v0 %v2: bool = cmp fne f32 %v0, %v0 trap_if bool %v2, reason=\"after comparisons\" trap reason=\"later\" } }"; + let module = parse_module(source).unwrap(); + let printed = print_module(&module); + assert!(printed.contains("fcmp uno")); + assert!(printed.contains("cmp fne")); + assert!( + matches!(interpret(&module,FunctionId(0),&[]),Err(InterpreterError::Trap(InterpreterTrap{site:ExecutionSite{instruction:3,..},reason:TrapReason::Explicit(reason),steps:4})) if reason=="after comparisons") + ); + let prior = + source.replace("%v1: bool = fcmp", "trap reason=\"first\" %b1 \"dead\": %v1: bool = fcmp"); + // The dead block needs its own dominating constants to remain valid O0 IR. + let prior = prior + .replace("%b1 \"dead\":", "%b1 \"dead\": %v3: f32 = const f32 0x7f800001") + .replace("fcmp uno f32 %v0, %v0", "fcmp uno f32 %v3, %v3") + .replace("cmp fne f32 %v0, %v0", "cmp fne f32 %v3, %v3"); + assert!( + matches!(interpret(&parse_module(&prior).unwrap(),FunctionId(0),&[]),Err(InterpreterError::Trap(InterpreterTrap{site:ExecutionSite{instruction:1,..},reason:TrapReason::Explicit(reason),steps:2})) if reason=="first") + ); +} + +#[test] +fn comparing_signaling_nan_values_never_quiets_or_replaces_their_payloads() { + for ty in [Type::F16, Type::F32, Type::F64] { + for (bits, rank) in samples(&ty) { + if rank.is_some() { + continue; + } + let mut module = module(&ty, "fcmp", "uno"); + module.declarations[0].signature.ret = ty.clone(); + module.functions[0].ret_ty = ty.clone(); + module.functions[0].blocks[0].terminator = + Some(Terminator::Ret { ty: ty.clone(), value: Some(ValueId(0)) }); + verify_module(&module).unwrap(); + assert_eq!( + interpret(&module, FunctionId(0), &[ConstValue::F(bits), ConstValue::F(bits)]) + .unwrap() + .value, + Some(ConstValue::F(bits)) + ); + } + } +} diff --git a/tests/float_comparisons_cli.rs b/tests/float_comparisons_cli.rs new file mode 100644 index 0000000..d0f9911 --- /dev/null +++ b/tests/float_comparisons_cli.rs @@ -0,0 +1,24 @@ +use std::{path::PathBuf, process::Command}; + +#[test] +fn documented_float_comparisons_report_boolean_results() { + let input = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("ir/tests/fixtures/float-comparisons-v7.wir"); + for (function, a, b, expected) in [ + ("@f0", "0x7ff0000000000001", "0x3ff0000000000000", "bool true\n"), + ("@f0", "0x3ff0000000000000", "0xfff8123456789abc", "bool true\n"), + ("@f1", "0x7ff0000000000001", "0x3ff0000000000000", "bool false\n"), + ("@f1", "0x3ff0000000000000", "0xfff8123456789abc", "bool false\n"), + ("@f0", "0x7ff0000000000000", "0x7ff0000000000000", "bool false\n"), + ("@f2", "0x8000", "0x0000", "bool true\n"), + ] { + let output = Command::new(env!("CARGO_BIN_EXE_whale")) + .args(["ir", "run"]) + .arg(&input) + .args(["--function", function, "--arg", a, "--arg", b]) + .output() + .unwrap(); + assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); + assert_eq!(output.stdout, expected.as_bytes()); + } +}