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
13 from subprocess import *
14 from optparse import OptionParser, make_option
16 from perf_trace_context import perf_set_itrace_options, \
17 perf_sample_insn, perf_sample_srccode
19 # Below are some example commands for using this script.
21 # Output disassembly with objdump:
22 # perf script -s scripts/python/arm-cs-trace-disasm.py \
23 # -- -d objdump -k path/to/vmlinux
24 # Output disassembly with llvm-objdump:
25 # perf script -s scripts/python/arm-cs-trace-disasm.py \
26 # -- -d llvm-objdump-11 -k path/to/vmlinux
27 # Output only source line and symbols:
28 # perf script -s scripts/python/arm-cs-trace-disasm.py
30 # Command line parsing.
32 # formatting options for the bottom entry of the stack
33 make_option("-k", "--vmlinux", dest="vmlinux_name",
34 help="Set path to vmlinux file"),
35 make_option("-d", "--objdump", dest="objdump_name",
36 help="Set path to objdump executable file"),
37 make_option("-v", "--verbose", dest="verbose",
38 action="store_true", default=False,
39 help="Enable debugging log")
42 parser = OptionParser(option_list=option_list)
43 (options, args) = parser.parse_args()
45 # Initialize global dicts and regular expression
48 disasm_re = re.compile(r"^\s*([0-9a-fA-F]+):")
49 disasm_func_re = re.compile(r"^\s*([0-9a-fA-F]+)\s.*:")
52 glb_source_file_name = None
53 glb_line_number = None
56 def get_optional(perf_dict, field):
57 if field in perf_dict:
58 return perf_dict[field]
61 def get_offset(perf_dict, field):
62 if field in perf_dict:
63 return "+%#x" % perf_dict[field]
66 def get_dso_file_path(dso_name, dso_build_id):
67 if (dso_name == "[kernel.kallsyms]" or dso_name == "vmlinux"):
68 if (options.vmlinux_name):
69 return options.vmlinux_name;
73 if (dso_name == "[vdso]") :
78 dso_path = os.environ['PERF_BUILDID_DIR'] + "/" + dso_name + "/" + dso_build_id + append;
79 # Replace duplicate slash chars to single slash char
80 dso_path = dso_path.replace('//', '/', 1)
83 def read_disam(dso_fname, dso_start, start_addr, stop_addr):
84 addr_range = str(start_addr) + ":" + str(stop_addr) + ":" + dso_fname
86 # Don't let the cache get too big, clear it when it hits max size
87 if (len(disasm_cache) > cache_size):
90 if addr_range in disasm_cache:
91 disasm_output = disasm_cache[addr_range];
93 start_addr = start_addr - dso_start;
94 stop_addr = stop_addr - dso_start;
95 disasm = [ options.objdump_name, "-d", "-z",
96 "--start-address="+format(start_addr,"#x"),
97 "--stop-address="+format(stop_addr,"#x") ]
98 disasm += [ dso_fname ]
99 disasm_output = check_output(disasm).decode('utf-8').split('\n')
100 disasm_cache[addr_range] = disasm_output
104 def print_disam(dso_fname, dso_start, start_addr, stop_addr):
105 for line in read_disam(dso_fname, dso_start, start_addr, stop_addr):
106 m = disasm_func_re.search(line)
108 m = disasm_re.search(line)
113 def print_sample(sample):
114 print("Sample = { cpu: %04d addr: 0x%016x phys_addr: 0x%016x ip: 0x%016x " \
115 "pid: %d tid: %d period: %d time: %d }" % \
116 (sample['cpu'], sample['addr'], sample['phys_addr'], \
117 sample['ip'], sample['pid'], sample['tid'], \
118 sample['period'], sample['time']))
121 print('ARM CoreSight Trace Data Assembler Dump')
126 def trace_unhandled(event_name, context, event_fields_dict):
127 print(' '.join(['%s=%s'%(k,str(v))for k,v in sorted(event_fields_dict.items())]))
129 def common_start_str(comm, sample):
130 sec = int(sample["time"] / 1000000000)
131 ns = sample["time"] % 1000000000
135 return "%16s %5u/%-5u [%04u] %9u.%09u " % (comm, pid, tid, cpu, sec, ns)
137 # This code is copied from intel-pt-events.py for printing source code
139 def print_srccode(comm, param_dict, sample, symbol, dso):
141 if symbol == "[unknown]":
142 start_str = common_start_str(comm, sample) + ("%x" % ip).rjust(16).ljust(40)
144 offs = get_offset(param_dict, "symoff")
145 start_str = common_start_str(comm, sample) + (symbol + offs).ljust(40)
147 global glb_source_file_name
148 global glb_line_number
151 source_file_name, line_number, source_line = perf_sample_srccode(perf_script_context)
153 if glb_line_number == line_number and glb_source_file_name == source_file_name:
156 if len(source_file_name) > 40:
157 src_file = ("..." + source_file_name[-37:]) + " "
159 src_file = source_file_name.ljust(41)
161 if source_line is None:
162 src_str = src_file + str(line_number).rjust(4) + " <source not found>"
164 src_str = src_file + str(line_number).rjust(4) + " " + source_line
172 glb_line_number = line_number
173 glb_source_file_name = source_file_name
175 print(start_str, src_str)
177 def process_event(param_dict):
181 sample = param_dict["sample"]
182 comm = param_dict["comm"]
184 name = param_dict["ev_name"]
185 dso = get_optional(param_dict, "dso")
186 dso_bid = get_optional(param_dict, "dso_bid")
187 dso_start = get_optional(param_dict, "dso_map_start")
188 dso_end = get_optional(param_dict, "dso_map_end")
189 symbol = get_optional(param_dict, "symbol")
193 addr = sample["addr"]
195 # Initialize CPU data if it's empty, and directly return back
196 # if this is the first tracing event for this CPU.
197 if (cpu_data.get(str(cpu) + 'addr') == None):
198 cpu_data[str(cpu) + 'addr'] = addr
202 if (options.verbose == True):
203 print("Event type: %s" % name)
206 # If cannot find dso so cannot dump assembler, bail out
207 if (dso == '[unknown]'):
210 # Validate dso start and end addresses
211 if ((dso_start == '[unknown]') or (dso_end == '[unknown]')):
212 print("Failed to find valid dso map for dso %s" % dso)
215 if (name[0:12] == "instructions"):
216 print_srccode(comm, param_dict, sample, symbol, dso)
219 # Don't proceed if this event is not a branch sample, .
220 if (name[0:8] != "branches"):
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 and executable file dso, so in this case we set
264 if (dso == "[kernel.kallsyms]" or dso_start == 0x400000):
267 dso_vm_start = int(dso_start)
269 dso_fname = get_dso_file_path(dso, dso_bid)
270 if path.exists(dso_fname):
271 print_disam(dso_fname, dso_vm_start, start_addr, stop_addr)
273 print("Failed to find dso %s for address range [ 0x%x .. 0x%x ]" % (dso, start_addr, stop_addr))
275 print_srccode(comm, param_dict, sample, symbol, dso)