Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 1 | #!/usr/bin/python |
| 2 | # Copyright 2017 The Chromium Authors. All rights reserved. |
| 3 | # Use of this source code is governed by a BSD-style license that can be |
| 4 | # found in the LICENSE file. |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 5 | """This script helps to generate code coverage report. |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 6 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 7 | It uses Clang Source-based Code Coverage - |
| 8 | https://clang.llvm.org/docs/SourceBasedCodeCoverage.html |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 9 | |
Abhishek Arya | 16f059a | 2017-12-07 17:47:32 | [diff] [blame] | 10 | In order to generate code coverage report, you need to first add |
| 11 | "use_clang_coverage=true" GN flag to args.gn file in your build |
| 12 | output directory (e.g. out/coverage). |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 13 | |
Abhishek Arya | 16f059a | 2017-12-07 17:47:32 | [diff] [blame] | 14 | It is recommended to add "is_component_build=false" flag as well because: |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 15 | 1. It is incompatible with other sanitizer flags (like "is_asan", "is_msan") |
| 16 | and others like "optimize_for_fuzzing". |
| 17 | 2. If it is not set explicitly, "is_debug" overrides it to true. |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 18 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 19 | Example usage: |
| 20 | |
Abhishek Arya | 16f059a | 2017-12-07 17:47:32 | [diff] [blame] | 21 | gn gen out/coverage --args='use_clang_coverage=true is_component_build=false' |
| 22 | gclient runhooks |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 23 | python tools/code_coverage/coverage.py crypto_unittests url_unittests \\ |
Abhishek Arya | 16f059a | 2017-12-07 17:47:32 | [diff] [blame] | 24 | -b out/coverage -o out/report -c 'out/coverage/crypto_unittests' \\ |
| 25 | -c 'out/coverage/url_unittests --gtest_filter=URLParser.PathURL' \\ |
| 26 | -f url/ -f crypto/ |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 27 | |
Abhishek Arya | 16f059a | 2017-12-07 17:47:32 | [diff] [blame] | 28 | The command above builds crypto_unittests and url_unittests targets and then |
| 29 | runs them with specified command line arguments. For url_unittests, it only |
| 30 | runs the test URLParser.PathURL. The coverage report is filtered to include |
| 31 | only files and sub-directories under url/ and crypto/ directories. |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 32 | |
| 33 | If you are building a fuzz target, you need to add "use_libfuzzer=true" GN |
| 34 | flag as well. |
| 35 | |
| 36 | Sample workflow for a fuzz target (e.g. pdfium_fuzzer): |
| 37 | |
Abhishek Arya | 16f059a | 2017-12-07 17:47:32 | [diff] [blame] | 38 | python tools/code_coverage/coverage.py pdfium_fuzzer \\ |
| 39 | -b out/coverage -o out/report \\ |
| 40 | -c 'out/coverage/pdfium_fuzzer -runs=<runs> <corpus_dir>' \\ |
| 41 | -f third_party/pdfium |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 42 | |
| 43 | where: |
| 44 | <corpus_dir> - directory containing samples files for this format. |
| 45 | <runs> - number of times to fuzz target function. Should be 0 when you just |
| 46 | want to see the coverage on corpus and don't want to fuzz at all. |
| 47 | |
| 48 | For more options, please refer to tools/code_coverage/coverage.py -h. |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 49 | """ |
| 50 | |
| 51 | from __future__ import print_function |
| 52 | |
| 53 | import sys |
| 54 | |
| 55 | import argparse |
Yuke Liao | ea228d0 | 2018-01-05 19:10:33 | [diff] [blame] | 56 | import json |
Yuke Liao | 481d348 | 2018-01-29 19:17:10 | [diff] [blame^] | 57 | import logging |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 58 | import os |
| 59 | import subprocess |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 60 | import urllib2 |
| 61 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 62 | sys.path.append( |
| 63 | os.path.join( |
| 64 | os.path.dirname(__file__), os.path.pardir, os.path.pardir, 'tools', |
| 65 | 'clang', 'scripts')) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 66 | import update as clang_update |
| 67 | |
Yuke Liao | ea228d0 | 2018-01-05 19:10:33 | [diff] [blame] | 68 | sys.path.append( |
| 69 | os.path.join( |
| 70 | os.path.dirname(__file__), os.path.pardir, os.path.pardir, |
| 71 | 'third_party')) |
| 72 | import jinja2 |
| 73 | from collections import defaultdict |
| 74 | |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 75 | # Absolute path to the root of the checkout. |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 76 | SRC_ROOT_PATH = os.path.abspath( |
| 77 | os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir)) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 78 | |
| 79 | # Absolute path to the code coverage tools binary. |
| 80 | LLVM_BUILD_DIR = clang_update.LLVM_BUILD_DIR |
| 81 | LLVM_COV_PATH = os.path.join(LLVM_BUILD_DIR, 'bin', 'llvm-cov') |
| 82 | LLVM_PROFDATA_PATH = os.path.join(LLVM_BUILD_DIR, 'bin', 'llvm-profdata') |
| 83 | |
| 84 | # Build directory, the value is parsed from command line arguments. |
| 85 | BUILD_DIR = None |
| 86 | |
| 87 | # Output directory for generated artifacts, the value is parsed from command |
| 88 | # line arguemnts. |
| 89 | OUTPUT_DIR = None |
| 90 | |
| 91 | # Default number of jobs used to build when goma is configured and enabled. |
| 92 | DEFAULT_GOMA_JOBS = 100 |
| 93 | |
| 94 | # Name of the file extension for profraw data files. |
| 95 | PROFRAW_FILE_EXTENSION = 'profraw' |
| 96 | |
| 97 | # Name of the final profdata file, and this file needs to be passed to |
| 98 | # "llvm-cov" command in order to call "llvm-cov show" to inspect the |
| 99 | # line-by-line coverage of specific files. |
| 100 | PROFDATA_FILE_NAME = 'coverage.profdata' |
| 101 | |
| 102 | # Build arg required for generating code coverage data. |
| 103 | CLANG_COVERAGE_BUILD_ARG = 'use_clang_coverage' |
| 104 | |
| 105 | # A set of targets that depend on target "testing/gtest", this set is generated |
| 106 | # by 'gn refs "testing/gtest"', and it is lazily initialized when needed. |
| 107 | GTEST_TARGET_NAMES = None |
| 108 | |
Yuke Liao | ea228d0 | 2018-01-05 19:10:33 | [diff] [blame] | 109 | # The default name of the html coverage report for a directory. |
| 110 | DIRECTORY_COVERAGE_HTML_REPORT_NAME = os.extsep.join(['report', 'html']) |
| 111 | |
| 112 | |
| 113 | class _CoverageSummary(object): |
| 114 | """Encapsulates coverage summary representation.""" |
| 115 | |
| 116 | def __init__(self, regions_total, regions_covered, functions_total, |
| 117 | functions_covered, lines_total, lines_covered): |
| 118 | """Initializes _CoverageSummary object.""" |
| 119 | self._summary = { |
| 120 | 'regions': { |
| 121 | 'total': regions_total, |
| 122 | 'covered': regions_covered |
| 123 | }, |
| 124 | 'functions': { |
| 125 | 'total': functions_total, |
| 126 | 'covered': functions_covered |
| 127 | }, |
| 128 | 'lines': { |
| 129 | 'total': lines_total, |
| 130 | 'covered': lines_covered |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | def Get(self): |
| 135 | """Returns summary as a dictionary.""" |
| 136 | return self._summary |
| 137 | |
| 138 | def AddSummary(self, other_summary): |
| 139 | """Adds another summary to this one element-wise.""" |
| 140 | for feature in self._summary: |
| 141 | self._summary[feature]['total'] += other_summary.Get()[feature]['total'] |
| 142 | self._summary[feature]['covered'] += other_summary.Get()[feature][ |
| 143 | 'covered'] |
| 144 | |
| 145 | |
| 146 | class _DirectoryCoverageReportHtmlGenerator(object): |
| 147 | """Encapsulates coverage html report generation for a directory. |
| 148 | |
| 149 | The generated html has a table that contains links to the coverage report of |
| 150 | its sub-directories and files. Please refer to ./directory_example_report.html |
| 151 | for an example of the generated html file. |
| 152 | """ |
| 153 | |
| 154 | def __init__(self): |
| 155 | """Initializes _DirectoryCoverageReportHtmlGenerator object.""" |
| 156 | css_file_name = os.extsep.join(['style', 'css']) |
| 157 | css_absolute_path = os.path.abspath(os.path.join(OUTPUT_DIR, css_file_name)) |
| 158 | assert os.path.exists(css_absolute_path), ( |
| 159 | 'css file doesn\'t exit. Please make sure "llvm-cov show -format=html" ' |
| 160 | 'is called first, and the css file is generated at: "%s"' % |
| 161 | css_absolute_path) |
| 162 | |
| 163 | self._css_absolute_path = css_absolute_path |
| 164 | self._table_entries = [] |
Yuke Liao | d54030e | 2018-01-08 17:34:12 | [diff] [blame] | 165 | self._total_entry = {} |
Yuke Liao | ea228d0 | 2018-01-05 19:10:33 | [diff] [blame] | 166 | template_dir = os.path.join( |
| 167 | os.path.dirname(os.path.realpath(__file__)), 'html_templates') |
| 168 | |
| 169 | jinja_env = jinja2.Environment( |
| 170 | loader=jinja2.FileSystemLoader(template_dir), trim_blocks=True) |
| 171 | self._header_template = jinja_env.get_template('header.html') |
| 172 | self._table_template = jinja_env.get_template('table.html') |
| 173 | self._footer_template = jinja_env.get_template('footer.html') |
| 174 | |
| 175 | def AddLinkToAnotherReport(self, html_report_path, name, summary): |
| 176 | """Adds a link to another html report in this report. |
| 177 | |
| 178 | The link to be added is assumed to be an entry in this directory. |
| 179 | """ |
Yuke Liao | d54030e | 2018-01-08 17:34:12 | [diff] [blame] | 180 | table_entry = self._CreateTableEntryFromCoverageSummary( |
| 181 | summary, html_report_path, name, |
| 182 | os.path.basename(html_report_path) == |
| 183 | DIRECTORY_COVERAGE_HTML_REPORT_NAME) |
| 184 | self._table_entries.append(table_entry) |
| 185 | |
| 186 | def CreateTotalsEntry(self, summary): |
| 187 | """Creates an entry corresponds to the 'TOTALS' row in the html report.""" |
| 188 | self._total_entry = self._CreateTableEntryFromCoverageSummary(summary) |
| 189 | |
| 190 | def _CreateTableEntryFromCoverageSummary(self, |
| 191 | summary, |
| 192 | href=None, |
| 193 | name=None, |
| 194 | is_dir=None): |
| 195 | """Creates an entry to display in the html report.""" |
| 196 | entry = {} |
Yuke Liao | ea228d0 | 2018-01-05 19:10:33 | [diff] [blame] | 197 | summary_dict = summary.Get() |
Yuke Liao | d54030e | 2018-01-08 17:34:12 | [diff] [blame] | 198 | for feature in summary_dict: |
Yuke Liao | ea228d0 | 2018-01-05 19:10:33 | [diff] [blame] | 199 | percentage = round((float(summary_dict[feature]['covered'] |
| 200 | ) / summary_dict[feature]['total']) * 100, 2) |
| 201 | color_class = self._GetColorClass(percentage) |
Yuke Liao | d54030e | 2018-01-08 17:34:12 | [diff] [blame] | 202 | entry[feature] = { |
Yuke Liao | ea228d0 | 2018-01-05 19:10:33 | [diff] [blame] | 203 | 'total': summary_dict[feature]['total'], |
| 204 | 'covered': summary_dict[feature]['covered'], |
| 205 | 'percentage': percentage, |
| 206 | 'color_class': color_class |
| 207 | } |
Yuke Liao | d54030e | 2018-01-08 17:34:12 | [diff] [blame] | 208 | |
| 209 | if href != None: |
| 210 | entry['href'] = href |
| 211 | if name != None: |
| 212 | entry['name'] = name |
| 213 | if is_dir != None: |
| 214 | entry['is_dir'] = is_dir |
| 215 | |
| 216 | return entry |
Yuke Liao | ea228d0 | 2018-01-05 19:10:33 | [diff] [blame] | 217 | |
| 218 | def _GetColorClass(self, percentage): |
| 219 | """Returns the css color class based on coverage percentage.""" |
| 220 | if percentage >= 0 and percentage < 80: |
| 221 | return 'red' |
| 222 | if percentage >= 80 and percentage < 100: |
| 223 | return 'yellow' |
| 224 | if percentage == 100: |
| 225 | return 'green' |
| 226 | |
| 227 | assert False, 'Invalid coverage percentage: "%d"' % percentage |
| 228 | |
| 229 | def WriteHtmlCoverageReport(self, output_path): |
| 230 | """Write html coverage report for the directory. |
| 231 | |
| 232 | In the report, sub-directories are displayed before files and within each |
| 233 | category, entries are sorted alphabetically. |
| 234 | |
| 235 | Args: |
| 236 | output_path: A path to the html report. |
| 237 | """ |
| 238 | |
| 239 | def EntryCmp(left, right): |
| 240 | """Compare function for table entries.""" |
| 241 | if left['is_dir'] != right['is_dir']: |
| 242 | return -1 if left['is_dir'] == True else 1 |
| 243 | |
| 244 | return left['name'] < right['name'] |
| 245 | |
| 246 | self._table_entries = sorted(self._table_entries, cmp=EntryCmp) |
| 247 | |
| 248 | css_path = os.path.join(OUTPUT_DIR, os.extsep.join(['style', 'css'])) |
| 249 | html_header = self._header_template.render( |
| 250 | css_path=os.path.relpath(css_path, os.path.dirname(output_path))) |
Yuke Liao | d54030e | 2018-01-08 17:34:12 | [diff] [blame] | 251 | html_table = self._table_template.render( |
| 252 | entries=self._table_entries, total_entry=self._total_entry) |
Yuke Liao | ea228d0 | 2018-01-05 19:10:33 | [diff] [blame] | 253 | html_footer = self._footer_template.render() |
| 254 | |
| 255 | with open(output_path, 'w') as html_file: |
| 256 | html_file.write(html_header + html_table + html_footer) |
| 257 | |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 258 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 259 | def _GetPlatform(): |
| 260 | """Returns current running platform.""" |
| 261 | if sys.platform == 'win32' or sys.platform == 'cygwin': |
| 262 | return 'win' |
| 263 | if sys.platform.startswith('linux'): |
| 264 | return 'linux' |
| 265 | else: |
| 266 | assert sys.platform == 'darwin' |
| 267 | return 'mac' |
| 268 | |
| 269 | |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 270 | # TODO(crbug.com/759794): remove this function once tools get included to |
| 271 | # Clang bundle: |
| 272 | # https://chromium-review.googlesource.com/c/chromium/src/+/688221 |
| 273 | def DownloadCoverageToolsIfNeeded(): |
| 274 | """Temporary solution to download llvm-profdata and llvm-cov tools.""" |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 275 | |
| 276 | def _GetRevisionFromStampFile(stamp_file_path, platform): |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 277 | """Returns a pair of revision number by reading the build stamp file. |
| 278 | |
| 279 | Args: |
| 280 | stamp_file_path: A path the build stamp file created by |
| 281 | tools/clang/scripts/update.py. |
| 282 | Returns: |
| 283 | A pair of integers represeting the main and sub revision respectively. |
| 284 | """ |
| 285 | if not os.path.exists(stamp_file_path): |
| 286 | return 0, 0 |
| 287 | |
| 288 | with open(stamp_file_path) as stamp_file: |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 289 | for stamp_file_line in stamp_file.readlines(): |
| 290 | if ',' in stamp_file_line: |
| 291 | package_version, target_os = stamp_file_line.rstrip().split(',') |
| 292 | else: |
| 293 | package_version = stamp_file_line.rstrip() |
| 294 | target_os = '' |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 295 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 296 | if target_os and platform != target_os: |
| 297 | continue |
| 298 | |
| 299 | clang_revision_str, clang_sub_revision_str = package_version.split('-') |
| 300 | return int(clang_revision_str), int(clang_sub_revision_str) |
| 301 | |
| 302 | assert False, 'Coverage is only supported on target_os - linux, mac.' |
| 303 | |
| 304 | platform = _GetPlatform() |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 305 | clang_revision, clang_sub_revision = _GetRevisionFromStampFile( |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 306 | clang_update.STAMP_FILE, platform) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 307 | |
| 308 | coverage_revision_stamp_file = os.path.join( |
| 309 | os.path.dirname(clang_update.STAMP_FILE), 'cr_coverage_revision') |
| 310 | coverage_revision, coverage_sub_revision = _GetRevisionFromStampFile( |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 311 | coverage_revision_stamp_file, platform) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 312 | |
Yuke Liao | ea228d0 | 2018-01-05 19:10:33 | [diff] [blame] | 313 | has_coverage_tools = ( |
| 314 | os.path.exists(LLVM_COV_PATH) and os.path.exists(LLVM_PROFDATA_PATH)) |
Abhishek Arya | 16f059a | 2017-12-07 17:47:32 | [diff] [blame] | 315 | |
Yuke Liao | ea228d0 | 2018-01-05 19:10:33 | [diff] [blame] | 316 | if (has_coverage_tools and coverage_revision == clang_revision and |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 317 | coverage_sub_revision == clang_sub_revision): |
| 318 | # LLVM coverage tools are up to date, bail out. |
| 319 | return clang_revision |
| 320 | |
| 321 | package_version = '%d-%d' % (clang_revision, clang_sub_revision) |
| 322 | coverage_tools_file = 'llvm-code-coverage-%s.tgz' % package_version |
| 323 | |
| 324 | # The code bellow follows the code from tools/clang/scripts/update.py. |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 325 | if platform == 'mac': |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 326 | coverage_tools_url = clang_update.CDS_URL + '/Mac/' + coverage_tools_file |
| 327 | else: |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 328 | assert platform == 'linux' |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 329 | coverage_tools_url = ( |
| 330 | clang_update.CDS_URL + '/Linux_x64/' + coverage_tools_file) |
| 331 | |
| 332 | try: |
| 333 | clang_update.DownloadAndUnpack(coverage_tools_url, |
| 334 | clang_update.LLVM_BUILD_DIR) |
Yuke Liao | 481d348 | 2018-01-29 19:17:10 | [diff] [blame^] | 335 | logging.info('Coverage tools %s unpacked', package_version) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 336 | with open(coverage_revision_stamp_file, 'w') as file_handle: |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 337 | file_handle.write('%s,%s' % (package_version, platform)) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 338 | file_handle.write('\n') |
| 339 | except urllib2.URLError: |
| 340 | raise Exception( |
| 341 | 'Failed to download coverage tools: %s.' % coverage_tools_url) |
| 342 | |
| 343 | |
Yuke Liao | 66da173 | 2017-12-05 22:19:42 | [diff] [blame] | 344 | def _GenerateLineByLineFileCoverageInHtml(binary_paths, profdata_file_path, |
| 345 | filters): |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 346 | """Generates per file line-by-line coverage in html using 'llvm-cov show'. |
| 347 | |
| 348 | For a file with absolute path /a/b/x.cc, a html report is generated as: |
| 349 | OUTPUT_DIR/coverage/a/b/x.cc.html. An index html file is also generated as: |
| 350 | OUTPUT_DIR/index.html. |
| 351 | |
| 352 | Args: |
| 353 | binary_paths: A list of paths to the instrumented binaries. |
| 354 | profdata_file_path: A path to the profdata file. |
Yuke Liao | 66da173 | 2017-12-05 22:19:42 | [diff] [blame] | 355 | filters: A list of directories and files to get coverage for. |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 356 | """ |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 357 | # llvm-cov show [options] -instr-profile PROFILE BIN [-object BIN,...] |
| 358 | # [[-object BIN]] [SOURCES] |
| 359 | # NOTE: For object files, the first one is specified as a positional argument, |
| 360 | # and the rest are specified as keyword argument. |
Yuke Liao | 481d348 | 2018-01-29 19:17:10 | [diff] [blame^] | 361 | logging.debug('Generating per file line by line coverage reports using ' |
| 362 | '"llvm-cov show" command') |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 363 | subprocess_cmd = [ |
| 364 | LLVM_COV_PATH, 'show', '-format=html', |
| 365 | '-output-dir={}'.format(OUTPUT_DIR), |
| 366 | '-instr-profile={}'.format(profdata_file_path), binary_paths[0] |
| 367 | ] |
| 368 | subprocess_cmd.extend( |
| 369 | ['-object=' + binary_path for binary_path in binary_paths[1:]]) |
Yuke Liao | 66da173 | 2017-12-05 22:19:42 | [diff] [blame] | 370 | subprocess_cmd.extend(filters) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 371 | subprocess.check_call(subprocess_cmd) |
Yuke Liao | 481d348 | 2018-01-29 19:17:10 | [diff] [blame^] | 372 | logging.debug('Finished running "llvm-cov show" command') |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 373 | |
| 374 | |
Yuke Liao | ea228d0 | 2018-01-05 19:10:33 | [diff] [blame] | 375 | def _GeneratePerDirectoryCoverageInHtml(binary_paths, profdata_file_path, |
| 376 | filters): |
| 377 | """Generates coverage breakdown per directory.""" |
Yuke Liao | 481d348 | 2018-01-29 19:17:10 | [diff] [blame^] | 378 | logging.debug('Calculating and writing per-directory coverage reports') |
Yuke Liao | ea228d0 | 2018-01-05 19:10:33 | [diff] [blame] | 379 | per_file_coverage_summary = _GeneratePerFileCoverageSummary( |
| 380 | binary_paths, profdata_file_path, filters) |
Yuke Liao | ea228d0 | 2018-01-05 19:10:33 | [diff] [blame] | 381 | per_directory_coverage_summary = defaultdict( |
| 382 | lambda: _CoverageSummary(0, 0, 0, 0, 0, 0)) |
| 383 | |
| 384 | # Calculate per directory code coverage summaries. |
| 385 | for file_path in per_file_coverage_summary: |
| 386 | summary = per_file_coverage_summary[file_path] |
| 387 | parent_dir = os.path.dirname(file_path) |
| 388 | while True: |
| 389 | per_directory_coverage_summary[parent_dir].AddSummary(summary) |
| 390 | |
| 391 | if parent_dir == SRC_ROOT_PATH: |
| 392 | break |
| 393 | parent_dir = os.path.dirname(parent_dir) |
| 394 | |
| 395 | for dir_path in per_directory_coverage_summary: |
| 396 | _GenerateCoverageInHtmlForDirectory( |
| 397 | dir_path, per_directory_coverage_summary, per_file_coverage_summary) |
| 398 | |
Yuke Liao | 481d348 | 2018-01-29 19:17:10 | [diff] [blame^] | 399 | logging.debug( |
| 400 | 'Finished calculating and writing per-directory coverage reports') |
| 401 | |
Yuke Liao | ea228d0 | 2018-01-05 19:10:33 | [diff] [blame] | 402 | |
| 403 | def _GenerateCoverageInHtmlForDirectory( |
| 404 | dir_path, per_directory_coverage_summary, per_file_coverage_summary): |
| 405 | """Generates coverage html report for a single directory.""" |
| 406 | html_generator = _DirectoryCoverageReportHtmlGenerator() |
| 407 | |
| 408 | for entry_name in os.listdir(dir_path): |
| 409 | entry_path = os.path.normpath(os.path.join(dir_path, entry_name)) |
| 410 | entry_html_report_path = _GetCoverageHtmlReportPath(entry_path) |
| 411 | |
| 412 | # Use relative paths instead of absolute paths to make the generated |
| 413 | # reports portable. |
| 414 | html_report_path = _GetCoverageHtmlReportPath(dir_path) |
| 415 | entry_html_report_relative_path = os.path.relpath( |
| 416 | entry_html_report_path, os.path.dirname(html_report_path)) |
| 417 | |
| 418 | if entry_path in per_directory_coverage_summary: |
| 419 | html_generator.AddLinkToAnotherReport( |
| 420 | entry_html_report_relative_path, os.path.basename(entry_path), |
| 421 | per_directory_coverage_summary[entry_path]) |
| 422 | elif entry_path in per_file_coverage_summary: |
| 423 | html_generator.AddLinkToAnotherReport( |
| 424 | entry_html_report_relative_path, os.path.basename(entry_path), |
| 425 | per_file_coverage_summary[entry_path]) |
| 426 | |
Yuke Liao | d54030e | 2018-01-08 17:34:12 | [diff] [blame] | 427 | html_generator.CreateTotalsEntry(per_directory_coverage_summary[dir_path]) |
Yuke Liao | ea228d0 | 2018-01-05 19:10:33 | [diff] [blame] | 428 | html_generator.WriteHtmlCoverageReport(html_report_path) |
| 429 | |
| 430 | |
| 431 | def _OverwriteHtmlReportsIndexFile(): |
| 432 | """Overwrites the index file to link to the source root directory report.""" |
| 433 | html_index_file_path = os.path.join(OUTPUT_DIR, |
| 434 | os.extsep.join(['index', 'html'])) |
| 435 | src_root_html_report_path = _GetCoverageHtmlReportPath(SRC_ROOT_PATH) |
| 436 | src_root_html_report_relative_path = os.path.relpath( |
| 437 | src_root_html_report_path, os.path.dirname(html_index_file_path)) |
| 438 | content = (""" |
| 439 | <!DOCTYPE html> |
| 440 | <html> |
| 441 | <head> |
| 442 | <!-- HTML meta refresh URL redirection --> |
| 443 | <meta http-equiv="refresh" content="0; url=%s"> |
| 444 | </head> |
| 445 | </html>""" % src_root_html_report_relative_path) |
| 446 | with open(html_index_file_path, 'w') as f: |
| 447 | f.write(content) |
| 448 | |
| 449 | |
| 450 | def _GetCoverageHtmlReportPath(file_or_dir_path): |
| 451 | """Given a file or directory, returns the corresponding html report path.""" |
| 452 | html_path = ( |
| 453 | os.path.join(os.path.abspath(OUTPUT_DIR), 'coverage') + |
| 454 | os.path.abspath(file_or_dir_path)) |
| 455 | if os.path.isdir(file_or_dir_path): |
| 456 | return os.path.join(html_path, DIRECTORY_COVERAGE_HTML_REPORT_NAME) |
| 457 | else: |
| 458 | return os.extsep.join([html_path, 'html']) |
| 459 | |
| 460 | |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 461 | def _CreateCoverageProfileDataForTargets(targets, commands, jobs_count=None): |
| 462 | """Builds and runs target to generate the coverage profile data. |
| 463 | |
| 464 | Args: |
| 465 | targets: A list of targets to build with coverage instrumentation. |
| 466 | commands: A list of commands used to run the targets. |
| 467 | jobs_count: Number of jobs to run in parallel for building. If None, a |
| 468 | default value is derived based on CPUs availability. |
| 469 | |
| 470 | Returns: |
| 471 | A relative path to the generated profdata file. |
| 472 | """ |
| 473 | _BuildTargets(targets, jobs_count) |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 474 | profraw_file_paths = _GetProfileRawDataPathsByExecutingCommands( |
| 475 | targets, commands) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 476 | profdata_file_path = _CreateCoverageProfileDataFromProfRawData( |
| 477 | profraw_file_paths) |
| 478 | |
Yuke Liao | d4a986520 | 2018-01-12 23:17:52 | [diff] [blame] | 479 | for profraw_file_path in profraw_file_paths: |
| 480 | os.remove(profraw_file_path) |
| 481 | |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 482 | return profdata_file_path |
| 483 | |
| 484 | |
| 485 | def _BuildTargets(targets, jobs_count): |
| 486 | """Builds target with Clang coverage instrumentation. |
| 487 | |
| 488 | This function requires current working directory to be the root of checkout. |
| 489 | |
| 490 | Args: |
| 491 | targets: A list of targets to build with coverage instrumentation. |
| 492 | jobs_count: Number of jobs to run in parallel for compilation. If None, a |
| 493 | default value is derived based on CPUs availability. |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 494 | """ |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 495 | |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 496 | def _IsGomaConfigured(): |
| 497 | """Returns True if goma is enabled in the gn build args. |
| 498 | |
| 499 | Returns: |
| 500 | A boolean indicates whether goma is configured for building or not. |
| 501 | """ |
| 502 | build_args = _ParseArgsGnFile() |
| 503 | return 'use_goma' in build_args and build_args['use_goma'] == 'true' |
| 504 | |
Yuke Liao | 481d348 | 2018-01-29 19:17:10 | [diff] [blame^] | 505 | logging.info('Building %s', str(targets)) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 506 | if jobs_count is None and _IsGomaConfigured(): |
| 507 | jobs_count = DEFAULT_GOMA_JOBS |
| 508 | |
| 509 | subprocess_cmd = ['ninja', '-C', BUILD_DIR] |
| 510 | if jobs_count is not None: |
| 511 | subprocess_cmd.append('-j' + str(jobs_count)) |
| 512 | |
| 513 | subprocess_cmd.extend(targets) |
| 514 | subprocess.check_call(subprocess_cmd) |
Yuke Liao | 481d348 | 2018-01-29 19:17:10 | [diff] [blame^] | 515 | logging.debug('Finished building %s', str(targets)) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 516 | |
| 517 | |
| 518 | def _GetProfileRawDataPathsByExecutingCommands(targets, commands): |
| 519 | """Runs commands and returns the relative paths to the profraw data files. |
| 520 | |
| 521 | Args: |
| 522 | targets: A list of targets built with coverage instrumentation. |
| 523 | commands: A list of commands used to run the targets. |
| 524 | |
| 525 | Returns: |
| 526 | A list of relative paths to the generated profraw data files. |
| 527 | """ |
Yuke Liao | 481d348 | 2018-01-29 19:17:10 | [diff] [blame^] | 528 | logging.debug('Executing the test commands') |
| 529 | |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 530 | # Remove existing profraw data files. |
| 531 | for file_or_dir in os.listdir(OUTPUT_DIR): |
| 532 | if file_or_dir.endswith(PROFRAW_FILE_EXTENSION): |
| 533 | os.remove(os.path.join(OUTPUT_DIR, file_or_dir)) |
| 534 | |
Yuke Liao | d4a986520 | 2018-01-12 23:17:52 | [diff] [blame] | 535 | # Run all test targets to generate profraw data files. |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 536 | for target, command in zip(targets, commands): |
Yuke Liao | d4a986520 | 2018-01-12 23:17:52 | [diff] [blame] | 537 | _ExecuteCommand(target, command) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 538 | |
Yuke Liao | 481d348 | 2018-01-29 19:17:10 | [diff] [blame^] | 539 | logging.debug('Finished executing the test commands') |
| 540 | |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 541 | profraw_file_paths = [] |
| 542 | for file_or_dir in os.listdir(OUTPUT_DIR): |
| 543 | if file_or_dir.endswith(PROFRAW_FILE_EXTENSION): |
| 544 | profraw_file_paths.append(os.path.join(OUTPUT_DIR, file_or_dir)) |
| 545 | |
| 546 | # Assert one target/command generates at least one profraw data file. |
| 547 | for target in targets: |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 548 | assert any( |
| 549 | os.path.basename(profraw_file).startswith(target) |
| 550 | for profraw_file in profraw_file_paths), ( |
| 551 | 'Running target: %s failed to generate any profraw data file, ' |
| 552 | 'please make sure the binary exists and is properly instrumented.' % |
| 553 | target) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 554 | |
| 555 | return profraw_file_paths |
| 556 | |
| 557 | |
| 558 | def _ExecuteCommand(target, command): |
| 559 | """Runs a single command and generates a profraw data file. |
| 560 | |
| 561 | Args: |
| 562 | target: A target built with coverage instrumentation. |
| 563 | command: A command used to run the target. |
| 564 | """ |
Yuke Liao | d4a986520 | 2018-01-12 23:17:52 | [diff] [blame] | 565 | # Per Clang "Source-based Code Coverage" doc: |
| 566 | # "%Nm" expands out to the instrumented binary's signature. When this pattern |
| 567 | # is specified, the runtime creates a pool of N raw profiles which are used |
| 568 | # for on-line profile merging. The runtime takes care of selecting a raw |
| 569 | # profile from the pool, locking it, and updating it before the program exits. |
| 570 | # If N is not specified (i.e the pattern is "%m"), it's assumed that N = 1. |
| 571 | # N must be between 1 and 9. The merge pool specifier can only occur once per |
| 572 | # filename pattern. |
| 573 | # |
| 574 | # 4 is chosen because it creates some level of parallelism, but it's not too |
| 575 | # big to consume too much computing resource or disk space. |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 576 | expected_profraw_file_name = os.extsep.join( |
Yuke Liao | d4a986520 | 2018-01-12 23:17:52 | [diff] [blame] | 577 | [target, '%4m', PROFRAW_FILE_EXTENSION]) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 578 | expected_profraw_file_path = os.path.join(OUTPUT_DIR, |
| 579 | expected_profraw_file_name) |
| 580 | output_file_name = os.extsep.join([target + '_output', 'txt']) |
| 581 | output_file_path = os.path.join(OUTPUT_DIR, output_file_name) |
| 582 | |
Yuke Liao | 481d348 | 2018-01-29 19:17:10 | [diff] [blame^] | 583 | logging.info('Running command: "%s", the output is redirected to "%s"', |
| 584 | command, output_file_path) |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 585 | output = subprocess.check_output( |
| 586 | command.split(), env={ |
| 587 | 'LLVM_PROFILE_FILE': expected_profraw_file_path |
| 588 | }) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 589 | with open(output_file_path, 'w') as output_file: |
| 590 | output_file.write(output) |
| 591 | |
| 592 | |
| 593 | def _CreateCoverageProfileDataFromProfRawData(profraw_file_paths): |
| 594 | """Returns a relative path to the profdata file by merging profraw data files. |
| 595 | |
| 596 | Args: |
| 597 | profraw_file_paths: A list of relative paths to the profraw data files that |
| 598 | are to be merged. |
| 599 | |
| 600 | Returns: |
| 601 | A relative path to the generated profdata file. |
| 602 | |
| 603 | Raises: |
| 604 | CalledProcessError: An error occurred merging profraw data files. |
| 605 | """ |
Yuke Liao | 481d348 | 2018-01-29 19:17:10 | [diff] [blame^] | 606 | logging.info('Creating the coverage profile data file') |
| 607 | logging.debug('Merging profraw files to create profdata file') |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 608 | profdata_file_path = os.path.join(OUTPUT_DIR, PROFDATA_FILE_NAME) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 609 | try: |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 610 | subprocess_cmd = [ |
| 611 | LLVM_PROFDATA_PATH, 'merge', '-o', profdata_file_path, '-sparse=true' |
| 612 | ] |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 613 | subprocess_cmd.extend(profraw_file_paths) |
| 614 | subprocess.check_call(subprocess_cmd) |
| 615 | except subprocess.CalledProcessError as error: |
| 616 | print('Failed to merge profraw files to create profdata file') |
| 617 | raise error |
| 618 | |
Yuke Liao | 481d348 | 2018-01-29 19:17:10 | [diff] [blame^] | 619 | logging.debug('Finished merging profraw files') |
| 620 | logging.info('Code coverage profile data is created as: %s', |
| 621 | profdata_file_path) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 622 | return profdata_file_path |
| 623 | |
| 624 | |
Yuke Liao | ea228d0 | 2018-01-05 19:10:33 | [diff] [blame] | 625 | def _GeneratePerFileCoverageSummary(binary_paths, profdata_file_path, filters): |
| 626 | """Generates per file coverage summary using "llvm-cov export" command.""" |
| 627 | # llvm-cov export [options] -instr-profile PROFILE BIN [-object BIN,...] |
| 628 | # [[-object BIN]] [SOURCES]. |
| 629 | # NOTE: For object files, the first one is specified as a positional argument, |
| 630 | # and the rest are specified as keyword argument. |
Yuke Liao | 481d348 | 2018-01-29 19:17:10 | [diff] [blame^] | 631 | logging.debug('Generating per-file code coverage summary using "llvm-cov ' |
| 632 | 'export -summary-only" command') |
Yuke Liao | ea228d0 | 2018-01-05 19:10:33 | [diff] [blame] | 633 | subprocess_cmd = [ |
| 634 | LLVM_COV_PATH, 'export', '-summary-only', |
| 635 | '-instr-profile=' + profdata_file_path, binary_paths[0] |
| 636 | ] |
| 637 | subprocess_cmd.extend( |
| 638 | ['-object=' + binary_path for binary_path in binary_paths[1:]]) |
| 639 | subprocess_cmd.extend(filters) |
| 640 | |
| 641 | json_output = json.loads(subprocess.check_output(subprocess_cmd)) |
| 642 | assert len(json_output['data']) == 1 |
| 643 | files_coverage_data = json_output['data'][0]['files'] |
| 644 | |
| 645 | per_file_coverage_summary = {} |
| 646 | for file_coverage_data in files_coverage_data: |
| 647 | file_path = file_coverage_data['filename'] |
| 648 | summary = file_coverage_data['summary'] |
| 649 | |
| 650 | # TODO(crbug.com/797345): Currently, [SOURCES] parameter doesn't apply to |
| 651 | # llvm-cov export command, so work it around by manually filter the paths. |
| 652 | # Remove this logic once the bug is fixed and clang has rolled past it. |
| 653 | if filters and not any( |
| 654 | os.path.abspath(file_path).startswith(os.path.abspath(filter)) |
| 655 | for filter in filters): |
| 656 | continue |
| 657 | |
| 658 | if summary['lines']['count'] == 0: |
| 659 | continue |
| 660 | |
| 661 | per_file_coverage_summary[file_path] = _CoverageSummary( |
| 662 | regions_total=summary['regions']['count'], |
| 663 | regions_covered=summary['regions']['covered'], |
| 664 | functions_total=summary['functions']['count'], |
| 665 | functions_covered=summary['functions']['covered'], |
| 666 | lines_total=summary['lines']['count'], |
| 667 | lines_covered=summary['lines']['covered']) |
| 668 | |
Yuke Liao | 481d348 | 2018-01-29 19:17:10 | [diff] [blame^] | 669 | logging.debug('Finished generating per-file code coverage summary') |
Yuke Liao | ea228d0 | 2018-01-05 19:10:33 | [diff] [blame] | 670 | return per_file_coverage_summary |
| 671 | |
| 672 | |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 673 | def _GetBinaryPath(command): |
| 674 | """Returns a relative path to the binary to be run by the command. |
| 675 | |
| 676 | Args: |
| 677 | command: A command used to run a target. |
| 678 | |
| 679 | Returns: |
| 680 | A relative path to the binary. |
| 681 | """ |
| 682 | return command.split()[0] |
| 683 | |
| 684 | |
Yuke Liao | 95d13d7 | 2017-12-07 18:18:50 | [diff] [blame] | 685 | def _VerifyTargetExecutablesAreInBuildDirectory(commands): |
| 686 | """Verifies that the target executables specified in the commands are inside |
| 687 | the given build directory.""" |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 688 | for command in commands: |
| 689 | binary_path = _GetBinaryPath(command) |
Yuke Liao | 95d13d7 | 2017-12-07 18:18:50 | [diff] [blame] | 690 | binary_absolute_path = os.path.abspath(os.path.normpath(binary_path)) |
| 691 | assert binary_absolute_path.startswith(os.path.abspath(BUILD_DIR)), ( |
| 692 | 'Target executable "%s" in command: "%s" is outside of ' |
| 693 | 'the given build directory: "%s".' % (binary_path, command, BUILD_DIR)) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 694 | |
| 695 | |
| 696 | def _ValidateBuildingWithClangCoverage(): |
| 697 | """Asserts that targets are built with Clang coverage enabled.""" |
| 698 | build_args = _ParseArgsGnFile() |
| 699 | |
| 700 | if (CLANG_COVERAGE_BUILD_ARG not in build_args or |
| 701 | build_args[CLANG_COVERAGE_BUILD_ARG] != 'true'): |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 702 | assert False, ('\'{} = true\' is required in args.gn.' |
| 703 | ).format(CLANG_COVERAGE_BUILD_ARG) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 704 | |
| 705 | |
| 706 | def _ParseArgsGnFile(): |
| 707 | """Parses args.gn file and returns results as a dictionary. |
| 708 | |
| 709 | Returns: |
| 710 | A dictionary representing the build args. |
| 711 | """ |
| 712 | build_args_path = os.path.join(BUILD_DIR, 'args.gn') |
| 713 | assert os.path.exists(build_args_path), ('"%s" is not a build directory, ' |
| 714 | 'missing args.gn file.' % BUILD_DIR) |
| 715 | with open(build_args_path) as build_args_file: |
| 716 | build_args_lines = build_args_file.readlines() |
| 717 | |
| 718 | build_args = {} |
| 719 | for build_arg_line in build_args_lines: |
| 720 | build_arg_without_comments = build_arg_line.split('#')[0] |
| 721 | key_value_pair = build_arg_without_comments.split('=') |
| 722 | if len(key_value_pair) != 2: |
| 723 | continue |
| 724 | |
| 725 | key = key_value_pair[0].strip() |
| 726 | value = key_value_pair[1].strip() |
| 727 | build_args[key] = value |
| 728 | |
| 729 | return build_args |
| 730 | |
| 731 | |
Abhishek Arya | 16f059a | 2017-12-07 17:47:32 | [diff] [blame] | 732 | def _VerifyPathsAndReturnAbsolutes(paths): |
| 733 | """Verifies that the paths specified in |paths| exist and returns absolute |
| 734 | versions. |
Yuke Liao | 66da173 | 2017-12-05 22:19:42 | [diff] [blame] | 735 | |
| 736 | Args: |
| 737 | paths: A list of files or directories. |
| 738 | """ |
Abhishek Arya | 16f059a | 2017-12-07 17:47:32 | [diff] [blame] | 739 | absolute_paths = [] |
Yuke Liao | 66da173 | 2017-12-05 22:19:42 | [diff] [blame] | 740 | for path in paths: |
Abhishek Arya | 16f059a | 2017-12-07 17:47:32 | [diff] [blame] | 741 | absolute_path = os.path.join(SRC_ROOT_PATH, path) |
| 742 | assert os.path.exists(absolute_path), ('Path: "%s" doesn\'t exist.' % path) |
| 743 | |
| 744 | absolute_paths.append(absolute_path) |
| 745 | |
| 746 | return absolute_paths |
Yuke Liao | 66da173 | 2017-12-05 22:19:42 | [diff] [blame] | 747 | |
| 748 | |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 749 | def _ParseCommandArguments(): |
| 750 | """Adds and parses relevant arguments for tool comands. |
| 751 | |
| 752 | Returns: |
| 753 | A dictionary representing the arguments. |
| 754 | """ |
| 755 | arg_parser = argparse.ArgumentParser() |
| 756 | arg_parser.usage = __doc__ |
| 757 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 758 | arg_parser.add_argument( |
| 759 | '-b', |
| 760 | '--build-dir', |
| 761 | type=str, |
| 762 | required=True, |
| 763 | help='The build directory, the path needs to be relative to the root of ' |
| 764 | 'the checkout.') |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 765 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 766 | arg_parser.add_argument( |
| 767 | '-o', |
| 768 | '--output-dir', |
| 769 | type=str, |
| 770 | required=True, |
| 771 | help='Output directory for generated artifacts.') |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 772 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 773 | arg_parser.add_argument( |
| 774 | '-c', |
| 775 | '--command', |
| 776 | action='append', |
| 777 | required=True, |
| 778 | help='Commands used to run test targets, one test target needs one and ' |
| 779 | 'only one command, when specifying commands, one should assume the ' |
| 780 | 'current working directory is the root of the checkout.') |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 781 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 782 | arg_parser.add_argument( |
Yuke Liao | 66da173 | 2017-12-05 22:19:42 | [diff] [blame] | 783 | '-f', |
| 784 | '--filters', |
| 785 | action='append', |
Abhishek Arya | 16f059a | 2017-12-07 17:47:32 | [diff] [blame] | 786 | required=False, |
Yuke Liao | 66da173 | 2017-12-05 22:19:42 | [diff] [blame] | 787 | help='Directories or files to get code coverage for, and all files under ' |
| 788 | 'the directories are included recursively.') |
| 789 | |
| 790 | arg_parser.add_argument( |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 791 | '-j', |
| 792 | '--jobs', |
| 793 | type=int, |
| 794 | default=None, |
| 795 | help='Run N jobs to build in parallel. If not specified, a default value ' |
| 796 | 'will be derived based on CPUs availability. Please refer to ' |
| 797 | '\'ninja -h\' for more details.') |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 798 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 799 | arg_parser.add_argument( |
Yuke Liao | 481d348 | 2018-01-29 19:17:10 | [diff] [blame^] | 800 | '-v', |
| 801 | '--verbose', |
| 802 | action='store_true', |
| 803 | help='Prints additional output for diagnostics.') |
| 804 | |
| 805 | arg_parser.add_argument( |
| 806 | '-l', '--log_file', type=str, help='Redirects logs to a file.') |
| 807 | |
| 808 | arg_parser.add_argument( |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 809 | 'targets', nargs='+', help='The names of the test targets to run.') |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 810 | |
| 811 | args = arg_parser.parse_args() |
| 812 | return args |
| 813 | |
| 814 | |
| 815 | def Main(): |
| 816 | """Execute tool commands.""" |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 817 | assert _GetPlatform() in ['linux', 'mac'], ( |
| 818 | 'Coverage is only supported on linux and mac platforms.') |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 819 | assert os.path.abspath(os.getcwd()) == SRC_ROOT_PATH, ('This script must be ' |
| 820 | 'called from the root ' |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 821 | 'of checkout.') |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 822 | DownloadCoverageToolsIfNeeded() |
| 823 | |
| 824 | args = _ParseCommandArguments() |
| 825 | global BUILD_DIR |
| 826 | BUILD_DIR = args.build_dir |
| 827 | global OUTPUT_DIR |
| 828 | OUTPUT_DIR = args.output_dir |
| 829 | |
Yuke Liao | 481d348 | 2018-01-29 19:17:10 | [diff] [blame^] | 830 | log_level = logging.DEBUG if args.verbose else logging.INFO |
| 831 | log_format = '[%(asctime)s] %(message)s' |
| 832 | log_file = args.log_file if args.log_file else None |
| 833 | logging.basicConfig(filename=log_file, level=log_level, format=log_format) |
| 834 | |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 835 | assert len(args.targets) == len(args.command), ('Number of targets must be ' |
| 836 | 'equal to the number of test ' |
| 837 | 'commands.') |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 838 | assert os.path.exists(BUILD_DIR), ( |
| 839 | 'Build directory: {} doesn\'t exist. ' |
| 840 | 'Please run "gn gen" to generate.').format(BUILD_DIR) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 841 | _ValidateBuildingWithClangCoverage() |
Yuke Liao | 95d13d7 | 2017-12-07 18:18:50 | [diff] [blame] | 842 | _VerifyTargetExecutablesAreInBuildDirectory(args.command) |
Abhishek Arya | 16f059a | 2017-12-07 17:47:32 | [diff] [blame] | 843 | |
| 844 | absolute_filter_paths = [] |
Yuke Liao | 66da173 | 2017-12-05 22:19:42 | [diff] [blame] | 845 | if args.filters: |
Abhishek Arya | 16f059a | 2017-12-07 17:47:32 | [diff] [blame] | 846 | absolute_filter_paths = _VerifyPathsAndReturnAbsolutes(args.filters) |
Yuke Liao | 66da173 | 2017-12-05 22:19:42 | [diff] [blame] | 847 | |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 848 | if not os.path.exists(OUTPUT_DIR): |
| 849 | os.makedirs(OUTPUT_DIR) |
| 850 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 851 | profdata_file_path = _CreateCoverageProfileDataForTargets( |
| 852 | args.targets, args.command, args.jobs) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 853 | binary_paths = [_GetBinaryPath(command) for command in args.command] |
Yuke Liao | ea228d0 | 2018-01-05 19:10:33 | [diff] [blame] | 854 | |
Yuke Liao | 481d348 | 2018-01-29 19:17:10 | [diff] [blame^] | 855 | logging.info('Generating code coverage report in html (this can take a while ' |
| 856 | 'depending on size of target!)') |
Yuke Liao | 66da173 | 2017-12-05 22:19:42 | [diff] [blame] | 857 | _GenerateLineByLineFileCoverageInHtml(binary_paths, profdata_file_path, |
Abhishek Arya | 16f059a | 2017-12-07 17:47:32 | [diff] [blame] | 858 | absolute_filter_paths) |
Yuke Liao | ea228d0 | 2018-01-05 19:10:33 | [diff] [blame] | 859 | _GeneratePerDirectoryCoverageInHtml(binary_paths, profdata_file_path, |
| 860 | absolute_filter_paths) |
| 861 | |
| 862 | # The default index file is generated only for the list of source files, needs |
| 863 | # to overwrite it to display per directory code coverage breakdown. |
| 864 | _OverwriteHtmlReportsIndexFile() |
| 865 | |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 866 | html_index_file_path = 'file://' + os.path.abspath( |
| 867 | os.path.join(OUTPUT_DIR, 'index.html')) |
Yuke Liao | 481d348 | 2018-01-29 19:17:10 | [diff] [blame^] | 868 | logging.info('Index file for html report is generated as: %s', |
| 869 | html_index_file_path) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 870 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 871 | |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 872 | if __name__ == '__main__': |
| 873 | sys.exit(Main()) |