blob: 4ed5c59cdc5f0b7da2c61648da7a11e346057848 [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)
Josh Gao19f18ce2015-10-22 16:08:13 -0700164 gdb_commands += "directory '{}'\n".format(root)
Josh Gao043bad72015-09-22 11:43:08 -0700165 gdb_commands += "set solib-absolute-prefix {}\n".format(sysroot)
166 gdb_commands += "set solib-search-path {}\n".format(solib_search_path)
167
168 dalvik_gdb_script = os.path.join(root, "development", "scripts", "gdb",
169 "dalvik.gdb")
170 if not os.path.exists(dalvik_gdb_script):
171 logging.warning(("couldn't find {} - ART debugging options will not " +
172 "be available").format(dalvik_gdb_script))
173 else:
174 gdb_commands += "source {}\n".format(dalvik_gdb_script)
175
David Pursell320f8812015-10-05 14:22:10 -0700176 # Try to connect for a few seconds, sometimes the device gdbserver takes
177 # a little bit to come up, especially on emulators.
178 gdb_commands += """
179python
180
181def target_remote_with_retry(target, timeout_seconds):
182 import time
183 end_time = time.time() + timeout_seconds
184 while True:
185 try:
186 gdb.execute("target remote " + target)
187 return True
188 except gdb.error as e:
189 time_left = end_time - time.time()
190 if time_left < 0 or time_left > timeout_seconds:
191 print("Error: unable to connect to device.")
192 print(e)
193 return False
194 time.sleep(min(0.25, time_left))
195
196target_remote_with_retry(':{}', {})
197
198end
199""".format(port, connect_timeout)
200
Josh Gao043bad72015-09-22 11:43:08 -0700201 return gdb_commands
202
203
204def main():
205 args = parse_args()
206 device = args.device
207 props = device.get_props()
208
209 root = os.environ["ANDROID_BUILD_TOP"]
210 sysroot = dump_var(root, "abs-TARGET_OUT_UNSTRIPPED")
211
212 # Make sure the environment matches the attached device.
213 verify_device(root, props)
214
215 debug_socket = "/data/local/tmp/debug_socket"
216 pid = None
217 run_cmd = None
218
219 # Fetch binary for -p, -n.
220 binary_file, pid, run_cmd = handle_switches(args)
221
222 with binary_file:
223 arch = gdbrunner.get_binary_arch(binary_file)
224 is64bit = arch.endswith("64")
225
226 # Make sure we have the linker
227 ensure_linker(device, sysroot, is64bit)
228
229 # Start gdbserver.
230 gdbserver_local_path = get_gdbserver_path(root, arch)
231 gdbserver_remote_path = "/data/local/tmp/{}-gdbserver".format(arch)
232 gdbrunner.start_gdbserver(
233 device, gdbserver_local_path, gdbserver_remote_path,
234 target_pid=pid, run_cmd=run_cmd, debug_socket=debug_socket,
235 port=args.port, user=args.user)
236
237 # Generate a gdb script.
238 gdb_commands = generate_gdb_script(sysroot=sysroot,
239 binary_file=binary_file,
240 is64bit=is64bit,
241 port=args.port)
242
243 # Find where gdb is
244 if sys.platform.startswith("linux"):
245 platform_name = "linux-x86"
246 elif sys.platform.startswith("darwin"):
247 platform_name = "darwin-x86"
248 else:
249 sys.exit("Unknown platform: {}".format(sys.platform))
250 gdb_path = os.path.join(root, "prebuilts", "gdb", platform_name, "bin",
251 "gdb")
252
253 # Start gdb.
254 gdbrunner.start_gdb(gdb_path, gdb_commands)
255
256if __name__ == "__main__":
257 main()