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