blob: 4d15cfd33984b1ada12dc462f19af7d2313fa34f [file] [log] [blame]
Elliott Hughes17de6ce2021-06-23 18:00:46 -07001#!/usr/bin/env python3
Josh Gao043bad72015-09-22 11:43:08 -07002#
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
Alex Light92476652019-01-17 11:18:48 -080020import json
Josh Gao043bad72015-09-22 11:43:08 -070021import logging
22import os
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -070023import posixpath
Elliott Hughes89e1ecf2017-06-30 14:03:32 -070024import re
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -070025import shutil
Josh Gao043bad72015-09-22 11:43:08 -070026import subprocess
27import sys
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -070028import tempfile
Alex Light92476652019-01-17 11:18:48 -080029import textwrap
Josh Gao043bad72015-09-22 11:43:08 -070030
31# Shared functions across gdbclient.py and ndk-gdb.py.
32import gdbrunner
33
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -070034g_temp_dirs = []
35
Haibo Huange194fce2020-01-06 14:40:27 -080036
37def read_toolchain_config(root):
38 """Finds out current toolchain path and version."""
39 def get_value(str):
40 return str[str.index('"') + 1:str.rindex('"')]
41
42 config_path = os.path.join(root, 'build', 'soong', 'cc', 'config',
43 'global.go')
44 with open(config_path) as f:
45 contents = f.readlines()
46 clang_base = ""
47 clang_version = ""
48 for line in contents:
49 line = line.strip()
50 if line.startswith('ClangDefaultBase'):
51 clang_base = get_value(line)
52 elif line.startswith('ClangDefaultVersion'):
53 clang_version = get_value(line)
54 return (clang_base, clang_version)
55
56
Haibo Huange4d8bfd2020-07-22 16:37:35 -070057def get_lldb_path(toolchain_path):
58 for lldb_name in ['lldb.sh', 'lldb.cmd', 'lldb', 'lldb.exe']:
59 debugger_path = os.path.join(toolchain_path, "bin", lldb_name)
60 if os.path.isfile(debugger_path):
61 return debugger_path
62 return None
63
64
Haibo Huange194fce2020-01-06 14:40:27 -080065def get_lldb_server_path(root, clang_base, clang_version, arch):
66 arch = {
67 'arm': 'arm',
68 'arm64': 'aarch64',
69 'x86': 'i386',
70 'x86_64': 'x86_64',
71 }[arch]
72 return os.path.join(root, clang_base, "linux-x86",
73 clang_version, "runtimes_ndk_cxx", arch, "lldb-server")
74
75
Elliott Hughes89e1ecf2017-06-30 14:03:32 -070076def get_tracer_pid(device, pid):
77 if pid is None:
78 return 0
79
80 line, _ = device.shell(["grep", "-e", "^TracerPid:", "/proc/{}/status".format(pid)])
81 tracer_pid = re.sub('TracerPid:\t(.*)\n', r'\1', line)
82 return int(tracer_pid)
83
84
Josh Gao043bad72015-09-22 11:43:08 -070085def parse_args():
86 parser = gdbrunner.ArgumentParser()
87
88 group = parser.add_argument_group(title="attach target")
89 group = group.add_mutually_exclusive_group(required=True)
90 group.add_argument(
91 "-p", dest="target_pid", metavar="PID", type=int,
92 help="attach to a process with specified PID")
93 group.add_argument(
94 "-n", dest="target_name", metavar="NAME",
95 help="attach to a process with specified name")
96 group.add_argument(
97 "-r", dest="run_cmd", metavar="CMD", nargs=argparse.REMAINDER,
98 help="run a binary on the device, with args")
99
100 parser.add_argument(
101 "--port", nargs="?", default="5039",
Elliott Hughes89e1ecf2017-06-30 14:03:32 -0700102 help="override the port used on the host [default: 5039]")
Josh Gao043bad72015-09-22 11:43:08 -0700103 parser.add_argument(
104 "--user", nargs="?", default="root",
105 help="user to run commands as on the device [default: root]")
Alex Light92476652019-01-17 11:18:48 -0800106 parser.add_argument(
Alex Lighta8f224d2020-11-10 10:30:19 -0800107 "--setup-forwarding", default=None,
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700108 choices=["lldb", "vscode-lldb"],
109 help=("Set up lldb-server and port forwarding. Prints commands or " +
Alex Light92476652019-01-17 11:18:48 -0800110 ".vscode/launch.json configuration needed to connect the debugging " +
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700111 "client to the server. 'vscode' with llbd and 'vscode-lldb' both " +
112 "require the 'vadimcn.vscode-lldb' extension."))
Haibo Huange194fce2020-01-06 14:40:27 -0800113
Peter Collingbourne63bf1082018-12-19 20:51:42 -0800114 parser.add_argument(
115 "--env", nargs=1, action="append", metavar="VAR=VALUE",
116 help="set environment variable when running a binary")
117
Josh Gao043bad72015-09-22 11:43:08 -0700118 return parser.parse_args()
119
120
Elliott Hughes1a2f12d2017-06-02 13:15:59 -0700121def verify_device(root, device):
Junichi Uekawa6612c922020-09-07 11:20:59 +0900122 names = set([device.get_prop("ro.build.product"), device.get_prop("ro.product.name")])
Josh Gao466e2892017-07-13 15:39:05 -0700123 target_device = os.environ["TARGET_PRODUCT"]
Junichi Uekawa6612c922020-09-07 11:20:59 +0900124 if target_device not in names:
Josh Gao466e2892017-07-13 15:39:05 -0700125 msg = "TARGET_PRODUCT ({}) does not match attached device ({})"
Junichi Uekawa6612c922020-09-07 11:20:59 +0900126 sys.exit(msg.format(target_device, ", ".join(names)))
Josh Gao043bad72015-09-22 11:43:08 -0700127
128
129def get_remote_pid(device, process_name):
130 processes = gdbrunner.get_processes(device)
131 if process_name not in processes:
132 msg = "failed to find running process {}".format(process_name)
133 sys.exit(msg)
134 pids = processes[process_name]
135 if len(pids) > 1:
136 msg = "multiple processes match '{}': {}".format(process_name, pids)
137 sys.exit(msg)
138
139 # Fetch the binary using the PID later.
140 return pids[0]
141
142
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -0700143def make_temp_dir(prefix):
144 global g_temp_dirs
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700145 result = tempfile.mkdtemp(prefix='lldbclient-linker-')
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -0700146 g_temp_dirs.append(result)
147 return result
148
149
150def ensure_linker(device, sysroot, interp):
151 """Ensure that the device's linker exists on the host.
152
153 PT_INTERP is usually /system/bin/linker[64], but on the device, that file is
154 a symlink to /apex/com.android.runtime/bin/linker[64]. The symbolized linker
155 binary on the host is located in ${sysroot}/apex, not in ${sysroot}/system,
156 so add the ${sysroot}/apex path to the solib search path.
157
158 PT_INTERP will be /system/bin/bootstrap/linker[64] for executables using the
159 non-APEX/bootstrap linker. No search path modification is needed.
160
161 For a tapas build, only an unbundled app is built, and there is no linker in
162 ${sysroot} at all, so copy the linker from the device.
163
164 Returns:
165 A directory to add to the soinfo search path or None if no directory
166 needs to be added.
167 """
168
169 # Static executables have no interpreter.
170 if interp is None:
171 return None
172
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700173 # lldb will search for the linker using the PT_INTERP path. First try to find
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -0700174 # it in the sysroot.
175 local_path = os.path.join(sysroot, interp.lstrip("/"))
176 if os.path.exists(local_path):
177 return None
178
179 # If the linker on the device is a symlink, search for the symlink's target
180 # in the sysroot directory.
181 interp_real, _ = device.shell(["realpath", interp])
182 interp_real = interp_real.strip()
183 local_path = os.path.join(sysroot, interp_real.lstrip("/"))
184 if os.path.exists(local_path):
185 if posixpath.basename(interp) == posixpath.basename(interp_real):
186 # Add the interpreter's directory to the search path.
187 return os.path.dirname(local_path)
188 else:
189 # If PT_INTERP is linker_asan[64], but the sysroot file is
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700190 # linker[64], then copy the local file to the name lldb expects.
191 result = make_temp_dir('lldbclient-linker-')
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -0700192 shutil.copy(local_path, os.path.join(result, posixpath.basename(interp)))
193 return result
194
195 # Pull the system linker.
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700196 result = make_temp_dir('lldbclient-linker-')
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -0700197 device.pull(interp, os.path.join(result, posixpath.basename(interp)))
198 return result
Josh Gao043bad72015-09-22 11:43:08 -0700199
200
David Pursell639d1c42015-10-20 15:38:32 -0700201def handle_switches(args, sysroot):
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700202 """Fetch the targeted binary and determine how to attach lldb.
Josh Gao043bad72015-09-22 11:43:08 -0700203
204 Args:
205 args: Parsed arguments.
206 sysroot: Local sysroot path.
207
208 Returns:
209 (binary_file, attach_pid, run_cmd).
210 Precisely one of attach_pid or run_cmd will be None.
211 """
212
213 device = args.device
214 binary_file = None
215 pid = None
216 run_cmd = None
217
Josh Gao057c2732017-05-24 15:55:50 -0700218 args.su_cmd = ["su", args.user] if args.user else []
219
Josh Gao043bad72015-09-22 11:43:08 -0700220 if args.target_pid:
221 # Fetch the binary using the PID later.
222 pid = args.target_pid
223 elif args.target_name:
224 # Fetch the binary using the PID later.
225 pid = get_remote_pid(device, args.target_name)
226 elif args.run_cmd:
227 if not args.run_cmd[0]:
228 sys.exit("empty command passed to -r")
Josh Gao043bad72015-09-22 11:43:08 -0700229 run_cmd = args.run_cmd
Kevin Rocard258c89e2017-07-12 18:21:29 -0700230 if not run_cmd[0].startswith("/"):
231 try:
232 run_cmd[0] = gdbrunner.find_executable_path(device, args.run_cmd[0],
233 run_as_cmd=args.su_cmd)
234 except RuntimeError:
235 sys.exit("Could not find executable '{}' passed to -r, "
236 "please provide an absolute path.".format(args.run_cmd[0]))
237
David Pursell639d1c42015-10-20 15:38:32 -0700238 binary_file, local = gdbrunner.find_file(device, run_cmd[0], sysroot,
Josh Gao057c2732017-05-24 15:55:50 -0700239 run_as_cmd=args.su_cmd)
Josh Gao043bad72015-09-22 11:43:08 -0700240 if binary_file is None:
241 assert pid is not None
242 try:
David Pursell639d1c42015-10-20 15:38:32 -0700243 binary_file, local = gdbrunner.find_binary(device, pid, sysroot,
Josh Gao057c2732017-05-24 15:55:50 -0700244 run_as_cmd=args.su_cmd)
Josh Gao043bad72015-09-22 11:43:08 -0700245 except adb.ShellError:
246 sys.exit("failed to pull binary for PID {}".format(pid))
247
David Pursell639d1c42015-10-20 15:38:32 -0700248 if not local:
249 logging.warning("Couldn't find local unstripped executable in {},"
250 " symbols may not be available.".format(sysroot))
251
Josh Gao043bad72015-09-22 11:43:08 -0700252 return (binary_file, pid, run_cmd)
253
Alex Lighta8f224d2020-11-10 10:30:19 -0800254def generate_vscode_lldb_script(root, sysroot, binary_name, port, solib_search_path):
255 # TODO It would be nice if we didn't need to copy this or run the
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700256 # lldbclient.py program manually. Doing this would probably require
Alex Lighta8f224d2020-11-10 10:30:19 -0800257 # writing a vscode extension or modifying an existing one.
258 # TODO: https://code.visualstudio.com/api/references/vscode-api#debug and
259 # https://code.visualstudio.com/api/extension-guides/debugger-extension and
260 # https://github.com/vadimcn/vscode-lldb/blob/6b775c439992b6615e92f4938ee4e211f1b060cf/extension/pickProcess.ts#L6
261 res = {
262 "name": "(lldbclient.py) Attach {} (port: {})".format(binary_name.split("/")[-1], port),
263 "type": "lldb",
264 "request": "custom",
265 "relativePathBase": root,
266 "sourceMap": { "/b/f/w" : root, '': root, '.': root },
267 "initCommands": ['settings append target.exec-search-paths {}'.format(' '.join(solib_search_path))],
268 "targetCreateCommands": ["target create {}".format(binary_name),
269 "target modules search-paths add / {}/".format(sysroot)],
270 "processCreateCommands": ["gdb-remote {}".format(port)]
271 }
272 return json.dumps(res, indent=4)
273
Haibo Huang07e17072020-05-12 16:51:29 -0700274def generate_lldb_script(root, sysroot, binary_name, port, solib_search_path):
Haibo Huange194fce2020-01-06 14:40:27 -0800275 commands = []
276 commands.append(
277 'settings append target.exec-search-paths {}'.format(' '.join(solib_search_path)))
278
279 commands.append('target create {}'.format(binary_name))
Haibo Huang987436c2020-09-22 21:01:31 -0700280 # For RBE support.
281 commands.append("settings append target.source-map '/b/f/w' '{}'".format(root))
282 commands.append("settings append target.source-map '' '{}'".format(root))
Haibo Huange194fce2020-01-06 14:40:27 -0800283 commands.append('target modules search-paths add / {}/'.format(sysroot))
284 commands.append('gdb-remote {}'.format(port))
285 return '\n'.join(commands)
286
287
288def generate_setup_script(debugger_path, sysroot, linker_search_dir, binary_file, is64bit, port, debugger, connect_timeout=5):
Alex Light92476652019-01-17 11:18:48 -0800289 # Generate a setup script.
Alex Light92476652019-01-17 11:18:48 -0800290 root = os.environ["ANDROID_BUILD_TOP"]
291 symbols_dir = os.path.join(sysroot, "system", "lib64" if is64bit else "lib")
292 vendor_dir = os.path.join(sysroot, "vendor", "lib64" if is64bit else "lib")
293
294 solib_search_path = []
295 symbols_paths = ["", "hw", "ssl/engines", "drm", "egl", "soundfx"]
296 vendor_paths = ["", "hw", "egl"]
297 solib_search_path += [os.path.join(symbols_dir, x) for x in symbols_paths]
298 solib_search_path += [os.path.join(vendor_dir, x) for x in vendor_paths]
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -0700299 if linker_search_dir is not None:
300 solib_search_path += [linker_search_dir]
Alex Light92476652019-01-17 11:18:48 -0800301
Alex Lighta8f224d2020-11-10 10:30:19 -0800302 if debugger == "vscode-lldb":
303 return generate_vscode_lldb_script(
304 root, sysroot, binary_file.name, port, solib_search_path)
Haibo Huange194fce2020-01-06 14:40:27 -0800305 elif debugger == 'lldb':
306 return generate_lldb_script(
Haibo Huang07e17072020-05-12 16:51:29 -0700307 root, sysroot, binary_file.name, port, solib_search_path)
Alex Light92476652019-01-17 11:18:48 -0800308 else:
309 raise Exception("Unknown debugger type " + debugger)
310
Josh Gao043bad72015-09-22 11:43:08 -0700311
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -0700312def do_main():
Josh Gao466e2892017-07-13 15:39:05 -0700313 required_env = ["ANDROID_BUILD_TOP",
314 "ANDROID_PRODUCT_OUT", "TARGET_PRODUCT"]
315 for env in required_env:
316 if env not in os.environ:
317 sys.exit(
318 "Environment variable '{}' not defined, have you run lunch?".format(env))
319
Josh Gao043bad72015-09-22 11:43:08 -0700320 args = parse_args()
321 device = args.device
Josh Gao44b84a82015-10-28 11:57:37 -0700322
323 if device is None:
324 sys.exit("ERROR: Failed to find device.")
325
Josh Gao043bad72015-09-22 11:43:08 -0700326 root = os.environ["ANDROID_BUILD_TOP"]
Josh Gao466e2892017-07-13 15:39:05 -0700327 sysroot = os.path.join(os.environ["ANDROID_PRODUCT_OUT"], "symbols")
Josh Gao043bad72015-09-22 11:43:08 -0700328
329 # Make sure the environment matches the attached device.
Elliott Hughes1a2f12d2017-06-02 13:15:59 -0700330 verify_device(root, device)
Josh Gao043bad72015-09-22 11:43:08 -0700331
332 debug_socket = "/data/local/tmp/debug_socket"
333 pid = None
334 run_cmd = None
335
336 # Fetch binary for -p, -n.
David Pursell639d1c42015-10-20 15:38:32 -0700337 binary_file, pid, run_cmd = handle_switches(args, sysroot)
Josh Gao043bad72015-09-22 11:43:08 -0700338
339 with binary_file:
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -0700340 if sys.platform.startswith("linux"):
341 platform_name = "linux-x86"
342 elif sys.platform.startswith("darwin"):
343 platform_name = "darwin-x86"
344 else:
345 sys.exit("Unknown platform: {}".format(sys.platform))
346
Josh Gao043bad72015-09-22 11:43:08 -0700347 arch = gdbrunner.get_binary_arch(binary_file)
348 is64bit = arch.endswith("64")
349
350 # Make sure we have the linker
Haibo Huange194fce2020-01-06 14:40:27 -0800351 clang_base, clang_version = read_toolchain_config(root)
352 toolchain_path = os.path.join(root, clang_base, platform_name,
353 clang_version)
354 llvm_readobj_path = os.path.join(toolchain_path, "bin", "llvm-readobj")
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -0700355 interp = gdbrunner.get_binary_interp(binary_file.name, llvm_readobj_path)
356 linker_search_dir = ensure_linker(device, sysroot, interp)
Josh Gao043bad72015-09-22 11:43:08 -0700357
Elliott Hughes89e1ecf2017-06-30 14:03:32 -0700358 tracer_pid = get_tracer_pid(device, pid)
359 if tracer_pid == 0:
Peter Collingbourne63bf1082018-12-19 20:51:42 -0800360 cmd_prefix = args.su_cmd
361 if args.env:
362 cmd_prefix += ['env'] + [v[0] for v in args.env]
363
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700364 # Start lldb-server.
365 server_local_path = get_lldb_server_path(root, clang_base, clang_version, arch)
366 server_remote_path = "/data/local/tmp/{}-lldb-server".format(arch)
Elliott Hughes89e1ecf2017-06-30 14:03:32 -0700367 gdbrunner.start_gdbserver(
Haibo Huange194fce2020-01-06 14:40:27 -0800368 device, server_local_path, server_remote_path,
Elliott Hughes89e1ecf2017-06-30 14:03:32 -0700369 target_pid=pid, run_cmd=run_cmd, debug_socket=debug_socket,
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700370 port=args.port, run_as_cmd=cmd_prefix, lldb=True)
Elliott Hughes89e1ecf2017-06-30 14:03:32 -0700371 else:
Haibo Huange194fce2020-01-06 14:40:27 -0800372 print(
373 "Connecting to tracing pid {} using local port {}".format(
374 tracer_pid, args.port))
Elliott Hughes89e1ecf2017-06-30 14:03:32 -0700375 gdbrunner.forward_gdbserver_port(device, local=args.port,
376 remote="tcp:{}".format(args.port))
Josh Gao043bad72015-09-22 11:43:08 -0700377
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700378 debugger_path = get_lldb_path(toolchain_path)
379 debugger = args.setup_forwarding or 'lldb'
Haibo Huange194fce2020-01-06 14:40:27 -0800380
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700381 # Generate the lldb script.
Haibo Huange194fce2020-01-06 14:40:27 -0800382 setup_commands = generate_setup_script(debugger_path=debugger_path,
Alex Light92476652019-01-17 11:18:48 -0800383 sysroot=sysroot,
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -0700384 linker_search_dir=linker_search_dir,
Alex Light92476652019-01-17 11:18:48 -0800385 binary_file=binary_file,
386 is64bit=is64bit,
387 port=args.port,
Haibo Huange194fce2020-01-06 14:40:27 -0800388 debugger=debugger)
Josh Gao043bad72015-09-22 11:43:08 -0700389
Alex Lighta8f224d2020-11-10 10:30:19 -0800390 if not args.setup_forwarding:
Alex Light92476652019-01-17 11:18:48 -0800391 # Print a newline to separate our messages from the GDB session.
392 print("")
David Pursell639d1c42015-10-20 15:38:32 -0700393
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700394 # Start lldb.
395 gdbrunner.start_gdb(debugger_path, setup_commands, lldb=True)
Alex Light92476652019-01-17 11:18:48 -0800396 else:
397 print("")
Haibo Huange194fce2020-01-06 14:40:27 -0800398 print(setup_commands)
Alex Light92476652019-01-17 11:18:48 -0800399 print("")
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700400 if args.setup_forwarding == "vscode-lldb":
Haibo Huange194fce2020-01-06 14:40:27 -0800401 print(textwrap.dedent("""
Alex Light92476652019-01-17 11:18:48 -0800402 Paste the above json into .vscode/launch.json and start the debugger as
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700403 normal. Press enter in this terminal once debugging is finished to shut
404 lldb-server down and close all the ports."""))
Alex Light92476652019-01-17 11:18:48 -0800405 else:
Haibo Huange194fce2020-01-06 14:40:27 -0800406 print(textwrap.dedent("""
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700407 Paste the lldb commands above into the lldb frontend to set up the
408 lldb-server connection. Press enter in this terminal once debugging is
409 finished to shut lldb-server down and close all the ports."""))
Alex Light92476652019-01-17 11:18:48 -0800410 print("")
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700411 raw_input("Press enter to shut down lldb-server")
Josh Gao043bad72015-09-22 11:43:08 -0700412
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -0700413
414def main():
415 try:
416 do_main()
417 finally:
418 global g_temp_dirs
419 for temp_dir in g_temp_dirs:
420 shutil.rmtree(temp_dir)
421
422
Josh Gao043bad72015-09-22 11:43:08 -0700423if __name__ == "__main__":
424 main()