stackcollapse.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  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. import os
  22. import sys
  23. from collections import defaultdict
  24. from optparse import OptionParser, make_option
  25. sys.path.append(os.environ['PERF_EXEC_PATH'] + \
  26. '/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
  27. from perf_trace_context import *
  28. from Core import *
  29. from EventClass import *
  30. # command line parsing
  31. option_list = [
  32. # formatting options for the bottom entry of the stack
  33. make_option("--include-tid", dest="include_tid",
  34. action="store_true", default=False,
  35. help="include thread id in stack"),
  36. make_option("--include-pid", dest="include_pid",
  37. action="store_true", default=False,
  38. help="include process id in stack"),
  39. make_option("--no-comm", dest="include_comm",
  40. action="store_false", default=True,
  41. help="do not separate stacks according to comm"),
  42. make_option("--tidy-java", dest="tidy_java",
  43. action="store_true", default=False,
  44. help="beautify Java signatures"),
  45. make_option("--kernel", dest="annotate_kernel",
  46. action="store_true", default=False,
  47. help="annotate kernel functions with _[k]")
  48. ]
  49. parser = OptionParser(option_list=option_list)
  50. (opts, args) = parser.parse_args()
  51. if len(args) != 0:
  52. parser.error("unexpected command line argument")
  53. if opts.include_tid and not opts.include_comm:
  54. parser.error("requesting tid but not comm is invalid")
  55. if opts.include_pid and not opts.include_comm:
  56. parser.error("requesting pid but not comm is invalid")
  57. # event handlers
  58. lines = defaultdict(lambda: 0)
  59. def process_event(param_dict):
  60. def tidy_function_name(sym, dso):
  61. if sym is None:
  62. sym = '[unknown]'
  63. sym = sym.replace(';', ':')
  64. if opts.tidy_java:
  65. # the original stackcollapse-perf.pl script gives the
  66. # example of converting this:
  67. # Lorg/mozilla/javascript/MemberBox;.<init>(Ljava/lang/reflect/Method;)V
  68. # to this:
  69. # org/mozilla/javascript/MemberBox:.init
  70. sym = sym.replace('<', '')
  71. sym = sym.replace('>', '')
  72. if sym[0] == 'L' and sym.find('/'):
  73. sym = sym[1:]
  74. try:
  75. sym = sym[:sym.index('(')]
  76. except ValueError:
  77. pass
  78. if opts.annotate_kernel and dso == '[kernel.kallsyms]':
  79. return sym + '_[k]'
  80. else:
  81. return sym
  82. stack = list()
  83. if 'callchain' in param_dict:
  84. for entry in param_dict['callchain']:
  85. entry.setdefault('sym', dict())
  86. entry['sym'].setdefault('name', None)
  87. entry.setdefault('dso', None)
  88. stack.append(tidy_function_name(entry['sym']['name'],
  89. entry['dso']))
  90. else:
  91. param_dict.setdefault('symbol', None)
  92. param_dict.setdefault('dso', None)
  93. stack.append(tidy_function_name(param_dict['symbol'],
  94. param_dict['dso']))
  95. if opts.include_comm:
  96. comm = param_dict["comm"].replace(' ', '_')
  97. sep = "-"
  98. if opts.include_pid:
  99. comm = comm + sep + str(param_dict['sample']['pid'])
  100. sep = "/"
  101. if opts.include_tid:
  102. comm = comm + sep + str(param_dict['sample']['tid'])
  103. stack.append(comm)
  104. stack_string = ';'.join(reversed(stack))
  105. lines[stack_string] = lines[stack_string] + 1
  106. def trace_end():
  107. list = lines.keys()
  108. list.sort()
  109. for stack in list:
  110. print "%s %d" % (stack, lines[stack])