blob: 67660261a2226d2a9c53001ecea4bdb403db1863 [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
Raul E Rangeleb8aadc2018-05-17 09:10:27 -060011import glob
Julius Werner634ccac2014-06-24 13:59:18 -070012import os
13import re
Julius Werner634ccac2014-06-24 13:59:18 -070014import socket
15import time
16
Mike Frysinger849d6402019-10-17 00:14:16 -040017from elftools.elf.elffile import ELFFile
18
Aviv Keshetb7519e12016-10-04 00:50:00 -070019from chromite.lib import constants
Julius Werner634ccac2014-06-24 13:59:18 -070020from chromite.lib import cros_build_lib
Ralph Nathan91874ca2015-03-19 13:29:41 -070021from chromite.lib import cros_logging as logging
Julius Werner634ccac2014-06-24 13:59:18 -070022from chromite.lib import timeout_util
23
Julius Werner634ccac2014-06-24 13:59:18 -070024# Need to do this before Servo import
25cros_build_lib.AssertInsideChroot()
26
Mike Frysinger92bdef52019-08-21 21:05:13 -040027# pylint: disable=import-error,wrong-import-position
Julius Werner634ccac2014-06-24 13:59:18 -070028from servo import client
Ruben Rodriguez Buchillon15bdd452018-10-09 08:31:41 +080029from servo import servo_parsing
Aseda Aboagye6e21d3f2016-10-21 11:37:56 -070030from servo import terminal_freezer
Mike Frysinger92bdef52019-08-21 21:05:13 -040031# pylint: enable=import-error,wrong-import-position
Julius Werner634ccac2014-06-24 13:59:18 -070032
Ralph Nathan91874ca2015-03-19 13:29:41 -070033
Julius Werner634ccac2014-06-24 13:59:18 -070034_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
Julius Werner634ccac2014-06-24 13:59:18 -070039_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
Julius Werner149fe782018-10-10 15:18:14 -070043def GetGdbForElf(elf):
44 """Return the correct C compiler prefix for the target ELF file."""
Mike Frysinger17844a02019-08-24 18:21:02 -040045 with open(elf, 'rb') as fp:
Julius Werner149fe782018-10-10 15:18:14 -070046 return {
47 'EM_386': 'x86_64-cros-linux-gnu-gdb',
48 'EM_X86_64': 'x86_64-cros-linux-gnu-gdb',
49 'EM_ARM': 'armv7a-cros-linux-gnueabihf-gdb',
50 'EM_AARCH64': 'aarch64-cros-linux-gnu-gdb',
Mike Frysinger17844a02019-08-24 18:21:02 -040051 }[ELFFile(fp).header.e_machine]
Julius Werner634ccac2014-06-24 13:59:18 -070052
53
54def ParseArgs(argv):
55 """Parse and validate command line arguments."""
Raul E Rangelb54ec042020-02-06 09:25:12 -070056 description = 'Debug depthcharge using GDB'
57 parser = servo_parsing.ServodClientParser(description=description)
Julius Werner634ccac2014-06-24 13:59:18 -070058 parser.add_argument('-b', '--board',
59 help='The board overlay name (auto-detect by default)')
Raul E Rangel72f32712018-05-29 11:42:59 -060060 parser.add_argument('-c', '--cgdb', action='store_true',
61 help='Use cgdb curses interface rather than plain gdb')
Raul E Rangelb54ec042020-02-06 09:25:12 -070062 parser.add_argument('-y', '--symbols',
Julius Werner634ccac2014-06-24 13:59:18 -070063 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)')
Julius Werner634ccac2014-06-24 13:59:18 -070071 parser.add_argument('-t', '--tty',
72 help='TTY file to connect to (defaults to cpu_uart_pty)')
Julius Werner634ccac2014-06-24 13:59:18 -070073 opts = parser.parse_args(argv)
Ruben Rodriguez Buchillond7c65bd2018-12-10 10:10:19 +080074
Julius Werner634ccac2014-06-24 13:59:18 -070075 return opts
76
77
Julius Werner193c9142018-05-09 16:25:38 -070078def FindSymbols(firmware_dir, board):
Julius Werner634ccac2014-06-24 13:59:18 -070079 """Find the symbolized depthcharge ELF (may be supplied by -s flag)."""
Raul E Rangeleb8aadc2018-05-17 09:10:27 -060080
81 # Allow overriding the file directly just in case our detection screws up.
82 if firmware_dir and firmware_dir.endswith('.elf'):
83 return firmware_dir
84
85 if not firmware_dir:
86 # Unified builds have the format
87 # /build/<board|family>/firmware/<build_target|model>/. The board in
88 # depthcharge corresponds to the build_target in unified builds. For this
89 # reason we need to glob all boards to find the correct build_target.
90 unified_build_dirs = glob.glob('/build/*/firmware/%s' % board)
91 if len(unified_build_dirs) == 1:
92 firmware_dir = unified_build_dirs[0]
93 elif len(unified_build_dirs) > 1:
94 raise ValueError(
95 'Multiple boards were found (%s). Use -s to specify manually' %
96 (', '.join(unified_build_dirs)))
97
Julius Werner634ccac2014-06-24 13:59:18 -070098 if not firmware_dir:
99 firmware_dir = os.path.join(cros_build_lib.GetSysroot(board), 'firmware')
Julius Werner634ccac2014-06-24 13:59:18 -0700100
Julius Werner193c9142018-05-09 16:25:38 -0700101 # Very old firmware you might still find on GoldenEye had dev.ro.elf.
102 basenames = ['dev.elf', 'dev.ro.elf']
103 for basename in basenames:
104 path = os.path.join(firmware_dir, 'depthcharge', basename)
105 if not os.path.exists(path):
106 path = os.path.join(firmware_dir, basename)
107 if os.path.exists(path):
108 logging.warning('Auto-detected symbol file at %s... make sure that this'
109 ' matches the image on your DUT!', path)
110 return path
Julius Werner634ccac2014-06-24 13:59:18 -0700111
Julius Werner193c9142018-05-09 16:25:38 -0700112 raise ValueError('Could not find depthcharge symbol file (dev.elf)! '
113 '(You can use -s to supply it manually.)')
Julius Werner634ccac2014-06-24 13:59:18 -0700114
115
116# TODO(jwerner): Fine tune |wait| delay or maybe even make it configurable if
117# this causes problems due to load on the host. The callers where this is
118# critical should all have their own timeouts now, though, so it's questionable
119# whether the delay here is even needed at all anymore.
120def ReadAll(fd, wait=0.03):
121 """Read from |fd| until no more data has come for at least |wait| seconds."""
122 data = ''
123 try:
124 while True:
125 time.sleep(wait)
Julius Werner193c9142018-05-09 16:25:38 -0700126 new_data = os.read(fd, 4096)
127 if not new_data:
128 break
129 data += new_data
Julius Werner634ccac2014-06-24 13:59:18 -0700130 except OSError as e:
Julius Werner193c9142018-05-09 16:25:38 -0700131 if e.errno != errno.EAGAIN:
132 raise
133 logging.debug(data)
134 return data
Julius Werner634ccac2014-06-24 13:59:18 -0700135
136
137def GdbChecksum(message):
138 """Calculate a remote-GDB style checksum."""
139 chksum = sum([ord(x) for x in message])
140 return ('%.2x' % chksum)[-2:]
141
142
143def TestConnection(fd):
144 """Return True iff there is a resposive GDB stub on the other end of 'fd'."""
145 cmd = 'vUnknownCommand'
Mike Frysinger79cca962019-06-13 15:26:53 -0400146 for _ in range(3):
Julius Werner634ccac2014-06-24 13:59:18 -0700147 os.write(fd, '$%s#%s\n' % (cmd, GdbChecksum(cmd)))
148 reply = ReadAll(fd)
149 if '+$#00' in reply:
150 os.write(fd, '+')
Mike Frysinger2403af42015-04-30 06:25:03 -0400151 logging.info('TestConnection: Could successfully connect to remote end.')
Julius Werner634ccac2014-06-24 13:59:18 -0700152 return True
Mike Frysinger2403af42015-04-30 06:25:03 -0400153 logging.info('TestConnection: Remote end does not respond.')
Julius Werner634ccac2014-06-24 13:59:18 -0700154 return False
155
156
157def main(argv):
158 opts = ParseArgs(argv)
Raul E Rangelb54ec042020-02-06 09:25:12 -0700159 servo = client.ServoClient(host=opts.host, port=opts.port)
Julius Werner634ccac2014-06-24 13:59:18 -0700160
161 if not opts.tty:
162 try:
163 opts.tty = servo.get('cpu_uart_pty')
164 except (client.ServoClientError, socket.error):
Mike Frysinger2403af42015-04-30 06:25:03 -0400165 logging.error('Cannot auto-detect TTY file without servod. Use the --tty '
166 'option.')
Julius Werner634ccac2014-06-24 13:59:18 -0700167 raise
Aseda Aboagye6e21d3f2016-10-21 11:37:56 -0700168 with terminal_freezer.TerminalFreezer(opts.tty):
Julius Werner634ccac2014-06-24 13:59:18 -0700169 fd = os.open(opts.tty, os.O_RDWR | os.O_NONBLOCK)
170
171 data = ReadAll(fd)
172 if opts.reboot == 'auto':
173 if TestConnection(fd):
174 opts.reboot = 'no'
175 else:
176 opts.reboot = 'yes'
177
178 if opts.reboot == 'yes':
Mike Frysinger2403af42015-04-30 06:25:03 -0400179 logging.info('Rebooting DUT...')
Julius Werner634ccac2014-06-24 13:59:18 -0700180 try:
181 servo.set('warm_reset', 'on')
182 time.sleep(0.1)
183 servo.set('warm_reset', 'off')
184 except (client.ServoClientError, socket.error):
Mike Frysinger2403af42015-04-30 06:25:03 -0400185 logging.error('Cannot reboot without a Servo board. You have to boot '
186 'into developer mode and press CTRL+G manually before '
187 'running fwgdb.')
Julius Werner634ccac2014-06-24 13:59:18 -0700188 raise
189
190 # Throw away old data to avoid confusion from messages before the reboot
191 data = ''
Julius Werner193c9142018-05-09 16:25:38 -0700192 msg = ('Could not reboot into depthcharge!')
Mike Frysingerd6e2df02014-11-26 02:55:04 -0500193 with timeout_util.Timeout(10, msg):
Julius Werner193c9142018-05-09 16:25:38 -0700194 while not re.search(_PTRN_BOARD, data):
Julius Werner634ccac2014-06-24 13:59:18 -0700195 data += ReadAll(fd)
196
Mike Frysingerd6e2df02014-11-26 02:55:04 -0500197 msg = ('Could not enter GDB mode with CTRL+G! '
Julius Werner193c9142018-05-09 16:25:38 -0700198 '(Confirm that you flashed an "image.dev.bin" image to this DUT, '
199 'and that you have GBB_FLAG_FORCE_DEV_SWITCH_ON (0x8) set.)')
200 with timeout_util.Timeout(5, msg):
201 while not re.search(_PTRN_GDB, data):
202 # Send a CTRL+G to tell depthcharge to trap into GDB.
203 logging.debug('[Ctrl+G]')
204 os.write(fd, chr(ord('G') & 0x1f))
Julius Werner634ccac2014-06-24 13:59:18 -0700205 data += ReadAll(fd)
206
207 if not opts.board:
208 matches = re.findall(_PTRN_BOARD, data)
209 if not matches:
210 raise ValueError('Could not auto-detect board! Please use -b option.')
211 opts.board = matches[-1]
Mike Frysinger2403af42015-04-30 06:25:03 -0400212 logging.info('Auto-detected board as %s from DUT console output.',
213 opts.board)
Julius Werner634ccac2014-06-24 13:59:18 -0700214
215 if not TestConnection(fd):
216 raise IOError('Could not connect to remote end! Confirm that your DUT is '
217 'running in GDB mode on %s.' % opts.tty)
218
219 # Eat up leftover data or it will spill back to terminal
220 ReadAll(fd)
221 os.close(fd)
222
223 opts.execute.insert(0, 'target remote %s' % opts.tty)
224 ex_args = sum([['--ex', cmd] for cmd in opts.execute], [])
225
Julius Werner149fe782018-10-10 15:18:14 -0700226 elf = FindSymbols(opts.symbols, opts.board)
227 gdb_cmd = GetGdbForElf(elf)
Raul E Rangel72f32712018-05-29 11:42:59 -0600228
Raul E Rangel72f32712018-05-29 11:42:59 -0600229 gdb_args = [
Julius Werner149fe782018-10-10 15:18:14 -0700230 '--symbols', elf,
Raul E Rangel72f32712018-05-29 11:42:59 -0600231 '--directory', _SRC_DC,
232 '--directory', _SRC_VB,
233 '--directory', _SRC_LP,
234 ] + ex_args
235
236 if opts.cgdb:
237 full_cmd = ['cgdb', '-d', gdb_cmd, '--'] + gdb_args
238 else:
239 full_cmd = [gdb_cmd] + gdb_args
240
Julius Werner149fe782018-10-10 15:18:14 -0700241 logging.info('Launching GDB...')
Mike Frysinger45602c72019-09-22 02:15:11 -0400242 cros_build_lib.run(
Raul E Rangel72f32712018-05-29 11:42:59 -0600243 full_cmd, ignore_sigint=True, debug_level=logging.WARNING)