summaryrefslogtreecommitdiffstats
path: root/scripts/gen_fuzz.py
blob: a1d20e3b1d66f573660ea0baeaaae109d2dd2569 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/usr/bin/env python3
"""Generate fuzz table entries from ts indicator metadata.

Parses lib/*.c via ts_parser to extract function names and input/output
counts, then generates a C source file with the complete fuzz table.
"""

import argparse
import importlib.util
import os
import sys

_spec = importlib.util.spec_from_file_location(
    "ts_parser",
    os.path.join(os.path.dirname(os.path.abspath(__file__)), "ts_parser.py"),
)
if _spec and _spec.loader:
    _ts_parser = importlib.util.module_from_spec(_spec)
    _spec.loader.exec_module(_ts_parser)
    parse_all = _ts_parser.parse_all
else:
    print("Error: could not load ts_parser", file=sys.stderr)
    sys.exit(1)

OUT = os.path.join(
    os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
    "test",
    "fuzz_table_generated.c",
)


def generate_table(funcs, dry_run=False):
    """Generate the fuzz table C source file."""
    if dry_run:
        print(f"[dry-run] Would generate {len(funcs)} fuzz entries -> {OUT}")
        return

    with open(OUT, "w", encoding="utf-8") as f:
        f.write("/* Auto-generated fuzz table. Do not edit. */\n\n")
        f.write('#include "ts.h"\n\n')
        f.write("static const fuzz_entry_t _fuzz_table_generated[] = {\n")

        for fm in funcs:
            f.write(f"    {{ts_{fm.name}, {fm.x_n}, {fm.y_n}}},\n")

        f.write("};\n\n")
        f.write(
            "static const uint_t _fuzz_generated_n = sizeof(_fuzz_table_generated) / sizeof(_fuzz_table_generated[0]);\n"
        )


def main():
    parser = argparse.ArgumentParser(description="Generate fuzz table from registry")
    parser.add_argument(
        "--dry-run",
        action="store_true",
        help="Print what would be generated without writing",
    )
    args = parser.parse_args()

    funcs = parse_all(detect_x_access=True)

    if not funcs:
        print("Warning: no ts_parameter declarations found.", file=sys.stderr)
        sys.exit(1)

    generate_table(funcs, dry_run=args.dry_run)

    if not args.dry_run:
        print(f"Generated {len(funcs)} fuzz entries -> {OUT}")


if __name__ == "__main__":
    main()