blob: 9d029efa757088a694eccec847f307d22ad9e690 [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
109def handle_switches(args):
110 """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
126 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")
135 if not args.run_cmd[0].startswith("/"):
136 sys.exit("commands passed to -r must use absolute paths")
137 run_cmd = args.run_cmd
138 binary_file = gdbrunner.pull_file(device, run_cmd[0], user=args.user)
139 if binary_file is None:
140 assert pid is not None
141 try:
142 binary_file = gdbrunner.pull_binary(device, pid=pid, user=args.user)
143 except adb.ShellError:
144 sys.exit("failed to pull binary for PID {}".format(pid))
145
146 return (binary_file, pid, run_cmd)
147
David Pursell320f8812015-10-05 14:22:10 -0700148def generate_gdb_script(sysroot, binary_file, is64bit, port, connect_timeout=5):
Josh Gao043bad72015-09-22 11:43:08 -0700149 # Generate a gdb script.
150 # TODO: Detect the zygote and run 'art-on' automatically.
151 root = os.environ["ANDROID_BUILD_TOP"]
152 symbols_dir = os.path.join(sysroot, "system", "lib64" if is64bit else "lib")
153 vendor_dir = os.path.join(sysroot, "vendor", "lib64" if is64bit else "lib")
154
155 solib_search_path = []
156 symbols_paths = ["", "hw", "ssl/engines", "drm", "egl", "soundfx"]
157 vendor_paths = ["", "hw", "egl"]
158 solib_search_path += [os.path.join(symbols_dir, x) for x in symbols_paths]
159 solib_search_path += [os.path.join(vendor_dir, x) for x in vendor_paths]
160 solib_search_path = ":".join(solib_search_path)
161
162 gdb_commands = ""
163 gdb_commands += "file '{}'\n".format(binary_file.name)
164 gdb_commands += "set solib-absolute-prefix {}\n".format(sysroot)
165 gdb_commands += "set solib-search-path {}\n".format(solib_search_path)
166
167 dalvik_gdb_script = os.path.join(root, "development", "scripts", "gdb",
168 "dalvik.gdb")
169 if not os.path.exists(dalvik_gdb_script):
170 logging.warning(("couldn't find {} - ART debugging options will not " +
171 "be available").format(dalvik_gdb_script))
172 else:
173 gdb_commands += "source {}\n".format(dalvik_gdb_script)
174
David Pursell320f8812015-10-05 14:22:10 -0700175 # Try to connect for a few seconds, sometimes the device gdbserver takes
176 # a little bit to come up, especially on emulators.
177 gdb_commands += """
178python
179
180def target_remote_with_retry(target, timeout_seconds):
181 import time
182 end_time = time.time() + timeout_seconds
183 while True:
184 try:
185 gdb.execute("target remote " + target)
186 return True
187 except gdb.error as e:
188 time_left = end_time - time.time()
189 if time_left < 0 or time_left > timeout_seconds:
190 print("Error: unable to connect to device.")
191 print(e)
192 return False
193 time.sleep(min(0.25, time_left))
194
195target_remote_with_retry(':{}', {})
196
197end
198""".format(port, connect_timeout)
199
Josh Gao043bad72015-09-22 11:43:08 -0700200 return gdb_commands
201
202
203def main():
204 args = parse_args()
205 device = args.device
206 props = device.get_props()
207
208 root = os.environ["ANDROID_BUILD_TOP"]
209 sysroot = dump_var(root, "abs-TARGET_OUT_UNSTRIPPED")
210
211 # Make sure the environment matches the attached device.
212 verify_device(root, props)
213
214 debug_socket = "/data/local/tmp/debug_socket"
215 pid = None
216 run_cmd = None
217
218 # Fetch binary for -p, -n.
219 binary_file, pid, run_cmd = handle_switches(args)
220
221 with binary_file:
222 arch = gdbrunner.get_binary_arch(binary_file)
223 is64bit = arch.endswith("64")
224
225 # Make sure we have the linker
226 ensure_linker(device, sysroot, is64bit)
227
228 # Start gdbserver.
229 gdbserver_local_path = get_gdbserver_path(root, arch)
230 gdbserver_remote_path = "/data/local/tmp/{}-gdbserver".format(arch)
231 gdbrunner.start_gdbserver(
232 device, gdbserver_local_path, gdbserver_remote_path,
233 target_pid=pid, run_cmd=run_cmd, debug_socket=debug_socket,
234 port=args.port, user=args.user)
235
236 # Generate a gdb script.
237 gdb_commands = generate_gdb_script(sysroot=sysroot,
238 binary_file=binary_file,
239 is64bit=is64bit,
240 port=args.port)
241
242 # Find where gdb is
243 if sys.platform.startswith("linux"):
244 platform_name = "linux-x86"
245 elif sys.platform.startswith("darwin"):
246 platform_name = "darwin-x86"
247 else:
248 sys.exit("Unknown platform: {}".format(sys.platform))
249 gdb_path = os.path.join(root, "prebuilts", "gdb", platform_name, "bin",
250 "gdb")
251
252 # Start gdb.
253 gdbrunner.start_gdb(gdb_path, gdb_commands)
254
255if __name__ == "__main__":
256 main()