Files

391 lines
19 KiB
Python

#!/usr/bin/env python3
"""Build raw BTF from core anchors and types.json using the standard library.
--source-dir is the directory containing the anchors, or its project root
(with a src/ directory). Kernel include/configuration flags belong in --cflags;
no kernel implementation translation units are compiled. Tool options accept
shlex command strings, but are never executed through a shell.
"""
import argparse
import json
from pathlib import Path
import re
import shlex
import struct
import subprocess
import sys
import time
import uuid
REQUIRED = ("sk_buff", "sock", "task_struct", "net_device")
ANCHOR = re.compile(
r"^BTF_KEEP\s*\(\s*([A-Za-z_]\w*)\s*,\s*(.*?)\s*\)\s*;\s*(?:(?://.*)|(?:/\*.*\*/))?$"
)
KEEP_LINE = re.compile(r"^BTF_KEEP\s*\(")
CANDIDATE = re.compile(r"^(?:(?:const|volatile)\s+)*(struct|union|enum)\s+([A-Za-z_]\w*)$")
def read_btf(path):
"""Walk standalone BTF v1, rejecting unknown kinds and truncated records."""
data = Path(path).read_bytes()
if len(data) < 24:
raise ValueError("raw BTF header is truncated")
if data[:2] == b"\x9f\xeb":
endian = "<"
elif data[:2] == b"\xeb\x9f":
endian = ">"
else:
raise ValueError("invalid raw BTF magic")
_, version, flags, hdr_len, type_off, type_len, str_off, str_len = struct.unpack_from(
endian + "HBBIIIII", data
)
if version != 1 or flags != 0 or hdr_len < 24 or hdr_len > len(data):
raise ValueError("unsupported or invalid raw BTF header")
start, end = hdr_len + type_off, hdr_len + type_off + type_len
strings_start, strings_end = hdr_len + str_off, hdr_len + str_off + str_len
if end > len(data) or strings_end > len(data) or not str_len:
raise ValueError("raw BTF section is truncated or string table is empty")
if max(start, strings_start) < min(end, strings_end):
raise ValueError("raw BTF type and string sections overlap")
strings = data[strings_start:strings_end]
if strings[0] != 0 or strings[-1] != 0:
raise ValueError("invalid BTF string table boundaries")
def name_at(offset):
if offset >= len(strings):
raise ValueError("BTF name offset is outside the string table")
stop = strings.find(b"\0", offset)
if stop < 0:
raise ValueError("unterminated BTF name")
return strings[offset:stop].decode("utf-8", errors="replace")
stats = {"types": 0, "complete_structs": 0, "complete_unions": 0,
"complete_enums": 0, "forwards": 0}
definitions = {"struct": {}, "union": {}, "enum": {}}
position = start
while position < end:
if end - position < 12:
raise ValueError("truncated BTF type header")
name_off, info, size = struct.unpack_from(endian + "III", data, position)
kind, vlen = (info >> 24) & 31, info & 65535
name = name_at(name_off)
if kind < 1 or kind > 19:
raise ValueError("unknown BTF kind {} at offset {}".format(kind, position))
payload = {1: 4, 2: 0, 3: 12, 4: vlen * 12, 5: vlen * 12,
6: vlen * 8, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0,
12: 0, 13: vlen * 8, 14: 4, 15: vlen * 12,
16: 0, 17: 4, 18: 0, 19: vlen * 12}[kind]
next_position = position + 12 + payload
if next_position > end:
raise ValueError("truncated payload for BTF kind {}".format(kind))
# Member, enumerator and parameter records also contain name offsets.
stride = {4: 12, 5: 12, 6: 8, 13: 8, 19: 12}.get(kind)
if stride:
for offset in range(position + 12, next_position, stride):
name_at(struct.unpack_from(endian + "I", data, offset)[0])
stats["types"] += 1
if kind in (4, 5):
category = "struct" if kind == 4 else "union"
# STRUCT/UNION records are definitions, including empty GNU types.
stats["complete_" + category + "s"] += 1
if name:
definitions[category].setdefault(name, []).append(size)
elif kind in (6, 19):
if vlen:
stats["complete_enums"] += 1
if name:
definitions["enum"].setdefault(name, []).append(size)
else:
stats["forwards"] += 1
elif kind == 7:
stats["forwards"] += 1
position = next_position
return {"byte_order": "little" if endian == "<" else "big", "bytes": len(data),
"stats": stats, "definitions": definitions}
class Builder:
def __init__(self, args):
self.args = args
self.started = time.monotonic()
self.build = Path(args.build_dir).resolve()
self.source = Path(args.source_dir).resolve()
self.run_id = uuid.uuid4().hex
self.probes = self.build / "probes" / self.run_id
self.raw = self.build / "vmlinux-btf"
self.report = {"success": False, "source_dir": str(self.source),
"build_dir": str(self.build), "run_id": self.run_id,
"raw_btf": str(self.raw), "manifest": None, "compile_attempts": 0,
"elapsed_seconds": 0, "units": [], "attempts": [],
"anchors": [], "btf": None, "error": None,
"missing_required_structs": list(REQUIRED)}
self.objects = []
self.serial = 0
self.commands = {}
def command(self, tool, arguments, phase, details=None):
self.serial += 1
log = self.probes / ("{:05d}-{}.log".format(self.serial, phase))
argv = self.commands[tool] + [str(arg) for arg in arguments]
record = {"phase": phase, "command": argv, "log": str(log)}
if details:
record.update(details)
self.report["attempts"].append(record)
if phase == "compile":
self.report["compile_attempts"] += 1
started = time.monotonic()
with log.open("w", encoding="utf-8") as output:
output.write("$ " + " ".join(shlex.quote(arg) for arg in argv) + "\n")
output.flush()
try:
completed = subprocess.run(argv, stdout=output, stderr=subprocess.STDOUT,
cwd=str(self.source), check=False)
record["returncode"] = completed.returncode
except OSError as error:
output.write(str(error) + "\n")
record["returncode"] = None
record["error"] = str(error)
raise RuntimeError("cannot run {}: {} (log: {})".format(tool, error, log)) from error
finally:
record["elapsed_seconds"] = round(time.monotonic() - started, 6)
return record
def load_units(self):
"""Validate the declaration list and materialize one probe per group."""
directory = self.source
if not (directory / "shadow_btf_core.c").is_file():
directory = directory / "src"
core = directory / "shadow_btf_core.c"
if not core.is_file():
raise ValueError("no shadow_btf_core.c in --source-dir or its src/ directory")
manifest = directory / "types.json"
if not manifest.is_file():
return [core] # A standalone core fixture needs no manifest or shared header.
self.report["manifest"] = str(manifest)
groups = json.loads(manifest.read_text(encoding="utf-8"))
if not isinstance(groups, list):
raise ValueError("types.json must contain a list of groups")
names = set()
for group in groups:
if not isinstance(group, dict) or not {"name", "header", "types"} <= group.keys():
raise ValueError("each manifest group requires name, header and types")
name, header, types = group["name"], group["header"], group["types"]
if not isinstance(name, str) or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_-]*", name) or name in names:
raise ValueError("manifest group names must be safe and unique: {!r}".format(name))
names.add(name)
if (not isinstance(header, str) or not re.fullmatch(r"[A-Za-z0-9_/-]+[.]h", header)
or header.startswith("/") or ".." in header or "//" in header):
raise ValueError("invalid kernel-relative header: {!r}".format(header))
if (not isinstance(types, list) or not types
or any(not isinstance(t, str) or not re.fullmatch(r"(struct|union|enum) [A-Za-z_][A-Za-z0-9_]*", t) for t in types)
or len(types) != len(set(types))):
raise ValueError("group {} requires unique struct/union/enum type strings".format(name))
probe_header = directory / "btf_probe.h"
if not probe_header.is_file():
raise ValueError("manifest requires btf_probe.h beside types.json")
include = '#include "{}"\n'.format(probe_header)
# Fail before optional-unit isolation can swallow unsupported layout settings.
environment = self.probes / "environment.c"
environment.write_text(include, encoding="utf-8")
check = self.command("cc", self.cflags + ["-fsyntax-only", environment], "environment")
if check["returncode"] != 0:
raise RuntimeError("probe environment check failed (log: {})".format(check["log"]))
generated = self.probes / "units"
generated.mkdir()
paths = [core]
for group in groups:
header = group["header"]
lines = [include, "#if __has_include(<{}>)\n".format(header),
"#include <{}>\n".format(header),
'#else\n#error "manifest header unavailable"\n#endif\n']
# A missing header fails the header-only check and skips the whole group.
for index, spelling in enumerate(group["types"]):
lines.append("BTF_KEEP(candidate_{}, {});\n".format(index, spelling))
path = generated / (group["name"] + ".c")
path.write_text("".join(lines), encoding="utf-8")
paths.append(path)
return paths
def compile_unit(self, path):
unit = {"source": str(path), "skip": False, "reason": None, "logs": [],
"objects": [], "anchors": []}
self.report["units"].append(unit)
original = path.read_text(encoding="utf-8")
lines = original.splitlines(keepends=True)
indices = []
for index, line in enumerate(lines):
if not KEEP_LINE.match(line):
continue
match = ANCHOR.fullmatch(line.rstrip("\r\n"))
if not match:
raise ValueError("unsupported standalone BTF_KEEP line in {}: {}".format(path, line.strip()))
anchor_name, spelling = match.groups()
candidate = CANDIDATE.fullmatch(spelling)
anchor = {"source": str(path), "anchor": anchor_name, "type": spelling,
"kind": candidate.group(1) if candidate else None,
"name": candidate.group(2) if candidate else None,
"skip": False, "reason": None, "log": None,
"covered": False, "coverage_reason": "final BTF unavailable"}
unit["anchors"].append(anchor)
self.report["anchors"].append(anchor)
indices.append(index)
by_index = dict(zip(indices, unit["anchors"]))
def compile_subset(selected, purpose):
ident = "{}-{:05d}".format(path.stem, self.serial + 1)
generated = self.probes / (ident + ".c")
obj = self.probes / (ident + ".o")
chosen = set(selected)
generated.write_text("".join(
"\n" if i in by_index and i not in chosen else line
for i, line in enumerate(lines)), encoding="utf-8")
record = self.command("cc", ["-g", "-O0"] + self.cflags +
["-iquote", path.parent, "-c", generated, "-o", obj],
"compile", {"unit": str(path), "purpose": purpose,
"source": str(generated), "object": str(obj),
"anchors": [by_index[i]["anchor"] for i in selected]})
unit["logs"].append(record["log"])
if record["returncode"] == 0:
if not obj.is_file() or obj.stat().st_size == 0:
raise RuntimeError("compiler succeeded without a nonempty object: {}".format(obj))
return obj, record
return None, record
def collect(obj):
self.objects.append(obj)
unit["objects"].append(str(obj))
def bisect(selected):
obj, record = compile_subset(selected, "anchor probe")
if obj is not None:
collect(obj)
return
if len(selected) == 1:
anchor = by_index[selected[0]]
anchor.update(skip=True, reason="anchor compilation failed", log=record["log"])
return
middle = len(selected) // 2
bisect(selected[:middle])
bisect(selected[middle:])
obj, failure = compile_subset(indices, "whole unit")
if obj is not None:
collect(obj)
return
_, header = compile_subset([], "headers without anchors")
if header["returncode"] != 0:
unit.update(skip=True, reason="headers or non-anchor source compilation failed",
log=header["log"])
for anchor in unit["anchors"]:
anchor.update(skip=True, reason=unit["reason"], log=header["log"])
return
if not indices:
unit.update(skip=True, reason="unit failed without anchors", log=failure["log"])
return
if len(indices) == 1:
by_index[indices[0]].update(skip=True, reason="anchor compilation failed", log=failure["log"])
else:
middle = len(indices) // 2
bisect(indices[:middle])
bisect(indices[middle:])
if not unit["objects"]:
unit.update(skip=True, reason="all anchors failed compilation", log=failure["log"])
def run(self):
self.probes.mkdir(parents=True, exist_ok=True)
# Never let a previous invocation satisfy this invocation's validation.
try:
self.raw.unlink()
except FileNotFoundError:
pass
for tool in ("cc", "ld", "objcopy", "pahole"):
self.commands[tool] = shlex.split(getattr(self.args, tool))
if not self.commands[tool]:
raise ValueError("--{} must not be empty".format(tool))
self.cflags = shlex.split(self.args.cflags)
paths = self.load_units()
for path in paths:
self.compile_unit(path)
if not self.objects:
raise RuntimeError("no successful anchor objects to link")
linked = self.probes / "linked.o"
result = self.command("ld", ["-r", "-o", linked] + self.objects, "link")
if result["returncode"] != 0:
raise RuntimeError("link failed (log: {})".format(result["log"]))
detached = self.command("pahole", ["--btf_encode_detached=" + str(self.raw), linked], "pahole-detached")
if detached["returncode"] != 0 or not self.raw.is_file() or not self.raw.stat().st_size:
try:
self.raw.unlink()
except FileNotFoundError:
pass
encoded = self.command("pahole", ["-J", linked], "pahole-embedded")
if encoded["returncode"] != 0:
raise RuntimeError("pahole failed in detached and embedded modes (log: {})".format(encoded["log"]))
extracted = self.command("objcopy", ["--dump-section", ".BTF=" + str(self.raw), linked], "extract-btf")
if extracted["returncode"] != 0:
raise RuntimeError("BTF extraction failed (log: {})".format(extracted["log"]))
if not self.raw.is_file() or self.raw.stat().st_size == 0:
raise RuntimeError("raw BTF output is missing or empty")
btf = read_btf(self.raw)
self.report["btf"] = btf
definitions = btf["definitions"]
for anchor in self.report["anchors"]:
kind, name = anchor["kind"], anchor["name"]
if kind is None:
anchor["coverage_reason"] = "not a directly named struct/union/enum candidate"
continue
anchor["covered"] = name in definitions[kind]
anchor["coverage_reason"] = ("complete definition present in final BTF" if anchor["covered"] else
"complete definition absent from final BTF (possibly disabled by configuration)")
missing = [name for name in REQUIRED if not any(size > 0 for size in definitions["struct"].get(name, []))]
self.report["missing_required_structs"] = missing
if missing:
raise RuntimeError("final BTF lacks nonempty complete STRUCT definitions: " + ", ".join(missing))
self.report["success"] = True
def finish(self):
self.report["elapsed_seconds"] = round(time.monotonic() - self.started, 6)
self.build.mkdir(parents=True, exist_ok=True)
report_path = self.build / "coverage.json"
temporary = self.build / ("coverage." + self.run_id + ".tmp")
temporary.write_text(json.dumps(self.report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
temporary.replace(report_path)
covered = sum(anchor["covered"] for anchor in self.report["anchors"])
candidates = sum(anchor["kind"] is not None for anchor in self.report["anchors"])
skipped = sum(unit["skip"] for unit in self.report["units"])
print("BTF {}: {} compile attempts, {} units ({} skipped), {}/{} candidates covered, {:.2f}s".format(
"OK" if self.report["success"] else "FAILED", self.report["compile_attempts"],
len(self.report["units"]), skipped, covered, candidates, self.report["elapsed_seconds"]))
print("Report: " + str(report_path))
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--source-dir", required=True)
parser.add_argument("--build-dir", required=True)
parser.add_argument("--cc", default="cc", help="compiler command string (shlex)")
parser.add_argument("--ld", default="ld", help="relocatable linker command string (shlex)")
parser.add_argument("--objcopy", default="objcopy", help="objcopy command string (shlex)")
parser.add_argument("--pahole", default="pahole", help="pahole command string (shlex)")
parser.add_argument("--cflags", default="", help="compiler flags (shlex); use --cflags='-I... -D...'")
args = parser.parse_args(argv)
builder = Builder(args)
try:
builder.run()
except (Exception, KeyboardInterrupt) as error:
builder.report["error"] = str(error) or type(error).__name__
print("build_btf: " + builder.report["error"], file=sys.stderr)
finally:
try:
builder.finish()
except Exception as error:
print("build_btf: could not write coverage report: " + str(error), file=sys.stderr)
builder.report["success"] = False
return 0 if builder.report["success"] else 1
if __name__ == "__main__":
sys.exit(main())