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