id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
177,072
from _pydev_bundle import pydev_log from _pydevd_bundle.pydevd_constants import DebugInfoHolder, IS_WINDOWS, IS_JYTHON, \ DISABLE_FILE_VALIDATION, is_true_in_env, IS_MAC from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding from _pydevd_bundle.pydevd_comm_constants import file_system_encoding, filesystem_encoding_is_utf8 from _pydev_bundle.pydev_log import error_once import json import os.path import sys import itertools import ntpath from functools import partial _client_filename_in_utf8_to_source_reference = {} def get_client_filename_source_reference(client_filename): return _client_filename_in_utf8_to_source_reference.get(client_filename, 0)
null
177,073
from _pydev_bundle import pydev_log from _pydevd_bundle.pydevd_constants import DebugInfoHolder, IS_WINDOWS, IS_JYTHON, \ DISABLE_FILE_VALIDATION, is_true_in_env, IS_MAC from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding from _pydevd_bundle.pydevd_comm_constants import file_system_encoding, filesystem_encoding_is_utf8 from _pydev_bundle.pydev_log import error_once import json import os.path import sys import itertools import ntpath from functools import partial _source_reference_to_server_filename = {} def get_server_filename_from_source_reference(source_reference): return _source_reference_to_server_filename.get(source_reference, '')
null
177,074
from _pydev_bundle import pydev_log from _pydevd_bundle.pydevd_constants import DebugInfoHolder, IS_WINDOWS, IS_JYTHON, \ DISABLE_FILE_VALIDATION, is_true_in_env, IS_MAC from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding from _pydevd_bundle.pydevd_comm_constants import file_system_encoding, filesystem_encoding_is_utf8 from _pydev_bundle.pydev_log import error_once import json import os.path import sys import itertools import ntpath from functools import partial _line_cache_source_reference_to_server_filename = {} _next_source_reference = partial(next, itertools.count(1)) def create_source_reference_for_linecache(server_filename): source_reference = _next_source_reference() pydev_log.debug('Created linecache id source reference: %s for server filename: %s', source_reference, server_filename) _line_cache_source_reference_to_server_filename[source_reference] = server_filename return source_reference
null
177,075
from _pydev_bundle import pydev_log from _pydevd_bundle.pydevd_constants import DebugInfoHolder, IS_WINDOWS, IS_JYTHON, \ DISABLE_FILE_VALIDATION, is_true_in_env, IS_MAC from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding from _pydevd_bundle.pydevd_comm_constants import file_system_encoding, filesystem_encoding_is_utf8 from _pydev_bundle.pydev_log import error_once import json import os.path import sys import itertools import ntpath from functools import partial _line_cache_source_reference_to_server_filename = {} def get_source_reference_filename_from_linecache(source_reference): return _line_cache_source_reference_to_server_filename.get(source_reference)
null
177,076
from _pydev_bundle import pydev_log from _pydevd_bundle.pydevd_constants import DebugInfoHolder, IS_WINDOWS, IS_JYTHON, \ DISABLE_FILE_VALIDATION, is_true_in_env, IS_MAC from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding from _pydevd_bundle.pydevd_comm_constants import file_system_encoding, filesystem_encoding_is_utf8 from _pydev_bundle.pydev_log import error_once import json import os.path import sys import itertools import ntpath from functools import partial _source_reference_to_frame_id = {} _next_source_reference = partial(next, itertools.count(1)) def create_source_reference_for_frame_id(frame_id, original_filename): source_reference = _next_source_reference() pydev_log.debug('Created frame id source reference: %s for frame id: %s (%s)', source_reference, frame_id, original_filename) _source_reference_to_frame_id[source_reference] = frame_id return source_reference
null
177,077
from _pydev_bundle import pydev_log from _pydevd_bundle.pydevd_constants import DebugInfoHolder, IS_WINDOWS, IS_JYTHON, \ DISABLE_FILE_VALIDATION, is_true_in_env, IS_MAC from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding from _pydevd_bundle.pydevd_comm_constants import file_system_encoding, filesystem_encoding_is_utf8 from _pydev_bundle.pydev_log import error_once import json import os.path import sys import itertools import ntpath from functools import partial _source_reference_to_frame_id = {} def get_frame_id_from_source_reference(source_reference): return _source_reference_to_frame_id.get(source_reference)
null
177,078
from _pydev_bundle import pydev_log from _pydevd_bundle.pydevd_constants import DebugInfoHolder, IS_WINDOWS, IS_JYTHON, \ DISABLE_FILE_VALIDATION, is_true_in_env, IS_MAC from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding from _pydevd_bundle.pydevd_comm_constants import file_system_encoding, filesystem_encoding_is_utf8 from _pydev_bundle.pydev_log import error_once import json import os.path import sys import itertools import ntpath from functools import partial _global_resolve_symlinks = is_true_in_env('PYDEVD_RESOLVE_SYMLINKS') def set_resolve_symlinks(resolve_symlinks): global _global_resolve_symlinks _global_resolve_symlinks = resolve_symlinks
null
177,079
from _pydev_bundle import pydev_log from _pydevd_bundle.pydevd_constants import DebugInfoHolder, IS_WINDOWS, IS_JYTHON, \ DISABLE_FILE_VALIDATION, is_true_in_env, IS_MAC from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding from _pydevd_bundle.pydevd_comm_constants import file_system_encoding, filesystem_encoding_is_utf8 from _pydev_bundle.pydev_log import error_once import json import os.path import sys import itertools import ntpath from functools import partial join = os.path.join if sys.platform == 'win32': try: import ctypes from ctypes.wintypes import MAX_PATH, LPCWSTR, LPWSTR, DWORD GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW # noqa GetLongPathName.argtypes = [LPCWSTR, LPWSTR, DWORD] GetLongPathName.restype = DWORD GetShortPathName = ctypes.windll.kernel32.GetShortPathNameW # noqa GetShortPathName.argtypes = [LPCWSTR, LPWSTR, DWORD] GetShortPathName.restype = DWORD # Check that it actually works _get_path_with_real_case(__file__) except: # Something didn't quite work out, leave no-op conversions in place. if DebugInfoHolder.DEBUG_TRACE_LEVEL > 2: pydev_log.exception() else: convert_to_long_pathname = _convert_to_long_pathname convert_to_short_pathname = _convert_to_short_pathname get_path_with_real_case = _get_path_with_real_case elif IS_JYTHON and IS_WINDOWS: elif IS_MAC: def get_package_dir(mod_name): for path in sys.path: mod_path = join(path, mod_name.replace('.', '/')) if os.path.isdir(mod_path): return mod_path return None
null
177,080
import sys import os def process_command_line(argv): setup = {} setup['port'] = 5678 # Default port for PyDev remote debugger setup['pid'] = 0 setup['host'] = '127.0.0.1' setup['protocol'] = '' setup['debug-mode'] = '' i = 0 while i < len(argv): if argv[i] == '--port': del argv[i] setup['port'] = int(argv[i]) del argv[i] elif argv[i] == '--pid': del argv[i] setup['pid'] = int(argv[i]) del argv[i] elif argv[i] == '--host': del argv[i] setup['host'] = argv[i] del argv[i] elif argv[i] == '--protocol': del argv[i] setup['protocol'] = argv[i] del argv[i] elif argv[i] == '--debug-mode': del argv[i] setup['debug-mode'] = argv[i] del argv[i] if not setup['pid']: sys.stderr.write('Expected --pid to be passed.\n') sys.exit(1) return setup
null
177,081
import sys import struct import os import threading def loop_in_thread(): while True: import time time.sleep(.5) sys.stdout.write('#') sys.stdout.flush()
null
177,082
import sys import struct import os import threading def is_python_64bit(): return (struct.calcsize('P') == 8)
null
177,083
import ctypes import os import struct import subprocess import sys import time from contextlib import contextmanager import platform import traceback def _create_win_event(name): from winappdbg.win32.kernel32 import CreateEventA, WaitForSingleObject, CloseHandle manual_reset = False # i.e.: after someone waits it, automatically set to False. initial_state = False if not isinstance(name, bytes): name = name.encode('utf-8') event = CreateEventA(None, manual_reset, initial_state, name) if not event: raise ctypes.WinError() class _WinEvent(object): def wait_for_event_set(self, timeout=None): ''' :param timeout: in seconds ''' if timeout is None: timeout = 0xFFFFFFFF else: timeout = int(timeout * 1000) ret = WaitForSingleObject(event, timeout) if ret in (0, 0x80): return True elif ret == 0x102: # Timed out return False else: raise ctypes.WinError() try: yield _WinEvent() finally: CloseHandle(event) def is_python_64bit(): return (struct.calcsize('P') == 8) def get_target_filename(is_target_process_64=None, prefix=None, extension=None): # Note: we have an independent (and similar -- but not equal) version of this method in # `pydevd_tracing.py` which should be kept synchronized with this one (we do a copy # because the `pydevd_attach_to_process` is mostly independent and shouldn't be imported in the # debugger -- the only situation where it's imported is if the user actually does an attach to # process, through `attach_pydevd.py`, but this should usually be called from the IDE directly # and not from the debugger). libdir = os.path.dirname(__file__) if is_target_process_64 is None: if IS_WINDOWS: # i.e.: On windows the target process could have a different bitness (32bit is emulated on 64bit). raise AssertionError("On windows it's expected that the target bitness is specified.") # For other platforms, just use the the same bitness of the process we're running in. is_target_process_64 = is_python_64bit() arch = '' if IS_WINDOWS: # prefer not using platform.machine() when possible (it's a bit heavyweight as it may # spawn a subprocess). arch = os.environ.get("PROCESSOR_ARCHITEW6432", os.environ.get('PROCESSOR_ARCHITECTURE', '')) if not arch: arch = platform.machine() if not arch: print('platform.machine() did not return valid value.') # This shouldn't happen... return None if IS_WINDOWS: if not extension: extension = '.dll' suffix_64 = 'amd64' suffix_32 = 'x86' elif IS_LINUX: if not extension: extension = '.so' suffix_64 = 'amd64' suffix_32 = 'x86' elif IS_MAC: if not extension: extension = '.dylib' suffix_64 = 'x86_64' suffix_32 = 'x86' else: print('Unable to attach to process in platform: %s', sys.platform) return None if arch.lower() not in ('amd64', 'x86', 'x86_64', 'i386', 'x86'): # We don't support this processor by default. Still, let's support the case where the # user manually compiled it himself with some heuristics. # # Ideally the user would provide a library in the format: "attach_<arch>.<extension>" # based on the way it's currently compiled -- see: # - windows/compile_windows.bat # - linux_and_mac/compile_linux.sh # - linux_and_mac/compile_mac.sh try: found = [name for name in os.listdir(libdir) if name.startswith('attach_') and name.endswith(extension)] except: print('Error listing dir: %s' % (libdir,)) traceback.print_exc() return None if prefix: expected_name = prefix + arch + extension expected_name_linux = prefix + 'linux_' + arch + extension else: # Default is looking for the attach_ / attach_linux expected_name = 'attach_' + arch + extension expected_name_linux = 'attach_linux_' + arch + extension filename = None if expected_name in found: # Heuristic: user compiled with "attach_<arch>.<extension>" filename = os.path.join(libdir, expected_name) elif IS_LINUX and expected_name_linux in found: # Heuristic: user compiled with "attach_linux_<arch>.<extension>" filename = os.path.join(libdir, expected_name_linux) elif len(found) == 1: # Heuristic: user removed all libraries and just left his own lib. filename = os.path.join(libdir, found[0]) else: # Heuristic: there's one additional library which doesn't seem to be our own. Find the odd one. filtered = [name for name in found if not name.endswith((suffix_64 + extension, suffix_32 + extension))] if len(filtered) == 1: # If more than one is available we can't be sure... filename = os.path.join(libdir, found[0]) if filename is None: print( 'Unable to attach to process in arch: %s (did not find %s in %s).' % ( arch, expected_name, libdir ) ) return None print('Using %s in arch: %s.' % (filename, arch)) else: if is_target_process_64: suffix = suffix_64 else: suffix = suffix_32 if not prefix: # Default is looking for the attach_ / attach_linux if IS_WINDOWS or IS_MAC: # just the extension changes prefix = 'attach_' elif IS_LINUX: prefix = 'attach_linux_' # historically it has a different name else: print('Unable to attach to process in platform: %s' % (sys.platform,)) return None filename = os.path.join(libdir, '%s%s%s' % (prefix, suffix, extension)) if not os.path.exists(filename): print('Expected: %s to exist.' % (filename,)) return None return filename def _acquire_mutex(mutex_name, timeout): ''' Only one process may be attaching to a pid, so, create a system mutex to make sure this holds in practice. ''' from winappdbg.win32.kernel32 import CreateMutex, GetLastError, CloseHandle from winappdbg.win32.defines import ERROR_ALREADY_EXISTS initial_time = time.time() while True: mutex = CreateMutex(None, True, mutex_name) acquired = GetLastError() != ERROR_ALREADY_EXISTS if acquired: break if time.time() - initial_time > timeout: raise TimeoutError('Unable to acquire mutex to make attach before timeout.') time.sleep(.2) try: yield finally: CloseHandle(mutex) def _win_write_to_shared_named_memory(python_code, pid): # Use the definitions from winappdbg when possible. from winappdbg.win32 import defines from winappdbg.win32.kernel32 import ( CreateFileMapping, MapViewOfFile, CloseHandle, UnmapViewOfFile, ) memmove = ctypes.cdll.msvcrt.memmove memmove.argtypes = [ ctypes.c_void_p, ctypes.c_void_p, defines.SIZE_T, ] memmove.restype = ctypes.c_void_p # Note: BUFSIZE must be the same from run_code_in_memory.hpp BUFSIZE = 2048 assert isinstance(python_code, bytes) assert len(python_code) > 0, 'Python code must not be empty.' # Note: -1 so that we're sure we'll add a \0 to the end. assert len(python_code) < BUFSIZE - 1, 'Python code must have at most %s bytes (found: %s)' % (BUFSIZE - 1, len(python_code)) python_code += b'\0' * (BUFSIZE - len(python_code)) assert python_code.endswith(b'\0') INVALID_HANDLE_VALUE = -1 PAGE_READWRITE = 0x4 FILE_MAP_WRITE = 0x2 filemap = CreateFileMapping( INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, BUFSIZE, u"__pydevd_pid_code_to_run__%s" % (pid,)) if filemap == INVALID_HANDLE_VALUE or filemap is None: raise Exception("Failed to create named file mapping (ctypes: CreateFileMapping): %s" % (filemap,)) try: view = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, 0) if not view: raise Exception("Failed to create view of named file mapping (ctypes: MapViewOfFile).") try: memmove(view, python_code, BUFSIZE) yield finally: UnmapViewOfFile(view) finally: CloseHandle(filemap) class Process (_ThreadContainer, _ModuleContainer): """ Interface to a process. Contains threads and modules snapshots. get_pid, is_alive, is_debugged, is_wow64, get_arch, get_bits, get_filename, get_exit_code, get_start_time, get_exit_time, get_running_time, get_services, get_dep_policy, get_peb, get_peb_address, get_entry_point, get_main_module, get_image_base, get_image_name, get_command_line, get_environment, get_command_line_block, get_environment_block, get_environment_variables, get_handle, open_handle, close_handle kill, wait, suspend, resume, inject_code, inject_dll, clean_exit disassemble, disassemble_around, disassemble_around_pc, disassemble_string, disassemble_instruction, disassemble_current flush_instruction_cache, debug_break, peek_pointers_in_data take_memory_snapshot, generate_memory_snapshot, iter_memory_snapshot, restore_memory_snapshot, get_memory_map, get_mapped_filenames, generate_memory_map, iter_memory_map, is_pointer, is_address_valid, is_address_free, is_address_reserved, is_address_commited, is_address_guard, is_address_readable, is_address_writeable, is_address_copy_on_write, is_address_executable, is_address_executable_and_writeable, is_buffer, is_buffer_readable, is_buffer_writeable, is_buffer_executable, is_buffer_executable_and_writeable, is_buffer_copy_on_write malloc, free, mprotect, mquery read, read_char, read_int, read_uint, read_float, read_double, read_dword, read_qword, read_pointer, read_string, read_structure, peek, peek_char, peek_int, peek_uint, peek_float, peek_double, peek_dword, peek_qword, peek_pointer, peek_string write, write_char, write_int, write_uint, write_float, write_double, write_dword, write_qword, write_pointer, poke, poke_char, poke_int, poke_uint, poke_float, poke_double, poke_dword, poke_qword, poke_pointer search, search_bytes, search_hexa, search_text, search_regexp, strings scan, clear, __contains__, __iter__, __len__ get_environment_data, parse_environment_data """ def __init__(self, dwProcessId, hProcess = None, fileName = None): """ """ _ThreadContainer.__init__(self) _ModuleContainer.__init__(self) self.dwProcessId = dwProcessId self.hProcess = hProcess self.fileName = fileName def get_pid(self): """ """ return self.dwProcessId def get_filename(self): """ """ if not self.fileName: self.fileName = self.get_image_name() return self.fileName 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. "smarter" and tries to reuse handles and merge 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} 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. """ 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 close_handle(self): """ Closes the handle to the process. 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. """ 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 get_handle(self, dwDesiredAccess = win32.PROCESS_ALL_ACCESS): """ Returns a handle to the process with I{at least} the access rights requested. 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. Defaults to L{win32.PROCESS_ALL_ACCESS}. See: U{http://msdn.microsoft.com/en-us/library/windows/desktop/ms684880(v=vs.85).aspx} 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. """ 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 #------------------------------------------------------------------------------ # Not really sure if it's a good idea... ## def __eq__(self, aProcess): ## """ ## Compare two Process objects. The comparison is made using the IDs. ## ## @warning: ## If you have two Process instances with different handles the ## equality operator still returns C{True}, so be careful! ## ## @type aProcess: L{Process} ## @param aProcess: Another Process object. ## ## @rtype: bool ## @return: C{True} if the two process IDs are equal, ## C{False} otherwise. ## """ ## return isinstance(aProcess, Process) and \ ## self.get_pid() == aProcess.get_pid() def __contains__(self, anObject): """ The same as: C{self.has_thread(anObject) or self.has_module(anObject)} Can be a Thread, Module, thread global ID or module base address. """ return _ThreadContainer.__contains__(self, anObject) or \ _ModuleContainer.__contains__(self, anObject) def __len__(self): """ """ return _ThreadContainer.__len__(self) + \ _ModuleContainer.__len__(self) class __ThreadsAndModulesIterator (object): """ Iterator object for L{Process} objects. Iterates through L{Thread} objects first, L{Module} objects next. """ def __init__(self, container): """ """ self.__container = container self.__iterator = None self.__state = 0 def __iter__(self): 'x.__iter__() <==> iter(x)' return self def next(self): 'x.next() -> the next value, or raise StopIteration' if self.__state == 0: self.__iterator = self.__container.iter_threads() self.__state = 1 if self.__state == 1: try: return self.__iterator.next() except StopIteration: self.__iterator = self.__container.iter_modules() self.__state = 2 if self.__state == 2: try: return self.__iterator.next() except StopIteration: self.__iterator = None self.__state = 3 raise StopIteration def __iter__(self): """ All threads are iterated first, then all modules. """ return self.__ThreadsAndModulesIterator(self) #------------------------------------------------------------------------------ def wait(self, dwTimeout = None): """ Waits for the process to finish executing. """ self.get_handle(win32.SYNCHRONIZE).wait(dwTimeout) def kill(self, dwExitCode = 0): """ Terminates the execution of the process. """ hProcess = self.get_handle(win32.PROCESS_TERMINATE) win32.TerminateProcess(hProcess, dwExitCode) def suspend(self): """ Suspends execution on all threads of the process. """ 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 resume(self): """ Resumes execution on all threads of the process. """ 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 is_debugged(self): """ Tries to determine if the process is being debugged by another process. It may detect other debuggers besides WinAppDbg. May return inaccurate results when some anti-debug techniques are used by the target process. object, call L{Debug.is_debugee} instead. """ # 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_alive(self): """ """ try: self.wait(0) except WindowsError: e = sys.exc_info()[1] return e.winerror == win32.WAIT_TIMEOUT return False def get_exit_code(self): """ 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. """ 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 scan(self): """ Populates the snapshot of threads and modules. """ self.scan_threads() self.scan_modules() def clear(self): """ Clears the snapshot of threads and modules. """ try: try: self.clear_threads() finally: self.clear_modules() finally: self.close_handle() #------------------------------------------------------------------------------ # Regular expression to find hexadecimal values of any size. __hexa_parameter = re.compile('0x[0-9A-Fa-f]+') 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. """ 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 disassemble_string(self, lpAddress, code): """ Disassemble instructions from a block of binary code. and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. No compatible disassembler was found for the current platform. """ try: disasm = self.__disasm except AttributeError: disasm = self.__disasm = Disassembler( self.get_arch() ) return disasm.decode(lpAddress, code) def disassemble(self, lpAddress, dwSize): """ Disassemble instructions from the address space of the process. and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. """ data = self.read(lpAddress, dwSize) disasm = self.disassemble_string(lpAddress, data) self.__fixup_labels(disasm) return disasm # FIXME # This algorithm really bad, I've got to write a better one :P def disassemble_around(self, lpAddress, dwSize = 64): """ Disassemble around the given address. Code will be read from lpAddress - dwSize to lpAddress + dwSize. and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. """ 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_pc(self, dwThreadId, dwSize = 64): """ Disassemble around the program counter of the given thread. The program counter for this thread will be used as the disassembly address. Code will be read from pc - dwSize to pc + dwSize. and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. """ aThread = self.get_thread(dwThreadId) return self.disassemble_around(aThread.get_pc(), dwSize) def disassemble_instruction(self, lpAddress): """ Disassemble the instruction at the given memory address. and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. """ return self.disassemble(lpAddress, 15)[0] def disassemble_current(self, dwThreadId): """ Disassemble the instruction at the program counter of the given thread. The program counter for this thread will be used as the disassembly address. and contains: - Memory address of instruction. - Size of instruction in bytes. - Disassembly line of instruction. - Hexadecimal dump of instruction. """ aThread = self.get_thread(dwThreadId) return self.disassemble_instruction(aThread.get_pc()) #------------------------------------------------------------------------------ def flush_instruction_cache(self): """ Flush the instruction cache. This is required if the process memory is modified and one or more threads are executing nearby the modified memory region. """ # FIXME # No idea what access rights are required here! # Maybe PROCESS_VM_OPERATION ??? # In any case we're only calling this from the debugger, # so it should be fine (we already have PROCESS_ALL_ACCESS). win32.FlushInstructionCache( self.get_handle() ) def debug_break(self): """ Triggers the system breakpoint in the process. """ # The exception is raised by a new thread. # When continuing the exception, the thread dies by itself. # This thread is hidden from the debugger. win32.DebugBreakProcess( self.get_handle() ) def is_wow64(self): """ Determines if the process is running under WOW64. 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. """ 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 get_arch(self): """ For example, if running a 32 bit binary in a 64 bit machine, the architecture returned by this method will be L{win32.ARCH_I386}, but the value of L{System.arch} will be L{win32.ARCH_AMD64}. """ # Are we in a 32 bit machine? if win32.bits == 32 and not win32.wow64: return win32.arch # Is the process outside of WOW64? if not self.is_wow64(): return win32.arch # In WOW64, "amd64" becomes "i386". if win32.arch == win32.ARCH_AMD64: return win32.ARCH_I386 # We don't know the translation for other architectures. raise NotImplementedError() def get_bits(self): """ running. For example, if running a 32 bit binary in a 64 bit machine, the number of bits returned by this method will be C{32}, but the value of L{System.arch} will be C{64}. """ # Are we in a 32 bit machine? if win32.bits == 32 and not win32.wow64: # All processes are 32 bits. return 32 # Is the process inside WOW64? if self.is_wow64(): # The process is 32 bits. return 32 # The process is 64 bits. return 64 # TODO: get_os, to test compatibility run # See: http://msdn.microsoft.com/en-us/library/windows/desktop/ms683224(v=vs.85).aspx #------------------------------------------------------------------------------ def get_start_time(self): """ Determines when has this process started running. """ 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_exit_time(self): """ Determines when has this process finished running. If the process is still alive, the current time is returned instead. """ 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_running_time(self): """ Determines how long has this process been running. """ 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 # 100 nanoseconds steps => milliseconds #------------------------------------------------------------------------------ def __load_System_class(self): global System # delayed import if System is None: from system import System def get_services(self): """ Retrieves the list of system services that are currently running in this process. """ self.__load_System_class() pid = self.get_pid() return [d for d in System.get_active_services() if d.ProcessId == pid] #------------------------------------------------------------------------------ def get_dep_policy(self): """ Retrieves the DEP (Data Execution Prevention) policy for this process. only for 32 bit processes. It will fail in any other circumstance. 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. """ 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_peb(self): """ Returns a copy of the PEB. To dereference pointers in it call L{Process.read_structure}. """ self.get_handle( win32.PROCESS_VM_READ | win32.PROCESS_QUERY_INFORMATION ) return self.read_structure(self.get_peb_address(), win32.PEB) def get_peb_address(self): """ Returns a remote pointer to the PEB. Returns C{None} on error. """ 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_entry_point(self): """ Alias to C{process.get_main_module().get_entry_point()}. """ return self.get_main_module().get_entry_point() def get_main_module(self): """ """ return self.get_module(self.get_image_base()) def get_image_base(self): """ """ return self.get_peb().ImageBaseAddress def get_image_name(self): """ This method does it's best to retrieve the filename. However sometimes this is not possible, so C{None} may be returned instead. """ # Method 1: Module.fileName # It's cached if the filename was already found by the other methods, # if it came with the corresponding debug event, or it was found by the # toolhelp API. mainModule = None try: mainModule = self.get_main_module() name = mainModule.fileName if not name: name = None except (KeyError, AttributeError, WindowsError): ## traceback.print_exc() # XXX DEBUG name = None # Method 2: QueryFullProcessImageName() # Not implemented until Windows Vista. if not name: try: hProcess = self.get_handle( win32.PROCESS_QUERY_LIMITED_INFORMATION) name = win32.QueryFullProcessImageName(hProcess) except (AttributeError, WindowsError): ## traceback.print_exc() # XXX DEBUG name = None # Method 3: GetProcessImageFileName() # # Not implemented until Windows XP. # For more info see: # https://voidnish.wordpress.com/2005/06/20/getprocessimagefilenamequerydosdevice-trivia/ if not name: try: hProcess = self.get_handle(win32.PROCESS_QUERY_INFORMATION) name = win32.GetProcessImageFileName(hProcess) if name: name = PathOperations.native_to_win32_pathname(name) else: name = None except (AttributeError, WindowsError): ## traceback.print_exc() # XXX DEBUG if not name: name = None # Method 4: GetModuleFileNameEx() # Not implemented until Windows 2000. # # May be spoofed by malware, since this information resides # in usermode space (see http://www.ragestorm.net/blogs/?p=163). if not name: try: hProcess = self.get_handle( win32.PROCESS_VM_READ | win32.PROCESS_QUERY_INFORMATION ) try: name = win32.GetModuleFileNameEx(hProcess) except WindowsError: ## traceback.print_exc() # XXX DEBUG name = win32.GetModuleFileNameEx( hProcess, self.get_image_base()) if name: name = PathOperations.native_to_win32_pathname(name) else: name = None except (AttributeError, WindowsError): ## traceback.print_exc() # XXX DEBUG if not name: name = None # Method 5: PEB.ProcessParameters->ImagePathName # # May fail since it's using an undocumented internal structure. # # May be spoofed by malware, since this information resides # in usermode space (see http://www.ragestorm.net/blogs/?p=163). if not name: try: peb = self.get_peb() pp = self.read_structure(peb.ProcessParameters, win32.RTL_USER_PROCESS_PARAMETERS) s = pp.ImagePathName name = self.peek_string(s.Buffer, dwMaxSize=s.MaximumLength, fUnicode=True) if name: name = PathOperations.native_to_win32_pathname(name) else: name = None except (AttributeError, WindowsError): ## traceback.print_exc() # XXX DEBUG name = None # Method 6: Module.get_filename() # It tries to get the filename from the file handle. # # There are currently some problems due to the strange way the API # works - it returns the pathname without the drive letter, and I # couldn't figure out a way to fix it. if not name and mainModule is not None: try: name = mainModule.get_filename() if not name: name = None except (AttributeError, WindowsError): ## traceback.print_exc() # XXX DEBUG name = None # Remember the filename. if name and mainModule is not None: mainModule.fileName = name # Return the image filename, or None on error. return name def get_command_line_block(self): """ Retrieves the command line block memory address and size. and it's maximum size in Unicode characters. """ 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_environment_block(self): """ Retrieves the environment block memory address for the process. 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. and it's size. """ 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_command_line(self): """ Retrieves the command line with wich the program was started. """ (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_environment_variables(self): """ Retrieves the environment variables with wich the program is running. """ # 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_data(self, fUnicode = None): """ Retrieves the environment block data with wich the program is running. to return a list of ANSI strings, or C{None} to return whatever the default is for string types. as found in the process memory. """ # 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 parse_environment_data(block): """ Parse the environment block into a Python dictionary. """ # 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 get_environment(self, fUnicode = None): """ Retrieves the environment with wich the program is running. 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())} to return a list of ANSI strings, or C{None} to return whatever the default is for string types. """ # 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 search(self, pattern, minAddr = None, maxAddr = None): """ Search for the given pattern within the process memory. 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. - The memory address where the pattern was found. - The size of the data that matches the pattern. - The data that matches the pattern. process memory. """ 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_bytes(self, bytes, minAddr = None, maxAddr = None): """ Search for the given byte pattern within the process memory. process memory. """ pattern = BytePattern(bytes) matches = Search.search_process(self, pattern, minAddr, maxAddr) for addr, size, data in matches: yield addr def search_text(self, text, encoding = "utf-16le", caseSensitive = False, minAddr = None, maxAddr = None): """ Search for the given text within the process memory. Only used when the text to search for is a Unicode string. Don't change unless you know what you're doing! C{False} otherwise. - The memory address where the pattern was found. - The text that matches the pattern. process memory. """ pattern = TextPattern(text, encoding, caseSensitive) matches = Search.search_process(self, pattern, minAddr, maxAddr) for addr, size, data in matches: yield addr, data def search_regexp(self, regexp, flags = 0, minAddr = None, maxAddr = None, bufferPages = -1): """ Search for the given regular expression within the process memory. 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. - The memory address where the pattern was found. - The size of the data that matches the pattern. - The data that matches the pattern. process memory. """ pattern = RegExpPattern(regexp, flags) return Search.search_process(self, pattern, minAddr, maxAddr, bufferPages) 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 - The memory address where the pattern was found. - The bytes that match the pattern. process memory. """ pattern = HexPattern(hexa) matches = Search.search_process(self, pattern, minAddr, maxAddr) for addr, size, data in matches: yield addr, data def strings(self, minSize = 4, maxSize = 1024): """ Extract ASCII strings from the process memory. Each tuple contains the following: - The memory address where the string was found. - The size of the string. - The string. """ return Search.extract_ascii_strings(self, minSize = minSize, maxSize = maxSize) #------------------------------------------------------------------------------ def __read_c_type(self, address, format, c_type): size = ctypes.sizeof(c_type) packed = self.read(address, size) if len(packed) != size: raise ctypes.WinError() return struct.unpack(format, packed)[0] def __write_c_type(self, address, format, unpacked): packed = struct.pack('@L', unpacked) self.write(address, packed) # XXX TODO # + Maybe change page permissions before trying to read? def read(self, lpBaseAddress, nSize): """ Reads from the memory of the process. """ 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 write(self, lpBaseAddress, lpBuffer): """ Writes to the memory of the process. """ r = self.poke(lpBaseAddress, lpBuffer) if r != len(lpBuffer): raise ctypes.WinError() def read_char(self, lpBaseAddress): """ Reads a single character to the memory of the process. """ return ord( self.read(lpBaseAddress, 1) ) def write_char(self, lpBaseAddress, char): """ Writes a single character to the memory of the process. """ self.write(lpBaseAddress, chr(char)) def read_int(self, lpBaseAddress): """ Reads a signed integer from the memory of the process. """ return self.__read_c_type(lpBaseAddress, compat.b('@l'), ctypes.c_int) def write_int(self, lpBaseAddress, unpackedValue): """ Writes a signed integer to the memory of the process. """ self.__write_c_type(lpBaseAddress, '@l', unpackedValue) def read_uint(self, lpBaseAddress): """ Reads an unsigned integer from the memory of the process. """ return self.__read_c_type(lpBaseAddress, '@L', ctypes.c_uint) def write_uint(self, lpBaseAddress, unpackedValue): """ Writes an unsigned integer to the memory of the process. """ self.__write_c_type(lpBaseAddress, '@L', unpackedValue) def read_float(self, lpBaseAddress): """ Reads a float from the memory of the process. """ return self.__read_c_type(lpBaseAddress, '@f', ctypes.c_float) def write_float(self, lpBaseAddress, unpackedValue): """ Writes a float to the memory of the process. """ self.__write_c_type(lpBaseAddress, '@f', unpackedValue) def read_double(self, lpBaseAddress): """ Reads a double from the memory of the process. """ return self.__read_c_type(lpBaseAddress, '@d', ctypes.c_double) def write_double(self, lpBaseAddress, unpackedValue): """ Writes a double to the memory of the process. """ self.__write_c_type(lpBaseAddress, '@d', unpackedValue) def read_pointer(self, lpBaseAddress): """ Reads a pointer value from the memory of the process. """ return self.__read_c_type(lpBaseAddress, '@P', ctypes.c_void_p) def write_pointer(self, lpBaseAddress, unpackedValue): """ Writes a pointer value to the memory of the process. """ self.__write_c_type(lpBaseAddress, '@P', unpackedValue) def read_dword(self, lpBaseAddress): """ Reads a DWORD from the memory of the process. """ return self.__read_c_type(lpBaseAddress, '=L', win32.DWORD) def write_dword(self, lpBaseAddress, unpackedValue): """ Writes a DWORD to the memory of the process. """ self.__write_c_type(lpBaseAddress, '=L', unpackedValue) def read_qword(self, lpBaseAddress): """ Reads a QWORD from the memory of the process. """ return self.__read_c_type(lpBaseAddress, '=Q', win32.QWORD) def write_qword(self, lpBaseAddress, unpackedValue): """ Writes a QWORD to the memory of the process. """ self.__write_c_type(lpBaseAddress, '=Q', unpackedValue) def read_structure(self, lpBaseAddress, stype): """ Reads a ctypes structure from the memory of the process. read from the process memory. """ 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 # XXX TODO ## def write_structure(self, lpBaseAddress, sStructure): ## """ ## Writes a ctypes structure into 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 sStructure: ctypes.Structure or a subclass' instance. ## @param sStructure: Structure definition. ## ## @rtype: int ## @return: Structure instance filled in with data ## read from the process memory. ## ## @raise WindowsError: On error an exception is raised. ## """ ## size = ctypes.sizeof(sStructure) ## data = ctypes.create_string_buffer("", size = size) ## win32.CopyMemory(ctypes.byref(data), ctypes.byref(sStructure), size) ## self.write(lpBaseAddress, data.raw) def read_string(self, lpBaseAddress, nChars, fUnicode = False): """ Reads an ASCII or Unicode string from the address space of the process. Remember that Unicode strings have two byte characters. C{False} if it's expected to be ANSI. """ if fUnicode: nChars = nChars * 2 szString = self.read(lpBaseAddress, nChars) if fUnicode: szString = compat.unicode(szString, 'U16', 'ignore') return szString #------------------------------------------------------------------------------ # FIXME this won't work properly with a different endianness! def __peek_c_type(self, address, format, c_type): size = ctypes.sizeof(c_type) packed = self.peek(address, size) if len(packed) < size: packed = '\0' * (size - len(packed)) + packed elif len(packed) > size: packed = packed[:size] return struct.unpack(format, packed)[0] def __poke_c_type(self, address, format, unpacked): packed = struct.pack('@L', unpacked) return self.poke(address, packed) def peek(self, lpBaseAddress, nSize): """ Reads the memory of the process. Returns an empty string on error. """ # 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 poke(self, lpBaseAddress, lpBuffer): """ Writes to the memory of the process. May be less than the number of bytes to write. """ 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 peek_char(self, lpBaseAddress): """ Reads a single character from the memory of the process. Returns zero on error. """ char = self.peek(lpBaseAddress, 1) if char: return ord(char) return 0 def poke_char(self, lpBaseAddress, char): """ Writes a single character to the memory of the process. May be less than the number of bytes to write. """ return self.poke(lpBaseAddress, chr(char)) def peek_int(self, lpBaseAddress): """ Reads a signed integer from the memory of the process. Returns zero on error. """ return self.__peek_c_type(lpBaseAddress, '@l', ctypes.c_int) def poke_int(self, lpBaseAddress, unpackedValue): """ Writes a signed integer to the memory of the process. May be less than the number of bytes to write. """ return self.__poke_c_type(lpBaseAddress, '@l', unpackedValue) def peek_uint(self, lpBaseAddress): """ Reads an unsigned integer from the memory of the process. Returns zero on error. """ return self.__peek_c_type(lpBaseAddress, '@L', ctypes.c_uint) def poke_uint(self, lpBaseAddress, unpackedValue): """ Writes an unsigned integer to the memory of the process. May be less than the number of bytes to write. """ return self.__poke_c_type(lpBaseAddress, '@L', unpackedValue) def peek_float(self, lpBaseAddress): """ Reads a float from the memory of the process. Returns zero on error. """ return self.__peek_c_type(lpBaseAddress, '@f', ctypes.c_float) def poke_float(self, lpBaseAddress, unpackedValue): """ Writes a float to the memory of the process. May be less than the number of bytes to write. """ return self.__poke_c_type(lpBaseAddress, '@f', unpackedValue) def peek_double(self, lpBaseAddress): """ Reads a double from the memory of the process. Returns zero on error. """ return self.__peek_c_type(lpBaseAddress, '@d', ctypes.c_double) def poke_double(self, lpBaseAddress, unpackedValue): """ Writes a double to the memory of the process. May be less than the number of bytes to write. """ return self.__poke_c_type(lpBaseAddress, '@d', unpackedValue) def peek_dword(self, lpBaseAddress): """ Reads a DWORD from the memory of the process. Returns zero on error. """ return self.__peek_c_type(lpBaseAddress, '=L', win32.DWORD) def poke_dword(self, lpBaseAddress, unpackedValue): """ Writes a DWORD to the memory of the process. May be less than the number of bytes to write. """ return self.__poke_c_type(lpBaseAddress, '=L', unpackedValue) def peek_qword(self, lpBaseAddress): """ Reads a QWORD from the memory of the process. Returns zero on error. """ return self.__peek_c_type(lpBaseAddress, '=Q', win32.QWORD) def poke_qword(self, lpBaseAddress, unpackedValue): """ Writes a QWORD to the memory of the process. May be less than the number of bytes to write. """ return self.__poke_c_type(lpBaseAddress, '=Q', unpackedValue) def peek_pointer(self, lpBaseAddress): """ Reads a pointer value from the memory of the process. Returns zero on error. """ return self.__peek_c_type(lpBaseAddress, '@P', ctypes.c_void_p) def poke_pointer(self, lpBaseAddress, unpackedValue): """ Writes a pointer value to the memory of the process. May be less than the number of bytes to write. """ return self.__poke_c_type(lpBaseAddress, '@P', unpackedValue) def peek_string(self, lpBaseAddress, fUnicode = False, dwMaxSize = 0x1000): """ Tries to read an ASCII or Unicode string from the address space of the process. C{False} if it's expected to be ANSI. It B{doesn't} include the terminating null character. Returns an empty string on failure. """ # 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 # TODO # try to avoid reading the same page twice by caching it 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. 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. """ 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 malloc(self, dwSize, lpAddress = None): """ Allocates memory into the address space of the process. Desired address for the newly allocated memory. This is only a hint, the memory could still be allocated somewhere else. """ hProcess = self.get_handle(win32.PROCESS_VM_OPERATION) return win32.VirtualAllocEx(hProcess, lpAddress, dwSize) def mprotect(self, lpAddress, dwSize, flNewProtect): """ Set memory protection in the address space of the process. """ hProcess = self.get_handle(win32.PROCESS_VM_OPERATION) return win32.VirtualProtectEx(hProcess, lpAddress, dwSize, flNewProtect) def mquery(self, lpAddress): """ Query memory information from the address space of the process. Returns a L{win32.MemoryBasicInformation} object. """ hProcess = self.get_handle(win32.PROCESS_QUERY_INFORMATION) return win32.VirtualQueryEx(hProcess, lpAddress) def free(self, lpAddress): """ Frees memory from the address space of the process. Must be the base address returned by L{malloc}. """ hProcess = self.get_handle(win32.PROCESS_VM_OPERATION) win32.VirtualFreeEx(hProcess, lpAddress) #------------------------------------------------------------------------------ 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. """ 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_address_valid(self, address): """ Determines if an address is a valid user mode address. """ 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_free(self, address): """ Determines if an address belongs to a free page. """ 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_reserved(self, address): """ Determines if an address belongs to a reserved page. """ 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_commited(self, address): """ Determines if an address belongs to a commited page. """ 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_guard(self, address): """ Determines if an address belongs to a guard page. """ 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_readable(self, address): """ Determines if an address belongs to a commited and readable page. The page may or may not have additional permissions. C{True} if the address belongs to a commited and readable page. """ 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_writeable(self, address): """ Determines if an address belongs to a commited and writeable page. The page may or may not have additional permissions. C{True} if the address belongs to a commited and writeable page. """ 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_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. C{True} if the address belongs to a commited, copy-on-write page. """ 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_executable(self, address): """ Determines if an address belongs to a commited and executable page. The page may or may not have additional permissions. C{True} if the address belongs to a commited and executable page. """ 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_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. C{True} if the address belongs to a commited, writeable and executable page. """ 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_buffer(self, address, size): """ Determines if the given memory area is a valid code or data buffer. C{False} otherwise. """ 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_readable(self, address, size): """ Determines if the given memory area is readable. """ 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.is_readable(): return False size = size - mbi.RegionSize return True def is_buffer_writeable(self, address, size): """ Determines if the given memory area is writeable. """ 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.is_writeable(): return False size = size - mbi.RegionSize return True def is_buffer_copy_on_write(self, address, size): """ Determines if the given memory area is marked as copy-on-write. C{False} otherwise. """ 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.is_copy_on_write(): return False size = size - mbi.RegionSize return True def is_buffer_executable(self, address, size): """ Determines if the given memory area is executable. """ 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.is_executable(): return False size = size - mbi.RegionSize return True def is_buffer_executable_and_writeable(self, address, size): """ Determines if the given memory area is writeable and executable. Looking for writeable and executable pages is important when exploiting a software vulnerability. C{False} otherwise. """ 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.is_executable(): return False size = size - mbi.RegionSize return True def get_memory_map(self, minAddr = None, maxAddr = None): """ Produces a memory map to the process address space. Optionally restrict the map to the given address range. """ return list(self.iter_memory_map(minAddr, maxAddr)) def generate_memory_map(self, minAddr = None, maxAddr = None): """ Returns a L{Regenerator} that can iterate indefinitely over the memory map to the process address space. Optionally restrict the map to the given address range. """ return Regenerator(self.iter_memory_map, minAddr, maxAddr) 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. """ 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 get_mapped_filenames(self, memoryMap = None): """ Retrieves the filenames for memory mapped files in the debugee. If not given, the current memory map is used. Native filenames are converted to Win32 filenames when possible. """ 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 generate_memory_snapshot(self, minAddr = None, maxAddr = None): """ Returns a L{Regenerator} that allows you to iterate through the memory contents of a process indefinitely. 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 be iterated more than once. Each time it's iterated the memory contents of the process will be fetched again. You can also iterate the memory of a dead process, just as long as the last open handle to it hasn't been closed. objects. Two extra properties are added to these objects: - C{filename}: Mapped filename, or C{None}. - C{content}: Memory contents, or C{None}. """ return Regenerator(self.iter_memory_snapshot, minAddr, maxAddr) 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. Two extra properties are added to these objects: - C{filename}: Mapped filename, or C{None}. - C{content}: Memory contents, or C{None}. """ # 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 take_memory_snapshot(self, minAddr = None, maxAddr = None): """ Takes a snapshot of the memory contents of the process. It's best if the process is suspended (if alive) when taking the snapshot. Execution can be resumed afterwards. Example:: # Print the memory contents of a process. process.suspend() try: snapshot = process.take_memory_snapshot() for mbi in snapshot: print HexDump.hexblock(mbi.content, mbi.BaseAddress) finally: process.resume() You can also iterate the memory of a dead process, just as long as the last open handle to it hasn't been closed. resulting snapshot will be equally big. This may result in a severe performance penalty. Two extra properties are added to these objects: - C{filename}: Mapped filename, or C{None}. - C{content}: Memory contents, or C{None}. """ return list( self.iter_memory_snapshot(minAddr, maxAddr) ) 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. are restored. Under some circumstances this method may fail (for example if memory was freed and then reused by a mapped file). Snapshots returned by L{generate_memory_snapshot} don't work here. 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. 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. """ 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_mbi(self, hProcess, new_mbi, old_mbi, bSkipMappedFiles, bSkipOnError): """ Used internally by L{restore_memory_snapshot}. """ ## print "Restoring %s-%s" % ( ## HexDump.address(old_mbi.BaseAddress, self.get_bits()), ## HexDump.address(old_mbi.BaseAddress + old_mbi.RegionSize, ## self.get_bits())) try: # Restore the region state. if new_mbi.State != old_mbi.State: if new_mbi.is_free(): if old_mbi.is_reserved(): # Free -> Reserved address = win32.VirtualAllocEx(hProcess, old_mbi.BaseAddress, old_mbi.RegionSize, win32.MEM_RESERVE, old_mbi.Protect) if address != old_mbi.BaseAddress: self.free(address) msg = "Error restoring region at address %s" msg = msg % HexDump(old_mbi.BaseAddress, self.get_bits()) raise RuntimeError(msg) # permissions already restored new_mbi.Protect = old_mbi.Protect else: # elif old_mbi.is_commited(): # Free -> Commited address = win32.VirtualAllocEx(hProcess, old_mbi.BaseAddress, old_mbi.RegionSize, win32.MEM_RESERVE | \ win32.MEM_COMMIT, old_mbi.Protect) if address != old_mbi.BaseAddress: self.free(address) msg = "Error restoring region at address %s" msg = msg % HexDump(old_mbi.BaseAddress, self.get_bits()) raise RuntimeError(msg) # permissions already restored new_mbi.Protect = old_mbi.Protect elif new_mbi.is_reserved(): if old_mbi.is_commited(): # Reserved -> Commited address = win32.VirtualAllocEx(hProcess, old_mbi.BaseAddress, old_mbi.RegionSize, win32.MEM_COMMIT, old_mbi.Protect) if address != old_mbi.BaseAddress: self.free(address) msg = "Error restoring region at address %s" msg = msg % HexDump(old_mbi.BaseAddress, self.get_bits()) raise RuntimeError(msg) # permissions already restored new_mbi.Protect = old_mbi.Protect else: # elif old_mbi.is_free(): # Reserved -> Free win32.VirtualFreeEx(hProcess, old_mbi.BaseAddress, old_mbi.RegionSize, win32.MEM_RELEASE) else: # elif new_mbi.is_commited(): if old_mbi.is_reserved(): # Commited -> Reserved win32.VirtualFreeEx(hProcess, old_mbi.BaseAddress, old_mbi.RegionSize, win32.MEM_DECOMMIT) else: # elif old_mbi.is_free(): # Commited -> Free win32.VirtualFreeEx(hProcess, old_mbi.BaseAddress, old_mbi.RegionSize, win32.MEM_DECOMMIT | win32.MEM_RELEASE) new_mbi.State = old_mbi.State # Restore the region permissions. if old_mbi.is_commited() and old_mbi.Protect != new_mbi.Protect: win32.VirtualProtectEx(hProcess, old_mbi.BaseAddress, old_mbi.RegionSize, old_mbi.Protect) new_mbi.Protect = old_mbi.Protect # Restore the region data. # Ignore write errors when the region belongs to a mapped file. if old_mbi.has_content(): if old_mbi.Type != 0: if not bSkipMappedFiles: self.poke(old_mbi.BaseAddress, old_mbi.content) else: self.write(old_mbi.BaseAddress, old_mbi.content) new_mbi.content = old_mbi.content # On error, skip this region or raise an exception. except Exception: if not bSkipOnError: raise msg = "Error restoring region at address %s: %s" msg = msg % ( HexDump(old_mbi.BaseAddress, self.get_bits()), traceback.format_exc()) warnings.warn(msg, RuntimeWarning) #------------------------------------------------------------------------------ def inject_code(self, payload, lpParameter = 0): """ Injects relocatable code into the process memory and executes it. Otherwise you'll be leaking memory in the target process. and the memory address where the code was written. """ # 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 # TODO # The shellcode should check for errors, otherwise it just crashes # when the DLL can't be loaded or the procedure can't be found. # On error the shellcode should execute an int3 instruction. def inject_dll(self, dllname, procname = None, lpParameter = 0, bWait = True, dwTimeout = None): """ Injects a DLL into the process memory. debug event will cause a deadlock in your debugger. This is how the freeing of this memory is handled: - If the C{bWait} flag is set to C{True} the memory will be freed automatically before returning from this method. - If the C{bWait} flag is set to C{False}, the memory address is set as the L{Thread.pInjectedMemory} property of the returned thread object. - L{Debug} objects free L{Thread.pInjectedMemory} automatically both when it detaches from a process and when the injected thread finishes its execution. - The {Thread.kill} method also frees L{Thread.pInjectedMemory} automatically, even if you're not attached to the process. You could still be leaking memory if not careful. For example, if you inject a dll into a process you're not attached to, you don't wait for the thread's completion and you don't kill it either, the memory would be leaked. C{False} to return immediately. Ignored if C{bWait} is C{False}. thread will be dead, otherwise it will be alive. Currently calling a procedure in the library is only supported in the I{i386} architecture. """ # Resolve kernel32.dll aModule = self.get_module_by_name(compat.b('kernel32.dll')) if aModule is None: self.scan_modules() aModule = self.get_module_by_name(compat.b('kernel32.dll')) if aModule is None: raise RuntimeError( "Cannot resolve kernel32.dll in the remote process") # Old method, using shellcode. if procname: if self.get_arch() != win32.ARCH_I386: raise NotImplementedError() dllname = compat.b(dllname) # Resolve kernel32.dll!LoadLibraryA pllib = aModule.resolve(compat.b('LoadLibraryA')) if not pllib: raise RuntimeError( "Cannot resolve kernel32.dll!LoadLibraryA" " in the remote process") # Resolve kernel32.dll!GetProcAddress pgpad = aModule.resolve(compat.b('GetProcAddress')) if not pgpad: raise RuntimeError( "Cannot resolve kernel32.dll!GetProcAddress" " in the remote process") # Resolve kernel32.dll!VirtualFree pvf = aModule.resolve(compat.b('VirtualFree')) if not pvf: raise RuntimeError( "Cannot resolve kernel32.dll!VirtualFree" " in the remote process") # Shellcode follows... code = compat.b('') # push dllname code += compat.b('\xe8') + struct.pack('<L', len(dllname) + 1) + dllname + compat.b('\0') # mov eax, LoadLibraryA code += compat.b('\xb8') + struct.pack('<L', pllib) # call eax code += compat.b('\xff\xd0') if procname: # push procname code += compat.b('\xe8') + struct.pack('<L', len(procname) + 1) code += procname + compat.b('\0') # push eax code += compat.b('\x50') # mov eax, GetProcAddress code += compat.b('\xb8') + struct.pack('<L', pgpad) # call eax code += compat.b('\xff\xd0') # mov ebp, esp ; preserve stack pointer code += compat.b('\x8b\xec') # push lpParameter code += compat.b('\x68') + struct.pack('<L', lpParameter) # call eax code += compat.b('\xff\xd0') # mov esp, ebp ; restore stack pointer code += compat.b('\x8b\xe5') # pop edx ; our own return address code += compat.b('\x5a') # push MEM_RELEASE ; dwFreeType code += compat.b('\x68') + struct.pack('<L', win32.MEM_RELEASE) # push 0x1000 ; dwSize, shellcode max size 4096 bytes code += compat.b('\x68') + struct.pack('<L', 0x1000) # call $+5 code += compat.b('\xe8\x00\x00\x00\x00') # and dword ptr [esp], 0xFFFFF000 ; align to page boundary code += compat.b('\x81\x24\x24\x00\xf0\xff\xff') # mov eax, VirtualFree code += compat.b('\xb8') + struct.pack('<L', pvf) # push edx ; our own return address code += compat.b('\x52') # jmp eax ; VirtualFree will return to our own return address code += compat.b('\xff\xe0') # Inject the shellcode. # There's no need to free the memory, # because the shellcode will free it itself. aThread, lpStartAddress = self.inject_code(code, lpParameter) # New method, not using shellcode. else: # Resolve kernel32.dll!LoadLibrary (A/W) if type(dllname) == type(u''): pllibname = compat.b('LoadLibraryW') bufferlen = (len(dllname) + 1) * 2 dllname = win32.ctypes.create_unicode_buffer(dllname).raw[:bufferlen + 1] else: pllibname = compat.b('LoadLibraryA') dllname = compat.b(dllname) + compat.b('\x00') bufferlen = len(dllname) pllib = aModule.resolve(pllibname) if not pllib: msg = "Cannot resolve kernel32.dll!%s in the remote process" raise RuntimeError(msg % pllibname) # Copy the library name into the process memory space. pbuffer = self.malloc(bufferlen) try: self.write(pbuffer, dllname) # Create a new thread to load the library. try: aThread = self.start_thread(pllib, pbuffer) except WindowsError: e = sys.exc_info()[1] if e.winerror != win32.ERROR_NOT_ENOUGH_MEMORY: raise # This specific error is caused by trying to spawn a new # thread in a process belonging to a different Terminal # Services session (for example a service). raise NotImplementedError( "Target process belongs to a different" " Terminal Services session, cannot inject!" ) # Remember the buffer 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. aThread.pInjectedMemory = pbuffer # Free the memory on error. except Exception: self.free(pbuffer) raise # Wait for the thread to finish. if bWait: aThread.wait(dwTimeout) self.free(aThread.pInjectedMemory) del aThread.pInjectedMemory # Return the thread object. return aThread 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. debug event will cause a deadlock in your debugger. C{False} to return immediately. Ignored if C{bWait} is C{False}. """ if not dwExitCode: dwExitCode = 0 pExitProcess = self.resolve_label('kernel32!ExitProcess') aThread = self.start_thread(pExitProcess, dwExitCode) if bWait: aThread.wait(dwTimeout) #------------------------------------------------------------------------------ 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. """ # Do not use super() here. bCallHandler = _ThreadContainer._notify_create_process(self, event) bCallHandler = bCallHandler and \ _ModuleContainer._notify_create_process(self, event) return bCallHandler def run_python_code_windows(pid, python_code, connect_debugger_tracing=False, show_debug_info=0): assert '\'' not in python_code, 'Having a single quote messes with our command.' from winappdbg.process import Process if not isinstance(python_code, bytes): python_code = python_code.encode('utf-8') process = Process(pid) bits = process.get_bits() is_target_process_64 = bits == 64 # Note: this restriction no longer applies (we create a process with the proper bitness from # this process so that the attach works). # if is_target_process_64 != is_python_64bit(): # raise RuntimeError("The architecture of the Python used to connect doesn't match the architecture of the target.\n" # "Target 64 bits: %s\n" # "Current Python 64 bits: %s" % (is_target_process_64, is_python_64bit())) with _acquire_mutex('_pydevd_pid_attach_mutex_%s' % (pid,), 10): print('--- Connecting to %s bits target (current process is: %s) ---' % (bits, 64 if is_python_64bit() else 32)) sys.stdout.flush() with _win_write_to_shared_named_memory(python_code, pid): target_executable = get_target_filename(is_target_process_64, 'inject_dll_', '.exe') if not target_executable: raise RuntimeError('Could not find expected .exe file to inject dll in attach to process.') target_dll = get_target_filename(is_target_process_64) if not target_dll: raise RuntimeError('Could not find expected .dll file in attach to process.') print('\n--- Injecting attach dll: %s into pid: %s ---' % (os.path.basename(target_dll), pid)) sys.stdout.flush() args = [target_executable, str(pid), target_dll] subprocess.check_call(args) # Now, if the first injection worked, go on to the second which will actually # run the code. target_dll_run_on_dllmain = get_target_filename(is_target_process_64, 'run_code_on_dllmain_', '.dll') if not target_dll_run_on_dllmain: raise RuntimeError('Could not find expected .dll in attach to process.') with _create_win_event('_pydevd_pid_event_%s' % (pid,)) as event: print('\n--- Injecting run code dll: %s into pid: %s ---' % (os.path.basename(target_dll_run_on_dllmain), pid)) sys.stdout.flush() args = [target_executable, str(pid), target_dll_run_on_dllmain] subprocess.check_call(args) if not event.wait_for_event_set(15): print('Timeout error: the attach may not have completed.') sys.stdout.flush() print('--- Finished dll injection ---\n') sys.stdout.flush() return 0
null
177,084
import ctypes import os import struct import subprocess import sys import time from contextlib import contextmanager import platform import traceback def get_target_filename(is_target_process_64=None, prefix=None, extension=None): def run_python_code_linux(pid, python_code, connect_debugger_tracing=False, show_debug_info=0): assert '\'' not in python_code, 'Having a single quote messes with our command.' target_dll = get_target_filename() if not target_dll: raise RuntimeError('Could not find .so for attach to process.') target_dll_name = os.path.splitext(os.path.basename(target_dll))[0] # Note: we currently don't support debug builds is_debug = 0 # Note that the space in the beginning of each line in the multi-line is important! cmd = [ 'gdb', '--nw', # no gui interface '--nh', # no ~/.gdbinit '--nx', # no .gdbinit # '--quiet', # no version number on startup '--pid', str(pid), '--batch', # '--batch-silent', ] # PYDEVD_GDB_SCAN_SHARED_LIBRARIES can be a list of strings with the shared libraries # which should be scanned by default to make the attach to process (i.e.: libdl, libltdl, libc, libfreebl3). # # The default is scanning all shared libraries, but on some cases this can be in the 20-30 # seconds range for some corner cases. # See: https://github.com/JetBrains/intellij-community/pull/1608 # # By setting PYDEVD_GDB_SCAN_SHARED_LIBRARIES (to a comma-separated string), it's possible to # specify just a few libraries to be loaded (not many are needed for the attach, # but it can be tricky to pre-specify for all Linux versions as this may change # across different versions). # # See: https://github.com/microsoft/debugpy/issues/762#issuecomment-947103844 # for a comment that explains the basic steps on how to discover what should be available # in each case (mostly trying different versions based on the output of gdb). # # The upside is that for cases when too many libraries are loaded the attach could be slower # and just specifying the one that is actually needed for the attach can make it much faster. # # The downside is that it may be dependent on the Linux version being attached to (which is the # reason why this is no longer done by default -- see: https://github.com/microsoft/debugpy/issues/882). gdb_load_shared_libraries = os.environ.get('PYDEVD_GDB_SCAN_SHARED_LIBRARIES', '').strip() if gdb_load_shared_libraries: print('PYDEVD_GDB_SCAN_SHARED_LIBRARIES set: %s.' % (gdb_load_shared_libraries,)) cmd.extend(["--init-eval-command='set auto-solib-add off'"]) # Don't scan all libraries. for lib in gdb_load_shared_libraries.split(','): lib = lib.strip() cmd.extend(["--eval-command='sharedlibrary %s'" % (lib,)]) # Scan the specified library else: print('PYDEVD_GDB_SCAN_SHARED_LIBRARIES not set (scanning all libraries for needed symbols).') cmd.extend(["--eval-command='set scheduler-locking off'"]) # If on we'll deadlock. # Leave auto by default (it should do the right thing as we're attaching to a process in the # current host). cmd.extend(["--eval-command='set architecture auto'"]) cmd.extend([ "--eval-command='call (void*)dlopen(\"%s\", 2)'" % target_dll, "--eval-command='sharedlibrary %s'" % target_dll_name, "--eval-command='call (int)DoAttach(%s, \"%s\", %s)'" % ( is_debug, python_code, show_debug_info) ]) # print ' '.join(cmd) env = os.environ.copy() # Remove the PYTHONPATH (if gdb has a builtin Python it could fail if we # have the PYTHONPATH for a different python version or some forced encoding). env.pop('PYTHONIOENCODING', None) env.pop('PYTHONPATH', None) print('Running: %s' % (' '.join(cmd))) subprocess.check_call(' '.join(cmd), shell=True, env=env)
null
177,085
import ctypes import os import struct import subprocess import sys import time from contextlib import contextmanager import platform import traceback def get_target_filename(is_target_process_64=None, prefix=None, extension=None): # Note: we have an independent (and similar -- but not equal) version of this method in # `pydevd_tracing.py` which should be kept synchronized with this one (we do a copy # because the `pydevd_attach_to_process` is mostly independent and shouldn't be imported in the # debugger -- the only situation where it's imported is if the user actually does an attach to # process, through `attach_pydevd.py`, but this should usually be called from the IDE directly # and not from the debugger). libdir = os.path.dirname(__file__) if is_target_process_64 is None: if IS_WINDOWS: # i.e.: On windows the target process could have a different bitness (32bit is emulated on 64bit). raise AssertionError("On windows it's expected that the target bitness is specified.") # For other platforms, just use the the same bitness of the process we're running in. is_target_process_64 = is_python_64bit() arch = '' if IS_WINDOWS: # prefer not using platform.machine() when possible (it's a bit heavyweight as it may # spawn a subprocess). arch = os.environ.get("PROCESSOR_ARCHITEW6432", os.environ.get('PROCESSOR_ARCHITECTURE', '')) if not arch: arch = platform.machine() if not arch: print('platform.machine() did not return valid value.') # This shouldn't happen... return None if IS_WINDOWS: if not extension: extension = '.dll' suffix_64 = 'amd64' suffix_32 = 'x86' elif IS_LINUX: if not extension: extension = '.so' suffix_64 = 'amd64' suffix_32 = 'x86' elif IS_MAC: if not extension: extension = '.dylib' suffix_64 = 'x86_64' suffix_32 = 'x86' else: print('Unable to attach to process in platform: %s', sys.platform) return None if arch.lower() not in ('amd64', 'x86', 'x86_64', 'i386', 'x86'): # We don't support this processor by default. Still, let's support the case where the # user manually compiled it himself with some heuristics. # # Ideally the user would provide a library in the format: "attach_<arch>.<extension>" # based on the way it's currently compiled -- see: # - windows/compile_windows.bat # - linux_and_mac/compile_linux.sh # - linux_and_mac/compile_mac.sh try: found = [name for name in os.listdir(libdir) if name.startswith('attach_') and name.endswith(extension)] except: print('Error listing dir: %s' % (libdir,)) traceback.print_exc() return None if prefix: expected_name = prefix + arch + extension expected_name_linux = prefix + 'linux_' + arch + extension else: # Default is looking for the attach_ / attach_linux expected_name = 'attach_' + arch + extension expected_name_linux = 'attach_linux_' + arch + extension filename = None if expected_name in found: # Heuristic: user compiled with "attach_<arch>.<extension>" filename = os.path.join(libdir, expected_name) elif IS_LINUX and expected_name_linux in found: # Heuristic: user compiled with "attach_linux_<arch>.<extension>" filename = os.path.join(libdir, expected_name_linux) elif len(found) == 1: # Heuristic: user removed all libraries and just left his own lib. filename = os.path.join(libdir, found[0]) else: # Heuristic: there's one additional library which doesn't seem to be our own. Find the odd one. filtered = [name for name in found if not name.endswith((suffix_64 + extension, suffix_32 + extension))] if len(filtered) == 1: # If more than one is available we can't be sure... filename = os.path.join(libdir, found[0]) if filename is None: print( 'Unable to attach to process in arch: %s (did not find %s in %s).' % ( arch, expected_name, libdir ) ) return None print('Using %s in arch: %s.' % (filename, arch)) else: if is_target_process_64: suffix = suffix_64 else: suffix = suffix_32 if not prefix: # Default is looking for the attach_ / attach_linux if IS_WINDOWS or IS_MAC: # just the extension changes prefix = 'attach_' elif IS_LINUX: prefix = 'attach_linux_' # historically it has a different name else: print('Unable to attach to process in platform: %s' % (sys.platform,)) return None filename = os.path.join(libdir, '%s%s%s' % (prefix, suffix, extension)) if not os.path.exists(filename): print('Expected: %s to exist.' % (filename,)) return None return filename def find_helper_script(filedir, script_name): target_filename = os.path.join(filedir, 'linux_and_mac', script_name) target_filename = os.path.normpath(target_filename) if not os.path.exists(target_filename): raise RuntimeError('Could not find helper script: %s' % target_filename) return target_filename def run_python_code_mac(pid, python_code, connect_debugger_tracing=False, show_debug_info=0): assert '\'' not in python_code, 'Having a single quote messes with our command.' target_dll = get_target_filename() if not target_dll: raise RuntimeError('Could not find .dylib for attach to process.') libdir = os.path.dirname(__file__) lldb_prepare_file = find_helper_script(libdir, 'lldb_prepare.py') # Note: we currently don't support debug builds is_debug = 0 # Note that the space in the beginning of each line in the multi-line is important! cmd = [ 'lldb', '--no-lldbinit', # Do not automatically parse any '.lldbinit' files. # '--attach-pid', # str(pid), # '--arch', # arch, '--script-language', 'Python' # '--batch-silent', ] cmd.extend([ "-o 'process attach --pid %d'" % pid, "-o 'command script import \"%s\"'" % (lldb_prepare_file,), "-o 'load_lib_and_attach \"%s\" %s \"%s\" %s'" % (target_dll, is_debug, python_code, show_debug_info), ]) cmd.extend([ "-o 'process detach'", "-o 'script import os; os._exit(1)'", ]) # print ' '.join(cmd) env = os.environ.copy() # Remove the PYTHONPATH (if lldb has a builtin Python it could fail if we # have the PYTHONPATH for a different python version or some forced encoding). env.pop('PYTHONIOENCODING', None) env.pop('PYTHONPATH', None) print('Running: %s' % (' '.join(cmd))) subprocess.check_call(' '.join(cmd), shell=True, env=env)
null
177,086
import ctypes import os import struct import subprocess import sys import time from contextlib import contextmanager import platform import traceback def run_python_code(*args, **kwargs): print('Unable to attach to process in platform: %s', sys.platform)
null
177,087
import sys import os import ctypes import optparse from winappdbg import win32 from winappdbg import compat def CustomAddressIterator(memory_map, condition): """ Generator function that iterates through a memory map, filtering memory region blocks by any given condition. Returned by L{Process.get_memory_map}. block should be returned, or C{False} if it should be filtered. """ for mbi in memory_map: if condition(mbi): address = mbi.BaseAddress max_addr = address + mbi.RegionSize while address < max_addr: yield address address = address + 1 The provided code snippet includes necessary dependencies for implementing the `DataAddressIterator` function. Write a Python function `def DataAddressIterator(memory_map)` to solve the following problem: Generator function that iterates through a memory map, returning only those memory blocks that contain data. @type memory_map: list( L{win32.MemoryBasicInformation} ) @param memory_map: List of memory region information objects. Returned by L{Process.get_memory_map}. @rtype: generator of L{win32.MemoryBasicInformation} @return: Generator object to iterate memory blocks. Here is the function: def DataAddressIterator(memory_map): """ Generator function that iterates through a memory map, returning only those memory blocks that contain data. @type memory_map: list( L{win32.MemoryBasicInformation} ) @param memory_map: List of memory region information objects. Returned by L{Process.get_memory_map}. @rtype: generator of L{win32.MemoryBasicInformation} @return: Generator object to iterate memory blocks. """ return CustomAddressIterator(memory_map, win32.MemoryBasicInformation.has_content)
Generator function that iterates through a memory map, returning only those memory blocks that contain data. @type memory_map: list( L{win32.MemoryBasicInformation} ) @param memory_map: List of memory region information objects. Returned by L{Process.get_memory_map}. @rtype: generator of L{win32.MemoryBasicInformation} @return: Generator object to iterate memory blocks.
177,088
import sys import os import ctypes import optparse from winappdbg import win32 from winappdbg import compat def CustomAddressIterator(memory_map, condition): """ Generator function that iterates through a memory map, filtering memory region blocks by any given condition. Returned by L{Process.get_memory_map}. block should be returned, or C{False} if it should be filtered. """ for mbi in memory_map: if condition(mbi): address = mbi.BaseAddress max_addr = address + mbi.RegionSize while address < max_addr: yield address address = address + 1 The provided code snippet includes necessary dependencies for implementing the `ImageAddressIterator` function. Write a Python function `def ImageAddressIterator(memory_map)` to solve the following problem: Generator function that iterates through a memory map, returning only those memory blocks that belong to executable images. @type memory_map: list( L{win32.MemoryBasicInformation} ) @param memory_map: List of memory region information objects. Returned by L{Process.get_memory_map}. @rtype: generator of L{win32.MemoryBasicInformation} @return: Generator object to iterate memory blocks. Here is the function: def ImageAddressIterator(memory_map): """ Generator function that iterates through a memory map, returning only those memory blocks that belong to executable images. @type memory_map: list( L{win32.MemoryBasicInformation} ) @param memory_map: List of memory region information objects. Returned by L{Process.get_memory_map}. @rtype: generator of L{win32.MemoryBasicInformation} @return: Generator object to iterate memory blocks. """ return CustomAddressIterator(memory_map, win32.MemoryBasicInformation.is_image)
Generator function that iterates through a memory map, returning only those memory blocks that belong to executable images. @type memory_map: list( L{win32.MemoryBasicInformation} ) @param memory_map: List of memory region information objects. Returned by L{Process.get_memory_map}. @rtype: generator of L{win32.MemoryBasicInformation} @return: Generator object to iterate memory blocks.
177,089
import sys import os import ctypes import optparse from winappdbg import win32 from winappdbg import compat def CustomAddressIterator(memory_map, condition): """ Generator function that iterates through a memory map, filtering memory region blocks by any given condition. Returned by L{Process.get_memory_map}. block should be returned, or C{False} if it should be filtered. """ for mbi in memory_map: if condition(mbi): address = mbi.BaseAddress max_addr = address + mbi.RegionSize while address < max_addr: yield address address = address + 1 The provided code snippet includes necessary dependencies for implementing the `MappedAddressIterator` function. Write a Python function `def MappedAddressIterator(memory_map)` to solve the following problem: Generator function that iterates through a memory map, returning only those memory blocks that belong to memory mapped files. @type memory_map: list( L{win32.MemoryBasicInformation} ) @param memory_map: List of memory region information objects. Returned by L{Process.get_memory_map}. @rtype: generator of L{win32.MemoryBasicInformation} @return: Generator object to iterate memory blocks. Here is the function: def MappedAddressIterator(memory_map): """ Generator function that iterates through a memory map, returning only those memory blocks that belong to memory mapped files. @type memory_map: list( L{win32.MemoryBasicInformation} ) @param memory_map: List of memory region information objects. Returned by L{Process.get_memory_map}. @rtype: generator of L{win32.MemoryBasicInformation} @return: Generator object to iterate memory blocks. """ return CustomAddressIterator(memory_map, win32.MemoryBasicInformation.is_mapped)
Generator function that iterates through a memory map, returning only those memory blocks that belong to memory mapped files. @type memory_map: list( L{win32.MemoryBasicInformation} ) @param memory_map: List of memory region information objects. Returned by L{Process.get_memory_map}. @rtype: generator of L{win32.MemoryBasicInformation} @return: Generator object to iterate memory blocks.
177,090
import sys import os import ctypes import optparse from winappdbg import win32 from winappdbg import compat def CustomAddressIterator(memory_map, condition): """ Generator function that iterates through a memory map, filtering memory region blocks by any given condition. Returned by L{Process.get_memory_map}. block should be returned, or C{False} if it should be filtered. """ for mbi in memory_map: if condition(mbi): address = mbi.BaseAddress max_addr = address + mbi.RegionSize while address < max_addr: yield address address = address + 1 The provided code snippet includes necessary dependencies for implementing the `ReadableAddressIterator` function. Write a Python function `def ReadableAddressIterator(memory_map)` to solve the following problem: Generator function that iterates through a memory map, returning only those memory blocks that are readable. @type memory_map: list( L{win32.MemoryBasicInformation} ) @param memory_map: List of memory region information objects. Returned by L{Process.get_memory_map}. @rtype: generator of L{win32.MemoryBasicInformation} @return: Generator object to iterate memory blocks. Here is the function: def ReadableAddressIterator(memory_map): """ Generator function that iterates through a memory map, returning only those memory blocks that are readable. @type memory_map: list( L{win32.MemoryBasicInformation} ) @param memory_map: List of memory region information objects. Returned by L{Process.get_memory_map}. @rtype: generator of L{win32.MemoryBasicInformation} @return: Generator object to iterate memory blocks. """ return CustomAddressIterator(memory_map, win32.MemoryBasicInformation.is_readable)
Generator function that iterates through a memory map, returning only those memory blocks that are readable. @type memory_map: list( L{win32.MemoryBasicInformation} ) @param memory_map: List of memory region information objects. Returned by L{Process.get_memory_map}. @rtype: generator of L{win32.MemoryBasicInformation} @return: Generator object to iterate memory blocks.
177,091
import sys import os import ctypes import optparse from winappdbg import win32 from winappdbg import compat def CustomAddressIterator(memory_map, condition): """ Generator function that iterates through a memory map, filtering memory region blocks by any given condition. Returned by L{Process.get_memory_map}. block should be returned, or C{False} if it should be filtered. """ for mbi in memory_map: if condition(mbi): address = mbi.BaseAddress max_addr = address + mbi.RegionSize while address < max_addr: yield address address = address + 1 The provided code snippet includes necessary dependencies for implementing the `WriteableAddressIterator` function. Write a Python function `def WriteableAddressIterator(memory_map)` to solve the following problem: Generator function that iterates through a memory map, returning only those memory blocks that are writeable. @note: Writeable memory is always readable too. @type memory_map: list( L{win32.MemoryBasicInformation} ) @param memory_map: List of memory region information objects. Returned by L{Process.get_memory_map}. @rtype: generator of L{win32.MemoryBasicInformation} @return: Generator object to iterate memory blocks. Here is the function: def WriteableAddressIterator(memory_map): """ Generator function that iterates through a memory map, returning only those memory blocks that are writeable. @note: Writeable memory is always readable too. @type memory_map: list( L{win32.MemoryBasicInformation} ) @param memory_map: List of memory region information objects. Returned by L{Process.get_memory_map}. @rtype: generator of L{win32.MemoryBasicInformation} @return: Generator object to iterate memory blocks. """ return CustomAddressIterator(memory_map, win32.MemoryBasicInformation.is_writeable)
Generator function that iterates through a memory map, returning only those memory blocks that are writeable. @note: Writeable memory is always readable too. @type memory_map: list( L{win32.MemoryBasicInformation} ) @param memory_map: List of memory region information objects. Returned by L{Process.get_memory_map}. @rtype: generator of L{win32.MemoryBasicInformation} @return: Generator object to iterate memory blocks.
177,092
import sys import os import ctypes import optparse from winappdbg import win32 from winappdbg import compat def CustomAddressIterator(memory_map, condition): """ Generator function that iterates through a memory map, filtering memory region blocks by any given condition. Returned by L{Process.get_memory_map}. block should be returned, or C{False} if it should be filtered. """ for mbi in memory_map: if condition(mbi): address = mbi.BaseAddress max_addr = address + mbi.RegionSize while address < max_addr: yield address address = address + 1 The provided code snippet includes necessary dependencies for implementing the `ExecutableAddressIterator` function. Write a Python function `def ExecutableAddressIterator(memory_map)` to solve the following problem: Generator function that iterates through a memory map, returning only those memory blocks that are executable. @note: Executable memory is always readable too. @type memory_map: list( L{win32.MemoryBasicInformation} ) @param memory_map: List of memory region information objects. Returned by L{Process.get_memory_map}. @rtype: generator of L{win32.MemoryBasicInformation} @return: Generator object to iterate memory blocks. Here is the function: def ExecutableAddressIterator(memory_map): """ Generator function that iterates through a memory map, returning only those memory blocks that are executable. @note: Executable memory is always readable too. @type memory_map: list( L{win32.MemoryBasicInformation} ) @param memory_map: List of memory region information objects. Returned by L{Process.get_memory_map}. @rtype: generator of L{win32.MemoryBasicInformation} @return: Generator object to iterate memory blocks. """ return CustomAddressIterator(memory_map, win32.MemoryBasicInformation.is_executable)
Generator function that iterates through a memory map, returning only those memory blocks that are executable. @note: Executable memory is always readable too. @type memory_map: list( L{win32.MemoryBasicInformation} ) @param memory_map: List of memory region information objects. Returned by L{Process.get_memory_map}. @rtype: generator of L{win32.MemoryBasicInformation} @return: Generator object to iterate memory blocks.
177,093
import sys import os import ctypes import optparse from winappdbg import win32 from winappdbg import compat def CustomAddressIterator(memory_map, condition): """ Generator function that iterates through a memory map, filtering memory region blocks by any given condition. Returned by L{Process.get_memory_map}. block should be returned, or C{False} if it should be filtered. """ for mbi in memory_map: if condition(mbi): address = mbi.BaseAddress max_addr = address + mbi.RegionSize while address < max_addr: yield address address = address + 1 The provided code snippet includes necessary dependencies for implementing the `ExecutableAndWriteableAddressIterator` function. Write a Python function `def ExecutableAndWriteableAddressIterator(memory_map)` to solve the following problem: Generator function that iterates through a memory map, returning only those memory blocks that are executable and writeable. @note: The presence of such pages make memory corruption vulnerabilities much easier to exploit. @type memory_map: list( L{win32.MemoryBasicInformation} ) @param memory_map: List of memory region information objects. Returned by L{Process.get_memory_map}. @rtype: generator of L{win32.MemoryBasicInformation} @return: Generator object to iterate memory blocks. Here is the function: def ExecutableAndWriteableAddressIterator(memory_map): """ Generator function that iterates through a memory map, returning only those memory blocks that are executable and writeable. @note: The presence of such pages make memory corruption vulnerabilities much easier to exploit. @type memory_map: list( L{win32.MemoryBasicInformation} ) @param memory_map: List of memory region information objects. Returned by L{Process.get_memory_map}. @rtype: generator of L{win32.MemoryBasicInformation} @return: Generator object to iterate memory blocks. """ return CustomAddressIterator(memory_map, win32.MemoryBasicInformation.is_executable_and_writeable)
Generator function that iterates through a memory map, returning only those memory blocks that are executable and writeable. @note: The presence of such pages make memory corruption vulnerabilities much easier to exploit. @type memory_map: list( L{win32.MemoryBasicInformation} ) @param memory_map: List of memory region information objects. Returned by L{Process.get_memory_map}. @rtype: generator of L{win32.MemoryBasicInformation} @return: Generator object to iterate memory blocks.
177,094
from winappdbg.win32.defines import * def GetLargePageMinimum(): _GetLargePageMinimum = windll.user32.GetLargePageMinimum _GetLargePageMinimum.argtypes = [] _GetLargePageMinimum.restype = SIZE_T return _GetLargePageMinimum()
null
177,095
from winappdbg.win32.defines import * def GetCurrentThread(): ## return 0xFFFFFFFFFFFFFFFEL _GetCurrentThread = windll.kernel32.GetCurrentThread _GetCurrentThread.argtypes = [] _GetCurrentThread.restype = HANDLE return _GetCurrentThread()
null
177,096
from winappdbg.win32.defines import * def GetVersion(): _GetVersion = windll.kernel32.GetVersion _GetVersion.argtypes = [] _GetVersion.restype = DWORD _GetVersion.errcheck = RaiseIfZero # See the example code here: # http://msdn.microsoft.com/en-us/library/ms724439(VS.85).aspx dwVersion = _GetVersion() dwMajorVersion = dwVersion & 0x000000FF dwMinorVersion = (dwVersion & 0x0000FF00) >> 8 if (dwVersion & 0x80000000) == 0: dwBuild = (dwVersion & 0x7FFF0000) >> 16 else: dwBuild = None return int(dwMajorVersion), int(dwMinorVersion), int(dwBuild)
null
177,097
from winappdbg.win32.defines import * class OSVERSIONINFOA(Structure): _fields_ = [ ("dwOSVersionInfoSize", DWORD), ("dwMajorVersion", DWORD), ("dwMinorVersion", DWORD), ("dwBuildNumber", DWORD), ("dwPlatformId", DWORD), ("szCSDVersion", CHAR * 128), ] class OSVERSIONINFOEXA(Structure): _fields_ = [ ("dwOSVersionInfoSize", DWORD), ("dwMajorVersion", DWORD), ("dwMinorVersion", DWORD), ("dwBuildNumber", DWORD), ("dwPlatformId", DWORD), ("szCSDVersion", CHAR * 128), ("wServicePackMajor", WORD), ("wServicePackMinor", WORD), ("wSuiteMask", WORD), ("wProductType", BYTE), ("wReserved", BYTE), ] def GetVersionExA(): _GetVersionExA = windll.kernel32.GetVersionExA _GetVersionExA.argtypes = [POINTER(OSVERSIONINFOEXA)] _GetVersionExA.restype = bool _GetVersionExA.errcheck = RaiseIfZero osi = OSVERSIONINFOEXA() osi.dwOSVersionInfoSize = sizeof(osi) try: _GetVersionExA(byref(osi)) except WindowsError: osi = OSVERSIONINFOA() osi.dwOSVersionInfoSize = sizeof(osi) _GetVersionExA.argtypes = [POINTER(OSVERSIONINFOA)] _GetVersionExA(byref(osi)) return osi
null
177,098
from winappdbg.win32.defines import * class OSVERSIONINFOW(Structure): class OSVERSIONINFOEXW(Structure): def GetVersionExW(): _GetVersionExW = windll.kernel32.GetVersionExW _GetVersionExW.argtypes = [POINTER(OSVERSIONINFOEXW)] _GetVersionExW.restype = bool _GetVersionExW.errcheck = RaiseIfZero osi = OSVERSIONINFOEXW() osi.dwOSVersionInfoSize = sizeof(osi) try: _GetVersionExW(byref(osi)) except WindowsError: osi = OSVERSIONINFOW() osi.dwOSVersionInfoSize = sizeof(osi) _GetVersionExW.argtypes = [POINTER(OSVERSIONINFOW)] _GetVersionExW(byref(osi)) return osi
null
177,099
from winappdbg.win32.defines import * def GetProductInfo(dwOSMajorVersion, dwOSMinorVersion, dwSpMajorVersion, dwSpMinorVersion): _GetProductInfo = windll.kernel32.GetProductInfo _GetProductInfo.argtypes = [DWORD, DWORD, DWORD, DWORD, PDWORD] _GetProductInfo.restype = BOOL _GetProductInfo.errcheck = RaiseIfZero dwReturnedProductType = DWORD(0) _GetProductInfo(dwOSMajorVersion, dwOSMinorVersion, dwSpMajorVersion, dwSpMinorVersion, byref(dwReturnedProductType)) return dwReturnedProductType.value
null
177,100
from winappdbg.win32.defines import * class OSVERSIONINFOEXA(Structure): class OSVERSIONINFOEXW(Structure): def VerifyVersionInfoA(lpVersionInfo, dwTypeMask, dwlConditionMask): def VerifyVersionInfoW(lpVersionInfo, dwTypeMask, dwlConditionMask): def VerifyVersionInfo(lpVersionInfo, dwTypeMask, dwlConditionMask): if isinstance(lpVersionInfo, OSVERSIONINFOEXA): return VerifyVersionInfoA(lpVersionInfo, dwTypeMask, dwlConditionMask) if isinstance(lpVersionInfo, OSVERSIONINFOEXW): return VerifyVersionInfoW(lpVersionInfo, dwTypeMask, dwlConditionMask) raise TypeError("Bad OSVERSIONINFOEX structure")
null
177,101
from winappdbg.win32.defines import * def VerSetConditionMask(dwlConditionMask, dwTypeBitMask, dwConditionMask): _VerSetConditionMask = windll.kernel32.VerSetConditionMask _VerSetConditionMask.argtypes = [ULONGLONG, DWORD, BYTE] _VerSetConditionMask.restype = ULONGLONG return _VerSetConditionMask(dwlConditionMask, dwTypeBitMask, dwConditionMask)
null
177,102
from winappdbg.win32.defines import * The provided code snippet includes necessary dependencies for implementing the `_get_bits` function. Write a Python function `def _get_bits()` to solve the following problem: Determines the current integer size in bits. This is useful to know if we're running in a 32 bits or a 64 bits machine. @rtype: int @return: Returns the size of L{SIZE_T} in bits. Here is the function: def _get_bits(): """ Determines the current integer size in bits. This is useful to know if we're running in a 32 bits or a 64 bits machine. @rtype: int @return: Returns the size of L{SIZE_T} in bits. """ return sizeof(SIZE_T) * 8
Determines the current integer size in bits. This is useful to know if we're running in a 32 bits or a 64 bits machine. @rtype: int @return: Returns the size of L{SIZE_T} in bits.
177,103
from winappdbg.win32.defines import * def GetSystemInfo(): _GetSystemInfo = windll.kernel32.GetSystemInfo _GetSystemInfo.argtypes = [LPSYSTEM_INFO] _GetSystemInfo.restype = None sysinfo = SYSTEM_INFO() _GetSystemInfo(byref(sysinfo)) return sysinfo def GetNativeSystemInfo(): _GetNativeSystemInfo = windll.kernel32.GetNativeSystemInfo _GetNativeSystemInfo.argtypes = [LPSYSTEM_INFO] _GetNativeSystemInfo.restype = None sysinfo = SYSTEM_INFO() _GetNativeSystemInfo(byref(sysinfo)) return sysinfo ARCH_UNKNOWN = "unknown" _arch_map = { PROCESSOR_ARCHITECTURE_INTEL : ARCH_I386, PROCESSOR_ARCHITECTURE_MIPS : ARCH_MIPS, PROCESSOR_ARCHITECTURE_ALPHA : ARCH_ALPHA, PROCESSOR_ARCHITECTURE_PPC : ARCH_PPC, PROCESSOR_ARCHITECTURE_SHX : ARCH_SHX, PROCESSOR_ARCHITECTURE_ARM : ARCH_ARM, PROCESSOR_ARCHITECTURE_IA64 : ARCH_IA64, PROCESSOR_ARCHITECTURE_ALPHA64 : ARCH_ALPHA64, PROCESSOR_ARCHITECTURE_MSIL : ARCH_MSIL, PROCESSOR_ARCHITECTURE_AMD64 : ARCH_AMD64, PROCESSOR_ARCHITECTURE_SPARC : ARCH_SPARC, } The provided code snippet includes necessary dependencies for implementing the `_get_arch` function. Write a Python function `def _get_arch()` to solve the following problem: Determines the current processor architecture. @rtype: str @return: On error, returns: - L{ARCH_UNKNOWN} (C{"unknown"}) meaning the architecture could not be detected or is not known to WinAppDbg. On success, returns one of the following values: - L{ARCH_I386} (C{"i386"}) for Intel 32-bit x86 processor or compatible. - L{ARCH_AMD64} (C{"amd64"}) for Intel 64-bit x86_64 processor or compatible. May also return one of the following values if you get both Python and WinAppDbg to work in such machines... let me know if you do! :) - L{ARCH_MIPS} (C{"mips"}) for MIPS compatible processors. - L{ARCH_ALPHA} (C{"alpha"}) for Alpha processors. - L{ARCH_PPC} (C{"ppc"}) for PowerPC compatible processors. - L{ARCH_SHX} (C{"shx"}) for Hitachi SH processors. - L{ARCH_ARM} (C{"arm"}) for ARM compatible processors. - L{ARCH_IA64} (C{"ia64"}) for Intel Itanium processor or compatible. - L{ARCH_ALPHA64} (C{"alpha64"}) for Alpha64 processors. - L{ARCH_MSIL} (C{"msil"}) for the .NET virtual machine. - L{ARCH_SPARC} (C{"sparc"}) for Sun Sparc processors. Probably IronPython returns C{ARCH_MSIL} but I haven't tried it. Python on Windows CE and Windows Mobile should return C{ARCH_ARM}. Python on Solaris using Wine would return C{ARCH_SPARC}. Python in an Itanium machine should return C{ARCH_IA64} both on Wine and proper Windows. All other values should only be returned on Linux using Wine. Here is the function: def _get_arch(): """ Determines the current processor architecture. @rtype: str @return: On error, returns: - L{ARCH_UNKNOWN} (C{"unknown"}) meaning the architecture could not be detected or is not known to WinAppDbg. On success, returns one of the following values: - L{ARCH_I386} (C{"i386"}) for Intel 32-bit x86 processor or compatible. - L{ARCH_AMD64} (C{"amd64"}) for Intel 64-bit x86_64 processor or compatible. May also return one of the following values if you get both Python and WinAppDbg to work in such machines... let me know if you do! :) - L{ARCH_MIPS} (C{"mips"}) for MIPS compatible processors. - L{ARCH_ALPHA} (C{"alpha"}) for Alpha processors. - L{ARCH_PPC} (C{"ppc"}) for PowerPC compatible processors. - L{ARCH_SHX} (C{"shx"}) for Hitachi SH processors. - L{ARCH_ARM} (C{"arm"}) for ARM compatible processors. - L{ARCH_IA64} (C{"ia64"}) for Intel Itanium processor or compatible. - L{ARCH_ALPHA64} (C{"alpha64"}) for Alpha64 processors. - L{ARCH_MSIL} (C{"msil"}) for the .NET virtual machine. - L{ARCH_SPARC} (C{"sparc"}) for Sun Sparc processors. Probably IronPython returns C{ARCH_MSIL} but I haven't tried it. Python on Windows CE and Windows Mobile should return C{ARCH_ARM}. Python on Solaris using Wine would return C{ARCH_SPARC}. Python in an Itanium machine should return C{ARCH_IA64} both on Wine and proper Windows. All other values should only be returned on Linux using Wine. """ try: si = GetNativeSystemInfo() except Exception: si = GetSystemInfo() try: return _arch_map[si.id.w.wProcessorArchitecture] except KeyError: return ARCH_UNKNOWN
Determines the current processor architecture. @rtype: str @return: On error, returns: - L{ARCH_UNKNOWN} (C{"unknown"}) meaning the architecture could not be detected or is not known to WinAppDbg. On success, returns one of the following values: - L{ARCH_I386} (C{"i386"}) for Intel 32-bit x86 processor or compatible. - L{ARCH_AMD64} (C{"amd64"}) for Intel 64-bit x86_64 processor or compatible. May also return one of the following values if you get both Python and WinAppDbg to work in such machines... let me know if you do! :) - L{ARCH_MIPS} (C{"mips"}) for MIPS compatible processors. - L{ARCH_ALPHA} (C{"alpha"}) for Alpha processors. - L{ARCH_PPC} (C{"ppc"}) for PowerPC compatible processors. - L{ARCH_SHX} (C{"shx"}) for Hitachi SH processors. - L{ARCH_ARM} (C{"arm"}) for ARM compatible processors. - L{ARCH_IA64} (C{"ia64"}) for Intel Itanium processor or compatible. - L{ARCH_ALPHA64} (C{"alpha64"}) for Alpha64 processors. - L{ARCH_MSIL} (C{"msil"}) for the .NET virtual machine. - L{ARCH_SPARC} (C{"sparc"}) for Sun Sparc processors. Probably IronPython returns C{ARCH_MSIL} but I haven't tried it. Python on Windows CE and Windows Mobile should return C{ARCH_ARM}. Python on Solaris using Wine would return C{ARCH_SPARC}. Python in an Itanium machine should return C{ARCH_IA64} both on Wine and proper Windows. All other values should only be returned on Linux using Wine.
177,104
from winappdbg.win32.defines import * def GetCurrentProcess(): ## return 0xFFFFFFFFFFFFFFFFL _GetCurrentProcess = windll.kernel32.GetCurrentProcess _GetCurrentProcess.argtypes = [] _GetCurrentProcess.restype = HANDLE return _GetCurrentProcess() def IsWow64Process(hProcess): _IsWow64Process = windll.kernel32.IsWow64Process _IsWow64Process.argtypes = [HANDLE, PBOOL] _IsWow64Process.restype = bool _IsWow64Process.errcheck = RaiseIfZero Wow64Process = BOOL(FALSE) _IsWow64Process(hProcess, byref(Wow64Process)) return bool(Wow64Process) bits = _get_bits() wow64 = _get_wow64() The provided code snippet includes necessary dependencies for implementing the `_get_wow64` function. Write a Python function `def _get_wow64()` to solve the following problem: Determines if the current process is running in Windows-On-Windows 64 bits. @rtype: bool @return: C{True} of the current process is a 32 bit program running in a 64 bit version of Windows, C{False} if it's either a 32 bit program in a 32 bit Windows or a 64 bit program in a 64 bit Windows. Here is the function: def _get_wow64(): """ Determines if the current process is running in Windows-On-Windows 64 bits. @rtype: bool @return: C{True} of the current process is a 32 bit program running in a 64 bit version of Windows, C{False} if it's either a 32 bit program in a 32 bit Windows or a 64 bit program in a 64 bit Windows. """ # Try to determine if the debugger itself is running on WOW64. # On error assume False. if bits == 64: wow64 = False else: try: wow64 = IsWow64Process( GetCurrentProcess() ) except Exception: wow64 = False return wow64
Determines if the current process is running in Windows-On-Windows 64 bits. @rtype: bool @return: C{True} of the current process is a 32 bit program running in a 64 bit version of Windows, C{False} if it's either a 32 bit program in a 32 bit Windows or a 64 bit program in a 64 bit Windows.
177,105
from winappdbg.win32.defines import * VER_PLATFORM_WIN32_NT = 2 VER_SUITE_STORAGE_SERVER = 0x00002000 VER_SUITE_WH_SERVER = 0x00008000 VER_NT_WORKSTATION = 0x0000001 SM_SERVERR2 = 89 def GetSystemMetrics(nIndex): _GetSystemMetrics = windll.user32.GetSystemMetrics _GetSystemMetrics.argtypes = [ctypes.c_int] _GetSystemMetrics.restype = ctypes.c_int return _GetSystemMetrics(nIndex) GetVersionEx = GuessStringType(GetVersionExA, GetVersionExW) ARCH_AMD64 = "amd64" bits = _get_bits() arch = _get_arch() wow64 = _get_wow64() The provided code snippet includes necessary dependencies for implementing the `_get_os` function. Write a Python function `def _get_os(osvi = None)` to solve the following problem: Determines the current operating system. This function allows you to quickly tell apart major OS differences. For more detailed information call L{GetVersionEx} instead. @note: Wine reports itself as Windows XP 32 bits (even if the Linux host is 64 bits). ReactOS may report itself as Windows 2000 or Windows XP, depending on the version of ReactOS. @type osvi: L{OSVERSIONINFOEXA} @param osvi: Optional. The return value from L{GetVersionEx}. @rtype: str @return: One of the following values: - L{OS_UNKNOWN} (C{"Unknown"}) - L{OS_NT} (C{"Windows NT"}) - L{OS_W2K} (C{"Windows 2000"}) - L{OS_XP} (C{"Windows XP"}) - L{OS_XP_64} (C{"Windows XP (64 bits)"}) - L{OS_W2K3} (C{"Windows 2003"}) - L{OS_W2K3_64} (C{"Windows 2003 (64 bits)"}) - L{OS_W2K3R2} (C{"Windows 2003 R2"}) - L{OS_W2K3R2_64} (C{"Windows 2003 R2 (64 bits)"}) - L{OS_W2K8} (C{"Windows 2008"}) - L{OS_W2K8_64} (C{"Windows 2008 (64 bits)"}) - L{OS_W2K8R2} (C{"Windows 2008 R2"}) - L{OS_W2K8R2_64} (C{"Windows 2008 R2 (64 bits)"}) - L{OS_VISTA} (C{"Windows Vista"}) - L{OS_VISTA_64} (C{"Windows Vista (64 bits)"}) - L{OS_W7} (C{"Windows 7"}) - L{OS_W7_64} (C{"Windows 7 (64 bits)"}) Here is the function: def _get_os(osvi = None): """ Determines the current operating system. This function allows you to quickly tell apart major OS differences. For more detailed information call L{GetVersionEx} instead. @note: Wine reports itself as Windows XP 32 bits (even if the Linux host is 64 bits). ReactOS may report itself as Windows 2000 or Windows XP, depending on the version of ReactOS. @type osvi: L{OSVERSIONINFOEXA} @param osvi: Optional. The return value from L{GetVersionEx}. @rtype: str @return: One of the following values: - L{OS_UNKNOWN} (C{"Unknown"}) - L{OS_NT} (C{"Windows NT"}) - L{OS_W2K} (C{"Windows 2000"}) - L{OS_XP} (C{"Windows XP"}) - L{OS_XP_64} (C{"Windows XP (64 bits)"}) - L{OS_W2K3} (C{"Windows 2003"}) - L{OS_W2K3_64} (C{"Windows 2003 (64 bits)"}) - L{OS_W2K3R2} (C{"Windows 2003 R2"}) - L{OS_W2K3R2_64} (C{"Windows 2003 R2 (64 bits)"}) - L{OS_W2K8} (C{"Windows 2008"}) - L{OS_W2K8_64} (C{"Windows 2008 (64 bits)"}) - L{OS_W2K8R2} (C{"Windows 2008 R2"}) - L{OS_W2K8R2_64} (C{"Windows 2008 R2 (64 bits)"}) - L{OS_VISTA} (C{"Windows Vista"}) - L{OS_VISTA_64} (C{"Windows Vista (64 bits)"}) - L{OS_W7} (C{"Windows 7"}) - L{OS_W7_64} (C{"Windows 7 (64 bits)"}) """ # rough port of http://msdn.microsoft.com/en-us/library/ms724429%28VS.85%29.aspx if not osvi: osvi = GetVersionEx() if osvi.dwPlatformId == VER_PLATFORM_WIN32_NT and osvi.dwMajorVersion > 4: if osvi.dwMajorVersion == 6: if osvi.dwMinorVersion == 0: if osvi.wProductType == VER_NT_WORKSTATION: if bits == 64 or wow64: return 'Windows Vista (64 bits)' return 'Windows Vista' else: if bits == 64 or wow64: return 'Windows 2008 (64 bits)' return 'Windows 2008' if osvi.dwMinorVersion == 1: if osvi.wProductType == VER_NT_WORKSTATION: if bits == 64 or wow64: return 'Windows 7 (64 bits)' return 'Windows 7' else: if bits == 64 or wow64: return 'Windows 2008 R2 (64 bits)' return 'Windows 2008 R2' if osvi.dwMajorVersion == 5: if osvi.dwMinorVersion == 2: if GetSystemMetrics(SM_SERVERR2): if bits == 64 or wow64: return 'Windows 2003 R2 (64 bits)' return 'Windows 2003 R2' if osvi.wSuiteMask in (VER_SUITE_STORAGE_SERVER, VER_SUITE_WH_SERVER): if bits == 64 or wow64: return 'Windows 2003 (64 bits)' return 'Windows 2003' if osvi.wProductType == VER_NT_WORKSTATION and arch == ARCH_AMD64: return 'Windows XP (64 bits)' else: if bits == 64 or wow64: return 'Windows 2003 (64 bits)' return 'Windows 2003' if osvi.dwMinorVersion == 1: return 'Windows XP' if osvi.dwMinorVersion == 0: return 'Windows 2000' if osvi.dwMajorVersion == 4: return 'Windows NT' return 'Unknown'
Determines the current operating system. This function allows you to quickly tell apart major OS differences. For more detailed information call L{GetVersionEx} instead. @note: Wine reports itself as Windows XP 32 bits (even if the Linux host is 64 bits). ReactOS may report itself as Windows 2000 or Windows XP, depending on the version of ReactOS. @type osvi: L{OSVERSIONINFOEXA} @param osvi: Optional. The return value from L{GetVersionEx}. @rtype: str @return: One of the following values: - L{OS_UNKNOWN} (C{"Unknown"}) - L{OS_NT} (C{"Windows NT"}) - L{OS_W2K} (C{"Windows 2000"}) - L{OS_XP} (C{"Windows XP"}) - L{OS_XP_64} (C{"Windows XP (64 bits)"}) - L{OS_W2K3} (C{"Windows 2003"}) - L{OS_W2K3_64} (C{"Windows 2003 (64 bits)"}) - L{OS_W2K3R2} (C{"Windows 2003 R2"}) - L{OS_W2K3R2_64} (C{"Windows 2003 R2 (64 bits)"}) - L{OS_W2K8} (C{"Windows 2008"}) - L{OS_W2K8_64} (C{"Windows 2008 (64 bits)"}) - L{OS_W2K8R2} (C{"Windows 2008 R2"}) - L{OS_W2K8R2_64} (C{"Windows 2008 R2 (64 bits)"}) - L{OS_VISTA} (C{"Windows Vista"}) - L{OS_VISTA_64} (C{"Windows Vista (64 bits)"}) - L{OS_W7} (C{"Windows 7"}) - L{OS_W7_64} (C{"Windows 7 (64 bits)"})
177,106
from winappdbg.win32.defines import * GetVersionEx = GuessStringType(GetVersionExA, GetVersionExW) The provided code snippet includes necessary dependencies for implementing the `_get_ntddi` function. Write a Python function `def _get_ntddi(osvi)` to solve the following problem: Determines the current operating system. This function allows you to quickly tell apart major OS differences. For more detailed information call L{kernel32.GetVersionEx} instead. @note: Wine reports itself as Windows XP 32 bits (even if the Linux host is 64 bits). ReactOS may report itself as Windows 2000 or Windows XP, depending on the version of ReactOS. @type osvi: L{OSVERSIONINFOEXA} @param osvi: Optional. The return value from L{kernel32.GetVersionEx}. @rtype: int @return: NTDDI version number. Here is the function: def _get_ntddi(osvi): """ Determines the current operating system. This function allows you to quickly tell apart major OS differences. For more detailed information call L{kernel32.GetVersionEx} instead. @note: Wine reports itself as Windows XP 32 bits (even if the Linux host is 64 bits). ReactOS may report itself as Windows 2000 or Windows XP, depending on the version of ReactOS. @type osvi: L{OSVERSIONINFOEXA} @param osvi: Optional. The return value from L{kernel32.GetVersionEx}. @rtype: int @return: NTDDI version number. """ if not osvi: osvi = GetVersionEx() ntddi = 0 ntddi += (osvi.dwMajorVersion & 0xFF) << 24 ntddi += (osvi.dwMinorVersion & 0xFF) << 16 ntddi += (osvi.wServicePackMajor & 0xFF) << 8 ntddi += (osvi.wServicePackMinor & 0xFF) return ntddi
Determines the current operating system. This function allows you to quickly tell apart major OS differences. For more detailed information call L{kernel32.GetVersionEx} instead. @note: Wine reports itself as Windows XP 32 bits (even if the Linux host is 64 bits). ReactOS may report itself as Windows 2000 or Windows XP, depending on the version of ReactOS. @type osvi: L{OSVERSIONINFOEXA} @param osvi: Optional. The return value from L{kernel32.GetVersionEx}. @rtype: int @return: NTDDI version number.
177,107
from winappdbg.win32.defines import * def GetFileVersionInfoA(lptstrFilename): _GetFileVersionInfoA = windll.version.GetFileVersionInfoA _GetFileVersionInfoA.argtypes = [LPSTR, DWORD, DWORD, LPVOID] _GetFileVersionInfoA.restype = bool _GetFileVersionInfoA.errcheck = RaiseIfZero _GetFileVersionInfoSizeA = windll.version.GetFileVersionInfoSizeA _GetFileVersionInfoSizeA.argtypes = [LPSTR, LPVOID] _GetFileVersionInfoSizeA.restype = DWORD _GetFileVersionInfoSizeA.errcheck = RaiseIfZero dwLen = _GetFileVersionInfoSizeA(lptstrFilename, None) lpData = ctypes.create_string_buffer(dwLen) _GetFileVersionInfoA(lptstrFilename, 0, dwLen, byref(lpData)) return lpData
null
177,108
from winappdbg.win32.defines import * def GetFileVersionInfoW(lptstrFilename): _GetFileVersionInfoW = windll.version.GetFileVersionInfoW _GetFileVersionInfoW.argtypes = [LPWSTR, DWORD, DWORD, LPVOID] _GetFileVersionInfoW.restype = bool _GetFileVersionInfoW.errcheck = RaiseIfZero _GetFileVersionInfoSizeW = windll.version.GetFileVersionInfoSizeW _GetFileVersionInfoSizeW.argtypes = [LPWSTR, LPVOID] _GetFileVersionInfoSizeW.restype = DWORD _GetFileVersionInfoSizeW.errcheck = RaiseIfZero dwLen = _GetFileVersionInfoSizeW(lptstrFilename, None) lpData = ctypes.create_string_buffer(dwLen) # not a string! _GetFileVersionInfoW(lptstrFilename, 0, dwLen, byref(lpData)) return lpData
null
177,109
from winappdbg.win32.defines import * def VerQueryValueA(pBlock, lpSubBlock): _VerQueryValueA = windll.version.VerQueryValueA _VerQueryValueA.argtypes = [LPVOID, LPSTR, LPVOID, POINTER(UINT)] _VerQueryValueA.restype = bool _VerQueryValueA.errcheck = RaiseIfZero lpBuffer = LPVOID(0) uLen = UINT(0) _VerQueryValueA(pBlock, lpSubBlock, byref(lpBuffer), byref(uLen)) return lpBuffer, uLen.value
null
177,110
from winappdbg.win32.defines import * def VerQueryValueW(pBlock, lpSubBlock): _VerQueryValueW = windll.version.VerQueryValueW _VerQueryValueW.argtypes = [LPVOID, LPWSTR, LPVOID, POINTER(UINT)] _VerQueryValueW.restype = bool _VerQueryValueW.errcheck = RaiseIfZero lpBuffer = LPVOID(0) uLen = UINT(0) _VerQueryValueW(pBlock, lpSubBlock, byref(lpBuffer), byref(uLen)) return lpBuffer, uLen.value
null
177,111
from winappdbg.win32.defines import * from winappdbg.win32.advapi32 import * def WTSFreeMemory(pMemory): _WTSFreeMemory = windll.wtsapi32.WTSFreeMemory _WTSFreeMemory.argtypes = [PVOID] _WTSFreeMemory.restype = None _WTSFreeMemory(pMemory)
null
177,112
from winappdbg.win32.defines import * from winappdbg.win32.advapi32 import * WTS_CURRENT_SERVER_HANDLE = 0 PWTS_PROCESS_INFOA = POINTER(WTS_PROCESS_INFOA) def WTSEnumerateProcessesA(hServer = WTS_CURRENT_SERVER_HANDLE): _WTSEnumerateProcessesA = windll.wtsapi32.WTSEnumerateProcessesA _WTSEnumerateProcessesA.argtypes = [HANDLE, DWORD, DWORD, POINTER(PWTS_PROCESS_INFOA), PDWORD] _WTSEnumerateProcessesA.restype = bool _WTSEnumerateProcessesA.errcheck = RaiseIfZero pProcessInfo = PWTS_PROCESS_INFOA() Count = DWORD(0) _WTSEnumerateProcessesA(hServer, 0, 1, byref(pProcessInfo), byref(Count)) return pProcessInfo, Count.value
null
177,113
from winappdbg.win32.defines import * from winappdbg.win32.advapi32 import * WTS_CURRENT_SERVER_HANDLE = 0 PWTS_PROCESS_INFOW = POINTER(WTS_PROCESS_INFOW) def WTSEnumerateProcessesW(hServer = WTS_CURRENT_SERVER_HANDLE): _WTSEnumerateProcessesW = windll.wtsapi32.WTSEnumerateProcessesW _WTSEnumerateProcessesW.argtypes = [HANDLE, DWORD, DWORD, POINTER(PWTS_PROCESS_INFOW), PDWORD] _WTSEnumerateProcessesW.restype = bool _WTSEnumerateProcessesW.errcheck = RaiseIfZero pProcessInfo = PWTS_PROCESS_INFOW() Count = DWORD(0) _WTSEnumerateProcessesW(hServer, 0, 1, byref(pProcessInfo), byref(Count)) return pProcessInfo, Count.value
null
177,114
from winappdbg.win32.defines import * from winappdbg.win32.advapi32 import * def WTSTerminateProcess(hServer, ProcessId, ExitCode): _WTSTerminateProcess = windll.wtsapi32.WTSTerminateProcess _WTSTerminateProcess.argtypes = [HANDLE, DWORD, DWORD] _WTSTerminateProcess.restype = bool _WTSTerminateProcess.errcheck = RaiseIfZero _WTSTerminateProcess(hServer, ProcessId, ExitCode)
null
177,115
from winappdbg.win32.defines import * from winappdbg.win32.advapi32 import * def ProcessIdToSessionId(dwProcessId): _ProcessIdToSessionId = windll.kernel32.ProcessIdToSessionId _ProcessIdToSessionId.argtypes = [DWORD, PDWORD] _ProcessIdToSessionId.restype = bool _ProcessIdToSessionId.errcheck = RaiseIfZero dwSessionId = DWORD(0) _ProcessIdToSessionId(dwProcessId, byref(dwSessionId)) return dwSessionId.value
null
177,116
from winappdbg.win32.defines import * from winappdbg.win32.advapi32 import * def WTSGetActiveConsoleSessionId(): _WTSGetActiveConsoleSessionId = windll.kernel32.WTSGetActiveConsoleSessionId _WTSGetActiveConsoleSessionId.argtypes = [] _WTSGetActiveConsoleSessionId.restype = DWORD _WTSGetActiveConsoleSessionId.errcheck = RaiseIfZero return _WTSGetActiveConsoleSessionId()
null
177,117
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * def _load_latest_dbghelp_dll(): from os import getenv from os.path import join, exists program_files_location = getenv("ProgramFiles") if not program_files_location: program_files_location = "C:\\Program Files" program_files_x86_location = getenv("ProgramFiles(x86)") if arch == ARCH_AMD64: if wow64: pathname = join( program_files_x86_location or program_files_location, "Debugging Tools for Windows (x86)", "dbghelp.dll") else: pathname = join( program_files_location, "Debugging Tools for Windows (x64)", "dbghelp.dll") elif arch == ARCH_I386: pathname = join( program_files_location, "Debugging Tools for Windows (x86)", "dbghelp.dll") else: pathname = None if pathname and exists(pathname): try: _dbghelp = ctypes.windll.LoadLibrary(pathname) ctypes.windll.dbghelp = _dbghelp except Exception: pass
null
177,118
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * MakeSureDirectoryPathExists = GuessStringType(MakeSureDirectoryPathExistsA, MakeSureDirectoryPathExistsW) def MakeSureDirectoryPathExistsA(DirPath): _MakeSureDirectoryPathExists = windll.dbghelp.MakeSureDirectoryPathExists _MakeSureDirectoryPathExists.argtypes = [LPSTR] _MakeSureDirectoryPathExists.restype = bool _MakeSureDirectoryPathExists.errcheck = RaiseIfZero return _MakeSureDirectoryPathExists(DirPath)
null
177,119
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * SymInitialize = GuessStringType(SymInitializeA, SymInitializeW) def SymInitializeA(hProcess, UserSearchPath = None, fInvadeProcess = False): _SymInitialize = windll.dbghelp.SymInitialize _SymInitialize.argtypes = [HANDLE, LPSTR, BOOL] _SymInitialize.restype = bool _SymInitialize.errcheck = RaiseIfZero if not UserSearchPath: UserSearchPath = None _SymInitialize(hProcess, UserSearchPath, fInvadeProcess)
null
177,120
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * def SymCleanup(hProcess): _SymCleanup = windll.dbghelp.SymCleanup _SymCleanup.argtypes = [HANDLE] _SymCleanup.restype = bool _SymCleanup.errcheck = RaiseIfZero _SymCleanup(hProcess)
null
177,121
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * def SymRefreshModuleList(hProcess): _SymRefreshModuleList = windll.dbghelp.SymRefreshModuleList _SymRefreshModuleList.argtypes = [HANDLE] _SymRefreshModuleList.restype = bool _SymRefreshModuleList.errcheck = RaiseIfZero _SymRefreshModuleList(hProcess)
null
177,122
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * def SymSetParentWindow(hwnd): _SymSetParentWindow = windll.dbghelp.SymSetParentWindow _SymSetParentWindow.argtypes = [HWND] _SymSetParentWindow.restype = bool _SymSetParentWindow.errcheck = RaiseIfZero _SymSetParentWindow(hwnd)
null
177,123
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * def SymSetOptions(SymOptions): _SymSetOptions = windll.dbghelp.SymSetOptions _SymSetOptions.argtypes = [DWORD] _SymSetOptions.restype = DWORD _SymSetOptions.errcheck = RaiseIfZero _SymSetOptions(SymOptions)
null
177,124
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * def SymGetOptions(): _SymGetOptions = windll.dbghelp.SymGetOptions _SymGetOptions.argtypes = [] _SymGetOptions.restype = DWORD return _SymGetOptions()
null
177,125
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * SymLoadModule = GuessStringType(SymLoadModuleA, SymLoadModuleW) def SymLoadModuleA(hProcess, hFile = None, ImageName = None, ModuleName = None, BaseOfDll = None, SizeOfDll = None): _SymLoadModule = windll.dbghelp.SymLoadModule _SymLoadModule.argtypes = [HANDLE, HANDLE, LPSTR, LPSTR, DWORD, DWORD] _SymLoadModule.restype = DWORD if not ImageName: ImageName = None if not ModuleName: ModuleName = None if not BaseOfDll: BaseOfDll = 0 if not SizeOfDll: SizeOfDll = 0 SetLastError(ERROR_SUCCESS) lpBaseAddress = _SymLoadModule(hProcess, hFile, ImageName, ModuleName, BaseOfDll, SizeOfDll) if lpBaseAddress == NULL: dwErrorCode = GetLastError() if dwErrorCode != ERROR_SUCCESS: raise ctypes.WinError(dwErrorCode) return lpBaseAddress
null
177,126
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * SymLoadModule64 = GuessStringType(SymLoadModule64A, SymLoadModule64W) def SymLoadModule64A(hProcess, hFile = None, ImageName = None, ModuleName = None, BaseOfDll = None, SizeOfDll = None): _SymLoadModule64 = windll.dbghelp.SymLoadModule64 _SymLoadModule64.argtypes = [HANDLE, HANDLE, LPSTR, LPSTR, DWORD64, DWORD] _SymLoadModule64.restype = DWORD64 if not ImageName: ImageName = None if not ModuleName: ModuleName = None if not BaseOfDll: BaseOfDll = 0 if not SizeOfDll: SizeOfDll = 0 SetLastError(ERROR_SUCCESS) lpBaseAddress = _SymLoadModule64(hProcess, hFile, ImageName, ModuleName, BaseOfDll, SizeOfDll) if lpBaseAddress == NULL: dwErrorCode = GetLastError() if dwErrorCode != ERROR_SUCCESS: raise ctypes.WinError(dwErrorCode) return lpBaseAddress
null
177,127
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * def SymUnloadModule(hProcess, BaseOfDll): _SymUnloadModule = windll.dbghelp.SymUnloadModule _SymUnloadModule.argtypes = [HANDLE, DWORD] _SymUnloadModule.restype = bool _SymUnloadModule.errcheck = RaiseIfZero _SymUnloadModule(hProcess, BaseOfDll)
null
177,128
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * def SymUnloadModule64(hProcess, BaseOfDll): _SymUnloadModule64 = windll.dbghelp.SymUnloadModule64 _SymUnloadModule64.argtypes = [HANDLE, DWORD64] _SymUnloadModule64.restype = bool _SymUnloadModule64.errcheck = RaiseIfZero _SymUnloadModule64(hProcess, BaseOfDll)
null
177,129
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * class IMAGEHLP_MODULE (Structure): _fields_ = [ ("SizeOfStruct", DWORD), ("BaseOfImage", DWORD), ("ImageSize", DWORD), ("TimeDateStamp", DWORD), ("CheckSum", DWORD), ("NumSyms", DWORD), ("SymType", DWORD), # SYM_TYPE ("ModuleName", CHAR * 32), ("ImageName", CHAR * 256), ("LoadedImageName", CHAR * 256), ] PIMAGEHLP_MODULE = POINTER(IMAGEHLP_MODULE) SymGetModuleInfo = GuessStringType(SymGetModuleInfoA, SymGetModuleInfoW) def SymGetModuleInfoA(hProcess, dwAddr): _SymGetModuleInfo = windll.dbghelp.SymGetModuleInfo _SymGetModuleInfo.argtypes = [HANDLE, DWORD, PIMAGEHLP_MODULE] _SymGetModuleInfo.restype = bool _SymGetModuleInfo.errcheck = RaiseIfZero ModuleInfo = IMAGEHLP_MODULE() ModuleInfo.SizeOfStruct = sizeof(ModuleInfo) _SymGetModuleInfo(hProcess, dwAddr, byref(ModuleInfo)) return ModuleInfo
null
177,130
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * class IMAGEHLP_MODULEW (Structure): _fields_ = [ ("SizeOfStruct", DWORD), ("BaseOfImage", DWORD), ("ImageSize", DWORD), ("TimeDateStamp", DWORD), ("CheckSum", DWORD), ("NumSyms", DWORD), ("SymType", DWORD), # SYM_TYPE ("ModuleName", WCHAR * 32), ("ImageName", WCHAR * 256), ("LoadedImageName", WCHAR * 256), ] PIMAGEHLP_MODULEW = POINTER(IMAGEHLP_MODULEW) def SymGetModuleInfoW(hProcess, dwAddr): _SymGetModuleInfoW = windll.dbghelp.SymGetModuleInfoW _SymGetModuleInfoW.argtypes = [HANDLE, DWORD, PIMAGEHLP_MODULEW] _SymGetModuleInfoW.restype = bool _SymGetModuleInfoW.errcheck = RaiseIfZero ModuleInfo = IMAGEHLP_MODULEW() ModuleInfo.SizeOfStruct = sizeof(ModuleInfo) _SymGetModuleInfoW(hProcess, dwAddr, byref(ModuleInfo)) return ModuleInfo
null
177,131
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * class IMAGEHLP_MODULE64 (Structure): _fields_ = [ ("SizeOfStruct", DWORD), ("BaseOfImage", DWORD64), ("ImageSize", DWORD), ("TimeDateStamp", DWORD), ("CheckSum", DWORD), ("NumSyms", DWORD), ("SymType", DWORD), # SYM_TYPE ("ModuleName", CHAR * 32), ("ImageName", CHAR * 256), ("LoadedImageName", CHAR * 256), ("LoadedPdbName", CHAR * 256), ("CVSig", DWORD), ("CVData", CHAR * (MAX_PATH * 3)), ("PdbSig", DWORD), ("PdbSig70", GUID), ("PdbAge", DWORD), ("PdbUnmatched", BOOL), ("DbgUnmatched", BOOL), ("LineNumbers", BOOL), ("GlobalSymbols", BOOL), ("TypeInfo", BOOL), ("SourceIndexed", BOOL), ("Publics", BOOL), ] PIMAGEHLP_MODULE64 = POINTER(IMAGEHLP_MODULE64) SymGetModuleInfo64 = GuessStringType(SymGetModuleInfo64A, SymGetModuleInfo64W) def SymGetModuleInfo64A(hProcess, dwAddr): _SymGetModuleInfo64 = windll.dbghelp.SymGetModuleInfo64 _SymGetModuleInfo64.argtypes = [HANDLE, DWORD64, PIMAGEHLP_MODULE64] _SymGetModuleInfo64.restype = bool _SymGetModuleInfo64.errcheck = RaiseIfZero ModuleInfo = IMAGEHLP_MODULE64() ModuleInfo.SizeOfStruct = sizeof(ModuleInfo) _SymGetModuleInfo64(hProcess, dwAddr, byref(ModuleInfo)) return ModuleInfo
null
177,132
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * def SymGetModuleInfo64W(hProcess, dwAddr): _SymGetModuleInfo64W = windll.dbghelp.SymGetModuleInfo64W _SymGetModuleInfo64W.argtypes = [HANDLE, DWORD64, PIMAGEHLP_MODULE64W] _SymGetModuleInfo64W.restype = bool _SymGetModuleInfo64W.errcheck = RaiseIfZero ModuleInfo = IMAGEHLP_MODULE64W() ModuleInfo.SizeOfStruct = sizeof(ModuleInfo) _SymGetModuleInfo64W(hProcess, dwAddr, byref(ModuleInfo)) return ModuleInfo
null
177,133
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * PSYM_ENUMMODULES_CALLBACK = WINFUNCTYPE(BOOL, LPSTR, DWORD, PVOID) SymEnumerateModules = GuessStringType(SymEnumerateModulesA, SymEnumerateModulesW) def SymEnumerateModulesA(hProcess, EnumModulesCallback, UserContext = None): _SymEnumerateModules = windll.dbghelp.SymEnumerateModules _SymEnumerateModules.argtypes = [HANDLE, PSYM_ENUMMODULES_CALLBACK, PVOID] _SymEnumerateModules.restype = bool _SymEnumerateModules.errcheck = RaiseIfZero EnumModulesCallback = PSYM_ENUMMODULES_CALLBACK(EnumModulesCallback) if UserContext: UserContext = ctypes.pointer(UserContext) else: UserContext = LPVOID(NULL) _SymEnumerateModules(hProcess, EnumModulesCallback, UserContext)
null
177,134
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * PSYM_ENUMMODULES_CALLBACKW = WINFUNCTYPE(BOOL, LPWSTR, DWORD, PVOID) def SymEnumerateModulesW(hProcess, EnumModulesCallback, UserContext = None): _SymEnumerateModulesW = windll.dbghelp.SymEnumerateModulesW _SymEnumerateModulesW.argtypes = [HANDLE, PSYM_ENUMMODULES_CALLBACKW, PVOID] _SymEnumerateModulesW.restype = bool _SymEnumerateModulesW.errcheck = RaiseIfZero EnumModulesCallback = PSYM_ENUMMODULES_CALLBACKW(EnumModulesCallback) if UserContext: UserContext = ctypes.pointer(UserContext) else: UserContext = LPVOID(NULL) _SymEnumerateModulesW(hProcess, EnumModulesCallback, UserContext)
null
177,135
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * PSYM_ENUMMODULES_CALLBACK64 = WINFUNCTYPE(BOOL, LPSTR, DWORD64, PVOID) SymEnumerateModules64 = GuessStringType(SymEnumerateModules64A, SymEnumerateModules64W) def SymEnumerateModules64A(hProcess, EnumModulesCallback, UserContext = None): _SymEnumerateModules64 = windll.dbghelp.SymEnumerateModules64 _SymEnumerateModules64.argtypes = [HANDLE, PSYM_ENUMMODULES_CALLBACK64, PVOID] _SymEnumerateModules64.restype = bool _SymEnumerateModules64.errcheck = RaiseIfZero EnumModulesCallback = PSYM_ENUMMODULES_CALLBACK64(EnumModulesCallback) if UserContext: UserContext = ctypes.pointer(UserContext) else: UserContext = LPVOID(NULL) _SymEnumerateModules64(hProcess, EnumModulesCallback, UserContext)
null
177,136
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * def SymEnumerateModules64W(hProcess, EnumModulesCallback, UserContext = None): _SymEnumerateModules64W = windll.dbghelp.SymEnumerateModules64W _SymEnumerateModules64W.argtypes = [HANDLE, PSYM_ENUMMODULES_CALLBACK64W, PVOID] _SymEnumerateModules64W.restype = bool _SymEnumerateModules64W.errcheck = RaiseIfZero EnumModulesCallback = PSYM_ENUMMODULES_CALLBACK64W(EnumModulesCallback) if UserContext: UserContext = ctypes.pointer(UserContext) else: UserContext = LPVOID(NULL) _SymEnumerateModules64W(hProcess, EnumModulesCallback, UserContext)
null
177,137
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * PSYM_ENUMSYMBOLS_CALLBACK = WINFUNCTYPE(BOOL, LPSTR, DWORD, ULONG, PVOID) SymEnumerateSymbols = GuessStringType(SymEnumerateSymbolsA, SymEnumerateSymbolsW) def SymEnumerateSymbolsA(hProcess, BaseOfDll, EnumSymbolsCallback, UserContext = None): _SymEnumerateSymbols = windll.dbghelp.SymEnumerateSymbols _SymEnumerateSymbols.argtypes = [HANDLE, ULONG, PSYM_ENUMSYMBOLS_CALLBACK, PVOID] _SymEnumerateSymbols.restype = bool _SymEnumerateSymbols.errcheck = RaiseIfZero EnumSymbolsCallback = PSYM_ENUMSYMBOLS_CALLBACK(EnumSymbolsCallback) if UserContext: UserContext = ctypes.pointer(UserContext) else: UserContext = LPVOID(NULL) _SymEnumerateSymbols(hProcess, BaseOfDll, EnumSymbolsCallback, UserContext)
null
177,138
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * PSYM_ENUMSYMBOLS_CALLBACKW = WINFUNCTYPE(BOOL, LPWSTR, DWORD, ULONG, PVOID) def SymEnumerateSymbolsW(hProcess, BaseOfDll, EnumSymbolsCallback, UserContext = None): _SymEnumerateSymbolsW = windll.dbghelp.SymEnumerateSymbolsW _SymEnumerateSymbolsW.argtypes = [HANDLE, ULONG, PSYM_ENUMSYMBOLS_CALLBACKW, PVOID] _SymEnumerateSymbolsW.restype = bool _SymEnumerateSymbolsW.errcheck = RaiseIfZero EnumSymbolsCallback = PSYM_ENUMSYMBOLS_CALLBACKW(EnumSymbolsCallback) if UserContext: UserContext = ctypes.pointer(UserContext) else: UserContext = LPVOID(NULL) _SymEnumerateSymbolsW(hProcess, BaseOfDll, EnumSymbolsCallback, UserContext)
null
177,139
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * PSYM_ENUMSYMBOLS_CALLBACK64 = WINFUNCTYPE(BOOL, LPSTR, DWORD64, ULONG, PVOID) SymEnumerateSymbols64 = GuessStringType(SymEnumerateSymbols64A, SymEnumerateSymbols64W) def SymEnumerateSymbols64A(hProcess, BaseOfDll, EnumSymbolsCallback, UserContext = None): _SymEnumerateSymbols64 = windll.dbghelp.SymEnumerateSymbols64 _SymEnumerateSymbols64.argtypes = [HANDLE, ULONG64, PSYM_ENUMSYMBOLS_CALLBACK64, PVOID] _SymEnumerateSymbols64.restype = bool _SymEnumerateSymbols64.errcheck = RaiseIfZero EnumSymbolsCallback = PSYM_ENUMSYMBOLS_CALLBACK64(EnumSymbolsCallback) if UserContext: UserContext = ctypes.pointer(UserContext) else: UserContext = LPVOID(NULL) _SymEnumerateSymbols64(hProcess, BaseOfDll, EnumSymbolsCallback, UserContext)
null
177,140
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * def SymEnumerateSymbols64W(hProcess, BaseOfDll, EnumSymbolsCallback, UserContext = None): _SymEnumerateSymbols64W = windll.dbghelp.SymEnumerateSymbols64W _SymEnumerateSymbols64W.argtypes = [HANDLE, ULONG64, PSYM_ENUMSYMBOLS_CALLBACK64W, PVOID] _SymEnumerateSymbols64W.restype = bool _SymEnumerateSymbols64W.errcheck = RaiseIfZero EnumSymbolsCallback = PSYM_ENUMSYMBOLS_CALLBACK64W(EnumSymbolsCallback) if UserContext: UserContext = ctypes.pointer(UserContext) else: UserContext = LPVOID(NULL) _SymEnumerateSymbols64W(hProcess, BaseOfDll, EnumSymbolsCallback, UserContext)
null
177,141
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * UNDNAME_COMPLETE = 0x0000 UnDecorateSymbolName = GuessStringType(UnDecorateSymbolNameA, UnDecorateSymbolNameW) def UnDecorateSymbolNameA(DecoratedName, Flags = UNDNAME_COMPLETE): _UnDecorateSymbolNameA = windll.dbghelp.UnDecorateSymbolName _UnDecorateSymbolNameA.argtypes = [LPSTR, LPSTR, DWORD, DWORD] _UnDecorateSymbolNameA.restype = DWORD _UnDecorateSymbolNameA.errcheck = RaiseIfZero UndecoratedLength = _UnDecorateSymbolNameA(DecoratedName, None, 0, Flags) UnDecoratedName = ctypes.create_string_buffer('', UndecoratedLength + 1) _UnDecorateSymbolNameA(DecoratedName, UnDecoratedName, UndecoratedLength, Flags) return UnDecoratedName.value
null
177,142
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * UNDNAME_COMPLETE = 0x0000 def UnDecorateSymbolNameW(DecoratedName, Flags = UNDNAME_COMPLETE): _UnDecorateSymbolNameW = windll.dbghelp.UnDecorateSymbolNameW _UnDecorateSymbolNameW.argtypes = [LPWSTR, LPWSTR, DWORD, DWORD] _UnDecorateSymbolNameW.restype = DWORD _UnDecorateSymbolNameW.errcheck = RaiseIfZero UndecoratedLength = _UnDecorateSymbolNameW(DecoratedName, None, 0, Flags) UnDecoratedName = ctypes.create_unicode_buffer(u'', UndecoratedLength + 1) _UnDecorateSymbolNameW(DecoratedName, UnDecoratedName, UndecoratedLength, Flags) return UnDecoratedName.value
null
177,143
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * SymGetSearchPath = GuessStringType(SymGetSearchPathA, SymGetSearchPathW) def SymGetSearchPathA(hProcess): _SymGetSearchPath = windll.dbghelp.SymGetSearchPath _SymGetSearchPath.argtypes = [HANDLE, LPSTR, DWORD] _SymGetSearchPath.restype = bool _SymGetSearchPath.errcheck = RaiseIfZero SearchPathLength = MAX_PATH SearchPath = ctypes.create_string_buffer("", SearchPathLength) _SymGetSearchPath(hProcess, SearchPath, SearchPathLength) return SearchPath.value
null
177,144
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * def SymGetSearchPathW(hProcess): _SymGetSearchPathW = windll.dbghelp.SymGetSearchPathW _SymGetSearchPathW.argtypes = [HANDLE, LPWSTR, DWORD] _SymGetSearchPathW.restype = bool _SymGetSearchPathW.errcheck = RaiseIfZero SearchPathLength = MAX_PATH SearchPath = ctypes.create_unicode_buffer(u"", SearchPathLength) _SymGetSearchPathW(hProcess, SearchPath, SearchPathLength) return SearchPath.value
null
177,145
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * SymSetSearchPath = GuessStringType(SymSetSearchPathA, SymSetSearchPathW) def SymSetSearchPathA(hProcess, SearchPath = None): _SymSetSearchPath = windll.dbghelp.SymSetSearchPath _SymSetSearchPath.argtypes = [HANDLE, LPSTR] _SymSetSearchPath.restype = bool _SymSetSearchPath.errcheck = RaiseIfZero if not SearchPath: SearchPath = None _SymSetSearchPath(hProcess, SearchPath)
null
177,146
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * def SymSetSearchPathW(hProcess, SearchPath = None): _SymSetSearchPathW = windll.dbghelp.SymSetSearchPathW _SymSetSearchPathW.argtypes = [HANDLE, LPWSTR] _SymSetSearchPathW.restype = bool _SymSetSearchPathW.errcheck = RaiseIfZero if not SearchPath: SearchPath = None _SymSetSearchPathW(hProcess, SearchPath)
null
177,147
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * def SymGetHomeDirectoryA(type): _SymGetHomeDirectoryA = windll.dbghelp.SymGetHomeDirectoryA _SymGetHomeDirectoryA.argtypes = [DWORD, LPSTR, SIZE_T] _SymGetHomeDirectoryA.restype = LPSTR _SymGetHomeDirectoryA.errcheck = RaiseIfZero size = MAX_PATH dir = ctypes.create_string_buffer("", size) _SymGetHomeDirectoryA(type, dir, size) return dir.value
null
177,148
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * def SymGetHomeDirectoryW(type): _SymGetHomeDirectoryW = windll.dbghelp.SymGetHomeDirectoryW _SymGetHomeDirectoryW.argtypes = [DWORD, LPWSTR, SIZE_T] _SymGetHomeDirectoryW.restype = LPWSTR _SymGetHomeDirectoryW.errcheck = RaiseIfZero size = MAX_PATH dir = ctypes.create_unicode_buffer(u"", size) _SymGetHomeDirectoryW(type, dir, size) return dir.value
null
177,149
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * def SymSetHomeDirectoryA(hProcess, dir = None): _SymSetHomeDirectoryA = windll.dbghelp.SymSetHomeDirectoryA _SymSetHomeDirectoryA.argtypes = [HANDLE, LPSTR] _SymSetHomeDirectoryA.restype = LPSTR _SymSetHomeDirectoryA.errcheck = RaiseIfZero if not dir: dir = None _SymSetHomeDirectoryA(hProcess, dir) return dir
null
177,150
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * def SymSetHomeDirectoryW(hProcess, dir = None): _SymSetHomeDirectoryW = windll.dbghelp.SymSetHomeDirectoryW _SymSetHomeDirectoryW.argtypes = [HANDLE, LPWSTR] _SymSetHomeDirectoryW.restype = LPWSTR _SymSetHomeDirectoryW.errcheck = RaiseIfZero if not dir: dir = None _SymSetHomeDirectoryW(hProcess, dir) return dir
null
177,151
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * MAX_SYM_NAME = 2000 class SYM_INFO(Structure): _fields_ = [ ("SizeOfStruct", ULONG), ("TypeIndex", ULONG), ("Reserved", ULONG64 * 2), ("Index", ULONG), ("Size", ULONG), ("ModBase", ULONG64), ("Flags", ULONG), ("Value", ULONG64), ("Address", ULONG64), ("Register", ULONG), ("Scope", ULONG), ("Tag", ULONG), ("NameLen", ULONG), ("MaxNameLen", ULONG), ("Name", CHAR * (MAX_SYM_NAME + 1)), ] PSYM_INFO = POINTER(SYM_INFO) def SymFromName(hProcess, Name): _SymFromNameA = windll.dbghelp.SymFromName _SymFromNameA.argtypes = [HANDLE, LPSTR, PSYM_INFO] _SymFromNameA.restype = bool _SymFromNameA.errcheck = RaiseIfZero SymInfo = SYM_INFO() SymInfo.SizeOfStruct = 88 # *don't modify*: sizeof(SYMBOL_INFO) in C. SymInfo.MaxNameLen = MAX_SYM_NAME _SymFromNameA(hProcess, Name, byref(SymInfo)) return SymInfo
null
177,152
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * MAX_SYM_NAME = 2000 class SYM_INFOW(Structure): _fields_ = [ ("SizeOfStruct", ULONG), ("TypeIndex", ULONG), ("Reserved", ULONG64 * 2), ("Index", ULONG), ("Size", ULONG), ("ModBase", ULONG64), ("Flags", ULONG), ("Value", ULONG64), ("Address", ULONG64), ("Register", ULONG), ("Scope", ULONG), ("Tag", ULONG), ("NameLen", ULONG), ("MaxNameLen", ULONG), ("Name", WCHAR * (MAX_SYM_NAME + 1)), ] PSYM_INFOW = POINTER(SYM_INFOW) def SymFromNameW(hProcess, Name): _SymFromNameW = windll.dbghelp.SymFromNameW _SymFromNameW.argtypes = [HANDLE, LPWSTR, PSYM_INFOW] _SymFromNameW.restype = bool _SymFromNameW.errcheck = RaiseIfZero SymInfo = SYM_INFOW() SymInfo.SizeOfStruct = 88 # *don't modify*: sizeof(SYMBOL_INFOW) in C. SymInfo.MaxNameLen = MAX_SYM_NAME _SymFromNameW(hProcess, Name, byref(SymInfo)) return SymInfo
null
177,153
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * MAX_SYM_NAME = 2000 class SYM_INFO(Structure): _fields_ = [ ("SizeOfStruct", ULONG), ("TypeIndex", ULONG), ("Reserved", ULONG64 * 2), ("Index", ULONG), ("Size", ULONG), ("ModBase", ULONG64), ("Flags", ULONG), ("Value", ULONG64), ("Address", ULONG64), ("Register", ULONG), ("Scope", ULONG), ("Tag", ULONG), ("NameLen", ULONG), ("MaxNameLen", ULONG), ("Name", CHAR * (MAX_SYM_NAME + 1)), ] PSYM_INFO = POINTER(SYM_INFO) def SymFromAddr(hProcess, Address): _SymFromAddr = windll.dbghelp.SymFromAddr _SymFromAddr.argtypes = [HANDLE, DWORD64, PDWORD64, PSYM_INFO] _SymFromAddr.restype = bool _SymFromAddr.errcheck = RaiseIfZero SymInfo = SYM_INFO() SymInfo.SizeOfStruct = 88 # *don't modify*: sizeof(SYMBOL_INFO) in C. SymInfo.MaxNameLen = MAX_SYM_NAME Displacement = DWORD64(0) _SymFromAddr(hProcess, Address, byref(Displacement), byref(SymInfo)) return (Displacement.value, SymInfo)
null
177,154
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * MAX_SYM_NAME = 2000 class SYM_INFOW(Structure): _fields_ = [ ("SizeOfStruct", ULONG), ("TypeIndex", ULONG), ("Reserved", ULONG64 * 2), ("Index", ULONG), ("Size", ULONG), ("ModBase", ULONG64), ("Flags", ULONG), ("Value", ULONG64), ("Address", ULONG64), ("Register", ULONG), ("Scope", ULONG), ("Tag", ULONG), ("NameLen", ULONG), ("MaxNameLen", ULONG), ("Name", WCHAR * (MAX_SYM_NAME + 1)), ] PSYM_INFOW = POINTER(SYM_INFOW) def SymFromAddrW(hProcess, Address): _SymFromAddr = windll.dbghelp.SymFromAddrW _SymFromAddr.argtypes = [HANDLE, DWORD64, PDWORD64, PSYM_INFOW] _SymFromAddr.restype = bool _SymFromAddr.errcheck = RaiseIfZero SymInfo = SYM_INFOW() SymInfo.SizeOfStruct = 88 # *don't modify*: sizeof(SYMBOL_INFOW) in C. SymInfo.MaxNameLen = MAX_SYM_NAME Displacement = DWORD64(0) _SymFromAddr(hProcess, Address, byref(Displacement), byref(SymInfo)) return (Displacement.value, SymInfo)
null
177,155
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * MAX_SYM_NAME = 2000 class IMAGEHLP_SYMBOL64 (Structure): _fields_ = [ ("SizeOfStruct", DWORD), ("Address", DWORD64), ("Size", DWORD), ("Flags", DWORD), ("MaxNameLength", DWORD), ("Name", CHAR * (MAX_SYM_NAME + 1)), ] PIMAGEHLP_SYMBOL64 = POINTER(IMAGEHLP_SYMBOL64) def SymGetSymFromAddr64(hProcess, Address): _SymGetSymFromAddr64 = windll.dbghelp.SymGetSymFromAddr64 _SymGetSymFromAddr64.argtypes = [HANDLE, DWORD64, PDWORD64, PIMAGEHLP_SYMBOL64] _SymGetSymFromAddr64.restype = bool _SymGetSymFromAddr64.errcheck = RaiseIfZero imagehlp_symbol64 = IMAGEHLP_SYMBOL64() imagehlp_symbol64.SizeOfStruct = 32 # *don't modify*: sizeof(IMAGEHLP_SYMBOL64) in C. imagehlp_symbol64.MaxNameLen = MAX_SYM_NAME Displacement = DWORD64(0) _SymGetSymFromAddr64(hProcess, Address, byref(Displacement), byref(imagehlp_symbol64)) return (Displacement.value, imagehlp_symbol64)
null
177,156
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * LPAPI_VERSION = PAPI_VERSION def ImagehlpApiVersion(): _ImagehlpApiVersion = windll.dbghelp.ImagehlpApiVersion _ImagehlpApiVersion.restype = LPAPI_VERSION api_version = _ImagehlpApiVersion() return api_version.contents
null
177,157
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * class API_VERSION (Structure): _fields_ = [ ("MajorVersion", USHORT), ("MinorVersion", USHORT), ("Revision", USHORT), ("Reserved", USHORT), ] LPAPI_VERSION = PAPI_VERSION def ImagehlpApiVersionEx(MajorVersion, MinorVersion, Revision): _ImagehlpApiVersionEx = windll.dbghelp.ImagehlpApiVersionEx _ImagehlpApiVersionEx.argtypes = [LPAPI_VERSION] _ImagehlpApiVersionEx.restype = LPAPI_VERSION api_version = API_VERSION(MajorVersion, MinorVersion, Revision, 0) ret_api_version = _ImagehlpApiVersionEx(byref(api_version)) return ret_api_version.contents
null
177,158
from winappdbg.win32.defines import * from winappdbg.win32.version import * from winappdbg.win32.kernel32 import * LPSTACKFRAME64 = POINTER(STACKFRAME64) PREAD_PROCESS_MEMORY_ROUTINE64 = WINFUNCTYPE(BOOL, HANDLE, DWORD64, PVOID, DWORD, LPDWORD) PFUNCTION_TABLE_ACCESS_ROUTINE64 = WINFUNCTYPE(PVOID, HANDLE, DWORD64) PGET_MODULE_BASE_ROUTINE64 = WINFUNCTYPE(DWORD64, HANDLE, DWORD64) PTRANSLATE_ADDRESS_ROUTINE64 = WINFUNCTYPE(DWORD64, HANDLE, DWORD64) def StackWalk64(MachineType, hProcess, hThread, StackFrame, ContextRecord = None, ReadMemoryRoutine = None, FunctionTableAccessRoutine = None, GetModuleBaseRoutine = None, TranslateAddress = None): _StackWalk64 = windll.dbghelp.StackWalk64 _StackWalk64.argtypes = [DWORD, HANDLE, HANDLE, LPSTACKFRAME64, PVOID, PREAD_PROCESS_MEMORY_ROUTINE64, PFUNCTION_TABLE_ACCESS_ROUTINE64, PGET_MODULE_BASE_ROUTINE64, PTRANSLATE_ADDRESS_ROUTINE64] _StackWalk64.restype = bool pReadMemoryRoutine = None if ReadMemoryRoutine: pReadMemoryRoutine = PREAD_PROCESS_MEMORY_ROUTINE64(ReadMemoryRoutine) else: pReadMemoryRoutine = ctypes.cast(None, PREAD_PROCESS_MEMORY_ROUTINE64) pFunctionTableAccessRoutine = None if FunctionTableAccessRoutine: pFunctionTableAccessRoutine = PFUNCTION_TABLE_ACCESS_ROUTINE64(FunctionTableAccessRoutine) else: pFunctionTableAccessRoutine = ctypes.cast(None, PFUNCTION_TABLE_ACCESS_ROUTINE64) pGetModuleBaseRoutine = None if GetModuleBaseRoutine: pGetModuleBaseRoutine = PGET_MODULE_BASE_ROUTINE64(GetModuleBaseRoutine) else: pGetModuleBaseRoutine = ctypes.cast(None, PGET_MODULE_BASE_ROUTINE64) pTranslateAddress = None if TranslateAddress: pTranslateAddress = PTRANSLATE_ADDRESS_ROUTINE64(TranslateAddress) else: pTranslateAddress = ctypes.cast(None, PTRANSLATE_ADDRESS_ROUTINE64) pContextRecord = None if ContextRecord is None: ContextRecord = GetThreadContext(hThread, raw=True) pContextRecord = PCONTEXT(ContextRecord) #this function *DOESN'T* set last error [GetLastError()] properly most of the time. ret = _StackWalk64(MachineType, hProcess, hThread, byref(StackFrame), pContextRecord, pReadMemoryRoutine, pFunctionTableAccessRoutine, pGetModuleBaseRoutine, pTranslateAddress) return ret
null
177,159
from winappdbg.win32.defines import * from winappdbg.win32.version import ARCH_I386 class LDT_ENTRY(Structure): LPLDT_ENTRY = PLDT_ENTRY def GetThreadSelectorEntry(hThread, dwSelector): _GetThreadSelectorEntry = windll.kernel32.GetThreadSelectorEntry _GetThreadSelectorEntry.argtypes = [HANDLE, DWORD, LPLDT_ENTRY] _GetThreadSelectorEntry.restype = bool _GetThreadSelectorEntry.errcheck = RaiseIfZero ldt = LDT_ENTRY() _GetThreadSelectorEntry(hThread, dwSelector, byref(ldt)) return ldt
null
177,160
from winappdbg.win32.defines import * from winappdbg.win32.version import ARCH_I386 CONTEXT_i386 = 0x00010000 CONTEXT_ALL = (CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS | \ CONTEXT_FLOATING_POINT | CONTEXT_DEBUG_REGISTERS | \ CONTEXT_EXTENDED_REGISTERS) class CONTEXT(Structure): arch = ARCH_I386 _pack_ = 1 # Context Frame # # This frame has a several purposes: 1) it is used as an argument to # NtContinue, 2) is is used to constuct a call frame for APC delivery, # and 3) it is used in the user level thread creation routines. # # The layout of the record conforms to a standard call frame. _fields_ = [ # The flags values within this flag control the contents of # a CONTEXT record. # # If the context record is used as an input parameter, then # for each portion of the context record controlled by a flag # whose value is set, it is assumed that that portion of the # context record contains valid context. If the context record # is being used to modify a threads context, then only that # portion of the threads context will be modified. # # If the context record is used as an IN OUT parameter to capture # the context of a thread, then only those portions of the thread's # context corresponding to set flags will be returned. # # The context record is never used as an OUT only parameter. ('ContextFlags', DWORD), # This section is specified/returned if CONTEXT_DEBUG_REGISTERS is # set in ContextFlags. Note that CONTEXT_DEBUG_REGISTERS is NOT # included in CONTEXT_FULL. ('Dr0', DWORD), ('Dr1', DWORD), ('Dr2', DWORD), ('Dr3', DWORD), ('Dr6', DWORD), ('Dr7', DWORD), # This section is specified/returned if the # ContextFlags word contains the flag CONTEXT_FLOATING_POINT. ('FloatSave', FLOATING_SAVE_AREA), # This section is specified/returned if the # ContextFlags word contains the flag CONTEXT_SEGMENTS. ('SegGs', DWORD), ('SegFs', DWORD), ('SegEs', DWORD), ('SegDs', DWORD), # This section is specified/returned if the # ContextFlags word contains the flag CONTEXT_INTEGER. ('Edi', DWORD), ('Esi', DWORD), ('Ebx', DWORD), ('Edx', DWORD), ('Ecx', DWORD), ('Eax', DWORD), # This section is specified/returned if the # ContextFlags word contains the flag CONTEXT_CONTROL. ('Ebp', DWORD), ('Eip', DWORD), ('SegCs', DWORD), # MUST BE SANITIZED ('EFlags', DWORD), # MUST BE SANITIZED ('Esp', DWORD), ('SegSs', DWORD), # This section is specified/returned if the ContextFlags word # contains the flag CONTEXT_EXTENDED_REGISTERS. # The format and contexts are processor specific. ('ExtendedRegisters', BYTE * MAXIMUM_SUPPORTED_EXTENSION), ] _ctx_debug = ('Dr0', 'Dr1', 'Dr2', 'Dr3', 'Dr6', 'Dr7') _ctx_segs = ('SegGs', 'SegFs', 'SegEs', 'SegDs', ) _ctx_int = ('Edi', 'Esi', 'Ebx', 'Edx', 'Ecx', 'Eax') _ctx_ctrl = ('Ebp', 'Eip', 'SegCs', 'EFlags', 'Esp', 'SegSs') def from_dict(cls, ctx): 'Instance a new structure from a Python dictionary.' ctx = Context(ctx) s = cls() ContextFlags = ctx['ContextFlags'] setattr(s, 'ContextFlags', ContextFlags) if (ContextFlags & CONTEXT_DEBUG_REGISTERS) == CONTEXT_DEBUG_REGISTERS: for key in s._ctx_debug: setattr(s, key, ctx[key]) if (ContextFlags & CONTEXT_FLOATING_POINT) == CONTEXT_FLOATING_POINT: fsa = ctx['FloatSave'] s.FloatSave = FLOATING_SAVE_AREA.from_dict(fsa) if (ContextFlags & CONTEXT_SEGMENTS) == CONTEXT_SEGMENTS: for key in s._ctx_segs: setattr(s, key, ctx[key]) if (ContextFlags & CONTEXT_INTEGER) == CONTEXT_INTEGER: for key in s._ctx_int: setattr(s, key, ctx[key]) if (ContextFlags & CONTEXT_CONTROL) == CONTEXT_CONTROL: for key in s._ctx_ctrl: setattr(s, key, ctx[key]) if (ContextFlags & CONTEXT_EXTENDED_REGISTERS) == CONTEXT_EXTENDED_REGISTERS: er = ctx['ExtendedRegisters'] for index in compat.xrange(0, MAXIMUM_SUPPORTED_EXTENSION): s.ExtendedRegisters[index] = er[index] return s def to_dict(self): 'Convert a structure into a Python native type.' ctx = Context() ContextFlags = self.ContextFlags ctx['ContextFlags'] = ContextFlags if (ContextFlags & CONTEXT_DEBUG_REGISTERS) == CONTEXT_DEBUG_REGISTERS: for key in self._ctx_debug: ctx[key] = getattr(self, key) if (ContextFlags & CONTEXT_FLOATING_POINT) == CONTEXT_FLOATING_POINT: ctx['FloatSave'] = self.FloatSave.to_dict() if (ContextFlags & CONTEXT_SEGMENTS) == CONTEXT_SEGMENTS: for key in self._ctx_segs: ctx[key] = getattr(self, key) if (ContextFlags & CONTEXT_INTEGER) == CONTEXT_INTEGER: for key in self._ctx_int: ctx[key] = getattr(self, key) if (ContextFlags & CONTEXT_CONTROL) == CONTEXT_CONTROL: for key in self._ctx_ctrl: ctx[key] = getattr(self, key) if (ContextFlags & CONTEXT_EXTENDED_REGISTERS) == CONTEXT_EXTENDED_REGISTERS: er = [ self.ExtendedRegisters[index] for index in compat.xrange(0, MAXIMUM_SUPPORTED_EXTENSION) ] er = tuple(er) ctx['ExtendedRegisters'] = er return ctx LPCONTEXT = PCONTEXT class Context(dict): """ Register context dictionary for the i386 architecture. """ arch = CONTEXT.arch def __get_pc(self): return self['Eip'] def __set_pc(self, value): self['Eip'] = value pc = property(__get_pc, __set_pc) def __get_sp(self): return self['Esp'] def __set_sp(self, value): self['Esp'] = value sp = property(__get_sp, __set_sp) def __get_fp(self): return self['Ebp'] def __set_fp(self, value): self['Ebp'] = value fp = property(__get_fp, __set_fp) def GetThreadContext(hThread, ContextFlags = None, raw = False): _GetThreadContext = windll.kernel32.GetThreadContext _GetThreadContext.argtypes = [HANDLE, LPCONTEXT] _GetThreadContext.restype = bool _GetThreadContext.errcheck = RaiseIfZero if ContextFlags is None: ContextFlags = CONTEXT_ALL | CONTEXT_i386 Context = CONTEXT() Context.ContextFlags = ContextFlags _GetThreadContext(hThread, byref(Context)) if raw: return Context return Context.to_dict()
null
177,161
from winappdbg.win32.defines import * from winappdbg.win32.version import ARCH_I386 class CONTEXT(Structure): arch = ARCH_I386 _pack_ = 1 # Context Frame # # This frame has a several purposes: 1) it is used as an argument to # NtContinue, 2) is is used to constuct a call frame for APC delivery, # and 3) it is used in the user level thread creation routines. # # The layout of the record conforms to a standard call frame. _fields_ = [ # The flags values within this flag control the contents of # a CONTEXT record. # # If the context record is used as an input parameter, then # for each portion of the context record controlled by a flag # whose value is set, it is assumed that that portion of the # context record contains valid context. If the context record # is being used to modify a threads context, then only that # portion of the threads context will be modified. # # If the context record is used as an IN OUT parameter to capture # the context of a thread, then only those portions of the thread's # context corresponding to set flags will be returned. # # The context record is never used as an OUT only parameter. ('ContextFlags', DWORD), # This section is specified/returned if CONTEXT_DEBUG_REGISTERS is # set in ContextFlags. Note that CONTEXT_DEBUG_REGISTERS is NOT # included in CONTEXT_FULL. ('Dr0', DWORD), ('Dr1', DWORD), ('Dr2', DWORD), ('Dr3', DWORD), ('Dr6', DWORD), ('Dr7', DWORD), # This section is specified/returned if the # ContextFlags word contains the flag CONTEXT_FLOATING_POINT. ('FloatSave', FLOATING_SAVE_AREA), # This section is specified/returned if the # ContextFlags word contains the flag CONTEXT_SEGMENTS. ('SegGs', DWORD), ('SegFs', DWORD), ('SegEs', DWORD), ('SegDs', DWORD), # This section is specified/returned if the # ContextFlags word contains the flag CONTEXT_INTEGER. ('Edi', DWORD), ('Esi', DWORD), ('Ebx', DWORD), ('Edx', DWORD), ('Ecx', DWORD), ('Eax', DWORD), # This section is specified/returned if the # ContextFlags word contains the flag CONTEXT_CONTROL. ('Ebp', DWORD), ('Eip', DWORD), ('SegCs', DWORD), # MUST BE SANITIZED ('EFlags', DWORD), # MUST BE SANITIZED ('Esp', DWORD), ('SegSs', DWORD), # This section is specified/returned if the ContextFlags word # contains the flag CONTEXT_EXTENDED_REGISTERS. # The format and contexts are processor specific. ('ExtendedRegisters', BYTE * MAXIMUM_SUPPORTED_EXTENSION), ] _ctx_debug = ('Dr0', 'Dr1', 'Dr2', 'Dr3', 'Dr6', 'Dr7') _ctx_segs = ('SegGs', 'SegFs', 'SegEs', 'SegDs', ) _ctx_int = ('Edi', 'Esi', 'Ebx', 'Edx', 'Ecx', 'Eax') _ctx_ctrl = ('Ebp', 'Eip', 'SegCs', 'EFlags', 'Esp', 'SegSs') def from_dict(cls, ctx): 'Instance a new structure from a Python dictionary.' ctx = Context(ctx) s = cls() ContextFlags = ctx['ContextFlags'] setattr(s, 'ContextFlags', ContextFlags) if (ContextFlags & CONTEXT_DEBUG_REGISTERS) == CONTEXT_DEBUG_REGISTERS: for key in s._ctx_debug: setattr(s, key, ctx[key]) if (ContextFlags & CONTEXT_FLOATING_POINT) == CONTEXT_FLOATING_POINT: fsa = ctx['FloatSave'] s.FloatSave = FLOATING_SAVE_AREA.from_dict(fsa) if (ContextFlags & CONTEXT_SEGMENTS) == CONTEXT_SEGMENTS: for key in s._ctx_segs: setattr(s, key, ctx[key]) if (ContextFlags & CONTEXT_INTEGER) == CONTEXT_INTEGER: for key in s._ctx_int: setattr(s, key, ctx[key]) if (ContextFlags & CONTEXT_CONTROL) == CONTEXT_CONTROL: for key in s._ctx_ctrl: setattr(s, key, ctx[key]) if (ContextFlags & CONTEXT_EXTENDED_REGISTERS) == CONTEXT_EXTENDED_REGISTERS: er = ctx['ExtendedRegisters'] for index in compat.xrange(0, MAXIMUM_SUPPORTED_EXTENSION): s.ExtendedRegisters[index] = er[index] return s def to_dict(self): 'Convert a structure into a Python native type.' ctx = Context() ContextFlags = self.ContextFlags ctx['ContextFlags'] = ContextFlags if (ContextFlags & CONTEXT_DEBUG_REGISTERS) == CONTEXT_DEBUG_REGISTERS: for key in self._ctx_debug: ctx[key] = getattr(self, key) if (ContextFlags & CONTEXT_FLOATING_POINT) == CONTEXT_FLOATING_POINT: ctx['FloatSave'] = self.FloatSave.to_dict() if (ContextFlags & CONTEXT_SEGMENTS) == CONTEXT_SEGMENTS: for key in self._ctx_segs: ctx[key] = getattr(self, key) if (ContextFlags & CONTEXT_INTEGER) == CONTEXT_INTEGER: for key in self._ctx_int: ctx[key] = getattr(self, key) if (ContextFlags & CONTEXT_CONTROL) == CONTEXT_CONTROL: for key in self._ctx_ctrl: ctx[key] = getattr(self, key) if (ContextFlags & CONTEXT_EXTENDED_REGISTERS) == CONTEXT_EXTENDED_REGISTERS: er = [ self.ExtendedRegisters[index] for index in compat.xrange(0, MAXIMUM_SUPPORTED_EXTENSION) ] er = tuple(er) ctx['ExtendedRegisters'] = er return ctx LPCONTEXT = PCONTEXT def SetThreadContext(hThread, lpContext): _SetThreadContext = windll.kernel32.SetThreadContext _SetThreadContext.argtypes = [HANDLE, LPCONTEXT] _SetThreadContext.restype = bool _SetThreadContext.errcheck = RaiseIfZero if isinstance(lpContext, dict): lpContext = CONTEXT.from_dict(lpContext) _SetThreadContext(hThread, byref(lpContext))
null
177,162
from winappdbg.win32.defines import * from winappdbg.win32.peb_teb import * SYSDBG_COMMAND = DWORD def RtlNtStatusToDosError(Status): _RtlNtStatusToDosError = windll.ntdll.RtlNtStatusToDosError _RtlNtStatusToDosError.argtypes = [NTSTATUS] _RtlNtStatusToDosError.restype = ULONG return _RtlNtStatusToDosError(Status) def NtSystemDebugControl(Command, InputBuffer = None, InputBufferLength = None, OutputBuffer = None, OutputBufferLength = None): _NtSystemDebugControl = windll.ntdll.NtSystemDebugControl _NtSystemDebugControl.argtypes = [SYSDBG_COMMAND, PVOID, ULONG, PVOID, ULONG, PULONG] _NtSystemDebugControl.restype = NTSTATUS # Validate the input buffer if InputBuffer is None: if InputBufferLength is None: InputBufferLength = 0 else: raise ValueError( "Invalid call to NtSystemDebugControl: " "input buffer length given but no input buffer!") else: if InputBufferLength is None: InputBufferLength = sizeof(InputBuffer) InputBuffer = byref(InputBuffer) # Validate the output buffer if OutputBuffer is None: if OutputBufferLength is None: OutputBufferLength = 0 else: OutputBuffer = ctypes.create_string_buffer("", OutputBufferLength) elif OutputBufferLength is None: OutputBufferLength = sizeof(OutputBuffer) # Make the call (with an output buffer) if OutputBuffer is not None: ReturnLength = ULONG(0) ntstatus = _NtSystemDebugControl(Command, InputBuffer, InputBufferLength, byref(OutputBuffer), OutputBufferLength, byref(ReturnLength)) if ntstatus != 0: raise ctypes.WinError( RtlNtStatusToDosError(ntstatus) ) ReturnLength = ReturnLength.value if ReturnLength != OutputBufferLength: raise ctypes.WinError(ERROR_BAD_LENGTH) return OutputBuffer, ReturnLength # Make the call (without an output buffer) ntstatus = _NtSystemDebugControl(Command, InputBuffer, InputBufferLength, OutputBuffer, OutputBufferLength, None) if ntstatus != 0: raise ctypes.WinError( RtlNtStatusToDosError(ntstatus) )
null
177,163
from winappdbg.win32.defines import * from winappdbg.win32.peb_teb import * PROCESSINFOCLASS = DWORD ProcessBasicInformation = 0 ProcessDebugPort = 7 ProcessWx86Information = 19 ProcessHandleCount = 20 ProcessPriorityBoost = 22 ProcessWow64Information = 26 ProcessImageFileName = 27 class PROCESS_BASIC_INFORMATION(Structure): def RtlNtStatusToDosError(Status): def NtQueryInformationProcess(ProcessHandle, ProcessInformationClass, ProcessInformationLength = None): _NtQueryInformationProcess = windll.ntdll.NtQueryInformationProcess _NtQueryInformationProcess.argtypes = [HANDLE, PROCESSINFOCLASS, PVOID, ULONG, PULONG] _NtQueryInformationProcess.restype = NTSTATUS if ProcessInformationLength is not None: ProcessInformation = ctypes.create_string_buffer("", ProcessInformationLength) else: if ProcessInformationClass == ProcessBasicInformation: ProcessInformation = PROCESS_BASIC_INFORMATION() ProcessInformationLength = sizeof(PROCESS_BASIC_INFORMATION) elif ProcessInformationClass == ProcessImageFileName: unicode_buffer = ctypes.create_unicode_buffer(u"", 0x1000) ProcessInformation = UNICODE_STRING(0, 0x1000, addressof(unicode_buffer)) ProcessInformationLength = sizeof(UNICODE_STRING) elif ProcessInformationClass in (ProcessDebugPort, ProcessWow64Information, ProcessWx86Information, ProcessHandleCount, ProcessPriorityBoost): ProcessInformation = DWORD() ProcessInformationLength = sizeof(DWORD) else: raise Exception("Unknown ProcessInformationClass, use an explicit ProcessInformationLength value instead") ReturnLength = ULONG(0) ntstatus = _NtQueryInformationProcess(ProcessHandle, ProcessInformationClass, byref(ProcessInformation), ProcessInformationLength, byref(ReturnLength)) if ntstatus != 0: raise ctypes.WinError( RtlNtStatusToDosError(ntstatus) ) if ProcessInformationClass == ProcessBasicInformation: retval = ProcessInformation elif ProcessInformationClass in (ProcessDebugPort, ProcessWow64Information, ProcessWx86Information, ProcessHandleCount, ProcessPriorityBoost): retval = ProcessInformation.value elif ProcessInformationClass == ProcessImageFileName: vptr = ctypes.c_void_p(ProcessInformation.Buffer) cptr = ctypes.cast( vptr, ctypes.c_wchar * ProcessInformation.Length ) retval = cptr.contents.raw else: retval = ProcessInformation.raw[:ReturnLength.value] return retval
null
177,164
from winappdbg.win32.defines import * from winappdbg.win32.peb_teb import * THREADINFOCLASS = DWORD ThreadBasicInformation = 0 ThreadQuerySetWin32StartAddress = 9 ThreadPerformanceCount = 11 ThreadAmILastThread = 12 ThreadPriorityBoost = 14 ThreadHideFromDebugger = 17 class THREAD_BASIC_INFORMATION(Structure): _fields_ = [ ("ExitStatus", NTSTATUS), ("TebBaseAddress", PVOID), # PTEB ("ClientId", CLIENT_ID), ("AffinityMask", KAFFINITY), ("Priority", SDWORD), ("BasePriority", SDWORD), ] def RtlNtStatusToDosError(Status): _RtlNtStatusToDosError = windll.ntdll.RtlNtStatusToDosError _RtlNtStatusToDosError.argtypes = [NTSTATUS] _RtlNtStatusToDosError.restype = ULONG return _RtlNtStatusToDosError(Status) def NtQueryInformationThread(ThreadHandle, ThreadInformationClass, ThreadInformationLength = None): _NtQueryInformationThread = windll.ntdll.NtQueryInformationThread _NtQueryInformationThread.argtypes = [HANDLE, THREADINFOCLASS, PVOID, ULONG, PULONG] _NtQueryInformationThread.restype = NTSTATUS if ThreadInformationLength is not None: ThreadInformation = ctypes.create_string_buffer("", ThreadInformationLength) else: if ThreadInformationClass == ThreadBasicInformation: ThreadInformation = THREAD_BASIC_INFORMATION() elif ThreadInformationClass == ThreadHideFromDebugger: ThreadInformation = BOOLEAN() elif ThreadInformationClass == ThreadQuerySetWin32StartAddress: ThreadInformation = PVOID() elif ThreadInformationClass in (ThreadAmILastThread, ThreadPriorityBoost): ThreadInformation = DWORD() elif ThreadInformationClass == ThreadPerformanceCount: ThreadInformation = LONGLONG() # LARGE_INTEGER else: raise Exception("Unknown ThreadInformationClass, use an explicit ThreadInformationLength value instead") ThreadInformationLength = sizeof(ThreadInformation) ReturnLength = ULONG(0) ntstatus = _NtQueryInformationThread(ThreadHandle, ThreadInformationClass, byref(ThreadInformation), ThreadInformationLength, byref(ReturnLength)) if ntstatus != 0: raise ctypes.WinError( RtlNtStatusToDosError(ntstatus) ) if ThreadInformationClass == ThreadBasicInformation: retval = ThreadInformation elif ThreadInformationClass == ThreadHideFromDebugger: retval = bool(ThreadInformation.value) elif ThreadInformationClass in (ThreadQuerySetWin32StartAddress, ThreadAmILastThread, ThreadPriorityBoost, ThreadPerformanceCount): retval = ThreadInformation.value else: retval = ThreadInformation.raw[:ReturnLength.value] return retval
null
177,165
from winappdbg.win32.defines import * from winappdbg.win32.peb_teb import * class IO_STATUS_BLOCK(Structure): _fields_ = [ ("Status", NTSTATUS), ("Information", ULONG_PTR), ] def __get_Pointer(self): return PVOID(self.Status) def __set_Pointer(self, ptr): self.Status = ptr.value Pointer = property(__get_Pointer, __set_Pointer) PIO_STATUS_BLOCK = POINTER(IO_STATUS_BLOCK) def RtlNtStatusToDosError(Status): _RtlNtStatusToDosError = windll.ntdll.RtlNtStatusToDosError _RtlNtStatusToDosError.argtypes = [NTSTATUS] _RtlNtStatusToDosError.restype = ULONG return _RtlNtStatusToDosError(Status) def NtQueryInformationFile(FileHandle, FileInformationClass, FileInformation, Length): _NtQueryInformationFile = windll.ntdll.NtQueryInformationFile _NtQueryInformationFile.argtypes = [HANDLE, PIO_STATUS_BLOCK, PVOID, ULONG, DWORD] _NtQueryInformationFile.restype = NTSTATUS IoStatusBlock = IO_STATUS_BLOCK() ntstatus = _NtQueryInformationFile(FileHandle, byref(IoStatusBlock), byref(FileInformation), Length, FileInformationClass) if ntstatus != 0: raise ctypes.WinError( RtlNtStatusToDosError(ntstatus) ) return IoStatusBlock
null
177,166
from winappdbg.win32.defines import * from winappdbg.win32.peb_teb import * def CsrGetProcessId(): _CsrGetProcessId = windll.ntdll.CsrGetProcessId _CsrGetProcessId.argtypes = [] _CsrGetProcessId.restype = DWORD return _CsrGetProcessId()
null
177,167
from winappdbg.win32.defines import * from winappdbg.win32.kernel32 import LocalFree def CommandLineToArgvW(lpCmdLine): _CommandLineToArgvW = windll.shell32.CommandLineToArgvW _CommandLineToArgvW.argtypes = [LPVOID, POINTER(ctypes.c_int)] _CommandLineToArgvW.restype = LPVOID if not lpCmdLine: lpCmdLine = None argc = ctypes.c_int(0) vptr = ctypes.windll.shell32.CommandLineToArgvW(lpCmdLine, byref(argc)) if vptr == NULL: raise ctypes.WinError() argv = vptr try: argc = argc.value if argc <= 0: raise ctypes.WinError() argv = ctypes.cast(argv, ctypes.POINTER(LPWSTR * argc) ) argv = [ argv.contents[i] for i in compat.xrange(0, argc) ] finally: if vptr is not None: LocalFree(vptr) return argv def CommandLineToArgvA(lpCmdLine): t_ansi = GuessStringType.t_ansi t_unicode = GuessStringType.t_unicode if isinstance(lpCmdLine, t_ansi): cmdline = t_unicode(lpCmdLine) else: cmdline = lpCmdLine return [t_ansi(x) for x in CommandLineToArgvW(cmdline)]
null
177,168
from winappdbg.win32.defines import * from winappdbg.win32.kernel32 import LocalFree def ShellExecuteA(hwnd = None, lpOperation = None, lpFile = None, lpParameters = None, lpDirectory = None, nShowCmd = None): _ShellExecuteA = windll.shell32.ShellExecuteA _ShellExecuteA.argtypes = [HWND, LPSTR, LPSTR, LPSTR, LPSTR, INT] _ShellExecuteA.restype = HINSTANCE if not nShowCmd: nShowCmd = 0 success = _ShellExecuteA(hwnd, lpOperation, lpFile, lpParameters, lpDirectory, nShowCmd) success = ctypes.cast(success, c_int) success = success.value if not success > 32: # weird! isn't it? raise ctypes.WinError(success)
null
177,169
from winappdbg.win32.defines import * from winappdbg.win32.kernel32 import LocalFree def ShellExecuteW(hwnd = None, lpOperation = None, lpFile = None, lpParameters = None, lpDirectory = None, nShowCmd = None): _ShellExecuteW = windll.shell32.ShellExecuteW _ShellExecuteW.argtypes = [HWND, LPWSTR, LPWSTR, LPWSTR, LPWSTR, INT] _ShellExecuteW.restype = HINSTANCE if not nShowCmd: nShowCmd = 0 success = _ShellExecuteW(hwnd, lpOperation, lpFile, lpParameters, lpDirectory, nShowCmd) success = ctypes.cast(success, c_int) success = success.value if not success > 32: # weird! isn't it? raise ctypes.WinError(success)
null
177,170
from winappdbg.win32.defines import * from winappdbg.win32.kernel32 import LocalFree def ShellExecuteExA(lpExecInfo): _ShellExecuteExA = windll.shell32.ShellExecuteExA _ShellExecuteExA.argtypes = [LPSHELLEXECUTEINFOA] _ShellExecuteExA.restype = BOOL _ShellExecuteExA.errcheck = RaiseIfZero _ShellExecuteExA(byref(lpExecInfo)) def ShellExecuteExW(lpExecInfo): _ShellExecuteExW = windll.shell32.ShellExecuteExW _ShellExecuteExW.argtypes = [LPSHELLEXECUTEINFOW] _ShellExecuteExW.restype = BOOL _ShellExecuteExW.errcheck = RaiseIfZero _ShellExecuteExW(byref(lpExecInfo)) def ShellExecuteEx(lpExecInfo): if isinstance(lpExecInfo, SHELLEXECUTEINFOA): ShellExecuteExA(lpExecInfo) elif isinstance(lpExecInfo, SHELLEXECUTEINFOW): ShellExecuteExW(lpExecInfo) else: raise TypeError("Expected SHELLEXECUTEINFOA or SHELLEXECUTEINFOW, got %s instead" % type(lpExecInfo))
null
177,171
from winappdbg.win32.defines import * from winappdbg.win32.kernel32 import LocalFree def FindExecutableA(lpFile, lpDirectory = None): _FindExecutableA = windll.shell32.FindExecutableA _FindExecutableA.argtypes = [LPSTR, LPSTR, LPSTR] _FindExecutableA.restype = HINSTANCE lpResult = ctypes.create_string_buffer(MAX_PATH) success = _FindExecutableA(lpFile, lpDirectory, lpResult) success = ctypes.cast(success, ctypes.c_void_p) success = success.value if not success > 32: # weird! isn't it? raise ctypes.WinError(success) return lpResult.value
null