Created
August 4, 2015 04:32
-
-
Save mcoffin/93bb625eb352d2314d62 to your computer and use it in GitHub Desktop.
reglist-lvbitx.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import argparse | |
from xml.etree import ElementTree | |
from operator import attrgetter | |
import json | |
import re | |
class Register: | |
def __init__(self, name, offset, length, registers=None): | |
self.name = name | |
self.offset = offset | |
self.length = length | |
self.registers = registers | |
def __str__(self): | |
return "%(name)s (%(length)d) @ %(offset)d" % {"name": self.name, "offset": self.offset, "length": self.length} | |
explicit_datatype_expr = re.compile(r'^[UI](?P<length>\d+)$') | |
def parse_datatype_length(datatype_elem): | |
datatype = datatype_elem.tag | |
length = -1 | |
m = explicit_datatype_expr.match(datatype) | |
if m: | |
length = int(m.group('length')) | |
elif datatype == "Boolean": | |
length = 1 | |
elif datatype == "Array": | |
arr_size = int(datatype_elem.find("./Size").text) | |
elem_len = parse_datatype_length(datatype_elem.find("./Type")[0]) | |
length = arr_size * elem_len | |
if length < 0: | |
raise ValueError("Unknown datatype: %s" % datatype) | |
return length | |
def deflatten_registers(flat_registers): | |
""" | |
Flattens a list of XML registers with dot-separated names | |
into a usable list of real registers | |
""" | |
registers = [] | |
for reg in flat_registers: | |
# Parse things given to use by XML | |
flat_name = reg.find("./Name").text | |
offset = int(reg.find("./Offset").text) | |
length = parse_datatype_length(reg.find("./Datatype")[0]) | |
# If we didn't parse a length properly, throw | |
if length < 0: | |
raise ValueError("Unknown datatype: %s" % datatype) | |
# Create register | |
new_reg = Register(flat_name, offset, length) | |
registers.append(new_reg) | |
# Sort registers in the order they would appear in memory | |
registers = sorted(registers, key=attrgetter('offset')) | |
return registers | |
def main(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument("input", type=str, help="input file path") | |
args = parser.parse_args() | |
tree = ElementTree.parse(args.input) | |
root = tree.getroot() | |
registers = root.findall("./VI/RegisterList/Register") | |
registers = deflatten_registers(registers) | |
for reg in registers: | |
print(reg) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment