"""
03_static_libraries.py -- bundling .o files into a .a, and the link-order rule
===============================================================================

[Questions this demo answers]
  - What is a static library (a .a archive), and how is one built?
  - When you link against a library, does the whole library go into your
    program, or only the parts you use?
  - Why does `cc main.o libvector.a` work but `cc libvector.a main.o` can
    fail? (The famous link-order rule.)

[How to run]
  python3 03_static_libraries.py

[How to read the output]
  PART A builds libvector.a from addvec.o and multvec.o and lists its members.
  PART B links the client two ways and reports which symbols ended up in the
  executable (main2 calls addvec but not multvec). PART C demonstrates the
  order rule with a deliberately bad command line.

[Systems link / CS:APP 7.6.2]
  A static library is just an indexed bundle of .o files. The linker walks the
  command line left to right, and when it meets a library it pulls in ONLY the
  members that satisfy references it has seen so FAR. So a library must come
  after the code that uses it.
"""

import re

import toolchain as tc


def part_a():
    print("PART A: building the archive libvector.a")
    tc.ensure_build()
    tc.cc(["-O1", "-c", tc.src("addvec.c"), "-o", "addvec.o"])
    tc.cc(["-O1", "-c", tc.src("multvec.c"), "-o", "multvec.o"])
    tc.cc(["-O1", "-c", tc.src("main2.c"), "-o", "main2.o"])
    tc.run(["ar", "rcs", "libvector.a", "addvec.o", "multvec.o"])
    members = tc.run(["ar", "t", "libvector.a"]).stdout.split()
    print("  ar rcs libvector.a addvec.o multvec.o   ->  members: %s" % ", ".join(members))
    print("  An archive is a bundle of .o files with an index of their symbols. Nothing")
    print("  is linked yet; it is a container the linker can search.\n")


def symbols_in(exe):
    """The defined function symbols (T/t) in a built executable."""
    out = set()
    for line in tc.nm(exe):
        parts = line.split()
        if len(parts) >= 3 and parts[-2] in ("T", "t"):
            out.add(parts[-1].lstrip("_"))
    return out


def part_b():
    print("PART B: only the members you USE are pulled in")
    tc.cc(["main2.o", "libvector.a", "-o", "client"])
    syms = symbols_in("client")
    print("  main2 calls addvec but not multvec. In the linked executable:")
    print("    addvec present:  %s" % ("yes" if "addvec" in syms else "no"))
    print("    multvec present: %s" % ("yes" if "multvec" in syms else "no"))
    cp = tc.run(["./client"])
    print("  ./client  ->  %s" % cp.stdout.strip())
    print("  The linker copied addvec.o out of the archive (it resolved a reference)")
    print("  and left multvec.o behind (nothing referenced it). A static library is")
    print("  resolved member by member, not all-or-nothing.\n")


def part_c():
    print("PART C: the link-order rule")
    good = tc.cc(["main2.o", "libvector.a", "-o", "ok_order"])
    bad = tc.cc(["libvector.a", "main2.o", "-o", "bad_order"])
    print("  cc main2.o libvector.a   -> %s" % ("links" if good.returncode == 0 else "ERROR"))
    print("  cc libvector.a main2.o   -> %s" % ("links" if bad.returncode == 0
                                                else "ERROR: " +
          next((l.strip() for l in (bad.stderr or bad.stdout).splitlines()
                if "addvec" in l or "undefined" in l.lower() or "symbol" in l.lower()),
               "undefined symbol")))
    if bad.returncode == 0:
        print("  (This linker happens to tolerate the reversed order; the classic GNU ld")
        print("   rejects it. The rule still holds in general, and -Wl,--start-group")
        print("   exists for mutually dependent libraries.)")
    else:
        print("  When the linker met libvector.a FIRST, it had seen no references yet, so")
        print("  it took nothing from the archive. Then main2.o referenced addvec, which")
        print("  was already passed. Rule: put libraries AFTER the code that uses them.")
    print()


def main():
    print("=== Demo 03: static libraries ===\n")
    part_a()
    part_b()
    part_c()
    print("Observations:")
    print("  * A static library (.a) is an indexed bundle of .o files.")
    print("  * The linker extracts only the members that resolve references it has")
    print("    already seen, so unused code (multvec) stays out of the executable.")
    print("  * Because resolution is left-to-right, a library must appear after the")
    print("    objects that use it on the command line.")


if __name__ == "__main__":
    main()
