def main(): ROM = uctypes.bytearray_at(0x40200000, 16) fid = esp.flash_id() print("FlashROM:") print("Flash ID: %x (Vendor: %x Device: %x)" % (fid, fid & 0xFF, fid & 0xFF00 | fid >> 16)) print("Flash bootloader data:") SZ_MAP = {0: "512KB", 1: "256KB", 2: "1MB", 3: "2MB", 4: "4MB"} FREQ_MAP = {0: "40MHZ", 1: "26MHZ", 2: "20MHz", 0xF: "80MHz"} print("Byte @2: %02x" % ROM[2]) print("Byte @3: %02x (Flash size: %s Flash freq: %s)" % (ROM[3], SZ_MAP.get(ROM[3] >> 4, "?"), FREQ_MAP.get(ROM[3] & 0xF))) print("Firmware checksum:") print(esp.check_fw()) print("\nNetworking:") print("STA ifconfig:", network.WLAN(network.STA_IF).ifconfig()) print("AP ifconfig:", network.WLAN(network.AP_IF).ifconfig()) print("Free WiFi driver buffers of type:") for i, comm in enumerate(("1,2 TX", "4 Mngmt TX(len: 0x41-0x100)", "5 Mngmt TX (len: 0-0x40)", "7", "8 RX")): print("%d: %d (%s)" % (i, esp.esf_free_bufs(i), comm)) print("lwIP PCBs:") lwip.print_pcbs()
def gmtime(t=None): if t is None: t = time() t = int(t) a = ustruct.pack('i', t) tm_p = gmtime_(a) return _c_tm_to_tuple(uctypes.bytearray_at(tm_p, 36))
def localtime(t=None): if t is None: t = time() t = int(t) a = ustruct.pack('i', t) tm_p = localtime_(a) return _c_tm_to_struct_time(uctypes.bytearray_at(tm_p, 52))
def _set_rgb_values(buf, index, value): #print("_set_rgb_values(0x%x, %d, %r)" % (addressof(buf), index, value)) if isinstance(value, int): value = bytearray_at(value, 3) i = index * 3 # G, R, B buf[i] = value[1] buf[i+1] = value[0] buf[i+2] = value[2]
def sync(self, to=None): if to is None: self.spi.send(self.buf) else: short_buf = bytearray_at(addressof(self.buf), 3*4*to + 1) # extra byte t = short_buf[-1] short_buf[-1] = 0 self.spi.send(short_buf) short_buf[-1] = t
def alloc_exec(sz): ptr = array.array("L", [0]) size = array.array("L", [0]) #print(ptr, size) mp_unix_alloc_exec(sz, ptr, size) #print(ptr, size) b = uctypes.bytearray_at(ptr[0], sz) #print(b) return b
def __init__(self): stm.mem32[stm.RCC + stm.RCC_APB1ENR] |= 0x10000000 # PWREN bit stm.mem32[ stm.PWR + stm. PWR_CR] |= 0x100 # Set the DBP bit in the PWR power control register stm.mem32[stm.RCC + stm.RCC_AHB1ENR] |= 0x40000 # enable BKPSRAMEN stm.mem32[stm.PWR + stm.PWR_CSR] |= 0x200 # BRE backup register enable bit self._ba = uctypes.bytearray_at(self.BKPSRAM, 4096)
def _set_rgb_values(buf, index, value): #print("_set_rgb_values(0x%x, %d, %r)" % (addressof(buf), index, value)) if isinstance(value, int): value = bytearray_at(value, 3) i = index * 3 # G, R, B buf[i] = value[1] buf[i + 1] = value[0] buf[i + 2] = value[2]
def sync(self, to=None): if to is None: self.spi.send(self.buf) else: short_buf = bytearray_at(addressof(self.buf), 3 * 4 * to + 1) # extra byte t = short_buf[-1] short_buf[-1] = 0 self.spi.send(short_buf) short_buf[-1] = t
def _pchfast(self, char, invert=False, recurse=False): s = self._getstate() self._get_char(char, recurse) if self.glyph is None: return # All done buf = bytearray_at(addressof(self.glyph), len(self.glyph)) fbc = framebuf.FrameBuffer(buf, self.char_width, self.char_height, self.map) fgcolor = self.bgcolor if invert else self.fgcolor bgcolor = self.fgcolor if invert else self.bgcolor render(self.device, fbc, s.text_col, s.text_row, fgcolor, bgcolor) s.text_col += self.char_width self.cpos += 1
def initialize(): global initialized, buf, screen, _tim if initialized: return False buf = uctypes.bytearray_at(_ledmatrix.init(), WIDTH * HEIGHT) screen = framebuf.FrameBuffer(buf, WIDTH, HEIGHT, framebuf.RGB332) _tim = pyb.Timer(4) pyb.Pin.board.PC0.init(pyb.Pin.OUT_PP) pyb.Pin.board.PC1.init(pyb.Pin.IN, pyb.Pin.PULL_UP) pyb.Pin.board.PC2.init(pyb.Pin.OUT_PP) initialized = True return True
def image_blob(self): """Gets the image raw binary data""" _reset_iterator(self._wand) length = bytearray(calcsize('P')) data = _get_image_blob(self._wand, length) try: length = unpack('P', length)[0] # It is a bit inefficient to copy the data, but it is needed for # seamless memory management return bytearray_at(data, length)[:] finally: _relinquish_memory(data)
def main(): ROM = uctypes.bytearray_at(0x40200000, 16) fid = esp.flash_id() print("Flash ID: %x (Vendor: %x Device: %x)" % (fid, fid & 0xff, fid & 0xff00 | fid >> 16)) print("Flash bootloader data:") SZ_MAP = {0: "512KB", 1: "256KB", 2: "1MB", 3: "2MB", 4: "4MB"} FREQ_MAP = {0: "40MHZ", 1: "26MHZ", 2: "20MHz", 0xf: "80MHz"} print("Byte @2: %02x" % ROM[2]) print("Byte @3: %02x (Flash size: %s Flash freq: %s)" % (ROM[3], SZ_MAP.get(ROM[3] >> 4, "?"), FREQ_MAP.get(ROM[3] & 0xf)))
def blank_object(item): # Use/abuse uctypes to blank objects until python. Will likely # even work on immutable types, so be careful. Also works # well to kill references to sensitive values (but not copies). # if isinstance(item, (bytearray, bytes, str)): addr, ln = uctypes.addressof(item), len(item) buf = uctypes.bytearray_at(addr, ln) for i in range(ln): buf[i] = 0 elif isinstance(item, tcc.bip32.HDNode): item.blank() else: raise TypeError(item)
def _printchar(self, char, invert=False, recurse=False): s = self._getstate() self._get_char(char, recurse) if self.glyph is None: return # All done buf = bytearray_at(addressof(self.glyph), len(self.glyph)) fbc = framebuf.FrameBuffer(buf, self.clip_width, self.char_height, self.map) palette = self.device.palette palette.bg(self.fgcolor if invert else self.bgcolor) palette.fg(self.bgcolor if invert else self.fgcolor) self.device.blit(fbc, s.text_col, s.text_row, -1, palette) s.text_col += self.char_width self.cpos += 1
def _enqueue(self, data): """ Adds a data record to the queue. Raises a QueueOverrunException when there are no more slots available in in the queue. Parameters ---------- data An uctype stucture holding the message to add to the queue. The structure SHOULD conform to the definition given when creating the MemFifo object or should at least have the same size. Longer structures get silently truncated when addded to the queue. """ hdr = self._hdr if hdr.full: raise QueueOverrun() addr = self._data_addr + hdr.elem_size * hdr.wr_i src = uctypes.bytearray_at(uctypes.addressof(data), hdr.elem_size) dst = uctypes.bytearray_at(addr, hdr.elem_size) dst[:] = src[:] hdr.wr_i = self._incr_wrap(hdr.wr_i) hdr.full = hdr.wr_i == hdr.rd_i
def __init__(self, ws, start=0, end=None): self.ws = ws if start < -len(ws) or start >= len(ws): raise IndexError("start %d is outside underlying ws of length %d" % (start, len(ws))) start %= len(ws) self.start = start if end is None: self.end = len(ws) else: self.end = end self.pixels = ws[start:end] self.sync = ws.sync # risky self.mem = ws.mem self.a = uctypes.addressof(ws.buf) + 3 * 4 * start self.buf = uctypes.bytearray_at(self.a, 3 * 4 * (end - start))
def blank_object(item): # Use/abuse uctypes to blank objects until python. Will likely # even work on immutable types, so be careful. Also works # well to kill references to sensitive values (but not copies). # if isinstance(item, (bytearray, bytes, str)): addr, ln = uctypes.addressof(item), len(item) buf = uctypes.bytearray_at(addr, ln) for i in range(ln): buf[i] = 0 elif isinstance(item, trezorcrypto.bip32.HDNode): pass # This function was added by coinkite # TODO: Important enough to add blank() back into trezor? # item.blank() else: raise TypeError(item)
def print_char(self, c, wrap, fgcolor, bgcolor, tab=32): # get the character's pixel bitmap and dimensions if self.text_font: glyph, rows, cols = self.text_font.get_ch(c) else: raise AttributeError('No font selected') if c == '\n': self._newline(rows) return 0 if c == '\t': xs = self.text_x self.text_x += tab - self.text_x % tab return self.text_x - xs # test char fit if wrap: if self.text_x + cols >= self.w: # does the glyph fit on the screen? self._newline(rows) # wrap to next text row then print if self.text_x + cols >= self.w or self.text_y + rows >= self.h: return 0 # Glyph is not entirely on screen fbuf = framebuf.FrameBuffer(self.glyph_buf, cols, rows, framebuf.RGB565) if fast_mode: buf = bytearray_at(addressof(glyph), len(glyph)) # Object with buffer protocol fbc = framebuf.FrameBuffer(buf, cols, rows, framebuf.MONO_HLSB) render(fbuf, fbc, 0, 0, fgcolor, bgcolor) else: div, mod = divmod(cols, 8) # Horizontal mapping gbytes = div + 1 if mod else div # No. of bytes per row of glyph for row in range(rows): for col in range(cols): gbyte, gbit = divmod(col, 8) if gbit == 0: # Next glyph byte data = glyph[row * gbytes + gbyte] fbuf.pixel( col, row, fgcolor if data & (1 << (7 - gbit)) else bgcolor) self.set_spi_win(self.text_x, self.text_y, cols, rows) self.show_framebuf(fbuf) self.text_x += cols return cols
def printScreen(string, display, font, col_start, row_start, fg=st7789.YELLOW, bg=st7789.BLACK): for char in string: glyph, char_height, char_width = font.get_ch(char) buf = bytearray_at(addressof(glyph), len(glyph)) buffer = bytearray(char_width * char_height * 2) display.map_bitarray_to_rgb565(buf, buffer, char_width, fg, bg) display.blit_buffer(buffer, col_start, row_start, char_width, char_height) col_start += char_width
def main(): ROM = uctypes.bytearray_at(0x40200000, 16) fid = esp.flash_id() print("FlashROM:") print("Flash ID: %x (Vendor: %x Device: %x)" % (fid, fid & 0xff, fid & 0xff00 | fid >> 16)) print("Flash bootloader data:") SZ_MAP = {0: "512KB", 1: "256KB", 2: "1MB", 3: "2MB", 4: "4MB"} FREQ_MAP = {0: "40MHZ", 1: "26MHZ", 2: "20MHz", 0xf: "80MHz"} print("Byte @2: %02x" % ROM[2]) print("Byte @3: %02x (Flash size: %s Flash freq: %s)" % (ROM[3], SZ_MAP.get(ROM[3] >> 4, "?"), FREQ_MAP.get(ROM[3] & 0xf))) print("\nNetworking:") print("Free WiFi driver buffers of type:") for i in range(5): print("%d: %d" % (i, esp.esf_free_bufs(i))) print("lwIP PCBs:") lwip.print_pcbs()
def main(): ROM = uctypes.bytearray_at(0x40200000, 16) fid = esp.flash_id() print("FlashROM:") print("Flash ID: %x (Vendor: %x Device: %x)" % (fid, fid & 0xff, fid & 0xff00 | fid >> 16)) print("Flash bootloader data:") SZ_MAP = {0: "512KB", 1: "256KB", 2: "1MB", 3: "2MB", 4: "4MB"} FREQ_MAP = {0: "40MHZ", 1: "26MHZ", 2: "20MHz", 0xf: "80MHz"} print("Byte @2: %02x" % ROM[2]) print("Byte @3: %02x (Flash size: %s Flash freq: %s)" % (ROM[3], SZ_MAP.get(ROM[3] >> 4, "?"), FREQ_MAP.get(ROM[3] & 0xf))) print("Firmware checksum:") print(esp.check_fw()) print("\nNetworking:") print("STA ifconfig:", network.WLAN(network.STA_IF).ifconfig()) print("AP ifconfig:", network.WLAN(network.AP_IF).ifconfig()) print("Free WiFi driver buffers of type:") for i, comm in enumerate(("1,2 TX", "4 Mngmt TX(len: 0x41-0x100)", "5 Mngmt TX (len: 0-0x40)", "7", "8 RX")): print("%d: %d (%s)" % (i, esp.esf_free_bufs(i), comm)) print("lwIP PCBs:") lwip.print_pcbs()
def cmp(pa, pb): a = uctypes.bytearray_at(pa, 1) b = uctypes.bytearray_at(pb, 1) print("cmp:", a, b) return a[0] - b[0]
def _alloc(ln): global _start rv = uctypes.bytearray_at(_start, ln) _start += ln return rv
try: import uctypes except ImportError: print("SKIP") raise SystemExit data = bytearray(b"01234567") print(uctypes.bytes_at(uctypes.addressof(data), 4)) print(uctypes.bytearray_at(uctypes.addressof(data), 4)) print(uctypes.bytes_at(uctypes.addressof(data) + 2))
try: import uctypes except ImportError: print("SKIP") raise SystemExit data = bytearray(b'01234567') print(uctypes.bytes_at(uctypes.addressof(data), 4)) print(uctypes.bytearray_at(uctypes.addressof(data), 4))
def __init__(self): stm.mem32[stm.RCC + stm.RCC_APB1ENR] |= 0x10000000 # PWREN bit stm.mem32[stm.PWR + stm.PWR_CR] |= 0x100 # Set the DBP bit in the PWR power control register stm.mem32[stm.RCC +stm.RCC_AHB1ENR]|= 0x40000 # enable BKPSRAMEN stm.mem32[stm.PWR + stm.PWR_CSR] |= 0x200 # BRE backup register enable bit self._ba = uctypes.bytearray_at(self.BKPSRAM, 4096)
def pgm_save(buf, wrap, xsize, ysize, fname): with open(fname, "wb") as f: f.write("P5\n%d %d\n%d\n" % (xsize, ysize, 255)) for i in range(ysize): f.write(uctypes.bytearray_at(int(buf) + i * wrap, xsize))
def find_first_erased_addr(self): for addr in SLOT_ADDRS: buf = uctypes.bytearray_at(addr, 4) if buf[0] == buf[1] == buf[2] == buf[3] == 0xff: return addr return 0
def go(operation='', field='chain', value='BTC'): import common from sram4 import viewfinder_buf print('2: Available RAM = {}'.format(gc.mem_free())) # Avalanche noise source from foundation import Noise common.noise = Noise() # Get the async event loop to pass in where needed common.loop = asyncio.get_event_loop() # System from foundation import System common.system = System() print('2.75: Available RAM = {}'.format(gc.mem_free())) # Initialize the keypad from keypad import Keypad common.keypad = Keypad() print('3: Available RAM = {}'.format(gc.mem_free())) # Initialize SD card from files import CardSlot CardSlot.setup() print('3.5: Available RAM = {}'.format(gc.mem_free())) # External SPI Flash from sflash import SPIFlash common.sf = SPIFlash() # Initialize NV settings from settings import Settings common.settings = Settings(common.loop) print('4: Available RAM = {}'.format(gc.mem_free())) # Initialize the display and show the splash screen from display import Display print("disp 1") common.dis = Display() print("disp 2") common.dis.set_brightness(common.settings.get('screen_brightness', 100)) print("disp 3") common.dis.splash() print('5: Available RAM = {}'.format(gc.mem_free())) # Allocate buffers for camera from constants import VIEWFINDER_WIDTH, VIEWFINDER_HEIGHT, CAMERA_WIDTH, CAMERA_HEIGHT # QR buf is 1 byte per pixel grayscale import uctypes common.qr_buf = uctypes.bytearray_at(0x20000000, CAMERA_WIDTH * CAMERA_HEIGHT) # common.qr_buf = bytearray(CAMERA_WIDTH * CAMERA_HEIGHT) print('6: Available RAM = {}'.format(gc.mem_free())) # Viewfinder buf 1s 1 bit per pixel and we round the screen width up to 240 # so it's a multiple of 8 bits. The screen height of 303 minus 31 for the # header and 31 for the footer gives 241 pixels, which we round down to 240 # to give one blank (white) line before the footer. common.viewfinder_buf = bytearray( (VIEWFINDER_WIDTH * VIEWFINDER_HEIGHT) // 8) print('7: Available RAM = {}'.format(gc.mem_free())) # Show REPL welcome message print("Passport by Foundation Devices Inc. (C) 2020.\n") print('8: Available RAM = {}'.format(gc.mem_free())) from foundation import SettingsFlash f = SettingsFlash() if operation == 'dump': print('Settings = {}'.format(common.settings.curr_dict)) print('addr = {}'.format(common.settings.addr)) elif operation == 'erase': f.erase() elif operation == 'set': common.settings.set(field, value) elif operation == 'stress': for f in range(35): print("Round {}:".format(f)) print(' Settings = {}'.format(common.settings.curr_dict)) common.settings.set('field_{}'.format(f), f) common.settings.save() print('\nFinal Settings = {}'.format(common.settings.curr_dict)) # This "pa" object holds some state shared w/ bootloader about the PIN try: from pincodes import PinAttempt common.pa = PinAttempt() common.pa.setup(b'') except RuntimeError as e: print("Secure Element Problem: %r" % e) print('9: Available RAM = {}'.format(gc.mem_free())) # Setup the startup task common.loop.create_task(startup()) run_loop()
async def dispatch_DebugLinkMemoryWrite(ctx, msg): from uctypes import bytearray_at l = len(msg.memory) data = bytearray_at(msg.address, l) data[0:l] = msg.memory
def decrypt(self, ciphertext: bytearray) -> bytearray: # Decrypts ciphertext in-place. Returns a zero-copy bytearray up to where # the padding begins. self._decryptor.decrypt(ciphertext, ciphertext) n = PKCS7.verify(ciphertext, self.block_size) return uctypes.bytearray_at(uctypes.addressof(ciphertext), n)
def load(self): # Search all slots for any we can read, decrypt that, # and pick the newest one (in unlikely case of dups) try: # reset self.curr_dict.clear() self.overrides.clear() self.addr = 0 self.is_dirty = 0 for addr in SLOT_ADDRS: buf = uctypes.bytearray_at(addr, 4) if buf[0] == buf[1] == buf[2] == buf[3] == 0xff: # Save this so we can start at an empty slot when no decodable data # is found (we can't just start at the beginning since it might # not be erased). # print(' Slot is ERASED') # erased (probably) continue # check if first 2 bytes makes sense for JSON flash_offset = (addr - SETTINGS_FLASH_START) // BLOCK_SIZE aes = self.get_aes(flash_offset) chk = aes.decrypt(b'{"') if chk != buf[0:2]: # doesn't look like JSON, so skip it # print(' Slot does not contain JSON') continue # probably good, so prepare to read it aes = self.get_aes(flash_offset) chk = trezorcrypto.sha256() expect = None # Copy the data - our flash is memory mapped, so we read directly by address buf = uctypes.bytearray_at(addr, DATA_SIZE) # Get a bytearray for the SHA256 at the end expected_sha = uctypes.bytearray_at(addr + DATA_SIZE, 32) # Decrypt and check hash b = aes.decrypt(buf) # Add the decrypted result to the SHA chk.update(b) try: # verify hash in last 32 bytes assert expected_sha == chk.digest() # FOUNDATION # loads() can't work from a byte array, and converting to # bytes here would copy it; better to use file emulation. # print('json = {}'.format(b)) d = ujson.load(BytesIO(b)) except: # One in 65k or so chance to come here w/ garbage decoded, so # not an error. # print('ERROR? Unable to decode JSON') continue curr_version = d.get('_version', 0) if curr_version > self.curr_dict.get('_version', -1): # print('Found candidate JSON: {}'.format(d)) # A newer entry was found self.curr_dict = d self.addr = addr # If we loaded settings, then we're done if self.addr: return # Add some che # if self. # If no entries were found, which means this is either the first boot or we have corrupt settings, so raise an exception so we erase and set default # raise ValueError('Flash is either blank or corrupt, so me must reset to recover to avoid a crash!') self.curr_dict = self.default_values() self.overrides.clear() self.addr = 0 except Exception as e: print('Exception in settings.load(): e={}'.format(e)) self.reset() self.is_dirty = True self.write_out()
def mmap(fd, sz, flags, prot, access=None, offset=0): ptr = mmap_(None, sz, prot, flags, fd, offset) return uctypes.bytearray_at(ptr, sz)