1#!/usr/bin/env python3
2#
3# Copyright (C) 2018 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    Support profiling without usb connection in below steps:
20    1. With usb connection, start simpleperf recording.
21    2. Unplug the usb cable and play the app you want to profile, while the process of
22       simpleperf keeps running and collecting samples.
23    3. Replug the usb cable, stop simpleperf recording and pull recording file on host.
24
25    Note that recording is stopped once the app is killed. So if you restart the app
26    during profiling time, simpleperf only records the first running.
27"""
28
29from __future__ import print_function
30import argparse
31import subprocess
32import sys
33import time
34
35from simpleperf_utils import AdbHelper, get_target_binary_path, log_warning
36
37
38def start_recording(args):
39    adb = AdbHelper()
40    device_arch = adb.get_device_arch()
41    simpleperf_binary = get_target_binary_path(device_arch, 'simpleperf')
42    adb.check_run(['push', simpleperf_binary, '/data/local/tmp'])
43    adb.check_run(['shell', 'chmod', 'a+x', '/data/local/tmp/simpleperf'])
44    adb.check_run(['shell', 'rm', '-rf', '/data/local/tmp/perf.data',
45                   '/data/local/tmp/simpleperf_output'])
46    shell_cmd = 'cd /data/local/tmp && nohup ./simpleperf record ' + args.record_options
47    if args.app:
48        shell_cmd += ' --app ' + args.app
49    if args.size_limit:
50        shell_cmd += ' --size-limit ' + args.size_limit
51    shell_cmd += ' >/data/local/tmp/simpleperf_output 2>&1'
52    print('shell_cmd: %s' % shell_cmd)
53    subproc = subprocess.Popen([adb.adb_path, 'shell', shell_cmd])
54    # Wait 2 seconds to see if the simpleperf command fails to start.
55    time.sleep(2)
56    if subproc.poll() is None:
57        print('Simpleperf recording has started. Please unplug the usb cable and run the app.')
58        print('After that, run `%s stop` to get recording result.' % sys.argv[0])
59    else:
60        adb.run(['shell', 'cat', '/data/local/tmp/simpleperf_output'])
61        sys.exit(subproc.returncode)
62
63
64def stop_recording(args):
65    adb = AdbHelper()
66    result = adb.run(['shell', 'pidof', 'simpleperf'])
67    if not result:
68        log_warning('No simpleperf process on device. The recording has ended.')
69    else:
70        adb.run(['shell', 'pkill', '-l', '2', 'simpleperf'])
71        print('Waiting for simpleperf process to finish...')
72        while adb.run(['shell', 'pidof', 'simpleperf']):
73            time.sleep(1)
74    adb.run(['shell', 'cat', '/data/local/tmp/simpleperf_output'])
75    adb.check_run(['pull', '/data/local/tmp/perf.data', args.perf_data_path])
76    print('The recording data has been collected in %s.' % args.perf_data_path)
77
78
79def main():
80    parser = argparse.ArgumentParser(description=__doc__,
81                                     formatter_class=argparse.RawDescriptionHelpFormatter)
82    subparsers = parser.add_subparsers()
83    start_parser = subparsers.add_parser('start', help='Start recording.')
84    start_parser.add_argument('-r', '--record_options',
85                              default='-e task-clock:u -g',
86                              help="""Set options for `simpleperf record` command.
87                                      Default is `-e task-clock:u -g`.""")
88    start_parser.add_argument('-p', '--app', help="""Profile an Android app, given the package
89                              name. Like `-p com.example.android.myapp`.""")
90    start_parser.add_argument('--size_limit', type=str,
91                              help="""Stop profiling when recording data reaches
92                                      [size_limit][K|M|G] bytes. Like `--size_limit 1M`.""")
93    start_parser.set_defaults(func=start_recording)
94    stop_parser = subparsers.add_parser('stop', help='Stop recording.')
95    stop_parser.add_argument('-o', '--perf_data_path', default='perf.data', help="""The path to
96                             store profiling data on host. Default is perf.data.""")
97    stop_parser.set_defaults(func=stop_recording)
98    args = parser.parse_args()
99    args.func(args)
100
101
102if __name__ == '__main__':
103    main()
104