"""
01_scientific_debugging.py -- find a bug on purpose (the slides' badfib)
=========================================================================

[Questions this demo answers]
  - The slides' fib() prints fib(9)..fib(2) correctly but fib(1) is wrong.
    How do you find the defect methodically instead of poking at the code?
  - Why does the SAME bug behave differently at -O0 and -O2?
  - How do the steps hypothesis -> prediction -> experiment -> observation
    play out, and which candidate fix is the real one?

[How to run]
  python3 01_scientific_debugging.py

[How to read the output]
  PART A reproduces the failure: at -O0 fib(1) is wrong AND unstable (three
  runs disagree). To keep the rest of the demo reproducible, PART A and the
  experiments pin the uninitialized value with clang's
  -ftrivial-auto-var-init=pattern (it fills uninitialized locals with 0xAA
  bytes = -1431655766, and is itself a real hardening flag). PART B runs the
  slides' three hypotheses as experiments and reports which the evidence
  supports.

[Systems link / CS:APP "debugging"]
  A defect (bug in the code) may cause an error (wrong state) which may cause a
  failure (wrong result at an interface). Debugging searches back from a
  failure to its defect; doing it scientifically -- one changed condition at a
  time, never guessing past the first bug -- is faster and surer than brute
  force.
"""

import os
import subprocess

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

PIN = "-ftrivial-auto-var-init=pattern"        # make the uninitialized read reproducible
PATTERN_INT = -1431655766                       # 0xAAAAAAAA read as a signed int
# What a CORRECT version of this program prints (fib(1)=1, then the values the
# working cases already produce): 1, 2, 3, 5, 8, 13, 21, 34, 55.
SPEC = {1: 1, 2: 2, 3: 3, 4: 5, 5: 8, 6: 13, 7: 21, 8: 34, 9: 55}


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


def run(path):
    cp = subprocess.run([path], capture_output=True, text=True)
    vals = {}
    for line in cp.stdout.splitlines():
        if line.startswith("fib(") and "=" in line:
            vals[int(line[4:line.index(")")])] = int(line.split("=")[1])
    return vals, cp.returncode


def part_a():
    print("PART A: reproduce the failure (and see why 'works at -O0' means nothing)")
    buggy0, _ = build("fib_O0", ["-O0"])
    runs = [run(buggy0)[0].get(1) for _ in range(3)]
    stable = len(set(runs)) == 1
    print("  buggy build at -O0: fib(9)..fib(2) are all correct; fib(1) is wrong.")
    print("    fib(1) equals the spec value 1?  no")
    print("    fib(1) the same on three runs?   %s" % ("yes" if stable else "no"))
    if not stable:
        print("    (the three values differ; they are leftover stack bytes, so they are")
        print("     not shown. An UNSTABLE result is the signature of reading an")
        print("     uninitialized variable.)")
    pinned, _ = build("fib_pin", ["-O0", PIN])
    vp = run(pinned)[0].get(1)
    print("  the SAME source, compiled with %s:" % PIN)
    print("    fib(1) = %d, the SAME on every run -- the flag fills uninitialized" % vp)
    print("    locals with 0xAA bytes. Reproducible, but still not 1: reproducible-")
    print("    wrong is still wrong. (This flag is also a real hardening default, and")
    print("    it is what makes the experiments below repeatable.)")
    print("  Because reading `f` is undefined behavior, the compiler may do anything,")
    print("  and the symptom also shifts with the optimization level and the compiler")
    print("  version. So 'it works at -O0' proves nothing.")
    print("  Know first what SHOULD happen: the spec says fib(1) = 1. It does not, so")
    print("  this is a FAILURE (a violated spec), not just surprising output.\n")


def experiment(name, flags):
    path, cp = build(name, [PIN] + flags)
    if cp.returncode != 0:
        return {}, "did not compile"
    vals, rc = run(path)
    return vals, rc


def summarize(vals, only_one=False):
    if only_one:
        return "fib(1) = %s" % ("1 (correct)" if vals.get(1) == 1 else "%d (still wrong)" % vals.get(1))
    broke = [k for k in (2, 3, 4, 5) if k in vals and vals[k] != SPEC[k]]
    if vals.get(1) == 1 and not broke:
        return "ALL correct, including fib(1)=1"
    if broke:
        k = broke[0]
        return "breaks a working case: fib(%d)=%d, should be %d" % (k, vals[k], SPEC[k])
    return "fib(1) = %d (still wrong)" % vals.get(1)


def part_b():
    print("PART B: the slides' three hypotheses, each a one-change experiment")
    v1, _ = experiment("fib_only1", ["-O0", "-DONLY1"])
    v2, _ = experiment("fib_loop", ["-O0", "-DLOOPCOND=(n>=1)"])
    v3, _ = experiment("fib_init", ["-O0", "-DINITF==1"])
    rows = [
        ("1. call order matters", "call fib(1) first and alone", summarize(v1, only_one=True)),
        ("2. loop test `n > 1` is wrong", "change it to `n >= 1`", summarize(v2)),
        ("3. `f` is uninitialized", "initialize `int f = 1;`", summarize(v3)),
    ]
    for hyp, exp, obs in rows:
        print("  hypothesis: %s" % hyp)
        print("    experiment:  %s" % exp)
        print("    observation: %s\n" % obs)
    print("  Diagnosis: hypothesis 3. For n = 1 the loop never runs, so the")
    print("  uninitialized `f` is returned. Initializing it fixes fib(1) AND keeps")
    print("  every working case. Hypothesis 1 is refuted (call order cannot matter --")
    print("  the loop still never runs). Hypothesis 2 'fixes' fib(1) but breaks")
    print("  fib(2) and up: a fix must not create new failures.\n")


def main():
    print("=== Demo 01: scientific debugging (the slides' badfib) ===\n")
    part_a()
    part_b()
    print("Observations:")
    print("  * defect -> error -> failure: the failure (fib(1) wrong) is the visible")
    print("    end; debugging searches back to the defect (uninitialized f).")
    print("  * Change ONE condition per experiment, compare with a known-good run, and")
    print("    do not proceed past the first bug.")
    print("  * A 'fix' that passes the failing case but breaks others (hypothesis 2) is")
    print("    not a fix. Confirm the fix AND the previously-working behavior.")
    print("  * Undefined behavior makes the symptom depend on the optimization level.")
    print("    On Linux, valgrind or -fsanitize=memory names the uninitialized read")
    print("    directly; both are unavailable on arm64 macOS, so the method did it.")


if __name__ == "__main__":
    main()
