blob: 151255cb7f987cb907b650f55ed67887770e2534 [file] [log] [blame]
Mike Frysinger69cb41d2013-08-11 20:08:19 -04001# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Generate minidump symbols for use by the Crash server.
6
7Note: This should be run inside the chroot.
8
9This produces files in the breakpad format required by minidump_stackwalk and
10the crash server to dump stack information.
11
12Basically it scans all the split .debug files in /build/$BOARD/usr/lib/debug/
13and converts them over using the `dump_syms` programs. Those plain text .sym
14files are then stored in /build/$BOARD/usr/lib/debug/breakpad/.
15
Mike Frysinger02e1e072013-11-10 22:11:34 -050016If you want to actually upload things, see upload_symbols.py.
17"""
Mike Frysinger69cb41d2013-08-11 20:08:19 -040018
19import collections
20import ctypes
Chris McDonaldb55b7032021-06-17 16:41:32 -060021import logging
Mike Frysinger69cb41d2013-08-11 20:08:19 -040022import multiprocessing
23import os
Mike Frysinger69cb41d2013-08-11 20:08:19 -040024
Chris McDonaldb55b7032021-06-17 16:41:32 -060025from chromite.cbuildbot import cbuildbot_alerts
Mike Frysinger06a51c82021-04-06 11:39:17 -040026from chromite.lib import build_target_lib
Mike Frysinger69cb41d2013-08-11 20:08:19 -040027from chromite.lib import commandline
28from chromite.lib import cros_build_lib
29from chromite.lib import osutils
30from chromite.lib import parallel
Mike Frysinger96ad3f22014-04-24 23:27:27 -040031from chromite.lib import signals
Alex Klein1809f572021-09-09 11:28:37 -060032from chromite.utils import file_util
Mike Frysinger69cb41d2013-08-11 20:08:19 -040033
Stephen Boydfc1c8032021-10-06 20:58:37 -070034# Elf files that don't exist but have a split .debug file installed.
35ALLOWED_DEBUG_ONLY_FILES = {
36 'boot/vmlinux',
37}
Mike Frysinger69cb41d2013-08-11 20:08:19 -040038
39SymbolHeader = collections.namedtuple('SymbolHeader',
40 ('cpu', 'id', 'name', 'os',))
41
42
43def ReadSymsHeader(sym_file):
44 """Parse the header of the symbol file
45
46 The first line of the syms file will read like:
47 MODULE Linux arm F4F6FA6CCBDEF455039C8DE869C8A2F40 blkid
48
49 https://code.google.com/p/google-breakpad/wiki/SymbolFiles
50
51 Args:
52 sym_file: The symbol file to parse
Mike Frysinger1a736a82013-12-12 01:50:59 -050053
Mike Frysinger69cb41d2013-08-11 20:08:19 -040054 Returns:
55 A SymbolHeader object
Mike Frysinger1a736a82013-12-12 01:50:59 -050056
Mike Frysinger69cb41d2013-08-11 20:08:19 -040057 Raises:
58 ValueError if the first line of |sym_file| is invalid
59 """
Alex Klein1809f572021-09-09 11:28:37 -060060 with file_util.Open(sym_file, 'rb') as f:
Mike Frysinger374ba4f2019-11-14 23:45:15 -050061 header = f.readline().decode('utf-8').split()
Mike Frysinger69cb41d2013-08-11 20:08:19 -040062
63 if header[0] != 'MODULE' or len(header) != 5:
64 raise ValueError('header of sym file is invalid')
Mike Frysinger50cedd32014-02-09 23:03:18 -050065
Mike Frysinger69cb41d2013-08-11 20:08:19 -040066 return SymbolHeader(os=header[1], cpu=header[2], id=header[3], name=header[4])
67
68
69def GenerateBreakpadSymbol(elf_file, debug_file=None, breakpad_dir=None,
Don Garrett39f0dc62015-09-24 15:18:31 -070070 strip_cfi=False, num_errors=None,
71 dump_syms_cmd='dump_syms'):
Mike Frysinger69cb41d2013-08-11 20:08:19 -040072 """Generate the symbols for |elf_file| using |debug_file|
73
74 Args:
75 elf_file: The file to dump symbols for
76 debug_file: Split debug file to use for symbol information
77 breakpad_dir: The dir to store the output symbol file in
Mike Frysinger69cb41d2013-08-11 20:08:19 -040078 strip_cfi: Do not generate CFI data
79 num_errors: An object to update with the error count (needs a .value member)
Don Garrett39f0dc62015-09-24 15:18:31 -070080 dump_syms_cmd: Command to use for dumping symbols.
Mike Frysinger1a736a82013-12-12 01:50:59 -050081
Mike Frysinger69cb41d2013-08-11 20:08:19 -040082 Returns:
Mike Frysinger5c219f02021-06-09 01:25:33 -040083 The name of symbol file written out on success, or the failure count.
Mike Frysinger69cb41d2013-08-11 20:08:19 -040084 """
Don Garrette548cff2015-09-23 14:36:21 -070085 assert breakpad_dir
Mike Frysinger69cb41d2013-08-11 20:08:19 -040086 if num_errors is None:
87 num_errors = ctypes.c_int()
Stephen Boydfc1c8032021-10-06 20:58:37 -070088 debug_file_only = not os.path.exists(elf_file)
Mike Frysinger69cb41d2013-08-11 20:08:19 -040089
Mike Frysinger2808deb2016-01-28 01:22:13 -050090 cmd_base = [dump_syms_cmd, '-v']
Mike Frysinger69cb41d2013-08-11 20:08:19 -040091 if strip_cfi:
92 cmd_base += ['-c']
93 # Some files will not be readable by non-root (e.g. set*id /bin/su).
94 needs_sudo = not os.access(elf_file, os.R_OK)
95
96 def _DumpIt(cmd_args):
97 if needs_sudo:
Mike Frysinger45602c72019-09-22 02:15:11 -040098 run_command = cros_build_lib.sudo_run
Mike Frysinger69cb41d2013-08-11 20:08:19 -040099 else:
Mike Frysinger45602c72019-09-22 02:15:11 -0400100 run_command = cros_build_lib.run
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400101 return run_command(
Mike Frysinger0282d222019-12-17 17:15:48 -0500102 cmd_base + cmd_args, stderr=True, stdout=temp.name,
Mike Frysingerf5a3b2d2019-12-12 14:36:17 -0500103 check=False, debug_level=logging.DEBUG)
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400104
105 def _CrashCheck(ret, msg):
106 if ret < 0:
Chris McDonaldb55b7032021-06-17 16:41:32 -0600107 cbuildbot_alerts.PrintBuildbotStepWarnings()
Ralph Nathan446aee92015-03-23 14:44:56 -0700108 logging.warning('dump_syms crashed with %s; %s',
109 signals.StrSignal(-ret), msg)
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400110
111 osutils.SafeMakedirs(breakpad_dir)
Mike Frysinger374ba4f2019-11-14 23:45:15 -0500112 with cros_build_lib.UnbufferedNamedTemporaryFile(
113 dir=breakpad_dir, delete=False) as temp:
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400114 if debug_file:
115 # Try to dump the symbols using the debug file like normal.
Stephen Boydfc1c8032021-10-06 20:58:37 -0700116 if debug_file_only:
117 cmd_args = [debug_file]
118 else:
119 cmd_args = [elf_file, os.path.dirname(debug_file)]
120
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400121 result = _DumpIt(cmd_args)
122
123 if result.returncode:
124 # Sometimes dump_syms can crash because there's too much info.
125 # Try dumping and stripping the extended stuff out. At least
Mike Frysingerdcad4e02018-08-03 16:20:02 -0400126 # this way we'll get the extended symbols. https://crbug.com/266064
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400127 _CrashCheck(result.returncode, 'retrying w/out CFI')
128 cmd_args = ['-c', '-r'] + cmd_args
129 result = _DumpIt(cmd_args)
130 _CrashCheck(result.returncode, 'retrying w/out debug')
131
132 basic_dump = result.returncode
133 else:
134 basic_dump = True
135
136 if basic_dump:
137 # If that didn't work (no debug, or dump_syms still failed), try
138 # dumping just the file itself directly.
139 result = _DumpIt([elf_file])
140 if result.returncode:
141 # A lot of files (like kernel files) contain no debug information,
142 # do not consider such occurrences as errors.
Chris McDonaldb55b7032021-06-17 16:41:32 -0600143 cbuildbot_alerts.PrintBuildbotStepWarnings()
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400144 _CrashCheck(result.returncode, 'giving up entirely')
Mike Frysinger374ba4f2019-11-14 23:45:15 -0500145 if b'file contains no debugging information' in result.stderr:
Ralph Nathan446aee92015-03-23 14:44:56 -0700146 logging.warning('no symbols found for %s', elf_file)
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400147 else:
148 num_errors.value += 1
Ralph Nathan59900422015-03-24 10:41:17 -0700149 logging.error('dumping symbols for %s failed:\n%s', elf_file,
Mike Frysingerd1c188d2021-06-09 01:16:26 -0400150 result.error.decode('utf-8'))
Mike Frysinger374ba4f2019-11-14 23:45:15 -0500151 os.unlink(temp.name)
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400152 return num_errors.value
153
154 # Move the dumped symbol file to the right place:
155 # /build/$BOARD/usr/lib/debug/breakpad/<module-name>/<id>/<module-name>.sym
156 header = ReadSymsHeader(temp)
Ralph Nathan03047282015-03-23 11:09:32 -0700157 logging.info('Dumped %s as %s : %s', elf_file, header.name, header.id)
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400158 sym_file = os.path.join(breakpad_dir, header.name, header.id,
159 header.name + '.sym')
160 osutils.SafeMakedirs(os.path.dirname(sym_file))
161 os.rename(temp.name, sym_file)
Mike Frysinger60ec1012013-10-21 00:11:10 -0400162 os.chmod(sym_file, 0o644)
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400163
Don Garrettc9de3ac2015-10-01 15:40:10 -0700164 return sym_file
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400165
166
167def GenerateBreakpadSymbols(board, breakpad_dir=None, strip_cfi=False,
Mike Frysingeref9ab2f2013-08-26 22:16:00 -0400168 generate_count=None, sysroot=None,
Shawn Nematbakhsh2c169cb2013-10-29 16:23:58 -0700169 num_processes=None, clean_breakpad=False,
Prathmesh Prabhu9995e9b2013-10-31 16:43:55 -0700170 exclude_dirs=(), file_list=None):
171 """Generate symbols for this board.
172
173 If |file_list| is None, symbols are generated for all executables, otherwise
174 only for the files included in |file_list|.
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400175
176 TODO(build):
177 This should be merged with buildbot_commands.GenerateBreakpadSymbols()
178 once we rewrite cros_generate_breakpad_symbols in python.
179
180 Args:
181 board: The board whose symbols we wish to generate
182 breakpad_dir: The full path to the breakpad directory where symbols live
183 strip_cfi: Do not generate CFI data
184 generate_count: If set, only generate this many symbols (meant for testing)
185 sysroot: The root where to find the corresponding ELFs
Mike Frysingeref9ab2f2013-08-26 22:16:00 -0400186 num_processes: Number of jobs to run in parallel
Mike Frysinger9a628bb2013-10-24 15:51:37 -0400187 clean_breakpad: Should we `rm -rf` the breakpad output dir first; note: we
188 do not do any locking, so do not run more than one in parallel when True
Shawn Nematbakhsh2c169cb2013-10-29 16:23:58 -0700189 exclude_dirs: List of dirs (relative to |sysroot|) to not search
Prathmesh Prabhu9995e9b2013-10-31 16:43:55 -0700190 file_list: Only generate symbols for files in this list. Each file must be a
191 full path (including |sysroot| prefix).
192 TODO(build): Support paths w/o |sysroot|.
Mike Frysinger1a736a82013-12-12 01:50:59 -0500193
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400194 Returns:
195 The number of errors that were encountered.
196 """
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400197 if sysroot is None:
Mike Frysinger06a51c82021-04-06 11:39:17 -0400198 sysroot = build_target_lib.get_default_sysroot_path(board)
Mike Frysinger3f571af2016-08-31 23:56:53 -0400199 if breakpad_dir is None:
200 breakpad_dir = FindBreakpadDir(board, sysroot=sysroot)
Mike Frysinger9a628bb2013-10-24 15:51:37 -0400201 if clean_breakpad:
Ralph Nathan03047282015-03-23 11:09:32 -0700202 logging.info('cleaning out %s first', breakpad_dir)
Mike Frysinger9a628bb2013-10-24 15:51:37 -0400203 osutils.RmDir(breakpad_dir, ignore_missing=True, sudo=True)
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400204 # Make sure non-root can write out symbols as needed.
205 osutils.SafeMakedirs(breakpad_dir, sudo=True)
206 if not os.access(breakpad_dir, os.W_OK):
Mike Frysinger45602c72019-09-22 02:15:11 -0400207 cros_build_lib.sudo_run(['chown', '-R', str(os.getuid()), breakpad_dir])
Mike Frysinger3f571af2016-08-31 23:56:53 -0400208 debug_dir = FindDebugDir(board, sysroot=sysroot)
Shawn Nematbakhsh2c169cb2013-10-29 16:23:58 -0700209 exclude_paths = [os.path.join(debug_dir, x) for x in exclude_dirs]
Prathmesh Prabhu9995e9b2013-10-31 16:43:55 -0700210 if file_list is None:
211 file_list = []
212 file_filter = dict.fromkeys([os.path.normpath(x) for x in file_list], False)
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400213
Ralph Nathan03047282015-03-23 11:09:32 -0700214 logging.info('generating breakpad symbols using %s', debug_dir)
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400215
Prathmesh Prabhu9995e9b2013-10-31 16:43:55 -0700216 # Let's locate all the debug_files and elfs first along with the debug file
217 # sizes. This way we can start processing the largest files first in parallel
218 # with the small ones.
219 # If |file_list| was given, ignore all other files.
220 targets = []
Shawn Nematbakhsh2c169cb2013-10-29 16:23:58 -0700221 for root, dirs, files in os.walk(debug_dir):
222 if root in exclude_paths:
Ralph Nathan03047282015-03-23 11:09:32 -0700223 logging.info('Skipping excluded dir %s', root)
Shawn Nematbakhsh2c169cb2013-10-29 16:23:58 -0700224 del dirs[:]
225 continue
226
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400227 for debug_file in files:
228 debug_file = os.path.join(root, debug_file)
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400229 # Turn /build/$BOARD/usr/lib/debug/sbin/foo.debug into
230 # /build/$BOARD/sbin/foo.
231 elf_file = os.path.join(sysroot, debug_file[len(debug_dir) + 1:-6])
Prathmesh Prabhu9995e9b2013-10-31 16:43:55 -0700232
233 if file_filter:
234 if elf_file in file_filter:
235 file_filter[elf_file] = True
236 elif debug_file in file_filter:
237 file_filter[debug_file] = True
238 else:
239 continue
240
241 # Filter out files based on common issues with the debug file.
242 if not debug_file.endswith('.debug'):
243 continue
244
Prathmesh Prabhu9995e9b2013-10-31 16:43:55 -0700245 elif os.path.islink(debug_file):
246 # The build-id stuff is common enough to filter out by default.
247 if '/.build-id/' in debug_file:
Ralph Nathan5a582ff2015-03-20 18:18:30 -0700248 msg = logging.debug
Prathmesh Prabhu9995e9b2013-10-31 16:43:55 -0700249 else:
Ralph Nathan446aee92015-03-23 14:44:56 -0700250 msg = logging.warning
Prathmesh Prabhu9995e9b2013-10-31 16:43:55 -0700251 msg('Skipping symbolic link %s', debug_file)
252 continue
253
254 # Filter out files based on common issues with the elf file.
Stephen Boydfc1c8032021-10-06 20:58:37 -0700255 elf_path = os.path.relpath(elf_file, sysroot)
256 debug_only = elf_path in ALLOWED_DEBUG_ONLY_FILES
257 if not os.path.exists(elf_file) and not debug_only:
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400258 # Sometimes we filter out programs from /usr/bin but leave behind
259 # the .debug file.
Ralph Nathan446aee92015-03-23 14:44:56 -0700260 logging.warning('Skipping missing %s', elf_file)
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400261 continue
262
Prathmesh Prabhu9995e9b2013-10-31 16:43:55 -0700263 targets.append((os.path.getsize(debug_file), elf_file, debug_file))
264
265 bg_errors = multiprocessing.Value('i')
266 if file_filter:
Mike Frysinger0bdbc102019-06-13 15:27:29 -0400267 files_not_found = [x for x, found in file_filter.items() if not found]
Prathmesh Prabhu9995e9b2013-10-31 16:43:55 -0700268 bg_errors.value += len(files_not_found)
269 if files_not_found:
Ralph Nathan59900422015-03-24 10:41:17 -0700270 logging.error('Failed to find requested files: %s', files_not_found)
Prathmesh Prabhu9995e9b2013-10-31 16:43:55 -0700271
272 # Now start generating symbols for the discovered elfs.
273 with parallel.BackgroundTaskRunner(GenerateBreakpadSymbol,
Don Garrette548cff2015-09-23 14:36:21 -0700274 breakpad_dir=breakpad_dir,
Prathmesh Prabhu9995e9b2013-10-31 16:43:55 -0700275 strip_cfi=strip_cfi,
276 num_errors=bg_errors,
277 processes=num_processes) as queue:
278 for _, elf_file, debug_file in sorted(targets, reverse=True):
279 if generate_count == 0:
280 break
281
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400282 queue.put([elf_file, debug_file])
283 if generate_count is not None:
284 generate_count -= 1
285 if generate_count == 0:
286 break
287
288 return bg_errors.value
289
290
Mike Frysinger3f571af2016-08-31 23:56:53 -0400291def FindDebugDir(board, sysroot=None):
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400292 """Given a |board|, return the path to the split debug dir for it"""
Mike Frysinger3f571af2016-08-31 23:56:53 -0400293 if sysroot is None:
Mike Frysinger06a51c82021-04-06 11:39:17 -0400294 sysroot = build_target_lib.get_default_sysroot_path(board)
Yu-Ju Hongdd9bb2b2014-01-03 17:08:26 -0800295 return os.path.join(sysroot, 'usr', 'lib', 'debug')
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400296
297
Mike Frysinger3f571af2016-08-31 23:56:53 -0400298def FindBreakpadDir(board, sysroot=None):
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400299 """Given a |board|, return the path to the breakpad dir for it"""
Mike Frysinger3f571af2016-08-31 23:56:53 -0400300 return os.path.join(FindDebugDir(board, sysroot=sysroot), 'breakpad')
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400301
302
303def main(argv):
304 parser = commandline.ArgumentParser(description=__doc__)
305
306 parser.add_argument('--board', default=None,
307 help='board to generate symbols for')
308 parser.add_argument('--breakpad_root', type='path', default=None,
Mike Frysinger3f571af2016-08-31 23:56:53 -0400309 help='root output directory for breakpad symbols')
310 parser.add_argument('--sysroot', type='path', default=None,
311 help='root input directory for files')
Shawn Nematbakhsh2c169cb2013-10-29 16:23:58 -0700312 parser.add_argument('--exclude-dir', type=str, action='append',
313 default=[],
314 help='directory (relative to |board| root) to not search')
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400315 parser.add_argument('--generate-count', type=int, default=None,
316 help='only generate # number of symbols')
Mike Frysinger9a628bb2013-10-24 15:51:37 -0400317 parser.add_argument('--noclean', dest='clean', action='store_false',
318 default=True,
319 help='do not clean out breakpad dir before running')
Mike Frysingeref9ab2f2013-08-26 22:16:00 -0400320 parser.add_argument('--jobs', type=int, default=None,
321 help='limit number of parallel jobs')
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400322 parser.add_argument('--strip_cfi', action='store_true', default=False,
323 help='do not generate CFI data (pass -c to dump_syms)')
Prathmesh Prabhu9995e9b2013-10-31 16:43:55 -0700324 parser.add_argument('file_list', nargs='*', default=None,
325 help='generate symbols for only these files '
326 '(e.g. /build/$BOARD/usr/bin/foo)')
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400327
328 opts = parser.parse_args(argv)
Mike Frysinger90e49ca2014-01-14 14:42:07 -0500329 opts.Freeze()
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400330
Mike Frysinger3f571af2016-08-31 23:56:53 -0400331 if opts.board is None and opts.sysroot is None:
332 cros_build_lib.Die('--board or --sysroot is required')
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400333
334 ret = GenerateBreakpadSymbols(opts.board, breakpad_dir=opts.breakpad_root,
335 strip_cfi=opts.strip_cfi,
Mike Frysingeref9ab2f2013-08-26 22:16:00 -0400336 generate_count=opts.generate_count,
Mike Frysinger3f571af2016-08-31 23:56:53 -0400337 sysroot=opts.sysroot,
Mike Frysinger9a628bb2013-10-24 15:51:37 -0400338 num_processes=opts.jobs,
Shawn Nematbakhsh2c169cb2013-10-29 16:23:58 -0700339 clean_breakpad=opts.clean,
Prathmesh Prabhu9995e9b2013-10-31 16:43:55 -0700340 exclude_dirs=opts.exclude_dir,
341 file_list=opts.file_list)
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400342 if ret:
Ralph Nathan59900422015-03-24 10:41:17 -0700343 logging.error('encountered %i problem(s)', ret)
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400344 # Since exit(status) gets masked, clamp it to 1 so we don't inadvertently
345 # return 0 in case we are a multiple of the mask.
346 ret = 1
347
348 return ret