blob: 238462f0ba4acbe68126bae4d66fa211dbaff2ba [file] [log] [blame]
Yuke Liaobb571bd62018-10-31 21:51:521#!/usr/bin/env python
2# Copyright 2018 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.
Sajjad Mirzabf9e66a2019-03-07 21:49:065"""Removes code coverage flags from invocations of the Clang C/C++ compiler.
Yuke Liaobb571bd62018-10-31 21:51:526
Sajjad Mirzabf9e66a2019-03-07 21:49:067If the GN arg `use_clang_coverage=true`, this script will be invoked by default.
8GN will add coverage instrumentation flags to almost all source files.
9
10This script is used to remove instrumentation flags from a subset of the source
11files. By default, it will not remove flags from any files. If the option
12--files-to-instrument is passed, this script will remove flags from all files
13except the ones listed in --files-to-instrument.
14
15This script also contains hard-coded exclusion lists of files to never
16instrument, indexed by target operating system. Files in these lists have their
17flags removed in both modes. The OS can be selected with --target-os.
Yuke Liaobb571bd62018-10-31 21:51:5218
Sajjad Mirza18f89f22019-12-20 21:18:1219This script also contains hard-coded force lists of files to always instrument,
20indexed by target operating system. Files in these lists never have their flags
21removed in either mode. The OS can be selected with --target-os.
22
23The order of precedence is: force list, exclusion list, --files-to-instrument.
24
Yuke Liaobb571bd62018-10-31 21:51:5225The path to the coverage instrumentation input file should be relative to the
26root build directory, and the file consists of multiple lines where each line
27represents a path to a source file, and the specified paths must be relative to
28the root build directory. e.g. ../../base/task/post_task.cc for build
Sajjad Mirza18f89f22019-12-20 21:18:1229directory 'out/Release'. The paths should be written using OS-native path
30separators for the current platform.
Yuke Liaobb571bd62018-10-31 21:51:5231
32One caveat with this compiler wrapper is that it may introduce unexpected
33behaviors in incremental builds when the file path to the coverage
34instrumentation input file changes between consecutive runs, so callers of this
35script are strongly advised to always use the same path such as
36"${root_build_dir}/coverage_instrumentation_input.txt".
37
38It's worth noting on try job builders, if the contents of the instrumentation
39file changes so that a file doesn't need to be instrumented any longer, it will
40be recompiled automatically because if try job B runs after try job A, the files
41that were instrumented in A will be updated (i.e., reverted to the checked in
42version) in B, and so they'll be considered out of date by ninja and recompiled.
43
44Example usage:
45 clang_code_coverage_wrapper.py \\
46 --files-to-instrument=coverage_instrumentation_input.txt
47"""
48
Raul Tambre9e24293b2019-05-12 06:11:0749from __future__ import print_function
50
Yuke Liaobb571bd62018-10-31 21:51:5251import argparse
52import os
53import subprocess
54import sys
55
56# Flags used to enable coverage instrumentation.
Sajjad Mirzabf9e66a2019-03-07 21:49:0657# Flags should be listed in the same order that they are added in
58# build/config/coverage/BUILD.gn
Yuke Liao5eff7822019-02-28 03:56:2459_COVERAGE_FLAGS = [
Sajjad Mirza18f89f22019-12-20 21:18:1260 '-fprofile-instr-generate',
61 '-fcoverage-mapping',
Sajjad Mirza49c00e32019-03-01 22:46:5262 # Following experimental flags remove unused header functions from the
63 # coverage mapping data embedded in the test binaries, and the reduction
64 # of binary size enables building Chrome's large unit test targets on
65 # MacOS. Please refer to crbug.com/796290 for more details.
Sajjad Mirza18f89f22019-12-20 21:18:1266 '-mllvm',
67 '-limited-coverage-experimental=true',
Yuke Liao5eff7822019-02-28 03:56:2468]
Yuke Liaobb571bd62018-10-31 21:51:5269
Sajjad Mirza750bd0b2019-10-16 23:39:5170# Files that should not be built with coverage flags by default.
71_DEFAULT_COVERAGE_EXCLUSION_LIST = []
72
Sajjad Mirzabf9e66a2019-03-07 21:49:0673# Map of exclusion lists indexed by target OS.
74# If no target OS is defined, or one is defined that doesn't have a specific
Sajjad Mirza750bd0b2019-10-16 23:39:5175# entry, use _DEFAULT_COVERAGE_EXCLUSION_LIST.
Sajjad Mirzabf9e66a2019-03-07 21:49:0676_COVERAGE_EXCLUSION_LIST_MAP = {
Yun Liue643df752019-10-25 19:11:3377 'android': [
78 # This file caused webview native library failed on arm64.
79 '../../device/gamepad/dualshock4_controller.cc',
80 ],
Yuke Liao8098d702019-08-05 23:57:4181 'linux': [
82 # These files caused a static initializer to be generated, which
83 # shouldn't.
84 # TODO(crbug.com/990948): Remove when the bug is fixed.
Sajjad Mirza750bd0b2019-10-16 23:39:5185 '../../chrome/browser/media/router/providers/cast/cast_internal_message_util.cc', #pylint: disable=line-too-long
Yuke Liao8098d702019-08-05 23:57:4186 '../../chrome/common/media_router/providers/cast/cast_media_source.cc',
87 '../../components/cast_channel/cast_channel_enum.cc',
Sajjad Mirza750bd0b2019-10-16 23:39:5188 '../../components/cast_channel/cast_message_util.cc',
Yuke Liao8098d702019-08-05 23:57:4189 ],
Sajjad Mirzabf9e66a2019-03-07 21:49:0690 'chromeos': [
91 # These files caused clang to crash while compiling them. They are
92 # excluded pending an investigation into the underlying compiler bug.
93 '../../third_party/webrtc/p2p/base/p2p_transport_channel.cc',
94 '../../third_party/icu/source/common/uts46.cpp',
95 '../../third_party/icu/source/common/ucnvmbcs.cpp',
96 '../../base/android/android_image_reader_compat.cc',
Sajjad Mirza750bd0b2019-10-16 23:39:5197 ],
98 'win': [],
Sajjad Mirzabf9e66a2019-03-07 21:49:0699}
100
Sajjad Mirza18f89f22019-12-20 21:18:12101# Map of force lists indexed by target OS.
102_COVERAGE_FORCE_LIST_MAP = {
103 # clang_coverage.cc refers to the symbol `__llvm_profile_dump` from the
104 # profiling runtime. In a partial coverage build, it is possible for a
105 # binary to include clang_coverage.cc but have no instrumented files, thus
106 # causing an unresolved symbol error because the profiling runtime will not
107 # be linked in. Therefore we force coverage for this file to ensure that
108 # any target that includes it will also get the profiling runtime.
109 'win': [r'..\..\base\test\clang_coverage.cc'],
110}
Sajjad Mirzabf9e66a2019-03-07 21:49:06111
Sajjad Mirza750bd0b2019-10-16 23:39:51112
Sajjad Mirzabf9e66a2019-03-07 21:49:06113def _remove_flags_from_command(command):
114 # We need to remove the coverage flags for this file, but we only want to
115 # remove them if we see the exact sequence defined in _COVERAGE_FLAGS.
116 # That ensures that we only remove the flags added by GN when
117 # "use_clang_coverage" is true. Otherwise, we would remove flags set by
118 # other parts of the build system.
119 start_flag = _COVERAGE_FLAGS[0]
120 num_flags = len(_COVERAGE_FLAGS)
121 start_idx = 0
122 try:
123 while True:
124 idx = command.index(start_flag, start_idx)
125 start_idx = idx + 1
Sajjad Mirza18f89f22019-12-20 21:18:12126 if command[idx:idx + num_flags] == _COVERAGE_FLAGS:
127 del command[idx:idx + num_flags]
Sajjad Mirzabf9e66a2019-03-07 21:49:06128 break
129 except ValueError:
130 pass
Yuke Liaobb571bd62018-10-31 21:51:52131
Sajjad Mirza18f89f22019-12-20 21:18:12132
Yuke Liaobb571bd62018-10-31 21:51:52133def main():
134 # TODO(crbug.com/898695): Make this wrapper work on Windows platform.
135 arg_parser = argparse.ArgumentParser()
136 arg_parser.usage = __doc__
137 arg_parser.add_argument(
138 '--files-to-instrument',
139 type=str,
Yuke Liaobb571bd62018-10-31 21:51:52140 help='Path to a file that contains a list of file names to instrument.')
Sajjad Mirzabf9e66a2019-03-07 21:49:06141 arg_parser.add_argument(
Sajjad Mirza18f89f22019-12-20 21:18:12142 '--target-os', required=False, help='The OS to compile for.')
Yuke Liaobb571bd62018-10-31 21:51:52143 arg_parser.add_argument('args', nargs=argparse.REMAINDER)
144 parsed_args = arg_parser.parse_args()
145
Sajjad Mirzabf9e66a2019-03-07 21:49:06146 if (parsed_args.files_to_instrument and
147 not os.path.isfile(parsed_args.files_to_instrument)):
Yuke Liaobb571bd62018-10-31 21:51:52148 raise Exception('Path to the coverage instrumentation file: "%s" doesn\'t '
149 'exist.' % parsed_args.files_to_instrument)
150
151 compile_command = parsed_args.args
Sajjad Mirzabf9e66a2019-03-07 21:49:06152 if not any('clang' in s for s in compile_command):
153 return subprocess.call(compile_command)
154
Sajjad Mirza750bd0b2019-10-16 23:39:51155 target_os = parsed_args.target_os
156
Yuke Liaobb571bd62018-10-31 21:51:52157 try:
158 # The command is assumed to use Clang as the compiler, and the path to the
159 # source file is behind the -c argument, and the path to the source path is
160 # relative to the root build directory. For example:
161 # clang++ -fvisibility=hidden -c ../../base/files/file_path.cc -o \
162 # obj/base/base/file_path.o
Sajjad Mirza750bd0b2019-10-16 23:39:51163 # On Windows, clang-cl.exe uses /c instead of -c.
164 source_flag = '/c' if target_os == 'win' else '-c'
165 source_flag_index = compile_command.index(source_flag)
Yuke Liaobb571bd62018-10-31 21:51:52166 except ValueError:
Sajjad Mirza750bd0b2019-10-16 23:39:51167 print('%s argument is not found in the compile command.' % source_flag)
Yuke Liaobb571bd62018-10-31 21:51:52168 raise
169
Sajjad Mirza750bd0b2019-10-16 23:39:51170 if source_flag_index + 1 >= len(compile_command):
Yuke Liaobb571bd62018-10-31 21:51:52171 raise Exception('Source file to be compiled is missing from the command.')
172
Sajjad Mirzae677802c2019-12-18 21:51:59173 # On Windows, filesystem paths should use '\', but GN creates build commands
174 # that use '/'. We invoke os.path.normpath to ensure that the path uses the
175 # correct separator for the current platform (i.e. '\' on Windows and '/'
176 # otherwise).
177 compile_source_file = os.path.normpath(compile_command[source_flag_index + 1])
Sajjad Mirza750bd0b2019-10-16 23:39:51178 exclusion_list = _COVERAGE_EXCLUSION_LIST_MAP.get(
179 target_os, _DEFAULT_COVERAGE_EXCLUSION_LIST)
Sajjad Mirza18f89f22019-12-20 21:18:12180 force_list = _COVERAGE_FORCE_LIST_MAP.get(target_os, [])
Sajjad Mirzabf9e66a2019-03-07 21:49:06181
Sajjad Mirza18f89f22019-12-20 21:18:12182 should_remove_flags = False
183 if compile_source_file not in force_list:
184 if compile_source_file in exclusion_list:
185 should_remove_flags = True
186 elif parsed_args.files_to_instrument:
187 with open(parsed_args.files_to_instrument) as f:
188 if compile_source_file not in f.read():
189 should_remove_flags = True
190
191 if should_remove_flags:
Sajjad Mirzabf9e66a2019-03-07 21:49:06192 _remove_flags_from_command(compile_command)
Yuke Liaobb571bd62018-10-31 21:51:52193
194 return subprocess.call(compile_command)
195
Sajjad Mirza18f89f22019-12-20 21:18:12196
Yuke Liaobb571bd62018-10-31 21:51:52197if __name__ == '__main__':
198 sys.exit(main())