diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..1ffbf85 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,47 @@ +# Derived from MAINTAINERS. Update both in the same pull request. +# Review requests only; repository rules are configured separately. +* @LunaStev + +# CLI and Commands +/src/ @LunaStev + +# Manifest, WSON and Lockfile +/manifest/ @LunaStev +/wson/ @LunaStev +/lockfile/ @LunaStev + +# Dependency Resolution and Git +/resolver/ @LunaStev +/source/ @LunaStev + +# Compiler and Toolchain Integration +/compiler/ @LunaStev +/toolchain/ @LunaStev +/process/ @LunaStev +/diagnostic/ @LunaStev + +# Project State and Artifacts +/state/ @LunaStev + +# Tests and Examples +/tests/ @LunaStev +/examples/ @LunaStev + +# Release and CI +/.github/ @LunaStev +/Cargo.toml @LunaStev +/Cargo.lock @LunaStev +/rust-toolchain.toml @LunaStev +/meson.build @LunaStev +/meson.options @LunaStev +/platforms.json @LunaStev +/tools/ @LunaStev +/RELEASING.md @LunaStev + +# Documentation and Community +/*.md @LunaStev +/docs/ @LunaStev +/MAINTAINERS @LunaStev +/COPYRIGHT @LunaStev +/NOTICE @LunaStev +/ai.txt @LunaStev diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml new file mode 100644 index 0000000..17aef84 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug.yml @@ -0,0 +1,57 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 +name: "Bug report" +description: "Report a reproducible defect" +labels: ["bug"] +body: + - type: markdown + attributes: + value: | + Remove credentials and private source before posting. Security vulnerabilities belong in [private reporting](https://github.com/wavefnd/Vex/security/advisories/new), not this public form. + - type: textarea + id: environment + attributes: + label: "Environment" + description: "Vex version/commit, wavec version and selection, OS and architecture." + validations: + required: true + - type: textarea + id: command + attributes: + label: "Command and reproduction" + description: "Commands and minimal steps, starting from a prepared or new project." + validations: + required: true + - type: textarea + id: manifest + attributes: + label: "Manifest and source" + description: "Minimal vex.ws and relevant source; remove secrets." + render: text + validations: + required: false + - type: textarea + id: dependency + attributes: + label: "Dependencies and lockfile" + description: "For dependency bugs: path/Git source, selectors, fetch/update history, locked/offline flags, and a sanitized vex.lock." + render: text + validations: + required: false + - type: textarea + id: expected + attributes: + label: "Expected behavior" + description: "What should happen?" + validations: + required: true + - type: textarea + id: actual + attributes: + label: "Actual behavior" + description: "What happened? Include complete sanitized errors." + render: text + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..a33e010 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,9 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 +blank_issues_enabled: true +contact_links: + - name: Private security report + url: https://github.com/wavefnd/Vex/security/advisories/new + about: Report security vulnerabilities privately. diff --git a/.github/ISSUE_TEMPLATE/design.yml b/.github/ISSUE_TEMPLATE/design.yml new file mode 100644 index 0000000..675e03b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/design.yml @@ -0,0 +1,33 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 +name: "Design discussion" +description: "Discuss a contract or architecture change" +labels: ["discussion"] +body: + - type: markdown + attributes: + value: | + Remove credentials and private source before posting. Security vulnerabilities belong in [private reporting](https://github.com/wavefnd/Vex/security/advisories/new), not this public form. + - type: textarea + id: problem + attributes: + label: "Problem and scope" + description: "Which Vex contract needs a decision, and why?" + validations: + required: true + - type: textarea + id: options + attributes: + label: "Options and recommendation" + description: "Compare behavior, compatibility, ownership, failure recovery and tradeoffs." + validations: + required: true + - type: textarea + id: validation + attributes: + label: "Acceptance and validation" + description: "How would we prove the design works on affected platforms?" + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/feature.yml b/.github/ISSUE_TEMPLATE/feature.yml new file mode 100644 index 0000000..11c812e --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature.yml @@ -0,0 +1,33 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 +name: "Feature request" +description: "Propose a user-facing improvement" +labels: ["feature request"] +body: + - type: markdown + attributes: + value: | + Remove credentials and private source before posting. Security vulnerabilities belong in [private reporting](https://github.com/wavefnd/Vex/security/advisories/new), not this public form. + - type: textarea + id: problem + attributes: + label: "Problem" + description: "Describe the use case and current limitation." + validations: + required: true + - type: textarea + id: proposal + attributes: + label: "Proposed behavior" + description: "Examples of commands or manifests are helpful." + validations: + required: true + - type: textarea + id: alternatives + attributes: + label: "Alternatives and compatibility" + description: "Optional alternatives, affected platforms or existing workflows." + validations: + required: false diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fc9b245..f44af12 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -217,3 +217,15 @@ GitHub's API and signature metadata receive the merge exception. Synthetic PR merge refs are not used as contribution heads. No DCO application or repository write token is used. Repair your own missing certification with `git commit --amend -s`, or rebase and sign off the affected contribution commits. + +## Ownership and issue reports + +`MAINTAINERS` is the authoritative subsystem map. When paths or maintainers +change, update it and `.github/CODEOWNERS` in the same PR. CODEOWNERS requests +review; it does not grant repository permissions or configure a bypass. Check +GitHub's CODEOWNERS validation on the branch after pushing. + +Use the bug, feature or design issue forms. Minimal manifests, sanitized +lockfiles and exact commands help reproduce dependency failures. Optional +fields may be left empty. Report vulnerabilities through the private channel +in [SECURITY.md](SECURITY.md). diff --git a/Cargo.lock b/Cargo.lock index e197725..d828137 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -96,12 +96,14 @@ checksum = "9cbe37c69085a508a1bbaa07ad57ec34a2d9d277da94a830b031fb08cac16ba1" [[package]] name = "compiler" -version = "0.0.2-beta" +version = "0.0.3-beta" dependencies = [ "diagnostic", "process", + "semver", "serde_json", "sha2", + "source", "state", "toolchain", ] @@ -147,7 +149,7 @@ dependencies = [ [[package]] name = "diagnostic" -version = "0.0.2-beta" +version = "0.0.3-beta" [[package]] name = "digest" @@ -411,13 +413,14 @@ checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" [[package]] name = "lockfile" -version = "0.0.2-beta" +version = "0.0.3-beta" dependencies = [ "diagnostic", "serde", "serde_json", "sha2", "source", + "state", "wson", ] @@ -429,7 +432,7 @@ checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" [[package]] name = "manifest" -version = "0.0.2-beta" +version = "0.0.3-beta" dependencies = [ "diagnostic", "semver", @@ -507,7 +510,7 @@ dependencies = [ [[package]] name = "process" -version = "0.0.2-beta" +version = "0.0.3-beta" dependencies = [ "libc", "windows-sys", @@ -553,7 +556,7 @@ checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" [[package]] name = "resolver" -version = "0.0.2-beta" +version = "0.0.3-beta" dependencies = [ "diagnostic", "lockfile", @@ -665,7 +668,7 @@ checksum = "ba467056f1b547ed52077911161fc86985becbc60e8e1857c8a144dab0def891" [[package]] name = "source" -version = "0.0.2-beta" +version = "0.0.3-beta" dependencies = [ "percent-encoding", "serde", @@ -680,7 +683,7 @@ checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" [[package]] name = "state" -version = "0.0.2-beta" +version = "0.0.3-beta" dependencies = [ "libc", "process", @@ -745,7 +748,7 @@ dependencies = [ [[package]] name = "toolchain" -version = "0.0.2-beta" +version = "0.0.3-beta" dependencies = [ "flate2", "process", @@ -759,9 +762,9 @@ dependencies = [ [[package]] name = "typed-path" -version = "0.12.3" +version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" +checksum = "54ec2755506471f54baf5e4bb5499d8e510cc1caf271270e778a736bd2d7336c" [[package]] name = "typenum" @@ -795,7 +798,7 @@ checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" [[package]] name = "vex" -version = "0.0.2-beta" +version = "0.0.3-beta" dependencies = [ "colorex", "compiler", @@ -932,7 +935,7 @@ checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" [[package]] name = "wson" -version = "0.0.2-beta" +version = "0.0.3-beta" dependencies = [ "serde_json", "wson_rs", @@ -1038,9 +1041,9 @@ dependencies = [ [[package]] name = "zip" -version = "9.0.4" +version = "9.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a954114b47a54df49f83d2722814e86b23d4bb1b54a1b90fb7d92b41619ddc22" +checksum = "6e04976da629d3b04204ba8105b396a193af8ad2583b2c79bfb3ab8af580a11e" dependencies = [ "crc32fast", "flate2", diff --git a/Cargo.toml b/Cargo.toml index 39b3253..c79c9d1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,7 +20,7 @@ members = ["diagnostic", ".", "manifest", "lockfile", "resolver", "compiler", "t resolver = "2" [workspace.package] -version = "0.0.2-beta" +version = "0.0.3-beta" edition = "2021" rust-version = "1.96.0" license = "MPL-2.0" diff --git a/MAINTAINERS b/MAINTAINERS index ff9ca60..667b5b0 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -1,42 +1,53 @@ +# Authoritative subsystem ownership map. Keep .github/CODEOWNERS in sync. + [CLI and Commands] M: LunaStev -F: src/main.rs -F: src/commands/ -F: src/ui.rs +F: /src/ -[Manifest and Lockfile] +[Manifest, WSON and Lockfile] M: LunaStev -F: src/manifest.rs -F: src/lockfile.rs +F: /manifest/ +F: /wson/ +F: /lockfile/ [Dependency Resolution and Git] M: LunaStev -F: src/resolver.rs -F: tests/git_*.rs +F: /resolver/ +F: /source/ + +[Compiler and Toolchain Integration] +M: LunaStev +F: /compiler/ +F: /toolchain/ +F: /process/ +F: /diagnostic/ + +[Project State and Artifacts] +M: LunaStev +F: /state/ -[wavec Integration] +[Tests and Examples] M: LunaStev -F: src/wavec.rs -F: src/validate.rs -F: src/commands/build.rs -F: src/commands/check.rs -F: src/commands/run.rs +F: /tests/ +F: /examples/ [Release and CI] M: LunaStev -F: .github/ -F: Cargo.toml -F: Cargo.lock -F: meson.build -F: meson.options -F: tools/ -F: tests/tooling/ -F: RELEASING.md +F: /.github/ +F: /Cargo.toml +F: /Cargo.lock +F: /rust-toolchain.toml +F: /meson.build +F: /meson.options +F: /platforms.json +F: /tools/ +F: /RELEASING.md [Documentation and Community] M: LunaStev -F: *.md -F: MAINTAINERS -F: COPYRIGHT -F: NOTICE -F: ai.txt +F: /*.md +F: /docs/ +F: /MAINTAINERS +F: /COPYRIGHT +F: /NOTICE +F: /ai.txt diff --git a/SECURITY.md b/SECURITY.md index 73d374a..8a98adb 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,13 +2,14 @@ ## Supported versions -Vex `v0.0.1` is the current public release (published 2026-08-23). Security -fixes for that release are made on the latest `master` branch and ship in the +Vex `v0.0.2-beta` is the current public release (published 2026-10-15). Security +fixes for supported releases are made on the latest `master` branch and ship in the next published release when needed. Pre-`v0.0.1` snapshots and older commits are not supported. | Version | Supported | |---|---| +| `v0.0.2-beta` | Yes (current) | | `v0.0.1` | Yes | | `master` | Best effort (development tip) | | Pre-`v0.0.1` snapshots and older commits | No | diff --git a/THIRD_PARTY_LICENSES b/THIRD_PARTY_LICENSES index 538a544..5f59b2b 100644 --- a/THIRD_PARTY_LICENSES +++ b/THIRD_PARTY_LICENSES @@ -1,7 +1,7 @@ Third-party dependency notices for Vex ===================================== -Cargo.lock SHA-256 (LF): 2603e5dfcd8fd9e451a03b538001787c14326665debd9872cd02a4ddfc865284 +Cargo.lock SHA-256 (LF): 0afef4f6ae2684eb0e9f32a34542f0e03cfd0eb34c3d8128b4b4a36de19fdcc4 Generated by tools/dependency_notices.py from Cargo's locked package sources. Includes build-time and platform-specific dependencies; a given binary may @@ -448,7 +448,7 @@ Declared license: Unicode-3.0 Source: registry+https://github.com/rust-lang/crates.io-index LICENSE: Text 34 -typed-path 0.12.3 +typed-path 0.12.4 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 38 @@ -598,7 +598,7 @@ Declared license: Unicode-3.0 Source: registry+https://github.com/rust-lang/crates.io-index LICENSE: Text 34 -zip 9.0.4 +zip 9.0.5 Declared license: MIT Source: registry+https://github.com/rust-lang/crates.io-index LICENSE: Text 67 diff --git a/compiler/Cargo.toml b/compiler/Cargo.toml index e28b768..b1a2cce 100644 --- a/compiler/Cargo.toml +++ b/compiler/Cargo.toml @@ -18,3 +18,6 @@ process.workspace = true serde_json.workspace = true state.workspace = true sha2 = "0.11.1" +semver = "1" + +source.workspace = true diff --git a/compiler/src/archive.rs b/compiler/src/archive.rs new file mode 100644 index 0000000..ddbe8bb --- /dev/null +++ b/compiler/src/archive.rs @@ -0,0 +1,315 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +//! Target-aware static archives. Native/system libraries remain separate inputs. +use diagnostic::Error; +use serde_json::{json, Value}; +use std::{ + fs, + path::{Path, PathBuf}, + process::Command, + time::Duration, +}; +#[derive(Clone, Debug)] +pub struct ArchivePlan { + pub output: PathBuf, + pub program: PathBuf, + pub format: String, + pub target: String, + pub identity: String, + pub version: String, + llvm: bool, +} +fn executable(name: &Path) -> Option { + let candidates = if name.is_absolute() || name.components().count() > 1 { + vec![name.into()] + } else { + std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()) + .map(|d| d.join(name)) + .collect() + }; + for candidate in candidates { + #[cfg(windows)] + let candidate = if candidate.extension().is_none() { + candidate.with_extension("exe") + } else { + candidate + }; + if !candidate.is_file() { + continue; + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + if fs::metadata(&candidate).ok()?.permissions().mode() & 0o111 == 0 { + continue; + } + } + return std::env::current_dir().ok().map(|cwd| cwd.join(candidate)); + } + None +} +impl ArchivePlan { + pub fn select( + requested: Option<&Path>, + compiler: &Path, + output: PathBuf, + target: &str, + format: &str, + ) -> Result { + if !matches!(format, "elf" | "macho" | "coff") { + return Err(Error::resolution( + "static output requires an ELF, Mach-O, or COFF target", + )); + } + let name = if format == "coff" { + "llvm-lib" + } else { + "llvm-ar" + }; + let mut candidates = Vec::new(); + if let Some(requested) = requested { + candidates.push(requested.into()); + } else { + if let Some(parent) = compiler.parent() { + for base in [ + parent.to_owned(), + parent.join("llvm/bin"), + parent.join("../llvm/bin"), + ] { + candidates.push(base.join(name)); + } + } + candidates.push(PathBuf::from(name)); + if format == "elf" { + candidates.push(PathBuf::from("ar")); + } + } + let program = candidates + .iter() + .find_map(|p| executable(p)) + .ok_or_else(|| { + Error::environment(format!( + "static output requires {name}; install it or configure build.archiver" + )) + })?; + let response = process::output( + Command::new(&program).arg(if format == "coff" { "/?" } else { "--version" }), + Duration::from_secs(60), + ) + .map_err(Error::environment)?; + let text = format!( + "{}{}", + String::from_utf8_lossy(&response.stdout), + String::from_utf8_lossy(&response.stderr) + ); + let llvm = text.contains("LLVM"); + let supported = llvm + || (format == "elf" && text.contains("GNU ar")) + || (format == "coff" && text.contains("Library Manager")); + if !response.status.success() || !supported { + return Err(Error::environment( + "archiver cannot prove support for the requested deterministic archive format", + )); + } + let identity = + crate::identity::file_digest(&program.canonicalize().map_err(Error::environment)?)?; + Ok(Self { + output, + program, + format: format.into(), + target: target.into(), + identity, + version: text.trim().into(), + llvm, + }) + } + pub fn value(&self, members: &[PathBuf]) -> Value { + json!({"program":self.program,"sha256":self.identity,"version":self.version,"format":self.format,"target":self.target,"output":self.output,"members":members,"deterministic":true,"symbol_index":true}) + } + pub fn execute(&self, members: &[PathBuf], output: &Path) -> Result<(), Error> { + if members.is_empty() { + return Err(Error::compiler("static output has no Wave objects")); + } + if crate::identity::file_digest(&self.program.canonicalize().map_err(Error::environment)?)? + != self.identity + { + return Err(Error::environment("archiver changed after planning")); + } + state::ensure_tree( + output + .parent() + .ok_or_else(|| Error::internal("archive parent is missing"))?, + ) + .map_err(Error::environment)?; + let cwd = std::env::current_dir().map_err(Error::environment)?; + let output = cwd.join(output); + let members_absolute = members.iter().map(|p| cwd.join(p)).collect::>(); + let mut common = members_absolute[0] + .parent() + .ok_or_else(|| Error::internal("archive member lacks parent"))?; + while members_absolute.iter().any(|p| !p.starts_with(common)) { + common = common + .parent() + .ok_or_else(|| Error::internal("archive members have no common directory"))?; + } + let arguments = members_absolute + .iter() + .map(|p| { + p.strip_prefix(common) + .map(Path::to_path_buf) + .map_err(Error::internal) + }) + .collect::, _>>()?; + let mut command = Command::new(&self.program); + command.current_dir(common); + if self.format == "coff" { + if !self.llvm { + command.arg("/Brepro"); + } + command.arg(format!("/OUT:{}", output.display())); + } else { + if self.llvm { + command.arg(if self.format == "macho" { + "--format=darwin" + } else { + "--format=gnu" + }); + } + command.arg("rcsD").arg(&output); + } + #[cfg(unix)] + for member in members { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(member, fs::Permissions::from_mode(0o644)) + .map_err(Error::environment)?; + } + command.args(arguments); + let status = process::status(&mut command, Some(Duration::from_secs(300)), false) + .map_err(Error::environment)?; + if !status.success() { + return Err(Error::compiler(format!("archiver failed with {status}"))); + } + self.verify(members, &output) + } + fn verify(&self, members: &[PathBuf], output: &Path) -> Result<(), Error> { + state::reject_link(output).map_err(Error::environment)?; + let data = fs::read(output).map_err(Error::environment)?; + if !data.starts_with(b"!\n") { + return Err(Error::compiler( + "archiver produced an invalid or thin archive", + )); + } + let mut remaining = std::collections::BTreeMap::new(); + for member in members { + *remaining + .entry(crate::identity::file_digest(member)?) + .or_insert(0usize) += 1; + } + let mut offset = 8; + let mut index = false; + while offset < data.len() { + let header = data + .get(offset..offset + 60) + .ok_or_else(|| Error::compiler("truncated archive member"))?; + if &header[58..60] != b"`\n" { + return Err(Error::compiler("invalid archive member header")); + } + let number = |part: &[u8]| { + std::str::from_utf8(part) + .ok() + .and_then(|s| s.trim().parse::().ok()) + }; + let size = number(&header[48..58]) + .ok_or_else(|| Error::compiler("invalid archive member length"))?; + let end = offset + .checked_add(60) + .and_then(|n| n.checked_add(size)) + .ok_or_else(|| Error::compiler("archive length overflow"))?; + if number(&header[16..28]).unwrap_or(0) != 0 { + return Err(Error::compiler( + "archiver did not produce deterministic member timestamps", + )); + } + let mut body = data + .get(offset + 60..end) + .ok_or_else(|| Error::compiler("truncated archive member bytes"))?; + let name = std::str::from_utf8(&header[..16]) + .map_err(Error::compiler)? + .trim(); + let mut symbol = name == "/" || name == "/SYM64/" || name.starts_with("__.SYMDEF"); + if let Some(n) = name.strip_prefix("#1/") { + let n = n.trim().parse::().map_err(Error::compiler)?; + let long = body + .get(..n) + .ok_or_else(|| Error::compiler("invalid BSD archive member name"))?; + symbol = long.starts_with(b"__.SYMDEF"); + body = body + .get(n..) + .ok_or_else(|| Error::compiler("invalid BSD member payload"))?; + } + if symbol { + index = true; + } else if name != "//" { + let valid = match self.format.as_str() { + "elf" => { + let machine = if self.target.starts_with("x86_64") { + 62u16 + } else if self.target.starts_with("aarch64") { + 183 + } else if self.target.starts_with("riscv64") { + 243 + } else if self.target.starts_with("loongarch64") { + 258 + } else { + 0 + }; + body.starts_with(b"\x7fELF") + && body.get(4..6) == Some(&[2, 1][..]) + && body.get(18..20) == Some(&machine.to_le_bytes()[..]) + } + "macho" => { + let cpu = if self.target.starts_with("aarch64") { + 0x0100000cu32 + } else { + 0x01000007u32 + }; + body.starts_with(b"\xcf\xfa\xed\xfe") + && body.get(4..8) == Some(&cpu.to_le_bytes()[..]) + } + "coff" => body.starts_with(if self.target.starts_with("aarch64") { + b"\x64\xaa" + } else { + b"\x64\x86" + }), + _ => false, + }; + if !valid { + return Err(Error::compiler( + "archive contains an object for the wrong target format", + )); + } + use sha2::Digest; + let digest = sha2::Sha256::digest(body) + .iter() + .map(|b| format!("{b:02x}")) + .collect::(); + let count = remaining + .get_mut(&digest) + .filter(|n| **n > 0) + .ok_or_else(|| { + Error::compiler("archive contains an unexpected or duplicate object") + })?; + *count -= 1; + } + offset = end + (end % 2); + } + if !index || remaining.values().any(|n| *n != 0) { + return Err(Error::compiler( + "archive lacks its complete Wave objects or symbol index", + )); + } + Ok(()) + } +} diff --git a/compiler/src/freshness.rs b/compiler/src/freshness.rs index 20eacf2..07132ac 100644 --- a/compiler/src/freshness.rs +++ b/compiler/src/freshness.rs @@ -75,6 +75,7 @@ fn tree(hash: &mut Sha256, path: &Path, sources: bool) -> Result<(), String> { || path.extension().is_some_and(|e| e == "wave") || name == "vex.ws" || name == "vex.lock" + || name == "vex.toolchain.lock" { file(hash, &path)?; } @@ -90,7 +91,9 @@ impl Inputs { sources.sort(); sources.dedup(); let output = process::output( - Command::new(compiler.path()).args(["print", "std-path", "--format=json"]), + compiler + .command() + .args(["print", "std-path", "--format=json"]), Duration::from_secs(60), )?; if !output.status.success() { @@ -204,6 +207,11 @@ pub(crate) fn key( if !plan["sysroot"].is_null() { return Err("SDK/sysroot contents are not fully declared".into()); } + if !plan["vex_archive"].is_null() { + return Err( + "archiver runtime closure is not fully declared; compile conservatively".into(), + ); + } let mut hash = Sha256::new(); bytes(&mut hash, base.as_bytes()); if !plan["link"].is_null() { diff --git a/compiler/src/identity.rs b/compiler/src/identity.rs new file mode 100644 index 0000000..7f213f9 --- /dev/null +++ b/compiler/src/identity.rs @@ -0,0 +1,249 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +//! Prepared compiler/std identities; observation never installs a toolchain. +use diagnostic::Error; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use std::{ + fs, + io::Read, + path::{Path, PathBuf}, + time::Duration, +}; + +pub const FILE: &str = "vex.toolchain.lock"; +fn hex(bytes: impl AsRef<[u8]>) -> String { + bytes.as_ref().iter().map(|b| format!("{b:02x}")).collect() +} +pub fn file_digest(path: &Path) -> Result { + state::reject_link(path).map_err(Error::environment)?; + let mut input = state::open_regular(path).map_err(Error::environment)?; + if !input.metadata().map_err(Error::environment)?.is_file() { + return Err(Error::environment("identity input must be a regular file")); + } + let mut hash = Sha256::new(); + let mut buffer = [0; 65536]; + loop { + if process::cancelled() { + return Err(Error::new( + diagnostic::Category::Cancelled, + "toolchain hashing cancelled", + )); + } + let n = input.read(&mut buffer).map_err(Error::environment)?; + if n == 0 { + break; + } + hash.update(&buffer[..n]); + } + Ok(hex(hash.finalize())) +} +pub fn tree_digest(root: &Path) -> Result { + state::reject_link(root).map_err(Error::environment)?; + let mut pending = vec![root.to_owned()]; + let mut files = Vec::new(); + while let Some(directory) = pending.pop() { + for entry in fs::read_dir(directory).map_err(Error::environment)? { + let path = entry.map_err(Error::environment)?.path(); + if path.file_name().is_some_and(|n| n == ".git") { + continue; + } + state::reject_link(&path).map_err(Error::environment)?; + let metadata = fs::symlink_metadata(&path).map_err(Error::environment)?; + if metadata.is_dir() { + pending.push(path); + } else if metadata.is_file() { + files.push(path); + } else { + return Err(Error::environment("std identity contains a special file")); + } + if pending.len() + files.len() > 65536 { + return Err(Error::environment( + "std identity exceeds 65536 files/directories", + )); + } + } + } + files.sort(); + let mut hash = Sha256::new(); + hash.update(b"vex.std-tree.v1\0"); + for path in files { + let name = path + .strip_prefix(root) + .map_err(Error::internal)? + .to_str() + .ok_or_else(|| Error::resolution("std identity requires UTF-8 paths"))? + .replace('\\', "/"); + hash.update((name.len() as u64).to_le_bytes()); + hash.update(name.as_bytes()); + hash.update(file_digest(&path)?.as_bytes()); + } + Ok(hex(hash.finalize())) +} +pub fn host() -> String { + source::graph::Context::host().triple +} +fn valid_digest(value: &Value) -> bool { + value.as_str().is_some_and(|s| { + s.len() == 64 + && s.bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + }) +} +pub fn read(project: &Path) -> Result, Error> { + let path = project.join(FILE); + state::reject_link(&path).map_err(Error::environment)?; + let file = match state::open_regular(&path) { + Ok(f) => f, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(Error::environment(e)), + }; + let mut bytes = Vec::new(); + file.take(8 * 1024 * 1024 + 1) + .read_to_end(&mut bytes) + .map_err(Error::environment)?; + if bytes.len() > 8 * 1024 * 1024 { + return Err(Error::resolution("toolchain lock exceeds 8 MiB")); + } + let value: Value = serde_json::from_slice(&bytes).map_err(Error::resolution)?; + if value["schema_version"] != 1 + || value.as_object().is_none_or(|o| { + o.keys() + .any(|k| !matches!(k.as_str(), "schema_version" | "hosts")) + }) + { + return Err(Error::resolution("unsupported toolchain lock schema")); + } + let hosts = value["hosts"] + .as_object() + .ok_or_else(|| Error::resolution("toolchain lock requires host identities"))?; + for (host, identity) in hosts { + source::graph::Context::new(host).map_err(Error::resolution)?; + if identity + .get("source_revision") + .is_some_and(|value| !value.is_null()) + { + return Err(Error::resolution("source revision pins require a reliable compiler provenance contract; this schema currently records null")); + } + if ["compiler_sha256", "std_sha256", "compiler_version"] + .iter() + .any(|key| identity.get(*key).is_none()) + { + return Err(Error::resolution( + "toolchain identity is missing a required field", + )); + } + if !valid_digest(&identity["compiler_sha256"]) + || (!identity["std_sha256"].is_null() && !valid_digest(&identity["std_sha256"])) + || identity["compiler_version"] + .as_str() + .is_none_or(|s| semver::Version::parse(s).is_err()) + || identity.as_object().is_none_or(|o| { + o.keys().any(|k| { + !matches!( + k.as_str(), + "compiler_sha256" | "std_sha256" | "compiler_version" | "source_revision" + ) + }) + }) + { + return Err(Error::resolution("malformed pinned compiler/std identity")); + } + } + Ok(Some(value)) +} +impl crate::Compiler { + pub fn select_explicit(path: Option<&Path>) -> Result { + let Some(path) = path else { + return Self::select(); + }; + Self::from_executable(path) + } + pub fn selected_standard(&self) -> Option<&Path> { + self.standard.as_deref() + } + pub fn set_standard(&mut self, path: &Path) -> Result<(), Error> { + self.standard = Some(path.canonicalize().map_err(Error::environment)?); + self.identity = None; + Ok(()) + } + pub fn observe_identity(&mut self) -> Result { + let output = process::output( + self.command().args(["print", "std-path", "--format=json"]), + Duration::from_secs(60), + ) + .map_err(Error::environment)?; + if !output.status.success() { + return Err(Error::compiler( + "compiler cannot report the selected standard library", + )); + } + let standard: Option = + serde_json::from_slice(&output.stdout).map_err(Error::compiler)?; + if let Some(path) = standard.as_ref() { + if !path.is_absolute() || !path.is_dir() { + return Err(Error::environment( + "compiler reported an unavailable std root", + )); + } + if self + .standard + .as_ref() + .is_some_and(|explicit| explicit.canonicalize().ok() != path.canonicalize().ok()) + { + return Err(Error::compiler( + "compiler did not retain the explicitly selected std root", + )); + } + } else if self.standard.is_some() { + return Err(Error::compiler( + "compiler ignored the selected standard library", + )); + } + let std_digest = standard.as_ref().map(|p| tree_digest(p)).transpose()?; + let identity = json!({"compiler_version":self.version()?,"compiler_sha256":file_digest(&self.path.canonicalize().map_err(Error::environment)?)?,"std_sha256":std_digest,"source_revision":null}); + self.standard = standard; + self.identity = Some(identity.clone()); + Ok(identity) + } + pub fn validate_identity(&mut self, project: &Path) -> Result<(), Error> { + let Some(lock) = read(project)? else { + return Ok(()); + }; + let expected = &lock["hosts"][host()]; + if expected.is_null() { + return Err(Error::resolution(format!( + "toolchain lock has no identity for host {}", + host() + ))); + } + let observed = self.observe_identity()?; + for key in ["compiler_version", "compiler_sha256", "std_sha256"] { + if expected[key] != observed[key] { + return Err(Error::resolution(format!("selected toolchain does not match vex.toolchain.lock: {key} differs; select the pinned compiler/std pair explicitly"))); + } + } + Ok(()) + } + pub fn identity(&self) -> Option<&Value> { + self.identity.as_ref() + } + pub fn capture_identity(&mut self, project: &Path, replace: bool) -> Result { + let _guard = state::Guard::acquire(false, |_, _| {}).map_err(Error::environment)?; + let mut lock = read(project)?.unwrap_or_else(|| json!({"schema_version":1,"hosts":{}})); + let host = host(); + if !lock["hosts"][&host].is_null() && !replace { + return Err(Error::usage( + "this host is already pinned; use --replace to update its identity explicitly", + )); + } + let identity = self.observe_identity()?; + lock["hosts"][&host] = identity.clone(); + let mut bytes = serde_json::to_string_pretty(&lock).map_err(Error::internal)?; + bytes.push('\n'); + state::edit::replace(&project.join(FILE), &bytes).map_err(Error::environment)?; + Ok(identity) + } +} diff --git a/compiler/src/invocation.rs b/compiler/src/invocation.rs index d9aa7f0..5735400 100644 --- a/compiler/src/invocation.rs +++ b/compiler/src/invocation.rs @@ -74,6 +74,10 @@ fn runner_program(program: &str) -> Result { /// A validated compiler plan. Constructing it does not create build outputs. pub struct PreparedBuild { + context: crate::Compiler, + metadata: serde_json::Value, + archive: Option, + inputs: Option, freshness: Option<(String, String, crate::freshness::Inputs)>, plan: serde_json::Value, args: Vec, @@ -84,6 +88,72 @@ pub struct PreparedBuild { generation: Option, } impl PreparedBuild { + pub fn metadata(&self) -> &serde_json::Value { + &self.metadata + } + pub fn with_inputs(mut self, inputs: crate::provenance::Inputs) -> Result { + let project = std::env::current_dir().map_err(Error::environment)?; + let mut roots = vec![(project, "/vex/workspace".into())]; + if let Some(nodes) = self.metadata["source_roots"].as_array() { + for node in nodes { + roots.push(( + PathBuf::from( + node["root"] + .as_str() + .ok_or_else(|| Error::internal("source root missing"))?, + ), + format!( + "/vex/packages/{}", + node["id"] + .as_str() + .ok_or_else(|| Error::internal("source identity missing"))? + ), + )); + } + } + roots.push(( + self.context + .path() + .canonicalize() + .map_err(Error::environment)?, + "/vex/compiler".into(), + )); + if let Some(archive) = &self.archive { + roots.push(( + archive.program.canonicalize().map_err(Error::environment)?, + "/vex/archiver".into(), + )); + } + if let Some(root) = self.context.selected_standard() { + roots.push((root.into(), "/vex/std".into())); + } + self.metadata["portable_inputs"] = match inputs.portable(&roots) { + Ok(value) => value, + Err(e) if self.metadata["settings"]["reproducible"] == true => return Err(e), + Err(e) => serde_json::json!({"complete":false,"reason":e.to_string()}), + }; + self.metadata["inputs"] = inputs.value(); + self.inputs = Some(inputs); + Ok(self) + } + pub fn with_archive(mut self, archive: Option) -> Self { + if let Some(archive) = archive { + self.plan["vex_archive"] = archive.value(&self.outputs); + self.outputs.push(archive.output.clone()); + self.archive = Some(archive); + } + self + } + pub fn with_metadata(mut self, metadata: serde_json::Value) -> Self { + self.metadata = metadata; + self + } + pub fn result_key(&self) -> Result { + let mut paths = self.outputs.clone(); + paths.extend(self.optional_outputs.clone()); + crate::publication::key(&paths, &self.root) + } + pub fn with_fingerprint( mut self, base: &str, @@ -128,6 +198,10 @@ impl PreparedBuild { decision: &mut dyn FnMut(String), ) -> Result, Error> { let Self { + context, + mut metadata, + archive, + inputs: captured_inputs, freshness, plan, args, @@ -137,17 +211,76 @@ impl PreparedBuild { execution, generation, } = self; + let _ = compiler; + let compiler = &context; let wavec = &compiler.path; - state::ensure_dir(Path::new("target")).map_err(Error::environment)?; + state::ensure_tree(&root.join("target")).map_err(Error::environment)?; let mut compile_args: Vec<_> = args[..] .iter() .filter(|a| a.as_str() != "--run") .cloned() .collect(); + crate::publication::recover(&root, false)?; + let _final_preflight = state::artifacts::Batch::prepare_with_optional( + &root, + outputs.clone(), + optional_outputs.clone(), + ) + .map_err(Error::environment)?; + let (publication_generation, _publication_lease) = + if generation.is_none() && !outputs.is_empty() { + let path = create_run_generation()?; + let lease = + state::artifacts::RunLease::create(&root, &path).map_err(Error::environment)?; + (Some(path), Some(lease)) + } else { + (None, None) + }; + let final_outputs = outputs; + let final_optional = optional_outputs; + let map_output = |path: &Path| -> Result { + if let Some(stage) = &publication_generation { + let absolute = root.join(path); + let relative = + state::layout::relative_output(&root, &absolute).map_err(Error::environment)?; + Ok(root.join(stage).join("artifacts").join(relative)) + } else { + Ok(path.to_path_buf()) + } + }; + let outputs = final_outputs + .iter() + .map(|p| map_output(p)) + .collect::, _>>()?; + let optional_outputs = final_optional + .iter() + .map(|p| map_output(p)) + .collect::, _>>()?; + if publication_generation.is_some() { + let mut next_output = false; + for arg in &mut compile_args { + if next_output { + *arg = map_output(Path::new(arg))? + .to_str() + .ok_or_else(|| Error::resolution("output path is not UTF-8"))? + .to_owned(); + next_output = false; + } else if arg == "-o" { + next_output = true; + } else if let Some(path) = arg.strip_prefix("--target-dir=") { + *arg = format!("--target-dir={}", map_output(Path::new(path))?.display()); + } + } + } + let compiler_count = outputs.len() - usize::from(archive.is_some()); + let archive_output = archive + .as_ref() + .map(|a| map_output(&a.output)) + .transpose()?; let ownership = state::artifacts::Batch::prepare_with_optional( &root, outputs.clone(), - optional_outputs.iter().cloned(), + optional_outputs.clone(), ) .map_err(Error::environment)?; let reused = match freshness.as_ref() { @@ -186,9 +319,12 @@ impl PreparedBuild { let result = (|| -> Result { let status = if let Some(sink) = report.as_mut() { insert_build_flag(&mut compile_args, "--error-format=json"); - let output = - process::output_without_deadline(Command::new(wavec).args(&compile_args)) - .map_err(Error::environment)?; + let output = process::output_with_input( + compiler.build_command().args(&compile_args), + None, + compiler.input.as_deref(), + ) + .map_err(Error::environment)?; diagnostic::output::stdout(format_args!( "{}", String::from_utf8_lossy(&output.stdout) @@ -202,19 +338,26 @@ impl PreparedBuild { emit_diagnostics(&output.stderr, &mut **sink)?; output.status } else { - process::status(Command::new(wavec).args(&compile_args), None, false).map_err( - |e| { - Error::environment(format!( - "failed to execute `{}` build: {e}", - wavec.display() - )) - }, - )? + process::status_with_input( + compiler.build_command().args(&compile_args), + None, + false, + compiler.input.as_deref(), + ) + .map_err(|e| { + Error::environment(format!( + "failed to execute `{}` build: {e}", + wavec.display() + )) + })? }; Ok(status) })(); result.and_then(|status| { if status.success() { + if let (Some(archive), Some(destination)) = (&archive, &archive_output) { + archive.execute(&outputs[..compiler_count], destination)?; + } ownership.verify_outputs().map_err(Error::compiler) } else { Err(compiler_error( @@ -225,6 +368,39 @@ impl PreparedBuild { }) }; finish_compilation(compile_result, ownership.finish())?; + if let Some(inputs) = &captured_inputs { + inputs.verify()?; + } + // A pinned pair must still match after compilation, before publication. + let mut verified = context.clone(); + if let Some(before) = context.identity() { + if verified.observe_identity()? != *before { + return Err(Error::resolution("compiler/std pair changed while compilation was in progress; previous generation preserved")); + } + } + verified.validate_identity(&std::env::current_dir().map_err(Error::environment)?)?; + if let Some(stage) = publication_generation.as_ref().or(generation.as_ref()) { + if let Some(archive) = &archive { + metadata["archive"] = archive.value(&final_outputs[..compiler_count]); + } + metadata["compiler"]=verified.identity().cloned().unwrap_or_else(||serde_json::json!({"compiler_sha256":crate::identity::file_digest(compiler.path()).ok(),"std_sha256":null,"identity_complete":false})); + let mut destinations = final_outputs.clone(); + destinations.extend(final_optional.clone()); + let mut staged = outputs.clone(); + staged.extend(optional_outputs.clone()); + let result = crate::publication::publish( + &root, + &root.join(stage), + &destinations, + &staged, + metadata.clone(), + )?; + if let Some(sink) = report.as_mut() { + sink( + serde_json::json!({"event":"artifact-result","origin":"vex","result":result}), + )?; + } + } if !reused { if let Some((key, base, inputs)) = freshness.as_ref() { if inputs.fingerprint().as_deref() == Ok(base.as_str()) @@ -243,7 +419,9 @@ impl PreparedBuild { } } if let Some(sink) = report.as_mut() { - let mut outputs: Vec<_> = if let Some(output) = plan["link"]["output"].as_str() { + let mut outputs: Vec<_> = if let Some(archive) = &archive { + vec![archive.output.to_string_lossy().into_owned()] + } else if let Some(output) = plan["link"]["output"].as_str() { vec![output.to_owned()] } else { plan["compile"] @@ -254,7 +432,7 @@ impl PreparedBuild { .collect() }; outputs.extend( - optional_outputs + final_optional .iter() .filter(|path| path.is_file()) .map(|path| path.to_string_lossy().into_owned()), @@ -305,8 +483,7 @@ pub fn prepare_build( insert_build_flag(&mut dry_run_args, "--dry-run"); } insert_build_flag(&mut dry_run_args, "--error-format=json"); - let wavec = &compiler.path; - let validation_output = run_wavec_dry_run(wavec, &dry_run_args, &mut report)?; + let validation_output = run_wavec_dry_run(compiler, &dry_run_args, &mut report)?; let mut plan = plan::validate_dry_run_json_output(&validation_output.stdout, &validation_output.stderr) .map_err(|error| Error::compiler(format!("installed wavec is incompatible with Vex: {error}\nhelp: update wavec or set VEX_WAVEC=/path/to/wavec")))?; if !validation_output.stderr.is_empty() { @@ -315,8 +492,31 @@ pub fn prepare_build( String::from_utf8_lossy(&validation_output.stderr) ))?; } + if let Some(input) = compiler.input.as_ref() { + let expected: serde_json::Value = serde_json::from_slice(input).map_err(Error::internal)?; + if plan["package_graph"] != expected { + return Err(Error::compiler( + "compiler plan did not retain the selected package graph", + )); + } + } let root = std::env::current_dir().map_err(Error::environment)?; let separator = args.iter().position(|a| a == "--").unwrap_or(args.len()); + let requested = args[..separator].iter().enumerate().find_map(|(i, arg)| { + arg.strip_prefix("--target=").or_else(|| { + (arg == "--target") + .then(|| args.get(i + 1).map(String::as_str)) + .flatten() + }) + }); + if let Some(requested) = requested { + if plan["target"].as_str() != Some(requested) { + return Err(Error::compiler(format!( + "compiler target mismatch: requested `{requested}`, returned `{}`", + plan["target"].as_str().unwrap_or("") + ))); + } + } let is_run = args[..separator].iter().any(|a| a == "--run"); let execution = if is_run { let generation = @@ -388,7 +588,7 @@ pub fn prepare_build( } else { None }; - let root = std::env::current_dir().map_err(Error::environment)?; + let root = state::layout::build_root(&std::env::current_dir().map_err(Error::environment)?); let (outputs, optional_outputs) = validate_plan_outputs(&plan, &root, &args[..separator])?; validate_requested_outputs(&plan, &root, &args[..separator])?; if user_requested_dry_run && !runtime.is_empty() { @@ -406,6 +606,10 @@ pub fn prepare_build( args.extend(values.into_iter().map(serde_json::Value::String)); } Ok(PreparedBuild { + context: compiler.clone(), + metadata: serde_json::json!({}), + archive: None, + inputs: None, freshness: None, plan, args: args[..separator].to_vec(), @@ -494,7 +698,7 @@ fn validate_requested_outputs( _ => result.push(component.as_os_str()), } } - result + state::layout::path_form(&result) }; let expected = normalize(Path::new(expected)); let compile = plan["compile"].as_array().unwrap(); @@ -709,8 +913,13 @@ fn validate_output_path(output: &Path, generation: &Path) -> Result<(), Error> { } pub fn create_run_generation() -> Result { - state::ensure_dir(Path::new("target")).map_err(Error::environment)?; - let parent = Path::new("target/.vex-run"); + let root = state::layout::build_root(&std::env::current_dir().map_err(Error::environment)?); + state::ensure_tree(&root.join("target")).map_err(Error::environment)?; + let parent_path = state::layout::output( + &std::env::current_dir().map_err(Error::environment)?, + "target/.vex-run", + ); + let parent = parent_path.as_path(); state::ensure_dir(parent).map_err(Error::environment)?; loop { let time = std::time::SystemTime::now() @@ -786,18 +995,19 @@ fn emit_diagnostics( } fn run_wavec_dry_run( - wavec: &Path, + compiler: &crate::Compiler, dry_run_args: &[String], report: &mut Option<&mut dyn FnMut(serde_json::Value) -> Result<(), Error>>, ) -> Result { - let output = process::output( - Command::new(wavec).args(dry_run_args), - std::time::Duration::from_secs(60), + let output = process::output_with_input( + compiler.build_command().args(dry_run_args), + Some(std::time::Duration::from_secs(60)), + compiler.input.as_deref(), ) .map_err(|error| { Error::environment(format!( "failed to execute `{}`. Install wavec or set VEX_WAVEC=/path/to/wavec: {error}", - wavec.display() + compiler.path.display() )) })?; if let Some(sink) = report.as_mut() { @@ -808,7 +1018,7 @@ fn run_wavec_dry_run( output.status, format!( "wavec dry-run failed using `{}` [{}]: {}", - wavec.display(), + compiler.path.display(), classify_exit(output.status), combined_output(&output.stdout, &output.stderr) ), @@ -833,6 +1043,26 @@ fn combined_output(stdout: &[u8], stderr: &[u8]) -> String { #[cfg(test)] mod message_tests { + + #[cfg(windows)] + #[test] + fn requested_output_accepts_equivalent_normal_and_verbatim_windows_paths() { + let root = std::path::Path::new(r"\\?\C:\build"); + let plan = serde_json::json!({"emit":"obj","link":null, + "compile":[{"output":"target/app.o"}]}); + let args = vec![ + "--emit=obj".into(), + "-o".into(), + "C:/build/target/app.o".into(), + ]; + super::validate_requested_outputs(&plan, root, &args).unwrap(); + let other = vec![ + "--emit=obj".into(), + "-o".into(), + "C:/build/target/other.o".into(), + ]; + assert!(super::validate_requested_outputs(&plan, root, &other).is_err()); + } #[test] fn tracking_failure_never_replaces_an_existing_error_category() { for category in [ diff --git a/compiler/src/lib.rs b/compiler/src/lib.rs index 085a021..88b22bc 100644 --- a/compiler/src/lib.rs +++ b/compiler/src/lib.rs @@ -2,9 +2,14 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. // SPDX-License-Identifier: MPL-2.0 +pub mod archive; pub mod freshness; +pub mod identity; mod invocation; mod plan; +pub mod provenance; +pub mod publication; +pub mod reports; mod selection; pub use invocation::{ diff --git a/compiler/src/provenance.rs b/compiler/src/provenance.rs new file mode 100644 index 0000000..b05457b --- /dev/null +++ b/compiler/src/provenance.rs @@ -0,0 +1,256 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +//! Content snapshots and scheduler inputs, distinct from cache eligibility. +use diagnostic::Error; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use std::{ + collections::BTreeSet, + path::{Path, PathBuf}, +}; +#[derive(Clone)] +pub struct Inputs { + pub files: Vec, + pub directories: Vec, + digest: String, + pub complete_sources: bool, + complete_toolchain_paths: bool, +} +impl Inputs { + pub fn capture(plan: &Value, manifests: &[PathBuf], project: &Path) -> Result { + let mut files = BTreeSet::new(); + let mut directories = BTreeSet::new(); + let source_inputs = plan["source_inputs"].as_array(); + if let Some(inputs) = source_inputs { + for input in inputs { + let path = input + .as_str() + .ok_or_else(|| Error::compiler("source_inputs must be UTF-8 paths"))?; + files.insert(project.join(path)); + } + } + for input in plan["inputs"] + .as_array() + .ok_or_else(|| Error::compiler("compiler inputs are missing"))? + { + if let Some(path) = input["path"].as_str() { + files.insert(project.join(path)); + } + } + for manifest in manifests { + files.insert(project.join(manifest)); + if let Some(parent) = manifest.parent() { + directories.insert(project.join(parent)); + } + } + for name in ["vex.lock", "vex.toolchain.lock"] { + let path = project.join(name); + if path.exists() { + files.insert(path); + } + } + if let Some(script) = plan["linker_script"].as_str() { + files.insert(project.join(script)); + } + if let Some(args) = plan["link"]["args"].as_array() { + for arg in args.iter().filter_map(Value::as_str) { + let path = Path::new(arg); + if path.is_absolute() && path.is_file() { + files.insert(path.into()); + } + } + } + for path in &files { + if let Some(parent) = path.parent() { + directories.insert(parent.into()); + } + } + let files = files.into_iter().collect(); + let directories = directories.into_iter().collect(); + let mut inputs = Self { + files, + directories, + digest: String::new(), + complete_sources: source_inputs.is_some(), + complete_toolchain_paths: false, + }; + inputs.digest = inputs.fingerprint()?; + Ok(inputs) + } + pub fn include_files(&mut self, paths: impl IntoIterator) -> Result<(), Error> { + self.files.extend(paths); + self.files.sort(); + self.files.dedup(); + self.digest = self.fingerprint()?; + Ok(()) + } + pub fn include_toolchain( + &mut self, + compiler: &crate::Compiler, + archiver: Option<&Path>, + ) -> Result<(), Error> { + self.files + .push(compiler.path().canonicalize().map_err(Error::environment)?); + if let Some(path) = archiver { + self.files + .push(path.canonicalize().map_err(Error::environment)?); + } + if let Some(root) = compiler.selected_standard() { + let mut pending = vec![root.to_owned()]; + let mut count = 0; + while let Some(directory) = pending.pop() { + state::reject_link(&directory).map_err(Error::environment)?; + self.directories.push(directory.clone()); + for entry in std::fs::read_dir(&directory).map_err(Error::environment)? { + let path = entry.map_err(Error::environment)?.path(); + if path.file_name().is_some_and(|n| n == ".git") { + continue; + } + state::reject_link(&path).map_err(Error::environment)?; + let metadata = std::fs::metadata(&path).map_err(Error::environment)?; + if metadata.is_dir() { + pending.push(path); + } else if metadata.is_file() { + self.files.push(path); + } else { + return Err(Error::environment("std contains a special file")); + } + count += 1; + if count > 65536 { + return Err(Error::environment( + "std scheduler inputs exceed 65536 entries", + )); + } + } + } + } + self.files.sort(); + self.files.dedup(); + self.directories.sort(); + self.directories.dedup(); + self.complete_toolchain_paths = true; + self.digest = self.fingerprint()?; + Ok(()) + } + pub fn fingerprint(&self) -> Result { + let mut hash = Sha256::new(); + hash.update(b"vex.build-inputs.v1\0"); + for path in &self.files { + let text = path + .to_str() + .ok_or_else(|| Error::resolution("build inputs require UTF-8 paths"))?; + hash.update((text.len() as u64).to_le_bytes()); + hash.update(text.as_bytes()); + hash.update(crate::identity::file_digest(path)?.as_bytes()); + } + for directory in &self.directories { + let mut names = std::fs::read_dir(directory) + .map_err(Error::environment)? + .filter_map(|e| match e { + Ok(e) => { + if e.path().is_dir() || e.path().extension().is_some_and(|x| x == "wave") { + Some(Ok(e.file_name())) + } else { + None + } + } + Err(e) => Some(Err(e)), + }) + .collect::, _>>() + .map_err(Error::environment)?; + names.sort(); + for name in names { + let name = name + .to_str() + .ok_or_else(|| Error::resolution("source directory entries must be UTF-8"))?; + if name == "target" || name == ".vex" || name == ".git" { + continue; + } + hash.update((name.len() as u64).to_le_bytes()); + hash.update(name.as_bytes()); + } + } + Ok(hash.finalize().iter().map(|b| format!("{b:02x}")).collect()) + } + pub fn verify(&self) -> Result<(), Error> { + if self.fingerprint()? != self.digest { + return Err(Error::resolution("build inputs changed while the compiler was running; previous generation preserved")); + } + Ok(()) + } + pub fn portable(&self, roots: &[(PathBuf, String)]) -> Result { + let mut entries = std::collections::BTreeMap::new(); + for path in &self.files { + let root = roots + .iter() + .filter(|(root, _)| { + state::layout::path_form(path).starts_with(state::layout::path_form(root)) + }) + .max_by_key(|(root, _)| root.components().count()); + let (root,logical)=root.ok_or_else(||Error::resolution("portable provenance cannot name an input outside the selected source/std roots"))?; + let relative = state::layout::relative_output(root, path).map_err(Error::resolution)?; + let suffix = relative + .to_str() + .ok_or_else(|| Error::resolution("portable input path is not UTF-8"))? + .replace('\\', "/"); + let logical = format!("{logical}/{suffix}"); + if entries + .insert(logical, crate::identity::file_digest(path)?) + .is_some() + { + return Err(Error::resolution("portable input identities collide")); + } + } + let bytes = serde_json::to_vec(&entries).map_err(Error::internal)?; + let digest = Sha256::digest(bytes) + .iter() + .map(|b| format!("{b:02x}")) + .collect::(); + Ok( + json!({"schema_version":1,"sha256":digest,"files":entries,"complete_sources":self.complete_sources}), + ) + } + pub fn value(&self) -> Value { + json!({"fingerprint":self.digest,"complete_sources":self.complete_sources,"complete_toolchain_paths":self.complete_toolchain_paths,"files":self.files,"directories":self.directories}) + } +} +pub fn escape(path: &Path) -> Result { + let text = path + .to_str() + .ok_or_else(|| Error::resolution("depfile paths must be UTF-8"))?; + if text.contains(['\n', '\r', '\0']) { + return Err(Error::resolution( + "depfile cannot represent a path with a newline or NUL", + )); + } + Ok(text + .replace('\\', "\\\\") + .replace('$', "$$") + .replace(' ', "\\ ") + .replace('#', "\\#") + .replace(':', "\\:")) +} +pub fn depfile(targets: &[PathBuf], inputs: &[Inputs]) -> Result { + if targets.is_empty() { + return Err(Error::usage( + "depfile requires at least one artifact target", + )); + } + let targets = targets + .iter() + .map(|p| escape(p)) + .collect::, _>>()? + .join(" "); + let dependencies = inputs + .iter() + .flat_map(|i| i.files.iter().chain(&i.directories)) + .collect::>(); + let dependencies = dependencies + .into_iter() + .map(|p| escape(p)) + .collect::, _>>()? + .join(" "); + Ok(format!("{targets}: {dependencies}\n")) +} diff --git a/compiler/src/publication.rs b/compiler/src/publication.rs new file mode 100644 index 0000000..57da3d1 --- /dev/null +++ b/compiler/src/publication.rs @@ -0,0 +1,374 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +//! A durable, per-target generation commit. The result pointer is authoritative. +use diagnostic::Error; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use std::{ + fs, + io::Read, + path::{Component, Path, PathBuf}, +}; +const JOURNAL: &str = ".vex/build-publication.json"; +fn error(value: impl std::fmt::Display) -> Error { + Error::environment(value) +} +fn hex(bytes: impl AsRef<[u8]>) -> String { + bytes.as_ref().iter().map(|b| format!("{b:02x}")).collect() +} +pub fn key(paths: &[PathBuf], root: &Path) -> Result { + let names = state::artifacts::validate_output_paths(root, paths).map_err(error)?; + Ok(hex(Sha256::digest( + serde_json::to_vec(&names).map_err(Error::internal)?, + ))) +} +pub fn pointer(root: &Path, key: &str) -> PathBuf { + root.join("target/.vex-results").join(format!("{key}.json")) +} +fn bounded_json(path: &Path) -> Result, Error> { + state::reject_link(path).map_err(error)?; + let file = match state::open_regular(path) { + Ok(file) => file, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(error(e)), + }; + if !file.metadata().map_err(error)?.is_file() { + return Err(error("publication record is not a regular file")); + } + let mut bytes = Vec::new(); + file.take(8 * 1024 * 1024 + 1) + .read_to_end(&mut bytes) + .map_err(error)?; + if bytes.len() > 8 * 1024 * 1024 { + return Err(error("publication record exceeds 8 MiB")); + } + serde_json::from_slice(&bytes).map(Some).map_err(error) +} +fn safe(root: &Path, value: &Value) -> Result { + let name = value + .as_str() + .ok_or_else(|| error("publication path must be a string"))?; + let path = Path::new(name); + state::artifacts::validate_output_paths(root, &[path.to_path_buf()]).map_err(error)?; + let mut checked = root.to_path_buf(); + for part in path.components() { + if !matches!(part, Component::Normal(_)) { + return Err(error("invalid publication path")); + } + checked.push(part); + state::reject_link(&checked).map_err(error)?; + } + Ok(root.join(path)) +} +fn relative(root: &Path, path: &Path) -> Result { + let absolute = root.join(path); + state::layout::relative_output(root, &absolute) + .map_err(error)? + .to_str() + .map(str::to_owned) + .ok_or_else(|| error("publication path is not UTF-8")) +} +pub fn atomic_copy(source: &Path, destination: &Path) -> Result<(), Error> { + state::reject_link(source).map_err(error)?; + state::reject_link(destination).map_err(error)?; + let parent = destination + .parent() + .ok_or_else(|| error("missing output parent"))?; + state::ensure_tree(parent).map_err(error)?; + let nonce = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_err(error)? + .as_nanos(); + let temporary = parent.join(format!(".vex-publish-{}-{nonce}", std::process::id())); + let result = (|| { + let mut input = fs::File::open(source).map_err(error)?; + let metadata = input.metadata().map_err(error)?; + if !metadata.is_file() { + return Err(error("staged output must be a regular file")); + } + let mut output = fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&temporary) + .map_err(error)?; + std::io::copy(&mut input, &mut output).map_err(error)?; + output + .set_permissions(metadata.permissions()) + .map_err(error)?; + output.sync_all().map_err(error)?; + drop(output); + state::atomic_rename(&temporary, destination).map_err(error) + })(); + if result.is_err() { + let _ = fs::remove_file(&temporary); + } + result +} +fn record_text(path: &Path, value: &Value) -> Result<(), Error> { + let parent = path + .parent() + .ok_or_else(|| error("missing record parent"))?; + state::ensure_tree(parent).map_err(error)?; + let mut text = serde_json::to_string(value).map_err(Error::internal)?; + text.push('\n'); + state::edit::replace(path, &text).map_err(error) +} +fn fingerprint(path: &Path) -> Result { + state::artifacts::file_fingerprint(path) + .map(|v| json!(v)) + .map_err(error) +} +pub fn recover(root: &Path, readonly: bool) -> Result<(), Error> { + let journal = root.join(JOURNAL); + let Some(record) = bounded_json(&journal)? else { + return Ok(()); + }; + if readonly { + return Err(error( + "artifact publication recovery is pending; run a normal build first", + )); + } + if record["schema_version"] != 1 { + return Err(error("unsupported artifact publication journal")); + } + let point = safe(root, &record["pointer"])?; + let entries = record["entries"] + .as_array() + .ok_or_else(|| error("invalid publication journal entries"))?; + if entries.is_empty() || entries.len() > 4096 { + return Err(error("invalid publication entry count")); + } + let valid_hash = |value: &Value| { + value.is_null() + || value.as_str().is_some_and(|s| { + s.len() == 64 + && s.bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + }) + }; + if record["pointer_after"].is_null() || !valid_hash(&record["pointer_after"]) { + return Err(error("invalid publication commit identity")); + } + let last = entries.last().unwrap(); + if safe(root, &last["path"])? != point || last["after"] != record["pointer_after"] { + return Err(error("publication commit point is not the final entry")); + } + let destinations = entries[..entries.len() - 1] + .iter() + .map(|e| safe(root, &e["path"])) + .collect::, _>>()?; + if destinations.is_empty() || pointer(root, &key(&destinations, root)?) != point { + return Err(error( + "publication pointer does not match its artifact destinations", + )); + } + let committed = fingerprint(&point)? == record["pointer_after"]; + let mut paths = Vec::new(); + let mut identities = std::collections::BTreeSet::new(); + let mut backups = std::collections::BTreeSet::new(); + // Validate the complete journal before moving a single byte. + for entry in entries { + let destination = safe(root, &entry["path"])?; + if !identities.insert(destination.clone()) { + return Err(error("duplicate publication destination")); + } + if !valid_hash(&entry["before"]) || !valid_hash(&entry["after"]) { + return Err(error("invalid publication content identity")); + } + let owned = + json!(state::artifacts::recorded_fingerprint(root, &destination).map_err(error)?); + if !entry["before"].is_null() + && owned != entry["before"] + && !(committed && owned == entry["after"]) + { + return Err(error("publication journal lacks previous output ownership")); + } + let current = fingerprint(&destination)?; + if current != entry["before"] && current != entry["after"] { + return Err(error("published artifact was modified; preserve build-publication.json for manual recovery")); + } + if !entry["backup"].is_null() { + let backup = safe(root, &entry["backup"])?; + if entry["before"].is_null() + || !backups.insert(backup.clone()) + || destinations.iter().any(|p| p == &backup) + || !backup.starts_with(root.join("target/.vex-run")) + || fingerprint(&backup)? != entry["before"] + { + return Err(error("publication backup is missing or modified")); + } + } else if !entry["before"].is_null() { + return Err(error("publication entry lacks its backup")); + } + if committed && current != entry["after"] { + return Err(error( + "committed artifact generation is incomplete; preserve recovery state", + )); + } + paths.push(destination); + } + if !committed { + for entry in entries.iter().rev() { + let destination = safe(root, &entry["path"])?; + if fingerprint(&destination)? == entry["before"] { + continue; + } + if entry["backup"].is_null() { + fs::remove_file(&destination).map_err(error)?; + state::sync_dir(destination.parent().unwrap()).map_err(error)?; + } else { + atomic_copy(&safe(root, &entry["backup"])?, &destination)?; + } + } + } + state::artifacts::record_verified(root, &paths).map_err(error)?; + fs::remove_file(&journal).map_err(error)?; + state::sync_dir(journal.parent().unwrap()).map_err(error) +} + +pub fn publish( + root: &Path, + generation: &Path, + final_paths: &[PathBuf], + staged: &[PathBuf], + metadata: Value, +) -> Result { + recover(root, false)?; + if final_paths.len() != staged.len() || final_paths.is_empty() { + return Err(Error::internal("invalid generation output shape")); + } + let final_paths = final_paths.iter().map(|p| root.join(p)).collect::>(); + let staged = staged.iter().map(|p| root.join(p)).collect::>(); + let name = key(&final_paths, root)?; + let point = pointer(root, &name); + let mut artifacts = Vec::new(); + for (destination, source) in final_paths.iter().zip(&staged) { + if !source.is_file() { + continue; + } + let role = if destination + .components() + .any(|p| p.as_os_str() == ".vex-obj") + { + "intermediate" + } else if destination.extension().is_some_and(|e| e == "pdb") { + "debug" + } else if metadata["artifact_kind"] == "shared" + && destination.extension().is_some_and(|e| e == "lib") + { + "import_library" + } else { + "primary" + }; + artifacts.push(json!({"role":role,"path":source,"published_path":destination,"sha256":crate::identity::file_digest(source)?})); + } + let mut protected = final_paths.clone(); + protected.push(point.clone()); + let _ = state::artifacts::Batch::prepare_with_optional(root, Vec::::new(), protected) + .map_err(error)?; + if let Some(previous) = bounded_json(&point)? { + let old = previous["artifacts"].as_array(); + if previous["metadata"] == metadata + && old.is_some_and(|old| { + old.len() == artifacts.len() + && old.iter().zip(&artifacts).all(|(a, b)| { + a["published_path"] == b["published_path"] + && a["sha256"] == b["sha256"] + && a["path"].as_str().is_some_and(|p| { + crate::identity::file_digest(Path::new(p)).ok().as_deref() + == a["sha256"].as_str() + }) + }) + }) + { + return Ok(previous); + } + } + let archive_identity = metadata + .get("archive") + .map(|a| json!({"sha256":a["sha256"],"format":a["format"],"target":a["target"]})); + let provenance = json!({"schema_version":1,"package":metadata["package"],"package_target":metadata["package_target"],"profile":metadata["profile"],"target":metadata["target"],"features":metadata["features"],"settings":{"mode":metadata["settings"]["mode"],"relocation":metadata["settings"]["relocation"],"entry":metadata["settings"]["entry"],"startup":metadata["settings"]["startup"],"native":metadata["settings"]["native"],"reproducible":metadata["settings"]["reproducible"],"sysroot_configured":!metadata["settings"]["sysroot"].is_null(),"explicit_linker":!metadata["settings"]["linker"].is_null()},"compiler":metadata["compiler"],"inputs":metadata["portable_inputs"],"native_requirements":metadata["native_requirements"].as_array().map(|entries|entries.iter().map(|r|json!({"package_id":r["package_id"],"package":r["package"],"version":r["version"],"path":r["declared_path"],"name":r["name"],"target":r["target"]})).collect::>()),"archive":archive_identity}); + let record = json!({"schema":"vex.artifact-generation","schema_version":1,"generation":generation,"metadata":metadata,"provenance":provenance,"artifacts":artifacts}); + let staged_point = generation.join("result.json"); + state::artifacts::Batch::prepare(root, [staged_point.clone()]) + .map_err(error)? + .finish() + .map_err(error)?; + record_text(&staged_point, &record)?; + state::artifacts::record_verified(root, std::slice::from_ref(&staged_point)).map_err(error)?; + let mut destinations = final_paths.clone(); + destinations.push(point.clone()); + let mut sources = staged; + sources.push(staged_point); + let _ = state::artifacts::Batch::prepare_with_optional( + root, + Vec::::new(), + destinations.clone(), + ) + .map_err(error)?; + let backup_dir = generation.join("backup"); + let mut entries = Vec::new(); + for (index, (destination, source)) in destinations.iter().zip(&sources).enumerate() { + let before = fingerprint(destination)?; + let after = fingerprint(source)?; + let backup = if before.is_null() { + None + } else { + let backup = backup_dir.join(index.to_string()); + let batch = state::artifacts::Batch::prepare(root, [backup.clone()]).map_err(error)?; + state::ensure_tree(backup.parent().unwrap()).map_err(error)?; + fs::copy(destination, &backup).map_err(error)?; + batch.finish().map_err(error)?; + Some(relative(root, &backup)?) + }; + entries.push(json!({"path":relative(root,destination)?,"before":before,"after":after,"backup":backup})); + } + let journal = json!({"schema_version":1,"pointer":relative(root,&point)?,"pointer_after":fingerprint(sources.last().unwrap())?,"entries":entries}); + record_text(&root.join(JOURNAL), &journal)?; + let outcome = (|| { + for (index, (destination, source)) in destinations.iter().zip(&sources).enumerate() { + let entry = &journal["entries"][index]; + if fingerprint(destination)? != entry["before"] { + return Err(error("output changed during publication")); + } + if entry["before"] == entry["after"] { + continue; + } + if entry["after"].is_null() { + if destination.exists() { + fs::remove_file(destination).map_err(error)?; + } + } else { + atomic_copy(source, destination)?; + } + #[cfg(debug_assertions)] + if std::env::var("VEX_TEST_PUBLICATION_CRASH_AFTER") + .ok() + .and_then(|v| v.parse::().ok()) + == Some(index) + { + std::process::exit(97); + } + #[cfg(debug_assertions)] + if std::env::var("VEX_TEST_PUBLICATION_FAIL_AFTER") + .ok() + .and_then(|v| v.parse::().ok()) + == Some(index) + { + return Err(error("injected artifact publication failure")); + } + } + Ok(()) + })(); + let recovery = recover(root, false); + match (outcome, recovery) { + (Ok(()), Ok(())) => Ok(record), + (Err(primary), Ok(())) => Err(primary), + (Err(primary), Err(secondary)) => { + Err(primary.with_help(format!("recovery also failed: {secondary}"))) + } + (Ok(()), Err(e)) => Err(e), + } +} diff --git a/compiler/src/reports.rs b/compiler/src/reports.rs new file mode 100644 index 0000000..3779013 --- /dev/null +++ b/compiler/src/reports.rs @@ -0,0 +1,386 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +//! Exclusive ownership and recoverable replacement of reusable consumer reports. +use diagnostic::Error; +use serde_json::{json, Value}; +use std::{ + fs, + io::{Read, Write}, + path::{Path, PathBuf}, +}; +const OWNERS: &str = ".vex/report-ownership.json"; +const JOURNAL: &str = ".vex/report-publication.json"; +fn error(e: impl std::fmt::Display) -> Error { + Error::environment(e) +} +fn read(path: &Path) -> Result, Error> { + state::reject_link(path).map_err(error)?; + let file = match state::open_regular(path) { + Ok(f) => f, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(error(e)), + }; + if !file.metadata().map_err(error)?.is_file() { + return Err(error("consumer report metadata is not a regular file")); + } + let mut bytes = Vec::new(); + file.take(8 * 1024 * 1024 + 1) + .read_to_end(&mut bytes) + .map_err(error)?; + if bytes.len() > 8 * 1024 * 1024 { + return Err(error("consumer report metadata exceeds 8 MiB")); + } + serde_json::from_slice(&bytes).map(Some).map_err(error) +} +fn valid_hash(value: &Value) -> bool { + value.as_str().is_some_and(|s| { + s.len() == 64 + && s.bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + }) +} +fn validate_registry(value: &Value) -> Result<(), Error> { + if value["schema_version"] != 1 + || value["files"].as_object().is_none_or(|files| { + files.iter().any(|(path, hash)| { + !Path::new(path).is_absolute() + || Path::new(path) + .components() + .any(|c| matches!(c, std::path::Component::ParentDir)) + || !valid_hash(hash) + }) + }) + { + return Err(error("invalid report ownership registry")); + } + Ok(()) +} +fn owners(root: &Path) -> Result { + let value = read(&root.join(OWNERS))?.unwrap_or_else(|| json!({"schema_version":1,"files":{}})); + validate_registry(&value)?; + Ok(value) +} +fn name(path: &Path) -> Result<&str, Error> { + path.to_str() + .ok_or_else(|| Error::usage("consumer report paths must be UTF-8")) +} +fn digest(path: &Path) -> Result { + match fs::symlink_metadata(path) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Value::Null), + Err(e) => Err(error(e)), + Ok(m) => { + if !m.is_file() { + return Err(error("consumer report must be a regular file")); + } + crate::identity::file_digest(path).map(|s| json!(s)) + } + } +} +fn check_parents(path: &Path) -> Result<(), Error> { + for parent in path.ancestors() { + state::reject_link(parent).map_err(error)?; + } + Ok(()) +} +pub fn destination(path: &Path) -> Result { + check_parents(path)?; + let mut normalized = PathBuf::new(); + for part in path.components() { + match part { + std::path::Component::CurDir => {} + std::path::Component::ParentDir => { + if !normalized.pop() { + return Err(Error::usage("report path escapes filesystem root")); + } + } + part => normalized.push(part), + } + } + let mut ancestor = normalized.as_path(); + while !ancestor.exists() { + ancestor = ancestor + .parent() + .ok_or_else(|| Error::usage("report destination has no existing ancestor"))?; + } + let real = ancestor.canonicalize().map_err(error)?; + let tail = normalized.strip_prefix(ancestor).map_err(error)?; + Ok(if tail.as_os_str().is_empty() { + real + } else { + real.join(tail) + }) +} +pub fn preflight(root: &Path, paths: &[PathBuf]) -> Result<(), Error> { + let registry = owners(root)?; + let mut unique = std::collections::BTreeSet::new(); + for path in paths { + if !path.is_absolute() { + return Err(Error::usage( + "consumer report destination must resolve to an absolute path", + )); + } + check_parents(path)?; + if !unique.insert(path) { + return Err(Error::usage( + "artifact manifest and depfile need different destinations", + )); + } + let key = name(path)?; + let current = digest(path)?; + if !current.is_null() && registry["files"][key] != current { + return Err(error( + "refusing to overwrite an unowned or modified consumer report", + )); + } + let parent = path + .parent() + .ok_or_else(|| Error::usage("consumer report lacks a parent directory"))?; + if !parent.is_dir() && !parent.starts_with(root) { + return Err(error( + "consumer report parent must already exist outside the build root", + )); + } + if path.starts_with(root.join(".vex")) || path.starts_with(root.join("target/.vex-run")) { + return Err(Error::usage("consumer report overlaps private Vex state")); + } + } + Ok(()) +} +fn replace(path: &Path, value: &Value) -> Result<(), Error> { + let mut text = serde_json::to_string(value).map_err(Error::internal)?; + text.push('\n'); + state::edit::replace(path, &text).map_err(error) +} +pub fn recover(root: &Path, readonly: bool) -> Result<(), Error> { + let Some(record) = read(&root.join(JOURNAL))? else { + return Ok(()); + }; + if readonly { + return Err(error( + "consumer report recovery pending; run a normal build", + )); + } + if record["schema_version"] != 1 { + return Err(error("unsupported consumer report journal")); + } + let entries = record["entries"] + .as_array() + .ok_or_else(|| error("invalid report transaction entries"))?; + if entries.len() > 2 || entries.is_empty() { + return Err(error("invalid report transaction size")); + } + validate_registry(&record["before_registry"])?; + validate_registry(&record["after_registry"])?; + let registry = owners(root)?; + let committed = registry == record["after_registry"]; + let mut seen = std::collections::BTreeSet::new(); + for entry in entries { + let path = Path::new( + entry["path"] + .as_str() + .ok_or_else(|| error("missing report journal path"))?, + ); + if path + .components() + .any(|c| matches!(c, std::path::Component::ParentDir)) + || path.starts_with(root.join(".vex")) + || path.starts_with(root.join("target/.vex-run")) + || !path.is_absolute() + || !seen.insert(path) + { + return Err(error("invalid or duplicate report journal path")); + } + check_parents(path)?; + if (!entry["before"].is_null() && !valid_hash(&entry["before"])) + || !valid_hash(&entry["after"]) + || record["after_registry"]["files"][name(path)?] != entry["after"] + { + return Err(error("invalid report transaction identity")); + } + if entry["before"].is_null() != entry["backup"].is_null() { + return Err(error("report transaction lacks a valid backup")); + } + let current = digest(path)?; + if current != entry["before"] && current != entry["after"] { + return Err(error( + "consumer report changed during recovery; preserve the journal", + )); + } + if !entry["before"].is_null() + && record["before_registry"]["files"][name(path)?] != entry["before"] + { + return Err(error("journal lacks previous report ownership")); + } + if !entry["backup"].is_null() { + let backup = Path::new( + entry["backup"] + .as_str() + .ok_or_else(|| error("invalid report backup"))?, + ); + check_parents(backup)?; + if !backup.starts_with(root.join("target/.vex-run")) + || backup + .components() + .any(|c| matches!(c, std::path::Component::ParentDir)) + || digest(backup)? != entry["before"] + { + return Err(error("report backup is unavailable or modified")); + } + } + if committed && current != entry["after"] { + return Err(error("committed consumer report is incomplete")); + } + } + let mut expected = record["before_registry"].clone(); + for entry in entries { + expected["files"][entry["path"].as_str().unwrap()] = entry["after"].clone(); + } + if expected != record["after_registry"] { + return Err(error("report journal changes unrelated ownership")); + } + if !committed { + if registry != record["before_registry"] { + return Err(error( + "report ownership changed outside pending transaction", + )); + } + for entry in entries.iter().rev() { + let path = Path::new(entry["path"].as_str().unwrap()); + if digest(path)? == entry["before"] { + continue; + } + if entry["before"].is_null() { + fs::remove_file(path).map_err(error)?; + state::sync_dir(path.parent().unwrap()).map_err(error)?; + } else { + crate::publication::atomic_copy( + Path::new( + entry["backup"] + .as_str() + .ok_or_else(|| error("missing report backup"))?, + ), + path, + )?; + } + } + } + fs::remove_file(root.join(JOURNAL)).map_err(error)?; + state::sync_dir(&root.join(".vex")).map_err(error) +} +pub fn publish(root: &Path, files: &[(PathBuf, String)]) -> Result<(), Error> { + if files.is_empty() { + return Ok(()); + } + recover(root, false)?; + preflight( + root, + &files.iter().map(|(p, _)| p.clone()).collect::>(), + )?; + let generation = crate::create_run_generation()?; + let generation = root.join(generation); + let _lease = state::artifacts::RunLease::create(root, &generation).map_err(error)?; + let before = owners(root)?; + let mut after = before.clone(); + let mut entries = Vec::new(); + let mut sources = Vec::new(); + for (index, (path, text)) in files.iter().enumerate() { + let staged = generation.join(format!("report-{index}")); + let batch = state::artifacts::Batch::prepare(root, [staged.clone()]).map_err(error)?; + let mut file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&staged) + .map_err(error)?; + // Windows requires write access for sync_all (FlushFileBuffers). + file.write_all(text.as_bytes()) + .and_then(|_| file.sync_all()) + .map_err(error)?; + drop(file); + batch.finish().map_err(error)?; + let previous = digest(path)?; + let next = digest(&staged)?; + let backup = if previous.is_null() { + None + } else { + let backup = generation.join(format!("report-backup-{index}")); + let batch = state::artifacts::Batch::prepare(root, [backup.clone()]).map_err(error)?; + fs::copy(path, &backup).map_err(error)?; + batch.finish().map_err(error)?; + Some(backup) + }; + after["files"][name(path)?] = next.clone(); + entries.push(json!({"path":path,"before":previous,"after":next,"backup":backup})); + sources.push(staged); + } + if after == before { + return Ok(()); + } + let journal = json!({"schema_version":1,"before_registry":before,"after_registry":after,"entries":entries}); + replace(&root.join(JOURNAL), &journal)?; + let result = (|| { + for (index, ((destination, _), source)) in files.iter().zip(sources).enumerate() { + if digest(destination)? != journal["entries"][index]["before"] { + return Err(error("consumer report was modified during publication")); + } + if journal["entries"][index]["before"] != journal["entries"][index]["after"] { + crate::publication::atomic_copy(&source, destination)?; + } + #[cfg(debug_assertions)] + if std::env::var("VEX_TEST_REPORT_CRASH_AFTER") + .ok() + .and_then(|s| s.parse::().ok()) + == Some(index) + { + std::process::exit(97); + } + #[cfg(debug_assertions)] + if std::env::var("VEX_TEST_REPORT_FAIL_AFTER") + .ok() + .and_then(|s| s.parse::().ok()) + == Some(index) + { + return Err(error("injected report publication failure")); + } + } + replace(&root.join(OWNERS), &after) + })(); + let recovery = recover(root, false); + match (result, recovery) { + (Ok(()), Ok(())) => Ok(()), + (Err(e), Ok(())) => Err(e), + (Ok(()), Err(e)) => Err(e), + (Err(e), Err(other)) => Err(e.with_help(format!("report recovery also failed: {other}"))), + } +} +pub fn load_result(root: &Path, key: &str) -> Result { + let value = read(&crate::publication::pointer(root, key))? + .ok_or_else(|| error("completed build has no artifact result"))?; + if value["schema_version"] != 1 || value["schema"] != "vex.artifact-generation" { + return Err(error("invalid artifact generation result")); + } + for artifact in value["artifacts"] + .as_array() + .ok_or_else(|| error("missing artifact result entries"))? + { + let path = Path::new( + artifact["path"] + .as_str() + .ok_or_else(|| error("missing artifact path"))?, + ); + if !state::layout::path_form(path) + .starts_with(state::layout::path_form(&root.join("target/.vex-run"))) + || path + .components() + .any(|c| matches!(c, std::path::Component::ParentDir)) + { + return Err(error("artifact result escapes its generation")); + } + check_parents(path)?; + if !valid_hash(&artifact["sha256"]) || digest(path)? != artifact["sha256"] { + return Err(error("completed artifact is missing or corrupt")); + } + } + Ok(value) +} diff --git a/compiler/src/selection.rs b/compiler/src/selection.rs index ff2d710..a63060d 100644 --- a/compiler/src/selection.rs +++ b/compiler/src/selection.rs @@ -9,14 +9,105 @@ use std::process::Command; use std::time::Duration; /// One selection per Vex command. Capability results never outlive this process. +#[derive(Clone)] pub struct Compiler { pub(crate) path: PathBuf, targets: Option>, version: Option, specs: BTreeMap, serde_json::Value>, + pub(crate) input: Option>, + pub(crate) standard: Option, + pub(crate) remappings: Vec<(PathBuf, String)>, + pub(crate) identity: Option, + capabilities: Option>, } impl Compiler { + pub(crate) fn command(&self) -> Command { + let mut command = Command::new(&self.path); + if let Some(root) = &self.standard { + command.arg(format!("--std-root={}", root.display())); + } + command + } + pub(crate) fn build_command(&self) -> Command { + let mut command = self.command(); + if self.input.is_some() { + command.arg("--package-graph-stdin"); + } + for (real, logical) in &self.remappings { + command.arg(format!("--remap-path-prefix={}={logical}", real.display())); + } + command + } + pub fn capabilities(&mut self) -> Result, Error> { + if self.capabilities.is_none() { + let output = process::output( + self.command() + .args(["print", "vex-capabilities", "--format=json"]), + Duration::from_secs(60), + ) + .map_err(Error::environment)?; + self.capabilities = Some(if output.status.success() { + let value: serde_json::Value = + serde_json::from_slice(&output.stdout).map_err(Error::compiler)?; + if value["schema_version"] != 1 { + return Err(Error::compiler("unsupported compiler capability schema")); + } + Some(value) + } else { + None + }); + } + Ok(self.capabilities.as_ref().and_then(|value| value.as_ref())) + } + pub fn package_graph(&mut self, graph: Option) -> Result<(), Error> { + if let Some(graph) = graph { + if self.capabilities()?.is_none_or(|c| c["package_graph"] != 1) { + return Err(Error::compiler("selected compiler does not support package-scoped imports; select a compatible Wave release")); + } + let bytes = serde_json::to_vec(&graph).map_err(Error::internal)?; + if bytes.len() > 8 * 1024 * 1024 { + return Err(Error::resolution("compiler package graph exceeds 8 MiB")); + } + self.input = Some(bytes); + } else { + self.input = None; + } + Ok(()) + } + pub fn path_remappings(&mut self, roots: Vec<(PathBuf, String)>) -> Result<(), Error> { + if !roots.is_empty() && self.capabilities()?.is_none_or(|c| c["path_remap"] != 1) { + return Err(Error::compiler( + "selected compiler does not support verified logical path remapping", + )); + } + if roots.iter().any(|(path, logical)| { + path.to_str().is_none() + || path.to_string_lossy().contains('=') + || !logical.starts_with('/') + }) { + return Err(Error::resolution("invalid path remapping root")); + } + self.remappings = roots; + Ok(()) + } + pub(crate) fn from_executable(path: &Path) -> Result { + Ok(Self { + path: std::env::current_dir() + .map_err(Error::environment)? + .join(path), + targets: None, + version: None, + specs: BTreeMap::new(), + input: None, + standard: std::env::var_os("VEX_WAVE_STD") + .map(|p| std::env::current_dir().unwrap_or_default().join(p)), + remappings: Vec::new(), + identity: None, + capabilities: None, + }) + } /// The command-local selected executable, before entering a project directory. pub fn path(&self) -> &Path { &self.path @@ -24,12 +115,21 @@ impl Compiler { pub fn select() -> Result { let cwd = std::env::current_dir().map_err(Error::environment)?; - let find = |name: &std::ffi::OsStr| { + let find = |name: &std::ffi::OsStr, automatic: bool| { std::env::var_os("PATH").and_then(|paths| { std::env::split_paths(&paths) .map(|p| cwd.join(p).join(name)) .find_map(|p| { if p.is_file() { + #[cfg(unix)] + if automatic { + use std::os::unix::fs::PermissionsExt; + if std::fs::metadata(&p).ok()?.permissions().mode() & 0o111 == 0 { + return None; + } + } + #[cfg(not(unix))] + let _ = automatic; return Some(p); } #[cfg(windows)] @@ -49,13 +149,13 @@ impl Compiler { } let path = PathBuf::from(value); if path.components().count() == 1 && !path.is_absolute() { - find(path.as_os_str()).unwrap_or_else(|| cwd.join(path)) + find(path.as_os_str(), false).unwrap_or_else(|| cwd.join(path)) } else { cwd.join(path) } } else { let name = if cfg!(windows) { "wavec.exe" } else { "wavec" }; - find(std::ffi::OsStr::new(name)) + find(std::ffi::OsStr::new(name), true) .or_else(toolchain::managed_wavec) .map(|p| cwd.join(p)) .ok_or_else(|| { @@ -69,6 +169,11 @@ impl Compiler { targets: None, version: None, specs: BTreeMap::new(), + input: None, + standard: std::env::var_os("VEX_WAVE_STD").map(|p| cwd.join(p)), + remappings: Vec::new(), + identity: None, + capabilities: None, }) } @@ -102,7 +207,10 @@ impl Compiler { } let text = String::from_utf8(output.stdout).map_err(Error::compiler)?; let tokens: Vec<_> = text.split_whitespace().collect(); - if tokens.len() < 2 || tokens[0] != "wavec" { + if tokens.len() < 2 + || tokens[0] != "wavec" + || semver::Version::parse(tokens[1]).is_err() + { return Err(Error::compiler("malformed wavec version response")); } self.version = Some(tokens[1].to_owned()); @@ -128,7 +236,7 @@ impl Compiler { if let Some(value) = self.specs.get(&key) { return Ok(value.clone()); } - let mut command = Command::new(&self.path); + let mut command = self.command(); command.args(["print", "target-spec", "--format=json"]); if let Some(target) = target { self.validate_target(target)?; @@ -175,7 +283,8 @@ impl Compiler { pub fn supported_targets(&mut self) -> Result<&[String], Error> { if self.targets.is_none() { let output = process::output( - Command::new(&self.path).args(["print", "supported-targets", "--format=json"]), + self.command() + .args(["print", "supported-targets", "--format=json"]), Duration::from_secs(60), ) .map_err(|e| { diff --git a/diagnostic/src/lib.rs b/diagnostic/src/lib.rs index 3a9457d..9c2f22f 100644 --- a/diagnostic/src/lib.rs +++ b/diagnostic/src/lib.rs @@ -79,6 +79,11 @@ impl Error { self.context_fields.push((key.into(), value.to_string())); self } + /// Add actionable guidance without replacing the original typed context. + pub fn with_help(mut self, help: impl fmt::Display) -> Self { + self.message.push_str(&format!("\nhelp: {help}")); + self + } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/docs/commands.md b/docs/commands.md index 8fc695b..81c773b 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -10,16 +10,16 @@ See [manifest and operational contracts](reference.md) for field types, environm Vex - Wave package manager Usage: - vex [-q|--quiet] [-v|--verbose] [--message-file ] [--manifest-path ] [-p|--package |--workspace] [--features ] [--no-default-features] [--include-tests] [options] + vex [-q|--quiet] [-v|--verbose] [--message-file ] [--manifest-path ] [-p|--package |--workspace] [--features ] [--no-default-features] [--include-tests] [--build-dir ] [--state-dir ] [options] vex init [--lib] - vex build [--lib] [--bin ] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] - vex run [--bin ] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] [-- ] + vex build [--lib] [--bin ] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] [--artifact-manifest ] [--depfile ] + vex run [--bin ] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] [--artifact-manifest ] [--depfile ] [-- ] vex check [--lib] [--bin ] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] - vex test [filter] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] [-- ] + vex test [filter] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] [--artifact-manifest ] [--depfile ] [-- ] vex fetch [--locked] [--offline] [--target ] vex update [...] [--target ] vex info - vex metadata [--format=json] [--format-version <1|2>] [--locked] [--offline] [--target ] + vex metadata [--format=json] [--format-version <1|2|3>] [--locked] [--offline] [--target ] vex tree [--invert ] [--depth ] [--locked] [--offline] [--target ] vex clean [--dry-run] vex prune [--apply] [--dry-run] @@ -31,6 +31,7 @@ Usage: vex cache prune [--apply] [--dry-run] vex completions vex manpage + vex toolchain capture [--wavec ] [--std ] [--replace] vex --version Output: @@ -49,7 +50,7 @@ Manage init ## build ```text -usage: vex build [--lib] [--bin ] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] +usage: vex build [--lib] [--bin ] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] [--artifact-manifest ] [--depfile ] Compile selected package targets ``` @@ -57,7 +58,7 @@ Compile selected package targets ## run ```text -usage: vex run [--bin ] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] [-- ] +usage: vex run [--bin ] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] [--artifact-manifest ] [--depfile ] [-- ] Compile and execute one binary ``` @@ -73,7 +74,7 @@ Check selected package targets ## test ```text -usage: vex test [filter] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] [-- ] +usage: vex test [filter] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] [--artifact-manifest ] [--depfile ] [-- ] Compile and execute explicit main-based tests; run every selected test and return the first failure ``` @@ -105,7 +106,7 @@ Manage info ## metadata ```text -usage: vex metadata [--format=json] [--format-version <1|2>] [--locked] [--offline] [--target ] +usage: vex metadata [--format=json] [--format-version <1|2|3>] [--locked] [--offline] [--target ] Manage metadata ``` @@ -197,3 +198,11 @@ usage: vex manpage Print the vex(1) manual ``` + +## toolchain + +```text +usage: vex toolchain capture [--wavec ] [--std ] [--replace] + +Record a prepared host compiler/std pair by content identity; never downloads a toolchain. +``` diff --git a/docs/completions/vex.bash b/docs/completions/vex.bash index 0de21ef..be9c9c2 100644 --- a/docs/completions/vex.bash +++ b/docs/completions/vex.bash @@ -1,3 +1,3 @@ # Generated from command-spec.json -_vex() { COMPREPLY=( $(compgen -W '-- --apply --bin --branch --depth --dry-run --features --format-version --format=json --git --include-tests --invert --lib --locked --manifest-path --message-file --name --no-default-features --offline --package --package-name --path --profile --quiet --release --rev --script-fallback --subdir --tag --target --verbose --version --version-req --workspace -p -q -v add build cache check clean completions doctor fetch info init manpage metadata new prune remove run setup test tree update' -- "${COMP_WORDS[COMP_CWORD]}") ); } +_vex() { COMPREPLY=( $(compgen -W '-- --apply --artifact-manifest --bin --branch --build-dir --depfile --depth --dry-run --features --format-version --format=json --git --include-tests --invert --lib --locked --manifest-path --message-file --name --no-default-features --offline --package --package-name --path --profile --quiet --release --replace --rev --script-fallback --state-dir --std --subdir --tag --target --verbose --version --version-req --wavec --workspace -p -q -v add build cache check clean completions doctor fetch info init manpage metadata new prune remove run setup test toolchain tree update' -- "${COMP_WORDS[COMP_CWORD]}") ); } complete -F _vex vex diff --git a/docs/completions/vex.fish b/docs/completions/vex.fish index b076661..69fdaad 100644 --- a/docs/completions/vex.fish +++ b/docs/completions/vex.fish @@ -1,7 +1,10 @@ # Generated from command-spec.json complete -c vex -l apply +complete -c vex -l artifact-manifest complete -c vex -l bin complete -c vex -l branch +complete -c vex -l build-dir +complete -c vex -l depfile complete -c vex -l depth complete -c vex -l dry-run complete -c vex -l features @@ -23,14 +26,18 @@ complete -c vex -l path complete -c vex -l profile complete -c vex -l quiet complete -c vex -l release +complete -c vex -l replace complete -c vex -l rev complete -c vex -l script-fallback +complete -c vex -l state-dir +complete -c vex -l std complete -c vex -l subdir complete -c vex -l tag complete -c vex -l target complete -c vex -l verbose complete -c vex -l version complete -c vex -l version-req +complete -c vex -l wavec complete -c vex -l workspace complete -c vex -f -a add complete -c vex -f -a build @@ -50,5 +57,6 @@ complete -c vex -f -a remove complete -c vex -f -a run complete -c vex -f -a setup complete -c vex -f -a test +complete -c vex -f -a toolchain complete -c vex -f -a tree complete -c vex -f -a update diff --git a/docs/completions/vex.powershell b/docs/completions/vex.powershell index a23b16f..30e631c 100644 --- a/docs/completions/vex.powershell +++ b/docs/completions/vex.powershell @@ -1,4 +1,4 @@ # Generated from command-spec.json Register-ArgumentCompleter -Native -CommandName vex -ScriptBlock { param($wordToComplete, $commandAst, $cursorPosition) - '-- --apply --bin --branch --depth --dry-run --features --format-version --format=json --git --include-tests --invert --lib --locked --manifest-path --message-file --name --no-default-features --offline --package --package-name --path --profile --quiet --release --rev --script-fallback --subdir --tag --target --verbose --version --version-req --workspace -p -q -v add build cache check clean completions doctor fetch info init manpage metadata new prune remove run setup test tree update'.Split(' ') | Where-Object { $_.StartsWith($wordToComplete) } | ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) } + '-- --apply --artifact-manifest --bin --branch --build-dir --depfile --depth --dry-run --features --format-version --format=json --git --include-tests --invert --lib --locked --manifest-path --message-file --name --no-default-features --offline --package --package-name --path --profile --quiet --release --replace --rev --script-fallback --state-dir --std --subdir --tag --target --verbose --version --version-req --wavec --workspace -p -q -v add build cache check clean completions doctor fetch info init manpage metadata new prune remove run setup test toolchain tree update'.Split(' ') | Where-Object { $_.StartsWith($wordToComplete) } | ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) } } diff --git a/docs/completions/vex.zsh b/docs/completions/vex.zsh index cea8d82..bb42a35 100644 --- a/docs/completions/vex.zsh +++ b/docs/completions/vex.zsh @@ -1,3 +1,3 @@ #compdef vex # Generated from command-spec.json -_arguments '*:command or option:(-- --apply --bin --branch --depth --dry-run --features --format-version --format=json --git --include-tests --invert --lib --locked --manifest-path --message-file --name --no-default-features --offline --package --package-name --path --profile --quiet --release --rev --script-fallback --subdir --tag --target --verbose --version --version-req --workspace -p -q -v add build cache check clean completions doctor fetch info init manpage metadata new prune remove run setup test tree update)' +_arguments '*:command or option:(-- --apply --artifact-manifest --bin --branch --build-dir --depfile --depth --dry-run --features --format-version --format=json --git --include-tests --invert --lib --locked --manifest-path --message-file --name --no-default-features --offline --package --package-name --path --profile --quiet --release --replace --rev --script-fallback --state-dir --std --subdir --tag --target --verbose --version --version-req --wavec --workspace -p -q -v add build cache check clean completions doctor fetch info init manpage metadata new prune remove run setup test toolchain tree update)' diff --git a/docs/external-builds.md b/docs/external-builds.md new file mode 100644 index 0000000..7d7142c --- /dev/null +++ b/docs/external-builds.md @@ -0,0 +1,196 @@ +# External builds and completed artifacts + +These contracts are introduced for Vex `0.0.3-beta`. Manifest formats 1–4 keep +their meanings and are never automatically rewritten. New projects use format +5. Formats 4–5 use dependency lock v4; formats 1–3 retain v3 writing and +legacy read compatibility. Toolchain identity has a separate file. + +## Source, build and dependency storage + +`--build-dir ` selects a build root, overriding `VEX_BUILD_DIR`. Relative CLI +and environment paths resolve from the invocation directory, before project +selection. Without an override the project/workspace root is the build root. +Outputs, intermediates, caches and generations live under `B/target/`; ownership, +build publication and generation leases live under `B/.vex/`. Vex claims its own +subdirectories, not other files in the surrounding Meson build directory. + +`--state-dir ` overrides `VEX_STATE_DIR` and chooses dependency state, including +checkouts and their recovery journal. The default is the source `.vex/`, or +`B/.vex/dependencies/` when a build root is selected. Reviewed `vex.ws`, +`vex.lock` and `vex.toolchain.lock` remain source inputs. No existing state is +silently moved. A store/build ownership marker binds storage to one source root. +Protected source/managed-output overlaps and another project's stores are errors. + +All commands coordinate the source identity through a persistent OS state file +before reading its dependency lock, then acquire the selected dependency-store +lease. The OS location is `LOCALAPPDATA/Vex/state` on Windows, +`XDG_STATE_HOME/vex` or `~/.local/state/vex` on Unix (temporary-directory fallback +only when no home/state directory is available). A separate `B/.vex/build.lock` +serializes publication into one build root. Two roots may compile concurrently +from prepared source while update remains excluded until compilation completes. +These are OS leases, not PID/existence locks. Never delete a coordination inode +as a stale-lock workaround. + +Prepare each selected store explicitly while source is writable: + +```sh +vex --manifest-path /src/project/vex.ws --build-dir /build/one fetch --offline +vex --manifest-path /src/project/vex.ws --build-dir /build/one build --locked --offline +``` + +The second command works with read-only source. Preparation must already have +created the common project and dependency leases. Metadata and clean honor the +same storage selectors. Cleaning one root preserves other roots and source. +Pending dependency/build/report transactions stop clean and dry-run; a normal +fetch/build performs the appropriate validated recovery. + +## Library settings and archives + +```wson +{ + format = 5, + name = "module", + version = "1.0.0", + targets = { lib = { output = "static", mode = "freestanding", relocation = "pic" } }, + build = { reproducible = true, archiver = "llvm-ar" }, + target_config = [{ triple = "aarch64-pc-windows-msvc", lib = { relocation = "default" }, archiver = "llvm-lib" }] +} +``` + +A library output is `object` (default), `shared`, or format-5 `static`. Mode is +`hosted` or `freestanding`; relocation is `default`, `pic`, or `static`. Exact +triple library overrides take precedence over the library declaration. Profiles +continue to control optimization only. Entry/startup/linker scripts belong to +binaries. Explicit relocation is supported for ELF/Mach-O; COFF/Wasm reject +unverified explicit models. Freestanding native libraries support ELF, Mach-O +and COFF; freestanding binaries retain the ELF restriction. Wasm archives are +not supported. Shared libraries require PIC where an explicit model is selected. + +Static output is `lib.a` for ELF/Mach-O and `.lib` for MSVC, +under `target///lib/` (workspace package subdirectories apply). +Vex queries the selected archiver, requests a deterministic target format and +symbol index, and verifies all members, object machines, timestamps and hashes. +It archives the objects from this root Wave compilation, which includes imported +Wave code once. Foreign objects/archives and system libraries are **not bundled**; +`metadata.native_requirements` reports selected transitive declarations in link +order, resolved paths when known and owning package IDs. Consumers own those +additional links. Repeated native libraries retain their order and repetition. + +`build.archiver` and a triple-specific `archiver` select one executable name/path; +Vex does not split shell words or accept raw argument strings. Selection otherwise +checks compiler-adjacent LLVM tools, PATH `llvm-ar`/`llvm-lib`, and GNU `ar` for +ELF. Install suitable tools explicitly; Vex does not download them. Unknown +archiver/runtime closure disables artifact reuse rather than guessing freshness. + +## Toolchain identity and reproducibility + +`VEX_WAVEC` → PATH → managed installation remains the compiler precedence. +`VEX_WAVE_STD` selects an explicit prepared standard-library directory. Paths +resolve before entering the project. Exact manifest `compiler` version checks, +content pins, capabilities and package-language compatibility remain independent. + +```sh +vex toolchain capture --wavec /prepared/wavec --std /prepared/std +vex toolchain capture --replace +``` + +Explicit capture writes `vex.toolchain.lock` schema 1 with host-specific compiler +and std SHA-256 identities, and the compiler version. Other hosts are preserved. +An existing host requires `--replace`. Source revision is null unless reliably +known; no revision is inferred from a path/version. A compiler reporting no std +records a null std identity, distinct from a prepared tree. Tree hashing rejects +links/special files and sorts relative UTF-8 names. All build/check/run/test +paths, including dry-run, reject a mismatched or missing host pin before dependency +mutation; they never install or fall back to another compiler. Doctor reports +expected and observed identities without repair/network access. + +`build.reproducible = true` requests strict directory-independent object/static +bytes and portable provenance. It requires Wave's versioned package graph and +logical path remapping. Package IDs and `/vex/...` logical roots replace physical +paths in compiler symbol identities. Diagnostics and depfiles retain real local +paths. Reproducibility currently rejects executable/shared links, SDK/sysroot and +other unverified external link plans. Explicit remapping prefixes containing `=` +are not representable by the current compiler protocol and are rejected. This is +a bounded guarantee for supported compiler/object/archive formats, not a claim +that arbitrary external SDKs or native linkers are reproducible. + +## Result publication and depfiles + +```sh +vex build --locked --offline --artifact-manifest /build/artifacts.json --depfile /build/inputs.d +``` + +Paths are invocation-relative. Existing files must be unchanged reports owned by +this build root. Unowned/edited files are errors, even in dry-run. Check emits no +artifacts and rejects these options. Run/test publish before executing programs; +program stdio/exit codes and exclusive JSONL `--message-file` behavior stay intact. + +Compilation targets private leased generations. Required outputs and optional +companions are verified; captured inputs and observed compiler/std identities are +checked again before publication. Compatibility paths are mirrors. The **atomic +result-pointer replacement** is the per-target commit point; several mirror +renames are not one atomic filesystem operation. Cooperating Vex readers hold the +build lock. External readers use the immutable paths in a completed result and +hold its generation lease while copying/consuming. Before commit recovery restores +old mirrors; after commit it retains the complete new generation. User edits or +invalid journals stop recovery without discarding evidence. Earlier successful +targets remain when a later target fails. No automatic generation GC is added. + +The requested [`vex.artifacts` schema 1](schemas/artifacts-v1.json) aggregates +selected package-target results in deterministic order. Each contains roles, +immutable and compatibility paths, SHA-256, target/profile/features/effective +settings, compiler/std identities, source/config fingerprints and a distinct +path-free `provenance` object. Intermediate, debug and import-library companions +are identified separately. Compiler/archiver/input-verification failure leaves +the previous complete generation and requested reports intact. Report replacement +has its own journal/ownership commit; an interrupted report transaction is +recovered before the next normal build. Dry-run creates neither reports nor +artifacts and performs no recovery. Unchanged verified report bytes keep mtimes. + +Depfiles use Make/Ninja escaping and list selected sources/imports, manifests, +lock/config files, compiler/std files, declared resolved native inputs and source +listing directories. Unknown SDK/system-name closures prevent unsafe cache reuse; +a depfile does not pin them. Always run the consumer freshness scan so newly +added/deleted imports, tool selections and environment changes cannot hide behind +an old scheduler file. `--locked` pins dependency resolution, not mutable path or +SDK contents. No execution/test results are cached. + +Metadata keeps schema 1 as its default; format-5 declarations require explicit +[`--format-version 3`](schemas/metadata-v3.json), without querying a compiler. +Dry-run always emits [`vex.build-plan` schema 2](schemas/build-plan-v2.json), +including source/build roots, selected reports and observed toolchain identity. + +## Meson consumer and acceptance + +The [official example](../examples/meson-consumer/meson.build) links a multi-file +Wave library into C, C++ and Rust programs. Prepare its Wave store first, then: + +```sh +meson setup /build/consumer examples/meson-consumer -Dvex=/absolute/path/to/vex +meson compile -C /build/consumer +meson test -C /build/consumer --no-rebuild +``` + +Select a prepared compatible compiler/std through the environment. The +[adapter](../tools/meson_consumer.py) always invokes Vex locked/offline, reads +verified machine results, leases a generation while copying, and atomically +updates Meson-owned bridge bytes only when changed. Meson compiles/links foreign +sources. For Meson 1.8 Rust, a generated entry includes the original caller and +verified archive digest so both scheduling and re-linking are compiler-input +dependencies. Build-machine Vex/wavec can produce another output target; Meson's +host configuration must match `-Dwave_target`. Running cross programs requires a +matching Meson execution wrapper and runtime. + +`tests/external_builds.py --vex ... --wavec ... --std ... --cross-formats` exercises +real Meson restat, imports, readonly source, separate roots, profile/features, +failure preservation, portable provenance and indexed O0/O2 cross-format archives. +The checked fixture digests identify a small Whale-shaped C ABI package; it is +not Whale compiler source. Native release acceptance separately links actual +Wave archives into C/C++/Rust on all nine existing hosts. + +New scoped-import/result/reproducibility acceptance requires a public Wave +artifact advertising `vex-capabilities` schema 1 with `package_graph`, `path_remap` +and `source_inputs` at version 1. [Wave #1071](https://github.com/wavefnd/Wave/pull/1071) supplies the +#1066/#1067 compiler contract in a separate PR. Until a compatible public release is pinned and actually executed, +local development-compiler results are supplemental and do not establish new +nine-host release readiness. Existing pinned public Wave 0.2.1 gates remain. diff --git a/docs/native-interop.md b/docs/native-interop.md index 1200dee..453ec4b 100644 --- a/docs/native-interop.md +++ b/docs/native-interop.md @@ -160,3 +160,8 @@ pinned public compiler. It builds C/C++/Rust fixtures outside Vex, links Wave in both directions, and checks object/shared artifacts, transitive native inputs, locked/offline behavior and conservative cleanup. A local cross-plan check is not a substitute for executing those host acceptance jobs. + +Format 5 adds target-aware deterministic static archives and explicit library +mode/relocation. See [external builds](external-builds.md) and the +[Meson consumer](../examples/meson-consumer/meson.build) for completed result, +depfile, native requirements and portable provenance contracts. diff --git a/docs/reference.md b/docs/reference.md index aa070a5..ab0e0d4 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -5,6 +5,9 @@ platform. Project commands select `--manifest-path` first, otherwise search real ancestors from the invocation directory. `init` uses the current directory. Builds and user programs execute from the selected project root. +For format 5, external storage, static libraries, pins, depfiles and completed +results see [external builds](external-builds.md). + ## Manifest `vex.ws` is a WSON object. Unknown and duplicate fields are errors. Names match @@ -12,27 +15,31 @@ Builds and user programs execute from the selected project root. | Field | Type | Default / meaning | | --- | --- | --- | -| `format` | integer 1, 2, or 3 | 1 when absent; generated single-target manifests use 2 | +| `format` | integer 1–5 | 1 when absent; new manifests use 5 | | `name` | string | Required package/import identity | -| `version` | version literal or string | `0.1.0`; dependency equality is exact | +| `version` | version literal or string | `0.1.0`; formats 4/5 use SemVer | | `lib` | boolean | Formats 1/2 only: false; true selects `src/lib.wave`, otherwise `src/main.wave` | | `compiler` | string | Absent means no version requirement; exact canonical wavec version, including prerelease, without build metadata | | `description`, `author`, `license` | string | Optional descriptive metadata | | `dependencies` | array of objects | Empty when absent | | `native` | object | Prebuilt library inputs and search paths; formats 1/2 also declare library output here; see [native interoperability](native-interop.md) | -| `targets` | object | Required in format 3; optional `lib` and array `bins` declare at least one target | +| `targets` | object | Required in formats 3–5; optional `lib` and array `bins` declare at least one target | | `default_run` | string | Format 3: optional declared binary name | | `profiles` | object | Format 3: dev/release overrides and custom profiles inheriting one builtin | | `build` | object | Format 3: optional default compiler `target` triple | | `target_config` | array of objects | Format 3: exact-triple sysroot/linker and binary platform overrides | A dependency requires a unique `name` and exactly one nonempty `path` or `git` -string. Optional `version` is an exact package version assertion, not a range. +string. Optional `version` is an exact package version assertion. Formats 4/5 additionally +accept explicit SemVer `version_req`. Git alone accepts at most one nonempty `branch`, `tag` or `rev` string. Without a selector, initial fetch and explicit update follow the remote default branch; locked reuse preserves the exact commit. Path values resolve relative to their -own declaring manifest. Dependencies must declare libraries. One package name -cannot identify conflicting sources or versions anywhere in the graph. +own declaring manifest. Dependencies must declare libraries. Formats 1–3 reject conflicting package sources/versions. Formats 4/5 separate +import aliases and package IDs, support explicit `package`, SemVer `version_req`, +Git `subdir`, optional/target dependencies and additive features. A single owner +cannot activate conflicting bindings for one alias. Cross-package alias +conflicts require the versioned Wave package-graph capability. ```wson { @@ -48,7 +55,7 @@ fields, selection, platform restrictions, and migration. Existing formats are not automatically rewritten. Library dependencies may declare binaries in format 3, but consumers only use their library. -Format 1 preserves legacy literal backslashes. Formats 2 and 3 decode `\\`, `\"`, +Format 1 preserves legacy literal backslashes. Formats 2–5 decode `\\`, `\"`, `\/`, `\b`, `\f`, `\n`, `\r`, `\t`, and JSON `\uXXXX` sequences; unsupported escapes are rejected. A format change is explicit: files are never silently reinterpreted. Additive fields may retain a @@ -58,7 +65,8 @@ and compiler requirement. See [compatibility policy](release-readiness.md). ## Dependency state -Commit generated `vex.lock`. New writes use v3; compatible v2 stays byte-identical +Commit generated `vex.lock`. Formats 4/5 write union graph v4; legacy manifests +retain v3 writes. Compatible v2 stays byte-identical under `--locked`. Legacy v1 needs an explicit normal fetch to migrate. Unsupported, malformed, conflicting or cyclic locks fail before publication. Git commits are exact; path content is not pinned and must be versioned separately. @@ -121,6 +129,8 @@ reusing a pruned dependency may require network access through `fetch`. | Variable | Contract | | --- | --- | +| `VEX_BUILD_DIR`, `VEX_STATE_DIR` | External storage defaults; explicit CLI paths take precedence | +| `VEX_WAVE_STD` | Prepared std root selected before entering the project | | `VEX_WAVEC` | Explicit selected compiler; empty is an error; relative paths use invocation directory | | `PATH` | Compiler and required system-tool lookup; precedes the managed compiler | | `VEX_TOOLCHAIN_HOME` | Managed compiler installation root; default documented in [installation](../README.md#install) | @@ -166,7 +176,9 @@ start stops Vex; reporting failure after program start warns and preserves the program exit. Missing final events mean an incomplete report. Machine-readable schemas: [metadata v1](schemas/metadata-v1.json), -[metadata v2](schemas/metadata-v2.json), [build-plan v1](schemas/build-plan-v1.json), +[metadata v2](schemas/metadata-v2.json), [metadata v3](schemas/metadata-v3.json), +[build-plan v2](schemas/build-plan-v2.json), [completed artifacts](schemas/artifacts-v1.json), +[toolchain pins](schemas/toolchain-v1.json), [doctor](schemas/doctor-v1.json) and [message events](schemas/messages-v1.json). Additive fields are permitted; changed existing meanings require a new schema version. There is no registry or publish @@ -188,7 +200,7 @@ already successful artifacts. General and native output paths are unified under `.vex-obj////`. Old paths are left untouched. Run keeps an independent generation, lease and lock-release boundary. -Dry-run stdout is one `vex.build-plan` schema-1 envelope for single or multiple +Dry-run stdout is one `vex.build-plan` schema-2 envelope for single or multiple targets. It contains `target`, `profile: {name, opt_level}`, and ordered `plans` entries with `package_target: {name, kind}` and the validated `compiler_plan`. It replaces the previous direct compiler-plan output. Planning runs once per diff --git a/docs/release-readiness.md b/docs/release-readiness.md index 50828fb..449a7d3 100644 --- a/docs/release-readiness.md +++ b/docs/release-readiness.md @@ -1,7 +1,11 @@ -# Unreleased: targets, profiles, and format migration +# Unreleased: v0.0.3-beta integration This describes the development branch, not an already published Vex release. -No release version or tag is assigned by this change. +The planned version is `0.0.3-beta`; no tag or release is created by this text. + +The current storage, archive, pin, graph and publication contracts are in +[external builds](external-builds.md). Existing public-compiler acceptance remains +mandatory; new Wave capability gates await a compatible public artifact. ## Compatibility window @@ -10,12 +14,15 @@ No release version or tag is assigned by this change. | Manifest without `format`, or format 1 | Literal backslashes | Same | Same | | Manifest format 2 | JSON string escapes | Same | Same | | Manifest format 3 | Explicit package targets/profiles; JSON string escapes | Same; no manifest rewrite | Same | -| Lockfile v1 | Resolve and migrate to v3 | Reject unchanged | Migrate only from locally available sources | -| Lockfile v2 | Read legacy strings; successful resolution may migrate to v3 | Preserve bytes if graph matches | Never fetch; migration still allowed without `--locked` | -| Lockfile v3 | Read/write escaped strings | Preserve bytes if graph matches | Never fetch | +| Lockfile v1 | Resolve and migrate to the selected manifest graph format | Reject unchanged | Migrate only from locally available sources | +| Lockfile v2 | Read legacy strings; successful resolution may migrate to the selected manifest graph format | Preserve bytes if graph matches | Never fetch; migration still allowed without `--locked` | +| Manifest format 4 | SemVer, aliases, features and user workspaces | Same; no rewrite | Same | +| Manifest format 5 | External build integration and library settings | Same; no rewrite | Same | +| Lockfile v4 | Union graph, concrete IDs and escaped strings | Preserve bytes if graph matches | Never fetch | +| Lockfile v3 | Read escaped strings; normal resolution may migrate | Preserve bytes if graph matches | Never fetch | | Unknown format or malformed graph | Error; preserve file | Error; preserve file | Error; preserve file | -Older Vex binaries do not understand manifest format 2 or lockfile v3. Upgrade +Older Vex binaries may not understand manifest format 5 or lockfile v4. Upgrade collaborators before committing a migrated lockfile. Existing manifests are never automatically rewritten. To opt into escaped strings, add `format = 2` and encode each existing string's actual value, rather than guessing what backslashes meant. @@ -26,7 +33,7 @@ The new shared WSON boundary recognizes comments and delimiters only outside strings. It preserves URL fragments and former sentinel text, rejects duplicate keys, and reports parser source locations. Unsupported versioned escapes fail before graph publication. Package version strings retain their existing meaning; -format versions do not introduce SemVer dependency requirements or a registry. +formats 4/5 introduce explicit SemVer requirements without a registry. ## Target/profile migration (#46, #47, #48, #54) @@ -34,7 +41,7 @@ Manifest format 3 opts into an explicit library and named binaries, root profile default run selection, and exact-triple build settings. Legacy formats retain their meaning, and are not rewritten. Use `targets.lib` instead of root `lib`, and put library output/exports there instead of `native`. Keep native inputs in -root `native`. Lockfile v3 retains its source, commit and edge meanings. +root `native`. Historical lockfile v3 retains its source, commit and edge meanings. All manifests now produce ordinary/native outputs under `target///{bin,lib}/`, with isolated intermediate objects. @@ -46,7 +53,7 @@ generations and releases the build lock before starting the program. profiles have optimization levels 0–3 and inherit only dev or release. Build/check default to all root targets; run requires an unambiguous binary choice. -Dry-run stdout changes for every project: it is one `vex.build-plan` schema-1 +Dry-run stdout changes for every project: it is one `vex.build-plan` schema-2 JSON envelope, containing the profile and target-specific compiler plans, rather than a direct compiler plan. Consumers must update their readers. Metadata keeps schema 1 as the default for single-target packages; a mixed/multiple-target diff --git a/docs/roadmap.md b/docs/roadmap.md index 0eae403..2a05858 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,40 +1,36 @@ -# Vex stabilization roadmap - -Vex `v0.0.2-beta` is published. Its release acceptance covers all nine hosts in -[platforms.json](../platforms.json), public Wave `0.2.1-pre-beta` artifacts, -transaction recovery, installation verification and release provenance. -See [platform validation](../README.md#platform-validation) for the tested -baselines and the limits of emulated runtime evidence. Every subsequent release -must pass those same platform gates for its own source commit. - -## Current operational follow-up - -This source branch adds explicit, conservative build cleanup (#49) and unused -checkout pruning (#88), offline environment diagnosis (#53), quiet/verbose -output policy (#62), inverse/depth tree queries (#64), and reuse of refs already -obtained by an initial clone (#43). These changes still require the normal PR -review and nine-platform CI before being included in a release. - -Cleanup preserves untracked/legacy state and edited files. Live run generations -have independent OS leases; there is no automatic GC. Prune defaults to preview -and requires `--apply` for deletion. Recovery transactions, transaction backups -and prior compiler installations remain outside deletion scope. - -The current target/profile work (#46/#47/#48/#54) adds manifest format 3, -explicit library and binary targets, unified artifact paths, root profiles and -exact-triple platform settings. Metadata schema 2 describes these declarations; -dry-run uses a Vex build-plan envelope. See [the contract](targets-and-profiles.md) -for compatibility details. Acceptance follows the checks for this source commit. - -## Separate designs - -User workspaces (#30), shared caches (#29), manifest editing (#28), build -fingerprints (#59), package version -ranges (#132/#51), optional dependencies, registry and publish remain separate -product work. Implemented project discovery, metadata, lockfile v3, source -credential handling, project leases, isolated run generations and atomic init -are maintained rather than reimplemented. - -Issue closure follows acceptance evidence, not roadmap checkboxes. Build-only -cross checks do not establish native runtime support, and a compiler schema -match alone does not establish package-language compatibility. +# Vex development and release acceptance + +The public release is `v0.0.2-beta`. The current integration targets +`v0.0.3-beta`; implementation on a branch is not evidence of a published release. + +The existing base includes user workspaces, content-verified build reuse, Git +object sharing/subdirectories, conditional dependency/feature union locks, +SemVer/aliases, new/add/remove transactions, main-based executable tests, +cleanup/prune, doctor, tree queries and Meson repository automation. These are +maintained through their regression suites. + +The v0.0.3 integration covers external build/dependency roots (#177), complete +depfiles (#178), reusable completed results (#179), library mode/relocation +(#180), compiler/std content pins (#181), bounded reproducibility (#182), +last-good artifact generations (#183), a real Meson C/C++/Rust consumer (#184) +and deterministic static archives (#185). It also addresses #162–174, conditional +alias removal #186, issue forms #76 and subsystem ownership #83. See +[the implementation contracts and validation limits](external-builds.md). + +Full package-scoped multiple-version imports (#58) additionally require the +separate Wave #1066 contract; logical remapping requires Wave #1067. Existing +public Wave 0.2.1 acceptance stays required on all nine hosts. New capability +acceptance must use a verified compatible public Wave release before it becomes +a mandatory release gate. Local development-compiler or cross-format object +inspection does not establish native execution support for those new features. + +The approved test workflow (#60) uses explicit main-based test targets, separate +test dependencies, deterministic filters, JSONL results and unchanged program +exit codes. Compiler-native unit-test syntax/harness is not claimed. No registry, +publish, foreign-source build-script system or automatic garbage collector is +introduced by this integration. + +Issue completion follows implemented acceptance and test evidence. A release +requires all nine host reports for its exact commit, including native ABI +consumers and RISC-V/LoongArch cross-build plus QEMU execution. Historical CI +results do not validate a later source commit. diff --git a/docs/schemas/artifacts-v1.json b/docs/schemas/artifacts-v1.json new file mode 100644 index 0000000..840f843 --- /dev/null +++ b/docs/schemas/artifacts-v1.json @@ -0,0 +1,93 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Vex completed artifacts v1", + "type": "object", + "required": [ + "schema", + "schema_version", + "results" + ], + "properties": { + "schema": { + "const": "vex.artifacts" + }, + "schema_version": { + "const": 1 + }, + "results": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "required": [ + "schema", + "schema_version", + "generation", + "metadata", + "provenance", + "artifacts" + ], + "properties": { + "schema": { + "const": "vex.artifact-generation" + }, + "schema_version": { + "const": 1 + }, + "generation": { + "type": "string" + }, + "metadata": { + "type": "object", + "required": [ + "package", + "package_target", + "target", + "profile", + "features", + "settings", + "compiler", + "inputs" + ] + }, + "provenance": { + "type": "object" + }, + "artifacts": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "required": [ + "role", + "path", + "published_path", + "sha256" + ], + "properties": { + "role": { + "enum": [ + "primary", + "intermediate", + "debug", + "import_library" + ] + }, + "path": { + "type": "string" + }, + "published_path": { + "type": "string" + }, + "sha256": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + } + } + } + } + } + } + } + } +} diff --git a/docs/schemas/build-plan-v2.json b/docs/schemas/build-plan-v2.json new file mode 100644 index 0000000..52bd170 --- /dev/null +++ b/docs/schemas/build-plan-v2.json @@ -0,0 +1,115 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Vex build-plan v2", + "type": "object", + "required": [ + "schema", + "schema_version", + "target", + "profile", + "plans" + ], + "properties": { + "schema": { + "const": "vex.build-plan" + }, + "schema_version": { + "const": 2 + }, + "target": { + "type": "string" + }, + "profile": { + "type": "object", + "required": [ + "name", + "opt_level" + ], + "properties": { + "name": { + "type": "string" + }, + "opt_level": { + "type": "integer", + "minimum": 0, + "maximum": 3 + } + } + }, + "plans": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "required": [ + "package_target", + "compiler_plan" + ], + "properties": { + "package_target": { + "type": "object", + "required": [ + "name", + "kind" + ], + "properties": { + "name": { + "type": "string" + }, + "kind": { + "enum": [ + "library", + "binary" + ] + } + } + }, + "compiler_plan": { + "type": "object" + }, + "package": { + "type": "string" + }, + "manifest_path": { + "type": "string" + }, + "build_directory": { + "type": "string" + }, + "run_directory": { + "type": [ + "string", + "null" + ] + }, + "project_directory": { + "type": "string" + } + } + } + }, + "toolchain": { + "type": [ + "object", + "null" + ] + }, + "reports": { + "type": "object", + "properties": { + "artifact_manifest": { + "type": [ + "string", + "null" + ] + }, + "depfile": { + "type": [ + "string", + "null" + ] + } + } + } + } +} diff --git a/docs/schemas/metadata-v3.json b/docs/schemas/metadata-v3.json new file mode 100644 index 0000000..756d78f --- /dev/null +++ b/docs/schemas/metadata-v3.json @@ -0,0 +1,420 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Vex metadata v3", + "type": "object", + "required": [ + "schema_version", + "root", + "packages", + "target_directory" + ], + "properties": { + "schema_version": { + "const": 3 + }, + "root": { + "oneOf": [ + { + "$ref": "#/$defs/package" + }, + { + "$ref": "#/$defs/workspace" + } + ] + }, + "packages": { + "type": "array", + "items": { + "$ref": "#/$defs/package" + } + }, + "target_directory": { + "type": "string" + }, + "selection": { + "type": [ + "object", + "null" + ] + }, + "selected_features": { + "type": "object" + }, + "union_bindings": { + "type": "array", + "items": { + "type": "object" + } + }, + "selections": { + "type": "array", + "items": { + "type": "object" + } + }, + "workspace_members": { + "type": "array", + "items": { + "$ref": "#/$defs/package" + } + }, + "build_directory": { + "type": "string" + }, + "state_directory": { + "type": "string" + }, + "toolchain_lock": { + "type": [ + "object", + "null" + ] + } + }, + "$defs": { + "package": { + "type": "object", + "required": [ + "name", + "version", + "root", + "manifest_path", + "dependencies", + "manifest_format", + "compiler", + "targets", + "default_run", + "profiles", + "build_target", + "target_config" + ], + "properties": { + "name": { + "type": "string" + }, + "version": { + "type": "string" + }, + "root": { + "type": "string" + }, + "manifest_path": { + "type": "string" + }, + "dependencies": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true + }, + "manifest_format": { + "enum": [ + 1, + 2, + 3, + 4 + ] + }, + "compiler": { + "type": [ + "string", + "null" + ] + }, + "source": { + "type": "object", + "required": [ + "kind" + ], + "properties": { + "kind": { + "enum": [ + "path", + "git" + ] + } + } + }, + "native": { + "type": [ + "object", + "null" + ], + "properties": { + "output": { + "enum": [ + "object", + "shared", + null + ] + }, + "exports": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" + }, + "uniqueItems": true + }, + "libraries": { + "type": "array", + "items": { + "type": "object" + } + }, + "search_paths": { + "type": "array", + "items": { + "type": "object" + } + } + } + }, + "targets": { + "type": "array", + "items": { + "$ref": "#/$defs/target" + } + }, + "default_run": { + "type": [ + "string", + "null" + ] + }, + "profiles": { + "type": "object", + "required": [ + "dev", + "release" + ], + "additionalProperties": { + "type": "object", + "required": [ + "opt_level", + "inherits" + ], + "properties": { + "opt_level": { + "type": "integer", + "minimum": 0, + "maximum": 3 + }, + "inherits": { + "enum": [ + "dev", + "release", + null + ] + } + } + } + }, + "build_target": { + "type": [ + "string", + "null" + ] + }, + "target_config": { + "type": "array", + "items": { + "type": "object", + "required": [ + "triple", + "sysroot", + "linker", + "bins" + ], + "properties": { + "triple": { + "type": "string" + }, + "sysroot": { + "type": [ + "string", + "null" + ] + }, + "linker": { + "type": [ + "string", + "null" + ] + }, + "bins": { + "type": "array", + "items": { + "type": "object", + "required": [ + "name", + "platform" + ], + "properties": { + "name": { + "type": "string" + }, + "platform": { + "$ref": "#/$defs/platform" + } + } + } + } + } + } + }, + "id": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "alias": { + "type": "string" + }, + "binding": { + "type": "string" + }, + "features": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "tests": { + "type": "array", + "items": { + "type": "object", + "required": [ + "name", + "entry_path", + "platform" + ] + } + } + } + }, + "platform": { + "type": "object", + "required": [ + "mode", + "entry", + "startup", + "linker_script" + ], + "properties": { + "mode": { + "enum": [ + "hosted", + "freestanding", + "wasi", + "bare_wasm", + null + ] + }, + "entry": { + "type": [ + "string", + "null" + ] + }, + "startup": { + "enum": [ + "default", + "none", + null + ] + }, + "linker_script": { + "type": [ + "string", + "null" + ] + } + } + }, + "target": { + "type": "object", + "required": [ + "name", + "kind", + "entry_path", + "output", + "exports", + "platform" + ], + "properties": { + "name": { + "type": "string" + }, + "kind": { + "enum": [ + "library", + "binary" + ] + }, + "entry_path": { + "type": "string" + }, + "output": { + "enum": [ + "object", + "shared", + null + ] + }, + "exports": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true + }, + "platform": { + "$ref": "#/$defs/platform" + } + } + }, + "workspace": { + "type": "object", + "required": [ + "kind", + "root", + "manifest_path", + "members", + "default_members" + ], + "properties": { + "kind": { + "const": "workspace" + }, + "root": { + "type": "string" + }, + "manifest_path": { + "type": "string" + }, + "package": { + "type": [ + "string", + "null" + ] + }, + "members": { + "type": "array", + "items": { + "type": "string" + } + }, + "default_members": { + "type": "array", + "items": { + "type": "string" + } + } + } + } + } +} diff --git a/docs/schemas/toolchain-v1.json b/docs/schemas/toolchain-v1.json new file mode 100644 index 0000000..4526e1c --- /dev/null +++ b/docs/schemas/toolchain-v1.json @@ -0,0 +1,50 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Vex toolchain identity v1", + "type": "object", + "required": [ + "schema_version", + "hosts" + ], + "additionalProperties": false, + "properties": { + "schema_version": { + "const": 1 + }, + "hosts": { + "type": "object", + "additionalProperties": { + "type": "object", + "required": [ + "compiler_version", + "compiler_sha256", + "std_sha256" + ], + "additionalProperties": false, + "properties": { + "compiler_version": { + "type": "string" + }, + "compiler_sha256": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "std_sha256": { + "oneOf": [ + { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + { + "type": "null" + } + ] + }, + "source_revision": { + "type": "null" + } + } + } + } + } +} diff --git a/docs/targets-and-profiles.md b/docs/targets-and-profiles.md index 22639d1..e051d7a 100644 --- a/docs/targets-and-profiles.md +++ b/docs/targets-and-profiles.md @@ -172,7 +172,7 @@ even when selecting a single target: ```json { "schema": "vex.build-plan", - "schema_version": 1, + "schema_version": 2, "target": "x86_64-unknown-linux-gnu", "profile": { "name": "dev", "opt_level": 0 }, "plans": [ @@ -195,3 +195,7 @@ direct compiler-plan stdout shape is replaced by this envelope. configuration without querying a compiler. It does not guess an actual default compiler triple or an artifact path. `vex metadata` defaults to schema 1 for single-target consumers; use `--format-version 2` for mixed or multiple targets. + +Format 5 extends the library declarations, external storage, completed results +and dry-run schema 2. See [external builds](external-builds.md). Formats 1–4 +retain their meanings; new initialization uses format 5 with a ready v4 lock. diff --git a/docs/vex.1 b/docs/vex.1 index cd6ae0e..a805beb 100644 --- a/docs/vex.1 +++ b/docs/vex.1 @@ -3,22 +3,22 @@ vex \- Wave package manager .SH SYNOPSIS .B vex -[-q|--quiet] [-v|--verbose] [--message-file ] [--manifest-path ] [-p|--package |--workspace] [--features ] [--no-default-features] [--include-tests] [options] +[-q|--quiet] [-v|--verbose] [--message-file ] [--manifest-path ] [-p|--package |--workspace] [--features ] [--no-default-features] [--include-tests] [--build-dir ] [--state-dir ] [options] .SH COMMANDS .TP .B vex init [\-\-lib] Manage init .TP -.B vex build [\-\-lib] [\-\-bin ] [\-\-target ] [\-\-profile |\-\-release] [\-\-dry\-run] [\-\-locked] [\-\-offline] +.B vex build [\-\-lib] [\-\-bin ] [\-\-target ] [\-\-profile |\-\-release] [\-\-dry\-run] [\-\-locked] [\-\-offline] [\-\-artifact\-manifest ] [\-\-depfile ] Compile selected package targets .TP -.B vex run [\-\-bin ] [\-\-target ] [\-\-profile |\-\-release] [\-\-dry\-run] [\-\-locked] [\-\-offline] [\-\- ] +.B vex run [\-\-bin ] [\-\-target ] [\-\-profile |\-\-release] [\-\-dry\-run] [\-\-locked] [\-\-offline] [\-\-artifact\-manifest ] [\-\-depfile ] [\-\- ] Compile and execute one binary .TP .B vex check [\-\-lib] [\-\-bin ] [\-\-target ] [\-\-profile |\-\-release] [\-\-dry\-run] [\-\-locked] [\-\-offline] Check selected package targets .TP -.B vex test [filter] [\-\-target ] [\-\-profile |\-\-release] [\-\-dry\-run] [\-\-locked] [\-\-offline] [\-\- ] +.B vex test [filter] [\-\-target ] [\-\-profile |\-\-release] [\-\-dry\-run] [\-\-locked] [\-\-offline] [\-\-artifact\-manifest ] [\-\-depfile ] [\-\- ] Compile and execute explicit main-based tests; run every selected test and return the first failure .TP .B vex fetch [\-\-locked] [\-\-offline] [\-\-target ] @@ -30,7 +30,7 @@ Manage update .B vex info Manage info .TP -.B vex metadata [\-\-format=json] [\-\-format\-version <1|2>] [\-\-locked] [\-\-offline] [\-\-target ] +.B vex metadata [\-\-format=json] [\-\-format\-version <1|2|3>] [\-\-locked] [\-\-offline] [\-\-target ] Manage metadata .TP .B vex tree [\-\-invert ] [\-\-depth ] [\-\-locked] [\-\-offline] [\-\-target ] @@ -65,6 +65,9 @@ Print shell completion script .TP .B vex manpage Print the vex(1) manual +.TP +.B vex toolchain capture [\-\-wavec ] [\-\-std ] [\-\-replace] +Record a prepared host compiler/std pair by content identity; never downloads a toolchain. .SH FILES vex.ws, vex.lock .SH ENVIRONMENT diff --git a/examples/meson-consumer/caller.c b/examples/meson-consumer/caller.c new file mode 100644 index 0000000..31b1712 --- /dev/null +++ b/examples/meson-consumer/caller.c @@ -0,0 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +#include +int32_t wave_answer(void); +int main(void) { return wave_answer() == 42 ? 0 : 1; } diff --git a/examples/meson-consumer/caller.cpp b/examples/meson-consumer/caller.cpp new file mode 100644 index 0000000..2beba42 --- /dev/null +++ b/examples/meson-consumer/caller.cpp @@ -0,0 +1,7 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +#include +extern "C" std::int32_t wave_answer(); +int main() { return wave_answer() == 42 ? 0 : 1; } diff --git a/examples/meson-consumer/caller.rs b/examples/meson-consumer/caller.rs new file mode 100644 index 0000000..1791d59 --- /dev/null +++ b/examples/meson-consumer/caller.rs @@ -0,0 +1,6 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +unsafe extern "C" { fn wave_answer() -> i32; } +fn main() { assert_eq!(unsafe { wave_answer() }, 42); } diff --git a/examples/meson-consumer/fixture.json b/examples/meson-consumer/fixture.json new file mode 100644 index 0000000..0e18812 --- /dev/null +++ b/examples/meson-consumer/fixture.json @@ -0,0 +1,14 @@ +{ + "schema_version": 1, + "purpose": "Reviewed minimal Whale-shaped freestanding/PIC C ABI fixture; not Whale compiler source", + "sha256": { + "wave/vex.ws": "54058f1347f1d48d9f5e125f1b26726ac777687c818d0b86a303b8acfeb75ce7", + "wave/src/lib.wave": "c32acf78e9a7e24f397dcf7454b15bf56ce68f635f15b2ff047dba89639f776f", + "math/vex.ws": "c775c433d86b41f70d20f1554215110fb6797c13cf4bfada835e03ebf0a05e06", + "math/src/lib.wave": "ac3c02128b160e2ceb6f421b86a4af8da8377caebc8ebc5d8a70ded2b79e4958", + "math/src/value.wave": "186faddecceb6e2ad58e44b98d244674e51eb3e48c66585f430cbc2e73b53032", + "caller.c": "8dbe7e665d201fbd5480d13c9b7c4c23518d448c9d804f22043447e31d050b2c", + "caller.cpp": "eba449d4cf2053cb2c13e7fab9de04552faaf606f834ec94df1ce127c07f8731", + "caller.rs": "69b6e6e2af7297bb0c5220e21195b7777157924755691a453edcb6b4689987ee" + } +} diff --git a/examples/meson-consumer/math/src/lib.wave b/examples/meson-consumer/math/src/lib.wave new file mode 100644 index 0000000..662e7d1 --- /dev/null +++ b/examples/meson-consumer/math/src/lib.wave @@ -0,0 +1 @@ +pub import("./value.wave")::{answer}; diff --git a/examples/meson-consumer/math/src/value.wave b/examples/meson-consumer/math/src/value.wave new file mode 100644 index 0000000..fe1afb4 --- /dev/null +++ b/examples/meson-consumer/math/src/value.wave @@ -0,0 +1 @@ +pub fun answer() -> i32 { return 42; } diff --git a/examples/meson-consumer/math/vex.ws b/examples/meson-consumer/math/vex.ws new file mode 100644 index 0000000..11febaf --- /dev/null +++ b/examples/meson-consumer/math/vex.ws @@ -0,0 +1 @@ +{ format = 5, name = "math", version = "0.1.0", targets = { lib = {} } } diff --git a/examples/meson-consumer/meson.build b/examples/meson-consumer/meson.build new file mode 100644 index 0000000..f6aeb23 --- /dev/null +++ b/examples/meson-consumer/meson.build @@ -0,0 +1,74 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 +project( + 'vex-consumer', + 'c', + 'cpp', + 'rust', + meson_version: '>=1.8.5', + default_options: ['rust_std=2021'], +) +python = import('python').find_installation() +vex = find_program(get_option('vex'), native: true) +bridge_name = host_machine.system() == 'windows' ? 'wave_bridge.lib' : 'libwave_bridge.a' +adapter = get_option('adapter') +if adapter == '' + adapter = meson.current_source_dir() / '../../tools/meson_consumer.py' +endif +command = [ + python, + adapter, + '--vex', + vex, + '--manifest', + meson.current_source_dir() / 'wave/vex.ws', + '--build-dir', + meson.current_build_dir() / 'vex', + '--profile', + get_option('wave_profile'), + '--kind', + 'static', + '--output', + '@OUTPUT0@', + '--depfile', + '@DEPFILE@', + '--rust-main', + '@OUTPUT1@', + '--rust-source', + meson.current_source_dir() / 'caller.rs', +] +if get_option('wave_target') != '' + command += ['--target', get_option('wave_target')] +endif +foreach feature : get_option('wave_features') + command += ['--features', feature] +endforeach +# Always run the bounded freshness scan, including new/deleted imports. The +# adapter leaves the bridge mtime unchanged when verified bytes are unchanged. +wave = custom_target( + 'wave', + output: [bridge_name, 'caller_wave.rs'], + depfile: 'wave.d', + command: command, + build_always_stale: true, +) +foreach language : ['c', 'cpp', 'rs'] + if language == 'rs' + # The generated Rust entry includes caller.rs and the verified digest. + # It is a real compiler input, so Meson 1.8 schedules and relinks it. + caller = executable( + 'caller_rs', + wave[1], + rust_args: ['-Clink-arg=' + wave[0].full_path()], + ) + else + caller = executable( + 'caller_' + language, + 'caller.' + language, + link_with: wave[0], + ) + endif + test('wave-' + language, caller) +endforeach diff --git a/examples/meson-consumer/meson.options b/examples/meson-consumer/meson.options new file mode 100644 index 0000000..f4d4c21 --- /dev/null +++ b/examples/meson-consumer/meson.options @@ -0,0 +1,24 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 +option( + 'vex', + type: 'string', + value: 'vex', + description: 'Prepared Vex executable on the build machine', +) +option( + 'wave_target', + type: 'string', + value: '', + description: 'Exact Wave output target; empty selects compiler host', +) +option('wave_profile', type: 'string', value: 'dev') +option('wave_features', type: 'array', value: []) +option( + 'adapter', + type: 'string', + value: '', + description: 'Optional absolute path to tools/meson_consumer.py', +) diff --git a/examples/meson-consumer/wave/src/lib.wave b/examples/meson-consumer/wave/src/lib.wave new file mode 100644 index 0000000..5b243fc --- /dev/null +++ b/examples/meson-consumer/wave/src/lib.wave @@ -0,0 +1,2 @@ +import("math")::{answer}; +export(c) fun wave_answer() -> i32 { return answer(); } diff --git a/examples/meson-consumer/wave/vex.ws b/examples/meson-consumer/wave/vex.ws new file mode 100644 index 0000000..410489c --- /dev/null +++ b/examples/meson-consumer/wave/vex.ws @@ -0,0 +1,8 @@ +{ format = 5, name = "wave_bridge", version = "0.1.0", + targets = { lib = { output = "static", mode = "freestanding", relocation = "pic" } }, + target_config = [ + { triple = "x86_64-pc-windows-msvc", lib = { relocation = "default" } }, + { triple = "aarch64-pc-windows-msvc", lib = { relocation = "default" } } + ], + features = { tuned = [] }, + dependencies = [{ name = "math", path = "../math" }] } diff --git a/lockfile/Cargo.toml b/lockfile/Cargo.toml index 98f4cd4..e24e576 100644 --- a/lockfile/Cargo.toml +++ b/lockfile/Cargo.toml @@ -18,3 +18,5 @@ wson.workspace = true sha2 = "0.11.1" serde_json.workspace = true serde = { version = "1", features = ["derive"] } + +state.workspace = true diff --git a/lockfile/src/lib.rs b/lockfile/src/lib.rs index 84f5522..4fd9e37 100644 --- a/lockfile/src/lib.rs +++ b/lockfile/src/lib.rs @@ -63,9 +63,14 @@ impl LockedPackage { pub fn directory(&self) -> PathBuf { let (LockedSource::Path { resolved, .. } | LockedSource::Git { resolved, .. }) = &self.source; + let physical = if resolved.starts_with(".vex") { + state::layout::dependency(&std::env::current_dir().unwrap_or_default(), resolved) + } else { + resolved.clone() + }; self.subdir .as_ref() - .map_or_else(|| resolved.clone(), |subdir| resolved.join(subdir)) + .map_or_else(|| physical.clone(), |subdir| physical.join(subdir)) } } diff --git a/manifest/src/lib.rs b/manifest/src/lib.rs index 2042e71..1277114 100644 --- a/manifest/src/lib.rs +++ b/manifest/src/lib.rs @@ -93,6 +93,8 @@ pub struct Manifest { pub default_run: Option, pub profiles: BTreeMap, pub build_target: Option, + pub reproducible: bool, + pub archiver: Option, pub target_config: Vec, pub description: Option, pub author: Option, @@ -224,6 +226,16 @@ impl Manifest { { platform.overlay(&overrides.platform); } + if target.kind == TargetKind::Library { + if let Some(library) = self + .target_config + .iter() + .find(|c| c.triple == triple) + .and_then(|c| c.library.as_ref()) + { + platform.overlay(library); + } + } platform } } diff --git a/manifest/src/model.rs b/manifest/src/model.rs index 5e1cc49..e3ad9df 100644 --- a/manifest/src/model.rs +++ b/manifest/src/model.rs @@ -69,9 +69,13 @@ pub struct PlatformSettings { pub entry: Option, pub startup: Option, pub linker_script: Option, + pub relocation: Option, } impl PlatformSettings { pub(crate) fn overlay(&mut self, other: &Self) { + if other.relocation.is_some() { + self.relocation.clone_from(&other.relocation); + } if other.mode.is_some() { self.mode = other.mode; } @@ -97,6 +101,8 @@ pub struct TargetConfig { pub sysroot: Option, pub linker: Option, pub bins: Vec, + pub library: Option, + pub archiver: Option, } #[derive(Clone, Debug, Eq, PartialEq)] pub struct BinaryOverride { @@ -143,15 +149,54 @@ pub(crate) fn parse(data: &WsonMap, package_name: &str) -> Result let mut targets = Vec::new(); if let Some(value) = target_object.get("lib") { let library = object(Some(value), "targets.lib")?; - reject_unknown_fields(library, &["output", "exports"], "targets.lib")?; + reject_unknown_fields( + library, + &["output", "exports", "mode", "relocation"], + "targets.lib", + )?; + let format5 = matches!(data.get("format"), Some(WsonValue::Int(5))); + if !format5 + && ["mode", "relocation"] + .iter() + .any(|key| library.contains_key(*key)) + { + return Err("library mode/relocation require format = 5".into()); + } + let library_mode = string(library, "mode", "targets.lib")?; + let mode = match library_mode.as_deref() { + None => None, + Some("hosted") => Some(PlatformMode::Hosted), + Some("freestanding") => Some(PlatformMode::Freestanding), + _ => return Err("library mode must be hosted or freestanding".into()), + }; + let relocation = string(library, "relocation", "targets.lib")?; + if relocation + .as_ref() + .is_some_and(|r| !matches!(r.as_str(), "default" | "pic" | "static")) + { + return Err("library relocation must be default, pic, or static".into()); + } let output = match string(library, "output", "targets.lib")?.as_deref() { None | Some("object") => NativeOutput::Object, Some("shared") => NativeOutput::Shared, + Some("static") if format5 => NativeOutput::Static, Some(_) => return Err("targets.lib output must be `object` or `shared`".into()), }; // The native export parser enforces one portable C symbol per entry. let mut export_config = library.clone(); - export_config.insert("output".into(), WsonValue::String(output.as_str().into())); + export_config.remove("mode"); + export_config.remove("relocation"); + export_config.insert( + "output".into(), + WsonValue::String( + if output == NativeOutput::Static { + "object" + } else { + output.as_str() + } + .into(), + ), + ); let exports = native::parse(Some(&WsonValue::Object(export_config)), true)? .expect("library config exists") .exports; @@ -161,7 +206,11 @@ pub(crate) fn parse(data: &WsonMap, package_name: &str) -> Result path: "src/lib.wave".into(), output: Some(output), exports, - platform: PlatformSettings::default(), + platform: PlatformSettings { + mode, + relocation, + ..Default::default() + }, }); } let mut bin_names = HashSet::new(); @@ -212,7 +261,7 @@ pub(crate) fn parse(data: &WsonMap, package_name: &str) -> Result None => None, Some(value) => { let build = object(Some(value), "build")?; - reject_unknown_fields(build, &["target"], "build")?; + reject_unknown_fields(build, &["target", "reproducible", "archiver"], "build")?; let target = string(build, "target", "build")?; if let Some(triple) = &target { validate_triple(triple)?; @@ -226,7 +275,7 @@ pub(crate) fn parse(data: &WsonMap, package_name: &str) -> Result let config = object(Some(value), "target_config entry")?; reject_unknown_fields( config, - &["triple", "sysroot", "linker", "bins"], + &["triple", "sysroot", "linker", "bins", "lib", "archiver"], "target_config", )?; let triple = required_string(config, "triple", "target_config")?; @@ -270,7 +319,49 @@ pub(crate) fn parse(data: &WsonMap, package_name: &str) -> Result validate_platform(&combined, "target_config binary override")?; bins.push(BinaryOverride { name, platform }); } + let library = if let Some(value) = config.get("lib") { + if !matches!(data.get("format"), Some(WsonValue::Int(5))) { + return Err("target_config.lib requires format = 5".into()); + } + let value = object(Some(value), "target_config.lib")?; + reject_unknown_fields(value, &["mode", "relocation"], "target_config.lib")?; + let mode = match string(value, "mode", "target_config.lib")?.as_deref() { + None => None, + Some("hosted") => Some(PlatformMode::Hosted), + Some("freestanding") => Some(PlatformMode::Freestanding), + _ => return Err("library mode must be hosted or freestanding".into()), + }; + let relocation = string(value, "relocation", "target_config.lib")?; + if relocation + .as_ref() + .is_some_and(|r| !matches!(r.as_str(), "default" | "pic" | "static")) + { + return Err("invalid library relocation".into()); + } + if !targets.iter().any(|t| t.kind == TargetKind::Library) { + return Err("library override requires a library target".into()); + } + Some(PlatformSettings { + mode, + relocation, + ..Default::default() + }) + } else { + None + }; + let archiver = string(config, "archiver", "target_config")?; + if archiver.is_some() && !matches!(data.get("format"), Some(WsonValue::Int(5))) { + return Err("target archiver requires format = 5".into()); + } + if archiver + .as_ref() + .is_some_and(|v| v.is_empty() || v.starts_with('-')) + { + return Err("archiver must be one executable name or path".into()); + } configs.push(TargetConfig { + library, + archiver, triple, sysroot, linker, @@ -401,6 +492,7 @@ fn platform(object: &WsonMap, context: &str) -> Result }) .transpose()?; Ok(PlatformSettings { + relocation: None, mode, entry, startup, @@ -742,12 +834,12 @@ mod tests { } #[test] - fn new_manifest_round_trips_explicit_format_three_targets_and_escaped_author() { + fn new_manifest_round_trips_format_five_targets_and_escaped_author() { for is_lib in [false, true] { let author = "Author \"quoted\" \\ path\nnext"; let raw = render_new_manifest("app", author, is_lib); let m = decode(&raw, "vex.ws".into()).unwrap(); - assert_eq!(m.format, 3); + assert_eq!(m.format, 5); assert_eq!(m.lib, is_lib); assert_eq!(m.author.as_deref(), Some(author)); assert_eq!(m.targets.len(), 1); @@ -762,3 +854,30 @@ mod tests { } } } + +#[cfg(test)] +mod external_library_contract { + use crate::{decode, NativeOutput, PlatformMode}; + #[test] + fn format_five_library_settings_are_typed_and_do_not_reinterpret_old_formats() { + let manifest=decode(r#"{format=5,name="ffi",version="1.0.0",targets={lib={output="static",mode="freestanding",relocation="pic"}},build={reproducible=true,archiver="llvm-ar"},target_config=[{triple="aarch64-pc-windows-msvc",lib={relocation="default"},archiver="llvm-lib"}]}"#,"vex.ws".into()).unwrap(); + assert_eq!(manifest.targets[0].output, Some(NativeOutput::Static)); + assert!(manifest.reproducible); + let effective = manifest.platform_for(&manifest.targets[0], "aarch64-pc-windows-msvc"); + assert_eq!(effective.mode, Some(PlatformMode::Freestanding)); + assert_eq!(effective.relocation.as_deref(), Some("default")); + for raw in [ + r#"{format=4,name="ffi",targets={lib={output="static"}}}"#, + r#"{format=4,name="ffi",targets={lib={mode="hosted"}}}"#, + r#"{format=5,name="ffi",targets={lib={mode="wasi"}}}"#, + r#"{format=5,name="ffi",targets={lib={relocation="pie"}}}"#, + r#"{format=5,name="ffi",targets={lib={}},build={archiver=""}}"#, + r#"{format=5,name="ffi",targets={lib={}},build={archiver="-ar"}}"#, + r#"{format=5,name="ffi",targets={lib={}},build={archiver="llvm\u0000ar"}}"#, + r#"{format=5,name="ffi",targets={lib={}},build={reproducible=1}}"#, + r#"{format=5,name="ffi",targets={lib={}},target_config=[{triple="x86_64-unknown-linux-gnu",lib={entry="start"}}]}"#, + ] { + assert!(decode(raw, "vex.ws".into()).is_err(), "accepted {raw}"); + } + } +} diff --git a/manifest/src/native.rs b/manifest/src/native.rs index e346cfe..855983a 100644 --- a/manifest/src/native.rs +++ b/manifest/src/native.rs @@ -21,6 +21,7 @@ pub struct NativeConfig { pub enum NativeOutput { Object, Shared, + Static, } impl NativeOutput { @@ -28,6 +29,7 @@ impl NativeOutput { match self { Self::Object => "object", Self::Shared => "shared", + Self::Static => "static", } } } @@ -106,7 +108,7 @@ pub(crate) fn parse(value: Option<&WsonValue>, lib: bool) -> Result Result { - let data = loads_versions(raw, "format", &[2, 3, 4]) + let data = loads_versions(raw, "format", &[2, 3, 4, 5]) .map_err(|e| format!("failed to parse manifest: {e}"))?; reject_unknown_fields(&data, ROOT_FIELDS, "manifest")?; let format = match data.get("format") { @@ -55,7 +55,8 @@ pub(crate) fn parse_manifest(raw: &str, source_path: PathBuf) -> Result 2, Some(WsonValue::Int(3)) => 3, Some(WsonValue::Int(4)) => 4, - _ => return Err("unsupported manifest format; expected 1 (legacy), 2 (escaped strings), 3 (explicit targets), or 4 (package graphs)".into()), + Some(WsonValue::Int(5)) => 5, + _ => return Err("unsupported manifest format; expected 1 (legacy), 2 (escaped strings), 3 (explicit targets), 4 (package graphs), or 5 (external builds)".into()), }; if format < 3 { for field in [ @@ -222,7 +223,29 @@ pub(crate) fn parse_manifest(raw: &str, source_path: PathBuf) -> Result { + let reproducible = match build.get("reproducible") { + None => false, + Some(WsonValue::Bool(v)) => *v, + _ => return Err("build.reproducible must be boolean".into()), + }; + let archiver = parse_optional_string(build.get("archiver"), "build.archiver")?; + if archiver.as_ref().is_some_and(|p| { + p.trim().is_empty() || p.starts_with('-') || p.chars().any(char::is_control) + }) { + return Err("archiver must be one executable name or path".into()); + } + if format < 5 && (build.contains_key("reproducible") || archiver.is_some()) { + return Err("new build settings require format = 5".into()); + } + (reproducible, archiver) + } + _ => (false, None), + }; Ok(Manifest { + reproducible, + archiver, tests, workspace, virtual_workspace, diff --git a/manifest/src/render.rs b/manifest/src/render.rs index 59aa530..0ab9ea2 100644 --- a/manifest/src/render.rs +++ b/manifest/src/render.rs @@ -5,9 +5,9 @@ pub fn render_new_manifest(project_name: &str, author: &str, is_lib: bool) -> String { format!( r#"{{ - format = 3, + format = 5, name = "{name}", - version = 0.1.0, + version = "0.1.0", targets = {targets}, description = "{name} Project", author = "{author}", diff --git a/manifest/src/workspace.rs b/manifest/src/workspace.rs index e2e37c6..af5ff7e 100644 --- a/manifest/src/workspace.rs +++ b/manifest/src/workspace.rs @@ -196,7 +196,7 @@ pub fn apply_policy( if member .target_config .iter() - .any(|c| c.sysroot.is_some() || c.linker.is_some()) + .any(|c| c.sysroot.is_some() || c.linker.is_some() || c.archiver.is_some()) { return Err(diagnostic::Error::resolution( "workspace sysroot/linker settings belong in the workspace root", @@ -214,6 +214,21 @@ pub fn apply_policy( } member.compiler = Some(required.clone()); } + member.reproducible = owner.reproducible; + let tool_path = |tool: &str| -> Result { + if Path::new(tool).components().count() > 1 || tool.contains('\\') { + Ok(root + .join(tool) + .to_str() + .ok_or_else(|| { + diagnostic::Error::resolution("workspace tool path must be UTF-8") + })? + .into()) + } else { + Ok(tool.into()) + } + }; + member.archiver = owner.archiver.as_deref().map(tool_path).transpose()?; member.profiles = owner.profiles.clone(); member.build_target = owner.build_target.clone(); let local = std::mem::take(&mut member.target_config); @@ -223,6 +238,8 @@ pub fn apply_policy( .map(|config| { let mut config = config.clone(); config.bins.clear(); + config.library = None; + config.archiver = config.archiver.as_deref().map(tool_path).transpose()?; if let Some(path) = &config.sysroot { config.sysroot = Some(root.join(path)); } @@ -250,6 +267,7 @@ pub fn apply_policy( .find(|c| c.triple == config.triple) { existing.bins = config.bins; + existing.library = config.library; } else { member.target_config.push(config); } diff --git a/meson.build b/meson.build index 34df890..87d6f8c 100644 --- a/meson.build +++ b/meson.build @@ -69,7 +69,7 @@ if get_option('test_target') != '' test_args = ['--target', get_option('test_target')] endif python_tests = ['-m', 'unittest', 'discover', '-s', 'tests/tooling', '-v'] -rust_tests = cargo + ['test', '--workspace', '--locked'] + test_args +rust_tests = cargo + ['test', '--workspace', '--locked', '--no-fail-fast'] + test_args test( 'tooling', python, @@ -82,17 +82,13 @@ test( test( 'rust', python, - args: [files('tools/automation_step.py')[0].full_path(), '--'] + cargo + [ - 'test', - '--workspace', - '--locked', - ] + test_args, + args: [files('tools/automation_step.py')[0].full_path(), '--'] + rust_tests, workdir: meson.project_source_root(), suite: 'rust', timeout: 7200, is_parallel: false, ) -custom_target( +debug_build = custom_target( 'build-debug', output: 'build-debug.stamp', command: step_runner + cargo + ['build', '--workspace', '--locked'], @@ -344,3 +340,23 @@ summary( 'development unverified packaging': get_option('allow_unverified'), }, ) + +# Supplemental development acceptance; this never substitutes for the pinned +# public compiler or the nine mandatory platform/release lanes. +if get_option('contract_wavec') != '' and get_option('contract_std') != '' + run_target( + 'consumer-acceptance', + command: [ + python, + files('tests/external_builds.py'), + '--vex', + meson.project_source_root() / (host_machine.system() == 'windows' ? 'target/debug/vex.exe' : 'target/debug/vex'), + '--wavec', + get_option('contract_wavec'), + '--std', + get_option('contract_std'), + '--cross-formats', + ], + depends: debug_build, + ) +endif diff --git a/meson.options b/meson.options index f13b6e8..6b4a6c4 100644 --- a/meson.options +++ b/meson.options @@ -32,3 +32,15 @@ option( value: '', description: 'Platform ID from platforms.json for full compiler/ABI acceptance', ) +option( + 'contract_wavec', + type: 'string', + value: '', + description: 'Explicit prepared compiler for supplemental external-build contract acceptance', +) +option( + 'contract_std', + type: 'string', + value: '', + description: 'Matching prepared std root for external-build contract acceptance', +) diff --git a/process/src/lib.rs b/process/src/lib.rs index cc704aa..5b15cb8 100644 --- a/process/src/lib.rs +++ b/process/src/lib.rs @@ -89,20 +89,65 @@ pub fn exit_code(status: ExitStatus) -> i32 { } pub fn output(command: &mut Command, timeout: Duration) -> Result { - captured_output(command, Some(timeout)) + captured_output(command, Some(timeout), None) } pub fn output_without_deadline(command: &mut Command) -> Result { - captured_output(command, None) + captured_output(command, None, None) } -fn captured_output(command: &mut Command, timeout: Option) -> Result { +pub fn output_with_input( + command: &mut Command, + timeout: Option, + input: Option<&[u8]>, +) -> Result { + captured_output(command, timeout, input) +} +fn write_input( + child: &mut Child, + input: Option<&[u8]>, +) -> Option>> { + input.map(|input| { + let bytes = input.to_vec(); + let mut stream = child.stdin.take().expect("piped build-contract input"); + let (tx, rx) = std::sync::mpsc::sync_channel(1); + std::thread::spawn(move || { + use std::io::Write; + let _ = tx.send(stream.write_all(&bytes)); + }); + rx + }) +} +fn finish_input( + input: Option>>, +) -> Result<(), String> { + if let Some(input) = input { + input + .recv_timeout(Duration::from_secs(3)) + .map_err(|_| "compiler input pipe did not close")? + .map_err(|e| format!("cannot deliver compiler input: {e}"))?; + } + Ok(()) +} +fn captured_output( + command: &mut Command, + timeout: Option, + input: Option<&[u8]>, +) -> Result { + if input.is_some_and(|bytes| bytes.len() > OUTPUT_LIMIT) { + return Err("compiler input exceeds 8 MiB".into()); + } install_handlers()?; command - .stdin(Stdio::null()) + .stdin(if input.is_some() { + Stdio::piped() + } else { + Stdio::null() + }) .stdout(Stdio::piped()) .stderr(Stdio::piped()); let (mut child, group) = spawn(command, false)?; + let input = write_input(&mut child, input); let overflow = Arc::new(AtomicBool::new(false)); let reader = |stream: Box, overflow: Arc| { let (tx, rx) = std::sync::mpsc::sync_channel(1); @@ -142,6 +187,9 @@ fn captured_output(command: &mut Command, timeout: Option) -> Result, interactive: bool, ) -> Result { + status_with_input(command, timeout, interactive, None) +} +pub fn status_with_input( + command: &mut Command, + timeout: Option, + interactive: bool, + input: Option<&[u8]>, +) -> Result { + if input.is_some_and(|bytes| bytes.len() > OUTPUT_LIMIT) { + return Err("compiler input exceeds 8 MiB".into()); + } install_handlers()?; + if input.is_some() { + command.stdin(Stdio::piped()); + } let (mut child, group) = spawn(command, interactive)?; + let input = write_input(&mut child, input); let result = wait(&mut child, &group, timeout, &AtomicBool::new(false)); + if input.is_some() && !interactive { + group.terminate(true); + } + if result.as_ref().is_ok_and(|s| s.success()) { + finish_input(input)?; + } #[cfg(windows)] if interactive && result.is_ok() { if let Err(error) = group.preserve_descendants() { @@ -420,6 +489,11 @@ mod tests { .write_all(&vec![b'x'; OUTPUT_LIMIT + 65536]) .unwrap(); } + "read" => { + let mut bytes = Vec::new(); + std::io::stdin().read_to_end(&mut bytes).unwrap(); + println!("INPUT_COUNT={}", bytes.len()); + } "exit" => std::process::exit(42), _ => panic!("unknown fixture"), } @@ -437,6 +511,43 @@ mod tests { command } #[test] + fn bounded_input_is_delivered_and_a_blocked_reader_cannot_hide_timeout_or_exit() { + let payload = vec![b'x'; 1024 * 1024]; + let output = output_with_input( + &mut command("read"), + Some(Duration::from_secs(10)), + Some(&payload), + ) + .unwrap(); + assert!(output.status.success()); + assert!(String::from_utf8(output.stdout) + .unwrap() + .contains("INPUT_COUNT=1048576")); + let started = Instant::now(); + let error = output_with_input( + &mut command("wait"), + Some(Duration::from_millis(100)), + Some(&payload), + ) + .unwrap_err(); + assert!(error.contains("timed out")); + assert!(started.elapsed() < Duration::from_secs(6)); + let output = output_with_input( + &mut command("exit"), + Some(Duration::from_secs(10)), + Some(&payload), + ) + .unwrap(); + assert_eq!(exit_code(output.status), 42); + assert!(output_with_input( + &mut command("read"), + Some(Duration::from_secs(10)), + Some(&vec![0; OUTPUT_LIMIT + 1]) + ) + .unwrap_err() + .contains("8 MiB")); + } + #[test] fn output_limit_and_timeout_terminate_children() { let start = Instant::now(); assert!(output(&mut command("wait"), Duration::from_millis(100)) diff --git a/resolver/src/activation.rs b/resolver/src/activation.rs index 4b13abc..c514661 100644 --- a/resolver/src/activation.rs +++ b/resolver/src/activation.rs @@ -78,6 +78,25 @@ fn selected( .cloned() .collect() } +fn validate_aliases( + edges: &[Edge], + packages: &BTreeMap<&str, &LockedPackage>, +) -> Result<(), Error> { + let mut aliases = BTreeMap::new(); + for edge in edges { + let id = identity(packages[edge.key.as_str()]); + if aliases + .insert(&edge.alias, id.clone()) + .is_some_and(|before| before != id) + { + return Err(Error::resolution(format!( + "import alias `{}` refers to multiple active package sources in one package", + edge.alias + ))); + } + } + Ok(()) +} /// Workspace package qualification is resolved before feature expansion. With /// several selected roots, unqualified names would silently affect the wrong /// package and are rejected. @@ -216,9 +235,10 @@ pub(crate) fn select( request.selection.include_tests, ); let mut features = BTreeMap::from([(root_identity(root), expanded.features)]); + validate_aliases(&root_edges, &packages)?; let mut pending: Vec<_> = root_edges.iter().map(|edge| edge.key.clone()).collect(); let mut seen = BTreeSet::new(); - let mut aliases = BTreeMap::new(); + let mut active = Vec::new(); while let Some(key) = pending.pop() { if !seen.insert(key.clone()) { @@ -226,19 +246,7 @@ pub(crate) fn select( } let package = packages[key.as_str()]; let id = identity(package); - let alias = package.import_name(); - if alias == root.name { - return Err(Error::resolution(format!( - "dependency alias `{alias}` conflicts with root package `{}`", - root.name - ))); - } - if aliases - .insert(alias, id.clone()) - .is_some_and(|previous| previous != id) - { - return Err(Error::resolution(format!("import alias `{alias}` refers to multiple active package sources; Wave currently exposes a global import-name map\nhelp: choose distinct aliases; scoped compiler dependency mappings are required for conflicting transitive imports"))); - } + // Cross-package names are scoped; each owner still needs one binding. let group = &groups[&id]; let all_edges = edges(package, &packages); let expanded = source::graph::expand( @@ -250,7 +258,9 @@ pub(crate) fn select( .map_err(Error::resolution)?; features.insert(id, expanded.features); let mut package = package.clone(); - package.dependencies = selected(&all_edges, &expanded.enabled, context, false) + let selected_edges = selected(&all_edges, &expanded.enabled, context, false); + validate_aliases(&selected_edges, &packages)?; + package.dependencies = selected_edges .into_iter() .map(|e| e.key) .collect::>() diff --git a/resolver/src/graph.rs b/resolver/src/graph.rs index 94d5310..9fd32eb 100644 --- a/resolver/src/graph.rs +++ b/resolver/src/graph.rs @@ -87,6 +87,10 @@ impl<'a> Resolver<'a> { return self.root.join(".vex/deps").join(suffix); } } + let store = state::layout::dependency(&self.root, ".vex/deps"); + if let Ok(tail) = path.strip_prefix(store) { + return self.root.join(".vex/deps").join(tail); + } path.to_owned() } @@ -400,7 +404,7 @@ impl<'a> Resolver<'a> { &encoded }; let name = target.file_name().unwrap().to_str().unwrap(); - let live = self.root.join(target); + let live = state::layout::dependency(&self.root, target); let locked_commit = self.pinned_commit(dependency); let reuse = if let Some(commit) = locked_commit.as_ref() { let checked = git::require_checkout_at(&live, url, &dependency.name, commit) @@ -418,7 +422,7 @@ impl<'a> Resolver<'a> { git::reject_dirty_checkout(&live, &dependency.name)?; } if let Some(previous) = previous.as_ref() { - let old = self.root.join(previous); + let old = state::layout::dependency(&self.root, previous); if old != live && old.exists() { git::reject_dirty_checkout(&old, &dependency.name)?; } @@ -434,7 +438,10 @@ impl<'a> Resolver<'a> { let copy_source = if fresh { None } else if migration { - Some(self.root.join(previous.as_ref().unwrap())) + Some(state::layout::dependency( + &self.root, + previous.as_ref().unwrap(), + )) } else { Some(live.clone()) }; @@ -759,7 +766,7 @@ impl<'a> Resolver<'a> { "invalid historical managed checkout path", )); } - let old_path = self.root.join(resolved); + let old_path = state::layout::dependency(&self.root, resolved); if old_path.exists() { git::verify_origin(&old_path, url)?; git::reject_dirty_checkout(&old_path, dependency.import_name())?; diff --git a/resolver/src/lib.rs b/resolver/src/lib.rs index 74ab009..3807672 100644 --- a/resolver/src/lib.rs +++ b/resolver/src/lib.rs @@ -26,7 +26,10 @@ pub fn recover_project(guard: &state::Guard, dry_run: bool) -> Result<(), Error> transaction::recover(guard.root(), dry_run).map_err(|error| { Error::environment(error) .with_field("operation", "recover dependency transaction") - .with_field("path", guard.root().join(".vex/transaction.json").display()) + .with_field( + "path", + state::layout::dependency(guard.root(), ".vex/transaction.json").display(), + ) .with_field( "recovery", "run a normal project command to recover; preserve user edits", @@ -151,7 +154,108 @@ impl Resolution { Ok(()) } + pub fn requires_package_graph(&self) -> bool { + let mut aliases = std::collections::BTreeMap::new(); + for package in &self.packages { + if package.import_name() == self.root.name + || aliases + .insert(package.import_name(), package.id.as_ref()) + .is_some_and(|old| old != package.id.as_ref()) + { + return true; + } + } + false + } + pub fn compiler_package_graph(&self) -> Result { + use serde_json::json; + let project = paths::env_root()?; + let root_id = activation::root_identity(&self.root); + let context = self + .selection + .target + .clone() + .unwrap_or_else(source::graph::Context::host); + let ids: std::collections::BTreeMap<_, _> = self + .packages + .iter() + .map(|p| { + ( + p.name.as_str(), + p.id.clone().unwrap_or_else(|| { + lockfile::package_identity( + p.package_name(), + &p.version, + &p.source, + p.subdir.as_deref(), + ) + }), + ) + }) + .collect(); + let select_edges = |edges: &[source::graph::Edge], + features: &source::graph::Features, + selected: &std::collections::BTreeSet, + tests: bool| + -> Result, Error> { + let expanded = source::graph::expand(features, edges, selected, false) + .map_err(Error::resolution)?; + let mut bindings = std::collections::BTreeMap::new(); + for edge in edges.iter().filter(|e| { + (!e.development || tests) + && e.target.as_ref().is_none_or(|p| p.matches(&context)) + && (!e.optional || expanded.enabled.contains(&e.alias)) + }) { + let id = ids + .get(edge.key.as_str()) + .ok_or_else(|| Error::internal("selected compiler graph is incomplete"))?; + if bindings + .insert(edge.alias.clone(), id.clone()) + .is_some_and(|previous| previous != *id) + { + return Err(Error::resolution(format!( + "import alias `{}` selects different active packages in one package", + edge.alias + ))); + } + } + Ok(bindings) + }; + let empty = std::collections::BTreeSet::new(); + let root_features = self.selected_features.get(&root_id).unwrap_or(&empty); + let mut nodes = std::collections::BTreeMap::new(); + let root_path = project + .join(&self.root.manifest) + .parent() + .unwrap() + .to_owned(); + nodes.insert(root_id.clone(),json!({"id":root_id,"name":self.root.name,"root":paths::portable_path(&root_path)?,"dependencies":select_edges(&self.root.edges,&self.root.features,root_features,self.selection.include_tests)?})); + for package in &self.packages { + let id = ids[package.name.as_str()].clone(); + let path = project + .join(package.directory()) + .canonicalize() + .map_err(Error::environment)?; + let selected = self.selected_features.get(&id).unwrap_or(&empty); + let node = json!({"id":id,"name":package.package_name(),"root":paths::portable_path(&path)?,"dependencies":select_edges(&package.edges,&package.features,selected,false)?}); + if let Some(previous) = nodes.insert(id, node.clone()) { + if previous != node { + return Err(Error::resolution( + "one package identity has inconsistent compiler bindings", + )); + } + } + } + Ok( + json!({"schema_version":1,"root":root_id,"packages":nodes.into_values().collect::>()}), + ) + } pub fn dependency_args(&self) -> Result, Error> { + if self.requires_package_graph() { + return Err(Error::compiler( + "this graph requires package-scoped imports; select a compatible Wave compiler", + )); + } let mut args = vec!["--dep-root=.vex/deps".to_string()]; let mut aliases = BTreeSet::new(); for package in &self.packages { @@ -354,12 +458,8 @@ pub fn inspect_selected( "Trace", "project lease: acquired before reading vex.lock".into(), ); - resolve_guarded(manifest, options, status, guard, &mut |_| Ok(()), true).map_err(|e| { - Error::new( - e.category, - format!("{e}\nhelp: run `vex fetch` to prepare the local graph"), - ) - }) + resolve_guarded(manifest, options, status, guard, &mut |_| Ok(()), true) + .map_err(|e| e.with_help("run `vex fetch` to prepare the local graph")) } fn report_policy(options: &ResolveOptions, status: &mut impl FnMut(&str, String)) { @@ -444,7 +544,7 @@ fn resolve_guarded( } let existing = existing.unwrap_or_else(Lockfile::empty); let root = paths::env_root()?; - let dep_root = root.join(".vex/deps"); + let dep_root = state::layout::dependency(&root, ".vex/deps"); let root_manifest = if manifest.source_path.is_absolute() { manifest.source_path.clone() } else { diff --git a/resolver/src/paths.rs b/resolver/src/paths.rs index 354969f..3ea4d76 100644 --- a/resolver/src/paths.rs +++ b/resolver/src/paths.rs @@ -82,7 +82,10 @@ pub(crate) fn relative_to_root(path: &Path, root: &Path) -> PathBuf { } pub(crate) fn validate_managed_root(root: &Path, dep_root: &Path) -> Result<(), Error> { - reject_symbolic_link(&root.join(".vex"), "managed Vex directory")?; + reject_symbolic_link( + &state::layout::dependency(root, ".vex"), + "managed Vex directory", + )?; reject_symbolic_link(dep_root, "managed dependency directory") } @@ -191,13 +194,15 @@ mod tests { let outside = root.with_extension("outside"); fs::create_dir_all(&root).expect("test project must be created"); fs::create_dir_all(&outside).expect("outside directory must be created"); - symlink(&outside, root.join(".vex")).expect("test link must be created"); + symlink(&outside, state::layout::dependency(&root, ".vex")) + .expect("test link must be created"); - let error = validate_managed_root(&root, &root.join(".vex/deps")) + let error = validate_managed_root(&root, &state::layout::dependency(&root, ".vex/deps")) .expect_err("managed root symlinks must be rejected"); assert!(error.contains("must not be a symbolic link"), "{error}"); - fs::remove_file(root.join(".vex")).expect("test link must be removed"); + fs::remove_file(state::layout::dependency(&root, ".vex")) + .expect("test link must be removed"); fs::remove_dir_all(root).expect("test project must be removed"); fs::remove_dir_all(outside).expect("outside directory must be removed"); } diff --git a/resolver/src/prune.rs b/resolver/src/prune.rs index a2ca4b9..d8a462b 100644 --- a/resolver/src/prune.rs +++ b/resolver/src/prune.rs @@ -67,11 +67,11 @@ pub fn prune( .map(|package| { let (LockedSource::Path { resolved, .. } | LockedSource::Git { resolved, .. }) = &package.source; - let path = root.join(resolved); + let path = state::layout::dependency(&root, resolved); path.canonicalize().unwrap_or(path) }) .collect(); - let directory = root.join(".vex/deps"); + let directory = state::layout::dependency(&root, ".vex/deps"); let entries = match fs::read_dir(&directory) { Ok(entries) => entries, Err(error) if error.kind() == std::io::ErrorKind::NotFound => { diff --git a/resolver/src/transaction.rs b/resolver/src/transaction.rs index 94132c7..23e67ba 100644 --- a/resolver/src/transaction.rs +++ b/resolver/src/transaction.rs @@ -24,7 +24,7 @@ impl Transaction { if self.names.borrow().contains(name) { self.stage.join(name) } else { - self.root.join(".vex/deps").join(name) + state::layout::dependency(&self.root, ".vex/deps").join(name) } } @@ -37,8 +37,7 @@ impl Transaction { .duration_since(std::time::UNIX_EPOCH) .map_err(|e| e.to_string())? .as_nanos(); - let directory = root - .join(".vex/transactions") + let directory = state::layout::dependency(root, ".vex/transactions") .join(format!("{}-{stamp}", std::process::id())); let stage = directory.join("deps"); Ok(Self { @@ -72,7 +71,8 @@ impl Transaction { if let Some(previous) = previous { valid_name(previous)?; } - let live = self.root.join(".vex/deps").join(previous.unwrap_or(name)); + let live = + state::layout::dependency(&self.root, ".vex/deps").join(previous.unwrap_or(name)); if previous.is_some() && fs::symlink_metadata(&live).is_ok() { crate::paths::validate_managed_checkout_path(&live).map_err(|e| e.to_string())?; if !live.join(".git").is_dir() { @@ -96,7 +96,7 @@ impl Transaction { } return Ok(()); } - let live_root = self.root.join(".vex/deps"); + let live_root = state::layout::dependency(&self.root, ".vex/deps"); state::ensure_dir(&live_root)?; // Recheck dirty data at the last possible point before moving anything. let mut entries = Vec::new(); @@ -120,7 +120,7 @@ impl Transaction { self.directory.as_path(), self.directory.parent().unwrap(), live_root.as_path(), - &self.root.join(".vex"), + &state::layout::dependency(&self.root, ".vex"), self.root.as_path(), ] { state::sync_dir(directory).map_err(err)?; @@ -148,7 +148,7 @@ impl Transaction { fn publish_record(&self, mut record: Value) -> Result<(), String> { for name in self.names.borrow().iter() { - let live = self.root.join(".vex/deps").join(name); + let live = state::layout::dependency(&self.root, ".vex/deps").join(name); if live.exists() { rename(&live, &self.directory.join("backup").join(name))?; } @@ -195,13 +195,13 @@ pub(crate) fn recover(root: &Path, dry_run: bool) -> Result<(), String> { if id.is_empty() || !id.bytes().all(|b| b.is_ascii_digit() || b == b'-') { return Err("invalid journal directory".into()); } - let directory = root.join(".vex/transactions").join(id); + let directory = state::layout::dependency(root, ".vex/transactions").join(id); for p in [ - root.join(".vex/transactions"), + state::layout::dependency(root, ".vex/transactions"), directory.clone(), directory.join("deps"), directory.join("backup"), - root.join(".vex/deps"), + state::layout::dependency(root, ".vex/deps"), ] { state::reject_link(&p)?; } @@ -248,13 +248,13 @@ pub(crate) fn recover(root: &Path, dry_run: bool) -> Result<(), String> { .as_bool() .ok_or("missing journal backup flag")?; for p in [ - root.join(".vex/deps").join(name), + state::layout::dependency(root, ".vex/deps").join(name), directory.join("backup").join(name), directory.join("deps").join(name), ] { state::reject_link(&p)?; } - let live = root.join(".vex/deps").join(name); + let live = state::layout::dependency(root, ".vex/deps").join(name); let backup = directory.join("backup").join(name); let stage = directory.join("deps").join(name); if committed && (!live.is_dir() || stage.exists()) { @@ -280,7 +280,7 @@ pub(crate) fn recover(root: &Path, dry_run: bool) -> Result<(), String> { if !committed { for entry in entries.iter().rev() { let name = entry["name"].as_str().unwrap(); - let live = root.join(".vex/deps").join(name); + let live = state::layout::dependency(root, ".vex/deps").join(name); let backup = directory.join("backup").join(name); let stage = directory.join("deps").join(name); if backup.exists() { @@ -307,10 +307,10 @@ pub(crate) fn recover(root: &Path, dry_run: bool) -> Result<(), String> { fn finish(root: &Path, _directory: &Path) -> Result<(), String> { fs::remove_file(journal(root)).map_err(err)?; - state::sync_dir(&root.join(".vex")).map_err(err) + state::sync_dir(&state::layout::dependency(root, ".vex")).map_err(err) } fn journal(root: &Path) -> PathBuf { - root.join(".vex/transaction.json") + state::layout::dependency(root, ".vex/transaction.json") } fn err(e: std::io::Error) -> String { e.to_string() diff --git a/src/cli.rs b/src/cli.rs index 081d262..2f172e2 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -36,7 +36,12 @@ fn run_reported() -> Result { use serde_json::json; let mut raw = std::env::args_os().skip(1); let mut path = None; - let mut selection = crate::project::Selection::default(); + let mut selection = crate::project::Selection { + build_dir: std::env::var_os("VEX_BUILD_DIR").map(std::path::PathBuf::from), + state_dir: std::env::var_os("VEX_STATE_DIR").map(std::path::PathBuf::from), + ..Default::default() + }; + let mut explicit_storage = std::collections::BTreeSet::new(); let mut args = Vec::new(); let mut runtime = Vec::new(); let mut quiet = false; @@ -94,6 +99,19 @@ fn run_reported() -> Result { quiet = true; } else if arg == "--verbose" || arg == "-v" || arg == "-vv" { verbosity = (verbosity + if arg == "-vv" { 2 } else { 1 }).min(2); + } else if arg == "--build-dir" || arg == "--state-dir" { + if !explicit_storage.insert(arg.clone()) { + return Err(Error::usage("storage selector may only be specified once")); + } + let value = raw + .next() + .filter(|v| !v.is_empty() && !v.to_string_lossy().starts_with('-')) + .ok_or_else(|| Error::usage("storage selector requires a directory"))?; + if arg == "--build-dir" { + selection.build_dir = Some(value.into()); + } else { + selection.state_dir = Some(value.into()); + } } else if arg == "--message-file" || arg == "--manifest-path" { let slot = if arg == "--message-file" { &mut path @@ -148,6 +166,7 @@ fn run_reported() -> Result { | "metadata" | "info" | "doctor" + | "toolchain" ) }) { @@ -287,6 +306,7 @@ fn dispatch( | "clean" | "prune" | "doctor" + | "toolchain" ) { help_args = vec![args[0].clone(), "--help".into()]; help_args.as_slice() @@ -310,6 +330,7 @@ fn dispatch( | "clean" | "prune" | "doctor" + | "toolchain" ) { return Err(Error::usage( @@ -343,6 +364,10 @@ fn dispatch( "metadata" => { crate::commands::metadata::metadata(&args[1..], selection).map(|()| Outcome::success()) } + "toolchain" => { + crate::commands::toolchain::toolchain(&args[1..], selection)?; + Ok(Outcome::success()) + } "setup" => setup(&args[1..]).map(|()| Outcome::success()), "clean" => { crate::commands::clean::clean(&args[1..], selection).map(|()| Outcome::success()) diff --git a/src/commands/build.rs b/src/commands/build.rs index f8d75f4..116f2b1 100644 --- a/src/commands/build.rs +++ b/src/commands/build.rs @@ -33,6 +33,8 @@ struct VexBuildOptions { dry_run: bool, locked: bool, offline: bool, + artifact_manifest: Option, + depfile: Option, } pub fn build( @@ -46,9 +48,34 @@ pub fn build( diagnostic::outln!("{}", build_usage(mode)); return Ok(Outcome::success()); } - let options = parse_vex_build_options(mode, args).map_err(Error::usage)?; + let mut options = parse_vex_build_options(mode, args).map_err(Error::usage)?; + let invocation = std::env::current_dir().map_err(Error::environment)?; + for path in [&mut options.artifact_manifest, &mut options.depfile] + .into_iter() + .flatten() + { + *path = compiler::reports::destination(&invocation.join(&*path))?; + } + if mode == BuildMode::Check + && (options.artifact_manifest.is_some() || options.depfile.is_some()) + { + return Err(Error::usage( + "check does not emit artifacts; use build for artifact manifests or depfiles", + )); + } let compiler = Compiler::select(); let _project = selection.enter()?; + let project_root = std::env::current_dir().map_err(Error::environment)?; + let build_root = state::layout::build_root(&project_root); + let paths = options + .depfile + .iter() + .chain(options.artifact_manifest.iter()) + .cloned() + .collect::>(); + if !build_root.join(".vex/report-publication.json").exists() { + compiler::reports::preflight(&build_root, &paths)?; + } run_build( mode, &_project.selected, @@ -171,6 +198,16 @@ fn run_build( let primary = &members[0].manifest; let mut selected_compiler = compiler?; let compiler = &mut selected_compiler; + compiler.validate_identity(&root)?; + if options.artifact_manifest.is_some() || options.depfile.is_some() { + if compiler + .capabilities()? + .is_none_or(|c| c["source_inputs"] != 1) + { + return Err(Error::compiler("consumer reports require Wave's complete source-input capability; select a compatible compiler")); + } + compiler.observe_identity()?; + } let requested_triple = options .target .as_deref() @@ -181,9 +218,11 @@ fn run_build( for member in &members { compiler.validate_version(member.manifest.compiler.as_deref())?; } + let prepared_read = state::layout::external(&root) && options.locked && options.offline; + let resolution_readonly = options.dry_run || prepared_read; let recovery_guard = - state::Guard::acquire(options.dry_run, ui::status).map_err(Error::environment)?; - resolver::recover_project(&recovery_guard, options.dry_run)?; + state::Guard::acquire(resolution_readonly, ui::status).map_err(Error::environment)?; + resolver::recover_project(&recovery_guard, resolution_readonly)?; drop(recovery_guard); let spec = compiler.target_spec(requested_triple)?; let triple = spec["triple"].as_str().unwrap().to_owned(); @@ -207,7 +246,7 @@ fn run_build( ResolveOptions { requests, selection: graph_selection.clone(), - dry_run: options.dry_run, + dry_run: resolution_readonly, update: UpdatePolicy::ReuseLocked, locked: options.locked, offline: options.offline, @@ -231,21 +270,52 @@ fn run_build( "bare WebAssembly has no process argument ABI; use a WASI target for program arguments", )); } + let _build_guard = if !options.dry_run { + state::layout::prepare_build(&root).map_err(Error::environment)?; + let build_root = state::layout::build_root(&root); + let lock = state::FileGuard::exclusive(&build_root.join(".vex/build.lock"), || { + ui::status("Waiting", "build directory") + }) + .map_err(Error::environment)?; + compiler::publication::recover(&build_root, false)?; + compiler::reports::recover(&build_root, false)?; + compiler::reports::preflight( + &build_root, + &options + .depfile + .iter() + .chain(options.artifact_manifest.iter()) + .cloned() + .collect::>(), + )?; + Some(lock) + } else { + compiler::publication::recover(&state::layout::build_root(&root), true)?; + compiler::reports::recover(&state::layout::build_root(&root), true)?; + None + }; let mut run_lease = None; let generation = if matches!(mode, BuildMode::Run | BuildMode::Test) { Some(if options.dry_run { - PathBuf::from("target/.vex-run/planned") + state::layout::output(&root, "target/.vex-run/planned") } else { let path = compiler::create_run_generation()?; - run_lease = - Some(state::artifacts::RunLease::create(&root, &path).map_err(Error::environment)?); + run_lease = Some( + state::artifacts::RunLease::create(&state::layout::build_root(&root), &path) + .map_err(Error::environment)?, + ); path }) } else { None }; let mut prepared = Vec::new(); + let mut report_inputs = Vec::new(); let reporting = messages.enabled(); + if !options.dry_run { + state::layout::prepare_build(&std::env::current_dir().map_err(Error::environment)?) + .map_err(Error::environment)?; + } messages.status("compiler")?; for member in &members { let profile = member @@ -268,6 +338,38 @@ fn run_build( } selection.target = Some(context); resolution.activate_root(&member.manifest.source_path, &selection)?; + let scoped = resolution.requires_package_graph() || member.manifest.reproducible; + compiler.package_graph(if scoped { + Some(resolution.compiler_package_graph()?) + } else { + None + })?; + if member.manifest.reproducible { + // Strict guarantees currently cover compiler-owned object/static + // output; arbitrary external SDK/linker closure is not pinned. + if target.output.is_none_or(|o| { + !matches!( + o, + manifest::NativeOutput::Object | manifest::NativeOutput::Static + ) + }) { + return Err(Error::resolution( + "strict reproducibility currently requires object or static library output", + )); + } + compiler.observe_identity()?; + let mut mappings = Vec::new(); + if let Some(standard) = compiler.selected_standard() { + mappings.push((standard.to_owned(), "/vex/std".into())); + } + let build_root = state::layout::build_root(&root); + if build_root != root { + mappings.push((build_root, "/vex/build".into())); + } + compiler.path_remappings(mappings)?; + } else { + compiler.path_remappings(Vec::new())?; + } let configuration = crate::native::prepare_target( &member.manifest, target, @@ -278,8 +380,12 @@ fn run_build( mode == BuildMode::Check, generation.as_deref(), )?; - let mut args = resolution.dependency_args()?; - if target.kind == TargetKind::Binary && member.manifest.lib { + let mut args = if scoped { + Vec::new() + } else { + resolution.dependency_args()? + }; + if !scoped && target.kind == TargetKind::Binary && member.manifest.lib { args.push(format!( "--dep={}={}", member.manifest.name, @@ -314,6 +420,87 @@ fn run_build( if reporting { Some(&mut report) } else { None }, ) .map_err(|e| target_error(e, target, profile_name))?; + if member.manifest.reproducible + && (!plan.plan()["sysroot"].is_null() || !plan.plan()["link"].is_null()) + { + return Err(Error::resolution("strict reproducibility cannot verify external SDK or linker inputs for this plan")); + } + let mut native_requirements = configuration.requirements.clone(); + let archive_program = configuration.archive.as_ref().map(|a| a.program.clone()); + let id = resolution + .root_records() + .iter() + .find(|r| r.name == member.manifest.name) + .map(resolver::root_identity); + let source_graph = resolution.compiler_package_graph()?; + for requirement in &mut native_requirements { + let owner = Path::new(requirement["manifest"].as_str().unwrap()) + .parent() + .unwrap() + .canonicalize() + .map_err(Error::environment)?; + requirement["package_id"] = source_graph["packages"] + .as_array() + .unwrap() + .iter() + .find(|node| { + node["root"].as_str().is_some_and(|p| { + state::layout::path_form(Path::new(p)) + == state::layout::path_form(&owner) + }) + }) + .map(|node| node["id"].clone()) + .unwrap_or(serde_json::Value::Null); + } + let mut settings = configuration.settings; + settings["native"] = crate::native::configuration(&member.manifest); + settings["reproducible"] = json!(member.manifest.reproducible); + let plan=plan.with_archive(configuration.archive).with_metadata(json!({ + "native_requirements":native_requirements,"source_roots":source_graph["packages"], + "package":{"id":id,"name":member.manifest.name,"version":member.manifest.version}, + "package_target":{"name":target.name,"kind":target.kind.as_str()}, + "profile":{"name":profile_name,"opt_level":profile.opt_level},"target":triple, + "artifact_kind":target.output.map(|v|v.as_str()).unwrap_or("binary"), + "features":resolution.selected_features(),"settings":settings + })); + let manifests = std::iter::once(member.manifest.source_path.clone()) + .chain( + resolution + .packages() + .iter() + .map(|p| root.join(p.directory()).join("vex.ws")), + ) + .collect::>(); + let plan = if !options.dry_run { + let mut inputs = + compiler::provenance::Inputs::capture(plan.plan(), &manifests, &root)?; + inputs.include_files( + native_requirements + .iter() + .filter_map(|r| r["resolved_path"].as_str().map(PathBuf::from)), + )?; + if compiler.path().to_str().is_some() { + inputs.include_toolchain(compiler, archive_program.as_deref())?; + } else if options.artifact_manifest.is_some() + || options.depfile.is_some() + || member.manifest.reproducible + { + return Err(Error::resolution( + "consumer report JSON cannot represent a non-UTF-8 compiler path", + )); + } + if (options.artifact_manifest.is_some() || options.depfile.is_some()) + && !inputs.complete_sources + { + return Err(Error::compiler( + "compiler omitted complete source inputs from its plan", + )); + } + report_inputs.push(inputs.clone()); + plan.with_inputs(inputs)? + } else { + plan + }; prepared.push(PlannedTarget { package: member.manifest.name.clone(), manifest_path: member.manifest.source_path.clone(), @@ -327,10 +514,11 @@ fn run_build( .iter() .flat_map(|p| p.plan.output_paths().cloned()) .collect::>(); - state::artifacts::validate_output_paths(&root, &paths).map_err(Error::compiler)?; + state::artifacts::validate_output_paths(&state::layout::build_root(&root), &paths) + .map_err(Error::compiler)?; if options.dry_run { ui::verbose("freshness: planning only; compiler will not execute"); - let plans = prepared.iter().map(|task| json!({"package":task.package,"manifest_path":task.manifest_path,"build_directory":root,"run_directory":if matches!(mode, BuildMode::Run|BuildMode::Test) { Some(&task.directory) } else { None },"package_target":{"name":task.target.name,"kind":task.target.kind.as_str()},"compiler_plan":task.plan.plan()})).collect::>(); + let plans = prepared.iter().map(|task| json!({"package":task.package,"manifest_path":task.manifest_path,"project_directory":root,"build_directory":state::layout::build_root(&root),"run_directory":if matches!(mode, BuildMode::Run|BuildMode::Test) { Some(&task.directory) } else { None },"package_target":{"name":task.target.name,"kind":task.target.kind.as_str()},"settings":task.plan.metadata()["settings"],"compiler_plan":task.plan.plan()})).collect::>(); for task in &prepared { ui::status( "Planning", @@ -343,7 +531,7 @@ fn run_build( ); } let profile = primary.profile(profile_name).map_err(Error::resolution)?; - diagnostic::outln!("{}", serde_json::to_string_pretty(&json!({"schema":"vex.build-plan","schema_version":1,"target":triple,"profile":{"name":profile_name,"opt_level":profile.opt_level},"plans":plans})).map_err(Error::internal)?); + diagnostic::outln!("{}", serde_json::to_string_pretty(&json!({"schema":"vex.build-plan","schema_version":2,"target":triple,"profile":{"name":profile_name,"opt_level":profile.opt_level},"toolchain":compiler.identity(),"reports":{"artifact_manifest":options.artifact_manifest,"depfile":options.depfile},"plans":plans})).map_err(Error::internal)?); return Ok(Outcome::success()); } for task in &prepared { @@ -371,6 +559,7 @@ fn run_build( }; match &freshness {Ok(_)=>ui::verbose("freshness: source, dependency, compiler runtime and standard library contents fingerprinted"), Err(reason)=>ui::verbose(format!("freshness: compiling; {reason}"))}; let mut executions = Vec::new(); + let mut artifact_results = Vec::new(); for mut task in prepared { if let Ok((inputs, base)) = &freshness { let (plan, status) = task.plan.with_fingerprint(base, inputs); @@ -393,7 +582,9 @@ fn run_build( task.target.name ), ); - let final_paths = if let Some(path) = task.plan.plan()["link"]["output"].as_str() { + let final_paths = if let Some(path) = task.plan.plan()["vex_archive"]["output"].as_str() { + vec![path.to_owned()] + } else if let Some(path) = task.plan.plan()["link"]["output"].as_str() { vec![path.to_owned()] } else { task.plan.plan()["compile"] @@ -414,6 +605,7 @@ fn run_build( } messages.emit(event) }; + let result_key = task.plan.result_key()?; let execution = task .plan .execute_reported( @@ -423,6 +615,12 @@ fn run_build( ) .map_err(|e| target_error(e, &task.target, profile_name))? .map(|execution| execution.in_directory(&task.directory)); + if mode != BuildMode::Check { + artifact_results.push(compiler::reports::load_result( + &state::layout::build_root(&root), + &result_key, + )?); + } if let Some(execution) = execution { executions.push((task.package.clone(), task.target.name.clone(), execution)); } @@ -430,7 +628,32 @@ fn run_build( ui::status("Artifact", path); } } + let mut consumer_files = Vec::new(); + if let Some(path) = &options.depfile { + let targets = if let Some(path) = &options.artifact_manifest { + vec![path.clone()] + } else { + artifact_results + .iter() + .flat_map(|r| r["artifacts"].as_array().into_iter().flatten()) + .filter(|a| a["role"] == "primary") + .filter_map(|a| a["published_path"].as_str().map(PathBuf::from)) + .collect() + }; + consumer_files.push(( + path.clone(), + compiler::provenance::depfile(&targets, &report_inputs)?, + )); + } + if let Some(path) = &options.artifact_manifest { + let value = json!({"schema":"vex.artifacts","schema_version":1,"results":artifact_results}); + let mut text = serde_json::to_string_pretty(&value).map_err(Error::internal)?; + text.push('\n'); + consumer_files.push((path.clone(), text)); + } + compiler::reports::publish(&state::layout::build_root(&root), &consumer_files)?; drop(resolution); + drop(_build_guard); let mut outcome = Outcome::success(); for (package, name, execution) in executions { ui::status( @@ -615,6 +838,22 @@ fn parse_vex_build_options(mode: BuildMode, args: &[String]) -> Result { + i += 1; + let value = args + .get(i) + .filter(|v| !v.is_empty() && !v.starts_with('-')) + .ok_or_else(|| format!("missing value for {token}"))?; + let slot = if token == "--artifact-manifest" { + &mut options.artifact_manifest + } else { + &mut options.depfile + }; + if slot.is_some() { + return Err(format!("duplicate {token}")); + } + *slot = Some(value.into()); + } "--release" => { if options.release { return Err("--release may only be specified once".into()); @@ -644,7 +883,7 @@ fn parse_vex_build_options(mode: BuildMode, args: &[String]) -> Result options.offline = true, "-h" | "--help" => return Err(build_usage(mode).to_string()), _ if token.starts_with("--target=") => { - set_target(&mut options, token.trim_start_matches("--target="))?; + set_target(&mut options, token.strip_prefix("--target=").unwrap())?; } _ if token.starts_with('-') => { return Err(format!( @@ -724,12 +963,12 @@ fn set_target(options: &mut VexBuildOptions, target: &str) -> Result<(), String> fn build_usage(mode: BuildMode) -> &'static str { match mode { - BuildMode::Test => "usage: vex test [filter] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] [-- ]", + BuildMode::Test => "usage: vex test [filter] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] [--artifact-manifest ] [--depfile ] [-- ]", BuildMode::Build => { - "usage: vex build [--lib] [--bin ] [--target ] [--profile | --release] [--dry-run] [--locked] [--offline]" + "usage: vex build [--lib] [--bin ] [--target ] [--profile | --release] [--dry-run] [--locked] [--offline] [--artifact-manifest ] [--depfile ]" } BuildMode::Run => { - "usage: vex run [--bin ] [--target ] [--profile | --release] [--dry-run] [--locked] [--offline] [-- ]" + "usage: vex run [--bin ] [--target ] [--profile | --release] [--dry-run] [--locked] [--offline] [--artifact-manifest ] [--depfile ] [-- ]" } BuildMode::Check => { "usage: vex check [--lib] [--bin ] [--target ] [--profile | --release] [--dry-run] [--locked] [--offline]" diff --git a/src/commands/clean.rs b/src/commands/clean.rs index 48d6897..2e77fd1 100644 --- a/src/commands/clean.rs +++ b/src/commands/clean.rs @@ -18,14 +18,19 @@ pub fn clean(args: &[String], selection: &Selection) -> Result<(), Error> { }; let _project = selection.enter()?; let _manifest = _project.primary(); - let root = std::env::current_dir().map_err(Error::environment)?; - for name in [".vex", ".vex/init.json", ".vex/transaction.json"] { - state::reject_link(&root.join(name)).map_err(Error::environment)?; - } - if root.join(".vex/init.json").exists() || root.join(".vex/transaction.json").exists() { - return Err(Error::resolution( - "recovery pending; clean preserves the transaction; run vex fetch first", - )); + let source_root = std::env::current_dir().map_err(Error::environment)?; + let root = state::layout::build_root(&source_root); + let dependencies = state::layout::dependency(&source_root, ".vex"); + for path in [ + dependencies.join("init.json"), + dependencies.join("transaction.json"), + root.join(".vex/build-publication.json"), + root.join(".vex/report-publication.json"), + ] { + state::reject_link(&path).map_err(Error::environment)?; + if path.exists() { + return Err(Error::resolution("recovery pending; clean preserves transaction files; run a normal fetch/build first")); + } } if !state::artifacts::has_records(&root).map_err(Error::environment)? { ui::status( @@ -40,8 +45,18 @@ pub fn clean(args: &[String], selection: &Selection) -> Result<(), Error> { state::Guard::acquire_existing_exclusive(ui::status) } .map_err(Error::environment)?; + let _build_guard = if !dry_run { + Some( + state::FileGuard::exclusive(&root.join(".vex/build.lock"), || { + ui::status("Waiting", "build directory") + }) + .map_err(Error::environment)?, + ) + } else { + None + }; let mut output_error = None; - state::artifacts::clean(&guard, !dry_run, |action, path| { + state::artifacts::clean_at(&guard, &root, !dry_run, |action, path| { // Preview is command output, not progress, and remains visible with -q. if dry_run { if let Err(error) = diff --git a/src/commands/doctor.rs b/src/commands/doctor.rs index e922605..fa61c2f 100644 --- a/src/commands/doctor.rs +++ b/src/commands/doctor.rs @@ -465,6 +465,13 @@ fn inspect_project( Err(error) => report.failure("project_compiler", error), } } + if let Some(selected) = compiler.as_mut() { + let root = std::env::current_dir().unwrap_or_default(); + match selected.validate_identity(&root) { + Ok(())=>report.check("toolchain_identity","ok",true,"selected compiler/std satisfies the project pin",json!({"expected":compiler::identity::read(&root).ok().flatten(),"observed":selected.identity()})), + Err(error)=>{report.failure("toolchain_identity",error);return;} + } + } let mut targets = manifest.targets.iter().collect::>(); targets.sort_by_key(|target| (target.kind != TargetKind::Library, &target.name)); let mut missing_entry = false; @@ -570,8 +577,18 @@ fn inspect_project( false, None, )?; - let mut args = resolution.dependency_args()?; - if package_target.kind == TargetKind::Binary && manifest.lib { + let scoped = resolution.requires_package_graph() || manifest.reproducible; + compiler.package_graph(if scoped { + Some(resolution.compiler_package_graph()?) + } else { + None + })?; + let mut args = if scoped { + Vec::new() + } else { + resolution.dependency_args()? + }; + if !scoped && package_target.kind == TargetKind::Binary && manifest.lib { let root = std::env::current_dir().map_err(Error::environment)?; args.push(format!("--dep={}={}", manifest.name, path_text(&root)?)); } @@ -627,7 +644,11 @@ fn inspect_project( if let Err(error) = std::env::current_dir() .map_err(Error::environment) .and_then(|root| { - state::artifacts::validate_output_paths(&root, &planned_paths).map_err(Error::compiler) + state::artifacts::validate_output_paths( + &state::layout::build_root(&root), + &planned_paths, + ) + .map_err(Error::compiler) }) { report.failure("output_paths", error); diff --git a/src/commands/init.rs b/src/commands/init.rs index c90677b..1652c1b 100644 --- a/src/commands/init.rs +++ b/src/commands/init.rs @@ -58,9 +58,15 @@ fn run_init(is_lib: bool) -> Result<(), Error> { ( "vex.lock", lockfile::encode(Lockfile { - version: 3, + version: 4, packages: Vec::new(), - roots: Vec::new(), + roots: vec![source::graph::Root { + manifest: "vex.ws".into(), + name: project_name.into(), + version: "0.1.0".into(), + edges: vec![], + features: Default::default(), + }], }), ), ]; diff --git a/src/commands/metadata.rs b/src/commands/metadata.rs index 7b37066..d13c98e 100644 --- a/src/commands/metadata.rs +++ b/src/commands/metadata.rs @@ -11,7 +11,7 @@ use std::path::Path; pub fn metadata(args: &[String], selection: &crate::project::Selection) -> Result<(), Error> { if matches!(args, [help] if help == "-h" || help == "--help") { diagnostic::outln!( - "usage: vex metadata [--format=json] [--format-version <1|2>] [--locked] [--offline]" + "usage: vex metadata [--format=json] [--format-version <1|2|3>] [--locked] [--offline]" ); return Ok(()); } @@ -41,6 +41,11 @@ pub fn metadata(args: &[String], selection: &crate::project::Selection) -> Resul let root = project.owner.source_path.parent().unwrap(); json_path(root)?; let manifest = project.primary(); + if manifest.format >= 5 && format_version < 3 { + return Err(Error::resolution( + "manifest format 5 requires metadata --format-version 3", + )); + } if format_version == 1 { require_single_target(&manifest)?; } @@ -85,8 +90,16 @@ pub fn metadata(args: &[String], selection: &crate::project::Selection) -> Resul if format_version >= 2 { value["dependency_declarations"] = json!(package.edges); } - if package.id.is_some() { - value["id"] = json!(package.id); + if format_version >= 3 || package.id.is_some() { + value["id"] = json!(package + .id + .clone() + .unwrap_or_else(|| lockfile::package_identity( + package.package_name(), + &package.version, + &package.source, + package.subdir.as_deref() + ))); value["alias"] = json!(package.import_name()); value["binding"] = json!(package.name); } @@ -107,6 +120,9 @@ pub fn metadata(args: &[String], selection: &crate::project::Selection) -> Resul } else { let mut value = package_record(&manifest, root, &project.manifest_path, format_version)?; value["dependencies"] = json!(resolution.root_dependencies()); + if format_version >= 3 { + value["id"] = json!(resolver::root_identity(&resolution.root_records()[0])); + } if format_version >= 2 { value["dependency_declarations"] = json!(resolution.root_records()[0].edges); } @@ -116,7 +132,7 @@ pub fn metadata(args: &[String], selection: &crate::project::Selection) -> Resul if project.workspace { for member in &project.members { let directory = member.source_path.parent().unwrap(); - let mut value = package_record(member, directory, &member.source_path, 2)?; + let mut value = package_record(member, directory, &member.source_path, format_version)?; let key = resolver::manifest_key(&member.source_path)?; let selected = project .selected @@ -145,7 +161,13 @@ pub fn metadata(args: &[String], selection: &crate::project::Selection) -> Resul let value: Value = json!({"schema_version":format_version,"root":root_record, "selected_features":resolution.selected_features(), "selection":if resolution.views().len() == 1 { Some(resolution.selection()) } else { None }, "selections":selections, "workspace_members":members,"union_bindings":union, - "target_directory":json_path(&root.join("target"))?, "packages":packages}); + "target_directory":json_path(&state::layout::build_root(root).join("target"))?, "packages":packages}); + let mut value = value; + if format_version >= 3 { + value["build_directory"] = json!(json_path(&state::layout::build_root(root))?); + value["state_directory"] = json!(json_path(&state::layout::dependency(root, ".vex"))?); + value["toolchain_lock"] = compiler::identity::read(root)?.unwrap_or(Value::Null); + } diagnostic::outln!( "{}", serde_json::to_string_pretty(&value).map_err(Error::internal)? @@ -176,7 +198,8 @@ fn parse_version(value: Option<&str>, selected: &mut Option) -> Result<(), *selected = Some(match value { Some("1") => 1, Some("2") => 2, - _ => return Err(Error::usage("--format-version requires 1 or 2")), + Some("3") => 3, + _ => return Err(Error::usage("--format-version requires 1, 2 or 3")), }); Ok(()) } @@ -197,6 +220,11 @@ fn package_record( manifest_path: &Path, version: u32, ) -> Result { + if manifest.format >= 5 && version < 3 { + return Err(Error::resolution( + "manifest format 5 requires metadata --format-version 3", + )); + } let mut dependencies: Vec<_> = manifest .dependencies .iter() @@ -207,6 +235,10 @@ fn package_record( "manifest_format":manifest.format, "compiler":manifest.compiler, "root":json_path(root)?, "manifest_path":json_path(manifest_path)?, "native":crate::native::configuration(manifest), "dependencies":dependencies}); + if version >= 3 { + value["reproducible"] = json!(manifest.reproducible); + value["archiver"] = json!(manifest.archiver); + } if version >= 2 { value["features"] = json!(manifest.features); } @@ -246,11 +278,11 @@ fn package_record( Ok(json!({"name":target.name, "kind":kind_name(target.kind), "entry_path":json_path(&root.join(&target.path))?, "output":target.output.map(|output| output.as_str()), "exports":target.exports, - "platform":platform_record(&target.platform)?})) + "platform":platform_record(&target.platform)?,"relocation":target.platform.relocation})) }) .collect::>()?, ); - value["tests"] = Value::Array(manifest.tests.iter().map(|target| Ok(json!({"name":target.name,"entry_path":json_path(&root.join(&target.path))?,"platform":platform_record(&target.platform)?}))).collect::>()?); + value["tests"] = Value::Array(manifest.tests.iter().map(|target| Ok(json!({"name":target.name,"entry_path":json_path(&root.join(&target.path))?,"platform":platform_record(&target.platform)?,"relocation":target.platform.relocation}))).collect::>()?); value["default_run"] = json!(manifest.default_run); value["profiles"] = json!(manifest .profiles @@ -266,6 +298,7 @@ fn package_record( value["target_config"] = Value::Array(manifest.target_config.iter().map(|config| { Ok(json!({"triple":config.triple, "sysroot":config.sysroot.as_deref().map(json_path).transpose()?, "linker":config.linker, + "library":config.library.as_ref().map(platform_record).transpose()?,"archiver":config.archiver, "bins":config.bins.iter().map(|bin| Ok(json!({"name":bin.name,"platform":platform_record(&bin.platform)?}))) .collect::, Error>>()?})) }).collect::>()?); @@ -275,7 +308,7 @@ fn package_record( fn platform_record(platform: &PlatformSettings) -> Result { Ok( - json!({"mode":platform.mode.map(|mode| mode.as_str()), "entry":platform.entry, + json!({"mode":platform.mode.map(|mode| mode.as_str()), "relocation":platform.relocation, "entry":platform.entry, "startup":platform.startup.map(|startup| startup.as_str()), "linker_script":platform.linker_script.as_deref().map(json_path).transpose()?}), ) diff --git a/src/commands/mod.rs b/src/commands/mod.rs index d4b9abe..ee411d4 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -21,3 +21,5 @@ pub mod cache; pub mod edit; pub mod new; + +pub mod toolchain; diff --git a/src/commands/new.rs b/src/commands/new.rs index 0c39934..74845dc 100644 --- a/src/commands/new.rs +++ b/src/commands/new.rs @@ -68,9 +68,7 @@ pub fn new(args: &[String]) -> Result<(), Error> { let result = (|| { std::env::set_current_dir(&stage)?; let guard = state::Guard::acquire(false, crate::ui::status).map_err(Error::environment)?; - let manifest = manifest::render_new_manifest(name, "unknown", library) - .replacen("format = 3", "format = 4", 1) - .replacen("version = 0.1.0", "version = \"0.1.0\"", 1); + let manifest = manifest::render_new_manifest(name, "unknown", library); let source = if library { "pub fun greet() {\n println(\"Hello from library\");\n}\n" } else { diff --git a/src/commands/setup.rs b/src/commands/setup.rs index c8b448e..aca219c 100644 --- a/src/commands/setup.rs +++ b/src/commands/setup.rs @@ -47,7 +47,10 @@ pub fn setup(args: &[String]) -> Result<(), Error> { } } } - diagnostic::outln!("installing wavec {}", toolchain::requested_version(version)); + crate::ui::status( + "Installing", + format!("wavec {}", toolchain::requested_version(version)), + ); match toolchain::install_wavec(version) { Ok(binary) => diagnostic::outln!("wavec installed at {}", binary.display()), Err(error) if script_fallback && !process::cancelled() => { diff --git a/src/commands/toolchain.rs b/src/commands/toolchain.rs new file mode 100644 index 0000000..4670faa --- /dev/null +++ b/src/commands/toolchain.rs @@ -0,0 +1,57 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +use diagnostic::Error; +use std::path::PathBuf; +pub fn toolchain(args: &[String], selection: &crate::project::Selection) -> Result<(), Error> { + const USAGE: &str = "usage: vex toolchain capture [--wavec ] [--std ] [--replace]"; + if matches!(args,[arg]if arg=="--help"||arg=="-h") { + diagnostic::outln!("{USAGE}"); + return Ok(()); + } + if args.first().is_none_or(|a| a != "capture") { + return Err(Error::usage(USAGE)); + } + let invocation = std::env::current_dir().map_err(Error::environment)?; + let mut wavec = None; + let mut standard = None; + let mut replace = false; + let mut at = 1; + while at < args.len() { + match args[at].as_str() { + "--wavec" | "--std" => { + let slot = if args[at] == "--wavec" { + &mut wavec + } else { + &mut standard + }; + if slot.is_some() { + return Err(Error::usage("duplicate toolchain path")); + } + at += 1; + let value = args + .get(at) + .filter(|v| !v.is_empty() && !v.starts_with('-')) + .ok_or_else(|| Error::usage("missing toolchain path"))?; + *slot = Some(invocation.join(PathBuf::from(value))); + } + "--replace" if !replace => replace = true, + _ => return Err(Error::usage(USAGE)), + } + at += 1; + } + let mut compiler = compiler::Compiler::select_explicit(wavec.as_deref())?; + if let Some(root) = standard { + compiler.set_standard(&root)?; + } + let project = selection.enter()?; + compiler.validate_version(project.owner.compiler.as_deref())?; + let root = project.owner.source_path.parent().unwrap(); + compiler.capture_identity(root, replace)?; + crate::ui::status( + "Pinned", + format!("compiler/std identity for {}", compiler::identity::host()), + ); + Ok(()) +} diff --git a/src/native.rs b/src/native.rs index b697bc1..67138f9 100644 --- a/src/native.rs +++ b/src/native.rs @@ -15,6 +15,9 @@ pub struct NativeBuild { pub global: Vec, pub inputs: Vec, pub output: Vec, + pub archive: Option, + pub requirements: Vec, + pub settings: Value, } pub fn configuration(manifest: &Manifest) -> Value { @@ -192,7 +195,15 @@ pub fn prepare_target( ) -> Result { let spec = compiler.target_spec(Some(triple))?; let manifests = manifests(root, resolution)?; - let mut build = prepare_settings(root, package_target, &spec, profile, check, generation)?; + let mut build = prepare_settings_with_compiler( + root, + package_target, + &spec, + profile, + check, + generation, + compiler.path(), + )?; let output = target_output(package_target); let format = spec["object_format"].as_str().unwrap(); for manifest in &manifests { @@ -225,7 +236,11 @@ pub fn prepare_target( format, )? }; - if !check && output != Some(NativeOutput::Object) { + let resolved = Path::new(&argument) + .is_absolute() + .then(|| PathBuf::from(&argument)); + build.requirements.push(json!({"package":manifest.name,"version":manifest.version,"manifest":manifest.source_path,"declared_path":library.path,"name":library.name,"target":triple,"argument":argument,"resolved_path":resolved,"search_paths":search_paths})); + if !check && !matches!(output, Some(NativeOutput::Object | NativeOutput::Static)) { // Preserve package and declaration order: static archive order // and repeated libraries are meaningful to native linkers. build.global.push(format!("-Clink-arg={argument}")); @@ -239,6 +254,7 @@ fn target_output(target: &PackageTarget) -> Option { (target.kind == TargetKind::Library).then_some(target.output.unwrap_or(NativeOutput::Object)) } +#[cfg(test)] fn prepare_settings( root: &Manifest, target: &PackageTarget, @@ -246,6 +262,25 @@ fn prepare_settings( profile: &str, check: bool, generation: Option<&Path>, +) -> Result { + prepare_settings_with_compiler( + root, + target, + spec, + profile, + check, + generation, + Path::new("wavec"), + ) +} +fn prepare_settings_with_compiler( + root: &Manifest, + target: &PackageTarget, + spec: &Value, + profile: &str, + check: bool, + generation: Option<&Path>, + compiler: &Path, ) -> Result { let triple = spec["triple"].as_str().unwrap(); let os = spec["os"].as_str().unwrap(); @@ -254,6 +289,11 @@ fn prepare_settings( .as_bool() .ok_or_else(|| Error::compiler("target-spec is missing boolean hosted"))?; let output = target_output(target); + if output == Some(NativeOutput::Static) && format == "wasm" { + return Err(Error::resolution( + "static archives require an ELF, Mach-O, or COFF target", + )); + } if output.is_some() && !matches!(format, "elf" | "macho" | "coff" | "wasm") || output == Some(NativeOutput::Shared) && format == "wasm" { @@ -296,9 +336,12 @@ fn prepare_settings( "hosted mode requires a hosted native target", )); } - PlatformMode::Freestanding if format != "elf" => { + PlatformMode::Freestanding + if format != "elf" + && !(target.kind == TargetKind::Library && matches!(format, "macho" | "coff")) => + { return Err(Error::resolution( - "freestanding mode requires an ELF target", + "freestanding binary mode requires an ELF target; native object/static libraries also support Mach-O/COFF", )); } PlatformMode::Wasi if format != "wasm" || os != "wasi" || !hosted => { @@ -314,7 +357,7 @@ fn prepare_settings( let link_settings = platform.entry.is_some() || platform.linker_script.is_some() || platform.startup == Some(Startup::None); - if target.kind == TargetKind::Library && (link_settings || platform.mode.is_some()) { + if target.kind == TargetKind::Library && link_settings { return Err(Error::resolution( "binary platform settings cannot be applied to a library target", )); @@ -349,6 +392,9 @@ fn prepare_settings( global: vec![format!("--target={triple}")], inputs: Vec::new(), output: Vec::new(), + archive: None, + requirements: Vec::new(), + settings: json!({"mode":mode.as_str(),"relocation":if output==Some(NativeOutput::Shared){"pic"}else{platform.relocation.as_deref().unwrap_or("default")},"entry":platform.entry,"startup":platform.startup.map(|s|s.as_str()),"linker_script":script,"sysroot":null,"linker":null}), }; if let Some(config) = root .target_config @@ -371,11 +417,16 @@ fn prepare_settings( if sysroot.is_some() && linker.is_some() && format == "macho" { return Err(Error::resolution("selected compiler cannot forward a Mach-O sysroot to a custom linker; use the compiler's default linker")); } + build.settings["linker"] = json!(linker); + build.settings["sysroot"] = json!(sysroot); if let Some(sysroot) = sysroot { build.global.push(format!("--sysroot={sysroot}")); // Bundled ELF and Darwin linkers consume the compiler sysroot // directly. An explicit ELF linker needs explicit forwarding. - if !check && output != Some(NativeOutput::Object) && linker.is_some() { + if !check + && !matches!(output, Some(NativeOutput::Object | NativeOutput::Static)) + && linker.is_some() + { build.global.push(format!("-Clink-sysroot={sysroot}")); } } @@ -390,6 +441,19 @@ fn prepare_settings( // and is meaningful even when only checking sources. build.output.push("--freestanding".into()); } + if let Some(relocation) = platform.relocation.as_deref().filter(|r| *r != "default") { + if !matches!(format, "elf" | "macho") { + return Err(Error::resolution( + "explicit library relocation is not supported for this target format", + )); + } + if output == Some(NativeOutput::Shared) && relocation != "pic" { + return Err(Error::resolution("shared library output requires PIC")); + } + build + .global + .extend(["-C".into(), format!("relocation-model={relocation}")]); + } if check { return Ok(build); } @@ -406,7 +470,9 @@ fn prepare_settings( } let directory = generation .map(Path::to_path_buf) - .unwrap_or_else(|| PathBuf::from("target")) + .unwrap_or_else(|| { + state::layout::output(&std::env::current_dir().unwrap_or_default(), "target") + }) .join(triple) .join(profile); let directory = if root.scope.is_some() { @@ -419,11 +485,47 @@ fn prepare_settings( } else { "bin" }); + let mut compiler_output = output_directory.join(&filename); + if output == Some(NativeOutput::Static) && !check { + let requested = root + .target_config + .iter() + .find(|c| c.triple == triple) + .and_then(|c| c.archiver.as_deref()) + .or(root.archiver.as_deref()); + let requested = requested.map(|value| { + if Path::new(value).components().count() > 1 { + root.source_path.parent().unwrap().join(value) + } else { + PathBuf::from(value) + } + }); + // Selection is bound later to the actual compiler executable. + compiler_output = directory + .join(".vex-obj/lib") + .join(&target.name) + .join("static") + .join(format!( + "{}.{}", + target.name, + if format == "coff" { "obj" } else { "o" } + )); + let selected = compiler::archive::ArchivePlan::select( + requested.as_deref(), + compiler, + output_directory.join(filename), + triple, + format, + )?; + build.archive = Some(selected); + } build .output - .extend(["-o".into(), path_text(&output_directory.join(filename))?]); + .extend(["-o".into(), path_text(&compiler_output)?]); match output { - Some(NativeOutput::Object) => build.output.push("--emit=obj".into()), + Some(NativeOutput::Static) | Some(NativeOutput::Object) => { + build.output.push("--emit=obj".into()) + } Some(NativeOutput::Shared) => { build.output.push("--shared".into()); build @@ -450,7 +552,7 @@ fn prepare_settings( } None => {} } - if output != Some(NativeOutput::Object) { + if !matches!(output, Some(NativeOutput::Object | NativeOutput::Static)) { build.output.push(format!( "--target-dir={}", path_text( @@ -471,6 +573,13 @@ fn prepare_settings( fn artifact_filename(target: &PackageTarget, os: &str, format: &str) -> String { match target_output(target) { + Some(NativeOutput::Static) => { + if format == "coff" { + format!("{}.lib", target.name) + } else { + format!("lib{}.a", target.name) + } + } Some(NativeOutput::Object) => format!( "{}.{}", target.name, @@ -713,6 +822,7 @@ mod tests { entry: Some("start".into()), startup: None, linker_script: None, + relocation: None, }; let bare = spec("wasm32-unknown-unknown", "unknown", "wasm", false); let build = prepare_settings(&root, &root.targets[0], &bare, "dev", false, None).unwrap(); @@ -769,6 +879,7 @@ mod tests { entry: Some("_start".into()), startup: Some(Startup::None), linker_script: None, + relocation: None, }; let bare = spec("x86_64-unknown-none-elf", "none", "elf", false); let check = prepare_settings(&root, &root.targets[0], &bare, "dev", true, None).unwrap(); @@ -807,6 +918,8 @@ mod tests { sysroot: Some(PathBuf::from("../sdk")), linker: Some(path_text(&std::env::current_exe().unwrap()).unwrap()), bins: vec![], + library: None, + archiver: None, }); let target = spec("aarch64-unknown-linux-gnu", "linux", "elf", true); let build = prepare_settings(&root, &root.targets[0], &target, "dev", false, None).unwrap(); diff --git a/src/project.rs b/src/project.rs index 17f4fb6..f2d4040 100644 --- a/src/project.rs +++ b/src/project.rs @@ -11,6 +11,8 @@ use std::path::{Path, PathBuf}; pub struct Selection { pub graph: source::graph::Selection, pub manifest_path: Option, + pub build_dir: Option, + pub state_dir: Option, pub packages: Vec, pub all_packages: bool, } @@ -22,6 +24,7 @@ pub struct Project { pub selected: Vec, pub workspace: bool, previous_directory: PathBuf, + _layout: state::layout::Scope, } impl Project { pub fn primary(&self) -> Manifest { @@ -159,6 +162,12 @@ impl Selection { selected_members.len() )); } + let storage_path = + |value: &Option| value.as_ref().map(|p| previous_directory.join(p)); + let build = storage_path(&self.build_dir); + let dependencies = storage_path(&self.state_dir); + let layout = state::layout::configure(root, build.as_deref(), dependencies.as_deref()) + .map_err(Error::usage)?; std::env::set_current_dir(root).map_err(Error::environment)?; Ok(Project { manifest_path: if selected_members.len() == 1 { @@ -171,6 +180,7 @@ impl Selection { selected: selected_members, workspace, previous_directory, + _layout: layout, }) } } diff --git a/state/src/artifacts.rs b/state/src/artifacts.rs index 42f233f..a2f1a7b 100644 --- a/state/src/artifacts.rs +++ b/state/src/artifacts.rs @@ -209,7 +209,8 @@ impl RunLease { .and_then(|p| p.to_str()) .ok_or("invalid run generation")?; let expected = generation(name)?; - if relative(path)? != expected { + let relative_path = path.strip_prefix(root).unwrap_or(path); + if relative(relative_path)? != expected { return Err("invalid run generation path".into()); } checked(root, &expected)?; @@ -286,13 +287,11 @@ pub fn validate_output_paths(root: &Path, outputs: &[PathBuf]) -> Result::new(); for output in outputs { let path = if output.is_absolute() { - output - .strip_prefix(root) - .map_err(|_| "compiler output is outside the project")? + crate::layout::relative_output(root, output)? } else { - output + output.clone() }; - let name = relative(path)?; + let name = relative(&path)?; #[cfg(windows)] for component in name.split('/') { if component.ends_with(['.', ' ']) || component.contains(':') { @@ -468,12 +467,15 @@ pub fn has_records(root: &Path) -> Result { /// The caller chooses a shared guard for previews and an exclusive guard for /// deletion. Unknown files and directories are never recursively removed. -pub fn clean( - guard: &Guard, +pub fn clean(guard: &Guard, apply: bool, report: impl FnMut(&str, String)) -> Result<(), String> { + clean_at(guard, guard.root(), apply, report) +} +pub fn clean_at( + _guard: &Guard, + root: &Path, apply: bool, mut report: impl FnMut(&str, String), ) -> Result<(), String> { - let root = guard.root(); for journal in [".vex/transaction.json", ".vex/init.json"] { reject_link(&root.join(journal))?; if root.join(journal).exists() { @@ -611,3 +613,29 @@ fn hex_digest(bytes: impl AsRef<[u8]>) -> String { }) .collect() } + +/// Fingerprint used to detect edits during a recoverable publication. +pub fn file_fingerprint(path: &Path) -> Result, String> { + fingerprint(path) +} +/// Record already verified transaction results after their commit or rollback. +pub fn record_verified(root: &Path, paths: &[PathBuf]) -> Result<(), String> { + let names = validate_output_paths(root, paths)?; + let mut registry = read(root)?; + for name in names { + let path = checked(root, &name)?; + reject_hardlinked_output(&path)?; + if let Some(hash) = fingerprint(&path)? { + registry.files.insert(name, hash); + } else { + registry.files.remove(&name); + } + } + write(root, ®istry) +} + +/// The recorded identity, without claiming or repairing any file. +pub fn recorded_fingerprint(root: &Path, path: &Path) -> Result, String> { + let names = validate_output_paths(root, &[path.to_owned()])?; + Ok(read(root)?.files.get(&names[0]).cloned()) +} diff --git a/state/src/edit.rs b/state/src/edit.rs index 825a0ff..f8fccfb 100644 --- a/state/src/edit.rs +++ b/state/src/edit.rs @@ -19,7 +19,7 @@ struct Record { committed: bool, } fn read(root: &Path) -> Result, String> { - let path = root.join(JOURNAL); + let path = crate::layout::dependency(root, JOURNAL); reject_link(&path)?; match fs::read_to_string(path) { Ok(raw) => serde_json::from_str(&raw) @@ -60,7 +60,7 @@ pub fn replace(path: &Path, text: &str) -> Result<(), String> { } fn store(root: &Path, record: &Record) -> Result<(), String> { replace( - &root.join(JOURNAL), + &crate::layout::dependency(root, JOURNAL), &serde_json::to_string(record).map_err(|e| e.to_string())?, ) } @@ -169,6 +169,6 @@ pub fn recover(root: &Path, readonly: bool) -> Result<(), String> { } else if manifest != record.new || lock != record.new_lock { return Err("committed dependency edit is incomplete; preserve journal".into()); } - fs::remove_file(root.join(JOURNAL)).map_err(|e| e.to_string())?; - sync_dir(&root.join(".vex")).map_err(|e| e.to_string()) + fs::remove_file(crate::layout::dependency(root, JOURNAL)).map_err(|e| e.to_string())?; + sync_dir(&crate::layout::dependency(root, ".vex")).map_err(|e| e.to_string()) } diff --git a/state/src/layout.rs b/state/src/layout.rs new file mode 100644 index 0000000..29c4fb8 --- /dev/null +++ b/state/src/layout.rs @@ -0,0 +1,366 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// SPDX-License-Identifier: MPL-2.0 +//! Command-local physical storage, separate from portable lockfile paths. +use std::{ + cell::RefCell, + path::{Component, Path, PathBuf}, +}; + +#[derive(Clone, Debug)] +struct Layout { + project: PathBuf, + build: PathBuf, + dependencies: PathBuf, +} +thread_local! { static CURRENT: RefCell> = const { RefCell::new(None) }; } +pub struct Scope(Option); +impl Drop for Scope { + fn drop(&mut self) { + CURRENT.with(|slot| *slot.borrow_mut() = self.0.take()); + } +} + +fn normalize(path: &Path) -> Result { + let mut result = PathBuf::new(); + for part in path.components() { + match part { + Component::CurDir => {} + Component::ParentDir => { + if !result.pop() { + return Err("storage path escapes filesystem root".into()); + } + } + part => result.push(part), + } + } + let mut ancestor = result.as_path(); + while !ancestor.exists() { + ancestor = ancestor + .parent() + .ok_or("storage path has no existing parent")?; + } + let real = ancestor.canonicalize().map_err(|e| e.to_string())?; + Ok(real.join(result.strip_prefix(ancestor).map_err(|e| e.to_string())?)) +} + +pub fn configure( + project: &Path, + build: Option<&Path>, + dependencies: Option<&Path>, +) -> Result { + let build_root = build + .map(normalize) + .transpose()? + .unwrap_or_else(|| project.to_owned()); + if build.is_some() + && ((project != build_root && project.starts_with(&build_root)) + || ["src", ".git", ".vex"] + .iter() + .any(|p| build_root.starts_with(project.join(p)))) + { + return Err("external build directory overlaps protected project sources".into()); + } + let dependencies = dependencies.map(normalize).transpose()?.unwrap_or_else(|| { + if build.is_some() { + build_root.join(".vex/dependencies") + } else { + project.join(".vex") + } + }); + if project.starts_with(&dependencies) + || ["src", ".git", "target"] + .iter() + .any(|p| dependencies.starts_with(project.join(p))) + || dependencies.starts_with(build_root.join("target")) + || dependencies == build_root + { + return Err("dependency state directory overlaps protected project sources".into()); + } + validate_owner(&build_root.join(".vex/build-owner.json"), project, false)?; + validate_owner(&dependencies.join("store-owner.json"), project, false)?; + Ok(CURRENT.with(|slot| { + Scope(slot.replace(Some(Layout { + project: project.into(), + build: build_root, + dependencies, + }))) + })) +} + +pub fn build_root(project: &Path) -> PathBuf { + CURRENT.with(|slot| { + slot.borrow() + .as_ref() + .filter(|l| path_form(&l.project) == path_form(project)) + .map_or_else(|| project.into(), |l| l.build.clone()) + }) +} +pub fn dependency(project: &Path, path: impl AsRef) -> PathBuf { + let path = path.as_ref(); + CURRENT.with(|slot| { + if let Some(layout) = slot + .borrow() + .as_ref() + .filter(|l| path_form(&l.project) == path_form(project)) + { + if let Ok(tail) = path.strip_prefix(".vex") { + return layout.dependencies.join(tail); + } + } + project.join(path) + }) +} +pub fn output(project: &Path, path: impl AsRef) -> PathBuf { + let path = path.as_ref(); + let root = build_root(project); + if path_form(&root) == path_form(project) { + path.to_owned() + } else { + root.join(path) + } +} +pub fn external(project: &Path) -> bool { + path_form(&build_root(project)) != path_form(project) + || path_form(&dependency(project, ".vex")) != path_form(&project.join(".vex")) +} + +/// Claims only Vex's state, never the surrounding Meson directory or its files. +pub fn prepare_build(project: &Path) -> Result<(), String> { + let root = build_root(project); + crate::ensure_tree(&root)?; + let managed = root.join(".vex"); + crate::ensure_tree(&managed)?; + validate_owner(&managed.join("build-owner.json"), project, true) +} + +/// Persistent identities are coordination metadata, never claims on user files. +pub(crate) fn validate_owner(path: &Path, project: &Path, create: bool) -> Result<(), String> { + use std::io::{Read, Write}; + crate::reject_link(path)?; + let project_identity = match project.to_str() { + Some(text) => serde_json::json!(text), + None => serde_json::json!({"native_path_sha256":identity_digest(project)}), + }; + let identity = serde_json::json!({"schema_version":1,"project":project_identity}); + match crate::open_regular(path) { + Ok(file) => { + if !file.metadata().map_err(|e| e.to_string())?.is_file() { + return Err("storage owner must be a regular file".into()); + } + let mut bytes = Vec::new(); + file.take(65537) + .read_to_end(&mut bytes) + .map_err(|e| e.to_string())?; + if bytes.len() > 65536 { + return Err("storage owner exceeds 64 KiB".into()); + } + let mut stored: serde_json::Value = + serde_json::from_slice(&bytes).map_err(|e| e.to_string())?; + // Normal and verbatim Windows prefixes identify the same path. + // Keep every other ownership field and lexical boundary strict. + if let (Some(recorded), Some(expected)) = + (stored["project"].as_str(), identity["project"].as_str()) + { + if path_form(Path::new(recorded)) == path_form(Path::new(expected)) { + stored["project"] = identity["project"].clone(); + } + } + if stored != identity { + return Err( + "storage directory belongs to a different project or has invalid ownership" + .into(), + ); + } + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound && create => { + let mut file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(path) + .map_err(|e| e.to_string())?; + file.write_all(identity.to_string().as_bytes()) + .and_then(|_| file.sync_all()) + .map_err(|e| e.to_string())?; + crate::sync_dir(path.parent().unwrap()).map_err(|e| e.to_string())?; + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(e.to_string()), + } + Ok(()) +} + +/// Persistent coordination is separate from the shared Git object cache. +pub fn coordination(project: &Path) -> Result { + let selected = if cfg!(windows) { + std::env::var_os("LOCALAPPDATA").map(|p| (PathBuf::from(p), "Vex/state")) + } else { + std::env::var_os("XDG_STATE_HOME") + .map(|p| (PathBuf::from(p), "vex")) + .or_else(|| { + std::env::var_os("HOME").map(|p| (PathBuf::from(p).join(".local/state"), "vex")) + }) + }; + let (base, owned) = selected.unwrap_or_else(|| (std::env::temp_dir(), "vex-state")); + if !base.is_absolute() { + return Err("OS state directory must be absolute".into()); + } + // OS-selected roots may have physical aliases (macOS /var, redirected + // homes). Resolve that boundary before appending Vex-owned components; + // links within the owned coordination tree remain rejected by ensure_tree. + let base = normalize(&base)?.join(owned); + let digest = identity_digest(project); + Ok(base.join("projects").join(digest).join("state.lock")) +} + +fn identity_digest(project: &Path) -> String { + use sha2::{Digest, Sha256}; + #[cfg(unix)] + let bytes = { + use std::os::unix::ffi::OsStrExt; + project.as_os_str().as_bytes().to_vec() + }; + #[cfg(windows)] + let bytes = { + use std::os::windows::ffi::OsStrExt; + project + .as_os_str() + .encode_wide() + .flat_map(u16::to_le_bytes) + .collect::>() + }; + Sha256::digest(bytes) + .iter() + .map(|b| format!("{b:02x}")) + .collect() +} + +/// Match filesystem paths across Windows normal/verbatim spellings without +/// resolving links or parent components. All containment checks remain lexical. +pub fn path_form(path: &Path) -> PathBuf { + #[cfg(windows)] + { + use std::path::Prefix; + let mut components = path.components(); + let Some(Component::Prefix(prefix)) = components.next() else { + return path.into(); + }; + let mut normalized = match prefix.kind() { + Prefix::Disk(drive) | Prefix::VerbatimDisk(drive) => { + PathBuf::from(format!("{}:\\", (drive as char).to_ascii_uppercase())) + } + Prefix::UNC(server, share) | Prefix::VerbatimUNC(server, share) => { + let mut result = PathBuf::from(r"\\"); + result.push(server); + result.push(share); + result + } + _ => return path.into(), + }; + for component in components { + if !matches!(component, Component::RootDir) { + normalized.push(component.as_os_str()); + } + } + normalized + } + #[cfg(not(windows))] + { + path.into() + } +} +pub fn relative_output(root: &Path, path: &Path) -> Result { + path_form(path) + .strip_prefix(path_form(root)) + .map(Path::to_path_buf) + .map_err(|_| { + format!( + "compiler output `{}` is outside build root `{}`", + path.display(), + root.display() + ) + }) +} + +#[cfg(all(test, windows))] +mod windows_tests { + use super::*; + #[test] + fn storage_selection_and_ownership_accept_both_windows_path_forms() { + let temporary = std::env::temp_dir().join(format!( + "vex-layout-forms-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + std::fs::create_dir_all(temporary.join("source")).unwrap(); + let project = temporary.join("source").canonicalize().unwrap(); + let normal = path_form(&project); + let build = temporary.join("build"); + let dependencies = temporary.join("dependencies"); + { + let _scope = configure(&project, Some(&build), Some(&dependencies)).unwrap(); + assert_eq!(build_root(&normal), build_root(&project)); + assert_eq!( + dependency(&normal, ".vex/deps"), + dependency(&project, ".vex/deps") + ); + assert_eq!( + output(&normal, "target/app.obj"), + output(&project, "target/app.obj") + ); + assert!(external(&normal)); + prepare_build(&normal).unwrap(); + } + let owner = build.join(".vex/build-owner.json"); + let before = std::fs::read(&owner).unwrap(); + { + let _scope = configure(&project, Some(&build), Some(&dependencies)).unwrap(); + prepare_build(&project).unwrap(); + } + assert_eq!(std::fs::read(&owner).unwrap(), before); + assert!(configure(&temporary.join("other"), Some(&build), None).is_err()); + assert_eq!(std::fs::read(&owner).unwrap(), before); + { + let _scope = configure(&project, None, None).unwrap(); + assert!(!external(&normal)); + assert_eq!( + output(&normal, "target/app.obj"), + Path::new("target/app.obj") + ); + } + std::fs::remove_dir_all(temporary).unwrap(); + } + #[test] + fn normal_verbatim_drives_and_unc_paths_have_one_lexical_boundary() { + assert_eq!( + relative_output( + Path::new(r"\\?\C:\build"), + Path::new(r"c:\build\target\app.o") + ) + .unwrap(), + Path::new(r"target\app.o") + ); + assert_eq!( + relative_output( + Path::new(r"\\?\UNC\server\share\build"), + Path::new(r"\\server\share\build\target\app.o") + ) + .unwrap(), + Path::new(r"target\app.o") + ); + assert!(relative_output( + Path::new(r"C:\build"), + Path::new(r"C:\build-other\target\app.o") + ) + .is_err()); + assert!(crate::artifacts::validate_output_paths( + Path::new(r"C:\build"), + &[r"C:\build\target\..\escape".into()] + ) + .is_err()); + } +} diff --git a/state/src/lib.rs b/state/src/lib.rs index 3defc55..dce585a 100644 --- a/state/src/lib.rs +++ b/state/src/lib.rs @@ -10,12 +10,14 @@ use std::path::{Path, PathBuf}; pub mod artifacts; pub mod edit; +pub mod layout; mod scaffold; pub use scaffold::initialize; #[derive(Debug)] pub struct Guard { _file: File, + _project: File, root: PathBuf, } @@ -46,9 +48,27 @@ impl Guard { let root = std::env::current_dir() .and_then(|p| p.canonicalize()) .map_err(|e| e.to_string())?; - let managed = root.join(".vex"); + // One project identity coordinates source manifests/lockfiles even when + // callers choose different dependency stores or output directories. + let coordination = layout::coordination(&root)?; if create { - ensure_dir(&managed)?; + ensure_tree(coordination.parent().unwrap())?; + } + let project_file = acquire_file(&coordination, shared, create, || { + waiting("Waiting", format!("project {}", root.display())) + }) + .map_err(|e| format!("cannot acquire project lease: {e}; run vex fetch first"))?; + if !project_file + .metadata() + .map_err(|e| e.to_string())? + .is_file() + { + return Err("project coordination must be a regular file".into()); + } + inherit(&project_file).map_err(|e| e.to_string())?; + let managed = layout::dependency(&root, ".vex"); + if create { + ensure_tree(&managed)?; } else { reject_link(&managed)?; } @@ -62,7 +82,12 @@ impl Guard { return Err("project coordination path must be a regular file".into()); } inherit(&file).map_err(|e| format!("cannot protect compiler/Git child lifetime: {e}"))?; - let guard = Self { _file: file, root }; + layout::validate_owner(&managed.join("store-owner.json"), &root, create)?; + let guard = Self { + _file: file, + _project: project_file, + root, + }; scaffold::recover(guard.root(), shared || !create)?; Ok(guard) } @@ -297,3 +322,52 @@ pub fn atomic_rename(from: &Path, to: &Path) -> io::Result<()> { sync_dir(from.parent().unwrap())?; sync_dir(to.parent().unwrap()) } + +/// Create only ordinary directory components; reject links at every boundary. +pub fn ensure_tree(path: &Path) -> Result<(), String> { + if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { + ensure_tree(parent)?; + } + reject_link(path)?; + if path.is_dir() { + Ok(()) + } else { + ensure_dir(path) + } +} + +/// Open a bounded-reader input without waiting for a FIFO or following a final +/// symlink. Callers separately validate parent containment where required. +pub fn open_regular(path: &Path) -> io::Result { + let mut options = OpenOptions::new(); + options.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK); + } + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + options.custom_flags(0x00200000); // FILE_FLAG_OPEN_REPARSE_POINT + } + let file = options.open(path)?; + let metadata = file.metadata()?; + #[cfg(windows)] + { + use std::os::windows::fs::MetadataExt; + if metadata.file_attributes() & 0x400 != 0 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "input is a reparse point", + )); + } + } + if !metadata.is_file() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "input must be a regular file", + )); + } + Ok(file) +} diff --git a/tests/build_artifact_integrity.rs b/tests/build_artifact_integrity.rs index 0c2a33b..ce1ef0e 100644 --- a/tests/build_artifact_integrity.rs +++ b/tests/build_artifact_integrity.rs @@ -29,7 +29,9 @@ impl Fixture { fs::write(root.join("vex.ws"), "{name=\"app\",version=0.1.0,lib=true}").unwrap(); fs::write(root.join("src/lib.wave"), "fun main() {}\n").unwrap(); fs::write(root.join("src/main.wave"), "fun main() {}\n").unwrap(); - Self { root } + Self { + root: root.canonicalize().unwrap(), + } } fn shared() -> Self { let fixture = Self::new(); @@ -176,7 +178,10 @@ fn missing_or_nonregular_outputs_do_not_publish_artifact_success() { ); assert!(!f.events().iter().any(|event| event["event"] == "artifact")); assert_eq!(f.events().last().unwrap()["category"], "compiler"); - assert!(f.root.join(intermediate).is_file()); + assert!( + !f.root.join(intermediate).exists(), + "failed compilation must not publish partial intermediate outputs" + ); f.clean(); assert!(!f.root.join(intermediate).exists()); @@ -193,7 +198,10 @@ fn missing_or_nonregular_outputs_do_not_publish_artifact_success() { f.root.join("compiled").exists(), "fixture must reach compilation" ); - assert!(f.root.join(path).is_dir()); + assert!( + !f.root.join(path).exists(), + "nonregular staged output must never be published" + ); assert!(!f.events().iter().any(|event| event["event"] == "artifact")); assert_eq!(f.events().last().unwrap()["category"], "compiler"); } @@ -468,3 +476,443 @@ fn compiler_cannot_change_selected_artifact_kind_or_namespace() { assert_code(&f.build(&escaped_intermediate, &[]), 4); assert!(!f.root.join("compiled").exists()); } + +#[test] +fn staged_failure_and_mid_publication_rollback_keep_the_last_complete_generation() { + let f = Fixture::new(); + let name = "target/x86_64-unknown-linux-gnu/dev/lib/app.o"; + let plan = plan_object(name); + assert_code(&f.build(&plan, &[name]), 0); + let pointers = f.root.join("target/.vex-results"); + let pointer = fs::read_dir(&pointers) + .unwrap() + .next() + .unwrap() + .unwrap() + .path(); + let before = fs::read(&pointer).unwrap(); + let result: Value = serde_json::from_slice(&before).unwrap(); + let generation = PathBuf::from(result["artifacts"][0]["path"].as_str().unwrap()); + let good = fs::read(&generation).unwrap(); + for (variable, value) in [ + ("COMPILE_EXIT", "1"), + ("VEX_TEST_PUBLICATION_FAIL_AFTER", "0"), + ] { + let output = f + .command(&plan, &[name]) + .env("ARTIFACT_BYTES", "changed artifact") + .env(variable, value) + .arg("build") + .output() + .unwrap(); + assert!(!output.status.success()); + assert_eq!(fs::read(f.root.join(name)).unwrap(), good); + assert_eq!(fs::read(&generation).unwrap(), good); + assert_eq!(fs::read(&pointer).unwrap(), before); + assert!(!f.root.join(".vex/build-publication.json").exists()); + } + assert_code( + &f.command(&plan, &[name]) + .env("ARTIFACT_BYTES", "changed artifact") + .arg("build") + .output() + .unwrap(), + 0, + ); + assert_eq!(fs::read(f.root.join(name)).unwrap(), b"changed artifact"); + assert_eq!(fs::read(generation).unwrap(), good); +} + +#[test] +fn external_roots_reports_and_toolchain_pins_preserve_source_and_owned_files() { + let f = Fixture::new(); + let name = "target/x86_64-unknown-linux-gnu/dev/lib/app.o"; + let mut plan = plan_object(name); + plan["source_inputs"] = json!(["src/lib.wave"]); + let first = f.root.join("build one é"); + let second = f.root.join("build two"); + let report = f.root.join("result #$.json"); + let depfile = f.root.join("result #$.d"); + let standard = f.root.join("prepared std"); + fs::create_dir(&standard).unwrap(); + fs::write(standard.join("lib.wave"), "std input").unwrap(); + let command = |build: &std::path::Path| { + let mut command = f.command(&plan, &[name]); + command + .env("MODERN_CONTRACT", "1") + .env("VEX_WAVE_STD", &standard) + .arg("--build-dir") + .arg(build); + command + }; + assert_code( + &command(&first) + .args(["fetch", "--offline"]) + .output() + .unwrap(), + 0, + ); + let lock = fs::read(f.root.join("vex.lock")).unwrap(); + let build = || { + let mut c = command(&first); + c.args(["build", "--locked", "--offline", "--artifact-manifest"]) + .arg(&report) + .arg("--depfile") + .arg(&depfile); + c + }; + assert_code(&build().output().unwrap(), 0); + assert!(!f.root.join("target").exists()); + assert!(!f.root.join(".vex").exists()); + assert!(first.join(name).is_file()); + let document: Value = serde_json::from_slice(&fs::read(&report).unwrap()).unwrap(); + assert_eq!(document["schema"], "vex.artifacts"); + assert_eq!( + document["results"][0]["metadata"]["compiler"]["std_sha256"] + .as_str() + .unwrap() + .len(), + 64 + ); + let deps = fs::read_to_string(&depfile).unwrap(); + // Windows accepts either separator; plans may retain a forward slash even + // when the project root uses backslashes. + assert!( + deps.contains("src/lib.wave") || cfg!(windows) && deps.contains(r"src\\lib.wave"), + "{deps}" + ); + assert!(deps.contains("vex.lock")); + assert!(deps.contains("prepared\\ std")); + let previous = fs::read(&report).unwrap(); + let previous_depfile = fs::read(&depfile).unwrap(); + let mtime = fs::metadata(&report).unwrap().modified().unwrap(); + assert_code(&build().output().unwrap(), 0); + assert_eq!(fs::metadata(&report).unwrap().modified().unwrap(), mtime); + fs::write( + f.root.join("src/lib.wave"), + "fun main() {} // invalidate the fixture cache\n", + ) + .unwrap(); + let failed = build() + .env("ARTIFACT_BYTES", "replacement") + .env("VEX_TEST_REPORT_FAIL_AFTER", "0") + .output() + .unwrap(); + assert!(!failed.status.success()); + assert_eq!(fs::read(&report).unwrap(), previous); + assert_eq!(fs::read(&depfile).unwrap(), previous_depfile); + assert_code( + &command(&first) + .args(["toolchain", "capture"]) + .output() + .unwrap(), + 0, + ); + let pinned = fs::read(f.root.join("vex.toolchain.lock")).unwrap(); + fs::write( + standard.join("lib.wave"), + "changed std, same compiler version", + ) + .unwrap(); + let mismatch = build().output().unwrap(); + assert_code(&mismatch, 3); + assert!(String::from_utf8_lossy(&mismatch.stderr).contains("std_sha256")); + assert_eq!(fs::read(f.root.join("vex.toolchain.lock")).unwrap(), pinned); + assert_eq!(fs::read(f.root.join("vex.lock")).unwrap(), lock); + fs::write(standard.join("lib.wave"), "std input").unwrap(); + assert_code( + &command(&second) + .args(["fetch", "--locked", "--offline"]) + .output() + .unwrap(), + 0, + ); + assert_code( + &command(&second) + .args(["build", "--locked", "--offline"]) + .output() + .unwrap(), + 0, + ); + assert!(second.join(name).is_file()); + assert_code(&command(&first).arg("clean").output().unwrap(), 0); + assert!(second.join(name).is_file()); + fs::write(&report, "user file").unwrap(); + let refused = build().output().unwrap(); + assert_code(&refused, 5); + assert_eq!(fs::read(&report).unwrap(), b"user file"); +} + +#[test] +fn interrupted_publication_is_readonly_in_dry_run_and_recovers_on_a_normal_build() { + for existing in [false, true] { + let f = Fixture::new(); + let name = "target/x86_64-unknown-linux-gnu/dev/lib/app.o"; + let plan = plan_object(name); + if existing { + assert_code(&f.build(&plan, &[name]), 0); + } + let crashed = f + .command(&plan, &[name]) + .env("ARTIFACT_BYTES", "new complete generation") + .env("VEX_TEST_PUBLICATION_CRASH_AFTER", "0") + .arg("build") + .output() + .unwrap(); + assert_code(&crashed, 97); + let journal = fs::read(f.root.join(".vex/build-publication.json")).unwrap(); + let staged = fs::read(f.root.join(name)).unwrap(); + let dry = f + .command(&plan, &[name]) + .args(["build", "--dry-run"]) + .output() + .unwrap(); + assert!(!dry.status.success()); + assert_eq!( + fs::read(f.root.join(".vex/build-publication.json")).unwrap(), + journal + ); + assert_eq!(fs::read(f.root.join(name)).unwrap(), staged); + assert_code(&f.build(&plan, &[name]), 0); + assert!(!f.root.join(".vex/build-publication.json").exists()); + assert_eq!(fs::read(f.root.join(name)).unwrap(), b"compiled artifact"); + } +} + +#[test] +fn interrupted_report_publication_requires_writable_recovery() { + for existing in [false, true] { + let f = Fixture::new(); + let name = "target/x86_64-unknown-linux-gnu/dev/lib/app.o"; + let mut plan = plan_object(name); + plan["source_inputs"] = json!(["src/lib.wave"]); + let report = f.root.join("artifacts.json"); + let depfile = f.root.join("artifacts.d"); + let build = || { + let mut c = f.command(&plan, &[name]); + c.env("MODERN_CONTRACT", "1") + .args(["build", "--artifact-manifest"]) + .arg(&report) + .arg("--depfile") + .arg(&depfile); + c + }; + if existing { + assert_code(&build().output().unwrap(), 0); + } + fs::write(f.root.join("src/lib.wave"), "fun main() {} // changed\n").unwrap(); + let crashed = build() + .env("ARTIFACT_BYTES", "replacement") + .env("VEX_TEST_REPORT_CRASH_AFTER", "0") + .output() + .unwrap(); + assert_code(&crashed, 97); + let journal_path = f.root.join(".vex/report-publication.json"); + let journal = fs::read(&journal_path).unwrap(); + let staged = fs::read(&report).ok(); + let old_depfile = fs::read(&depfile).ok(); + let dry = build().arg("--dry-run").output().unwrap(); + assert!(!dry.status.success()); + assert_eq!(fs::read(&journal_path).unwrap(), journal); + assert_eq!(fs::read(&report).ok(), staged); + assert_eq!(fs::read(&depfile).ok(), old_depfile); + assert_code(&build().output().unwrap(), 0); + assert!(!journal_path.exists()); + let result: Value = serde_json::from_slice(&fs::read(&report).unwrap()).unwrap(); + assert_eq!(result["schema"], "vex.artifacts"); + assert!(fs::read_to_string(&depfile).unwrap().contains("vex.ws")); + } +} + +#[test] +fn same_version_different_compiler_bytes_fail_before_dependency_mutation() { + use std::io::Write; + let f = Fixture::new(); + let name = "target/x86_64-unknown-linux-gnu/dev/lib/app.o"; + let plan = plan_object(name); + let template = f.command(&plan, &[name]); + let original = template + .get_envs() + .find(|(name, _)| *name == "VEX_WAVEC") + .unwrap() + .1 + .unwrap(); + let prepared = f.root.join(if cfg!(windows) { + "prepared.exe" + } else { + "prepared" + }); + fs::copy(original, &prepared).unwrap(); + let command = || { + let mut c = f.command(&plan, &[name]); + c.env("VEX_WAVEC", &prepared); + c + }; + assert_code( + &command().args(["toolchain", "capture"]).output().unwrap(), + 0, + ); + let pin = fs::read(f.root.join("vex.toolchain.lock")).unwrap(); + fs::OpenOptions::new() + .append(true) + .open(&prepared) + .unwrap() + .write_all(b"same version, different build") + .unwrap(); + let output = command().args(["build", "--offline"]).output().unwrap(); + assert_code(&output, 3); + assert!(String::from_utf8_lossy(&output.stderr).contains("compiler_sha256")); + assert!(!f.root.join("target").exists()); + assert!(!f.root.join("vex.lock").exists()); + assert!(!f.root.join("compiled").exists()); + assert_eq!(fs::read(f.root.join("vex.toolchain.lock")).unwrap(), pin); +} + +#[test] +fn absolute_external_outputs_and_private_report_aliases_use_the_same_storage_boundary() { + let f = Fixture::new(); + let build = f.root.join("external build"); + let name = "target/x86_64-unknown-linux-gnu/dev/lib/app.o"; + // On Windows the compiler receives a normal drive path while the selected + // build root is canonical/verbatim. Both denote this exact owned location. + let output = state::layout::path_form(&build.join(name)); + let mut plan = plan_object(output.to_str().unwrap()); + plan["source_inputs"] = json!(["src/lib.wave"]); + let first = f + .command(&plan, &[name]) + .arg("--build-dir") + .arg(&build) + .arg("build") + .output() + .unwrap(); + assert_code(&first, 0); + assert!(output.is_file()); + assert!(!f.root.join(name).exists()); + let before = fs::read(build.join(".vex/build-owner.json")).unwrap(); + let alias = build.join("absent/../.vex/report.json"); + let refused = f + .command(&plan, &[name]) + .arg("--build-dir") + .arg(&build) + .args(["build", "--artifact-manifest"]) + .arg(alias) + .output() + .unwrap(); + assert_code(&refused, 2); + assert_eq!( + fs::read(build.join(".vex/build-owner.json")).unwrap(), + before + ); + assert!(!build.join(".vex/report.json").exists()); + let other = Fixture::new(); + let refused = other + .command(&plan, &[name]) + .arg("--build-dir") + .arg(&build) + .arg("build") + .output() + .unwrap(); + assert_code(&refused, 2); + assert_eq!( + fs::read(build.join(".vex/build-owner.json")).unwrap(), + before + ); +} + +#[cfg(unix)] +#[test] +fn cancelled_rebuild_preserves_completed_artifact_and_consumer_reports() { + use std::time::{Duration, Instant}; + let f = Fixture::new(); + let name = "target/x86_64-unknown-linux-gnu/dev/lib/app.o"; + let mut plan = plan_object(name); + plan["source_inputs"] = json!(["src/lib.wave"]); + let report = f.root.join("artifacts.json"); + let depfile = f.root.join("artifacts.d"); + let build = || { + let mut c = f.command(&plan, &[name]); + c.env("MODERN_CONTRACT", "1") + .args(["build", "--artifact-manifest"]) + .arg(&report) + .arg("--depfile") + .arg(&depfile); + c + }; + assert_code(&build().output().unwrap(), 0); + let before = [ + fs::read(f.root.join(name)).unwrap(), + fs::read(&report).unwrap(), + fs::read(&depfile).unwrap(), + ]; + fs::write(f.root.join("src/lib.wave"), "fun main() {} // changed\n").unwrap(); + let marker = f.root.join("staged-ready"); + let mut child = build() + .env("PAUSE_AFTER_OUTPUT", &marker) + .env("ARTIFACT_BYTES", "unpublished replacement") + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn() + .unwrap(); + let deadline = Instant::now() + Duration::from_secs(15); + while !marker.exists() { + if child.try_wait().unwrap().is_some() || Instant::now() > deadline { + let _ = child.kill(); + let _ = child.wait(); + panic!("compiler did not stage replacement outputs"); + } + std::thread::sleep(Duration::from_millis(10)); + } + assert!(Command::new("kill") + .args(["-TERM", &child.id().to_string()]) + .status() + .unwrap() + .success()); + assert_eq!(child.wait().unwrap().code(), Some(130)); + assert_eq!( + [ + fs::read(f.root.join(name)).unwrap(), + fs::read(&report).unwrap(), + fs::read(&depfile).unwrap() + ], + before + ); + assert_code(&build().output().unwrap(), 0); +} + +#[cfg(unix)] +#[test] +fn nonregular_build_owner_is_rejected_without_waiting_for_a_fifo_writer() { + use std::time::{Duration, Instant}; + let f = Fixture::new(); + let build = f.root.join("external-fifo-owner"); + fs::create_dir_all(build.join(".vex")).unwrap(); + assert!(Command::new("mkfifo") + .arg(build.join(".vex/build-owner.json")) + .status() + .unwrap() + .success()); + let plan = plan_object("target/x86_64-unknown-linux-gnu/dev/lib/app.o"); + let mut child = f + .command(&plan, &[]) + .arg("--build-dir") + .arg(build) + .arg("build") + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn() + .unwrap(); + let deadline = Instant::now() + Duration::from_secs(5); + loop { + if let Some(status) = child.try_wait().unwrap() { + assert!(!status.success()); + break; + } + if Instant::now() > deadline { + let _ = child.kill(); + let _ = child.wait(); + panic!("opening an invalid storage owner blocked"); + } + std::thread::sleep(Duration::from_millis(10)); + } + assert!(!f.root.join("compiled").exists()); +} diff --git a/tests/cli_contract.rs b/tests/cli_contract.rs index f72f9e8..d9eec12 100644 --- a/tests/cli_contract.rs +++ b/tests/cli_contract.rs @@ -783,3 +783,24 @@ fn init_reports_ignore_creation_only_when_created() { } } } + +#[test] +fn format_five_init_is_ready_for_immediate_locked_offline_use() { + let fixture = TestDir::new(); + let project = fixture.0.join("new_package"); + fs::create_dir(&project).unwrap(); + assert_success(&vex(&project, &["init", "--lib"]), "new format 5 library"); + assert!(fs::read_to_string(project.join("vex.ws")) + .unwrap() + .contains("format = 5")); + let bytes = fs::read(project.join("vex.lock")).unwrap(); + let lock = lockfile::decode(std::str::from_utf8(&bytes).unwrap()).unwrap(); + assert_eq!(lock.version, 4); + assert_eq!(lock.roots.len(), 1); + assert_eq!(lock.roots[0].name, "new_package"); + assert_success( + &vex(&project, &["fetch", "--locked", "--offline"]), + "immediate prepared lock reuse", + ); + assert_eq!(fs::read(project.join("vex.lock")).unwrap(), bytes); +} diff --git a/tests/dependency_edit.rs b/tests/dependency_edit.rs index c57ea2d..610af25 100644 --- a/tests/dependency_edit.rs +++ b/tests/dependency_edit.rs @@ -119,7 +119,7 @@ fn crash_recovery_is_readonly_until_normal_command() { let modified = f.pair(); check( f.app() - .args(["metadata", "--format-version", "2"]) + .args(["metadata", "--format-version", "3"]) .output() .unwrap(), 5, @@ -188,3 +188,68 @@ fn cache_dry_run_preserves_message_file_contract() { "existing" ); } + +#[test] +fn removal_deletes_all_conditional_bindings_and_preserves_test_dependencies() { + let f = F::new(); + let text = r#"{format=4,name="app",targets={bins=[{name="app",path="src/main.wave"}]},dependencies=[/*before*/{name="platform",package="dep",path="../dep",target={os="linux"}},/*middle*/{name="platform",package="dep",path="../dep",target={os="windows"}}/*after*/],test_dependencies=[{name="platform",package="dep",path="../dep"}]}"#; + // Test/normal alias coexistence is deliberately rejected by the manifest, + // so exercise independent test declarations with a different alias here. + let text = text.replace( + "test_dependencies=[{name=\"platform\"", + "test_dependencies=[{name=\"fixture\"", + ); + fs::write(f.0.join("app/vex.ws"), text).unwrap(); + check( + f.app() + .args(["remove", "platform", "--offline"]) + .output() + .unwrap(), + 0, + ); + let (manifest, lock) = f.pair(); + assert!(!manifest.contains("name=\"platform\"")); + assert!(manifest.contains("name=\"fixture\"")); + for comment in ["/*before*/", "/*middle*/", "/*after*/"] { + assert!(manifest.contains(comment)); + } + assert!(lock.contains("fixture")); +} + +#[test] +fn metadata_fetch_guidance_preserves_the_resolver_context_and_causes() { + let f = F::new(); + fs::write(f.0.join("app/vex.ws"),r#"{format=4,name="app",targets={bins=[{name="app",path="src/main.wave"}]},dependencies=[{name="dep",path="../dep"}]}"#).unwrap(); + fs::write( + f.0.join("dep/vex.ws"), + r#"{format=4,name="dep",targets={lib={}},unknown_field=true}"#, + ) + .unwrap(); + for (name, args) in [ + ("fetch.jsonl", vec!["fetch", "--offline"]), + ("metadata.jsonl", vec!["metadata", "--format-version", "2"]), + ] { + check( + f.app() + .args(["--message-file", name]) + .args(args) + .output() + .unwrap(), + 3, + ); + let raw = fs::read_to_string(f.0.join("app").join(name)).unwrap(); + let events = raw + .lines() + .map(|l| serde_json::from_str::(l).unwrap()) + .collect::>(); + let diagnostic = events.iter().find(|v| v["event"] == "diagnostic").unwrap(); + assert!( + !diagnostic["context"].as_array().unwrap().is_empty(), + "{raw}" + ); + assert!( + !diagnostic["causes"].as_array().unwrap().is_empty(), + "{raw}" + ); + } +} diff --git a/tests/doctor.rs b/tests/doctor.rs index a7d73e0..f60278d 100644 --- a/tests/doctor.rs +++ b/tests/doctor.rs @@ -55,6 +55,16 @@ impl Fixture { "{ version = 3, package = [] }\n", ) .unwrap(); + let prepared = self + .command() + .args(["fetch", "--offline"]) + .output() + .unwrap(); + assert!( + prepared.status.success(), + "{}", + String::from_utf8_lossy(&prepared.stderr) + ); } } fn command(&self) -> Command { @@ -560,3 +570,143 @@ fn every_declared_entry_is_validated_before_doctor_plans_any_target() { assert!(!f.calls().lines().any(|call| call.contains(" build "))); assert_eq!(before, snapshot(&f.work)); } + +#[test] +fn malformed_version_tokens_are_compiler_errors() { + let f = Fixture::new(); + for version in ["banana", "1.2", "01.2.3"] { + let out = f + .command() + .env("DOCTOR_VERSION", version) + .args(["doctor", "--format=json"]) + .output() + .unwrap(); + assert!( + !out.status.success(), + "{}", + String::from_utf8_lossy(&out.stdout) + ); + } + for version in ["0.2.1-pre-beta-dev", "0.2.1+development"] { + let out = f + .command() + .env("DOCTOR_VERSION", version) + .args(["doctor", "--format=json"]) + .output() + .unwrap(); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stdout) + ); + } +} + +#[test] +fn an_explicit_plan_target_mismatch_fails_without_compilation() { + let f = Fixture::new(); + f.project(true); + for args in [ + vec!["build", "--dry-run", "--target", "doctor-cross-target"], + vec!["build", "--dry-run", "--target=doctor-cross-target"], + vec!["doctor", "--format=json", "--target", "doctor-cross-target"], + ] { + let out = f + .command() + .env("DOCTOR_PLAN_TARGET", host_target()) + .args(args) + .output() + .unwrap(); + assert_eq!( + out.status.code(), + Some(4), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + assert!( + String::from_utf8_lossy(&out.stderr).contains("target mismatch") + || String::from_utf8_lossy(&out.stdout).contains("target mismatch") + ); + } +} +#[cfg(unix)] +#[test] +fn path_lookup_skips_nonexecutables_but_explicit_selection_is_preserved() { + use std::os::unix::fs::PermissionsExt; + let f = Fixture::new(); + let bad = f.root.join("bad-path"); + fs::create_dir(&bad).unwrap(); + let file = bad.join("wavec"); + fs::write(&file, "not executable").unwrap(); + fs::set_permissions(&file, fs::Permissions::from_mode(0o644)).unwrap(); + let path = std::env::join_paths([bad.as_path(), f.bin.as_path()]).unwrap(); + let output = f + .command() + .env_remove("VEX_WAVEC") + .env("PATH", &path) + .args(["doctor", "--format=json"]) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let explicit = f + .command() + .env("VEX_WAVEC", file) + .env("PATH", path) + .args(["doctor", "--format=json"]) + .output() + .unwrap(); + assert_eq!(explicit.status.code(), Some(5)); +} +#[test] +fn quiet_setup_suppresses_installation_progress_on_failure() { + let f = Fixture::new(); + // Windows searches the application directory before System32 and PATH. + // Keep the installer beside its stub so the system curl cannot be used. + let vex = f.bin.join(exe("vex")); + fs::copy(env!("CARGO_BIN_EXE_vex"), &vex).unwrap(); + fs::copy(fake(), f.bin.join(exe("curl"))).unwrap(); + let toolchain = f.root.join("toolchain"); + for quiet in [false, true] { + let mut command = Command::new(&vex); + command + .current_dir(&f.work) + .env("PATH", &f.bin) + .env("DOCTOR_LOG", f.root.join("calls.log")) + .env("VEX_TOOLCHAIN_HOME", &toolchain) + .env_remove("GH_TOKEN") + .env_remove("GITHUB_TOKEN"); + if quiet { + command.arg("--quiet"); + } + let output = command + .args(["setup", "wavec", "--version", "0.2.1-pre-beta"]) + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(5), "{stderr}"); + assert!( + stderr.contains("could not query compiler GitHub API"), + "{stderr}" + ); + assert!( + output.stdout.is_empty(), + "{}", + String::from_utf8_lossy(&output.stdout) + ); + assert_eq!(stderr.contains("Installing"), !quiet); + assert!(!toolchain.exists()); + } + let calls = f.calls(); + assert_eq!( + calls + .lines() + .filter(|line| line.starts_with("curl:")) + .count(), + 2, + "{calls}" + ); +} diff --git a/tests/external_builds.py b/tests/external_builds.py new file mode 100644 index 0000000..567eda3 --- /dev/null +++ b/tests/external_builds.py @@ -0,0 +1,220 @@ +#!/usr/bin/env python3 +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 +"""Real Wave contract acceptance; requires package_graph/path_remap/source_inputs v1. + +This is supplemental until a compatible public compiler is pinned for release. +It never downloads or builds a compiler and never converts a missing capability +into a passed check. Meson owns all C/C++/Rust compilation and final linking. +""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import shutil +import signal +import subprocess +import sys +import tempfile +import time + +ROOT = Path(__file__).resolve().parents[1] +EXAMPLE = ROOT / 'examples/meson-consumer' + + +def run(command, env, *, expected=0): + print('+', *map(str, command), flush=True) + output = subprocess.run(list(map(str, command)), env=env, capture_output=True, + text=True, encoding='utf-8', timeout=300) + if output.returncode != expected: + raise RuntimeError(f'exit {output.returncode}, expected {expected}: {output.stdout}\n{output.stderr}') + return output + + +def file_hash(path): + with path.open('rb') as stream: + return hashlib.file_digest(stream, 'sha256').hexdigest() + + +def result(build): + return json.loads((build/'vex/consumer-result.json').read_text(encoding='utf-8'))['results'][0] + + +def primaries(record): + return [Path(a['path']) for a in record['artifacts'] if a['role'] == 'primary'] + + +def mtimes(build): + return {str(p): p.stat().st_mtime_ns for p in build.iterdir() + if p.is_file() and (p.name.startswith('caller_') or p.suffix in {'.a', '.lib'})} + + +def prepare(vex, source, build, env): + run([vex, '--manifest-path', source/'wave/vex.ws', '--build-dir', build/'vex', 'fetch', '--offline'], env) + + +def configure(vex, source, build, env, profile='dev', features=''): + run(['meson', 'setup', '--reconfigure', build, source, '-Dvex='+str(vex), + '-Dadapter='+str(ROOT/'tools/meson_consumer.py'), '-Dwave_profile='+profile, + '-Dwave_features='+features], env) + + +def build_and_run(build, env): + run(['meson', 'compile', '-C', build], env) + run(['meson', 'test', '-C', build, '--no-rebuild', '--print-errorlogs'], env) + + +def meson_contract(vex, temporary, env): + first = temporary/'source é one' + second = temporary/'source é two' + shutil.copytree(EXAMPLE, first) + manifest = first/'wave/vex.ws' + manifest.write_text(manifest.read_text(encoding='utf-8').replace('features =', 'build = { reproducible = true }, features ='), encoding='utf-8') + a = temporary/'build é one' + b = temporary/'build é two' + prepare(vex, first, a, env) + run([vex, '--manifest-path', manifest, '--build-dir', a/'vex', 'toolchain', 'capture'], env) + shutil.copytree(first, second) + prepare(vex, second, b, env) + for source, build in [(first, a), (second, b)]: + configure(vex, source, build, env) + build_and_run(build, env) + ra, rb = result(a), result(b) + if [p.read_bytes() for p in primaries(ra)] != [p.read_bytes() for p in primaries(rb)] or ra['provenance'] != rb['provenance']: + raise RuntimeError('separate roots produced different artifact bytes or portable provenance') + portable = json.dumps(ra['provenance'], ensure_ascii=False) + if str(temporary) in portable: + raise RuntimeError('portable provenance leaked a physical source/build path') + before = mtimes(a) + build_and_run(a, env) + if before != mtimes(a): + raise RuntimeError('unchanged verified inputs relinked native consumers: '+repr((before,mtimes(a)))) + # A renamed transitive import must be rediscovered without configuring Meson. + (first/'math/src/value.wave').rename(first/'math/src/renamed.wave') + (first/'math/src/lib.wave').write_text('pub import("./renamed.wave")::{answer};\n', encoding='utf-8') + build_and_run(a, env) + inputs = result(a)['metadata']['inputs']['files'] + if not any(p.endswith('renamed.wave') for p in inputs) or any(p.endswith('value.wave') for p in inputs): + raise RuntimeError('scheduler inputs did not follow an import addition/removal') + # Compilation failure must preserve reports, complete bridge and consumers. + report = a/'vex/consumer-result.json' + saved = report.read_bytes() + bridge = a/('wave_bridge.lib' if os.name == 'nt' else 'libwave_bridge.a') + saved_bridge = bridge.read_bytes() + value = first/'math/src/renamed.wave' + saved_source = value.read_bytes() + value.write_text('this is invalid Wave source', encoding='utf-8') + failure = subprocess.run(['meson', 'compile', '-C', str(a)], env=env, capture_output=True, timeout=300) + if failure.returncode == 0 or report.read_bytes() != saved or bridge.read_bytes() != saved_bridge: + raise RuntimeError('failed rebuild replaced a complete consumer result') + value.write_bytes(saved_source) + # Prepared read-only source uses external leases/checkouts/output state only. + permissions = [] + if os.name != 'nt': + for path in sorted(first.rglob('*'), reverse=True): + permissions.append((path, path.stat().st_mode)) + path.chmod(0o555 if path.is_dir() else 0o444) + permissions.append((first, first.stat().st_mode)) + first.chmod(0o555) + try: + build_and_run(a, env) + finally: + for path, mode in reversed(permissions): + path.chmod(mode) + configure(vex, first, a, env, 'release', 'tuned') + build_and_run(a, env) + record = result(a) + if record['metadata']['profile']['opt_level'] != 2 or 'tuned' not in json.dumps(record['metadata']['features']): + raise RuntimeError('profile/feature selection was not recorded') + if (first/'wave/target').exists() or (first/'wave/.vex').exists(): + raise RuntimeError('external builds wrote generated state into source') + print('PASS: Meson C/C++/Rust, independent roots/provenance, restat, imports, failure, readonly, profile/features', flush=True) + + +def scoped_aliases(vex, temporary, env): + base = temporary/'scoped aliases é' + declarations = { + 'one': ('math', '1.0.0', [], 'pub fun value()->i32{return 11;}'), + 'two': ('math', '2.0.0', [], 'pub fun value()->i32{return 31;}'), + 'left': ('left', '1.0.0', [('math', '../one')], 'import("math")::{value}; pub fun left()->i32{return value();}'), + 'right': ('right', '1.0.0', [('math', '../two')], 'import("math")::{value}; pub fun right()->i32{return value();}')} + for directory, (name, version, dependencies, source) in declarations.items(): + package = base/directory + (package/'src').mkdir(parents=True) + deps = ','.join('{name='+json.dumps(alias)+',path='+json.dumps(path)+'}' for alias, path in dependencies) + (package/'vex.ws').write_text('{format=5,name='+json.dumps(name)+',version='+json.dumps(version)+',targets={lib={}},dependencies=['+deps+']}', encoding='utf-8') + (package/'src/lib.wave').write_text(source, encoding='utf-8') + app = base/'app' + (app/'src').mkdir(parents=True) + (app/'vex.ws').write_text('{format=5,name="app",version="1.0.0",targets={bins=[{name="app",path="src/main.wave"}]},dependencies=[{name="left",path="../left"},{name="right",path="../right"}]}', encoding='utf-8') + (app/'src/main.wave').write_text('import("left")::{left};import("right")::{right};fun main(){println("{}",left()+right());}', encoding='utf-8') + command = [vex, '--manifest-path', app/'vex.ws', '--build-dir', base/'build'] + run(command+['fetch', '--offline'], env) + output = run(command+['run', '--locked', '--offline'], env) + if output.stdout.strip() != '42': + raise RuntimeError('package-scoped aliases did not select their distinct transitive versions') + print('PASS: Vex scoped aliases and simultaneous transitive versions execute as 42', flush=True) + + +def cross_archives(vex, temporary, env, selected=None): + rows = json.loads((ROOT/'platforms.json').read_text())['platforms'] + for row in rows: + if selected is not None and row['id'] not in selected: + continue + triple = row['rust_target'] + if triple.startswith('riscv64gc-'): + triple = triple.replace('riscv64gc-', 'riscv64-', 1) + records = [] + for directory in ['first é', 'second é']: + source = temporary/row['id']/directory/'source' + (source/'src').mkdir(parents=True) + relocation = 'default' if row['os'] == 'windows' else 'pic' + (source/'vex.ws').write_text('{format=5,name="portable",version="1.0.0",targets={lib={output="static",mode="freestanding",relocation="'+relocation+'"}},build={reproducible=true}}', encoding='utf-8') + (source/'src/lib.wave').write_text('export(c) fun wave_add(a:i32,b:i32)->i32{return a+b;}\n', encoding='utf-8') + build = source.parent/'build' + command = [vex, '--manifest-path', source/'vex.ws', '--build-dir', build] + run(command+['fetch', '--offline'], env) + outputs = [] + for profile in ['dev', 'release']: + report = build/(profile+'.json') + run(command+['build', '--locked', '--offline', '--target', triple, '--profile', profile, + '--artifact-manifest', report], env) + record = json.loads(report.read_text(encoding='utf-8'))['results'][0] + outputs.append(([p.read_bytes() for p in primaries(record)], record['provenance'])) + records.append(outputs) + if records[0] != records[1]: + raise RuntimeError('non-deterministic archive bytes/provenance for '+triple) + print('PASS: O0/O2 deterministic indexed archive and object machine inspection: '+triple, flush=True) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--vex', type=Path, required=True) + parser.add_argument('--wavec', type=Path, required=True) + parser.add_argument('--std', type=Path, required=True) + parser.add_argument('--cross-formats', action='store_true') + args = parser.parse_args() + fixture = json.loads((EXAMPLE/'fixture.json').read_text(encoding='utf-8')) + for name, expected in fixture['sha256'].items(): + if file_hash(EXAMPLE/name) != expected: + raise RuntimeError('reviewed Whale-shaped fixture changed: '+name) + with tempfile.TemporaryDirectory(prefix='vex-external-contract-') as path: + temporary = Path(path).resolve() + env = dict(os.environ, VEX_WAVEC=str(args.wavec.resolve()), VEX_WAVE_STD=str(args.std.resolve()), + VEX_CACHE_HOME=str(temporary/'cache'), XDG_STATE_HOME=str(temporary/'state')) + for key in ['GH_TOKEN', 'GITHUB_TOKEN', 'VEX_BUILD_DIR', 'VEX_STATE_DIR']: + env.pop(key, None) + capabilities = json.loads(run([args.wavec.resolve(), 'print', 'vex-capabilities', '--format=json'], env).stdout) + if capabilities.get('schema_version') != 1 or any(capabilities.get(k) != 1 for k in ['package_graph', 'path_remap', 'source_inputs']): + raise RuntimeError('compiler lacks the required explicit build contract') + scoped_aliases(args.vex.resolve(), temporary, env) + meson_contract(args.vex.resolve(), temporary, env) + if args.cross_formats: + cross_archives(args.vex.resolve(), temporary, env) + + +if __name__ == '__main__': + main() diff --git a/tests/fixtures/artifact_wavec.rs b/tests/fixtures/artifact_wavec.rs index d7aa043..5c15899 100644 --- a/tests/fixtures/artifact_wavec.rs +++ b/tests/fixtures/artifact_wavec.rs @@ -7,14 +7,25 @@ use std::{env, fs, path::Path, process}; fn quote(value: &str) -> String { format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\"")) } +fn output_prefix(actual: &str, suffix: &Path) -> Option { + let path = Path::new(actual); + if !path.ends_with(suffix) { return None; } + let mut prefix = path.to_path_buf(); + for _ in suffix.components() { prefix.pop(); } + Some(prefix) +} fn main() { let args: Vec<_> = env::args().collect(); if args.iter().any(|arg| arg == "--version") { println!("wavec 0.2.1-pre-beta"); return; } - if args.get(1).is_some_and(|arg| arg == "print") { - if args.get(2).is_some_and(|arg| arg == "supported-targets") { + if let Some(at)=args.iter().position(|arg|arg=="print") { + if args.get(at+1).is_some_and(|arg|arg=="std-path") { + if let Some(root)=args.iter().find_map(|a|a.strip_prefix("--std-root=")) {println!("{}",quote(root));}else{println!("null");} + } else if args.get(at+1).is_some_and(|arg|arg=="vex-capabilities") { + if env::var_os("MODERN_CONTRACT").is_some(){println!("{{\"schema_version\":1,\"package_graph\":1,\"path_remap\":1,\"source_inputs\":1}}");}else{process::exit(2);} + } else if args.get(at+1).is_some_and(|arg| arg == "supported-targets") { println!("[\"x86_64-unknown-linux-gnu\",\"x86_64-pc-windows-msvc\"]"); } else { let triple = args.iter().find_map(|arg| arg.strip_prefix("--target=")) @@ -29,16 +40,32 @@ fn main() { return; } fs::write("compiled", "compiler started").unwrap(); - for path in env::var("OUTPUTS").unwrap_or_default().lines() { - let path = Path::new(path); + let outputs=env::var("OUTPUTS").unwrap_or_default(); + let actual_output=args.windows(2).find(|pair|pair[0]=="-o").map(|pair|pair[1].as_str()); + let actual_directory=args.iter().find_map(|arg|arg.strip_prefix("--target-dir=")); + let mut prefix=None; + for output in outputs.lines() { + if let Some(actual)=actual_output.and_then(|path|output_prefix(path, Path::new(output))) {prefix=Some(actual);break;} + if let Some(parent)=Path::new(output).parent() { + if let Some(actual)=actual_directory.and_then(|path|output_prefix(path,parent)) {prefix=Some(actual);break;} + } + } + for original in outputs.lines() { + let mapped=prefix.as_ref().map(|prefix|prefix.join(original)).unwrap_or_else(||Path::new(original).to_path_buf()); + let path = mapped.as_path(); fs::create_dir_all(path.parent().unwrap()).unwrap(); if env::var_os("DIRECTORY_OUTPUT").is_some() { fs::create_dir(path).unwrap(); } else { - fs::write(path, b"compiled artifact").unwrap(); + fs::write(path, env::var("ARTIFACT_BYTES").unwrap_or_else(|_|"compiled artifact".into())).unwrap(); } } + if let Some(marker) = env::var_os("PAUSE_AFTER_OUTPUT") { + fs::write(marker, "outputs staged").unwrap(); + std::thread::sleep(std::time::Duration::from_secs(30)); + } if env::var_os("FAIL_OWNERSHIP").is_some() { + let _=fs::remove_file(".vex/artifacts.json"); fs::create_dir(".vex/artifacts.json").unwrap(); } let code = env::var("COMPILE_EXIT").unwrap_or_else(|_| "0".into()).parse().unwrap(); diff --git a/tests/fixtures/doctor_tools.rs b/tests/fixtures/doctor_tools.rs index 3beb88a..73a68fd 100644 --- a/tests/fixtures/doctor_tools.rs +++ b/tests/fixtures/doctor_tools.rs @@ -10,13 +10,16 @@ fn main() { if let Ok(path) = env::var("DOCTOR_LOG") { writeln!(OpenOptions::new().create(true).append(true).open(path).unwrap(), "{kind}:{}", args.join(" ")).unwrap(); } + if kind == "curl" { + std::process::exit(7); + } if kind == "git" { assert_eq!(args, ["--version"], "doctor must never fetch or access a remote"); println!("git version 2.48.0"); return; } if args == ["--version"] { assert!(env::var_os("NO_COLOR").is_some()); - println!("wavec 0.2.1-pre-beta"); return; + println!("wavec {}",env::var("DOCTOR_VERSION").unwrap_or_else(|_|"0.2.1-pre-beta".into())); return; } if args == ["print", "supported-targets", "--format=json"] { println!("{}", env::var("DOCTOR_TARGETS").unwrap()); return; @@ -41,5 +44,6 @@ fn main() { let compile = if object { format!("[{{\"input\":\"src/lib.wave\",\"kind\":\"wave\",\"output\":{requested_output:?},\"command\":\"wavec\"}}]") } else { "[]".into() }; + let target = env::var("DOCTOR_PLAN_TARGET").unwrap_or(target); println!("{{\"schema_version\":{schema},\"mode\":\"build\",\"target\":{target:?},\"emit\":{emit:?},\"emit_kinds\":[],\"control_mode\":null,\"forced_input_type\":null,\"inputs\":[],\"emit_jobs\":[],\"compile\":{compile},\"link\":{link},\"execute\":null}}"); } diff --git a/tests/fixtures/fake_wavec.rs b/tests/fixtures/fake_wavec.rs index d87d55f..da2872d 100644 --- a/tests/fixtures/fake_wavec.rs +++ b/tests/fixtures/fake_wavec.rs @@ -90,11 +90,12 @@ fn main() { } else { format!("{{\"program\":{output:?},\"args\":{runtime:?}}}") }; (link, if mode == "build+run" { execute } else { "null".into() }) } else { ("null".into(), "null".into()) }; - println!("{{\"schema_version\":{schema},\"mode\":\"{mode}\",\"target\":\"test-target\",\"emit\":\"{emit}\",\"emit_kinds\":[],\"control_mode\":null,\"forced_input_type\":null,\"inputs\":[],\"emit_jobs\":[],\"compile\":[],\"link\":{link},\"execute\":{execute}}}"); + let target=args.iter().find_map(|a|a.strip_prefix("--target=")).unwrap_or("test-target"); + println!("{{\"schema_version\":{schema},\"mode\":\"{mode}\",\"target\":{target:?},\"emit\":\"{emit}\",\"emit_kinds\":[],\"control_mode\":null,\"forced_input_type\":null,\"inputs\":[],\"emit_jobs\":[],\"compile\":[],\"link\":{link},\"execute\":{execute}}}"); } else { assert!(!args.iter().any(|a| a == "--run" || a == "--")); checkpoint("COMPILE"); - if let Some(output) = env::var_os("FAKE_BUILD_OUTPUT").map(PathBuf::from) { + if let Some(output) = env::var_os("FAKE_BUILD_OUTPUT").map(|_|explicit_output.clone().unwrap_or_else(||PathBuf::from(env::var_os("FAKE_BUILD_OUTPUT").unwrap()))) { fs::create_dir_all(output.parent().unwrap()).unwrap(); fs::write(output, b"compiled artifact").unwrap(); } diff --git a/tests/git_lock_reproducibility.rs b/tests/git_lock_reproducibility.rs index 175962a..f006574 100644 --- a/tests/git_lock_reproducibility.rs +++ b/tests/git_lock_reproducibility.rs @@ -1149,7 +1149,7 @@ fn unsupported_windows_checkout_directory_preserves_existing_state() { create_package(&app, "app", &[("dep", git_url(&dep), None)]); assert_success( &vex(&app, &["fetch"]), - "initial fetch before moving project", + "prepare checkout fixture at a supported path", ); let lock = fs::read(app.join("vex.lock")).unwrap(); let parsed = lockfile::decode(std::str::from_utf8(&lock).unwrap()).unwrap(); @@ -1161,9 +1161,17 @@ fn unsupported_windows_checkout_directory_preserves_existing_state() { while deep.as_os_str().len() < 175 { deep.push("nested project directory"); } - fs::create_dir_all(&deep).unwrap(); deep.push("app"); - fs::rename(&app, &deep).unwrap(); + // Prepare ownership at the final source root. Moving the whole prepared + // project would fail the source-identity guard before reaching Git's path + // limit. Seed only the lock and checkout to test preservation at that limit. + create_package(&deep, "app", &[]); + assert_success(&vex(&deep, &["fetch", "--offline"]), "prepare deep store"); + create_package(&deep, "app", &[("dep", git_url(&dep), None)]); + fs::write(deep.join("vex.lock"), &lock).unwrap(); + fs::create_dir_all(deep.join(resolved).parent().unwrap()).unwrap(); + fs::rename(app.join(resolved), deep.join(resolved)).unwrap(); + let owner = fs::read(deep.join(".vex/store-owner.json")).unwrap(); let output = vex(&deep, &["update", "dep"]); let stderr = String::from_utf8_lossy(&output.stderr); assert_eq!(output.status.code(), Some(5), "{stderr}"); @@ -1173,6 +1181,7 @@ fn unsupported_windows_checkout_directory_preserves_existing_state() { ); assert!(!stderr.contains("Cloning"), "{stderr}"); assert_eq!(fs::read(deep.join("vex.lock")).unwrap(), lock); + assert_eq!(fs::read(deep.join(".vex/store-owner.json")).unwrap(), owner); assert_eq!( fs::read(deep.join(resolved).join("src/lib.wave")).unwrap(), source diff --git a/tests/lockfile_compatibility.rs b/tests/lockfile_compatibility.rs index 871b7e9..cfb1639 100644 --- a/tests/lockfile_compatibility.rs +++ b/tests/lockfile_compatibility.rs @@ -173,7 +173,15 @@ fn invalid_v2_locks_fail_before_mutating_dependency_state() { assert!(stderr.contains("help:"), "{stderr}"); assert_eq!(fixture.lock(), input); assert!(fixture.0.join("app/.vex/state.lock").is_file()); - assert_eq!(fs::read_dir(fixture.0.join("app/.vex")).unwrap().count(), 1); + assert_eq!( + fs::read_dir(fixture.0.join("app/.vex")) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect::>(), + ["state.lock".to_owned(), "store-owner.json".to_owned()] + .into_iter() + .collect() + ); assert_eq!(fs::read_dir(fixture.0.join("app")).unwrap().count(), 3); } } diff --git a/tests/native_interop.py b/tests/native_interop.py index 11d95ad..e97669e 100644 --- a/tests/native_interop.py +++ b/tests/native_interop.py @@ -17,15 +17,21 @@ from pathlib import Path import shutil import subprocess +import sys import tempfile def run(command, cwd, env, expected=0, *, native_tool=False): + # CI may redirect stdout through a legacy Windows code page. Keep both + # decoding and replayed diagnostic bytes UTF-8. + for stream in (sys.stdout, sys.stderr): + if hasattr(stream, 'reconfigure'): + stream.reconfigure(encoding='utf-8') command = list(map(str, command)) if env.get("VEX_TEST_TARGET_RUNNER") and not native_tool: command.insert(0, env["VEX_TEST_TARGET_RUNNER"]) print("$", " ".join(command), flush=True) - result = subprocess.run(command, cwd=cwd, env=env, text=True, + result = subprocess.run(command, cwd=cwd, env=env, text=True, encoding="utf-8", capture_output=True, timeout=300) print(result.stdout, end="", flush=True) print(result.stderr, end="", flush=True) @@ -331,6 +337,55 @@ def format_three_exports(vex, root, tools, spec): raise RuntimeError("format 3 native output selection changed vex.lock") +def static_exports(vex, root, tools, spec): + project = root / "static exports é" + (project / "src").mkdir(parents=True) + (project / "src/lib.wave").write_text( + 'export(c) fun wave_add(a:i32,b:i32)->i32{return a+b;}\n', encoding='utf-8') + archiver = os.environ.get('VEX_TEST_ARCHIVER') + if not archiver and tools.windows: + candidates = [shutil.which('llvm-lib.exe', path=tools.env['PATH']), + str(Path(tools.env.get('PROGRAMFILES', r'C:\Program Files')) / 'LLVM/bin/llvm-lib.exe')] + archiver = next((p for p in candidates if p and Path(p).is_file()), None) + if not archiver: + raise RuntimeError('COFF static acceptance requires llvm-lib.exe') + if not archiver and spec['object_format'] == 'macho': + archiver = shutil.which('llvm-ar', path=tools.env['PATH']) + if not archiver: + prefix = run(['brew', '--prefix', 'llvm@18'], root, tools.env, native_tool=True).stdout.strip() + archiver = str(Path(prefix) / 'bin/llvm-ar') + library = dict(output='static', mode='freestanding') + if spec['object_format'] in {'elf', 'macho'}: + library['relocation'] = 'pic' + manifest = dict(format=5, name='wave_static', targets=dict(lib=library)) + if archiver: + manifest['build'] = dict(archiver=archiver) + (project/'vex.ws').write_text(wson(manifest)+'\n', encoding='utf-8') + run([vex, 'fetch', '--offline'], project, tools.env) + for profile in ['dev', 'release']: + run([vex, 'build', '--profile', profile, '--locked', '--offline'], project, tools.env) + name = 'wave_static.lib' if tools.windows else 'libwave_static.a' + archive = project/'target'/spec['triple']/profile/'lib'/name + if archive.read_bytes()[:8] != b'!\n': + raise RuntimeError('static output is not a real archive') + consumer = root/('static '+profile+' consumer') + consumer.mkdir() + tools.consume(consumer, archive) + cpp = consumer/'cpp.cpp' + cpp.write_text('extern "C" int wave_add(int,int); int main(){return wave_add(20,22)==42?0:1;}\n', encoding='utf-8') + exe = consumer/('cpp.exe' if tools.windows else 'cpp') + if tools.windows: + run([tools.cxx, '/nologo', '/MD', cpp, archive, '/Fe'+str(exe)], consumer, tools.env) + else: + run([tools.cxx, cpp, archive, '-o', exe], consumer, tools.env, native_tool=True) + run([exe], consumer, tools.env) + rust = consumer/'caller.rs' + rust.write_text('unsafe extern "C" { fn wave_add(a:i32,b:i32)->i32; } fn main(){assert_eq!(unsafe{wave_add(20,22)},42);}\n', encoding='utf-8') + exe = consumer/('rust.exe' if tools.windows else 'rust') + run([tools.rustc, '--edition=2021', rust, '-C', 'link-arg='+str(archive), '-o', exe], consumer, tools.env, native_tool=True) + run([exe], consumer, tools.env) + + def archive_order(vex, root, tools): """A name/path mix must preserve the manifest's static-library order.""" project = root / "library order" @@ -383,6 +438,7 @@ def main(): archive_order(vex, root, tools) outbound(vex, root, tools, spec) format_three_exports(vex, root, tools, spec) + static_exports(vex, root, tools, spec) print("Native C/C++/Rust inputs and legacy/format 3 Wave object/shared consumers passed.", flush=True) diff --git a/tests/package_identity.rs b/tests/package_identity.rs index 000f3a8..8f248d3 100644 --- a/tests/package_identity.rs +++ b/tests/package_identity.rs @@ -108,7 +108,7 @@ fn compatible_transitive_requirements_share_an_alias_and_mismatch_preserves_lock assert_eq!(fs::read(app.join("vex.lock")).unwrap(), old); } #[test] -fn scoped_alias_conflicts_explain_compiler_limit_before_publication() { +fn conflicting_transitive_names_are_locked_as_package_scoped_bindings() { let f = Fixture::new(); f.package("one", "math", "1.0.0", ""); f.package("two", "math", "2.0.0", ""); @@ -121,13 +121,19 @@ fn scoped_alias_conflicts_explain_compiler_limit_before_publication() { "{name=\"left\",path=\"../left\"},{name=\"right\",path=\"../right\"}", ); let out = f.vex(&app, &["fetch"]); - assert_eq!(out.status.code(), Some(3)); - let error = String::from_utf8_lossy(&out.stderr); assert!( - error.contains("scoped compiler dependency mappings"), - "{error}" + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) ); - assert!(!app.join("vex.lock").exists()); + let lock = lockfile::decode(&fs::read_to_string(app.join("vex.lock")).unwrap()).unwrap(); + let math = lock + .packages + .iter() + .filter(|p| p.package_name() == "math") + .collect::>(); + assert_eq!(math.len(), 2); + assert_ne!(math[0].id, math[1].id); } #[test] fn locked_legacy_file_is_never_silently_migrated() { diff --git a/tests/package_targets.rs b/tests/package_targets.rs index acc39eb..dbc19ca 100644 --- a/tests/package_targets.rs +++ b/tests/package_targets.rs @@ -164,7 +164,7 @@ fn default_build_plans_library_then_sorted_binaries_once_without_mutation() { let before = snapshot(&f.app); let output = plan(&f.run(&["build", "--dry-run", "--locked", "--offline"])); assert_eq!(output["schema"], "vex.build-plan"); - assert_eq!(output["schema_version"], 1); + assert_eq!(output["schema_version"], 2); assert_eq!(output["target"], triple()); assert_eq!(output["profile"], json!({"name":"dev","opt_level":0})); assert_eq!( diff --git a/tests/project_state.rs b/tests/project_state.rs index 2ea39b5..c3c8532 100644 --- a/tests/project_state.rs +++ b/tests/project_state.rs @@ -718,3 +718,36 @@ fn conflict_reports_both_dependency_paths_as_structured_context() { assert!(!diagnostic["causes"].as_array().unwrap().is_empty()); assert_eq!(fs::read(fixture.root.join("vex.lock")).unwrap(), lock); } + +#[cfg(unix)] +#[test] +fn aliased_os_state_root_keeps_one_physical_coordination_tree() { + use std::os::unix::fs::symlink; + let f = Fixture::new(); + let home = f.root.join("physical-home"); + let alias = f.root.join("home-alias"); + fs::create_dir(&home).unwrap(); + symlink(&home, &alias).unwrap(); + let fetch = |selected: &std::path::Path| { + f.command(&["fetch", "--offline"]) + .env_remove("XDG_STATE_HOME") + .env("HOME", selected) + .output() + .unwrap() + }; + for selected in [&alias, &home] { + let output = fetch(selected); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + } + let state = home.join(".local/state"); + assert_eq!(fs::read_dir(state.join("vex/projects")).unwrap().count(), 1); + fs::rename(state.join("vex"), state.join("moved-vex")).unwrap(); + symlink(state.join("moved-vex"), state.join("vex")).unwrap(); + let rejected = fetch(&alias); + assert!(!rejected.status.success()); + assert!(String::from_utf8_lossy(&rejected.stderr).contains("symbolic link")); +} diff --git a/tests/target_metadata.rs b/tests/target_metadata.rs index 59e6d11..a4235ca 100644 --- a/tests/target_metadata.rs +++ b/tests/target_metadata.rs @@ -222,7 +222,7 @@ fn format_version_options_fail_before_project_discovery() { let f = Fixture::new(); for args in [ vec!["metadata", "--format-version"], - vec!["metadata", "--format-version", "3"], + vec!["metadata", "--format-version", "4"], vec!["metadata", "--format-version=0"], vec!["metadata", "--format-version", "2", "--format-version=2"], ] { diff --git a/tests/tooling/test_ci_cross.py b/tests/tooling/test_ci_cross.py index a16646c..96ef764 100644 --- a/tests/tooling/test_ci_cross.py +++ b/tests/tooling/test_ci_cross.py @@ -58,7 +58,7 @@ def test_cross_report_cannot_claim_native_build_or_another_runtime(self): row = dict(id='linux-riscv64', rust_target='riscv64gc-unknown-linux-gnu', executor='qemu', arch='riscv64') pin = dict(version='fixture', archives={row['id']: 'd'*64}) - report = dict(schema_version=1, executor='qemu', os='Linux', + report = dict(schema_version=1, executor='qemu', os='Linux', native_interop=sorted(repository_checks.NATIVE_INTEROP), source='a'*40, platform=row['id'], rust_target=row['rust_target'], status='passed', wave_version='fixture', compiler_sha256='b'*64, wave_archive_digest='sha256:'+'d'*64, build_method='cross', build_host='x86_64-unknown-linux-gnu', execution_arch='riscv64', diff --git a/tests/tooling/test_ci_github_api.py b/tests/tooling/test_ci_github_api.py new file mode 100644 index 0000000..b918008 --- /dev/null +++ b/tests/tooling/test_ci_github_api.py @@ -0,0 +1,84 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 +import base64 +import io +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest +from unittest.mock import patch +import urllib.error +from tools import ci_github_api as api + + +def encoded(status, body): + return dict(status=status, body=base64.b64encode(body).decode()) + + +class CompilerApiTransportTests(unittest.TestCase): + def test_host_authenticates_without_persisting_credentials_and_preserves_404(self): + url = api.API + 'attestations/sha256:' + 'a'*64 + failure = urllib.error.HTTPError(url, 404, 'Not Found', {}, io.BytesIO(b'{"message":"Not Found"}')) + with patch.object(api.urllib.request, 'urlopen', side_effect=failure) as request: + result = api.query(url, 'host-secret') + self.assertEqual(request.call_args.args[0].get_header('Authorization'), 'Bearer host-secret') + self.assertEqual(result, encoded(404, b'{"message":"Not Found"}')) + self.assertNotIn('host-secret', json.dumps(result)) + for status in [401, 403, 429, 500]: + failure = urllib.error.HTTPError(url, status, 'Denied', {}, io.BytesIO(b'denied')) + with patch.object(api.urllib.request, 'urlopen', side_effect=failure): + with self.assertRaisesRegex(RuntimeError, f'HTTP {status}'): + api.query(url, 'host-secret') + with patch.object(api.urllib.request, 'urlopen', side_effect=OSError('connection closed')): + with self.assertRaises(OSError): api.query(url, 'host-secret') + + def test_snapshots_are_limited_to_pinned_release_digest_and_required_commit(self): + release = b'{"tag_name":"v0.2.1-pre-beta","draft":false}' + for response, commit_expected in [(encoded(404, b'{}'), False), + (encoded(200, b'{"attestations":[]}'), False), + (encoded(200, b'{"attestations":[{"bundle":{}}]}'), True)]: + replies = [response, encoded(200, b'{"sha":"source"}')] + with patch.object(api, 'query', side_effect=replies) as query: + records = api.snapshots('0.2.1-pre-beta', 'a'*64, release, 'host-secret') + self.assertEqual(len(records), 3 if commit_expected else 2) + self.assertEqual(query.call_args_list[0].args, (api.API+'attestations/sha256:'+'a'*64, 'host-secret')) + self.assertEqual(records[api.API+'releases/tags/v0.2.1-pre-beta'], encoded(200, release)) + if commit_expected: + self.assertEqual(query.call_args_list[1].args, (api.API+'commits/v0.2.1-pre-beta', 'host-secret')) + with self.assertRaises(ValueError): api.snapshots('../other', 'a'*64, release, None) + with self.assertRaises(ValueError): api.snapshots('0.2.1-pre-beta', '../other', release, None) + + def test_shim_replays_exact_public_status_and_rejects_unknown_api_requests(self): + with tempfile.TemporaryDirectory() as temporary: + directory = Path(temporary)/'transport space' + records = {api.API+'release': encoded(200, b'{"release":true}'), + api.API+'attestations': encoded(404, b'{"message":"Not Found"}')} + api.write_curl(directory, records) + command = ([str(directory/'curl')] if sys.platform.startswith('linux') else + [sys.executable, api.__file__, 'curl', str(directory/'responses.json')]) + for endpoint, response in records.items(): + result = subprocess.run([*command, '--write-out', '\n%{http_code}', endpoint], capture_output=True) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout, base64.b64decode(response['body']) + b'\n' + str(response['status']).encode()) + result = subprocess.run([*command, '--write-out', '\n%{http_code}', api.API+'unexpected'], capture_output=True) + self.assertNotEqual(result.returncode, 0) + self.assertIn(b'no anonymous fallback', result.stderr) + + def test_archive_curl_retains_https_arguments_and_receives_no_authentication(self): + arguments = ['--proto', '=https', '--proto-redir', '=https', '--output', '/shared/archive', + 'https://github.com/wavefnd/Wave/releases/download/v0.2.1-pre-beta/archive.tar.gz'] + with patch.dict(os.environ, GH_TOKEN='secret', GITHUB_TOKEN='secret'): + with patch.object(api.os, 'execv') as execute: + api.curl('/not-read-for-archive', arguments) + self.assertNotIn('GH_TOKEN', os.environ) + self.assertNotIn('GITHUB_TOKEN', os.environ) + execute.assert_called_once_with('/usr/bin/curl', ['/usr/bin/curl', *arguments]) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/tooling/test_ci_platform.py b/tests/tooling/test_ci_platform.py index 2cb7b4d..25cc815 100644 --- a/tests/tooling/test_ci_platform.py +++ b/tests/tooling/test_ci_platform.py @@ -46,11 +46,22 @@ def guest_run(configuration, command, env=None, cwd=None): self.assertNotIn('GITHUB_TOKEN', env) if len(command) > 1 and command[0] != 'meson' and command[1] == 'setup': home = Path(env['VEX_TOOLCHAIN_HOME']) + self.assertIn('VEX_TEST_GUEST_PATH', env) + self.assertTrue((home/'api-transport/curl').is_file()) + snapshots = (home/'api-transport/responses.json').read_text() + self.assertNotIn('host-api-secret', snapshots) + self.assertNotIn('never-forward', snapshots) (home/'current').write_text('wavec') (home/'wavec').write_bytes(b'compiler fixture') release = dict(draft=False, tag_name='v'+ci.WAVE_VERSION, id=1, assets=[dict(id=2, name=f'wave-v{ci.WAVE_VERSION}-{target["wave_target"]}.tar.gz')]) + def public_response(request, timeout): + body = release if '/releases/' in request.full_url else {'attestations': []} + response = io.BytesIO(json.dumps(body).encode()) + response.status = 200 + return response + with tempfile.TemporaryDirectory() as temporary: root = Path(temporary) (root/'dist').mkdir() @@ -63,7 +74,7 @@ def guest_run(configuration, command, env=None, cwd=None): patch.object(ci.ci_cross, 'check_elf') as check_elf, patch.object(ci.ci_cross, 'execution_identity', return_value=dict(os='QEMU Linux', libc=['glibc', '2.41'], machine='riscv64')), patch.object(ci.ci_cross, 'run_target', side_effect=guest_run), - patch.object(ci.urllib.request, 'urlopen', return_value=io.BytesIO(json.dumps(release).encode())) as request): + patch.object(ci.urllib.request, 'urlopen', side_effect=public_response) as request): ci.main() setup = next(args for args, _ in native if args[:2] == ('meson', 'setup')) self.assertIn('-Dcargo=cargo', setup) @@ -80,6 +91,9 @@ def guest_run(configuration, command, env=None, cwd=None): self.assertEqual(Path(interop['VEX_TEST_TARGET_RUNNER']), Path('/cross/tools')/'runner') self.assertTrue(any(command[:2] == ('meson', 'test') and 'tooling' in command for command, _ in guest)) self.assertTrue(any(command[:2] == ('meson', 'compile') and command[-1] == 'package' for command, _ in guest)) + for command, environment in guest: + if environment and not (len(command) > 1 and command[1] == 'setup'): + self.assertNotIn('VEX_TEST_GUEST_PATH', environment) for script in ['tools/cli_reference.py', 'tests/wave_compatibility.py']: self.assertTrue(any(len(command) > 1 and command[1] == script for command, _ in guest)) self.assertFalse(any(command[0] in ['cargo', 'rustc'] for command, _ in guest)) diff --git a/tests/tooling/test_meson.py b/tests/tooling/test_meson.py index 56a3667..60d1b1e 100644 --- a/tests/tooling/test_meson.py +++ b/tests/tooling/test_meson.py @@ -130,6 +130,7 @@ def test_successful_check_runs_the_complete_ordered_suite(self): self.run_meson('compile', '-C', 'build', 'check') self.assertTrue((self.root / 'tooling-marker').is_file()) self.assertEqual([call['args'][0] for call in self.calls()], ['fmt', 'test', 'clippy', 'build']) + self.assertIn('--no-fail-fast', self.calls()[1]['args']) for call in self.calls()[1:]: self.assertIn('--workspace', call['args']) self.assertIn('--locked', call['args']) diff --git a/tests/tooling/test_repository_contracts.py b/tests/tooling/test_repository_contracts.py index 34e6e24..ac31d11 100644 --- a/tests/tooling/test_repository_contracts.py +++ b/tests/tooling/test_repository_contracts.py @@ -26,7 +26,7 @@ def test_acceptance_rejects_missing_failed_and_wrong_commit_evidence(self): with self.assertRaises(FileNotFoundError): repository_checks.acceptance(directory, 'a'*40, [row], pin) report = dict(schema_version=1, executor='native', os='fixture-os', wave_archive_digest='sha256:'+'d'*64, status='passed', source='a'*40, platform='fixture', rust_target='fixture-target', - wave_version='0.2.1-pre-beta', compiler_sha256='b'*64) + wave_version='0.2.1-pre-beta', compiler_sha256='b'*64, native_interop=sorted(repository_checks.NATIVE_INTEROP)) path = directory/'acceptance-fixture.json' path.write_text(json.dumps(report)) repository_checks.acceptance(directory, 'a'*40, [row], pin) @@ -75,7 +75,7 @@ def test_installer_verification_failures_preserve_existing_binary(self): release = dict(draft=False, tag_name='v0.0.2-beta', assets=[ dict(name=name, browser_download_url='https://github.com/wavefnd/Vex/releases/download/v0.0.2-beta/'+name) for name in [archive_name, 'SHA256SUMS']]) - for failure in ['checksum', 'provenance', 'version', 'replace', 'success']: + for failure in ['checksum', 'provenance', 'version', 'replace', 'attestation-timeout', 'version-timeout', 'success']: def download(url, output=None): if output: output.write_bytes(data) @@ -92,14 +92,57 @@ def download(url, output=None): stack.enter_context(patch.object(install, 'host', return_value=target)) stack.enter_context(patch.object(install.shutil, 'which', return_value='/fixture/gh')) stack.enter_context(patch.object(install, 'download', side_effect=download)) - attest = stack.enter_context(patch.object(install.subprocess, 'run', side_effect=subprocess.CalledProcessError(1, 'gh') if failure == 'provenance' else None)) - stack.enter_context(patch.object(install.subprocess, 'check_output', return_value='vex '+('0.0.1' if failure == 'version' else '0.0.2-beta'))) + attest = stack.enter_context(patch.object(install.subprocess, 'run', side_effect=(subprocess.CalledProcessError(1, 'gh') if failure == 'provenance' else subprocess.TimeoutExpired('gh attestation verify', 120) if failure == 'attestation-timeout' else None))) + stack.enter_context(patch.object(install.subprocess, 'check_output', side_effect=subprocess.TimeoutExpired('vex --version', 15) if failure == 'version-timeout' else None, return_value='vex '+('0.0.1' if failure == 'version' else '0.0.2-beta'))) if failure == 'replace': stack.enter_context(patch.object(install.os, 'replace', side_effect=OSError('replace failed'))) if failure == 'success': install.main() self.assertEqual(destination.read_bytes(), b'vex') self.assertIn('--source-digest', attest.call_args[0][0]) else: - with self.assertRaises((ValueError, OSError, subprocess.CalledProcessError)): install.main() + with self.assertRaises((ValueError, OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired)): install.main() self.assertEqual(destination.read_bytes(), b'previous release') self.assertEqual(list(destination.parent.glob('.vex-install-*')), []) + + def test_installer_host_aliases(self): + for system, machine, expected in [('FreeBSD','amd64','freebsd-amd64'), ('Windows','AMD64','windows-amd64'), ('Darwin','arm64','macos-arm64')]: + with self.subTest(system=system), patch.object(install.platform,'system',return_value=system), patch.object(install.platform,'machine',return_value=machine): + self.assertEqual(install.host()['id'],expected) + with patch.object(install.platform,'machine',return_value='unknown'): + with self.assertRaises(ValueError): install.host() + + def test_malformed_install_metadata_is_a_controlled_error(self): + for value in [[], {}, {'draft':False,'tag_name':'v0.0.2-beta'}, {'draft':False,'tag_name':'v0.0.2-beta','assets':{}}, {'draft':False,'tag_name':'v0.0.2-beta','assets':[None]}]: + with self.subTest(value=value), patch('sys.argv',['install.py','--version','0.0.2-beta']), patch.object(install,'host',return_value=dict(rust_target='fixture',archive='tar.gz')), patch.object(install.shutil,'which',return_value='gh'), patch.object(install,'download',return_value=json.dumps(value).encode()): + with self.assertRaises(ValueError): install.main() + for value in [None, [], {}, {'object':None}, {'object':{'type':'commit','sha':'invalid'}}]: + with self.subTest(tag=value), self.assertRaises(ValueError): install.tag_object(value) + + def test_native_evidence_requires_complete_unique_string_members(self): + row=dict(id='fixture',rust_target='fixture-target',executor='native') + pin=dict(version='0.2.1-pre-beta',archives={'fixture':'d'*64}) + report=dict(schema_version=1,executor='native',os='fixture',wave_archive_digest='sha256:'+'d'*64,status='passed',source='a'*40,platform='fixture',rust_target='fixture-target',wave_version=pin['version'],compiler_sha256='b'*64) + with tempfile.TemporaryDirectory() as temporary: + directory=Path(temporary) + for value in [None, 'c', ['c'], [None], sorted(repository_checks.NATIVE_INTEROP)+['c'], sorted(repository_checks.NATIVE_INTEROP)]: + (directory/'acceptance-fixture.json').write_text(json.dumps(dict(report,native_interop=value)),encoding='utf-8') + if value == sorted(repository_checks.NATIVE_INTEROP): repository_checks.acceptance(directory,'a'*40,[row],pin) + else: + with self.assertRaises(ValueError): repository_checks.acceptance(directory,'a'*40,[row],pin) + + def test_smoke_helpers_decode_utf8_even_under_legacy_locale(self): + import importlib.util + import sys + import io + import contextlib + for name in ['native_interop','wave_compatibility']: + spec=importlib.util.spec_from_file_location(name,Path(__file__).resolve().parents[1]/(name+'.py')) + module=importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + raw = io.BytesIO() + output = io.TextIOWrapper(raw, encoding='cp1252') + with contextlib.redirect_stdout(output), patch('subprocess._text_encoding',return_value='cp1252'): + result=module.run([sys.executable,'-c',"import sys;sys.stdout.buffer.write(bytes.fromhex('eab081'))"],Path.cwd(),{}) + output.flush() + self.assertIn('각', raw.getvalue().decode('utf-8')) + self.assertEqual(result.stdout,'각') diff --git a/tests/wave_compatibility.py b/tests/wave_compatibility.py index d90276a..99d42f8 100644 --- a/tests/wave_compatibility.py +++ b/tests/wave_compatibility.py @@ -11,11 +11,17 @@ import os from pathlib import Path import subprocess +import sys import tempfile def run(command, cwd, env, *, succeeds=True): - result = subprocess.run(command, cwd=cwd, env=env, text=True, capture_output=True) + # CI may redirect stdout through a legacy Windows code page. Keep both + # decoding and replayed diagnostic bytes UTF-8. + for stream in (sys.stdout, sys.stderr): + if hasattr(stream, 'reconfigure'): + stream.reconfigure(encoding='utf-8') + result = subprocess.run(command, cwd=cwd, env=env, text=True, encoding="utf-8", capture_output=True) print(f"$ {' '.join(map(str, command))}", flush=True) print(result.stdout, end="", flush=True) print(result.stderr, end="", flush=True) @@ -63,7 +69,7 @@ def snapshot(): planned = run([vex, "build", "--profile", "fast", "--dry-run", "--locked", "--offline"], app, env) envelope = json.loads(planned.stdout) plans = envelope.get("plans", []) - if (envelope.get("schema") != "vex.build-plan" or envelope.get("schema_version") != 1 + if (envelope.get("schema") != "vex.build-plan" or envelope.get("schema_version") != 2 or envelope.get("target") != host_target or envelope.get("profile") != {"name": "fast", "opt_level": 3} or [item["package_target"] for item in plans] != [ @@ -273,7 +279,7 @@ def main(): for command in ("build", "check", "run"): result = run([vex, command, "--dry-run", "--locked", "--offline"], nested, env) plan = json.loads(result.stdout) - if plan["schema_version"] != 1 or plan["target"] not in targets: + if plan["schema_version"] != 2 or plan["target"] not in targets: raise RuntimeError("compiler plan disagrees with capabilities") if command == "build": host_target = plan["target"] @@ -340,10 +346,10 @@ def main(): raise RuntimeError("run did not report its artifact and executable") if events[-1]["origin"] != "program" or events[-1]["exit_code"] != 0: raise RuntimeError("runtime outcome was not preserved") - metadata = run([vex, "metadata", "--locked", "--offline"], nested, env) + metadata = run([vex, "metadata", "--format-version", "3", "--locked", "--offline"], nested, env) graph = json.loads(metadata.stdout) - repeated = run([vex, "--manifest-path", str(app / "vex.ws"), "metadata"], root, env) - if metadata.stdout != repeated.stdout or graph["schema_version"] != 1: + repeated = run([vex, "--manifest-path", str(app / "vex.ws"), "metadata", "--format-version", "3"], root, env) + if metadata.stdout != repeated.stdout or graph["schema_version"] != 3: raise RuntimeError("metadata changed with project-selection method") if graph["root"]["dependencies"] != ["middle"] or [p["name"] for p in graph["packages"]] != ["leaf", "middle"]: raise RuntimeError("metadata omitted the transitive graph") diff --git a/toolchain/Cargo.toml b/toolchain/Cargo.toml index b0ccdca..fa0d4f7 100644 --- a/toolchain/Cargo.toml +++ b/toolchain/Cargo.toml @@ -19,4 +19,4 @@ process.workspace = true semver = "1" sha2 = "0.11.1" tar = "0.4" -zip = { version = "9", default-features = false, features = ["deflate"] } +zip = { version = "9.0.5", default-features = false, features = ["deflate"] } diff --git a/toolchain/src/artifact.rs b/toolchain/src/artifact.rs index e12dbf8..39a7d7d 100644 --- a/toolchain/src/artifact.rs +++ b/toolchain/src/artifact.rs @@ -12,7 +12,7 @@ use std::fs::{self, File, OpenOptions}; use std::io::{Read, Write}; use std::path::{Component, Path, PathBuf}; use std::process::Command; -use std::time::Duration; +use std::time::{Duration, Instant}; const REPOSITORY: &str = "https://api.github.com/repos/wavefnd/Wave/releases"; const DOWNLOAD: &str = "https://github.com/wavefnd/Wave/releases/download/"; @@ -117,23 +117,57 @@ fn get(url: &str) -> Result, String> { Ok(output.stdout) } fn download(url: &str, path: &Path) -> Result<(), String> { - let output = process::output( - curl(url) - .args(["--max-filesize", &MAX_ARCHIVE.to_string(), "--output"]) - .arg(path), + transfer_archive( + &mut archive_command(url, path), + path, Duration::from_secs(310), ) - .map_err(error)?; - if !output.status.success() { - return Err(error(format!( - "archive download failed: {}", - String::from_utf8_lossy(&output.stderr) - ))); - } - if fs::metadata(path).map_err(error)?.len() > MAX_ARCHIVE { - return Err(error("archive exceeds 512 MiB")); +} + +fn archive_command(url: &str, path: &Path) -> Command { + let mut command = curl(url); + command + .args(["--max-filesize", &MAX_ARCHIVE.to_string(), "--output"]) + .arg(path); + command +} + +fn transfer_archive(command: &mut Command, path: &Path, budget: Duration) -> Result<(), String> { + let started = Instant::now(); + for attempt in 0..3 { + if attempt > 0 { + // Each attempt starts from zero; never append to or resume a partial + // archive. This path is private to the unpublished install stage. + match fs::remove_file(path) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(error(e)), + } + } + let output = + process::output(command, budget.saturating_sub(started.elapsed())).map_err(error)?; + if output.status.success() { + if fs::metadata(path).map_err(error)?.len() > MAX_ARCHIVE { + return Err(error("archive exceeds 512 MiB")); + } + return Ok(()); + } + // Retry transport failures only (including TLS receive EOF, curl 56). + // HTTP rejection, certificate errors, local I/O and integrity failures + // are not retried. Supervisor cancellation/timeout errors return above. + let transient = matches!( + output.status.code(), + Some(5 | 6 | 7 | 18 | 28 | 52 | 55 | 56) + ); + if !transient || attempt == 2 { + return Err(error(format!( + "archive download failed after {} attempt(s): {}", + attempt + 1, + String::from_utf8_lossy(&output.stderr) + ))); + } } - Ok(()) + unreachable!("the final failed transfer returns its error") } #[derive(Debug)] @@ -758,6 +792,147 @@ mod tests { } } + fn with_http_server( + responses: Vec<&'static [u8]>, + run: impl FnOnce(&str) -> T, + ) -> (T, usize) { + use std::net::TcpListener; + use std::sync::mpsc::{channel, TryRecvError}; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://{}/archive", listener.local_addr().unwrap()); + listener.set_nonblocking(true).unwrap(); + let (stop, stopped) = channel::<()>(); + let server = std::thread::spawn(move || { + let deadline = Instant::now() + Duration::from_secs(30); + let mut requests = 0; + while matches!(stopped.try_recv(), Err(TryRecvError::Empty)) { + assert!(Instant::now() < deadline, "download test server timed out"); + match listener.accept() { + Ok((mut stream, _)) => { + // Windows inherits the listener's nonblocking mode. + // The accepted connection uses blocking I/O with deadlines. + stream.set_nonblocking(false).unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + stream + .set_write_timeout(Some(Duration::from_secs(5))) + .unwrap(); + let mut request = Vec::new(); + let mut byte = [0]; + while !request.ends_with(b"\r\n\r\n") { + assert!(request.len() < 16384); + stream.read_exact(&mut byte).unwrap(); + request.push(byte[0]); + } + let response = responses[requests.min(responses.len() - 1)]; + requests += 1; + stream.write_all(response).unwrap(); + } + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { + std::thread::sleep(Duration::from_millis(5)); + } + Err(e) => panic!("test server: {e}"), + } + } + requests + }); + let result = run(&url); + drop(stop); + (result, server.join().unwrap()) + } + + fn local_archive_command(url: &str, path: &Path) -> Command { + let mut command = archive_command(url, path); + // Only this loopback fixture permits HTTP; production remains HTTPS-only. + command.args([ + "--proto", + "=http", + "--proto-redir", + "=http", + "--noproxy", + "*", + ]); + command + } + + const PARTIAL_ARCHIVE: &[u8] = b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\nConnection: close\r\n\r\npartial response longer than final archive"; + const COMPLETE_ARCHIVE: &[u8] = + b"HTTP/1.1 200 OK\r\nContent-Length: 7\r\nConnection: close\r\n\r\narchive"; + + #[test] + fn download_test_server_waits_for_delayed_request_headers() { + use std::net::TcpStream; + let (response, requests) = with_http_server(vec![COMPLETE_ARCHIVE], |url| { + let address = url + .strip_prefix("http://") + .unwrap() + .strip_suffix("/archive") + .unwrap(); + let mut client = TcpStream::connect(address).unwrap(); + client + .set_read_timeout(Some(Duration::from_secs(5))) + .unwrap(); + // Accept the connection before sending any bytes, then split the + // header terminator to exercise waits after both accept and read. + std::thread::sleep(Duration::from_millis(100)); + client + .write_all(b"GET /archive HTTP/1.1\r\nHost: localhost\r\n") + .unwrap(); + std::thread::sleep(Duration::from_millis(20)); + client.write_all(b"\r\n").unwrap(); + let mut response = Vec::new(); + client.read_to_end(&mut response).unwrap(); + response + }); + assert_eq!(response, COMPLETE_ARCHIVE); + assert_eq!(requests, 1); + } + + #[test] + fn interrupted_archive_download_restarts_without_partial_bytes() { + let fixture = Fixture::new(); + let path = fixture.0.join("download"); + let (result, requests) = with_http_server( + vec![PARTIAL_ARCHIVE, PARTIAL_ARCHIVE, COMPLETE_ARCHIVE], + |url| { + transfer_archive( + &mut local_archive_command(url, &path), + &path, + Duration::from_secs(20), + ) + }, + ); + result.unwrap(); + assert_eq!(requests, 3); + assert_eq!(fs::read(&path).unwrap(), b"archive"); + verify_checksum(&path, &hex_digest(Sha256::digest(b"archive"))).unwrap(); + assert!(verify_checksum(&path, &"0".repeat(64)).is_err()); + } + + #[test] + fn archive_transport_retries_are_bounded_and_http_errors_are_not_retried() { + for (response, expected_requests) in [ + (PARTIAL_ARCHIVE, 3), + ( + &b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"[..], + 1, + ), + ] { + let fixture = Fixture::new(); + let path = fixture.0.join("download"); + let (result, requests) = with_http_server(vec![response], |url| { + transfer_archive( + &mut local_archive_command(url, &path), + &path, + Duration::from_secs(20), + ) + }); + assert!(result.unwrap_err().contains("archive download failed")); + assert_eq!(requests, expected_requests); + } + } + #[test] fn authenticated_api_preserves_http_errors_instead_of_treating_them_as_absence() { for status in [200, 403, 404, 500] { diff --git a/tools/ci_github_api.py b/tools/ci_github_api.py new file mode 100644 index 0000000..747f550 --- /dev/null +++ b/tools/ci_github_api.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 +"""Keep authenticated compiler API queries on the cross-build host.""" +import base64 +import json +import os +from pathlib import Path +import sys +import urllib.error +import urllib.request + +API = 'https://api.github.com/repos/wavefnd/Wave/' +LIMIT = 8 * 1024 * 1024 + + +def query(url, token): + """Return a public API response, preserving an authoritative 404.""" + if not url.startswith(API): + raise ValueError('unexpected compiler API endpoint') + headers = {'User-Agent': 'Vex-release-acceptance'} + if token: + headers['Authorization'] = 'Bearer ' + token + request = urllib.request.Request(url, headers=headers) + try: + with urllib.request.urlopen(request, timeout=60) as response: + status, body = response.status, response.read(LIMIT + 1) + except urllib.error.HTTPError as error: + try: + if error.code != 404: + raise RuntimeError(f'compiler API query failed with HTTP {error.code}') from None + status, body = error.code, error.read(LIMIT + 1) + finally: + error.close() + if status not in (200, 404): + raise RuntimeError(f'compiler API query failed with HTTP {status}') + if len(body) > LIMIT: + raise RuntimeError('compiler API response exceeds 8 MiB') + return {'status': status, 'body': base64.b64encode(body).decode('ascii')} + + +def snapshots(version, digest, release_body, token): + """Fetch only the pinned installer's possible public API inputs.""" + if (not version or any(c not in '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-' for c in version) + or len(digest) != 64 or any(c not in '0123456789abcdef' for c in digest)): + raise ValueError('invalid pinned compiler identity') + release_url = API + 'releases/tags/v' + version + attestations_url = API + 'attestations/sha256:' + digest + responses = {release_url: {'status': 200, 'body': base64.b64encode(release_body).decode('ascii')}} + response = query(attestations_url, token) + responses[attestations_url] = response + if response['status'] == 200: + document = json.loads(base64.b64decode(response['body'])) + if not isinstance(document.get('attestations'), list): + raise ValueError('invalid provenance response') + if document['attestations']: + commit_url = API + 'commits/v' + version + commit = query(commit_url, token) + if commit['status'] != 200: + raise RuntimeError('release tag source commit is unavailable') + responses[commit_url] = commit + return responses + + +def write_curl(directory, responses): + directory = Path(directory) + directory.mkdir() + record = directory / 'responses.json' + record.write_text(json.dumps(responses), encoding='utf-8') + executable = directory / 'curl' + script = str(Path(__file__).resolve()) + executable.write_text('#!/usr/bin/python3\nimport os, sys\n' + 'os.execv("/usr/bin/python3", ["/usr/bin/python3", ' + + repr(script) + ', "curl", ' + repr(str(record)) + '] + sys.argv[1:])\n', encoding='utf-8') + executable.chmod(0o755) + return str(directory) + ':/usr/local/bin:/usr/bin:/bin' + + +def curl(record, arguments): + # The snapshot contains public response bodies only. No credential is needed + # by the guest, archive downloader, verifier, compiler or user program. + os.environ.pop('GH_TOKEN', None) + os.environ.pop('GITHUB_TOKEN', None) + urls = [arg for arg in arguments if arg.startswith(('http://', 'https://'))] + api_urls = [url for url in urls if url.startswith('https://api.github.com/')] + if api_urls: + responses = json.loads(Path(record).read_text(encoding='utf-8')) + if len(urls) != 1 or api_urls[0] not in responses: + raise ValueError('unexpected compiler API request; no anonymous fallback is permitted') + if '--output' in arguments or '--write-out' not in arguments: + raise ValueError('unexpected compiler API output mode') + index = arguments.index('--write-out') + if arguments[index + 1:index + 2] != ['\n%{http_code}']: + raise ValueError('unexpected compiler API output mode') + response = responses[api_urls[0]] + if response['status'] not in (200, 404): + raise ValueError('invalid public compiler API snapshot status') + sys.stdout.buffer.write(base64.b64decode(response['body'], validate=True)) + sys.stdout.buffer.write(('\n' + str(response['status'])).encode('ascii')) + return + # Archive/checksum transfers retain their original HTTPS, size and redirect + # restrictions and execute the real target curl in the target userspace. + os.execv('/usr/bin/curl', ['/usr/bin/curl', *arguments]) + + +if __name__ == '__main__': + try: + if len(sys.argv) < 4 or sys.argv[1] != 'curl': + raise ValueError('expected curl snapshot invocation') + curl(sys.argv[2], sys.argv[3:]) + except (ValueError, RuntimeError, OSError) as error: + print(str(error), file=sys.stderr) + sys.exit(1) diff --git a/tools/ci_platform.py b/tools/ci_platform.py index eac2a93..50b47a3 100644 --- a/tools/ci_platform.py +++ b/tools/ci_platform.py @@ -18,7 +18,8 @@ ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) -from tools import ci_cross +from tools import ci_cross, ci_github_api +from tools.repository_checks import NATIVE_INTEROP PLATFORMS = json.loads((ROOT / 'platforms.json').read_text())['platforms'] WAVE_PIN = json.loads((ROOT / 'tools/wave-release.json').read_text()) WAVE_VERSION = WAVE_PIN['version'] @@ -92,7 +93,8 @@ def execute(*command, env=None): request = urllib.request.Request(url, headers=headers) try: with urllib.request.urlopen(request, timeout=60) as response: - release = json.load(response) + release_body = response.read() + release = json.loads(release_body) except urllib.error.HTTPError as error: detail = error.read(4096).decode('utf-8', errors='replace') raise RuntimeError(f'cannot query official Wave v{WAVE_VERSION} (HTTP {error.code}): {detail}') from error @@ -106,6 +108,9 @@ def execute(*command, env=None): env = dict(os.environ, VEX_TOOLCHAIN_HOME=temporary, VEX_WAVEC_ARCHIVE_SHA256=WAVE_PIN['archives'][target['id']]) env.pop('VEX_WAVEC', None) setup_env = dict(env, GH_TOKEN=api_token) if api_token and not cross else env + if cross: + responses = ci_github_api.snapshots(WAVE_VERSION, WAVE_PIN['archives'][target['id']], release_body, api_token) + setup_env = dict(env, VEX_TEST_GUEST_PATH=ci_github_api.write_curl(Path(temporary)/'api-transport', responses)) execute(binary, 'setup', 'wavec', '--version', WAVE_VERSION, env=setup_env) compiler = Path(temporary) / (Path(temporary) / 'current').read_text().strip() if cross: @@ -123,7 +128,7 @@ def execute(*command, env=None): os=identity['os'], libc=identity['libc'], wave_version=WAVE_VERSION, wave_release_id=release['id'], wave_asset_id=assets[0]['id'], wave_archive_digest='sha256:'+WAVE_PIN['archives'][target['id']], compiler_sha256=compiler_hash, - native_interop=['c', 'cpp-c-abi', 'rust-c-abi', 'wave-object', 'wave-shared'], + native_interop=sorted(NATIVE_INTEROP), status='passed') if cross: report.update(build_method='cross', build_host=cross['build_host'], execution_arch=identity['machine'], diff --git a/tools/command-spec.json b/tools/command-spec.json index 1688f51..65c0f70 100644 --- a/tools/command-spec.json +++ b/tools/command-spec.json @@ -1,5 +1,5 @@ { - "globals": "[-q|--quiet] [-v|--verbose] [--message-file ] [--manifest-path ] [-p|--package |--workspace] [--features ] [--no-default-features] [--include-tests]", + "globals": "[-q|--quiet] [-v|--verbose] [--message-file ] [--manifest-path ] [-p|--package |--workspace] [--features ] [--no-default-features] [--include-tests] [--build-dir ] [--state-dir ]", "commands": [ { "name": "init", @@ -8,12 +8,12 @@ }, { "name": "build", - "usage": "build [--lib] [--bin ] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline]", + "usage": "build [--lib] [--bin ] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] [--artifact-manifest ] [--depfile ]", "description": "Compile selected package targets" }, { "name": "run", - "usage": "run [--bin ] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] [-- ]", + "usage": "run [--bin ] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] [--artifact-manifest ] [--depfile ] [-- ]", "description": "Compile and execute one binary" }, { @@ -23,7 +23,7 @@ }, { "name": "test", - "usage": "test [filter] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] [-- ]", + "usage": "test [filter] [--target ] [--profile |--release] [--dry-run] [--locked] [--offline] [--artifact-manifest ] [--depfile ] [-- ]", "description": "Compile and execute explicit main-based tests; run every selected test and return the first failure" }, { @@ -43,7 +43,7 @@ }, { "name": "metadata", - "usage": "metadata [--format=json] [--format-version <1|2>] [--locked] [--offline] [--target ]", + "usage": "metadata [--format=json] [--format-version <1|2|3>] [--locked] [--offline] [--target ]", "description": "Manage metadata" }, { @@ -100,6 +100,11 @@ "name": "manpage", "usage": "manpage", "description": "Print the vex(1) manual" + }, + { + "name": "toolchain", + "usage": "toolchain capture [--wavec ] [--std ] [--replace]", + "description": "Record a prepared host compiler/std pair by content identity; never downloads a toolchain." } ] } diff --git a/tools/install.py b/tools/install.py index 9650eb2..5837505 100644 --- a/tools/install.py +++ b/tools/install.py @@ -43,7 +43,7 @@ def download(url, output=None): def host(): os_name = {'Linux': 'linux', 'Darwin': 'macos', 'Windows': 'windows', 'FreeBSD': 'freebsd'}.get(platform.system()) - arch = {'AMD64': 'x86_64', 'arm64': 'aarch64', 'ARM64': 'aarch64'}.get(platform.machine(), platform.machine()) + arch = {'amd64': 'x86_64', 'AMD64': 'x86_64', 'arm64': 'aarch64', 'ARM64': 'aarch64'}.get(platform.machine(), platform.machine()) rows = json.loads((ROOT / 'platforms.json').read_text())['platforms'] found = [row for row in rows if row['os'] == os_name and row['arch'] == arch] if len(found) != 1: @@ -51,6 +51,15 @@ def host(): return found[0] +def tag_object(value): + obj = value.get('object') if isinstance(value, dict) else None + if (not isinstance(obj, dict) or obj.get('type') not in ('tag', 'commit') + or not isinstance(obj.get('sha'), str) or len(obj['sha']) != 40 + or any(c not in '0123456789abcdef' for c in obj['sha'])): + raise ValueError('malformed release tag object: expected type and commit/tag SHA') + return obj + + def payload(archive, root, executable): member = f'{root}/{executable}' if archive.suffix == '.zip': @@ -84,11 +93,15 @@ def main(): raise ValueError('GitHub CLI (gh) is required to verify release provenance') tag = 'v' + args.version release = json.loads(download(f'https://api.github.com/repos/{REPO}/releases/tags/{tag}')) + if not isinstance(release, dict): + raise ValueError('malformed release metadata: expected an object') if release.get('draft') is not False or release.get('tag_name') != tag: raise ValueError('release is draft or mismatched') root = f"vex-{tag}-{target['rust_target']}" archive_name = root + '.' + target['archive'] - assets = release['assets'] + assets = release.get('assets') + if not isinstance(assets, list) or any(not isinstance(a, dict) or not isinstance(a.get('name'), str) or not isinstance(a.get('browser_download_url'), str) for a in assets): + raise ValueError('malformed release metadata: assets must contain named asset objects with URLs') def asset(name): found = [a for a in assets if a['name'] == name] expected = f'https://github.com/{REPO}/releases/download/{tag}/{name}' @@ -115,33 +128,34 @@ def asset(name): raise ValueError('release archive checksum mismatch') # GitHub attestation includes the immutable source commit. Verify the # exact tag's commit, rather than trusting release target_commitish. - ref = json.loads(download(f'https://api.github.com/repos/{REPO}/git/ref/tags/{tag}'))['object'] + ref = tag_object(json.loads(download(f'https://api.github.com/repos/{REPO}/git/ref/tags/{tag}'))) for _ in range(8): if ref['type'] == 'commit': break if ref['type'] != 'tag': raise ValueError('release tag does not resolve to a commit') - ref = json.loads(download(f'https://api.github.com/repos/{REPO}/git/tags/{ref["sha"]}'))['object'] + ref = tag_object(json.loads(download(f'https://api.github.com/repos/{REPO}/git/tags/{ref["sha"]}'))) if ref['type'] != 'commit': raise ValueError('release tag nesting limit exceeded') - attestations = json.loads(download(f'https://api.github.com/repos/{REPO}/attestations/sha256:{digest}')).get('attestations') + provenance = json.loads(download(f'https://api.github.com/repos/{REPO}/attestations/sha256:{digest}')) + attestations = provenance.get('attestations') if isinstance(provenance, dict) else None if not isinstance(attestations, list) or not attestations: raise ValueError('release provenance is missing') bundle = Path(temporary)/'attestations.jsonl' with bundle.open('x') as output: for attestation in attestations: - if not isinstance(attestation.get('bundle'), dict): + if not isinstance(attestation, dict) or not isinstance(attestation.get('bundle'), dict): raise ValueError('invalid release provenance bundle') output.write(json.dumps(attestation['bundle'])+'\n') subprocess.run(['gh', 'attestation', 'verify', str(archive), '--bundle', str(bundle), '--repo', REPO, '--signer-workflow', REPO+'/.github/workflows/release.yml', '--source-ref', 'refs/heads/master', '--source-digest', ref['sha'], - '--signer-digest', ref['sha'], '--deny-self-hosted-runners'], check=True) + '--signer-digest', ref['sha'], '--deny-self-hosted-runners'], check=True, timeout=120) data = payload(archive, root, executable) candidate = Path(temporary) / executable candidate.write_bytes(data) candidate.chmod(0o755) - actual = subprocess.check_output([str(candidate), '--version'], text=True).strip() + actual = subprocess.check_output([str(candidate), '--version'], text=True, encoding='utf-8', timeout=15).strip() if actual != 'vex '+args.version: raise ValueError('binary version does not match requested release') destination.parent.mkdir(parents=True, exist_ok=True) @@ -170,5 +184,5 @@ def asset(name): if __name__ == '__main__': try: main() - except (OSError, ValueError, tarfile.TarError, zipfile.BadZipFile, subprocess.CalledProcessError) as error: + except (OSError, ValueError, tarfile.TarError, zipfile.BadZipFile, subprocess.CalledProcessError, subprocess.TimeoutExpired) as error: sys.exit(f'error: {error}') diff --git a/tools/meson_consumer.py b/tools/meson_consumer.py new file mode 100644 index 0000000..2906e58 --- /dev/null +++ b/tools/meson_consumer.py @@ -0,0 +1,232 @@ +#!/usr/bin/env python3 +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# SPDX-License-Identifier: MPL-2.0 +"""Copy one verified Vex library into a Meson-owned bridge without mtime churn.""" +import argparse +from contextlib import contextmanager +import hashlib +import json +import os +import signal +from pathlib import Path +import stat +import subprocess +import sys +import tempfile +import time + + +def path_form(path): + text = str(path) + if os.name == 'nt': + if text.startswith('\\\\?\\UNC\\'): + text = '\\\\' + text[8:] + elif text.startswith('\\\\?\\'): + text = text[4:] + text = os.path.normcase(text) + return Path(text) + + +def regular(path): + for parent in (path, *path.parents): + if parent.is_symlink() or (hasattr(parent, 'is_junction') and parent.is_junction()): + raise ValueError(f'consumer paths must not contain links: {parent}') + if not stat.S_ISREG(path.stat().st_mode): + raise ValueError(f'consumer input is not a regular file: {path}') + + +def digest(path): + regular(path) + with path.open('rb') as stream: + return hashlib.file_digest(stream, 'sha256').hexdigest() + + +def read_json(path): + regular(path) + with path.open('rb') as stream: + data = stream.read(8 * 1024 * 1024 + 1) + if len(data) > 8 * 1024 * 1024: + raise ValueError('consumer metadata exceeds 8 MiB') + return json.loads(data) + + +def sync_directory(path): + if os.name != 'nt': + fd = os.open(path, os.O_RDONLY) + try: + os.fsync(fd) + finally: + os.close(fd) + + +def atomic_bytes(path, data): + fd, temporary = tempfile.mkstemp(prefix='.vex-consumer-', dir=path.parent) + try: + with os.fdopen(fd, 'wb') as stream: + stream.write(data) + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, path) + sync_directory(path.parent) + finally: + if os.path.exists(temporary): + os.unlink(temporary) + + +@contextmanager +def generation_lease(build, generation): + """Use Vex's existing inode/Windows share lease, never an existence lock.""" + base = build / 'target/.vex-run' + if generation.parent != base or not generation.name or any(c not in '0123456789-' for c in generation.name): + raise ValueError('invalid artifact generation') + lock = build / '.vex/run-locks' / (generation.name + '.lock') + regular(lock) + if os.name == 'nt': + import ctypes + from ctypes import wintypes + kernel = ctypes.WinDLL('kernel32', use_last_error=True) + kernel.CreateFileW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, + wintypes.LPVOID, wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE] + kernel.CreateFileW.restype = wintypes.HANDLE + kernel.CloseHandle.argtypes = [wintypes.HANDLE] + deadline = time.monotonic() + 30 + while True: + handle = kernel.CreateFileW(str(lock), 0x80000000, 1, None, 3, 0x00200000, None) + if handle != wintypes.HANDLE(-1).value: + break + code = ctypes.get_last_error() + if code != 32 or time.monotonic() >= deadline: + raise OSError(code, 'cannot hold Vex generation lease') + time.sleep(.04) + try: + yield + finally: + kernel.CloseHandle(handle) + else: + import fcntl + fd = os.open(lock, os.O_RDONLY | os.O_NOFOLLOW) + try: + fcntl.flock(fd, fcntl.LOCK_SH) + yield + finally: + os.close(fd) + + +def escape(path): + text = str(path) + if any(c in text for c in '\r\n\0'): + raise ValueError('depfile cannot represent newlines or NUL') + return text.replace('\\', '\\\\').replace('$', '$$').replace(' ', '\\ ').replace('#', '\\#').replace(':', '\\:') + + +def publish_bridge(output, data, depfile, dependencies, rust_main=None, rust_source=None): + owner = output.with_name(output.name + '.vex-owner.json') + registry = read_json(owner) if owner.exists() else {'schema_version': 1, 'files': {}} + if registry.get('schema_version') != 1 or not isinstance(registry.get('files'), dict): + raise ValueError('invalid bridge ownership record') + files = [(output, data), (depfile, (escape(output) + ': ' + ' '.join(escape(p) for p in sorted(set(dependencies))) + '\n').encode())] + if rust_main: + source = str(rust_source.resolve()) + if any(ord(c) < 32 for c in source): + raise ValueError('Rust consumer source path contains control characters') + shim = '// Vex bridge sha256: ' + hashlib.sha256(data).hexdigest() + '\ninclude!(' + json.dumps(source, ensure_ascii=False) + ');\n' + files.append((rust_main, shim.encode('utf-8'))) + updated = {'schema_version': 1, 'files': {}} + for path, content in files: + current = digest(path) if path.exists() else None + allowed = registry['files'].get(str(path), []) + if not isinstance(allowed, list) or (current is not None and current not in allowed): + raise ValueError(f'refusing to overwrite unowned/modified bridge file: {path}') + new = hashlib.sha256(content).hexdigest() + updated['files'][str(path)] = [new] if current is None else sorted({current, new}) + # Record both recoverable states before atomic replacement. An interrupted + # copy can leave only a complete previously verified bridge, never a prefix. + atomic_bytes(owner, (json.dumps(updated, sort_keys=True) + '\n').encode()) + for path, content in files: + if not path.exists() or digest(path) != hashlib.sha256(content).hexdigest(): + atomic_bytes(path, content) + updated['files'] = {str(p): [hashlib.sha256(data).hexdigest()] for p, data in files} + atomic_bytes(owner, (json.dumps(updated, sort_keys=True) + '\n').encode()) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--vex', required=True) + parser.add_argument('--manifest', type=Path, required=True) + parser.add_argument('--build-dir', type=Path, required=True) + parser.add_argument('--state-dir', type=Path) + parser.add_argument('--output', type=Path, required=True) + parser.add_argument('--depfile', type=Path, required=True) + parser.add_argument('--rust-main', type=Path) + parser.add_argument('--rust-source', type=Path) + parser.add_argument('--kind', choices=['object', 'static'], required=True) + parser.add_argument('--profile', default='dev') + parser.add_argument('--target') + parser.add_argument('--features', action='append', default=[]) + args = parser.parse_args() + if bool(args.rust_main) != bool(args.rust_source): + parser.error("--rust-main and --rust-source must be provided together") + build = path_form(args.build_dir.resolve()) + report = build / 'consumer-result.json' + command = [args.vex, '--manifest-path', str(args.manifest.resolve()), '--build-dir', str(build)] + if args.state_dir: + command += ['--state-dir', str(args.state_dir.resolve())] + for feature in args.features: + command += ['--features', feature] + command += ['build', '--lib', '--locked', '--offline', '--profile', args.profile, + '--artifact-manifest', str(report), '--depfile', str(build / 'consumer-inputs.d')] + if args.target: + command += ['--target', args.target] + # Leave stdout/stderr and process cancellation connected to Meson/Ninja. + child = subprocess.Popen(command) + previous = {} + cancelled = False + def forward(signum, frame): + nonlocal cancelled + cancelled = True + if child.poll() is None: + child.send_signal(signum) + try: + for signum in (signal.SIGINT, signal.SIGTERM): + previous[signum] = signal.signal(signum, forward) + code = child.wait() + finally: + for signum, handler in previous.items(): + signal.signal(signum, handler) + if cancelled: + return 130 + if code: + return code if code > 0 else 128 - code + value = read_json(report) + if value.get('schema') != 'vex.artifacts' or value.get('schema_version') != 1 or len(value.get('results', [])) != 1: + raise ValueError('expected one version-1 artifact result') + result = value['results'][0] + if result.get('schema') != 'vex.artifact-generation' or result.get('schema_version') != 1 or result['metadata']['artifact_kind'] != args.kind: + raise ValueError('artifact result kind/schema differs from the declared Meson bridge') + generation = path_form(Path(result['generation'])) + with generation_lease(build, generation): + primary = [] + for artifact in result['artifacts']: + if '..' in Path(artifact['path']).parts: + raise ValueError('artifact result contains parent traversal') + path = path_form(Path(artifact['path'])) + if not path.is_relative_to(generation) or '..' in path.parts or digest(path) != artifact['sha256']: + raise ValueError('artifact escaped its generation or failed content verification') + if artifact['role'] == 'primary': + primary.append(path) + if len(primary) != 1: + raise ValueError('expected exactly one primary library') + inputs = result['metadata']['inputs'] + dependencies = inputs['files'] + inputs['directories'] + publish_bridge(args.output.absolute(), primary[0].read_bytes(), args.depfile.absolute(), dependencies, args.rust_main.absolute() if args.rust_main else None, args.rust_source) + return 0 + + +if __name__ == '__main__': + try: + raise SystemExit(main()) + except (OSError, ValueError, KeyError, TypeError) as error: + print(f'error: Vex Meson consumer: {error}', file=sys.stderr) + raise SystemExit(1) diff --git a/tools/repository_checks.py b/tools/repository_checks.py index 89fe442..c0317a3 100644 --- a/tools/repository_checks.py +++ b/tools/repository_checks.py @@ -10,6 +10,7 @@ import re ROOT = Path(__file__).resolve().parents[1] +NATIVE_INTEROP = frozenset({'c', 'cpp-c-abi', 'rust-c-abi', 'wave-object', 'wave-shared', 'wave-static'}) def validate(root=ROOT): @@ -61,6 +62,10 @@ def acceptance(directory, commit, rows, pin=None): or report.get('wave_version') != pin['version'] or not re.fullmatch('[0-9a-f]{64}', report.get('compiler_sha256', ''))): raise ValueError(f'invalid acceptance evidence for {row["id"]}') + coverage = report.get('native_interop') + if (not isinstance(coverage, list) or any(not isinstance(c, str) for c in coverage) + or len(coverage) != len(set(coverage)) or set(coverage) != NATIVE_INTEROP): + raise ValueError(f'invalid native interoperability evidence for {row["id"]}') if row['executor'] == 'qemu': if (report.get('build_method') != 'cross' or report.get('build_host') != 'x86_64-unknown-linux-gnu' diff --git a/wson/src/edit.rs b/wson/src/edit.rs index 85acb2f..68cf987 100644 --- a/wson/src/edit.rs +++ b/wson/src/edit.rs @@ -7,8 +7,8 @@ use super::*; use std::ops::Range; pub fn dependency(raw: &str, name: &str, addition: Option<&str>) -> Result { - let map = loads_versions(raw, "format", &[2, 3, 4])?; - let escapes = matches!(map.get("format"), Some(WsonValue::Int(2..=4))); + let map = loads_versions(raw, "format", &[2, 3, 4, 5])?; + let escapes = matches!(map.get("format"), Some(WsonValue::Int(2..=5))); let mut p = Parser { raw, pos: 0, @@ -91,24 +91,40 @@ pub fn dependency(raw: &str, name: &str, addition: Option<&str>) -> Result return Err(format!("direct dependency `{name}` already exists")), - (Some(text), None) => { + let found: Vec<_> = entries + .iter() + .enumerate() + .filter_map(|(i, (_, _, alias))| (alias == name).then_some(i)) + .collect(); + match addition { + Some(_) if !found.is_empty() => return Err(format!("direct dependency `{name}` already exists")), + Some(text) => { result.insert_str(p.pos, &format!("\n {text}\n ")); if let Some((range, None, _)) = entries.last() { result.insert(range.end, ','); } } - (None, Some(index)) => { - let (range, comma, _) = &entries[index]; - if let Some(comma) = comma { result.remove(*comma); } - result.replace_range(range.clone(), ""); - if comma.is_none() && index > 0 { - if let Some(comma) = entries[index-1].1 { result.remove(comma); } + None if !found.is_empty() => { + // Original byte coordinates remain valid when edits run backwards. + // Remove every conditional declaration, retaining comments outside + // the objects and all declarations of other aliases. + let mut removals = std::collections::BTreeSet::new(); + for index in found { + let (range, comma, _) = &entries[index]; + removals.insert((range.start, range.end)); + if let Some(comma) = comma { + removals.insert((*comma, comma + 1)); + } else if index > 0 { + if let Some(comma) = entries[index - 1].1 { + removals.insert((comma, comma + 1)); + } + } + } + for (start, end) in removals.into_iter().rev() { + result.replace_range(start..end, ""); } } - (None, None) => return Err(format!("unknown direct dependency `{name}`; transitive dependencies must be edited in their owning package")), + None => return Err(format!("unknown direct dependency `{name}`; transitive dependencies must be edited in their owning package")), } - loads_versions(&result, "format", &[2, 3, 4])?; + loads_versions(&result, "format", &[2, 3, 4, 5])?; Ok(result) } @@ -127,7 +143,7 @@ mod tests { assert!(dependency(&removed, "one", None).is_err()); for input in ["{}", "{name=\"app\"}", "{name=\"app\", // hi\n}"] { let output = dependency(input, "one", Some("{name=\"one\",path=\"a\"}")).unwrap(); - assert!(loads_versions(&output, "format", &[2, 3, 4]).is_ok()); + assert!(loads_versions(&output, "format", &[2, 3, 4, 5]).is_ok()); } } }