blob: 2684b06cf2b36b4df812e85ff3ae9e99d9e904ab [file] [log] [blame]
Julius Werner634ccac2014-06-24 13:59:18 -07001# Copyright 2014 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Connect to a DUT in firmware via remote GDB, install custom GDB commands."""
6
7import errno
Raul E Rangeleb8aadc2018-05-17 09:10:27 -06008import glob
Julius Werner634ccac2014-06-24 13:59:18 -07009import os
10import re
Julius Werner634ccac2014-06-24 13:59:18 -070011import socket
12import time
13
Mike Frysinger06a51c82021-04-06 11:39:17 -040014from chromite.lib import build_target_lib
Aviv Keshetb7519e12016-10-04 00:50:00 -070015from chromite.lib import constants
Julius Werner634ccac2014-06-24 13:59:18 -070016from chromite.lib import cros_build_lib
Ralph Nathan91874ca2015-03-19 13:29:41 -070017from chromite.lib import cros_logging as logging
Julius Werner634ccac2014-06-24 13:59:18 -070018from chromite.lib import timeout_util
Mike Frysinger2ec0f122021-05-22 11:22:54 -040019from chromite.third_party.pyelftools.elftools.elf.elffile import ELFFile
Julius Werner634ccac2014-06-24 13:59:18 -070020
Julius Werner634ccac2014-06-24 13:59:18 -070021# Need to do this before Servo import
22cros_build_lib.AssertInsideChroot()
23
Mike Frysinger92bdef52019-08-21 21:05:13 -040024# pylint: disable=import-error,wrong-import-position
Julius Werner634ccac2014-06-24 13:59:18 -070025from servo import client
Ruben Rodriguez Buchillon15bdd452018-10-09 08:31:41 +080026from servo import servo_parsing
Aseda Aboagye6e21d3f2016-10-21 11:37:56 -070027from servo import terminal_freezer
Mike Frysinger92bdef52019-08-21 21:05:13 -040028# pylint: enable=import-error,wrong-import-position
Julius Werner634ccac2014-06-24 13:59:18 -070029
Ralph Nathan91874ca2015-03-19 13:29:41 -070030
Julius Werner634ccac2014-06-24 13:59:18 -070031_SRC_ROOT = os.path.join(constants.CHROOT_SOURCE_ROOT, 'src')
32_SRC_DC = os.path.join(_SRC_ROOT, 'platform/depthcharge')
33_SRC_VB = os.path.join(_SRC_ROOT, 'platform/vboot_reference')
34_SRC_LP = os.path.join(_SRC_ROOT, 'third_party/coreboot/payloads/libpayload')
35
Julius Werner634ccac2014-06-24 13:59:18 -070036_PTRN_GDB = 'Ready for GDB connection'
Julius Werner20dfc992014-07-21 18:40:11 -070037_PTRN_BOARD = 'Starting(?: read-only| read/write)? depthcharge on ([a-z_]+)...'
Julius Werner634ccac2014-06-24 13:59:18 -070038
39
Julius Werner149fe782018-10-10 15:18:14 -070040def GetGdbForElf(elf):
41 """Return the correct C compiler prefix for the target ELF file."""
Mike Frysinger17844a02019-08-24 18:21:02 -040042 with open(elf, 'rb') as fp:
Julius Werner149fe782018-10-10 15:18:14 -070043 return {
44 'EM_386': 'x86_64-cros-linux-gnu-gdb',
45 'EM_X86_64': 'x86_64-cros-linux-gnu-gdb',
46 'EM_ARM': 'armv7a-cros-linux-gnueabihf-gdb',
47 'EM_AARCH64': 'aarch64-cros-linux-gnu-gdb',
Mike Frysinger17844a02019-08-24 18:21:02 -040048 }[ELFFile(fp).header.e_machine]
Julius Werner634ccac2014-06-24 13:59:18 -070049
50
51def ParseArgs(argv):
52 """Parse and validate command line arguments."""
Raul E Rangelb54ec042020-02-06 09:25:12 -070053 description = 'Debug depthcharge using GDB'
54 parser = servo_parsing.ServodClientParser(description=description)
Julius Werner634ccac2014-06-24 13:59:18 -070055 parser.add_argument('-b', '--board',
56 help='The board overlay name (auto-detect by default)')
Raul E Rangel72f32712018-05-29 11:42:59 -060057 parser.add_argument('-c', '--cgdb', action='store_true',
58 help='Use cgdb curses interface rather than plain gdb')
Raul E Rangelb54ec042020-02-06 09:25:12 -070059 parser.add_argument('-y', '--symbols',
Julius Werner634ccac2014-06-24 13:59:18 -070060 help='Root directory or complete path to symbolized ELF '
61 '(defaults to /build/<BOARD>/firmware)')
62 parser.add_argument('-r', '--reboot', choices=['yes', 'no', 'auto'],
63 help='Reboot the DUT before connect (default: reboot if '
64 'the remote and is unreachable)', default='auto')
65 parser.add_argument('-e', '--execute', action='append', default=[],
66 help='GDB command to run after connect (can be supplied '
67 'multiple times)')
Julius Werner634ccac2014-06-24 13:59:18 -070068 parser.add_argument('-t', '--tty',
69 help='TTY file to connect to (defaults to cpu_uart_pty)')
Julius Werner634ccac2014-06-24 13:59:18 -070070 opts = parser.parse_args(argv)
Ruben Rodriguez Buchillond7c65bd2018-12-10 10:10:19 +080071
Julius Werner634ccac2014-06-24 13:59:18 -070072 return opts
73
74
Julius Werner193c9142018-05-09 16:25:38 -070075def FindSymbols(firmware_dir, board):
Julius Werner634ccac2014-06-24 13:59:18 -070076 """Find the symbolized depthcharge ELF (may be supplied by -s flag)."""
Raul E Rangeleb8aadc2018-05-17 09:10:27 -060077
78 # Allow overriding the file directly just in case our detection screws up.
79 if firmware_dir and firmware_dir.endswith('.elf'):
80 return firmware_dir
81
82 if not firmware_dir:
83 # Unified builds have the format
84 # /build/<board|family>/firmware/<build_target|model>/. The board in
85 # depthcharge corresponds to the build_target in unified builds. For this
86 # reason we need to glob all boards to find the correct build_target.
87 unified_build_dirs = glob.glob('/build/*/firmware/%s' % board)
88 if len(unified_build_dirs) == 1:
89 firmware_dir = unified_build_dirs[0]
90 elif len(unified_build_dirs) > 1:
91 raise ValueError(
92 'Multiple boards were found (%s). Use -s to specify manually' %
93 (', '.join(unified_build_dirs)))
94
Julius Werner634ccac2014-06-24 13:59:18 -070095 if not firmware_dir:
Mike Frysinger06a51c82021-04-06 11:39:17 -040096 firmware_dir = os.path.join(
97 build_target_lib.get_default_sysroot_path(board), 'firmware')
Julius Werner634ccac2014-06-24 13:59:18 -070098
Julius Werner193c9142018-05-09 16:25:38 -070099 # Very old firmware you might still find on GoldenEye had dev.ro.elf.
100 basenames = ['dev.elf', 'dev.ro.elf']
101 for basename in basenames:
102 path = os.path.join(firmware_dir, 'depthcharge', basename)
103 if not os.path.exists(path):
104 path = os.path.join(firmware_dir, basename)
105 if os.path.exists(path):
106 logging.warning('Auto-detected symbol file at %s... make sure that this'
107 ' matches the image on your DUT!', path)
108 return path
Julius Werner634ccac2014-06-24 13:59:18 -0700109
Julius Werner193c9142018-05-09 16:25:38 -0700110 raise ValueError('Could not find depthcharge symbol file (dev.elf)! '
111 '(You can use -s to supply it manually.)')
Julius Werner634ccac2014-06-24 13:59:18 -0700112
113
114# TODO(jwerner): Fine tune |wait| delay or maybe even make it configurable if
115# this causes problems due to load on the host. The callers where this is
116# critical should all have their own timeouts now, though, so it's questionable
117# whether the delay here is even needed at all anymore.
118def ReadAll(fd, wait=0.03):
119 """Read from |fd| until no more data has come for at least |wait| seconds."""
120 data = ''
121 try:
122 while True:
123 time.sleep(wait)
Julius Werner193c9142018-05-09 16:25:38 -0700124 new_data = os.read(fd, 4096)
125 if not new_data:
126 break
127 data += new_data
Julius Werner634ccac2014-06-24 13:59:18 -0700128 except OSError as e:
Julius Werner193c9142018-05-09 16:25:38 -0700129 if e.errno != errno.EAGAIN:
130 raise
131 logging.debug(data)
132 return data
Julius Werner634ccac2014-06-24 13:59:18 -0700133
134
135def GdbChecksum(message):
136 """Calculate a remote-GDB style checksum."""
137 chksum = sum([ord(x) for x in message])
138 return ('%.2x' % chksum)[-2:]
139
140
141def TestConnection(fd):
142 """Return True iff there is a resposive GDB stub on the other end of 'fd'."""
143 cmd = 'vUnknownCommand'
Mike Frysinger79cca962019-06-13 15:26:53 -0400144 for _ in range(3):
Julius Werner634ccac2014-06-24 13:59:18 -0700145 os.write(fd, '$%s#%s\n' % (cmd, GdbChecksum(cmd)))
146 reply = ReadAll(fd)
147 if '+$#00' in reply:
148 os.write(fd, '+')
Mike Frysinger2403af42015-04-30 06:25:03 -0400149 logging.info('TestConnection: Could successfully connect to remote end.')
Julius Werner634ccac2014-06-24 13:59:18 -0700150 return True
Mike Frysinger2403af42015-04-30 06:25:03 -0400151 logging.info('TestConnection: Remote end does not respond.')
Julius Werner634ccac2014-06-24 13:59:18 -0700152 return False
153
154
155def main(argv):
156 opts = ParseArgs(argv)
Raul E Rangelb54ec042020-02-06 09:25:12 -0700157 servo = client.ServoClient(host=opts.host, port=opts.port)
Julius Werner634ccac2014-06-24 13:59:18 -0700158
159 if not opts.tty:
160 try:
161 opts.tty = servo.get('cpu_uart_pty')
162 except (client.ServoClientError, socket.error):
Mike Frysinger2403af42015-04-30 06:25:03 -0400163 logging.error('Cannot auto-detect TTY file without servod. Use the --tty '
164 'option.')
Julius Werner634ccac2014-06-24 13:59:18 -0700165 raise
Aseda Aboagye6e21d3f2016-10-21 11:37:56 -0700166 with terminal_freezer.TerminalFreezer(opts.tty):
Julius Werner634ccac2014-06-24 13:59:18 -0700167 fd = os.open(opts.tty, os.O_RDWR | os.O_NONBLOCK)
168
169 data = ReadAll(fd)
170 if opts.reboot == 'auto':
171 if TestConnection(fd):
172 opts.reboot = 'no'
173 else:
174 opts.reboot = 'yes'
175
176 if opts.reboot == 'yes':
Mike Frysinger2403af42015-04-30 06:25:03 -0400177 logging.info('Rebooting DUT...')
Julius Werner634ccac2014-06-24 13:59:18 -0700178 try:
179 servo.set('warm_reset', 'on')
180 time.sleep(0.1)
181 servo.set('warm_reset', 'off')
182 except (client.ServoClientError, socket.error):
Mike Frysinger2403af42015-04-30 06:25:03 -0400183 logging.error('Cannot reboot without a Servo board. You have to boot '
184 'into developer mode and press CTRL+G manually before '
185 'running fwgdb.')
Julius Werner634ccac2014-06-24 13:59:18 -0700186 raise
187
188 # Throw away old data to avoid confusion from messages before the reboot
189 data = ''
Julius Werner193c9142018-05-09 16:25:38 -0700190 msg = ('Could not reboot into depthcharge!')
Mike Frysingerd6e2df02014-11-26 02:55:04 -0500191 with timeout_util.Timeout(10, msg):
Julius Werner193c9142018-05-09 16:25:38 -0700192 while not re.search(_PTRN_BOARD, data):
Julius Werner634ccac2014-06-24 13:59:18 -0700193 data += ReadAll(fd)
194
Mike Frysingerd6e2df02014-11-26 02:55:04 -0500195 msg = ('Could not enter GDB mode with CTRL+G! '
Julius Werner193c9142018-05-09 16:25:38 -0700196 '(Confirm that you flashed an "image.dev.bin" image to this DUT, '
197 'and that you have GBB_FLAG_FORCE_DEV_SWITCH_ON (0x8) set.)')
198 with timeout_util.Timeout(5, msg):
199 while not re.search(_PTRN_GDB, data):
200 # Send a CTRL+G to tell depthcharge to trap into GDB.
201 logging.debug('[Ctrl+G]')
202 os.write(fd, chr(ord('G') & 0x1f))
Julius Werner634ccac2014-06-24 13:59:18 -0700203 data += ReadAll(fd)
204
205 if not opts.board:
206 matches = re.findall(_PTRN_BOARD, data)
207 if not matches:
208 raise ValueError('Could not auto-detect board! Please use -b option.')
209 opts.board = matches[-1]
Mike Frysinger2403af42015-04-30 06:25:03 -0400210 logging.info('Auto-detected board as %s from DUT console output.',
211 opts.board)
Julius Werner634ccac2014-06-24 13:59:18 -0700212
213 if not TestConnection(fd):
214 raise IOError('Could not connect to remote end! Confirm that your DUT is '
215 'running in GDB mode on %s.' % opts.tty)
216
217 # Eat up leftover data or it will spill back to terminal
218 ReadAll(fd)
219 os.close(fd)
220
221 opts.execute.insert(0, 'target remote %s' % opts.tty)
222 ex_args = sum([['--ex', cmd] for cmd in opts.execute], [])
223
Julius Werner149fe782018-10-10 15:18:14 -0700224 elf = FindSymbols(opts.symbols, opts.board)
225 gdb_cmd = GetGdbForElf(elf)
Raul E Rangel72f32712018-05-29 11:42:59 -0600226
Raul E Rangel72f32712018-05-29 11:42:59 -0600227 gdb_args = [
Julius Werner149fe782018-10-10 15:18:14 -0700228 '--symbols', elf,
Raul E Rangel72f32712018-05-29 11:42:59 -0600229 '--directory', _SRC_DC,
230 '--directory', _SRC_VB,
231 '--directory', _SRC_LP,
232 ] + ex_args
233
234 if opts.cgdb:
235 full_cmd = ['cgdb', '-d', gdb_cmd, '--'] + gdb_args
236 else:
237 full_cmd = [gdb_cmd] + gdb_args
238
Julius Werner149fe782018-10-10 15:18:14 -0700239 logging.info('Launching GDB...')
Mike Frysinger45602c72019-09-22 02:15:11 -0400240 cros_build_lib.run(
Raul E Rangel72f32712018-05-29 11:42:59 -0600241 full_cmd, ignore_sigint=True, debug_level=logging.WARNING)