1#!/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 re 23import 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 37def 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 46def 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", 63 help="override the port used on the host [default: 5039]") 64 parser.add_argument( 65 "--user", nargs="?", default="root", 66 help="user to run commands as on the device [default: root]") 67 68 return parser.parse_args() 69 70 71def dump_var(root, variable): 72 make_args = ["make", "CALLED_FROM_SETUP=true", 73 "BUILD_SYSTEM={}/build/core".format(root), 74 "--no-print-directory", "-f", 75 "{}/build/core/config.mk".format(root), 76 "dumpvar-{}".format(variable)] 77 78 # subprocess cwd argument does not change the PWD shell variable, but 79 # dumpvar.mk uses PWD to create an absolute path, so we need to set it. 80 saved_pwd = os.environ['PWD'] 81 os.environ['PWD'] = root 82 make_output = subprocess.check_output(make_args, cwd=root) 83 os.environ['PWD'] = saved_pwd 84 return make_output.splitlines()[0] 85 86 87def verify_device(root, device): 88 names = set([device.get_prop("ro.build.product"), device.get_prop("ro.product.device")]) 89 target_device = dump_var(root, "TARGET_DEVICE") 90 if target_device not in names: 91 msg = "TARGET_DEVICE ({}) does not match attached device ({})" 92 sys.exit(msg.format(target_device, ", ".join(names))) 93 94 95def get_remote_pid(device, process_name): 96 processes = gdbrunner.get_processes(device) 97 if process_name not in processes: 98 msg = "failed to find running process {}".format(process_name) 99 sys.exit(msg) 100 pids = processes[process_name] 101 if len(pids) > 1: 102 msg = "multiple processes match '{}': {}".format(process_name, pids) 103 sys.exit(msg) 104 105 # Fetch the binary using the PID later. 106 return pids[0] 107 108 109def ensure_linker(device, sysroot, is64bit): 110 local_path = os.path.join(sysroot, "system", "bin", "linker") 111 remote_path = "/system/bin/linker" 112 if is64bit: 113 local_path += "64" 114 remote_path += "64" 115 if not os.path.exists(local_path): 116 device.pull(remote_path, local_path) 117 118 119def handle_switches(args, sysroot): 120 """Fetch the targeted binary and determine how to attach gdb. 121 122 Args: 123 args: Parsed arguments. 124 sysroot: Local sysroot path. 125 126 Returns: 127 (binary_file, attach_pid, run_cmd). 128 Precisely one of attach_pid or run_cmd will be None. 129 """ 130 131 device = args.device 132 binary_file = None 133 pid = None 134 run_cmd = None 135 136 args.su_cmd = ["su", args.user] if args.user else [] 137 138 if args.target_pid: 139 # Fetch the binary using the PID later. 140 pid = args.target_pid 141 elif args.target_name: 142 # Fetch the binary using the PID later. 143 pid = get_remote_pid(device, args.target_name) 144 elif args.run_cmd: 145 if not args.run_cmd[0]: 146 sys.exit("empty command passed to -r") 147 run_cmd = args.run_cmd 148 if not run_cmd[0].startswith("/"): 149 try: 150 run_cmd[0] = gdbrunner.find_executable_path(device, args.run_cmd[0], 151 run_as_cmd=args.su_cmd) 152 except RuntimeError: 153 sys.exit("Could not find executable '{}' passed to -r, " 154 "please provide an absolute path.".format(args.run_cmd[0])) 155 156 binary_file, local = gdbrunner.find_file(device, run_cmd[0], sysroot, 157 run_as_cmd=args.su_cmd) 158 if binary_file is None: 159 assert pid is not None 160 try: 161 binary_file, local = gdbrunner.find_binary(device, pid, sysroot, 162 run_as_cmd=args.su_cmd) 163 except adb.ShellError: 164 sys.exit("failed to pull binary for PID {}".format(pid)) 165 166 if not local: 167 logging.warning("Couldn't find local unstripped executable in {}," 168 " symbols may not be available.".format(sysroot)) 169 170 return (binary_file, pid, run_cmd) 171 172def generate_gdb_script(sysroot, binary_file, is64bit, port, connect_timeout=5): 173 # Generate a gdb script. 174 # TODO: Detect the zygote and run 'art-on' automatically. 175 root = os.environ["ANDROID_BUILD_TOP"] 176 symbols_dir = os.path.join(sysroot, "system", "lib64" if is64bit else "lib") 177 vendor_dir = os.path.join(sysroot, "vendor", "lib64" if is64bit else "lib") 178 179 solib_search_path = [] 180 symbols_paths = ["", "hw", "ssl/engines", "drm", "egl", "soundfx"] 181 vendor_paths = ["", "hw", "egl"] 182 solib_search_path += [os.path.join(symbols_dir, x) for x in symbols_paths] 183 solib_search_path += [os.path.join(vendor_dir, x) for x in vendor_paths] 184 solib_search_path = ":".join(solib_search_path) 185 186 gdb_commands = "" 187 gdb_commands += "file '{}'\n".format(binary_file.name) 188 gdb_commands += "directory '{}'\n".format(root) 189 gdb_commands += "set solib-absolute-prefix {}\n".format(sysroot) 190 gdb_commands += "set solib-search-path {}\n".format(solib_search_path) 191 192 dalvik_gdb_script = os.path.join(root, "development", "scripts", "gdb", 193 "dalvik.gdb") 194 if not os.path.exists(dalvik_gdb_script): 195 logging.warning(("couldn't find {} - ART debugging options will not " + 196 "be available").format(dalvik_gdb_script)) 197 else: 198 gdb_commands += "source {}\n".format(dalvik_gdb_script) 199 200 # Try to connect for a few seconds, sometimes the device gdbserver takes 201 # a little bit to come up, especially on emulators. 202 gdb_commands += """ 203python 204 205def target_remote_with_retry(target, timeout_seconds): 206 import time 207 end_time = time.time() + timeout_seconds 208 while True: 209 try: 210 gdb.execute("target remote " + target) 211 return True 212 except gdb.error as e: 213 time_left = end_time - time.time() 214 if time_left < 0 or time_left > timeout_seconds: 215 print("Error: unable to connect to device.") 216 print(e) 217 return False 218 time.sleep(min(0.25, time_left)) 219 220target_remote_with_retry(':{}', {}) 221 222end 223""".format(port, connect_timeout) 224 225 return gdb_commands 226 227 228def main(): 229 args = parse_args() 230 device = args.device 231 232 if device is None: 233 sys.exit("ERROR: Failed to find device.") 234 235 root = os.environ["ANDROID_BUILD_TOP"] 236 sysroot = dump_var(root, "abs-TARGET_OUT_UNSTRIPPED") 237 238 # Make sure the environment matches the attached device. 239 verify_device(root, device) 240 241 debug_socket = "/data/local/tmp/debug_socket" 242 pid = None 243 run_cmd = None 244 245 # Fetch binary for -p, -n. 246 binary_file, pid, run_cmd = handle_switches(args, sysroot) 247 248 with binary_file: 249 arch = gdbrunner.get_binary_arch(binary_file) 250 is64bit = arch.endswith("64") 251 252 # Make sure we have the linker 253 ensure_linker(device, sysroot, is64bit) 254 255 tracer_pid = get_tracer_pid(device, pid) 256 if tracer_pid == 0: 257 # 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, 263 port=args.port, run_as_cmd=args.su_cmd) 264 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)) 268 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 285 # Print a newline to separate our messages from the GDB session. 286 print("") 287 288 # Start gdb. 289 gdbrunner.start_gdb(gdb_path, gdb_commands) 290 291if __name__ == "__main__": 292 main() 293