blob: 2e37e0b1bdd07f2dcec32fffeedc3af298bdeb00 [file] [log] [blame]
Josh Gao043bad72015-09-22 11:43:08 -07001#!/usr/bin/env python
2#
3# Copyright (C) 2015 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
18import adb
19import argparse
20import logging
21import os
Elliott Hughes89e1ecf2017-06-30 14:03:32 -070022import re
Josh Gao043bad72015-09-22 11:43:08 -070023import subprocess
24import sys
25
26# Shared functions across gdbclient.py and ndk-gdb.py.
27import gdbrunner
28
29def get_gdbserver_path(root, arch):
30 path = "{}/prebuilts/misc/android-{}/gdbserver{}/gdbserver{}"
31 if arch.endswith("64"):
32 return path.format(root, arch, "64", "64")
33 else:
34 return path.format(root, arch, "", "")
35
36
Elliott Hughes89e1ecf2017-06-30 14:03:32 -070037def get_tracer_pid(device, pid):
38 if pid is None:
39 return 0
40
41 line, _ = device.shell(["grep", "-e", "^TracerPid:", "/proc/{}/status".format(pid)])
42 tracer_pid = re.sub('TracerPid:\t(.*)\n', r'\1', line)
43 return int(tracer_pid)
44
45
Josh Gao043bad72015-09-22 11:43:08 -070046def parse_args():
47 parser = gdbrunner.ArgumentParser()
48
49 group = parser.add_argument_group(title="attach target")
50 group = group.add_mutually_exclusive_group(required=True)
51 group.add_argument(
52 "-p", dest="target_pid", metavar="PID", type=int,
53 help="attach to a process with specified PID")
54 group.add_argument(
55 "-n", dest="target_name", metavar="NAME",
56 help="attach to a process with specified name")
57 group.add_argument(
58 "-r", dest="run_cmd", metavar="CMD", nargs=argparse.REMAINDER,
59 help="run a binary on the device, with args")
60
61 parser.add_argument(
62 "--port", nargs="?", default="5039",
Elliott Hughes89e1ecf2017-06-30 14:03:32 -070063 help="override the port used on the host [default: 5039]")
Josh Gao043bad72015-09-22 11:43:08 -070064 parser.add_argument(
65 "--user", nargs="?", default="root",
66 help="user to run commands as on the device [default: root]")
67
68 return parser.parse_args()
69
70
71def dump_var(root, variable):
72 make_args = ["make", "CALLED_FROM_SETUP=true",
73 "BUILD_SYSTEM={}/build/core".format(root),
74 "--no-print-directory", "-f",
75 "{}/build/core/config.mk".format(root),
76 "dumpvar-{}".format(variable)]
77
David Purselld1fe92f2015-10-05 15:36:28 -070078 # subprocess cwd argument does not change the PWD shell variable, but
79 # dumpvar.mk uses PWD to create an absolute path, so we need to set it.
80 saved_pwd = os.environ['PWD']
81 os.environ['PWD'] = root
Josh Gao6382f172015-10-02 15:58:05 -070082 make_output = subprocess.check_output(make_args, cwd=root)
David Purselld1fe92f2015-10-05 15:36:28 -070083 os.environ['PWD'] = saved_pwd
Josh Gao043bad72015-09-22 11:43:08 -070084 return make_output.splitlines()[0]
85
86
Elliott Hughes1a2f12d2017-06-02 13:15:59 -070087def verify_device(root, device):
88 names = set([device.get_prop("ro.build.product"), device.get_prop("ro.product.device")])
Josh Gao043bad72015-09-22 11:43:08 -070089 target_device = dump_var(root, "TARGET_DEVICE")
90 if target_device not in names:
91 msg = "TARGET_DEVICE ({}) does not match attached device ({})"
92 sys.exit(msg.format(target_device, ", ".join(names)))
93
94
95def get_remote_pid(device, process_name):
96 processes = gdbrunner.get_processes(device)
97 if process_name not in processes:
98 msg = "failed to find running process {}".format(process_name)
99 sys.exit(msg)
100 pids = processes[process_name]
101 if len(pids) > 1:
102 msg = "multiple processes match '{}': {}".format(process_name, pids)
103 sys.exit(msg)
104
105 # Fetch the binary using the PID later.
106 return pids[0]
107
108
109def ensure_linker(device, sysroot, is64bit):
110 local_path = os.path.join(sysroot, "system", "bin", "linker")
111 remote_path = "/system/bin/linker"
112 if is64bit:
113 local_path += "64"
114 remote_path += "64"
115 if not os.path.exists(local_path):
116 device.pull(remote_path, local_path)
117
118
David Pursell639d1c42015-10-20 15:38:32 -0700119def handle_switches(args, sysroot):
Josh Gao043bad72015-09-22 11:43:08 -0700120 """Fetch the targeted binary and determine how to attach gdb.
121
122 Args:
123 args: Parsed arguments.
124 sysroot: Local sysroot path.
125
126 Returns:
127 (binary_file, attach_pid, run_cmd).
128 Precisely one of attach_pid or run_cmd will be None.
129 """
130
131 device = args.device
132 binary_file = None
133 pid = None
134 run_cmd = None
135
Josh Gao057c2732017-05-24 15:55:50 -0700136 args.su_cmd = ["su", args.user] if args.user else []
137
Josh Gao043bad72015-09-22 11:43:08 -0700138 if args.target_pid:
139 # Fetch the binary using the PID later.
140 pid = args.target_pid
141 elif args.target_name:
142 # Fetch the binary using the PID later.
143 pid = get_remote_pid(device, args.target_name)
144 elif args.run_cmd:
145 if not args.run_cmd[0]:
146 sys.exit("empty command passed to -r")
147 if not args.run_cmd[0].startswith("/"):
148 sys.exit("commands passed to -r must use absolute paths")
149 run_cmd = args.run_cmd
David Pursell639d1c42015-10-20 15:38:32 -0700150 binary_file, local = gdbrunner.find_file(device, run_cmd[0], sysroot,
Josh Gao057c2732017-05-24 15:55:50 -0700151 run_as_cmd=args.su_cmd)
Josh Gao043bad72015-09-22 11:43:08 -0700152 if binary_file is None:
153 assert pid is not None
154 try:
David Pursell639d1c42015-10-20 15:38:32 -0700155 binary_file, local = gdbrunner.find_binary(device, pid, sysroot,
Josh Gao057c2732017-05-24 15:55:50 -0700156 run_as_cmd=args.su_cmd)
Josh Gao043bad72015-09-22 11:43:08 -0700157 except adb.ShellError:
158 sys.exit("failed to pull binary for PID {}".format(pid))
159
David Pursell639d1c42015-10-20 15:38:32 -0700160 if not local:
161 logging.warning("Couldn't find local unstripped executable in {},"
162 " symbols may not be available.".format(sysroot))
163
Josh Gao043bad72015-09-22 11:43:08 -0700164 return (binary_file, pid, run_cmd)
165
David Pursell320f8812015-10-05 14:22:10 -0700166def generate_gdb_script(sysroot, binary_file, is64bit, port, connect_timeout=5):
Josh Gao043bad72015-09-22 11:43:08 -0700167 # Generate a gdb script.
168 # TODO: Detect the zygote and run 'art-on' automatically.
169 root = os.environ["ANDROID_BUILD_TOP"]
170 symbols_dir = os.path.join(sysroot, "system", "lib64" if is64bit else "lib")
171 vendor_dir = os.path.join(sysroot, "vendor", "lib64" if is64bit else "lib")
172
173 solib_search_path = []
174 symbols_paths = ["", "hw", "ssl/engines", "drm", "egl", "soundfx"]
175 vendor_paths = ["", "hw", "egl"]
176 solib_search_path += [os.path.join(symbols_dir, x) for x in symbols_paths]
177 solib_search_path += [os.path.join(vendor_dir, x) for x in vendor_paths]
178 solib_search_path = ":".join(solib_search_path)
179
180 gdb_commands = ""
181 gdb_commands += "file '{}'\n".format(binary_file.name)
Josh Gao19f18ce2015-10-22 16:08:13 -0700182 gdb_commands += "directory '{}'\n".format(root)
Josh Gao043bad72015-09-22 11:43:08 -0700183 gdb_commands += "set solib-absolute-prefix {}\n".format(sysroot)
184 gdb_commands += "set solib-search-path {}\n".format(solib_search_path)
185
186 dalvik_gdb_script = os.path.join(root, "development", "scripts", "gdb",
187 "dalvik.gdb")
188 if not os.path.exists(dalvik_gdb_script):
189 logging.warning(("couldn't find {} - ART debugging options will not " +
190 "be available").format(dalvik_gdb_script))
191 else:
192 gdb_commands += "source {}\n".format(dalvik_gdb_script)
193
David Pursell320f8812015-10-05 14:22:10 -0700194 # Try to connect for a few seconds, sometimes the device gdbserver takes
195 # a little bit to come up, especially on emulators.
196 gdb_commands += """
197python
198
199def target_remote_with_retry(target, timeout_seconds):
200 import time
201 end_time = time.time() + timeout_seconds
202 while True:
203 try:
204 gdb.execute("target remote " + target)
205 return True
206 except gdb.error as e:
207 time_left = end_time - time.time()
208 if time_left < 0 or time_left > timeout_seconds:
209 print("Error: unable to connect to device.")
210 print(e)
211 return False
212 time.sleep(min(0.25, time_left))
213
214target_remote_with_retry(':{}', {})
215
216end
217""".format(port, connect_timeout)
218
Josh Gao043bad72015-09-22 11:43:08 -0700219 return gdb_commands
220
221
222def main():
223 args = parse_args()
224 device = args.device
Josh Gao44b84a82015-10-28 11:57:37 -0700225
226 if device is None:
227 sys.exit("ERROR: Failed to find device.")
228
Josh Gao043bad72015-09-22 11:43:08 -0700229 root = os.environ["ANDROID_BUILD_TOP"]
230 sysroot = dump_var(root, "abs-TARGET_OUT_UNSTRIPPED")
231
232 # Make sure the environment matches the attached device.
Elliott Hughes1a2f12d2017-06-02 13:15:59 -0700233 verify_device(root, device)
Josh Gao043bad72015-09-22 11:43:08 -0700234
235 debug_socket = "/data/local/tmp/debug_socket"
236 pid = None
237 run_cmd = None
238
239 # Fetch binary for -p, -n.
David Pursell639d1c42015-10-20 15:38:32 -0700240 binary_file, pid, run_cmd = handle_switches(args, sysroot)
Josh Gao043bad72015-09-22 11:43:08 -0700241
242 with binary_file:
243 arch = gdbrunner.get_binary_arch(binary_file)
244 is64bit = arch.endswith("64")
245
246 # Make sure we have the linker
247 ensure_linker(device, sysroot, is64bit)
248
Elliott Hughes89e1ecf2017-06-30 14:03:32 -0700249 tracer_pid = get_tracer_pid(device, pid)
250 if tracer_pid == 0:
251 # Start gdbserver.
252 gdbserver_local_path = get_gdbserver_path(root, arch)
253 gdbserver_remote_path = "/data/local/tmp/{}-gdbserver".format(arch)
254 gdbrunner.start_gdbserver(
255 device, gdbserver_local_path, gdbserver_remote_path,
256 target_pid=pid, run_cmd=run_cmd, debug_socket=debug_socket,
257 port=args.port, run_as_cmd=args.su_cmd)
258 else:
259 print "Connecting to tracing pid {} using local port {}".format(tracer_pid, args.port)
260 gdbrunner.forward_gdbserver_port(device, local=args.port,
261 remote="tcp:{}".format(args.port))
Josh Gao043bad72015-09-22 11:43:08 -0700262
263 # Generate a gdb script.
264 gdb_commands = generate_gdb_script(sysroot=sysroot,
265 binary_file=binary_file,
266 is64bit=is64bit,
267 port=args.port)
268
269 # Find where gdb is
270 if sys.platform.startswith("linux"):
271 platform_name = "linux-x86"
272 elif sys.platform.startswith("darwin"):
273 platform_name = "darwin-x86"
274 else:
275 sys.exit("Unknown platform: {}".format(sys.platform))
276 gdb_path = os.path.join(root, "prebuilts", "gdb", platform_name, "bin",
277 "gdb")
278
David Pursell639d1c42015-10-20 15:38:32 -0700279 # Print a newline to separate our messages from the GDB session.
280 print("")
281
Josh Gao043bad72015-09-22 11:43:08 -0700282 # Start gdb.
283 gdbrunner.start_gdb(gdb_path, gdb_commands)
284
285if __name__ == "__main__":
286 main()