1 # SPDX-License-Identifier: GPL-2.0
2 # arm-cs-trace-disasm.py: ARM CoreSight Trace Dump With Disassember
9 from __future__ import print_function
14 from subprocess import *
15 from optparse import OptionParser, make_option
17 from perf_trace_context import perf_set_itrace_options, \
18 perf_sample_insn, perf_sample_srccode
20 # Below are some example commands for using this script.
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
31 # Command line parsing.
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")
43 parser = OptionParser(option_list=option_list)
44 (options, args) = parser.parse_args()
46 # Initialize global dicts and regular expression
49 disasm_re = re.compile("^\s*([0-9a-fA-F]+):")
50 disasm_func_re = re.compile("^\s*([0-9a-fA-F]+)\s.*:")
53 glb_source_file_name = None
54 glb_line_number = None
57 def get_optional(perf_dict, field):
58 if field in perf_dict:
59 return perf_dict[field]
62 def get_offset(perf_dict, field):
63 if field in perf_dict:
64 return "+%#x" % perf_dict[field]
67 def 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;
74 if (dso_name == "[vdso]") :
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)
84 def read_disam(dso_fname, dso_start, start_addr, stop_addr):
85 addr_range = str(start_addr) + ":" + str(stop_addr) + ":" + dso_fname
87 # Don't let the cache get too big, clear it when it hits max size
88 if (len(disasm_cache) > cache_size):
91 if addr_range in disasm_cache:
92 disasm_output = disasm_cache[addr_range];
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
105 def 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)
109 m = disasm_re.search(line)
114 def 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']))
122 print('ARM CoreSight Trace Data Assembler Dump')
127 def 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())]))
130 def common_start_str(comm, sample):
131 sec = int(sample["time"] / 1000000000)
132 ns = sample["time"] % 1000000000
136 return "%16s %5u/%-5u [%04u] %9u.%09u " % (comm, pid, tid, cpu, sec, ns)
138 # This code is copied from intel-pt-events.py for printing source code
140 def print_srccode(comm, param_dict, sample, symbol, dso):
142 if symbol == "[unknown]":
143 start_str = common_start_str(comm, sample) + ("%x" % ip).rjust(16).ljust(40)
145 offs = get_offset(param_dict, "symoff")
146 start_str = common_start_str(comm, sample) + (symbol + offs).ljust(40)
148 global glb_source_file_name
149 global glb_line_number
152 source_file_name, line_number, source_line = perf_sample_srccode(perf_script_context)
154 if glb_line_number == line_number and glb_source_file_name == source_file_name:
157 if len(source_file_name) > 40:
158 src_file = ("..." + source_file_name[-37:]) + " "
160 src_file = source_file_name.ljust(41)
162 if source_line is None:
163 src_str = src_file + str(line_number).rjust(4) + " <source not found>"
165 src_str = src_file + str(line_number).rjust(4) + " " + source_line
173 glb_line_number = line_number
174 glb_source_file_name = source_file_name
176 print(start_str, src_str)
178 def process_event(param_dict):
182 sample = param_dict["sample"]
183 comm = param_dict["comm"]
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")
192 if (options.verbose == True):
193 print("Event type: %s" % name)
196 # If cannot find dso so cannot dump assembler, bail out
197 if (dso == '[unknown]'):
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)
205 if (name[0:12] == "instructions"):
206 print_srccode(comm, param_dict, sample, symbol, dso)
209 # Don't proceed if this event is not a branch sample, .
210 if (name[0:8] != "branches"):
215 addr = sample["addr"]
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
223 # The format for packet is:
225 # +------------+------------+------------+
226 # sample_prev: | addr | ip | cpu |
227 # +------------+------------+------------+
228 # sample_next: | addr | ip | cpu |
229 # +------------+------------+------------+
231 # We need to combine the two continuous packets to get the instruction
232 # range for sample_prev::cpu:
234 # [ sample_prev::addr .. sample_next::ip ]
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']
244 # Record for previous sample packet
245 cpu_data[str(cpu) + 'addr'] = addr
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)
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))
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))
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]"):
266 dso_vm_start = int(dso_start)
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)
272 print("Failed to find dso %s for address range [ 0x%x .. 0x%x ]" % (dso, start_addr, stop_addr))
274 print_srccode(comm, param_dict, sample, symbol, dso)