Add software

This commit is contained in:
RocketGod
2022-09-22 09:26:57 -07:00
parent fee0ab05fd
commit 957ea3d712
4511 changed files with 1943182 additions and 0 deletions

View File

@ -0,0 +1,73 @@
#!/usr/bin/env python
# Copyright 2013 Jared Boone
#
# Interpret the LPC43xx Clock Generation Unit (CGU) FREQ_MON register
# and display the estimated clock frequency.
#
# This file is part of HackRF.
#
# This program 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 2, or (at your option)
# any later version.
#
# This program 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 this program; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
"""
Inside GDB:
(gdb) set {int}0x40050014 = 0x09800000
(gdb) x 0x40050014
0x40050014: 0x091bd000
This script:
./check_clock.py 0x<register value> 0x<RCNT initial value>
"""
import sys
clock_source_names = {
0x00: '32 kHz oscillator',
0x01: 'IRC',
0x02: 'ENET_RX_CLK',
0x03: 'ENET_TX_CLK',
0x04: 'GP_CLKIN',
0x06: 'Crystal oscillator',
0x07: 'PLL0USB',
0x08: 'PLL0AUDIO',
0x09: 'PLL1',
0x0c: 'IDIVA',
0x0d: 'IDIVB',
0x0e: 'IDIVC',
0x0f: 'IDIVD',
0x10: 'IDIVE',
}
reg_value = int(sys.argv[1], 16)
rcnt = int(sys.argv[2], 16)
print('0x%08x' % reg_value)
rcnt_final = reg_value & 0x1ff
fcnt = (reg_value >> 9) & 0x3fff
clock_source = (reg_value >> 24) & 0x1f
fref = 12e6
if rcnt_final != 0:
raise RuntimeError('RCNT did not reach 0')
print('RCNT: %d' % rcnt)
print('FCNT: %d' % fcnt)
print('Fref: %d' % fref)
clock_hz = fcnt / float(rcnt) * fref
clock_mhz = clock_hz / 1e6
clock_name = clock_source_names[clock_source] if clock_source in clock_source_names else 'Reserved'
print('%s: %.3f MHz' % (clock_name, clock_mhz))

View File

@ -0,0 +1,278 @@
#!/usr/bin/env python3
# Xilinx CoolRunner II XC2C64A characteristics
bits_of_address = 7
bits_of_data = 274
bytes_of_data = (bits_of_data + 7) // 8
bits_in_program_row = bits_of_address + bits_of_data
address_sequence = (0x00, 0x40, 0x60, 0x20, 0x30, 0x70, 0x50, 0x10, 0x18, 0x58, 0x78, 0x38, 0x28, 0x68, 0x48, 0x08, 0x0c, 0x4c, 0x6c, 0x2c, 0x3c, 0x7c, 0x5c, 0x1c, 0x14, 0x54, 0x74, 0x34, 0x24, 0x64, 0x44, 0x04, 0x06, 0x46, 0x66, 0x26, 0x36, 0x76, 0x56, 0x16, 0x1e, 0x5e, 0x7e, 0x3e, 0x2e, 0x6e, 0x4e, 0x0e, 0x0a, 0x4a, 0x6a, 0x2a, 0x3a, 0x7a, 0x5a, 0x1a, 0x12, 0x52, 0x72, 0x32, 0x22, 0x62, 0x42, 0x02, 0x03, 0x43, 0x63, 0x23, 0x33, 0x73, 0x53, 0x13, 0x1b, 0x5b, 0x7b, 0x3b, 0x2b, 0x6b, 0x4b, 0x0b, 0x0f, 0x4f, 0x6f, 0x2f, 0x3f, 0x7f, 0x5f, 0x1f, 0x17, 0x57, 0x77, 0x37, 0x27, 0x67, 0x47, 0x07, 0x05, 0x45,)
def values_list_line_wrap(values):
line_length = 16
return [' '.join(values[n:n+line_length]) for n in range(0, len(values), line_length)]
def dec_lines(bytes):
return values_list_line_wrap(['%d,' % n for n in bytes])
def hex_lines(bytes):
return values_list_line_wrap(['0x%02x,' % n for n in bytes])
def reverse_bits(n, bit_count):
byte_count = (bit_count + 7) >> 3
# n = int(bytes.hex(), 16)
n_bits = bin(n)[2:].zfill(bit_count)
n_bits_reversed = n_bits[::-1]
n_reversed = int(n_bits_reversed, 2)
return n_reversed.to_bytes(byte_count, byteorder='little')
def extract_addresses(block):
return tuple([row['address'] for row in block])
def extract_data(block):
return tuple([row['data'] for row in block])
def extract_mask(block):
return tuple([row['mask'] for row in block])
def equal_blocks(block1, block2, mask):
block1_data = extract_data(block1)
block2_data = extract_data(block2)
assert(len(block1_data) == len(block2_data))
assert(len(block1_data) == len(mask))
for row1, row2, mask in zip(block1_data, block2_data, mask):
differences = (row1 ^ row2) & mask
if differences != 0:
return False
return True
def dump_block(rows, endian='little'):
data_bytes = (bits_of_data + 7) >> 3
for row in rows:
print('%02x %s' % (row['address'], row['data'].to_bytes(data_bytes, byteorder=endian).hex()))
def extract_programming_data(commands):
ir_map = {
0x01: 'idcode',
0xc0: 'conld',
0xe8: 'enable',
0xea: 'program',
0xed: 'erase',
0xee: 'verify',
0xf0: 'init',
0xff: 'bypass',
# Other instructions unimplemented and if encountered, will cause tool to crash.
}
ir = None
program = []
verify = []
for command in commands:
if command['type'] == 'xsir':
ir = ir_map[command['tdi']['data'][0]]
if ir == 'program':
program.append([])
if ir == 'verify':
verify.append([])
elif ir == 'verify' and command['type'] == 'xsdrtdo':
tdi_length = command['tdi']['length']
end_state = command['end_state']
if tdi_length == bits_of_address and end_state == 1:
address = int(command['tdi']['data'].hex(), 16)
verify[-1].append({'address': address})
elif tdi_length == bits_of_data and end_state == 0:
mask = int(command['tdo_mask']['data'].hex(), 16)
expected = int(command['tdo_expected']['data'].hex(), 16)
verify[-1][-1]['data'] = expected
verify[-1][-1]['mask'] = mask
elif ir == 'program' and command['type'] == 'xsdrtdo':
tdi_length = command['tdi']['length']
end_state = command['end_state']
if tdi_length == bits_in_program_row and end_state == 0:
tdi = int(command['tdi']['data'].hex(), 16)
address = (tdi >> bits_of_data) & ((1 << bits_of_address) - 1)
data = tdi & ((1 << bits_of_data) - 1)
program[-1].append({
'address': address,
'data': data
})
return {
'program': program,
'verify': verify,
}
def validate_programming_data(programming_data):
# Validate program blocks:
# There should be two extracted program blocks. The first contains the
# the bitstream with done bit(s) not asserted. The second updates the
# "done" bit(s) to finish the process.
assert(len(programming_data['program']) == 2)
# First program phase writes the bitstream to flash (or SRAM) with
# special bit(s) not asserted, so the bitstream is not yet valid.
assert(extract_addresses(programming_data['program'][0]) == address_sequence)
# Second program phase updates a single row to finish the programming
# process.
assert(len(programming_data['program'][1]) == 1)
assert(programming_data['program'][1][0]['address'] == 0x05)
# Validate verify blocks:
# There should be two extracted verify blocks.
assert(len(programming_data['verify']) == 2)
# The two verify blocks should match.
assert(programming_data['verify'][0] == programming_data['verify'][1])
# Check the row address order of the second verify block.
assert(extract_addresses(programming_data['verify'][0]) == address_sequence)
assert(extract_addresses(programming_data['verify'][1]) == address_sequence)
# Checks across programming and verification:
# Check that program data matches data expected during verification.
assert(equal_blocks(programming_data['program'][0], programming_data['verify'][0], extract_mask(programming_data['verify'][0])))
assert(equal_blocks(programming_data['program'][0], programming_data['verify'][1], extract_mask(programming_data['verify'][1])))
def make_sram_program(program_blocks):
program_sram = list(program_blocks[0])
program_sram[-2] = program_blocks[1][0]
return program_sram
#######################################################################
# Command line argument parsing.
#######################################################################
import argparse
parser = argparse.ArgumentParser()
action_group = parser.add_argument_group(title='outputs')
action_group.add_argument('--checksum', action='store_true', help='Print bitstream verification CRC32 value')
action_group.add_argument('--hackrf-data', type=str, help='C data file for HackRF bitstream loading/programming/verification')
action_group.add_argument('--portapack-data', type=str, help='C++ data file for PortaPack bitstream loading/programming/verification')
parser.add_argument('--crcmod', action='store_true', help='Use Python crcmod library instead of built-in CRC32 code')
parser.add_argument('--debug', action='store_true', help='Enable debug output')
parser.add_argument('--xsvf', required=True, type=str, help='HackRF Xilinx XC2C64A CPLD XSVF file containing erase/program/verify phases')
args = parser.parse_args()
#######################################################################
# Generic XSVF parsing phase, produces a tree of commands performed
# against the CPLD.
#######################################################################
with open(args.xsvf, "rb") as f:
from xsvf import XSVFParser
commands = XSVFParser().parse(f, debug=args.debug)
programming_data = extract_programming_data(commands)
validate_programming_data(programming_data)
#######################################################################
# Patch the second programming phase into the first for SRAM
# programming.
#######################################################################
verify_blocks = programming_data['verify']
program_blocks = programming_data['program']
#######################################################################
# Calculate CRC of data read from CPLD during the second verification
# pass, which is after the "done" bit is set. Mask off insignificant
# bits (turning them to zero) and extending rows to the next full byte.
#######################################################################
if args.checksum:
if args.crcmod:
# Use a proper CRC library
import crcmod
crc = crcmod.predefined.Crc('crc-32')
else:
# Use my home-grown, simple, slow CRC32 object to avoid additional
# Python dependencies.
from dumb_crc32 import DumbCRC32
crc = DumbCRC32()
verify_block = verify_blocks[1]
for address, data, mask in verify_block:
valid_data = data & mask
bytes = valid_data.to_bytes(bytes_of_data, byteorder='little')
crc.update(bytes)
print('0x%s' % crc.hexdigest().lower())
if args.hackrf_data:
program_sram = make_sram_program(program_blocks)
verify_block = verify_blocks[1]
verify_masks = tuple(frozenset(extract_mask(verify_block)))
verify_mask_index = dict([(k, v) for v, k in enumerate(verify_masks)])
verify_mask_row_index = [verify_mask_index[row['mask']] for row in verify_block]
result = []
result.extend((
'/* WARNING: Auto-generated file. Do not edit. */',
'',
'#include <cpld_xc2c.h>',
'',
'const cpld_xc2c64a_program_t cpld_hackrf_program_sram = { {',
))
data_lines = [', '.join(['0x%02x' % n for n in row['data'].to_bytes(bytes_of_data, byteorder='little')]) for row in program_sram]
result.extend(['\t{ { %s } },' % line for line in data_lines])
result.extend((
'} };',
'',
'const cpld_xc2c64a_verify_t cpld_hackrf_verify = {',
'\t.mask = {',
))
verify_mask_lines = [', '.join(['0x%02x' % n for n in mask.to_bytes(bytes_of_data, byteorder='little')]) for mask in verify_masks]
result.extend(['\t\t{ { %s } },' % line for line in verify_mask_lines])
result.extend((
'\t},'
'\t.mask_index = {',
))
result.extend(['\t\t%s' % line for line in dec_lines(verify_mask_row_index)])
result.extend((
'\t}',
'};',
'',
'const cpld_xc2c64a_row_addresses_t cpld_hackrf_row_addresses = { {',
))
result.extend(['\t%s' % line for line in hex_lines(address_sequence)])
result.extend((
'} };',
'',
))
with open(args.hackrf_data, 'w') as f:
f.write('\n'.join(result))
if args.portapack_data:
program_sram = make_sram_program(program_blocks)
verify_block = verify_blocks[1]
verify_masks = extract_mask(verify_block)
result = []
result.extend((
'/*',
' * WARNING: Auto-generated file. Do not edit.',
'*/',
'#include "hackrf_cpld_data.hpp"',
'namespace hackrf {',
'namespace one {',
'namespace cpld {',
'const ::cpld::xilinx::XC2C64A::verify_blocks_t verify_blocks { {',
))
data_lines = [', '.join(['0x%02x' % n for n in row['data'].to_bytes(bytes_of_data, byteorder='big')]) for row in program_sram]
mask_lines = [', '.join(['0x%02x' % n for n in mask.to_bytes(bytes_of_data, byteorder='big')]) for mask in verify_masks]
lines = ['{ 0x%02x, { { %s } }, { { %s } } }' % data for data in zip(address_sequence, data_lines, mask_lines)]
result.extend('\t%s,' % line for line in lines)
result.extend((
'} };',
'} /* namespace hackrf */',
'} /* namespace one */',
'} /* namespace cpld */',
'',
))
with open(args.portapack_data, 'w') as f:
f.write('\n'.join(result))

View File

@ -0,0 +1,22 @@
class DumbCRC32(object):
def __init__(self):
self._remainder = 0xffffffff
self._reversed_polynomial = 0xedb88320
self._final_xor = 0xffffffff
def update(self, data):
bit_count = len(data) * 8
for bit_n in range(bit_count):
bit_in = data[bit_n >> 3] & (1 << (bit_n & 7))
self._remainder ^= 1 if bit_in != 0 else 0
bit_out = (self._remainder & 1)
self._remainder >>= 1;
if bit_out != 0:
self._remainder ^= self._reversed_polynomial;
def digest(self):
return self._remainder ^ self._final_xor
def hexdigest(self):
return '%08x' % self.digest()

View File

@ -0,0 +1,382 @@
#!/usr/bin/env python
# Copyright 2013 Jared Boone
#
# Display the LPC43xx Clock Generation Unit (CGU) registers in an
# easy-to-read format.
#
# This file is part of HackRF.
#
# This program 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 2, or (at your option)
# any later version.
#
# This program 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 this program; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
"""
In GDB:
dump binary memory cgu.bin 0x40050014 0x400500cc
"""
import sys
from struct import unpack
address = 0x40050014
f = open(sys.argv[1], 'read')
d = '\x00' * 20 + f.read()
length = len(d)
f.close()
def print_data(d):
for i in range(0, length, 16):
values = unpack('<IIII', d[i:i+16])
values = ['%08x' % v for v in values]
values_str = ' '.join(values)
line = '%08x: %s' % (address + i, values_str)
print(line)
#print_data(d)
#sys.exit(0)
data = {}
for i in range(0, length, 4):
data[i] = unpack('<I', d[i:i+4])[0]
registers = {
0x14: {
'name': 'FREQ_MON',
'fields': (
('RCNT', 0, 9),
('FCNT', 9, 14),
('MEAS', 23, 1),
('CLK_SEL', 24, 5),
),
},
0x18: {
'name': 'XTAL_OSC_CONTROL',
'fields': (
('ENABLE', 0, 1),
('BYPASS', 1, 1),
('HF', 2, 1)
),
},
0x1c: {
'name': 'PLL0USB_STAT',
'fields': (
('LOCK', 0, 1),
('FR', 1, 1),
),
},
0x20: {
'name': 'PLL0USB_CTRL',
'fields': (
('PD', 0, 1),
('BYPASS', 1, 1),
('DIRECTI', 2, 1),
('DIRECTO', 3, 1),
('CLKEN', 4, 1),
('FRM', 6, 1),
('AUTOBLOCK', 11, 1),
('CLK_SEL', 24, 5),
),
},
0x24: {
'name': 'PLL0USB_MDIV',
'fields': (
('MDEC', 0, 17),
('SELP', 17, 5),
('SELI', 22, 6),
('SELR', 28, 4),
),
},
0x28: {
'name': 'PLL0USB_NP_DIV',
'fields': (
('PDEC', 0, 7),
('NDEC', 12, 10),
),
},
0x40: {
'name': 'PLL1_STAT',
'fields': (
('LOCK', 0, 1),
),
},
0x44: {
'name': 'PLL1_CTRL',
'fields': (
('PD', 0, 1),
('BYPASS', 1, 1),
('FBSEL', 6, 1),
('DIRECT', 7, 1),
('PSEL', 8, 2),
('AUTOBLOCK', 11, 1),
('NSEL', 12, 2),
('MSEL', 16, 8),
('CLK_SEL', 24, 5),
),
},
0x48: {
'name': 'IDIVA_CTRL',
'fields': (
('PD', 0, 1),
('IDIV', 2, 2),
('AUTOBLOCK', 11, 1),
('CLK_SEL', 24, 5),
),
},
0x4C: {
'name': 'IDIVB_CTRL',
'fields': (
('PD', 0, 1),
('IDIV', 2, 4),
('AUTOBLOCK', 11, 1),
('CLK_SEL', 24, 5),
),
},
0x50: {
'name': 'IDIVC_CTRL',
'fields': (
('PD', 0, 1),
('IDIV', 2, 4),
('AUTOBLOCK', 11, 1),
('CLK_SEL', 24, 5),
),
},
0x54: {
'name': 'IDIVD_CTRL',
'fields': (
('PD', 0, 1),
('IDIV', 2, 4),
('AUTOBLOCK', 11, 1),
('CLK_SEL', 24, 5),
),
},
0x58: {
'name': 'IDIVE_CTRL',
'fields': (
('PD', 0, 1),
('IDIV', 2, 8),
('AUTOBLOCK', 11, 1),
('CLK_SEL', 24, 5),
),
},
0x5C: {
'name': 'BASE_SAFE_CLK',
'fields': (
('PD', 0, 1),
('AUTOBLOCK', 11, 1),
('CLK_SEL', 24, 5),
),
},
0x60: {
'name': 'BASE_USB0_CLK',
'fields': (
('PD', 0, 1),
('AUTOBLOCK', 11, 1),
('CLK_SEL', 24, 5),
),
},
0x64: {
'name': 'BASE_PERIPH_CLK',
'fields': (
('PD', 0, 1),
('AUTOBLOCK', 11, 1),
('CLK_SEL', 24, 5),
),
},
0x68: {
'name': 'BASE_USB1_CLK',
'fields': (
('PD', 0, 1),
('AUTOBLOCK', 11, 1),
('CLK_SEL', 24, 5),
),
},
0x6C: {
'name': 'BASE_M4_CLK',
'fields': (
('PD', 0, 1),
('AUTOBLOCK', 11, 1),
('CLK_SEL', 24, 5),
),
},
0x70: {
'name': 'BASE_SPIFI_CLK',
'fields': (
('PD', 0, 1),
('AUTOBLOCK', 11, 1),
('CLK_SEL', 24, 5),
),
},
0x74: {
'name': 'BASE_SPI_CLK',
'fields': (
('PD', 0, 1),
('AUTOBLOCK', 11, 1),
('CLK_SEL', 24, 5),
),
},
0x78: {
'name': 'BASE_PHY_RX_CLK',
'fields': (
('PD', 0, 1),
('AUTOBLOCK', 11, 1),
('CLK_SEL', 24, 5),
),
},
0x7C: {
'name': 'BASE_PHY_TX_CLK',
'fields': (
('PD', 0, 1),
('AUTOBLOCK', 11, 1),
('CLK_SEL', 24, 5),
),
},
0x80: {
'name': 'BASE_APB1_CLK',
'fields': (
('PD', 0, 1),
('AUTOBLOCK', 11, 1),
('CLK_SEL', 24, 5),
),
},
0x84: {
'name': 'BASE_APB3_CLK',
'fields': (
('PD', 0, 1),
('AUTOBLOCK', 11, 1),
('CLK_SEL', 24, 5),
),
},
0x88: {
'name': 'BASE_LCD_CLK',
'fields': (
('PD', 0, 1),
('AUTOBLOCK', 11, 1),
('CLK_SEL', 24, 5),
),
},
0x8C: {
'name': 'BASE_VADC_CLK',
'fields': (
('PD', 0, 1),
('AUTOBLOCK', 11, 1),
('CLK_SEL', 24, 5),
),
},
0x90: {
'name': 'BASE_SDIO_CLK',
'fields': (
('PD', 0, 1),
('AUTOBLOCK', 11, 1),
('CLK_SEL', 24, 5),
),
},
0x94: {
'name': 'BASE_SSP0_CLK',
'fields': (
('PD', 0, 1),
('AUTOBLOCK', 11, 1),
('CLK_SEL', 24, 5),
),
},
0x98: {
'name': 'BASE_SSP1_CLK',
'fields': (
('PD', 0, 1),
('AUTOBLOCK', 11, 1),
('CLK_SEL', 24, 5),
),
},
0x9C: {
'name': 'BASE_UART0_CLK',
'fields': (
('PD', 0, 1),
('AUTOBLOCK', 11, 1),
('CLK_SEL', 24, 5),
),
},
0xA0: {
'name': 'BASE_UART1_CLK',
'fields': (
('PD', 0, 1),
('AUTOBLOCK', 11, 1),
('CLK_SEL', 24, 5),
),
},
0xA4: {
'name': 'BASE_UART2_CLK',
'fields': (
('PD', 0, 1),
('AUTOBLOCK', 11, 1),
('CLK_SEL', 24, 5),
),
},
0xA8: {
'name': 'BASE_UART3_CLK',
'fields': (
('PD', 0, 1),
('AUTOBLOCK', 11, 1),
('CLK_SEL', 24, 5),
),
},
0xAC: {
'name': 'BASE_OUT_CLK',
'fields': (
('PD', 0, 1),
('AUTOBLOCK', 11, 1),
('CLK_SEL', 24, 5),
),
},
0xC0: {
'name': 'BASE_APLL_CLK',
'fields': (
('PD', 0, 1),
('AUTOBLOCK', 11, 1),
('CLK_SEL', 24, 5),
),
},
0xC4: {
'name': 'BASE_CGU_OUT0_CLK',
'fields': (
('PD', 0, 1),
('AUTOBLOCK', 11, 1),
('CLK_SEL', 24, 5),
),
},
0xC8: {
'name': 'BASE_CGU_OUT1_CLK',
'fields': (
('PD', 0, 1),
('AUTOBLOCK', 11, 1),
('CLK_SEL', 24, 5),
),
},
# TODO: Add other CGU registers. I did the ones that were
# valuable to me to debug CPU clock issues.
}
for address in sorted(registers):
register = registers[address]
name = register['name']
fields = register['fields']
value = data[address]
bits = bin(value)[2:].zfill(32)
print('%03x %20s %s = %08x' % (address, name, bits, value))
for field in fields:
name, low_bit, count = field
field_value = (value >> low_bit) & ((1 << count) - 1)
field_bits = bin(field_value)[2:].zfill(count) + ' ' * low_bit
field_bits = field_bits.rjust(32)
print('%03s %20s %s = %8x %s' % ('', '', field_bits, field_value, name))

View File

@ -0,0 +1,208 @@
import struct
class XSVFParser(object):
def __init__(self):
self._handlers = {
0x00: self.XCOMPLETE ,
0x01: self.XTDOMASK ,
0x02: self.XSIR ,
0x03: self.XSDR ,
0x04: self.XRUNTEST ,
0x07: self.XREPEAT ,
0x08: self.XSDRSIZE ,
0x09: self.XSDRTDO ,
0x0a: self.XSETSDRMASKS,
0x0b: self.XSDRINC ,
0x0c: self.XSDRB ,
0x0d: self.XSDRC ,
0x0e: self.XSDRE ,
0x0f: self.XSDRTDOB ,
0x10: self.XSDRTDOC ,
0x11: self.XSDRTDOE ,
0x12: self.XSTATE ,
0x13: self.XENDIR ,
0x14: self.XENDDR ,
0x15: self.XSIR2 ,
0x16: self.XCOMMENT ,
0x17: self.XWAIT ,
}
def tdomask(self):
return self._xtdomask
def read_byte(self):
return self.read_bytes(1)[0]
def read_bytes(self, n):
c = self._f.read(n)
if len(c) == n:
return c
else:
raise RuntimeError('unexpected end of file')
def read_bits(self, n):
length_bytes = (n + 7) >> 3
return self.read_bytes(length_bytes)
def read_u32(self):
return struct.unpack('>I', self.read_bytes(4))[0]
def parse(self, f, debug=False):
self._f = f
self._debug = debug
self._xcomplete = False
self._xenddr = None
self._xendir = None
self._xruntest = 0
self._xsdrsize = None
self._xtdomask = None
self._commands = []
while self._xcomplete == False:
self.read_instruction()
self._f = None
return self._commands
def read_instruction(self):
instruction_id = self.read_byte()
if instruction_id in self._handlers:
instruction_handler = self._handlers[instruction_id]
result = instruction_handler()
if result is not None:
self._commands.append(result)
else:
raise RuntimeError('unexpected instruction 0x%02x' % instruction_id)
def XCOMPLETE(self):
self._xcomplete = True
def XTDOMASK(self):
length_bits = self._xsdrsize
self._xtdomask = self.read_bits(length_bits)
def XSIR(self):
length_bits = self.read_byte()
tdi = self.read_bits(length_bits)
if self._debug:
print('XSIR tdi=%d:%s' % (length_bits, tdi.hex()))
return {
'type': 'xsir',
'tdi': {
'length': length_bits,
'data': tdi
},
}
def XSDR(self):
length_bits = self._xsdrsize
tdi = self.read_bits(length_bits)
if self._debug:
print('XSDR tdi=%d:%s' % (length_bits, tdi.hex()))
return {
'type': 'xsdr',
'tdi': {
'length': length_bits,
'data': tdi,
},
}
def XRUNTEST(self):
self._xruntest = self.read_u32()
if self._debug:
print('XRUNTEST number=%d' % self._xruntest)
def XREPEAT(self):
repeat = self.read_byte()
# print('XREPEAT times=%d' % repeat)
def XSDRSIZE(self):
self._xsdrsize = self.read_u32()
def XSDRTDO(self):
length_bits = self._xsdrsize
tdi = self.read_bits(length_bits)
tdo_mask = self._xtdomask
self._tdo_expected = (length_bits, self.read_bits(length_bits))
wait = self._xruntest
if wait == 0:
end_state = self._xenddr
else:
end_state = 1 # Run-Test/Idle
if self._debug:
print('XSDRTDO tdi=%d:%s tdo_mask=%d:%s tdo_expected=%d:%s end_state=%u wait=%u' % (
length_bits, tdi.hex(),
length_bits, tdo_mask.hex(),
self._tdo_expected[0], self._tdo_expected[1].hex(),
end_state,
wait,
))
return {
'type': 'xsdrtdo',
'tdi': {
'length': length_bits,
'data': tdi
},
'tdo_mask': {
'length': length_bits,
'data': tdo_mask,
},
'tdo_expected': {
'length': self._tdo_expected[0],
'data': self._tdo_expected[1],
},
'end_state': end_state,
'wait': wait,
}
def XSETSDRMASKS(self):
raise RuntimeError('unimplemented')
def XSDRINC(self):
raise RuntimeError('unimplemented')
def XSDRB(self):
raise RuntimeError('unimplemented')
def XSDRC(self):
raise RuntimeError('unimplemented')
def XSDRE(self):
raise RuntimeError('unimplemented')
def XSDRTDOB(self):
raise RuntimeError('unimplemented')
def XSDRTDOC(self):
raise RuntimeError('unimplemented')
def XSDRTDOE(self):
raise RuntimeError('unimplemented')
def XSTATE(self):
state = self.read_byte()
if self._debug:
print('XSTATE %u' % state)
return {
'type': 'xstate',
'state': state,
}
def XENDIR(self):
self._xendir = self.read_byte()
def XENDDR(self):
self._xenddr = self.read_byte()
def XSIR2(self):
raise RuntimeError('unimplemented')
def XCOMMENT(self):
raise RuntimeError('unimplemented')
def XWAIT(self):
wait_state = self.read_byte()
end_state = self.read_byte()
wait_time = self.read_u32()