Files

150 lines
6.0 KiB
Rust

#[path = "src/embedded_spec.rs"]
mod embedded_spec;
fn main() {
embed_engine().expect("invalid embedded engine build configuration");
println!("cargo:rerun-if-changed=src/ggml_bridge.c");
println!("cargo:rerun-if-changed=third_party/ggml");
println!("cargo:rerun-if-changed=src/ggml_msvc_stubs.c");
let mut build = cc::Build::new();
build
.file("third_party/ggml/ggml-quants.c")
.file("src/ggml_bridge.c")
.include("third_party/ggml")
.flag_if_supported("-std=c11")
.flag_if_supported("-ffunction-sections")
.flag_if_supported("-fdata-sections")
.warnings(false);
// The Windows linkers (MSVC and the mingw one used by the Docker cross-build) keep the quantizer object and
// need ggml.c's four helpers; see the file.
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
build.file("src/ggml_msvc_stubs.c");
}
build.compile("strata_ggml_quants");
}
type BuildResult<T> = Result<T, Box<dyn std::error::Error>>;
/// The three variables that configure an embedded engine: all unset, or all set.
const ENGINE_VARS: [&str; 3] =
["STRATA_EMBED_ENGINE_PATH", "STRATA_EMBED_ENGINE_SHA256", "STRATA_EMBED_ENGINE_REVISION"];
fn embed_engine() -> BuildResult<()> {
use std::{env, fs, path::PathBuf};
for name in ENGINE_VARS {
println!("cargo:rerun-if-env-changed={name}");
}
let values: Vec<_> = ENGINE_VARS.iter().map(env::var_os).collect();
let output = PathBuf::from(env::var_os("OUT_DIR").ok_or("missing OUT_DIR")?);
let payload_path = output.join("embedded-engine.bin");
let (digest, revision) = write_payload(&values, &payload_path)?;
let size = fs::metadata(&payload_path)?.len();
let declaration = if size == 0 {
"pub const BYTES: &[u8] = &[];\n".to_owned()
} else {
payload_declaration(&output, &payload_path, size)?
};
fs::write(
output.join("embedded-engine.rs"),
format!(
"{declaration}\
pub const SHA256: &str = {digest:?};\n\
pub const SOURCE_REVISION: &str = {revision:?};\n"
),
)?;
Ok(())
}
/// Writes the verified engine bytes to `payload_path`; returns the lowercase digest and revision
/// (both empty when no engine is embedded).
fn write_payload(
values: &[Option<std::ffi::OsString>],
payload_path: &std::path::Path,
) -> BuildResult<(String, String)> {
use std::{env, fs};
if values.iter().all(Option::is_none) {
fs::write(payload_path, [])?;
return Ok((String::new(), String::new()));
}
let file = open_engine(values)?;
let digest = values[1].as_ref().unwrap().to_str().ok_or("digest must be ASCII")?;
let revision = values[2].as_ref().unwrap().to_str().ok_or("revision must be ASCII")?;
embedded_spec::copy_verified(
file,
fs::File::create(payload_path)?,
&env::var("CARGO_CFG_TARGET_ARCH")?,
digest,
revision,
)?;
Ok((digest.to_ascii_lowercase(), revision.to_ascii_lowercase()))
}
/// All three variables must be set, and the target must be Linux.
fn check_engine_config(values: &[Option<std::ffi::OsString>]) -> BuildResult<()> {
if values.iter().any(Option::is_none) {
return Err("set all three STRATA_EMBED_ENGINE_PATH/SHA256/REVISION variables".into());
}
if std::env::var("CARGO_CFG_TARGET_OS")? != "linux" {
return Err("embedded engines require a Linux target".into());
}
Ok(())
}
/// The canonical engine path from `STRATA_EMBED_ENGINE_PATH`; cargo reruns when the file changes.
fn engine_path(value: &std::ffi::OsString) -> BuildResult<std::path::PathBuf> {
let path = std::path::PathBuf::from(value).canonicalize()?;
let printable = path.to_str().ok_or("engine path must be UTF-8")?;
if printable.contains(['\n', '\r']) {
return Err("engine path cannot contain newlines".into());
}
println!("cargo:rerun-if-changed={printable}");
Ok(path)
}
/// Checks the configuration and opens the engine file named by `STRATA_EMBED_ENGINE_PATH`.
fn open_engine(values: &[Option<std::ffi::OsString>]) -> BuildResult<std::fs::File> {
check_engine_config(values)?;
let path = engine_path(values[0].as_ref().unwrap())?;
let file = std::fs::File::open(path)?;
if !file.metadata()?.is_file() {
return Err("embedded engine must be a regular file".into());
}
if file.metadata()?.len() > embedded_spec::MAX_BYTES {
return Err("embedded engine exceeds 1 GiB".into());
}
Ok(file)
}
/// The assembler source that places the payload file in an immutable ELF section.
fn engine_assembly(path: &str) -> String {
format!(
".section .rodata.strata_engine,\"a\"\n\
.balign 16\n\
.global strata_embedded_engine_bytes\n\
.hidden strata_embedded_engine_bytes\n\
strata_embedded_engine_bytes:\n\
.incbin \"{path}\"\n\
.size strata_embedded_engine_bytes, .-strata_embedded_engine_bytes\n\
.section .note.GNU-stack,\"\"\n"
)
}
/// Assembles the payload into the crate and returns the Rust declaration of `BYTES` for it.
fn payload_declaration(output: &std::path::Path, payload_path: &std::path::Path, size: u64) -> BuildResult<String> {
// Keep large verified payloads out of Rust constant evaluation/LLVM IR.
// The target assembler copies the bytes into an immutable ELF section.
let path = payload_path.to_str().ok_or("payload path must be UTF-8")?;
if path.contains(['\n', '\r']) {
return Err("payload path cannot contain newlines".into());
}
let path = path.replace('\\', "\\\\").replace('"', "\\\"");
let assembly = output.join("embedded-engine.S");
std::fs::write(&assembly, engine_assembly(&path))?;
cc::Build::new().file(assembly).compile("strata_embedded_payload");
Ok(format!(
"unsafe extern \"C\" {{ static strata_embedded_engine_bytes: [u8; {size}]; }}\n\
// SAFETY: build.rs emits exactly {size} verified bytes in read-only storage.\n\
pub static BYTES: &[u8] = unsafe {{ &strata_embedded_engine_bytes }};\n"
))
}