diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3402cd18..5d48eb81 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1444,7 +1444,7 @@ jobs: timeout-minutes: 30 run: | set -euo pipefail - python -m mesonbuild.mesonmain test -C build-ci --suite tooling --print-errorlogs + python -m mesonbuild.mesonmain test -C build-ci --suite tooling --verbose --print-errorlogs - name: Build release compiler id: stage-10 shell: bash @@ -1572,7 +1572,7 @@ jobs: timeout-minutes: 30 run: | set -euo pipefail - python -m mesonbuild.mesonmain test -C build-ci --suite tooling --print-errorlogs + python -m mesonbuild.mesonmain test -C build-ci --suite tooling --verbose --print-errorlogs - name: Build release compiler id: stage-10 shell: bash @@ -1975,7 +1975,7 @@ jobs: timeout-minutes: 30 run: | $ErrorActionPreference = "Stop" - & 'python' '-m' 'mesonbuild.mesonmain' 'test' '-C' 'build-ci' '--suite' 'tooling' '--print-errorlogs' + & 'python' '-m' 'mesonbuild.mesonmain' 'test' '-C' 'build-ci' '--suite' 'tooling' '--verbose' '--print-errorlogs' if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } if: ${{ !cancelled() && steps.tooling_bootstrap.outcome == 'success' }} - name: Install Wave standard library @@ -2191,7 +2191,7 @@ jobs: timeout-minutes: 30 run: | $ErrorActionPreference = "Stop" - & 'python' '-m' 'mesonbuild.mesonmain' 'test' '-C' 'build-ci' '--suite' 'tooling' '--print-errorlogs' + & 'python' '-m' 'mesonbuild.mesonmain' 'test' '-C' 'build-ci' '--suite' 'tooling' '--verbose' '--print-errorlogs' if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } if: ${{ !cancelled() && steps.tooling_bootstrap.outcome == 'success' }} - name: Run native ARM64 unit and frontend driver tests diff --git a/Cargo.lock b/Cargo.lock index 4d5ee7d2..64decd08 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -47,6 +47,12 @@ dependencies = [ "generic-array", ] +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + [[package]] name = "cap-fs-ext" version = "3.4.4" @@ -111,6 +117,15 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" +[[package]] +name = "constant_time_eq" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "144e7f1de087984240b7816d47f698b414979faa6f40839c5b86d6bd47db57b7" +dependencies = [ + "rustversion", +] + [[package]] name = "cpufeatures" version = "0.2.17" @@ -252,8 +267,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi", + "wasm-bindgen", ] [[package]] @@ -355,6 +372,16 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "wasm-bindgen", +] + [[package]] name = "lazy_static" version = "1.5.0" @@ -444,9 +471,9 @@ dependencies = [ [[package]] name = "num-conv" -version = "0.1.0" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" [[package]] name = "object" @@ -555,6 +582,12 @@ dependencies = [ "rustix", ] +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + [[package]] name = "semver" version = "1.0.28" @@ -714,30 +747,30 @@ dependencies = [ [[package]] name = "time" -version = "0.3.44" +version = "0.3.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91e7d9e3bb61134e77bde20dd4825b97c010155709965fedf0f49bb138e52a9d" +checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c" dependencies = [ "deranged", "itoa", "num-conv", "powerfmt", - "serde", + "serde_core", "time-core", "time-macros", ] [[package]] name = "time-core" -version = "0.1.6" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40868e7c1d2f0b8d73e4a8c7f0ff63af4f6d19be117e90bd73eb1d62cf831c6b" +checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca" [[package]] name = "time-macros" -version = "0.2.24" +version = "0.2.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30cfb0125f12d9c277f35663a0a33f8c30190f4e4574868a330595412d34ebf3" +checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215" dependencies = [ "num-conv", "time-core", @@ -786,9 +819,9 @@ checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" [[package]] name = "typed-path" -version = "0.12.3" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" +checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" [[package]] name = "typenum" @@ -828,6 +861,50 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + [[package]] name = "wave-tools" version = "0.1.0" @@ -995,15 +1072,41 @@ dependencies = [ "hashlink", ] +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.118", +] + [[package]] name = "zip" -version = "8.6.0" +version = "9.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b" +checksum = "df3845f734baabdd02de353a20580e30ceccd03897def44a4eb8e9654992e294" dependencies = [ + "constant_time_eq", "crc32fast", "flate2", + "getrandom", "indexmap", + "libc", "memchr", + "nix", "typed-path", + "windows-sys 0.61.2", + "zeroize", ] diff --git a/front/parser/src/ast.rs b/front/parser/src/ast.rs index 82636a49..cb3bb1e7 100644 --- a/front/parser/src/ast.rs +++ b/front/parser/src/ast.rs @@ -31,6 +31,7 @@ pub enum WaveType { Bool, Char, Byte, + /// NUL-terminated bytes. Literal storage is read-only; a view into a mutable buffer may be written. String, Pointer(Box), /// A lazy asynchronous computation with this completion type. diff --git a/front/parser/src/ast/visit.rs b/front/parser/src/ast/visit.rs index 441eea71..0d454e5a 100644 --- a/front/parser/src/ast/visit.rs +++ b/front/parser/src/ast/visit.rs @@ -14,21 +14,37 @@ use super::{ASTNode, Expression, StatementNode}; pub fn walk_nodes(nodes: &[ASTNode], visit: &mut impl FnMut(&Expression)) { + walk_nodes_with_statements(nodes, visit, &mut |_| {}); +} + +pub fn walk_node(node: &ASTNode, visit: &mut impl FnMut(&Expression)) { + walk_node_with_statements(node, visit, &mut |_| {}); +} + +pub(crate) fn walk_nodes_with_statements( + nodes: &[ASTNode], + visit: &mut impl FnMut(&Expression), + statement: &mut impl FnMut(&StatementNode), +) { for node in nodes { - walk_node(node, visit); + walk_node_with_statements(node, visit, statement); } } -pub fn walk_node(node: &ASTNode, visit: &mut impl FnMut(&Expression)) { +fn walk_node_with_statements( + node: &ASTNode, + visit: &mut impl FnMut(&Expression), + statement: &mut impl FnMut(&StatementNode), +) { match node { - ASTNode::Located { value, .. } => walk_node(value, visit), + ASTNode::Located { value, .. } => walk_node_with_statements(value, visit, statement), ASTNode::Function(function) => { for parameter in &function.parameters { if let Some(default) = ¶meter.initial_value { walk_expression(default, visit); } } - walk_nodes(&function.body, visit); + walk_nodes_with_statements(&function.body, visit, statement); }, ASTNode::Struct(structure) => { for method in &structure.methods { @@ -37,7 +53,7 @@ pub fn walk_node(node: &ASTNode, visit: &mut impl FnMut(&Expression)) { walk_expression(default, visit); } } - walk_nodes(&method.body, visit); + walk_nodes_with_statements(&method.body, visit, statement); } }, ASTNode::ProtoImpl(implementation) => { @@ -47,10 +63,13 @@ pub fn walk_node(node: &ASTNode, visit: &mut impl FnMut(&Expression)) { walk_expression(default, visit); } } - walk_nodes(&method.body, visit); + walk_nodes_with_statements(&method.body, visit, statement); } }, - ASTNode::Statement(statement) => walk_statement(statement, visit), + ASTNode::Statement(node) => { + statement(node); + walk_statement(node, visit, statement); + }, ASTNode::Variable(variable) => { if let Some(initializer) = &variable.initial_value { walk_expression(initializer, visit); @@ -65,8 +84,12 @@ pub fn walk_node(node: &ASTNode, visit: &mut impl FnMut(&Expression)) { } } -fn walk_statement(statement: &StatementNode, visit: &mut impl FnMut(&Expression)) { - match statement { +fn walk_statement( + node: &StatementNode, + visit: &mut impl FnMut(&Expression), + statement: &mut impl FnMut(&StatementNode), +) { + match node { StatementNode::PrintFormat { args, .. } | StatementNode::PrintlnFormat { args, .. } | StatementNode::Input { args, .. } => { @@ -76,31 +99,31 @@ fn walk_statement(statement: &StatementNode, visit: &mut impl FnMut(&Expression) }, StatementNode::If { condition, body, else_if_blocks, else_block } => { walk_expression(condition, visit); - walk_nodes(body, visit); + walk_nodes_with_statements(body, visit, statement); if let Some(blocks) = else_if_blocks { for (condition, body) in blocks.iter() { walk_expression(condition, visit); - walk_nodes(body, visit); + walk_nodes_with_statements(body, visit, statement); } } if let Some(body) = else_block { - walk_nodes(body, visit); + walk_nodes_with_statements(body, visit, statement); } }, StatementNode::For { initialization, condition, increment, body } => { - walk_node(initialization, visit); + walk_node_with_statements(initialization, visit, statement); walk_expression(condition, visit); walk_expression(increment, visit); - walk_nodes(body, visit); + walk_nodes_with_statements(body, visit, statement); }, StatementNode::While { condition, body } => { walk_expression(condition, visit); - walk_nodes(body, visit); + walk_nodes_with_statements(body, visit, statement); }, StatementNode::Match { value, arms } => { walk_expression(value, visit); for arm in arms { - walk_nodes(&arm.body, visit); + walk_nodes_with_statements(&arm.body, visit, statement); } }, StatementNode::Assign { value, .. } => walk_expression(value, visit), diff --git a/front/parser/src/import.rs b/front/parser/src/import.rs index 40509f69..e4480f91 100644 --- a/front/parser/src/import.rs +++ b/front/parser/src/import.rs @@ -161,95 +161,78 @@ fn is_supported_target_item_start(line: &str) -> bool { false } +#[derive(Clone, Copy, PartialEq, Eq)] +enum TargetItemEnd { + TrackComments, + ReadKeyword, + BraceOrSemicolon, + Semicolon, +} + fn scan_target_item_line( line: &str, in_block_comment: &mut usize, - depth: &mut i32, - seen_open: &mut bool, - saw_semicolon: &mut bool, -) { - let mut chars = line.chars().peekable(); - let mut in_string = false; - let mut in_char = false; - let mut escape = false; - + depth: &mut usize, + end: &mut TargetItemEnd, + quote: &mut Option, +) -> Option { + let mut chars = line.chars(); while let Some(ch) = chars.next() { if *in_block_comment > 0 { - if ch == '*' && chars.peek() == Some(&'/') { + if ch == '*' && chars.as_str().starts_with('/') { chars.next(); *in_block_comment -= 1; - } else if ch == '/' && chars.peek() == Some(&'*') { + } else if ch == '/' && chars.as_str().starts_with('*') { chars.next(); *in_block_comment += 1; } continue; } - - if in_string { - if escape { - escape = false; - continue; - } - if ch == '\\' { - escape = true; - continue; - } - if ch == '"' { - in_string = false; - } - continue; - } - - if in_char { - if escape { - escape = false; - continue; - } + if let Some(delimiter) = *quote { if ch == '\\' { - escape = true; - continue; - } - if ch == '\'' { - in_char = false; + chars.next(); + } else if ch == delimiter { + *quote = None; } continue; } - - if ch == '/' { - if chars.peek() == Some(&'/') { - break; - } - if chars.peek() == Some(&'*') { - chars.next(); - *in_block_comment = 1; - continue; - } + if ch == '/' && chars.as_str().starts_with('/') { + break; } - - if ch == '"' { - in_string = true; + if ch == '/' && chars.as_str().starts_with('*') { + chars.next(); + *in_block_comment = 1; continue; } - if ch == '\'' { - in_char = true; + if ch == '"' || ch == '\'' { + *quote = Some(ch); continue; } - if ch == '{' { + if *end == TargetItemEnd::ReadKeyword && ch.is_ascii_alphabetic() { + let start = line.len() - chars.as_str().len() - 1; + let word = line[start..] + .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) + .next() + .unwrap(); + chars = line[start + word.len()..].chars(); + *end = match word { + "pub" | "async" => TargetItemEnd::ReadKeyword, + "import" | "const" | "static" | "type" => TargetItemEnd::Semicolon, + _ => TargetItemEnd::BraceOrSemicolon, + }; + } else if ch == '{' { *depth += 1; - *seen_open = true; - continue; - } - if ch == '}' { - if *depth > 0 { - *depth -= 1; + } else if ch == '}' && *depth > 0 { + *depth -= 1; + if *depth == 0 && *end == TargetItemEnd::BraceOrSemicolon { + return Some(line.len() - chars.as_str().len()); } - continue; - } - if ch == ';' { - *saw_semicolon = true; + } else if ch == ';' && *depth == 0 && *end != TargetItemEnd::TrackComments { + return Some(line.len() - chars.as_str().len()); } } + None } fn consume_target_item( @@ -261,37 +244,39 @@ fn consume_target_item( in_block_comment: &mut usize, ) -> usize { let first = idx; - let mut depth: i32 = 0; - let mut seen_open = false; - + let mut depth = 0; + let mut end = TargetItemEnd::ReadKeyword; + let mut quote = None; while idx < lines.len() { let line = lines[idx]; - if keep { - out.push(line.to_string()); - } else { - out.push(" ".repeat(line.len())); - } - - let mut saw_semicolon = false; - scan_target_item_line( - if idx == first { &line[first_offset..] } else { line }, + let start = if idx == first { first_offset } else { 0 }; + let boundary = scan_target_item_line( + &line[start..], in_block_comment, &mut depth, - &mut seen_open, - &mut saw_semicolon, + &mut end, + &mut quote, ); + let stop = boundary.map_or(line.len(), |offset| start + offset); + if keep { + out.push(line.to_owned()); + } else { + out.push(format!("{}{}{}", &line[..start], " ".repeat(stop - start), &line[stop..])); + } idx += 1; - - if seen_open { - if depth == 0 { - break; - } - } else if saw_semicolon { + if boundary.is_some() { + // A following declaration or opening block comment belongs to active source. + scan_target_item_line( + &line[stop..], + in_block_comment, + &mut 0, + &mut TargetItemEnd::TrackComments, + &mut None, + ); break; } } - idx } @@ -333,63 +318,36 @@ pub fn preprocess_target_attrs(source: &str, target: &TargetConditionContext) -> let mut idx: usize = 0; let mut comment_depth = 0; + let mut pending = None; while idx < lines.len() { let line = lines[idx]; - if let Some((target_attr, tail, tail_depth)) = - (comment_depth == 0).then(|| parse_target_attr(line)).flatten() - { - let keep_item = target_attr.matches(target); - // Retain active trailing comments, including their opening delimiter, - // while replacing only the attribute's bytes with spaces. - out.push(if keep_item { - format!("{}{}", " ".repeat(tail), &line[tail..]) - } else { - " ".repeat(line.len()) - }); + let Some(start) = target_item_start(line, &mut comment_depth) else { + out.push(line.to_owned()); + idx += 1; + continue; + }; + if let Some((attr, len, tail_depth)) = parse_target_attr(&line[start..]) { + pending = Some(pending.unwrap_or(true) && attr.matches(target)); + out.push(format!("{}{}{}", &line[..start], " ".repeat(len), &line[start + len..])); comment_depth = tail_depth; idx += 1; - - // Attribute applies to the next top-level item. - // Preserve line count for any leading blanks/comments. - while idx < lines.len() { - let item_line = lines[idx]; - let code_start = target_item_start(item_line, &mut comment_depth); - if code_start.is_none() { - if keep_item { - out.push(item_line.to_string()); - } else { - out.push(" ".repeat(item_line.len())); - } - idx += 1; - continue; - } - - let code_start = code_start.unwrap(); - if is_supported_target_item_start(&item_line[code_start..]) { - idx = consume_target_item( - &lines, - idx, - code_start, - keep_item, - &mut out, - &mut comment_depth, - ); - } else if keep_item { - out.push(item_line.to_string()); - idx += 1; - } else { - out.push(" ".repeat(item_line.len())); - idx += 1; - } - break; - } continue; } - - // Track comments in ordinary source too: attribute-looking text inside - // a comment is source text, not a preprocessing directive. - scan_target_item_line(line, &mut comment_depth, &mut 0, &mut false, &mut false); - out.push(line.to_string()); + if let Some(keep) = pending.take() { + if is_supported_target_item_start(&line[start..]) { + idx = consume_target_item(&lines, idx, start, keep, &mut out, &mut comment_depth); + continue; + } + } + // Leave malformed attributes visible to the parser, even after a false condition. + scan_target_item_line( + &line[start..], + &mut comment_depth, + &mut 0, + &mut TargetItemEnd::TrackComments, + &mut None, + ); + out.push(line.to_owned()); idx += 1; } @@ -1143,6 +1101,74 @@ mod tests { std::fs::remove_dir_all(root).unwrap(); } + #[test] + fn inactive_item_ends_before_other_declarations_on_the_same_line() { + for item in [ + r#"pub fun absent() { var s: str = "};"; /* } ; */ if (true) { return; } }"#, + r#"import("absent")::{one, two};"#, + "struct Absent { x: i32; }", + "pub /* ignored } */ const ABSENT: i32 = 7;", + "pub\nconst ABSENT: Pair = Pair { x: 1 }\n;", + ] { + for newline in ["\n", "\r\n", "\r"] { + let source = format!("#[target(os=\"windows\")]\n{item} const KEEP: i32 = 7; /*\n#[target(os=\"windows\")]\n*/ fun main() -> i32 {{ return KEEP; }}").replace('\n', newline); + let processed = preprocess_target_attrs( + &source, + &TargetConditionContext { os: Some("linux".into()), ..Default::default() }, + ); + let after = source.find(" const KEEP").unwrap(); + assert_eq!(&processed[after..], &source[after..]); + assert!(processed[..after].trim().is_empty(), "{processed}"); + let tokens = Lexer::new(&processed).tokenize().unwrap(); + crate::parse_syntax_only(&tokens).unwrap(); + } + } + } + + #[test] + fn stacked_target_attributes_require_every_condition_and_keep_source_spans() { + for newline in ["\n", "\r", "\r\n"] { + for attributes in [ + ["os=\"windows\"", "arch=\"amd64\"", "env=\"msvc\""], + ["env=\"msvc\"", "os=\"windows\"", "arch=\"amd64\""], + ["arch=\"amd64\"", "env=\"msvc\"", "os=\"windows\""], + ] { + let mut lines = vec!["/* é */".to_owned()]; + for attribute in attributes { + lines.extend([ + format!("#[target({attribute})] /* start"), + " */ // next condition".into(), + String::new(), + ]); + } + lines.push("fun platform() {} fun after() {}".into()); + let source = lines.join(newline); + for (os, arch, env, keep) in [ + ("windows", "x86_64", "msvc", true), + ("linux", "x86_64", "msvc", false), + ("windows", "arm64", "msvc", false), + ("windows", "x86_64", "gnu", false), + ] { + let target = TargetConditionContext { + os: Some(os.into()), + arch: Some(arch.into()), + env: Some(env.into()), + ..Default::default() + }; + let output = preprocess_target_attrs(&source, &target); + assert_eq!(output.len(), source.len()); + assert_eq!(output.find("fun after"), source.find("fun after")); + assert_eq!(output.contains("fun platform"), keep); + crate::parse_syntax_only(&Lexer::new(&output).tokenize().unwrap()).unwrap(); + } + } + } + let malformed = "#[target(os=\"never\")]\n#[target(typo=\"linux\")]\nfun platform() {}"; + let output = preprocess_target_attrs(malformed, &TargetConditionContext::default()); + assert!(output.contains("#[target(typo=")); + assert!(output.contains("fun platform")); + } + #[test] fn target_attribute_trivia_handles_nested_comments_and_preserves_source_offsets() { for newline in ["\n", "\r\n", "\r"] { diff --git a/front/parser/src/verification.rs b/front/parser/src/verification.rs index a4ec1a2a..3a4443e3 100644 --- a/front/parser/src/verification.rs +++ b/front/parser/src/verification.rs @@ -120,6 +120,7 @@ struct Validator<'a> { program: &'a ProgramTypes, scopes: Vec>, binding_sites: Vec)>>, + rebound_names: HashSet, declaration_order: usize, related: Vec, suggestions: Vec, @@ -151,6 +152,7 @@ impl<'a> Validator<'a> { program, scopes: vec![HashMap::new()], binding_sites: vec![HashMap::new()], + rebound_names: HashSet::new(), declaration_order: 0, related: Vec::new(), suggestions: Vec::new(), @@ -333,12 +335,18 @@ impl<'a> Validator<'a> { &format!("return type of function `{}`", display_name), )?; + let previous_rebound = + std::mem::replace(&mut self.rebound_names, storage::rebound_names(&function.body)); let result = self.with_scope(|validator| { for parameter in &function.parameters { validator.source_span = parameter.span.clone(); validator.insert_current_binding( parameter.name.clone(), - Binding { mutability: Mutability::Var, ty: parameter.param_type.clone() }, + Binding { + literal_address: false, + mutability: Mutability::Var, + ty: parameter.param_type.clone(), + }, "parameter", )?; } @@ -357,6 +365,7 @@ impl<'a> Validator<'a> { Ok(()) }); + self.rebound_names = previous_rebound; self.current_async = previous_async; self.current_function = previous_function; self.current_return_type = previous_return; @@ -448,7 +457,11 @@ impl<'a> Validator<'a> { if asm_initializer { self.insert_current_binding( variable.name.clone(), - Binding { mutability: variable.mutability, ty: variable.type_name.clone() }, + Binding { + literal_address: false, + mutability: variable.mutability, + ty: variable.type_name.clone(), + }, "variable", )?; } @@ -464,9 +477,15 @@ impl<'a> Validator<'a> { if !asm_initializer { self.source_span = self.source_map.nodes.get(&(node as *const _ as usize)).cloned(); + let literal_address = !self.rebound_names.contains(&variable.name) + && variable.initial_value.as_ref().is_some_and(|value| self.literal_address(value)); self.insert_current_binding( variable.name.clone(), - Binding { mutability: variable.mutability, ty: variable.type_name.clone() }, + Binding { + literal_address, + mutability: variable.mutability, + ty: variable.type_name.clone(), + }, "variable", )?; } @@ -591,7 +610,7 @@ impl<'a> Validator<'a> { if !is_lvalue_expression(argument) { return Err("input argument must be a mutable lvalue".to_string()); } - self.ensure_mutable_write_target(argument, "write input into")?; + self.ensure_writable_storage(argument, "write input into")?; let ty = self.validate_expr(argument)?; let supported = match &ty { ExpressionType::Known(ty) => matches!( @@ -888,7 +907,7 @@ impl<'a> Validator<'a> { for (name, ty) in bindings { validator.insert_current_binding( name, - Binding { mutability: Mutability::Var, ty }, + Binding { literal_address: false, mutability: Mutability::Var, ty }, "pattern binding", )?; } diff --git a/front/parser/src/verification/expression.rs b/front/parser/src/verification/expression.rs index ba3bbe9b..8ed6326b 100644 --- a/front/parser/src/verification/expression.rs +++ b/front/parser/src/verification/expression.rs @@ -487,7 +487,7 @@ impl Validator<'_> { if !is_lvalue_expression(target) { return Err("assignment target is not an lvalue".to_string()); } - self.ensure_mutable_write_target(target, "assign")?; + self.ensure_writable_storage(target, "assign")?; let target_type = self.validate_expr(target)?; let target_type = match target_type { ExpressionType::Known(ty) => ExpressionType::Known(self.program.canonical_type(&ty)), @@ -520,7 +520,7 @@ impl Validator<'_> { if !is_lvalue_expression(target) { return Err("compound assignment target is not an lvalue".to_string()); } - self.ensure_mutable_write_target(target, "modify with compound assignment")?; + self.ensure_writable_storage(target, "modify with compound assignment")?; let target_type = self.validate_expr(target)?; let target_type = match target_type { ExpressionType::Known(ty) => ExpressionType::Known(self.program.canonical_type(&ty)), @@ -576,7 +576,7 @@ impl Validator<'_> { if !is_lvalue_expression(target) { return Err("++/-- target is not an lvalue".to_string()); } - self.ensure_mutable_write_target(target, "modify with ++/--")?; + self.ensure_writable_storage(target, "modify with ++/--")?; let ty = self.validate_expr(target)?; let supported = match &ty { ExpressionType::Known(ty) => matches!( diff --git a/front/parser/src/verification/model.rs b/front/parser/src/verification/model.rs index e1a05d18..24887709 100644 --- a/front/parser/src/verification/model.rs +++ b/front/parser/src/verification/model.rs @@ -15,6 +15,7 @@ use crate::ast::{Expression, Mutability, WaveType}; #[derive(Clone, Debug)] pub(super) struct Binding { + pub(super) literal_address: bool, pub(super) mutability: Mutability, pub(super) ty: WaveType, } diff --git a/front/parser/src/verification/program.rs b/front/parser/src/verification/program.rs index c462714e..55bea56d 100644 --- a/front/parser/src/verification/program.rs +++ b/front/parser/src/verification/program.rs @@ -230,7 +230,15 @@ impl ProgramTypes { .map_err(|message| failure(message, Some(top_level_span_hint(node))))?; out.globals.insert( variable.name.clone(), - Binding { mutability: variable.mutability, ty: variable.type_name.clone() }, + Binding { + literal_address: variable.mutability == Mutability::Const + && matches!( + variable.initial_value, + Some(Expression::Literal(Literal::String(_))) + ), + mutability: variable.mutability, + ty: variable.type_name.clone(), + }, ); if matches!(variable.mutability, Mutability::Const) { if let Some(Expression::Literal(Literal::Int(raw))) = @@ -265,6 +273,7 @@ impl ProgramTypes { out.globals.insert( variant.name.clone(), Binding { + literal_address: false, mutability: Mutability::Const, ty: WaveType::Struct(enumeration.name.clone()), }, diff --git a/front/parser/src/verification/storage.rs b/front/parser/src/verification/storage.rs index 5d4160ae..45b34f1d 100644 --- a/front/parser/src/verification/storage.rs +++ b/front/parser/src/verification/storage.rs @@ -112,3 +112,105 @@ pub(super) fn validate( } Ok(()) } + +fn ungroup(mut value: &Expression) -> &Expression { + while let Expression::Grouped(inner) | Expression::Located { value: inner, .. } = value { + value = inner; + } + value +} + +fn record_name(names: &mut HashSet, expression: &Expression) { + if let Expression::Variable(name) = ungroup(expression) { + names.insert(name.clone()); + } +} + +/// A source diagnostic requires a stable address. A reassigned or escaped +/// binding (including a loop back-edge) is checked at the actual write instead. +pub(super) fn rebound_names(body: &[ASTNode]) -> HashSet { + let mut expressions = HashSet::new(); + let mut statements = HashSet::new(); + visit::walk_nodes_with_statements( + body, + &mut |expr| match expr { + Expression::Assignment { target, .. } + | Expression::AssignOperation { target, .. } + | Expression::IncDec { target, .. } + | Expression::AddressOf(target) => record_name(&mut expressions, target), + Expression::AsmBlock { outputs, .. } => { + for (_, output) in outputs { + record_name(&mut expressions, output); + } + }, + _ => {}, + }, + &mut |statement| match statement { + StatementNode::AsmBlock { outputs, .. } => { + for (_, output) in outputs { + record_name(&mut statements, output); + } + }, + StatementNode::Assign { variable, .. } => { + statements.insert(variable.clone()); + }, + StatementNode::Input { args, .. } => { + for output in args { + record_name(&mut statements, output); + } + }, + _ => {}, + }, + ); + expressions.extend(statements); + expressions +} + +impl super::Validator<'_> { + fn literal_storage(&self, place: &Expression) -> bool { + match ungroup(place) { + Expression::Deref(address) | Expression::IndexAccess { target: address, .. } => { + self.literal_address(address) + }, + Expression::FieldAccess { object, .. } => { + self.literal_storage(object) || self.literal_address(object) + }, + _ => false, + } + } + + pub(super) fn literal_address(&self, value: &Expression) -> bool { + match ungroup(value) { + Expression::Literal(Literal::String(_)) => true, + Expression::Variable(name) => { + self.lookup_binding(name).is_some_and(|b| b.literal_address) + }, + Expression::Cast { expr, target_type } + if matches!( + self.program.canonical_type(target_type), + WaveType::Pointer(_) | WaveType::String + ) => + { + self.literal_address(expr) + }, + Expression::AddressOf(place) => self.literal_storage(place), + _ => false, + } + } + + pub(super) fn ensure_writable_storage( + &mut self, + target: &Expression, + operation: &str, + ) -> Result<(), String> { + if self.literal_storage(target) { + if let Some(span) = self.source_map.expressions.get(&(target as *const _ as usize)) { + self.source_span = Some(span.clone()); + } + self.diagnostic_help = + Some("write into a mutable byte buffer or a str backed by that buffer".into()); + return Err("cannot write to read-only string literal storage".into()); + } + self.ensure_mutable_write_target(target, operation) + } +} diff --git a/llvm/src/codegen/consts.rs b/llvm/src/codegen/consts.rs index bb5b5d86..bbd455ff 100644 --- a/llvm/src/codegen/consts.rs +++ b/llvm/src/codegen/consts.rs @@ -19,7 +19,7 @@ use hir::HirExpressionType; use inkwell::context::Context; -use inkwell::module::{Linkage, Module}; +use inkwell::module::Module; use inkwell::targets::TargetData; use inkwell::types::{BasicTypeEnum, StringRadix, StructType}; use inkwell::values::{BasicValue, BasicValueEnum}; @@ -338,12 +338,7 @@ fn const_raw<'ctx>( Err(ConstEvalError::Unsupported("ICE: cast missing HIR conversion facts".into())) }, Expression::Literal(Literal::String(bytes)) => { - let value = context.const_string(bytes, true); - let global = module.add_global(value.get_type(), None, "$const$str"); - global.set_initializer(&value); - global.set_constant(true); - global.set_linkage(Linkage::Private); - Ok(global.as_pointer_value().into()) + Ok(super::literal_storage::literal(context, module, bytes).into()) }, Expression::Literal(Literal::Char(value)) => { Ok(context.i8_type().const_int(*value as u64, false).into()) diff --git a/llvm/src/codegen/conversions.rs b/llvm/src/codegen/conversions.rs index a426f7ea..f5051595 100644 --- a/llvm/src/codegen/conversions.rs +++ b/llvm/src/codegen/conversions.rs @@ -14,12 +14,12 @@ use super::types::{wave_type_to_llvm_type, TypeFlavor}; use hir::conversions::{unsigned, ConversionInfo, ConversionKind}; use inkwell::{ - builder::Builder, + builder::{Builder, BuilderError}, context::Context, intrinsics::Intrinsic, module::Module, types::StructType, - values::{BasicValue, BasicValueEnum}, + values::{BasicValue, BasicValueEnum, IntValue}, FloatPredicate, IntPredicate, }; use parser::ast::{Operator, WaveType}; @@ -160,6 +160,21 @@ pub(crate) fn apply<'ctx>( } } +pub(crate) fn signed_remainder<'ctx>( + builder: &Builder<'ctx>, + dividend: IntValue<'ctx>, + divisor: IntValue<'ctx>, + name: &str, +) -> Result, BuilderError> { + // Both 1 and -1 give remainder zero, but LLVM srem overflows for MIN % -1. + let ty = divisor.get_type(); + let negative_one = + builder.build_int_compare(IntPredicate::EQ, divisor, ty.const_all_ones(), "rem.neg_one")?; + let safe_divisor = + builder.build_select(negative_one, ty.const_int(1, false), divisor, "rem.divisor")?; + builder.build_int_signed_rem(dividend, safe_divisor.into_int_value(), name) +} + pub(crate) fn binary<'ctx>( context: &'ctx Context, module: &Module<'ctx>, @@ -214,7 +229,7 @@ pub(crate) fn binary<'ctx>( Operator::Remainder if operation_unsigned => { builder.build_int_unsigned_rem(l_casted, r_casted, "modtmp") }, - Operator::Remainder => builder.build_int_signed_rem(l_casted, r_casted, "modtmp"), + Operator::Remainder => signed_remainder(builder, l_casted, r_casted, "modtmp"), Operator::ShiftLeft => builder.build_left_shift(l_casted, r_casted, "shl"), Operator::ShiftRight => { let arithmetic = !operation_unsigned; diff --git a/llvm/src/codegen/ir.rs b/llvm/src/codegen/ir.rs index 5896df74..bc733141 100644 --- a/llvm/src/codegen/ir.rs +++ b/llvm/src/codegen/ir.rs @@ -923,7 +923,7 @@ fn build_module( } } - define_variant_types(context, &variant_definitions, &struct_types, td); + define_variant_types(context, &variant_definitions, &struct_types, td)?; codegen_trace("lower global initializers"); for ast in ast_nodes { @@ -1366,6 +1366,10 @@ fn build_module( build_wasi_start_wrapper(context, builder, module, abi_target)?; + if let Some(guard) = super::literal_storage::protect(context, module, td)? { + apply_function_codegen_attrs(context, guard, disable_red_zone, abi_target, cpu, features); + } + codegen_trace("verify module"); module .verify() diff --git a/llvm/src/codegen/literal_storage.rs b/llvm/src/codegen/literal_storage.rs new file mode 100644 index 00000000..affb551e --- /dev/null +++ b/llvm/src/codegen/literal_storage.rs @@ -0,0 +1,143 @@ +// SPDX-License-Identifier: MPL-2.0 +//! Keep the raw str/pointer ABI while checking writes whose backing storage is +//! known only at runtime. All Wave imports are lowered into the same module. +use inkwell::{ + builder::BuilderError, + context::Context, + intrinsics::Intrinsic, + module::{Linkage, Module}, + targets::TargetData, + values::{BasicValue, FunctionValue, InstructionOpcode, PointerValue}, + AddressSpace, IntPredicate, +}; +use std::collections::HashSet; + +// This temporary classification never reaches an object file. +const LITERAL_SECTION: &str = "wave.literal.pending"; + +pub(crate) fn literal<'ctx>( + context: &'ctx Context, + module: &Module<'ctx>, + bytes: &[u8], +) -> PointerValue<'ctx> { + let value = context.const_string(bytes, true); + let global = module.add_global(value.get_type(), None, "$wave.string"); + global.set_initializer(&value); + global.set_constant(true); + global.set_linkage(Linkage::Private); + global.set_section(Some(LITERAL_SECTION)); + global.as_pointer_value() +} + +fn known_writable<'ctx>( + mut address: PointerValue<'ctx>, + globals: &HashSet>, +) -> bool { + while let Some(instruction) = address.as_instruction_value() { + match instruction.get_opcode() { + InstructionOpcode::Alloca => return true, + InstructionOpcode::GetElementPtr | InstructionOpcode::BitCast => { + address = instruction.get_operand(0).unwrap().unwrap_value().into_pointer_value(); + }, + _ => return false, + } + } + globals.contains(&address) +} + +pub(super) fn protect<'ctx>( + context: &'ctx Context, + module: &Module<'ctx>, + target: &TargetData, +) -> Result>, BuilderError> { + let literals: Vec<_> = module + .get_globals() + .filter(|global| { + global.get_section().is_some_and(|s| s.to_bytes() == LITERAL_SECTION.as_bytes()) + }) + .collect(); + if literals.is_empty() { + return Ok(None); + } + let writable = module + .get_globals() + .filter(|global| !global.is_constant()) + .map(|global| global.as_pointer_value()) + .collect(); + let mut writes = Vec::new(); + for instruction in + module.get_functions().flat_map(|f| f.get_basic_blocks()).flat_map(|b| b.get_instructions()) + { + if instruction.get_opcode() == InstructionOpcode::Store { + let address = instruction.get_operand(1).unwrap().unwrap_value().into_pointer_value(); + let size = target + .get_store_size(&instruction.get_operand(0).unwrap().unwrap_value().get_type()); + if size != 0 && !known_writable(address, &writable) { + writes.push((instruction, size)); + } + } + } + if writes.is_empty() { + for global in literals { + global.set_section(None); + } + return Ok(None); + } + + // A packed pool preserves distinct addresses, embedded NULs and the final + // terminator of each literal. One range check covers any interior alias. + let initializers: Vec<_> = literals.iter().map(|g| g.get_initializer().unwrap()).collect(); + let value = context.const_struct(&initializers, true); + let pool = module.add_global(value.get_type(), None, "$wave.literal.storage"); + pool.set_initializer(&value); + pool.set_constant(true); + pool.set_linkage(Linkage::Private); + let index_type = context.i32_type(); + for (index, global) in literals.into_iter().enumerate() { + // SAFETY: each index selects its corresponding field in the packed initializer. + let field = unsafe { + pool.as_pointer_value().const_in_bounds_gep( + value.get_type(), + &[index_type.const_zero(), index_type.const_int(index as u64, false)], + ) + }; + global.as_pointer_value().replace_all_uses_with(field); + // SAFETY: all uses now reference the pool and code generation for user functions is complete. + unsafe { global.delete() }; + } + let word = context.ptr_sized_int_type(target, None); + let pointer = context.ptr_type(AddressSpace::default()); + let signature = context.void_type().fn_type(&[pointer.into(), word.into()], false); + let guard = module.add_function("$wave.check.literal.write", signature, Some(Linkage::Private)); + let builder = context.create_builder(); + builder.position_at_end(context.append_basic_block(guard, "entry")); + let base = pool.as_pointer_value().const_to_int(word); + let dest = builder.build_ptr_to_int( + guard.get_first_param().unwrap().into_pointer_value(), + word, + "dest", + )?; + let size = guard.get_nth_param(1).unwrap().into_int_value(); + let length = word.const_int(target.get_store_size(&value.get_type()), false); + let from_base = builder.build_int_sub(dest, base, "from.base")?; + let inside = builder.build_int_compare(IntPredicate::ULT, from_base, length, "inside")?; + let to_base = builder.build_int_sub(base, dest, "to.base")?; + let crosses = builder.build_int_compare(IntPredicate::ULT, to_base, size, "crosses")?; + let overlap = builder.build_or(inside, crosses, "overlap")?; + let fail = context.append_basic_block(guard, "literal.write"); + let ok = context.append_basic_block(guard, "writable"); + builder.build_conditional_branch(overlap, fail, ok)?; + builder.position_at_end(fail); + let trap = Intrinsic::find("llvm.trap").unwrap().get_declaration(module, &[]).unwrap(); + builder.build_call(trap, &[], "")?; + builder.build_unreachable()?; + builder.position_at_end(ok); + builder.build_return(None)?; + for (store, size) in writes { + // Read the operand after replacing literal globals above. + let address = store.get_operand(1).unwrap().unwrap_value(); + builder.position_before(&store); + builder.build_call(guard, &[address.into(), word.const_int(size, false).into()], "")?; + } + Ok(Some(guard)) +} diff --git a/llvm/src/codegen/mod.rs b/llvm/src/codegen/mod.rs index 82885ea4..ddca84f5 100644 --- a/llvm/src/codegen/mod.rs +++ b/llvm/src/codegen/mod.rs @@ -42,3 +42,4 @@ mod validation; pub(crate) mod conversions; mod arithmetic_runtime; +pub(crate) mod literal_storage; diff --git a/llvm/src/codegen/variants.rs b/llvm/src/codegen/variants.rs index 075662dc..6631a32b 100644 --- a/llvm/src/codegen/variants.rs +++ b/llvm/src/codegen/variants.rs @@ -19,6 +19,7 @@ //! selected case; projections reinterpret field 2 using that case's tuple type. use super::types::{wave_type_to_llvm_type, TypeFlavor}; +use crate::diagnostic::{CodegenError, CodegenErrorKind, CodegenPhase}; use hir::{HirExpressionType, TypedProgram}; use inkwell::context::Context; use inkwell::targets::TargetData; @@ -28,16 +29,17 @@ use parser::types::{parse_type, split_top_level_generic_args, token_type_to_wave use std::collections::{BTreeMap, BTreeSet, HashMap}; #[derive(Debug)] -pub(crate) struct VariantDefinition { +pub(crate) struct VariantDefinition<'ast> { + declaration: &'ast VariantNode, pub name: String, pub cases: Vec>, } -pub(crate) fn declare_variant_types<'ctx>( +pub(crate) fn declare_variant_types<'ctx, 'ast>( context: &'ctx Context, - program: &TypedProgram, + program: &'ast TypedProgram, struct_types: &mut HashMap>, -) -> Vec { +) -> Vec> { let templates = program .syntax() .iter() @@ -70,26 +72,26 @@ pub(crate) fn declare_variant_types<'ctx>( names.insert(variant.name.clone()); } - let mut definitions = BTreeMap::>>::new(); + let mut definitions = BTreeMap::new(); while let Some(name) = names.iter().find(|name| !definitions.contains_key(*name)).cloned() { - let cases = specialize_variant(&name, &templates); + let (declaration, cases) = specialize_variant(&name, &templates); for case in &cases { for payload in case { collect_type_variants(payload, &mut names); } } - definitions.insert(name, cases); + definitions.insert(name, (declaration, cases)); } let definitions = definitions .into_iter() - .map(|(name, cases)| { + .map(|(name, (declaration, cases))| { let llvm_name = format!("variant.{name}"); let ty = context.opaque_struct_type(&llvm_name); if struct_types.insert(name.clone(), ty).is_some() { panic!("variant type '{}' conflicts with another LLVM aggregate", name); } - VariantDefinition { name, cases } + VariantDefinition { declaration, name, cases } }) .collect::>(); definitions @@ -109,57 +111,66 @@ pub(crate) fn payload_type<'ctx>( pub(crate) fn define_variant_types<'ctx>( context: &'ctx Context, - definitions: &[VariantDefinition], + definitions: &[VariantDefinition<'_>], struct_types: &HashMap>, target_data: &TargetData, -) { +) -> Result<(), CodegenError> { let mut pending = definitions.iter().collect::>(); while !pending.is_empty() { let before = pending.len(); - pending.retain(|definition| { + for definition in std::mem::take(&mut pending) { let payloads = definition .cases .iter() .map(|case| payload_type(context, case, struct_types)) .collect::>(); if payloads.iter().any(|ty| ty.size_of().is_none()) { - return true; + pending.push(definition); + continue; } let mut alignment_witness = context.i8_type().as_basic_type_enum(); let mut alignment = 1; let mut size = 0; - for payload in payloads { - size = size.max(target_data.get_abi_size(&payload)); + for (case, payload) in definition.declaration.cases.iter().zip(payloads) { + let bytes = target_data.get_abi_size(&payload); + let capacity = u32::try_from(bytes).map_err(|_| { + let mut diagnostic = CodegenError::new( + CodegenPhase::Validation, + "lay out variant payload", + format!("variant `{}::{}` needs {bytes} payload bytes on this target; the maximum is {}", definition.name, case.name, u32::MAX), + ).with_span(case.span.clone()); + diagnostic.kind = CodegenErrorKind::InvalidLayout; + diagnostic + })?; + size = size.max(capacity); let payload_alignment = target_data.get_abi_alignment(&payload); if payload_alignment > alignment { alignment = payload_alignment; alignment_witness = payload.as_basic_type_enum(); } } - let storage_size = - u32::try_from(size).expect("variant payload exceeds LLVM array capacity"); struct_types[&definition.name].set_body( &[ context.i32_type().into(), alignment_witness.array_type(0).into(), - context.i8_type().array_type(storage_size).into(), + context.i8_type().array_type(size).into(), ], false, ); - false - }); + } assert!(pending.len() < before, "validated variants contain an unsized value cycle"); } + Ok(()) } -fn specialize_variant( +fn specialize_variant<'ast>( concrete_name: &str, - templates: &HashMap, -) -> Vec> { + templates: &HashMap, +) -> (&'ast VariantNode, Vec>) { if let Some(concrete) = templates.get(concrete_name).filter(|variant| variant.generic_params.is_empty()) { - return concrete.cases.iter().map(|case| case.payload_types.clone()).collect(); + return (concrete, concrete.cases.iter().map(|case| case.payload_types.clone()).collect()); } let (base, arguments) = split_variant_application(concrete_name) .unwrap_or_else(|| (concrete_name.to_string(), Vec::new())); @@ -175,7 +186,7 @@ fn specialize_variant( } let substitutions = template.generic_params.iter().cloned().zip(arguments).collect::>(); - template + let cases = template .cases .iter() .map(|case| { @@ -184,7 +195,8 @@ fn specialize_variant( .map(|payload| resolve_payload_type(payload, &substitutions, templates)) .collect() }) - .collect() + .collect(); + (template, cases) } fn resolve_payload_type( diff --git a/llvm/src/diagnostic.rs b/llvm/src/diagnostic.rs index 9424778c..aea5f41d 100644 --- a/llvm/src/diagnostic.rs +++ b/llvm/src/diagnostic.rs @@ -31,6 +31,7 @@ impl fmt::Display for CodegenPhase { pub enum CodegenErrorKind { BackendFailure, InvalidAssembly, + InvalidLayout, MissingTool, } diff --git a/llvm/src/expression/rvalue/arrays.rs b/llvm/src/expression/rvalue/arrays.rs index c41506af..ba5f6190 100644 --- a/llvm/src/expression/rvalue/arrays.rs +++ b/llvm/src/expression/rvalue/arrays.rs @@ -43,7 +43,7 @@ Use a temp variable: `var tmp: array = [...]; foo(tmp);`" let elem_ty = arr_ty.get_element_type(); - let alloca = env.builder.build_alloca(arr_ty, "arr_lit").unwrap(); + let alloca = env.scratch_slot(arr_ty, "arr_lit"); let zero = env.context.i32_type().const_zero(); for (i, e) in elements.iter().enumerate() { diff --git a/llvm/src/expression/rvalue/assign.rs b/llvm/src/expression/rvalue/assign.rs index e0fa8b72..685c622b 100644 --- a/llvm/src/expression/rvalue/assign.rs +++ b/llvm/src/expression/rvalue/assign.rs @@ -18,6 +18,7 @@ //! compound assignments with side effects. use super::ExprGenEnv; +use crate::codegen::conversions::signed_remainder; use crate::codegen::types::TypeFlavor; use crate::codegen::{generate_address_ir, wave_type_to_llvm_type}; use crate::statement::variable::{coerce_basic_value, wave_type_is_unsigned, CoercionMode}; @@ -369,11 +370,9 @@ pub(crate) fn gen_assign_operation<'ctx, 'a>( .build_int_unsigned_rem(lhs, rhs, "rem_assign") .unwrap() .as_basic_value_enum(), - AssignOperator::RemAssign => env - .builder - .build_int_signed_rem(lhs, rhs, "rem_assign") - .unwrap() - .as_basic_value_enum(), + AssignOperator::RemAssign => { + signed_remainder(env.builder, lhs, rhs, "rem_assign").unwrap().as_basic_value_enum() + }, AssignOperator::Assign => unreachable!(), }, diff --git a/llvm/src/expression/rvalue/calls.rs b/llvm/src/expression/rvalue/calls.rs index 2d2e0ba8..2abb108e 100644 --- a/llvm/src/expression/rvalue/calls.rs +++ b/llvm/src/expression/rvalue/calls.rs @@ -79,10 +79,10 @@ fn pack_agg_to_int<'ctx, 'a>( ) -> BasicValueEnum<'ctx> { let agg_ty = agg.get_type(); - let agg_tmp = env.builder.build_alloca(agg_ty, &format!("{}_agg_tmp", tag)).unwrap(); + let agg_tmp = env.scratch_slot(agg_ty, &format!("{}_agg_tmp", tag)); env.builder.build_store(agg_tmp, agg).unwrap(); - let int_tmp = env.builder.build_alloca(dst, &format!("{}_int_tmp", tag)).unwrap(); + let int_tmp = env.scratch_slot(dst, &format!("{}_int_tmp", tag)); // The ABI transport slot may be wider than the aggregate object (for // example a 3-byte RV64 aggregate transported in i64). Keep padding bits @@ -103,8 +103,8 @@ fn unpack_int_to_agg<'ctx, 'a>( dst_agg_ty: BasicTypeEnum<'ctx>, tag: &str, ) -> BasicValueEnum<'ctx> { - let agg_tmp = env.builder.build_alloca(dst_agg_ty, &format!("{}_agg_tmp", tag)).unwrap(); - let int_tmp = env.builder.build_alloca(iv.get_type(), &format!("{}_int_tmp", tag)).unwrap(); + let agg_tmp = env.scratch_slot(dst_agg_ty, &format!("{}_agg_tmp", tag)); + let int_tmp = env.scratch_slot(iv.get_type(), &format!("{}_int_tmp", tag)); env.builder.build_store(int_tmp, iv).unwrap(); @@ -316,7 +316,7 @@ fn gen_extern_call<'ctx, 'a>( let mut sret_tmp: Option> = None; if let RetLowering::SRet { ty, .. } = &info.ret { let agg = any_agg_to_basic(*ty); - let tmp = env.builder.build_alloca(agg, &format!("{}_sret_tmp", name)).unwrap(); + let tmp = env.scratch_slot(agg, &format!("{}_sret_tmp", name)); let expected_ptr = meta_into_ptr(llvm_param_types[0]); let tmp2 = coerce_ptr_to(env, tmp, expected_ptr, &format!("{}_sret_ptrcast", name)); @@ -343,8 +343,7 @@ fn gen_extern_call<'ctx, 'a>( ParamLowering::Indirect { ty } | ParamLowering::ByVal { ty, .. } => { let agg = any_agg_to_basic(*ty); let v = env.gen(arg_expr, Some(agg)); - let tmp = - env.builder.build_alloca(agg, &format!("{}_byval_tmp_{}", name, i)).unwrap(); + let tmp = env.scratch_slot(agg, &format!("{}_byval_tmp_{}", name, i)); // Windows x64 passes odd-sized aggregates through a caller // temporary aligned to at least 16 bytes, without byval. if matches!( @@ -524,8 +523,7 @@ fn coerce_to_expected<'ctx, 'a>( got_agg @ (BasicTypeEnum::StructType(_) | BasicTypeEnum::ArrayType(_)), BasicTypeEnum::PointerType(dst), ) => { - let source = - env.builder.build_alloca(got_agg, &format!("arg{}_ptr_agg", arg_index)).unwrap(); + let source = env.scratch_slot(got_agg, &format!("arg{}_ptr_agg", arg_index)); env.builder.build_store(source, val).unwrap(); env.builder .build_load(dst, source, &format!("arg{}_ptr_transport", arg_index)) @@ -578,13 +576,9 @@ fn coerce_to_expected<'ctx, 'a>( ); } - let source = - env.builder.build_alloca(got_agg, &format!("arg{}_agg_source", arg_index)).unwrap(); + let source = env.scratch_slot(got_agg, &format!("arg{}_agg_source", arg_index)); env.builder.build_store(source, val).unwrap(); - let transport = env - .builder - .build_alloca(dst_agg, &format!("arg{}_agg_transport", arg_index)) - .unwrap(); + let transport = env.scratch_slot(dst_agg, &format!("arg{}_agg_transport", arg_index)); env.builder.build_store(transport, dst_agg.const_zero()).unwrap(); let bytes = env.context.i64_type().const_int(got_size, false); env.builder @@ -617,8 +611,7 @@ fn coerce_to_expected<'ctx, 'a>( ); } - let tmp = - env.builder.build_alloca(got_agg, &format!("arg{}_agg_tmp", arg_index)).unwrap(); + let tmp = env.scratch_slot(got_agg, &format!("arg{}_agg_tmp", arg_index)); env.builder.build_store(tmp, val).unwrap(); env.builder @@ -641,8 +634,7 @@ fn coerce_to_expected<'ctx, 'a>( ); } - let tmp = - env.builder.build_alloca(dst_agg, &format!("arg{}_v2agg_tmp", arg_index)).unwrap(); + let tmp = env.scratch_slot(dst_agg, &format!("arg{}_v2agg_tmp", arg_index)); env.builder.build_store(tmp, val).unwrap(); @@ -727,10 +719,10 @@ fn split_agg_parts_from_agg<'ctx, 'a>( let aggregate_type = agg_val.get_type(); let aggregate_size = env.target_data.get_store_size(&aggregate_type); let staging_type = env.context.i8_type().array_type(total_bytes as u32); - let staging = env.builder.build_alloca(staging_type, &format!("{tag}_staging")).unwrap(); + let staging = env.scratch_slot(staging_type, &format!("{tag}_staging")); env.builder.build_store(staging, staging_type.const_zero()).unwrap(); - let aggregate = env.builder.build_alloca(aggregate_type, &format!("{tag}_aggregate")).unwrap(); + let aggregate = env.scratch_slot(aggregate_type, &format!("{tag}_aggregate")); env.builder.build_store(aggregate, agg_val).unwrap(); env.builder .build_memcpy( @@ -745,7 +737,7 @@ fn split_agg_parts_from_agg<'ctx, 'a>( let mut offset: u64 = 0; for (pi, part_ty) in parts.iter().enumerate() { let part_size = env.target_data.get_store_size(part_ty) as u64; - let dst = env.builder.build_alloca(*part_ty, &format!("{tag}_part_dst_{pi}")).unwrap(); + let dst = env.scratch_slot(*part_ty, &format!("{tag}_part_dst_{pi}")); let off = env.context.i64_type().const_int(offset, false); let src_off = unsafe { @@ -777,7 +769,7 @@ fn coerce_and_expand_agg_parts<'ctx, 'a>( ) -> Vec> { let aggregate_type = aggregate.get_type(); let aggregate_size = env.target_data.get_store_size(&aggregate_type); - let source = env.builder.build_alloca(aggregate_type, &format!("{tag}_aggregate")).unwrap(); + let source = env.scratch_slot(aggregate_type, &format!("{tag}_aggregate")); env.builder.build_store(source, aggregate).unwrap(); parts @@ -789,8 +781,7 @@ fn coerce_and_expand_agg_parts<'ctx, 'a>( part.offset + size <= aggregate_size, "LoongArch ABI part extends past its aggregate" ); - let destination = - env.builder.build_alloca(part.ty, &format!("{tag}_part_{index}")).unwrap(); + let destination = env.scratch_slot(part.ty, &format!("{tag}_part_{index}")); let offset = env.context.i64_type().const_int(part.offset, false); // SAFETY: classification derives every offset from the target data // layout and verifies the complete part remains in the allocation. @@ -836,8 +827,7 @@ fn coerce_lowered_ret_to_expected<'ctx, 'a>( BasicTypeEnum::PointerType(_), BasicTypeEnum::StructType(_) | BasicTypeEnum::ArrayType(_), ) => { - let destination = - env.builder.build_alloca(expected, &format!("{tag}_ptr_agg")).unwrap(); + let destination = env.scratch_slot(expected, &format!("{tag}_ptr_agg")); env.builder.build_store(destination, lowered_ret).unwrap(); env.builder .build_load(expected, destination, &format!("{tag}_ptr_agg_load")) @@ -854,7 +844,7 @@ fn coerce_lowered_ret_to_expected<'ctx, 'a>( BasicTypeEnum::VectorType(_vt), BasicTypeEnum::StructType(_) | BasicTypeEnum::ArrayType(_), ) => { - let tmp = env.builder.build_alloca(expected, &format!("{tag}_v2agg_tmp")).unwrap(); + let tmp = env.scratch_slot(expected, &format!("{tag}_v2agg_tmp")); env.builder.build_store(tmp, lowered_ret).unwrap(); env.builder .build_load(expected, tmp, &format!("{tag}_v2agg_load")) @@ -866,7 +856,7 @@ fn coerce_lowered_ret_to_expected<'ctx, 'a>( BasicTypeEnum::FloatType(_ft), BasicTypeEnum::StructType(_) | BasicTypeEnum::ArrayType(_), ) => { - let tmp = env.builder.build_alloca(expected, &format!("{tag}_f2agg_tmp")).unwrap(); + let tmp = env.scratch_slot(expected, &format!("{tag}_f2agg_tmp")); env.builder.build_store(tmp, lowered_ret).unwrap(); env.builder .build_load(expected, tmp, &format!("{tag}_f2agg_load")) @@ -887,10 +877,10 @@ fn coerce_lowered_ret_to_expected<'ctx, 'a>( return lowered_ret; } - let src = env.builder.build_alloca(got, &format!("{tag}_agg_src")).unwrap(); + let src = env.scratch_slot(got, &format!("{tag}_agg_src")); env.builder.build_store(src, lowered_ret).unwrap(); - let dst = env.builder.build_alloca(expected, &format!("{tag}_agg_dst")).unwrap(); + let dst = env.scratch_slot(expected, &format!("{tag}_agg_dst")); let bytes = env.context.i64_type().const_int(exp_sz as u64, false); env.builder.build_memcpy(dst, 1, src, 1, bytes).unwrap(); diff --git a/llvm/src/expression/rvalue/const_projection.rs b/llvm/src/expression/rvalue/const_projection.rs index ffdd5578..f66e657b 100644 --- a/llvm/src/expression/rvalue/const_projection.rs +++ b/llvm/src/expression/rvalue/const_projection.rs @@ -146,7 +146,7 @@ pub(crate) fn try_gen_index_access<'ctx, 'a>( // LLVM extractvalue requires a fixed immediate index. Keep dynamic // indexing value-only by materializing an internal temporary whose // address is never entered in the Wave variable environment. - let storage = env.builder.build_alloca(array_type, "const.array.storage").unwrap(); + let storage = env.scratch_slot(array_type, "const.array.storage"); env.builder.build_store(storage, array).unwrap(); let zero = env.context.i32_type().const_zero(); let element_pointer = unsafe { diff --git a/llvm/src/expression/rvalue/literals.rs b/llvm/src/expression/rvalue/literals.rs index 967785c5..b34f493c 100644 --- a/llvm/src/expression/rvalue/literals.rs +++ b/llvm/src/expression/rvalue/literals.rs @@ -122,29 +122,8 @@ pub(crate) fn gen<'ctx, 'a>( _ => panic!("Unsupported expected_type for float"), }, - Literal::String(value) => { - let bytes = value.as_slice(); - let mut null_terminated = bytes.to_vec(); - null_terminated.push(0); - - let global_name = "str_lit"; - - let str_type = env.context.i8_type().array_type(null_terminated.len() as u32); - - let global = env.module.add_global(str_type, None, global_name); - global.set_initializer(&env.context.const_string(&null_terminated, false)); - global.set_constant(true); - - let zero = env.context.i32_type().const_zero(); - let indices = [zero, zero]; - - let gep = unsafe { - env.builder - .build_in_bounds_gep(str_type, global.as_pointer_value(), &indices, "str_gep") - .unwrap() - }; - - gep.as_basic_value_enum() + Literal::String(bytes) => { + crate::codegen::literal_storage::literal(env.context, env.module, bytes).into() }, Literal::Bool(v) => { diff --git a/llvm/src/expression/rvalue/mod.rs b/llvm/src/expression/rvalue/mod.rs index eac0a67d..e53a02ac 100644 --- a/llvm/src/expression/rvalue/mod.rs +++ b/llvm/src/expression/rvalue/mod.rs @@ -24,8 +24,8 @@ use inkwell::builder::Builder; use inkwell::context::Context; use inkwell::module::Module; use inkwell::targets::TargetData; -use inkwell::types::{BasicTypeEnum, StructType}; -use inkwell::values::BasicValueEnum; +use inkwell::types::{BasicType, BasicTypeEnum, StructType}; +use inkwell::values::{BasicValueEnum, PointerValue}; use parser::ast::{Expression, WaveType}; use std::collections::HashMap; @@ -68,6 +68,17 @@ pub(crate) struct ExprGenEnv<'ctx, 'a> { } impl<'ctx, 'a> ExprGenEnv<'ctx, 'a> { + /// A fixed slot per call site and stack frame for private value transport. + /// Wave expressions that expose their temporary's address must allocate separately. + fn scratch_slot(&self, ty: impl BasicType<'ctx>, name: &str) -> PointerValue<'ctx> { + crate::statement::variable::build_entry_alloca( + self.context, + self.builder, + ty.as_basic_type_enum(), + name, + ) + } + #[inline] pub fn gen( &mut self, diff --git a/llvm/src/expression/rvalue/structs.rs b/llvm/src/expression/rvalue/structs.rs index 21398865..b14728a3 100644 --- a/llvm/src/expression/rvalue/structs.rs +++ b/llvm/src/expression/rvalue/structs.rs @@ -18,8 +18,8 @@ use super::ExprGenEnv; use crate::statement::variable::{coerce_basic_value, wave_type_is_unsigned, CoercionMode}; -use inkwell::types::{BasicType, BasicTypeEnum}; -use inkwell::values::{BasicValue, BasicValueEnum}; +use inkwell::types::BasicTypeEnum; +use inkwell::values::BasicValueEnum; use parser::ast::{Expression, WaveType}; pub(crate) fn gen_struct_literal<'ctx, 'a>( @@ -35,7 +35,7 @@ pub(crate) fn gen_struct_literal<'ctx, 'a>( .get(name) .unwrap_or_else(|| panic!("Field index map for struct '{}' not found", name)); - let tmp_alloca = env.builder.build_alloca(struct_ty, &format!("tmp_{}_literal", name)).unwrap(); + let mut literal = struct_ty.get_undef(); for (field_name, field_expr) in fields { let idx = *field_indices @@ -57,18 +57,14 @@ pub(crate) fn gen_struct_literal<'ctx, 'a>( wave_type_is_unsigned(env.wave_type(field_expr).as_ref()), ); - let field_ptr = env + literal = env .builder - .build_struct_gep(struct_ty, tmp_alloca, idx, &format!("{}.{}", name, field_name)) - .unwrap(); - - env.builder.build_store(field_ptr, field_val).unwrap(); + .build_insert_value(literal, field_val, idx, field_name) + .unwrap() + .into_struct_value(); } - env.builder - .build_load(struct_ty.as_basic_type_enum(), tmp_alloca, &format!("{}_literal_val", name)) - .unwrap() - .as_basic_value_enum() + literal.into() } pub(crate) fn gen_field_access<'ctx, 'a>( diff --git a/llvm/src/expression/rvalue/variants.rs b/llvm/src/expression/rvalue/variants.rs index f7efe299..94436080 100644 --- a/llvm/src/expression/rvalue/variants.rs +++ b/llvm/src/expression/rvalue/variants.rs @@ -34,8 +34,7 @@ pub(crate) fn gen_constructor<'ctx, 'a>( }; let variant_ty = *env.struct_types.get(name).unwrap_or_else(|| panic!("variant type '{}' not found", name)); - let value_ptr = - env.builder.build_alloca(variant_ty, &format!("variant.{}.value", name)).unwrap(); + let value_ptr = env.scratch_slot(variant_ty, &format!("variant.{}.value", name)); env.builder.build_store(value_ptr, variant_ty.const_zero()).unwrap(); let tag_ptr = @@ -58,7 +57,7 @@ pub(crate) fn gen_constructor<'ctx, 'a>( name, construction.case_name ); } - let payload_ptr = env.builder.build_alloca(payload_ty, "variant.payload.value").unwrap(); + let payload_ptr = env.scratch_slot(payload_ty, "variant.payload.value"); env.builder.build_store(payload_ptr, payload_ty.const_zero()).unwrap(); for (index, (argument, payload_wave_type)) in diff --git a/src/runner.rs b/src/runner.rs index 38e2e48f..fa1fa304 100644 --- a/src/runner.rs +++ b/src/runner.rs @@ -267,10 +267,10 @@ fn emit_backend_error_and_exit( 0, 0, ) - .with_code(if error.kind == llvm::diagnostic::CodegenErrorKind::InvalidAssembly { - "E3401" - } else { - "E9002" + .with_code(match error.kind { + llvm::diagnostic::CodegenErrorKind::InvalidAssembly => "E3401", + llvm::diagnostic::CodegenErrorKind::InvalidLayout => "E3001", + _ => "E9002", }) .with_context(format!("compiler phase: {}", error.phase)); if let Some(span) = error.span { diff --git a/tests/cases/shared/test143.wave b/tests/cases/shared/test143.wave new file mode 100644 index 00000000..59811185 --- /dev/null +++ b/tests/cases/shared/test143.wave @@ -0,0 +1,44 @@ +// wave-test: runtime=portable +// wave-test: mode=run +// Signed remainder is zero for every dividend when the divisor is -1. +static calls: i32 = 0; + +fun divisor() -> i32 { + calls += 1; + return -1; +} + +fun index() -> i32 { + calls = calls * 10 + 3; + return 0; +} + +fun wide(value: i128, by: i128) -> i128 { + return value % by; +} + +fun main() -> i32 { + var a: i8 = -128; + var b: i16 = -32768; + var c: i32 = -2147483648; + var d: i64 = -9223372036854775808; + var e: i128 = -170141183460469231731687303715884105728; + a %= -1; + b %= -1; + d %= -1; + if (a != 0 || b != 0 || c % divisor() != 0 || calls != 1 || d != 0) { + return 1; + } + if (wide(e, -1) != 0 || wide(-17, 5) != -2 || wide(17, -5) != 2) { + return 2; + } + if (-2147483648 % -1 != 0) { + return 3; + } + var slots: array = [c]; + slots[index()] %= divisor(); + if (slots[0] != 0 || calls != 14) { + return 4; + } + return 0; +} diff --git a/tests/codegen/language.rs b/tests/codegen/language.rs index ec968fac..85337b19 100644 --- a/tests/codegen/language.rs +++ b/tests/codegen/language.rs @@ -3,6 +3,133 @@ //! These tests share the parent integration suite's fixtures and target gates. use super::*; +#[test] +fn signed_remainder_boundaries_execute_at_o0_and_o2() { + run_shared_case_at_both_optimization_levels("test143"); +} + +#[test] +fn aggregate_loop_reuses_value_storage_but_keeps_addressed_literals_distinct() { + let dir = temp_case_dir("aggregate-loop-storage"); + let source = write_wave( + &dir, + "loop.wave", + r#" + struct Record { x: i64; y: array; } + fun main() -> i32 { + var i: i32 = 0; + var sum: i64 = 0; + while (i < 500000) { + var record: Record = Record { x: i, y: [i, i + 1] }; + sum += record.y[1] - record.x; + i += 1; + } + if (sum != 500000) { return 1; } + var first: ptr> = null; + var j: i32 = 0; + while (j < 2) { + var current: ptr> = &[j]; + if (j == 0) { first = current; } + if (j == 1 && (first[0] != 0 || current[0] != 1)) { return 2; } + j += 1; + } + return 0; + } + "#, + ); + for optimization in ["-O0", "-O2"] { + run_wavec([ + OsStr::new("build"), + source.as_os_str(), + OsStr::new(optimization), + OsStr::new(if native_target_enabled() { "--run" } else { "--emit=ir,obj" }), + OsStr::new("--out-dir"), + dir.join(optimization).as_os_str(), + ]); + } +} + +#[test] +fn literal_backed_string_writes_have_source_diagnostics_and_mutable_views_remain_writable() { + let dir = temp_case_dir("literal-write"); + for operation in [ + "s[1] = 65;", + "var alias: str = s; alias[1] += 1;", + "var p: ptr = s as ptr; (deref p)++;", + "var p: ptr = &s[1]; deref p = 65;", + "input(\"{}\", s[1]);", + ] { + let source = write_wave( + &dir, + "direct.wave", + &format!("fun main() {{ var s: str = \"abc\"; {operation} }}"), + ); + let error = run_wavec_expect_failure([OsStr::new("check"), source.as_os_str()]); + assert!( + error.contains("cannot write to read-only string literal storage"), + "{operation}: {error}" + ); + assert!(error.contains("direct.wave:1:"), "{error}"); + } + + // The mutable and literal calls pass exactly the same raw pointer ABI. + let common = r#" + const TEXT: str = "abc"; + fun identity(s: str) -> str { return s; } + fun write(s: str) { s[1] = 77; } + "#; + let mutable = write_wave( + &dir, + "mutable.wave", + &format!( + r#"{common} + fun main() -> i32 {{ + var b: array = [65, 66, 0]; + var s: str = TEXT; + if (s[0] != 97) {{ return 1; }} + s = (&b[0]) as str; + write(identity(s)); + if (b[1] != 77) {{ return 2; }} + return 0; + }}"# + ), + ); + let literal = write_wave( + &dir, + "literal.wave", + &format!("{common} fun main() {{ write(identity(TEXT)); }}"), + ); + for opt in ["-O0", "-O2"] { + let out = dir.join(opt); + for source in [&mutable, &literal] { + run_wavec([ + OsStr::new("build"), + source.as_os_str(), + OsStr::new(opt), + OsStr::new(if native_target_enabled() { "--emit=ir,bin" } else { "--emit=ir,obj" }), + OsStr::new("--out-dir"), + out.as_os_str(), + ]); + } + let ir = fs::read_to_string(out.join("literal.ll")).unwrap(); + assert!(ir.contains("call void @llvm.trap()"), "{ir}"); + if native_target_enabled() { + let run = |stem: &str| { + Command::new(out.join(format!("{stem}{}", std::env::consts::EXE_SUFFIX))) + .current_dir(&out) + .output() + .unwrap() + .status + }; + assert!(run("mutable").success()); + let status = run("literal"); + assert!(!status.success()); + #[cfg(all(target_os = "linux", any(target_arch = "x86_64", target_arch = "x86")))] + assert_eq!(std::os::unix::process::ExitStatusExt::signal(&status), Some(4)); + } + } +} + #[test] fn typed_pointer_expression_strides_execute_at_o0_and_o2() { let ir = run_shared_case_at_both_optimization_levels("test120"); diff --git a/tests/frontend_regressions.rs b/tests/frontend_regressions.rs index 5ce77131..339a4a69 100644 --- a/tests/frontend_regressions.rs +++ b/tests/frontend_regressions.rs @@ -50,6 +50,55 @@ fn successful(output: &Output) { ); } +#[test] +fn runner_check_preserves_frontend_results_without_requesting_artifacts() { + let dir = directory(); + let source = dir.join("case.wave"); + let report = dir.join("report.json"); + let triple = frontend_target(); + let manifest = wave_tools::cases::Manifest::load(&wave_tools::root(), false).unwrap(); + let target = manifest.resolve(&triple).unwrap(); + for (body, pass) in [("return 0;", true), ("return missing;", false)] { + std::fs::write( + &source, + format!("// wave-test: mode=check\nfun main() -> i32 {{ {body} }}\n"), + ) + .unwrap(); + let result = wave_tools::build::test_command() + .unwrap() + .args(["test", "--wavec", env!("CARGO_BIN_EXE_wavec")]) + .args(["--target-id", &target.id, "--compile-only", "--source"]) + .arg(&source) + .arg("--report-json") + .arg(&report) + .output() + .unwrap(); + assert_eq!(result.status.success(), pass, "{}", String::from_utf8_lossy(&result.stderr)); + let report = wave_tools::config::read_json(&report).unwrap(); + let row = &report.get_arr("tests").unwrap()[0]; + assert_eq!(row.get_str("phase"), Some("check")); + let commands = row.get_arr("commands").unwrap(); + assert_eq!(commands.len(), 1); + let args: Vec<_> = commands[0] + .get_arr("command") + .unwrap() + .iter() + .map(|arg| match arg { + utils::wson::Value::String(s) => s.as_str(), + _ => panic!("expected a string argument"), + }) + .collect(); + assert!(args.windows(2).any(|pair| pair == ["--target", &triple])); + assert!(!args + .iter() + .any(|arg| matches!(*arg, "-o" | "--out-dir") || arg.starts_with("--emit"))); + if !pass { + assert!(row.get_str("stderr").unwrap().contains("undeclared identifier `missing`")); + } + } + std::fs::remove_dir_all(dir).unwrap(); +} + #[test] fn imported_variants_respect_active_and_inactive_target_attributes() { let dir = directory(); diff --git a/tests/payload_variant_targets.rs b/tests/payload_variant_targets.rs index 87320676..873e6045 100644 --- a/tests/payload_variant_targets.rs +++ b/tests/payload_variant_targets.rs @@ -67,3 +67,39 @@ fn payload_variants_emit_ir_and_objects_for_every_advertised_target() { } fs::remove_dir_all(directory).unwrap(); } + +#[test] +fn unused_variant_payload_capacity_has_a_source_diagnostic_and_preserves_output() { + let temporary = + std::env::temp_dir().join(format!("wave-payload-capacity-{}", std::process::id())); + fs::create_dir_all(&temporary).unwrap(); + let source = temporary.join("capacity.wave"); + let compiler = env!("CARGO_BIN_EXE_wavec"); + let target = llvm::codegen::target::supported_target_specs()[0].triple; + let build = || { + Command::new(compiler) + .arg("build") + .arg(&source) + .args(["--target", target, "--emit=ir", "--error-format=json", "--out-dir"]) + .arg(&temporary) + .output() + .unwrap() + }; + let ir = temporary.join("capacity.ll"); + fs::write(&source, "variant V {\n Fits(array)\n}\nfun main() {}").unwrap(); + let accepted = build(); + assert!(accepted.status.success(), "{}", String::from_utf8_lossy(&accepted.stderr)); + let original = fs::read(&ir).unwrap(); + fs::write(&source, "variant V {\n Excess(array)\n}\nfun main() {}").unwrap(); + let rejected = build(); + assert!(!rejected.status.success()); + let text = String::from_utf8(rejected.stderr).unwrap(); + let json = utils::wson::parse_json(&text).unwrap(); + let error = json.get("error").unwrap(); + assert_eq!(error.get_str("code"), Some("E3001"), "{text}"); + assert!(error.get_str("message").unwrap().contains("V::Excess"), "{text}"); + assert!(text.contains("4294967296") && text.contains("4294967295"), "{text}"); + assert_eq!(error.get_u64("line"), Some(2), "{text}"); + assert_eq!(fs::read(ir).unwrap(), original); + fs::remove_dir_all(temporary).unwrap(); +} diff --git a/tests/wasi_provider_errors.rs b/tests/wasi_provider_errors.rs index e55249f1..b26c9857 100644 --- a/tests/wasi_provider_errors.rs +++ b/tests/wasi_provider_errors.rs @@ -51,6 +51,61 @@ fn available(tool: &str) -> bool { Command::new(tool).arg("--version").output().is_ok_and(|output| output.status.success()) } +#[test] +fn wasi_case_runner_delivers_stdin_and_compares_the_program_exit() { + if llvm::codegen::target::target_spec_for_triple("wasm32-wasip1").is_none() + || !available("node") + || !available("wasm-ld") + { + return; + } + let case = Case::new(); + let source = case.0.join("input.wave"); + let report_path = case.0.join("report.json"); + for (stdin, actual) in [("A", 7), ("B", 2)] { + fs::write( + &source, + format!( + r#"// wave-test: expected-exit=7, stdin={stdin} +import("std::sys::fs")::{{read}}; +fun main() -> i32 {{ + var b: u8 = 0; + if (read(0, &b, 1) != 1 || b != 65) {{ return 2; }} + return 7; +}} +"# + ), + ) + .unwrap(); + let result = wave_tools::build::test_command() + .unwrap() + .args([ + "test", + "--wavec", + env!("CARGO_BIN_EXE_wavec"), + "--target-id", + "wasm-wasi", + "--source", + ]) + .arg(&source) + .arg("--report-json") + .arg(&report_path) + .output() + .unwrap(); + assert_eq!( + result.status.success(), + actual == 7, + "{}", + String::from_utf8_lossy(&result.stderr) + ); + let report = wave_tools::config::read_json(&report_path).unwrap(); + let row = &report.get_arr("tests").unwrap()[0]; + assert_eq!(row.get_str("phase"), Some("run")); + assert_eq!(row.get_u64("actual_exit"), Some(actual)); + assert_eq!(row.get_u64("expected_exit"), Some(7)); + } +} + #[test] fn wasi_provider_failures_keep_the_wasi_errno_domain() { let target = "wasm32-wasip1"; diff --git a/tools/Cargo.toml b/tools/Cargo.toml index 76b6ded5..a9f13b6d 100644 --- a/tools/Cargo.toml +++ b/tools/Cargo.toml @@ -14,13 +14,13 @@ regex-lite = "=0.1.9" base64 = "=0.22.1" getrandom = "=0.4.3" yaml-rust2 = { version = "=0.13.0", default-features = false } -time = { version = "=0.3.44", features = ["formatting", "parsing"] } +time = { version = "=0.3.47", features = ["formatting", "parsing"] } sha2 = "=0.10.9" object = { version = "=0.37.3", default-features = false, features = ["read", "std"] } tempfile = "=3.27.0" tar = { version = "=0.4.46", default-features = false } flate2 = { version = "=1.1.10", default-features = false, features = ["rust_backend"] } -zip = { version = "=8.6.0", default-features = false, features = ["deflate-flate2"] } +zip = { version = "=9.4.2", default-features = false, features = ["deflate-flate2"] } [target.'cfg(unix)'.dependencies] nix = { version = "=0.31.3", default-features = false, features = ["signal", "process", "fs", "resource", "term", "user"] } diff --git a/tools/src/binary.rs b/tools/src/binary.rs index 2d1d47a6..01b6537a 100644 --- a/tools/src/binary.rs +++ b/tools/src/binary.rs @@ -12,10 +12,21 @@ pub struct Info { pub bits: u32, pub flags: u32, pub needed: BTreeSet, - pub rpaths: BTreeSet, + pub rpaths: Vec, + pub runpaths: Vec, pub interpreter: Option, } +impl Info { + pub fn runtime_paths(&self) -> &[String] { + if self.runpaths.is_empty() { + &self.rpaths + } else { + &self.runpaths + } + } +} + fn arch(architecture: object::Architecture) -> String { match architecture { object::Architecture::X86_64 => "x86_64", @@ -155,8 +166,10 @@ fn elf(bytes: &[u8], info: &mut Info, little: bool) -> Result<()> { if tag == 1 { info.needed.insert(string(strings, value)?); } - if tag == 15 || tag == 29 { + if tag == 15 { info.rpaths.extend(string(strings, value)?.split(':').map(String::from)); + } else if tag == 29 { + info.runpaths.extend(string(strings, value)?.split(':').map(String::from)); } } Ok(()) @@ -203,6 +216,23 @@ fn pe(bytes: &[u8], info: &mut Info) -> Result<()> { }) .ok_or_else(|| error("PE RVA outside file-backed sections")) }; + // Forwarders live in the export address table, including ordinal-only slots. + // Ordinary exports point at code or data and add no dependency. + if let Some(exports) = object::read::pe::PeFile64::parse(bytes)?.export_table()? { + use object::read::pe::ExportTarget; + for index in 0..exports.addresses().len() { + let library = match exports.target_by_index(u32::try_from(index)?)? { + ExportTarget::ForwardByName(name, _) | ExportTarget::ForwardByOrdinal(name, _) => { + std::str::from_utf8(name)? + }, + ExportTarget::Address(_) => continue, + }; + if library.is_empty() || library.contains(['/', '\\', ':']) { + return Err(error("invalid forwarded DLL name")); + } + info.needed.insert(format!("{library}.dll")); + } + } for index in [1u64, 13] { if directories <= index { continue; @@ -265,7 +295,7 @@ fn macho(bytes: &[u8], info: &mut Info, little: bool) -> Result<()> { info.needed.insert(string(data, integer(data, 8, 4, little)?)?); } if command == 0x8000001c { - info.rpaths.insert(string(data, integer(data, 8, 4, little)?)?); + info.rpaths.push(string(data, integer(data, 8, 4, little)?)?); } offset += size; } diff --git a/tools/src/build.rs b/tools/src/build.rs index 46c52d30..6d084a97 100644 --- a/tools/src/build.rs +++ b/tools/src/build.rs @@ -145,14 +145,12 @@ pub fn clean(arguments: &[OsString]) -> Result { pub fn clean_outputs(root: &Path, selected: &Path, dist: &Path) -> Result<()> { let owner = fs::canonicalize(root)?; - let default = storage::resolved(&root.join("target"))?; let location = |path: &Path| -> Result { let name = path.file_name().ok_or_else(|| error("cleanup requires a named output directory"))?; Ok(storage::resolved(path.parent().unwrap_or(Path::new(".")))?.join(name)) }; let selected_location = location(selected)?; - let selected_path = storage::resolved(selected)?; // Validate every destination before removing anything. Resolve parents but // not the final directory link: cleanup unlinks that link, never its target. if selected_location == owner || owner.starts_with(&selected_location) { @@ -161,11 +159,11 @@ pub fn clean_outputs(root: &Path, selected: &Path, dist: &Path) -> Result<()> { if location(dist)? != owner.join("dist") { return Err(error("refusing to delete an unowned custom distribution directory")); } - if storage::exists(selected) - && !fs::symlink_metadata(selected)?.is_symlink() - && selected_path != default + if storage::exists(&selected_location) + && !fs::symlink_metadata(&selected_location)?.is_symlink() + && selected_location != owner.join("target") { - let marker = selected.join(".wave-cargo-owner"); + let marker = selected_location.join(".wave-cargo-owner"); if fs::read_to_string(marker).unwrap_or_default().trim() != owner.to_string_lossy() { return Err(error("refusing to delete unowned custom Cargo directory")); } @@ -177,8 +175,8 @@ pub fn clean_outputs(root: &Path, selected: &Path, dist: &Path) -> Result<()> { .filter(|t| t.enabled) .map(|t| t.archive_target()) .collect::>>()?; - storage::remove(selected)?; - storage::remove(dist)?; + storage::remove(&selected_location)?; + storage::remove(&owner.join("dist"))?; for entry in fs::read_dir(root)? { let path = entry?.path(); let name = path.file_name().unwrap().to_string_lossy(); diff --git a/tools/src/checks.rs b/tools/src/checks.rs index 7064ef9d..95394488 100644 --- a/tools/src/checks.rs +++ b/tools/src/checks.rs @@ -78,6 +78,7 @@ pub fn binary(arguments: &[OsString]) -> Result { package::require_rpath(&path, &expected)?; } if json { + let rpaths = Value::strings(info.runtime_paths()); print!( "{}", config::json(&Value::object([ @@ -86,7 +87,7 @@ pub fn binary(arguments: &[OsString]) -> Result { ("bits", Value::integer(info.bits as u64)), ("flags", Value::integer(info.flags as u64)), ("needed", Value::strings(info.needed)), - ("rpaths", Value::strings(info.rpaths)) + ("rpaths", rpaths) ]))? ); } else { @@ -102,6 +103,9 @@ pub fn release_assets( expected_revision: Option, ) -> Result { crate::publication::validate_version(version, false)?; + if expected_revision.is_some() && source.is_none() { + return Err(error("--std-revision requires --source to verify package metadata")); + } if let Some(source) = source { crate::publication::sha(source)?; } @@ -137,7 +141,8 @@ pub fn release_assets( if records.len() != 1 || records[0].len() < 66 { return Err(error("malformed checksum record")); } - let (digest, filename) = records[0].split_at(64); + let (digest, filename) = + records[0].split_at_checked(64).ok_or_else(|| error("malformed checksum record"))?; if !digest.bytes().all(|b| b.is_ascii_hexdigit()) || ![format!(" {name}"), format!(" *{name}")].contains(&filename.to_string()) || storage::digest(&archive)? != digest.to_ascii_lowercase() diff --git a/tools/src/ci.rs b/tools/src/ci.rs index 76891679..3aa39375 100644 --- a/tools/src/ci.rs +++ b/tools/src/ci.rs @@ -45,6 +45,24 @@ pub fn runtime_evidence( if shards == 0 || shard >= shards { return Err(error("invalid runtime evidence shard")); } + if report.get_u64("schema_version") != Some(1) { + return Err(error("unsupported runtime evidence schema version")); + } + let selection = report.get("selection").ok_or_else(|| error("missing report selection"))?; + for (key, expected) in [ + ("id", target.id.as_str()), + ("target", target.rust_target()?.as_str()), + ("executor", target.executor.as_str()), + ] { + if selection.get_str(key) != Some(expected) { + return Err(error(format!("runtime evidence selection {key} must be {expected}"))); + } + } + if selection.get_u64("shard_index") != Some(shard as u64) + || selection.get_u64("shard_count") != Some(shards as u64) + { + return Err(error("runtime evidence shard does not match the requested selection")); + } let manifest = cases::Manifest::load(&crate::root(), true)?; let sources = manifest.sources(Some(target))?; let selected = sources @@ -64,11 +82,12 @@ pub fn runtime_evidence( .iter() .find(|row| row.get_str("name") == Some(&name)) .ok_or_else(|| error(format!("missing runtime evidence for {name}")))?; + let expected_exit = config::number(metadata.expected_exit.into()); if row.get_str("status") != Some("pass") || !config::array(row, "commands")?.iter().any(|command| { command.get_str("phase") == Some("run") && command.get_str("status") == Some("pass") - && command.get_u64("actual_exit") == Some(0) + && command.get("actual_exit") == Some(&expected_exit) }) { return Err(error(format!("runtime source was not successfully executed: {name}"))); diff --git a/tools/src/package.rs b/tools/src/package.rs index ae597c83..2843e812 100644 --- a/tools/src/package.rs +++ b/tools/src/package.rs @@ -357,9 +357,8 @@ pub fn linux_crt(stage: &Path, target: &str) -> Result<()> { Ok(()) } -fn library_directories(source: &Path, sdk: &Path) -> Vec { - let mut directories = - vec![source.parent().unwrap().into(), sdk.join("lib"), sdk.join("lib64"), sdk.join("bin")]; +fn library_directories(sdk: &Path) -> Vec { + let mut directories = vec![sdk.join("lib"), sdk.join("lib64"), sdk.join("bin")]; for name in ["WAVE_LLVM_LIB", "WAVE_WINDOWS_LLVM_BIN", "LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH"] { if let Some(value) = std::env::var_os(name) { directories.extend(std::env::split_paths(&value)); @@ -388,46 +387,76 @@ fn library_directories(source: &Path, sdk: &Path) -> Vec { directories } +fn elf_directories(paths: &[String], source: &Path) -> Vec { + let origin = source.parent().unwrap().to_string_lossy(); + paths + .iter() + .filter_map(|path| { + let expanded = path.replace("${ORIGIN}", &origin).replace("$ORIGIN", &origin); + (!expanded.contains('$')).then(|| PathBuf::from(expanded)) + }) + .collect() +} + +fn mach_path(name: &str, loader_dir: &Path, executable_dir: &Path) -> PathBuf { + let path = Path::new(name); + for (prefix, directory) in [("@loader_path", loader_dir), ("@executable_path", executable_dir)] + { + if let Ok(relative) = path.strip_prefix(prefix) { + return directory.join(relative); + } + } + path.to_owned() +} + fn resolve_library( name: &str, source: &Path, + executable_dir: &Path, info: &binary::Info, sdk: &Path, target: &str, + inherited_rpaths: &[PathBuf], ) -> Result { let mut candidates = Vec::new(); if Path::new(name).is_absolute() { candidates.push(PathBuf::from(name)); } - for prefix in ["@loader_path/", "@executable_path/"] { - if let Some(suffix) = name.strip_prefix(prefix) { - candidates.push(source.parent().unwrap().join(suffix)); + if target.contains("darwin") { + if let Some(suffix) = name.strip_prefix("@rpath/") { + candidates.extend(inherited_rpaths.iter().map(|directory| directory.join(suffix))); + } else if name.starts_with("@loader_path/") || name.starts_with("@executable_path/") { + candidates.push(mach_path(name, source.parent().unwrap(), executable_dir)); } } - if let Some(suffix) = name.strip_prefix("@rpath/") { - for rpath in &info.rpaths { - let rpath = rpath - .replace("@loader_path", &source.parent().unwrap().to_string_lossy()) - .replace("@executable_path", &source.parent().unwrap().to_string_lossy()); - candidates.push(PathBuf::from(rpath).join(suffix)); + if info.format == "Elf" && target.contains("-linux") { + // DT_RPATH is inherited. DT_RUNPATH applies only to direct dependencies + // and follows LD_LIBRARY_PATH. Preserve the order within each list. + if info.runpaths.is_empty() { + candidates.extend(inherited_rpaths.iter().map(|directory| directory.join(name))); } + if let Some(paths) = std::env::var_os("LD_LIBRARY_PATH") { + candidates.extend(std::env::split_paths(&paths).map(|directory| directory.join(name))); + } + candidates.extend(elf_directories(&info.runpaths, source).iter().map(|dir| dir.join(name))); + } + // ELF does not implicitly search the directory of the referring object. + let mut fallbacks = library_directories(sdk); + if !target.contains("-linux") { + fallbacks.insert(0, source.parent().unwrap().into()); } - for directory in library_directories(source, sdk) { + for directory in &fallbacks { candidates .push(directory.join( Path::new(name).file_name().ok_or_else(|| error("invalid dependency name"))?, )); } - for rpath in &info.rpaths { - let directory = rpath - .replace("${ORIGIN}", &source.parent().unwrap().to_string_lossy()) - .replace("$ORIGIN", &source.parent().unwrap().to_string_lossy()); - if !directory.contains('$') { - candidates.push(PathBuf::from(directory).join(name)); - } + if !target.contains("-linux") { + candidates + .extend(elf_directories(info.runtime_paths(), source).iter().map(|dir| dir.join(name))); } if cfg!(windows) { - for directory in library_directories(source, sdk) { + for directory in fallbacks { if directory.is_dir() { for entry in fs::read_dir(directory)? { let entry = entry?; @@ -464,7 +493,10 @@ pub fn runtime_closure( ) -> Result> { if target.contains("windows") { let binaries = roots.iter().map(|(source, _)| source.clone()).collect::>(); - let mut search = library_directories(&binaries[0], sdk); + let mut search = library_directories(sdk); + if let Some(directory) = binaries.first().and_then(|path| path.parent()) { + search.insert(0, directory.into()); + } search.extend(roots.iter().filter_map(|(source, _)| source.parent().map(Path::to_owned))); let system = PathBuf::from( std::env::var_os("SystemRoot").ok_or_else(|| error("missing Windows SystemRoot"))?, @@ -499,17 +531,47 @@ pub fn runtime_closure( )?; return Ok(copied); } - let mut pending: VecDeque<_> = roots.iter().cloned().collect(); + let mut pending = VecDeque::new(); + let darwin = target.contains("darwin"); + for (source, staged) in roots { + let executable_dir = if darwin { + fs::canonicalize(source)?.parent().unwrap().to_owned() + } else { + PathBuf::new() + }; + pending.push_back((source.clone(), staged.clone(), executable_dir, Vec::new())); + } + let mut rewritten = BTreeSet::new(); let mut visited = BTreeSet::new(); let mut names: BTreeMap = BTreeMap::new(); let mut copied = Vec::new(); let library_dir = stage.join(if target.contains("windows") { "llvm/bin" } else { "llvm/lib" }); fs::create_dir_all(&library_dir)?; - while let Some((source, staged)) = pending.pop_front() { - if !visited.insert((fs::canonicalize(&source)?, staged.clone())) { + while let Some((source, staged, executable_dir, mut inherited_rpaths)) = pending.pop_front() { + let resolved_source = fs::canonicalize(&source)?; + if !visited.insert(( + resolved_source.clone(), + staged.clone(), + executable_dir.clone(), + inherited_rpaths.clone(), + )) { continue; } let info = binary::inspect(&source, Some(target))?; + if darwin || target.contains("-linux") && info.runpaths.is_empty() { + let mut directories = if darwin { + info.rpaths + .iter() + .map(|path| mach_path(path, resolved_source.parent().unwrap(), &executable_dir)) + .collect() + } else { + elf_directories(&info.rpaths, &resolved_source) + }; + let mut seen = BTreeSet::new(); + directories.append(&mut inherited_rpaths); + directories.retain(|path| seen.insert(path.clone())); + inherited_rpaths = directories; + } for name in &info.needed { if binary::system_library(name, target) { continue; @@ -522,7 +584,17 @@ pub fn runtime_closure( binary::inspect(&path, Some(target))?; continue; } - let dependency = resolve_library(name, &source, &info, sdk, target)?; + let loader = + if darwin || target.contains("-linux") { &resolved_source } else { &source }; + let dependency = resolve_library( + name, + loader, + &executable_dir, + &info, + sdk, + target, + &inherited_rpaths, + )?; binary::inspect(&dependency, Some(target))?; if target.contains("freebsd") && freebsd_base_library( @@ -539,21 +611,31 @@ pub fn runtime_closure( let key = if target.contains("windows") { basename.to_lowercase() } else { basename.clone() }; if let Some(previous) = names.get(&key) { - if storage::digest(previous)? != storage::digest(&dependency)? { + if previous != &dependency + && storage::digest(previous)? != storage::digest(&dependency)? + { return Err(error(format!("conflicting runtime library basename: {basename}"))); } } let destination = library_dir.join(&basename); - if !destination.exists() { + let newly_staged = !destination.exists(); + if newly_staged { fs::copy(&dependency, &destination)?; copied.push(destination.clone()); names.insert(key, dependency.clone()); - pending.push_back((dependency.clone(), destination.clone())); + } + if newly_staged || darwin || target.contains("-linux") { + pending.push_back(( + dependency.clone(), + destination.clone(), + executable_dir.clone(), + inherited_rpaths.clone(), + )); } if target.contains("windows") { fs::copy(&dependency, stage.join(&basename))?; } - if target.contains("darwin") { + if darwin && rewritten.insert((staged.clone(), name.clone())) { let prefix = if staged.parent() == Some(library_dir.as_path()) { "@loader_path" } else if staged.parent() == Some(stage) { @@ -580,7 +662,7 @@ fn freebsd_base_library(path: &Path, root: &Path) -> bool { pub fn require_rpath(path: &Path, expected: &str) -> Result<()> { let info = binary::inspect(path, None)?; - if info.format != "Elf" || !info.rpaths.contains(expected) { + if info.format != "Elf" || !info.runtime_paths().iter().any(|path| path == expected) { return Err(error(format!( "{}: missing exact runtime search path {expected}", path.display() @@ -802,17 +884,15 @@ fn archive_at_epoch(stage: &Path, output: &Path, name: &str, epoch: u64) -> Resu ) .map_err(|_| error("invalid ZIP archive epoch"))?; let mut zip = zip::ZipWriter::new(fs::File::create(output)?); - zip.add_directory( - format!("{name}/"), - zip::write::SimpleFileOptions::default() - .last_modified_time(stamp) - .unix_permissions(0o755), - )?; + // ZIP readers interpret permission bits according to the creator system. + let options = zip::write::SimpleFileOptions::default() + .system(zip::System::Unix) + .last_modified_time(stamp); + zip.add_directory(format!("{name}/"), options.unix_permissions(0o755))?; for (relative, path) in entries { let directory = path.is_dir(); - let options = zip::write::SimpleFileOptions::default() + let options = options .compression_method(zip::CompressionMethod::Deflated) - .last_modified_time(stamp) .unix_permissions(archive_mode(&path, directory)?); if directory { zip.add_directory(format!("{name}/{relative}/"), options)?; @@ -1510,6 +1590,11 @@ mod tests { fs::create_dir(stage.join("empty")).unwrap(); archive_at_epoch(&stage, &second, "wave", 1600000001).unwrap(); assert_eq!(fs::read(&first).unwrap(), fs::read(&second).unwrap(), "{extension}"); + let unpacked = temp.path().join(format!("unpacked-{extension}")); + crate::sdk::extract(&first, &unpacked, false).unwrap(); + assert!(unpacked.join("wave/empty").is_dir()); + assert_eq!(fs::read(unpacked.join("wave/bin/wavec.exe")).unwrap(), b"executable bytes"); + assert_eq!(fs::read(unpacked.join("wave/payload")).unwrap(), b"unchanged bytes"); if extension == "tar.gz" { let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(fs::File::open(first).unwrap())); @@ -1533,14 +1618,17 @@ mod tests { } else { let mut archive = zip::ZipArchive::new(fs::File::open(first).unwrap()).unwrap(); assert_eq!(archive.len(), 5); - assert_eq!( - archive.by_name("wave/bin/wavec.exe").unwrap().unix_mode().unwrap() & 0o777, - 0o755 - ); - assert_eq!( - archive.by_name("wave/payload").unwrap().unix_mode().unwrap() & 0o777, - 0o644 - ); + for (name, mode) in [ + ("wave/", 0o755), + ("wave/bin/", 0o755), + ("wave/bin/wavec.exe", 0o755), + ("wave/empty/", 0o755), + ("wave/payload", 0o644), + ] { + let entry = archive.by_name(name).unwrap(); + assert_eq!(entry.system(), zip::System::Unix, "{name}"); + assert_eq!(entry.unix_mode().unwrap() & 0o777, mode, "{name}"); + } } } } diff --git a/tools/src/runner.rs b/tools/src/runner.rs index 5e496911..65c8d93d 100644 --- a/tools/src/runner.rs +++ b/tools/src/runner.rs @@ -83,21 +83,27 @@ fn patterns(text: &str) -> Result> { impl Metadata { pub fn parse(source: &str) -> Result { let mut values = BTreeMap::new(); - for line in source.lines() { + // A CR before LF is one terminator. Any CR left within the line + // starts a new physical source line, just as it does in wavec. + let lines = + source.split('\n').flat_map(|line| line.strip_suffix('\r').unwrap_or(line).split('\r')); + for (index, line) in lines.enumerate() { let line = line.trim(); if !line.is_empty() && !line.starts_with("//") { break; } if let Some(body) = line.strip_prefix("// wave-test:") { for item in body.split(',') { - let (key, value) = item - .trim() - .split_once('=') - .ok_or_else(|| error("malformed wave-test metadata"))?; + let (key, value) = item.trim().split_once('=').ok_or_else(|| { + error(format!("malformed wave-test metadata at line {}", index + 1)) + })?; let key = key.trim(); let value = value.trim(); if key.is_empty() || value.is_empty() || values.insert(key, value).is_some() { - return Err(error("empty or duplicate wave-test metadata")); + return Err(error(format!( + "empty or duplicate wave-test metadata at line {}", + index + 1 + ))); } } } @@ -212,10 +218,11 @@ impl Metadata { || metadata.riscv_float_abi.is_some() || metadata.loongarch_float_abi.is_some(); let assembly = !metadata.asm_contains.is_empty() || !metadata.asm_not_contains.is_empty(); - if object && metadata.emit != "obj" - || assembly && metadata.emit != "asm" - || (object || assembly) && metadata.expected_exit != 0 + if metadata.expected_exit != 0 && (metadata.mode != "run" || metadata.runtime == "compile") { + return Err(error("nonzero expected exit requires runtime execution")); + } + if object && metadata.emit != "obj" || assembly && metadata.emit != "asm" { return Err(error("artifact contract conflicts with emit/exit contract")); } Ok(metadata) @@ -509,7 +516,6 @@ fn run_one(source: &Path, metadata: &Metadata, options: &Options, row: &mut Valu // source's normal compile-only assembly contract in the complete case suite. let hosted = Metadata::default(); let metadata = if options.hosted_abi { &hosted } else { metadata }; - let output = tempfile::Builder::new().prefix("wave-case-").tempdir()?; let target = metadata .target .clone() @@ -522,6 +528,29 @@ fn run_one(source: &Path, metadata: &Metadata, options: &Options, row: &mut Valu }) .transpose()?; let mode = options.target.as_ref().map(|t| t.executor.as_str()).unwrap_or("native"); + let mut args: Vec = vec![ + options.compiler.clone().into_os_string(), + if metadata.mode == "check" { "check" } else { "build" }.into(), + source.as_os_str().into(), + "--std-root".into(), + crate::root().join("std").into_os_string(), + ]; + if let Some(target) = &target { + args.extend(["--target".into(), target.into()]); + } + if let Some(sysroot) = &options.sysroot { + args.extend(["--sysroot".into(), sysroot.clone().into_os_string()]); + } + if metadata.mode == "check" { + if options.expected_stdout.is_some() { + return Err(error("an stdout contract requires actual runtime execution")); + } + let mut spec = process::Spec::new(args); + spec.timeout = options.build_timeout; + command(row, "check", &spec, 0)?; + return Ok(()); + } + let output = tempfile::Builder::new().prefix("wave-case-").tempdir()?; let compile = metadata.runner == "compile" || mode == "compile" || ["qemu", "wasm"].contains(&mode) @@ -555,28 +584,15 @@ fn run_one(source: &Path, metadata: &Metadata, options: &Options, row: &mut Valu artifact_name.push("."); artifact_name.push(suffix); let artifact = output.path().join(artifact_name); - let mut args: Vec = vec![ - options.compiler.clone().into_os_string(), - if metadata.mode == "check" { "check" } else { "build" }.into(), - source.as_os_str().into(), - "--std-root".into(), - crate::root().join("std").into_os_string(), + args.extend([ "--out-dir".into(), output.path().as_os_str().into(), - ]; - if metadata.mode != "check" { - args.push(options.optimization.clone().into()); - // Wave accepts -o for a binary or one object, but names assembly, - // textual IR and bitcode from the input stem inside --out-dir. - if named_output { - args.extend(["-o".into(), artifact.clone().into_os_string()]); - } - } - if let Some(target) = &target { - args.extend(["--target".into(), target.into()]); - } - if let Some(sysroot) = &options.sysroot { - args.extend(["--sysroot".into(), sysroot.clone().into_os_string()]); + options.optimization.clone().into(), + ]); + // Wave accepts -o for a binary or one object, but names assembly, + // textual IR and bitcode from the input stem inside --out-dir. + if named_output { + args.extend(["-o".into(), artifact.clone().into_os_string()]); } if compile { args.push(format!("--emit={emit}").into()); @@ -588,15 +604,21 @@ fn run_one(source: &Path, metadata: &Metadata, options: &Options, row: &mut Valu } let mut spec = process::Spec::new(args); spec.timeout = options.build_timeout; - command(row, if metadata.mode == "check" { "check" } else { "build" }, &spec, 0)?; - if metadata.mode == "check" { - return Ok(()); - } + command(row, "build", &spec, 0)?; if !artifact.is_file() { return Err(error("build succeeded without expected output")); } if compile { config::field(row, "phase", Value::string("artifact"))?; + if metadata.mode == "run" { + config::field( + row, + "runtime_skip_reason", + Value::string(format!( + "{mode} executor cannot run this case with its declared runtime and capabilities" + )), + )?; + } let mut metadata = metadata.clone(); metadata.emit = emit.into(); return verify_artifact(&artifact, &metadata, target.as_deref()); @@ -767,7 +789,12 @@ pub fn execute( Value::object([ ( "name", - Value::string(p.strip_prefix(crate::root()).unwrap_or(p).to_string_lossy()), + Value::string( + p.strip_prefix(crate::root()) + .unwrap_or(p) + .to_string_lossy() + .replace('\\', "/"), + ), ), ("status", Value::string("not_run")), ("commands", Value::Array(vec![])), @@ -1235,15 +1262,13 @@ pub fn local_network_unavailable() -> Result> { } pub fn runtime_eligible(metadata: &Metadata, target: &cases::Target) -> bool { - metadata.mode == "run" + target.executor != "compile" + && metadata.mode == "run" && metadata.runner == "native" && metadata.runtime != "compile" && (metadata.runtime != "native" || ["native", "qemu"].contains(&target.executor.as_str())) && metadata.requires.iter().all(|cap| target.capabilities.contains(cap)) - && metadata.stdin.is_none() - && metadata.stdin_file.is_none() && !metadata.udp_input - && metadata.expected_exit == 0 } pub fn assembly_code(source: &str, target: &str) -> Result { diff --git a/tools/src/sdk.rs b/tools/src/sdk.rs index ca57d32f..3ab8dd62 100644 --- a/tools/src/sdk.rs +++ b/tools/src/sdk.rs @@ -75,9 +75,7 @@ fn check_tree_policy(root: &Path, directories: bool) -> Result<()> { return Err(error("cyclic LLVM bundle link")); } let target = fs::read_link(¤t)?; - if target.is_absolute() { - return Err(error("absolute LLVM bundle link")); - } + validate_link_target(&target)?; let components: Vec<_> = target.components().map(|c| c.as_os_str().to_owned()).collect(); for component in components.into_iter().rev() { @@ -211,6 +209,18 @@ fn relative(path: &Path) -> Result { Ok(output) } +fn validate_link_target(target: &Path) -> Result<()> { + for component in target.components() { + match component { + Component::CurDir | Component::ParentDir => {}, + Component::Normal(name) if !cfg!(windows) || !name.to_string_lossy().contains(':') => { + }, + _ => return Err(error(format!("expected relative bundle link: {}", target.display()))), + } + } + Ok(()) +} + #[cfg(unix)] fn link(target: &Path, path: &Path) -> Result<()> { std::os::unix::fs::symlink(target, path)?; @@ -280,16 +290,24 @@ fn extract_policy( Ok(()) }; let name = archive.to_string_lossy(); + let gzip = name.ends_with(".tar.gz") || name.ends_with(".tgz"); if name.ends_with(".zip") { let mut zip = zip::ZipArchive::new(File::open(archive)?)?; + zip.validate_header_consistency()?; for index in 0..zip.len() { let mut entry = zip.by_index(index)?; - if entry.is_dir() - && Path::new(entry.name()).components().all(|c| c == Component::CurDir) - { + if entry.is_dir() && entry.read(&mut [0])? != 0 { + return Err(error("unexpected ZIP directory payload")); + } + let entry_name = entry.name()?; + let entry_path = Path::new(entry_name.as_ref()); + if entry.is_dir() && entry_path.components().all(|c| c == Component::CurDir) { continue; } - let path = relative(Path::new(entry.name()))?; + if entry.enclosed_name().is_none() { + return Err(error(format!("invalid ZIP entry path: {entry_name}"))); + } + let path = relative(entry_path)?; let mode = entry.unix_mode().unwrap_or(0o100644); if entry.is_dir() { fs::create_dir_all(stage.join(path))?; @@ -298,17 +316,24 @@ fn extract_policy( return Err(error("archive symlink is not allowed")); } let mut target = String::new(); - entry.read_to_string(&mut target)?; + let size = entry.size(); + if entry.by_ref().take(size).read_to_string(&mut target)? as u64 != size { + return Err(error("truncated archive link")); + } links.push((path, PathBuf::from(target), false)); } else if mode & 0o170000 == 0 || mode & 0o170000 == 0o100000 { put(&path, entry.size(), mode, &mut entry)?; } else { return Err(error("unsupported archive entry type")); } + // The ZIP reader checks the CRC on the first read past the payload. + if entry.read(&mut [0])? != 0 { + return Err(error("ZIP entry exceeds its declared size")); + } } } else { - let reader: Box = if name.ends_with(".tar.gz") || name.ends_with(".tgz") { - Box::new(flate2::read::GzDecoder::new(File::open(archive)?)) + let reader: Box = if gzip { + Box::new(flate2::read::MultiGzDecoder::new(File::open(archive)?)) } else if name.ends_with(".tar.xz") || name.ends_with(".txz") { let compressed = work.path().join("input.tar.xz"); fs::copy(archive, &compressed)?; @@ -355,6 +380,15 @@ fn extract_policy( return Err(error("unsupported archive entry type")); } } + if gzip { + // TAR stops at its end marker. Consume gzip padding and trailers, + // including any later members, before activating the staged tree. + let remaining = MAX_EXPANDED - expanded; + let mut tail = tar.into_inner().take(remaining + 1); + if std::io::copy(&mut tail, &mut std::io::sink())? > remaining { + return Err(error("expanded archive exceeds size limit")); + } + } } // Creating a link never grants permission to write through it. let link_names: BTreeSet<_> = links.iter().map(|(name, _, _)| name.clone()).collect(); @@ -367,9 +401,7 @@ fn extract_policy( if !seen.insert(name.clone()) || storage::exists(&stage.join(name)) { return Err(error("duplicate archive link")); } - if target.is_absolute() { - return Err(error("absolute archive link")); - } + validate_link_target(target)?; let path = stage.join(name); fs::create_dir_all(path.parent().unwrap())?; if *hard { diff --git a/tools/src/storage.rs b/tools/src/storage.rs index 1015aeea..66593eff 100644 --- a/tools/src/storage.rs +++ b/tools/src/storage.rs @@ -29,6 +29,14 @@ pub fn exists(path: &Path) -> bool { pub fn remove(path: &Path) -> Result<()> { if let Ok(metadata) = fs::symlink_metadata(path) { + #[cfg(windows)] + { + use std::os::windows::fs::FileTypeExt; + if metadata.file_type().is_symlink_dir() { + fs::remove_dir(path)?; + return Ok(()); + } + } if metadata.is_dir() && !metadata.is_symlink() { fs::remove_dir_all(path)?; } else { diff --git a/tools/tests/artifacts.rs b/tools/tests/artifacts.rs index eeb9d0c3..76622fc9 100644 --- a/tools/tests/artifacts.rs +++ b/tools/tests/artifacts.rs @@ -189,3 +189,110 @@ fn coff_address_width_and_every_archive_member_follow_the_native_machine() { fs::write(&library, b"!\n").unwrap(); assert!(binary::inspect(&library, Some("x86_64-pc-windows-msvc")).is_err()); } + +#[test] +fn forwarded_pe_exports_resolve_names_ordinals_and_cycles() { + fn forwards(file: &Path, targets: &[&str]) { + pe(file, 0x8664, &[]); + let mut data = fs::read(file).unwrap(); + // Export directory at RVA 0x1100, with an ordinal-only address table. + let base = 0x300; + let mut word = |at: usize, n: u32| data[at..at + 4].copy_from_slice(&n.to_le_bytes()); + word(88 + 112, 0x1100); + word(88 + 116, 0x200); + word(base + 16, 1); + word(base + 20, targets.len() as u32); + word(base + 28, 0x1140); + let mut strings = 0x1180u32; + for (i, name) in targets.iter().enumerate() { + let entry = base + 0x40 + 4 * i; + data[entry..entry + 4].copy_from_slice(&strings.to_le_bytes()); + let at = base + (strings - 0x1100) as usize; + data[at..at + name.len()].copy_from_slice(name.as_bytes()); + strings += name.len() as u32 + 1; + } + fs::write(file, data).unwrap(); + } + let directory = tempfile::tempdir().unwrap(); + let dir = directory.path(); + let root = dir.join("root.exe"); + pe(&root, 0x8664, &["a.dll"]); + forwards(&dir.join("a.dll"), &["B.value", "kernel32.Sleep"]); + forwards(&dir.join("b.dll"), &["c.#12", "api-ms-win-core-file-l1-1-0.GetFileType"]); + forwards(&dir.join("c.dll"), &["a.other"]); + let closure = || { + windows::dependency_closure( + std::slice::from_ref(&root), + "x86_64-pc-windows-msvc", + &[dir.into()], + &[], + ) + }; + let (payload, prerequisites) = closure().unwrap(); + assert_eq!(payload.keys().map(String::as_str).collect::>(), ["a.dll", "b.dll", "c.dll"]); + assert!(prerequisites.is_empty()); + fs::remove_file(dir.join("b.dll")).unwrap(); + assert!(closure().unwrap_err().to_string().contains("B.dll")); +} + +#[cfg(windows)] +#[test] +fn a_packaged_forwarded_export_executes_on_native_windows() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + let stage = root.join("stage"); + fs::create_dir(&stage).unwrap(); + let target = if cfg!(target_arch = "aarch64") { + "aarch64-pc-windows-msvc" + } else { + "x86_64-pc-windows-msvc" + }; + let machine = if cfg!(target_arch = "aarch64") { "/machine:arm64" } else { "/machine:x64" }; + let run = |program: &str, args: &[&str]| { + let result = + std::process::Command::new(program).current_dir(root).args(args).output().unwrap(); + assert!(result.status.success(), "{program}: {}", String::from_utf8_lossy(&result.stderr)); + }; + fs::write(root.join("b.c"), "__declspec(dllexport) int value(void) { return 22; }").unwrap(); + fs::write(root.join("a.def"), "LIBRARY a\nEXPORTS\n value=b.value\n").unwrap(); + fs::write(root.join("empty.c"), "int placeholder;").unwrap(); + fs::write( + root.join("root.c"), + "__declspec(dllimport) int value(void); int mainCRTStartup(void) { return value() != 22; }", + ) + .unwrap(); + for (source, object) in [("b.c", "b.obj"), ("empty.c", "empty.obj"), ("root.c", "root.obj")] { + run("clang", &["-target", target, "-c", source, "-o", object]); + } + run("lld-link", &[machine, "/dll", "/noentry", "/nodefaultlib", "/out:b.dll", "b.obj"]); + run( + "lld-link", + &[machine, "/dll", "/noentry", "/nodefaultlib", "/def:a.def", "/out:a.dll", "empty.obj"], + ); + run( + "lld-link", + &[ + machine, + "/entry:mainCRTStartup", + "/subsystem:console", + "/nodefaultlib", + "/out:root.exe", + "root.obj", + "a.lib", + ], + ); + let exe = root.join("root.exe"); + let (providers, _) = + windows::dependency_closure(std::slice::from_ref(&exe), target, &[root.into()], &[]) + .unwrap(); + assert!(providers.contains_key("b.dll")); + for (name, source) in providers { + fs::copy(source, stage.join(name)).unwrap(); + } + fs::copy(exe, stage.join("root.exe")).unwrap(); + assert!(std::process::Command::new(stage.join("root.exe")) + .current_dir(&stage) + .status() + .unwrap() + .success()); +} diff --git a/tools/tests/contracts.rs b/tools/tests/contracts.rs index c783c56d..f0375f3d 100644 --- a/tools/tests/contracts.rs +++ b/tools/tests/contracts.rs @@ -101,6 +101,20 @@ fn output_budget_is_bounded_and_reported() { assert_eq!(result.stdout.len(), 1024); } +#[test] +fn case_metadata_preserves_physical_lines_across_line_endings() { + use wave_tools::runner::Metadata; + for newline in ["\n", "\r\n", "\r"] { + let text = ["// header", "", "// wave-test: expected-exit=7, stdin=A", "fun main() {}"] + .join(newline); + let case = Metadata::parse(&text).unwrap(); + assert_eq!(case.expected_exit, 7); + assert_eq!(case.stdin.as_deref(), Some("A")); + let malformed = ["// header", "", "// wave-test: stdin"].join(newline); + assert!(Metadata::parse(&malformed).unwrap_err().to_string().contains("line 3")); + } +} + #[test] fn metadata_rejects_ambiguous_fixtures_and_invalid_compile_contracts() { use wave_tools::runner::Metadata; @@ -110,6 +124,8 @@ fn metadata_rejects_ambiguous_fixtures_and_invalid_compile_contracts() { "// wave-test: requires=clock|clock", "// wave-test: stdout-file=../outside", "// wave-test: target=aarch64-unknown-linux-gnu", + "// wave-test: mode=check,expected-exit=7", + "// wave-test: runtime=compile,expected-exit=7", ] { assert!(Metadata::parse(source).is_err(), "{source}"); } @@ -292,6 +308,114 @@ fn cleanup_preflights_ownership_preserves_tmp_and_recognizes_native_archives() { assert!(root.join("unrelated.zip").is_file()); } +#[test] +#[cfg(unix)] +fn clean_applies_the_default_exception_to_the_target_entry() { + use std::os::unix::fs::symlink; + use wave_tools::build::clean_outputs; + + let work = tempfile::tempdir().unwrap(); + let root = work.path(); + fs::create_dir_all(root.join("tests/cases")).unwrap(); + fs::copy( + wave_tools::root().join("tests/cases/cases.toml"), + root.join("tests/cases/cases.toml"), + ) + .unwrap(); + let data = root.join("custom"); + let target = root.join("target"); + let dist = root.join("dist"); + fs::create_dir(&data).unwrap(); + fs::create_dir(&dist).unwrap(); + fs::write(data.join("sentinel"), "keep").unwrap(); + symlink(&data, &target).unwrap(); + assert!(clean_outputs(root, &data, &dist).is_err()); + assert!(dist.is_dir()); + clean_outputs(root, &target, &dist).unwrap(); + assert!(!storage::exists(&target)); + assert_eq!(fs::read(data.join("sentinel")).unwrap(), b"keep"); + fs::write(data.join(".wave-cargo-owner"), fs::canonicalize(root).unwrap().to_str().unwrap()) + .unwrap(); + clean_outputs(root, &data, &dist).unwrap(); + assert!(!data.exists()); +} + +#[test] +fn runtime_evidence_checks_the_schema_target_executor_and_shard() { + use utils::wson::Value; + use wave_tools::{cases::Manifest, ci::runtime_evidence, runner}; + + let root = wave_tools::root(); + let manifest = Manifest::load(&root, true).unwrap(); + let target = manifest.target("linux-amd64").unwrap(); + let sources = manifest.sources(Some(target)).unwrap(); + let (index, source) = sources + .iter() + .enumerate() + .find(|(_, path)| { + let metadata = runner::Metadata::parse(&fs::read_to_string(path).unwrap()).unwrap(); + metadata.expected_exit != 0 && runner::runtime_eligible(&metadata, target) + }) + .unwrap(); + let count = sources.len(); + let expected = + runner::Metadata::parse(&fs::read_to_string(source).unwrap()).unwrap().expected_exit; + let selection = Value::object([ + ("id", Value::string(&target.id)), + ("executor", Value::string(&target.executor)), + ("target", Value::string(target.rust_target().unwrap())), + ("shard_index", Value::integer(index as u64)), + ("shard_count", Value::integer(count as u64)), + ]); + let row = |actual: i32| { + Value::object([ + ( + "name", + Value::string( + source.strip_prefix(&root).unwrap().to_string_lossy().replace('\\', "/"), + ), + ), + ("status", Value::string("pass")), + ( + "commands", + Value::Array(vec![Value::object([ + ("phase", Value::string("run")), + ("status", Value::string("pass")), + ("actual_exit", config::number(actual.into())), + ])]), + ), + ]) + }; + let report = Value::object([ + ("schema_version", Value::integer(1)), + ("selection", selection.clone()), + ("tests", Value::Array(vec![row(expected)])), + ]); + let check = |report: &Value| runtime_evidence(report, target, index, count); + assert_eq!(check(&report).unwrap(), 1); + let mut wrong_exit = report.clone(); + config::field(&mut wrong_exit, "tests", Value::Array(vec![row(0)])).unwrap(); + assert!(check(&wrong_exit).is_err()); + for (key, value) in [ + ("id", Value::string("windows-arm64")), + ("executor", Value::string("compile")), + ("target", Value::string("aarch64-pc-windows-msvc")), + ("shard_index", Value::integer((index + 1) as u64)), + ("shard_count", Value::integer((count + 1) as u64)), + ] { + let mut wrong = selection.clone(); + config::field(&mut wrong, key, value).unwrap(); + let mut input = report.clone(); + config::field(&mut input, "selection", wrong).unwrap(); + assert!(check(&input).is_err(), "{key}"); + } + for (key, value) in [("schema_version", Value::integer(2)), ("selection", Value::Null)] { + let mut input = report.clone(); + config::field(&mut input, key, value).unwrap(); + assert!(check(&input).is_err(), "{key}"); + } +} + #[test] fn actions_outputs_share_the_codec_without_relaxing_environment_names() { let directory = tempfile::tempdir().unwrap(); diff --git a/tools/tests/package_inputs.rs b/tools/tests/package_inputs.rs index b00dc3a5..2e81ad0f 100644 --- a/tools/tests/package_inputs.rs +++ b/tools/tests/package_inputs.rs @@ -78,3 +78,174 @@ fn package_membership_uses_committed_blobs_excludes_local_files_and_rejects_dirt assert!(String::from_utf8_lossy(&link.stderr).contains("not a regular committed blob")); assert_eq!(fs::read(root.join("std/core.wave")).unwrap(), b"COMMITTED\n"); } + +#[cfg(all(target_os = "linux", target_arch = "x86_64"))] +#[test] +fn linux_package_preserves_loader_path_order_and_rpath_inheritance() { + let work = tempfile::tempdir().unwrap(); + let root = work.path(); + for dir in ["z-first", "a-second", "sdk/lib"] { + fs::create_dir_all(root.join(dir)).unwrap(); + } + let cc = |args: &[&str]| { + let output = Command::new("cc").current_dir(root).args(args).output().unwrap(); + assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); + }; + for (dir, value) in [("z-first", 22), ("a-second", 33), ("sdk/lib", 11)] { + fs::write(root.join("value.c"), format!("int value(void) {{ return {value}; }}")).unwrap(); + cc(&[ + "-shared", + "-fPIC", + "value.c", + "-Wl,-soname,libwave_value.so", + "-o", + &format!("{dir}/libwave_value.so"), + ]); + } + fs::write(root.join("call.c"), "extern int value(void); int call(void) { return value(); }") + .unwrap(); + cc(&[ + "-shared", + "-fPIC", + "call.c", + "-Lz-first", + "-lwave_value", + "-Wl,-soname,libwave_call.so", + "-o", + "z-first/libwave_call.so", + ]); + fs::write(root.join("main.c"), "extern int call(void); int main(void) { return call(); }") + .unwrap(); + let target = "x86_64-unknown-linux-gnu"; + for (name, flag, provider) in [ + ("rpath", "-Wl,--disable-new-dtags", "z-first"), + ("runpath", "-Wl,--enable-new-dtags", "sdk/lib"), + ] { + cc(&[ + "main.c", + "-Lz-first", + "-lwave_call", + "-Wl,-rpath-link,z-first", + flag, + "-Wl,-rpath,$ORIGIN/z-first:${ORIGIN}/a-second", + "-o", + "program", + ]); + let program = root.join("program"); + let info = wave_tools::binary::inspect(&program, Some(target)).unwrap(); + assert_eq!(info.runtime_paths(), ["$ORIGIN/z-first", "${ORIGIN}/a-second"]); + assert_eq!(info.runpaths.is_empty(), name == "rpath"); + let stage = root.join(name); + fs::create_dir(&stage).unwrap(); + let staged = stage.join("program"); + fs::copy(&program, &staged).unwrap(); + wave_tools::package::runtime_closure( + &stage, + target, + &root.join("sdk"), + &[(program, staged.clone())], + ) + .unwrap(); + let libs = stage.join("llvm/lib"); + assert_eq!( + storage::digest(&libs.join("libwave_value.so")).unwrap(), + storage::digest(&root.join(provider).join("libwave_value.so")).unwrap(), + "{name} provider" + ); + let status = Command::new(staged).env("LD_LIBRARY_PATH", libs).status().unwrap(); + assert_eq!(status.code(), Some(if name == "rpath" { 22 } else { 11 })); + } +} + +#[cfg(target_os = "macos")] +#[test] +fn macos_package_uses_the_main_executable_for_transitive_dylibs() { + let work = tempfile::tempdir().unwrap(); + let root = work.path(); + for path in ["app/lib", "app/plugins", "app/providers", "stage"] { + fs::create_dir_all(root.join(path)).unwrap(); + } + let target = + if cfg!(target_arch = "aarch64") { "aarch64-apple-darwin" } else { "x86_64-apple-darwin" }; + let clang = |args: &[&str]| { + let output = Command::new("clang") + .args(args) + .arg("-Wl,-headerpad_max_install_names") + .current_dir(root) + .output() + .unwrap(); + assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); + }; + fs::write(root.join("value.c"), "int value(void) { return 22; }").unwrap(); + fs::write( + root.join("plugin.c"), + "extern int value(void); int plugin(void) { return value(); }", + ) + .unwrap(); + fs::write( + root.join("lib.c"), + "extern int plugin(void); int library(void) { return plugin(); }", + ) + .unwrap(); + fs::write( + root.join("main.c"), + "extern int library(void); int main(void) { return library() != 22; }", + ) + .unwrap(); + clang(&[ + "-dynamiclib", + "value.c", + "-Wl,-install_name,@rpath/value.dylib", + "-o", + "app/providers/value.dylib", + ]); + clang(&[ + "-dynamiclib", + "plugin.c", + "app/providers/value.dylib", + "-Wl,-install_name,@executable_path/plugins/plugin.dylib", + "-o", + "app/plugins/plugin.dylib", + ]); + clang(&[ + "-dynamiclib", + "lib.c", + "app/plugins/plugin.dylib", + "-Wl,-install_name,@loader_path/lib/library.dylib", + "-o", + "app/lib/library.dylib", + ]); + clang(&[ + "main.c", + "app/lib/library.dylib", + "-Wl,-rpath,@executable_path/providers", + "-o", + "app/program", + ]); + fs::create_dir_all(root.join("sdk/bin")).unwrap(); + fs::write(root.join("tool.c"), "int main(void) { return 0; }").unwrap(); + clang(&["tool.c", "-o", "tool"]); + for name in ["ld64.lld", "ld.lld", "llc", "llvm-as", "llvm-mc"] { + fs::copy(root.join("tool"), root.join("sdk/bin").join(name)).unwrap(); + } + let stage = root.join("stage"); + let installed = Command::new(env!("CARGO_BIN_EXE_wave-tools")) + .args(["install", "--target", target, "--binary"]) + .arg(root.join("app/program")) + .arg("--llvm-prefix") + .arg(root.join("sdk")) + .arg("--prefix") + .arg(&stage) + .env("WAVE_LLVM_BIN", root.join("sdk/bin")) + .env_remove("WAVE_WINDOWS_LLVM_BIN") + .env_remove("MESON_INSTALL_DRY_RUN") + .output() + .unwrap(); + assert!(installed.status.success(), "{}", String::from_utf8_lossy(&installed.stderr)); + let payload = stage.join("bin"); + for name in ["library.dylib", "plugin.dylib", "value.dylib"] { + assert!(payload.join("llvm/lib").join(name).is_file()); + } + fs::remove_dir_all(root.join("app")).unwrap(); + assert!(Command::new(payload.join("wavec")).current_dir(&stage).status().unwrap().success()); +} diff --git a/tools/tests/publication.rs b/tools/tests/publication.rs index 09da29bd..c130f8f5 100644 --- a/tools/tests/publication.rs +++ b/tools/tests/publication.rs @@ -363,6 +363,39 @@ fn generation_has_nine_archives_and_twenty_nine_bound_assets() { } } +#[test] +fn release_assets_require_source_for_revision_and_reject_malformed_sidecars() { + use wave_tools::checks::release_assets; + let dir = tempfile::tempdir().unwrap(); + let (staged, _) = generation(dir.path(), 'a', 1); + let input = staged.parent().unwrap(); + let version = "0.0.1-alpha-dev"; + let sha = source('a'); + assert_eq!(release_assets(input, version, None, None).unwrap(), 9); + assert_eq!(release_assets(input, version, Some(&sha), Some(4)).unwrap(), 9); + assert!(release_assets(input, version, Some(&sha), Some(5)).is_err()); + assert!(release_assets(input, version, None, Some(4)) + .unwrap_err() + .to_string() + .contains("--source")); + + let sums = input.join("SHA256SUMS"); + std::fs::write(&sums, "previous manifest").unwrap(); + let name = format!("wave-v{version}-x86_64-linux-gnu.tar.gz"); + let sidecar = input.join(format!("{name}.sha256")); + let digest = storage::digest(&input.join(&name)).unwrap(); + for record in [ + format!("{}한 {name}", "a".repeat(63)), + format!("{} {name}", "g".repeat(64)), + "short".to_string(), + format!("{digest} incorrect"), + ] { + std::fs::write(&sidecar, record).unwrap(); + assert!(release_assets(input, version, None, None).is_err()); + assert_eq!(std::fs::read_to_string(&sums).unwrap(), "previous manifest"); + } +} + #[test] fn recoverable_promotion_retains_the_old_release_until_verified_uploads() { for fault in ["upload", "digest", "lost-response", "none"] { diff --git a/tools/tests/sdk.rs b/tools/tests/sdk.rs index ebb05e27..fb54e387 100644 --- a/tools/tests/sdk.rs +++ b/tools/tests/sdk.rs @@ -21,6 +21,68 @@ fn archive(path: &Path, links: &[(&str, &str)]) { builder.finish().unwrap(); } +#[test] +fn gzip_members_are_read_and_verified_through_the_last_trailer() { + use flate2::{write::GzEncoder, Compression}; + use std::io::Write; + + let member = |bytes: &[u8]| { + let mut gzip = GzEncoder::new(Vec::new(), Compression::fast()); + gzip.write_all(bytes).unwrap(); + gzip.finish().unwrap() + }; + let dir = tempfile::tempdir().unwrap(); + let tar = dir.path().join("test.tar"); + archive(&tar, &[]); + let bytes = fs::read(tar).unwrap(); + let input = dir.path().join("test.tar.gz"); + for (i, gzip) in [ + member(&bytes), + [member(&bytes[..515]), member(&bytes[515..])].concat(), + [member(&bytes), member(&[0; 512])].concat(), + ] + .into_iter() + .enumerate() + { + fs::write(&input, &gzip).unwrap(); + let output = dir.path().join(format!("valid-{i}")); + sdk::extract(&input, &output, false).unwrap(); + assert_eq!(fs::read(output.join("llvm/bin/tool")).unwrap(), b"PAYLOAD"); + + let trailer = gzip.len() - 8; + let mut damaged = gzip.clone(); + damaged[trailer] ^= 1; + for bad in [&damaged[..], &gzip[..trailer]] { + fs::write(&input, bad).unwrap(); + let output = dir.path().join("refused"); + assert!(sdk::extract(&input, &output, false).is_err()); + assert!(!output.exists()); + } + } +} + +#[test] +fn zip_payload_crc_is_verified_before_activation() { + use std::io::{Cursor, Write}; + let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new())); + let options = + zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); + zip.start_file("tool", options).unwrap(); + zip.write_all(b"PAYLOAD").unwrap(); + let mut bytes = zip.finish().unwrap().into_inner(); + let dir = tempfile::tempdir().unwrap(); + let input = dir.path().join("tool.zip"); + fs::write(&input, &bytes).unwrap(); + sdk::extract(&input, &dir.path().join("valid"), false).unwrap(); + let data = bytes.windows(7).position(|window| window == b"PAYLOAD").unwrap(); + bytes[data] ^= 1; + fs::write(&input, bytes).unwrap(); + let output = dir.path().join("refused"); + assert!(sdk::extract(&input, &output, false).is_err()); + assert!(!output.exists()); + assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 2); +} + #[test] fn extraction_retains_regular_bytes_permissions_and_rejects_links_by_default() { let dir = tempfile::tempdir().unwrap();