blob: f88550f65972a16cc9222d15a115f798db69ff5c [file] [log] [blame]
Krzysztof Kosińskib1361112021-03-11 18:05:01 -08001#!/usr/bin/env python3
Ben Chengb42dad02013-04-25 15:14:04 -07002#
3# Copyright (C) 2013 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""stack symbolizes native crash dumps."""
18
David Srbecky3a3349e2021-10-28 13:08:10 +010019import collections
20import functools
Christopher Ferrisece64c42015-08-20 20:09:09 -070021import os
David Srbecky3a3349e2021-10-28 13:08:10 +010022import pathlib
Ben Chengb42dad02013-04-25 15:14:04 -070023import re
Christopher Ferrisece64c42015-08-20 20:09:09 -070024import subprocess
Ben Chengb42dad02013-04-25 15:14:04 -070025import symbol
Christopher Ferrisece64c42015-08-20 20:09:09 -070026import tempfile
Elliott Hughesa9e34172014-07-01 14:56:22 -070027import unittest
Ben Chengb42dad02013-04-25 15:14:04 -070028
Elliott Hughesc3166be2014-07-07 15:06:28 -070029import example_crashes
30
Ben Chengb42dad02013-04-25 15:14:04 -070031def ConvertTrace(lines):
Brigid Smithea0a8352014-06-30 16:01:40 -070032 tracer = TraceConverter()
Krzysztof Kosińskib1361112021-03-11 18:05:01 -080033 print("Reading symbols from", symbol.SYMBOLS_DIR)
Brigid Smithea0a8352014-06-30 16:01:40 -070034 tracer.ConvertTrace(lines)
35
36class TraceConverter:
Krzysztof Kosińskib1361112021-03-11 18:05:01 -080037 process_info_line = re.compile(r"(pid: [0-9]+, tid: [0-9]+.*)")
38 revision_line = re.compile(r"(Revision: '(.*)')")
39 signal_line = re.compile(r"(signal [0-9]+ \(.*\).*)")
40 abort_message_line = re.compile(r"(Abort message: '.*')")
41 thread_line = re.compile(r"(.*)(--- ){15}---")
Ben Chengb42dad02013-04-25 15:14:04 -070042 dalvik_jni_thread_line = re.compile("(\".*\" prio=[0-9]+ tid=[0-9]+ NATIVE.*)")
43 dalvik_native_thread_line = re.compile("(\".*\" sysTid=[0-9]+ nice=[0-9]+.*)")
Brigid Smithea0a8352014-06-30 16:01:40 -070044 register_line = re.compile("$a")
45 trace_line = re.compile("$a")
Andreas Gamped900d082015-08-21 15:25:03 -070046 sanitizer_trace_line = re.compile("$a")
Brigid Smithea0a8352014-06-30 16:01:40 -070047 value_line = re.compile("$a")
48 code_line = re.compile("$a")
Krzysztof Kosińskib1361112021-03-11 18:05:01 -080049 zipinfo_central_directory_line = re.compile(r"Central\s+directory\s+entry")
Christopher Ferrisabe22f42016-03-16 12:17:59 -070050 zipinfo_central_info_match = re.compile(
Krzysztof Kosińskib1361112021-03-11 18:05:01 -080051 r"^\s*(\S+)$\s*offset of local header from start of archive:\s*(\d+)"
52 r".*^\s*compressed size:\s+(\d+)", re.M | re.S)
53 unreachable_line = re.compile(r"((\d+ bytes in \d+ unreachable allocations)|"
54 r"(\d+ bytes unreachable at [0-9a-f]+)|"
55 r"(referencing \d+ unreachable bytes in \d+ allocation(s)?)|"
56 r"(and \d+ similar unreachable bytes in \d+ allocation(s)?))")
Ben Chengb42dad02013-04-25 15:14:04 -070057 trace_lines = []
58 value_lines = []
59 last_frame = -1
Brigid Smithea0a8352014-06-30 16:01:40 -070060 width = "{8}"
Elliott Hughesc3c86192014-08-29 13:49:57 -070061 spacing = ""
Christopher Ferrisece64c42015-08-20 20:09:09 -070062 apk_info = dict()
Christopher Ferris29fcc842022-11-02 17:33:30 -070063 lib_to_path = dict()
Ben Chengb42dad02013-04-25 15:14:04 -070064
Elliott Hughesa9e34172014-07-01 14:56:22 -070065 register_names = {
66 "arm": "r0|r1|r2|r3|r4|r5|r6|r7|r8|r9|sl|fp|ip|sp|lr|pc|cpsr",
Elliott Hughesbe4de462014-07-14 17:15:41 -070067 "arm64": "x0|x1|x2|x3|x4|x5|x6|x7|x8|x9|x10|x11|x12|x13|x14|x15|x16|x17|x18|x19|x20|x21|x22|x23|x24|x25|x26|x27|x28|x29|x30|sp|pc|pstate",
Elliott Hughesa9e34172014-07-01 14:56:22 -070068 "x86": "eax|ebx|ecx|edx|esi|edi|x?cs|x?ds|x?es|x?fs|x?ss|eip|ebp|esp|flags",
69 "x86_64": "rax|rbx|rcx|rdx|rsi|rdi|r8|r9|r10|r11|r12|r13|r14|r15|cs|ss|rip|rbp|rsp|eflags",
Prashanth Swaminathan01fd4182023-03-08 13:16:35 -080070 "riscv64": "ra|sp|gp|tp|t0|t1|t2|s0|s1|a0|a1|a2|a3|a4|a5|a6|a7|s2|s3|s4|s5|s6|s7|s8|s9|s10|s11|t3|t4|t5|t6|pc",
Elliott Hughesa9e34172014-07-01 14:56:22 -070071 }
72
David Srbecky3a3349e2021-10-28 13:08:10 +010073 # We use the "file" command line tool to extract BuildId from ELF files.
74 ElfInfo = collections.namedtuple("ElfInfo", ["bitness", "build_id"])
Christopher Ferris29fcc842022-11-02 17:33:30 -070075 readelf_output = re.compile(r"Class:\s*ELF(?P<bitness>32|64).*"
76 r"Build ID:\s*(?P<build_id>[0-9a-f]+)",
77 flags=re.DOTALL)
David Srbecky3a3349e2021-10-28 13:08:10 +010078
Elliott Hughesa9e34172014-07-01 14:56:22 -070079 def UpdateAbiRegexes(self):
Prashanth Swaminathan01fd4182023-03-08 13:16:35 -080080 if symbol.ARCH == "arm64" or symbol.ARCH == "x86_64" or symbol.ARCH == "riscv64":
Brigid Smithea0a8352014-06-30 16:01:40 -070081 self.width = "{16}"
Elliott Hughesc3c86192014-08-29 13:49:57 -070082 self.spacing = " "
Brigid Smith15142f72014-07-15 13:47:07 -070083 else:
84 self.width = "{8}"
Elliott Hughesc3c86192014-08-29 13:49:57 -070085 self.spacing = ""
Brigid Smithea0a8352014-06-30 16:01:40 -070086
Prashanth Swaminathan01fd4182023-03-08 13:16:35 -080087 self.register_line = re.compile("(([ ]*\\b(" + self.register_names[symbol.ARCH] + ")\\b +[0-9a-f]" + self.width + "){1,5}$)")
Brigid Smithea0a8352014-06-30 16:01:40 -070088
89 # Note that both trace and value line matching allow for variable amounts of
90 # whitespace (e.g. \t). This is because the we want to allow for the stack
91 # tool to operate on AndroidFeedback provided system logs. AndroidFeedback
92 # strips out double spaces that are found in tombsone files and logcat output.
93 #
94 # Examples of matched trace lines include lines from tombstone files like:
95 # #00 pc 001cf42e /data/data/com.my.project/lib/libmyproject.so
96 #
97 # Or lines from AndroidFeedback crash report system logs like:
98 # 03-25 00:51:05.520 I/DEBUG ( 65): #00 pc 001cf42e /data/data/com.my.project/lib/libmyproject.so
99 # Please note the spacing differences.
Andreas Gamped900d082015-08-21 15:25:03 -0700100 self.trace_line = re.compile(
Krzysztof Kosińskib1361112021-03-11 18:05:01 -0800101 r".*" # Random start stuff.
102 r"\#(?P<frame>[0-9]+)" # Frame number.
103 r"[ \t]+..[ \t]+" # (space)pc(space).
104 r"(?P<offset>[0-9a-f]" + self.width + ")[ \t]+" # Offset (hex number given without
105 # 0x prefix).
106 r"(?P<dso>\[[^\]]+\]|[^\r\n \t]*)" # Library name.
107 r"( \(offset (?P<so_offset>0x[0-9a-fA-F]+)\))?" # Offset into the file to find the start of the shared so.
David Srbecky3a3349e2021-10-28 13:08:10 +0100108 r"(?P<symbolpresent> \((?P<symbol>.*?)\))?" # Is the symbol there? (non-greedy)
109 r"( \(BuildId: (?P<build_id>.*)\))?" # Optional build-id of the ELF file.
110 r"[ \t]*$") # End of line (to expand non-greedy match).
Krzysztof Kosińskib1361112021-03-11 18:05:01 -0800111 # pylint: disable-msg=C6310
Andreas Gamped900d082015-08-21 15:25:03 -0700112 # Sanitizer output. This is different from debuggerd output, and it is easier to handle this as
113 # its own regex. Example:
114 # 08-19 05:29:26.283 397 403 I : #0 0xb6a15237 (/system/lib/libclang_rt.asan-arm-android.so+0x4f237)
115 self.sanitizer_trace_line = re.compile(
Krzysztof Kosińskib1361112021-03-11 18:05:01 -0800116 r".*" # Random start stuff.
117 r"\#(?P<frame>[0-9]+)" # Frame number.
118 r"[ \t]+0x[0-9a-f]+[ \t]+" # PC, not interesting to us.
119 r"\(" # Opening paren.
120 r"(?P<dso>[^+]+)" # Library name.
121 r"\+" # '+'
122 r"0x(?P<offset>[0-9a-f]+)" # Offset (hex number given with
123 # 0x prefix).
124 r"\)") # Closing paren.
125 # pylint: disable-msg=C6310
Brigid Smithea0a8352014-06-30 16:01:40 -0700126 # Examples of matched value lines include:
127 # bea4170c 8018e4e9 /data/data/com.my.project/lib/libmyproject.so
128 # bea4170c 8018e4e9 /data/data/com.my.project/lib/libmyproject.so (symbol)
129 # 03-25 00:51:05.530 I/DEBUG ( 65): bea4170c 8018e4e9 /data/data/com.my.project/lib/libmyproject.so
130 # Again, note the spacing differences.
Krzysztof Kosińskib1361112021-03-11 18:05:01 -0800131 self.value_line = re.compile(r"(.*)([0-9a-f]" + self.width + r")[ \t]+([0-9a-f]" + self.width + r")[ \t]+([^\r\n \t]*)( \((.*)\))?")
Brigid Smithea0a8352014-06-30 16:01:40 -0700132 # Lines from 'code around' sections of the output will be matched before
133 # value lines because otheriwse the 'code around' sections will be confused as
134 # value lines.
135 #
136 # Examples include:
137 # 801cf40c ffffc4cc 00b2f2c5 00b2f1c7 00c1e1a8
138 # 03-25 00:51:05.530 I/DEBUG ( 65): 801cf40c ffffc4cc 00b2f2c5 00b2f1c7 00c1e1a8
Krzysztof Kosińskib1361112021-03-11 18:05:01 -0800139 self.code_line = re.compile(r"(.*)[ \t]*[a-f0-9]" + self.width +
140 r"[ \t]*[a-f0-9]" + self.width +
141 r"[ \t]*[a-f0-9]" + self.width +
142 r"[ \t]*[a-f0-9]" + self.width +
143 r"[ \t]*[a-f0-9]" + self.width +
144 r"[ \t]*[ \r\n]") # pylint: disable-msg=C6310
Brigid Smithea0a8352014-06-30 16:01:40 -0700145
146 def CleanLine(self, ln):
147 # AndroidFeedback adds zero width spaces into its crash reports. These
148 # should be removed or the regular expresssions will fail to match.
Krzysztof Kosińskib1361112021-03-11 18:05:01 -0800149 return ln.encode().decode(encoding='utf8', errors='ignore')
Brigid Smithea0a8352014-06-30 16:01:40 -0700150
151 def PrintTraceLines(self, trace_lines):
152 """Print back trace."""
Krzysztof Kosińskib1361112021-03-11 18:05:01 -0800153 maxlen = max(len(tl[1]) for tl in trace_lines)
154 print("\nStack Trace:")
155 print(" RELADDR " + self.spacing + "FUNCTION".ljust(maxlen) + " FILE:LINE")
Brigid Smithea0a8352014-06-30 16:01:40 -0700156 for tl in self.trace_lines:
157 (addr, symbol_with_offset, location) = tl
Krzysztof Kosińskib1361112021-03-11 18:05:01 -0800158 print(" %8s %s %s" % (addr, symbol_with_offset.ljust(maxlen), location))
Brigid Smithea0a8352014-06-30 16:01:40 -0700159
160 def PrintValueLines(self, value_lines):
161 """Print stack data values."""
Krzysztof Kosińskib1361112021-03-11 18:05:01 -0800162 maxlen = max(len(tl[2]) for tl in self.value_lines)
163 print("\nStack Data:")
164 print(" ADDR " + self.spacing + "VALUE " + "FUNCTION".ljust(maxlen) + " FILE:LINE")
Brigid Smithea0a8352014-06-30 16:01:40 -0700165 for vl in self.value_lines:
166 (addr, value, symbol_with_offset, location) = vl
Krzysztof Kosińskib1361112021-03-11 18:05:01 -0800167 print(" %8s %8s %s %s" % (addr, value, symbol_with_offset.ljust(maxlen), location))
Brigid Smithea0a8352014-06-30 16:01:40 -0700168
169 def PrintOutput(self, trace_lines, value_lines):
170 if self.trace_lines:
171 self.PrintTraceLines(self.trace_lines)
172 if self.value_lines:
173 self.PrintValueLines(self.value_lines)
174
175 def PrintDivider(self):
Krzysztof Kosińskib1361112021-03-11 18:05:01 -0800176 print("\n-----------------------------------------------------\n")
Brigid Smithea0a8352014-06-30 16:01:40 -0700177
Christopher Ferrisece64c42015-08-20 20:09:09 -0700178 def DeleteApkTmpFiles(self):
Christopher Ferrisabe22f42016-03-16 12:17:59 -0700179 for _, _, tmp_files in self.apk_info.values():
180 for tmp_file in tmp_files.values():
181 os.unlink(tmp_file)
Christopher Ferrisece64c42015-08-20 20:09:09 -0700182
Brigid Smithea0a8352014-06-30 16:01:40 -0700183 def ConvertTrace(self, lines):
Krzysztof Kosińskib1361112021-03-11 18:05:01 -0800184 lines = [self.CleanLine(line) for line in lines]
Christopher Ferrisece64c42015-08-20 20:09:09 -0700185 try:
Christopher Ferrisbf8a9402016-03-11 15:50:46 -0800186 if not symbol.ARCH:
187 symbol.SetAbi(lines)
188 self.UpdateAbiRegexes()
Christopher Ferrisece64c42015-08-20 20:09:09 -0700189 for line in lines:
190 self.ProcessLine(line)
191 self.PrintOutput(self.trace_lines, self.value_lines)
192 finally:
193 # Delete any temporary files created while processing the lines.
194 self.DeleteApkTmpFiles()
Brigid Smithea0a8352014-06-30 16:01:40 -0700195
Andreas Gamped900d082015-08-21 15:25:03 -0700196 def MatchTraceLine(self, line):
David Srbecky3a3349e2021-10-28 13:08:10 +0100197 match = self.trace_line.match(line)
198 if match:
Andreas Gamped900d082015-08-21 15:25:03 -0700199 return {"frame": match.group("frame"),
200 "offset": match.group("offset"),
Christopher Ferrisece64c42015-08-20 20:09:09 -0700201 "so_offset": match.group("so_offset"),
Andreas Gamped900d082015-08-21 15:25:03 -0700202 "dso": match.group("dso"),
203 "symbol_present": bool(match.group("symbolpresent")),
David Srbecky3a3349e2021-10-28 13:08:10 +0100204 "symbol_name": match.group("symbol"),
205 "build_id": match.group("build_id")}
206 match = self.sanitizer_trace_line.match(line)
207 if match:
Andreas Gamped900d082015-08-21 15:25:03 -0700208 return {"frame": match.group("frame"),
209 "offset": match.group("offset"),
Andreas Gampe57acd5f2015-09-17 11:44:21 -0700210 "so_offset": None,
Andreas Gamped900d082015-08-21 15:25:03 -0700211 "dso": match.group("dso"),
212 "symbol_present": False,
David Srbecky3a3349e2021-10-28 13:08:10 +0100213 "symbol_name": None,
214 "build_id": None}
Andreas Gamped900d082015-08-21 15:25:03 -0700215 return None
216
Christopher Ferrisece64c42015-08-20 20:09:09 -0700217 def ExtractLibFromApk(self, apk, shared_lib_name):
218 # Create a temporary file containing the shared library from the apk.
219 tmp_file = None
220 try:
221 tmp_fd, tmp_file = tempfile.mkstemp()
222 if subprocess.call(["unzip", "-p", apk, shared_lib_name], stdout=tmp_fd) == 0:
223 os.close(tmp_fd)
224 shared_file = tmp_file
225 tmp_file = None
226 return shared_file
227 finally:
228 if tmp_file:
229 os.close(tmp_fd)
230 os.unlink(tmp_file)
231 return None
232
Christopher Ferrisabe22f42016-03-16 12:17:59 -0700233 def ProcessCentralInfo(self, offset_list, central_info):
234 match = self.zipinfo_central_info_match.search(central_info)
235 if not match:
236 raise Exception("Cannot find all info from zipinfo\n" + central_info)
237 name = match.group(1)
238 start = int(match.group(2))
239 end = start + int(match.group(3))
240
241 offset_list.append([name, start, end])
242 return name, start, end
243
Christopher Ferrisece64c42015-08-20 20:09:09 -0700244 def GetLibFromApk(self, apk, offset):
245 # Convert the string to hex.
246 offset = int(offset, 16)
247
248 # Check if we already have information about this offset.
249 if apk in self.apk_info:
Christopher Ferrisabe22f42016-03-16 12:17:59 -0700250 apk_full_path, offset_list, tmp_files = self.apk_info[apk]
251 for file_name, start, end in offset_list:
252 if offset >= start and offset < end:
253 if file_name in tmp_files:
254 return file_name, tmp_files[file_name]
Christopher Ferrisece64c42015-08-20 20:09:09 -0700255 tmp_file = self.ExtractLibFromApk(apk_full_path, file_name)
256 if tmp_file:
Christopher Ferrisabe22f42016-03-16 12:17:59 -0700257 tmp_files[file_name] = tmp_file
Christopher Ferrisece64c42015-08-20 20:09:09 -0700258 return file_name, tmp_file
259 break
260 return None, None
261
262 if not "ANDROID_PRODUCT_OUT" in os.environ:
Krzysztof Kosińskib1361112021-03-11 18:05:01 -0800263 print("ANDROID_PRODUCT_OUT environment variable not set.")
Christopher Ferrisece64c42015-08-20 20:09:09 -0700264 return None, None
265 out_dir = os.environ["ANDROID_PRODUCT_OUT"]
266 if not os.path.exists(out_dir):
Krzysztof Kosińskib1361112021-03-11 18:05:01 -0800267 print("ANDROID_PRODUCT_OUT", out_dir, "does not exist.")
Christopher Ferrisece64c42015-08-20 20:09:09 -0700268 return None, None
269 if apk.startswith("/"):
270 apk_full_path = out_dir + apk
271 else:
272 apk_full_path = os.path.join(out_dir, apk)
273 if not os.path.exists(apk_full_path):
Krzysztof Kosińskib1361112021-03-11 18:05:01 -0800274 print("Cannot find apk", apk)
Christopher Ferrisece64c42015-08-20 20:09:09 -0700275 return None, None
276
Christopher Ferris7ea56f02021-10-21 00:20:18 +0000277 cmd = subprocess.Popen(["zipinfo", "-v", apk_full_path], stdout=subprocess.PIPE,
278 encoding='utf8')
Christopher Ferrisabe22f42016-03-16 12:17:59 -0700279 # Find the first central info marker.
280 for line in cmd.stdout:
281 if self.zipinfo_central_directory_line.search(line):
282 break
283
284 central_info = ""
285 file_name = None
Christopher Ferrisece64c42015-08-20 20:09:09 -0700286 offset_list = []
287 for line in cmd.stdout:
Christopher Ferrisabe22f42016-03-16 12:17:59 -0700288 match = self.zipinfo_central_directory_line.search(line)
Christopher Ferrisece64c42015-08-20 20:09:09 -0700289 if match:
Christopher Ferrisabe22f42016-03-16 12:17:59 -0700290 cur_name, start, end = self.ProcessCentralInfo(offset_list, central_info)
291 if not file_name and offset >= start and offset < end:
292 file_name = cur_name
293 central_info = ""
294 else:
295 central_info += line
296 if central_info:
297 cur_name, start, end = self.ProcessCentralInfo(offset_list, central_info)
298 if not file_name and offset >= start and offset < end:
299 file_name = cur_name
Christopher Ferrisece64c42015-08-20 20:09:09 -0700300
Christopher Ferris7ea56f02021-10-21 00:20:18 +0000301 # Make sure the offset_list is sorted, the zip file does not guarantee
302 # that the entries are in order.
303 offset_list = sorted(offset_list, key=lambda entry: entry[1])
304
Christopher Ferrisece64c42015-08-20 20:09:09 -0700305 # Save the information from the zip.
Christopher Ferrisabe22f42016-03-16 12:17:59 -0700306 tmp_files = dict()
307 self.apk_info[apk] = [apk_full_path, offset_list, tmp_files]
308 if not file_name:
Christopher Ferrisece64c42015-08-20 20:09:09 -0700309 return None, None
Christopher Ferrisabe22f42016-03-16 12:17:59 -0700310 tmp_shared_lib = self.ExtractLibFromApk(apk_full_path, file_name)
Christopher Ferrisece64c42015-08-20 20:09:09 -0700311 if tmp_shared_lib:
Christopher Ferrisabe22f42016-03-16 12:17:59 -0700312 tmp_files[file_name] = tmp_shared_lib
313 return file_name, tmp_shared_lib
Christopher Ferrisece64c42015-08-20 20:09:09 -0700314 return None, None
315
David Srbecky3a3349e2021-10-28 13:08:10 +0100316 # Find all files in the symbols directory and group them by basename (without directory).
David Srbeckydf6d4822021-10-29 11:35:18 +0100317 @functools.lru_cache(maxsize=None)
David Srbecky3a3349e2021-10-28 13:08:10 +0100318 def GlobSymbolsDir(self, symbols_dir):
319 files_by_basename = {}
320 for path in sorted(pathlib.Path(symbols_dir).glob("**/*")):
Christopher Ferrise6e02b02022-11-08 17:47:37 -0800321 if os.path.isfile(path):
322 files_by_basename.setdefault(path.name, []).append(path)
David Srbecky3a3349e2021-10-28 13:08:10 +0100323 return files_by_basename
324
325 # Use the "file" command line tool to find the bitness and build_id of given ELF file.
David Srbeckydf6d4822021-10-29 11:35:18 +0100326 @functools.lru_cache(maxsize=None)
David Srbecky3a3349e2021-10-28 13:08:10 +0100327 def GetLibraryInfo(self, lib):
Christopher Ferris29fcc842022-11-02 17:33:30 -0700328 stdout = subprocess.check_output([symbol.ToolPath("llvm-readelf"), "-h", "-n", lib], text=True)
329 match = self.readelf_output.search(stdout)
David Srbecky3a3349e2021-10-28 13:08:10 +0100330 if match:
331 return self.ElfInfo(bitness=match.group("bitness"), build_id=match.group("build_id"))
332 return None
333
334 # Search for a library with the given basename and build_id anywhere in the symbols directory.
David Srbeckydf6d4822021-10-29 11:35:18 +0100335 @functools.lru_cache(maxsize=None)
David Srbecky3a3349e2021-10-28 13:08:10 +0100336 def GetLibraryByBuildId(self, symbols_dir, basename, build_id):
Christopher Ferris27bee5a2022-01-25 13:05:53 -0800337 for candidate in self.GlobSymbolsDir(symbols_dir).get(basename, []):
David Srbecky3a3349e2021-10-28 13:08:10 +0100338 info = self.GetLibraryInfo(candidate)
339 if info and info.build_id == build_id:
340 return "/" + str(candidate.relative_to(symbols_dir))
341 return None
342
Christopher Ferris1f2051d2021-09-10 14:41:00 -0700343 def GetLibPath(self, lib):
Christopher Ferris29fcc842022-11-02 17:33:30 -0700344 if lib in self.lib_to_path:
345 return self.lib_to_path[lib]
346
347 lib_path = self.FindLibPath(lib)
348 self.lib_to_path[lib] = lib_path
349 return lib_path
350
351 def FindLibPath(self, lib):
Christopher Ferris1f2051d2021-09-10 14:41:00 -0700352 symbol_dir = symbol.SYMBOLS_DIR
353 if os.path.isfile(symbol_dir + lib):
354 return lib
355
Christopher Ferris598cc362022-04-22 14:37:56 -0700356 # Try and rewrite any apex files if not found in symbols.
357 # For some reason, the directory in symbols does not match
358 # the path on system.
359 # The path is com.android.<directory> on device, but
360 # com.google.android.<directory> in symbols.
361 new_lib = lib.replace("/com.android.", "/com.google.android.")
362 if os.path.isfile(symbol_dir + new_lib):
363 return new_lib
364
Christopher Ferris1f2051d2021-09-10 14:41:00 -0700365 # When using atest, test paths are different between the out/ directory
366 # and device. Apply fixups.
367 if not lib.startswith("/data/local/tests/") and not lib.startswith("/data/local/tmp/"):
368 print("WARNING: Cannot find %s in symbol directory" % lib)
369 return lib
370
371 test_name = lib.rsplit("/", 1)[-1]
372 test_dir = "/data/nativetest"
373 test_dir_bitness = ""
374 if symbol.ARCH.endswith("64"):
375 bitness = "64"
376 test_dir_bitness = "64"
377 else:
378 bitness = "32"
379
380 # Unfortunately, the location of the real symbol file is not
381 # standardized, so we need to go hunting for it.
382
383 # This is in vendor, look for the value in:
384 # /data/nativetest{64}/vendor/test_name/test_name
385 if lib.startswith("/data/local/tests/vendor/"):
Christopher Ferris29fcc842022-11-02 17:33:30 -0700386 lib_path = os.path.join(test_dir + test_dir_bitness, "vendor", test_name, test_name)
387 if os.path.isfile(symbol_dir + lib_path):
388 return lib_path
Christopher Ferris1f2051d2021-09-10 14:41:00 -0700389
390 # Look for the path in:
391 # /data/nativetest{64}/test_name/test_name
392 lib_path = os.path.join(test_dir + test_dir_bitness, test_name, test_name)
393 if os.path.isfile(symbol_dir + lib_path):
394 return lib_path
395
396 # CtsXXX tests are in really non-standard locations try:
397 # /data/nativetest/{test_name}
398 lib_path = os.path.join(test_dir, test_name)
399 if os.path.isfile(symbol_dir + lib_path):
400 return lib_path
401 # Try:
402 # /data/nativetest/{test_name}{32|64}
403 lib_path += bitness
404 if os.path.isfile(symbol_dir + lib_path):
405 return lib_path
406
407 # Cannot find location, give up and return the original path
408 print("WARNING: Cannot find %s in symbol directory" % lib)
409 return lib
410
411
Brigid Smithea0a8352014-06-30 16:01:40 -0700412 def ProcessLine(self, line):
Brigid Smith9c2192a2014-07-07 10:33:21 -0700413 ret = False
Brigid Smithea0a8352014-06-30 16:01:40 -0700414 process_header = self.process_info_line.search(line)
415 signal_header = self.signal_line.search(line)
416 abort_message_header = self.abort_message_line.search(line)
417 thread_header = self.thread_line.search(line)
418 register_header = self.register_line.search(line)
Brigid Smith0b309402014-07-07 14:34:00 -0700419 revision_header = self.revision_line.search(line)
Brigid Smithea0a8352014-06-30 16:01:40 -0700420 dalvik_jni_thread_header = self.dalvik_jni_thread_line.search(line)
421 dalvik_native_thread_header = self.dalvik_native_thread_line.search(line)
Colin Cross807ec0e2016-03-04 17:29:01 -0800422 unreachable_header = self.unreachable_line.search(line)
Christopher Ferrisbf8a9402016-03-11 15:50:46 -0800423 if process_header or signal_header or abort_message_header or thread_header or \
Colin Cross807ec0e2016-03-04 17:29:01 -0800424 register_header or dalvik_jni_thread_header or dalvik_native_thread_header or \
425 revision_header or unreachable_header:
426 ret = True
Brigid Smithea0a8352014-06-30 16:01:40 -0700427 if self.trace_lines or self.value_lines:
428 self.PrintOutput(self.trace_lines, self.value_lines)
429 self.PrintDivider()
430 self.trace_lines = []
431 self.value_lines = []
432 self.last_frame = -1
Ben Chengb42dad02013-04-25 15:14:04 -0700433 if process_header:
Krzysztof Kosińskib1361112021-03-11 18:05:01 -0800434 print(process_header.group(1))
Ben Chengb42dad02013-04-25 15:14:04 -0700435 if signal_header:
Krzysztof Kosińskib1361112021-03-11 18:05:01 -0800436 print(signal_header.group(1))
Elliott Hughesd2471c82014-06-17 16:55:10 -0700437 if abort_message_header:
Krzysztof Kosińskib1361112021-03-11 18:05:01 -0800438 print(abort_message_header.group(1))
Ben Chengb42dad02013-04-25 15:14:04 -0700439 if register_header:
Krzysztof Kosińskib1361112021-03-11 18:05:01 -0800440 print(register_header.group(1))
Ben Chengb42dad02013-04-25 15:14:04 -0700441 if thread_header:
Krzysztof Kosińskib1361112021-03-11 18:05:01 -0800442 print(thread_header.group(1))
Ben Chengb42dad02013-04-25 15:14:04 -0700443 if dalvik_jni_thread_header:
Krzysztof Kosińskib1361112021-03-11 18:05:01 -0800444 print(dalvik_jni_thread_header.group(1))
Ben Chengb42dad02013-04-25 15:14:04 -0700445 if dalvik_native_thread_header:
Krzysztof Kosińskib1361112021-03-11 18:05:01 -0800446 print(dalvik_native_thread_header.group(1))
Brigid Smith0b309402014-07-07 14:34:00 -0700447 if revision_header:
Krzysztof Kosińskib1361112021-03-11 18:05:01 -0800448 print(revision_header.group(1))
Colin Cross807ec0e2016-03-04 17:29:01 -0800449 if unreachable_header:
Krzysztof Kosińskib1361112021-03-11 18:05:01 -0800450 print(unreachable_header.group(1))
Christopher Ferrisbf8a9402016-03-11 15:50:46 -0800451 return True
Andreas Gamped900d082015-08-21 15:25:03 -0700452 trace_line_dict = self.MatchTraceLine(line)
453 if trace_line_dict is not None:
Brigid Smith9c2192a2014-07-07 10:33:21 -0700454 ret = True
Andreas Gampe48068ac2016-07-25 21:07:27 -0700455 frame = int(trace_line_dict["frame"])
Andreas Gamped900d082015-08-21 15:25:03 -0700456 code_addr = trace_line_dict["offset"]
457 area = trace_line_dict["dso"]
Christopher Ferrisece64c42015-08-20 20:09:09 -0700458 so_offset = trace_line_dict["so_offset"]
Andreas Gamped900d082015-08-21 15:25:03 -0700459 symbol_present = trace_line_dict["symbol_present"]
460 symbol_name = trace_line_dict["symbol_name"]
David Srbecky3a3349e2021-10-28 13:08:10 +0100461 build_id = trace_line_dict["build_id"]
Ben Chengb42dad02013-04-25 15:14:04 -0700462
Brigid Smithea0a8352014-06-30 16:01:40 -0700463 if frame <= self.last_frame and (self.trace_lines or self.value_lines):
464 self.PrintOutput(self.trace_lines, self.value_lines)
465 self.PrintDivider()
466 self.trace_lines = []
467 self.value_lines = []
468 self.last_frame = frame
Ben Chengb42dad02013-04-25 15:14:04 -0700469
Brigid Smithea0a8352014-06-30 16:01:40 -0700470 if area == "<unknown>" or area == "[heap]" or area == "[stack]":
471 self.trace_lines.append((code_addr, "", area))
Ben Chengb42dad02013-04-25 15:14:04 -0700472 else:
Christopher Ferrisece64c42015-08-20 20:09:09 -0700473 # If this is an apk, it usually means that there is actually
474 # a shared so that was loaded directly out of it. In that case,
475 # extract the shared library and the name of the shared library.
476 lib = None
Christopher Ferris55a96992019-03-13 15:37:31 -0700477 # The format of the map name:
478 # Some.apk!libshared.so
479 # or
480 # Some.apk
481 if so_offset:
482 # If it ends in apk, we are done.
483 apk = None
484 if area.endswith(".apk"):
485 apk = area
486 else:
Christopher Ferris5e4b3722020-01-31 14:38:07 -0800487 index = area.rfind(".so!")
Christopher Ferris55a96992019-03-13 15:37:31 -0700488 if index != -1:
Christopher Ferris5e4b3722020-01-31 14:38:07 -0800489 # Sometimes we'll see something like:
490 # #01 pc abcd libart.so!libart.so (offset 0x134000)
491 # Remove everything after the ! and zero the offset value.
492 area = area[0:index + 3]
493 so_offset = 0
494 else:
495 index = area.rfind(".apk!")
496 if index != -1:
497 apk = area[0:index + 4]
Christopher Ferrisac90d1d2019-03-15 12:21:57 -0700498 if apk:
Christopher Ferris55a96992019-03-13 15:37:31 -0700499 lib_name, lib = self.GetLibFromApk(apk, so_offset)
Christopher Ferris7d4d5272022-05-05 15:04:58 -0700500 else:
501 # Sometimes we'll see something like:
502 # #01 pc abcd libart.so!libart.so
503 # Remove everything after the !.
504 index = area.rfind(".so!")
505 if index != -1:
506 area = area[0:index + 3]
Christopher Ferrisece64c42015-08-20 20:09:09 -0700507 if not lib:
508 lib = area
509 lib_name = None
510
David Srbecky3a3349e2021-10-28 13:08:10 +0100511 if build_id:
512 # If we have the build_id, do a brute-force search of the symbols directory.
David Srbeckydf6d4822021-10-29 11:35:18 +0100513 basename = os.path.basename(lib)
514 lib = self.GetLibraryByBuildId(symbol.SYMBOLS_DIR, basename, build_id)
David Srbecky3a3349e2021-10-28 13:08:10 +0100515 if not lib:
516 print("WARNING: Cannot find {} with build id {} in symbols directory."
David Srbeckydf6d4822021-10-29 11:35:18 +0100517 .format(basename, build_id))
David Srbecky3a3349e2021-10-28 13:08:10 +0100518 else:
519 # When using atest, test paths are different between the out/ directory
520 # and device. Apply fixups.
521 lib = self.GetLibPath(lib)
Krzysztof Kosińskidd45e182021-02-24 15:21:50 -0800522
Ben Chengb42dad02013-04-25 15:14:04 -0700523 # If a calls b which further calls c and c is inlined to b, we want to
524 # display "a -> b -> c" in the stack trace instead of just "a -> c"
Christopher Ferrisece64c42015-08-20 20:09:09 -0700525 info = symbol.SymbolInformation(lib, code_addr)
Ben Chengb42dad02013-04-25 15:14:04 -0700526 nest_count = len(info) - 1
David Srbecky80547ae2021-11-01 21:59:59 +0000527 for (source_symbol, source_location, symbol_with_offset) in info:
Ben Chengb42dad02013-04-25 15:14:04 -0700528 if not source_symbol:
529 if symbol_present:
530 source_symbol = symbol.CallCppFilt(symbol_name)
531 else:
Brigid Smithea0a8352014-06-30 16:01:40 -0700532 source_symbol = "<unknown>"
David Srbecky80547ae2021-11-01 21:59:59 +0000533 if not symbol.VERBOSE:
534 source_symbol = symbol.FormatSymbolWithoutParameters(source_symbol)
535 symbol_with_offset = symbol.FormatSymbolWithoutParameters(symbol_with_offset)
Ben Chengb42dad02013-04-25 15:14:04 -0700536 if not source_location:
537 source_location = area
Christopher Ferrisece64c42015-08-20 20:09:09 -0700538 if lib_name:
539 source_location += "(" + lib_name + ")"
Ben Chengb42dad02013-04-25 15:14:04 -0700540 if nest_count > 0:
541 nest_count = nest_count - 1
Brigid Smithea0a8352014-06-30 16:01:40 -0700542 arrow = "v------>"
Prashanth Swaminathan01fd4182023-03-08 13:16:35 -0800543 if symbol.ARCH == "arm64" or symbol.ARCH == "x86_64" or symbol.ARCH == "riscv64":
Brigid Smithea0a8352014-06-30 16:01:40 -0700544 arrow = "v-------------->"
545 self.trace_lines.append((arrow, source_symbol, source_location))
Ben Chengb42dad02013-04-25 15:14:04 -0700546 else:
David Srbecky80547ae2021-11-01 21:59:59 +0000547 if not symbol_with_offset:
548 symbol_with_offset = source_symbol
549 self.trace_lines.append((code_addr, symbol_with_offset, source_location))
Brigid Smithea0a8352014-06-30 16:01:40 -0700550 if self.code_line.match(line):
Ben Chengb42dad02013-04-25 15:14:04 -0700551 # Code lines should be ignored. If this were exluded the 'code around'
552 # sections would trigger value_line matches.
Brigid Smith9c2192a2014-07-07 10:33:21 -0700553 return ret
Brigid Smithea0a8352014-06-30 16:01:40 -0700554 if self.value_line.match(line):
Brigid Smith9c2192a2014-07-07 10:33:21 -0700555 ret = True
Brigid Smithea0a8352014-06-30 16:01:40 -0700556 match = self.value_line.match(line)
Ben Chengb42dad02013-04-25 15:14:04 -0700557 (unused_, addr, value, area, symbol_present, symbol_name) = match.groups()
Brigid Smithea0a8352014-06-30 16:01:40 -0700558 if area == "<unknown>" or area == "[heap]" or area == "[stack]" or not area:
559 self.value_lines.append((addr, value, "", area))
Ben Chengb42dad02013-04-25 15:14:04 -0700560 else:
561 info = symbol.SymbolInformation(area, value)
562 (source_symbol, source_location, object_symbol_with_offset) = info.pop()
Christopher Ferris5f1b4f02016-09-19 13:24:37 -0700563 # If there is no information, skip this.
564 if source_symbol or source_location or object_symbol_with_offset:
565 if not source_symbol:
566 if symbol_present:
567 source_symbol = symbol.CallCppFilt(symbol_name)
568 else:
569 source_symbol = "<unknown>"
570 if not source_location:
571 source_location = area
572 if not object_symbol_with_offset:
573 object_symbol_with_offset = source_symbol
574 self.value_lines.append((addr,
575 value,
576 object_symbol_with_offset,
577 source_location))
Ben Chengb42dad02013-04-25 15:14:04 -0700578
Brigid Smith9c2192a2014-07-07 10:33:21 -0700579 return ret
Elliott Hughesa9e34172014-07-01 14:56:22 -0700580
581
Elliott Hughesa9e34172014-07-01 14:56:22 -0700582class RegisterPatternTests(unittest.TestCase):
583 def assert_register_matches(self, abi, example_crash, stupid_pattern):
584 tc = TraceConverter()
Christopher Ferrisbf8a9402016-03-11 15:50:46 -0800585 lines = example_crash.split('\n')
586 symbol.SetAbi(lines)
587 tc.UpdateAbiRegexes()
588 for line in lines:
Elliott Hughesc3c86192014-08-29 13:49:57 -0700589 tc.ProcessLine(line)
Elliott Hughesa9e34172014-07-01 14:56:22 -0700590 is_register = (re.search(stupid_pattern, line) is not None)
591 matched = (tc.register_line.search(line) is not None)
Krzysztof Kosińskib1361112021-03-11 18:05:01 -0800592 self.assertEqual(matched, is_register, line)
Elliott Hughesc3c86192014-08-29 13:49:57 -0700593 tc.PrintOutput(tc.trace_lines, tc.value_lines)
Elliott Hughesa9e34172014-07-01 14:56:22 -0700594
595 def test_arm_registers(self):
Elliott Hughesc3166be2014-07-07 15:06:28 -0700596 self.assert_register_matches("arm", example_crashes.arm, '\\b(r0|r4|r8|ip)\\b')
Elliott Hughesa9e34172014-07-01 14:56:22 -0700597
598 def test_arm64_registers(self):
Elliott Hughesc3166be2014-07-07 15:06:28 -0700599 self.assert_register_matches("arm64", example_crashes.arm64, '\\b(x0|x4|x8|x12|x16|x20|x24|x28|sp)\\b')
Elliott Hughesa9e34172014-07-01 14:56:22 -0700600
Elliott Hughesa9e34172014-07-01 14:56:22 -0700601 def test_x86_registers(self):
Elliott Hughesc3166be2014-07-07 15:06:28 -0700602 self.assert_register_matches("x86", example_crashes.x86, '\\b(eax|esi|xcs|eip)\\b')
Elliott Hughesa9e34172014-07-01 14:56:22 -0700603
604 def test_x86_64_registers(self):
Elliott Hughesc3166be2014-07-07 15:06:28 -0700605 self.assert_register_matches("x86_64", example_crashes.x86_64, '\\b(rax|rsi|r8|r12|cs|rip)\\b')
Elliott Hughesa9e34172014-07-01 14:56:22 -0700606
Prashanth Swaminathan01fd4182023-03-08 13:16:35 -0800607 def test_riscv64_registers(self):
608 self.assert_register_matches("riscv64", example_crashes.riscv64, '\\b(gp|t2|t6|s3|s7|s11|a3|a7|sp)\\b')
609
Colin Cross807ec0e2016-03-04 17:29:01 -0800610class LibmemunreachablePatternTests(unittest.TestCase):
611 def test_libmemunreachable(self):
612 tc = TraceConverter()
613 lines = example_crashes.libmemunreachable.split('\n')
614
615 symbol.SetAbi(lines)
Krzysztof Kosińskib1361112021-03-11 18:05:01 -0800616 self.assertEqual(symbol.ARCH, "arm")
Colin Cross807ec0e2016-03-04 17:29:01 -0800617
618 tc.UpdateAbiRegexes()
619 header_lines = 0
Colin Cross1127df92016-07-26 10:15:01 -0700620 trace_lines = 0
Colin Cross807ec0e2016-03-04 17:29:01 -0800621 for line in lines:
622 tc.ProcessLine(line)
623 if re.search(tc.unreachable_line, line) is not None:
624 header_lines += 1
Colin Cross1127df92016-07-26 10:15:01 -0700625 if tc.MatchTraceLine(line) is not None:
626 trace_lines += 1
Krzysztof Kosińskib1361112021-03-11 18:05:01 -0800627 self.assertEqual(header_lines, 3)
628 self.assertEqual(trace_lines, 2)
Colin Cross807ec0e2016-03-04 17:29:01 -0800629 tc.PrintOutput(tc.trace_lines, tc.value_lines)
Elliott Hughesa9e34172014-07-01 14:56:22 -0700630
Andreas Gampe48068ac2016-07-25 21:07:27 -0700631class LongASANStackTests(unittest.TestCase):
632 # Test that a long ASAN-style (non-padded frame numbers) stack trace is not split into two
633 # when the frame number becomes two digits. This happened before as the frame number was
634 # handled as a string and not converted to an integral.
635 def test_long_asan_crash(self):
636 tc = TraceConverter()
637 lines = example_crashes.long_asan_crash.splitlines()
638 symbol.SetAbi(lines)
639 tc.UpdateAbiRegexes()
640 # Test by making sure trace_line_count is monotonically non-decreasing. If the stack trace
641 # is split, a separator is printed and trace_lines is flushed.
642 trace_line_count = 0
643 for line in lines:
644 tc.ProcessLine(line)
645 self.assertLessEqual(trace_line_count, len(tc.trace_lines))
646 trace_line_count = len(tc.trace_lines)
647 # The split happened at transition of frame #9 -> #10. Make sure we have parsed (and stored)
648 # more than ten frames.
649 self.assertGreater(trace_line_count, 10)
650 tc.PrintOutput(tc.trace_lines, tc.value_lines)
651
Christopher Ferris5f1b4f02016-09-19 13:24:37 -0700652class ValueLinesTest(unittest.TestCase):
653 def test_value_line_skipped(self):
654 tc = TraceConverter()
655 symbol.SetAbi(["ABI: 'arm'"])
656 tc.UpdateAbiRegexes()
657 tc.ProcessLine(" 12345678 00001000 .")
658 self.assertEqual([], tc.value_lines)
659
Elliott Hughesa9e34172014-07-01 14:56:22 -0700660if __name__ == '__main__':
Krzysztof Kosińskib1361112021-03-11 18:05:01 -0800661 unittest.main(verbosity=2)