"""
02_relocation.py -- how the linker fills in the addresses (relocation)
=======================================================================

[Questions this demo answers]
  - In a .o file the address of `array` and the target of `call/jmp sum` are
    not known yet. What does the compiler leave there, and how does it tell
    the linker what to patch?
  - What is a RELOCATION ENTRY, and what do its types mean (a PC-relative
    branch; a PC/image-relative data reference)?
  - After linking, what do those placeholder bytes become? Does the
    PC-relative displacement add up?

[How to run]
  make -C .. >/dev/null 2>&1   # or just run it; it compiles what it needs
  python3 02_relocation.py

[How to read the output]
  The demo compiles the slides' main.c to x86-64 (so the relocation types
  match the slides). PART A shows main.o's disassembly with zero placeholders
  and the relocation table. PART B shows the linked program with the real
  bytes filled in, and checks the jmp displacement by hand.

[Systems link / CS:APP 7.7]
  Relocation is the second half of linking. The compiler cannot know final
  addresses -- they depend on how every module is laid out -- so it writes
  placeholder zeros plus relocation entries telling the linker what to patch.
"""

import re

import toolchain as tc

# This lecture's relocations are clearest in x86-64 (the slides' architecture).
X86 = ["-arch", "x86_64"] if tc.IS_MAC else []


def disasm(path):
    tool = "objdump"
    args = [tool, "--macho", "-d"] if tc.IS_MAC else [tool, "-d"]
    return tc.run(args + [path]).stdout


def relocs(path):
    args = ["objdump", "--macho", "-r"] if tc.IS_MAC else ["objdump", "-r"]
    return tc.run(args + [path]).stdout


def func_lines(text, name):
    """The disassembly lines of one function, from its label to the next blank/label."""
    out, grab = [], False
    for line in text.splitlines():
        if re.match(r"_?%s:\s*$" % name, line.strip()):
            grab = True
            out.append(line.rstrip())
            continue
        if grab:
            if not line.strip() or re.match(r"[_.A-Za-z].*:\s*$", line.strip()):
                break
            out.append(line.rstrip())
            if re.search(r"\b(ret|retq)\b", line) or re.search(r"\bjmp\b", line):
                break
    return out


def part_a():
    print("PART A: main.o BEFORE linking (compiled to x86-64, as on the slides)")
    tc.ensure_build()
    tc.cc(X86 + ["-O1", "-c", tc.src("main.c"), "-o", "main.o"])
    for line in func_lines(disasm("main.o"), "main"):
        print("    " + line)
    print("  Relocation entries (objdump -r):")
    for line in relocs("main.o").splitlines():
        if re.search(r"\b(BRANCH|SIGNED|PC32|PLT32|_32|GOT)\b", line):
            print("    " + line.strip())
    print("  The address slots are ZERO (`8d 3d 00 00 00 00`, `e9 00 00 00 00`). Each")
    print("  relocation entry names the symbol and the patch form:")
    print("    _array : SIGNED  (a %rip-relative data reference)  = ELF R_X86_64_PC32")
    print("    _sum   : BRANCH  (a PC-relative call/jmp target)    = ELF R_X86_64_PLT32")
    print("  Same idea in both formats: 'patch this slot with the address of sym'.\n")


def part_b():
    print("PART B: the linked program -- the placeholders are now real")
    tc.cc(X86 + ["-O1", "-c", tc.src("sum.c"), "-o", "sum.o"])
    tc.cc(X86 + ["main.o", "sum.o", "-o", "prog"])
    lines = func_lines(disasm("prog"), "main")
    for line in lines:
        print("    " + line)
    # Check the jmp _sum displacement: target = addr(next insn) + disp32.
    jmp = next((l for l in lines if re.search(r"\bjmp\b", l)), "")
    cols = jmp.split("\t")                 # addr: | bytes | mnemonic | operands
    if len(cols) >= 2 and ":" in cols[0]:
        addr = int(cols[0].split(":")[0], 16)
        raw = cols[1].split()                   # e.g. ['e9','0a','00','00','00']
        disp = int.from_bytes(bytes(int(b, 16) for b in raw[1:5]), "little", signed=True)
        nxt = addr + len(raw)
        print("  Checking the jmp: it is at 0x%x, %d bytes long (e9 + 4-byte disp), so the" % (addr, len(raw)))
        print("  next instruction is 0x%x. displacement = 0x%x (%d). target = 0x%x + %d = 0x%x = _sum."
              % (nxt, disp & 0xFFFFFFFF, disp, nxt, disp, nxt + disp))
    cp = tc.run(["./prog"])
    print("  Running it: ./prog; echo $?  ->  %d  (= 1 + 2)\n" % cp.returncode)


def main():
    print("=== Demo 02: relocation ===\n")
    part_a()
    part_b()
    print("Observations:")
    print("  * A .o has holes (zero bytes) where addresses go, plus relocation entries")
    print("    saying which symbol patches each hole and in what form.")
    print("  * Linking lays out all modules, then patches: a data reference becomes a")
    print("    %rip-relative offset, a call/jmp becomes a PC-relative displacement.")
    print("  * The displacement is self-consistent: target = next-instruction + disp,")
    print("    the same arithmetic you decoded by hand in Lecture 3.")


if __name__ == "__main__":
    main()
