1use crate::walk::Canonical;
5use std::path::{Path, PathBuf};
6use std::process::Command;
7
8use anyhow::{Context, Result, bail};
9use serde_json::{Value, json};
10
11use crate::bridge::Manifest;
12use crate::harness::{BenchRow, CASES, DiffOutcome};
13use crate::lang::c::{defines_main, scalar};
14
15const WORK_DIR: &str = ".rust-anything";
16
17fn run(cmd: &mut Command, what: &str) -> Result<()> {
18 let _scratch = crate::harness::scratch_cwd(cmd)?;
19 let output = cmd
20 .output()
21 .map_err(|e| crate::process::spawn_error(cmd, what, e))?;
22 if !output.status.success() {
23 let stderr = String::from_utf8_lossy(&output.stderr);
24 let tail: Vec<&str> = stderr.lines().rev().take(25).collect();
25 bail!(
26 "{what} failed ({}):\n{}",
27 output.status,
28 tail.into_iter().rev().collect::<Vec<_>>().join("\n")
29 );
30 }
31 Ok(())
32}
33
34fn compiler() -> &'static str {
35 if Command::new("cc").arg("--version").output().is_ok() {
36 "cc"
37 } else {
38 "gcc"
39 }
40}
41
42fn signatures(manifest: &Manifest) -> Value {
48 use crate::codegen_c::{CKind, c_struct, kind, pointee, returns_into};
49 let ctype = |c: &str| scalar(c).map_or("c_int", |(_, _, _, ct)| ct).to_string();
50 let structure = |ts: &str| {
51 c_struct(ts).map(|s| {
52 let fields: Vec<String> = s
53 .fields
54 .iter()
55 .map(|(ty, name)| format!("{name}={}", ctype(ty)))
56 .collect();
57 format!("struct:{}", fields.join(","))
58 })
59 };
60 let map: serde_json::Map<String, Value> = manifest
61 .exports
62 .iter()
63 .map(|f| {
64 let args: Vec<String> = f
65 .params
66 .iter()
67 .map(|p| {
68 let native = p.native_type.as_deref().unwrap_or("int");
69 match kind(p) {
70 CKind::Str => "c_char_p".into(),
71 CKind::Bytes => "bytes".into(),
72 CKind::Buffer => "buffer".into(),
73 CKind::Len(i) => format!("len:{i}:{}", ctype(native)),
74 CKind::Out => format!("out:{}", ctype(&pointee(native))),
75 CKind::OutPtr(i) => format!("outptr:{i}"),
76 CKind::Struct => structure(&p.ts_type).unwrap_or_else(|| "c_int".into()),
77 CKind::Scalar => ctype(native),
78 }
79 })
80 .collect();
81 let ret = match returns_into(f) {
82 Some(i) => format!("ptr:{i}"),
83 None if structure(&f.returns).is_some() => {
84 structure(&f.returns).unwrap_or_default()
85 }
86 None if f.native_return.as_deref().unwrap_or("void") == "void" => "None".into(),
87 None => ctype(f.native_return.as_deref().unwrap_or("int")),
88 };
89 (
90 f.name.clone(),
91 json!({
92 "args": args,
93 "ret": ret,
94 "names": f.params.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(),
95 "writes": crate::codegen_c::writes(f),
96 }),
97 )
98 })
99 .collect();
100 Value::Object(map)
101}
102
103fn build_original(crate_dir: &Path, manifest: &Manifest) -> Result<PathBuf> {
105 let (sources, include_dirs) = original_sources(manifest)?;
106 let out = crate_dir.join(WORK_DIR).join("original.so");
107 std::fs::create_dir_all(crate_dir.join(WORK_DIR))?;
108 let mut cmd = Command::new(compiler());
109 cmd.args(["-shared", "-fPIC", "-O1", "-w", "-o"]).arg(&out);
110 cmd.args(include_args(&include_dirs));
111 cmd.args(&sources).arg("-lm");
112 run(&mut cmd, "cc (original sources)")?;
113 Ok(out)
114}
115
116fn include_args(dirs: &std::collections::BTreeSet<PathBuf>) -> Vec<String> {
120 let mut out = Vec::new();
121 for dir in dirs {
122 let shadows = crate::lang::c::STANDARD_HEADERS.iter().any(|h| {
123 dir.join(h.trim_start_matches('<').trim_end_matches('>'))
124 .is_file()
125 });
126 if shadows {
127 out.push("-iquote".into());
128 out.push(dir.display().to_string());
129 } else {
130 out.push(format!("-I{}", dir.display()));
131 }
132 }
133 out.extend(
134 std::env::var("CFLAGS")
135 .unwrap_or_default()
136 .split_whitespace()
137 .map(str::to_string),
138 );
139 out
140}
141
142fn driver(crate_dir: &Path, manifest: &Manifest) -> Result<(PathBuf, PathBuf)> {
143 let work = crate_dir.join(WORK_DIR);
144 std::fs::create_dir_all(&work)?;
145 let path = work.join("driver_c.py");
146 std::fs::write(&path, DRIVER_C_PY)?;
147 let sigs = work.join("signatures.json");
148 std::fs::write(&sigs, serde_json::to_string(&signatures(manifest))?)?;
149 Ok((path, sigs))
150}
151
152fn python() -> Command {
153 let mut cmd = Command::new("python3");
154 cmd.env("PYTHONDONTWRITEBYTECODE", "1");
155 cmd
156}
157
158pub fn record(crate_dir: &Path, manifest: &Manifest, cases: &[Value]) -> Result<PathBuf> {
159 let original = build_original(crate_dir, manifest)?;
160 let (driver, sigs) = driver(crate_dir, manifest)?;
161 let out = crate_dir.join(CASES);
162 crate::harness::record_cases(
163 cases,
164 &crate_dir.join(WORK_DIR),
165 &out,
166 "python (ctypes)",
167 |inputs, part| {
168 let mut cmd = python();
169 cmd.arg(&driver)
170 .arg("record")
171 .arg(&original)
172 .arg(&sigs)
173 .arg(inputs)
174 .arg(part);
175 Ok(cmd)
176 },
177 )?;
178 Ok(out)
179}
180
181pub fn build(crate_dir: &Path, manifest: &Manifest) -> Result<PathBuf> {
183 let target = crate::cache::target_for(crate_dir)?;
184 run(
185 Command::new("cargo")
186 .args(["build", "--release", "--manifest-path"])
187 .arg(crate_dir.join("Cargo.toml"))
188 .env("CARGO_TARGET_DIR", &target.dir),
189 "cargo build",
190 )?;
191 let lib = manifest.lib_name();
192 let release = crate::cache::publish(&target, crate_dir, &lib, &target.dir.join("release"))?;
193 [
194 format!("lib{lib}.so"),
195 format!("lib{lib}.dylib"),
196 format!("{lib}.dll"),
197 ]
198 .iter()
199 .map(|n| release.join(n))
200 .find(|p| p.exists())
201 .with_context(|| format!("no shared library for `{lib}` in {}", release.display()))
202}
203
204pub fn built_library(crate_dir: &Path, manifest: &Manifest) -> Result<PathBuf> {
206 let lib = manifest.lib_name();
207 let release = crate_dir.join("target/release");
208 [
209 format!("lib{lib}.so"),
210 format!("lib{lib}.dylib"),
211 format!("{lib}.dll"),
212 ]
213 .iter()
214 .map(|n| release.join(n))
215 .find(|p| p.exists())
216 .with_context(|| {
217 format!(
218 "no built library in {} (run `rust-anything build {}` first)",
219 release.display(),
220 crate_dir.display()
221 )
222 })
223}
224
225pub fn diff(crate_dir: &Path, manifest: &Manifest) -> Result<DiffOutcome> {
226 let cases = crate_dir.join(CASES);
227 if !cases.exists() {
228 bail!(
229 "no {CASES} in {} (run `rust-anything record` first)",
230 crate_dir.display()
231 );
232 }
233 let rust = built_library(crate_dir, manifest)?;
234 let (driver, sigs) = driver(crate_dir, manifest)?;
235 let out = crate_dir.join(WORK_DIR).join("diff.json");
236 run(
237 python()
238 .arg(&driver)
239 .arg("diff")
240 .arg(&rust)
241 .arg(&sigs)
242 .arg(&cases)
243 .arg(&out),
244 "python (ctypes)",
245 )?;
246 Ok(serde_json::from_str(&std::fs::read_to_string(&out)?)?)
247}
248
249pub fn bench(crate_dir: &Path, manifest: &Manifest, min_ms: u64) -> Result<Vec<BenchRow>> {
250 let cases_path = crate_dir.join(CASES);
251 if !cases_path.exists() {
252 bail!(
253 "no {CASES} in {} (run `rust-anything record` first)",
254 crate_dir.display()
255 );
256 }
257 let rust = built_library(crate_dir, manifest)?.canonical()?;
258 let work = crate_dir.canonical()?.join(WORK_DIR);
259 std::fs::create_dir_all(&work)?;
260 let cases: Vec<Value> = std::fs::read_to_string(&cases_path)?
261 .lines()
262 .filter(|l| !l.trim().is_empty())
263 .map(serde_json::from_str)
264 .collect::<Result<_, _>>()?;
265 let source = work.join("bench.c");
266 std::fs::write(&source, bench_c(manifest, &cases, min_ms))?;
267 let (sources, include_dirs) = original_sources(manifest)?;
270 let bin = work.join("bench");
271 let mut cmd = Command::new(compiler());
272 cmd.args(["-O2", "-w", "-o"]).arg(&bin).arg(&source);
273 for f in crate::codegen_c::shadow_flags(manifest).split_whitespace() {
274 cmd.arg(f);
275 }
276 cmd.args(include_args(&include_dirs));
277 cmd.args(&sources)
278 .arg(&rust)
279 .arg(format!(
280 "-Wl,-rpath,{}",
281 rust.parent()
282 .map_or_else(String::new, |p| p.display().to_string())
283 ))
284 .arg("-lm");
285 run(&mut cmd, "cc (bench)")?;
286 let out = work.join("bench.json");
287 run(Command::new(&bin).arg(&out), "bench")?;
288 let timings: serde_json::Map<String, Value> =
289 serde_json::from_str(&std::fs::read_to_string(&out)?)?;
290 Ok(manifest
291 .exports
292 .iter()
293 .filter_map(|f| {
294 let t = timings.get(&f.name)?;
295 let (o, n) = (t["original_ns"].as_f64()?, t["rust_ns"].as_f64()?);
296 Some(BenchRow {
297 failing: false,
298 name: f.name.clone(),
299 cases: usize::try_from(t["cases"].as_u64().unwrap_or(0)).unwrap_or(0),
300 original_ns: o,
301 rust_ns: n,
302 speedup: o / n,
303 })
304 })
305 .collect())
306}
307
308fn original_sources(
310 manifest: &Manifest,
311) -> Result<(Vec<PathBuf>, std::collections::BTreeSet<PathBuf>)> {
312 let ws = crate::lang::c::discover(&manifest.root)?;
313 let mut sources = Vec::new();
314 let mut include_dirs = std::collections::BTreeSet::new();
315 include_dirs.insert(manifest.root.clone());
316 for file in ws
317 .files
318 .iter()
319 .filter(|f| f.kind == crate::ts::discover::FileKind::Source)
320 {
321 let path = manifest.root.join(&file.path);
322 if let Some(dir) = path.parent() {
323 include_dirs.insert(dir.to_path_buf());
324 }
325 if file.path.ends_with(".c")
326 && !defines_main(&std::fs::read_to_string(&path).unwrap_or_default())
327 {
328 sources.push(path);
329 }
330 }
331 for entry in crate::walk::builder(&manifest.root)
332 .require_git(false)
333 .build()
334 .flatten()
335 {
336 if entry.path().extension().is_some_and(|e| e == "h")
337 && let Some(dir) = entry.path().parent()
338 {
339 include_dirs.insert(dir.to_path_buf());
340 }
341 }
342 Ok((sources, include_dirs))
343}
344
345fn c_literal(s: &str) -> String {
347 let mut out = String::from("\"");
348 for b in s.bytes() {
349 match b {
350 b'"' => out.push_str("\\\""),
351 b'\\' => out.push_str("\\\\"),
352 0x20..=0x7e if b != b'?' => out.push(b as char),
353 _ => out.push_str(&format!("\\{b:03o}")),
354 }
355 }
356 out.push('"');
357 out
358}
359
360fn c_arg(v: &Value, c_type: &str, is_string: bool) -> Option<String> {
362 if is_string {
363 return match v {
364 Value::String(s) => Some(c_literal(s)),
365 Value::Null => Some("NULL".into()),
366 _ => None,
367 };
368 }
369 let float = matches!(
370 c_type.trim_start_matches("const ").trim(),
371 "double" | "float" | "long double"
372 );
373 match v {
374 Value::Number(n) if float => n
375 .as_f64()
376 .map(|x| format!("({c_type})rust_anything_f({}ULL)", x.to_bits())),
377 Value::Object(o) if float => {
378 let x = match o.get("$num")?.as_str()? {
379 "NaN" => f64::NAN,
380 "Infinity" => f64::INFINITY,
381 "-Infinity" => f64::NEG_INFINITY,
382 _ => -0.0,
383 };
384 Some(format!("({c_type})rust_anything_f({}ULL)", x.to_bits()))
385 }
386 Value::Number(n) => n
387 .as_i64()
388 .map(|i| format!("({c_type}){i}LL"))
389 .or_else(|| n.as_u64().map(|u| format!("({c_type}){u}ULL"))),
390 Value::Bool(b) => Some(format!("({c_type}){}", i32::from(*b))),
391 _ => None,
392 }
393}
394
395fn c_bytes_literal(bytes: &[u8]) -> String {
397 let mut out = String::from("\"");
398 for &b in bytes {
399 let _ = std::fmt::Write::write_fmt(&mut out, format_args!("\\{b:03o}"));
400 }
401 out.push('"');
402 out
403}
404
405fn buffer_arg(v: &Value) -> Option<Option<Vec<u8>>> {
407 match v {
408 Value::Null => Some(None),
409 Value::Number(n) => Some(Some(vec![0; usize::try_from(n.as_u64()?).ok()?])),
410 Value::String(s) => {
411 if s.len() % 2 != 0 {
412 return None;
413 }
414 (0..s.len())
415 .step_by(2)
416 .map(|i| u8::from_str_radix(s.get(i..i + 2)?, 16).ok())
417 .collect::<Option<Vec<u8>>>()
418 .map(Some)
419 }
420 _ => None,
421 }
422}
423
424fn c_call(
427 f: &crate::ts::exports::ExportedFn,
428 args: &[Value],
429 tag: &str,
430) -> Option<(String, String, String)> {
431 use crate::codegen_c::{CKind, kind, pointee};
432 use std::fmt::Write as _;
433 let mut given = args.iter();
434 let values: Vec<Value> = f
435 .params
436 .iter()
437 .map(|p| match kind(p) {
438 CKind::Len(_) => Value::Null,
439 _ => given.next().cloned().unwrap_or(Value::Null),
440 })
441 .collect();
442 let (mut globals, mut setup) = (String::new(), String::new());
443 let mut lens = std::collections::HashMap::new();
444 let mut exprs = Vec::new();
445 for (i, (p, v)) in f.params.iter().zip(&values).enumerate() {
446 let native = p.native_type.as_deref().unwrap_or("int");
447 let expr = match kind(p) {
448 CKind::Str => c_arg(v, native, true)?,
449 CKind::Bytes => match buffer_arg(v)? {
450 None => "NULL".into(),
451 Some(bytes) => {
452 lens.insert(i, bytes.len());
453 format!("({native}){}", c_bytes_literal(&bytes))
454 }
455 },
456 CKind::Buffer => match buffer_arg(v)? {
457 None => "NULL".into(),
458 Some(bytes) => {
459 let n = bytes.len();
460 lens.insert(i, n);
461 let _ = writeln!(
462 globals,
463 "static const unsigned char init_{tag}_{i}[{}] = {};\nstatic unsigned char buf_{tag}_{i}[{}];",
464 n.max(1),
465 c_bytes_literal(&bytes),
466 n.max(1)
467 );
468 let _ = write!(setup, "memcpy(buf_{tag}_{i}, init_{tag}_{i}, {n}); ");
469 format!("({native})buf_{tag}_{i}")
470 }
471 },
472 CKind::Out => {
473 if v.is_null() {
474 "NULL".into()
475 } else {
476 let ty = pointee(native);
477 let _ = writeln!(globals, "static {ty} out_{tag}_{i};");
478 let _ = write!(setup, "out_{tag}_{i} = {}; ", c_arg(v, &ty, false)?);
479 format!("&out_{tag}_{i}")
480 }
481 }
482 CKind::Struct => {
483 let s = crate::codegen_c::c_struct(&p.ts_type)?;
484 let Value::Object(o) = v else {
485 return None;
486 };
487 let fields = s
488 .fields
489 .iter()
490 .map(|(ty, name)| {
491 let v = o.get(name).cloned().unwrap_or(Value::from(0));
492 Some(format!(".{name} = {}", c_arg(&v, ty, false)?))
493 })
494 .collect::<Option<Vec<_>>>()?;
495 format!("({}){{{}}}", s.c_name, fields.join(", "))
496 }
497 CKind::OutPtr(_) => match v {
498 Value::Null => "NULL".into(),
499 _ => {
500 let _ = writeln!(
501 globals,
502 "static {};",
503 crate::codegen_c::c_decl(
504 native.trim_end().strip_suffix('*').unwrap_or(native),
505 &format!("slot_{tag}_{i}")
506 )
507 );
508 format!("&slot_{tag}_{i}")
509 }
510 },
511 CKind::Len(_) => String::new(),
512 CKind::Scalar => c_arg(v, native, false)?,
513 };
514 exprs.push(expr);
515 }
516 for (i, (p, v)) in f.params.iter().zip(&values).enumerate() {
517 if let CKind::OutPtr(target) = kind(p)
518 && !v.is_null()
519 {
520 let at = match v.as_u64() {
521 Some(k) if !v.is_boolean() => format!("({}) + {k}", exprs[target]),
522 _ => "NULL".into(),
523 };
524 let _ = write!(setup, "slot_{tag}_{i} = {at}; ");
525 }
526 }
527 for (i, p) in f.params.iter().enumerate() {
528 if let CKind::Len(target) = kind(p) {
529 exprs[i] = format!(
530 "({}){}",
531 p.native_type.as_deref().unwrap_or("int"),
532 lens.get(&target).copied().unwrap_or(0)
533 );
534 }
535 }
536 Some((globals, setup, exprs.join(", ")))
537}
538
539fn bench_c(m: &Manifest, cases: &[Value], min_ms: u64) -> String {
541 use std::fmt::Write as _;
542 let mut out = String::from(
543 "#include <stdbool.h>\n#include <stddef.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <string.h>\n\
544 #include <sys/types.h>\n#include <time.h>\n\n\
545 static double rust_anything_f(uint64_t bits) { double d; memcpy(&d, &bits, sizeof d); return d; }\n\
546 static double now_ns(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1e9 + t.tv_nsec; }\n\
547 static volatile uint64_t sink;\n\n",
548 );
549 out.push_str(&crate::codegen_c::c_struct_defs(m));
550 let mut rows = Vec::new();
551 for f in &m.exports {
552 let _ = writeln!(
553 out,
554 "{};\n{};",
555 crate::codegen_c::c_prototype(f, &format!("{}__original", f.name)),
556 crate::codegen_c::c_prototype(f, &format!("rust_anything_{}", f.name))
557 );
558 let mut calls = Vec::new();
559 for (k, c) in cases
560 .iter()
561 .filter(|c| c["fn"] == f.name.as_str() && c.get("error").is_none())
562 .enumerate()
563 {
564 let args = c["args"].as_array().cloned().unwrap_or_default();
565 if let Some((globals, setup, exprs)) = c_call(f, &args, &format!("{}_{k}", f.name)) {
566 out.push_str(&globals);
567 calls.push((setup, exprs));
568 }
569 }
570 if calls.is_empty() {
571 continue;
572 }
573 let void = f.native_return.as_deref() == Some("void");
574 let first_field = crate::codegen_c::c_struct(&f.returns)
575 .and_then(|s| s.fields.first().map(|(_, n)| n.clone()));
576 let body = |target: &str| -> String {
577 calls
578 .iter()
579 .map(|(setup, a)| {
580 if void {
581 format!(" {setup}{target}({a});\n")
582 } else if let Some(field) = &first_field {
583 format!(" {setup}sink += (uint64_t){target}({a}).{field};\n")
584 } else {
585 format!(" {setup}sink += (uint64_t)(uintptr_t){target}({a});\n")
586 }
587 })
588 .collect()
589 };
590 let _ = writeln!(
591 out,
592 "static void pass_{n}_original(void) {{\n{}}}\nstatic void pass_{n}_rust(void) {{\n{}}}\n",
593 body(&format!("{}__original", f.name)),
594 body(&format!("rust_anything_{}", f.name)),
595 n = f.name
596 );
597 rows.push((f.name.clone(), calls.len()));
598 }
599 let _ = writeln!(
600 out,
601 "static double timed(void (*pass)(void), int calls) {{\n pass();\n double start = now_ns(), elapsed;\n long passes = 0;\n\
602 \x20 do {{ pass(); passes++; elapsed = now_ns() - start; }} while (elapsed < {min_ms} * 1e6);\n return elapsed / ((double)passes * calls);\n}}\n\n\
603 int main(int argc, char **argv) {{\n FILE *out = fopen(argv[1], \"w\");\n fputs(\"{{\", out);"
604 );
605 for (i, (name, n)) in rows.iter().enumerate() {
606 let _ = writeln!(
607 out,
608 " fprintf(out, \"{}\\\"{name}\\\": {{\\\"cases\\\": {n}, \\\"original_ns\\\": %f, \\\"rust_ns\\\": %f}}\", \
609 timed(pass_{name}_original, {n}), timed(pass_{name}_rust, {n}));",
610 if i == 0 { "" } else { "," }
611 );
612 }
613 out.push_str(" fputs(\"}\", out);\n fclose(out);\n return 0;\n}\n");
614 out
615}
616
617const DRIVER_C_PY: &str = r#"
618import ctypes
619import json
620import locale
621import math
622import os
623import signal
624import sys
625import time
626
627# Python switches C's locale to the user's at startup; a C program stays in "C" unless it calls
628# setlocale, so the library must see "C" here (isspace, toupper, strtod depend on it).
629locale.setlocale(locale.LC_ALL, "C")
630
631
632def enc(v):
633 if isinstance(v, float):
634 if math.isnan(v):
635 return {"$num": "NaN"}
636 if math.isinf(v):
637 return {"$num": "Infinity" if v > 0 else "-Infinity"}
638 if v == 0 and math.copysign(1, v) < 0:
639 return {"$num": "-0"}
640 if isinstance(v, bytes):
641 return {"$bytes": list(v)}
642 return v
643
644
645def dec(v):
646 if isinstance(v, dict) and len(v) == 1:
647 (key, inner), = v.items()
648 if key == "$undefined":
649 return None
650 if key == "$num":
651 return {"NaN": math.nan, "Infinity": math.inf, "-Infinity": -math.inf, "-0": -0.0}[inner]
652 return v
653
654
655STRUCTS = {}
656
657
658def structure(kind):
659 """The ctypes Structure for `struct:<field>=<ctype>,...`."""
660 if kind not in STRUCTS:
661 fields = [f.split("=", 1) for f in kind[len("struct:"):].split(",")]
662 STRUCTS[kind] = type("Struct", (ctypes.Structure,), {"_fields_": [(n, getattr(ctypes, t)) for n, t in fields]})
663 return STRUCTS[kind]
664
665
666def scalar(ctype, value):
667 if ctype in (ctypes.c_float, ctypes.c_double):
668 return float(value) if isinstance(value, (int, float)) else 0.0
669 if ctype is ctypes.c_bool:
670 return bool(value)
671 return int(value) if isinstance(value, (int, float)) and math.isfinite(value) else 0
672
673
674def to_struct(kind, value):
675 """A struct argument from an object of its fields; missing fields are zero."""
676 if not isinstance(value, dict):
677 raise TypeError("expects an object with fields %s" % ", ".join(n for n, _ in structure(kind)._fields_))
678 cls = structure(kind)
679 return cls(**{n: scalar(t, dec(value.get(n, 0))) for n, t in cls._fields_})
680
681
682def from_struct(value):
683 return {n: enc(getattr(value, n)) for n, _ in type(value)._fields_}
684
685
686def argtype(kind):
687 if kind.startswith("struct:"):
688 return structure(kind)
689 if kind in ("bytes", "buffer") or kind.startswith("out:") or kind.startswith("outptr:"):
690 return ctypes.c_void_p
691 if kind.startswith("len:"):
692 return getattr(ctypes, kind.split(":")[2])
693 return getattr(ctypes, kind)
694
695
696def bind(path, signatures):
697 lib = ctypes.CDLL(path)
698 functions = {}
699 for name, sig in signatures.items():
700 try:
701 fn = getattr(lib, name)
702 except AttributeError:
703 continue
704 fn.argtypes = [argtype(t) for t in sig["args"]]
705 ret = sig["ret"]
706 if ret == "None":
707 fn.restype = None
708 elif ret.startswith("ptr:"):
709 fn.restype = ctypes.c_void_p
710 elif ret.startswith("struct:"):
711 fn.restype = structure(ret)
712 else:
713 fn.restype = getattr(ctypes, ret)
714 functions[name] = (fn, sig)
715 return functions
716
717
718def as_bytes(value):
719 """A buffer argument: hex text, or a size for that many zero bytes; None is NULL."""
720 if value is None:
721 return None
722 if isinstance(value, bool):
723 return bytes(int(value))
724 if isinstance(value, (int, float)):
725 return bytes(max(int(value), 0))
726 return bytes.fromhex(str(value))
727
728
729def call(functions, c):
730 fn, sig = functions[c["fn"]]
731 kinds = sig["args"]
732 given = iter([dec(a) for a in c["args"]])
733 values = [None if k.startswith("len:") else next(given, None) for k in kinds]
734 args = [None] * len(kinds)
735 memory = {}
736 outs = {}
737 for i, (value, kind) in enumerate(zip(values, kinds)):
738 if kind == "c_char_p":
739 if value is not None:
740 data = str(value).encode("utf-8")
741 buf = ctypes.create_string_buffer(data)
742 memory[i] = (buf, len(data) + 1)
743 args[i] = ctypes.cast(buf, ctypes.c_char_p)
744 elif kind in ("bytes", "buffer"):
745 data = as_bytes(value)
746 if data is not None:
747 buf = ctypes.create_string_buffer(data, max(len(data), 1))
748 memory[i] = (buf, len(data))
749 args[i] = ctypes.cast(buf, ctypes.c_void_p)
750 elif kind.startswith("out:"):
751 if value is not None:
752 ctype = getattr(ctypes, kind[4:])
753 cell = ctype(value if ctype in (ctypes.c_float, ctypes.c_double) else int(value))
754 outs[i] = cell
755 args[i] = ctypes.cast(ctypes.pointer(cell), ctypes.c_void_p)
756 elif kind.startswith("struct:"):
757 args[i] = to_struct(kind, value)
758 elif kind.startswith("outptr:"):
759 pass
760 elif kind in ("c_float", "c_double"):
761 args[i] = float(value) if isinstance(value, (int, float)) else 0.0
762 elif kind == "c_bool":
763 args[i] = bool(value)
764 elif not kind.startswith("len:"):
765 args[i] = int(value) if isinstance(value, (int, float)) and math.isfinite(value) else 0
766 for i, kind in enumerate(kinds):
767 if kind.startswith("len:"):
768 target = int(kind.split(":")[1])
769 args[i] = memory[target][1] if target in memory else 0
770 slots = {}
771 for i, (value, kind) in enumerate(zip(values, kinds)):
772 if kind.startswith("outptr:") and value is not None:
773 # The starting pointer: an offset into its target argument, or NULL for `true`.
774 target = int(kind.split(":")[1])
775 start = None
776 if isinstance(value, int) and not isinstance(value, bool):
777 if target not in memory or not 0 <= value <= memory[target][1]:
778 return {"error": "starts a pointer outside its arguments"}
779 start = ctypes.addressof(memory[target][0]) + value
780 slots[i] = ctypes.c_void_p(start)
781 args[i] = ctypes.addressof(slots[i])
782 result = fn(*args)
783 if sig["ret"].startswith("ptr:"):
784 target = int(sig["ret"][4:])
785 if result is not None:
786 if target not in memory:
787 return {"error": "returns a pointer outside its arguments"}
788 offset = result - ctypes.addressof(memory[target][0])
789 if not 0 <= offset <= memory[target][1]:
790 return {"error": "returns a pointer outside its arguments"}
791 result = offset
792 elif sig["ret"].startswith("struct:"):
793 result = from_struct(result)
794 else:
795 result = enc(result)
796 if not sig.get("writes"):
797 return {"ok": result}
798 ok = {} if sig["ret"] == "None" else {"return": result}
799 for i, kind in enumerate(kinds):
800 name = sig["names"][i]
801 if kind == "buffer":
802 ok[name] = memory[i][0].raw[: memory[i][1]].hex() if i in memory else None
803 elif kind.startswith("out:"):
804 ok[name] = enc(outs[i].value) if i in outs else None
805 elif kind.startswith("outptr:"):
806 target = int(kind.split(":")[1])
807 pointer = slots[i].value if i in slots else None
808 if pointer is None:
809 ok[name] = None
810 else:
811 offset = pointer - ctypes.addressof(memory[target][0]) if target in memory else -1
812 if target not in memory or not 0 <= offset <= memory[target][1]:
813 return {"error": "writes a pointer outside its arguments"}
814 ok[name] = offset
815 return {"ok": ok}
816
817
818def isolated(functions, c):
819 """Runs one case in a forked child: undefined behavior in C can crash the process."""
820 read_end, write_end = os.pipe()
821 pid = os.fork()
822 if pid == 0:
823 os.close(read_end)
824 try:
825 result = call(functions, c)
826 except Exception as e: # ctypes conversion errors
827 result = {"error": "%s: %s" % (type(e).__name__, e)}
828 os.write(write_end, json.dumps(result).encode())
829 os._exit(0)
830 os.close(write_end)
831 data = b""
832 while True:
833 chunk = os.read(read_end, 65536)
834 if not chunk:
835 break
836 data += chunk
837 os.close(read_end)
838 _, status = os.waitpid(pid, 0)
839 if os.WIFSIGNALED(status):
840 return {"error": "crash: " + signal.Signals(os.WTERMSIG(status)).name}
841 return json.loads(data) if data else {"error": "crash: no result"}
842
843
844def cases_of(path):
845 return [json.loads(line) for line in open(path, encoding="utf-8") if line.strip()]
846
847
848def record(lib, sigs, inputs, out_path):
849 functions = bind(lib, json.load(open(sigs)))
850 progress = os.environ.get("RUST_ANYTHING_PROGRESS")
851 with open(out_path, "w", encoding="utf-8") as out:
852 for index, c in enumerate(json.load(open(inputs, encoding="utf-8"))):
853 if progress:
854 with open(progress, "a", encoding="utf-8") as p:
855 p.write("%d\n" % index)
856 line = {"fn": c["fn"], "args": c["args"]}
857 line.update(isolated(functions, c))
858 out.write(json.dumps(line, ensure_ascii=False) + "\n")
859 out.flush()
860
861
862def diff(lib, sigs, cases_path, out_path):
863 functions = bind(lib, json.load(open(sigs)))
864 summary = {"total": 0, "passed": 0, "failed": 0, "missing": [], "mismatches": []}
865 for c in cases_of(cases_path):
866 summary["total"] += 1
867 if c["fn"] not in functions:
868 if c["fn"] not in summary["missing"]:
869 summary["missing"].append(c["fn"])
870 summary["failed"] += 1
871 continue
872 error = str(c.get("error", ""))
873 if error.startswith("crash:") or error in (
874 "returns a pointer outside its arguments",
875 "writes a pointer outside its arguments",
876 ):
877 # The original's behavior is undefined there: any answer of the port passes.
878 summary["passed"] += 1
879 continue
880 got = isolated(functions, c)
881 expected = {"error": c["error"]} if "error" in c else {"ok": c.get("ok")}
882 if json.dumps(got) == json.dumps(expected):
883 summary["passed"] += 1
884 else:
885 summary["failed"] += 1
886 summary["mismatches"].append({"fn": c["fn"], "args": c["args"], "expected": expected, "actual": got})
887 json.dump(summary, open(out_path, "w", encoding="utf-8"), ensure_ascii=False)
888
889
890def bench(original, rust, sigs, cases_path, out_path, min_ms):
891 signatures = json.load(open(sigs))
892 old, new = bind(original, signatures), bind(rust, signatures)
893 groups = {}
894 for c in cases_of(cases_path):
895 if "error" not in c:
896 groups.setdefault(c["fn"], []).append(c)
897 rows = []
898 for name, cases in groups.items():
899 if name not in old or name not in new:
900 continue
901
902 def timed(functions):
903 def once():
904 for c in cases:
905 call(functions, c)
906 once()
907 passes, start = 0, time.perf_counter()
908 while True:
909 once()
910 passes += 1
911 elapsed = time.perf_counter() - start
912 if elapsed * 1000 >= min_ms:
913 return elapsed * 1e9 / (passes * len(cases))
914 original_ns, rust_ns = timed(old), timed(new)
915 rows.append({"fn": name, "cases": len(cases), "original_ns": original_ns, "rust_ns": rust_ns, "speedup": original_ns / rust_ns})
916 json.dump(rows, open(out_path, "w"))
917
918
919if __name__ == "__main__":
920 mode, *rest = sys.argv[1:]
921 if mode == "record":
922 record(*rest)
923 elif mode == "diff":
924 diff(*rest)
925 elif mode == "bench":
926 bench(rest[0], rest[1], rest[2], rest[3], rest[4], int(rest[5]))
927"#;
928
929#[cfg(test)]
930mod tests {
931 use super::*;
932
933 #[test]
934 fn c_literal_escapes_quotes_question_marks_and_non_ascii_bytes() {
935 assert_eq!(c_literal("abc"), r#""abc""#);
936 assert_eq!(c_literal(r#"say "hi""#), r#""say \"hi\"""#);
937 assert_eq!(c_literal(r"a\b"), r#""a\\b""#);
938 assert_eq!(c_literal("??="), r#""\077\077=""#);
939 assert_eq!(c_literal("a\nb"), r#""a\012b""#);
940 assert_eq!(c_literal("é"), r#""\303\251""#);
941 assert_eq!(c_literal("\t\u{7f}"), r#""\011\177""#);
942 assert_eq!(c_literal(""), r#""""#);
943 }
944}