Debian Codegraph @

legacy/fuzzer.py

raw symbols SCIP
1 import re
2 import os
3 import tempfile
4 import subprocess
5 from collections import deque
6 from itertools import chain, count
7 from random import shuffle, seed
8 from warnings import warn
9 from math import factorial
10 import numpy as np
11 from multiprocessing.dummy import Pool
12
13 import codegen
14 import bslib
15 import pindef
16
17 import sys, pdb
18 # resource sets
19 # CFU=CLU?
20 # ENABLE: only one fuzzer switches things on and off at the same time
21 # IOB, CLU_LUT, CLU_MUX, CLU_DFF, CFU, BRAM, DSP, ENABLE
22
23 gowinhome = os.getenv("GOWINHOME")
24 if not gowinhome:
25 raise Exception("GOWINHOME not set")
26
27 def np_to_vector(array):
28 return "{}'b{}".format(
29 len(array),
30 ''.join(str(int(n)) for n in array))
31
32 def popcnt(x):
33 res = 0
34 while x:
35 if x & 1:
36 res += 1
37 x >>= 1
38 return res
39
40 def get_cb_size(n):
41 return factorial(n) // factorial(n // 2) // factorial((n + 1) // 2)
42
43 def gen_cb(n):
44 res = []
45 for i in range(1, 2**n):
46 if popcnt(i) == (n + 1) // 2:
47 res.append(i)
48 assert len(res) == get_cb_size(n)
49 return res
50
51 def get_codes(n):
52 bits = n.bit_length()
53 while get_cb_size(bits) < n:
54 bits += 1
55 cb = gen_cb(bits)
56 return bits, cb[:n]
57
58 def configbits(bitlen, codes):
59 """
60 Given n bits of configuration data
61 generate uniquely identifying
62 bit patterns for each configuration bit.
63 This makes each configuration bit uniquely
64 identifiable in the bitstream.
65 """
66 codelen = len(codes)
67 byteview = np.array(codes, dtype=np.uint32).view(np.uint8)
68 bits = np.unpackbits(byteview, bitorder='little')
69 return bits.reshape(codelen, 32)[:,:bitlen].T
70
71 def configcodes(stack):
72 "Turn bit arrays back into numbers"
73 bytestack = np.packbits(stack, axis=0, bitorder='little').astype(np.uint32)
74 sequences = np.zeros(bytestack.shape[1:], dtype=np.uint32)
75 for i in range(bytestack.shape[0]):
76 sequences += bytestack[i] << (i*8)
77 return sequences
78
79 def find_bits(stack):
80 sequences = configcodes(stack)
81 indices = np.where((sequences>0) & (sequences<sequences.max()))
82 return indices, sequences[indices]
83
84 class Fuzzer:
85 # a set of resources used by this fuzzer
86 resources = set()
87 # added to name to avoid conflicts
88 prefix = ""
89 # values higher than this will trigger a warning
90 max_std = 20
91 # bits of side-effects
92 se_bits = 0
93 # list of side-effect identifiers
94 se_loc = []
95
96 @property
97 def cfg_bits(self):
98 return len(self.locations)*self.loc_bits
99
100 @property
101 def se_bits(self):
102 # this is dumb and potentially slow
103 return self.side_effects(np.zeros((0, self.cfg_bits), dtype=np.uint8)).shape[1]
104
105 def location_to_name(self, location):
106 return self.prefix + re.sub("\[([0-4AB])\]", "_\\1", location)
107
108 def location_chunks(self, bits):
109 return zip(self.locations, bslib.chunks(bits, self.loc_bits))
110
111 def primitives(self, mod, bits):
112 "Generate verilog for this fuzzer"
113 raise NotImplementedError
114
115 def constraints(self, constr, bits):
116 "Generate cst lines for this fuzzer"
117 raise NotImplementedError
118
119 def side_effects(self, bits):
120 """
121 Returns a list of codes that
122 don't map 1-1 to bitstream bits.
123 e.g. OR/AND of several other bits.
124 """
125 return np.zeros((1, 0))
126
127 def side_effect_cfg(self):
128 """
129 For each side-effect, return a set of
130 config bits that triggers
131 the corresponding side-effect.
132 """
133 return np.zeros((0, self.cfg_bits))
134
135 def check(self, bits):
136 "Perform some basic checks on the bitstream bits"
137 if len(self.locations)*self.loc_bits != len(bits):
138 warn("{} clusters expected, but {} clusters found".format(
139 len(self.locations)*self.loc_bits,
140 len(bits)))
141
142 for loc, b in self.location_chunks(bits):
143 a = np.array(b)
144 std = np.std(a, axis=1)
145 if np.any(std > self.max_std):
146 warn("High deviation in location {}".format(loc))
147
148
149 def report(self, bits):
150 """Generate a report of the bistream locations
151 corresponding to the provided config bits"""
152 for loc, b in self.location_chunks(bits):
153 print(self.__class__.__name__, loc, b)
154
155 def report_side_effects(self, bits):
156 """Generate a report of the bistream locations
157 corresponding to side-effect bits"""
158 for se, b in zip(self.se_loc, bits):
159 print(self.__class__.__name__, "se", se, b)
160
161 class CluFuzzer(Fuzzer):
162 scope = "CLU"
163 ncls = 4 # 3 for REG
164
165 def __init__(self, rows, cols, exclude):
166 self.locations = []
167 if self.scope == "CLU":
168 for row in range(2, rows):
169 if row not in exclude:
170 for col in range(2, cols):
171 self.locations.append("R{}C{}".format(row, col))
172 elif self.scope == "CLS":
173 for row in range(2, rows):
174 if row not in exclude:
175 for col in range(2, cols):
176 for cls in range(self.ncls):
177 self.locations.append("R{}C{}[{}]".format(row, col, cls))
178 else:
179 for row in range(2, rows):
180 if row not in exclude:
181 for col in range(2, cols):
182 for cls in range(self.ncls):
183 for lut in ["A", "B"]:
184 self.locations.append("R{}C{}[{}][{}]".format(row, col, cls, lut))
185
186 shuffle(self.locations)
187
188 def constraints(self, constr, bits):
189 "Generate cst lines for this fuzzer"
190 for loc in self.locations:
191 name = self.location_to_name(loc)
192 constr.cells[name] = loc
193
194 class Lut4BitsFuzzer(CluFuzzer):
195 """
196 This fuzzer finds the lookuptable bits of a LUT4
197 """
198 resources = {"CLU_LUT"}
199 loc_bits = 16
200 scope = "LUT"
201 prefix = "LUT"
202
203 def primitives(self, mod, bits):
204 "Generate verilog for LUT4s"
205 for location, bits in self.location_chunks(bits):
206 name = self.location_to_name(location)
207 lut = codegen.Primitive("LUT4", name)
208 lut.params["INIT"] = np_to_vector(1^bits) # inverted
209 lut.portmap['F'] = name+"_F"
210 lut.portmap['I0'] = name+"_I0"
211 lut.portmap['I1'] = name+"_I1"
212 lut.portmap['I2'] = name+"_I2"
213 lut.portmap['I3'] = name+"_I3"
214 mod.wires.update(lut.portmap.values())
215 mod.primitives[name] = lut
216
217 class DffFuzzer(CluFuzzer):
218 """
219 This fuzzer finds the bits for a DFF
220 But includes an empty LUT because otherwise
221 a pass-through LUT is created.
222 """
223 resources = {"CLU_LUT", "CLU_DFF"}
224 loc_bits = 1
225 scope = "CLS"
226 ncls = 3 # CLS 3 has no DFF
227
228 def primitives(self, mod, bits):
229 "Generate verilog for a LUT4 and DFF"
230 for location, bits in self.location_chunks(bits):
231 if bits[0]:
232 name = self.location_to_name(location)
233 location_a = location+"[A]_LUT"
234 name_a_lut = self.location_to_name(location_a)
235 lut = codegen.Primitive("LUT4", name_a_lut)
236 lut.params["INIT"] = "16'hffff"
237 lut.portmap['F'] = name_a_lut+"_F"
238 lut.portmap['I0'] = name_a_lut+"_I0"
239 lut.portmap['I1'] = name_a_lut+"_I1"
240 lut.portmap['I2'] = name_a_lut+"_I2"
241 lut.portmap['I3'] = name_a_lut+"_I3"
242 mod.wires.update(lut.portmap.values())
243 mod.primitives[name_a_lut] = lut
244
245 location_b = location+"[B]_LUT"
246 name_b_lut = self.location_to_name(location_b)
247 lut = codegen.Primitive("LUT4", name_b_lut)
248 lut.params["INIT"] = "16'hffff"
249 lut.portmap['F'] = name_b_lut+"_F"
250 lut.portmap['I0'] = name_b_lut+"_I0"
251 lut.portmap['I1'] = name_b_lut+"_I1"
252 lut.portmap['I2'] = name_b_lut+"_I2"
253 lut.portmap['I3'] = name_b_lut+"_I3"
254 mod.wires.update(lut.portmap.values())
255 mod.primitives[name_b_lut] = lut
256
257 location_a = location+"[A]_DFF"
258 name_a_dff = self.location_to_name(location_a)
259 dff = codegen.Primitive("DFF", name_a_dff)
260 dff.portmap['CLK'] = name+"_CLK" # share clk
261 dff.portmap['D'] = name_a_lut+"_F"
262 dff.portmap['Q'] = name_a_dff+"_Q"
263 mod.wires.update(dff.portmap.values())
264 mod.primitives[name_a_dff] = dff
265
266 location_a = location+"[B]_DFF"
267 name_b_dff = self.location_to_name(location_a)
268 dff = codegen.Primitive("DFF", name_b_dff)
269 dff.portmap['CLK'] = name+"_CLK"
270 dff.portmap['D'] = name_b_lut+"_F"
271 dff.portmap['Q'] = name_b_dff+"_Q"
272 mod.wires.update(dff.portmap.values())
273 mod.primitives[name_b_dff] = dff
274
275 def constraints(self, constr, bits):
276 for loc, bits in self.location_chunks(bits):
277 if bits[0]:
278 name = self.location_to_name(loc+"[A]_LUT")
279 constr.cells[name] = loc
280 name = self.location_to_name(loc+"[B]_LUT")
281 constr.cells[name] = loc
282 name = self.location_to_name(loc+"[A]_DFF")
283 constr.cells[name] = loc
284 name = self.location_to_name(loc+"[B]_DFF")
285 constr.cells[name] = loc
286
287 class DffsrFuzzer(CluFuzzer):
288 """
289 This fuzzer finds the DFF bits that control
290 1. clock polarity
291 2. sync/async
292 3. reset value
293 it does not find
294 4. unknown (DFF/DFFN)
295 5. unknown (always 1)
296 Layout:
297 ..4
298 2.5
299 .31
300 """
301 resources = {"CLU_DFF"}
302 loc_bits = 3
303 scope = "CLS"
304 ncls = 3 # CLS 3 has no DFF
305 prefix = "DFF"
306
307 # clkpol, sync/async, set/reset
308 ffmap = {
309 (0, 0, 0): ("DFFSE", "SET"),
310 (0, 0, 1): ("DFFRE", "RESET"),
311 (0, 1, 0): ("DFFPE", "PRESET"),
312 (0, 1, 1): ("DFFCE", "CLEAR"),
313 (1, 0, 0): ("DFFNSE", "SET"),
314 (1, 0, 1): ("DFFNRE", "RESET"),
315 (1, 1, 0): ("DFFNPE", "PRESET"),
316 (1, 1, 1): ("DFFNCE", "CLEAR"),
317 }
318
319 def primitives(self, mod, bits):
320 "Generate verilog for a DFF at this location"
321 for location, bits in self.location_chunks(bits):
322 prim, port = self.ffmap[tuple(bits)]
323 name = self.location_to_name(location)
324 dff = codegen.Primitive(prim, name)
325 dff.portmap['CLK'] = name+"_CLK"
326 dff.portmap['D'] = name+"_F"
327 dff.portmap['Q'] = name+"_Q"
328 dff.portmap['CE'] = name+"_CE"
329 dff.portmap[port] = name+"_"+port
330 mod.wires.update(dff.portmap.values())
331 mod.primitives[name] = dff
332
333 class OneHopWireFuzzer(CluFuzzer):
334 """
335 This fuzzer finds wires to adjacent tiles
336 """
337 resources = {"CLU_LUT"}
338 loc_bits = 4
339 scope = "LUT"
340 prefix = "LUT"
341
342 def neighbours(self, location):
343 for r, c in [(1,0), (0, 1), (-1, 0), (0, -1)]:
344 yield re.sub(
345 "R(\\d+)C(\\d+)",
346 lambda m: "R{}C{}".format(
347 int(m[1])+r, int(m[2])+c),
348 location)
349
350 def primitives(self, mod, bits):
351 "Generate verilog for LUT4s"
352 for location, bits in self.location_chunks(bits):
353 name = self.location_to_name(location)
354 lut = codegen.Primitive("LUT4", name)
355 lut.params["INIT"] = "16'h0000"
356 lut.portmap['F'] = name+"_F"
357 neigh = self.neighbours(location)
358 for i, ne, bit in zip(count(), neigh, bits):
359 if bit:
360 ne_name = self.location_to_name(ne)
361 lut.portmap['I{}'.format(i)] = ne_name+"_F"
362 else:
363 lut.portmap['I{}'.format(i)] = name+"_I{}".format(i)
364
365 mod.wires.update(lut.portmap.values())
366 mod.primitives[name] = lut
367
368 class PinFuzzer(Fuzzer):
369 def __init__(self, series, package):
370 self.locations = []
371 self.banks = pindef.get_pins(series, package)
372 self.se_loc = self.banks.keys()
373 for bank in self.banks.values():
374 self.locations.extend(bank)
375 shuffle(self.locations)
376 self.bank_indices = {
377 bank: [self.locations.index(pin)
378 for pin in pins]
379 for bank, pins in self.banks.items()
380 }
381
382 def constraints(self, constr, bits):
383 "Generate cst lines for this fuzzer"
384 for loc in self.locations:
385 name = "IOB{}".format(loc)
386 constr.ports[name] = loc
387
388 class IobFuzzer(PinFuzzer):
389 resources = {"IOB"}
390 loc_bits = 1
391 kindmap = {
392 "IBUF": {"wires": ["O"], "inputs": ["I"]},
393 "OBUF": {"wires": ["I"], "outputs": ["O"]},
394 "TBUF": {"wires": ["I", "OEN"], "outputs": ["O"]},
395 "IOBUF": {"wires": ["I", "O", "OEN"], "inouts": ["IO"]},
396 #"TLVDS_IBUF": ["I", "IB", "O"],
397 #"TLVDS_OBUF": ["I", "OB", "O"],
398 #"TLVDS_TBUF": ["I", "OB", "O", "OEN"],
399 #"TLVDS_IOBUF": ["I", "IO", "IOB", "O", "OEN"],
400 #"MIPI_IBUF_HS": ["I", "IB", "OH"],
401 #"MIPI_IBUF_LP": ["I", "IB", "OL", "OB"],
402 #"MIPI_IBUF": ["I", "IB", "HSREN", "OEN", "OENB", "OH", "OB", "IO", "IOB"],
403 #"MIPI_OBUF": ["MODESEL", "I", "IB", "O", "OB"],
404 #"I3C_IOBUF": ["MODESEL", "I", "O", "IO"],
405 }
406
407 def __init__(self, kind, pins, exclude):
408 super().__init__(pins, exclude)
409 self.kind = kind
410 self.ports = self.kindmap[kind]
411
412 def primitives(self, mod, bits):
413 "Generate verilog for an IOB at this location"
414 for location, bits in self.location_chunks(bits):
415 if bits[0]:
416 name = "IOB{}".format(location)
417 dff = codegen.Primitive(self.kind, name)
418 for port in chain.from_iterable(self.ports.values()):
419 dff.portmap[port] = name+"_"+port
420
421 for direction, wires in self.ports.items():
422 wnames = [name+"_"+w for w in wires]
423 getattr(mod, direction).update(wnames)
424 mod.primitives[name] = dff
425
426 def constraints(self, constr, bits):
427 for loc, bits in self.location_chunks(bits):
428 if bits[0]:
429 name = "IOB{}".format(loc)
430 constr.ports[name] = loc
431
432 def side_effects(self, bits):
433 "If any pin is turned on, the bank is also enabled"
434 return np.array([
435 np.any(bits[:,idc], axis=1)
436 for bank, idc in self.bank_indices.items()
437 ]).T
438
439 def side_effect_cfg(self):
440 "Turn each bank on seperately"
441 cfglist = []
442 for bank, indices in self.bank_indices.items():
443 cfg = np.zeros(self.cfg_bits, dtype=np.uint8)
444 cfg[indices] = 1
445 cfglist.append(cfg)
446 return np.vstack(cfglist)
447
448 def run_pnr(fuzzers, bits):
449 #TODO generalize/parameterize
450 mod = codegen.Module()
451 constr = codegen.Constraints()
452 start = 0
453 for fuzzer in fuzzers:
454 cb = bits[start:start+fuzzer.cfg_bits]
455 start += fuzzer.cfg_bits
456 fuzzer.primitives(mod, cb)
457 fuzzer.constraints(constr, cb)
458
459 cfg = codegen.DeviceConfig({
460 "JTAG regular_io": "false",
461 "SSPI regular_io": "false",
462 "MSPI regular_io": "false",
463 "READY regular_io": "false",
464 "DONE regular_io": "false",
465 "RECONFIG_N regular_io": "false",
466 "MODE regular_io": "false",
467 "CRC_check": "true",
468 "compress": "false",
469 "encryption": "false",
470 "security_bit_enable": "true",
471 "bsram_init_fuse_print": "true",
472 "download_speed": "250/100",
473 "spi_flash_address": "0x00FFF000",
474 "format": "txt",
475 "background_programming": "false",
476 "secure_mode": "false"})
477
478 opt = codegen.PnrOptions([])
479 #"sdf", "oc", "ibs", "posp", "o",
480 #"warning_all", "timing", "reg_not_in_iob"])
481
482 pnr = codegen.Pnr()
483 pnr.device = "GW1NR-9-QFN88-6"
484 pnr.partnumber = "GW1NR-LV9QN88C6/I5"
485
486 with tempfile.TemporaryDirectory() as tmpdir:
487 pnr.outdir = tmpdir
488 with open(tmpdir+"/top.v", "w") as f:
489 mod.write(f)
490 pnr.netlist = tmpdir+"/top.v"
491 with open(tmpdir+"/top.cst", "w") as f:
492 constr.write(f)
493 pnr.cst = tmpdir+"/top.cst"
494 with open(tmpdir+"/device.cfg", "w") as f:
495 cfg.write(f)
496 pnr.cfg = tmpdir+"/device.cfg"
497 with open(tmpdir+"/pnr.cfg", "w") as f:
498 opt.write(f)
499 pnr.opt = tmpdir+"/pnr.cfg"
500 with open(tmpdir+"/run.tcl", "w") as f:
501 pnr.write(f)
502 subprocess.run([gowinhome+"/IDE/bin/gw_sh", tmpdir+"/run.tcl"])
503 #print(tmpdir); input()
504 try:
505 return bslib.read_bitstream(tmpdir+"/impl/pnr/top.fs")[0]
506 except FileNotFoundError:
507 return None
508
509 def get_extra_bits(fuzzers, bits):
510 "Extend bits with configurations that test side-effects"
511 groups = []
512 start = 0
513 for fuzzer in fuzzers:
514 cfg = fuzzer.side_effect_cfg()
515 group = np.zeros((cfg.shape[0], bits.shape[1]), dtype=np.uint8)
516 group[:,start:start+fuzzer.cfg_bits] = cfg
517 start += fuzzer.cfg_bits
518 groups.append(group)
519 gstack = np.vstack(groups)
520
521 nrofbits = gstack.shape[0]
522 if nrofbits > 0:
523 codelen, codes = get_codes(nrofbits)
524 shuffle(codes)
525 sebits = configbits(codelen, codes)
526 rows = [np.sum(gstack[row==1], axis=0) for row in sebits]
527 rows.append(bits)
528 return codelen, np.vstack(rows)
529 else:
530 return 0, bits
531
532 def get_extra_codes(fuzzers, bits):
533 "Get codes produces by fuzzer side-effects"
534 extra_bits = []
535 start = 0
536 for fuzzer in fuzzers:
537 cb = bits[:,start:start+fuzzer.cfg_bits]
538 start += fuzzer.cfg_bits
539 se = fuzzer.side_effects(cb)
540 if se.size:
541 extra_bits.append(se)
542 if extra_bits:
543 return configcodes(np.hstack(extra_bits))
544 else:
545 return []
546
547 def run_batch(fuzzers):
548 nrofbits = sum([f.cfg_bits for f in fuzzers])
549 codelen, codes = get_codes(nrofbits)
550 shuffle(codes)
551 bits = configbits(codelen, codes)
552
553 secodelen, bits = get_extra_bits(fuzzers, bits)
554 codes = configcodes(bits) # extended codes
555 extra_codes = get_extra_codes(fuzzers, bits)
556
557 if True:
558 p = Pool()
559 bitstreams = p.map(lambda cb: run_pnr(fuzzers, cb), bits)
560 stack = np.stack([b for b in bitstreams if b is not None])
561 np.savez_compressed("bitstreams.npz", *bitstreams)
562 else:
563 stack = np.stack(list(np.load("bitstreams.npz").values()), axis=0)
564
565 indices, sequences = find_bits(stack)
566
567 #debug image
568 bitmap = np.zeros(stack.shape[1:], dtype=np.uint8)
569 bitmap[indices] = 1
570 bslib.display("indices.png", bitmap)
571
572 seqloc = np.array([sequences, *indices]).T
573 c_set = set(codes)
574 ec_set = set(extra_codes)
575 for s, x, y in seqloc:
576 if s in c_set:
577 print("Valid sequence at: {}, {}".format(x, y))
578 continue
579 if s in ec_set:
580 print("Side effect at: {}, {}".format(x, y))
581 continue
582 raise ValueError("invalid sequence at: {}, {}".format(x, y))
583
584 mapping = {}
585 for seq, x, y in seqloc:
586 mapping.setdefault(seq, []).append((x, y))
587
588 codesq = deque(codes)
589 extra_codesq = deque(extra_codes)
590 for fuzzer in fuzzers:
591 bits = []
592 extra_bits = []
593 for _ in range(fuzzer.cfg_bits):
594 code = codesq.popleft()
595 bits.append(mapping[code])
596 for _ in range(fuzzer.se_bits):
597 code = extra_codesq.popleft()
598 extra_bits.append(mapping[code])
599
600 fuzzer.report(bits)
601 fuzzer.report_side_effects(extra_bits)
602 fuzzer.check(bits)
603
604 if __name__ == "__main__":
605 seed(0xdeadbeef)
606 fuzzers = [
607 #Lut4BitsFuzzer(28, 47, {10, 19, 28}),
608 #DffFuzzer(28, 47, {10, 19, 28}),
609 #DffsrFuzzer(28, 47, {10, 19, 28}),
610 OneHopWireFuzzer(28, 47, {10, 19, 28}),
611 #IobFuzzer("IBUF", "GW1NR-9", "QN881"),
612 ]
613 run_batch(fuzzers)