def __init__(self, hexfile):
        try:
            self.app_size_packet = None
            self.app_crc_packet = 0xFFFF
            self.data_packets = []

            ih = IntelHex(hexfile)
            bin_array = ih.tobinarray()
            fsize = len(bin_array)
            self.app_size_packet = [(fsize >>  0 & 0xFF),
                                    (fsize >>  8 & 0xFF),
                                    (fsize >> 16 & 0xFF),
                                    (fsize >> 24 & 0xFF)]

            for i in range(0, len(bin_array), PKT_SIZE):
                data = (bin_array[i:i+PKT_SIZE])
                self.data_packets.append(data)
                self.crc16_compute(data)

            crc_packet = self.app_crc_packet
            self.app_crc_packet = [(crc_packet >> 0 & 0xFF),
                                   (crc_packet >> 8 & 0xFF)]

        except Exception, e1:
            print "HexToDFUPkts init Exception %s" % str(e1)
            sys.exit(0)
예제 #2
0
파일: build_api.py 프로젝트: akselsm/mbed
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')
예제 #3
0
파일: loader.py 프로젝트: HexTank/KADE
 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
예제 #4
0
 def load_image(self, path):
     retst = True
     self.data_buffer = bytearray()
     if path.lower().endswith(".bin"):
         with open(path, "rb") as f:
             self.data_buffer = f.read()
             f.close()
     elif path.lower().endswith(".hex"):
         ihex = IntelHex()
         try:
             ihex.loadfile(path, format="hex")
         except Exception as e:
             wx.MessageBox("Could not read from file: %s\n\n%s" % (path, str(e)), "ERROR", wx.OK | wx.ICON_ERROR)
             retst = False
         else:
             dhex = ihex.todict()
             self.data_buffer = bytearray([0xFF] * (max(dhex.keys()) + 1))
             for i, val in dhex.items():
                 self.data_buffer[i] = val
     elif path.lower().endswith((".s19", ".srec")):
         srec = SRecFile()
         try:
             srec.open(path)
         except Exception as e:
             wx.MessageBox("Could not read from file: %s\n\n%s" % (path, str(e)), "ERROR", wx.OK | wx.ICON_ERROR)
             retst = False
         else:
             self.data_buffer = srec.data
     else:
         retst = False
         wx.MessageBox("Not supported file Type !", "ERROR", wx.OK | wx.ICON_ERROR)
     return retst
예제 #5
0
def main():
	addr = 0
	page = 0
	port = sys.argv[1]
	firmware = IntelHex(sys.argv[2])
	
	# Wait for device to appear
	print "Waiting for device to appear"
	dev_found = False
	while dev_found == False:
		cmd_output = commands.getstatusoutput("ls " + port)
		if "such" not in cmd_output[1]:
			dev_found = True
	print "Device Found!"

	prog = loader()
	# try:
		
	# except:
		# print "Usage: "+sys.argv[0]+" name of hex file"
		# raise SystemExit
		
	prog.openSerial(port,57600)
	prog.getId()
	prog.getType()
	prog.getVersion()
	for i in range(0,len(firmware),128):
		prog.setAddress(addr)
		#print "Writing page", hex(addr)
		prog.writeFlashPage(firmware.tobinarray(start=addr, size=128))
		addr += 128
  
	prog.enableRwwSection()
	prog.ser.close()
예제 #6
0
파일: flash_tool.py 프로젝트: geky/pyOCD
def main():
    args = parser.parse_args()
    setup_logging(args)

    # Sanity checks before attaching to board
    if args.format == 'hex' and not intelhex_available:
        print("Unable to program hex file")
        print("Module 'intelhex' must be installed first")
        exit()

    if args.list_all:
        MbedBoard.listConnectedBoards()
    else:
        board_selected = MbedBoard.chooseBoard(board_id=args.board_id, target_override=args.target_override,
                                               frequency=args.frequency)
        with board_selected as board:
            flash = board.flash
            transport = board.transport

            # Boost speed with deferred transfers
            transport.setDeferredTransfer(True)

            progress = print_progress
            if args.hide_progress:
                progress = None

            chip_erase = None
            if args.chip_erase:
                chip_erase = True
            elif args.sector_erase:
                chip_erase = False

            # Binary file format
            if args.format == 'bin':
                # If no address is specified use the start of rom
                if args.address is None:
                    args.address = board.flash.getFlashInfo().rom_start

                with open(args.file, "rb") as f:
                    f.seek(args.skip, 0)
                    data = f.read()
                args.address += args.skip
                data = unpack(str(len(data)) + 'B', data)
                flash.flashBlock(args.address, data, chip_erase=chip_erase, progress_cb=progress,
                                 fast_verify=args.fast_program)

            # Intel hex file format
            if args.format == 'hex':
                hex = IntelHex(args.file)
                addresses = hex.addresses()
                addresses.sort()

                flash_builder = flash.getFlashBuilder()

                data_list = list(ranges(addresses))
                for start, end in data_list:
                    size = end - start + 1
                    data = list(hex.tobinarray(start=start, size=size))
                    flash_builder.addData(start, data)
                flash_builder.program(chip_erase=chip_erase, progress_cb=progress, fast_verify=args.fast_program)
예제 #7
0
파일: targets.py 프로젝트: jurgis/mbed
    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')
예제 #8
0
class Driver(FirmwareBase):
    def __init__(self, filename):
        FirmwareBase.__init__(self)

        self.__ih = IntelHex()
        self.__ih.loadhex(filename)

        cs = crc.crc16()
        for each in range(self.__ih.minaddr(), self.__ih.maxaddr()+1):
            cs.addByte(self.__ih[each])
        self.__size = self.__ih.maxaddr()+1
        self.__checksum = cs.getResult()


    def download(self):
        progress = 0.0
        self.sendStatus("Starting Download to Node " + str(self.destNode))
        while True:
            if self.kill==True:
                self.sendProgress(0.0)
                self.sendStatus("Download Stopped")
                return
            time.sleep(0.1)
            self.sendProgress(progress)
            progress = progress + 0.01
            if progress > 1: break
        self.sendProgress(1.0)
        self.sendStatus("Download Successful")
예제 #9
0
    def program(self, args):
        from intelhex import IntelHex
        nrf = SetupCommand(args)

        if args.eraseall:
            nrf.api.erase_all()
        if args.sectorsanduicrerase:
            nrf.api.erase_uicr()

        hex_file = IntelHex(args.file)
        for segment in hex_file.segments():
            start_addr, end_addr = segment
            size = end_addr - start_addr

            if args.sectorserase or args.sectorsanduicrerase:
                start_page = int(start_addr / nrf.device.page_size)
                end_page = int(end_addr / nrf.device.page_size)
                for page in range(start_page, end_page + 1):
                    nrf.api.erase_page(page * nrf.device.page_size)

            data = hex_file.tobinarray(start=start_addr, size=(size))
            nrf.api.write(start_addr, data.tolist(), True)

            if args.verify:
                read_data = nrf.api.read(start_addr, len(data))
                assert (self.byte_lists_equal(data, read_data)), 'Verify failed. Data readback from memory does not match data written.'

        self._reset(nrf, args)

        nrf.cleanup()
예제 #10
0
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)
예제 #11
0
def mpmSecGetVersionNumberFromHex(firmwareName):
	firmware = IntelHex(firmwareName)
	firmware_bin = firmware.tobinarray()
	for i in range(len(firmware_bin) - 3):
		if chr(firmware_bin[i]) == 'v' and chr(firmware_bin[i + 1]) >= '1' and chr(firmware_bin[i + 1]) <= '9' and chr(firmware_bin[i + 2]) == '.' and chr(firmware_bin[i + 3]) >= '0' and chr(firmware_bin[i + 3]) <= '9':
			firmware_version = "".join(map(chr, firmware_bin[i:i+4]))
			return firmware_version
	return ""
예제 #12
0
    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')
예제 #13
0
파일: _test.py 프로젝트: tali/PyMK
 def _test_read(self, hexstr, data, start_addr):
     sio = StringIO(hexstr)
     ih = IntelHex(sio)
     self.assert_(ih.readfile(), "readfile return error: %s" % ih.Error)
     sio.close()
     # test data
     self.assertEqual(data, ih._buf, "Internal buffer: %r != %r" % (data, ih._buf))
     self.assertEqual(start_addr, ih.start_addr, "Start address: %r != %r" % (start_addr, ih.start_addr))
예제 #14
0
def flashHex(target, filename):
    '''
    flash a hex file to nRF51822
    '''
    ihex = IntelHex(filename)
    addresses = ihex.addresses()
    nbytes = len(addresses)
    addresses.sort()
    
    start = time()
    
    target.halt()
    
    if addresses[0] == 0:
        logging.info("Erase All")
        target.writeMemory(NVMC_CONFIG, 2)
        target.writeMemory(NVMC_ERASEALL, 1)
        while target.readMemory(NVMC_READY) == 0:
            pass
       
    logging.info("Prepare to write")
    target.writeMemory(NVMC_CONFIG, 1)
    while target.readMemory(NVMC_READY) == 0:
        pass


    nbytes_align32 = nbytes & ~(32 - 1)
    for i in range(0, nbytes_align32, 32):
        if (addresses[i] + 31) == addresses[i + 31]:
            start_address = addresses[i]
            # read 32 data bytes
            bytes = ihex.tobinarray(start=start_address, size=32)
            target.writeBlockMemoryUnaligned8(start_address, bytes)
            
            bytes_readback = target.readBlockMemoryUnaligned8(start_address, 32)
            for j in range(len(bytes)):
                if (bytes[j] != bytes_readback[j]):
                    logging.info("Write: error at 0x%X - 0x%X | 0x%X", start_address + j, bytes[j], bytes_readback[j])
                    raise Exception("Verify Error") 
            
        else:
            # data always 4 bytes aligned
            for j in range(0, 32, 4):
                start_address = addresses[i + j]
                bytes = ihex.tobinarray(start=start_address, size=4)
                target.writeBlockMemoryUnaligned8(start_address, bytes)      
        
    for i in range(nbytes_align32, nbytes, 4):
        start_address = addresses[i]
        bytes = ihex.tobinarray(start=start_address, size=4)
        target.writeBlockMemoryUnaligned8(start_address, bytes)
        
    target.writeMemory(NVMC_CONFIG, 0)
    while target.readMemory(NVMC_READY) == 0:
        pass
        
    end = time()
    print("%f kbytes flashed in %f seconds ===> %f kbytes/s" %(nbytes/1000, end-start, nbytes/(1000*(end - start))))
예제 #15
0
파일: loader.py 프로젝트: mesheven/pyOCD
    def _program_hex(self, file_obj, **kwargs):
        hexfile = IntelHex(file_obj)
        addresses = hexfile.addresses()
        addresses.sort()

        data_list = list(ranges(addresses))
        for start, end in data_list:
            size = end - start + 1
            data = list(hexfile.tobinarray(start=start, size=size))
            self._loader.add_data(start, data)
예제 #16
0
파일: targets.py 프로젝트: jurgis/mbed
    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')
예제 #17
0
파일: device.py 프로젝트: vkorehov/haserver
def firmware_upload(i2c_addr, filename, size, log):
        global total_retries_count
	ih = IntelHex()
	ih.loadhex(filename)
	ihd = ih.todict()     # dump contents to pydict
	skiprange = False
	for a in range(0,size, flash_write_block*2): # PIC16F
		skiprange = True
		for aa in range(a,a+flash_write_block*2):
			if aa in ihd:
				skiprange = False
		if skiprange:
			continue;
                # only 14bit data with leading high byte, mask unused bits away, if hex file had no entry for some byte them, put zeres
                d = [(ihd[aa] if aa in ihd else 0) for aa in range(a,a+flash_write_block*2)]
		
		aw = a/2 # config space is mapped AS-IS

		if aw >= 0x8000: # skip programming of config space
			continue;
                if aw >= 0x4000:
                        raise IOError('hex file is too large to fit into memory range')

		if aw < 0x80000: # skip programming of config space
			print >>log, "programming block @:"+hex(aw) + " data:"+(':'.join("%02x" % c for c in d))
			_flash_upload(i2c_addr, aw, [c for c in d])		
		aw += flash_write_block

        skiprange = False
        for a in range(0,size, flash_write_block*2): # PIC16F
                skiprange = True
                for aa in range(a,a+flash_write_block*2):
                        if aa in ihd:
                                skiprange = False
                if skiprange:
                        continue;
		# only 14bit data with leading high byte, mask unused bits away, if hex file had no entry for some byte them, put zeres
                d = [(ihd[aa] if aa in ihd else 0) & 0x3f if a % 2 == 1 else (ihd[aa] if aa in ihd else 0)  for aa in range(a,a+flash_write_block*2)]

                aw = a/2 # config space is mapped AS-IS
		if aw >= 0x8000:
			# skip verification of config space
			continue

                print >>log, "verifying block (expected) @:"+hex(aw) + " data:"+(':'.join("%02x" % c for c in d)),
		dd = _flash_download(i2c_addr, aw)
		#print "verifying block (actual  ) @:"+hex(aw) + " data:"+(':'.join("%02x" % c for c in dd))
                aw += flash_write_block		
		for av in range(a,a+flash_write_block*2,2):
			if (av in ihd) and ((dd[av - a] != d[av - a]) or dd[av - a + 1] & 0x3f != d[av - a + 1]):
				fa = aw-flash_write_block + av/2				
				raise IOError("device flash data is different from expected @"+hex(aw-flash_write_block)+\
							", it is:"+hex(dd[av-a])+","+hex(dd[av-a+1])+" while should be:"+hex(d[av-a])+","+hex(d[av-a+1]))
		print >>log, "OK"
	return total_retries_count
예제 #18
0
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')
예제 #19
0
    def verify(self, args):
        board = self._setup()

        hex_file = IntelHex(args.file)
        for segment in hex_file.segments():
            start_addr, end_addr = segment
            size = end_addr - start_addr

            data = hex_file.tobinarray(start=start_addr, size=size)
            read_data = board.target.readBlockMemoryUnaligned8(start_addr, size)

            assert (self.byte_lists_equal(data, read_data)), 'Verify failed. Data readback from memory does not match data written.'
예제 #20
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);
예제 #21
0
파일: utils.py 프로젝트: sg-/mbed-os
def intelhex_offset(filename, offset):
    """Load a hex or bin file at a particular offset"""
    _, inteltype = splitext(filename)
    ih = IntelHex()
    if inteltype == ".bin":
        ih.loadbin(filename, offset=offset)
    elif inteltype == ".hex":
        ih.loadhex(filename)
    else:
        raise ToolException("File %s does not have a known binary file type"
                            % filename)
    return ih
예제 #22
0
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"]
예제 #23
0
 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])
예제 #24
0
파일: csv2hex.py 프로젝트: icyd/MOD_TL901
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')
예제 #25
0
파일: main.py 프로젝트: molejar/pyKBoot
def write(addr, offset, file):

    if file.lower().endswith('.bin'):
        with open(file, "rb") as f:
            data = f.read()
            f.close()
    elif file.lower().endswith('.hex'):
        ihex = IntelHex()
        try:
            ihex.loadfile(file, format='hex')
        except Exception as e:
            raise Exception('Could not read from file: %s \n [%s]' % (file, str(e)))
        else:
            dhex = ihex.todict()
            data = bytearray([0xFF]*(max(dhex.keys()) + 1))
            for i, val in dhex.items():
                data[i] = val
    else:
        srec = kboot.SRecFile()
        try:
            srec.open(file)
        except Exception as e:
            raise Exception('Could not read from file: %s \n [%s]' % (file, str(e)))
        else:
            data = srec.data
            if addr ==  0:
                addr = srec.start_addr

    if offset < len(data):
        data = data[offset:]

    click.echo('\n Writing into MCU memory, please wait !\n')

    # Read Flash Sector Size of connected MCU
    flashSectorSize = KBOOT.get_property(kboot.Property.FlashSectorSize)['raw_value']

    # Align Erase Start Address and Len to Flash Sector Size
    saddr = (addr & ~(flashSectorSize - 1))
    slen = (len(data) & ~(flashSectorSize - 1))
    if (len(data) % flashSectorSize) > 0:
        slen += flashSectorSize

    # Erase specified region in MCU Flash memory
    KBOOT.flash_erase_region(saddr, slen)

    # Write data into MCU Flash memory
    KBOOT.write_memory(addr, data)

    # Disconnect KBoot device
    KBOOT.disconnect()

    click.secho(" Done Successfully. \n")
예제 #26
0
  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)
예제 #27
0
    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')
예제 #28
0
    def from_eep_file(cls, eep_file_name):
        """Create an ErrorLog instance with the content from the EEPROM-file."""
        hex_file = IntelHex()
        hex_file.fromfile(eep_file_name, format='hex')

        log = cls()
        for addr in range(ErrorLog._START_ADDRESS, ErrorLog._END_ADDRESS, ErrorMessage.size()):
            data = hex_file.gets(addr, ErrorMessage.size())

            error_message = ErrorMessage.from_bytes(data)
            if error_message:
                log.append(error_message)

        return log
예제 #29
0
def hex_crc(args):
    ihex_file = args.file[0]
    programSize = int(args.size[0])

    from intelhex import IntelHex

    ih = IntelHex()
    ih.loadfile(ihex_file, format="hex")
    ih.padding = 0xFF
    bin = ih.tobinarray(size=programSize)
    crc = stm32_crc32_bytes(0xffffffff, bin)
    print(hex(crc))

    return 0
예제 #30
0
    def verify(self, args):
        from intelhex import IntelHex
        nrf = SetupCommand(args)

        hex_file = IntelHex(args.file)
        for segment in hex_file.segments():
            start_addr, end_addr = segment
            size = end_addr - start_addr

            data = hex_file.tobinarray(start=start_addr, size=size)
            read_data = nrf.api.read(start_addr, size)

            assert (self.byte_lists_equal(data, read_data)), 'Verify failed. Data readback from memory does not match data written.'

        nrf.cleanup()
예제 #31
0
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')
예제 #32
0
파일: regions.py 프로젝트: yyunju80/QMesh
def _fill_header(region_list, current_region):
    """Fill an application header region

    This is done it three steps:
     * Fill the whole region with zeros
     * Fill const, timestamp and size entries with their data
     * Fill the digests using this header as the header region
    """
    region_dict = {r.name: r for r in region_list}
    header = IntelHex()
    header.puts(current_region.start, b'\x00' * current_region.size)
    start = current_region.start
    for member in current_region.filename:
        _, type, subtype, data = member
        if type == "const":
            fmt = {
                "8le": ">B", "16le": "<H", "32le": "<L", "64le": "<Q",
                "8be": "<B", "16be": ">H", "32be": ">L", "64be": ">Q"
            }[subtype]
            header.puts(start, struct.pack(fmt, integer(data, 0)))
        elif type == "timestamp":
            fmt = {"32le": "<L", "64le": "<Q",
                   "32be": ">L", "64be": ">Q"}[subtype]
            header.puts(start, struct.pack(fmt, int(time())))
        elif type == "size":
            fmt = {"32le": "<L", "64le": "<Q",
                   "32be": ">L", "64be": ">Q"}[subtype]
            size = sum(_real_region_size(region_dict[r]) for r in data)
            header.puts(start, struct.pack(fmt, size))
        elif type == "digest":
            if data == "header":
                ih = header[:start]
            else:
                ih = intelhex_offset(
                    region_dict[data].filename,
                    offset=region_dict[data].start
                )
            if subtype.startswith("CRCITT32"):
                fmt = {"CRCITT32be": ">L", "CRCITT32le": "<L"}[subtype]
                crc_val = zlib.crc32(ih.tobinarray()) & 0xffffffff
                header.puts(start, struct.pack(fmt, crc_val))
            elif subtype.startswith("SHA"):
                if subtype == "SHA256":
                    hash = hashlib.sha256()
                elif subtype == "SHA512":
                    hash = hashlib.sha512()
                hash.update(ih.tobinarray())
                header.puts(start, hash.digest())
        start += Config.header_member_size(member)
    return header
예제 #33
0
파일: regions.py 프로젝트: yyunju80/QMesh
def merge_region_list(
        region_list,
        destination,
        notify,
        padding=b'\xFF',
        restrict_size=None
):
    """Merge 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 gaps with
    restrict_size - check to ensure a region fits within the given size
    """
    merged = IntelHex()
    _, format = splitext(destination)
    notify.info("Merging Regions")
    # Merged file list: Keep track of binary/hex files that we have already
    # merged. e.g In some cases, bootloader may be split into multiple parts,
    # but all internally referring to the same bootloader file.
    merged_list = []

    for region in region_list:
        if region.active and not region.filename:
            raise ToolException(
                "Active region has no contents: No file found."
            )
        if isinstance(region.filename, list):
            header_basename, _ = splitext(destination)
            header_filename = header_basename + "_header.hex"
            _fill_header(region_list, region).tofile(
                header_filename, format='hex'
            )
            region = region._replace(filename=header_filename)
        if region.filename and (region.filename not in merged_list):
            notify.info("  Filling region %s with %s" % (
                region.name, region.filename
            ))
            part = intelhex_offset(region.filename, offset=region.start)
            part.start_addr = None
            # Normally, we assume that part.maxddr() can be beyond
            # end of rom. If the size is restricted with config, don't
            # allow this.
            if restrict_size is not None:
                part_size = (part.maxaddr() - part.minaddr()) + 1
                if part_size > region.size:
                    raise ToolException(
                        "Contents of region %s does not fit" % region.name
                    )
            merged_list.append(region.filename)
            merged.merge(part)
        elif region.filename in merged_list:
            notify.info(
                "  Skipping %s as it is merged previously" % (region.name)
            )

    # Hex file can have gaps, so no padding needed. While other formats may
    # need padding. Iterate through segments and pad the gaps.
    if format != ".hex":
        # begin patching from the end of the first segment
        _, begin = merged.segments()[0]
        for start, stop in merged.segments()[1:]:
            pad_size = start - begin
            merged.puts(begin, padding * pad_size)
            begin = stop + 1

    if not exists(dirname(destination)):
        makedirs(dirname(destination))
    notify.info("Space used after regions merged: 0x%x" %
                (merged.maxaddr() - merged.minaddr() + 1))
    merged.tofile(destination, format=format.strip("."))
예제 #34
0
    def program_file(self, name):
        def parseField(f):
            return base64.b64decode(helpers.from_websafe(f).encode())

        def isCorrectVersion(current, target):
            """current is tuple (x,y,z).  target is string '>=x.y.z'.
            Return True if current satisfies the target expression.
            """
            if "=" in target:
                target = target.split("=")
                assert target[0] in [">", "<"]
                target_num = [int(x) for x in target[1].split(".")]
                assert len(target_num) == 3
                comp = target[0] + "="
            else:
                assert target[0] in [">", "<"]
                target_num = [int(x) for x in target[1:].split(".")]
                comp = target[0]
            target_num = ((target_num[0] << 16) | (target_num[1] << 8) |
                          (target_num[2] << 0))
            current_num = (current[0] << 16) | (current[1] << 8) | (
                current[2] << 0)
            return eval(str(current_num) + comp + str(target_num))

        firmware_file_data = None
        if name.lower().endswith(".json"):
            firmware_file_data = json.loads(open(name, "r").read())
            fw = parseField(firmware_file_data["firmware"])
            sig = None

            if "versions" in firmware_file_data:
                current = (0, 0, 0)
                try:
                    current = self.bootloader_version()
                except CtapError as e:
                    if e.code == CtapError.ERR.INVALID_COMMAND:
                        pass
                    else:
                        raise (e)
                # for v in firmware_file_data["versions"]:
                #     if not isCorrectVersion(current, v):
                #         print("using signature version", v)
                #         sig = parseField(firmware_file_data["versions"][v]["signature"])
                #         break
                sig = parseField(
                    firmware_file_data["versions"][">2.5.3"]["signature"])

                if sig is None:
                    raise RuntimeError(
                        "Improperly formatted firmware file.  Could not match version."
                    )
            else:
                sig = parseField(firmware_file_data["signature"])

            ih = IntelHex()
            tmp = tempfile.NamedTemporaryFile(delete=False)
            tmp.write(fw)
            tmp.seek(0)
            tmp.close()
            ih.fromfile(tmp.name, format="hex")
        else:
            if not name.lower().endswith(".hex"):
                print('Warning, assuming "%s" is an Intel Hex file.' % name)
            sig = None
            ih = IntelHex()
            ih.fromfile(name, format="hex")

        if self.exchange == self.exchange_hid:
            chunk = 2048
        else:
            chunk = 240

        seg = ih.segments()[0]
        size = seg[1] - seg[0]
        total = 0
        t1 = time.time() * 1000
        print("erasing firmware...")
        for i in range(seg[0], seg[1], chunk):
            s = i
            e = min(i + chunk, seg[1])  # type: ignore
            data = ih.tobinarray(start=i, size=e - s)
            self.write_flash(i, data)
            total += chunk
            progress = total / float(size) * 100
            sys.stdout.write("updating firmware %.2f%%...\r" % progress)
        sys.stdout.write("updated firmware 100%             \r\n")
        t2 = time.time() * 1000
        print("time: %.2f s" % ((t2 - t1) / 1000.0))

        if sig is None:
            sig = b"A" * 64

        success = False
        if self.do_reboot:
            try:
                print("bootloader is verifying signature...")
                print(f"Trying with {sig.hex()}")
                self.verify_flash(sig)
                print("...pass!")
                success = True
            except CtapError as e:
                if e.code != 0x27:
                    raise
                print("...error!")

        # if not success:
        #     for v in firmware_file_data["versions"]:
        #         sig = v["signature"]
        #         print(f'Trying with {sig}')
        #         self.verify_flash(sig)

        return sig
예제 #35
0
    def __init__(self, path):
        """
        Read a firmware file and store its data ready for device programming.

        This class will try to guess the file type if python-magic is available.

        If python-magic indicates a plain text file, and if IntelHex is
        available, then the file will be treated as one of Intel HEX format.

        In all other cases, the file will be treated as a raw binary file.

        In both cases, the file's contents are stored in bytes for subsequent
        usage to program a device or to perform a crc check.

        Parameters:
            path -- A str with the path to the firmware file.

        Attributes:
            bytes: A bytearray with firmware contents ready to send to the device
        """
        self._crc32 = None
        firmware_is_hex = False

        if have_magic:
            file_type = bytearray(magic.from_file(path, True))

            #from_file() returns bytes with PY3, str with PY2. This comparison
            #will be True in both cases"""
            if file_type == b'text/plain':
                firmware_is_hex = True
                mdebug(5, "Firmware file: Intel Hex")
            elif file_type == b'application/octet-stream':
                mdebug(5, "Firmware file: Raw Binary")
            else:
                error_str = "Could not determine firmware type. Magic " \
                            "indicates '%s'" % (file_type)
                raise CmdException(error_str)
        else:
            if os.path.splitext(path)[1][1:] in self.HEX_FILE_EXTENSIONS:
                firmware_is_hex = True
                mdebug(5, "Your firmware looks like an Intel Hex file")
            else:
                mdebug(5,
                       "Cannot auto-detect firmware filetype: Assuming .bin")

            mdebug(
                10, "For more solid firmware type auto-detection, install "
                "python-magic.")
            mdebug(10, "Please see the readme for more details.")

        if firmware_is_hex:
            if have_hex_support:
                self.bytes = bytearray(IntelHex(path).tobinarray())
                return
            else:
                error_str = "Firmware is Intel Hex, but the IntelHex library " \
                            "could not be imported.\n" \
                            "Install IntelHex in site-packages or program " \
                            "your device with a raw binary (.bin) file.\n" \
                            "Please see the readme for more details."
                raise CmdException(error_str)

        with open(path, 'rb') as f:
            self.bytes = bytearray(f.read())
예제 #36
0
                    help="output file name",
                    default="output.bin")
args = parser.parse_args()

if not args.input:
    print("Input file must be specified")

if os.path.exists(args.output):
    try:
        os.path.delete(args.output)
    except FileError as e:
        print("File error ({0}): {1}".format(e.errno, e.strerror))
    except:
        print("Filesystem Error!")

try:
    if (os.path.exists(args.input) == False):
        errorHandler("Application file missing!")

    filename, file_ext = os.path.splitext(args.input)
    #convert hex to bin
    if file_ext == ".hex":
        print("Convert HEX to Binary: " + args.input)
        ih = IntelHex(args.input)
        ih.tobinfile(args.output)
    else:
        print("File is not HEX type; aborting!")
except FileError as e:
    print("File error ({0}): {1}".format(e.errno, e.strerror))
except:
    errorHandler("Filesystem Error!")
예제 #37
0
파일: target.py 프로젝트: nanofan321/aa
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_WITH_COMPILE_API_LIST
    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)
예제 #38
0
    for patch_name in PARAMETERIZED_PATCHES:
        patch_data = PARAMETERIZED_PATCHES[patch_name]
        parser.add_argument('--%s' % patch_name,
                            help=patch_data['description'],
                            type=int,
                            nargs=patch_data['params'])

    parser.add_argument(
        '--patch',
        help=
        'Performs an arbitrary memory patch. Specify address, then bytes. Can be specified multiple times.',
        action='append',
        nargs='+')

    args = parser.parse_args()

    ih = IntelHex()
    ih.loadhex(args.input_file)

    do_patches(ih, args)
    do_parameterized_patches(ih, args)
    do_arbitrary_patches(ih, args)

    # backup_file(args.input_file)
    sio = StringIO()
    ih.write_hex_file(sio)
    output = sio.getvalue()
    output = output.encode('utf-8').replace(b'\r\n', b'\n')
    with open(args.output_file, 'wb') as f:
        f.write(output)
예제 #39
0
def ReadProgram(prog_file):
    prog_hex = IntelHex(prog_file)

    if (len(prog_hex.tobinarray()) % 256 != 0):
        raise Exception("ReadProgram: wrong program file size: " + prog_file)
    return prog_hex
예제 #40
0
    def merge_secure(t_self, resources, ns_elf, ns_hex):
        t_self.notify.info("Merging non-secure image with secure image")
        configured_secure_image_filename = t_self.target.secure_image_filename
        t_self.notify.info("Non-secure elf image %s" % ns_elf)
        t_self.notify.info("Non-secure hex image %s" % ns_hex)
        t_self.notify.info("Finding secure image %s" % configured_secure_image_filename)
        s_hex = find_secure_image(
            t_self.notify,
            resources,
            ns_hex,
            configured_secure_image_filename,
            FileType.HEX
        )
        t_self.notify.info("Found secure image %s" % s_hex)

        _, ext = os.path.splitext(s_hex)
        if ext != ".hex":
            t_self.notify.debug("Secure image %s must be in Intel HEX format" % s_hex)
            return
        if not os.path.isfile(s_hex):
            t_self.notify.debug("Secure image %s must be regular file" % s_hex)
            return

        ns_main, ext = os.path.splitext(ns_hex)
        if ext != ".hex":
            t_self.notify.debug("Non-secure image %s must be in Intel HEX format" % s_hex)
            return
        if not os.path.isfile(ns_hex):
            t_self.notify.debug("Non-secure image %s must be regular file" % s_hex)
            return

        # Keep original non-secure before merge with secure
        ns_nosecure_hex = ns_main + "_no-secure-merge" + ext
        t_self.notify.info("Keep no-secure-merge image %s" % ns_nosecure_hex)
        shutil.copy2(ns_hex, ns_nosecure_hex)

        # Merge secure and non-secure and save to non-secure (override it)
        from intelhex import IntelHex
        s_ih = IntelHex()
        s_ih.loadhex(s_hex)
        ns_ih = IntelHex()
        ns_ih.loadhex(ns_hex)
        ns_ih.start_addr = None
        s_ih.merge(ns_ih)
        s_ih.tofile(ns_hex, 'hex')
예제 #41
0
파일: image.py 프로젝트: yyunju80/QMesh
 def load(self, path):
     ih = IntelHex(path)
     return ih.tobinarray(), ih.minaddr()
예제 #42
0
    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
        sd_with_offsets = t_self.target.EXPECTED_SOFTDEVICES_WITH_OFFSETS
        for softdevice_and_offset_entry in sd_with_offsets:
            for hexf in resources.get_file_paths(FileType.HEX):
                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.get_file_paths(FileType.HEX):
                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)
            sdh.start_addr = None
            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)
            blh.start_addr = None
            binh.merge(blh)

        with open(binf.replace(".bin", ".hex"), "w") as fileout:
            binh.write_hex_file(fileout, write_start_addr=False)
예제 #43
0
    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')
예제 #44
0
def main():
    if len(sys.argv) < 3:
        print("Switches a CCG2 device to another")
        print(
            "Usage: %s <hex file> <device name ie. CYPD2104-20FNXIT or CYPD2122-20FNXIT>"
        )
        sys.exit()

    hex_file = sys.argv[1]
    devicetype = sys.argv[2]

    if "CYPD2104-20FNXIT" in devicetype:
        deviceid = int(CYPD2104_20FNXIT, 16)
    elif "CYPD2122-20FNXIT" in devicetype:
        deviceid = int(CYPD2122_20FNXIT, 16)
    else:
        print("%s is not a recognized device type" % devicetype)
        sys.exit()

    if not os.path.isfile(hex_file):
        print("hex file path %s does not exist. Exiting..." % (hex_file))
        sys.exit()
    else:
        print("hex file: " + hex_file)

    with open(hex_file, mode='r') as hfp:
        hf = hfp.read()

        # break off hex file from meta data
        hexdatas = hf.split(meta_identifier, 1)
        hexdata = hexdatas[0]
        metadata = meta_identifier + hexdatas[1]
        #print(metadata)

    # can't do it with ihex without a file, make one
    with open("tmp_123456", mode='w') as tfp:
        tfp.write(hexdata)

    ih = IntelHex("tmp_123456")
    b = ih.tobinstr()

    # calculate the binary checksum
    csum = calcChecksum(b)
    csum_short = csum & 0xFFFF

    # Create the device record meta data
    DiDR = createDeviceIdRecord(csum, deviceid)

    # no need to create it since we already have it stored in their method
    hexstr = hexdata
    """
    # create the hex file string
    sio = StringIO()
    ihex = IntelHex()
    ihex.start_addr = None
    ihex.padding = 0x00
    
    # ihex failed to decode a character, so doing it one by one
    for i, c in enumerate(b):
        ihex[i] = c
    
    # write out the ihex string 
    ihex.write_hex_file( sio )
    hexstr = sio.getvalue()
    sio.close()
    
    # remove the EOF so we can add the cypress metadata
    hexstr = hexstr[:hexstr.rfind(ihex_eof)]
    """

    # metadata stoarge
    suffix = []

    # add checksum short
    suffix.append(":0200000490303A")
    suffix.append(makedataline(csum_short.to_bytes(2, byteorder='big'), 0, 0))

    # metadata
    suffix.append(":0200000490402A")
    if FLASH_PROTECT:
        suffix.append(
            ":20000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7F80"
        )
    else:
        suffix.append(
            ":200000000000000000000000000000000000000000000000000000000000000000000000E0"
        )

    # Device id record
    suffix.append(":0200000490501A")
    suffix.append(makedataline(DiDR, 0, 0))

    # chip level protection
    suffix.append(":0200000490600A")
    if CHIP_PROTECT:
        suffix.append(":0100000002FD")
    else:
        suffix.append(":0100000001FE")

    # EOF
    suffix.append(ihex_eof)

    tail = '\n'.join(suffix)

    hexstr = hexstr + tail.upper()

    fn = devicetype + "_converted.hex"
    with open(fn, mode='w') as ofp:
        ofp.write(hexstr)
        print("device switched into %s" % (fn))
def combine(bootloader_fn, app_fn, app_addr, hdr_addr, bootloader_addr,
            output_fn, version, no_bootloader):
    # read bootloader
    bootloader_format = bootloader_fn.split('.')[-1]
    bootloader = IntelHex()
    if not no_bootloader:
        if bootloader_format == 'hex':
            bootloader.fromfile(bootloader_fn, bootloader_format)
        elif bootloader_format == 'bin':
            bootloader.loadbin(bootloader_fn, bootloader_addr)
        else:
            print('Bootloader format can only be .bin or .hex')
            exit(-1)

    # read application
    app_format = app_fn.split('.')[-1]
    app = IntelHex()
    if app_format == 'hex':
        app.fromfile(app_fn, app_format)
    elif app_format == 'bin':
        app.loadbin(app_fn, app_addr)
    else:
        print('Application format can only be .bin or .hex')
        exit(-1)

    # create firmware header
    header = IntelHex()
    fw_header = create_header(app.tobinstr(), version)
    header.puts(hdr_addr, fw_header)

    # combine
    output_format = output_fn.split('.')[-1]
    output = IntelHex()
    if not no_bootloader:
        print("Writing bootloader to address 0x%08x-0x%08x." %
              (bootloader.addresses()[0], bootloader.addresses()[-1]))
        output.merge(bootloader, overlap='error')
    print("Writing header to address 0x%08x-0x%08x." %
          (header.addresses()[0], header.addresses()[-1]))
    output.merge(header, overlap='error')
    print("Writing application to address 0x%08x-0x%08x." %
          (app.addresses()[0], app.addresses()[-1]))
    output.merge(app, overlap='error')

    # write output file
    output.tofile(output_fn, format=output_format)
예제 #46
0
파일: targets.py 프로젝트: flyleaf91/mbed
    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')
예제 #47
0
#!/bin/env python3

# Copyright (C) 2015 Herbert Poetzl

import sys
import serial
import struct

from intelhex import IntelHex
from time import sleep
from icsp import *

tty = "/dev/ttyPS1"

ih = IntelHex(sys.argv[1])
ih.padding = 0xFF

def ih_data(ih, addr, count=32):
    data = []
    mask = 0xFFFF
    for n in range(count):
        l, h = ih[(addr + n)*2], ih[(addr + n)*2 + 1]
        val = (h << 8)|l
        mask &= val
        data.append(val)
    return data, mask

ser = serial.Serial(
    port = tty,
    baudrate = 10000000,
    bytesize = serial.EIGHTBITS,
예제 #48
0
    return h


port = sys.argv[1]
speed = int(sys.argv[2])
file = sys.argv[3]
size = int(sys.argv[4], base=16)

print(port)
print(speed)
print(file)
print(size)

iterations = round(size / 128)

hex = IntelHex()

data = []

boot = MyBoot(port, speed)
boot.open()

for i in range(0, iterations):
    start = i * 128
    print(start)
    boot.setAddr(start)
    print(boot.getAddr())
    datan = list(boot.readData(128))
    data = data + datan

boot.close()
예제 #49
0
def append_validation_data(signature, input_file, public_key, offset, output_file, 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("Incorrect offset, must be bigger than %x" % 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_file)
예제 #50
0
def flashHex(target, filename):
    '''
    flash a hex file to nRF51822
    '''
    ihex = IntelHex(filename)
    addresses = ihex.addresses()
    nbytes = len(addresses)
    addresses.sort()

    start = time()

    target.halt()

    if addresses[0] == 0:
        logging.info("Erase All")
        target.writeMemory(NVMC_CONFIG, 2)
        target.writeMemory(NVMC_ERASEALL, 1)
        while target.readMemory(NVMC_READY) == 0:
            pass

    logging.info("Prepare to write")
    target.writeMemory(NVMC_CONFIG, 1)
    while target.readMemory(NVMC_READY) == 0:
        pass

    nbytes_align32 = nbytes & ~(32 - 1)
    for i in range(0, nbytes_align32, 32):
        if (addresses[i] + 31) == addresses[i + 31]:
            start_address = addresses[i]
            # read 32 data bytes
            bytes = ihex.tobinarray(start=start_address, size=32)
            target.writeBlockMemoryUnaligned8(start_address, bytes)

            bytes_readback = target.readBlockMemoryUnaligned8(
                start_address, 32)
            for j in range(len(bytes)):
                if (bytes[j] != bytes_readback[j]):
                    logging.info("Write: error at 0x%X - 0x%X | 0x%X",
                                 start_address + j, bytes[j],
                                 bytes_readback[j])
                    raise Exception("Verify Error")

        else:
            # data always 4 bytes aligned
            for j in range(0, 32, 4):
                start_address = addresses[i + j]
                bytes = ihex.tobinarray(start=start_address, size=4)
                target.writeBlockMemoryUnaligned8(start_address, bytes)

    for i in range(nbytes_align32, nbytes, 4):
        start_address = addresses[i]
        bytes = ihex.tobinarray(start=start_address, size=4)
        target.writeBlockMemoryUnaligned8(start_address, bytes)

    target.writeMemory(NVMC_CONFIG, 0)
    while target.readMemory(NVMC_READY) == 0:
        pass

    end = time()
    print("%f kbytes flashed in %f seconds ===> %f kbytes/s" %
          (nbytes / 1000, end - start, nbytes / (1000 * (end - start))))
예제 #51
0
parser.add_argument(
    "-u",
    "--uuid",
    help=
    "The 12-byte UUID of the device. This is a hexadecimal number of the format"
    "00000000-00000000-00000000")
parser.add_argument(
    "-s",
    "--serial-number",
    help=
    "The 12-digit serial number of the device. This is a string consisting of 12 upper case hexadecimal digits as displayed in lsusb"
    "example: 385F324D3037")
args = parser.parse_args()

# load hex file
hexfile = IntelHex(args.file)

#print("Contiguous segments in hex file:")
#for start, end in hexfile.segments():
#    print(" {:08X} to {:08X}".format(start, end - 1))

if args.uuid != None:
    serial_number = uuid_to_serial(*str_to_uuid(args.uuid))
elif args.serial_number != None:
    serial_number = args.serial_number
else:
    serial_number = None

app_cancellation_token = threading.Event()
find_odrive_cancellation_token = threading.Event()
try:
예제 #52
0
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())
예제 #53
0
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')
예제 #54
0
    def run(self):

        # Create prompt objects.
        fw_update_prompt = \
            UpdatePrompt(
                         title='Firmware Update',
                         actions=[update_button, close_button],
                         update_callback=self.manage_firmware_updates,
                        )

        console_outdated_prompt = \
            UpdatePrompt(
                         title="Console Outdated",
                         actions=[close_button],
                        )

        # Get index that contains file URLs and latest
        # version strings from Swift Nav's website.
        try:
            f = urlopen(INDEX_URL)
            index = jsonload(f)
            f.close()
        except URLError:
            self.write(
                "\nError: Failed to download latest file index from Swift Navigation's website (%s). Please visit our website to check that you're running the latest Piksi firmware and Piksi console.\n\n"
                % INDEX_URL)
            return

        # Make sure index contains all keys we are interested in.
        try:
            index['piksi_v2.3.1']['stm_fw']['version']
            index['piksi_v2.3.1']['stm_fw']['url']
            index['piksi_v2.3.1']['nap_fw']['version']
            index['piksi_v2.3.1']['nap_fw']['url']
            index['piksi_v2.3.1']['console']['version']
        except KeyError:
            self.write(
                "\nError: Index downloaded from Swift Navigation's website (%s) doesn't contain all keys. Please contact Swift Navigation.\n\n"
                % INDEX_URL)
            return

        # Make sure settings contains Piksi firmware version strings.
        try:
            self.settings['system_info']['firmware_version'].value
            self.settings['system_info']['nap_version'].value
        except:
            self.write(
                "\nError: Settings received from Piksi don't contain firmware version keys. Please contact Swift Navigation.\n\n"
                % INDEX_URL)
            return

        # Assign text to UpdatePrompt's
        fw_update_prompt.text = \
            "Local STM Version :\n\t%s\n" % \
                self.settings['system_info']['firmware_version'].value + \
            "Newest STM Version :\n\t%s\n\n" % \
                index['piksi_v2.3.1']['stm_fw']['version'] + \
            "Local SwiftNAP Version :\n\t%s\n" % \
                self.settings['system_info']['nap_version'].value + \
            "Newest SwiftNAP Version :\n\t%s\n\n" % \
                index['piksi_v2.3.1']['nap_fw']['version']

        console_outdated_prompt.text = \
            "Your Console is out of date and may be incompatible\n" + \
            "with current firmware. We highly recommend upgrading\n" + \
            "to ensure proper behavior.\n\n" + \
            "Please visit http://download.swift-nav.com to\n" + \
            "download the newest version.\n\n" + \
            "Local Console Version :\n\t" + \
                CONSOLE_VERSION + \
            "\nNewest Console Version :\n\t" + \
                index['piksi_v2.3.1']['console']['version'] + "\n"

        # Does local version match latest from website?
        local_fw_version = parse_version(
            self.settings['system_info']['firmware_version'].value)
        remote_fw_version = parse_version(
            index['piksi_v2.3.1']['stm_fw']['version'])
        self.stm_fw_outdated = remote_fw_version > local_fw_version

        local_nap_version = parse_version(
            self.settings['system_info']['nap_version'].value)
        remote_nap_version = parse_version(
            index['piksi_v2.3.1']['nap_fw']['version'])
        self.nap_fw_outdated = remote_nap_version > local_nap_version

        local_console_version = parse_version(CONSOLE_VERSION)
        remote_console_version = parse_version(
            index['piksi_v2.3.1']['console']['version'])
        self.console_outdated = remote_console_version > local_console_version

        # Get firmware files from Swift Nav's website.
        self.nap_ihx = None
        if self.nap_fw_outdated:
            try:
                f = urlopen(index['piksi_v2.3.1']['nap_fw']['url'])
                self.nap_ihx = IntelHex(f)
                f.close()
            except URLError:
                self.write(
                    "\nError: Failed to download latest Piksi SwiftNAP firmware from Swift Navigation's website (%s). Please visit our website to check that you're running the latest firmware.\n"
                    % index['piksi_v2.3.1']['nap_fw']['url'])

        self.stm_ihx = None
        if self.stm_fw_outdated:
            try:
                f = urlopen(index['piksi_v2.3.1']['stm_fw']['url'])
                self.stm_ihx = IntelHex(f)
                f.close()
            except URLError:
                self.write(
                    "\nError: Failed to download latest Piksi STM firmware from Swift Navigation's website (%s). Please visit our website to check that you're running the latest firmware.\n"
                    % index['piksi_v2.3.1']['stm_fw']['url'])

        # Prompt user to update firmware(s). Only update if firmware was
        # successfully downloaded. If both are out of date, only allow
        # update if we successfully downloaded both files.
        if (self.stm_fw_outdated and self.stm_ihx and not self.nap_fw_outdated) or \
            (self.nap_fw_outdated and self.nap_ihx and not self.stm_fw_outdated) or \
             (self.stm_fw_outdated and self.stm_ihx and \
               self.nap_fw_outdated and self.nap_ihx):
            fw_update_prompt.run()

        # For timing aesthetics between windows popping up.
        sleep(0.5)

        # Check if console is out of date and notify user if so.
        if self.console_outdated:
            console_outdated_prompt.run()
예제 #55
0
                try:
                    address = int(address, 0) & 0xFFFFFFFF
                except ValueError:
                    print("Address %s invalid." % address)
                    sys.exit(1)
                if not os.path.isfile(binfile):
                    print("Unreadable file '%s'." % binfile)
                    sys.exit(1)
                target.append({
                    'address': address,
                    'data': open(binfile, 'rb').read()
                })

        if options.hexfiles:
            for hex in options.hexfiles:
                ih = IntelHex(hex)
                address = ih.minaddr()
                data = ih.tobinstr()
                try:
                    address = address & 0xFFFFFFFF
                except ValueError:
                    print("Address %s invalid." % address)
                    sys.exit(1)
                target.append({'address': address, 'data': data})

        outfile = args[0]
        device = DEFAULT_DEVICE
        if options.device:
            device = options.device
        try:
            v, d = [int(x, 0) & 0xFFFF for x in device.split(':', 1)]
예제 #56
0
                        nargs=1,
                        dest="serial",
                        help="set product serial dword",
                        required=False)
    parser.add_argument("-v,--version",
                        nargs=1,
                        dest="version",
                        help="set product version dword",
                        required=False)
    args = parser.parse_args()

    if not os.path.isfile(args.hex_file[0]):
        print '==> error: gboot image could not be opened or does not exist.'
        sys.exit(1)
    else:
        ih = IntelHex(args.hex_file[0])

    # unimplemented in gflash (TODO: fix or remove)
    if args.config:
        print '==> info: update config item at offset 0x%04x' % (
            GBOOT_CONFIG_OFFSET)
        config_value = struct.pack('<L', int(args.config[0], 16))
        write_hex_entry(ih, config_value, GBOOT_CONFIG_OFFSET)

    if args.ext_info:
        print '==> info: update ext info item at offset 0x%04x' % (
            GBOOT_EXT_INFO_OFFSET)
        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:
예제 #57
0
        opts, args = getopt.gnu_getopt(argv, 'hv', ['help', 'version'])

        for o, a in opts:
            if o in ('-h', '--help'):
                print(USAGE)
                return 0
            elif o in ('-v', '--version'):
                print(VERSION)
                return 0

    except getopt.GetoptError, e:
        sys.stderr.write(str(e) + "\n")
        sys.stderr.write(USAGE + "\n")
        return 1

    if len(args) != 2:
        sys.stderr.write("ERROR: You should specify 2 files to diff.\n")
        sys.stderr.write(USAGE + "\n")
        return 1

    fname1, fname2 = args

    from intelhex import IntelHex, diff_dumps
    ih1 = IntelHex(fname1)
    ih2 = IntelHex(fname2)
    diff_dumps(ih1, ih2, name1=fname1, name2=fname2)


if __name__ == '__main__':
    sys.exit(main())
예제 #58
0
파일: image.py 프로젝트: yyunju80/QMesh
 def save(self, path):
     h = IntelHex()
     h.frombytes(bytes=self.payload, offset=self.base_addr)
     h.tofile(path, 'hex')
예제 #59
0
from intelhex import IntelHex

FLASH_BASE = 0x0
FLASH_SIZE = 0x20000

hex = IntelHex(r"noboot.hex")
bin = hex.tobinarray(start=FLASH_BASE, size=FLASH_SIZE)

with open("firmware.tcl", "w") as f:
    f.write("set FIRMWARE {")
    column = 0
    for i in range(FLASH_SIZE // 4):
        word = bin[4 * i] | (bin[4 * i + 1] << 8) | (bin[4 * i + 2] << 16) | (
            bin[4 * i + 3] << 24)
        if column == 0:
            text = f"\n\t0x{word:08X}"
        else:
            text = f" 0x{word:08X}"
        column = (column + 1) % 16
        f.write(text)
    f.write("\n}\n")
예제 #60
0

def getData(importedhex, startAddress, Size):
    retstr = ""
    for index in range(Size):
        retstr += str(importedhex[startAddress + index])
        if index + 1 < Size:
            retstr += (',')
    return retstr


def createArrayStr(importedhex, arrayName, startAddress, Size):
    retstr = TYPEDEF + ' ' + arrayName + '[] ' + OPENARRAY + getData(
        hexDict, startAddress, Size) + CLOSEARRAY
    return retstr


f = open(filename, mode='w')
importedHexFile = IntelHex(inputFile)

hexDict = importedHexFile.todict()
print(hexDict)
f.write("hex file converted from " + inputFile + "\n")
for memoryIndex in range(len(names)):

    f.write(
        createArrayStr(hexDict, names[memoryIndex], locations[memoryIndex],
                       datasizes[memoryIndex]))

f.close()