stack.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  1. #!/usr/bin/env python3
  2. #
  3. # Script to find stack usage at the function level. Will detect recursion and
  4. # report as infinite stack usage.
  5. #
  6. # Example:
  7. # ./scripts/stack.py lfs.ci lfs_util.ci -Slimit
  8. #
  9. # Copyright (c) 2022, The littlefs authors.
  10. # SPDX-License-Identifier: BSD-3-Clause
  11. #
  12. import collections as co
  13. import csv
  14. import glob
  15. import itertools as it
  16. import math as m
  17. import os
  18. import re
  19. CI_PATHS = ['*.ci']
  20. # integer fields
  21. class Int(co.namedtuple('Int', 'x')):
  22. __slots__ = ()
  23. def __new__(cls, x=0):
  24. if isinstance(x, Int):
  25. return x
  26. if isinstance(x, str):
  27. try:
  28. x = int(x, 0)
  29. except ValueError:
  30. # also accept +-∞ and +-inf
  31. if re.match('^\s*\+?\s*(?:∞|inf)\s*$', x):
  32. x = m.inf
  33. elif re.match('^\s*-\s*(?:∞|inf)\s*$', x):
  34. x = -m.inf
  35. else:
  36. raise
  37. assert isinstance(x, int) or m.isinf(x), x
  38. return super().__new__(cls, x)
  39. def __str__(self):
  40. if self.x == m.inf:
  41. return '∞'
  42. elif self.x == -m.inf:
  43. return '-∞'
  44. else:
  45. return str(self.x)
  46. def __int__(self):
  47. assert not m.isinf(self.x)
  48. return self.x
  49. def __float__(self):
  50. return float(self.x)
  51. none = '%7s' % '-'
  52. def table(self):
  53. return '%7s' % (self,)
  54. diff_none = '%7s' % '-'
  55. diff_table = table
  56. def diff_diff(self, other):
  57. new = self.x if self else 0
  58. old = other.x if other else 0
  59. diff = new - old
  60. if diff == +m.inf:
  61. return '%7s' % '+∞'
  62. elif diff == -m.inf:
  63. return '%7s' % '-∞'
  64. else:
  65. return '%+7d' % diff
  66. def ratio(self, other):
  67. new = self.x if self else 0
  68. old = other.x if other else 0
  69. if m.isinf(new) and m.isinf(old):
  70. return 0.0
  71. elif m.isinf(new):
  72. return +m.inf
  73. elif m.isinf(old):
  74. return -m.inf
  75. elif not old and not new:
  76. return 0.0
  77. elif not old:
  78. return 1.0
  79. else:
  80. return (new-old) / old
  81. def __add__(self, other):
  82. return self.__class__(self.x + other.x)
  83. def __sub__(self, other):
  84. return self.__class__(self.x - other.x)
  85. def __mul__(self, other):
  86. return self.__class__(self.x * other.x)
  87. # size results
  88. class StackResult(co.namedtuple('StackResult', [
  89. 'file', 'function', 'frame', 'limit', 'calls'])):
  90. _by = ['file', 'function']
  91. _fields = ['frame', 'limit']
  92. _types = {'frame': Int, 'limit': Int}
  93. __slots__ = ()
  94. def __new__(cls, file='', function='',
  95. frame=0, limit=0, calls=set()):
  96. return super().__new__(cls, file, function,
  97. Int(frame), Int(limit),
  98. calls)
  99. def __add__(self, other):
  100. return StackResult(self.file, self.function,
  101. self.frame + other.frame,
  102. max(self.limit, other.limit),
  103. self.calls | other.calls)
  104. def openio(path, mode='r'):
  105. if path == '-':
  106. if mode == 'r':
  107. return os.fdopen(os.dup(sys.stdin.fileno()), 'r')
  108. else:
  109. return os.fdopen(os.dup(sys.stdout.fileno()), 'w')
  110. else:
  111. return open(path, mode)
  112. def collect(paths, *,
  113. sources=None,
  114. everything=False,
  115. **args):
  116. # parse the vcg format
  117. k_pattern = re.compile('([a-z]+)\s*:', re.DOTALL)
  118. v_pattern = re.compile('(?:"(.*?)"|([a-z]+))', re.DOTALL)
  119. def parse_vcg(rest):
  120. def parse_vcg(rest):
  121. node = []
  122. while True:
  123. rest = rest.lstrip()
  124. m_ = k_pattern.match(rest)
  125. if not m_:
  126. return (node, rest)
  127. k, rest = m_.group(1), rest[m_.end(0):]
  128. rest = rest.lstrip()
  129. if rest.startswith('{'):
  130. v, rest = parse_vcg(rest[1:])
  131. assert rest[0] == '}', "unexpected %r" % rest[0:1]
  132. rest = rest[1:]
  133. node.append((k, v))
  134. else:
  135. m_ = v_pattern.match(rest)
  136. assert m_, "unexpected %r" % rest[0:1]
  137. v, rest = m_.group(1) or m_.group(2), rest[m_.end(0):]
  138. node.append((k, v))
  139. node, rest = parse_vcg(rest)
  140. assert rest == '', "unexpected %r" % rest[0:1]
  141. return node
  142. # collect into functions
  143. callgraph = co.defaultdict(lambda: (None, None, 0, set()))
  144. f_pattern = re.compile(
  145. r'([^\\]*)\\n([^:]*)[^\\]*\\n([0-9]+) bytes \((.*)\)')
  146. for path in paths:
  147. with open(path) as f:
  148. vcg = parse_vcg(f.read())
  149. for k, graph in vcg:
  150. if k != 'graph':
  151. continue
  152. for k, info in graph:
  153. if k == 'node':
  154. info = dict(info)
  155. m_ = f_pattern.match(info['label'])
  156. if m_:
  157. function, file, size, type = m_.groups()
  158. if (not args.get('quiet')
  159. and 'static' not in type
  160. and 'bounded' not in type):
  161. print("warning: "
  162. "found non-static stack for %s (%s, %s)" % (
  163. function, type, size))
  164. _, _, _, targets = callgraph[info['title']]
  165. callgraph[info['title']] = (
  166. file, function, int(size), targets)
  167. elif k == 'edge':
  168. info = dict(info)
  169. _, _, _, targets = callgraph[info['sourcename']]
  170. targets.add(info['targetname'])
  171. else:
  172. continue
  173. callgraph_ = co.defaultdict(lambda: (None, None, 0, set()))
  174. for source, (s_file, s_function, frame, targets) in callgraph.items():
  175. # discard internal functions
  176. if not everything and s_function.startswith('__'):
  177. continue
  178. # ignore filtered sources
  179. if sources is not None:
  180. if not any(
  181. os.path.abspath(s_file) == os.path.abspath(s)
  182. for s in sources):
  183. continue
  184. else:
  185. # default to only cwd
  186. if not everything and not os.path.commonpath([
  187. os.getcwd(),
  188. os.path.abspath(s_file)]) == os.getcwd():
  189. continue
  190. # smiplify path
  191. if os.path.commonpath([
  192. os.getcwd(),
  193. os.path.abspath(s_file)]) == os.getcwd():
  194. s_file = os.path.relpath(s_file)
  195. else:
  196. s_file = os.path.abspath(s_file)
  197. callgraph_[source] = (s_file, s_function, frame, targets)
  198. callgraph = callgraph_
  199. if not everything:
  200. callgraph_ = co.defaultdict(lambda: (None, None, 0, set()))
  201. for source, (s_file, s_function, frame, targets) in callgraph.items():
  202. # discard filtered sources
  203. if sources is not None and not any(
  204. os.path.abspath(s_file) == os.path.abspath(s)
  205. for s in sources):
  206. continue
  207. # discard internal functions
  208. if s_function.startswith('__'):
  209. continue
  210. callgraph_[source] = (s_file, s_function, frame, targets)
  211. callgraph = callgraph_
  212. # find maximum stack size recursively, this requires also detecting cycles
  213. # (in case of recursion)
  214. def find_limit(source, seen=None):
  215. seen = seen or set()
  216. if source not in callgraph:
  217. return 0
  218. _, _, frame, targets = callgraph[source]
  219. limit = 0
  220. for target in targets:
  221. if target in seen:
  222. # found a cycle
  223. return m.inf
  224. limit_ = find_limit(target, seen | {target})
  225. limit = max(limit, limit_)
  226. return frame + limit
  227. def find_calls(targets):
  228. calls = set()
  229. for target in targets:
  230. if target in callgraph:
  231. t_file, t_function, _, _ = callgraph[target]
  232. calls.add((t_file, t_function))
  233. return calls
  234. # build results
  235. results = []
  236. for source, (s_file, s_function, frame, targets) in callgraph.items():
  237. limit = find_limit(source)
  238. calls = find_calls(targets)
  239. results.append(StackResult(s_file, s_function, frame, limit, calls))
  240. return results
  241. def fold(Result, results, *,
  242. by=None,
  243. defines=None,
  244. **_):
  245. if by is None:
  246. by = Result._by
  247. for k in it.chain(by or [], (k for k, _ in defines or [])):
  248. if k not in Result._by and k not in Result._fields:
  249. print("error: could not find field %r?" % k)
  250. sys.exit(-1)
  251. # filter by matching defines
  252. if defines is not None:
  253. results_ = []
  254. for r in results:
  255. if all(getattr(r, k) in vs for k, vs in defines):
  256. results_.append(r)
  257. results = results_
  258. # organize results into conflicts
  259. folding = co.OrderedDict()
  260. for r in results:
  261. name = tuple(getattr(r, k) for k in by)
  262. if name not in folding:
  263. folding[name] = []
  264. folding[name].append(r)
  265. # merge conflicts
  266. folded = []
  267. for name, rs in folding.items():
  268. folded.append(sum(rs[1:], start=rs[0]))
  269. return folded
  270. def table(Result, results, diff_results=None, *,
  271. by=None,
  272. fields=None,
  273. sort=None,
  274. summary=False,
  275. all=False,
  276. percent=False,
  277. tree=False,
  278. depth=1,
  279. **_):
  280. all_, all = all, __builtins__.all
  281. if by is None:
  282. by = Result._by
  283. if fields is None:
  284. fields = Result._fields
  285. types = Result._types
  286. # fold again
  287. results = fold(Result, results, by=by)
  288. if diff_results is not None:
  289. diff_results = fold(Result, diff_results, by=by)
  290. # organize by name
  291. table = {
  292. ','.join(str(getattr(r, k) or '') for k in by): r
  293. for r in results}
  294. diff_table = {
  295. ','.join(str(getattr(r, k) or '') for k in by): r
  296. for r in diff_results or []}
  297. names = list(table.keys() | diff_table.keys())
  298. # sort again, now with diff info, note that python's sort is stable
  299. names.sort()
  300. if diff_results is not None:
  301. names.sort(key=lambda n: tuple(
  302. types[k].ratio(
  303. getattr(table.get(n), k, None),
  304. getattr(diff_table.get(n), k, None))
  305. for k in fields),
  306. reverse=True)
  307. if sort:
  308. for k, reverse in reversed(sort):
  309. names.sort(key=lambda n: (getattr(table[n], k),)
  310. if getattr(table.get(n), k, None) is not None else (),
  311. reverse=reverse ^ (not k or k in Result._fields))
  312. # build up our lines
  313. lines = []
  314. # header
  315. line = []
  316. line.append('%s%s' % (
  317. ','.join(by),
  318. ' (%d added, %d removed)' % (
  319. sum(1 for n in table if n not in diff_table),
  320. sum(1 for n in diff_table if n not in table))
  321. if diff_results is not None and not percent else '')
  322. if not summary else '')
  323. if diff_results is None:
  324. for k in fields:
  325. line.append(k)
  326. elif percent:
  327. for k in fields:
  328. line.append(k)
  329. else:
  330. for k in fields:
  331. line.append('o'+k)
  332. for k in fields:
  333. line.append('n'+k)
  334. for k in fields:
  335. line.append('d'+k)
  336. line.append('')
  337. lines.append(line)
  338. # entries
  339. if not summary:
  340. for name in names:
  341. r = table.get(name)
  342. if diff_results is not None:
  343. diff_r = diff_table.get(name)
  344. ratios = [
  345. types[k].ratio(
  346. getattr(r, k, None),
  347. getattr(diff_r, k, None))
  348. for k in fields]
  349. if not any(ratios) and not all_:
  350. continue
  351. line = []
  352. line.append(name)
  353. if diff_results is None:
  354. for k in fields:
  355. line.append(getattr(r, k).table()
  356. if getattr(r, k, None) is not None
  357. else types[k].none)
  358. elif percent:
  359. for k in fields:
  360. line.append(getattr(r, k).diff_table()
  361. if getattr(r, k, None) is not None
  362. else types[k].diff_none)
  363. else:
  364. for k in fields:
  365. line.append(getattr(diff_r, k).diff_table()
  366. if getattr(diff_r, k, None) is not None
  367. else types[k].diff_none)
  368. for k in fields:
  369. line.append(getattr(r, k).diff_table()
  370. if getattr(r, k, None) is not None
  371. else types[k].diff_none)
  372. for k in fields:
  373. line.append(types[k].diff_diff(
  374. getattr(r, k, None),
  375. getattr(diff_r, k, None)))
  376. if diff_results is None:
  377. line.append('')
  378. elif percent:
  379. line.append(' (%s)' % ', '.join(
  380. '+∞%' if t == +m.inf
  381. else '-∞%' if t == -m.inf
  382. else '%+.1f%%' % (100*t)
  383. for t in ratios))
  384. else:
  385. line.append(' (%s)' % ', '.join(
  386. '+∞%' if t == +m.inf
  387. else '-∞%' if t == -m.inf
  388. else '%+.1f%%' % (100*t)
  389. for t in ratios
  390. if t)
  391. if any(ratios) else '')
  392. lines.append(line)
  393. # total
  394. r = next(iter(fold(Result, results, by=[])), None)
  395. if diff_results is not None:
  396. diff_r = next(iter(fold(Result, diff_results, by=[])), None)
  397. ratios = [
  398. types[k].ratio(
  399. getattr(r, k, None),
  400. getattr(diff_r, k, None))
  401. for k in fields]
  402. line = []
  403. line.append('TOTAL')
  404. if diff_results is None:
  405. for k in fields:
  406. line.append(getattr(r, k).table()
  407. if getattr(r, k, None) is not None
  408. else types[k].none)
  409. elif percent:
  410. for k in fields:
  411. line.append(getattr(r, k).diff_table()
  412. if getattr(r, k, None) is not None
  413. else types[k].diff_none)
  414. else:
  415. for k in fields:
  416. line.append(getattr(diff_r, k).diff_table()
  417. if getattr(diff_r, k, None) is not None
  418. else types[k].diff_none)
  419. for k in fields:
  420. line.append(getattr(r, k).diff_table()
  421. if getattr(r, k, None) is not None
  422. else types[k].diff_none)
  423. for k in fields:
  424. line.append(types[k].diff_diff(
  425. getattr(r, k, None),
  426. getattr(diff_r, k, None)))
  427. if diff_results is None:
  428. line.append('')
  429. elif percent:
  430. line.append(' (%s)' % ', '.join(
  431. '+∞%' if t == +m.inf
  432. else '-∞%' if t == -m.inf
  433. else '%+.1f%%' % (100*t)
  434. for t in ratios))
  435. else:
  436. line.append(' (%s)' % ', '.join(
  437. '+∞%' if t == +m.inf
  438. else '-∞%' if t == -m.inf
  439. else '%+.1f%%' % (100*t)
  440. for t in ratios
  441. if t)
  442. if any(ratios) else '')
  443. lines.append(line)
  444. # find the best widths, note that column 0 contains the names and column -1
  445. # the ratios, so those are handled a bit differently
  446. widths = [
  447. ((max(it.chain([w], (len(l[i]) for l in lines)))+1+4-1)//4)*4-1
  448. for w, i in zip(
  449. it.chain([23], it.repeat(7)),
  450. range(len(lines[0])-1))]
  451. # adjust the name width based on the expected call depth, though
  452. # note this doesn't really work with unbounded recursion
  453. if not summary:
  454. if not m.isinf(depth):
  455. widths[0] += 4*(depth-1)
  456. # print our table with optional call info
  457. #
  458. # note we try to adjust our name width based on expected call depth, but
  459. # this doesn't work if there's unbounded recursion
  460. if not tree:
  461. print('%-*s %s%s' % (
  462. widths[0], lines[0][0],
  463. ' '.join('%*s' % (w, x)
  464. for w, x, in zip(widths[1:], lines[0][1:-1])),
  465. lines[0][-1]))
  466. # print the tree recursively
  467. if not summary:
  468. line_table = {n: l for n, l in zip(names, lines[1:-1])}
  469. def recurse(names_, depth_, prefixes=('', '', '', '')):
  470. for i, name in enumerate(names_):
  471. if name not in line_table:
  472. continue
  473. line = line_table[name]
  474. is_last = (i == len(names_)-1)
  475. print('%s%-*s ' % (
  476. prefixes[0+is_last],
  477. widths[0] - (
  478. len(prefixes[0+is_last])
  479. if not m.isinf(depth) else 0),
  480. line[0]),
  481. end='')
  482. if not tree:
  483. print(' %s%s' % (
  484. ' '.join('%*s' % (w, x)
  485. for w, x, in zip(widths[1:], line[1:-1])),
  486. line[-1]),
  487. end='')
  488. print()
  489. # recurse?
  490. if name in table and depth_ > 0:
  491. calls = {
  492. ','.join(str(getattr(Result(*c), k) or '') for k in by)
  493. for c in table[name].calls}
  494. recurse(
  495. # note we're maintaining sort order
  496. [n for n in names if n in calls],
  497. depth_-1,
  498. (prefixes[2+is_last] + "|-> ",
  499. prefixes[2+is_last] + "'-> ",
  500. prefixes[2+is_last] + "| ",
  501. prefixes[2+is_last] + " "))
  502. recurse(names, depth-1)
  503. if not tree:
  504. print('%-*s %s%s' % (
  505. widths[0], lines[-1][0],
  506. ' '.join('%*s' % (w, x)
  507. for w, x, in zip(widths[1:], lines[-1][1:-1])),
  508. lines[-1][-1]))
  509. def main(ci_paths,
  510. by=None,
  511. fields=None,
  512. defines=None,
  513. sort=None,
  514. **args):
  515. # it doesn't really make sense to not have a depth with tree,
  516. # so assume depth=inf if tree by default
  517. if args.get('depth') is None:
  518. args['depth'] = m.inf if args['tree'] else 1
  519. elif args.get('depth') == 0:
  520. args['depth'] = m.inf
  521. # find sizes
  522. if not args.get('use', None):
  523. # find .ci files
  524. paths = []
  525. for path in ci_paths:
  526. if os.path.isdir(path):
  527. path = path + '/*.ci'
  528. for path in glob.glob(path):
  529. paths.append(path)
  530. if not paths:
  531. print("error: no .ci files found in %r?" % ci_paths)
  532. sys.exit(-1)
  533. results = collect(paths, **args)
  534. else:
  535. results = []
  536. with openio(args['use']) as f:
  537. reader = csv.DictReader(f, restval='')
  538. for r in reader:
  539. try:
  540. results.append(StackResult(
  541. **{k: r[k] for k in StackResult._by
  542. if k in r and r[k].strip()},
  543. **{k: r['stack_'+k] for k in StackResult._fields
  544. if 'stack_'+k in r and r['stack_'+k].strip()}))
  545. except TypeError:
  546. pass
  547. # fold
  548. results = fold(StackResult, results, by=by, defines=defines)
  549. # sort, note that python's sort is stable
  550. results.sort()
  551. if sort:
  552. for k, reverse in reversed(sort):
  553. results.sort(key=lambda r: (getattr(r, k),)
  554. if getattr(r, k) is not None else (),
  555. reverse=reverse ^ (not k or k in StackResult._fields))
  556. # write results to CSV
  557. if args.get('output'):
  558. with openio(args['output'], 'w') as f:
  559. writer = csv.DictWriter(f,
  560. (by if by is not None else StackResult._by)
  561. + ['stack_'+k for k in StackResult._fields])
  562. writer.writeheader()
  563. for r in results:
  564. writer.writerow(
  565. {k: getattr(r, k)
  566. for k in (by if by is not None else StackResult._by)}
  567. | {'stack_'+k: getattr(r, k)
  568. for k in StackResult._fields})
  569. # find previous results?
  570. if args.get('diff'):
  571. diff_results = []
  572. try:
  573. with openio(args['diff']) as f:
  574. reader = csv.DictReader(f, restval='')
  575. for r in reader:
  576. try:
  577. diff_results.append(StackResult(
  578. **{k: r[k] for k in StackResult._by
  579. if k in r and r[k].strip()},
  580. **{k: r['stack_'+k] for k in StackResult._fields
  581. if 'stack_'+k in r and r['stack_'+k].strip()}))
  582. except TypeError:
  583. raise
  584. except FileNotFoundError:
  585. pass
  586. # fold
  587. diff_results = fold(StackResult, diff_results, by=by, defines=defines)
  588. # print table
  589. if not args.get('quiet'):
  590. table(StackResult, results,
  591. diff_results if args.get('diff') else None,
  592. by=by if by is not None else ['function'],
  593. fields=fields,
  594. sort=sort,
  595. **args)
  596. # error on recursion
  597. if args.get('error_on_recursion') and any(
  598. m.isinf(float(r.limit)) for r in results):
  599. sys.exit(2)
  600. if __name__ == "__main__":
  601. import argparse
  602. import sys
  603. parser = argparse.ArgumentParser(
  604. description="Find stack usage at the function level.",
  605. allow_abbrev=False)
  606. parser.add_argument(
  607. 'ci_paths',
  608. nargs='*',
  609. default=CI_PATHS,
  610. help="Description of where to find *.ci files. May be a directory "
  611. "or a list of paths. Defaults to %r." % CI_PATHS)
  612. parser.add_argument(
  613. '-v', '--verbose',
  614. action='store_true',
  615. help="Output commands that run behind the scenes.")
  616. parser.add_argument(
  617. '-q', '--quiet',
  618. action='store_true',
  619. help="Don't show anything, useful with -o.")
  620. parser.add_argument(
  621. '-o', '--output',
  622. help="Specify CSV file to store results.")
  623. parser.add_argument(
  624. '-u', '--use',
  625. help="Don't parse anything, use this CSV file.")
  626. parser.add_argument(
  627. '-d', '--diff',
  628. help="Specify CSV file to diff against.")
  629. parser.add_argument(
  630. '-a', '--all',
  631. action='store_true',
  632. help="Show all, not just the ones that changed.")
  633. parser.add_argument(
  634. '-p', '--percent',
  635. action='store_true',
  636. help="Only show percentage change, not a full diff.")
  637. parser.add_argument(
  638. '-b', '--by',
  639. action='append',
  640. choices=StackResult._by,
  641. help="Group by this field.")
  642. parser.add_argument(
  643. '-f', '--field',
  644. dest='fields',
  645. action='append',
  646. choices=StackResult._fields,
  647. help="Show this field.")
  648. parser.add_argument(
  649. '-D', '--define',
  650. dest='defines',
  651. action='append',
  652. type=lambda x: (lambda k,v: (k, set(v.split(','))))(*x.split('=', 1)),
  653. help="Only include results where this field is this value.")
  654. class AppendSort(argparse.Action):
  655. def __call__(self, parser, namespace, value, option):
  656. if namespace.sort is None:
  657. namespace.sort = []
  658. namespace.sort.append((value, True if option == '-S' else False))
  659. parser.add_argument(
  660. '-s', '--sort',
  661. action=AppendSort,
  662. help="Sort by this fields.")
  663. parser.add_argument(
  664. '-S', '--reverse-sort',
  665. action=AppendSort,
  666. help="Sort by this fields, but backwards.")
  667. parser.add_argument(
  668. '-Y', '--summary',
  669. action='store_true',
  670. help="Only show the total.")
  671. parser.add_argument(
  672. '-F', '--source',
  673. dest='sources',
  674. action='append',
  675. help="Only consider definitions in this file. Defaults to anything "
  676. "in the current directory.")
  677. parser.add_argument(
  678. '--everything',
  679. action='store_true',
  680. help="Include builtin and libc specific symbols.")
  681. parser.add_argument(
  682. '--tree',
  683. action='store_true',
  684. help="Only show the function call tree.")
  685. parser.add_argument(
  686. '-Z', '--depth',
  687. nargs='?',
  688. type=lambda x: int(x, 0),
  689. const=0,
  690. help="Depth of function calls to show. 0 shows all calls but may not "
  691. "terminate!")
  692. parser.add_argument(
  693. '-e', '--error-on-recursion',
  694. action='store_true',
  695. help="Error if any functions are recursive.")
  696. sys.exit(main(**{k: v
  697. for k, v in vars(parser.parse_intermixed_args()).items()
  698. if v is not None}))