stackcollapse.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. # stackcollapse.py - format perf samples with one line per distinct call stack
  2. # SPDX-License-Identifier: GPL-2.0
  3. #
  4. # This script's output has two space-separated fields. The first is a semicolon
  5. # separated stack including the program name (from the "comm" field) and the
  6. # function names from the call stack. The second is a count:
  7. #
  8. # swapper;start_kernel;rest_init;cpu_idle;default_idle;native_safe_halt 2
  9. #
  10. # The file is sorted according to the first field.
  11. #
  12. # Input may be created and processed using:
  13. #
  14. # perf record -a -g -F 99 sleep 60
  15. # perf script report stackcollapse > out.stacks-folded
  16. #
  17. # (perf script record stackcollapse works too).
  18. #
  19. # Written by Paolo Bonzini <pbonzini@redhat.com>
  20. # Based on Brendan Gregg's stackcollapse-perf.pl script.
  21. from __future__ import print_function
  22. import os
  23. import sys
  24. from collections import defaultdict
  25. from optparse import OptionParser, make_option
  26. sys.path.append(os.environ['PERF_EXEC_PATH'] + \
  27. '/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
  28. from perf_trace_context import *
  29. from Core import *
  30. from EventClass import *
  31. # command line parsing
  32. option_list = [
  33. # formatting options for the bottom entry of the stack
  34. make_option("--include-tid", dest="include_tid",
  35. action="store_true", default=False,
  36. help="include thread id in stack"),
  37. make_option("--include-pid", dest="include_pid",
  38. action="store_true", default=False,
  39. help="include process id in stack"),
  40. make_option("--no-comm", dest="include_comm",
  41. action="store_false", default=True,
  42. help="do not separate stacks according to comm"),
  43. make_option("--tidy-java", dest="tidy_java",
  44. action="store_true", default=False,
  45. help="beautify Java signatures"),
  46. make_option("--kernel", dest="annotate_kernel",
  47. action="store_true", default=False,
  48. help="annotate kernel functions with _[k]")
  49. ]
  50. parser = OptionParser(option_list=option_list)
  51. (opts, args) = parser.parse_args()
  52. if len(args) != 0:
  53. parser.error("unexpected command line argument")
  54. if opts.include_tid and not opts.include_comm:
  55. parser.error("requesting tid but not comm is invalid")
  56. if opts.include_pid and not opts.include_comm:
  57. parser.error("requesting pid but not comm is invalid")
  58. # event handlers
  59. lines = defaultdict(lambda: 0)
  60. def process_event(param_dict):
  61. def tidy_function_name(sym, dso):
  62. if sym is None:
  63. sym = '[unknown]'
  64. sym = sym.replace(';', ':')
  65. if opts.tidy_java:
  66. # the original stackcollapse-perf.pl script gives the
  67. # example of converting this:
  68. # Lorg/mozilla/javascript/MemberBox;.<init>(Ljava/lang/reflect/Method;)V
  69. # to this:
  70. # org/mozilla/javascript/MemberBox:.init
  71. sym = sym.replace('<', '')
  72. sym = sym.replace('>', '')
  73. if sym[0] == 'L' and sym.find('/'):
  74. sym = sym[1:]
  75. try:
  76. sym = sym[:sym.index('(')]
  77. except ValueError:
  78. pass
  79. if opts.annotate_kernel and dso == '[kernel.kallsyms]':
  80. return sym + '_[k]'
  81. else:
  82. return sym
  83. stack = list()
  84. if 'callchain' in param_dict:
  85. for entry in param_dict['callchain']:
  86. entry.setdefault('sym', dict())
  87. entry['sym'].setdefault('name', None)
  88. entry.setdefault('dso', None)
  89. stack.append(tidy_function_name(entry['sym']['name'],
  90. entry['dso']))
  91. else:
  92. param_dict.setdefault('symbol', None)
  93. param_dict.setdefault('dso', None)
  94. stack.append(tidy_function_name(param_dict['symbol'],
  95. param_dict['dso']))
  96. if opts.include_comm:
  97. comm = param_dict["comm"].replace(' ', '_')
  98. sep = "-"
  99. if opts.include_pid:
  100. comm = comm + sep + str(param_dict['sample']['pid'])
  101. sep = "/"
  102. if opts.include_tid:
  103. comm = comm + sep + str(param_dict['sample']['tid'])
  104. stack.append(comm)
  105. stack_string = ';'.join(reversed(stack))
  106. lines[stack_string] = lines[stack_string] + 1
  107. def trace_end():
  108. list = sorted(lines)
  109. for stack in list:
  110. print("%s %d" % (stack, lines[stack]))