def main(options, args): # If using ANSI coloring is available, initialize colorama if fail_color: init() # Import intelhex if avaialable, otherwise fail try: from intelhex import IntelHex except: return fail( 'error: You do not have \'intelhex\' installed. Please run \'pip install intelhex\' then retry.' ) if len(options.output) is 0: print "No output file specified" exit(1) if len(args) < 2: return fail('Only one file was provided to merge.') exit(0) # Get the first hex file, merge the remainder and save the result orig = IntelHex(args[0]) convert_start_addr(orig) args = args[1:] for arg in args: other = IntelHex(arg) convert_start_addr(other) orig.merge(other, overlap='replace') orig.write_hex_file(options.output)
def build_image(stack, app, passkey, out): passkey_index = 0 signature = 0xdeadbeef ih = IntelHex(app) for i in range(0, len(ih)): if ih[i] == (signature & 0xff) and ih[i + 1] == ( (signature >> 8) & 0xff) and ih[i + 2] == ( (signature >> 16) & 0xff) and ih[i + 3] == ((signature >> 24) & 0xff): if passkey_index == 0: passkey_index = i else: raise RuntimeError('Found passkey signature twice?!') if passkey_index == 0: raise RuntimeError('Passkey signature was not found!') print('Setting new passkey %06d' % passkey) ih[passkey_index] = passkey & 0xff ih[passkey_index + 1] = (passkey >> 8) & 0xff ih[passkey_index + 2] = (passkey >> 16) & 0xff ih[passkey_index + 3] = (passkey >> 24) & 0xff stack = IntelHex(stack) ih.merge(stack) ih.write_hex_file(out, byte_count=32)
def generate_provision_hex_file(s0_address, s1_address, hashes, provision_address, output, max_size, num_counter_slots_version): # Add addresses provision_data = struct.pack('III', s0_address, s1_address, len(hashes)) for mhash in hashes: provision_data += struct.pack('I', 0xFFFFFFFF) # Invalidation token provision_data += mhash num_counters = 1 if num_counter_slots_version > 0 else 0 provision_data += struct.pack('H', 1) # Type "counter collection" provision_data += struct.pack('H', num_counters) if num_counters == 1: if num_counter_slots_version % 2 == 1: num_counter_slots_version += 1 print(f'Monotonic counter slots rounded up to {num_counter_slots_version}') provision_data += struct.pack('H', 1) # counter description provision_data += struct.pack('H', num_counter_slots_version) assert (len(provision_data) + (2 * num_counter_slots_version)) <= max_size, """Provisioning data doesn't fit. Reduce the number of public keys or counter slots and try again.""" ih = IntelHex() ih.frombytes(provision_data, offset=provision_address) ih.write_hex_file(output)
def __init__(self, fw, channel=16, serial_port=None, snr=None): ''' Ininitialises the OTA Flasher class which handles flashing the devboard with the needed OTA Server firmware and the update file for the OTA Client. The said devboard shall become the OTA Server which shall propagate the image on the Zigbee network. Keyword arguments: fw -- path to the update file for the OTA Client channel -- a 802.15.4 channel number, on which the OTA Server shall operate (default 16) serial_port -- a serial port of the connected devboard which shall be flashed with OTA Server snr -- a JLink serial number of the connected devboard which shall be flashed with OTA Server Note: only one parameter out of (serial_port, snr) must be provided, since the superclass constructor shall handle resolving the rest. ''' # Call the superclass constructor super().__init__(serial_port, snr) # Create a Intel Hex out of the Zigbee Update file ih = IntelHex() update = open(fw, 'rb').read() ih.puts(OTAFlasher.OTA_UPDATE_OFFSET, update) self.update_firmware_hex = fw + '.hex' ih.write_hex_file(self.update_firmware_hex) # Open the serial channel to the devboard and save the 802.15.4 channel self.ser = Serial(self.serial_port, 115200) self.channel = channel
def sign_and_append_validation_data(pem_file, input_file, offset, output_file, magic_value, pk_hash_len): 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("Incorrect offset, must be bigger than %x" % minimum_offset) # Parse comma-separated string of uint32s into hex string. Each in 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(pem_file=pem_file, input_hex=ih, magic_value=parsed_magic_value, pk_hash_len=pk_hash_len) 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_file)
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 read(start, lenght, fname): stop=start+lenght f=fname print "Dumping from %04x to %04x as %s." % (start,stop,f) #h = IntelHex16bit(None) # FIXME: get mcu state and return it to that state try: h = IntelHex(None) i=start while i<=stop: #data=client.ARMreadMem(i, 48) data=client.ARMreadChunk(i, 48, verbose=0) print "Dumped %06x."%i for dword in data: if i<=stop and dword != 0xdeadbeef: h.puts( i, struct.pack("<I", dword) ) i+=4 # FIXME: get mcu state and return it to that state except: print "Unknown error during read. Writing results to output file." print "Rename file with last address dumped %06x."%i pass h.write_hex_file(f)
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.notify.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.notify.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.notify.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.notify.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.notify.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.notify.debug("Merge BootLoader file %s" % blf) blh = IntelHex(blf) binh.merge(blh) with open(binf.replace(".bin", ".hex"), "w") as fileout: binh.write_hex_file(fileout, write_start_addr=False)
def main(arguments): # If using ANSI coloring is available, initialize colorama if fail_color: init() # Import intelhex if avaialable, otherwise fail try: from intelhex import IntelHex except: return fail( 'error: You do not have \'intelhex\' installed. Please run \'pip install intelhex\' then retry.' ) # Ensure the right number of arguments are supplied if not len(arguments) == 3: return fail( 'error: Improper use of merge_hex.py.\nUSAGE: merge_hex.py input_file1 input_file2 output_file.' ) # Get the two hex files, merge them, and save the result orig = IntelHex(arguments[0]) convert_start_addr(orig) new = IntelHex(arguments[1]) convert_start_addr(new) orig.merge(new, overlap='replace') orig.write_hex_file(arguments[2])
def main(id, src_path): eeprom_path = "eeprom_temp.hex" eeprom_contents = IntelHex("eedump_0.hex") eeprom_contents[6] = id eeprom_contents[10] = 0 # Seen all badges & uber badges """ for i in range(100): eeprom_contents[10+i] = 1 """ # Seen some badges & uber badges """ for i in range(0,100,2): eeprom_contents[10+i] = 1 """ # Seen all uber badges """ for i in range(10): eeprom_contents[10+i] = 1 """ # Seen all badges, not all uber """ for i in range(95): eeprom_contents[15+i] = 1 """ # with open(eeprom_path, 'w') as eeprom_file: eeprom_contents.write_hex_file(eeprom_file) # External 16 MHz: cmd_string = "avrdude -p m328p -c usbtiny -u -U hfuse:w:0xDE:m -U lfuse:w:0xBF:m -U efuse:w:0x05:m -U flash:w:%s -U eeprom:w:%s" % ( src_path, eeprom_path) # internal 8 MHz: #cmd_string = "avrdude -p m328p -c usbtiny -u -U hfuse:w:0xDE:m -U lfuse:w:0xA2:m -U efuse:w:0x05:m -U flash:w:%s -U eeprom:w:%s" % (src_path, eeprom_path) os.system(cmd_string)
def flashEeprom(self): do_flash = False if "custom" in self.firmware.lower( ) or "extended" in self.firmware.lower(): from intelhex import IntelHex eep_file = os.path.join(get_path("ROOT"), "eeprom.eep") map_file = os.path.join(get_path("ROOT"), "%s.map" % self.firmware) if not os.path.exists(map_file): map_file = os.path.join(get_path("ROOT"), "%s-default.map" % self.firmware) if os.path.exists(map_file): try: with open(map_file, 'r') as f: mappings = f.read().split("\n") f.closed except: pass if mappings: ih = IntelHex() i = 0 for line in mappings: try: ih[i] = int(line) except: ih[i] = 0 i += 1 eep = open(eep_file, 'w') ih.write_hex_file(eep) eep.close() do_flash = True return do_flash
def dump_state(filename, regs, content_chunks): from intelhex import IntelHex ih = IntelHex() for base_addr, contents in content_chunks.items(): # print("Adding chunk of size 0x{:x}".format(len(contents))) # f.write("0x{:08x} {}\n".format(base_addr, hexlify(contents.rstrip(b'\0')).decode())) ih.puts(base_addr, contents) with open(filename, "w") as f: f.write("""r0=0x{:x} r1=0x{:x} r2=0x{:x} r3=0x{:x} r4=0x{:x} r5=0x{:x} r6=0x{:x} r7=0x{:x} r8=0x{:x} r9=0x{:x} r10=0x{:x} r11=0x{:x} r12=0x{:x} lr=0x{:x} pc=0x{:x} sp=0x{:x} xpsr=0x{:x} """.format(*[regs[const] for const in uc_reg_consts])) print("Writing ihex dump now...") ih.write_hex_file(f)
def combine(out_file, startup_hex, bootloader_hex, firmware_hex, bin_out): """This command makes a firmare file for initial programming of a "clean" defice. The firmware file is made by combining together the Start-up code, the Bootloader, and, optionally, the Main Firmware. """ # Create initial firmware: begin with a HEX file of the Start-up code out_ih = IntelHex(startup_hex) # Read and process a HEX file of the Bootloader bootloader_ih = IntelHex(bootloader_hex) memmap = get_memmap(intelhex_to_bytes(bootloader_ih)) intelhex_add_icr(bootloader_ih, memmap['bootloader_size']) out_ih.merge(bootloader_ih, overlap='ignore') # Read and process a HEX file of the Main Firmware if specified if firmware_hex: main_ih = IntelHex(firmware_hex) if main_ih.minaddr() != memmap['main_firmware_start']: raise click.ClickException( "Main Firmware is incomatible with the Bootloader") intelhex_add_icr(main_ih, memmap['main_firmware_size']) out_ih.merge(main_ih, overlap='ignore') # Write resulting firmware in HEX or binary format if bin_out: file_obj = open(out_file, "wb") file_obj.write(intelhex_to_bytes(out_ih)) file_obj.close() else: out_ih.write_hex_file(out_file)
def read2313Flash(self, file, size, linesize = 32): iterations = round(size / 32) hex = IntelHex() data = [] for i in range(0, iterations): print(self.set2313Addr(i)) datan = list(self.read2313Data(32)) data = data + datan g0 = True for i in range(0, size): d = data[i] g1 = False g = (data[i] == 255) for f in range(0, 8): if (i + f) >= len(data): break if data[(i + f)] != 255: g1 = True break if not g0: g0 = not g g1 = False else: g0 = g1 if not g: g1 = True if g1: hex[i] = d hex.write_hex_file(file, byte_count=linesize)
def flashEeprom(self): do_flash = False if "custom" in self.firmware.lower() or "extended" in self.firmware.lower(): from intelhex import IntelHex eep_file = os.path.join(get_path("ROOT"), "eeprom.eep") map_file = os.path.join(get_path("ROOT"), "%s.map" % self.firmware) if not os.path.exists(map_file): map_file = os.path.join(get_path("ROOT"), "%s-default.map" % self.firmware) if os.path.exists(map_file): try: with open(map_file, 'r') as f: mappings = f.read().split("\n") f.closed except: pass if mappings: ih = IntelHex() i = 0 for line in mappings: try: ih[i] = int(line) except: ih[i] = 0 i +=1 eep = open(eep_file, 'w') ih.write_hex_file(eep) eep.close() do_flash = True return do_flash
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.write_hex_file(fileout, write_start_addr=False)
def generate_provision_hex_file(s0_address, s1_address, hashes, provision_address, output): # Add addresses provision_data = struct.pack('III', s0_address, s1_address, len(hashes)) provision_data += b''.join(hashes) ih = IntelHex() ih.frombytes(provision_data, offset=provision_address) ih.write_hex_file(output)
def post_process(self): logging.info("Processing binaries") # save original dir cwd = os.getcwd() # change to target dir os.chdir(self.target_dir) ih = IntelHex('main.hex') fwid = uuid.UUID('{' + self.settings["FWID"] + '}') size = ih.maxaddr() - ih.minaddr() + 1 # get os info os_project = get_project_builder(self.settings["OS_PROJECT"]) # create firmware info structure fw_info = struct.pack('<I16s128s16s128s16s', size, fwid.bytes, os_project.proj_name, os_project.version, self.proj_name, self.version) # insert fw info into hex ih.puts(0x120, fw_info) # compute crc crc_func = crcmod.predefined.mkCrcFun('crc-aug-ccitt') crc = crc_func(ih.tobinstr()) logging.info("size: %d" % (size)) logging.info("fwid: %s" % (fwid)) logging.info("crc: 0x%x" % (crc)) logging.info("os name: %s" % (os_project.proj_name)) logging.info("os version: %s" % (os_project.version)) logging.info("app name: %s" % (self.proj_name)) logging.info("app version: %s" % (self.version)) ih.puts(ih.maxaddr() + 1, struct.pack('>H', crc)) ih.write_hex_file('main.hex') ih.tobinfile('firmware.bin') # get loader info loader_project = get_project_builder(self.settings["LOADER_PROJECT"]) # create loader image loader_hex = os.path.join(loader_project.target_dir, "main.hex") self.merge_hex('main.hex', loader_hex, 'loader_image.hex') # change back to original dir os.chdir(cwd)
def tofile(self, outfile: Union[str, IO]) -> None: ih = IntelHex() ih.puts(self.base or 0, bytes(self.fw)) if Firmware._ishex(outfile): if not isinstance(outfile, str): outfile = io.TextIOWrapper(outfile) ih.write_hex_file(outfile) else: ih.tobinfile(outfile)
def create_hex(filename, addr, auto_rst, automation_allowed, overflow_detect, detect_incompatible_target, pad_size): intel_hex = IntelHex() intel_hex.puts(addr, struct.pack(FORMAT, CFG_KEY, FORMAT_LENGTH, auto_rst, automation_allowed, overflow_detect, detect_incompatible_target)) 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) intel_hex.write_hex_file(filename)
def generate_provision_hex_file(s0_address, s1_address, hashes, provision_address, output): # Add addresses provision_data = struct.pack('III', s0_address, s1_address, len(hashes)) for mhash in hashes: provision_data += struct.pack('I', 0xFFFFFFFF) # Invalidation token provision_data += mhash ih = IntelHex() ih.frombytes(provision_data, offset=provision_address) ih.write_hex_file(output)
def to_eep_file(self, eep_file_name): """Save the configuration to an EEPROM-file.""" hex_file = IntelHex() # Change any existing files instead of overwriting them. if os.path.isfile(eep_file_name): hex_file.fromfile(eep_file_name, format='hex') data = self.to_bytes(crc=True) hex_file.puts(Config.START_ADDRESS, data) hex_file.write_hex_file(eep_file_name, byte_count=0x20)
def save_changes(self): new_hex = IntelHex() new_hex.fromdict(self.get_table_dict()) save_filename = QtGui.QFileDialog.getSaveFileName(self, NAME+" - Save", os.path.join(QtCore.QDir.home().path(), self.original_filename.replace(".hex", "_copy.hex")), "Hex files (*.hex;;All Files (*)") if save_filename: new_hex.write_hex_file(save_filename[0])
def dump(self,file,start=0,stop=0xffff): """Dump an intel hex file from code memory.""" print "Dumping code from %04x to %04x as %s." % (start,stop,file); h = IntelHex(None); i=start; while i<=stop: h[i]=self.CCpeekcodebyte(i); if(i%0x100==0): print "Dumped %04x."%i; h.write_hex_file(file); #buffer to disk. i+=1; h.write_hex_file(file);
def merge_hex_files(output, input_hex_files): ih = IntelHex() for hex_file_path in input_hex_files: to_merge = IntelHex(hex_file_path) # Since 'arm-none-eabi-objcopy' incorrectly inserts record type '03 - Start Segment Address', we need to remove # the start_addr to avoid conflicts when merging. to_merge.start_addr = None ih.merge(to_merge) ih.write_hex_file(output)
def main(): parser = argparse.ArgumentParser() parser.add_argument("--output", required=True, type=pathlib.Path) parser.add_argument("--ds_hex", required=True, type=pathlib.Path) parser.add_argument("--xs_hex", required=True, type=pathlib.Path) option = parser.parse_args() ds_hex = IntelHex(str(option.ds_hex)) xs_hex = IntelHex(str(option.xs_hex)) ds_hex.merge(xs_hex) ds_hex.write_hex_file(option.output)
def writetofile(self, fwname="out.hex", eename="out.eep"): ih = IntelHex() ih.start_address = 0x100000 for x in xrange(len(self.fw_data)): ih[x] = self.fw_data[x] ih.write_hex_file(fwname) ihe = IntelHex() ihe.start_address = 0x100000 for x in xrange(len(self.ee_data)): ihe[x] = self.ee_data[x] ihe.write_hex_file(eename) print "Name: %s FW Size: %d EE Size: %d Fuses %02x:%02x:%02x Lock %02x" % (self.h_name, self.h_fw_size, self.h_ee_size, self.h_f, self.h_fh, self.h_fe, self.h_lock)
def setUp(cls): random.seed(420) cls._bin_data = bytes([random.randint(0, 0xFF) for i in range(10000)]) ihex = IntelHex() ihex.frombytes(cls._bin_data) hex_data = io.StringIO() ihex.write_hex_file(hex_data, write_start_addr=False) cls._hex_data = codecs.encode(hex_data.getvalue(), encoding='ascii') cls._args = [ 'python3', 'qpsk/encoder.py', '-s', '48000', '-y', '6000', '-b', '1K', '-f', '1K:40', '-a', '0', '-w', '10', '-p', '256' ]
def read(self, address, length, hex_file_path): if ((int(length, 16) % 4) != 0): print("ERROR: number of bytes must be a multiple of 4") return NrfDfuErr.INVALID_PARAMETER if (not self._quiet): print("Reading %s bytes from address %s" % (length, address)) open(hex_file_path, 'w+') ih = IntelHex(hex_file_path) ih.__init__() self.api.write_u32(0x2000000C, 0x00000004, True) self.api.write_u32(0x20000010, int(address, 16), False) self.api.write_u32(0x20000014, int(length, 16), False) self.api.write_u32(0x4002A004, 0x00000001, False) start_time = time.time() event_received = False while (event_received == False): if ((time.time() - start_time) > 10): print ("ERROR: Time out, no event received after 10 sec.") return NrfDfuErr.TIME_OUT return_value, event_received = self.get_event_status() if return_value < 0: return return_value self.acknowlage_events() return_value, modem_response = self.read_be(0x2000000C) if (modem_response == "5a000001"): print("\n\n ERROR: UNKNOWN COMMAND") return NrfDfuErr.DFU_ERROR elif (modem_response == "5a000002"): print("\n\n ERROR: COMMAND ERROR") error_result = self.api.read_u32(0x20000010) print("ERROR: Read failed at {}".format(hex(error_result))) return NrfDfuErr.DFU_ERROR word_count = int(length, 16)//4 for i in range(0, word_count): return_value, lelevel = self.hex_read(0x20000010+(i*4)) ih.puts(int(address,16)+(i*4), codecs.decode(lelevel, "hex")) ih.write_hex_file(hex_file_path) if (not self._quiet): print ("Reading completed") return NrfDfuErr.SUCCESS
def to_hex(self, f): ''' Convert the assembled machine code to Intel HEX file format. :param f: The HEX data will be written to this destination. :type f: filename or file-like object ''' from intelhex import IntelHex ih = IntelHex() for addr, val in self.accumulator.iteritems(): addr = int(addr, 16) ih.puts(addr, val) ih.write_hex_file(f)
def save_changes(self): new_hex = IntelHex() new_hex.fromdict(self.get_table_dict()) save_filename = QtGui.QFileDialog.getSaveFileName( self, NAME + " - Save", os.path.join(QtCore.QDir.home().path(), self.original_filename.replace(".hex", "_copy.hex")), "Hex files (*.hex;;All Files (*)") if save_filename: new_hex.write_hex_file(save_filename[0])
def generate_test_hexfile(filename, size): """ Generates a random hex file :param filename: location and name to generate :param size: number of bytes of data """ hexfile = IntelHex() # Add some data to the hexfile for i in range(size): hexfile[i] = randint(0, 255) # Turn the hexfile object into an actual file hexfile.write_hex_file(filename)
def main(args: argparse.Namespace): brtype = args.branch_type hexfile = args.hexfile # Pad a numeric string with zeros brtype = brtype.zfill(BRANCH_TYPE_BYTES * 2) # Split string data into bytes (e.g. "AABBCCDD" -> b'\xaa\xbb\xcc\xdd' bytes_brtype = bytes.fromhex(brtype) ''' # for debug print("bytes_brtype=", end='') print(bytes_brtype) ''' ih = IntelHex() # Write out user defined data global csvFilePath csvFilePath = args.user_data if csvFilePath is not None: # if csvFilePath is given if os.path.exists(csvFilePath): with open(csvFilePath, 'r') as fp: csvList = list(csv.reader(fp)) if len(csvList) > 0: print("csvList has some contents") flatList = [item for subList in csvList for item in subList] print(flatList) bytes_data = strlist_to_bytes(flatList) if len(bytes_data) > 0: ih.puts(USER_DATA_ADDR, bytes_data) else: print(csvFilePath + " is empty") ErrorMsg() else: print(csvFilePath + " not found. Skip user defined EEPROM data flash.") print() else: print("Skip user defined EEPROM data flash.") print() # Write out branchType ih.puts(SYSTEM_RESERVED_ADDR, bytes_brtype) hex_file_name = os.path.join(os.path.dirname(os.path.abspath(__file__)), hexfile) ih.dump() ih.write_hex_file(hex_file_name)
def write_eeprom_file(eeprom, eep_file="map.eep"): from intelhex import IntelHex ih = IntelHex() i = 0 for byte in eeprom: try: ih[i] = int(byte) except: ih[i] = 0 i += 1 eep = open(eep_file, 'w') ih.write_hex_file(eep) eep.close() print "EEPROM written to file: %s" % eep_file
def main(file, append, port, baud): """ Receive a code file from an attached ELF with MAX binary sender. The program reads a MAX-format binary file from the specified serial port and stores in the given file. """ class State(Enum): DATA = auto() ESCAPE = auto() ADDR_HI = auto() ADDR_LO = auto() DONE = auto() state = State.DATA address = 0 intel_hex = IntelHex() if append: intel_hex.loadhex(file) with serial.serial_for_url(port) as ser: ser.baudrate = baud ser.write(constants.START_RECV) while state != State.DONE: data = ser.read(ser.in_waiting) for byte in data: if state == State.DATA: if byte == constants.ESCAPE: state = State.ESCAPE elif byte == constants.END_OF_FILE: state = State.DONE elif byte == constants.NEW_ADDRESS: state = State.ADDR_HI else: intel_hex[address] = byte address += 1 elif state == State.ESCAPE: intel_hex[address] = byte ^ 0x20 address += 1 state = State.DATA elif state == State.ADDR_HI: address = byte << 8 state = State.ADDR_LO elif state == State.ADDR_LO: address |= byte state = State.DATA intel_hex.write_hex_file(file)
def patch_file(in_file, out_file, hex_file): with open(in_file, 'rb') as i: data = i.read() padding = bytes([0xFF]) data = data.ljust(BL_SIZE, padding) data = patch_data(data) with open(out_file, 'wb') as df: df.write(data) if len(hex_file) > 0: from intelhex import IntelHex out = IntelHex() out.frombytes(data, offset=BL_START) out.write_hex_file(hex_file)
def to_hex(self, filename, offset): ih = IntelHex() # Cycles and command numbers ih[offset] = self.__cycles_number // 256 ih[offset + 1] = self.__cycles_number % 256 ih[offset + 2] = self.cmd_number() offset += 3 # Commands for cmd in self.__commands: offset = self.__cmd_to_hex(cmd, ih, offset) ih.write_hex_file(filename)
class HexTruth: #Class which takes a dict or CSV file and converts it into an Intel Hex file for ROM burning. def __init__(self, csvFilename, loadDict = None, hexFilename=None ): if hexFilename is None: hexFilename = csvFilename.split(".")[0]+ ".hex" self.csvFilename = csvFilename self.hexFilename = hexFilename self.ih= IntelHex() self.hexDict = {}; if loadDict is not None: self.hexDict = loadDict self.ih.fromdict(loadDict) self.writeFromIntelHex() def writeFromIntelHex(self): #Takes the IntelHex object and writes it to a hex file. f = open(self.hexFilename, 'w'); self.ih.write_hex_file(f) f.close() print("Hex file generated.") def importCSV(self): #Opens a given csv filename and returns it's values as a list of lists. #list of lists = rows of columns self.csvTruth = [] with open(self.csvFilename, newline='') as csvfile: csvReadingMachine = csv.reader(csvfile, delimiter=',', quotechar='"') for row in csvReadingMachine: self.csvTruth.append(row) if "#" in str(row):continue [addr, dat] = str(row).split("''") rangeIn = [0, addr.count(',') -1] if dat.count(",") is 1: rangeOut = [rangeIn[-1] + 2] else:rangeOut = [rangeIn[-1] + 2, rangeIn[-1] + 1 + dat.count(",")] binaryString = "" for j in range(rangeIn[0], rangeIn[-1] + 1): binaryString+=str(row[j]) #address = binaryString address = (int(binaryString,2)) binaryString = "" for j in range(rangeOut[0], rangeOut[-1] + 1): binaryString+=str(row[j]) #data = binaryString; data = (int(binaryString,2)) #print(str(address) + ":" + str(data)) self.hexDict[address] = data #print(row) return self.hexDict
def createHexWithPagePositions(lastOffset): tmp=open(bin_dir+program_name+"_privateData.hex","w+"); ih=IntelHex(); num_pages= floor(float(lastOffset)/float(PAGE_SIZE)); initPosition=0; counterEPROM=initPosition; i=0; while i < num_pages*PAGE_SIZE: first=(i & 0xFF00)>>8; second=(i & 0x00FF); # LITTLE ENDIAN ih[counterEPROM]=second; ih[counterEPROM+1]=first; i+=PAGE_SIZE; counterEPROM+=2; print; ih.write_hex_file(tmp);
def main(arguments): # If using ANSI coloring is available, initialize colorama if fail_color: init() # Import intelhex if avaialable, otherwise fail try: from intelhex import IntelHex except: return fail('error: You do not have \'intelhex\' installed. Please run \'pip install intelhex\' then retry.') # Ensure the right number of arguments are supplied if not len(arguments) == 3: return fail('error: Improper use of merge_hex.py.\nUSAGE: merge_hex.py input_file1 input_file2 output_file.') # Get the two hex files, merge them, and save the result orig = IntelHex(arguments[0]) new = IntelHex(arguments[1]) orig.merge(new, overlap='replace') orig.write_hex_file(arguments[2])
def create(ds_address, app_address, script_file): bl_scr = bl_script(1) bl_scr.cmd_app_handshake() bl_scr.cmd_sd_init(app_address) bl_scr.cmd_exec(app_address) scrdata = bl_scr.get() scrdata = bl_script.page_start(scrdata) scrdata = bl_script.page_stop(scrdata) ih = IntelHex() for i in range(len(scrdata)): ih[ds_address + i] = scrdata[i] with open(script_file, 'w') as out_file: ih.write_hex_file(out_file) click.echo("Created default page hex file %s with address: %s and app start address %s " % (script_file, hex(ds_address), hex(app_address)))
def dump(self, fn, start=0, stop=0xFFFFFFFF): """Dump an intel hex file from code memory.""" print "Dumping from %04x to %04x as %s." % (start, stop, f) # FIXME: get mcu state and return it to that state self.halt() h = IntelHex(None) i = start while i <= stop: data = self.ARMreadChunk(i, 48, verbose=0) print "Dumped %06x." % i for dword in data: if i <= stop and dword != 0xDEADBEEF: h.puts(i, struct.pack("<I", dword)) i += 4 # FIXME: get mcu state and return it to that state self.resume() h.write_hex_file(fn) print "Dump not implemented."
def dump(self,fn,start=0,stop=0xffffffff): """Dump an intel hex file from code memory.""" print "Dumping from %04x to %04x as %s." % (start,stop,f); # FIXME: get mcu state and return it to that state self.halt() print "halted, starting the dump" h = IntelHex(None); i=start; while i<=stop: data=self.ARMreadChunk(i, 48, verbose=0); print "Dumped %06x."%i; for dword in data: if i<=stop and dword != 0xdeadbeef: h.puts( i, struct.pack("<I", dword) ) i+=4; # FIXME: get mcu state and return it to that state self.resume() h.write_hex_file(fn); print "Dump not implemented.";
def encrypt(): tmp=open(bootloader_dir+bootloaderName+"_encrypted.hex","w+"); ih=IntelHex(bootloader_dir+bootloaderName+".hex"); keyPos=0; dictionary=ih.todict(); addresses=dictionary.keys(); pages=-1; for b in addresses: #print hex(p)+":"+hex(dictionary[p]); if (b!="start_addr") and b>=initAddr and b<endAddr: #print b,hex(b); if (b%PAGE_SIZE)==0: pages=pages+1; keyPos=0 print; print; print "PAGE ",pages; print hex(b)+":"+hex(dictionary[b])+"^"+hex(key[keyPos])+"=", dictionary[b]=dictionary[b]^key[keyPos] print hex(dictionary[b])+" ", keyPos=keyPos+1; ih.fromdict(dictionary); ih.write_hex_file(tmp);
# Sanity checks, very important if ih.maxaddr() < 0x1004 or ih.maxaddr() > 32767: print "Insane hexfile: min=0x%x max=0x%x" % (ih.minaddr(), ih.maxaddr()) sys.exit(2) print "Length: %d / 28672" % (ih.maxaddr() - 4096 + 1) print "Free: %d" % (28672 - (ih.maxaddr() - 4096 + 1)) # Hack to force tobinstr() to write data from addres 0. IntelHex will # only write data from the first location with initialized data, skipping # over any uninitialized data beforehand. This initializes address 0, # forcing IntelHex to do what I want. ih[0]=ih[0] sumdata = (ih.tobinstr())[0x1004:] sumdata += '\xff' * (0x6ffc - len(sumdata)) cksum = binascii.crc32(sumdata) & 0xffffffff print "Checksum: 0x%08x" % cksum ih.puts(0x1000, struct.pack('<L', cksum)) # Rather than using IntelHex.tobinfile(), i'm writing to a file this way # to ensure that the file ends up at exactly 32768 bytes. binfw = ih.tobinstr() binfw += '\xff' * (0x8000 - len(binfw)) out.write(binfw) out.close() # Testing only. a=IntelHex() a.loadbin(sys.argv[2]) a.write_hex_file(sys.argv[2] + '.hex')
if not os.path.exists(sys.argv[2]): sys.exit("Unable open build %s" % sys.argv[2]) build_filename = sys.argv[1] prog_filename = sys.argv[2] # open the build and prog # note open build via StringIO so we can add to it build = IntelHex(StringIO.StringIO(open(build_filename, "r").read())) prog = IntelHex(prog_filename) # merge program into build prog_header_addr = prog.minaddr() prog.start_addr = build.start_addr # we need this to make the merge work smoothly build.merge(prog) # add pointer to program header to the bootstrap header_tbl_addr = 0x08000204 header_tbl_len = 2 #@todo get this from 0x0800200 as uint32_t header_tbl_format = "<LL" header_tbl = list(struct.unpack(header_tbl_format, build.gets(header_tbl_addr, header_tbl_len * 4))) k = 0 while header_tbl[k] != 0xffffffff: if k > header_tbl_len: sys.exit("bootstrap program table full [you have too many programs]!"); k += 1 header_tbl[k] = prog_header_addr build.puts(header_tbl_addr, struct.pack(header_tbl_format, *header_tbl)) # done build.write_hex_file(build_filename)
if modf(chan)[0] != 0.0: print "Illegal freq/spacing combo" sys.exit(2) chan = int(chan) # First create the data without the checksum, note that we specify # little-endianness for multi-byte values. t = pack('<BBBHB8x', band, demphasis, spacing, chan, volume) # Calculate and append a crc-16 checksum crc16 = Crc('crc-16') crc16.update(t) t = t + pack('<H', crc16.crcValue) # # Simply create a hex file with the concatenation of two tuning structures (t) # and optionally one manufacturing structure, then write the result. # eeprom = t + t if manuf: eeprom = eeprom + manuf_record(sn, ts, campaign) hexfile = IntelHex() hexfile.puts(0, eeprom) hexfile.write_hex_file(outfile)
def get_hex(f, b, d, cs): # # All the following to be able to be set with getopt. # These defaults will do for testing purposes. # outfile=sys.stdout # manufacturing data # manuf=False sn="" ts="" campaign="" eyecatcher='The Public Radio' # tuning info defaults # freq=0.0 band=0 # US 87.5 - 108 demphasis=0 # US 75uS spacing=0 # US 200KHz volume=0x0f # max (0 dBFS) # # Create a manufacturing record. # def manuf_record(sn, ts, campaign): ww = int(date.today().strftime('%V')) yy = int(date.today().strftime('%g')) return pack('17sBB2s13s17s', sn[:16], ww, yy, ts[:2], campaign[:12], eyecatcher) # # calculate channel # based on freq, band & channel spacing. # Note that we force the floating point arithmetic to round # to a reasonable number of digits in order to avoid daft problems. freq = float(f) band = int(b) demphasis = int(d) spacing= int(cs) base = {0: 87.5, 1: 76, 2: 76} step = {0: 5, 1: 10, 2: 20} try: chan = round((freq - base[band]) * step[spacing], 4) except: chan = round((freq - base[0]) * step[0], 4) if modf(chan)[0] != 0.0: chan = 0 chan = int(chan) # First create the data without the checksum, note that we specify # little-endianness for multi-byte values. t = pack('<BBBHB8x', band, demphasis, spacing, chan, volume) # Calculate and append a crc-16 checksum crc16 = crcmod.predefined.Crc('crc-16') crc16.update(t) t = t + pack('<H', crc16.crcValue) # # Simply create a hex file with the concatenation of two tuning structures (t) # and optionally one manufacturing structure, then write the result. # eeprom = t + t if manuf: eeprom = eeprom + manuf_record(sn, ts, campaign) outfile = tempfile.NamedTemporaryFile(prefix='eeprom.', suffix='.hex', delete=False) hexfile = IntelHex() hexfile.puts(0, eeprom) hexfile.write_hex_file(outfile) outfile.close() return outfile
import sys from intelhex import IntelHex WRITEBACK = True if len(sys.argv) > 1: WRITEBACK = False ser = int(sys.argv[1]) else: try: ser = int(file(".serial", "rb").read(), 16) + 1 except IOError: ser = 0 print >>sys.stderr, ("[--- new serial number: %.4x ---]" % ser) if WRITEBACK: file(".serial", "wb").write("%.13x" % ser) sertxt = "" sertmp = "%.13x" % ser for c in sertmp: sertxt += "%s\x00" % c ihc = IntelHex("CCBootloader/CCBootloader-rfcat-chronosdongle.hex") ihd = IntelHex("CCBootloader/CCBootloader-rfcat-donsdongle.hex") ihc.puts(0x13E0, "@las\x1c\x03" + sertxt) ihd.puts(0x13E0, "@las\x1c\x03" + sertxt) ihc.write_hex_file("CCBootloader/CCBootloader-rfcat-chronosdongle-serial.hex") ihd.write_hex_file("CCBootloader/CCBootloader-rfcat-donsdongle-serial.hex")
model, version, subversion, litera, assmcode =\ struct.unpack_from('<HHHcB', code, ver_data_offset) ver = str(model) + '.' + str(version) + '.' + str(subversion) + '.' + litera + '-' + str(assmcode) print 'Extracted version data:', ver print 'Merging bootloader file...', ih.start_addr = None # program start addr record will be from BL part try: ih.merge(blih, overlap='error') print 'Ok' except AddressOverlapError: print ' probably already merged, data overlap! CHECK THIS!' finally: hx_fn = 'DKSF_' + ver + '_HX.hex' print 'Writing', hx_fn, '...', ih.write_hex_file(hx_fn) print 'Ok' npf = '' npf += fwstart npf += code npf += fwend npf += resstart npf += res npf += resend npf += jsstart npf += """function fw_is_updated(v) { return v == 'v%d.%d.%d.%c-%d'; } """ % (model, version, subversion, litera.upper(), assmcode) npf += """function fw_is_compatible() { return fwver.split('.')[0] == 'v%d'; }
mergedHex.puts(metaAddr, meta) #production image only calculates over imgA region if vargs.oadtype == 'onchip' and vargs.imgtype == 'production': asBin = mergedHex.tobinstr(INT_FL_OAD_IMG_A_META_BEGIN, INT_FL_OAD_IMG_A_END) else: asBin = mergedHex.tobinstr(startAddr, endAddr-1) crc = crc16(asBin[4:]) mergedHex.puts(metaAddr, struct.pack('H', crc)) metaVector = [crc, crcShdw, imgVer, imgLen, usrId, imgAddr, imgType, META_STATUS_SUCCESS] print_metadata(metaVector) #mergedHex.puts(metaAddr, struct.pack('B', 0xff)*16) # Output merged hex file unless both hex and bin is stdout, in which case bin wins if not (vargs.out is sys.stdout and vargs.outbin is sys.stdout): print("Writing to:\n", vargs.out.name) mergedHex.write_hex_file(vargs.out) vargs.out.flush() # Output binary if vargs.outbin is not None: print("Writing to:\n", vargs.outbin.name) for ch in mergedHex.tobinstr(startAddr, endAddr-1): vargs.outbin.write(ch) vargs.outbin.flush() print("******************************************************************************************") print("Success") print("******************************************************************************************")
ext_item_value = struct.pack('<L', int(args.ext_info[0], 16)) write_hex_entry(ih, ext_item_value, GBOOT_EXT_INFO_OFFSET) if args.mcu: print '==> info: update MCU item at offset 0x%04x' % (GBOOT_MCU_OFFSET) mcu_value = struct.pack('<H', int(args.mcu[0], 16)) write_hex_entry(ih, mcu_value, GBOOT_MCU_OFFSET) if args.pcb_rev: print '==> info: update PCB revision item at offset 0x%04x' % (GBOOT_PCB_REV_OFFSET) pcb_rev_value = struct.pack('<B', int(args.pcb_rev[0], 16)) write_hex_entry(ih, pcb_rev_value, GBOOT_PCB_REV_OFFSET) if args.pid: print '==> info: update USB PID item at offset 0x%04x' % (GBOOT_PID_OFFSET) pid_value = struct.pack('<H', int(args.pid[0], 16)) write_hex_entry(ih, pid_value, GBOOT_PID_OFFSET) if args.serial: print '==> info: update Serial ID item at offset 0x%04x' % (GBOOT_SERIAL_OFFSET) serial_value = struct.pack('<L', int(args.serial[0], 16)) write_hex_entry(ih, serial_value, GBOOT_SERIAL_OFFSET) if args.version: print '==> info: update Version item at offset 0x%04x' % (GBOOT_VER_OFFSET) version_value = struct.pack('<B', int(args.version[0], 16)) write_hex_entry(ih, version_value, GBOOT_VER_OFFSET) print '==> info: finished updating gboot bootload image' ih.write_hex_file(args.hex_file[0])
def arm9_cli_handler(client, argv): if(argv[1]=="info"): client.halt() print >>sys.stderr, client.ARMidentstr() print >>sys.stderr,"Debug Status:\t%s" % client.statusstr() print >>sys.stderr,"CPSR: (%s) %s\n"%(client.ARMget_regCPSRstr()) client.resume() if(argv[1]=="dump"): f = sys.argv[2] start=0x00000000 stop=0xFFFFFFFF if(len(sys.argv)>3): start=int(sys.argv[3],16) if(len(sys.argv)>4): stop=int(sys.argv[4],16) print "Dumping from %04x to %04x as %s." % (start,stop,f) #h = IntelHex16bit(None) # FIXME: get mcu state and return it to that state client.halt() try: h = IntelHex(None) i=start while i<=stop: #data=client.ARMreadMem(i, 48) data=client.ARMreadChunk(i, 48, verbose=0) print "Dumped %06x."%i for dword in data: if i<=stop and dword != 0xdeadbeef: h.puts( i, struct.pack("<I", dword) ) i+=4 # FIXME: get mcu state and return it to that state except: print "Unknown error during read. Writing results to output file." print "Rename file with last address dumped %06x."%i pass client.resume() h.write_hex_file(f) ''' if(sys.argv[1]=="erase"): print "Erasing main flash memory." client.ARMmasserase() if(sys.argv[1]=="eraseinfo"): print "Erasing info memory." client.ARMinfoerase() ''' if(sys.argv[1]=="ivt"): client.halt() client.ARMprintChunk(0x0,0x20) client.resume() if(sys.argv[1]=="regs"): client.halt() for i in range(0,16): print "r%i=%04x" % (i,client.ARMget_register(i)) client.resume() if(sys.argv[1]=="flash"): f=sys.argv[2] start=0 stop=0x10000 if(len(sys.argv)>3): start=int(sys.argv[3],16) if(len(sys.argv)>4): stop=int(sys.argv[4],16) client.halt() h = IntelHex16bit(f) #Should this be default? #Makes flashing multiple images inconvenient. #client.ARMmasserase() count=0; #Bytes in commit. first=0 vals=[] last=0; #Last address committed. for i in h._buf.keys(): if((count>0x40 or last+2!=i) and count>0 and i&1==0): #print "%i, %x, %x" % (len(vals), last, i) client.ARMpokeflashblock(first,vals) count=0 first=0 last=0 vals=[] if(i>=start and i<stop and i&1==0): val=h[i>>1] if(count==0): first=i last=i count+=2 vals+=[val&0xff,(val&0xff00)>>8] if(i%0x100==0): print "%04x" % i if count>0: #last commit, ivt client.ARMpokeflashblock(first,vals) client.resume() if(sys.argv[1]=="verify"): f=sys.argv[2] start=0 stop=0xFFFF if(len(sys.argv)>3): start=int(sys.argv[3],16) if(len(sys.argv)>4): stop=int(sys.argv[4],16) client.halt() h = IntelHex16bit(f) for i in h._buf.keys(): if(i>=start and i<stop and i&1==0): peek=client.peek(i) if(h[i>>1]!=peek): print "ERROR at %04x, found %04x not %04x"%(i,peek,h[i>>1]) if(i%0x100==0): print "%04x" % i client.resume() if(sys.argv[1]=="peek"): start = 0x0000 if(len(sys.argv)>2): start=int(sys.argv[2],16) stop = start+4 if(len(sys.argv)>3): stop=int(sys.argv[3],16) print "Peeking from %04x to %04x." % (start,stop) client.halt() for dword in client.ARMreadChunk(start, (stop-start)/4, verbose=0): print "%.4x: %.8x" % (start, dword) start += 4 client.resume() if(sys.argv[1]=="poke"): start=0x0000 val=0x00 if(len(sys.argv)>2): start=int(sys.argv[2],16) if(len(sys.argv)>3): val=int(sys.argv[3],16) print "Poking %06x to become %04x." % (start,val) client.halt() #???while client.ARMreadMem(start)[0]&(~val)>0: client.ARMwriteChunk(start, [val]) print "Poked to %.8x" % client.ARMreadMem(start)[0] client.resume() if(sys.argv[1]=="reset"): #Set PC to RESET vector's value. #client.ARMsetPC(0x00000000) #client.ARMset_regCPSR(0) #client.ARMreleasecpu() client.ARMresettarget(1000)
def generateNewHex(): tmp=open(bin_dir+program_name+"_modified.hex","w+"); ih=IntelHex(bin_dir+program_name+".hex"); binary=ih.tobinarray(); for p in pointers: if 'rjmp' in p: offset=int(p.split(":")[1],16); destination=p.split(":")[3]; binary.pop(offset); binary.pop(offset); insertOpcodeJMP(destination,offset,binary); elif 'jmp' in p: offset=int(p.split(":")[1],16); destination=p.split(":")[3]; binary.pop(offset); binary.pop(offset); binary.pop(offset); binary.pop(offset); insertOpcodeJMP(destination,offset,binary); elif 'rcall' in p: offset=int(p.split(":")[1],16); destination=p.split(":")[3]; binary.pop(offset); binary.pop(offset); insertOpcodeCALL(destination,offset,binary); elif 'call' in p: offset=int(p.split(":")[1],16); destination=p.split(":")[3]; binary.pop(offset); binary.pop(offset); binary.pop(offset); binary.pop(offset); insertOpcodeCALL(destination,offset,binary); elif 'br' in p: offset=int(p.split(":")[1],16); destination=p.split(":")[3]; opcode=p.split(":")[4]; binary.pop(offset); binary.pop(offset); insertOpcodeBR(destination,offset,binary,opcode); elif 'nop' in p: offset=int(p.split(":")[1],16); binary.insert(offset,0x00); binary.insert(offset+1,0x00); elif 'jump_link' in p: offset=int(p.split(":")[1],16); destination=p.split(":")[3]; insertOpcodeJMP(destination,offset,binary); elif 'global_ctors' in p: offset=int(p.split(":")[1],16); destination=p.split(":")[3]; binary.pop(offset); binary.pop(offset); insertOpcodeGLOBAL_CTORS(destination,offset,binary); elif 'vpointer' in p: offset=int(p.split(":")[1],16)-0x800000-0x100+offsetDataInSRAM; destination=p.split(":")[3]; binary.pop(offset); binary.pop(offset); insertOpcodeVPointers(destination,offset,binary); elif 'ldi_data_offset' in p: offset=int(p.split(":")[1],16); destination=p.split(":")[3]; binary.pop(offset); binary.pop(offset); binary.pop(offset); binary.pop(offset); insertOpcodeLDI_destination(destination,offset,binary); elif 'prologues' in p: offset=int(p.split(":")[1],16); destination=p.split(":")[3]; ad=destination.split("0x")[1]; while (len(ad)<4): ad='0'+ad; pc=address2pc(int(ad[0:2],16),int(ad[2:4],16)); destination="0x"+h(pc)+l(pc); binary.pop(offset); binary.pop(offset); binary.pop(offset); binary.pop(offset); insertOpcodeLDI_destination(destination,offset,binary); ih.frombytes(binary); ih.write_hex_file(tmp);
header_addr = prog.minaddr() # all programs require there header to be located at the start # read out the header header = ih2header(prog) # optional updates if args.pid != None and args.pid >= 0 and args.pid < 256: header['pid'] = args.pid if args.key != None: header['key'] = args.key if args.hw != None: header['hw_id'] = args.hw # update the header len l = prog.maxaddr() - prog.minaddr() + 1 header['len'] = l prog = header2ih(prog, header) # put the length back into the intel hex file for crc # update the header crc (note we do no include the CRC word in the CRC) crc_start_addr = prog.minaddr() + 4 prog.padding = 0xff buf = prog.tobinstr(start=crc_start_addr) crc.crc_init(crc.stm32f10x_crc_h) crc = crc.crc_buf(crc.stm32f10x_crc_h, buf, len(buf)) & 0xffffffff header['crc'] = crc prog = header2ih(prog, header) # put the crc back into the intel hex file so we can write it out # write header back to hex file prog.write_hex_file(sys.stdout)
def merge_hex(self, hex1, hex2, target): ih = IntelHex(hex1) ih.merge(IntelHex(hex2)) ih.write_hex_file(target)