blob: fd938c0431e1f341f7699280774a5d81ec85aebf [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
37_PTRN_DEVMODE = 'Entering VbBootDeveloper()'
38_PTRN_GDB = 'Ready for GDB connection'
Julius Werner20dfc992014-07-21 18:40:11 -070039_PTRN_BOARD = 'Starting(?: read-only| read/write)? depthcharge on ([a-z_]+)...'
Julius Werner634ccac2014-06-24 13:59:18 -070040
41
Julius Werner634ccac2014-06-24 13:59:18 -070042def ParsePortage(board):
43 """Parse some data from portage files. equery takes ages in comparison."""
44 with open(os.path.join('/build', board, 'packages/Packages'), 'r') as f:
45 chost = None
46 use = None
47 for line in f:
48 if line[:7] == 'CHOST: ':
49 chost = line[7:].strip()
50 if line[:5] == 'USE: ':
51 use = line[5:].strip()
52 if chost and use:
53 return (chost, use)
54
55
56def ParseArgs(argv):
57 """Parse and validate command line arguments."""
58 parser = commandline.ArgumentParser(default_log_level='warning')
59
60 parser.add_argument('-b', '--board',
61 help='The board overlay name (auto-detect by default)')
62 parser.add_argument('-s', '--symbols',
63 help='Root directory or complete path to symbolized ELF '
64 '(defaults to /build/<BOARD>/firmware)')
65 parser.add_argument('-r', '--reboot', choices=['yes', 'no', 'auto'],
66 help='Reboot the DUT before connect (default: reboot if '
67 'the remote and is unreachable)', default='auto')
68 parser.add_argument('-e', '--execute', action='append', default=[],
69 help='GDB command to run after connect (can be supplied '
70 'multiple times)')
71
72 parser.add_argument('-n', '--servod-name', dest='name')
73 parser.add_argument('--servod-rcfile', default=multiservo.DEFAULT_RC_FILE)
74 parser.add_argument('--servod-server')
75 parser.add_argument('-p', '--servod-port', type=int, dest='port')
76 parser.add_argument('-t', '--tty',
77 help='TTY file to connect to (defaults to cpu_uart_pty)')
78
79 opts = parser.parse_args(argv)
80 multiservo.get_env_options(logging, opts)
81 if opts.name:
82 rc = multiservo.parse_rc(logging, opts.servod_rcfile)
83 if opts.name not in rc:
84 raise parser.error('%s not in %s' % (opts.name, opts.servod_rcfile))
85 if not opts.servod_server:
86 opts.servod_server = rc[opts.name]['sn']
87 if not opts.port:
88 opts.port = rc[opts.name].get('port', client.DEFAULT_PORT)
89 if not opts.board and 'board' in rc[opts.name]:
90 opts.board = rc[opts.name]['board']
Bertrand SIMONNET0ddf7762015-05-20 14:38:00 -070091 logging.warning('Inferring board %s from %s; make sure this is correct!',
92 opts.board, opts.servod_rcfile)
Julius Werner634ccac2014-06-24 13:59:18 -070093
94 if not opts.servod_server:
95 opts.servod_server = client.DEFAULT_HOST
96 if not opts.port:
97 opts.port = client.DEFAULT_PORT
98
99 return opts
100
101
102def FindSymbols(firmware_dir, board, use):
103 """Find the symbolized depthcharge ELF (may be supplied by -s flag)."""
104 if not firmware_dir:
105 firmware_dir = os.path.join(cros_build_lib.GetSysroot(board), 'firmware')
106 # Allow overriding the file directly just in case our detection screws up
107 if firmware_dir.endswith('.elf'):
108 return firmware_dir
109
110 if 'unified_depthcharge' in use:
Julius Werner20dfc992014-07-21 18:40:11 -0700111 basename = 'dev.elf'
Julius Werner634ccac2014-06-24 13:59:18 -0700112 else:
Julius Werner20dfc992014-07-21 18:40:11 -0700113 basename = 'dev.ro.elf'
Julius Werner634ccac2014-06-24 13:59:18 -0700114
Julius Werner20dfc992014-07-21 18:40:11 -0700115 path = os.path.join(firmware_dir, 'depthcharge', basename)
Julius Werner634ccac2014-06-24 13:59:18 -0700116 if not os.path.exists(path):
117 path = os.path.join(firmware_dir, basename)
118
119 if os.path.exists(path):
Bertrand SIMONNET0ddf7762015-05-20 14:38:00 -0700120 logging.warning('Auto-detected symbol file at %s... make sure that this '
121 'matches the image on your DUT!', path)
Julius Werner634ccac2014-06-24 13:59:18 -0700122 return path
123
124 raise ValueError('Could not find %s symbol file!' % basename)
125
126
127# TODO(jwerner): Fine tune |wait| delay or maybe even make it configurable if
128# this causes problems due to load on the host. The callers where this is
129# critical should all have their own timeouts now, though, so it's questionable
130# whether the delay here is even needed at all anymore.
131def ReadAll(fd, wait=0.03):
132 """Read from |fd| until no more data has come for at least |wait| seconds."""
133 data = ''
134 try:
135 while True:
136 time.sleep(wait)
137 data += os.read(fd, 4096)
138 except OSError as e:
139 if e.errno == errno.EAGAIN:
Mike Frysinger2403af42015-04-30 06:25:03 -0400140 logging.debug(data)
Julius Werner634ccac2014-06-24 13:59:18 -0700141 return data
142 raise
143
144
145def GdbChecksum(message):
146 """Calculate a remote-GDB style checksum."""
147 chksum = sum([ord(x) for x in message])
148 return ('%.2x' % chksum)[-2:]
149
150
151def TestConnection(fd):
152 """Return True iff there is a resposive GDB stub on the other end of 'fd'."""
153 cmd = 'vUnknownCommand'
154 for _ in xrange(3):
155 os.write(fd, '$%s#%s\n' % (cmd, GdbChecksum(cmd)))
156 reply = ReadAll(fd)
157 if '+$#00' in reply:
158 os.write(fd, '+')
Mike Frysinger2403af42015-04-30 06:25:03 -0400159 logging.info('TestConnection: Could successfully connect to remote end.')
Julius Werner634ccac2014-06-24 13:59:18 -0700160 return True
Mike Frysinger2403af42015-04-30 06:25:03 -0400161 logging.info('TestConnection: Remote end does not respond.')
Julius Werner634ccac2014-06-24 13:59:18 -0700162 return False
163
164
165def main(argv):
166 opts = ParseArgs(argv)
167 servo = client.ServoClient(host=opts.servod_server, port=opts.port)
168
169 if not opts.tty:
170 try:
171 opts.tty = servo.get('cpu_uart_pty')
172 except (client.ServoClientError, socket.error):
Mike Frysinger2403af42015-04-30 06:25:03 -0400173 logging.error('Cannot auto-detect TTY file without servod. Use the --tty '
174 'option.')
Julius Werner634ccac2014-06-24 13:59:18 -0700175 raise
Aseda Aboagye6e21d3f2016-10-21 11:37:56 -0700176 with terminal_freezer.TerminalFreezer(opts.tty):
Julius Werner634ccac2014-06-24 13:59:18 -0700177 fd = os.open(opts.tty, os.O_RDWR | os.O_NONBLOCK)
178
179 data = ReadAll(fd)
180 if opts.reboot == 'auto':
181 if TestConnection(fd):
182 opts.reboot = 'no'
183 else:
184 opts.reboot = 'yes'
185
186 if opts.reboot == 'yes':
Mike Frysinger2403af42015-04-30 06:25:03 -0400187 logging.info('Rebooting DUT...')
Julius Werner634ccac2014-06-24 13:59:18 -0700188 try:
189 servo.set('warm_reset', 'on')
190 time.sleep(0.1)
191 servo.set('warm_reset', 'off')
192 except (client.ServoClientError, socket.error):
Mike Frysinger2403af42015-04-30 06:25:03 -0400193 logging.error('Cannot reboot without a Servo board. You have to boot '
194 'into developer mode and press CTRL+G manually before '
195 'running fwgdb.')
Julius Werner634ccac2014-06-24 13:59:18 -0700196 raise
197
198 # Throw away old data to avoid confusion from messages before the reboot
199 data = ''
Mike Frysingerd6e2df02014-11-26 02:55:04 -0500200 msg = ('Could not reboot into developer mode! '
201 '(Confirm that you have GBB_FLAG_FORCE_DEV_SWITCH_ON (0x8) set.)')
202 with timeout_util.Timeout(10, msg):
Julius Werner634ccac2014-06-24 13:59:18 -0700203 while _PTRN_DEVMODE not in data:
204 data += ReadAll(fd)
205
206 # Send a CTRL+G
Mike Frysinger2403af42015-04-30 06:25:03 -0400207 logging.info('Developer mode detected, pressing CTRL+G...')
Julius Werner634ccac2014-06-24 13:59:18 -0700208 os.write(fd, chr(ord('G') & 0x1f))
209
Mike Frysingerd6e2df02014-11-26 02:55:04 -0500210 msg = ('Could not enter GDB mode with CTRL+G! '
211 '(Confirm that you flashed an "image.dev.bin" image to this DUT.)')
212 with timeout_util.Timeout(1, msg):
Julius Werner634ccac2014-06-24 13:59:18 -0700213 while _PTRN_GDB not in data:
214 data += ReadAll(fd)
215
216 if not opts.board:
217 matches = re.findall(_PTRN_BOARD, data)
218 if not matches:
219 raise ValueError('Could not auto-detect board! Please use -b option.')
220 opts.board = matches[-1]
Mike Frysinger2403af42015-04-30 06:25:03 -0400221 logging.info('Auto-detected board as %s from DUT console output.',
222 opts.board)
Julius Werner634ccac2014-06-24 13:59:18 -0700223
224 if not TestConnection(fd):
225 raise IOError('Could not connect to remote end! Confirm that your DUT is '
226 'running in GDB mode on %s.' % opts.tty)
227
228 # Eat up leftover data or it will spill back to terminal
229 ReadAll(fd)
230 os.close(fd)
231
232 opts.execute.insert(0, 'target remote %s' % opts.tty)
233 ex_args = sum([['--ex', cmd] for cmd in opts.execute], [])
234
235 chost, use = ParsePortage(opts.board)
Mike Frysinger2403af42015-04-30 06:25:03 -0400236 logging.info('Launching GDB...')
Mike Frysingerd6e2df02014-11-26 02:55:04 -0500237 cros_build_lib.RunCommand(
238 [chost + '-gdb',
239 '--symbols', FindSymbols(opts.symbols, opts.board, use),
240 '--directory', _SRC_DC,
241 '--directory', _SRC_VB,
242 '--directory', _SRC_LP] + ex_args,
Julius Werner634ccac2014-06-24 13:59:18 -0700243 ignore_sigint=True, debug_level=logging.WARNING)