1#!/usr/bin/env python
2#
3# Copyright (C) 2019 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
18"""
19    This script is part of controlling simpleperf recording in user code. It is used to prepare
20    profiling environment (upload simpleperf to device and enable profiling) before recording
21    and collect recording data on host after recording.
22    Controlling simpleperf recording is done in below steps:
23    1. Add simpleperf Java API/C++ API to the app's source code. And call the API in user code.
24    2. Run `api_profiler.py prepare` to prepare profiling environment.
25    3. Run the app one or more times to generate recording data.
26    4. Run `api_profiler.py collect` to collect recording data on host.
27"""
28
29from __future__ import print_function
30import argparse
31import os
32import os.path
33import shutil
34import zipfile
35
36from utils import AdbHelper, get_target_binary_path, log_exit, log_info, remove
37
38def prepare_recording(args):
39    adb = AdbHelper()
40    enable_profiling_on_device(adb, args)
41    upload_simpleperf_to_device(adb)
42    run_simpleperf_prepare_cmd(adb)
43
44def enable_profiling_on_device(adb, args):
45    android_version = adb.get_android_version()
46    if android_version >= 10:
47        adb.set_property('debug.perf_event_max_sample_rate', str(args.max_sample_rate[0]))
48        adb.set_property('debug.perf_cpu_time_max_percent', str(args.max_cpu_percent[0]))
49        adb.set_property('debug.perf_event_mlock_kb', str(args.max_memory_in_kb[0]))
50    adb.set_property('security.perf_harden', '0')
51
52def upload_simpleperf_to_device(adb):
53    device_arch = adb.get_device_arch()
54    simpleperf_binary = get_target_binary_path(device_arch, 'simpleperf')
55    adb.check_run(['push', simpleperf_binary, '/data/local/tmp'])
56    adb.check_run(['shell', 'chmod', 'a+x', '/data/local/tmp/simpleperf'])
57
58def run_simpleperf_prepare_cmd(adb):
59    adb.check_run(['shell', '/data/local/tmp/simpleperf', 'api-prepare'])
60
61
62def collect_data(args):
63    adb = AdbHelper()
64    if not os.path.isdir(args.out_dir):
65        os.makedirs(args.out_dir)
66    download_recording_data(adb, args)
67    unzip_recording_data(args)
68
69def download_recording_data(adb, args):
70    """ download recording data to simpleperf_data.zip."""
71    upload_simpleperf_to_device(adb)
72    adb.check_run(['shell', '/data/local/tmp/simpleperf', 'api-collect', '--app', args.app[0],
73                   '-o', '/data/local/tmp/simpleperf_data.zip'])
74    adb.check_run(['pull', '/data/local/tmp/simpleperf_data.zip', args.out_dir])
75    adb.check_run(['shell', 'rm', '-rf', '/data/local/tmp/simpleperf_data'])
76
77def unzip_recording_data(args):
78    zip_file_path = os.path.join(args.out_dir, 'simpleperf_data.zip')
79    with zipfile.ZipFile(zip_file_path, 'r') as zip_fh:
80        names = zip_fh.namelist()
81        log_info('There are %d recording data files.' % len(names))
82        for name in names:
83            log_info('recording file: %s' % os.path.join(args.out_dir, name))
84            zip_fh.extract(name, args.out_dir)
85    remove(zip_file_path)
86
87class ArgumentHelpFormatter(argparse.ArgumentDefaultsHelpFormatter,
88                            argparse.RawDescriptionHelpFormatter):
89    pass
90
91def main():
92    parser = argparse.ArgumentParser(description=__doc__,
93                                     formatter_class=ArgumentHelpFormatter)
94    subparsers = parser.add_subparsers()
95    prepare_parser = subparsers.add_parser('prepare', help='Prepare recording on device.',
96                                           formatter_class=ArgumentHelpFormatter)
97    prepare_parser.add_argument('--max-sample-rate', nargs=1, type=int, default=[100000], help="""
98                                Set max sample rate (only on Android >= Q).""")
99    prepare_parser.add_argument('--max-cpu-percent', nargs=1, type=int, default=[25], help="""
100                                Set max cpu percent for recording (only on Android >= Q).""")
101    prepare_parser.add_argument('--max-memory-in-kb', nargs=1, type=int,
102                                default=[(1024 + 1) * 4 * 8], help="""
103                                Set max kernel buffer size for recording (only on Android >= Q).
104                                """)
105    prepare_parser.set_defaults(func=prepare_recording)
106    collect_parser = subparsers.add_parser('collect', help='Collect recording data.',
107                                           formatter_class=ArgumentHelpFormatter)
108    collect_parser.add_argument('-p', '--app', nargs=1, required=True, help="""
109                                The app package name of the app profiled.""")
110    collect_parser.add_argument('-o', '--out-dir', default='simpleperf_data', help="""
111                                The directory to store recording data.""")
112    collect_parser.set_defaults(func=collect_data)
113    args = parser.parse_args()
114    args.func(args)
115
116if __name__ == '__main__':
117    main()
118