code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
if data is None:
return ''
if arch is None:
arch = win32.arch
pointers = compat.keys(data)
pointers.sort()
result = ''
if pointers:
if arch == win32.ARCH_I386:
spreg = 'esp'
elif arch == win32.ARCH_AMD64:
spreg = 'rsp'
else:
spreg = 'STACK' # just a generic tag
tag_fmt = '[%s+0x%%.%dx]' % (spreg, len( '%x' % pointers[-1] ) )
for offset in pointers:
dumped = HexDump.hexline(data[offset], separator, width)
tag = tag_fmt % offset
result += '%s -> %s\n' % (tag, dumped)
return result | def dump_stack_peek(data, separator = ' ', width = 16, arch = None) | Dump data from pointers guessed within the given stack dump.
@type data: str
@param data: Dictionary mapping stack offsets to the data they point to.
@type separator: str
@param separator:
Separator between the hexadecimal representation of each character.
@type width: int
@param width:
(Optional) Maximum number of characters to convert per text line.
This value is also used for padding.
@type arch: str
@param arch: Architecture of the machine whose registers were dumped.
Defaults to the current architecture.
@rtype: str
@return: Text suitable for logging. | 4.204653 | 4.302927 | 0.977161 |
if not stack_trace:
return ''
table = Table()
table.addRow('Frame', 'Origin', 'Module')
for (fp, ra, mod) in stack_trace:
fp_d = HexDump.address(fp, bits)
ra_d = HexDump.address(ra, bits)
table.addRow(fp_d, ra_d, mod)
return table.getOutput() | def dump_stack_trace(stack_trace, bits = None) | Dump a stack trace, as returned by L{Thread.get_stack_trace} with the
C{bUseLabels} parameter set to C{False}.
@type stack_trace: list( int, int, str )
@param stack_trace: Stack trace as a list of tuples of
( return address, frame pointer, module filename )
@type bits: int
@param bits:
(Optional) Number of bits of the target architecture.
The default is platform dependent. See: L{HexDump.address_size}
@rtype: str
@return: Text suitable for logging. | 4.250593 | 3.646839 | 1.165556 |
if not stack_trace:
return ''
table = Table()
table.addRow('Frame', 'Origin')
for (fp, label) in stack_trace:
table.addRow( HexDump.address(fp, bits), label )
return table.getOutput() | def dump_stack_trace_with_labels(stack_trace, bits = None) | Dump a stack trace,
as returned by L{Thread.get_stack_trace_with_labels}.
@type stack_trace: list( int, int, str )
@param stack_trace: Stack trace as a list of tuples of
( return address, frame pointer, module filename )
@type bits: int
@param bits:
(Optional) Number of bits of the target architecture.
The default is platform dependent. See: L{HexDump.address_size}
@rtype: str
@return: Text suitable for logging. | 6.188745 | 5.818748 | 1.063587 |
if not disassembly:
return ''
table = Table(sep = ' | ')
for (addr, size, code, dump) in disassembly:
if bLowercase:
code = code.lower()
if addr == pc:
addr = ' * %s' % HexDump.address(addr, bits)
else:
addr = ' %s' % HexDump.address(addr, bits)
table.addRow(addr, dump, code)
table.justify(1, 1)
return table.getOutput() | def dump_code(disassembly, pc = None,
bLowercase = True,
bits = None) | Dump a disassembly. Optionally mark where the program counter is.
@type disassembly: list of tuple( int, int, str, str )
@param disassembly: Disassembly dump as returned by
L{Process.disassemble} or L{Thread.disassemble_around_pc}.
@type pc: int
@param pc: (Optional) Program counter.
@type bLowercase: bool
@param bLowercase: (Optional) If C{True} convert the code to lowercase.
@type bits: int
@param bits:
(Optional) Number of bits of the target architecture.
The default is platform dependent. See: L{HexDump.address_size}
@rtype: str
@return: Text suitable for logging. | 3.822675 | 3.719471 | 1.027747 |
if bits is None:
address_size = HexDump.address_size
else:
address_size = bits / 4
(addr, size, code, dump) = disassembly_line
dump = dump.replace(' ', '')
result = list()
fmt = ''
if bShowAddress:
result.append( HexDump.address(addr, bits) )
fmt += '%%%ds:' % address_size
if bShowDump:
result.append(dump)
if dwDumpWidth:
fmt += ' %%-%ds' % dwDumpWidth
else:
fmt += ' %s'
if bLowercase:
code = code.lower()
result.append(code)
if dwCodeWidth:
fmt += ' %%-%ds' % dwCodeWidth
else:
fmt += ' %s'
return fmt % tuple(result) | def dump_code_line(disassembly_line, bShowAddress = True,
bShowDump = True,
bLowercase = True,
dwDumpWidth = None,
dwCodeWidth = None,
bits = None) | Dump a single line of code. To dump a block of code use L{dump_code}.
@type disassembly_line: tuple( int, int, str, str )
@param disassembly_line: Single item of the list returned by
L{Process.disassemble} or L{Thread.disassemble_around_pc}.
@type bShowAddress: bool
@param bShowAddress: (Optional) If C{True} show the memory address.
@type bShowDump: bool
@param bShowDump: (Optional) If C{True} show the hexadecimal dump.
@type bLowercase: bool
@param bLowercase: (Optional) If C{True} convert the code to lowercase.
@type dwDumpWidth: int or None
@param dwDumpWidth: (Optional) Width in characters of the hex dump.
@type dwCodeWidth: int or None
@param dwCodeWidth: (Optional) Width in characters of the code.
@type bits: int
@param bits:
(Optional) Number of bits of the target architecture.
The default is platform dependent. See: L{HexDump.address_size}
@rtype: str
@return: Text suitable for logging. | 2.536261 | 2.375498 | 1.067675 |
if not memoryMap:
return ''
table = Table()
if mappedFilenames:
table.addRow("Address", "Size", "State", "Access", "Type", "File")
else:
table.addRow("Address", "Size", "State", "Access", "Type")
# For each memory block in the map...
for mbi in memoryMap:
# Address and size of memory block.
BaseAddress = HexDump.address(mbi.BaseAddress, bits)
RegionSize = HexDump.address(mbi.RegionSize, bits)
# State (free or allocated).
mbiState = mbi.State
if mbiState == win32.MEM_RESERVE:
State = "Reserved"
elif mbiState == win32.MEM_COMMIT:
State = "Commited"
elif mbiState == win32.MEM_FREE:
State = "Free"
else:
State = "Unknown"
# Page protection bits (R/W/X/G).
if mbiState != win32.MEM_COMMIT:
Protect = ""
else:
mbiProtect = mbi.Protect
if mbiProtect & win32.PAGE_NOACCESS:
Protect = "--- "
elif mbiProtect & win32.PAGE_READONLY:
Protect = "R-- "
elif mbiProtect & win32.PAGE_READWRITE:
Protect = "RW- "
elif mbiProtect & win32.PAGE_WRITECOPY:
Protect = "RC- "
elif mbiProtect & win32.PAGE_EXECUTE:
Protect = "--X "
elif mbiProtect & win32.PAGE_EXECUTE_READ:
Protect = "R-X "
elif mbiProtect & win32.PAGE_EXECUTE_READWRITE:
Protect = "RWX "
elif mbiProtect & win32.PAGE_EXECUTE_WRITECOPY:
Protect = "RCX "
else:
Protect = "??? "
if mbiProtect & win32.PAGE_GUARD:
Protect += "G"
else:
Protect += "-"
if mbiProtect & win32.PAGE_NOCACHE:
Protect += "N"
else:
Protect += "-"
if mbiProtect & win32.PAGE_WRITECOMBINE:
Protect += "W"
else:
Protect += "-"
# Type (file mapping, executable image, or private memory).
mbiType = mbi.Type
if mbiType == win32.MEM_IMAGE:
Type = "Image"
elif mbiType == win32.MEM_MAPPED:
Type = "Mapped"
elif mbiType == win32.MEM_PRIVATE:
Type = "Private"
elif mbiType == 0:
Type = ""
else:
Type = "Unknown"
# Output a row in the table.
if mappedFilenames:
FileName = mappedFilenames.get(mbi.BaseAddress, '')
table.addRow( BaseAddress, RegionSize, State, Protect, Type, FileName )
else:
table.addRow( BaseAddress, RegionSize, State, Protect, Type )
# Return the table output.
return table.getOutput() | def dump_memory_map(memoryMap, mappedFilenames = None, bits = None) | Dump the memory map of a process. Optionally show the filenames for
memory mapped files as well.
@type memoryMap: list( L{win32.MemoryBasicInformation} )
@param memoryMap: Memory map returned by L{Process.get_memory_map}.
@type mappedFilenames: dict( int S{->} str )
@param mappedFilenames: (Optional) Memory mapped filenames
returned by L{Process.get_mapped_filenames}.
@type bits: int
@param bits:
(Optional) Number of bits of the target architecture.
The default is platform dependent. See: L{HexDump.address_size}
@rtype: str
@return: Text suitable for logging. | 1.884431 | 1.826377 | 1.031787 |
if text.endswith('\n'):
text = text[:-len('\n')]
#text = text.replace('\n', '\n\t\t') # text CSV
ltime = time.strftime("%X")
msecs = (time.time() % 1) * 1000
return '[%s.%04d] %s' % (ltime, msecs, text) | def log_text(text) | Log lines of text, inserting a timestamp.
@type text: str
@param text: Text to log.
@rtype: str
@return: Log line. | 4.961261 | 4.858914 | 1.021064 |
if not text:
if event.get_event_code() == win32.EXCEPTION_DEBUG_EVENT:
what = event.get_exception_description()
if event.is_first_chance():
what = '%s (first chance)' % what
else:
what = '%s (second chance)' % what
try:
address = event.get_fault_address()
except NotImplementedError:
address = event.get_exception_address()
else:
what = event.get_event_name()
address = event.get_thread().get_pc()
process = event.get_process()
label = process.get_label_at_address(address)
address = HexDump.address(address, process.get_bits())
if label:
where = '%s (%s)' % (address, label)
else:
where = address
text = '%s at %s' % (what, where)
text = 'pid %d tid %d: %s' % (event.get_pid(), event.get_tid(), text)
#text = 'pid %d tid %d:\t%s' % (event.get_pid(), event.get_tid(), text) # text CSV
return cls.log_text(text) | def log_event(cls, event, text = None) | Log lines of text associated with a debug event.
@type event: L{Event}
@param event: Event object.
@type text: str
@param text: (Optional) Text to log. If no text is provided the default
is to show a description of the event itself.
@rtype: str
@return: Log line. | 3.291538 | 3.471663 | 0.948116 |
from sys import stderr
msg = "Warning, error writing log file %s: %s\n"
msg = msg % (self.logfile, str(e))
stderr.write(DebugLog.log_text(msg))
self.logfile = None
self.fd = None | def __logfile_error(self, e) | Shows an error message to standard error
if the log file can't be written to.
Used internally.
@type e: Exception
@param e: Exception raised when trying to write to the log file. | 6.059569 | 6.198478 | 0.97759 |
if isinstance(text, compat.unicode):
text = text.encode('cp1252')
if self.verbose:
print(text)
if self.logfile:
try:
self.fd.writelines('%s\n' % text)
except IOError:
e = sys.exc_info()[1]
self.__logfile_error(e) | def __do_log(self, text) | Writes the given text verbatim into the log file (if any)
and/or standard input (if the verbose flag is turned on).
Used internally.
@type text: str
@param text: Text to print. | 3.321849 | 3.519804 | 0.94376 |
self.__do_log( DebugLog.log_event(event, text) ) | def log_event(self, event, text = None) | Log lines of text associated with a debug event.
@type event: L{Event}
@param event: Event object.
@type text: str
@param text: (Optional) Text to log. If no text is provided the default
is to show a description of the event itself. | 16.979406 | 22.440756 | 0.756633 |
try:
params, method = xmlrpclib.loads(data)
# generate response
if dispatch_method is not None:
response = dispatch_method(method, params)
else:
response = self._dispatch(method, params)
# wrap response in a singleton tuple
response = (response,)
response = xmlrpclib.dumps(response, methodresponse=1,
allow_none=self.allow_none, encoding=self.encoding)
except Fault, fault:
response = xmlrpclib.dumps(fault, allow_none=self.allow_none,
encoding=self.encoding)
except:
# report exception back to server
response = xmlrpclib.dumps(
xmlrpclib.Fault(1, "%s:%s" % (sys.exc_type, sys.exc_value)), #@UndefinedVariable exc_value only available when we actually have an exception
encoding=self.encoding, allow_none=self.allow_none,
)
return response | def _marshaled_dispatch(self, data, dispatch_method=None) | Dispatches an XML-RPC method from marshalled (XML) data.
XML-RPC methods are dispatched from the marshalled (XML) data
using the _dispatch method and the result is returned as
marshalled data. For backwards compatibility, a dispatch
function can be provided as an argument (see comment in
SimpleXMLRPCRequestHandler.do_POST) but overriding the
existing method through subclassing is the prefered means
of changing method dispatch behavior. | 2.950706 | 2.850152 | 1.03528 |
methods = self.funcs.keys()
if self.instance is not None:
# Instance can implement _listMethod to return a list of
# methods
if hasattr(self.instance, '_listMethods'):
methods = remove_duplicates(
methods + self.instance._listMethods()
)
# if the instance has a _dispatch method then we
# don't have enough information to provide a list
# of methods
elif not hasattr(self.instance, '_dispatch'):
methods = remove_duplicates(
methods + list_public_methods(self.instance)
)
methods.sort()
return methods | def system_listMethods(self) | system.listMethods() => ['add', 'subtract', 'multiple']
Returns a list of the methods supported by the server. | 4.588974 | 4.834699 | 0.949175 |
# Check that the path is legal
if not self.is_rpc_path_valid():
self.report_404()
return
try:
# Get arguments by reading body of request.
# We read this in chunks to avoid straining
# socket.read(); around the 10 or 15Mb mark, some platforms
# begin to have problems (bug #792570).
max_chunk_size = 10 * 1024 * 1024
size_remaining = int(self.headers["content-length"])
L = []
while size_remaining:
chunk_size = min(size_remaining, max_chunk_size)
L.append(self.rfile.read(chunk_size))
size_remaining -= len(L[-1])
data = ''.join(L)
# In previous versions of SimpleXMLRPCServer, _dispatch
# could be overridden in this class, instead of in
# SimpleXMLRPCDispatcher. To maintain backwards compatibility,
# check to see if a subclass implements _dispatch and dispatch
# using that method if present.
response = self.server._marshaled_dispatch(
data, getattr(self, '_dispatch', None)
)
except: # This should only happen if the module is buggy
# internal error, report as HTTP server error
self.send_response(500)
self.end_headers()
else:
# got a valid XML RPC response
self.send_response(200)
self.send_header("Content-type", "text/xml")
self.send_header("Content-length", str(len(response)))
self.end_headers()
self.wfile.write(response)
# shut down the connection
self.wfile.flush()
self.connection.shutdown(1) | def do_POST(self) | Handles the HTTP POST request.
Attempts to interpret all HTTP POST requests as XML-RPC calls,
which are forwarded to the server's _dispatch method for handling. | 3.350973 | 3.228825 | 1.037831 |
if self.server.logRequests:
BaseHTTPServer.BaseHTTPRequestHandler.log_request(self, code, size) | def log_request(self, code='-', size='-') | Selectively log an accepted request. | 5.167363 | 4.647738 | 1.111802 |
response = self._marshaled_dispatch(request_text)
sys.stdout.write('Content-Type: text/xml\n')
sys.stdout.write('Content-Length: %d\n' % len(response))
sys.stdout.write('\n')
sys.stdout.write(response) | def handle_xmlrpc(self, request_text) | Handle a single XML-RPC request | 2.409623 | 2.317833 | 1.039602 |
code = 400
message, explain = \
BaseHTTPServer.BaseHTTPRequestHandler.responses[code]
response = BaseHTTPServer.DEFAULT_ERROR_MESSAGE % { #@UndefinedVariable
'code' : code,
'message' : message,
'explain' : explain
}
sys.stdout.write('Status: %d %s\n' % (code, message))
sys.stdout.write('Content-Type: text/html\n')
sys.stdout.write('Content-Length: %d\n' % len(response))
sys.stdout.write('\n')
sys.stdout.write(response) | def handle_get(self) | Handle a single HTTP GET request.
Default implementation indicates an error because
XML-RPC uses the POST method. | 3.224762 | 2.976531 | 1.083396 |
if request_text is None and \
os.environ.get('REQUEST_METHOD', None) == 'GET':
self.handle_get()
else:
# POST data is normally available through stdin
if request_text is None:
request_text = sys.stdin.read()
self.handle_xmlrpc(request_text) | def handle_request(self, request_text=None) | Handle a single XML-RPC request passed through a CGI post method.
If no XML data is given then it is read from stdin. The resulting
XML-RPC response is printed to stdout along with the correct HTTP
headers. | 4.001236 | 3.393461 | 1.179102 |
''' Return True if running Python is suitable for GUI Event Integration and deeper IPython integration '''
# We require Python 2.6+ ...
if sys.hexversion < 0x02060000:
return False
# Or Python 3.2+
if sys.hexversion >= 0x03000000 and sys.hexversion < 0x03020000:
return False
# Not supported under Jython nor IronPython
if sys.platform.startswith("java") or sys.platform.startswith('cli'):
return False
return True | def versionok_for_gui() | Return True if running Python is suitable for GUI Event Integration and deeper IPython integration | 4.423306 | 2.612899 | 1.692873 |
if result != ERROR_SUCCESS:
raise ctypes.WinError(result)
return result | def RaiseIfNotErrorSuccess(result, func = None, arguments = ()) | Error checking for Win32 Registry API calls.
The function is assumed to return a Win32 error code. If the code is not
C{ERROR_SUCCESS} then a C{WindowsError} exception is raised. | 4.962661 | 5.391725 | 0.920422 |
@functools.wraps(fn)
def wrapper(*argv, **argd):
t_ansi = GuessStringType.t_ansi
t_unicode = GuessStringType.t_unicode
v_types = [ type(item) for item in argv ]
v_types.extend( [ type(value) for (key, value) in compat.iteritems(argd) ] )
if t_ansi in v_types:
argv = list(argv)
for index in compat.xrange(len(argv)):
if v_types[index] == t_ansi:
argv[index] = t_unicode(argv[index])
for key, value in argd.items():
if type(value) == t_ansi:
argd[key] = t_unicode(value)
return fn(*argv, **argd)
return wrapper | def MakeANSIVersion(fn) | Decorator that generates an ANSI version of a Unicode (wide) only API call.
@type fn: callable
@param fn: Unicode (wide) version of the API function to call. | 2.798136 | 2.809104 | 0.996095 |
".example - This is an example plugin for the command line debugger"
print "This is an example command."
print "%s.do(%r, %r):" % (__name__, self, arg)
print " last event", self.lastEvent
print " prefix", self.cmdprefix
print " arguments", self.split_tokens(arg) | def do(self, arg) | .example - This is an example plugin for the command line debugger | 11.9434 | 6.989578 | 1.708744 |
if process is None:
self.dwProcessId = None
self.__process = None
else:
self.__load_Process_class()
if not isinstance(process, Process):
msg = "Parent process must be a Process instance, "
msg += "got %s instead" % type(process)
raise TypeError(msg)
self.dwProcessId = process.get_pid()
self.__process = process | def set_process(self, process = None) | Manually set the parent Process object. Use with care!
@type process: L{Process}
@param process: (Optional) Process object. Use C{None} for no process. | 3.988331 | 4.068824 | 0.980217 |
if self.dwProcessId is None:
if self.__process is not None:
# Infinite loop if self.__process is None
self.dwProcessId = self.get_process().get_pid()
else:
try:
# I wish this had been implemented before Vista...
# XXX TODO find the real ntdll call under this api
hThread = self.get_handle(
win32.THREAD_QUERY_LIMITED_INFORMATION)
self.dwProcessId = win32.GetProcessIdOfThread(hThread)
except AttributeError:
# This method really sucks :P
self.dwProcessId = self.__get_pid_by_scanning()
return self.dwProcessId | def get_pid(self) | @rtype: int
@return: Parent process global ID.
@raise WindowsError: An error occured when calling a Win32 API function.
@raise RuntimeError: The parent process ID can't be found. | 6.375044 | 6.109527 | 1.04346 |
'Internally used by get_pid().'
dwProcessId = None
dwThreadId = self.get_tid()
with win32.CreateToolhelp32Snapshot(win32.TH32CS_SNAPTHREAD) as hSnapshot:
te = win32.Thread32First(hSnapshot)
while te is not None:
if te.th32ThreadID == dwThreadId:
dwProcessId = te.th32OwnerProcessID
break
te = win32.Thread32Next(hSnapshot)
if dwProcessId is None:
msg = "Cannot find thread ID %d in any process" % dwThreadId
raise RuntimeError(msg)
return dwProcessId | def __get_pid_by_scanning(self) | Internally used by get_pid(). | 2.870977 | 2.588083 | 1.109306 |
hThread = win32.OpenThread(dwDesiredAccess, win32.FALSE, self.dwThreadId)
# In case hThread was set to an actual handle value instead of a Handle
# object. This shouldn't happen unless the user tinkered with it.
if not hasattr(self.hThread, '__del__'):
self.close_handle()
self.hThread = hThread | def open_handle(self, dwDesiredAccess = win32.THREAD_ALL_ACCESS) | Opens a new handle to the thread, closing the previous one.
The new handle is stored in the L{hThread} property.
@warn: Normally you should call L{get_handle} instead, since it's much
"smarter" and tries to reuse handles and merge access rights.
@type dwDesiredAccess: int
@param dwDesiredAccess: Desired access rights.
Defaults to L{win32.THREAD_ALL_ACCESS}.
See: U{http://msdn.microsoft.com/en-us/library/windows/desktop/ms686769(v=vs.85).aspx}
@raise WindowsError: It's not possible to open a handle to the thread
with the requested access rights. This tipically happens because
the target thread belongs to system process and the debugger is not
runnning with administrative rights. | 5.395032 | 6.386814 | 0.844714 |
try:
if hasattr(self.hThread, 'close'):
self.hThread.close()
elif self.hThread not in (None, win32.INVALID_HANDLE_VALUE):
win32.CloseHandle(self.hThread)
finally:
self.hThread = None | def close_handle(self) | Closes the handle to the thread.
@note: Normally you don't need to call this method. All handles
created by I{WinAppDbg} are automatically closed when the garbage
collector claims them. | 2.660498 | 2.610134 | 1.019296 |
if self.hThread in (None, win32.INVALID_HANDLE_VALUE):
self.open_handle(dwDesiredAccess)
else:
dwAccess = self.hThread.dwAccess
if (dwAccess | dwDesiredAccess) != dwAccess:
self.open_handle(dwAccess | dwDesiredAccess)
return self.hThread | def get_handle(self, dwDesiredAccess = win32.THREAD_ALL_ACCESS) | Returns a handle to the thread with I{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.
@type dwDesiredAccess: int
@param dwDesiredAccess: Desired access rights.
See: U{http://msdn.microsoft.com/en-us/library/windows/desktop/ms686769(v=vs.85).aspx}
@rtype: ThreadHandle
@return: Handle to the thread.
@raise WindowsError: It's not possible to open a handle to the thread
with the requested access rights. This tipically happens because
the target thread belongs to system process and the debugger is not
runnning with administrative rights. | 2.902881 | 3.186027 | 0.911129 |
hThread = self.get_handle(win32.THREAD_TERMINATE)
win32.TerminateThread(hThread, dwExitCode)
# Ugliest hack ever, won't work if many pieces of code are injected.
# Seriously, what was I thinking? Lame! :(
if self.pInjectedMemory is not None:
try:
self.get_process().free(self.pInjectedMemory)
self.pInjectedMemory = None
except Exception:
## raise # XXX DEBUG
pass | def kill(self, dwExitCode = 0) | Terminates the thread execution.
@note: If the C{lpInjectedMemory} member contains a valid pointer,
the memory is freed.
@type dwExitCode: int
@param dwExitCode: (Optional) Thread exit code. | 8.280322 | 7.70827 | 1.074213 |
hThread = self.get_handle(win32.THREAD_SUSPEND_RESUME)
if self.is_wow64():
# FIXME this will be horribly slow on XP 64
# since it'll try to resolve a missing API every time
try:
return win32.Wow64SuspendThread(hThread)
except AttributeError:
pass
return win32.SuspendThread(hThread) | def suspend(self) | Suspends the thread execution.
@rtype: int
@return: Suspend count. If zero, the thread is running. | 5.528724 | 5.643402 | 0.979679 |
hThread = self.get_handle(win32.THREAD_SUSPEND_RESUME)
return win32.ResumeThread(hThread) | def resume(self) | Resumes the thread execution.
@rtype: int
@return: Suspend count. If zero, the thread is running. | 5.605873 | 4.793352 | 1.16951 |
# Some words on the "strange errors" that lead to the bSuspend
# parameter. Peter Van Eeckhoutte and I were working on a fix
# for some bugs he found in the 1.5 betas when we stumbled upon
# what seemed to be a deadlock in the debug API that caused the
# GetThreadContext() call never to return. Since removing the
# call to SuspendThread() solved the problem, and a few Google
# searches showed a handful of problems related to these two
# APIs and Wow64 environments, I decided to break compatibility.
#
# Here are some pages about the weird behavior of SuspendThread:
# http://zachsaw.blogspot.com.es/2010/11/wow64-bug-getthreadcontext-may-return.html
# http://stackoverflow.com/questions/3444190/windows-suspendthread-doesnt-getthreadcontext-fails
# Get the thread handle.
dwAccess = win32.THREAD_GET_CONTEXT
if bSuspend:
dwAccess = dwAccess | win32.THREAD_SUSPEND_RESUME
hThread = self.get_handle(dwAccess)
# Suspend the thread if requested.
if bSuspend:
try:
self.suspend()
except WindowsError:
# Threads can't be suspended when the exit process event
# arrives, but you can still get the context.
bSuspend = False
# If an exception is raised, make sure the thread execution is resumed.
try:
if win32.bits == self.get_bits():
# 64 bit debugger attached to 64 bit process, or
# 32 bit debugger attached to 32 bit process.
ctx = win32.GetThreadContext(hThread,
ContextFlags = ContextFlags)
else:
if self.is_wow64():
# 64 bit debugger attached to 32 bit process.
if ContextFlags is not None:
ContextFlags &= ~win32.ContextArchMask
ContextFlags |= win32.WOW64_CONTEXT_i386
ctx = win32.Wow64GetThreadContext(hThread, ContextFlags)
else:
# 32 bit debugger attached to 64 bit process.
# XXX only i386/AMD64 is supported in this particular case
if win32.arch not in (win32.ARCH_I386, win32.ARCH_AMD64):
raise NotImplementedError()
if ContextFlags is not None:
ContextFlags &= ~win32.ContextArchMask
ContextFlags |= win32.context_amd64.CONTEXT_AMD64
ctx = win32.context_amd64.GetThreadContext(hThread,
ContextFlags = ContextFlags)
finally:
# Resume the thread if we suspended it.
if bSuspend:
self.resume()
# Return the context.
return ctx | def get_context(self, ContextFlags = None, bSuspend = False) | Retrieves the execution context (i.e. the registers values) for this
thread.
@type ContextFlags: int
@param ContextFlags: Optional, specify which registers to retrieve.
Defaults to C{win32.CONTEXT_ALL} which retrieves all registes
for the current platform.
@type bSuspend: bool
@param bSuspend: C{True} to automatically suspend the thread before
getting its context, C{False} otherwise.
Defaults to C{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.
@rtype: dict( str S{->} int )
@return: Dictionary mapping register names to their values.
@see: L{set_context} | 5.052615 | 5.020725 | 1.006352 |
# Get the thread handle.
dwAccess = win32.THREAD_SET_CONTEXT
if bSuspend:
dwAccess = dwAccess | win32.THREAD_SUSPEND_RESUME
hThread = self.get_handle(dwAccess)
# Suspend the thread if requested.
if bSuspend:
self.suspend()
# No fix for the exit process event bug.
# Setting the context of a dead thread is pointless anyway.
# Set the thread context.
try:
if win32.bits == 64 and self.is_wow64():
win32.Wow64SetThreadContext(hThread, context)
else:
win32.SetThreadContext(hThread, context)
# Resume the thread if we suspended it.
finally:
if bSuspend:
self.resume() | def set_context(self, context, bSuspend = False) | Sets the values of the registers.
@see: L{get_context}
@type context: dict( str S{->} int )
@param context: Dictionary mapping register names to their values.
@type bSuspend: bool
@param bSuspend: C{True} to automatically suspend the thread before
setting its context, C{False} otherwise.
Defaults to C{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. | 3.728173 | 3.937723 | 0.946784 |
context = self.get_context()
context[register] = value
self.set_context(context) | def set_register(self, register, value) | Sets the value of a specific register.
@type register: str
@param register: Register name.
@rtype: int
@return: Register value. | 4.027259 | 5.632222 | 0.715039 |
try:
wow64 = self.__wow64
except AttributeError:
if (win32.bits == 32 and not win32.wow64):
wow64 = False
else:
wow64 = self.get_process().is_wow64()
self.__wow64 = wow64
return wow64 | def is_wow64(self) | Determines if the thread is running under WOW64.
@rtype: bool
@return:
C{True} if the thread is running under WOW64. That is, it belongs
to a 32-bit application running in a 64-bit Windows.
C{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.
@raise WindowsError: On error an exception is raised.
@see: U{http://msdn.microsoft.com/en-us/library/aa384249(VS.85).aspx} | 3.14844 | 3.366977 | 0.935094 |
try:
return self._teb_ptr
except AttributeError:
try:
hThread = self.get_handle(win32.THREAD_QUERY_INFORMATION)
tbi = win32.NtQueryInformationThread( hThread,
win32.ThreadBasicInformation)
address = tbi.TebBaseAddress
except WindowsError:
address = self.get_linear_address('SegFs', 0) # fs:[0]
if not address:
raise
self._teb_ptr = address
return address | def get_teb_address(self) | Returns a remote pointer to the TEB.
@rtype: int
@return: Remote pointer to the L{TEB} structure.
@raise WindowsError: An exception is raised on error. | 5.511821 | 4.983355 | 1.106046 |
hThread = self.get_handle(win32.THREAD_QUERY_INFORMATION)
selector = self.get_register(segment)
ldt = win32.GetThreadSelectorEntry(hThread, selector)
BaseLow = ldt.BaseLow
BaseMid = ldt.HighWord.Bytes.BaseMid << 16
BaseHi = ldt.HighWord.Bytes.BaseHi << 24
Base = BaseLow | BaseMid | BaseHi
LimitLow = ldt.LimitLow
LimitHi = ldt.HighWord.Bits.LimitHi << 16
Limit = LimitLow | LimitHi
if address > Limit:
msg = "Address %s too large for segment %s (selector %d)"
msg = msg % (HexDump.address(address, self.get_bits()),
segment, selector)
raise ValueError(msg)
return Base + address | def get_linear_address(self, segment, address) | Translates segment-relative addresses to linear addresses.
Linear addresses can be used to access a process memory,
calling L{Process.read} and L{Process.write}.
@type segment: str
@param segment: Segment register name.
@type address: int
@param address: Segment relative memory address.
@rtype: int
@return: Linear memory address.
@raise ValueError: Address is too large for selector.
@raise WindowsError:
The current architecture does not support selectors.
Selectors only exist in x86-based systems. | 4.466239 | 3.894897 | 1.14669 |
if win32.arch != win32.ARCH_I386:
raise NotImplementedError(
"SEH chain parsing is only supported in 32-bit Windows.")
process = self.get_process()
address = self.get_linear_address( 'SegFs', 0 )
return process.read_pointer( address ) | def get_seh_chain_pointer(self) | Get the pointer to the first structured exception handler block.
@rtype: int
@return: Remote pointer to the first block of the structured exception
handlers linked list. If the list is empty, the returned value is
C{0xFFFFFFFF}.
@raise NotImplementedError:
This method is only supported in 32 bits versions of Windows. | 6.718904 | 5.760048 | 1.166467 |
if win32.arch != win32.ARCH_I386:
raise NotImplementedError(
"SEH chain parsing is only supported in 32-bit Windows.")
process = self.get_process()
address = self.get_linear_address( 'SegFs', 0 )
process.write_pointer( address, value ) | def set_seh_chain_pointer(self, value) | Change the pointer to the first structured exception handler block.
@type value: int
@param value: Value of the remote pointer to the first block of the
structured exception handlers linked list. To disable SEH set the
value C{0xFFFFFFFF}.
@raise NotImplementedError:
This method is only supported in 32 bits versions of Windows. | 6.537397 | 5.886761 | 1.110525 |
seh_chain = list()
try:
process = self.get_process()
seh = self.get_seh_chain_pointer()
while seh != 0xFFFFFFFF:
seh_func = process.read_pointer( seh + 4 )
seh_chain.append( (seh, seh_func) )
seh = process.read_pointer( seh )
except WindowsError:
seh_chain.append( (seh, None) )
return seh_chain | def get_seh_chain(self) | @rtype: list of tuple( int, int )
@return: 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 B{next} block instead.
@raise NotImplementedError:
This method is only supported in 32 bits versions of Windows. | 2.91687 | 2.679642 | 1.08853 |
aProcess = self.get_process()
arch = aProcess.get_arch()
bits = aProcess.get_bits()
if arch == win32.ARCH_I386:
MachineType = win32.IMAGE_FILE_MACHINE_I386
elif arch == win32.ARCH_AMD64:
MachineType = win32.IMAGE_FILE_MACHINE_AMD64
elif arch == win32.ARCH_IA64:
MachineType = win32.IMAGE_FILE_MACHINE_IA64
else:
msg = "Stack walking is not available for this architecture: %s"
raise NotImplementedError(msg % arch)
hProcess = aProcess.get_handle( win32.PROCESS_VM_READ |
win32.PROCESS_QUERY_INFORMATION )
hThread = self.get_handle( win32.THREAD_GET_CONTEXT |
win32.THREAD_QUERY_INFORMATION )
StackFrame = win32.STACKFRAME64()
StackFrame.AddrPC = win32.ADDRESS64( self.get_pc() )
StackFrame.AddrFrame = win32.ADDRESS64( self.get_fp() )
StackFrame.AddrStack = win32.ADDRESS64( self.get_sp() )
trace = list()
while win32.StackWalk64(MachineType, hProcess, hThread, StackFrame):
if depth <= 0:
break
fp = StackFrame.AddrFrame.Offset
ra = aProcess.peek_pointer(fp + 4)
if ra == 0:
break
lib = aProcess.get_module_at_address(ra)
if lib is None:
lib = ""
else:
if lib.fileName:
lib = lib.fileName
else:
lib = "%s" % HexDump.address(lib.lpBaseOfDll, bits)
if bUseLabels:
label = aProcess.get_label_at_address(ra)
if bMakePretty:
label = '%s (%s)' % (HexDump.address(ra, bits), label)
trace.append( (fp, label) )
else:
trace.append( (fp, ra, lib) )
fp = aProcess.peek_pointer(fp)
return tuple(trace) | def __get_stack_trace(self, depth = 16, bUseLabels = True,
bMakePretty = True) | Tries to get a stack trace for the current function using the debug
helper API (dbghelp.dll).
@type depth: int
@param depth: Maximum depth of stack trace.
@type bUseLabels: bool
@param bUseLabels: C{True} to use labels, C{False} to use addresses.
@type bMakePretty: bool
@param bMakePretty:
C{True} for user readable labels,
C{False} for labels that can be passed to L{Process.resolve_label}.
"Pretty" labels look better when producing output for the user to
read, while pure labels are more useful programatically.
@rtype: tuple of tuple( int, int, str )
@return: Stack trace of the thread as a tuple of
( return address, frame pointer address, module filename )
when C{bUseLabels} is C{True}, or a tuple of
( return address, frame pointer label )
when C{bUseLabels} is C{False}.
@raise WindowsError: Raises an exception on error. | 2.652738 | 2.563813 | 1.034685 |
aProcess = self.get_process()
st, sb = self.get_stack_range() # top, bottom
fp = self.get_fp()
trace = list()
if aProcess.get_module_count() == 0:
aProcess.scan_modules()
bits = aProcess.get_bits()
while depth > 0:
if fp == 0:
break
if not st <= fp < sb:
break
ra = aProcess.peek_pointer(fp + 4)
if ra == 0:
break
lib = aProcess.get_module_at_address(ra)
if lib is None:
lib = ""
else:
if lib.fileName:
lib = lib.fileName
else:
lib = "%s" % HexDump.address(lib.lpBaseOfDll, bits)
if bUseLabels:
label = aProcess.get_label_at_address(ra)
if bMakePretty:
label = '%s (%s)' % (HexDump.address(ra, bits), label)
trace.append( (fp, label) )
else:
trace.append( (fp, ra, lib) )
fp = aProcess.peek_pointer(fp)
return tuple(trace) | def __get_stack_trace_manually(self, depth = 16, bUseLabels = True,
bMakePretty = True) | Tries to get a stack trace for the current function.
Only works for functions with standard prologue and epilogue.
@type depth: int
@param depth: Maximum depth of stack trace.
@type bUseLabels: bool
@param bUseLabels: C{True} to use labels, C{False} to use addresses.
@type bMakePretty: bool
@param bMakePretty:
C{True} for user readable labels,
C{False} for labels that can be passed to L{Process.resolve_label}.
"Pretty" labels look better when producing output for the user to
read, while pure labels are more useful programatically.
@rtype: tuple of tuple( int, int, str )
@return: Stack trace of the thread as a tuple of
( return address, frame pointer address, module filename )
when C{bUseLabels} is C{True}, or a tuple of
( return address, frame pointer label )
when C{bUseLabels} is C{False}.
@raise WindowsError: Raises an exception on error. | 3.68065 | 3.565056 | 1.032424 |
try:
trace = self.__get_stack_trace(depth, False)
except Exception:
import traceback
traceback.print_exc()
trace = ()
if not trace:
trace = self.__get_stack_trace_manually(depth, False)
return trace | def get_stack_trace(self, depth = 16) | Tries to get a stack trace for the current function.
Only works for functions with standard prologue and epilogue.
@type depth: int
@param depth: Maximum depth of stack trace.
@rtype: tuple of tuple( int, int, str )
@return: Stack trace of the thread as a tuple of
( return address, frame pointer address, module filename ).
@raise WindowsError: Raises an exception on error. | 3.93435 | 3.984827 | 0.987333 |
try:
trace = self.__get_stack_trace(depth, True, bMakePretty)
except Exception:
trace = ()
if not trace:
trace = self.__get_stack_trace_manually(depth, True, bMakePretty)
return trace | def get_stack_trace_with_labels(self, depth = 16, bMakePretty = True) | Tries to get a stack trace for the current function.
Only works for functions with standard prologue and epilogue.
@type depth: int
@param depth: Maximum depth of stack trace.
@type bMakePretty: bool
@param bMakePretty:
C{True} for user readable labels,
C{False} for labels that can be passed to L{Process.resolve_label}.
"Pretty" labels look better when producing output for the user to
read, while pure labels are more useful programatically.
@rtype: tuple of tuple( int, int, str )
@return: Stack trace of the thread as a tuple of
( return address, frame pointer label ).
@raise WindowsError: Raises an exception on error. | 3.404767 | 3.907794 | 0.871276 |
st, sb = self.get_stack_range() # top, bottom
sp = self.get_sp()
fp = self.get_fp()
size = fp - sp
if not st <= sp < sb:
raise RuntimeError('Stack pointer lies outside the stack')
if not st <= fp < sb:
raise RuntimeError('Frame pointer lies outside the stack')
if sp > fp:
raise RuntimeError('No valid stack frame found')
return (sp, fp) | def get_stack_frame_range(self) | Returns the starting and ending addresses of the stack frame.
Only works for functions with standard prologue and epilogue.
@rtype: tuple( int, int )
@return: Stack frame range.
May not be accurate, depending on the compiler used.
@raise RuntimeError: The stack frame is invalid,
or the function doesn't have a standard prologue
and epilogue.
@raise WindowsError: An error occured when getting the thread context. | 4.623396 | 4.734306 | 0.976573 |
sp, fp = self.get_stack_frame_range()
size = fp - sp
if max_size and size > max_size:
size = max_size
return self.get_process().peek(sp, size) | def get_stack_frame(self, max_size = None) | Reads the contents of the current stack frame.
Only works for functions with standard prologue and epilogue.
@type max_size: int
@param max_size: (Optional) Maximum amount of bytes to read.
@rtype: str
@return: Stack frame data.
May not be accurate, depending on the compiler used.
May return an empty string.
@raise RuntimeError: The stack frame is invalid,
or the function doesn't have a standard prologue
and epilogue.
@raise WindowsError: An error occured when getting the thread context
or reading data from the process memory. | 5.144859 | 5.989875 | 0.858926 |
aProcess = self.get_process()
return aProcess.read(self.get_sp() + offset, size) | def read_stack_data(self, size = 128, offset = 0) | Reads the contents of the top of the stack.
@type size: int
@param size: Number of bytes to read.
@type offset: int
@param offset: Offset from the stack pointer to begin reading.
@rtype: str
@return: Stack data.
@raise WindowsError: Could not read the requested data. | 7.34113 | 9.304505 | 0.788987 |
aProcess = self.get_process()
return aProcess.peek(self.get_sp() + offset, size) | def peek_stack_data(self, size = 128, offset = 0) | Tries to read the contents of the top of the stack.
@type size: int
@param size: Number of bytes to read.
@type offset: int
@param offset: Offset from the stack pointer to begin reading.
@rtype: str
@return: Stack data.
Returned data may be less than the requested size. | 7.350995 | 10.784776 | 0.681608 |
if count > 0:
stackData = self.read_stack_data(count * 4, offset)
return struct.unpack('<'+('L'*count), stackData)
return () | def read_stack_dwords(self, count, offset = 0) | Reads DWORDs from the top of the stack.
@type count: int
@param count: Number of DWORDs to read.
@type offset: int
@param offset: Offset from the stack pointer to begin reading.
@rtype: tuple( int... )
@return: Tuple of integers read from the stack.
@raise WindowsError: Could not read the requested data. | 4.130292 | 5.859174 | 0.704927 |
stackData = self.peek_stack_data(count * 4, offset)
if len(stackData) & 3:
stackData = stackData[:-len(stackData) & 3]
if not stackData:
return ()
return struct.unpack('<'+('L'*count), stackData) | def peek_stack_dwords(self, count, offset = 0) | Tries to read DWORDs from the top of the stack.
@type count: int
@param count: Number of DWORDs to read.
@type offset: int
@param offset: Offset from the stack pointer to begin reading.
@rtype: tuple( int... )
@return: Tuple of integers read from the stack.
May be less than the requested number of DWORDs. | 3.22303 | 3.926586 | 0.820822 |
stackData = self.read_stack_data(count * 8, offset)
return struct.unpack('<'+('Q'*count), stackData) | def read_stack_qwords(self, count, offset = 0) | Reads QWORDs from the top of the stack.
@type count: int
@param count: Number of QWORDs to read.
@type offset: int
@param offset: Offset from the stack pointer to begin reading.
@rtype: tuple( int... )
@return: Tuple of integers read from the stack.
@raise WindowsError: Could not read the requested data. | 4.34023 | 6.904527 | 0.628606 |
aProcess = self.get_process()
stackData = aProcess.read_structure(self.get_sp() + offset, structure)
return tuple([ stackData.__getattribute__(name)
for (name, type) in stackData._fields_ ]) | def read_stack_structure(self, structure, offset = 0) | Reads the given structure at the top of the stack.
@type structure: ctypes.Structure
@param structure: Structure of the data to read from the stack.
@type offset: int
@param offset: Offset from the stack pointer to begin reading.
The stack pointer is the same returned by the L{get_sp} method.
@rtype: tuple
@return: Tuple of elements read from the stack. The type of each
element matches the types in the stack frame structure. | 8.167257 | 6.084177 | 1.342377 |
aProcess = self.get_process()
stackData = aProcess.read_structure(self.get_fp() + offset, structure)
return tuple([ stackData.__getattribute__(name)
for (name, type) in stackData._fields_ ]) | def read_stack_frame(self, structure, offset = 0) | Reads the stack frame of the thread.
@type structure: ctypes.Structure
@param structure: Structure of the stack frame.
@type offset: int
@param offset: Offset from the frame pointer to begin reading.
The frame pointer is the same returned by the L{get_fp} method.
@rtype: tuple
@return: Tuple of elements read from the stack frame. The type of each
element matches the types in the stack frame structure. | 7.62001 | 5.931397 | 1.284691 |
return self.get_process().read(self.get_pc() + offset, size) | def read_code_bytes(self, size = 128, offset = 0) | Tries to read some bytes of the code currently being executed.
@type size: int
@param size: Number of bytes to read.
@type offset: int
@param offset: Offset from the program counter to begin reading.
@rtype: str
@return: Bytes read from the process memory.
@raise WindowsError: Could not read the requested data. | 7.761797 | 9.207753 | 0.842963 |
return self.get_process().peek(self.get_pc() + offset, size) | def peek_code_bytes(self, size = 128, offset = 0) | Tries to read some bytes of the code currently being executed.
@type size: int
@param size: Number of bytes to read.
@type offset: int
@param offset: Offset from the program counter to begin reading.
@rtype: str
@return: Bytes read from the process memory.
May be less than the requested number of bytes. | 7.862465 | 9.058769 | 0.86794 |
peekable_registers = (
'Eax', 'Ebx', 'Ecx', 'Edx', 'Esi', 'Edi', 'Ebp'
)
if not context:
context = self.get_context(win32.CONTEXT_CONTROL | \
win32.CONTEXT_INTEGER)
aProcess = self.get_process()
data = dict()
for (reg_name, reg_value) in compat.iteritems(context):
if reg_name not in peekable_registers:
continue
## if reg_name == 'Ebp':
## stack_begin, stack_end = self.get_stack_range()
## print hex(stack_end), hex(reg_value), hex(stack_begin)
## if stack_begin and stack_end and stack_end < stack_begin and \
## stack_begin <= reg_value <= stack_end:
## continue
reg_data = aProcess.peek(reg_value, peekSize)
if reg_data:
data[reg_name] = reg_data
return data | def peek_pointers_in_registers(self, peekSize = 16, context = None) | Tries to guess which values in the registers are valid pointers,
and reads some data from them.
@type peekSize: int
@param peekSize: Number of bytes to read from each pointer found.
@type context: dict( str S{->} int )
@param context: (Optional)
Dictionary mapping register names to their values.
If not given, the current thread context will be used.
@rtype: dict( str S{->} str )
@return: Dictionary mapping register names to the data they point to. | 3.264289 | 3.590959 | 0.90903 |
aProcess = self.get_process()
return aProcess.peek_pointers_in_data(data, peekSize, peekStep) | def peek_pointers_in_data(self, data, peekSize = 16, peekStep = 1) | Tries to guess which values in the given data are valid pointers,
and reads some data from them.
@type data: str
@param data: Binary data to find pointers in.
@type peekSize: int
@param peekSize: Number of bytes to read from each pointer found.
@type peekStep: int
@param peekStep: Expected data alignment.
Tipically you specify 1 when data alignment is unknown,
or 4 when you expect data to be DWORD aligned.
Any other value may be specified.
@rtype: dict( str S{->} str )
@return: Dictionary mapping stack offsets to the data they point to. | 3.859207 | 5.681708 | 0.679234 |
aProcess = self.get_process()
return aProcess.disassemble_string(lpAddress, code) | def disassemble_string(self, lpAddress, code) | Disassemble instructions from a block of binary code.
@type lpAddress: int
@param lpAddress: Memory address where the code was read from.
@type code: str
@param code: Binary code to disassemble.
@rtype: list of tuple( long, int, str, str )
@return: 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. | 4.784173 | 8.384483 | 0.570598 |
aProcess = self.get_process()
return aProcess.disassemble(lpAddress, dwSize) | def disassemble(self, lpAddress, dwSize) | Disassemble instructions from the address space of the process.
@type lpAddress: int
@param lpAddress: Memory address where to read the code from.
@type dwSize: int
@param dwSize: Size of binary code to disassemble.
@rtype: list of tuple( long, int, str, str )
@return: 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. | 5.048124 | 8.036033 | 0.628186 |
aProcess = self.get_process()
return aProcess.disassemble_around(lpAddress, dwSize) | def disassemble_around(self, lpAddress, dwSize = 64) | Disassemble around the given address.
@type lpAddress: int
@param lpAddress: Memory address where to read the code from.
@type dwSize: int
@param dwSize: Delta offset.
Code will be read from lpAddress - dwSize to lpAddress + dwSize.
@rtype: list of tuple( long, int, str, str )
@return: 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. | 4.337473 | 7.236527 | 0.599386 |
aProcess = self.get_process()
return aProcess.disassemble_around(self.get_pc(), dwSize) | def disassemble_around_pc(self, dwSize = 64) | Disassemble around the program counter of the given thread.
@type dwSize: int
@param dwSize: Delta offset.
Code will be read from pc - dwSize to pc + dwSize.
@rtype: list of tuple( long, int, str, str )
@return: 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. | 4.8012 | 7.815172 | 0.614343 |
self.__initialize_snapshot()
if dwThreadId not in self.__threadDict:
msg = "Unknown thread ID: %d" % dwThreadId
raise KeyError(msg)
return self.__threadDict[dwThreadId] | def get_thread(self, dwThreadId) | @type dwThreadId: int
@param dwThreadId: Global ID of the thread to look for.
@rtype: L{Thread}
@return: Thread object with the given global ID. | 4.019858 | 4.291445 | 0.936714 |
found_threads = list()
# Find threads with no name.
if name is None:
for aThread in self.iter_threads():
if aThread.get_name() is None:
found_threads.append(aThread)
# Find threads matching the given name exactly.
elif bExactMatch:
for aThread in self.iter_threads():
if aThread.get_name() == name:
found_threads.append(aThread)
# Find threads whose names match the given substring.
else:
for aThread in self.iter_threads():
t_name = aThread.get_name()
if t_name is not None and name in t_name:
found_threads.append(aThread)
return found_threads | def find_threads_by_name(self, name, bExactMatch = True) | Find threads by name, using different search methods.
@type name: str, None
@param name: Name to look for. Use C{None} to find nameless threads.
@type bExactMatch: bool
@param bExactMatch: C{True} if the name must be
B{exactly} as given, C{False} if the name can be
loosely matched.
This parameter is ignored when C{name} is C{None}.
@rtype: list( L{Thread} )
@return: All threads matching the given name. | 1.916378 | 2.062699 | 0.929064 |
if bSuspended:
dwCreationFlags = win32.CREATE_SUSPENDED
else:
dwCreationFlags = 0
hProcess = self.get_handle( win32.PROCESS_CREATE_THREAD |
win32.PROCESS_QUERY_INFORMATION |
win32.PROCESS_VM_OPERATION |
win32.PROCESS_VM_WRITE |
win32.PROCESS_VM_READ )
hThread, dwThreadId = win32.CreateRemoteThread(
hProcess, 0, 0, lpStartAddress, lpParameter, dwCreationFlags)
aThread = Thread(dwThreadId, hThread, self)
self._add_thread(aThread)
return aThread | def start_thread(self, lpStartAddress, lpParameter=0, bSuspended = False) | Remotely creates a new thread in the process.
@type lpStartAddress: int
@param lpStartAddress: Start address for the new thread.
@type lpParameter: int
@param lpParameter: Optional argument for the new thread.
@type bSuspended: bool
@param bSuspended: C{True} if the new thread should be suspended.
In that case use L{Thread.resume} to start execution. | 2.39987 | 2.740232 | 0.875791 |
# Ignore special process IDs.
# PID 0: System Idle Process. Also has a special meaning to the
# toolhelp APIs (current process).
# PID 4: System Integrity Group. See this forum post for more info:
# http://tinyurl.com/ycza8jo
# (points to social.technet.microsoft.com)
# Only on XP and above
# PID 8: System (?) only in Windows 2000 and below AFAIK.
# It's probably the same as PID 4 in XP and above.
dwProcessId = self.get_pid()
if dwProcessId in (0, 4, 8):
return
## dead_tids = set( self.get_thread_ids() ) # XXX triggers a scan
dead_tids = self._get_thread_ids()
dwProcessId = self.get_pid()
hSnapshot = win32.CreateToolhelp32Snapshot(win32.TH32CS_SNAPTHREAD,
dwProcessId)
try:
te = win32.Thread32First(hSnapshot)
while te is not None:
if te.th32OwnerProcessID == dwProcessId:
dwThreadId = te.th32ThreadID
if dwThreadId in dead_tids:
dead_tids.remove(dwThreadId)
## if not self.has_thread(dwThreadId): # XXX triggers a scan
if not self._has_thread_id(dwThreadId):
aThread = Thread(dwThreadId, process = self)
self._add_thread(aThread)
te = win32.Thread32Next(hSnapshot)
finally:
win32.CloseHandle(hSnapshot)
for tid in dead_tids:
self._del_thread(tid) | def scan_threads(self) | Populates the snapshot with running threads. | 4.423561 | 4.353222 | 1.016158 |
for tid in self.get_thread_ids():
aThread = self.get_thread(tid)
if not aThread.is_alive():
self._del_thread(aThread) | def clear_dead_threads(self) | Remove Thread objects from the snapshot
referring to threads no longer running. | 3.607291 | 3.268841 | 1.103538 |
for aThread in compat.itervalues(self.__threadDict):
aThread.clear()
self.__threadDict = dict() | def clear_threads(self) | Clears the threads snapshot. | 7.880703 | 7.04373 | 1.118825 |
for aThread in self.iter_threads():
try:
aThread.close_handle()
except Exception:
try:
e = sys.exc_info()[1]
msg = "Cannot close thread handle %s, reason: %s"
msg %= (aThread.hThread.value, str(e))
warnings.warn(msg)
except Exception:
pass | def close_thread_handles(self) | Closes all open handles to threads in the snapshot. | 3.383332 | 3.226575 | 1.048583 |
## if not isinstance(aThread, Thread):
## if hasattr(aThread, '__class__'):
## typename = aThread.__class__.__name__
## else:
## typename = str(type(aThread))
## msg = "Expected Thread, got %s instead" % typename
## raise TypeError(msg)
dwThreadId = aThread.dwThreadId
## if dwThreadId in self.__threadDict:
## msg = "Already have a Thread object with ID %d" % dwThreadId
## raise KeyError(msg)
aThread.set_process(self)
self.__threadDict[dwThreadId] = aThread | def _add_thread(self, aThread) | Private method to add a thread object to the snapshot.
@type aThread: L{Thread}
@param aThread: Thread object. | 2.463362 | 2.634233 | 0.935134 |
try:
aThread = self.__threadDict[dwThreadId]
del self.__threadDict[dwThreadId]
except KeyError:
aThread = None
msg = "Unknown thread ID %d" % dwThreadId
warnings.warn(msg, RuntimeWarning)
if aThread:
aThread.clear() | def _del_thread(self, dwThreadId) | Private method to remove a thread object from the snapshot.
@type dwThreadId: int
@param dwThreadId: Global thread ID. | 3.151567 | 3.305398 | 0.95346 |
dwThreadId = event.get_tid()
hThread = event.get_thread_handle()
## if not self.has_thread(dwThreadId): # XXX this would trigger a scan
if not self._has_thread_id(dwThreadId):
aThread = Thread(dwThreadId, hThread, self)
teb_ptr = event.get_teb() # remember the TEB pointer
if teb_ptr:
aThread._teb_ptr = teb_ptr
self._add_thread(aThread) | def __add_created_thread(self, event) | Private method to automatically add new thread objects from debug events.
@type event: L{Event}
@param event: Event object. | 4.937882 | 5.347756 | 0.923356 |
dwThreadId = event.get_tid()
## if self.has_thread(dwThreadId): # XXX this would trigger a scan
if self._has_thread_id(dwThreadId):
self._del_thread(dwThreadId)
return True | def _notify_exit_thread(self, event) | Notify the termination of a thread.
This is done automatically by the L{Debug} class, you shouldn't need
to call it yourself.
@type event: L{ExitThreadEvent}
@param event: Exit thread event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} otherwise. | 7.512145 | 9.155831 | 0.820477 |
orig_value = getattr(original_code, attribute_name)
insert_value = getattr(insert_code, attribute_name)
orig_names_len = len(orig_value)
code_with_new_values = list(insert_code_list)
offset = 0
while offset < len(code_with_new_values):
op = code_with_new_values[offset]
if op in op_list:
new_val = code_with_new_values[offset + 1] + orig_names_len
if new_val > MAX_BYTE:
code_with_new_values[offset + 1] = new_val & MAX_BYTE
code_with_new_values = code_with_new_values[:offset] + [EXTENDED_ARG, new_val >> 8] + \
code_with_new_values[offset:]
offset += 2
else:
code_with_new_values[offset + 1] = new_val
offset += 2
new_values = orig_value + insert_value
return bytes(code_with_new_values), new_values | def _add_attr_values_from_insert_to_original(original_code, insert_code, insert_code_list, attribute_name, op_list) | This function appends values of the attribute `attribute_name` of the inserted code to the original values,
and changes indexes inside inserted code. If some bytecode instruction in the inserted code used to call argument
number i, after modification it calls argument n + i, where n - length of the values in the original code.
So it helps to avoid variables mixing between two pieces of code.
:param original_code: code to modify
:param insert_code: code to insert
:param insert_code_obj: bytes sequence of inserted code, which should be modified too
:param attribute_name: name of attribute to modify ('co_names', 'co_consts' or 'co_varnames')
:param op_list: sequence of bytecodes whose arguments should be changed
:return: modified bytes sequence of the code to insert and new values of the attribute `attribute_name` for
original code | 2.265712 | 2.121963 | 1.067744 |
# There's a nice overview of co_lnotab in
# https://github.com/python/cpython/blob/3.6/Objects/lnotab_notes.txt
new_list = list(code_to_modify.co_lnotab)
if not new_list:
# Could happen on a lambda (in this case, a breakpoint in the lambda should fallback to
# tracing).
return None
# As all numbers are relative, what we want is to hide the code we inserted in the previous line
# (it should be the last thing right before we increment the line so that we have a line event
# right after the inserted code).
bytecode_delta = len(code_to_insert)
byte_increments = code_to_modify.co_lnotab[0::2]
line_increments = code_to_modify.co_lnotab[1::2]
if offset == 0:
new_list[0] += bytecode_delta
else:
addr = 0
it = zip(byte_increments, line_increments)
for i, (byte_incr, _line_incr) in enumerate(it):
addr += byte_incr
if addr == offset:
new_list[i * 2] += bytecode_delta
break
return bytes(new_list) | def _modify_new_lines(code_to_modify, offset, code_to_insert) | Update new lines: the bytecode inserted should be the last instruction of the previous line.
:return: bytes sequence of code with updated lines offsets | 4.993622 | 4.962952 | 1.00618 |
extended_arg = 0
for i in range(0, len(code), 2):
op = code[i]
if op >= HAVE_ARGUMENT:
if not extended_arg:
# in case if we added EXTENDED_ARG, but haven't inserted it to the source code yet.
for code_index in range(current_index, len(inserted_code_list)):
inserted_offset, inserted_code = inserted_code_list[code_index]
if inserted_offset == i and inserted_code[0] == EXTENDED_ARG:
extended_arg = inserted_code[1] << 8
arg = code[i + 1] | extended_arg
extended_arg = (arg << 8) if op == EXTENDED_ARG else 0
else:
arg = None
yield (i, op, arg) | def _unpack_opargs(code, inserted_code_list, current_index) | Modified version of `_unpack_opargs` function from module `dis`.
We have to use it, because sometimes code can be in an inconsistent state: if EXTENDED_ARG
operator was introduced into the code, but it hasn't been inserted into `code_list` yet.
In this case we can't use standard `_unpack_opargs` and we should check whether there are
some new operators in `inserted_code_list`. | 3.262449 | 2.881644 | 1.132149 |
inserted_code = list()
# the list with all inserted pieces of code
inserted_code.append((breakpoint_offset, breakpoint_code_list))
code_list = list(code_obj)
j = 0
while j < len(inserted_code):
current_offset, current_code_list = inserted_code[j]
offsets_for_modification = []
for offset, op, arg in _unpack_opargs(code_list, inserted_code, j):
if arg is not None:
if op in dis.hasjrel:
# has relative jump target
label = offset + 2 + arg
if offset < current_offset < label:
# change labels for relative jump targets if code was inserted inside
offsets_for_modification.append(offset)
elif op in dis.hasjabs:
# change label for absolute jump if code was inserted before it
if current_offset < arg:
offsets_for_modification.append(offset)
for i in range(0, len(code_list), 2):
op = code_list[i]
if i in offsets_for_modification and op >= dis.HAVE_ARGUMENT:
new_arg = code_list[i + 1] + len(current_code_list)
if new_arg <= MAX_BYTE:
code_list[i + 1] = new_arg
else:
# handle bytes overflow
if i - 2 > 0 and code_list[i - 2] == EXTENDED_ARG and code_list[i - 1] < MAX_BYTE:
# if new argument > 255 and EXTENDED_ARG already exists we need to increase it's argument
code_list[i - 1] += 1
else:
# if there isn't EXTENDED_ARG operator yet we have to insert the new operator
extended_arg_code = [EXTENDED_ARG, new_arg >> 8]
inserted_code.append((i, extended_arg_code))
code_list[i + 1] = new_arg & MAX_BYTE
code_list = code_list[:current_offset] + current_code_list + code_list[current_offset:]
for k in range(len(inserted_code)):
offset, inserted_code_list = inserted_code[k]
if current_offset < offset:
inserted_code[k] = (offset + len(current_code_list), inserted_code_list)
j += 1
return bytes(code_list), inserted_code | def _update_label_offsets(code_obj, breakpoint_offset, breakpoint_code_list) | Update labels for the relative and absolute jump targets
:param code_obj: code to modify
:param breakpoint_offset: offset for the inserted code
:param breakpoint_code_list: size of the inserted code
:return: bytes sequence with modified labels; list of tuples (resulting offset, list of code instructions) with
information about all inserted pieces of code | 3.251684 | 3.141782 | 1.034981 |
extended_arg_list = []
if jump_arg > MAX_BYTE:
extended_arg_list += [EXTENDED_ARG, jump_arg >> 8]
jump_arg = jump_arg & MAX_BYTE
# remove 'RETURN_VALUE' instruction and add 'POP_JUMP_IF_TRUE' with (if needed) 'EXTENDED_ARG'
return list(code_to_insert.co_code[:-RETURN_VALUE_SIZE]) + extended_arg_list + [opmap['POP_JUMP_IF_TRUE'], jump_arg] | def add_jump_instruction(jump_arg, code_to_insert) | Note: although it's adding a POP_JUMP_IF_TRUE, it's actually no longer used now
(we could only return the return and possibly the load of the 'None' before the
return -- not done yet because it needs work to fix all related tests). | 4.485371 | 4.062 | 1.104227 |
'''
:param all_lines_with_breaks:
tuple(int) a tuple with all the breaks in the given code object (this method is expected
to be called multiple times with different lines to add multiple breakpoints, so, the
variable `before_line` should have the current breakpoint an the all_lines_with_breaks
should have all the breakpoints added so far (including the `before_line`).
'''
if not all_lines_with_breaks:
# Backward-compatibility with signature which received only one line.
all_lines_with_breaks = (before_line,)
# The cache is needed for generator functions, because after each yield a new frame
# is created but the former code object is used (so, check if code_to_modify is
# already there and if not cache based on the new code generated).
# print('inserting code', before_line, all_lines_with_breaks)
# dis.dis(code_to_modify)
ok_and_new_code = _created.get((code_to_modify, all_lines_with_breaks))
if ok_and_new_code is not None:
return ok_and_new_code
ok, new_code = _insert_code(code_to_modify, code_to_insert, before_line)
# print('insert code ok', ok)
# dis.dis(new_code)
# Note: caching with new code!
cache_key = new_code, all_lines_with_breaks
_created[cache_key] = (ok, new_code)
return _created[cache_key] | def insert_code(code_to_modify, code_to_insert, before_line, all_lines_with_breaks=()) | :param all_lines_with_breaks:
tuple(int) a tuple with all the breaks in the given code object (this method is expected
to be called multiple times with different lines to add multiple breakpoints, so, the
variable `before_line` should have the current breakpoint an the all_lines_with_breaks
should have all the breakpoints added so far (including the `before_line`). | 5.164474 | 3.141388 | 1.64401 |
linestarts = dict(dis.findlinestarts(code_to_modify))
if not linestarts:
return False, code_to_modify
if code_to_modify.co_name == '<module>':
# There's a peculiarity here: if a breakpoint is added in the first line of a module, we
# can't replace the code because we require a line event to stop and the line event
# was already generated, so, fallback to tracing.
if before_line == min(linestarts.values()):
return False, code_to_modify
if before_line not in linestarts.values():
return False, code_to_modify
offset = None
for off, line_no in linestarts.items():
if line_no == before_line:
offset = off
break
code_to_insert_list = add_jump_instruction(offset, code_to_insert)
try:
code_to_insert_list, new_names = \
_add_attr_values_from_insert_to_original(code_to_modify, code_to_insert, code_to_insert_list, 'co_names',
dis.hasname)
code_to_insert_list, new_consts = \
_add_attr_values_from_insert_to_original(code_to_modify, code_to_insert, code_to_insert_list, 'co_consts',
[opmap['LOAD_CONST']])
code_to_insert_list, new_vars = \
_add_attr_values_from_insert_to_original(code_to_modify, code_to_insert, code_to_insert_list, 'co_varnames',
dis.haslocal)
new_bytes, all_inserted_code = _update_label_offsets(code_to_modify.co_code, offset, list(code_to_insert_list))
new_lnotab = _modify_new_lines(code_to_modify, offset, code_to_insert_list)
if new_lnotab is None:
return False, code_to_modify
except ValueError:
pydev_log.exception()
return False, code_to_modify
new_code = CodeType(
code_to_modify.co_argcount, # integer
code_to_modify.co_kwonlyargcount, # integer
len(new_vars), # integer
code_to_modify.co_stacksize, # integer
code_to_modify.co_flags, # integer
new_bytes, # bytes
new_consts, # tuple
new_names, # tuple
new_vars, # tuple
code_to_modify.co_filename, # string
code_to_modify.co_name, # string
code_to_modify.co_firstlineno, # integer
new_lnotab, # bytes
code_to_modify.co_freevars, # tuple
code_to_modify.co_cellvars # tuple
)
return True, new_code | def _insert_code(code_to_modify, code_to_insert, before_line) | Insert piece of code `code_to_insert` to `code_to_modify` right inside the line `before_line` before the
instruction on this line by modifying original bytecode
:param code_to_modify: Code to modify
:param code_to_insert: Code to insert
:param before_line: Number of line for code insertion
:return: boolean flag whether insertion was successful, modified code | 2.577377 | 2.548188 | 1.011455 |
"Internally used by get_pid() and get_tid()."
self.dwThreadId, self.dwProcessId = \
win32.GetWindowThreadProcessId(self.get_handle()) | def __get_pid_and_tid(self) | Internally used by get_pid() and get_tid(). | 7.303176 | 5.645186 | 1.2937 |
if thread is None:
self.__thread = None
else:
self.__load_Thread_class()
if not isinstance(thread, Thread):
msg = "Parent thread must be a Thread instance, "
msg += "got %s instead" % type(thread)
raise TypeError(msg)
self.dwThreadId = thread.get_tid()
self.__thread = thread | def set_thread(self, thread = None) | Manually set the thread process. Use with care!
@type thread: L{Thread}
@param thread: (Optional) Thread object. Use C{None} to autodetect. | 4.356902 | 4.670676 | 0.932821 |
window = Window(hWnd)
if window.get_pid() == self.get_pid():
window.set_process( self.get_process() )
if window.get_tid() == self.get_tid():
window.set_thread( self.get_thread() )
return window | def __get_window(self, hWnd) | User internally to get another Window from this one.
It'll try to copy the parent Process and Thread references if possible. | 2.675252 | 2.004148 | 1.334858 |
cr = win32.GetClientRect( self.get_handle() )
cr.left, cr.top = self.client_to_screen(cr.left, cr.top)
cr.right, cr.bottom = self.client_to_screen(cr.right, cr.bottom)
return cr | def get_client_rect(self) | Get the window's client area coordinates in the desktop.
@rtype: L{win32.Rect}
@return: Rectangle occupied by the window's client area in the desktop.
@raise WindowsError: An error occured while processing this request. | 2.827168 | 2.438085 | 1.159585 |
return tuple( win32.ClientToScreen( self.get_handle(), (x, y) ) ) | def client_to_screen(self, x, y) | Translates window client coordinates to screen coordinates.
@note: This is a simplified interface to some of the functionality of
the L{win32.Point} class.
@see: {win32.Point.client_to_screen}
@type x: int
@param x: Horizontal coordinate.
@type y: int
@param y: Vertical coordinate.
@rtype: tuple( int, int )
@return: Translated coordinates in a tuple (x, y).
@raise WindowsError: An error occured while processing this request. | 9.703301 | 8.660357 | 1.120427 |
return tuple( win32.ScreenToClient( self.get_handle(), (x, y) ) ) | def screen_to_client(self, x, y) | Translates window screen coordinates to client coordinates.
@note: This is a simplified interface to some of the functionality of
the L{win32.Point} class.
@see: {win32.Point.screen_to_client}
@type x: int
@param x: Horizontal coordinate.
@type y: int
@param y: Vertical coordinate.
@rtype: tuple( int, int )
@return: Translated coordinates in a tuple (x, y).
@raise WindowsError: An error occured while processing this request. | 8.756138 | 8.104836 | 1.08036 |
try:
if bAllowTransparency:
hWnd = win32.RealChildWindowFromPoint( self.get_handle(), (x, y) )
else:
hWnd = win32.ChildWindowFromPoint( self.get_handle(), (x, y) )
if hWnd:
return self.__get_window(hWnd)
except WindowsError:
pass
return None | def get_child_at(self, x, y, bAllowTransparency = True) | Get the child window located at the given coordinates. If no such
window exists an exception is raised.
@see: L{get_children}
@type x: int
@param x: Horizontal coordinate.
@type y: int
@param y: Vertical coordinate.
@type bAllowTransparency: bool
@param bAllowTransparency: If C{True} transparent areas in windows are
ignored, returning the window behind them. If C{False} transparent
areas are treated just like any other area.
@rtype: L{Window}
@return: Child window at the requested position, or C{None} if there
is no window at those coordinates. | 3.209399 | 3.409477 | 0.941317 |
if bAsync:
win32.ShowWindowAsync( self.get_handle(), win32.SW_SHOW )
else:
win32.ShowWindow( self.get_handle(), win32.SW_SHOW ) | def show(self, bAsync = True) | Make the window visible.
@see: L{hide}
@type bAsync: bool
@param bAsync: Perform the request asynchronously.
@raise WindowsError: An error occured while processing this request. | 2.339086 | 2.630045 | 0.889371 |
if bAsync:
win32.ShowWindowAsync( self.get_handle(), win32.SW_HIDE )
else:
win32.ShowWindow( self.get_handle(), win32.SW_HIDE ) | def hide(self, bAsync = True) | Make the window invisible.
@see: L{show}
@type bAsync: bool
@param bAsync: Perform the request asynchronously.
@raise WindowsError: An error occured while processing this request. | 2.425297 | 2.63748 | 0.919551 |
if bAsync:
win32.ShowWindowAsync( self.get_handle(), win32.SW_MAXIMIZE )
else:
win32.ShowWindow( self.get_handle(), win32.SW_MAXIMIZE ) | def maximize(self, bAsync = True) | Maximize the window.
@see: L{minimize}, L{restore}
@type bAsync: bool
@param bAsync: Perform the request asynchronously.
@raise WindowsError: An error occured while processing this request. | 2.386044 | 2.60469 | 0.916057 |
if bAsync:
win32.ShowWindowAsync( self.get_handle(), win32.SW_MINIMIZE )
else:
win32.ShowWindow( self.get_handle(), win32.SW_MINIMIZE ) | def minimize(self, bAsync = True) | Minimize the window.
@see: L{maximize}, L{restore}
@type bAsync: bool
@param bAsync: Perform the request asynchronously.
@raise WindowsError: An error occured while processing this request. | 2.396189 | 2.581246 | 0.928307 |
if bAsync:
win32.ShowWindowAsync( self.get_handle(), win32.SW_RESTORE )
else:
win32.ShowWindow( self.get_handle(), win32.SW_RESTORE ) | def restore(self, bAsync = True) | Unmaximize and unminimize the window.
@see: L{maximize}, L{minimize}
@type bAsync: bool
@param bAsync: Perform the request asynchronously.
@raise WindowsError: An error occured while processing this request. | 2.565284 | 2.68351 | 0.955943 |
if None in (x, y, width, height):
rect = self.get_screen_rect()
if x is None:
x = rect.left
if y is None:
y = rect.top
if width is None:
width = rect.right - rect.left
if height is None:
height = rect.bottom - rect.top
win32.MoveWindow(self.get_handle(), x, y, width, height, bRepaint) | def move(self, x = None, y = None, width = None, height = None,
bRepaint = True) | Moves and/or resizes the window.
@note: This is request is performed syncronously.
@type x: int
@param x: (Optional) New horizontal coordinate.
@type y: int
@param y: (Optional) New vertical coordinate.
@type width: int
@param width: (Optional) Desired window width.
@type height: int
@param height: (Optional) Desired window height.
@type bRepaint: bool
@param bRepaint:
(Optional) C{True} if the window should be redrawn afterwards.
@raise WindowsError: An error occured while processing this request. | 1.88374 | 2.27694 | 0.827312 |
if dwTimeout is None:
return win32.SendMessage(self.get_handle(), uMsg, wParam, lParam)
return win32.SendMessageTimeout(
self.get_handle(), uMsg, wParam, lParam,
win32.SMTO_ABORTIFHUNG | win32.SMTO_ERRORONEXIT, dwTimeout) | def send(self, uMsg, wParam = None, lParam = None, dwTimeout = None) | Send a low-level window message syncronically.
@type uMsg: int
@param uMsg: Message code.
@param wParam:
The type and meaning of this parameter depends on the message.
@param lParam:
The type and meaning of this parameter depends on the message.
@param dwTimeout: Optional timeout for the operation.
Use C{None} to wait indefinitely.
@rtype: int
@return: The meaning of the return value depends on the window message.
Typically a value of C{0} means an error occured. You can get the
error code by calling L{win32.GetLastError}. | 2.859851 | 2.903006 | 0.985134 |
win32.PostMessage(self.get_handle(), uMsg, wParam, lParam) | def post(self, uMsg, wParam = None, lParam = None) | Post a low-level window message asyncronically.
@type uMsg: int
@param uMsg: Message code.
@param wParam:
The type and meaning of this parameter depends on the message.
@param lParam:
The type and meaning of this parameter depends on the message.
@raise WindowsError: An error occured while sending the message. | 4.722255 | 6.978583 | 0.676678 |
'''
Processes a debug adapter protocol json command.
'''
DEBUG = False
try:
request = self.from_json(json_contents, update_ids_from_dap=True)
except KeyError as e:
request = self.from_json(json_contents, update_ids_from_dap=False)
error_msg = str(e)
if error_msg.startswith("'") and error_msg.endswith("'"):
error_msg = error_msg[1:-1]
# This means a failure updating ids from the DAP (the client sent a key we didn't send).
def on_request(py_db, request):
error_response = {
'type': 'response',
'request_seq': request.seq,
'success': False,
'command': request.command,
'message': error_msg,
}
return NetCommand(CMD_RETURN, 0, error_response, is_json=True)
else:
if DebugInfoHolder.DEBUG_RECORD_SOCKET_READS and DebugInfoHolder.DEBUG_TRACE_LEVEL >= 1:
pydev_log.info('Process %s: %s\n' % (
request.__class__.__name__, json.dumps(request.to_dict(), indent=4, sort_keys=True),))
assert request.type == 'request'
method_name = 'on_%s_request' % (request.command.lower(),)
on_request = getattr(self, method_name, None)
if on_request is None:
print('Unhandled: %s not available in _PyDevJsonCommandProcessor.\n' % (method_name,))
return
if DEBUG:
print('Handled in pydevd: %s (in _PyDevJsonCommandProcessor).\n' % (method_name,))
py_db._main_lock.acquire()
try:
cmd = on_request(py_db, request)
if cmd is not None:
py_db.writer.add_command(cmd)
finally:
py_db._main_lock.release() | def process_net_command_json(self, py_db, json_contents) | Processes a debug adapter protocol json command. | 4.193034 | 3.937702 | 1.064843 |
'''
:param ConfigurationDoneRequest request:
'''
self.api.run(py_db)
configuration_done_response = pydevd_base_schema.build_response(request)
return NetCommand(CMD_RETURN, 0, configuration_done_response, is_json=True) | def on_configurationdone_request(self, py_db, request) | :param ConfigurationDoneRequest request: | 8.812529 | 8.015187 | 1.099479 |
'''
:param ThreadsRequest request:
'''
return self.api.list_threads(py_db, request.seq) | def on_threads_request(self, py_db, request) | :param ThreadsRequest request: | 10.643572 | 7.895952 | 1.347978 |
'''
:param CompletionsRequest request:
'''
arguments = request.arguments # : :type arguments: CompletionsArguments
seq = request.seq
text = arguments.text
frame_id = arguments.frameId
thread_id = py_db.suspended_frames_manager.get_thread_id_for_variable_reference(
frame_id)
if thread_id is None:
body = CompletionsResponseBody([])
variables_response = pydevd_base_schema.build_response(
request,
kwargs={
'body': body,
'success': False,
'message': 'Thread to get completions seems to have resumed already.'
})
return NetCommand(CMD_RETURN, 0, variables_response, is_json=True)
# Note: line and column are 1-based (convert to 0-based for pydevd).
column = arguments.column - 1
if arguments.line is None:
# line is optional
line = -1
else:
line = arguments.line - 1
self.api.request_completions(py_db, seq, thread_id, frame_id, text, line=line, column=column) | def on_completions_request(self, py_db, request) | :param CompletionsRequest request: | 5.167008 | 5.089781 | 1.015173 |
'''
:param AttachRequest request:
'''
self.api.set_enable_thread_notifications(py_db, True)
self._set_debug_options(py_db, request.arguments.kwargs)
response = pydevd_base_schema.build_response(request)
return NetCommand(CMD_RETURN, 0, response, is_json=True) | def on_attach_request(self, py_db, request) | :param AttachRequest request: | 10.031368 | 8.969597 | 1.118374 |
'''
:param PauseRequest request:
'''
arguments = request.arguments # : :type arguments: PauseArguments
thread_id = arguments.threadId
self.api.request_suspend_thread(py_db, thread_id=thread_id)
response = pydevd_base_schema.build_response(request)
return NetCommand(CMD_RETURN, 0, response, is_json=True) | def on_pause_request(self, py_db, request) | :param PauseRequest request: | 7.862397 | 6.98273 | 1.125977 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.