def mergeSAMD() : bootHex = IntelHex(sys.argv[2]) appHex = IntelHex(sys.argv[3]) combinedHex = IntelHex() # Insert the bootloader in the first 8kB for i in bootHex.addresses() : combinedHex[i] = bootHex[i] # Insert the application in the remaining 120kB for i in appHex.addresses() : combinedHex[i] = appHex[i] # Write to the combined hex file combinedHex.tofile(sys.argv[4], 'hex')
def _compute_crc(hex_file_path): # Read in hex file new_hex_file = IntelHex() new_hex_file.padding = 0xFF new_hex_file.fromfile(hex_file_path, format='hex') # Get the starting and ending address addresses = new_hex_file.addresses() addresses.sort() start_end_pairs = list(_ranges(addresses)) regions = len(start_end_pairs) assert regions == 1, ("Error - only 1 region allowed in " "hex file %i found." % regions) start, end = start_end_pairs[0] # Compute checksum over the range (don't include data at location of crc) size = end - start + 1 crc_size = size - 4 data = new_hex_file.tobinarray(start=start, size=crc_size) data_crc32 = binascii.crc32(data) & 0xFFFFFFFF # Grab the crc from the image embedded_crc32 = (((new_hex_file[end - 3] & 0xFF) << 0) | ((new_hex_file[end - 2] & 0xFF) << 8) | ((new_hex_file[end - 1] & 0xFF) << 16) | ((new_hex_file[end - 0] & 0xFF) << 24)) return data_crc32, embedded_crc32
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)
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))))
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)
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)
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() 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) 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))))
def _program_hex(self, path): board = self._session.board flash = board.flash hexfile = IntelHex(path) addresses = hexfile.addresses() addresses.sort() flash_builder = flash.get_flash_builder() data_list = list(ranges(addresses)) for start, end in data_list: size = end - start + 1 data = list(hexfile.tobinarray(start=start, size=size)) flash_builder.add_data(start, data) flash_builder.program(chip_erase=self._chip_erase, progress_cb=self._progress, fast_verify=self._args.trust_crc)
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)) # Ignore invalid addresses for HEX files only # Binary files (obviously) don't contain addresses # For ELF files, any metadata that's not part of the application code # will be held in a section that doesn't have the SHF_WRITE flag set try: self._loader.add_data(start, data) except ValueError as e: logging.warning("Failed to add data chunk: %s", e)
def _program_hex(self, file_obj, **kwargs): """! Intel hex file format loader""" 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)) # Ignore invalid addresses for HEX files only # Binary files (obviously) don't contain addresses # For ELF files, any metadata that's not part of the application code # will be held in a section that doesn't have the SHF_WRITE flag set try: self._loader.add_data(start, data) except ValueError as e: LOG.warning("Failed to add data chunk: %s", e)
def _download(self, addr, filename): """Downloads a binary file to the target system Args: addr: Start address where the binary file is stored filename: File name of the binary file """ import platform if platform.architecture()[0] == '64bit': filenamebuf = c_char_p(filename.encode('UTF-8')) c_addr = c_uint32(addr) self.jl.JLINK_DownloadFile(filenamebuf, c_addr) else: from intelhex import IntelHex ih = IntelHex() extension = os.path.splitext(filename)[1][1:] ih.fromfile(filename,format=extension) for (a, d) in zip(ih.addresses(), ih.tobinarray()): self.wr_mem(8, addr+a, d)
def program_prepare(): global file, transfer, attached global serial, boot_type, tx_size, start_add, length_add ih = IntelHex(file) passes = False addresses = [] sectors= [] sector = 0 sector_write = False count = 0 lastadd= 0 if tx_size: if file: print "[+] device connected and hex loaded" # Initiate the sectors list as a tempororary hold containing all possible sectors to be sent for sect in range((length_add/tx_size)+1): sectors.append([]) if(Debug):print "sectors="+str(len(sectors)) if(Debug):print sectors if(Debug):print str(len(ih.addresses())) if(Debug):print length_add # Truncate hex file to only allowed addresses for the device for add in ih.addresses(): if add >= start_add and add <= (length_add+start_add): addresses.append(add) print "[+] "+str(len(addresses))+" addresses of valid code" #Start of iteration over valid adressess for addr in addresses: if addr == (lastadd+1): # If address is sequential to previous one if count == 0: sectors[sector] = get_sector_add(sector) sector_write=True sectors[sector].append(chr(ih[addr])) #print sector count +=1 lastadd = addr #print "prev" else: # If address is unexpected if sector_write: for i in range(count,tx_size,1): sectors[sector].append(chr(0xFF)) count +=1 tmpsector= (addr-start_add)/tx_size tmpcount = int(((float(addr-start_add)/tx_size)-((addr-start_add)/tx_size))*tx_size) if len(sectors[tmpsector]) == 0: sectors[tmpsector] = get_sector_add(tmpsector) for i in range((len(sectors[tmpsector])-4), tmpcount-1,1): sectors[tmpsector].append(chr(0xFF)) sectors[tmpsector].append(chr(ih[addr])) sector_write = True sector = tmpsector count = tmpcount+1 lastadd= addr if count >= tx_size: count = 0 sector +=1 sector_write=False if sector_write: for i in range(count,tx_size,1): sectors[sector].append(chr(0xFF)) count +=1 sector_write=False transfer = [] for sects in sectors: if len(sects)-4 == tx_size: transfer.append(sects) #else: #print str(len(sects)) #print sects # Convert transfer to string bytes #print type(transfer[2][30]) for data in range(len(transfer)): #print transfer[data] tmp = ''.join(transfer[data]) transfer[data] = tmp #print transfer program()
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 has_file = args.file is not None chip_erase = None if args.chip_erase: chip_erase = True elif args.sector_erase: chip_erase = False if not has_file: if chip_erase: print("Erasing chip...") flash.init() flash.eraseAll() print("Done") elif args.sector_erase and args.address is not None: flash.init() page_addr = args.address for i in range(args.count): page_info = flash.getPageInfo(page_addr) if not page_info: break # Align page address on first time through. if i == 0: delta = page_addr % page_info.size if delta: print( "Warning: sector address 0x%08x is unaligned" % page_addr) page_addr -= delta print("Erasing sector 0x%08x" % page_addr) flash.erasePage(page_addr) page_addr += page_info.size else: print("No operation performed") return # If no format provided, use the file's extension. if not args.format: args.format = os.path.splitext(args.file)[1][1:] # 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 elif 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) else: print("Unknown file format '%s'" % args.format)
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 has_file = args.file is not None chip_erase = None if args.chip_erase: chip_erase = True elif args.sector_erase: chip_erase = False if not has_file: if chip_erase: print("Erasing chip...") flash.init() flash.eraseAll() print("Done") elif args.sector_erase and args.address is not None: flash.init() page_addr = args.address for i in range(args.count): page_info = flash.getPageInfo(page_addr) if not page_info: break # Align page address on first time through. if i == 0: delta = page_addr % page_info.size if delta: print("Warning: sector address 0x%08x is unaligned" % page_addr) page_addr -= delta print("Erasing sector 0x%08x" % page_addr) flash.erasePage(page_addr) page_addr += page_info.size else: print("No operation performed") return # If no format provided, use the file's extension. if not args.format: args.format = os.path.splitext(args.file)[1][1:] # 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 elif 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) else: print("Unknown file format '%s'" % args.format)
sys.exit(1) except: print("Fatal Error: -- FAILED parsing input hex file(s)") sys.exit(1) #print information about the input hex files print_args_info(inputFileNames, vargs.out, vargs.outbin, vargs.oadtype, vargs.imgtype, mergedHex) #Now that we have a merged hex image, lets do a bunch of arg checking #since mergedHex is an merge of all input hexes, it can be treated as an argument to the script argument_sanity_check(vargs, mergedHex) # Cut off / fill with --fill. startAddr = mergedHex.minaddr() endAddr = mergedHex.addresses()[-1] + 1 # Inclusive address if startAddr % OAD_BLOCK_SIZE: print( "Fatal Error: -- Start address 0x%X is not divisible by 16. Exiting" ) sys.exit(1) # DevMon rounds up to nearest sector. Why not, if they want to waste time and space. if vargs.round is not None: endAddr = ((endAddr + INT_FL_PG_SIZE) & ~(INT_FL_PG_SIZE - 1)) print('endAddr round', hex(endAddr)) if vargs.range is not None: if vargs.range[0] is not None: startAddr = vargs.range[0] if vargs.range[1] is not None: endAddr = vargs.range[1]
sys.exit(1) except: print("Fatal Error: -- FAILED parsing input hex file(s)") sys.exit(1) #print information about the input hex files print_args_info(inputFileNames, vargs.out, vargs.outbin, vargs.oadtype, vargs.imgtype) #Now that we have a merged hex image, lets do a bunch of arg checking #since mergedHex is an merge of all input hexes, it can be treated as an argument to the script argument_sanity_check(vargs, mergedHex) # Cut off / fill with --fill. startAddr = mergedHex.minaddr() endAddr = mergedHex.addresses()[-1] + 1 # Inclusive address if startAddr % OAD_BLOCK_SIZE: print("Fatal Error: -- Start address 0x%X is not divisible by 16. Exiting") sys.exit(1) # DevMon rounds up to nearest sector. Why not, if they want to waste time and space. if vargs.round is not None: endAddr = ((endAddr + INT_FL_PG_SIZE) & ~(INT_FL_PG_SIZE-1)) print ('endAddr round', hex(endAddr)) if vargs.range is not None: if vargs.range[0] is not None: startAddr = vargs.range[0] if vargs.range[1] is not None: endAddr = vargs.range[1] # Make sure the last address is divisible by 16
def execute(self, capability, *args, **kwargs): """! Executes capability by name @param capability Capability name @param args Additional arguments @param kwargs Additional arguments @return Capability call return value """ if not self.check_parameters(capability, *args, **kwargs): return False if not kwargs['image_path']: self.print_plugin_error("Error: image path not specified") return False if not kwargs['target_id']: self.print_plugin_error("Error: Target ID") return False target_id = kwargs['target_id'] image_path = os.path.normpath(kwargs['image_path']) with MbedBoard.chooseBoard(board_id=target_id) as board: # Performance hack! # Eventually pyOCD will know default clock speed # per target test_clock = 10000000 target_type = board.getTargetType() if target_type == "nrf51": # Override clock since 10MHz is too fast test_clock = 1000000 if target_type == "ncs36510": # Override clock since 10MHz is too fast test_clock = 1000000 # Configure link board.link.set_clock(test_clock) board.link.set_deferred_transfer(True) # Collect address, data pairs for programming program_list = [] extension = os.path.splitext(image_path)[1] if extension == '.bin': # Binary file format memory_map = board.target.getMemoryMap() rom_region = memory_map.getBootMemory() with open(image_path, "rb") as file_handle: program_data = file_handle.read() program_list.append((rom_region.start, program_data)) elif extension == '.hex': # Intel hex file format ihex = IntelHex(image_path) addresses = ihex.addresses() addresses.sort() for start, end in _enum_continguous_addr_start_end(addresses): size = end - start + 1 data = ihex.tobinarray(start=start, size=size) data = bytearray(data) program_list.append((start, data)) else: # Unsupported raise Exception("Unsupported file format %s" % extension) # Program data flash_builder = board.flash.getFlashBuilder() for addr, data in program_list: flash_builder.addData(addr, list(bytearray(data))) flash_builder.program() # Read back and verify programming was successful for addr, data in program_list: read_data = board.target.readBlockMemoryUnaligned8( addr, len(data)) read_data = bytearray(read_data) if bytes(data) != bytes(read_data): raise Exception("Flash programming error - failed to " "program address 0x%x size %s" % (addr, len(data))) # Cleanup board.uninit(resume=False) return True
from config import * # Path to hex file f = data_targetFile print(f) # Serial port name p = serialPort print(p) # Read hex file ih = IntelHex() ih.fromfile(f, format='hex') if ih.addresses()[len(ih.addresses()) - 1] > 0x7FF: a = input('The data is too large, max data is 2048 bytes, continue? y/n: ') if a != 'Y' and a != 'y': quit() with serial.Serial(p, 9600) as ser: time.sleep(2) print(ser.readline().decode('utf-8')) ser.write(b'\x50') # Enable programming ih.dump() print('Programming...') print(ser.readline().decode('utf-8')) conta = 0 for i in range(0, len(ih.addresses())): addr = ih.addresses()[i] if addr <= 0x7FF:
def load(self, filename): ih = IntelHex(filename) for addr in ih.addresses(): self.memory[addr] = ih[addr]
except: print( "Fatal Error: -- FAILED merge due to overlap when merging " + f.name) sys.exit(1) except: print("Fatal Error: -- FAILED parsing input hex file(s)") sys.exit(1) #print information about the input hex files print_args_info(inputFileNames, vargs.out, vargs.outbin, vargs.oadtype, vargs.imgtype, mergedHex) # Cut off / fill with --fill. startAddr = mergedHex.minaddr() endAddr = mergedHex.addresses()[-1] + 1 # Inclusive address if startAddr % vargs.blockSize: print( "Fatal Error: -- Start address 0x%X is not divisible by 16. Exiting" % startAddr) sys.exit(1) if vargs.range is not None: if vargs.range[0] is not None: startAddr = vargs.range[0] if vargs.range[1] is not None: endAddr = vargs.range[1] # Make sure the last address is divisible by the block size remainder = endAddr % vargs.blockSize if remainder: print(
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)
def main(): args = parser.parse_args() setup_logging(args) DAPAccess.set_args(args.daparg) # 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: ConnectHelper.list_connected_probes() else: session = ConnectHelper.session_with_chosen_probe( config_file=args.config, board_id=args.board_id, target_override=args.target_override, frequency=args.frequency, blocking=False, **convert_session_options(args.option)) if session is None: print("Error: There is no debug probe connected.") sys.exit(1) with session: board = session.board flash = board.flash progress = print_progress() if args.hide_progress: progress = None has_file = args.file is not None chip_erase = None if args.chip_erase: chip_erase = True elif args.sector_erase: chip_erase = False if args.mass_erase: print("Mass erasing device...") if board.target.mass_erase(): print("Successfully erased.") else: print("Failed.") return if not has_file: if chip_erase: print("Erasing chip...") flash.init() flash.erase_all() print("Done") elif args.sector_erase and args.address is not None: flash.init() page_addr = args.address for i in range(args.count): page_info = flash.get_page_info(page_addr) if not page_info: break # Align page address on first time through. if i == 0: delta = page_addr % page_info.size if delta: print( "Warning: sector address 0x%08x is unaligned" % page_addr) page_addr -= delta print("Erasing sector 0x%08x" % page_addr) flash.erase_page(page_addr) page_addr += page_info.size else: print("No operation performed") return # If no format provided, use the file's extension. if not args.format: args.format = os.path.splitext(args.file)[1][1:] if args.format == 'axf': args.format = 'elf' # 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.get_flash_info().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.flash_block(args.address, data, chip_erase=chip_erase, progress_cb=progress, fast_verify=args.fast_program) # Intel hex file format elif args.format == 'hex': hexfile = IntelHex(args.file) addresses = hexfile.addresses() addresses.sort() flash_builder = flash.get_flash_builder() data_list = list(ranges(addresses)) for start, end in data_list: size = end - start + 1 data = list(hexfile.tobinarray(start=start, size=size)) flash_builder.add_data(start, data) flash_builder.program(chip_erase=chip_erase, progress_cb=progress, fast_verify=args.fast_program) # ELF format elif args.format == 'elf': flash_builder = flash.get_flash_builder() with open(args.file, "rb") as f: elf = ELFBinaryFile(f, board.target.memory_map) for section in elf.sections: if ((section.type == 'SHT_PROGBITS') and ((section.flags & (SH_FLAGS.SHF_ALLOC | SH_FLAGS.SHF_WRITE)) == SH_FLAGS.SHF_ALLOC) and (section.length > 0) and (section.region.is_flash)): logging.debug("Writing section %s", repr(section)) flash_builder.add_data(section.start, section.data) else: logging.debug("Skipping section %s", repr(section)) flash_builder.program(chip_erase=chip_erase, progress_cb=progress, fast_verify=args.fast_program) else: print("Unknown file format '%s'" % args.format)