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