blob: 7a3f98027f5e0b5846c746f1c327fddd8fd96d43 [file] [log] [blame]
Jonathan Metzmand5ee1c62018-11-05 10:33:08 -08001# -*- coding: utf-8 -*-
2# Copyright 2018 The Chromium OS Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Script for performing tasks that are useful for fuzzer development.
7
8Run "cros_fuzz" in the chroot for a list of command or "cros_fuzz $COMMAND
9--help" for their full details. Below is a summary of commands that the script
10can perform:
11
12coverage: Generate a coverage report for a given fuzzer (specified by "--fuzzer"
13 option). You almost certainly want to specify the package to build (using
14 the "--package" option) so that a coverage build is done, since a coverage
15 build is needed to generate a report. If your fuzz target is running on
16 ClusterFuzz already, you can use the "--download" option to download the
17 corpus from ClusterFuzz. Otherwise, you can use the "--corpus" option to
18 specify the path of the corpus to run the fuzzer on and generate a report.
19 The corpus will be copied to the sysroot so that the fuzzer can use it.
20 Note that "--download" and "--corpus" are mutually exclusive.
21
22reproduce: Runs the fuzzer specified by the "--fuzzer" option on a testcase
23 (path specified by the "--testcase" argument). Optionally does a build when
24 the "--package" option is used. The type of build can be specified using the
25 "--build_type" argument.
26
27download: Downloads the corpus from ClusterFuzz of the fuzzer specified by the
28 "--fuzzer" option. The path of the directory the corpus directory is
29 downloaded to can be specified using the "--directory" option.
30
31shell: Sets up the sysroot for fuzzing and then chroots into the sysroot giving
32 you a shell that is ready to fuzz.
33
34setup: Sets up the sysroot for fuzzing (done prior to doing "reproduce", "shell"
35 and "coverage" commands).
36
37cleanup: Undoes "setup".
38
39Note that cros_fuzz will print every shell command it runs if you set the
40log-level to debug ("--log-level debug"). Otherwise it will print commands that
41fail.
42"""
43
44from __future__ import print_function
45
46import os
47import shutil
48
49from elftools.elf.elffile import ELFFile
50import lddtree
51
52from chromite.lib import commandline
53from chromite.lib import constants
54from chromite.lib import cros_build_lib
55from chromite.lib import cros_logging as logging
56from chromite.lib import gs
57from chromite.lib import osutils
58
59# Directory in sysroot's /tmp directory that this script will use for files it
60# needs to write. We need a directory to write files to because this script uses
61# external programs that must write and read to/from files and because these
62# must be run inside the sysroot and thus are usually unable to read or write
63# from directories in the chroot environment this script is executed in.
64SCRIPT_STORAGE_DIRECTORY = 'fuzz'
65SCRIPT_STORAGE_PATH = os.path.join('/', 'tmp', SCRIPT_STORAGE_DIRECTORY)
66
67# Names of subdirectories in "fuzz" directory used by this script to store
68# things.
69CORPUS_DIRECTORY_NAME = 'corpus'
70TESTCASE_DIRECTORY_NAME = 'testcase'
71COVERAGE_REPORT_DIRECTORY_NAME = 'coverage-report'
72
Jonathan Metzmand5ee1c62018-11-05 10:33:08 -080073# Constants for names of libFuzzer command line options.
74RUNS_OPTION_NAME = 'runs'
75MAX_TOTAL_TIME_OPTION_NAME = 'max_total_time'
76
77# The default path a profraw file written by a clang coverage instrumented
78# binary when run by this script (default is current working directory).
79DEFAULT_PROFRAW_PATH = '/default.profraw'
80
81# Constants for libFuzzer command line values.
82# 0 runs means execute everything in the corpus and do no mutations.
83RUNS_DEFAULT_VALUE = 0
84# An arbitrary but short amount of time to run a fuzzer to get some coverage
85# data (when a corpus hasn't been provided and we aren't told to download one.
86MAX_TOTAL_TIME_DEFAULT_VALUE = 30
87
88
89class BuildType(object):
90 """Class to hold the different kinds of build types."""
91
92 ASAN = 'asan'
Manoj Guptae207b562019-05-02 11:30:35 -070093 MSAN = 'msan'
Jonathan Metzmand5ee1c62018-11-05 10:33:08 -080094 UBSAN = 'ubsan'
95 COVERAGE = 'coverage'
96 STANDARD = ''
97
98 # Build types that users can specify.
Manoj Guptae207b562019-05-02 11:30:35 -070099 CHOICES = (ASAN, MSAN, UBSAN, COVERAGE)
Jonathan Metzmand5ee1c62018-11-05 10:33:08 -0800100
101
102class SysrootPath(object):
103 """Class for representing a path that is in the sysroot.
104
105 Useful for dealing with paths that we must interact with when chrooted into
106 the sysroot and outside of it.
107
108 For example, if we need to interact with the "/tmp" directory of the sysroot,
109 SysrootPath('/tmp').sysroot returns the path of the directory if we are in
110 chrooted into the sysroot, i.e. "/tmp".
111
112 SysrootPath('/tmp').chroot returns the path of the directory when in the
113 cros_sdk i.e. SYSROOT_DIRECTORY + "/tmp" (this will probably be
114 "/build/amd64-generic/tmp" in most cases).
115 """
116
117 # The actual path to the sysroot (from within the chroot).
118 path_to_sysroot = None
119
120 def __init__(self, path):
121 """Constructor.
122
123 Args:
124 path: An absolute path representing something in the sysroot.
125 """
126
127 assert path.startswith('/')
128 if self.IsPathInSysroot(path):
129 path = self.FromChrootPathInSysroot(os.path.abspath(path))
130 self.path_list = path.split(os.sep)[1:]
131
132 @classmethod
133 def SetPathToSysroot(cls, board):
134 """Sets path_to_sysroot
135
136 Args:
137 board: The board we will use for our sysroot.
138
139 Returns:
140 The path to the sysroot (the value of path_to_sysroot).
141 """
142 cls.path_to_sysroot = cros_build_lib.GetSysroot(board)
143 return cls.path_to_sysroot
144
145 @property
146 def chroot(self):
147 """Get the path of the object in the Chrome OS SDK chroot.
148
149 Returns:
150 The path this object represents when chrooted into the sysroot.
151 """
Jonathan Metzmanb2c33732018-11-08 11:33:35 -0800152 assert self.path_to_sysroot is not None, 'set SysrootPath.path_to_sysroot'
Jonathan Metzmand5ee1c62018-11-05 10:33:08 -0800153 return os.path.join(self.path_to_sysroot, *self.path_list)
154
155 @property
156 def sysroot(self):
157 """Get the path of the object when in the sysroot.
158
159 Returns:
160 The path this object represents when in the Chrome OS SDK .
161 """
162 return os.path.join('/', *self.path_list)
163
164 @classmethod
165 def IsPathInSysroot(cls, path):
166 """Is a path in the sysroot.
167
168 Args:
169 path: The path we are checking is in the sysroot.
170
171 Returns:
172 True if path is within the sysroot's path in the chroot.
173 """
174 assert cls.path_to_sysroot
175 return path.startswith(cls.path_to_sysroot)
176
177 @classmethod
178 def FromChrootPathInSysroot(cls, path):
179 """Converts a chroot-relative path that is in sysroot into sysroot-relative.
180
181 Args:
182 path: The chroot-relative path we are converting to sysroot relative.
183
184 Returns:
185 The sysroot relative version of |path|.
186 """
187 assert cls.IsPathInSysroot(path)
188 common_prefix = os.path.commonprefix([cls.path_to_sysroot, path])
189 return path[len(common_prefix):]
190
191
192def GetScriptStoragePath(relative_path):
193 """Get the SysrootPath representing a script storage path.
194
195 Get a path of a directory this script will store things in.
196
197 Args:
198 relative_path: The path relative to the root of the script storage
199 directory.
200
201 Returns:
202 The SysrootPath representing absolute path of |relative_path| in the script
203 storage directory.
204 """
205 path = os.path.join(SCRIPT_STORAGE_PATH, relative_path)
206 return SysrootPath(path)
207
208
209def GetSysrootPath(path):
210 """Get the chroot-relative path of a path in the sysroot.
211
212 Args:
213 path: An absolute path in the sysroot that we will get the path in the
214 chroot for.
215
216 Returns:
217 The chroot-relative path of |path| in the sysroot.
218 """
219 return SysrootPath(path).chroot
220
221
222def GetCoverageDirectory(fuzzer):
223 """Get a coverage report directory for a fuzzer
224
225 Args:
226 fuzzer: The fuzzer to get the coverage report directory for.
227
228 Returns:
229 The location of the coverage report directory for the |fuzzer|.
230 """
231 relative_path = os.path.join(COVERAGE_REPORT_DIRECTORY_NAME, fuzzer)
232 return GetScriptStoragePath(relative_path)
233
234
235def GetFuzzerSysrootPath(fuzzer):
236 """Get the path in the sysroot of a fuzzer.
237
238 Args:
239 fuzzer: The fuzzer to get the path of.
240
241 Returns:
242 The path of |fuzzer| in the sysroot.
243 """
244 return SysrootPath(os.path.join('/', 'usr', 'libexec', 'fuzzers', fuzzer))
245
246
247def GetProfdataPath(fuzzer):
248 """Get the profdata file of a fuzzer.
249
250 Args:
251 fuzzer: The fuzzer to get the profdata file of.
252
253 Returns:
254 The path of the profdata file that should be used by |fuzzer|.
255 """
256 return GetScriptStoragePath('%s.profdata' % fuzzer)
257
258
259def GetPathForCopy(parent_directory, chroot_path):
260 """Returns a path in the script storage directory to copy chroot_path.
261
262 Returns a SysrootPath representing the location where |chroot_path| should
263 copied. This path will be in the parent_directory which will be in the script
264 storage directory.
265 """
266 basename = os.path.basename(chroot_path)
267 return GetScriptStoragePath(os.path.join(parent_directory, basename))
268
269
270def CopyCorpusToSysroot(src_corpus_path):
271 """Copies corpus into the sysroot.
272
273 Copies corpus into the sysroot. Doesn't copy if corpus is already in sysroot.
274
275 Args:
276 src_corpus_path: A path (in the chroot) to a corpus that will be copied into
277 sysroot.
278
279 Returns:
280 The path in the sysroot that the corpus was copied to.
281 """
282 if src_corpus_path is None:
283 return None
284
285 if SysrootPath.IsPathInSysroot(src_corpus_path):
286 # Don't copy if |src_testcase_path| is already in sysroot. Just return it in
287 # the format expected by the caller.
288 return SysrootPath(src_corpus_path)
289
290 dest_corpus_path = GetPathForCopy(CORPUS_DIRECTORY_NAME, src_corpus_path)
291 osutils.RmDir(dest_corpus_path.chroot)
292 shutil.copytree(src_corpus_path, dest_corpus_path.chroot)
293 return dest_corpus_path
294
295
296def CopyTestcaseToSysroot(src_testcase_path):
297 """Copies a testcase into the sysroot.
298
299 Copies a testcase into the sysroot. Doesn't copy if testcase is already in
300 sysroot.
301
302 Args:
303 src_testcase_path: A path (in the chroot) to a testcase that will be copied
304 into sysroot.
305
306 Returns:
307 The path in the sysroot that the testcase was copied to.
308 """
309 if SysrootPath.IsPathInSysroot(src_testcase_path):
310 # Don't copy if |src_testcase_path| is already in sysroot. Just return it in
311 # the format expected by the caller.
312 return SysrootPath(src_testcase_path)
313
314 dest_testcase_path = GetPathForCopy(TESTCASE_DIRECTORY_NAME,
315 src_testcase_path)
316 osutils.SafeMakedirsNonRoot(os.path.dirname(dest_testcase_path.chroot))
317 osutils.SafeUnlink(dest_testcase_path.chroot)
318
319 shutil.copy(src_testcase_path, dest_testcase_path.chroot)
320 return dest_testcase_path
321
322
323def SudoRunCommand(*args, **kwargs):
324 """Wrapper around cros_build_lib.SudoRunCommand.
325
326 Wrapper that calls cros_build_lib.SudoRunCommand but sets debug_level by
327 default.
328
329 Args:
330 *args: Positional arguments to pass to cros_build_lib.SudoRunCommand.
331 *kwargs: Keyword arguments to pass to cros_build_lib.SudoRunCommand.
332
333 Returns:
334 The value returned by calling cros_build_lib.SudoRunCommand.
335 """
336 kwargs.setdefault('debug_level', logging.DEBUG)
337 return cros_build_lib.SudoRunCommand(*args, **kwargs)
338
339
340def GetLibFuzzerOption(option_name, option_value):
341 """Gets the libFuzzer command line option with the specified name and value.
342
343 Args:
344 option_name: The name of the libFuzzer option.
345 option_value: The value of the libFuzzer option.
346
347 Returns:
348 The libFuzzer option composed of |option_name| and |option_value|.
349 """
350 return '-%s=%s' % (option_name, option_value)
351
352
353def IsOptionLimit(option):
354 """Determines if fuzzer option limits fuzzing time."""
355 for limit_name in [MAX_TOTAL_TIME_OPTION_NAME, RUNS_OPTION_NAME]:
356 if option.startswith('-%s' % limit_name):
357 return True
358
359 return False
360
361
362def LimitFuzzing(fuzz_command, corpus):
363 """Limits how long fuzzing will go if unspecified.
364
365 Adds a reasonable limit on how much fuzzing will be done unless there already
366 is some kind of limit. Mutates fuzz_command.
367
368 Args:
369 fuzz_command: A command to run a fuzzer. Used to determine if a limit needs
370 to be set. Mutated if it is needed to specify a limit.
371 corpus: The corpus that will be passed to the fuzzer. If not None then
372 fuzzing is limited by running everything in the corpus once.
373 """
Jonathan Metzmanb2c33732018-11-08 11:33:35 -0800374 if any(IsOptionLimit(x) for x in fuzz_command[1:]):
Jonathan Metzmand5ee1c62018-11-05 10:33:08 -0800375 # Don't do anything if there is already a limit.
376 return
377
378 if corpus:
379 # If there is a corpus, just run everything in the corpus once.
380 fuzz_command.append(
381 GetLibFuzzerOption(RUNS_OPTION_NAME, RUNS_DEFAULT_VALUE))
382 return
383
384 # Since there is no corpus, just fuzz for 30 seconds.
385 logging.info('Limiting fuzzing to %s seconds.', MAX_TOTAL_TIME_DEFAULT_VALUE)
386 max_total_time_option = GetLibFuzzerOption(MAX_TOTAL_TIME_OPTION_NAME,
387 MAX_TOTAL_TIME_DEFAULT_VALUE)
388 fuzz_command.append(max_total_time_option)
389
390
Jonathan Metzmanb2c33732018-11-08 11:33:35 -0800391def GetFuzzExtraEnv(extra_options=None):
392 """Gets extra_env for fuzzing.
393
394 Gets environment varaibles and values for running libFuzzer. Sets defaults and
395 allows user to specify extra sanitizer options.
396
397 Args:
398 extra_options: A dict containing sanitizer options to set in addition to the
399 defaults.
400
401 Returns:
402 A dict containing environment variables and their values that can be used in
403 the environment libFuzzer runs in.
404 """
405 if extra_options is None:
406 extra_options = {}
407
408 # log_path must be set because Chrome OS's patched compiler changes it.
409 options_dict = {'log_path': 'stderr'}
410 options_dict.update(extra_options)
411 sanitizer_options = ':'.join('%s=%s' % x for x in options_dict.items())
412 sanitizers = ('ASAN', 'MSAN', 'UBSAN')
413 return {x + '_OPTIONS': sanitizer_options for x in sanitizers}
414
415
Manoj Gupta5ca17652019-05-13 11:15:33 -0700416def RunFuzzer(fuzzer,
417 corpus_path=None,
418 fuzz_args='',
419 testcase_path=None,
Jonathan Metzmanb2c33732018-11-08 11:33:35 -0800420 crash_expected=False):
Jonathan Metzmand5ee1c62018-11-05 10:33:08 -0800421 """Runs the fuzzer while chrooted into the sysroot.
422
423 Args:
424 fuzzer: The fuzzer to run.
Jonathan Metzmanb2c33732018-11-08 11:33:35 -0800425 corpus_path: A path to a corpus (not necessarily in the sysroot) to run the
426 fuzzer on.
Jonathan Metzmand5ee1c62018-11-05 10:33:08 -0800427 fuzz_args: Additional arguments to pass to the fuzzer when running it.
428 testcase_path: A path to a testcase (not necessarily in the sysroot) to run
429 the fuzzer on.
Jonathan Metzmanb2c33732018-11-08 11:33:35 -0800430 crash_expected: Is it normal for the fuzzer to crash on this run?
Jonathan Metzmand5ee1c62018-11-05 10:33:08 -0800431 """
432 logging.info('Running fuzzer: %s', fuzzer)
433 fuzzer_sysroot_path = GetFuzzerSysrootPath(fuzzer)
434 fuzz_command = [fuzzer_sysroot_path.sysroot]
435 fuzz_command += fuzz_args.split()
436
437 if testcase_path:
438 fuzz_command.append(testcase_path)
439 else:
440 LimitFuzzing(fuzz_command, corpus_path)
441
442 if corpus_path:
443 fuzz_command.append(corpus_path)
444
Jonathan Metzmanb2c33732018-11-08 11:33:35 -0800445 if crash_expected:
446 # Don't return nonzero when fuzzer OOMs, leaks, or timesout, since we don't
447 # want an exception in those cases. The user may be trying to reproduce
448 # those issues.
449 fuzz_command += ['-error_exitcode=0', '-timeout_exitcode=0']
450
451 # We must set exitcode=0 or else the fuzzer will return nonzero on
452 # successful reproduction.
453 sanitizer_options = {'exitcode': '0'}
454 else:
455 sanitizer_options = {}
456
457 extra_env = GetFuzzExtraEnv(sanitizer_options)
458 RunSysrootCommand(fuzz_command, extra_env=extra_env, debug_level=logging.INFO)
Jonathan Metzmand5ee1c62018-11-05 10:33:08 -0800459
460
461def MergeProfraw(fuzzer):
462 """Merges profraw file from a fuzzer and creates a profdata file.
463
464 Args:
465 fuzzer: The fuzzer to merge the profraw file from.
466 """
467 profdata_path = GetProfdataPath(fuzzer)
468 command = [
469 'llvm-profdata',
470 'merge',
471 '-sparse',
472 DEFAULT_PROFRAW_PATH,
473 '-o',
474 profdata_path.sysroot,
475 ]
476
477 RunSysrootCommand(command)
478 return profdata_path
479
480
481def GenerateCoverageReport(fuzzer, shared_libraries):
482 """Generates an HTML coverage report from a fuzzer run.
483
484 Args:
485 fuzzer: The fuzzer to generate the coverage report for.
486 shared_libraries: Libraries loaded dynamically by |fuzzer|.
487
488 Returns:
489 The path of the coverage report.
490 """
491 fuzzer_path = GetFuzzerSysrootPath(fuzzer).chroot
492 command = ['llvm-cov', 'show', '-object', fuzzer_path]
493 for library in shared_libraries:
494 command += ['-object', library]
495
496 coverage_directory = GetCoverageDirectory(fuzzer)
497 command += [
498 '-format=html',
499 '-instr-profile=%s' % GetProfdataPath(fuzzer).chroot,
500 '-output-dir=%s' % coverage_directory.chroot,
501 ]
502
503 # TODO(metzman): Investigate error messages printed by this command.
504 cros_build_lib.RunCommand(
505 command, redirect_stderr=True, debug_level=logging.DEBUG)
506 return coverage_directory
507
508
509def GetSharedLibraries(binary_path):
510 """Gets the shared libraries used by a binary.
511
512 Gets the shared libraries used by the binary. Based on GetSharedLibraries from
513 src/tools/code_coverage/coverage_utils.py in Chromium.
514
515 Args:
516 binary_path: The path to the binary we want to find the shared libraries of.
517
518 Returns:
519 The shared libraries used by |binary_path|.
520 """
521 logging.info('Finding shared libraries for targets (if any).')
522 shared_libraries = []
523 elf_dict = lddtree.ParseELF(
524 binary_path.chroot, root=SysrootPath.path_to_sysroot)
525 for shared_library in elf_dict['libs'].itervalues():
526 shared_library_path = shared_library['path']
527
528 if shared_library_path in shared_libraries:
529 continue
530
531 assert os.path.exists(shared_library_path), ('Shared library "%s" used by '
532 'the given target(s) does not '
533 'exist.' % shared_library_path)
534
535 if IsInstrumentedWithClangCoverage(shared_library_path):
536 # Do not add non-instrumented libraries. Otherwise, llvm-cov errors out.
537 shared_libraries.append(shared_library_path)
538
539 logging.debug('Found shared libraries (%d): %s.', len(shared_libraries),
540 shared_libraries)
541 logging.info('Finished finding shared libraries for targets.')
542 return shared_libraries
543
544
545def IsInstrumentedWithClangCoverage(binary_path):
546 """Determines if a binary is instrumented with clang source based coverage.
547
548 Args:
549 binary_path: The path of the binary (executable or library) we are checking
550 is instrumented with clang source based coverage.
551
552 Returns:
553 True if the binary is instrumented with clang source based coverage.
554 """
555 with open(binary_path, 'rb') as file_handle:
556 elf_file = ELFFile(file_handle)
557 return elf_file.get_section_by_name('__llvm_covmap') is not None
558
559
560def RunFuzzerAndGenerateCoverageReport(fuzzer, corpus, fuzz_args):
561 """Runs a fuzzer generates a coverage report and returns the report's path.
562
563 Gets a coverage report for a fuzzer.
564
565 Args:
566 fuzzer: The fuzzer to run and generate the coverage report for.
567 corpus: The path to a corpus to run the fuzzer on.
568 fuzz_args: Additional arguments to pass to the fuzzer.
569
570 Returns:
571 The path to the coverage report.
572 """
573 corpus_path = CopyCorpusToSysroot(corpus)
574 if corpus_path:
575 corpus_path = corpus_path.sysroot
576
577 RunFuzzer(fuzzer, corpus_path=corpus_path, fuzz_args=fuzz_args)
578 MergeProfraw(fuzzer)
579 fuzzer_sysroot_path = GetFuzzerSysrootPath(fuzzer)
580 shared_libraries = GetSharedLibraries(fuzzer_sysroot_path)
581 return GenerateCoverageReport(fuzzer, shared_libraries)
582
583
Jonathan Metzmanb2c33732018-11-08 11:33:35 -0800584def RunSysrootCommand(command, **kwargs):
Jonathan Metzmand5ee1c62018-11-05 10:33:08 -0800585 """Runs command while chrooted into sysroot and returns the output.
586
587 Args:
588 command: A command to run in the sysroot.
Jonathan Metzmand5ee1c62018-11-05 10:33:08 -0800589 kwargs: Extra arguments to pass to cros_build_lib.SudoRunCommand.
590
591 Returns:
592 The result of a call to cros_build_lib.SudoRunCommand.
593 """
594 command = ['chroot', SysrootPath.path_to_sysroot] + command
Jonathan Metzmanb2c33732018-11-08 11:33:35 -0800595 return SudoRunCommand(command, **kwargs)
Jonathan Metzmand5ee1c62018-11-05 10:33:08 -0800596
597
598def GetBuildExtraEnv(build_type):
599 """Gets the extra_env for building a package.
600
601 Args:
602 build_type: The type of build we want to do.
603
604 Returns:
605 The extra_env to use when building.
606 """
607 if build_type is None:
608 build_type = BuildType.ASAN
609
610 use_flags = os.environ.get('USE', '').split()
611 # Check that the user hasn't already set USE flags that we can set.
612 # No good way to iterate over an enum in python2.
613 for use_flag in BuildType.CHOICES:
614 if use_flag in use_flags:
615 logging.warn('%s in USE flags. Please use --build_type instead.',
616 use_flag)
617
618 # Set USE flags.
619 fuzzer_build_type = 'fuzzer'
620 use_flags += [fuzzer_build_type, build_type]
621 features_flags = os.environ.get('FEATURES', '').split()
622 if build_type == BuildType.COVERAGE:
623 # We must use ASan when doing coverage builds.
624 use_flags.append(BuildType.ASAN)
625 # Use noclean so that a coverage report can be generated based on the source
626 # code.
627 features_flags.append('noclean')
628
629 return {
630 'FEATURES': ' '.join(features_flags),
631 'USE': ' '.join(use_flags),
632 }
633
634
635def BuildPackage(package, board, build_type):
636 """Builds a package on a specified board.
637
638 Args:
639 package: The package to build. Nothing is built if None.
640 board: The board to build the package on.
Manoj Guptae207b562019-05-02 11:30:35 -0700641 build_type: The type of the build to do (e.g. asan, msan, ubsan, coverage).
Jonathan Metzmand5ee1c62018-11-05 10:33:08 -0800642 """
643 if package is None:
644 return
645
646 logging.info('Building %s using %s.', package, build_type)
Jonathan Metzmanb2c33732018-11-08 11:33:35 -0800647 extra_env = GetBuildExtraEnv(build_type)
Jonathan Metzmand5ee1c62018-11-05 10:33:08 -0800648 build_packages_path = os.path.join(constants.SOURCE_ROOT, 'src', 'scripts',
649 'build_packages')
650 command = [
651 build_packages_path,
652 '--board',
653 board,
654 '--skip_chroot_upgrade',
655 package,
656 ]
Manoj Gupta5ca17652019-05-13 11:15:33 -0700657 # For msan builds, always use "--nousepkg" since all package needs to be
658 # instrumented with msan.
659 if build_type == BuildType.MSAN:
660 command += ['--nousepkg']
661
Jonathan Metzmand5ee1c62018-11-05 10:33:08 -0800662 # Print the output of the build command. Do this because it is familiar to
663 # devs and we don't want to leave them not knowing about the build's progress
664 # for a long time.
Jonathan Metzmanb2c33732018-11-08 11:33:35 -0800665 cros_build_lib.RunCommand(command, extra_env=extra_env)
Jonathan Metzmand5ee1c62018-11-05 10:33:08 -0800666
667
668def DownloadFuzzerCorpus(fuzzer, dest_directory=None):
669 """Downloads a corpus and returns its path.
670
Jonathan Metzmanb2c33732018-11-08 11:33:35 -0800671 Downloads a corpus to a subdirectory of dest_directory if specified and
672 returns path on the filesystem of the corpus. Asks users to authenticate
673 if permission to read from bucket is denied.
674
Jonathan Metzmand5ee1c62018-11-05 10:33:08 -0800675 Args:
676 fuzzer: The name of the fuzzer who's corpus we want to download.
677 dest_directory: The directory to download the corpus to.
678
Jonathan Metzmand5ee1c62018-11-05 10:33:08 -0800679 Returns:
680 The path to the downloaded corpus.
681
682 Raises:
683 gs.NoSuchKey: A corpus for the fuzzer doesn't exist.
684 gs.GSCommandError: The corpus failed to download for another reason.
685 """
686 if not fuzzer.startswith('chromeos_'):
687 # ClusterFuzz internally appends "chromeos_" to chromeos targets' names.
688 # Therefore we must do so in order to find the corpus.
689 fuzzer = 'chromeos_%s' % fuzzer
690
691 if dest_directory is None:
692 dest_directory = GetScriptStoragePath(CORPUS_DIRECTORY_NAME).chroot
693 osutils.SafeMakedirsNonRoot(dest_directory)
694
695 clusterfuzz_gcs_corpus_bucket = 'chromeos-corpus'
696 suburl = 'libfuzzer/%s' % fuzzer
697 gcs_path = gs.GetGsURL(
698 clusterfuzz_gcs_corpus_bucket,
699 for_gsutil=True,
700 public=False,
701 suburl=suburl)
702
703 dest_path = os.path.join(dest_directory, fuzzer)
704
705 try:
706 logging.info('Downloading corpus to %s.', dest_path)
707 ctx = gs.GSContext()
708 ctx.Copy(
709 gcs_path,
710 dest_directory,
711 recursive=True,
712 parallel=True,
713 debug_level=logging.DEBUG)
714 logging.info('Finished downloading corpus.')
715 except gs.GSNoSuchKey as exception:
716 logging.error('Corpus for fuzzer: %s does not exist.', fuzzer)
717 raise exception
718 # Try to authenticate if we were denied permission to access the corpus.
719 except gs.GSCommandError as exception:
720 logging.error(
721 'gsutil failed to download the corpus. You may need to log in. See:\n'
722 'https://chromium.googlesource.com/chromiumos/docs/+/master/gsutil.md'
723 '#setup\n'
724 'for instructions on doing this.')
725 raise exception
726
727 return dest_path
728
729
730def Reproduce(fuzzer, testcase_path):
731 """Runs a fuzzer in the sysroot on a testcase.
732
733 Args:
734 fuzzer: The fuzzer to run.
735 testcase_path: The path (not necessarily in the sysroot) of the testcase to
736 run the fuzzer on.
737 """
Jonathan Metzmanb2c33732018-11-08 11:33:35 -0800738 testcase_sysroot_path = CopyTestcaseToSysroot(testcase_path).sysroot
739 RunFuzzer(fuzzer, testcase_path=testcase_sysroot_path, crash_expected=True)
Jonathan Metzmand5ee1c62018-11-05 10:33:08 -0800740
741
742def SetUpSysrootForFuzzing():
743 """Sets up the the sysroot for fuzzing
744
745 Prepares the sysroot for fuzzing. Idempotent.
746 """
747 logging.info('Setting up sysroot for fuzzing.')
748 # TODO(metzman): Don't create devices or mount /proc, use platform2_test.py
749 # instead.
750 # Mount /proc in sysroot and setup dev there because they are needed by
751 # sanitizers.
752 proc_manager = ProcManager()
753 proc_manager.Mount()
754
755 # Setup devices in /dev that are needed by libFuzzer.
756 device_manager = DeviceManager()
757 device_manager.SetUp()
758
759 # Set up asan_symbolize.py, llvm-symbolizer, and llvm-profdata in the
760 # sysroot so that fuzzer output (including stack traces) can be symbolized
761 # and so that coverage reports can be generated.
762 tool_manager = ToolManager()
763 tool_manager.Install()
764
765 osutils.SafeMakedirsNonRoot(GetSysrootPath(SCRIPT_STORAGE_PATH))
766
767
768def CleanUpSysroot():
769 """Cleans up the the sysroot from SetUpSysrootForFuzzing.
770
771 Undoes SetUpSysrootForFuzzing. Idempotent.
772 """
773 logging.info('Cleaning up the sysroot.')
774 proc_manager = ProcManager()
775 proc_manager.Unmount()
776
777 device_manager = DeviceManager()
778 device_manager.CleanUp()
779
780 tool_manager = ToolManager()
781 tool_manager.Uninstall()
Jonathan Metzmanb2c33732018-11-08 11:33:35 -0800782 osutils.RmDir(GetSysrootPath(SCRIPT_STORAGE_PATH), ignore_missing=True)
Jonathan Metzmand5ee1c62018-11-05 10:33:08 -0800783
784
785class ToolManager(object):
786 """Class that installs or uninstalls fuzzing tools to/from the sysroot.
787
788 Install and Uninstall methods are idempotent. Both are safe to call at any
789 point.
790 """
791
792 # Path to asan_symbolize.py.
793 ASAN_SYMBOLIZE_PATH = os.path.join('/', 'usr', 'bin', 'asan_symbolize.py')
794
795 # List of LLVM binaries we must install in sysroot.
Manoj Guptafeb1b7a2019-02-20 11:04:05 -0800796 LLVM_BINARY_NAMES = ['gdbserver', 'llvm-symbolizer', 'llvm-profdata']
Jonathan Metzmand5ee1c62018-11-05 10:33:08 -0800797
798 def __init__(self):
799 self.asan_symbolize_sysroot_path = GetSysrootPath(self.ASAN_SYMBOLIZE_PATH)
800
801 def Install(self):
802 """Installs tools to the sysroot."""
803 # Install asan_symbolize.py.
804 SudoRunCommand(
805 ['cp', self.ASAN_SYMBOLIZE_PATH, self.asan_symbolize_sysroot_path])
806 # Install the LLVM binaries.
807 # TODO(metzman): Build these tools so that we don't mess up when board is
808 # for a different ISA.
809 for llvm_binary in self._GetLLVMBinaries():
810 llvm_binary.Install()
811
812 def Uninstall(self):
813 """Uninstalls tools from the sysroot. Undoes Install."""
814 # Uninstall asan_symbolize.py.
815 osutils.SafeUnlink(self.asan_symbolize_sysroot_path, sudo=True)
816 # Uninstall the LLVM binaries.
817 for llvm_binary in self._GetLLVMBinaries():
818 llvm_binary.Uninstall()
819
820 def _GetLLVMBinaries(self):
821 """Creates LllvmBinary objects for each binary name in LLVM_BINARY_NAMES."""
Jonathan Metzmanb2c33732018-11-08 11:33:35 -0800822 return [LlvmBinary(x) for x in self.LLVM_BINARY_NAMES]
Jonathan Metzmand5ee1c62018-11-05 10:33:08 -0800823
824
825class LlvmBinary(object):
826 """Class for representing installing/uninstalling an LLVM binary in sysroot.
827
828 Install and Uninstall methods are idempotent. Both are safe to call at any
829 time.
830 """
831
832 # Path to the lddtree chromite script.
833 LDDTREE_SCRIPT_PATH = os.path.join(constants.CHROMITE_BIN_DIR, 'lddtree')
834
835 def __init__(self, binary):
836 self.binary = binary
837 self.install_dir = GetSysrootPath(
838 os.path.join('/', 'usr', 'libexec', binary))
839 self.binary_dir_path = GetSysrootPath(os.path.join('/', 'usr', 'bin'))
840 self.binary_chroot_dest_path = os.path.join(self.binary_dir_path, binary)
841
842 def Uninstall(self):
843 """Removes an LLVM binary from sysroot. Undoes Install."""
844 osutils.RmDir(self.install_dir, ignore_missing=True, sudo=True)
845 osutils.SafeUnlink(self.binary_chroot_dest_path, sudo=True)
846
847 def Install(self):
848 """Installs (sets up) an LLVM binary in the sysroot.
849
850 Sets up an llvm binary in the sysroot so that it can be run there.
851 """
852 # Create a directory for installing |binary| and all of its dependencies in
853 # the sysroot.
854 binary_rel_path = ['usr', 'bin', self.binary]
855 binary_chroot_path = os.path.join('/', *binary_rel_path)
Manoj Guptafeb1b7a2019-02-20 11:04:05 -0800856 if not os.path.exists(binary_chroot_path):
857 logging.warning('Cannot copy %s, file does not exist in chroot.',
858 binary_chroot_path)
859 logging.warning('Functionality provided by %s will be missing.',
860 binary_chroot_path)
861 return
862
Jonathan Metzmand5ee1c62018-11-05 10:33:08 -0800863 osutils.SafeMakedirsNonRoot(self.install_dir)
864
865 # Copy the binary and everything needed to run it into the sysroot.
866 cmd = [
867 self.LDDTREE_SCRIPT_PATH,
868 '-v',
869 '--generate-wrappers',
870 '--root',
871 '/',
872 '--copy-to-tree',
873 self.install_dir,
874 binary_chroot_path,
875 ]
876 SudoRunCommand(cmd)
877
878 # Create a symlink to the copy of the binary (we can't do lddtree in
879 # self.binary_dir_path). Note that symlink should be relative so that it
880 # will be valid when chrooted into the sysroot.
881 rel_path = os.path.relpath(self.install_dir, self.binary_dir_path)
882 link_path = os.path.join(rel_path, *binary_rel_path)
883 osutils.SafeSymlink(link_path, self.binary_chroot_dest_path, sudo=True)
884
885
886class DeviceManager(object):
887 """Class that creates or removes devices from /dev in sysroot.
888
889 SetUp and CleanUp methods are idempotent. Both are safe to call at any point.
890 """
891
892 DEVICE_MKNOD_PARAMS = {
893 'null': (666, 3),
894 'random': (444, 8),
895 'urandom': (444, 9),
896 }
897
898 MKNOD_MAJOR = '1'
899
900 def __init__(self):
901 self.dev_path_chroot = GetSysrootPath('/dev')
902
903 def _GetDevicePath(self, device_name):
904 """Returns the path of |device_name| in sysroot's /dev."""
905 return os.path.join(self.dev_path_chroot, device_name)
906
907 def SetUp(self):
908 """Sets up devices in the sysroot's /dev.
909
910 Creates /dev/null, /dev/random, and /dev/urandom. If they already exist then
911 recreates them.
912 """
913 self.CleanUp()
914 osutils.SafeMakedirsNonRoot(self.dev_path_chroot)
915 for device, mknod_params in self.DEVICE_MKNOD_PARAMS.iteritems():
916 device_path = self._GetDevicePath(device)
917 self._MakeCharDevice(device_path, *mknod_params)
918
919 def CleanUp(self):
920 """Cleans up devices in the sysroot's /dev. Undoes SetUp.
921
922 Removes /dev/null, /dev/random, and /dev/urandom if they exist.
923 """
924 for device in self.DEVICE_MKNOD_PARAMS:
925 device_path = self._GetDevicePath(device)
926 if os.path.exists(device_path):
927 # Use -r since dev/null is sometimes a directory.
928 SudoRunCommand(['rm', '-r', device_path])
929
930 def _MakeCharDevice(self, path, mode, minor):
931 """Make a character device."""
932 mode = str(mode)
933 minor = str(minor)
934 command = ['mknod', '-m', mode, path, 'c', self.MKNOD_MAJOR, minor]
935 SudoRunCommand(command)
936
937
938class ProcManager(object):
939 """Class that mounts or unmounts /proc in sysroot.
940
941 Mount and Unmount are idempotent. Both are safe to call at any point.
942 """
943
944 PROC_PATH = '/proc'
945
946 def __init__(self):
947 self.proc_path_chroot = GetSysrootPath(self.PROC_PATH)
948 self.is_mounted = osutils.IsMounted(self.proc_path_chroot)
949
950 def Unmount(self):
951 """Unmounts /proc in chroot. Undoes Mount."""
952 if not self.is_mounted:
953 return
954 osutils.UmountDir(self.proc_path_chroot, cleanup=False)
955
956 def Mount(self):
957 """Mounts /proc in chroot. Remounts it if already mounted."""
958 self.Unmount()
959 osutils.MountDir(
960 self.PROC_PATH,
961 self.proc_path_chroot,
962 'proc',
963 debug_level=logging.DEBUG)
964
965
966def EnterSysrootShell():
967 """Spawns and gives user access to a bash shell in the sysroot."""
968 command = ['/bin/bash', '-i']
969 return RunSysrootCommand(
Jonathan Metzmanb2c33732018-11-08 11:33:35 -0800970 command,
971 extra_env=GetFuzzExtraEnv(),
972 debug_level=logging.INFO,
Jonathan Metzmand5ee1c62018-11-05 10:33:08 -0800973 error_code_ok=True).returncode
974
975
976def StripFuzzerPrefixes(fuzzer_name):
977 """Strip the prefix ClusterFuzz uses in case they are specified.
978
979 Strip the prefixes used by ClusterFuzz if the users has included them by
980 accident.
981
982 Args:
983 fuzzer_name: The fuzzer who's name may contain prefixes.
984
985 Returns:
986 The name of the fuzz target without prefixes.
987 """
988 initial_name = fuzzer_name
989
990 def StripPrefix(prefix):
991 if fuzzer_name.startswith(prefix):
992 return fuzzer_name[len(prefix):]
993 return fuzzer_name
994
995 clusterfuzz_prefixes = ['libFuzzer_', 'chromeos_']
996
997 for prefix in clusterfuzz_prefixes:
998 fuzzer_name = StripPrefix(prefix)
999
1000 if initial_name != fuzzer_name:
1001 logging.warn(
1002 '%s contains a prefix from ClusterFuzz (one or more of %s) that is not '
1003 'part of the fuzzer\'s name. Interpreting --fuzzer as %s.',
1004 initial_name, clusterfuzz_prefixes, fuzzer_name)
1005
1006 return fuzzer_name
1007
1008
1009def ExecuteShellCommand():
1010 """Executes the "shell" command.
1011
1012 Sets up the sysroot for fuzzing and gives user access to a bash shell it
1013 spawns in the sysroot.
1014
1015 Returns:
1016 The exit code of the shell command.
1017 """
1018 SetUpSysrootForFuzzing()
1019 return EnterSysrootShell()
1020
1021
1022def ExecuteSetupCommand():
1023 """Executes the "setup" command. Wrapper for SetUpSysrootForFuzzing.
1024
1025 Sets up the sysroot for fuzzing.
1026 """
1027 SetUpSysrootForFuzzing()
1028
1029
1030def ExecuteCleanupCommand():
1031 """Executes the "cleanup" command. Wrapper for CleanUpSysroot.
1032
1033 Undoes pre-fuzzing setup.
1034 """
1035 CleanUpSysroot()
1036
1037
1038def ExecuteCoverageCommand(options):
1039 """Executes the "coverage" command.
1040
1041 Executes the "coverage" command by optionally doing a coverage build of a
1042 package, optionally downloading the fuzzer's corpus, optionally copying it
1043 into the sysroot, running the fuzzer and then generating a coverage report
1044 for the user to view. Causes program to exit if fuzzer is not instrumented
1045 with source based coverage.
1046
1047 Args:
1048 options: The parsed arguments passed to this program.
1049 """
1050 BuildPackage(options.package, options.board, BuildType.COVERAGE)
1051
1052 fuzzer = StripFuzzerPrefixes(options.fuzzer)
1053 fuzzer_sysroot_path = GetFuzzerSysrootPath(fuzzer)
1054 if not IsInstrumentedWithClangCoverage(fuzzer_sysroot_path.chroot):
1055 # Don't run the fuzzer if it isn't instrumented with source based coverage.
1056 # Quit and let the user know how to build the fuzzer properly.
1057 cros_build_lib.Die(
1058 '%s is not instrumented with source based coverage.\nSpecify --package '
1059 'to do a coverage build or build with USE flag: "coverage".', fuzzer)
1060
1061 corpus = options.corpus
1062 if options.download:
1063 corpus = DownloadFuzzerCorpus(options.fuzzer)
1064
1065 # Set up sysroot for fuzzing.
1066 SetUpSysrootForFuzzing()
1067
1068 coverage_report_path = RunFuzzerAndGenerateCoverageReport(
1069 fuzzer, corpus, options.fuzz_args)
1070
1071 # Get path on host so user can access it with their browser.
1072 # TODO(metzman): Add the ability to convert to host paths to path_util.
1073 external_trunk_path = os.getenv('EXTERNAL_TRUNK_PATH')
1074 coverage_report_host_path = os.path.join(external_trunk_path, 'chroot',
1075 coverage_report_path.chroot[1:])
1076 print('Coverage report written to file://%s/index.html' %
1077 coverage_report_host_path)
1078
1079
1080def ExecuteDownloadCommand(options):
1081 """Executes the "download" command. Wrapper around DownloadFuzzerCorpus."""
1082 DownloadFuzzerCorpus(StripFuzzerPrefixes(options.fuzzer), options.directory)
1083
1084
1085def ExecuteReproduceCommand(options):
1086 """Executes the "reproduce" command.
1087
1088 Executes the "reproduce" command by Running a fuzzer on a testcase.
1089 May build the fuzzer before running.
1090
1091 Args:
1092 options: The parsed arguments passed to this program.
1093 """
1094 if options.build_type and not options.package:
1095 raise Exception('Cannot specify --build_type without specifying --package.')
1096
Manoj Gupta5ca17652019-05-13 11:15:33 -07001097 # Verify that "msan-fuzzer" profile is being used with msan.
1098 # Check presence of "-fsanitize=memory" in CFLAGS.
1099 if options.build_type == BuildType.MSAN:
1100 cmd = ['portageq-%s' % options.board, 'envvar', 'CFLAGS']
1101 cflags = cros_build_lib.RunCommand(
1102 cmd, capture_output=True).output.splitlines()
1103 check_string = '-fsanitize=memory'
1104 if not any(check_string in s for s in cflags):
1105 logging.error(
1106 '-fsanitize=memory not found in CFLAGS. '
1107 'Use "setup_board --board=amd64-generic --profile=msan-fuzzer" '
1108 'for MSan Fuzzing Builds.')
1109 raise Exception('Incompatible profile used for msan fuzzing.')
1110
Jonathan Metzmand5ee1c62018-11-05 10:33:08 -08001111 BuildPackage(options.package, options.board, options.build_type)
1112 SetUpSysrootForFuzzing()
1113 Reproduce(StripFuzzerPrefixes(options.fuzzer), options.testcase)
1114
1115
1116def ParseArgs(argv):
1117 """Parses program arguments.
1118
1119 Args:
1120 argv: The program arguments we want to parse.
1121
1122 Returns:
1123 An options object which will tell us which command to run and which options
1124 to use for that command.
1125 """
1126 parser = commandline.ArgumentParser(description=__doc__)
1127
1128 parser.add_argument(
1129 '--board',
1130 default=cros_build_lib.GetDefaultBoard(),
1131 help='Board on which to run test.')
1132
1133 subparsers = parser.add_subparsers(dest='command')
1134
1135 subparsers.add_parser('cleanup', help='Undo setup command.')
1136 coverage_parser = subparsers.add_parser(
1137 'coverage', help='Get a coverage report for a fuzzer.')
1138
1139 coverage_parser.add_argument('--package', help='Package to build.')
1140
1141 corpus_parser = coverage_parser.add_mutually_exclusive_group()
1142 corpus_parser.add_argument('--corpus', help='Corpus to run fuzzer on.')
1143
1144 corpus_parser.add_argument(
1145 '--download',
1146 action='store_true',
1147 help='Generate coverage report based on corpus from ClusterFuzz.')
1148
1149 coverage_parser.add_argument(
1150 '--fuzzer',
1151 required=True,
1152 help='The fuzz target to generate a coverage report for.')
1153
1154 coverage_parser.add_argument(
1155 '--fuzz-args',
1156 default='',
1157 help='Arguments to pass libFuzzer. '
1158 'Please use an equals sign or parsing will fail '
1159 '(i.e. --fuzzer_args="-rss_limit_mb=2048 -print_funcs=1").')
1160
1161 download_parser = subparsers.add_parser('download', help='Download a corpus.')
1162
1163 download_parser.add_argument(
1164 '--directory', help='Path to directory to download the corpus to.')
1165
1166 download_parser.add_argument(
1167 '--fuzzer', required=True, help='Fuzzer to download the corpus for.')
1168
1169 reproduce_parser = subparsers.add_parser(
1170 'reproduce', help='Run a fuzzer on a testcase.')
1171
1172 reproduce_parser.add_argument(
1173 '--testcase', required=True, help='Path of testcase to run fuzzer on.')
1174
1175 reproduce_parser.add_argument(
1176 '--fuzzer', required=True, help='Fuzzer to reproduce the crash on.')
1177
1178 reproduce_parser.add_argument('--package', help='Package to build.')
1179
1180 reproduce_parser.add_argument(
1181 '--build-type',
1182 choices=BuildType.CHOICES,
1183 help='Type of build.',
1184 type=str.lower) # Ignore sanitizer case.
1185
1186 subparsers.add_parser('setup', help='Set up the sysroot to test fuzzing.')
1187
1188 subparsers.add_parser(
1189 'shell',
1190 help='Set up sysroot for fuzzing and get a shell in the sysroot.')
1191
1192 opts = parser.parse_args(argv)
1193 opts.Freeze()
1194 return opts
1195
1196
1197def main(argv):
1198 """Parses arguments and executes a command.
1199
1200 Args:
1201 argv: The prorgram arguments.
1202
1203 Returns:
1204 0 on success. Non-zero on failure.
1205 """
1206 cros_build_lib.AssertInsideChroot()
1207 options = ParseArgs(argv)
1208 if options.board is None:
1209 logging.error('Please specify "--board" or set ".default_board".')
1210 return 1
1211
1212 SysrootPath.SetPathToSysroot(options.board)
1213
1214 if options.command == 'cleanup':
1215 ExecuteCleanupCommand()
1216 elif options.command == 'coverage':
1217 ExecuteCoverageCommand(options)
1218 elif options.command == 'setup':
1219 ExecuteSetupCommand()
1220 elif options.command == 'download':
1221 ExecuteDownloadCommand(options)
1222 elif options.command == 'reproduce':
1223 ExecuteReproduceCommand(options)
1224 elif options.command == 'shell':
1225 return ExecuteShellCommand()
1226
1227 return 0