From 44dde71da2fdd177bdefb496b81f6fe0ba6a61a6 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 19:36:01 -0700 Subject: [PATCH 1/3] chore(quest): claim quest/m1/ffi-export/contract.md Quest-Claim: 53e4cf6eda7dee63 From c29a110e4a84d3af5f9102d33fb93298ea378387 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 19:56:44 -0700 Subject: [PATCH 2/3] feat(ffi): a contract symbol each header and library check Each export's header defines _CONTRACT, a stable hash of what it declares, and the library exports _contract() returning it, so a binding refuses a header and a library from different builds. Co-Authored-By: Claude Opus 5.5 --- ffi/README.md | 4 +++ ffi/moq/moq.c | 1 + ffi/src/abi.rs | 4 +-- ffi/src/c.rs | 44 ++++++++++++++++++++++----------- ffi/src/glue.rs | 9 ++++++- ffi/tests/api.c | 4 +++ quest/m1/ffi-export/README.md | 3 ++- quest/m1/ffi-export/contract.md | 13 ---------- 8 files changed, 51 insertions(+), 31 deletions(-) delete mode 100644 quest/m1/ffi-export/contract.md diff --git a/ffi/README.md b/ffi/README.md index 7c5dc1a35..ba9ba4f06 100644 --- a/ffi/README.md +++ b/ffi/README.md @@ -114,6 +114,10 @@ refused, and the census counts why. - **Callbacks** are a struct of a table and its data. Rust calls `free` once it drops the implementation, and may call the others from any thread. A callback takes scalars and buffers lent for the call, and returns a scalar. +- **The contract** is a hash of the header's declarations, its docs included: the header + defines it as `_CONTRACT`, and `_contract()` returns it from the library + built with the header. A binding checks the two match before any other call, so a header + and a library from different builds refuse to mix. - **Panics** abort, as an `extern "C"` function's do. - **Names** are the prefix, then the item's path from its crate's root, each segment in snake case, joined by `_`: `track::Producer::append_group` is diff --git a/ffi/moq/moq.c b/ffi/moq/moq.c index 3d3da4b5a..bb411af39 100644 --- a/ffi/moq/moq.c +++ b/ffi/moq/moq.c @@ -45,6 +45,7 @@ static void wake(void *data) { int main(void) { moq_waker waker = {.wake = wake}; moq_error *err = NULL; + CHECK(moq_contract() == MOQ_CONTRACT); moq_broadcast_info *info = moq_broadcast_info_new(); moq_broadcast_producer *broadcast = moq_broadcast_info_produce(info); diff --git a/ffi/src/abi.rs b/ffi/src/abi.rs index efae91827..3bdcc2dcd 100644 --- a/ffi/src/abi.rs +++ b/ffi/src/abi.rs @@ -387,10 +387,10 @@ impl<'a> Abi<'a> { .map(|r| r.span) .or_else(|| api.objects.first().map(|o| o.span)) .unwrap_or(rustc_span::DUMMY_SP); - for runtime in ["buf", "buf_free", "duration", "waker", "poll"] { + for runtime in ["contract", "buf", "buf_free", "duration", "waker", "poll"] { self.claim(self.rt(runtime), "the runtime".to_string(), crate_span); } - for constant in ["POLL_PENDING", "POLL_READY", "POLL_ERROR"] { + for constant in ["CONTRACT", "POLL_PENDING", "POLL_READY", "POLL_ERROR"] { let name = format!("{}_{constant}", self.prefix.to_uppercase()); self.claim(name, "the runtime".to_string(), crate_span); } diff --git a/ffi/src/c.rs b/ffi/src/c.rs index 72f1e8912..72d4eb9c1 100644 --- a/ffi/src/c.rs +++ b/ffi/src/c.rs @@ -1,19 +1,43 @@ //! The C header: the declarations of everything [`crate::glue`] defines. use std::collections::BTreeSet; +use std::hash::Hasher; + +use rustc_data_structures::stable_hash::StableHasher; use crate::abi::{self, Abi, Sig, Ty}; use crate::ir::{Function, Int, Literal, Receiver, Traits, Type}; -/// The header for `abi`, as `.h`. -pub fn header(abi: &Abi<'_>, packages: &str) -> String { +/// The header for `abi`, as `.h`, and its contract: a hash of what it declares, +/// which the library returns from `_contract`. +pub fn header(abi: &Abi<'_>, packages: &str) -> (String, u64) { let mut h = Header { abi, out: String::new(), defined: BTreeSet::new(), }; - h.write(packages); - h.out + h.write(); + // Platform independent, so a header names the same contract wherever it is generated. + let mut hasher = StableHasher::new(); + hasher.write(h.out.as_bytes()); + let contract = Hasher::finish(&hasher); + let p = &abi.prefix; + let upper = p.to_uppercase(); + let guard = format!("{upper}_H"); + let header = format!( + "/* Generated by rust2-ffi: the C ABI of the pub API of {packages}. Do not edit. */\n\n\ + #ifndef {guard}\n#define {guard}\n\n\ + #include \n#include \n#include \n\n\ + #ifdef __cplusplus\nextern \"C\" {{\n#endif\n\n\ + /* A hash of everything below, which {p}_contract returns from a library built with\n * this header. Check it before any other call: a header and a library that declare\n * different APIs must not mix. */\n\ + #define {upper}_CONTRACT ((uint64_t)0x{contract:016x}ULL)\n\ + uint64_t {p}_contract(void);\n\n\ + {body}\n\ + #ifdef __cplusplus\n}}\n#endif\n\n\ + #endif /* {guard} */\n", + body = h.out, + ); + (header, contract) } struct Header<'a> { @@ -66,18 +90,12 @@ impl Header<'_> { format!("{};", self.decl(&sig.ret, &format!("{}({params})", sig.name))) } - fn write(&mut self, packages: &str) { + /// Everything the header declares but its contract. + fn write(&mut self) { let abi = self.abi; let api = abi.api; let p = abi.prefix.clone(); - let guard = format!("{}_H", p.to_uppercase()); let upper = p.to_uppercase(); - self.line(format!( - "/* Generated by rust2-ffi: the C ABI of the pub API of {packages}. Do not edit. */\n" - )); - self.line(format!("#ifndef {guard}\n#define {guard}\n")); - self.line("#include \n#include \n#include \n"); - self.line("#ifdef __cplusplus\nextern \"C\" {\n#endif\n"); self.line(format!( "/* Bytes. Passed in, a view Rust reads during the call and never frees. Returned,\n * an owned buffer to free once with {p}_buf_free. A null ptr is None. */\ntypedef struct {p}_buf {{\n\tconst uint8_t *ptr;\n\tsize_t len;\n\tvoid *owner;\n}} {p}_buf;\n\nvoid {p}_buf_free({p}_buf buf);\n" )); @@ -237,8 +255,6 @@ impl Header<'_> { for function in &api.functions { self.function(function, None); } - self.line("\n#ifdef __cplusplus\n}\n#endif\n"); - self.line(format!("#endif /* {guard} */")); } /// A value struct, after the structs its fields hold. diff --git a/ffi/src/glue.rs b/ffi/src/glue.rs index 84e1f1c0f..3c2677a8f 100644 --- a/ffi/src/glue.rs +++ b/ffi/src/glue.rs @@ -77,10 +77,11 @@ impl Crate<'_> { packages = self.packages(), lib = self.abi.prefix, ); - let header = crate::c::header(self.abi, &self.packages()); + let (header, contract) = crate::c::header(self.abi, &self.packages()); let mut generator = Gen { abi: self.abi, packages: self.packages(), + contract, dependencies: self.exports.iter().map(|export| dependency(&export.root())).collect(), out: String::new(), }; @@ -96,6 +97,8 @@ struct Gen<'a> { abi: &'a Abi<'a>, /// The exported packages, for the docs. packages: String, + /// The header's contract, which `_contract` returns. + contract: u64, /// The name the crate depends on each export by. dependencies: Vec, out: String, @@ -328,6 +331,10 @@ impl Gen<'_> { self.line(format!( "#[unsafe(no_mangle)]\npub unsafe extern \"C\" fn {p}_buf_free(buf: rt::Buf) {{\n\tunsafe {{ buf.free() }}\n}}\n" )); + self.line(format!( + "#[unsafe(no_mangle)]\npub extern \"C\" fn {p}_contract() -> u64 {{\n\t0x{:016x}\n}}\n", + self.contract + )); for (name, ty) in &self.abi.ranges { let (kind, int) = match ty { diff --git a/ffi/tests/api.c b/ffi/tests/api.c index 49d636c54..d9ba05d3c 100644 --- a/ffi/tests/api.c +++ b/ffi/tests/api.c @@ -384,6 +384,10 @@ static int broken(const char *which) { } int main(int argc, char **argv) { + if (api_contract() != API_CONTRACT) { + fprintf(stderr, "api.h and the library are from different builds\n"); + return 1; + } if (argc > 1) { return broken(argv[1]); } diff --git a/quest/m1/ffi-export/README.md b/quest/m1/ffi-export/README.md index d728049b2..a39688bd4 100644 --- a/quest/m1/ffi-export/README.md +++ b/quest/m1/ffi-export/README.md @@ -21,6 +21,8 @@ package's place. Every generator on the C ABI: +- checks `_contract()` against the header's contract when it loads, before any + other call, and fails loud on a mismatch; - is measured on the [binding benchmark](/bench/ffi/README.md); - keeps the C ABI's bulk and zero-copy payloads, with no per-byte loop on either side; - reports its generated size, raw and gzipped, against the fork's (Python 653 KiB, Kotlin @@ -40,6 +42,5 @@ Every generator on the C ABI: - [Closures lent for the call](/quest/m1/ffi-export/lent-closures.md) - a callback borrowed for one call, as `modify`'s `Guard` needs - [One library from several crates](/quest/m1/ffi-export/crates.md) - the C names the several-crate export still can't give - [Driving sessions and origins](/quest/m1/ffi-export/driving.md) - how a binding polls moq's `Driver` -- [A contract symbol](/quest/m1/ffi-export/contract.md) - a header and a library from different builds refuse to mix - [C++ bindings](/quest/m1/ffi-export/cpp.md) - C++17, 20, and 23 over the C ABI, with native futures - [Kotlin bindings](/quest/m1/ffi-export/kotlin.md) - JNI or Panama over the C ABI, with native futures diff --git a/quest/m1/ffi-export/contract.md b/quest/m1/ffi-export/contract.md deleted file mode 100644 index 30042d2dd..000000000 --- a/quest/m1/ffi-export/contract.md +++ /dev/null @@ -1,13 +0,0 @@ -# [S] A contract symbol - -## Goal - -Each build exports a contract symbol that bindings check when they load, so a header and a -library from different builds refuse to mix. - -## Plan - -It replaces the fork's namespaced contract and per-method checksums, which the export never -had. - -Public API: one exported symbol per library. From 677a93275f30560496e791e1bd0f1e9c6b6feaf3 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Tue, 27 Oct 2026 20:03:03 -0700 Subject: [PATCH 3/3] docs(ffi): the contract's reserved names in MIGRATE.md Co-Authored-By: Claude Opus 5.5 --- ffi/MIGRATE.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 ffi/MIGRATE.md diff --git a/ffi/MIGRATE.md b/ffi/MIGRATE.md new file mode 100644 index 000000000..4f308bf77 --- /dev/null +++ b/ffi/MIGRATE.md @@ -0,0 +1,7 @@ +# Migrating + +## Unreleased + +- Every export defines `_contract` and `_CONTRACT`, so an exported item + that the naming rule names either, such as a crate root's `pub fn contract` or + `pub const CONTRACT`, clashes with them: give it another name with a `rename`.