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