Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 1 | # Copyright 2018 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 | """Script for performing tasks that are useful for fuzzer development. |
| 6 | |
| 7 | Run "cros_fuzz" in the chroot for a list of command or "cros_fuzz $COMMAND |
| 8 | --help" for their full details. Below is a summary of commands that the script |
| 9 | can perform: |
| 10 | |
| 11 | coverage: Generate a coverage report for a given fuzzer (specified by "--fuzzer" |
| 12 | option). You almost certainly want to specify the package to build (using |
| 13 | the "--package" option) so that a coverage build is done, since a coverage |
| 14 | build is needed to generate a report. If your fuzz target is running on |
| 15 | ClusterFuzz already, you can use the "--download" option to download the |
| 16 | corpus from ClusterFuzz. Otherwise, you can use the "--corpus" option to |
| 17 | specify the path of the corpus to run the fuzzer on and generate a report. |
| 18 | The corpus will be copied to the sysroot so that the fuzzer can use it. |
| 19 | Note that "--download" and "--corpus" are mutually exclusive. |
| 20 | |
| 21 | reproduce: Runs the fuzzer specified by the "--fuzzer" option on a testcase |
| 22 | (path specified by the "--testcase" argument). Optionally does a build when |
| 23 | the "--package" option is used. The type of build can be specified using the |
| 24 | "--build_type" argument. |
| 25 | |
| 26 | download: Downloads the corpus from ClusterFuzz of the fuzzer specified by the |
| 27 | "--fuzzer" option. The path of the directory the corpus directory is |
| 28 | downloaded to can be specified using the "--directory" option. |
| 29 | |
| 30 | shell: Sets up the sysroot for fuzzing and then chroots into the sysroot giving |
| 31 | you a shell that is ready to fuzz. |
| 32 | |
| 33 | setup: Sets up the sysroot for fuzzing (done prior to doing "reproduce", "shell" |
| 34 | and "coverage" commands). |
| 35 | |
| 36 | cleanup: Undoes "setup". |
| 37 | |
| 38 | Note that cros_fuzz will print every shell command it runs if you set the |
| 39 | log-level to debug ("--log-level debug"). Otherwise it will print commands that |
| 40 | fail. |
| 41 | """ |
| 42 | |
Chris McDonald | 59650c3 | 2021-07-20 15:29:28 -0600 | [diff] [blame] | 43 | import logging |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 44 | import os |
| 45 | import shutil |
| 46 | |
Chris McDonald | 59650c3 | 2021-07-20 15:29:28 -0600 | [diff] [blame] | 47 | from chromite.third_party import lddtree |
| 48 | from chromite.third_party.pyelftools.elftools.elf.elffile import ELFFile |
| 49 | |
Mike Frysinger | 06a51c8 | 2021-04-06 11:39:17 -0400 | [diff] [blame] | 50 | from chromite.lib import build_target_lib |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 51 | from chromite.lib import commandline |
| 52 | from chromite.lib import constants |
| 53 | from chromite.lib import cros_build_lib |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 54 | from chromite.lib import gs |
| 55 | from chromite.lib import osutils |
Manoj Gupta | e5e1e61 | 2019-10-21 12:39:57 -0700 | [diff] [blame] | 56 | from chromite.lib import portage_util |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 57 | |
Mike Frysinger | 03b983f | 2020-02-21 02:31:49 -0500 | [diff] [blame] | 58 | |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 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. |
| 64 | SCRIPT_STORAGE_DIRECTORY = 'fuzz' |
| 65 | SCRIPT_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. |
| 69 | CORPUS_DIRECTORY_NAME = 'corpus' |
| 70 | TESTCASE_DIRECTORY_NAME = 'testcase' |
| 71 | COVERAGE_REPORT_DIRECTORY_NAME = 'coverage-report' |
| 72 | |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 73 | # Constants for names of libFuzzer command line options. |
| 74 | RUNS_OPTION_NAME = 'runs' |
| 75 | MAX_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). |
| 79 | DEFAULT_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. |
| 83 | RUNS_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. |
| 86 | MAX_TOTAL_TIME_DEFAULT_VALUE = 30 |
| 87 | |
| 88 | |
| 89 | class BuildType(object): |
| 90 | """Class to hold the different kinds of build types.""" |
| 91 | |
| 92 | ASAN = 'asan' |
Manoj Gupta | e207b56 | 2019-05-02 11:30:35 -0700 | [diff] [blame] | 93 | MSAN = 'msan' |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 94 | UBSAN = 'ubsan' |
| 95 | COVERAGE = 'coverage' |
| 96 | STANDARD = '' |
| 97 | |
| 98 | # Build types that users can specify. |
Manoj Gupta | e207b56 | 2019-05-02 11:30:35 -0700 | [diff] [blame] | 99 | CHOICES = (ASAN, MSAN, UBSAN, COVERAGE) |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 100 | |
| 101 | |
| 102 | class 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 | """ |
Mike Frysinger | 06a51c8 | 2021-04-06 11:39:17 -0400 | [diff] [blame] | 142 | cls.path_to_sysroot = build_target_lib.get_default_sysroot_path(board) |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 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 Metzman | b2c3373 | 2018-11-08 11:33:35 -0800 | [diff] [blame] | 152 | assert self.path_to_sysroot is not None, 'set SysrootPath.path_to_sysroot' |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 153 | 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 | |
| 192 | def 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 | |
| 209 | def 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 | |
| 222 | def 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 | |
| 235 | def 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 | |
| 247 | def 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 | |
| 259 | def 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 | |
| 270 | def 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) |
Manoj Gupta | 639d30f | 2019-10-28 16:24:25 -0700 | [diff] [blame] | 291 | osutils.RmDir(dest_corpus_path.chroot, ignore_missing=True) |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 292 | shutil.copytree(src_corpus_path, dest_corpus_path.chroot) |
| 293 | return dest_corpus_path |
| 294 | |
| 295 | |
| 296 | def 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 | |
Mike Frysinger | 45602c7 | 2019-09-22 02:15:11 -0400 | [diff] [blame] | 323 | def sudo_run(*args, **kwargs): |
| 324 | """Wrapper around cros_build_lib.sudo_run. |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 325 | |
Mike Frysinger | 45602c7 | 2019-09-22 02:15:11 -0400 | [diff] [blame] | 326 | Wrapper that calls cros_build_lib.sudo_run but sets debug_level by |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 327 | default. |
| 328 | |
| 329 | Args: |
Mike Frysinger | 45602c7 | 2019-09-22 02:15:11 -0400 | [diff] [blame] | 330 | *args: Positional arguments to pass to cros_build_lib.sudo_run. |
| 331 | *kwargs: Keyword arguments to pass to cros_build_lib.sudo_run. |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 332 | |
| 333 | Returns: |
Mike Frysinger | 45602c7 | 2019-09-22 02:15:11 -0400 | [diff] [blame] | 334 | The value returned by calling cros_build_lib.sudo_run. |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 335 | """ |
| 336 | kwargs.setdefault('debug_level', logging.DEBUG) |
Mike Frysinger | 45602c7 | 2019-09-22 02:15:11 -0400 | [diff] [blame] | 337 | return cros_build_lib.sudo_run(*args, **kwargs) |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 338 | |
| 339 | |
| 340 | def 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 | |
| 353 | def 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 | |
| 362 | def 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 Metzman | b2c3373 | 2018-11-08 11:33:35 -0800 | [diff] [blame] | 374 | if any(IsOptionLimit(x) for x in fuzz_command[1:]): |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 375 | # 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 Metzman | b2c3373 | 2018-11-08 11:33:35 -0800 | [diff] [blame] | 391 | def 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. |
Manoj Gupta | 339b356 | 2021-10-20 11:11:29 -0700 | [diff] [blame^] | 409 | # disable odr violation since many fuzzers hit it and it is also disabled on |
| 410 | # clusterfuzz. |
| 411 | options_dict = {'log_path': 'stderr', 'detect_odr_violation': '0'} |
Jonathan Metzman | b2c3373 | 2018-11-08 11:33:35 -0800 | [diff] [blame] | 412 | options_dict.update(extra_options) |
| 413 | sanitizer_options = ':'.join('%s=%s' % x for x in options_dict.items()) |
| 414 | sanitizers = ('ASAN', 'MSAN', 'UBSAN') |
| 415 | return {x + '_OPTIONS': sanitizer_options for x in sanitizers} |
| 416 | |
| 417 | |
Manoj Gupta | 5ca1765 | 2019-05-13 11:15:33 -0700 | [diff] [blame] | 418 | def RunFuzzer(fuzzer, |
| 419 | corpus_path=None, |
| 420 | fuzz_args='', |
| 421 | testcase_path=None, |
Jonathan Metzman | b2c3373 | 2018-11-08 11:33:35 -0800 | [diff] [blame] | 422 | crash_expected=False): |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 423 | """Runs the fuzzer while chrooted into the sysroot. |
| 424 | |
| 425 | Args: |
| 426 | fuzzer: The fuzzer to run. |
Jonathan Metzman | b2c3373 | 2018-11-08 11:33:35 -0800 | [diff] [blame] | 427 | corpus_path: A path to a corpus (not necessarily in the sysroot) to run the |
| 428 | fuzzer on. |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 429 | fuzz_args: Additional arguments to pass to the fuzzer when running it. |
| 430 | testcase_path: A path to a testcase (not necessarily in the sysroot) to run |
| 431 | the fuzzer on. |
Jonathan Metzman | b2c3373 | 2018-11-08 11:33:35 -0800 | [diff] [blame] | 432 | crash_expected: Is it normal for the fuzzer to crash on this run? |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 433 | """ |
| 434 | logging.info('Running fuzzer: %s', fuzzer) |
| 435 | fuzzer_sysroot_path = GetFuzzerSysrootPath(fuzzer) |
| 436 | fuzz_command = [fuzzer_sysroot_path.sysroot] |
| 437 | fuzz_command += fuzz_args.split() |
| 438 | |
| 439 | if testcase_path: |
| 440 | fuzz_command.append(testcase_path) |
| 441 | else: |
| 442 | LimitFuzzing(fuzz_command, corpus_path) |
| 443 | |
| 444 | if corpus_path: |
| 445 | fuzz_command.append(corpus_path) |
| 446 | |
Jonathan Metzman | b2c3373 | 2018-11-08 11:33:35 -0800 | [diff] [blame] | 447 | if crash_expected: |
| 448 | # Don't return nonzero when fuzzer OOMs, leaks, or timesout, since we don't |
| 449 | # want an exception in those cases. The user may be trying to reproduce |
| 450 | # those issues. |
| 451 | fuzz_command += ['-error_exitcode=0', '-timeout_exitcode=0'] |
| 452 | |
| 453 | # We must set exitcode=0 or else the fuzzer will return nonzero on |
| 454 | # successful reproduction. |
| 455 | sanitizer_options = {'exitcode': '0'} |
| 456 | else: |
| 457 | sanitizer_options = {} |
| 458 | |
| 459 | extra_env = GetFuzzExtraEnv(sanitizer_options) |
| 460 | RunSysrootCommand(fuzz_command, extra_env=extra_env, debug_level=logging.INFO) |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 461 | |
| 462 | |
| 463 | def MergeProfraw(fuzzer): |
| 464 | """Merges profraw file from a fuzzer and creates a profdata file. |
| 465 | |
| 466 | Args: |
| 467 | fuzzer: The fuzzer to merge the profraw file from. |
| 468 | """ |
| 469 | profdata_path = GetProfdataPath(fuzzer) |
| 470 | command = [ |
| 471 | 'llvm-profdata', |
| 472 | 'merge', |
| 473 | '-sparse', |
| 474 | DEFAULT_PROFRAW_PATH, |
| 475 | '-o', |
| 476 | profdata_path.sysroot, |
| 477 | ] |
| 478 | |
| 479 | RunSysrootCommand(command) |
| 480 | return profdata_path |
| 481 | |
| 482 | |
| 483 | def GenerateCoverageReport(fuzzer, shared_libraries): |
| 484 | """Generates an HTML coverage report from a fuzzer run. |
| 485 | |
| 486 | Args: |
| 487 | fuzzer: The fuzzer to generate the coverage report for. |
| 488 | shared_libraries: Libraries loaded dynamically by |fuzzer|. |
| 489 | |
| 490 | Returns: |
| 491 | The path of the coverage report. |
| 492 | """ |
| 493 | fuzzer_path = GetFuzzerSysrootPath(fuzzer).chroot |
| 494 | command = ['llvm-cov', 'show', '-object', fuzzer_path] |
| 495 | for library in shared_libraries: |
| 496 | command += ['-object', library] |
| 497 | |
| 498 | coverage_directory = GetCoverageDirectory(fuzzer) |
| 499 | command += [ |
| 500 | '-format=html', |
| 501 | '-instr-profile=%s' % GetProfdataPath(fuzzer).chroot, |
| 502 | '-output-dir=%s' % coverage_directory.chroot, |
| 503 | ] |
| 504 | |
| 505 | # TODO(metzman): Investigate error messages printed by this command. |
Mike Frysinger | 0282d22 | 2019-12-17 17:15:48 -0500 | [diff] [blame] | 506 | cros_build_lib.run(command, stderr=True, debug_level=logging.DEBUG) |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 507 | return coverage_directory |
| 508 | |
| 509 | |
| 510 | def GetSharedLibraries(binary_path): |
| 511 | """Gets the shared libraries used by a binary. |
| 512 | |
| 513 | Gets the shared libraries used by the binary. Based on GetSharedLibraries from |
| 514 | src/tools/code_coverage/coverage_utils.py in Chromium. |
| 515 | |
| 516 | Args: |
| 517 | binary_path: The path to the binary we want to find the shared libraries of. |
| 518 | |
| 519 | Returns: |
| 520 | The shared libraries used by |binary_path|. |
| 521 | """ |
| 522 | logging.info('Finding shared libraries for targets (if any).') |
| 523 | shared_libraries = [] |
| 524 | elf_dict = lddtree.ParseELF( |
| 525 | binary_path.chroot, root=SysrootPath.path_to_sysroot) |
Mike Frysinger | 0bdbc10 | 2019-06-13 15:27:29 -0400 | [diff] [blame] | 526 | for shared_library in elf_dict['libs'].values(): |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 527 | shared_library_path = shared_library['path'] |
| 528 | |
| 529 | if shared_library_path in shared_libraries: |
| 530 | continue |
| 531 | |
| 532 | assert os.path.exists(shared_library_path), ('Shared library "%s" used by ' |
| 533 | 'the given target(s) does not ' |
| 534 | 'exist.' % shared_library_path) |
| 535 | |
| 536 | if IsInstrumentedWithClangCoverage(shared_library_path): |
| 537 | # Do not add non-instrumented libraries. Otherwise, llvm-cov errors out. |
| 538 | shared_libraries.append(shared_library_path) |
| 539 | |
| 540 | logging.debug('Found shared libraries (%d): %s.', len(shared_libraries), |
| 541 | shared_libraries) |
| 542 | logging.info('Finished finding shared libraries for targets.') |
| 543 | return shared_libraries |
| 544 | |
| 545 | |
| 546 | def IsInstrumentedWithClangCoverage(binary_path): |
| 547 | """Determines if a binary is instrumented with clang source based coverage. |
| 548 | |
| 549 | Args: |
| 550 | binary_path: The path of the binary (executable or library) we are checking |
| 551 | is instrumented with clang source based coverage. |
| 552 | |
| 553 | Returns: |
| 554 | True if the binary is instrumented with clang source based coverage. |
| 555 | """ |
| 556 | with open(binary_path, 'rb') as file_handle: |
| 557 | elf_file = ELFFile(file_handle) |
Manoj Gupta | 339b356 | 2021-10-20 11:11:29 -0700 | [diff] [blame^] | 558 | return elf_file.get_section_by_name(b'__llvm_covmap') is not None |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 559 | |
| 560 | |
| 561 | def RunFuzzerAndGenerateCoverageReport(fuzzer, corpus, fuzz_args): |
| 562 | """Runs a fuzzer generates a coverage report and returns the report's path. |
| 563 | |
| 564 | Gets a coverage report for a fuzzer. |
| 565 | |
| 566 | Args: |
| 567 | fuzzer: The fuzzer to run and generate the coverage report for. |
| 568 | corpus: The path to a corpus to run the fuzzer on. |
| 569 | fuzz_args: Additional arguments to pass to the fuzzer. |
| 570 | |
| 571 | Returns: |
| 572 | The path to the coverage report. |
| 573 | """ |
| 574 | corpus_path = CopyCorpusToSysroot(corpus) |
| 575 | if corpus_path: |
| 576 | corpus_path = corpus_path.sysroot |
| 577 | |
| 578 | RunFuzzer(fuzzer, corpus_path=corpus_path, fuzz_args=fuzz_args) |
| 579 | MergeProfraw(fuzzer) |
| 580 | fuzzer_sysroot_path = GetFuzzerSysrootPath(fuzzer) |
| 581 | shared_libraries = GetSharedLibraries(fuzzer_sysroot_path) |
| 582 | return GenerateCoverageReport(fuzzer, shared_libraries) |
| 583 | |
| 584 | |
Jonathan Metzman | b2c3373 | 2018-11-08 11:33:35 -0800 | [diff] [blame] | 585 | def RunSysrootCommand(command, **kwargs): |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 586 | """Runs command while chrooted into sysroot and returns the output. |
| 587 | |
| 588 | Args: |
| 589 | command: A command to run in the sysroot. |
Mike Frysinger | 45602c7 | 2019-09-22 02:15:11 -0400 | [diff] [blame] | 590 | kwargs: Extra arguments to pass to cros_build_lib.sudo_run. |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 591 | |
| 592 | Returns: |
Mike Frysinger | 45602c7 | 2019-09-22 02:15:11 -0400 | [diff] [blame] | 593 | The result of a call to cros_build_lib.sudo_run. |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 594 | """ |
| 595 | command = ['chroot', SysrootPath.path_to_sysroot] + command |
Mike Frysinger | 45602c7 | 2019-09-22 02:15:11 -0400 | [diff] [blame] | 596 | return sudo_run(command, **kwargs) |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 597 | |
| 598 | |
| 599 | def GetBuildExtraEnv(build_type): |
| 600 | """Gets the extra_env for building a package. |
| 601 | |
| 602 | Args: |
| 603 | build_type: The type of build we want to do. |
| 604 | |
| 605 | Returns: |
| 606 | The extra_env to use when building. |
| 607 | """ |
| 608 | if build_type is None: |
| 609 | build_type = BuildType.ASAN |
| 610 | |
| 611 | use_flags = os.environ.get('USE', '').split() |
| 612 | # Check that the user hasn't already set USE flags that we can set. |
| 613 | # No good way to iterate over an enum in python2. |
| 614 | for use_flag in BuildType.CHOICES: |
| 615 | if use_flag in use_flags: |
Mike Frysinger | 968c114 | 2020-05-09 00:37:56 -0400 | [diff] [blame] | 616 | logging.warning('%s in USE flags. Please use --build_type instead.', |
| 617 | use_flag) |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 618 | |
| 619 | # Set USE flags. |
| 620 | fuzzer_build_type = 'fuzzer' |
| 621 | use_flags += [fuzzer_build_type, build_type] |
| 622 | features_flags = os.environ.get('FEATURES', '').split() |
| 623 | if build_type == BuildType.COVERAGE: |
| 624 | # We must use ASan when doing coverage builds. |
| 625 | use_flags.append(BuildType.ASAN) |
| 626 | # Use noclean so that a coverage report can be generated based on the source |
| 627 | # code. |
| 628 | features_flags.append('noclean') |
| 629 | |
| 630 | return { |
| 631 | 'FEATURES': ' '.join(features_flags), |
| 632 | 'USE': ' '.join(use_flags), |
| 633 | } |
| 634 | |
| 635 | |
| 636 | def BuildPackage(package, board, build_type): |
| 637 | """Builds a package on a specified board. |
| 638 | |
| 639 | Args: |
| 640 | package: The package to build. Nothing is built if None. |
| 641 | board: The board to build the package on. |
Manoj Gupta | e207b56 | 2019-05-02 11:30:35 -0700 | [diff] [blame] | 642 | build_type: The type of the build to do (e.g. asan, msan, ubsan, coverage). |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 643 | """ |
| 644 | if package is None: |
| 645 | return |
| 646 | |
| 647 | logging.info('Building %s using %s.', package, build_type) |
Jonathan Metzman | b2c3373 | 2018-11-08 11:33:35 -0800 | [diff] [blame] | 648 | extra_env = GetBuildExtraEnv(build_type) |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 649 | build_packages_path = os.path.join(constants.SOURCE_ROOT, 'src', 'scripts', |
| 650 | 'build_packages') |
| 651 | command = [ |
| 652 | build_packages_path, |
| 653 | '--board', |
| 654 | board, |
| 655 | '--skip_chroot_upgrade', |
| 656 | package, |
| 657 | ] |
Manoj Gupta | 5ca1765 | 2019-05-13 11:15:33 -0700 | [diff] [blame] | 658 | # For msan builds, always use "--nousepkg" since all package needs to be |
| 659 | # instrumented with msan. |
| 660 | if build_type == BuildType.MSAN: |
| 661 | command += ['--nousepkg'] |
| 662 | |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 663 | # Print the output of the build command. Do this because it is familiar to |
| 664 | # devs and we don't want to leave them not knowing about the build's progress |
| 665 | # for a long time. |
Mike Frysinger | 45602c7 | 2019-09-22 02:15:11 -0400 | [diff] [blame] | 666 | cros_build_lib.run(command, extra_env=extra_env) |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 667 | |
| 668 | |
| 669 | def DownloadFuzzerCorpus(fuzzer, dest_directory=None): |
| 670 | """Downloads a corpus and returns its path. |
| 671 | |
Jonathan Metzman | b2c3373 | 2018-11-08 11:33:35 -0800 | [diff] [blame] | 672 | Downloads a corpus to a subdirectory of dest_directory if specified and |
| 673 | returns path on the filesystem of the corpus. Asks users to authenticate |
| 674 | if permission to read from bucket is denied. |
| 675 | |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 676 | Args: |
| 677 | fuzzer: The name of the fuzzer who's corpus we want to download. |
| 678 | dest_directory: The directory to download the corpus to. |
| 679 | |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 680 | Returns: |
| 681 | The path to the downloaded corpus. |
| 682 | |
| 683 | Raises: |
| 684 | gs.NoSuchKey: A corpus for the fuzzer doesn't exist. |
| 685 | gs.GSCommandError: The corpus failed to download for another reason. |
| 686 | """ |
| 687 | if not fuzzer.startswith('chromeos_'): |
| 688 | # ClusterFuzz internally appends "chromeos_" to chromeos targets' names. |
| 689 | # Therefore we must do so in order to find the corpus. |
| 690 | fuzzer = 'chromeos_%s' % fuzzer |
| 691 | |
| 692 | if dest_directory is None: |
| 693 | dest_directory = GetScriptStoragePath(CORPUS_DIRECTORY_NAME).chroot |
| 694 | osutils.SafeMakedirsNonRoot(dest_directory) |
| 695 | |
| 696 | clusterfuzz_gcs_corpus_bucket = 'chromeos-corpus' |
| 697 | suburl = 'libfuzzer/%s' % fuzzer |
| 698 | gcs_path = gs.GetGsURL( |
| 699 | clusterfuzz_gcs_corpus_bucket, |
| 700 | for_gsutil=True, |
| 701 | public=False, |
| 702 | suburl=suburl) |
| 703 | |
| 704 | dest_path = os.path.join(dest_directory, fuzzer) |
| 705 | |
| 706 | try: |
| 707 | logging.info('Downloading corpus to %s.', dest_path) |
| 708 | ctx = gs.GSContext() |
| 709 | ctx.Copy( |
| 710 | gcs_path, |
| 711 | dest_directory, |
| 712 | recursive=True, |
| 713 | parallel=True, |
| 714 | debug_level=logging.DEBUG) |
| 715 | logging.info('Finished downloading corpus.') |
| 716 | except gs.GSNoSuchKey as exception: |
| 717 | logging.error('Corpus for fuzzer: %s does not exist.', fuzzer) |
| 718 | raise exception |
| 719 | # Try to authenticate if we were denied permission to access the corpus. |
| 720 | except gs.GSCommandError as exception: |
| 721 | logging.error( |
| 722 | 'gsutil failed to download the corpus. You may need to log in. See:\n' |
Mike Frysinger | 92dc649 | 2021-02-17 16:01:09 -0500 | [diff] [blame] | 723 | 'https://chromium.googlesource.com/chromiumos/docs/+/HEAD/gsutil.md' |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 724 | '#setup\n' |
| 725 | 'for instructions on doing this.') |
| 726 | raise exception |
| 727 | |
| 728 | return dest_path |
| 729 | |
| 730 | |
| 731 | def Reproduce(fuzzer, testcase_path): |
| 732 | """Runs a fuzzer in the sysroot on a testcase. |
| 733 | |
| 734 | Args: |
| 735 | fuzzer: The fuzzer to run. |
| 736 | testcase_path: The path (not necessarily in the sysroot) of the testcase to |
| 737 | run the fuzzer on. |
| 738 | """ |
Jonathan Metzman | b2c3373 | 2018-11-08 11:33:35 -0800 | [diff] [blame] | 739 | testcase_sysroot_path = CopyTestcaseToSysroot(testcase_path).sysroot |
| 740 | RunFuzzer(fuzzer, testcase_path=testcase_sysroot_path, crash_expected=True) |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 741 | |
| 742 | |
| 743 | def SetUpSysrootForFuzzing(): |
| 744 | """Sets up the the sysroot for fuzzing |
| 745 | |
| 746 | Prepares the sysroot for fuzzing. Idempotent. |
| 747 | """ |
| 748 | logging.info('Setting up sysroot for fuzzing.') |
| 749 | # TODO(metzman): Don't create devices or mount /proc, use platform2_test.py |
| 750 | # instead. |
| 751 | # Mount /proc in sysroot and setup dev there because they are needed by |
| 752 | # sanitizers. |
| 753 | proc_manager = ProcManager() |
| 754 | proc_manager.Mount() |
| 755 | |
| 756 | # Setup devices in /dev that are needed by libFuzzer. |
| 757 | device_manager = DeviceManager() |
| 758 | device_manager.SetUp() |
| 759 | |
| 760 | # Set up asan_symbolize.py, llvm-symbolizer, and llvm-profdata in the |
| 761 | # sysroot so that fuzzer output (including stack traces) can be symbolized |
| 762 | # and so that coverage reports can be generated. |
| 763 | tool_manager = ToolManager() |
| 764 | tool_manager.Install() |
| 765 | |
| 766 | osutils.SafeMakedirsNonRoot(GetSysrootPath(SCRIPT_STORAGE_PATH)) |
| 767 | |
| 768 | |
| 769 | def CleanUpSysroot(): |
| 770 | """Cleans up the the sysroot from SetUpSysrootForFuzzing. |
| 771 | |
| 772 | Undoes SetUpSysrootForFuzzing. Idempotent. |
| 773 | """ |
| 774 | logging.info('Cleaning up the sysroot.') |
| 775 | proc_manager = ProcManager() |
| 776 | proc_manager.Unmount() |
| 777 | |
| 778 | device_manager = DeviceManager() |
| 779 | device_manager.CleanUp() |
| 780 | |
| 781 | tool_manager = ToolManager() |
| 782 | tool_manager.Uninstall() |
Jonathan Metzman | b2c3373 | 2018-11-08 11:33:35 -0800 | [diff] [blame] | 783 | osutils.RmDir(GetSysrootPath(SCRIPT_STORAGE_PATH), ignore_missing=True) |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 784 | |
| 785 | |
| 786 | class ToolManager(object): |
| 787 | """Class that installs or uninstalls fuzzing tools to/from the sysroot. |
| 788 | |
| 789 | Install and Uninstall methods are idempotent. Both are safe to call at any |
| 790 | point. |
| 791 | """ |
| 792 | |
| 793 | # Path to asan_symbolize.py. |
| 794 | ASAN_SYMBOLIZE_PATH = os.path.join('/', 'usr', 'bin', 'asan_symbolize.py') |
| 795 | |
| 796 | # List of LLVM binaries we must install in sysroot. |
Manoj Gupta | feb1b7a | 2019-02-20 11:04:05 -0800 | [diff] [blame] | 797 | LLVM_BINARY_NAMES = ['gdbserver', 'llvm-symbolizer', 'llvm-profdata'] |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 798 | |
| 799 | def __init__(self): |
| 800 | self.asan_symbolize_sysroot_path = GetSysrootPath(self.ASAN_SYMBOLIZE_PATH) |
| 801 | |
| 802 | def Install(self): |
| 803 | """Installs tools to the sysroot.""" |
| 804 | # Install asan_symbolize.py. |
Mike Frysinger | 45602c7 | 2019-09-22 02:15:11 -0400 | [diff] [blame] | 805 | sudo_run(['cp', self.ASAN_SYMBOLIZE_PATH, self.asan_symbolize_sysroot_path]) |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 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 Metzman | b2c3373 | 2018-11-08 11:33:35 -0800 | [diff] [blame] | 822 | return [LlvmBinary(x) for x in self.LLVM_BINARY_NAMES] |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 823 | |
| 824 | |
| 825 | class 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 Gupta | feb1b7a | 2019-02-20 11:04:05 -0800 | [diff] [blame] | 856 | 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 Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 863 | 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 | ] |
Mike Frysinger | 45602c7 | 2019-09-22 02:15:11 -0400 | [diff] [blame] | 876 | sudo_run(cmd) |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 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 | |
| 886 | class 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) |
Mike Frysinger | 0bdbc10 | 2019-06-13 15:27:29 -0400 | [diff] [blame] | 915 | for device, mknod_params in self.DEVICE_MKNOD_PARAMS.items(): |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 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. |
Mike Frysinger | 45602c7 | 2019-09-22 02:15:11 -0400 | [diff] [blame] | 928 | sudo_run(['rm', '-r', device_path]) |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 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] |
Mike Frysinger | 45602c7 | 2019-09-22 02:15:11 -0400 | [diff] [blame] | 935 | sudo_run(command) |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 936 | |
| 937 | |
| 938 | class 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 | |
| 966 | def EnterSysrootShell(): |
| 967 | """Spawns and gives user access to a bash shell in the sysroot.""" |
| 968 | command = ['/bin/bash', '-i'] |
| 969 | return RunSysrootCommand( |
Jonathan Metzman | b2c3373 | 2018-11-08 11:33:35 -0800 | [diff] [blame] | 970 | command, |
| 971 | extra_env=GetFuzzExtraEnv(), |
| 972 | debug_level=logging.INFO, |
Mike Frysinger | f5a3b2d | 2019-12-12 14:36:17 -0500 | [diff] [blame] | 973 | check=False).returncode |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 974 | |
| 975 | |
| 976 | def 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: |
Mike Frysinger | 968c114 | 2020-05-09 00:37:56 -0400 | [diff] [blame] | 1001 | logging.warning( |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 1002 | '%s contains a prefix from ClusterFuzz (one or more of %s) that is not ' |
Mike Frysinger | 80de501 | 2019-08-01 14:10:53 -0400 | [diff] [blame] | 1003 | "part of the fuzzer's name. Interpreting --fuzzer as %s.", |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 1004 | initial_name, clusterfuzz_prefixes, fuzzer_name) |
| 1005 | |
| 1006 | return fuzzer_name |
| 1007 | |
| 1008 | |
| 1009 | def 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 | |
| 1022 | def ExecuteSetupCommand(): |
| 1023 | """Executes the "setup" command. Wrapper for SetUpSysrootForFuzzing. |
| 1024 | |
| 1025 | Sets up the sysroot for fuzzing. |
| 1026 | """ |
| 1027 | SetUpSysrootForFuzzing() |
| 1028 | |
| 1029 | |
| 1030 | def ExecuteCleanupCommand(): |
| 1031 | """Executes the "cleanup" command. Wrapper for CleanUpSysroot. |
| 1032 | |
| 1033 | Undoes pre-fuzzing setup. |
| 1034 | """ |
| 1035 | CleanUpSysroot() |
| 1036 | |
| 1037 | |
| 1038 | def 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 | |
| 1080 | def ExecuteDownloadCommand(options): |
| 1081 | """Executes the "download" command. Wrapper around DownloadFuzzerCorpus.""" |
| 1082 | DownloadFuzzerCorpus(StripFuzzerPrefixes(options.fuzzer), options.directory) |
| 1083 | |
| 1084 | |
| 1085 | def 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 Gupta | 5ca1765 | 2019-05-13 11:15:33 -0700 | [diff] [blame] | 1097 | # 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'] |
Manoj Gupta | bc6fc7f | 2020-04-17 19:24:24 -0700 | [diff] [blame] | 1101 | cflags = cros_build_lib.run( |
| 1102 | cmd, capture_output=True, encoding='utf-8').stdout.splitlines() |
Manoj Gupta | 5ca1765 | 2019-05-13 11:15:33 -0700 | [diff] [blame] | 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 Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 1111 | BuildPackage(options.package, options.board, options.build_type) |
| 1112 | SetUpSysrootForFuzzing() |
| 1113 | Reproduce(StripFuzzerPrefixes(options.fuzzer), options.testcase) |
| 1114 | |
Manoj Gupta | e5e1e61 | 2019-10-21 12:39:57 -0700 | [diff] [blame] | 1115 | |
Manoj Gupta | ec08b81 | 2019-10-10 14:21:16 -0700 | [diff] [blame] | 1116 | def InstallBaseDependencies(options): |
Mike Frysinger | df1d0b0 | 2019-11-12 17:44:12 -0500 | [diff] [blame] | 1117 | """Installs the base packages needed to chroot in board sysroot. |
Manoj Gupta | ec08b81 | 2019-10-10 14:21:16 -0700 | [diff] [blame] | 1118 | |
| 1119 | Args: |
| 1120 | options: The parsed arguments passed to this program. |
| 1121 | """ |
Manoj Gupta | e5e1e61 | 2019-10-21 12:39:57 -0700 | [diff] [blame] | 1122 | package = 'virtual/implicit-system' |
| 1123 | if not portage_util.IsPackageInstalled( |
| 1124 | package, sysroot=SysrootPath.path_to_sysroot): |
| 1125 | build_type = getattr(options, 'build_type', None) |
| 1126 | BuildPackage(package, options.board, build_type) |
| 1127 | |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 1128 | |
| 1129 | def ParseArgs(argv): |
| 1130 | """Parses program arguments. |
| 1131 | |
| 1132 | Args: |
| 1133 | argv: The program arguments we want to parse. |
| 1134 | |
| 1135 | Returns: |
| 1136 | An options object which will tell us which command to run and which options |
| 1137 | to use for that command. |
| 1138 | """ |
| 1139 | parser = commandline.ArgumentParser(description=__doc__) |
| 1140 | |
| 1141 | parser.add_argument( |
| 1142 | '--board', |
| 1143 | default=cros_build_lib.GetDefaultBoard(), |
| 1144 | help='Board on which to run test.') |
| 1145 | |
| 1146 | subparsers = parser.add_subparsers(dest='command') |
| 1147 | |
| 1148 | subparsers.add_parser('cleanup', help='Undo setup command.') |
| 1149 | coverage_parser = subparsers.add_parser( |
| 1150 | 'coverage', help='Get a coverage report for a fuzzer.') |
| 1151 | |
| 1152 | coverage_parser.add_argument('--package', help='Package to build.') |
| 1153 | |
| 1154 | corpus_parser = coverage_parser.add_mutually_exclusive_group() |
| 1155 | corpus_parser.add_argument('--corpus', help='Corpus to run fuzzer on.') |
| 1156 | |
| 1157 | corpus_parser.add_argument( |
| 1158 | '--download', |
| 1159 | action='store_true', |
| 1160 | help='Generate coverage report based on corpus from ClusterFuzz.') |
| 1161 | |
| 1162 | coverage_parser.add_argument( |
| 1163 | '--fuzzer', |
| 1164 | required=True, |
| 1165 | help='The fuzz target to generate a coverage report for.') |
| 1166 | |
| 1167 | coverage_parser.add_argument( |
| 1168 | '--fuzz-args', |
| 1169 | default='', |
| 1170 | help='Arguments to pass libFuzzer. ' |
| 1171 | 'Please use an equals sign or parsing will fail ' |
| 1172 | '(i.e. --fuzzer_args="-rss_limit_mb=2048 -print_funcs=1").') |
| 1173 | |
| 1174 | download_parser = subparsers.add_parser('download', help='Download a corpus.') |
| 1175 | |
| 1176 | download_parser.add_argument( |
| 1177 | '--directory', help='Path to directory to download the corpus to.') |
| 1178 | |
| 1179 | download_parser.add_argument( |
| 1180 | '--fuzzer', required=True, help='Fuzzer to download the corpus for.') |
| 1181 | |
| 1182 | reproduce_parser = subparsers.add_parser( |
| 1183 | 'reproduce', help='Run a fuzzer on a testcase.') |
| 1184 | |
| 1185 | reproduce_parser.add_argument( |
| 1186 | '--testcase', required=True, help='Path of testcase to run fuzzer on.') |
| 1187 | |
| 1188 | reproduce_parser.add_argument( |
| 1189 | '--fuzzer', required=True, help='Fuzzer to reproduce the crash on.') |
| 1190 | |
| 1191 | reproduce_parser.add_argument('--package', help='Package to build.') |
| 1192 | |
| 1193 | reproduce_parser.add_argument( |
| 1194 | '--build-type', |
| 1195 | choices=BuildType.CHOICES, |
| 1196 | help='Type of build.', |
| 1197 | type=str.lower) # Ignore sanitizer case. |
| 1198 | |
| 1199 | subparsers.add_parser('setup', help='Set up the sysroot to test fuzzing.') |
| 1200 | |
| 1201 | subparsers.add_parser( |
| 1202 | 'shell', |
| 1203 | help='Set up sysroot for fuzzing and get a shell in the sysroot.') |
| 1204 | |
| 1205 | opts = parser.parse_args(argv) |
| 1206 | opts.Freeze() |
| 1207 | return opts |
| 1208 | |
| 1209 | |
| 1210 | def main(argv): |
| 1211 | """Parses arguments and executes a command. |
| 1212 | |
| 1213 | Args: |
| 1214 | argv: The prorgram arguments. |
| 1215 | |
| 1216 | Returns: |
| 1217 | 0 on success. Non-zero on failure. |
| 1218 | """ |
| 1219 | cros_build_lib.AssertInsideChroot() |
| 1220 | options = ParseArgs(argv) |
| 1221 | if options.board is None: |
| 1222 | logging.error('Please specify "--board" or set ".default_board".') |
| 1223 | return 1 |
| 1224 | |
| 1225 | SysrootPath.SetPathToSysroot(options.board) |
| 1226 | |
Manoj Gupta | ec08b81 | 2019-10-10 14:21:16 -0700 | [diff] [blame] | 1227 | InstallBaseDependencies(options) |
| 1228 | |
Jonathan Metzman | d5ee1c6 | 2018-11-05 10:33:08 -0800 | [diff] [blame] | 1229 | if options.command == 'cleanup': |
| 1230 | ExecuteCleanupCommand() |
| 1231 | elif options.command == 'coverage': |
| 1232 | ExecuteCoverageCommand(options) |
| 1233 | elif options.command == 'setup': |
| 1234 | ExecuteSetupCommand() |
| 1235 | elif options.command == 'download': |
| 1236 | ExecuteDownloadCommand(options) |
| 1237 | elif options.command == 'reproduce': |
| 1238 | ExecuteReproduceCommand(options) |
| 1239 | elif options.command == 'shell': |
| 1240 | return ExecuteShellCommand() |
| 1241 | |
| 1242 | return 0 |