blob: bb92151893ddcd3532f4031844d6a56615fdd4c5 [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):
Pirama Arumuga Nainarf7f95442021-06-30 13:31:41 -070038 """Finds out current toolchain version."""
39 version_output = subprocess.check_output(
40 f'{root}/build/soong/scripts/get_clang_version.py',
41 text=True)
42 return version_output.strip()
Haibo Huange194fce2020-01-06 14:40:27 -080043
44
Haibo Huange4d8bfd2020-07-22 16:37:35 -070045def get_lldb_path(toolchain_path):
46 for lldb_name in ['lldb.sh', 'lldb.cmd', 'lldb', 'lldb.exe']:
47 debugger_path = os.path.join(toolchain_path, "bin", lldb_name)
48 if os.path.isfile(debugger_path):
49 return debugger_path
50 return None
51
52
Haibo Huange194fce2020-01-06 14:40:27 -080053def get_lldb_server_path(root, clang_base, clang_version, arch):
54 arch = {
55 'arm': 'arm',
56 'arm64': 'aarch64',
57 'x86': 'i386',
58 'x86_64': 'x86_64',
59 }[arch]
60 return os.path.join(root, clang_base, "linux-x86",
61 clang_version, "runtimes_ndk_cxx", arch, "lldb-server")
62
63
Elliott Hughes89e1ecf2017-06-30 14:03:32 -070064def get_tracer_pid(device, pid):
65 if pid is None:
66 return 0
67
68 line, _ = device.shell(["grep", "-e", "^TracerPid:", "/proc/{}/status".format(pid)])
69 tracer_pid = re.sub('TracerPid:\t(.*)\n', r'\1', line)
70 return int(tracer_pid)
71
72
Josh Gao043bad72015-09-22 11:43:08 -070073def parse_args():
74 parser = gdbrunner.ArgumentParser()
75
76 group = parser.add_argument_group(title="attach target")
77 group = group.add_mutually_exclusive_group(required=True)
78 group.add_argument(
79 "-p", dest="target_pid", metavar="PID", type=int,
80 help="attach to a process with specified PID")
81 group.add_argument(
82 "-n", dest="target_name", metavar="NAME",
83 help="attach to a process with specified name")
84 group.add_argument(
85 "-r", dest="run_cmd", metavar="CMD", nargs=argparse.REMAINDER,
86 help="run a binary on the device, with args")
87
88 parser.add_argument(
89 "--port", nargs="?", default="5039",
Elliott Hughes89e1ecf2017-06-30 14:03:32 -070090 help="override the port used on the host [default: 5039]")
Josh Gao043bad72015-09-22 11:43:08 -070091 parser.add_argument(
92 "--user", nargs="?", default="root",
93 help="user to run commands as on the device [default: root]")
Alex Light92476652019-01-17 11:18:48 -080094 parser.add_argument(
Alex Lighta8f224d2020-11-10 10:30:19 -080095 "--setup-forwarding", default=None,
Elliott Hughes4c8e8752021-06-25 14:23:22 -070096 choices=["lldb", "vscode-lldb"],
97 help=("Set up lldb-server and port forwarding. Prints commands or " +
Alex Light92476652019-01-17 11:18:48 -080098 ".vscode/launch.json configuration needed to connect the debugging " +
Elliott Hughes4c8e8752021-06-25 14:23:22 -070099 "client to the server. 'vscode' with llbd and 'vscode-lldb' both " +
100 "require the 'vadimcn.vscode-lldb' extension."))
Haibo Huange194fce2020-01-06 14:40:27 -0800101
Peter Collingbourne63bf1082018-12-19 20:51:42 -0800102 parser.add_argument(
103 "--env", nargs=1, action="append", metavar="VAR=VALUE",
104 help="set environment variable when running a binary")
105
Josh Gao043bad72015-09-22 11:43:08 -0700106 return parser.parse_args()
107
108
Elliott Hughes1a2f12d2017-06-02 13:15:59 -0700109def verify_device(root, device):
Junichi Uekawa6612c922020-09-07 11:20:59 +0900110 names = set([device.get_prop("ro.build.product"), device.get_prop("ro.product.name")])
Josh Gao466e2892017-07-13 15:39:05 -0700111 target_device = os.environ["TARGET_PRODUCT"]
Junichi Uekawa6612c922020-09-07 11:20:59 +0900112 if target_device not in names:
Josh Gao466e2892017-07-13 15:39:05 -0700113 msg = "TARGET_PRODUCT ({}) does not match attached device ({})"
Junichi Uekawa6612c922020-09-07 11:20:59 +0900114 sys.exit(msg.format(target_device, ", ".join(names)))
Josh Gao043bad72015-09-22 11:43:08 -0700115
116
117def get_remote_pid(device, process_name):
118 processes = gdbrunner.get_processes(device)
119 if process_name not in processes:
120 msg = "failed to find running process {}".format(process_name)
121 sys.exit(msg)
122 pids = processes[process_name]
123 if len(pids) > 1:
124 msg = "multiple processes match '{}': {}".format(process_name, pids)
125 sys.exit(msg)
126
127 # Fetch the binary using the PID later.
128 return pids[0]
129
130
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -0700131def make_temp_dir(prefix):
132 global g_temp_dirs
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700133 result = tempfile.mkdtemp(prefix='lldbclient-linker-')
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -0700134 g_temp_dirs.append(result)
135 return result
136
137
138def ensure_linker(device, sysroot, interp):
139 """Ensure that the device's linker exists on the host.
140
141 PT_INTERP is usually /system/bin/linker[64], but on the device, that file is
142 a symlink to /apex/com.android.runtime/bin/linker[64]. The symbolized linker
143 binary on the host is located in ${sysroot}/apex, not in ${sysroot}/system,
144 so add the ${sysroot}/apex path to the solib search path.
145
146 PT_INTERP will be /system/bin/bootstrap/linker[64] for executables using the
147 non-APEX/bootstrap linker. No search path modification is needed.
148
149 For a tapas build, only an unbundled app is built, and there is no linker in
150 ${sysroot} at all, so copy the linker from the device.
151
152 Returns:
153 A directory to add to the soinfo search path or None if no directory
154 needs to be added.
155 """
156
157 # Static executables have no interpreter.
158 if interp is None:
159 return None
160
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700161 # lldb will search for the linker using the PT_INTERP path. First try to find
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -0700162 # it in the sysroot.
163 local_path = os.path.join(sysroot, interp.lstrip("/"))
164 if os.path.exists(local_path):
165 return None
166
167 # If the linker on the device is a symlink, search for the symlink's target
168 # in the sysroot directory.
169 interp_real, _ = device.shell(["realpath", interp])
170 interp_real = interp_real.strip()
171 local_path = os.path.join(sysroot, interp_real.lstrip("/"))
172 if os.path.exists(local_path):
173 if posixpath.basename(interp) == posixpath.basename(interp_real):
174 # Add the interpreter's directory to the search path.
175 return os.path.dirname(local_path)
176 else:
177 # If PT_INTERP is linker_asan[64], but the sysroot file is
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700178 # linker[64], then copy the local file to the name lldb expects.
179 result = make_temp_dir('lldbclient-linker-')
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -0700180 shutil.copy(local_path, os.path.join(result, posixpath.basename(interp)))
181 return result
182
183 # Pull the system linker.
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700184 result = make_temp_dir('lldbclient-linker-')
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -0700185 device.pull(interp, os.path.join(result, posixpath.basename(interp)))
186 return result
Josh Gao043bad72015-09-22 11:43:08 -0700187
188
David Pursell639d1c42015-10-20 15:38:32 -0700189def handle_switches(args, sysroot):
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700190 """Fetch the targeted binary and determine how to attach lldb.
Josh Gao043bad72015-09-22 11:43:08 -0700191
192 Args:
193 args: Parsed arguments.
194 sysroot: Local sysroot path.
195
196 Returns:
197 (binary_file, attach_pid, run_cmd).
198 Precisely one of attach_pid or run_cmd will be None.
199 """
200
201 device = args.device
202 binary_file = None
203 pid = None
204 run_cmd = None
205
Josh Gao057c2732017-05-24 15:55:50 -0700206 args.su_cmd = ["su", args.user] if args.user else []
207
Josh Gao043bad72015-09-22 11:43:08 -0700208 if args.target_pid:
209 # Fetch the binary using the PID later.
210 pid = args.target_pid
211 elif args.target_name:
212 # Fetch the binary using the PID later.
213 pid = get_remote_pid(device, args.target_name)
214 elif args.run_cmd:
215 if not args.run_cmd[0]:
216 sys.exit("empty command passed to -r")
Josh Gao043bad72015-09-22 11:43:08 -0700217 run_cmd = args.run_cmd
Kevin Rocard258c89e2017-07-12 18:21:29 -0700218 if not run_cmd[0].startswith("/"):
219 try:
220 run_cmd[0] = gdbrunner.find_executable_path(device, args.run_cmd[0],
221 run_as_cmd=args.su_cmd)
222 except RuntimeError:
223 sys.exit("Could not find executable '{}' passed to -r, "
224 "please provide an absolute path.".format(args.run_cmd[0]))
225
David Pursell639d1c42015-10-20 15:38:32 -0700226 binary_file, local = gdbrunner.find_file(device, run_cmd[0], sysroot,
Josh Gao057c2732017-05-24 15:55:50 -0700227 run_as_cmd=args.su_cmd)
Josh Gao043bad72015-09-22 11:43:08 -0700228 if binary_file is None:
229 assert pid is not None
230 try:
David Pursell639d1c42015-10-20 15:38:32 -0700231 binary_file, local = gdbrunner.find_binary(device, pid, sysroot,
Josh Gao057c2732017-05-24 15:55:50 -0700232 run_as_cmd=args.su_cmd)
Josh Gao043bad72015-09-22 11:43:08 -0700233 except adb.ShellError:
234 sys.exit("failed to pull binary for PID {}".format(pid))
235
David Pursell639d1c42015-10-20 15:38:32 -0700236 if not local:
237 logging.warning("Couldn't find local unstripped executable in {},"
238 " symbols may not be available.".format(sysroot))
239
Josh Gao043bad72015-09-22 11:43:08 -0700240 return (binary_file, pid, run_cmd)
241
Alex Lighta8f224d2020-11-10 10:30:19 -0800242def generate_vscode_lldb_script(root, sysroot, binary_name, port, solib_search_path):
243 # TODO It would be nice if we didn't need to copy this or run the
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700244 # lldbclient.py program manually. Doing this would probably require
Alex Lighta8f224d2020-11-10 10:30:19 -0800245 # writing a vscode extension or modifying an existing one.
246 # TODO: https://code.visualstudio.com/api/references/vscode-api#debug and
247 # https://code.visualstudio.com/api/extension-guides/debugger-extension and
248 # https://github.com/vadimcn/vscode-lldb/blob/6b775c439992b6615e92f4938ee4e211f1b060cf/extension/pickProcess.ts#L6
249 res = {
250 "name": "(lldbclient.py) Attach {} (port: {})".format(binary_name.split("/")[-1], port),
251 "type": "lldb",
252 "request": "custom",
253 "relativePathBase": root,
254 "sourceMap": { "/b/f/w" : root, '': root, '.': root },
255 "initCommands": ['settings append target.exec-search-paths {}'.format(' '.join(solib_search_path))],
256 "targetCreateCommands": ["target create {}".format(binary_name),
257 "target modules search-paths add / {}/".format(sysroot)],
258 "processCreateCommands": ["gdb-remote {}".format(port)]
259 }
260 return json.dumps(res, indent=4)
261
Haibo Huang07e17072020-05-12 16:51:29 -0700262def generate_lldb_script(root, sysroot, binary_name, port, solib_search_path):
Haibo Huange194fce2020-01-06 14:40:27 -0800263 commands = []
264 commands.append(
265 'settings append target.exec-search-paths {}'.format(' '.join(solib_search_path)))
266
267 commands.append('target create {}'.format(binary_name))
Haibo Huang987436c2020-09-22 21:01:31 -0700268 # For RBE support.
269 commands.append("settings append target.source-map '/b/f/w' '{}'".format(root))
270 commands.append("settings append target.source-map '' '{}'".format(root))
Haibo Huange194fce2020-01-06 14:40:27 -0800271 commands.append('target modules search-paths add / {}/'.format(sysroot))
272 commands.append('gdb-remote {}'.format(port))
273 return '\n'.join(commands)
274
275
276def generate_setup_script(debugger_path, sysroot, linker_search_dir, binary_file, is64bit, port, debugger, connect_timeout=5):
Alex Light92476652019-01-17 11:18:48 -0800277 # Generate a setup script.
Alex Light92476652019-01-17 11:18:48 -0800278 root = os.environ["ANDROID_BUILD_TOP"]
279 symbols_dir = os.path.join(sysroot, "system", "lib64" if is64bit else "lib")
280 vendor_dir = os.path.join(sysroot, "vendor", "lib64" if is64bit else "lib")
281
282 solib_search_path = []
283 symbols_paths = ["", "hw", "ssl/engines", "drm", "egl", "soundfx"]
284 vendor_paths = ["", "hw", "egl"]
285 solib_search_path += [os.path.join(symbols_dir, x) for x in symbols_paths]
286 solib_search_path += [os.path.join(vendor_dir, x) for x in vendor_paths]
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -0700287 if linker_search_dir is not None:
288 solib_search_path += [linker_search_dir]
Alex Light92476652019-01-17 11:18:48 -0800289
Alex Lighta8f224d2020-11-10 10:30:19 -0800290 if debugger == "vscode-lldb":
291 return generate_vscode_lldb_script(
292 root, sysroot, binary_file.name, port, solib_search_path)
Haibo Huange194fce2020-01-06 14:40:27 -0800293 elif debugger == 'lldb':
294 return generate_lldb_script(
Haibo Huang07e17072020-05-12 16:51:29 -0700295 root, sysroot, binary_file.name, port, solib_search_path)
Alex Light92476652019-01-17 11:18:48 -0800296 else:
297 raise Exception("Unknown debugger type " + debugger)
298
Josh Gao043bad72015-09-22 11:43:08 -0700299
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -0700300def do_main():
Josh Gao466e2892017-07-13 15:39:05 -0700301 required_env = ["ANDROID_BUILD_TOP",
302 "ANDROID_PRODUCT_OUT", "TARGET_PRODUCT"]
303 for env in required_env:
304 if env not in os.environ:
305 sys.exit(
306 "Environment variable '{}' not defined, have you run lunch?".format(env))
307
Josh Gao043bad72015-09-22 11:43:08 -0700308 args = parse_args()
309 device = args.device
Josh Gao44b84a82015-10-28 11:57:37 -0700310
311 if device is None:
312 sys.exit("ERROR: Failed to find device.")
313
Josh Gao043bad72015-09-22 11:43:08 -0700314 root = os.environ["ANDROID_BUILD_TOP"]
Josh Gao466e2892017-07-13 15:39:05 -0700315 sysroot = os.path.join(os.environ["ANDROID_PRODUCT_OUT"], "symbols")
Josh Gao043bad72015-09-22 11:43:08 -0700316
317 # Make sure the environment matches the attached device.
Elliott Hughes1a2f12d2017-06-02 13:15:59 -0700318 verify_device(root, device)
Josh Gao043bad72015-09-22 11:43:08 -0700319
320 debug_socket = "/data/local/tmp/debug_socket"
321 pid = None
322 run_cmd = None
323
324 # Fetch binary for -p, -n.
David Pursell639d1c42015-10-20 15:38:32 -0700325 binary_file, pid, run_cmd = handle_switches(args, sysroot)
Josh Gao043bad72015-09-22 11:43:08 -0700326
327 with binary_file:
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -0700328 if sys.platform.startswith("linux"):
329 platform_name = "linux-x86"
330 elif sys.platform.startswith("darwin"):
331 platform_name = "darwin-x86"
332 else:
333 sys.exit("Unknown platform: {}".format(sys.platform))
334
Josh Gao043bad72015-09-22 11:43:08 -0700335 arch = gdbrunner.get_binary_arch(binary_file)
336 is64bit = arch.endswith("64")
337
338 # Make sure we have the linker
Pirama Arumuga Nainarf7f95442021-06-30 13:31:41 -0700339 clang_base = 'prebuilts/clang/host'
340 clang_version = read_toolchain_config(root)
Haibo Huange194fce2020-01-06 14:40:27 -0800341 toolchain_path = os.path.join(root, clang_base, platform_name,
342 clang_version)
343 llvm_readobj_path = os.path.join(toolchain_path, "bin", "llvm-readobj")
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -0700344 interp = gdbrunner.get_binary_interp(binary_file.name, llvm_readobj_path)
345 linker_search_dir = ensure_linker(device, sysroot, interp)
Josh Gao043bad72015-09-22 11:43:08 -0700346
Elliott Hughes89e1ecf2017-06-30 14:03:32 -0700347 tracer_pid = get_tracer_pid(device, pid)
348 if tracer_pid == 0:
Peter Collingbourne63bf1082018-12-19 20:51:42 -0800349 cmd_prefix = args.su_cmd
350 if args.env:
351 cmd_prefix += ['env'] + [v[0] for v in args.env]
352
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700353 # Start lldb-server.
354 server_local_path = get_lldb_server_path(root, clang_base, clang_version, arch)
355 server_remote_path = "/data/local/tmp/{}-lldb-server".format(arch)
Elliott Hughes89e1ecf2017-06-30 14:03:32 -0700356 gdbrunner.start_gdbserver(
Haibo Huange194fce2020-01-06 14:40:27 -0800357 device, server_local_path, server_remote_path,
Elliott Hughes89e1ecf2017-06-30 14:03:32 -0700358 target_pid=pid, run_cmd=run_cmd, debug_socket=debug_socket,
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700359 port=args.port, run_as_cmd=cmd_prefix, lldb=True)
Elliott Hughes89e1ecf2017-06-30 14:03:32 -0700360 else:
Haibo Huange194fce2020-01-06 14:40:27 -0800361 print(
362 "Connecting to tracing pid {} using local port {}".format(
363 tracer_pid, args.port))
Elliott Hughes89e1ecf2017-06-30 14:03:32 -0700364 gdbrunner.forward_gdbserver_port(device, local=args.port,
365 remote="tcp:{}".format(args.port))
Josh Gao043bad72015-09-22 11:43:08 -0700366
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700367 debugger_path = get_lldb_path(toolchain_path)
368 debugger = args.setup_forwarding or 'lldb'
Haibo Huange194fce2020-01-06 14:40:27 -0800369
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700370 # Generate the lldb script.
Haibo Huange194fce2020-01-06 14:40:27 -0800371 setup_commands = generate_setup_script(debugger_path=debugger_path,
Alex Light92476652019-01-17 11:18:48 -0800372 sysroot=sysroot,
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -0700373 linker_search_dir=linker_search_dir,
Alex Light92476652019-01-17 11:18:48 -0800374 binary_file=binary_file,
375 is64bit=is64bit,
376 port=args.port,
Haibo Huange194fce2020-01-06 14:40:27 -0800377 debugger=debugger)
Josh Gao043bad72015-09-22 11:43:08 -0700378
Alex Lighta8f224d2020-11-10 10:30:19 -0800379 if not args.setup_forwarding:
Alex Light92476652019-01-17 11:18:48 -0800380 # Print a newline to separate our messages from the GDB session.
381 print("")
David Pursell639d1c42015-10-20 15:38:32 -0700382
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700383 # Start lldb.
384 gdbrunner.start_gdb(debugger_path, setup_commands, lldb=True)
Alex Light92476652019-01-17 11:18:48 -0800385 else:
386 print("")
Haibo Huange194fce2020-01-06 14:40:27 -0800387 print(setup_commands)
Alex Light92476652019-01-17 11:18:48 -0800388 print("")
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700389 if args.setup_forwarding == "vscode-lldb":
Haibo Huange194fce2020-01-06 14:40:27 -0800390 print(textwrap.dedent("""
Alex Light92476652019-01-17 11:18:48 -0800391 Paste the above json into .vscode/launch.json and start the debugger as
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700392 normal. Press enter in this terminal once debugging is finished to shut
393 lldb-server down and close all the ports."""))
Alex Light92476652019-01-17 11:18:48 -0800394 else:
Haibo Huange194fce2020-01-06 14:40:27 -0800395 print(textwrap.dedent("""
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700396 Paste the lldb commands above into the lldb frontend to set up the
397 lldb-server connection. Press enter in this terminal once debugging is
398 finished to shut lldb-server down and close all the ports."""))
Alex Light92476652019-01-17 11:18:48 -0800399 print("")
Elliott Hughes4c8e8752021-06-25 14:23:22 -0700400 raw_input("Press enter to shut down lldb-server")
Josh Gao043bad72015-09-22 11:43:08 -0700401
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -0700402
403def main():
404 try:
405 do_main()
406 finally:
407 global g_temp_dirs
408 for temp_dir in g_temp_dirs:
409 shutil.rmtree(temp_dir)
410
411
Josh Gao043bad72015-09-22 11:43:08 -0700412if __name__ == "__main__":
413 main()