aboutsummaryrefslogtreecommitdiff
path: root/util/stm32eeprom_parser.py
diff options
context:
space:
mode:
authorDonald Kjer <don.kjer@gmail.com>2021-08-23 15:15:34 -0700
committerGitHub <noreply@github.com>2021-08-23 23:15:34 +0100
commite756a21636149ad47c19c659d04be93cf3071dab (patch)
treeaa350c7209c5375f8a3c400353969d2ce0ed3748 /util/stm32eeprom_parser.py
parent2481e109a0f79b4cdcecab4a6bf6755fb5eda3fc (diff)
downloadqmk_firmware-e756a21636149ad47c19c659d04be93cf3071dab.tar.gz
qmk_firmware-e756a21636149ad47c19c659d04be93cf3071dab.zip
eeprom_stm32: implement high density wear leveling (#12567)
* eeprom_stm32: implement wear leveling Update EECONFIG_MAGIC_NUMBER eeprom_stm32: check emulated eeprom size is large enough * eeprom_stm32: Increasing simulated EEPROM density on stm32 * Adding utility script to decode emulated eeprom * Adding unit tests * Applying qmk cformat changes * cleaned up flash mocking * Fix for stm32eeprom_parser.py checking via signature with wrong base * Fix for nk65 keyboard Co-authored-by: Ilya Zhuravlev <whatever@xyz.is> Co-authored-by: zvecr <git@zvecr.com>
Diffstat (limited to 'util/stm32eeprom_parser.py')
-rwxr-xr-xutil/stm32eeprom_parser.py317
1 files changed, 317 insertions, 0 deletions
diff --git a/util/stm32eeprom_parser.py b/util/stm32eeprom_parser.py
new file mode 100755
index 000000000..b124f713d
--- /dev/null
+++ b/util/stm32eeprom_parser.py
@@ -0,0 +1,317 @@
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 empty_rows = 0
201 prev_row = ''
202 first_repeat = True
203 for pos in range(0, size, 16):
204 row=data[pos:pos+16]
205 row[len(row):16] = (16-len(row))*[None]
206 if row == prev_row:
207 if first_repeat:
208 print("*")
209 first_repeat = False
210 else:
211 first_repeat = True
212 display(pos, row)
213 prev_row = row
214 print("%04x" % (pos+16))
215
216def dumpEeconfig(data, eeconfig):
217 print("EECONFIG:")
218 for (name, pos, length) in eeconfig:
219 fmt = STRUCT_FMTS[length]
220 value = unpack(fmt, ''.join([chr(x) for x in data[pos:pos+length]]))[0]
221 print(("%%04x %%s = 0x%%0%dx" % (length * 2)) % (pos, name, value))
222
223def dumpVia(data, base, layers, cols, rows, macros,
224 layout_options_size, custom_config_size):
225 magicYear = data[base + 0]
226 magicMonth = data[base + 1]
227 magicDay = data[base + 2]
228 # Sanity check
229 if not 10 <= magicYear <= 0x99 or \
230 not 0 <= magicMonth <= 0x12 or \
231 not 0 <= magicDay <= 0x31:
232 print("ERROR: VIA Signature is not valid; Year:%x, Month:%x, Day:%x" % (magicYear, magicMonth, magicDay))
233 return
234 if cols is None or rows is None:
235 print("ERROR: VIA dump requires specifying --rows and --cols", file=sys.stderr)
236 return 2
237 print("VIA:")
238 # Decode magic
239 print("%04x MAGIC = 20%02x-%02x-%02x" % (base, magicYear, magicMonth, magicDay))
240 # Decode layout options
241 options = 0
242 pos = base + 3
243 for i in range(base+3, base+3+layout_options_size):
244 options = options << 8
245 options |= data[i]
246 print(("%%04x LAYOUT_OPTIONS = 0x%%0%dx" % (layout_options_size * 2)) % (pos, options))
247 pos += layout_options_size + custom_config_size
248 # Decode keycodes
249 keymap_size = layers * rows * cols * 2
250 if (pos + keymap_size) >= (len(data) - 1):
251 print("ERROR: VIA keymap requires %d bytes, but only %d available" % (keymap_size, len(data) - pos))
252 return 3
253 for layer in range(layers):
254 print("%s LAYER %d %s" % ('-'*int(cols*2.5), layer, '-'*int(cols*2.5)))
255 for row in range(rows):
256 print("%04x | " % pos, end='')
257 for col in range(cols):
258 keycode = (data[pos] << 8) | (data[pos+1])
259 print(" %04x" % keycode, end='')
260 pos += 2
261 print("")
262 # Decode macros
263 for macro_num in range(macros):
264 macro = ""
265 macro_pos = pos
266 while pos < len(data):
267 char = chr(data[pos])
268 pos += 1
269 if char == '\x00':
270 print("%04x MACRO[%d] = '%s'" % (macro_pos, macro_num, macro))
271 break
272 else:
273 macro += char
274 return 0
275
276
277def decodeSTM32Eeprom(input, canonical, size=None, output=None, **kwargs):
278 input_size = os.path.getsize(input)
279 if size is None:
280 size = input_size >> 1
281
282 # Read the first few bytes to check magic signature
283 with open(input, 'rb') as in_file:
284 magic=in_file.read(4)
285 in_file.seek(0)
286
287 if magic == MAGIC_FEEA:
288 decoded = decodeEepromFEEA(in_file, size)
289 eeconfig = EECONFIG_V1
290 via_base = VIABASE_V1
291 elif magic[:2] == MAGIC_FEE9:
292 decoded = decodeEepromFEE9(in_file, size)
293 eeconfig = EECONFIG_V1
294 via_base = VIABASE_V1
295 else:
296 print("Unknown magic signature: %s" % " ".join(["0x%02x" % ord(x) for x in magic]), file=sys.stderr)
297 return 1
298
299 if output is not None:
300 with open(output, 'wb') as out_file:
301 out_file.write(pack('%dB' % len(decoded), *decoded))
302 print("DECODED EEPROM:")
303 dumpBinary(decoded, canonical)
304 dumpEeconfig(decoded, eeconfig)
305 if kwargs['rows'] is not None and kwargs['cols'] is not None:
306 return dumpVia(decoded, via_base, **kwargs)
307
308 return 0
309
310def main():
311 global VERBOSE
312 kwargs = vars(parseArgs())
313 VERBOSE = kwargs.pop('verbose')
314 return decodeSTM32Eeprom(**kwargs)
315
316if __name__ == '__main__':
317 sys.exit(main())