winappdbg.thread

Thread instrumentation.

class winappdbg.thread.Thread(dwThreadId, hThread=None, process=None)

Interface to a thread in another process.

Variables:
  • dwThreadId – Global thread ID.

  • hThread – Handle to the thread.

  • process – Parent process object.

  • pInjectedMemory

    If the thread was created by Process.inject_code(), this member contains a pointer to the memory buffer for the injected code. Otherwise it’s None.

    The kill() method uses this member to free the buffer when the injected thread is killed.

clear()

Clears the resources held by this object.

clear_tf()

Clears the Trap flag.

close_handle()

Closes the handle to the thread.

Note

Normally you don’t need to call this method. All handles created by WinAppDbg are automatically closed when the garbage collector claims them.

disassemble(lpAddress, dwSize)

Disassemble instructions from the address space of the process.

Parameters:
  • lpAddress (int) – Memory address where to read the code from.

  • dwSize (int) – Size of binary code to disassemble.

Return type:

list of tuple( long, int, str, str )

Returns:

List of tuples. Each tuple represents an assembly instruction and contains:

  • Memory address of instruction.

  • Size of instruction in bytes.

  • Disassembly line of instruction.

  • Hexadecimal dump of instruction.

disassemble_around(lpAddress, dwSize=64)

Disassemble around the given address.

Parameters:
  • lpAddress (int) – Memory address where to read the code from.

  • dwSize (int) – Delta offset. Code will be read from lpAddress - dwSize to lpAddress + dwSize.

Return type:

list of tuple( long, int, str, str )

Returns:

List of tuples. Each tuple represents an assembly instruction and contains:

  • Memory address of instruction.

  • Size of instruction in bytes.

  • Disassembly line of instruction.

  • Hexadecimal dump of instruction.

disassemble_around_pc(dwSize=64)

Disassemble around the program counter of the given thread.

Parameters:

dwSize (int) – Delta offset. Code will be read from pc - dwSize to pc + dwSize.

Return type:

list of tuple( long, int, str, str )

Returns:

List of tuples. Each tuple represents an assembly instruction and contains:

  • Memory address of instruction.

  • Size of instruction in bytes.

  • Disassembly line of instruction.

  • Hexadecimal dump of instruction.

disassemble_current()

Disassemble the instruction at the program counter of the given thread.

Return type:

tuple( long, int, str, str )

Returns:

The tuple represents an assembly instruction and contains:

  • Memory address of instruction.

  • Size of instruction in bytes.

  • Disassembly line of instruction.

  • Hexadecimal dump of instruction.

disassemble_instruction(lpAddress)

Disassemble the instruction at the given memory address.

Parameters:

lpAddress (int) – Memory address where to read the code from.

Return type:

tuple( long, int, str, str )

Returns:

The tuple represents an assembly instruction and contains:

  • Memory address of instruction.

  • Size of instruction in bytes.

  • Disassembly line of instruction.

  • Hexadecimal dump of instruction.

disassemble_string(lpAddress, code)

Disassemble instructions from a block of binary code.

Parameters:
  • lpAddress (int) – Memory address where the code was read from.

  • code (bytes) – Binary code to disassemble.

Return type:

list of tuple( long, int, str, str )

Returns:

List of tuples. Each tuple represents an assembly instruction and contains:

  • Memory address of instruction.

  • Size of instruction in bytes.

  • Disassembly line of instruction.

  • Hexadecimal dump of instruction.

get_arch()
Return type:

str

Returns:

The architecture in which this thread believes to be running. For example, if running a 32 bit binary in a 64 bit machine, the architecture returned by this method will be win32.ARCH_I386, but the value of System.arch will be win32.ARCH_AMD64.

get_bits()
Return type:

str

Returns:

The number of bits in which this thread believes to be running. For example, if running a 32 bit binary in a 64 bit machine, the number of bits returned by this method will be 32, but the value of System.arch will be 64.

get_context(ContextFlags=None, bSuspend=False, bRaw=False)

Retrieves the execution context (i.e. the registers values) for this thread.

Parameters:
  • ContextFlags (int) – Optional, specify which registers to retrieve. Defaults to win32.CONTEXT_ALL which retrieves all registes for the current platform.

  • bSuspend (bool) –

    True to automatically suspend the thread before getting its context, False otherwise.

    Defaults to False because suspending the thread during some debug events (like thread creation or destruction) may lead to strange errors.

    Note that WinAppDbg 1.4 used to suspend the thread automatically always. This behavior was changed in version 1.5.

  • bRaw (bool) – True to return a raw ctypes CONTEXT structure, False to get Python dictionary mapping register names to their values. Defaults to False because in most cases you never need the ctypes structure.

Return type:

dict( str -> int )

Returns:

Dictionary mapping register names to their values.

See also

set_context()

get_exit_code()
Return type:

int

Returns:

Thread exit code, or STILL_ACTIVE if it’s still alive.

get_flags(FlagMask=4294967295)
Parameters:

FlagMask (int) – (Optional) Bitwise-AND mask.

Return type:

int

Returns:

Flag register contents, optionally masking out some bits.

get_fp()
Return type:

int

Returns:

Value of the frame pointer register.

get_handle(dwDesiredAccess=2032639)

Returns a handle to the thread with at least the access rights requested.

Note

If a handle was previously opened and has the required access rights, it’s reused. If not, a new handle is opened with the combination of the old and new access rights.

Parameters:

dwDesiredAccess (int) – Desired access rights. See: http://msdn.microsoft.com/en-us/library/windows/desktop/ms686769(v=vs.85).aspx

Return type:

ThreadHandle

Returns:

Handle to the thread.

Raises:

WindowsError – It’s not possible to open a handle to the thread with the requested access rights. This typically happens because the target thread belongs to system process and the debugger is not runnning with administrative rights.

get_label_at_pc()
Return type:

str

Returns:

Label that points to the instruction currently being executed.

get_linear_address(segment, address)

Translates segment-relative addresses to linear addresses.

Linear addresses can be used to access a process memory, calling Process.read() and Process.write().

Parameters:
  • segment (str, int or long) – Segment register name or DWORD descriptor table index.

  • address (int) – Segment relative memory address.

Return type:

int

Returns:

Linear memory address.

Raises:
  • ValueError – Address is too large for selector.

  • WindowsError – The current architecture does not support selectors. Selectors only exist in x86-based systems.

get_name()
Return type:

str

Returns:

Thread name, or None if the thread is nameless.

get_pc()
Return type:

int

Returns:

Value of the program counter register.

get_pid()
Return type:

int

Returns:

Parent process global ID.

Raises:
  • WindowsError – An error occured when calling a Win32 API function.

  • RuntimeError – The parent process ID can’t be found.

get_process()
Return type:

Process

Returns:

Parent Process object. Returns None if unknown.

get_register(register)
Parameters:

register (str) – Register name.

Return type:

int

Returns:

Value of the requested register.

get_seh_chain()
Return type:

list of tuple( int, int )

Returns:

List of structured exception handlers. Each SEH is represented as a tuple of two addresses:

  • Address of this SEH block

  • Address of the SEH callback function

Do not confuse this with the contents of the SEH block itself, where the first member is a pointer to the next block instead.

Raises:

NotImplementedError – This method is only supported in 32 bits versions of Windows.

get_seh_chain_pointer()

Get the pointer to the first structured exception handler block.

Return type:

int

Returns:

Remote pointer to the first block of the structured exception handlers linked list. If the list is empty, the returned value is 0xFFFFFFFF.

Raises:

NotImplementedError – This method is only supported in 32 bits versions of Windows.

get_sp()
Return type:

int

Returns:

Value of the stack pointer register.

get_stack_frame(max_size=None)

Reads the contents of the current stack frame. Only works for functions with standard prologue and epilogue.

Parameters:

max_size (int) – (Optional) Maximum amount of bytes to read.

Return type:

bytes

Returns:

Stack frame data. May not be accurate, depending on the compiler used. May return an empty string.

Raises:
  • RuntimeError – The stack frame is invalid, or the function doesn’t have a standard prologue and epilogue.

  • WindowsError – An error occured when getting the thread context or reading data from the process memory.

get_stack_frame_range()

Returns the starting and ending addresses of the stack frame. Only works for functions with standard prologue and epilogue.

Return type:

tuple( int, int )

Returns:

Stack frame range. May not be accurate, depending on the compiler used.

Raises:
  • RuntimeError – The stack frame is invalid, or the function doesn’t have a standard prologue and epilogue.

  • WindowsError – An error occured when getting the thread context.

get_stack_range()
Return type:

tuple( int, int )

Returns:

Stack beginning and end pointers, in memory addresses order. That is, the first pointer is the stack top, and the second pointer is the stack bottom, since the stack grows towards lower memory addresses.

Raises:

WindowsError – Raises an exception on error.

get_stack_trace(depth=16)

Tries to get a stack trace for the current function. Only works for functions with standard prologue and epilogue.

Parameters:

depth (int) – Maximum depth of stack trace.

Return type:

tuple of tuple( int, int, str )

Returns:

Stack trace of the thread as a tuple of ( return address, frame pointer address, module filename ).

Raises:

WindowsError – Raises an exception on error.

get_stack_trace_with_labels(depth=16, bMakePretty=True)

Tries to get a stack trace for the current function. Only works for functions with standard prologue and epilogue.

Parameters:
  • depth (int) – Maximum depth of stack trace.

  • bMakePretty (bool) –

    True for user readable labels, False for labels that can be passed to Process.resolve_label().

    ”Pretty” labels look better when producing output for the user to read, while pure labels are more useful programatically.

Return type:

tuple of tuple( int, int, str )

Returns:

Stack trace of the thread as a tuple of ( return address, frame pointer label ).

Raises:

WindowsError – Raises an exception on error.

get_teb()

Returns a copy of the TEB. To dereference pointers in it call Process.read_structure().

Return type:

win32.TEB

Returns:

TEB structure.

Raises:

WindowsError – An exception is raised on error.

get_teb_address()

Returns a remote pointer to the TEB.

Return type:

int

Returns:

Remote pointer to the TEB structure.

Raises:

WindowsError – An exception is raised on error.

get_tf()

Gets the Trap flag.

get_tid()
Return type:

int

Returns:

Thread global ID.

get_wait_chain()
Return type:

tuple of ( list of win32.WaitChainNodeInfo structures, bool)

Returns:

Wait chain for the thread. The boolean indicates if there’s a cycle in the chain (a deadlock).

Raises:

AttributeError – This method is only suppported in Windows Vista and above.

See:

http://msdn.microsoft.com/en-us/library/ms681622%28VS.85%29.aspx

get_windows()
Return type:

list of Window

Returns:

Returns a list of windows handled by this thread.

is_alive()
Return type:

bool

Returns:

True if the thread if currently running.

Raises:

WindowsError – The debugger doesn’t have enough privileges to perform this action.

is_hidden()

Determines if the thread has been hidden from debuggers.

Some binary packers hide their own threads to thwart debugging.

Return type:

bool

Returns:

True if the thread is hidden from debuggers. This means the thread’s execution won’t be stopped for debug events, and thus said events won’t be sent to the debugger.

is_wow64()

Determines if the thread is running under WOW64.

Return type:

bool

Returns:

True if the thread is running under WOW64. That is, it belongs to a 32-bit application running in a 64-bit Windows.

False if the thread belongs to either a 32-bit application running in a 32-bit Windows, or a 64-bit application running in a 64-bit Windows.

Raises:

WindowsError – On error an exception is raised.

See:

http://msdn.microsoft.com/en-us/library/aa384249(VS.85).aspx

kill(dwExitCode=0)

Terminates the thread execution.

Note

If the lpInjectedMemory member contains a valid pointer, the memory is freed.

Parameters:

dwExitCode (int) – (Optional) Thread exit code.

open_handle(dwDesiredAccess=2032639)

Opens a new handle to the thread, closing the previous one.

The new handle is stored in the hThread property.

Warning

Normally you should call get_handle() instead, since it’s much “smarter” and tries to reuse handles and merge access rights.

Parameters:

dwDesiredAccess (int) – Desired access rights. Defaults to win32.THREAD_ALL_ACCESS. See: http://msdn.microsoft.com/en-us/library/windows/desktop/ms686769(v=vs.85).aspx

Raises:

WindowsError – It’s not possible to open a handle to the thread with the requested access rights. This typically happens because the target thread belongs to system process and the debugger is not runnning with administrative rights.

peek_code_bytes(size=128, offset=0)

Tries to read some bytes of the code currently being executed.

Parameters:
  • size (int) – Number of bytes to read.

  • offset (int) – Offset from the program counter to begin reading.

Return type:

bytes

Returns:

Bytes read from the process memory. May be less than the requested number of bytes.

peek_pointers_in_data(data, peekSize=16, peekStep=1)

Tries to guess which values in the given data are valid pointers, and reads some data from them.

Parameters:
  • data (bytes) – Binary data to find pointers in.

  • peekSize (int) – Number of bytes to read from each pointer found.

  • peekStep (int) – Expected data alignment. Typically you specify 1 when data alignment is unknown, or 4 when you expect data to be DWORD aligned. Any other value may be specified.

Return type:

dict( str -> bytes )

Returns:

Dictionary mapping stack offsets to the data they point to.

peek_pointers_in_registers(peekSize=16, context=None)

Tries to guess which values in the registers are valid pointers, and reads some data from them.

Parameters:
  • peekSize (int) – Number of bytes to read from each pointer found.

  • context (dict( str -> int )) – (Optional) Dictionary mapping register names to their values. If not given, the current thread context will be used.

Return type:

dict( str -> bytes )

Returns:

Dictionary mapping register names to the data they point to.

peek_stack_data(size=128, offset=0)

Tries to read the contents of the top of the stack.

Parameters:
  • size (int) – Number of bytes to read.

  • offset (int) – Offset from the stack pointer to begin reading.

Return type:

bytes

Returns:

Stack data. Returned data may be less than the requested size.

peek_stack_dwords(count, offset=0)

Tries to read DWORDs from the top of the stack.

Parameters:
  • count (int) – Number of DWORDs to read.

  • offset (int) – Offset from the stack pointer to begin reading.

Return type:

tuple( int… )

Returns:

Tuple of integers read from the stack. May be less than the requested number of DWORDs.

peek_stack_qwords(count, offset=0)

Tries to read QWORDs from the top of the stack.

Parameters:
  • count (int) – Number of QWORDs to read.

  • offset (int) – Offset from the stack pointer to begin reading.

Return type:

tuple( int… )

Returns:

Tuple of integers read from the stack. May be less than the requested number of QWORDs.

read_code_bytes(size=128, offset=0)

Tries to read some bytes of the code currently being executed.

Parameters:
  • size (int) – Number of bytes to read.

  • offset (int) – Offset from the program counter to begin reading.

Return type:

bytes

Returns:

Bytes read from the process memory.

Raises:

WindowsError – Could not read the requested data.

read_stack_data(size=128, offset=0)

Reads the contents of the top of the stack.

Parameters:
  • size (int) – Number of bytes to read.

  • offset (int) – Offset from the stack pointer to begin reading.

Return type:

bytes

Returns:

Stack data.

Raises:

WindowsError – Could not read the requested data.

read_stack_dwords(count, offset=0)

Reads DWORDs from the top of the stack.

Parameters:
  • count (int) – Number of DWORDs to read.

  • offset (int) – Offset from the stack pointer to begin reading.

Return type:

tuple( int… )

Returns:

Tuple of integers read from the stack.

Raises:

WindowsError – Could not read the requested data.

read_stack_frame(structure, offset=0)

Reads the stack frame of the thread.

Parameters:
  • structure (ctypes.Structure) – Structure of the stack frame.

  • offset (int) – Offset from the frame pointer to begin reading. The frame pointer is the same returned by the get_fp() method.

Return type:

tuple

Returns:

Tuple of elements read from the stack frame. The type of each element matches the types in the stack frame structure.

read_stack_qwords(count, offset=0)

Reads QWORDs from the top of the stack.

Parameters:
  • count (int) – Number of QWORDs to read.

  • offset (int) – Offset from the stack pointer to begin reading.

Return type:

tuple( int… )

Returns:

Tuple of integers read from the stack.

Raises:

WindowsError – Could not read the requested data.

read_stack_structure(structure, offset=0)

Reads the given structure at the top of the stack.

Parameters:
  • structure (ctypes.Structure) – Structure of the data to read from the stack.

  • offset (int) – Offset from the stack pointer to begin reading. The stack pointer is the same returned by the get_sp() method.

Return type:

tuple

Returns:

Tuple of elements read from the stack. The type of each element matches the types in the stack frame structure.

resume()

Resumes the thread execution.

Return type:

int

Returns:

Suspend count. If zero, the thread is running.

set_context(context, bSuspend=False)

Sets the values of the registers.

See also

get_context()

Parameters:
  • context (dict( str -> int )) – Dictionary mapping register names to their values.

  • bSuspend (bool) –

    True to automatically suspend the thread before setting its context, False otherwise.

    Defaults to False because suspending the thread during some debug events (like thread creation or destruction) may lead to strange errors.

    Note that WinAppDbg 1.4 used to suspend the thread automatically always. This behavior was changed in version 1.5.

set_flags(value, FlagMask=4294967295)

Sets the flags register, optionally masking some bits.

Parameters:
  • value (int) – Flag register contents.

  • FlagMask (int) – (Optional) Bitwise-AND mask.

set_fp(fp)

Sets the value of the frame pointer register.

Parameters:

fp (int) – Value of the frame pointer register.

set_name(name=None)

Sets the thread’s name.

Parameters:

name (str) – Thread name, or None if the thread is nameless.

set_pc(pc)

Sets the value of the program counter register.

Parameters:

pc (int) – Value of the program counter register.

set_process(process=None)

Manually set the parent Process object. Use with care!

Parameters:

process (Process) – (Optional) Process object. Use None for no process.

set_register(register, value)

Sets the value of a specific register.

Parameters:

register (str) – Register name.

Return type:

int

Returns:

Register value.

set_seh_chain_pointer(value)

Change the pointer to the first structured exception handler block.

Parameters:

value (int) – Value of the remote pointer to the first block of the structured exception handlers linked list. To disable SEH set the value 0xFFFFFFFF.

Raises:

NotImplementedError – This method is only supported in 32 bits versions of Windows.

set_sp(sp)

Sets the value of the stack pointer register.

Parameters:

sp (int) – Value of the stack pointer register.

set_tf()

Sets the Trap flag.

suspend()

Suspends the thread execution.

Return type:

int

Returns:

Suspend count. If zero, the thread is running.

wait(dwTimeout=None)

Waits for the thread to finish executing.

Parameters:

dwTimeout (int) – (Optional) Timeout value in milliseconds. Use INFINITE or None for no timeout.