blob: 7d78078ba8abc9ae205d0c4548bef7a13ed22274 [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
Julius Werner634ccac2014-06-24 13:59:18 -070011import os
12import re
Julius Werner634ccac2014-06-24 13:59:18 -070013import socket
14import time
15
Aviv Keshetb7519e12016-10-04 00:50:00 -070016from chromite.lib import constants
Julius Werner634ccac2014-06-24 13:59:18 -070017from chromite.lib import commandline
18from chromite.lib import cros_build_lib
Ralph Nathan91874ca2015-03-19 13:29:41 -070019from chromite.lib import cros_logging as logging
Julius Werner634ccac2014-06-24 13:59:18 -070020from chromite.lib import timeout_util
21
Julius Werner634ccac2014-06-24 13:59:18 -070022# Need to do this before Servo import
23cros_build_lib.AssertInsideChroot()
24
Mike Frysinger61ef29a2014-12-17 02:05:27 -050025# pylint: disable=import-error
Julius Werner634ccac2014-06-24 13:59:18 -070026from servo import client
27from servo import multiservo
Aseda Aboagye6e21d3f2016-10-21 11:37:56 -070028from servo import terminal_freezer
Mike Frysinger61ef29a2014-12-17 02:05:27 -050029# pylint: enable=import-error
Julius Werner634ccac2014-06-24 13:59:18 -070030
Ralph Nathan91874ca2015-03-19 13:29:41 -070031
Julius Werner634ccac2014-06-24 13:59:18 -070032_SRC_ROOT = os.path.join(constants.CHROOT_SOURCE_ROOT, 'src')
33_SRC_DC = os.path.join(_SRC_ROOT, 'platform/depthcharge')
34_SRC_VB = os.path.join(_SRC_ROOT, 'platform/vboot_reference')
35_SRC_LP = os.path.join(_SRC_ROOT, 'third_party/coreboot/payloads/libpayload')
36
Julius Werner634ccac2014-06-24 13:59:18 -070037_PTRN_GDB = 'Ready for GDB connection'
Julius Werner20dfc992014-07-21 18:40:11 -070038_PTRN_BOARD = 'Starting(?: read-only| read/write)? depthcharge on ([a-z_]+)...'
Julius Werner634ccac2014-06-24 13:59:18 -070039
40
Julius Werner634ccac2014-06-24 13:59:18 -070041def ParsePortage(board):
42 """Parse some data from portage files. equery takes ages in comparison."""
43 with open(os.path.join('/build', board, 'packages/Packages'), 'r') as f:
Julius Werner634ccac2014-06-24 13:59:18 -070044 for line in f:
45 if line[:7] == 'CHOST: ':
Julius Werner193c9142018-05-09 16:25:38 -070046 return line[7:].strip()
Julius Werner634ccac2014-06-24 13:59:18 -070047
48
49def ParseArgs(argv):
50 """Parse and validate command line arguments."""
51 parser = commandline.ArgumentParser(default_log_level='warning')
52
53 parser.add_argument('-b', '--board',
54 help='The board overlay name (auto-detect by default)')
Raul E Rangel72f32712018-05-29 11:42:59 -060055 parser.add_argument('-c', '--cgdb', action='store_true',
56 help='Use cgdb curses interface rather than plain gdb')
Julius Werner634ccac2014-06-24 13:59:18 -070057 parser.add_argument('-s', '--symbols',
58 help='Root directory or complete path to symbolized ELF '
59 '(defaults to /build/<BOARD>/firmware)')
60 parser.add_argument('-r', '--reboot', choices=['yes', 'no', 'auto'],
61 help='Reboot the DUT before connect (default: reboot if '
62 'the remote and is unreachable)', default='auto')
63 parser.add_argument('-e', '--execute', action='append', default=[],
64 help='GDB command to run after connect (can be supplied '
65 'multiple times)')
66
67 parser.add_argument('-n', '--servod-name', dest='name')
68 parser.add_argument('--servod-rcfile', default=multiservo.DEFAULT_RC_FILE)
69 parser.add_argument('--servod-server')
70 parser.add_argument('-p', '--servod-port', type=int, dest='port')
71 parser.add_argument('-t', '--tty',
72 help='TTY file to connect to (defaults to cpu_uart_pty)')
73
74 opts = parser.parse_args(argv)
75 multiservo.get_env_options(logging, opts)
76 if opts.name:
77 rc = multiservo.parse_rc(logging, opts.servod_rcfile)
78 if opts.name not in rc:
79 raise parser.error('%s not in %s' % (opts.name, opts.servod_rcfile))
80 if not opts.servod_server:
81 opts.servod_server = rc[opts.name]['sn']
82 if not opts.port:
83 opts.port = rc[opts.name].get('port', client.DEFAULT_PORT)
84 if not opts.board and 'board' in rc[opts.name]:
85 opts.board = rc[opts.name]['board']
Bertrand SIMONNET0ddf7762015-05-20 14:38:00 -070086 logging.warning('Inferring board %s from %s; make sure this is correct!',
87 opts.board, opts.servod_rcfile)
Julius Werner634ccac2014-06-24 13:59:18 -070088
89 if not opts.servod_server:
90 opts.servod_server = client.DEFAULT_HOST
91 if not opts.port:
92 opts.port = client.DEFAULT_PORT
93
94 return opts
95
96
Julius Werner193c9142018-05-09 16:25:38 -070097def FindSymbols(firmware_dir, board):
Julius Werner634ccac2014-06-24 13:59:18 -070098 """Find the symbolized depthcharge ELF (may be supplied by -s flag)."""
99 if not firmware_dir:
100 firmware_dir = os.path.join(cros_build_lib.GetSysroot(board), 'firmware')
101 # Allow overriding the file directly just in case our detection screws up
102 if firmware_dir.endswith('.elf'):
103 return firmware_dir
104
Julius Werner193c9142018-05-09 16:25:38 -0700105 # Very old firmware you might still find on GoldenEye had dev.ro.elf.
106 basenames = ['dev.elf', 'dev.ro.elf']
107 for basename in basenames:
108 path = os.path.join(firmware_dir, 'depthcharge', basename)
109 if not os.path.exists(path):
110 path = os.path.join(firmware_dir, basename)
111 if os.path.exists(path):
112 logging.warning('Auto-detected symbol file at %s... make sure that this'
113 ' matches the image on your DUT!', path)
114 return path
Julius Werner634ccac2014-06-24 13:59:18 -0700115
Julius Werner193c9142018-05-09 16:25:38 -0700116 raise ValueError('Could not find depthcharge symbol file (dev.elf)! '
117 '(You can use -s to supply it manually.)')
Julius Werner634ccac2014-06-24 13:59:18 -0700118
119
120# TODO(jwerner): Fine tune |wait| delay or maybe even make it configurable if
121# this causes problems due to load on the host. The callers where this is
122# critical should all have their own timeouts now, though, so it's questionable
123# whether the delay here is even needed at all anymore.
124def ReadAll(fd, wait=0.03):
125 """Read from |fd| until no more data has come for at least |wait| seconds."""
126 data = ''
127 try:
128 while True:
129 time.sleep(wait)
Julius Werner193c9142018-05-09 16:25:38 -0700130 new_data = os.read(fd, 4096)
131 if not new_data:
132 break
133 data += new_data
Julius Werner634ccac2014-06-24 13:59:18 -0700134 except OSError as e:
Julius Werner193c9142018-05-09 16:25:38 -0700135 if e.errno != errno.EAGAIN:
136 raise
137 logging.debug(data)
138 return data
Julius Werner634ccac2014-06-24 13:59:18 -0700139
140
141def GdbChecksum(message):
142 """Calculate a remote-GDB style checksum."""
143 chksum = sum([ord(x) for x in message])
144 return ('%.2x' % chksum)[-2:]
145
146
147def TestConnection(fd):
148 """Return True iff there is a resposive GDB stub on the other end of 'fd'."""
149 cmd = 'vUnknownCommand'
150 for _ in xrange(3):
151 os.write(fd, '$%s#%s\n' % (cmd, GdbChecksum(cmd)))
152 reply = ReadAll(fd)
153 if '+$#00' in reply:
154 os.write(fd, '+')
Mike Frysinger2403af42015-04-30 06:25:03 -0400155 logging.info('TestConnection: Could successfully connect to remote end.')
Julius Werner634ccac2014-06-24 13:59:18 -0700156 return True
Mike Frysinger2403af42015-04-30 06:25:03 -0400157 logging.info('TestConnection: Remote end does not respond.')
Julius Werner634ccac2014-06-24 13:59:18 -0700158 return False
159
160
161def main(argv):
162 opts = ParseArgs(argv)
163 servo = client.ServoClient(host=opts.servod_server, port=opts.port)
164
165 if not opts.tty:
166 try:
167 opts.tty = servo.get('cpu_uart_pty')
168 except (client.ServoClientError, socket.error):
Mike Frysinger2403af42015-04-30 06:25:03 -0400169 logging.error('Cannot auto-detect TTY file without servod. Use the --tty '
170 'option.')
Julius Werner634ccac2014-06-24 13:59:18 -0700171 raise
Aseda Aboagye6e21d3f2016-10-21 11:37:56 -0700172 with terminal_freezer.TerminalFreezer(opts.tty):
Julius Werner634ccac2014-06-24 13:59:18 -0700173 fd = os.open(opts.tty, os.O_RDWR | os.O_NONBLOCK)
174
175 data = ReadAll(fd)
176 if opts.reboot == 'auto':
177 if TestConnection(fd):
178 opts.reboot = 'no'
179 else:
180 opts.reboot = 'yes'
181
182 if opts.reboot == 'yes':
Mike Frysinger2403af42015-04-30 06:25:03 -0400183 logging.info('Rebooting DUT...')
Julius Werner634ccac2014-06-24 13:59:18 -0700184 try:
185 servo.set('warm_reset', 'on')
186 time.sleep(0.1)
187 servo.set('warm_reset', 'off')
188 except (client.ServoClientError, socket.error):
Mike Frysinger2403af42015-04-30 06:25:03 -0400189 logging.error('Cannot reboot without a Servo board. You have to boot '
190 'into developer mode and press CTRL+G manually before '
191 'running fwgdb.')
Julius Werner634ccac2014-06-24 13:59:18 -0700192 raise
193
194 # Throw away old data to avoid confusion from messages before the reboot
195 data = ''
Julius Werner193c9142018-05-09 16:25:38 -0700196 msg = ('Could not reboot into depthcharge!')
Mike Frysingerd6e2df02014-11-26 02:55:04 -0500197 with timeout_util.Timeout(10, msg):
Julius Werner193c9142018-05-09 16:25:38 -0700198 while not re.search(_PTRN_BOARD, data):
Julius Werner634ccac2014-06-24 13:59:18 -0700199 data += ReadAll(fd)
200
Mike Frysingerd6e2df02014-11-26 02:55:04 -0500201 msg = ('Could not enter GDB mode with CTRL+G! '
Julius Werner193c9142018-05-09 16:25:38 -0700202 '(Confirm that you flashed an "image.dev.bin" image to this DUT, '
203 'and that you have GBB_FLAG_FORCE_DEV_SWITCH_ON (0x8) set.)')
204 with timeout_util.Timeout(5, msg):
205 while not re.search(_PTRN_GDB, data):
206 # Send a CTRL+G to tell depthcharge to trap into GDB.
207 logging.debug('[Ctrl+G]')
208 os.write(fd, chr(ord('G') & 0x1f))
Julius Werner634ccac2014-06-24 13:59:18 -0700209 data += ReadAll(fd)
210
211 if not opts.board:
212 matches = re.findall(_PTRN_BOARD, data)
213 if not matches:
214 raise ValueError('Could not auto-detect board! Please use -b option.')
215 opts.board = matches[-1]
Mike Frysinger2403af42015-04-30 06:25:03 -0400216 logging.info('Auto-detected board as %s from DUT console output.',
217 opts.board)
Julius Werner634ccac2014-06-24 13:59:18 -0700218
219 if not TestConnection(fd):
220 raise IOError('Could not connect to remote end! Confirm that your DUT is '
221 'running in GDB mode on %s.' % opts.tty)
222
223 # Eat up leftover data or it will spill back to terminal
224 ReadAll(fd)
225 os.close(fd)
226
227 opts.execute.insert(0, 'target remote %s' % opts.tty)
228 ex_args = sum([['--ex', cmd] for cmd in opts.execute], [])
229
Julius Werner193c9142018-05-09 16:25:38 -0700230 chost = ParsePortage(opts.board)
Mike Frysinger2403af42015-04-30 06:25:03 -0400231 logging.info('Launching GDB...')
Raul E Rangel72f32712018-05-29 11:42:59 -0600232
233 gdb_cmd = chost + '-gdb'
234 gdb_args = [
235 '--symbols', FindSymbols(opts.symbols, opts.board),
236 '--directory', _SRC_DC,
237 '--directory', _SRC_VB,
238 '--directory', _SRC_LP,
239 ] + ex_args
240
241 if opts.cgdb:
242 full_cmd = ['cgdb', '-d', gdb_cmd, '--'] + gdb_args
243 else:
244 full_cmd = [gdb_cmd] + gdb_args
245
Mike Frysingerd6e2df02014-11-26 02:55:04 -0500246 cros_build_lib.RunCommand(
Raul E Rangel72f32712018-05-29 11:42:59 -0600247 full_cmd, ignore_sigint=True, debug_level=logging.WARNING)