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