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 | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 57 | import os |
| 58 | import subprocess |
| 59 | import threading |
| 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) |
| 335 | print('Coverage tools %s unpacked' % package_version) |
| 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. |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 361 | subprocess_cmd = [ |
| 362 | LLVM_COV_PATH, 'show', '-format=html', |
| 363 | '-output-dir={}'.format(OUTPUT_DIR), |
| 364 | '-instr-profile={}'.format(profdata_file_path), binary_paths[0] |
| 365 | ] |
| 366 | subprocess_cmd.extend( |
| 367 | ['-object=' + binary_path for binary_path in binary_paths[1:]]) |
Yuke Liao | 66da173 | 2017-12-05 22:19:42 | [diff] [blame] | 368 | subprocess_cmd.extend(filters) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 369 | |
| 370 | subprocess.check_call(subprocess_cmd) |
| 371 | |
| 372 | |
Yuke Liao | ea228d0 | 2018-01-05 19:10:33 | [diff] [blame] | 373 | def _GeneratePerDirectoryCoverageInHtml(binary_paths, profdata_file_path, |
| 374 | filters): |
| 375 | """Generates coverage breakdown per directory.""" |
| 376 | per_file_coverage_summary = _GeneratePerFileCoverageSummary( |
| 377 | binary_paths, profdata_file_path, filters) |
| 378 | |
| 379 | per_directory_coverage_summary = defaultdict( |
| 380 | lambda: _CoverageSummary(0, 0, 0, 0, 0, 0)) |
| 381 | |
| 382 | # Calculate per directory code coverage summaries. |
| 383 | for file_path in per_file_coverage_summary: |
| 384 | summary = per_file_coverage_summary[file_path] |
| 385 | parent_dir = os.path.dirname(file_path) |
| 386 | while True: |
| 387 | per_directory_coverage_summary[parent_dir].AddSummary(summary) |
| 388 | |
| 389 | if parent_dir == SRC_ROOT_PATH: |
| 390 | break |
| 391 | parent_dir = os.path.dirname(parent_dir) |
| 392 | |
| 393 | for dir_path in per_directory_coverage_summary: |
| 394 | _GenerateCoverageInHtmlForDirectory( |
| 395 | dir_path, per_directory_coverage_summary, per_file_coverage_summary) |
| 396 | |
| 397 | |
| 398 | def _GenerateCoverageInHtmlForDirectory( |
| 399 | dir_path, per_directory_coverage_summary, per_file_coverage_summary): |
| 400 | """Generates coverage html report for a single directory.""" |
| 401 | html_generator = _DirectoryCoverageReportHtmlGenerator() |
| 402 | |
| 403 | for entry_name in os.listdir(dir_path): |
| 404 | entry_path = os.path.normpath(os.path.join(dir_path, entry_name)) |
| 405 | entry_html_report_path = _GetCoverageHtmlReportPath(entry_path) |
| 406 | |
| 407 | # Use relative paths instead of absolute paths to make the generated |
| 408 | # reports portable. |
| 409 | html_report_path = _GetCoverageHtmlReportPath(dir_path) |
| 410 | entry_html_report_relative_path = os.path.relpath( |
| 411 | entry_html_report_path, os.path.dirname(html_report_path)) |
| 412 | |
| 413 | if entry_path in per_directory_coverage_summary: |
| 414 | html_generator.AddLinkToAnotherReport( |
| 415 | entry_html_report_relative_path, os.path.basename(entry_path), |
| 416 | per_directory_coverage_summary[entry_path]) |
| 417 | elif entry_path in per_file_coverage_summary: |
| 418 | html_generator.AddLinkToAnotherReport( |
| 419 | entry_html_report_relative_path, os.path.basename(entry_path), |
| 420 | per_file_coverage_summary[entry_path]) |
| 421 | |
Yuke Liao | d54030e | 2018-01-08 17:34:12 | [diff] [blame^] | 422 | html_generator.CreateTotalsEntry(per_directory_coverage_summary[dir_path]) |
Yuke Liao | ea228d0 | 2018-01-05 19:10:33 | [diff] [blame] | 423 | html_generator.WriteHtmlCoverageReport(html_report_path) |
| 424 | |
| 425 | |
| 426 | def _OverwriteHtmlReportsIndexFile(): |
| 427 | """Overwrites the index file to link to the source root directory report.""" |
| 428 | html_index_file_path = os.path.join(OUTPUT_DIR, |
| 429 | os.extsep.join(['index', 'html'])) |
| 430 | src_root_html_report_path = _GetCoverageHtmlReportPath(SRC_ROOT_PATH) |
| 431 | src_root_html_report_relative_path = os.path.relpath( |
| 432 | src_root_html_report_path, os.path.dirname(html_index_file_path)) |
| 433 | content = (""" |
| 434 | <!DOCTYPE html> |
| 435 | <html> |
| 436 | <head> |
| 437 | <!-- HTML meta refresh URL redirection --> |
| 438 | <meta http-equiv="refresh" content="0; url=%s"> |
| 439 | </head> |
| 440 | </html>""" % src_root_html_report_relative_path) |
| 441 | with open(html_index_file_path, 'w') as f: |
| 442 | f.write(content) |
| 443 | |
| 444 | |
| 445 | def _GetCoverageHtmlReportPath(file_or_dir_path): |
| 446 | """Given a file or directory, returns the corresponding html report path.""" |
| 447 | html_path = ( |
| 448 | os.path.join(os.path.abspath(OUTPUT_DIR), 'coverage') + |
| 449 | os.path.abspath(file_or_dir_path)) |
| 450 | if os.path.isdir(file_or_dir_path): |
| 451 | return os.path.join(html_path, DIRECTORY_COVERAGE_HTML_REPORT_NAME) |
| 452 | else: |
| 453 | return os.extsep.join([html_path, 'html']) |
| 454 | |
| 455 | |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 456 | def _CreateCoverageProfileDataForTargets(targets, commands, jobs_count=None): |
| 457 | """Builds and runs target to generate the coverage profile data. |
| 458 | |
| 459 | Args: |
| 460 | targets: A list of targets to build with coverage instrumentation. |
| 461 | commands: A list of commands used to run the targets. |
| 462 | jobs_count: Number of jobs to run in parallel for building. If None, a |
| 463 | default value is derived based on CPUs availability. |
| 464 | |
| 465 | Returns: |
| 466 | A relative path to the generated profdata file. |
| 467 | """ |
| 468 | _BuildTargets(targets, jobs_count) |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 469 | profraw_file_paths = _GetProfileRawDataPathsByExecutingCommands( |
| 470 | targets, commands) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 471 | profdata_file_path = _CreateCoverageProfileDataFromProfRawData( |
| 472 | profraw_file_paths) |
| 473 | |
| 474 | return profdata_file_path |
| 475 | |
| 476 | |
| 477 | def _BuildTargets(targets, jobs_count): |
| 478 | """Builds target with Clang coverage instrumentation. |
| 479 | |
| 480 | This function requires current working directory to be the root of checkout. |
| 481 | |
| 482 | Args: |
| 483 | targets: A list of targets to build with coverage instrumentation. |
| 484 | jobs_count: Number of jobs to run in parallel for compilation. If None, a |
| 485 | default value is derived based on CPUs availability. |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 486 | """ |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 487 | |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 488 | def _IsGomaConfigured(): |
| 489 | """Returns True if goma is enabled in the gn build args. |
| 490 | |
| 491 | Returns: |
| 492 | A boolean indicates whether goma is configured for building or not. |
| 493 | """ |
| 494 | build_args = _ParseArgsGnFile() |
| 495 | return 'use_goma' in build_args and build_args['use_goma'] == 'true' |
| 496 | |
| 497 | print('Building %s' % str(targets)) |
| 498 | |
| 499 | if jobs_count is None and _IsGomaConfigured(): |
| 500 | jobs_count = DEFAULT_GOMA_JOBS |
| 501 | |
| 502 | subprocess_cmd = ['ninja', '-C', BUILD_DIR] |
| 503 | if jobs_count is not None: |
| 504 | subprocess_cmd.append('-j' + str(jobs_count)) |
| 505 | |
| 506 | subprocess_cmd.extend(targets) |
| 507 | subprocess.check_call(subprocess_cmd) |
| 508 | |
| 509 | |
| 510 | def _GetProfileRawDataPathsByExecutingCommands(targets, commands): |
| 511 | """Runs commands and returns the relative paths to the profraw data files. |
| 512 | |
| 513 | Args: |
| 514 | targets: A list of targets built with coverage instrumentation. |
| 515 | commands: A list of commands used to run the targets. |
| 516 | |
| 517 | Returns: |
| 518 | A list of relative paths to the generated profraw data files. |
| 519 | """ |
| 520 | # Remove existing profraw data files. |
| 521 | for file_or_dir in os.listdir(OUTPUT_DIR): |
| 522 | if file_or_dir.endswith(PROFRAW_FILE_EXTENSION): |
| 523 | os.remove(os.path.join(OUTPUT_DIR, file_or_dir)) |
| 524 | |
| 525 | # Run different test targets in parallel to generate profraw data files. |
| 526 | threads = [] |
| 527 | for target, command in zip(targets, commands): |
| 528 | thread = threading.Thread(target=_ExecuteCommand, args=(target, command)) |
| 529 | thread.start() |
| 530 | threads.append(thread) |
| 531 | for thread in threads: |
| 532 | thread.join() |
| 533 | |
| 534 | profraw_file_paths = [] |
| 535 | for file_or_dir in os.listdir(OUTPUT_DIR): |
| 536 | if file_or_dir.endswith(PROFRAW_FILE_EXTENSION): |
| 537 | profraw_file_paths.append(os.path.join(OUTPUT_DIR, file_or_dir)) |
| 538 | |
| 539 | # Assert one target/command generates at least one profraw data file. |
| 540 | for target in targets: |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 541 | assert any( |
| 542 | os.path.basename(profraw_file).startswith(target) |
| 543 | for profraw_file in profraw_file_paths), ( |
| 544 | 'Running target: %s failed to generate any profraw data file, ' |
| 545 | 'please make sure the binary exists and is properly instrumented.' % |
| 546 | target) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 547 | |
| 548 | return profraw_file_paths |
| 549 | |
| 550 | |
| 551 | def _ExecuteCommand(target, command): |
| 552 | """Runs a single command and generates a profraw data file. |
| 553 | |
| 554 | Args: |
| 555 | target: A target built with coverage instrumentation. |
| 556 | command: A command used to run the target. |
| 557 | """ |
| 558 | if _IsTargetGTestTarget(target): |
| 559 | # This test argument is required and only required for gtest unit test |
| 560 | # targets because by default, they run tests in parallel, and that won't |
| 561 | # generated code coverage data correctly. |
| 562 | command += ' --test-launcher-jobs=1' |
| 563 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 564 | expected_profraw_file_name = os.extsep.join( |
| 565 | [target, '%p', PROFRAW_FILE_EXTENSION]) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 566 | expected_profraw_file_path = os.path.join(OUTPUT_DIR, |
| 567 | expected_profraw_file_name) |
| 568 | output_file_name = os.extsep.join([target + '_output', 'txt']) |
| 569 | output_file_path = os.path.join(OUTPUT_DIR, output_file_name) |
| 570 | |
| 571 | print('Running command: "%s", the output is redirected to "%s"' % |
| 572 | (command, output_file_path)) |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 573 | output = subprocess.check_output( |
| 574 | command.split(), env={ |
| 575 | 'LLVM_PROFILE_FILE': expected_profraw_file_path |
| 576 | }) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 577 | with open(output_file_path, 'w') as output_file: |
| 578 | output_file.write(output) |
| 579 | |
| 580 | |
| 581 | def _CreateCoverageProfileDataFromProfRawData(profraw_file_paths): |
| 582 | """Returns a relative path to the profdata file by merging profraw data files. |
| 583 | |
| 584 | Args: |
| 585 | profraw_file_paths: A list of relative paths to the profraw data files that |
| 586 | are to be merged. |
| 587 | |
| 588 | Returns: |
| 589 | A relative path to the generated profdata file. |
| 590 | |
| 591 | Raises: |
| 592 | CalledProcessError: An error occurred merging profraw data files. |
| 593 | """ |
| 594 | print('Creating the profile data file') |
| 595 | |
| 596 | profdata_file_path = os.path.join(OUTPUT_DIR, PROFDATA_FILE_NAME) |
Abhishek Arya | 16f059a | 2017-12-07 17:47:32 | [diff] [blame] | 597 | |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 598 | try: |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 599 | subprocess_cmd = [ |
| 600 | LLVM_PROFDATA_PATH, 'merge', '-o', profdata_file_path, '-sparse=true' |
| 601 | ] |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 602 | subprocess_cmd.extend(profraw_file_paths) |
| 603 | subprocess.check_call(subprocess_cmd) |
| 604 | except subprocess.CalledProcessError as error: |
| 605 | print('Failed to merge profraw files to create profdata file') |
| 606 | raise error |
| 607 | |
| 608 | return profdata_file_path |
| 609 | |
| 610 | |
Yuke Liao | ea228d0 | 2018-01-05 19:10:33 | [diff] [blame] | 611 | def _GeneratePerFileCoverageSummary(binary_paths, profdata_file_path, filters): |
| 612 | """Generates per file coverage summary using "llvm-cov export" command.""" |
| 613 | # llvm-cov export [options] -instr-profile PROFILE BIN [-object BIN,...] |
| 614 | # [[-object BIN]] [SOURCES]. |
| 615 | # NOTE: For object files, the first one is specified as a positional argument, |
| 616 | # and the rest are specified as keyword argument. |
| 617 | subprocess_cmd = [ |
| 618 | LLVM_COV_PATH, 'export', '-summary-only', |
| 619 | '-instr-profile=' + profdata_file_path, binary_paths[0] |
| 620 | ] |
| 621 | subprocess_cmd.extend( |
| 622 | ['-object=' + binary_path for binary_path in binary_paths[1:]]) |
| 623 | subprocess_cmd.extend(filters) |
| 624 | |
| 625 | json_output = json.loads(subprocess.check_output(subprocess_cmd)) |
| 626 | assert len(json_output['data']) == 1 |
| 627 | files_coverage_data = json_output['data'][0]['files'] |
| 628 | |
| 629 | per_file_coverage_summary = {} |
| 630 | for file_coverage_data in files_coverage_data: |
| 631 | file_path = file_coverage_data['filename'] |
| 632 | summary = file_coverage_data['summary'] |
| 633 | |
| 634 | # TODO(crbug.com/797345): Currently, [SOURCES] parameter doesn't apply to |
| 635 | # llvm-cov export command, so work it around by manually filter the paths. |
| 636 | # Remove this logic once the bug is fixed and clang has rolled past it. |
| 637 | if filters and not any( |
| 638 | os.path.abspath(file_path).startswith(os.path.abspath(filter)) |
| 639 | for filter in filters): |
| 640 | continue |
| 641 | |
| 642 | if summary['lines']['count'] == 0: |
| 643 | continue |
| 644 | |
| 645 | per_file_coverage_summary[file_path] = _CoverageSummary( |
| 646 | regions_total=summary['regions']['count'], |
| 647 | regions_covered=summary['regions']['covered'], |
| 648 | functions_total=summary['functions']['count'], |
| 649 | functions_covered=summary['functions']['covered'], |
| 650 | lines_total=summary['lines']['count'], |
| 651 | lines_covered=summary['lines']['covered']) |
| 652 | |
| 653 | return per_file_coverage_summary |
| 654 | |
| 655 | |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 656 | def _GetBinaryPath(command): |
| 657 | """Returns a relative path to the binary to be run by the command. |
| 658 | |
| 659 | Args: |
| 660 | command: A command used to run a target. |
| 661 | |
| 662 | Returns: |
| 663 | A relative path to the binary. |
| 664 | """ |
| 665 | return command.split()[0] |
| 666 | |
| 667 | |
| 668 | def _IsTargetGTestTarget(target): |
| 669 | """Returns True if the target is a gtest target. |
| 670 | |
| 671 | Args: |
| 672 | target: A target built with coverage instrumentation. |
| 673 | |
| 674 | Returns: |
| 675 | A boolean value indicates whether the target is a gtest target. |
| 676 | """ |
| 677 | global GTEST_TARGET_NAMES |
| 678 | if GTEST_TARGET_NAMES is None: |
| 679 | output = subprocess.check_output(['gn', 'refs', BUILD_DIR, 'testing/gtest']) |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 680 | list_of_gtest_targets = [ |
| 681 | gtest_target for gtest_target in output.splitlines() if gtest_target |
| 682 | ] |
| 683 | GTEST_TARGET_NAMES = set( |
| 684 | [gtest_target.split(':')[1] for gtest_target in list_of_gtest_targets]) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 685 | |
| 686 | return target in GTEST_TARGET_NAMES |
| 687 | |
| 688 | |
Yuke Liao | 95d13d7 | 2017-12-07 18:18:50 | [diff] [blame] | 689 | def _VerifyTargetExecutablesAreInBuildDirectory(commands): |
| 690 | """Verifies that the target executables specified in the commands are inside |
| 691 | the given build directory.""" |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 692 | for command in commands: |
| 693 | binary_path = _GetBinaryPath(command) |
Yuke Liao | 95d13d7 | 2017-12-07 18:18:50 | [diff] [blame] | 694 | binary_absolute_path = os.path.abspath(os.path.normpath(binary_path)) |
| 695 | assert binary_absolute_path.startswith(os.path.abspath(BUILD_DIR)), ( |
| 696 | 'Target executable "%s" in command: "%s" is outside of ' |
| 697 | 'the given build directory: "%s".' % (binary_path, command, BUILD_DIR)) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 698 | |
| 699 | |
| 700 | def _ValidateBuildingWithClangCoverage(): |
| 701 | """Asserts that targets are built with Clang coverage enabled.""" |
| 702 | build_args = _ParseArgsGnFile() |
| 703 | |
| 704 | if (CLANG_COVERAGE_BUILD_ARG not in build_args or |
| 705 | build_args[CLANG_COVERAGE_BUILD_ARG] != 'true'): |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 706 | assert False, ('\'{} = true\' is required in args.gn.' |
| 707 | ).format(CLANG_COVERAGE_BUILD_ARG) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 708 | |
| 709 | |
| 710 | def _ParseArgsGnFile(): |
| 711 | """Parses args.gn file and returns results as a dictionary. |
| 712 | |
| 713 | Returns: |
| 714 | A dictionary representing the build args. |
| 715 | """ |
| 716 | build_args_path = os.path.join(BUILD_DIR, 'args.gn') |
| 717 | assert os.path.exists(build_args_path), ('"%s" is not a build directory, ' |
| 718 | 'missing args.gn file.' % BUILD_DIR) |
| 719 | with open(build_args_path) as build_args_file: |
| 720 | build_args_lines = build_args_file.readlines() |
| 721 | |
| 722 | build_args = {} |
| 723 | for build_arg_line in build_args_lines: |
| 724 | build_arg_without_comments = build_arg_line.split('#')[0] |
| 725 | key_value_pair = build_arg_without_comments.split('=') |
| 726 | if len(key_value_pair) != 2: |
| 727 | continue |
| 728 | |
| 729 | key = key_value_pair[0].strip() |
| 730 | value = key_value_pair[1].strip() |
| 731 | build_args[key] = value |
| 732 | |
| 733 | return build_args |
| 734 | |
| 735 | |
Abhishek Arya | 16f059a | 2017-12-07 17:47:32 | [diff] [blame] | 736 | def _VerifyPathsAndReturnAbsolutes(paths): |
| 737 | """Verifies that the paths specified in |paths| exist and returns absolute |
| 738 | versions. |
Yuke Liao | 66da173 | 2017-12-05 22:19:42 | [diff] [blame] | 739 | |
| 740 | Args: |
| 741 | paths: A list of files or directories. |
| 742 | """ |
Abhishek Arya | 16f059a | 2017-12-07 17:47:32 | [diff] [blame] | 743 | absolute_paths = [] |
Yuke Liao | 66da173 | 2017-12-05 22:19:42 | [diff] [blame] | 744 | for path in paths: |
Abhishek Arya | 16f059a | 2017-12-07 17:47:32 | [diff] [blame] | 745 | absolute_path = os.path.join(SRC_ROOT_PATH, path) |
| 746 | assert os.path.exists(absolute_path), ('Path: "%s" doesn\'t exist.' % path) |
| 747 | |
| 748 | absolute_paths.append(absolute_path) |
| 749 | |
| 750 | return absolute_paths |
Yuke Liao | 66da173 | 2017-12-05 22:19:42 | [diff] [blame] | 751 | |
| 752 | |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 753 | def _ParseCommandArguments(): |
| 754 | """Adds and parses relevant arguments for tool comands. |
| 755 | |
| 756 | Returns: |
| 757 | A dictionary representing the arguments. |
| 758 | """ |
| 759 | arg_parser = argparse.ArgumentParser() |
| 760 | arg_parser.usage = __doc__ |
| 761 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 762 | arg_parser.add_argument( |
| 763 | '-b', |
| 764 | '--build-dir', |
| 765 | type=str, |
| 766 | required=True, |
| 767 | help='The build directory, the path needs to be relative to the root of ' |
| 768 | 'the checkout.') |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 769 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 770 | arg_parser.add_argument( |
| 771 | '-o', |
| 772 | '--output-dir', |
| 773 | type=str, |
| 774 | required=True, |
| 775 | help='Output directory for generated artifacts.') |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 776 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 777 | arg_parser.add_argument( |
| 778 | '-c', |
| 779 | '--command', |
| 780 | action='append', |
| 781 | required=True, |
| 782 | help='Commands used to run test targets, one test target needs one and ' |
| 783 | 'only one command, when specifying commands, one should assume the ' |
| 784 | 'current working directory is the root of the checkout.') |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 785 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 786 | arg_parser.add_argument( |
Yuke Liao | 66da173 | 2017-12-05 22:19:42 | [diff] [blame] | 787 | '-f', |
| 788 | '--filters', |
| 789 | action='append', |
Abhishek Arya | 16f059a | 2017-12-07 17:47:32 | [diff] [blame] | 790 | required=False, |
Yuke Liao | 66da173 | 2017-12-05 22:19:42 | [diff] [blame] | 791 | help='Directories or files to get code coverage for, and all files under ' |
| 792 | 'the directories are included recursively.') |
| 793 | |
| 794 | arg_parser.add_argument( |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 795 | '-j', |
| 796 | '--jobs', |
| 797 | type=int, |
| 798 | default=None, |
| 799 | help='Run N jobs to build in parallel. If not specified, a default value ' |
| 800 | 'will be derived based on CPUs availability. Please refer to ' |
| 801 | '\'ninja -h\' for more details.') |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 802 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 803 | arg_parser.add_argument( |
| 804 | 'targets', nargs='+', help='The names of the test targets to run.') |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 805 | |
| 806 | args = arg_parser.parse_args() |
| 807 | return args |
| 808 | |
| 809 | |
| 810 | def Main(): |
| 811 | """Execute tool commands.""" |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 812 | assert _GetPlatform() in ['linux', 'mac'], ( |
| 813 | 'Coverage is only supported on linux and mac platforms.') |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 814 | assert os.path.abspath(os.getcwd()) == SRC_ROOT_PATH, ('This script must be ' |
| 815 | 'called from the root ' |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 816 | 'of checkout.') |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 817 | DownloadCoverageToolsIfNeeded() |
| 818 | |
| 819 | args = _ParseCommandArguments() |
| 820 | global BUILD_DIR |
| 821 | BUILD_DIR = args.build_dir |
| 822 | global OUTPUT_DIR |
| 823 | OUTPUT_DIR = args.output_dir |
| 824 | |
| 825 | assert len(args.targets) == len(args.command), ('Number of targets must be ' |
| 826 | 'equal to the number of test ' |
| 827 | 'commands.') |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 828 | assert os.path.exists(BUILD_DIR), ( |
| 829 | 'Build directory: {} doesn\'t exist. ' |
| 830 | 'Please run "gn gen" to generate.').format(BUILD_DIR) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 831 | _ValidateBuildingWithClangCoverage() |
Yuke Liao | 95d13d7 | 2017-12-07 18:18:50 | [diff] [blame] | 832 | _VerifyTargetExecutablesAreInBuildDirectory(args.command) |
Abhishek Arya | 16f059a | 2017-12-07 17:47:32 | [diff] [blame] | 833 | |
| 834 | absolute_filter_paths = [] |
Yuke Liao | 66da173 | 2017-12-05 22:19:42 | [diff] [blame] | 835 | if args.filters: |
Abhishek Arya | 16f059a | 2017-12-07 17:47:32 | [diff] [blame] | 836 | absolute_filter_paths = _VerifyPathsAndReturnAbsolutes(args.filters) |
Yuke Liao | 66da173 | 2017-12-05 22:19:42 | [diff] [blame] | 837 | |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 838 | if not os.path.exists(OUTPUT_DIR): |
| 839 | os.makedirs(OUTPUT_DIR) |
| 840 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 841 | profdata_file_path = _CreateCoverageProfileDataForTargets( |
| 842 | args.targets, args.command, args.jobs) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 843 | binary_paths = [_GetBinaryPath(command) for command in args.command] |
Yuke Liao | ea228d0 | 2018-01-05 19:10:33 | [diff] [blame] | 844 | |
| 845 | print('Generating code coverage report in html (this can take a while ' |
| 846 | 'depending on size of target!)') |
Yuke Liao | 66da173 | 2017-12-05 22:19:42 | [diff] [blame] | 847 | _GenerateLineByLineFileCoverageInHtml(binary_paths, profdata_file_path, |
Abhishek Arya | 16f059a | 2017-12-07 17:47:32 | [diff] [blame] | 848 | absolute_filter_paths) |
Yuke Liao | ea228d0 | 2018-01-05 19:10:33 | [diff] [blame] | 849 | _GeneratePerDirectoryCoverageInHtml(binary_paths, profdata_file_path, |
| 850 | absolute_filter_paths) |
| 851 | |
| 852 | # The default index file is generated only for the list of source files, needs |
| 853 | # to overwrite it to display per directory code coverage breakdown. |
| 854 | _OverwriteHtmlReportsIndexFile() |
| 855 | |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 856 | html_index_file_path = 'file://' + os.path.abspath( |
| 857 | os.path.join(OUTPUT_DIR, 'index.html')) |
| 858 | print('\nCode coverage profile data is created as: %s' % profdata_file_path) |
Abhishek Arya | 16f059a | 2017-12-07 17:47:32 | [diff] [blame] | 859 | print('Index file for html report is generated as: %s' % html_index_file_path) |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 860 | |
Abhishek Arya | 1ec832c | 2017-12-05 18:06:59 | [diff] [blame] | 861 | |
Yuke Liao | 506e882 | 2017-12-04 16:52:54 | [diff] [blame] | 862 | if __name__ == '__main__': |
| 863 | sys.exit(Main()) |