blob: 19a4a172945cecca5bc3b3a0215311f973d10af8 [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
Peter Collingbourne63bf1082018-12-19 20:51:42 -080068 parser.add_argument(
69 "--env", nargs=1, action="append", metavar="VAR=VALUE",
70 help="set environment variable when running a binary")
71
Josh Gao043bad72015-09-22 11:43:08 -070072 return parser.parse_args()
73
74
Elliott Hughes1a2f12d2017-06-02 13:15:59 -070075def verify_device(root, device):
Josh Gao466e2892017-07-13 15:39:05 -070076 name = device.get_prop("ro.product.name")
77 target_device = os.environ["TARGET_PRODUCT"]
78 if target_device != name:
79 msg = "TARGET_PRODUCT ({}) does not match attached device ({})"
80 sys.exit(msg.format(target_device, name))
Josh Gao043bad72015-09-22 11:43:08 -070081
82
83def get_remote_pid(device, process_name):
84 processes = gdbrunner.get_processes(device)
85 if process_name not in processes:
86 msg = "failed to find running process {}".format(process_name)
87 sys.exit(msg)
88 pids = processes[process_name]
89 if len(pids) > 1:
90 msg = "multiple processes match '{}': {}".format(process_name, pids)
91 sys.exit(msg)
92
93 # Fetch the binary using the PID later.
94 return pids[0]
95
96
97def ensure_linker(device, sysroot, is64bit):
98 local_path = os.path.join(sysroot, "system", "bin", "linker")
99 remote_path = "/system/bin/linker"
100 if is64bit:
101 local_path += "64"
102 remote_path += "64"
103 if not os.path.exists(local_path):
104 device.pull(remote_path, local_path)
105
106
David Pursell639d1c42015-10-20 15:38:32 -0700107def handle_switches(args, sysroot):
Josh Gao043bad72015-09-22 11:43:08 -0700108 """Fetch the targeted binary and determine how to attach gdb.
109
110 Args:
111 args: Parsed arguments.
112 sysroot: Local sysroot path.
113
114 Returns:
115 (binary_file, attach_pid, run_cmd).
116 Precisely one of attach_pid or run_cmd will be None.
117 """
118
119 device = args.device
120 binary_file = None
121 pid = None
122 run_cmd = None
123
Josh Gao057c2732017-05-24 15:55:50 -0700124 args.su_cmd = ["su", args.user] if args.user else []
125
Josh Gao043bad72015-09-22 11:43:08 -0700126 if args.target_pid:
127 # Fetch the binary using the PID later.
128 pid = args.target_pid
129 elif args.target_name:
130 # Fetch the binary using the PID later.
131 pid = get_remote_pid(device, args.target_name)
132 elif args.run_cmd:
133 if not args.run_cmd[0]:
134 sys.exit("empty command passed to -r")
Josh Gao043bad72015-09-22 11:43:08 -0700135 run_cmd = args.run_cmd
Kevin Rocard258c89e2017-07-12 18:21:29 -0700136 if not run_cmd[0].startswith("/"):
137 try:
138 run_cmd[0] = gdbrunner.find_executable_path(device, args.run_cmd[0],
139 run_as_cmd=args.su_cmd)
140 except RuntimeError:
141 sys.exit("Could not find executable '{}' passed to -r, "
142 "please provide an absolute path.".format(args.run_cmd[0]))
143
David Pursell639d1c42015-10-20 15:38:32 -0700144 binary_file, local = gdbrunner.find_file(device, run_cmd[0], sysroot,
Josh Gao057c2732017-05-24 15:55:50 -0700145 run_as_cmd=args.su_cmd)
Josh Gao043bad72015-09-22 11:43:08 -0700146 if binary_file is None:
147 assert pid is not None
148 try:
David Pursell639d1c42015-10-20 15:38:32 -0700149 binary_file, local = gdbrunner.find_binary(device, pid, sysroot,
Josh Gao057c2732017-05-24 15:55:50 -0700150 run_as_cmd=args.su_cmd)
Josh Gao043bad72015-09-22 11:43:08 -0700151 except adb.ShellError:
152 sys.exit("failed to pull binary for PID {}".format(pid))
153
David Pursell639d1c42015-10-20 15:38:32 -0700154 if not local:
155 logging.warning("Couldn't find local unstripped executable in {},"
156 " symbols may not be available.".format(sysroot))
157
Josh Gao043bad72015-09-22 11:43:08 -0700158 return (binary_file, pid, run_cmd)
159
Josh Gao466e2892017-07-13 15:39:05 -0700160
David Pursell320f8812015-10-05 14:22:10 -0700161def generate_gdb_script(sysroot, binary_file, is64bit, port, connect_timeout=5):
Josh Gao043bad72015-09-22 11:43:08 -0700162 # Generate a gdb script.
163 # TODO: Detect the zygote and run 'art-on' automatically.
164 root = os.environ["ANDROID_BUILD_TOP"]
165 symbols_dir = os.path.join(sysroot, "system", "lib64" if is64bit else "lib")
166 vendor_dir = os.path.join(sysroot, "vendor", "lib64" if is64bit else "lib")
167
168 solib_search_path = []
169 symbols_paths = ["", "hw", "ssl/engines", "drm", "egl", "soundfx"]
170 vendor_paths = ["", "hw", "egl"]
171 solib_search_path += [os.path.join(symbols_dir, x) for x in symbols_paths]
172 solib_search_path += [os.path.join(vendor_dir, x) for x in vendor_paths]
173 solib_search_path = ":".join(solib_search_path)
174
175 gdb_commands = ""
176 gdb_commands += "file '{}'\n".format(binary_file.name)
Josh Gao19f18ce2015-10-22 16:08:13 -0700177 gdb_commands += "directory '{}'\n".format(root)
Josh Gao043bad72015-09-22 11:43:08 -0700178 gdb_commands += "set solib-absolute-prefix {}\n".format(sysroot)
179 gdb_commands += "set solib-search-path {}\n".format(solib_search_path)
180
181 dalvik_gdb_script = os.path.join(root, "development", "scripts", "gdb",
182 "dalvik.gdb")
183 if not os.path.exists(dalvik_gdb_script):
184 logging.warning(("couldn't find {} - ART debugging options will not " +
185 "be available").format(dalvik_gdb_script))
186 else:
187 gdb_commands += "source {}\n".format(dalvik_gdb_script)
188
David Pursell320f8812015-10-05 14:22:10 -0700189 # Try to connect for a few seconds, sometimes the device gdbserver takes
190 # a little bit to come up, especially on emulators.
191 gdb_commands += """
192python
193
194def target_remote_with_retry(target, timeout_seconds):
195 import time
196 end_time = time.time() + timeout_seconds
197 while True:
198 try:
Dan Albertd124bc72018-06-26 11:15:16 -0700199 gdb.execute("target extended-remote " + target)
David Pursell320f8812015-10-05 14:22:10 -0700200 return True
201 except gdb.error as e:
202 time_left = end_time - time.time()
203 if time_left < 0 or time_left > timeout_seconds:
204 print("Error: unable to connect to device.")
205 print(e)
206 return False
207 time.sleep(min(0.25, time_left))
208
209target_remote_with_retry(':{}', {})
210
211end
212""".format(port, connect_timeout)
213
Josh Gao043bad72015-09-22 11:43:08 -0700214 return gdb_commands
215
216
217def main():
Josh Gao466e2892017-07-13 15:39:05 -0700218 required_env = ["ANDROID_BUILD_TOP",
219 "ANDROID_PRODUCT_OUT", "TARGET_PRODUCT"]
220 for env in required_env:
221 if env not in os.environ:
222 sys.exit(
223 "Environment variable '{}' not defined, have you run lunch?".format(env))
224
Josh Gao043bad72015-09-22 11:43:08 -0700225 args = parse_args()
226 device = args.device
Josh Gao44b84a82015-10-28 11:57:37 -0700227
228 if device is None:
229 sys.exit("ERROR: Failed to find device.")
230
Josh Gao043bad72015-09-22 11:43:08 -0700231 root = os.environ["ANDROID_BUILD_TOP"]
Josh Gao466e2892017-07-13 15:39:05 -0700232 sysroot = os.path.join(os.environ["ANDROID_PRODUCT_OUT"], "symbols")
Josh Gao043bad72015-09-22 11:43:08 -0700233
234 # Make sure the environment matches the attached device.
Elliott Hughes1a2f12d2017-06-02 13:15:59 -0700235 verify_device(root, device)
Josh Gao043bad72015-09-22 11:43:08 -0700236
237 debug_socket = "/data/local/tmp/debug_socket"
238 pid = None
239 run_cmd = None
240
241 # Fetch binary for -p, -n.
David Pursell639d1c42015-10-20 15:38:32 -0700242 binary_file, pid, run_cmd = handle_switches(args, sysroot)
Josh Gao043bad72015-09-22 11:43:08 -0700243
244 with binary_file:
245 arch = gdbrunner.get_binary_arch(binary_file)
246 is64bit = arch.endswith("64")
247
248 # Make sure we have the linker
249 ensure_linker(device, sysroot, is64bit)
250
Elliott Hughes89e1ecf2017-06-30 14:03:32 -0700251 tracer_pid = get_tracer_pid(device, pid)
252 if tracer_pid == 0:
Peter Collingbourne63bf1082018-12-19 20:51:42 -0800253 cmd_prefix = args.su_cmd
254 if args.env:
255 cmd_prefix += ['env'] + [v[0] for v in args.env]
256
Elliott Hughes89e1ecf2017-06-30 14:03:32 -0700257 # Start gdbserver.
258 gdbserver_local_path = get_gdbserver_path(root, arch)
259 gdbserver_remote_path = "/data/local/tmp/{}-gdbserver".format(arch)
260 gdbrunner.start_gdbserver(
261 device, gdbserver_local_path, gdbserver_remote_path,
262 target_pid=pid, run_cmd=run_cmd, debug_socket=debug_socket,
Peter Collingbourne63bf1082018-12-19 20:51:42 -0800263 port=args.port, run_as_cmd=cmd_prefix)
Elliott Hughes89e1ecf2017-06-30 14:03:32 -0700264 else:
265 print "Connecting to tracing pid {} using local port {}".format(tracer_pid, args.port)
266 gdbrunner.forward_gdbserver_port(device, local=args.port,
267 remote="tcp:{}".format(args.port))
Josh Gao043bad72015-09-22 11:43:08 -0700268
269 # Generate a gdb script.
270 gdb_commands = generate_gdb_script(sysroot=sysroot,
271 binary_file=binary_file,
272 is64bit=is64bit,
273 port=args.port)
274
275 # Find where gdb is
276 if sys.platform.startswith("linux"):
277 platform_name = "linux-x86"
278 elif sys.platform.startswith("darwin"):
279 platform_name = "darwin-x86"
280 else:
281 sys.exit("Unknown platform: {}".format(sys.platform))
282 gdb_path = os.path.join(root, "prebuilts", "gdb", platform_name, "bin",
283 "gdb")
284
David Pursell639d1c42015-10-20 15:38:32 -0700285 # Print a newline to separate our messages from the GDB session.
286 print("")
287
Josh Gao043bad72015-09-22 11:43:08 -0700288 # Start gdb.
289 gdbrunner.start_gdb(gdb_path, gdb_commands)
290
291if __name__ == "__main__":
292 main()