blob: a6f35e34a00e630b95a2bb4845eb2755ce62d268 [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
Roland Levillaine6d27362022-04-05 10:57:26 +010036# $ acov-llvm.py report -s <one-or-more-source-paths-in-$ANDROID_BUILD_TOP> \
Pirama Arumuga Nainarc41549f2021-03-25 16:31:17 -070037# -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 Nainarf7f95442021-06-30 13:31:41 -070063 version_output = subprocess.check_output(
64 android_build_top() / 'build/soong/scripts/get_clang_version.py',
65 text=True)
66 return version_output.strip()
Pirama Arumuga Nainarc41549f2021-03-25 16:31:17 -070067
68
69CLANG_TOP = android_build_top() / 'prebuilts/clang/host/linux-x86/' \
70 / _get_clang_revision()
71LLVM_PROFDATA_PATH = CLANG_TOP / 'bin' / 'llvm-profdata'
72LLVM_COV_PATH = CLANG_TOP / 'bin' / 'llvm-cov'
73
74
75def check_output(cmd, *args, **kwargs):
76 """subprocess.check_output with logging."""
77 cmd_str = cmd if isinstance(cmd, str) else ' '.join(cmd)
78 logging.debug(cmd_str)
79 return subprocess.run(
80 cmd, *args, **kwargs, check=True, stdout=subprocess.PIPE).stdout
81
82
Roland Levillaind203b9e2021-05-13 16:19:45 +010083def adb(cmd, *args, **kwargs):
84 """call 'adb <cmd>' with logging."""
85 return check_output(['adb'] + cmd, *args, **kwargs)
86
87
88def adb_root(*args, **kwargs):
89 """call 'adb root' with logging."""
90 return adb(['root'], *args, **kwargs)
91
92
Pirama Arumuga Nainarc41549f2021-03-25 16:31:17 -070093def adb_shell(cmd, *args, **kwargs):
94 """call 'adb shell <cmd>' with logging."""
Roland Levillaind203b9e2021-05-13 16:19:45 +010095 return adb(['shell'] + cmd, *args, **kwargs)
Pirama Arumuga Nainarbeb6fb72021-04-27 21:55:54 -070096
97
98def send_flush_signal(pids=None):
99
100 def _has_handler_sig37(pid):
101 try:
102 status = adb_shell(['cat', f'/proc/{pid}/status'],
103 text=True,
104 stderr=subprocess.DEVNULL)
105 except subprocess.CalledProcessError:
106 logging.warning(f'Process {pid} is no longer active')
107 return False
108
109 status = status.split('\n')
110 sigcgt = [
111 line.split(':\t')[1] for line in status if line.startswith('SigCgt')
112 ]
113 if not sigcgt:
114 logging.warning(f'Cannot find \'SigCgt:\' in /proc/{pid}/status')
115 return False
116 return int(sigcgt[0], base=16) & (1 << 36)
117
118 if not pids:
119 output = adb_shell(['ps', '-eo', 'pid'], text=True)
120 pids = [pid.strip() for pid in output.split()]
121 pids = pids[1:] # ignore the column header
122 pids = [pid for pid in pids if _has_handler_sig37(pid)]
123
124 if not pids:
125 logging.warning(
126 f'couldn\'t find any process with handler for signal 37')
127
128 adb_shell(['kill', '-37'] + pids)
Pirama Arumuga Nainarc41549f2021-03-25 16:31:17 -0700129
130
131def do_clean_device(args):
Roland Levillaind203b9e2021-05-13 16:19:45 +0100132 adb_root()
Pirama Arumuga Nainarbeb6fb72021-04-27 21:55:54 -0700133
Pirama Arumuga Nainarc41549f2021-03-25 16:31:17 -0700134 logging.info('resetting coverage on device')
Pirama Arumuga Nainarbeb6fb72021-04-27 21:55:54 -0700135 send_flush_signal()
Pirama Arumuga Nainarc41549f2021-03-25 16:31:17 -0700136
137 logging.info(
138 f'sleeping for {FLUSH_SLEEP} seconds for coverage to be written')
139 time.sleep(FLUSH_SLEEP)
140
141 logging.info('deleting coverage data from device')
142 adb_shell(['rm', '-rf', '/data/misc/trace/*.profraw'])
143
144
145def do_flush(args):
Roland Levillaind203b9e2021-05-13 16:19:45 +0100146 adb_root()
Pirama Arumuga Nainarbeb6fb72021-04-27 21:55:54 -0700147
Pirama Arumuga Nainarc41549f2021-03-25 16:31:17 -0700148 if args.procnames:
149 pids = adb_shell(['pidof'] + args.procnames, text=True).split()
150 logging.info(f'flushing coverage for pids: {pids}')
151 else:
Pirama Arumuga Nainarbeb6fb72021-04-27 21:55:54 -0700152 pids = None
Pirama Arumuga Nainarc41549f2021-03-25 16:31:17 -0700153 logging.info('flushing coverage for all processes on device')
154
Pirama Arumuga Nainarbeb6fb72021-04-27 21:55:54 -0700155 send_flush_signal(pids)
Pirama Arumuga Nainarc41549f2021-03-25 16:31:17 -0700156
157 logging.info(
158 f'sleeping for {FLUSH_SLEEP} seconds for coverage to be written')
159 time.sleep(FLUSH_SLEEP)
160
161
162def do_report(args):
Roland Levillaind203b9e2021-05-13 16:19:45 +0100163 adb_root()
Pirama Arumuga Nainarbeb6fb72021-04-27 21:55:54 -0700164
Pirama Arumuga Nainarc41549f2021-03-25 16:31:17 -0700165 temp_dir = tempfile.mkdtemp(
166 prefix='covreport-', dir=os.environ.get('ANDROID_BUILD_TOP', None))
167 logging.info(f'generating coverage report in {temp_dir}')
168
169 # Pull coverage files from /data/misc/trace on the device
170 compressed = adb_shell(['tar', '-czf', '-', '-C', '/data/misc', 'trace'])
171 check_output(['tar', 'zxvf', '-', '-C', temp_dir], input=compressed)
172
173 # Call llvm-profdata followed by llvm-cov
174 profdata = f'{temp_dir}/merged.profdata'
175 check_output(
176 f'{LLVM_PROFDATA_PATH} merge --failure-mode=all --output={profdata} {temp_dir}/trace/*.profraw',
177 shell=True)
178
179 object_flags = [args.binary[0]] + ['--object=' + b for b in args.binary[1:]]
180 source_dirs = ['/proc/self/cwd/' + s for s in args.source_dir]
181
Roland Levillaind2f12362021-05-21 17:18:46 +0100182 output_dir = f'{temp_dir}/html'
183
Pirama Arumuga Nainarc41549f2021-03-25 16:31:17 -0700184 check_output([
185 str(LLVM_COV_PATH), 'show', f'--instr-profile={profdata}',
Roland Levillaind2f12362021-05-21 17:18:46 +0100186 '--format=html', f'--output-dir={output_dir}',
Pirama Arumuga Nainarc41549f2021-03-25 16:31:17 -0700187 '--show-region-summary=false'
188 ] + object_flags + source_dirs)
189
Roland Levillaind2f12362021-05-21 17:18:46 +0100190 print(f'Coverage report data written in {output_dir}')
191
Pirama Arumuga Nainarc41549f2021-03-25 16:31:17 -0700192
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()