build.rs
cdk-rsx/crates/cdk-rsx-memory-abi/build.rs
1//! Source qualification complements, and never replaces, physical reflection.2use cdk_rsx_compat as compatibility;3use sha2::{Digest, Sha256};4use std::{5 env, fs,6 io::{self, Read},7 path::{Path, PathBuf},8 process::Command,9};1011fn word(hash: &mut Sha256, value: &[u8]) {12 hash.update((value.len() as u64).to_le_bytes());13 hash.update(value);14}15fn file(hash: &mut Sha256, label: &str, path: &Path) {16 word(hash, label.as_bytes());17 let mut input =18 fs::File::open(path).unwrap_or_else(|e| panic!("ABI source {}: {e}", path.display()));19 hash.update(input.metadata().unwrap().len().to_le_bytes());20 let mut buffer = [0u8; 65536];21 loop {22 let count = input.read(&mut buffer).expect("ABI source read");23 if count == 0 {24 break;25 }26 hash.update(&buffer[..count]);27 }28 println!("cargo:rerun-if-changed={}", path.display());29}30fn source_files(path: &Path, files: &mut Vec<PathBuf>) -> io::Result<()> {31 for entry in fs::read_dir(path)? {32 let entry = entry?;33 let kind = entry.file_type()?;34 assert!(!kind.is_symlink(), "unqualified source symlink");35 if kind.is_dir() {36 source_files(&entry.path(), files)?;37 } else if kind.is_file() {38 files.push(entry.path());39 }40 }41 Ok(())42}43fn rustc(argument: &str) -> String {44 let compiler = env::var_os("RUSTC").expect("qualified Cargo RUSTC");45 let result = Command::new(compiler)46 .arg(argument)47 .output()48 .expect("qualified compiler facts");49 assert!(result.status.success(), "qualified compiler query failed");50 String::from_utf8(result.stdout).expect("compiler facts UTF-8")51}52fn main() {53 for name in [54 compatibility::CONTEXT_ENV,55 compatibility::ALIASES_ENV,56 compatibility::TOOLING_ENV,57 ] {58 println!("cargo:rerun-if-env-changed={name}");59 }60 let context = match env::var(compatibility::CONTEXT_ENV) {61 Ok(value) => Some(value),62 Err(env::VarError::NotPresent) => None,63 Err(error) => panic!("compiler compatibility context: {error}"),64 };65 let aliases = env::var_os(compatibility::ALIASES_ENV).map(PathBuf::from);66 if let Some(path) = &aliases {67 println!("cargo:rerun-if-changed={}", path.display());68 }69 let resolver = compatibility::Resolver::load(context.as_deref(), aliases.as_deref())70 .unwrap_or_else(|error| panic!("compiler compatibility: {error}"));71 let compiler = PathBuf::from(env::var_os("RUSTC").expect("qualified Cargo RUSTC"));72 let sysroot = PathBuf::from(rustc("--print=sysroot").trim());73 let library = sysroot.join("lib/rustlib/src/rust/library");74 assert!(75 library.is_dir(),76 "ABI qualification requires the pinned rust-src used by -Zbuild-std"77 );78 let version = rustc("-vV");79 println!("cargo:rerun-if-changed={}", library.display());80 println!("cargo:rerun-if-changed={}", sysroot.join("lib").display());81 let mut hash = Sha256::new();82 word(&mut hash, b"cdk-rsx-compiler-source-class-v2");83 word(&mut hash, version.as_bytes());84 // The canonical builder pins the trusted producer/build dependency closure.85 // Registry records, their paths and the resolution context stay detached.86 word(&mut hash, compatibility::TOOLING_ENV.as_bytes());87 match env::var(compatibility::TOOLING_ENV) {88 Ok(tooling) => word(89 &mut hash,90 &compatibility::parse_fingerprint(&tooling)91 .unwrap_or_else(|error| panic!("compiler tooling qualification: {error}")),92 ),93 Err(env::VarError::NotPresent) => word(&mut hash, b"unqualified"),94 Err(error) => panic!("compiler tooling qualification: {error}"),95 }96 file(&mut hash, "rustc", &compiler);97 let mut drivers: Vec<_> = fs::read_dir(sysroot.join("lib"))98 .expect("compiler library directory")99 .map(|entry| entry.unwrap().path())100 .filter(|path| {101 // This build script runs on the compiler host, even for Wasm.102 let name = path.file_name().unwrap().to_string_lossy();103 name.starts_with("librustc_driver-") && name.ends_with(env::consts::DLL_SUFFIX)104 })105 .collect();106 drivers.sort();107 assert_eq!(108 drivers.len(),109 1,110 "ABI qualification requires one exact compiler driver"111 );112 file(&mut hash, "rustc-driver", &drivers[0]);113 // Include the pinned LLVM shared library and any accompanying linker114 // script. Paths themselves never enter the class.115 let mut backends: Vec<_> = fs::read_dir(sysroot.join("lib"))116 .unwrap()117 .map(|entry| entry.unwrap().path())118 .filter(|path| {119 path.file_name()120 .unwrap()121 .to_string_lossy()122 .starts_with("libLLVM")123 })124 .collect();125 backends.sort();126 assert!(!backends.is_empty(), "missing qualified LLVM backend");127 hash.update((backends.len() as u64).to_le_bytes());128 for path in backends {129 file(130 &mut hash,131 &path.file_name().unwrap().to_string_lossy(),132 &path,133 );134 }135 let mut sources = Vec::new();136 source_files(&library, &mut sources).expect("complete pinned standard-library source");137 sources.sort();138 assert!(139 !sources.is_empty(),140 "empty standard-library source qualification"141 );142 hash.update((sources.len() as u64).to_le_bytes());143 for path in sources {144 file(145 &mut hash,146 &path.strip_prefix(&library).unwrap().to_string_lossy(),147 &path,148 );149 }150 for name in [151 "TARGET",152 "CARGO_CFG_TARGET_ARCH",153 "CARGO_CFG_TARGET_POINTER_WIDTH",154 "CARGO_CFG_TARGET_ENDIAN",155 "CARGO_CFG_TARGET_FEATURE",156 "CARGO_CFG_TARGET_HAS_ATOMIC",157 "CARGO_CFG_PANIC",158 "CARGO_ENCODED_RUSTFLAGS",159 ] {160 println!("cargo:rerun-if-env-changed={name}");161 word(&mut hash, name.as_bytes());162 word(&mut hash, env::var(name).unwrap_or_default().as_bytes());163 }164 // Exact SDK qualification recipes, never the application executable/source.165 for name in [166 "Cargo.toml",167 "src/lib.rs",168 "src/catalog.rs",169 "src/rooted.rs",170 "src/tagged.rs",171 "build.rs",172 ] {173 file(&mut hash, name, Path::new(name));174 }175 // Cargo chooses and tracks these exact-version build dependencies. Hash176 // their recipe bytes without assuming a workspace sibling layout.177 for (owner, recipe) in [178 (179 "cdk-rsx-compat",180 [181 ("Cargo.toml", compatibility::RECIPE_MANIFEST.as_bytes()),182 ("src/lib.rs", compatibility::RECIPE_SOURCE.as_bytes()),183 ],184 ),185 (186 "cdk-rsx-memory-abi-derive",187 cdk_rsx_memory_abi_derive::__abi_recipe!(),188 ),189 ("cdk-rsx-platform", cdk_rsx_platform::profile::__ABI_RECIPE),190 ] {191 word(&mut hash, owner.as_bytes());192 for (path, bytes) in recipe {193 word(&mut hash, path.as_bytes());194 word(&mut hash, bytes);195 }196 }197 let raw: [u8; 32] = hash.finalize().into();198 let scope = format!(199 "compiler/{}",200 env::var("TARGET").expect("compiler qualification target")201 );202 let identity = resolver.resolve(&scope, raw);203 let record = resolver.record(&scope, raw, identity);204 let record = compatibility::wasm_record(&record);205 let generated = format!(206 r#"pub const RAW_COMPILER_SOURCE_CLASS: [u8;32] = {raw:?};207pub const COMPILER_SOURCE_CLASS: [u8;32] = {identity:?};208{record}209"#210 );211 fs::write(212 PathBuf::from(env::var_os("OUT_DIR").unwrap()).join("compiler_class.rs"),213 generated,214 )215 .expect("compiled ABI qualification constants");216}