blob: f7fc2109be18809e4c924914117fa2c1f7d1399b [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
Mike Frysinger383367e2014-09-16 15:06:17 -04007from __future__ import print_function
8
Julius Werner634ccac2014-06-24 13:59:18 -07009import errno
10import logging
11import os
12import re
13import signal
14import socket
15import time
16
17from chromite.cbuildbot import constants
18from chromite.lib import commandline
19from chromite.lib import cros_build_lib
Julius Werner2c46b982015-02-13 12:47:20 -080020from chromite.lib import osutils
Julius Werner634ccac2014-06-24 13:59:18 -070021from chromite.lib import timeout_util
22
23# pylint: disable=W0622
24from chromite.lib.cros_build_lib import Error, Warning, Info, Debug
25
26# Need to do this before Servo import
27cros_build_lib.AssertInsideChroot()
28
Mike Frysinger61ef29a2014-12-17 02:05:27 -050029# pylint: disable=import-error
Julius Werner634ccac2014-06-24 13:59:18 -070030from servo import client
31from servo import multiservo
Mike Frysinger61ef29a2014-12-17 02:05:27 -050032# pylint: enable=import-error
Julius Werner634ccac2014-06-24 13:59:18 -070033
34_SRC_ROOT = os.path.join(constants.CHROOT_SOURCE_ROOT, 'src')
35_SRC_DC = os.path.join(_SRC_ROOT, 'platform/depthcharge')
36_SRC_VB = os.path.join(_SRC_ROOT, 'platform/vboot_reference')
37_SRC_LP = os.path.join(_SRC_ROOT, 'third_party/coreboot/payloads/libpayload')
38
39_PTRN_DEVMODE = 'Entering VbBootDeveloper()'
40_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
44class TerminalFreezer(object):
45 """SIGSTOP all processes (and their parents) that have the TTY open."""
46
47 def __init__(self, tty):
48 self._tty = tty
49 self._processes = None
Julius Werner2c46b982015-02-13 12:47:20 -080050 if 'cros_sdk' in osutils.ReadFile('/proc/1/cmdline'):
51 raise OSError('You must run this tool in a chroot that was entered with '
52 '"cros_sdk --no-ns-pid" (see crbug.com/444931 for details)')
Julius Werner634ccac2014-06-24 13:59:18 -070053
54 def __enter__(self):
Mike Frysingerd6e2df02014-11-26 02:55:04 -050055 lsof = cros_build_lib.RunCommand(
56 ['lsof', '-FR', self._tty],
Julius Werner634ccac2014-06-24 13:59:18 -070057 capture_output=True, log_output=True, error_code_ok=True)
58 self._processes = re.findall(r'^(?:R|p)(\d+)$', lsof.output, re.MULTILINE)
59
60 # SIGSTOP parents before children
61 try:
62 for p in reversed(self._processes):
63 Info('Sending SIGSTOP to process %s!', p)
64 time.sleep(0.02)
65 os.kill(int(p), signal.SIGSTOP)
66 except OSError:
67 self.__exit__(None, None, None)
68 raise
69
70 def __exit__(self, _t, _v, _b):
71 # ...and wake 'em up again in reverse order
72 for p in self._processes:
73 Info('Sending SIGCONT to process %s!', p)
74 try:
75 os.kill(int(p), signal.SIGCONT)
76 except OSError as e:
Julius Werner2c46b982015-02-13 12:47:20 -080077 Error('Error when trying to unfreeze process %s: %s' % (p, str(e)))
Julius Werner634ccac2014-06-24 13:59:18 -070078
79
80def ParsePortage(board):
81 """Parse some data from portage files. equery takes ages in comparison."""
82 with open(os.path.join('/build', board, 'packages/Packages'), 'r') as f:
83 chost = None
84 use = None
85 for line in f:
86 if line[:7] == 'CHOST: ':
87 chost = line[7:].strip()
88 if line[:5] == 'USE: ':
89 use = line[5:].strip()
90 if chost and use:
91 return (chost, use)
92
93
94def ParseArgs(argv):
95 """Parse and validate command line arguments."""
96 parser = commandline.ArgumentParser(default_log_level='warning')
97
98 parser.add_argument('-b', '--board',
99 help='The board overlay name (auto-detect by default)')
100 parser.add_argument('-s', '--symbols',
101 help='Root directory or complete path to symbolized ELF '
102 '(defaults to /build/<BOARD>/firmware)')
103 parser.add_argument('-r', '--reboot', choices=['yes', 'no', 'auto'],
104 help='Reboot the DUT before connect (default: reboot if '
105 'the remote and is unreachable)', default='auto')
106 parser.add_argument('-e', '--execute', action='append', default=[],
107 help='GDB command to run after connect (can be supplied '
108 'multiple times)')
109
110 parser.add_argument('-n', '--servod-name', dest='name')
111 parser.add_argument('--servod-rcfile', default=multiservo.DEFAULT_RC_FILE)
112 parser.add_argument('--servod-server')
113 parser.add_argument('-p', '--servod-port', type=int, dest='port')
114 parser.add_argument('-t', '--tty',
115 help='TTY file to connect to (defaults to cpu_uart_pty)')
116
117 opts = parser.parse_args(argv)
118 multiservo.get_env_options(logging, opts)
119 if opts.name:
120 rc = multiservo.parse_rc(logging, opts.servod_rcfile)
121 if opts.name not in rc:
122 raise parser.error('%s not in %s' % (opts.name, opts.servod_rcfile))
123 if not opts.servod_server:
124 opts.servod_server = rc[opts.name]['sn']
125 if not opts.port:
126 opts.port = rc[opts.name].get('port', client.DEFAULT_PORT)
127 if not opts.board and 'board' in rc[opts.name]:
128 opts.board = rc[opts.name]['board']
129 Warning('Inferring board %s from %s... make sure this is correct!',
130 opts.board, opts.servod_rcfile)
131
132 if not opts.servod_server:
133 opts.servod_server = client.DEFAULT_HOST
134 if not opts.port:
135 opts.port = client.DEFAULT_PORT
136
137 return opts
138
139
140def FindSymbols(firmware_dir, board, use):
141 """Find the symbolized depthcharge ELF (may be supplied by -s flag)."""
142 if not firmware_dir:
143 firmware_dir = os.path.join(cros_build_lib.GetSysroot(board), 'firmware')
144 # Allow overriding the file directly just in case our detection screws up
145 if firmware_dir.endswith('.elf'):
146 return firmware_dir
147
148 if 'unified_depthcharge' in use:
Julius Werner20dfc992014-07-21 18:40:11 -0700149 basename = 'dev.elf'
Julius Werner634ccac2014-06-24 13:59:18 -0700150 else:
Julius Werner20dfc992014-07-21 18:40:11 -0700151 basename = 'dev.ro.elf'
Julius Werner634ccac2014-06-24 13:59:18 -0700152
Julius Werner20dfc992014-07-21 18:40:11 -0700153 path = os.path.join(firmware_dir, 'depthcharge', basename)
Julius Werner634ccac2014-06-24 13:59:18 -0700154 if not os.path.exists(path):
155 path = os.path.join(firmware_dir, basename)
156
157 if os.path.exists(path):
158 Warning('Auto-detected symbol file at %s... make sure that this matches '
159 'the image on your DUT!', path)
160 return path
161
162 raise ValueError('Could not find %s symbol file!' % basename)
163
164
165# TODO(jwerner): Fine tune |wait| delay or maybe even make it configurable if
166# this causes problems due to load on the host. The callers where this is
167# critical should all have their own timeouts now, though, so it's questionable
168# whether the delay here is even needed at all anymore.
169def ReadAll(fd, wait=0.03):
170 """Read from |fd| until no more data has come for at least |wait| seconds."""
171 data = ''
172 try:
173 while True:
174 time.sleep(wait)
175 data += os.read(fd, 4096)
176 except OSError as e:
177 if e.errno == errno.EAGAIN:
178 Debug(data)
179 return data
180 raise
181
182
183def GdbChecksum(message):
184 """Calculate a remote-GDB style checksum."""
185 chksum = sum([ord(x) for x in message])
186 return ('%.2x' % chksum)[-2:]
187
188
189def TestConnection(fd):
190 """Return True iff there is a resposive GDB stub on the other end of 'fd'."""
191 cmd = 'vUnknownCommand'
192 for _ in xrange(3):
193 os.write(fd, '$%s#%s\n' % (cmd, GdbChecksum(cmd)))
194 reply = ReadAll(fd)
195 if '+$#00' in reply:
196 os.write(fd, '+')
197 Info('TestConnection: Could successfully connect to remote end.')
198 return True
199 Info('TestConnection: Remote end does not respond.')
200 return False
201
202
203def main(argv):
204 opts = ParseArgs(argv)
205 servo = client.ServoClient(host=opts.servod_server, port=opts.port)
206
207 if not opts.tty:
208 try:
209 opts.tty = servo.get('cpu_uart_pty')
210 except (client.ServoClientError, socket.error):
211 Error('Cannot auto-detect TTY file without servod. Use the --tty option.')
212 raise
213 with TerminalFreezer(opts.tty):
214 fd = os.open(opts.tty, os.O_RDWR | os.O_NONBLOCK)
215
216 data = ReadAll(fd)
217 if opts.reboot == 'auto':
218 if TestConnection(fd):
219 opts.reboot = 'no'
220 else:
221 opts.reboot = 'yes'
222
223 if opts.reboot == 'yes':
224 Info('Rebooting DUT...')
225 try:
226 servo.set('warm_reset', 'on')
227 time.sleep(0.1)
228 servo.set('warm_reset', 'off')
229 except (client.ServoClientError, socket.error):
230 Error('Cannot reboot without a Servo board. You have to boot into '
231 'developer mode and press CTRL+G manually before running fwgdb.')
232 raise
233
234 # Throw away old data to avoid confusion from messages before the reboot
235 data = ''
Mike Frysingerd6e2df02014-11-26 02:55:04 -0500236 msg = ('Could not reboot into developer mode! '
237 '(Confirm that you have GBB_FLAG_FORCE_DEV_SWITCH_ON (0x8) set.)')
238 with timeout_util.Timeout(10, msg):
Julius Werner634ccac2014-06-24 13:59:18 -0700239 while _PTRN_DEVMODE not in data:
240 data += ReadAll(fd)
241
242 # Send a CTRL+G
243 Info('Developer mode detected, pressing CTRL+G...')
244 os.write(fd, chr(ord('G') & 0x1f))
245
Mike Frysingerd6e2df02014-11-26 02:55:04 -0500246 msg = ('Could not enter GDB mode with CTRL+G! '
247 '(Confirm that you flashed an "image.dev.bin" image to this DUT.)')
248 with timeout_util.Timeout(1, msg):
Julius Werner634ccac2014-06-24 13:59:18 -0700249 while _PTRN_GDB not in data:
250 data += ReadAll(fd)
251
252 if not opts.board:
253 matches = re.findall(_PTRN_BOARD, data)
254 if not matches:
255 raise ValueError('Could not auto-detect board! Please use -b option.')
256 opts.board = matches[-1]
257 Info('Auto-detected board as %s from DUT console output.', opts.board)
258
259 if not TestConnection(fd):
260 raise IOError('Could not connect to remote end! Confirm that your DUT is '
261 'running in GDB mode on %s.' % opts.tty)
262
263 # Eat up leftover data or it will spill back to terminal
264 ReadAll(fd)
265 os.close(fd)
266
267 opts.execute.insert(0, 'target remote %s' % opts.tty)
268 ex_args = sum([['--ex', cmd] for cmd in opts.execute], [])
269
270 chost, use = ParsePortage(opts.board)
271 Info('Launching GDB...')
Mike Frysingerd6e2df02014-11-26 02:55:04 -0500272 cros_build_lib.RunCommand(
273 [chost + '-gdb',
274 '--symbols', FindSymbols(opts.symbols, opts.board, use),
275 '--directory', _SRC_DC,
276 '--directory', _SRC_VB,
277 '--directory', _SRC_LP] + ex_args,
Julius Werner634ccac2014-06-24 13:59:18 -0700278 ignore_sigint=True, debug_level=logging.WARNING)