Elliott Hughes | 17de6ce | 2021-06-23 18:00:46 -0700 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 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 | |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 18 | import argparse |
Alex Light | 9247665 | 2019-01-17 11:18:48 -0800 | [diff] [blame] | 19 | import json |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 20 | import logging |
| 21 | import os |
Nikita Putikhin | 7da179e | 2023-07-03 07:37:58 +0000 | [diff] [blame] | 22 | import pathlib |
Ryan Prichard | 5d1c3cb | 2019-06-04 16:35:02 -0700 | [diff] [blame] | 23 | import posixpath |
Elliott Hughes | 89e1ecf | 2017-06-30 14:03:32 -0700 | [diff] [blame] | 24 | import re |
Ryan Prichard | 5d1c3cb | 2019-06-04 16:35:02 -0700 | [diff] [blame] | 25 | import shutil |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 26 | import subprocess |
| 27 | import sys |
Ryan Prichard | 5d1c3cb | 2019-06-04 16:35:02 -0700 | [diff] [blame] | 28 | import tempfile |
Alex Light | 9247665 | 2019-01-17 11:18:48 -0800 | [diff] [blame] | 29 | import textwrap |
Nikita Putikhin | 7da179e | 2023-07-03 07:37:58 +0000 | [diff] [blame] | 30 | from typing import Any, BinaryIO |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 31 | |
Nikita Putikhin | 7da179e | 2023-07-03 07:37:58 +0000 | [diff] [blame] | 32 | import adb |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 33 | # Shared functions across gdbclient.py and ndk-gdb.py. |
| 34 | import gdbrunner |
| 35 | |
Ryan Prichard | 5d1c3cb | 2019-06-04 16:35:02 -0700 | [diff] [blame] | 36 | g_temp_dirs = [] |
| 37 | |
Nikita Putikhin | 7da179e | 2023-07-03 07:37:58 +0000 | [diff] [blame] | 38 | g_vscode_config_marker_begin = '// #lldbclient-generated-begin' |
| 39 | g_vscode_config_marker_end = '// #lldbclient-generated-end' |
| 40 | |
Haibo Huang | e194fce | 2020-01-06 14:40:27 -0800 | [diff] [blame] | 41 | |
Nikita Putikhin | 516960e | 2023-05-31 21:57:38 +0000 | [diff] [blame] | 42 | def read_toolchain_config(root: str) -> str: |
Pirama Arumuga Nainar | f7f9544 | 2021-06-30 13:31:41 -0700 | [diff] [blame] | 43 | """Finds out current toolchain version.""" |
| 44 | version_output = subprocess.check_output( |
| 45 | f'{root}/build/soong/scripts/get_clang_version.py', |
| 46 | text=True) |
| 47 | return version_output.strip() |
Haibo Huang | e194fce | 2020-01-06 14:40:27 -0800 | [diff] [blame] | 48 | |
| 49 | |
Nikita Putikhin | 516960e | 2023-05-31 21:57:38 +0000 | [diff] [blame] | 50 | def get_lldb_path(toolchain_path: str) -> str | None: |
Haibo Huang | e4d8bfd | 2020-07-22 16:37:35 -0700 | [diff] [blame] | 51 | for lldb_name in ['lldb.sh', 'lldb.cmd', 'lldb', 'lldb.exe']: |
| 52 | debugger_path = os.path.join(toolchain_path, "bin", lldb_name) |
| 53 | if os.path.isfile(debugger_path): |
| 54 | return debugger_path |
| 55 | return None |
| 56 | |
| 57 | |
Nikita Putikhin | 516960e | 2023-05-31 21:57:38 +0000 | [diff] [blame] | 58 | def get_lldb_server_path(root: str, clang_base: str, clang_version: str, arch: str) -> str: |
Haibo Huang | e194fce | 2020-01-06 14:40:27 -0800 | [diff] [blame] | 59 | arch = { |
| 60 | 'arm': 'arm', |
| 61 | 'arm64': 'aarch64', |
Samuel Holland | c434dec | 2023-06-16 09:35:40 -0700 | [diff] [blame] | 62 | 'riscv64': 'riscv64', |
Haibo Huang | e194fce | 2020-01-06 14:40:27 -0800 | [diff] [blame] | 63 | 'x86': 'i386', |
| 64 | 'x86_64': 'x86_64', |
| 65 | }[arch] |
| 66 | return os.path.join(root, clang_base, "linux-x86", |
| 67 | clang_version, "runtimes_ndk_cxx", arch, "lldb-server") |
| 68 | |
| 69 | |
Nikita Putikhin | 516960e | 2023-05-31 21:57:38 +0000 | [diff] [blame] | 70 | def get_tracer_pid(device: adb.AndroidDevice, pid: int | str | None) -> int: |
Elliott Hughes | 89e1ecf | 2017-06-30 14:03:32 -0700 | [diff] [blame] | 71 | if pid is None: |
| 72 | return 0 |
| 73 | |
| 74 | line, _ = device.shell(["grep", "-e", "^TracerPid:", "/proc/{}/status".format(pid)]) |
| 75 | tracer_pid = re.sub('TracerPid:\t(.*)\n', r'\1', line) |
| 76 | return int(tracer_pid) |
| 77 | |
| 78 | |
Nikita Putikhin | 516960e | 2023-05-31 21:57:38 +0000 | [diff] [blame] | 79 | def parse_args() -> argparse.Namespace: |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 80 | parser = gdbrunner.ArgumentParser() |
| 81 | |
| 82 | group = parser.add_argument_group(title="attach target") |
| 83 | group = group.add_mutually_exclusive_group(required=True) |
| 84 | group.add_argument( |
| 85 | "-p", dest="target_pid", metavar="PID", type=int, |
| 86 | help="attach to a process with specified PID") |
| 87 | group.add_argument( |
| 88 | "-n", dest="target_name", metavar="NAME", |
| 89 | help="attach to a process with specified name") |
| 90 | group.add_argument( |
| 91 | "-r", dest="run_cmd", metavar="CMD", nargs=argparse.REMAINDER, |
| 92 | help="run a binary on the device, with args") |
| 93 | |
| 94 | parser.add_argument( |
| 95 | "--port", nargs="?", default="5039", |
AdityaK | 50c9af7 | 2023-07-14 16:02:43 -0700 | [diff] [blame] | 96 | help="Unused **host** port to forward the debug_socket to.[default: 5039]") |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 97 | parser.add_argument( |
| 98 | "--user", nargs="?", default="root", |
| 99 | help="user to run commands as on the device [default: root]") |
Alex Light | 9247665 | 2019-01-17 11:18:48 -0800 | [diff] [blame] | 100 | parser.add_argument( |
Alex Light | a8f224d | 2020-11-10 10:30:19 -0800 | [diff] [blame] | 101 | "--setup-forwarding", default=None, |
Elliott Hughes | 4c8e875 | 2021-06-25 14:23:22 -0700 | [diff] [blame] | 102 | choices=["lldb", "vscode-lldb"], |
| 103 | help=("Set up lldb-server and port forwarding. Prints commands or " + |
Alex Light | 9247665 | 2019-01-17 11:18:48 -0800 | [diff] [blame] | 104 | ".vscode/launch.json configuration needed to connect the debugging " + |
Nikita Putikhin | 9aa3bc6 | 2023-05-19 20:39:51 +0000 | [diff] [blame] | 105 | "client to the server. 'vscode' with lldb and 'vscode-lldb' both " + |
Elliott Hughes | 4c8e875 | 2021-06-25 14:23:22 -0700 | [diff] [blame] | 106 | "require the 'vadimcn.vscode-lldb' extension.")) |
Nikita Putikhin | 9aa3bc6 | 2023-05-19 20:39:51 +0000 | [diff] [blame] | 107 | parser.add_argument( |
| 108 | "--vscode-launch-props", default=None, |
| 109 | dest="vscode_launch_props", |
| 110 | help=("JSON with extra properties to add to launch parameters when using " + |
| 111 | "vscode-lldb forwarding.")) |
Nikita Putikhin | 7da179e | 2023-07-03 07:37:58 +0000 | [diff] [blame] | 112 | parser.add_argument( |
| 113 | "--vscode-launch-file", default=None, |
| 114 | dest="vscode_launch_file", |
| 115 | help=textwrap.dedent(f"""Path to .vscode/launch.json file for the generated launch |
| 116 | config when using vscode-lldb forwarding. The file needs to |
| 117 | contain two marker lines: '{g_vscode_config_marker_begin}' |
| 118 | and '{g_vscode_config_marker_end}'. The config will be written inline |
| 119 | between these lines, replacing any text that is already there.""")) |
Haibo Huang | e194fce | 2020-01-06 14:40:27 -0800 | [diff] [blame] | 120 | |
Peter Collingbourne | 63bf108 | 2018-12-19 20:51:42 -0800 | [diff] [blame] | 121 | parser.add_argument( |
| 122 | "--env", nargs=1, action="append", metavar="VAR=VALUE", |
| 123 | help="set environment variable when running a binary") |
Peter Collingbourne | ba54826 | 2022-03-03 12:17:43 -0800 | [diff] [blame] | 124 | parser.add_argument( |
| 125 | "--chroot", nargs='?', default="", metavar="PATH", |
| 126 | help="run command in a chroot in the given directory") |
Peter Collingbourne | 63bf108 | 2018-12-19 20:51:42 -0800 | [diff] [blame] | 127 | |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 128 | return parser.parse_args() |
| 129 | |
| 130 | |
Nikita Putikhin | 516960e | 2023-05-31 21:57:38 +0000 | [diff] [blame] | 131 | def verify_device(device: adb.AndroidDevice) -> None: |
Junichi Uekawa | 6612c92 | 2020-09-07 11:20:59 +0900 | [diff] [blame] | 132 | names = set([device.get_prop("ro.build.product"), device.get_prop("ro.product.name")]) |
Josh Gao | 466e289 | 2017-07-13 15:39:05 -0700 | [diff] [blame] | 133 | target_device = os.environ["TARGET_PRODUCT"] |
Junichi Uekawa | 6612c92 | 2020-09-07 11:20:59 +0900 | [diff] [blame] | 134 | if target_device not in names: |
AdityaK | 50c9af7 | 2023-07-14 16:02:43 -0700 | [diff] [blame] | 135 | msg = "You used the wrong lunch: TARGET_PRODUCT ({}) does not match attached device ({})" |
Nikita Putikhin | 516960e | 2023-05-31 21:57:38 +0000 | [diff] [blame] | 136 | sys.exit(msg.format(target_device, ", ".join(n if n else "None" for n in names))) |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 137 | |
| 138 | |
Nikita Putikhin | 516960e | 2023-05-31 21:57:38 +0000 | [diff] [blame] | 139 | def get_remote_pid(device: adb.AndroidDevice, process_name: str) -> int: |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 140 | processes = gdbrunner.get_processes(device) |
| 141 | if process_name not in processes: |
| 142 | msg = "failed to find running process {}".format(process_name) |
| 143 | sys.exit(msg) |
| 144 | pids = processes[process_name] |
| 145 | if len(pids) > 1: |
| 146 | msg = "multiple processes match '{}': {}".format(process_name, pids) |
| 147 | sys.exit(msg) |
| 148 | |
| 149 | # Fetch the binary using the PID later. |
| 150 | return pids[0] |
| 151 | |
| 152 | |
Nikita Putikhin | 516960e | 2023-05-31 21:57:38 +0000 | [diff] [blame] | 153 | def make_temp_dir(prefix: str) -> str: |
Ryan Prichard | 5d1c3cb | 2019-06-04 16:35:02 -0700 | [diff] [blame] | 154 | global g_temp_dirs |
Elliott Hughes | 4c8e875 | 2021-06-25 14:23:22 -0700 | [diff] [blame] | 155 | result = tempfile.mkdtemp(prefix='lldbclient-linker-') |
Ryan Prichard | 5d1c3cb | 2019-06-04 16:35:02 -0700 | [diff] [blame] | 156 | g_temp_dirs.append(result) |
| 157 | return result |
| 158 | |
| 159 | |
Nikita Putikhin | 516960e | 2023-05-31 21:57:38 +0000 | [diff] [blame] | 160 | def ensure_linker(device: adb.AndroidDevice, sysroot: str, interp: str | None) -> str | None: |
Ryan Prichard | 5d1c3cb | 2019-06-04 16:35:02 -0700 | [diff] [blame] | 161 | """Ensure that the device's linker exists on the host. |
| 162 | |
| 163 | PT_INTERP is usually /system/bin/linker[64], but on the device, that file is |
| 164 | a symlink to /apex/com.android.runtime/bin/linker[64]. The symbolized linker |
| 165 | binary on the host is located in ${sysroot}/apex, not in ${sysroot}/system, |
| 166 | so add the ${sysroot}/apex path to the solib search path. |
| 167 | |
| 168 | PT_INTERP will be /system/bin/bootstrap/linker[64] for executables using the |
| 169 | non-APEX/bootstrap linker. No search path modification is needed. |
| 170 | |
| 171 | For a tapas build, only an unbundled app is built, and there is no linker in |
| 172 | ${sysroot} at all, so copy the linker from the device. |
| 173 | |
| 174 | Returns: |
| 175 | A directory to add to the soinfo search path or None if no directory |
| 176 | needs to be added. |
| 177 | """ |
| 178 | |
| 179 | # Static executables have no interpreter. |
| 180 | if interp is None: |
| 181 | return None |
| 182 | |
Elliott Hughes | 4c8e875 | 2021-06-25 14:23:22 -0700 | [diff] [blame] | 183 | # lldb will search for the linker using the PT_INTERP path. First try to find |
Ryan Prichard | 5d1c3cb | 2019-06-04 16:35:02 -0700 | [diff] [blame] | 184 | # it in the sysroot. |
| 185 | local_path = os.path.join(sysroot, interp.lstrip("/")) |
| 186 | if os.path.exists(local_path): |
| 187 | return None |
| 188 | |
| 189 | # If the linker on the device is a symlink, search for the symlink's target |
| 190 | # in the sysroot directory. |
| 191 | interp_real, _ = device.shell(["realpath", interp]) |
| 192 | interp_real = interp_real.strip() |
| 193 | local_path = os.path.join(sysroot, interp_real.lstrip("/")) |
| 194 | if os.path.exists(local_path): |
| 195 | if posixpath.basename(interp) == posixpath.basename(interp_real): |
| 196 | # Add the interpreter's directory to the search path. |
| 197 | return os.path.dirname(local_path) |
| 198 | else: |
| 199 | # If PT_INTERP is linker_asan[64], but the sysroot file is |
Elliott Hughes | 4c8e875 | 2021-06-25 14:23:22 -0700 | [diff] [blame] | 200 | # linker[64], then copy the local file to the name lldb expects. |
| 201 | result = make_temp_dir('lldbclient-linker-') |
Ryan Prichard | 5d1c3cb | 2019-06-04 16:35:02 -0700 | [diff] [blame] | 202 | shutil.copy(local_path, os.path.join(result, posixpath.basename(interp))) |
| 203 | return result |
| 204 | |
| 205 | # Pull the system linker. |
Elliott Hughes | 4c8e875 | 2021-06-25 14:23:22 -0700 | [diff] [blame] | 206 | result = make_temp_dir('lldbclient-linker-') |
Ryan Prichard | 5d1c3cb | 2019-06-04 16:35:02 -0700 | [diff] [blame] | 207 | device.pull(interp, os.path.join(result, posixpath.basename(interp))) |
| 208 | return result |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 209 | |
| 210 | |
Nikita Putikhin | 516960e | 2023-05-31 21:57:38 +0000 | [diff] [blame] | 211 | def handle_switches(args, sysroot: str) -> tuple[BinaryIO, int | None, str | None]: |
Elliott Hughes | 4c8e875 | 2021-06-25 14:23:22 -0700 | [diff] [blame] | 212 | """Fetch the targeted binary and determine how to attach lldb. |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 213 | |
| 214 | Args: |
| 215 | args: Parsed arguments. |
| 216 | sysroot: Local sysroot path. |
| 217 | |
| 218 | Returns: |
| 219 | (binary_file, attach_pid, run_cmd). |
| 220 | Precisely one of attach_pid or run_cmd will be None. |
| 221 | """ |
| 222 | |
| 223 | device = args.device |
| 224 | binary_file = None |
| 225 | pid = None |
| 226 | run_cmd = None |
| 227 | |
Josh Gao | 057c273 | 2017-05-24 15:55:50 -0700 | [diff] [blame] | 228 | args.su_cmd = ["su", args.user] if args.user else [] |
| 229 | |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 230 | if args.target_pid: |
| 231 | # Fetch the binary using the PID later. |
| 232 | pid = args.target_pid |
| 233 | elif args.target_name: |
| 234 | # Fetch the binary using the PID later. |
| 235 | pid = get_remote_pid(device, args.target_name) |
| 236 | elif args.run_cmd: |
| 237 | if not args.run_cmd[0]: |
| 238 | sys.exit("empty command passed to -r") |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 239 | run_cmd = args.run_cmd |
Kevin Rocard | 258c89e | 2017-07-12 18:21:29 -0700 | [diff] [blame] | 240 | if not run_cmd[0].startswith("/"): |
| 241 | try: |
| 242 | run_cmd[0] = gdbrunner.find_executable_path(device, args.run_cmd[0], |
| 243 | run_as_cmd=args.su_cmd) |
| 244 | except RuntimeError: |
| 245 | sys.exit("Could not find executable '{}' passed to -r, " |
| 246 | "please provide an absolute path.".format(args.run_cmd[0])) |
| 247 | |
David Pursell | 639d1c4 | 2015-10-20 15:38:32 -0700 | [diff] [blame] | 248 | binary_file, local = gdbrunner.find_file(device, run_cmd[0], sysroot, |
Josh Gao | 057c273 | 2017-05-24 15:55:50 -0700 | [diff] [blame] | 249 | run_as_cmd=args.su_cmd) |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 250 | if binary_file is None: |
| 251 | assert pid is not None |
| 252 | try: |
David Pursell | 639d1c4 | 2015-10-20 15:38:32 -0700 | [diff] [blame] | 253 | binary_file, local = gdbrunner.find_binary(device, pid, sysroot, |
Josh Gao | 057c273 | 2017-05-24 15:55:50 -0700 | [diff] [blame] | 254 | run_as_cmd=args.su_cmd) |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 255 | except adb.ShellError: |
| 256 | sys.exit("failed to pull binary for PID {}".format(pid)) |
| 257 | |
David Pursell | 639d1c4 | 2015-10-20 15:38:32 -0700 | [diff] [blame] | 258 | if not local: |
| 259 | logging.warning("Couldn't find local unstripped executable in {}," |
| 260 | " symbols may not be available.".format(sysroot)) |
| 261 | |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 262 | return (binary_file, pid, run_cmd) |
| 263 | |
Nikita Putikhin | 9aa3bc6 | 2023-05-19 20:39:51 +0000 | [diff] [blame] | 264 | def merge_launch_dict(base: dict[str, Any], to_add: dict[str, Any] | None) -> None: |
| 265 | """Merges two dicts describing VSCode launch.json properties: base and |
| 266 | to_add. Base is modified in-place with items from to_add. |
| 267 | Items from to_add that are not present in base are inserted. Items that are |
| 268 | present are merged following these rules: |
| 269 | - Lists are merged with to_add elements appended to the end of base |
| 270 | list. Only a list can be merged with a list. |
| 271 | - dicts are merged recursively. Only a dict can be merged with a dict. |
| 272 | - Other present values in base get overwritten with values from to_add. |
| 273 | |
| 274 | The reason for these rules is that merging in new values should prefer to |
| 275 | expand the existing set instead of overwriting where possible. |
| 276 | """ |
| 277 | if to_add is None: |
| 278 | return |
| 279 | |
| 280 | for key, val in to_add.items(): |
| 281 | if key not in base: |
| 282 | base[key] = val |
| 283 | else: |
| 284 | if isinstance(base[key], list) and not isinstance(val, list): |
| 285 | raise ValueError(f'Cannot merge non-list into list at key={key}. ' + |
| 286 | 'You probably need to wrap your value into a list.') |
| 287 | if not isinstance(base[key], list) and isinstance(val, list): |
| 288 | raise ValueError(f'Cannot merge list into non-list at key={key}.') |
| 289 | if isinstance(base[key], dict) != isinstance(val, dict): |
| 290 | raise ValueError(f'Cannot merge dict and non-dict at key={key}') |
| 291 | |
| 292 | # We don't allow the user to overwrite or interleave lists and don't allow |
| 293 | # to delete dict entries. |
| 294 | # It can be done but would make the implementation a bit more complicated |
| 295 | # and provides less value than adding elements. |
| 296 | # We expect that the config generated by gdbclient doesn't contain anything |
| 297 | # the user would want to remove. |
| 298 | if isinstance(base[key], list): |
| 299 | base[key] += val |
| 300 | elif isinstance(base[key], dict): |
| 301 | merge_launch_dict(base[key], val) |
| 302 | else: |
| 303 | base[key] = val |
| 304 | |
| 305 | |
| 306 | def generate_vscode_lldb_script(root: str, sysroot: str, binary_name: str, port: str | int, solib_search_path: list[str], extra_props: dict[str, Any] | None) -> str: |
Alex Light | a8f224d | 2020-11-10 10:30:19 -0800 | [diff] [blame] | 307 | # TODO It would be nice if we didn't need to copy this or run the |
Elliott Hughes | 4c8e875 | 2021-06-25 14:23:22 -0700 | [diff] [blame] | 308 | # lldbclient.py program manually. Doing this would probably require |
Alex Light | a8f224d | 2020-11-10 10:30:19 -0800 | [diff] [blame] | 309 | # writing a vscode extension or modifying an existing one. |
| 310 | # TODO: https://code.visualstudio.com/api/references/vscode-api#debug and |
| 311 | # https://code.visualstudio.com/api/extension-guides/debugger-extension and |
| 312 | # https://github.com/vadimcn/vscode-lldb/blob/6b775c439992b6615e92f4938ee4e211f1b060cf/extension/pickProcess.ts#L6 |
| 313 | res = { |
| 314 | "name": "(lldbclient.py) Attach {} (port: {})".format(binary_name.split("/")[-1], port), |
| 315 | "type": "lldb", |
| 316 | "request": "custom", |
| 317 | "relativePathBase": root, |
| 318 | "sourceMap": { "/b/f/w" : root, '': root, '.': root }, |
| 319 | "initCommands": ['settings append target.exec-search-paths {}'.format(' '.join(solib_search_path))], |
| 320 | "targetCreateCommands": ["target create {}".format(binary_name), |
| 321 | "target modules search-paths add / {}/".format(sysroot)], |
Peter Collingbourne | b6b58a4 | 2023-03-15 14:11:00 -0700 | [diff] [blame] | 322 | "processCreateCommands": ["gdb-remote {}".format(str(port))] |
Alex Light | a8f224d | 2020-11-10 10:30:19 -0800 | [diff] [blame] | 323 | } |
Nikita Putikhin | 9aa3bc6 | 2023-05-19 20:39:51 +0000 | [diff] [blame] | 324 | merge_launch_dict(res, extra_props) |
Alex Light | a8f224d | 2020-11-10 10:30:19 -0800 | [diff] [blame] | 325 | return json.dumps(res, indent=4) |
| 326 | |
Nikita Putikhin | 516960e | 2023-05-31 21:57:38 +0000 | [diff] [blame] | 327 | def generate_lldb_script(root: str, sysroot: str, binary_name: str, port: str | int, solib_search_path: list[str]) -> str: |
Haibo Huang | e194fce | 2020-01-06 14:40:27 -0800 | [diff] [blame] | 328 | commands = [] |
| 329 | commands.append( |
| 330 | 'settings append target.exec-search-paths {}'.format(' '.join(solib_search_path))) |
| 331 | |
| 332 | commands.append('target create {}'.format(binary_name)) |
Haibo Huang | 987436c | 2020-09-22 21:01:31 -0700 | [diff] [blame] | 333 | # For RBE support. |
| 334 | commands.append("settings append target.source-map '/b/f/w' '{}'".format(root)) |
| 335 | commands.append("settings append target.source-map '' '{}'".format(root)) |
Haibo Huang | e194fce | 2020-01-06 14:40:27 -0800 | [diff] [blame] | 336 | commands.append('target modules search-paths add / {}/'.format(sysroot)) |
Peter Collingbourne | b6b58a4 | 2023-03-15 14:11:00 -0700 | [diff] [blame] | 337 | commands.append('gdb-remote {}'.format(str(port))) |
Haibo Huang | e194fce | 2020-01-06 14:40:27 -0800 | [diff] [blame] | 338 | return '\n'.join(commands) |
| 339 | |
| 340 | |
Nikita Putikhin | 9aa3bc6 | 2023-05-19 20:39:51 +0000 | [diff] [blame] | 341 | def generate_setup_script(sysroot: str, linker_search_dir: str | None, binary_name: str, is64bit: bool, port: str | int, debugger: str, vscode_launch_props: dict[str, Any] | None) -> str: |
Alex Light | 9247665 | 2019-01-17 11:18:48 -0800 | [diff] [blame] | 342 | # Generate a setup script. |
Alex Light | 9247665 | 2019-01-17 11:18:48 -0800 | [diff] [blame] | 343 | root = os.environ["ANDROID_BUILD_TOP"] |
| 344 | symbols_dir = os.path.join(sysroot, "system", "lib64" if is64bit else "lib") |
| 345 | vendor_dir = os.path.join(sysroot, "vendor", "lib64" if is64bit else "lib") |
| 346 | |
| 347 | solib_search_path = [] |
| 348 | symbols_paths = ["", "hw", "ssl/engines", "drm", "egl", "soundfx"] |
| 349 | vendor_paths = ["", "hw", "egl"] |
| 350 | solib_search_path += [os.path.join(symbols_dir, x) for x in symbols_paths] |
| 351 | solib_search_path += [os.path.join(vendor_dir, x) for x in vendor_paths] |
Ryan Prichard | 5d1c3cb | 2019-06-04 16:35:02 -0700 | [diff] [blame] | 352 | if linker_search_dir is not None: |
| 353 | solib_search_path += [linker_search_dir] |
Alex Light | 9247665 | 2019-01-17 11:18:48 -0800 | [diff] [blame] | 354 | |
Alex Light | a8f224d | 2020-11-10 10:30:19 -0800 | [diff] [blame] | 355 | if debugger == "vscode-lldb": |
| 356 | return generate_vscode_lldb_script( |
Nikita Putikhin | 9aa3bc6 | 2023-05-19 20:39:51 +0000 | [diff] [blame] | 357 | root, sysroot, binary_name, port, solib_search_path, vscode_launch_props) |
Haibo Huang | e194fce | 2020-01-06 14:40:27 -0800 | [diff] [blame] | 358 | elif debugger == 'lldb': |
| 359 | return generate_lldb_script( |
Nikita Putikhin | 516960e | 2023-05-31 21:57:38 +0000 | [diff] [blame] | 360 | root, sysroot, binary_name, port, solib_search_path) |
Alex Light | 9247665 | 2019-01-17 11:18:48 -0800 | [diff] [blame] | 361 | else: |
| 362 | raise Exception("Unknown debugger type " + debugger) |
| 363 | |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 364 | |
Nikita Putikhin | 7da179e | 2023-07-03 07:37:58 +0000 | [diff] [blame] | 365 | def insert_commands_into_vscode_config(dst_launch_config: str, setup_commands: str) -> str: |
| 366 | """Inserts setup commands into launch config between two marker lines. |
| 367 | Marker lines are set in global variables g_vscode_config_marker_end and g_vscode_config_marker_end. |
| 368 | The commands are inserted with the same indentation as the first marker line. |
| 369 | |
| 370 | Args: |
| 371 | dst_launch_config: Config to insert commands into. |
| 372 | setup_commands: Commands to insert. |
| 373 | Returns: |
| 374 | Config with inserted commands. |
| 375 | Raises: |
| 376 | ValueError if the begin marker is not found or not terminated with an end marker. |
| 377 | """ |
| 378 | |
| 379 | # We expect the files to be small (~10s KB), so we use simple string concatenation |
| 380 | # for simplicity and readability even if it is slower. |
| 381 | output = "" |
| 382 | found_at_least_one_begin = False |
| 383 | unterminated_begin_line = None |
| 384 | |
| 385 | # It might be tempting to rewrite this using find() or even regexes, |
| 386 | # but keeping track of line numbers, preserving whitespace, and detecting indent |
| 387 | # becomes tricky enough that this simple loop is more clear. |
| 388 | for linenum, line in enumerate(dst_launch_config.splitlines(keepends=True), start=1): |
| 389 | if unterminated_begin_line != None: |
| 390 | if line.strip() == g_vscode_config_marker_end: |
| 391 | unterminated_begin_line = None |
| 392 | else: |
| 393 | continue |
| 394 | output += line |
| 395 | if line.strip() == g_vscode_config_marker_begin: |
| 396 | found_at_least_one_begin = True |
| 397 | unterminated_begin_line = linenum |
| 398 | marker_indent = line[:line.find(g_vscode_config_marker_begin)] |
| 399 | output += textwrap.indent(setup_commands, marker_indent) + '\n' |
| 400 | |
| 401 | if not found_at_least_one_begin: |
| 402 | raise ValueError(f"Did not find begin marker line '{g_vscode_config_marker_begin}' " + |
| 403 | "in the VSCode launch file") |
| 404 | |
| 405 | if unterminated_begin_line is not None: |
| 406 | raise ValueError(f"Unterminated begin marker at line {unterminated_begin_line} " + |
| 407 | f"in the VSCode launch file. Add end marker line to file: '{g_vscode_config_marker_end}'") |
| 408 | |
| 409 | return output |
| 410 | |
| 411 | |
| 412 | def replace_file_contents(dst_path: os.PathLike, contents: str) -> None: |
| 413 | """Replaces the contents of the file pointed to by dst_path. |
| 414 | |
| 415 | This function writes the new contents into a temporary file, then atomically swaps it with |
| 416 | the target file. This way if a write fails, the original file is not overwritten. |
| 417 | |
| 418 | Args: |
| 419 | dst_path: The path to the file to be replaced. |
| 420 | contents: The new contents of the file. |
| 421 | Raises: |
| 422 | Forwards exceptions from underlying filesystem methods. |
| 423 | """ |
| 424 | tempf = tempfile.NamedTemporaryFile('w', delete=False) |
| 425 | try: |
| 426 | tempf.write(contents) |
| 427 | os.replace(tempf.name, dst_path) |
| 428 | except: |
| 429 | os.remove(tempf.name) |
| 430 | raise |
| 431 | |
| 432 | |
| 433 | def write_vscode_config(vscode_launch_file: pathlib.Path, setup_commands: str) -> None: |
| 434 | """Writes setup_commands into the file pointed by vscode_launch_file. |
| 435 | |
| 436 | See insert_commands_into_vscode_config for the description of how the setup commands are written. |
| 437 | """ |
| 438 | contents = insert_commands_into_vscode_config(vscode_launch_file.read_text(), setup_commands) |
| 439 | replace_file_contents(vscode_launch_file, contents) |
| 440 | |
| 441 | |
Nikita Putikhin | 516960e | 2023-05-31 21:57:38 +0000 | [diff] [blame] | 442 | def do_main() -> None: |
Josh Gao | 466e289 | 2017-07-13 15:39:05 -0700 | [diff] [blame] | 443 | required_env = ["ANDROID_BUILD_TOP", |
| 444 | "ANDROID_PRODUCT_OUT", "TARGET_PRODUCT"] |
| 445 | for env in required_env: |
| 446 | if env not in os.environ: |
| 447 | sys.exit( |
| 448 | "Environment variable '{}' not defined, have you run lunch?".format(env)) |
| 449 | |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 450 | args = parse_args() |
| 451 | device = args.device |
Josh Gao | 44b84a8 | 2015-10-28 11:57:37 -0700 | [diff] [blame] | 452 | |
| 453 | if device is None: |
| 454 | sys.exit("ERROR: Failed to find device.") |
| 455 | |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 456 | root = os.environ["ANDROID_BUILD_TOP"] |
Josh Gao | 466e289 | 2017-07-13 15:39:05 -0700 | [diff] [blame] | 457 | sysroot = os.path.join(os.environ["ANDROID_PRODUCT_OUT"], "symbols") |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 458 | |
| 459 | # Make sure the environment matches the attached device. |
Peter Collingbourne | ba54826 | 2022-03-03 12:17:43 -0800 | [diff] [blame] | 460 | # Skip when running in a chroot because the chroot lunch target may not |
| 461 | # match the device's lunch target. |
| 462 | if not args.chroot: |
Nikita Putikhin | 516960e | 2023-05-31 21:57:38 +0000 | [diff] [blame] | 463 | verify_device(device) |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 464 | |
| 465 | debug_socket = "/data/local/tmp/debug_socket" |
| 466 | pid = None |
| 467 | run_cmd = None |
| 468 | |
| 469 | # Fetch binary for -p, -n. |
David Pursell | 639d1c4 | 2015-10-20 15:38:32 -0700 | [diff] [blame] | 470 | binary_file, pid, run_cmd = handle_switches(args, sysroot) |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 471 | |
Nikita Putikhin | 9aa3bc6 | 2023-05-19 20:39:51 +0000 | [diff] [blame] | 472 | vscode_launch_props = None |
| 473 | if args.vscode_launch_props: |
| 474 | if args.setup_forwarding != "vscode-lldb": |
Nikita Putikhin | 7da179e | 2023-07-03 07:37:58 +0000 | [diff] [blame] | 475 | raise ValueError( |
| 476 | 'vscode-launch-props requires --setup-forwarding=vscode-lldb') |
Nikita Putikhin | 9aa3bc6 | 2023-05-19 20:39:51 +0000 | [diff] [blame] | 477 | vscode_launch_props = json.loads(args.vscode_launch_props) |
| 478 | |
Nikita Putikhin | 7da179e | 2023-07-03 07:37:58 +0000 | [diff] [blame] | 479 | vscode_launch_file = None |
| 480 | if args.vscode_launch_file: |
| 481 | if args.setup_forwarding != "vscode-lldb": |
| 482 | raise ValueError( |
| 483 | 'vscode-launch-file requires --setup-forwarding=vscode-lldb') |
| 484 | vscode_launch_file = args.vscode_launch_file |
| 485 | |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 486 | with binary_file: |
Ryan Prichard | 5d1c3cb | 2019-06-04 16:35:02 -0700 | [diff] [blame] | 487 | if sys.platform.startswith("linux"): |
| 488 | platform_name = "linux-x86" |
| 489 | elif sys.platform.startswith("darwin"): |
| 490 | platform_name = "darwin-x86" |
| 491 | else: |
| 492 | sys.exit("Unknown platform: {}".format(sys.platform)) |
| 493 | |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 494 | arch = gdbrunner.get_binary_arch(binary_file) |
| 495 | is64bit = arch.endswith("64") |
| 496 | |
| 497 | # Make sure we have the linker |
Pirama Arumuga Nainar | f7f9544 | 2021-06-30 13:31:41 -0700 | [diff] [blame] | 498 | clang_base = 'prebuilts/clang/host' |
| 499 | clang_version = read_toolchain_config(root) |
Haibo Huang | e194fce | 2020-01-06 14:40:27 -0800 | [diff] [blame] | 500 | toolchain_path = os.path.join(root, clang_base, platform_name, |
| 501 | clang_version) |
| 502 | llvm_readobj_path = os.path.join(toolchain_path, "bin", "llvm-readobj") |
Ryan Prichard | 5d1c3cb | 2019-06-04 16:35:02 -0700 | [diff] [blame] | 503 | interp = gdbrunner.get_binary_interp(binary_file.name, llvm_readobj_path) |
| 504 | linker_search_dir = ensure_linker(device, sysroot, interp) |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 505 | |
Elliott Hughes | 89e1ecf | 2017-06-30 14:03:32 -0700 | [diff] [blame] | 506 | tracer_pid = get_tracer_pid(device, pid) |
| 507 | if tracer_pid == 0: |
Peter Collingbourne | 63bf108 | 2018-12-19 20:51:42 -0800 | [diff] [blame] | 508 | cmd_prefix = args.su_cmd |
| 509 | if args.env: |
| 510 | cmd_prefix += ['env'] + [v[0] for v in args.env] |
| 511 | |
Elliott Hughes | 4c8e875 | 2021-06-25 14:23:22 -0700 | [diff] [blame] | 512 | # Start lldb-server. |
| 513 | server_local_path = get_lldb_server_path(root, clang_base, clang_version, arch) |
| 514 | server_remote_path = "/data/local/tmp/{}-lldb-server".format(arch) |
Elliott Hughes | 89e1ecf | 2017-06-30 14:03:32 -0700 | [diff] [blame] | 515 | gdbrunner.start_gdbserver( |
Haibo Huang | e194fce | 2020-01-06 14:40:27 -0800 | [diff] [blame] | 516 | device, server_local_path, server_remote_path, |
Elliott Hughes | 89e1ecf | 2017-06-30 14:03:32 -0700 | [diff] [blame] | 517 | target_pid=pid, run_cmd=run_cmd, debug_socket=debug_socket, |
Peter Collingbourne | ba54826 | 2022-03-03 12:17:43 -0800 | [diff] [blame] | 518 | port=args.port, run_as_cmd=cmd_prefix, lldb=True, chroot=args.chroot) |
Elliott Hughes | 89e1ecf | 2017-06-30 14:03:32 -0700 | [diff] [blame] | 519 | else: |
Haibo Huang | e194fce | 2020-01-06 14:40:27 -0800 | [diff] [blame] | 520 | print( |
| 521 | "Connecting to tracing pid {} using local port {}".format( |
| 522 | tracer_pid, args.port)) |
Elliott Hughes | 89e1ecf | 2017-06-30 14:03:32 -0700 | [diff] [blame] | 523 | gdbrunner.forward_gdbserver_port(device, local=args.port, |
| 524 | remote="tcp:{}".format(args.port)) |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 525 | |
Elliott Hughes | 4c8e875 | 2021-06-25 14:23:22 -0700 | [diff] [blame] | 526 | debugger_path = get_lldb_path(toolchain_path) |
| 527 | debugger = args.setup_forwarding or 'lldb' |
Haibo Huang | e194fce | 2020-01-06 14:40:27 -0800 | [diff] [blame] | 528 | |
Elliott Hughes | 4c8e875 | 2021-06-25 14:23:22 -0700 | [diff] [blame] | 529 | # Generate the lldb script. |
Nikita Putikhin | 516960e | 2023-05-31 21:57:38 +0000 | [diff] [blame] | 530 | setup_commands = generate_setup_script(sysroot=sysroot, |
Ryan Prichard | 5d1c3cb | 2019-06-04 16:35:02 -0700 | [diff] [blame] | 531 | linker_search_dir=linker_search_dir, |
Nikita Putikhin | 516960e | 2023-05-31 21:57:38 +0000 | [diff] [blame] | 532 | binary_name=binary_file.name, |
Alex Light | 9247665 | 2019-01-17 11:18:48 -0800 | [diff] [blame] | 533 | is64bit=is64bit, |
| 534 | port=args.port, |
Nikita Putikhin | 9aa3bc6 | 2023-05-19 20:39:51 +0000 | [diff] [blame] | 535 | debugger=debugger, |
| 536 | vscode_launch_props=vscode_launch_props) |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 537 | |
Alex Light | a8f224d | 2020-11-10 10:30:19 -0800 | [diff] [blame] | 538 | if not args.setup_forwarding: |
Alex Light | 9247665 | 2019-01-17 11:18:48 -0800 | [diff] [blame] | 539 | # Print a newline to separate our messages from the GDB session. |
| 540 | print("") |
David Pursell | 639d1c4 | 2015-10-20 15:38:32 -0700 | [diff] [blame] | 541 | |
Elliott Hughes | 4c8e875 | 2021-06-25 14:23:22 -0700 | [diff] [blame] | 542 | # Start lldb. |
| 543 | gdbrunner.start_gdb(debugger_path, setup_commands, lldb=True) |
Alex Light | 9247665 | 2019-01-17 11:18:48 -0800 | [diff] [blame] | 544 | else: |
Nikita Putikhin | 7da179e | 2023-07-03 07:37:58 +0000 | [diff] [blame] | 545 | if args.setup_forwarding == "vscode-lldb" and vscode_launch_file: |
| 546 | write_vscode_config(pathlib.Path(vscode_launch_file) , setup_commands) |
| 547 | print(f"Generated config written to '{vscode_launch_file}'") |
Alex Light | 9247665 | 2019-01-17 11:18:48 -0800 | [diff] [blame] | 548 | else: |
Nikita Putikhin | 7da179e | 2023-07-03 07:37:58 +0000 | [diff] [blame] | 549 | print("") |
| 550 | print(setup_commands) |
| 551 | print("") |
| 552 | if args.setup_forwarding == "vscode-lldb": |
| 553 | print(textwrap.dedent(""" |
| 554 | Paste the above json into .vscode/launch.json and start the debugger as |
| 555 | normal.""")) |
| 556 | else: |
| 557 | print(textwrap.dedent(""" |
| 558 | Paste the lldb commands above into the lldb frontend to set up the |
| 559 | lldb-server connection.""")) |
| 560 | |
| 561 | print(textwrap.dedent(""" |
| 562 | Press enter in this terminal once debugging is finished to shut lldb-server |
| 563 | down and close all the ports.""")) |
Alex Light | 9247665 | 2019-01-17 11:18:48 -0800 | [diff] [blame] | 564 | print("") |
Siarhei Vishniakou | 9c4f1b3 | 2021-12-02 10:43:14 -0800 | [diff] [blame] | 565 | input("Press enter to shut down lldb-server") |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 566 | |
Ryan Prichard | 5d1c3cb | 2019-06-04 16:35:02 -0700 | [diff] [blame] | 567 | |
| 568 | def main(): |
| 569 | try: |
| 570 | do_main() |
| 571 | finally: |
| 572 | global g_temp_dirs |
| 573 | for temp_dir in g_temp_dirs: |
| 574 | shutil.rmtree(temp_dir) |
| 575 | |
| 576 | |
Josh Gao | 043bad7 | 2015-09-22 11:43:08 -0700 | [diff] [blame] | 577 | if __name__ == "__main__": |
| 578 | main() |