blob: 9c38d7122858e43153ea91fa79bd4e7f4540e57b [file] [log] [blame]
Takuto Ikuta3dab32e02023-01-12 18:52:001#!/usr/bin/env python3
Avi Drissman73a09d12022-09-08 20:33:382# Copyright 2018 The Chromium Authors
Yuke Liaobb571bd62018-10-31 21:51:523# 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
Junji Watanabe9bd33642023-07-05 16:27:1747
48Siso implements the same logic in
49build/config/siso/clang_code_coverage_wrapper.star, which avoids the wrapper
50invocations for remote execution and performance improvement.
51Please update the Siso starlark file when updating this file.
Yuke Liaobb571bd62018-10-31 21:51:5252"""
Richard Wang91cc90f2023-07-25 16:49:1253# LINT.IfChange
Raul Tambre9e24293b2019-05-12 06:11:0754
Yuke Liaobb571bd62018-10-31 21:51:5255import argparse
56import os
57import subprocess
58import sys
59
60# Flags used to enable coverage instrumentation.
Sajjad Mirzabf9e66a2019-03-07 21:49:0661# Flags should be listed in the same order that they are added in
62# build/config/coverage/BUILD.gn
Yuke Liao5eff7822019-02-28 03:56:2463_COVERAGE_FLAGS = [
Sajjad Mirza18f89f22019-12-20 21:18:1264 '-fprofile-instr-generate',
65 '-fcoverage-mapping',
Alan Zhaof8fa31302024-01-11 03:35:3966 '-mllvm',
67 '-runtime-counter-relocation=true',
Sajjad Mirza49c00e32019-03-01 22:46:5268 # Following experimental flags remove unused header functions from the
69 # coverage mapping data embedded in the test binaries, and the reduction
70 # of binary size enables building Chrome's large unit test targets on
71 # MacOS. Please refer to crbug.com/796290 for more details.
Sajjad Mirza18f89f22019-12-20 21:18:1272 '-mllvm',
73 '-limited-coverage-experimental=true',
Yuke Liao5eff7822019-02-28 03:56:2474]
Yuke Liaobb571bd62018-10-31 21:51:5275
Sajjad Mirza750bd0b2019-10-16 23:39:5176# Files that should not be built with coverage flags by default.
Junji Watanabe782802c2023-06-30 08:08:1277_DEFAULT_COVERAGE_EXCLUSION_LIST = []
Sajjad Mirza750bd0b2019-10-16 23:39:5178
Sajjad Mirzabf9e66a2019-03-07 21:49:0679# Map of exclusion lists indexed by target OS.
80# If no target OS is defined, or one is defined that doesn't have a specific
Sajjad Mirza750bd0b2019-10-16 23:39:5181# entry, use _DEFAULT_COVERAGE_EXCLUSION_LIST.
Sajjad Mirzabf9e66a2019-03-07 21:49:0682_COVERAGE_EXCLUSION_LIST_MAP = {
Yun Liue643df752019-10-25 19:11:3383 'android': [
84 # This file caused webview native library failed on arm64.
85 '../../device/gamepad/dualshock4_controller.cc',
86 ],
Chong Gu1809f312021-02-17 18:12:4087 'fuchsia': [
Alison Galed965ba02024-04-26 21:50:5488 # TODO(crbug.com/40167659): These files caused clang to crash while
Chong Gu1809f312021-02-17 18:12:4089 # compiling them.
Chong Gu1809f312021-02-17 18:12:4090 '../../third_party/skia/src/core/SkOpts.cpp',
91 '../../third_party/skia/src/opts/SkOpts_hsw.cpp',
92 '../../third_party/skia/third_party/skcms/skcms.cc',
93 ],
Yuke Liao8098d702019-08-05 23:57:4194 'linux': [
95 # These files caused a static initializer to be generated, which
96 # shouldn't.
Alison Gale3a3959162024-04-29 18:52:4497 # TODO(crbug.com/41474559): Remove when the bug is fixed.
Sajjad Mirza750bd0b2019-10-16 23:39:5198 '../../chrome/browser/media/router/providers/cast/cast_internal_message_util.cc', #pylint: disable=line-too-long
mark a. foltz5cb60682022-10-05 17:43:1299 '../../components/media_router/common/providers/cast/channel/cast_channel_enum.cc', #pylint: disable=line-too-long
100 '../../components/media_router/common/providers/cast/channel/cast_message_util.cc', #pylint: disable=line-too-long
Zhaoyang Li75408932020-10-13 19:06:34101 '../../components/media_router/common/providers/cast/cast_media_source.cc', #pylint: disable=line-too-long
Yuke Liao40543c9f72020-01-07 18:27:04102 '../../ui/events/keycodes/dom/keycode_converter.cc',
Yuke Liao8098d702019-08-05 23:57:41103 ],
Sajjad Mirzabf9e66a2019-03-07 21:49:06104 'chromeos': [
105 # These files caused clang to crash while compiling them. They are
106 # excluded pending an investigation into the underlying compiler bug.
107 '../../third_party/webrtc/p2p/base/p2p_transport_channel.cc',
108 '../../third_party/icu/source/common/uts46.cpp',
109 '../../third_party/icu/source/common/ucnvmbcs.cpp',
110 '../../base/android/android_image_reader_compat.cc',
Olivier Li0504bb02020-02-14 17:06:22111 ],
Sajjad Mirzabf9e66a2019-03-07 21:49:06112}
113
Sajjad Mirza18f89f22019-12-20 21:18:12114# Map of force lists indexed by target OS.
115_COVERAGE_FORCE_LIST_MAP = {
Sebastien Marchandbd02bc29e2020-03-11 15:53:36116 # clang_profiling.cc refers to the symbol `__llvm_profile_dump` from the
Sajjad Mirza18f89f22019-12-20 21:18:12117 # profiling runtime. In a partial coverage build, it is possible for a
Sebastien Marchandbd02bc29e2020-03-11 15:53:36118 # binary to include clang_profiling.cc but have no instrumented files, thus
Sajjad Mirza18f89f22019-12-20 21:18:12119 # causing an unresolved symbol error because the profiling runtime will not
120 # be linked in. Therefore we force coverage for this file to ensure that
121 # any target that includes it will also get the profiling runtime.
Sebastien Marchandbd02bc29e2020-03-11 15:53:36122 'win': [r'..\..\base\test\clang_profiling.cc'],
Alison Galed965ba02024-04-26 21:50:54123 # TODO(crbug.com/40154378) We're seeing runtime LLVM errors in mac-rel when
Sajjad Mirza72b3140d2020-11-25 16:45:03124 # no files are changed, so we suspect that this is similar to the other
125 # problem with clang_profiling.cc on Windows. The TODO here is to force
126 # coverage for this specific file on ALL platforms, if it turns out to fix
127 # this issue on Mac as well. It's the only file that directly calls
128 # `__llvm_profile_dump` so it warrants some special treatment.
129 'mac': ['../../base/test/clang_profiling.cc'],
Sajjad Mirza18f89f22019-12-20 21:18:12130}
Sajjad Mirzabf9e66a2019-03-07 21:49:06131
Sajjad Mirza750bd0b2019-10-16 23:39:51132
Sajjad Mirzabf9e66a2019-03-07 21:49:06133def _remove_flags_from_command(command):
134 # We need to remove the coverage flags for this file, but we only want to
135 # remove them if we see the exact sequence defined in _COVERAGE_FLAGS.
136 # That ensures that we only remove the flags added by GN when
137 # "use_clang_coverage" is true. Otherwise, we would remove flags set by
138 # other parts of the build system.
139 start_flag = _COVERAGE_FLAGS[0]
140 num_flags = len(_COVERAGE_FLAGS)
141 start_idx = 0
142 try:
143 while True:
144 idx = command.index(start_flag, start_idx)
Sajjad Mirza18f89f22019-12-20 21:18:12145 if command[idx:idx + num_flags] == _COVERAGE_FLAGS:
146 del command[idx:idx + num_flags]
Zhaoyang Li75408932020-10-13 19:06:34147 # There can be multiple sets of _COVERAGE_FLAGS. All of these need to be
148 # removed.
149 start_idx = idx
150 else:
151 start_idx = idx + 1
Sajjad Mirzabf9e66a2019-03-07 21:49:06152 except ValueError:
153 pass
Yuke Liaobb571bd62018-10-31 21:51:52154
Sajjad Mirza18f89f22019-12-20 21:18:12155
Yuke Liaobb571bd62018-10-31 21:51:52156def main():
Yuke Liaobb571bd62018-10-31 21:51:52157 arg_parser = argparse.ArgumentParser()
158 arg_parser.usage = __doc__
159 arg_parser.add_argument(
160 '--files-to-instrument',
161 type=str,
Yuke Liaobb571bd62018-10-31 21:51:52162 help='Path to a file that contains a list of file names to instrument.')
Sajjad Mirzabf9e66a2019-03-07 21:49:06163 arg_parser.add_argument(
Sajjad Mirza18f89f22019-12-20 21:18:12164 '--target-os', required=False, help='The OS to compile for.')
Yuke Liaobb571bd62018-10-31 21:51:52165 arg_parser.add_argument('args', nargs=argparse.REMAINDER)
166 parsed_args = arg_parser.parse_args()
167
Sajjad Mirzabf9e66a2019-03-07 21:49:06168 if (parsed_args.files_to_instrument and
169 not os.path.isfile(parsed_args.files_to_instrument)):
Yuke Liaobb571bd62018-10-31 21:51:52170 raise Exception('Path to the coverage instrumentation file: "%s" doesn\'t '
171 'exist.' % parsed_args.files_to_instrument)
172
173 compile_command = parsed_args.args
Sajjad Mirzabf9e66a2019-03-07 21:49:06174 if not any('clang' in s for s in compile_command):
175 return subprocess.call(compile_command)
176
Sajjad Mirza750bd0b2019-10-16 23:39:51177 target_os = parsed_args.target_os
178
Yuke Liaobb571bd62018-10-31 21:51:52179 try:
180 # The command is assumed to use Clang as the compiler, and the path to the
181 # source file is behind the -c argument, and the path to the source path is
182 # relative to the root build directory. For example:
183 # clang++ -fvisibility=hidden -c ../../base/files/file_path.cc -o \
184 # obj/base/base/file_path.o
Sajjad Mirza750bd0b2019-10-16 23:39:51185 # On Windows, clang-cl.exe uses /c instead of -c.
186 source_flag = '/c' if target_os == 'win' else '-c'
187 source_flag_index = compile_command.index(source_flag)
Yuke Liaobb571bd62018-10-31 21:51:52188 except ValueError:
Sajjad Mirza750bd0b2019-10-16 23:39:51189 print('%s argument is not found in the compile command.' % source_flag)
Yuke Liaobb571bd62018-10-31 21:51:52190 raise
191
Sajjad Mirza750bd0b2019-10-16 23:39:51192 if source_flag_index + 1 >= len(compile_command):
Yuke Liaobb571bd62018-10-31 21:51:52193 raise Exception('Source file to be compiled is missing from the command.')
194
Sajjad Mirzae677802c2019-12-18 21:51:59195 # On Windows, filesystem paths should use '\', but GN creates build commands
196 # that use '/'. We invoke os.path.normpath to ensure that the path uses the
197 # correct separator for the current platform (i.e. '\' on Windows and '/'
198 # otherwise).
199 compile_source_file = os.path.normpath(compile_command[source_flag_index + 1])
Bruce Dawson09c1bd02021-06-26 00:06:11200 extension = os.path.splitext(compile_source_file)[1]
201 if not extension in ['.c', '.cc', '.cpp', '.cxx', '.m', '.mm', '.S']:
202 raise Exception('Invalid source file %s found' % compile_source_file)
Sajjad Mirza750bd0b2019-10-16 23:39:51203 exclusion_list = _COVERAGE_EXCLUSION_LIST_MAP.get(
204 target_os, _DEFAULT_COVERAGE_EXCLUSION_LIST)
Sajjad Mirza18f89f22019-12-20 21:18:12205 force_list = _COVERAGE_FORCE_LIST_MAP.get(target_os, [])
Sajjad Mirzabf9e66a2019-03-07 21:49:06206
Sajjad Mirza18f89f22019-12-20 21:18:12207 should_remove_flags = False
208 if compile_source_file not in force_list:
209 if compile_source_file in exclusion_list:
210 should_remove_flags = True
211 elif parsed_args.files_to_instrument:
212 with open(parsed_args.files_to_instrument) as f:
213 if compile_source_file not in f.read():
214 should_remove_flags = True
215
216 if should_remove_flags:
Sajjad Mirzabf9e66a2019-03-07 21:49:06217 _remove_flags_from_command(compile_command)
Yuke Liaobb571bd62018-10-31 21:51:52218
219 return subprocess.call(compile_command)
220
Sajjad Mirza18f89f22019-12-20 21:18:12221
Yuke Liaobb571bd62018-10-31 21:51:52222if __name__ == '__main__':
223 sys.exit(main())
Richard Wang91cc90f2023-07-25 16:49:12224
225# LINT.ThenChange(/build/config/siso/clang_code_coverage_wrapper.star)