INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Erases the flash contents of the device. This erases the flash memory of the target device. If this method fails, the device may be left in an inoperable state. Args: self (JLink): the ``JLink`` instance Returns: Number of bytes erased.
def erase(self): """Erases the flash contents of the device. This erases the flash memory of the target device. If this method fails, the device may be left in an inoperable state. Args: self (JLink): the ``JLink`` instance Returns: Number of bytes erased. """ try: # This has to be in a try-catch, as the device may not be in a # state where it can halt, but we still want to try and erase. if not self.halted(): self.halt() except errors.JLinkException: # Can't halt, so just continue to erasing. pass res = self._dll.JLINK_EraseChip() if res < 0: raise errors.JLinkEraseException(res) return res
Flashes the target device. The given ``on_progress`` callback will be called as ``on_progress(action, progress_string, percentage)`` periodically as the data is written to flash. The action is one of ``Compare``, ``Erase``, ``Verify``, ``Flash``. Args: self (JLink): the ``JLink`` instance data (list): list of bytes to write to flash addr (int): start address on flash which to write the data on_progress (function): callback to be triggered on flash progress power_on (boolean): whether to power the target before flashing flags (int): reserved, do not use Returns: Number of bytes flashed. This number may not necessarily be equal to ``len(data)``, but that does not indicate an error. Raises: JLinkException: on hardware errors.
def flash(self, data, addr, on_progress=None, power_on=False, flags=0): """Flashes the target device. The given ``on_progress`` callback will be called as ``on_progress(action, progress_string, percentage)`` periodically as the data is written to flash. The action is one of ``Compare``, ``Erase``, ``Verify``, ``Flash``. Args: self (JLink): the ``JLink`` instance data (list): list of bytes to write to flash addr (int): start address on flash which to write the data on_progress (function): callback to be triggered on flash progress power_on (boolean): whether to power the target before flashing flags (int): reserved, do not use Returns: Number of bytes flashed. This number may not necessarily be equal to ``len(data)``, but that does not indicate an error. Raises: JLinkException: on hardware errors. """ if flags != 0: raise errors.JLinkException('Flags are reserved for future use.') if on_progress is not None: # Set the function to be called on flash programming progress. func = enums.JLinkFunctions.FLASH_PROGRESS_PROTOTYPE(on_progress) self._dll.JLINK_SetFlashProgProgressCallback(func) else: self._dll.JLINK_SetFlashProgProgressCallback(0) # First power on the device. if power_on: self.power_on() try: # Stop the target before flashing. This is required to be in a # try-catch as the 'halted()' check may fail with an exception. if not self.halted(): self.halt() except errors.JLinkException: pass res = self.flash_write(addr, data, flags=flags) return res
Flashes the target device. The given ``on_progress`` callback will be called as ``on_progress(action, progress_string, percentage)`` periodically as the data is written to flash. The action is one of ``Compare``, ``Erase``, ``Verify``, ``Flash``. Args: self (JLink): the ``JLink`` instance path (str): absolute path to the source file to flash addr (int): start address on flash which to write the data on_progress (function): callback to be triggered on flash progress power_on (boolean): whether to power the target before flashing Returns: Integer value greater than or equal to zero. Has no significance. Raises: JLinkException: on hardware errors.
def flash_file(self, path, addr, on_progress=None, power_on=False): """Flashes the target device. The given ``on_progress`` callback will be called as ``on_progress(action, progress_string, percentage)`` periodically as the data is written to flash. The action is one of ``Compare``, ``Erase``, ``Verify``, ``Flash``. Args: self (JLink): the ``JLink`` instance path (str): absolute path to the source file to flash addr (int): start address on flash which to write the data on_progress (function): callback to be triggered on flash progress power_on (boolean): whether to power the target before flashing Returns: Integer value greater than or equal to zero. Has no significance. Raises: JLinkException: on hardware errors. """ if on_progress is not None: # Set the function to be called on flash programming progress. func = enums.JLinkFunctions.FLASH_PROGRESS_PROTOTYPE(on_progress) self._dll.JLINK_SetFlashProgProgressCallback(func) else: self._dll.JLINK_SetFlashProgProgressCallback(0) # First power on the device. if power_on: self.power_on() try: # Stop the target before flashing. This is required to be in a # try-catch as the 'halted()' check may fail with an exception. if not self.halted(): self.halt() except errors.JLinkException: pass # Program the target. bytes_flashed = self._dll.JLINK_DownloadFile(path.encode(), addr) if bytes_flashed < 0: raise errors.JLinkFlashException(bytes_flashed) return bytes_flashed
Resets the target. This method resets the target, and by default toggles the RESET and TRST pins. Args: self (JLink): the ``JLink`` instance ms (int): Amount of milliseconds to delay after reset (default: 0) halt (bool): if the CPU should halt after reset (default: True) Returns: Number of bytes read.
def reset(self, ms=0, halt=True): """Resets the target. This method resets the target, and by default toggles the RESET and TRST pins. Args: self (JLink): the ``JLink`` instance ms (int): Amount of milliseconds to delay after reset (default: 0) halt (bool): if the CPU should halt after reset (default: True) Returns: Number of bytes read. """ self._dll.JLINKARM_SetResetDelay(ms) res = self._dll.JLINKARM_Reset() if res < 0: raise errors.JLinkException(res) elif not halt: self._dll.JLINKARM_Go() return res
Restarts the CPU core and simulates/emulates instructions. Note: This is a no-op if the CPU isn't halted. Args: self (JLink): the ``JLink`` instance num_instructions (int): number of instructions to simulate, defaults to zero skip_breakpoints (bool): skip current breakpoint (default: ``False``) Returns: ``True`` if device was restarted, otherwise ``False``. Raises: ValueError: if instruction count is not a natural number.
def restart(self, num_instructions=0, skip_breakpoints=False): """Restarts the CPU core and simulates/emulates instructions. Note: This is a no-op if the CPU isn't halted. Args: self (JLink): the ``JLink`` instance num_instructions (int): number of instructions to simulate, defaults to zero skip_breakpoints (bool): skip current breakpoint (default: ``False``) Returns: ``True`` if device was restarted, otherwise ``False``. Raises: ValueError: if instruction count is not a natural number. """ if not util.is_natural(num_instructions): raise ValueError('Invalid instruction count: %s.' % num_instructions) if not self.halted(): return False flags = 0 if skip_breakpoints: flags = flags | enums.JLinkFlags.GO_OVERSTEP_BP self._dll.JLINKARM_GoEx(num_instructions, flags) return True
Halts the CPU Core. Args: self (JLink): the ``JLink`` instance Returns: ``True`` if halted, ``False`` otherwise.
def halt(self): """Halts the CPU Core. Args: self (JLink): the ``JLink`` instance Returns: ``True`` if halted, ``False`` otherwise. """ res = int(self._dll.JLINKARM_Halt()) if res == 0: time.sleep(1) return True return False
Returns whether the CPU core was halted. Args: self (JLink): the ``JLink`` instance Returns: ``True`` if the CPU core is halted, otherwise ``False``. Raises: JLinkException: on device errors.
def halted(self): """Returns whether the CPU core was halted. Args: self (JLink): the ``JLink`` instance Returns: ``True`` if the CPU core is halted, otherwise ``False``. Raises: JLinkException: on device errors. """ result = int(self._dll.JLINKARM_IsHalted()) if result < 0: raise errors.JLinkException(result) return (result > 0)
Returns the name of the target ARM core. Args: self (JLink): the ``JLink`` instance Returns: The target core's name.
def core_name(self): """Returns the name of the target ARM core. Args: self (JLink): the ``JLink`` instance Returns: The target core's name. """ buf_size = self.MAX_BUF_SIZE buf = (ctypes.c_char * buf_size)() self._dll.JLINKARM_Core2CoreName(self.core_cpu(), buf, buf_size) return ctypes.string_at(buf).decode()
Retrieves and returns the number of bits in the scan chain. Args: self (JLink): the ``JLink`` instance scan_chain (int): scan chain to be measured Returns: Number of bits in the specified scan chain. Raises: JLinkException: on error.
def scan_chain_len(self, scan_chain): """Retrieves and returns the number of bits in the scan chain. Args: self (JLink): the ``JLink`` instance scan_chain (int): scan chain to be measured Returns: Number of bits in the specified scan chain. Raises: JLinkException: on error. """ res = self._dll.JLINKARM_MeasureSCLen(scan_chain) if res < 0: raise errors.JLinkException(res) return res
Returns a list of the indices for the CPU registers. The returned indices can be used to read the register content or grab the register name. Args: self (JLink): the ``JLink`` instance Returns: List of registers.
def register_list(self): """Returns a list of the indices for the CPU registers. The returned indices can be used to read the register content or grab the register name. Args: self (JLink): the ``JLink`` instance Returns: List of registers. """ num_items = self.MAX_NUM_CPU_REGISTERS buf = (ctypes.c_uint32 * num_items)() num_regs = self._dll.JLINKARM_GetRegisterList(buf, num_items) return buf[:num_regs]
Retrives and returns the name of an ARM CPU register. Args: self (JLink): the ``JLink`` instance register_index (int): index of the register whose name to retrieve Returns: Name of the register.
def register_name(self, register_index): """Retrives and returns the name of an ARM CPU register. Args: self (JLink): the ``JLink`` instance register_index (int): index of the register whose name to retrieve Returns: Name of the register. """ result = self._dll.JLINKARM_GetRegisterName(register_index) return ctypes.cast(result, ctypes.c_char_p).value.decode()
Retrieves the CPU speed of the target. If the target does not support CPU frequency detection, this function will return ``0``. Args: self (JLink): the ``JLink`` instance silent (bool): ``True`` if the CPU detection should not report errors to the error handler on failure. Returns: The measured CPU frequency on success, otherwise ``0`` if the core does not support CPU frequency detection. Raises: JLinkException: on hardware error.
def cpu_speed(self, silent=False): """Retrieves the CPU speed of the target. If the target does not support CPU frequency detection, this function will return ``0``. Args: self (JLink): the ``JLink`` instance silent (bool): ``True`` if the CPU detection should not report errors to the error handler on failure. Returns: The measured CPU frequency on success, otherwise ``0`` if the core does not support CPU frequency detection. Raises: JLinkException: on hardware error. """ res = self._dll.JLINKARM_MeasureCPUSpeedEx(-1, 1, int(silent)) if res < 0: raise errors.JLinkException(res) return res
Retrives the reasons that the CPU was halted. Args: self (JLink): the ``JLink`` instance Returns: A list of ``JLInkMOEInfo`` instances specifying the reasons for which the CPU was halted. This list may be empty in the case that the CPU is not halted. Raises: JLinkException: on hardware error.
def cpu_halt_reasons(self): """Retrives the reasons that the CPU was halted. Args: self (JLink): the ``JLink`` instance Returns: A list of ``JLInkMOEInfo`` instances specifying the reasons for which the CPU was halted. This list may be empty in the case that the CPU is not halted. Raises: JLinkException: on hardware error. """ buf_size = self.MAX_NUM_MOES buf = (structs.JLinkMOEInfo * buf_size)() num_reasons = self._dll.JLINKARM_GetMOEs(buf, buf_size) if num_reasons < 0: raise errors.JLinkException(num_reasons) return list(buf)[:num_reasons]
Sends data via JTAG. Sends data via JTAG on the rising clock edge, TCK. At on each rising clock edge, on bit is transferred in from TDI and out to TDO. The clock uses the TMS to step through the standard JTAG state machine. Args: self (JLink): the ``JLink`` instance tms (int): used to determine the state transitions for the Test Access Port (TAP) controller from its current state tdi (int): input data to be transferred in from TDI to TDO num_bits (int): a number in the range ``[1, 32]`` inclusively specifying the number of meaningful bits in the ``tms`` and ``tdi`` parameters for the purpose of extracting state and data information Returns: ``None`` Raises: ValueError: if ``num_bits < 1`` or ``num_bits > 32``. See Also: `JTAG Technical Overview <https://www.xjtag.com/about-jtag/jtag-a-technical-overview>`_.
def jtag_send(self, tms, tdi, num_bits): """Sends data via JTAG. Sends data via JTAG on the rising clock edge, TCK. At on each rising clock edge, on bit is transferred in from TDI and out to TDO. The clock uses the TMS to step through the standard JTAG state machine. Args: self (JLink): the ``JLink`` instance tms (int): used to determine the state transitions for the Test Access Port (TAP) controller from its current state tdi (int): input data to be transferred in from TDI to TDO num_bits (int): a number in the range ``[1, 32]`` inclusively specifying the number of meaningful bits in the ``tms`` and ``tdi`` parameters for the purpose of extracting state and data information Returns: ``None`` Raises: ValueError: if ``num_bits < 1`` or ``num_bits > 32``. See Also: `JTAG Technical Overview <https://www.xjtag.com/about-jtag/jtag-a-technical-overview>`_. """ if not util.is_natural(num_bits) or num_bits <= 0 or num_bits > 32: raise ValueError('Number of bits must be >= 1 and <= 32.') self._dll.JLINKARM_StoreBits(tms, tdi, num_bits) return None
Gets a unit of ``8`` bits from the input buffer. Args: self (JLink): the ``JLink`` instance offset (int): the offset (in bits) from which to start reading Returns: The integer read from the input buffer.
def swd_read8(self, offset): """Gets a unit of ``8`` bits from the input buffer. Args: self (JLink): the ``JLink`` instance offset (int): the offset (in bits) from which to start reading Returns: The integer read from the input buffer. """ value = self._dll.JLINK_SWD_GetU8(offset) return ctypes.c_uint8(value).value
Gets a unit of ``16`` bits from the input buffer. Args: self (JLink): the ``JLink`` instance offset (int): the offset (in bits) from which to start reading Returns: The integer read from the input buffer.
def swd_read16(self, offset): """Gets a unit of ``16`` bits from the input buffer. Args: self (JLink): the ``JLink`` instance offset (int): the offset (in bits) from which to start reading Returns: The integer read from the input buffer. """ value = self._dll.JLINK_SWD_GetU16(offset) return ctypes.c_uint16(value).value
Gets a unit of ``32`` bits from the input buffer. Args: self (JLink): the ``JLink`` instance offset (int): the offset (in bits) from which to start reading Returns: The integer read from the input buffer.
def swd_read32(self, offset): """Gets a unit of ``32`` bits from the input buffer. Args: self (JLink): the ``JLink`` instance offset (int): the offset (in bits) from which to start reading Returns: The integer read from the input buffer. """ value = self._dll.JLINK_SWD_GetU32(offset) return ctypes.c_uint32(value).value
Writes bytes over SWD (Serial Wire Debug). Args: self (JLink): the ``JLink`` instance output (int): the output buffer offset to write to value (int): the value to write to the output buffer nbits (int): the number of bits needed to represent the ``output`` and ``value`` Returns: The bit position of the response in the input buffer.
def swd_write(self, output, value, nbits): """Writes bytes over SWD (Serial Wire Debug). Args: self (JLink): the ``JLink`` instance output (int): the output buffer offset to write to value (int): the value to write to the output buffer nbits (int): the number of bits needed to represent the ``output`` and ``value`` Returns: The bit position of the response in the input buffer. """ pDir = binpacker.pack(output, nbits) pIn = binpacker.pack(value, nbits) bitpos = self._dll.JLINK_SWD_StoreRaw(pDir, pIn, nbits) if bitpos < 0: raise errors.JLinkException(bitpos) return bitpos
Causes a flush to write all data remaining in output buffers to SWD device. Args: self (JLink): the ``JLink`` instance pad (bool): ``True`` if should pad the data to full byte size Returns: ``None``
def swd_sync(self, pad=False): """Causes a flush to write all data remaining in output buffers to SWD device. Args: self (JLink): the ``JLink`` instance pad (bool): ``True`` if should pad the data to full byte size Returns: ``None`` """ if pad: self._dll.JLINK_SWD_SyncBytes() else: self._dll.JLINK_SWD_SyncBits() return None
Writes data to the flash region of a device. The given number of bits, if provided, must be either ``8``, ``16``, or ``32``. Args: self (JLink): the ``JLink`` instance addr (int): starting flash address to write to data (list): list of data units to write nbits (int): number of bits to use for each unit Returns: Number of bytes written to flash.
def flash_write(self, addr, data, nbits=None, flags=0): """Writes data to the flash region of a device. The given number of bits, if provided, must be either ``8``, ``16``, or ``32``. Args: self (JLink): the ``JLink`` instance addr (int): starting flash address to write to data (list): list of data units to write nbits (int): number of bits to use for each unit Returns: Number of bytes written to flash. """ # This indicates that all data written from this point on will go into # the buffer of the flashloader of the DLL. self._dll.JLINKARM_BeginDownload(flags) self.memory_write(addr, data, nbits=nbits) # Start downloading the data into the flash memory. bytes_flashed = self._dll.JLINKARM_EndDownload() if bytes_flashed < 0: raise errors.JLinkFlashException(bytes_flashed) return bytes_flashed
Reads bytes from code memory. Note: This is similar to calling ``memory_read`` or ``memory_read8``, except that this uses a cache and reads ahead. This should be used in instances where you want to read a small amount of bytes at a time, and expect to always read ahead. Args: self (JLink): the ``JLink`` instance addr (int): starting address from which to read num_bytes (int): number of bytes to read Returns: A list of bytes read from the target. Raises: JLinkException: if memory could not be read.
def code_memory_read(self, addr, num_bytes): """Reads bytes from code memory. Note: This is similar to calling ``memory_read`` or ``memory_read8``, except that this uses a cache and reads ahead. This should be used in instances where you want to read a small amount of bytes at a time, and expect to always read ahead. Args: self (JLink): the ``JLink`` instance addr (int): starting address from which to read num_bytes (int): number of bytes to read Returns: A list of bytes read from the target. Raises: JLinkException: if memory could not be read. """ buf_size = num_bytes buf = (ctypes.c_uint8 * buf_size)() res = self._dll.JLINKARM_ReadCodeMem(addr, buf_size, buf) if res < 0: raise errors.JLinkException(res) return list(buf)[:res]
Returns the number of memory zones supported by the target. Args: self (JLink): the ``JLink`` instance Returns: An integer count of the number of memory zones supported by the target. Raises: JLinkException: on error.
def num_memory_zones(self): """Returns the number of memory zones supported by the target. Args: self (JLink): the ``JLink`` instance Returns: An integer count of the number of memory zones supported by the target. Raises: JLinkException: on error. """ count = self._dll.JLINK_GetMemZones(0, 0) if count < 0: raise errors.JLinkException(count) return count
Gets all memory zones supported by the current target. Some targets support multiple memory zones. This function provides the ability to get a list of all the memory zones to facilate using the memory zone routing functions. Args: self (JLink): the ``JLink`` instance Returns: A list of all the memory zones as ``JLinkMemoryZone`` structures. Raises: JLinkException: on hardware errors.
def memory_zones(self): """Gets all memory zones supported by the current target. Some targets support multiple memory zones. This function provides the ability to get a list of all the memory zones to facilate using the memory zone routing functions. Args: self (JLink): the ``JLink`` instance Returns: A list of all the memory zones as ``JLinkMemoryZone`` structures. Raises: JLinkException: on hardware errors. """ count = self.num_memory_zones() if count == 0: return list() buf = (structs.JLinkMemoryZone * count)() res = self._dll.JLINK_GetMemZones(buf, count) if res < 0: raise errors.JLinkException(res) return list(buf)
Reads memory from a target system or specific memory zone. The optional ``zone`` specifies a memory zone to access to read from, e.g. ``IDATA``, ``DDATA``, or ``CODE``. The given number of bits, if provided, must be either ``8``, ``16``, or ``32``. If not provided, always reads ``num_units`` bytes. Args: self (JLink): the ``JLink`` instance addr (int): start address to read from num_units (int): number of units to read zone (str): optional memory zone name to access nbits (int): number of bits to use for each unit Returns: List of units read from the target system. Raises: JLinkException: if memory could not be read. ValueError: if ``nbits`` is not ``None``, and not in ``8``, ``16``, or ``32``.
def memory_read(self, addr, num_units, zone=None, nbits=None): """Reads memory from a target system or specific memory zone. The optional ``zone`` specifies a memory zone to access to read from, e.g. ``IDATA``, ``DDATA``, or ``CODE``. The given number of bits, if provided, must be either ``8``, ``16``, or ``32``. If not provided, always reads ``num_units`` bytes. Args: self (JLink): the ``JLink`` instance addr (int): start address to read from num_units (int): number of units to read zone (str): optional memory zone name to access nbits (int): number of bits to use for each unit Returns: List of units read from the target system. Raises: JLinkException: if memory could not be read. ValueError: if ``nbits`` is not ``None``, and not in ``8``, ``16``, or ``32``. """ buf_size = num_units buf = None access = 0 if nbits is None: buf = (ctypes.c_uint8 * buf_size)() access = 0 elif nbits == 8: buf = (ctypes.c_uint8 * buf_size)() access = 1 elif nbits == 16: buf = (ctypes.c_uint16 * buf_size)() access = 2 buf_size = buf_size * access elif nbits == 32: buf = (ctypes.c_uint32 * buf_size)() access = 4 buf_size = buf_size * access else: raise ValueError('Given bit size is invalid: %s' % nbits) args = [addr, buf_size, buf, access] method = self._dll.JLINKARM_ReadMemEx if zone is not None: method = self._dll.JLINKARM_ReadMemZonedEx args.append(zone.encode()) units_read = method(*args) if units_read < 0: raise errors.JLinkReadException(units_read) return buf[:units_read]
Reads memory from the target system in units of bytes. Args: self (JLink): the ``JLink`` instance addr (int): start address to read from num_bytes (int): number of bytes to read zone (str): memory zone to read from Returns: List of bytes read from the target system. Raises: JLinkException: if memory could not be read.
def memory_read8(self, addr, num_bytes, zone=None): """Reads memory from the target system in units of bytes. Args: self (JLink): the ``JLink`` instance addr (int): start address to read from num_bytes (int): number of bytes to read zone (str): memory zone to read from Returns: List of bytes read from the target system. Raises: JLinkException: if memory could not be read. """ return self.memory_read(addr, num_bytes, zone=zone, nbits=8)
Reads memory from the target system in units of 16-bits. Args: self (JLink): the ``JLink`` instance addr (int): start address to read from num_halfwords (int): number of half words to read zone (str): memory zone to read from Returns: List of halfwords read from the target system. Raises: JLinkException: if memory could not be read
def memory_read16(self, addr, num_halfwords, zone=None): """Reads memory from the target system in units of 16-bits. Args: self (JLink): the ``JLink`` instance addr (int): start address to read from num_halfwords (int): number of half words to read zone (str): memory zone to read from Returns: List of halfwords read from the target system. Raises: JLinkException: if memory could not be read """ return self.memory_read(addr, num_halfwords, zone=zone, nbits=16)
Reads memory from the target system in units of 32-bits. Args: self (JLink): the ``JLink`` instance addr (int): start address to read from num_words (int): number of words to read zone (str): memory zone to read from Returns: List of words read from the target system. Raises: JLinkException: if memory could not be read
def memory_read32(self, addr, num_words, zone=None): """Reads memory from the target system in units of 32-bits. Args: self (JLink): the ``JLink`` instance addr (int): start address to read from num_words (int): number of words to read zone (str): memory zone to read from Returns: List of words read from the target system. Raises: JLinkException: if memory could not be read """ return self.memory_read(addr, num_words, zone=zone, nbits=32)
Reads memory from the target system in units of 64-bits. Args: self (JLink): the ``JLink`` instance addr (int): start address to read from num_long_words (int): number of long words to read Returns: List of long words read from the target system. Raises: JLinkException: if memory could not be read
def memory_read64(self, addr, num_long_words): """Reads memory from the target system in units of 64-bits. Args: self (JLink): the ``JLink`` instance addr (int): start address to read from num_long_words (int): number of long words to read Returns: List of long words read from the target system. Raises: JLinkException: if memory could not be read """ buf_size = num_long_words buf = (ctypes.c_ulonglong * buf_size)() units_read = self._dll.JLINKARM_ReadMemU64(addr, buf_size, buf, 0) if units_read < 0: raise errors.JLinkException(units_read) return buf[:units_read]
Writes memory to a target system or specific memory zone. The optional ``zone`` specifies a memory zone to access to write to, e.g. ``IDATA``, ``DDATA``, or ``CODE``. The given number of bits, if provided, must be either ``8``, ``16``, or ``32``. Args: self (JLink): the ``JLink`` instance addr (int): start address to write to data (list): list of data units to write zone (str): optional memory zone name to access nbits (int): number of bits to use for each unit Returns: Number of units written. Raises: JLinkException: on write hardware failure. ValueError: if ``nbits`` is not ``None``, and not in ``8``, ``16`` or ``32``.
def memory_write(self, addr, data, zone=None, nbits=None): """Writes memory to a target system or specific memory zone. The optional ``zone`` specifies a memory zone to access to write to, e.g. ``IDATA``, ``DDATA``, or ``CODE``. The given number of bits, if provided, must be either ``8``, ``16``, or ``32``. Args: self (JLink): the ``JLink`` instance addr (int): start address to write to data (list): list of data units to write zone (str): optional memory zone name to access nbits (int): number of bits to use for each unit Returns: Number of units written. Raises: JLinkException: on write hardware failure. ValueError: if ``nbits`` is not ``None``, and not in ``8``, ``16`` or ``32``. """ buf_size = len(data) buf = None access = 0 if nbits is None: # Pack the given data into an array of 8-bit unsigned integers in # order to write it successfully packed_data = map(lambda d: reversed(binpacker.pack(d)), data) packed_data = list(itertools.chain(*packed_data)) buf_size = len(packed_data) buf = (ctypes.c_uint8 * buf_size)(*packed_data) # Allow the access width to be chosen for us. access = 0 elif nbits == 8: buf = (ctypes.c_uint8 * buf_size)(*data) access = 1 elif nbits == 16: buf = (ctypes.c_uint16 * buf_size)(*data) access = 2 buf_size = buf_size * access elif nbits == 32: buf = (ctypes.c_uint32 * buf_size)(*data) access = 4 buf_size = buf_size * access else: raise ValueError('Given bit size is invalid: %s' % nbits) args = [addr, buf_size, buf, access] method = self._dll.JLINKARM_WriteMemEx if zone is not None: method = self._dll.JLINKARM_WriteMemZonedEx args.append(zone.encode()) units_written = method(*args) if units_written < 0: raise errors.JLinkWriteException(units_written) return units_written
Writes bytes to memory of a target system. Args: self (JLink): the ``JLink`` instance addr (int): start address to write to data (list): list of bytes to write zone (str): optional memory zone to access Returns: Number of bytes written to target. Raises: JLinkException: on memory access error.
def memory_write8(self, addr, data, zone=None): """Writes bytes to memory of a target system. Args: self (JLink): the ``JLink`` instance addr (int): start address to write to data (list): list of bytes to write zone (str): optional memory zone to access Returns: Number of bytes written to target. Raises: JLinkException: on memory access error. """ return self.memory_write(addr, data, zone, 8)
Writes half-words to memory of a target system. Args: self (JLink): the ``JLink`` instance addr (int): start address to write to data (list): list of half-words to write zone (str): optional memory zone to access Returns: Number of half-words written to target. Raises: JLinkException: on memory access error.
def memory_write16(self, addr, data, zone=None): """Writes half-words to memory of a target system. Args: self (JLink): the ``JLink`` instance addr (int): start address to write to data (list): list of half-words to write zone (str): optional memory zone to access Returns: Number of half-words written to target. Raises: JLinkException: on memory access error. """ return self.memory_write(addr, data, zone, 16)
Writes words to memory of a target system. Args: self (JLink): the ``JLink`` instance addr (int): start address to write to data (list): list of words to write zone (str): optional memory zone to access Returns: Number of words written to target. Raises: JLinkException: on memory access error.
def memory_write32(self, addr, data, zone=None): """Writes words to memory of a target system. Args: self (JLink): the ``JLink`` instance addr (int): start address to write to data (list): list of words to write zone (str): optional memory zone to access Returns: Number of words written to target. Raises: JLinkException: on memory access error. """ return self.memory_write(addr, data, zone, 32)
Writes long words to memory of a target system. Note: This is little-endian. Args: self (JLink): the ``JLink`` instance addr (int): start address to write to data (list): list of long words to write zone (str): optional memory zone to access Returns: Number of long words written to target. Raises: JLinkException: on memory access error.
def memory_write64(self, addr, data, zone=None): """Writes long words to memory of a target system. Note: This is little-endian. Args: self (JLink): the ``JLink`` instance addr (int): start address to write to data (list): list of long words to write zone (str): optional memory zone to access Returns: Number of long words written to target. Raises: JLinkException: on memory access error. """ words = [] bitmask = 0xFFFFFFFF for long_word in data: words.append(long_word & bitmask) # Last 32-bits words.append((long_word >> 32) & bitmask) # First 32-bits return self.memory_write32(addr, words, zone=zone)
Retrieves the values from the registers specified. Args: self (JLink): the ``JLink`` instance register_indices (list): list of registers to read Returns: A list of values corresponding one-to-one for each of the given register indices. The returned list of values are the values in order of which the indices were specified. Raises: JLinkException: if a given register is invalid or an error occurs.
def register_read_multiple(self, register_indices): """Retrieves the values from the registers specified. Args: self (JLink): the ``JLink`` instance register_indices (list): list of registers to read Returns: A list of values corresponding one-to-one for each of the given register indices. The returned list of values are the values in order of which the indices were specified. Raises: JLinkException: if a given register is invalid or an error occurs. """ num_regs = len(register_indices) buf = (ctypes.c_uint32 * num_regs)(*register_indices) data = (ctypes.c_uint32 * num_regs)(0) # TODO: For some reason, these statuses are wonky, not sure why, might # be bad documentation, but they cannot be trusted at all. statuses = (ctypes.c_uint8 * num_regs)(0) res = self._dll.JLINKARM_ReadRegs(buf, data, statuses, num_regs) if res < 0: raise errors.JLinkException(res) return list(data)
Writes into an ARM register. Note: The data is not immediately written, but is cached before being transferred to the CPU on CPU start. Args: self (JLink): the ``JLink`` instance reg_index (int): the ARM register to write to value (int): the value to write to the register Returns: The value written to the ARM register. Raises: JLinkException: on write error.
def register_write(self, reg_index, value): """Writes into an ARM register. Note: The data is not immediately written, but is cached before being transferred to the CPU on CPU start. Args: self (JLink): the ``JLink`` instance reg_index (int): the ARM register to write to value (int): the value to write to the register Returns: The value written to the ARM register. Raises: JLinkException: on write error. """ res = self._dll.JLINKARM_WriteReg(reg_index, value) if res != 0: raise errors.JLinkException('Error writing to register %d' % reg_index) return value
Writes to multiple CPU registers. Writes the values to the given registers in order. There must be a one-to-one correspondence between the values and the registers specified. Args: self (JLink): the ``JLink`` instance register_indices (list): list of registers to write to values (list): list of values to write to the registers Returns: ``None`` Raises: ValueError: if ``len(register_indices) != len(values)`` JLinkException: if a register could not be written to or on error
def register_write_multiple(self, register_indices, values): """Writes to multiple CPU registers. Writes the values to the given registers in order. There must be a one-to-one correspondence between the values and the registers specified. Args: self (JLink): the ``JLink`` instance register_indices (list): list of registers to write to values (list): list of values to write to the registers Returns: ``None`` Raises: ValueError: if ``len(register_indices) != len(values)`` JLinkException: if a register could not be written to or on error """ if len(register_indices) != len(values): raise ValueError('Must be an equal number of registers and values') num_regs = len(register_indices) buf = (ctypes.c_uint32 * num_regs)(*register_indices) data = (ctypes.c_uint32 * num_regs)(*values) # TODO: For some reason, these statuses are wonky, not sure why, might # be bad documentation, but they cannot be trusted at all. statuses = (ctypes.c_uint8 * num_regs)(0) res = self._dll.JLINKARM_WriteRegs(buf, data, statuses, num_regs) if res != 0: raise errors.JLinkException(res) return None
Writes a value to an ARM ICE register. Args: self (JLink): the ``JLink`` instance register_index (int): the ICE register to write to value (int): the value to write to the ICE register delay (bool): boolean specifying if the write should be delayed Returns: ``None``
def ice_register_write(self, register_index, value, delay=False): """Writes a value to an ARM ICE register. Args: self (JLink): the ``JLink`` instance register_index (int): the ICE register to write to value (int): the value to write to the ICE register delay (bool): boolean specifying if the write should be delayed Returns: ``None`` """ self._dll.JLINKARM_WriteICEReg(register_index, int(value), int(delay)) return None
Returns if the CPU core supports ETM. Args: self (JLink): the ``JLink`` instance. Returns: ``True`` if the CPU has the ETM unit, otherwise ``False``.
def etm_supported(self): """Returns if the CPU core supports ETM. Args: self (JLink): the ``JLink`` instance. Returns: ``True`` if the CPU has the ETM unit, otherwise ``False``. """ res = self._dll.JLINKARM_ETM_IsPresent() if (res == 1): return True # JLINKARM_ETM_IsPresent() only works on ARM 7/9 devices. This # fallback checks if ETM is present by checking the Cortex ROM table # for debugging information for ETM. info = ctypes.c_uint32(0) index = enums.JLinkROMTable.ETM res = self._dll.JLINKARM_GetDebugInfo(index, ctypes.byref(info)) if (res == 1): return False return True
Writes a value to an ETM register. Args: self (JLink): the ``JLink`` instance. register_index (int): the register to write to. value (int): the value to write to the register. delay (bool): boolean specifying if the write should be buffered. Returns: ``None``
def etm_register_write(self, register_index, value, delay=False): """Writes a value to an ETM register. Args: self (JLink): the ``JLink`` instance. register_index (int): the register to write to. value (int): the value to write to the register. delay (bool): boolean specifying if the write should be buffered. Returns: ``None`` """ self._dll.JLINKARM_ETM_WriteReg(int(register_index), int(value), int(delay)) return None
Reads an Ap/DP register on a CoreSight DAP. Wait responses and special handling are both handled by this method. Note: ``coresight_configure()`` must be called prior to calling this method. Args: self (JLink): the ``JLink`` instance reg (int): index of DP/AP register to read ap (bool): ``True`` if reading from an Access Port register, otherwise ``False`` for Debug Port Returns: Data read from register. Raises: JLinkException: on hardware error
def coresight_read(self, reg, ap=True): """Reads an Ap/DP register on a CoreSight DAP. Wait responses and special handling are both handled by this method. Note: ``coresight_configure()`` must be called prior to calling this method. Args: self (JLink): the ``JLink`` instance reg (int): index of DP/AP register to read ap (bool): ``True`` if reading from an Access Port register, otherwise ``False`` for Debug Port Returns: Data read from register. Raises: JLinkException: on hardware error """ data = ctypes.c_uint32() ap = 1 if ap else 0 res = self._dll.JLINKARM_CORESIGHT_ReadAPDPReg(reg, ap, ctypes.byref(data)) if res < 0: raise errors.JLinkException(res) return data.value
Writes an Ap/DP register on a CoreSight DAP. Note: ``coresight_configure()`` must be called prior to calling this method. Args: self (JLink): the ``JLink`` instance reg (int): index of DP/AP register to write data (int): data to write ap (bool): ``True`` if writing to an Access Port register, otherwise ``False`` for Debug Port Returns: Number of repetitions needed until write request accepted. Raises: JLinkException: on hardware error
def coresight_write(self, reg, data, ap=True): """Writes an Ap/DP register on a CoreSight DAP. Note: ``coresight_configure()`` must be called prior to calling this method. Args: self (JLink): the ``JLink`` instance reg (int): index of DP/AP register to write data (int): data to write ap (bool): ``True`` if writing to an Access Port register, otherwise ``False`` for Debug Port Returns: Number of repetitions needed until write request accepted. Raises: JLinkException: on hardware error """ ap = 1 if ap else 0 res = self._dll.JLINKARM_CORESIGHT_WriteAPDPReg(reg, ap, data) if res < 0: raise errors.JLinkException(res) return res
Sets vector catch bits of the processor. The CPU will jump to a vector if the given vector catch is active, and will enter a debug state. This has the effect of halting the CPU as well, meaning the CPU must be explicitly restarted. Args: self (JLink): the ``JLink`` instance Returns: ``None`` Raises: JLinkException: on error.
def set_vector_catch(self, flags): """Sets vector catch bits of the processor. The CPU will jump to a vector if the given vector catch is active, and will enter a debug state. This has the effect of halting the CPU as well, meaning the CPU must be explicitly restarted. Args: self (JLink): the ``JLink`` instance Returns: ``None`` Raises: JLinkException: on error. """ res = self._dll.JLINKARM_WriteVectorCatch(flags) if res < 0: raise errors.JLinkException(res) return None
Executes a single step. Steps even if there is a breakpoint. Args: self (JLink): the ``JLink`` instance thumb (bool): boolean indicating if to step in thumb mode Returns: ``None`` Raises: JLinkException: on error
def step(self, thumb=False): """Executes a single step. Steps even if there is a breakpoint. Args: self (JLink): the ``JLink`` instance thumb (bool): boolean indicating if to step in thumb mode Returns: ``None`` Raises: JLinkException: on error """ method = self._dll.JLINKARM_Step if thumb: method = self._dll.JLINKARM_StepComposite res = method() if res != 0: raise errors.JLinkException("Failed to step over instruction.") return None
Returns the information about a set breakpoint. Note: Either ``handle`` or ``index`` can be specified. If the ``index`` is not provided, the ``handle`` must be set, and vice-versa. If both ``index`` and ``handle`` are provided, the ``index`` overrides the provided ``handle``. Args: self (JLink): the ``JLink`` instance handle (int): option handle of a valid breakpoint index (int): optional index of the breakpoint. Returns: An instance of ``JLinkBreakpointInfo`` specifying information about the breakpoint. Raises: JLinkException: on error. ValueError: if both the handle and index are invalid.
def breakpoint_info(self, handle=0, index=-1): """Returns the information about a set breakpoint. Note: Either ``handle`` or ``index`` can be specified. If the ``index`` is not provided, the ``handle`` must be set, and vice-versa. If both ``index`` and ``handle`` are provided, the ``index`` overrides the provided ``handle``. Args: self (JLink): the ``JLink`` instance handle (int): option handle of a valid breakpoint index (int): optional index of the breakpoint. Returns: An instance of ``JLinkBreakpointInfo`` specifying information about the breakpoint. Raises: JLinkException: on error. ValueError: if both the handle and index are invalid. """ if index < 0 and handle == 0: raise ValueError('Handle must be provided if index is not set.') bp = structs.JLinkBreakpointInfo() bp.Handle = int(handle) res = self._dll.JLINKARM_GetBPInfoEx(index, ctypes.byref(bp)) if res < 0: raise errors.JLinkException('Failed to get breakpoint info.') return bp
Sets a breakpoint at the specified address. If ``thumb`` is ``True``, the breakpoint is set in THUMB-mode, while if ``arm`` is ``True``, the breakpoint is set in ARM-mode, otherwise a normal breakpoint is set. Args: self (JLink): the ``JLink`` instance addr (int): the address where the breakpoint will be set thumb (bool): boolean indicating to set the breakpoint in THUMB mode arm (bool): boolean indicating to set the breakpoint in ARM mode Returns: An integer specifying the breakpoint handle. This handle should be retained for future breakpoint operations. Raises: TypeError: if the given address is not an integer. JLinkException: if the breakpoint could not be set.
def breakpoint_set(self, addr, thumb=False, arm=False): """Sets a breakpoint at the specified address. If ``thumb`` is ``True``, the breakpoint is set in THUMB-mode, while if ``arm`` is ``True``, the breakpoint is set in ARM-mode, otherwise a normal breakpoint is set. Args: self (JLink): the ``JLink`` instance addr (int): the address where the breakpoint will be set thumb (bool): boolean indicating to set the breakpoint in THUMB mode arm (bool): boolean indicating to set the breakpoint in ARM mode Returns: An integer specifying the breakpoint handle. This handle should be retained for future breakpoint operations. Raises: TypeError: if the given address is not an integer. JLinkException: if the breakpoint could not be set. """ flags = enums.JLinkBreakpoint.ANY if thumb: flags = flags | enums.JLinkBreakpoint.THUMB elif arm: flags = flags | enums.JLinkBreakpoint.ARM handle = self._dll.JLINKARM_SetBPEx(int(addr), flags) if handle <= 0: raise errors.JLinkException('Breakpoint could not be set.') return handle
Sets a software breakpoint at the specified address. If ``thumb`` is ``True``, the breakpoint is set in THUMB-mode, while if ``arm`` is ``True``, the breakpoint is set in ARM-mode, otherwise a normal breakpoint is set. If ``flash`` is ``True``, the breakpoint is set in flash, otherwise if ``ram`` is ``True``, the breakpoint is set in RAM. If both are ``True`` or both are ``False``, then the best option is chosen for setting the breakpoint in software. Args: self (JLink): the ``JLink`` instance addr (int): the address where the breakpoint will be set thumb (bool): boolean indicating to set the breakpoint in THUMB mode arm (bool): boolean indicating to set the breakpoint in ARM mode flash (bool): boolean indicating to set the breakpoint in flash ram (bool): boolean indicating to set the breakpoint in RAM Returns: An integer specifying the breakpoint handle. This handle should sbe retained for future breakpoint operations. Raises: TypeError: if the given address is not an integer. JLinkException: if the breakpoint could not be set.
def software_breakpoint_set(self, addr, thumb=False, arm=False, flash=False, ram=False): """Sets a software breakpoint at the specified address. If ``thumb`` is ``True``, the breakpoint is set in THUMB-mode, while if ``arm`` is ``True``, the breakpoint is set in ARM-mode, otherwise a normal breakpoint is set. If ``flash`` is ``True``, the breakpoint is set in flash, otherwise if ``ram`` is ``True``, the breakpoint is set in RAM. If both are ``True`` or both are ``False``, then the best option is chosen for setting the breakpoint in software. Args: self (JLink): the ``JLink`` instance addr (int): the address where the breakpoint will be set thumb (bool): boolean indicating to set the breakpoint in THUMB mode arm (bool): boolean indicating to set the breakpoint in ARM mode flash (bool): boolean indicating to set the breakpoint in flash ram (bool): boolean indicating to set the breakpoint in RAM Returns: An integer specifying the breakpoint handle. This handle should sbe retained for future breakpoint operations. Raises: TypeError: if the given address is not an integer. JLinkException: if the breakpoint could not be set. """ if flash and not ram: flags = enums.JLinkBreakpoint.SW_FLASH elif not flash and ram: flags = enums.JLinkBreakpoint.SW_RAM else: flags = enums.JLinkBreakpoint.SW if thumb: flags = flags | enums.JLinkBreakpoint.THUMB elif arm: flags = flags | enums.JLinkBreakpoint.ARM handle = self._dll.JLINKARM_SetBPEx(int(addr), flags) if handle <= 0: raise errors.JLinkException('Software breakpoint could not be set.') return handle
Returns information about the specified watchpoint. Note: Either ``handle`` or ``index`` can be specified. If the ``index`` is not provided, the ``handle`` must be set, and vice-versa. If both ``index`` and ``handle`` are provided, the ``index`` overrides the provided ``handle``. Args: self (JLink): the ``JLink`` instance handle (int): optional handle of a valid watchpoint. index (int): optional index of a watchpoint. Returns: An instance of ``JLinkWatchpointInfo`` specifying information about the watchpoint if the watchpoint was found, otherwise ``None``. Raises: JLinkException: on error. ValueError: if both handle and index are invalid.
def watchpoint_info(self, handle=0, index=-1): """Returns information about the specified watchpoint. Note: Either ``handle`` or ``index`` can be specified. If the ``index`` is not provided, the ``handle`` must be set, and vice-versa. If both ``index`` and ``handle`` are provided, the ``index`` overrides the provided ``handle``. Args: self (JLink): the ``JLink`` instance handle (int): optional handle of a valid watchpoint. index (int): optional index of a watchpoint. Returns: An instance of ``JLinkWatchpointInfo`` specifying information about the watchpoint if the watchpoint was found, otherwise ``None``. Raises: JLinkException: on error. ValueError: if both handle and index are invalid. """ if index < 0 and handle == 0: raise ValueError('Handle must be provided if index is not set.') wp = structs.JLinkWatchpointInfo() res = self._dll.JLINKARM_GetWPInfoEx(index, ctypes.byref(wp)) if res < 0: raise errors.JLinkException('Failed to get watchpoint info.') for i in range(res): res = self._dll.JLINKARM_GetWPInfoEx(i, ctypes.byref(wp)) if res < 0: raise errors.JLinkException('Failed to get watchpoint info.') elif wp.Handle == handle or wp.WPUnit == index: return wp return None
Sets a watchpoint at the given address. This method allows for a watchpoint to be set on an given address or range of addresses. The watchpoint can then be triggered if the data at the given address matches the specified ``data`` or range of data as determined by ``data_mask``, on specific access size events, reads, writes, or privileged accesses. Both ``addr_mask`` and ``data_mask`` are used to specify ranges. Bits set to ``1`` are masked out and not taken into consideration when comparison against an address or data value. E.g. an ``addr_mask`` with a value of ``0x1`` and ``addr`` with value ``0xdeadbeef`` means that the watchpoint will be set on addresses ``0xdeadbeef`` and ``0xdeadbeee``. If the ``data`` was ``0x11223340`` and the given ``data_mask`` has a value of ``0x0000000F``, then the watchpoint would trigger for data matching ``0x11223340 - 0x1122334F``. Note: If both ``read`` and ``write`` are specified, then the watchpoint will trigger on both read and write events to the given address. Args: self (JLink): the ``JLink`` instance addr_mask (int): optional mask to use for determining which address the watchpoint should be set on data (int): optional data to set the watchpoint on in order to have the watchpoint triggered when the value at the specified address matches the given ``data`` data_mask (int): optional mask to use for determining the range of data on which the watchpoint should be triggered access_size (int): if specified, this must be one of ``{8, 16, 32}`` and determines the access size for which the watchpoint should trigger read (bool): if ``True``, triggers the watchpoint on read events write (bool): if ``True``, triggers the watchpoint on write events privileged (bool): if ``True``, triggers the watchpoint on privileged accesses Returns: The handle of the created watchpoint. Raises: ValueError: if an invalid access size is given. JLinkException: if the watchpoint fails to be set.
def watchpoint_set(self, addr, addr_mask=0x0, data=0x0, data_mask=0x0, access_size=None, read=False, write=False, privileged=False): """Sets a watchpoint at the given address. This method allows for a watchpoint to be set on an given address or range of addresses. The watchpoint can then be triggered if the data at the given address matches the specified ``data`` or range of data as determined by ``data_mask``, on specific access size events, reads, writes, or privileged accesses. Both ``addr_mask`` and ``data_mask`` are used to specify ranges. Bits set to ``1`` are masked out and not taken into consideration when comparison against an address or data value. E.g. an ``addr_mask`` with a value of ``0x1`` and ``addr`` with value ``0xdeadbeef`` means that the watchpoint will be set on addresses ``0xdeadbeef`` and ``0xdeadbeee``. If the ``data`` was ``0x11223340`` and the given ``data_mask`` has a value of ``0x0000000F``, then the watchpoint would trigger for data matching ``0x11223340 - 0x1122334F``. Note: If both ``read`` and ``write`` are specified, then the watchpoint will trigger on both read and write events to the given address. Args: self (JLink): the ``JLink`` instance addr_mask (int): optional mask to use for determining which address the watchpoint should be set on data (int): optional data to set the watchpoint on in order to have the watchpoint triggered when the value at the specified address matches the given ``data`` data_mask (int): optional mask to use for determining the range of data on which the watchpoint should be triggered access_size (int): if specified, this must be one of ``{8, 16, 32}`` and determines the access size for which the watchpoint should trigger read (bool): if ``True``, triggers the watchpoint on read events write (bool): if ``True``, triggers the watchpoint on write events privileged (bool): if ``True``, triggers the watchpoint on privileged accesses Returns: The handle of the created watchpoint. Raises: ValueError: if an invalid access size is given. JLinkException: if the watchpoint fails to be set. """ access_flags = 0x0 access_mask_flags = 0x0 # If an access size is not specified, we must specify that the size of # the access does not matter by specifying the access mask flags. if access_size is None: access_mask_flags = access_mask_flags | enums.JLinkAccessMaskFlags.SIZE elif access_size == 8: access_flags = access_flags | enums.JLinkAccessFlags.SIZE_8BIT elif access_size == 16: access_flags = access_flags | enums.JLinkAccessFlags.SIZE_16BIT elif access_size == 32: access_flags = access_flags | enums.JLinkAccessFlags.SIZE_32BIT else: raise ValueError('Invalid access size given: %d' % access_size) # The read and write access flags cannot be specified together, so if # the user specifies that they want read and write access, then the # access mask flag must be set. if read and write: access_mask_flags = access_mask_flags | enums.JLinkAccessMaskFlags.DIR elif read: access_flags = access_flags | enums.JLinkAccessFlags.READ elif write: access_flags = access_flags | enums.JLinkAccessFlags.WRITE # If privileged is not specified, then there is no specification level # on which kinds of writes should be accessed, in which case we must # specify that flag. if privileged: access_flags = access_flags | enums.JLinkAccessFlags.PRIV else: access_mask_flags = access_mask_flags | enums.JLinkAccessMaskFlags.PRIV # Populate the Data event to configure how the watchpoint is triggered. wp = structs.JLinkDataEvent() wp.Addr = addr wp.AddrMask = addr_mask wp.Data = data wp.DataMask = data_mask wp.Access = access_flags wp.AccessMask = access_mask_flags # Return value of the function is <= 0 in the event of an error, # otherwise the watchpoint was set successfully. handle = ctypes.c_uint32() res = self._dll.JLINKARM_SetDataEvent(ctypes.pointer(wp), ctypes.pointer(handle)) if res < 0: raise errors.JLinkDataException(res) return handle.value
Disassembles and returns the assembly instruction string. Args: self (JLink): the ``JLink`` instance. instruction (int): the instruction address. Returns: A string corresponding to the assembly instruction string at the given instruction address. Raises: JLinkException: on error. TypeError: if ``instruction`` is not a number.
def disassemble_instruction(self, instruction): """Disassembles and returns the assembly instruction string. Args: self (JLink): the ``JLink`` instance. instruction (int): the instruction address. Returns: A string corresponding to the assembly instruction string at the given instruction address. Raises: JLinkException: on error. TypeError: if ``instruction`` is not a number. """ if not util.is_integer(instruction): raise TypeError('Expected instruction to be an integer.') buf_size = self.MAX_BUF_SIZE buf = (ctypes.c_char * buf_size)() res = self._dll.JLINKARM_DisassembleInst(ctypes.byref(buf), buf_size, instruction) if res < 0: raise errors.JLinkException('Failed to disassemble instruction.') return ctypes.string_at(buf).decode()
Configures the trace port width for tracing. Note that configuration cannot occur while STRACE is running. Args: self (JLink): the ``JLink`` instance port_width (int): the trace port width to use. Returns: ``None`` Raises: ValueError: if ``port_width`` is not ``1``, ``2``, or ``4``. JLinkException: on error.
def strace_configure(self, port_width): """Configures the trace port width for tracing. Note that configuration cannot occur while STRACE is running. Args: self (JLink): the ``JLink`` instance port_width (int): the trace port width to use. Returns: ``None`` Raises: ValueError: if ``port_width`` is not ``1``, ``2``, or ``4``. JLinkException: on error. """ if port_width not in [1, 2, 4]: raise ValueError('Invalid port width: %s' % str(port_width)) config_string = 'PortWidth=%d' % port_width res = self._dll.JLINK_STRACE_Config(config_string.encode()) if res < 0: raise errors.JLinkException('Failed to configure STRACE port') return None
Reads and returns a number of instructions captured by STRACE. The number of instructions must be a non-negative value of at most ``0x10000`` (``65536``). Args: self (JLink): the ``JLink`` instance. num_instructions (int): number of instructions to fetch. Returns: A list of instruction addresses in order from most recently executed to oldest executed instructions. Note that the number of instructions returned can be less than the number of instructions requested in the case that there are not ``num_instructions`` in the trace buffer. Raises: JLinkException: on error. ValueError: if ``num_instructions < 0`` or ``num_instructions > 0x10000``.
def strace_read(self, num_instructions): """Reads and returns a number of instructions captured by STRACE. The number of instructions must be a non-negative value of at most ``0x10000`` (``65536``). Args: self (JLink): the ``JLink`` instance. num_instructions (int): number of instructions to fetch. Returns: A list of instruction addresses in order from most recently executed to oldest executed instructions. Note that the number of instructions returned can be less than the number of instructions requested in the case that there are not ``num_instructions`` in the trace buffer. Raises: JLinkException: on error. ValueError: if ``num_instructions < 0`` or ``num_instructions > 0x10000``. """ if num_instructions < 0 or num_instructions > 0x10000: raise ValueError('Invalid instruction count.') buf = (ctypes.c_uint32 * num_instructions)() buf_size = num_instructions res = self._dll.JLINK_STRACE_Read(ctypes.byref(buf), buf_size) if res < 0: raise errors.JLinkException('Failed to read from STRACE buffer.') return list(buf)[:res]
Sets an event to trigger trace logic when data access is made. Data access corresponds to either a read or write. Args: self (JLink): the ``JLink`` instance. operation (int): one of the operations in ``JLinkStraceOperation``. address (int): the address of the load/store data. data (int): the data to be compared the event data to. data_mask (int): optional bitmask specifying bits to ignore in comparison. acess_width (int): optional access width for the data. address_range (int): optional range of address to trigger event on. Returns: An integer specifying the trace event handle. This handle should be retained in order to clear the event at a later time. Raises: JLinkException: on error.
def strace_data_access_event(self, operation, address, data, data_mask=None, access_width=4, address_range=0): """Sets an event to trigger trace logic when data access is made. Data access corresponds to either a read or write. Args: self (JLink): the ``JLink`` instance. operation (int): one of the operations in ``JLinkStraceOperation``. address (int): the address of the load/store data. data (int): the data to be compared the event data to. data_mask (int): optional bitmask specifying bits to ignore in comparison. acess_width (int): optional access width for the data. address_range (int): optional range of address to trigger event on. Returns: An integer specifying the trace event handle. This handle should be retained in order to clear the event at a later time. Raises: JLinkException: on error. """ cmd = enums.JLinkStraceCommand.TRACE_EVENT_SET event_info = structs.JLinkStraceEventInfo() event_info.Type = enums.JLinkStraceEvent.DATA_ACCESS event_info.Op = operation event_info.AccessSize = int(access_width) event_info.Addr = int(address) event_info.Data = int(data) event_info.DataMask = int(data_mask or 0) event_info.AddrRangeSize = int(address_range) handle = self._dll.JLINK_STRACE_Control(cmd, ctypes.byref(event_info)) if handle < 0: raise errors.JLinkException(handle) return handle
Sets an event to trigger trace logic when data write access is made. Args: self (JLink): the ``JLink`` instance. operation (int): one of the operations in ``JLinkStraceOperation``. address (int): the address of the store data. address_range (int): optional range of address to trigger event on. Returns: An integer specifying the trace event handle. This handle should be retained in order to clear the event at a later time. Raises: JLinkException: on error.
def strace_data_store_event(self, operation, address, address_range=0): """Sets an event to trigger trace logic when data write access is made. Args: self (JLink): the ``JLink`` instance. operation (int): one of the operations in ``JLinkStraceOperation``. address (int): the address of the store data. address_range (int): optional range of address to trigger event on. Returns: An integer specifying the trace event handle. This handle should be retained in order to clear the event at a later time. Raises: JLinkException: on error. """ cmd = enums.JLinkStraceCommand.TRACE_EVENT_SET event_info = structs.JLinkStraceEventInfo() event_info.Type = enums.JLinkStraceEvent.DATA_STORE event_info.Op = operation event_info.Addr = int(address) event_info.AddrRangeSize = int(address_range) handle = self._dll.JLINK_STRACE_Control(cmd, ctypes.byref(event_info)) if handle < 0: raise errors.JLinkException(handle) return handle
Clears the trace event specified by the given handle. Args: self (JLink): the ``JLink`` instance. handle (int): handle of the trace event. Returns: ``None`` Raises: JLinkException: on error.
def strace_clear(self, handle): """Clears the trace event specified by the given handle. Args: self (JLink): the ``JLink`` instance. handle (int): handle of the trace event. Returns: ``None`` Raises: JLinkException: on error. """ data = ctypes.c_int(handle) res = self._dll.JLINK_STRACE_Control(enums.JLinkStraceCommand.TRACE_EVENT_CLR, ctypes.byref(data)) if res < 0: raise errors.JLinkException('Failed to clear STRACE event.') return None
Clears all STRACE events. Args: self (JLink): the ``JLink`` instance. Returns: ``None`` Raises: JLinkException: on error.
def strace_clear_all(self): """Clears all STRACE events. Args: self (JLink): the ``JLink`` instance. Returns: ``None`` Raises: JLinkException: on error. """ data = 0 res = self._dll.JLINK_STRACE_Control(enums.JLinkStraceCommand.TRACE_EVENT_CLR_ALL, data) if res < 0: raise errors.JLinkException('Failed to clear all STRACE events.') return None
Sets the STRACE buffer size. Args: self (JLink): the ``JLink`` instance. Returns: ``None`` Raises: JLinkException: on error.
def strace_set_buffer_size(self, size): """Sets the STRACE buffer size. Args: self (JLink): the ``JLink`` instance. Returns: ``None`` Raises: JLinkException: on error. """ size = ctypes.c_uint32(size) res = self._dll.JLINK_STRACE_Control(enums.JLinkStraceCommand.SET_BUFFER_SIZE, size) if res < 0: raise errors.JLinkException('Failed to set the STRACE buffer size.') return None
Starts collecting trace data. Args: self (JLink): the ``JLink`` instance. Returns: ``None``
def trace_start(self): """Starts collecting trace data. Args: self (JLink): the ``JLink`` instance. Returns: ``None`` """ cmd = enums.JLinkTraceCommand.START res = self._dll.JLINKARM_TRACE_Control(cmd, 0) if (res == 1): raise errors.JLinkException('Failed to start trace.') return None
Stops collecting trace data. Args: self (JLink): the ``JLink`` instance. Returns: ``None``
def trace_stop(self): """Stops collecting trace data. Args: self (JLink): the ``JLink`` instance. Returns: ``None`` """ cmd = enums.JLinkTraceCommand.STOP res = self._dll.JLINKARM_TRACE_Control(cmd, 0) if (res == 1): raise errors.JLinkException('Failed to stop trace.') return None
Flushes the trace buffer. After this method is called, the trace buffer is empty. This method is best called when the device is reset. Args: self (JLink): the ``JLink`` instance. Returns: ``None``
def trace_flush(self): """Flushes the trace buffer. After this method is called, the trace buffer is empty. This method is best called when the device is reset. Args: self (JLink): the ``JLink`` instance. Returns: ``None`` """ cmd = enums.JLinkTraceCommand.FLUSH res = self._dll.JLINKARM_TRACE_Control(cmd, 0) if (res == 1): raise errors.JLinkException('Failed to flush the trace buffer.') return None
Retrieves the trace buffer's current capacity. Args: self (JLink): the ``JLink`` instance. Returns: The current capacity of the trace buffer. This is not necessarily the maximum possible size the buffer could be configured with.
def trace_buffer_capacity(self): """Retrieves the trace buffer's current capacity. Args: self (JLink): the ``JLink`` instance. Returns: The current capacity of the trace buffer. This is not necessarily the maximum possible size the buffer could be configured with. """ cmd = enums.JLinkTraceCommand.GET_CONF_CAPACITY data = ctypes.c_uint32(0) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data)) if (res == 1): raise errors.JLinkException('Failed to get trace buffer size.') return data.value
Sets the capacity for the trace buffer. Args: self (JLink): the ``JLink`` instance. size (int): the new capacity for the trace buffer. Returns: ``None``
def trace_set_buffer_capacity(self, size): """Sets the capacity for the trace buffer. Args: self (JLink): the ``JLink`` instance. size (int): the new capacity for the trace buffer. Returns: ``None`` """ cmd = enums.JLinkTraceCommand.SET_CAPACITY data = ctypes.c_uint32(size) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data)) if (res == 1): raise errors.JLinkException('Failed to set trace buffer size.') return None
Retrieves the minimum capacity the trace buffer can be configured with. Args: self (JLink): the ``JLink`` instance. Returns: The minimum configurable capacity for the trace buffer.
def trace_min_buffer_capacity(self): """Retrieves the minimum capacity the trace buffer can be configured with. Args: self (JLink): the ``JLink`` instance. Returns: The minimum configurable capacity for the trace buffer. """ cmd = enums.JLinkTraceCommand.GET_MIN_CAPACITY data = ctypes.c_uint32(0) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data)) if (res == 1): raise errors.JLinkException('Failed to get min trace buffer size.') return data.value
Retrieves the maximum size the trace buffer can be configured with. Args: self (JLink): the ``JLink`` instance. Returns: The maximum configurable capacity for the trace buffer.
def trace_max_buffer_capacity(self): """Retrieves the maximum size the trace buffer can be configured with. Args: self (JLink): the ``JLink`` instance. Returns: The maximum configurable capacity for the trace buffer. """ cmd = enums.JLinkTraceCommand.GET_MAX_CAPACITY data = ctypes.c_uint32(0) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data)) if (res == 1): raise errors.JLinkException('Failed to get max trace buffer size.') return data.value
Sets the format for the trace buffer to use. Args: self (JLink): the ``JLink`` instance. fmt (int): format for the trace buffer; this is one of the attributes of ``JLinkTraceFormat``. Returns: ``None``
def trace_set_format(self, fmt): """Sets the format for the trace buffer to use. Args: self (JLink): the ``JLink`` instance. fmt (int): format for the trace buffer; this is one of the attributes of ``JLinkTraceFormat``. Returns: ``None`` """ cmd = enums.JLinkTraceCommand.SET_FORMAT data = ctypes.c_uint32(fmt) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data)) if (res == 1): raise errors.JLinkException('Failed to set trace format.') return None
Retrieves the current format the trace buffer is using. Args: self (JLink): the ``JLink`` instance. Returns: The current format the trace buffer is using. This is one of the attributes of ``JLinkTraceFormat``.
def trace_format(self): """Retrieves the current format the trace buffer is using. Args: self (JLink): the ``JLink`` instance. Returns: The current format the trace buffer is using. This is one of the attributes of ``JLinkTraceFormat``. """ cmd = enums.JLinkTraceCommand.GET_FORMAT data = ctypes.c_uint32(0) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data)) if (res == 1): raise errors.JLinkException('Failed to get trace format.') return data.value
Retrieves a count of the number of available trace regions. Args: self (JLink): the ``JLink`` instance. Returns: Count of the number of available trace regions.
def trace_region_count(self): """Retrieves a count of the number of available trace regions. Args: self (JLink): the ``JLink`` instance. Returns: Count of the number of available trace regions. """ cmd = enums.JLinkTraceCommand.GET_NUM_REGIONS data = ctypes.c_uint32(0) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data)) if (res == 1): raise errors.JLinkException('Failed to get trace region count.') return data.value
Retrieves the properties of a trace region. Args: self (JLink): the ``JLink`` instance. region_index (int): the trace region index. Returns: An instance of ``JLinkTraceRegion`` describing the specified region.
def trace_region(self, region_index): """Retrieves the properties of a trace region. Args: self (JLink): the ``JLink`` instance. region_index (int): the trace region index. Returns: An instance of ``JLinkTraceRegion`` describing the specified region. """ cmd = enums.JLinkTraceCommand.GET_REGION_PROPS_EX region = structs.JLinkTraceRegion() region.RegionIndex = int(region_index) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(region)) if (res == 1): raise errors.JLinkException('Failed to get trace region.') return region
Reads data from the trace buffer and returns it. Args: self (JLink): the ``JLink`` instance. offset (int): the offset from which to start reading from the trace buffer. num_items (int): number of items to read from the trace buffer. Returns: A list of ``JLinkTraceData`` instances corresponding to the items read from the trace buffer. Note that this list may have size less than ``num_items`` in the event that there are not ``num_items`` items in the trace buffer. Raises: JLinkException: on error.
def trace_read(self, offset, num_items): """Reads data from the trace buffer and returns it. Args: self (JLink): the ``JLink`` instance. offset (int): the offset from which to start reading from the trace buffer. num_items (int): number of items to read from the trace buffer. Returns: A list of ``JLinkTraceData`` instances corresponding to the items read from the trace buffer. Note that this list may have size less than ``num_items`` in the event that there are not ``num_items`` items in the trace buffer. Raises: JLinkException: on error. """ buf_size = ctypes.c_uint32(num_items) buf = (structs.JLinkTraceData * num_items)() res = self._dll.JLINKARM_TRACE_Read(buf, int(offset), ctypes.byref(buf_size)) if (res == 1): raise errors.JLinkException('Failed to read from trace buffer.') return list(buf)[:int(buf_size.value)]
Starts collecting SWO data. Note: If SWO is already enabled, it will first stop SWO before enabling it again. Args: self (JLink): the ``JLink`` instance swo_speed (int): the frequency in Hz used by the target to communicate Returns: ``None`` Raises: JLinkException: on error
def swo_start(self, swo_speed=9600): """Starts collecting SWO data. Note: If SWO is already enabled, it will first stop SWO before enabling it again. Args: self (JLink): the ``JLink`` instance swo_speed (int): the frequency in Hz used by the target to communicate Returns: ``None`` Raises: JLinkException: on error """ if self.swo_enabled(): self.swo_stop() info = structs.JLinkSWOStartInfo() info.Speed = swo_speed res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.START, ctypes.byref(info)) if res < 0: raise errors.JLinkException(res) self._swo_enabled = True return None
Stops collecting SWO data. Args: self (JLink): the ``JLink`` instance Returns: ``None`` Raises: JLinkException: on error
def swo_stop(self): """Stops collecting SWO data. Args: self (JLink): the ``JLink`` instance Returns: ``None`` Raises: JLinkException: on error """ res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.STOP, 0) if res < 0: raise errors.JLinkException(res) return None
Enables SWO output on the target device. Configures the output protocol, the SWO output speed, and enables any ITM & stimulus ports. This is equivalent to calling ``.swo_start()``. Note: If SWO is already enabled, it will first stop SWO before enabling it again. Args: self (JLink): the ``JLink`` instance cpu_speed (int): the target CPU frequency in Hz swo_speed (int): the frequency in Hz used by the target to communicate port_mask (int): port mask specifying which stimulus ports to enable Returns: ``None`` Raises: JLinkException: on error
def swo_enable(self, cpu_speed, swo_speed=9600, port_mask=0x01): """Enables SWO output on the target device. Configures the output protocol, the SWO output speed, and enables any ITM & stimulus ports. This is equivalent to calling ``.swo_start()``. Note: If SWO is already enabled, it will first stop SWO before enabling it again. Args: self (JLink): the ``JLink`` instance cpu_speed (int): the target CPU frequency in Hz swo_speed (int): the frequency in Hz used by the target to communicate port_mask (int): port mask specifying which stimulus ports to enable Returns: ``None`` Raises: JLinkException: on error """ if self.swo_enabled(): self.swo_stop() res = self._dll.JLINKARM_SWO_EnableTarget(cpu_speed, swo_speed, enums.JLinkSWOInterfaces.UART, port_mask) if res != 0: raise errors.JLinkException(res) self._swo_enabled = True return None
Disables ITM & Stimulus ports. Args: self (JLink): the ``JLink`` instance port_mask (int): mask specifying which ports to disable Returns: ``None`` Raises: JLinkException: on error
def swo_disable(self, port_mask): """Disables ITM & Stimulus ports. Args: self (JLink): the ``JLink`` instance port_mask (int): mask specifying which ports to disable Returns: ``None`` Raises: JLinkException: on error """ res = self._dll.JLINKARM_SWO_DisableTarget(port_mask) if res != 0: raise errors.JLinkException(res) return None
Flushes data from the SWO buffer. After this method is called, the flushed part of the SWO buffer is empty. If ``num_bytes`` is not present, flushes all data currently in the SWO buffer. Args: self (JLink): the ``JLink`` instance num_bytes (int): the number of bytes to flush Returns: ``None`` Raises: JLinkException: on error
def swo_flush(self, num_bytes=None): """Flushes data from the SWO buffer. After this method is called, the flushed part of the SWO buffer is empty. If ``num_bytes`` is not present, flushes all data currently in the SWO buffer. Args: self (JLink): the ``JLink`` instance num_bytes (int): the number of bytes to flush Returns: ``None`` Raises: JLinkException: on error """ if num_bytes is None: num_bytes = self.swo_num_bytes() buf = ctypes.c_uint32(num_bytes) res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.FLUSH, ctypes.byref(buf)) if res < 0: raise errors.JLinkException(res) return None
Retrieves information about the supported SWO speeds. Args: self (JLink): the ``JLink`` instance Returns: A ``JLinkSWOSpeedInfo`` instance describing the target's supported SWO speeds. Raises: JLinkException: on error
def swo_speed_info(self): """Retrieves information about the supported SWO speeds. Args: self (JLink): the ``JLink`` instance Returns: A ``JLinkSWOSpeedInfo`` instance describing the target's supported SWO speeds. Raises: JLinkException: on error """ info = structs.JLinkSWOSpeedInfo() res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.GET_SPEED_INFO, ctypes.byref(info)) if res < 0: raise errors.JLinkException(res) return info
Retrives the number of bytes in the SWO buffer. Args: self (JLink): the ``JLink`` instance Returns: Number of bytes in the SWO buffer. Raises: JLinkException: on error
def swo_num_bytes(self): """Retrives the number of bytes in the SWO buffer. Args: self (JLink): the ``JLink`` instance Returns: Number of bytes in the SWO buffer. Raises: JLinkException: on error """ res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.GET_NUM_BYTES, 0) if res < 0: raise errors.JLinkException(res) return res
Sets the size of the buffer used by the host to collect SWO data. Args: self (JLink): the ``JLink`` instance buf_size (int): the new size of the host buffer Returns: ``None`` Raises: JLinkException: on error
def swo_set_host_buffer_size(self, buf_size): """Sets the size of the buffer used by the host to collect SWO data. Args: self (JLink): the ``JLink`` instance buf_size (int): the new size of the host buffer Returns: ``None`` Raises: JLinkException: on error """ buf = ctypes.c_uint32(buf_size) res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.SET_BUFFERSIZE_HOST, ctypes.byref(buf)) if res < 0: raise errors.JLinkException(res) return None
Sets the size of the buffer used by the J-Link to collect SWO data. Args: self (JLink): the ``JLink`` instance buf_size (int): the new size of the emulator buffer Returns: ``None`` Raises: JLinkException: on error
def swo_set_emu_buffer_size(self, buf_size): """Sets the size of the buffer used by the J-Link to collect SWO data. Args: self (JLink): the ``JLink`` instance buf_size (int): the new size of the emulator buffer Returns: ``None`` Raises: JLinkException: on error """ buf = ctypes.c_uint32(buf_size) res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.SET_BUFFERSIZE_EMU, ctypes.byref(buf)) if res < 0: raise errors.JLinkException(res) return None
Retrives a list of SWO speeds supported by both the target and the connected J-Link. The supported speeds are returned in order from highest to lowest. Args: self (JLink): the ``JLink`` instance cpu_speed (int): the target's CPU speed in Hz num_speeds (int): the number of compatible speeds to return Returns: A list of compatible SWO speeds in Hz in order from highest to lowest.
def swo_supported_speeds(self, cpu_speed, num_speeds=3): """Retrives a list of SWO speeds supported by both the target and the connected J-Link. The supported speeds are returned in order from highest to lowest. Args: self (JLink): the ``JLink`` instance cpu_speed (int): the target's CPU speed in Hz num_speeds (int): the number of compatible speeds to return Returns: A list of compatible SWO speeds in Hz in order from highest to lowest. """ buf_size = num_speeds buf = (ctypes.c_uint32 * buf_size)() res = self._dll.JLINKARM_SWO_GetCompatibleSpeeds(cpu_speed, 0, buf, buf_size) if res < 0: raise errors.JLinkException(res) return list(buf)[:res]
Reads data from the SWO buffer. The data read is not automatically removed from the SWO buffer after reading unless ``remove`` is ``True``. Otherwise the callee must explicitly remove the data by calling ``.swo_flush()``. Args: self (JLink): the ``JLink`` instance offset (int): offset of first byte to be retrieved num_bytes (int): number of bytes to read remove (bool): if data should be removed from buffer after read Returns: A list of bytes read from the SWO buffer.
def swo_read(self, offset, num_bytes, remove=False): """Reads data from the SWO buffer. The data read is not automatically removed from the SWO buffer after reading unless ``remove`` is ``True``. Otherwise the callee must explicitly remove the data by calling ``.swo_flush()``. Args: self (JLink): the ``JLink`` instance offset (int): offset of first byte to be retrieved num_bytes (int): number of bytes to read remove (bool): if data should be removed from buffer after read Returns: A list of bytes read from the SWO buffer. """ buf_size = ctypes.c_uint32(num_bytes) buf = (ctypes.c_uint8 * num_bytes)(0) self._dll.JLINKARM_SWO_Read(buf, offset, ctypes.byref(buf_size)) # After the call, ``buf_size`` has been modified to be the actual # number of bytes that was read. buf_size = buf_size.value if remove: self.swo_flush(buf_size) return list(buf)[:buf_size]
Reads the printable data via SWO. This method reads SWO for one stimulus port, which is all printable data. Note: Stimulus port ``0`` is used for ``printf`` debugging. Args: self (JLink): the ``JLink`` instance port (int): the stimulus port to read from, ``0 - 31`` num_bytes (int): number of bytes to read Returns: A list of bytes read via SWO. Raises: ValueError: if ``port < 0`` or ``port > 31``
def swo_read_stimulus(self, port, num_bytes): """Reads the printable data via SWO. This method reads SWO for one stimulus port, which is all printable data. Note: Stimulus port ``0`` is used for ``printf`` debugging. Args: self (JLink): the ``JLink`` instance port (int): the stimulus port to read from, ``0 - 31`` num_bytes (int): number of bytes to read Returns: A list of bytes read via SWO. Raises: ValueError: if ``port < 0`` or ``port > 31`` """ if port < 0 or port > 31: raise ValueError('Invalid port number: %s' % port) buf_size = num_bytes buf = (ctypes.c_uint8 * buf_size)() bytes_read = self._dll.JLINKARM_SWO_ReadStimulus(port, buf, buf_size) return list(buf)[:bytes_read]
After starting RTT, get the current number of up buffers. Args: self (JLink): the ``JLink`` instance Returns: The number of configured up buffers on the target. Raises: JLinkRTTException if the underlying JLINK_RTTERMINAL_Control call fails.
def rtt_get_num_up_buffers(self): """After starting RTT, get the current number of up buffers. Args: self (JLink): the ``JLink`` instance Returns: The number of configured up buffers on the target. Raises: JLinkRTTException if the underlying JLINK_RTTERMINAL_Control call fails. """ cmd = enums.JLinkRTTCommand.GETNUMBUF dir = ctypes.c_int(enums.JLinkRTTDirection.UP) return self.rtt_control(cmd, dir)
After starting RTT, get the current number of down buffers. Args: self (JLink): the ``JLink`` instance Returns: The number of configured down buffers on the target. Raises: JLinkRTTException if the underlying JLINK_RTTERMINAL_Control call fails.
def rtt_get_num_down_buffers(self): """After starting RTT, get the current number of down buffers. Args: self (JLink): the ``JLink`` instance Returns: The number of configured down buffers on the target. Raises: JLinkRTTException if the underlying JLINK_RTTERMINAL_Control call fails. """ cmd = enums.JLinkRTTCommand.GETNUMBUF dir = ctypes.c_int(enums.JLinkRTTDirection.DOWN) return self.rtt_control(cmd, dir)
Reads data from the RTT buffer. This method will read at most num_bytes bytes from the specified RTT buffer. The data is automatically removed from the RTT buffer. If there are not num_bytes bytes waiting in the RTT buffer, the entire contents of the RTT buffer will be read. Args: self (JLink): the ``JLink`` instance buffer_index (int): the index of the RTT buffer to read from num_bytes (int): the maximum number of bytes to read Returns: A list of bytes read from RTT. Raises: JLinkRTTException if the underlying JLINK_RTTERMINAL_Read call fails.
def rtt_read(self, buffer_index, num_bytes): """Reads data from the RTT buffer. This method will read at most num_bytes bytes from the specified RTT buffer. The data is automatically removed from the RTT buffer. If there are not num_bytes bytes waiting in the RTT buffer, the entire contents of the RTT buffer will be read. Args: self (JLink): the ``JLink`` instance buffer_index (int): the index of the RTT buffer to read from num_bytes (int): the maximum number of bytes to read Returns: A list of bytes read from RTT. Raises: JLinkRTTException if the underlying JLINK_RTTERMINAL_Read call fails. """ buf = (ctypes.c_ubyte * num_bytes)() bytes_read = self._dll.JLINK_RTTERMINAL_Read(buffer_index, buf, num_bytes) if bytes_read < 0: raise errors.JLinkRTTException(bytes_read) return list(buf)[:bytes_read]
Writes data to the RTT buffer. This method will write at most len(data) bytes to the specified RTT buffer. Args: self (JLink): the ``JLink`` instance buffer_index (int): the index of the RTT buffer to write to data (list): the list of bytes to write to the RTT buffer Returns: The number of bytes successfully written to the RTT buffer. Raises: JLinkRTTException if the underlying JLINK_RTTERMINAL_Write call fails.
def rtt_write(self, buffer_index, data): """Writes data to the RTT buffer. This method will write at most len(data) bytes to the specified RTT buffer. Args: self (JLink): the ``JLink`` instance buffer_index (int): the index of the RTT buffer to write to data (list): the list of bytes to write to the RTT buffer Returns: The number of bytes successfully written to the RTT buffer. Raises: JLinkRTTException if the underlying JLINK_RTTERMINAL_Write call fails. """ buf_size = len(data) buf = (ctypes.c_ubyte * buf_size)(*bytearray(data)) bytes_written = self._dll.JLINK_RTTERMINAL_Write(buffer_index, buf, buf_size) if bytes_written < 0: raise errors.JLinkRTTException(bytes_written) return bytes_written
Issues an RTT Control command. All RTT control is done through a single API call which expects specifically laid-out configuration structures. Args: self (JLink): the ``JLink`` instance command (int): the command to issue (see enums.JLinkRTTCommand) config (ctypes type): the configuration to pass by reference. Returns: An integer containing the result of the command.
def rtt_control(self, command, config): """Issues an RTT Control command. All RTT control is done through a single API call which expects specifically laid-out configuration structures. Args: self (JLink): the ``JLink`` instance command (int): the command to issue (see enums.JLinkRTTCommand) config (ctypes type): the configuration to pass by reference. Returns: An integer containing the result of the command. """ config_byref = ctypes.byref(config) if config is not None else None res = self._dll.JLINK_RTTERMINAL_Control(command, config_byref) if res < 0: raise errors.JLinkRTTException(res) return res
Reads the JLink RTT buffer #0 at 10Hz and prints to stdout. This method is a polling loop against the connected JLink unit. If the JLink is disconnected, it will exit. Additionally, if any exceptions are raised, they will be caught and re-raised after interrupting the main thread. sys.stdout.write and sys.stdout.flush are used since target terminals are expected to transmit newlines, which may or may not line up with the arbitrarily-chosen 1024-byte buffer that this loop uses to read. Args: jlink (pylink.JLink): The JLink to read. Raises: Exception on error.
def read_rtt(jlink): """Reads the JLink RTT buffer #0 at 10Hz and prints to stdout. This method is a polling loop against the connected JLink unit. If the JLink is disconnected, it will exit. Additionally, if any exceptions are raised, they will be caught and re-raised after interrupting the main thread. sys.stdout.write and sys.stdout.flush are used since target terminals are expected to transmit newlines, which may or may not line up with the arbitrarily-chosen 1024-byte buffer that this loop uses to read. Args: jlink (pylink.JLink): The JLink to read. Raises: Exception on error. """ try: while jlink.connected(): terminal_bytes = jlink.rtt_read(0, 1024) if terminal_bytes: sys.stdout.write("".join(map(chr, terminal_bytes))) sys.stdout.flush() time.sleep(0.1) except Exception: print("IO read thread exception, exiting...") thread.interrupt_main() raise
Writes kayboard input to JLink RTT buffer #0. This method is a loop that blocks waiting on stdin. When enter is pressed, LF and NUL bytes are added to the input and transmitted as a byte list. If the JLink is disconnected, it will exit gracefully. If any other exceptions are raised, they will be caught and re-raised after interrupting the main thread. Args: jlink (pylink.JLink): The JLink to write to. Raises: Exception on error.
def write_rtt(jlink): """Writes kayboard input to JLink RTT buffer #0. This method is a loop that blocks waiting on stdin. When enter is pressed, LF and NUL bytes are added to the input and transmitted as a byte list. If the JLink is disconnected, it will exit gracefully. If any other exceptions are raised, they will be caught and re-raised after interrupting the main thread. Args: jlink (pylink.JLink): The JLink to write to. Raises: Exception on error. """ try: while jlink.connected(): bytes = list(bytearray(input(), "utf-8") + b"\x0A\x00") bytes_written = jlink.rtt_write(0, bytes) except Exception: print("IO write thread exception, exiting...") thread.interrupt_main() raise
Creates an interactive terminal to the target via RTT. The main loop opens a connection to the JLink, and then connects to the target device. RTT is started, the number of buffers is presented, and then two worker threads are spawned: one for read, and one for write. The main loops sleeps until the JLink is either disconnected or the user hits ctrl-c. Args: target_device (string): The target CPU to connect to. Returns: Always returns ``0`` or a JLinkException. Raises: JLinkException on error.
def main(target_device): """Creates an interactive terminal to the target via RTT. The main loop opens a connection to the JLink, and then connects to the target device. RTT is started, the number of buffers is presented, and then two worker threads are spawned: one for read, and one for write. The main loops sleeps until the JLink is either disconnected or the user hits ctrl-c. Args: target_device (string): The target CPU to connect to. Returns: Always returns ``0`` or a JLinkException. Raises: JLinkException on error. """ jlink = pylink.JLink() print("connecting to JLink...") jlink.open() print("connecting to %s..." % target_device) jlink.set_tif(pylink.enums.JLinkInterfaces.SWD) jlink.connect(target_device) print("connected, starting RTT...") jlink.rtt_start() while True: try: num_up = jlink.rtt_get_num_up_buffers() num_down = jlink.rtt_get_num_down_buffers() print("RTT started, %d up bufs, %d down bufs." % (num_up, num_down)) break except pylink.errors.JLinkRTTException: time.sleep(0.1) try: thread.start_new_thread(read_rtt, (jlink,)) thread.start_new_thread(write_rtt, (jlink,)) while jlink.connected(): time.sleep(1) print("JLink disconnected, exiting...") except KeyboardInterrupt: print("ctrl-c detected, exiting...") pass
Runs the thread. Args: self (ThreadReturn): the ``ThreadReturn`` instance Returns: ``None``
def run(self): """Runs the thread. Args: self (ThreadReturn): the ``ThreadReturn`` instance Returns: ``None`` """ target = getattr(self, '_Thread__target', getattr(self, '_target', None)) args = getattr(self, '_Thread__args', getattr(self, '_args', None)) kwargs = getattr(self, '_Thread__kwargs', getattr(self, '_kwargs', None)) if target is not None: self._return = target(*args, **kwargs) return None
Joins the thread. Args: self (ThreadReturn): the ``ThreadReturn`` instance args: optional list of arguments kwargs: optional key-word arguments Returns: The return value of the exited thread.
def join(self, *args, **kwargs): """Joins the thread. Args: self (ThreadReturn): the ``ThreadReturn`` instance args: optional list of arguments kwargs: optional key-word arguments Returns: The return value of the exited thread. """ super(ThreadReturn, self).join(*args, **kwargs) return self._return
Upgrades the firmware of the J-Links connected to a Windows device. Returns: None. Raises: OSError: if there are no J-Link software packages.
def main(): """Upgrades the firmware of the J-Links connected to a Windows device. Returns: None. Raises: OSError: if there are no J-Link software packages. """ windows_libraries = list(pylink.Library.find_library_windows()) latest_library = None for lib in windows_libraries: if os.path.dirname(lib).endswith('JLinkARM'): # Always use the one pointed to by the 'JLinkARM' directory. latest_library = lib break elif latest_library is None: latest_library = lib elif os.path.dirname(lib) > os.path.dirname(latest_library): latest_library = lib if latest_library is None: raise OSError('No J-Link library found.') library = pylink.Library(latest_library) jlink = pylink.JLink(lib=library) print('Found version: %s' % jlink.version) for emu in jlink.connected_emulators(): jlink.disable_dialog_boxes() jlink.open(serial_no=emu.SerialNumber) jlink.sync_firmware() print('Updated emulator with serial number %s' % emu.SerialNumber) return None
Main function. Args: jlink_serial (str): the J-Link serial number device (str): the target CPU Returns: ``None`` Raises: JLinkException: on error
def main(jlink_serial, device): """Main function. Args: jlink_serial (str): the J-Link serial number device (str): the target CPU Returns: ``None`` Raises: JLinkException: on error """ buf = StringIO.StringIO() jlink = pylink.JLink(log=buf.write, detailed_log=buf.write) jlink.open(serial_no=jlink_serial) jlink.set_tif(pylink.enums.JLinkInterfaces.SWD) jlink.connect(device, verbose=True) # Figure out our original endianess first. big_endian = jlink.set_little_endian() if big_endian: jlink.set_big_endian() print('Target Endian Mode: %s Endian' % ('Big' if big_endian else 'Little'))
Asynchronous function decorator. Interprets the function as being asynchronous, so returns a function that will handle calling the Function asynchronously. Args: func (function): function to be called asynchronously Returns: The wrapped function. Raises: AttributeError: if ``func`` is not callable
def async_decorator(func): """Asynchronous function decorator. Interprets the function as being asynchronous, so returns a function that will handle calling the Function asynchronously. Args: func (function): function to be called asynchronously Returns: The wrapped function. Raises: AttributeError: if ``func`` is not callable """ @functools.wraps(func) def async_wrapper(*args, **kwargs): """Wraps up the call to ``func``, so that it is called from a separate thread. The callback, if given, will be called with two parameters, ``exception`` and ``result`` as ``callback(exception, result)``. If the thread ran to completion without error, ``exception`` will be ``None``, otherwise ``exception`` will be the generated exception that stopped the thread. Result is the result of the exected function. Args: callback (function): the callback to ultimately be called args: list of arguments to pass to ``func`` kwargs: key-word arguments dictionary to pass to ``func`` Returns: A thread if the call is asynchronous, otherwise the the return value of the wrapped function. Raises: TypeError: if ``callback`` is not callable or is missing """ if 'callback' not in kwargs or not kwargs['callback']: return func(*args, **kwargs) callback = kwargs.pop('callback') if not callable(callback): raise TypeError('Expected \'callback\' is not callable.') def thread_func(*args, **kwargs): """Thread function on which the given ``func`` and ``callback`` are executed. Args: args: list of arguments to pass to ``func`` kwargs: key-word arguments dictionary to pass to ``func`` Returns: Return value of the wrapped function. """ exception, res = None, None try: res = func(*args, **kwargs) except Exception as e: exception = e return callback(exception, res) thread = threads.ThreadReturn(target=thread_func, args=args, kwargs=kwargs) thread.daemon = True thread.start() return thread return async_wrapper
Implements simple trace using the STrace API. Args: device (str): the device to connect to trace_address (int): address to begin tracing from breakpoint_address (int): address to breakpoint at Returns: ``None``
def strace(device, trace_address, breakpoint_address): """Implements simple trace using the STrace API. Args: device (str): the device to connect to trace_address (int): address to begin tracing from breakpoint_address (int): address to breakpoint at Returns: ``None`` """ jlink = pylink.JLink() jlink.open() # Do the initial connection sequence. jlink.power_on() jlink.set_tif(pylink.JLinkInterfaces.SWD) jlink.connect(device) jlink.reset() # Clear any breakpoints that may exist as of now. jlink.breakpoint_clear_all() # Start the simple trace. op = pylink.JLinkStraceOperation.TRACE_START jlink.strace_clear_all() jlink.strace_start() # Set the breakpoint and trace events, then restart the CPU so that it # will execute. bphandle = jlink.breakpoint_set(breakpoint_address, thumb=True) trhandle = jlink.strace_code_fetch_event(op, address=trace_address) jlink.restart() time.sleep(1) # Run until the CPU halts due to the breakpoint being hit. while True: if jlink.halted(): break # Print out all instructions that were captured by the trace. while True: instructions = jlink.strace_read(1) if len(instructions) == 0: break instruction = instructions[0] print(jlink.disassemble_instruction(instruction)) jlink.power_off() jlink.close()
Builds the command parser. This needs to be exported in order for Sphinx to document it correctly. Returns: An instance of an ``argparse.ArgumentParser`` that parses all the commands supported by the PyLink CLI.
def create_parser(): """Builds the command parser. This needs to be exported in order for Sphinx to document it correctly. Returns: An instance of an ``argparse.ArgumentParser`` that parses all the commands supported by the PyLink CLI. """ parser = argparse.ArgumentParser(prog=pylink.__title__, description=pylink.__description__, epilog=pylink.__copyright__) parser.add_argument('--version', action='version', version='%(prog)s ' + pylink.__version__) parser.add_argument('-v', '--verbose', action='count', default=0, help='increase output verbosity') kwargs = {} kwargs['title'] = 'command' kwargs['description'] = 'specify subcommand to run' kwargs['help'] = 'subcommands' subparsers = parser.add_subparsers(**kwargs) for command in commands(): kwargs = {} kwargs['name'] = command.name kwargs['description'] = command.description kwargs['help'] = command.help subparser = subparsers.add_parser(**kwargs) subparser.set_defaults(command=command.run) command.add_arguments(subparser) return parser
Main command-line interface entrypoint. Runs the given subcommand or argument that were specified. If not given a ``args`` parameter, assumes the arguments are passed on the command-line. Args: args (list): list of command-line arguments Returns: Zero on success, non-zero otherwise.
def main(args=None): """Main command-line interface entrypoint. Runs the given subcommand or argument that were specified. If not given a ``args`` parameter, assumes the arguments are passed on the command-line. Args: args (list): list of command-line arguments Returns: Zero on success, non-zero otherwise. """ if args is None: args = sys.argv[1:] parser = create_parser() args = parser.parse_args(args) if args.verbose >= 2: level = logging.DEBUG elif args.verbose >= 1: level = logging.INFO else: level = logging.WARNING logging.basicConfig(level=level) try: args.command(args) except pylink.JLinkException as e: sys.stderr.write('Error: %s%s' % (str(e), os.linesep)) return 1 return 0
Creates an instance of a J-Link from the given arguments. Args: self (Command): the ``Command`` instance args (Namespace): arguments to construct the ``JLink`` instance from Returns: An instance of a ``JLink``.
def create_jlink(self, args): """Creates an instance of a J-Link from the given arguments. Args: self (Command): the ``Command`` instance args (Namespace): arguments to construct the ``JLink`` instance from Returns: An instance of a ``JLink``. """ jlink = pylink.JLink() jlink.open(args.serial_no, args.ip_addr) if hasattr(args, 'tif') and args.tif is not None: if args.tif.lower() == 'swd': jlink.set_tif(pylink.JLinkInterfaces.SWD) else: jlink.set_tif(pylink.JLinkInterfaces.JTAG) if hasattr(args, 'device') and args.device is not None: jlink.connect(args.device) return jlink
Adds common arguments to the given parser. Common arguments for a J-Link command are the target interface, and J-Link serial number or IP address. Args: self (Command): the ``Command`` instance parser (argparse.ArgumentParser): the parser to add the arguments to has_device (bool): boolean indicating if it has the device argument Returns: ``None``
def add_common_arguments(self, parser, has_device=False): """Adds common arguments to the given parser. Common arguments for a J-Link command are the target interface, and J-Link serial number or IP address. Args: self (Command): the ``Command`` instance parser (argparse.ArgumentParser): the parser to add the arguments to has_device (bool): boolean indicating if it has the device argument Returns: ``None`` """ if has_device: parser.add_argument('-t', '--tif', required=True, type=str.lower, choices=['jtag', 'swd'], help='target interface (JTAG | SWD)') parser.add_argument('-d', '--device', required=True, help='specify the target device name') group = parser.add_mutually_exclusive_group(required=False) group.add_argument('-s', '--serial', dest='serial_no', help='specify the J-Link serial number') group.add_argument('-i', '--ip_addr', dest='ip_addr', help='J-Link IP address') return None
Erases the device connected to the J-Link. Args: self (EraseCommand): the ``EraseCommand`` instance args (Namespace): the arguments passed on the command-line Returns: ``None``
def run(self, args): """Erases the device connected to the J-Link. Args: self (EraseCommand): the ``EraseCommand`` instance args (Namespace): the arguments passed on the command-line Returns: ``None`` """ jlink = self.create_jlink(args) erased = jlink.erase() print('Bytes Erased: %d' % erased)
Flashes the device connected to the J-Link. Args: self (FlashCommand): the ``FlashCommand`` instance args (Namespace): the arguments passed on the command-line Returns: ``None``
def run(self, args): """Flashes the device connected to the J-Link. Args: self (FlashCommand): the ``FlashCommand`` instance args (Namespace): the arguments passed on the command-line Returns: ``None`` """ kwargs = {} kwargs['path'] = args.file[0] kwargs['addr'] = args.addr kwargs['on_progress'] = pylink.util.flash_progress_callback jlink = self.create_jlink(args) _ = jlink.flash_file(**kwargs) print('Flashed device successfully.')