Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 1 | #!/usr/bin/python |
| 2 | # Copyright 2017 The Chromium 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. |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 5 | """This script helps to generate code coverage report. |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 6 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 7 | It uses Clang Source-based Code Coverage - |
| 8 | https://clang.llvm.org/docs/SourceBasedCodeCoverage.html |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 9 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 10 | In order to generate code coverage report, you need to first build the target |
| 11 | program with "use_clang_coverage=true" GN flag. |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 12 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 13 | It is recommended to set "is_component_build=false" flag explicitly in GN |
| 14 | configuration because: |
| 15 | 1. It is incompatible with other sanitizer flags (like "is_asan", "is_msan") |
| 16 | and others like "optimize_for_fuzzing". |
| 17 | 2. If it is not set explicitly, "is_debug" overrides it to true. |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 18 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 19 | Example usage: |
| 20 | |
| 21 | python tools/code_coverage/coverage.py crypto_unittests url_unittests \\ |
| 22 | -b out/coverage -o out/report -c 'out/coverage/crypto_unittests' \\ |
| 23 | -c 'out/coverage/url_unittests --gtest_filter=URLParser.PathURL' |
| 24 | |
| 25 | The command above generates code coverage report for crypto_unittests and |
| 26 | url_unittests and all generated artifacts are stored in out/report. |
| 27 | For url_unittests, it only runs the test URLParser.PathURL. |
| 28 | |
| 29 | If you are building a fuzz target, you need to add "use_libfuzzer=true" GN |
| 30 | flag as well. |
| 31 | |
| 32 | Sample workflow for a fuzz target (e.g. pdfium_fuzzer): |
| 33 | |
| 34 | python tools/code_coverage/coverage.py \\ |
| 35 | -b out/coverage -o out/report \\ |
| 36 | -c 'out/coverage/pdfium_fuzzer -runs=<runs> <corpus_dir>' |
| 37 | |
| 38 | where: |
| 39 | <corpus_dir> - directory containing samples files for this format. |
| 40 | <runs> - number of times to fuzz target function. Should be 0 when you just |
| 41 | want to see the coverage on corpus and don't want to fuzz at all. |
| 42 | |
| 43 | For more options, please refer to tools/code_coverage/coverage.py -h. |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 44 | """ |
| 45 | |
| 46 | from __future__ import print_function |
| 47 | |
| 48 | import sys |
| 49 | |
| 50 | import argparse |
| 51 | import os |
| 52 | import subprocess |
| 53 | import threading |
| 54 | import urllib2 |
| 55 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 56 | sys.path.append( |
| 57 | os.path.join( |
| 58 | os.path.dirname(__file__), os.path.pardir, os.path.pardir, 'tools', |
| 59 | 'clang', 'scripts')) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 60 | |
| 61 | import update as clang_update |
| 62 | |
| 63 | # Absolute path to the root of the checkout. |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 64 | SRC_ROOT_PATH = os.path.abspath( |
| 65 | os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir)) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 66 | |
| 67 | # Absolute path to the code coverage tools binary. |
| 68 | LLVM_BUILD_DIR = clang_update.LLVM_BUILD_DIR |
| 69 | LLVM_COV_PATH = os.path.join(LLVM_BUILD_DIR, 'bin', 'llvm-cov') |
| 70 | LLVM_PROFDATA_PATH = os.path.join(LLVM_BUILD_DIR, 'bin', 'llvm-profdata') |
| 71 | |
| 72 | # Build directory, the value is parsed from command line arguments. |
| 73 | BUILD_DIR = None |
| 74 | |
| 75 | # Output directory for generated artifacts, the value is parsed from command |
| 76 | # line arguemnts. |
| 77 | OUTPUT_DIR = None |
| 78 | |
| 79 | # Default number of jobs used to build when goma is configured and enabled. |
| 80 | DEFAULT_GOMA_JOBS = 100 |
| 81 | |
| 82 | # Name of the file extension for profraw data files. |
| 83 | PROFRAW_FILE_EXTENSION = 'profraw' |
| 84 | |
| 85 | # Name of the final profdata file, and this file needs to be passed to |
| 86 | # "llvm-cov" command in order to call "llvm-cov show" to inspect the |
| 87 | # line-by-line coverage of specific files. |
| 88 | PROFDATA_FILE_NAME = 'coverage.profdata' |
| 89 | |
| 90 | # Build arg required for generating code coverage data. |
| 91 | CLANG_COVERAGE_BUILD_ARG = 'use_clang_coverage' |
| 92 | |
| 93 | # A set of targets that depend on target "testing/gtest", this set is generated |
| 94 | # by 'gn refs "testing/gtest"', and it is lazily initialized when needed. |
| 95 | GTEST_TARGET_NAMES = None |
| 96 | |
| 97 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 98 | def _GetPlatform(): |
| 99 | """Returns current running platform.""" |
| 100 | if sys.platform == 'win32' or sys.platform == 'cygwin': |
| 101 | return 'win' |
| 102 | if sys.platform.startswith('linux'): |
| 103 | return 'linux' |
| 104 | else: |
| 105 | assert sys.platform == 'darwin' |
| 106 | return 'mac' |
| 107 | |
| 108 | |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 109 | # TODO(crbug.com/759794): remove this function once tools get included to |
| 110 | # Clang bundle: |
| 111 | # https://chromium-review.googlesource.com/c/chromium/src/+/688221 |
| 112 | def DownloadCoverageToolsIfNeeded(): |
| 113 | """Temporary solution to download llvm-profdata and llvm-cov tools.""" |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 114 | |
| 115 | def _GetRevisionFromStampFile(stamp_file_path, platform): |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 116 | """Returns a pair of revision number by reading the build stamp file. |
| 117 | |
| 118 | Args: |
| 119 | stamp_file_path: A path the build stamp file created by |
| 120 | tools/clang/scripts/update.py. |
| 121 | Returns: |
| 122 | A pair of integers represeting the main and sub revision respectively. |
| 123 | """ |
| 124 | if not os.path.exists(stamp_file_path): |
| 125 | return 0, 0 |
| 126 | |
| 127 | with open(stamp_file_path) as stamp_file: |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 128 | for stamp_file_line in stamp_file.readlines(): |
| 129 | if ',' in stamp_file_line: |
| 130 | package_version, target_os = stamp_file_line.rstrip().split(',') |
| 131 | else: |
| 132 | package_version = stamp_file_line.rstrip() |
| 133 | target_os = '' |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 134 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 135 | if target_os and platform != target_os: |
| 136 | continue |
| 137 | |
| 138 | clang_revision_str, clang_sub_revision_str = package_version.split('-') |
| 139 | return int(clang_revision_str), int(clang_sub_revision_str) |
| 140 | |
| 141 | assert False, 'Coverage is only supported on target_os - linux, mac.' |
| 142 | |
| 143 | platform = _GetPlatform() |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 144 | clang_revision, clang_sub_revision = _GetRevisionFromStampFile( |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 145 | clang_update.STAMP_FILE, platform) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 146 | |
| 147 | coverage_revision_stamp_file = os.path.join( |
| 148 | os.path.dirname(clang_update.STAMP_FILE), 'cr_coverage_revision') |
| 149 | coverage_revision, coverage_sub_revision = _GetRevisionFromStampFile( |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 150 | coverage_revision_stamp_file, platform) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 151 | |
| 152 | if (coverage_revision == clang_revision and |
| 153 | coverage_sub_revision == clang_sub_revision): |
| 154 | # LLVM coverage tools are up to date, bail out. |
| 155 | return clang_revision |
| 156 | |
| 157 | package_version = '%d-%d' % (clang_revision, clang_sub_revision) |
| 158 | coverage_tools_file = 'llvm-code-coverage-%s.tgz' % package_version |
| 159 | |
| 160 | # The code bellow follows the code from tools/clang/scripts/update.py. |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 161 | if platform == 'mac': |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 162 | coverage_tools_url = clang_update.CDS_URL + '/Mac/' + coverage_tools_file |
| 163 | else: |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 164 | assert platform == 'linux' |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 165 | coverage_tools_url = ( |
| 166 | clang_update.CDS_URL + '/Linux_x64/' + coverage_tools_file) |
| 167 | |
| 168 | try: |
| 169 | clang_update.DownloadAndUnpack(coverage_tools_url, |
| 170 | clang_update.LLVM_BUILD_DIR) |
| 171 | print('Coverage tools %s unpacked' % package_version) |
| 172 | with open(coverage_revision_stamp_file, 'w') as file_handle: |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 173 | file_handle.write('%s,%s' % (package_version, platform)) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 174 | file_handle.write('\n') |
| 175 | except urllib2.URLError: |
| 176 | raise Exception( |
| 177 | 'Failed to download coverage tools: %s.' % coverage_tools_url) |
| 178 | |
| 179 | |
| 180 | def _GenerateLineByLineFileCoverageInHtml(binary_paths, profdata_file_path): |
| 181 | """Generates per file line-by-line coverage in html using 'llvm-cov show'. |
| 182 | |
| 183 | For a file with absolute path /a/b/x.cc, a html report is generated as: |
| 184 | OUTPUT_DIR/coverage/a/b/x.cc.html. An index html file is also generated as: |
| 185 | OUTPUT_DIR/index.html. |
| 186 | |
| 187 | Args: |
| 188 | binary_paths: A list of paths to the instrumented binaries. |
| 189 | profdata_file_path: A path to the profdata file. |
| 190 | """ |
| 191 | print('Generating per file line by line code coverage in html') |
| 192 | |
| 193 | # llvm-cov show [options] -instr-profile PROFILE BIN [-object BIN,...] |
| 194 | # [[-object BIN]] [SOURCES] |
| 195 | # NOTE: For object files, the first one is specified as a positional argument, |
| 196 | # and the rest are specified as keyword argument. |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 197 | subprocess_cmd = [ |
| 198 | LLVM_COV_PATH, 'show', '-format=html', |
| 199 | '-output-dir={}'.format(OUTPUT_DIR), |
| 200 | '-instr-profile={}'.format(profdata_file_path), binary_paths[0] |
| 201 | ] |
| 202 | subprocess_cmd.extend( |
| 203 | ['-object=' + binary_path for binary_path in binary_paths[1:]]) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 204 | |
| 205 | subprocess.check_call(subprocess_cmd) |
| 206 | |
| 207 | |
| 208 | def _CreateCoverageProfileDataForTargets(targets, commands, jobs_count=None): |
| 209 | """Builds and runs target to generate the coverage profile data. |
| 210 | |
| 211 | Args: |
| 212 | targets: A list of targets to build with coverage instrumentation. |
| 213 | commands: A list of commands used to run the targets. |
| 214 | jobs_count: Number of jobs to run in parallel for building. If None, a |
| 215 | default value is derived based on CPUs availability. |
| 216 | |
| 217 | Returns: |
| 218 | A relative path to the generated profdata file. |
| 219 | """ |
| 220 | _BuildTargets(targets, jobs_count) |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 221 | profraw_file_paths = _GetProfileRawDataPathsByExecutingCommands( |
| 222 | targets, commands) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 223 | profdata_file_path = _CreateCoverageProfileDataFromProfRawData( |
| 224 | profraw_file_paths) |
| 225 | |
| 226 | return profdata_file_path |
| 227 | |
| 228 | |
| 229 | def _BuildTargets(targets, jobs_count): |
| 230 | """Builds target with Clang coverage instrumentation. |
| 231 | |
| 232 | This function requires current working directory to be the root of checkout. |
| 233 | |
| 234 | Args: |
| 235 | targets: A list of targets to build with coverage instrumentation. |
| 236 | jobs_count: Number of jobs to run in parallel for compilation. If None, a |
| 237 | default value is derived based on CPUs availability. |
| 238 | |
| 239 | |
| 240 | """ |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 241 | |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 242 | def _IsGomaConfigured(): |
| 243 | """Returns True if goma is enabled in the gn build args. |
| 244 | |
| 245 | Returns: |
| 246 | A boolean indicates whether goma is configured for building or not. |
| 247 | """ |
| 248 | build_args = _ParseArgsGnFile() |
| 249 | return 'use_goma' in build_args and build_args['use_goma'] == 'true' |
| 250 | |
| 251 | print('Building %s' % str(targets)) |
| 252 | |
| 253 | if jobs_count is None and _IsGomaConfigured(): |
| 254 | jobs_count = DEFAULT_GOMA_JOBS |
| 255 | |
| 256 | subprocess_cmd = ['ninja', '-C', BUILD_DIR] |
| 257 | if jobs_count is not None: |
| 258 | subprocess_cmd.append('-j' + str(jobs_count)) |
| 259 | |
| 260 | subprocess_cmd.extend(targets) |
| 261 | subprocess.check_call(subprocess_cmd) |
| 262 | |
| 263 | |
| 264 | def _GetProfileRawDataPathsByExecutingCommands(targets, commands): |
| 265 | """Runs commands and returns the relative paths to the profraw data files. |
| 266 | |
| 267 | Args: |
| 268 | targets: A list of targets built with coverage instrumentation. |
| 269 | commands: A list of commands used to run the targets. |
| 270 | |
| 271 | Returns: |
| 272 | A list of relative paths to the generated profraw data files. |
| 273 | """ |
| 274 | # Remove existing profraw data files. |
| 275 | for file_or_dir in os.listdir(OUTPUT_DIR): |
| 276 | if file_or_dir.endswith(PROFRAW_FILE_EXTENSION): |
| 277 | os.remove(os.path.join(OUTPUT_DIR, file_or_dir)) |
| 278 | |
| 279 | # Run different test targets in parallel to generate profraw data files. |
| 280 | threads = [] |
| 281 | for target, command in zip(targets, commands): |
| 282 | thread = threading.Thread(target=_ExecuteCommand, args=(target, command)) |
| 283 | thread.start() |
| 284 | threads.append(thread) |
| 285 | for thread in threads: |
| 286 | thread.join() |
| 287 | |
| 288 | profraw_file_paths = [] |
| 289 | for file_or_dir in os.listdir(OUTPUT_DIR): |
| 290 | if file_or_dir.endswith(PROFRAW_FILE_EXTENSION): |
| 291 | profraw_file_paths.append(os.path.join(OUTPUT_DIR, file_or_dir)) |
| 292 | |
| 293 | # Assert one target/command generates at least one profraw data file. |
| 294 | for target in targets: |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 295 | assert any( |
| 296 | os.path.basename(profraw_file).startswith(target) |
| 297 | for profraw_file in profraw_file_paths), ( |
| 298 | 'Running target: %s failed to generate any profraw data file, ' |
| 299 | 'please make sure the binary exists and is properly instrumented.' % |
| 300 | target) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 301 | |
| 302 | return profraw_file_paths |
| 303 | |
| 304 | |
| 305 | def _ExecuteCommand(target, command): |
| 306 | """Runs a single command and generates a profraw data file. |
| 307 | |
| 308 | Args: |
| 309 | target: A target built with coverage instrumentation. |
| 310 | command: A command used to run the target. |
| 311 | """ |
| 312 | if _IsTargetGTestTarget(target): |
| 313 | # This test argument is required and only required for gtest unit test |
| 314 | # targets because by default, they run tests in parallel, and that won't |
| 315 | # generated code coverage data correctly. |
| 316 | command += ' --test-launcher-jobs=1' |
| 317 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 318 | expected_profraw_file_name = os.extsep.join( |
| 319 | [target, '%p', PROFRAW_FILE_EXTENSION]) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 320 | expected_profraw_file_path = os.path.join(OUTPUT_DIR, |
| 321 | expected_profraw_file_name) |
| 322 | output_file_name = os.extsep.join([target + '_output', 'txt']) |
| 323 | output_file_path = os.path.join(OUTPUT_DIR, output_file_name) |
| 324 | |
| 325 | print('Running command: "%s", the output is redirected to "%s"' % |
| 326 | (command, output_file_path)) |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 327 | output = subprocess.check_output( |
| 328 | command.split(), env={ |
| 329 | 'LLVM_PROFILE_FILE': expected_profraw_file_path |
| 330 | }) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 331 | with open(output_file_path, 'w') as output_file: |
| 332 | output_file.write(output) |
| 333 | |
| 334 | |
| 335 | def _CreateCoverageProfileDataFromProfRawData(profraw_file_paths): |
| 336 | """Returns a relative path to the profdata file by merging profraw data files. |
| 337 | |
| 338 | Args: |
| 339 | profraw_file_paths: A list of relative paths to the profraw data files that |
| 340 | are to be merged. |
| 341 | |
| 342 | Returns: |
| 343 | A relative path to the generated profdata file. |
| 344 | |
| 345 | Raises: |
| 346 | CalledProcessError: An error occurred merging profraw data files. |
| 347 | """ |
| 348 | print('Creating the profile data file') |
| 349 | |
| 350 | profdata_file_path = os.path.join(OUTPUT_DIR, PROFDATA_FILE_NAME) |
| 351 | try: |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 352 | subprocess_cmd = [ |
| 353 | LLVM_PROFDATA_PATH, 'merge', '-o', profdata_file_path, '-sparse=true' |
| 354 | ] |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 355 | subprocess_cmd.extend(profraw_file_paths) |
| 356 | subprocess.check_call(subprocess_cmd) |
| 357 | except subprocess.CalledProcessError as error: |
| 358 | print('Failed to merge profraw files to create profdata file') |
| 359 | raise error |
| 360 | |
| 361 | return profdata_file_path |
| 362 | |
| 363 | |
| 364 | def _GetBinaryPath(command): |
| 365 | """Returns a relative path to the binary to be run by the command. |
| 366 | |
| 367 | Args: |
| 368 | command: A command used to run a target. |
| 369 | |
| 370 | Returns: |
| 371 | A relative path to the binary. |
| 372 | """ |
| 373 | return command.split()[0] |
| 374 | |
| 375 | |
| 376 | def _IsTargetGTestTarget(target): |
| 377 | """Returns True if the target is a gtest target. |
| 378 | |
| 379 | Args: |
| 380 | target: A target built with coverage instrumentation. |
| 381 | |
| 382 | Returns: |
| 383 | A boolean value indicates whether the target is a gtest target. |
| 384 | """ |
| 385 | global GTEST_TARGET_NAMES |
| 386 | if GTEST_TARGET_NAMES is None: |
| 387 | output = subprocess.check_output(['gn', 'refs', BUILD_DIR, 'testing/gtest']) |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 388 | list_of_gtest_targets = [ |
| 389 | gtest_target for gtest_target in output.splitlines() if gtest_target |
| 390 | ] |
| 391 | GTEST_TARGET_NAMES = set( |
| 392 | [gtest_target.split(':')[1] for gtest_target in list_of_gtest_targets]) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 393 | |
| 394 | return target in GTEST_TARGET_NAMES |
| 395 | |
| 396 | |
| 397 | def _ValidateCommandsAreRelativeToSrcRoot(commands): |
| 398 | for command in commands: |
| 399 | binary_path = _GetBinaryPath(command) |
| 400 | assert binary_path.startswith(BUILD_DIR), ('Target executable "%s" is ' |
| 401 | 'outside of the given build ' |
| 402 | 'directory: "%s". Please make ' |
| 403 | 'sure the command: "%s" is ' |
| 404 | 'relative to the root of the ' |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 405 | 'checkout.' % |
| 406 | (binary_path, BUILD_DIR, |
| 407 | command)) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 408 | |
| 409 | |
| 410 | def _ValidateBuildingWithClangCoverage(): |
| 411 | """Asserts that targets are built with Clang coverage enabled.""" |
| 412 | build_args = _ParseArgsGnFile() |
| 413 | |
| 414 | if (CLANG_COVERAGE_BUILD_ARG not in build_args or |
| 415 | build_args[CLANG_COVERAGE_BUILD_ARG] != 'true'): |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 416 | assert False, ('\'{} = true\' is required in args.gn.' |
| 417 | ).format(CLANG_COVERAGE_BUILD_ARG) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 418 | |
| 419 | |
| 420 | def _ParseArgsGnFile(): |
| 421 | """Parses args.gn file and returns results as a dictionary. |
| 422 | |
| 423 | Returns: |
| 424 | A dictionary representing the build args. |
| 425 | """ |
| 426 | build_args_path = os.path.join(BUILD_DIR, 'args.gn') |
| 427 | assert os.path.exists(build_args_path), ('"%s" is not a build directory, ' |
| 428 | 'missing args.gn file.' % BUILD_DIR) |
| 429 | with open(build_args_path) as build_args_file: |
| 430 | build_args_lines = build_args_file.readlines() |
| 431 | |
| 432 | build_args = {} |
| 433 | for build_arg_line in build_args_lines: |
| 434 | build_arg_without_comments = build_arg_line.split('#')[0] |
| 435 | key_value_pair = build_arg_without_comments.split('=') |
| 436 | if len(key_value_pair) != 2: |
| 437 | continue |
| 438 | |
| 439 | key = key_value_pair[0].strip() |
| 440 | value = key_value_pair[1].strip() |
| 441 | build_args[key] = value |
| 442 | |
| 443 | return build_args |
| 444 | |
| 445 | |
| 446 | def _ParseCommandArguments(): |
| 447 | """Adds and parses relevant arguments for tool comands. |
| 448 | |
| 449 | Returns: |
| 450 | A dictionary representing the arguments. |
| 451 | """ |
| 452 | arg_parser = argparse.ArgumentParser() |
| 453 | arg_parser.usage = __doc__ |
| 454 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 455 | arg_parser.add_argument( |
| 456 | '-b', |
| 457 | '--build-dir', |
| 458 | type=str, |
| 459 | required=True, |
| 460 | help='The build directory, the path needs to be relative to the root of ' |
| 461 | 'the checkout.') |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 462 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 463 | arg_parser.add_argument( |
| 464 | '-o', |
| 465 | '--output-dir', |
| 466 | type=str, |
| 467 | required=True, |
| 468 | help='Output directory for generated artifacts.') |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 469 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 470 | arg_parser.add_argument( |
| 471 | '-c', |
| 472 | '--command', |
| 473 | action='append', |
| 474 | required=True, |
| 475 | help='Commands used to run test targets, one test target needs one and ' |
| 476 | 'only one command, when specifying commands, one should assume the ' |
| 477 | 'current working directory is the root of the checkout.') |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 478 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 479 | arg_parser.add_argument( |
| 480 | '-j', |
| 481 | '--jobs', |
| 482 | type=int, |
| 483 | default=None, |
| 484 | help='Run N jobs to build in parallel. If not specified, a default value ' |
| 485 | 'will be derived based on CPUs availability. Please refer to ' |
| 486 | '\'ninja -h\' for more details.') |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 487 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 488 | arg_parser.add_argument( |
| 489 | 'targets', nargs='+', help='The names of the test targets to run.') |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 490 | |
| 491 | args = arg_parser.parse_args() |
| 492 | return args |
| 493 | |
| 494 | |
| 495 | def Main(): |
| 496 | """Execute tool commands.""" |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 497 | assert _GetPlatform() in ['linux', 'mac'], ( |
| 498 | 'Coverage is only supported on linux and mac platforms.') |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 499 | assert os.path.abspath(os.getcwd()) == SRC_ROOT_PATH, ('This script must be ' |
| 500 | 'called from the root ' |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 501 | 'of checkout.') |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 502 | DownloadCoverageToolsIfNeeded() |
| 503 | |
| 504 | args = _ParseCommandArguments() |
| 505 | global BUILD_DIR |
| 506 | BUILD_DIR = args.build_dir |
| 507 | global OUTPUT_DIR |
| 508 | OUTPUT_DIR = args.output_dir |
| 509 | |
| 510 | assert len(args.targets) == len(args.command), ('Number of targets must be ' |
| 511 | 'equal to the number of test ' |
| 512 | 'commands.') |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 513 | assert os.path.exists(BUILD_DIR), ( |
| 514 | 'Build directory: {} doesn\'t exist. ' |
| 515 | 'Please run "gn gen" to generate.').format(BUILD_DIR) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 516 | _ValidateBuildingWithClangCoverage() |
| 517 | _ValidateCommandsAreRelativeToSrcRoot(args.command) |
| 518 | if not os.path.exists(OUTPUT_DIR): |
| 519 | os.makedirs(OUTPUT_DIR) |
| 520 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 521 | profdata_file_path = _CreateCoverageProfileDataForTargets( |
| 522 | args.targets, args.command, args.jobs) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 523 | |
| 524 | binary_paths = [_GetBinaryPath(command) for command in args.command] |
| 525 | _GenerateLineByLineFileCoverageInHtml(binary_paths, profdata_file_path) |
| 526 | html_index_file_path = 'file://' + os.path.abspath( |
| 527 | os.path.join(OUTPUT_DIR, 'index.html')) |
| 528 | print('\nCode coverage profile data is created as: %s' % profdata_file_path) |
| 529 | print('index file for html report is generated as: %s' % html_index_file_path) |
| 530 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame^] | 531 | |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 532 | if __name__ == '__main__': |
| 533 | sys.exit(Main()) |