Parent directory

stm32eeprom_parser.py

11014 bytes
  1#!/usr/bin/env python
  2#
  3# Copyright 2021 Don Kjer
  4#
  5# This program is free software: you can redistribute it and/or modify
  6# it under the terms of the GNU General Public License as published by
  7# the Free Software Foundation, either version 2 of the License, or
  8# (at your option) any later version.
  9#
 10# This program is distributed in the hope that it will be useful,
 11# but WITHOUT ANY WARRANTY; without even the implied warranty of
 12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 13# GNU General Public License for more details.
 14#
 15# You should have received a copy of the GNU General Public License
 16# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 17#
 18
 19from __future__ import print_function
 20
 21import argparse
 22from struct import pack, unpack
 23import os, sys
 24
 25MAGIC_FEEA     = '\xea\xff\xfe\xff'
 26
 27MAGIC_FEE9     = '\x16\x01'
 28EMPTY_WORD     = '\xff\xff'
 29WORD_ENCODING  = 0x8000
 30VALUE_NEXT     = 0x6000
 31VALUE_RESERVED = 0x4000
 32VALUE_ENCODED  = 0x2000
 33BYTE_RANGE     = 0x80
 34
 35CHUNK_SIZE = 1024
 36
 37STRUCT_FMTS = {
 38    1: 'B',
 39    2: 'H',
 40    4: 'I'
 41}
 42PRINTABLE='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ '
 43
 44EECONFIG_V1 = [
 45    ("MAGIC",                0, 2),
 46    ("DEBUG",                2, 1),
 47    ("DEFAULT_LAYER",        3, 1),
 48    ("KEYMAP",               4, 1),
 49    ("MOUSEKEY_ACCEL",       5, 1),
 50    ("BACKLIGHT",            6, 1),
 51    ("AUDIO",                7, 1),
 52    ("RGBLIGHT",             8, 4),
 53    ("UNICODEMODE",         12, 1),
 54    ("STENOMODE",           13, 1),
 55    ("HANDEDNESS",          14, 1),
 56    ("KEYBOARD",            15, 4),
 57    ("USER",                19, 4),
 58    ("VELOCIKEY",           23, 1),
 59    ("HAPTIC",              24, 4),
 60    ("MATRIX",              28, 4),
 61    ("MATRIX_EXTENDED",     32, 2),
 62    ("KEYMAP_UPPER_BYTE",   34, 1),
 63]
 64VIABASE_V1 = 35
 65
 66VERBOSE = False
 67
 68def parseArgs():
 69    parser = argparse.ArgumentParser(description='Decode an STM32 emulated eeprom dump')
 70    parser.add_argument('-s', '--size', type=int,
 71                        help='Size of the emulated eeprom (default: input_size / 2)')
 72    parser.add_argument('-o', '--output', help='File to write decoded eeprom to')
 73    parser.add_argument('-y', '--layout-options-size', type=int,
 74                        help='VIA layout options size (default: 1)', default=1)
 75    parser.add_argument('-t', '--custom-config-size', type=int,
 76                        help='VIA custom config size (default: 0)', default=0)
 77    parser.add_argument('-l', '--layers', type=int,
 78                        help='VIA keyboard layers (default: 4)', default=4)
 79    parser.add_argument('-r', '--rows', type=int, help='VIA matrix rows')
 80    parser.add_argument('-c', '--cols', type=int, help='VIA matrix columns')
 81    parser.add_argument('-m', '--macros', type=int,
 82                        help='VIA macro count (default: 16)', default=16)
 83    parser.add_argument('-C', '--canonical', action='store_true',
 84                        help='Canonical hex+ASCII display.')
 85    parser.add_argument('-v', '--verbose', action='store_true', help='Verbose output')
 86    parser.add_argument('input', help='Raw contents of the STM32 flash area used to emulate eeprom')
 87    return parser.parse_args()
 88
 89
 90def decodeEepromFEEA(in_file, size):
 91    decoded=size*[None]
 92    pos = 0
 93    while True:
 94        chunk = in_file.read(CHUNK_SIZE)
 95        for i in range(0, len(chunk), 2):
 96            decoded[pos] = unpack('B', chunk[i])[0]
 97            pos += 1
 98            if pos >= size:
 99                break
100
101        if len(chunk) < CHUNK_SIZE or pos >= size:
102            break
103    return decoded
104
105def decodeEepromFEE9(in_file, size):
106    decoded=size*[None]
107    pos = 0
108    # Read compacted flash 
109    while True:
110        read_size = min(size - pos, CHUNK_SIZE)
111        chunk = in_file.read(read_size)
112        for i in range(len(chunk)):
113            decoded[pos] = unpack('B', chunk[i])[0] ^ 0xFF
114            pos += 1
115            if pos >= size:
116                break
117
118        if len(chunk) < read_size or pos >= size:
119            break
120    if VERBOSE:
121        print("COMPACTED EEPROM:")
122        dumpBinary(decoded, True)
123        print("WRITE LOG:")
124    # Read write log
125    while True:
126        entry = in_file.read(2)
127        if len(entry) < 2:
128            print("Partial log address at position 0x%04x" % pos, file=sys.stderr)
129            break
130        pos += 2
131
132        if entry == EMPTY_WORD:
133            break
134
135        be_entry = unpack('>H', entry)[0]
136        entry = unpack('H', entry)[0]
137        if not (entry & WORD_ENCODING):
138            address = entry >> 8
139            decoded[address] = entry & 0xFF
140            if VERBOSE:
141                print("[0x%04x]: BYTE 0x%02x = 0x%02x" % (be_entry, address, decoded[address]))
142        else:
143            if (entry & VALUE_NEXT) == VALUE_NEXT:
144                # Read next word as value
145                value = in_file.read(2)
146                if len(value) < 2:
147                    print("Partial log value at position 0x%04x" % pos, file=sys.stderr)
148                    break
149                pos += 2
150                address = entry & 0x1FFF
151                address <<= 1
152                address += BYTE_RANGE
153                decoded[address]   = unpack('B', value[0])[0] ^ 0xFF
154                decoded[address+1] = unpack('B', value[1])[0] ^ 0xFF
155                be_value = unpack('>H', value)[0]
156                if VERBOSE:
157                    print("[0x%04x 0x%04x]: WORD 0x%04x = 0x%02x%02x" % (be_entry, be_value, address, decoded[address+1], decoded[address]))
158            else:
159                # Reserved for future use
160                if entry & VALUE_RESERVED:
161                    if VERBOSE:
162                        print("[0x%04x]: RESERVED 0x%04x" % (be_entry, address))
163                    continue
164                address = entry & 0x1FFF
165                address <<= 1
166                decoded[address]   = (entry & VALUE_ENCODED) >> 13
167                decoded[address+1] = 0
168                if VERBOSE:
169                    print("[0x%04x]: ENCODED 0x%04x = 0x%02x%02x" % (be_entry, address, decoded[address+1], decoded[address]))
170
171    return decoded
172
173def dumpBinary(data, canonical):
174    def display(pos, row):
175        print("%04x" % pos, end='')
176        for i in range(len(row)):
177            if i % 8 == 0:
178                print(" ", end='')
179            char = row[i]
180            if char is None:
181                print("   ", end='')
182            else:
183                print(" %02x" % row[i], end='')
184        if canonical:
185            print("  |", end='')
186            for i in range(len(row)):
187                char = row[i]
188                if char is None:
189                    char = " "
190                else:
191                    char = chr(char)
192                if char not in PRINTABLE:
193                    char = "."
194                print(char, end='')
195            print("|", end='')
196
197        print("")
198
199    size = len(data)
200    prev_row = ''
201    first_repeat = True
202    for pos in range(0, size, 16):
203        row=data[pos:pos+16]
204        row[len(row):16] = (16-len(row))*[None]
205        if row == prev_row:
206            if first_repeat:
207                print("*")
208                first_repeat = False
209        else:
210            first_repeat = True
211            display(pos, row)
212        prev_row = row
213    print("%04x" % (pos+16))
214
215def dumpEeconfig(data, eeconfig):
216    print("EECONFIG:")
217    for (name, pos, length) in eeconfig:
218        fmt = STRUCT_FMTS[length]
219        value = unpack(fmt, ''.join([chr(x) for x in data[pos:pos+length]]))[0]
220        print(("%%04x %%s = 0x%%0%dx" % (length * 2)) % (pos, name, value))
221
222def dumpVia(data, base, layers, cols, rows, macros,
223            layout_options_size, custom_config_size):
224    magicYear  = data[base + 0]
225    magicMonth = data[base + 1]
226    magicDay   = data[base + 2]
227    # Sanity check
228    if not 10 <= magicYear <= 0x99 or \
229       not 0 <= magicMonth <= 0x12 or \
230       not 0 <= magicDay <= 0x31:
231        print("ERROR: VIA Signature is not valid; Year:%x, Month:%x, Day:%x" % (magicYear, magicMonth, magicDay))
232        return
233    if cols is None or rows is None:
234        print("ERROR: VIA dump requires specifying --rows and --cols", file=sys.stderr)
235        return 2
236    print("VIA:")
237    # Decode magic
238    print("%04x MAGIC = 20%02x-%02x-%02x" % (base, magicYear, magicMonth, magicDay))
239    # Decode layout options
240    options = 0
241    pos = base + 3
242    for i in range(base+3, base+3+layout_options_size):
243        options = options << 8
244        options |= data[i]
245    print(("%%04x LAYOUT_OPTIONS = 0x%%0%dx" % (layout_options_size * 2)) % (pos, options))
246    pos += layout_options_size + custom_config_size
247    # Decode keycodes
248    keymap_size = layers * rows * cols * 2
249    if (pos + keymap_size) >= (len(data) - 1):
250        print("ERROR: VIA keymap requires %d bytes, but only %d available" % (keymap_size, len(data) - pos))
251        return 3
252    for layer in range(layers):
253        print("%s LAYER %d %s" % ('-'*int(cols*2.5), layer, '-'*int(cols*2.5)))
254        for row in range(rows):
255            print("%04x  | " % pos, end='')
256            for col in range(cols):
257                keycode = (data[pos] << 8) | (data[pos+1])
258                print(" %04x" % keycode, end='')
259                pos += 2
260            print("")
261    # Decode macros
262    for macro_num in range(macros):
263        macro = ""
264        macro_pos = pos
265        while pos < len(data):
266            char = chr(data[pos])
267            pos += 1
268            if char == '\x00':
269                print("%04x MACRO[%d] = '%s'" % (macro_pos, macro_num, macro))
270                break
271            else:
272                macro += char
273    return 0
274
275
276def decodeSTM32Eeprom(input, canonical, size=None, output=None, **kwargs):
277    input_size = os.path.getsize(input)
278    if size is None:
279        size = input_size >> 1
280
281    # Read the first few bytes to check magic signature
282    with open(input, 'rb') as in_file:
283        magic=in_file.read(4)
284        in_file.seek(0)
285
286        if magic == MAGIC_FEEA:
287            decoded = decodeEepromFEEA(in_file, size)
288            eeconfig = EECONFIG_V1
289            via_base = VIABASE_V1
290        elif magic[:2] == MAGIC_FEE9:
291            decoded = decodeEepromFEE9(in_file, size)
292            eeconfig = EECONFIG_V1
293            via_base = VIABASE_V1
294        else:
295            print("Unknown magic signature: %s" % " ".join(["0x%02x" % ord(x) for x in magic]), file=sys.stderr)
296            return 1
297
298    if output is not None:
299        with open(output, 'wb') as out_file:
300            out_file.write(pack('%dB' % len(decoded), *decoded))
301    print("DECODED EEPROM:")
302    dumpBinary(decoded, canonical)
303    dumpEeconfig(decoded, eeconfig)
304    if kwargs['rows'] is not None and kwargs['cols'] is not None:
305        return dumpVia(decoded, via_base, **kwargs)
306
307    return 0
308
309def main():
310    global VERBOSE
311    kwargs = vars(parseArgs())
312    VERBOSE = kwargs.pop('verbose')
313    return decodeSTM32Eeprom(**kwargs)
314
315if __name__ == '__main__':
316    sys.exit(main())