code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if argv is None: argv = sys.argv try: # Exit on broken pipe. signal.signal(signal.SIGPIPE, signal.SIG_DFL) except AttributeError: # pragma: no cover # SIGPIPE is not available on Windows. pass try: args = parse_args(argv[1:], apply_config=apply_con...
def main(argv=None, apply_config=True)
Command-line entry.
3.742963
3.684962
1.01574
target = self.source[result['line'] - 1] offset = result['column'] - 1 fixed = target[:offset] + ' ' + target[offset:] # Only proceed if non-whitespace characters match. # And make sure we don't break the indentation. if ( fixed.replace(' ', '') == t...
def fix_e225(self, result)
Fix missing whitespace around operator.
4.116336
3.894979
1.056832
cr = '\n' # check comment line offset = result['line'] - 2 while True: if offset < 0: break line = self.source[offset].lstrip() if len(line) == 0: break if line[0] != '#': break ...
def fix_e305(self, result)
Add missing 2 blank lines after end of function or class.
3.63115
3.287778
1.104439
if ( not logical or len(logical[2]) == 1 or self.source[result['line'] - 1].lstrip().startswith('#') ): return self.fix_long_line_physically(result) start_line_index = logical[0][0] end_line_index = logical[1][0] logical_l...
def fix_long_line_logically(self, result, logical)
Try to make lines fit within --max-line-length characters.
2.61092
2.576464
1.013373
line_index = result['line'] - 1 target = self.source[line_index] previous_line = get_item(self.source, line_index - 1, default='') next_line = get_item(self.source, line_index + 1, default='') try: fixed = self.fix_long_line( target=target, ...
def fix_long_line_physically(self, result)
Try to make lines fit within --max-line-length characters.
2.948529
2.856308
1.032287
(line_index, offset, target) = get_index_offset_contents(result, self.source) # Handle very easy "not" special cases. if re.match(r'^\s*if [\w.]+ == False:$', target): self.source[line_index] = re.sub(r'if ([\...
def fix_e712(self, result)
Fix (trivial case of) comparison with boolean.
2.760069
2.656555
1.038965
(line_index, _, target) = get_index_offset_contents(result, self.source) match = COMPARE_NEGATIVE_REGEX.search(target) if match: if match.group(3) == 'in': pos_start = match.start(1) ...
def fix_e713(self, result)
Fix (trivial case of) non-membership check.
5.002427
4.783921
1.045675
(line_index, _, target) = get_index_offset_contents(result, self.source) if BARE_EXCEPT_REGEX.search(target): self.source[line_index] = '{0}{1}'.format( target[:result['column'] - 1], "except Exception:")
def fix_e722(self, result)
fix bare except
12.816359
9.404444
1.362798
self._delete_whitespace() if self.fits_on_current_line(item.size): return last_space = None for item in reversed(self._lines): if ( last_space and (not isinstance(item, Atom) or not item.is_colon) ): ...
def _split_after_delimiter(self, item, indent_amt)
Split the line only after a delimiter.
4.426615
4.291894
1.03139
console = InteractiveConsole(local) if readfunc is not None: console.raw_input = readfunc else: try: import readline except ImportError: pass console.interact(banner)
def interact(banner=None, readfunc=None, local=None)
Closely emulate the interactive Python interpreter. This is a backwards compatible interface to the InteractiveConsole class. When readfunc is not specified, it attempts to import the readline module to enable GNU readline if it is available. Arguments (all optional, all default to None): banner...
3.248326
2.956113
1.09885
try: code = self.compile(source, filename, symbol) except (OverflowError, SyntaxError, ValueError): # Case 1 self.showsyntaxerror(filename) return False if code is None: # Case 2 return True # Case 3 ...
def runsource(self, source, filename="<input>", symbol="single")
Compile and run some source in the interpreter. Arguments are as for compile_command(). One several things can happen: 1) The input is incorrect; compile_command() raised an exception (SyntaxError or OverflowError). A syntax traceback will be printed by calling the showsyntax...
2.697362
2.429712
1.110157
try: exec code in self.locals except SystemExit: raise except: self.showtraceback() else: if softspace(sys.stdout, 0): sys.stdout.write('\n')
def runcode(self, code)
Execute a code object. When an exception occurs, self.showtraceback() is called to display a traceback. All exceptions are caught except SystemExit, which is reraised. A note about KeyboardInterrupt: this exception may occur elsewhere in this code, and may not always be caught...
3.650519
3.635496
1.004132
type, value, sys.last_traceback = sys.exc_info() sys.last_type = type sys.last_value = value if filename and type is SyntaxError: # Work hard to stuff the correct filename in the exception try: msg, (dummy_filename, lineno, offset, line) =...
def showsyntaxerror(self, filename=None)
Display the syntax error that just occurred. This doesn't display a stack trace because there isn't one. If a filename is given, it is stuffed in the exception instead of what was there before (because Python's parser always uses "<string>" when reading from a string). The out...
3.18455
3.149764
1.011044
try: type, value, tb = sys.exc_info() sys.last_type = type sys.last_value = value sys.last_traceback = tb tblist = traceback.extract_tb(tb) del tblist[:1] list = traceback.format_list(tblist) if list: ...
def showtraceback(self, *args, **kwargs)
Display the exception that just occurred. We remove the first stack item because it is our own code. The output is written by self.write(), below.
2.348095
2.334422
1.005857
try: sys.ps1 #@UndefinedVariable except AttributeError: sys.ps1 = ">>> " try: sys.ps2 #@UndefinedVariable except AttributeError: sys.ps2 = "... " cprt = 'Type "help", "copyright", "credits" or "license" for more information...
def interact(self, banner=None)
Closely emulate the interactive Python console. The optional banner argument specify the banner to print before the first interaction; by default it prints a banner similar to the one printed by the real Python interpreter, followed by the current class name in parentheses (so as not ...
1.952135
1.964046
0.993935
self.buffer.append(line) source = "\n".join(self.buffer) more = self.runsource(source, self.filename) if not more: self.resetbuffer() return more
def push(self, line)
Push a line to the interpreter. The line should not have a trailing newline; it may have internal newlines. The line is appended to a buffer and the interpreter's runsource() method is called with the concatenated contents of the buffer as source. If this indicates that the co...
4.159332
3.076838
1.35182
# On PyDev we just output the string, there are scroll bars in the console # to handle "paging". This is the same behaviour as when TERM==dump (see # page.py) # for compatibility with mime-bundle form: if isinstance(strng, dict): strng = strng.get('text/plain', strng) print(strng)
def show_in_pager(self, strng, *args, **kwargs)
Run a string through pager
19.331612
18.882622
1.023778
# To remove python_matches we now have to override it as it's now a property in the superclass. return [ self.file_matches, self.magic_matches, self.python_func_kw_matches, self.dict_key_matches, ]
def matchers(self)
All active matcher routines for completion
15.865642
15.380022
1.031575
# Deferred import from pydev_ipython.inputhook import enable_gui as real_enable_gui try: return real_enable_gui(gui, app) except ValueError as e: raise UsageError("%s" % e)
def enable_gui(gui=None, app=None)
Switch amongst GUI input hooks by name.
6.05549
5.342056
1.133551
# PyDev uses its own completer and custom hooks so that it uses # most completions from PyDev's core completer which provides # extra information. # See getCompletions for where the two sets of results are merged if IPythonRelease._version_major >= 6: self.C...
def init_completer(self)
Initialize the completion machinery. This creates a completer that provides the completions that are IPython specific. We use this to supplement PyDev's core code completions.
5.239797
4.918367
1.065353
hProcess = win32.OpenProcess(dwDesiredAccess, win32.FALSE, self.dwProcessId) try: self.close_handle() except Exception: warnings.warn( "Failed to close process handle: %s" % traceback.format_exc()) self.hProcess = hProcess
def open_handle(self, dwDesiredAccess = win32.PROCESS_ALL_ACCESS)
Opens a new handle to the process. The new handle is stored in the L{hProcess} 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:...
2.994044
3.647118
0.820934
try: if hasattr(self.hProcess, 'close'): self.hProcess.close() elif self.hProcess not in (None, win32.INVALID_HANDLE_VALUE): win32.CloseHandle(self.hProcess) finally: self.hProcess = None
def close_handle(self)
Closes the handle to the process. @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. So unless you've been tinkering with it, setting L{hProcess} to C{None} should be enough...
2.561924
2.325445
1.101692
if self.hProcess in (None, win32.INVALID_HANDLE_VALUE): self.open_handle(dwDesiredAccess) else: dwAccess = self.hProcess.dwAccess if (dwAccess | dwDesiredAccess) != dwAccess: self.open_handle(dwAccess | dwDesiredAccess) return self.hPr...
def get_handle(self, dwDesiredAccess = win32.PROCESS_ALL_ACCESS)
Returns a handle to the process 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. @typ...
2.886871
3.194264
0.903767
hProcess = self.get_handle(win32.PROCESS_TERMINATE) win32.TerminateProcess(hProcess, dwExitCode)
def kill(self, dwExitCode = 0)
Terminates the execution of the process. @raise WindowsError: On error an exception is raised.
4.101335
3.526831
1.162895
self.scan_threads() # force refresh the snapshot suspended = list() try: for aThread in self.iter_threads(): aThread.suspend() suspended.append(aThread) except Exception: for aThread in suspended: try: ...
def suspend(self)
Suspends execution on all threads of the process. @raise WindowsError: On error an exception is raised.
4.923619
4.263792
1.154751
if self.get_thread_count() == 0: self.scan_threads() # only refresh the snapshot if empty resumed = list() try: for aThread in self.iter_threads(): aThread.resume() resumed.append(aThread) except Exception: for ...
def resume(self)
Resumes execution on all threads of the process. @raise WindowsError: On error an exception is raised.
4.681825
4.199429
1.114872
# FIXME the MSDN docs don't say what access rights are needed here! hProcess = self.get_handle(win32.PROCESS_QUERY_INFORMATION) return win32.CheckRemoteDebuggerPresent(hProcess)
def is_debugged(self)
Tries to determine if the process is being debugged by another process. It may detect other debuggers besides WinAppDbg. @rtype: bool @return: C{True} if the process has a debugger attached. @warning: May return inaccurate results when some anti-debug techniques are ...
11.424371
10.265275
1.112914
if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA: dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION else: dwAccess = win32.PROCESS_QUERY_INFORMATION return win32.GetExitCodeProcess( self.get_handle(dwAccess) )
def get_exit_code(self)
@rtype: int @return: Process exit code, or C{STILL_ACTIVE} if it's still alive. @warning: If a process returns C{STILL_ACTIVE} as it's exit code, you may not be able to determine if it's active or not with this method. Use L{is_alive} to check if the process is still active. ...
3.212761
3.195701
1.005339
for index in compat.xrange(len(disasm)): (address, size, text, dump) = disasm[index] m = self.__hexa_parameter.search(text) while m: s, e = m.span() value = text[s:e] try: label = self.get_label_at_a...
def __fixup_labels(self, disasm)
Private method used when disassembling from process memory. It has no return value because the list is modified in place. On return all raw memory addresses are replaced by labels when possible. @type disasm: list of tuple(int, int, str, str) @param disasm: Output of one of the dissas...
3.064355
3.027231
1.012263
try: disasm = self.__disasm except AttributeError: disasm = self.__disasm = Disassembler( self.get_arch() ) return disasm.decode(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. E...
4.329615
4.372317
0.990234
data = self.read(lpAddress, dwSize) disasm = self.disassemble_string(lpAddress, data) self.__fixup_labels(disasm) return disasm
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 ) @retu...
4.851707
7.779202
0.623677
dwDelta = int(float(dwSize) / 2.0) addr_1 = lpAddress - dwDelta addr_2 = lpAddress size_1 = dwDelta size_2 = dwSize - dwDelta data = self.read(addr_1, dwSize) data_1 = data[:size_1] data_2 = data[size_1:] disasm_1 = self.d...
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, ...
2.429904
2.580834
0.941519
aThread = self.get_thread(dwThreadId) return self.disassemble_around(aThread.get_pc(), dwSize)
def disassemble_around_pc(self, dwThreadId, dwSize = 64)
Disassemble around the program counter of the given thread. @type dwThreadId: int @param dwThreadId: Global thread ID. The program counter for this thread will be used as the disassembly address. @type dwSize: int @param dwSize: Delta offset. Code ...
3.828915
5.767066
0.663928
aThread = self.get_thread(dwThreadId) return self.disassemble_instruction(aThread.get_pc())
def disassemble_current(self, dwThreadId)
Disassemble the instruction at the program counter of the given thread. @type dwThreadId: int @param dwThreadId: Global thread ID. The program counter for this thread will be used as the disassembly address. @rtype: tuple( long, int, str, str ) @return: The tu...
4.562658
6.957137
0.655824
try: wow64 = self.__wow64 except AttributeError: if (win32.bits == 32 and not win32.wow64): wow64 = False else: if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA: dwAccess = win32.PROCESS_QUERY_L...
def is_wow64(self)
Determines if the process is running under WOW64. @rtype: bool @return: C{True} if the process is running under WOW64. That is, a 32-bit application running in a 64-bit Windows. C{False} if the process is either a 32-bit application running in a 32-bit ...
2.516115
2.629672
0.956817
if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA: dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION else: dwAccess = win32.PROCESS_QUERY_INFORMATION hProcess = self.get_handle(dwAccess) CreationTime = win32.GetProcessTimes(hProcess)[0] ...
def get_start_time(self)
Determines when has this process started running. @rtype: win32.SYSTEMTIME @return: Process start time.
3.117644
3.083918
1.010936
if self.is_alive(): ExitTime = win32.GetSystemTimeAsFileTime() else: if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA: dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION else: dwAccess = win32.PROCESS_QUERY_INFORMA...
def get_exit_time(self)
Determines when has this process finished running. If the process is still alive, the current time is returned instead. @rtype: win32.SYSTEMTIME @return: Process exit time.
2.928018
2.619168
1.117919
if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA: dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION else: dwAccess = win32.PROCESS_QUERY_INFORMATION hProcess = self.get_handle(dwAccess) (CreationTime, ExitTime, _, _) = win32.GetProcessTimes(...
def get_running_time(self)
Determines how long has this process been running. @rtype: long @return: Process running time in milliseconds.
2.74926
2.812116
0.977648
self.__load_System_class() pid = self.get_pid() return [d for d in System.get_active_services() if d.ProcessId == pid]
def get_services(self)
Retrieves the list of system services that are currently running in this process. @see: L{System.get_services} @rtype: list( L{win32.ServiceStatusProcessEntry} ) @return: List of service status descriptors.
12.317141
10.275419
1.1987
hProcess = self.get_handle(win32.PROCESS_QUERY_INFORMATION) try: return win32.kernel32.GetProcessDEPPolicy(hProcess) except AttributeError: msg = "This method is only available in Windows XP SP3 and above." raise NotImplementedError(msg)
def get_dep_policy(self)
Retrieves the DEP (Data Execution Prevention) policy for this process. @note: This method is only available in Windows XP SP3 and above, and only for 32 bit processes. It will fail in any other circumstance. @see: U{http://msdn.microsoft.com/en-us/library/bb736297(v=vs.85).aspx} @...
4.611237
3.199736
1.44113
self.get_handle( win32.PROCESS_VM_READ | win32.PROCESS_QUERY_INFORMATION ) return self.read_structure(self.get_peb_address(), win32.PEB)
def get_peb(self)
Returns a copy of the PEB. To dereference pointers in it call L{Process.read_structure}. @rtype: L{win32.PEB} @return: PEB structure. @raise WindowsError: An exception is raised on error.
5.908932
4.08758
1.445582
try: return self._peb_ptr except AttributeError: hProcess = self.get_handle(win32.PROCESS_QUERY_INFORMATION) pbi = win32.NtQueryInformationProcess(hProcess, win32.ProcessBasicInformation) address = p...
def get_peb_address(self)
Returns a remote pointer to the PEB. @rtype: int @return: Remote pointer to the L{win32.PEB} structure. Returns C{None} on error.
3.52689
3.208878
1.099104
peb = self.get_peb() pp = self.read_structure(peb.ProcessParameters, win32.RTL_USER_PROCESS_PARAMETERS) s = pp.CommandLine return (s.Buffer, s.MaximumLength)
def get_command_line_block(self)
Retrieves the command line block memory address and size. @rtype: tuple(int, int) @return: Tuple with the memory address of the command line block and it's maximum size in Unicode characters. @raise WindowsError: On error an exception is raised.
13.629782
8.074543
1.687994
peb = self.get_peb() pp = self.read_structure(peb.ProcessParameters, win32.RTL_USER_PROCESS_PARAMETERS) Environment = pp.Environment try: EnvironmentSize = pp.EnvironmentSize except AttributeError: mbi ...
def get_environment_block(self)
Retrieves the environment block memory address for the process. @note: The size is always enough to contain the environment data, but it may not be an exact size. It's best to read the memory and scan for two null wide chars to find the actual size. @rtype: tuple(int, int) ...
8.65052
6.54968
1.320755
(Buffer, MaximumLength) = self.get_command_line_block() CommandLine = self.peek_string(Buffer, dwMaxSize=MaximumLength, fUnicode=True) gst = win32.GuessStringType if gst.t_default == gst.t_ansi: CommandLine ...
def get_command_line(self)
Retrieves the command line with wich the program was started. @rtype: str @return: Command line string. @raise WindowsError: On error an exception is raised.
14.374216
15.915499
0.903158
# Note: the first bytes are garbage and must be skipped. Then the first # two environment entries are the current drive and directory as key # and value pairs, followed by the ExitCode variable (it's what batch # files know as "errorlevel"). After that, the real environment var...
def get_environment_variables(self)
Retrieves the environment variables with wich the program is running. @rtype: list of tuple(compat.unicode, compat.unicode) @return: Environment keys and values as found in the process memory. @raise WindowsError: On error an exception is raised.
4.925334
4.888639
1.007506
# Issue a deprecation warning. warnings.warn( "Process.get_environment_data() is deprecated" \ " since WinAppDbg 1.5.", DeprecationWarning) # Get the environment variables. block = [ key + u'=' + value for (key, value) \ ...
def get_environment_data(self, fUnicode = None)
Retrieves the environment block data with wich the program is running. @warn: Deprecated since WinAppDbg 1.5. @see: L{win32.GuessStringType} @type fUnicode: bool or None @param fUnicode: C{True} to return a list of Unicode strings, C{False} to return a list of ANSI string...
5.54994
4.128768
1.344212
# Issue a deprecation warning. warnings.warn( "Process.parse_environment_data() is deprecated" \ " since WinAppDbg 1.5.", DeprecationWarning) # Create an empty environment dictionary. environment = dict() # End here if the environme...
def parse_environment_data(block)
Parse the environment block into a Python dictionary. @warn: Deprecated since WinAppDbg 1.5. @note: Values of duplicated keys are joined using null characters. @type block: list of str @param block: List of strings as returned by L{get_environment_data}. @rtype: dict(str S{...
5.137426
4.383285
1.172049
# Get the environment variables. variables = self.get_environment_variables() # Convert the strings to ANSI if requested. if fUnicode is None: gst = win32.GuessStringType fUnicode = gst.t_default == gst.t_unicode if not fUnicode: var...
def get_environment(self, fUnicode = None)
Retrieves the environment with wich the program is running. @note: Duplicated keys are joined using null characters. To avoid this behavior, call L{get_environment_variables} instead and convert the results to a dictionary directly, like this: C{dict(process.get_environment_...
4.026871
3.222047
1.249786
if isinstance(pattern, str): return self.search_bytes(pattern, minAddr, maxAddr) if isinstance(pattern, compat.unicode): return self.search_bytes(pattern.encode("utf-16le"), minAddr, maxAddr) if isinstance(pattern, Pattern): ...
def search(self, pattern, minAddr = None, maxAddr = None)
Search for the given pattern within the process memory. @type pattern: str, compat.unicode or L{Pattern} @param pattern: Pattern to search for. It may be a byte string, a Unicode string, or an instance of L{Pattern}. The following L{Pattern} subclasses are provided...
2.841176
2.557232
1.111036
pattern = BytePattern(bytes) matches = Search.search_process(self, pattern, minAddr, maxAddr) for addr, size, data in matches: yield addr
def search_bytes(self, bytes, minAddr = None, maxAddr = None)
Search for the given byte pattern within the process memory. @type bytes: str @param bytes: Bytes to search for. @type minAddr: int @param minAddr: (Optional) Start the search at this memory address. @type maxAddr: int @param maxAddr: (Optional) Stop the search at t...
5.762213
10.182376
0.565901
pattern = TextPattern(text, encoding, caseSensitive) matches = Search.search_process(self, pattern, minAddr, maxAddr) for addr, size, data in matches: yield addr, data
def search_text(self, text, encoding = "utf-16le", caseSensitive = False, minAddr = None, maxAddr = None)
Search for the given text within the process memory. @type text: str or compat.unicode @param text: Text to search for. @type encoding: str @param encoding: (Optional) Encoding for the text parameter. Only used when the text to search for is a Unicode string. ...
4.366022
8.046077
0.542627
pattern = RegExpPattern(regexp, flags) return Search.search_process(self, pattern, minAddr, maxAddr, bufferPages)
def search_regexp(self, regexp, flags = 0, minAddr = None, maxAddr = None, bufferPages = -1)
Search for the given regular expression within the process memory. @type regexp: str @param regexp: Regular expression string. @type flags: int @param flags: Regular expression flags. @type minAddr: int @param minAddr: (Optional) Start the search at this memory addr...
5.755914
13.070329
0.44038
pattern = HexPattern(hexa) matches = Search.search_process(self, pattern, minAddr, maxAddr) for addr, size, data in matches: yield addr, data
def search_hexa(self, hexa, minAddr = None, maxAddr = None)
Search for the given hexadecimal pattern within the process memory. Hex patterns must be in this form:: "68 65 6c 6c 6f 20 77 6f 72 6c 64" # "hello world" Spaces are optional. Capitalization of hex digits doesn't matter. This is exactly equivalent to the previous example:: ...
5.766424
9.207738
0.626259
return Search.extract_ascii_strings(self, minSize = minSize, maxSize = maxSize)
def strings(self, minSize = 4, maxSize = 1024)
Extract ASCII strings from the process memory. @type minSize: int @param minSize: (Optional) Minimum size of the strings to search for. @type maxSize: int @param maxSize: (Optional) Maximum size of the strings to search for. @rtype: iterator of tuple(int, int, str) ...
12.648412
17.916712
0.705956
hProcess = self.get_handle( win32.PROCESS_VM_READ | win32.PROCESS_QUERY_INFORMATION ) if not self.is_buffer(lpBaseAddress, nSize): raise ctypes.WinError(win32.ERROR_INVALID_ADDRESS) data = win32.ReadProcessMemory(hProcess, lpBaseAddress, n...
def read(self, lpBaseAddress, nSize)
Reads from the memory of the process. @see: L{peek} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type nSize: int @param nSize: Number of bytes to read. @rtype: str @return: Bytes read from the process memory. @ra...
2.86958
3.090882
0.928402
r = self.poke(lpBaseAddress, lpBuffer) if r != len(lpBuffer): raise ctypes.WinError()
def write(self, lpBaseAddress, lpBuffer)
Writes to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{poke} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type lpBuffer: str @param lpBuffer: Bytes to write. @raise ...
4.606937
5.476495
0.84122
return self.__read_c_type(lpBaseAddress, compat.b('@l'), ctypes.c_int)
def read_int(self, lpBaseAddress)
Reads a signed integer from the memory of the process. @see: L{peek_int} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Integer value read from the process memory. @raise WindowsError: On error an exception is ra...
16.444302
29.296913
0.561298
if type(lpBaseAddress) not in (type(0), type(long(0))): lpBaseAddress = ctypes.cast(lpBaseAddress, ctypes.c_void_p) data = self.read(lpBaseAddress, ctypes.sizeof(stype)) buff = ctypes.create_string_buffer(data) ptr = ctypes.cast(ctypes.pointer(buff), ctypes.POINTER(...
def read_structure(self, lpBaseAddress, stype)
Reads a ctypes structure from the memory of the process. @see: L{read} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type stype: class ctypes.Structure or a subclass. @param stype: Structure definition. @rtype: int @return...
2.455814
2.746741
0.894083
if fUnicode: nChars = nChars * 2 szString = self.read(lpBaseAddress, nChars) if fUnicode: szString = compat.unicode(szString, 'U16', 'ignore') return szString
def read_string(self, lpBaseAddress, nChars, fUnicode = False)
Reads an ASCII or Unicode string from the address space of the process. @see: L{peek_string} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type nChars: int @param nChars: String length to read, in characters. Remember th...
3.373131
4.265631
0.790769
# XXX TODO # + Maybe change page permissions before trying to read? # + Maybe use mquery instead of get_memory_map? # (less syscalls if we break out of the loop earlier) data = '' if nSize > 0: try: hProcess = self.get_handle( win32....
def peek(self, lpBaseAddress, nSize)
Reads the memory of the process. @see: L{read} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type nSize: int @param nSize: Number of bytes to read. @rtype: str @return: Bytes read from the process memory. Retur...
4.775307
4.822387
0.990237
assert isinstance(lpBuffer, compat.bytes) hProcess = self.get_handle( win32.PROCESS_VM_WRITE | win32.PROCESS_VM_OPERATION | win32.PROCESS_QUERY_INFORMATION ) mbi = self.mquery(lpBaseAddress) if not mbi.has_c...
def poke(self, lpBaseAddress, lpBuffer)
Writes to the memory of the process. @note: Page permissions may be changed temporarily while writing. @see: L{write} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin writing. @type lpBuffer: str @param lpBuffer: Bytes to write. @rtype...
2.899365
2.917209
0.993883
char = self.peek(lpBaseAddress, 1) if char: return ord(char) return 0
def peek_char(self, lpBaseAddress)
Reads a single character from the memory of the process. @see: L{read_char} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Character read from the process memory. Returns zero on error.
3.739406
7.480146
0.499911
# Validate the parameters. if not lpBaseAddress or dwMaxSize == 0: if fUnicode: return u'' return '' if not dwMaxSize: dwMaxSize = 0x1000 # Read the string. szString = self.peek(lpBaseAddress, dwMaxSize) # If...
def peek_string(self, lpBaseAddress, fUnicode = False, dwMaxSize = 0x1000)
Tries to read an ASCII or Unicode string from the address space of the process. @see: L{read_string} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type fUnicode: bool @param fUnicode: C{True} is the string is expected to be Unicode,...
2.506855
2.440241
1.027298
result = dict() ptrSize = win32.sizeof(win32.LPVOID) if ptrSize == 4: ptrFmt = '<L' else: ptrFmt = '<Q' if len(data) > 0: for i in compat.xrange(0, len(data), peekStep): packed = data[i:i+ptrSize] ...
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. @see: L{peek} @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. ...
3.55028
3.794726
0.935583
hProcess = self.get_handle(win32.PROCESS_VM_OPERATION) return win32.VirtualAllocEx(hProcess, lpAddress, dwSize)
def malloc(self, dwSize, lpAddress = None)
Allocates memory into the address space of the process. @see: L{free} @type dwSize: int @param dwSize: Number of bytes to allocate. @type lpAddress: int @param lpAddress: (Optional) Desired address for the newly allocated memory. This is only a hint, ...
3.914165
5.068449
0.772261
hProcess = self.get_handle(win32.PROCESS_VM_OPERATION) return win32.VirtualProtectEx(hProcess, lpAddress, dwSize, flNewProtect)
def mprotect(self, lpAddress, dwSize, flNewProtect)
Set memory protection in the address space of the process. @see: U{http://msdn.microsoft.com/en-us/library/aa366899.aspx} @type lpAddress: int @param lpAddress: Address of memory to protect. @type dwSize: int @param dwSize: Number of bytes to protect. @type flNewPr...
3.357158
4.087492
0.821325
hProcess = self.get_handle(win32.PROCESS_QUERY_INFORMATION) return win32.VirtualQueryEx(hProcess, lpAddress)
def mquery(self, lpAddress)
Query memory information from the address space of the process. Returns a L{win32.MemoryBasicInformation} object. @see: U{http://msdn.microsoft.com/en-us/library/aa366907(VS.85).aspx} @type lpAddress: int @param lpAddress: Address of memory to query. @rtype: L{win32.MemoryBa...
4.385845
4.565458
0.960658
hProcess = self.get_handle(win32.PROCESS_VM_OPERATION) win32.VirtualFreeEx(hProcess, lpAddress)
def free(self, lpAddress)
Frees memory from the address space of the process. @see: U{http://msdn.microsoft.com/en-us/library/aa366894(v=vs.85).aspx} @type lpAddress: int @param lpAddress: Address of memory to free. Must be the base address returned by L{malloc}. @raise WindowsError: On error an e...
4.187265
5.35038
0.782611
try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.has_content()
def is_pointer(self, address)
Determines if an address is a valid code or data pointer. That is, the address must be valid and must point to code or data in the target process. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address is a valid code...
4.863883
4.61616
1.053664
try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return True
def is_address_valid(self, address)
Determines if an address is a valid user mode address. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address is a valid user mode address. @raise WindowsError: An exception is raised on error.
4.967989
4.112768
1.207943
try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_free()
def is_address_free(self, address)
Determines if an address belongs to a free page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a free page. @raise WindowsError: An except...
4.415252
3.867896
1.141512
try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_reserved()
def is_address_reserved(self, address)
Determines if an address belongs to a reserved page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a reserved page. @raise WindowsError: A...
4.406361
3.91637
1.125114
try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_commited()
def is_address_commited(self, address)
Determines if an address belongs to a commited page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited page. @raise WindowsError: A...
4.489951
3.767737
1.191684
try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_guard()
def is_address_guard(self, address)
Determines if an address belongs to a guard page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a guard page. @raise WindowsError: An exce...
4.639878
3.87007
1.198913
try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_readable()
def is_address_readable(self, address)
Determines if an address belongs to a commited and readable page. The page may or may not have additional permissions. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: ...
4.497089
3.821343
1.176835
try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_writeable()
def is_address_writeable(self, address)
Determines if an address belongs to a commited and writeable page. The page may or may not have additional permissions. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: ...
4.277963
3.74667
1.141804
try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_copy_on_write()
def is_address_copy_on_write(self, address)
Determines if an address belongs to a commited, copy-on-write page. The page may or may not have additional permissions. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: ...
3.937784
3.441706
1.144137
try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_executable()
def is_address_executable(self, address)
Determines if an address belongs to a commited and executable page. The page may or may not have additional permissions. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: ...
4.128526
3.737859
1.104516
try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_executable_and_writeable()
def is_address_executable_and_writeable(self, address)
Determines if an address belongs to a commited, writeable and executable page. The page may or may not have additional permissions. Looking for writeable and executable pages is important when exploiting a software vulnerability. @note: Returns always C{False} for kernel mode addresses...
3.823729
3.605684
1.060473
if size <= 0: raise ValueError("The size argument must be greater than zero") while size > 0: try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAM...
def is_buffer(self, address, size)
Determines if the given memory area is a valid code or data buffer. @note: Returns always C{False} for kernel mode addresses. @see: L{mquery} @type address: int @param address: Memory address. @type size: int @param size: Number of bytes. Must be greater than zero. ...
3.851006
3.383027
1.138332
minAddr, maxAddr = MemoryAddresses.align_address_range(minAddr,maxAddr) prevAddr = minAddr - 1 currentAddr = minAddr while prevAddr < currentAddr < maxAddr: try: mbi = self.mquery(currentAddr) except WindowsError: e = sy...
def iter_memory_map(self, minAddr = None, maxAddr = None)
Produces an iterator over the memory map to the process address space. Optionally restrict the map to the given address range. @see: L{mquery} @type minAddr: int @param minAddr: (Optional) Starting address in address range to query. @type maxAddr: int @param maxAddr...
3.758382
3.299107
1.139212
hProcess = self.get_handle( win32.PROCESS_VM_READ | win32.PROCESS_QUERY_INFORMATION ) if not memoryMap: memoryMap = self.get_memory_map() mappedFilenames = dict() for mbi in memoryMap: if mbi.Type not in (win32.MEM_IMAG...
def get_mapped_filenames(self, memoryMap = None)
Retrieves the filenames for memory mapped files in the debugee. @type memoryMap: list( L{win32.MemoryBasicInformation} ) @param memoryMap: (Optional) Memory map returned by L{get_memory_map}. If not given, the current memory map is used. @rtype: dict( int S{->} str ) @ret...
3.160573
2.865472
1.102985
# One may feel tempted to include calls to self.suspend() and # self.resume() here, but that wouldn't work on a dead process. # It also wouldn't be needed when debugging since the process is # already suspended when the debug event arrives. So it's up to # the user to s...
def iter_memory_snapshot(self, minAddr = None, maxAddr = None)
Returns an iterator that allows you to go through the memory contents of a process. It's basically the same as the L{take_memory_snapshot} method, but it takes the snapshot of each memory region as it goes, as opposed to taking the whole snapshot at once. This allows you to work with ve...
3.400158
3.086135
1.101753
if not snapshot or not isinstance(snapshot, list) \ or not isinstance(snapshot[0], win32.MemoryBasicInformation): raise TypeError( "Only snapshots returned by " \ "take_memory_snapshot() can be used here." ) # Get the process handle. ...
def restore_memory_snapshot(self, snapshot, bSkipMappedFiles = True, bSkipOnError = False)
Attempts to restore the memory state as it was when the given snapshot was taken. @warning: Currently only the memory contents, state and protect bits are restored. Under some circumstances this method may fail (for example if memory was freed and then reused by a mapped file). ...
2.549071
2.428446
1.049672
# Uncomment for debugging... ## payload = '\xCC' + payload # Allocate the memory for the shellcode. lpStartAddress = self.malloc(len(payload)) # Catch exceptions so we can free the memory on error. try: # Write the shellcode to our memory location....
def inject_code(self, payload, lpParameter = 0)
Injects relocatable code into the process memory and executes it. @warning: Don't forget to free the memory when you're done with it! Otherwise you'll be leaking memory in the target process. @see: L{inject_dll} @type payload: str @param payload: Relocatable code to run i...
6.254585
5.741249
1.089412
if not dwExitCode: dwExitCode = 0 pExitProcess = self.resolve_label('kernel32!ExitProcess') aThread = self.start_thread(pExitProcess, dwExitCode) if bWait: aThread.wait(dwTimeout)
def clean_exit(self, dwExitCode = 0, bWait = False, dwTimeout = None)
Injects a new thread to call ExitProcess(). Optionally waits for the injected thread to finish. @warning: Setting C{bWait} to C{True} when the process is frozen by a debug event will cause a deadlock in your debugger. @type dwExitCode: int @param dwExitCode: Process exit c...
5.090942
4.852643
1.049107
# Do not use super() here. bCallHandler = _ThreadContainer._notify_create_process(self, event) bCallHandler = bCallHandler and \ _ModuleContainer._notify_create_process(self, event) return bCallHandler
def _notify_create_process(self, event)
Notify the creation of a new process. This is done automatically by the L{Debug} class, you shouldn't need to call it yourself. @type event: L{CreateProcessEvent} @param event: Create process event. @rtype: bool @return: C{True} to call the user-defined handle, C{Fal...
7.849273
9.727597
0.806908
if not self.__processDict: try: self.scan_processes() # remote desktop api (relative fn) except Exception: self.scan_processes_fast() # psapi (no filenames) self.scan_process_filenames()
def __initialize_snapshot(self)
Private method to automatically initialize the snapshot when you try to use it without calling any of the scan_* methods first. You don't need to call this yourself.
24.448368
21.067875
1.160457
self.__initialize_snapshot() if dwProcessId not in self.__processDict: msg = "Unknown process ID %d" % dwProcessId raise KeyError(msg) return self.__processDict[dwProcessId]
def get_process(self, dwProcessId)
@type dwProcessId: int @param dwProcessId: Global ID of the process to look for. @rtype: L{Process} @return: Process object with the given global ID.
4.204909
4.412847
0.952879
try: # No good, because in XP and below it tries to get the PID # through the toolhelp API, and that's slow. We don't want # to scan for threads over and over for each call. ## dwProcessId = Thread(dwThreadId).get_pid() # This API only exists...
def get_pid_from_tid(self, dwThreadId)
Retrieves the global ID of the process that owns the thread. @type dwThreadId: int @param dwThreadId: Thread global ID. @rtype: int @return: Process global ID. @raise KeyError: The thread does not exist.
4.544095
4.503634
1.008984
cmdline = list() for token in argv: if not token: token = '""' else: if '"' in token: token = token.replace('"', '\\"') if ' ' in token or \ '\t' in token or \ '...
def argv_to_cmdline(argv)
Convert a list of arguments to a single command line string. @type argv: list( str ) @param argv: List of argument strings. The first element is the program to execute. @rtype: str @return: Command line string.
2.435316
2.915345
0.835344
try: exp = win32.SHGetFolderPath(win32.CSIDL_WINDOWS) except Exception: exp = None if not exp: exp = os.getenv('SystemRoot') if exp: exp = os.path.join(exp, 'explorer.exe') exp_list = self.find_processes_by_filename(exp...
def get_explorer_pid(self)
Tries to find the process ID for "explorer.exe". @rtype: int or None @return: Returns the process ID, or C{None} on error.
3.77698
3.672278
1.028511
has_threads = True try: try: # Try using the Toolhelp API # to scan for processes and threads. self.scan_processes_and_threads() except Exception: # On error, try using the PSAPI to scan for process IDs o...
def scan(self)
Populates the snapshot with running processes and threads, and loaded modules. Tipically this is the first method called after instantiating a L{System} object, as it makes a best effort approach to gathering information on running processes. @rtype: bool @return: C{Tru...
7.044037
6.781468
1.038719
# The main module filename may be spoofed by malware, # since this information resides in usermode space. # See: http://www.ragestorm.net/blogs/?p=163 our_pid = win32.GetCurrentProcessId() dead_pids = set( compat.iterkeys(self.__processDict) ) found_tids = ...
def scan_processes_and_threads(self)
Populates the snapshot with running processes and threads. Tipically you don't need to call this method directly, if unsure use L{scan} instead. @note: This method uses the Toolhelp API. @see: L{scan_modules} @raise WindowsError: An error occured while updating the snapshot. ...
2.431187
2.399474
1.013216
complete = True for aProcess in compat.itervalues(self.__processDict): try: aProcess.scan_modules() except WindowsError: complete = False return complete
def scan_modules(self)
Populates the snapshot with loaded modules. Tipically you don't need to call this method directly, if unsure use L{scan} instead. @note: This method uses the Toolhelp API. @see: L{scan_processes_and_threads} @rtype: bool @return: C{True} if the snapshot is complete, C...
8.968842
7.620577
1.176924
# Get the previous list of PIDs. # We'll be removing live PIDs from it as we find them. our_pid = win32.GetCurrentProcessId() dead_pids = set( compat.iterkeys(self.__processDict) ) # Ignore our own PID. if our_pid in dead_pids: dead_pids.remove(o...
def scan_processes(self)
Populates the snapshot with running processes. Tipically you don't need to call this method directly, if unsure use L{scan} instead. @note: This method uses the Remote Desktop API instead of the Toolhelp API. It might give slightly different results, especially if the c...
3.763117
3.569231
1.054321
# Get the new and old list of pids new_pids = set( win32.EnumProcesses() ) old_pids = set( compat.iterkeys(self.__processDict) ) # Ignore our own pid our_pid = win32.GetCurrentProcessId() if our_pid in new_pids: new_pids.remove(our_pid) if ...
def scan_processes_fast(self)
Populates the snapshot with running processes. Only the PID is retrieved for each process. Dead processes are removed. Threads and modules of living processes are ignored. Tipically you don't need to call this method directly, if unsure use L{scan} instead. @note: This...
2.832018
2.928459
0.967068
complete = True for aProcess in self.__processDict.values(): try: new_name = None old_name = aProcess.fileName try: aProcess.fileName = None new_name = aProcess.get_filename() fin...
def scan_process_filenames(self)
Update the filename for each process in the snapshot when possible. @note: Tipically you don't need to call this method. It's called automatically by L{scan} to get the full pathname for each process when possible, since some scan methods only get filenames without the path ...
3.861756
3.946318
0.978572
for pid in self.get_process_ids(): aProcess = self.get_process(pid) if not aProcess.is_alive(): self._del_process(aProcess)
def clear_dead_processes(self)
Removes Process objects from the snapshot referring to processes no longer running.
3.526329
3.139608
1.123175