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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions .github/workflows/quality.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
47 changes: 44 additions & 3 deletions assembler/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use diagnostic::EscapedName;

use std::fmt;

/// Half-open UTF-8 byte range; line/column are one-based Unicode-scalar coordinates.
Expand Down Expand Up @@ -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(())
},
Expand All @@ -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"));
}
}
20 changes: 19 additions & 1 deletion backend-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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(['.', ' '])
Expand Down Expand Up @@ -422,4 +425,19 @@ mod tests {
let artifacts = compile_names(&names).unwrap();
assert_eq!(artifacts.iter().map(|a| a.name.as_str()).collect::<Vec<_>>(), 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());
}
}
11 changes: 6 additions & 5 deletions diagnostic/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand All @@ -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}")?,
Expand Down
3 changes: 3 additions & 0 deletions fuzz/support.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
3 changes: 3 additions & 0 deletions ir/src/float/arithmetic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,9 @@ pub fn negate(value: FloatBits) -> FloatBits {
}

pub fn arithmetic(op: &BinOp, lhs: FloatBits, rhs: FloatBits) -> Option<FloatBits> {
if !matches!(op, BinOp::FAdd | BinOp::FSub | BinOp::FMul | BinOp::FDiv | BinOp::FRem) {
return None;
}
if lhs.width() != rhs.width() {
return None;
}
Expand Down
39 changes: 29 additions & 10 deletions ir/src/float/conversions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Format> {
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<ConstValue> {
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 {
Expand All @@ -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;
Expand All @@ -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 {
Expand Down
4 changes: 3 additions & 1 deletion ir/src/lower_ast/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

use crate::{ConstValue, Type};

use diagnostic::EscapedName;

#[derive(Debug)]
pub enum LowerError {
Located { annotation: crate::SourceAnnotation, error: Box<LowerError> },
Expand Down Expand Up @@ -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 {
Expand Down
15 changes: 13 additions & 2 deletions ir/src/lower_ast/o0/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
4 changes: 3 additions & 1 deletion ir/src/source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))]
Expand Down Expand Up @@ -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)
}
Expand Down
6 changes: 4 additions & 2 deletions ir/src/verifier.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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(),
})
Expand Down
Loading
Loading