From 8ef552c378dbe757284173ac27c4869660a7281f Mon Sep 17 00:00:00 2001 From: LunaStev Date: Sat, 17 Oct 2026 18:40:37 +0900 Subject: [PATCH 1/2] feat: add native C ABI interoperability and protect build artifacts Signed-off-by: LunaStev --- README.md | 6 + compiler/src/invocation.rs | 250 +++++++++++- compiler/src/lib.rs | 10 + compiler/src/selection.rs | 50 +++ docs/native-interop.md | 143 +++++++ docs/reference.md | 4 + docs/schemas/metadata-v1.json | 27 ++ manifest/src/lib.rs | 3 + manifest/src/native.rs | 412 +++++++++++++++++++ manifest/src/parse.rs | 9 +- src/commands/build.rs | 20 + src/commands/doctor.rs | 19 +- src/commands/metadata.rs | 4 +- src/main.rs | 1 + src/native.rs | 310 +++++++++++++++ state/src/artifacts.rs | 156 ++++++-- tests/build_artifact_integrity.rs | 386 ++++++++++++++++++ tests/clean.rs | 25 +- tests/doctor.rs | 33 +- tests/fixtures/fake_wavec.rs | 8 + tests/native_build.rs | 632 ++++++++++++++++++++++++++++++ tests/native_interop.py | 334 ++++++++++++++++ tools/ci_platform.py | 4 + 23 files changed, 2786 insertions(+), 60 deletions(-) create mode 100644 docs/native-interop.md create mode 100644 manifest/src/native.rs create mode 100644 src/native.rs create mode 100644 tests/build_artifact_integrity.rs create mode 100644 tests/native_build.rs create mode 100644 tests/native_interop.py diff --git a/README.md b/README.md index 3526c63..cbf7bf0 100644 --- a/README.md +++ b/README.md @@ -567,3 +567,9 @@ for implemented contracts, verification limits and remaining acceptance work. The complete [command and manifest reference](docs/reference.md) includes generated CLI help, field types, environment variables, streams, and machine-readable schemas. + +### Native C ABI libraries + +Vex supports manifest-owned prebuilt native inputs and Wave object/shared outputs. +See [native interoperability](docs/native-interop.md) for C, C++ and Rust C ABI +contracts, target-specific paths, artifact ownership and runtime prerequisites. diff --git a/compiler/src/invocation.rs b/compiler/src/invocation.rs index b646bb7..d5eaf12 100644 --- a/compiler/src/invocation.rs +++ b/compiler/src/invocation.rs @@ -89,6 +89,8 @@ pub fn run_build_with_dry_run( } else { None }; + let root = std::env::current_dir().map_err(Error::environment)?; + let (outputs, optional_outputs) = validate_plan_outputs(&plan, &root, &args[..separator])?; if user_requested_dry_run { if !runtime.is_empty() { let values = runtime @@ -116,16 +118,12 @@ pub fn run_build_with_dry_run( .filter(|a| a.as_str() != "--run") .cloned() .collect(); - let outputs = plan["compile"] - .as_array() - .unwrap() - .iter() - .filter_map(|job| job["output"].as_str()) - .chain(plan["link"]["output"].as_str()) - .map(PathBuf::from) - .collect::>(); - let root = std::env::current_dir().map_err(Error::environment)?; - let ownership = state::artifacts::Batch::prepare(&root, outputs).map_err(Error::environment)?; + let ownership = state::artifacts::Batch::prepare_with_optional( + &root, + outputs, + optional_outputs.iter().cloned(), + ) + .map_err(Error::environment)?; let compile_result = (|| -> Result { let status = if let Some(sink) = report.as_mut() { insert_build_flag(&mut compile_args, "--error-format=json"); @@ -153,16 +151,19 @@ pub fn run_build_with_dry_run( }; Ok(status) })(); - ownership.finish().map_err(Error::environment)?; - let status = compile_result?; - if !status.success() { - return Err(compiler_error( - status, - format!("wavec build failed [{}]", classify_exit(status)), - )); - } + let compile_result = compile_result.and_then(|status| { + if status.success() { + ownership.verify_outputs().map_err(Error::compiler) + } else { + Err(compiler_error( + status, + format!("wavec build failed [{}]", classify_exit(status)), + )) + } + }); + finish_compilation(compile_result, ownership.finish())?; if let Some(sink) = report.as_mut() { - let outputs: Vec<_> = if let Some(output) = plan["link"]["output"].as_str() { + let mut outputs: Vec<_> = if let Some(output) = plan["link"]["output"].as_str() { vec![output.to_owned()] } else { plan["compile"] @@ -172,6 +173,12 @@ pub fn run_build_with_dry_run( .filter_map(|job| job["output"].as_str().map(str::to_owned)) .collect() }; + outputs.extend( + optional_outputs + .iter() + .filter(|path| path.is_file()) + .map(|path| path.to_string_lossy().into_owned()), + ); sink( serde_json::json!({"event":"artifact", "origin":"vex", "target":plan["target"], "emit":plan["emit"], "paths":outputs, "executable":execution.as_ref().map(|(_,path)| path)}), @@ -203,6 +210,163 @@ pub fn run_build_with_dry_run( Ok(None) } +fn finish_compilation( + compilation: Result<(), Error>, + ownership: Result<(), String>, +) -> Result<(), Error> { + match (compilation, ownership) { + (Err(primary), Err(secondary)) => { + // Bookkeeping must not replace compiler, message-file, or + // supervision failures. The secondary cause remains in JSONL too. + let _ = diagnostic::output::stderr(format_args!( + "warning: artifact ownership could not be recorded: {secondary}\n" + )); + Err(primary.with_field("artifact_ownership_error", secondary)) + } + (Err(primary), Ok(())) => Err(primary), + (Ok(()), Err(error)) => Err(Error::environment(error)), + (Ok(()), Ok(())) => Ok(()), + } +} + +pub(crate) fn validate_plan_outputs( + plan: &serde_json::Value, + root: &Path, + compiler_args: &[String], +) -> Result<(Vec, Vec), Error> { + let compile = plan["compile"].as_array().unwrap(); + let outputs: Vec<_> = compile + .iter() + .filter_map(|job| job["output"].as_str()) + .chain(plan["link"]["output"].as_str()) + .map(PathBuf::from) + .collect(); + let optional = optional_link_outputs(plan); + let all_outputs: Vec<_> = outputs.iter().chain(&optional).cloned().collect(); + let names = + state::artifacts::validate_output_paths(root, &all_outputs).map_err(Error::compiler)?; + let identity = |path: &Path| { + let path = if path.is_absolute() { + path.to_owned() + } else { + root.join(path) + }; + let path = path.canonicalize().unwrap_or_else(|_| { + let mut normalized = PathBuf::new(); + for component in path.components() { + match component { + std::path::Component::CurDir => {} + std::path::Component::ParentDir => { + normalized.pop(); + } + _ => normalized.push(component.as_os_str()), + } + } + normalized + }); + let value = path.to_string_lossy().into_owned(); + if cfg!(any(windows, target_os = "macos")) { + value.to_lowercase() + } else { + value + } + }; + let output_ids: Vec<_> = names.iter().map(|name| identity(Path::new(name))).collect(); + let compile_ids: Vec<_> = compile + .iter() + .map(|job| identity(Path::new(job["output"].as_str().unwrap()))) + .collect(); + let inputs = plan["inputs"] + .as_array() + .unwrap() + .iter() + .map(|input| input["path"].as_str().unwrap()) + .chain(compile.iter().map(|job| job["input"].as_str().unwrap())); + for input in inputs { + if output_ids.contains(&identity(Path::new(input))) { + return Err(Error::compiler(format!( + "compiler output aliases input `{input}`" + ))); + } + } + // Native absolute file arguments are generated by Vex, not accepted from + // the CLI. Schema v1 omits raw linker arguments from link.inputs, so protect + // them explicitly before any compile job could replace them. + for input in compiler_args + .iter() + .filter_map(|argument| argument.strip_prefix("-Clink-arg=")) + .filter(|input| Path::new(input).is_absolute()) + { + if output_ids.contains(&identity(Path::new(input))) { + return Err(Error::compiler(format!( + "compiler output aliases native linker input `{input}`" + ))); + } + } + if let Some(inputs) = plan["link"]["inputs"].as_array() { + for input in inputs { + let input = input.as_str().unwrap(); + let id = identity(Path::new(input)); + // Objects generated in this same plan are intentionally link inputs. + if !compile_ids.contains(&id) && output_ids.contains(&id) { + return Err(Error::compiler(format!( + "compiler output aliases link input `{input}`" + ))); + } + } + } + Ok((outputs, optional)) +} + +fn optional_link_outputs(plan: &serde_json::Value) -> Vec { + if !plan["target"].as_str().unwrap().ends_with("-windows-msvc") { + return Vec::new(); + } + let Some(output) = plan["link"]["output"].as_str().map(PathBuf::from) else { + return Vec::new(); + }; + let args = plan["link"]["args"].as_array().unwrap(); + let mut paths = Vec::new(); + // Schema v1 lists the image but omits MSVC linker companions. Reserve the + // compiler's documented destinations without parsing display-only commands. + for (option, default) in [ + ("IMPLIB", output.with_extension("lib")), + ("PDB", output.with_extension("pdb")), + ("ILK", output.with_extension("ilk")), + ("MAP", output.with_extension("map")), + ( + "MANIFESTFILE", + PathBuf::from(format!("{}.manifest", output.display())), + ), + ] { + let path = args + .iter() + .rev() + .find_map(|arg| { + let arg = arg.as_str().unwrap(); + let (name, value) = arg + .strip_prefix('/') + .or_else(|| arg.strip_prefix('-'))? + .split_once(':')?; + name.eq_ignore_ascii_case(option) + .then(|| PathBuf::from(value)) + }) + .unwrap_or(default); + if option == "PDB" + && path + .to_str() + .is_some_and(|path| path.eq_ignore_ascii_case("NONE")) + { + continue; + } + if option == "IMPLIB" { + paths.push(path.with_extension("exp")); + } + paths.push(path); + } + paths +} + fn validate_output_path(output: &Path, generation: &Path) -> Result<(), Error> { if !output.starts_with(generation) || output @@ -341,6 +505,54 @@ fn combined_output(stdout: &[u8], stderr: &[u8]) -> String { #[cfg(test)] mod message_tests { + #[test] + fn tracking_failure_never_replaces_an_existing_error_category() { + for category in [ + diagnostic::Category::Compiler, + diagnostic::Category::Environment, + diagnostic::Category::Timeout, + diagnostic::Category::Cancelled, + ] { + let error = super::finish_compilation( + Err(diagnostic::Error::new(category, "primary failure")), + Err("registry failure".into()), + ) + .unwrap_err(); + assert_eq!(error.category, category); + assert_eq!(error.to_string(), "primary failure"); + assert_eq!( + error.context_fields, + vec![("artifact_ownership_error".into(), "registry failure".into())] + ); + } + } + + #[test] + fn native_linker_arguments_cannot_alias_compiler_outputs() { + let root = std::env::current_dir().unwrap(); + let plan = serde_json::json!({ + "target":"x86_64-unknown-linux-gnu", "link":null, + "compile":[{"input":"src/main.wave","output":"target/native-input-alias.o"}], + "inputs":[{"path":"src/main.wave"}] + }); + let arguments = vec![format!( + "-Clink-arg={}", + root.join("target/native-input-alias.o").display() + )]; + let error = super::validate_plan_outputs(&plan, &root, &arguments).unwrap_err(); + assert_eq!(error.category, diagnostic::Category::Compiler); + assert!(error.to_string().contains("aliases native linker input")); + super::validate_plan_outputs( + &plan, + &root, + &[ + "-Clink-arg=-soname".into(), + "-Clink-arg=libexample.so".into(), + ], + ) + .unwrap(); + } + #[test] fn structured_diagnostic_preserves_nested_spans_and_related_locations() { let payload = serde_json::json!({"error":{"message":"fixture", "span":{"start":3,"end":8,"line":2}, "related":[{"span":{"start":0,"end":1}}]}}); diff --git a/compiler/src/lib.rs b/compiler/src/lib.rs index cd1a2a1..3f243e1 100644 --- a/compiler/src/lib.rs +++ b/compiler/src/lib.rs @@ -9,3 +9,13 @@ pub use selection::Compiler; pub fn validate_plan(bytes: &[u8]) -> Result { plan::validate_dry_run_json_output(bytes, &[]) } + +/// Check compiler destinations and protected native inputs without creating +/// outputs or ownership records. Call after validating the schema. +pub fn validate_plan_outputs( + plan: &serde_json::Value, + root: &std::path::Path, + compiler_args: &[String], +) -> Result<(), diagnostic::Error> { + invocation::validate_plan_outputs(plan, root, compiler_args).map(|_| ()) +} diff --git a/compiler/src/selection.rs b/compiler/src/selection.rs index c03c4d0..b61b071 100644 --- a/compiler/src/selection.rs +++ b/compiler/src/selection.rs @@ -1,4 +1,5 @@ use diagnostic::Error; +use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use std::process::Command; use std::time::Duration; @@ -8,6 +9,7 @@ pub struct Compiler { pub(crate) path: PathBuf, targets: Option>, version: Option, + specs: BTreeMap, serde_json::Value>, } impl Compiler { @@ -62,6 +64,7 @@ impl Compiler { path, targets: None, version: None, + specs: BTreeMap::new(), }) } @@ -115,6 +118,53 @@ impl Compiler { Ok(()) } + /// Target metadata is cached only for this invocation, just like the target list. + pub fn target_spec(&mut self, target: Option<&str>) -> Result { + let key = target.map(str::to_owned); + if let Some(value) = self.specs.get(&key) { + return Ok(value.clone()); + } + let mut command = Command::new(&self.path); + command.args(["print", "target-spec", "--format=json"]); + if let Some(target) = target { + self.validate_target(target)?; + command.arg(format!("--target={target}")); + } + let output = + process::output(&mut command, Duration::from_secs(60)).map_err(Error::environment)?; + if !output.status.success() { + return Err(super::invocation::compiler_error( + output.status, + format!( + "wavec target-spec query failed: {}", + String::from_utf8_lossy(&output.stderr) + ), + )); + } + let spec: serde_json::Value = serde_json::from_slice(&output.stdout) + .map_err(|e| Error::compiler(format!("invalid wavec target-spec JSON: {e}")))?; + let triple = spec["triple"] + .as_str() + .ok_or_else(|| Error::compiler("target-spec is missing triple"))?; + if triple.is_empty() + || !triple + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.')) + || triple == "." + || triple == ".." + || target.is_some_and(|expected| expected != triple) + || spec["supported"] != true + || spec["object_format"].as_str().is_none() + || spec["os"].as_str().is_none() + { + return Err(Error::compiler( + "invalid or inconsistent compiler target-spec", + )); + } + self.specs.insert(key, spec.clone()); + Ok(spec) + } + /// Query once per invocation; doctor uses the same validated capability data /// as normal builds without resolving dependencies or creating project state. pub fn supported_targets(&mut self) -> Result<&[String], Error> { diff --git a/docs/native-interop.md b/docs/native-interop.md new file mode 100644 index 0000000..01766c7 --- /dev/null +++ b/docs/native-interop.md @@ -0,0 +1,143 @@ +# Native C ABI interoperability + +Vex links prebuilt native code into Wave packages and emits Wave objects or shared +libraries for native callers. The ABI is the C ABI implemented by the selected +Wave compiler. C++ and Rust libraries must expose C ABI symbols (`extern "C"`), +not their language-specific ABI. Vex never builds C/C++/Rust source trees or runs +foreign build scripts. Prepare native inputs with the appropriate toolchain first. + +The supported compiler baseline is the public Wave `0.2.1-pre-beta` release. +Object and shared output are supported; static-library creation is not part of +this interface. An object can be archived by an external build system. Wave +`pub` controls module visibility; `export(c)` controls exported C symbols. + +## Wave calls native libraries + +```wson +{ + format = 2, + name = "app", + version = "0.1.0", + native = { + libraries = [ + { path = "native/libarithmetic.a", target = "x86_64-unknown-linux-gnu" }, + { name = "support" } + ], + search_paths = [{ path = "native" }] + } +} +``` + +```wave +extern(c, "native_add") fun native_add(a: i32, b: i32) -> i32; +fun main() { + var result: i32 = native_add(20, 22); + println("{}", result); +} +``` + +A library entry has exactly one `path` or `name`. A path names a prebuilt `.o`, +`.obj`, `.a`, or `.lib`; a shared library uses `name` plus `search_paths` (on +Windows the linker consumes its import `.lib`, not a `.dll`). `name` uses the +selected target's linker convention. Do not include flags in names or paths. + +With public Wave `0.2.1-pre-beta`, declarations inside imported packages must +use the explicit linker-symbol form `extern(c, "native_add")`. The shorter +`extern(c)` form works at the root but can incorrectly receive a module prefix +inside imported packages. The explicit symbol form is used in the transitive +interoperability acceptance fixture. + +Paths are UTF-8, relative to the **declaring package**, and use `/` on every OS. +Absolute paths, parent traversal, empty/dot components, Windows-reserved path +components and symlink escapes outside that package are rejected. Selected files +and search directories must already exist, including during `check` and dry-run. +Native declarations in transitive Git/path packages are included in the final +link. Consuming packages precede their dependencies, and each package's library +declaration order is preserved, including names repeated across packages. A name is resolved +first within its declaring package's selected search paths (shared before static +on Unix); if no local file matches, the compiler's default system library search +is used. One package's search paths do not select another package's library. +No package graph or lockfile format change is introduced. + +An optional `target` is an exact compiler triple. Only matching entries are used; +there is no predicate language or target-dependent Wave dependency graph here. +For example, use separate `.a` and MSVC `.lib` entries for different targets. +`--target` still selects the compiler target and must be supported by that +compiler. Vex does not install native SDKs or cross toolchains automatically. + +Shared inputs need a runtime loader search configuration supplied by the caller +or deployment environment. Vex does not modify `PATH`, `LD_LIBRARY_PATH`, or +`DYLD_LIBRARY_PATH`, copy DLLs, or insert library search directories into runtime +loader paths. Compile-time search paths alone do not ensure runtime availability. + +## Native callers use Wave + +```wson +{ + format = 2, + name = "arithmetic", + version = "0.1.0", + lib = true, + native = { output = "object" } +} +``` + +```wave +export(c) fun wave_add(a: i32, b: i32) -> i32 { return a + b; } +``` + +Use `output = "shared"` for a shared library. Both values require `lib = true`. +A library without an explicit output setting now builds an object instead of +attempting to link an executable without `main`. A binary package can declare +native inputs but cannot set a library output kind. `vex run` still rejects +library packages. `vex check` performs Wave checking without linking native +inputs or producing native artifacts; it still validates their selected paths. + +On Linux, a C caller can declare `int32_t wave_add(int32_t, int32_t);` and link the +produced object with its C compiler. C++ callers use `extern "C"`; Rust callers +use an `extern "C"` declaration and appropriate native linking. Keep the C +header/declarations synchronized with Wave yourself: Vex does not generate +bindings or headers. Integer widths, layout, calling convention, ownership, +allocation/free pairing and pointer lifetimes remain the caller/library contract. +Exceptions or Rust panics must not unwind through an incompatible ABI boundary. + +## Artifacts and reproducibility + +Library packages and binary packages using native declarations (including +transitive declarations) use: + +- `target//dev/` or `target//release/` +- `.o` (`.obj` on Windows) for objects +- `lib.so`, `lib.dylib`, or `.dll` for shared libraries +- `` (`.exe` on Windows) for native binaries +- `.vex-obj//` below that directory for intermediate objects + +Run outputs remain in a per-run generation; its lease protects them while the +program executes. Binary projects with no native declarations retain their +existing layout. This is the native slice of the broader targets/layout design; +multiple named package targets and custom profiles are not introduced. + +ELF shared libraries receive a stable SONAME; Mach-O shared libraries receive an +`@rpath` install name. Windows import libraries and other compiler-generated +companions are preserved and tracked when produced. `--message-file` artifact +events report paths only after successful output verification. Metadata schema 1 +adds a nullable `native` declaration object for each package without querying a +compiler. Consumers must continue to tolerate additive fields. + +Builds refuse overwriting unowned or edited artifact files, including implicit +Windows companions. Move such files aside explicitly before rebuilding. `clean` +only removes unchanged owned artifacts and skips leased generations. If compiler +execution fails, its error remains primary even if ownership bookkeeping fails. + +`--locked` preserves the selected Wave graph; `--offline` prevents dependency +network access. Neither option locks an external SDK, a system library selected +by name, or mutable path-package contents. Version and distribute prebuilt native +inputs with the package, select the correct target entry and verify the resulting +binary with the intended runtime environment. Native inputs committed in Git +packages follow that package's exact locked commit. + +The nine-platform acceptance pipeline runs `tests/native_interop.py` using the +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. diff --git a/docs/reference.md b/docs/reference.md index 8fc3640..dc859f5 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -19,6 +19,7 @@ Builds and user programs execute from the selected project root. | `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 | Optional prebuilt library inputs, search paths and library output; see [native interoperability](native-interop.md) | 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. @@ -92,6 +93,9 @@ be removed, but directories containing unknown files are retained. Ownership begins with builds made by this version; existing files are never adopted merely because a later compiler invocation writes the same path. Run lease files remain as coordination identities, even after their generation is removed. +Builds now refuse to overwrite these unknown or edited files; move them aside +explicitly before rebuilding. A successful build verifies its declared outputs +exist before reporting artifact events. `prune` previews unused Git checkouts; `--apply` performs deletion. A complete current local graph and existing project coordination are required; run `fetch` diff --git a/docs/schemas/metadata-v1.json b/docs/schemas/metadata-v1.json index 27bec4e..1e32b5e 100644 --- a/docs/schemas/metadata-v1.json +++ b/docs/schemas/metadata-v1.json @@ -93,6 +93,33 @@ ] } } + }, + "native": { + "type": [ + "object", + "null" + ], + "properties": { + "output": { + "enum": [ + "object", + "shared", + null + ] + }, + "libraries": { + "type": "array", + "items": { + "type": "object" + } + }, + "search_paths": { + "type": "array", + "items": { + "type": "object" + } + } + } } } } diff --git a/manifest/src/lib.rs b/manifest/src/lib.rs index 74babe6..36e31ec 100644 --- a/manifest/src/lib.rs +++ b/manifest/src/lib.rs @@ -1,8 +1,10 @@ use std::path::{Path, PathBuf}; +mod native; mod parse; mod render; +pub use native::{NativeConfig, NativeLibrary, NativeOutput, NativeSearchPath}; pub use render::render_new_manifest; /// Parse a manifest without filesystem access or project-state mutation. @@ -54,6 +56,7 @@ pub struct Manifest { pub name: String, pub version: String, pub lib: bool, + pub native: Option, pub description: Option, pub author: Option, pub license: Option, diff --git a/manifest/src/native.rs b/manifest/src/native.rs new file mode 100644 index 0000000..ac79455 --- /dev/null +++ b/manifest/src/native.rs @@ -0,0 +1,412 @@ +use std::collections::HashSet; + +use wson::{WsonMap, WsonValue}; + +use crate::parse::reject_unknown_fields; + +/// Native link inputs are resolved relative to the declaring package. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct NativeConfig { + pub output: Option, + pub libraries: Vec, + pub search_paths: Vec, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum NativeOutput { + Object, + Shared, +} + +impl NativeOutput { + pub fn as_str(self) -> &'static str { + match self { + Self::Object => "object", + Self::Shared => "shared", + } + } +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct NativeLibrary { + pub path: Option, + pub name: Option, + pub target: Option, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct NativeSearchPath { + pub path: String, + pub target: Option, +} + +pub(crate) fn parse(value: Option<&WsonValue>, lib: bool) -> Result, String> { + let Some(value) = value else { + return Ok(None); + }; + let WsonValue::Object(object) = value else { + return Err("manifest field `native` must be an object".into()); + }; + reject_unknown_fields(object, &["output", "libraries", "search_paths"], "native")?; + let output = match optional_string(object, "output", "native")? { + None => None, + Some(_) if !lib => return Err("native field `output` requires `lib = true`".into()), + Some(value) => match value.as_str() { + "object" => Some(NativeOutput::Object), + "shared" => Some(NativeOutput::Shared), + _ => return Err("native field `output` must be `object` or `shared`".into()), + }, + }; + + let mut libraries = Vec::new(); + let mut library_keys = HashSet::new(); + for value in array(object, "libraries")? { + let WsonValue::Object(library) = value else { + return Err("native library entry must be an object".into()); + }; + reject_unknown_fields(library, &["path", "name", "target"], "native library")?; + let path = optional_string(library, "path", "native library")?; + let name = optional_string(library, "name", "native library")?; + if path.is_some() == name.is_some() { + return Err("native library must specify exactly one of `path` or `name`".into()); + } + if let Some(path) = &path { + validate_path(path, "native library path")?; + if ![".o", ".obj", ".a", ".lib"] + .iter() + .any(|extension| path.ends_with(extension)) + { + return Err("native library `path` must name an object or static library (.o, .obj, .a, or .lib); use `name` and `search_paths` for shared libraries".into()); + } + } + if let Some(name) = &name { + validate_name(name)?; + } + let target = target(library, "native library")?; + if !library_keys.insert((path.clone(), name.clone(), target.clone())) { + return Err("native library is declared more than once for the same target".into()); + } + libraries.push(NativeLibrary { path, name, target }); + } + + let mut search_paths = Vec::new(); + let mut search_keys = HashSet::new(); + for value in array(object, "search_paths")? { + let WsonValue::Object(search_path) = value else { + return Err("native search path entry must be an object".into()); + }; + reject_unknown_fields(search_path, &["path", "target"], "native search path")?; + let path = optional_string(search_path, "path", "native search path")? + .ok_or_else(|| "native search path field `path` must be a string".to_string())?; + validate_path(&path, "native search path")?; + let target = target(search_path, "native search path")?; + if !search_keys.insert((path.clone(), target.clone())) { + return Err("native search path is declared more than once for the same target".into()); + } + search_paths.push(NativeSearchPath { path, target }); + } + Ok(Some(NativeConfig { + output, + libraries, + search_paths, + })) +} + +fn optional_string(object: &WsonMap, field: &str, context: &str) -> Result, String> { + match object.get(field) { + None => Ok(None), + Some(WsonValue::String(value)) + if !value.trim().is_empty() && !value.chars().any(char::is_control) => + { + Ok(Some(value.clone())) + } + Some(WsonValue::String(_)) => Err(format!( + "{context} field `{field}` must not be empty or contain control characters" + )), + Some(_) => Err(format!("{context} field `{field}` must be a string")), + } +} + +fn array<'a>(object: &'a WsonMap, field: &str) -> Result<&'a [WsonValue], String> { + match object.get(field) { + None => Ok(&[]), + Some(WsonValue::Array(values)) => Ok(values), + Some(_) => Err(format!("native field `{field}` must be an array")), + } +} + +fn target(object: &WsonMap, context: &str) -> Result, String> { + let target = optional_string(object, "target", context)?; + if let Some(target) = &target { + let components: Vec<_> = target.split('-').collect(); + if components.len() < 3 + || components.iter().any(|part| { + part.is_empty() + || !part + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_') + }) + { + return Err(format!( + "{context} field `target` must be an exact compiler target triple" + )); + } + } + Ok(target) +} + +fn validate_name(name: &str) -> Result<(), String> { + let mut bytes = name.bytes(); + if !bytes + .next() + .is_some_and(|byte| byte.is_ascii_alphanumeric() || byte == b'_') + || !bytes + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'+' | b'-')) + { + return Err("native library `name` must start with an ASCII letter, digit, or underscore and contain only ASCII letters, digits, `_`, `.`, `+`, or `-`".into()); + } + Ok(()) +} + +fn validate_path(path: &str, context: &str) -> Result<(), String> { + if path.contains(['\\', ':', '*', '?', '"', '<', '>', '|']) + || path.split('/').any(|part| { + part.is_empty() + || matches!(part, "." | "..") + || part.starts_with('-') + || part.ends_with(['.', ' ']) + || reserved_windows_component(part) + }) + { + return Err(format!("{context} must be a portable relative path with forward slashes, without parent, empty, dot, or option-like components")); + } + Ok(()) +} + +fn reserved_windows_component(part: &str) -> bool { + let stem = part.split('.').next().unwrap_or(part).to_ascii_uppercase(); + matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL") + || ["COM", "LPT"].into_iter().any(|prefix| { + stem.strip_prefix(prefix).is_some_and(|suffix| { + matches!( + suffix, + "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³" + ) + }) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::decode; + + fn manifest(native: &str, lib: bool) -> Result { + decode( + &format!("{{format=2,name=\"app\",lib={lib},native={native}}}"), + "vex.ws".into(), + ) + } + + #[test] + fn imports_prebuilt_libraries_and_preserves_order_and_target_variants() { + let config = manifest( + r#"{ + libraries=[{path="vendor/ffi/libsample.a",target="x86_64-unknown-linux-gnu"}, + {name="sample++",target="aarch64-apple-darwin"}, + {name="sample++",target="x86_64-apple-darwin"}], + search_paths=[{path="vendor/native libs",target="aarch64-apple-darwin"}, + {path="vendor/native libs",target="x86_64-apple-darwin"}] + }"#, + false, + ) + .unwrap() + .native + .unwrap(); + assert_eq!(config.output, None); + assert_eq!(config.libraries.len(), 3); + assert_eq!( + config.libraries[0].path.as_deref(), + Some("vendor/ffi/libsample.a") + ); + assert_eq!(config.libraries[1].name.as_deref(), Some("sample++")); + assert_eq!( + config.libraries[2].target.as_deref(), + Some("x86_64-apple-darwin") + ); + assert_eq!(config.search_paths[0].path, "vendor/native libs"); + } + + #[test] + fn exports_object_or_shared_library_only_for_library_packages() { + for (value, output) in [ + ("object", NativeOutput::Object), + ("shared", NativeOutput::Shared), + ] { + let raw = format!("{{output=\"{value}\"}}"); + assert_eq!( + manifest(&raw, true).unwrap().native.unwrap().output, + Some(output) + ); + assert_eq!(output.as_str(), value); + assert!(manifest(&raw, false) + .unwrap_err() + .contains("requires `lib = true`")); + } + for lib in [false, true] { + assert_eq!( + manifest("{}", lib).unwrap().native, + Some(NativeConfig::default()) + ); + assert_eq!( + decode(&format!("{{name=\"app\",lib={lib}}}"), "vex.ws".into()) + .unwrap() + .native, + None + ); + } + } + + #[test] + fn rejects_unknown_duplicate_ambiguous_and_wrong_typed_fields() { + for raw in [ + "[]", + "false", + r#"{output="static"}"#, + "{output=1}", + "{flags=[]}", + "{libraries={}}", + "{search_paths=false}", + "{libraries=[1]}", + "{libraries=[{}]}", + r#"{libraries=[{name="m",path="libm.a"}]}"#, + r#"{libraries=[{name="m",flags=[]}]}"#, + "{libraries=[{name=false}]}", + "{libraries=[{path=1}]}", + r#"{libraries=[{name="m",target=1}]}"#, + "{search_paths=[1]}", + "{search_paths=[{}]}", + "{search_paths=[{path=1}]}", + r#"{search_paths=[{path="vendor",name="m"}]}"#, + r#"{libraries=[{name="m"},{name="m"}]}"#, + r#"{libraries=[{path="vendor/libm.a"},{path="vendor/libm.a"}]}"#, + r#"{libraries=[{path="vendor/libm.so"}]}"#, + r#"{libraries=[{path="vendor/libm.dylib"}]}"#, + r#"{libraries=[{path="vendor/libm.dll"}]}"#, + r#"{libraries=[{path="vendor/libm"}]}"#, + r#"{search_paths=[{path="vendor"},{path="vendor"}]}"#, + r#"{libraries=[{name="m",name="other"}]}"#, + r#"{output="object",output="shared"}"#, + ] { + assert!( + manifest(raw, true).is_err(), + "accepted invalid native declaration: {raw}" + ); + } + } + + #[test] + fn rejects_nonportable_paths_and_option_injection() { + for path in [ + "", + " ", + "/lib.a", + "//server/lib.a", + "C:/lib.a", + "C:lib.a", + "lib\\ffi.a", + "../lib.a", + "vendor/../lib.a", + ".", + "./lib.a", + "vendor/./lib.a", + "vendor//lib.a", + "vendor/", + "-lfoo", + "vendor/-lfoo", + "lib?.a", + "vendor./lib.a", + "vendor /lib.a", + "vendor\n/lib.a", + "NUL.a", + "con/lib.a", + "LPT1.obj", + "COM².lib", + ] { + for field in ["libraries", "search_paths"] { + let raw = format!("{{{field}=[{{path={}}}]}}", wson::quote(path)); + assert!( + manifest(&raw, true).is_err(), + "accepted {field} path {path:?}" + ); + } + } + } + + #[test] + fn accepts_each_supported_prebuilt_library_extension() { + for path in [ + "native/export.o", + "native/export.obj", + "native/export.a", + "native/export.lib", + ] { + let raw = format!("{{libraries=[{{path={}}}]}}", wson::quote(path)); + assert_eq!( + manifest(&raw, false).unwrap().native.unwrap().libraries[0] + .path + .as_deref(), + Some(path) + ); + } + } + + #[test] + fn rejects_invalid_names_and_target_patterns() { + for name in [ + "", " ", ".", "..", "-lm", "m;echo", "m/path", "m\\path", "m\n", "café", + ] { + let raw = format!("{{libraries=[{{name={}}}]}}", wson::quote(name)); + assert!(manifest(&raw, false).is_err(), "accepted name {name:?}"); + } + for target in [ + "", + " ", + "linux", + "x86_64-linux", + "*-unknown-linux-gnu", + "x86_64--linux-gnu", + "-x86_64-linux-gnu", + "x86_64-unknown-linux-gnu ", + "x86_64-unknown-linux-gnu\n", + ] { + for (field, declaration) in [ + ("libraries", "name=\"m\""), + ("search_paths", "path=\"vendor\""), + ] { + let raw = format!( + "{{{field}=[{{{declaration},target={}}}]}}", + wson::quote(target) + ); + assert!(manifest(&raw, true).is_err(), "accepted target {target:?}"); + } + } + } + + #[test] + fn uses_existing_format_boundary_for_native_strings() { + let raw = r#"{name="app",native={libraries=[{path="native\u002flib.a"}]}}"#; + assert!(decode(raw, "vex.ws".into()).is_err()); + let escaped = raw.replacen('{', "{format=2,", 1); + assert_eq!( + decode(&escaped, "vex.ws".into()) + .unwrap() + .native + .unwrap() + .libraries[0] + .path + .as_deref(), + Some("native/lib.a") + ); + } +} diff --git a/manifest/src/parse.rs b/manifest/src/parse.rs index 078b934..a27b2e0 100644 --- a/manifest/src/parse.rs +++ b/manifest/src/parse.rs @@ -11,6 +11,7 @@ const ROOT_FIELDS: &[&str] = &[ "name", "version", "lib", + "native", "description", "author", "license", @@ -43,6 +44,7 @@ pub(crate) fn parse_manifest(raw: &str, source_path: PathBuf) -> Result return Err("manifest field `lib` must be a bool".to_string()), }; let compiler = parse_optional_string(data.get("compiler"), "compiler")?; + let native = crate::native::parse(data.get("native"), lib)?; if let Some(required) = &compiler { let version = semver::Version::parse(required) .map_err(|_| "manifest compiler must be an exact version such as 0.2.1-pre-beta; ranges are unsupported")?; @@ -77,6 +79,7 @@ pub(crate) fn parse_manifest(raw: &str, source_path: PathBuf) -> Result) -> Result, Stri Ok(dependencies) } -fn reject_unknown_fields(object: &WsonMap, accepted: &[&str], context: &str) -> Result<(), String> { +pub(crate) fn reject_unknown_fields( + object: &WsonMap, + accepted: &[&str], + context: &str, +) -> Result<(), String> { let Some(field) = object .keys() .find(|field| !accepted.contains(&field.as_str())) diff --git a/src/commands/build.rs b/src/commands/build.rs index a2878a5..29b4da4 100644 --- a/src/commands/build.rs +++ b/src/commands/build.rs @@ -123,6 +123,26 @@ fn run_build( } else { None }; + if let Some(native) = crate::native::prepare( + manifest, + &resolution, + compiler, + options.target.as_deref(), + options.release, + mode == BuildMode::Check, + generation.as_deref(), + )? { + // Native preparation supplies one canonical target and owns all output + // paths, including run-generation intermediates. + global_args.retain(|arg| arg != "--target"); + if let Some(target) = &options.target { + global_args.retain(|arg| arg != target); + } + global_args.extend(native.global); + build_args.retain(|arg| !arg.starts_with("--target-dir=")); + build_args.extend(native.inputs); + build_args.extend(native.output); + } let mut wavec_args = Vec::new(); wavec_args.extend(resolution.dependency_args()?); wavec_args.extend(global_args); diff --git a/src/commands/doctor.rs b/src/commands/doctor.rs index 97c16cd..1a3104a 100644 --- a/src/commands/doctor.rs +++ b/src/commands/doctor.rs @@ -524,7 +524,11 @@ fn inspect_project( compiler.validate_version(manifest.compiler.as_deref())?; } let mut args = resolution.dependency_args()?; - if let Some(target) = target { + let native = + crate::native::prepare(manifest, &resolution, compiler, target, false, false, None)?; + if let Some(native) = &native { + args.extend(native.global.clone()); + } else if let Some(target) = target { args.extend(["--target".into(), target.into()]); } args.extend([ @@ -533,9 +537,13 @@ fn inspect_project( "--dry-run".into(), "--error-format=json".into(), ]); + if let Some(native) = native { + args.extend(native.inputs); + args.extend(native.output); + } let output = process::output( Command::new(compiler.path()) - .args(args) + .args(&args) .env("NO_COLOR", "1"), Duration::from_secs(60), ) @@ -552,7 +560,10 @@ fn inspect_project( Error::compiler(message) }); } - compiler::validate_plan(&output.stdout).map_err(Error::compiler) + let plan = compiler::validate_plan(&output.stdout).map_err(Error::compiler)?; + let root = std::env::current_dir().map_err(Error::environment)?; + compiler::validate_plan_outputs(&plan, &root, &args)?; + Ok(plan) })(); match result { Ok(plan) => { @@ -560,7 +571,7 @@ fn inspect_project( "dry_run", "ok", true, - "compiler dry-run schema v1 is valid; compilation and linking were not executed", + "compiler dry-run schema v1 and output paths are valid; compilation and linking were not executed", json!({"schema_version":plan["schema_version"], "target":plan["target"]}), ); if let Some(program) = plan["link"]["program"].as_str() { diff --git a/src/commands/metadata.rs b/src/commands/metadata.rs index 91d82ed..00c3d76 100644 --- a/src/commands/metadata.rs +++ b/src/commands/metadata.rs @@ -61,13 +61,13 @@ pub fn metadata(args: &[String], selection: &crate::project::Selection) -> Resul packages.push(json!({"name":package.name, "version":package.version, "manifest_format":package_manifest.format, "compiler":package_manifest.compiler, "source":source, "root":json_path(&directory)?, "manifest_path":json_path(&package_manifest_path)?, "entry_path":json_path(&directory.join(package_manifest.default_entry_path()))?, - "kind":if package_manifest.lib {"library"} else {"binary"}, "dependencies":dependencies})); + "kind":if package_manifest.lib {"library"} else {"binary"}, "native":crate::native::configuration(&package_manifest), "dependencies":dependencies})); } packages.sort_by(|a, b| a["name"].as_str().cmp(&b["name"].as_str())); let value: Value = json!({"schema_version":1, "root":{"name":manifest.name,"version":manifest.version,"manifest_format":manifest.format,"compiler":manifest.compiler,"kind":if manifest.lib {"library"} else {"binary"}, "root":root_text,"manifest_path":json_path(&project.manifest_path)?, - "entry_path":json_path(&root.join(manifest.default_entry_path()))?,"dependencies":root_dependencies}, + "entry_path":json_path(&root.join(manifest.default_entry_path()))?,"native":crate::native::configuration(&manifest),"dependencies":root_dependencies}, "target_directory":json_path(&root.join("target"))?, "packages":packages}); diagnostic::outln!( "{}", diff --git a/src/main.rs b/src/main.rs index d1866ba..42f757d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,7 @@ mod cli; mod commands; mod messages; +mod native; mod outcome; mod project; mod ui; diff --git a/src/native.rs b/src/native.rs new file mode 100644 index 0000000..49eb562 --- /dev/null +++ b/src/native.rs @@ -0,0 +1,310 @@ +//! Manifest-owned native linking. Foreign sources and build scripts are never executed. +use compiler::Compiler; +use diagnostic::Error; +use manifest::{Manifest, NativeOutput}; +use resolver::Resolution; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, BTreeSet}; +use std::path::{Path, PathBuf}; + +pub struct NativeBuild { + pub global: Vec, + pub inputs: Vec, + pub output: Vec, +} + +pub fn configuration(manifest: &Manifest) -> Value { + match &manifest.native { + None => Value::Null, + Some(config) => json!({ + "output":config.output.map(NativeOutput::as_str), + "libraries":config.libraries.iter().map(|lib| json!({"path":lib.path,"name":lib.name,"target":lib.target})).collect::>(), + "search_paths":config.search_paths.iter().map(|path| json!({"path":path.path,"target":path.target})).collect::>() + }), + } +} + +/// Validate selected native files while the dependency/project guard is held. +fn native_path(manifest: &Manifest, value: &str, directory: bool) -> Result { + let base = manifest + .source_path + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + let root = base.canonicalize().map_err(Error::environment)?; + let requested = root.join(value); + let path = requested.canonicalize().map_err(|e| { + Error::resolution(format!( + "native input `{value}` in package `{}` is unavailable: {e}", + manifest.name + )) + })?; + if !path.starts_with(&root) || (directory && !path.is_dir()) || (!directory && !path.is_file()) + { + return Err(Error::resolution(format!( + "native input `{value}` must be a {} inside package `{}`", + if directory { + "directory" + } else { + "regular file" + }, + manifest.name + ))); + } + path_text(&path) +} + +fn path_text(path: &Path) -> Result { + let path = path + .to_str() + .ok_or_else(|| Error::resolution("native compiler inputs require UTF-8 paths"))?; + #[cfg(windows)] + { + if let Some(tail) = path.strip_prefix(r"\\?\UNC\") { + return Ok(format!("//{}", tail.replace('\\', "/"))); + } + Ok(path + .strip_prefix(r"\\?\") + .unwrap_or(path) + .replace('\\', "/")) + } + #[cfg(not(windows))] + Ok(path.into()) +} + +fn named_library( + manifest: &Manifest, + name: &str, + search_paths: &[PathBuf], + object_format: &str, +) -> Result { + let (candidates, fallback) = match object_format { + "coff" => { + let library = if name.to_ascii_lowercase().ends_with(".lib") { + name.to_owned() + } else { + format!("{name}.lib") + }; + (vec![library.clone()], library) + } + "macho" => ( + vec![format!("lib{name}.dylib"), format!("lib{name}.a")], + format!("-l{name}"), + ), + _ => ( + vec![format!("lib{name}.so"), format!("lib{name}.a")], + format!("-l{name}"), + ), + }; + for directory in search_paths { + for candidate in &candidates { + let path = directory.join(candidate); + match std::fs::symlink_metadata(&path) { + Ok(_) => return native_path(manifest, &path_text(&path)?, false), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => { + return Err(Error::environment(format!( + "cannot inspect native library `{}`: {error}", + path.display() + ))) + } + } + } + } + // A package's search paths never influence another package's fallback. + // The compiler and linker retain their platform system-library discovery. + Ok(fallback) +} + +/// Dependent libraries precede their dependencies, including diamonds. Preserve +/// declaration order within a package because static archive order is significant. +fn manifests(root: &Manifest, resolution: &Resolution) -> Result, Error> { + let mut values = BTreeMap::from([(root.name.clone(), root.clone())]); + for package in resolution.packages() { + let directory = match &package.source { + lockfile::LockedSource::Git { resolved, .. } + | lockfile::LockedSource::Path { resolved, .. } => resolved, + }; + values.insert( + package.name.clone(), + Manifest::load_from(directory.join(manifest::MANIFEST_FILE))?, + ); + } + let mut incoming: BTreeMap<_, usize> = values.keys().map(|name| (name.clone(), 0)).collect(); + for manifest in values.values() { + for dependency in &manifest.dependencies { + *incoming.get_mut(&dependency.name).ok_or_else(|| { + Error::resolution("incomplete native dependency graph; run vex fetch") + })? += 1; + } + } + let mut ready: BTreeSet<_> = incoming + .iter() + .filter(|(_, count)| **count == 0) + .map(|(name, _)| name.clone()) + .collect(); + let mut result = Vec::new(); + while let Some(name) = ready.pop_first() { + let manifest = values.remove(&name).unwrap(); + for dependency in &manifest.dependencies { + let count = incoming.get_mut(&dependency.name).unwrap(); + *count -= 1; + if *count == 0 { + ready.insert(dependency.name.clone()); + } + } + result.push(manifest); + } + if !values.is_empty() { + return Err(Error::resolution("cycle in native dependency graph")); + } + Ok(result) +} + +pub fn prepare( + root: &Manifest, + resolution: &Resolution, + compiler: &mut Compiler, + target: Option<&str>, + release: bool, + check: bool, + generation: Option<&Path>, +) -> Result, Error> { + let manifests = manifests(root, resolution)?; + if !root.lib && !manifests.iter().any(|m| m.native.is_some()) { + return Ok(None); + } + let spec = compiler.target_spec(target)?; + let triple = spec["triple"].as_str().unwrap(); + let os = spec["os"].as_str().unwrap(); + if !matches!( + spec["object_format"].as_str(), + Some("elf" | "macho" | "coff") + ) { + return Err(Error::resolution( + "native C ABI artifacts require an ELF, Mach-O, or COFF target", + )); + } + let kind = if root.lib { + Some( + root.native + .as_ref() + .and_then(|n| n.output) + .unwrap_or(NativeOutput::Object), + ) + } else { + None + }; + if kind == Some(NativeOutput::Shared) && spec["hosted"] != true { + return Err(Error::resolution( + "shared libraries require a hosted target", + )); + } + let mut build = NativeBuild { + global: vec![format!("--target={triple}")], + inputs: Vec::new(), + output: Vec::new(), + }; + for manifest in &manifests { + let Some(native) = &manifest.native else { + continue; + }; + let mut search_paths = Vec::new(); + for search in &native.search_paths { + if search.target.as_deref().is_some_and(|t| t != triple) { + continue; + } + search_paths.push(PathBuf::from(native_path(manifest, &search.path, true)?)); + } + for library in &native.libraries { + if library.target.as_deref().is_some_and(|t| t != triple) { + continue; + } + let argument = if let Some(path) = &library.path { + native_path(manifest, path, false)? + } else { + named_library( + manifest, + library.name.as_deref().unwrap(), + &search_paths, + spec["object_format"].as_str().unwrap(), + )? + }; + if !check && kind != Some(NativeOutput::Object) { + // Keep paths and names in one sequence after Wave's objects. + // Repeated archives can be necessary, including across packages. + build.global.push(format!("-Clink-arg={argument}")); + } + } + } + if check { + return Ok(Some(build)); + } + let directory = generation.map(Path::to_path_buf).unwrap_or_else(|| { + PathBuf::from("target") + .join(triple) + .join(if release { "release" } else { "dev" }) + }); + let filename = match kind { + Some(NativeOutput::Object) => format!( + "{}.{}", + root.name, + if os == "windows" { "obj" } else { "o" } + ), + Some(NativeOutput::Shared) => match os { + "windows" => format!("{}.dll", root.name), + "macos" => format!("lib{}.dylib", root.name), + _ => format!("lib{}.so", root.name), + }, + None => format!("{}{}", root.name, if os == "windows" { ".exe" } else { "" }), + }; + if os == "windows" && windows_device_name(&filename) { + return Err(Error::resolution(format!( + "package `{}` produces reserved Windows output `{filename}`; choose a package name that is not a Windows device name", + root.name + ))); + } + build + .output + .extend(["-o".into(), path_text(&directory.join(filename))?]); + match kind { + Some(NativeOutput::Object) => build.output.push("--emit=obj".into()), + Some(NativeOutput::Shared) => { + build.output.push("--shared".into()); + build + .global + .extend(["-C".into(), "relocation-model=pic".into()]); + // wavec links through temporary files. Give the final library a + // stable loader identity instead of embedding that temporary path. + if os == "macos" { + build.global.extend([ + "-Clink-arg=-install_name".into(), + format!("-Clink-arg=@rpath/lib{}.dylib", root.name), + ]); + } else if spec["object_format"] == "elf" { + build.global.extend([ + "-Clink-arg=-soname".into(), + format!("-Clink-arg=lib{}.so", root.name), + ]); + } + } + None => {} + } + if kind != Some(NativeOutput::Object) { + build.output.push(format!( + "--target-dir={}", + path_text(&directory.join(".vex-obj").join(&root.name))? + )); + } + Ok(Some(build)) +} + +fn windows_device_name(filename: &str) -> bool { + let stem = filename.split('.').next().unwrap().to_ascii_uppercase(); + matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL") + || ["COM", "LPT"].into_iter().any(|prefix| { + stem.strip_prefix(prefix).is_some_and(|number| { + matches!(number, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9") + }) + }) +} diff --git a/state/src/artifacts.rs b/state/src/artifacts.rs index 703d07b..9cd0798 100644 --- a/state/src/artifacts.rs +++ b/state/src/artifacts.rs @@ -275,63 +275,167 @@ fn try_lease(root: &Path, name: &str) -> Result, String> { } } -/// Snapshots candidate outputs before compilation; preexisting unknown or -/// edited outputs are never adopted, even if the compiler overwrites them. +/// Check every declared destination before the compiler can write anything. +/// This does not create state, and is also used for dry-run plans. +pub fn validate_output_paths(root: &Path, outputs: &[PathBuf]) -> Result, String> { + let mut names = Vec::new(); + let mut identities = BTreeSet::::new(); + for output in outputs { + let path = if output.is_absolute() { + output + .strip_prefix(root) + .map_err(|_| "compiler output is outside the project")? + } else { + output + }; + let name = relative(path)?; + #[cfg(windows)] + for component in name.split('/') { + if component.ends_with(['.', ' ']) || component.contains(':') { + return Err(format!("ambiguous Windows compiler output `{name}`")); + } + } + let identity = if cfg!(any(windows, target_os = "macos")) { + name.to_lowercase() + } else { + name.clone() + }; + if identities.iter().any(|previous| { + previous == &identity + || identity.starts_with(&format!("{previous}/")) + || previous.starts_with(&format!("{identity}/")) + }) { + return Err(format!("compiler output destinations overlap at `{name}`")); + } + checked(root, &name)?; + identities.insert(identity); + names.push(name); + } + Ok(names) +} + +fn reject_hardlinked_output(path: &Path) -> Result<(), String> { + let file = match open_read(path) { + Ok(file) => file, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(error.to_string()), + }; + #[cfg(unix)] + let links = { + use std::os::unix::fs::MetadataExt; + file.metadata().map_err(|error| error.to_string())?.nlink() + }; + #[cfg(windows)] + let links = { + use std::os::windows::io::AsRawHandle; + #[link(name = "kernel32")] + unsafe extern "system" { + fn GetFileInformationByHandle(handle: *mut std::ffi::c_void, info: *mut u32) -> i32; + } + // BY_HANDLE_FILE_INFORMATION is thirteen DWORDs; number of links is + // DWORD 10. The handle remains open throughout this query. + let mut info = [0u32; 13]; + if unsafe { GetFileInformationByHandle(file.as_raw_handle(), info.as_mut_ptr()) } == 0 { + return Err(io::Error::last_os_error().to_string()); + } + u64::from(info[10]) + }; + if links > 1 { + return Err(format!( + "refusing to overwrite hard-linked compiler output `{}`", + path.display() + )); + } + Ok(()) +} + +/// Reserve compiler destinations. Only absent files or unchanged, previously +/// recorded artifacts may be replaced; user data must survive every build. pub struct Batch { root: PathBuf, registry: Registry, eligible: BTreeSet, + required: BTreeSet, } impl Batch { pub fn prepare( root: &Path, outputs: impl IntoIterator, + ) -> Result { + Self::prepare_with_optional(root, outputs, []) + } + + /// Linkers can produce optional companions that still need overwrite and + /// ownership protection, even when a particular build does not emit them. + pub fn prepare_with_optional( + root: &Path, + outputs: impl IntoIterator, + optional: impl IntoIterator, ) -> Result { let mut registry = read(root)?; let mut eligible = BTreeSet::new(); - for output in outputs { - let path = if output.is_absolute() { - output - .strip_prefix(root) - .map_err(|_| "compiler output is outside the project")? - } else { - &output - }; - // Other compiler-managed locations are outside clean's ownership. - let Ok(name) = relative(path) else { continue }; + let mut outputs: Vec<_> = outputs.into_iter().collect(); + let required = validate_output_paths(root, &outputs)?.into_iter().collect(); + outputs.extend(optional); + for name in validate_output_paths(root, &outputs)? { if let Some(tail) = name.strip_prefix("target/.vex-run/") { if !registry .generations .contains(tail.split('/').next().unwrap()) { - continue; + return Err("compiler output has no owned run generation".into()); } } let absolute = checked(root, &name)?; let current = fingerprint(&absolute)?; let owned = registry.files.get(&name); - if current.is_none() || current.as_ref() == owned { - eligible.insert(name); - for parent in path - .ancestors() - .skip(1) - .take_while(|p| p.components().count() > 1) - { - let name = relative(parent)?; - if !root.join(parent).exists() { - registry.directories.insert(name); - } + if current.is_some() && current.as_ref() != owned { + return Err(format!( + "refusing to overwrite unowned or modified compiler output `{name}`; move it before rebuilding" + )); + } + reject_hardlinked_output(&absolute)?; + for parent in Path::new(&name) + .ancestors() + .skip(1) + .take_while(|p| p.components().count() > 1) + { + let name = relative(parent)?; + if !root.join(parent).exists() { + registry.directories.insert(name); } - } else { - registry.files.remove(&name); } + eligible.insert(name); } Ok(Self { root: root.to_owned(), registry, eligible, + required, }) } + + /// A successful compiler must actually produce every promised artifact. + pub fn verify_outputs(&self) -> Result<(), String> { + for name in &self.eligible { + let path = checked(&self.root, name)?; + let metadata = match fs::symlink_metadata(&path) { + Ok(metadata) => metadata, + Err(error) + if error.kind() == io::ErrorKind::NotFound && !self.required.contains(name) => + { + continue + } + Err(error) => return Err(format!("compiler did not produce `{name}`: {error}")), + }; + if !metadata.is_file() { + return Err(format!("compiler output `{name}` is not a regular file")); + } + reject_hardlinked_output(&path)?; + } + Ok(()) + } + /// Record partial outputs too, so a failed compile can be cleaned safely. pub fn finish(mut self) -> Result<(), String> { for name in self.eligible { diff --git a/tests/build_artifact_integrity.rs b/tests/build_artifact_integrity.rs new file mode 100644 index 0000000..0b3f688 --- /dev/null +++ b/tests/build_artifact_integrity.rs @@ -0,0 +1,386 @@ +use serde_json::{json, Value}; +use std::fs; +use std::path::PathBuf; +use std::process::{Command, Output}; +use std::sync::{ + atomic::{AtomicU64, Ordering}, + OnceLock, +}; + +const COMPILER_SOURCE: &str = r#" +use std::{env, fs, path::Path, process}; +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.iter().any(|arg| arg == "--dry-run") { + println!("{}", env::var("PLAN").unwrap()); + return; + } + fs::write("compiled", "compiler started").unwrap(); + for path in env::var("OUTPUTS").unwrap_or_default().lines() { + let path = Path::new(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(); + } + } + if env::var_os("FAIL_OWNERSHIP").is_some() { + fs::create_dir(".vex/artifacts.json").unwrap(); + } + let code = env::var("COMPILE_EXIT").unwrap_or_else(|_| "0".into()).parse().unwrap(); + if code != 0 { eprintln!("fixture compiler diagnostic"); } + process::exit(code); +} +"#; + +struct Fixture { + root: PathBuf, +} +impl Fixture { + fn new() -> Self { + static ID: AtomicU64 = AtomicU64::new(0); + let root = std::env::temp_dir().join(format!( + "vex artifact integrity {} {}", + std::process::id(), + ID.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(root.join("src")).unwrap(); + fs::write(root.join("vex.ws"), "{name=\"app\",version=0.1.0}").unwrap(); + fs::write(root.join("src/main.wave"), "fun main() {}\n").unwrap(); + Self { root } + } + fn command(&self, plan: &Value, outputs: &[&str]) -> Command { + static COMPILER: OnceLock = OnceLock::new(); + let compiler = COMPILER.get_or_init(|| { + let root = + std::env::temp_dir().join(format!("vex-artifact-compiler-{}", std::process::id())); + fs::create_dir_all(&root).unwrap(); + let source = root.join("fake.rs"); + fs::write(&source, COMPILER_SOURCE).unwrap(); + let compiler = root.join(if cfg!(windows) { "wavec.exe" } else { "wavec" }); + assert!(Command::new("rustc") + .arg(source) + .arg("-o") + .arg(&compiler) + .status() + .unwrap() + .success()); + compiler + }); + let mut command = Command::new(env!("CARGO_BIN_EXE_vex")); + command + .current_dir(&self.root) + .env("VEX_WAVEC", compiler) + .env("PLAN", plan.to_string()) + .env("OUTPUTS", outputs.join("\n")) + .env("NO_COLOR", "1"); + command + } + fn build(&self, plan: &Value, outputs: &[&str]) -> Output { + self.command(plan, outputs).arg("build").output().unwrap() + } + fn clean(&self) { + let output = Command::new(env!("CARGO_BIN_EXE_vex")) + .arg("clean") + .current_dir(&self.root) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + } + fn events(&self) -> Vec { + fs::read_to_string(self.root.join("messages.jsonl")) + .unwrap() + .lines() + .map(|line| serde_json::from_str(line).unwrap()) + .collect() + } +} +impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.root); + } +} + +fn plan(outputs: &[&str]) -> Value { + json!({"schema_version":1,"mode":"build","target":"x86_64-unknown-linux-gnu","emit":"obj","emit_kinds":["obj"],"control_mode":null,"forced_input_type":null,"inputs":[{"path":"src/main.wave","kind":"wave"}],"emit_jobs":[],"compile":outputs.iter().map(|output| json!({"input":"src/main.wave","kind":"wave","output":output,"command":"compiler"})).collect::>(),"link":null,"execute":null}) +} +fn assert_code(output: &Output, code: i32) { + assert_eq!( + output.status.code(), + Some(code), + "{}", + String::from_utf8_lossy(&output.stderr) + ); +} + +#[test] +fn unknown_and_modified_outputs_are_rejected_before_compiler_execution() { + for modified in [false, true] { + let f = Fixture::new(); + let plan = plan(&["target/result.o"]); + if modified { + assert_code(&f.build(&plan, &["target/result.o"]), 0); + fs::remove_file(f.root.join("compiled")).unwrap(); + } else { + fs::create_dir(f.root.join("target")).unwrap(); + } + fs::write(f.root.join("target/result.o"), b"user content").unwrap(); + let registry = fs::read(f.root.join(".vex/artifacts.json")).ok(); + assert_code(&f.build(&plan, &["target/result.o"]), 5); + assert!(!f.root.join("compiled").exists()); + assert_eq!( + fs::read(f.root.join("target/result.o")).unwrap(), + b"user content" + ); + assert_eq!(fs::read(f.root.join(".vex/artifacts.json")).ok(), registry); + f.clean(); + assert_eq!( + fs::read(f.root.join("target/result.o")).unwrap(), + b"user content" + ); + } +} + +#[test] +fn unchanged_owned_outputs_can_be_rebuilt_and_cleaned() { + let f = Fixture::new(); + let plan = plan(&["target/result.o"]); + for _ in 0..2 { + assert_code(&f.build(&plan, &["target/result.o"]), 0); + } + f.clean(); + assert!(!f.root.join("target/result.o").exists()); +} + +#[test] +fn missing_or_nonregular_outputs_do_not_publish_artifact_success() { + for directory in [false, true] { + let f = Fixture::new(); + let plan = plan(&["target/result.o", "target/partial.o"]); + let mut command = f.command(&plan, &["target/partial.o"]); + if directory { + command.env("DIRECTORY_OUTPUT", "1"); + } + let output = command + .args(["--message-file", "messages.jsonl", "build"]) + .output() + .unwrap(); + assert_code(&output, 4); + let events = f.events(); + assert!(!events.iter().any(|event| event["event"] == "artifact")); + assert_eq!(events.last().unwrap()["category"], "compiler"); + if !directory { + f.clean(); + assert!(!f.root.join("target/partial.o").exists()); + } + } +} + +#[test] +fn ownership_failure_preserves_primary_compiler_error_and_structured_context() { + for (compiler_code, expected) in [(1, 4), (3, 5), (0, 5)] { + let f = Fixture::new(); + let output = f + .command(&plan(&["target/result.o"]), &["target/result.o"]) + .args(["--message-file", "messages.jsonl", "build"]) + .env("COMPILE_EXIT", compiler_code.to_string()) + .env("FAIL_OWNERSHIP", "1") + .output() + .unwrap(); + assert_code(&output, expected); + let events = f.events(); + assert!(!events.iter().any(|event| event["event"] == "artifact")); + if compiler_code != 0 { + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("wavec build failed"), "{stderr}"); + let error = events + .iter() + .find(|event| event["event"] == "diagnostic") + .unwrap(); + assert!(error["context"] + .to_string() + .contains("artifact_ownership_error")); + } + } +} + +#[test] +fn escaping_duplicate_and_overlapping_outputs_fail_before_execution() { + for paths in [ + vec!["src/main.wave"], + vec!["target/../src/main.wave"], + vec!["target/a.o", "target/a.o"], + vec!["target/a.o", "target/./a.o"], + vec!["target/output", "target/output/a.o"], + ] { + let f = Fixture::new(); + let output = f.build(&plan(&paths), &paths); + assert_code(&output, 4); + assert!(!f.root.join("compiled").exists()); + assert_eq!( + fs::read(f.root.join("src/main.wave")).unwrap(), + b"fun main() {}\n" + ); + } +} + +#[test] +fn direct_input_and_final_output_aliases_are_rejected() { + let f = Fixture::new(); + let mut plan = plan(&["target/result.o"]); + assert_code(&f.build(&plan, &["target/result.o"]), 0); + fs::remove_file(f.root.join("compiled")).unwrap(); + plan["inputs"][0]["path"] = json!("target/result.o"); + assert_code(&f.build(&plan, &["target/result.o"]), 4); + assert!(!f.root.join("compiled").exists()); +} + +#[test] +fn hard_links_to_owned_outputs_are_not_overwritten() { + let f = Fixture::new(); + let plan = plan(&["target/result.o"]); + assert_code(&f.build(&plan, &["target/result.o"]), 0); + fs::remove_file(f.root.join("compiled")).unwrap(); + fs::hard_link(f.root.join("target/result.o"), f.root.join("preserve.o")).unwrap(); + assert_code(&f.build(&plan, &["target/result.o"]), 5); + assert!(!f.root.join("compiled").exists()); + assert_eq!( + fs::read(f.root.join("preserve.o")).unwrap(), + b"compiled artifact" + ); +} + +fn msvc_plan() -> Value { + let mut plan = plan(&["target/native/input.o"]); + plan["target"] = json!("x86_64-pc-windows-msvc"); + plan["emit"] = json!("bin"); + plan["link"] = json!({"output":"target/native/answer.dll","inputs":["target/native/input.o"],"program":"lld-link","args":["/OUT:target/native/answer.dll","/DLL"]}); + plan +} + +#[test] +fn optional_msvc_companions_are_reported_and_cleaned_only_when_produced() { + let f = Fixture::new(); + let outputs = [ + "target/native/input.o", + "target/native/answer.dll", + "target/native/answer.lib", + "target/native/answer.exp", + ]; + let output = f + .command(&msvc_plan(), &outputs) + .args(["--message-file", "messages.jsonl", "build"]) + .output() + .unwrap(); + assert_code(&output, 0); + let events = f.events(); + let artifact = events + .iter() + .find(|event| event["event"] == "artifact") + .unwrap(); + let paths = artifact["paths"].as_array().unwrap(); + for expected in &outputs[1..] { + assert!(paths.contains(&json!(expected))); + } + assert_eq!(paths.len(), 3); + f.clean(); + for output in outputs { + assert!(!f.root.join(output).exists()); + } +} + +#[test] +fn optional_msvc_output_collisions_and_unowned_files_are_protected() { + for sidecar in [ + "answer.lib", + "answer.exp", + "answer.pdb", + "answer.ilk", + "answer.map", + "answer.dll.manifest", + ] { + let f = Fixture::new(); + fs::create_dir_all(f.root.join("target/native")).unwrap(); + let path = f.root.join("target/native").join(sidecar); + fs::write(&path, "user content").unwrap(); + assert_code(&f.build(&msvc_plan(), &[]), 5); + assert!(!f.root.join("compiled").exists()); + assert_eq!(fs::read(path).unwrap(), b"user content"); + } + let f = Fixture::new(); + let mut plan = msvc_plan(); + plan["link"]["args"] + .as_array_mut() + .unwrap() + .push(json!("/PDB:target/native/input.o")); + assert_code(&f.build(&plan, &[]), 4); + assert!(!f.root.join("compiled").exists()); +} + +#[test] +fn dry_run_validates_destinations_without_creating_outputs() { + let f = Fixture::new(); + let fetch = Command::new(env!("CARGO_BIN_EXE_vex")) + .args(["fetch", "--offline"]) + .current_dir(&f.root) + .output() + .unwrap(); + assert_code(&fetch, 0); + let output = f + .command(&plan(&["src/main.wave"]), &[]) + .args(["build", "--dry-run", "--locked", "--offline"]) + .output() + .unwrap(); + assert_code(&output, 4); + assert!(!f.root.join("target").exists()); + assert!(!f.root.join("compiled").exists()); +} + +#[cfg(any(windows, target_os = "macos"))] +#[test] +fn case_only_output_aliases_are_rejected_on_case_insensitive_hosts() { + let f = Fixture::new(); + assert_code( + &f.build(&plan(&["target/answer.o", "target/ANSWER.o"]), &[]), + 4, + ); + assert!(!f.root.join("compiled").exists()); +} + +#[cfg(windows)] +#[test] +fn windows_trailing_dot_and_alternate_stream_destinations_are_rejected() { + for path in [ + "target/answer.o.", + "target/answer.o ", + "target/answer.o:stream", + ] { + let f = Fixture::new(); + assert_code(&f.build(&plan(&[path]), &[]), 4); + assert!(!f.root.join("compiled").exists()); + } +} + +#[cfg(unix)] +#[test] +fn symlink_destinations_are_rejected_before_compilation() { + use std::os::unix::fs::symlink; + let f = Fixture::new(); + fs::create_dir(f.root.join("target")).unwrap(); + symlink(f.root.join("src/main.wave"), f.root.join("target/result.o")).unwrap(); + assert_code(&f.build(&plan(&["target/result.o"]), &[]), 4); + assert!(!f.root.join("compiled").exists()); + assert_eq!( + fs::read(f.root.join("src/main.wave")).unwrap(), + b"fun main() {}\n" + ); +} diff --git a/tests/clean.rs b/tests/clean.rs index 774d880..e3c1404 100644 --- a/tests/clean.rs +++ b/tests/clean.rs @@ -134,23 +134,34 @@ fn removes_only_new_unchanged_outputs_and_dry_run_preserves_everything() { } #[test] -fn modified_and_preexisting_outputs_are_never_adopted() { +fn modified_and_preexisting_outputs_are_preserved_before_compilation() { let f = Fixture::new(); fs::create_dir(f.root.join("target")).unwrap(); fs::write(f.root.join("target/legacy.o"), "old compiler output").unwrap(); - f.build("target/legacy.o", false); + let output = f + .command(&["build"]) + .env("FAKE_BUILD_OUTPUT", "target/legacy.o") + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(5)); + assert_eq!( + fs::read(f.root.join("target/legacy.o")).unwrap(), + b"old compiler output" + ); f.build("target/edited.o", false); fs::write(f.root.join("target/edited.o"), "user change").unwrap(); f.ok(&["clean"]); - assert!(f.root.join("target/legacy.o").is_file()); + let output = f + .command(&["build"]) + .env("FAKE_BUILD_OUTPUT", "target/edited.o") + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(5)); + f.ok(&["clean"]); assert_eq!( fs::read(f.root.join("target/edited.o")).unwrap(), b"user change" ); - // Rebuilding a modified output does not retroactively reclaim ownership. - f.build("target/edited.o", false); - f.ok(&["clean"]); - assert!(f.root.join("target/edited.o").is_file()); } #[test] diff --git a/tests/doctor.rs b/tests/doctor.rs index 436c4bc..095bc98 100644 --- a/tests/doctor.rs +++ b/tests/doctor.rs @@ -128,7 +128,8 @@ fn main() { assert!(!args.iter().any(|s| s == "--run"), "doctor must not run"); if let Ok(error) = env::var("DOCTOR_ERROR") { eprintln!("{error}"); std::process::exit(env::var("DOCTOR_EXIT").ok().and_then(|s| s.parse().ok()).unwrap_or(1)); } let schema = env::var("DOCTOR_SCHEMA").unwrap_or_else(|_| "1".into()); - let link = env::var("DOCTOR_LINK").map(|p| format!("{{\"output\":\"target/main\",\"inputs\":[],\"program\":{p:?},\"args\":[]}}")).unwrap_or_else(|_| "null".into()); + let link_output = env::var("DOCTOR_LINK_OUTPUT").unwrap_or_else(|_| "target/main".into()); + let link = env::var("DOCTOR_LINK").map(|p| format!("{{\"output\":{link_output:?},\"inputs\":[],\"program\":{p:?},\"args\":[]}}")).unwrap_or_else(|_| "null".into()); println!("{{\"schema_version\":{schema},\"mode\":\"build\",\"target\":\"test-target\",\"emit\":\"bin\",\"emit_kinds\":[],\"control_mode\":null,\"forced_input_type\":null,\"inputs\":[],\"emit_jobs\":[],\"compile\":[],\"link\":{link},\"execute\":null}}"); } "###).unwrap(); @@ -429,3 +430,33 @@ fn unknown_options_and_help_do_not_spawn_tools() { assert!(String::from_utf8_lossy(&out.stdout).contains("usage: vex doctor")); assert!(f.calls().is_empty()); } + +#[test] +fn unsafe_compiler_outputs_fail_doctor_before_linker_checks_without_writes() { + for output in ["src/main.wave", "target/../src/main.wave"] { + let f = Fixture::new(); + f.project(true); + let before = snapshot(&f.work); + let out = f + .command() + .env("DOCTOR_LINK", "missing-doctor-linker") + .env("DOCTOR_LINK_OUTPUT", output) + .args(["doctor", "--format=json"]) + .output() + .unwrap(); + assert_eq!(out.status.code(), Some(4)); + let report = document(&out); + assert_eq!(report["success"], false); + assert_eq!(check(&report, "dry_run")["status"], "error"); + assert!(check(&report, "dry_run")["message"] + .as_str() + .unwrap() + .contains("strictly inside target")); + assert!(!report["checks"] + .as_array() + .unwrap() + .iter() + .any(|item| item["id"] == "linker")); + assert_eq!(before, snapshot(&f.work)); + } +} diff --git a/tests/fixtures/fake_wavec.rs b/tests/fixtures/fake_wavec.rs index 5f370c9..a3ad880 100644 --- a/tests/fixtures/fake_wavec.rs +++ b/tests/fixtures/fake_wavec.rs @@ -57,6 +57,14 @@ fn main() { writeln!(log, "{}", args.join(" ")).unwrap(); } if args.first().is_some_and(|s| s == "print") { + if args.get(1).is_some_and(|s| s == "target-spec") { + let target = args.iter().find_map(|a| a.strip_prefix("--target=")).unwrap_or("x86_64-unknown-linux-gnu"); + let (os, format) = if target.contains("windows") { ("windows", "coff") } + else if target.contains("darwin") { ("macos", "macho") } + else { ("linux", "elf") }; + println!("{{\"triple\":{target:?},\"os\":{os:?},\"object_format\":{format:?},\"hosted\":true,\"supported\":true}}"); + return; + } assert_eq!(args, ["print", "supported-targets", "--format=json"]); println!("{}", env::var("FAKE_TARGETS").unwrap_or_else(|_| "[\"x86_64-unknown-linux-gnu\",\"aarch64-unknown-linux-gnu\"]".into())); return; diff --git a/tests/native_build.rs b/tests/native_build.rs new file mode 100644 index 0000000..36d7fb3 --- /dev/null +++ b/tests/native_build.rs @@ -0,0 +1,632 @@ +use serde_json::{json, Value}; +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; +use std::sync::{ + atomic::{AtomicU64, Ordering}, + OnceLock, +}; + +// An independent process boundary: this fixture accepts compiler arguments and +// reports their actual outputs; it does not depend on Vex's native model. +const COMPILER_SOURCE: &str = r#" +use std::{env, fs, io::Write, path::PathBuf}; +fn quote(value: &str) -> String { + let mut text = String::from("\""); + for ch in value.chars() { + match ch { + '\\' => text.push_str("\\\\"), '"' => text.push_str("\\\""), + '\n' => text.push_str("\\n"), '\r' => text.push_str("\\r"), + '\t' => text.push_str("\\t"), + c if c.is_control() => text.push_str(&format!("\\u{:04x}", c as u32)), + c => text.push(c), + } + } + text.push('"'); text +} +fn list(values: &[String]) -> String { + format!("[{}]", values.iter().map(|s| quote(s)).collect::>().join(",")) +} +fn main() { + let args: Vec<_> = env::args().skip(1).collect(); + if !env::current_exe().unwrap().file_stem().unwrap().to_string_lossy().starts_with("fake-native-wavec") { + fs::write("program-started", list(&args)).unwrap(); + println!("native fixture program"); + std::process::exit(17); + } + if let Some(path) = env::var_os("NATIVE_COMPILER_LOG") { + let mut log = fs::OpenOptions::new().create(true).append(true).open(path).unwrap(); + writeln!(log, "{}", list(&args)).unwrap(); + } + if args.iter().any(|s| s == "--version") { println!("wavec 0.2.1-pre-beta"); return; } + let value = |flag: &str| args.iter().find_map(|s| s.strip_prefix(&format!("{flag}=")).map(str::to_owned)) + .or_else(|| args.iter().position(|s| s == flag).and_then(|i| args.get(i+1).cloned())); + let target = value("--target").unwrap_or_else(|| env::var("NATIVE_DEFAULT_TARGET").unwrap_or_else(|_| "x86_64-unknown-linux-gnu".into())); + if args.first().is_some_and(|s| s == "print") { + if args.get(1).is_some_and(|s| s == "supported-targets") { + println!("[\"x86_64-unknown-linux-gnu\",\"aarch64-unknown-linux-gnu\",\"x86_64-pc-windows-msvc\",\"aarch64-pc-windows-msvc\",\"x86_64-apple-darwin\",\"aarch64-apple-darwin\"]"); + } else if let Ok(bad) = env::var("NATIVE_BAD_SPEC") { println!("{bad}"); } + else { + let (os, format) = if target.contains("windows") { ("windows", "coff") } + else if target.contains("apple") { ("macos", "macho") } else { ("linux", "elf") }; + println!("{{\"triple\":{},\"supported\":true,\"hosted\":true,\"os\":{},\"object_format\":{}}}", quote(&target), quote(os), quote(format)); + } + return; + } + let check = args.iter().any(|s| s == "--emit=check"); + let object = args.iter().any(|s| s == "--emit=obj"); + let run = args.iter().any(|s| s == "--run"); + let input = args.iter().find(|s| s.ends_with(".wave")).unwrap(); + let output = value("-o").unwrap_or_else(|| "target/default-program".into()); + let intermediate = if object { output.clone() } + else { PathBuf::from(value("--target-dir").unwrap_or_else(|| "target".into())).join("native.o").to_string_lossy().into_owned() }; + if args.iter().any(|s| s == "--dry-run") { + let emit = if check { "check" } else if object { "obj" } else { "bin" }; + let compile = if check { "[]".into() } else { format!("[{{\"input\":{},\"kind\":\"wave\",\"output\":{},\"command\":\"fixture compile\"}}]", quote(input), quote(&intermediate)) }; + let native_args: Vec<_> = args.iter().filter_map(|arg| arg.strip_prefix("-Clink-arg=").map(str::to_owned)).collect(); + let link = if check || object { "null".into() } else { format!("{{\"output\":{},\"inputs\":[{}],\"program\":\"fixture linker\",\"args\":{}}}", quote(&output), quote(&intermediate), list(&native_args)) }; + let execute = if run { format!("{{\"program\":{},\"args\":[]}}", quote(&output)) } else { "null".into() }; + println!("{{\"schema_version\":1,\"mode\":{},\"target\":{},\"emit\":{},\"emit_kinds\":[],\"control_mode\":null,\"forced_input_type\":null,\"inputs\":[{{\"path\":{},\"kind\":\"wave\"}}],\"emit_jobs\":[],\"compile\":{},\"link\":{},\"execute\":{}}}", quote(if run { "build+run" } else { "build" }), quote(&target), quote(emit), quote(input), compile, link, execute); + return; + } + fs::write("compiler-started", list(&args)).unwrap(); + if !check { + for path in if object { vec![intermediate] } else { vec![intermediate, output.clone()] } { + let path = PathBuf::from(path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, b"native artifact").unwrap(); + } + if output.contains(".vex-run") { fs::copy(env::current_exe().unwrap(), output).unwrap(); } + } +} +"#; + +struct Fixture { + root: PathBuf, + project: PathBuf, +} +impl Fixture { + fn new(lib: bool, native: &str) -> Self { + static ID: AtomicU64 = AtomicU64::new(0); + let root = std::env::temp_dir().join(format!( + "vex native build {} {}", + std::process::id(), + ID.fetch_add(1, Ordering::Relaxed) + )); + let project = root.join("app"); + let fixture = Self { root, project }; + fixture.package("app", lib, native, ""); + fs::write(fixture.project.join("vex.lock"), "{version=3,package=[]}\n").unwrap(); + fixture + } + fn package(&self, name: &str, lib: bool, native: &str, dependencies: &str) -> PathBuf { + let root = self.root.join(name); + fs::create_dir_all(root.join("src")).unwrap(); + fs::write( + root.join("vex.ws"), + format!("{{format=2,name=\"{name}\",lib={lib},dependencies=[{dependencies}]{native}}}"), + ) + .unwrap(); + fs::write( + root.join(if lib { "src/lib.wave" } else { "src/main.wave" }), + "fun main() {}\n", + ) + .unwrap(); + root + } + fn command(&self) -> Command { + static COMPILER: OnceLock = OnceLock::new(); + let compiler = COMPILER.get_or_init(|| { + let root = + std::env::temp_dir().join(format!("vex-native-compiler-{}", std::process::id())); + fs::create_dir_all(&root).unwrap(); + let source = root.join("fixture.rs"); + fs::write(&source, COMPILER_SOURCE).unwrap(); + let compiler = root.join(if cfg!(windows) { + "fake-native-wavec.exe" + } else { + "fake-native-wavec" + }); + let output = Command::new("rustc") + .args(["--edition=2021"]) + .arg(&source) + .arg("-o") + .arg(&compiler) + .output() + .unwrap(); + code(&output, 0); + compiler + }); + let mut command = Command::new(env!("CARGO_BIN_EXE_vex")); + command + .current_dir(&self.project) + .env("VEX_WAVEC", compiler) + .env("NATIVE_COMPILER_LOG", self.root.join("compiler.jsonl")) + .env("NO_COLOR", "1"); + command + } + fn run(&self, args: &[&str]) -> Output { + self.command().args(args).output().unwrap() + } + fn invocations(&self) -> Vec> { + fs::read_to_string(self.root.join("compiler.jsonl")) + .unwrap_or_default() + .lines() + .map(|line| serde_json::from_str(line).unwrap()) + .collect() + } + fn build_arguments(&self) -> Vec { + self.invocations() + .into_iter() + .rev() + .find(|args| args.iter().any(|arg| arg == "build")) + .expect("compiler build invocation") + } +} +impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.root); + } +} +fn code(output: &Output, expected: i32) { + assert_eq!( + output.status.code(), + Some(expected), + "stdout: {}\nstderr: {}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); +} +fn plan(output: &Output) -> Value { + code(output, 0); + serde_json::from_slice(&output.stdout).unwrap() +} +fn snapshot(root: &Path) -> BTreeMap> { + fn visit(root: &Path, directory: &Path, result: &mut BTreeMap>) { + for entry in fs::read_dir(directory).unwrap() { + let path = entry.unwrap().path(); + let metadata = fs::symlink_metadata(&path).unwrap(); + let relative = path.strip_prefix(root).unwrap().to_owned(); + if metadata.is_dir() { + result.insert(relative, Vec::new()); + visit(root, &path, result); + } else if metadata.is_file() { + result.insert(relative, fs::read(&path).unwrap()); + } + } + } + let mut result = BTreeMap::new(); + visit(root, root, &mut result); + result +} +fn assert_path(actual: &str, expected: &Path) { + assert_eq!( + Path::new(actual).canonicalize().unwrap(), + expected.canonicalize().unwrap() + ); +} +fn flag_value<'a>(args: &'a [String], flag: &str) -> &'a str { + let index = args.iter().position(|arg| arg == flag).unwrap(); + &args[index + 1] +} + +fn link_arguments(args: &[String]) -> Vec<&str> { + args.iter() + .filter_map(|arg| arg.strip_prefix("-Clink-arg=")) + .collect() +} + +#[test] +fn dry_run_selects_package_target_and_profile_outputs_without_mutation() { + for (lib, native, emit, filename) in [ + (false, ",native={}", "bin", "app"), + (true, "", "obj", "app.o"), + (true, ",native={output=\"object\"}", "obj", "app.o"), + (true, ",native={output=\"shared\"}", "bin", "libapp.so"), + ] { + let f = Fixture::new(lib, native); + code(&f.run(&["fetch"]), 0); + let before = snapshot(&f.project); + let value = plan(&f.run(&["build", "--release", "--dry-run"])); + assert_eq!(value["target"], "x86_64-unknown-linux-gnu"); + assert_eq!(value["emit"], emit); + let output = if emit == "obj" { + &value["compile"][0]["output"] + } else { + &value["link"]["output"] + }; + assert_eq!( + output, + &json!(format!( + "target/x86_64-unknown-linux-gnu/release/{filename}" + )) + ); + assert_eq!(snapshot(&f.project), before); + assert!(!f.project.join("compiler-started").exists()); + assert_eq!( + f.invocations() + .iter() + .filter(|args| args.iter().any(|arg| arg == "target-spec")) + .count(), + 1 + ); + } +} + +#[test] +fn explicit_targets_choose_windows_and_macos_library_names() { + for (target, native, filename) in [ + ("aarch64-pc-windows-msvc", "object", "app.obj"), + ("x86_64-pc-windows-msvc", "shared", "app.dll"), + ("aarch64-apple-darwin", "shared", "libapp.dylib"), + ] { + let f = Fixture::new(true, &format!(",native={{output=\"{native}\"}}")); + let value = plan(&f.run(&["build", "--target", target, "--dry-run"])); + let output = if native == "object" { + &value["compile"][0]["output"] + } else { + &value["link"]["output"] + }; + assert_eq!(output, &json!(format!("target/{target}/dev/{filename}"))); + assert_eq!(value["target"], target); + assert!(!f.project.join("target").exists()); + } +} + +#[test] +fn root_and_transitive_inputs_use_the_declaring_package_and_preserve_link_order() { + let f = Fixture::new(false, ""); + let leaf = f.package( + "leaf", + true, + ",native={libraries=[{path=\"native/leaf.a\"}],search_paths=[{path=\"native\"}]}", + "", + ); + let middle = f.package( + "middle", + true, + ",native={libraries=[{path=\"native/middle.a\"}]}", + "{name=\"leaf\",path=\"../leaf\"}", + ); + f.package("app", false, ",native={libraries=[{path=\"native/root.o\"},{name=\"system_math\"}],search_paths=[{path=\"native\"}]}", "{name=\"middle\",path=\"../middle\"}"); + for (root, filename) in [ + (&f.project, "root.o"), + (&middle, "middle.a"), + (&leaf, "leaf.a"), + ] { + fs::create_dir(root.join("native")).unwrap(); + fs::write(root.join("native").join(filename), "prebuilt input").unwrap(); + } + code(&f.run(&["fetch"]), 0); + let lock = fs::read(f.project.join("vex.lock")).unwrap(); + code(&f.run(&["build", "--locked", "--offline"]), 0); + let args = f.build_arguments(); + let inputs = link_arguments(&args); + assert_eq!(inputs.len(), 4); + assert_eq!(inputs[1], "-lsystem_math"); + for (actual, expected) in [inputs[0], inputs[2], inputs[3]].iter().zip([ + f.project.join("native/root.o"), + middle.join("native/middle.a"), + leaf.join("native/leaf.a"), + ]) { + assert_path(actual, &expected); + } + assert!(!args.iter().any(|arg| arg == "-L" || arg == "--link")); + assert_eq!(fs::read(f.project.join("vex.lock")).unwrap(), lock); + assert!(f + .project + .join("target/x86_64-unknown-linux-gnu/dev/app") + .is_file()); +} + +#[test] +fn mixed_named_and_path_archives_preserve_manifest_order() { + let f = Fixture::new(false, ",native={libraries=[{name=\"first\"},{path=\"native/second.a\"},{name=\"last\"}],search_paths=[{path=\"native\"}]}"); + fs::create_dir(f.project.join("native")).unwrap(); + for name in ["libfirst.a", "second.a", "liblast.a"] { + fs::write(f.project.join("native").join(name), name).unwrap(); + } + plan(&f.run(&["build", "--dry-run"])); + let args = f.build_arguments(); + let inputs = link_arguments(&args); + assert_eq!(inputs.len(), 3, "{args:?}"); + for (input, name) in inputs.iter().zip(["libfirst.a", "second.a", "liblast.a"]) { + assert_path(input, &f.project.join("native").join(name)); + } + assert!(!args.iter().any(|arg| arg == "-L" || arg == "--link")); +} + +#[test] +fn same_library_name_is_resolved_independently_for_each_declaring_package() { + let f = Fixture::new(false, ""); + let native = ",native={libraries=[{name=\"private_impl\"}],search_paths=[{path=\"native\"}]}"; + let leaf = f.package("leaf", true, native, ""); + f.package("app", false, native, "{name=\"leaf\",path=\"../leaf\"}"); + for (root, contents) in [ + (&f.project, "root implementation"), + (&leaf, "leaf implementation"), + ] { + fs::create_dir(root.join("native")).unwrap(); + fs::write(root.join("native/libprivate_impl.a"), contents).unwrap(); + } + code(&f.run(&["fetch"]), 0); + plan(&f.run(&["build", "--locked", "--offline", "--dry-run"])); + let args = f.build_arguments(); + let inputs = link_arguments(&args); + assert_eq!(inputs.len(), 2, "{args:?}"); + assert_path(inputs[0], &f.project.join("native/libprivate_impl.a")); + assert_path(inputs[1], &leaf.join("native/libprivate_impl.a")); + assert!(!args.iter().any(|arg| arg == "-L" || arg == "--link")); +} + +#[test] +fn native_named_library_uses_target_specific_shared_then_static_candidates() { + for (target, names, selected) in [ + ( + "x86_64-unknown-linux-gnu", + ["libchoice.so", "libchoice.a"], + "libchoice.so", + ), + ( + "aarch64-apple-darwin", + ["libchoice.dylib", "libchoice.a"], + "libchoice.dylib", + ), + ( + "x86_64-pc-windows-msvc", + ["choice.lib", "libchoice.a"], + "choice.lib", + ), + ] { + let f = Fixture::new( + false, + ",native={libraries=[{name=\"choice\"}],search_paths=[{path=\"native\"}]}", + ); + fs::create_dir(f.project.join("native")).unwrap(); + for name in names { + fs::write(f.project.join("native").join(name), name).unwrap(); + } + plan(&f.run(&["build", "--target", target, "--dry-run"])); + let args = f.build_arguments(); + let inputs = link_arguments(&args); + assert_eq!(inputs.len(), 1, "{args:?}"); + assert_path(inputs[0], &f.project.join("native").join(selected)); + } +} + +#[test] +fn prebuilt_native_input_that_aliases_a_compile_output_is_preserved() { + let relative = "target/x86_64-unknown-linux-gnu/dev/.vex-obj/app/native.o"; + let f = Fixture::new( + false, + &format!(",native={{libraries=[{{path=\"{relative}\"}}]}}"), + ); + let input = f.project.join(relative); + fs::create_dir_all(input.parent().unwrap()).unwrap(); + fs::write(&input, "prebuilt native input").unwrap(); + let output = f.run(&["build"]); + code(&output, 4); + assert_eq!(fs::read(&input).unwrap(), b"prebuilt native input"); + assert!(!f.project.join("compiler-started").exists()); + assert!(!f + .project + .join("target/x86_64-unknown-linux-gnu/dev/app") + .exists()); +} + +#[test] +fn valid_package_names_that_are_windows_devices_cannot_be_native_outputs() { + for (name, lib, native) in [ + ("CON", false, "{}"), + ("NUL", true, "{output=\"object\"}"), + ("LPT9", true, "{output=\"shared\"}"), + ] { + let f = Fixture::new(lib, &format!(",native={native}")); + fs::write( + f.project.join("vex.ws"), + format!("{{name=\"{name}\",lib={lib},native={native}}}"), + ) + .unwrap(); + code(&f.run(&["info"]), 0); + let output = f.run(&["build", "--target=x86_64-pc-windows-msvc", "--dry-run"]); + code(&output, 3); + assert!(String::from_utf8_lossy(&output.stderr).contains("Windows")); + assert!(!f + .invocations() + .iter() + .any(|args| args.iter().any(|arg| arg == "build"))); + assert!(!f.project.join("compiler-started").exists()); + assert!(!f.project.join("target").exists()); + } +} + +#[test] +fn metadata_reports_native_declarations_without_loading_compiler_or_inputs() { + let f = Fixture::new(false, ",native={libraries=[{name=\"rootlib\"}]}"); + f.package("dep", true, ",native={output=\"shared\",libraries=[{path=\"missing.a\",target=\"aarch64-apple-darwin\"}],search_paths=[{path=\"missing\",target=\"aarch64-apple-darwin\"}]}", ""); + f.package( + "app", + false, + ",native={libraries=[{name=\"rootlib\"}]}", + "{name=\"dep\",path=\"../dep\"}", + ); + code(&f.run(&["fetch"]), 0); + let before = snapshot(&f.project); + let output = f + .command() + .env("VEX_WAVEC", f.root.join("not-a-compiler")) + .args(["metadata", "--locked", "--offline"]) + .output() + .unwrap(); + let value = plan(&output); + assert_eq!(value["schema_version"], 1); + assert_eq!(value["root"]["native"]["libraries"][0]["name"], "rootlib"); + assert_eq!( + value["packages"][0]["native"], + json!({"output":"shared","libraries":[{"path":"missing.a","name":null,"target":"aarch64-apple-darwin"}],"search_paths":[{"path":"missing","target":"aarch64-apple-darwin"}]}) + ); + assert_eq!(snapshot(&f.project), before); + assert!(f.invocations().is_empty()); +} + +#[test] +fn unselected_target_files_are_ignored_but_selected_missing_inputs_fail() { + let f = Fixture::new(false, ",native={libraries=[{path=\"missing.a\",target=\"aarch64-apple-darwin\"}],search_paths=[{path=\"missing\",target=\"aarch64-apple-darwin\"}]}"); + plan(&f.run(&["build", "--dry-run", "--target=x86_64-unknown-linux-gnu"])); + let output = f.run(&["build", "--dry-run", "--target=aarch64-apple-darwin"]); + code(&output, 3); + assert!(String::from_utf8_lossy(&output.stderr).contains("native input")); + assert!(!f.project.join("compiler-started").exists()); + assert!(!f.project.join("target").exists()); +} + +#[test] +fn native_inputs_must_have_the_selected_file_or_directory_kind() { + for native in [ + ",native={libraries=[{path=\"directory.a\"}]}", + ",native={search_paths=[{path=\"file\"}]}", + ] { + let f = Fixture::new(false, native); + fs::create_dir(f.project.join("directory.a")).unwrap(); + fs::write(f.project.join("file"), "not a directory").unwrap(); + let output = f.run(&["build", "--dry-run"]); + code(&output, 3); + assert!(String::from_utf8_lossy(&output.stderr).contains("inside package")); + assert!(!f.project.join("compiler-started").exists()); + } +} + +#[cfg(unix)] +#[test] +fn native_input_symlinks_cannot_escape_the_declaring_package() { + for search in [false, true] { + let native = if search { + ",native={search_paths=[{path=\"escape\"}]}" + } else { + ",native={libraries=[{path=\"escape.a\"}]}" + }; + let f = Fixture::new(false, native); + let outside = f.root.join("outside"); + if search { + fs::create_dir(&outside).unwrap(); + } else { + fs::write(&outside, "outside input").unwrap(); + } + std::os::unix::fs::symlink( + &outside, + f.project.join(if search { "escape" } else { "escape.a" }), + ) + .unwrap(); + let output = f.run(&["build", "--dry-run"]); + code(&output, 3); + assert!(String::from_utf8_lossy(&output.stderr).contains("inside package")); + assert!(!f.project.join("compiler-started").exists()); + } +} + +#[test] +fn check_validates_manifest_inputs_without_linking_or_emitting_native_artifacts() { + let f = Fixture::new(true, ",native={output=\"shared\",libraries=[{path=\"native.a\"},{name=\"math\"}],search_paths=[{path=\"libs\"}]}"); + fs::write(f.project.join("native.a"), "archive").unwrap(); + fs::create_dir(f.project.join("libs")).unwrap(); + code(&f.run(&["fetch"]), 0); + let before = snapshot(&f.project); + let value = plan(&f.run(&["check", "--dry-run"])); + assert_eq!(value["emit"], "check"); + assert_eq!(value["compile"], json!([])); + assert!(value["link"].is_null()); + let args = f.build_arguments(); + for flag in ["-o", "-L", "--link", "--shared", "--emit=obj"] { + assert!(!args.iter().any(|arg| arg == flag), "{args:?}"); + } + assert!(!args + .iter() + .any(|arg| arg.ends_with("native.a") || arg.starts_with("--target-dir="))); + assert!(link_arguments(&args).is_empty()); + assert_eq!(snapshot(&f.project), before); + code(&f.run(&["check"]), 0); + assert!(f.project.join("compiler-started").exists()); + assert!(!f + .project + .join("target/x86_64-unknown-linux-gnu/dev/libapp.so") + .exists()); +} + +#[test] +fn invalid_target_spec_stops_before_a_compile_plan_or_execution() { + for response in [ + "not json", + "{}", + "[]", + r#"{"triple":"../escape","supported":true,"os":"linux","object_format":"elf"}"#, + r#"{"triple":"aarch64-unknown-linux-gnu","supported":true,"os":"linux","object_format":"elf"}"#, + r#"{"triple":"x86_64-unknown-linux-gnu","supported":false,"os":"linux","object_format":"elf"}"#, + ] { + let f = Fixture::new(false, ",native={}"); + code(&f.run(&["fetch"]), 0); + let before = snapshot(&f.project); + let output = f + .command() + .env("NATIVE_BAD_SPEC", response) + .args(["build", "--dry-run", "--target=x86_64-unknown-linux-gnu"]) + .output() + .unwrap(); + code(&output, 4); + assert!(String::from_utf8_lossy(&output.stderr).contains("target-spec")); + assert!(!f + .invocations() + .iter() + .any(|args| args.iter().any(|arg| arg == "build"))); + assert_eq!(snapshot(&f.project), before); + } +} + +#[test] +fn native_configuration_does_not_enable_raw_compiler_cli_options() { + let f = Fixture::new(false, ",native={}"); + for option in [ + "--link=foreign", + "-Lvendor", + "--shared", + "--emit=obj", + "-o", + "foreign.a", + ] { + code(&f.run(&["build", option]), 2); + } + assert!(f.invocations().is_empty()); + assert!(!f.project.join(".vex").exists()); +} + +#[test] +fn native_run_uses_an_independent_generation_and_preserves_program_exit_and_arguments() { + let f = Fixture::new(false, ",native={}"); + let output = f + .command() + .env( + "NATIVE_DEFAULT_TARGET", + if cfg!(windows) { + "x86_64-pc-windows-msvc" + } else { + "x86_64-unknown-linux-gnu" + }, + ) + .args(["run", "--", "with spaces", "--program-flag"]) + .output() + .unwrap(); + code(&output, 17); + assert!(String::from_utf8_lossy(&output.stdout).contains("native fixture program")); + let arguments: Value = + serde_json::from_slice(&fs::read(f.project.join("program-started")).unwrap()).unwrap(); + assert_eq!(arguments, json!(["with spaces", "--program-flag"])); + let args = f.build_arguments(); + assert!(!args.iter().any(|arg| arg == "--run")); + let output = Path::new(flag_value(&args, "-o")); + assert!(output.starts_with("target/.vex-run")); + assert!(f.project.join(output).is_file()); + assert!(!f + .project + .join("target/x86_64-unknown-linux-gnu/dev/app") + .exists()); +} diff --git a/tests/native_interop.py b/tests/native_interop.py new file mode 100644 index 0000000..535dc40 --- /dev/null +++ b/tests/native_interop.py @@ -0,0 +1,334 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MPL-2.0 +"""Native C ABI acceptance against a verified Wave release on the current host. + +Requires cc/c++/ar and rustc on Unix, or Visual Studio C++ tools and rustc on +Windows. Foreign sources are built only by this fixture; Vex receives prebuilt +archives/objects. Every language and both Wave output modes are required. +""" + +import argparse +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import tempfile + + +def run(command, cwd, env, expected=0): + command = list(map(str, command)) + print("$", " ".join(command), flush=True) + result = subprocess.run(command, cwd=cwd, env=env, text=True, + capture_output=True, timeout=300) + print(result.stdout, end="", flush=True) + print(result.stderr, end="", flush=True) + if result.returncode != expected: + raise RuntimeError(f"expected exit {expected}, got {result.returncode}: {command}") + return result + + +def required_tool(name, env): + tool = shutil.which(name, path=env.get("PATH")) + if not tool: + raise RuntimeError(f"native interoperability acceptance requires {name}") + return tool + + +def msvc_environment(root, env, arch): + """Select matching native tools even outside a Developer Command Prompt.""" + installer = Path(env.get("PROGRAMFILES(X86)", env.get("ProgramFiles(x86)", + r"C:\Program Files (x86)"))) + vswhere = installer / "Microsoft Visual Studio/Installer/vswhere.exe" + if not vswhere.is_file(): + raise RuntimeError("native Windows acceptance requires Visual Studio's vswhere.exe") + installation = run([vswhere, "-latest", "-products", "*", "-property", + "installationPath"], root, env).stdout.strip() + devcmd = Path(installation) / "Common7/Tools/VsDevCmd.bat" + if not installation or not devcmd.is_file(): + raise RuntimeError("cannot locate Visual Studio C++ developer environment") + batch = root / "msvc-environment.cmd" + batch.write_text( + '@echo off\ncall "%VEX_INTEROP_VSDEVCMD%" -no_logo ' + '-arch=%VEX_INTEROP_ARCH% >nul\n' + 'if errorlevel 1 exit /b %errorlevel%\nset\n', encoding="ascii") + selection = dict(env, VEX_INTEROP_VSDEVCMD=str(devcmd), + VEX_INTEROP_ARCH="arm64" if arch == "aarch64" else "amd64") + # `set` contains the runner's environment: capture it without printing it. + result = subprocess.run([env.get("COMSPEC", "cmd.exe"), "/d", "/c", str(batch)], + cwd=root, env=selection, text=True, capture_output=True, + timeout=60) + if result.returncode: + raise RuntimeError(f"Visual Studio environment setup failed: {result.stderr}") + selected = dict(env) + for line in result.stdout.splitlines(): + key, separator, value = line.partition("=") + if separator and key and not key.startswith("="): + # Windows environment keys are case insensitive; normalize the ones + # used by Python executable lookup instead of keeping two PATHs. + if key.upper() in {"PATH", "INCLUDE", "LIB", "LIBPATH"}: + key = key.upper() + selected[key] = value + return selected + + +class NativeTools: + def __init__(self, root, env, spec): + self.windows = spec["os"] == "windows" + self.env = msvc_environment(root, env, spec["arch"]) if self.windows else env + self.cc = required_tool("cl.exe" if self.windows else "cc", self.env) + self.cxx = self.cc if self.windows else required_tool("c++", self.env) + self.ar = required_tool("lib.exe" if self.windows else "ar", self.env) + self.rustc = required_tool("rustc", self.env) + self.object_extension = ".obj" if self.windows else ".o" + + def archive(self, root, name, source, cpp=False): + path = root / (name + (".cpp" if cpp else ".c")) + path.write_text(source, encoding="utf-8") + obj = root / (name + self.object_extension) + archive = root / (name + ".lib" if self.windows else "lib" + name + ".a") + if self.windows: + run([self.cc, "/nologo", "/MD", "/c", "/TP" if cpp else "/TC", + path, "/Fo" + str(obj)], root, self.env) + run([self.ar, "/NOLOGO", "/OUT:" + str(archive), obj], root, self.env) + else: + run([self.cxx if cpp else self.cc, "-fPIC", "-c", path, "-o", obj], root, self.env) + run([self.ar, "rcs", archive, obj], root, self.env) + return archive + + def rust_object(self, root): + source = root / "native_rust.rs" + source.write_text( + '#![no_std]\n#[no_mangle]\npub extern "C" fn native_rust(a: i32, b: i32) ' + '-> i32 { a.wrapping_add(b) }\n', encoding="utf-8") + obj = root / ("native_rust" + self.object_extension) + run([self.rustc, "--edition=2021", "--crate-type=lib", "--emit=obj", + "-C", "panic=abort", source, "-o", obj], root, self.env) + return obj + + def consume(self, root, library, shared=False): + source = root / "consumer.c" + source.write_text('extern int wave_add(int, int);\n' + 'int main(void) { return wave_add(20, 22) == 42 ? 0 : 1; }\n', + encoding="utf-8") + executable = root / ("consumer.exe" if self.windows else "consumer") + if self.windows: + link_input = library.with_suffix(".lib") if shared else library + if not link_input.is_file(): + raise RuntimeError(f"Wave did not publish the required import library: {link_input}") + run([self.cc, "/nologo", "/MD", source, link_input, + "/Fe" + str(executable), "/link", "/INCREMENTAL:NO"], root, self.env) + else: + args = [self.cc, source, library, "-o", executable] + if shared: + args.append("-Wl,-rpath," + str(library.parent)) + run(args, root, self.env) + env = dict(self.env) + if shared and self.windows: + # This is the external consumer's loader setup, not a Vex policy. + env["PATH"] = str(library.parent) + os.pathsep + env.get("PATH", "") + run([executable], root, env) + + +def wson(value): + if isinstance(value, dict): + return "{" + ",".join(key + "=" + wson(item) for key, item in value.items()) + "}" + if isinstance(value, list): + return "[" + ",".join(wson(item) for item in value) + "]" + return json.dumps(value) + + +def package(path, name, *, lib=False, native=None, dependencies=None): + (path / "src").mkdir(parents=True, exist_ok=True) + document = dict(format=2, name=name, version="0.1.0", lib=lib) + if native is not None: + document["native"] = native + if dependencies is not None: + document["dependencies"] = dependencies + (path / "vex.ws").write_text(wson(document) + "\n", encoding="utf-8") + + +def snapshot(root): + return {str(path.relative_to(root)): hashlib.sha256(path.read_bytes()).hexdigest() + for path in root.rglob("*") if path.is_file()} + + +def events(path): + return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()] + + +def build(vex, root, env, report): + run([vex, "--message-file", report, "build", "--locked", "--offline"], root, env) + records = [event for event in events(report) if event["event"] == "artifact"] + if len(records) != 1 or not records[0]["paths"]: + raise RuntimeError("native build did not report its artifacts") + outputs = [root / path for path in records[0]["paths"]] + if not all(path.is_file() for path in outputs): + raise RuntimeError("artifact event listed a missing native output") + return outputs + + +def inbound(vex, root, tools, spec): + app, middle, bridge = [root / name for name in ("native app", "middle", "bridge")] + native_dir = bridge / "native files" + native_dir.mkdir(parents=True) + c_archive = tools.archive(native_dir, "vex_c", "int native_c(int a, int b) { return a+b; }\n") + tools.archive(native_dir, "vex_cpp", 'extern "C" int native_cpp(int a, int b) { return a+b; }\n', cpp=True) + rust_obj = tools.rust_object(native_dir) + other_target = ("aarch64-unknown-linux-gnu" if spec["triple"] != "aarch64-unknown-linux-gnu" + else "x86_64-unknown-linux-gnu") + package(bridge, "bridge", lib=True, native=dict( + libraries=[dict(path="native files/" + c_archive.name), + dict(name="vex_cpp", target=spec["triple"]), + dict(path="native files/" + rust_obj.name), + dict(path="unselected/missing.a", target=other_target)], + search_paths=[dict(path="native files", target=spec["triple"])])) + (bridge / "src/lib.wave").write_text( + # Public Wave 0.2.1 needs explicit linker names in imported modules: + # the module resolver renames local declarations, not these symbols. + 'extern(c, "native_c") fun native_c(a: i32, b: i32) -> i32;\n' + 'extern(c, "native_cpp") fun native_cpp(a: i32, b: i32) -> i32;\n' + 'extern(c, "native_rust") fun native_rust(a: i32, b: i32) -> i32;\n' + 'pub fun answer() -> i32 { return native_c(10, 1) + native_cpp(10, 2) + native_rust(10, 9); }\n', + encoding="utf-8") + package(middle, "middle", lib=True, dependencies=[dict(name="bridge", path="../bridge")]) + (middle / "src/lib.wave").write_text('pub import("bridge")::{answer};\n', encoding="utf-8") + package(app, "native_app", dependencies=[dict(name="middle", path="../middle")]) + (app / "src/main.wave").write_text( + 'import("middle")::{answer};\nfun main() -> i32 { ' + 'var result: i32 = answer(); println("{}", result); return result - 42; }\n', encoding="utf-8") + run([vex, "fetch", "--offline"], app, tools.env) + locked = (app / "vex.lock").read_bytes() + before = snapshot(app) + plan = json.loads(run([vex, "build", "--dry-run", "--locked", "--offline"], app, tools.env).stdout) + if snapshot(app) != before or plan["target"] != spec["triple"]: + raise RuntimeError("native dry-run mutated the project or selected the wrong target") + outputs = build(vex, app, tools.env, root / "inbound-build.jsonl") + executable = app / plan["link"]["output"] + if executable not in outputs: + raise RuntimeError("build artifact did not match the planned native executable") + if "42" not in run([executable], app, tools.env).stdout.splitlines(): + raise RuntimeError("C/C++/Rust native inputs did not produce the expected result") + run([vex, "check", "--locked", "--offline"], app, tools.env) + report = root / "inbound-run.jsonl" + result = run([vex, "--message-file", report, "run", "--locked", "--offline"], app, tools.env) + if "42" not in result.stdout.splitlines() or events(report)[-1].get("origin") != "program": + raise RuntimeError("native run lost the program result or structured origin") + metadata = json.loads(run([vex, "metadata", "--locked", "--offline"], app, tools.env).stdout) + bridge_metadata = next(item for item in metadata["packages"] if item["name"] == "bridge") + if c_archive.name not in json.dumps(bridge_metadata.get("native")): + raise RuntimeError("metadata omitted transitive native build inputs") + if (app / "vex.lock").read_bytes() != locked: + raise RuntimeError("locked native operations changed the lockfile") + + # A native link error must retain the previous usable image and its cause. + previous = executable.read_bytes() + (app / "src/main.wave").write_text( + 'extern(c) fun missing_native_symbol() -> i32;\n' + 'fun main() -> i32 { return missing_native_symbol(); }\n', encoding="utf-8") + report = root / "inbound-failure.jsonl" + failed = run([vex, "--message-file", report, "build", "--locked", "--offline"], + app, tools.env, expected=4) + outcome = events(report)[-1] + if ("missing_native_symbol" not in failed.stderr or outcome.get("origin") != "vex" + or outcome.get("exit_code") != 4 or executable.read_bytes() != previous): + raise RuntimeError("native linker failure lost its cause, category, or previous output") + + +def outbound(vex, root, tools, spec): + project = root / "wave exports" + package(project, "wave_exports", lib=True) + (project / "src/lib.wave").write_text( + 'export(c) fun wave_add(a: i32, b: i32) -> i32 { return a + b; }\n', encoding="utf-8") + run([vex, "fetch", "--offline"], project, tools.env) + output_dir = project / "target" / spec["triple"] / "dev" + obj = output_dir / ("wave_exports" + tools.object_extension) + outputs = build(vex, project, tools.env, root / "outbound-object.jsonl") + if obj not in outputs: + raise RuntimeError("library default output is not the named target/profile object") + consumer = root / "object consumer" + consumer.mkdir() + tools.consume(consumer, obj) + unknown = output_dir / "user-file" + unknown.write_text("preserve me", encoding="utf-8") + run([vex, "clean"], project, tools.env) + if obj.exists() or unknown.read_text(encoding="utf-8") != "preserve me": + raise RuntimeError("clean failed to distinguish native output from user data") + + package(project, "wave_exports", lib=True, native=dict(output="shared")) + outputs = build(vex, project, tools.env, root / "outbound-shared.jsonl") + name = {"coff": "wave_exports.dll", "macho": "libwave_exports.dylib", + "elf": "libwave_exports.so"}[spec["object_format"]] + library = output_dir / name + if library not in outputs: + raise RuntimeError("shared artifact path does not match the target object format") + if tools.windows and library.with_suffix(".lib") not in outputs: + raise RuntimeError("shared artifact event omitted the Windows import library") + consumer = root / "shared consumer" + consumer.mkdir() + tools.consume(consumer, library, shared=True) + run([vex, "clean", "--dry-run"], project, tools.env) + if not all(path.is_file() for path in outputs): + raise RuntimeError("clean preview removed a shared output") + run([vex, "clean"], project, tools.env) + if any(path.exists() for path in outputs) or unknown.read_text(encoding="utf-8") != "preserve me": + raise RuntimeError("clean did not remove the owned shared artifact set safely") + + +def archive_order(vex, root, tools): + """A name/path mix must preserve the manifest's static-library order.""" + project = root / "library order" + native_dir = project / "native files" + native_dir.mkdir(parents=True) + tools.archive(native_dir, "order_first", "int chosen(void) { return 1; }\n") + second = tools.archive(native_dir, "order_second", "int chosen(void) { return 2; }\n") + libraries = [dict(name="order_first"), dict(path="native files/" + second.name)] + for expected, ordered in [(1, libraries), (2, list(reversed(libraries)))]: + package(project, "library_order", native=dict( + libraries=ordered, search_paths=[dict(path="native files")])) + (project / "src/main.wave").write_text( + 'extern(c) fun chosen() -> i32;\n' + f'fun main() -> i32 {{ return chosen() - {expected}; }}\n', encoding="utf-8") + if expected == 1: + run([vex, "fetch", "--offline"], project, tools.env) + # Both archives define chosen; only the earlier definition should be + # extracted. The reversed case prevents an accidental fixed preference. + run([vex, "run", "--locked", "--offline"], project, tools.env) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--vex", type=Path, required=True) + parser.add_argument("--wavec-bin", type=Path, required=True) + parser.add_argument("--expected-version") + parser.add_argument("--expected-sha256", help="Compiler executable digest, not the archive digest") + args = parser.parse_args() + vex = args.vex.resolve() + compiler = args.wavec_bin.resolve() / ("wavec.exe" if os.name == "nt" else "wavec") + digest = hashlib.sha256(compiler.read_bytes()).hexdigest() + if args.expected_sha256 and digest != args.expected_sha256.lower(): + raise RuntimeError("compiler executable SHA-256 does not match the verified release") + print(f"native interop compiler: {compiler}\nSHA-256: {digest}", flush=True) + env = dict(os.environ) + env.pop("VEX_WAVEC", None) + env.pop("GH_TOKEN", None) + env.pop("GITHUB_TOKEN", None) + env["PATH"] = str(compiler.parent) + os.pathsep + env.get("PATH", "") + with tempfile.TemporaryDirectory(prefix="vex native interop ") as temporary: + root = Path(temporary) + version = run([compiler, "--version"], root, dict(env, NO_COLOR="1")) + if args.expected_version and version.stdout.split()[:2] != ["wavec", args.expected_version]: + raise RuntimeError("native interop compiler version differs from the verified release") + spec = json.loads(run([compiler, "print", "target-spec", "--format=json"], root, env).stdout) + if not spec["hosted"] or spec["object_format"] not in {"elf", "macho", "coff"}: + raise RuntimeError("native acceptance requires a supported hosted target") + tools = NativeTools(root, env, spec) + inbound(vex, root, tools, spec) + archive_order(vex, root, tools) + outbound(vex, root, tools, spec) + print("Native C/C++/Rust inputs and Wave object/shared consumers passed.", flush=True) + + +if __name__ == "__main__": + main() diff --git a/tools/ci_platform.py b/tools/ci_platform.py index f9d67c2..8dd000e 100644 --- a/tools/ci_platform.py +++ b/tools/ci_platform.py @@ -71,11 +71,15 @@ def main(): run(sys.executable, 'tests/wave_compatibility.py', '--vex', binary, '--wavec-bin', compiler.parent, '--reexports', '--expected-version', WAVE_VERSION, '--expected-sha256', compiler_hash, env=env) + run(sys.executable, 'tests/native_interop.py', '--vex', binary, + '--wavec-bin', compiler.parent, '--expected-version', WAVE_VERSION, + '--expected-sha256', compiler_hash, env=env) report = dict(schema_version=1, platform=target['id'], rust_target=target['rust_target'], executor=target['executor'], source=run('git', 'rev-parse', 'HEAD', capture=True).stdout.strip(), os=platform.platform(), libc=platform.libc_ver(), 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'], status='passed') (ROOT / 'dist' / f"acceptance-{target['id']}.json").write_text(json.dumps(report, indent=2)+'\n') From 23e48ded82688f62a345b0420a65e90eebcb3a1e Mon Sep 17 00:00:00 2001 From: LunaStev Date: Sat, 17 Oct 2026 19:07:00 +0900 Subject: [PATCH 2/2] fix: declare Windows DLL exports and update vulnerable zip dependency Signed-off-by: LunaStev --- Cargo.lock | 23 +- THIRD_PARTY_LICENSES | 382 ++++++++++++++++++++-------------- docs/native-interop.md | 16 ++ docs/schemas/metadata-v1.json | 8 + manifest/src/native.rs | 64 +++++- src/native.rs | 15 +- tests/native_build.rs | 39 +++- tests/native_interop.py | 20 +- toolchain/Cargo.toml | 2 +- toolchain/src/artifact.rs | 2 +- 10 files changed, 409 insertions(+), 162 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1ab17c4..ac960ee 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -69,6 +69,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + [[package]] name = "chrono" version = "0.4.44" @@ -438,6 +444,18 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -1013,14 +1031,15 @@ dependencies = [ [[package]] name = "zip" -version = "8.6.0" +version = "9.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b" +checksum = "a954114b47a54df49f83d2722814e86b23d4bb1b54a1b90fb7d92b41619ddc22" dependencies = [ "crc32fast", "flate2", "indexmap", "memchr", + "nix", "typed-path", "zopfli", ] diff --git a/THIRD_PARTY_LICENSES b/THIRD_PARTY_LICENSES index 32a2fdb..5d8806b 100644 --- a/THIRD_PARTY_LICENSES +++ b/THIRD_PARTY_LICENSES @@ -1,7 +1,7 @@ Third-party dependency notices for Vex ===================================== -Cargo.lock SHA-256 (LF): 8b4521d1f2a1034abc9ad73c1502bb50d06fe4e9813c81d7dc5bc79a8ac5589e +Cargo.lock SHA-256 (LF): db7d1a6e1117beb5db479def50e45bdf4f24fcbd2d766bd655ba68373f60f621 Generated by tools/dependency_notices.py from Cargo's locked package sources. Includes build-time and platform-specific dependencies; a given binary may @@ -65,45 +65,51 @@ Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 9 LICENSE-MIT: Text 15 +cfg_aliases 0.2.2 +Declared license: MIT +Source: registry+https://github.com/rust-lang/crates.io-index + LICENSE: Text 16 + NOTICES.md: Text 17 + chrono 0.4.44 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE.txt: Text 16 + LICENSE.txt: Text 18 colorex 0.1.2 Declared license: MPL-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE: Text 17 + LICENSE: Text 19 core-foundation-sys 0.8.7 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 9 - LICENSE-MIT: Text 18 + LICENSE-MIT: Text 20 cpufeatures 0.2.17 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 12 - LICENSE-MIT: Text 19 + LICENSE-MIT: Text 21 crc32fast 1.5.2 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE-APACHE: Text 20 - LICENSE-MIT: Text 21 + LICENSE-APACHE: Text 22 + LICENSE-MIT: Text 23 crypto-common 0.1.7 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 12 - LICENSE-MIT: Text 22 + LICENSE-MIT: Text 24 digest 0.10.7 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 12 - LICENSE-MIT: Text 23 + LICENSE-MIT: Text 25 displaydoc 0.2.6 Declared license: MIT OR Apache-2.0 @@ -115,13 +121,13 @@ equivalent 1.0.2 Declared license: Apache-2.0 OR MIT Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 9 - LICENSE-MIT: Text 24 + LICENSE-MIT: Text 26 errno 0.3.14 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 9 - LICENSE-MIT: Text 25 + LICENSE-MIT: Text 27 filetime 0.2.29 Declared license: MIT/Apache-2.0 @@ -139,94 +145,94 @@ flate2 1.1.10 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 9 - LICENSE-MIT: Text 26 + LICENSE-MIT: Text 28 form_urlencoded 1.2.2 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 9 - LICENSE-MIT: Text 27 + LICENSE-MIT: Text 29 generic-array 0.14.7 Declared license: MIT Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE: Text 28 + LICENSE: Text 30 hashbrown 0.17.1 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 9 - LICENSE-MIT: Text 29 + LICENSE-MIT: Text 31 iana-time-zone 0.1.65 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE-APACHE: Text 30 - LICENSE-MIT: Text 31 + LICENSE-APACHE: Text 32 + LICENSE-MIT: Text 33 iana-time-zone-haiku 0.1.2 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE-APACHE: Text 30 - LICENSE-MIT: Text 31 + LICENSE-APACHE: Text 32 + LICENSE-MIT: Text 33 icu_collections 2.2.0 Declared license: Unicode-3.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE: Text 32 + LICENSE: Text 34 icu_locale_core 2.2.0 Declared license: Unicode-3.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE: Text 32 + LICENSE: Text 34 icu_normalizer 2.2.0 Declared license: Unicode-3.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE: Text 32 + LICENSE: Text 34 icu_normalizer_data 2.2.0 Declared license: Unicode-3.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE: Text 32 + LICENSE: Text 34 icu_properties 2.2.0 Declared license: Unicode-3.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE: Text 32 + LICENSE: Text 34 icu_properties_data 2.2.0 Declared license: Unicode-3.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE: Text 32 + LICENSE: Text 34 icu_provider 2.2.0 Declared license: Unicode-3.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE: Text 32 + LICENSE: Text 34 idna 1.1.0 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 9 - LICENSE-MIT: Text 33 + LICENSE-MIT: Text 35 idna_adapter 1.2.2 Declared license: Apache-2.0 OR MIT Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 9 - LICENSE-MIT: Text 34 + LICENSE-MIT: Text 36 indexmap 2.14.2 Declared license: Apache-2.0 OR MIT Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 9 - LICENSE-MIT: Text 35 + LICENSE-MIT: Text 37 itoa 1.0.18 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE-APACHE: Text 36 + LICENSE-APACHE: Text 38 LICENSE-MIT: Text 3 js-sys 0.3.91 @@ -238,21 +244,21 @@ Source: registry+https://github.com/rust-lang/crates.io-index libc 0.2.189 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE-APACHE: Text 36 - LICENSE-MIT: Text 37 + LICENSE-APACHE: Text 38 + LICENSE-MIT: Text 39 linux-raw-sys 0.12.1 Declared license: Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT Source: registry+https://github.com/rust-lang/crates.io-index - COPYRIGHT: Text 38 + COPYRIGHT: Text 40 LICENSE-APACHE: Text 9 - LICENSE-Apache-2.0_WITH_LLVM-exception: Text 39 + LICENSE-Apache-2.0_WITH_LLVM-exception: Text 41 LICENSE-MIT: Text 3 litemap 0.8.2 Declared license: Unicode-3.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE: Text 32 + LICENSE: Text 34 log 0.4.29 Declared license: MIT OR Apache-2.0 @@ -270,10 +276,15 @@ Source: registry+https://github.com/rust-lang/crates.io-index miniz_oxide 0.9.1 Declared license: MIT OR Zlib OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE: Text 40 - LICENSE-APACHE.md: Text 41 - LICENSE-MIT.md: Text 42 - LICENSE-ZLIB.md: Text 43 + LICENSE: Text 42 + LICENSE-APACHE.md: Text 43 + LICENSE-MIT.md: Text 44 + LICENSE-ZLIB.md: Text 45 + +nix 0.31.3 +Declared license: MIT +Source: registry+https://github.com/rust-lang/crates.io-index + LICENSE: Text 46 num-traits 0.2.19 Declared license: MIT OR Apache-2.0 @@ -291,23 +302,23 @@ percent-encoding 2.3.2 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 9 - LICENSE-MIT: Text 33 + LICENSE-MIT: Text 35 potential_utf 0.1.5 Declared license: Unicode-3.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE: Text 32 + LICENSE: Text 34 proc-macro2 1.0.106 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE-APACHE: Text 36 + LICENSE-APACHE: Text 38 LICENSE-MIT: Text 3 quote 1.0.45 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE-APACHE: Text 36 + LICENSE-APACHE: Text 38 LICENSE-MIT: Text 3 regex 1.12.3 @@ -327,147 +338,147 @@ Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 9 LICENSE-MIT: Text 11 - src/unicode_tables/LICENSE-UNICODE: Text 44 + src/unicode_tables/LICENSE-UNICODE: Text 47 rustix 1.1.5 Declared license: Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT Source: registry+https://github.com/rust-lang/crates.io-index - COPYRIGHT: Text 45 + COPYRIGHT: Text 48 LICENSE-APACHE: Text 9 - LICENSE-Apache-2.0_WITH_LLVM-exception: Text 39 + LICENSE-Apache-2.0_WITH_LLVM-exception: Text 41 LICENSE-MIT: Text 3 rustversion 1.0.22 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE-APACHE: Text 36 + LICENSE-APACHE: Text 38 LICENSE-MIT: Text 3 semver 1.0.28 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE-APACHE: Text 36 + LICENSE-APACHE: Text 38 LICENSE-MIT: Text 3 serde 1.0.229 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE-APACHE: Text 36 + LICENSE-APACHE: Text 38 LICENSE-MIT: Text 3 serde_core 1.0.229 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE-APACHE: Text 36 + LICENSE-APACHE: Text 38 LICENSE-MIT: Text 3 serde_derive 1.0.229 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE-APACHE: Text 36 + LICENSE-APACHE: Text 38 LICENSE-MIT: Text 3 serde_json 1.0.151 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE-APACHE: Text 36 + LICENSE-APACHE: Text 38 LICENSE-MIT: Text 3 sha2 0.10.9 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 12 - LICENSE-MIT: Text 46 + LICENSE-MIT: Text 49 shlex 1.3.0 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE-APACHE: Text 47 - LICENSE-MIT: Text 48 + LICENSE-APACHE: Text 50 + LICENSE-MIT: Text 51 simd-adler32 0.3.10 Declared license: MIT Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE.md: Text 49 + LICENSE.md: Text 52 smallvec 1.16.1 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 9 - LICENSE-MIT: Text 50 + LICENSE-MIT: Text 53 stable_deref_trait 1.2.1 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 9 - LICENSE-MIT: Text 51 + LICENSE-MIT: Text 54 syn 2.0.117 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE-APACHE: Text 36 + LICENSE-APACHE: Text 38 LICENSE-MIT: Text 3 syn 3.0.3 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE-APACHE: Text 36 + LICENSE-APACHE: Text 38 LICENSE-MIT: Text 3 synstructure 0.13.2 Declared license: MIT Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE: Text 52 + LICENSE: Text 55 tar 0.4.46 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 9 - LICENSE-MIT: Text 53 + LICENSE-MIT: Text 56 tinystr 0.8.3 Declared license: Unicode-3.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE: Text 32 + LICENSE: Text 34 typed-path 0.12.3 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE-APACHE: Text 36 + LICENSE-APACHE: Text 38 LICENSE-MIT: Text 3 typenum 1.20.1 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE: Text 54 - LICENSE-APACHE: Text 55 - LICENSE-MIT: Text 56 + LICENSE: Text 57 + LICENSE-APACHE: Text 58 + LICENSE-MIT: Text 59 unicode-ident 1.0.24 Declared license: (MIT OR Apache-2.0) AND Unicode-3.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE-APACHE: Text 36 + LICENSE-APACHE: Text 38 LICENSE-MIT: Text 3 - LICENSE-UNICODE: Text 57 + LICENSE-UNICODE: Text 60 url 2.5.8 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 9 - LICENSE-MIT: Text 33 + LICENSE-MIT: Text 35 utf8_iter 1.0.4 Declared license: Apache-2.0 OR MIT Source: registry+https://github.com/rust-lang/crates.io-index - COPYRIGHT: Text 58 - LICENSE-APACHE: Text 59 - LICENSE-MIT: Text 60 + COPYRIGHT: Text 61 + LICENSE-APACHE: Text 62 + LICENSE-MIT: Text 63 version_check 0.9.5 Declared license: MIT/Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 9 - LICENSE-MIT: Text 61 + LICENSE-MIT: Text 64 wasm-bindgen 0.2.114 Declared license: MIT OR Apache-2.0 @@ -496,105 +507,105 @@ Source: registry+https://github.com/rust-lang/crates.io-index windows-core 0.62.2 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - license-apache-2.0: Text 62 - license-mit: Text 63 + license-apache-2.0: Text 65 + license-mit: Text 66 windows-implement 0.60.2 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - license-apache-2.0: Text 62 - license-mit: Text 63 + license-apache-2.0: Text 65 + license-mit: Text 66 windows-interface 0.59.3 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - license-apache-2.0: Text 62 - license-mit: Text 63 + license-apache-2.0: Text 65 + license-mit: Text 66 windows-link 0.2.1 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - license-apache-2.0: Text 62 - license-mit: Text 63 + license-apache-2.0: Text 65 + license-mit: Text 66 windows-result 0.4.1 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - license-apache-2.0: Text 62 - license-mit: Text 63 + license-apache-2.0: Text 65 + license-mit: Text 66 windows-strings 0.5.1 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - license-apache-2.0: Text 62 - license-mit: Text 63 + license-apache-2.0: Text 65 + license-mit: Text 66 windows-sys 0.61.2 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - license-apache-2.0: Text 62 - license-mit: Text 63 + license-apache-2.0: Text 65 + license-mit: Text 66 writeable 0.6.3 Declared license: Unicode-3.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE: Text 32 + LICENSE: Text 34 wson_rs 0.2.5 Declared license: MPL-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE: Text 17 + LICENSE: Text 19 xattr 1.6.1 Declared license: MIT OR Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index LICENSE-APACHE: Text 9 - LICENSE-MIT: Text 64 + LICENSE-MIT: Text 67 yoke 0.8.3 Declared license: Unicode-3.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE: Text 32 + LICENSE: Text 34 yoke-derive 0.8.2 Declared license: Unicode-3.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE: Text 32 + LICENSE: Text 34 zerofrom 0.1.8 Declared license: Unicode-3.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE: Text 32 + LICENSE: Text 34 zerofrom-derive 0.1.7 Declared license: Unicode-3.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE: Text 32 + LICENSE: Text 34 zerotrie 0.2.4 Declared license: Unicode-3.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE: Text 32 + LICENSE: Text 34 zerovec 0.11.6 Declared license: Unicode-3.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE: Text 32 + LICENSE: Text 34 zerovec-derive 0.11.3 Declared license: Unicode-3.0 Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE: Text 32 + LICENSE: Text 34 -zip 8.6.0 +zip 9.0.4 Declared license: MIT Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE: Text 65 + LICENSE: Text 68 zlib-rs 0.6.8 Declared license: Zlib Source: registry+https://github.com/rust-lang/crates.io-index - LICENSE: Text 66 + LICENSE: Text 69 zmij 1.0.23 Declared license: MIT @@ -604,7 +615,7 @@ Source: registry+https://github.com/rust-lang/crates.io-index zopfli 0.8.3 Declared license: Apache-2.0 Source: registry+https://github.com/rust-lang/crates.io-index - COPYING: Text 67 + COPYING: Text 70 Text 1 ======================================================================== @@ -1497,6 +1508,47 @@ DEALINGS IN THE SOFTWARE. Text 16 ======================================================================== +MIT License + +Copyright (c) 2020 Katharos Technology + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Text 17 +======================================================================== +# 3rd Party Notices + +The `cfg_aliases!` macro uses a lot of the code from [`tectonic_cfg_support::target_cfg!`] macro which is under the following license: + +[`tectonic_cfg_support::target_cfg!`]: https://github.com/tectonic-typesetting/tectonic/blob/f2439b936470ad27bdf92882064bc4702ee01899/cfg_support/src/lib.rs#L166 + + tectonic_cfg_support is licensed under the MIT License. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the “Software”), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +--- + +Text 18 +======================================================================== Rust-chrono is dual-licensed under The MIT License [1] and Apache 2.0 License [2]. Copyright (c) 2014--2026, Kang Seonghoon and contributors. @@ -1737,7 +1789,7 @@ See the License for the specific language governing permissions and limitations under the License. ~~~~ -Text 17 +Text 19 ======================================================================== Mozilla Public License Version 2.0 ================================== @@ -2113,7 +2165,7 @@ Exhibit B - "Incompatible With Secondary Licenses" Notice This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. -Text 18 +Text 20 ======================================================================== Copyright (c) 2012-2013 Mozilla Foundation @@ -2141,7 +2193,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 19 +Text 21 ======================================================================== Copyright (c) 2020-2025 The RustCrypto Project Developers @@ -2169,7 +2221,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 20 +Text 22 ======================================================================== Apache License Version 2.0, January 2004 @@ -2373,7 +2425,7 @@ Apache License See the License for the specific language governing permissions and limitations under the License. -Text 21 +Text 23 ======================================================================== MIT License @@ -2397,7 +2449,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 22 +Text 24 ======================================================================== Copyright (c) 2021 RustCrypto Developers @@ -2425,7 +2477,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 23 +Text 25 ======================================================================== Copyright (c) 2017 Artyom Pavlov @@ -2453,7 +2505,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 24 +Text 26 ======================================================================== Copyright (c) 2016--2023 @@ -2481,7 +2533,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 25 +Text 27 ======================================================================== Copyright (c) 2014 Chris Wong @@ -2509,7 +2561,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 26 +Text 28 ======================================================================== Copyright (c) 2014-2026 Alex Crichton @@ -2537,7 +2589,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 27 +Text 29 ======================================================================== Copyright (c) 2013-2016 The rust-url developers @@ -2565,7 +2617,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 28 +Text 30 ======================================================================== The MIT License (MIT) @@ -2589,7 +2641,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 29 +Text 31 ======================================================================== Copyright (c) 2016 Amanieu d'Antras @@ -2617,7 +2669,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 30 +Text 32 ======================================================================== Apache License Version 2.0, January 2004 @@ -2821,7 +2873,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -Text 31 +Text 33 ======================================================================== Copyright (c) 2020 Andrew D. Straw @@ -2849,7 +2901,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 32 +Text 34 ======================================================================== UNICODE LICENSE V3 @@ -2898,7 +2950,7 @@ SPDX-License-Identifier: Unicode-3.0 Portions of ICU4X may have been adapted from ICU4C and/or ICU4J. ICU 1.8.1 to ICU 57.1 © 1995-2016 International Business Machines Corporation and others. -Text 33 +Text 35 ======================================================================== Copyright (c) 2013-2025 The rust-url developers @@ -2926,7 +2978,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 34 +Text 36 ======================================================================== Copyright (c) The rust-url developers @@ -2954,7 +3006,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 35 +Text 37 ======================================================================== Copyright (c) 2016--2017 @@ -2982,7 +3034,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 36 +Text 38 ======================================================================== Apache License Version 2.0, January 2004 @@ -3161,7 +3213,7 @@ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION END OF TERMS AND CONDITIONS -Text 37 +Text 39 ======================================================================== Copyright (c) The Rust Project Developers @@ -3189,7 +3241,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 38 +Text 40 ======================================================================== Short version for non-lawyers: @@ -3221,7 +3273,7 @@ is licensed under: at your option. -Text 39 +Text 41 ======================================================================== Apache License Version 2.0, January 2004 @@ -3442,7 +3494,7 @@ prospectively choose to deem waived or otherwise exclude such Section(s) of the License, but only in their entirety and only with respect to the Combined Software. -Text 40 +Text 42 ======================================================================== MIT License @@ -3470,7 +3522,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 41 +Text 43 ======================================================================== Apache License Version 2.0, January 2004 @@ -3649,7 +3701,7 @@ Apache License END OF TERMS AND CONDITIONS -Text 42 +Text 44 ======================================================================== MIT License @@ -3676,7 +3728,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 43 +Text 45 ======================================================================== Copyright 2013-2014 RAD Game Tools and Valve Software Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC @@ -3693,7 +3745,31 @@ Permission is granted to anyone to use this software for any purpose, including 3. This notice may not be removed or altered from any source distribution. -Text 44 +Text 46 +======================================================================== +The MIT License (MIT) + +Copyright (c) 2015 Carl Lerche + nix-rust Authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +Text 47 ======================================================================== UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE @@ -3753,7 +3829,7 @@ shall not be used in advertising or otherwise to promote the sale, use or other dealings in these Data Files or Software without prior written authorization of the copyright holder. -Text 45 +Text 48 ======================================================================== Short version for non-lawyers: @@ -3785,7 +3861,7 @@ is licensed under: at your option. -Text 46 +Text 49 ======================================================================== Copyright (c) 2006-2009 Graydon Hoare Copyright (c) 2009-2013 Mozilla Foundation @@ -3815,7 +3891,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 47 +Text 50 ======================================================================== Copyright 2015 Nicholas Allegra (comex). @@ -3831,7 +3907,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -Text 48 +Text 51 ======================================================================== The MIT License (MIT) @@ -3855,7 +3931,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 49 +Text 52 ======================================================================== MIT License @@ -3879,7 +3955,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 50 +Text 53 ======================================================================== Copyright (c) 2018 The Servo Project Developers @@ -3907,7 +3983,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 51 +Text 54 ======================================================================== Copyright (c) 2017 Robert Grosse @@ -3935,7 +4011,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 52 +Text 55 ======================================================================== Copyright 2016 Nika Layzell @@ -3945,7 +4021,7 @@ The above copyright notice and this permission notice shall be included in all c THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 53 +Text 56 ======================================================================== Copyright (c) The tar-rs Project Contributors @@ -3973,11 +4049,11 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 54 +Text 57 ======================================================================== MIT OR Apache-2.0 -Text 55 +Text 58 ======================================================================== Apache License Version 2.0, January 2004 @@ -4181,7 +4257,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -Text 56 +Text 59 ======================================================================== The MIT License (MIT) @@ -4205,7 +4281,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 57 +Text 60 ======================================================================== UNICODE LICENSE V3 @@ -4247,7 +4323,7 @@ not be used in advertising or otherwise to promote the sale, use or other dealings in these Data Files or Software without prior written authorization of the copyright holder. -Text 58 +Text 61 ======================================================================== Copyright Mozilla Foundation @@ -4292,7 +4368,7 @@ licensed under the Apache License, Version 2.0 or or the MIT license or , at your option. -Text 59 +Text 62 ======================================================================== Apache License Version 2.0, January 2004 @@ -4496,7 +4572,7 @@ Apache License See the License for the specific language governing permissions and limitations under the License. -Text 60 +Text 63 ======================================================================== Copyright Mozilla Foundation @@ -4524,7 +4600,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 61 +Text 64 ======================================================================== The MIT License (MIT) Copyright (c) 2017-2018 Sergio Benitez @@ -4546,7 +4622,7 @@ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 62 +Text 65 ======================================================================== Apache License Version 2.0, January 2004 @@ -4750,7 +4826,7 @@ Apache License See the License for the specific language governing permissions and limitations under the License. -Text 63 +Text 66 ======================================================================== MIT License @@ -4774,7 +4850,7 @@ MIT License OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE -Text 64 +Text 67 ======================================================================== Copyright (c) 2015 Steven Allen @@ -4802,7 +4878,7 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 65 +Text 68 ======================================================================== The MIT License (MIT) @@ -4826,7 +4902,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Text 66 +Text 69 ======================================================================== (C) 2024 Trifecta Tech Foundation @@ -4848,7 +4924,7 @@ freely, subject to the following restrictions: 3. This notice may not be removed or altered from any source distribution. -Text 67 +Text 70 ======================================================================== Apache License Version 2.0, January 2004 diff --git a/docs/native-interop.md b/docs/native-interop.md index 01766c7..6537d39 100644 --- a/docs/native-interop.md +++ b/docs/native-interop.md @@ -93,6 +93,22 @@ native inputs but cannot set a library output kind. `vex run` still rejects library packages. `vex check` performs Wave checking without linking native inputs or producing native artifacts; it still validates their selected paths. +Windows DLLs also require an explicit list of exported C symbols: + +```wson +native = { output = "shared", exports = ["wave_add"] } +``` + +Public Wave `0.2.1-pre-beta` emits C ABI symbols for `export(c)` but does not +automatically add them to the DLL export table. Vex passes the root package's +`exports` to the Windows linker, which rejects undefined symbols. Entries must +be unique ASCII C identifiers; aliases, ordinals, and linker options are not +accepted. The source still needs `export(c)` (or its explicit symbol form). +`exports` is allowed only with `output = "shared"` and must be nonempty for +Windows shared builds. On ELF/Mach-O it is retained in metadata but does not +restrict symbol visibility. Dependency export lists are not merged into the +root DLL; list every intended public C symbol in the root package. + On Linux, a C caller can declare `int32_t wave_add(int32_t, int32_t);` and link the produced object with its C compiler. C++ callers use `extern "C"`; Rust callers use an `extern "C"` declaration and appropriate native linking. Keep the C diff --git a/docs/schemas/metadata-v1.json b/docs/schemas/metadata-v1.json index 1e32b5e..40b2d43 100644 --- a/docs/schemas/metadata-v1.json +++ b/docs/schemas/metadata-v1.json @@ -107,6 +107,14 @@ null ] }, + "exports": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" + }, + "uniqueItems": true + }, "libraries": { "type": "array", "items": { diff --git a/manifest/src/native.rs b/manifest/src/native.rs index ac79455..3c26cad 100644 --- a/manifest/src/native.rs +++ b/manifest/src/native.rs @@ -8,6 +8,7 @@ use crate::parse::reject_unknown_fields; #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct NativeConfig { pub output: Option, + pub exports: Vec, pub libraries: Vec, pub search_paths: Vec, } @@ -47,7 +48,11 @@ pub(crate) fn parse(value: Option<&WsonValue>, lib: bool) -> Result None, Some(_) if !lib => return Err("native field `output` requires `lib = true`".into()), @@ -58,6 +63,29 @@ pub(crate) fn parse(value: Option<&WsonValue>, lib: bool) -> Result, lib: bool) -> Result Value { None => Value::Null, Some(config) => json!({ "output":config.output.map(NativeOutput::as_str), + "exports":config.exports, "libraries":config.libraries.iter().map(|lib| json!({"path":lib.path,"name":lib.name,"target":lib.target})).collect::>(), "search_paths":config.search_paths.iter().map(|path| json!({"path":path.path,"target":path.target})).collect::>() }), @@ -276,7 +277,19 @@ pub fn prepare( .extend(["-C".into(), "relocation-model=pic".into()]); // wavec links through temporary files. Give the final library a // stable loader identity instead of embedding that temporary path. - if os == "macos" { + if os == "windows" { + let exports = &root.native.as_ref().unwrap().exports; + if exports.is_empty() { + return Err(Error::resolution( + "Windows shared libraries require a nonempty `native.exports` list of C symbols declared with `export(c)`", + )); + } + build.global.extend( + exports + .iter() + .map(|name| format!("-Clink-arg=/EXPORT:{name}")), + ); + } else if os == "macos" { build.global.extend([ "-Clink-arg=-install_name".into(), format!("-Clink-arg=@rpath/lib{}.dylib", root.name), diff --git a/tests/native_build.rs b/tests/native_build.rs index 36d7fb3..d6e4872 100644 --- a/tests/native_build.rs +++ b/tests/native_build.rs @@ -261,7 +261,12 @@ fn explicit_targets_choose_windows_and_macos_library_names() { ("x86_64-pc-windows-msvc", "shared", "app.dll"), ("aarch64-apple-darwin", "shared", "libapp.dylib"), ] { - let f = Fixture::new(true, &format!(",native={{output=\"{native}\"}}")); + let exports = if native == "shared" { + ",exports=[\"wave_add\"]" + } else { + "" + }; + let f = Fixture::new(true, &format!(",native={{output=\"{native}\"{exports}}}")); let value = plan(&f.run(&["build", "--target", target, "--dry-run"])); let output = if native == "object" { &value["compile"][0]["output"] @@ -274,6 +279,36 @@ fn explicit_targets_choose_windows_and_macos_library_names() { } } +#[test] +fn windows_shared_requires_explicit_exports_and_keeps_them_in_metadata() { + for target in ["x86_64-pc-windows-msvc", "aarch64-pc-windows-msvc"] { + let f = Fixture::new(true, ",native={output=\"shared\"}"); + code(&f.run(&["fetch", "--offline"]), 0); + let before = snapshot(&f.project); + let result = f.run(&["build", "--target", target, "--dry-run"]); + code(&result, 3); + assert!(String::from_utf8_lossy(&result.stderr).contains("native.exports")); + assert_eq!(snapshot(&f.project), before); + assert!(!f.project.join("compiler-started").exists()); + + f.package( + "app", + true, + ",native={output=\"shared\",exports=[\"wave_add\",\"_other2\"]}", + "", + ); + let value = plan(&f.run(&["build", "--target", target, "--dry-run"])); + let args = value["link"]["args"].as_array().unwrap(); + assert!(args.contains(&json!("/EXPORT:wave_add"))); + assert!(args.contains(&json!("/EXPORT:_other2"))); + let value = plan(&f.run(&["metadata", "--offline"])); + assert_eq!( + value["root"]["native"]["exports"], + json!(["wave_add", "_other2"]) + ); + } +} + #[test] fn root_and_transitive_inputs_use_the_declaring_package_and_preserve_link_order() { let f = Fixture::new(false, ""); @@ -464,7 +499,7 @@ fn metadata_reports_native_declarations_without_loading_compiler_or_inputs() { assert_eq!(value["root"]["native"]["libraries"][0]["name"], "rootlib"); assert_eq!( value["packages"][0]["native"], - json!({"output":"shared","libraries":[{"path":"missing.a","name":null,"target":"aarch64-apple-darwin"}],"search_paths":[{"path":"missing","target":"aarch64-apple-darwin"}]}) + json!({"output":"shared","exports":[],"libraries":[{"path":"missing.a","name":null,"target":"aarch64-apple-darwin"}],"search_paths":[{"path":"missing","target":"aarch64-apple-darwin"}]}) ); assert_eq!(snapshot(&f.project), before); assert!(f.invocations().is_empty()); diff --git a/tests/native_interop.py b/tests/native_interop.py index 535dc40..166776d 100644 --- a/tests/native_interop.py +++ b/tests/native_interop.py @@ -256,7 +256,8 @@ def outbound(vex, root, tools, spec): if obj.exists() or unknown.read_text(encoding="utf-8") != "preserve me": raise RuntimeError("clean failed to distinguish native output from user data") - package(project, "wave_exports", lib=True, native=dict(output="shared")) + package(project, "wave_exports", lib=True, + native=dict(output="shared", exports=["wave_add"])) outputs = build(vex, project, tools.env, root / "outbound-shared.jsonl") name = {"coff": "wave_exports.dll", "macho": "libwave_exports.dylib", "elf": "libwave_exports.so"}[spec["object_format"]] @@ -268,6 +269,23 @@ def outbound(vex, root, tools, spec): consumer = root / "shared consumer" consumer.mkdir() tools.consume(consumer, library, shared=True) + if tools.windows: + # A nonexistent export must fail linking rather than publish an empty + # import library or replace the previously usable DLL/import pair. + previous = {path: path.read_bytes() + for path in (library, library.with_suffix(".lib"))} + package(project, "wave_exports", lib=True, + native=dict(output="shared", exports=["missing_export"])) + report = root / "outbound-failure.jsonl" + failed = run([vex, "--message-file", report, "build", "--locked", "--offline"], + project, tools.env, expected=4) + outcome = events(report)[-1] + if ("missing_export" not in failed.stderr or outcome.get("origin") != "vex" + or outcome.get("exit_code") != 4 + or any(path.read_bytes() != content for path, content in previous.items())): + raise RuntimeError("undefined DLL export lost its error or previous library pair") + package(project, "wave_exports", lib=True, + native=dict(output="shared", exports=["wave_add"])) run([vex, "clean", "--dry-run"], project, tools.env) if not all(path.is_file() for path in outputs): raise RuntimeError("clean preview removed a shared output") diff --git a/toolchain/Cargo.toml b/toolchain/Cargo.toml index 33ebe80..3649e79 100644 --- a/toolchain/Cargo.toml +++ b/toolchain/Cargo.toml @@ -15,4 +15,4 @@ process.workspace = true semver = "1" sha2 = "0.10" tar = "0.4" -zip = { version = "8", default-features = false, features = ["deflate"] } +zip = { version = "9", default-features = false, features = ["deflate"] } diff --git a/toolchain/src/artifact.rs b/toolchain/src/artifact.rs index 5bf0faf..08b448f 100644 --- a/toolchain/src/artifact.rs +++ b/toolchain/src/artifact.rs @@ -665,7 +665,7 @@ fn extract(archive: &Path, root: &Path, zip: bool) -> Result<(), String> { if entry.is_symlink() { return Err(error("archive symlinks are unsupported")); } - let name = entry.name().to_string(); + let name = entry.name().map_err(error)?.into_owned(); let (directory, size, mode) = (entry.is_dir(), entry.size(), entry.unix_mode().unwrap_or(0)); write(&name, directory, size, &mut entry, mode)?;