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"""
18Retrieves the counts of how many objects have a particular field filled with what on all running
19processes.
20
21Prints a json map from pid -> (log-tag, field-name, field-type, count, total-size).
22"""
23
24
25import adb
26import argparse
27import concurrent.futures
28import itertools
29import json
30import logging
31import os
32import os.path
33import signal
34import subprocess
35import time
36
37def main():
38  parser = argparse.ArgumentParser(description="Get counts of null fields from a device.")
39  parser.add_argument("-S", "--serial", metavar="SERIAL", type=str,
40                      required=False,
41                      default=os.environ.get("ANDROID_SERIAL", None),
42                      help="Android serial to use. Defaults to ANDROID_SERIAL")
43  parser.add_argument("-p", "--pid", required=False,
44                      default=[], action="append",
45                      help="Specific pids to check. By default checks all running dalvik processes")
46  has_out = "OUT" in os.environ
47  def_32 = os.path.join(os.environ.get("OUT", ""), "system", "lib", "libfieldcounts.so")
48  def_64 = os.path.join(os.environ.get("OUT", ""), "system", "lib64", "libfieldcounts.so")
49  has_32 = has_out and os.path.exists(def_32)
50  has_64 = has_out and os.path.exists(def_64)
51  def pushable_lib(name):
52    if os.path.isfile(name):
53      return name
54    else:
55      raise argparse.ArgumentTypeError(name + " is not a file!")
56  parser.add_argument('--lib32', type=pushable_lib,
57                      required=not has_32,
58                      action='store',
59                      default=def_32,
60                      help="Location of 32 bit agent to push")
61  parser.add_argument('--lib64', type=pushable_lib,
62                      required=not has_64,
63                      action='store',
64                      default=def_64 if has_64 else None,
65                      help="Location of 64 bit agent to push")
66  parser.add_argument("fields", nargs="+",
67                      help="fields to check")
68
69  out = parser.parse_args()
70
71  device = adb.device.get_device(out.serial)
72  print("getting root")
73  device.root()
74
75  print("Disabling selinux")
76  device.shell("setenforce 0".split())
77
78  print("Pushing libraries")
79  lib32 = device.shell("mktemp".split())[0].strip()
80  lib64 = device.shell("mktemp".split())[0].strip()
81
82  print(out.lib32 + " -> " + lib32)
83  device.push(out.lib32, lib32)
84
85  print(out.lib64 + " -> " + lib64)
86  device.push(out.lib64, lib64)
87
88  mkcmd = lambda lib: "'{}={}'".format(lib, ','.join(out.fields))
89
90  if len(out.pid) == 0:
91    print("Getting jdwp pids")
92    new_env = dict(os.environ)
93    new_env["ANDROID_SERIAL"] = device.serial
94    p = subprocess.Popen([device.adb_path, "jdwp"], env=new_env, stdout=subprocess.PIPE)
95    # ADB jdwp doesn't ever exit so just kill it after 1 second to get a list of pids.
96    with concurrent.futures.ProcessPoolExecutor() as ppe:
97      ppe.submit(kill_it, p.pid).result()
98    out.pid = p.communicate()[0].strip().split()
99    p.wait()
100    print(out.pid)
101  print("Clearing logcat")
102  device.shell("logcat -c".split())
103  final = {}
104  print("Getting info from every process dumped to logcat")
105  for p in out.pid:
106    res = check_single_process(p, device, mkcmd, lib32, lib64);
107    if res is not None:
108      final[p] = res
109  device.shell('rm {}'.format(lib32).split())
110  device.shell('rm {}'.format(lib64).split())
111  print(json.dumps(final, indent=2))
112
113def kill_it(p):
114  time.sleep(1)
115  os.kill(p, signal.SIGINT)
116
117def check_single_process(pid, device, mkcmd, bit32, bit64):
118  try:
119    # Link agent into the /data/data/<app>/code_cache directory
120    name = device.shell('cat /proc/{}/cmdline'.format(pid).split())[0].strip('\0')
121    targetdir = str('/data/data/{}/code_cache'.format(str(name).strip()))
122    print("Will place agents in {}".format(targetdir))
123    target32 = device.shell('mktemp -p {}'.format(targetdir).split())[0].strip()
124    print("{} -> {}".format(bit32, target32))
125    target64 = device.shell('mktemp -p {}'.format(targetdir).split())[0].strip()
126    print("{} -> {}".format(bit64, target64))
127    try:
128      device.shell('cp {} {}'.format(bit32, target32).split())
129      device.shell('cp {} {}'.format(bit64, target64).split())
130      device.shell('chmod 555 {}'.format(target32).split())
131      device.shell('chmod 555 {}'.format(target64).split())
132      # Just try attaching both 32 and 64 bit. Wrong one will fail silently.
133      device.shell(['am', 'attach-agent', str(pid), mkcmd(target32)])
134      device.shell(['am', 'attach-agent', str(pid), mkcmd(target64)])
135      time.sleep(0.5)
136      device.shell('kill -3 {}'.format(pid).split())
137      time.sleep(0.5)
138    finally:
139      print("Removing agent copies at {}, {}".format(target32, target64))
140      device.shell(['rm', '-f', target32])
141      device.shell(['rm', '-f', target64])
142    out = []
143    all_fields = []
144    lc_cmd = "logcat -d -b main --pid={} -e '^\\t.*\\t.*\\t[0-9]*\\t[0-9]*$'".format(pid).split(' ')
145    for l in device.shell(lc_cmd)[0].strip().split('\n'):
146      # first 4 are just date and other useless data.
147      data = l.strip().split()[5:]
148      if len(data) < 5:
149        continue
150      # If we run multiple times many copies of the agent will be attached. Just choose one of any
151      # copies for each field.
152      # data is (process, field, field-type, count, size)
153      field = (data[1], data[2])
154      if field not in all_fields:
155        out.append((str(data[0]), str(data[1]), str(data[2]), int(data[3]), int(data[4])))
156        all_fields.append(field)
157    if len(out) != 0:
158      print("pid: " + pid + " -> " + str(out))
159      return out
160    else:
161      return None
162  except adb.device.ShellError as e:
163    print("failed on pid " + repr(pid) + " because " + repr(e))
164    return None
165
166if __name__ == '__main__':
167  main()
168