Skip to content
81 changes: 71 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,8 +156,10 @@ The reader consumes at most N + 1 bytes, including for growing or streamed
files. This budget is independent of assembly reservation and ELF output limits.
Oversized or invalid UTF-8 assembly input preserves an existing output file.

IR stdout writes are fallible: a closed pipe exits successfully, and other write
errors exit with status 1 and a diagnostic. Canonical IR and scalar results
CLI stdout writes are fallible: a closed pipe does not cause a panic, and other
write errors exit with status 1 and a diagnostic. Assembly, object and link
reporting continues after a closed pipe, preserving completed artifacts and
real command failures. Successful IR output also treats a closed pipe as success. Canonical IR and scalar results
retain their normal stdout format. `-o` still publishes atomically. The optional
Wave bootstrap likewise replaces its archive only after successful creation,
preserving the previous archive on an archiver failure.
Expand Down Expand Up @@ -189,24 +191,84 @@ cargo run --locked -- ir run answer.wir --function @f7
```

The output is `i32 42`. The default build verifies the whole module and runs
one explicit Whale-convention function with integer/bool parameters and scalar
or void return. Use repeated `--arg` decimal literals (`true`/`false` for Bool)
one explicit Whale-convention function with integer/bool/float parameters and scalar
or void return. Use repeated `--arg` decimal integer literals (`true`/`false` for Bool,
exact-width hexadecimal storage bits for floats)
and `--max-steps` to set the instruction/terminator budget (default 1,000,000).
Zero division/remainder and explicit traps return structured errors; unused
executed operations still trap. Loops evaluate phi inputs simultaneously.

This oracle supports integer constants, arithmetic, comparisons, bit casts,
checked pairs, select and control flow. It also supports tracked stack allocations, integer/Bool/data-pointer storage,
checked pairs, select and control flow. It also supports bit-exact f16/f32/f64 constants, mov/phi/select and tracked
stack allocations, integer/Bool/float/data-pointer storage,
typed GEP, byte copies and fills, with initialization and capability checks.
It executes direct and signature-checked indirect Whale calls with integer/Bool,
It executes direct and signature-checked indirect Whale calls with integer/Bool/float,
data-pointer and function-pointer arguments/results, using one shared fuel and
memory arena. Function pointers retain their full signature and calling convention
through mov/phi/select, storage and complete or split byte copies. It rejects
floating point, external/SysV execution and general aggregate values in every
floating arithmetic/numerical conversions, external/SysV execution and general aggregate values in every
block of the entry and reachable callees, including unreachable blocks. Native
code generation remains unfinished. Legacy `undef` is a verification error. See the Rust `interpret_with_options` API for
adjustable verification limits and trap IR identities.

### Execute exact floating storage and bitcasts

`f16`, `f32` and `f64` use exactly 4, 8 and 16 hexadecimal storage digits.
Constants, arguments/returns, mov/phi/select, stack/global loads and stores, and
byte copies preserve every bit, including signaling/quiet NaN payloads and
signed zero. These operations perform no host floating-point conversion.
Equal-width integer/float `bitcast` reinterprets those bits; `fext`, `ftrunc` and
numeric integer/float conversions remain unsupported during execution. Bitcasts
cannot recover pointer or function-pointer authority from numerical bits.

```sh
cargo run --locked -- ir run ir/tests/fixtures/float-storage-v7.wir --function @f0 --arg 0x7c01
cargo run --locked -- ir run ir/tests/fixtures/float-storage-v7.wir --function @f3
```

These print `f16 0x7c01` and `u64 9218868437227405603`. Floating storage obeys
the same bounds, explicit alignment, permissions, initialization masks and work
budgets as integer storage. A typed field load checks its value bytes without
requiring surrounding aggregate padding to be initialized. Plain storage and
copies never canonicalize a NaN; arithmetic and width-changing conversions have
separate semantics.

### Compare floating values

Generic floating comparisons have the following scalar contract in both
constant evaluation and interpreted IR. Every result has type `bool`.

| Generic operator | Explicit `fcmp` predicate | Result if either operand is NaN |
| --- | --- | --- |
| `cmp feq` | `oeq` | false |
| `cmp fne` | `une` | true |
| `cmp flt` | `olt` | false |
| `cmp fle` | `ole` | false |
| `cmp fgt` | `ogt` | false |
| `cmp fge` | `oge` | false |

Thus generic `!=` is always the logical negation of generic `==`, including
NaN on either side. `+0` and `-0` compare equal; infinities follow numerical
ordering. All NaNs, including signaling NaNs and every sign/payload, make the
operands unordered. Comparisons do not change their original storage bits or
raise floating-point traps.

Explicit `fcmp` supports `oeq`, `one`, `olt`, `ole`, `ogt`, `oge`, `ord`, `uno`,
`ueq`, `une`, `ult`, `ule`, `ugt` and `uge`. Ordered relational predicates
require neither operand to be NaN; unordered relational predicates also return
true if either operand is NaN. `ord` tests that neither is NaN, and `uno` tests
that at least one is NaN. In particular, explicit `one` returns false for NaN,
while generic `fne` maps to `une` and returns true. `CmpOp::float_predicate`
exposes this mapping and `FloatBits::compare` evaluates equal-width predicates.
Runtime execution preserves instruction/trap order, including unused comparisons.

```sh
cargo run --locked -- ir run ir/tests/fixtures/float-comparisons-v7.wir --function @f0 --arg 0x7ff0000000000001 --arg 0x3ff0000000000000
cargo run --locked -- ir run ir/tests/fixtures/float-comparisons-v7.wir --function @f1 --arg 0x7ff0000000000001 --arg 0x3ff0000000000000
```

These print `bool true` (generic inequality) and `bool false` (ordered inequality).

### Execute tracked stack memory

Save [the complete memory fixture](ir/tests/fixtures/tracked-memory-v4.wir)
Expand Down Expand Up @@ -269,9 +331,8 @@ with existing compile-time `Global` declarations, while functions have their own
source-name namespace. `ConstRef` still refers only to compile-time declarations;
it never becomes a runtime address. Initialized storage accepts exact scalar
literal values; pointer/function-pointer cells can start explicitly uninitialized.
Read-only uninitialized declarations and aggregate storage are rejected. Floating
storage literals round-trip, but the current integer interpreter rejects their
instantiation. Integer/Bool initializers initialize their value bytes; physical
Read-only uninitialized declarations and aggregate storage are rejected. Integer/Bool/float
initializers initialize their value bytes; physical
zero-fill of uninitialized storage does not initialize a value.

External storage definitions require an explicit nonempty `link_name`; internal
Expand Down
155 changes: 145 additions & 10 deletions backend-api/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: MPL-2.0
//! Statically linked, out-of-tree code generation. This is a Rust API, not a dylib ABI.
use diagnostic::{Context, Diagnostic, ToDiagnostic};
use std::collections::BTreeSet;
use std::collections::{BTreeMap, BTreeSet};
use target_spec::TargetSpec;

pub enum Requirement<'a> {
Expand All @@ -22,7 +22,10 @@ pub enum Support {
}

pub struct Artifact {
/// Relative portable path. Validated before returning artifacts to callers.
/// Relative portable path, with Windows-compatible components. Paths in one
/// artifact set must be distinct under ASCII case folding and cannot be
/// component-wise ancestors of one another. Unicode case folding is not applied.
/// Validated before returning artifacts to callers.
pub name: String,
pub bytes: Vec<u8>,
}
Expand Down Expand Up @@ -155,23 +158,63 @@ pub fn compile(
) -> Result<Vec<Artifact>, Vec<Diagnostic>> {
let checked = check(backend, module, target, limits)?;
let artifacts = backend.emit(&checked)?;
let mut names = BTreeSet::new();
if artifacts.is_empty() {
return Err(vec![artifact_error("backend emitted no artifacts")]);
}
let mut names = BTreeMap::<String, &str>::new();
for artifact in &artifacts {
if artifact.name.is_empty()
|| artifact.name.contains(['\\', ':'])
|| artifact.name.chars().any(char::is_control)
|| artifact.name.split('/').any(|part| part.is_empty() || part == "." || part == "..")
|| !names.insert(&artifact.name)
{
return Err(vec![artifact_error("invalid or duplicate artifact path")]);
if !artifact.name.split('/').all(portable_component) {
return Err(vec![artifact_error(&format!(
"invalid artifact path {:?}",
artifact.name
))]);
}
let folded = artifact.name.to_ascii_lowercase();
// Prefixes must end at a component boundary: `out` and `out2/a.o`
// are independent files. Check both orders without comparing every pair.
let ancestor = folded.match_indices('/').find_map(|(at, _)| names.get(&folded[..at]));
let prefix = format!("{folded}/");
let descendant = names
.range(prefix.clone()..)
.next()
.filter(|(name, _)| name.starts_with(&prefix))
.map(|(_, name)| name);
if let Some(other) = names.get(&folded).or(ancestor).or(descendant) {
return Err(vec![artifact_error(&format!(
"artifact path {:?} conflicts with {:?}",
artifact.name, other
))]);
}
names.insert(folded, &artifact.name);
}
Ok(artifacts)
}

fn portable_component(part: &str) -> bool {
if part.is_empty()
|| part == "."
|| part == ".."
|| part.ends_with(['.', ' '])
|| part
.chars()
.any(|c| c.is_control() || matches!(c, '\\' | ':' | '<' | '>' | '"' | '|' | '?' | '*'))
{
return false;
}
// Windows also ignores spaces before the extension when recognizing devices.
let basename = part.split('.').next().expect("nonempty component").trim_end_matches(' ');
let reserved = ["CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$"]
.iter()
.any(|name| basename.eq_ignore_ascii_case(name));
let numbered = basename.get(..3).is_some_and(|prefix| {
prefix.eq_ignore_ascii_case("COM") || prefix.eq_ignore_ascii_case("LPT")
}) && matches!(
basename.get(3..),
Some("1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³")
);
!reserved && !numbered
}

fn artifact_error(message: &str) -> Diagnostic {
Diagnostic::new("backend", "emit", "backend.artifact", message)
}
Expand Down Expand Up @@ -268,4 +311,96 @@ mod tests {
let p = probe(Support::Expanded);
assert_eq!(compile(&p, &m, &t, ir::IrLimits::default()).unwrap()[0].bytes, [42]);
}
fn compile_names(names: &[&str]) -> Result<Vec<Artifact>, Vec<Diagnostic>> {
let m = module();
let t = ir::Target::X86_64WhaleLinux.specification();
let mut p = probe(Support::Direct);
p.names = names.iter().map(|s| (*s).to_owned()).collect();
compile(&p, &m, &t, ir::IrLimits::default())
}

#[test]
fn artifact_ancestors_and_ascii_case_collisions_fail_in_either_order() {
for (a, b) in [
("out", "out/module.o"),
("a/b", "a/b/c.o"),
("OUT.o", "out.o"),
("Dir/a.o", "dir/A.o"),
("Dir", "dir/module.o"),
] {
for names in [[a, b], [b, a]] {
let errors = compile_names(&names).err().unwrap();
assert_eq!(errors[0].code, "backend.artifact");
assert!(errors[0].message.contains(a), "{}", errors[0]);
assert!(errors[0].message.contains(b), "{}", errors[0]);
}
}
// A non-ancestor sorting between a path and its child must not hide it.
assert!(compile_names(&["a", "a-b", "a/b.o"]).is_err());
assert!(compile_names(&["a/b.o", "a-b", "a"]).is_err());
}

#[test]
fn every_artifact_component_must_be_portable() {
for part in [
"CON",
"con.txt",
"CON .txt",
"COM1 .o",
"LPT9 .obj",
"NUL .txt",
"PrN",
"NUL.txt",
"AUX",
"COM1.obj",
"lpt9",
"COM¹",
"lpt².txt",
"CONIN$",
"CONOUT$.txt",
"out?.o",
"a|b.o",
"a<b",
"a>b",
"a*b",
"a\"b",
"a:b",
"out.o.",
"out.o ",
"bad\nname",
"bad\0name",
"bad\u{85}name",
] {
for name in [part.to_owned(), format!("valid/{part}/file.o")] {
let errors = compile_names(&[&name]).err().unwrap();
assert_eq!(errors[0].code, "backend.artifact", "{name:?}");
}
}
for number in 1..=9 {
for prefix in ["COM", "lPt"] {
assert!(compile_names(&[&format!("{prefix}{number}.obj")]).is_err());
}
}
}

#[test]
fn valid_artifact_names_keep_their_original_spelling() {
let names = [
"out",
"out2/module.o",
"Dir/a.o",
"dir/B.o",
"한글/λ.o",
"Ä.o",
"ä.o",
"COM0",
"COM10",
"LPT0.txt",
"NULled.o",
"CON name.txt",
"COM10 .o",
];
let artifacts = compile_names(&names).unwrap();
assert_eq!(artifacts.iter().map(|a| a.name.as_str()).collect::<Vec<_>>(), names);
}
}
63 changes: 60 additions & 3 deletions diagnostic/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,16 +66,36 @@ impl ToDiagnostic for Diagnostic {
}
}

// Keep ordinary Unicode paths readable while preventing names from creating
// new terminal lines or control sequences. Structured contexts stay lossless.
struct ContextName<'a>(&'a str);

impl fmt::Display for ContextName<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use fmt::Write;
for character in self.0.chars() {
if character.is_control() {
write!(f, "{}", character.escape_debug())?;
} else {
f.write_char(character)?;
}
}
Ok(())
}
}

impl fmt::Display for Diagnostic {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}: {}", self.code, self.message)?;
for context in &self.contexts {
match context {
Context::Source(s) => write!(f, " at {}:{}:{}", s.source, s.line, s.column)?,
Context::Source(s) => {
write!(f, " at {}:{}:{}", ContextName(&s.source), s.line, s.column)?
},
Context::Object { name, member } => {
write!(f, " in {name}")?;
write!(f, " in {}", ContextName(name))?;
if let Some(m) = member {
write!(f, "({m})")?;
write!(f, "({})", ContextName(m))?;
}
},
Context::Input(i) => write!(f, " input {i}")?,
Expand Down Expand Up @@ -118,3 +138,40 @@ mod tests {
assert_eq!(d.code, "invalid-index");
}
}

#[cfg(test)]
mod control_tests {
use super::*;

#[test]
fn context_names_escape_controls_without_changing_structured_fields() {
for control in ['\n', '\r', '\t', '\x1b'] {
let name = format!("경로/{control}file");
let d = Diagnostic::new("audit", "read", "audit.invalid", "invalid")
.with_context(Context::Source(SourceLocation {
source: name.clone(),
line: 2,
column: 3,
..Default::default()
}))
.with_context(Context::Object { name: name.clone(), member: Some(name.clone()) });
let original = d.clone();
let rendered = d.to_string();
assert!(!rendered.contains(control), "{rendered:?}");
assert!(rendered.contains("경로/"));
assert!(rendered.contains(":2:3"));
assert!(rendered.contains(&control.escape_debug().to_string()));
assert_eq!(d, original);
assert_eq!(d.diagnostic(), original);
}
let d = Diagnostic::new("audit", "read", "audit.invalid", "invalid").with_context(
Context::Source(SourceLocation {
source: "경로/café.s".into(),
line: 4,
column: 5,
..Default::default()
}),
);
assert_eq!(d.to_string(), "audit.invalid: invalid at 경로/café.s:4:5");
}
}
4 changes: 3 additions & 1 deletion ir/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,9 @@ impl ModuleBuilder {
};
}
if let Some(link) = &candidate.link_name {
if self.module.declarations.iter().any(|d| d.link_name.as_ref() == Some(link)) {
if self.module.declarations.iter().any(|d| d.link_name.as_ref() == Some(link))
|| self.module.global_storage.iter().any(|g| g.link_name.as_ref() == Some(link))
{
return Err(crate::CallError::LinkNameCollision(link.clone()));
}
}
Expand Down
Loading
Loading