blob: d8459bd830583ebf5564fba4037bdaaa6eaabd06 [file] [log] [blame]
Mike Frysingere58c0e22017-10-04 15:43:30 -04001# -*- coding: utf-8 -*-
Julius Werner634ccac2014-06-24 13:59:18 -07002# Copyright 2014 The Chromium OS Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Connect to a DUT in firmware via remote GDB, install custom GDB commands."""
7
Mike Frysinger383367e2014-09-16 15:06:17 -04008from __future__ import print_function
9
Julius Werner634ccac2014-06-24 13:59:18 -070010import errno
Raul E Rangeleb8aadc2018-05-17 09:10:27 -060011import glob
Julius Werner634ccac2014-06-24 13:59:18 -070012import os
13import re
Julius Werner634ccac2014-06-24 13:59:18 -070014import socket
15import time
16
Mike Frysinger849d6402019-10-17 00:14:16 -040017from elftools.elf.elffile import ELFFile
18
Aviv Keshetb7519e12016-10-04 00:50:00 -070019from chromite.lib import constants
Julius Werner634ccac2014-06-24 13:59:18 -070020from chromite.lib import commandline
21from chromite.lib import cros_build_lib
Ralph Nathan91874ca2015-03-19 13:29:41 -070022from chromite.lib import cros_logging as logging
Julius Werner634ccac2014-06-24 13:59:18 -070023from chromite.lib import timeout_util
24
Julius Werner634ccac2014-06-24 13:59:18 -070025# Need to do this before Servo import
26cros_build_lib.AssertInsideChroot()
27
Mike Frysinger92bdef52019-08-21 21:05:13 -040028# pylint: disable=import-error,wrong-import-position
Julius Werner634ccac2014-06-24 13:59:18 -070029from servo import client
Ruben Rodriguez Buchillon15bdd452018-10-09 08:31:41 +080030from servo import servo_parsing
Aseda Aboagye6e21d3f2016-10-21 11:37:56 -070031from servo import terminal_freezer
Mike Frysinger92bdef52019-08-21 21:05:13 -040032# pylint: enable=import-error,wrong-import-position
Julius Werner634ccac2014-06-24 13:59:18 -070033
Ralph Nathan91874ca2015-03-19 13:29:41 -070034
Julius Werner634ccac2014-06-24 13:59:18 -070035_SRC_ROOT = os.path.join(constants.CHROOT_SOURCE_ROOT, 'src')
36_SRC_DC = os.path.join(_SRC_ROOT, 'platform/depthcharge')
37_SRC_VB = os.path.join(_SRC_ROOT, 'platform/vboot_reference')
38_SRC_LP = os.path.join(_SRC_ROOT, 'third_party/coreboot/payloads/libpayload')
39
Julius Werner634ccac2014-06-24 13:59:18 -070040_PTRN_GDB = 'Ready for GDB connection'
Julius Werner20dfc992014-07-21 18:40:11 -070041_PTRN_BOARD = 'Starting(?: read-only| read/write)? depthcharge on ([a-z_]+)...'
Julius Werner634ccac2014-06-24 13:59:18 -070042
43
Julius Werner149fe782018-10-10 15:18:14 -070044def GetGdbForElf(elf):
45 """Return the correct C compiler prefix for the target ELF file."""
Mike Frysinger17844a02019-08-24 18:21:02 -040046 with open(elf, 'rb') as fp:
Julius Werner149fe782018-10-10 15:18:14 -070047 return {
48 'EM_386': 'x86_64-cros-linux-gnu-gdb',
49 'EM_X86_64': 'x86_64-cros-linux-gnu-gdb',
50 'EM_ARM': 'armv7a-cros-linux-gnueabihf-gdb',
51 'EM_AARCH64': 'aarch64-cros-linux-gnu-gdb',
Mike Frysinger17844a02019-08-24 18:21:02 -040052 }[ELFFile(fp).header.e_machine]
Julius Werner634ccac2014-06-24 13:59:18 -070053
54
55def ParseArgs(argv):
56 """Parse and validate command line arguments."""
57 parser = commandline.ArgumentParser(default_log_level='warning')
58
59 parser.add_argument('-b', '--board',
60 help='The board overlay name (auto-detect by default)')
Raul E Rangel72f32712018-05-29 11:42:59 -060061 parser.add_argument('-c', '--cgdb', action='store_true',
62 help='Use cgdb curses interface rather than plain gdb')
Julius Werner634ccac2014-06-24 13:59:18 -070063 parser.add_argument('-s', '--symbols',
64 help='Root directory or complete path to symbolized ELF '
65 '(defaults to /build/<BOARD>/firmware)')
66 parser.add_argument('-r', '--reboot', choices=['yes', 'no', 'auto'],
67 help='Reboot the DUT before connect (default: reboot if '
68 'the remote and is unreachable)', default='auto')
69 parser.add_argument('-e', '--execute', action='append', default=[],
70 help='GDB command to run after connect (can be supplied '
71 'multiple times)')
Ruben Rodriguez Buchillon483426c2018-12-10 10:10:34 +080072 parser.add_argument('--servod-rcfile', default=servo_parsing.DEFAULT_RC_FILE,
73 dest='rcfile')
Julius Werner634ccac2014-06-24 13:59:18 -070074 parser.add_argument('--servod-server')
Ruben Rodriguez Buchillon483426c2018-12-10 10:10:34 +080075 # Add --name for rc servod configuration.
76 servo_parsing.ServodRCParser.AddRCEnabledNameArg(parser)
77 # Add |port_flags| as the port arguments.
Ruben Rodriguez Buchillond7c65bd2018-12-10 10:10:19 +080078 port_flags = ['-p', '--servod-port']
Ruben Rodriguez Buchillon483426c2018-12-10 10:10:34 +080079 servo_parsing.BaseServodParser.AddRCEnabledPortArg(parser,
80 port_flags=port_flags)
Julius Werner634ccac2014-06-24 13:59:18 -070081 parser.add_argument('-t', '--tty',
82 help='TTY file to connect to (defaults to cpu_uart_pty)')
Julius Werner634ccac2014-06-24 13:59:18 -070083 opts = parser.parse_args(argv)
Ruben Rodriguez Buchillond7c65bd2018-12-10 10:10:19 +080084
85 # Set |.port| and |.board| in |opts| if there's a rc match for opts.name.
Ruben Rodriguez Buchillon483426c2018-12-10 10:10:34 +080086 servo_parsing.ServodRCParser.PostProcessRCElements(opts)
Julius Werner634ccac2014-06-24 13:59:18 -070087
88 if not opts.servod_server:
89 opts.servod_server = client.DEFAULT_HOST
90 if not opts.port:
91 opts.port = client.DEFAULT_PORT
92
93 return opts
94
95
Julius Werner193c9142018-05-09 16:25:38 -070096def FindSymbols(firmware_dir, board):
Julius Werner634ccac2014-06-24 13:59:18 -070097 """Find the symbolized depthcharge ELF (may be supplied by -s flag)."""
Raul E Rangeleb8aadc2018-05-17 09:10:27 -060098
99 # Allow overriding the file directly just in case our detection screws up.
100 if firmware_dir and firmware_dir.endswith('.elf'):
101 return firmware_dir
102
103 if not firmware_dir:
104 # Unified builds have the format
105 # /build/<board|family>/firmware/<build_target|model>/. The board in
106 # depthcharge corresponds to the build_target in unified builds. For this
107 # reason we need to glob all boards to find the correct build_target.
108 unified_build_dirs = glob.glob('/build/*/firmware/%s' % board)
109 if len(unified_build_dirs) == 1:
110 firmware_dir = unified_build_dirs[0]
111 elif len(unified_build_dirs) > 1:
112 raise ValueError(
113 'Multiple boards were found (%s). Use -s to specify manually' %
114 (', '.join(unified_build_dirs)))
115
Julius Werner634ccac2014-06-24 13:59:18 -0700116 if not firmware_dir:
117 firmware_dir = os.path.join(cros_build_lib.GetSysroot(board), 'firmware')
Julius Werner634ccac2014-06-24 13:59:18 -0700118
Julius Werner193c9142018-05-09 16:25:38 -0700119 # Very old firmware you might still find on GoldenEye had dev.ro.elf.
120 basenames = ['dev.elf', 'dev.ro.elf']
121 for basename in basenames:
122 path = os.path.join(firmware_dir, 'depthcharge', basename)
123 if not os.path.exists(path):
124 path = os.path.join(firmware_dir, basename)
125 if os.path.exists(path):
126 logging.warning('Auto-detected symbol file at %s... make sure that this'
127 ' matches the image on your DUT!', path)
128 return path
Julius Werner634ccac2014-06-24 13:59:18 -0700129
Julius Werner193c9142018-05-09 16:25:38 -0700130 raise ValueError('Could not find depthcharge symbol file (dev.elf)! '
131 '(You can use -s to supply it manually.)')
Julius Werner634ccac2014-06-24 13:59:18 -0700132
133
134# TODO(jwerner): Fine tune |wait| delay or maybe even make it configurable if
135# this causes problems due to load on the host. The callers where this is
136# critical should all have their own timeouts now, though, so it's questionable
137# whether the delay here is even needed at all anymore.
138def ReadAll(fd, wait=0.03):
139 """Read from |fd| until no more data has come for at least |wait| seconds."""
140 data = ''
141 try:
142 while True:
143 time.sleep(wait)
Julius Werner193c9142018-05-09 16:25:38 -0700144 new_data = os.read(fd, 4096)
145 if not new_data:
146 break
147 data += new_data
Julius Werner634ccac2014-06-24 13:59:18 -0700148 except OSError as e:
Julius Werner193c9142018-05-09 16:25:38 -0700149 if e.errno != errno.EAGAIN:
150 raise
151 logging.debug(data)
152 return data
Julius Werner634ccac2014-06-24 13:59:18 -0700153
154
155def GdbChecksum(message):
156 """Calculate a remote-GDB style checksum."""
157 chksum = sum([ord(x) for x in message])
158 return ('%.2x' % chksum)[-2:]
159
160
161def TestConnection(fd):
162 """Return True iff there is a resposive GDB stub on the other end of 'fd'."""
163 cmd = 'vUnknownCommand'
Mike Frysinger79cca962019-06-13 15:26:53 -0400164 for _ in range(3):
Julius Werner634ccac2014-06-24 13:59:18 -0700165 os.write(fd, '$%s#%s\n' % (cmd, GdbChecksum(cmd)))
166 reply = ReadAll(fd)
167 if '+$#00' in reply:
168 os.write(fd, '+')
Mike Frysinger2403af42015-04-30 06:25:03 -0400169 logging.info('TestConnection: Could successfully connect to remote end.')
Julius Werner634ccac2014-06-24 13:59:18 -0700170 return True
Mike Frysinger2403af42015-04-30 06:25:03 -0400171 logging.info('TestConnection: Remote end does not respond.')
Julius Werner634ccac2014-06-24 13:59:18 -0700172 return False
173
174
175def main(argv):
176 opts = ParseArgs(argv)
177 servo = client.ServoClient(host=opts.servod_server, port=opts.port)
178
179 if not opts.tty:
180 try:
181 opts.tty = servo.get('cpu_uart_pty')
182 except (client.ServoClientError, socket.error):
Mike Frysinger2403af42015-04-30 06:25:03 -0400183 logging.error('Cannot auto-detect TTY file without servod. Use the --tty '
184 'option.')
Julius Werner634ccac2014-06-24 13:59:18 -0700185 raise
Aseda Aboagye6e21d3f2016-10-21 11:37:56 -0700186 with terminal_freezer.TerminalFreezer(opts.tty):
Julius Werner634ccac2014-06-24 13:59:18 -0700187 fd = os.open(opts.tty, os.O_RDWR | os.O_NONBLOCK)
188
189 data = ReadAll(fd)
190 if opts.reboot == 'auto':
191 if TestConnection(fd):
192 opts.reboot = 'no'
193 else:
194 opts.reboot = 'yes'
195
196 if opts.reboot == 'yes':
Mike Frysinger2403af42015-04-30 06:25:03 -0400197 logging.info('Rebooting DUT...')
Julius Werner634ccac2014-06-24 13:59:18 -0700198 try:
199 servo.set('warm_reset', 'on')
200 time.sleep(0.1)
201 servo.set('warm_reset', 'off')
202 except (client.ServoClientError, socket.error):
Mike Frysinger2403af42015-04-30 06:25:03 -0400203 logging.error('Cannot reboot without a Servo board. You have to boot '
204 'into developer mode and press CTRL+G manually before '
205 'running fwgdb.')
Julius Werner634ccac2014-06-24 13:59:18 -0700206 raise
207
208 # Throw away old data to avoid confusion from messages before the reboot
209 data = ''
Julius Werner193c9142018-05-09 16:25:38 -0700210 msg = ('Could not reboot into depthcharge!')
Mike Frysingerd6e2df02014-11-26 02:55:04 -0500211 with timeout_util.Timeout(10, msg):
Julius Werner193c9142018-05-09 16:25:38 -0700212 while not re.search(_PTRN_BOARD, data):
Julius Werner634ccac2014-06-24 13:59:18 -0700213 data += ReadAll(fd)
214
Mike Frysingerd6e2df02014-11-26 02:55:04 -0500215 msg = ('Could not enter GDB mode with CTRL+G! '
Julius Werner193c9142018-05-09 16:25:38 -0700216 '(Confirm that you flashed an "image.dev.bin" image to this DUT, '
217 'and that you have GBB_FLAG_FORCE_DEV_SWITCH_ON (0x8) set.)')
218 with timeout_util.Timeout(5, msg):
219 while not re.search(_PTRN_GDB, data):
220 # Send a CTRL+G to tell depthcharge to trap into GDB.
221 logging.debug('[Ctrl+G]')
222 os.write(fd, chr(ord('G') & 0x1f))
Julius Werner634ccac2014-06-24 13:59:18 -0700223 data += ReadAll(fd)
224
225 if not opts.board:
226 matches = re.findall(_PTRN_BOARD, data)
227 if not matches:
228 raise ValueError('Could not auto-detect board! Please use -b option.')
229 opts.board = matches[-1]
Mike Frysinger2403af42015-04-30 06:25:03 -0400230 logging.info('Auto-detected board as %s from DUT console output.',
231 opts.board)
Julius Werner634ccac2014-06-24 13:59:18 -0700232
233 if not TestConnection(fd):
234 raise IOError('Could not connect to remote end! Confirm that your DUT is '
235 'running in GDB mode on %s.' % opts.tty)
236
237 # Eat up leftover data or it will spill back to terminal
238 ReadAll(fd)
239 os.close(fd)
240
241 opts.execute.insert(0, 'target remote %s' % opts.tty)
242 ex_args = sum([['--ex', cmd] for cmd in opts.execute], [])
243
Julius Werner149fe782018-10-10 15:18:14 -0700244 elf = FindSymbols(opts.symbols, opts.board)
245 gdb_cmd = GetGdbForElf(elf)
Raul E Rangel72f32712018-05-29 11:42:59 -0600246
Raul E Rangel72f32712018-05-29 11:42:59 -0600247 gdb_args = [
Julius Werner149fe782018-10-10 15:18:14 -0700248 '--symbols', elf,
Raul E Rangel72f32712018-05-29 11:42:59 -0600249 '--directory', _SRC_DC,
250 '--directory', _SRC_VB,
251 '--directory', _SRC_LP,
252 ] + ex_args
253
254 if opts.cgdb:
255 full_cmd = ['cgdb', '-d', gdb_cmd, '--'] + gdb_args
256 else:
257 full_cmd = [gdb_cmd] + gdb_args
258
Julius Werner149fe782018-10-10 15:18:14 -0700259 logging.info('Launching GDB...')
Mike Frysinger45602c72019-09-22 02:15:11 -0400260 cros_build_lib.run(
Raul E Rangel72f32712018-05-29 11:42:59 -0600261 full_cmd, ignore_sigint=True, debug_level=logging.WARNING)