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 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
68    # 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
72    make_output = subprocess.check_output(make_args, cwd=root)
73    os.environ['PWD'] = saved_pwd
74    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, sysroot):
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, local = gdbrunner.find_file(device, run_cmd[0], sysroot,
139                                                 user=args.user)
140    if binary_file is None:
141        assert pid is not None
142        try:
143            binary_file, local = gdbrunner.find_binary(device, pid, sysroot,
144                                                       user=args.user)
145        except adb.ShellError:
146            sys.exit("failed to pull binary for PID {}".format(pid))
147
148    if not local:
149        logging.warning("Couldn't find local unstripped executable in {},"
150                        " symbols may not be available.".format(sysroot))
151
152    return (binary_file, pid, run_cmd)
153
154def generate_gdb_script(sysroot, binary_file, is64bit, port, connect_timeout=5):
155    # Generate a gdb script.
156    # TODO: Detect the zygote and run 'art-on' automatically.
157    root = os.environ["ANDROID_BUILD_TOP"]
158    symbols_dir = os.path.join(sysroot, "system", "lib64" if is64bit else "lib")
159    vendor_dir = os.path.join(sysroot, "vendor", "lib64" if is64bit else "lib")
160
161    solib_search_path = []
162    symbols_paths = ["", "hw", "ssl/engines", "drm", "egl", "soundfx"]
163    vendor_paths = ["", "hw", "egl"]
164    solib_search_path += [os.path.join(symbols_dir, x) for x in symbols_paths]
165    solib_search_path += [os.path.join(vendor_dir, x) for x in vendor_paths]
166    solib_search_path = ":".join(solib_search_path)
167
168    gdb_commands = ""
169    gdb_commands += "file '{}'\n".format(binary_file.name)
170    gdb_commands += "directory '{}'\n".format(root)
171    gdb_commands += "set solib-absolute-prefix {}\n".format(sysroot)
172    gdb_commands += "set solib-search-path {}\n".format(solib_search_path)
173
174    dalvik_gdb_script = os.path.join(root, "development", "scripts", "gdb",
175                                     "dalvik.gdb")
176    if not os.path.exists(dalvik_gdb_script):
177        logging.warning(("couldn't find {} - ART debugging options will not " +
178                         "be available").format(dalvik_gdb_script))
179    else:
180        gdb_commands += "source {}\n".format(dalvik_gdb_script)
181
182    # Try to connect for a few seconds, sometimes the device gdbserver takes
183    # a little bit to come up, especially on emulators.
184    gdb_commands += """
185python
186
187def target_remote_with_retry(target, timeout_seconds):
188  import time
189  end_time = time.time() + timeout_seconds
190  while True:
191    try:
192      gdb.execute("target remote " + target)
193      return True
194    except gdb.error as e:
195      time_left = end_time - time.time()
196      if time_left < 0 or time_left > timeout_seconds:
197        print("Error: unable to connect to device.")
198        print(e)
199        return False
200      time.sleep(min(0.25, time_left))
201
202target_remote_with_retry(':{}', {})
203
204end
205""".format(port, connect_timeout)
206
207    return gdb_commands
208
209
210def main():
211    args = parse_args()
212    device = args.device
213
214    if device is None:
215        sys.exit("ERROR: Failed to find device.")
216
217    props = device.get_props()
218
219    root = os.environ["ANDROID_BUILD_TOP"]
220    sysroot = dump_var(root, "abs-TARGET_OUT_UNSTRIPPED")
221
222    # Make sure the environment matches the attached device.
223    verify_device(root, props)
224
225    debug_socket = "/data/local/tmp/debug_socket"
226    pid = None
227    run_cmd = None
228
229    # Fetch binary for -p, -n.
230    binary_file, pid, run_cmd = handle_switches(args, sysroot)
231
232    with binary_file:
233        arch = gdbrunner.get_binary_arch(binary_file)
234        is64bit = arch.endswith("64")
235
236        # Make sure we have the linker
237        ensure_linker(device, sysroot, is64bit)
238
239        # Start gdbserver.
240        gdbserver_local_path = get_gdbserver_path(root, arch)
241        gdbserver_remote_path = "/data/local/tmp/{}-gdbserver".format(arch)
242        gdbrunner.start_gdbserver(
243            device, gdbserver_local_path, gdbserver_remote_path,
244            target_pid=pid, run_cmd=run_cmd, debug_socket=debug_socket,
245            port=args.port, user=args.user)
246
247        # Generate a gdb script.
248        gdb_commands = generate_gdb_script(sysroot=sysroot,
249                                           binary_file=binary_file,
250                                           is64bit=is64bit,
251                                           port=args.port)
252
253        # Find where gdb is
254        if sys.platform.startswith("linux"):
255            platform_name = "linux-x86"
256        elif sys.platform.startswith("darwin"):
257            platform_name = "darwin-x86"
258        else:
259            sys.exit("Unknown platform: {}".format(sys.platform))
260        gdb_path = os.path.join(root, "prebuilts", "gdb", platform_name, "bin",
261                                "gdb")
262
263        # Print a newline to separate our messages from the GDB session.
264        print("")
265
266        # Start gdb.
267        gdbrunner.start_gdb(gdb_path, gdb_commands)
268
269if __name__ == "__main__":
270    main()
271