arm-cs-trace-disasm.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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. import argparse
  14. import platform
  15. from perf_trace_context import perf_sample_srccode, perf_config_get
  16. # Below are some example commands for using this script.
  17. # Note a --kcore recording is required for accurate decode
  18. # due to the alternatives patching mechanism. However this
  19. # script only supports reading vmlinux for disassembly dump,
  20. # meaning that any patched instructions will appear
  21. # as unpatched, but the instruction ranges themselves will
  22. # be correct. In addition to this, source line info comes
  23. # from Perf, and when using kcore there is no debug info. The
  24. # following lists the supported features in each mode:
  25. #
  26. # +-----------+-----------------+------------------+------------------+
  27. # | Recording | Accurate decode | Source line dump | Disassembly dump |
  28. # +-----------+-----------------+------------------+------------------+
  29. # | --kcore | yes | no | yes |
  30. # | normal | no | yes | yes |
  31. # +-----------+-----------------+------------------+------------------+
  32. #
  33. # Output disassembly with objdump and auto detect vmlinux
  34. # (when running on same machine.)
  35. # perf script -s scripts/python/arm-cs-trace-disasm.py -d
  36. #
  37. # Output disassembly with llvm-objdump:
  38. # perf script -s scripts/python/arm-cs-trace-disasm.py \
  39. # -- -d llvm-objdump-11 -k path/to/vmlinux
  40. #
  41. # Output only source line and symbols:
  42. # perf script -s scripts/python/arm-cs-trace-disasm.py
  43. def default_objdump():
  44. config = perf_config_get("annotate.objdump")
  45. return config if config else "objdump"
  46. # Command line parsing.
  47. def int_arg(v):
  48. v = int(v)
  49. if v < 0:
  50. raise argparse.ArgumentTypeError("Argument must be a positive integer")
  51. return v
  52. args = argparse.ArgumentParser()
  53. args.add_argument("-k", "--vmlinux",
  54. help="Set path to vmlinux file. Omit to autodetect if running on same machine")
  55. args.add_argument("-d", "--objdump", nargs="?", const=default_objdump(),
  56. help="Show disassembly. Can also be used to change the objdump path"),
  57. args.add_argument("-v", "--verbose", action="store_true", help="Enable debugging log")
  58. args.add_argument("--start-time", type=int_arg, help="Monotonic clock time of sample to start from. "
  59. "See 'time' field on samples in -v mode.")
  60. args.add_argument("--stop-time", type=int_arg, help="Monotonic clock time of sample to stop at. "
  61. "See 'time' field on samples in -v mode.")
  62. args.add_argument("--start-sample", type=int_arg, help="Index of sample to start from. "
  63. "See 'index' field on samples in -v mode.")
  64. args.add_argument("--stop-sample", type=int_arg, help="Index of sample to stop at. "
  65. "See 'index' field on samples in -v mode.")
  66. options = args.parse_args()
  67. if (options.start_time and options.stop_time and
  68. options.start_time >= options.stop_time):
  69. print("--start-time must less than --stop-time")
  70. exit(2)
  71. if (options.start_sample and options.stop_sample and
  72. options.start_sample >= options.stop_sample):
  73. print("--start-sample must less than --stop-sample")
  74. exit(2)
  75. # Initialize global dicts and regular expression
  76. disasm_cache = dict()
  77. cpu_data = dict()
  78. disasm_re = re.compile(r"^\s*([0-9a-fA-F]+):")
  79. disasm_func_re = re.compile(r"^\s*([0-9a-fA-F]+)\s.*:")
  80. cache_size = 64*1024
  81. sample_idx = -1
  82. glb_source_file_name = None
  83. glb_line_number = None
  84. glb_dso = None
  85. kver = platform.release()
  86. vmlinux_paths = [
  87. f"/usr/lib/debug/boot/vmlinux-{kver}.debug",
  88. f"/usr/lib/debug/lib/modules/{kver}/vmlinux",
  89. f"/lib/modules/{kver}/build/vmlinux",
  90. f"/usr/lib/debug/boot/vmlinux-{kver}",
  91. f"/boot/vmlinux-{kver}",
  92. f"/boot/vmlinux",
  93. f"vmlinux"
  94. ]
  95. def get_optional(perf_dict, field):
  96. if field in perf_dict:
  97. return perf_dict[field]
  98. return "[unknown]"
  99. def get_offset(perf_dict, field):
  100. if field in perf_dict:
  101. return "+%#x" % perf_dict[field]
  102. return ""
  103. def find_vmlinux():
  104. if hasattr(find_vmlinux, "path"):
  105. return find_vmlinux.path
  106. for v in vmlinux_paths:
  107. if os.access(v, os.R_OK):
  108. find_vmlinux.path = v
  109. break
  110. else:
  111. find_vmlinux.path = None
  112. return find_vmlinux.path
  113. def get_dso_file_path(dso_name, dso_build_id):
  114. if (dso_name == "[kernel.kallsyms]" or dso_name == "vmlinux"):
  115. if (options.vmlinux):
  116. return options.vmlinux;
  117. else:
  118. return find_vmlinux() if find_vmlinux() else dso_name
  119. if (dso_name == "[vdso]") :
  120. append = "/vdso"
  121. else:
  122. append = "/elf"
  123. dso_path = os.environ['PERF_BUILDID_DIR'] + "/" + dso_name + "/" + dso_build_id + append;
  124. # Replace duplicate slash chars to single slash char
  125. dso_path = dso_path.replace('//', '/', 1)
  126. return dso_path
  127. def read_disam(dso_fname, dso_start, start_addr, stop_addr):
  128. addr_range = str(start_addr) + ":" + str(stop_addr) + ":" + dso_fname
  129. # Don't let the cache get too big, clear it when it hits max size
  130. if (len(disasm_cache) > cache_size):
  131. disasm_cache.clear();
  132. if addr_range in disasm_cache:
  133. disasm_output = disasm_cache[addr_range];
  134. else:
  135. start_addr = start_addr - dso_start;
  136. stop_addr = stop_addr - dso_start;
  137. disasm = [ options.objdump, "-d", "-z",
  138. "--start-address="+format(start_addr,"#x"),
  139. "--stop-address="+format(stop_addr,"#x") ]
  140. disasm += [ dso_fname ]
  141. disasm_output = check_output(disasm).decode('utf-8').split('\n')
  142. disasm_cache[addr_range] = disasm_output
  143. return disasm_output
  144. def print_disam(dso_fname, dso_start, start_addr, stop_addr):
  145. for line in read_disam(dso_fname, dso_start, start_addr, stop_addr):
  146. m = disasm_func_re.search(line)
  147. if m is None:
  148. m = disasm_re.search(line)
  149. if m is None:
  150. continue
  151. print("\t" + line)
  152. def print_sample(sample):
  153. print("Sample = { cpu: %04d addr: 0x%016x phys_addr: 0x%016x ip: 0x%016x " \
  154. "pid: %d tid: %d period: %d time: %d index: %d}" % \
  155. (sample['cpu'], sample['addr'], sample['phys_addr'], \
  156. sample['ip'], sample['pid'], sample['tid'], \
  157. sample['period'], sample['time'], sample_idx))
  158. def trace_begin():
  159. print('ARM CoreSight Trace Data Assembler Dump')
  160. def trace_end():
  161. print('End')
  162. def trace_unhandled(event_name, context, event_fields_dict):
  163. print(' '.join(['%s=%s'%(k,str(v))for k,v in sorted(event_fields_dict.items())]))
  164. def common_start_str(comm, sample):
  165. sec = int(sample["time"] / 1000000000)
  166. ns = sample["time"] % 1000000000
  167. cpu = sample["cpu"]
  168. pid = sample["pid"]
  169. tid = sample["tid"]
  170. return "%16s %5u/%-5u [%04u] %9u.%09u " % (comm, pid, tid, cpu, sec, ns)
  171. # This code is copied from intel-pt-events.py for printing source code
  172. # line and symbols.
  173. def print_srccode(comm, param_dict, sample, symbol, dso):
  174. ip = sample["ip"]
  175. if symbol == "[unknown]":
  176. start_str = common_start_str(comm, sample) + ("%x" % ip).rjust(16).ljust(40)
  177. else:
  178. offs = get_offset(param_dict, "symoff")
  179. start_str = common_start_str(comm, sample) + (symbol + offs).ljust(40)
  180. global glb_source_file_name
  181. global glb_line_number
  182. global glb_dso
  183. source_file_name, line_number, source_line = perf_sample_srccode(perf_script_context)
  184. if source_file_name:
  185. if glb_line_number == line_number and glb_source_file_name == source_file_name:
  186. src_str = ""
  187. else:
  188. if len(source_file_name) > 40:
  189. src_file = ("..." + source_file_name[-37:]) + " "
  190. else:
  191. src_file = source_file_name.ljust(41)
  192. if source_line is None:
  193. src_str = src_file + str(line_number).rjust(4) + " <source not found>"
  194. else:
  195. src_str = src_file + str(line_number).rjust(4) + " " + source_line
  196. glb_dso = None
  197. elif dso == glb_dso:
  198. src_str = ""
  199. else:
  200. src_str = dso
  201. glb_dso = dso
  202. glb_line_number = line_number
  203. glb_source_file_name = source_file_name
  204. print(start_str, src_str)
  205. def process_event(param_dict):
  206. global cache_size
  207. global options
  208. global sample_idx
  209. sample = param_dict["sample"]
  210. comm = param_dict["comm"]
  211. name = param_dict["ev_name"]
  212. dso = get_optional(param_dict, "dso")
  213. dso_bid = get_optional(param_dict, "dso_bid")
  214. dso_start = get_optional(param_dict, "dso_map_start")
  215. dso_end = get_optional(param_dict, "dso_map_end")
  216. symbol = get_optional(param_dict, "symbol")
  217. map_pgoff = get_optional(param_dict, "map_pgoff")
  218. # check for valid map offset
  219. if (str(map_pgoff) == '[unknown]'):
  220. map_pgoff = 0
  221. cpu = sample["cpu"]
  222. ip = sample["ip"]
  223. addr = sample["addr"]
  224. sample_idx += 1
  225. if (options.start_time and sample["time"] < options.start_time):
  226. return
  227. if (options.stop_time and sample["time"] > options.stop_time):
  228. exit(0)
  229. if (options.start_sample and sample_idx < options.start_sample):
  230. return
  231. if (options.stop_sample and sample_idx > options.stop_sample):
  232. exit(0)
  233. if (options.verbose == True):
  234. print("Event type: %s" % name)
  235. print_sample(sample)
  236. # Initialize CPU data if it's empty, and directly return back
  237. # if this is the first tracing event for this CPU.
  238. if (cpu_data.get(str(cpu) + 'addr') == None):
  239. cpu_data[str(cpu) + 'addr'] = addr
  240. return
  241. # If cannot find dso so cannot dump assembler, bail out
  242. if (dso == '[unknown]'):
  243. return
  244. # Validate dso start and end addresses
  245. if ((dso_start == '[unknown]') or (dso_end == '[unknown]')):
  246. print("Failed to find valid dso map for dso %s" % dso)
  247. return
  248. if (name[0:12] == "instructions"):
  249. print_srccode(comm, param_dict, sample, symbol, dso)
  250. return
  251. # Don't proceed if this event is not a branch sample, .
  252. if (name[0:8] != "branches"):
  253. return
  254. # The format for packet is:
  255. #
  256. # +------------+------------+------------+
  257. # sample_prev: | addr | ip | cpu |
  258. # +------------+------------+------------+
  259. # sample_next: | addr | ip | cpu |
  260. # +------------+------------+------------+
  261. #
  262. # We need to combine the two continuous packets to get the instruction
  263. # range for sample_prev::cpu:
  264. #
  265. # [ sample_prev::addr .. sample_next::ip ]
  266. #
  267. # For this purose, sample_prev::addr is stored into cpu_data structure
  268. # and read back for 'start_addr' when the new packet comes, and we need
  269. # to use sample_next::ip to calculate 'stop_addr', plusing extra 4 for
  270. # 'stop_addr' is for the sake of objdump so the final assembler dump can
  271. # include last instruction for sample_next::ip.
  272. start_addr = cpu_data[str(cpu) + 'addr']
  273. stop_addr = ip + 4
  274. # Record for previous sample packet
  275. cpu_data[str(cpu) + 'addr'] = addr
  276. # Filter out zero start_address. Optionally identify CS_ETM_TRACE_ON packet
  277. if (start_addr == 0):
  278. if ((stop_addr == 4) and (options.verbose == True)):
  279. print("CPU%d: CS_ETM_TRACE_ON packet is inserted" % cpu)
  280. return
  281. if (start_addr < int(dso_start) or start_addr > int(dso_end)):
  282. 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))
  283. return
  284. if (stop_addr < int(dso_start) or stop_addr > int(dso_end)):
  285. 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))
  286. return
  287. if (options.objdump != None):
  288. # It doesn't need to decrease virtual memory offset for disassembly
  289. # for kernel dso and executable file dso, so in this case we set
  290. # vm_start to zero.
  291. if (dso == "[kernel.kallsyms]" or dso_start == 0x400000):
  292. dso_vm_start = 0
  293. map_pgoff = 0
  294. else:
  295. dso_vm_start = int(dso_start)
  296. dso_fname = get_dso_file_path(dso, dso_bid)
  297. if path.exists(dso_fname):
  298. print_disam(dso_fname, dso_vm_start, start_addr + map_pgoff, stop_addr + map_pgoff)
  299. else:
  300. print("Failed to find dso %s for address range [ 0x%x .. 0x%x ]" % (dso, start_addr + map_pgoff, stop_addr + map_pgoff))
  301. print_srccode(comm, param_dict, sample, symbol, dso)