blob: 7fc8540effbc612955744102d76e9d66322d401e [file] [log] [blame]
Florian Mayerc8aa81c2021-04-19 15:16:15 +01001#!/usr/bin/env python3
Florian Mayera8ff9032020-03-04 11:31:48 -08002
3# Copyright (C) 2020 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 __future__ import absolute_import
18from __future__ import division
19from __future__ import print_function
20
21import argparse
22import os
23import subprocess
24import sys
25import tempfile
26import time
Florian Mayer0ac0e742021-05-19 15:46:59 +010027import uuid
Florian Mayera8ff9032020-03-04 11:31:48 -080028
29NULL = open(os.devnull)
30
31PACKAGES_LIST_CFG = '''data_sources {
32 config {
33 name: "android.packages_list"
34 }
35}
36'''
37
38CFG_IDENT = ' '
39CFG = '''buffers {{
40 size_kb: 100024
41 fill_policy: RING_BUFFER
42}}
43
44data_sources {{
45 config {{
46 name: "android.java_hprof"
47 java_hprof_config {{
48{target_cfg}
49{continuous_dump_config}
50 }}
51 }}
52}}
53
Florian Mayerbab93652020-09-25 13:58:31 +010054data_source_stop_timeout_ms: {data_source_stop_timeout_ms}
55duration_ms: {duration_ms}
Florian Mayera8ff9032020-03-04 11:31:48 -080056'''
57
58CONTINUOUS_DUMP = """
59 continuous_dump_config {{
60 dump_phase_ms: 0
61 dump_interval_ms: {dump_interval}
62 }}
63"""
64
Florian Mayer0ac0e742021-05-19 15:46:59 +010065UUID = str(uuid.uuid4())[-6:]
66PROFILE_PATH = '/data/misc/perfetto-traces/java-profile-' + UUID
67
Florian Mayera8ff9032020-03-04 11:31:48 -080068PERFETTO_CMD = ('CFG=\'{cfg}\'; echo ${{CFG}} | '
Florian Mayer0ac0e742021-05-19 15:46:59 +010069 'perfetto --txt -c - -o ' + PROFILE_PATH + ' -d')
Florian Mayera8ff9032020-03-04 11:31:48 -080070
Florian Mayerbab93652020-09-25 13:58:31 +010071
Florian Mayera8ff9032020-03-04 11:31:48 -080072def main(argv):
73 parser = argparse.ArgumentParser()
74 parser.add_argument(
75 "-o",
76 "--output",
77 help="Filename to save profile to.",
78 metavar="FILE",
79 default=None)
80 parser.add_argument(
81 "-p",
82 "--pid",
83 help="Comma-separated list of PIDs to "
84 "profile.",
85 metavar="PIDS")
86 parser.add_argument(
87 "-n",
88 "--name",
89 help="Comma-separated list of process "
90 "names to profile.",
91 metavar="NAMES")
92 parser.add_argument(
93 "-c",
94 "--continuous-dump",
95 help="Dump interval in ms. 0 to disable continuous dump.",
96 type=int,
97 default=0)
98 parser.add_argument(
99 "--no-versions",
100 action="store_true",
101 help="Do not get version information about APKs.")
102 parser.add_argument(
Florian Mayere3eed3a2020-04-04 11:57:30 +0200103 "--dump-smaps",
104 action="store_true",
105 help="Get information about /proc/$PID/smaps of target.")
106 parser.add_argument(
Florian Mayera8ff9032020-03-04 11:31:48 -0800107 "--print-config",
108 action="store_true",
109 help="Print config instead of running. For debugging.")
Florian Mayerbab93652020-09-25 13:58:31 +0100110 parser.add_argument(
Florian Mayer70f1e982020-11-11 15:54:44 +0000111 "--stop-when-done",
Florian Mayerbab93652020-09-25 13:58:31 +0100112 action="store_true",
113 help="On recent builds of S, use a new method to stop the profile when "
114 "the dump is done. Previously, we would hardcode a duration.")
Florian Mayer70f1e982020-11-11 15:54:44 +0000115
Florian Mayera8ff9032020-03-04 11:31:48 -0800116 args = parser.parse_args()
117
118 fail = False
119 if args.pid is None and args.name is None:
120 print("FATAL: Neither PID nor NAME given.", file=sys.stderr)
121 fail = True
122
123 target_cfg = ""
124 if args.pid:
125 for pid in args.pid.split(','):
126 try:
127 pid = int(pid)
128 except ValueError:
129 print("FATAL: invalid PID %s" % pid, file=sys.stderr)
130 fail = True
131 target_cfg += '{}pid: {}\n'.format(CFG_IDENT, pid)
132 if args.name:
133 for name in args.name.split(','):
134 target_cfg += '{}process_cmdline: "{}"\n'.format(CFG_IDENT, name)
Florian Mayere3eed3a2020-04-04 11:57:30 +0200135 if args.dump_smaps:
136 target_cfg += '{}dump_smaps: true\n'.format(CFG_IDENT)
Florian Mayera8ff9032020-03-04 11:31:48 -0800137
138 if fail:
139 parser.print_help()
140 return 1
141
142 output_file = args.output
143 if output_file is None:
144 fd, name = tempfile.mkstemp('profile')
145 os.close(fd)
146 output_file = name
147
148 continuous_dump_cfg = ""
149 if args.continuous_dump:
150 continuous_dump_cfg = CONTINUOUS_DUMP.format(
151 dump_interval=args.continuous_dump)
Florian Mayerbab93652020-09-25 13:58:31 +0100152
153 # TODO(fmayer): Once the changes have been in S for long enough, make this
154 # the default for S+.
155 if args.stop_when_done:
156 duration_ms = 1000
157 data_source_stop_timeout_ms = 100000
158 else:
159 duration_ms = 20000
160 data_source_stop_timeout_ms = 0
161
Florian Mayera8ff9032020-03-04 11:31:48 -0800162 cfg = CFG.format(
163 target_cfg=target_cfg,
Florian Mayerbab93652020-09-25 13:58:31 +0100164 continuous_dump_config=continuous_dump_cfg,
165 duration_ms=duration_ms,
166 data_source_stop_timeout_ms=data_source_stop_timeout_ms)
Florian Mayera8ff9032020-03-04 11:31:48 -0800167 if not args.no_versions:
168 cfg += PACKAGES_LIST_CFG
169
170 if args.print_config:
171 print(cfg)
172 return 0
173
Florian Mayerc8aa81c2021-04-19 15:16:15 +0100174 user = subprocess.check_output(
175 ['adb', 'shell', 'whoami']).strip().decode('utf8')
Florian Mayera8ff9032020-03-04 11:31:48 -0800176 perfetto_pid = subprocess.check_output(
177 ['adb', 'exec-out',
Florian Mayerc8aa81c2021-04-19 15:16:15 +0100178 PERFETTO_CMD.format(cfg=cfg, user=user)]).strip().decode('utf8')
Florian Mayera8ff9032020-03-04 11:31:48 -0800179 try:
180 int(perfetto_pid.strip())
181 except ValueError:
182 print("Failed to invoke perfetto: {}".format(perfetto_pid), file=sys.stderr)
183 return 1
184
185 print("Dumping Java Heap.")
186 exists = True
187
188 # Wait for perfetto cmd to return.
189 while exists:
190 exists = subprocess.call(
191 ['adb', 'shell', '[ -d /proc/{} ]'.format(perfetto_pid)]) == 0
192 time.sleep(1)
193
194 subprocess.check_call(
Florian Mayer0ac0e742021-05-19 15:46:59 +0100195 ['adb', 'pull', PROFILE_PATH, output_file], stdout=NULL)
196
197 subprocess.check_call(
198 ['adb', 'shell', 'rm', PROFILE_PATH], stdout=NULL)
Florian Mayera8ff9032020-03-04 11:31:48 -0800199
200 print("Wrote profile to {}".format(output_file))
201 print("This can be viewed using https://ui.perfetto.dev.")
202
203
204if __name__ == '__main__':
205 sys.exit(main(sys.argv))