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