def __init__(self, template): self.fl = open(template + "_iram_l.tmp", "w") self.fh = open(template + "_iram_h.tmp", "w") self.fda = open(template + "_dram_a.tmp", "w") self.fdb = open(template + "_dram_b.tmp", "w") self.text = intelhex.IntelHex() self.data_a = intelhex.IntelHex() self.data_b = intelhex.IntelHex() self.endian = ">"
def __init__(self, template, size = 2): self.textfile = open(template + "_text.tmp", "w") self.datafile = open(template + "_data.tmp", "w") self.text = intelhex.IntelHex() self.data = intelhex.IntelHex() self.size = size self.endian = ">" self.text_offset = 0x0000 self.data_offset = 0xc000
def action_program(self, input): import usb.core import usb.util import intelhex self.dev_info = None success = False dev = self.connect_digispark(usb) if dev != None: print_info("Digispark detected!") self.get_info(usb, dev) if self.parameters["digispark_print_dev_info"]["value"].upper( ) == "TRUE": self.print_info() if self.program_erase(usb, dev) != 0: return "Error erasing deigispark!" firmware = [0xff] * (65536 + 256) ih = intelhex.IntelHex() ih.loadhex((os.path.dirname(__file__).strip() + "/digispark/digispark_keyboard_firmware.hex").strip()) f_size = 0 for k, v in ih.todict().iteritems(): firmware[int(k)] = chr(v) f_size = int(k) if int(k) > f_size else f_size stat, firmware = self.patch_firmware(firmware, input) if stat != "": return "Error patching firmware: %s " % stat self.program_write_flash(firmware, f_size, dev, usb) return "" else: return "Digispark not detected in 30s aborting!"
def bootload_modules(module_type, filename, logger, master_communicator=INJECTED): """ Bootload all modules of the given type with the firmware in the given filename. :param module_type: Type of the modules (O, R, D, I, T, C) :type module_type: str :param filename: The filename for the hex file to load :type filename: str :param logger: Logger :param master_communicator: used to read the addresses from the master eeprom. :type master_communicator: MasterCommunicator """ master_communicator.start() addresses = get_module_addresses(module_type) blocks = 922 if module_type == 'C' else 410 ihex = intelhex.IntelHex(filename) crc = calc_crc(ihex, blocks) update_success = True for address in addresses: logger('Bootloading module {0}'.format(pretty_address(address))) try: bootload(master_communicator, address, ihex, crc, blocks, logger) except Exception: update_success = False logger('Bootloading failed:') logger(traceback.format_exc()) return update_success
def main(ihex_input, dfu_output, device): if not os.path.isfile(ihex_input): raise RuntimeError(f"Input file {ihex_input} doesn't exist") ihex = intelhex.IntelHex(ihex_input) if device == 'stm32': flash_table = STM32_FLASH_TABLE device = STM32_DEVICE dfu_version = STM32_DFU_VERSION elif device == 'sam': flash_table = SAM_FLASH_TABLE device = SAM_DEVICE dfu_version = SAM_DFU_VERSION else: print("Must specify a device") sys.exit(-1) target = [] for segment in flash_table: # TODO: Could be more efficient here by finding the max address within the # FLASH_TABLE segment. As-is, the first section will always be padded to fill the # section, even though its much shorter segment_size = min(ihex.maxaddr() - segment[0], segment[1]) bindata = bytes(ihex.tobinarray(start=segment[0], size=segment_size)) print(f"Writing data from start={hex(segment[0])} size={segment_size}") print(f"Size: {len(bindata)}") target.append({'address': segment[0], 'data': bindata}) build(dfu_output, [target], device, dfu_version)
def flash_read_to_hex(size=16): # result = [] if size not in [16, 32]: raise Exception("Cannot read flash size {} only 16 or 32".format(size)) page_size = 0x200 block_size = 0x40 blocks_per_16kb = 0x100 hexfile = intelhex.IntelHex() cur_addr = 0x0000 def read_16kb_region(): chunks_per_block = 4 chunk_size = block_size // chunks_per_block nonlocal cur_addr for i in range(blocks_per_16kb): block = flash_read_block(i) # break the block into chunks to we can check which regions # actuall have flash data for chunk in chunk_iterator(block, chunk_size): if not is_empty_flash_data(chunk): hexfile.puts(cur_addr, bytes(chunk)) cur_addr += chunk_size flash_select_half(0) read_16kb_region() if size == 32: flash_select_half(1) read_16kb_region() return hexfile
def flash_device(self, list_of_files: List[str], expected_version: Optional[str] = None, expected_build_type: Optional[str] = None, verify_flash: bool = True, method: Optional[str] = None) -> None: """Flashes the firmware image (.hex file) on the device. Args: list_of_files: Image files on local host, currently supports flashing only one hex file at a time. expected_version: Not used. expected_build_type: Not used. verify_flash: Not used. method: Not used. """ del expected_version, expected_build_type, verify_flash, method # Unused. if len(list_of_files) != 1: raise ValueError("Only one hex file can be flashed via JLink.") image_path = list_of_files[0] if not image_path.endswith(".hex"): raise ValueError("Only hex type file can be flashed.") if not os.path.exists(image_path): raise errors.DeviceError( f"Firmware image {image_path} does not exist.") self._open_and_halt() image = intelhex.IntelHex(os.path.abspath(image_path)) for segment_start, segment_end in image.segments(): segment_size = segment_end - segment_start segment = image.tobinarray(start=segment_start, size=segment_size) self._jlink.flash_write8(segment_start, segment) self._reset_and_close()
def write_hexfile(self, filename, generate_crc=None): max_write_addr = 0x6800 crc_addr = max_write_addr - 2 hexfile = intelhex.IntelHex() hexfile.padding = 0xff with open(filename) as f: hexfile.loadhex(f) print(hexfile.maxaddr(), max_write_addr - 2) if generate_crc == None and hexfile.maxaddr() < max_write_addr - 2: generate_crc = True if generate_crc: if hexfile.maxaddr() > max_write_addr - 2: raise HexfileTooBig("hexfile too big") crc = crc16.crc16(hexfile, max_write_addr - 2) hexfile[crc_addr + 0] = hi(crc) hexfile[crc_addr + 1] = lo(crc) else: if hexfile.maxaddr() > max_write_addr: raise HexfileTooBig("hexfile too big") expected_crc = crc16.crc16(hexfile, max_write_addr - 2) got_crc = (hexfile[crc_addr + 0] << 8) | (hexfile[crc_addr + 1]) if expected_crc != got_crc: raise BadCRC16("Invalid crc16 include inhexfile. Expected 0x{:x}, got 0x{:x}" \ .format(expected_crc, got_crc)) # hexfile.dump() for i in range(MAX_PROGRAMMABLE_PAGE + 1): self.cmd_erase_page(i) # a = [hex(hexfile[i]) for i in range(1, max_write_addr)] # print(a, hex(len(a))) self.cmd_write_bytes( 0x0001, array('B', [hexfile[i] for i in range(1, max_write_addr)])) self.cmd_write_bytes(0x0000, array('B', [hexfile[0]]))
def parseFromHex(hexfile, parameters): hexdict = intelhex.IntelHex(hexfile).todict() for parameter in parameters: vals = [] for offset in range(parameter.dict[jsonSize]): vals += [hexdict[parameter.dict[jsonAddress] + offset]] parameter.dict[jsonDefaultValue] = vals
def load_intelhex_firmware(self, filename): """Loads firmware from an IntelHex formatted file""" total = 0 fw_hex = intelhex.IntelHex(filename) if not self.reset(enable_cpu=False): raise IOError("Failed to halt CPU") for seg_start, seg_end in fw_hex.segments(): data = fw_hex.tobinstr(start=seg_start, end=seg_end - 1) # libusb issue #110 https://github.com/libusb/libusb/issues/110 offset = 0 while len(data) > 0: end = len(data) if end > self.MAX_CTRL_BUFFER_LENGTH: end = self.MAX_CTRL_BUFFER_LENGTH print("0x{0:04x} loading {1:4d} bytes".format( seg_start + offset, end)) wrote = self.dev.ctrl_transfer(self.REQ_WRITE, self.CMD_RW_INTERNAL, seg_start + offset, 0x00, data[:end]) if not wrote == end: raise IOError("Failed to write %d bytes to %x" % (end, seg_start)) total += wrote offset += wrote data = data[end:] if not self.reset(enable_cpu=True): raise IOError("Failed to start CPU") return total
def upgrade_fw(hex_file_name, skip_goto, device_name): ih = intelhex.IntelHex() ih.fromfile(hex_file_name, "hex") if not skip_goto: goto_bootloader(device_name) sleep(6) log_level = 1 if device_name == "auto": devices = auto() if len(devices) == 0: print("Failed to find COM port matching known vid and pids") return 1 device_name = devices[0] bootloader = Bootloader(device_name, log_level) print(bootloader.get_bootloader_info()) flash_offset = 0x400000 blob = ih.tobinarray(start=flash_offset) page_size = 512 pages = len(blob) / page_size if (len(blob) % page_size) > 0: pages += 1 for page in range(0, int(pages)): if page == 0 or page > 127: address = flash_offset + page * page_size bootloader.write_page(page, ih.tobinarray(start=address, size=page_size)) sleep(1) bootloader.start_application(12) print("done")
def open_hex(filename): try: ih = intelhex.IntelHex(filename) return ih except (IOError, intelhex.IntelHexError), e: print('Error reading file: %s\n' % e) raise Exception("Could not read hex format")
def readProgram(conn, nbPages=None): pagesMax = 256 - 8 if nbPages == None: nbPages = pagesMax if nbPages > pagesMax: print('WARNING: a maximum of {} pages can be read'.format(pagesMax)) nbPages = pagesMax ihx = intelhex.IntelHex() for page in range(nbPages): packet = readProgramPagePacket(page) conn.write(packet) bytesToRead = 0x100 + 1 data = b'' if page == 0: data += conn.read(1) bytesToRead -= 1 if data == b'\x07': print('Cannot read program.') if conn.dev: leave(1) data += conn.read(bytesToRead) if not verify_checksum(data): print('Checksum fail') if conn.dev: leave(1) return None ihx.frombytes(data[:-1], page * 0x100) return ihx
def loadImage(self, imageFile): try: self.__h = intelhex.IntelHex(str(imageFile)) self.__h.padding = 0xFF except intelhex.IntelHexError as e: raise SimplePWMError(f"Failed to parse hex file '{imageFile}':\n" f"{str(e)}")
def bootload_modules(module_type, filename, gen3_firmware, version): # type: (str, str, bool, Optional[str]) -> bool """ Bootload all modules of the given type with the firmware in the given filename. :param module_type: Type of the modules (O, R, D, I, T, C) :param filename: The filename for the hex file to load :param gen3_firmware: Indicates whether it's a gen3 firmware :param version: The version of the hexfile, if known """ logger.info('Loading module addresses...') addresses = get_module_addresses(module_type) blocks = 922 if module_type == 'C' else 410 ihex = intelhex.IntelHex(filename) crc = calc_crc(ihex, blocks) update_success = True for address in addresses: logger.info('Bootloading module {0}'.format(pretty_address(address))) try: bootload(address, ihex, crc, blocks, version, gen3_firmware) except Exception: update_success = False logger.info('Bootloading failed:') logger.info(traceback.format_exc()) return update_success
def __init__(self): """ """ # instantiate a hex object self.ihex = intelhex.IntelHex() self.temp_dir = None self.hex_file = ""
def generate(self, path, offset=PRODUCTION_CONFIG_DEFAULT_OFFSET): # Calculate the CRC-16 of the install code self._struct = ( struct.pack( self.PRODUCTION_CONFIG_HEADER_FORMAT, struct.calcsize(self.PRODUCTION_CONFIG_HEADER_FORMAT) + 4 + self._ad_len, # Plus the CRC-32; plus the app_data self.PRODUCTION_CONFIG_VERSION, self._parsed_values["channel_mask"], self._parsed_values["extended_address"], self._parsed_values["tx_power"], self._parsed_values["install_code"], self._ic_crc) + self._parsed_values["app_data"]) crc32 = self._custom_crc32(self._struct) output = struct.pack( '<L', self.PRODUCTION_CONFIG_MAGIC_NUMBER) + struct.pack( '<L', crc32) + self._struct if len( output ) > self.PRODUCTION_CONFIG_SIZE_MAX + 4: # 4 is for Magic Number raise ProductionConfigTooLargeException(len(output)) ih = intelhex.IntelHex() ih.puts(offset, output) ih.write_hex_file(path)
def write_flash_hex(self, hexFile, hexFormat='hex'): """ Write a hex file to the bootloader. Parameters: hexFile: file name or file-like object hexFormat: file format ('hex' or 'bin') """ ihex = intelhex.IntelHex() ihex.fromfile(hexFile, hexFormat) # check that the hex file fits into the application section if ihex.maxaddr() >= self.info.bootloaderStart: raise EFM8BootloaderHexError( "Hex file too large. Available space for application is {} " "bytes, but got {} bytes.".format( self.info.bootloaderStart, ihex.maxaddr(), )) # get a list of flash pages from the hex file pages = self._packetizeHex(ihex, self.info.pageSize) if len(pages) == 0: return firstPageAddr = pages[0][0] firstPageData = pages[0][1] # Enable writing to flash self._auto_modify_enable() # The bootloader checks the flash byte at 0x0000 to determine if the # flash is empty and will run the bootloader at start up if it is. # # To help improve reliability erase this page first and write it last. # This way, if the bootloader is interrupted before it can write this # page, when the device is reset, it will still enter the bootloader. if firstPageAddr == 0x0000: # Erase the page at start of flash self.erase_page(firstPageAddr) else: # If the hex file doesn't write to 0x0000, then write the page now self.write_page(firstPageAddr, firstPageData) # Write all the other pages for (pageAddr, pageData) in pages[1:]: self.write_page(pageAddr, pageData) # Finally, write the page at start of flash if firstPageAddr == 0x0000: self.write_page(firstPageAddr, firstPageData, erase=False) for (segStart, segEnd) in ihex.segments(): crc = self.compute_crc(ihex.tobinstr(segStart, segEnd)) self.verify(segStart, segEnd, crc) # Disable further flash modifications self._auto_modify_disable()
def Load(name): # init and empty code dictionary info.dHex = None try: info.dHex = intelhex.IntelHex(name) return True except: return False
def main(): if len(sys.argv) != 3: print "Usage: %s [hexfile] [outfile]" % (sys.argv[0], ) sys.exit(1) hexfile = intelhex.IntelHex(sys.argv[1]) if hexfile.minaddr() != APP_START: print "Error: image does not start at %x" % (APP_START, ) sys.exit(1) # Find the actual data length imagelen = (hexfile.maxaddr() - APP_START + IMAGE_ROUND) imagelen -= (imagelen % IMAGE_ROUND) # Insert data length as vector 8 data_len = struct.pack("<I", imagelen) hexfile.puts(APP_START + 0x20, data_len) # Extract the binary image data data = hexfile.tobinstr(start = APP_START) print "Image length: %d / %x (rounded up from %d)" % ( imagelen, imagelen, len(data)) data = data.ljust(imagelen, "\0") # Add a crc crc = zlib.crc32(data) & 0xffffffff print "CRC: 0x%08x" % (crc, ) crcdata = struct.pack("<I", crc) data += crcdata + "\0" * 252 # Tack on a header image = ("j4cDAC firmware image - DO NOT EDIT\n".ljust(51, "~") + "\n" + struct.pack("<I", 0x12345678) + crcdata + data_len + data) file(sys.argv[2], "w").write(image) print "Wrote %d bytes." % (len(image), ) h2 = intelhex.IntelHex() h2.loadbin(StringIO.StringIO(data), APP_START) h2.tofile(sys.argv[2] + "hex", format='hex')
def sendProgram(conn, f): ihx = intelhex.IntelHex() ihx.loadhex(f) for start, stop in segments(ihx): binstr = ihx[start:stop].tobinstr() packets = writeProgramMemoryPackets(start, binstr) for packet in packets: sendPacket(conn, packet)
def hex2dump(hexfile, start=None, end=None): import intelhex if hexfile == '-': hexfile = sys.stdin try: ih = intelhex.IntelHex(hexfile) except (IOError, intelhex.IntelHexError), e: sys.stderr.write('Error reading file: %s\n' % e) return 1
def bin_data_to_hex_data(addr, data): """Covert binary data to a string in intel hex format""" intel_hex = intelhex.IntelHex() intel_hex.puts(addr, data) sio = cStringIO.StringIO() intel_hex.tofile(sio, format='hex') hex_data = sio.getvalue() hex_data = bytearray(hex_data) return hex_data
def write_hex(self, hexfile): # Info page metadata raw_data = bytearray(struct.pack("<BBBB", 4, 1, 8, 8)) raw_data += bytearray().join(map(DevicePageEntry.serialize, self.entries)) raw_data += bytearray(struct.pack("<HH", 0xFFFF, BLInfoType.LAST)) hex_output = intelhex.IntelHex() hex_output.frombytes(raw_data, self.platform["flash_size"] - self.platform["page_size"]) hex_output.tofile(hexfile, "hex")
def main(): if len(sys.argv) != 3: print "Usage: %s [hexfile] [outfile]" % (sys.argv[0], ) sys.exit(1) hexfile = intelhex.IntelHex(sys.argv[1]) lpc1758_fixup(hexfile) hexfile.tofile(sys.argv[2], format = "hex")
def bin_data_to_hex_data(addr, data): """Covert binary data to a string in intel hex format""" intel_hex = intelhex.IntelHex() if sys.version_info >= (3,0): data = data.decode('latin1') intel_hex.puts(addr, data) sio = StringIO() intel_hex.tofile(sio, format='hex') hex_data = sio.getvalue() return bytearray(hex_data.encode('latin1'))
def is_correct_file_type(filename): try: with zipfile.ZipFile(filename, "r") as _: pass except zipfile.BadZipfile: try: ih = intelhex.IntelHex() ih.loadhex(filename) except intelhex.IntelHexError: raise ValidationError(gettext("Invalid file type."))
def comparefiles(self, actual, wanted): actualfile = intelhex.IntelHex() actualfile.loadfile(actual, format="bin") wantedfile = intelhex.IntelHex() wantedfile.loadfile(wanted, format="bin") self.assertEqual(actualfile.minaddr(), wantedfile.minaddr()) self.assertEqual(actualfile.maxaddr(), wantedfile.maxaddr()) minaddress = actualfile.minaddr() maxaddress = actualfile.maxaddr() length = maxaddress - minaddress actualfile_data = actualfile.gets(minaddress, length) wantedfile_data = wantedfile.gets(minaddress, length) self.assertEqual(actualfile_data, wantedfile_data)
def __init__(self, version, key = '', iv = '', block_size = 512): self.ih = intelhex.IntelHex() self.ih.padding = 0xFF self.key = key self.iv = iv self.version = version self.block_size = block_size self.blocks = {} self.version_binary_str = self.parse_version(self.version) self.packed_buffer = None self.packed_hash = None
def read_data(config): raw_data = intelhex.IntelHex(config.filename).tobinarray() app_temp_size = config.app_size # Must pad out the crc calculation with 0xff up to the mem size. num_pad_bytes = app_temp_size - len(raw_data) pad_data = array.array('B', [0xff] * num_pad_bytes) crc = crc16(raw_data + pad_data) return (raw_data, crc)