structs.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. #!/usr/bin/env python3
  2. #
  3. # Script to find struct sizes.
  4. #
  5. import os
  6. import glob
  7. import itertools as it
  8. import subprocess as sp
  9. import shlex
  10. import re
  11. import csv
  12. import collections as co
  13. OBJ_PATHS = ['*.o']
  14. def collect(paths, **args):
  15. decl_pattern = re.compile(
  16. '^\s+(?P<no>[0-9]+)'
  17. '\s+(?P<dir>[0-9]+)'
  18. '\s+.*'
  19. '\s+(?P<file>[^\s]+)$')
  20. struct_pattern = re.compile(
  21. '^(?:.*DW_TAG_(?P<tag>[a-z_]+).*'
  22. '|^.*DW_AT_name.*:\s*(?P<name>[^:\s]+)\s*'
  23. '|^.*DW_AT_decl_file.*:\s*(?P<decl>[0-9]+)\s*'
  24. '|^.*DW_AT_byte_size.*:\s*(?P<size>[0-9]+)\s*)$')
  25. results = co.defaultdict(lambda: 0)
  26. for path in paths:
  27. # find decl, we want to filter by structs in .h files
  28. decls = {}
  29. # note objdump-tool may contain extra args
  30. cmd = args['objdump_tool'] + ['--dwarf=rawline', path]
  31. if args.get('verbose'):
  32. print(' '.join(shlex.quote(c) for c in cmd))
  33. proc = sp.Popen(cmd,
  34. stdout=sp.PIPE,
  35. stderr=sp.PIPE if not args.get('verbose') else None,
  36. universal_newlines=True,
  37. errors='replace')
  38. for line in proc.stdout:
  39. # find file numbers
  40. m = decl_pattern.match(line)
  41. if m:
  42. decls[int(m.group('no'))] = m.group('file')
  43. proc.wait()
  44. if proc.returncode != 0:
  45. if not args.get('verbose'):
  46. for line in proc.stderr:
  47. sys.stdout.write(line)
  48. sys.exit(-1)
  49. # collect structs as we parse dwarf info
  50. found = False
  51. name = None
  52. decl = None
  53. size = None
  54. # note objdump-tool may contain extra args
  55. cmd = args['objdump_tool'] + ['--dwarf=info', path]
  56. if args.get('verbose'):
  57. print(' '.join(shlex.quote(c) for c in cmd))
  58. proc = sp.Popen(cmd,
  59. stdout=sp.PIPE,
  60. stderr=sp.PIPE if not args.get('verbose') else None,
  61. universal_newlines=True,
  62. errors='replace')
  63. for line in proc.stdout:
  64. # state machine here to find structs
  65. m = struct_pattern.match(line)
  66. if m:
  67. if m.group('tag'):
  68. if (name is not None
  69. and decl is not None
  70. and size is not None):
  71. decl = decls.get(decl, '?')
  72. results[(decl, name)] = size
  73. found = (m.group('tag') == 'structure_type')
  74. name = None
  75. decl = None
  76. size = None
  77. elif found and m.group('name'):
  78. name = m.group('name')
  79. elif found and name and m.group('decl'):
  80. decl = int(m.group('decl'))
  81. elif found and name and m.group('size'):
  82. size = int(m.group('size'))
  83. proc.wait()
  84. if proc.returncode != 0:
  85. if not args.get('verbose'):
  86. for line in proc.stderr:
  87. sys.stdout.write(line)
  88. sys.exit(-1)
  89. flat_results = []
  90. for (file, struct), size in results.items():
  91. # map to source files
  92. if args.get('build_dir'):
  93. file = re.sub('%s/*' % re.escape(args['build_dir']), '', file)
  94. # only include structs declared in header files in the current
  95. # directory, ignore internal-only # structs (these are represented
  96. # in other measurements)
  97. if not args.get('everything'):
  98. if not file.endswith('.h'):
  99. continue
  100. # replace .o with .c, different scripts report .o/.c, we need to
  101. # choose one if we want to deduplicate csv files
  102. file = re.sub('\.o$', '.c', file)
  103. flat_results.append((file, struct, size))
  104. return flat_results
  105. def main(**args):
  106. def openio(path, mode='r'):
  107. if path == '-':
  108. if 'r' in mode:
  109. return os.fdopen(os.dup(sys.stdin.fileno()), 'r')
  110. else:
  111. return os.fdopen(os.dup(sys.stdout.fileno()), 'w')
  112. else:
  113. return open(path, mode)
  114. # find sizes
  115. if not args.get('use', None):
  116. # find .o files
  117. paths = []
  118. for path in args['obj_paths']:
  119. if os.path.isdir(path):
  120. path = path + '/*.o'
  121. for path in glob.glob(path):
  122. paths.append(path)
  123. if not paths:
  124. print('no .obj files found in %r?' % args['obj_paths'])
  125. sys.exit(-1)
  126. results = collect(paths, **args)
  127. else:
  128. with openio(args['use']) as f:
  129. r = csv.DictReader(f)
  130. results = [
  131. ( result['file'],
  132. result['name'],
  133. int(result['struct_size']))
  134. for result in r
  135. if result.get('struct_size') not in {None, ''}]
  136. total = 0
  137. for _, _, size in results:
  138. total += size
  139. # find previous results?
  140. if args.get('diff'):
  141. try:
  142. with openio(args['diff']) as f:
  143. r = csv.DictReader(f)
  144. prev_results = [
  145. ( result['file'],
  146. result['name'],
  147. int(result['struct_size']))
  148. for result in r
  149. if result.get('struct_size') not in {None, ''}]
  150. except FileNotFoundError:
  151. prev_results = []
  152. prev_total = 0
  153. for _, _, size in prev_results:
  154. prev_total += size
  155. # write results to CSV
  156. if args.get('output'):
  157. merged_results = co.defaultdict(lambda: {})
  158. other_fields = []
  159. # merge?
  160. if args.get('merge'):
  161. try:
  162. with openio(args['merge']) as f:
  163. r = csv.DictReader(f)
  164. for result in r:
  165. file = result.pop('file', '')
  166. struct = result.pop('name', '')
  167. result.pop('struct_size', None)
  168. merged_results[(file, struct)] = result
  169. other_fields = result.keys()
  170. except FileNotFoundError:
  171. pass
  172. for file, struct, size in results:
  173. merged_results[(file, struct)]['struct_size'] = size
  174. with openio(args['output'], 'w') as f:
  175. w = csv.DictWriter(f, ['file', 'name', *other_fields, 'struct_size'])
  176. w.writeheader()
  177. for (file, struct), result in sorted(merged_results.items()):
  178. w.writerow({'file': file, 'name': struct, **result})
  179. # print results
  180. def dedup_entries(results, by='name'):
  181. entries = co.defaultdict(lambda: 0)
  182. for file, struct, size in results:
  183. entry = (file if by == 'file' else struct)
  184. entries[entry] += size
  185. return entries
  186. def diff_entries(olds, news):
  187. diff = co.defaultdict(lambda: (0, 0, 0, 0))
  188. for name, new in news.items():
  189. diff[name] = (0, new, new, 1.0)
  190. for name, old in olds.items():
  191. _, new, _, _ = diff[name]
  192. diff[name] = (old, new, new-old, (new-old)/old if old else 1.0)
  193. return diff
  194. def sorted_entries(entries):
  195. if args.get('size_sort'):
  196. return sorted(entries, key=lambda x: (-x[1], x))
  197. elif args.get('reverse_size_sort'):
  198. return sorted(entries, key=lambda x: (+x[1], x))
  199. else:
  200. return sorted(entries)
  201. def sorted_diff_entries(entries):
  202. if args.get('size_sort'):
  203. return sorted(entries, key=lambda x: (-x[1][1], x))
  204. elif args.get('reverse_size_sort'):
  205. return sorted(entries, key=lambda x: (+x[1][1], x))
  206. else:
  207. return sorted(entries, key=lambda x: (-x[1][3], x))
  208. def print_header(by=''):
  209. if not args.get('diff'):
  210. print('%-36s %7s' % (by, 'size'))
  211. else:
  212. print('%-36s %7s %7s %7s' % (by, 'old', 'new', 'diff'))
  213. def print_entry(name, size):
  214. print("%-36s %7d" % (name, size))
  215. def print_diff_entry(name, old, new, diff, ratio):
  216. print("%-36s %7s %7s %+7d%s" % (name,
  217. old or "-",
  218. new or "-",
  219. diff,
  220. ' (%+.1f%%)' % (100*ratio) if ratio else ''))
  221. def print_entries(by='name'):
  222. entries = dedup_entries(results, by=by)
  223. if not args.get('diff'):
  224. print_header(by=by)
  225. for name, size in sorted_entries(entries.items()):
  226. print_entry(name, size)
  227. else:
  228. prev_entries = dedup_entries(prev_results, by=by)
  229. diff = diff_entries(prev_entries, entries)
  230. print_header(by='%s (%d added, %d removed)' % (by,
  231. sum(1 for old, _, _, _ in diff.values() if not old),
  232. sum(1 for _, new, _, _ in diff.values() if not new)))
  233. for name, (old, new, diff, ratio) in sorted_diff_entries(
  234. diff.items()):
  235. if ratio or args.get('all'):
  236. print_diff_entry(name, old, new, diff, ratio)
  237. def print_totals():
  238. if not args.get('diff'):
  239. print_entry('TOTAL', total)
  240. else:
  241. ratio = (0.0 if not prev_total and not total
  242. else 1.0 if not prev_total
  243. else (total-prev_total)/prev_total)
  244. print_diff_entry('TOTAL',
  245. prev_total, total,
  246. total-prev_total,
  247. ratio)
  248. if args.get('quiet'):
  249. pass
  250. elif args.get('summary'):
  251. print_header()
  252. print_totals()
  253. elif args.get('files'):
  254. print_entries(by='file')
  255. print_totals()
  256. else:
  257. print_entries(by='name')
  258. print_totals()
  259. if __name__ == "__main__":
  260. import argparse
  261. import sys
  262. parser = argparse.ArgumentParser(
  263. description="Find struct sizes.")
  264. parser.add_argument('obj_paths', nargs='*', default=OBJ_PATHS,
  265. help="Description of where to find *.o files. May be a directory \
  266. or a list of paths. Defaults to %r." % OBJ_PATHS)
  267. parser.add_argument('-v', '--verbose', action='store_true',
  268. help="Output commands that run behind the scenes.")
  269. parser.add_argument('-q', '--quiet', action='store_true',
  270. help="Don't show anything, useful with -o.")
  271. parser.add_argument('-o', '--output',
  272. help="Specify CSV file to store results.")
  273. parser.add_argument('-u', '--use',
  274. help="Don't compile and find struct sizes, instead use this CSV file.")
  275. parser.add_argument('-d', '--diff',
  276. help="Specify CSV file to diff struct size against.")
  277. parser.add_argument('-m', '--merge',
  278. help="Merge with an existing CSV file when writing to output.")
  279. parser.add_argument('-a', '--all', action='store_true',
  280. help="Show all functions, not just the ones that changed.")
  281. parser.add_argument('-A', '--everything', action='store_true',
  282. help="Include builtin and libc specific symbols.")
  283. parser.add_argument('-s', '--size-sort', action='store_true',
  284. help="Sort by size.")
  285. parser.add_argument('-S', '--reverse-size-sort', action='store_true',
  286. help="Sort by size, but backwards.")
  287. parser.add_argument('-F', '--files', action='store_true',
  288. help="Show file-level struct sizes.")
  289. parser.add_argument('-Y', '--summary', action='store_true',
  290. help="Only show the total struct size.")
  291. parser.add_argument('--objdump-tool', default=['objdump'], type=lambda x: x.split(),
  292. help="Path to the objdump tool to use.")
  293. parser.add_argument('--build-dir',
  294. help="Specify the relative build directory. Used to map object files \
  295. to the correct source files.")
  296. sys.exit(main(**vars(parser.parse_args())))