Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/aien-abi-conformance/src/probe.rs # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / aien-abi-conformance / src / probe.rs` 254 lines ยท 9363 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 //! C side of the check (used from `build.rs`): headers, a compiled layout probe, and `nm`. 17 18 use crate::header; 19 use crate::manifest::Manifest; 20 use std::fmt::Write as _; 21 use std::path::{Path, PathBuf}; 22 use std::process::Command; 23 24 /// Inputs for [`check_c`]. 25 pub struct CCheck<'a> { 26 pub manifest: &'a Manifest, 27 /// Directory the manifest's `header` paths are relative to (the omega checkout). 28 pub root: &'a Path, 29 /// Extra `-I` directories the headers need (omega `src`, physics `m16`, ...). 30 pub includes: Vec, 31 /// The archive that will be linked; every manifest `fn` must be a defined global symbol. 32 /// `None` skips the symbol check (header-only use in tests). 33 pub archive: Option<&'a Path>, 34 /// Scratch directory for the probe source and binary. 35 pub work: &'a Path, 36 /// C compiler (`$CC` or `cc`). 37 pub cc: String, 38 } 39 40 /// Run every C-side check. `Ok(report)` lists what was checked; `Err` lists every mismatch. 41 pub fn check_c(c: &CCheck) -> Result> { 42 let m = c.manifest; 43 let mut errs = Vec::new(); 44 let mut report = String::new(); 45 46 // 1. Headers: field names and order, prototypes, callback typedefs. 47 let mut parsed = header::Header::default(); 48 for h in &m.headers { 49 let p = c.root.join(h); 50 match std::fs::read_to_string(&p) { 51 Ok(src) => { 52 let one = header::parse(&src); 53 parsed.structs.extend(one.structs); 54 parsed.fns.extend(one.fns); 55 parsed.fnptrs.extend(one.fnptrs); 56 } 57 Err(e) => errs.push(format!("cannot read header {}: {e}", p.display())), 58 } 59 } 60 for (s, ..) in &m.structs { 61 let want = m.field_names(s); 62 match parsed.structs.get(s) { 63 None => errs.push(format!("struct {s}: not declared in the headers")), 64 Some(got) if *got != want => errs.push(format!( 65 "struct {s}: C fields {got:?} != manifest fields {want:?} (added, removed, renamed or reordered)" 66 )), 67 Some(_) => {} 68 } 69 } 70 for (n, sig) in &m.fns { 71 match parsed.fns.get(n) { 72 None => errs.push(format!("fn {n}: no prototype in the headers")), 73 Some(got) if got != sig => { 74 errs.push(format!("fn {n}: C signature `{got}` != manifest `{sig}`")) 75 } 76 Some(_) => {} 77 } 78 } 79 for (n, sig) in &m.fnptrs { 80 match parsed.fnptrs.get(n) { 81 None => errs.push(format!("fnptr {n}: no typedef in the headers")), 82 Some(got) if got != sig => errs.push(format!( 83 "fnptr {n}: C signature `{got}` != manifest `{sig}`" 84 )), 85 Some(_) => {} 86 } 87 } 88 let _ = writeln!( 89 report, 90 "headers: {} structs, {} functions, {} callback types", 91 m.structs.len(), 92 m.fns.len(), 93 m.fnptrs.len() 94 ); 95 96 // 2. Probe: compiled against the same headers, prints the layout facts. 97 match run_probe(c) { 98 Ok(lines) => { 99 let want: Vec = m 100 .fact_lines() 101 .into_iter() 102 .filter(|l| !l.starts_with("fn") && !l.starts_with("fnptr")) 103 .collect(); 104 for w in &want { 105 if !lines.contains(w) { 106 let n = if w.starts_with("field ") { 3 } else { 2 }; 107 let key: Vec<&str> = w.split_whitespace().take(n).collect(); 108 let key = key.join(" "); 109 let got = lines 110 .iter() 111 .find(|l| l.starts_with(&format!("{key} "))) 112 .cloned() 113 .unwrap_or_else(|| "(absent)".into()); 114 errs.push(format!("layout: C `{got}` != manifest `{w}`")); 115 } 116 } 117 let _ = writeln!(report, "probe: {} layout/constant facts match", want.len()); 118 } 119 Err(e) => errs.push(e), 120 } 121 122 // 3. Symbols: every declared function is defined by the archive. 123 if let Some(a) = c.archive { 124 match defined_symbols(a) { 125 Ok(syms) => { 126 for (n, _) in &m.fns { 127 if !syms.iter().any(|s| s == n) { 128 errs.push(format!("symbol {n}: not defined in {}", a.display())); 129 } 130 } 131 let _ = writeln!(report, "nm: {} functions defined", m.fns.len()); 132 } 133 Err(e) => errs.push(e), 134 } 135 } 136 if errs.is_empty() { 137 Ok(report) 138 } else { 139 Err(errs) 140 } 141 } 142 143 /// The probe's C source for a manifest (public for tests and for the evidence record). 144 pub fn probe_source(m: &Manifest) -> String { 145 let mut s = String::from( 146 "#include \n#include \n#include \n#include \n", 147 ); 148 for h in &m.headers { 149 let _ = writeln!(s, "#include \"{h}\""); 150 } 151 s.push_str( 152 "_Static_assert(sizeof(long) == 8 && sizeof(void *) == 8, \"LP64 only\");\n\ 153 #define K(x) _Generic((x), _Bool: \"bool\", char: \"c_char\", signed char: \"i8\", \ 154 unsigned char: \"u8\", short: \"i16\", unsigned short: \"u16\", int: \"i32\", \ 155 unsigned int: \"u32\", long: \"i64\", unsigned long: \"u64\", long long: \"i64\", \ 156 unsigned long long: \"u64\", float: \"f32\", double: \"f64\", default: \"other\")\n\ 157 int main(void) {\n", 158 ); 159 for (st, size, align) in &m.structs { 160 let _ = (size, align); 161 let _ = writeln!( 162 s, 163 " printf(\"struct {st} %zu %zu\\n\", sizeof({st}), _Alignof({st}));" 164 ); 165 for (fs, f, _, _, _, n) in &m.fields { 166 if fs != st { 167 continue; 168 } 169 let el = if *n > 1 { 170 format!("((({st} *)0)->{f}[0])") 171 } else { 172 format!("((({st} *)0)->{f})") 173 }; 174 let _ = writeln!( 175 s, 176 " printf(\"field {st} {f} %zu %zu %s %zu\\n\", offsetof({st}, {f}), \ 177 sizeof((({st} *)0)->{f}), K({el}), sizeof((({st} *)0)->{f}) / sizeof({el}));" 178 ); 179 } 180 } 181 for (n, _) in &m.consts { 182 let _ = writeln!(s, " printf(\"const {n} %lld\\n\", (long long)({n}));"); 183 } 184 s.push_str(" return 0;\n}\n"); 185 s 186 } 187 188 fn run_probe(c: &CCheck) -> Result, String> { 189 std::fs::create_dir_all(c.work).map_err(|e| format!("probe dir: {e}"))?; 190 let src = c.work.join("abi_probe.c"); 191 let bin = c.work.join("abi_probe"); 192 std::fs::write(&src, probe_source(c.manifest)).map_err(|e| format!("probe source: {e}"))?; 193 let mut cmd = Command::new(&c.cc); 194 cmd.arg("-std=gnu11") 195 .arg("-D_GNU_SOURCE") 196 .arg("-w") 197 .arg("-I") 198 .arg(c.root); 199 for i in &c.includes { 200 cmd.arg("-I").arg(i); 201 } 202 let out = cmd 203 .arg("-o") 204 .arg(&bin) 205 .arg(&src) 206 .output() 207 .map_err(|e| format!("cannot run {}: {e}", c.cc))?; 208 if !out.status.success() { 209 let err = String::from_utf8_lossy(&out.stderr); 210 let first: Vec<&str> = err 211 .lines() 212 .filter(|l| l.contains("error")) 213 .take(6) 214 .collect(); 215 return Err(format!( 216 "layout probe did not compile against the headers (a field or constant the manifest names is missing or changed shape): {}", 217 first.join(" | ") 218 )); 219 } 220 let run = Command::new(&bin) 221 .output() 222 .map_err(|e| format!("cannot run the layout probe: {e}"))?; 223 if !run.status.success() { 224 return Err("layout probe exited nonzero".into()); 225 } 226 Ok(String::from_utf8_lossy(&run.stdout) 227 .lines() 228 .map(str::to_string) 229 .collect()) 230 } 231 232 /// Global symbols the archive defines (`nm -g --defined-only`). 233 pub fn defined_symbols(archive: &Path) -> Result, String> { 234 let out = Command::new("nm") 235 .arg("-g") 236 .arg("--defined-only") 237 .arg(archive) 238 .output() 239 .map_err(|e| format!("cannot run nm on {}: {e}", archive.display()))?; 240 if !out.status.success() { 241 return Err(format!( 242 "nm failed on {} (corrupt or truncated archive?): {}", 243 archive.display(), 244 String::from_utf8_lossy(&out.stderr).trim() 245 )); 246 } 247 Ok(String::from_utf8_lossy(&out.stdout) 248 .lines() 249 .filter_map(|l| { 250 let w: Vec<&str> = l.split_whitespace().collect(); 251 (w.len() == 3 && matches!(w[1], "T" | "D" | "R" | "B")).then(|| w[2].to_string()) 252 }) 253 .collect()) 254 }