style: format python files with isort and double-quote-string-fixer

This commit is contained in:
Fu Hanxi
2021-01-26 10:49:01 +08:00
parent dc8402ea61
commit 0146f258d7
276 changed files with 8241 additions and 8162 deletions

View File

@@ -31,18 +31,17 @@
#
from builtins import bytes
import argparse
import binascii
import logging
import struct
import sys
import logging
import binascii
from builtins import bytes
from collections import namedtuple
from pyparsing import Literal, Word, nums, OneOrMore, srange, Group, Combine
# Used for type annotations only. Silence linter warnings.
from pyparsing import ParseResults, ParserElement # noqa: F401 # pylint: disable=unused-import
from pyparsing import (Combine, Group, Literal, OneOrMore, ParserElement, # noqa: F401 # pylint: disable=unused-import
ParseResults, Word, nums, srange)
try:
import typing # noqa: F401 # pylint: disable=unused-import
@@ -50,30 +49,30 @@ except ImportError:
pass
# pyparsing helper
hexnumber = srange("[0-9a-f]")
hexnumber = srange('[0-9a-f]')
# List of registers to be passed to GDB, in the order GDB expects.
# The names should match those used in IDF panic handler.
# Registers not present in IDF panic handler output (like X0) will be assumed to be 0.
GDB_REGS_INFO_RISCV_ILP32 = [
"X0", "RA", "SP", "GP",
"TP", "T0", "T1", "T2",
"S0/FP", "S1", "A0", "A1",
"A2", "A3", "A4", "A5",
"A6", "A7", "S2", "S3",
"S4", "S5", "S6", "S7",
"S8", "S9", "S10", "S11",
"T3", "T4", "T5", "T6",
"MEPC"
'X0', 'RA', 'SP', 'GP',
'TP', 'T0', 'T1', 'T2',
'S0/FP', 'S1', 'A0', 'A1',
'A2', 'A3', 'A4', 'A5',
'A6', 'A7', 'S2', 'S3',
'S4', 'S5', 'S6', 'S7',
'S8', 'S9', 'S10', 'S11',
'T3', 'T4', 'T5', 'T6',
'MEPC'
]
GDB_REGS_INFO = {
"esp32c3": GDB_REGS_INFO_RISCV_ILP32
'esp32c3': GDB_REGS_INFO_RISCV_ILP32
}
PanicInfo = namedtuple("PanicInfo", "core_id regs stack_base_addr stack_data")
PanicInfo = namedtuple('PanicInfo', 'core_id regs stack_base_addr stack_data')
def build_riscv_panic_output_parser(): # type: () -> typing.Type[ParserElement]
@@ -83,25 +82,25 @@ def build_riscv_panic_output_parser(): # type: () -> typing.Type[ParserElement]
# Guru Meditation Error: Core 0 panic'ed (Store access fault). Exception was unhandled.
# Core 0 register dump:
reg_dump_header = Group(Literal("Core") +
Word(nums)("core_id") +
Literal("register dump:"))("reg_dump_header")
reg_dump_header = Group(Literal('Core') +
Word(nums)('core_id') +
Literal('register dump:'))('reg_dump_header')
# MEPC : 0x4200232c RA : 0x42009694 SP : 0x3fc93a80 GP : 0x3fc8b320
reg_name = Word(srange("[A-Z_0-9/-]"))("name")
hexnumber_with_0x = Combine(Literal("0x") + Word(hexnumber))
reg_value = hexnumber_with_0x("value")
reg_dump_one_reg = Group(reg_name + Literal(":") + reg_value) # not named because there will be OneOrMore
reg_dump_all_regs = Group(OneOrMore(reg_dump_one_reg))("regs")
reg_name = Word(srange('[A-Z_0-9/-]'))('name')
hexnumber_with_0x = Combine(Literal('0x') + Word(hexnumber))
reg_value = hexnumber_with_0x('value')
reg_dump_one_reg = Group(reg_name + Literal(':') + reg_value) # not named because there will be OneOrMore
reg_dump_all_regs = Group(OneOrMore(reg_dump_one_reg))('regs')
reg_dump = Group(reg_dump_header + reg_dump_all_regs) # not named because there will be OneOrMore
reg_dumps = Group(OneOrMore(reg_dump))("reg_dumps")
reg_dumps = Group(OneOrMore(reg_dump))('reg_dumps')
# Stack memory:
# 3fc93a80: 0x00000030 0x00000021 0x3fc8aedc 0x4200232a 0xa5a5a5a5 0xa5a5a5a5 0x3fc8aedc 0x420099b0
stack_line = Group(Word(hexnumber)("base") + Literal(":") +
Group(OneOrMore(hexnumber_with_0x))("data"))
stack_dump = Group(Literal("Stack memory:") +
Group(OneOrMore(stack_line))("lines"))("stack_dump")
stack_line = Group(Word(hexnumber)('base') + Literal(':') +
Group(OneOrMore(hexnumber_with_0x))('data'))
stack_dump = Group(Literal('Stack memory:') +
Group(OneOrMore(stack_line))('lines'))('stack_dump')
# Parser for the complete panic output:
panic_output = reg_dumps + stack_dump
@@ -113,7 +112,7 @@ def get_stack_addr_and_data(res): # type: (ParseResults) -> typing.Tuple[int, b
stack_base_addr = 0 # First reported address in the dump
base_addr = 0 # keeps track of the address for the given line of the dump
bytes_in_line = 0 # bytes of stack parsed on the previous line; used to validate the next base address
stack_data = b"" # accumulates all the dumped stack data
stack_data = b'' # accumulates all the dumped stack data
for line in res.stack_dump.lines:
# update and validate the base address
prev_base_addr = base_addr
@@ -125,7 +124,7 @@ def get_stack_addr_and_data(res): # type: (ParseResults) -> typing.Tuple[int, b
# convert little-endian hex words to byte representation
words = [int(w, 16) for w in line.data]
line_data = b"".join([struct.pack("<I", w) for w in words])
line_data = b''.join([struct.pack('<I', w) for w in words])
bytes_in_line = len(line_data)
# accumulate in the whole stack data
@@ -143,7 +142,7 @@ def parse_idf_riscv_panic_output(panic_text): # type: (str) -> PanicInfo
res = results[0]
if len(res.reg_dumps) > 1:
raise NotImplementedError("Handling of multi-core register dumps not implemented")
raise NotImplementedError('Handling of multi-core register dumps not implemented')
# Build a dict of register names/values
rd = res.reg_dumps[0]
@@ -162,7 +161,7 @@ def parse_idf_riscv_panic_output(panic_text): # type: (str) -> PanicInfo
PANIC_OUTPUT_PARSERS = {
"esp32c3": parse_idf_riscv_panic_output
'esp32c3': parse_idf_riscv_panic_output
}
@@ -173,82 +172,82 @@ class GdbServer(object):
self.out_stream = sys.stdout
self.reg_list = GDB_REGS_INFO[target]
self.logger = logging.getLogger("GdbServer")
self.logger = logging.getLogger('GdbServer')
if log_file:
handler = logging.FileHandler(log_file, "w+")
handler = logging.FileHandler(log_file, 'w+')
self.logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
self.logger.addHandler(handler)
def run(self): # type: () -> None
""" Process GDB commands from stdin until GDB tells us to quit """
buffer = ""
buffer = ''
while True:
buffer += self.in_stream.read(1)
if len(buffer) > 3 and buffer[-3] == '#':
self._handle_command(buffer)
buffer = ""
buffer = ''
def _handle_command(self, buffer): # type: (str) -> None
command = buffer[1:-3] # ignore checksums
# Acknowledge the command
self.out_stream.write("+")
self.out_stream.write('+')
self.out_stream.flush()
self.logger.debug("Got command: %s", command)
if command == "?":
self.logger.debug('Got command: %s', command)
if command == '?':
# report sigtrap as the stop reason; the exact reason doesn't matter for backtracing
self._respond("T05")
elif command.startswith("Hg") or command.startswith("Hc"):
self._respond('T05')
elif command.startswith('Hg') or command.startswith('Hc'):
# Select thread command
self._respond("OK")
elif command == "qfThreadInfo":
self._respond('OK')
elif command == 'qfThreadInfo':
# Get list of threads.
# Only one thread for now, can be extended to show one thread for each core,
# if we dump both cores (e.g. on an interrupt watchdog)
self._respond("m1")
elif command == "qC":
self._respond('m1')
elif command == 'qC':
# That single thread is selected.
self._respond("QC1")
elif command == "g":
self._respond('QC1')
elif command == 'g':
# Registers read
self._respond_regs()
elif command.startswith("m"):
elif command.startswith('m'):
# Memory read
addr, size = [int(v, 16) for v in command[1:].split(",")]
addr, size = [int(v, 16) for v in command[1:].split(',')]
self._respond_mem(addr, size)
elif command.startswith("vKill") or command == "k":
elif command.startswith('vKill') or command == 'k':
# Quit
self._respond("OK")
self._respond('OK')
raise SystemExit(0)
else:
# Empty response required for any unknown command
self._respond("")
self._respond('')
def _respond(self, data): # type: (str) -> None
# calculate checksum
data_bytes = bytes(data.encode("ascii")) # bytes() for Py2 compatibility
data_bytes = bytes(data.encode('ascii')) # bytes() for Py2 compatibility
checksum = sum(data_bytes) & 0xff
# format and write the response
res = "${}#{:02x}".format(data, checksum)
self.logger.debug("Wrote: %s", res)
res = '${}#{:02x}'.format(data, checksum)
self.logger.debug('Wrote: %s', res)
self.out_stream.write(res)
self.out_stream.flush()
# get the result ('+' or '-')
ret = self.in_stream.read(1)
self.logger.debug("Response: %s", ret)
self.logger.debug('Response: %s', ret)
if ret != '+':
sys.stderr.write("GDB responded with '-' to {}".format(res))
raise SystemExit(1)
def _respond_regs(self): # type: () -> None
response = ""
response = ''
for reg_name in self.reg_list:
# register values are reported as hexadecimal strings
# in target byte order (i.e. LSB first for RISC-V)
reg_val = self.panic_info.regs.get(reg_name, 0)
reg_bytes = struct.pack("<L", reg_val)
response += binascii.hexlify(reg_bytes).decode("ascii")
reg_bytes = struct.pack('<L', reg_val)
response += binascii.hexlify(reg_bytes).decode('ascii')
self._respond(response)
def _respond_mem(self, start_addr, size): # type: (int, int) -> None
@@ -262,24 +261,24 @@ class GdbServer(object):
def in_stack(addr):
return stack_addr_min <= addr < stack_addr_max
result = ""
result = ''
for addr in range(start_addr, start_addr + size):
if not in_stack(addr):
result += "00"
result += '00'
else:
result += "{:02x}".format(stack_data[addr - stack_addr_min])
result += '{:02x}'.format(stack_data[addr - stack_addr_min])
self._respond(result)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("input_file", type=argparse.FileType("r"),
help="File containing the panic handler output")
parser.add_argument("--target", choices=GDB_REGS_INFO.keys(),
help="Chip to use (determines the architecture)")
parser.add_argument("--gdb-log", default=None,
help="If specified, the file for logging GDB server debug information")
parser.add_argument('input_file', type=argparse.FileType('r'),
help='File containing the panic handler output')
parser.add_argument('--target', choices=GDB_REGS_INFO.keys(),
help='Chip to use (determines the architecture)')
parser.add_argument('--gdb-log', default=None,
help='If specified, the file for logging GDB server debug information')
args = parser.parse_args()
panic_info = PANIC_OUTPUT_PARSERS[args.target](args.input_file.read())
@@ -291,5 +290,5 @@ def main():
sys.exit(0)
if __name__ == "__main__":
if __name__ == '__main__':
main()