#!/usr/bin/env python3 """Attribute direct calls in a Mach-O to objects in its same-build Link Map.""" import argparse from bisect import bisect_right import csv from pathlib import Path import re from machox import Macho from redirect_to_runtime import defined_symbols from verify_baseline import inspect_binary def load_link_map(path): objects, symbols = {}, [] section = '' for line in path.read_text(errors='replace').splitlines(): if line in ('# Object files:', '# Sections:', '# Symbols:', '# Dead Stripped Symbols:'): section = line elif line.startswith('# '): continue elif section == '# Object files:': match = re.fullmatch(r'\[\s*(\d+)\]\s+(.+)', line) if match: objects[int(match[1])] = match[2] elif section == '# Symbols:': match = re.fullmatch(r'(0x[0-9a-fA-F]+)\s+(0x[0-9a-fA-F]+)\s+\[\s*(\d+)\]\s+(.+)', line) if match and int(match[2], 16): symbols.append((int(match[1], 16), int(match[2], 16), int(match[3]), match[4])) if not objects or not symbols: raise ValueError(f'Incomplete Link Map: {path}') return objects, sorted(symbols) def attribute(binary, link_map): objects, entries = load_link_map(link_map) defined = defined_symbols(Macho(binary.read_bytes())) # Require matching named functions before trusting the object addresses. common = [(address, defined[name]) for address, _, _, name in entries if name in defined] if not common or any(mapped != actual for mapped, actual in common): raise ValueError('Link Map symbols do not match executable') _, calls = inspect_binary(binary) starts = [entry[0] for entry in entries] for call in calls: site = int(call['site'], 16) index = bisect_right(starts, site) - 1 if index >= 0: address, size, obj, name = entries[index] if site < address + size and (index == 0 or starts[index - 1] != address): call.update(caller=name, object=objects.get(obj, '')) yield call if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('binary', type=Path) parser.add_argument('link_map', type=Path) parser.add_argument('output', type=Path) args = parser.parse_args() rows = list(attribute(args.binary, args.link_map)) with args.output.open('x', newline='') as stream: writer = csv.DictWriter(stream, fieldnames=['slice_offset', 'site', 'target', 'branch', 'symbol', 'caller', 'object']) writer.writeheader() writer.writerows(rows)