blob: 3b97955d72d33c19c5c7ad6380ba55b57bc5a3bc [file] [log] [blame]
Yuke Liao506e8822017-12-04 16:52:541#!/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 Arya1ec832c2017-12-05 18:06:595"""This script helps to generate code coverage report.
Yuke Liao506e8822017-12-04 16:52:546
Abhishek Arya1ec832c2017-12-05 18:06:597 It uses Clang Source-based Code Coverage -
8 https://clang.llvm.org/docs/SourceBasedCodeCoverage.html
Yuke Liao506e8822017-12-04 16:52:549
Abhishek Arya16f059a2017-12-07 17:47:3210 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 Liao506e8822017-12-04 16:52:5413
Abhishek Arya16f059a2017-12-07 17:47:3214 It is recommended to add "is_component_build=false" flag as well because:
Abhishek Arya1ec832c2017-12-05 18:06:5915 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 Liao506e8822017-12-04 16:52:5418
Abhishek Arya1ec832c2017-12-05 18:06:5919 Example usage:
20
Abhishek Arya16f059a2017-12-07 17:47:3221 gn gen out/coverage --args='use_clang_coverage=true is_component_build=false'
22 gclient runhooks
Abhishek Arya1ec832c2017-12-05 18:06:5923 python tools/code_coverage/coverage.py crypto_unittests url_unittests \\
Abhishek Arya16f059a2017-12-07 17:47:3224 -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 Arya1ec832c2017-12-05 18:06:5927
Abhishek Arya16f059a2017-12-07 17:47:3228 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 Arya1ec832c2017-12-05 18:06:5932
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 Arya16f059a2017-12-07 17:47:3238 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 Arya1ec832c2017-12-05 18:06:5942
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 Liao506e8822017-12-04 16:52:5449"""
50
51from __future__ import print_function
52
53import sys
54
55import argparse
56import os
57import subprocess
58import threading
59import urllib2
60
Abhishek Arya1ec832c2017-12-05 18:06:5961sys.path.append(
62 os.path.join(
63 os.path.dirname(__file__), os.path.pardir, os.path.pardir, 'tools',
64 'clang', 'scripts'))
Yuke Liao506e8822017-12-04 16:52:5465
66import update as clang_update
67
68# Absolute path to the root of the checkout.
Abhishek Arya1ec832c2017-12-05 18:06:5969SRC_ROOT_PATH = os.path.abspath(
70 os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir))
Yuke Liao506e8822017-12-04 16:52:5471
72# Absolute path to the code coverage tools binary.
73LLVM_BUILD_DIR = clang_update.LLVM_BUILD_DIR
74LLVM_COV_PATH = os.path.join(LLVM_BUILD_DIR, 'bin', 'llvm-cov')
75LLVM_PROFDATA_PATH = os.path.join(LLVM_BUILD_DIR, 'bin', 'llvm-profdata')
76
77# Build directory, the value is parsed from command line arguments.
78BUILD_DIR = None
79
80# Output directory for generated artifacts, the value is parsed from command
81# line arguemnts.
82OUTPUT_DIR = None
83
84# Default number of jobs used to build when goma is configured and enabled.
85DEFAULT_GOMA_JOBS = 100
86
87# Name of the file extension for profraw data files.
88PROFRAW_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.
93PROFDATA_FILE_NAME = 'coverage.profdata'
94
95# Build arg required for generating code coverage data.
96CLANG_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.
100GTEST_TARGET_NAMES = None
101
102
Abhishek Arya1ec832c2017-12-05 18:06:59103def _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 Liao506e8822017-12-04 16:52:54114# 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
117def DownloadCoverageToolsIfNeeded():
118 """Temporary solution to download llvm-profdata and llvm-cov tools."""
Abhishek Arya1ec832c2017-12-05 18:06:59119
120 def _GetRevisionFromStampFile(stamp_file_path, platform):
Yuke Liao506e8822017-12-04 16:52:54121 """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 Arya1ec832c2017-12-05 18:06:59133 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 Liao506e8822017-12-04 16:52:54139
Abhishek Arya1ec832c2017-12-05 18:06:59140 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 Liao506e8822017-12-04 16:52:54149 clang_revision, clang_sub_revision = _GetRevisionFromStampFile(
Abhishek Arya1ec832c2017-12-05 18:06:59150 clang_update.STAMP_FILE, platform)
Yuke Liao506e8822017-12-04 16:52:54151
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 Arya1ec832c2017-12-05 18:06:59155 coverage_revision_stamp_file, platform)
Yuke Liao506e8822017-12-04 16:52:54156
Abhishek Arya16f059a2017-12-07 17:47:32157 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 Liao506e8822017-12-04 16:52:54162 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 Arya1ec832c2017-12-05 18:06:59170 if platform == 'mac':
Yuke Liao506e8822017-12-04 16:52:54171 coverage_tools_url = clang_update.CDS_URL + '/Mac/' + coverage_tools_file
172 else:
Abhishek Arya1ec832c2017-12-05 18:06:59173 assert platform == 'linux'
Yuke Liao506e8822017-12-04 16:52:54174 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 Arya1ec832c2017-12-05 18:06:59182 file_handle.write('%s,%s' % (package_version, platform))
Yuke Liao506e8822017-12-04 16:52:54183 file_handle.write('\n')
184 except urllib2.URLError:
185 raise Exception(
186 'Failed to download coverage tools: %s.' % coverage_tools_url)
187
188
Yuke Liao66da1732017-12-05 22:19:42189def _GenerateLineByLineFileCoverageInHtml(binary_paths, profdata_file_path,
190 filters):
Yuke Liao506e8822017-12-04 16:52:54191 """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 Liao66da1732017-12-05 22:19:42200 filters: A list of directories and files to get coverage for.
Yuke Liao506e8822017-12-04 16:52:54201 """
Abhishek Arya16f059a2017-12-07 17:47:32202 print('Generating per file line-by-line code coverage in html '
203 '(this can take a while depending on size of target!)')
Yuke Liao506e8822017-12-04 16:52:54204
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 Arya1ec832c2017-12-05 18:06:59209 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 Liao66da1732017-12-05 22:19:42216 subprocess_cmd.extend(filters)
Yuke Liao506e8822017-12-04 16:52:54217
218 subprocess.check_call(subprocess_cmd)
219
220
221def _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 Arya1ec832c2017-12-05 18:06:59234 profraw_file_paths = _GetProfileRawDataPathsByExecutingCommands(
235 targets, commands)
Yuke Liao506e8822017-12-04 16:52:54236 profdata_file_path = _CreateCoverageProfileDataFromProfRawData(
237 profraw_file_paths)
238
239 return profdata_file_path
240
241
242def _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 Arya1ec832c2017-12-05 18:06:59254
Yuke Liao506e8822017-12-04 16:52:54255 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
277def _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 Arya1ec832c2017-12-05 18:06:59308 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 Liao506e8822017-12-04 16:52:54314
315 return profraw_file_paths
316
317
318def _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 Arya1ec832c2017-12-05 18:06:59331 expected_profraw_file_name = os.extsep.join(
332 [target, '%p', PROFRAW_FILE_EXTENSION])
Yuke Liao506e8822017-12-04 16:52:54333 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 Arya1ec832c2017-12-05 18:06:59340 output = subprocess.check_output(
341 command.split(), env={
342 'LLVM_PROFILE_FILE': expected_profraw_file_path
343 })
Yuke Liao506e8822017-12-04 16:52:54344 with open(output_file_path, 'w') as output_file:
345 output_file.write(output)
346
347
348def _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 Arya16f059a2017-12-07 17:47:32364
Yuke Liao506e8822017-12-04 16:52:54365 try:
Abhishek Arya1ec832c2017-12-05 18:06:59366 subprocess_cmd = [
367 LLVM_PROFDATA_PATH, 'merge', '-o', profdata_file_path, '-sparse=true'
368 ]
Yuke Liao506e8822017-12-04 16:52:54369 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
378def _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
390def _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 Arya1ec832c2017-12-05 18:06:59402 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 Liao506e8822017-12-04 16:52:54407
408 return target in GTEST_TARGET_NAMES
409
410
Yuke Liao95d13d72017-12-07 18:18:50411def _VerifyTargetExecutablesAreInBuildDirectory(commands):
412 """Verifies that the target executables specified in the commands are inside
413 the given build directory."""
Yuke Liao506e8822017-12-04 16:52:54414 for command in commands:
415 binary_path = _GetBinaryPath(command)
Yuke Liao95d13d72017-12-07 18:18:50416 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 Liao506e8822017-12-04 16:52:54420
421
422def _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 Arya1ec832c2017-12-05 18:06:59428 assert False, ('\'{} = true\' is required in args.gn.'
429 ).format(CLANG_COVERAGE_BUILD_ARG)
Yuke Liao506e8822017-12-04 16:52:54430
431
432def _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 Arya16f059a2017-12-07 17:47:32458def _VerifyPathsAndReturnAbsolutes(paths):
459 """Verifies that the paths specified in |paths| exist and returns absolute
460 versions.
Yuke Liao66da1732017-12-05 22:19:42461
462 Args:
463 paths: A list of files or directories.
464 """
Abhishek Arya16f059a2017-12-07 17:47:32465 absolute_paths = []
Yuke Liao66da1732017-12-05 22:19:42466 for path in paths:
Abhishek Arya16f059a2017-12-07 17:47:32467 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 Liao66da1732017-12-05 22:19:42473
474
Yuke Liao506e8822017-12-04 16:52:54475def _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 Arya1ec832c2017-12-05 18:06:59484 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 Liao506e8822017-12-04 16:52:54491
Abhishek Arya1ec832c2017-12-05 18:06:59492 arg_parser.add_argument(
493 '-o',
494 '--output-dir',
495 type=str,
496 required=True,
497 help='Output directory for generated artifacts.')
Yuke Liao506e8822017-12-04 16:52:54498
Abhishek Arya1ec832c2017-12-05 18:06:59499 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 Liao506e8822017-12-04 16:52:54507
Abhishek Arya1ec832c2017-12-05 18:06:59508 arg_parser.add_argument(
Yuke Liao66da1732017-12-05 22:19:42509 '-f',
510 '--filters',
511 action='append',
Abhishek Arya16f059a2017-12-07 17:47:32512 required=False,
Yuke Liao66da1732017-12-05 22:19:42513 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 Arya1ec832c2017-12-05 18:06:59517 '-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 Liao506e8822017-12-04 16:52:54524
Abhishek Arya1ec832c2017-12-05 18:06:59525 arg_parser.add_argument(
526 'targets', nargs='+', help='The names of the test targets to run.')
Yuke Liao506e8822017-12-04 16:52:54527
528 args = arg_parser.parse_args()
529 return args
530
531
532def Main():
533 """Execute tool commands."""
Abhishek Arya1ec832c2017-12-05 18:06:59534 assert _GetPlatform() in ['linux', 'mac'], (
535 'Coverage is only supported on linux and mac platforms.')
Yuke Liao506e8822017-12-04 16:52:54536 assert os.path.abspath(os.getcwd()) == SRC_ROOT_PATH, ('This script must be '
537 'called from the root '
Abhishek Arya1ec832c2017-12-05 18:06:59538 'of checkout.')
Yuke Liao506e8822017-12-04 16:52:54539 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 Arya1ec832c2017-12-05 18:06:59550 assert os.path.exists(BUILD_DIR), (
551 'Build directory: {} doesn\'t exist. '
552 'Please run "gn gen" to generate.').format(BUILD_DIR)
Yuke Liao506e8822017-12-04 16:52:54553 _ValidateBuildingWithClangCoverage()
Yuke Liao95d13d72017-12-07 18:18:50554 _VerifyTargetExecutablesAreInBuildDirectory(args.command)
Abhishek Arya16f059a2017-12-07 17:47:32555
556 absolute_filter_paths = []
Yuke Liao66da1732017-12-05 22:19:42557 if args.filters:
Abhishek Arya16f059a2017-12-07 17:47:32558 absolute_filter_paths = _VerifyPathsAndReturnAbsolutes(args.filters)
Yuke Liao66da1732017-12-05 22:19:42559
Yuke Liao506e8822017-12-04 16:52:54560 if not os.path.exists(OUTPUT_DIR):
561 os.makedirs(OUTPUT_DIR)
562
Abhishek Arya1ec832c2017-12-05 18:06:59563 profdata_file_path = _CreateCoverageProfileDataForTargets(
564 args.targets, args.command, args.jobs)
Yuke Liao506e8822017-12-04 16:52:54565
566 binary_paths = [_GetBinaryPath(command) for command in args.command]
Yuke Liao66da1732017-12-05 22:19:42567 _GenerateLineByLineFileCoverageInHtml(binary_paths, profdata_file_path,
Abhishek Arya16f059a2017-12-07 17:47:32568 absolute_filter_paths)
Yuke Liao506e8822017-12-04 16:52:54569 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 Arya16f059a2017-12-07 17:47:32572 print('Index file for html report is generated as: %s' % html_index_file_path)
Yuke Liao506e8822017-12-04 16:52:54573
Abhishek Arya1ec832c2017-12-05 18:06:59574
Yuke Liao506e8822017-12-04 16:52:54575if __name__ == '__main__':
576 sys.exit(Main())