stackcollapse.py 4.3 KB

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