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