blob: e175b19b1d8cb400df4f9358047c80465c432c43 [file] [log] [blame]
Pirama Arumuga Nainarc41549f2021-03-25 16:31:17 -07001#!/usr/bin/env python3
2#
3# Copyright (C) 202121 The Android Open Source Project
4#
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#
35# 4. pull coverage from device and generate coverage report
36# $ 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.:
39# development/scripts/acov-llvm.py report \
40# -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():
63 regex = r'ClangDefaultVersion\s+= "(?P<rev>clang-r\d+)"'
64 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
87def adb_shell(cmd, *args, **kwargs):
88 """call 'adb shell <cmd>' with logging."""
89 return check_output(['adb', 'shell'] + cmd)
90
91
92def do_clean_device(args):
93 logging.info('resetting coverage on device')
94 adb_shell(['kill', '-37', '-1'])
95
96 logging.info(
97 f'sleeping for {FLUSH_SLEEP} seconds for coverage to be written')
98 time.sleep(FLUSH_SLEEP)
99
100 logging.info('deleting coverage data from device')
101 adb_shell(['rm', '-rf', '/data/misc/trace/*.profraw'])
102
103
104def do_flush(args):
105 if args.procnames:
106 pids = adb_shell(['pidof'] + args.procnames, text=True).split()
107 logging.info(f'flushing coverage for pids: {pids}')
108 else:
109 pids = ['-1']
110 logging.info('flushing coverage for all processes on device')
111
112 # TODO(pirama) Send signal 37 to only those processes that have a
113 # handler installed for it. See b/149047976
114 adb_shell(['kill', '-37'] + pids)
115
116 logging.info(
117 f'sleeping for {FLUSH_SLEEP} seconds for coverage to be written')
118 time.sleep(FLUSH_SLEEP)
119
120
121def do_report(args):
122 temp_dir = tempfile.mkdtemp(
123 prefix='covreport-', dir=os.environ.get('ANDROID_BUILD_TOP', None))
124 logging.info(f'generating coverage report in {temp_dir}')
125
126 # Pull coverage files from /data/misc/trace on the device
127 compressed = adb_shell(['tar', '-czf', '-', '-C', '/data/misc', 'trace'])
128 check_output(['tar', 'zxvf', '-', '-C', temp_dir], input=compressed)
129
130 # Call llvm-profdata followed by llvm-cov
131 profdata = f'{temp_dir}/merged.profdata'
132 check_output(
133 f'{LLVM_PROFDATA_PATH} merge --failure-mode=all --output={profdata} {temp_dir}/trace/*.profraw',
134 shell=True)
135
136 object_flags = [args.binary[0]] + ['--object=' + b for b in args.binary[1:]]
137 source_dirs = ['/proc/self/cwd/' + s for s in args.source_dir]
138
139 check_output([
140 str(LLVM_COV_PATH), 'show', f'--instr-profile={profdata}',
141 '--format=html', f'--output-dir={temp_dir}/html',
142 '--show-region-summary=false'
143 ] + object_flags + source_dirs)
144
145
146def parse_args():
147 parser = argparse.ArgumentParser()
148 parser.add_argument(
149 '-v',
150 '--verbose',
151 action='store_true',
152 default=False,
153 help='enable debug logging')
154
155 subparsers = parser.add_subparsers(dest='command', required=True)
156
157 clean_device = subparsers.add_parser(
158 'clean-device', help='reset coverage on device')
159 clean_device.set_defaults(func=do_clean_device)
160
161 flush = subparsers.add_parser(
162 'flush', help='flush coverage for processes on device')
163 flush.add_argument(
164 'procnames',
165 nargs='*',
166 metavar='PROCNAME',
167 help='flush coverage for one or more processes with name PROCNAME')
168 flush.set_defaults(func=do_flush)
169
170 report = subparsers.add_parser(
171 'report', help='fetch coverage from device and generate report')
172 report.add_argument(
173 '-b',
174 '--binary',
175 nargs='+',
176 metavar='BINARY',
177 action='extend',
178 required=True,
179 help='generate coverage report for BINARY')
180 report.add_argument(
181 '-s',
182 '--source-dir',
183 nargs='+',
184 action='extend',
185 metavar='PATH',
186 required=True,
187 help='generate coverage report for source files in PATH')
188 report.set_defaults(func=do_report)
189 return parser.parse_args()
190
191
192def main():
193 args = parse_args()
194 if args.verbose:
195 logging.basicConfig(level=logging.DEBUG)
196
197 args.func(args)
198
199
200if __name__ == '__main__':
201 main()