File size: 2,898 Bytes
cf6b956
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/usr/bin/env python3
"""Attribute fingerprint (BBV) segments to functions.

Reads the libfpg pcmap (bb_pc,bb_id,bb_size,bb_pc_vec) and bbfp SimPoint basic
block vector file, plus `nm` symbol output for the traced binary, and reports
the per-function share of executed instructions for a chosen set of segments.

Usage: fp_funcs.py <pcmap> <bbfp> <nm-file> [segment ...]
       (no segments -> whole run)
"""
import sys
import bisect
from collections import defaultdict


def load_symbols(nm_path):
    syms = []
    with open(nm_path) as f:
        for line in f:
            parts = line.split(None, 2)
            if len(parts) < 3:
                continue
            addr, typ, name = parts[0], parts[1], parts[2].strip()
            if typ.lower() not in ("t", "w", "i"):
                continue
            try:
                syms.append((int(addr, 16), name))
            except ValueError:
                continue
    syms.sort()
    return [s[0] for s in syms], [s[1] for s in syms]


def main():
    pcmap_path, bbfp_path, nm_path = sys.argv[1:4]
    wanted = set(int(x) for x in sys.argv[4:])

    addrs, names = load_symbols(nm_path)

    # bb_id -> (bb_pc, bb_size)
    bb = {}
    with open(pcmap_path) as f:
        f.readline()
        for line in f:
            fields = line.rstrip("\n").split(",")
            if len(fields) < 3:
                continue
            bb[int(fields[1])] = (int(fields[0]), int(fields[2]))

    per_func = defaultdict(int)
    total = 0
    seg = 0
    with open(bbfp_path) as f:
        for line in f:
            line = line.strip()
            if not line.startswith("T"):
                continue
            seg += 1
            if wanted and seg not in wanted:
                continue
            for tok in line[1:].split():
                tok = tok.strip()
                if not tok.startswith(":"):
                    continue
                bb_id, cnt = tok[1:].split(":")
                bb_id, cnt = int(bb_id), int(cnt)
                pc, size = bb.get(bb_id, (0, 0))
                # libfpg already weights each basic-block entry by the number
                # of instructions in the block, so cnt is an instruction count.
                instrs = cnt
                total += instrs
                if pc < addrs[0] or pc > addrs[-1] + 0x10000:
                    per_func["[outside main binary: libc/ld.so]"] += instrs
                    continue
                i = bisect.bisect_right(addrs, pc) - 1
                per_func[names[i] if i >= 0 else "?"] += instrs

    print(f"# segments considered: {len(wanted) if wanted else seg}")
    print(f"# total instructions:  {total}")
    print(f"{'share%':>8}  {'instructions':>14}  function")
    for name, n in sorted(per_func.items(), key=lambda kv: -kv[1])[:30]:
        print(f"{100.0 * n / total:8.3f}  {n:14d}  {name}")


if __name__ == "__main__":
    main()