blob: 639f6e9d0cbd634518416eed5620fac58feadfcd [file] [log] [blame]
Josh Gao043bad72015-09-22 11:43:08 -07001#!/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
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
Josh Gao043bad72015-09-22 11:43:08 -070057def get_gdbserver_path(root, arch):
Haibo Huang931cd0b2019-03-26 13:57:32 -070058 path = "{}/prebuilts/misc/gdbserver/android-{}/gdbserver{}"
Josh Gao043bad72015-09-22 11:43:08 -070059 if arch.endswith("64"):
Haibo Huang931cd0b2019-03-26 13:57:32 -070060 return path.format(root, arch, "64")
Josh Gao043bad72015-09-22 11:43:08 -070061 else:
Haibo Huang931cd0b2019-03-26 13:57:32 -070062 return path.format(root, arch, "")
Josh Gao043bad72015-09-22 11:43:08 -070063
64
Haibo Huange4d8bfd2020-07-22 16:37:35 -070065def get_lldb_path(toolchain_path):
66 for lldb_name in ['lldb.sh', 'lldb.cmd', 'lldb', 'lldb.exe']:
67 debugger_path = os.path.join(toolchain_path, "bin", lldb_name)
68 if os.path.isfile(debugger_path):
69 return debugger_path
70 return None
71
72
Haibo Huange194fce2020-01-06 14:40:27 -080073def get_lldb_server_path(root, clang_base, clang_version, arch):
74 arch = {
75 'arm': 'arm',
76 'arm64': 'aarch64',
77 'x86': 'i386',
78 'x86_64': 'x86_64',
79 }[arch]
80 return os.path.join(root, clang_base, "linux-x86",
81 clang_version, "runtimes_ndk_cxx", arch, "lldb-server")
82
83
Elliott Hughes89e1ecf2017-06-30 14:03:32 -070084def get_tracer_pid(device, pid):
85 if pid is None:
86 return 0
87
88 line, _ = device.shell(["grep", "-e", "^TracerPid:", "/proc/{}/status".format(pid)])
89 tracer_pid = re.sub('TracerPid:\t(.*)\n', r'\1', line)
90 return int(tracer_pid)
91
92
Josh Gao043bad72015-09-22 11:43:08 -070093def parse_args():
94 parser = gdbrunner.ArgumentParser()
95
96 group = parser.add_argument_group(title="attach target")
97 group = group.add_mutually_exclusive_group(required=True)
98 group.add_argument(
99 "-p", dest="target_pid", metavar="PID", type=int,
100 help="attach to a process with specified PID")
101 group.add_argument(
102 "-n", dest="target_name", metavar="NAME",
103 help="attach to a process with specified name")
104 group.add_argument(
105 "-r", dest="run_cmd", metavar="CMD", nargs=argparse.REMAINDER,
106 help="run a binary on the device, with args")
107
108 parser.add_argument(
109 "--port", nargs="?", default="5039",
Elliott Hughes89e1ecf2017-06-30 14:03:32 -0700110 help="override the port used on the host [default: 5039]")
Josh Gao043bad72015-09-22 11:43:08 -0700111 parser.add_argument(
112 "--user", nargs="?", default="root",
113 help="user to run commands as on the device [default: root]")
Alex Light92476652019-01-17 11:18:48 -0800114 parser.add_argument(
115 "--setup-forwarding", default=None, choices=["gdb", "vscode"],
116 help=("Setup the gdbserver and port forwarding. Prints commands or " +
117 ".vscode/launch.json configuration needed to connect the debugging " +
118 "client to the server."))
Josh Gao043bad72015-09-22 11:43:08 -0700119
Haibo Huange194fce2020-01-06 14:40:27 -0800120 lldb_group = parser.add_mutually_exclusive_group()
121 lldb_group.add_argument("--lldb", action="store_true", help="Use lldb.")
122 lldb_group.add_argument("--no-lldb", action="store_true", help="Do not use lldb.")
123
Peter Collingbourne63bf1082018-12-19 20:51:42 -0800124 parser.add_argument(
125 "--env", nargs=1, action="append", metavar="VAR=VALUE",
126 help="set environment variable when running a binary")
127
Josh Gao043bad72015-09-22 11:43:08 -0700128 return parser.parse_args()
129
130
Elliott Hughes1a2f12d2017-06-02 13:15:59 -0700131def verify_device(root, device):
Junichi Uekawa6612c922020-09-07 11:20:59 +0900132 names = set([device.get_prop("ro.build.product"), device.get_prop("ro.product.name")])
Josh Gao466e2892017-07-13 15:39:05 -0700133 target_device = os.environ["TARGET_PRODUCT"]
Junichi Uekawa6612c922020-09-07 11:20:59 +0900134 if target_device not in names:
Josh Gao466e2892017-07-13 15:39:05 -0700135 msg = "TARGET_PRODUCT ({}) does not match attached device ({})"
Junichi Uekawa6612c922020-09-07 11:20:59 +0900136 sys.exit(msg.format(target_device, ", ".join(names)))
Josh Gao043bad72015-09-22 11:43:08 -0700137
138
139def get_remote_pid(device, process_name):
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
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -0700153def make_temp_dir(prefix):
154 global g_temp_dirs
155 result = tempfile.mkdtemp(prefix='gdbclient-linker-')
156 g_temp_dirs.append(result)
157 return result
158
159
160def ensure_linker(device, sysroot, interp):
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
183 # gdb will search for the linker using the PT_INTERP path. First try to find
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
200 # linker[64], then copy the local file to the name gdb expects.
201 result = make_temp_dir('gdbclient-linker-')
202 shutil.copy(local_path, os.path.join(result, posixpath.basename(interp)))
203 return result
204
205 # Pull the system linker.
206 result = make_temp_dir('gdbclient-linker-')
207 device.pull(interp, os.path.join(result, posixpath.basename(interp)))
208 return result
Josh Gao043bad72015-09-22 11:43:08 -0700209
210
David Pursell639d1c42015-10-20 15:38:32 -0700211def handle_switches(args, sysroot):
Josh Gao043bad72015-09-22 11:43:08 -0700212 """Fetch the targeted binary and determine how to attach gdb.
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 Gao057c2732017-05-24 15:55:50 -0700228 args.su_cmd = ["su", args.user] if args.user else []
229
Josh Gao043bad72015-09-22 11:43:08 -0700230 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 Gao043bad72015-09-22 11:43:08 -0700239 run_cmd = args.run_cmd
Kevin Rocard258c89e2017-07-12 18:21:29 -0700240 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 Pursell639d1c42015-10-20 15:38:32 -0700248 binary_file, local = gdbrunner.find_file(device, run_cmd[0], sysroot,
Josh Gao057c2732017-05-24 15:55:50 -0700249 run_as_cmd=args.su_cmd)
Josh Gao043bad72015-09-22 11:43:08 -0700250 if binary_file is None:
251 assert pid is not None
252 try:
David Pursell639d1c42015-10-20 15:38:32 -0700253 binary_file, local = gdbrunner.find_binary(device, pid, sysroot,
Josh Gao057c2732017-05-24 15:55:50 -0700254 run_as_cmd=args.su_cmd)
Josh Gao043bad72015-09-22 11:43:08 -0700255 except adb.ShellError:
256 sys.exit("failed to pull binary for PID {}".format(pid))
257
David Pursell639d1c42015-10-20 15:38:32 -0700258 if not local:
259 logging.warning("Couldn't find local unstripped executable in {},"
260 " symbols may not be available.".format(sysroot))
261
Josh Gao043bad72015-09-22 11:43:08 -0700262 return (binary_file, pid, run_cmd)
263
Alex Light92476652019-01-17 11:18:48 -0800264def generate_vscode_script(gdbpath, root, sysroot, binary_name, port, dalvik_gdb_script, solib_search_path):
265 # TODO It would be nice if we didn't need to copy this or run the
266 # gdbclient.py program manually. Doing this would probably require
267 # writing a vscode extension or modifying an existing one.
268 res = {
269 "name": "(gdbclient.py) Attach {} (port: {})".format(binary_name.split("/")[-1], port),
270 "type": "cppdbg",
271 "request": "launch", # Needed for gdbserver.
272 "cwd": root,
273 "program": binary_name,
274 "MIMode": "gdb",
275 "miDebuggerServerAddress": "localhost:{}".format(port),
276 "miDebuggerPath": gdbpath,
277 "setupCommands": [
278 {
279 # Required for vscode.
280 "description": "Enable pretty-printing for gdb",
281 "text": "-enable-pretty-printing",
282 "ignoreFailures": True,
283 },
284 {
285 "description": "gdb command: dir",
286 "text": "-environment-directory {}".format(root),
287 "ignoreFailures": False
288 },
289 {
290 "description": "gdb command: set solib-search-path",
291 "text": "-gdb-set solib-search-path {}".format(":".join(solib_search_path)),
292 "ignoreFailures": False
293 },
294 {
295 "description": "gdb command: set solib-absolute-prefix",
296 "text": "-gdb-set solib-absolute-prefix {}".format(sysroot),
297 "ignoreFailures": False
298 },
299 ]
300 }
301 if dalvik_gdb_script:
302 res["setupCommands"].append({
303 "description": "gdb command: source art commands",
304 "text": "-interpreter-exec console \"source {}\"".format(dalvik_gdb_script),
305 "ignoreFailures": False,
306 })
307 return json.dumps(res, indent=4)
Josh Gao466e2892017-07-13 15:39:05 -0700308
Alex Light92476652019-01-17 11:18:48 -0800309def generate_gdb_script(root, sysroot, binary_name, port, dalvik_gdb_script, solib_search_path, connect_timeout):
Josh Gao043bad72015-09-22 11:43:08 -0700310 solib_search_path = ":".join(solib_search_path)
311
312 gdb_commands = ""
Alex Light92476652019-01-17 11:18:48 -0800313 gdb_commands += "file '{}'\n".format(binary_name)
Josh Gao19f18ce2015-10-22 16:08:13 -0700314 gdb_commands += "directory '{}'\n".format(root)
Josh Gao043bad72015-09-22 11:43:08 -0700315 gdb_commands += "set solib-absolute-prefix {}\n".format(sysroot)
316 gdb_commands += "set solib-search-path {}\n".format(solib_search_path)
Alex Light92476652019-01-17 11:18:48 -0800317 if dalvik_gdb_script:
Josh Gao043bad72015-09-22 11:43:08 -0700318 gdb_commands += "source {}\n".format(dalvik_gdb_script)
319
David Pursell320f8812015-10-05 14:22:10 -0700320 # Try to connect for a few seconds, sometimes the device gdbserver takes
321 # a little bit to come up, especially on emulators.
322 gdb_commands += """
323python
324
325def target_remote_with_retry(target, timeout_seconds):
326 import time
327 end_time = time.time() + timeout_seconds
328 while True:
329 try:
Dan Albertd124bc72018-06-26 11:15:16 -0700330 gdb.execute("target extended-remote " + target)
David Pursell320f8812015-10-05 14:22:10 -0700331 return True
332 except gdb.error as e:
333 time_left = end_time - time.time()
334 if time_left < 0 or time_left > timeout_seconds:
335 print("Error: unable to connect to device.")
336 print(e)
337 return False
338 time.sleep(min(0.25, time_left))
339
340target_remote_with_retry(':{}', {})
341
342end
343""".format(port, connect_timeout)
344
Josh Gao043bad72015-09-22 11:43:08 -0700345 return gdb_commands
346
Haibo Huange194fce2020-01-06 14:40:27 -0800347
Haibo Huang07e17072020-05-12 16:51:29 -0700348def generate_lldb_script(root, sysroot, binary_name, port, solib_search_path):
Haibo Huange194fce2020-01-06 14:40:27 -0800349 commands = []
350 commands.append(
351 'settings append target.exec-search-paths {}'.format(' '.join(solib_search_path)))
352
353 commands.append('target create {}'.format(binary_name))
Haibo Huang987436c2020-09-22 21:01:31 -0700354 # For RBE support.
355 commands.append("settings append target.source-map '/b/f/w' '{}'".format(root))
356 commands.append("settings append target.source-map '' '{}'".format(root))
Haibo Huange194fce2020-01-06 14:40:27 -0800357 commands.append('target modules search-paths add / {}/'.format(sysroot))
358 commands.append('gdb-remote {}'.format(port))
359 return '\n'.join(commands)
360
361
362def generate_setup_script(debugger_path, sysroot, linker_search_dir, binary_file, is64bit, port, debugger, connect_timeout=5):
Alex Light92476652019-01-17 11:18:48 -0800363 # Generate a setup script.
364 # TODO: Detect the zygote and run 'art-on' automatically.
365 root = os.environ["ANDROID_BUILD_TOP"]
366 symbols_dir = os.path.join(sysroot, "system", "lib64" if is64bit else "lib")
367 vendor_dir = os.path.join(sysroot, "vendor", "lib64" if is64bit else "lib")
368
369 solib_search_path = []
370 symbols_paths = ["", "hw", "ssl/engines", "drm", "egl", "soundfx"]
371 vendor_paths = ["", "hw", "egl"]
372 solib_search_path += [os.path.join(symbols_dir, x) for x in symbols_paths]
373 solib_search_path += [os.path.join(vendor_dir, x) for x in vendor_paths]
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -0700374 if linker_search_dir is not None:
375 solib_search_path += [linker_search_dir]
Alex Light92476652019-01-17 11:18:48 -0800376
377 dalvik_gdb_script = os.path.join(root, "development", "scripts", "gdb", "dalvik.gdb")
378 if not os.path.exists(dalvik_gdb_script):
379 logging.warning(("couldn't find {} - ART debugging options will not " +
380 "be available").format(dalvik_gdb_script))
381 dalvik_gdb_script = None
382
383 if debugger == "vscode":
384 return generate_vscode_script(
Haibo Huange194fce2020-01-06 14:40:27 -0800385 debugger_path, root, sysroot, binary_file.name, port, dalvik_gdb_script, solib_search_path)
Alex Light92476652019-01-17 11:18:48 -0800386 elif debugger == "gdb":
387 return generate_gdb_script(root, sysroot, binary_file.name, port, dalvik_gdb_script, solib_search_path, connect_timeout)
Haibo Huange194fce2020-01-06 14:40:27 -0800388 elif debugger == 'lldb':
389 return generate_lldb_script(
Haibo Huang07e17072020-05-12 16:51:29 -0700390 root, sysroot, binary_file.name, port, solib_search_path)
Alex Light92476652019-01-17 11:18:48 -0800391 else:
392 raise Exception("Unknown debugger type " + debugger)
393
Josh Gao043bad72015-09-22 11:43:08 -0700394
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -0700395def do_main():
Josh Gao466e2892017-07-13 15:39:05 -0700396 required_env = ["ANDROID_BUILD_TOP",
397 "ANDROID_PRODUCT_OUT", "TARGET_PRODUCT"]
398 for env in required_env:
399 if env not in os.environ:
400 sys.exit(
401 "Environment variable '{}' not defined, have you run lunch?".format(env))
402
Josh Gao043bad72015-09-22 11:43:08 -0700403 args = parse_args()
404 device = args.device
Josh Gao44b84a82015-10-28 11:57:37 -0700405
406 if device is None:
407 sys.exit("ERROR: Failed to find device.")
408
Josh Gao043bad72015-09-22 11:43:08 -0700409 root = os.environ["ANDROID_BUILD_TOP"]
Josh Gao466e2892017-07-13 15:39:05 -0700410 sysroot = os.path.join(os.environ["ANDROID_PRODUCT_OUT"], "symbols")
Josh Gao043bad72015-09-22 11:43:08 -0700411
412 # Make sure the environment matches the attached device.
Elliott Hughes1a2f12d2017-06-02 13:15:59 -0700413 verify_device(root, device)
Josh Gao043bad72015-09-22 11:43:08 -0700414
415 debug_socket = "/data/local/tmp/debug_socket"
416 pid = None
417 run_cmd = None
418
419 # Fetch binary for -p, -n.
David Pursell639d1c42015-10-20 15:38:32 -0700420 binary_file, pid, run_cmd = handle_switches(args, sysroot)
Josh Gao043bad72015-09-22 11:43:08 -0700421
422 with binary_file:
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -0700423 if sys.platform.startswith("linux"):
424 platform_name = "linux-x86"
425 elif sys.platform.startswith("darwin"):
426 platform_name = "darwin-x86"
427 else:
428 sys.exit("Unknown platform: {}".format(sys.platform))
429
Josh Gao043bad72015-09-22 11:43:08 -0700430 arch = gdbrunner.get_binary_arch(binary_file)
431 is64bit = arch.endswith("64")
432
433 # Make sure we have the linker
Haibo Huange194fce2020-01-06 14:40:27 -0800434 clang_base, clang_version = read_toolchain_config(root)
435 toolchain_path = os.path.join(root, clang_base, platform_name,
436 clang_version)
437 llvm_readobj_path = os.path.join(toolchain_path, "bin", "llvm-readobj")
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -0700438 interp = gdbrunner.get_binary_interp(binary_file.name, llvm_readobj_path)
439 linker_search_dir = ensure_linker(device, sysroot, interp)
Josh Gao043bad72015-09-22 11:43:08 -0700440
Elliott Hughes89e1ecf2017-06-30 14:03:32 -0700441 tracer_pid = get_tracer_pid(device, pid)
Haibo Huang6a4636a2020-09-14 18:39:52 -0700442 if os.path.basename(__file__) == 'gdbclient.py' and not args.lldb:
443 print("gdb is deprecated in favor of lldb. "
444 "If you can't use lldb, please set --no-lldb and file a bug asap.")
445 use_lldb = not args.no_lldb
Elliott Hughes89e1ecf2017-06-30 14:03:32 -0700446 if tracer_pid == 0:
Peter Collingbourne63bf1082018-12-19 20:51:42 -0800447 cmd_prefix = args.su_cmd
448 if args.env:
449 cmd_prefix += ['env'] + [v[0] for v in args.env]
450
Elliott Hughes89e1ecf2017-06-30 14:03:32 -0700451 # Start gdbserver.
Haibo Huange194fce2020-01-06 14:40:27 -0800452 if use_lldb:
453 server_local_path = get_lldb_server_path(
454 root, clang_base, clang_version, arch)
455 server_remote_path = "/data/local/tmp/{}-lldb-server".format(
456 arch)
457 else:
458 server_local_path = get_gdbserver_path(root, arch)
459 server_remote_path = "/data/local/tmp/{}-gdbserver".format(
460 arch)
Elliott Hughes89e1ecf2017-06-30 14:03:32 -0700461 gdbrunner.start_gdbserver(
Haibo Huange194fce2020-01-06 14:40:27 -0800462 device, server_local_path, server_remote_path,
Elliott Hughes89e1ecf2017-06-30 14:03:32 -0700463 target_pid=pid, run_cmd=run_cmd, debug_socket=debug_socket,
Haibo Huange194fce2020-01-06 14:40:27 -0800464 port=args.port, run_as_cmd=cmd_prefix, lldb=use_lldb)
Elliott Hughes89e1ecf2017-06-30 14:03:32 -0700465 else:
Haibo Huange194fce2020-01-06 14:40:27 -0800466 print(
467 "Connecting to tracing pid {} using local port {}".format(
468 tracer_pid, args.port))
Elliott Hughes89e1ecf2017-06-30 14:03:32 -0700469 gdbrunner.forward_gdbserver_port(device, local=args.port,
470 remote="tcp:{}".format(args.port))
Josh Gao043bad72015-09-22 11:43:08 -0700471
Haibo Huange194fce2020-01-06 14:40:27 -0800472 if use_lldb:
Haibo Huange4d8bfd2020-07-22 16:37:35 -0700473 debugger_path = get_lldb_path(toolchain_path)
Haibo Huange194fce2020-01-06 14:40:27 -0800474 debugger = 'lldb'
475 else:
476 debugger_path = os.path.join(
477 root, "prebuilts", "gdb", platform_name, "bin", "gdb")
478 debugger = args.setup_forwarding or "gdb"
479
Alex Light92476652019-01-17 11:18:48 -0800480 # Generate a gdb script.
Haibo Huange194fce2020-01-06 14:40:27 -0800481 setup_commands = generate_setup_script(debugger_path=debugger_path,
Alex Light92476652019-01-17 11:18:48 -0800482 sysroot=sysroot,
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -0700483 linker_search_dir=linker_search_dir,
Alex Light92476652019-01-17 11:18:48 -0800484 binary_file=binary_file,
485 is64bit=is64bit,
486 port=args.port,
Haibo Huange194fce2020-01-06 14:40:27 -0800487 debugger=debugger)
Josh Gao043bad72015-09-22 11:43:08 -0700488
Haibo Huange194fce2020-01-06 14:40:27 -0800489 if use_lldb or not args.setup_forwarding:
Alex Light92476652019-01-17 11:18:48 -0800490 # Print a newline to separate our messages from the GDB session.
491 print("")
David Pursell639d1c42015-10-20 15:38:32 -0700492
Alex Light92476652019-01-17 11:18:48 -0800493 # Start gdb.
Haibo Huange194fce2020-01-06 14:40:27 -0800494 gdbrunner.start_gdb(debugger_path, setup_commands, lldb=use_lldb)
Alex Light92476652019-01-17 11:18:48 -0800495 else:
496 print("")
Haibo Huange194fce2020-01-06 14:40:27 -0800497 print(setup_commands)
Alex Light92476652019-01-17 11:18:48 -0800498 print("")
499 if args.setup_forwarding == "vscode":
Haibo Huange194fce2020-01-06 14:40:27 -0800500 print(textwrap.dedent("""
Alex Light92476652019-01-17 11:18:48 -0800501 Paste the above json into .vscode/launch.json and start the debugger as
502 normal. Press enter in this terminal once debugging is finished to shutdown
Haibo Huange194fce2020-01-06 14:40:27 -0800503 the gdbserver and close all the ports."""))
Alex Light92476652019-01-17 11:18:48 -0800504 else:
Haibo Huange194fce2020-01-06 14:40:27 -0800505 print(textwrap.dedent("""
Alex Light92476652019-01-17 11:18:48 -0800506 Paste the above gdb commands into the gdb frontend to setup the gdbserver
507 connection. Press enter in this terminal once debugging is finished to
Haibo Huange194fce2020-01-06 14:40:27 -0800508 shutdown the gdbserver and close all the ports."""))
Alex Light92476652019-01-17 11:18:48 -0800509 print("")
510 raw_input("Press enter to shutdown gdbserver")
Josh Gao043bad72015-09-22 11:43:08 -0700511
Ryan Prichard5d1c3cb2019-06-04 16:35:02 -0700512
513def main():
514 try:
515 do_main()
516 finally:
517 global g_temp_dirs
518 for temp_dir in g_temp_dirs:
519 shutil.rmtree(temp_dir)
520
521
Josh Gao043bad72015-09-22 11:43:08 -0700522if __name__ == "__main__":
523 main()