def main(): args = parser.parse_args() gdb_server_settings = get_gdb_server_settings(args) setup_logging(args) gdb = None if args.list_all == True: MbedBoard.listConnectedBoards() else: try: board_selected = MbedBoard.chooseBoard( board_id=args.board_id, target_override=args.target_override, frequency=args.frequency) with board_selected as board: # Boost speed with deferred transfers board.transport.setDeferredTransfer(True) gdb = GDBServer(board, args.port_number, gdb_server_settings) while gdb.isAlive(): gdb.join(timeout=0.5) except KeyboardInterrupt: if gdb != None: gdb.stop() except Exception as e: print "uncaught exception: %s" % e traceback.print_exc() if gdb != None: gdb.stop()
def _launchPyOCDGDBServer(msg_queue): logger.info('starting PyOCD gdbserver...') # ignore Ctrl-C, so we don't interrupt the GDB server when the # being-debugged program is being stopped: signal.signal(signal.SIGINT, _ignoreSignal); from pyOCD.gdbserver import GDBServer from pyOCD.board import MbedBoard gdb = None try: board_selected = MbedBoard.chooseBoard() with board_selected as board: gdb = GDBServer( board, 3333, { 'break_at_hardfault': True, 'step_into_interrupt': False, 'break_on_reset': False, } ) if gdb.isAlive(): msg_queue.put('alive') while gdb.isAlive(): gdb.join(timeout = 0.5) # check for a "kill" message from the parent process: try: msg = msg_queue.get(False) if msg == 'kill': gdb.stop() break except Queue.Empty: pass except Exception as e: if gdb != None: gdb.stop() raise msg_queue.put('dead')
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 run(self): self.args = self.build_parser().parse_args() self.gdb_server_settings = self.get_gdb_server_settings(self.args) self.setup_logging(self.args) self.process_commands(self.args.commands) gdb = None if self.args.list_all == True: MbedBoard.listConnectedBoards() else: try: board_selected = MbedBoard.chooseBoard( board_id=self.args.board_id, target_override=self.args.target_override, frequency=self.args.frequency) with board_selected as board: # Boost speed with deferred transfers board.transport.setDeferredTransfer(True) gdb = GDBServer(board, self.args.port_number, self.gdb_server_settings) while gdb.isAlive(): gdb.join(timeout=0.5) except KeyboardInterrupt: if gdb != None: gdb.stop() except Exception as e: print "uncaught exception: %s" % e traceback.print_exc() if gdb != None: gdb.stop() return 1 # Successful exit. return 0
def search_and_lock(board_id): """Repeatedly lock a board with the given ID""" for _ in range(0, 20): device = DAPAccess.get_device(board_id) device.open() device.close() with MbedBoard.chooseBoard(board_id=board_id): pass
def run(self, args=None): try: self.args = self.build_parser().parse_args(args) self.gdb_server_settings = self.get_gdb_server_settings(self.args) self.setup_logging(self.args) DAPAccess.set_args(self.args.daparg) self.process_commands(self.args.commands) gdb = None if self.args.list_all == True: self.list_boards() elif self.args.list_targets == True: self.list_targets() else: try: board_selected = MbedBoard.chooseBoard( board_id=self.args.board_id, target_override=self.args.target_override, frequency=self.args.frequency) with board_selected as board: gdb = GDBServer(board, self.args.port_number, self.gdb_server_settings) while gdb.isAlive(): gdb.join(timeout=0.5) except KeyboardInterrupt: if gdb != None: gdb.stop() except Exception as e: print "uncaught exception: %s" % e traceback.print_exc() if gdb != None: gdb.stop() return 1 # Successful exit. return 0 except InvalidArgumentError as e: self.parser.error(e) return 1
def _launchPyOCDGDBServer(msg_queue): logger.info('preparing PyOCD gdbserver...') from pyOCD.gdbserver import GDBServer from pyOCD.board import MbedBoard gdb = None try: logger.info('finding connected board...') board_selected = MbedBoard.chooseBoard(blocking=False) if board_selected is not None: with board_selected as board: logger.info('starting PyOCD gdbserver...') gdb = GDBServer( board, 3333, { 'break_at_hardfault': True, 'step_into_interrupt': False, 'break_on_reset': False, } ) if gdb.isAlive(): msg_queue.put('alive') while gdb.isAlive(): gdb.join(timeout = 0.5) # check for a "kill" message from the parent process: try: msg = msg_queue.get(False) if msg == 'kill': gdb.stop() break except Queue.Empty: pass else: logger.error('failed to find a connected board') except Exception as e: logger.error('exception in GDB server thread: %s', e) if gdb != None: gdb.stop() raise msg_queue.put('dead')
def cortex_test(board_id): with MbedBoard.chooseBoard(board_id=board_id, frequency=1000000) as board: target_type = board.getTargetType() binary_file = os.path.join(parentdir, 'binaries', board.getTestBinary()) test_clock = 10000000 addr_invalid = 0x3E000000 # Last 16MB of ARM SRAM region - typically empty 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 memory_map = board.target.getMemoryMap() ram_regions = [region for region in memory_map if region.type == 'ram'] ram_region = ram_regions[0] rom_region = memory_map.getBootMemory() addr = ram_region.start + 1 size = 0x502 addr_bin = rom_region.start target = board.target link = board.link flash = board.flash link.set_clock(test_clock) link.set_deferred_transfer(True) test_pass_count = 0 test_count = 0 result = CortexTestResult() print "\r\n\r\n----- FLASH NEW BINARY BEFORE TEST -----" flash.flashBinary(binary_file, addr_bin) # Let the target run for a bit so it # can initialize the watchdog if it needs to target.resume() sleep(0.2) target.halt() print "PROGRAMMING COMPLETE" print "\r\n\r\n----- TESTING CORTEX-M PERFORMANCE -----" test_time = test_function(board, target.getTResponse) print("Function getTResponse time: %f" % test_time) # Step test_time = test_function(board, target.step) print("Function step time: %f" % test_time) # Breakpoint def set_remove_breakpoint(): target.setBreakpoint(0) target.removeBreakpoint(0) test_time = test_function(board, set_remove_breakpoint) print("Add and remove breakpoint: %f" % test_time) # getRegisterContext test_time = test_function(board, target.getRegisterContext) print("Function getRegisterContext: %f" % test_time) # setRegisterContext context = target.getRegisterContext() def set_register_context(): target.setRegisterContext(context) test_time = test_function(board, set_register_context) print("Function setRegisterContext: %f" % test_time) # Run / Halt def run_halt(): target.resume() target.halt() test_time = test_function(board, run_halt) print("Resume and halt: %f" % test_time) # GDB stepping def simulate_step(): target.step() target.getTResponse() target.setBreakpoint(0) target.resume() target.halt() target.getTResponse() target.removeBreakpoint(0) test_time = test_function(board, simulate_step) print("Simulated GDB step: %f" % test_time) # Test passes if there are no exceptions test_pass_count += 1 test_count += 1 print("TEST PASSED") print "\r\n\r\n------ Testing Invalid Memory Access Recovery ------" memory_access_pass = True try: target.readBlockMemoryUnaligned8(addr_invalid, 0x1000) target.flush() # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0 if target_type != "nrf51": memory_access_pass = False except DAPAccess.TransferFaultError: pass try: target.readBlockMemoryUnaligned8(addr_invalid + 1, 0x1000) target.flush() # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0 if target_type != "nrf51": memory_access_pass = False except DAPAccess.TransferFaultError: pass data = [0x00] * 0x1000 try: target.writeBlockMemoryUnaligned8(addr_invalid, data) target.flush() # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0 if target_type != "nrf51": memory_access_pass = False except DAPAccess.TransferFaultError: pass data = [0x00] * 0x1000 try: target.writeBlockMemoryUnaligned8(addr_invalid + 1, data) target.flush() # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0 if target_type != "nrf51": memory_access_pass = False except DAPAccess.TransferFaultError: pass data = [randrange(0, 255) for x in range(size)] target.writeBlockMemoryUnaligned8(addr, data) block = target.readBlockMemoryUnaligned8(addr, size) if same(data, block): print "Aligned access pass" else: print("Memory read does not match memory written") memory_access_pass = False data = [randrange(0, 255) for x in range(size)] target.writeBlockMemoryUnaligned8(addr + 1, data) block = target.readBlockMemoryUnaligned8(addr + 1, size) if same(data, block): print "Unaligned access pass" else: print("Unaligned memory read does not match memory written") memory_access_pass = False test_count += 1 if memory_access_pass: test_pass_count += 1 print "TEST PASSED" else: print "TEST FAILED" print "\r\n\r\n------ Testing Software Breakpoints ------" test_passed = True orig8x2 = target.readBlockMemoryUnaligned8(addr, 2) orig8 = target.read8(addr) orig16 = target.read16(addr & ~1) orig32 = target.read32(addr & ~3) origAligned32 = target.readBlockMemoryAligned32(addr & ~3, 1) def test_filters(): test_passed = True filtered = target.readBlockMemoryUnaligned8(addr, 2) if same(orig8x2, filtered): print "2 byte unaligned passed" else: print "2 byte unaligned failed (read %x-%x, expected %x-%x)" % ( filtered[0], filtered[1], orig8x2[0], orig8x2[1]) test_passed = False for now in (True, False): filtered = target.read8(addr, now) if not now: filtered = filtered() if filtered == orig8: print "8-bit passed [now=%s]" % now else: print "8-bit failed [now=%s] (read %x, expected %x)" % ( now, filtered, orig8) test_passed = False filtered = target.read16(addr & ~1, now) if not now: filtered = filtered() if filtered == orig16: print "16-bit passed [now=%s]" % now else: print "16-bit failed [now=%s] (read %x, expected %x)" % ( now, filtered, orig16) test_passed = False filtered = target.read32(addr & ~3, now) if not now: filtered = filtered() if filtered == orig32: print "32-bit passed [now=%s]" % now else: print "32-bit failed [now=%s] (read %x, expected %x)" % ( now, filtered, orig32) test_passed = False filtered = target.readBlockMemoryAligned32(addr & ~3, 1) if same(filtered, origAligned32): print "32-bit aligned passed" else: print "32-bit aligned failed (read %x, expected %x)" % ( filtered[0], origAligned32[0]) test_passed = False return test_passed print "Installed software breakpoint at 0x%08x" % addr target.setBreakpoint(addr, pyOCD.target.target.Target.BREAKPOINT_SW) test_passed = test_filters() and test_passed print "Removed software breakpoint" target.removeBreakpoint(addr) test_passed = test_filters() and test_passed test_count += 1 if test_passed: test_pass_count += 1 print "TEST PASSED" else: print "TEST FAILED" target.reset() result.passed = test_count == test_pass_count return result
args = parser.parse_args() if args.verbose == 2: logging.basicConfig(level=logging.DEBUG) elif args.verbose == 1: logging.basicConfig(level=logging.INFO) if (args.list): print MbedBoard.listConnectedBoards() sys.exit(0) adapter = None try: adapter = None if (args.board_id): adapter = MbedBoard.chooseBoard(board_id=args.board_id) else: interfaces = INTERFACE[usb_backend].getAllConnectedInterface( VID, PID) if interfaces == None: print "Not find a mbed interface" sys.exit(1) # Use the first one first_interface = interfaces[0] adapter = MbedBoard("target_nrf51822", "flash_nrf51822", first_interface) adapter.init() target = adapter.target target.halt()
def basic_test(board_id, file): with MbedBoard.chooseBoard(board_id=board_id) as board: addr = 0 size = 0 f = None binary_file = "l1_" interface = None target_type = board.getTargetType() if file is None: binary_file = os.path.join(parentdir, 'binaries', board.getTestBinary()) else: binary_file = file print "binary file: %s" % binary_file addr_bin = 0x00000000 if target_type == "lpc1768": addr = 0x10000001 size = 0x1102 addr_flash = 0x10000 elif target_type == "lpc11u24": addr = 0x10000001 size = 0x502 addr_flash = 0x4000 elif target_type == "kl25z": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 elif target_type == "k64f": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 elif target_type == "k22f": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 elif target_type == "k20d50m": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 elif target_type == "kl46z": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 elif target_type == "lpc800": addr = 0x10000001 size = 0x502 addr_flash = 0x2000 elif target_type == "nrf51822": addr = 0x20000001 size = 0x502 addr_flash = 0x20000 elif target_type == "lpc4330": addr = 0x10000001 size = 0x1102 addr_flash = 0x14010000 addr_bin = 0x14000000 elif target_type == "maxwsnenv": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 elif target_type == "max32600mbed": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 else: raise Exception("A board is not supported by this test script.") target = board.target transport = board.transport flash = board.flash interface = board.interface print "\r\n\r\n------ GET Unique ID ------" print "Unique ID: %s" % board.getUniqueID() print "\r\n\r\n------ TEST READ / WRITE CORE REGISTER ------" pc = target.readCoreRegister('pc') print "initial pc: 0x%X" % target.readCoreRegister('pc') # write in pc dummy value target.writeCoreRegister('pc', 0x3D82) print "now pc: 0x%X" % target.readCoreRegister('pc') # write initial pc value target.writeCoreRegister('pc', pc) print "initial pc value rewritten: 0x%X" % target.readCoreRegister( 'pc') msp = target.readCoreRegister('msp') psp = target.readCoreRegister('psp') print "MSP = 0x%08x; PSP = 0x%08x" % (msp, psp) control = target.readCoreRegister('control') faultmask = target.readCoreRegister('faultmask') basepri = target.readCoreRegister('basepri') primask = target.readCoreRegister('primask') print "CONTROL = 0x%02x; FAULTMASK = 0x%02x; BASEPRI = 0x%02x; PRIMASK = 0x%02x" % ( control, faultmask, basepri, primask) target.writeCoreRegister('primask', 1) newPrimask = target.readCoreRegister('primask') print "New PRIMASK = 0x%02x" % newPrimask target.writeCoreRegister('primask', primask) newPrimask = target.readCoreRegister('primask') print "Restored PRIMASK = 0x%02x" % newPrimask if target.has_fpu: s0 = target.readCoreRegister('s0') print "S0 = %g (0x%08x)" % (s0, float2int(s0)) target.writeCoreRegister('s0', math.pi) newS0 = target.readCoreRegister('s0') print "New S0 = %g (0x%08x)" % (newS0, float2int(newS0)) target.writeCoreRegister('s0', s0) newS0 = target.readCoreRegister('s0') print "Restored S0 = %g (0x%08x)" % (newS0, float2int(newS0)) print "\r\n\r\n------ TEST HALT / RESUME ------" print "resume" target.resume() sleep(0.2) print "halt" target.halt() print "HALT: pc: 0x%X" % target.readCoreRegister('pc') sleep(0.2) print "\r\n\r\n------ TEST READ / WRITE MEMORY ------" target.halt() print "READ32/WRITE32" val = randrange(0, 0xffffffff) print "write32 0x%X at 0x%X" % (val, addr) target.writeMemory(addr, val) res = target.readMemory(addr) print "read32 at 0x%X: 0x%X" % (addr, res) if res != val: print "ERROR in READ/WRITE 32" print "\r\nREAD16/WRITE16" val = randrange(0, 0xffff) print "write16 0x%X at 0x%X" % (val, addr + 2) target.writeMemory(addr + 2, val, 16) res = target.readMemory(addr + 2, 16) print "read16 at 0x%X: 0x%X" % (addr + 2, res) if res != val: print "ERROR in READ/WRITE 16" print "\r\nREAD8/WRITE8" val = randrange(0, 0xff) print "write8 0x%X at 0x%X" % (val, addr + 1) target.writeMemory(addr + 1, val, 8) res = target.readMemory(addr + 1, 8) print "read8 at 0x%X: 0x%X" % (addr + 1, res) if res != val: print "ERROR in READ/WRITE 8" print "\r\n\r\n------ TEST READ / WRITE MEMORY BLOCK ------" data = [randrange(1, 50) for x in range(size)] target.writeBlockMemoryUnaligned8(addr, data) block = target.readBlockMemoryUnaligned8(addr, size) error = False for i in range(len(block)): if (block[i] != data[i]): error = True print "ERROR: 0x%X, 0x%X, 0x%X!!!" % ( (addr + i), block[i], data[i]) if error: print "TEST FAILED" else: print "TEST PASSED" print "\r\n\r\n------ TEST RESET ------" target.reset() sleep(0.1) target.halt() for i in range(5): target.step() print "pc: 0x%X" % target.readCoreRegister('pc') print "\r\n\r\n------ TEST PROGRAM/ERASE PAGE ------" # Fill 3 pages with 0x55 fill = [0x55] * flash.page_size flash.init() for i in range(0, 3): flash.erasePage(addr_flash + flash.page_size * i) flash.programPage(addr_flash + flash.page_size * i, fill) # Erase the middle page flash.erasePage(addr_flash + flash.page_size) # Verify the 1st and 3rd page were not erased, and that the 2nd page is fully erased data = target.readBlockMemoryUnaligned8(addr_flash, flash.page_size * 3) expected = fill + [0xFF] * flash.page_size + fill if data == expected: print "TEST PASSED" else: print "TEST FAILED" print "\r\n\r\n----- FLASH NEW BINARY -----" flash.flashBinary(binary_file, addr_bin) target.reset()
def connect_test(board): board_id = board.getUniqueID() binary_file = os.path.join(parentdir, 'binaries', board.getTestBinary()) print("binary file: %s" % binary_file) test_pass_count = 0 test_count = 0 result = ConnectTestResult() # Install binary. live_board = MbedBoard.chooseBoard(board_id=board_id, frequency=1000000) memory_map = board.target.getMemoryMap() rom_region = memory_map.getBootMemory() rom_start = rom_region.start def test_connect(halt_on_connect, expected_state, resume): print("Connecting with halt_on_connect=%s" % halt_on_connect) live_board = MbedBoard.chooseBoard(board_id=board_id, frequency=1000000, init_board=False) live_board.target.setHaltOnConnect(halt_on_connect) live_board.init() print("Verifying target is", STATE_NAMES.get(expected_state, "unknown")) actualState = live_board.target.getState() if actualState == expected_state: passed = 1 print("TEST PASSED") else: passed = 0 print("TEST FAILED (state={}, expected={})".format( STATE_NAMES.get(actualState, "unknown"), STATE_NAMES.get(expected_state, "unknown"))) print("Disconnecting with resume=%s" % resume) live_board.uninit(resume) live_board = None return passed # TEST CASE COMBINATIONS test_cases = [ # <prev_exit> <halt_on_connect> <expected_state> <disconnect_resume> <exit_state> ConnectTestCase(RUNNING, False, RUNNING, False, RUNNING), ConnectTestCase(RUNNING, True, HALTED, False, HALTED), ConnectTestCase(HALTED, True, HALTED, True, RUNNING), ConnectTestCase(RUNNING, True, HALTED, True, RUNNING), ConnectTestCase(RUNNING, False, RUNNING, True, RUNNING), ConnectTestCase(RUNNING, True, HALTED, False, HALTED), ConnectTestCase(HALTED, False, HALTED, False, HALTED), ConnectTestCase(HALTED, True, HALTED, False, HALTED), ConnectTestCase(HALTED, False, HALTED, True, RUNNING), ConnectTestCase(RUNNING, False, RUNNING, False, RUNNING), ] print("\n\n----- FLASH NEW BINARY -----") live_board.flash.flashBinary(binary_file, rom_start) live_board.target.reset() test_count += 1 print("Verifying target is running") if live_board.target.isRunning(): test_pass_count += 1 print("TEST PASSED") else: print("TEST FAILED") print("Disconnecting with resume=True") live_board.uninit(resume=True) live_board = None # Leave running. # Run all the cases. for case in test_cases: test_count += 1 did_pass = test_connect(halt_on_connect=case.halt_on_connect, expected_state=case.expected_state, resume=case.disconnect_resume) test_pass_count += did_pass case.passed = did_pass print("\n\nTest Summary:") print("\n{:<4}{:<12}{:<19}{:<12}{:<21}{:<11}{:<10}".format( "#", "Prev Exit", "Halt on Connect", "Expected", "Disconnect Resume", "Exit", "Passed")) for i, case in enumerate(test_cases): print("{:<4}{:<12}{:<19}{:<12}{:<21}{:<11}{:<10}".format( i, STATE_NAMES[case.prev_exit_state], repr(case.halt_on_connect), STATE_NAMES[case.expected_state], repr(case.disconnect_resume), STATE_NAMES[case.exit_state], "PASS" if case.passed else "FAIL")) print("\nPass count %i of %i tests" % (test_pass_count, test_count)) if test_pass_count == test_count: print("CONNECT TEST SCRIPT PASSED") else: print("CONNECT TEST SCRIPT FAILED") result.passed = (test_count == test_pass_count) return result
def test_hid(workspace, parent_test): test_info = parent_test.create_subtest("HID test") board = workspace.board with MbedBoard.chooseBoard(board_id=board.get_unique_id()) as mbed_board: addr = 0 size = 0 target_type = mbed_board.getTargetType() binary_file = workspace.target.bin_path addr_bin = 0x00000000 if target_type == "lpc1768": addr = 0x10000001 size = 0x1102 addr_flash = 0x10000 elif target_type == "lpc11u24": addr = 0x10000001 size = 0x502 addr_flash = 0x4000 elif target_type == "kl25z": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 elif target_type == "kl28z": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 elif target_type == "k64f": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 elif target_type == "k22f": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 elif target_type == "k20d50m": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 elif target_type == "kl46z": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 elif target_type == "kl05z": addr = 0x20000001 size = 0x502 addr_flash = 0x6000 elif target_type == "lpc800": addr = 0x10000001 size = 0x502 addr_flash = 0x2000 elif target_type == "lpc11xx_32": addr = 0x10000001 size = 0x502 addr_flash = 0x4000 elif target_type == "nrf51": addr = 0x20000001 size = 0x502 addr_flash = 0x20000 elif target_type == "lpc4330": addr = 0x10000001 size = 0x1102 addr_flash = 0x14010000 addr_bin = 0x14000000 elif target_type == "maxwsnenv": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 elif target_type == "max32600mbed": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 elif target_type == "w7500": addr = 0x20000001 size = 0x1102 addr_flash = 0x00000000 elif target_type == "lpc824": addr = 0x10000001 size = 0x502 addr_flash = 0x4000 else: raise Exception("A board is not supported by this test script.") target = mbed_board.target flash = mbed_board.flash test_info.info("\r\n\r\n----- FLASH NEW BINARY -----") flash.flashBinary(binary_file, addr_bin) test_info.info("\r\n\r\n------ GET Unique ID ------") test_info.info("Unique ID: %s" % mbed_board.getUniqueID()) test_info.info("\r\n\r\n------ TEST READ / WRITE CORE REGISTER ------") pc = target.readCoreRegister('pc') test_info.info("initial pc: 0x%X" % target.readCoreRegister('pc')) # write in pc dummy value target.writeCoreRegister('pc', 0x3D82) test_info.info("now pc: 0x%X" % target.readCoreRegister('pc')) # write initial pc value target.writeCoreRegister('pc', pc) test_info.info("initial pc value rewritten: 0x%X" % target.readCoreRegister('pc')) msp = target.readCoreRegister('msp') psp = target.readCoreRegister('psp') test_info.info("MSP = 0x%08x; PSP = 0x%08x" % (msp, psp)) control = target.readCoreRegister('control') faultmask = target.readCoreRegister('faultmask') basepri = target.readCoreRegister('basepri') primask = target.readCoreRegister('primask') test_info.info( "CONTROL = 0x%02x; FAULTMASK = 0x%02x; BASEPRI = 0x%02x; PRIMASK = 0x%02x" % (control, faultmask, basepri, primask)) target.writeCoreRegister('primask', 1) newPrimask = target.readCoreRegister('primask') test_info.info("New PRIMASK = 0x%02x" % newPrimask) target.writeCoreRegister('primask', primask) newPrimask = target.readCoreRegister('primask') test_info.info("Restored PRIMASK = 0x%02x" % newPrimask) if target.has_fpu: s0 = target.readCoreRegister('s0') test_info.info("S0 = %g (0x%08x)" % (s0, float32beToU32be(s0))) target.writeCoreRegister('s0', math.pi) newS0 = target.readCoreRegister('s0') test_info.info("New S0 = %g (0x%08x)" % (newS0, float32beToU32be(newS0))) target.writeCoreRegister('s0', s0) newS0 = target.readCoreRegister('s0') test_info.info("Restored S0 = %g (0x%08x)" % (newS0, float32beToU32be(newS0))) test_info.info("\r\n\r\n------ TEST HALT / RESUME ------") test_info.info("resume") target.resume() sleep(0.2) test_info.info("halt") target.halt() test_info.info("HALT: pc: 0x%X" % target.readCoreRegister('pc')) sleep(0.2) test_info.info("\r\n\r\n------ TEST STEP ------") test_info.info("reset and halt") target.resetStopOnReset() currentPC = target.readCoreRegister('pc') test_info.info("HALT: pc: 0x%X" % currentPC) sleep(0.2) for i in range(4): test_info.info("step") target.step() newPC = target.readCoreRegister('pc') test_info.info("STEP: pc: 0x%X" % newPC) currentPC = newPC sleep(0.2) test_info.info("\r\n\r\n------ TEST READ / WRITE MEMORY ------") target.halt() test_info.info("READ32/WRITE32") val = randrange(0, 0xffffffff) test_info.info("write32 0x%X at 0x%X" % (val, addr)) target.writeMemory(addr, val) res = target.readMemory(addr) test_info.info("read32 at 0x%X: 0x%X" % (addr, res)) if res != val: test_info.failure("ERROR in READ/WRITE 32") test_info.info("\r\nREAD16/WRITE16") val = randrange(0, 0xffff) test_info.info("write16 0x%X at 0x%X" % (val, addr + 2)) target.writeMemory(addr + 2, val, 16) res = target.readMemory(addr + 2, 16) test_info.info("read16 at 0x%X: 0x%X" % (addr + 2, res)) if res != val: test_info.failure("ERROR in READ/WRITE 16") test_info.info("\r\nREAD8/WRITE8") val = randrange(0, 0xff) test_info.info("write8 0x%X at 0x%X" % (val, addr + 1)) target.writeMemory(addr + 1, val, 8) res = target.readMemory(addr + 1, 8) test_info.info("read8 at 0x%X: 0x%X" % (addr + 1, res)) if res != val: test_info.failure("ERROR in READ/WRITE 8") test_info.info("\r\n\r\n------ TEST READ / WRITE MEMORY BLOCK ------") data = [randrange(1, 50) for _ in range(size)] target.writeBlockMemoryUnaligned8(addr, data) block = target.readBlockMemoryUnaligned8(addr, size) error = False for i in range(len(block)): if (block[i] != data[i]): error = True test_info.info("ERROR: 0x%X, 0x%X, 0x%X!!!" % ((addr + i), block[i], data[i])) if error: test_info.failure("TEST FAILED") else: test_info.info("TEST PASSED") test_info.info("\r\n\r\n------ TEST RESET ------") target.reset() sleep(0.1) target.halt() for i in range(5): target.step() test_info.info("pc: 0x%X" % target.readCoreRegister('pc')) test_info.info("\r\n\r\n------ TEST PROGRAM/ERASE PAGE ------") # Fill 3 pages with 0x55 page_size = flash.getPageInfo(addr_flash).size fill = [0x55] * page_size flash.init() for i in range(0, 3): address = addr_flash + page_size * i # Test only supports a location with 3 aligned # pages of the same size current_page_size = flash.getPageInfo(addr_flash).size assert page_size == current_page_size assert address % current_page_size == 0 flash.erasePage(address) flash.programPage(address, fill) # Erase the middle page flash.erasePage(addr_flash + page_size) # Verify the 1st and 3rd page were not erased, and that # the 2nd page is fully erased data = target.readBlockMemoryUnaligned8(addr_flash, page_size * 3) expected = fill + [0xFF] * page_size + fill if data == expected: test_info.info("TEST PASSED") else: test_info.failure("TEST FAILED") test_info.info("\r\n\r\n----- Restoring image -----") flash.flashBinary(binary_file, addr_bin) target.reset() test_info.info("HID test complete")
from pyOCD.gdbserver import GDBServer from pyOCD.board import MbedBoard import logging logging.basicConfig(level=logging.INFO) board = MbedBoard.chooseBoard() # start gdbserver gdb = GDBServer(board, 3333)
def flash_test(board_id): with MbedBoard.chooseBoard(board_id=board_id, frequency=1000000) as board: target_type = board.getTargetType() test_clock = 10000000 if target_type == "kl25z": ram_start = 0x1ffff000 ram_size = 0x4000 rom_start = 0x00000000 rom_size = 0x20000 elif target_type == "kl46z": ram_start = 0x1fffe000 ram_size = 0x8000 rom_start = 0x00000000 rom_size = 0x40000 elif target_type == "k22f": ram_start = 0x1fff0000 ram_size = 0x20000 rom_start = 0x00000000 rom_size = 0x80000 elif target_type == "k64f": ram_start = 0x1FFF0000 ram_size = 0x40000 rom_start = 0x00000000 rom_size = 0x100000 elif target_type == "lpc11u24": ram_start = 0x10000000 ram_size = 0x2000 rom_start = 0x00000000 rom_size = 0x8000 elif target_type == "lpc1768": ram_start = 0x10000000 ram_size = 0x8000 rom_start = 0x00000000 rom_size = 0x80000 elif target_type == "lpc4330": ram_start = 0x10000000 ram_size = 0x20000 rom_start = 0x14000000 rom_size = 0x100000 elif target_type == "lpc800": ram_start = 0x10000000 ram_size = 0x1000 rom_start = 0x00000000 rom_size = 0x4000 elif target_type == "nrf51822": ram_start = 0x20000000 ram_size = 0x4000 rom_start = 0x00000000 rom_size = 0x40000 # Override clock since 10MHz is too fast test_clock = 1000000 else: raise Exception("The board is not supported by this test script.") target = board.target transport = board.transport flash = board.flash interface = board.interface transport.setClock(test_clock) test_pass_count = 0 test_count = 0 print "\r\n\r\n------ Test Read / Write Speed ------" test_addr = ram_start test_size = ram_size data = [randrange(1, 50) for x in range(test_size)] start = time() target.writeBlockMemoryUnaligned8(test_addr, data) stop = time() diff = stop-start print("Writing %i byte took %s seconds: %s B/s" % (test_size, diff, test_size / diff)) start = time() block = target.readBlockMemoryUnaligned8(test_addr, test_size) stop = time() diff = stop-start print("Reading %i byte took %s seconds: %s B/s" % (test_size, diff, test_size / diff)) if same(block, data): print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 def print_progress(progress): assert progress >= 0.0 assert progress <= 1.0 assert (progress == 0 and print_progress.prev_progress == 1.0) or (progress >= print_progress.prev_progress) # Reset state on 0.0 if progress == 0.0: print_progress.prev_progress = 0 print_progress.backwards_progress = False print_progress.done = False # Check for backwards progress if progress < print_progress.prev_progress: print_progress.backwards_progress = True print_progress.prev_progress = progress # print progress bar if not print_progress.done: sys.stdout.write('\r') i = int(progress*20.0) sys.stdout.write("[%-20s] %3d%%" % ('='*i, round(progress * 100))) # Finish on 1.0 if progress >= 1.0: if not print_progress.done: print_progress.done = True sys.stdout.write("\n") if print_progress.backwards_progress: print("Progress went backwards during flash") print_progress.prev_progress = 0 binary_file = "l1_" binary_file += target_type + ".bin" binary_file = os.path.join(parentdir, 'binaries', binary_file) with open(binary_file, "rb") as f: data = f.read() data = struct.unpack("%iB" % len(data), data) unused = rom_size - len(data) addr = rom_start size = len(data) print "\r\n\r\n------ Test Basic Page Erase ------" operation = flash.flashBlock(addr, data, False, False, progress_cb = print_progress) data_flashed = target.readBlockMemoryUnaligned8(addr, size) if same(data_flashed, data) and operation is FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Basic Chip Erase ------" operation = flash.flashBlock(addr, data, False, True, progress_cb = print_progress) data_flashed = target.readBlockMemoryUnaligned8(addr, size) if same(data_flashed, data) and operation is FLASH_CHIP_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Smart Page Erase ------" operation = flash.flashBlock(addr, data, True, False, progress_cb = print_progress) data_flashed = target.readBlockMemoryUnaligned8(addr, size) if same(data_flashed, data) and operation is FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Smart Chip Erase ------" operation = flash.flashBlock(addr, data, True, True, progress_cb = print_progress) data_flashed = target.readBlockMemoryUnaligned8(addr, size) if same(data_flashed, data) and operation is FLASH_CHIP_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Offset Write ------" new_data = [0x55] * board.flash.page_size * 2 addr = rom_start + rom_size / 2 operation = flash.flashBlock(addr, new_data, progress_cb = print_progress) data_flashed = target.readBlockMemoryUnaligned8(addr, len(new_data)) if same(data_flashed, new_data) and operation is FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Multiple Block Writes ------" more_data = [0x33] * board.flash.page_size * 2 addr = (rom_start + rom_size / 2) + 1 #cover multiple pages fb = flash.getFlashBuilder() fb.addData(rom_start, data) fb.addData(addr, more_data) fb.program(progress_cb = print_progress) data_flashed = target.readBlockMemoryUnaligned8(rom_start, len(data)) data_flashed_more = target.readBlockMemoryUnaligned8(addr, len(more_data)) if same(data_flashed, data) and same(data_flashed_more, more_data): print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Overlapping Blocks ------" test_pass = False new_data = [0x33] * board.flash.page_size addr = (rom_start + rom_size / 2) #cover multiple pages fb = flash.getFlashBuilder() fb.addData(addr, new_data) try: fb.addData(addr + 1, new_data) except ValueError as e: print("Exception: %s" % e) test_pass = True if test_pass: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Empty Block Write ------" # Freebee if nothing asserts fb = flash.getFlashBuilder() fb.program() print("TEST PASSED") test_pass_count += 1 test_count += 1 print "\r\n\r\n------ Test Missing Progress Callback ------" # Freebee if nothing asserts addr = rom_start flash.flashBlock(rom_start, data, True) print("TEST PASSED") test_pass_count += 1 test_count += 1 # Note - The decision based tests below are order dependent since they # depend on the previous state of the flash print "\r\n\r\n------ Test Chip Erase Decision ------" new_data = list(data) new_data.extend([0xff] * unused) # Pad with 0xFF operation = flash.flashBlock(0, new_data, progress_cb = print_progress) if operation == FLASH_CHIP_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Chip Erase Decision 2 ------" new_data = list(data) new_data.extend([0x00] * unused) # Pad with 0x00 operation = flash.flashBlock(0, new_data, progress_cb = print_progress) if operation == FLASH_CHIP_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Page Erase Decision ------" new_data = list(data) new_data.extend([0x00] * unused) # Pad with 0x00 operation = flash.flashBlock(0, new_data, progress_cb = print_progress) if operation == FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Page Erase Decision 2 ------" new_data = list(data) size_same = unused * 5 / 6 size_differ = unused - size_same new_data.extend([0x00] * size_same) # Pad 5/6 with 0x00 and 1/6 with 0xFF new_data.extend([0x55] * size_differ) operation = flash.flashBlock(0, new_data, progress_cb = print_progress) if operation == FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print("\r\n\r\nTest Summary:") print("Pass count %i of %i tests" % (test_pass_count, test_count)) if test_pass_count == test_count: print("FLASH TEST SCRIPT PASSED") else: print("FLASH TEST SCRIPT FAILED") target.reset() return test_count == test_pass_count
def test_mass_storage(workspace, parent_test): """Test the mass storage endpoint Requirements: None Positional arguments: filename - A string containing the name of the file to load Return: True if the test passed, False otherwise """ test_info = parent_test.create_subtest('test_mass_storage') # Setup test board = workspace.board target = workspace.target bin_file = target.bin_path hex_file = target.hex_path with open(bin_file, 'rb') as test_file: bin_file_contents = bytearray(test_file.read()) with open(hex_file, 'rb') as test_file: hex_file_contents = bytearray(test_file.read()) blank_bin_contents = bytearray([0xff]) * 0x2000 vectors_and_pad = bin_file_contents[0:32] + blank_bin_contents locked_when_erased = board.get_board_id( ) in info.BOARD_ID_LOCKED_WHEN_ERASED page_erase_supported = board.get_board_id( ) in info.BOARD_ID_SUPPORTING_PAGE_ERASE bad_vector_table = target.name in info.TARGET_WITH_BAD_VECTOR_TABLE_LIST intel_hex = intelhex.IntelHex(hex_file) addresses = intel_hex.addresses() addresses.sort() start = addresses[0] # Test loading a binary file with shutils if not bad_vector_table: test = MassStorageTester(board, test_info, "Shutil binary file load") test.set_shutils_copy(bin_file) test.set_expected_data(bin_file_contents, start) test.run() # Test loading a binary file with flushes if not bad_vector_table: test = MassStorageTester(board, test_info, "Load binary with flushes") test.set_programming_data(bin_file_contents, 'image.bin') test.set_expected_data(bin_file_contents, start) test.set_flush_size(0x1000) test.run() # Test loading a hex file with shutils test = MassStorageTester(board, test_info, "Shutil hex file load") test.set_shutils_copy(hex_file) test.set_expected_data(bin_file_contents, start) test.run() # Test loading a hex file with flushes test = MassStorageTester(board, test_info, "Load hex with flushes") test.set_programming_data(hex_file_contents, 'image.hex') test.set_expected_data(bin_file_contents, start) test.set_flush_size(0x1000) test.run() # Test loading a binary smaller than a sector if not bad_vector_table: test = MassStorageTester(board, test_info, "Load .bin smaller than sector") test_data_size = 0x789 test_data = bin_file_contents[0:0 + test_data_size] test.set_programming_data(test_data, 'image.bin') test.set_expected_data(test_data, start) test.run() # Test loading a blank binary - this image should cause a timeout # since it doesn't have a valid vector table test = MassStorageTester(board, test_info, "Load blank binary") test.set_programming_data(blank_bin_contents, 'image.bin') test.set_expected_failure_msg("The transfer timed out.", "transient, user") test.set_expected_data(None, start) test.run() # Test loading a blank binary with a vector table but padded with 0xFF. # A blank image can lock some devices. if not bad_vector_table: test = MassStorageTester(board, test_info, "Load blank binary + vector table") test.set_programming_data(vectors_and_pad, 'image.bin') if locked_when_erased: test.set_expected_failure_msg( "The interface firmware ABORTED programming. Image is trying to set security bits", "user") test.set_expected_data(None, start) else: test.set_expected_data(vectors_and_pad, start) test.run() # Test a normal load with dummy files created beforehand test = MassStorageTester(board, test_info, "Extra Files") test.set_programming_data(hex_file_contents, 'image.hex') test.add_mock_dirs(MOCK_DIR_LIST) test.add_mock_files(MOCK_FILE_LIST) test.add_mock_dirs_after_load(MOCK_DIR_LIST_AFTER) test.add_mock_files_after_load(MOCK_FILE_LIST_AFTER) test.set_expected_data(bin_file_contents, start) test.run() # Note - it is not unexpected for an "Extra Files" test to fail # when a binary file is loaded, since there is no way to # tell where the end of the file is. if page_erase_supported: # Test page erase, a.k.a. sector erase by generating iHex with discrete addresses, # programing the device then comparing device memory against expected content. test = MassStorageTester(board, test_info, "Sector Erase") with MbedBoard.chooseBoard(board_id=board.get_unique_id(), init_board=False) as mbed_board: memory_map = mbed_board.target.getMemoryMap() flash_regions = [ region for region in memory_map if region.type == 'flash' ] max_address = intel_hex.maxaddr() # Create an object. We'll add the addresses of unused even blocks to it first, then unused odd blocks for each region ih = intelhex.IntelHex() # Add the content from test bin first expected_bin_contents = bin_file_contents for region_index, the_region in enumerate(flash_regions): if the_region.isBootMemory == False: continue flash_start = the_region.start flash_length = the_region.length block_size = the_region.blocksize number_of_blocks = flash_length // block_size # Sanity check the regions are contiguous if region_index: assert flash_start == (flash_regions[region_index - 1].start + flash_regions[region_index - 1].length) if max_address >= (flash_start + flash_length): # This bin image crosses this region, don't modify the content, go to the next region continue elif max_address >= flash_start: # This bin image occupies partial region. Skip the used portion to avoid touching any security bits and pad the rest expected_bin_contents += bytearray( [0xff]) * (flash_start + flash_length - max_address - 1) # Calculate the starting block after the image to avoid stumbling upon security bits block_start = (max_address - flash_start) // block_size + 1 else: # This bin image doesn't reach this region expected_bin_contents += bytearray([0xff]) * flash_length block_start = 0 # For all even blocks, overwrite all addresses with 0x55; for all odd blocks, overwrite all addresses with 0xAA for pass_number in range(2): if pass_number == 0: modifier = 0x55 else: modifier = 0xAA block_start += 1 for block_idx in range(block_start, number_of_blocks, 2): for address_to_modify in range( flash_start + block_idx * block_size, flash_start + (block_idx + 1) * block_size): expected_bin_contents[address_to_modify] = modifier ih[address_to_modify] = modifier if not os.path.exists("tmp"): os.makedirs("tmp") # Write out the modified iHex to file ih.tofile("tmp/interleave.hex", format='hex') # Load this hex file with shutils test.set_shutils_copy("tmp/interleave.hex") test.set_expected_data(expected_bin_contents, start) test.run() # Finally, load a good binary test = MassStorageTester(board, test_info, "Load good file to restore state") test.set_programming_data(hex_file_contents, 'image.hex') test.set_expected_data(bin_file_contents, start) test.run()
def flash_test(board_id): with MbedBoard.chooseBoard(board_id=board_id, frequency=1000000) as board: target_type = board.getTargetType() test_clock = 10000000 if target_type == "kl25z": ram_start = 0x1ffff000 ram_size = 0x4000 rom_start = 0x00000000 rom_size = 0x20000 elif target_type == "kl28z": ram_start = 0x1fffa000 ram_size = 96 * 1024 rom_start = 0x00000000 rom_size = 512 * 1024 elif target_type == "kl46z": ram_start = 0x1fffe000 ram_size = 0x8000 rom_start = 0x00000000 rom_size = 0x40000 elif target_type == "k22f": ram_start = 0x1fff0000 ram_size = 0x20000 rom_start = 0x00000000 rom_size = 0x80000 elif target_type == "k64f": ram_start = 0x1FFF0000 ram_size = 0x40000 rom_start = 0x00000000 rom_size = 0x100000 elif target_type == "lpc11u24": ram_start = 0x10000000 ram_size = 0x2000 rom_start = 0x00000000 rom_size = 0x8000 elif target_type == "lpc1768": ram_start = 0x10000000 ram_size = 0x8000 rom_start = 0x00000000 rom_size = 0x80000 elif target_type == "lpc4330": ram_start = 0x10000000 ram_size = 0x20000 rom_start = 0x14000000 rom_size = 0x100000 elif target_type == "lpc800": ram_start = 0x10000000 ram_size = 0x1000 rom_start = 0x00000000 rom_size = 0x4000 elif target_type == "nrf51": ram_start = 0x20000000 ram_size = 0x4000 rom_start = 0x00000000 rom_size = 0x40000 # Override clock since 10MHz is too fast test_clock = 1000000 elif target_type == "maxwsnenv": ram_start = 0x20000000 ram_size = 0x8000 rom_start = 0x00000000 rom_size = 0x40000 elif target_type == "max32600mbed": ram_start = 0x20000000 ram_size = 0x8000 rom_start = 0x00000000 rom_size = 0x40000 elif target_type == "w7500": ram_start = 0x20000000 ram_size = 0x4000 rom_start = 0x00000000 rom_size = 0x20000 else: raise Exception("The board is not supported by this test script.") target = board.target transport = board.transport flash = board.flash interface = board.interface transport.setClock(test_clock) transport.setDeferredTransfer(True) test_pass_count = 0 test_count = 0 result = FlashTestResult() def print_progress(progress): assert progress >= 0.0 assert progress <= 1.0 assert (progress == 0 and print_progress.prev_progress == 1.0) or (progress >= print_progress.prev_progress) # Reset state on 0.0 if progress == 0.0: print_progress.prev_progress = 0 print_progress.backwards_progress = False print_progress.done = False # Check for backwards progress if progress < print_progress.prev_progress: print_progress.backwards_progress = True print_progress.prev_progress = progress # print progress bar if not print_progress.done: sys.stdout.write('\r') i = int(progress * 20.0) sys.stdout.write("[%-20s] %3d%%" % ('=' * i, round(progress * 100))) sys.stdout.flush() # Finish on 1.0 if progress >= 1.0: if not print_progress.done: print_progress.done = True sys.stdout.write("\n") if print_progress.backwards_progress: print("Progress went backwards during flash") print_progress.prev_progress = 0 binary_file = os.path.join(parentdir, 'binaries', board.getTestBinary()) with open(binary_file, "rb") as f: data = f.read() data = struct.unpack("%iB" % len(data), data) unused = rom_size - len(data) addr = rom_start size = len(data) # Turn on extra checks for the next 4 tests flash.setFlashAlgoDebug(True) print "\r\n\r\n------ Test Basic Page Erase ------" info = flash.flashBlock(addr, data, False, False, progress_cb=print_progress) data_flashed = target.readBlockMemoryUnaligned8(addr, size) if same(data_flashed, data) and info.program_type is FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Basic Chip Erase ------" info = flash.flashBlock(addr, data, False, True, progress_cb=print_progress) data_flashed = target.readBlockMemoryUnaligned8(addr, size) if same(data_flashed, data) and info.program_type is FLASH_CHIP_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Smart Page Erase ------" info = flash.flashBlock(addr, data, True, False, progress_cb=print_progress) data_flashed = target.readBlockMemoryUnaligned8(addr, size) if same(data_flashed, data) and info.program_type is FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Smart Chip Erase ------" info = flash.flashBlock(addr, data, True, True, progress_cb=print_progress) data_flashed = target.readBlockMemoryUnaligned8(addr, size) if same(data_flashed, data) and info.program_type is FLASH_CHIP_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 flash.setFlashAlgoDebug(False) print "\r\n\r\n------ Test Basic Page Erase (Entire chip) ------" new_data = list(data) new_data.extend(unused * [0x77]) info = flash.flashBlock(0, new_data, False, False, progress_cb=print_progress) if info.program_type == FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 result.page_erase_rate = float(len(new_data)) / float( info.program_time) else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Fast Verify ------" info = flash.flashBlock(0, new_data, progress_cb=print_progress, fast_verify=True) if info.program_type == FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Offset Write ------" addr = rom_start + rom_size / 2 page_size = flash.getPageInfo(addr).size new_data = [0x55] * page_size * 2 info = flash.flashBlock(addr, new_data, progress_cb=print_progress) data_flashed = target.readBlockMemoryUnaligned8(addr, len(new_data)) if same(data_flashed, new_data) and info.program_type is FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Multiple Block Writes ------" addr = rom_start + rom_size / 2 page_size = flash.getPageInfo(addr).size more_data = [0x33] * page_size * 2 addr = (rom_start + rom_size / 2) + 1 #cover multiple pages fb = flash.getFlashBuilder() fb.addData(rom_start, data) fb.addData(addr, more_data) fb.program(progress_cb=print_progress) data_flashed = target.readBlockMemoryUnaligned8(rom_start, len(data)) data_flashed_more = target.readBlockMemoryUnaligned8( addr, len(more_data)) if same(data_flashed, data) and same(data_flashed_more, more_data): print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Overlapping Blocks ------" test_pass = False addr = (rom_start + rom_size / 2) #cover multiple pages page_size = flash.getPageInfo(addr).size new_data = [0x33] * page_size fb = flash.getFlashBuilder() fb.addData(addr, new_data) try: fb.addData(addr + 1, new_data) except ValueError as e: print("Exception: %s" % e) test_pass = True if test_pass: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Empty Block Write ------" # Freebee if nothing asserts fb = flash.getFlashBuilder() fb.program() print("TEST PASSED") test_pass_count += 1 test_count += 1 print "\r\n\r\n------ Test Missing Progress Callback ------" # Freebee if nothing asserts addr = rom_start flash.flashBlock(rom_start, data, True) print("TEST PASSED") test_pass_count += 1 test_count += 1 # Only run test if the reset handler can be programmed (rom start at address 0) if rom_start == 0: print "\r\n\r\n------ Test Non-Thumb reset handler ------" non_thumb_data = list(data) # Clear bit 0 of 2nd word - reset handler non_thumb_data[4] = non_thumb_data[4] & ~1 flash.flashBlock(rom_start, non_thumb_data) flash.flashBlock(rom_start, data) print("TEST PASSED") test_pass_count += 1 test_count += 1 # Note - The decision based tests below are order dependent since they # depend on the previous state of the flash print "\r\n\r\n------ Test Chip Erase Decision ------" new_data = list(data) new_data.extend([0xff] * unused) # Pad with 0xFF info = flash.flashBlock(0, new_data, progress_cb=print_progress) if info.program_type == FLASH_CHIP_ERASE: print("TEST PASSED") test_pass_count += 1 result.chip_erase_rate_erased = float(len(new_data)) / float( info.program_time) else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Chip Erase Decision 2 ------" new_data = list(data) new_data.extend([0x00] * unused) # Pad with 0x00 info = flash.flashBlock(0, new_data, progress_cb=print_progress) if info.program_type == FLASH_CHIP_ERASE: print("TEST PASSED") test_pass_count += 1 result.chip_erase_rate = float(len(new_data)) / float( info.program_time) else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Page Erase Decision ------" new_data = list(data) new_data.extend([0x00] * unused) # Pad with 0x00 info = flash.flashBlock(0, new_data, progress_cb=print_progress) if info.program_type == FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 result.page_erase_rate_same = float(len(new_data)) / float( info.program_time) result.analyze = info.analyze_type result.analyze_time = info.analyze_time result.analyze_rate = float(len(new_data)) / float( info.analyze_time) else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Page Erase Decision 2 ------" new_data = list(data) size_same = unused * 5 / 6 size_differ = unused - size_same new_data.extend([0x00] * size_same) # Pad 5/6 with 0x00 and 1/6 with 0xFF new_data.extend([0x55] * size_differ) info = flash.flashBlock(0, new_data, progress_cb=print_progress) if info.program_type == FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print("\r\n\r\nTest Summary:") print("Pass count %i of %i tests" % (test_pass_count, test_count)) if test_pass_count == test_count: print("FLASH TEST SCRIPT PASSED") else: print("FLASH TEST SCRIPT FAILED") target.reset() result.passed = test_count == test_pass_count return result
def speed_test(board_id): with MbedBoard.chooseBoard(board_id = board_id, frequency = 1000000) as board: target_type = board.getTargetType() test_clock = 10000000 if target_type == "kl25z": ram_start = 0x1ffff000 ram_size = 0x4000 rom_start = 0x00000000 rom_size = 0x20000 elif target_type == "kl28z": ram_start = 0x1fffa000 ram_size = 96*1024 rom_start = 0x00000000 rom_size = 512*1024 elif target_type == "kl46z": ram_start = 0x1fffe000 ram_size = 0x8000 rom_start = 0x00000000 rom_size = 0x40000 elif target_type == "k22f": ram_start = 0x1fff0000 ram_size = 0x20000 rom_start = 0x00000000 rom_size = 0x80000 elif target_type == "k64f": ram_start = 0x1FFF0000 ram_size = 0x40000 rom_start = 0x00000000 rom_size = 0x100000 elif target_type == "lpc11u24": ram_start = 0x10000000 ram_size = 0x2000 rom_start = 0x00000000 rom_size = 0x8000 elif target_type == "lpc1768": ram_start = 0x10000000 ram_size = 0x8000 rom_start = 0x00000000 rom_size = 0x80000 elif target_type == "lpc800": ram_start = 0x10000000 ram_size = 0x1000 rom_start = 0x00000000 rom_size = 0x4000 elif target_type == "lpc4330": ram_start = 0x10000000 ram_size = 0x20000 rom_start = 0x14000000 rom_size = 0x100000 elif target_type == "nrf51": ram_start = 0x20000000 ram_size = 0x4000 rom_start = 0x00000000 rom_size = 0x40000 # Override clock since 10MHz is too fast test_clock = 1000000 elif target_type == "maxwsnenv": ram_start = 0x20000000 ram_size = 0x8000 rom_start = 0x00000000 rom_size = 0x40000 elif target_type == "max32600mbed": ram_start = 0x20000000 ram_size = 0x8000 rom_start = 0x00000000 rom_size = 0x40000 else: raise Exception("The board is not supported by this test script.") target = board.target transport = board.transport flash = board.flash interface = board.interface test_pass_count = 0 test_count = 0 result = SpeedTestResult() transport.setClock(test_clock) transport.setDeferredTransfer(True) print "\r\n\r\n------ TEST USB TRANSFER SPEED ------" max_packets = interface.getPacketCount() data_to_write = [0x80] + [0x00] * 63 start = time() packet_count = USB_TEST_XFER_COUNT while packet_count > 0: interface.write(data_to_write) interface.read() packet_count = packet_count - 1 stop = time() result.usb_speed = USB_TEST_XFER_COUNT * 64 / (stop-start) print "USB transfer rate %f B/s" % result.usb_speed print "\r\n\r\n------ TEST OVERLAPPED USB TRANSFER SPEED ------" max_packets = interface.getPacketCount() print("Concurrent packets: %i" % max_packets) data_to_write = [0x80] + [0x00] * 63 start = time() packet_count = USB_TEST_XFER_COUNT reads_pending = 0 while packet_count > 0 or reads_pending > 0: # Make sure the transmit buffer stays saturated while packet_count > 0 and reads_pending < max_packets: interface.write(data_to_write) packet_count = packet_count - 1 reads_pending = reads_pending + 1 # Read data if reads_pending > 0: interface.read() reads_pending = reads_pending - 1 stop = time() result.usb_overlapped = USB_TEST_XFER_COUNT * 64 / (stop-start) print "USB transfer rate %f B/s" % result.usb_overlapped print "\r\n\r\n------ TEST RAM READ / WRITE SPEED ------" test_addr = ram_start test_size = ram_size data = [randrange(1, 50) for x in range(test_size)] start = time() target.writeBlockMemoryUnaligned8(test_addr, data) stop = time() diff = stop-start result.write_speed = test_size / diff print("Writing %i byte took %s seconds: %s B/s" % (test_size, diff, result.write_speed)) start = time() block = target.readBlockMemoryUnaligned8(test_addr, test_size) stop = time() diff = stop-start result.read_speed = test_size / diff print("Reading %i byte took %s seconds: %s B/s" % (test_size, diff, result.read_speed)) error = False for i in range(len(block)): if (block[i] != data[i]): error = True print "ERROR: 0x%X, 0x%X, 0x%X!!!" % ((addr + i), block[i], data[i]) if error: print "TEST FAILED" else: print "TEST PASSED" test_pass_count += 1 test_count += 1 print "\r\n\r\n------ TEST ROM READ SPEED ------" test_addr = rom_start test_size = rom_size start = time() block = target.readBlockMemoryUnaligned8(test_addr, test_size) stop = time() diff = stop-start print("Reading %i byte took %s seconds: %s B/s" % (test_size, diff, test_size / diff)) print "TEST PASSED" test_pass_count += 1 test_count += 1 target.reset() result.passed = test_count == test_pass_count return result
def test_hid(workspace, parent_test): test_info = parent_test.create_subtest("HID test") board = workspace.board with MbedBoard.chooseBoard(board_id=board.get_unique_id()) as mbed_board: addr = 0 size = 0 target_type = mbed_board.getTargetType() binary_file = workspace.target.bin_path addr_bin = 0x00000000 if target_type == "lpc1768": addr = 0x10000001 size = 0x1102 addr_flash = 0x10000 elif target_type == "lpc11u24": addr = 0x10000001 size = 0x502 addr_flash = 0x4000 elif target_type == "kl25z": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 elif target_type == "kl28z": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 elif target_type == "k64f": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 elif target_type == "k22f": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 elif target_type == "k20d50m": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 elif target_type == "kl46z": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 elif target_type == "kl05z": addr = 0x20000001 size = 0x502 addr_flash = 0x6000 elif target_type == "lpc800": addr = 0x10000001 size = 0x502 addr_flash = 0x2000 elif target_type == "lpc11xx_32": addr = 0x10000001 size = 0x502 addr_flash = 0x4000 elif target_type == "nrf51": addr = 0x20000001 size = 0x502 addr_flash = 0x20000 elif target_type == "lpc4330": addr = 0x10000001 size = 0x1102 addr_flash = 0x14010000 addr_bin = 0x14000000 elif target_type == "maxwsnenv": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 elif target_type == "max32600mbed": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 elif target_type == "w7500": addr = 0x20000001 size = 0x1102 addr_flash = 0x00000000 elif target_type == "lpc824": addr = 0x10000001 size = 0x502 addr_flash = 0x4000 else: raise Exception("A board is not supported by this test script.") target = mbed_board.target flash = mbed_board.flash test_info.info("\r\n\r\n----- FLASH NEW BINARY -----") flash.flashBinary(binary_file, addr_bin) test_info.info("\r\n\r\n------ GET Unique ID ------") test_info.info("Unique ID: %s" % mbed_board.getUniqueID()) test_info.info("\r\n\r\n------ TEST READ / WRITE CORE REGISTER ------") pc = target.readCoreRegister('pc') test_info.info("initial pc: 0x%X" % target.readCoreRegister('pc')) # write in pc dummy value target.writeCoreRegister('pc', 0x3D82) test_info.info("now pc: 0x%X" % target.readCoreRegister('pc')) # write initial pc value target.writeCoreRegister('pc', pc) test_info.info("initial pc value rewritten: 0x%X" % target.readCoreRegister('pc')) msp = target.readCoreRegister('msp') psp = target.readCoreRegister('psp') test_info.info("MSP = 0x%08x; PSP = 0x%08x" % (msp, psp)) control = target.readCoreRegister('control') faultmask = target.readCoreRegister('faultmask') basepri = target.readCoreRegister('basepri') primask = target.readCoreRegister('primask') test_info.info("CONTROL = 0x%02x; FAULTMASK = 0x%02x; BASEPRI = 0x%02x; PRIMASK = 0x%02x" % (control, faultmask, basepri, primask)) target.writeCoreRegister('primask', 1) newPrimask = target.readCoreRegister('primask') test_info.info("New PRIMASK = 0x%02x" % newPrimask) target.writeCoreRegister('primask', primask) newPrimask = target.readCoreRegister('primask') test_info.info("Restored PRIMASK = 0x%02x" % newPrimask) if target.has_fpu: s0 = target.readCoreRegister('s0') test_info.info("S0 = %g (0x%08x)" % (s0, float32beToU32be(s0))) target.writeCoreRegister('s0', math.pi) newS0 = target.readCoreRegister('s0') test_info.info("New S0 = %g (0x%08x)" % (newS0, float32beToU32be(newS0))) target.writeCoreRegister('s0', s0) newS0 = target.readCoreRegister('s0') test_info.info("Restored S0 = %g (0x%08x)" % (newS0, float32beToU32be(newS0))) test_info.info("\r\n\r\n------ TEST HALT / RESUME ------") test_info.info("resume") target.resume() sleep(0.2) test_info.info("halt") target.halt() test_info.info("HALT: pc: 0x%X" % target.readCoreRegister('pc')) sleep(0.2) test_info.info("\r\n\r\n------ TEST STEP ------") test_info.info("reset and halt") target.resetStopOnReset() currentPC = target.readCoreRegister('pc') test_info.info("HALT: pc: 0x%X" % currentPC) sleep(0.2) for i in range(4): test_info.info("step") target.step() newPC = target.readCoreRegister('pc') test_info.info("STEP: pc: 0x%X" % newPC) currentPC = newPC sleep(0.2) test_info.info("\r\n\r\n------ TEST READ / WRITE MEMORY ------") target.halt() test_info.info("READ32/WRITE32") val = randrange(0, 0xffffffff) test_info.info("write32 0x%X at 0x%X" % (val, addr)) target.writeMemory(addr, val) res = target.readMemory(addr) test_info.info("read32 at 0x%X: 0x%X" % (addr, res)) if res != val: test_info.failure("ERROR in READ/WRITE 32") test_info.info("\r\nREAD16/WRITE16") val = randrange(0, 0xffff) test_info.info("write16 0x%X at 0x%X" % (val, addr + 2)) target.writeMemory(addr + 2, val, 16) res = target.readMemory(addr + 2, 16) test_info.info("read16 at 0x%X: 0x%X" % (addr + 2, res)) if res != val: test_info.failure("ERROR in READ/WRITE 16") test_info.info("\r\nREAD8/WRITE8") val = randrange(0, 0xff) test_info.info("write8 0x%X at 0x%X" % (val, addr + 1)) target.writeMemory(addr + 1, val, 8) res = target.readMemory(addr + 1, 8) test_info.info("read8 at 0x%X: 0x%X" % (addr + 1, res)) if res != val: test_info.failure("ERROR in READ/WRITE 8") test_info.info("\r\n\r\n------ TEST READ / WRITE MEMORY BLOCK ------") data = [randrange(1, 50) for _ in range(size)] target.writeBlockMemoryUnaligned8(addr, data) block = target.readBlockMemoryUnaligned8(addr, size) error = False for i in range(len(block)): if (block[i] != data[i]): error = True test_info.info("ERROR: 0x%X, 0x%X, 0x%X!!!" % ((addr + i), block[i], data[i])) if error: test_info.failure("TEST FAILED") else: test_info.info("TEST PASSED") test_info.info("\r\n\r\n------ TEST RESET ------") target.reset() sleep(0.1) target.halt() for i in range(5): target.step() test_info.info("pc: 0x%X" % target.readCoreRegister('pc')) test_info.info("\r\n\r\n------ TEST PROGRAM/ERASE PAGE ------") # Fill 3 pages with 0x55 page_size = flash.getPageInfo(addr_flash).size fill = [0x55] * page_size flash.init() for i in range(0, 3): address = addr_flash + page_size * i # Test only supports a location with 3 aligned # pages of the same size current_page_size = flash.getPageInfo(addr_flash).size assert page_size == current_page_size assert address % current_page_size == 0 flash.erasePage(address) flash.programPage(address, fill) # Erase the middle page flash.erasePage(addr_flash + page_size) # Verify the 1st and 3rd page were not erased, and that # the 2nd page is fully erased data = target.readBlockMemoryUnaligned8(addr_flash, page_size * 3) expected = fill + [0xFF] * page_size + fill if data == expected: test_info.info("TEST PASSED") else: test_info.failure("TEST FAILED") test_info.info("\r\n\r\n----- Restoring image -----") flash.flashBinary(binary_file, addr_bin) target.reset() test_info.info("HID test complete")
def cortex_test(board_id): with MbedBoard.chooseBoard(board_id=board_id, frequency=1000000) as board: target_type = board.getTargetType() binary_file = os.path.join(parentdir, "binaries", board.getTestBinary()) test_clock = 10000000 addr_invalid = 0x3E000000 # Last 16MB of ARM SRAM region - typically empty if target_type == "nrf51": # Override clock since 10MHz is too fast test_clock = 1000000 memory_map = board.target.getMemoryMap() ram_regions = [region for region in memory_map if region.type == "ram"] ram_region = ram_regions[0] rom_region = memory_map.getBootMemory() addr = ram_region.start + 1 size = 0x502 addr_bin = rom_region.start target = board.target link = board.link flash = board.flash link.set_clock(test_clock) link.set_deferred_transfer(True) test_pass_count = 0 test_count = 0 result = CortexTestResult() print "\r\n\r\n----- FLASH NEW BINARY BEFORE TEST -----" flash.flashBinary(binary_file, addr_bin) # Let the target run for a bit so it # can initialize the watchdog if it needs to target.resume() sleep(0.2) target.halt() print "PROGRAMMING COMPLETE" print "\r\n\r\n----- TESTING CORTEX-M PERFORMANCE -----" test_time = test_function(board, target.getTResponse) print ("Function getTResponse time: %f" % test_time) # Step test_time = test_function(board, target.step) print ("Function step time: %f" % test_time) # Breakpoint def set_remove_breakpoint(): target.setBreakpoint(0) target.removeBreakpoint(0) test_time = test_function(board, set_remove_breakpoint) print ("Add and remove breakpoint: %f" % test_time) # getRegisterContext test_time = test_function(board, target.getRegisterContext) print ("Function getRegisterContext: %f" % test_time) # setRegisterContext context = target.getRegisterContext() def set_register_context(): target.setRegisterContext(context) test_time = test_function(board, set_register_context) print ("Function setRegisterContext: %f" % test_time) # Run / Halt def run_halt(): target.resume() target.halt() test_time = test_function(board, run_halt) print ("Resume and halt: %f" % test_time) # GDB stepping def simulate_step(): target.step() target.getTResponse() target.setBreakpoint(0) target.resume() target.halt() target.getTResponse() target.removeBreakpoint(0) test_time = test_function(board, simulate_step) print ("Simulated GDB step: %f" % test_time) # Test passes if there are no exceptions test_pass_count += 1 test_count += 1 print ("TEST PASSED") print "\r\n\r\n------ Testing Invalid Memory Access Recovery ------" memory_access_pass = True try: target.readBlockMemoryUnaligned8(addr_invalid, 0x1000) target.flush() # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0 if target_type != "nrf51": memory_access_pass = False except DAPAccess.TransferFaultError: pass try: target.readBlockMemoryUnaligned8(addr_invalid + 1, 0x1000) target.flush() # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0 if target_type != "nrf51": memory_access_pass = False except DAPAccess.TransferFaultError: pass data = [0x00] * 0x1000 try: target.writeBlockMemoryUnaligned8(addr_invalid, data) target.flush() # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0 if target_type != "nrf51": memory_access_pass = False except DAPAccess.TransferFaultError: pass data = [0x00] * 0x1000 try: target.writeBlockMemoryUnaligned8(addr_invalid + 1, data) target.flush() # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0 if target_type != "nrf51": memory_access_pass = False except DAPAccess.TransferFaultError: pass data = [randrange(0, 255) for x in range(size)] target.writeBlockMemoryUnaligned8(addr, data) block = target.readBlockMemoryUnaligned8(addr, size) if same(data, block): print "Aligned access pass" else: print ("Memory read does not match memory written") memory_access_pass = False data = [randrange(0, 255) for x in range(size)] target.writeBlockMemoryUnaligned8(addr + 1, data) block = target.readBlockMemoryUnaligned8(addr + 1, size) if same(data, block): print "Unaligned access pass" else: print ("Unaligned memory read does not match memory written") memory_access_pass = False test_count += 1 if memory_access_pass: test_pass_count += 1 print "TEST PASSED" else: print "TEST FAILED" target.reset() result.passed = test_count == test_pass_count return result
from pyOCD.board import MbedBoard #specific board used for OCD by setting board_id = '<board id of OCD reported by mbedls command>'. If you set to None, then it will search for one and ask for confirmation. board_id = '10500000e062eef000000000000000000000000097969902' #board_id = None RIPPED_FILE = "rom.bin" # name given to rom ripped from device with MbedBoard.chooseBoard(target_override='k20d50m', board_id=board_id) as board: addr = 0x00000000 size = 128 * 1024 # K20 has 128 KB of flash. 1024 converts to KB data = board.target.readBlockMemoryUnaligned8(addr, size) data = bytearray(data) with open(RIPPED_FILE, 'wb') as f: f.write(data) print("Dump success. File " + RIPPED_FILE + " created")
def configure_board(maincfg, target): # retrieve all connected mbed boards mbed_ls = mbed_lstools.create() connected_boards = mbed_ls.list_mbeds() if not connected_boards: print("Error: no mbed boards found.", file=sys.stderr) exit(1) mbed_board_info = None if target.board.auto: # select the first mbed board found that match the selected platform for connected_board in connected_boards: if connected_board['platform_name'].upper( ) == target.platform.upper(): mbed_board_info = connected_board if not mbed_board_info: print("Error: no {0} board found ".format(target.platform), file=sys.stderr) exit(1) else: # use the specified targetid to select the board for connected_board in connected_boards: if target.board.target_id == connected_board['target_id']: mbed_board_info = connected_board break if not mbed_board_info: print("Error: no mbed board found with target_id {0}".format( target.board.target_id), file=sys.stderr) exit(1) if target.platform.upper() != mbed_board_info['platform_name']: print("Error: platform mismatch ({0}, {1})".format( target.platform, mbed_board_info["platform_name"])) exit(1) # print board info print("Using {0} board - serial port: {1}.".format( mbed_board_info['platform_name'], mbed_board_info['serial_port'])) # connect to the mbed board mbed_board = MbedBoard.chooseBoard( board_id=mbed_board_info["target_id_usb_id"], init_board=True) # flash the binary if specified if target.board.flash: binfile = os.path.join(maincfg.project[target.platform].path, maincfg.project[target.platform].bin_path, maincfg.project.bin_file) try: print("Flash binary {0}...".format(binfile), file=sys.stderr) mbed_board.target.resume() mbed_board.target.halt() mbed_board.flash.flashBinary(binfile) except IOError as e: print("{0}: {1}".format(binfile, e.strerror), file=sys.stderr) exit(1) # reset target board mbed_board.target.reset() mbed_board.uninit() return mbed_board_info
def basic_test(board_id, file): with MbedBoard.chooseBoard(board_id=board_id) as board: addr = 0 size = 0 f = None binary_file = "l1_" target_type = board.getTargetType() if file is None: binary_file = os.path.join(parentdir, 'binaries', board.getTestBinary()) else: binary_file = file print("binary file: %s" % binary_file) memory_map = board.target.getMemoryMap() ram_regions = [region for region in memory_map if region.type == 'ram'] ram_region = ram_regions[0] rom_region = memory_map.getBootMemory() addr = ram_region.start + 1 size = 0x502 addr_bin = rom_region.start addr_flash = rom_region.start + rom_region.length // 2 target = board.target link = board.link flash = board.flash print("\n\n------ GET Unique ID ------") print("Unique ID: %s" % board.getUniqueID()) print("\n\n------ TEST READ / WRITE CORE REGISTER ------") pc = target.readCoreRegister('pc') print("initial pc: 0x%X" % target.readCoreRegister('pc')) # write in pc dummy value target.writeCoreRegister('pc', 0x3D82) print("now pc: 0x%X" % target.readCoreRegister('pc')) # write initial pc value target.writeCoreRegister('pc', pc) print("initial pc value rewritten: 0x%X" % target.readCoreRegister('pc')) msp = target.readCoreRegister('msp') psp = target.readCoreRegister('psp') print("MSP = 0x%08x; PSP = 0x%08x" % (msp, psp)) control = target.readCoreRegister('control') faultmask = target.readCoreRegister('faultmask') basepri = target.readCoreRegister('basepri') primask = target.readCoreRegister('primask') print( "CONTROL = 0x%02x; FAULTMASK = 0x%02x; BASEPRI = 0x%02x; PRIMASK = 0x%02x" % (control, faultmask, basepri, primask)) target.writeCoreRegister('primask', 1) newPrimask = target.readCoreRegister('primask') print("New PRIMASK = 0x%02x" % newPrimask) target.writeCoreRegister('primask', primask) newPrimask = target.readCoreRegister('primask') print("Restored PRIMASK = 0x%02x" % newPrimask) if target.has_fpu: s0 = target.readCoreRegister('s0') print("S0 = %g (0x%08x)" % (s0, float32beToU32be(s0))) target.writeCoreRegister('s0', math.pi) newS0 = target.readCoreRegister('s0') print("New S0 = %g (0x%08x)" % (newS0, float32beToU32be(newS0))) target.writeCoreRegister('s0', s0) newS0 = target.readCoreRegister('s0') print("Restored S0 = %g (0x%08x)" % (newS0, float32beToU32be(newS0))) print("\n\n------ TEST HALT / RESUME ------") print("resume") target.resume() sleep(0.2) print("halt") target.halt() print("HALT: pc: 0x%X" % target.readCoreRegister('pc')) sleep(0.2) print("\n\n------ TEST STEP ------") print("reset and halt") target.resetStopOnReset() currentPC = target.readCoreRegister('pc') print("HALT: pc: 0x%X" % currentPC) sleep(0.2) for i in range(4): print("step") target.step() newPC = target.readCoreRegister('pc') print("STEP: pc: 0x%X" % newPC) currentPC = newPC sleep(0.2) print("\n\n------ TEST READ / WRITE MEMORY ------") target.halt() print("READ32/WRITE32") val = randrange(0, 0xffffffff) print("write32 0x%X at 0x%X" % (val, addr)) target.writeMemory(addr, val) res = target.readMemory(addr) print("read32 at 0x%X: 0x%X" % (addr, res)) if res != val: print("ERROR in READ/WRITE 32") print("\nREAD16/WRITE16") val = randrange(0, 0xffff) print("write16 0x%X at 0x%X" % (val, addr + 2)) target.writeMemory(addr + 2, val, 16) res = target.readMemory(addr + 2, 16) print("read16 at 0x%X: 0x%X" % (addr + 2, res)) if res != val: print("ERROR in READ/WRITE 16") print("\nREAD8/WRITE8") val = randrange(0, 0xff) print("write8 0x%X at 0x%X" % (val, addr + 1)) target.writeMemory(addr + 1, val, 8) res = target.readMemory(addr + 1, 8) print("read8 at 0x%X: 0x%X" % (addr + 1, res)) if res != val: print("ERROR in READ/WRITE 8") print("\n\n------ TEST READ / WRITE MEMORY BLOCK ------") data = [randrange(1, 50) for x in range(size)] target.writeBlockMemoryUnaligned8(addr, data) block = target.readBlockMemoryUnaligned8(addr, size) error = False for i in range(len(block)): if (block[i] != data[i]): error = True print("ERROR: 0x%X, 0x%X, 0x%X!!!" % ((addr + i), block[i], data[i])) if error: print("TEST FAILED") else: print("TEST PASSED") print("\n\n------ TEST RESET ------") target.reset() sleep(0.1) target.halt() for i in range(5): target.step() print("pc: 0x%X" % target.readCoreRegister('pc')) print("\n\n------ TEST PROGRAM/ERASE PAGE ------") # Fill 3 pages with 0x55 page_size = flash.getPageInfo(addr_flash).size fill = [0x55] * page_size flash.init() for i in range(0, 3): address = addr_flash + page_size * i # Test only supports a location with 3 aligned # pages of the same size current_page_size = flash.getPageInfo(addr_flash).size assert page_size == current_page_size assert address % current_page_size == 0 flash.erasePage(address) flash.programPage(address, fill) # Erase the middle page flash.erasePage(addr_flash + page_size) # Verify the 1st and 3rd page were not erased, and that the 2nd page is fully erased data = target.readBlockMemoryUnaligned8(addr_flash, page_size * 3) expected = fill + [0xFF] * page_size + fill if data == expected: print("TEST PASSED") else: print("TEST FAILED") print("\n\n----- FLASH NEW BINARY -----") flash.flashBinary(binary_file, addr_bin) target.reset()
) parser.add_option("-t", "--target", dest="target_override", default=None, help="Override target to debug") (option, args) = parser.parse_args() gdb = None level = LEVELS.get(option.debug_level, logging.NOTSET) logging.basicConfig(level=level) if option.list_all == True: MbedBoard.listConnectedBoards() else: try: board_selected = MbedBoard.chooseBoard( board_id=option.board_id, target_override=option.target_override) if board_selected != None: try: gdb = GDBServer(board_selected, int(option.port_number)) while gdb.isAlive(): gdb.join(timeout=0.5) except ValueError: logging.error("Port number error!") except KeyboardInterrupt: if gdb != None: gdb.stop() except Exception as e: print "uncaught exception: %s" % e traceback.print_exc() if gdb != None: gdb.stop()
def run(self): try: # Read command-line arguments. self.args = self.get_args() self.cmd = self.args.cmd if self.cmd: self.cmd = self.cmd.lower() # Set logging level self.configure_logging() DAPAccess.set_args(self.args.daparg) # Check for a valid command. if self.cmd and self.cmd not in self.command_list: print "Error: unrecognized command '%s'" % self.cmd return 1 # Handle certain commands without connecting. if self.cmd == 'list': self.handle_list([]) return 0 elif self.cmd == 'help': self.handle_help(self.args.args) return 0 if self.args.clock != DEFAULT_CLOCK_FREQ_KHZ: print "Setting SWD clock to %d kHz" % self.args.clock # Connect to board. self.board = MbedBoard.chooseBoard(board_id=self.args.board, target_override=self.args.target, init_board=False, frequency=(self.args.clock * 1000)) self.board.target.setAutoUnlock(False) self.board.target.setHaltOnConnect(False) try: if not self.args.no_init: self.board.init() except DAPAccess.TransferFaultError as e: if not self.board.target.isLocked(): print "Transfer fault while initing board: %s" % e traceback.print_exc() self.exitCode = 1 return self.exitCode except Exception as e: print "Exception while initing board: %s" % e traceback.print_exc() self.exitCode = 1 return self.exitCode self.target = self.board.target self.link = self.board.link self.flash = self.board.flash self.svd_device = self.target.svd_device self.peripherals = {} if self.svd_device: for p in self.svd_device.peripherals: self.peripherals[p.name.lower()] = p # Halt if requested. if self.args.halt: self.handle_halt([]) # Handle a device with flash security enabled. self.didErase = False if not self.args.no_init and self.target.isLocked() and self.cmd != 'unlock': print "Warning: Target is locked, limited operations available. Use unlock command to mass erase and unlock." # If no command, enter interactive mode. if not self.cmd: if not self.args.no_init: try: # Say what we're connected to. print "Connected to %s [%s]: %s" % (self.target.part_number, CORE_STATUS_DESC[self.target.getState()], self.board.getUniqueID()) except DAPAccess.TransferFaultError: pass # Run the command line. console = PyOCDConsole(self) console.run() else: # Invoke action handler. result = self.command_list[self.cmd](self.args.args) if result is not None: self.exitCode = result except ToolExitException: self.exitCode = 0 except ValueError: print "Error: invalid argument" except DAPAccess.TransferError: print "Error: transfer failed" traceback.print_exc() self.exitCode = 2 except ToolError as e: print "Error:", e self.exitCode = 1 finally: if self.board != None: # Pass false to prevent target resume. self.board.uninit(False) return self.exitCode
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 cortex_test(board_id): with MbedBoard.chooseBoard(board_id = board_id, frequency = 1000000) as board: addr = 0 size = 0 f = None binary_file = "l1_" target_type = board.getTargetType() binary_file = os.path.join(parentdir, 'binaries', board.getTestBinary()) addr_bin = 0x00000000 test_clock = 10000000 addr_invalid = 0x3E000000 # Last 16MB of ARM SRAM region - typically empty if target_type == "lpc1768": addr = 0x10000000 size = 0x1102 addr_flash = 0x10000 elif target_type == "lpc11u24": addr = 0x10000000 size = 0x502 addr_flash = 0x4000 elif target_type == "kl25z": addr = 0x20000000 size = 0x502 addr_flash = 0x10000 elif target_type == "kl28z": addr = 0x20000000 size = 0x502 addr_flash = 0x10000 elif target_type == "k64f": addr = 0x20000000 size = 0x502 addr_flash = 0x10000 elif target_type == "k22f": addr = 0x20000000 size = 0x502 addr_flash = 0x10000 elif target_type == "k20d50m": addr = 0x20000000 size = 0x502 addr_flash = 0x10000 elif target_type == "kl46z": addr = 0x20000000 size = 0x502 addr_flash = 0x10000 elif target_type == "lpc800": addr = 0x10000000 size = 0x502 addr_flash = 0x2000 elif target_type == "nrf51": addr = 0x20000000 size = 0x502 addr_flash = 0x20000 # Override clock since 10MHz is too fast test_clock = 1000000 elif target_type == "lpc4330": addr = 0x10000000 size = 0x1102 addr_flash = 0x14010000 addr_bin = 0x14000000 elif target_type == "maxwsnenv": addr = 0x20000000 size = 0x502 addr_flash = 0x10000 elif target_type == "max32600mbed": addr = 0x20000000 size = 0x502 addr_flash = 0x10000 elif target_type == "w7500": addr = 0x20000000 size = 0x1102 addr_flash = 0x00000000 else: raise Exception("A board is not supported by this test script.") target = board.target transport = board.transport flash = board.flash transport.setClock(test_clock) transport.setDeferredTransfer(True) test_pass_count = 0 test_count = 0 result = CortexTestResult() print "\r\n\r\n----- FLASH NEW BINARY BEFORE TEST -----" flash.flashBinary(binary_file, addr_bin) # Let the target run for a bit so it # can initialize the watchdog if it needs to target.resume() sleep(0.2) target.halt() print "PROGRAMMING COMPLETE" print "\r\n\r\n----- TESTING CORTEX-M PERFORMANCE -----" test_time = test_function(board, target.getTResponse) print("Function getTResponse time: %f" % test_time) # Step test_time = test_function(board, target.step) print("Function step time: %f" % test_time) # Breakpoint def set_remove_breakpoint(): target.setBreakpoint(0) target.removeBreakpoint(0) test_time = test_function(board, set_remove_breakpoint) print("Add and remove breakpoint: %f" % test_time) # getRegisterContext test_time = test_function(board, target.getRegisterContext) print("Function getRegisterContext: %f" % test_time) # setRegisterContext context = target.getRegisterContext() def set_register_context(): target.setRegisterContext(context) test_time = test_function(board, set_register_context) print("Function setRegisterContext: %f" % test_time) # Run / Halt def run_halt(): target.resume() target.halt() test_time = test_function(board, run_halt) print("Resume and halt: %f" % test_time) # GDB stepping def simulate_step(): target.step() target.getTResponse() target.setBreakpoint(0) target.resume() target.halt() target.getTResponse() target.removeBreakpoint(0) test_time = test_function(board, simulate_step) print("Simulated GDB step: %f" % test_time) # Test passes if there are no exceptions test_pass_count += 1 test_count += 1 print("TEST PASSED") print "\r\n\r\n------ Testing Invalid Memory Access Recovery ------" memory_access_pass = True try: target.readBlockMemoryUnaligned8(addr_invalid, 0x1000) target.flush() # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0 if target_type != "nrf51": memory_access_pass = False except TransferError: pass try: target.readBlockMemoryUnaligned8(addr_invalid + 1, 0x1000) target.flush() # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0 if target_type != "nrf51": memory_access_pass = False except TransferError: pass data = [0x00] * 0x1000 try: target.writeBlockMemoryUnaligned8(addr_invalid, data) target.flush() # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0 if target_type != "nrf51": memory_access_pass = False except TransferError: pass data = [0x00] * 0x1000 try: target.writeBlockMemoryUnaligned8(addr_invalid + 1, data) target.flush() # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0 if target_type != "nrf51": memory_access_pass = False except TransferError: pass data = [randrange(0, 255) for x in range(size)] target.writeBlockMemoryUnaligned8(addr, data) block = target.readBlockMemoryUnaligned8(addr, size) if same(data, block): print "Aligned access pass" else: print("Memory read does not match memory written") memory_access_pass = False data = [randrange(0, 255) for x in range(size)] target.writeBlockMemoryUnaligned8(addr + 1, data) block = target.readBlockMemoryUnaligned8(addr + 1, size) if same(data, block): print "Unaligned access pass" else: print("Unaligned memory read does not match memory written") memory_access_pass = False test_count += 1 if memory_access_pass: test_pass_count += 1 print "TEST PASSED" else: print "TEST FAILED" target.reset() result.passed = test_count == test_pass_count return result
def cortex_test(board_id): with MbedBoard.chooseBoard(board_id=board_id, frequency=1000000) as board: target_type = board.getTargetType() binary_file = os.path.join(parentdir, 'binaries', board.getTestBinary()) test_clock = 10000000 addr_invalid = 0x3E000000 # Last 16MB of ARM SRAM region - typically empty 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 memory_map = board.target.getMemoryMap() ram_regions = [region for region in memory_map if region.type == 'ram'] ram_region = ram_regions[0] rom_region = memory_map.getBootMemory() addr = ram_region.start + 1 size = 0x502 addr_bin = rom_region.start target = board.target link = board.link flash = board.flash link.set_clock(test_clock) link.set_deferred_transfer(True) test_pass_count = 0 test_count = 0 result = CortexTestResult() print "\r\n\r\n----- FLASH NEW BINARY BEFORE TEST -----" flash.flashBinary(binary_file, addr_bin) # Let the target run for a bit so it # can initialize the watchdog if it needs to target.resume() sleep(0.2) target.halt() print "PROGRAMMING COMPLETE" print "\r\n\r\n----- TESTING CORTEX-M PERFORMANCE -----" test_time = test_function(board, target.getTResponse) print("Function getTResponse time: %f" % test_time) # Step test_time = test_function(board, target.step) print("Function step time: %f" % test_time) # Breakpoint def set_remove_breakpoint(): target.setBreakpoint(0) target.removeBreakpoint(0) test_time = test_function(board, set_remove_breakpoint) print("Add and remove breakpoint: %f" % test_time) # getRegisterContext test_time = test_function(board, target.getRegisterContext) print("Function getRegisterContext: %f" % test_time) # setRegisterContext context = target.getRegisterContext() def set_register_context(): target.setRegisterContext(context) test_time = test_function(board, set_register_context) print("Function setRegisterContext: %f" % test_time) # Run / Halt def run_halt(): target.resume() target.halt() test_time = test_function(board, run_halt) print("Resume and halt: %f" % test_time) # GDB stepping def simulate_step(): target.step() target.getTResponse() target.setBreakpoint(0) target.resume() target.halt() target.getTResponse() target.removeBreakpoint(0) test_time = test_function(board, simulate_step) print("Simulated GDB step: %f" % test_time) # Test passes if there are no exceptions test_pass_count += 1 test_count += 1 print("TEST PASSED") print "\r\n\r\n------ Testing Invalid Memory Access Recovery ------" memory_access_pass = True try: target.readBlockMemoryUnaligned8(addr_invalid, 0x1000) target.flush() # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0 if target_type != "nrf51": memory_access_pass = False except DAPAccess.TransferFaultError: pass try: target.readBlockMemoryUnaligned8(addr_invalid + 1, 0x1000) target.flush() # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0 if target_type != "nrf51": memory_access_pass = False except DAPAccess.TransferFaultError: pass data = [0x00] * 0x1000 try: target.writeBlockMemoryUnaligned8(addr_invalid, data) target.flush() # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0 if target_type != "nrf51": memory_access_pass = False except DAPAccess.TransferFaultError: pass data = [0x00] * 0x1000 try: target.writeBlockMemoryUnaligned8(addr_invalid + 1, data) target.flush() # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0 if target_type != "nrf51": memory_access_pass = False except DAPAccess.TransferFaultError: pass data = [randrange(0, 255) for x in range(size)] target.writeBlockMemoryUnaligned8(addr, data) block = target.readBlockMemoryUnaligned8(addr, size) if same(data, block): print "Aligned access pass" else: print("Memory read does not match memory written") memory_access_pass = False data = [randrange(0, 255) for x in range(size)] target.writeBlockMemoryUnaligned8(addr + 1, data) block = target.readBlockMemoryUnaligned8(addr + 1, size) if same(data, block): print "Unaligned access pass" else: print("Unaligned memory read does not match memory written") memory_access_pass = False test_count += 1 if memory_access_pass: test_pass_count += 1 print "TEST PASSED" else: print "TEST FAILED" print "\r\n\r\n------ Testing Software Breakpoints ------" test_passed = True orig8x2 = target.readBlockMemoryUnaligned8(addr, 2) orig8 = target.read8(addr) orig16 = target.read16(addr & ~1) orig32 = target.read32(addr & ~3) origAligned32 = target.readBlockMemoryAligned32(addr & ~3, 1) def test_filters(): test_passed = True filtered = target.readBlockMemoryUnaligned8(addr, 2) if same(orig8x2, filtered): print "2 byte unaligned passed" else: print "2 byte unaligned failed (read %x-%x, expected %x-%x)" % (filtered[0], filtered[1], orig8x2[0], orig8x2[1]) test_passed = False for now in (True, False): filtered = target.read8(addr, now) if not now: filtered = filtered() if filtered == orig8: print "8-bit passed [now=%s]" % now else: print "8-bit failed [now=%s] (read %x, expected %x)" % (now, filtered, orig8) test_passed = False filtered = target.read16(addr & ~1, now) if not now: filtered = filtered() if filtered == orig16: print "16-bit passed [now=%s]" % now else: print "16-bit failed [now=%s] (read %x, expected %x)" % (now, filtered, orig16) test_passed = False filtered = target.read32(addr & ~3, now) if not now: filtered = filtered() if filtered == orig32: print "32-bit passed [now=%s]" % now else: print "32-bit failed [now=%s] (read %x, expected %x)" % (now, filtered, orig32) test_passed = False filtered = target.readBlockMemoryAligned32(addr & ~3, 1) if same(filtered, origAligned32): print "32-bit aligned passed" else: print "32-bit aligned failed (read %x, expected %x)" % (filtered[0], origAligned32[0]) test_passed = False return test_passed print "Installed software breakpoint at 0x%08x" % addr target.setBreakpoint(addr, pyOCD.target.target.Target.BREAKPOINT_SW) test_passed = test_filters() and test_passed print "Removed software breakpoint" target.removeBreakpoint(addr) test_passed = test_filters() and test_passed test_count += 1 if test_passed: test_pass_count += 1 print "TEST PASSED" else: print "TEST FAILED" target.reset() result.passed = test_count == test_pass_count return result
def speed_test(board_id): with MbedBoard.chooseBoard(board_id=board_id, frequency=1000000) as board: target_type = board.getTargetType() test_clock = 10000000 if target_type == "nrf51": # Override clock since 10MHz is too fast test_clock = 1000000 memory_map = board.target.getMemoryMap() ram_regions = [region for region in memory_map if region.type == "ram"] ram_region = ram_regions[0] rom_region = memory_map.getBootMemory() ram_start = ram_region.start ram_size = ram_region.length rom_start = rom_region.start rom_size = rom_region.length target = board.target link = board.link test_pass_count = 0 test_count = 0 result = SpeedTestResult() link.set_clock(test_clock) link.set_deferred_transfer(True) print("\r\n\r\n------ TEST RAM READ / WRITE SPEED ------") test_addr = ram_start test_size = ram_size data = [randrange(1, 50) for x in range(test_size)] start = time() target.writeBlockMemoryUnaligned8(test_addr, data) target.flush() stop = time() diff = stop - start result.write_speed = test_size / diff print("Writing %i byte took %s seconds: %s B/s" % (test_size, diff, result.write_speed)) start = time() block = target.readBlockMemoryUnaligned8(test_addr, test_size) target.flush() stop = time() diff = stop - start result.read_speed = test_size / diff print("Reading %i byte took %s seconds: %s B/s" % (test_size, diff, result.read_speed)) error = False for i in range(len(block)): if block[i] != data[i]: error = True print("ERROR: 0x%X, 0x%X, 0x%X!!!" % ((addr + i), block[i], data[i])) if error: print("TEST FAILED") else: print("TEST PASSED") test_pass_count += 1 test_count += 1 print("\r\n\r\n------ TEST ROM READ SPEED ------") test_addr = rom_start test_size = rom_size start = time() block = target.readBlockMemoryUnaligned8(test_addr, test_size) target.flush() stop = time() diff = stop - start print("Reading %i byte took %s seconds: %s B/s" % (test_size, diff, test_size / diff)) print("TEST PASSED") test_pass_count += 1 test_count += 1 target.reset() result.passed = test_count == test_pass_count return result
from pyOCD.board import MbedBoard #specific board used for OCD by setting board_id = '<board id of OCD reported by mbedls command>'. If you set to None, then it will search for one and ask for confirmation. board_id = '10500000e062eef000000000000000000000000097969902' #board_id = None RECOVERY_FILE = "rom.bin" # binary to write onto device # to flash bootloader/interface firmware, set target_override='k20d50m'. To flash application firmware to target, set target_override='<target board type>'. with MbedBoard.chooseBoard(target_override='k20d50m', board_id=board_id, frequency=10000000) as board: print("Flashing " + RECOVERY_FILE + " to target") board.flash.flashBinary(RECOVERY_FILE) print("Recovery successful")
def test_gdb(board_id=None): result = GdbTestResult() with MbedBoard.chooseBoard(board_id=board_id) as board: memory_map = board.target.getMemoryMap() ram_regions = [region for region in memory_map if region.type == 'ram'] ram_region = ram_regions[0] rom_region = memory_map.getBootMemory() target_type = board.getTargetType() binary_file = os.path.join(parentdir, 'binaries', board.getTestBinary()) if board_id is None: board_id = board.getUniqueID() test_clock = 10000000 test_port = 3334 error_on_invalid_access = True # Hardware breakpoints are not supported above 0x20000000 on # CortexM devices ignore_hw_bkpt_result = 1 if ram_region.start >= 0x20000000 else 0 if target_type == "nrf51": # Override clock since 10MHz is too fast test_clock = 1000000 # Reading invalid ram returns 0 or nrf51 error_on_invalid_access = False # Program with initial test image board.flash.flashBinary(binary_file, rom_region.start) board.uninit(False) # Write out the test configuration test_params = {} test_params["rom_start"] = rom_region.start test_params["rom_length"] = rom_region.length test_params["ram_start"] = ram_region.start test_params["ram_length"] = ram_region.length test_params["invalid_start"] = 0xffff0000 test_params["invalid_length"] = 0x1000 test_params["expect_error_on_invalid_access"] = error_on_invalid_access test_params["ignore_hw_bkpt_result"] = ignore_hw_bkpt_result with open(TEST_PARAM_FILE, "wb") as f: f.write(json.dumps(test_params)) # Run the test gdb = [PYTHON_GDB, "--command=gdb_script.py"] with open("output.txt", "wb") as f: program = Popen(gdb, stdin=PIPE, stdout=f, stderr=STDOUT) args = ['-p=%i' % test_port, "-f=%i" % test_clock, "-b=%s" % board_id] server = GDBServerTool() server.run(args) program.wait() # Read back the result with open(TEST_RESULT_FILE, "rb") as f: test_result = json.loads(f.read()) # Print results if set(TEST_RESULT_KEYS).issubset(test_result): print("----------------Test Results----------------") print("HW breakpoint count: %s" % test_result["breakpoint_count"]) print("Watchpoint count: %s" % test_result["watchpoint_count"]) print("Average instruction step time: %s" % test_result["step_time_si"]) print("Average single step time: %s" % test_result["step_time_s"]) print("Average over step time: %s" % test_result["step_time_n"]) print("Failure count: %i" % test_result["fail_count"]) result.passed = test_result["fail_count"] == 0 else: result.passed = False # Cleanup os.remove(TEST_RESULT_FILE) os.remove(TEST_PARAM_FILE) return result
parser.add_option("-d", "--debug", dest = "debug_level", default = 'info', help = "Set the level of system logging output, the available value for DEBUG_LEVEL: debug, info, warning, error, critical" ) parser.add_option("-t", "--target", dest = "target_override", default = None, help = "Override target to debug" ) parser.add_option("-n", "--nobreak", dest = "break_at_hardfault", default = True, action="store_false", help = "Disable breakpoint at hardfault handler. Required for nrf51 chip with SoftDevice based application." ) parser.add_option("-s", "--skip", dest = "skip_bytes", default = False, help = "Skip N (hexidecimal) first bytes of flash (for example SoftDevice on nrf51 chip). " ) (option, args) = parser.parse_args() if (option.skip_bytes): option.skip_bytes = int(option.skip_bytes, 16) gdb = None level = LEVELS.get(option.debug_level, logging.NOTSET) logging.basicConfig(level=level) if option.list_all == True: MbedBoard.listConnectedBoards() else: try: board_selected = MbedBoard.chooseBoard(board_id = option.board_id, target_override = option.target_override) if board_selected != None: try: gdb = GDBServer(board_selected, int(option.port_number), {'skip_bytes' : option.skip_bytes, 'break_at_hardfault' : option.break_at_hardfault}) while gdb.isAlive(): gdb.join(timeout = 0.5) except ValueError: logging.error("Port number error!") except KeyboardInterrupt: if gdb != None: gdb.stop() except Exception as e: print "uncaught exception: %s" % e traceback.print_exc() if gdb != None: gdb.stop()
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
def test_board(board_id, n, loglevel, logToConsole, commonLogFile): board = MbedBoard.chooseBoard(board_id=board_id, open_board=False) originalStdout = sys.stdout originalStderr = sys.stderr # Open board-specific output file. log_filename = "automated_test_results_%s_%d.txt" % (board.name, n) if os.path.exists(log_filename): os.remove(log_filename) log_file = open(log_filename, "a", buffering=1) # 1=Unbuffered # Setup logging. log_handler = RecordingLogHandler(None) log_handler.setFormatter(logging.Formatter(LOG_FORMAT)) root_logger = logging.getLogger() root_logger.setLevel(loglevel) root_logger.addHandler(log_handler) result_list = [] try: # Write board header to board log file, common log file, and console. print_board_header(log_file, board, n) if commonLogFile: print_board_header(commonLogFile, board, n, includeLeadingNewline=(n != 0)) print_board_header(originalStdout, board, n, logToConsole, includeLeadingNewline=(n != 0)) # Run all tests on this board. for test in test_list: print("{} #{}: starting {}...".format(board.name, n, test.name), file=originalStdout) # Set a unique port for the GdbTest. if isinstance(test, GdbTest): test.n = n # Create a StringIO object to record the test's output, an IOTee to copy # output to both the log file and StringIO, then set the log handler and # stdio to write to the tee. testOutput = io.StringIO() tee = IOTee(log_file, testOutput) if logToConsole: tee.add(originalStdout) if commonLogFile is not None: tee.add(commonLogFile) log_handler.stream = tee sys.stdout = tee sys.stderr = tee test_start = time() result = test.run(board) test_stop = time() result.time = test_stop - test_start tee.flush() result.output = testOutput.getvalue() result_list.append(result) passFail = "PASSED" if result.passed else "FAILED" print("{} #{}: finished {}... {} ({:.3f} s)".format( board.name, n, test.name, passFail, result.time), file=originalStdout) finally: # Restore stdout/stderr in case we're running in the parent process (1 job). sys.stdout = originalStdout sys.stderr = originalStderr root_logger.removeHandler(log_handler) log_handler.flush() log_handler.close() return result_list
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import logging from pyOCD.gdbserver import GDBServer from pyOCD.board import MbedBoard logging.basicConfig(level=logging.INFO) try: board_selected = MbedBoard.chooseBoard() if board_selected != None: gdb = GDBServer(board_selected, 3333) while gdb.isAlive(): gdb.join(timeout = 0.5) except KeyboardInterrupt: gdb.stop() except Exception as e: print "uncaught exception: %s" % e gdb.stop()
def run(self): board = None exitCode = 0 try: # Read command-line arguments. args = self.get_args() if args.verbose: logging.basicConfig(level=logging.INFO) # Print a list of all connected boards. if args.action == ACTION_LIST: MbedBoard.listConnectedBoards() sys.exit(0) board = MbedBoard.chooseBoard(board_id=args.board, target_override=args.target, init_board=False) board.target.setAutoUnlock(False) try: board.init() except Exception, e: print "Exception:", e target = board.target transport = board.transport flash = board.flash # Set specified SWD clock. if args.clock > 0: print "Setting SWD clock to %d kHz" % args.clock transport.setClock(args.clock * 1000) # Handle reset action first if args.action == ACTION_RESET: print "Resetting target" target.reset() sys.exit(0) # Handle a device with flash security enabled. didErase = False if target.isLocked() and args.action != ACTION_UNLOCK: print "Target is locked, cannot complete operation. Use --unlock to mass erase and unlock." # Handle actions. if args.action == ACTION_INFO: print "Unique ID: %s" % board.getUniqueID() print "Core ID: 0x%08x" % target.readIDCode() if isinstance(target, pyOCD.target.target_kinetis.Kinetis): print "MDM-AP Control: 0x%08x" % transport.readAP(target_kinetis.MDM_CTRL) print "MDM-AP Status: 0x%08x" % transport.readAP(target_kinetis.MDM_STATUS) status = target.getState() if status == pyOCD.target.cortex_m.TARGET_HALTED: print "Core status: Halted" self.dumpRegisters(target) elif status == pyOCD.target.cortex_m.TARGET_RUNNING: print "Core status: Running" elif args.action == ACTION_READ: if args.width == 8: data = target.readBlockMemoryUnaligned8(args.read, args.len) elif args.width == 16: if args.read & 0x1: raise ToolError("read address 0x%08x is not 16-bit aligned" % args.read) byteData = target.readBlockMemoryUnaligned8(args.read, args.len * 2) i = 0 data = [] while i < len(byteData): data.append(byteData[i] | (byteData[i + 1] << 8)) i += 2 elif args.width == 32: if args.read & 0x3: raise ToolError("read address 0x%08x is not 32-bit aligned" % args.read) data = target.readBlockMemoryAligned32(args.read, args.len / 4) # Either print disasm or hex dump of output if args.disasm: if args.width == 8: code = bytearray(data) elif args.width == 16: code = bytearray(byteData) elif args.width == 32: byteData = [] for v in data: byteData.extend([(v >> 24) & 0xff, (v >> 16) & 0xff, (v >> 8) & 0xff, v & 0xff]) code = bytearray(byteData) self.disasm(str(code), args.read) else: dumpHexData(data, args.read, width=args.width) elif args.action == ACTION_WRITE: if args.width == 8: target.writeBlockMemoryUnaligned8(args.write, args.data) elif args.width == 16: if args.write & 0x1: raise ToolError("write address 0x%08x is not 16-bit aligned" % args.write) print "16-bit writes are currently not supported" elif args.width == 32: if args.write & 0x3: raise ToolError("write address 0x%08x is not 32-bit aligned" % args.write) target.writeBlockMemoryAligned32(args.write, args.data) elif args.action == ACTION_PROGRAM: if not os.path.exists(args.file): raise ToolError("%s does not exist!" % args.file) print "Programming %s into flash..." % args.file flash.flashBinary(args.file) elif args.action == ACTION_ERASE: # TODO: change to be a complete chip erase that doesn't write FSEC to 0xfe. if not didErase: target.massErase() elif args.action == ACTION_UNLOCK: # Currently the same as erase. if not didErase: target.massErase() elif args.action == ACTION_GO: target.resume()
def cortex_test(board_id): with MbedBoard.chooseBoard(board_id = board_id, frequency = 1000000) as board: addr = 0 size = 0 f = None binary_file = "l1_" interface = None target_type = board.getTargetType() binary_file = os.path.join(parentdir, 'binaries', board.getTestBinary()) addr_bin = 0x00000000 test_clock = 10000000 addr_invalid = 0x3E000000 # Last 16MB of ARM SRAM region - typically empty if target_type == "lpc1768": addr = 0x10000000 size = 0x1102 addr_flash = 0x10000 elif target_type == "lpc11u24": addr = 0x10000000 size = 0x502 addr_flash = 0x4000 elif target_type == "kl25z": addr = 0x20000000 size = 0x502 addr_flash = 0x10000 elif target_type == "kl28z": addr = 0x20000000 size = 0x502 addr_flash = 0x10000 elif target_type == "k64f": addr = 0x20000000 size = 0x502 addr_flash = 0x10000 elif target_type == "k22f": addr = 0x20000000 size = 0x502 addr_flash = 0x10000 elif target_type == "k20d50m": addr = 0x20000000 size = 0x502 addr_flash = 0x10000 elif target_type == "kl46z": addr = 0x20000000 size = 0x502 addr_flash = 0x10000 elif target_type == "lpc800": addr = 0x10000000 size = 0x502 addr_flash = 0x2000 elif target_type == "nrf51": addr = 0x20000000 size = 0x502 addr_flash = 0x20000 # Override clock since 10MHz is too fast test_clock = 1000000 elif target_type == "lpc4330": addr = 0x10000000 size = 0x1102 addr_flash = 0x14010000 addr_bin = 0x14000000 elif target_type == "maxwsnenv": addr = 0x20000000 size = 0x502 addr_flash = 0x10000 elif target_type == "max32600mbed": addr = 0x20000000 size = 0x502 addr_flash = 0x10000 elif target_type == "w7500": addr = 0x20000000 size = 0x1102 addr_flash = 0x00000000 else: raise Exception("A board is not supported by this test script.") target = board.target transport = board.transport flash = board.flash interface = board.interface transport.setClock(test_clock) transport.setDeferredTransfer(True) test_pass_count = 0 test_count = 0 result = CortexTestResult() print "\r\n\r\n----- FLASH NEW BINARY BEFORE TEST -----" flash.flashBinary(binary_file, addr_bin) # Let the target run for a bit so it # can initialize the watchdog if it needs to target.resume() sleep(0.2) target.halt() print "PROGRAMMING COMPLETE" print "\r\n\r\n----- TESTING CORTEX-M PERFORMANCE -----" test_time = test_function(board, target.getTResponse) print("Function getTResponse time: %f" % test_time) # Step test_time = test_function(board, target.step) print("Function step time: %f" % test_time) # Breakpoint def set_remove_breakpoint(): target.setBreakpoint(0) target.removeBreakpoint(0) test_time = test_function(board, set_remove_breakpoint) print("Add and remove breakpoint: %f" % test_time) # getRegisterContext test_time = test_function(board, target.getRegisterContext) print("Function getRegisterContext: %f" % test_time) # setRegisterContext context = target.getRegisterContext() def set_register_context(): target.setRegisterContext(context) test_time = test_function(board, set_register_context) print("Function setRegisterContext: %f" % test_time) # Run / Halt def run_halt(): target.resume() target.halt() test_time = test_function(board, run_halt) print("Resume and halt: %f" % test_time) # GDB stepping def simulate_step(): target.step() target.getTResponse() target.setBreakpoint(0) target.resume() target.halt() target.getTResponse() target.removeBreakpoint(0) test_time = test_function(board, simulate_step) print("Simulated GDB step: %f" % test_time) # Test passes if there are no exceptions test_pass_count += 1 test_count += 1 print("TEST PASSED") print "\r\n\r\n------ Testing Invalid Memory Access Recovery ------" memory_access_pass = True try: target.readBlockMemoryUnaligned8(addr_invalid, 0x1000) target.flush() # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0 if target_type != "nrf51": memory_access_pass = False except TransferError: pass try: target.readBlockMemoryUnaligned8(addr_invalid + 1, 0x1000) target.flush() # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0 if target_type != "nrf51": memory_access_pass = False except TransferError: pass data = [0x00] * 0x1000 try: target.writeBlockMemoryUnaligned8(addr_invalid, data) target.flush() # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0 if target_type != "nrf51": memory_access_pass = False except TransferError: pass data = [0x00] * 0x1000 try: target.writeBlockMemoryUnaligned8(addr_invalid + 1, data) target.flush() # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0 if target_type != "nrf51": memory_access_pass = False except TransferError: pass data = [randrange(0, 255) for x in range(size)] target.writeBlockMemoryUnaligned8(addr, data) block = target.readBlockMemoryUnaligned8(addr, size) if same(data, block): print "Aligned access pass" else: print("Memory read does not match memory written") memory_access_pass = False data = [randrange(0, 255) for x in range(size)] target.writeBlockMemoryUnaligned8(addr + 1, data) block = target.readBlockMemoryUnaligned8(addr + 1, size) if same(data, block): print "Unaligned access pass" else: print("Unaligned memory read does not match memory written") memory_access_pass = False test_count += 1 if memory_access_pass: test_pass_count += 1 print "TEST PASSED" else: print "TEST FAILED" target.reset() result.passed = test_count == test_pass_count return result
def cortex_test(board_id): with MbedBoard.chooseBoard(board_id=board_id, frequency=1000000) as board: target_type = board.getTargetType() binary_file = os.path.join(parentdir, 'binaries', board.getTestBinary()) test_clock = 10000000 addr_invalid = 0x3E000000 # Last 16MB of ARM SRAM region - typically empty if target_type == "nrf51": # Override clock since 10MHz is too fast test_clock = 1000000 memory_map = board.target.getMemoryMap() ram_regions = [region for region in memory_map if region.type == 'ram'] ram_region = ram_regions[0] rom_region = memory_map.getBootMemory() addr = ram_region.start + 1 size = 0x502 addr_bin = rom_region.start target = board.target link = board.link flash = board.flash link.set_clock(test_clock) link.set_deferred_transfer(True) test_pass_count = 0 test_count = 0 result = CortexTestResult() print "\r\n\r\n----- FLASH NEW BINARY BEFORE TEST -----" flash.flashBinary(binary_file, addr_bin) # Let the target run for a bit so it # can initialize the watchdog if it needs to target.resume() sleep(0.2) target.halt() print "PROGRAMMING COMPLETE" print "\r\n\r\n----- TESTING CORTEX-M PERFORMANCE -----" test_time = test_function(board, target.getTResponse) print("Function getTResponse time: %f" % test_time) # Step test_time = test_function(board, target.step) print("Function step time: %f" % test_time) # Breakpoint def set_remove_breakpoint(): target.setBreakpoint(0) target.removeBreakpoint(0) test_time = test_function(board, set_remove_breakpoint) print("Add and remove breakpoint: %f" % test_time) # getRegisterContext test_time = test_function(board, target.getRegisterContext) print("Function getRegisterContext: %f" % test_time) # setRegisterContext context = target.getRegisterContext() def set_register_context(): target.setRegisterContext(context) test_time = test_function(board, set_register_context) print("Function setRegisterContext: %f" % test_time) # Run / Halt def run_halt(): target.resume() target.halt() test_time = test_function(board, run_halt) print("Resume and halt: %f" % test_time) # GDB stepping def simulate_step(): target.step() target.getTResponse() target.setBreakpoint(0) target.resume() target.halt() target.getTResponse() target.removeBreakpoint(0) test_time = test_function(board, simulate_step) print("Simulated GDB step: %f" % test_time) # Test passes if there are no exceptions test_pass_count += 1 test_count += 1 print("TEST PASSED") print "\r\n\r\n------ Testing Invalid Memory Access Recovery ------" memory_access_pass = True try: target.readBlockMemoryUnaligned8(addr_invalid, 0x1000) target.flush() # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0 if target_type != "nrf51": memory_access_pass = False except DAPAccess.TransferFaultError: pass try: target.readBlockMemoryUnaligned8(addr_invalid + 1, 0x1000) target.flush() # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0 if target_type != "nrf51": memory_access_pass = False except DAPAccess.TransferFaultError: pass data = [0x00] * 0x1000 try: target.writeBlockMemoryUnaligned8(addr_invalid, data) target.flush() # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0 if target_type != "nrf51": memory_access_pass = False except DAPAccess.TransferFaultError: pass data = [0x00] * 0x1000 try: target.writeBlockMemoryUnaligned8(addr_invalid + 1, data) target.flush() # If no exception is thrown the tests fails except on nrf51 where invalid addresses read as 0 if target_type != "nrf51": memory_access_pass = False except DAPAccess.TransferFaultError: pass data = [randrange(0, 255) for x in range(size)] target.writeBlockMemoryUnaligned8(addr, data) block = target.readBlockMemoryUnaligned8(addr, size) if same(data, block): print "Aligned access pass" else: print("Memory read does not match memory written") memory_access_pass = False data = [randrange(0, 255) for x in range(size)] target.writeBlockMemoryUnaligned8(addr + 1, data) block = target.readBlockMemoryUnaligned8(addr + 1, size) if same(data, block): print "Unaligned access pass" else: print("Unaligned memory read does not match memory written") memory_access_pass = False test_count += 1 if memory_access_pass: test_pass_count += 1 print "TEST PASSED" else: print "TEST FAILED" target.reset() result.passed = test_count == test_pass_count return result
def basic_test(board_id, file): with MbedBoard.chooseBoard(board_id=board_id) as board: addr = 0 size = 0 f = None binary_file = "l1_" target_type = board.getTargetType() if file is None: binary_file = os.path.join(parentdir, 'binaries', board.getTestBinary()) else: binary_file = file print "binary file: %s" % binary_file memory_map = board.target.getMemoryMap() ram_regions = [region for region in memory_map if region.type == 'ram'] ram_region = ram_regions[0] rom_region = memory_map.getBootMemory() addr = ram_region.start + 1 size = 0x502 addr_bin = rom_region.start addr_flash = rom_region.start + rom_region.length // 2 target = board.target link = board.link flash = board.flash print "\r\n\r\n------ GET Unique ID ------" print "Unique ID: %s" % board.getUniqueID() print "\r\n\r\n------ TEST READ / WRITE CORE REGISTER ------" pc = target.readCoreRegister('pc') print "initial pc: 0x%X" % target.readCoreRegister('pc') # write in pc dummy value target.writeCoreRegister('pc', 0x3D82) print "now pc: 0x%X" % target.readCoreRegister('pc') # write initial pc value target.writeCoreRegister('pc', pc) print "initial pc value rewritten: 0x%X" % target.readCoreRegister('pc') msp = target.readCoreRegister('msp') psp = target.readCoreRegister('psp') print "MSP = 0x%08x; PSP = 0x%08x" % (msp, psp) control = target.readCoreRegister('control') faultmask = target.readCoreRegister('faultmask') basepri = target.readCoreRegister('basepri') primask = target.readCoreRegister('primask') print "CONTROL = 0x%02x; FAULTMASK = 0x%02x; BASEPRI = 0x%02x; PRIMASK = 0x%02x" % (control, faultmask, basepri, primask) target.writeCoreRegister('primask', 1) newPrimask = target.readCoreRegister('primask') print "New PRIMASK = 0x%02x" % newPrimask target.writeCoreRegister('primask', primask) newPrimask = target.readCoreRegister('primask') print "Restored PRIMASK = 0x%02x" % newPrimask if target.has_fpu: s0 = target.readCoreRegister('s0') print "S0 = %g (0x%08x)" % (s0, float32beToU32be(s0)) target.writeCoreRegister('s0', math.pi) newS0 = target.readCoreRegister('s0') print "New S0 = %g (0x%08x)" % (newS0, float32beToU32be(newS0)) target.writeCoreRegister('s0', s0) newS0 = target.readCoreRegister('s0') print "Restored S0 = %g (0x%08x)" % (newS0, float32beToU32be(newS0)) print "\r\n\r\n------ TEST HALT / RESUME ------" print "resume" target.resume() sleep(0.2) print "halt" target.halt() print "HALT: pc: 0x%X" % target.readCoreRegister('pc') sleep(0.2) print "\r\n\r\n------ TEST STEP ------" print "reset and halt" target.resetStopOnReset() currentPC = target.readCoreRegister('pc') print "HALT: pc: 0x%X" % currentPC sleep(0.2) for i in range(4): print "step" target.step() newPC = target.readCoreRegister('pc') print "STEP: pc: 0x%X" % newPC currentPC = newPC sleep(0.2) print "\r\n\r\n------ TEST READ / WRITE MEMORY ------" target.halt() print "READ32/WRITE32" val = randrange(0, 0xffffffff) print "write32 0x%X at 0x%X" % (val, addr) target.writeMemory(addr, val) res = target.readMemory(addr) print "read32 at 0x%X: 0x%X" % (addr, res) if res != val: print "ERROR in READ/WRITE 32" print "\r\nREAD16/WRITE16" val = randrange(0, 0xffff) print "write16 0x%X at 0x%X" % (val, addr + 2) target.writeMemory(addr + 2, val, 16) res = target.readMemory(addr + 2, 16) print "read16 at 0x%X: 0x%X" % (addr + 2, res) if res != val: print "ERROR in READ/WRITE 16" print "\r\nREAD8/WRITE8" val = randrange(0, 0xff) print "write8 0x%X at 0x%X" % (val, addr + 1) target.writeMemory(addr + 1, val, 8) res = target.readMemory(addr + 1, 8) print "read8 at 0x%X: 0x%X" % (addr + 1, res) if res != val: print "ERROR in READ/WRITE 8" print "\r\n\r\n------ TEST READ / WRITE MEMORY BLOCK ------" data = [randrange(1, 50) for x in range(size)] target.writeBlockMemoryUnaligned8(addr, data) block = target.readBlockMemoryUnaligned8(addr, size) error = False for i in range(len(block)): if (block[i] != data[i]): error = True print "ERROR: 0x%X, 0x%X, 0x%X!!!" % ((addr + i), block[i], data[i]) if error: print "TEST FAILED" else: print "TEST PASSED" print "\r\n\r\n------ TEST RESET ------" target.reset() sleep(0.1) target.halt() for i in range(5): target.step() print "pc: 0x%X" % target.readCoreRegister('pc') print "\r\n\r\n------ TEST PROGRAM/ERASE PAGE ------" # Fill 3 pages with 0x55 page_size = flash.getPageInfo(addr_flash).size fill = [0x55] * page_size flash.init() for i in range(0, 3): address = addr_flash + page_size * i # Test only supports a location with 3 aligned # pages of the same size current_page_size = flash.getPageInfo(addr_flash).size assert page_size == current_page_size assert address % current_page_size == 0 flash.erasePage(address) flash.programPage(address, fill) # Erase the middle page flash.erasePage(addr_flash + page_size) # Verify the 1st and 3rd page were not erased, and that the 2nd page is fully erased data = target.readBlockMemoryUnaligned8(addr_flash, page_size * 3) expected = fill + [0xFF] * page_size + fill if data == expected: print "TEST PASSED" else: print "TEST FAILED" print "\r\n\r\n----- FLASH NEW BINARY -----" flash.flashBinary(binary_file, addr_bin) target.reset()
def run(self): try: # Read command-line arguments. self.args = self.get_args() self.cmd = self.args.cmd if self.cmd: self.cmd = self.cmd.lower() # Set logging level self.configure_logging() # Check for a valid command. if self.cmd and self.cmd not in self.command_list: print "Error: unrecognized command '%s'" % self.cmd return 1 # List command must be dealt with specially. if self.cmd == 'list': self.handle_list([]) return 0 if self.args.clock != DEFAULT_CLOCK_FREQ_KHZ: print "Setting SWD clock to %d kHz" % self.args.clock # Connect to board. self.board = MbedBoard.chooseBoard( board_id=self.args.board, target_override=self.args.target, init_board=False, frequency=(self.args.clock * 1000)) self.board.target.setAutoUnlock(False) self.board.target.setHaltOnConnect(False) try: self.board.init() except Exception as e: print "Exception while initing board:", e self.target = self.board.target self.transport = self.board.transport self.flash = self.board.flash # Halt if requested. if self.args.halt: self.handle_halt() # Handle a device with flash security enabled. self.didErase = False if self.target.isLocked() and self.cmd != 'unlock': print "Error: Target is locked, cannot complete operation. Use unlock command to mass erase and unlock." if self.cmd and self.cmd not in ['reset', 'info']: return 1 # If no command, enter interactive mode. if not self.cmd: # Say what we're connected to. print "Connected to %s [%s]: %s" % ( self.target.part_number, CORE_STATUS_DESC[self.target.getState()], self.board.getUniqueID()) # Remove list command that disrupts the connection. self.command_list.pop('list') COMMAND_INFO.pop('list') # Run the command line. console = PyOCDConsole(self) console.run() else: # Invoke action handler. result = self.command_list[self.cmd](self.args.args) if result is not None: self.exitCode = result except ToolExitException: self.exitCode = 0 except ValueError: print "Error: invalid argument" except pyOCD.transport.transport.TransferError: print "Error: transfer failed" self.exitCode = 2 except ToolError as e: print "Error:", e self.exitCode = 1 finally: if self.board != None: # Pass false to prevent target resume. self.board.uninit(False) return self.exitCode
def flash_test(board_id): with MbedBoard.chooseBoard(board_id=board_id, frequency=1000000) as board: target_type = board.getTargetType() test_clock = 10000000 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 memory_map = board.target.getMemoryMap() ram_regions = [region for region in memory_map if region.type == 'ram'] ram_region = ram_regions[0] ram_start = ram_region.start ram_size = ram_region.length target = board.target link = board.link flash = board.flash flash_info = flash.getFlashInfo() link.set_clock(test_clock) link.set_deferred_transfer(True) test_pass_count = 0 test_count = 0 result = FlashTestResult() # Test each flash region separately. for rom_region in memory_map.getRegionsOfType('flash'): if not rom_region.isTestable: continue rom_start = rom_region.start rom_size = rom_region.length print("\n\n===== Testing flash region '%s' from 0x%08x to 0x%08x ====" % (rom_region.name, rom_region.start, rom_region.end)) binary_file = os.path.join(parentdir, 'binaries', board.getTestBinary()) with open(binary_file, "rb") as f: data = f.read() data = struct.unpack("%iB" % len(data), data) unused = rom_size - len(data) # Make sure data doesn't overflow this region. if unused < 0: data = data[:rom_size] unused = 0 addr = rom_start size = len(data) # Turn on extra checks for the next 4 tests flash.setFlashAlgoDebug(True) print("\n------ Test Basic Page Erase ------") info = flash.flashBlock(addr, data, False, False, progress_cb=print_progress()) data_flashed = target.readBlockMemoryUnaligned8(addr, size) if same(data_flashed, data) and info.program_type is FlashBuilder.FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print("\n------ Test Basic Chip Erase ------") info = flash.flashBlock(addr, data, False, True, progress_cb=print_progress()) data_flashed = target.readBlockMemoryUnaligned8(addr, size) if same(data_flashed, data) and info.program_type is FlashBuilder.FLASH_CHIP_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print("\n------ Test Smart Page Erase ------") info = flash.flashBlock(addr, data, True, False, progress_cb=print_progress()) data_flashed = target.readBlockMemoryUnaligned8(addr, size) if same(data_flashed, data) and info.program_type is FlashBuilder.FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print("\n------ Test Smart Chip Erase ------") info = flash.flashBlock(addr, data, True, True, progress_cb=print_progress()) data_flashed = target.readBlockMemoryUnaligned8(addr, size) if same(data_flashed, data) and info.program_type is FlashBuilder.FLASH_CHIP_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 flash.setFlashAlgoDebug(False) print("\n------ Test Basic Page Erase (Entire region) ------") new_data = list(data) new_data.extend(unused * [0x77]) info = flash.flashBlock(addr, new_data, False, False, progress_cb=print_progress()) if info.program_type == FlashBuilder.FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 result.page_erase_rate = float(len(new_data)) / float(info.program_time) else: print("TEST FAILED") test_count += 1 print("\n------ Test Fast Verify ------") info = flash.flashBlock(addr, new_data, progress_cb=print_progress(), fast_verify=True) if info.program_type == FlashBuilder.FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print("\n------ Test Offset Write ------") addr = rom_start + rom_size // 2 page_size = flash.getPageInfo(addr).size new_data = [0x55] * page_size * 2 info = flash.flashBlock(addr, new_data, progress_cb=print_progress()) data_flashed = target.readBlockMemoryUnaligned8(addr, len(new_data)) if same(data_flashed, new_data) and info.program_type is FlashBuilder.FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print("\n------ Test Multiple Block Writes ------") addr = rom_start + rom_size // 2 page_size = flash.getPageInfo(addr).size more_data = [0x33] * page_size * 2 addr = (rom_start + rom_size // 2) + 1 #cover multiple pages fb = flash.getFlashBuilder() fb.addData(rom_start, data) fb.addData(addr, more_data) fb.program(progress_cb=print_progress()) data_flashed = target.readBlockMemoryUnaligned8(rom_start, len(data)) data_flashed_more = target.readBlockMemoryUnaligned8(addr, len(more_data)) if same(data_flashed, data) and same(data_flashed_more, more_data): print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print("\n------ Test Overlapping Blocks ------") test_pass = False addr = (rom_start + rom_size // 2) #cover multiple pages page_size = flash.getPageInfo(addr).size new_data = [0x33] * page_size fb = flash.getFlashBuilder() fb.addData(addr, new_data) try: fb.addData(addr + 1, new_data) except ValueError as e: print("Exception: %s" % e) test_pass = True if test_pass: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print("\n------ Test Empty Block Write ------") # Freebee if nothing asserts fb = flash.getFlashBuilder() fb.program() print("TEST PASSED") test_pass_count += 1 test_count += 1 print("\n------ Test Missing Progress Callback ------") # Freebee if nothing asserts addr = rom_start flash.flashBlock(rom_start, data, True) print("TEST PASSED") test_pass_count += 1 test_count += 1 # Only run test if the reset handler can be programmed (rom start at address 0) if rom_start == 0: print("\n------ Test Non-Thumb reset handler ------") non_thumb_data = list(data) # Clear bit 0 of 2nd word - reset handler non_thumb_data[4] = non_thumb_data[4] & ~1 flash.flashBlock(rom_start, non_thumb_data) flash.flashBlock(rom_start, data) print("TEST PASSED") test_pass_count += 1 test_count += 1 # Note - The decision based tests below are order dependent since they # depend on the previous state of the flash if rom_start == flash_info.rom_start: print("\n------ Test Chip Erase Decision ------") new_data = list(data) new_data.extend([0xff] * unused) # Pad with 0xFF info = flash.flashBlock(addr, new_data, progress_cb=print_progress()) if info.program_type == FlashBuilder.FLASH_CHIP_ERASE: print("TEST PASSED") test_pass_count += 1 result.chip_erase_rate_erased = float(len(new_data)) / float(info.program_time) else: print("TEST FAILED") test_count += 1 print("\n------ Test Chip Erase Decision 2 ------") new_data = list(data) new_data.extend([0x00] * unused) # Pad with 0x00 info = flash.flashBlock(addr, new_data, progress_cb=print_progress()) if info.program_type == FlashBuilder.FLASH_CHIP_ERASE: print("TEST PASSED") test_pass_count += 1 result.chip_erase_rate = float(len(new_data)) / float(info.program_time) else: print("TEST FAILED") test_count += 1 print("\n------ Test Page Erase Decision ------") new_data = list(data) new_data.extend([0x00] * unused) # Pad with 0x00 info = flash.flashBlock(addr, new_data, progress_cb=print_progress()) if info.program_type == FlashBuilder.FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 result.page_erase_rate_same = float(len(new_data)) / float(info.program_time) result.analyze = info.analyze_type result.analyze_time = info.analyze_time result.analyze_rate = float(len(new_data)) / float(info.analyze_time) else: print("TEST FAILED") test_count += 1 print("\n------ Test Page Erase Decision 2 ------") new_data = list(data) size_same = unused * 5 // 6 size_differ = unused - size_same new_data.extend([0x00] * size_same) # Pad 5/6 with 0x00 and 1/6 with 0xFF new_data.extend([0x55] * size_differ) info = flash.flashBlock(addr, new_data, progress_cb=print_progress()) if info.program_type == FlashBuilder.FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print("\n\nTest Summary:") print("Pass count %i of %i tests" % (test_pass_count, test_count)) if test_pass_count == test_count: print("FLASH TEST SCRIPT PASSED") else: print("FLASH TEST SCRIPT FAILED") target.reset() result.passed = test_count == test_pass_count return result
f = None binary_file = "l1_" interface = None import logging logging.basicConfig(level=logging.INFO) parser = argparse.ArgumentParser(description="A CMSIS-DAP python debugger") parser.add_argument("-f", help="binary file", dest="file") args = parser.parse_args() try: board = MbedBoard.chooseBoard() target_type = board.getTargetType() if args.file is None: binary_file += target_type + ".bin" binary_file = os.path.join(parentdir, "binaries", binary_file) else: binary_file = args.file print "binary file: %s" % binary_file if target_type == "lpc1768": addr = 0x10000001 size = 0x1102 elif target_type == "lpc11u24": addr = 0x10000001
def basic_test(board_id, file): with MbedBoard.chooseBoard(board_id = board_id) as board: addr = 0 size = 0 f = None binary_file = "l1_" interface = None target_type = board.getTargetType() if file is None: binary_file = os.path.join(parentdir, 'binaries', board.getTestBinary()) else: binary_file = file print "binary file: %s" % binary_file addr_bin = 0x00000000 if target_type == "lpc1768": addr = 0x10000001 size = 0x1102 addr_flash = 0x10000 elif target_type == "lpc11u24": addr = 0x10000001 size = 0x502 addr_flash = 0x4000 elif target_type == "kl25z": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 elif target_type == "kl28z": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 elif target_type == "k64f": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 elif target_type == "k22f": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 elif target_type == "k20d50m": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 elif target_type == "kl46z": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 elif target_type == "lpc800": addr = 0x10000001 size = 0x502 addr_flash = 0x2000 elif target_type == "nrf51": addr = 0x20000001 size = 0x502 addr_flash = 0x20000 elif target_type == "lpc4330": addr = 0x10000001 size = 0x1102 addr_flash = 0x14010000 addr_bin = 0x14000000 elif target_type == "maxwsnenv": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 elif target_type == "max32600mbed": addr = 0x20000001 size = 0x502 addr_flash = 0x10000 else: raise Exception("A board is not supported by this test script.") target = board.target transport = board.transport flash = board.flash interface = board.interface print "\r\n\r\n------ GET Unique ID ------" print "Unique ID: %s" % board.getUniqueID() print "\r\n\r\n------ TEST READ / WRITE CORE REGISTER ------" pc = target.readCoreRegister('pc') print "initial pc: 0x%X" % target.readCoreRegister('pc') # write in pc dummy value target.writeCoreRegister('pc', 0x3D82) print "now pc: 0x%X" % target.readCoreRegister('pc') # write initial pc value target.writeCoreRegister('pc', pc) print "initial pc value rewritten: 0x%X" % target.readCoreRegister('pc') msp = target.readCoreRegister('msp') psp = target.readCoreRegister('psp') print "MSP = 0x%08x; PSP = 0x%08x" % (msp, psp) control = target.readCoreRegister('control') faultmask = target.readCoreRegister('faultmask') basepri = target.readCoreRegister('basepri') primask = target.readCoreRegister('primask') print "CONTROL = 0x%02x; FAULTMASK = 0x%02x; BASEPRI = 0x%02x; PRIMASK = 0x%02x" % (control, faultmask, basepri, primask) target.writeCoreRegister('primask', 1) newPrimask = target.readCoreRegister('primask') print "New PRIMASK = 0x%02x" % newPrimask target.writeCoreRegister('primask', primask) newPrimask = target.readCoreRegister('primask') print "Restored PRIMASK = 0x%02x" % newPrimask if target.has_fpu: s0 = target.readCoreRegister('s0') print "S0 = %g (0x%08x)" % (s0,float2int(s0)) target.writeCoreRegister('s0', math.pi) newS0 = target.readCoreRegister('s0') print "New S0 = %g (0x%08x)" % (newS0, float2int(newS0)) target.writeCoreRegister('s0', s0) newS0 = target.readCoreRegister('s0') print "Restored S0 = %g (0x%08x)" % (newS0, float2int(newS0)) print "\r\n\r\n------ TEST HALT / RESUME ------" print "resume" target.resume() sleep(0.2) print "halt" target.halt() print "HALT: pc: 0x%X" % target.readCoreRegister('pc') sleep(0.2) print "\r\n\r\n------ TEST STEP ------" print "reset and halt" target.resetStopOnReset() currentPC = target.readCoreRegister('pc') print "HALT: pc: 0x%X" % currentPC sleep(0.2) for i in range(4): print "step" target.step() newPC = target.readCoreRegister('pc') print "STEP: pc: 0x%X" % newPC currentPC = newPC sleep(0.2) print "\r\n\r\n------ TEST READ / WRITE MEMORY ------" target.halt() print "READ32/WRITE32" val = randrange(0, 0xffffffff) print "write32 0x%X at 0x%X" % (val, addr) target.writeMemory(addr, val) res = target.readMemory(addr) print "read32 at 0x%X: 0x%X" % (addr, res) if res != val: print "ERROR in READ/WRITE 32" print "\r\nREAD16/WRITE16" val = randrange(0, 0xffff) print "write16 0x%X at 0x%X" % (val, addr + 2) target.writeMemory(addr + 2, val, 16) res = target.readMemory(addr + 2, 16) print "read16 at 0x%X: 0x%X" % (addr + 2, res) if res != val: print "ERROR in READ/WRITE 16" print "\r\nREAD8/WRITE8" val = randrange(0, 0xff) print "write8 0x%X at 0x%X" % (val, addr + 1) target.writeMemory(addr + 1, val, 8) res = target.readMemory(addr + 1, 8) print "read8 at 0x%X: 0x%X" % (addr + 1, res) if res != val: print "ERROR in READ/WRITE 8" print "\r\n\r\n------ TEST READ / WRITE MEMORY BLOCK ------" data = [randrange(1, 50) for x in range(size)] target.writeBlockMemoryUnaligned8(addr, data) block = target.readBlockMemoryUnaligned8(addr, size) error = False for i in range(len(block)): if (block[i] != data[i]): error = True print "ERROR: 0x%X, 0x%X, 0x%X!!!" % ((addr + i), block[i], data[i]) if error: print "TEST FAILED" else: print "TEST PASSED" print "\r\n\r\n------ TEST RESET ------" target.reset() sleep(0.1) target.halt() for i in range(5): target.step() print "pc: 0x%X" % target.readCoreRegister('pc') print "\r\n\r\n------ TEST PROGRAM/ERASE PAGE ------" # Fill 3 pages with 0x55 fill = [0x55] * flash.page_size flash.init() for i in range(0, 3): flash.erasePage(addr_flash + flash.page_size * i) flash.programPage( addr_flash + flash.page_size * i, fill ) # Erase the middle page flash.erasePage(addr_flash + flash.page_size) # Verify the 1st and 3rd page were not erased, and that the 2nd page is fully erased data = target.readBlockMemoryUnaligned8(addr_flash, flash.page_size * 3) expected = fill + [0xFF] * flash.page_size + fill if data == expected: print "TEST PASSED" else: print "TEST FAILED" print "\r\n\r\n----- FLASH NEW BINARY -----" flash.flashBinary(binary_file, addr_bin) target.reset()
from time import sleep from random import randrange import math parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, parentdir) import pyOCD from pyOCD.board import MbedBoard import logging logging.basicConfig(level=logging.INFO) print "\r\n\r\n------ Test attaching to locked board ------" for i in range(0, 10): with MbedBoard.chooseBoard() as board: # Erase and then reset - This locks Kinetis devices board.flash.init() board.flash.eraseAll() board.target.reset() print "\r\n\r\n------ Testing Attaching to board ------" for i in range(0, 100): with MbedBoard.chooseBoard() as board: board.target.halt() sleep(0.01) board.target.resume() sleep(0.01) print "\r\n\r\n------ Flashing new code ------" with MbedBoard.chooseBoard() as board:
def flash_test(board_id): with MbedBoard.chooseBoard(board_id=board_id, frequency=1000000) as board: target_type = board.getTargetType() test_clock = 10000000 if target_type == "kl25z": ram_start = 0x1ffff000 ram_size = 0x4000 rom_start = 0x00000000 rom_size = 0x20000 elif target_type == "kl46z": ram_start = 0x1fffe000 ram_size = 0x8000 rom_start = 0x00000000 rom_size = 0x40000 elif target_type == "k22f": ram_start = 0x1fff0000 ram_size = 0x20000 rom_start = 0x00000000 rom_size = 0x80000 elif target_type == "k64f": ram_start = 0x1FFF0000 ram_size = 0x40000 rom_start = 0x00000000 rom_size = 0x100000 elif target_type == "lpc11u24": ram_start = 0x10000000 ram_size = 0x2000 rom_start = 0x00000000 rom_size = 0x8000 elif target_type == "lpc1768": ram_start = 0x10000000 ram_size = 0x8000 rom_start = 0x00000000 rom_size = 0x80000 elif target_type == "lpc4330": ram_start = 0x10000000 ram_size = 0x20000 rom_start = 0x14000000 rom_size = 0x100000 elif target_type == "lpc800": ram_start = 0x10000000 ram_size = 0x1000 rom_start = 0x00000000 rom_size = 0x4000 elif target_type == "nrf51822": ram_start = 0x20000000 ram_size = 0x4000 rom_start = 0x00000000 rom_size = 0x40000 # Override clock since 10MHz is too fast test_clock = 1000000 else: raise Exception("The board is not supported by this test script.") target = board.target transport = board.transport flash = board.flash interface = board.interface transport.setClock(test_clock) test_pass_count = 0 test_count = 0 print "\r\n\r\n------ Test Read / Write Speed ------" test_addr = ram_start test_size = ram_size data = [randrange(1, 50) for x in range(test_size)] start = time() target.writeBlockMemoryUnaligned8(test_addr, data) stop = time() diff = stop - start print("Writing %i byte took %s seconds: %s B/s" % (test_size, diff, test_size / diff)) start = time() block = target.readBlockMemoryUnaligned8(test_addr, test_size) stop = time() diff = stop - start print("Reading %i byte took %s seconds: %s B/s" % (test_size, diff, test_size / diff)) if same(block, data): print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 def print_progress(progress): assert progress >= 0.0 assert progress <= 1.0 assert (progress == 0 and print_progress.prev_progress == 1.0) or (progress >= print_progress.prev_progress) # Reset state on 0.0 if progress == 0.0: print_progress.prev_progress = 0 print_progress.backwards_progress = False print_progress.done = False # Check for backwards progress if progress < print_progress.prev_progress: print_progress.backwards_progress = True print_progress.prev_progress = progress # print progress bar if not print_progress.done: sys.stdout.write('\r') i = int(progress * 20.0) sys.stdout.write("[%-20s] %3d%%" % ('=' * i, round(progress * 100))) # Finish on 1.0 if progress >= 1.0: if not print_progress.done: print_progress.done = True sys.stdout.write("\n") if print_progress.backwards_progress: print("Progress went backwards during flash") print_progress.prev_progress = 0 binary_file = "l1_" binary_file += target_type + ".bin" binary_file = os.path.join(parentdir, 'binaries', binary_file) with open(binary_file, "rb") as f: data = f.read() data = struct.unpack("%iB" % len(data), data) unused = rom_size - len(data) addr = rom_start size = len(data) print "\r\n\r\n------ Test Basic Page Erase ------" operation = flash.flashBlock(addr, data, False, False, progress_cb=print_progress) data_flashed = target.readBlockMemoryUnaligned8(addr, size) if same(data_flashed, data) and operation is FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Basic Chip Erase ------" operation = flash.flashBlock(addr, data, False, True, progress_cb=print_progress) data_flashed = target.readBlockMemoryUnaligned8(addr, size) if same(data_flashed, data) and operation is FLASH_CHIP_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Smart Page Erase ------" operation = flash.flashBlock(addr, data, True, False, progress_cb=print_progress) data_flashed = target.readBlockMemoryUnaligned8(addr, size) if same(data_flashed, data) and operation is FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Smart Chip Erase ------" operation = flash.flashBlock(addr, data, True, True, progress_cb=print_progress) data_flashed = target.readBlockMemoryUnaligned8(addr, size) if same(data_flashed, data) and operation is FLASH_CHIP_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Offset Write ------" new_data = [0x55] * board.flash.page_size * 2 addr = rom_start + rom_size / 2 operation = flash.flashBlock(addr, new_data, progress_cb=print_progress) data_flashed = target.readBlockMemoryUnaligned8(addr, len(new_data)) if same(data_flashed, new_data) and operation is FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Multiple Block Writes ------" more_data = [0x33] * board.flash.page_size * 2 addr = (rom_start + rom_size / 2) + 1 #cover multiple pages fb = flash.getFlashBuilder() fb.addData(rom_start, data) fb.addData(addr, more_data) fb.program(progress_cb=print_progress) data_flashed = target.readBlockMemoryUnaligned8(rom_start, len(data)) data_flashed_more = target.readBlockMemoryUnaligned8( addr, len(more_data)) if same(data_flashed, data) and same(data_flashed_more, more_data): print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Overlapping Blocks ------" test_pass = False new_data = [0x33] * board.flash.page_size addr = (rom_start + rom_size / 2) #cover multiple pages fb = flash.getFlashBuilder() fb.addData(addr, new_data) try: fb.addData(addr + 1, new_data) except ValueError as e: print("Exception: %s" % e) test_pass = True if test_pass: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Empty Block Write ------" # Freebee if nothing asserts fb = flash.getFlashBuilder() fb.program() print("TEST PASSED") test_pass_count += 1 test_count += 1 print "\r\n\r\n------ Test Missing Progress Callback ------" # Freebee if nothing asserts addr = rom_start flash.flashBlock(rom_start, data, True) print("TEST PASSED") test_pass_count += 1 test_count += 1 # Note - The decision based tests below are order dependent since they # depend on the previous state of the flash print "\r\n\r\n------ Test Chip Erase Decision ------" new_data = list(data) new_data.extend([0xff] * unused) # Pad with 0xFF operation = flash.flashBlock(0, new_data, progress_cb=print_progress) if operation == FLASH_CHIP_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Chip Erase Decision 2 ------" new_data = list(data) new_data.extend([0x00] * unused) # Pad with 0x00 operation = flash.flashBlock(0, new_data, progress_cb=print_progress) if operation == FLASH_CHIP_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Page Erase Decision ------" new_data = list(data) new_data.extend([0x00] * unused) # Pad with 0x00 operation = flash.flashBlock(0, new_data, progress_cb=print_progress) if operation == FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Page Erase Decision 2 ------" new_data = list(data) size_same = unused * 5 / 6 size_differ = unused - size_same new_data.extend([0x00] * size_same) # Pad 5/6 with 0x00 and 1/6 with 0xFF new_data.extend([0x55] * size_differ) operation = flash.flashBlock(0, new_data, progress_cb=print_progress) if operation == FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print("\r\n\r\nTest Summary:") print("Pass count %i of %i tests" % (test_pass_count, test_count)) if test_pass_count == test_count: print("FLASH TEST SCRIPT PASSED") else: print("FLASH TEST SCRIPT FAILED") target.reset() return test_count == test_pass_count
def speed_test(board_id): with MbedBoard.chooseBoard(board_id=board_id, frequency=1000000) as board: target_type = board.getTargetType() test_clock = 10000000 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 memory_map = board.target.getMemoryMap() ram_regions = [region for region in memory_map if region.type == 'ram'] ram_region = ram_regions[0] rom_region = memory_map.getBootMemory() ram_start = ram_region.start ram_size = ram_region.length rom_start = rom_region.start rom_size = rom_region.length target = board.target link = board.link test_pass_count = 0 test_count = 0 result = SpeedTestResult() link.set_clock(test_clock) link.set_deferred_transfer(True) print("\r\n\r\n------ TEST RAM READ / WRITE SPEED ------") test_addr = ram_start test_size = ram_size data = [randrange(1, 50) for x in range(test_size)] start = time() target.writeBlockMemoryUnaligned8(test_addr, data) target.flush() stop = time() diff = stop - start result.write_speed = test_size / diff print("Writing %i byte took %s seconds: %s B/s" % (test_size, diff, result.write_speed)) start = time() block = target.readBlockMemoryUnaligned8(test_addr, test_size) target.flush() stop = time() diff = stop - start result.read_speed = test_size / diff print("Reading %i byte took %s seconds: %s B/s" % (test_size, diff, result.read_speed)) error = False for i in range(len(block)): if (block[i] != data[i]): error = True print("ERROR: 0x%X, 0x%X, 0x%X!!!" % ((addr + i), block[i], data[i])) if error: print("TEST FAILED") else: print("TEST PASSED") test_pass_count += 1 test_count += 1 print("\r\n\r\n------ TEST ROM READ SPEED ------") test_addr = rom_start test_size = rom_size start = time() block = target.readBlockMemoryUnaligned8(test_addr, test_size) target.flush() stop = time() diff = stop - start print("Reading %i byte took %s seconds: %s B/s" % (test_size, diff, test_size / diff)) print("TEST PASSED") test_pass_count += 1 test_count += 1 target.reset() result.passed = test_count == test_pass_count return result
you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import logging from pyOCD.gdbserver import GDBServer from pyOCD.board import MbedBoard logging.basicConfig(level=logging.INFO) try: board_selected = MbedBoard.chooseBoard() if board_selected != None: gdb = GDBServer(board_selected, 3333) while gdb.isAlive(): gdb.join(timeout = 0.5) except KeyboardInterrupt: gdb.stop() except Exception as e: print "uncaught exception: %s" % e gdb.stop()
def flash_test(board_id): with MbedBoard.chooseBoard(board_id=board_id, frequency=1000000) as board: target_type = board.getTargetType() test_clock = 10000000 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 memory_map = board.target.getMemoryMap() ram_regions = [region for region in memory_map if region.type == 'ram'] ram_region = ram_regions[0] ram_start = ram_region.start ram_size = ram_region.length # Grab boot flash and any regions coming immediately after rom_region = memory_map.getBootMemory() rom_start = rom_region.start rom_size = rom_region.length for region in memory_map: if region.isFlash and (region.start == rom_start + rom_size): rom_size += region.length target = board.target link = board.link flash = board.flash link.set_clock(test_clock) link.set_deferred_transfer(True) test_pass_count = 0 test_count = 0 result = FlashTestResult() def print_progress(progress): assert progress >= 0.0 assert progress <= 1.0 assert (progress == 0 and print_progress.prev_progress == 1.0) or (progress >= print_progress.prev_progress) # Reset state on 0.0 if progress == 0.0: print_progress.prev_progress = 0 print_progress.backwards_progress = False print_progress.done = False # Check for backwards progress if progress < print_progress.prev_progress: print_progress.backwards_progress = True print_progress.prev_progress = progress # print progress bar if not print_progress.done: sys.stdout.write('\r') i = int(progress * 20.0) sys.stdout.write("[%-20s] %3d%%" % ('=' * i, round(progress * 100))) sys.stdout.flush() # Finish on 1.0 if progress >= 1.0: if not print_progress.done: print_progress.done = True sys.stdout.write("\n") if print_progress.backwards_progress: print("Progress went backwards during flash") print_progress.prev_progress = 0 binary_file = os.path.join(parentdir, 'binaries', board.getTestBinary()) with open(binary_file, "rb") as f: data = f.read() data = struct.unpack("%iB" % len(data), data) unused = rom_size - len(data) addr = rom_start size = len(data) # Turn on extra checks for the next 4 tests flash.setFlashAlgoDebug(True) print("\r\n\r\n------ Test Basic Page Erase ------") info = flash.flashBlock(addr, data, False, False, progress_cb=print_progress) data_flashed = target.readBlockMemoryUnaligned8(addr, size) if same(data_flashed, data) and info.program_type is FlashBuilder.FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print("\r\n\r\n------ Test Basic Chip Erase ------") info = flash.flashBlock(addr, data, False, True, progress_cb=print_progress) data_flashed = target.readBlockMemoryUnaligned8(addr, size) if same(data_flashed, data) and info.program_type is FlashBuilder.FLASH_CHIP_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print("\r\n\r\n------ Test Smart Page Erase ------") info = flash.flashBlock(addr, data, True, False, progress_cb=print_progress) data_flashed = target.readBlockMemoryUnaligned8(addr, size) if same(data_flashed, data) and info.program_type is FlashBuilder.FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print("\r\n\r\n------ Test Smart Chip Erase ------") info = flash.flashBlock(addr, data, True, True, progress_cb=print_progress) data_flashed = target.readBlockMemoryUnaligned8(addr, size) if same(data_flashed, data) and info.program_type is FlashBuilder.FLASH_CHIP_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 flash.setFlashAlgoDebug(False) print("\r\n\r\n------ Test Basic Page Erase (Entire chip) ------") new_data = list(data) new_data.extend(unused * [0x77]) info = flash.flashBlock(addr, new_data, False, False, progress_cb=print_progress) if info.program_type == FlashBuilder.FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 result.page_erase_rate = float(len(new_data)) / float( info.program_time) else: print("TEST FAILED") test_count += 1 print("\r\n\r\n------ Test Fast Verify ------") info = flash.flashBlock(addr, new_data, progress_cb=print_progress, fast_verify=True) if info.program_type == FlashBuilder.FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print("\r\n\r\n------ Test Offset Write ------") addr = rom_start + rom_size / 2 page_size = flash.getPageInfo(addr).size new_data = [0x55] * page_size * 2 info = flash.flashBlock(addr, new_data, progress_cb=print_progress) data_flashed = target.readBlockMemoryUnaligned8(addr, len(new_data)) if same(data_flashed, new_data ) and info.program_type is FlashBuilder.FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print("\r\n\r\n------ Test Multiple Block Writes ------") addr = rom_start + rom_size / 2 page_size = flash.getPageInfo(addr).size more_data = [0x33] * page_size * 2 addr = (rom_start + rom_size / 2) + 1 #cover multiple pages fb = flash.getFlashBuilder() fb.addData(rom_start, data) fb.addData(addr, more_data) fb.program(progress_cb=print_progress) data_flashed = target.readBlockMemoryUnaligned8(rom_start, len(data)) data_flashed_more = target.readBlockMemoryUnaligned8( addr, len(more_data)) if same(data_flashed, data) and same(data_flashed_more, more_data): print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print("\r\n\r\n------ Test Overlapping Blocks ------") test_pass = False addr = (rom_start + rom_size / 2) #cover multiple pages page_size = flash.getPageInfo(addr).size new_data = [0x33] * page_size fb = flash.getFlashBuilder() fb.addData(addr, new_data) try: fb.addData(addr + 1, new_data) except ValueError as e: print("Exception: %s" % e) test_pass = True if test_pass: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print("\r\n\r\n------ Test Empty Block Write ------") # Freebee if nothing asserts fb = flash.getFlashBuilder() fb.program() print("TEST PASSED") test_pass_count += 1 test_count += 1 print("\r\n\r\n------ Test Missing Progress Callback ------") # Freebee if nothing asserts addr = rom_start flash.flashBlock(rom_start, data, True) print("TEST PASSED") test_pass_count += 1 test_count += 1 # Only run test if the reset handler can be programmed (rom start at address 0) if rom_start == 0: print("\r\n\r\n------ Test Non-Thumb reset handler ------") non_thumb_data = list(data) # Clear bit 0 of 2nd word - reset handler non_thumb_data[4] = non_thumb_data[4] & ~1 flash.flashBlock(rom_start, non_thumb_data) flash.flashBlock(rom_start, data) print("TEST PASSED") test_pass_count += 1 test_count += 1 # Note - The decision based tests below are order dependent since they # depend on the previous state of the flash print("\r\n\r\n------ Test Chip Erase Decision ------") new_data = list(data) new_data.extend([0xff] * unused) # Pad with 0xFF info = flash.flashBlock(addr, new_data, progress_cb=print_progress) if info.program_type == FlashBuilder.FLASH_CHIP_ERASE: print("TEST PASSED") test_pass_count += 1 result.chip_erase_rate_erased = float(len(new_data)) / float( info.program_time) else: print("TEST FAILED") test_count += 1 print("\r\n\r\n------ Test Chip Erase Decision 2 ------") new_data = list(data) new_data.extend([0x00] * unused) # Pad with 0x00 info = flash.flashBlock(addr, new_data, progress_cb=print_progress) if info.program_type == FlashBuilder.FLASH_CHIP_ERASE: print("TEST PASSED") test_pass_count += 1 result.chip_erase_rate = float(len(new_data)) / float( info.program_time) else: print("TEST FAILED") test_count += 1 print("\r\n\r\n------ Test Page Erase Decision ------") new_data = list(data) new_data.extend([0x00] * unused) # Pad with 0x00 info = flash.flashBlock(addr, new_data, progress_cb=print_progress) if info.program_type == FlashBuilder.FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 result.page_erase_rate_same = float(len(new_data)) / float( info.program_time) result.analyze = info.analyze_type result.analyze_time = info.analyze_time result.analyze_rate = float(len(new_data)) / float( info.analyze_time) else: print("TEST FAILED") test_count += 1 print("\r\n\r\n------ Test Page Erase Decision 2 ------") new_data = list(data) size_same = unused * 5 / 6 size_differ = unused - size_same new_data.extend([0x00] * size_same) # Pad 5/6 with 0x00 and 1/6 with 0xFF new_data.extend([0x55] * size_differ) info = flash.flashBlock(addr, new_data, progress_cb=print_progress) if info.program_type == FlashBuilder.FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print("\r\n\r\nTest Summary:") print("Pass count %i of %i tests" % (test_pass_count, test_count)) if test_pass_count == test_count: print("FLASH TEST SCRIPT PASSED") else: print("FLASH TEST SCRIPT FAILED") target.reset() result.passed = test_count == test_pass_count return result
build_type = build_types[0].strip().split("=")[1] if build_type != "Debug": raise Exception("CMAKE_BUILD_TYPE was '%s', expected 'Debug'. Rebuild with `yt build -d`." % build_type) # create crashdump folder mkdir_p("crashdump") # copy over AXF file potential_axf = [f for f in os.listdir(yotta_build_path) if isfile(join(yotta_build_path, f)) and "." not in f] if len(potential_axf) != 1: raise Exception("Found %d files without extension in %s, expected 1" % (len(potential_axf), yotta_build_path)) copyfile(join(yotta_build_path, potential_axf[0]), "crashdump/" + potential_axf[0] + ".axf") print "[2/6] Build verified. Connecting to board..." with MbedBoard.chooseBoard(frequency=10000000) as board: memory_map = board.target.getMemoryMap() ram_regions = [region for region in memory_map if region.type == 'ram'] ram_region = ram_regions[0] rom_region = memory_map.getBootMemory() target_type = board.getTargetType() print "[3/6] Board recognized as %s. Downloading ROM..." % target_type addr = rom_region.start size = rom_region.length data = board.target.readBlockMemoryUnaligned8(addr, size) data = bytearray(data) with open("crashdump/rom.bin", 'wb') as f: f.write(data)
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 speed_test(board_id): with MbedBoard.chooseBoard(board_id = board_id, frequency = 1000000) as board: target_type = board.getTargetType() test_clock = 10000000 if target_type == "kl25z": ram_start = 0x1ffff000 ram_size = 0x4000 rom_start = 0x00000000 rom_size = 0x20000 elif target_type == "kl46z": ram_start = 0x1fffe000 ram_size = 0x8000 rom_start = 0x00000000 rom_size = 0x40000 elif target_type == "k22f": ram_start = 0x1fff0000 ram_size = 0x20000 rom_start = 0x00000000 rom_size = 0x80000 elif target_type == "k64f": ram_start = 0x1FFF0000 ram_size = 0x40000 rom_start = 0x00000000 rom_size = 0x100000 elif target_type == "lpc11u24": ram_start = 0x10000000 ram_size = 0x2000 rom_start = 0x00000000 rom_size = 0x8000 elif target_type == "lpc1768": ram_start = 0x10000000 ram_size = 0x8000 rom_start = 0x00000000 rom_size = 0x80000 elif target_type == "lpc800": ram_start = 0x10000000 ram_size = 0x1000 rom_start = 0x00000000 rom_size = 0x4000 elif target_type == "lpc4330": ram_start = 0x10000000 ram_size = 0x20000 rom_start = 0x14000000 rom_size = 0x100000 elif target_type == "nrf51822": ram_start = 0x20000000 ram_size = 0x4000 rom_start = 0x00000000 rom_size = 0x40000 # Override clock since 10MHz is too fast test_clock = 1000000 elif target_type == "maxwsnenv": ram_start = 0x20000000 ram_size = 0x8000 rom_start = 0x00000000 rom_size = 0x40000 elif target_type == "max32600mbed": ram_start = 0x20000000 ram_size = 0x8000 rom_start = 0x00000000 rom_size = 0x40000 else: raise Exception("The board is not supported by this test script.") target = board.target transport = board.transport flash = board.flash interface = board.interface test_pass_count = 0 test_count = 0 transport.setClock(test_clock) print "\r\n\r\n------ TEST RAM READ / WRITE SPEED ------" test_addr = ram_start test_size = ram_size data = [randrange(1, 50) for x in range(test_size)] start = time() target.writeBlockMemoryUnaligned8(test_addr, data) stop = time() diff = stop-start write_speed = test_size / diff print("Writing %i byte took %s seconds: %s B/s" % (test_size, diff, write_speed)) start = time() block = target.readBlockMemoryUnaligned8(test_addr, test_size) stop = time() diff = stop-start read_speed = test_size / diff print("Reading %i byte took %s seconds: %s B/s" % (test_size, diff, read_speed)) error = False for i in range(len(block)): if (block[i] != data[i]): error = True print "ERROR: 0x%X, 0x%X, 0x%X!!!" % ((addr + i), block[i], data[i]) if error: print "TEST FAILED" else: print "TEST PASSED" test_pass_count += 1 test_count += 1 print "\r\n\r\n------ TEST ROM READ SPEED ------" test_addr = rom_start test_size = rom_size start = time() block = target.readBlockMemoryUnaligned8(test_addr, test_size) stop = time() diff = stop-start print("Reading %i byte took %s seconds: %s B/s" % (test_size, diff, test_size / diff)) print "TEST PASSED" test_pass_count += 1 test_count += 1 target.reset() return (test_count == test_pass_count, write_speed, read_speed)
def speed_test(board_id): with MbedBoard.chooseBoard(board_id=board_id, frequency=1000000) as board: target_type = board.getTargetType() test_clock = 10000000 if target_type == "kl25z": ram_start = 0x1ffff000 ram_size = 0x4000 rom_start = 0x00000000 rom_size = 0x20000 elif target_type == "kl28z": ram_start = 0x1fffa000 ram_size = 96 * 1024 rom_start = 0x00000000 rom_size = 512 * 1024 elif target_type == "kl46z": ram_start = 0x1fffe000 ram_size = 0x8000 rom_start = 0x00000000 rom_size = 0x40000 elif target_type == "k22f": ram_start = 0x1fff0000 ram_size = 0x20000 rom_start = 0x00000000 rom_size = 0x80000 elif target_type == "k64f": ram_start = 0x1FFF0000 ram_size = 0x40000 rom_start = 0x00000000 rom_size = 0x100000 elif target_type == "lpc11u24": ram_start = 0x10000000 ram_size = 0x2000 rom_start = 0x00000000 rom_size = 0x8000 elif target_type == "lpc1768": ram_start = 0x10000000 ram_size = 0x8000 rom_start = 0x00000000 rom_size = 0x80000 elif target_type == "lpc800": ram_start = 0x10000000 ram_size = 0x1000 rom_start = 0x00000000 rom_size = 0x4000 elif target_type == "lpc4330": ram_start = 0x10000000 ram_size = 0x20000 rom_start = 0x14000000 rom_size = 0x100000 elif target_type == "nrf51": ram_start = 0x20000000 ram_size = 0x4000 rom_start = 0x00000000 rom_size = 0x40000 # Override clock since 10MHz is too fast test_clock = 1000000 elif target_type == "maxwsnenv": ram_start = 0x20000000 ram_size = 0x8000 rom_start = 0x00000000 rom_size = 0x40000 elif target_type == "max32600mbed": ram_start = 0x20000000 ram_size = 0x8000 rom_start = 0x00000000 rom_size = 0x40000 elif target_type == "w7500": ram_start = 0x20000000 ram_size = 0x4000 rom_start = 0x00000000 rom_size = 0x20000 else: raise Exception("The board is not supported by this test script.") target = board.target link = board.link test_pass_count = 0 test_count = 0 result = SpeedTestResult() link.set_clock(test_clock) link.set_deferred_transfer(True) print "\r\n\r\n------ TEST RAM READ / WRITE SPEED ------" test_addr = ram_start test_size = ram_size data = [randrange(1, 50) for x in range(test_size)] start = time() target.writeBlockMemoryUnaligned8(test_addr, data) target.flush() stop = time() diff = stop - start result.write_speed = test_size / diff print("Writing %i byte took %s seconds: %s B/s" % (test_size, diff, result.write_speed)) start = time() block = target.readBlockMemoryUnaligned8(test_addr, test_size) target.flush() stop = time() diff = stop - start result.read_speed = test_size / diff print("Reading %i byte took %s seconds: %s B/s" % (test_size, diff, result.read_speed)) error = False for i in range(len(block)): if (block[i] != data[i]): error = True print "ERROR: 0x%X, 0x%X, 0x%X!!!" % ((addr + i), block[i], data[i]) if error: print "TEST FAILED" else: print "TEST PASSED" test_pass_count += 1 test_count += 1 print "\r\n\r\n------ TEST ROM READ SPEED ------" test_addr = rom_start test_size = rom_size start = time() block = target.readBlockMemoryUnaligned8(test_addr, test_size) target.flush() stop = time() diff = stop - start print("Reading %i byte took %s seconds: %s B/s" % (test_size, diff, test_size / diff)) print "TEST PASSED" test_pass_count += 1 test_count += 1 target.reset() result.passed = test_count == test_pass_count return result
def test_gdb(board_id=None): result = GdbTestResult() with MbedBoard.chooseBoard(board_id=board_id) as board: memory_map = board.target.getMemoryMap() ram_regions = [region for region in memory_map if region.type == "ram"] ram_region = ram_regions[0] rom_region = memory_map.getBootMemory() target_type = board.getTargetType() binary_file = os.path.join(parentdir, "binaries", board.getTestBinary()) if board_id is None: board_id = board.getUniqueID() test_clock = 10000000 test_port = 3334 error_on_invalid_access = True # Hardware breakpoints are not supported above 0x20000000 on # CortexM devices ignore_hw_bkpt_result = 1 if ram_region.start >= 0x20000000 else 0 if target_type == "nrf51": # Override clock since 10MHz is too fast test_clock = 1000000 # Reading invalid ram returns 0 or nrf51 error_on_invalid_access = False # Program with initial test image board.flash.flashBinary(binary_file, rom_region.start) board.uninit(False) # Write out the test configuration test_params = {} test_params["rom_start"] = rom_region.start test_params["rom_length"] = rom_region.length test_params["ram_start"] = ram_region.start test_params["ram_length"] = ram_region.length test_params["invalid_start"] = 0xFFFF0000 test_params["invalid_length"] = 0x1000 test_params["expect_error_on_invalid_access"] = error_on_invalid_access test_params["ignore_hw_bkpt_result"] = ignore_hw_bkpt_result with open(TEST_PARAM_FILE, "wb") as f: f.write(json.dumps(test_params)) # Run the test gdb = [PYTHON_GDB, "--command=gdb_script.py"] with open("output.txt", "wb") as f: program = Popen(gdb, stdin=PIPE, stdout=f, stderr=STDOUT) args = ["-p=%i" % test_port, "-f=%i" % test_clock, "-b=%s" % board_id] server = GDBServerTool() server.run(args) program.wait() # Read back the result with open(TEST_RESULT_FILE, "rb") as f: test_result = json.loads(f.read()) # Print results if set(TEST_RESULT_KEYS).issubset(test_result): print("----------------Test Results----------------") print("HW breakpoint count: %s" % test_result["breakpoint_count"]) print("Watchpoint count: %s" % test_result["watchpoint_count"]) print("Average instruction step time: %s" % test_result["step_time_si"]) print("Average single step time: %s" % test_result["step_time_s"]) print("Average over step time: %s" % test_result["step_time_n"]) print("Failure count: %i" % test_result["fail_count"]) result.passed = test_result["fail_count"] == 0 else: result.passed = False # Cleanup os.remove(TEST_RESULT_FILE) os.remove(TEST_PARAM_FILE) return result
def flash_test(board_id): with MbedBoard.chooseBoard(board_id=board_id, frequency=1000000) as board: target_type = board.getTargetType() test_clock = 10000000 if target_type == "kl25z": ram_start = 0x1ffff000 ram_size = 0x4000 rom_start = 0x00000000 rom_size = 0x20000 elif target_type == "kl28z": ram_start = 0x1fffa000 ram_size = 96 * 1024 rom_start = 0x00000000 rom_size = 512 * 1024 elif target_type == "kl46z": ram_start = 0x1fffe000 ram_size = 0x8000 rom_start = 0x00000000 rom_size = 0x40000 elif target_type == "k22f": ram_start = 0x1fff0000 ram_size = 0x20000 rom_start = 0x00000000 rom_size = 0x80000 elif target_type == "k64f": ram_start = 0x1FFF0000 ram_size = 0x40000 rom_start = 0x00000000 rom_size = 0x100000 elif target_type == "lpc11u24": ram_start = 0x10000000 ram_size = 0x2000 rom_start = 0x00000000 rom_size = 0x8000 elif target_type == "lpc1768": ram_start = 0x10000000 ram_size = 0x8000 rom_start = 0x00000000 rom_size = 0x80000 elif target_type == "lpc4330": ram_start = 0x10000000 ram_size = 0x20000 rom_start = 0x14000000 rom_size = 0x100000 elif target_type == "lpc800": ram_start = 0x10000000 ram_size = 0x1000 rom_start = 0x00000000 rom_size = 0x4000 elif target_type == "nrf51": ram_start = 0x20000000 ram_size = 0x4000 rom_start = 0x00000000 rom_size = 0x40000 # Override clock since 10MHz is too fast test_clock = 1000000 elif target_type == "maxwsnenv": ram_start = 0x20000000 ram_size = 0x8000 rom_start = 0x00000000 rom_size = 0x40000 elif target_type == "max32600mbed": ram_start = 0x20000000 ram_size = 0x8000 rom_start = 0x00000000 rom_size = 0x40000 elif target_type == "w7500": ram_start = 0x20000000 ram_size = 0x4000 rom_start = 0x00000000 rom_size = 0x20000 else: raise Exception("The board is not supported by this test script.") target = board.target transport = board.transport flash = board.flash interface = board.interface transport.setClock(test_clock) transport.setDeferredTransfer(True) test_pass_count = 0 test_count = 0 result = FlashTestResult() def print_progress(progress): assert progress >= 0.0 assert progress <= 1.0 assert (progress == 0 and print_progress.prev_progress == 1.0) or (progress >= print_progress.prev_progress) # Reset state on 0.0 if progress == 0.0: print_progress.prev_progress = 0 print_progress.backwards_progress = False print_progress.done = False # Check for backwards progress if progress < print_progress.prev_progress: print_progress.backwards_progress = True print_progress.prev_progress = progress # print progress bar if not print_progress.done: sys.stdout.write('\r') i = int(progress * 20.0) sys.stdout.write("[%-20s] %3d%%" % ('=' * i, round(progress * 100))) sys.stdout.flush() # Finish on 1.0 if progress >= 1.0: if not print_progress.done: print_progress.done = True sys.stdout.write("\n") if print_progress.backwards_progress: print("Progress went backwards during flash") print_progress.prev_progress = 0 binary_file = os.path.join(parentdir, 'binaries', board.getTestBinary()) with open(binary_file, "rb") as f: data = f.read() data = struct.unpack("%iB" % len(data), data) unused = rom_size - len(data) addr = rom_start size = len(data) # Turn on extra checks for the next 4 tests flash.setFlashAlgoDebug(True) print "\r\n\r\n------ Test Basic Page Erase ------" info = flash.flashBlock(addr, data, False, False, progress_cb=print_progress) data_flashed = target.readBlockMemoryUnaligned8(addr, size) if same(data_flashed, data) and info.program_type is FlashBuilder.FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Basic Chip Erase ------" info = flash.flashBlock(addr, data, False, True, progress_cb=print_progress) data_flashed = target.readBlockMemoryUnaligned8(addr, size) if same(data_flashed, data) and info.program_type is FlashBuilder.FLASH_CHIP_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Smart Page Erase ------" info = flash.flashBlock(addr, data, True, False, progress_cb=print_progress) data_flashed = target.readBlockMemoryUnaligned8(addr, size) if same(data_flashed, data) and info.program_type is FlashBuilder.FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Smart Chip Erase ------" info = flash.flashBlock(addr, data, True, True, progress_cb=print_progress) data_flashed = target.readBlockMemoryUnaligned8(addr, size) if same(data_flashed, data) and info.program_type is FlashBuilder.FLASH_CHIP_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 flash.setFlashAlgoDebug(False) print "\r\n\r\n------ Test Basic Page Erase (Entire chip) ------" new_data = list(data) new_data.extend(unused * [0x77]) info = flash.flashBlock(0, new_data, False, False, progress_cb=print_progress) if info.program_type == FlashBuilder.FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 result.page_erase_rate = float(len(new_data)) / float(info.program_time) else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Fast Verify ------" info = flash.flashBlock(0, new_data, progress_cb=print_progress, fast_verify=True) if info.program_type == FlashBuilder.FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Offset Write ------" addr = rom_start + rom_size / 2 page_size = flash.getPageInfo(addr).size new_data = [0x55] * page_size * 2 info = flash.flashBlock(addr, new_data, progress_cb=print_progress) data_flashed = target.readBlockMemoryUnaligned8(addr, len(new_data)) if same(data_flashed, new_data) and info.program_type is FlashBuilder.FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Multiple Block Writes ------" addr = rom_start + rom_size / 2 page_size = flash.getPageInfo(addr).size more_data = [0x33] * page_size * 2 addr = (rom_start + rom_size / 2) + 1 #cover multiple pages fb = flash.getFlashBuilder() fb.addData(rom_start, data) fb.addData(addr, more_data) fb.program(progress_cb=print_progress) data_flashed = target.readBlockMemoryUnaligned8(rom_start, len(data)) data_flashed_more = target.readBlockMemoryUnaligned8(addr, len(more_data)) if same(data_flashed, data) and same(data_flashed_more, more_data): print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Overlapping Blocks ------" test_pass = False addr = (rom_start + rom_size / 2) #cover multiple pages page_size = flash.getPageInfo(addr).size new_data = [0x33] * page_size fb = flash.getFlashBuilder() fb.addData(addr, new_data) try: fb.addData(addr + 1, new_data) except ValueError as e: print("Exception: %s" % e) test_pass = True if test_pass: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Empty Block Write ------" # Freebee if nothing asserts fb = flash.getFlashBuilder() fb.program() print("TEST PASSED") test_pass_count += 1 test_count += 1 print "\r\n\r\n------ Test Missing Progress Callback ------" # Freebee if nothing asserts addr = rom_start flash.flashBlock(rom_start, data, True) print("TEST PASSED") test_pass_count += 1 test_count += 1 # Only run test if the reset handler can be programmed (rom start at address 0) if rom_start == 0: print "\r\n\r\n------ Test Non-Thumb reset handler ------" non_thumb_data = list(data) # Clear bit 0 of 2nd word - reset handler non_thumb_data[4] = non_thumb_data[4] & ~1 flash.flashBlock(rom_start, non_thumb_data) flash.flashBlock(rom_start, data) print("TEST PASSED") test_pass_count += 1 test_count += 1 # Note - The decision based tests below are order dependent since they # depend on the previous state of the flash print "\r\n\r\n------ Test Chip Erase Decision ------" new_data = list(data) new_data.extend([0xff] * unused) # Pad with 0xFF info = flash.flashBlock(0, new_data, progress_cb=print_progress) if info.program_type == FlashBuilder.FLASH_CHIP_ERASE: print("TEST PASSED") test_pass_count += 1 result.chip_erase_rate_erased = float(len(new_data)) / float(info.program_time) else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Chip Erase Decision 2 ------" new_data = list(data) new_data.extend([0x00] * unused) # Pad with 0x00 info = flash.flashBlock(0, new_data, progress_cb=print_progress) if info.program_type == FlashBuilder.FLASH_CHIP_ERASE: print("TEST PASSED") test_pass_count += 1 result.chip_erase_rate = float(len(new_data)) / float(info.program_time) else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Page Erase Decision ------" new_data = list(data) new_data.extend([0x00] * unused) # Pad with 0x00 info = flash.flashBlock(0, new_data, progress_cb=print_progress) if info.program_type == FlashBuilder.FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 result.page_erase_rate_same = float(len(new_data)) / float(info.program_time) result.analyze = info.analyze_type result.analyze_time = info.analyze_time result.analyze_rate = float(len(new_data)) / float(info.analyze_time) else: print("TEST FAILED") test_count += 1 print "\r\n\r\n------ Test Page Erase Decision 2 ------" new_data = list(data) size_same = unused * 5 / 6 size_differ = unused - size_same new_data.extend([0x00] * size_same) # Pad 5/6 with 0x00 and 1/6 with 0xFF new_data.extend([0x55] * size_differ) info = flash.flashBlock(0, new_data, progress_cb=print_progress) if info.program_type == FlashBuilder.FLASH_PAGE_ERASE: print("TEST PASSED") test_pass_count += 1 else: print("TEST FAILED") test_count += 1 print("\r\n\r\nTest Summary:") print("Pass count %i of %i tests" % (test_pass_count, test_count)) if test_pass_count == test_count: print("FLASH TEST SCRIPT PASSED") else: print("FLASH TEST SCRIPT FAILED") target.reset() result.passed = test_count == test_pass_count return result
parser = OptionParser() parser.add_option("-p", "--port", dest = "port_number", default = 3333, help = "Write the port number that GDB server will open") parser.add_option("-b", "--board", dest = "board_id", default = None, help = "Write the board id you want to connect") parser.add_option("-l", "--list", action = "store_true", dest = "list_all", default = False, help = "List all the connected board") parser.add_option("-d", "--debug", dest = "debug_level", default = 'info', help = "Set the level of system logging output, the available value for DEBUG_LEVEL: debug, info, warning, error, critical" ) (option, args) = parser.parse_args() gdb = None level = LEVELS.get(option.debug_level, logging.NOTSET) logging.basicConfig(level=level) if option.list_all == True: MbedBoard.listConnectedBoards() else: try: board_selected = MbedBoard.chooseBoard(board_id = option.board_id) if board_selected != None: try: gdb = GDBServer(board_selected, int(option.port_number)) while gdb.isAlive(): gdb.join(timeout = 0.5) except ValueError: logging.error("Port number error!") except KeyboardInterrupt: if gdb != None: gdb.shutdown_event.set() #gdb.stop() except Exception as e: print "uncaught exception: %s" % e traceback.print_exc() if gdb != None:
def read_target_memory(self, addr, size, resume=True): assert self.get_mode() == self.MODE_IF with MbedBoard.chooseBoard(board_id=self.get_unique_id()) as board: data = board.target.readBlockMemoryUnaligned8(addr, size) board.uninit(resume) return bytearray(data)
def run(self): try: # Read command-line arguments. self.args = self.get_args() self.cmd = self.args.cmd if self.cmd: self.cmd = self.cmd.lower() # Set logging level self.configure_logging() # Check for a valid command. if self.cmd and self.cmd not in self.command_list: print "Error: unrecognized command '%s'" % self.cmd return 1 # List command must be dealt with specially. if self.cmd == 'list': self.handle_list([]) return 0 if self.args.clock != DEFAULT_CLOCK_FREQ_KHZ: print "Setting SWD clock to %d kHz" % self.args.clock # Connect to board. self.board = MbedBoard.chooseBoard(board_id=self.args.board, target_override=self.args.target, init_board=False, frequency=(self.args.clock * 1000)) self.board.target.setAutoUnlock(False) self.board.target.setHaltOnConnect(False) try: self.board.init() except Exception as e: print "Exception while initing board:", e self.target = self.board.target self.link = self.board.link self.flash = self.board.flash # Halt if requested. if self.args.halt: self.handle_halt([]) # Handle a device with flash security enabled. self.didErase = False if self.target.isLocked() and self.cmd != 'unlock': print "Error: Target is locked, cannot complete operation. Use unlock command to mass erase and unlock." if self.cmd and self.cmd not in ['reset', 'info']: return 1 # If no command, enter interactive mode. if not self.cmd: # Say what we're connected to. print "Connected to %s [%s]: %s" % (self.target.part_number, CORE_STATUS_DESC[self.target.getState()], self.board.getUniqueID()) # Remove list command that disrupts the connection. self.command_list.pop('list') COMMAND_INFO.pop('list') # Run the command line. console = PyOCDConsole(self) console.run() else: # Invoke action handler. result = self.command_list[self.cmd](self.args.args) if result is not None: self.exitCode = result except ToolExitException: self.exitCode = 0 except ValueError: print "Error: invalid argument" except DAPAccess.TransferError: print "Error: transfer failed" self.exitCode = 2 except ToolError as e: print "Error:", e self.exitCode = 1 finally: if self.board != None: # Pass false to prevent target resume. self.board.uninit(False) return self.exitCode
"--persist", dest="persist", default=False, action="store_true", help="Keep GDB server running even after remote has detached.") (option, args) = parser.parse_args() gdb = None level = LEVELS.get(option.debug_level, logging.NOTSET) logging.basicConfig(level=level) if option.list_all == True: MbedBoard.listConnectedBoards() else: try: board_selected = MbedBoard.chooseBoard( board_id=option.board_id, target_override=option.target_override, frequency=option.debug_clock_frequency) print board_selected with board_selected as board: gdb = GDBServer( board, int(option.port_number), { 'break_at_hardfault': option.break_at_hardfault, 'step_into_interrupt': option.step_into_interrupt, 'break_on_reset': option.break_on_reset, 'persist': option.persist }) while gdb.isAlive(): gdb.join(timeout=0.5) except KeyboardInterrupt: if gdb != None: gdb.stop()