blob: 3eecc7755444943972c1203c1251786f66a1db34 [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
Yuke Liaoea228d02018-01-05 19:10:3356import json
Yuke Liao506e8822017-12-04 16:52:5457import os
58import subprocess
Yuke Liao506e8822017-12-04 16:52:5459import 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:5465import update as clang_update
66
Yuke Liaoea228d02018-01-05 19:10:3367sys.path.append(
68 os.path.join(
69 os.path.dirname(__file__), os.path.pardir, os.path.pardir,
70 'third_party'))
71import jinja2
72from collections import defaultdict
73
Yuke Liao506e8822017-12-04 16:52:5474# Absolute path to the root of the checkout.
Abhishek Arya1ec832c2017-12-05 18:06:5975SRC_ROOT_PATH = os.path.abspath(
76 os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir))
Yuke Liao506e8822017-12-04 16:52:5477
78# Absolute path to the code coverage tools binary.
79LLVM_BUILD_DIR = clang_update.LLVM_BUILD_DIR
80LLVM_COV_PATH = os.path.join(LLVM_BUILD_DIR, 'bin', 'llvm-cov')
81LLVM_PROFDATA_PATH = os.path.join(LLVM_BUILD_DIR, 'bin', 'llvm-profdata')
82
83# Build directory, the value is parsed from command line arguments.
84BUILD_DIR = None
85
86# Output directory for generated artifacts, the value is parsed from command
87# line arguemnts.
88OUTPUT_DIR = None
89
90# Default number of jobs used to build when goma is configured and enabled.
91DEFAULT_GOMA_JOBS = 100
92
93# Name of the file extension for profraw data files.
94PROFRAW_FILE_EXTENSION = 'profraw'
95
96# Name of the final profdata file, and this file needs to be passed to
97# "llvm-cov" command in order to call "llvm-cov show" to inspect the
98# line-by-line coverage of specific files.
99PROFDATA_FILE_NAME = 'coverage.profdata'
100
101# Build arg required for generating code coverage data.
102CLANG_COVERAGE_BUILD_ARG = 'use_clang_coverage'
103
104# A set of targets that depend on target "testing/gtest", this set is generated
105# by 'gn refs "testing/gtest"', and it is lazily initialized when needed.
106GTEST_TARGET_NAMES = None
107
Yuke Liaoea228d02018-01-05 19:10:33108# The default name of the html coverage report for a directory.
109DIRECTORY_COVERAGE_HTML_REPORT_NAME = os.extsep.join(['report', 'html'])
110
111
112class _CoverageSummary(object):
113 """Encapsulates coverage summary representation."""
114
115 def __init__(self, regions_total, regions_covered, functions_total,
116 functions_covered, lines_total, lines_covered):
117 """Initializes _CoverageSummary object."""
118 self._summary = {
119 'regions': {
120 'total': regions_total,
121 'covered': regions_covered
122 },
123 'functions': {
124 'total': functions_total,
125 'covered': functions_covered
126 },
127 'lines': {
128 'total': lines_total,
129 'covered': lines_covered
130 }
131 }
132
133 def Get(self):
134 """Returns summary as a dictionary."""
135 return self._summary
136
137 def AddSummary(self, other_summary):
138 """Adds another summary to this one element-wise."""
139 for feature in self._summary:
140 self._summary[feature]['total'] += other_summary.Get()[feature]['total']
141 self._summary[feature]['covered'] += other_summary.Get()[feature][
142 'covered']
143
144
145class _DirectoryCoverageReportHtmlGenerator(object):
146 """Encapsulates coverage html report generation for a directory.
147
148 The generated html has a table that contains links to the coverage report of
149 its sub-directories and files. Please refer to ./directory_example_report.html
150 for an example of the generated html file.
151 """
152
153 def __init__(self):
154 """Initializes _DirectoryCoverageReportHtmlGenerator object."""
155 css_file_name = os.extsep.join(['style', 'css'])
156 css_absolute_path = os.path.abspath(os.path.join(OUTPUT_DIR, css_file_name))
157 assert os.path.exists(css_absolute_path), (
158 'css file doesn\'t exit. Please make sure "llvm-cov show -format=html" '
159 'is called first, and the css file is generated at: "%s"' %
160 css_absolute_path)
161
162 self._css_absolute_path = css_absolute_path
163 self._table_entries = []
Yuke Liaod54030e2018-01-08 17:34:12164 self._total_entry = {}
Yuke Liaoea228d02018-01-05 19:10:33165 template_dir = os.path.join(
166 os.path.dirname(os.path.realpath(__file__)), 'html_templates')
167
168 jinja_env = jinja2.Environment(
169 loader=jinja2.FileSystemLoader(template_dir), trim_blocks=True)
170 self._header_template = jinja_env.get_template('header.html')
171 self._table_template = jinja_env.get_template('table.html')
172 self._footer_template = jinja_env.get_template('footer.html')
173
174 def AddLinkToAnotherReport(self, html_report_path, name, summary):
175 """Adds a link to another html report in this report.
176
177 The link to be added is assumed to be an entry in this directory.
178 """
Yuke Liaod54030e2018-01-08 17:34:12179 table_entry = self._CreateTableEntryFromCoverageSummary(
180 summary, html_report_path, name,
181 os.path.basename(html_report_path) ==
182 DIRECTORY_COVERAGE_HTML_REPORT_NAME)
183 self._table_entries.append(table_entry)
184
185 def CreateTotalsEntry(self, summary):
186 """Creates an entry corresponds to the 'TOTALS' row in the html report."""
187 self._total_entry = self._CreateTableEntryFromCoverageSummary(summary)
188
189 def _CreateTableEntryFromCoverageSummary(self,
190 summary,
191 href=None,
192 name=None,
193 is_dir=None):
194 """Creates an entry to display in the html report."""
195 entry = {}
Yuke Liaoea228d02018-01-05 19:10:33196 summary_dict = summary.Get()
Yuke Liaod54030e2018-01-08 17:34:12197 for feature in summary_dict:
Yuke Liaoea228d02018-01-05 19:10:33198 percentage = round((float(summary_dict[feature]['covered']
199 ) / summary_dict[feature]['total']) * 100, 2)
200 color_class = self._GetColorClass(percentage)
Yuke Liaod54030e2018-01-08 17:34:12201 entry[feature] = {
Yuke Liaoea228d02018-01-05 19:10:33202 'total': summary_dict[feature]['total'],
203 'covered': summary_dict[feature]['covered'],
204 'percentage': percentage,
205 'color_class': color_class
206 }
Yuke Liaod54030e2018-01-08 17:34:12207
208 if href != None:
209 entry['href'] = href
210 if name != None:
211 entry['name'] = name
212 if is_dir != None:
213 entry['is_dir'] = is_dir
214
215 return entry
Yuke Liaoea228d02018-01-05 19:10:33216
217 def _GetColorClass(self, percentage):
218 """Returns the css color class based on coverage percentage."""
219 if percentage >= 0 and percentage < 80:
220 return 'red'
221 if percentage >= 80 and percentage < 100:
222 return 'yellow'
223 if percentage == 100:
224 return 'green'
225
226 assert False, 'Invalid coverage percentage: "%d"' % percentage
227
228 def WriteHtmlCoverageReport(self, output_path):
229 """Write html coverage report for the directory.
230
231 In the report, sub-directories are displayed before files and within each
232 category, entries are sorted alphabetically.
233
234 Args:
235 output_path: A path to the html report.
236 """
237
238 def EntryCmp(left, right):
239 """Compare function for table entries."""
240 if left['is_dir'] != right['is_dir']:
241 return -1 if left['is_dir'] == True else 1
242
243 return left['name'] < right['name']
244
245 self._table_entries = sorted(self._table_entries, cmp=EntryCmp)
246
247 css_path = os.path.join(OUTPUT_DIR, os.extsep.join(['style', 'css']))
248 html_header = self._header_template.render(
249 css_path=os.path.relpath(css_path, os.path.dirname(output_path)))
Yuke Liaod54030e2018-01-08 17:34:12250 html_table = self._table_template.render(
251 entries=self._table_entries, total_entry=self._total_entry)
Yuke Liaoea228d02018-01-05 19:10:33252 html_footer = self._footer_template.render()
253
254 with open(output_path, 'w') as html_file:
255 html_file.write(html_header + html_table + html_footer)
256
Yuke Liao506e8822017-12-04 16:52:54257
Abhishek Arya1ec832c2017-12-05 18:06:59258def _GetPlatform():
259 """Returns current running platform."""
260 if sys.platform == 'win32' or sys.platform == 'cygwin':
261 return 'win'
262 if sys.platform.startswith('linux'):
263 return 'linux'
264 else:
265 assert sys.platform == 'darwin'
266 return 'mac'
267
268
Yuke Liao506e8822017-12-04 16:52:54269# TODO(crbug.com/759794): remove this function once tools get included to
270# Clang bundle:
271# https://chromium-review.googlesource.com/c/chromium/src/+/688221
272def DownloadCoverageToolsIfNeeded():
273 """Temporary solution to download llvm-profdata and llvm-cov tools."""
Abhishek Arya1ec832c2017-12-05 18:06:59274
275 def _GetRevisionFromStampFile(stamp_file_path, platform):
Yuke Liao506e8822017-12-04 16:52:54276 """Returns a pair of revision number by reading the build stamp file.
277
278 Args:
279 stamp_file_path: A path the build stamp file created by
280 tools/clang/scripts/update.py.
281 Returns:
282 A pair of integers represeting the main and sub revision respectively.
283 """
284 if not os.path.exists(stamp_file_path):
285 return 0, 0
286
287 with open(stamp_file_path) as stamp_file:
Abhishek Arya1ec832c2017-12-05 18:06:59288 for stamp_file_line in stamp_file.readlines():
289 if ',' in stamp_file_line:
290 package_version, target_os = stamp_file_line.rstrip().split(',')
291 else:
292 package_version = stamp_file_line.rstrip()
293 target_os = ''
Yuke Liao506e8822017-12-04 16:52:54294
Abhishek Arya1ec832c2017-12-05 18:06:59295 if target_os and platform != target_os:
296 continue
297
298 clang_revision_str, clang_sub_revision_str = package_version.split('-')
299 return int(clang_revision_str), int(clang_sub_revision_str)
300
301 assert False, 'Coverage is only supported on target_os - linux, mac.'
302
303 platform = _GetPlatform()
Yuke Liao506e8822017-12-04 16:52:54304 clang_revision, clang_sub_revision = _GetRevisionFromStampFile(
Abhishek Arya1ec832c2017-12-05 18:06:59305 clang_update.STAMP_FILE, platform)
Yuke Liao506e8822017-12-04 16:52:54306
307 coverage_revision_stamp_file = os.path.join(
308 os.path.dirname(clang_update.STAMP_FILE), 'cr_coverage_revision')
309 coverage_revision, coverage_sub_revision = _GetRevisionFromStampFile(
Abhishek Arya1ec832c2017-12-05 18:06:59310 coverage_revision_stamp_file, platform)
Yuke Liao506e8822017-12-04 16:52:54311
Yuke Liaoea228d02018-01-05 19:10:33312 has_coverage_tools = (
313 os.path.exists(LLVM_COV_PATH) and os.path.exists(LLVM_PROFDATA_PATH))
Abhishek Arya16f059a2017-12-07 17:47:32314
Yuke Liaoea228d02018-01-05 19:10:33315 if (has_coverage_tools and coverage_revision == clang_revision and
Yuke Liao506e8822017-12-04 16:52:54316 coverage_sub_revision == clang_sub_revision):
317 # LLVM coverage tools are up to date, bail out.
318 return clang_revision
319
320 package_version = '%d-%d' % (clang_revision, clang_sub_revision)
321 coverage_tools_file = 'llvm-code-coverage-%s.tgz' % package_version
322
323 # The code bellow follows the code from tools/clang/scripts/update.py.
Abhishek Arya1ec832c2017-12-05 18:06:59324 if platform == 'mac':
Yuke Liao506e8822017-12-04 16:52:54325 coverage_tools_url = clang_update.CDS_URL + '/Mac/' + coverage_tools_file
326 else:
Abhishek Arya1ec832c2017-12-05 18:06:59327 assert platform == 'linux'
Yuke Liao506e8822017-12-04 16:52:54328 coverage_tools_url = (
329 clang_update.CDS_URL + '/Linux_x64/' + coverage_tools_file)
330
331 try:
332 clang_update.DownloadAndUnpack(coverage_tools_url,
333 clang_update.LLVM_BUILD_DIR)
334 print('Coverage tools %s unpacked' % package_version)
335 with open(coverage_revision_stamp_file, 'w') as file_handle:
Abhishek Arya1ec832c2017-12-05 18:06:59336 file_handle.write('%s,%s' % (package_version, platform))
Yuke Liao506e8822017-12-04 16:52:54337 file_handle.write('\n')
338 except urllib2.URLError:
339 raise Exception(
340 'Failed to download coverage tools: %s.' % coverage_tools_url)
341
342
Yuke Liao66da1732017-12-05 22:19:42343def _GenerateLineByLineFileCoverageInHtml(binary_paths, profdata_file_path,
344 filters):
Yuke Liao506e8822017-12-04 16:52:54345 """Generates per file line-by-line coverage in html using 'llvm-cov show'.
346
347 For a file with absolute path /a/b/x.cc, a html report is generated as:
348 OUTPUT_DIR/coverage/a/b/x.cc.html. An index html file is also generated as:
349 OUTPUT_DIR/index.html.
350
351 Args:
352 binary_paths: A list of paths to the instrumented binaries.
353 profdata_file_path: A path to the profdata file.
Yuke Liao66da1732017-12-05 22:19:42354 filters: A list of directories and files to get coverage for.
Yuke Liao506e8822017-12-04 16:52:54355 """
Yuke Liao506e8822017-12-04 16:52:54356 # llvm-cov show [options] -instr-profile PROFILE BIN [-object BIN,...]
357 # [[-object BIN]] [SOURCES]
358 # NOTE: For object files, the first one is specified as a positional argument,
359 # and the rest are specified as keyword argument.
Abhishek Arya1ec832c2017-12-05 18:06:59360 subprocess_cmd = [
361 LLVM_COV_PATH, 'show', '-format=html',
362 '-output-dir={}'.format(OUTPUT_DIR),
363 '-instr-profile={}'.format(profdata_file_path), binary_paths[0]
364 ]
365 subprocess_cmd.extend(
366 ['-object=' + binary_path for binary_path in binary_paths[1:]])
Yuke Liao66da1732017-12-05 22:19:42367 subprocess_cmd.extend(filters)
Yuke Liao506e8822017-12-04 16:52:54368
369 subprocess.check_call(subprocess_cmd)
370
371
Yuke Liaoea228d02018-01-05 19:10:33372def _GeneratePerDirectoryCoverageInHtml(binary_paths, profdata_file_path,
373 filters):
374 """Generates coverage breakdown per directory."""
375 per_file_coverage_summary = _GeneratePerFileCoverageSummary(
376 binary_paths, profdata_file_path, filters)
377
378 per_directory_coverage_summary = defaultdict(
379 lambda: _CoverageSummary(0, 0, 0, 0, 0, 0))
380
381 # Calculate per directory code coverage summaries.
382 for file_path in per_file_coverage_summary:
383 summary = per_file_coverage_summary[file_path]
384 parent_dir = os.path.dirname(file_path)
385 while True:
386 per_directory_coverage_summary[parent_dir].AddSummary(summary)
387
388 if parent_dir == SRC_ROOT_PATH:
389 break
390 parent_dir = os.path.dirname(parent_dir)
391
392 for dir_path in per_directory_coverage_summary:
393 _GenerateCoverageInHtmlForDirectory(
394 dir_path, per_directory_coverage_summary, per_file_coverage_summary)
395
396
397def _GenerateCoverageInHtmlForDirectory(
398 dir_path, per_directory_coverage_summary, per_file_coverage_summary):
399 """Generates coverage html report for a single directory."""
400 html_generator = _DirectoryCoverageReportHtmlGenerator()
401
402 for entry_name in os.listdir(dir_path):
403 entry_path = os.path.normpath(os.path.join(dir_path, entry_name))
404 entry_html_report_path = _GetCoverageHtmlReportPath(entry_path)
405
406 # Use relative paths instead of absolute paths to make the generated
407 # reports portable.
408 html_report_path = _GetCoverageHtmlReportPath(dir_path)
409 entry_html_report_relative_path = os.path.relpath(
410 entry_html_report_path, os.path.dirname(html_report_path))
411
412 if entry_path in per_directory_coverage_summary:
413 html_generator.AddLinkToAnotherReport(
414 entry_html_report_relative_path, os.path.basename(entry_path),
415 per_directory_coverage_summary[entry_path])
416 elif entry_path in per_file_coverage_summary:
417 html_generator.AddLinkToAnotherReport(
418 entry_html_report_relative_path, os.path.basename(entry_path),
419 per_file_coverage_summary[entry_path])
420
Yuke Liaod54030e2018-01-08 17:34:12421 html_generator.CreateTotalsEntry(per_directory_coverage_summary[dir_path])
Yuke Liaoea228d02018-01-05 19:10:33422 html_generator.WriteHtmlCoverageReport(html_report_path)
423
424
425def _OverwriteHtmlReportsIndexFile():
426 """Overwrites the index file to link to the source root directory report."""
427 html_index_file_path = os.path.join(OUTPUT_DIR,
428 os.extsep.join(['index', 'html']))
429 src_root_html_report_path = _GetCoverageHtmlReportPath(SRC_ROOT_PATH)
430 src_root_html_report_relative_path = os.path.relpath(
431 src_root_html_report_path, os.path.dirname(html_index_file_path))
432 content = ("""
433 <!DOCTYPE html>
434 <html>
435 <head>
436 <!-- HTML meta refresh URL redirection -->
437 <meta http-equiv="refresh" content="0; url=%s">
438 </head>
439 </html>""" % src_root_html_report_relative_path)
440 with open(html_index_file_path, 'w') as f:
441 f.write(content)
442
443
444def _GetCoverageHtmlReportPath(file_or_dir_path):
445 """Given a file or directory, returns the corresponding html report path."""
446 html_path = (
447 os.path.join(os.path.abspath(OUTPUT_DIR), 'coverage') +
448 os.path.abspath(file_or_dir_path))
449 if os.path.isdir(file_or_dir_path):
450 return os.path.join(html_path, DIRECTORY_COVERAGE_HTML_REPORT_NAME)
451 else:
452 return os.extsep.join([html_path, 'html'])
453
454
Yuke Liao506e8822017-12-04 16:52:54455def _CreateCoverageProfileDataForTargets(targets, commands, jobs_count=None):
456 """Builds and runs target to generate the coverage profile data.
457
458 Args:
459 targets: A list of targets to build with coverage instrumentation.
460 commands: A list of commands used to run the targets.
461 jobs_count: Number of jobs to run in parallel for building. If None, a
462 default value is derived based on CPUs availability.
463
464 Returns:
465 A relative path to the generated profdata file.
466 """
467 _BuildTargets(targets, jobs_count)
Abhishek Arya1ec832c2017-12-05 18:06:59468 profraw_file_paths = _GetProfileRawDataPathsByExecutingCommands(
469 targets, commands)
Yuke Liao506e8822017-12-04 16:52:54470 profdata_file_path = _CreateCoverageProfileDataFromProfRawData(
471 profraw_file_paths)
472
Yuke Liaod4a9865202018-01-12 23:17:52473 for profraw_file_path in profraw_file_paths:
474 os.remove(profraw_file_path)
475
Yuke Liao506e8822017-12-04 16:52:54476 return profdata_file_path
477
478
479def _BuildTargets(targets, jobs_count):
480 """Builds target with Clang coverage instrumentation.
481
482 This function requires current working directory to be the root of checkout.
483
484 Args:
485 targets: A list of targets to build with coverage instrumentation.
486 jobs_count: Number of jobs to run in parallel for compilation. If None, a
487 default value is derived based on CPUs availability.
Yuke Liao506e8822017-12-04 16:52:54488 """
Abhishek Arya1ec832c2017-12-05 18:06:59489
Yuke Liao506e8822017-12-04 16:52:54490 def _IsGomaConfigured():
491 """Returns True if goma is enabled in the gn build args.
492
493 Returns:
494 A boolean indicates whether goma is configured for building or not.
495 """
496 build_args = _ParseArgsGnFile()
497 return 'use_goma' in build_args and build_args['use_goma'] == 'true'
498
499 print('Building %s' % str(targets))
500
501 if jobs_count is None and _IsGomaConfigured():
502 jobs_count = DEFAULT_GOMA_JOBS
503
504 subprocess_cmd = ['ninja', '-C', BUILD_DIR]
505 if jobs_count is not None:
506 subprocess_cmd.append('-j' + str(jobs_count))
507
508 subprocess_cmd.extend(targets)
509 subprocess.check_call(subprocess_cmd)
510
511
512def _GetProfileRawDataPathsByExecutingCommands(targets, commands):
513 """Runs commands and returns the relative paths to the profraw data files.
514
515 Args:
516 targets: A list of targets built with coverage instrumentation.
517 commands: A list of commands used to run the targets.
518
519 Returns:
520 A list of relative paths to the generated profraw data files.
521 """
522 # Remove existing profraw data files.
523 for file_or_dir in os.listdir(OUTPUT_DIR):
524 if file_or_dir.endswith(PROFRAW_FILE_EXTENSION):
525 os.remove(os.path.join(OUTPUT_DIR, file_or_dir))
526
Yuke Liaod4a9865202018-01-12 23:17:52527 # Run all test targets to generate profraw data files.
Yuke Liao506e8822017-12-04 16:52:54528 for target, command in zip(targets, commands):
Yuke Liaod4a9865202018-01-12 23:17:52529 _ExecuteCommand(target, command)
Yuke Liao506e8822017-12-04 16:52:54530
531 profraw_file_paths = []
532 for file_or_dir in os.listdir(OUTPUT_DIR):
533 if file_or_dir.endswith(PROFRAW_FILE_EXTENSION):
534 profraw_file_paths.append(os.path.join(OUTPUT_DIR, file_or_dir))
535
536 # Assert one target/command generates at least one profraw data file.
537 for target in targets:
Abhishek Arya1ec832c2017-12-05 18:06:59538 assert any(
539 os.path.basename(profraw_file).startswith(target)
540 for profraw_file in profraw_file_paths), (
541 'Running target: %s failed to generate any profraw data file, '
542 'please make sure the binary exists and is properly instrumented.' %
543 target)
Yuke Liao506e8822017-12-04 16:52:54544
545 return profraw_file_paths
546
547
548def _ExecuteCommand(target, command):
549 """Runs a single command and generates a profraw data file.
550
551 Args:
552 target: A target built with coverage instrumentation.
553 command: A command used to run the target.
554 """
Yuke Liaod4a9865202018-01-12 23:17:52555 # Per Clang "Source-based Code Coverage" doc:
556 # "%Nm" expands out to the instrumented binary's signature. When this pattern
557 # is specified, the runtime creates a pool of N raw profiles which are used
558 # for on-line profile merging. The runtime takes care of selecting a raw
559 # profile from the pool, locking it, and updating it before the program exits.
560 # If N is not specified (i.e the pattern is "%m"), it's assumed that N = 1.
561 # N must be between 1 and 9. The merge pool specifier can only occur once per
562 # filename pattern.
563 #
564 # 4 is chosen because it creates some level of parallelism, but it's not too
565 # big to consume too much computing resource or disk space.
Abhishek Arya1ec832c2017-12-05 18:06:59566 expected_profraw_file_name = os.extsep.join(
Yuke Liaod4a9865202018-01-12 23:17:52567 [target, '%4m', PROFRAW_FILE_EXTENSION])
Yuke Liao506e8822017-12-04 16:52:54568 expected_profraw_file_path = os.path.join(OUTPUT_DIR,
569 expected_profraw_file_name)
570 output_file_name = os.extsep.join([target + '_output', 'txt'])
571 output_file_path = os.path.join(OUTPUT_DIR, output_file_name)
572
573 print('Running command: "%s", the output is redirected to "%s"' %
574 (command, output_file_path))
Abhishek Arya1ec832c2017-12-05 18:06:59575 output = subprocess.check_output(
576 command.split(), env={
577 'LLVM_PROFILE_FILE': expected_profraw_file_path
578 })
Yuke Liao506e8822017-12-04 16:52:54579 with open(output_file_path, 'w') as output_file:
580 output_file.write(output)
581
582
583def _CreateCoverageProfileDataFromProfRawData(profraw_file_paths):
584 """Returns a relative path to the profdata file by merging profraw data files.
585
586 Args:
587 profraw_file_paths: A list of relative paths to the profraw data files that
588 are to be merged.
589
590 Returns:
591 A relative path to the generated profdata file.
592
593 Raises:
594 CalledProcessError: An error occurred merging profraw data files.
595 """
596 print('Creating the profile data file')
597
598 profdata_file_path = os.path.join(OUTPUT_DIR, PROFDATA_FILE_NAME)
Abhishek Arya16f059a2017-12-07 17:47:32599
Yuke Liao506e8822017-12-04 16:52:54600 try:
Abhishek Arya1ec832c2017-12-05 18:06:59601 subprocess_cmd = [
602 LLVM_PROFDATA_PATH, 'merge', '-o', profdata_file_path, '-sparse=true'
603 ]
Yuke Liao506e8822017-12-04 16:52:54604 subprocess_cmd.extend(profraw_file_paths)
605 subprocess.check_call(subprocess_cmd)
606 except subprocess.CalledProcessError as error:
607 print('Failed to merge profraw files to create profdata file')
608 raise error
609
610 return profdata_file_path
611
612
Yuke Liaoea228d02018-01-05 19:10:33613def _GeneratePerFileCoverageSummary(binary_paths, profdata_file_path, filters):
614 """Generates per file coverage summary using "llvm-cov export" command."""
615 # llvm-cov export [options] -instr-profile PROFILE BIN [-object BIN,...]
616 # [[-object BIN]] [SOURCES].
617 # NOTE: For object files, the first one is specified as a positional argument,
618 # and the rest are specified as keyword argument.
619 subprocess_cmd = [
620 LLVM_COV_PATH, 'export', '-summary-only',
621 '-instr-profile=' + profdata_file_path, binary_paths[0]
622 ]
623 subprocess_cmd.extend(
624 ['-object=' + binary_path for binary_path in binary_paths[1:]])
625 subprocess_cmd.extend(filters)
626
627 json_output = json.loads(subprocess.check_output(subprocess_cmd))
628 assert len(json_output['data']) == 1
629 files_coverage_data = json_output['data'][0]['files']
630
631 per_file_coverage_summary = {}
632 for file_coverage_data in files_coverage_data:
633 file_path = file_coverage_data['filename']
634 summary = file_coverage_data['summary']
635
636 # TODO(crbug.com/797345): Currently, [SOURCES] parameter doesn't apply to
637 # llvm-cov export command, so work it around by manually filter the paths.
638 # Remove this logic once the bug is fixed and clang has rolled past it.
639 if filters and not any(
640 os.path.abspath(file_path).startswith(os.path.abspath(filter))
641 for filter in filters):
642 continue
643
644 if summary['lines']['count'] == 0:
645 continue
646
647 per_file_coverage_summary[file_path] = _CoverageSummary(
648 regions_total=summary['regions']['count'],
649 regions_covered=summary['regions']['covered'],
650 functions_total=summary['functions']['count'],
651 functions_covered=summary['functions']['covered'],
652 lines_total=summary['lines']['count'],
653 lines_covered=summary['lines']['covered'])
654
655 return per_file_coverage_summary
656
657
Yuke Liao506e8822017-12-04 16:52:54658def _GetBinaryPath(command):
659 """Returns a relative path to the binary to be run by the command.
660
661 Args:
662 command: A command used to run a target.
663
664 Returns:
665 A relative path to the binary.
666 """
667 return command.split()[0]
668
669
Yuke Liao95d13d72017-12-07 18:18:50670def _VerifyTargetExecutablesAreInBuildDirectory(commands):
671 """Verifies that the target executables specified in the commands are inside
672 the given build directory."""
Yuke Liao506e8822017-12-04 16:52:54673 for command in commands:
674 binary_path = _GetBinaryPath(command)
Yuke Liao95d13d72017-12-07 18:18:50675 binary_absolute_path = os.path.abspath(os.path.normpath(binary_path))
676 assert binary_absolute_path.startswith(os.path.abspath(BUILD_DIR)), (
677 'Target executable "%s" in command: "%s" is outside of '
678 'the given build directory: "%s".' % (binary_path, command, BUILD_DIR))
Yuke Liao506e8822017-12-04 16:52:54679
680
681def _ValidateBuildingWithClangCoverage():
682 """Asserts that targets are built with Clang coverage enabled."""
683 build_args = _ParseArgsGnFile()
684
685 if (CLANG_COVERAGE_BUILD_ARG not in build_args or
686 build_args[CLANG_COVERAGE_BUILD_ARG] != 'true'):
Abhishek Arya1ec832c2017-12-05 18:06:59687 assert False, ('\'{} = true\' is required in args.gn.'
688 ).format(CLANG_COVERAGE_BUILD_ARG)
Yuke Liao506e8822017-12-04 16:52:54689
690
691def _ParseArgsGnFile():
692 """Parses args.gn file and returns results as a dictionary.
693
694 Returns:
695 A dictionary representing the build args.
696 """
697 build_args_path = os.path.join(BUILD_DIR, 'args.gn')
698 assert os.path.exists(build_args_path), ('"%s" is not a build directory, '
699 'missing args.gn file.' % BUILD_DIR)
700 with open(build_args_path) as build_args_file:
701 build_args_lines = build_args_file.readlines()
702
703 build_args = {}
704 for build_arg_line in build_args_lines:
705 build_arg_without_comments = build_arg_line.split('#')[0]
706 key_value_pair = build_arg_without_comments.split('=')
707 if len(key_value_pair) != 2:
708 continue
709
710 key = key_value_pair[0].strip()
711 value = key_value_pair[1].strip()
712 build_args[key] = value
713
714 return build_args
715
716
Abhishek Arya16f059a2017-12-07 17:47:32717def _VerifyPathsAndReturnAbsolutes(paths):
718 """Verifies that the paths specified in |paths| exist and returns absolute
719 versions.
Yuke Liao66da1732017-12-05 22:19:42720
721 Args:
722 paths: A list of files or directories.
723 """
Abhishek Arya16f059a2017-12-07 17:47:32724 absolute_paths = []
Yuke Liao66da1732017-12-05 22:19:42725 for path in paths:
Abhishek Arya16f059a2017-12-07 17:47:32726 absolute_path = os.path.join(SRC_ROOT_PATH, path)
727 assert os.path.exists(absolute_path), ('Path: "%s" doesn\'t exist.' % path)
728
729 absolute_paths.append(absolute_path)
730
731 return absolute_paths
Yuke Liao66da1732017-12-05 22:19:42732
733
Yuke Liao506e8822017-12-04 16:52:54734def _ParseCommandArguments():
735 """Adds and parses relevant arguments for tool comands.
736
737 Returns:
738 A dictionary representing the arguments.
739 """
740 arg_parser = argparse.ArgumentParser()
741 arg_parser.usage = __doc__
742
Abhishek Arya1ec832c2017-12-05 18:06:59743 arg_parser.add_argument(
744 '-b',
745 '--build-dir',
746 type=str,
747 required=True,
748 help='The build directory, the path needs to be relative to the root of '
749 'the checkout.')
Yuke Liao506e8822017-12-04 16:52:54750
Abhishek Arya1ec832c2017-12-05 18:06:59751 arg_parser.add_argument(
752 '-o',
753 '--output-dir',
754 type=str,
755 required=True,
756 help='Output directory for generated artifacts.')
Yuke Liao506e8822017-12-04 16:52:54757
Abhishek Arya1ec832c2017-12-05 18:06:59758 arg_parser.add_argument(
759 '-c',
760 '--command',
761 action='append',
762 required=True,
763 help='Commands used to run test targets, one test target needs one and '
764 'only one command, when specifying commands, one should assume the '
765 'current working directory is the root of the checkout.')
Yuke Liao506e8822017-12-04 16:52:54766
Abhishek Arya1ec832c2017-12-05 18:06:59767 arg_parser.add_argument(
Yuke Liao66da1732017-12-05 22:19:42768 '-f',
769 '--filters',
770 action='append',
Abhishek Arya16f059a2017-12-07 17:47:32771 required=False,
Yuke Liao66da1732017-12-05 22:19:42772 help='Directories or files to get code coverage for, and all files under '
773 'the directories are included recursively.')
774
775 arg_parser.add_argument(
Abhishek Arya1ec832c2017-12-05 18:06:59776 '-j',
777 '--jobs',
778 type=int,
779 default=None,
780 help='Run N jobs to build in parallel. If not specified, a default value '
781 'will be derived based on CPUs availability. Please refer to '
782 '\'ninja -h\' for more details.')
Yuke Liao506e8822017-12-04 16:52:54783
Abhishek Arya1ec832c2017-12-05 18:06:59784 arg_parser.add_argument(
785 'targets', nargs='+', help='The names of the test targets to run.')
Yuke Liao506e8822017-12-04 16:52:54786
787 args = arg_parser.parse_args()
788 return args
789
790
791def Main():
792 """Execute tool commands."""
Abhishek Arya1ec832c2017-12-05 18:06:59793 assert _GetPlatform() in ['linux', 'mac'], (
794 'Coverage is only supported on linux and mac platforms.')
Yuke Liao506e8822017-12-04 16:52:54795 assert os.path.abspath(os.getcwd()) == SRC_ROOT_PATH, ('This script must be '
796 'called from the root '
Abhishek Arya1ec832c2017-12-05 18:06:59797 'of checkout.')
Yuke Liao506e8822017-12-04 16:52:54798 DownloadCoverageToolsIfNeeded()
799
800 args = _ParseCommandArguments()
801 global BUILD_DIR
802 BUILD_DIR = args.build_dir
803 global OUTPUT_DIR
804 OUTPUT_DIR = args.output_dir
805
806 assert len(args.targets) == len(args.command), ('Number of targets must be '
807 'equal to the number of test '
808 'commands.')
Abhishek Arya1ec832c2017-12-05 18:06:59809 assert os.path.exists(BUILD_DIR), (
810 'Build directory: {} doesn\'t exist. '
811 'Please run "gn gen" to generate.').format(BUILD_DIR)
Yuke Liao506e8822017-12-04 16:52:54812 _ValidateBuildingWithClangCoverage()
Yuke Liao95d13d72017-12-07 18:18:50813 _VerifyTargetExecutablesAreInBuildDirectory(args.command)
Abhishek Arya16f059a2017-12-07 17:47:32814
815 absolute_filter_paths = []
Yuke Liao66da1732017-12-05 22:19:42816 if args.filters:
Abhishek Arya16f059a2017-12-07 17:47:32817 absolute_filter_paths = _VerifyPathsAndReturnAbsolutes(args.filters)
Yuke Liao66da1732017-12-05 22:19:42818
Yuke Liao506e8822017-12-04 16:52:54819 if not os.path.exists(OUTPUT_DIR):
820 os.makedirs(OUTPUT_DIR)
821
Abhishek Arya1ec832c2017-12-05 18:06:59822 profdata_file_path = _CreateCoverageProfileDataForTargets(
823 args.targets, args.command, args.jobs)
Yuke Liao506e8822017-12-04 16:52:54824 binary_paths = [_GetBinaryPath(command) for command in args.command]
Yuke Liaoea228d02018-01-05 19:10:33825
826 print('Generating code coverage report in html (this can take a while '
827 'depending on size of target!)')
Yuke Liao66da1732017-12-05 22:19:42828 _GenerateLineByLineFileCoverageInHtml(binary_paths, profdata_file_path,
Abhishek Arya16f059a2017-12-07 17:47:32829 absolute_filter_paths)
Yuke Liaoea228d02018-01-05 19:10:33830 _GeneratePerDirectoryCoverageInHtml(binary_paths, profdata_file_path,
831 absolute_filter_paths)
832
833 # The default index file is generated only for the list of source files, needs
834 # to overwrite it to display per directory code coverage breakdown.
835 _OverwriteHtmlReportsIndexFile()
836
Yuke Liao506e8822017-12-04 16:52:54837 html_index_file_path = 'file://' + os.path.abspath(
838 os.path.join(OUTPUT_DIR, 'index.html'))
839 print('\nCode coverage profile data is created as: %s' % profdata_file_path)
Abhishek Arya16f059a2017-12-07 17:47:32840 print('Index file for html report is generated as: %s' % html_index_file_path)
Yuke Liao506e8822017-12-04 16:52:54841
Abhishek Arya1ec832c2017-12-05 18:06:59842
Yuke Liao506e8822017-12-04 16:52:54843if __name__ == '__main__':
844 sys.exit(Main())