summaryrefslogtreecommitdiffstats
path: root/tools/release-surface-probe.py
blob: 34c598dc475262579bf26233d0fbfa06019b707f (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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
#!/usr/bin/env python3
"""Prove what the release build exports, without asking the detector's permission.

The first version of this tool took its candidate list from
`tools/test-surface.py`. That made it strictly downstream of the inference it
was meant to audit: an item the detector dropped could never be probed, and the
tool cheerfully reported "0 leaked" about a table that was missing the leak.
`db::candidates::open_reviews_for` was exactly that item — ungated, zero
production callers, named only by a test, reachable from an external release
build, and absent from the table.

So this version enumerates on its own:

  1. every `pub` declaration in `src/`, found by scanning the files directly;
  2. which of those names appear in `tests/`, so an item nobody outside the crate
     is asked for is not this tool's business;
  3. for each candidate, a real compile against the library twice — once without
     `test-support`, once with it.

An item fails if a release build lets an outside crate reach it, a test names
it, and it is not declared in `tools/test-surface-interface.json` as public
because a public signature requires it. Items the detector missed therefore show
up here as failures rather than as an empty table.

The compile is the only part that is not inference. A path that compiles *with*
`test-support` proves the path is real; the same path failing *without* it proves
the release build does not export it.

Usage:
    python3 tools/release-surface-probe.py            # report
    python3 tools/release-surface-probe.py --quiet    # exit status only
"""
import argparse
import json
import os
import re
import shutil
import subprocess
import sys

ROOT = os.path.dirname(os.path.abspath(__file__)) + "/.."
SRC = os.path.join(ROOT, "src")
TESTS = os.path.join(ROOT, "tests")
CACHE = os.path.join(ROOT, "target", "release-surface-probe")

DECL = re.compile(r"^\s*pub\s+(fn|struct|enum|trait|const|static|type|mod)\s+([A-Za-z0-9_]+)")
COMMENT = re.compile(r"^\s*(?://|//!|///)")
GATE = 'feature = "test-support"'


def rust_files(d):
    out = []
    for base, _, files in os.walk(d):
        for f in sorted(files):
            if f.endswith(".rs"):
                out.append(os.path.join(base, f))
    return out


def module_of(path):
    rel = os.path.relpath(path, SRC)
    parts = rel.split(os.sep)
    if parts[0] == "bin":
        return os.path.join("bin", *parts[1:]).removesuffix(".rs")
    if len(parts) > 1:
        return parts[0]
    return parts[0].removesuffix(".rs")


def strip_line(line):
    """Drop comments and string literals: a mention inside either is not a call."""
    line = re.sub(r"//[^\"]*$", "", line)
    line = re.sub(r'r#?"(?:[^"\\]|\\.)*"#?', '""', line)
    line = re.sub(r'"(?:[^"\\]|\\.)*"', '""', line)
    return line


def use_lines(text):
    out, in_use, depth = set(), False, 0
    for i, raw in enumerate(text.split("\n")):
        line = strip_line(raw)
        if not in_use and re.match(r"^\s*(?:pub(?:\(crate\))?\s+)?use\b", line):
            in_use = True
        if in_use:
            out.add(i)
            depth += line.count("{") - line.count("}")
            if ";" in line and depth <= 0:
                in_use, depth = False, 0
    return out


def declarations():
    """Every `pub` declaration in src/, found here rather than by asking anyone.

    Skips a declaration that a `use` statement shares (a re-export is not a new
    item) and one whose attribute block carries the test-support gate, since a
    release build does not compile it at all.
    """
    out = []
    for path in rust_files(SRC):
        text = open(path).read()
        lines = text.split("\n")
        used = use_lines(text)
        for i, line in enumerate(lines):
            if i in used or COMMENT.match(line):
                continue
            m = DECL.match(line)
            if not m:
                continue
            k, gated = i - 1, False
            while k >= max(0, i - 6) and (lines[k].strip().startswith("#[")
                                          or lines[k].strip().startswith("//")
                                          or not lines[k].strip()):
                if GATE in lines[k]:
                    gated = True
                k -= 1
            if gated:
                continue
            mod = module_of(path)
            if mod.startswith("bin"):
                continue
            out.append({"name": m.group(2), "module": mod, "kind": m.group(1),
                        "file": path,
                        "where": "%s:%d" % (os.path.relpath(path, ROOT), i + 1)})
    return out


def test_named():
    """Names the test tier writes, with comments and strings removed."""
    names = set()
    for path in rust_files(TESTS):
        for line in open(path).read().split("\n"):
            clean = strip_line(line)
            for m in re.finditer(r"\b([A-Za-z_][A-Za-z0-9_]*)\b", clean):
                names.add(m.group(1))
    return names


def paths_for(decl):
    """Every path an outside crate could use to name this item.

    The declaring *file* gives the real module path — an item in
    `src/review/approve.rs` is `aur_build::review::approve::name`, not
    `aur_build::review::name`. Deriving the path from the census module instead
    was a silent failure: the probe could not compile the path even with
    `test-support`, filed the item as "not nameable", and reported no leak for
    an item that was leaking. A path that fails to compile is only evidence when
    the path is right, so the submodule path and the module-door re-export path
    are both tried.
    """
    rel = os.path.relpath(decl["file"], SRC)
    parts = rel.split(os.sep)
    if parts[-1] == "mod.rs":
        parts = parts[:-1]
    else:
        parts[-1] = parts[-1][:-3]
    real = "::".join(parts)
    top = parts[0]
    out = {"aur_build::%s::%s" % (real, decl["name"])}
    # the module door, where most items are re-exported for callers
    out.add("aur_build::%s::%s" % (top, decl["name"]))
    # any intermediate directory that re-exports it, e.g. `aur_build::review::x::Name`
    for i in range(1, len(parts)):
        out.add("aur_build::%s::%s" % ("::".join(parts[:i]), decl["name"]))
    return sorted(out)


def compile_probe(units, feature):
    """Compile one tiny binary per path; return the set of names that failed."""
    d = os.path.join(CACHE, "with" if feature else "no")
    shutil.rmtree(d, ignore_errors=True)
    os.makedirs(os.path.join(d, "src", "bin"))
    with open(os.path.join(d, "Cargo.toml"), "w") as h:
        h.write('[package]\nname="surface-probe"\nversion="0.0.0"\nedition="2021"\n\n'
                '[dependencies]\naur-build = { path = "%s"%s }\n'
                % (os.path.abspath(os.path.join(ROOT, ".")),
                   ', features = ["test-support"]' if feature else ""))
    os.makedirs(os.path.join(d, "src"), exist_ok=True)
    with open(os.path.join(d, "src", "main.rs"), "w") as h:
        h.write("fn main() {}\n")
    for name, path in units.items():
        with open(os.path.join(d, "src", "bin", name + ".rs"), "w") as h:
            h.write("#![allow(unused_imports, dead_code)]\nuse %s;\nfn main() {}\n" % path)
    r = subprocess.run(["cargo", "build", "--bins", "--keep-going", "--message-format=short",
                        "--target-dir", os.path.join(CACHE, "tgt-" + ("with" if feature else "no"))],
                       cwd=d, capture_output=True, text=True)
    return set(re.findall(r"\b(p\d+)\.rs", r.stdout + r.stderr))


def production_used(decls):
    """{(module, name)} for items some module other than the declaring one writes.

    Deliberately a second, simpler implementation rather than a call into the
    resolver in `tools/test-surface.py`. Two independent rules that must agree
    is a check; one rule consulted twice is not. The only refinement over "the
    name appears elsewhere" is the two things that made the first detector lie:
    comments and string literals do not count, and neither does a `use` line —
    a re-export is not a call. That one refinement is what makes
    `open_reviews_for` visible here: its only outside mention was the line that
    re-exported it.
    """
    used = set()
    texts = {p: open(p).read() for p in rust_files(SRC)}
    stripped = {}
    for p, t in texts.items():
        skip = use_lines(t)
        stripped[p] = [strip_line(l) for i, l in enumerate(t.split("\n"))
                       if i not in skip and not COMMENT.match(l)]
    for d in decls:
        pat = re.compile(r"\b%s\b" % re.escape(d["name"]))
        for p, lines in stripped.items():
            if module_of(p) == d["module"]:
                continue
            if any(pat.search(l) for l in lines):
                used.add((d["module"], d["name"]))
                break
    # A `pub mod` is a namespace, not an item. Nothing outside `watch` writes the
    # word `upstream` — they write `upstream::probe` — so a module declaration is
    # credited by whether anything declared in the file it names is used.
    files_in_use = {d["file"] for d in decls if (d["module"], d["name"]) in used}
    for d in decls:
        if d["kind"] != "mod" or (d["module"], d["name"]) in used:
            continue
        here = os.path.dirname(d["file"])
        for cand in (os.path.join(here, d["name"] + ".rs"),
                     os.path.join(here, d["name"], "mod.rs")):
            if os.path.exists(cand) and cand in files_in_use:
                used.add((d["module"], d["name"]))
                break
    return used


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--quiet", action="store_true")
    args = ap.parse_args()

    decls = declarations()
    named = test_named()
    used = production_used(decls)
    interface = json.load(open(os.path.join(ROOT, "tools", "test-surface-interface.json")))

    # Public and reached by nobody: no other module writes the name and no test
    # does either. That is not the goal's headline failure — it is not test-only —
    # but it is public surface with no caller, and it hides behind the same
    # re-export line that hid the test-only ones. `db::candidates::reopen_rejected`
    # was exactly this: declared, re-exported by `review`, called by nothing.
    # Counted over every file, including the declaring one: an item used only by
    # its own module is over-exposed, which is a different complaint from
    # "nothing reaches it at all". Only the latter belongs here.
    anywhere = {}
    for path in rust_files(SRC):
        text = open(path).read()
        skip = use_lines(text)
        anywhere[path] = " ".join(strip_line(l) for i, l in enumerate(text.split("\n"))
                                  if i not in skip and not COMMENT.match(l))
    tests_text = " ".join(strip_line(l) for p in rust_files(TESTS)
                          for l in open(p).read().split("\n"))

    def reached_from_anywhere(d):
        """Does anything other than the declaration itself write this name?

        Same-file use counts: a helper called three times in its own module is
        not "reached by nothing", it is over-exposed, which is a different
        complaint. Only the declaration line is excluded.
        """
        pat = re.compile(r"\b%s\b" % re.escape(d["name"]))
        if pat.search(tests_text):
            return True
        for p, text in anywhere.items():
            if p != d["file"]:
                if pat.search(text):
                    return True
        # in the declaring file, on a line that is not the declaration
        text = open(d["file"]).read()
        skip = use_lines(text)
        decl_no = int(d["where"].rsplit(":", 1)[1]) - 1
        for i, l in enumerate(text.split("\n")):
            if i == decl_no or i in skip or COMMENT.match(l):
                continue
            if pat.search(strip_line(l)):
                return True
        return False

    unreachable = [d for d in decls
                   if d["kind"] != "mod"
                   and "%s.%s" % (d["module"], d["name"]) not in interface
                   and not reached_from_anywhere(d)]

    # Candidates: public declarations a test writes by name and no other module
    # needs. Something production uses is not this goal's problem, and neither
    # is something no test asks for, however dead it is.
    units, owner = {}, {}
    n = 0
    used_elsewhere = 0
    for d in decls:
        declared_public = "%s.%s" % (d["module"], d["name"]) in interface
        if declared_public:
            # Probe the claim: an item declared public-on-purpose must actually be
            # reachable, or the interface file is stale and quietly rotting.
            pass
        elif d["name"] not in named or (d["module"], d["name"]) in used:
            used_elsewhere += 1
            continue
        for p in paths_for(d):
            units["p%04d" % n] = p
            owner["p%04d" % n] = d
            n += 1

    failed_with = compile_probe(units, True)
    failed_without = compile_probe(units, False)

    real = set(units) - failed_with                 # paths a test build can name
    leaked = sorted(u for u in real
                    if u not in failed_without
                    and "%s.%s" % (owner[u]["module"], owner[u]["name"]) not in interface)
    declared = sorted(u for u in real
                      if "%s.%s" % (owner[u]["module"], owner[u]["name"]) in interface)

    if not args.quiet:
        print("pub declarations found here:      %d" % len(decls))
        print("used by another module:           %d" % used_elsewhere)
        print("probed as test-only:              %d paths" % len(units))
        print("paths a test build can actually name: %d" % len(real))
        print("declared public interface:        %d" % len(declared))
        for u in declared:
            print("    %s  (%s)" % (units[u], "%s.%s" % (owner[u]["module"], owner[u]["name"])))
        print("public with no caller anywhere:   %d" % len(unreachable))
        for d in unreachable:
            print("    %-22s %s" % (d["name"], d["where"]))
        print()

    if leaked or unreachable:
        if leaked:
            print("LEAKED — a release build exports these and only tests name them:")
            for u in leaked:
                d = owner[u]
                print("    %-22s %-14s %s" % (d["name"], d["where"], units[u]))
            print("\nEither close them, or add each to tools/test-surface-interface.json "
                  "with the public signature that forces it open.")
        if unreachable:
            print("PUBLIC WITH NO CALLER — nothing in src or tests reaches these:")
            for d in unreachable:
                print("    %-22s %s" % (d["name"], d["where"]))
            print("\nDelete them, or say what they are for.")
        return 1
    if not args.quiet:
        print("nothing leaked: every path a test can name is closed in a release build, "
              "except the ones declared public on purpose")
    return 0


if __name__ == "__main__":
    sys.exit(main())