]> git.saurik.com Git - apple/xnu.git/blame - tools/symbolify.py
xnu-3789.21.4.tar.gz
[apple/xnu.git] / tools / symbolify.py
CommitLineData
6d2010ae
A
1#!/usr/bin/env python
2from subprocess import Popen, PIPE, call
3import re
4import sys
5import os
6
39236c6e
A
7SLIDE = 0
8
6d2010ae
A
9NM_FORMAT = "([0-9a-f]+) ([UuAaTtDdBbCcSsIi]) (.*)"
10
11nm_re = re.compile(NM_FORMAT)
12
13def parse_nm_output(str):
14 "returns (start, type, name)"
15 m = nm_re.match(str)
16 if m:
17 start = int(m.group(1), 16)
18 return (start, m.group(2), m.group(3))
19 else:
20 return None
21
22def nm(file):
23 cmd = "nm %s" % file
24 p = Popen(cmd, shell=True, stdout=PIPE)
25 return p.stdout
26
27class SymbolLookup:
28 def __init__(self, file, min_width=16):
29 self.min_width = min_width
30 self.symbols = [parse_nm_output(l) for l in nm(file)]
31 self.symbols.sort(key=lambda x: x[0])
32
33 def padded(self, str):
34 return ("%%%ds" % self.min_width) % str
35
36 def __call__(self, saddr):
37 addr = int(saddr.group(0), 16)
38 last = (0, ' ', '<start of file>')
39236c6e
A
39 if( addr > SLIDE ):
40 addr -= SLIDE
6d2010ae
A
41 # stupid linear search... feel free to improve
42 for s in self.symbols:
43 if s[0] == addr:
44 return self.padded(s[2])
45 elif s[0] > addr:
46 if last[2] == "_last_kernel_symbol":
47 return saddr.group(0)
48 return self.padded("<%s>+%x" % (last[2], addr - last[0]))
49 else:
50 last = s
51 if last[2] == "_last_kernel_symbol":
52 return saddr.group(0)
53 return self.padded("<%s>+%x" % (last[2], addr - last[0]))
54
55def symbolify(objfile, input, *args, **kargs):
56 replacer = SymbolLookup(objfile, *args, **kargs)
57 for l in input:
58 print re.sub("(0x)?[0-9a-f]{6,16}", replacer, l),
59
60
61def usage():
62
39236c6e 63 print "usage: %s [filename] [slide]" % sys.argv[0]
6d2010ae
A
64 print "\tor speficy a filename in your SYMBOLIFY_KERNEL environment variable"
65
66 # die now
67 sys.exit(1)
68
69KERNEL_FILE = None
70
39236c6e 71if( len(sys.argv) > 3 ):
6d2010ae
A
72 usage()
73
39236c6e
A
74if( len(sys.argv) == 3 ):
75 SLIDE = int(sys.argv[2], 16)
76
77if( len(sys.argv) >= 2 ):
6d2010ae
A
78 KERNEL_FILE = sys.argv[1]
79
80if( KERNEL_FILE is None ):
81 KERNEL_FILE = os.environ.get("SYMBOLIFY_KERNEL")
82
83if( KERNEL_FILE is None ):
84 usage()
85
39236c6e 86print "using kernel file '%s', slide 0x%x" % (KERNEL_FILE, SLIDE)
6d2010ae
A
87
88symbolify(KERNEL_FILE, sys.stdin, min_width=40)
89