"""
02_tools.py -- the right tool finds the right bug class
========================================================

[Questions this demo answers]
  - Some bugs (out-of-bounds, use-after-free, signed overflow, bad shifts) do
    not reliably crash -- they may corrupt silently or seem to work. How do
    you MAKE them show themselves?
  - What does each sanitizer catch, and what does it report?

[How to run]
  python3 02_tools.py

[How to read the output]
  For each bug, the demo builds bugs.c twice -- once plain, once with the
  matching sanitizer -- and runs the one case. The plain build's behaviour is
  unreliable (it may print a value, or crash); the instrumented build pinpoints
  the bug with a file and line. Sanitizer addresses are masked so the output is
  reproducible.

[Systems link / CS:APP "debugging", 3.10]
  AddressSanitizer (ASan) instruments every memory access to check it is in a
  live, in-bounds region -- memory-safety bugs. UndefinedBehaviorSanitizer
  (UBSan) checks operations the C standard leaves undefined -- overflow, bad
  shifts, out-of-range indices. On Linux, valgrind's memcheck catches the same
  memory-safety class without recompiling. Running under a sanitizer is itself
  a lesson: "I can't reproduce it" usually means "I haven't run the right tool".
"""

import os
import re
import subprocess

HERE = os.path.dirname(os.path.abspath(__file__))
SRC = os.path.join(HERE, "src", "bugs.c")
BUILD = os.path.join(HERE, "build")
CC = os.environ.get("CC", "cc")

# (case, sanitizer flags, human description, what the tool should say)
CASES = [
    ("heap-oob", ["-fsanitize=address"], "write one past a heap array", "heap-buffer-overflow"),
    ("use-after-free", ["-fsanitize=address"], "read freed heap memory", "heap-use-after-free"),
    ("stack-oob", ["-fsanitize=address"], "read one past a stack array", "stack-buffer-overflow"),
    ("signed-overflow", ["-fsanitize=undefined"], "INT_MAX + 1", "signed integer overflow"),
    ("bad-shift", ["-fsanitize=undefined"], "1 << 31 (overflows int)", "shift"),
    ("oob-index", ["-fsanitize=undefined"], "array[10] on a 4-element array", "out of bounds"),
]


def build(name, flags):
    os.makedirs(BUILD, exist_ok=True)
    out = os.path.join(BUILD, name)
    cp = subprocess.run([CC, "-g", "-O0"] + flags + [SRC, "-o", out], capture_output=True, text=True)
    return out, cp.returncode == 0


def run(path, case):
    cp = subprocess.run([path, case], capture_output=True, text=True)
    return cp.stdout + cp.stderr, cp.returncode


def mask(line):
    """Hide addresses, PIDs, thread ids and absolute paths for reproducibility."""
    line = re.sub(r"0x[0-9a-fA-F]+", "0x…", line)
    line = re.sub(r"==\d+==", "", line)
    line = re.sub(r"\s*(pc|bp|sp) 0x…", "", line)
    line = re.sub(r"/\S+/(bugs\.c)", r"\1", line)        # absolute path -> bugs.c
    return line.strip()


def tool_report(output, want):
    """The key diagnostic from a sanitizer report, masked and trimmed."""
    lines = output.splitlines()
    # UBSan: a single "runtime error:" line already names the file and line.
    for line in lines:
        if "runtime error:" in line:
            m = re.search(r"(bugs\.c:\d+).*?runtime error: (.*)", mask(line))
            return "UBSan: %s  (%s)" % (m.group(2), m.group(1)) if m else mask(line)
    # ASan: the "ERROR:" line names the bug; the first "#0 ... bugs.c:NN" the site.
    kind = next((mask(l) for l in lines if "ERROR: AddressSanitizer" in l), None)
    if kind:
        k = re.search(r"AddressSanitizer: ([\w-]+)", kind)
        site = next((re.search(r"(bugs\.c:\d+)", mask(l)) for l in lines
                     if "#0" in l and "bugs.c" in l), None)
        where = ("  (%s)" % site.group(1)) if site else ""
        return "ASan: %s%s" % (k.group(1) if k else "error", where)
    return "(no diagnostic; tool unavailable on this platform?)"


def plain_behaviour(path, case):
    out, rc = run(path, case)
    if rc == 0:
        return "ran without crashing -- bug hidden"
    if rc >= 128:
        return "crashed (signal %d), no explanation" % (rc - 128)
    return "exited %d" % rc


def main():
    print("=== Demo 02: sanitizers find bugs that hide ===\n")
    for case, flags, desc, want in CASES:
        plain, _ = build("plain_" + case, [])
        instr, ok = build("san_" + case, flags)
        pb = plain_behaviour(plain, case)
        report = tool_report(run(instr, case)[0], want) if ok else "(tool unavailable here)"
        print("  %s  (%s)" % (case, desc))
        print("    plain -O0:  %s" % pb)
        print("    %s\n" % report)
    print("Observations:")
    print("  * Every plain build ran without crashing, yet every one has a real bug.")
    print("    'It didn't crash' is not 'it's correct' -- the damage is just silent.")
    print("  * AddressSanitizer names the exact out-of-bounds / use-after-free access")
    print("    with a file and line; UBSanitizer names the overflow or bad shift.")
    print("  * Pick the tool for the bug class: ASan/valgrind for memory safety,")
    print("    UBSan for undefined arithmetic, -Wall for many mistakes at compile time.")
    print("  * Build your tests to run under these tools from day one (datalab, cachelab")
    print("    and malloclab all reward it).")


if __name__ == "__main__":
    main()
