def binary_hook(t_self, resources, elf, binf): for hexf in resources.hex_files: found = False for softdeviceAndOffsetEntry in NRF51822.EXPECTED_SOFTDEVICES_WITH_OFFSETS: if hexf.find(softdeviceAndOffsetEntry['name']) != -1: found = True break if found: break else: t_self.debug("Hex file not found. Aborting.") return # Merge user code with softdevice t_self.debug("Patching Hex file %s" % softdeviceAndOffsetEntry['name']) from intelhex import IntelHex binh = IntelHex() binh.loadbin(binf, offset=softdeviceAndOffsetEntry['offset']) if t_self.target.MERGE_SOFT_DEVICE is True: sdh = IntelHex(hexf) binh.merge(sdh) with open(binf.replace(".bin", ".hex"), "w") as f: binh.tofile(f, format='hex')
def save_image(self, path): if self.data_buffer: if path.lower().endswith('.bin'): with open(path, "wb") as f: f.write(self.data_buffer) f.close() elif path.lower().endswith('.hex'): ihex = IntelHex() ihex.frombytes(self.data_buffer, 0) ihex.start_addr = self.FlashStartAddress try: ihex.tofile(path, format='hex') except Exception as e: wx.MessageBox( "Could not write into file: %s\n\n%s" % (path, str(e)), 'ERROR', wx.OK | wx.ICON_ERROR) elif path.lower().endswith(('.s19', '.srec')): srec = SRecFile() srec.header = "KBOOT" srec.start_addr = self.FlashStartAddress srec.data = self.data_buffer try: srec.save(path) except Exception as e: wx.MessageBox( "Could not write into file: %s\n\n%s" % (path, str(e)), 'ERROR', wx.OK | wx.ICON_ERROR) else: wx.MessageBox('Not supported file Type !', 'ERROR', wx.OK | wx.ICON_ERROR) else: wx.MessageBox('No data to save', 'INFO', wx.OK | wx.ICON_INFORMATION)
def binary_hook(t_self, resources, elf, binf): from intelhex import IntelHex binh = IntelHex() binh.loadbin(binf, offset=0) with open(binf.replace(".bin", ".hex"), "w") as f: binh.tofile(f, format='hex')
def main_mergehex(): if len(sys.argv) < 3: print( 'usage: %s <file1.hex> <file2.hex> [...] [-s <secret_attestation_key>] <output.hex>' ) sys.exit(1) def flash_addr(num): return 0x08000000 + num * 2048 args = sys.argv[:] # generic / hacker attestation key secret_attestation_key = ( "1b2626ecc8f69b0f69e34fb236d76466ba12ac16c3ab5750ba064e8b90e02448" ) # user supplied, optional for i, x in enumerate(args): if x == '-s': secret_attestation_key = args[i + 1] args = args[:i] + args[i + 2 :] break # TODO put definitions somewhere else PAGES = 128 APPLICATION_END_PAGE = PAGES - 19 AUTH_WORD_ADDR = flash_addr(APPLICATION_END_PAGE) - 8 ATTEST_ADDR = flash_addr(PAGES - 15) first = IntelHex(args[1]) for i in range(2, len(args) - 1): print('merging %s with ' % (args[1]), args[i]) first.merge(IntelHex(args[i]), overlap='replace') first[flash_addr(APPLICATION_END_PAGE - 1)] = 0x41 first[flash_addr(APPLICATION_END_PAGE - 1) + 1] = 0x41 first[AUTH_WORD_ADDR - 4] = 0 first[AUTH_WORD_ADDR - 1] = 0 first[AUTH_WORD_ADDR - 2] = 0 first[AUTH_WORD_ADDR - 3] = 0 first[AUTH_WORD_ADDR] = 0 first[AUTH_WORD_ADDR + 1] = 0 first[AUTH_WORD_ADDR + 2] = 0 first[AUTH_WORD_ADDR + 3] = 0 first[AUTH_WORD_ADDR + 4] = 0xFF first[AUTH_WORD_ADDR + 5] = 0xFF first[AUTH_WORD_ADDR + 6] = 0xFF first[AUTH_WORD_ADDR + 7] = 0xFF if secret_attestation_key is not None: key = unhexlify(secret_attestation_key) for i, x in enumerate(key): first[ATTEST_ADDR + i] = x first.tofile(args[len(args) - 1], format='hex')
def merge_region_list(region_list, destination, padding=b'\xFF'): """Merege the region_list into a single image Positional Arguments: region_list - list of regions, which should contain filenames destination - file name to write all regions to padding - bytes to fill gapps with """ merged = IntelHex() print("Merging Regions:") for region in region_list: if region.active and not region.filename: raise ToolException("Active region has no contents: No file found.") if region.filename: print(" Filling region %s with %s" % (region.name, region.filename)) part = intelhex_offset(region.filename, offset=region.start) part_size = (part.maxaddr() - part.minaddr()) + 1 if part_size > region.size: raise ToolException("Contents of region %s does not fit" % region.name) merged.merge(part) pad_size = region.size - part_size if pad_size > 0 and region != region_list[-1]: print(" Padding region %s with 0x%x bytes" % (region.name, pad_size)) merged.puts(merged.maxaddr() + 1, padding * pad_size) if not exists(dirname(destination)): makedirs(dirname(destination)) print("Space used after regions merged: 0x%x" % (merged.maxaddr() - merged.minaddr() + 1)) with open(destination, "wb+") as output: merged.tofile(output, format='bin')
def main(): args = parser.parse_args() base_hex = IntelHex() # Merge in hex files for file_name in args.hex: file_name = os.path.expanduser(file_name) new_hex_data = IntelHex() print "opening file %s" % file_name new_hex_data.fromfile(file_name, format='hex') print_hex_info(file_name, new_hex_data) base_hex = merge_hex(base_hex, new_hex_data) # Merge in binary files for file_name, addr_str in args.bin: file_name = os.path.expanduser(file_name) offset = int(addr_str, 0) new_hex_data = IntelHex() new_hex_data.loadbin(file_name, offset=offset) print_hex_info(file_name, new_hex_data) base_hex = merge_hex(base_hex, new_hex_data) # Write out data print_hex_info(os.path.expanduser(args.output_file), base_hex) with open(os.path.expanduser(args.output_file), 'wb') as output_file: base_hex.tofile(output_file, 'hex') if args.output_bin_file is not None: with open(os.path.expanduser(args.output_bin_file), 'wb') as output_file: base_hex.tofile(output_file, 'bin')
def binary_hook(t_self, resources, elf, binf): from intelhex import IntelHex binh = IntelHex() binh.loadbin(binf, offset = 0) with open(binf.replace(".bin", ".hex"), "w") as f: binh.tofile(f, format='hex')
def show(self, dump=False, filtered=True, verbose=False): # type: (bool, bool, bool) -> Optional[str] s = super(UDS_RMBASequentialEnumerator, self).show( dump, filtered, verbose) or "" try: from intelhex import IntelHex ih = IntelHex() for tup in self.results_with_positive_response: for i, b in enumerate(tup.resp.dataRecord): addr = self.get_addr(tup.req) ih[addr + i] = orb(b) ih.tofile("RMBA_dump.hex", format="hex") except ImportError: err_msg = "Install 'intelhex' to create a hex file of the memory" log_interactive.critical(err_msg) with open("RMBA_dump.hex", "w") as file: file.write(err_msg) if dump: return s + "\n" else: print(s) return None
def append_validation_data(signature, input_file, public_key, offset, output_hex, output_bin, magic_value): ih = IntelHex(input_file) ih.start_addr = None # OBJCOPY incorrectly inserts x86 specific records, remove the start_addr as it is wrong. minimum_offset = ((ih.maxaddr() // 4) + 1) * 4 if offset != 0 and offset < minimum_offset: raise RuntimeError( f'Incorrect offset, must be bigger than {hex(minimum_offset)}') # Parse comma-separated string of uint32s into hex string. Each is encoded in little-endian byte order parsed_magic_value = b''.join( [struct.pack('<I', int(m, 0)) for m in magic_value.split(',')]) validation_data = get_validation_data(signature_bytes=signature, input_hex=ih, public_key=public_key, magic_value=parsed_magic_value) validation_data_hex = IntelHex() # If no offset is given, append metadata right after input hex file (word aligned). if offset == 0: offset = minimum_offset validation_data_hex.frombytes(validation_data, offset) ih.merge(validation_data_hex) ih.write_hex_file(output_hex) if output_bin: ih.tofile(output_bin.name, format='bin')
def save_image(self, path): if self.data_buffer: if path.lower().endswith(".bin"): with open(path, "wb") as f: f.write(self.data_buffer) f.close() elif path.lower().endswith(".hex"): ihex = IntelHex() ihex.frombytes(self.data_buffer, 0) ihex.start_addr = self.FlashStartAddress try: ihex.tofile(path, format="hex") except Exception as e: wx.MessageBox( "Could not write into file: %s\n\n%s" % (path, str(e)), "ERROR", wx.OK | wx.ICON_ERROR ) elif path.lower().endswith((".s19", ".srec")): srec = SRecFile() srec.header = "KBOOT" srec.start_addr = self.FlashStartAddress srec.data = self.data_buffer try: srec.save(path) except Exception as e: wx.MessageBox( "Could not write into file: %s\n\n%s" % (path, str(e)), "ERROR", wx.OK | wx.ICON_ERROR ) else: wx.MessageBox("Not supported file Type !", "ERROR", wx.OK | wx.ICON_ERROR) else: wx.MessageBox("No data to save", "INFO", wx.OK | wx.ICON_INFORMATION)
def binary_hook(t_self, resources, elf, binf): # Scan to find the actual paths of soft device and bootloader files sdf = None blf = None for hexf in resources.hex_files: if hexf.find(t_self.target.EXPECTED_BOOTLOADER_FILENAME) != -1: blf = hexf else: for softdeviceAndOffsetEntry in t_self.target.EXPECTED_SOFTDEVICES_WITH_OFFSETS: if hexf.find(softdeviceAndOffsetEntry['name']) != -1: sdf = hexf break if sdf is None: t_self.debug("Hex file not found. Aborting.") return # Merge user code with softdevice from intelhex import IntelHex binh = IntelHex() binh.loadbin(binf, offset=softdeviceAndOffsetEntry['offset']) if t_self.target.MERGE_SOFT_DEVICE is True: t_self.debug("Merge SoftDevice file %s" % softdeviceAndOffsetEntry['name']) sdh = IntelHex(sdf) binh.merge(sdh) if t_self.target.MERGE_BOOTLOADER is True and blf is not None: t_self.debug("Merge BootLoader file %s" % t_self.target.EXPECTED_BOOTLOADER_FILENAME) blh = IntelHex(blf) binh.merge(blh) with open(binf.replace(".bin", ".hex"), "w") as f: binh.tofile(f, format='hex')
def save(self, path, hex_addr=None): """Save an image from a given file""" ext = os.path.splitext(path)[1][1:].lower() if ext == INTEL_HEX_EXT: # input was in binary format, but HEX needs to know the base addr if self.base_addr is None and hex_addr is None: raise click.UsageError("No address exists in input file " "neither was it provided by user") h = IntelHex() if hex_addr is not None: self.base_addr = hex_addr h.frombytes(bytes=self.payload, offset=self.base_addr) if self.pad: trailer_size = self._trailer_size(self.align, self.max_sectors, self.overwrite_only, self.enckey, self.save_enctlv, self.enctlv_len) trailer_addr = (self.base_addr + self.slot_size) - trailer_size padding = bytes([self.erased_val] * (trailer_size - len(boot_magic))) + boot_magic h.puts(trailer_addr, padding) h.tofile(path, 'hex') else: if self.pad: self.pad_to(self.slot_size) with open(path, 'wb') as f: f.write(self.payload)
def replace_image_body(self, orig, repl, padding): """ Replaces original image with the replacement image :param orig: The image to be replaced :param repl: The image to replace with :param padding: Padding value """ orig_ih = IntelHex() orig_ih.padding = padding orig_ih.loadhex(orig) repl_ih = IntelHex() repl_ih.padding = padding repl_ih.loadhex(repl) minaddr = repl_ih.minaddr() maxaddr = repl_ih.maxaddr() # This adds padding if the image is not aligned to 16 Bytes pad_len = (maxaddr - minaddr + self.header_size) % 16 if pad_len > 0: pad_len = 16 - pad_len for i in range(repl_ih.minaddr(), repl_ih.maxaddr() + pad_len): orig_ih[i] = repl_ih[i] orig_ih.tofile(orig, pathlib.Path(orig).suffix[1:])
def main(args): if len(args) == 1: img = Image.open(sys.stdin) else: img = Image.open(args[1]) if img.mode not in ('1', 'P'): sys.exit("Expected a 1-bit image, got %s" % img.mode) if img.size != (8, 8): sys.exit("Expected an 8x8 pixel image") if 'duration' not in img.info: sys.exit("Expected an animation") out = IntelHex() out.puts(0x00, struct.pack("BBB", 1, img.info['duration'] / 10, 0)) for idx, frame in enumerate(ImageSequence.Iterator(img)): framedata = [0] * 8 for i, bit in enumerate(frame.getdata()): framedata[i % 8] = (framedata[i % 8] << 1) | bit out.puts(data_offset + idx * 8, struct.pack('8B', *framedata)) # Write out the frame count out[0x02] = idx + 1 if len(args) == 2: out.tofile(sys.stdout, format='hex') else: out.tofile(open(args[2], 'w'), format='hex')
def binary_hook(t_self, resources, _, binf): """Hook that merges the soft device with the bin file""" # Scan to find the actual paths of soft device sdf = None for softdevice_and_offset_entry\ in t_self.target.EXPECTED_SOFTDEVICES_WITH_OFFSETS: for hexf in resources.hex_files: if hexf.find(softdevice_and_offset_entry['name']) != -1: t_self.debug("SoftDevice file found %s." % softdevice_and_offset_entry['name']) sdf = hexf if sdf is not None: break if sdf is not None: break if sdf is None: t_self.debug("Hex file not found. Aborting.") return # Look for bootloader file that matches this soft device or bootloader # override image blf = None if t_self.target.MERGE_BOOTLOADER is True: for hexf in resources.hex_files: if hexf.find(t_self.target.OVERRIDE_BOOTLOADER_FILENAME) != -1: t_self.debug("Bootloader file found %s." % t_self.target.OVERRIDE_BOOTLOADER_FILENAME) blf = hexf break elif hexf.find(softdevice_and_offset_entry['boot']) != -1: t_self.debug("Bootloader file found %s." % softdevice_and_offset_entry['boot']) blf = hexf break # Merge user code with softdevice from intelhex import IntelHex binh = IntelHex() _, ext = os.path.splitext(binf) if ext == ".hex": binh.loadhex(binf) elif ext == ".bin": binh.loadbin(binf, softdevice_and_offset_entry['offset']) if t_self.target.MERGE_SOFT_DEVICE is True: t_self.debug("Merge SoftDevice file %s" % softdevice_and_offset_entry['name']) sdh = IntelHex(sdf) binh.merge(sdh) if t_self.target.MERGE_BOOTLOADER is True and blf is not None: t_self.debug("Merge BootLoader file %s" % blf) blh = IntelHex(blf) binh.merge(blh) with open(binf.replace(".bin", ".hex"), "w") as fileout: binh.tofile(fileout, format='hex')
def dumpV2(self, all): start_address = 0x3ff2 if all else 0x37f8 cmd_verif = [0xa6, 0, 0, 0, 0, 0, 0, 0] cmd_verif[1] = 5 + 8 # find block of 8 0xFF at the end of the device memory block = [0xff] * 8 found = False data = [d ^ self.scrambleCodeV2[i % 8] for i, d in enumerate(block)] for address in range(start_address, -1, -1): print('Looking for 0xFF block at address 0x{:04X}'.format( address), end='\n') cmd_verif[3:5] = address & 0xFF, (address >> 8) & 0xFF r, _ = self.cmd_verify_v2(bin_str_of_list(cmd_verif + data)) if r == 0: print('\nFound 0xFF block at address 0x{:04X}'.format(address)) found = True break if not found: print('\nUnable to find 0xFF block') return memdump = IntelHex() memdump.puts(address, bin_str_of_list(block)) print('Starting flash dumping') for i in reversed(block): print('{:02X} '.format(i), end='') sys.stdout.flush() nTry = 0 nBytes = 0 for address in range(address - 1, -1, -1): block[1:] = block[:-1] # shift cmd_verif[3:5] = address & 0xFF, (address >> 8) & 0xFF found = False for i in range(256): val = stats[i] block[0] = val nTry += 1 data = [d ^ self.scrambleCodeV2[i % 8] for i, d in enumerate(block)] r, _ = self.cmd_verify_v2(bin_str_of_list(cmd_verif + data),9) if r == 0: # verification ok, we found the correct byte print('{:02X} '.format(val), end='') sys.stdout.flush() found = True nBytes += 1 memdump[address] = val break if not found: raise ValueError('Unable to find correct ' 'byte for address 0x{:04X}'.format(address)) output_bin = 'out.bin' output_hex = 'out.hex' print('\nDone, writing output files {} and {}'.format(output_bin, output_hex)) print('Ntry = {} {:.2f}try/bytes'.format(nTry, float(nTry) / nBytes)) memdump.tobinfile(output_bin) memdump.tofile(output_hex, format='hex')
def binary_hook(t_self, resources, elf, binf): """Hook that is run after elf is generated""" from intelhex import IntelHex binh = IntelHex() binh.loadbin(binf, offset=0) with open(binf.replace(".bin", ".hex"), "w") as file_desc: binh.tofile(file_desc, format='hex')
def read_hex(comm, filename): print('# Reading chip flash...') data = comm.do_read(AT89C2051_FLASH_SIZE) ih = IntelHex() for i in range(AT89C2051_FLASH_SIZE): ih[i] = data[i] ih.tofile(filename, format='hex') print('# Done!')
class FormatIntelHex(FormatReader, FormatWriter): def __init__(self): self.hexinstance = IntelHex() def load_file(self, filename=None): if filename is None: raise FormatError("Filename not specified.") file_extension = os.path.splitext(filename)[1][1 : ].lower() try: if file_extension == "bin": self.hexinstance.loadbin(filename) else: self.hexinstance.loadhex(filename) except: raise FormatError("Could not open %s file \"%s\"." % (file_extension.upper(), filename)) def save_file(self, filename): if filename is None: raise FormatError("Filename not specified.") file_extension = os.path.splitext(filename)[1][1 : ].lower() try: if file_extension == "bin": self.hexinstance.tofile(filename, format="bin") else: self.hexinstance.tofile(filename, format="hex") except: raise FormatError("Could not save %s file \"%s\"." % (file_extension.upper(), filename)) def add_section(self, start, data): self.hexinstance[start : start + len(data)] = data def get_sections(self): sections = dict() if self.hexinstance.minaddr() is not None: sections[None] = FormatIntelHex_Section(self.hexinstance) return sections @staticmethod def get_name(): return "Intel HEX File Parser" @staticmethod def get_extensions(): return ["hex", "eep"]
def main(): try: os.remove(RESULT) except OSError: pass ihx = IntelHex() ihx.fromfile(TARGET, format='hex') addr_min, addr_max = ihx.minaddr(), ihx.maxaddr() print hex(addr_min), hex(addr_max) ihx.tofile(TEST, format='hex') d = Disassembler() function = ihx.tobinarray()[FUNC_START:] blocks = d.parse(function, 0, FUNC_START) for b in blocks: print '-' * 40 print repr(b) print '-' * 40 blocks = sum(blocks) data = blocks.assemble(FUNC_START, externalize_labels=True) print 'Stream:', ' '.join('%02x' % b for b in bytearray(data)) data_length = len(data) print 'Writing %d bytes.' % data_length ihx.puts(FUNC_START, data) appendix = Block() label_nops = Label('look_mah_no_ops') appendix += Block(label_nops, nop, nop, nop, nop) appendix += Block(Data('\xef\xbe')) appendix += Block(Data(0xbeef)) appendix += Block(Data(label_nops)) end = ihx.maxaddr() + 1 data = appendix.assemble(end, externalize_labels=True) data_length = len(data) print 'Writing %d bytes.' % data_length ihx.puts(end, data) ihx.tofile(RESULT, format='hex') patched = IntelHex() patched.fromfile(RESULT, format='hex') check = ihx.tobinarray()[FUNC_START:FUNC_START + data_length] print 'Stream:', ' '.join('%02x' % b for b in bytearray(data)) print hex(patched.minaddr()), hex(patched.maxaddr())
def ReadConfig(id='', force_backup=False, clear_code_protect=True): print "Read config area" if (force_backup == True): try: conf_hex = IntelHex(SAVE_PATH + '/' + List2Hex(id, '') + '_cfg.hex') if (len(conf_hex.tobinarray()) != 256): raise Exception("ReadConfig: wrong config file size: " + SAVE_PATH + '/' + List2Hex(id, '') + '_cfg.hex') print "\tloaded config from backup:" DecodeConfig(conf_hex, '\t\t') except: raise Exception("ReadConfig: no backup config found") print "\tDone" return conf_hex conf = ReadFlashPage(PAGE_CONF, SIZE_CONF) if (clear_code_protect == True): conf[1] = 0xFF # disable code-protect hex = {} conf_hex = IntelHex(hex) i = 0 empty = True for c in conf: conf_hex[i] = c i += 1 if (c != 0xFF): empty = False if (id != ''): if (empty == True): try: print "\tEmpty config area, read config from backup: " + SAVE_PATH + '/' + List2Hex( id, '') + '_cfg.hex' conf_hex = IntelHex(SAVE_PATH + '/' + List2Hex(id, '') + '_cfg.hex') if (len(conf_hex.tobinarray()) != 256): raise Exception("ReadConfig: wrong config file size: " + SAVE_PATH + '/' + List2Hex(id, '') + '_cfg.hex') print "\tloaded config from backup:" DecodeConfig(conf_hex, '\t\t') except: raise Exception( "ReadConfig: empty chip and no backup config found") else: conf_hex.tofile(SAVE_PATH + '/' + List2Hex(id, '') + '_cfg.hex', format='hex') print "\tloaded config from module:" DecodeConfig(conf_hex, '\t\t') print "\tDone" return conf_hex
def mergehex(fn_1, fn_2): """ merge two hex files write back to file 1. """ ih_1 = IntelHex(fn_1) ih_2 = IntelHex(fn_2) ih_1.merge(ih_2) ih_1.tofile(fn_1, format='hex')
def save(self, path): """Save an image from a given file""" ext = os.path.splitext(path)[1][1:].lower() if ext != INTEL_HEX_EXT: raise Exception("Only hex input file supported") h = IntelHex() h.frombytes(bytes=self.payload, offset=self.load_address) h.tofile(path, 'hex')
def lpc55s69_complete(t_self, non_secure_bin, secure_bin): assert os.path.isfile(secure_bin) assert os.path.isfile(non_secure_bin) ns_hex = IntelHex(non_secure_bin) s_hex = IntelHex() s_hex.loadbin(secure_bin) s_hex.merge(ns_hex, overlap='ignore') s_hex.tofile(non_secure_bin, 'hex')
def create_hex(filename, addr, auto_rst, pad_size): file_format = 'hex' intel_hex = IntelHex() intel_hex.puts(addr, struct.pack(FORMAT, CFG_KEY, FORMAT_LENGTH, auto_rst)) pad_addr = addr + FORMAT_LENGTH pad_byte_count = pad_size - (FORMAT_LENGTH % pad_size) pad_data = '\xFF' * pad_byte_count intel_hex.puts(pad_addr, pad_data) with open(filename, 'wb') as f: intel_hex.tofile(f, file_format)
def binary_hook(t_self, resources, _, binf): """Hook that merges the soft device with the bin file""" # Scan to find the actual paths of soft device sdf = None for softdevice_and_offset_entry\ in t_self.target.EXPECTED_SOFTDEVICES_WITH_OFFSETS: for hexf in resources.hex_files: if hexf.find(softdevice_and_offset_entry['name']) != -1: t_self.debug("SoftDevice file found %s." % softdevice_and_offset_entry['name']) sdf = hexf if sdf is not None: break if sdf is not None: break if sdf is None: t_self.debug("Hex file not found. Aborting.") return # Look for bootloader file that matches this soft device or bootloader # override image blf = None if t_self.target.MERGE_BOOTLOADER is True: for hexf in resources.hex_files: if hexf.find(t_self.target.OVERRIDE_BOOTLOADER_FILENAME) != -1: t_self.debug("Bootloader file found %s." % t_self.target.OVERRIDE_BOOTLOADER_FILENAME) blf = hexf break elif hexf.find(softdevice_and_offset_entry['boot']) != -1: t_self.debug("Bootloader file found %s." % softdevice_and_offset_entry['boot']) blf = hexf break # Merge user code with softdevice from intelhex import IntelHex binh = IntelHex() binh.loadbin(binf, offset=softdevice_and_offset_entry['offset']) if t_self.target.MERGE_SOFT_DEVICE is True: t_self.debug("Merge SoftDevice file %s" % softdevice_and_offset_entry['name']) sdh = IntelHex(sdf) binh.merge(sdh) if t_self.target.MERGE_BOOTLOADER is True and blf is not None: t_self.debug("Merge BootLoader file %s" % blf) blh = IntelHex(blf) binh.merge(blh) with open(binf.replace(".bin", ".hex"), "w") as fileout: binh.tofile(fileout, format='hex')
def create_hex(filename, addr, auto_rst, automation_allowed, pad_size): file_format = 'hex' intel_hex = IntelHex() intel_hex.puts(addr, struct.pack(FORMAT, CFG_KEY, FORMAT_LENGTH, auto_rst, automation_allowed)) pad_addr = addr + FORMAT_LENGTH pad_byte_count = pad_size - (FORMAT_LENGTH % pad_size) pad_data = '\xFF' * pad_byte_count intel_hex.puts(pad_addr, pad_data) with open(filename, 'wb') as f: intel_hex.tofile(f, file_format)
def _main(): """Append credentials to a prebuilt hex file, download it via a J-Link debug probe, allow the hex file to run, verify the result code, and then erase the hex file. """ args = _add_and_parse_args() nrfjprog_api = None nrfjprog_probe = None try: hex_path = HEX_PATH if args.in_file: hex_path = args.in_file intel_hex = IntelHex(hex_path) if intel_hex.maxaddr() >= CRED_PAGE_ADDR: if hex_path == HEX_PATH: print("error: Prebuilt hex file is too large.") _close_and_exit(nrfjprog_api, -3) elif (intel_hex.maxaddr() < FW_RESULT_CODE_ADDR or intel_hex.gets(CRED_PAGE_ADDR, 4) != MAGIC_NUMBER_BYTES): print("error: Magic number not found in hex file.") _close_and_exit(nrfjprog_api, -2) else: intel_hex.puts(CRED_PAGE_ADDR, MAGIC_NUMBER_BYTES) intel_hex.puts(CRED_COUNT_ADDR, struct.pack('B', 0x00)) if not args.out_file or args.program_app: nrfjprog_api, nrfjprog_probe = _connect_to_jlink(args) _append_creds(intel_hex, args) if args.out_file: intel_hex.tofile(args.out_file, "hex") else: # Create a temporary file to pass to pynrfjprog and then delete it when finished. tmp_file = os.path.sep.join((tempfile.mkdtemp(), TMP_FILE_NAME)) intel_hex.tofile(tmp_file, "hex") _write_firmware(nrfjprog_probe, tmp_file) time.sleep(args.fw_delay) result_code = nrfjprog_probe.read(FW_RESULT_CODE_ADDR) if result_code: print("error: Firmware result is 0x{:X}".format(result_code)) _close_and_exit(nrfjprog_api, -4) imei_bytes = nrfjprog_probe.read(IMEI_ADDR, IMEI_LEN + 1) if (IMEI_LEN != imei_bytes.find(BLANK_FLASH_VALUE) or not imei_bytes[:IMEI_LEN].isdigit()): print("error: IMEI does not look valid.") _close_and_exit(nrfjprog_api, -5) print(imei_bytes[:-1].decode()) nrfjprog_probe.erase(HighLevel.EraseAction.ERASE_ALL) os.remove(tmp_file) os.removedirs(os.path.dirname(tmp_file)) if args.program_app: _write_firmware(nrfjprog_probe, args.program_app) _close_and_exit(nrfjprog_api, 0) except Exception as ex: print("error: " + str(ex)) _close_and_exit(nrfjprog_api, -2)
def tofile(self, outfile: Union[str, BinaryIO], fmt: Optional[str] = None) -> None: if fmt is None and isinstance( outfile, str) and outfile.lower().endswith('.hex'): fmt = 'hex' else: fmt = 'bin' ih = IntelHex() ih.puts(self.base or 0, bytes(self.fw)) ih.tofile(outfile, fmt)
def dump(self): end_address = 0x3ff0 # send the key b = '\xa6\x04' + struct.pack('BBBB', *scrambleCode) self.xcmd(b, 0) # find block of 16 0xFF at the end of the device memory block = [0xff] * 16 found = False for address in range(end_address, -1, -1): print('\rLooking for address 0x{:04X}'.format(address), end='') r = self.cmd('\xa7\16' + struct.pack('<H', address) + bin_str_of_list(scramble(block))) if r == 0: print('\nFound 0xFF block at address 0x{:04X}'.format(address)) found = True break if not found: print('\nUnable to find 0xFF block') return memdump = IntelHex() memdump.puts(address, bin_str_of_list(block)) print('Starting flash dumping') base = [0xa7, 16, 0, 0] nTry = 0 nBytes = 0 for address in range(address - 1, - 1, -1): block[1:] = block[:-1] # shift base[2:4] = address & 0xFF, address >> 8 found = False for i in range(256): i = stats[i] block[0] = i nTry += 1 r = self.cmd(bin_str_of_list(base + scramble(block)), 4) if r == 0: # verification ok, we found the correct byte print('{:02X} '.format(i), end='') sys.stdout.flush() found = True nBytes += 1 memdump[address] = i break if not found: raise ValueError('Unable to find correct ' 'byte for address 0x{:04X}'.format(address)) output_bin = 'out.bin' output_hex = 'out.hex' print('\nDone, writing output files {} and {}'.format(output_bin, output_hex)) print('Ntry = {} {:.2f}try/bytes'.format(nTry, float(nTry) / nBytes)) memdump.tobinfile(output_bin) memdump.tofile(output_hex, format='hex')
def main(): (opts, args) = init_parser() fsource = open(opts.file, 'r') reader = csv.reader(fsource, delimiter=opts.delim) data = [] for l in reader: data.append(l[opts.col]) fsource.close() ih = IntelHex() for n in range(opts.row, len(data)): ih[n-opts.row] = int(data[n]) ih.tofile(opts.out, format='hex')
def build_target_firmware(self, parent_test): """ Build test firmware for the board Login credentials must have been set with set_build_login. """ prebuilt = self._target_dir is not None build_login = (self._username is not None and self._password is not None) assert prebuilt or build_login if prebuilt: destdir = self._target_dir else: destdir = 'tmp' build_name = board_id_to_build_target[self.get_board_id()] name_base = os.path.normpath(destdir + os.sep + build_name) self._target_hex_path = name_base + '.hex' self._target_bin_path = name_base + '.bin' # Build target test image if a prebuild location is not specified if not prebuilt: test_info = parent_test.create_subtest('build_target_test_firmware') if not os.path.isdir(destdir): os.mkdir(destdir) # Remove previous build files if os.path.isfile(self._target_hex_path): os.remove(self._target_hex_path) if os.path.isfile(self._target_bin_path): os.remove(self._target_bin_path) test_info.info('Starting remote build') start = time.time() built_file = mbedapi.build_repo(self._username, self._password, TEST_REPO, build_name, destdir) stop = time.time() test_info.info("Build took %s seconds" % (stop - start)) extension = os.path.splitext(built_file)[1].lower() assert extension == '.hex' or extension == '.bin' if extension == '.hex': intel_hex = IntelHex(built_file) # Only supporting devices with the starting # address at 0 currently assert intel_hex.minaddr() == 0 intel_hex.tobinfile(self._target_bin_path) os.rename(built_file, self._target_hex_path) if extension == '.bin': intel_hex = IntelHex() intel_hex.loadbin(built_file, offset=0) intel_hex.tofile(self._target_hex_path, 'hex') os.rename(built_file, self._target_bin_path) # Assert that required files are present assert os.path.isfile(self._target_hex_path) assert os.path.isfile(self._target_bin_path) self._target_firmware_present = True
def mergehex(input_hex_files, output_hex_file, attestation_key=None): """Merges hex files, and patches in the attestation key. If no attestation key is passed, uses default Solo Hacker one. Note that later hex files replace data of earlier ones, if they overlap. """ if attestation_key is None: # generic / hacker attestation key attestation_key = ( "1b2626ecc8f69b0f69e34fb236d76466ba12ac16c3ab5750ba064e8b90e02448") # TODO put definitions somewhere else def flash_addr(num): return 0x08000000 + num * 2048 PAGES = 128 APPLICATION_END_PAGE = PAGES - 19 AUTH_WORD_ADDR = flash_addr(APPLICATION_END_PAGE) - 8 ATTEST_ADDR = flash_addr(PAGES - 15) first = IntelHex(input_hex_files[0]) for input_hex_file in input_hex_files[1:]: print(f"merging {first} with {input_hex_file}") first.merge(IntelHex(input_hex_file), overlap="replace") first[flash_addr(APPLICATION_END_PAGE - 1)] = 0x41 first[flash_addr(APPLICATION_END_PAGE - 1) + 1] = 0x41 first[AUTH_WORD_ADDR - 4] = 0 first[AUTH_WORD_ADDR - 1] = 0 first[AUTH_WORD_ADDR - 2] = 0 first[AUTH_WORD_ADDR - 3] = 0 first[AUTH_WORD_ADDR] = 0 first[AUTH_WORD_ADDR + 1] = 0 first[AUTH_WORD_ADDR + 2] = 0 first[AUTH_WORD_ADDR + 3] = 0 first[AUTH_WORD_ADDR + 4] = 0xFF first[AUTH_WORD_ADDR + 5] = 0xFF first[AUTH_WORD_ADDR + 6] = 0xFF first[AUTH_WORD_ADDR + 7] = 0xFF # patch in the attestation key key = binascii.unhexlify(attestation_key) for i, x in enumerate(key): first[ATTEST_ADDR + i] = x first.tofile(output_hex_file, format="hex")
def save(self, path): """Save an image from a given file""" ext = os.path.splitext(path)[1][1:].lower() if ext == INTEL_HEX_EXT: # input was in binary format, but HEX needs to know the base addr if self.slot_address is None: raise Exception("Input file does not provide a slot address") h = IntelHex() h.frombytes(bytes=self.payload, offset=self.slot_address) h.tofile(path, 'hex') else: with open(path, 'wb') as f: f.write(self.payload)
def getBinaryFromIHex(self, filepath, generateBin): # Fetching Hex File and Storing hexFile = IntelHex(filepath) if generateBin == "y": # Create a Binary File of this Hex File binFilePath = string.replace(filepath, ".hex", ".bin") logging.debug("Binary File Path : %s", binFilePath) hexFile.tofile(binFilePath, format='bin') # Obtain the actual Binary content from the Hex File binary = hexFile.tobinarray() return binary
def generate(self, workspace, outBin=None, outHex=None, skip=False): self.generated = False self.generatedBinary = None if self.valid: try: p = workspace.getParameters(self.parameters) if p is not None: if p.generateBinary(workspace, self): if outBin is not None: path = os.path.join(outBin, self.parameters) if not os.path.isdir(path): os.makedirs(path) self.destinationBin = os.path.join( path, self.name + ".bin") sink = open(self.destinationBin, 'wb') sink.write(p.generatedBinary) else: self.destinationBin = None if outHex is not None: path = os.path.join(outHex, self.parameters) if not os.path.isdir(path): os.makedirs(path) self.destinationHex = os.path.join( path, self.name + ".hex") ih = IntelHex() ih.frombytes(p.generatedBinary) ih.tofile(self.destinationHex, "hex") else: self.destinationHex = None self.generated = True else: self.reason = p.reason else: self.reason = "Cannot find a valid parameters file for '" + self.parameters + "'" return self.generated except IOError as e: self.reason = CoreConsole.error( str(e.strerror) + " [" + CoreConsole.highlightFilename(e.filename) + "]") CoreConsole.fail("ParametersTarget::generate: " + self.reason) return False
def mergeSAMD() : bootHex = IntelHex(sys.argv[2]) appHex = IntelHex(sys.argv[3]) combinedHex = IntelHex() # Insert the bootloader in the first 8kB for i in bootHex.addresses() : combinedHex[i] = bootHex[i] # Insert the application in the remaining 120kB for i in appHex.addresses() : combinedHex[i] = appHex[i] # Write to the combined hex file combinedHex.tofile(sys.argv[4], 'hex')
def ReadConfig( id = '', force_backup = False, clear_code_protect = True): print( "Read config area") if( force_backup == True): try: conf_hex = IntelHex( SAVE_PATH + '/' + List2Hex( id, '') + '_cfg.hex') if( len( conf_hex.tobinarray()) != 256): raise Exception( "ReadConfig: wrong config file size: " + SAVE_PATH + '/' + List2Hex( id, '') + '_cfg.hex') print( "\tloaded config from backup:") DecodeConfig( conf_hex, '\t\t') except: raise Exception( "ReadConfig: no backup config found") print( "\tDone") return conf_hex conf = ReadFlashPage( PAGE_CONF, SIZE_CONF) if( clear_code_protect == True): conf[1] = 0xFF; # disable code-protect hex = {} conf_hex = IntelHex( hex) i = 0 empty = True for c in conf: conf_hex[i] = c i+=1 if( c != 0xFF): empty = False if( id != ''): if( empty == True): try: print( "\tEmpty config area, read config from backup: " + SAVE_PATH + '/' + List2Hex( id, '') + '_cfg.hex') conf_hex = IntelHex( SAVE_PATH + '/' + List2Hex( id, '') + '_cfg.hex') if( len( conf_hex.tobinarray()) != 256): raise Exception( "ReadConfig: wrong config file size: " + SAVE_PATH + '/' + List2Hex( id, '') + '_cfg.hex') print( "\tloaded config from backup:") DecodeConfig( conf_hex, '\t\t') except: raise Exception( "ReadConfig: empty chip and no backup config found") else: conf_hex.tofile( SAVE_PATH + '/' + List2Hex( id, '') + '_cfg.hex', format='hex') print( "\tloaded config from module:") DecodeConfig( conf_hex, '\t\t') print( "\t\tdumped config to: " + SAVE_PATH + '/' + List2Hex( id, '') + '_cfg.hex') print( "\tDone") return conf_hex
def generate(self, workspace, outBin=None, outHex=None,skip=False): self.generated = False self.generatedBinary = None if self.valid: try: p = workspace.getParameters(self.parameters) if p is not None: if p.generateBinary(workspace, self): if outBin is not None: path = os.path.join(outBin, self.parameters) if not os.path.isdir(path): os.makedirs(path) self.destinationBin = os.path.join(path, self.name + ".bin") sink = open(self.destinationBin, 'wb') sink.write(p.generatedBinary) else: self.destinationBin = None if outHex is not None: path = os.path.join(outHex, self.parameters) if not os.path.isdir(path): os.makedirs(path) self.destinationHex = os.path.join(path, self.name + ".hex") ih = IntelHex() ih.frombytes(p.generatedBinary) ih.tofile(self.destinationHex, "hex") else: self.destinationHex = None self.generated = True else: self.reason = p.reason else: self.reason = "Cannot find a valid parameters file for '" + self.parameters + "'" return self.generated except IOError as e: self.reason = CoreConsole.error(str(e.strerror) + " [" + CoreConsole.highlightFilename(e.filename) + "]") CoreConsole.fail("ParametersTarget::generate: " + self.reason) return False
def build_target_bundle(directory, username, password, parent_test=None): """Build target firmware package""" if parent_test is None: parent_test = TestInfoStub() target_names = info.TARGET_NAME_TO_BOARD_ID.keys() for build_name in target_names: name_base = os.path.normpath(directory + os.sep + build_name) target_hex_path = name_base + '.hex' target_bin_path = name_base + '.bin' # Build target test image test_info = parent_test.create_subtest('Building target %s' % build_name) if not os.path.isdir(directory): os.mkdir(directory) # Remove previous build files if os.path.isfile(target_hex_path): os.remove(target_hex_path) if os.path.isfile(target_bin_path): os.remove(target_bin_path) test_info.info('Starting remote build') start = time.time() built_file = mbedapi.build_repo(username, password, TEST_REPO, build_name, directory) stop = time.time() test_info.info("Build took %s seconds" % (stop - start)) extension = os.path.splitext(built_file)[1].lower() assert extension == '.hex' or extension == '.bin' if extension == '.hex': intel_hex = IntelHex(built_file) # Only supporting devices with the starting # address at 0 currently assert intel_hex.minaddr() == 0 intel_hex.tobinfile(target_bin_path) os.rename(built_file, target_hex_path) if extension == '.bin': intel_hex = IntelHex() intel_hex.loadbin(built_file, offset=0) intel_hex.tofile(target_hex_path, 'hex') os.rename(built_file, target_bin_path) # Assert that required files are present assert os.path.isfile(target_hex_path) assert os.path.isfile(target_bin_path)
def binary_hook(t_self, resources, elf, binf): for hexf in resources.hex_files: if hexf.find(NRF51822.EXPECTED_SOFTDEVICE) != -1: break else: t_self.debug("Hex file not found. Aborting.") return # Merge user code with softdevice from intelhex import IntelHex binh = IntelHex() binh.loadbin(binf, offset = NRF51822.APPCODE_OFFSET) sdh = IntelHex(hexf) sdh.merge(binh) with open(binf.replace(".bin", ".hex"), "w") as f: sdh.tofile(f, format = 'hex')
def mergeAVR() : bootHex = IntelHex(sys.argv[2]) appHex = IntelHex(sys.argv[3]) combinedHex = IntelHex() # Insert the application in the first 6kB for i in range(1024*6) : combinedHex[i] = appHex[i] # Insert the bootloader in the last 2kB for i in range(1024*6,1024*8) : combinedHex[i] = bootHex[i] # The first two bytes are the reset vector. They come from the bootloader. combinedHex[0] = bootHex[0] combinedHex[1] = bootHex[1] # When the bootloader exits, it will execute the instruction at byte address # 0x17FE (the byte immediately before the bootloader). We need to arrange # for that instruction to be an rjmp to the application. Normally the # firt instruction (at address 0) is an rjmp to the application, so we can # determine the app start address from that. # Word address of the app start vector appStartAddress = 0xFFF & ( appHex[0] + (appHex[1] << 8)) # Word address of the trampoline instruction trampolineAddress = (6*1024)/2 - 1 # Determine the offset between the trampoline and app start addresses. # Mask it to 12 bits. trampoline = 0xFFF & (appStartAddress-trampolineAddress) # The rjmp opcode is 0xC000. The lower twelve bits are the address offset. trampolineInstruction = 0xC000 | trampoline # Insert the instruction at the trampoline address combinedHex[trampolineAddress*2] = (trampolineInstruction & 0xFF) combinedHex[trampolineAddress*2+1] = (trampolineInstruction >> 8) # Write to the combined hex file combinedHex.tofile(sys.argv[4], 'hex')
def main(): args = parser.parse_args() base_hex = IntelHex() # Merge in hex files for file_name in args.hex: new_hex_data = IntelHex() print "opening file %s" % file_name new_hex_data.fromfile(file_name, format='hex') print_hex_info(file_name, new_hex_data) base_hex = merge_hex(base_hex, new_hex_data) # Merge in binary files for file_name, addr_str in args.bin: offset = int(addr_str, 0) new_hex_data = IntelHex() new_hex_data.loadbin(file_name, offset=offset) print_hex_info(file_name, new_hex_data) base_hex = merge_hex(base_hex, new_hex_data) # Write out data print_hex_info(args.output_file, base_hex) with open(args.output_file, 'wb') as output_file: base_hex.tofile(output_file, 'hex')
def binary_hook(t_self, resources, elf, binf): for hexf in resources.hex_files: if hexf.find(NRF51822.EXPECTED_SOFTDEVICE) != -1: break else: t_self.debug("Hex file not found. Aborting.") return # Merge user code with softdevice from intelhex import IntelHex binh = IntelHex() binh.loadbin(binf, offset = NRF51822.APPCODE_OFFSET) sdh = IntelHex(hexf) sdh.merge(binh) # Remove UICR section del sdh[NRF51822.UICR_START:NRF51822.UICR_END+1] with open(binf, "wb") as f: sdh.tofile(f, format = 'bin')
def read(addr, length, compress, file): click.echo("\n Reading from MCU memory, please wait !\n") # Call KBoot flash erase all function data = KBOOT.read_memory(addr, length) # Disconnect KBoot Device KBOOT.disconnect() if file is None: click.echo(hexdump(data, addr, compress)) else: if file.lower().endswith('.bin'): with open(file, "wb") as f: f.write(data) f.close() elif file.lower().endswith('.hex'): ihex = IntelHex() ihex.frombytes(data, 0) ihex.start_addr = addr try: ihex.tofile(file, format='hex') except Exception as e: raise Exception('Could not write to file: %s \n [%s]' % (file, str(e))) else: srec = kboot.SRecFile() srec.header = "pyKBoot" srec.start_addr = addr srec.data = data try: srec.save(file) except Exception as e: raise Exception('Could not write to file: %s \n [%s]' % (file, str(e))) click.secho(" Successfully saved into: %s. \n" % file)
filename = device + ".hex" # Add default extension to filename name, ext = splitext(filename) if ext == "": filename = name + ".hex" # Set up the device interface mb = Microboot() info = mb.getDeviceInfo(device) if info is None: print "Unsupported device type '%s'." % device # Show what we are doing size = info[4] - info[3] + 1 print "Reading %d bytes (0x%04X:0x%04X) from '%s' on '%s'." % (size, info[3], info[4], device, port) # Set up logging if requested if g_logFile is not None: mb.logger = logFunction # Connect to the device mb.connect(device, port) # Read everything data = mb.read(info[3], size) mb.disconnect() # Create the HEX file hexfile = IntelHex() address = info[3] for val in data: hexfile[address] = val address = address + 1 hexfile.tofile(filename, "hex") print "Output written to '%s'." % filename
#!/usr/bin/python import sys from intelhex import IntelHex hexFile = IntelHex(sys.argv[1]) trimHex = IntelHex() #for i in hexFile.addresses() : # if hexFile[i] != 0xFF : # trimHex[i] = hexFile[i] for i in range(0, 128*1024, 16) : writeRow = False for j in range(i, i+16) : if hexFile[j] != 0xFF : writeRow = True break if writeRow : for j in range(i, i+16) : trimHex[j] = hexFile[j] # Write to the combined hex file trimHex.tofile(sys.argv[2], 'hex')
def write_to_file(self, filen, output_format, bias=0): """ Write to a file the Sound Lib using a output format function """ try: # Opening file if filen is None: # Try to open the file fich = sys.stdout else: print(self.__info) if output_format == 'lib' or output_format == 'raw': fich = open(filen, 'wb') else: fich = open(filen, "w") # Writting if output_format == 'lib_ihex' or output_format == 'lib': ptr_addr = 0 # Were write Ptr to sound data end addr = 1024 # Were write sound data ih = IntelHex() for name in self.__snames: if not fich is sys.stdout: print(self.sounds[name]['info']) data = ssc.pack(self.sounds[name]['bitstream']) while len(data) % 32 != 0: #Padding to fill 32 byte blocks data += PAD_FILL btl_output(data, ih, addr, ptr_addr, bias) ptr_addr += 4 addr += len(data) # Fills the header with 0s for n in range(ptr_addr, 1024): ih[n] = 0 # Binary o IntelHEX output if output_format == 'lib': ih.tofile(fich, 'bin') else: ih.tofile(fich, 'hex') elif output_format == 'raw_ihex' or output_format == 'raw': addr = 0 # Were write sound data ih = IntelHex() for name in self.__snames: if not fich is sys.stdout: print(self.sounds[name]['info']) data = ssc.pack(self.sounds[name]['bitstream']) while len(data) % 32 != 0: # Padding to fill 32 byte blocks data += PAD_FILL btc_output(data, ih, addr, bias) addr += len(data) # Binary or IntelHEX output if output_format == 'raw': ih.tofile(fich, 'bin') else: ih.tofile(fich, 'hex') elif output_format == 'c': fich.write('#include <stdlib.h>\n\n') fich.write('/*\n' + self.__info + '/*\n\n') for name in self.__snames: if not fich is sys.stdout: print(self.sounds[name]['info']) data = ssc.pack(self.sounds[name]['bitstream']) c_array_print(data, fich, self.sounds[name]['info'], name) finally: if fich != sys.stdout: fich.close()
ram_regions = [region for region in memory_map if region.type == 'ram'] ram_region = ram_regions[0] rom_region = memory_map.getBootMemory() target_type = board.getTargetType() print "[3/6] Board recognized as %s. Downloading ROM..." % target_type addr = rom_region.start size = rom_region.length data = board.target.readBlockMemoryUnaligned8(addr, size) data = bytearray(data) with open("crashdump/rom.bin", 'wb') as f: f.write(data) ih = IntelHex() ih.puts(addr, data) ih.tofile("crashdump/rom.hex", format='hex') print "[4/6] Dumped ROM. Downloading RAM..." addr = ram_region.start size = ram_region.length data = board.target.readBlockMemoryUnaligned8(addr, size) data = bytearray(data) with open("crashdump/ram.bin", 'wb') as f: f.write(data) ih = IntelHex() ih.puts(addr, data) ih.tofile("crashdump/ram.hex", format='hex') print "[5/6] Dumped RAM. Creating uVision project..."
sys.exit() printIntroMessage() print str('-' * (len(sHexFilePath) + 20)) print "Hex File Path = \"" + sHexFilePath + "\"" print str('-' * (len(sHexFilePath) + 20)) # Fetching Hex File and Storing hexFile = IntelHex(sHexFilePath) if sGenerateBinary == "y": # Create a Binary File of this Hex File sBinFilePath = string.replace(sHexFilePath, ".hex", ".bin") logging.debug("Binary File Path : %s", sBinFilePath) hexFile.tofile(sBinFilePath, format='bin') # Obtain the actual Binary content from the Hex File binArray = hexFile.tobinarray() sPort = serial.Serial( port=sDeviceFile, baudrate=sInitialDeviceBaud, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS) # sPort.rts = True # sPort.dtr = True # time.sleep(2)
# print(icsp_cmd(ser, b'%', 5)) # reset stats print(icsp_cmd(ser, b'^')) # enter LVP print("dumping program memory ...") data = icsp_read_data(ser, 0x4000) for a in range(0x0000, 0x4000): val = data[a] ih.puts(a*2, struct.pack("<h", val)) icsp_cmd(ser, b'[X0=]', 0) # switch to config mem print("dumping config memory ...") data = icsp_read_data(ser, 0x11) for a in range(0x8000, 0x8011): val = data[a - 0x8000] ih.puts(a*2, struct.pack("<h", val)) print(icsp_cmd(ser, b'#', 9)) # retrieve checksum print(icsp_cmd(ser, b'Z')) # tristate MCLK (icsp) if sel == "A": # bring A_!RST high again i2c0.write_byte_data(0x23, 0x14, ioa|0x10) elif sel == "B": # bring B_!RST high again i2c0.write_byte_data(0x22, 0x14, iob|0x10) if sel != "P": i2c2.write_byte(0x70, 0x0) # disable mux ih.tofile(sys.argv[2], "hex")
def main(argv): # Interpret parameters sensorConfig = "" hexFile = "../../build/artifacts/smartsensor_fw/opt/smartsensor_fw.hex" helpText = (argv[0] if len(argv)>0 else "generate.py") + \ " [-d] [-i <hex-file>] <sensor-type>" helpMore = "Supported sensor types:\n\t" + ", ".join(ss_type.allTypes()) try: opts, args = getopt.getopt(argv[1:],"hdi:") except getopt.GetoptError: print helpText sys.exit(2) for opt, arg in opts: if opt == '-h': print helpText print helpMore sys.exit() elif opt == "-i": hexFile = arg elif opt == "-d": if len(args)>0: try: ss_type.descriptor(args[0]) sys.exit(0) except KeyError: sys.exit(args[0]+" is not a valid sensor type.\n"+helpMore) else: sys.exit("Enter a sensor type\n"+helpMore) if len(args)==0: print helpText print helpMore sys.exit(2) else: sensorConfig = args[0] try: descriptor = ss_type.descriptor(sensorConfig) except KeyError: sys.exit(args[0]+" is not a valid sensor type.\n"+helpMore) # Decide the new sensor's ID try: firstType = descriptor["channels"][0]["type"] except IndexError: firstType = 0xFF # TODO(nikita): Proper ID generation idNew = array('B', [0, 0, 0, 0, 0, firstType, random.randint(0,255), random.randint(0,255), firstType]) # Create the new sensor's descriptor channelsStr = b"" for channel in descriptor["channels"]: # Pack each channel packer = struct.Struct( "<B%upB%us"%(len(channel["description"])+1,len(channel["additional"]))) channelsStr += packer.pack( packer.size, channel["description"], channel["type"], channel["additional"].tostring()) packer = struct.Struct( "<H%upBBB%usB"%(len(descriptor["description"])+1,len(channelsStr))) descriptorStr = packer.pack( packer.size, descriptor["description"], descriptor["chunksNumer"], descriptor["chunksDenom"], len(descriptor["channels"]), channelsStr, 0xC8) crc = crc8(0, array('B', descriptorStr)) descriptorStr = packer.pack( packer.size, descriptor["description"], descriptor["chunksNumer"], descriptor["chunksDenom"], len(descriptor["channels"]), channelsStr, crc) descriptorNew = array('B', descriptorStr) # Write the ID and descriptor to the hex file descriptorPlaceholder = \ b"Do not change this string. It is a placeholder that is replaced in the " + \ b"compiled hex file when the deploy script is run." idPlaceholder = "SENSORID" ih = IntelHex(hexFile) ihDict = ih.todict() ihArr = array('B', [ihDict[key] for key in sorted(ihDict)]) ihString = ihArr.tostring() try: descriptorIndex = ihArr.tostring().index(descriptorPlaceholder) except ValueError: sys.exit('Error: Descriptor placeholder not found in hex file.') try: idIndex = ihArr.tostring().index(idPlaceholder) except ValueError: sys.exit('Error: ID placeholder not found in hex file.') descriptorDict = {descriptorIndex+i: descriptorNew[i] for i in range(len(descriptorNew))} idDict = {idIndex+i: idNew[i] for i in range(len(idNew))} ihDict = dict(ihDict.items()+descriptorDict.items()+idDict.items()) newIh = IntelHex() newIh.fromdict(ihDict) newIh.tofile(sys.stdout, format='hex') # Print new hex file to stdout