blob: 811d564e726fd2e5d0f6f34dc6a556be16921438 [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
Josh Gao6382f172015-10-02 15:58:05 -070068 make_output = subprocess.check_output(make_args, cwd=root)
Josh Gao043bad72015-09-22 11:43:08 -070069 return make_output.splitlines()[0]
70
71
72def verify_device(root, props):
73 names = set([props["ro.build.product"], props["ro.product.device"]])
74 target_device = dump_var(root, "TARGET_DEVICE")
75 if target_device not in names:
76 msg = "TARGET_DEVICE ({}) does not match attached device ({})"
77 sys.exit(msg.format(target_device, ", ".join(names)))
78
79
80def get_remote_pid(device, process_name):
81 processes = gdbrunner.get_processes(device)
82 if process_name not in processes:
83 msg = "failed to find running process {}".format(process_name)
84 sys.exit(msg)
85 pids = processes[process_name]
86 if len(pids) > 1:
87 msg = "multiple processes match '{}': {}".format(process_name, pids)
88 sys.exit(msg)
89
90 # Fetch the binary using the PID later.
91 return pids[0]
92
93
94def ensure_linker(device, sysroot, is64bit):
95 local_path = os.path.join(sysroot, "system", "bin", "linker")
96 remote_path = "/system/bin/linker"
97 if is64bit:
98 local_path += "64"
99 remote_path += "64"
100 if not os.path.exists(local_path):
101 device.pull(remote_path, local_path)
102
103
104def handle_switches(args):
105 """Fetch the targeted binary and determine how to attach gdb.
106
107 Args:
108 args: Parsed arguments.
109 sysroot: Local sysroot path.
110
111 Returns:
112 (binary_file, attach_pid, run_cmd).
113 Precisely one of attach_pid or run_cmd will be None.
114 """
115
116 device = args.device
117 binary_file = None
118 pid = None
119 run_cmd = None
120
121 if args.target_pid:
122 # Fetch the binary using the PID later.
123 pid = args.target_pid
124 elif args.target_name:
125 # Fetch the binary using the PID later.
126 pid = get_remote_pid(device, args.target_name)
127 elif args.run_cmd:
128 if not args.run_cmd[0]:
129 sys.exit("empty command passed to -r")
130 if not args.run_cmd[0].startswith("/"):
131 sys.exit("commands passed to -r must use absolute paths")
132 run_cmd = args.run_cmd
133 binary_file = gdbrunner.pull_file(device, run_cmd[0], user=args.user)
134 if binary_file is None:
135 assert pid is not None
136 try:
137 binary_file = gdbrunner.pull_binary(device, pid=pid, user=args.user)
138 except adb.ShellError:
139 sys.exit("failed to pull binary for PID {}".format(pid))
140
141 return (binary_file, pid, run_cmd)
142
David Pursell320f8812015-10-05 14:22:10 -0700143def generate_gdb_script(sysroot, binary_file, is64bit, port, connect_timeout=5):
Josh Gao043bad72015-09-22 11:43:08 -0700144 # Generate a gdb script.
145 # TODO: Detect the zygote and run 'art-on' automatically.
146 root = os.environ["ANDROID_BUILD_TOP"]
147 symbols_dir = os.path.join(sysroot, "system", "lib64" if is64bit else "lib")
148 vendor_dir = os.path.join(sysroot, "vendor", "lib64" if is64bit else "lib")
149
150 solib_search_path = []
151 symbols_paths = ["", "hw", "ssl/engines", "drm", "egl", "soundfx"]
152 vendor_paths = ["", "hw", "egl"]
153 solib_search_path += [os.path.join(symbols_dir, x) for x in symbols_paths]
154 solib_search_path += [os.path.join(vendor_dir, x) for x in vendor_paths]
155 solib_search_path = ":".join(solib_search_path)
156
157 gdb_commands = ""
158 gdb_commands += "file '{}'\n".format(binary_file.name)
159 gdb_commands += "set solib-absolute-prefix {}\n".format(sysroot)
160 gdb_commands += "set solib-search-path {}\n".format(solib_search_path)
161
162 dalvik_gdb_script = os.path.join(root, "development", "scripts", "gdb",
163 "dalvik.gdb")
164 if not os.path.exists(dalvik_gdb_script):
165 logging.warning(("couldn't find {} - ART debugging options will not " +
166 "be available").format(dalvik_gdb_script))
167 else:
168 gdb_commands += "source {}\n".format(dalvik_gdb_script)
169
David Pursell320f8812015-10-05 14:22:10 -0700170 # Try to connect for a few seconds, sometimes the device gdbserver takes
171 # a little bit to come up, especially on emulators.
172 gdb_commands += """
173python
174
175def target_remote_with_retry(target, timeout_seconds):
176 import time
177 end_time = time.time() + timeout_seconds
178 while True:
179 try:
180 gdb.execute("target remote " + target)
181 return True
182 except gdb.error as e:
183 time_left = end_time - time.time()
184 if time_left < 0 or time_left > timeout_seconds:
185 print("Error: unable to connect to device.")
186 print(e)
187 return False
188 time.sleep(min(0.25, time_left))
189
190target_remote_with_retry(':{}', {})
191
192end
193""".format(port, connect_timeout)
194
Josh Gao043bad72015-09-22 11:43:08 -0700195 return gdb_commands
196
197
198def main():
199 args = parse_args()
200 device = args.device
201 props = device.get_props()
202
203 root = os.environ["ANDROID_BUILD_TOP"]
204 sysroot = dump_var(root, "abs-TARGET_OUT_UNSTRIPPED")
205
206 # Make sure the environment matches the attached device.
207 verify_device(root, props)
208
209 debug_socket = "/data/local/tmp/debug_socket"
210 pid = None
211 run_cmd = None
212
213 # Fetch binary for -p, -n.
214 binary_file, pid, run_cmd = handle_switches(args)
215
216 with binary_file:
217 arch = gdbrunner.get_binary_arch(binary_file)
218 is64bit = arch.endswith("64")
219
220 # Make sure we have the linker
221 ensure_linker(device, sysroot, is64bit)
222
223 # Start gdbserver.
224 gdbserver_local_path = get_gdbserver_path(root, arch)
225 gdbserver_remote_path = "/data/local/tmp/{}-gdbserver".format(arch)
226 gdbrunner.start_gdbserver(
227 device, gdbserver_local_path, gdbserver_remote_path,
228 target_pid=pid, run_cmd=run_cmd, debug_socket=debug_socket,
229 port=args.port, user=args.user)
230
231 # Generate a gdb script.
232 gdb_commands = generate_gdb_script(sysroot=sysroot,
233 binary_file=binary_file,
234 is64bit=is64bit,
235 port=args.port)
236
237 # Find where gdb is
238 if sys.platform.startswith("linux"):
239 platform_name = "linux-x86"
240 elif sys.platform.startswith("darwin"):
241 platform_name = "darwin-x86"
242 else:
243 sys.exit("Unknown platform: {}".format(sys.platform))
244 gdb_path = os.path.join(root, "prebuilts", "gdb", platform_name, "bin",
245 "gdb")
246
247 # Start gdb.
248 gdbrunner.start_gdb(gdb_path, gdb_commands)
249
250if __name__ == "__main__":
251 main()