arm-cs-trace-disasm.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. # SPDX-License-Identifier: GPL-2.0
  2. # arm-cs-trace-disasm.py: ARM CoreSight Trace Dump With Disassember
  3. #
  4. # Author: Tor Jeremiassen <tor@ti.com>
  5. # Mathieu Poirier <mathieu.poirier@linaro.org>
  6. # Leo Yan <leo.yan@linaro.org>
  7. # Al Grant <Al.Grant@arm.com>
  8. from __future__ import print_function
  9. import os
  10. from os import path
  11. import re
  12. from subprocess import *
  13. from optparse import OptionParser, make_option
  14. from perf_trace_context import perf_set_itrace_options, \
  15. perf_sample_insn, perf_sample_srccode
  16. # Below are some example commands for using this script.
  17. #
  18. # Output disassembly with objdump:
  19. # perf script -s scripts/python/arm-cs-trace-disasm.py \
  20. # -- -d objdump -k path/to/vmlinux
  21. # Output disassembly with llvm-objdump:
  22. # perf script -s scripts/python/arm-cs-trace-disasm.py \
  23. # -- -d llvm-objdump-11 -k path/to/vmlinux
  24. # Output only source line and symbols:
  25. # perf script -s scripts/python/arm-cs-trace-disasm.py
  26. # Command line parsing.
  27. option_list = [
  28. # formatting options for the bottom entry of the stack
  29. make_option("-k", "--vmlinux", dest="vmlinux_name",
  30. help="Set path to vmlinux file"),
  31. make_option("-d", "--objdump", dest="objdump_name",
  32. help="Set path to objdump executable file"),
  33. make_option("-v", "--verbose", dest="verbose",
  34. action="store_true", default=False,
  35. help="Enable debugging log")
  36. ]
  37. parser = OptionParser(option_list=option_list)
  38. (options, args) = parser.parse_args()
  39. # Initialize global dicts and regular expression
  40. disasm_cache = dict()
  41. cpu_data = dict()
  42. disasm_re = re.compile(r"^\s*([0-9a-fA-F]+):")
  43. disasm_func_re = re.compile(r"^\s*([0-9a-fA-F]+)\s.*:")
  44. cache_size = 64*1024
  45. glb_source_file_name = None
  46. glb_line_number = None
  47. glb_dso = None
  48. def get_optional(perf_dict, field):
  49. if field in perf_dict:
  50. return perf_dict[field]
  51. return "[unknown]"
  52. def get_offset(perf_dict, field):
  53. if field in perf_dict:
  54. return "+%#x" % perf_dict[field]
  55. return ""
  56. def get_dso_file_path(dso_name, dso_build_id):
  57. if (dso_name == "[kernel.kallsyms]" or dso_name == "vmlinux"):
  58. if (options.vmlinux_name):
  59. return options.vmlinux_name;
  60. else:
  61. return dso_name
  62. if (dso_name == "[vdso]") :
  63. append = "/vdso"
  64. else:
  65. append = "/elf"
  66. dso_path = os.environ['PERF_BUILDID_DIR'] + "/" + dso_name + "/" + dso_build_id + append;
  67. # Replace duplicate slash chars to single slash char
  68. dso_path = dso_path.replace('//', '/', 1)
  69. return dso_path
  70. def read_disam(dso_fname, dso_start, start_addr, stop_addr):
  71. addr_range = str(start_addr) + ":" + str(stop_addr) + ":" + dso_fname
  72. # Don't let the cache get too big, clear it when it hits max size
  73. if (len(disasm_cache) > cache_size):
  74. disasm_cache.clear();
  75. if addr_range in disasm_cache:
  76. disasm_output = disasm_cache[addr_range];
  77. else:
  78. start_addr = start_addr - dso_start;
  79. stop_addr = stop_addr - dso_start;
  80. disasm = [ options.objdump_name, "-d", "-z",
  81. "--start-address="+format(start_addr,"#x"),
  82. "--stop-address="+format(stop_addr,"#x") ]
  83. disasm += [ dso_fname ]
  84. disasm_output = check_output(disasm).decode('utf-8').split('\n')
  85. disasm_cache[addr_range] = disasm_output
  86. return disasm_output
  87. def print_disam(dso_fname, dso_start, start_addr, stop_addr):
  88. for line in read_disam(dso_fname, dso_start, start_addr, stop_addr):
  89. m = disasm_func_re.search(line)
  90. if m is None:
  91. m = disasm_re.search(line)
  92. if m is None:
  93. continue
  94. print("\t" + line)
  95. def print_sample(sample):
  96. print("Sample = { cpu: %04d addr: 0x%016x phys_addr: 0x%016x ip: 0x%016x " \
  97. "pid: %d tid: %d period: %d time: %d }" % \
  98. (sample['cpu'], sample['addr'], sample['phys_addr'], \
  99. sample['ip'], sample['pid'], sample['tid'], \
  100. sample['period'], sample['time']))
  101. def trace_begin():
  102. print('ARM CoreSight Trace Data Assembler Dump')
  103. def trace_end():
  104. print('End')
  105. def trace_unhandled(event_name, context, event_fields_dict):
  106. print(' '.join(['%s=%s'%(k,str(v))for k,v in sorted(event_fields_dict.items())]))
  107. def common_start_str(comm, sample):
  108. sec = int(sample["time"] / 1000000000)
  109. ns = sample["time"] % 1000000000
  110. cpu = sample["cpu"]
  111. pid = sample["pid"]
  112. tid = sample["tid"]
  113. return "%16s %5u/%-5u [%04u] %9u.%09u " % (comm, pid, tid, cpu, sec, ns)
  114. # This code is copied from intel-pt-events.py for printing source code
  115. # line and symbols.
  116. def print_srccode(comm, param_dict, sample, symbol, dso):
  117. ip = sample["ip"]
  118. if symbol == "[unknown]":
  119. start_str = common_start_str(comm, sample) + ("%x" % ip).rjust(16).ljust(40)
  120. else:
  121. offs = get_offset(param_dict, "symoff")
  122. start_str = common_start_str(comm, sample) + (symbol + offs).ljust(40)
  123. global glb_source_file_name
  124. global glb_line_number
  125. global glb_dso
  126. source_file_name, line_number, source_line = perf_sample_srccode(perf_script_context)
  127. if source_file_name:
  128. if glb_line_number == line_number and glb_source_file_name == source_file_name:
  129. src_str = ""
  130. else:
  131. if len(source_file_name) > 40:
  132. src_file = ("..." + source_file_name[-37:]) + " "
  133. else:
  134. src_file = source_file_name.ljust(41)
  135. if source_line is None:
  136. src_str = src_file + str(line_number).rjust(4) + " <source not found>"
  137. else:
  138. src_str = src_file + str(line_number).rjust(4) + " " + source_line
  139. glb_dso = None
  140. elif dso == glb_dso:
  141. src_str = ""
  142. else:
  143. src_str = dso
  144. glb_dso = dso
  145. glb_line_number = line_number
  146. glb_source_file_name = source_file_name
  147. print(start_str, src_str)
  148. def process_event(param_dict):
  149. global cache_size
  150. global options
  151. sample = param_dict["sample"]
  152. comm = param_dict["comm"]
  153. name = param_dict["ev_name"]
  154. dso = get_optional(param_dict, "dso")
  155. dso_bid = get_optional(param_dict, "dso_bid")
  156. dso_start = get_optional(param_dict, "dso_map_start")
  157. dso_end = get_optional(param_dict, "dso_map_end")
  158. symbol = get_optional(param_dict, "symbol")
  159. cpu = sample["cpu"]
  160. ip = sample["ip"]
  161. addr = sample["addr"]
  162. if (options.verbose == True):
  163. print("Event type: %s" % name)
  164. print_sample(sample)
  165. # Initialize CPU data if it's empty, and directly return back
  166. # if this is the first tracing event for this CPU.
  167. if (cpu_data.get(str(cpu) + 'addr') == None):
  168. cpu_data[str(cpu) + 'addr'] = addr
  169. return
  170. # If cannot find dso so cannot dump assembler, bail out
  171. if (dso == '[unknown]'):
  172. return
  173. # Validate dso start and end addresses
  174. if ((dso_start == '[unknown]') or (dso_end == '[unknown]')):
  175. print("Failed to find valid dso map for dso %s" % dso)
  176. return
  177. if (name[0:12] == "instructions"):
  178. print_srccode(comm, param_dict, sample, symbol, dso)
  179. return
  180. # Don't proceed if this event is not a branch sample, .
  181. if (name[0:8] != "branches"):
  182. return
  183. # The format for packet is:
  184. #
  185. # +------------+------------+------------+
  186. # sample_prev: | addr | ip | cpu |
  187. # +------------+------------+------------+
  188. # sample_next: | addr | ip | cpu |
  189. # +------------+------------+------------+
  190. #
  191. # We need to combine the two continuous packets to get the instruction
  192. # range for sample_prev::cpu:
  193. #
  194. # [ sample_prev::addr .. sample_next::ip ]
  195. #
  196. # For this purose, sample_prev::addr is stored into cpu_data structure
  197. # and read back for 'start_addr' when the new packet comes, and we need
  198. # to use sample_next::ip to calculate 'stop_addr', plusing extra 4 for
  199. # 'stop_addr' is for the sake of objdump so the final assembler dump can
  200. # include last instruction for sample_next::ip.
  201. start_addr = cpu_data[str(cpu) + 'addr']
  202. stop_addr = ip + 4
  203. # Record for previous sample packet
  204. cpu_data[str(cpu) + 'addr'] = addr
  205. # Handle CS_ETM_TRACE_ON packet if start_addr=0 and stop_addr=4
  206. if (start_addr == 0 and stop_addr == 4):
  207. print("CPU%d: CS_ETM_TRACE_ON packet is inserted" % cpu)
  208. return
  209. if (start_addr < int(dso_start) or start_addr > int(dso_end)):
  210. print("Start address 0x%x is out of range [ 0x%x .. 0x%x ] for dso %s" % (start_addr, int(dso_start), int(dso_end), dso))
  211. return
  212. if (stop_addr < int(dso_start) or stop_addr > int(dso_end)):
  213. print("Stop address 0x%x is out of range [ 0x%x .. 0x%x ] for dso %s" % (stop_addr, int(dso_start), int(dso_end), dso))
  214. return
  215. if (options.objdump_name != None):
  216. # It doesn't need to decrease virtual memory offset for disassembly
  217. # for kernel dso and executable file dso, so in this case we set
  218. # vm_start to zero.
  219. if (dso == "[kernel.kallsyms]" or dso_start == 0x400000):
  220. dso_vm_start = 0
  221. else:
  222. dso_vm_start = int(dso_start)
  223. dso_fname = get_dso_file_path(dso, dso_bid)
  224. if path.exists(dso_fname):
  225. print_disam(dso_fname, dso_vm_start, start_addr, stop_addr)
  226. else:
  227. print("Failed to find dso %s for address range [ 0x%x .. 0x%x ]" % (dso, start_addr, stop_addr))
  228. print_srccode(comm, param_dict, sample, symbol, dso)