"""
04_shared_libraries.py -- dynamic libraries: load-time, run-time, interposition
=================================================================================

[Questions this demo answers]
  - A shared library is linked into a program as it RUNS, not baked into the
    executable. How do you build one, and how do you see which ones a program
    needs?
  - How does a program load a library and find a function in it at run time
    (dlopen / dlsym -- the slides' dll.c)?
  - How can you INTERPOSE your own version of a function in front of the real
    one without recompiling the program (LD_PRELOAD on Linux; the __interpose
    section on macOS)?

[How to run]
  python3 04_shared_libraries.py

[How to read the output]
  PART A builds libvector as a shared library and lists the program's library
  dependencies. PART B runs dll.c, which dlopens the library by name. PART C
  interposes a traced version of square() in front of the real one and shows
  the same unmodified program calling the interposer.

[Systems link / CS:APP 7.10-7.13]
  Shared libraries exist because statically linking libc into every program
  wastes disk and memory and freezes bug fixes into each binary. One copy of a
  .so/.dylib on disk is mapped into many processes. The flip side -- being
  able to swap the implementation at load time -- is what interposition and
  tools like LD_PRELOAD exploit.
"""

import os

import toolchain as tc


def part_a():
    print("PART A: building a shared library and seeing the dependency")
    tc.ensure_build()
    libname, cp = tc.shared_lib("libvector", ["addvec.c", "multvec.c"])
    print("  built %s (%s)" % (libname, "macOS .dylib" if tc.IS_MAC else "ELF .so"))
    # A client that links against the shared library (not a copy of it).
    tc.cc(["-O1", "-c", tc.src("main2.c"), "-o", "main2.o"])
    link = ["main2.o", "-L.", "-lvector", "-o", "client_dyn"]
    if not tc.IS_MAC:
        link = ["main2.o", "-L.", "-Wl,-rpath,.", "-lvector", "-o", "client_dyn"]
    tc.cc(link)
    d = tc.deps("client_dyn")
    print("  the executable's library dependencies (%s):" % ("otool -L" if tc.IS_MAC else "ldd"))
    for line in d.splitlines():
        if "vector" in line or "libc" in line or "libSystem" in line:
            print("    " + line.strip())
    print("  The executable does NOT contain addvec's code; it records that it NEEDS")
    print("  libvector at run time. One copy of the library on disk serves every")
    print("  program that uses it, and a bug fix in the library reaches them all.\n")


def part_b():
    print("PART B: loading a library at RUN TIME (the slides' dll.c, dlopen/dlsym)")
    libname = "libvector.%s" % tc.SOEXT
    tc.cc(["-O1", tc.src("dll.c"), "-o", "dll"] + ([] if tc.IS_MAC else ["-ldl"]))
    cp = tc.run(["./dll", "./" + libname])
    print("  ./dll ./%s  ->  %s" % (libname, cp.stdout.strip() or cp.stderr.strip()))
    print("  dll was built with NO -lvector: it names the library as a STRING and asks")
    print("  for it with dlopen(), then looks up addvec by name with dlsym(). This is")
    print("  how plugins work -- code chosen at run time, not known at compile time.\n")


def part_c():
    print("PART C: interposition -- replacing a function without recompiling the program")
    # The real implementation, in its own shared library, and a client linked to it.
    tc.shared_lib("libsquare", ["square_real.c"])
    link = ["-O1", tc.src("square_app.c"), "-L.", "-lsquare", "-o", "square_app"]
    if not tc.IS_MAC:
        link += ["-Wl,-rpath,."]
    tc.cc(link)
    env = dict(os.environ)
    env[tc.LIBPATH_VAR] = "." + os.pathsep + env.get(tc.LIBPATH_VAR, "")
    print("  normal run (square from libsquare):")
    for line in tc.run(["./square_app"], env=env).stdout.strip().splitlines():
        print("    " + line)
    # Build the interposer appropriate to the platform.
    if tc.IS_MAC:
        tc.shared_lib("libtrace", ["square_trace_macos.c"], extra=["-L.", "-lsquare"])
        mech = "the __interpose section"
    else:
        tc.shared_lib("libtrace", ["square_trace_linux.c"], extra=["-ldl"])
        mech = "LD_PRELOAD + dlsym(RTLD_NEXT)"
    env2 = dict(env)
    env2[tc.PRELOAD_VAR] = "./libtrace.%s" % tc.SOEXT
    print("  with the interposer loaded first (%s, via %s):" % (mech, tc.PRELOAD_VAR))
    out = tc.run(["./square_app"], env=env2)
    for line in (out.stdout + out.stderr).strip().splitlines():
        print("    " + line)
    print("  The SAME unmodified square_app now calls the interposer, which calls the")
    print("  real square(), prints a trace, and adds 1000. This is exactly how a")
    print("  malloc tracer or a mock in a test is slipped under a program.\n")


def main():
    print("=== Demo 04: shared libraries and interposition ===\n")
    part_a()
    part_b()
    part_c()
    print("Observations:")
    print("  * A shared library is linked in as the program loads (or later): the")
    print("    executable only records that it needs the library, so one on-disk copy")
    print("    is shared by every process and fixes propagate without relinking.")
    print("  * dlopen/dlsym choose and bind code at run time -- the basis of plugins.")
    print("  * Because binding happens at load time, your own library can be inserted")
    print("    in front of a function (LD_PRELOAD / __interpose) and still call the")
    print("    original -- powerful for tracing and testing, and a security concern.")


if __name__ == "__main__":
    main()
