blob: a5b34c0d498154b142b2ea09236d3740d8cbc35c [file] [log] [blame]
Pirama Arumuga Nainarc41549f2021-03-25 16:31:17 -07001#!/usr/bin/env python3
2#
Roland Levillaind203b9e2021-05-13 16:19:45 +01003# Copyright (C) 2021 The Android Open Source Project
Pirama Arumuga Nainarc41549f2021-03-25 16:31:17 -07004#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17# acov-llvm.py is a tool for gathering coverage information from a device and
18# generating an LLVM coverage report from that information. To use:
19#
20# This script would work only when the device image was built with the following
21# build variables:
22# CLANG_COVERAGE=true NATIVE_COVERAGE_PATHS="<list-of-paths>"
23#
24# 1. [optional] Reset coverage information on the device
25# $ acov-llvm.py clean-device
26#
27# 2. Run tests
28#
29# 3. Flush coverage
30# from select daemons and system processes on the device
31# $ acov-llvm.py flush [list of process names]
32# or from all processes on the device:
33# $ acov-llvm.py flush
34#
Roland Levillaind203b9e2021-05-13 16:19:45 +010035# 4. Pull coverage from device and generate coverage report
Pirama Arumuga Nainarc41549f2021-03-25 16:31:17 -070036# $ acov-llvm.py report -s <one-or-more-source-paths-in-$ANDROID_BUILD_TOP \
37# -b <one-or-more-binaries-in-$OUT> \
38# E.g.:
Roland Levillaind203b9e2021-05-13 16:19:45 +010039# acov-llvm.py report \
Pirama Arumuga Nainarc41549f2021-03-25 16:31:17 -070040# -s bionic \
41# -b \
42# $OUT/symbols/apex/com.android.runtime/lib/bionic/libc.so \
43# $OUT/symbols/apex/com.android.runtime/lib/bionic/libm.so
44
45import argparse
46import logging
47import os
48import re
49import subprocess
50import time
51import tempfile
52
53from pathlib import Path
54
55FLUSH_SLEEP = 60
56
57
58def android_build_top():
59 return Path(os.environ.get('ANDROID_BUILD_TOP', None))
60
61
62def _get_clang_revision():
Pirama Arumuga Nainarbeb6fb72021-04-27 21:55:54 -070063 regex = r'ClangDefaultVersion\s+= "(?P<rev>clang-r\d+[a-z]?)"'
Pirama Arumuga Nainarc41549f2021-03-25 16:31:17 -070064 global_go = android_build_top() / 'build/soong/cc/config/global.go'
65 with open(global_go) as infile:
66 match = re.search(regex, infile.read())
67
68 if match is None:
69 raise RuntimeError(f'Parsing clang info from {global_go} failed')
70 return match.group('rev')
71
72
73CLANG_TOP = android_build_top() / 'prebuilts/clang/host/linux-x86/' \
74 / _get_clang_revision()
75LLVM_PROFDATA_PATH = CLANG_TOP / 'bin' / 'llvm-profdata'
76LLVM_COV_PATH = CLANG_TOP / 'bin' / 'llvm-cov'
77
78
79def check_output(cmd, *args, **kwargs):
80 """subprocess.check_output with logging."""
81 cmd_str = cmd if isinstance(cmd, str) else ' '.join(cmd)
82 logging.debug(cmd_str)
83 return subprocess.run(
84 cmd, *args, **kwargs, check=True, stdout=subprocess.PIPE).stdout
85
86
Roland Levillaind203b9e2021-05-13 16:19:45 +010087def adb(cmd, *args, **kwargs):
88 """call 'adb <cmd>' with logging."""
89 return check_output(['adb'] + cmd, *args, **kwargs)
90
91
92def adb_root(*args, **kwargs):
93 """call 'adb root' with logging."""
94 return adb(['root'], *args, **kwargs)
95
96
Pirama Arumuga Nainarc41549f2021-03-25 16:31:17 -070097def adb_shell(cmd, *args, **kwargs):
98 """call 'adb shell <cmd>' with logging."""
Roland Levillaind203b9e2021-05-13 16:19:45 +010099 return adb(['shell'] + cmd, *args, **kwargs)
Pirama Arumuga Nainarbeb6fb72021-04-27 21:55:54 -0700100
101
102def send_flush_signal(pids=None):
103
104 def _has_handler_sig37(pid):
105 try:
106 status = adb_shell(['cat', f'/proc/{pid}/status'],
107 text=True,
108 stderr=subprocess.DEVNULL)
109 except subprocess.CalledProcessError:
110 logging.warning(f'Process {pid} is no longer active')
111 return False
112
113 status = status.split('\n')
114 sigcgt = [
115 line.split(':\t')[1] for line in status if line.startswith('SigCgt')
116 ]
117 if not sigcgt:
118 logging.warning(f'Cannot find \'SigCgt:\' in /proc/{pid}/status')
119 return False
120 return int(sigcgt[0], base=16) & (1 << 36)
121
122 if not pids:
123 output = adb_shell(['ps', '-eo', 'pid'], text=True)
124 pids = [pid.strip() for pid in output.split()]
125 pids = pids[1:] # ignore the column header
126 pids = [pid for pid in pids if _has_handler_sig37(pid)]
127
128 if not pids:
129 logging.warning(
130 f'couldn\'t find any process with handler for signal 37')
131
132 adb_shell(['kill', '-37'] + pids)
Pirama Arumuga Nainarc41549f2021-03-25 16:31:17 -0700133
134
135def do_clean_device(args):
Roland Levillaind203b9e2021-05-13 16:19:45 +0100136 adb_root()
Pirama Arumuga Nainarbeb6fb72021-04-27 21:55:54 -0700137
Pirama Arumuga Nainarc41549f2021-03-25 16:31:17 -0700138 logging.info('resetting coverage on device')
Pirama Arumuga Nainarbeb6fb72021-04-27 21:55:54 -0700139 send_flush_signal()
Pirama Arumuga Nainarc41549f2021-03-25 16:31:17 -0700140
141 logging.info(
142 f'sleeping for {FLUSH_SLEEP} seconds for coverage to be written')
143 time.sleep(FLUSH_SLEEP)
144
145 logging.info('deleting coverage data from device')
146 adb_shell(['rm', '-rf', '/data/misc/trace/*.profraw'])
147
148
149def do_flush(args):
Roland Levillaind203b9e2021-05-13 16:19:45 +0100150 adb_root()
Pirama Arumuga Nainarbeb6fb72021-04-27 21:55:54 -0700151
Pirama Arumuga Nainarc41549f2021-03-25 16:31:17 -0700152 if args.procnames:
153 pids = adb_shell(['pidof'] + args.procnames, text=True).split()
154 logging.info(f'flushing coverage for pids: {pids}')
155 else:
Pirama Arumuga Nainarbeb6fb72021-04-27 21:55:54 -0700156 pids = None
Pirama Arumuga Nainarc41549f2021-03-25 16:31:17 -0700157 logging.info('flushing coverage for all processes on device')
158
Pirama Arumuga Nainarbeb6fb72021-04-27 21:55:54 -0700159 send_flush_signal(pids)
Pirama Arumuga Nainarc41549f2021-03-25 16:31:17 -0700160
161 logging.info(
162 f'sleeping for {FLUSH_SLEEP} seconds for coverage to be written')
163 time.sleep(FLUSH_SLEEP)
164
165
166def do_report(args):
Roland Levillaind203b9e2021-05-13 16:19:45 +0100167 adb_root()
Pirama Arumuga Nainarbeb6fb72021-04-27 21:55:54 -0700168
Pirama Arumuga Nainarc41549f2021-03-25 16:31:17 -0700169 temp_dir = tempfile.mkdtemp(
170 prefix='covreport-', dir=os.environ.get('ANDROID_BUILD_TOP', None))
171 logging.info(f'generating coverage report in {temp_dir}')
172
173 # Pull coverage files from /data/misc/trace on the device
174 compressed = adb_shell(['tar', '-czf', '-', '-C', '/data/misc', 'trace'])
175 check_output(['tar', 'zxvf', '-', '-C', temp_dir], input=compressed)
176
177 # Call llvm-profdata followed by llvm-cov
178 profdata = f'{temp_dir}/merged.profdata'
179 check_output(
180 f'{LLVM_PROFDATA_PATH} merge --failure-mode=all --output={profdata} {temp_dir}/trace/*.profraw',
181 shell=True)
182
183 object_flags = [args.binary[0]] + ['--object=' + b for b in args.binary[1:]]
184 source_dirs = ['/proc/self/cwd/' + s for s in args.source_dir]
185
186 check_output([
187 str(LLVM_COV_PATH), 'show', f'--instr-profile={profdata}',
188 '--format=html', f'--output-dir={temp_dir}/html',
189 '--show-region-summary=false'
190 ] + object_flags + source_dirs)
191
192
193def parse_args():
194 parser = argparse.ArgumentParser()
195 parser.add_argument(
196 '-v',
197 '--verbose',
198 action='store_true',
199 default=False,
200 help='enable debug logging')
201
202 subparsers = parser.add_subparsers(dest='command', required=True)
203
204 clean_device = subparsers.add_parser(
205 'clean-device', help='reset coverage on device')
206 clean_device.set_defaults(func=do_clean_device)
207
208 flush = subparsers.add_parser(
209 'flush', help='flush coverage for processes on device')
210 flush.add_argument(
211 'procnames',
212 nargs='*',
213 metavar='PROCNAME',
214 help='flush coverage for one or more processes with name PROCNAME')
215 flush.set_defaults(func=do_flush)
216
217 report = subparsers.add_parser(
218 'report', help='fetch coverage from device and generate report')
219 report.add_argument(
220 '-b',
221 '--binary',
222 nargs='+',
223 metavar='BINARY',
224 action='extend',
225 required=True,
226 help='generate coverage report for BINARY')
227 report.add_argument(
228 '-s',
229 '--source-dir',
230 nargs='+',
231 action='extend',
232 metavar='PATH',
233 required=True,
234 help='generate coverage report for source files in PATH')
235 report.set_defaults(func=do_report)
236 return parser.parse_args()
237
238
239def main():
240 args = parse_args()
241 if args.verbose:
242 logging.basicConfig(level=logging.DEBUG)
243
244 args.func(args)
245
246
247if __name__ == '__main__':
248 main()