structs.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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 openio(path, mode='r'):
  15. if path == '-':
  16. if 'r' in mode:
  17. return os.fdopen(os.dup(sys.stdin.fileno()), 'r')
  18. else:
  19. return os.fdopen(os.dup(sys.stdout.fileno()), 'w')
  20. else:
  21. return open(path, mode)
  22. def collect(paths, **args):
  23. decl_pattern = re.compile(
  24. '^\s+(?P<no>[0-9]+)'
  25. '\s+(?P<dir>[0-9]+)'
  26. '\s+.*'
  27. '\s+(?P<file>[^\s]+)$')
  28. struct_pattern = re.compile(
  29. '^(?:.*DW_TAG_(?P<tag>[a-z_]+).*'
  30. '|^.*DW_AT_name.*:\s*(?P<name>[^:\s]+)\s*'
  31. '|^.*DW_AT_decl_file.*:\s*(?P<decl>[0-9]+)\s*'
  32. '|^.*DW_AT_byte_size.*:\s*(?P<size>[0-9]+)\s*)$')
  33. results = co.defaultdict(lambda: 0)
  34. for path in paths:
  35. # find decl, we want to filter by structs in .h files
  36. decls = {}
  37. # note objdump-tool may contain extra args
  38. cmd = args['objdump_tool'] + ['--dwarf=rawline', path]
  39. if args.get('verbose'):
  40. print(' '.join(shlex.quote(c) for c in cmd))
  41. proc = sp.Popen(cmd,
  42. stdout=sp.PIPE,
  43. stderr=sp.PIPE if not args.get('verbose') else None,
  44. universal_newlines=True,
  45. errors='replace')
  46. for line in proc.stdout:
  47. # find file numbers
  48. m = decl_pattern.match(line)
  49. if m:
  50. decls[int(m.group('no'))] = m.group('file')
  51. proc.wait()
  52. if proc.returncode != 0:
  53. if not args.get('verbose'):
  54. for line in proc.stderr:
  55. sys.stdout.write(line)
  56. sys.exit(-1)
  57. # collect structs as we parse dwarf info
  58. found = False
  59. name = None
  60. decl = None
  61. size = None
  62. # note objdump-tool may contain extra args
  63. cmd = args['objdump_tool'] + ['--dwarf=info', path]
  64. if args.get('verbose'):
  65. print(' '.join(shlex.quote(c) for c in cmd))
  66. proc = sp.Popen(cmd,
  67. stdout=sp.PIPE,
  68. stderr=sp.PIPE if not args.get('verbose') else None,
  69. universal_newlines=True,
  70. errors='replace')
  71. for line in proc.stdout:
  72. # state machine here to find structs
  73. m = struct_pattern.match(line)
  74. if m:
  75. if m.group('tag'):
  76. if (name is not None
  77. and decl is not None
  78. and size is not None):
  79. decl = decls.get(decl, '?')
  80. results[(decl, name)] = size
  81. found = (m.group('tag') == 'structure_type')
  82. name = None
  83. decl = None
  84. size = None
  85. elif found and m.group('name'):
  86. name = m.group('name')
  87. elif found and name and m.group('decl'):
  88. decl = int(m.group('decl'))
  89. elif found and name and m.group('size'):
  90. size = int(m.group('size'))
  91. proc.wait()
  92. if proc.returncode != 0:
  93. if not args.get('verbose'):
  94. for line in proc.stderr:
  95. sys.stdout.write(line)
  96. sys.exit(-1)
  97. flat_results = []
  98. for (file, struct), size in results.items():
  99. # map to source files
  100. if args.get('build_dir'):
  101. file = re.sub('%s/*' % re.escape(args['build_dir']), '', file)
  102. # only include structs declared in header files in the current
  103. # directory, ignore internal-only # structs (these are represented
  104. # in other measurements)
  105. if not args.get('everything'):
  106. if not file.endswith('.h'):
  107. continue
  108. # replace .o with .c, different scripts report .o/.c, we need to
  109. # choose one if we want to deduplicate csv files
  110. file = re.sub('\.o$', '.c', file)
  111. flat_results.append((file, struct, size))
  112. return flat_results
  113. def main(**args):
  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(**{k: v
  297. for k, v in vars(parser.parse_args()).items()
  298. if v is not None}))