Beispiel #1
0
    def data_from_svd(self, cmsis_svd_datapath, segment_size, vendor, chip):
        if vendor == None:
            self.vendors = os.listdir(cmsis_svd_datapath)
            for v in self.vendors:
                self.data_top_hash["vendors"][v] = {}
                for f in glob.glob(os.path.join(cmsis_svd_datapath, v,
                                                '*.svd')):
                    c = f.split(os.path.sep)[-1][:-4]
                    self.data_top_hash["vendors"][v][c] = {}
                    self.data_top_hash["vendors"][v][c]["file"] = f
                    self.data_top_hash["vendors"][v][c]["dirty"] = True
        else:
            self.vendors = [vendor]
            self.data_top_hash["vendors"][vendor] = {}
            if (chip):
                self.data_top_hash["vendors"][vendor][chip] = {}
                self.data_top_hash["vendors"][vendor][chip][
                    "file"] = os.path.join(cmsis_svd_datapath, vendor,
                                           chip + '.svd')
                self.data_top_hash["vendors"][vendor][chip]["dirty"] = True
            else:
                for f in glob.glob(
                        os.path.join(cmsis_svd_datapath, vendor, '*.svd')):
                    c = f.split(os.path.sep)[-1][:-4]
                    self.data_top_hash["vendors"][vendor][c] = {}
                    self.data_top_hash["vendors"][vendor][c]["file"] = f
                    self.data_top_hash["vendors"][vendor][c]["dirty"] = True

            #print(   self.data_top_hash)
        for v in self.data_top_hash["vendors"].keys():
            for c in sorted(self.data_top_hash["vendors"][v].keys()):
                print(v, c)
                self.parse_chip_svd(self.data_top_hash["vendors"][v][c],
                                    SVDParser.for_packaged_svd(v, c + '.svd'))
Beispiel #2
0
    def invoke(self, arg, from_tty):
        args = gdb.string_to_argv(arg)
        if len(args) >= 1:
            if args[0] not in self.vendors:
                raise gdb.GdbError("Invalid vendor name")
                return
            vendor_name = args[0]
            vendor_filenames = self.vendors[vendor_name]
            if len(args) == 1:
                raise gdb.GdbError(
                    "Usage: svd_load <vendor-name> <filename.svd>")
            elif len(args) >= 2:
                filename = args[1]
                try:
                    parser = SVDParser.for_packaged_svd(vendor_name, filename)
                    _svd_printer.set_device(parser.get_device())
                except IOError:
                    raise gdb.GdbError("Failed to load SVD file")
                else:
                    print("Loaded {}/{}".format(vendor_name, filename))

                    for peripheral in _svd_printer.device.peripherals:
                        print("%s @ 0x%08x" %
                              (peripheral.name, peripheral.base_address))

        else:
            raise gdb.GdbError("Usage: svd_load <vendor-name> <filename.svd>")
Beispiel #3
0
    def load(self):
        if not isCmsisSvdAvailable:
            return

        if self.is_local:
            self.device = SVDParser.for_xml_file(self.filename).get_device()
        else:
            self.device = SVDParser.for_packaged_svd(self.vendor, self.filename).get_device()
Beispiel #4
0
def load_svd(self, vendor, file):
    parser = SVDParser.for_packaged_svd(vendor, file)
    for peripheral in parser.get_device().peripherals:
        p_dict = peripheral.to_dict()
        base_addr = p_dict['base_address']
        size = int(p_dict['address_block']['size']) - 1  #hackhack
        name = peripheral.name
        self.add_memory_range(base_addr, size)
Beispiel #5
0
    def load(self):
        if not isCmsisSvdAvailable:
            return

        if self.is_local:
            self.device = SVDParser.for_xml_file(self.filename).get_device()
        else:
            self.device = SVDParser.for_packaged_svd(self.vendor, self.filename).get_device()
def get_parser(mcu, svd):
    try:
        if mcu:
            return SVDParser.for_packaged_svd(mcu[0], "{}.svd".format(mcu[1]))
        return SVDParser(ET.ElementTree(ET.fromstring(svd.read())))
    except IOError:
        print("No SVD file found")
        sys.exit()
Beispiel #7
0
def get_parser(mcu, svd):
    try:
        if mcu:
            return SVDParser.for_packaged_svd(mcu[0], "{}.svd".format(mcu[1]))
        return SVDParser(ET.ElementTree(ET.fromstring(svd.read())))
    except IOError:
        print("No SVD file found")
        sys.exit()
Beispiel #8
0
def main():
    parser = SVDParser.for_packaged_svd('Nordic', 'nrf51.svd')
    #dump_json(parser)
    interrupts = get_peripheral_interrupts(parser)
    dump_macros(interrupts,
            open("src/chips/nrf51822/peripheral_interrupts.h", "w"))
    peripherals = get_peripheral_registers(parser, ["GPIO"])
    dump_registers(peripherals,
            open("src/chips/nrf51822/peripheral_registers.rs", "w"))
Beispiel #9
0
def main():
    parser = SVDParser.for_packaged_svd('STMicro', 'STM32F0xx.svd')
    address2peripheral = {}
    for peripheral in parser.get_device().peripherals:
        address2peripheral[peripheral.base_address] = peripheral
    for _, peripheral in sorted(address2peripheral.items()):
        print(f'{peripheral.name: <16} @ 0x{peripheral.base_address:08x}')
    svd_dict = parser.get_device().to_dict()
    print(json.dumps(svd_dict, sort_keys=True, indent=4))
Beispiel #10
0
    def load(self):
        if not IS_CMSIS_SVD_AVAILABLE:
            return

        if self.is_local:
            self.device = SVDParser.for_xml_file(self.filename).get_device()
        else:
            self.device = SVDParser.for_packaged_svd(
                self.vendor, self.filename).get_device()
Beispiel #11
0
    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]))
            parser = SVDParser.for_xml_file(svd_file)
        elif argc == 2:
            gdb.write("Loading SVD file {}/{}...\n".format(args[0], args[1]))
            parser = SVDParser.for_packaged_svd(vendor, device)

        self.dont_repeat()
Beispiel #12
0
def main():
    from jinja2 import Environment, FileSystemLoader

    parser = SVDParser.for_packaged_svd('Nordic', 'nrf51.svd')
    #dump_json(parser)
    interrupts = get_peripheral_interrupts(parser)
    dump_macros(interrupts,
            open("src/chips/nrf51822/peripheral_interrupts.h", "w"))
    peripherals = get_peripheral_registers(parser, ["GPIO"])

    env = Environment(loader=FileSystemLoader('src/chips/nrf51822'))
    template = env.get_template('peripheral_registers.rs.jinja')
    template.stream(program=PROGRAM, peripherals=peripherals).dump(
            'src/chips/nrf51822/peripheral_registers.rs')
Beispiel #13
0
def main():
    from jinja2 import Environment, FileSystemLoader

    parser = SVDParser.for_packaged_svd('Nordic', 'nrf51.svd')
    #dump_json(parser)
    interrupts = get_peripheral_interrupts(parser)
    dump_macros(interrupts,
                open("src/chips/nrf51822/src/peripheral_interrupts.h", "w"))
    peripherals = get_peripheral_registers(parser, ["GPIO"])

    env = Environment(loader=FileSystemLoader('src/chips/nrf51822/src'))
    template = env.get_template('peripheral_registers.rs.jinja')
    template.stream(program=PROGRAM, peripherals=peripherals).dump(
        'src/chips/nrf51822/src/peripheral_registers.rs')
Beispiel #14
0
def parseFile(company, file):
    print("Parsing %s,%s " % (company, file))
    parser = SVDParser.for_packaged_svd(company, file + ".svd", 1)
    extention = []
    jsonPath = posixpath.join(posixpath.dirname(posixpath.abspath(__file__)),
                              "Extention", company, file + ".json")
    #print(jsonPath)
    device = parser.get_device()
    if posixpath.isfile(jsonPath):
        extFile = open(jsonPath, "r", encoding='utf-8')
        extention = json.load(extFile)
    subdir = Ft.formatCpuName(Ft.getKey(extention, ["device", "cpu", "name"]),
                              device)
    chipDir = posixpath.join('..', '..', 'Lib', 'Chip')
    subdir = posixpath.join(chipDir, subdir)
    if not posixpath.exists(subdir):
        os.makedirs(subdir)
    subdir = posixpath.join(subdir, company)
    if not posixpath.exists(subdir):
        os.makedirs(subdir)
    subdir = posixpath.join(subdir, file)
    if not posixpath.exists(subdir):
        os.makedirs(subdir)
    chipText = "#pragma once \n"
    chipText += "#include <cstdint>\n"
    incDir = subdir[10:]
    if Ft.getKey(extention, ["kvasir", "io"]):
        parseIo(extention, device, subdir)
        chipText += "#include <%s>\n" % (posixpath.join(incDir, "Io.hpp"))
    for peripheral in device.peripherals:
        if peripheral.name is not None:
            chipText += "#include <%s>\n" % (posixpath.join(
                incDir, peripheral.name + ".hpp"))
            out = "#pragma once \n#include <Register/Utility.hpp>\n"
            out += "namespace Kvasir {\n"
            out += parsePeripheral(
                peripheral, Ft.getKey(extention, ['.' + peripheral.name]))
            out += "}\n"

            outFile = open(posixpath.join(subdir, peripheral.name + ".hpp"),
                           'w',
                           encoding='utf-8')
            outFile.write(out)
        else:
            print("error no name in %s" % (file))
    outFile = open(posixpath.join(chipDir, file + ".hpp"),
                   'w',
                   encoding='utf-8')
    outFile.write(chipText)
Beispiel #15
0
def main():
    parser = SVDParser.for_packaged_svd(sys.argv[1], sys.argv[2] + '.svd')
    device = parser.get_device()

    zig_fmt = subprocess.Popen(('zig', 'fmt', '--stdin'),
                               stdin=subprocess.PIPE,
                               stdout=subprocess.PIPE,
                               encoding='utf8')

    generator = MMIOFileGenerator(zig_fmt.stdin)
    generator.generate_file(device)

    zig_fmt.stdin.flush()
    zig_fmt.stdin.close()
    print(zig_fmt.stdout.read())
Beispiel #16
0
def main(mcu, mcu_peripheral=None):
    """Given a chip and peripheral, prints the registers.
    """
    parser = SVDParser.for_packaged_svd(*MCU2VENDOR_FILE[mcu])
    address2peripheral = {}
    for peripheral in parser.get_device().peripherals:
        address2peripheral[peripheral.base_address] = peripheral
    for _, peripheral in sorted(address2peripheral.items()):
        print(
            f'{peripheral.name: <16} @ 0x{peripheral.base_address:08x} ({peripheral.address_block.size: >4})'
        )
    if mcu_peripheral:
        for peripheral in parser.get_device().peripherals:
            if peripheral.name == mcu_peripheral or mcu_peripheral == ALL:
                show_peripheral(peripheral)
Beispiel #17
0
def parseFile(company,file):
    print("Parsing %s,%s " % (company,file))
    parser = SVDParser.for_packaged_svd(company, file + ".svd",1,1)
    extention = []
    jsonPath = os.path.join(os.path.dirname(os.path.abspath(__file__)),"Extention",company,file+".json")
    #print(jsonPath)
    device = parser.get_device()
    if os.path.isfile(jsonPath):
        extFile = open(jsonPath,"r",encoding='utf-8')
        extention = json.load(extFile)
    subdir = Ft.formatCpuName(Ft.getKey(extention,["device","cpu","name"]),device)
    chipDir = os.path.join('..','..','Lib','Chip')
    subdir = os.path.join(chipDir, subdir)
    if not os.path.exists(subdir):
        os.makedirs(subdir)
    subdir = os.path.join(subdir,company)
    if not os.path.exists(subdir):
        os.makedirs(subdir)
    subdir = os.path.join(subdir,file)
    if not os.path.exists(subdir):
        os.makedirs(subdir)
    chipText = "#pragma once \n"
    incDir = subdir[10:]
    if Ft.getKey(extention,["kvasir","io"]):
        parseIo(extention,device,subdir)
        chipText += "#include \"%s\"\n" % (os.path.join(incDir,"Io.hpp"))
    for peripheral in device.peripherals:
        if peripheral.name is not None:
            chipText += "#include \"%s\"\n" % (os.path.join(incDir,peripheral.name+".hpp"))
            out = "#pragma once \n#include \"Register/Utility.hpp\"\n"
            out += "namespace Kvasir {\n"
            out += parsePeripheral(peripheral,Ft.getKey(extention,['.'+peripheral.name]))
            out += "}\n"

            outFile = open(os.path.join(subdir,peripheral.name+".hpp"), 'w',encoding='utf-8')
            outFile.write(out)
        else:
            print("error no name in %s" % (file))
    outFile = open(os.path.join(chipDir,file + ".hpp"), 'w',encoding='utf-8')
    outFile.write(chipText)
Beispiel #18
0
 def test_packaged_xml(self):
     parser = SVDParser.for_packaged_svd('Freescale', 'MK20D7.svd')
     device = parser.get_device()
     self.assertTrue(len(device.peripherals) > 0)
Beispiel #19
0
 def test_derived_from_registers(self):
     parser = SVDParser.for_packaged_svd('ARM_SAMPLE', 'ARM_Sample.svd')
     regs = {p.name: p.registers for p in parser.get_device().peripherals}
     self.assertEqual(len(regs["TIMER0"]), len(regs["TIMER1"]))
     self.assertEqual(len(regs["TIMER0"]), len(regs["TIMER2"]))
     self.assertEqual(len(regs["TIMER1"]), len(regs["TIMER2"]))
Beispiel #20
0
 def load(self):
     if self.is_local:
         self.device = SVDParser.for_xml_file(self.filename).get_device()
     else:
         self.device = SVDParser.for_packaged_svd(self.vendor, self.filename).get_device()
#
# Copyright 2015 Paul Osborne <*****@*****.**>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from cmsis_svd.parser import SVDParser

parser = SVDParser.for_packaged_svd('Freescale', 'MK20D7.xml')
for peripheral in parser.get_device().peripherals:
    print("%s @ 0x%08x" % (peripheral.name, peripheral.base_address))
Beispiel #22
0
def banner(x):
    comment('==== {:=<55}'.format("%s " % x))


def caption(x):
    print()
    comment('---- {:-<55}'.format("%s " % x))


def comment(x):
    print(comment_str(x))


# ------------------------------------

parser = SVDParser.for_packaged_svd('STMicro', svd_name)
device = parser.get_device()

print()
banner('%s PERIPHERALS' % device.name)
comment('')
comment('CTU Prague, FEL, Department of Measurement')
comment('')
comment('-' * 60)
comment('')
comment('Generated from "%s"' % svd_name)
comment('')
comment('SVD parsing library (c) Paul Osborne, 2015-2016')
comment('    https://github.com/posborne/cmsis-svd')
comment('ASM building script (c) Ondrej Hruska, 2016')
comment('')
Beispiel #23
0
def load_svd_for_mcu(mcu):
    vendor, filename = find_for_mcu(mcu)
    if (vendor is None) or (filename is None):
        return None
    return SVDParser.for_packaged_svd(vendor, filename).get_device()
Beispiel #24
0
if (svd_file != None):
    parser = SVDParser.for_xml_file(svd_file)
elif (selected_device != None):
    device = None
    dev = selected_device.lower().replace(".svd", "")
    for v in pkg_resources.resource_listdir("cmsis_svd", "data"):
        for d in pkg_resources.resource_listdir("cmsis_svd", "data/%s" % (v)):
            if (dev == d.lower().replace(".svd", "")):
                device = d
                vendor = v

    if (device == None):
        print("Could not find %s in cmsis_svd data." % (selected_device))
        exit(1)

    parser = SVDParser.for_packaged_svd(vendor, device)
else:
    print("No device selected.")
    usage()
    exit(1)

device_name = parser.get_device().name

if (output):
    try:
        os.mkdir(device_name)
    except:
        pass

if (selected_peripheral == None):
    memorymap_str = "#pragma once \n\n"
Beispiel #25
0
#
# Copyright 2015 Paul Osborne <*****@*****.**>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from cmsis_svd.parser import SVDParser

parser = SVDParser.for_packaged_svd('Freescale', 'MK20D7.svd')
for peripheral in parser.get_device().peripherals:
    print("%s @ 0x%08x" % (peripheral.name, peripheral.base_address))
# pip install -U cmsis-svd
# python3 nrf51.py >> nrf51.flags.r2

from cmsis_svd.parser import SVDParser

parser = SVDParser.for_packaged_svd('Nordic', 'nrf51.svd')
for peripheral in parser.get_device().peripherals:
    print("f %s = 0x%08x" % (peripheral.name, peripheral.base_address))
    for register in peripheral.registers:
        print("f %s.%s = 0x%08x" %
              (peripheral.name, register.name,
               peripheral.base_address + register.address_offset))
	print(comment_str(x))

def banner(x):
	comment('==== {:=<55}'.format("%s " % x))

def caption(x):
	print()
	comment('---- {:-<55}'.format("%s " % x))

def comment(x):
	print(comment_str(x))


# ------------------------------------

parser = SVDParser.for_packaged_svd('STMicro', svd_name)
device = parser.get_device()

print()
banner('%s PERIPHERALS' % device.name)
comment('')
comment('CTU Prague, FEL, Department of Measurement')
comment('')
comment('-' * 60)
comment('')
comment('Generated from "%s"' % svd_name)
comment('')
comment('SVD parsing library (c) Paul Osborne, 2015-2016')
comment('    https://github.com/posborne/cmsis-svd')
comment('ASM building script (c) Ondrej Hruska, 2016')
comment('')
Beispiel #28
0
            print('\n'.join(vendors))
        elif argc == 2:
            svds = pkg_resources.resource_listdir("cmsis_svd",
                                                  "data/%s" % (sys.argv[1]))
            print('\n'.join(svds))
        else:
            raise Exception('')
    except:
        print('Usage: .!r2svd [mcu] [svd]')
        sys.exit(1)
    sys.exit(0)

mcu = sys.argv[1]  # Freescale
svd = sys.argv[2]  # MK20D7.svd

parser = SVDParser.for_packaged_svd(mcu, svd)
svd_dict = parser.get_device().to_dict()
for p in svd_dict['peripherals']:
    addr = p['base_address']
    size = p['address_block']['size'] / 8
    print("CC %s @ 0x%x" % (p['description'], addr))
    print("f %s %d 0x%x" % (p['name'], size, addr))
    s = ""
    for r in p['registers']:
        offs = int(r['address_offset'])
        at = int(addr) + math.floor(offs / 8)
        bt = (offs % 8)
        s += " " + r['name']
        if at != addr:
            print("f %s.%s %d 0x%x" % (p['name'], r['name'], size, at))
        # print("   0x%x %d %s"%(at, bt, r['name']))
Beispiel #29
0
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Simple script for ida loadProcConfig configuration file generator
#
from cmsis_svd.parser import SVDParser

parser = SVDParser.for_packaged_svd('STMicro', 'STM32F105xx.svd')
allregs = []
blocksize = 0x400 - 1

fmt = "{:28}{:28}{:12}"
for peripheral in parser.get_device().peripherals:
    col1 = "area DATA " + peripheral.name
    base = peripheral.base_address
    if peripheral._address_block == None:
        limit= base + blocksize
    else:
        limit= base + peripheral._address_block.size - 1
        blocksize = peripheral._address_block.size - 1

    col2 = "0x{0:08X}:0x{1:08X}".format(base, limit)
    col3 = peripheral.name
import json
from cmsis_svd.parser import SVDParser

parser = SVDParser.for_packaged_svd('STMicro', 'STM32F042x.svd')
svd_dict = parser.get_device().to_dict()
print(json.dumps(svd_dict, sort_keys=True,
                 indent=4, separators=(',', ': ')))