aboutsummaryrefslogtreecommitdiff
path: root/tools/java_heap_dump
blob: 03abb016204e98c57bee6e1b03f11133d03961e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
#!/usr/bin/env python3

# Copyright (C) 2020 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import os
import subprocess
import sys
import tempfile
import time

NULL = open(os.devnull)

PACKAGES_LIST_CFG = '''data_sources {
  config {
    name: "android.packages_list"
  }
}
'''

CFG_IDENT = '      '
CFG = '''buffers {{
  size_kb: 100024
  fill_policy: RING_BUFFER
}}

data_sources {{
  config {{
    name: "android.java_hprof"
    java_hprof_config {{
{target_cfg}
{continuous_dump_config}
    }}
  }}
}}

data_source_stop_timeout_ms: {data_source_stop_timeout_ms}
duration_ms: {duration_ms}
'''

CONTINUOUS_DUMP = """
      continuous_dump_config {{
        dump_phase_ms: 0
        dump_interval_ms: {dump_interval}
      }}
"""

PERFETTO_CMD = ('CFG=\'{cfg}\'; echo ${{CFG}} | '
                'perfetto --txt -c - -o '
                '/data/misc/perfetto-traces/java-profile-{user} -d')


def main(argv):
  parser = argparse.ArgumentParser()
  parser.add_argument(
      "-o",
      "--output",
      help="Filename to save profile to.",
      metavar="FILE",
      default=None)
  parser.add_argument(
      "-p",
      "--pid",
      help="Comma-separated list of PIDs to "
      "profile.",
      metavar="PIDS")
  parser.add_argument(
      "-n",
      "--name",
      help="Comma-separated list of process "
      "names to profile.",
      metavar="NAMES")
  parser.add_argument(
      "-c",
      "--continuous-dump",
      help="Dump interval in ms. 0 to disable continuous dump.",
      type=int,
      default=0)
  parser.add_argument(
      "--no-versions",
      action="store_true",
      help="Do not get version information about APKs.")
  parser.add_argument(
      "--dump-smaps",
      action="store_true",
      help="Get information about /proc/$PID/smaps of target.")
  parser.add_argument(
      "--print-config",
      action="store_true",
      help="Print config instead of running. For debugging.")
  parser.add_argument(
      "--stop-when-done",
      action="store_true",
      help="On recent builds of S, use a new method to stop the profile when "
           "the dump is done. Previously, we would hardcode a duration.")

  args = parser.parse_args()

  fail = False
  if args.pid is None and args.name is None:
    print("FATAL: Neither PID nor NAME given.", file=sys.stderr)
    fail = True

  target_cfg = ""
  if args.pid:
    for pid in args.pid.split(','):
      try:
        pid = int(pid)
      except ValueError:
        print("FATAL: invalid PID %s" % pid, file=sys.stderr)
        fail = True
      target_cfg += '{}pid: {}\n'.format(CFG_IDENT, pid)
  if args.name:
    for name in args.name.split(','):
      target_cfg += '{}process_cmdline: "{}"\n'.format(CFG_IDENT, name)
  if args.dump_smaps:
    target_cfg += '{}dump_smaps: true\n'.format(CFG_IDENT)

  if fail:
    parser.print_help()
    return 1

  output_file = args.output
  if output_file is None:
    fd, name = tempfile.mkstemp('profile')
    os.close(fd)
    output_file = name

  continuous_dump_cfg = ""
  if args.continuous_dump:
    continuous_dump_cfg = CONTINUOUS_DUMP.format(
        dump_interval=args.continuous_dump)

  # TODO(fmayer): Once the changes have been in S for long enough, make this
  #               the default for S+.
  if args.stop_when_done:
    duration_ms = 1000
    data_source_stop_timeout_ms = 100000
  else:
    duration_ms = 20000
    data_source_stop_timeout_ms = 0

  cfg = CFG.format(
      target_cfg=target_cfg,
      continuous_dump_config=continuous_dump_cfg,
      duration_ms=duration_ms,
      data_source_stop_timeout_ms=data_source_stop_timeout_ms)
  if not args.no_versions:
    cfg += PACKAGES_LIST_CFG

  if args.print_config:
    print(cfg)
    return 0

  user = subprocess.check_output(
    ['adb', 'shell', 'whoami']).strip().decode('utf8')
  perfetto_pid = subprocess.check_output(
      ['adb', 'exec-out',
       PERFETTO_CMD.format(cfg=cfg, user=user)]).strip().decode('utf8')
  try:
    int(perfetto_pid.strip())
  except ValueError:
    print("Failed to invoke perfetto: {}".format(perfetto_pid), file=sys.stderr)
    return 1

  print("Dumping Java Heap.")
  exists = True

  # Wait for perfetto cmd to return.
  while exists:
    exists = subprocess.call(
        ['adb', 'shell', '[ -d /proc/{} ]'.format(perfetto_pid)]) == 0
    time.sleep(1)

  subprocess.check_call(
    ['adb', 'pull', '/data/misc/perfetto-traces/java-profile-{}'.format(user),
     output_file], stdout=NULL)

  print("Wrote profile to {}".format(output_file))
  print("This can be viewed using https://ui.perfetto.dev.")


if __name__ == '__main__':
  sys.exit(main(sys.argv))