TExcelTAD

Build Exercises

Each exercise is a small piece of a real build tool, written as a pure function with the tests already in place. Run the starter first: it prints placeholder answers, which shows what the tests call. Fill in the code marked TODO until your output matches the expected output, then compare with the solution. The topics link back to the lessons that explain them.

Exercise 1: Find unresolved symbols

Topics: Symbols: nm, objdump & readelf, Link Errors & Link Order

nm output for several objects is given as text. Return the sorted list of symbols that some object needs (U) but no object defines (any uppercase type other than U). Those are the future "undefined reference" errors.

python · try it yourself
NM_OUTPUT = {
    "main.o": """
                 U config_load
0000000000000000 T main
                 U printf
                 U render_frame
""",
    "render.o": """
0000000000000000 T render_frame
                 U shader_compile
0000000000000010 b frame_count
""",
    "config.o": """
0000000000000000 T config_load
0000000000000000 D config_path
                 U fopen
""",
}

def unresolved(nm_output, provided_by_libs=()):
    # TODO: collect needed and defined symbols, return sorted(needed - defined - provided)
    return []

print(unresolved(NM_OUTPUT))
print(unresolved(NM_OUTPUT, provided_by_libs={"printf", "fopen"}))
[]
[]

Expected output:

text
['fopen', 'printf', 'shader_compile']
['shader_compile']
Show solution
python
def unresolved(nm_output, provided_by_libs=()):
    needed, defined = set(), set()
    for text in nm_output.values():
        for line in text.strip().splitlines():
            parts = line.split()
            kind, name = parts[-2], parts[-1]
            if kind == "U":
                needed.add(name)
            elif kind.isupper():
                defined.add(name)
    return sorted(needed - defined - set(provided_by_libs))

Exercise 2: Order the link line

Topics: Link Errors & Link Order, Build Graphs & Topological Order

Static libraries must appear after every library that uses them. Given which libraries each library depends on, return a valid -l order for GNU ld (users before providers). Break ties alphabetically so the answer is unique, and raise ValueError on a cycle.

python · try it yourself
def link_order(deps):
    # deps: library -> list of libraries it calls into
    # TODO: Kahn's algorithm where a library is "ready" once every library that USES it is placed
    return []

print(link_order({"app": ["net", "log"], "net": ["tls", "log"], "tls": ["crypto"], "log": [], "crypto": []}))
print(link_order({"ui": ["gfx"], "gfx": ["math"], "math": [], "audio": ["math"]}))
try:
    print(link_order({"a": ["b"], "b": ["a"]}))
except ValueError as e:
    print("error:", e)
[]
[]
[]

Expected output:

text
['app', 'net', 'log', 'tls', 'crypto']
['audio', 'ui', 'gfx', 'math']
error: cycle between a, b
Show solution
python
def link_order(deps):
    users = {lib: 0 for lib in deps}               # how many libraries use each one
    for lib, uses in deps.items():
        for d in uses:
            users[d] += 1
    ready = sorted(l for l, n in users.items() if n == 0)
    order = []
    while ready:
        lib = ready.pop(0)
        order.append(lib)
        for d in deps[lib]:
            users[d] -= 1
            if users[d] == 0:
                ready.append(d)
                ready.sort()
    if len(order) != len(deps):
        raise ValueError("cycle between " + ", ".join(sorted(set(deps) - set(order))))
    return order

Exercise 3: What needs rebuilding?

Topics: Incremental Builds, A Tiny Make Engine

Given rules (target -> inputs) and modification times, return the sorted list of targets a timestamp-based tool would rebuild. A target is rebuilt if it is missing, if any input is newer, or if any input is itself rebuilt.

python · try it yourself
RULES = {
    "app": ["main.o", "libcore.a"],
    "libcore.a": ["parse.o", "eval.o"],
    "main.o": ["main.c", "core.h"],
    "parse.o": ["parse.c", "core.h"],
    "eval.o": ["eval.c"],
}

def to_rebuild(rules, mtimes):
    # TODO: walk each target's inputs first (recursion with a memo), then decide
    return []

base = {"main.c": 10, "core.h": 10, "parse.c": 10, "eval.c": 10,
        "main.o": 20, "parse.o": 20, "eval.o": 20, "libcore.a": 30, "app": 40}
print(to_rebuild(RULES, base))
print(to_rebuild(RULES, {**base, "eval.c": 50}))
print(to_rebuild(RULES, {**base, "core.h": 50}))
print(to_rebuild(RULES, {k: v for k, v in base.items() if k != "parse.o"}))
[]
[]
[]
[]

Expected output:

text
[]
['app', 'eval.o', 'libcore.a']
['app', 'libcore.a', 'main.o', 'parse.o']
['app', 'libcore.a', 'parse.o']
Show solution
python
def to_rebuild(rules, mtimes):
    memo = {}
    def stale(target):
        if target not in rules:                     # a source file
            return False
        if target not in memo:
            inputs_stale = [stale(i) for i in rules[target]]   # visit every input
            memo[target] = (target not in mtimes or any(inputs_stale)
                            or any(mtimes.get(i, 0) > mtimes[target] for i in rules[target]))
        return memo[target]
    return sorted(t for t in rules if stale(t))

Exercise 4: Caret and tilde ranges

Topics: Versions & Semver Ranges

Return the half-open interval (lower, upper) that a caret or tilde range means, as version strings. Remember the 0.x rule for carets: the first non-zero part is the one that may not change.

python · try it yourself
def bounds(rng):
    # TODO: "^1.4.2" -> ("1.4.2", "2.0.0"), "~1.4.2" -> ("1.4.2", "1.5.0"), handle ^0.x and ^0.0.x
    return None

for r in ["^1.4.2", "^0.4.2", "^0.0.3", "~1.4.2", "~0.4.2"]:
    print(r, bounds(r))
^1.4.2 None
^0.4.2 None
^0.0.3 None
~1.4.2 None
~0.4.2 None

Expected output:

text
^1.4.2 ('1.4.2', '2.0.0')
^0.4.2 ('0.4.2', '0.5.0')
^0.0.3 ('0.0.3', '0.0.4')
~1.4.2 ('1.4.2', '1.5.0')
~0.4.2 ('0.4.2', '0.5.0')
Show solution
python
def bounds(rng):
    op, version = rng[0], rng[1:]
    major, minor, patch = (int(x) for x in version.split("."))
    if op == "~":
        upper = (major, minor + 1, 0)
    elif major > 0:
        upper = (major + 1, 0, 0)
    elif minor > 0:
        upper = (0, minor + 1, 0)
    else:
        upper = (0, 0, patch + 1)
    return version, ".".join(map(str, upper))

Exercise 5: A stable cache key

Topics: Content-Addressed Caches, Hermetic Builds

Write cache_key(action) returning the first 12 hex digits of a SHA-256 over everything that affects the output. The key must not change when the input files are listed in a different order or when the irrelevant "user" field changes, but must change when file contents, flags or the compiler change.

python · try it yourself
import hashlib, json

def cache_key(action):
    # TODO: hash compiler, flags and the CONTENT of inputs (sorted by name); ignore "user"
    return "000000000000"

a = {"compiler": "gcc 13.3", "flags": ["-O2"], "user": "ada",
     "inputs": {"main.c": "int main(void){}", "util.h": "#pragma once"}}
b = {**a, "user": "linus", "inputs": dict(reversed(list(a["inputs"].items())))}
c = {**a, "flags": ["-O2", "-g"]}
d = {**a, "inputs": {**a["inputs"], "util.h": "#pragma once\n"}}
print("same action, other user and order:", cache_key(a) == cache_key(b))
print("different flags:                  ", cache_key(a) != cache_key(c))
print("one header byte changed:          ", cache_key(a) != cache_key(d))
print("key length:", len(cache_key(a)))
same action, other user and order: True
different flags:                   False
one header byte changed:           False
key length: 12

Expected output:

text
same action, other user and order: True
different flags:                   True
one header byte changed:           True
key length: 12
Show solution
python
def cache_key(action):
    relevant = {
        "compiler": action["compiler"],
        "flags": action["flags"],                       # order of flags can matter: keep it
        "inputs": {name: hashlib.sha256(text.encode()).hexdigest()
                   for name, text in sorted(action["inputs"].items())},
    }
    return hashlib.sha256(json.dumps(relevant, sort_keys=True).encode()).hexdigest()[:12]

Exercise 6: Read a dependency file

Topics: Header Dependencies (-MMD)

Parse the text of a .d file written by gcc -MMD -MP into {target: [inputs]}, skipping the empty -MP rules. Lines can be continued with a backslash.

python · try it yourself
D_FILE = r"""build/net.o: src/net.c include/net.h include/buffer.h \
 include/platform/linux.h
include/net.h:
include/buffer.h:
include/platform/linux.h:
"""

def parse_d(text):
    # TODO: join continuation lines, split "target: inputs", drop rules with no inputs
    return {}

print(parse_d(D_FILE))
{}

Expected output:

text
{'build/net.o': ['src/net.c', 'include/net.h', 'include/buffer.h', 'include/platform/linux.h']}
Show solution
python
def parse_d(text):
    rules = {}
    for line in text.replace("\\\n", " ").splitlines():
        target, sep, inputs = line.partition(":")
        if sep and inputs.split():
            rules[target.strip()] = inputs.split()
    return rules

Exercise 7 (shell): Diagnose a link failure

Topics: Static Libraries (ar), Link Errors & Link Order

This session builds two static libraries and fails to link. Before reading the answer, work out from the output why it fails, and what the shortest correct link command is. Then try it on your machine.

bash · try it yourself
mkdir -p ex && cd ex
printf 'int checksum(const char *s) { int h = 0; while (*s) h = h * 31 + *s++; return h; }\n' > hash.c
printf 'int checksum(const char *s);\nint verify(const char *s, int expected) { return checksum(s) == expected; }\n' > verify.c
printf '#include <stdio.h>\nint verify(const char *, int);\nint main(void) { printf("%%s\\n", verify("abc", 96354) ? "valid" : "invalid"); return 0; }\n' > main.c
gcc -c hash.c verify.c main.c
ar rcs libhash.a hash.o && ar rcs libverify.a verify.o
gcc main.o -L. -lhash -lverify -o app
/usr/bin/ld: ./libverify.a(verify.o): in function `verify':
verify.c:(.text+0x1b): undefined reference to `checksum'
collect2: error: ld returned 1 exit status
Show answer

libverify.a needs checksum from libhash.a, but libhash.a comes first on the line: when the linker scanned it, nothing needed checksum yet, so no member was taken. Users must come before providers: gcc main.o -L. -lverify -lhash -o app, which prints valid.

Test yourself

In Exercise 2, why must log come after both app and net?

  1. Alphabetical order
  2. Both use log, and GNU ld only takes archive members for symbols that are already undefined
  3. log is the largest library
  4. It doesn't matter

In Exercise 5, why is the user field left out of the key?

  1. To save space
  2. It doesn't affect the output, so including it would cause needless cache misses between users
  3. It is secret
  4. JSON can't encode it