blob: 68f04bca15d8e3aabd60f68341e15fcc71021327 [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
21import logging
22import multiprocessing
23import os
24import tempfile
25
26from chromite.lib import commandline
27from chromite.lib import cros_build_lib
28from chromite.lib import osutils
29from chromite.lib import parallel
Mike Frysinger96ad3f22014-04-24 23:27:27 -040030from chromite.lib import signals
Mike Frysinger69cb41d2013-08-11 20:08:19 -040031
32
33SymbolHeader = collections.namedtuple('SymbolHeader',
34 ('cpu', 'id', 'name', 'os',))
35
36
37def ReadSymsHeader(sym_file):
38 """Parse the header of the symbol file
39
40 The first line of the syms file will read like:
41 MODULE Linux arm F4F6FA6CCBDEF455039C8DE869C8A2F40 blkid
42
43 https://code.google.com/p/google-breakpad/wiki/SymbolFiles
44
45 Args:
46 sym_file: The symbol file to parse
Mike Frysinger1a736a82013-12-12 01:50:59 -050047
Mike Frysinger69cb41d2013-08-11 20:08:19 -040048 Returns:
49 A SymbolHeader object
Mike Frysinger1a736a82013-12-12 01:50:59 -050050
Mike Frysinger69cb41d2013-08-11 20:08:19 -040051 Raises:
52 ValueError if the first line of |sym_file| is invalid
53 """
Mike Frysinger50cedd32014-02-09 23:03:18 -050054 with cros_build_lib.Open(sym_file) as f:
55 header = f.readline().split()
Mike Frysinger69cb41d2013-08-11 20:08:19 -040056
57 if header[0] != 'MODULE' or len(header) != 5:
58 raise ValueError('header of sym file is invalid')
Mike Frysinger50cedd32014-02-09 23:03:18 -050059
Mike Frysinger69cb41d2013-08-11 20:08:19 -040060 return SymbolHeader(os=header[1], cpu=header[2], id=header[3], name=header[4])
61
62
63def GenerateBreakpadSymbol(elf_file, debug_file=None, breakpad_dir=None,
64 board=None, strip_cfi=False, num_errors=None):
65 """Generate the symbols for |elf_file| using |debug_file|
66
67 Args:
68 elf_file: The file to dump symbols for
69 debug_file: Split debug file to use for symbol information
70 breakpad_dir: The dir to store the output symbol file in
71 board: If |breakpad_dir| is not specified, use |board| to find it
72 strip_cfi: Do not generate CFI data
73 num_errors: An object to update with the error count (needs a .value member)
Mike Frysinger1a736a82013-12-12 01:50:59 -050074
Mike Frysinger69cb41d2013-08-11 20:08:19 -040075 Returns:
76 The number of errors that were encountered.
77 """
78 if breakpad_dir is None:
79 breakpad_dir = FindBreakpadDir(board)
80 if num_errors is None:
81 num_errors = ctypes.c_int()
82
83 cmd_base = ['dump_syms']
84 if strip_cfi:
85 cmd_base += ['-c']
86 # Some files will not be readable by non-root (e.g. set*id /bin/su).
87 needs_sudo = not os.access(elf_file, os.R_OK)
88
89 def _DumpIt(cmd_args):
90 if needs_sudo:
91 run_command = cros_build_lib.SudoRunCommand
92 else:
93 run_command = cros_build_lib.RunCommand
94 return run_command(
95 cmd_base + cmd_args, redirect_stderr=True, log_stdout_to_file=temp.name,
96 error_code_ok=True, debug_level=logging.DEBUG)
97
98 def _CrashCheck(ret, msg):
99 if ret < 0:
100 cros_build_lib.PrintBuildbotStepWarnings()
101 cros_build_lib.Warning('dump_syms crashed with %s; %s',
Mike Frysinger96ad3f22014-04-24 23:27:27 -0400102 signals.StrSignal(-ret), msg)
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400103
104 osutils.SafeMakedirs(breakpad_dir)
105 with tempfile.NamedTemporaryFile(dir=breakpad_dir, bufsize=0) as temp:
106 if debug_file:
107 # Try to dump the symbols using the debug file like normal.
108 cmd_args = [elf_file, os.path.dirname(debug_file)]
109 result = _DumpIt(cmd_args)
110
111 if result.returncode:
112 # Sometimes dump_syms can crash because there's too much info.
113 # Try dumping and stripping the extended stuff out. At least
114 # this way we'll get the extended symbols. http://crbug.com/266064
115 _CrashCheck(result.returncode, 'retrying w/out CFI')
116 cmd_args = ['-c', '-r'] + cmd_args
117 result = _DumpIt(cmd_args)
118 _CrashCheck(result.returncode, 'retrying w/out debug')
119
120 basic_dump = result.returncode
121 else:
122 basic_dump = True
123
124 if basic_dump:
125 # If that didn't work (no debug, or dump_syms still failed), try
126 # dumping just the file itself directly.
127 result = _DumpIt([elf_file])
128 if result.returncode:
129 # A lot of files (like kernel files) contain no debug information,
130 # do not consider such occurrences as errors.
131 cros_build_lib.PrintBuildbotStepWarnings()
132 _CrashCheck(result.returncode, 'giving up entirely')
133 if 'file contains no debugging information' in result.error:
134 cros_build_lib.Warning('no symbols found for %s', elf_file)
135 else:
136 num_errors.value += 1
137 cros_build_lib.Error('dumping symbols for %s failed:\n%s',
138 elf_file, result.error)
139 return num_errors.value
140
141 # Move the dumped symbol file to the right place:
142 # /build/$BOARD/usr/lib/debug/breakpad/<module-name>/<id>/<module-name>.sym
143 header = ReadSymsHeader(temp)
144 cros_build_lib.Info('Dumped %s as %s : %s', elf_file, header.name,
145 header.id)
146 sym_file = os.path.join(breakpad_dir, header.name, header.id,
147 header.name + '.sym')
148 osutils.SafeMakedirs(os.path.dirname(sym_file))
149 os.rename(temp.name, sym_file)
Mike Frysinger60ec1012013-10-21 00:11:10 -0400150 os.chmod(sym_file, 0o644)
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400151 temp.delete = False
152
153 return num_errors.value
154
155
156def GenerateBreakpadSymbols(board, breakpad_dir=None, strip_cfi=False,
Mike Frysingeref9ab2f2013-08-26 22:16:00 -0400157 generate_count=None, sysroot=None,
Shawn Nematbakhsh2c169cb2013-10-29 16:23:58 -0700158 num_processes=None, clean_breakpad=False,
Prathmesh Prabhu9995e9b2013-10-31 16:43:55 -0700159 exclude_dirs=(), file_list=None):
160 """Generate symbols for this board.
161
162 If |file_list| is None, symbols are generated for all executables, otherwise
163 only for the files included in |file_list|.
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400164
165 TODO(build):
166 This should be merged with buildbot_commands.GenerateBreakpadSymbols()
167 once we rewrite cros_generate_breakpad_symbols in python.
168
169 Args:
170 board: The board whose symbols we wish to generate
171 breakpad_dir: The full path to the breakpad directory where symbols live
172 strip_cfi: Do not generate CFI data
173 generate_count: If set, only generate this many symbols (meant for testing)
174 sysroot: The root where to find the corresponding ELFs
Mike Frysingeref9ab2f2013-08-26 22:16:00 -0400175 num_processes: Number of jobs to run in parallel
Mike Frysinger9a628bb2013-10-24 15:51:37 -0400176 clean_breakpad: Should we `rm -rf` the breakpad output dir first; note: we
177 do not do any locking, so do not run more than one in parallel when True
Shawn Nematbakhsh2c169cb2013-10-29 16:23:58 -0700178 exclude_dirs: List of dirs (relative to |sysroot|) to not search
Prathmesh Prabhu9995e9b2013-10-31 16:43:55 -0700179 file_list: Only generate symbols for files in this list. Each file must be a
180 full path (including |sysroot| prefix).
181 TODO(build): Support paths w/o |sysroot|.
Mike Frysinger1a736a82013-12-12 01:50:59 -0500182
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400183 Returns:
184 The number of errors that were encountered.
185 """
186 if breakpad_dir is None:
187 breakpad_dir = FindBreakpadDir(board)
188 if sysroot is None:
Yu-Ju Hongdd9bb2b2014-01-03 17:08:26 -0800189 sysroot = cros_build_lib.GetSysroot(board=board)
Mike Frysinger9a628bb2013-10-24 15:51:37 -0400190 if clean_breakpad:
191 cros_build_lib.Info('cleaning out %s first', breakpad_dir)
192 osutils.RmDir(breakpad_dir, ignore_missing=True, sudo=True)
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400193 # Make sure non-root can write out symbols as needed.
194 osutils.SafeMakedirs(breakpad_dir, sudo=True)
195 if not os.access(breakpad_dir, os.W_OK):
196 cros_build_lib.SudoRunCommand(['chown', '-R', str(os.getuid()),
197 breakpad_dir])
198 debug_dir = FindDebugDir(board)
Shawn Nematbakhsh2c169cb2013-10-29 16:23:58 -0700199 exclude_paths = [os.path.join(debug_dir, x) for x in exclude_dirs]
Prathmesh Prabhu9995e9b2013-10-31 16:43:55 -0700200 if file_list is None:
201 file_list = []
202 file_filter = dict.fromkeys([os.path.normpath(x) for x in file_list], False)
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400203
Prathmesh Prabhu9995e9b2013-10-31 16:43:55 -0700204 cros_build_lib.Info('generating breakpad symbols using %s', debug_dir)
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400205
Prathmesh Prabhu9995e9b2013-10-31 16:43:55 -0700206 # Let's locate all the debug_files and elfs first along with the debug file
207 # sizes. This way we can start processing the largest files first in parallel
208 # with the small ones.
209 # If |file_list| was given, ignore all other files.
210 targets = []
Shawn Nematbakhsh2c169cb2013-10-29 16:23:58 -0700211 for root, dirs, files in os.walk(debug_dir):
212 if root in exclude_paths:
213 cros_build_lib.Info('Skipping excluded dir %s', root)
214 del dirs[:]
215 continue
216
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400217 for debug_file in files:
218 debug_file = os.path.join(root, debug_file)
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400219 # Turn /build/$BOARD/usr/lib/debug/sbin/foo.debug into
220 # /build/$BOARD/sbin/foo.
221 elf_file = os.path.join(sysroot, debug_file[len(debug_dir) + 1:-6])
Prathmesh Prabhu9995e9b2013-10-31 16:43:55 -0700222
223 if file_filter:
224 if elf_file in file_filter:
225 file_filter[elf_file] = True
226 elif debug_file in file_filter:
227 file_filter[debug_file] = True
228 else:
229 continue
230
231 # Filter out files based on common issues with the debug file.
232 if not debug_file.endswith('.debug'):
233 continue
234
235 elif debug_file.endswith('.ko.debug'):
236 cros_build_lib.Debug('Skipping kernel module %s', debug_file)
237 continue
238
239 elif os.path.islink(debug_file):
240 # The build-id stuff is common enough to filter out by default.
241 if '/.build-id/' in debug_file:
242 msg = cros_build_lib.Debug
243 else:
244 msg = cros_build_lib.Warning
245 msg('Skipping symbolic link %s', debug_file)
246 continue
247
248 # Filter out files based on common issues with the elf file.
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400249 if not os.path.exists(elf_file):
250 # Sometimes we filter out programs from /usr/bin but leave behind
251 # the .debug file.
252 cros_build_lib.Warning('Skipping missing %s', elf_file)
253 continue
254
Prathmesh Prabhu9995e9b2013-10-31 16:43:55 -0700255 targets.append((os.path.getsize(debug_file), elf_file, debug_file))
256
257 bg_errors = multiprocessing.Value('i')
258 if file_filter:
259 files_not_found = [x for x, found in file_filter.iteritems() if not found]
260 bg_errors.value += len(files_not_found)
261 if files_not_found:
262 cros_build_lib.Error('Failed to find requested files: %s',
263 files_not_found)
264
265 # Now start generating symbols for the discovered elfs.
266 with parallel.BackgroundTaskRunner(GenerateBreakpadSymbol,
267 breakpad_dir=breakpad_dir, board=board,
268 strip_cfi=strip_cfi,
269 num_errors=bg_errors,
270 processes=num_processes) as queue:
271 for _, elf_file, debug_file in sorted(targets, reverse=True):
272 if generate_count == 0:
273 break
274
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400275 queue.put([elf_file, debug_file])
276 if generate_count is not None:
277 generate_count -= 1
278 if generate_count == 0:
279 break
280
281 return bg_errors.value
282
283
284def FindDebugDir(board):
285 """Given a |board|, return the path to the split debug dir for it"""
Yu-Ju Hongdd9bb2b2014-01-03 17:08:26 -0800286 sysroot = cros_build_lib.GetSysroot(board=board)
287 return os.path.join(sysroot, 'usr', 'lib', 'debug')
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400288
289
290def FindBreakpadDir(board):
291 """Given a |board|, return the path to the breakpad dir for it"""
292 return os.path.join(FindDebugDir(board), 'breakpad')
293
294
295def main(argv):
296 parser = commandline.ArgumentParser(description=__doc__)
297
298 parser.add_argument('--board', default=None,
299 help='board to generate symbols for')
300 parser.add_argument('--breakpad_root', type='path', default=None,
301 help='root directory for breakpad symbols')
Shawn Nematbakhsh2c169cb2013-10-29 16:23:58 -0700302 parser.add_argument('--exclude-dir', type=str, action='append',
303 default=[],
304 help='directory (relative to |board| root) to not search')
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400305 parser.add_argument('--generate-count', type=int, default=None,
306 help='only generate # number of symbols')
Mike Frysinger9a628bb2013-10-24 15:51:37 -0400307 parser.add_argument('--noclean', dest='clean', action='store_false',
308 default=True,
309 help='do not clean out breakpad dir before running')
Mike Frysingeref9ab2f2013-08-26 22:16:00 -0400310 parser.add_argument('--jobs', type=int, default=None,
311 help='limit number of parallel jobs')
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400312 parser.add_argument('--strip_cfi', action='store_true', default=False,
313 help='do not generate CFI data (pass -c to dump_syms)')
Prathmesh Prabhu9995e9b2013-10-31 16:43:55 -0700314 parser.add_argument('file_list', nargs='*', default=None,
315 help='generate symbols for only these files '
316 '(e.g. /build/$BOARD/usr/bin/foo)')
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400317
318 opts = parser.parse_args(argv)
Mike Frysinger90e49ca2014-01-14 14:42:07 -0500319 opts.Freeze()
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400320
321 if opts.board is None:
322 cros_build_lib.Die('--board is required')
323
324 ret = GenerateBreakpadSymbols(opts.board, breakpad_dir=opts.breakpad_root,
325 strip_cfi=opts.strip_cfi,
Mike Frysingeref9ab2f2013-08-26 22:16:00 -0400326 generate_count=opts.generate_count,
Mike Frysinger9a628bb2013-10-24 15:51:37 -0400327 num_processes=opts.jobs,
Shawn Nematbakhsh2c169cb2013-10-29 16:23:58 -0700328 clean_breakpad=opts.clean,
Prathmesh Prabhu9995e9b2013-10-31 16:43:55 -0700329 exclude_dirs=opts.exclude_dir,
330 file_list=opts.file_list)
Mike Frysinger69cb41d2013-08-11 20:08:19 -0400331 if ret:
332 cros_build_lib.Error('encountered %i problem(s)', ret)
333 # Since exit(status) gets masked, clamp it to 1 so we don't inadvertently
334 # return 0 in case we are a multiple of the mask.
335 ret = 1
336
337 return ret