1#!/usr/bin/env python3 2# 3# Copyright (C) 2021 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 17import os 18import re 19import shutil 20import subprocess 21 22from simpleperf_utils import remove 23from . test_utils import TestBase, TestHelper, AdbHelper, INFERNO_SCRIPT 24 25 26class TestExampleBase(TestBase): 27 @classmethod 28 def prepare(cls, example_name, package_name, activity_name, abi=None, adb_root=False): 29 cls.adb = AdbHelper(enable_switch_to_root=adb_root) 30 cls.example_path = TestHelper.testdata_path(example_name) 31 if not os.path.isdir(cls.example_path): 32 log_fatal("can't find " + cls.example_path) 33 for root, _, files in os.walk(cls.example_path): 34 if 'app-profiling.apk' in files: 35 cls.apk_path = os.path.join(root, 'app-profiling.apk') 36 break 37 if not hasattr(cls, 'apk_path'): 38 log_fatal("can't find app-profiling.apk under " + cls.example_path) 39 cls.package_name = package_name 40 cls.activity_name = activity_name 41 args = ["install", "-r"] 42 if abi: 43 args += ["--abi", abi] 44 args.append(cls.apk_path) 45 cls.adb.check_run(args) 46 cls.adb_root = adb_root 47 cls.has_perf_data_for_report = False 48 # On Android >= P (version 9), we can profile JITed and interpreted Java code. 49 # So only compile Java code on Android <= O (version 8). 50 cls.use_compiled_java_code = TestHelper.android_version <= 8 51 cls.testcase_dir = TestHelper.get_test_dir(cls.__name__) 52 53 @classmethod 54 def tearDownClass(cls): 55 remove(cls.testcase_dir) 56 if hasattr(cls, 'package_name'): 57 cls.adb.check_run(["uninstall", cls.package_name]) 58 59 def setUp(self): 60 super(TestExampleBase, self).setUp() 61 if 'TraceOffCpu' in self.id() and not TestHelper.is_trace_offcpu_supported(): 62 self.skipTest('trace-offcpu is not supported on device') 63 # Use testcase_dir to share a common perf.data for reporting. So we don't need to 64 # generate it for each test. 65 if not os.path.isdir(self.testcase_dir): 66 os.makedirs(self.testcase_dir) 67 os.chdir(self.testcase_dir) 68 self.run_app_profiler(compile_java_code=self.use_compiled_java_code) 69 os.chdir(self.test_dir) 70 71 for name in os.listdir(self.testcase_dir): 72 path = os.path.join(self.testcase_dir, name) 73 if os.path.isfile(path): 74 shutil.copy(path, self.test_dir) 75 elif os.path.isdir(path): 76 shutil.copytree(path, os.path.join(self.test_dir, name)) 77 78 def run(self, result=None): 79 self.__class__.test_result = result 80 super(TestExampleBase, self).run(result) 81 82 def run_app_profiler(self, record_arg="-g --duration 10", build_binary_cache=True, 83 start_activity=True, compile_java_code=False): 84 args = ['app_profiler.py', '--app', self.package_name, '-r', record_arg, '-o', 'perf.data'] 85 if not build_binary_cache: 86 args.append("-nb") 87 if compile_java_code: 88 args.append('--compile_java_code') 89 if start_activity: 90 args += ["-a", self.activity_name] 91 args += ["-lib", self.example_path] 92 if not self.adb_root: 93 args.append("--disable_adb_root") 94 self.run_cmd(args) 95 self.check_exist(filename="perf.data") 96 if build_binary_cache: 97 self.check_exist(dirname="binary_cache") 98 99 def check_file_under_dir(self, dirname, filename): 100 self.check_exist(dirname=dirname) 101 for _, _, files in os.walk(dirname): 102 for f in files: 103 if f == filename: 104 return 105 self.fail("Failed to call check_file_under_dir(dir=%s, file=%s)" % (dirname, filename)) 106 107 def check_annotation_summary(self, summary_file, check_entries): 108 """ check_entries is a list of (name, accumulated_period, period). 109 This function checks for each entry, if the line containing [name] 110 has at least required accumulated_period and period. 111 """ 112 self.check_exist(filename=summary_file) 113 with open(summary_file, 'r') as fh: 114 summary = fh.read() 115 fulfilled = [False for x in check_entries] 116 summary_check_re = re.compile(r'accumulated_period:\s*([\d.]+)%.*period:\s*([\d.]+)%') 117 for line in summary.split('\n'): 118 for i, (name, need_acc_period, need_period) in enumerate(check_entries): 119 if not fulfilled[i] and name in line: 120 m = summary_check_re.search(line) 121 if m: 122 acc_period = float(m.group(1)) 123 period = float(m.group(2)) 124 if acc_period >= need_acc_period and period >= need_period: 125 fulfilled[i] = True 126 127 self.check_fulfilled_entries(fulfilled, check_entries) 128 129 def check_inferno_report_html(self, check_entries, filename="report.html"): 130 self.check_exist(filename=filename) 131 with open(filename, 'r') as fh: 132 data = fh.read() 133 fulfilled = [False for _ in check_entries] 134 for line in data.split('\n'): 135 # each entry is a (function_name, min_percentage) pair. 136 for i, entry in enumerate(check_entries): 137 if fulfilled[i] or line.find(entry[0]) == -1: 138 continue 139 m = re.search(r'(\d+\.\d+)%', line) 140 if m and float(m.group(1)) >= entry[1]: 141 fulfilled[i] = True 142 break 143 self.check_fulfilled_entries(fulfilled, check_entries) 144 145 def common_test_app_profiler(self): 146 self.run_cmd(["app_profiler.py", "-h"]) 147 remove("binary_cache") 148 self.run_app_profiler(build_binary_cache=False) 149 self.assertFalse(os.path.isdir("binary_cache")) 150 args = ["binary_cache_builder.py"] 151 if not self.adb_root: 152 args.append("--disable_adb_root") 153 self.run_cmd(args) 154 self.check_exist(dirname="binary_cache") 155 remove("binary_cache") 156 self.run_app_profiler(build_binary_cache=True) 157 self.run_app_profiler() 158 self.run_app_profiler(start_activity=False) 159 160 def common_test_report(self): 161 self.run_cmd(["report.py", "-h"]) 162 self.run_cmd(["report.py"]) 163 self.run_cmd(["report.py", "-i", "perf.data"]) 164 self.run_cmd(["report.py", "-g"]) 165 self.run_cmd(["report.py", "--self-kill-for-testing", "-g", "--gui"]) 166 167 def common_test_annotate(self): 168 self.run_cmd(["annotate.py", "-h"]) 169 remove("annotated_files") 170 self.run_cmd(["annotate.py", "-s", self.example_path]) 171 self.check_exist(dirname="annotated_files") 172 173 def common_test_report_sample(self, check_strings): 174 self.run_cmd(["report_sample.py", "-h"]) 175 self.run_cmd(["report_sample.py"]) 176 output = self.run_cmd(["report_sample.py", "perf.data"], return_output=True) 177 self.check_strings_in_content(output, check_strings) 178 179 def common_test_pprof_proto_generator(self, check_strings_with_lines, 180 check_strings_without_lines): 181 self.run_cmd(["pprof_proto_generator.py", "-h"]) 182 self.run_cmd(["pprof_proto_generator.py"]) 183 remove("pprof.profile") 184 self.run_cmd(["pprof_proto_generator.py", "-i", "perf.data", "-o", "pprof.profile"]) 185 self.check_exist(filename="pprof.profile") 186 self.run_cmd(["pprof_proto_generator.py", "--show"]) 187 output = self.run_cmd(["pprof_proto_generator.py", "--show", "pprof.profile"], 188 return_output=True) 189 self.check_strings_in_content(output, check_strings_with_lines + ["has_line_numbers: True"]) 190 remove("binary_cache") 191 self.run_cmd(["pprof_proto_generator.py"]) 192 output = self.run_cmd(["pprof_proto_generator.py", "--show", "pprof.profile"], 193 return_output=True) 194 self.check_strings_in_content(output, check_strings_without_lines + 195 ["has_line_numbers: False"]) 196 197 def common_test_inferno(self): 198 self.run_cmd([INFERNO_SCRIPT, "-h"]) 199 remove("perf.data") 200 append_args = [] if self.adb_root else ["--disable_adb_root"] 201 self.run_cmd([INFERNO_SCRIPT, "-p", self.package_name, "-t", "3"] + append_args) 202 self.check_exist(filename="perf.data") 203 self.run_cmd([INFERNO_SCRIPT, "-p", self.package_name, "-f", "1000", "-du", "-t", "1"] + 204 append_args) 205 self.run_cmd([INFERNO_SCRIPT, "-p", self.package_name, "-e", "100000 cpu-cycles", 206 "-t", "1"] + append_args) 207 self.run_cmd([INFERNO_SCRIPT, "-sc"]) 208 209 def common_test_report_html(self): 210 self.run_cmd(['report_html.py', '-h']) 211 self.run_cmd(['report_html.py']) 212 self.run_cmd(['report_html.py', '--add_source_code', '--source_dirs', 'testdata']) 213 self.run_cmd(['report_html.py', '--add_disassembly']) 214 # Test with multiple perf.data. 215 shutil.move('perf.data', 'perf2.data') 216 self.run_app_profiler(record_arg='-g -f 1000 --duration 3 -e task-clock:u') 217 self.run_cmd(['report_html.py', '-i', 'perf.data', 'perf2.data']) 218 219 220class TestRecordingRealApps(TestBase): 221 def setUp(self): 222 super(TestRecordingRealApps, self).setUp() 223 self.adb = TestHelper.adb 224 self.installed_packages = [] 225 226 def tearDown(self): 227 for package in self.installed_packages: 228 self.adb.run(['shell', 'pm', 'uninstall', package]) 229 super(TestRecordingRealApps, self).tearDown() 230 231 def install_apk(self, apk_path, package_name): 232 self.adb.run(['uninstall', package_name]) 233 self.adb.run(['install', '-t', apk_path]) 234 self.installed_packages.append(package_name) 235 236 def start_app(self, start_cmd): 237 subprocess.Popen(self.adb.adb_path + ' ' + start_cmd, shell=True, 238 stdout=TestHelper.log_fh, stderr=TestHelper.log_fh) 239 240 def record_data(self, package_name, record_arg): 241 self.run_cmd(['app_profiler.py', '--app', package_name, '-r', record_arg]) 242 243 def check_symbol_in_record_file(self, symbol_name): 244 self.run_cmd(['report.py', '--children', '-o', 'report.txt']) 245 self.check_strings_in_file('report.txt', [symbol_name]) 246 247 def test_recording_displaybitmaps(self): 248 self.install_apk(TestHelper.testdata_path('DisplayBitmaps.apk'), 249 'com.example.android.displayingbitmaps') 250 self.install_apk(TestHelper.testdata_path('DisplayBitmapsTest.apk'), 251 'com.example.android.displayingbitmaps.test') 252 self.start_app('shell am instrument -w -r -e debug false -e class ' + 253 'com.example.android.displayingbitmaps.tests.GridViewTest ' + 254 'com.example.android.displayingbitmaps.test/' + 255 'androidx.test.runner.AndroidJUnitRunner') 256 self.record_data('com.example.android.displayingbitmaps', '-e cpu-clock -g --duration 10') 257 if TestHelper.android_version >= 9: 258 self.check_symbol_in_record_file('androidx.test.espresso') 259 260 def test_recording_endless_tunnel(self): 261 self.install_apk(TestHelper.testdata_path( 262 'EndlessTunnel.apk'), 'com.google.sample.tunnel') 263 self.start_app('shell am start -n com.google.sample.tunnel/android.app.NativeActivity -a ' + 264 'android.intent.action.MAIN -c android.intent.category.LAUNCHER') 265 self.record_data('com.google.sample.tunnel', '-e cpu-clock -g --duration 10') 266 self.check_symbol_in_record_file('PlayScene::DoFrame') 267