Debug: Add PyCortexDebug. Core and peripheral register database and decoder. (#251)
* Debug: pycortexdebug * Debug: format PyCortexMDebug source code
This commit is contained in:
0
debug/PyCortexMDebug/cmdebug/__init__.py
Normal file
0
debug/PyCortexMDebug/cmdebug/__init__.py
Normal file
152
debug/PyCortexMDebug/cmdebug/dwt_gdb.py
Normal file
152
debug/PyCortexMDebug/cmdebug/dwt_gdb.py
Normal file
@@ -0,0 +1,152 @@
|
||||
#!/usr/bin/env python
|
||||
"""
|
||||
This file is part of PyCortexMDebug
|
||||
|
||||
PyCortexMDebug is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
PyCortexMDebug is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with PyCortexMDebug. If not, see <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
import gdb
|
||||
import struct
|
||||
|
||||
DWT_CTRL = 0xE0001000
|
||||
DWT_CYCCNT = 0xE0001004
|
||||
DWT_CPICNT = 0xE0001008
|
||||
DWT_EXTCNT = 0xE000100C
|
||||
DWT_SLEEPCNT = 0xE0001010
|
||||
DWT_LSUCNT = 0xE0001014
|
||||
DWT_FOLDCNT = 0xE0001018
|
||||
DWT_PCSR = 0xE000101C
|
||||
|
||||
prefix = "dwt : "
|
||||
|
||||
|
||||
class DWT(gdb.Command):
|
||||
clk = None
|
||||
is_init = False
|
||||
|
||||
def __init__(self):
|
||||
gdb.Command.__init__(self, "dwt", gdb.COMMAND_DATA)
|
||||
|
||||
def read(self, address, bits=32):
|
||||
"""Read from memory (using print) and return an integer"""
|
||||
value = gdb.selected_inferior().read_memory(address, bits / 8)
|
||||
return struct.unpack_from("<i", value)[0]
|
||||
|
||||
def write(self, address, value, bits=32):
|
||||
"""Set a value in memory"""
|
||||
gdb.selected_inferior().write_memory(address, bytes(value), bits / 8)
|
||||
|
||||
def invoke(self, args, from_tty):
|
||||
if not self.is_init:
|
||||
self.write(0xE000EDFC, self.read(0xE000EDFC) | (1 << 24))
|
||||
self.write(DWT_CTRL, 0)
|
||||
self.is_init = True
|
||||
|
||||
s = map(lambda x: x.lower(), str(args).split(" "))
|
||||
# Check for empty command
|
||||
if s[0] in ["", "help"]:
|
||||
self.print_help()
|
||||
return ()
|
||||
|
||||
if s[0] == "cyccnt":
|
||||
if len(s) > 1:
|
||||
if s[1][:2] == "en":
|
||||
self.cyccnt_en()
|
||||
elif s[1][0] == "r":
|
||||
self.cyccnt_reset()
|
||||
elif s[1][0] == "d":
|
||||
self.cyccnt_dis()
|
||||
gdb.write(
|
||||
prefix
|
||||
+ "CYCCNT ({}): ".format("ON" if (self.read(DWT_CTRL) & 1) else "OFF")
|
||||
+ self.cycles_str(self.read(DWT_CYCCNT))
|
||||
)
|
||||
elif s[0] == "reset":
|
||||
if len(s) > 1:
|
||||
if s[1] == "cyccnt":
|
||||
self.cyccnt_reset()
|
||||
gdb.write(prefix + "CYCCNT reset\n")
|
||||
if s[1] == "counters":
|
||||
self.cyccnt_reset()
|
||||
gdb.write(prefix + "CYCCNT reset\n")
|
||||
else:
|
||||
self.cyccnt_reset()
|
||||
gdb.write(prefix + "CYCCNT reset\n")
|
||||
else:
|
||||
# Reset everything
|
||||
self.cyccnt_reset()
|
||||
gdb.write(prefix + "CYCCNT reset\n")
|
||||
elif s[0] == "configclk":
|
||||
if len(s) == 2:
|
||||
try:
|
||||
self.clk = float(s[1])
|
||||
except:
|
||||
self.print_help()
|
||||
else:
|
||||
self.print_help()
|
||||
else:
|
||||
# Try to figure out what stupid went on here
|
||||
gdb.write(args)
|
||||
self.print_help()
|
||||
|
||||
def complete(self, text, word):
|
||||
text = str(text).lower()
|
||||
s = text.split(" ")
|
||||
|
||||
commands = ["configclk", "reset", "cyccnt"]
|
||||
reset_commands = ["counters", "cyccnt"]
|
||||
cyccnt_commands = ["enable", "reset", "disable"]
|
||||
|
||||
if len(s) == 1:
|
||||
return filter(lambda x: x.startswith(s[0]), commands)
|
||||
|
||||
if len(s) == 2:
|
||||
if s[0] == "reset":
|
||||
return filter(lambda x: x.startswith(s[1]), reset_commands)
|
||||
if s[0] == "cyccnt":
|
||||
return filter(lambda x: x.startswith(s[1]), cyccnt_commands)
|
||||
|
||||
def cycles_str(self, cycles):
|
||||
if self.clk:
|
||||
return "%d cycles, %.3es\n" % (cycles, cycles * 1.0 / self.clk)
|
||||
else:
|
||||
return "%d cycles"
|
||||
|
||||
def cyccnt_en(self):
|
||||
self.write(DWT_CTRL, self.read(DWT_CTRL) | 1)
|
||||
|
||||
def cyccnt_dis(self):
|
||||
self.write(DWT_CTRL, self.read(DWT_CTRL) & 0xFFFFFFFE)
|
||||
|
||||
def cyccnt_reset(self, value=0):
|
||||
self.write(DWT_CYCCNT, value)
|
||||
|
||||
def cpicnt_reset(self, value=0):
|
||||
self.write(DWT_CPICNT, value & 0xFF)
|
||||
|
||||
def print_help(self):
|
||||
gdb.write("Usage:\n")
|
||||
gdb.write("=========\n")
|
||||
gdb.write("dwt:\n")
|
||||
gdb.write("\tList available peripherals\n")
|
||||
gdb.write("dwt configclk [Hz]:\n")
|
||||
gdb.write("\tSet clock for rendering time values in seconds\n")
|
||||
gdb.write("dwt reset:\n")
|
||||
gdb.write("\tReset everything in DWT\n")
|
||||
gdb.write("dwt reset counters:\n")
|
||||
gdb.write("\tReset all DWT counters\n")
|
||||
gdb.write("dwt cyccnt\n")
|
||||
gdb.write("\tDisplay the cycle count\n")
|
||||
gdb.write("\td(default):decimal, x: hex, o: octal, b: binary\n")
|
||||
return ()
|
288
debug/PyCortexMDebug/cmdebug/svd.py
Executable file
288
debug/PyCortexMDebug/cmdebug/svd.py
Executable file
@@ -0,0 +1,288 @@
|
||||
"""
|
||||
This file is part of PyCortexMDebug
|
||||
|
||||
PyCortexMDebug is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
PyCortexMDebug is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with PyCortexMDebug. If not, see <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
|
||||
import lxml.objectify as objectify
|
||||
import sys
|
||||
from copy import deepcopy
|
||||
from collections import OrderedDict
|
||||
import os
|
||||
import traceback
|
||||
|
||||
|
||||
class SVDNonFatalError(Exception):
|
||||
"""Exception class for non-fatal errors
|
||||
So far, these have related to quirks in some vendor SVD files which are reasonable to ignore
|
||||
"""
|
||||
|
||||
def __init__(self, m):
|
||||
self.m = m
|
||||
self.exc_info = sys.exc_info()
|
||||
|
||||
def __str__(self):
|
||||
s = "Non-fatal: {}".format(self.m)
|
||||
s += "\n" + str("".join(traceback.format_exc())).strip()
|
||||
return s
|
||||
|
||||
|
||||
class SVDFile:
|
||||
def __init__(self, fname):
|
||||
f = objectify.parse(os.path.expanduser(fname))
|
||||
root = f.getroot()
|
||||
periph = root.peripherals.getchildren()
|
||||
self.peripherals = OrderedDict()
|
||||
# XML elements
|
||||
for p in periph:
|
||||
try:
|
||||
self.peripherals[str(p.name)] = SVDPeripheral(p, self)
|
||||
except SVDNonFatalError as e:
|
||||
print(e)
|
||||
|
||||
|
||||
def add_register(parent, node):
|
||||
if hasattr(node, "dim"):
|
||||
dim = int(str(node.dim), 0)
|
||||
# dimension is not used, number of split indexes should be same
|
||||
incr = int(str(node.dimIncrement), 0)
|
||||
default_dim_index = ",".join((str(i) for i in range(dim)))
|
||||
dim_index = str(getattr(node, "dimIndex", default_dim_index))
|
||||
indexes = dim_index.split(",")
|
||||
offset = 0
|
||||
for i in indexes:
|
||||
name = str(node.name) % i
|
||||
reg = SVDPeripheralRegister(node, parent)
|
||||
reg.name = name
|
||||
reg.offset += offset
|
||||
parent.registers[name] = reg
|
||||
offset += incr
|
||||
else:
|
||||
try:
|
||||
parent.registers[str(node.name)] = SVDPeripheralRegister(node, parent)
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
def add_cluster(parent, node):
|
||||
if hasattr(node, "dim"):
|
||||
dim = int(str(node.dim), 0)
|
||||
# dimension is not used, number of split indexes should be same
|
||||
incr = int(str(node.dimIncrement), 0)
|
||||
default_dim_index = ",".join((str(i) for i in range(dim)))
|
||||
dim_index = str(getattr(node, "dimIndex", default_dim_index))
|
||||
indexes = dim_index.split(",")
|
||||
offset = 0
|
||||
for i in indexes:
|
||||
name = str(node.name) % i
|
||||
cluster = SVDRegisterCluster(node, parent)
|
||||
cluster.name = name
|
||||
cluster.address_offset += offset
|
||||
cluster.base_address += offset
|
||||
parent.clusters[name] = cluster
|
||||
offset += incr
|
||||
else:
|
||||
try:
|
||||
parent.clusters[str(node.name)] = SVDRegisterCluster(node, parent)
|
||||
except SVDNonFatalError as e:
|
||||
print(e)
|
||||
|
||||
|
||||
class SVDRegisterCluster:
|
||||
def __init__(self, svd_elem, parent):
|
||||
self.parent = parent
|
||||
self.address_offset = int(str(svd_elem.addressOffset), 0)
|
||||
self.base_address = self.address_offset + parent.base_address
|
||||
# This doesn't inherit registers from anything
|
||||
children = svd_elem.getchildren()
|
||||
self.description = str(svd_elem.description)
|
||||
self.name = str(svd_elem.name)
|
||||
self.registers = OrderedDict()
|
||||
self.clusters = OrderedDict()
|
||||
for r in children:
|
||||
if r.tag == "register":
|
||||
add_register(self, r)
|
||||
|
||||
def refactor_parent(self, parent):
|
||||
self.parent = parent
|
||||
self.base_address = parent.base_address + self.address_offset
|
||||
try:
|
||||
values = self.registers.itervalues()
|
||||
except AttributeError:
|
||||
values = self.registers.values()
|
||||
for r in values:
|
||||
r.refactor_parent(self)
|
||||
|
||||
def __unicode__(self):
|
||||
return str(self.name)
|
||||
|
||||
|
||||
class SVDPeripheral:
|
||||
def __init__(self, svd_elem, parent):
|
||||
self.parent = parent
|
||||
if not hasattr(svd_elem, "baseAddress"):
|
||||
raise SVDNonFatalError("Periph without base address")
|
||||
self.base_address = int(str(svd_elem.baseAddress), 0)
|
||||
if "derivedFrom" in svd_elem.attrib:
|
||||
derived_from = svd_elem.attrib["derivedFrom"]
|
||||
try:
|
||||
self.name = str(svd_elem.name)
|
||||
except:
|
||||
self.name = parent.peripherals[derived_from].name
|
||||
try:
|
||||
self.description = str(svd_elem.description)
|
||||
except:
|
||||
self.description = parent.peripherals[derived_from].description
|
||||
self.registers = deepcopy(parent.peripherals[derived_from].registers)
|
||||
self.clusters = deepcopy(parent.peripherals[derived_from].clusters)
|
||||
self.refactor_parent(parent)
|
||||
else:
|
||||
# This doesn't inherit registers from anything
|
||||
registers = svd_elem.registers.getchildren()
|
||||
self.description = str(svd_elem.description)
|
||||
self.name = str(svd_elem.name)
|
||||
self.registers = OrderedDict()
|
||||
self.clusters = OrderedDict()
|
||||
for r in registers:
|
||||
if r.tag == "cluster":
|
||||
add_cluster(self, r)
|
||||
else:
|
||||
add_register(self, r)
|
||||
|
||||
def refactor_parent(self, parent):
|
||||
self.parent = parent
|
||||
try:
|
||||
values = self.registers.itervalues()
|
||||
except AttributeError:
|
||||
values = self.registers.values()
|
||||
for r in values:
|
||||
r.refactor_parent(self)
|
||||
try:
|
||||
for c in self.clusters.itervalues():
|
||||
c.refactor_parent(self)
|
||||
except AttributeError:
|
||||
for c in self.clusters.values():
|
||||
c.refactor_parent(self)
|
||||
|
||||
def __unicode__(self):
|
||||
return str(self.name)
|
||||
|
||||
|
||||
class SVDPeripheralRegister:
|
||||
def __init__(self, svd_elem, parent):
|
||||
self.parent = parent
|
||||
self.name = str(svd_elem.name)
|
||||
self.description = str(svd_elem.description)
|
||||
self.offset = int(str(svd_elem.addressOffset), 0)
|
||||
try:
|
||||
self.access = str(svd_elem.access)
|
||||
except:
|
||||
self.access = "read-write"
|
||||
try:
|
||||
self.size = int(str(svd_elem.size), 0)
|
||||
except:
|
||||
self.size = 0x20
|
||||
self.fields = OrderedDict()
|
||||
if hasattr(svd_elem, "fields"):
|
||||
fields = svd_elem.fields.getchildren()
|
||||
for f in fields:
|
||||
self.fields[str(f.name)] = SVDPeripheralRegisterField(f, self)
|
||||
|
||||
def refactor_parent(self, parent):
|
||||
self.parent = parent
|
||||
try:
|
||||
fields = self.fields.itervalues()
|
||||
except AttributeError:
|
||||
fields = self.fields.values()
|
||||
for f in fields:
|
||||
f.refactor_parent(self)
|
||||
|
||||
def address(self):
|
||||
return self.parent.base_address + self.offset
|
||||
|
||||
def readable(self):
|
||||
return self.access in ["read-only", "read-write", "read-writeOnce"]
|
||||
|
||||
def writable(self):
|
||||
return self.access in [
|
||||
"write-only",
|
||||
"read-write",
|
||||
"writeOnce",
|
||||
"read-writeOnce",
|
||||
]
|
||||
|
||||
def __unicode__(self):
|
||||
return str(self.name)
|
||||
|
||||
|
||||
class SVDPeripheralRegisterField:
|
||||
def __init__(self, svd_elem, parent):
|
||||
self.parent = parent
|
||||
self.name = str(svd_elem.name)
|
||||
self.description = str(getattr(svd_elem, "description", ""))
|
||||
|
||||
try:
|
||||
self.offset = int(str(svd_elem.bitOffset))
|
||||
self.width = int(str(svd_elem.bitWidth))
|
||||
except:
|
||||
try:
|
||||
bitrange = list(
|
||||
map(int, str(svd_elem.bitRange).strip()[1:-1].split(":"))
|
||||
)
|
||||
self.offset = bitrange[1]
|
||||
self.width = 1 + bitrange[0] - bitrange[1]
|
||||
except:
|
||||
lsb = int(str(svd_elem.lsb))
|
||||
msb = int(str(svd_elem.msb))
|
||||
self.offset = lsb
|
||||
self.width = 1 + msb - lsb
|
||||
self.access = str(getattr(svd_elem, "access", parent.access))
|
||||
self.enum = {}
|
||||
|
||||
if hasattr(svd_elem, "enumeratedValues"):
|
||||
for v in svd_elem.enumeratedValues.getchildren():
|
||||
if v.tag == "name":
|
||||
continue
|
||||
# Some Kinetis parts have values with # instead of 0x...
|
||||
value = str(v.value).replace("#", "0x")
|
||||
self.enum[int(value, 0)] = (str(v.name), str(v.description))
|
||||
|
||||
def refactor_parent(self, parent):
|
||||
self.parent = parent
|
||||
|
||||
def readable(self):
|
||||
return self.access in ["read-only", "read-write", "read-writeOnce"]
|
||||
|
||||
def writable(self):
|
||||
return self.access in [
|
||||
"write-only",
|
||||
"read-write",
|
||||
"writeOnce",
|
||||
"read-writeOnce",
|
||||
]
|
||||
|
||||
def __unicode__(self):
|
||||
return str(self.name)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
for f in sys.argv[1:]:
|
||||
print("Testing file: {}".format(f))
|
||||
svd = SVDFile(f)
|
||||
print(svd.peripherals)
|
||||
key = list(svd.peripherals)[0]
|
||||
print("Registers in peripheral '{}':".format(key))
|
||||
print(svd.peripherals[key].registers)
|
||||
print("Done testing file: {}".format(f))
|
482
debug/PyCortexMDebug/cmdebug/svd_gdb.py
Normal file
482
debug/PyCortexMDebug/cmdebug/svd_gdb.py
Normal file
@@ -0,0 +1,482 @@
|
||||
#!/usr/bin/env python
|
||||
"""
|
||||
This file is part of PyCortexMDebug
|
||||
|
||||
PyCortexMDebug is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
PyCortexMDebug is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with PyCortexMDebug. If not, see <http://www.gnu.org/licenses/>.
|
||||
"""
|
||||
|
||||
import binascii
|
||||
import gdb
|
||||
import re
|
||||
import math
|
||||
import sys
|
||||
import struct
|
||||
import pkg_resources
|
||||
|
||||
sys.path.append(".")
|
||||
from cmdebug.svd import SVDFile
|
||||
|
||||
# from svd_test import *
|
||||
|
||||
BITS_TO_UNPACK_FORMAT = {
|
||||
8: "B",
|
||||
16: "H",
|
||||
32: "I",
|
||||
}
|
||||
|
||||
|
||||
class LoadSVD(gdb.Command):
|
||||
"""A command to load an SVD file and to create the command for inspecting
|
||||
that object
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.vendors = {}
|
||||
try:
|
||||
vendor_names = pkg_resources.resource_listdir("cmsis_svd", "data")
|
||||
for vendor in vendor_names:
|
||||
fnames = pkg_resources.resource_listdir(
|
||||
"cmsis_svd", "data/{}".format(vendor)
|
||||
)
|
||||
self.vendors[vendor] = [
|
||||
fname for fname in fnames if fname.lower().endswith(".svd")
|
||||
]
|
||||
except:
|
||||
pass
|
||||
|
||||
if len(self.vendors) > 0:
|
||||
gdb.Command.__init__(self, "svd_load", gdb.COMMAND_USER)
|
||||
else:
|
||||
gdb.Command.__init__(
|
||||
self, "svd_load", gdb.COMMAND_DATA, gdb.COMPLETE_FILENAME
|
||||
)
|
||||
|
||||
def complete(self, text, word):
|
||||
args = gdb.string_to_argv(text)
|
||||
num_args = len(args)
|
||||
if text.endswith(" "):
|
||||
num_args += 1
|
||||
if not text:
|
||||
num_args = 1
|
||||
|
||||
# "svd_load <tab>" or "svd_load ST<tab>"
|
||||
if num_args == 1:
|
||||
prefix = word.lower()
|
||||
return [
|
||||
vendor for vendor in self.vendors if vendor.lower().startswith(prefix)
|
||||
]
|
||||
# "svd_load STMicro<tab>" or "svd_load STMicro STM32F1<tab>"
|
||||
elif num_args == 2 and args[0] in self.vendors:
|
||||
prefix = word.lower()
|
||||
filenames = self.vendors[args[0]]
|
||||
return [fname for fname in filenames if fname.lower().startswith(prefix)]
|
||||
return gdb.COMPLETE_NONE
|
||||
|
||||
def invoke(self, args, from_tty):
|
||||
args = gdb.string_to_argv(args)
|
||||
argc = len(args)
|
||||
if argc == 1:
|
||||
gdb.write("Loading SVD file {}...\n".format(args[0]))
|
||||
f = args[0]
|
||||
elif argc == 2:
|
||||
gdb.write("Loading SVD file {}/{}...\n".format(args[0], args[1]))
|
||||
f = pkg_resources.resource_filename(
|
||||
"cmsis_svd", "data/{}/{}".format(args[0], args[1])
|
||||
)
|
||||
else:
|
||||
raise gdb.GdbError(
|
||||
"Usage: svd_load <vendor> <device.svd> or svd_load <path/to/filename.svd>\n"
|
||||
)
|
||||
try:
|
||||
SVD(SVDFile(f))
|
||||
except Exception as e:
|
||||
raise gdb.GdbError("Could not load SVD file {} : {}...\n".format(f, e))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# This will also get executed by GDB
|
||||
|
||||
# Create just the svd_load command
|
||||
LoadSVD()
|
||||
|
||||
|
||||
class SVD(gdb.Command):
|
||||
"""The CMSIS SVD (System View Description) inspector command
|
||||
|
||||
This allows easy access to all peripheral registers supported by the system
|
||||
in the GDB debug environment
|
||||
"""
|
||||
|
||||
def __init__(self, svd_file):
|
||||
gdb.Command.__init__(self, "svd", gdb.COMMAND_DATA)
|
||||
self.svd_file = svd_file
|
||||
|
||||
def _print_registers(self, container_name, form, registers):
|
||||
if len(registers) == 0:
|
||||
return
|
||||
try:
|
||||
regs_iter = registers.itervalues()
|
||||
except AttributeError:
|
||||
regs_iter = registers.values()
|
||||
gdb.write("Registers in %s:\n" % container_name)
|
||||
regList = []
|
||||
for r in regs_iter:
|
||||
if r.readable():
|
||||
data = self.read(r.address(), r.size)
|
||||
data = self.format(data, form, r.size)
|
||||
if form == "a":
|
||||
data += (
|
||||
" <"
|
||||
+ re.sub(
|
||||
r"\s+",
|
||||
" ",
|
||||
gdb.execute(
|
||||
"info symbol {}".format(data), True, True
|
||||
).strip(),
|
||||
)
|
||||
+ ">"
|
||||
)
|
||||
else:
|
||||
data = "(not readable)"
|
||||
desc = re.sub(r"\s+", " ", r.description)
|
||||
regList.append((r.name, data, desc))
|
||||
|
||||
column1Width = max(len(reg[0]) for reg in regList) + 2 # padding
|
||||
column2Width = max(len(reg[1]) for reg in regList)
|
||||
for reg in regList:
|
||||
gdb.write(
|
||||
"\t{}:{}{}".format(
|
||||
reg[0],
|
||||
"".ljust(column1Width - len(reg[0])),
|
||||
reg[1].rjust(column2Width),
|
||||
)
|
||||
)
|
||||
if reg[2] != reg[0]:
|
||||
gdb.write(" {}".format(reg[2]))
|
||||
gdb.write("\n")
|
||||
|
||||
def _print_register_fields(self, container_name, form, register):
|
||||
gdb.write("Fields in {}:\n".format(container_name))
|
||||
fields = register.fields
|
||||
if not register.readable():
|
||||
data = 0
|
||||
else:
|
||||
data = self.read(register.address(), register.size)
|
||||
fieldList = []
|
||||
try:
|
||||
fields_iter = fields.itervalues()
|
||||
except AttributeError:
|
||||
fields_iter = fields.values()
|
||||
for f in fields_iter:
|
||||
desc = re.sub(r"\s+", " ", f.description)
|
||||
if register.readable():
|
||||
val = data >> f.offset
|
||||
val &= (1 << f.width) - 1
|
||||
if f.enum:
|
||||
if val in f.enum:
|
||||
desc = f.enum[val][1] + " - " + desc
|
||||
val = f.enum[val][0]
|
||||
else:
|
||||
val = "Invalid enum value: " + self.format(val, form, f.width)
|
||||
else:
|
||||
val = self.format(val, form, f.width)
|
||||
else:
|
||||
val = "(not readable)"
|
||||
fieldList.append((f.name, val, desc))
|
||||
|
||||
column1Width = max(len(field[0]) for field in fieldList) + 2 # padding
|
||||
column2Width = max(len(field[1]) for field in fieldList) # padding
|
||||
for field in fieldList:
|
||||
gdb.write(
|
||||
"\t{}:{}{}".format(
|
||||
field[0],
|
||||
"".ljust(column1Width - len(field[0])),
|
||||
field[1].rjust(column2Width),
|
||||
)
|
||||
)
|
||||
if field[2] != field[0]:
|
||||
gdb.write(" {}".format(field[2]))
|
||||
gdb.write("\n")
|
||||
|
||||
def invoke(self, args, from_tty):
|
||||
s = str(args).split(" ")
|
||||
form = ""
|
||||
if s[0] and s[0][0] == "/":
|
||||
if len(s[0]) == 1:
|
||||
gdb.write("Incorrect format\n")
|
||||
return
|
||||
else:
|
||||
form = s[0][1:]
|
||||
if len(s) == 1:
|
||||
return
|
||||
s = s[1:]
|
||||
|
||||
if s[0].lower() == "help":
|
||||
gdb.write("Usage:\n")
|
||||
gdb.write("=========\n")
|
||||
gdb.write("svd:\n")
|
||||
gdb.write("\tList available peripherals\n")
|
||||
gdb.write("svd [peripheral_name]:\n")
|
||||
gdb.write("\tDisplay all registers pertaining to that peripheral\n")
|
||||
gdb.write("svd [peripheral_name] [register_name]:\n")
|
||||
gdb.write("\tDisplay the fields in that register\n")
|
||||
gdb.write("svd/[format_character] ...\n")
|
||||
gdb.write("\tFormat values using that character\n")
|
||||
gdb.write("\td(default):decimal, x: hex, o: octal, b: binary\n")
|
||||
return
|
||||
|
||||
if not len(s[0]):
|
||||
gdb.write("Available Peripherals:\n")
|
||||
try:
|
||||
peripherals = self.svd_file.peripherals.itervalues()
|
||||
except AttributeError:
|
||||
peripherals = self.svd_file.peripherals.values()
|
||||
columnWidth = max(len(p.name) for p in peripherals) + 2 # padding
|
||||
try:
|
||||
peripherals = self.svd_file.peripherals.itervalues()
|
||||
except AttributeError:
|
||||
peripherals = self.svd_file.peripherals.values()
|
||||
for p in peripherals:
|
||||
desc = re.sub(r"\s+", " ", p.description)
|
||||
gdb.write(
|
||||
"\t{}:{}{}\n".format(
|
||||
p.name, "".ljust(columnWidth - len(p.name)), desc
|
||||
)
|
||||
)
|
||||
return
|
||||
|
||||
registers = None
|
||||
if len(s) >= 1:
|
||||
peripheral_name = s[0]
|
||||
if peripheral_name not in self.svd_file.peripherals:
|
||||
gdb.write("Peripheral {} does not exist!\n".format(s[0]))
|
||||
return
|
||||
|
||||
peripheral = self.svd_file.peripherals[peripheral_name]
|
||||
|
||||
if len(s) == 1:
|
||||
self._print_registers(s[0], form, peripheral.registers)
|
||||
if len(peripheral.clusters) > 0:
|
||||
try:
|
||||
clusters_iter = peripheral.clusters.itervalues()
|
||||
except AttributeError:
|
||||
clusters_iter = peripheral.clusters.values()
|
||||
gdb.write("Clusters in %s:\n" % peripheral_name)
|
||||
regList = []
|
||||
for r in clusters_iter:
|
||||
desc = re.sub(r"\s+", " ", r.description)
|
||||
regList.append((r.name, "", desc))
|
||||
|
||||
column1Width = max(len(reg[0]) for reg in regList) + 2 # padding
|
||||
column2Width = max(len(reg[1]) for reg in regList)
|
||||
for reg in regList:
|
||||
gdb.write(
|
||||
"\t{}:{}{}".format(
|
||||
reg[0],
|
||||
"".ljust(column1Width - len(reg[0])),
|
||||
reg[1].rjust(column2Width),
|
||||
)
|
||||
)
|
||||
if reg[2] != reg[0]:
|
||||
gdb.write(" {}".format(reg[2]))
|
||||
gdb.write("\n")
|
||||
return
|
||||
|
||||
cluster = None
|
||||
if len(s) == 2:
|
||||
container = " ".join(s[:2])
|
||||
if s[1] in peripheral.clusters:
|
||||
self._print_registers(
|
||||
container, form, peripheral.clusters[s[1]].registers
|
||||
)
|
||||
elif s[1] in peripheral.registers:
|
||||
self._print_register_fields(
|
||||
container, form, self.svd_file.peripherals[s[0]].registers[s[1]]
|
||||
)
|
||||
else:
|
||||
gdb.write(
|
||||
"Register/cluster {} in peripheral {} does not exist!\n".format(
|
||||
s[1], s[0]
|
||||
)
|
||||
)
|
||||
return
|
||||
|
||||
if len(s) == 3:
|
||||
if s[1] not in peripheral.clusters:
|
||||
gdb.write(
|
||||
"Cluster {} in peripheral {} does not exist!\n".format(s[1], s[0])
|
||||
)
|
||||
elif s[2] not in peripheral.clusters[s[1]].registers:
|
||||
gdb.write(
|
||||
"Register {} in cluster {} in peripheral {} does not exist!\n".format(
|
||||
s[2], s[1], s[0]
|
||||
)
|
||||
)
|
||||
else:
|
||||
container = " ".join(s[:3])
|
||||
cluster = peripheral.clusters[s[1]]
|
||||
self._print_register_fields(container, form, cluster.registers[s[2]])
|
||||
return
|
||||
|
||||
if len(s) == 4:
|
||||
try:
|
||||
reg = self.svd_file.peripherals[s[0]].registers[s[1]]
|
||||
except KeyError:
|
||||
gdb.write(
|
||||
"Register {} in peripheral {} does not exist!\n".format(s[1], s[0])
|
||||
)
|
||||
return
|
||||
try:
|
||||
field = reg.fields[s[2]]
|
||||
except KeyError:
|
||||
gdb.write(
|
||||
"Field {} in register {} in peripheral {} does not exist!\n".format(
|
||||
s[2], s[1], s[0]
|
||||
)
|
||||
)
|
||||
return
|
||||
|
||||
if not field.writable() or not reg.writable():
|
||||
gdb.write(
|
||||
"Field {} in register {} in peripheral {} is read-only!\n".format(
|
||||
s[2], s[1], s[0]
|
||||
)
|
||||
)
|
||||
return
|
||||
|
||||
try:
|
||||
val = int(s[3], 0)
|
||||
except ValueError:
|
||||
gdb.write(
|
||||
"{} is not a valid number! You can prefix numbers with 0x for hex, 0b for binary, or any python int literal\n".format(
|
||||
s[3]
|
||||
)
|
||||
)
|
||||
return
|
||||
|
||||
if val >= 1 << field.width or val < 0:
|
||||
gdb.write(
|
||||
"{} not a valid number for a field with width {}!\n".format(
|
||||
val, field.width
|
||||
)
|
||||
)
|
||||
return
|
||||
|
||||
if not reg.readable():
|
||||
data = 0
|
||||
else:
|
||||
data = self.read(reg.address(), reg.size)
|
||||
data &= ~(((1 << field.width) - 1) << field.offset)
|
||||
data |= (val) << field.offset
|
||||
self.write(reg.address(), data, reg.size)
|
||||
return
|
||||
|
||||
gdb.write("Unknown input\n")
|
||||
|
||||
def complete(self, text, word):
|
||||
"""Perform tab-completion for the command"""
|
||||
text = str(text)
|
||||
s = text.split(" ")
|
||||
|
||||
# Deal with the possibility of a '/' parameter
|
||||
if s[0] and s[0][0] == "/":
|
||||
if len(s) > 1:
|
||||
s = s[1:]
|
||||
else:
|
||||
return
|
||||
|
||||
if len(s) == 1:
|
||||
return filter(
|
||||
lambda x: x.lower().startswith(s[0].lower()),
|
||||
self.peripheral_list() + ["help"],
|
||||
)
|
||||
|
||||
if len(s) == 2:
|
||||
reg = s[1].upper()
|
||||
if len(reg) and reg[0] == "&":
|
||||
reg = reg[1:]
|
||||
filt = filter(lambda x: x.startswith(reg), self.register_list(s[0].upper()))
|
||||
return filt
|
||||
|
||||
def read(self, address, bits=32):
|
||||
"""Read from memory and return an integer"""
|
||||
value = gdb.selected_inferior().read_memory(address, bits / 8)
|
||||
unpack_format = "I"
|
||||
if bits in BITS_TO_UNPACK_FORMAT:
|
||||
unpack_format = BITS_TO_UNPACK_FORMAT[bits]
|
||||
# gdb.write("{:x} {}\n".format(address, binascii.hexlify(value)))
|
||||
return struct.unpack_from("<" + unpack_format, value)[0]
|
||||
|
||||
def write(self, address, data, bits=32):
|
||||
"""Write data to memory"""
|
||||
gdb.selected_inferior().write_memory(address, bytes(data), bits / 8)
|
||||
|
||||
def format(self, value, form, length=32):
|
||||
"""Format a number based on a format character and length"""
|
||||
# get current gdb radix setting
|
||||
radix = int(
|
||||
re.search("\d+", gdb.execute("show output-radix", True, True)).group(0)
|
||||
)
|
||||
|
||||
# override it if asked to
|
||||
if form == "x" or form == "a":
|
||||
radix = 16
|
||||
elif form == "o":
|
||||
radix = 8
|
||||
elif form == "b" or form == "t":
|
||||
radix = 2
|
||||
|
||||
# format the output
|
||||
if radix == 16:
|
||||
# For addresses, probably best in hex too
|
||||
l = int(math.ceil(length / 4.0))
|
||||
return "0x" + "{:X}".format(value).zfill(l)
|
||||
if radix == 8:
|
||||
l = int(math.ceil(length / 3.0))
|
||||
return "0" + "{:o}".format(value).zfill(l)
|
||||
if radix == 2:
|
||||
return "0b" + "{:b}".format(value).zfill(length)
|
||||
# Default: Just return in decimal
|
||||
return str(value)
|
||||
|
||||
def peripheral_list(self):
|
||||
try:
|
||||
keys = self.svd_file.peripherals.iterkeys()
|
||||
except AttributeError:
|
||||
keys = elf.svd_file.peripherals.keys()
|
||||
return list(keys)
|
||||
|
||||
def register_list(self, peripheral):
|
||||
try:
|
||||
try:
|
||||
keys = self.svd_file.peripherals[peripheral].registers.iterkeys()
|
||||
except AttributeError:
|
||||
keys = self.svd_file.peripherals[peripheral].registers.keys()
|
||||
return list(keys)
|
||||
except:
|
||||
gdb.write("Peripheral {} doesn't exist\n".format(peripheral))
|
||||
return []
|
||||
|
||||
def field_list(self, peripheral, register):
|
||||
try:
|
||||
periph = svd_file.peripherals[peripheral]
|
||||
reg = periph.registers[register]
|
||||
try:
|
||||
regs = reg.fields.iterkeys()
|
||||
except AttributeError:
|
||||
regs = reg.fields.keys()
|
||||
return list(regs)
|
||||
except:
|
||||
gdb.write("Register {} doesn't exist on {}\n".format(register, peripheral))
|
||||
return []
|
Reference in New Issue
Block a user