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