okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Sources: no raw NUL bytes (expert_source.cpp, pinned.cu) + a test that scans for themf5082f41a

main
2.4 KiB55 linesraw
1"""No raw NUL byte in a source file.  A shell heredoc that loses the backslash of '\\0' leaves a literal 0x00 inside a
2character constant: gcc only warns ("null character(s) preserved in literal"), MSVC stops with an error (0.1.43.1's
3generate.cpp; expert_source.cpp and pinned.cu after it).  No binary, no GPU.
4
5    python -m unittest tools.test_source_nul_bytes
6"""
7from __future__ import annotations
8
9import subprocess
10import unittest
11from pathlib import Path
12
13ROOT = Path(__file__).resolve().parent.parent
14SOURCE_SUFFIXES = {".c", ".cc", ".cpp", ".cxx", ".h", ".hpp", ".cu", ".cuh", ".hip", ".mm", ".metal", ".py", ".cmake",
15                   ".txt", ".sh", ".bat", ".ps1", ".js", ".html", ".css", ".json", ".jinja", ".md", ".in"}
16SOURCE_DIRS = ("src", "include", "sycl", "metal", "serve", "tools", "tests", "cmake", "bench", "docs")
17
18
19def source_files() -> list[Path]:
20    try:
21        out = subprocess.run(["git", "ls-files", "-z", "--", *SOURCE_DIRS, "*.py", "*.txt", "*.sh", "*.bat"],
22                             cwd=ROOT, capture_output=True, check=True).stdout
23        names = [n.decode("utf-8", "surrogateescape") for n in out.split(b"\0") if n]
24        paths = [ROOT / n for n in names]
25    except (OSError, subprocess.CalledProcessError):   # not a git checkout (a release zip): walk the tree instead
26        paths = [p for d in SOURCE_DIRS if (ROOT / d).is_dir() for p in (ROOT / d).rglob("*")]
27        paths += [p for p in ROOT.iterdir() if p.is_file()]
28    return sorted({p for p in paths if p.is_file() and p.suffix.lower() in SOURCE_SUFFIXES})
29
30
31def nul_lines(path: Path) -> list[int]:
32    data = path.read_bytes()
33    if b"\0" not in data:
34        return []
35    return [i + 1 for i, line in enumerate(data.split(b"\n")) if b"\0" in line]
36
37
38class SourceNulBytes(unittest.TestCase):
39    def test_no_source_file_holds_a_nul_byte(self):
40        files = source_files()
41        self.assertGreater(len(files), 50, "the source scan found almost nothing")
42        bad = {str(p.relative_to(ROOT)): nul_lines(p) for p in files}
43        bad = {k: v for k, v in bad.items() if v}
44        self.assertEqual(bad, {}, "raw NUL bytes (write '\\0' instead) at file: [lines]")
45
46    def test_the_check_sees_a_nul(self):
47        import tempfile
48        with tempfile.TemporaryDirectory() as d:
49            p = Path(d) / "x.cpp"
50            p.write_bytes(b"int a;\nchar c = '\0';\n")
51            self.assertEqual(nul_lines(p), [2])
52
53
54if __name__ == "__main__":
55    unittest.main()