Skip to main content

rust_anything/
harness_c.rs

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