blob: d9334ca91a9c32688b482e49b3bab3b35b50a1f6 [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
22import subprocess
23import sys
24
25# Shared functions across gdbclient.py and ndk-gdb.py.
26import gdbrunner
27
28def get_gdbserver_path(root, arch):
29 path = "{}/prebuilts/misc/android-{}/gdbserver{}/gdbserver{}"
30 if arch.endswith("64"):
31 return path.format(root, arch, "64", "64")
32 else:
33 return path.format(root, arch, "", "")
34
35
36def parse_args():
37 parser = gdbrunner.ArgumentParser()
38
39 group = parser.add_argument_group(title="attach target")
40 group = group.add_mutually_exclusive_group(required=True)
41 group.add_argument(
42 "-p", dest="target_pid", metavar="PID", type=int,
43 help="attach to a process with specified PID")
44 group.add_argument(
45 "-n", dest="target_name", metavar="NAME",
46 help="attach to a process with specified name")
47 group.add_argument(
48 "-r", dest="run_cmd", metavar="CMD", nargs=argparse.REMAINDER,
49 help="run a binary on the device, with args")
50
51 parser.add_argument(
52 "--port", nargs="?", default="5039",
53 help="override the port used on the host")
54 parser.add_argument(
55 "--user", nargs="?", default="root",
56 help="user to run commands as on the device [default: root]")
57
58 return parser.parse_args()
59
60
61def dump_var(root, variable):
62 make_args = ["make", "CALLED_FROM_SETUP=true",
63 "BUILD_SYSTEM={}/build/core".format(root),
64 "--no-print-directory", "-f",
65 "{}/build/core/config.mk".format(root),
66 "dumpvar-{}".format(variable)]
67
David Purselld1fe92f2015-10-05 15:36:28 -070068 # subprocess cwd argument does not change the PWD shell variable, but
69 # dumpvar.mk uses PWD to create an absolute path, so we need to set it.
70 saved_pwd = os.environ['PWD']
71 os.environ['PWD'] = root
Josh Gao6382f172015-10-02 15:58:05 -070072 make_output = subprocess.check_output(make_args, cwd=root)
David Purselld1fe92f2015-10-05 15:36:28 -070073 os.environ['PWD'] = saved_pwd
Josh Gao043bad72015-09-22 11:43:08 -070074 return make_output.splitlines()[0]
75
76
77def verify_device(root, props):
78 names = set([props["ro.build.product"], props["ro.product.device"]])
79 target_device = dump_var(root, "TARGET_DEVICE")
80 if target_device not in names:
81 msg = "TARGET_DEVICE ({}) does not match attached device ({})"
82 sys.exit(msg.format(target_device, ", ".join(names)))
83
84
85def get_remote_pid(device, process_name):
86 processes = gdbrunner.get_processes(device)
87 if process_name not in processes:
88 msg = "failed to find running process {}".format(process_name)
89 sys.exit(msg)
90 pids = processes[process_name]
91 if len(pids) > 1:
92 msg = "multiple processes match '{}': {}".format(process_name, pids)
93 sys.exit(msg)
94
95 # Fetch the binary using the PID later.
96 return pids[0]
97
98
99def ensure_linker(device, sysroot, is64bit):
100 local_path = os.path.join(sysroot, "system", "bin", "linker")
101 remote_path = "/system/bin/linker"
102 if is64bit:
103 local_path += "64"
104 remote_path += "64"
105 if not os.path.exists(local_path):
106 device.pull(remote_path, local_path)
107
108
David Pursell639d1c42015-10-20 15:38:32 -0700109def handle_switches(args, sysroot):
Josh Gao043bad72015-09-22 11:43:08 -0700110 """Fetch the targeted binary and determine how to attach gdb.
111
112 Args:
113 args: Parsed arguments.
114 sysroot: Local sysroot path.
115
116 Returns:
117 (binary_file, attach_pid, run_cmd).
118 Precisely one of attach_pid or run_cmd will be None.
119 """
120
121 device = args.device
122 binary_file = None
123 pid = None
124 run_cmd = None
125
Josh Gao057c2732017-05-24 15:55:50 -0700126 args.su_cmd = ["su", args.user] if args.user else []
127
Josh Gao043bad72015-09-22 11:43:08 -0700128 if args.target_pid:
129 # Fetch the binary using the PID later.
130 pid = args.target_pid
131 elif args.target_name:
132 # Fetch the binary using the PID later.
133 pid = get_remote_pid(device, args.target_name)
134 elif args.run_cmd:
135 if not args.run_cmd[0]:
136 sys.exit("empty command passed to -r")
137 if not args.run_cmd[0].startswith("/"):
138 sys.exit("commands passed to -r must use absolute paths")
139 run_cmd = args.run_cmd
David Pursell639d1c42015-10-20 15:38:32 -0700140 binary_file, local = gdbrunner.find_file(device, run_cmd[0], sysroot,
Josh Gao057c2732017-05-24 15:55:50 -0700141 run_as_cmd=args.su_cmd)
Josh Gao043bad72015-09-22 11:43:08 -0700142 if binary_file is None:
143 assert pid is not None
144 try:
David Pursell639d1c42015-10-20 15:38:32 -0700145 binary_file, local = gdbrunner.find_binary(device, pid, sysroot,
Josh Gao057c2732017-05-24 15:55:50 -0700146 run_as_cmd=args.su_cmd)
Josh Gao043bad72015-09-22 11:43:08 -0700147 except adb.ShellError:
148 sys.exit("failed to pull binary for PID {}".format(pid))
149
David Pursell639d1c42015-10-20 15:38:32 -0700150 if not local:
151 logging.warning("Couldn't find local unstripped executable in {},"
152 " symbols may not be available.".format(sysroot))
153
Josh Gao043bad72015-09-22 11:43:08 -0700154 return (binary_file, pid, run_cmd)
155
David Pursell320f8812015-10-05 14:22:10 -0700156def generate_gdb_script(sysroot, binary_file, is64bit, port, connect_timeout=5):
Josh Gao043bad72015-09-22 11:43:08 -0700157 # Generate a gdb script.
158 # TODO: Detect the zygote and run 'art-on' automatically.
159 root = os.environ["ANDROID_BUILD_TOP"]
160 symbols_dir = os.path.join(sysroot, "system", "lib64" if is64bit else "lib")
161 vendor_dir = os.path.join(sysroot, "vendor", "lib64" if is64bit else "lib")
162
163 solib_search_path = []
164 symbols_paths = ["", "hw", "ssl/engines", "drm", "egl", "soundfx"]
165 vendor_paths = ["", "hw", "egl"]
166 solib_search_path += [os.path.join(symbols_dir, x) for x in symbols_paths]
167 solib_search_path += [os.path.join(vendor_dir, x) for x in vendor_paths]
168 solib_search_path = ":".join(solib_search_path)
169
170 gdb_commands = ""
171 gdb_commands += "file '{}'\n".format(binary_file.name)
Josh Gao19f18ce2015-10-22 16:08:13 -0700172 gdb_commands += "directory '{}'\n".format(root)
Josh Gao043bad72015-09-22 11:43:08 -0700173 gdb_commands += "set solib-absolute-prefix {}\n".format(sysroot)
174 gdb_commands += "set solib-search-path {}\n".format(solib_search_path)
175
176 dalvik_gdb_script = os.path.join(root, "development", "scripts", "gdb",
177 "dalvik.gdb")
178 if not os.path.exists(dalvik_gdb_script):
179 logging.warning(("couldn't find {} - ART debugging options will not " +
180 "be available").format(dalvik_gdb_script))
181 else:
182 gdb_commands += "source {}\n".format(dalvik_gdb_script)
183
David Pursell320f8812015-10-05 14:22:10 -0700184 # Try to connect for a few seconds, sometimes the device gdbserver takes
185 # a little bit to come up, especially on emulators.
186 gdb_commands += """
187python
188
189def target_remote_with_retry(target, timeout_seconds):
190 import time
191 end_time = time.time() + timeout_seconds
192 while True:
193 try:
194 gdb.execute("target remote " + target)
195 return True
196 except gdb.error as e:
197 time_left = end_time - time.time()
198 if time_left < 0 or time_left > timeout_seconds:
199 print("Error: unable to connect to device.")
200 print(e)
201 return False
202 time.sleep(min(0.25, time_left))
203
204target_remote_with_retry(':{}', {})
205
206end
207""".format(port, connect_timeout)
208
Josh Gao043bad72015-09-22 11:43:08 -0700209 return gdb_commands
210
211
212def main():
213 args = parse_args()
214 device = args.device
Josh Gao44b84a82015-10-28 11:57:37 -0700215
216 if device is None:
217 sys.exit("ERROR: Failed to find device.")
218
Josh Gao043bad72015-09-22 11:43:08 -0700219 props = device.get_props()
220
221 root = os.environ["ANDROID_BUILD_TOP"]
222 sysroot = dump_var(root, "abs-TARGET_OUT_UNSTRIPPED")
223
224 # Make sure the environment matches the attached device.
225 verify_device(root, props)
226
227 debug_socket = "/data/local/tmp/debug_socket"
228 pid = None
229 run_cmd = None
230
231 # Fetch binary for -p, -n.
David Pursell639d1c42015-10-20 15:38:32 -0700232 binary_file, pid, run_cmd = handle_switches(args, sysroot)
Josh Gao043bad72015-09-22 11:43:08 -0700233
234 with binary_file:
235 arch = gdbrunner.get_binary_arch(binary_file)
236 is64bit = arch.endswith("64")
237
238 # Make sure we have the linker
239 ensure_linker(device, sysroot, is64bit)
240
241 # Start gdbserver.
242 gdbserver_local_path = get_gdbserver_path(root, arch)
243 gdbserver_remote_path = "/data/local/tmp/{}-gdbserver".format(arch)
244 gdbrunner.start_gdbserver(
245 device, gdbserver_local_path, gdbserver_remote_path,
246 target_pid=pid, run_cmd=run_cmd, debug_socket=debug_socket,
Josh Gao057c2732017-05-24 15:55:50 -0700247 port=args.port, run_as_cmd=args.su_cmd)
Josh Gao043bad72015-09-22 11:43:08 -0700248
249 # Generate a gdb script.
250 gdb_commands = generate_gdb_script(sysroot=sysroot,
251 binary_file=binary_file,
252 is64bit=is64bit,
253 port=args.port)
254
255 # Find where gdb is
256 if sys.platform.startswith("linux"):
257 platform_name = "linux-x86"
258 elif sys.platform.startswith("darwin"):
259 platform_name = "darwin-x86"
260 else:
261 sys.exit("Unknown platform: {}".format(sys.platform))
262 gdb_path = os.path.join(root, "prebuilts", "gdb", platform_name, "bin",
263 "gdb")
264
David Pursell639d1c42015-10-20 15:38:32 -0700265 # Print a newline to separate our messages from the GDB session.
266 print("")
267
Josh Gao043bad72015-09-22 11:43:08 -0700268 # Start gdb.
269 gdbrunner.start_gdb(gdb_path, gdb_commands)
270
271if __name__ == "__main__":
272 main()