"""
01_symbols.py -- what symbols are, and how the linker resolves duplicates
==========================================================================

[Questions this demo answers]
  - A linker connects "references" to "definitions" across .o files. What
    exactly is a symbol, and which kind (global / external / local) is each
    name in the slides' main.c / sum.c?
  - How does `nm` show them, and what do the letters T / t / U / D / b mean?
  - The three symbol-resolution rules: what happens when two files define the
    same global? (strong+strong, strong+weak, weak+weak)
  - Why is a type mismatch between a strong and a weak global so dangerous?

[How to run]
  python3 01_symbols.py

[How to read the output]
  PART A compiles main.c and sum.c and classifies every symbol. PART B runs
  the three resolution rules as real link attempts and reports success or the
  linker's error. PART C shows a weak `long x` silently sharing storage with a
  strong `double x`, so writing one corrupts the other.

[Systems link / CS:APP 7.5-7.6]
  Separate compilation means each .o knows only its own code; the linker is
  what makes "one program" out of many modules. Its duplicate-symbol rules are
  a frequent source of baffling bugs, because a mismatch links cleanly and
  misbehaves only at run time.
"""

import os

import toolchain as tc


def classify(line):
    """Turn one `nm` line into (name, kind-letter, human description)."""
    parts = line.split()
    if len(parts) < 2:
        return None
    letter = parts[-2] if len(parts) >= 3 else parts[0]
    name = parts[-1]
    # nm letters: upper = global, lower = local; T/t text, D/d data, B/b bss,
    # U undefined (external reference), C common (tentative/weak).
    meaning = {
        "T": "GLOBAL, defined here (text/code)", "t": "local (static) function",
        "D": "GLOBAL, defined here (initialized data)", "d": "local initialized data",
        "B": "GLOBAL, defined here (.bss, zero-init)", "b": "local .bss",
        "C": "GLOBAL, tentative/common (a WEAK definition)",
        "U": "EXTERNAL: referenced here, defined elsewhere",
        "s": "local (Mach-O section symbol)", "S": "global .bss (Mach-O)",
    }.get(letter, "(%s)" % letter)
    return name, letter, meaning


def part_a():
    print("PART A: symbols in the slides' main.c / sum.c")
    tc.ensure_build()
    tc.cc(["-O1", "-c", tc.src("main.c"), "-o", "main.o"])
    tc.cc(["-O1", "-c", tc.src("sum.c"), "-o", "sum.o"])
    for obj in ("main.o", "sum.o"):
        print("  %s:" % obj)
        for line in tc.nm(obj):
            c = classify(line)
            if not c:
                continue
            name, letter, meaning = c
            if name.startswith(("ltmp", "l_")):          # assembler temporaries
                continue
            print("    %-10s %-3s %s" % (name, letter, meaning))
    print("  main.o DEFINES _main and _array (global), REFERENCES _sum (external, U).")
    print("  sum.o DEFINES _sum. The linker matches main.o's U _sum to sum.o's T _sum.")
    print("  (Names start with '_' on macOS; Linux has no leading underscore.)\n")


def try_link(label, objs, make_objs):
    """Compile the given sources and try to link them; report the outcome."""
    for s, o in make_objs:
        tc.cc(["-O1", "-c", tc.src(s), "-o", o])
    cp = tc.cc(objs + ["-o", "puzzle_out"])
    if cp.returncode == 0:
        print("  %-28s LINKS (no error)" % label)
    else:
        msg = (cp.stderr or cp.stdout).strip().splitlines()
        first = next((l for l in msg if "duplicate" in l.lower() or "multiple" in l.lower()
                      or "error" in l.lower()), msg[0] if msg else "error")
        print("  %-28s LINK ERROR: %s" % (label, first.strip()))


def part_b():
    print("PART B: the three resolution rules, as real link attempts")
    print("  (strong = initialized global or function; weak = tentative/uninitialized global)")
    # A main that uses p1/p2/q1/q2 so the objects are actually linked.
    main_c = os.path.join(tc.BUILD, "puzzle_main.c")
    with open(main_c, "w") as f:
        f.write("int x;\nint main(void){return x;}\n")
    tc.cc(["-O1", "-c", "puzzle_main.c", "-o", "puzzle_main.o"])
    print("  Rule 1 (two STRONG definitions of x is an error):")
    try_link("    strong1.o + strong2.o", ["puzzle_main.o", "strong1.o", "strong2.o"],
             [("strong1.c", "strong1.o"), ("strong2.c", "strong2.o")])
    print("  Rule 2 (one strong + weak -> the strong one wins): see PART C.")
    print("  Rule 3 (two WEAK definitions -> the linker picks one, silently):")
    try_link("    weak1.o + weak2.o", ["puzzle_main.o", "weak1.o", "weak2.o"],
             [("weak1.c", "weak1.o"), ("weak2.c", "weak2.o")])
    print("  Rule 3 is the trap: two files each think they own `int x`, but they")
    print("  share ONE location. A write in one is a surprise in the other.")
    print("  (`cc -fno-common` or, on modern toolchains, the default, turns Rule 3")
    print("   into a link error too. This toolchain still allows it.)\n")


def part_c():
    print("PART C: Rule 2 and a type mismatch -- a weak `long x` over a strong `double x`")
    print("  def_double.c:  double x = 3.14;  (strong)      main prints x, calls clobber()")
    print("  use_long.c:    long   x;          (weak)        clobber() does x = -1;")
    tc.cc(["-O1", "-c", tc.src("def_double.c"), "-o", "def_double.o"])
    tc.cc(["-O1", "-c", tc.src("use_long.c"), "-o", "use_long.o"])
    cp = tc.cc(["def_double.o", "use_long.o", "-o", "mismatch"])
    if cp.returncode != 0:
        print("  (this toolchain rejects the mismatch at link time: %s)"
              % (cp.stderr or cp.stdout).strip().splitlines()[0])
        print()
        return
    out = tc.run(["./mismatch"]).stdout
    print("  linked with NO error or warning. Running it:")
    for line in out.strip().splitlines():
        print("    " + line)
    print("  clobber() wrote the 8-byte integer -1 into the storage that main thinks")
    print("  is a double: 3.14 becomes nan. The two names are the same 8 bytes, with")
    print("  incompatible types -- exactly the 'Evil!' puzzle on the slides.\n")


def main():
    print("=== Demo 01: symbols and symbol resolution ===\n")
    part_a()
    part_b()
    part_c()
    print("Observations:")
    print("  * A symbol is a name the linker tracks: GLOBAL (defined here, usable")
    print("    elsewhere), EXTERNAL (used here, defined elsewhere: nm's U) or LOCAL")
    print("    (static, file-private). nm's letter gives the kind and the section.")
    print("  * Two strong definitions are a link error; a strong and weak pair resolves")
    print("    to the strong one; two weak ones silently share storage.")
    print("  * A strong/weak type mismatch links cleanly and corrupts data at run time.")
    print("    Lesson: avoid global variables; use static; initialize; use extern to")
    print("    REFERENCE, never to define.")


if __name__ == "__main__":
    main()
