Last active
January 26, 2022 21:00
-
-
Save bgamari/38f12831ebdec058537787909bb6c4e8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
""" | |
Compute link order | |
""" | |
import sys | |
from pathlib import Path | |
import typing | |
from typing import Set, NamedTuple | |
import subprocess | |
Symbol = str | |
class Syms(NamedTuple): | |
defined: Set[Symbol] | |
referenced: Set[Symbol] | |
def get_syms(obj): | |
out = subprocess.check_output(['nm', '-g', '--format=posix', obj], encoding='ASCII') | |
defined = set() | |
referenced = set() | |
for l in out.split('\n'): | |
parts = l.split(' ') | |
if len(parts) >= 2: | |
symbol = parts[0] | |
state = parts[1] | |
if state == 'U': | |
referenced.add(symbol) | |
else: | |
defined.add(symbol) | |
referenced.difference_update(defined) | |
return Syms(defined, referenced) | |
def dump_deps(objects: Set[str], file: typing.TextIO): | |
obj_symbols = {obj: get_syms(obj) for obj in objects} | |
for obj, syms in obj_symbols.items(): | |
for sym in syms.defined: | |
print(f'{sym} @{obj}', file=file) | |
for sym in syms.referenced: | |
print(f'@{obj} {sym}', file=file) | |
def link_order(objects): | |
p = subprocess.Popen(['tsort'], stdin=subprocess.PIPE, encoding='ASCII') | |
dump_deps(objects, p.stdin) | |
p.stdin.close() | |
p.wait() | |
def main(): | |
import argparse | |
parser = argparse.ArgumentParser() | |
parser.add_argument('object', nargs='+') | |
parser.add_argument('--raw', action='store_true') | |
args = parser.parse_args() | |
if args.raw: | |
dump_deps(args.object, sys.stdout) | |
else: | |
link_order(args.object) | |
if __name__ == '__main__': | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment