"""
02_memory_bugs.py -- the memory perils of C, and the tools that catch them
============================================================================

[Questions this demo answers]
  - The slides list the classic heap bugs: wrong allocation size, off-by-one,
    use-after-free, double-free, memory leaks. What do they do, and how do you
    catch each one?

[How to run]
  python3 02_memory_bugs.py

[How to read the output]
  Each bug is built from bugs14.c and run. The out-of-bounds / use-after-free /
  double-free cases are built under AddressSanitizer, which names the bug with
  a file and line (addresses masked for reproducibility). The leak case uses a
  counting allocator that reports bytes still live at exit.

[Systems link / CS:APP 9.11]
  Heap bugs are undefined behavior whose symptom often appears far away and
  long after the cause (the "action at a distance" of Lecture 1). Sanitizers
  and leak checkers turn them into immediate, located errors.
"""

import os
import re
import subprocess

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

ASAN = [("wrong-size", "malloc sized with sizeof(ptr), not sizeof(*ptr)"),
        ("off-by-one", "write a[n] on an n-element array"),
        ("use-free", "read a block after free()"),
        ("double-free", "free() the same block twice")]


def build(flags, name):
    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 mask(line):
    line = re.sub(r"0x[0-9a-fA-F]+", "0x…", line)
    line = re.sub(r"==\d+==", "", line)
    line = re.sub(r"/\S+/(bugs14\.c)", r"\1", line)
    return line.strip()


def asan_report(output):
    lines = output.splitlines()
    kind = next((mask(l) for l in lines if "ERROR: AddressSanitizer" in l), None)
    if not kind:
        return "(no diagnostic)"
    k = re.search(r"AddressSanitizer: (?:attempting )?([\w-]+)", kind)
    site = next((re.search(r"(bugs14\.c:\d+)", mask(l)) for l in lines
                 if ("#0" in l or "#1" in l) and "bugs14.c" in l), None)
    return "ASan: %s%s" % (k.group(1) if k else "error",
                           "  (%s)" % site.group(1) if site else "")


def main():
    print("=== Demo 02: heap memory bugs and how to catch them ===\n")
    print("  Bugs AddressSanitizer catches (plain build hides them):\n")
    for case, desc in ASAN:
        plain, _ = build([], "plain_" + case)
        san, ok = build(["-fsanitize=address"], "san_" + case)
        pr = subprocess.run([plain, case], capture_output=True, text=True)
        if pr.returncode == 0:
            plain_note = "ran, exit 0 -- bug hidden"
        elif pr.returncode < 0:
            plain_note = "crashed (signal %d), no explanation" % (-pr.returncode)
        else:
            plain_note = "exit %d (corrupted, no explanation)" % pr.returncode
        rep = asan_report(subprocess.run([san, case], capture_output=True, text=True).stdout +
                          subprocess.run([san, case], capture_output=True, text=True).stderr) if ok \
            else "(sanitizer unavailable)"
        print("  %s  (%s)" % (case, desc))
        print("    plain -O0:  %s" % plain_note)
        print("    %s\n" % rep)

    print("  Memory leak (no sanitizer -- a counting allocator reports it):")
    exe, _ = build([], "leak")
    out = subprocess.run([exe, "leak"], capture_output=True, text=True).stdout.strip()
    print("    " + out)
    print("    The program lost every pointer it allocated, so those 300 bytes can")
    print("    never be freed. On Linux, valgrind or LeakSanitizer would report the")
    print("    leak with the allocating stack; on macOS the `leaks` tool does.\n")

    print("Observations:")
    print("  * Wrong size, off-by-one, use-after-free and double-free are all undefined")
    print("    behavior that a plain build may 'run' through -- then corrupt silently.")
    print("  * AddressSanitizer turns each into an immediate, located error; build and")
    print("    test the allocator-heavy labs (malloclab) under it from the start.")
    print("  * A leak is not caught by ASan's access checks; use a leak checker (LSan,")
    print("    valgrind, macOS `leaks`) or track live bytes as the counting wrapper does.")


if __name__ == "__main__":
    main()
