diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml index 5301df1..af4ead5 100644 --- a/.github/workflows/quality.yml +++ b/.github/workflows/quality.yml @@ -86,6 +86,44 @@ jobs: if-no-files-found: warn retention-days: 7 + reduced-isa: + needs: asmobj + name: Selected ISA / ${{ matrix.name }} + runs-on: ubuntu-24.04 + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + include: + - { name: none, flags: '' } + - { name: amd64, flags: '--features asm-amd64' } + - { name: aarch64, flags: '--features asm-aarch64' } + - { name: riscv64, flags: '--features asm-riscv64' } + - { name: loongarch64, flags: '--features asm-loongarch64' } + env: + WHALE_ASMOBJ_DIR: ${{ github.workspace }}/.ci-asmobj/x86_64-unknown-linux-gnu + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + - name: Download complete Wave asmobj module + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + name: ${{ needs.asmobj.outputs.artifact_name }} + path: .ci-asmobj + - run: rustup toolchain install stable --profile minimal + - name: Check selected assembler registration and integration + run: python tools/ci.py run --name reduced-isa -- cargo test -p whale --no-default-features ${{ matrix.flags }} --locked + - name: Retain command logs and reproduction evidence + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: reduced-isa-${{ matrix.name }} + path: .ci-artifacts/ + include-hidden-files: true + if-no-files-found: warn + retention-days: 7 + docs: needs: asmobj name: Public crate documentation diff --git a/assembler/src/error.rs b/assembler/src/error.rs index 8caf54c..12db44b 100644 --- a/assembler/src/error.rs +++ b/assembler/src/error.rs @@ -1,3 +1,5 @@ +use diagnostic::EscapedName; + use std::fmt; /// Half-open UTF-8 byte range; line/column are one-based Unicode-scalar coordinates. @@ -58,11 +60,23 @@ impl fmt::Display for AsmError { AsmError::Diagnostic { source_name, span, related, error } => { write!( f, - "{error} at {source_name}: line {}, column {} (bytes {}..{})", - span.line, span.column, span.start, span.end + "{error} at {}: line {}, column {} (bytes {}..{})", + EscapedName(source_name), + span.line, + span.column, + span.start, + span.end )?; if let Some(previous) = related { - write!(f, "; previous declaration at {source_name}: line {}, column {} (bytes {}..{})", previous.line, previous.column, previous.start, previous.end)?; + write!( + f, + "; previous declaration at {}: line {}, column {} (bytes {}..{})", + EscapedName(source_name), + previous.line, + previous.column, + previous.start, + previous.end + )?; } Ok(()) }, @@ -78,3 +92,30 @@ impl std::error::Error for AsmError { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn source_names_are_escaped_in_primary_and_related_locations() { + let span = SourceSpan { start: 0, end: 1, line: 1, column: 2 }; + for control in ['\n', '\r', '\t', '\x1b'] { + let name = format!("경로/{control}file.s"); + let error = AsmError::ParserError("bad".into()).at(&name, span, Some(span)); + let rendered = error.to_string(); + assert!(!rendered.contains(control), "{rendered:?}"); + assert_eq!(rendered.matches(&control.escape_debug().to_string()).count(), 2); + assert!(rendered.contains("line 1, column 2 (bytes 0..1)")); + if let AsmError::Diagnostic { source_name, .. } = error { + assert_eq!(source_name, name); + } else { + panic!("expected located assembler error"); + } + } + assert!(AsmError::ParserError("bad".into()) + .at("경로/파일.s", span, None) + .to_string() + .contains("경로/파일.s")); + } +} diff --git a/backend-api/src/lib.rs b/backend-api/src/lib.rs index cb8daa0..4281e64 100644 --- a/backend-api/src/lib.rs +++ b/backend-api/src/lib.rs @@ -24,7 +24,8 @@ pub enum Support { } pub struct Artifact { - /// Relative portable path, with Windows-compatible components. Paths in one + /// Relative portable path, with components at most 255 UTF-8 bytes and + /// 255 UTF-16 code units. 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. @@ -200,6 +201,8 @@ pub fn compile( fn portable_component(part: &str) -> bool { if part.is_empty() + || part.len() > 255 + || part.encode_utf16().count() > 255 || part == "." || part == ".." || part.ends_with(['.', ' ']) @@ -422,4 +425,19 @@ mod tests { let artifacts = compile_names(&names).unwrap(); assert_eq!(artifacts.iter().map(|a| a.name.as_str()).collect::>(), names); } + + #[test] + fn artifact_components_obey_portable_encoded_length_limits() { + let ascii_255 = "x".repeat(255); + let ascii_256 = "x".repeat(256); + assert!(compile_names(&[&ascii_255]).is_ok()); + let errors = compile_names(&[&ascii_256]).err().unwrap(); + assert_eq!(errors[0].code, "backend.artifact"); + assert!(compile_names(&[&format!("nested/{ascii_255}/file.o")]).is_ok()); + assert!(compile_names(&[&format!("nested/{ascii_256}/file.o")]).is_err()); + assert!(compile_names(&[&"é".repeat(127)]).is_ok()); + assert!(compile_names(&[&"é".repeat(128)]).is_err()); + assert!(compile_names(&[&"🦀".repeat(63)]).is_ok()); + assert!(compile_names(&[&"🦀".repeat(64)]).is_err()); + } } diff --git a/diagnostic/src/lib.rs b/diagnostic/src/lib.rs index c0a68ff..aa248ea 100644 --- a/diagnostic/src/lib.rs +++ b/diagnostic/src/lib.rs @@ -68,9 +68,10 @@ 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); +/// Render a user-controlled name without terminal control characters. +pub struct EscapedName<'a>(pub &'a str); -impl fmt::Display for ContextName<'_> { +impl fmt::Display for EscapedName<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use fmt::Write; for character in self.0.chars() { @@ -90,12 +91,12 @@ impl fmt::Display for Diagnostic { for context in &self.contexts { match context { Context::Source(s) => { - write!(f, " at {}:{}:{}", ContextName(&s.source), s.line, s.column)? + write!(f, " at {}:{}:{}", EscapedName(&s.source), s.line, s.column)? }, Context::Object { name, member } => { - write!(f, " in {}", ContextName(name))?; + write!(f, " in {}", EscapedName(name))?; if let Some(m) = member { - write!(f, "({})", ContextName(m))?; + write!(f, "({})", EscapedName(m))?; } }, Context::Input(i) => write!(f, " input {i}")?, diff --git a/fuzz/support.rs b/fuzz/support.rs index ca10c4e..86749aa 100644 --- a/fuzz/support.rs +++ b/fuzz/support.rs @@ -58,6 +58,9 @@ pub fn check(target: Target, bytes: &[u8]) -> bool { }; match target { Target::Object => unreachable!("binary target handled before UTF-8 conversion"), + #[cfg(not(feature = "asm-amd64"))] + Target::Assembler => false, + #[cfg(feature = "asm-amd64")] Target::Assembler => { if let Ok(tokens) = assembler::tokens::tokenize(source) { let _ = amd64::parser::parse(&tokens); diff --git a/ir/src/float/arithmetic.rs b/ir/src/float/arithmetic.rs index d770e34..acf1202 100644 --- a/ir/src/float/arithmetic.rs +++ b/ir/src/float/arithmetic.rs @@ -151,6 +151,9 @@ pub fn negate(value: FloatBits) -> FloatBits { } pub fn arithmetic(op: &BinOp, lhs: FloatBits, rhs: FloatBits) -> Option { + if !matches!(op, BinOp::FAdd | BinOp::FSub | BinOp::FMul | BinOp::FDiv | BinOp::FRem) { + return None; + } if lhs.width() != rhs.width() { return None; } diff --git a/ir/src/float/conversions.rs b/ir/src/float/conversions.rs index 0b4255f..089d83d 100644 --- a/ir/src/float/conversions.rs +++ b/ir/src/float/conversions.rs @@ -4,23 +4,42 @@ use super::Format; use crate::{CastOp, ConstValue, FloatBits, Type}; -fn format(ty: &Type) -> Format { - Format::of(match ty { +fn format(ty: &Type) -> Option { + Some(Format::of(match ty { Type::F16 => FloatBits::F16(0), Type::F32 => FloatBits::F32(0), Type::F64 => FloatBits::F64(0), - _ => unreachable!("verified float type"), - }) + _ => return None, + })) } /// None is a defined invalid numerical conversion, never a poison value. pub fn convert(op: &CastOp, src: &Type, dst: &Type, value: &ConstValue) -> Option { use crate::interpreter::integer; + if !crate::constant::valid_constant(src, value) { + return None; + } + let src_float = format(src); + let dst_float = format(dst); + let src_integer = integer::shape(src); + let dst_integer = integer::shape(dst); + let valid = match op { + CastOp::FExt => src_float.zip(dst_float).is_some_and(|(s, d)| s.width < d.width), + CastOp::FTrunc => src_float.zip(dst_float).is_some_and(|(s, d)| s.width > d.width), + CastOp::IToF_S => src_integer.is_some_and(|(_, signed)| signed) && dst_float.is_some(), + CastOp::IToF_U => src_integer.is_some_and(|(_, signed)| !signed) && dst_float.is_some(), + CastOp::FToI_S => src_float.is_some() && dst_integer.is_some_and(|(_, signed)| signed), + CastOp::FToI_U => src_float.is_some() && dst_integer.is_some_and(|(_, signed)| !signed), + _ => false, + }; + if !valid { + return None; + } match op { CastOp::FExt | CastOp::FTrunc => { - let ConstValue::F(value) = value else { unreachable!("verified float operand") }; + let ConstValue::F(value) = value else { return None }; let parts = Format::of(*value).unpack(*value); - let f = format(dst); + let f = dst_float?; Some(ConstValue::F(if parts.nan { f.nan() } else if parts.infinity { @@ -30,16 +49,16 @@ pub fn convert(op: &CastOp, src: &Type, dst: &Type, value: &ConstValue) -> Optio })) }, CastOp::IToF_S | CastOp::IToF_U => { - let (bits, signed) = integer::shape(src).unwrap(); + let (bits, signed) = src_integer?; let raw = integer::raw(value, bits); let negative = signed && raw & (1u128 << (bits - 1)) != 0; let magnitude = if negative { 0u128.wrapping_sub(raw) } else { raw }; // Mask after taking two's-complement magnitude for narrow negatives. let magnitude = if bits < 128 { magnitude & ((1u128 << bits) - 1) } else { magnitude }; - Some(ConstValue::F(format(dst).pack(negative, magnitude, 0))) + Some(ConstValue::F(dst_float?.pack(negative, magnitude, 0))) }, CastOp::FToI_S | CastOp::FToI_U => { - let ConstValue::F(value) = value else { unreachable!("verified float operand") }; + let ConstValue::F(value) = value else { return None }; let p = Format::of(*value).unpack(*value); if p.nan || p.infinity { return None; @@ -55,7 +74,7 @@ pub fn convert(op: &CastOp, src: &Type, dst: &Type, value: &ConstValue) -> Optio } else { p.sig.checked_shr((-p.exp) as u32).unwrap_or(0) }; - let (bits, signed) = integer::shape(dst).unwrap(); + let (bits, signed) = dst_integer?; let maximum = if signed { (1u128 << (bits - 1)) - u128::from(!p.negative) } else if bits == 128 { diff --git a/ir/src/lower_ast/error.rs b/ir/src/lower_ast/error.rs index 83e25d0..fabb823 100644 --- a/ir/src/lower_ast/error.rs +++ b/ir/src/lower_ast/error.rs @@ -2,6 +2,8 @@ use crate::{ConstValue, Type}; +use diagnostic::EscapedName; + #[derive(Debug)] pub enum LowerError { Located { annotation: crate::SourceAnnotation, error: Box }, @@ -66,7 +68,7 @@ impl std::fmt::Display for LowerError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if let Self::Located { annotation, error } = self { if let Some(source) = &annotation.source { - write!(f, "{}:{}:{}: ", source.file, source.line, source.column)?; + write!(f, "{}:{}:{}: ", EscapedName(&source.file), source.line, source.column)?; } write!(f, "original @n{}: {error}", annotation.id) } else { diff --git a/ir/src/lower_ast/o0/storage.rs b/ir/src/lower_ast/o0/storage.rs index 05cac69..f345770 100644 --- a/ir/src/lower_ast/o0/storage.rs +++ b/ir/src/lower_ast/o0/storage.rs @@ -41,11 +41,22 @@ pub(super) fn write( fb.charge_lower_type(ty)?; let layout = crate::layout_of(ty, target).map_err(LowerError::Layout)?; if aggregate(ty) { + if ptr == value { + return Ok(()); + } + // A frontend assignment may alias through an address expression. + // Snapshot the RHS before writing the destination; explicit IR memcpy + // keeps its overlap trap. + let temporary = fb.alloca_in_entry(ty.clone(), layout.align); let byte_ptr = Type::ptr_to(Type::U8); let dst = fb.cast(crate::CastOp::Bitcast, Type::ptr_to(ty.clone()), byte_ptr.clone(), ptr); - let src = fb.cast(crate::CastOp::Bitcast, Type::ptr_to(ty.clone()), byte_ptr, value); + let src = + fb.cast(crate::CastOp::Bitcast, Type::ptr_to(ty.clone()), byte_ptr.clone(), value); + let snapshot = + fb.cast(crate::CastOp::Bitcast, Type::ptr_to(ty.clone()), byte_ptr, temporary); let size = fb.const_uint(Type::U64, layout.size.into()); - fb.memcpy(dst, src, size, layout.align); + fb.memcpy(snapshot, src, size, layout.align); + fb.memcpy(dst, snapshot, size, layout.align); } else { fb.store(ty.clone(), value, ptr, layout.align); } diff --git a/ir/src/source.rs b/ir/src/source.rs index 8e1962e..2d4d757 100644 --- a/ir/src/source.rs +++ b/ir/src/source.rs @@ -3,6 +3,8 @@ //! does not infer a source location from SSA values, names or canonical text. use crate::{BlockId, FunctionId, GlobalId, Module}; +use diagnostic::EscapedName; + use std::collections::{HashMap, HashSet}; #[cfg_attr(feature = "socket", derive(serde::Serialize, serde::Deserialize))] @@ -98,7 +100,7 @@ pub struct OriginalLocation { impl std::fmt::Display for OriginalLocation { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if let Some((file, span)) = &self.source { - write!(f, "{file}:{}:{} ", span.line, span.column)?; + write!(f, "{}:{}:{} ", EscapedName(file), span.line, span.column)?; } write!(f, "original @n{}", self.original) } diff --git a/ir/src/verifier.rs b/ir/src/verifier.rs index 6ca8db5..48483b4 100644 --- a/ir/src/verifier.rs +++ b/ir/src/verifier.rs @@ -22,6 +22,7 @@ use std::cell::Cell; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct VerificationStats { pub value_type_lookups: usize, + pub declaration_work: usize, pub dominance_queries: usize, pub analysis_work: usize, } @@ -345,7 +346,7 @@ pub fn verify_module_for_target_with_stats( return Err(VerifyError::DuplicateFunction { name: f.name.clone() }); } } - calls::verify_declarations(m, limits)?; + let declarations = calls::verify_declarations(m, limits)?; for f in &indexed { let mut blocks = HashSet::new(); for block in &f.blocks { @@ -548,13 +549,14 @@ pub fn verify_module_for_target_with_stats( }); } } - calls::verify_instruction(m, f, instruction, limits)?; + calls::verify_instruction(&declarations, f, instruction, limits)?; operands::verify_instruction(f, instruction)?; } } } Ok(VerificationStats { value_type_lookups: indexed.iter().map(|f| f.queries.get()).sum(), + declaration_work: declarations.work(), dominance_queries: analysis.queries.get(), analysis_work: analysis.work.get(), }) diff --git a/ir/src/verifier/calls.rs b/ir/src/verifier/calls.rs index b46a826..8bcc5d8 100644 --- a/ir/src/verifier/calls.rs +++ b/ir/src/verifier/calls.rs @@ -1,13 +1,34 @@ // SPDX-License-Identifier: MPL-2.0 -use crate::{CallError, Callee, Instruction, Module, Type, VerifyError}; +use crate::{CallError, Callee, FunctionDecl, FunctionId, Instruction, Module, Type, VerifyError}; -use std::collections::HashSet; +use std::cell::Cell; + +use std::collections::{HashMap, HashSet}; + +pub(super) struct DeclarationIndex<'a> { + by_id: HashMap, + work: Cell, +} + +impl<'a> DeclarationIndex<'a> { + fn get(&self, id: FunctionId) -> Option<&'a FunctionDecl> { + self.work.set(self.work.get().saturating_add(1)); + self.by_id.get(&id).copied() + } + + pub(super) fn work(&self) -> usize { + self.work.get() + } +} fn error(name: &str, reason: CallError) -> VerifyError { VerifyError::Call { func: name.into(), reason } } -pub(super) fn verify_declarations(m: &Module, limits: crate::IrLimits) -> Result<(), VerifyError> { +pub(super) fn verify_declarations( + m: &Module, + limits: crate::IrLimits, +) -> Result, VerifyError> { for f in &m.functions { for (_, ty) in &f.value_types { validate_pointer_types(ty, limits).map_err(|e| error(&f.name, e))?; @@ -24,6 +45,8 @@ pub(super) fn verify_declarations(m: &Module, limits: crate::IrLimits) -> Result let mut ids = HashSet::new(); let mut names = HashSet::new(); let mut links = HashSet::new(); + let body_ids: HashSet<_> = m.functions.iter().map(|f| f.id).collect(); + let mut by_id = HashMap::new(); for decl in &m.declarations { crate::function::validate_decl_with_limits(decl, limits) .map_err(|e| error(&decl.name, e))?; @@ -35,21 +58,22 @@ pub(super) fn verify_declarations(m: &Module, limits: crate::IrLimits) -> Result return Err(error(&decl.name, CallError::LinkNameCollision(link.clone()))); } } - if decl.linkage == crate::Linkage::Internal && !m.functions.iter().any(|f| f.id == decl.id) - { + if decl.linkage == crate::Linkage::Internal && !body_ids.contains(&decl.id) { return Err(error(&decl.name, CallError::MissingDefinition(decl.id))); } + by_id.insert(decl.id, decl); } + let index = DeclarationIndex { + by_id, + work: Cell::new(m.functions.len().saturating_add(m.declarations.len().saturating_mul(2))), + }; let mut bodies = HashSet::new(); for f in &m.functions { if !bodies.insert(f.id) { return Err(error(&f.name, CallError::DuplicateDefinition(f.id))); } - let decl = m - .declarations - .iter() - .find(|d| d.id == f.id) - .ok_or_else(|| error(&f.name, CallError::UnknownFunction(f.id)))?; + let decl = + index.get(f.id).ok_or_else(|| error(&f.name, CallError::UnknownFunction(f.id)))?; if decl.name != f.name || decl.signature.ret != f.ret_ty || decl.signature.params != f.params.iter().map(|p| p.ty.clone()).collect::>() @@ -57,11 +81,11 @@ pub(super) fn verify_declarations(m: &Module, limits: crate::IrLimits) -> Result return Err(error(&f.name, CallError::DefinitionMismatch(f.id))); } } - Ok(()) + Ok(index) } pub(super) fn verify_instruction( - m: &Module, + declarations: &DeclarationIndex<'_>, f: &super::IndexedFunction<'_>, ins: &Instruction, limits: crate::IrLimits, @@ -72,11 +96,8 @@ pub(super) fn verify_instruction( crate::function::validate_signature_with_limits(signature, limits)? }, Instruction::FunctionAddr { function, signature, .. } => { - let decl = m - .declarations - .iter() - .find(|d| d.id == *function) - .ok_or(CallError::UnknownFunction(*function))?; + let decl = + declarations.get(*function).ok_or(CallError::UnknownFunction(*function))?; if &decl.signature != signature { return Err(CallError::AddressTypeMismatch); } @@ -84,11 +105,7 @@ pub(super) fn verify_instruction( Instruction::Call { dst, ret_ty, convention, callee, args } => { let sig = match callee { Callee::Direct(id) => { - &m.declarations - .iter() - .find(|d| d.id == *id) - .ok_or(CallError::UnknownFunction(*id))? - .signature + &declarations.get(*id).ok_or(CallError::UnknownFunction(*id))?.signature }, Callee::Indirect(value) => match f.value_type(*value) { Some(Type::FnPtr(sig)) => sig, diff --git a/ir/tests/float_arithmetic.rs b/ir/tests/float_arithmetic.rs index 1158542..7414d93 100644 --- a/ir/tests/float_arithmetic.rs +++ b/ir/tests/float_arithmetic.rs @@ -19,6 +19,37 @@ fn op(name: &str) -> BinOp { } } +#[test] +fn non_float_opcodes_never_use_the_nan_fast_path() { + for op in [ + BinOp::Add, + BinOp::Sub, + BinOp::Mul, + BinOp::UDiv, + BinOp::SDiv, + BinOp::URem, + BinOp::SRem, + BinOp::And, + BinOp::Or, + BinOp::Xor, + BinOp::Shl, + BinOp::LShr, + BinOp::AShr, + ] { + for raw in [0x3f800000, 0x7f800000, 0x7fc00000, 0x7f800001] { + assert_eq!( + float::arithmetic::arithmetic(&op, FloatBits::F32(raw), FloatBits::F32(0)), + None, + "{op:?} {raw:x}" + ); + } + assert_eq!( + float::arithmetic::arithmetic(&op, FloatBits::F16(0x7e00), FloatBits::F32(0)), + None + ); + } +} + #[test] fn exact_fraction_vectors_execute_at_every_declared_precision() { let mut modules = std::collections::HashMap::new(); diff --git a/ir/tests/float_conversions.rs b/ir/tests/float_conversions.rs index 4d210f5..3183b5f 100644 --- a/ir/tests/float_conversions.rs +++ b/ir/tests/float_conversions.rs @@ -21,6 +21,32 @@ fn scalar(ty: &str, input: &str) -> ConstValue { } } +#[test] +fn public_float_conversion_rejects_invalid_types_and_payloads() { + let f16 = ConstValue::F(FloatBits::F16(0x3c00)); + let f32 = ConstValue::F(FloatBits::F32(0x3f800000)); + let f64 = ConstValue::F(FloatBits::F64(0x3ff0000000000000)); + for (op, src, dst, value) in [ + (CastOp::FTrunc, Type::F64, Type::F32, f16.clone()), + (CastOp::FTrunc, Type::F64, Type::F32, ConstValue::I(1)), + (CastOp::FExt, Type::F64, Type::F32, f64.clone()), + (CastOp::FTrunc, Type::F16, Type::F32, f16.clone()), + (CastOp::FExt, Type::F32, Type::F32, f32.clone()), + (CastOp::FExt, Type::F16, Type::U32, f16.clone()), + (CastOp::IToF_S, Type::U32, Type::F32, ConstValue::U(1)), + (CastOp::IToF_U, Type::I32, Type::F32, ConstValue::I(1)), + (CastOp::IToF_S, Type::I8, Type::F32, ConstValue::I(128)), + (CastOp::IToF_U, Type::U8, Type::F32, ConstValue::F(FloatBits::F32(0))), + (CastOp::FToI_S, Type::F32, Type::U32, f32.clone()), + (CastOp::FToI_U, Type::F32, Type::I32, f32.clone()), + (CastOp::FToI_S, Type::F32, Type::I32, ConstValue::U(1)), + (CastOp::Bitcast, Type::F32, Type::F32, f32.clone()), + ] { + assert_eq!(float::arithmetic::convert(&op, &src, &dst, &value), None, "{op:?}"); + } + assert_eq!(float::arithmetic::convert(&CastOp::FExt, &Type::F16, &Type::F32, &f16), Some(f32)); +} + #[test] fn independent_conversion_vectors_cover_every_width_pair_and_trap_site() { let mut modules = std::collections::HashMap::new(); diff --git a/ir/tests/frontend_storage.rs b/ir/tests/frontend_storage.rs index 9dcc1a9..f88f689 100644 --- a/ir/tests/frontend_storage.rs +++ b/ir/tests/frontend_storage.rs @@ -75,6 +75,51 @@ fn deref(e: a::Expr) -> a::Expr { a::Expr::Deref(Box::new(e)) } +#[test] +fn aggregate_assignment_snapshots_aliasing_rhs_without_changing_explicit_memcpy() { + let assignments = [ + a::Stmt::Assign { name: "a".into(), value: var("a") }, + a::Stmt::Store { place: var("a"), value: var("a") }, + a::Stmt::Store { place: deref(address(var("a"))), value: var("a") }, + ]; + for assignment in assignments { + let m = lower(vec![function( + "array_alias", + uint(32), + vec![ + decl("a", array(), literal()), + assignment, + a::Stmt::Return(Some(index(var("a"), n(8, 1)))), + ], + )]) + .unwrap(); + assert_eq!(interpret(&m, FunctionId(0), &[]).unwrap().value, Some(ConstValue::U(20))); + } + let init = a::Expr::Struct { + ty: record(), + fields: vec![ + a::FieldInit { name: "byte".into(), value: n(8, 1) }, + a::FieldInit { name: "wide".into(), value: n(64, 42) }, + ], + }; + for assignment in [ + a::Stmt::Assign { name: "s".into(), value: var("s") }, + a::Stmt::Store { place: deref(address(var("s"))), value: var("s") }, + ] { + let m = lower(vec![function( + "struct_alias", + uint(64), + vec![ + decl("s", record(), init.clone()), + assignment, + a::Stmt::Return(Some(field(var("s"), "wide"))), + ], + )]) + .unwrap(); + assert_eq!(interpret(&m, FunctionId(0), &[]).unwrap().value, Some(ConstValue::U(42))); + } +} + #[test] fn padded_structs_construct_copy_read_and_update_without_host_layout() { let init = a::Expr::Struct { diff --git a/ir/tests/source_metadata.rs b/ir/tests/source_metadata.rs index dad0455..f5b9537 100644 --- a/ir/tests/source_metadata.rs +++ b/ir/tests/source_metadata.rs @@ -50,6 +50,23 @@ fn operation_identity_roundtrip_includes_store_unused_constant_and_terminator() assert!(interpret(&decoded, FunctionId(0), &[]).is_ok()); } +#[test] +fn original_location_escapes_controls_without_changing_source_metadata() { + let span = SourceSpan { file: 0, line: 3, column: 4, end_line: 3, end_column: 9 }; + for control in ['\n', '\r', '\t', '\x1b'] { + let name = format!("경로/{control}file.wave"); + let location = OriginalLocation { original: 7, source: Some((name.clone(), span.clone())) }; + let rendered = location.to_string(); + assert!(!rendered.contains(control), "{rendered:?}"); + assert!(rendered.contains(&control.escape_debug().to_string())); + assert!(rendered.contains(":3:4 original @n7")); + assert_eq!(location.source.as_ref().unwrap().0, name); + } + let location = + OriginalLocation { original: 7, source: Some(("경로/파일.wave".into(), span)) }; + assert_eq!(location.to_string(), "경로/파일.wave:3:4 original @n7"); +} + #[test] fn required_operation_splitting_preserves_original_ids() { let mut m = module(); @@ -110,6 +127,30 @@ mod frontend { use ir::lower_ast::{frontend as ast, interchange}; + #[test] + fn located_lower_error_escapes_filename_but_retains_annotation() { + use ir::lower_ast::LowerError; + for control in ['\n', '\r', '\t', '\x1b'] { + let name = format!("경로/{control}file.wave"); + let annotation = SourceAnnotation { + id: 7, + source: Some(FrontendSource { + file: name.clone(), + line: 3, + column: 4, + end_line: 3, + end_column: 9, + }), + }; + let error = LowerError::UnknownVariable("missing".into()).at(&annotation); + let rendered = error.to_string(); + assert!(!rendered.contains(control), "{rendered:?}"); + assert!(rendered.contains(&control.escape_debug().to_string())); + assert!(rendered.contains(":3:4: original @n7")); + assert_eq!(error.annotation(), Some(&annotation)); + } + } + fn annotation(id: u64) -> SourceAnnotation { SourceAnnotation { id, diff --git a/ir/tests/verification_scaling.rs b/ir/tests/verification_scaling.rs index 1e5cc80..ad2b69d 100644 --- a/ir/tests/verification_scaling.rs +++ b/ir/tests/verification_scaling.rs @@ -72,6 +72,59 @@ fn chain(count: u32) -> Module { module(Type::Void, blocks, vec![(ValueId(7), Type::Bool)]) } +fn independent_calls(count: u32) -> Module { + let mut m = Module::new("x86_64-whale-linux", DataLayout::default_64bit_le()); + let signature = FunctionSignature::whale(vec![], Type::Void); + for n in 0..count { + let id = FunctionId(n); + let name = format!("function_{n}"); + m.declarations.push(FunctionDecl { + id, + name: name.clone(), + signature: signature.clone(), + linkage: Linkage::Internal, + link_name: None, + }); + m.functions.push(Function { + id, + name, + params: vec![], + ret_ty: Type::Void, + entry: BlockId(0), + blocks: vec![BasicBlock { + id: BlockId(0), + name: "entry".into(), + instructions: vec![ + Instruction::FunctionAddr { + dst: ValueId(0), + function: FunctionId(0), + signature: signature.clone(), + }, + Instruction::Call { + convention: CallingConvention::Whale, + dst: None, + ret_ty: Type::Void, + callee: Callee::Direct(FunctionId(0)), + args: vec![], + }, + ], + terminator: Some(Terminator::Ret { ty: Type::Void, value: None }), + }], + value_types: vec![(ValueId(0), Type::FnPtr(Box::new(signature.clone())))], + }); + } + m +} + +#[test] +fn declaration_and_direct_call_lookup_work_scales_with_function_count() { + for count in [100, 200, 400, 800] { + let m = independent_calls(count); + let stats = verify_module_with_stats(&m, IrLimits::default()).unwrap(); + assert_eq!(stats.declaration_work, 6 * count as usize, "{stats:?}"); + } +} + #[test] fn lookup_and_dominance_work_grow_linearly_without_reordering_ir() { for constructor in [moves, chain] { diff --git a/reverse/README.md b/reverse/README.md index 8be5c20..1f9c49e 100644 --- a/reverse/README.md +++ b/reverse/README.md @@ -39,3 +39,8 @@ unavailable capability and preserve an existing output file. The retained record/rendering APIs describe supplied typed facts; they do not implement instruction decoding or establish reachability. Source recovery, decompilation and IR lifting remain outside the current scope. + +`Instruction::original_bytes`, `format::instruction_text` and +`format::instruction_json` return `Result` so caller-supplied records with a +length outside 1..=15 fail before presentation. Valid records keep the same +text and JSON output. diff --git a/reverse/src/format.rs b/reverse/src/format.rs index a56fdbe..706eb00 100644 --- a/reverse/src/format.rs +++ b/reverse/src/format.rs @@ -1,5 +1,5 @@ //! Deterministic human and structured rendering of decoded facts. -use crate::{image::Annotation, Instruction, Operand}; +use crate::{image::Annotation, Instruction, Operand, PresentationError}; use serde_json::{json, Value}; @@ -55,9 +55,14 @@ pub fn operand_text(operand: &Operand, inst: &Instruction, base: u64) -> String } } -pub fn instruction_text(inst: &Instruction, base: u64, annotations: &[&Annotation]) -> String { +/// Fallible because public instruction records can contain invalid lengths. +pub fn instruction_text( + inst: &Instruction, + base: u64, + annotations: &[&Annotation], +) -> Result { let bytes = - inst.original_bytes().iter().map(|b| format!("{b:02x}")).collect::>().join(" "); + inst.original_bytes()?.iter().map(|b| format!("{b:02x}")).collect::>().join(" "); let operands = inst .operands .iter() @@ -83,10 +88,16 @@ pub fn instruction_text(inst: &Instruction, base: u64, annotations: &[&Annotatio result .push_str(&format!(" ; {:?} {}{:+} @section+{}", a.kind, a.symbol, a.addend, a.offset)); } - result + Ok(result) } -pub fn instruction_json(inst: &Instruction, base: u64, annotations: &[&Annotation]) -> Value { +/// Fallible because public instruction records can contain invalid lengths. +pub fn instruction_json( + inst: &Instruction, + base: u64, + annotations: &[&Annotation], +) -> Result { + let bytes = inst.original_bytes()?; let operands=inst.operands.iter().map(|o|match o{ Operand::Register(r)=>json!({"kind":"register","name":r.name(),"class":format!("{:?}",r.class),"index":r.index,"width":r.width,"high8":r.high8}), Operand::Immediate(i)=>json!({"kind":"immediate","bits":i.value,"width":i.width,"encoded_width":i.encoded_width,"sign_extended":i.sign_extended}), @@ -96,5 +107,7 @@ pub fn instruction_json(inst: &Instruction, base: u64, annotations: &[&Annotatio let field = |f: Option| { f.map(|f| json!({"offset":f.offset,"width_bytes":f.width,"bits":f.bits})) }; - json!({"offset":inst.offset,"address":base.checked_add(inst.offset as u64),"length":inst.length,"bytes":inst.original_bytes(),"mnemonic":inst.mnemonic(),"operands":operands,"flow":format!("{:?}",inst.flow),"target":if annotations.is_empty(){inst.relative_target(base)}else{None},"encoding":{"prefixes":inst.encoding.prefixes,"rex":inst.encoding.rex,"opcode_offset":inst.encoding.opcode_offset,"opcode_length":inst.encoding.opcode_len,"modrm":inst.encoding.modrm.map(|b|json!({"offset":b.offset,"value":b.value})),"sib":inst.encoding.sib.map(|b|json!({"offset":b.offset,"value":b.value})),"displacement":field(inst.encoding.displacement),"immediate":field(inst.encoding.immediate)},"relocations":annotations.iter().map(|a|json!({"offset":a.offset,"symbol":a.symbol,"addend":a.addend,"kind":format!("{:?}",a.kind),"width_bytes":a.width})).collect::>()}) + Ok( + json!({"offset":inst.offset,"address":base.checked_add(inst.offset as u64),"length":inst.length,"bytes":bytes,"mnemonic":inst.mnemonic(),"operands":operands,"flow":format!("{:?}",inst.flow),"target":if annotations.is_empty(){inst.relative_target(base)}else{None},"encoding":{"prefixes":inst.encoding.prefixes,"rex":inst.encoding.rex,"opcode_offset":inst.encoding.opcode_offset,"opcode_length":inst.encoding.opcode_len,"modrm":inst.encoding.modrm.map(|b|json!({"offset":b.offset,"value":b.value})),"sib":inst.encoding.sib.map(|b|json!({"offset":b.offset,"value":b.value})),"displacement":field(inst.encoding.displacement),"immediate":field(inst.encoding.immediate)},"relocations":annotations.iter().map(|a|json!({"offset":a.offset,"symbol":a.symbol,"addend":a.addend,"kind":format!("{:?}",a.kind),"width_bytes":a.width})).collect::>() }), + ) } diff --git a/reverse/src/image.rs b/reverse/src/image.rs index 613e838..85f6637 100644 --- a/reverse/src/image.rs +++ b/reverse/src/image.rs @@ -181,11 +181,13 @@ impl<'a> Image<'a> { } 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()); + if p.memory_size != 0 { + 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()); + } + mappings.push((p.virtual_address, end)); } - mappings.push((p.virtual_address, end)); if p.flags & 1 != 0 && !bytes.is_empty() { image.regions.push(CodeRegion { id: image.regions.len(), @@ -220,7 +222,7 @@ impl<'a> Image<'a> { return Err("section names require a string table".into()); } let names = view.range(table.offset, table.size).map_err(|e| e.to_string())?; - if names.first() != Some(&0) { + if !valid_string_table(names) { return Err("invalid section-name string table".into()); } Some(names) @@ -230,6 +232,9 @@ impl<'a> Image<'a> { for index in 1..view.header.section_count { charge(&mut work, 1)?; let s = view.section(index).map_err(|e| e.to_string())?; + if s.kind == 0 { + continue; + } if s.name != 0 { let names = section_names.ok_or("section name without string table")?; let tail = @@ -260,7 +265,10 @@ impl<'a> Image<'a> { } if s.entry_size != 24 || s.size % 24 != 0 + || s.size == 0 || s.size / 24 > limits.max_symbols as u64 + || s.info == 0 + || u64::from(s.info) > s.size / 24 || s.link as usize >= view.header.section_count { return Err("invalid executable symbol table".into()); @@ -274,9 +282,19 @@ impl<'a> Image<'a> { return Err("symbol names require a string table".into()); } let names = view.range(strings.offset, strings.size).map_err(|e| e.to_string())?; + if !valid_string_table(names) { + return Err("invalid symbol-name string table".into()); + } + if view.range(s.offset, 24).map_err(|e| e.to_string())?.iter().any(|byte| *byte != 0) { + return Err("executable symbol zero is not null".into()); + } for n in 1..s.size / 24 { charge(&mut work, 1)?; let at = s.offset + n * 24; + let binding = view.range(at + 4, 1).map_err(|e| e.to_string())?[0] >> 4; + if (n < u64::from(s.info)) != (binding == 0) { + return Err("executable local/global symbol order contradicts sh_info".into()); + } let name_offset = view.u32(at).map_err(|e| e.to_string())? as usize; let remaining = limits.max_string_bytes.saturating_sub(string_work); let tail = names.get(name_offset..).ok_or("symbol name offset outside table")?; @@ -387,3 +405,7 @@ fn charge(work: &mut usize, count: usize) -> Result<(), String> { *work = work.checked_sub(count).ok_or("ELF inspection work limit exceeded")?; Ok(()) } + +fn valid_string_table(bytes: &[u8]) -> bool { + bytes.first() == Some(&0) && bytes.last() == Some(&0) +} diff --git a/reverse/src/model.rs b/reverse/src/model.rs index fce204e..487715c 100644 --- a/reverse/src/model.rs +++ b/reverse/src/model.rs @@ -287,8 +287,12 @@ pub struct Instruction { } impl Instruction { - pub fn original_bytes(&self) -> &[u8] { - &self.bytes[..self.length as usize] + /// Caller-supplied records use a checked length; decoders produce 1..=15. + pub fn original_bytes(&self) -> Result<&[u8], PresentationError> { + if !(1..=15).contains(&self.length) { + return Err(PresentationError::InvalidLength(self.length)); + } + Ok(&self.bytes[..self.length as usize]) } pub fn mnemonic(&self) -> String { @@ -311,3 +315,21 @@ impl Instruction { u64::try_from(target).ok() } } + +/// An invalid caller-supplied instruction cannot be rendered as machine code. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PresentationError { + InvalidLength(u8), +} + +impl std::fmt::Display for PresentationError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::InvalidLength(length) => { + write!(f, "invalid instruction length {length}; expected 1..=15 bytes") + }, + } + } +} + +impl std::error::Error for PresentationError {} diff --git a/reverse/tests/images.rs b/reverse/tests/images.rs index a858408..f9a5a3e 100644 --- a/reverse/tests/images.rs +++ b/reverse/tests/images.rs @@ -100,9 +100,9 @@ fn relocatable_code_regions_and_symbolic_call_annotations_preserve_identity() { assert!(image.annotations(0, 5, 1).is_empty()); if reverse::backend_available() { let inst = reverse::decode(image.regions[0].bytes, 0).unwrap(); - let structured = reverse::format::instruction_json(&inst, 0, &a); + let structured = reverse::format::instruction_json(&inst, 0, &a).unwrap(); assert!(structured["target"].is_null()); - let text = reverse::format::instruction_text(&inst, 0, &a); + let text = reverse::format::instruction_text(&inst, 0, &a).unwrap(); assert!(text.contains("reloc(external-4)")); assert!(!text.contains("call 0x5")); } @@ -199,6 +199,113 @@ fn high_half_symbol_file_mapping_uses_checked_relative_offsets() { assert_eq!(image.symbols[0].offset, 0); } +#[test] +fn inactive_executable_sections_ignore_undefined_header_fields() { + let mut bytes = executable(); + bytes.resize(256, 0); + write64(&mut bytes, 40, 128); + bytes[58..60].copy_from_slice(&64u16.to_le_bytes()); + bytes[60..62].copy_from_slice(&2u16.to_le_bytes()); + assert!(Image::elf(&bytes, ObjectReadLimits::default()).is_ok()); + bytes[192..196].copy_from_slice(&u32::MAX.to_le_bytes()); + write64(&mut bytes, 192 + 24, u64::MAX); + write64(&mut bytes, 192 + 48, 3); + assert!(Image::elf(&bytes, ObjectReadLimits::default()).is_ok()); + bytes[128] = 1; + assert!(Image::elf(&bytes, ObjectReadLimits::default()).unwrap_err().contains("section zero")); + + let mut inactive_owner = symbol_executable(1); + inactive_owner[128 + 64 + 4..128 + 64 + 8].copy_from_slice(&0u32.to_le_bytes()); + inactive_owner[128 + 64 + 48..128 + 64 + 56].copy_from_slice(&3u64.to_le_bytes()); + let image = Image::elf(&inactive_owner, ObjectReadLimits::default()).unwrap(); + assert_eq!(image.symbols[0].region, None); +} + +#[test] +fn executable_string_tables_require_nul_boundaries_even_for_unused_bytes() { + let original = symbol_executable(1); + assert!(Image::elf(&original, ObjectReadLimits::default()).is_ok()); + let mut prefix = original.clone(); + prefix[0x1040] = b'X'; + assert!(Image::elf(&prefix, ObjectReadLimits::default()) + .unwrap_err() + .contains("symbol-name string table")); + let mut tail = original.clone(); + tail.push(b'X'); + write64(&mut tail, 128 + 3 * 64 + 32, 4); + assert!(Image::elf(&tail, ObjectReadLimits::default()).is_err()); + *tail.last_mut().unwrap() = 0; + assert!(Image::elf(&tail, ObjectReadLimits::default()).is_ok()); + write64(&mut tail, 128 + 3 * 64 + 32, 0); + assert!(Image::elf(&tail, ObjectReadLimits::default()).is_err()); + + let mut named = original; + named[62..64].copy_from_slice(&3u16.to_le_bytes()); + assert!(Image::elf(&named, ObjectReadLimits::default()).is_ok()); + named[0x1040] = b'X'; + assert!(Image::elf(&named, ObjectReadLimits::default()) + .unwrap_err() + .contains("section-name string table")); +} + +#[test] +fn executable_symtab_checks_null_record_and_local_global_boundary() { + let original = symbol_executable(1); + assert_eq!(Image::elf(&original, ObjectReadLimits::default()).unwrap().symbols.len(), 1); + let mut null = original.clone(); + null[0x1018] = 123; + assert!(Image::elf(&null, ObjectReadLimits::default()).unwrap_err().contains("symbol zero")); + for info in [0, 3, u32::MAX] { + let mut invalid = original.clone(); + invalid[128 + 2 * 64 + 44..128 + 2 * 64 + 48].copy_from_slice(&info.to_le_bytes()); + assert!(Image::elf(&invalid, ObjectReadLimits::default()).is_err(), "info {info}"); + } + let mut wrong_order = original.clone(); + wrong_order[128 + 2 * 64 + 44..128 + 2 * 64 + 48].copy_from_slice(&1u32.to_le_bytes()); + assert!(Image::elf(&wrong_order, ObjectReadLimits::default()) + .unwrap_err() + .contains("local/global")); + for binding in [1u8, 2] { + wrong_order[0x102c] = (binding << 4) | 2; + assert!(Image::elf(&wrong_order, ObjectReadLimits::default()).is_ok()); + } +} + +#[test] +fn empty_load_ranges_do_not_overlap_real_mappings() { + 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(&4u32.to_le_bytes()); + write64(&mut bytes, 128, 0); + write64(&mut bytes, 136, 0x400001); + write64(&mut bytes, 144, 0x400001); + write64(&mut bytes, 152, 0); + write64(&mut bytes, 160, 0); + write64(&mut bytes, 168, 1); + for address in [0x400001, 0x4000b1] { + write64(&mut bytes, 136, address); + let image = Image::elf(&bytes, ObjectReadLimits::default()).unwrap(); + assert_eq!(image.regions.len(), 1); + } + write64(&mut bytes, 136, 0x400001); + write64(&mut bytes, 160, 1); + assert!(Image::elf(&bytes, ObjectReadLimits::default()) + .unwrap_err() + .contains("overlapping PT_LOAD")); + write64(&mut bytes, 160, 0); + write64(&mut bytes, 152, 1); + assert!(Image::elf(&bytes, ObjectReadLimits::default()).is_err()); + write64(&mut bytes, 152, 0); + write64(&mut bytes, 168, 3); + assert!(Image::elf(&bytes, ObjectReadLimits::default()).is_err()); +} + #[test] fn relocatable_inspection_shares_actual_reader_work_instead_of_reserving_half() { let mut object = ObjectFile::new(ObjectFormat::ELF64); diff --git a/reverse/tests/presentation.rs b/reverse/tests/presentation.rs index c4c0c12..2f76c2b 100644 --- a/reverse/tests/presentation.rs +++ b/reverse/tests/presentation.rs @@ -38,11 +38,11 @@ fn symbolic_relocations_suppress_placeholder_call_targets() { kind: object::RelocKind::PLT32, }; let annotations = [&annotation]; - let report = format::instruction_json(&instruction, 0x400000, &annotations); + let report = format::instruction_json(&instruction, 0x400000, &annotations).unwrap(); assert!(report["target"].is_null()); assert_eq!(report["relocations"][0]["symbol"], "external"); assert_eq!(report["encoding"]["immediate"]["width_bytes"], 4); - let text = format::instruction_text(&instruction, 0x400000, &annotations); + let text = format::instruction_text(&instruction, 0x400000, &annotations).unwrap(); assert!(text.contains("call reloc(external-4)"), "{text}"); assert!(!text.contains("call 0x400005")); } @@ -53,11 +53,35 @@ fn checked_target_and_address_rendering_preserves_overflow() { assert_eq!(instruction.relative_target(0x1000), Some(0x1005)); assert_eq!(instruction.relative_target(u64::MAX), None); instruction.offset = 1; - let report = format::instruction_json(&instruction, u64::MAX, &[]); + let report = format::instruction_json(&instruction, u64::MAX, &[]).unwrap(); assert!(report["address"].is_null()); assert!(report["target"].is_null()); - assert!(format::instruction_text(&instruction, u64::MAX, &[]).starts_with("overflow")); - assert_eq!(instruction.original_bytes(), [0xe8, 0, 0, 0, 0]); + assert!(format::instruction_text(&instruction, u64::MAX, &[]).unwrap().starts_with("overflow")); + assert_eq!(instruction.original_bytes().unwrap(), [0xe8, 0, 0, 0, 0]); +} + +#[test] +fn public_instruction_lengths_fail_before_text_or_json_rendering() { + let mut instruction = call(); + for length in [0, 16, 255] { + instruction.length = length; + assert!(matches!( + instruction.original_bytes(), + Err(PresentationError::InvalidLength(actual)) if actual == length + )); + assert!(format::instruction_text(&instruction, 0, &[]) + .unwrap_err() + .to_string() + .contains("expected 1..=15")); + assert!(format::instruction_json(&instruction, 0, &[]).is_err()); + } + for length in [1, 5, 15] { + instruction.length = length; + assert_eq!(instruction.original_bytes().unwrap().len(), usize::from(length)); + assert!(format::instruction_text(&instruction, 0, &[]).is_ok()); + let report = format::instruction_json(&instruction, 0, &[]).unwrap(); + assert_eq!(report["bytes"].as_array().unwrap().len(), usize::from(length)); + } } #[test] diff --git a/src/commands/ir.rs b/src/commands/ir.rs index 9034514..f778f07 100644 --- a/src/commands/ir.rs +++ b/src/commands/ir.rs @@ -53,7 +53,9 @@ pub fn run(args: Vec) { if output.is_some() { fail("duplicate -o option"); } - output = Some(args.next().unwrap_or_else(|| fail("-o requires a path"))); + output = Some(args.next().filter(|value| !value.starts_with('-')).unwrap_or_else( + || fail("-o requires a path; use ./--name for a dash-leading filename"), + )); }, "--function" if command == "run" => { if function.is_some() { diff --git a/src/commands/reverse.rs b/src/commands/reverse.rs index 33e4f0c..7436086 100644 --- a/src/commands/reverse.rs +++ b/src/commands/reverse.rs @@ -1,3 +1,5 @@ +use super::report::println; + use reverse::image::Image; use std::{path::Path, process}; @@ -324,5 +326,5 @@ fn graph(image: &Image<'_>, options: &Options, mode: &str) -> Result [--json] [-o PATH]\n whale disasm --raw --amd64 --base ADDRESS \n whale reverse inspect [--json]\n whale reverse cfg|xrefs [--entry NAME|ADDRESS] [--json]\n\nAMD64 long mode, supported integer/scalar SSE forms only.\n--max-input N input bytes (default 8388608; cap 268435456)\n--max-output N output bytes (default 16777216; cap 268435456)\n--max-instructions N records (listing 100000; CFG 16384; cap 1000000)\n--max-work N CFG shared work (default 67108864; cap 1073741824)\n--max-workspace N CFG bytes (default 134217728; cap 536870912)\nUnknown listing bytes are data records; CFG stops at unknown encodings.\nCFG/xrefs analyze one region from ELF entry, raw base or _start; --entry overrides.\nET_REL without _start requires --entry. Relocations retain symbolic targets.\nExecutable listing starts at its entry in the containing executable file range."); + println!("Usage:\n whale reverse inspect [--json] [-o PATH]\n whale reverse inspect --raw --amd64 --base ADDRESS [--json]\n whale disasm [--json] [-o PATH]\n whale reverse cfg|xrefs [--entry NAME|ADDRESS] [--json]\n\nELF/raw AMD64 inspection is available without a decoder.\nDisassembly, CFG and xrefs are currently unavailable in this build.\n--max-input N input bytes (default 8388608; cap 268435456)\n--max-output N output bytes (default 16777216; cap 268435456)\n--max-instructions N records (listing 100000; CFG 16384; cap 1000000)\n--max-work N CFG shared work (default 67108864; cap 1073741824)\n--max-workspace N CFG bytes (default 134217728; cap 536870912)"); } diff --git a/src/commands/reverse_render.rs b/src/commands/reverse_render.rs index 2c95234..84223ca 100644 --- a/src/commands/reverse_render.rs +++ b/src/commands/reverse_render.rs @@ -246,7 +246,8 @@ impl Serialize for InstructionView<'_, '_> { // Decoded instructions have at most three operands and fifteen bytes. // Their fixed-size facts can use the existing formatter; potentially // large relocation names/counts remain borrowed and stream separately. - let facts = reverse::format::instruction_json(instruction, self.base, &[]); + let facts = reverse::format::instruction_json(instruction, self.base, &[]) + .map_err(serde::ser::Error::custom)?; let facts = facts.as_object().expect("instruction formatter returns a map"); let mut map = serializer.serialize_map(Some(facts.len()))?; for (key, value) in facts { @@ -364,7 +365,9 @@ impl ListingOutput { } else { self.bytes(b"overflow ")?; } - for (index, byte) in instruction.original_bytes().iter().enumerate() { + for (index, byte) in + instruction.original_bytes().map_err(|e| e.to_string())?.iter().enumerate() + { if index != 0 { self.bytes(b" ")?; } @@ -508,16 +511,14 @@ mod tests { let parsed: serde_json::Value = serde_json::from_str(&json).unwrap(); assert_eq!( parsed["records"][0]["instruction"], - reverse::format::instruction_json(&instruction, 0x1000, &annotations) + reverse::format::instruction_json(&instruction, 0x1000, &annotations).unwrap() ); assert_eq!(parsed["records"][1]["byte"], 0x0f); assert_eq!(parsed["records"][1]["code"], false); let text = render_listing(&image, &instruction, false, 10000).unwrap(); - assert!(text.contains(&reverse::format::instruction_text( - &instruction, - 0x1000, - &annotations - ))); + assert!(text.contains( + &reverse::format::instruction_text(&instruction, 0x1000, &annotations).unwrap() + )); for (structured, expected) in [(true, json), (false, text)] { assert_eq!( render_listing(&image, &instruction, structured, expected.len()).unwrap(), diff --git a/tests/asm_validation.rs b/tests/asm_validation.rs index f6869a0..5109684 100644 --- a/tests/asm_validation.rs +++ b/tests/asm_validation.rs @@ -1,3 +1,5 @@ +#![cfg(feature = "asm-amd64")] + use std::{fs, path::PathBuf, process::Command}; struct Scratch(PathBuf); diff --git a/tests/assembler_diagnostics.rs b/tests/assembler_diagnostics.rs index 886a0a1..3e5ec27 100644 --- a/tests/assembler_diagnostics.rs +++ b/tests/assembler_diagnostics.rs @@ -1,3 +1,5 @@ +#![cfg(feature = "asm-amd64")] + use std::{fs, process::Command}; #[test] diff --git a/tests/assembler_sections.rs b/tests/assembler_sections.rs index 0050244..eabefa9 100644 --- a/tests/assembler_sections.rs +++ b/tests/assembler_sections.rs @@ -1,3 +1,5 @@ +#![cfg(feature = "asm-amd64")] + use std::{collections::HashMap, fs, process::Command}; fn u32_at(b: &[u8], n: usize) -> u32 { diff --git a/tests/bss_cli.rs b/tests/bss_cli.rs index ea2b61a..b46109d 100644 --- a/tests/bss_cli.rs +++ b/tests/bss_cli.rs @@ -1,3 +1,5 @@ +#![cfg(feature = "asm-amd64")] + use std::{fs, process::Command}; #[test] diff --git a/tests/cli_arguments.rs b/tests/cli_arguments.rs index 0f66d8d..80cdbe4 100644 --- a/tests/cli_arguments.rs +++ b/tests/cli_arguments.rs @@ -65,6 +65,67 @@ fn repeated_or_conflicting_architecture_options_fail_before_reading_input() { } } +#[test] +fn ir_output_flags_reject_option_shaped_paths_before_publication() { + let directory = tempfile::tempdir().unwrap(); + let input = directory.path().join("input.wir"); + fs::write(&input, include_str!("../ir/tests/fixtures/wave-control-v3.wir")).unwrap(); + let lower_input = directory.path().join("input.json"); + if cfg!(feature = "socket-cli") { + fs::write(&lower_input, include_str!("../ir/tests/fixtures/ast-v2-u128.json")).unwrap(); + } + let output = directory.path().join("output with spaces.wir"); + let mut modes = vec![("print", &input)]; + if cfg!(feature = "socket-cli") { + modes.push(("lower", &lower_input)); + } + for (mode, source) in modes { + fs::write(&output, b"previous output").unwrap(); + for arguments in [vec!["-o"], vec!["-o", "--unexpected"]] { + let result = Command::new(env!("CARGO_BIN_EXE_whale")) + .current_dir(directory.path()) + .args(["ir", mode]) + .arg(source) + .args(arguments) + .output() + .unwrap(); + assert_eq!(result.status.code(), Some(1), "{result:?}"); + assert!(String::from_utf8_lossy(&result.stderr).contains("-o requires a path")); + assert_eq!(fs::read(&output).unwrap(), b"previous output"); + assert!(!directory.path().join("--unexpected").exists()); + } + let duplicate = Command::new(env!("CARGO_BIN_EXE_whale")) + .args(["ir", mode]) + .arg(source) + .arg("-o") + .arg(&output) + .args(["-o", "again.wir"]) + .output() + .unwrap(); + assert!(!duplicate.status.success()); + assert!(String::from_utf8_lossy(&duplicate.stderr).contains("duplicate -o")); + assert_eq!(fs::read(&output).unwrap(), b"previous output"); + let valid = Command::new(env!("CARGO_BIN_EXE_whale")) + .args(["ir", mode]) + .arg(source) + .arg("-o") + .arg(&output) + .output() + .unwrap(); + assert!(valid.status.success(), "{valid:?}"); + assert_ne!(fs::read(&output).unwrap(), b"previous output"); + let dash_name = Command::new(env!("CARGO_BIN_EXE_whale")) + .current_dir(directory.path()) + .args(["ir", mode]) + .arg(source) + .args(["-o", "./--name"]) + .output() + .unwrap(); + assert!(dash_name.status.success(), "{dash_name:?}"); + assert!(directory.path().join("--name").is_file()); + } +} + #[test] fn help_describes_available_commands_and_object_options() { for args in [vec![], vec!["--help"], vec!["-h"]] { diff --git a/tests/cli_io.rs b/tests/cli_io.rs index fdc4beb..c9e8d9b 100644 --- a/tests/cli_io.rs +++ b/tests/cli_io.rs @@ -13,6 +13,7 @@ fn version_forms_use_package_metadata() { } } +#[cfg(feature = "asm-amd64")] #[test] fn artifact_input_budgets_check_boundaries_and_preserve_output() { let directory = tempfile::tempdir().unwrap(); @@ -160,7 +161,7 @@ fn closed_stdout(command: &mut Command) -> std::process::Output { command.stdout(Stdio::from(OwnedFd::from(writer))).output().unwrap() } -#[cfg(unix)] +#[cfg(all(unix, feature = "asm-amd64"))] #[test] fn closed_artifact_stdout_preserves_completed_output_without_panicking() { let directory = tempfile::tempdir().unwrap(); diff --git a/tests/coff_cli.rs b/tests/coff_cli.rs index 20a8128..a932d33 100644 --- a/tests/coff_cli.rs +++ b/tests/coff_cli.rs @@ -8,7 +8,12 @@ fn coff_cli_uses_explicit_machine_and_preserves_output_on_invalid_options() { for (arch, source, machine) in [ ("amd64", "global entry\nentry: ret\n", 0x8664u16), ("aarch64", ".global entry\nentry: ret\n", 0xaa64), - ] { + ] + .into_iter() + .filter(|(arch, _, _)| { + (cfg!(feature = "asm-amd64") && *arch == "amd64") + || (cfg!(feature = "asm-aarch64") && *arch == "aarch64") + }) { fs::write(&input, source).unwrap(); let result = Command::new(env!("CARGO_BIN_EXE_whale")) .args(["asm", "--arch", arch, "--format", "coff"]) diff --git a/tests/fuzz_corpus.rs b/tests/fuzz_corpus.rs index 6e97e11..57afcce 100644 --- a/tests/fuzz_corpus.rs +++ b/tests/fuzz_corpus.rs @@ -4,7 +4,10 @@ mod fuzz; #[test] fn deterministic_seed_and_mutation_smoke_is_bounded() { let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fuzz/corpus"); - let targets = [fuzz::Target::Assembler, fuzz::Target::Ir, fuzz::Target::Object]; + let mut targets = vec![fuzz::Target::Ir, fuzz::Target::Object]; + if cfg!(feature = "asm-amd64") { + targets.push(fuzz::Target::Assembler); + } for target in targets { let seeds = fuzz::seeds(&root, target); let mut rng = fuzz::Rng::new(0x5748414c45); diff --git a/tests/macho_cli.rs b/tests/macho_cli.rs index 4043dc6..b9e7171 100644 --- a/tests/macho_cli.rs +++ b/tests/macho_cli.rs @@ -8,7 +8,12 @@ fn macho_cli_selects_machine_and_preserves_files_on_unsupported_forms() { for (arch, source, cpu) in [ ("amd64", "global _entry\n_entry: ret\n", 0x01000007u32), ("aarch64", ".global _entry\n_entry: ret\n", 0x0100000c), - ] { + ] + .into_iter() + .filter(|(arch, _, _)| { + (cfg!(feature = "asm-amd64") && *arch == "amd64") + || (cfg!(feature = "asm-aarch64") && *arch == "aarch64") + }) { fs::write(&input, source).unwrap(); let r = Command::new(env!("CARGO_BIN_EXE_whale")) .args(["asm", "--arch", arch, "--format", "macho"]) @@ -34,15 +39,17 @@ fn macho_cli_selects_machine_and_preserves_files_on_unsupported_forms() { assert!(!r.status.success()); assert_eq!(fs::read(&output).unwrap(), b"existing artifact"); } - fs::write(&input, ".text\n.global _entry\n.extern _other\n_entry: adr x0,_other\nret\n") - .unwrap(); - let r = Command::new(env!("CARGO_BIN_EXE_whale")) - .args(["asm", "--arch", "aarch64", "--format", "macho"]) - .arg(&input) - .arg("-o") - .arg(&output) - .output() - .unwrap(); - assert!(!r.status.success()); - assert_eq!(fs::read(&output).unwrap(), b"existing artifact"); + if cfg!(feature = "asm-aarch64") { + fs::write(&input, ".text\n.global _entry\n.extern _other\n_entry: adr x0,_other\nret\n") + .unwrap(); + let r = Command::new(env!("CARGO_BIN_EXE_whale")) + .args(["asm", "--arch", "aarch64", "--format", "macho"]) + .arg(&input) + .arg("-o") + .arg(&output) + .output() + .unwrap(); + assert!(!r.status.success()); + assert_eq!(fs::read(&output).unwrap(), b"existing artifact"); + } } diff --git a/tests/multi_isa.rs b/tests/multi_isa.rs index 48fb314..75b31e2 100644 --- a/tests/multi_isa.rs +++ b/tests/multi_isa.rs @@ -10,6 +10,13 @@ fn assemble(arch: &str, source: &str) -> AssemblerOutput { .unwrap_or_else(|e| panic!("{arch}: {source:?}: {e}")) } +fn selected(arch: &str) -> bool { + (cfg!(feature = "asm-aarch64") && matches!(arch, "aarch64" | "arm64")) + || (cfg!(feature = "asm-riscv64") && arch == "riscv64") + || (cfg!(feature = "asm-loongarch64") && arch == "loongarch64") + || (cfg!(feature = "asm-amd64") && arch == "amd64") +} + fn u16_at(bytes: &[u8], offset: usize) -> u16 { u16::from_le_bytes(bytes[offset..offset + 2].try_into().unwrap()) } @@ -48,7 +55,10 @@ fn section<'a>(bytes: &'a [u8], name: &str) -> (usize, &'a [u8]) { #[test] fn forward_backward_labels_and_numeric_branch_limits_are_checked() { - for (arch, branch) in [("aarch64", "b"), ("riscv64", "j"), ("loongarch64", "b")] { + for (arch, branch) in [("aarch64", "b"), ("riscv64", "j"), ("loongarch64", "b")] + .into_iter() + .filter(|(arch, _)| selected(arch)) + { let out = assemble(arch, &format!(".text\n_42: {branch} end\nnop\nend: {branch} _42\nret\n")); let forward = assemble(arch, &format!("{branch} 8")); @@ -69,7 +79,10 @@ fn canonical_numeric_registers_preserve_bytes_and_reject_malformed_names() { ("aarch64", "add", "x", [0x41, 0x00, 0x03, 0x8b]), ("riscv64", "add", "x", [0xb3, 0x00, 0x31, 0x00]), ("loongarch64", "add.d", "$r", [0x41, 0x8c, 0x10, 0x00]), - ] { + ] + .into_iter() + .filter(|(arch, _, _, _)| selected(arch)) + { let source = format!("{mnemonic} {prefix}1,{prefix}2,{prefix}3"); let out = assemble(arch, &source); assert_eq!(out.sections[0].data, expected); @@ -100,6 +113,8 @@ fn cli_rejects_malformed_register_names_without_replacing_output() { let output = directory.path().join("register.o"); for (arch, mnemonic, prefix) in [("aarch64", "add", "x"), ("riscv64", "add", "x"), ("loongarch64", "add.d", "$r")] + .into_iter() + .filter(|(arch, _, _)| selected(arch)) { fs::write(&input, format!("{mnemonic} {prefix}1,{prefix}2,{prefix}3\n")).unwrap(); let valid = Command::new(env!("CARGO_BIN_EXE_whale")) @@ -136,7 +151,10 @@ fn elf_identity_symbol_relocations_and_sparse_bss_are_preserved() { ("aarch64", Machine::AArch64, 183, "bl", 283), ("riscv64", Machine::RiscV64, 243, "jal ra,", 17), ("loongarch64", Machine::LoongArch64, 258, "bl", 66), - ] { + ] + .into_iter() + .filter(|(arch, _, _, _, _)| selected(arch)) + { let source=format!(".text\n.global entry\n.extern external\nentry: {call} external+4\nret\n.data\npayload: .quad entry+8\n.word external-4\n.bss\n.balign 4096\nstorage: .zero 1099511627776\n"); let output = assemble(arch, &source); let target = ObjectTarget::elf64(machine); @@ -183,7 +201,10 @@ fn cross_section_branches_keep_target_specific_relocations() { ("aarch64", "b.eq target+4"), ("riscv64", "beq a0,a1,target+4"), ("loongarch64", "beqz $a0,target+4"), - ] { + ] + .into_iter() + .filter(|(arch, _)| selected(arch)) + { let out = assemble(arch, &format!("{instruction}\n.data\ntarget: .quad 0")); assert_eq!(out.sections[0].relocs.len(), 1); assert_eq!(out.sections[0].relocs[0].addend, 4); @@ -262,7 +283,7 @@ fn invalid_operands_ranges_and_unimplemented_extensions_fail_explicitly() { ], ), ]; - for (arch, inputs) in cases { + for (arch, inputs) in cases.into_iter().filter(|(arch, _)| selected(arch)) { for input in inputs { let err = registry .assemble(arch, "bad.s", input, &AssemblyLimits::default()) @@ -278,7 +299,7 @@ fn invalid_operands_ranges_and_unimplemented_extensions_fail_explicitly() { #[test] fn shared_directives_limits_diagnostics_and_symbol_validation() { let registry = whale::builtins::registry(); - for arch in ["aarch64", "riscv64", "loongarch64"] { + for arch in ["aarch64", "riscv64", "loongarch64"].into_iter().filter(|arch| selected(arch)) { let out=assemble(arch,".text\r\n.global start\r\nstart: nop // Unicode 주석\r\n.data\n.byte -1,255\n.hword 0x1234\n.word -1\n.quad 0xffffffffffffffff\n.bss\n.zero 8192\n"); assert_eq!(out.sections[1].data, [vec![255, 255, 0x34, 0x12], vec![255; 12]].concat()); assert_eq!(out.sections[2].zero_fill, 8192); @@ -342,6 +363,7 @@ fn shared_directives_limits_diagnostics_and_symbol_validation() { } } +#[cfg(feature = "asm-aarch64")] #[test] fn mismatched_relocation_namespaces_and_symbol_sections_never_serialize() { let mut out = assemble("aarch64", ".extern x\nbl x"); @@ -359,7 +381,10 @@ fn cli_assembles_three_isas_and_keeps_existing_output_on_failure() { let directory = tempfile::tempdir().unwrap(); let input = directory.path().join("input.s"); let output = directory.path().join("output.o"); - for (arch, elf) in [("aarch64", 183), ("arm64", 183), ("riscv64", 243), ("loongarch64", 258)] { + for (arch, elf) in [("aarch64", 183), ("arm64", 183), ("riscv64", 243), ("loongarch64", 258)] + .into_iter() + .filter(|(arch, _)| selected(arch)) + { fs::write(&input, ".global entry\nentry: nop\nret\n").unwrap(); let result = Command::new(env!("CARGO_BIN_EXE_whale")) .args(["asm", &format!("--{arch}")]) @@ -405,7 +430,8 @@ fn parser_mutations_and_public_field_guards_never_panic() { bytes[index] = (state >> 24) as u8; } let text = String::from_utf8_lossy(&bytes); - for arch in ["aarch64", "riscv64", "loongarch64"] { + for arch in ["aarch64", "riscv64", "loongarch64"].into_iter().filter(|arch| selected(arch)) + { let _ = registry.assemble( arch, "mutation.s", @@ -422,42 +448,49 @@ fn parser_mutations_and_public_field_guards_never_panic() { assert!(assembler::fixed::displacement(0, 26, 0).is_err()); assert_eq!(assembler::fixed::signed("-1", 32).unwrap(), u32::MAX); assert_eq!(assembler::fixed::unsigned("0xffffffff", 32).unwrap(), u32::MAX); - assert_eq!( - assemble("aarch64", "add x0,x1,# 1").sections[0].data, - assemble("aarch64", "add x0,x1,#1").sections[0].data - ); + if selected("aarch64") { + assert_eq!( + assemble("aarch64", "add x0,x1,# 1").sections[0].data, + assemble("aarch64", "add x0,x1,#1").sections[0].data + ); + } } #[test] fn fixed_source_metadata_and_input_ceiling_precede_allocation() { let registry = whale::builtins::registry(); - let huge = " ".repeat(8 * 1024 * 1024 + 1); - assert!(registry - .assemble("aarch64", "large.s", &huge, &AssemblyLimits::default()) - .err() - .unwrap() - .to_string() - .contains("input exceeds")); - let sections: String = (0..4096).map(|i| format!(".section s{i}\n")).collect(); - assert!(registry - .assemble("riscv64", "many.s", §ions, &AssemblyLimits::default()) - .err() - .unwrap() - .to_string() - .contains("section count")); + if selected("aarch64") { + let huge = " ".repeat(8 * 1024 * 1024 + 1); + assert!(registry + .assemble("aarch64", "large.s", &huge, &AssemblyLimits::default()) + .err() + .unwrap() + .to_string() + .contains("input exceeds")); + } + if selected("riscv64") { + let sections: String = (0..4096).map(|i| format!(".section s{i}\n")).collect(); + assert!(registry + .assemble("riscv64", "many.s", §ions, &AssemblyLimits::default()) + .err() + .unwrap() + .to_string() + .contains("section count")); + } } #[test] fn registry_driven_cli_selection_checks_identity_before_reading_input() { let registry = whale::builtins::registry(); - assert_eq!( - registry.assembler_ids().collect::>(), - ["aarch64", "amd64", "loongarch64", "riscv64"] - ); + let expected = ["aarch64", "amd64", "loongarch64", "riscv64"] + .into_iter() + .filter(|arch| selected(arch)) + .collect::>(); + assert_eq!(registry.assembler_ids().collect::>(), expected); let directory = tempfile::tempdir().unwrap(); let input = directory.path().join("source.s"); let output = directory.path().join("out.o"); - for arch in ["aarch64", "riscv64", "loongarch64"] { + for arch in ["aarch64", "riscv64", "loongarch64"].into_iter().filter(|arch| selected(arch)) { fs::write(&input, "nop\nret").unwrap(); let result = Command::new(env!("CARGO_BIN_EXE_whale")) .args(["asm", "--arch", arch]) @@ -468,6 +501,7 @@ fn registry_driven_cli_selection_checks_identity_before_reading_input() { .unwrap(); assert!(result.status.success(), "{}", String::from_utf8_lossy(&result.stderr)); } + fs::write(&input, "nop\nret").unwrap(); fs::remove_file(&input).unwrap(); fs::write(&output, b"previous").unwrap(); let result = Command::new(env!("CARGO_BIN_EXE_whale")) @@ -480,6 +514,18 @@ fn registry_driven_cli_selection_checks_identity_before_reading_input() { assert!(!result.status.success()); assert!(String::from_utf8_lossy(&result.stderr).contains("unregistered assembler")); assert_eq!(fs::read(&output).unwrap(), b"previous"); + for arch in ["aarch64", "riscv64", "loongarch64"].into_iter().filter(|arch| !selected(arch)) { + let result = Command::new(env!("CARGO_BIN_EXE_whale")) + .args(["asm", "--arch", arch]) + .arg(&input) + .arg("-o") + .arg(&output) + .output() + .unwrap(); + assert!(!result.status.success()); + assert!(String::from_utf8_lossy(&result.stderr).contains("unregistered assembler")); + assert_eq!(fs::read(&output).unwrap(), b"previous"); + } for args in [ vec!["asm", "--arch"], vec!["asm", "--arch", "riscv64", "--amd64"], diff --git a/tests/output_publication.rs b/tests/output_publication.rs index b899be8..82d020f 100644 --- a/tests/output_publication.rs +++ b/tests/output_publication.rs @@ -18,7 +18,9 @@ fn run(mode: &str, input: &Path, output: &Path) -> std::process::Output { fn cases() -> Vec<(&'static str, &'static [u8])> { #[allow(unused_mut)] - let mut cases: Vec<(&str, &[u8])> = vec![("asm", b"section .text\nret\n"), ("object", b"\xc3")]; + let mut cases: Vec<(&str, &[u8])> = vec![("object", b"\xc3")]; + #[cfg(feature = "asm-amd64")] + cases.push(("asm", b"section .text\nret\n")); #[cfg(feature = "socket-cli")] cases.push(("ir", br#"{"format_version":2,"semantics_version":1,"features":[],"program":{"declarations":[],"globals":[],"functions":[]}}"#)); cases diff --git a/tests/relocation_intent.rs b/tests/relocation_intent.rs index 1f21e8b..d31d2d6 100644 --- a/tests/relocation_intent.rs +++ b/tests/relocation_intent.rs @@ -1,3 +1,5 @@ +#![cfg(feature = "asm-amd64")] + use std::{fs, process::Command}; fn u32_at(bytes: &[u8], offset: usize) -> u32 { diff --git a/tests/reverse_cli.rs b/tests/reverse_cli.rs index 87dcc52..25ea267 100644 --- a/tests/reverse_cli.rs +++ b/tests/reverse_cli.rs @@ -4,6 +4,35 @@ fn whale() -> Command { Command::new(env!("CARGO_BIN_EXE_whale")) } +#[test] +fn help_reports_the_actual_reverse_capability() { + assert!(!reverse::backend_available()); + for args in [vec!["disasm", "--help"], vec!["reverse", "--help"]] { + let result = whale().args(args).output().unwrap(); + assert!(result.status.success()); + let help = String::from_utf8(result.stdout).unwrap(); + assert!(help.contains("whale reverse inspect")); + assert!(help.contains("ELF/raw AMD64 inspection is available")); + assert!(help.contains("Disassembly, CFG and xrefs are currently unavailable")); + assert!(!help.contains("Unknown listing bytes are data records")); + } +} + +#[cfg(unix)] +#[test] +fn closed_reverse_help_stdout_exits_without_panicking() { + use std::{os::fd::OwnedFd, os::unix::net::UnixStream, process::Stdio}; + for args in [vec!["disasm", "--help"], vec!["reverse", "--help"]] { + let (reader, writer) = UnixStream::pair().unwrap(); + drop(reader); + let result = + whale().args(args).stdout(Stdio::from(OwnedFd::from(writer))).output().unwrap(); + assert_eq!(result.status.code(), Some(0), "{result:?}"); + assert!(!String::from_utf8_lossy(&result.stderr).contains("panicked")); + } + assert!(whale().args(["reverse", "--help"]).output().unwrap().status.success()); +} + fn object() -> Vec { use object::*; let mut o = ObjectFile::new(ObjectFormat::ELF64); diff --git a/tests/static_link_cli.rs b/tests/static_link_cli.rs index 2891502..0fd7f89 100644 --- a/tests/static_link_cli.rs +++ b/tests/static_link_cli.rs @@ -1,3 +1,5 @@ +#![cfg(feature = "asm-amd64")] + use std::{fs, path::Path, process::Command}; fn whale() -> Command { diff --git a/tests/symbol_metadata.rs b/tests/symbol_metadata.rs index f03b567..d483188 100644 --- a/tests/symbol_metadata.rs +++ b/tests/symbol_metadata.rs @@ -1,3 +1,5 @@ +#![cfg(feature = "asm-amd64")] + #[path = "../object/tests/common/mod.rs"] mod elf; diff --git a/tools/benchmark.py b/tools/benchmark.py index 2291e4b..3d309ce 100644 --- a/tools/benchmark.py +++ b/tools/benchmark.py @@ -46,6 +46,18 @@ def validate_record(record, phase, count): return record +def measurement_index(report, label): + measurements = {} + for entry in report["measurements"]: + name = entry["name"] + if type(name) is not str or not name: + raise ValueError(f"{label} has an invalid measurement name") + if name in measurements: + raise ValueError(f"{label} has a duplicate measurement: {name}") + measurements[name] = entry + return measurements + + def compare_reports(previous, current): # Timing comparisons need identical workloads/build mode/toolchain/host. # Different revisions and executable hashes are intentional, other changes @@ -58,8 +70,8 @@ def compare_reports(previous, current): after_inputs = [{key: item[key] for key in workload_keys} for item in current.get("workloads", [])] if before_inputs != after_inputs: raise ValueError("comparison requires identical input and expected artifact hashes") - old = {entry["name"]: entry for entry in previous["measurements"]} - new = {entry["name"]: entry for entry in current["measurements"]} + old = measurement_index(previous, "baseline") + new = measurement_index(current, "current report") if old.keys() != new.keys(): raise ValueError("comparison requires the same phases") comparison = {} diff --git a/tools/build_asmobj.py b/tools/build_asmobj.py index 8d1c725..93cdf13 100644 --- a/tools/build_asmobj.py +++ b/tools/build_asmobj.py @@ -77,8 +77,28 @@ def main(): 'bootstrap_provenance': str(bootstrap.provenance)}, indent=2) + '\n') fingerprint = temporary / 'asmobj.meta' fingerprint.write_text(metadata(source, archive.read_bytes(), args.target)) - for path in (archive, provenance, fingerprint): - os.replace(path, output / path.name) + staged = (archive, provenance, fingerprint) + previous = {} + for path in staged: + destination = output / path.name + if destination.exists(): + backup = temporary / (path.name + '.previous') + os.link(destination, backup) + previous[destination] = backup + published = [] + try: + for path in staged: + destination = output / path.name + os.replace(path, destination) + published.append(destination) + except OSError: + for destination in reversed(published): + backup = previous.get(destination) + if backup is None: + destination.unlink() + else: + os.replace(backup, destination) + raise print(f'WHALE_ASMOBJ_DIR={output}') if __name__ == '__main__': diff --git a/tools/check_module_layers.py b/tools/check_module_layers.py index 103cd14..166a7a0 100644 --- a/tools/check_module_layers.py +++ b/tools/check_module_layers.py @@ -26,7 +26,7 @@ def production_dependencies(manifest): for section in ("dependencies", "build-dependencies"): - yield from manifest.get(section, {}).values() + yield from manifest.get(section, {}).items() for conditional in manifest.get("target", {}).values(): yield from production_dependencies(conditional) @@ -34,6 +34,7 @@ def production_dependencies(manifest): def audit(root=ROOT): root = Path(root).resolve() workspace = tomllib.loads((root / "Cargo.toml").read_text()) + inherited = workspace.get("workspace", {}).get("dependencies", {}) members = set(workspace["workspace"]["members"]) | {"."} packages = {} for member in sorted(members): @@ -47,11 +48,20 @@ def audit(root=ROOT): edges = {} for name, (location, manifest) in sorted(packages.items()): dependencies = set() - for dep in production_dependencies(manifest): + for alias, dep in production_dependencies(manifest): + base = location + if isinstance(dep, dict) and dep.get("workspace") is True: + if alias not in inherited: + raise ValueError(f"{name}: missing workspace dependency {alias}") + dep = inherited[alias] + base = root if isinstance(dep, dict) and "path" in dep: - path = (location / dep["path"]).resolve() + path = (base / dep["path"]).resolve() if path not in names: raise ValueError(f"{name}: unclassified local dependency {path}") + expected = dep.get("package", alias) + if names[path] != expected: + raise ValueError(f"{name}: dependency {alias} names {expected}, but {path} is {names[path]}") dependencies.add(names[path]) edges[name] = sorted(dependencies) if name in CORE: diff --git a/tools/format-rust.py b/tools/format-rust.py index a5f6e43..e71b5d4 100644 --- a/tools/format-rust.py +++ b/tools/format-rust.py @@ -130,6 +130,15 @@ def strip_lexical_content(line, state): continue if line[i] == "'": + # A Rust label or lifetime starts with an identifier but has no + # closing apostrophe. A later quote can belong to a raw string on + # the same line, so do not use it as this token's terminator. + lifetime = re.match(r"'[A-Za-z_]\w*", line[i:]) + if lifetime and not line.startswith("'", i + len(lifetime.group(0))): + result.append("'") + i += 1 + continue + closing_quote = line.find("'", i + 1) is_char_literal = ( closing_quote != -1 diff --git a/tools/release.py b/tools/release.py index 8417098..11ceec2 100644 --- a/tools/release.py +++ b/tools/release.py @@ -69,10 +69,13 @@ def validate_machine(data, target): def limited_read(path, limit): with path.open("rb") as stream: - data = stream.read(limit + 1) - if len(data) > limit: - raise ValueError(f"file exceeds byte budget: {path}") - return data + data = bytearray() + while len(data) <= limit: + chunk = stream.read(min(65536, limit + 1 - len(data))) + if not chunk: + return bytes(data) + data.extend(chunk) + raise ValueError(f"file exceeds byte budget: {path}") def publish_bytes(path, data): @@ -147,6 +150,43 @@ def package(binary, output, version, target, source, socket=False, root=ROOT): return destination +def preflight_ustar(raw): + """Reject unsupported tar metadata before tarfile allocates its payload.""" + total = 0 + members = 0 + try: + with gzip.GzipFile(fileobj=io.BytesIO(raw)) as stream: + while True: + header = stream.read(512) + if len(header) != 512: + raise ValueError("truncated release tar header") + total += len(header) + if header == bytes(512): + return + if header[257:263] != b"ustar\0" or header[156:157] not in (b"0", b"\0"): + raise ValueError("release tar requires regular USTAR members") + members += 1 + if members > 4: + raise ValueError("release tar has too many members") + field = header[124:136].strip(b"\0 ") + try: + size = int(field, 8) + except ValueError as error: + raise ValueError("invalid release tar member size") from error + padded = (size + 511) // 512 * 512 + if total + padded > MAX_ARCHIVE: + raise ValueError("release tar exceeds byte budget") + remaining = padded + while remaining: + chunk = stream.read(min(65536, remaining)) + if not chunk: + raise ValueError("truncated release tar member") + remaining -= len(chunk) + total += len(chunk) + except (EOFError, OSError) as error: + raise ValueError("invalid compressed release tar") from error + + def unpack(archive, directory, version, target, source): stem = identity(version, target, source) expected = {f"{stem}/{name}" for name in (binary_name(target), "LICENSE", "README.md", "manifest.json")} @@ -172,6 +212,7 @@ def keep(name, size, mode, stream): with reader.open(info) as stream: keep(info.filename, info.file_size, info.external_attr >> 16, stream) else: + preflight_ustar(raw) with tarfile.open(fileobj=io.BytesIO(raw), mode="r:gz") as reader: for info in reader: if len(entries) >= 4 or not info.isfile(): @@ -182,8 +223,12 @@ def keep(name, size, mode, stream): raise ValueError("incomplete release archive") manifest = json.loads(entries[f"{stem}/manifest.json"][0]) required = {"format_version", "version", "target", "source_commit", "socket_cli", "binary", "binary_sha256"} - if (set(manifest) != required or manifest["format_version"] != 1 - or type(manifest["socket_cli"]) is not bool or manifest["version"] != version + if (type(manifest) is not dict or set(manifest) != required + or type(manifest["format_version"]) is not int or manifest["format_version"] != 1 + or type(manifest["socket_cli"]) is not bool + or any(type(manifest[key]) is not str for key in + ("version", "target", "source_commit", "binary", "binary_sha256")) + or manifest["version"] != version or manifest["target"] != target or manifest["source_commit"] != source or manifest["binary"] != binary_name(target)): raise ValueError("archive manifest identity mismatch") diff --git a/tools/test_benchmark.py b/tools/test_benchmark.py index 07d5406..ddf448c 100644 --- a/tools/test_benchmark.py +++ b/tools/test_benchmark.py @@ -83,6 +83,28 @@ def test_comparisons_reject_changed_environments_workloads_and_results(self): broken["workloads"][0]["sha256"]["input.asm"] = "b" with self.assertRaises(ValueError): benchmark.compare_reports(base, broken) + + def test_comparison_rejects_duplicate_measurements_in_either_report(self): + entry = {"name": "small/asm-encode", "fingerprint": benchmark.fingerprint(record()), + "median": {"phase_seconds": 2.0, "peak_rss_bytes": 1024}} + base = {"format_version": 1, "generator": "v1", "profile": "release", "rustc": "rustc", "host": {"cpu": "CPU"}, + "build_environment": {"CARGO_INCREMENTAL": "0"}, "warmups": 1, "runs": 3, + "counts": [64, 32768], "measurements": [entry], "workloads": []} + current = copy.deepcopy(base) + self.assertIn("small/asm-encode", benchmark.compare_reports(base, current)) + for side in ("baseline", "current"): + for position in (0, 1): + for same_fingerprint in (True, False): + with self.subTest(side=side, position=position, same=same_fingerprint): + before = copy.deepcopy(base) + after = copy.deepcopy(current) + target = before if side == "baseline" else after + duplicate = copy.deepcopy(entry) + if not same_fingerprint: + duplicate["fingerprint"]["result_digest"] = "wrong" + target["measurements"].insert(position, duplicate) + with self.assertRaisesRegex(ValueError, "duplicate measurement"): + benchmark.compare_reports(before, after) broken = copy.deepcopy(after) broken["measurements"][0]["fingerprint"]["output_bytes"] += 1 with self.assertRaises(ValueError): diff --git a/tools/test_build_asmobj.py b/tools/test_build_asmobj.py index 1fbaf4c..3414093 100644 --- a/tools/test_build_asmobj.py +++ b/tools/test_build_asmobj.py @@ -42,6 +42,21 @@ def publication(self, *, failure=None, existing=True, target=NATIVE, allow_netwo for name, data in original.items(): (output / name).write_bytes(data) calls = [] + publication_names = { + "publish-archive": archive_name, + "publish-provenance": "provenance.json", + "publish-meta": "asmobj.meta", + } + real_replace = os.replace + injected = False + + def replace(source_path, destination): + nonlocal injected + if (not injected and failure in publication_names + and Path(destination) == output / publication_names[failure]): + injected = True + raise OSError("injected publication failure") + return real_replace(source_path, destination) def fake_bootstrap(*args, **kwargs): self.assertEqual(args, (source, output / "bootstrap-cache")) @@ -90,10 +105,12 @@ def fake_run(command, **kwargs): with patch.object(sys, "argv", arguments), \ patch.object(helper, "ensure_bootstrap", side_effect=fake_bootstrap), \ patch.object(helper, "run", side_effect=fake_run), \ + patch.object(helper.os, "replace", side_effect=replace), \ patch.dict(os.environ, {"AR": "asmobj-test-ar"}), \ contextlib.redirect_stdout(io.StringIO()): if failure: - with self.assertRaises(subprocess.CalledProcessError): + expected = OSError if failure in publication_names else subprocess.CalledProcessError + with self.assertRaises(expected): helper.main() else: helper.main() @@ -138,6 +155,16 @@ def test_failed_first_build_never_publishes_partial_artifacts(self): with self.subTest(failure=failure): self.publication(failure=failure, existing=False) + def test_each_publication_failure_rolls_back_last_good_set(self): + for failure in ("publish-archive", "publish-provenance", "publish-meta"): + with self.subTest(failure=failure): + self.publication(failure=failure) + + def test_each_failed_first_publication_leaves_no_artifact_set(self): + for failure in ("publish-archive", "publish-provenance", "publish-meta"): + with self.subTest(failure=failure): + self.publication(failure=failure, existing=False) + def test_cross_object_targets_keep_distinct_metadata_and_archive_names(self): for target in ("riscv64gc-unknown-linux-gnu", "aarch64-pc-windows-msvc", "aarch64-apple-darwin"): with self.subTest(target=target): diff --git a/tools/test_check_module_layers.py b/tools/test_check_module_layers.py index 2784fcb..452b3f2 100644 --- a/tools/test_check_module_layers.py +++ b/tools/test_check_module_layers.py @@ -23,7 +23,8 @@ def test_optional_and_target_conditional_dependencies_are_not_hidden(self): "target": {"cfg(windows)": {"dependencies": {"d": {"path": "d"}}}}, } self.assertEqual(list(layers.production_dependencies(manifest)), - [{"path": "a", "optional": True}, {"path": "b"}, {"path": "d"}]) + [("a", {"path": "a", "optional": True}), ("b", {"path": "b"}), + ("d", {"path": "d"})]) def test_wrong_layer_fails_even_for_an_existing_dependency(self): rules = copy.deepcopy(layers.CORE) @@ -49,6 +50,42 @@ def test_concrete_isa_dependency_into_ir_is_rejected(self): with self.assertRaisesRegex(ValueError, "ir.*forbidden.*amd64"): layers.audit(root) + def test_inherited_aliases_resolve_from_workspace_for_all_production_kinds(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + workspace = tomllib.loads((layers.ROOT / "Cargo.toml").read_text())["workspace"] + for member in [".", *workspace["members"]]: + source = layers.ROOT / member / "Cargo.toml" + destination = root / source.relative_to(layers.ROOT) + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, destination) + with (root / "Cargo.toml").open("a") as stream: + stream.write('\n[workspace.dependencies]\n' + 'forbidden = { package = "amd64", path = "assembler/amd64" }\n') + ir_manifest = root / "ir/Cargo.toml" + for declaration in [ + '\n[dependencies]\nforbidden = { workspace = true, optional = true }\n', + '\n[build-dependencies]\nforbidden.workspace = true\n', + "\n[target.'cfg(windows)'.dependencies]\nforbidden.workspace = true\n", + '\n[dev-dependencies]\nforbidden.workspace = true\n', + ]: + original = ir_manifest.read_text() + # Existing tables may already be declared; append only the key when so. + table, entry = declaration.strip().split("\n", 1) + if table in original: + changed = original.replace(table, table + "\n" + entry, 1) + else: + changed = original + declaration + ir_manifest.write_text(changed) + try: + if table == "[dev-dependencies]": + self.assertNotIn("amd64", layers.audit(root)["production_dependencies"]["ir"]) + else: + with self.assertRaisesRegex(ValueError, "ir.*forbidden.*amd64"): + layers.audit(root) + finally: + ir_manifest.write_text(original) + if __name__ == "__main__": unittest.main() diff --git a/tools/test_format_rust.py b/tools/test_format_rust.py index 684d701..3ae4099 100644 --- a/tools/test_format_rust.py +++ b/tools/test_format_rust.py @@ -49,6 +49,18 @@ def test_ignores_braces_in_raw_strings(self): 'fn first() { let text = r##"{{{"##; }\n\nfn second() {}\n', ) + def test_label_before_multiline_raw_string_preserves_literal_bytes(self): + source = "fn main(){'l:loop{print!(\"{}\",r\"'\nfn first() {}\nfn second() {}\n'\");break 'l;}}\n" + self.assertEqual(FORMAT_RUST.add_item_spacing(source), source) + self.assertEqual(FORMAT_RUST.add_item_spacing(FORMAT_RUST.add_item_spacing(source)), source) + + def test_char_and_lifetime_before_raw_string_keep_item_spacing(self): + source = "fn first<'a>(value: &'a str) { let c = 'x'; let s = r\"text\"; }\nfn second() {}\n" + self.assertEqual( + FORMAT_RUST.add_item_spacing(source), + "fn first<'a>(value: &'a str) { let c = 'x'; let s = r\"text\"; }\n\nfn second() {}\n", + ) + def test_spaces_between_wave_items(self): source = "struct State {}\nfun first() {}\nexport(c) fun second() {}\n" @@ -86,4 +98,4 @@ def test_does_not_treat_rust_variables_named_fun_as_items(self): if __name__ == "__main__": - unittest.main() \ No newline at end of file + unittest.main() diff --git a/tools/test_release.py b/tools/test_release.py index 7a49485..1a13bce 100644 --- a/tools/test_release.py +++ b/tools/test_release.py @@ -1,5 +1,6 @@ """Release identity, reproducibility, archive integrity and exact-set regressions.""" +import gzip import io import json from pathlib import Path @@ -10,6 +11,7 @@ import unittest from unittest.mock import patch import zipfile +import sys import release @@ -180,6 +182,58 @@ def test_archive_rejects_tampering_links_paths_duplicates_and_missing_files(self with self.assertRaises(ValueError): release.validate(broken, VERSION, target, SOURCE, execute=False) + def test_manifest_requires_an_object_and_exact_field_types(self): + target = "x86_64-pc-windows-msvc" + original = self.package(target, "manifest-control") + self.assertEqual(release.validate(original, VERSION, target, SOURCE, execute=False)["format_version"], 1) + with zipfile.ZipFile(original) as reader: + entries = [(info, reader.read(info)) for info in reader.infolist()] + for mutation in (None, True, {"format_version": True}, {"format_version": 1.0}): + with self.subTest(mutation=mutation): + broken = self.root / "bad-manifest.zip" + with zipfile.ZipFile(broken, "w") as writer: + for info, data in entries: + if info.filename.endswith("/manifest.json"): + manifest = json.loads(data) + data = json.dumps(mutation if not isinstance(mutation, dict) + else {**manifest, **mutation}).encode() + writer.writestr(info, data) + with self.assertRaisesRegex(ValueError, "manifest identity"): + release.validate(broken, VERSION, target, SOURCE, execute=False) + + def test_pax_metadata_is_rejected_before_large_allocation(self): + target = "x86_64-unknown-linux-gnu" + archive = self.root / "pax.tar.gz" + size = 384 * 1024 * 1024 + header = tarfile.TarInfo("pax_global_header") + header.type = tarfile.XGLTYPE + header.size = size + prefix = f"{size} comment=".encode() + remaining = size - len(prefix) - 1 + chunk = b"A" * 65536 + with gzip.open(archive, "wb", compresslevel=1) as stream: + stream.write(header.tobuf(format=tarfile.USTAR_FORMAT)) + stream.write(prefix) + while remaining: + count = min(remaining, len(chunk)) + stream.write(chunk[:count]) + remaining -= count + stream.write(b"\n") + stream.write(bytes((-size) % 512 + 1024)) + self.assertLess(archive.stat().st_size, size // 100) + with self.assertRaisesRegex(ValueError, "USTAR"): + release.validate(archive, VERSION, target, SOURCE, execute=False) + if sys.platform.startswith("linux"): + code = ("import resource,sys; from pathlib import Path; " + "sys.path.insert(0,sys.argv[1]); import release; " + "resource.setrlimit(resource.RLIMIT_AS,(512*1024*1024,)*2); " + "release.validate(Path(sys.argv[2]),'0.1.0'," + "'x86_64-unknown-linux-gnu','a'*40,execute=False)") + child = subprocess.run([sys.executable, "-c", code, str(Path(release.__file__).parent), str(archive)], + capture_output=True, text=True, timeout=20) + self.assertNotEqual(child.returncode, 0) + self.assertIn("ValueError: release tar requires regular USTAR members", child.stderr) + if __name__ == "__main__": unittest.main()