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