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 17from collections import namedtuple 18import google.protobuf 19import os 20import re 21import tempfile 22from typing import List, Optional, Set 23 24from binary_cache_builder import BinaryCacheBuilder 25from pprof_proto_generator import load_pprof_profile, PprofProfileGenerator 26from . test_utils import TestBase, TestHelper 27from simpleperf_utils import ReportLibOptions 28 29 30class TestPprofProtoGenerator(TestBase): 31 def run_generator(self, options=None, testdata_file='perf_with_interpreter_frames.data'): 32 testdata_path = TestHelper.testdata_path(testdata_file) 33 options = options or [] 34 self.run_cmd(['pprof_proto_generator.py', '-i', testdata_path] + options) 35 return self.run_cmd(['pprof_proto_generator.py', '--show'], return_output=True) 36 37 def generate_profile(self, options: Optional[List[str]], testdata_files: List[str]): 38 testdata_paths = [TestHelper.testdata_path(f) for f in testdata_files] 39 options = options or [] 40 self.run_cmd(['pprof_proto_generator.py', '-i'] + testdata_paths + options) 41 return load_pprof_profile('pprof.profile') 42 43 def test_show_art_frames(self): 44 art_frame_str = 'art::interpreter::DoCall' 45 # By default, don't show art frames. 46 self.assertNotIn(art_frame_str, self.run_generator()) 47 # Use --show_art_frames to show art frames. 48 self.assertIn(art_frame_str, self.run_generator(['--show_art_frames'])) 49 50 def test_pid_filter(self): 51 key = 'PlayScene::DoFrame()' # function in process 10419 52 self.assertIn(key, self.run_generator()) 53 self.assertIn(key, self.run_generator(['--pid', '10419'])) 54 self.assertIn(key, self.run_generator(['--pid', '10419', '10416'])) 55 self.assertNotIn(key, self.run_generator(['--pid', '10416'])) 56 57 def test_thread_labels(self): 58 output = self.run_generator() 59 self.assertIn('label[0] = thread:Binder:10419_1', output) 60 self.assertIn('label[0] = thread:Binder:10419_2', output) 61 self.assertIn('label[0] = thread:Binder:10419_3', output) 62 self.assertIn('label[0] = thread:Binder:10419_4', output) 63 self.assertIn('label[1] = threadpool:Binder:%d_%d', output) 64 self.assertIn('label[2] = pid:10419', output) 65 self.assertIn('label[3] = tid:10459', output) 66 67 def test_tid_filter(self): 68 key1 = 'art::ProfileSaver::Run()' # function in thread 10459 69 key2 = 'PlayScene::DoFrame()' # function in thread 10463 70 for options in ([], ['--tid', '10459', '10463']): 71 output = self.run_generator(options) 72 self.assertIn(key1, output) 73 self.assertIn(key2, output) 74 output = self.run_generator(['--tid', '10459']) 75 self.assertIn(key1, output) 76 self.assertNotIn(key2, output) 77 output = self.run_generator(['--tid', '10463']) 78 self.assertNotIn(key1, output) 79 self.assertIn(key2, output) 80 81 def test_comm_filter(self): 82 key1 = 'art::ProfileSaver::Run()' # function in thread 'Profile Saver' 83 key2 = 'PlayScene::DoFrame()' # function in thread 'e.sample.tunnel' 84 for options in ([], ['--comm', 'Profile Saver', 'e.sample.tunnel']): 85 output = self.run_generator(options) 86 self.assertIn(key1, output) 87 self.assertIn(key2, output) 88 output = self.run_generator(['--comm', 'Profile Saver']) 89 self.assertIn(key1, output) 90 self.assertNotIn(key2, output) 91 output = self.run_generator(['--comm', 'e.sample.tunnel']) 92 self.assertNotIn(key1, output) 93 self.assertIn(key2, output) 94 95 def test_build_id(self): 96 """ Test the build ids generated are not padded with zeros. """ 97 self.assertIn('build_id: e3e938cc9e40de2cfe1a5ac7595897de(', self.run_generator()) 98 99 def test_build_id_with_binary_cache(self): 100 """ Test the build ids for elf files in binary_cache are not padded with zero. """ 101 # Test with binary_cache. 102 testdata_file = TestHelper.testdata_path('runtest_two_functions_arm64_perf.data') 103 104 # Build binary_cache. 105 binary_cache_builder = BinaryCacheBuilder(TestHelper.ndk_path, False) 106 binary_cache_builder.build_binary_cache(testdata_file, [TestHelper.testdata_dir]) 107 108 # Generate profile. 109 output = self.run_generator(testdata_file=testdata_file) 110 self.assertIn('build_id: b4f1b49b0fe9e34e78fb14e5374c930c(', output) 111 112 def test_location_address(self): 113 """ Test if the address of a location is within the memory range of the corresponding 114 mapping. 115 """ 116 profile = self.generate_profile(None, ['perf_with_interpreter_frames.data']) 117 # pylint: disable=no-member 118 for location in profile.location: 119 mapping = profile.mapping[location.mapping_id - 1] 120 self.assertLessEqual(mapping.memory_start, location.address) 121 self.assertGreaterEqual(mapping.memory_limit, location.address) 122 123 def test_sample_type(self): 124 """Test sample types have the right units.""" 125 output = self.run_generator() 126 self.assertIn('type=cpu-cycles_samples, unit=samples', output) 127 self.assertIn('type=cpu-cycles, unit=cpu-cycles', output) 128 129 def test_multiple_perf_data(self): 130 """ Test reporting multiple recording file. """ 131 profile1 = self.generate_profile(None, ['aggregatable_perf1.data']) 132 profile2 = self.generate_profile(None, ['aggregatable_perf2.data']) 133 profile_both = self.generate_profile( 134 None, ['aggregatable_perf1.data', 'aggregatable_perf2.data']) 135 # pylint: disable=no-member 136 self.assertGreater(len(profile_both.sample), len(profile1.sample)) 137 self.assertGreater(len(profile_both.sample), len(profile2.sample)) 138 139 def test_proguard_mapping_file(self): 140 """ Test --proguard-mapping-file option. """ 141 testdata_file = 'perf_need_proguard_mapping.data' 142 proguard_mapping_file = TestHelper.testdata_path('proguard_mapping.txt') 143 original_methodname = 'androidx.fragment.app.FragmentActivity.startActivityForResult' 144 # Can't show original method name without proguard mapping file. 145 self.assertNotIn(original_methodname, self.run_generator(testdata_file=testdata_file)) 146 # Show original method name with proguard mapping file. 147 self.assertIn(original_methodname, self.run_generator( 148 ['--proguard-mapping-file', proguard_mapping_file], testdata_file)) 149 150 def test_use_binary_cache(self): 151 testdata_file = TestHelper.testdata_path('runtest_two_functions_arm64_perf.data') 152 153 # Build binary_cache. 154 binary_cache_builder = BinaryCacheBuilder(TestHelper.ndk_path, False) 155 binary_cache_builder.build_binary_cache(testdata_file, [TestHelper.testdata_dir]) 156 157 # Generate profile. 158 output = self.run_generator(testdata_file=testdata_file) 159 self.assertIn('simpleperf_runtest_two_functions_arm64', output) 160 self.assertIn('two_functions.cpp', output) 161 162 def test_line_info(self): 163 """ Check line numbers generated in profile. """ 164 testdata_file = TestHelper.testdata_path('runtest_two_functions_arm64_perf.data') 165 166 # Build binary_cache. 167 binary_cache_builder = BinaryCacheBuilder(TestHelper.ndk_path, False) 168 binary_cache_builder.build_binary_cache(testdata_file, [TestHelper.testdata_dir]) 169 170 # Generate profile. 171 profile = self.generate_profile(None, [testdata_file]) 172 173 CheckItem = namedtuple( 174 'CheckItem', ['addr', 'source_file', 'source_line', 'func_name', 'func_start_line']) 175 176 check_items = [ 177 CheckItem(0x113c, 'two_functions.cpp', 22, 'main', 20), 178 CheckItem(0x1140, 'two_functions.cpp', 23, 'main', 20), 179 CheckItem(0x1094, 'two_functions.cpp', 9, 'Function1', 6), 180 CheckItem(0x1104, 'two_functions.cpp', 16, 'Function2', 13), 181 ] 182 mapping = None 183 for mapping in profile.mapping: 184 binary_path = profile.string_table[mapping.filename] 185 if 'runtest_two_functions_arm64' in binary_path: 186 self.assertTrue(mapping.has_line_numbers) 187 mapping = mapping 188 break 189 self.assertIsNotNone(mapping) 190 191 for check_item in check_items: 192 found = False 193 for location in profile.location: 194 if location.mapping_id != mapping.id: 195 continue 196 addr = location.address - mapping.memory_start + mapping.file_offset 197 if addr == check_item.addr: 198 found = True 199 self.assertEqual(len(location.line), 1) 200 line = location.line[0] 201 function = profile.function[line.function_id - 1] 202 self.assertIn(check_item.source_file, profile.string_table[function.filename]) 203 self.assertEqual(line.line, check_item.source_line) 204 self.assertIn(check_item.func_name, profile.string_table[function.name]) 205 self.assertEqual(function.start_line, check_item.func_start_line) 206 break 207 self.assertTrue(found, check_item) 208 209 def test_function_name_not_changed_by_line_info(self): 210 """ Adding line info shouldn't override function names from report library, which are more 211 accurate when proguard mapping file is given. 212 """ 213 testdata_file = TestHelper.testdata_path('runtest_two_functions_arm64_perf.data') 214 215 # Build binary_cache. 216 binary_cache_builder = BinaryCacheBuilder(TestHelper.ndk_path, False) 217 binary_cache_builder.build_binary_cache(testdata_file, [TestHelper.testdata_dir]) 218 219 # Read recording file. 220 config = {'ndk_path': TestHelper.ndk_path, 'max_chain_length': 1000000, 221 'report_lib_options': ReportLibOptions(False, '', None, None, None)} 222 generator = PprofProfileGenerator(config) 223 generator.load_record_file(testdata_file) 224 225 # Change function name. 226 sample = generator.sample_list[0] 227 self.assertGreaterEqual(len(sample.location_ids), 1) 228 location = generator.location_list[sample.location_ids[0] - 1] 229 self.assertGreaterEqual(len(location.lines), 1) 230 function = generator.get_function(location.lines[0].function_id) 231 function_name = generator.get_string(function.name_id) 232 self.assertEqual(function_name, 'Function1()') 233 location.lines[0].function_id = generator.get_function_id( 234 'NewFunction1()', generator.get_string(function.dso_name_id), function.vaddr_in_dso) 235 236 # Add line info. 237 generator.gen_source_lines(1) 238 239 # Check function name and line info. 240 sample = generator.sample_list[0] 241 self.assertGreaterEqual(len(sample.location_ids), 1) 242 location = generator.location_list[sample.location_ids[0] - 1] 243 self.assertGreaterEqual(len(location.lines), 1) 244 function = generator.get_function(location.lines[0].function_id) 245 function_name = generator.get_string(function.name_id) 246 self.assertEqual(function_name, 'NewFunction1()') 247 self.assertNotEqual(function.source_filename_id, 0) 248 source_filename = generator.get_string(function.source_filename_id) 249 self.assertIn('two_functions.cpp', source_filename) 250 251 def test_comments(self): 252 profile = self.generate_profile(None, ['perf_with_interpreter_frames.data']) 253 comments = "\n".join([profile.string_table[i] for i in profile.comment]) 254 comments = comments.replace('\\', '/') 255 self.assertIn('Simpleperf Record Command:\n/data/data/com.google.sample.tunnel/simpleperf record --in-app --tracepoint-events /data/local/tmp/tracepoint_events --app com.google.sample.tunnel -g --no-post-unwind --duration 30', comments) 256 self.assertIn('Converted to pprof with:', comments) 257 # The full path changes per-machine, so only assert on a subset of the 258 # path. 259 self.assertIn('testdata/perf_with_interpreter_frames.data', comments) 260 self.assertIn('Architecture:\naarch64', comments) 261 262 def test_sample_filters(self): 263 def get_threads_for_filter(filter: str) -> Set[int]: 264 report = self.run_generator(filter.split(), testdata_file='perf_display_bitmaps.data') 265 threads = set() 266 pattern = re.compile(r'\s+tid:(\d+)') 267 threads = set() 268 for m in re.finditer(pattern, report): 269 threads.add(int(m.group(1))) 270 return threads 271 272 self.assertNotIn(31850, get_threads_for_filter('--exclude-pid 31850')) 273 self.assertIn(31850, get_threads_for_filter('--include-pid 31850')) 274 self.assertIn(31850, get_threads_for_filter('--pid 31850')) 275 self.assertNotIn(31881, get_threads_for_filter('--exclude-tid 31881')) 276 self.assertIn(31881, get_threads_for_filter('--include-tid 31881')) 277 self.assertIn(31881, get_threads_for_filter('--tid 31881')) 278 self.assertNotIn(31881, get_threads_for_filter( 279 '--exclude-process-name com.example.android.displayingbitmaps')) 280 self.assertIn(31881, get_threads_for_filter( 281 '--include-process-name com.example.android.displayingbitmaps')) 282 self.assertNotIn(31850, get_threads_for_filter( 283 '--exclude-thread-name com.example.android.displayingbitmaps')) 284 self.assertIn(31850, get_threads_for_filter( 285 '--include-thread-name com.example.android.displayingbitmaps')) 286 287 with tempfile.NamedTemporaryFile('w', delete=False) as filter_file: 288 filter_file.write('GLOBAL_BEGIN 684943449406175\nGLOBAL_END 684943449406176') 289 filter_file.flush() 290 threads = get_threads_for_filter('--filter-file ' + filter_file.name) 291 self.assertIn(31881, threads) 292 self.assertNotIn(31850, threads) 293 os.unlink(filter_file.name) 294