Skip to content
suit Artifact [acf608ed1c]
Login

Artifact [acf608ed1c]

Artifact acf608ed1c5dd69dd904b783bad14524cd9f5c91554780967e1c9866a728966f:


#!/usr/bin/env python3
"""Fail unless every file in src/ is covered 100% (functions, lines, regions,
branches). Prints each uncovered line and branch on failure.

usage: cover_gate.py LLVM_COV PROFDATA BINARY [BINARY...]
"""
import json
import os
import re
import subprocess
import sys

KINDS = ("functions", "lines", "regions", "branches")


def run(cmd):
    return subprocess.run(cmd, check=True, capture_output=True, text=True).stdout


def objects(binaries):
    args = [binaries[0]]
    for b in binaries[1:]:
        args += ["-object", b]
    return args


def summary(llvm_cov, prof, binaries):
    out = run([llvm_cov, "export", "-summary-only", "-instr-profile=" + prof]
              + objects(binaries))
    files = json.loads(out)["data"][0]["files"]
    src = os.path.realpath("src") + os.sep
    return {f["filename"]: f["summary"] for f in files
            if os.path.realpath(f["filename"]).startswith(src)}


def misses(llvm_cov, prof, binaries, filename):
    """Yield (line number, text, why) for each uncovered line or branch."""
    out = run([llvm_cov, "show", "-instr-profile=" + prof, "-show-branches=count",
               "-show-regions", "-show-line-counts", "-format=text", "-sources", filename]
              + objects(binaries))
    line_re = re.compile(r"^\s*(\d+)\|\s*([\d.]+[kMGT]?)\|(.*)$")
    cur = None
    reported = set()
    for raw in out.splitlines():
        m = line_re.match(raw)
        if m:
            cur = (int(m.group(1)), m.group(3).strip())
            if m.group(2) == "0" and (cur[0], "line") not in reported:
                reported.add((cur[0], "line"))
                yield cur[0], cur[1], "line never ran"
            continue
        if cur is None:
            continue
        b = re.search(r"Branch \((\d+):(\d+)\): \[(True|Folded) *: *([\d.]+[kMGT]?)(?:, False: ([\d.]+[kMGT]?))?\]", raw)
        if b:
            true_n = b.group(4) if b.group(3) == "True" else "0"
            false_n = b.group(5) if b.group(5) is not None else "0"
            if (true_n == "0" or false_n == "0") and b.group(3) == "True" and b.group(5) is not None:
                side = "true" if true_n == "0" else "false"
                yield int(b.group(1)), cur[1], "branch at column %s never went %s" % (b.group(2), side)
        elif "^0" in raw:
            yield cur[0], cur[1], "region never ran"


def source_line(name, number):
    with open(name) as f:
        lines = f.read().splitlines()
    return lines[number - 1].strip() if 0 < number <= len(lines) else ""


def main():
    llvm_cov, prof, binaries = sys.argv[1], sys.argv[2], sys.argv[3:]
    files = summary(llvm_cov, prof, binaries)
    failed = False
    print("%-18s %10s %10s %10s %10s" % ("file", *KINDS))
    for name in sorted(files):
        s = files[name]
        cells = []
        for k in KINDS:
            c = "%d/%d" % (s[k]["covered"], s[k]["count"])
            cells.append(c)
            if s[k]["covered"] != s[k]["count"]:
                failed = True
        print("%-18s %10s %10s %10s %10s" % (os.path.relpath(name), *cells))
    if not files:
        print("cover: no files from src/ in the profile")
        return 1
    if failed:
        print("\ncover: FAIL, not everything in src/ is covered:")
        for name in sorted(files):
            seen = set()
            for line, text, why in misses(llvm_cov, prof, binaries, name):
                if (line, why) not in seen:
                    seen.add((line, why))
                    print("  %s:%d: %s: %s" % (os.path.relpath(name), line, why, source_line(name, line) or text))
        return 1
    print("\ncover: ok, 100%% of functions, lines, regions and branches in %d files" % len(files))
    return 0


sys.exit(main())