blob: c76f5f30163fe63ba58ffaa5ce25da80b7a3ffb8 [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
Yuke Liaoab9c44e2018-02-21 00:24:4011 "use_clang_coverage=true" and "is_component_build=false" GN flags to args.gn
12 file in your build output directory (e.g. out/coverage).
Yuke Liao506e8822017-12-04 16:52:5413
Yuke Liaod3b46272018-03-14 18:25:1414 Existing implementation requires "is_component_build=false" flag because
15 coverage info for dynamic libraries may be missing and "is_component_build"
16 is set to true by "is_debug" unless it is explicitly set to false.
Yuke Liao506e8822017-12-04 16:52:5417
Abhishek Arya1ec832c2017-12-05 18:06:5918 Example usage:
19
Abhishek Arya16f059a2017-12-07 17:47:3220 gn gen out/coverage --args='use_clang_coverage=true is_component_build=false'
21 gclient runhooks
Abhishek Arya1ec832c2017-12-05 18:06:5922 python tools/code_coverage/coverage.py crypto_unittests url_unittests \\
Abhishek Arya16f059a2017-12-07 17:47:3223 -b out/coverage -o out/report -c 'out/coverage/crypto_unittests' \\
24 -c 'out/coverage/url_unittests --gtest_filter=URLParser.PathURL' \\
25 -f url/ -f crypto/
Abhishek Arya1ec832c2017-12-05 18:06:5926
Abhishek Arya16f059a2017-12-07 17:47:3227 The command above builds crypto_unittests and url_unittests targets and then
28 runs them with specified command line arguments. For url_unittests, it only
29 runs the test URLParser.PathURL. The coverage report is filtered to include
30 only files and sub-directories under url/ and crypto/ directories.
Abhishek Arya1ec832c2017-12-05 18:06:5931
Yuke Liao545db322018-02-15 17:12:0132 If you want to run tests that try to draw to the screen but don't have a
33 display connected, you can run tests in headless mode with xvfb.
34
35 Sample flow for running a test target with xvfb (e.g. unit_tests):
36
37 python tools/code_coverage/coverage.py unit_tests -b out/coverage \\
38 -o out/report -c 'python testing/xvfb.py out/coverage/unit_tests'
39
Abhishek Arya1ec832c2017-12-05 18:06:5940 If you are building a fuzz target, you need to add "use_libfuzzer=true" GN
41 flag as well.
42
43 Sample workflow for a fuzz target (e.g. pdfium_fuzzer):
44
Abhishek Arya16f059a2017-12-07 17:47:3245 python tools/code_coverage/coverage.py pdfium_fuzzer \\
46 -b out/coverage -o out/report \\
47 -c 'out/coverage/pdfium_fuzzer -runs=<runs> <corpus_dir>' \\
48 -f third_party/pdfium
Abhishek Arya1ec832c2017-12-05 18:06:5949
50 where:
51 <corpus_dir> - directory containing samples files for this format.
52 <runs> - number of times to fuzz target function. Should be 0 when you just
53 want to see the coverage on corpus and don't want to fuzz at all.
54
55 For more options, please refer to tools/code_coverage/coverage.py -h.
Yuke Liao8e209fe82018-04-18 20:36:3856
57 For an overview of how code coverage works in Chromium, please refer to
58 https://chromium.googlesource.com/chromium/src/+/master/docs/code_coverage.md
Yuke Liao506e8822017-12-04 16:52:5459"""
60
61from __future__ import print_function
62
63import sys
64
65import argparse
Yuke Liaoea228d02018-01-05 19:10:3366import json
Yuke Liao481d3482018-01-29 19:17:1067import logging
Yuke Liao506e8822017-12-04 16:52:5468import os
Yuke Liaob2926832018-03-02 17:34:2969import re
70import shlex
Max Moroz025d8952018-05-03 16:33:3471import shutil
Yuke Liao506e8822017-12-04 16:52:5472import subprocess
Yuke Liao506e8822017-12-04 16:52:5473import urllib2
74
Abhishek Arya1ec832c2017-12-05 18:06:5975sys.path.append(
76 os.path.join(
77 os.path.dirname(__file__), os.path.pardir, os.path.pardir, 'tools',
78 'clang', 'scripts'))
Yuke Liao506e8822017-12-04 16:52:5479import update as clang_update
80
Yuke Liaoea228d02018-01-05 19:10:3381sys.path.append(
82 os.path.join(
83 os.path.dirname(__file__), os.path.pardir, os.path.pardir,
84 'third_party'))
85import jinja2
86from collections import defaultdict
87
Yuke Liao506e8822017-12-04 16:52:5488# Absolute path to the root of the checkout.
Abhishek Arya1ec832c2017-12-05 18:06:5989SRC_ROOT_PATH = os.path.abspath(
90 os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir))
Yuke Liao506e8822017-12-04 16:52:5491
92# Absolute path to the code coverage tools binary.
93LLVM_BUILD_DIR = clang_update.LLVM_BUILD_DIR
94LLVM_COV_PATH = os.path.join(LLVM_BUILD_DIR, 'bin', 'llvm-cov')
95LLVM_PROFDATA_PATH = os.path.join(LLVM_BUILD_DIR, 'bin', 'llvm-profdata')
96
97# Build directory, the value is parsed from command line arguments.
98BUILD_DIR = None
99
100# Output directory for generated artifacts, the value is parsed from command
101# line arguemnts.
102OUTPUT_DIR = None
103
104# Default number of jobs used to build when goma is configured and enabled.
105DEFAULT_GOMA_JOBS = 100
106
107# Name of the file extension for profraw data files.
108PROFRAW_FILE_EXTENSION = 'profraw'
109
110# Name of the final profdata file, and this file needs to be passed to
111# "llvm-cov" command in order to call "llvm-cov show" to inspect the
112# line-by-line coverage of specific files.
Max Moroz7c5354f2018-05-06 00:03:48113PROFDATA_FILE_NAME = os.extsep.join(['coverage', 'profdata'])
114
115# Name of the file with summary information generated by llvm-cov export.
116SUMMARY_FILE_NAME = os.extsep.join(['summary', 'json'])
Yuke Liao506e8822017-12-04 16:52:54117
118# Build arg required for generating code coverage data.
119CLANG_COVERAGE_BUILD_ARG = 'use_clang_coverage'
120
Yuke Liaoea228d02018-01-05 19:10:33121# The default name of the html coverage report for a directory.
122DIRECTORY_COVERAGE_HTML_REPORT_NAME = os.extsep.join(['report', 'html'])
123
Yuke Liaodd1ec0592018-02-02 01:26:37124# Name of the html index files for different views.
Yuke Liaodd1ec0592018-02-02 01:26:37125COMPONENT_VIEW_INDEX_FILE = os.extsep.join(['component_view_index', 'html'])
Max Moroz7c5354f2018-05-06 00:03:48126DIRECTORY_VIEW_INDEX_FILE = os.extsep.join(['directory_view_index', 'html'])
Yuke Liaodd1ec0592018-02-02 01:26:37127FILE_VIEW_INDEX_FILE = os.extsep.join(['file_view_index', 'html'])
Max Moroz7c5354f2018-05-06 00:03:48128INDEX_HTML_FILE = os.extsep.join(['index', 'html'])
129
130LOGS_DIR_NAME = 'logs'
Yuke Liaodd1ec0592018-02-02 01:26:37131
132# Used to extract a mapping between directories and components.
133COMPONENT_MAPPING_URL = 'https://storage.googleapis.com/chromium-owners/component_map.json'
134
Yuke Liao80afff32018-03-07 01:26:20135# Caches the results returned by _GetBuildArgs, don't use this variable
136# directly, call _GetBuildArgs instead.
137_BUILD_ARGS = None
138
Abhishek Aryac19bc5ef2018-05-04 22:10:02139# Retry failed merges.
140MERGE_RETRIES = 3
141
Yuke Liaoea228d02018-01-05 19:10:33142
143class _CoverageSummary(object):
144 """Encapsulates coverage summary representation."""
145
Yuke Liaodd1ec0592018-02-02 01:26:37146 def __init__(self,
147 regions_total=0,
148 regions_covered=0,
149 functions_total=0,
150 functions_covered=0,
151 lines_total=0,
152 lines_covered=0):
Yuke Liaoea228d02018-01-05 19:10:33153 """Initializes _CoverageSummary object."""
154 self._summary = {
155 'regions': {
156 'total': regions_total,
157 'covered': regions_covered
158 },
159 'functions': {
160 'total': functions_total,
161 'covered': functions_covered
162 },
163 'lines': {
164 'total': lines_total,
165 'covered': lines_covered
166 }
167 }
168
169 def Get(self):
170 """Returns summary as a dictionary."""
171 return self._summary
172
173 def AddSummary(self, other_summary):
174 """Adds another summary to this one element-wise."""
175 for feature in self._summary:
176 self._summary[feature]['total'] += other_summary.Get()[feature]['total']
177 self._summary[feature]['covered'] += other_summary.Get()[feature][
178 'covered']
179
180
Yuke Liaodd1ec0592018-02-02 01:26:37181class _CoverageReportHtmlGenerator(object):
182 """Encapsulates coverage html report generation.
Yuke Liaoea228d02018-01-05 19:10:33183
Yuke Liaodd1ec0592018-02-02 01:26:37184 The generated html has a table that contains links to other coverage reports.
Yuke Liaoea228d02018-01-05 19:10:33185 """
186
Yuke Liaodd1ec0592018-02-02 01:26:37187 def __init__(self, output_path, table_entry_type):
188 """Initializes _CoverageReportHtmlGenerator object.
189
190 Args:
191 output_path: Path to the html report that will be generated.
192 table_entry_type: Type of the table entries to be displayed in the table
193 header. For example: 'Path', 'Component'.
194 """
Yuke Liaoea228d02018-01-05 19:10:33195 css_file_name = os.extsep.join(['style', 'css'])
Max Moroz7c5354f2018-05-06 00:03:48196 css_absolute_path = os.path.join(OUTPUT_DIR, css_file_name)
Yuke Liaoea228d02018-01-05 19:10:33197 assert os.path.exists(css_absolute_path), (
198 'css file doesn\'t exit. Please make sure "llvm-cov show -format=html" '
199 'is called first, and the css file is generated at: "%s"' %
200 css_absolute_path)
201
202 self._css_absolute_path = css_absolute_path
Yuke Liaodd1ec0592018-02-02 01:26:37203 self._output_path = output_path
204 self._table_entry_type = table_entry_type
205
Yuke Liaoea228d02018-01-05 19:10:33206 self._table_entries = []
Yuke Liaod54030e2018-01-08 17:34:12207 self._total_entry = {}
Yuke Liaoea228d02018-01-05 19:10:33208 template_dir = os.path.join(
209 os.path.dirname(os.path.realpath(__file__)), 'html_templates')
210
211 jinja_env = jinja2.Environment(
212 loader=jinja2.FileSystemLoader(template_dir), trim_blocks=True)
213 self._header_template = jinja_env.get_template('header.html')
214 self._table_template = jinja_env.get_template('table.html')
215 self._footer_template = jinja_env.get_template('footer.html')
216
217 def AddLinkToAnotherReport(self, html_report_path, name, summary):
218 """Adds a link to another html report in this report.
219
220 The link to be added is assumed to be an entry in this directory.
221 """
Yuke Liaodd1ec0592018-02-02 01:26:37222 # Use relative paths instead of absolute paths to make the generated reports
223 # portable.
224 html_report_relative_path = _GetRelativePathToDirectoryOfFile(
225 html_report_path, self._output_path)
226
Yuke Liaod54030e2018-01-08 17:34:12227 table_entry = self._CreateTableEntryFromCoverageSummary(
Yuke Liaodd1ec0592018-02-02 01:26:37228 summary, html_report_relative_path, name,
Yuke Liaod54030e2018-01-08 17:34:12229 os.path.basename(html_report_path) ==
230 DIRECTORY_COVERAGE_HTML_REPORT_NAME)
231 self._table_entries.append(table_entry)
232
233 def CreateTotalsEntry(self, summary):
Yuke Liaoa785f4d32018-02-13 21:41:35234 """Creates an entry corresponds to the 'Totals' row in the html report."""
Yuke Liaod54030e2018-01-08 17:34:12235 self._total_entry = self._CreateTableEntryFromCoverageSummary(summary)
236
237 def _CreateTableEntryFromCoverageSummary(self,
238 summary,
239 href=None,
240 name=None,
241 is_dir=None):
242 """Creates an entry to display in the html report."""
Yuke Liaodd1ec0592018-02-02 01:26:37243 assert (href is None and name is None and is_dir is None) or (
244 href is not None and name is not None and is_dir is not None), (
245 'The only scenario when href or name or is_dir can be None is when '
Yuke Liaoa785f4d32018-02-13 21:41:35246 'creating an entry for the Totals row, and in that case, all three '
Yuke Liaodd1ec0592018-02-02 01:26:37247 'attributes must be None.')
248
Yuke Liaod54030e2018-01-08 17:34:12249 entry = {}
Yuke Liaodd1ec0592018-02-02 01:26:37250 if href is not None:
251 entry['href'] = href
252 if name is not None:
253 entry['name'] = name
254 if is_dir is not None:
255 entry['is_dir'] = is_dir
256
Yuke Liaoea228d02018-01-05 19:10:33257 summary_dict = summary.Get()
Yuke Liaod54030e2018-01-08 17:34:12258 for feature in summary_dict:
Yuke Liaodd1ec0592018-02-02 01:26:37259 if summary_dict[feature]['total'] == 0:
260 percentage = 0.0
261 else:
Yuke Liao0e4c8682018-04-18 21:06:59262 percentage = float(summary_dict[feature]
263 ['covered']) / summary_dict[feature]['total'] * 100
Yuke Liaoa785f4d32018-02-13 21:41:35264
Yuke Liaoea228d02018-01-05 19:10:33265 color_class = self._GetColorClass(percentage)
Yuke Liaod54030e2018-01-08 17:34:12266 entry[feature] = {
Yuke Liaoea228d02018-01-05 19:10:33267 'total': summary_dict[feature]['total'],
268 'covered': summary_dict[feature]['covered'],
Yuke Liaoa785f4d32018-02-13 21:41:35269 'percentage': '{:6.2f}'.format(percentage),
Yuke Liaoea228d02018-01-05 19:10:33270 'color_class': color_class
271 }
Yuke Liaod54030e2018-01-08 17:34:12272
Yuke Liaod54030e2018-01-08 17:34:12273 return entry
Yuke Liaoea228d02018-01-05 19:10:33274
275 def _GetColorClass(self, percentage):
276 """Returns the css color class based on coverage percentage."""
277 if percentage >= 0 and percentage < 80:
278 return 'red'
279 if percentage >= 80 and percentage < 100:
280 return 'yellow'
281 if percentage == 100:
282 return 'green'
283
284 assert False, 'Invalid coverage percentage: "%d"' % percentage
285
Yuke Liaodd1ec0592018-02-02 01:26:37286 def WriteHtmlCoverageReport(self):
287 """Writes html coverage report.
Yuke Liaoea228d02018-01-05 19:10:33288
289 In the report, sub-directories are displayed before files and within each
290 category, entries are sorted alphabetically.
Yuke Liaoea228d02018-01-05 19:10:33291 """
292
293 def EntryCmp(left, right):
294 """Compare function for table entries."""
295 if left['is_dir'] != right['is_dir']:
296 return -1 if left['is_dir'] == True else 1
297
Yuke Liaodd1ec0592018-02-02 01:26:37298 return -1 if left['name'] < right['name'] else 1
Yuke Liaoea228d02018-01-05 19:10:33299
300 self._table_entries = sorted(self._table_entries, cmp=EntryCmp)
301
302 css_path = os.path.join(OUTPUT_DIR, os.extsep.join(['style', 'css']))
Max Moroz7c5354f2018-05-06 00:03:48303
304 directory_view_path = _GetDirectoryViewPath()
305 component_view_path = _GetComponentViewPath()
306 file_view_path = _GetFileViewPath()
Yuke Liaodd1ec0592018-02-02 01:26:37307
Yuke Liaoea228d02018-01-05 19:10:33308 html_header = self._header_template.render(
Yuke Liaodd1ec0592018-02-02 01:26:37309 css_path=_GetRelativePathToDirectoryOfFile(css_path, self._output_path),
310 directory_view_href=_GetRelativePathToDirectoryOfFile(
311 directory_view_path, self._output_path),
312 component_view_href=_GetRelativePathToDirectoryOfFile(
313 component_view_path, self._output_path),
314 file_view_href=_GetRelativePathToDirectoryOfFile(
315 file_view_path, self._output_path))
316
Yuke Liaod54030e2018-01-08 17:34:12317 html_table = self._table_template.render(
Yuke Liaodd1ec0592018-02-02 01:26:37318 entries=self._table_entries,
319 total_entry=self._total_entry,
320 table_entry_type=self._table_entry_type)
Yuke Liaoea228d02018-01-05 19:10:33321 html_footer = self._footer_template.render()
322
Yuke Liaodd1ec0592018-02-02 01:26:37323 with open(self._output_path, 'w') as html_file:
Yuke Liaoea228d02018-01-05 19:10:33324 html_file.write(html_header + html_table + html_footer)
325
Yuke Liao506e8822017-12-04 16:52:54326
Abhishek Arya64636af2018-05-04 14:42:13327def _ConfigureLogging(args):
328 """Configures logging settings for later use."""
329 log_level = logging.DEBUG if args.verbose else logging.INFO
330 log_format = '[%(asctime)s %(levelname)s] %(message)s'
331 log_file = args.log_file if args.log_file else None
332 logging.basicConfig(filename=log_file, level=log_level, format=log_format)
333
334
Max Morozd73e45f2018-04-24 18:32:47335def _GetSharedLibraries(binary_paths):
336 """Returns set of shared libraries used by specified binaries."""
337 libraries = set()
338 cmd = []
339 shared_library_re = None
340
341 if sys.platform.startswith('linux'):
342 cmd.extend(['ldd'])
Abhishek Arya64636af2018-05-04 14:42:13343 shared_library_re = re.compile(r'.*\.so\s=>\s(.*' + BUILD_DIR +
344 r'.*\.so)\s.*')
Max Morozd73e45f2018-04-24 18:32:47345 elif sys.platform.startswith('darwin'):
346 cmd.extend(['otool', '-L'])
347 shared_library_re = re.compile(r'\s+(@rpath/.*\.dylib)\s.*')
348 else:
349 assert False, ('Cannot detect shared libraries used by the given targets.')
350
351 assert shared_library_re is not None
352
353 cmd.extend(binary_paths)
354 output = subprocess.check_output(cmd)
355
356 for line in output.splitlines():
357 m = shared_library_re.match(line)
358 if not m:
359 continue
360
361 shared_library_path = m.group(1)
362 if sys.platform.startswith('darwin'):
363 # otool outputs "@rpath" macro instead of the dirname of the given binary.
364 shared_library_path = shared_library_path.replace('@rpath', BUILD_DIR)
365
366 assert os.path.exists(shared_library_path), ('Shared library "%s" used by '
367 'the given target(s) does not '
368 'exist.' % shared_library_path)
369 with open(shared_library_path) as f:
370 data = f.read()
371
372 # Do not add non-instrumented libraries. Otherwise, llvm-cov errors outs.
373 if '__llvm_cov' in data:
374 libraries.add(shared_library_path)
375
376 return list(libraries)
377
378
Yuke Liaoc60b2d02018-03-02 21:40:43379def _GetHostPlatform():
380 """Returns the host platform.
381
382 This is separate from the target platform/os that coverage is running for.
383 """
Abhishek Arya1ec832c2017-12-05 18:06:59384 if sys.platform == 'win32' or sys.platform == 'cygwin':
385 return 'win'
386 if sys.platform.startswith('linux'):
387 return 'linux'
388 else:
389 assert sys.platform == 'darwin'
390 return 'mac'
391
392
Yuke Liaoc60b2d02018-03-02 21:40:43393def _GetTargetOS():
394 """Returns the target os specified in args.gn file.
395
396 Returns an empty string is target_os is not specified.
397 """
Yuke Liao80afff32018-03-07 01:26:20398 build_args = _GetBuildArgs()
Yuke Liaoc60b2d02018-03-02 21:40:43399 return build_args['target_os'] if 'target_os' in build_args else ''
400
401
Yuke Liaob2926832018-03-02 17:34:29402def _IsIOS():
Yuke Liaoa0c8c2f2018-02-28 20:14:10403 """Returns true if the target_os specified in args.gn file is ios"""
Yuke Liaoc60b2d02018-03-02 21:40:43404 return _GetTargetOS() == 'ios'
Yuke Liaoa0c8c2f2018-02-28 20:14:10405
406
Yuke Liao506e8822017-12-04 16:52:54407# TODO(crbug.com/759794): remove this function once tools get included to
408# Clang bundle:
409# https://chromium-review.googlesource.com/c/chromium/src/+/688221
410def DownloadCoverageToolsIfNeeded():
411 """Temporary solution to download llvm-profdata and llvm-cov tools."""
Abhishek Arya1ec832c2017-12-05 18:06:59412
Yuke Liaoc60b2d02018-03-02 21:40:43413 def _GetRevisionFromStampFile(stamp_file_path):
Yuke Liao506e8822017-12-04 16:52:54414 """Returns a pair of revision number by reading the build stamp file.
415
416 Args:
417 stamp_file_path: A path the build stamp file created by
418 tools/clang/scripts/update.py.
419 Returns:
420 A pair of integers represeting the main and sub revision respectively.
421 """
422 if not os.path.exists(stamp_file_path):
423 return 0, 0
424
425 with open(stamp_file_path) as stamp_file:
Yuke Liaoc60b2d02018-03-02 21:40:43426 stamp_file_line = stamp_file.readline()
427 if ',' in stamp_file_line:
428 package_version = stamp_file_line.rstrip().split(',')[0]
429 else:
430 package_version = stamp_file_line.rstrip()
Yuke Liao506e8822017-12-04 16:52:54431
Yuke Liaoc60b2d02018-03-02 21:40:43432 clang_revision_str, clang_sub_revision_str = package_version.split('-')
433 return int(clang_revision_str), int(clang_sub_revision_str)
Abhishek Arya1ec832c2017-12-05 18:06:59434
Yuke Liaoc60b2d02018-03-02 21:40:43435 host_platform = _GetHostPlatform()
Yuke Liao506e8822017-12-04 16:52:54436 clang_revision, clang_sub_revision = _GetRevisionFromStampFile(
Yuke Liaoc60b2d02018-03-02 21:40:43437 clang_update.STAMP_FILE)
Yuke Liao506e8822017-12-04 16:52:54438
439 coverage_revision_stamp_file = os.path.join(
440 os.path.dirname(clang_update.STAMP_FILE), 'cr_coverage_revision')
441 coverage_revision, coverage_sub_revision = _GetRevisionFromStampFile(
Yuke Liaoc60b2d02018-03-02 21:40:43442 coverage_revision_stamp_file)
Yuke Liao506e8822017-12-04 16:52:54443
Yuke Liaoea228d02018-01-05 19:10:33444 has_coverage_tools = (
445 os.path.exists(LLVM_COV_PATH) and os.path.exists(LLVM_PROFDATA_PATH))
Abhishek Arya16f059a2017-12-07 17:47:32446
Yuke Liaoea228d02018-01-05 19:10:33447 if (has_coverage_tools and coverage_revision == clang_revision and
Yuke Liao506e8822017-12-04 16:52:54448 coverage_sub_revision == clang_sub_revision):
449 # LLVM coverage tools are up to date, bail out.
Yuke Liaoc60b2d02018-03-02 21:40:43450 return
Yuke Liao506e8822017-12-04 16:52:54451
452 package_version = '%d-%d' % (clang_revision, clang_sub_revision)
453 coverage_tools_file = 'llvm-code-coverage-%s.tgz' % package_version
454
455 # The code bellow follows the code from tools/clang/scripts/update.py.
Yuke Liaoc60b2d02018-03-02 21:40:43456 if host_platform == 'mac':
Yuke Liao506e8822017-12-04 16:52:54457 coverage_tools_url = clang_update.CDS_URL + '/Mac/' + coverage_tools_file
Yuke Liaoc60b2d02018-03-02 21:40:43458 elif host_platform == 'linux':
Yuke Liao506e8822017-12-04 16:52:54459 coverage_tools_url = (
460 clang_update.CDS_URL + '/Linux_x64/' + coverage_tools_file)
Yuke Liaoc60b2d02018-03-02 21:40:43461 else:
462 assert host_platform == 'win'
463 coverage_tools_url = (clang_update.CDS_URL + '/Win/' + coverage_tools_file)
Yuke Liao506e8822017-12-04 16:52:54464
465 try:
466 clang_update.DownloadAndUnpack(coverage_tools_url,
467 clang_update.LLVM_BUILD_DIR)
Yuke Liao481d3482018-01-29 19:17:10468 logging.info('Coverage tools %s unpacked', package_version)
Yuke Liao506e8822017-12-04 16:52:54469 with open(coverage_revision_stamp_file, 'w') as file_handle:
Yuke Liaoc60b2d02018-03-02 21:40:43470 file_handle.write('%s,%s' % (package_version, host_platform))
Yuke Liao506e8822017-12-04 16:52:54471 file_handle.write('\n')
472 except urllib2.URLError:
473 raise Exception(
474 'Failed to download coverage tools: %s.' % coverage_tools_url)
475
476
Yuke Liaodd1ec0592018-02-02 01:26:37477def _GeneratePerFileLineByLineCoverageInHtml(binary_paths, profdata_file_path,
Yuke Liao0e4c8682018-04-18 21:06:59478 filters, ignore_filename_regex):
Yuke Liao506e8822017-12-04 16:52:54479 """Generates per file line-by-line coverage in html using 'llvm-cov show'.
480
481 For a file with absolute path /a/b/x.cc, a html report is generated as:
482 OUTPUT_DIR/coverage/a/b/x.cc.html. An index html file is also generated as:
483 OUTPUT_DIR/index.html.
484
485 Args:
486 binary_paths: A list of paths to the instrumented binaries.
487 profdata_file_path: A path to the profdata file.
Yuke Liao66da1732017-12-05 22:19:42488 filters: A list of directories and files to get coverage for.
Yuke Liao506e8822017-12-04 16:52:54489 """
Yuke Liao506e8822017-12-04 16:52:54490 # llvm-cov show [options] -instr-profile PROFILE BIN [-object BIN,...]
491 # [[-object BIN]] [SOURCES]
492 # NOTE: For object files, the first one is specified as a positional argument,
493 # and the rest are specified as keyword argument.
Yuke Liao481d3482018-01-29 19:17:10494 logging.debug('Generating per file line by line coverage reports using '
495 '"llvm-cov show" command')
Abhishek Arya1ec832c2017-12-05 18:06:59496 subprocess_cmd = [
497 LLVM_COV_PATH, 'show', '-format=html',
498 '-output-dir={}'.format(OUTPUT_DIR),
499 '-instr-profile={}'.format(profdata_file_path), binary_paths[0]
500 ]
501 subprocess_cmd.extend(
502 ['-object=' + binary_path for binary_path in binary_paths[1:]])
Yuke Liaob2926832018-03-02 17:34:29503 _AddArchArgumentForIOSIfNeeded(subprocess_cmd, len(binary_paths))
Yuke Liao66da1732017-12-05 22:19:42504 subprocess_cmd.extend(filters)
Yuke Liao0e4c8682018-04-18 21:06:59505 if ignore_filename_regex:
506 subprocess_cmd.append('-ignore-filename-regex=%s' % ignore_filename_regex)
507
Yuke Liao506e8822017-12-04 16:52:54508 subprocess.check_call(subprocess_cmd)
Max Moroz025d8952018-05-03 16:33:34509
510 # llvm-cov creates "coverage" subdir in the output dir. We would like to use
511 # the platform name instead, as it simplifies the report dir structure when
512 # the same report is generated for different platforms.
513 default_report_subdir_path = os.path.join(OUTPUT_DIR, 'coverage')
Max Moroz7c5354f2018-05-06 00:03:48514 platform_report_subdir_path = _GetCoverageReportRootDirPath()
515 _MergeTwoDirectories(default_report_subdir_path, platform_report_subdir_path)
Max Moroz025d8952018-05-03 16:33:34516
Yuke Liao481d3482018-01-29 19:17:10517 logging.debug('Finished running "llvm-cov show" command')
Yuke Liao506e8822017-12-04 16:52:54518
519
Yuke Liaodd1ec0592018-02-02 01:26:37520def _GenerateFileViewHtmlIndexFile(per_file_coverage_summary):
521 """Generates html index file for file view."""
Max Moroz7c5354f2018-05-06 00:03:48522 file_view_index_file_path = _GetFileViewPath()
Yuke Liaodd1ec0592018-02-02 01:26:37523 logging.debug('Generating file view html index file as: "%s".',
524 file_view_index_file_path)
525 html_generator = _CoverageReportHtmlGenerator(file_view_index_file_path,
526 'Path')
527 totals_coverage_summary = _CoverageSummary()
Yuke Liaoea228d02018-01-05 19:10:33528
Yuke Liaodd1ec0592018-02-02 01:26:37529 for file_path in per_file_coverage_summary:
530 totals_coverage_summary.AddSummary(per_file_coverage_summary[file_path])
531
532 html_generator.AddLinkToAnotherReport(
533 _GetCoverageHtmlReportPathForFile(file_path),
534 os.path.relpath(file_path, SRC_ROOT_PATH),
535 per_file_coverage_summary[file_path])
536
537 html_generator.CreateTotalsEntry(totals_coverage_summary)
538 html_generator.WriteHtmlCoverageReport()
539 logging.debug('Finished generating file view html index file.')
540
541
542def _CalculatePerDirectoryCoverageSummary(per_file_coverage_summary):
543 """Calculates per directory coverage summary."""
544 logging.debug('Calculating per-directory coverage summary')
545 per_directory_coverage_summary = defaultdict(lambda: _CoverageSummary())
546
Yuke Liaoea228d02018-01-05 19:10:33547 for file_path in per_file_coverage_summary:
548 summary = per_file_coverage_summary[file_path]
549 parent_dir = os.path.dirname(file_path)
550 while True:
551 per_directory_coverage_summary[parent_dir].AddSummary(summary)
552
553 if parent_dir == SRC_ROOT_PATH:
554 break
555 parent_dir = os.path.dirname(parent_dir)
556
Yuke Liaodd1ec0592018-02-02 01:26:37557 logging.debug('Finished calculating per-directory coverage summary')
558 return per_directory_coverage_summary
559
560
561def _GeneratePerDirectoryCoverageInHtml(per_directory_coverage_summary,
562 per_file_coverage_summary):
563 """Generates per directory coverage breakdown in html."""
564 logging.debug('Writing per-directory coverage html reports')
Yuke Liaoea228d02018-01-05 19:10:33565 for dir_path in per_directory_coverage_summary:
566 _GenerateCoverageInHtmlForDirectory(
567 dir_path, per_directory_coverage_summary, per_file_coverage_summary)
568
Yuke Liaodd1ec0592018-02-02 01:26:37569 logging.debug('Finished writing per-directory coverage html reports')
Yuke Liao481d3482018-01-29 19:17:10570
Yuke Liaoea228d02018-01-05 19:10:33571
572def _GenerateCoverageInHtmlForDirectory(
573 dir_path, per_directory_coverage_summary, per_file_coverage_summary):
574 """Generates coverage html report for a single directory."""
Yuke Liaodd1ec0592018-02-02 01:26:37575 html_generator = _CoverageReportHtmlGenerator(
576 _GetCoverageHtmlReportPathForDirectory(dir_path), 'Path')
Yuke Liaoea228d02018-01-05 19:10:33577
578 for entry_name in os.listdir(dir_path):
579 entry_path = os.path.normpath(os.path.join(dir_path, entry_name))
Yuke Liaoea228d02018-01-05 19:10:33580
Yuke Liaodd1ec0592018-02-02 01:26:37581 if entry_path in per_file_coverage_summary:
582 entry_html_report_path = _GetCoverageHtmlReportPathForFile(entry_path)
583 entry_coverage_summary = per_file_coverage_summary[entry_path]
584 elif entry_path in per_directory_coverage_summary:
585 entry_html_report_path = _GetCoverageHtmlReportPathForDirectory(
586 entry_path)
587 entry_coverage_summary = per_directory_coverage_summary[entry_path]
588 else:
Yuke Liaoc7e607142018-02-05 20:26:14589 # Any file without executable lines shouldn't be included into the report.
590 # For example, OWNER and README.md files.
Yuke Liaodd1ec0592018-02-02 01:26:37591 continue
Yuke Liaoea228d02018-01-05 19:10:33592
Yuke Liaodd1ec0592018-02-02 01:26:37593 html_generator.AddLinkToAnotherReport(entry_html_report_path,
594 os.path.basename(entry_path),
595 entry_coverage_summary)
Yuke Liaoea228d02018-01-05 19:10:33596
Yuke Liaod54030e2018-01-08 17:34:12597 html_generator.CreateTotalsEntry(per_directory_coverage_summary[dir_path])
Yuke Liaodd1ec0592018-02-02 01:26:37598 html_generator.WriteHtmlCoverageReport()
599
600
601def _GenerateDirectoryViewHtmlIndexFile():
602 """Generates the html index file for directory view.
603
604 Note that the index file is already generated under SRC_ROOT_PATH, so this
605 file simply redirects to it, and the reason of this extra layer is for
606 structural consistency with other views.
607 """
Max Moroz7c5354f2018-05-06 00:03:48608 directory_view_index_file_path = _GetDirectoryViewPath()
Yuke Liaodd1ec0592018-02-02 01:26:37609 logging.debug('Generating directory view html index file as: "%s".',
610 directory_view_index_file_path)
611 src_root_html_report_path = _GetCoverageHtmlReportPathForDirectory(
612 SRC_ROOT_PATH)
613 _WriteRedirectHtmlFile(directory_view_index_file_path,
614 src_root_html_report_path)
615 logging.debug('Finished generating directory view html index file.')
616
617
618def _CalculatePerComponentCoverageSummary(component_to_directories,
619 per_directory_coverage_summary):
620 """Calculates per component coverage summary."""
621 logging.debug('Calculating per-component coverage summary')
622 per_component_coverage_summary = defaultdict(lambda: _CoverageSummary())
623
624 for component in component_to_directories:
625 for directory in component_to_directories[component]:
626 absolute_directory_path = os.path.abspath(directory)
627 if absolute_directory_path in per_directory_coverage_summary:
628 per_component_coverage_summary[component].AddSummary(
629 per_directory_coverage_summary[absolute_directory_path])
630
631 logging.debug('Finished calculating per-component coverage summary')
632 return per_component_coverage_summary
633
634
635def _ExtractComponentToDirectoriesMapping():
636 """Returns a mapping from components to directories."""
637 component_mappings = json.load(urllib2.urlopen(COMPONENT_MAPPING_URL))
638 directory_to_component = component_mappings['dir-to-component']
639
640 component_to_directories = defaultdict(list)
641 for directory in directory_to_component:
642 component = directory_to_component[directory]
643 component_to_directories[component].append(directory)
644
645 return component_to_directories
646
647
648def _GeneratePerComponentCoverageInHtml(per_component_coverage_summary,
649 component_to_directories,
650 per_directory_coverage_summary):
651 """Generates per-component coverage reports in html."""
652 logging.debug('Writing per-component coverage html reports.')
653 for component in per_component_coverage_summary:
654 _GenerateCoverageInHtmlForComponent(
655 component, per_component_coverage_summary, component_to_directories,
656 per_directory_coverage_summary)
657
658 logging.debug('Finished writing per-component coverage html reports.')
659
660
661def _GenerateCoverageInHtmlForComponent(
662 component_name, per_component_coverage_summary, component_to_directories,
663 per_directory_coverage_summary):
664 """Generates coverage html report for a component."""
665 component_html_report_path = _GetCoverageHtmlReportPathForComponent(
666 component_name)
Yuke Liaoc7e607142018-02-05 20:26:14667 component_html_report_dir = os.path.dirname(component_html_report_path)
668 if not os.path.exists(component_html_report_dir):
669 os.makedirs(component_html_report_dir)
Yuke Liaodd1ec0592018-02-02 01:26:37670
671 html_generator = _CoverageReportHtmlGenerator(component_html_report_path,
672 'Path')
673
674 for dir_path in component_to_directories[component_name]:
675 dir_absolute_path = os.path.abspath(dir_path)
676 if dir_absolute_path not in per_directory_coverage_summary:
Yuke Liaoc7e607142018-02-05 20:26:14677 # Any directory without an excercised file shouldn't be included into the
678 # report.
Yuke Liaodd1ec0592018-02-02 01:26:37679 continue
680
681 html_generator.AddLinkToAnotherReport(
682 _GetCoverageHtmlReportPathForDirectory(dir_path),
683 os.path.relpath(dir_path, SRC_ROOT_PATH),
684 per_directory_coverage_summary[dir_absolute_path])
685
686 html_generator.CreateTotalsEntry(
687 per_component_coverage_summary[component_name])
688 html_generator.WriteHtmlCoverageReport()
689
690
691def _GenerateComponentViewHtmlIndexFile(per_component_coverage_summary):
692 """Generates the html index file for component view."""
Max Moroz7c5354f2018-05-06 00:03:48693 component_view_index_file_path = _GetComponentViewPath()
Yuke Liaodd1ec0592018-02-02 01:26:37694 logging.debug('Generating component view html index file as: "%s".',
695 component_view_index_file_path)
696 html_generator = _CoverageReportHtmlGenerator(component_view_index_file_path,
697 'Component')
698 totals_coverage_summary = _CoverageSummary()
699
700 for component in per_component_coverage_summary:
701 totals_coverage_summary.AddSummary(
702 per_component_coverage_summary[component])
703
704 html_generator.AddLinkToAnotherReport(
705 _GetCoverageHtmlReportPathForComponent(component), component,
706 per_component_coverage_summary[component])
707
708 html_generator.CreateTotalsEntry(totals_coverage_summary)
709 html_generator.WriteHtmlCoverageReport()
Yuke Liaoc7e607142018-02-05 20:26:14710 logging.debug('Finished generating component view html index file.')
Yuke Liaoea228d02018-01-05 19:10:33711
712
Max Moroz7c5354f2018-05-06 00:03:48713def _MergeTwoDirectories(src_path, dst_path):
714 """Merge src_path directory into dst_path directory."""
715 for filename in os.listdir(src_path):
716 dst_path = os.path.join(dst_path, filename)
717 if os.path.exists(dst_path):
718 shutil.rmtree(dst_path)
719 os.rename(os.path.join(src_path, filename), dst_path)
720 shutil.rmtree(src_path)
721
722
Yuke Liaoea228d02018-01-05 19:10:33723def _OverwriteHtmlReportsIndexFile():
Yuke Liaodd1ec0592018-02-02 01:26:37724 """Overwrites the root index file to redirect to the default view."""
Max Moroz7c5354f2018-05-06 00:03:48725 html_index_file_path = _GetHtmlIndexPath()
726 directory_view_index_file_path = _GetDirectoryViewPath()
Yuke Liaodd1ec0592018-02-02 01:26:37727 _WriteRedirectHtmlFile(html_index_file_path, directory_view_index_file_path)
728
729
730def _WriteRedirectHtmlFile(from_html_path, to_html_path):
731 """Writes a html file that redirects to another html file."""
732 to_html_relative_path = _GetRelativePathToDirectoryOfFile(
733 to_html_path, from_html_path)
Yuke Liaoea228d02018-01-05 19:10:33734 content = ("""
735 <!DOCTYPE html>
736 <html>
737 <head>
738 <!-- HTML meta refresh URL redirection -->
739 <meta http-equiv="refresh" content="0; url=%s">
740 </head>
Yuke Liaodd1ec0592018-02-02 01:26:37741 </html>""" % to_html_relative_path)
742 with open(from_html_path, 'w') as f:
Yuke Liaoea228d02018-01-05 19:10:33743 f.write(content)
744
745
Max Moroz7c5354f2018-05-06 00:03:48746def _CleanUpOutputDir():
747 """Perform a cleanup of the output dir."""
748 # Remove the default index.html file produced by llvm-cov.
749 index_path = os.path.join(OUTPUT_DIR, INDEX_HTML_FILE)
750 if os.path.exists(index_path):
751 os.remove(index_path)
752
753
Yuke Liaodd1ec0592018-02-02 01:26:37754def _GetCoverageHtmlReportPathForFile(file_path):
755 """Given a file path, returns the corresponding html report path."""
756 assert os.path.isfile(file_path), '"%s" is not a file' % file_path
757 html_report_path = os.extsep.join([os.path.abspath(file_path), 'html'])
758
759 # '+' is used instead of os.path.join because both of them are absolute paths
760 # and os.path.join ignores the first path.
Yuke Liaoc7e607142018-02-05 20:26:14761 # TODO(crbug.com/809150): Think of a generic cross platform fix (Windows).
Yuke Liaodd1ec0592018-02-02 01:26:37762 return _GetCoverageReportRootDirPath() + html_report_path
763
764
765def _GetCoverageHtmlReportPathForDirectory(dir_path):
766 """Given a directory path, returns the corresponding html report path."""
767 assert os.path.isdir(dir_path), '"%s" is not a directory' % dir_path
768 html_report_path = os.path.join(
769 os.path.abspath(dir_path), DIRECTORY_COVERAGE_HTML_REPORT_NAME)
770
771 # '+' is used instead of os.path.join because both of them are absolute paths
772 # and os.path.join ignores the first path.
Yuke Liaoc7e607142018-02-05 20:26:14773 # TODO(crbug.com/809150): Think of a generic cross platform fix (Windows).
Yuke Liaodd1ec0592018-02-02 01:26:37774 return _GetCoverageReportRootDirPath() + html_report_path
775
776
777def _GetCoverageHtmlReportPathForComponent(component_name):
778 """Given a component, returns the corresponding html report path."""
779 component_file_name = component_name.lower().replace('>', '-')
780 html_report_name = os.extsep.join([component_file_name, 'html'])
781 return os.path.join(_GetCoverageReportRootDirPath(), 'components',
782 html_report_name)
783
784
785def _GetCoverageReportRootDirPath():
786 """The root directory that contains all generated coverage html reports."""
Max Moroz7c5354f2018-05-06 00:03:48787 return os.path.join(OUTPUT_DIR, _GetHostPlatform())
788
789
790def _GetComponentViewPath():
791 """Path to the HTML file for the component view."""
792 return os.path.join(_GetCoverageReportRootDirPath(),
793 COMPONENT_VIEW_INDEX_FILE)
794
795
796def _GetDirectoryViewPath():
797 """Path to the HTML file for the directory view."""
798 return os.path.join(_GetCoverageReportRootDirPath(),
799 DIRECTORY_VIEW_INDEX_FILE)
800
801
802def _GetFileViewPath():
803 """Path to the HTML file for the file view."""
804 return os.path.join(_GetCoverageReportRootDirPath(), FILE_VIEW_INDEX_FILE)
805
806
807def _GetLogsDirectoryPath():
808 """Path to the logs directory."""
809 return os.path.join(_GetCoverageReportRootDirPath(), LOGS_DIR_NAME)
810
811
812def _GetHtmlIndexPath():
813 """Path to the main HTML index file."""
814 return os.path.join(_GetCoverageReportRootDirPath(), INDEX_HTML_FILE)
815
816
817def _GetProfdataFilePath():
818 """Path to the resulting .profdata file."""
819 return os.path.join(_GetCoverageReportRootDirPath(), PROFDATA_FILE_NAME)
820
821
822def _GetSummaryFilePath():
823 """The JSON file that contains coverage summary written by llvm-cov export."""
824 return os.path.join(_GetCoverageReportRootDirPath(), SUMMARY_FILE_NAME)
Yuke Liaoea228d02018-01-05 19:10:33825
826
Yuke Liao506e8822017-12-04 16:52:54827def _CreateCoverageProfileDataForTargets(targets, commands, jobs_count=None):
828 """Builds and runs target to generate the coverage profile data.
829
830 Args:
831 targets: A list of targets to build with coverage instrumentation.
832 commands: A list of commands used to run the targets.
833 jobs_count: Number of jobs to run in parallel for building. If None, a
834 default value is derived based on CPUs availability.
835
836 Returns:
837 A relative path to the generated profdata file.
838 """
839 _BuildTargets(targets, jobs_count)
Abhishek Aryac19bc5ef2018-05-04 22:10:02840 target_profdata_file_paths = _GetTargetProfDataPathsByExecutingCommands(
Abhishek Arya1ec832c2017-12-05 18:06:59841 targets, commands)
Abhishek Aryac19bc5ef2018-05-04 22:10:02842 coverage_profdata_file_path = (
843 _CreateCoverageProfileDataFromTargetProfDataFiles(
844 target_profdata_file_paths))
Yuke Liao506e8822017-12-04 16:52:54845
Abhishek Aryac19bc5ef2018-05-04 22:10:02846 for target_profdata_file_path in target_profdata_file_paths:
847 os.remove(target_profdata_file_path)
Yuke Liaod4a9865202018-01-12 23:17:52848
Abhishek Aryac19bc5ef2018-05-04 22:10:02849 return coverage_profdata_file_path
Yuke Liao506e8822017-12-04 16:52:54850
851
852def _BuildTargets(targets, jobs_count):
853 """Builds target with Clang coverage instrumentation.
854
855 This function requires current working directory to be the root of checkout.
856
857 Args:
858 targets: A list of targets to build with coverage instrumentation.
859 jobs_count: Number of jobs to run in parallel for compilation. If None, a
860 default value is derived based on CPUs availability.
Yuke Liao506e8822017-12-04 16:52:54861 """
Abhishek Arya1ec832c2017-12-05 18:06:59862
Yuke Liao506e8822017-12-04 16:52:54863 def _IsGomaConfigured():
864 """Returns True if goma is enabled in the gn build args.
865
866 Returns:
867 A boolean indicates whether goma is configured for building or not.
868 """
Yuke Liao80afff32018-03-07 01:26:20869 build_args = _GetBuildArgs()
Yuke Liao506e8822017-12-04 16:52:54870 return 'use_goma' in build_args and build_args['use_goma'] == 'true'
871
Yuke Liao481d3482018-01-29 19:17:10872 logging.info('Building %s', str(targets))
Yuke Liao506e8822017-12-04 16:52:54873 if jobs_count is None and _IsGomaConfigured():
874 jobs_count = DEFAULT_GOMA_JOBS
875
876 subprocess_cmd = ['ninja', '-C', BUILD_DIR]
877 if jobs_count is not None:
878 subprocess_cmd.append('-j' + str(jobs_count))
879
880 subprocess_cmd.extend(targets)
881 subprocess.check_call(subprocess_cmd)
Yuke Liao481d3482018-01-29 19:17:10882 logging.debug('Finished building %s', str(targets))
Yuke Liao506e8822017-12-04 16:52:54883
884
Abhishek Aryac19bc5ef2018-05-04 22:10:02885def _GetTargetProfDataPathsByExecutingCommands(targets, commands):
Yuke Liao506e8822017-12-04 16:52:54886 """Runs commands and returns the relative paths to the profraw data files.
887
888 Args:
889 targets: A list of targets built with coverage instrumentation.
890 commands: A list of commands used to run the targets.
891
892 Returns:
893 A list of relative paths to the generated profraw data files.
894 """
Yuke Liao481d3482018-01-29 19:17:10895 logging.debug('Executing the test commands')
896
Yuke Liao506e8822017-12-04 16:52:54897 # Remove existing profraw data files.
Max Moroz7c5354f2018-05-06 00:03:48898 for file_or_dir in os.listdir(_GetCoverageReportRootDirPath()):
Yuke Liao506e8822017-12-04 16:52:54899 if file_or_dir.endswith(PROFRAW_FILE_EXTENSION):
Max Moroz7c5354f2018-05-06 00:03:48900 os.remove(os.path.join(_GetCoverageReportRootDirPath(), file_or_dir))
901
902 # Ensure that logs directory exists.
903 if not os.path.exists(_GetLogsDirectoryPath()):
904 os.makedirs(_GetLogsDirectoryPath())
Yuke Liao506e8822017-12-04 16:52:54905
Abhishek Aryac19bc5ef2018-05-04 22:10:02906 profdata_file_paths = []
Yuke Liaoa0c8c2f2018-02-28 20:14:10907
Yuke Liaod4a9865202018-01-12 23:17:52908 # Run all test targets to generate profraw data files.
Yuke Liao506e8822017-12-04 16:52:54909 for target, command in zip(targets, commands):
Max Moroz7c5354f2018-05-06 00:03:48910 output_file_name = os.extsep.join([target + '_output', 'log'])
911 output_file_path = os.path.join(_GetLogsDirectoryPath(), output_file_name)
Yuke Liaoa0c8c2f2018-02-28 20:14:10912
Abhishek Aryac19bc5ef2018-05-04 22:10:02913 profdata_file_path = None
914 for _ in xrange(MERGE_RETRIES):
915 logging.info('Running command: "%s", the output is redirected to "%s"',
916 command, output_file_path)
Yuke Liaoa0c8c2f2018-02-28 20:14:10917
Abhishek Aryac19bc5ef2018-05-04 22:10:02918 if _IsIOSCommand(command):
919 # On iOS platform, due to lack of write permissions, profraw files are
920 # generated outside of the OUTPUT_DIR, and the exact paths are contained
921 # in the output of the command execution.
922 output = _ExecuteIOSCommand(target, command)
923 else:
924 # On other platforms, profraw files are generated inside the OUTPUT_DIR.
925 output = _ExecuteCommand(target, command)
926
927 with open(output_file_path, 'w') as output_file:
928 output_file.write(output)
929
930 profraw_file_paths = []
931 if _IsIOS():
932 profraw_file_paths = _GetProfrawDataFileByParsingOutput(output)
933 else:
Max Moroz7c5354f2018-05-06 00:03:48934 for file_or_dir in os.listdir(_GetCoverageReportRootDirPath()):
Abhishek Aryac19bc5ef2018-05-04 22:10:02935 if file_or_dir.endswith(PROFRAW_FILE_EXTENSION):
Max Moroz7c5354f2018-05-06 00:03:48936 profraw_file_paths.append(
937 os.path.join(_GetCoverageReportRootDirPath(), file_or_dir))
Abhishek Aryac19bc5ef2018-05-04 22:10:02938
939 assert profraw_file_paths, (
940 'Running target %s failed to generate any profraw data file, '
941 'please make sure the binary exists and is properly '
942 'instrumented.' % target)
943
944 try:
945 profdata_file_path = _CreateTargetProfDataFileFromProfRawFiles(
946 target, profraw_file_paths)
947 break
948 except Exception:
949 print('Retrying...')
950 finally:
951 # Remove profraw files now so that they are not used in next iteration.
952 for profraw_file_path in profraw_file_paths:
953 os.remove(profraw_file_path)
954
955 assert profdata_file_path, (
956 'Failed to merge target %s profraw files after %d retries. '
957 'Please file a bug with command you used, commit position and args.gn '
958 'config here: '
959 'https://bugs.chromium.org/p/chromium/issues/entry?'
960 'components=Tools%%3ECodeCoverage'% (target, MERGE_RETRIES))
961 profdata_file_paths.append(profdata_file_path)
Yuke Liao506e8822017-12-04 16:52:54962
Yuke Liao481d3482018-01-29 19:17:10963 logging.debug('Finished executing the test commands')
964
Abhishek Aryac19bc5ef2018-05-04 22:10:02965 return profdata_file_paths
Yuke Liao506e8822017-12-04 16:52:54966
967
968def _ExecuteCommand(target, command):
Yuke Liaoa0c8c2f2018-02-28 20:14:10969 """Runs a single command and generates a profraw data file."""
Yuke Liaod4a9865202018-01-12 23:17:52970 # Per Clang "Source-based Code Coverage" doc:
Yuke Liao27349c92018-03-22 21:10:01971 #
Max Morozd73e45f2018-04-24 18:32:47972 # "%p" expands out to the process ID. It's not used by this scripts due to:
973 # 1) If a target program spawns too many processess, it may exhaust all disk
974 # space available. For example, unit_tests writes thousands of .profraw
975 # files each of size 1GB+.
976 # 2) If a target binary uses shared libraries, coverage profile data for them
977 # will be missing, resulting in incomplete coverage reports.
Yuke Liao27349c92018-03-22 21:10:01978 #
Yuke Liaod4a9865202018-01-12 23:17:52979 # "%Nm" expands out to the instrumented binary's signature. When this pattern
980 # is specified, the runtime creates a pool of N raw profiles which are used
981 # for on-line profile merging. The runtime takes care of selecting a raw
982 # profile from the pool, locking it, and updating it before the program exits.
Yuke Liaod4a9865202018-01-12 23:17:52983 # N must be between 1 and 9. The merge pool specifier can only occur once per
984 # filename pattern.
985 #
Max Morozd73e45f2018-04-24 18:32:47986 # "%1m" is used when tests run in single process, such as fuzz targets.
Yuke Liao27349c92018-03-22 21:10:01987 #
Max Morozd73e45f2018-04-24 18:32:47988 # For other cases, "%4m" is chosen as it creates some level of parallelism,
989 # but it's not too big to consume too much computing resource or disk space.
990 profile_pattern_string = '%1m' if _IsFuzzerTarget(target) else '%4m'
Abhishek Arya1ec832c2017-12-05 18:06:59991 expected_profraw_file_name = os.extsep.join(
Yuke Liao27349c92018-03-22 21:10:01992 [target, profile_pattern_string, PROFRAW_FILE_EXTENSION])
Max Moroz7c5354f2018-05-06 00:03:48993 expected_profraw_file_path = os.path.join(_GetCoverageReportRootDirPath(),
Yuke Liao506e8822017-12-04 16:52:54994 expected_profraw_file_name)
Yuke Liao506e8822017-12-04 16:52:54995
Yuke Liaoa0c8c2f2018-02-28 20:14:10996 try:
Max Moroz7c5354f2018-05-06 00:03:48997 # Some fuzz targets or tests may write into stderr, redirect it as well.
Yuke Liaoa0c8c2f2018-02-28 20:14:10998 output = subprocess.check_output(
Yuke Liaob2926832018-03-02 17:34:29999 shlex.split(command),
Max Moroz7c5354f2018-05-06 00:03:481000 stderr=subprocess.STDOUT,
Yuke Liaob2926832018-03-02 17:34:291001 env={'LLVM_PROFILE_FILE': expected_profraw_file_path})
Yuke Liaoa0c8c2f2018-02-28 20:14:101002 except subprocess.CalledProcessError as e:
1003 output = e.output
1004 logging.warning('Command: "%s" exited with non-zero return code', command)
1005
1006 return output
1007
1008
Yuke Liao27349c92018-03-22 21:10:011009def _IsFuzzerTarget(target):
1010 """Returns true if the target is a fuzzer target."""
1011 build_args = _GetBuildArgs()
1012 use_libfuzzer = ('use_libfuzzer' in build_args and
1013 build_args['use_libfuzzer'] == 'true')
1014 return use_libfuzzer and target.endswith('_fuzzer')
1015
1016
Yuke Liaob2926832018-03-02 17:34:291017def _ExecuteIOSCommand(target, command):
Yuke Liaoa0c8c2f2018-02-28 20:14:101018 """Runs a single iOS command and generates a profraw data file.
1019
1020 iOS application doesn't have write access to folders outside of the app, so
1021 it's impossible to instruct the app to flush the profraw data file to the
1022 desired location. The profraw data file will be generated somewhere within the
1023 application's Documents folder, and the full path can be obtained by parsing
1024 the output.
1025 """
Yuke Liaob2926832018-03-02 17:34:291026 assert _IsIOSCommand(command)
1027
1028 # After running tests, iossim generates a profraw data file, it won't be
1029 # needed anyway, so dump it into the OUTPUT_DIR to avoid polluting the
1030 # checkout.
1031 iossim_profraw_file_path = os.path.join(
1032 OUTPUT_DIR, os.extsep.join(['iossim', PROFRAW_FILE_EXTENSION]))
Yuke Liaoa0c8c2f2018-02-28 20:14:101033
1034 try:
Yuke Liaob2926832018-03-02 17:34:291035 output = subprocess.check_output(
1036 shlex.split(command),
1037 env={'LLVM_PROFILE_FILE': iossim_profraw_file_path})
Yuke Liaoa0c8c2f2018-02-28 20:14:101038 except subprocess.CalledProcessError as e:
1039 # iossim emits non-zero return code even if tests run successfully, so
1040 # ignore the return code.
1041 output = e.output
1042
1043 return output
1044
1045
1046def _GetProfrawDataFileByParsingOutput(output):
1047 """Returns the path to the profraw data file obtained by parsing the output.
1048
1049 The output of running the test target has no format, but it is guaranteed to
1050 have a single line containing the path to the generated profraw data file.
1051 NOTE: This should only be called when target os is iOS.
1052 """
Yuke Liaob2926832018-03-02 17:34:291053 assert _IsIOS()
Yuke Liaoa0c8c2f2018-02-28 20:14:101054
Yuke Liaob2926832018-03-02 17:34:291055 output_by_lines = ''.join(output).splitlines()
1056 profraw_file_pattern = re.compile('.*Coverage data at (.*coverage\.profraw).')
Yuke Liaoa0c8c2f2018-02-28 20:14:101057
1058 for line in output_by_lines:
Yuke Liaob2926832018-03-02 17:34:291059 result = profraw_file_pattern.match(line)
1060 if result:
1061 return result.group(1)
Yuke Liaoa0c8c2f2018-02-28 20:14:101062
1063 assert False, ('No profraw data file was generated, did you call '
1064 'coverage_util::ConfigureCoverageReportPath() in test setup? '
1065 'Please refer to base/test/test_support_ios.mm for example.')
Yuke Liao506e8822017-12-04 16:52:541066
1067
Abhishek Aryac19bc5ef2018-05-04 22:10:021068def _CreateCoverageProfileDataFromTargetProfDataFiles(profdata_file_paths):
1069 """Returns a relative path to coverage profdata file by merging target
1070 profdata files.
Yuke Liao506e8822017-12-04 16:52:541071
1072 Args:
Abhishek Aryac19bc5ef2018-05-04 22:10:021073 profdata_file_paths: A list of relative paths to the profdata data files
1074 that are to be merged.
Yuke Liao506e8822017-12-04 16:52:541075
1076 Returns:
Abhishek Aryac19bc5ef2018-05-04 22:10:021077 A relative path to the merged coverage profdata file.
Yuke Liao506e8822017-12-04 16:52:541078
1079 Raises:
Abhishek Aryac19bc5ef2018-05-04 22:10:021080 CalledProcessError: An error occurred merging profdata files.
Yuke Liao506e8822017-12-04 16:52:541081 """
Yuke Liao481d3482018-01-29 19:17:101082 logging.info('Creating the coverage profile data file')
Max Moroz7c5354f2018-05-06 00:03:481083 logging.debug('Merging target profraw files to create target profdata file')
1084 profdata_file_path = _GetProfdataFilePath()
Yuke Liao506e8822017-12-04 16:52:541085 try:
Abhishek Arya1ec832c2017-12-05 18:06:591086 subprocess_cmd = [
1087 LLVM_PROFDATA_PATH, 'merge', '-o', profdata_file_path, '-sparse=true'
1088 ]
Abhishek Aryac19bc5ef2018-05-04 22:10:021089 subprocess_cmd.extend(profdata_file_paths)
1090 subprocess.check_call(subprocess_cmd)
1091 except subprocess.CalledProcessError as error:
1092 print('Failed to merge target profdata files to create coverage profdata. '
1093 'Try again.')
1094 raise error
1095
1096 logging.debug('Finished merging target profdata files')
1097 logging.info('Code coverage profile data is created as: %s',
1098 profdata_file_path)
1099 return profdata_file_path
1100
1101
1102def _CreateTargetProfDataFileFromProfRawFiles(target, profraw_file_paths):
1103 """Returns a relative path to target profdata file by merging target
1104 profraw files.
1105
1106 Args:
1107 profraw_file_paths: A list of relative paths to the profdata data files
1108 that are to be merged.
1109
1110 Returns:
1111 A relative path to the merged coverage profdata file.
1112
1113 Raises:
1114 CalledProcessError: An error occurred merging profdata files.
1115 """
1116 logging.info('Creating target profile data file')
1117 logging.debug('Merging target profraw files to create target profdata file')
1118 profdata_file_path = os.path.join(OUTPUT_DIR, '%s.profdata' % target)
1119
1120 try:
1121 subprocess_cmd = [
1122 LLVM_PROFDATA_PATH, 'merge', '-o', profdata_file_path, '-sparse=true'
1123 ]
Yuke Liao506e8822017-12-04 16:52:541124 subprocess_cmd.extend(profraw_file_paths)
1125 subprocess.check_call(subprocess_cmd)
1126 except subprocess.CalledProcessError as error:
Abhishek Aryac19bc5ef2018-05-04 22:10:021127 print('Failed to merge target profraw files to create target profdata.')
Yuke Liao506e8822017-12-04 16:52:541128 raise error
1129
Abhishek Aryac19bc5ef2018-05-04 22:10:021130 logging.debug('Finished merging target profraw files')
1131 logging.info('Target %s profile data is created as: %s', target,
Yuke Liao481d3482018-01-29 19:17:101132 profdata_file_path)
Yuke Liao506e8822017-12-04 16:52:541133 return profdata_file_path
1134
1135
Yuke Liao0e4c8682018-04-18 21:06:591136def _GeneratePerFileCoverageSummary(binary_paths, profdata_file_path, filters,
1137 ignore_filename_regex):
Yuke Liaoea228d02018-01-05 19:10:331138 """Generates per file coverage summary using "llvm-cov export" command."""
1139 # llvm-cov export [options] -instr-profile PROFILE BIN [-object BIN,...]
1140 # [[-object BIN]] [SOURCES].
1141 # NOTE: For object files, the first one is specified as a positional argument,
1142 # and the rest are specified as keyword argument.
Yuke Liao481d3482018-01-29 19:17:101143 logging.debug('Generating per-file code coverage summary using "llvm-cov '
1144 'export -summary-only" command')
Yuke Liaoea228d02018-01-05 19:10:331145 subprocess_cmd = [
1146 LLVM_COV_PATH, 'export', '-summary-only',
1147 '-instr-profile=' + profdata_file_path, binary_paths[0]
1148 ]
1149 subprocess_cmd.extend(
1150 ['-object=' + binary_path for binary_path in binary_paths[1:]])
Yuke Liaob2926832018-03-02 17:34:291151 _AddArchArgumentForIOSIfNeeded(subprocess_cmd, len(binary_paths))
Yuke Liaoea228d02018-01-05 19:10:331152 subprocess_cmd.extend(filters)
Yuke Liao0e4c8682018-04-18 21:06:591153 if ignore_filename_regex:
1154 subprocess_cmd.append('-ignore-filename-regex=%s' % ignore_filename_regex)
Yuke Liaoea228d02018-01-05 19:10:331155
Max Moroz7c5354f2018-05-06 00:03:481156 export_output = subprocess.check_output(subprocess_cmd)
1157
1158 # Write output on the disk to be used by code coverage bot.
1159 with open(_GetSummaryFilePath(), 'w') as f:
1160 f.write(export_output)
1161
1162 json_output = json.loads(export_output)
Yuke Liaoea228d02018-01-05 19:10:331163 assert len(json_output['data']) == 1
1164 files_coverage_data = json_output['data'][0]['files']
1165
1166 per_file_coverage_summary = {}
1167 for file_coverage_data in files_coverage_data:
1168 file_path = file_coverage_data['filename']
1169 summary = file_coverage_data['summary']
1170
Yuke Liaoea228d02018-01-05 19:10:331171 if summary['lines']['count'] == 0:
1172 continue
1173
1174 per_file_coverage_summary[file_path] = _CoverageSummary(
1175 regions_total=summary['regions']['count'],
1176 regions_covered=summary['regions']['covered'],
1177 functions_total=summary['functions']['count'],
1178 functions_covered=summary['functions']['covered'],
1179 lines_total=summary['lines']['count'],
1180 lines_covered=summary['lines']['covered'])
1181
Yuke Liao481d3482018-01-29 19:17:101182 logging.debug('Finished generating per-file code coverage summary')
Yuke Liaoea228d02018-01-05 19:10:331183 return per_file_coverage_summary
1184
1185
Yuke Liaob2926832018-03-02 17:34:291186def _AddArchArgumentForIOSIfNeeded(cmd_list, num_archs):
1187 """Appends -arch arguments to the command list if it's ios platform.
1188
1189 iOS binaries are universal binaries, and require specifying the architecture
1190 to use, and one architecture needs to be specified for each binary.
1191 """
1192 if _IsIOS():
1193 cmd_list.extend(['-arch=x86_64'] * num_archs)
1194
1195
Yuke Liao506e8822017-12-04 16:52:541196def _GetBinaryPath(command):
1197 """Returns a relative path to the binary to be run by the command.
1198
Yuke Liao545db322018-02-15 17:12:011199 Currently, following types of commands are supported (e.g. url_unittests):
1200 1. Run test binary direcly: "out/coverage/url_unittests <arguments>"
1201 2. Use xvfb.
1202 2.1. "python testing/xvfb.py out/coverage/url_unittests <arguments>"
1203 2.2. "testing/xvfb.py out/coverage/url_unittests <arguments>"
Yuke Liao92107f02018-03-07 01:44:371204 3. Use iossim to run tests on iOS platform, please refer to testing/iossim.mm
1205 for its usage.
Yuke Liaoa0c8c2f2018-02-28 20:14:101206 3.1. "out/Coverage-iphonesimulator/iossim
Yuke Liao92107f02018-03-07 01:44:371207 <iossim_arguments> -c <app_arguments>
1208 out/Coverage-iphonesimulator/url_unittests.app"
1209
Yuke Liao545db322018-02-15 17:12:011210
Yuke Liao506e8822017-12-04 16:52:541211 Args:
1212 command: A command used to run a target.
1213
1214 Returns:
1215 A relative path to the binary.
1216 """
Yuke Liao545db322018-02-15 17:12:011217 xvfb_script_name = os.extsep.join(['xvfb', 'py'])
1218
Yuke Liaob2926832018-03-02 17:34:291219 command_parts = shlex.split(command)
Yuke Liao545db322018-02-15 17:12:011220 if os.path.basename(command_parts[0]) == 'python':
1221 assert os.path.basename(command_parts[1]) == xvfb_script_name, (
1222 'This tool doesn\'t understand the command: "%s"' % command)
1223 return command_parts[2]
1224
1225 if os.path.basename(command_parts[0]) == xvfb_script_name:
1226 return command_parts[1]
1227
Yuke Liaob2926832018-03-02 17:34:291228 if _IsIOSCommand(command):
Yuke Liaoa0c8c2f2018-02-28 20:14:101229 # For a given application bundle, the binary resides in the bundle and has
1230 # the same name with the application without the .app extension.
Yuke Liao92107f02018-03-07 01:44:371231 app_path = command_parts[-1].rstrip(os.path.sep)
Yuke Liaoa0c8c2f2018-02-28 20:14:101232 app_name = os.path.splitext(os.path.basename(app_path))[0]
1233 return os.path.join(app_path, app_name)
1234
Yuke Liaob2926832018-03-02 17:34:291235 return command_parts[0]
Yuke Liao506e8822017-12-04 16:52:541236
1237
Yuke Liaob2926832018-03-02 17:34:291238def _IsIOSCommand(command):
Yuke Liaoa0c8c2f2018-02-28 20:14:101239 """Returns true if command is used to run tests on iOS platform."""
Yuke Liaob2926832018-03-02 17:34:291240 return os.path.basename(shlex.split(command)[0]) == 'iossim'
Yuke Liaoa0c8c2f2018-02-28 20:14:101241
1242
Yuke Liao95d13d72017-12-07 18:18:501243def _VerifyTargetExecutablesAreInBuildDirectory(commands):
1244 """Verifies that the target executables specified in the commands are inside
1245 the given build directory."""
Yuke Liao506e8822017-12-04 16:52:541246 for command in commands:
1247 binary_path = _GetBinaryPath(command)
Yuke Liao95d13d72017-12-07 18:18:501248 binary_absolute_path = os.path.abspath(os.path.normpath(binary_path))
Max Moroz7c5354f2018-05-06 00:03:481249 assert binary_absolute_path.startswith(BUILD_DIR), (
Yuke Liao95d13d72017-12-07 18:18:501250 'Target executable "%s" in command: "%s" is outside of '
1251 'the given build directory: "%s".' % (binary_path, command, BUILD_DIR))
Yuke Liao506e8822017-12-04 16:52:541252
1253
1254def _ValidateBuildingWithClangCoverage():
1255 """Asserts that targets are built with Clang coverage enabled."""
Yuke Liao80afff32018-03-07 01:26:201256 build_args = _GetBuildArgs()
Yuke Liao506e8822017-12-04 16:52:541257
1258 if (CLANG_COVERAGE_BUILD_ARG not in build_args or
1259 build_args[CLANG_COVERAGE_BUILD_ARG] != 'true'):
Abhishek Arya1ec832c2017-12-05 18:06:591260 assert False, ('\'{} = true\' is required in args.gn.'
1261 ).format(CLANG_COVERAGE_BUILD_ARG)
Yuke Liao506e8822017-12-04 16:52:541262
1263
Yuke Liaoc60b2d02018-03-02 21:40:431264def _ValidateCurrentPlatformIsSupported():
1265 """Asserts that this script suports running on the current platform"""
1266 target_os = _GetTargetOS()
1267 if target_os:
1268 current_platform = target_os
1269 else:
1270 current_platform = _GetHostPlatform()
1271
1272 assert current_platform in [
1273 'linux', 'mac', 'chromeos', 'ios'
1274 ], ('Coverage is only supported on linux, mac, chromeos and ios.')
1275
1276
Yuke Liao80afff32018-03-07 01:26:201277def _GetBuildArgs():
Yuke Liao506e8822017-12-04 16:52:541278 """Parses args.gn file and returns results as a dictionary.
1279
1280 Returns:
1281 A dictionary representing the build args.
1282 """
Yuke Liao80afff32018-03-07 01:26:201283 global _BUILD_ARGS
1284 if _BUILD_ARGS is not None:
1285 return _BUILD_ARGS
1286
1287 _BUILD_ARGS = {}
Yuke Liao506e8822017-12-04 16:52:541288 build_args_path = os.path.join(BUILD_DIR, 'args.gn')
1289 assert os.path.exists(build_args_path), ('"%s" is not a build directory, '
1290 'missing args.gn file.' % BUILD_DIR)
1291 with open(build_args_path) as build_args_file:
1292 build_args_lines = build_args_file.readlines()
1293
Yuke Liao506e8822017-12-04 16:52:541294 for build_arg_line in build_args_lines:
1295 build_arg_without_comments = build_arg_line.split('#')[0]
1296 key_value_pair = build_arg_without_comments.split('=')
1297 if len(key_value_pair) != 2:
1298 continue
1299
1300 key = key_value_pair[0].strip()
Yuke Liaoc60b2d02018-03-02 21:40:431301
1302 # Values are wrapped within a pair of double-quotes, so remove the leading
1303 # and trailing double-quotes.
1304 value = key_value_pair[1].strip().strip('"')
Yuke Liao80afff32018-03-07 01:26:201305 _BUILD_ARGS[key] = value
Yuke Liao506e8822017-12-04 16:52:541306
Yuke Liao80afff32018-03-07 01:26:201307 return _BUILD_ARGS
Yuke Liao506e8822017-12-04 16:52:541308
1309
Abhishek Arya16f059a2017-12-07 17:47:321310def _VerifyPathsAndReturnAbsolutes(paths):
1311 """Verifies that the paths specified in |paths| exist and returns absolute
1312 versions.
Yuke Liao66da1732017-12-05 22:19:421313
1314 Args:
1315 paths: A list of files or directories.
1316 """
Abhishek Arya16f059a2017-12-07 17:47:321317 absolute_paths = []
Yuke Liao66da1732017-12-05 22:19:421318 for path in paths:
Abhishek Arya16f059a2017-12-07 17:47:321319 absolute_path = os.path.join(SRC_ROOT_PATH, path)
1320 assert os.path.exists(absolute_path), ('Path: "%s" doesn\'t exist.' % path)
1321
1322 absolute_paths.append(absolute_path)
1323
1324 return absolute_paths
Yuke Liao66da1732017-12-05 22:19:421325
1326
Yuke Liaodd1ec0592018-02-02 01:26:371327def _GetRelativePathToDirectoryOfFile(target_path, base_path):
1328 """Returns a target path relative to the directory of base_path.
1329
1330 This method requires base_path to be a file, otherwise, one should call
1331 os.path.relpath directly.
1332 """
1333 assert os.path.dirname(base_path) != base_path, (
Yuke Liaoc7e607142018-02-05 20:26:141334 'Base path: "%s" is a directory, please call os.path.relpath directly.' %
Yuke Liaodd1ec0592018-02-02 01:26:371335 base_path)
Yuke Liaoc7e607142018-02-05 20:26:141336 base_dir = os.path.dirname(base_path)
1337 return os.path.relpath(target_path, base_dir)
Yuke Liaodd1ec0592018-02-02 01:26:371338
1339
Abhishek Arya64636af2018-05-04 14:42:131340def _GetBinaryPathsFromTargets(targets, build_dir):
1341 """Return binary paths from target names."""
1342 # FIXME: Derive output binary from target build definitions rather than
1343 # assuming that it is always the same name.
1344 binary_paths = []
1345 for target in targets:
1346 binary_path = os.path.join(build_dir, target)
1347 if _GetHostPlatform() == 'win':
1348 binary_path += '.exe'
1349
1350 if os.path.exists(binary_path):
1351 binary_paths.append(binary_path)
1352 else:
1353 logging.warning(
1354 'Target binary %s not found in build directory, skipping.',
1355 os.path.basename(binary_path))
1356
1357 return binary_paths
1358
1359
Yuke Liao506e8822017-12-04 16:52:541360def _ParseCommandArguments():
1361 """Adds and parses relevant arguments for tool comands.
1362
1363 Returns:
1364 A dictionary representing the arguments.
1365 """
1366 arg_parser = argparse.ArgumentParser()
1367 arg_parser.usage = __doc__
1368
Abhishek Arya1ec832c2017-12-05 18:06:591369 arg_parser.add_argument(
1370 '-b',
1371 '--build-dir',
1372 type=str,
1373 required=True,
1374 help='The build directory, the path needs to be relative to the root of '
1375 'the checkout.')
Yuke Liao506e8822017-12-04 16:52:541376
Abhishek Arya1ec832c2017-12-05 18:06:591377 arg_parser.add_argument(
1378 '-o',
1379 '--output-dir',
1380 type=str,
1381 required=True,
1382 help='Output directory for generated artifacts.')
Yuke Liao506e8822017-12-04 16:52:541383
Abhishek Arya1ec832c2017-12-05 18:06:591384 arg_parser.add_argument(
1385 '-c',
1386 '--command',
1387 action='append',
Abhishek Arya64636af2018-05-04 14:42:131388 required=False,
Abhishek Arya1ec832c2017-12-05 18:06:591389 help='Commands used to run test targets, one test target needs one and '
1390 'only one command, when specifying commands, one should assume the '
Abhishek Arya64636af2018-05-04 14:42:131391 'current working directory is the root of the checkout. This option is '
1392 'incompatible with -p/--profdata-file option.')
1393
1394 arg_parser.add_argument(
1395 '-p',
1396 '--profdata-file',
1397 type=str,
1398 required=False,
1399 help='Path to profdata file to use for generating code coverage reports. '
1400 'This can be useful if you generated the profdata file seperately in '
1401 'your own test harness. This option is ignored if run command(s) are '
1402 'already provided above using -c/--command option.')
Yuke Liao506e8822017-12-04 16:52:541403
Abhishek Arya1ec832c2017-12-05 18:06:591404 arg_parser.add_argument(
Yuke Liao66da1732017-12-05 22:19:421405 '-f',
1406 '--filters',
1407 action='append',
Abhishek Arya16f059a2017-12-07 17:47:321408 required=False,
Yuke Liao66da1732017-12-05 22:19:421409 help='Directories or files to get code coverage for, and all files under '
1410 'the directories are included recursively.')
1411
1412 arg_parser.add_argument(
Yuke Liao0e4c8682018-04-18 21:06:591413 '-i',
1414 '--ignore-filename-regex',
1415 type=str,
1416 help='Skip source code files with file paths that match the given '
1417 'regular expression. For example, use -i=\'.*/out/.*|.*/third_party/.*\' '
1418 'to exclude files in third_party/ and out/ folders from the report.')
1419
1420 arg_parser.add_argument(
Abhishek Arya1ec832c2017-12-05 18:06:591421 '-j',
1422 '--jobs',
1423 type=int,
1424 default=None,
1425 help='Run N jobs to build in parallel. If not specified, a default value '
1426 'will be derived based on CPUs availability. Please refer to '
1427 '\'ninja -h\' for more details.')
Yuke Liao506e8822017-12-04 16:52:541428
Abhishek Arya1ec832c2017-12-05 18:06:591429 arg_parser.add_argument(
Yuke Liao481d3482018-01-29 19:17:101430 '-v',
1431 '--verbose',
1432 action='store_true',
1433 help='Prints additional output for diagnostics.')
1434
1435 arg_parser.add_argument(
1436 '-l', '--log_file', type=str, help='Redirects logs to a file.')
1437
1438 arg_parser.add_argument(
Abhishek Aryac19bc5ef2018-05-04 22:10:021439 'targets',
1440 nargs='+',
1441 help='The names of the test targets to run. If multiple run commands are '
1442 'specified using the -c/--command option, then the order of targets and '
1443 'commands must match, otherwise coverage generation will fail.')
Yuke Liao506e8822017-12-04 16:52:541444
1445 args = arg_parser.parse_args()
1446 return args
1447
1448
1449def Main():
1450 """Execute tool commands."""
Abhishek Arya64636af2018-05-04 14:42:131451 # Change directory to source root to aid in relative paths calculations.
1452 os.chdir(SRC_ROOT_PATH)
Abhishek Arya8a0751a2018-05-03 18:53:111453
Abhishek Arya64636af2018-05-04 14:42:131454 # Setup coverage binaries even when script is called with empty params. This
1455 # is used by coverage bot for initial setup.
Abhishek Arya8a0751a2018-05-03 18:53:111456 DownloadCoverageToolsIfNeeded()
1457
Yuke Liao506e8822017-12-04 16:52:541458 args = _ParseCommandArguments()
Abhishek Arya64636af2018-05-04 14:42:131459 _ConfigureLogging(args)
1460
Yuke Liao506e8822017-12-04 16:52:541461 global BUILD_DIR
Max Moroz7c5354f2018-05-06 00:03:481462 BUILD_DIR = os.path.abspath(args.build_dir)
Yuke Liao506e8822017-12-04 16:52:541463 global OUTPUT_DIR
Max Moroz7c5354f2018-05-06 00:03:481464 OUTPUT_DIR = os.path.abspath(args.output_dir)
Yuke Liao506e8822017-12-04 16:52:541465
Abhishek Arya64636af2018-05-04 14:42:131466 assert args.command or args.profdata_file, (
1467 'Need to either provide commands to run using -c/--command option OR '
1468 'provide prof-data file as input using -p/--profdata-file option.')
Yuke Liaoc60b2d02018-03-02 21:40:431469
Abhishek Arya64636af2018-05-04 14:42:131470 assert not args.command or (len(args.targets) == len(args.command)), (
1471 'Number of targets must be equal to the number of test commands.')
Yuke Liaoc60b2d02018-03-02 21:40:431472
Abhishek Arya1ec832c2017-12-05 18:06:591473 assert os.path.exists(BUILD_DIR), (
1474 'Build directory: {} doesn\'t exist. '
1475 'Please run "gn gen" to generate.').format(BUILD_DIR)
Abhishek Arya64636af2018-05-04 14:42:131476
Yuke Liaoc60b2d02018-03-02 21:40:431477 _ValidateCurrentPlatformIsSupported()
Yuke Liao506e8822017-12-04 16:52:541478 _ValidateBuildingWithClangCoverage()
Abhishek Arya16f059a2017-12-07 17:47:321479
1480 absolute_filter_paths = []
Yuke Liao66da1732017-12-05 22:19:421481 if args.filters:
Abhishek Arya16f059a2017-12-07 17:47:321482 absolute_filter_paths = _VerifyPathsAndReturnAbsolutes(args.filters)
Yuke Liao66da1732017-12-05 22:19:421483
Max Moroz7c5354f2018-05-06 00:03:481484 if not os.path.exists(_GetCoverageReportRootDirPath()):
1485 os.makedirs(_GetCoverageReportRootDirPath())
Yuke Liao506e8822017-12-04 16:52:541486
Abhishek Arya64636af2018-05-04 14:42:131487 # Get profdate file and list of binary paths.
1488 if args.command:
1489 # A list of commands are provided. Run them to generate profdata file, and
1490 # create a list of binary paths from parsing commands.
1491 _VerifyTargetExecutablesAreInBuildDirectory(args.command)
1492 profdata_file_path = _CreateCoverageProfileDataForTargets(
1493 args.targets, args.command, args.jobs)
1494 binary_paths = [_GetBinaryPath(command) for command in args.command]
1495 else:
1496 # An input prof-data file is already provided. Just calculate binary paths.
1497 profdata_file_path = args.profdata_file
1498 binary_paths = _GetBinaryPathsFromTargets(args.targets, args.build_dir)
Yuke Liaoea228d02018-01-05 19:10:331499
Yuke Liao481d3482018-01-29 19:17:101500 logging.info('Generating code coverage report in html (this can take a while '
1501 'depending on size of target!)')
Max Morozd73e45f2018-04-24 18:32:471502 binary_paths.extend(_GetSharedLibraries(binary_paths))
Yuke Liaodd1ec0592018-02-02 01:26:371503 per_file_coverage_summary = _GeneratePerFileCoverageSummary(
Yuke Liao0e4c8682018-04-18 21:06:591504 binary_paths, profdata_file_path, absolute_filter_paths,
1505 args.ignore_filename_regex)
Yuke Liaodd1ec0592018-02-02 01:26:371506 _GeneratePerFileLineByLineCoverageInHtml(binary_paths, profdata_file_path,
Yuke Liao0e4c8682018-04-18 21:06:591507 absolute_filter_paths,
1508 args.ignore_filename_regex)
Yuke Liaodd1ec0592018-02-02 01:26:371509 _GenerateFileViewHtmlIndexFile(per_file_coverage_summary)
1510
1511 per_directory_coverage_summary = _CalculatePerDirectoryCoverageSummary(
1512 per_file_coverage_summary)
1513 _GeneratePerDirectoryCoverageInHtml(per_directory_coverage_summary,
1514 per_file_coverage_summary)
1515 _GenerateDirectoryViewHtmlIndexFile()
1516
1517 component_to_directories = _ExtractComponentToDirectoriesMapping()
1518 per_component_coverage_summary = _CalculatePerComponentCoverageSummary(
1519 component_to_directories, per_directory_coverage_summary)
1520 _GeneratePerComponentCoverageInHtml(per_component_coverage_summary,
1521 component_to_directories,
1522 per_directory_coverage_summary)
1523 _GenerateComponentViewHtmlIndexFile(per_component_coverage_summary)
Yuke Liaoea228d02018-01-05 19:10:331524
1525 # The default index file is generated only for the list of source files, needs
Yuke Liaodd1ec0592018-02-02 01:26:371526 # to overwrite it to display per directory coverage view by default.
Yuke Liaoea228d02018-01-05 19:10:331527 _OverwriteHtmlReportsIndexFile()
Max Moroz7c5354f2018-05-06 00:03:481528 _CleanUpOutputDir()
Yuke Liaoea228d02018-01-05 19:10:331529
Max Moroz7c5354f2018-05-06 00:03:481530 html_index_file_path = 'file://' + os.path.abspath(_GetHtmlIndexPath())
Yuke Liao481d3482018-01-29 19:17:101531 logging.info('Index file for html report is generated as: %s',
1532 html_index_file_path)
Yuke Liao506e8822017-12-04 16:52:541533
Abhishek Arya1ec832c2017-12-05 18:06:591534
Yuke Liao506e8822017-12-04 16:52:541535if __name__ == '__main__':
1536 sys.exit(Main())