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_config)
if args.list_fixes:
for code, description in sorted(supported_fixes()):
print('{code} - {description}'.format(
code=code, description=description))
return 0
if args.files == ['-']:
assert not args.in_place
encoding = sys.stdin.encoding or get_encoding()
# LineEndingWrapper is unnecessary here due to the symmetry between
# standard in and standard out.
wrap_output(sys.stdout, encoding=encoding).write(
fix_code(sys.stdin.read(), args, encoding=encoding))
else:
if args.in_place or args.diff:
args.files = list(set(args.files))
else:
assert len(args.files) == 1
assert not args.recursive
fix_multiple_files(args.files, args, sys.stdout)
except KeyboardInterrupt:
return 1 | 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(' ', '') == target.replace(' ', '') and
_get_indentation(fixed) == _get_indentation(target)
):
self.source[result['line'] - 1] = fixed
else:
return [] | 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
offset -= 1
offset += 1
self.source[offset] = cr + self.source[offset] | 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_lines = logical[2]
previous_line = get_item(self.source, start_line_index - 1, default='')
next_line = get_item(self.source, end_line_index + 1, default='')
single_line = join_logical_line(''.join(logical_lines))
try:
fixed = self.fix_long_line(
target=single_line,
previous_line=previous_line,
next_line=next_line,
original=''.join(logical_lines))
except (SyntaxError, tokenize.TokenError):
return self.fix_long_line_physically(result)
if fixed:
for line_index in range(start_line_index, end_line_index + 1):
self.source[line_index] = ''
self.source[start_line_index] = fixed
return range(start_line_index + 1, end_line_index + 1)
else:
return [] | 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,
previous_line=previous_line,
next_line=next_line,
original=target)
except (SyntaxError, tokenize.TokenError):
return []
if fixed:
self.source[line_index] = fixed
return [line_index + 1]
else:
return [] | 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 ([\w.]+) == False:',
r'if not \1:', target, count=1)
elif re.match(r'^\s*if [\w.]+ != True:$', target):
self.source[line_index] = re.sub(r'if ([\w.]+) != True:',
r'if not \1:', target, count=1)
else:
right_offset = offset + 2
if right_offset >= len(target):
return []
left = target[:offset].rstrip()
center = target[offset:right_offset]
right = target[right_offset:].lstrip()
# Handle simple cases only.
new_right = None
if center.strip() == '==':
if re.match(r'\bTrue\b', right):
new_right = re.sub(r'\bTrue\b *', '', right, count=1)
elif center.strip() == '!=':
if re.match(r'\bFalse\b', right):
new_right = re.sub(r'\bFalse\b *', '', right, count=1)
if new_right is None:
return []
if new_right[0].isalnum():
new_right = ' ' + new_right
self.source[line_index] = left + new_right | 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)
self.source[line_index] = '{0}{1} {2} {3} {4}'.format(
target[:pos_start], match.group(2), match.group(1),
match.group(3), target[match.end():]) | 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)
):
break
else:
last_space = None
if isinstance(item, self._Space):
last_space = item
if isinstance(item, (self._LineBreak, self._Indent)):
return
if not last_space:
return
self.add_line_break_at(self._lines.index(last_space), indent_amt) | 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 -- passed to InteractiveConsole.interact()
readfunc -- if not None, replaces InteractiveConsole.raw_input()
local -- passed to InteractiveInterpreter.__init__() | 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
self.runcode(code)
return False | 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 showsyntaxerror() method.
2) The input is incomplete, and more input is required;
compile_command() returned None. Nothing happens.
3) The input is complete; compile_command() returned a code
object. The code is executed by calling self.runcode() (which
also handles run-time exceptions, except for SystemExit).
The return value is True in case 2, False in the other cases (unless
an exception is raised). The return value can be used to
decide whether to use sys.ps1 or sys.ps2 to prompt the next
line. | 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. The
caller should be prepared to deal with it. | 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) = value
except:
# Not the format we expect; leave it alone
pass
else:
# Stuff in the right filename
value = SyntaxError(msg, (filename, lineno, offset, line))
sys.last_value = value
list = traceback.format_exception_only(type, value)
map(self.write, list) | 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 output is written by self.write(), below. | 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:
list.insert(0, "Traceback (most recent call last):\n")
list[len(list):] = traceback.format_exception_only(type, value)
finally:
tblist = tb = None
map(self.write, 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.'
if banner is None:
self.write("Python %s on %s\n%s\n(%s)\n" %
(sys.version, sys.platform, cprt,
self.__class__.__name__))
else:
self.write("%s\n" % str(banner))
more = 0
while 1:
try:
if more:
prompt = sys.ps2 #@UndefinedVariable
else:
prompt = sys.ps1 #@UndefinedVariable
try:
line = self.raw_input(prompt)
# Can be None if sys.stdin was redefined
encoding = getattr(sys.stdin, "encoding", None)
if encoding and not isinstance(line, unicode):
line = line.decode(encoding)
except EOFError:
self.write("\n")
break
else:
more = self.push(line)
except KeyboardInterrupt:
self.write("\nKeyboardInterrupt\n")
self.resetbuffer()
more = 0 | 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
to confuse this with the real interpreter -- since it's so
close!). | 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 command was executed or invalid, the buffer
is reset; otherwise, the command is incomplete, and the buffer
is left as it was after the line was appended. The return
value is 1 if more input is required, 0 if the line was dealt
with in some way (this is the same as runsource()). | 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.Completer = self._new_completer_600()
elif IPythonRelease._version_major >= 5:
self.Completer = self._new_completer_500()
elif IPythonRelease._version_major >= 2:
self.Completer = self._new_completer_234()
elif IPythonRelease._version_major >= 1:
self.Completer = self._new_completer_100()
if hasattr(self.Completer, 'use_jedi'):
self.Completer.use_jedi = False
self.add_completer_hooks()
if IPythonRelease._version_major <= 3:
# Only configure readline if we truly are using readline. IPython can
# do tab-completion over the network, in GUIs, etc, where readline
# itself may be absent
if self.has_readline:
self.set_readline_completer() | 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: Desired access rights.
Defaults to L{win32.PROCESS_ALL_ACCESS}.
See: U{http://msdn.microsoft.com/en-us/library/windows/desktop/ms684880(v=vs.85).aspx}
@raise WindowsError: It's not possible to open a handle to the process
with the requested access rights. This tipically happens because
the target process is a system process and the debugger is not
runnning with administrative rights. | 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.hProcess | 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.
@type dwDesiredAccess: int
@param dwDesiredAccess: Desired access rights.
Defaults to L{win32.PROCESS_ALL_ACCESS}.
See: U{http://msdn.microsoft.com/en-us/library/windows/desktop/ms684880(v=vs.85).aspx}
@rtype: L{ProcessHandle}
@return: Handle to the process.
@raise WindowsError: It's not possible to open a handle to the process
with the requested access rights. This tipically happens because
the target process is a system process and the debugger is not
runnning with administrative rights. | 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:
aThread.resume()
except Exception:
pass
raise | 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 aThread in resumed:
try:
aThread.suspend()
except Exception:
pass
raise | 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
used by the target process.
@note: To know if a process currently being debugged by a L{Debug}
object, call L{Debug.is_debugee} instead. | 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.
Alternatively you can call L{get_handle} to get the handle object
and then L{ProcessHandle.wait} on it to wait until the process
finishes running. | 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_address( int(value, 0x10) )
except Exception:
label = None
if label:
text = text[:s] + label + text[e:]
e = s + len(value)
m = self.__hexa_parameter.search(text, e)
disasm[index] = (address, size, text, dump) | 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 dissassembly functions. | 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. 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.
@raise NotImplementedError:
No compatible disassembler was found for the current platform. | 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 )
@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.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.disassemble_string(addr_1, data_1)
disasm_2 = self.disassemble_string(addr_2, data_2)
disasm = disasm_1 + disasm_2
self.__fixup_labels(disasm)
return disasm | 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. | 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 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. | 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 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.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_LIMITED_INFORMATION
else:
dwAccess = win32.PROCESS_QUERY_INFORMATION
hProcess = self.get_handle(dwAccess)
try:
wow64 = win32.IsWow64Process(hProcess)
except AttributeError:
wow64 = False
self.__wow64 = wow64
return wow64 | 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 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} | 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]
return win32.FileTimeToSystemTime(CreationTime) | 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_INFORMATION
hProcess = self.get_handle(dwAccess)
ExitTime = win32.GetProcessTimes(hProcess)[1]
return win32.FileTimeToSystemTime(ExitTime) | 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(hProcess)
if self.is_alive():
ExitTime = win32.GetSystemTimeAsFileTime()
CreationTime = CreationTime.dwLowDateTime + (CreationTime.dwHighDateTime << 32)
ExitTime = ExitTime.dwLowDateTime + ( ExitTime.dwHighDateTime << 32)
RunningTime = ExitTime - CreationTime
return RunningTime / 10000 | 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}
@rtype: tuple(int, int)
@return:
The first member of the tuple is the DEP flags. It can be a
combination of the following values:
- 0: DEP is disabled for this process.
- 1: DEP is enabled for this process. (C{PROCESS_DEP_ENABLE})
- 2: DEP-ATL thunk emulation is disabled for this process.
(C{PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION})
The second member of the tuple is the permanent flag. If C{TRUE}
the DEP settings cannot be changed in runtime for this process.
@raise WindowsError: On error an exception is raised. | 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 = pbi.PebBaseAddress
self._peb_ptr = address
return address | 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 = self.mquery(Environment)
EnvironmentSize = mbi.RegionSize + mbi.BaseAddress - Environment
return (Environment, EnvironmentSize) | 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)
@return: Tuple with the memory address of the environment block
and it's size.
@raise WindowsError: On error an exception is raised. | 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 = CommandLine.encode('cp1252')
return 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 vars
# are there in alphabetical order. In theory that's where it stops,
# but I've always seen one more "variable" tucked at the end which
# may be another environment block but in ANSI. I haven't examined it
# yet, I'm just skipping it because if it's parsed as Unicode it just
# renders garbage.
# Read the environment block contents.
data = self.peek( *self.get_environment_block() )
# Put them into a Unicode buffer.
tmp = ctypes.create_string_buffer(data)
buffer = ctypes.create_unicode_buffer(len(data))
ctypes.memmove(buffer, tmp, len(data))
del tmp
# Skip until the first Unicode null char is found.
pos = 0
while buffer[pos] != u'\0':
pos += 1
pos += 1
# Loop for each environment variable...
environment = []
while buffer[pos] != u'\0':
# Until we find a null char...
env_name_pos = pos
env_name = u''
found_name = False
while buffer[pos] != u'\0':
# Get the current char.
char = buffer[pos]
# Is it an equal sign?
if char == u'=':
# Skip leading equal signs.
if env_name_pos == pos:
env_name_pos += 1
pos += 1
continue
# Otherwise we found the separator equal sign.
pos += 1
found_name = True
break
# Add the char to the variable name.
env_name += char
# Next char.
pos += 1
# If the name was not parsed properly, stop.
if not found_name:
break
# Read the variable value until we find a null char.
env_value = u''
while buffer[pos] != u'\0':
env_value += buffer[pos]
pos += 1
# Skip the null char.
pos += 1
# Add to the list of environment variables found.
environment.append( (env_name, env_value) )
# Remove the last entry, it's garbage.
if environment:
environment.pop()
# Return the environment variables.
return environment | 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) \
in self.get_environment_variables() ]
# Convert the data to ANSI if requested.
if fUnicode is None:
gst = win32.GuessStringType
fUnicode = gst.t_default == gst.t_unicode
if not fUnicode:
block = [x.encode('cp1252') for x in block]
# Return the environment data.
return block | 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 strings, or C{None} to return whatever
the default is for string types.
@rtype: list of str
@return: Environment keys and values separated by a (C{=}) character,
as found in the process memory.
@raise WindowsError: On error an exception is raised. | 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 environment block is empty.
if not block:
return environment
# Prepare the tokens (ANSI or Unicode).
gst = win32.GuessStringType
if type(block[0]) == gst.t_ansi:
equals = '='
terminator = '\0'
else:
equals = u'='
terminator = u'\0'
# Split the blocks into key/value pairs.
for chunk in block:
sep = chunk.find(equals, 1)
if sep < 0:
## raise Exception()
continue # corrupted environment block?
key, value = chunk[:sep], chunk[sep+1:]
# For duplicated keys, append the value.
# Values are separated using null terminators.
if key not in environment:
environment[key] = value
else:
environment[key] += terminator + value
# Return the environment dictionary.
return environment | 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{->} str)
@return: Dictionary of environment keys and values. | 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:
variables = [ ( key.encode('cp1252'), value.encode('cp1252') ) \
for (key, value) in variables ]
# Add the variables to a dictionary, concatenating duplicates.
environment = dict()
for key, value in variables:
if key in environment:
environment[key] = environment[key] + u'\0' + value
else:
environment[key] = value
# Return the dictionary.
return environment | 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_variables())}
@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 strings, or C{None} to return whatever
the default is for string types.
@rtype: dict(str S{->} str)
@return: Dictionary of environment keys and values.
@raise WindowsError: On error an exception is raised. | 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):
return Search.search_process(self, pattern, minAddr, maxAddr)
raise TypeError("Unknown pattern type: %r" % type(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 by WinAppDbg:
- L{BytePattern}
- L{TextPattern}
- L{RegExpPattern}
- L{HexPattern}
You can also write your own subclass of L{Pattern} for customized
searches.
@type minAddr: int
@param minAddr: (Optional) Start the search at this memory address.
@type maxAddr: int
@param maxAddr: (Optional) Stop the search at this memory address.
@rtype: iterator of tuple( int, int, str )
@return: An iterator of tuples. Each tuple contains the following:
- The memory address where the pattern was found.
- The size of the data that matches the pattern.
- The data that matches the pattern.
@raise WindowsError: An error occurred when querying or reading the
process memory. | 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 this memory address.
@rtype: iterator of int
@return: An iterator of memory addresses where the pattern was found.
@raise WindowsError: An error occurred when querying or reading the
process memory. | 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.
Don't change unless you know what you're doing!
@type caseSensitive: bool
@param caseSensitive: C{True} of the search is case sensitive,
C{False} otherwise.
@type minAddr: int
@param minAddr: (Optional) Start the search at this memory address.
@type maxAddr: int
@param maxAddr: (Optional) Stop the search at this memory address.
@rtype: iterator of tuple( int, str )
@return: An iterator of tuples. Each tuple contains the following:
- The memory address where the pattern was found.
- The text that matches the pattern.
@raise WindowsError: An error occurred when querying or reading the
process memory. | 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 address.
@type maxAddr: int
@param maxAddr: (Optional) Stop the search at this memory address.
@type bufferPages: int
@param bufferPages: (Optional) Number of memory pages to buffer when
performing the search. Valid values are:
- C{0} or C{None}:
Automatically determine the required buffer size. May not give
complete results for regular expressions that match variable
sized strings.
- C{> 0}: Set the buffer size, in memory pages.
- C{< 0}: Disable buffering entirely. This may give you a little
speed gain at the cost of an increased memory usage. If the
target process has very large contiguous memory regions it may
actually be slower or even fail. It's also the only way to
guarantee complete results for regular expressions that match
variable sized strings.
@rtype: iterator of tuple( int, int, str )
@return: An iterator of tuples. Each tuple contains the following:
- The memory address where the pattern was found.
- The size of the data that matches the pattern.
- The data that matches the pattern.
@raise WindowsError: An error occurred when querying or reading the
process memory. | 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::
"68656C6C6F20776F726C64" # "hello world"
Wildcards are allowed, in the form of a C{?} sign in any hex digit::
"5? 5? c3" # pop register / pop register / ret
"b8 ?? ?? ?? ??" # mov eax, immediate value
@type hexa: str
@param hexa: Pattern 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 this memory address.
@rtype: iterator of tuple( int, str )
@return: An iterator of tuples. Each tuple contains the following:
- The memory address where the pattern was found.
- The bytes that match the pattern.
@raise WindowsError: An error occurred when querying or reading the
process memory. | 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)
@return: Iterator of strings extracted from the process memory.
Each tuple contains the following:
- The memory address where the string was found.
- The size of the string.
- The string. | 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, nSize)
if len(data) != nSize:
raise ctypes.WinError()
return data | 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.
@raise WindowsError: On error an exception is raised. | 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 WindowsError: On error an exception is raised. | 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 raised. | 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(stype))
return ptr.contents | 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: Structure instance filled in with data
read from the process memory.
@raise WindowsError: On error an exception is raised. | 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 that Unicode strings have two byte characters.
@type fUnicode: bool
@param fUnicode: C{True} is the string is expected to be Unicode,
C{False} if it's expected to be ANSI.
@rtype: str, compat.unicode
@return: String read from the process memory space.
@raise WindowsError: On error an exception is raised. | 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.PROCESS_VM_READ |
win32.PROCESS_QUERY_INFORMATION )
for mbi in self.get_memory_map(lpBaseAddress,
lpBaseAddress + nSize):
if not mbi.is_readable():
nSize = mbi.BaseAddress - lpBaseAddress
break
if nSize > 0:
data = win32.ReadProcessMemory(
hProcess, lpBaseAddress, nSize)
except WindowsError:
e = sys.exc_info()[1]
msg = "Error reading process %d address %s: %s"
msg %= (self.get_pid(),
HexDump.address(lpBaseAddress),
e.strerror)
warnings.warn(msg)
return data | 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.
Returns an empty string on error. | 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_content():
raise ctypes.WinError(win32.ERROR_INVALID_ADDRESS)
if mbi.is_image() or mbi.is_mapped():
prot = win32.PAGE_WRITECOPY
elif mbi.is_writeable():
prot = None
elif mbi.is_executable():
prot = win32.PAGE_EXECUTE_READWRITE
else:
prot = win32.PAGE_READWRITE
if prot is not None:
try:
self.mprotect(lpBaseAddress, len(lpBuffer), prot)
except Exception:
prot = None
msg = ("Failed to adjust page permissions"
" for process %s at address %s: %s")
msg = msg % (self.get_pid(),
HexDump.address(lpBaseAddress, self.get_bits()),
traceback.format_exc())
warnings.warn(msg, RuntimeWarning)
try:
r = win32.WriteProcessMemory(hProcess, lpBaseAddress, lpBuffer)
finally:
if prot is not None:
self.mprotect(lpBaseAddress, len(lpBuffer), mbi.Protect)
return r | 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: int
@return: Number of bytes written.
May be less than the number of bytes to write. | 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 the string is Unicode...
if fUnicode:
# Decode the string.
szString = compat.unicode(szString, 'U16', 'replace')
## try:
## szString = compat.unicode(szString, 'U16')
## except UnicodeDecodeError:
## szString = struct.unpack('H' * (len(szString) / 2), szString)
## szString = [ unichr(c) for c in szString ]
## szString = u''.join(szString)
# Truncate the string when the first null char is found.
szString = szString[ : szString.find(u'\0') ]
# If the string is ANSI...
else:
# Truncate the string when the first null char is found.
szString = szString[ : szString.find('\0') ]
# Return the decoded string.
return szString | 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,
C{False} if it's expected to be ANSI.
@type dwMaxSize: int
@param dwMaxSize: Maximum allowed string length to read, in bytes.
@rtype: str, compat.unicode
@return: String read from the process memory space.
It B{doesn't} include the terminating null character.
Returns an empty string on failure. | 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]
if len(packed) == ptrSize:
address = struct.unpack(ptrFmt, packed)[0]
## if not address & (~0xFFFF): continue
peek_data = self.peek(address, peekSize)
if peek_data:
result[i] = peek_data
return result | 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.
@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.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, the memory could still be allocated somewhere
else.
@rtype: int
@return: Address of the newly allocated memory.
@raise WindowsError: On error an exception is raised. | 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 flNewProtect: int
@param flNewProtect: New protect flags.
@rtype: int
@return: Old protect flags.
@raise WindowsError: On error an exception is raised. | 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.MemoryBasicInformation}
@return: Memory region information.
@raise WindowsError: On error an exception is raised. | 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 exception is raised. | 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 or data pointer.
@raise WindowsError: An exception is raised on error. | 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 exception is raised on error. | 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: An exception is raised on error. | 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: An exception is raised on error. | 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 exception is raised on error. | 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:
C{True} if the address belongs to a commited and readable page.
@raise WindowsError: An exception is raised on error. | 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:
C{True} if the address belongs to a commited and writeable page.
@raise WindowsError: An exception is raised on error. | 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:
C{True} if the address belongs to a commited, copy-on-write page.
@raise WindowsError: An exception is raised on error. | 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:
C{True} if the address belongs to a commited and executable page.
@raise WindowsError: An exception is raised on error. | 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.
@type address: int
@param address: Memory address to query.
@rtype: bool
@return:
C{True} if the address belongs to a commited, writeable and
executable page.
@raise WindowsError: An exception is raised on error. | 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_PARAMETER:
return False
raise
if not mbi.has_content():
return False
size = size - mbi.RegionSize
return True | 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.
@rtype: bool
@return: C{True} if the memory area is a valid code or data buffer,
C{False} otherwise.
@raise ValueError: The size argument must be greater than zero.
@raise WindowsError: On error an exception is raised. | 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 = sys.exc_info()[1]
if e.winerror == win32.ERROR_INVALID_PARAMETER:
break
raise
yield mbi
prevAddr = currentAddr
currentAddr = mbi.BaseAddress + mbi.RegionSize | 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: (Optional) Ending address in address range to query.
@rtype: iterator of L{win32.MemoryBasicInformation}
@return: List of memory region information objects. | 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_IMAGE, win32.MEM_MAPPED):
continue
baseAddress = mbi.BaseAddress
fileName = ""
try:
fileName = win32.GetMappedFileName(hProcess, baseAddress)
fileName = PathOperations.native_to_win32_pathname(fileName)
except WindowsError:
#e = sys.exc_info()[1]
#try:
# msg = "Can't get mapped file name at address %s in process " \
# "%d, reason: %s" % (HexDump.address(baseAddress),
# self.get_pid(),
# e.strerror)
# warnings.warn(msg, Warning)
#except Exception:
pass
mappedFilenames[baseAddress] = fileName
return mappedFilenames | 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 )
@return: Dictionary mapping memory addresses to file names.
Native filenames are converted to Win32 filenames when possible. | 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 suspend the process if needed.
# Get the memory map.
memory = self.get_memory_map(minAddr, maxAddr)
# Abort if the map couldn't be retrieved.
if not memory:
return
# Get the mapped filenames.
# Don't fail on access denied errors.
try:
filenames = self.get_mapped_filenames(memory)
except WindowsError:
e = sys.exc_info()[1]
if e.winerror != win32.ERROR_ACCESS_DENIED:
raise
filenames = dict()
# Trim the first memory information block if needed.
if minAddr is not None:
minAddr = MemoryAddresses.align_address_to_page_start(minAddr)
mbi = memory[0]
if mbi.BaseAddress < minAddr:
mbi.RegionSize = mbi.BaseAddress + mbi.RegionSize - minAddr
mbi.BaseAddress = minAddr
# Trim the last memory information block if needed.
if maxAddr is not None:
if maxAddr != MemoryAddresses.align_address_to_page_start(maxAddr):
maxAddr = MemoryAddresses.align_address_to_page_end(maxAddr)
mbi = memory[-1]
if mbi.BaseAddress + mbi.RegionSize > maxAddr:
mbi.RegionSize = maxAddr - mbi.BaseAddress
# Read the contents of each block and yield it.
while memory:
mbi = memory.pop(0) # so the garbage collector can take it
mbi.filename = filenames.get(mbi.BaseAddress, None)
if mbi.has_content():
mbi.content = self.read(mbi.BaseAddress, mbi.RegionSize)
else:
mbi.content = None
yield mbi | 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 very
large snapshots without a significant performance penalty.
Example::
# Print the memory contents of a process.
process.suspend()
try:
snapshot = process.generate_memory_snapshot()
for mbi in snapshot:
print HexDump.hexblock(mbi.content, mbi.BaseAddress)
finally:
process.resume()
The downside of this is the process must remain suspended while
iterating the snapshot, otherwise strange things may happen.
The snapshot can only iterated once. To be able to iterate indefinitely
call the L{generate_memory_snapshot} method instead.
You can also iterate the memory of a dead process, just as long as the
last open handle to it hasn't been closed.
@see: L{take_memory_snapshot}
@type minAddr: int
@param minAddr: (Optional) Starting address in address range to query.
@type maxAddr: int
@param maxAddr: (Optional) Ending address in address range to query.
@rtype: iterator of L{win32.MemoryBasicInformation}
@return: Iterator of memory region information objects.
Two extra properties are added to these objects:
- C{filename}: Mapped filename, or C{None}.
- C{content}: Memory contents, or C{None}. | 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.
hProcess = self.get_handle( win32.PROCESS_VM_WRITE |
win32.PROCESS_VM_OPERATION |
win32.PROCESS_SUSPEND_RESUME |
win32.PROCESS_QUERY_INFORMATION )
# Freeze the process.
self.suspend()
try:
# For each memory region in the snapshot...
for old_mbi in snapshot:
# If the region matches, restore it directly.
new_mbi = self.mquery(old_mbi.BaseAddress)
if new_mbi.BaseAddress == old_mbi.BaseAddress and \
new_mbi.RegionSize == old_mbi.RegionSize:
self.__restore_mbi(hProcess, new_mbi, old_mbi,
bSkipMappedFiles)
# If the region doesn't match, restore it page by page.
else:
# We need a copy so we don't corrupt the snapshot.
old_mbi = win32.MemoryBasicInformation(old_mbi)
# Get the overlapping range of pages.
old_start = old_mbi.BaseAddress
old_end = old_start + old_mbi.RegionSize
new_start = new_mbi.BaseAddress
new_end = new_start + new_mbi.RegionSize
if old_start > new_start:
start = old_start
else:
start = new_start
if old_end < new_end:
end = old_end
else:
end = new_end
# Restore each page in the overlapping range.
step = MemoryAddresses.pageSize
old_mbi.RegionSize = step
new_mbi.RegionSize = step
address = start
while address < end:
old_mbi.BaseAddress = address
new_mbi.BaseAddress = address
self.__restore_mbi(hProcess, new_mbi, old_mbi,
bSkipMappedFiles, bSkipOnError)
address = address + step
# Resume execution.
finally:
self.resume() | 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).
@type snapshot: list( L{win32.MemoryBasicInformation} )
@param snapshot: Memory snapshot returned by L{take_memory_snapshot}.
Snapshots returned by L{generate_memory_snapshot} don't work here.
@type bSkipMappedFiles: bool
@param bSkipMappedFiles: C{True} to avoid restoring the contents of
memory mapped files, C{False} otherwise. Use with care! Setting
this to C{False} can cause undesired side effects - changes to
memory mapped files may be written to disk by the OS. Also note
that most mapped files are typically executables and don't change,
so trying to restore their contents is usually a waste of time.
@type bSkipOnError: bool
@param bSkipOnError: C{True} to issue a warning when an error occurs
during the restoration of the snapshot, C{False} to stop and raise
an exception instead. Use with care! Setting this to C{True} will
cause the debugger to falsely believe the memory snapshot has been
correctly restored.
@raise WindowsError: An error occured while restoring the snapshot.
@raise RuntimeError: An error occured while restoring the snapshot.
@raise TypeError: A snapshot of the wrong type was passed. | 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.
self.write(lpStartAddress, payload)
# Start a new thread for the shellcode to run.
aThread = self.start_thread(lpStartAddress, lpParameter,
bSuspended = False)
# Remember the shellcode address.
# It will be freed ONLY by the Thread.kill() method
# and the EventHandler class, otherwise you'll have to
# free it in your code, or have your shellcode clean up
# after itself (recommended).
aThread.pInjectedMemory = lpStartAddress
# Free the memory on error.
except Exception:
self.free(lpStartAddress)
raise
# Return the Thread object and the shellcode address.
return aThread, lpStartAddress | 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 in a new thread.
@type lpParameter: int
@param lpParameter: (Optional) Parameter to be pushed in the stack.
@rtype: tuple( L{Thread}, int )
@return: The injected Thread object
and the memory address where the code was written.
@raise WindowsError: An exception is raised on error. | 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 code.
@type bWait: bool
@param bWait: C{True} to wait for the process to finish.
C{False} to return immediately.
@type dwTimeout: int
@param dwTimeout: (Optional) Timeout value in milliseconds.
Ignored if C{bWait} is C{False}.
@raise WindowsError: An exception is raised on error. | 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{False} otherwise. | 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 in Windows 2003, Vista and above.
try:
hThread = win32.OpenThread(
win32.THREAD_QUERY_LIMITED_INFORMATION, False, dwThreadId)
except WindowsError:
e = sys.exc_info()[1]
if e.winerror != win32.ERROR_ACCESS_DENIED:
raise
hThread = win32.OpenThread(
win32.THREAD_QUERY_INFORMATION, False, dwThreadId)
try:
return win32.GetProcessIdOfThread(hThread)
finally:
hThread.close()
# If all else fails, go through all processes in the snapshot
# looking for the one that owns the thread we're looking for.
# If the snapshot was empty the iteration should trigger an
# automatic scan. Otherwise, it'll look for the thread in what
# could possibly be an outdated snapshot.
except Exception:
for aProcess in self.iter_processes():
if aProcess.has_thread(dwThreadId):
return aProcess.get_pid()
# The thread wasn't found, so let's refresh the snapshot and retry.
# Normally this shouldn't happen since this function is only useful
# for the debugger, so the thread should already exist in the snapshot.
self.scan_processes_and_threads()
for aProcess in self.iter_processes():
if aProcess.has_thread(dwThreadId):
return aProcess.get_pid()
# No luck! It appears to be the thread doesn't exist after all.
msg = "Unknown thread ID %d" % dwThreadId
raise KeyError(msg) | 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 \
'\n' in token or \
'\r' in token:
token = '"%s"' % token
cmdline.append(token)
return ' '.join(cmdline) | 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)
if exp_list:
return exp_list[0][0].get_pid()
return None | 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 only.
self.scan_processes_fast()
# Now try using the Toolhelp again to get the threads.
for aProcess in self.__processDict.values():
if aProcess._get_thread_ids():
try:
aProcess.scan_threads()
except WindowsError:
has_threads = False
finally:
# Try using the Remote Desktop API to scan for processes only.
# This will update the filenames when it's not possible
# to obtain them from the Toolhelp API.
self.scan_processes()
# When finished scanning for processes, try modules too.
has_modules = self.scan_modules()
# Try updating the process filenames when possible.
has_full_names = self.scan_process_filenames()
# Return the completion status.
return has_threads and has_modules and has_full_names | 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{True} if the snapshot is complete, C{False} if the debugger
doesn't have permission to scan some processes. In either case, the
snapshot is complete for all processes the debugger has access to. | 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 = set()
# Ignore our own process if it's in the snapshot for some reason
if our_pid in dead_pids:
dead_pids.remove(our_pid)
# Take a snapshot of all processes and threads
dwFlags = win32.TH32CS_SNAPPROCESS | win32.TH32CS_SNAPTHREAD
with win32.CreateToolhelp32Snapshot(dwFlags) as hSnapshot:
# Add all the processes (excluding our own)
pe = win32.Process32First(hSnapshot)
while pe is not None:
dwProcessId = pe.th32ProcessID
if dwProcessId != our_pid:
if dwProcessId in dead_pids:
dead_pids.remove(dwProcessId)
if dwProcessId not in self.__processDict:
aProcess = Process(dwProcessId, fileName=pe.szExeFile)
self._add_process(aProcess)
elif pe.szExeFile:
aProcess = self.get_process(dwProcessId)
if not aProcess.fileName:
aProcess.fileName = pe.szExeFile
pe = win32.Process32Next(hSnapshot)
# Add all the threads
te = win32.Thread32First(hSnapshot)
while te is not None:
dwProcessId = te.th32OwnerProcessID
if dwProcessId != our_pid:
if dwProcessId in dead_pids:
dead_pids.remove(dwProcessId)
if dwProcessId in self.__processDict:
aProcess = self.get_process(dwProcessId)
else:
aProcess = Process(dwProcessId)
self._add_process(aProcess)
dwThreadId = te.th32ThreadID
found_tids.add(dwThreadId)
if not aProcess._has_thread_id(dwThreadId):
aThread = Thread(dwThreadId, process = aProcess)
aProcess._add_thread(aThread)
te = win32.Thread32Next(hSnapshot)
# Remove dead processes
for pid in dead_pids:
self._del_process(pid)
# Remove dead threads
for aProcess in compat.itervalues(self.__processDict):
dead_tids = set( aProcess._get_thread_ids() )
dead_tids.difference_update(found_tids)
for tid in dead_tids:
aProcess._del_thread(tid) | 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.
The snapshot was not modified. | 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{False} if the debugger
doesn't have permission to scan some processes. In either case, the
snapshot is complete for all processes the debugger has access to. | 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(our_pid)
# Get the list of processes from the Remote Desktop API.
pProcessInfo = None
try:
pProcessInfo, dwCount = win32.WTSEnumerateProcesses(
win32.WTS_CURRENT_SERVER_HANDLE)
# For each process found...
for index in compat.xrange(dwCount):
sProcessInfo = pProcessInfo[index]
## # Ignore processes belonging to other sessions.
## if sProcessInfo.SessionId != win32.WTS_CURRENT_SESSION:
## continue
# Ignore our own PID.
pid = sProcessInfo.ProcessId
if pid == our_pid:
continue
# Remove the PID from the dead PIDs list.
if pid in dead_pids:
dead_pids.remove(pid)
# Get the "process name".
# Empirically, this seems to be the filename without the path.
# (The MSDN docs aren't very clear about this API call).
fileName = sProcessInfo.pProcessName
# If the process is new, add a new Process object.
if pid not in self.__processDict:
aProcess = Process(pid, fileName = fileName)
self._add_process(aProcess)
# If the process was already in the snapshot, and the
# filename is missing, update the Process object.
elif fileName:
aProcess = self.__processDict.get(pid)
if not aProcess.fileName:
aProcess.fileName = fileName
# Free the memory allocated by the Remote Desktop API.
finally:
if pProcessInfo is not None:
try:
win32.WTSFreeMemory(pProcessInfo)
except WindowsError:
pass
# At this point the only remaining PIDs from the old list are dead.
# Remove them from the snapshot.
for pid in dead_pids:
self._del_process(pid) | 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
current process does not have full privileges.
@note: This method will only retrieve process filenames. To get the
process pathnames instead, B{after} this method call
L{scan_process_filenames}.
@raise WindowsError: An error occured while updating the snapshot.
The snapshot was not modified. | 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 our_pid in old_pids:
old_pids.remove(our_pid)
# Add newly found pids
for pid in new_pids.difference(old_pids):
self._add_process( Process(pid) )
# Remove missing pids
for pid in old_pids.difference(new_pids):
self._del_process(pid) | 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 method uses the PSAPI. It may be faster for scanning,
but some information may be missing, outdated or slower to obtain.
This could be a good tradeoff under some circumstances. | 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()
finally:
if not new_name:
aProcess.fileName = old_name
complete = False
except Exception:
complete = False
return complete | 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 component.
If unsure, use L{scan} instead.
@see: L{scan}, L{Process.get_filename}
@rtype: bool
@return: C{True} if all the pathnames were retrieved, C{False} if the
debugger doesn't have permission to scan some processes. In either
case, all processes the debugger has access to have a full pathname
instead of just a filename. | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.