diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 15c71da373..66680eaa69 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -19,7 +19,7 @@ jobs: - name: Install tools run: | - brew install llvm lld pkgconf zig + brew install llvm lld zig echo "$(brew --prefix llvm)/bin" >> "$GITHUB_PATH" echo "$(brew --prefix lld)/bin" >> "$GITHUB_PATH" rustup target add aarch64-apple-darwin x86_64-apple-darwin \ diff --git a/crates/stela-driver-gpu/build/initcalls.rs b/crates/stela-driver-gpu/build/initcalls.rs index d14e4c45c7..6e76764b80 100644 --- a/crates/stela-driver-gpu/build/initcalls.rs +++ b/crates/stela-driver-gpu/build/initcalls.rs @@ -97,7 +97,11 @@ fn resolved(program: &Path) -> PathBuf { let found = env::var_os("PATH") .into_iter() .flat_map(|paths| env::split_paths(&paths).collect::>()) - .map(|directory| directory.join(program)) + .map(|directory| { + let mut candidate = directory.join(program).into_os_string(); + candidate.push(env::consts::EXE_SUFFIX); + PathBuf::from(candidate) + }) .find(|candidate| candidate.is_file()) .unwrap_or_else(|| program.to_path_buf()); fs::canonicalize(&found).unwrap_or_else(|error| panic!("{}: {error}", found.display())) @@ -143,8 +147,8 @@ pub fn compile(build: &cc::Build, unit: Unit, ordinal: u32) -> Captured { .arg(&depfile)); let dependencies = fs::read_to_string(&depfile) .unwrap_or_else(|error| panic!("{}: {error}", depfile.display())) - .replace("\\\n", " ") - .split_whitespace() + .lines() + .flat_map(|line| line.trim_end_matches('\\').split_whitespace()) .skip(1) .map(PathBuf::from) .collect(); diff --git a/crates/stela-driver-gpu/build/inputs.rs b/crates/stela-driver-gpu/build/inputs.rs index 716a04a486..160740245a 100644 --- a/crates/stela-driver-gpu/build/inputs.rs +++ b/crates/stela-driver-gpu/build/inputs.rs @@ -7,6 +7,7 @@ use sha2::{Digest, Sha256}; use std::{ collections::BTreeMap, fs::File, + io::Read, path::{Component, Path, PathBuf}, }; @@ -111,6 +112,11 @@ pub fn validate_relative(path: &Path) -> Result<()> { path.display() ); } + #[cfg(windows)] + require!( + path.to_str().is_some_and(|text| !text.contains(':')), + "invalid relative input components" + ); #[cfg(any(target_os = "linux", target_os = "macos"))] { use std::os::unix::ffi::OsStrExt; @@ -128,6 +134,40 @@ pub fn validate_relative(path: &Path) -> Result<()> { Ok(()) } +/// The bytes of `input`, at most `limit`: their count, digest and, when +/// `retain` is set, the bytes themselves. +fn stream(input: &mut File, limit: u64, retain: bool) -> Result<(u64, Hash, Option>)> { + let mut digest = Sha256::new(); + let mut bytes = retain.then(Vec::new); + let mut size = 0u64; + let mut buffer = [0u8; 64 * 1024]; + loop { + let remaining = limit + .checked_add(1) + .and_then(|bound| bound.checked_sub(size)) + .ok_or("input limit overflow")?; + let count = + usize::try_from(remaining.min(u64::try_from(buffer.len()).map_err(|e| e.to_string())?)) + .map_err(|e| e.to_string())?; + let read = input + .read(&mut buffer[..count]) + .map_err(|e| e.to_string())?; + if read == 0 { + break; + } + size = size + .checked_add(u64::try_from(read).map_err(|e| e.to_string())?) + .ok_or("input size overflow")?; + require!(size <= limit, "input grew beyond byte bound"); + digest.update(&buffer[..read]); + if let Some(bytes) = &mut bytes { + bytes.try_reserve(read).map_err(|error| error.to_string())?; + bytes.extend_from_slice(&buffer[..read]); + } + } + Ok((size, digest.finalize().into(), bytes)) +} + pub struct Inputs { limits: Limits, roots: Vec, @@ -139,7 +179,7 @@ impl Inputs { pub fn new(limits: Limits) -> Result { require!( platform::SUPPORTED, - "safe build inputs require Linux/macOS no-follow descriptor operations" + "safe build inputs require no-follow operations this host lacks" ); require!( limits.max_unique_files > 0 @@ -402,7 +442,7 @@ mod platform { use super::*; use std::{ ffi::{CString, OsStr}, - io::{self, Read}, + io, mem::MaybeUninit, os::{ fd::{AsRawFd, FromRawFd, RawFd}, @@ -595,33 +635,7 @@ mod platform { }); } hook(Step::BeforeRead)?; - let mut digest = Sha256::new(); - let mut bytes = retain.then(Vec::new); - let mut size = 0u64; - let mut buffer = [0u8; 64 * 1024]; - loop { - let remaining = limit - .checked_add(1) - .and_then(|bound| bound.checked_sub(size)) - .ok_or("input limit overflow")?; - let count = usize::try_from( - remaining.min(u64::try_from(buffer.len()).map_err(|e| e.to_string())?), - ) - .map_err(|e| e.to_string())?; - let read = os(input.read(&mut buffer[..count]))?; - if read == 0 { - break; - } - size = size - .checked_add(u64::try_from(read).map_err(|e| e.to_string())?) - .ok_or("input size overflow")?; - require!(size <= limit, "input grew beyond byte bound"); - digest.update(&buffer[..read]); - if let Some(bytes) = &mut bytes { - bytes.try_reserve(read).map_err(|error| error.to_string())?; - bytes.extend_from_slice(&buffer[..read]); - } - } + let (size, sha256, bytes) = stream(&mut input, limit, retain)?; hook(Step::AfterRead)?; let after = identity(&input)?; require!( @@ -630,14 +644,228 @@ mod platform { ); Ok(Capture { identity: after, - sha256: Some(digest.finalize().into()), + sha256: Some(sha256), bytes, }) } } } -#[cfg(not(any(target_os = "linux", target_os = "macos")))] +#[cfg(windows)] +mod platform { + use super::*; + use std::{ + ffi::OsStr, + fs::OpenOptions, + io, + mem::MaybeUninit, + os::windows::{fs::OpenOptionsExt, io::AsRawHandle}, + }; + pub(super) const SUPPORTED: bool = true; + /// Holding a directory open without delete sharing pins its name, which + /// gives the walk what a descriptor-relative open gives it on Unix. + const SHARE_READ_WRITE: u32 = 1 | 2; + const BACKUP_SEMANTICS: u32 = 0x0200_0000; + const OPEN_REPARSE_POINT: u32 = 0x0020_0000; + const ATTRIBUTE_DIRECTORY: u32 = 0x10; + const ATTRIBUTE_REPARSE_POINT: u32 = 0x400; + /// Windows times count this many units in a second, and 100 ns in each. + const TICKS_PER_SECOND: u64 = 10_000_000; + #[repr(C)] + struct Time { + low: u32, + high: u32, + } + impl Time { + fn split(&self) -> (i128, i128) { + let ticks = u64::from(self.high) << 32 | u64::from(self.low); + ( + i128::from(ticks / TICKS_PER_SECOND), + i128::from(ticks % TICKS_PER_SECOND) * 100, + ) + } + } + #[repr(C)] + struct Information { + attributes: u32, + creation: Time, + access: Time, + write: Time, + volume: u32, + size_high: u32, + size_low: u32, + links: u32, + index_high: u32, + index_low: u32, + } + unsafe extern "system" { + fn GetFileInformationByHandle(file: *mut core::ffi::c_void, out: *mut Information) -> i32; + } + pub(super) fn identity(file: &File) -> Result { + let mut value = MaybeUninit::::uninit(); + // SAFETY: live File owns the handle; the output storage is writable. + let status = + unsafe { GetFileInformationByHandle(file.as_raw_handle(), value.as_mut_ptr()) }; + require!( + status != 0, + "handle information: {}", + io::Error::last_os_error() + ); + // SAFETY: a successful call initialized the whole structure. + let value = unsafe { value.assume_init() }; + let (mtime_secs, mtime_nanos) = value.write.split(); + let (ctime_secs, ctime_nanos) = value.creation.split(); + Ok(Identity { + device: i128::from(value.volume), + inode: u128::from(value.index_high) << 32 | u128::from(value.index_low), + mode: u64::from(value.attributes), + bytes: u64::from(value.size_high) << 32 | u64::from(value.size_low), + mtime_secs, + mtime_nanos, + ctime_secs, + ctime_nanos, + }) + } + fn plain(value: &Identity) -> bool { + value.mode & u64::from(ATTRIBUTE_REPARSE_POINT) == 0 + } + fn directory_mode(value: &Identity) -> bool { + value.mode & u64::from(ATTRIBUTE_DIRECTORY) != 0 && plain(value) + } + fn regular(value: &Identity) -> bool { + value.mode & u64::from(ATTRIBUTE_DIRECTORY) == 0 && plain(value) + } + /// The object at `path` itself, a reparse point or not. + fn open(path: &Path) -> Result { + os(OpenOptions::new() + .read(true) + .share_mode(SHARE_READ_WRITE) + .custom_flags(BACKUP_SEMANTICS | OPEN_REPARSE_POINT) + .open(path)) + .map_err(|error| format!("no-follow open {}: {error}", path.display())) + } + fn os(value: io::Result) -> Result { + value.map_err(|error| error.to_string()) + } + fn open_directory(path: &Path) -> Result { + let directory = open(path)?; + require!( + directory_mode(&identity(&directory)?), + "not a plain directory: {}", + path.display() + ); + Ok(directory) + } + /// Each directory of `path` opened without following, held to the end. + fn absolute(path: &Path) -> Result> { + let mut prefix = PathBuf::new(); + let mut held = Vec::new(); + for part in path.components() { + prefix.push(part); + if matches!(part, Component::Normal(_)) { + held.push(open_directory(&prefix)?); + } + } + Ok(held) + } + #[derive(Clone, Copy, Debug, Eq, PartialEq)] + pub(super) enum Step { + BeforeDirectory(usize), + BeforeFinalOpen, + BeforeRead, + AfterRead, + } + pub(super) struct Capture { + pub identity: Identity, + pub sha256: Option, + pub bytes: Option>, + } + pub(super) struct Root { + pub path: PathBuf, + pub identity: Identity, + _held: Vec, + } + impl Root { + pub fn new(selected: &Path) -> Result { + let path = os(selected.canonicalize())?; + // Sources are joined with `/`, which a verbatim path takes literally. + let path = path + .to_str() + .and_then(|path| path.strip_prefix(r"\\?\")) + .map_or(path.clone(), PathBuf::from); + let held = absolute(&path)?; + let identity = identity(held.last().ok_or("input root has no directory")?)?; + Ok(Self { + path, + identity, + _held: held, + }) + } + pub fn check(&self) -> Result<()> { + let held = absolute(&self.path)?; + let current = held.last().ok_or("input root has no directory")?; + require!( + self.identity.same_object(&identity(current)?), + "selected input root changed" + ); + Ok(()) + } + pub fn capture( + &self, + relative: &Path, + limit: u64, + hash: bool, + retain: bool, + hook: &mut impl FnMut(Step) -> Result<()>, + ) -> Result { + validate_relative(relative)?; + let mut at = self.path.clone(); + let mut held = Vec::new(); + let parent = relative + .parent() + .filter(|path| !path.as_os_str().is_empty()); + for (index, part) in parent.iter().flat_map(|path| path.components()).enumerate() { + hook(Step::BeforeDirectory(index))?; + let Component::Normal(part) = part else { + return Err("invalid input directory component".into()); + }; + at.push::<&OsStr>(part); + held.push(open_directory(&at)?); + } + at.push(relative.file_name().ok_or("input filename missing")?); + hook(Step::BeforeFinalOpen)?; + let mut input = open(&at)?; + let before = identity(&input)?; + require!( + regular(&before) && before.bytes <= limit, + "nonregular/symlink/oversized input: {}", + relative.display() + ); + if !hash { + return Ok(Capture { + identity: before, + sha256: None, + bytes: None, + }); + } + hook(Step::BeforeRead)?; + let (size, sha256, bytes) = stream(&mut input, limit, retain)?; + hook(Step::AfterRead)?; + let after = identity(&input)?; + require!( + before == after && size == before.bytes, + "input changed during bounded capture" + ); + Ok(Capture { + identity: after, + sha256: Some(sha256), + bytes, + }) + } + } +} + +#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))] mod platform { use super::*; pub(super) const SUPPORTED: bool = false; diff --git a/crates/stela-driver-gpu/src/compat/llvm/include/llvm/Config/config.h b/crates/stela-driver-gpu/src/compat/llvm/include/llvm/Config/config.h index 7cbb5f7cb1..ba727bdd67 100644 --- a/crates/stela-driver-gpu/src/compat/llvm/include/llvm/Config/config.h +++ b/crates/stela-driver-gpu/src/compat/llvm/include/llvm/Config/config.h @@ -14,6 +14,9 @@ #define HAVE_DECL_ARC4RANDOM 0 #define HAVE_DECL_FE_ALL_EXCEPT 1 #define HAVE_DECL_FE_INEXACT 1 +#ifdef _WIN32 +#define HAVE_DECL_STRERROR_S 1 +#else #define HAVE_DECL_STRERROR_S 0 #define HAVE_GETPAGESIZE 1 #define HAVE_ISATTY 1 @@ -26,6 +29,7 @@ #define HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC 1 #endif #define HAVE_UNISTD_H 1 +#endif #define HAVE_ICU 0 #define HAVE_WINDOWS_ICU 0 #define HAVE_ICONV 0 diff --git a/crates/stela-driver-gpu/src/compat/llvm/include/llvm/Config/llvm-config.h b/crates/stela-driver-gpu/src/compat/llvm/include/llvm/Config/llvm-config.h index 8b23158883..5f3f39b5a9 100644 --- a/crates/stela-driver-gpu/src/compat/llvm/include/llvm/Config/llvm-config.h +++ b/crates/stela-driver-gpu/src/compat/llvm/include/llvm/Config/llvm-config.h @@ -6,8 +6,10 @@ #define LLVM_ENABLE_THREADS 0 #define LLVM_HAS_ATOMICS 1 #define LLVM_HOST_TRIPLE "x86_64-unknown-uefi" +#ifndef _WIN32 #define LLVM_ON_UNIX 1 #define HAVE_SYSEXITS_H 1 +#endif #define LLVM_USE_INTEL_JITEVENTS 0 #define LLVM_USE_OPROFILE 0 #define LLVM_USE_PERF 0 diff --git a/rust-toolchain.toml b/rust-toolchain.toml index 48e641769d..ebb201bb5f 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -2,4 +2,4 @@ channel = "stable" profile = "minimal" components = ["rustfmt", "clippy", "llvm-tools"] -targets = ["x86_64-unknown-uefi"] +targets = ["x86_64-unknown-linux-musl", "x86_64-unknown-uefi"] diff --git a/xtask/src/gpu/fetch.rs b/xtask/src/gpu/fetch.rs index 17cda3d28b..f156ee8f22 100644 --- a/xtask/src/gpu/fetch.rs +++ b/xtask/src/gpu/fetch.rs @@ -239,6 +239,8 @@ fn initialize(submodule: &Submodule) -> Result<()> { let directory = submodule.directory(); fs::create_dir_all(&directory)?; exec(git(&directory).args(["init", "-q"]))?; + // Pinned sources hash and build the same on every host. + exec(git(&directory).args(["config", "core.autocrlf", "false"]))?; exec(git(&directory).args(["remote", "add", "origin", &submodule.url]))?; first_checkout(submodule) } diff --git a/xtask/src/gpu/llvm.rs b/xtask/src/gpu/llvm.rs index 45f059a63a..f2f89ec2bd 100644 --- a/xtask/src/gpu/llvm.rs +++ b/xtask/src/gpu/llvm.rs @@ -120,6 +120,27 @@ const CXX_FLAGS: [&str; 8] = [ "-D__STDC_LIMIT_MACROS", "-fno-exceptions", ]; +/// What LLVM's Windows support code expects of a unit that builds on Windows. +const TOOL_WINDOWS_FLAGS: [&str; 4] = [ + "-DUNICODE", + "-D_UNICODE", + "-D_HAS_EXCEPTIONS=0", + "-D_WIN32_WINNT=0x0A00", +]; +/// The system libraries `llvm-min-tblgen` links. +const TOOL_LIBRARIES: &[&str] = if cfg!(windows) { + &[ + "-lole32", + "-lpsapi", + "-lshell32", + "-lws2_32", + "-lntdll", + "-luuid", + "-ladvapi32", + ] +} else { + &["-lm"] +}; /// What a C unit drops of the flags above. const CXX_ONLY: [&str; 4] = [ "-std=c++17", @@ -156,7 +177,7 @@ fn sources(directory: &Path, extensions: &[&str], found: &mut Vec) -> R fn unit(source: &Path, objects: &Path, root: &Path, flags: &[String]) -> Result { let relative = source.strip_prefix(root).unwrap_or(source); - let name = relative.to_string_lossy().replace(['/', '.'], "_") + ".o"; + let name = relative.to_string_lossy().replace(['/', '\\', '.'], "_") + ".o"; let mut arguments = flags.to_vec(); arguments.push( if source.extension().is_some_and(|extension| extension == "c") { @@ -228,6 +249,9 @@ fn build_tool(toolchain: &Toolchain, llvm: &Path, directory: &Path, jobs: u16) - fs::create_dir_all(&objects)?; let mut flags: Vec = CXX_FLAGS.map(str::to_owned).to_vec(); flags.push("-O1".to_owned()); + if cfg!(windows) { + flags.extend(TOOL_WINDOWS_FLAGS.map(str::to_owned)); + } for include in [gpu().join("compat/llvm/include"), llvm.join("include")] { flags.push(format!("-I{}", include.display())); } @@ -264,7 +288,7 @@ fn build_tool(toolchain: &Toolchain, llvm: &Path, directory: &Path, jobs: u16) - }) .collect::>>()?; compile(&toolchain.clang, directory, &units, jobs)?; - let tool = directory.join("llvm-min-tblgen"); + let tool = directory.join(format!("llvm-min-tblgen{}", std::env::consts::EXE_SUFFIX)); let newest = units .iter() .map(|unit| fs::metadata(&unit.output)?.modified()) @@ -280,7 +304,7 @@ fn build_tool(toolchain: &Toolchain, llvm: &Path, directory: &Path, jobs: u16) - .arg("-o") .arg(&tool) .args(units.iter().map(|unit| &unit.output)) - .arg("-lm"), + .args(TOOL_LIBRARIES), )?; } Ok(tool) @@ -417,11 +441,10 @@ pub(super) fn build(toolchain: &Toolchain, jobs: u16, test: bool) -> Result<()> if archive.is_file() { fs::remove_file(&archive)?; } - exec( - Command::new(&toolchain.archiver) - .arg("rcs") - .arg(&archive) - .args(units.iter().map(|unit| &unit.output)), + super::support::archive( + &toolchain.archiver, + &archive, + units.iter().map(|unit| &unit.output), )?; println!("{} objects in {}", units.len(), archive.display()); if test { diff --git a/xtask/src/gpu/mesa.rs b/xtask/src/gpu/mesa.rs index bb27d682cf..fde2b31e5e 100644 --- a/xtask/src/gpu/mesa.rs +++ b/xtask/src/gpu/mesa.rs @@ -7,6 +7,7 @@ use super::support::{ build_directory, capture, evidence_directory, gpu, source_binding, third_party, tool, }; +use super::toolchain::GENERATORS; use crate::tools; use anyhow::{Context, Result, ensure}; use meson::Build; @@ -389,8 +390,8 @@ pub fn build(options: BuildOptions<'_>) -> Result<()> { .and_then(|_| tools::which("clrxdisasm")) .map(|path| tools::binding(&path)) .transpose()?; - let meson = tool("meson", "generators/bin")?; - let ninja = tool("ninja", "generators/bin")?; + let meson = tool("meson", GENERATORS)?; + let ninja = tool("ninja", GENERATORS)?; let bindgen = tool("bindgen", "rust/bin")?; let cbindgen = tool("cbindgen", "rust/bin")?; let paths = [&meson, &ninja, &bindgen, &cbindgen] diff --git a/xtask/src/gpu/nvidia.rs b/xtask/src/gpu/nvidia.rs index a080951337..fd2291a102 100644 --- a/xtask/src/gpu/nvidia.rs +++ b/xtask/src/gpu/nvidia.rs @@ -65,12 +65,13 @@ impl Toolchain { .join("lib/rustlib") .join(host) .join("bin"); + let tool = |name: &str| directory.join(format!("{name}{}", std::env::consts::EXE_SUFFIX)); let toolchain = Self { clang: tools::which("clang").context("install Clang")?, clangxx: tools::which("clang++").context("install Clang's C++ compiler")?, - linker: directory.join("gcc-ld/ld.lld"), - objcopy: directory.join("llvm-objcopy"), - archiver: directory.join("llvm-ar"), + linker: tool("gcc-ld/ld.lld"), + objcopy: tool("llvm-objcopy"), + archiver: tool("llvm-ar"), }; for path in [&toolchain.linker, &toolchain.objcopy, &toolchain.archiver] { ensure!( diff --git a/xtask/src/gpu/nvk.rs b/xtask/src/gpu/nvk.rs index 0967f6916e..8ec8f4946e 100644 --- a/xtask/src/gpu/nvk.rs +++ b/xtask/src/gpu/nvk.rs @@ -9,8 +9,9 @@ //! the C library, the configuration below and the units in `compat/mesa`. use super::{ nvidia::Toolchain, - support::{NATIVE_TARGET, build_directory, capture, gpu, third_party, tool}, + support::{NATIVE_TARGET, build_directory, capture, gpu, slashed, third_party, tool}, sysroot::Sysroot, + toolchain::GENERATORS, }; use crate::tools::{self, exec}; use anyhow::{Context, Result, ensure}; @@ -210,7 +211,7 @@ fn paths(directory: &Path) -> Result<(PathBuf, PathBuf)> { let path = std::env::join_paths( [ stubs.clone(), - local.join("generators/bin"), + local.join(GENERATORS), local.join("rust/bin"), ] .into_iter() @@ -230,7 +231,7 @@ fn setup( ) -> Result<()> { let packages = directory.join("pkgconfig"); let machine = directory.join("machine.ini"); - let description = sysroot.machine_file(toolchain, &packages); + let description = sysroot.machine_file(toolchain, &packages)?; let plan = build.join("build.ninja"); let modified = |path: &Path| fs::metadata(path).and_then(|file| file.modified()).ok(); if modified(&plan) > modified(&sysroot.libc()) @@ -246,10 +247,13 @@ fn setup( fs::create_dir_all(&stubs)?; for name in UNUSED_TOOLS { let stub = stubs.join(name); - fs::write(&stub, "#!/bin/sh\nexit 1\n")?; - exec(Command::new("chmod").arg("+x").arg(&stub))?; + fs::write(&stub, "#!/usr/bin/env python3\nraise SystemExit(1)\n")?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&stub, fs::Permissions::from_mode(0o755))?; + } } - crate::tools::which("pkg-config").context("install pkg-config, which finds the .pc files")?; fs::create_dir_all(&packages)?; let libdrm = third_party("libdrm"); fs::write( @@ -257,28 +261,32 @@ fn setup( format!( "Name: libdrm\nDescription: vendored headers\nVersion: {LIBDRM_VERSION}\n\ Cflags: -I{0} -I{0}/include/drm\n", - libdrm.display() + slashed(&libdrm) ), )?; fs::write( packages.join("libelf.pc"), format!("Name: libelf\nDescription: unused\nVersion: {LIBELF_VERSION}\nCflags:\n"), )?; - exec( - Command::new(tool("meson", "generators/bin")?) - .arg("setup") - .arg(build) - .arg(third_party("mesa")) - .arg("--cross-file") - .arg(machine) - .args(OPTIONS) - .env("PATH", path), - ) + let mut setup = Command::new(tool("meson", GENERATORS)?); + setup + .arg("setup") + .arg(build) + .arg(third_party("mesa")) + .arg("--cross-file") + .arg(machine) + .args(OPTIONS) + .env("PATH", path); + // Rust on Windows does not link through the C compiler Meson finds. + if cfg!(windows) { + setup.env("RUSTC_LD_FOR_BUILD", "lld-link"); + } + exec(&mut setup) } /// Every source Meson generates, and the structured copy of the compiler crate. fn generate(sysroot: &Sysroot, build: &Path, path: &Path) -> Result<()> { - let ninja = tool("ninja", "generators/bin")?; + let ninja = tool("ninja", GENERATORS)?; let mut targets = BTreeSet::new(); for rule in ["CUSTOM_COMMAND", "CUSTOM_COMMAND_DEP"] { let listed = capture( @@ -311,11 +319,17 @@ fn generate(sysroot: &Sysroot, build: &Path, path: &Path) -> Result<()> { && !target.starts_with("meson-") && !target.ends_with("install") }); + // bindgen splits these as a shell does, and a path may hold a space. + let quoted: Vec<_> = sysroot + .compile + .iter() + .map(|argument| format!("\"{}\"", argument.replace('\\', "/"))) + .collect(); exec( Command::new(&ninja) .args(&targets) .current_dir(build) - .env("BINDGEN_EXTRA_CLANG_ARGS", sysroot.compile.join(" ")) + .env("BINDGEN_EXTRA_CLANG_ARGS", quoted.join(" ")) .env("PATH", path), ) } @@ -693,7 +707,7 @@ pub fn build(jobs: u16) -> Result<()> { common.extend(TARGET_FLAGS.map(str::to_owned)); common.extend(ADDED_DEFINES.map(|define| format!("-D{define}"))); common.push(format!("-I{}", gpu().join("compat/mesa").display())); - let ninja = tool("ninja", "generators/bin")?; + let ninja = tool("ninja", GENERATORS)?; let units = units(&build, &objects, &ninja, &path, &common)?; compile(&toolchain.clang, &build, &units, jobs)?; @@ -702,11 +716,10 @@ pub fn build(jobs: u16) -> Result<()> { if archive.is_file() { fs::remove_file(&archive)?; } - exec( - Command::new(&toolchain.archiver) - .arg("rcs") - .arg(&archive) - .args(units.iter().map(|unit| &unit.output)), + super::support::archive( + &toolchain.archiver, + &archive, + units.iter().map(|unit| &unit.output), )?; println!("{} objects in {}", units.len(), archive.display()); // The test is a static Linux program. diff --git a/xtask/src/gpu/support.rs b/xtask/src/gpu/support.rs index 4a374bfe14..2a8ccce4cd 100644 --- a/xtask/src/gpu/support.rs +++ b/xtask/src/gpu/support.rs @@ -23,6 +23,31 @@ pub fn third_party(name: &str) -> PathBuf { crate::tools::root().join("third_party").join(name) } +/// A path as Meson's files and `.pc` files read it: a backslash is an escape in both. +pub fn slashed(path: &Path) -> String { + path.display().to_string().replace('\\', "/") +} + +/// Archives `members` through a response file: thousands of paths outgrow a +/// Windows command line. +pub fn archive<'a>( + archiver: &Path, + archive: &Path, + members: impl Iterator, +) -> Result<()> { + let list = archive.with_extension("rsp"); + let quoted: Vec<_> = members + .map(|member| format!("\"{}\"", slashed(member))) + .collect(); + fs::write(&list, quoted.join("\n"))?; + crate::tools::exec( + Command::new(archiver) + .arg("rcs") + .arg(archive) + .arg(format!("@{}", list.display())), + ) +} + /// A build tree under Cargo's target directory. pub fn build_directory(name: &str) -> PathBuf { crate::tools::root().join("target/gpu").join(name) @@ -45,7 +70,7 @@ pub fn tool(name: &str, local: &str) -> Result { let path = crate::tools::root() .join(".tools/gpu") .join(local) - .join(name); + .join(format!("{name}{}", std::env::consts::EXE_SUFFIX)); path.is_file() .then_some(path) .or_else(|| crate::tools::which(name)) diff --git a/xtask/src/gpu/sysroot.rs b/xtask/src/gpu/sysroot.rs index 4288f35b48..ebf3dbd1c5 100644 --- a/xtask/src/gpu/sysroot.rs +++ b/xtask/src/gpu/sysroot.rs @@ -6,17 +6,18 @@ use super::{ llvm, nvidia::Toolchain, nvk::{LIBC, LIBC_TEST_FLAGS, REGEX, Unit, compile, resource_directory}, - support::{gpu, third_party}, + support::{gpu, slashed, third_party}, }; -use crate::tools::exec; use anyhow::Result; use std::{ fs, path::{Path, PathBuf}, - process::Command, }; const TARGET: &str = "--target=x86_64-unknown-linux-gnu"; +/// The Rust of the machine: nothing builds with it, and Meson checks that it +/// links programs. This target carries the C library that takes. +const RUST_TARGET: &str = "x86_64-unknown-linux-musl"; /// Some of Mesa's probes link shared libraries. const POSITION_INDEPENDENT: &str = "-fPIC"; @@ -70,8 +71,8 @@ impl Sysroot { // The compiler's own directory is a default one, which Meson drops // from `-isystem`. - let installed = format!("-idirafter{resource}"); - let system = |include: &Path| format!("-isystem{}", include.display()); + let installed = format!("-idirafter{}", resource.replace('\\', "/")); + let system = |include: &Path| format!("-isystem{}", slashed(include)); let shared = [TARGET.to_owned(), "-nostdinc".to_owned()]; let mut compile = shared.to_vec(); compile.extend([system(&libc), installed.clone(), "-DSTELA_LIBC".to_owned()]); @@ -98,7 +99,7 @@ impl Sysroot { } /// Meson's description of the machine, with `.pc` files in `packages`. - pub fn machine_file(&self, toolchain: &Toolchain, packages: &Path) -> String { + pub fn machine_file(&self, toolchain: &Toolchain, packages: &Path) -> Result { let list = |flags: &[String]| { flags .iter() @@ -108,20 +109,22 @@ impl Sysroot { }; let mut link = vec![ TARGET.to_owned(), - format!("--ld-path={}", toolchain.linker.display()), - format!("--sysroot={}", self.directory.display()), + format!("--ld-path={}", slashed(&toolchain.linker)), + format!("--sysroot={}", slashed(&self.directory)), "-nostdlib".to_owned(), ]; let mut link_cxx = link.clone(); link.push("-lc".to_owned()); link_cxx.extend(["-lc++".to_owned(), "-lc".to_owned()]); - format!( + Ok(format!( "[binaries]\n\ c = '{clang}'\n\ cpp = '{clangxx}'\n\ ar = '{archiver}'\n\ - rust = 'rustc'\n\ - pkg-config = 'pkg-config'\n\ + nm = '{symbols}'\n\ + rust = ['rustc', '--target', '{RUST_TARGET}', '-C', 'link-arg={TARGET}', \ + '-C', 'link-arg=--ld-path={linker}']\n\ + pkg-config = '{pkg_config}'\n\ [built-in options]\n\ c_args = [{compile}]\n\ cpp_args = [{compile_cxx}]\n\ @@ -135,15 +138,22 @@ impl Sysroot { cpu_family = 'x86_64'\n\ cpu = 'x86_64'\n\ endian = 'little'\n", - clang = toolchain.clang.display(), - clangxx = toolchain.clangxx.display(), - archiver = toolchain.archiver.display(), + clang = slashed(&toolchain.clang), + clangxx = slashed(&toolchain.clangxx), + archiver = slashed(&toolchain.archiver), + symbols = slashed( + &toolchain + .archiver + .with_file_name(format!("llvm-nm{}", std::env::consts::EXE_SUFFIX)) + ), + linker = slashed(&toolchain.linker), + pkg_config = super::toolchain::pkg_config()?, compile = list(&self.compile), compile_cxx = list(&self.compile_cxx), link = list(&link), link_cxx = list(&link_cxx), - packages = packages.display(), - ) + packages = slashed(packages), + )) } } @@ -157,10 +167,9 @@ fn archive(toolchain: &Toolchain, archive: &Path, units: &[Unit]) -> Result<()> if archive.is_file() { fs::remove_file(archive)?; } - exec( - Command::new(&toolchain.archiver) - .arg("rcs") - .arg(archive) - .args(units.iter().map(|unit| &unit.output)), + super::support::archive( + &toolchain.archiver, + archive, + units.iter().map(|unit| &unit.output), ) } diff --git a/xtask/src/gpu/toolchain.rs b/xtask/src/gpu/toolchain.rs index 5e5b55e065..8a7163fecd 100644 --- a/xtask/src/gpu/toolchain.rs +++ b/xtask/src/gpu/toolchain.rs @@ -2,7 +2,7 @@ //! Ninja and Mesa's Python generator modules in a virtual environment, and the //! Rust binding generators NAK's build calls. use crate::tools::{self, exec}; -use anyhow::{Result, bail, ensure}; +use anyhow::{Context, Result, bail, ensure}; use sha2::{Digest, Sha256}; use std::{fs, path::PathBuf, process::Command}; @@ -26,9 +26,10 @@ const STANDALONE: [(&str, &str); 3] = [ "4595c5589fff7bf0cb158d9a88a797e0d791fa33830770fcb7bf3f4b104feeae", ), ]; -const PYTHON_PACKAGES: [&str; 5] = [ +const PYTHON_PACKAGES: [&str; 6] = [ "meson==1.11.2", "ninja==1.13.2", + "pkgconf==2.5.1.post2", "Mako==1.4.3", "packaging==26.3", "PyYAML==6.0.3", @@ -36,17 +37,48 @@ const PYTHON_PACKAGES: [&str; 5] = [ const RUST_PACKAGES: [&str; 2] = ["bindgen-cli@0.73.2", "cbindgen@0.29.4"]; /// The pins an installation was made from, beside it. const STAMP: &str = "stela-pins"; +/// Where a virtual environment keeps its programs, under `.tools/gpu`. +pub const GENERATORS: &str = if cfg!(windows) { + "generators/Scripts" +} else { + "generators/bin" +}; +/// The virtual environment's Python, under `.tools/gpu/generators`. +const VENV_PYTHON: &str = if cfg!(windows) { + "Scripts/python.exe" +} else { + "bin/python3" +}; fn directory() -> PathBuf { tools::root().join(".tools/gpu") } +/// Meson's pkg-config. The wheel's launcher loses its output to whoever +/// captures it, so Meson runs the program it wraps, which needs no system one. +pub fn pkg_config() -> Result { + let generators = directory().join("generators"); + let packages = if cfg!(windows) { + generators.join("Lib/site-packages") + } else { + fs::read_dir(generators.join("lib"))? + .next() + .context("the generators name no Python")?? + .path() + .join("site-packages") + }; + Ok(super::support::slashed(&packages.join(format!( + "pkgconf/.bin/pkgconf{}", + std::env::consts::EXE_SUFFIX + )))) +} + /// Installs whatever is missing or pinned differently, then returns. pub fn install() -> Result<()> { let generators = directory().join("generators"); let pins = PYTHON_PACKAGES.join("\n") + "\n"; if fs::read_to_string(generators.join(STAMP)).ok().as_deref() != Some(pins.as_str()) { - let python = generators.join("bin/python3"); + let python = generators.join(VENV_PYTHON); if !python.is_file() { exec( Command::new(base_python()?) diff --git a/xtask/src/tools.rs b/xtask/src/tools.rs index 8e6eca4fb0..81ec94b86c 100644 --- a/xtask/src/tools.rs +++ b/xtask/src/tools.rs @@ -36,9 +36,10 @@ pub fn exec(command: &mut Command) -> Result<()> { } pub fn which(name: impl AsRef) -> Option { - let name = name.as_ref(); + let mut name = name.as_ref().to_owned(); + name.push(env::consts::EXE_SUFFIX); env::split_paths(&env::var_os("PATH")?) - .map(|directory| directory.join(name)) + .map(|directory| directory.join(&name)) .find(|path| path.is_file()) }