file_path
stringlengths 22
162
| content
stringlengths 19
501k
| size
int64 19
501k
| lang
stringclasses 1
value | avg_line_length
float64 6.33
100
| max_line_length
int64 18
935
| alphanum_fraction
float64 0.34
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_ipython/inputhookgtk3.py | # encoding: utf-8
"""
Enable Gtk3 to be used interacive by IPython.
Authors: Thomi Richards
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2012, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from gi.repository import Gtk, GLib # @UnresolvedImport
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
def _main_quit(*args, **kwargs):
Gtk.main_quit()
return False
def create_inputhook_gtk3(stdin_file):
def inputhook_gtk3():
GLib.io_add_watch(stdin_file, GLib.IO_IN, _main_quit)
Gtk.main()
return 0
return inputhook_gtk3
| 1,104 | Python | 29.694444 | 78 | 0.394022 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_ipython/inputhookgtk.py | # encoding: utf-8
"""
Enable pygtk to be used interacive by setting PyOS_InputHook.
Authors: Brian Granger
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import gtk, gobject # @UnresolvedImport
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
def _main_quit(*args, **kwargs):
gtk.main_quit()
return False
def create_inputhook_gtk(stdin_file):
def inputhook_gtk():
gobject.io_add_watch(stdin_file, gobject.IO_IN, _main_quit)
gtk.main()
return 0
return inputhook_gtk
| 1,107 | Python | 28.945945 | 78 | 0.392954 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_ipython/inputhooktk.py | # encoding: utf-8
# Unlike what IPython does, we need to have an explicit inputhook because tkinter handles
# input hook in the C Source code
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from pydev_ipython.inputhook import stdin_ready
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
TCL_DONT_WAIT = 1 << 1
def create_inputhook_tk(app):
def inputhook_tk():
while app.dooneevent(TCL_DONT_WAIT) == 1:
if stdin_ready():
break
return 0
return inputhook_tk
| 748 | Python | 30.208332 | 89 | 0.378342 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_ipython/inputhookqt4.py | # -*- coding: utf-8 -*-
"""
Qt4's inputhook support function
Author: Christian Boos
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import os
import signal
import threading
from pydev_ipython.qt_for_kernel import QtCore, QtGui
from pydev_ipython.inputhook import allow_CTRL_C, ignore_CTRL_C, stdin_ready
# To minimise future merging complexity, rather than edit the entire code base below
# we fake InteractiveShell here
class InteractiveShell:
_instance = None
@classmethod
def instance(cls):
if cls._instance is None:
cls._instance = cls()
return cls._instance
def set_hook(self, *args, **kwargs):
# We don't consider the pre_prompt_hook because we don't have
# KeyboardInterrupts to consider since we are running under PyDev
pass
#-----------------------------------------------------------------------------
# Module Globals
#-----------------------------------------------------------------------------
got_kbdint = False
sigint_timer = None
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
def create_inputhook_qt4(mgr, app=None):
"""Create an input hook for running the Qt4 application event loop.
Parameters
----------
mgr : an InputHookManager
app : Qt Application, optional.
Running application to use. If not given, we probe Qt for an
existing application object, and create a new one if none is found.
Returns
-------
A pair consisting of a Qt Application (either the one given or the
one found or created) and a inputhook.
Notes
-----
We use a custom input hook instead of PyQt4's default one, as it
interacts better with the readline packages (issue #481).
The inputhook function works in tandem with a 'pre_prompt_hook'
which automatically restores the hook as an inputhook in case the
latter has been temporarily disabled after having intercepted a
KeyboardInterrupt.
"""
if app is None:
app = QtCore.QCoreApplication.instance()
if app is None:
app = QtGui.QApplication([" "])
# Re-use previously created inputhook if any
ip = InteractiveShell.instance()
if hasattr(ip, '_inputhook_qt4'):
return app, ip._inputhook_qt4
# Otherwise create the inputhook_qt4/preprompthook_qt4 pair of
# hooks (they both share the got_kbdint flag)
def inputhook_qt4():
"""PyOS_InputHook python hook for Qt4.
Process pending Qt events and if there's no pending keyboard
input, spend a short slice of time (50ms) running the Qt event
loop.
As a Python ctypes callback can't raise an exception, we catch
the KeyboardInterrupt and temporarily deactivate the hook,
which will let a *second* CTRL+C be processed normally and go
back to a clean prompt line.
"""
try:
allow_CTRL_C()
app = QtCore.QCoreApplication.instance()
if not app: # shouldn't happen, but safer if it happens anyway...
return 0
app.processEvents(QtCore.QEventLoop.AllEvents, 300)
if not stdin_ready():
# Generally a program would run QCoreApplication::exec()
# from main() to enter and process the Qt event loop until
# quit() or exit() is called and the program terminates.
#
# For our input hook integration, we need to repeatedly
# enter and process the Qt event loop for only a short
# amount of time (say 50ms) to ensure that Python stays
# responsive to other user inputs.
#
# A naive approach would be to repeatedly call
# QCoreApplication::exec(), using a timer to quit after a
# short amount of time. Unfortunately, QCoreApplication
# emits an aboutToQuit signal before stopping, which has
# the undesirable effect of closing all modal windows.
#
# To work around this problem, we instead create a
# QEventLoop and call QEventLoop::exec(). Other than
# setting some state variables which do not seem to be
# used anywhere, the only thing QCoreApplication adds is
# the aboutToQuit signal which is precisely what we are
# trying to avoid.
timer = QtCore.QTimer()
event_loop = QtCore.QEventLoop()
timer.timeout.connect(event_loop.quit)
while not stdin_ready():
timer.start(50)
event_loop.exec_()
timer.stop()
except KeyboardInterrupt:
global got_kbdint, sigint_timer
ignore_CTRL_C()
got_kbdint = True
mgr.clear_inputhook()
# This generates a second SIGINT so the user doesn't have to
# press CTRL+C twice to get a clean prompt.
#
# Since we can't catch the resulting KeyboardInterrupt here
# (because this is a ctypes callback), we use a timer to
# generate the SIGINT after we leave this callback.
#
# Unfortunately this doesn't work on Windows (SIGINT kills
# Python and CTRL_C_EVENT doesn't work).
if(os.name == 'posix'):
pid = os.getpid()
if(not sigint_timer):
sigint_timer = threading.Timer(.01, os.kill,
args=[pid, signal.SIGINT] )
sigint_timer.start()
else:
print("\nKeyboardInterrupt - Ctrl-C again for new prompt")
except: # NO exceptions are allowed to escape from a ctypes callback
ignore_CTRL_C()
from traceback import print_exc
print_exc()
print("Got exception from inputhook_qt4, unregistering.")
mgr.clear_inputhook()
finally:
allow_CTRL_C()
return 0
def preprompthook_qt4(ishell):
"""'pre_prompt_hook' used to restore the Qt4 input hook
(in case the latter was temporarily deactivated after a
CTRL+C)
"""
global got_kbdint, sigint_timer
if(sigint_timer):
sigint_timer.cancel()
sigint_timer = None
if got_kbdint:
mgr.set_inputhook(inputhook_qt4)
got_kbdint = False
ip._inputhook_qt4 = inputhook_qt4
ip.set_hook('pre_prompt_hook', preprompthook_qt4)
return app, inputhook_qt4
| 7,242 | Python | 35.766497 | 84 | 0.549296 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_ipython/inputhook.py | # coding: utf-8
"""
Inputhook management for GUI event loop integration.
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import sys
import select
#-----------------------------------------------------------------------------
# Constants
#-----------------------------------------------------------------------------
# Constants for identifying the GUI toolkits.
GUI_WX = 'wx'
GUI_QT = 'qt'
GUI_QT4 = 'qt4'
GUI_QT5 = 'qt5'
GUI_GTK = 'gtk'
GUI_TK = 'tk'
GUI_OSX = 'osx'
GUI_GLUT = 'glut'
GUI_PYGLET = 'pyglet'
GUI_GTK3 = 'gtk3'
GUI_NONE = 'none' # i.e. disable
#-----------------------------------------------------------------------------
# Utilities
#-----------------------------------------------------------------------------
def ignore_CTRL_C():
"""Ignore CTRL+C (not implemented)."""
pass
def allow_CTRL_C():
"""Take CTRL+C into account (not implemented)."""
pass
#-----------------------------------------------------------------------------
# Main InputHookManager class
#-----------------------------------------------------------------------------
class InputHookManager(object):
"""Manage PyOS_InputHook for different GUI toolkits.
This class installs various hooks under ``PyOSInputHook`` to handle
GUI event loop integration.
"""
def __init__(self):
self._return_control_callback = None
self._apps = {}
self._reset()
self.pyplot_imported = False
def _reset(self):
self._callback_pyfunctype = None
self._callback = None
self._current_gui = None
def set_return_control_callback(self, return_control_callback):
self._return_control_callback = return_control_callback
def get_return_control_callback(self):
return self._return_control_callback
def return_control(self):
return self._return_control_callback()
def get_inputhook(self):
return self._callback
def set_inputhook(self, callback):
"""Set inputhook to callback."""
# We don't (in the context of PyDev console) actually set PyOS_InputHook, but rather
# while waiting for input on xmlrpc we run this code
self._callback = callback
def clear_inputhook(self, app=None):
"""Clear input hook.
Parameters
----------
app : optional, ignored
This parameter is allowed only so that clear_inputhook() can be
called with a similar interface as all the ``enable_*`` methods. But
the actual value of the parameter is ignored. This uniform interface
makes it easier to have user-level entry points in the main IPython
app like :meth:`enable_gui`."""
self._reset()
def clear_app_refs(self, gui=None):
"""Clear IPython's internal reference to an application instance.
Whenever we create an app for a user on qt4 or wx, we hold a
reference to the app. This is needed because in some cases bad things
can happen if a user doesn't hold a reference themselves. This
method is provided to clear the references we are holding.
Parameters
----------
gui : None or str
If None, clear all app references. If ('wx', 'qt4') clear
the app for that toolkit. References are not held for gtk or tk
as those toolkits don't have the notion of an app.
"""
if gui is None:
self._apps = {}
elif gui in self._apps:
del self._apps[gui]
def enable_wx(self, app=None):
"""Enable event loop integration with wxPython.
Parameters
----------
app : WX Application, optional.
Running application to use. If not given, we probe WX for an
existing application object, and create a new one if none is found.
Notes
-----
This methods sets the ``PyOS_InputHook`` for wxPython, which allows
the wxPython to integrate with terminal based applications like
IPython.
If ``app`` is not given we probe for an existing one, and return it if
found. If no existing app is found, we create an :class:`wx.App` as
follows::
import wx
app = wx.App(redirect=False, clearSigInt=False)
"""
import wx
from distutils.version import LooseVersion as V
wx_version = V(wx.__version__).version # @UndefinedVariable
if wx_version < [2, 8]:
raise ValueError("requires wxPython >= 2.8, but you have %s" % wx.__version__) # @UndefinedVariable
from pydev_ipython.inputhookwx import inputhook_wx
self.set_inputhook(inputhook_wx)
self._current_gui = GUI_WX
if app is None:
app = wx.GetApp() # @UndefinedVariable
if app is None:
app = wx.App(redirect=False, clearSigInt=False) # @UndefinedVariable
app._in_event_loop = True
self._apps[GUI_WX] = app
return app
def disable_wx(self):
"""Disable event loop integration with wxPython.
This merely sets PyOS_InputHook to NULL.
"""
if GUI_WX in self._apps:
self._apps[GUI_WX]._in_event_loop = False
self.clear_inputhook()
def enable_qt(self, app=None):
from pydev_ipython.qt_for_kernel import QT_API, QT_API_PYQT5
if QT_API == QT_API_PYQT5:
self.enable_qt5(app)
else:
self.enable_qt4(app)
def enable_qt4(self, app=None):
"""Enable event loop integration with PyQt4.
Parameters
----------
app : Qt Application, optional.
Running application to use. If not given, we probe Qt for an
existing application object, and create a new one if none is found.
Notes
-----
This methods sets the PyOS_InputHook for PyQt4, which allows
the PyQt4 to integrate with terminal based applications like
IPython.
If ``app`` is not given we probe for an existing one, and return it if
found. If no existing app is found, we create an :class:`QApplication`
as follows::
from PyQt4 import QtCore
app = QtGui.QApplication(sys.argv)
"""
from pydev_ipython.inputhookqt4 import create_inputhook_qt4
app, inputhook_qt4 = create_inputhook_qt4(self, app)
self.set_inputhook(inputhook_qt4)
self._current_gui = GUI_QT4
app._in_event_loop = True
self._apps[GUI_QT4] = app
return app
def disable_qt4(self):
"""Disable event loop integration with PyQt4.
This merely sets PyOS_InputHook to NULL.
"""
if GUI_QT4 in self._apps:
self._apps[GUI_QT4]._in_event_loop = False
self.clear_inputhook()
def enable_qt5(self, app=None):
from pydev_ipython.inputhookqt5 import create_inputhook_qt5
app, inputhook_qt5 = create_inputhook_qt5(self, app)
self.set_inputhook(inputhook_qt5)
self._current_gui = GUI_QT5
app._in_event_loop = True
self._apps[GUI_QT5] = app
return app
def disable_qt5(self):
if GUI_QT5 in self._apps:
self._apps[GUI_QT5]._in_event_loop = False
self.clear_inputhook()
def enable_gtk(self, app=None):
"""Enable event loop integration with PyGTK.
Parameters
----------
app : ignored
Ignored, it's only a placeholder to keep the call signature of all
gui activation methods consistent, which simplifies the logic of
supporting magics.
Notes
-----
This methods sets the PyOS_InputHook for PyGTK, which allows
the PyGTK to integrate with terminal based applications like
IPython.
"""
from pydev_ipython.inputhookgtk import create_inputhook_gtk
self.set_inputhook(create_inputhook_gtk(self._stdin_file))
self._current_gui = GUI_GTK
def disable_gtk(self):
"""Disable event loop integration with PyGTK.
This merely sets PyOS_InputHook to NULL.
"""
self.clear_inputhook()
def enable_tk(self, app=None):
"""Enable event loop integration with Tk.
Parameters
----------
app : toplevel :class:`Tkinter.Tk` widget, optional.
Running toplevel widget to use. If not given, we probe Tk for an
existing one, and create a new one if none is found.
Notes
-----
If you have already created a :class:`Tkinter.Tk` object, the only
thing done by this method is to register with the
:class:`InputHookManager`, since creating that object automatically
sets ``PyOS_InputHook``.
"""
self._current_gui = GUI_TK
if app is None:
try:
import Tkinter as _TK
except:
# Python 3
import tkinter as _TK # @UnresolvedImport
app = _TK.Tk()
app.withdraw()
self._apps[GUI_TK] = app
from pydev_ipython.inputhooktk import create_inputhook_tk
self.set_inputhook(create_inputhook_tk(app))
return app
def disable_tk(self):
"""Disable event loop integration with Tkinter.
This merely sets PyOS_InputHook to NULL.
"""
self.clear_inputhook()
def enable_glut(self, app=None):
""" Enable event loop integration with GLUT.
Parameters
----------
app : ignored
Ignored, it's only a placeholder to keep the call signature of all
gui activation methods consistent, which simplifies the logic of
supporting magics.
Notes
-----
This methods sets the PyOS_InputHook for GLUT, which allows the GLUT to
integrate with terminal based applications like IPython. Due to GLUT
limitations, it is currently not possible to start the event loop
without first creating a window. You should thus not create another
window but use instead the created one. See 'gui-glut.py' in the
docs/examples/lib directory.
The default screen mode is set to:
glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH
"""
import OpenGL.GLUT as glut # @UnresolvedImport
from pydev_ipython.inputhookglut import glut_display_mode, \
glut_close, glut_display, \
glut_idle, inputhook_glut
if GUI_GLUT not in self._apps:
argv = getattr(sys, 'argv', [])
glut.glutInit(argv)
glut.glutInitDisplayMode(glut_display_mode)
# This is specific to freeglut
if bool(glut.glutSetOption):
glut.glutSetOption(glut.GLUT_ACTION_ON_WINDOW_CLOSE,
glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS)
glut.glutCreateWindow(argv[0] if len(argv) > 0 else '')
glut.glutReshapeWindow(1, 1)
glut.glutHideWindow()
glut.glutWMCloseFunc(glut_close)
glut.glutDisplayFunc(glut_display)
glut.glutIdleFunc(glut_idle)
else:
glut.glutWMCloseFunc(glut_close)
glut.glutDisplayFunc(glut_display)
glut.glutIdleFunc(glut_idle)
self.set_inputhook(inputhook_glut)
self._current_gui = GUI_GLUT
self._apps[GUI_GLUT] = True
def disable_glut(self):
"""Disable event loop integration with glut.
This sets PyOS_InputHook to NULL and set the display function to a
dummy one and set the timer to a dummy timer that will be triggered
very far in the future.
"""
import OpenGL.GLUT as glut # @UnresolvedImport
from glut_support import glutMainLoopEvent # @UnresolvedImport
glut.glutHideWindow() # This is an event to be processed below
glutMainLoopEvent()
self.clear_inputhook()
def enable_pyglet(self, app=None):
"""Enable event loop integration with pyglet.
Parameters
----------
app : ignored
Ignored, it's only a placeholder to keep the call signature of all
gui activation methods consistent, which simplifies the logic of
supporting magics.
Notes
-----
This methods sets the ``PyOS_InputHook`` for pyglet, which allows
pyglet to integrate with terminal based applications like
IPython.
"""
from pydev_ipython.inputhookpyglet import inputhook_pyglet
self.set_inputhook(inputhook_pyglet)
self._current_gui = GUI_PYGLET
return app
def disable_pyglet(self):
"""Disable event loop integration with pyglet.
This merely sets PyOS_InputHook to NULL.
"""
self.clear_inputhook()
def enable_gtk3(self, app=None):
"""Enable event loop integration with Gtk3 (gir bindings).
Parameters
----------
app : ignored
Ignored, it's only a placeholder to keep the call signature of all
gui activation methods consistent, which simplifies the logic of
supporting magics.
Notes
-----
This methods sets the PyOS_InputHook for Gtk3, which allows
the Gtk3 to integrate with terminal based applications like
IPython.
"""
from pydev_ipython.inputhookgtk3 import create_inputhook_gtk3
self.set_inputhook(create_inputhook_gtk3(self._stdin_file))
self._current_gui = GUI_GTK
def disable_gtk3(self):
"""Disable event loop integration with PyGTK.
This merely sets PyOS_InputHook to NULL.
"""
self.clear_inputhook()
def enable_mac(self, app=None):
""" Enable event loop integration with MacOSX.
We call function pyplot.pause, which updates and displays active
figure during pause. It's not MacOSX-specific, but it enables to
avoid inputhooks in native MacOSX backend.
Also we shouldn't import pyplot, until user does it. Cause it's
possible to choose backend before importing pyplot for the first
time only.
"""
def inputhook_mac(app=None):
if self.pyplot_imported:
pyplot = sys.modules['matplotlib.pyplot']
try:
pyplot.pause(0.01)
except:
pass
else:
if 'matplotlib.pyplot' in sys.modules:
self.pyplot_imported = True
self.set_inputhook(inputhook_mac)
self._current_gui = GUI_OSX
def disable_mac(self):
self.clear_inputhook()
def current_gui(self):
"""Return a string indicating the currently active GUI or None."""
return self._current_gui
inputhook_manager = InputHookManager()
enable_wx = inputhook_manager.enable_wx
disable_wx = inputhook_manager.disable_wx
enable_qt = inputhook_manager.enable_qt
enable_qt4 = inputhook_manager.enable_qt4
disable_qt4 = inputhook_manager.disable_qt4
enable_qt5 = inputhook_manager.enable_qt5
disable_qt5 = inputhook_manager.disable_qt5
enable_gtk = inputhook_manager.enable_gtk
disable_gtk = inputhook_manager.disable_gtk
enable_tk = inputhook_manager.enable_tk
disable_tk = inputhook_manager.disable_tk
enable_glut = inputhook_manager.enable_glut
disable_glut = inputhook_manager.disable_glut
enable_pyglet = inputhook_manager.enable_pyglet
disable_pyglet = inputhook_manager.disable_pyglet
enable_gtk3 = inputhook_manager.enable_gtk3
disable_gtk3 = inputhook_manager.disable_gtk3
enable_mac = inputhook_manager.enable_mac
disable_mac = inputhook_manager.disable_mac
clear_inputhook = inputhook_manager.clear_inputhook
set_inputhook = inputhook_manager.set_inputhook
current_gui = inputhook_manager.current_gui
clear_app_refs = inputhook_manager.clear_app_refs
# We maintain this as stdin_ready so that the individual inputhooks
# can diverge as little as possible from their IPython sources
stdin_ready = inputhook_manager.return_control
set_return_control_callback = inputhook_manager.set_return_control_callback
get_return_control_callback = inputhook_manager.get_return_control_callback
get_inputhook = inputhook_manager.get_inputhook
# Convenience function to switch amongst them
def enable_gui(gui=None, app=None):
"""Switch amongst GUI input hooks by name.
This is just a utility wrapper around the methods of the InputHookManager
object.
Parameters
----------
gui : optional, string or None
If None (or 'none'), clears input hook, otherwise it must be one
of the recognized GUI names (see ``GUI_*`` constants in module).
app : optional, existing application object.
For toolkits that have the concept of a global app, you can supply an
existing one. If not given, the toolkit will be probed for one, and if
none is found, a new one will be created. Note that GTK does not have
this concept, and passing an app if ``gui=="GTK"`` will raise an error.
Returns
-------
The output of the underlying gui switch routine, typically the actual
PyOS_InputHook wrapper object or the GUI toolkit app created, if there was
one.
"""
if get_return_control_callback() is None:
raise ValueError("A return_control_callback must be supplied as a reference before a gui can be enabled")
guis = {GUI_NONE: clear_inputhook,
GUI_OSX: enable_mac,
GUI_TK: enable_tk,
GUI_GTK: enable_gtk,
GUI_WX: enable_wx,
GUI_QT: enable_qt,
GUI_QT4: enable_qt4,
GUI_QT5: enable_qt5,
GUI_GLUT: enable_glut,
GUI_PYGLET: enable_pyglet,
GUI_GTK3: enable_gtk3,
}
try:
gui_hook = guis[gui]
except KeyError:
if gui is None or gui == '':
gui_hook = clear_inputhook
else:
e = "Invalid GUI request %r, valid ones are:%s" % (gui, list(guis.keys()))
raise ValueError(e)
return gui_hook(app)
__all__ = [
"GUI_WX",
"GUI_QT",
"GUI_QT4",
"GUI_QT5",
"GUI_GTK",
"GUI_TK",
"GUI_OSX",
"GUI_GLUT",
"GUI_PYGLET",
"GUI_GTK3",
"GUI_NONE",
"ignore_CTRL_C",
"allow_CTRL_C",
"InputHookManager",
"inputhook_manager",
"enable_wx",
"disable_wx",
"enable_qt",
"enable_qt4",
"disable_qt4",
"enable_qt5",
"disable_qt5",
"enable_gtk",
"disable_gtk",
"enable_tk",
"disable_tk",
"enable_glut",
"disable_glut",
"enable_pyglet",
"disable_pyglet",
"enable_gtk3",
"disable_gtk3",
"enable_mac",
"disable_mac",
"clear_inputhook",
"set_inputhook",
"current_gui",
"clear_app_refs",
"stdin_ready",
"set_return_control_callback",
"get_return_control_callback",
"get_inputhook",
"enable_gui"]
| 19,554 | Python | 31.976391 | 113 | 0.591388 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_ipython/inputhookpyglet.py | # encoding: utf-8
"""
Enable pyglet to be used interacive by setting PyOS_InputHook.
Authors
-------
* Nicolas P. Rougier
* Fernando Perez
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import os
import sys
from _pydev_bundle._pydev_saved_modules import time
from timeit import default_timer as clock
import pyglet # @UnresolvedImport
from pydev_ipython.inputhook import stdin_ready
# On linux only, window.flip() has a bug that causes an AttributeError on
# window close. For details, see:
# http://groups.google.com/group/pyglet-users/browse_thread/thread/47c1aab9aa4a3d23/c22f9e819826799e?#c22f9e819826799e
if sys.platform.startswith('linux'):
def flip(window):
try:
window.flip()
except AttributeError:
pass
else:
def flip(window):
window.flip()
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
def inputhook_pyglet():
"""Run the pyglet event loop by processing pending events only.
This keeps processing pending events until stdin is ready. After
processing all pending events, a call to time.sleep is inserted. This is
needed, otherwise, CPU usage is at 100%. This sleep time should be tuned
though for best performance.
"""
# We need to protect against a user pressing Control-C when IPython is
# idle and this is running. We trap KeyboardInterrupt and pass.
try:
t = clock()
while not stdin_ready():
pyglet.clock.tick()
for window in pyglet.app.windows:
window.switch_to()
window.dispatch_events()
window.dispatch_event('on_draw')
flip(window)
# We need to sleep at this point to keep the idle CPU load
# low. However, if sleep to long, GUI response is poor. As
# a compromise, we watch how often GUI events are being processed
# and switch between a short and long sleep time. Here are some
# stats useful in helping to tune this.
# time CPU load
# 0.001 13%
# 0.005 3%
# 0.01 1.5%
# 0.05 0.5%
used_time = clock() - t
if used_time > 10.0:
# print 'Sleep for 1 s' # dbg
time.sleep(1.0)
elif used_time > 0.1:
# Few GUI events coming in, so we can sleep longer
# print 'Sleep for 0.05 s' # dbg
time.sleep(0.05)
else:
# Many GUI events coming in, so sleep only very little
time.sleep(0.001)
except KeyboardInterrupt:
pass
return 0
| 3,255 | Python | 34.010752 | 118 | 0.519201 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_ipython/version.py | # encoding: utf-8
"""
Utilities for version comparison
It is a bit ridiculous that we need these.
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2013 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from distutils.version import LooseVersion
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
def check_version(v, check):
"""check version string v >= check
If dev/prerelease tags result in TypeError for string-number comparison,
it is assumed that the dependency is satisfied.
Users on dev branches are responsible for keeping their own packages up to date.
"""
try:
return LooseVersion(v) >= LooseVersion(check)
except TypeError:
return True
| 1,227 | Python | 32.189188 | 84 | 0.439283 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_ipython/inputhookglut.py | # coding: utf-8
"""
GLUT Inputhook support functions
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
# GLUT is quite an old library and it is difficult to ensure proper
# integration within IPython since original GLUT does not allow to handle
# events one by one. Instead, it requires for the mainloop to be entered
# and never returned (there is not even a function to exit he
# mainloop). Fortunately, there are alternatives such as freeglut
# (available for linux and windows) and the OSX implementation gives
# access to a glutCheckLoop() function that blocks itself until a new
# event is received. This means we have to setup the idle callback to
# ensure we got at least one event that will unblock the function.
#
# Furthermore, it is not possible to install these handlers without a window
# being first created. We choose to make this window invisible. This means that
# display mode options are set at this level and user won't be able to change
# them later without modifying the code. This should probably be made available
# via IPython options system.
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import os
import sys
from _pydev_bundle._pydev_saved_modules import time
import signal
import OpenGL.GLUT as glut # @UnresolvedImport
import OpenGL.platform as platform # @UnresolvedImport
from timeit import default_timer as clock
from pydev_ipython.inputhook import stdin_ready
#-----------------------------------------------------------------------------
# Constants
#-----------------------------------------------------------------------------
# Frame per second : 60
# Should probably be an IPython option
glut_fps = 60
# Display mode : double buffeed + rgba + depth
# Should probably be an IPython option
glut_display_mode = (glut.GLUT_DOUBLE |
glut.GLUT_RGBA |
glut.GLUT_DEPTH)
glutMainLoopEvent = None
if sys.platform == 'darwin':
try:
glutCheckLoop = platform.createBaseFunction(
'glutCheckLoop', dll=platform.GLUT, resultType=None,
argTypes=[],
doc='glutCheckLoop( ) -> None',
argNames=(),
)
except AttributeError:
raise RuntimeError(
'''Your glut implementation does not allow interactive sessions'''
'''Consider installing freeglut.''')
glutMainLoopEvent = glutCheckLoop
elif glut.HAVE_FREEGLUT:
glutMainLoopEvent = glut.glutMainLoopEvent
else:
raise RuntimeError(
'''Your glut implementation does not allow interactive sessions. '''
'''Consider installing freeglut.''')
#-----------------------------------------------------------------------------
# Callback functions
#-----------------------------------------------------------------------------
def glut_display():
# Dummy display function
pass
def glut_idle():
# Dummy idle function
pass
def glut_close():
# Close function only hides the current window
glut.glutHideWindow()
glutMainLoopEvent()
def glut_int_handler(signum, frame):
# Catch sigint and print the defautl message
signal.signal(signal.SIGINT, signal.default_int_handler)
print('\nKeyboardInterrupt')
# Need to reprint the prompt at this stage
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
def inputhook_glut():
"""Run the pyglet event loop by processing pending events only.
This keeps processing pending events until stdin is ready. After
processing all pending events, a call to time.sleep is inserted. This is
needed, otherwise, CPU usage is at 100%. This sleep time should be tuned
though for best performance.
"""
# We need to protect against a user pressing Control-C when IPython is
# idle and this is running. We trap KeyboardInterrupt and pass.
signal.signal(signal.SIGINT, glut_int_handler)
try:
t = clock()
# Make sure the default window is set after a window has been closed
if glut.glutGetWindow() == 0:
glut.glutSetWindow(1)
glutMainLoopEvent()
return 0
while not stdin_ready():
glutMainLoopEvent()
# We need to sleep at this point to keep the idle CPU load
# low. However, if sleep to long, GUI response is poor. As
# a compromise, we watch how often GUI events are being processed
# and switch between a short and long sleep time. Here are some
# stats useful in helping to tune this.
# time CPU load
# 0.001 13%
# 0.005 3%
# 0.01 1.5%
# 0.05 0.5%
used_time = clock() - t
if used_time > 10.0:
# print 'Sleep for 1 s' # dbg
time.sleep(1.0)
elif used_time > 0.1:
# Few GUI events coming in, so we can sleep longer
# print 'Sleep for 0.05 s' # dbg
time.sleep(0.05)
else:
# Many GUI events coming in, so sleep only very little
time.sleep(0.001)
except KeyboardInterrupt:
pass
return 0
| 5,675 | Python | 35.619355 | 79 | 0.56652 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_ipython/inputhookwx.py | # encoding: utf-8
"""
Enable wxPython to be used interacive by setting PyOS_InputHook.
Authors: Robin Dunn, Brian Granger, Ondrej Certik
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import sys
import signal
from _pydev_bundle._pydev_saved_modules import time
from timeit import default_timer as clock
import wx
from pydev_ipython.inputhook import stdin_ready
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
def inputhook_wx1():
"""Run the wx event loop by processing pending events only.
This approach seems to work, but its performance is not great as it
relies on having PyOS_InputHook called regularly.
"""
try:
app = wx.GetApp() # @UndefinedVariable
if app is not None:
assert wx.Thread_IsMain() # @UndefinedVariable
# Make a temporary event loop and process system events until
# there are no more waiting, then allow idle events (which
# will also deal with pending or posted wx events.)
evtloop = wx.EventLoop() # @UndefinedVariable
ea = wx.EventLoopActivator(evtloop) # @UndefinedVariable
while evtloop.Pending():
evtloop.Dispatch()
app.ProcessIdle()
del ea
except KeyboardInterrupt:
pass
return 0
class EventLoopTimer(wx.Timer): # @UndefinedVariable
def __init__(self, func):
self.func = func
wx.Timer.__init__(self) # @UndefinedVariable
def Notify(self):
self.func()
class EventLoopRunner(object):
def Run(self, time):
self.evtloop = wx.EventLoop() # @UndefinedVariable
self.timer = EventLoopTimer(self.check_stdin)
self.timer.Start(time)
self.evtloop.Run()
def check_stdin(self):
if stdin_ready():
self.timer.Stop()
self.evtloop.Exit()
def inputhook_wx2():
"""Run the wx event loop, polling for stdin.
This version runs the wx eventloop for an undetermined amount of time,
during which it periodically checks to see if anything is ready on
stdin. If anything is ready on stdin, the event loop exits.
The argument to elr.Run controls how often the event loop looks at stdin.
This determines the responsiveness at the keyboard. A setting of 1000
enables a user to type at most 1 char per second. I have found that a
setting of 10 gives good keyboard response. We can shorten it further,
but eventually performance would suffer from calling select/kbhit too
often.
"""
try:
app = wx.GetApp() # @UndefinedVariable
if app is not None:
assert wx.Thread_IsMain() # @UndefinedVariable
elr = EventLoopRunner()
# As this time is made shorter, keyboard response improves, but idle
# CPU load goes up. 10 ms seems like a good compromise.
elr.Run(time=10) # CHANGE time here to control polling interval
except KeyboardInterrupt:
pass
return 0
def inputhook_wx3():
"""Run the wx event loop by processing pending events only.
This is like inputhook_wx1, but it keeps processing pending events
until stdin is ready. After processing all pending events, a call to
time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%.
This sleep time should be tuned though for best performance.
"""
# We need to protect against a user pressing Control-C when IPython is
# idle and this is running. We trap KeyboardInterrupt and pass.
try:
app = wx.GetApp() # @UndefinedVariable
if app is not None:
if hasattr(wx, 'IsMainThread'):
assert wx.IsMainThread() # @UndefinedVariable
else:
assert wx.Thread_IsMain() # @UndefinedVariable
# The import of wx on Linux sets the handler for signal.SIGINT
# to 0. This is a bug in wx or gtk. We fix by just setting it
# back to the Python default.
if not callable(signal.getsignal(signal.SIGINT)):
signal.signal(signal.SIGINT, signal.default_int_handler)
evtloop = wx.EventLoop() # @UndefinedVariable
ea = wx.EventLoopActivator(evtloop) # @UndefinedVariable
t = clock()
while not stdin_ready():
while evtloop.Pending():
t = clock()
evtloop.Dispatch()
app.ProcessIdle()
# We need to sleep at this point to keep the idle CPU load
# low. However, if sleep to long, GUI response is poor. As
# a compromise, we watch how often GUI events are being processed
# and switch between a short and long sleep time. Here are some
# stats useful in helping to tune this.
# time CPU load
# 0.001 13%
# 0.005 3%
# 0.01 1.5%
# 0.05 0.5%
used_time = clock() - t
if used_time > 10.0:
# print 'Sleep for 1 s' # dbg
time.sleep(1.0)
elif used_time > 0.1:
# Few GUI events coming in, so we can sleep longer
# print 'Sleep for 0.05 s' # dbg
time.sleep(0.05)
else:
# Many GUI events coming in, so sleep only very little
time.sleep(0.001)
del ea
except KeyboardInterrupt:
pass
return 0
if sys.platform == 'darwin':
# On OSX, evtloop.Pending() always returns True, regardless of there being
# any events pending. As such we can't use implementations 1 or 3 of the
# inputhook as those depend on a pending/dispatch loop.
inputhook_wx = inputhook_wx2
else:
# This is our default implementation
inputhook_wx = inputhook_wx3
| 6,517 | Python | 37.341176 | 81 | 0.565444 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_ipython/qt_loaders.py | """
This module contains factory functions that attempt
to return Qt submodules from the various python Qt bindings.
It also protects against double-importing Qt with different
bindings, which is unstable and likely to crash
This is used primarily by qt and qt_for_kernel, and shouldn't
be accessed directly from the outside
"""
import sys
from functools import partial
from pydev_ipython.version import check_version
# Available APIs.
QT_API_PYQT = 'pyqt'
QT_API_PYQTv1 = 'pyqtv1'
QT_API_PYQT_DEFAULT = 'pyqtdefault' # don't set SIP explicitly
QT_API_PYSIDE = 'pyside'
QT_API_PYSIDE2 = 'pyside2'
QT_API_PYQT5 = 'pyqt5'
class ImportDenier(object):
"""Import Hook that will guard against bad Qt imports
once IPython commits to a specific binding
"""
def __init__(self):
self.__forbidden = set()
def forbid(self, module_name):
sys.modules.pop(module_name, None)
self.__forbidden.add(module_name)
def find_module(self, fullname, path=None):
if path:
return
if fullname in self.__forbidden:
return self
def load_module(self, fullname):
raise ImportError("""
Importing %s disabled by IPython, which has
already imported an Incompatible QT Binding: %s
""" % (fullname, loaded_api()))
ID = ImportDenier()
sys.meta_path.append(ID)
def commit_api(api):
"""Commit to a particular API, and trigger ImportErrors on subsequent
dangerous imports"""
if api == QT_API_PYSIDE:
ID.forbid('PyQt4')
ID.forbid('PyQt5')
else:
ID.forbid('PySide')
ID.forbid('PySide2')
def loaded_api():
"""Return which API is loaded, if any
If this returns anything besides None,
importing any other Qt binding is unsafe.
Returns
-------
None, 'pyside', 'pyside2', 'pyqt', or 'pyqtv1'
"""
if 'PyQt4.QtCore' in sys.modules:
if qtapi_version() == 2:
return QT_API_PYQT
else:
return QT_API_PYQTv1
elif 'PySide.QtCore' in sys.modules:
return QT_API_PYSIDE
elif 'PySide2.QtCore' in sys.modules:
return QT_API_PYSIDE2
elif 'PyQt5.QtCore' in sys.modules:
return QT_API_PYQT5
return None
def has_binding(api):
"""Safely check for PyQt4 or PySide, without importing
submodules
Parameters
----------
api : str [ 'pyqtv1' | 'pyqt' | 'pyside' | 'pyqtdefault']
Which module to check for
Returns
-------
True if the relevant module appears to be importable
"""
# we can't import an incomplete pyside and pyqt4
# this will cause a crash in sip (#1431)
# check for complete presence before importing
module_name = {QT_API_PYSIDE: 'PySide',
QT_API_PYSIDE2: 'PySide2',
QT_API_PYQT: 'PyQt4',
QT_API_PYQTv1: 'PyQt4',
QT_API_PYQT_DEFAULT: 'PyQt4',
QT_API_PYQT5: 'PyQt5',
}
module_name = module_name[api]
import imp
try:
# importing top level PyQt4/PySide module is ok...
mod = __import__(module_name)
# ...importing submodules is not
imp.find_module('QtCore', mod.__path__)
imp.find_module('QtGui', mod.__path__)
imp.find_module('QtSvg', mod.__path__)
# we can also safely check PySide version
if api == QT_API_PYSIDE:
return check_version(mod.__version__, '1.0.3')
else:
return True
except ImportError:
return False
def qtapi_version():
"""Return which QString API has been set, if any
Returns
-------
The QString API version (1 or 2), or None if not set
"""
try:
import sip
except ImportError:
return
try:
return sip.getapi('QString')
except ValueError:
return
def can_import(api):
"""Safely query whether an API is importable, without importing it"""
if not has_binding(api):
return False
current = loaded_api()
if api == QT_API_PYQT_DEFAULT:
return current in [QT_API_PYQT, QT_API_PYQTv1, QT_API_PYQT5, None]
else:
return current in [api, None]
def import_pyqt4(version=2):
"""
Import PyQt4
Parameters
----------
version : 1, 2, or None
Which QString/QVariant API to use. Set to None to use the system
default
ImportErrors raised within this function are non-recoverable
"""
# The new-style string API (version=2) automatically
# converts QStrings to Unicode Python strings. Also, automatically unpacks
# QVariants to their underlying objects.
import sip
if version is not None:
sip.setapi('QString', version)
sip.setapi('QVariant', version)
from PyQt4 import QtGui, QtCore, QtSvg
if not check_version(QtCore.PYQT_VERSION_STR, '4.7'):
raise ImportError("IPython requires PyQt4 >= 4.7, found %s" %
QtCore.PYQT_VERSION_STR)
# Alias PyQt-specific functions for PySide compatibility.
QtCore.Signal = QtCore.pyqtSignal
QtCore.Slot = QtCore.pyqtSlot
# query for the API version (in case version == None)
version = sip.getapi('QString')
api = QT_API_PYQTv1 if version == 1 else QT_API_PYQT
return QtCore, QtGui, QtSvg, api
def import_pyqt5():
"""
Import PyQt5
ImportErrors raised within this function are non-recoverable
"""
from PyQt5 import QtGui, QtCore, QtSvg
# Alias PyQt-specific functions for PySide compatibility.
QtCore.Signal = QtCore.pyqtSignal
QtCore.Slot = QtCore.pyqtSlot
return QtCore, QtGui, QtSvg, QT_API_PYQT5
def import_pyside():
"""
Import PySide
ImportErrors raised within this function are non-recoverable
"""
from PySide import QtGui, QtCore, QtSvg # @UnresolvedImport
return QtCore, QtGui, QtSvg, QT_API_PYSIDE
def import_pyside2():
"""
Import PySide2
ImportErrors raised within this function are non-recoverable
"""
from PySide2 import QtGui, QtCore, QtSvg # @UnresolvedImport
return QtCore, QtGui, QtSvg, QT_API_PYSIDE
def load_qt(api_options):
"""
Attempt to import Qt, given a preference list
of permissible bindings
It is safe to call this function multiple times.
Parameters
----------
api_options: List of strings
The order of APIs to try. Valid items are 'pyside',
'pyqt', and 'pyqtv1'
Returns
-------
A tuple of QtCore, QtGui, QtSvg, QT_API
The first three are the Qt modules. The last is the
string indicating which module was loaded.
Raises
------
ImportError, if it isn't possible to import any requested
bindings (either becaues they aren't installed, or because
an incompatible library has already been installed)
"""
loaders = {QT_API_PYSIDE: import_pyside,
QT_API_PYSIDE2: import_pyside2,
QT_API_PYQT: import_pyqt4,
QT_API_PYQTv1: partial(import_pyqt4, version=1),
QT_API_PYQT_DEFAULT: partial(import_pyqt4, version=None),
QT_API_PYQT5: import_pyqt5,
}
for api in api_options:
if api not in loaders:
raise RuntimeError(
"Invalid Qt API %r, valid values are: %r, %r, %r, %r, %r, %r" %
(api, QT_API_PYSIDE, QT_API_PYSIDE, QT_API_PYQT,
QT_API_PYQTv1, QT_API_PYQT_DEFAULT, QT_API_PYQT5))
if not can_import(api):
continue
# cannot safely recover from an ImportError during this
result = loaders[api]()
api = result[-1] # changed if api = QT_API_PYQT_DEFAULT
commit_api(api)
return result
else:
raise ImportError("""
Could not load requested Qt binding. Please ensure that
PyQt4 >= 4.7 or PySide >= 1.0.3 is available,
and only one is imported per session.
Currently-imported Qt library: %r
PyQt4 installed: %s
PyQt5 installed: %s
PySide >= 1.0.3 installed: %s
PySide2 installed: %s
Tried to load: %r
""" % (loaded_api(),
has_binding(QT_API_PYQT),
has_binding(QT_API_PYQT5),
has_binding(QT_API_PYSIDE),
has_binding(QT_API_PYSIDE2),
api_options))
| 8,413 | Python | 26.860927 | 79 | 0.609771 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_ipython/qt_for_kernel.py | """ Import Qt in a manner suitable for an IPython kernel.
This is the import used for the `gui=qt` or `matplotlib=qt` initialization.
Import Priority:
if Qt4 has been imported anywhere else:
use that
if matplotlib has been imported and doesn't support v2 (<= 1.0.1):
use PyQt4 @v1
Next, ask ETS' QT_API env variable
if QT_API not set:
ask matplotlib via rcParams['backend.qt4']
if it said PyQt:
use PyQt4 @v1
elif it said PySide:
use PySide
else: (matplotlib said nothing)
# this is the default path - nobody told us anything
try:
PyQt @v1
except:
fallback on PySide
else:
use PyQt @v2 or PySide, depending on QT_API
because ETS doesn't work with PyQt @v1.
"""
import os
import sys
from pydev_ipython.version import check_version
from pydev_ipython.qt_loaders import (load_qt, QT_API_PYSIDE, QT_API_PYSIDE2,
QT_API_PYQT, QT_API_PYQT_DEFAULT,
loaded_api, QT_API_PYQT5)
# Constraints placed on an imported matplotlib
def matplotlib_options(mpl):
if mpl is None:
return
# #PyDev-779: In pysrc/pydev_ipython/qt_for_kernel.py, matplotlib_options should be replaced with latest from ipython
# (i.e.: properly check backend to decide upon qt4/qt5).
backend = mpl.rcParams.get('backend', None)
if backend == 'Qt4Agg':
mpqt = mpl.rcParams.get('backend.qt4', None)
if mpqt is None:
return None
if mpqt.lower() == 'pyside':
return [QT_API_PYSIDE]
elif mpqt.lower() == 'pyqt4':
return [QT_API_PYQT_DEFAULT]
elif mpqt.lower() == 'pyqt4v2':
return [QT_API_PYQT]
raise ImportError("unhandled value for backend.qt4 from matplotlib: %r" %
mpqt)
elif backend == 'Qt5Agg':
mpqt = mpl.rcParams.get('backend.qt5', None)
if mpqt is None:
return None
if mpqt.lower() == 'pyqt5':
return [QT_API_PYQT5]
raise ImportError("unhandled value for backend.qt5 from matplotlib: %r" %
mpqt)
# Fallback without checking backend (previous code)
mpqt = mpl.rcParams.get('backend.qt4', None)
if mpqt is None:
mpqt = mpl.rcParams.get('backend.qt5', None)
if mpqt is None:
return None
if mpqt.lower() == 'pyside':
return [QT_API_PYSIDE]
elif mpqt.lower() == 'pyqt4':
return [QT_API_PYQT_DEFAULT]
elif mpqt.lower() == 'pyqt5':
return [QT_API_PYQT5]
raise ImportError("unhandled value for qt backend from matplotlib: %r" %
mpqt)
def get_options():
"""Return a list of acceptable QT APIs, in decreasing order of
preference
"""
# already imported Qt somewhere. Use that
loaded = loaded_api()
if loaded is not None:
return [loaded]
mpl = sys.modules.get('matplotlib', None)
if mpl is not None and not check_version(mpl.__version__, '1.0.2'):
# 1.0.1 only supports PyQt4 v1
return [QT_API_PYQT_DEFAULT]
if os.environ.get('QT_API', None) is None:
# no ETS variable. Ask mpl, then use either
return matplotlib_options(mpl) or [QT_API_PYQT_DEFAULT, QT_API_PYSIDE, QT_API_PYSIDE2, QT_API_PYQT5]
# ETS variable present. Will fallback to external.qt
return None
api_opts = get_options()
if api_opts is not None:
QtCore, QtGui, QtSvg, QT_API = load_qt(api_opts)
else: # use ETS variable
from pydev_ipython.qt import QtCore, QtGui, QtSvg, QT_API
| 3,619 | Python | 29.166666 | 121 | 0.609284 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_ipython/matplotlibtools.py |
import sys
from _pydev_bundle import pydev_log
backends = {'tk': 'TkAgg',
'gtk': 'GTKAgg',
'wx': 'WXAgg',
'qt': 'QtAgg', # Auto-choose qt4/5
'qt4': 'Qt4Agg',
'qt5': 'Qt5Agg',
'osx': 'MacOSX'}
# We also need a reverse backends2guis mapping that will properly choose which
# GUI support to activate based on the desired matplotlib backend. For the
# most part it's just a reverse of the above dict, but we also need to add a
# few others that map to the same GUI manually:
backend2gui = dict(zip(backends.values(), backends.keys()))
# In the reverse mapping, there are a few extra valid matplotlib backends that
# map to the same GUI support
backend2gui['GTK'] = backend2gui['GTKCairo'] = 'gtk'
backend2gui['WX'] = 'wx'
backend2gui['CocoaAgg'] = 'osx'
def do_enable_gui(guiname):
from _pydev_bundle.pydev_versioncheck import versionok_for_gui
if versionok_for_gui():
try:
from pydev_ipython.inputhook import enable_gui
enable_gui(guiname)
except:
sys.stderr.write("Failed to enable GUI event loop integration for '%s'\n" % guiname)
pydev_log.exception()
elif guiname not in ['none', '', None]:
# Only print a warning if the guiname was going to do something
sys.stderr.write("Debug console: Python version does not support GUI event loop integration for '%s'\n" % guiname)
# Return value does not matter, so return back what was sent
return guiname
def find_gui_and_backend():
"""Return the gui and mpl backend."""
matplotlib = sys.modules['matplotlib']
# WARNING: this assumes matplotlib 1.1 or newer!!
backend = matplotlib.rcParams['backend']
# In this case, we need to find what the appropriate gui selection call
# should be for IPython, so we can activate inputhook accordingly
gui = backend2gui.get(backend, None)
return gui, backend
def is_interactive_backend(backend):
""" Check if backend is interactive """
matplotlib = sys.modules['matplotlib']
from matplotlib.rcsetup import interactive_bk, non_interactive_bk # @UnresolvedImport
if backend in interactive_bk:
return True
elif backend in non_interactive_bk:
return False
else:
return matplotlib.is_interactive()
def patch_use(enable_gui_function):
""" Patch matplotlib function 'use' """
matplotlib = sys.modules['matplotlib']
def patched_use(*args, **kwargs):
matplotlib.real_use(*args, **kwargs)
gui, backend = find_gui_and_backend()
enable_gui_function(gui)
matplotlib.real_use = matplotlib.use
matplotlib.use = patched_use
def patch_is_interactive():
""" Patch matplotlib function 'use' """
matplotlib = sys.modules['matplotlib']
def patched_is_interactive():
return matplotlib.rcParams['interactive']
matplotlib.real_is_interactive = matplotlib.is_interactive
matplotlib.is_interactive = patched_is_interactive
def activate_matplotlib(enable_gui_function):
"""Set interactive to True for interactive backends.
enable_gui_function - Function which enables gui, should be run in the main thread.
"""
matplotlib = sys.modules['matplotlib']
gui, backend = find_gui_and_backend()
is_interactive = is_interactive_backend(backend)
if is_interactive:
enable_gui_function(gui)
if not matplotlib.is_interactive():
sys.stdout.write("Backend %s is interactive backend. Turning interactive mode on.\n" % backend)
matplotlib.interactive(True)
else:
if matplotlib.is_interactive():
sys.stdout.write("Backend %s is non-interactive backend. Turning interactive mode off.\n" % backend)
matplotlib.interactive(False)
patch_use(enable_gui_function)
patch_is_interactive()
def flag_calls(func):
"""Wrap a function to detect and flag when it gets called.
This is a decorator which takes a function and wraps it in a function with
a 'called' attribute. wrapper.called is initialized to False.
The wrapper.called attribute is set to False right before each call to the
wrapped function, so if the call fails it remains False. After the call
completes, wrapper.called is set to True and the output is returned.
Testing for truth in wrapper.called allows you to determine if a call to
func() was attempted and succeeded."""
# don't wrap twice
if hasattr(func, 'called'):
return func
def wrapper(*args, **kw):
wrapper.called = False
out = func(*args, **kw)
wrapper.called = True
return out
wrapper.called = False
wrapper.__doc__ = func.__doc__
return wrapper
def activate_pylab():
pylab = sys.modules['pylab']
pylab.show._needmain = False
# We need to detect at runtime whether show() is called by the user.
# For this, we wrap it into a decorator which adds a 'called' flag.
pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive)
def activate_pyplot():
pyplot = sys.modules['matplotlib.pyplot']
pyplot.show._needmain = False
# We need to detect at runtime whether show() is called by the user.
# For this, we wrap it into a decorator which adds a 'called' flag.
pyplot.draw_if_interactive = flag_calls(pyplot.draw_if_interactive)
| 5,378 | Python | 34.86 | 122 | 0.674972 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_ipython/qt.py | """ A Qt API selector that can be used to switch between PyQt and PySide.
This uses the ETS 4.0 selection pattern of:
PySide first, PyQt with API v2. second.
Do not use this if you need PyQt with the old QString/QVariant API.
"""
import os
from pydev_ipython.qt_loaders import (load_qt, QT_API_PYSIDE,
QT_API_PYQT, QT_API_PYQT5)
QT_API = os.environ.get('QT_API', None)
if QT_API not in [QT_API_PYSIDE, QT_API_PYQT, QT_API_PYQT5, None]:
raise RuntimeError("Invalid Qt API %r, valid values are: %r, %r" %
(QT_API, QT_API_PYSIDE, QT_API_PYQT, QT_API_PYQT5))
if QT_API is None:
api_opts = [QT_API_PYSIDE, QT_API_PYQT, QT_API_PYQT5]
else:
api_opts = [QT_API]
QtCore, QtGui, QtSvg, QT_API = load_qt(api_opts)
| 785 | Python | 31.749999 | 74 | 0.636943 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_plugins/__init__.py | import warnings
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=DeprecationWarning)
try:
__import__('pkg_resources').declare_namespace(__name__)
except ImportError:
import pkgutil
__path__ = pkgutil.extend_path(__path__, __name__)
| 294 | Python | 31.777774 | 66 | 0.656463 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_plugins/django_debug.py | import inspect
from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, DJANGO_SUSPEND, \
DebugInfoHolder
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode, just_raised, ignore_exception_trace
from pydevd_file_utils import canonical_normalized_path, absolute_path
from _pydevd_bundle.pydevd_api import PyDevdAPI
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
IS_DJANGO18 = False
IS_DJANGO19 = False
IS_DJANGO19_OR_HIGHER = False
try:
import django
version = django.VERSION
IS_DJANGO18 = version[0] == 1 and version[1] == 8
IS_DJANGO19 = version[0] == 1 and version[1] == 9
IS_DJANGO19_OR_HIGHER = ((version[0] == 1 and version[1] >= 9) or version[0] > 1)
except:
pass
class DjangoLineBreakpoint(LineBreakpointWithLazyValidation):
def __init__(self, canonical_normalized_filename, breakpoint_id, line, condition, func_name, expression, hit_condition=None, is_logpoint=False):
self.canonical_normalized_filename = canonical_normalized_filename
LineBreakpointWithLazyValidation.__init__(self, breakpoint_id, line, condition, func_name, expression, hit_condition=hit_condition, is_logpoint=is_logpoint)
def __str__(self):
return "DjangoLineBreakpoint: %s-%d" % (self.canonical_normalized_filename, self.line)
class _DjangoValidationInfo(ValidationInfo):
@overrides(ValidationInfo._collect_valid_lines_in_template_uncached)
def _collect_valid_lines_in_template_uncached(self, template):
lines = set()
for node in self._iternodes(template.nodelist):
if node.__class__.__name__ in _IGNORE_RENDER_OF_CLASSES:
continue
lineno = self._get_lineno(node)
if lineno is not None:
lines.add(lineno)
return lines
def _get_lineno(self, node):
if hasattr(node, 'token') and hasattr(node.token, 'lineno'):
return node.token.lineno
return None
def _iternodes(self, nodelist):
for node in nodelist:
yield node
try:
children = node.child_nodelists
except:
pass
else:
for attr in children:
nodelist = getattr(node, attr, None)
if nodelist:
# i.e.: yield from _iternodes(nodelist)
for node in self._iternodes(nodelist):
yield node
def add_line_breakpoint(plugin, pydb, type, canonical_normalized_filename, breakpoint_id, line, condition, expression, func_name, hit_condition=None, is_logpoint=False, add_breakpoint_result=None, on_changed_breakpoint_state=None):
if type == 'django-line':
django_line_breakpoint = DjangoLineBreakpoint(canonical_normalized_filename, breakpoint_id, line, condition, func_name, expression, hit_condition=hit_condition, is_logpoint=is_logpoint)
if not hasattr(pydb, 'django_breakpoints'):
_init_plugin_breaks(pydb)
if IS_DJANGO19_OR_HIGHER:
add_breakpoint_result.error_code = PyDevdAPI.ADD_BREAKPOINT_LAZY_VALIDATION
django_line_breakpoint.add_breakpoint_result = add_breakpoint_result
django_line_breakpoint.on_changed_breakpoint_state = on_changed_breakpoint_state
else:
add_breakpoint_result.error_code = PyDevdAPI.ADD_BREAKPOINT_NO_ERROR
return django_line_breakpoint, pydb.django_breakpoints
return None
def after_breakpoints_consolidated(plugin, py_db, canonical_normalized_filename, id_to_pybreakpoint, file_to_line_to_breakpoints):
if IS_DJANGO19_OR_HIGHER:
django_breakpoints_for_file = file_to_line_to_breakpoints.get(canonical_normalized_filename)
if not django_breakpoints_for_file:
return
if not hasattr(py_db, 'django_validation_info'):
_init_plugin_breaks(py_db)
# In general we validate the breakpoints only when the template is loaded, but if the template
# was already loaded, we can validate the breakpoints based on the last loaded value.
py_db.django_validation_info.verify_breakpoints_from_template_cached_lines(
py_db, canonical_normalized_filename, django_breakpoints_for_file)
def add_exception_breakpoint(plugin, pydb, type, exception):
if type == 'django':
if not hasattr(pydb, 'django_exception_break'):
_init_plugin_breaks(pydb)
pydb.django_exception_break[exception] = True
return True
return False
def _init_plugin_breaks(pydb):
pydb.django_exception_break = {}
pydb.django_breakpoints = {}
pydb.django_validation_info = _DjangoValidationInfo()
def remove_exception_breakpoint(plugin, pydb, type, exception):
if type == 'django':
try:
del pydb.django_exception_break[exception]
return True
except:
pass
return False
def remove_all_exception_breakpoints(plugin, pydb):
if hasattr(pydb, 'django_exception_break'):
pydb.django_exception_break = {}
return True
return False
def get_breakpoints(plugin, pydb, type):
if type == 'django-line':
return pydb.django_breakpoints
return None
def _inherits(cls, *names):
if cls.__name__ in names:
return True
inherits_node = False
for base in inspect.getmro(cls):
if base.__name__ in names:
inherits_node = True
break
return inherits_node
_IGNORE_RENDER_OF_CLASSES = ('TextNode', 'NodeList')
def _is_django_render_call(frame, debug=False):
try:
name = frame.f_code.co_name
if name != 'render':
return False
if 'self' not in frame.f_locals:
return False
cls = frame.f_locals['self'].__class__
inherits_node = _inherits(cls, 'Node')
if not inherits_node:
return False
clsname = cls.__name__
if IS_DJANGO19:
# in Django 1.9 we need to save the flag that there is included template
if clsname == 'IncludeNode':
if 'context' in frame.f_locals:
context = frame.f_locals['context']
context._has_included_template = True
return clsname not in _IGNORE_RENDER_OF_CLASSES
except:
pydev_log.exception()
return False
def _is_django_context_get_call(frame):
try:
if 'self' not in frame.f_locals:
return False
cls = frame.f_locals['self'].__class__
return _inherits(cls, 'BaseContext')
except:
pydev_log.exception()
return False
def _is_django_resolve_call(frame):
try:
name = frame.f_code.co_name
if name != '_resolve_lookup':
return False
if 'self' not in frame.f_locals:
return False
cls = frame.f_locals['self'].__class__
clsname = cls.__name__
return clsname == 'Variable'
except:
pydev_log.exception()
return False
def _is_django_suspended(thread):
return thread.additional_info.suspend_type == DJANGO_SUSPEND
def suspend_django(main_debugger, thread, frame, cmd=CMD_SET_BREAK):
if frame.f_lineno is None:
return None
main_debugger.set_suspend(thread, cmd)
thread.additional_info.suspend_type = DJANGO_SUSPEND
return frame
def _find_django_render_frame(frame):
while frame is not None and not _is_django_render_call(frame):
frame = frame.f_back
return frame
#=======================================================================================================================
# Django Frame
#=======================================================================================================================
def _read_file(filename):
# type: (str) -> str
f = open(filename, 'r', encoding='utf-8', errors='replace')
s = f.read()
f.close()
return s
def _offset_to_line_number(text, offset):
curLine = 1
curOffset = 0
while curOffset < offset:
if curOffset == len(text):
return -1
c = text[curOffset]
if c == '\n':
curLine += 1
elif c == '\r':
curLine += 1
if curOffset < len(text) and text[curOffset + 1] == '\n':
curOffset += 1
curOffset += 1
return curLine
def _get_source_django_18_or_lower(frame):
# This method is usable only for the Django <= 1.8
try:
node = frame.f_locals['self']
if hasattr(node, 'source'):
return node.source
else:
if IS_DJANGO18:
# The debug setting was changed since Django 1.8
pydev_log.error_once("WARNING: Template path is not available. Set the 'debug' option in the OPTIONS of a DjangoTemplates "
"backend.")
else:
# The debug setting for Django < 1.8
pydev_log.error_once("WARNING: Template path is not available. Please set TEMPLATE_DEBUG=True in your settings.py to make "
"django template breakpoints working")
return None
except:
pydev_log.exception()
return None
def _convert_to_str(s):
return s
def _get_template_original_file_name_from_frame(frame):
try:
if IS_DJANGO19:
# The Node source was removed since Django 1.9
if 'context' in frame.f_locals:
context = frame.f_locals['context']
if hasattr(context, '_has_included_template'):
# if there was included template we need to inspect the previous frames and find its name
back = frame.f_back
while back is not None and frame.f_code.co_name in ('render', '_render'):
locals = back.f_locals
if 'self' in locals:
self = locals['self']
if self.__class__.__name__ == 'Template' and hasattr(self, 'origin') and \
hasattr(self.origin, 'name'):
return _convert_to_str(self.origin.name)
back = back.f_back
else:
if hasattr(context, 'template') and hasattr(context.template, 'origin') and \
hasattr(context.template.origin, 'name'):
return _convert_to_str(context.template.origin.name)
return None
elif IS_DJANGO19_OR_HIGHER:
# For Django 1.10 and later there is much simpler way to get template name
if 'self' in frame.f_locals:
self = frame.f_locals['self']
if hasattr(self, 'origin') and hasattr(self.origin, 'name'):
return _convert_to_str(self.origin.name)
return None
source = _get_source_django_18_or_lower(frame)
if source is None:
pydev_log.debug("Source is None\n")
return None
fname = _convert_to_str(source[0].name)
if fname == '<unknown source>':
pydev_log.debug("Source name is %s\n" % fname)
return None
else:
return fname
except:
if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 2:
pydev_log.exception('Error getting django template filename.')
return None
def _get_template_line(frame):
if IS_DJANGO19_OR_HIGHER:
node = frame.f_locals['self']
if hasattr(node, 'token') and hasattr(node.token, 'lineno'):
return node.token.lineno
else:
return None
source = _get_source_django_18_or_lower(frame)
original_filename = _get_template_original_file_name_from_frame(frame)
if original_filename is not None:
try:
absolute_filename = absolute_path(original_filename)
return _offset_to_line_number(_read_file(absolute_filename), source[1][0])
except:
return None
return None
class DjangoTemplateFrame(object):
IS_PLUGIN_FRAME = True
def __init__(self, frame):
original_filename = _get_template_original_file_name_from_frame(frame)
self._back_context = frame.f_locals['context']
self.f_code = FCode('Django Template', original_filename)
self.f_lineno = _get_template_line(frame)
self.f_back = frame
self.f_globals = {}
self.f_locals = self._collect_context(self._back_context)
self.f_trace = None
def _collect_context(self, context):
res = {}
try:
for d in context.dicts:
for k, v in d.items():
res[k] = v
except AttributeError:
pass
return res
def _change_variable(self, name, value):
for d in self._back_context.dicts:
for k, v in d.items():
if k == name:
d[k] = value
class DjangoTemplateSyntaxErrorFrame(object):
IS_PLUGIN_FRAME = True
def __init__(self, frame, original_filename, lineno, f_locals):
self.f_code = FCode('Django TemplateSyntaxError', original_filename)
self.f_lineno = lineno
self.f_back = frame
self.f_globals = {}
self.f_locals = f_locals
self.f_trace = None
def change_variable(plugin, frame, attr, expression):
if isinstance(frame, DjangoTemplateFrame):
result = eval(expression, frame.f_globals, frame.f_locals)
frame._change_variable(attr, result)
return result
return False
def _is_django_variable_does_not_exist_exception_break_context(frame):
try:
name = frame.f_code.co_name
except:
name = None
return name in ('_resolve_lookup', 'find_template')
def _is_ignoring_failures(frame):
while frame is not None:
if frame.f_code.co_name == 'resolve':
ignore_failures = frame.f_locals.get('ignore_failures')
if ignore_failures:
return True
frame = frame.f_back
return False
#=======================================================================================================================
# Django Step Commands
#=======================================================================================================================
def can_skip(plugin, main_debugger, frame):
if main_debugger.django_breakpoints:
if _is_django_render_call(frame):
return False
if main_debugger.django_exception_break:
module_name = frame.f_globals.get('__name__', '')
if module_name == 'django.template.base':
# Exceptions raised at django.template.base must be checked.
return False
return True
def has_exception_breaks(plugin):
if len(plugin.main_debugger.django_exception_break) > 0:
return True
return False
def has_line_breaks(plugin):
for _canonical_normalized_filename, breakpoints in plugin.main_debugger.django_breakpoints.items():
if len(breakpoints) > 0:
return True
return False
def cmd_step_into(plugin, main_debugger, frame, event, args, stop_info, stop):
info = args[2]
thread = args[3]
plugin_stop = False
if _is_django_suspended(thread):
stop_info['django_stop'] = event == 'call' and _is_django_render_call(frame)
plugin_stop = stop_info['django_stop']
stop = stop and _is_django_resolve_call(frame.f_back) and not _is_django_context_get_call(frame)
if stop:
info.pydev_django_resolve_frame = True # we remember that we've go into python code from django rendering frame
return stop, plugin_stop
def cmd_step_over(plugin, main_debugger, frame, event, args, stop_info, stop):
info = args[2]
thread = args[3]
plugin_stop = False
if _is_django_suspended(thread):
stop_info['django_stop'] = event == 'call' and _is_django_render_call(frame)
plugin_stop = stop_info['django_stop']
stop = False
return stop, plugin_stop
else:
if event == 'return' and info.pydev_django_resolve_frame and _is_django_resolve_call(frame.f_back):
# we return to Django suspend mode and should not stop before django rendering frame
info.pydev_step_stop = frame.f_back
info.pydev_django_resolve_frame = False
thread.additional_info.suspend_type = DJANGO_SUSPEND
stop = info.pydev_step_stop is frame and event in ('line', 'return')
return stop, plugin_stop
def stop(plugin, main_debugger, frame, event, args, stop_info, arg, step_cmd):
main_debugger = args[0]
thread = args[3]
if 'django_stop' in stop_info and stop_info['django_stop']:
frame = suspend_django(main_debugger, thread, DjangoTemplateFrame(frame), step_cmd)
if frame:
main_debugger.do_wait_suspend(thread, frame, event, arg)
return True
return False
def get_breakpoint(plugin, py_db, pydb_frame, frame, event, args):
py_db = args[0]
_filename = args[1]
info = args[2]
breakpoint_type = 'django'
if event == 'call' and info.pydev_state != STATE_SUSPEND and py_db.django_breakpoints and _is_django_render_call(frame):
original_filename = _get_template_original_file_name_from_frame(frame)
pydev_log.debug("Django is rendering a template: %s", original_filename)
canonical_normalized_filename = canonical_normalized_path(original_filename)
django_breakpoints_for_file = py_db.django_breakpoints.get(canonical_normalized_filename)
if django_breakpoints_for_file:
# At this point, let's validate whether template lines are correct.
if IS_DJANGO19_OR_HIGHER:
django_validation_info = py_db.django_validation_info
context = frame.f_locals['context']
django_template = context.template
django_validation_info.verify_breakpoints(py_db, canonical_normalized_filename, django_breakpoints_for_file, django_template)
pydev_log.debug("Breakpoints for that file: %s", django_breakpoints_for_file)
template_line = _get_template_line(frame)
pydev_log.debug("Tracing template line: %s", template_line)
if template_line in django_breakpoints_for_file:
django_breakpoint = django_breakpoints_for_file[template_line]
new_frame = DjangoTemplateFrame(frame)
return True, django_breakpoint, new_frame, breakpoint_type
return False, None, None, breakpoint_type
def suspend(plugin, main_debugger, thread, frame, bp_type):
if bp_type == 'django':
return suspend_django(main_debugger, thread, DjangoTemplateFrame(frame))
return None
def _get_original_filename_from_origin_in_parent_frame_locals(frame, parent_frame_name):
filename = None
parent_frame = frame
while parent_frame.f_code.co_name != parent_frame_name:
parent_frame = parent_frame.f_back
origin = None
if parent_frame is not None:
origin = parent_frame.f_locals.get('origin')
if hasattr(origin, 'name') and origin.name is not None:
filename = _convert_to_str(origin.name)
return filename
def exception_break(plugin, main_debugger, pydb_frame, frame, args, arg):
main_debugger = args[0]
thread = args[3]
exception, value, trace = arg
if main_debugger.django_exception_break and exception is not None:
if exception.__name__ in ['VariableDoesNotExist', 'TemplateDoesNotExist', 'TemplateSyntaxError'] and \
just_raised(trace) and not ignore_exception_trace(trace):
if exception.__name__ == 'TemplateSyntaxError':
# In this case we don't actually have a regular render frame with the context
# (we didn't really get to that point).
token = getattr(value, 'token', None)
if token is None:
# Django 1.7 does not have token in exception. Try to get it from locals.
token = frame.f_locals.get('token')
lineno = getattr(token, 'lineno', None)
original_filename = None
if lineno is not None:
original_filename = _get_original_filename_from_origin_in_parent_frame_locals(frame, 'get_template')
if original_filename is None:
# Django 1.7 does not have origin in get_template. Try to get it from
# load_template.
original_filename = _get_original_filename_from_origin_in_parent_frame_locals(frame, 'load_template')
if original_filename is not None and lineno is not None:
syntax_error_frame = DjangoTemplateSyntaxErrorFrame(
frame, original_filename, lineno, {'token': token, 'exception': exception})
suspend_frame = suspend_django(
main_debugger, thread, syntax_error_frame, CMD_ADD_EXCEPTION_BREAK)
return True, suspend_frame
elif exception.__name__ == 'VariableDoesNotExist':
if _is_django_variable_does_not_exist_exception_break_context(frame):
if not getattr(exception, 'silent_variable_failure', False) and not _is_ignoring_failures(frame):
render_frame = _find_django_render_frame(frame)
if render_frame:
suspend_frame = suspend_django(
main_debugger, thread, DjangoTemplateFrame(render_frame), CMD_ADD_EXCEPTION_BREAK)
if suspend_frame:
add_exception_to_frame(suspend_frame, (exception, value, trace))
thread.additional_info.pydev_message = 'VariableDoesNotExist'
suspend_frame.f_back = frame
frame = suspend_frame
return True, frame
return None
| 22,430 | Python | 35.532573 | 231 | 0.595988 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_plugins/pydevd_line_validation.py | from _pydevd_bundle.pydevd_breakpoints import LineBreakpoint
from _pydevd_bundle.pydevd_api import PyDevdAPI
import bisect
from _pydev_bundle import pydev_log
class LineBreakpointWithLazyValidation(LineBreakpoint):
def __init__(self, *args, **kwargs):
LineBreakpoint.__init__(self, *args, **kwargs)
# This is the _AddBreakpointResult that'll be modified (and then re-sent on the
# on_changed_breakpoint_state).
self.add_breakpoint_result = None
# The signature for the callback should be:
# on_changed_breakpoint_state(breakpoint_id: int, add_breakpoint_result: _AddBreakpointResult)
self.on_changed_breakpoint_state = None
# When its state is checked (in which case it'd call on_changed_breakpoint_state if the
# state changed), we store a cache key in 'verified_cache_key' -- in case it changes
# we'd need to re-verify it (for instance, the template could have changed on disk).
self.verified_cache_key = None
class ValidationInfo(object):
def __init__(self):
self._canonical_normalized_filename_to_last_template_lines = {}
def _collect_valid_lines_in_template(self, template):
# We cache the lines in the template itself. Note that among requests the
# template may be a different instance (because the template contents could be
# changed on disk), but this may still be called multiple times during the
# same render session, so, caching is interesting.
lines_cache = getattr(template, '__pydevd_lines_cache__', None)
if lines_cache is not None:
lines, sorted_lines = lines_cache
return lines, sorted_lines
lines = self._collect_valid_lines_in_template_uncached(template)
lines = frozenset(lines)
sorted_lines = tuple(sorted(lines))
template.__pydevd_lines_cache__ = lines, sorted_lines
return lines, sorted_lines
def _collect_valid_lines_in_template_uncached(self, template):
raise NotImplementedError()
def verify_breakpoints(self, py_db, canonical_normalized_filename, template_breakpoints_for_file, template):
'''
This function should be called whenever a rendering is detected.
:param str canonical_normalized_filename:
:param dict[int:LineBreakpointWithLazyValidation] template_breakpoints_for_file:
'''
valid_lines_frozenset, sorted_lines = self._collect_valid_lines_in_template(template)
self._canonical_normalized_filename_to_last_template_lines[canonical_normalized_filename] = valid_lines_frozenset, sorted_lines
self._verify_breakpoints_with_lines_collected(py_db, canonical_normalized_filename, template_breakpoints_for_file, valid_lines_frozenset, sorted_lines)
def verify_breakpoints_from_template_cached_lines(self, py_db, canonical_normalized_filename, template_breakpoints_for_file):
'''
This is used when the lines are already available (if just the template is available,
`verify_breakpoints` should be used instead).
'''
cached = self._canonical_normalized_filename_to_last_template_lines.get(canonical_normalized_filename)
if cached is not None:
valid_lines_frozenset, sorted_lines = cached
self._verify_breakpoints_with_lines_collected(py_db, canonical_normalized_filename, template_breakpoints_for_file, valid_lines_frozenset, sorted_lines)
def _verify_breakpoints_with_lines_collected(self, py_db, canonical_normalized_filename, template_breakpoints_for_file, valid_lines_frozenset, sorted_lines):
for line, template_bp in list(template_breakpoints_for_file.items()): # Note: iterate in a copy (we may mutate it).
if template_bp.verified_cache_key != valid_lines_frozenset:
template_bp.verified_cache_key = valid_lines_frozenset
valid = line in valid_lines_frozenset
if not valid:
new_line = -1
if sorted_lines:
# Adjust to the first preceding valid line.
idx = bisect.bisect_left(sorted_lines, line)
if idx > 0:
new_line = sorted_lines[idx - 1]
if new_line >= 0 and new_line not in template_breakpoints_for_file:
# We just add it if found and if there's no existing breakpoint at that
# location.
if template_bp.add_breakpoint_result.error_code != PyDevdAPI.ADD_BREAKPOINT_NO_ERROR and template_bp.add_breakpoint_result.translated_line != new_line:
pydev_log.debug('Template breakpoint in %s in line: %s moved to line: %s', canonical_normalized_filename, line, new_line)
template_bp.add_breakpoint_result.error_code = PyDevdAPI.ADD_BREAKPOINT_NO_ERROR
template_bp.add_breakpoint_result.translated_line = new_line
# Add it to a new line.
template_breakpoints_for_file.pop(line, None)
template_breakpoints_for_file[new_line] = template_bp
template_bp.on_changed_breakpoint_state(template_bp.breakpoint_id, template_bp.add_breakpoint_result)
else:
if template_bp.add_breakpoint_result.error_code != PyDevdAPI.ADD_BREAKPOINT_INVALID_LINE:
pydev_log.debug('Template breakpoint in %s in line: %s invalid (valid lines: %s)', canonical_normalized_filename, line, valid_lines_frozenset)
template_bp.add_breakpoint_result.error_code = PyDevdAPI.ADD_BREAKPOINT_INVALID_LINE
template_bp.on_changed_breakpoint_state(template_bp.breakpoint_id, template_bp.add_breakpoint_result)
else:
if template_bp.add_breakpoint_result.error_code != PyDevdAPI.ADD_BREAKPOINT_NO_ERROR:
template_bp.add_breakpoint_result.error_code = PyDevdAPI.ADD_BREAKPOINT_NO_ERROR
template_bp.on_changed_breakpoint_state(template_bp.breakpoint_id, template_bp.add_breakpoint_result)
| 6,286 | Python | 57.212962 | 175 | 0.649539 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_plugins/jinja2_debug.py | from _pydevd_bundle.pydevd_constants import STATE_SUSPEND, JINJA2_SUSPEND
from _pydevd_bundle.pydevd_comm import CMD_SET_BREAK, CMD_ADD_EXCEPTION_BREAK
from pydevd_file_utils import canonical_normalized_path
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, FCode
from _pydev_bundle import pydev_log
from pydevd_plugins.pydevd_line_validation import LineBreakpointWithLazyValidation, ValidationInfo
from _pydev_bundle.pydev_override import overrides
from _pydevd_bundle.pydevd_api import PyDevdAPI
class Jinja2LineBreakpoint(LineBreakpointWithLazyValidation):
def __init__(self, canonical_normalized_filename, breakpoint_id, line, condition, func_name, expression, hit_condition=None, is_logpoint=False):
self.canonical_normalized_filename = canonical_normalized_filename
LineBreakpointWithLazyValidation.__init__(self, breakpoint_id, line, condition, func_name, expression, hit_condition=hit_condition, is_logpoint=is_logpoint)
def __str__(self):
return "Jinja2LineBreakpoint: %s-%d" % (self.canonical_normalized_filename, self.line)
class _Jinja2ValidationInfo(ValidationInfo):
@overrides(ValidationInfo._collect_valid_lines_in_template_uncached)
def _collect_valid_lines_in_template_uncached(self, template):
lineno_mapping = _get_frame_lineno_mapping(template)
if not lineno_mapping:
return set()
return set(x[0] for x in lineno_mapping)
def add_line_breakpoint(plugin, pydb, type, canonical_normalized_filename, breakpoint_id, line, condition, expression, func_name, hit_condition=None, is_logpoint=False, add_breakpoint_result=None, on_changed_breakpoint_state=None):
if type == 'jinja2-line':
jinja2_line_breakpoint = Jinja2LineBreakpoint(canonical_normalized_filename, breakpoint_id, line, condition, func_name, expression, hit_condition=hit_condition, is_logpoint=is_logpoint)
if not hasattr(pydb, 'jinja2_breakpoints'):
_init_plugin_breaks(pydb)
add_breakpoint_result.error_code = PyDevdAPI.ADD_BREAKPOINT_LAZY_VALIDATION
jinja2_line_breakpoint.add_breakpoint_result = add_breakpoint_result
jinja2_line_breakpoint.on_changed_breakpoint_state = on_changed_breakpoint_state
return jinja2_line_breakpoint, pydb.jinja2_breakpoints
return None
def after_breakpoints_consolidated(plugin, py_db, canonical_normalized_filename, id_to_pybreakpoint, file_to_line_to_breakpoints):
jinja2_breakpoints_for_file = file_to_line_to_breakpoints.get(canonical_normalized_filename)
if not jinja2_breakpoints_for_file:
return
if not hasattr(py_db, 'jinja2_validation_info'):
_init_plugin_breaks(py_db)
# In general we validate the breakpoints only when the template is loaded, but if the template
# was already loaded, we can validate the breakpoints based on the last loaded value.
py_db.jinja2_validation_info.verify_breakpoints_from_template_cached_lines(
py_db, canonical_normalized_filename, jinja2_breakpoints_for_file)
def add_exception_breakpoint(plugin, pydb, type, exception):
if type == 'jinja2':
if not hasattr(pydb, 'jinja2_exception_break'):
_init_plugin_breaks(pydb)
pydb.jinja2_exception_break[exception] = True
return True
return False
def _init_plugin_breaks(pydb):
pydb.jinja2_exception_break = {}
pydb.jinja2_breakpoints = {}
pydb.jinja2_validation_info = _Jinja2ValidationInfo()
def remove_all_exception_breakpoints(plugin, pydb):
if hasattr(pydb, 'jinja2_exception_break'):
pydb.jinja2_exception_break = {}
return True
return False
def remove_exception_breakpoint(plugin, pydb, type, exception):
if type == 'jinja2':
try:
del pydb.jinja2_exception_break[exception]
return True
except:
pass
return False
def get_breakpoints(plugin, pydb, type):
if type == 'jinja2-line':
return pydb.jinja2_breakpoints
return None
def _is_jinja2_render_call(frame):
try:
name = frame.f_code.co_name
if "__jinja_template__" in frame.f_globals and name in ("root", "loop", "macro") or name.startswith("block_"):
return True
return False
except:
pydev_log.exception()
return False
def _suspend_jinja2(pydb, thread, frame, cmd=CMD_SET_BREAK, message=None):
frame = Jinja2TemplateFrame(frame)
if frame.f_lineno is None:
return None
pydb.set_suspend(thread, cmd)
thread.additional_info.suspend_type = JINJA2_SUSPEND
if cmd == CMD_ADD_EXCEPTION_BREAK:
# send exception name as message
if message:
message = str(message)
thread.additional_info.pydev_message = message
return frame
def _is_jinja2_suspended(thread):
return thread.additional_info.suspend_type == JINJA2_SUSPEND
def _is_jinja2_context_call(frame):
return "_Context__obj" in frame.f_locals
def _is_jinja2_internal_function(frame):
return 'self' in frame.f_locals and frame.f_locals['self'].__class__.__name__ in \
('LoopContext', 'TemplateReference', 'Macro', 'BlockReference')
def _find_jinja2_render_frame(frame):
while frame is not None and not _is_jinja2_render_call(frame):
frame = frame.f_back
return frame
#=======================================================================================================================
# Jinja2 Frame
#=======================================================================================================================
class Jinja2TemplateFrame(object):
IS_PLUGIN_FRAME = True
def __init__(self, frame, original_filename=None, template_lineno=None):
if original_filename is None:
original_filename = _get_jinja2_template_original_filename(frame)
if template_lineno is None:
template_lineno = _get_jinja2_template_line(frame)
self.back_context = None
if 'context' in frame.f_locals:
# sometimes we don't have 'context', e.g. in macros
self.back_context = frame.f_locals['context']
self.f_code = FCode('template', original_filename)
self.f_lineno = template_lineno
self.f_back = frame
self.f_globals = {}
self.f_locals = self.collect_context(frame)
self.f_trace = None
def _get_real_var_name(self, orig_name):
# replace leading number for local variables
parts = orig_name.split('_')
if len(parts) > 1 and parts[0].isdigit():
return parts[1]
return orig_name
def collect_context(self, frame):
res = {}
for k, v in frame.f_locals.items():
if not k.startswith('l_'):
res[k] = v
elif v and not _is_missing(v):
res[self._get_real_var_name(k[2:])] = v
if self.back_context is not None:
for k, v in self.back_context.items():
res[k] = v
return res
def _change_variable(self, frame, name, value):
in_vars_or_parents = False
if 'context' in frame.f_locals:
if name in frame.f_locals['context'].parent:
self.back_context.parent[name] = value
in_vars_or_parents = True
if name in frame.f_locals['context'].vars:
self.back_context.vars[name] = value
in_vars_or_parents = True
l_name = 'l_' + name
if l_name in frame.f_locals:
if in_vars_or_parents:
frame.f_locals[l_name] = self.back_context.resolve(name)
else:
frame.f_locals[l_name] = value
class Jinja2TemplateSyntaxErrorFrame(object):
IS_PLUGIN_FRAME = True
def __init__(self, frame, exception_cls_name, filename, lineno, f_locals):
self.f_code = FCode('Jinja2 %s' % (exception_cls_name,), filename)
self.f_lineno = lineno
self.f_back = frame
self.f_globals = {}
self.f_locals = f_locals
self.f_trace = None
def change_variable(plugin, frame, attr, expression):
if isinstance(frame, Jinja2TemplateFrame):
result = eval(expression, frame.f_globals, frame.f_locals)
frame._change_variable(frame.f_back, attr, result)
return result
return False
def _is_missing(item):
if item.__class__.__name__ == 'MissingType':
return True
return False
def _find_render_function_frame(frame):
# in order to hide internal rendering functions
old_frame = frame
try:
while not ('self' in frame.f_locals and frame.f_locals['self'].__class__.__name__ == 'Template' and \
frame.f_code.co_name == 'render'):
frame = frame.f_back
if frame is None:
return old_frame
return frame
except:
return old_frame
def _get_jinja2_template_debug_info(frame):
frame_globals = frame.f_globals
jinja_template = frame_globals.get('__jinja_template__')
if jinja_template is None:
return None
return _get_frame_lineno_mapping(jinja_template)
def _get_frame_lineno_mapping(jinja_template):
'''
:rtype: list(tuple(int,int))
:return: list((original_line, line_in_frame))
'''
# _debug_info is a string with the mapping from frame line to actual line
# i.e.: "5=13&8=14"
_debug_info = jinja_template._debug_info
if not _debug_info:
# Sometimes template contains only plain text.
return None
# debug_info is a list with the mapping from frame line to actual line
# i.e.: [(5, 13), (8, 14)]
return jinja_template.debug_info
def _get_jinja2_template_line(frame):
debug_info = _get_jinja2_template_debug_info(frame)
if debug_info is None:
return None
lineno = frame.f_lineno
for pair in debug_info:
if pair[1] == lineno:
return pair[0]
return None
def _convert_to_str(s):
return s
def _get_jinja2_template_original_filename(frame):
if '__jinja_template__' in frame.f_globals:
return _convert_to_str(frame.f_globals['__jinja_template__'].filename)
return None
#=======================================================================================================================
# Jinja2 Step Commands
#=======================================================================================================================
def has_exception_breaks(plugin):
if len(plugin.main_debugger.jinja2_exception_break) > 0:
return True
return False
def has_line_breaks(plugin):
for _canonical_normalized_filename, breakpoints in plugin.main_debugger.jinja2_breakpoints.items():
if len(breakpoints) > 0:
return True
return False
def can_skip(plugin, pydb, frame):
if pydb.jinja2_breakpoints and _is_jinja2_render_call(frame):
filename = _get_jinja2_template_original_filename(frame)
if filename is not None:
canonical_normalized_filename = canonical_normalized_path(filename)
jinja2_breakpoints_for_file = pydb.jinja2_breakpoints.get(canonical_normalized_filename)
if jinja2_breakpoints_for_file:
return False
if pydb.jinja2_exception_break:
name = frame.f_code.co_name
# errors in compile time
if name in ('template', 'top-level template code', '<module>') or name.startswith('block '):
f_back = frame.f_back
module_name = ''
if f_back is not None:
module_name = f_back.f_globals.get('__name__', '')
if module_name.startswith('jinja2.'):
return False
return True
def cmd_step_into(plugin, pydb, frame, event, args, stop_info, stop):
info = args[2]
thread = args[3]
plugin_stop = False
stop_info['jinja2_stop'] = False
if _is_jinja2_suspended(thread):
stop_info['jinja2_stop'] = event in ('call', 'line') and _is_jinja2_render_call(frame)
plugin_stop = stop_info['jinja2_stop']
stop = False
if info.pydev_call_from_jinja2 is not None:
if _is_jinja2_internal_function(frame):
# if internal Jinja2 function was called, we sould continue debugging inside template
info.pydev_call_from_jinja2 = None
else:
# we go into python code from Jinja2 rendering frame
stop = True
if event == 'call' and _is_jinja2_context_call(frame.f_back):
# we called function from context, the next step will be in function
info.pydev_call_from_jinja2 = 1
if event == 'return' and _is_jinja2_context_call(frame.f_back):
# we return from python code to Jinja2 rendering frame
info.pydev_step_stop = info.pydev_call_from_jinja2
info.pydev_call_from_jinja2 = None
thread.additional_info.suspend_type = JINJA2_SUSPEND
stop = False
# print "info.pydev_call_from_jinja2", info.pydev_call_from_jinja2, "stop_info", stop_info, \
# "thread.additional_info.suspend_type", thread.additional_info.suspend_type
# print "event", event, "farme.locals", frame.f_locals
return stop, plugin_stop
def cmd_step_over(plugin, pydb, frame, event, args, stop_info, stop):
info = args[2]
thread = args[3]
plugin_stop = False
stop_info['jinja2_stop'] = False
if _is_jinja2_suspended(thread):
stop = False
if info.pydev_call_inside_jinja2 is None:
if _is_jinja2_render_call(frame):
if event == 'call':
info.pydev_call_inside_jinja2 = frame.f_back
if event in ('line', 'return'):
info.pydev_call_inside_jinja2 = frame
else:
if event == 'line':
if _is_jinja2_render_call(frame) and info.pydev_call_inside_jinja2 is frame:
stop_info['jinja2_stop'] = True
plugin_stop = stop_info['jinja2_stop']
if event == 'return':
if frame is info.pydev_call_inside_jinja2 and 'event' not in frame.f_back.f_locals:
info.pydev_call_inside_jinja2 = _find_jinja2_render_frame(frame.f_back)
return stop, plugin_stop
else:
if event == 'return' and _is_jinja2_context_call(frame.f_back):
# we return from python code to Jinja2 rendering frame
info.pydev_call_from_jinja2 = None
info.pydev_call_inside_jinja2 = _find_jinja2_render_frame(frame)
thread.additional_info.suspend_type = JINJA2_SUSPEND
stop = False
return stop, plugin_stop
# print "info.pydev_call_from_jinja2", info.pydev_call_from_jinja2, "stop", stop, "jinja_stop", jinja2_stop, \
# "thread.additional_info.suspend_type", thread.additional_info.suspend_type
# print "event", event, "info.pydev_call_inside_jinja2", info.pydev_call_inside_jinja2
# print "frame", frame, "frame.f_back", frame.f_back, "step_stop", info.pydev_step_stop
# print "is_context_call", _is_jinja2_context_call(frame)
# print "render", _is_jinja2_render_call(frame)
# print "-------------"
return stop, plugin_stop
def stop(plugin, pydb, frame, event, args, stop_info, arg, step_cmd):
pydb = args[0]
thread = args[3]
if 'jinja2_stop' in stop_info and stop_info['jinja2_stop']:
frame = _suspend_jinja2(pydb, thread, frame, step_cmd)
if frame:
pydb.do_wait_suspend(thread, frame, event, arg)
return True
return False
def get_breakpoint(plugin, py_db, pydb_frame, frame, event, args):
py_db = args[0]
_filename = args[1]
info = args[2]
break_type = 'jinja2'
if event == 'line' and info.pydev_state != STATE_SUSPEND and py_db.jinja2_breakpoints and _is_jinja2_render_call(frame):
jinja_template = frame.f_globals.get('__jinja_template__')
if jinja_template is None:
return False, None, None, break_type
original_filename = _get_jinja2_template_original_filename(frame)
if original_filename is not None:
pydev_log.debug("Jinja2 is rendering a template: %s", original_filename)
canonical_normalized_filename = canonical_normalized_path(original_filename)
jinja2_breakpoints_for_file = py_db.jinja2_breakpoints.get(canonical_normalized_filename)
if jinja2_breakpoints_for_file:
jinja2_validation_info = py_db.jinja2_validation_info
jinja2_validation_info.verify_breakpoints(py_db, canonical_normalized_filename, jinja2_breakpoints_for_file, jinja_template)
template_lineno = _get_jinja2_template_line(frame)
if template_lineno is not None:
jinja2_breakpoint = jinja2_breakpoints_for_file.get(template_lineno)
if jinja2_breakpoint is not None:
new_frame = Jinja2TemplateFrame(frame, original_filename, template_lineno)
return True, jinja2_breakpoint, new_frame, break_type
return False, None, None, break_type
def suspend(plugin, pydb, thread, frame, bp_type):
if bp_type == 'jinja2':
return _suspend_jinja2(pydb, thread, frame)
return None
def exception_break(plugin, pydb, pydb_frame, frame, args, arg):
pydb = args[0]
thread = args[3]
exception, value, trace = arg
if pydb.jinja2_exception_break and exception is not None:
exception_type = list(pydb.jinja2_exception_break.keys())[0]
if exception.__name__ in ('UndefinedError', 'TemplateNotFound', 'TemplatesNotFound'):
# errors in rendering
render_frame = _find_jinja2_render_frame(frame)
if render_frame:
suspend_frame = _suspend_jinja2(pydb, thread, render_frame, CMD_ADD_EXCEPTION_BREAK, message=exception_type)
if suspend_frame:
add_exception_to_frame(suspend_frame, (exception, value, trace))
suspend_frame.f_back = frame
frame = suspend_frame
return True, frame
elif exception.__name__ in ('TemplateSyntaxError', 'TemplateAssertionError'):
name = frame.f_code.co_name
# errors in compile time
if name in ('template', 'top-level template code', '<module>') or name.startswith('block '):
f_back = frame.f_back
if f_back is not None:
module_name = f_back.f_globals.get('__name__', '')
if module_name.startswith('jinja2.'):
# Jinja2 translates exception info and creates fake frame on his own
pydb_frame.set_suspend(thread, CMD_ADD_EXCEPTION_BREAK)
add_exception_to_frame(frame, (exception, value, trace))
thread.additional_info.suspend_type = JINJA2_SUSPEND
thread.additional_info.pydev_message = str(exception_type)
return True, frame
return None
| 19,141 | Python | 36.755424 | 231 | 0.618045 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_plugins/extensions/types/pydevd_plugins_django_form_str.py | from _pydevd_bundle.pydevd_extension_api import StrPresentationProvider
from .pydevd_helpers import find_mod_attr, find_class_name
class DjangoFormStr(object):
def can_provide(self, type_object, type_name):
form_class = find_mod_attr('django.forms', 'Form')
return form_class is not None and issubclass(type_object, form_class)
def get_str(self, val):
return '%s: %r' % (find_class_name(val), val)
import sys
if not sys.platform.startswith("java"):
StrPresentationProvider.register(DjangoFormStr)
| 538 | Python | 30.705881 | 77 | 0.717472 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_plugins/extensions/types/pydevd_plugin_pandas_types.py | import sys
from _pydevd_bundle.pydevd_constants import PANDAS_MAX_ROWS, PANDAS_MAX_COLS, PANDAS_MAX_COLWIDTH
from _pydevd_bundle.pydevd_extension_api import TypeResolveProvider, StrPresentationProvider
from _pydevd_bundle.pydevd_resolver import inspect, MethodWrapperType
from _pydevd_bundle.pydevd_utils import Timer
from .pydevd_helpers import find_mod_attr
from contextlib import contextmanager
def _get_dictionary(obj, replacements):
ret = dict()
cls = obj.__class__
for attr_name in dir(obj):
# This is interesting but it actually hides too much info from the dataframe.
# attr_type_in_cls = type(getattr(cls, attr_name, None))
# if attr_type_in_cls == property:
# ret[attr_name] = '<property (not computed)>'
# continue
timer = Timer()
try:
replacement = replacements.get(attr_name)
if replacement is not None:
ret[attr_name] = replacement
continue
attr_value = getattr(obj, attr_name, '<unable to get>')
if inspect.isroutine(attr_value) or isinstance(attr_value, MethodWrapperType):
continue
ret[attr_name] = attr_value
except Exception as e:
ret[attr_name] = '<error getting: %s>' % (e,)
finally:
timer.report_if_getting_attr_slow(cls, attr_name)
return ret
@contextmanager
def customize_pandas_options():
# The default repr depends on the settings of:
#
# pandas.set_option('display.max_columns', None)
# pandas.set_option('display.max_rows', None)
#
# which can make the repr **very** slow on some cases, so, we customize pandas to have
# smaller values if the current values are too big.
custom_options = []
from pandas import get_option
max_rows = get_option("display.max_rows")
max_cols = get_option("display.max_columns")
max_colwidth = get_option("display.max_colwidth")
if max_rows is None or max_rows > PANDAS_MAX_ROWS:
custom_options.append("display.max_rows")
custom_options.append(PANDAS_MAX_ROWS)
if max_cols is None or max_cols > PANDAS_MAX_COLS:
custom_options.append("display.max_columns")
custom_options.append(PANDAS_MAX_COLS)
if max_colwidth is None or max_colwidth > PANDAS_MAX_COLWIDTH:
custom_options.append("display.max_colwidth")
custom_options.append(PANDAS_MAX_COLWIDTH)
if custom_options:
from pandas import option_context
with option_context(*custom_options):
yield
else:
yield
class PandasDataFrameTypeResolveProvider(object):
def can_provide(self, type_object, type_name):
data_frame_class = find_mod_attr('pandas.core.frame', 'DataFrame')
return data_frame_class is not None and issubclass(type_object, data_frame_class)
def resolve(self, obj, attribute):
return getattr(obj, attribute)
def get_dictionary(self, obj):
replacements = {
# This actually calls: DataFrame.transpose(), which can be expensive, so,
# let's just add some string representation for it.
'T': '<transposed dataframe -- debugger:skipped eval>',
# This creates a whole new dict{index: Series) for each column. Doing a
# subsequent repr() from this dict can be very slow, so, don't return it.
'_series': '<dict[index:Series] -- debugger:skipped eval>',
'style': '<pandas.io.formats.style.Styler -- debugger: skipped eval>',
}
return _get_dictionary(obj, replacements)
def get_str(self, df):
with customize_pandas_options():
return repr(df)
class PandasSeriesTypeResolveProvider(object):
def can_provide(self, type_object, type_name):
series_class = find_mod_attr('pandas.core.series', 'Series')
return series_class is not None and issubclass(type_object, series_class)
def resolve(self, obj, attribute):
return getattr(obj, attribute)
def get_dictionary(self, obj):
replacements = {
# This actually calls: DataFrame.transpose(), which can be expensive, so,
# let's just add some string representation for it.
'T': '<transposed dataframe -- debugger:skipped eval>',
# This creates a whole new dict{index: Series) for each column. Doing a
# subsequent repr() from this dict can be very slow, so, don't return it.
'_series': '<dict[index:Series] -- debugger:skipped eval>',
'style': '<pandas.io.formats.style.Styler -- debugger: skipped eval>',
}
return _get_dictionary(obj, replacements)
def get_str(self, series):
with customize_pandas_options():
return repr(series)
class PandasStylerTypeResolveProvider(object):
def can_provide(self, type_object, type_name):
series_class = find_mod_attr('pandas.io.formats.style', 'Styler')
return series_class is not None and issubclass(type_object, series_class)
def resolve(self, obj, attribute):
return getattr(obj, attribute)
def get_dictionary(self, obj):
replacements = {
'data': '<Styler data -- debugger:skipped eval>',
'__dict__': '<dict -- debugger: skipped eval>',
}
return _get_dictionary(obj, replacements)
if not sys.platform.startswith("java"):
TypeResolveProvider.register(PandasDataFrameTypeResolveProvider)
StrPresentationProvider.register(PandasDataFrameTypeResolveProvider)
TypeResolveProvider.register(PandasSeriesTypeResolveProvider)
StrPresentationProvider.register(PandasSeriesTypeResolveProvider)
TypeResolveProvider.register(PandasStylerTypeResolveProvider)
| 5,791 | Python | 34.975155 | 97 | 0.654637 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_plugins/extensions/types/pydevd_plugin_numpy_types.py | from _pydevd_bundle.pydevd_extension_api import TypeResolveProvider
from _pydevd_bundle.pydevd_resolver import defaultResolver, MAX_ITEMS_TO_HANDLE, TOO_LARGE_ATTR, TOO_LARGE_MSG
from .pydevd_helpers import find_mod_attr
class NdArrayItemsContainer(object):
pass
class NDArrayTypeResolveProvider(object):
'''
This resolves a numpy ndarray returning some metadata about the NDArray
'''
def can_provide(self, type_object, type_name):
nd_array = find_mod_attr('numpy', 'ndarray')
return nd_array is not None and issubclass(type_object, nd_array)
def is_numeric(self, obj):
if not hasattr(obj, 'dtype'):
return False
return obj.dtype.kind in 'biufc'
def resolve(self, obj, attribute):
if attribute == '__internals__':
return defaultResolver.get_dictionary(obj)
if attribute == 'min':
if self.is_numeric(obj) and obj.size > 0:
return obj.min()
else:
return None
if attribute == 'max':
if self.is_numeric(obj) and obj.size > 0:
return obj.max()
else:
return None
if attribute == 'shape':
return obj.shape
if attribute == 'dtype':
return obj.dtype
if attribute == 'size':
return obj.size
if attribute.startswith('['):
container = NdArrayItemsContainer()
i = 0
format_str = '%0' + str(int(len(str(len(obj))))) + 'd'
for item in obj:
setattr(container, format_str % i, item)
i += 1
if i > MAX_ITEMS_TO_HANDLE:
setattr(container, TOO_LARGE_ATTR, TOO_LARGE_MSG)
break
return container
return None
def get_dictionary(self, obj):
ret = dict()
ret['__internals__'] = defaultResolver.get_dictionary(obj)
if obj.size > 1024 * 1024:
ret['min'] = 'ndarray too big, calculating min would slow down debugging'
ret['max'] = 'ndarray too big, calculating max would slow down debugging'
elif obj.size == 0:
ret['min'] = 'array is empty'
ret['max'] = 'array is empty'
else:
if self.is_numeric(obj):
ret['min'] = obj.min()
ret['max'] = obj.max()
else:
ret['min'] = 'not a numeric object'
ret['max'] = 'not a numeric object'
ret['shape'] = obj.shape
ret['dtype'] = obj.dtype
ret['size'] = obj.size
try:
ret['[0:%s] ' % (len(obj))] = list(obj[0:MAX_ITEMS_TO_HANDLE])
except:
# This may not work depending on the array shape.
pass
return ret
import sys
if not sys.platform.startswith("java"):
TypeResolveProvider.register(NDArrayTypeResolveProvider)
| 2,945 | Python | 32.862069 | 110 | 0.54635 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_plugins/extensions/types/pydevd_helpers.py | import sys
def find_cached_module(mod_name):
return sys.modules.get(mod_name, None)
def find_mod_attr(mod_name, attr):
mod = find_cached_module(mod_name)
if mod is None:
return None
return getattr(mod, attr, None)
def find_class_name(val):
class_name = str(val.__class__)
if class_name.find('.') != -1:
class_name = class_name.split('.')[-1]
elif class_name.find("'") != -1: #does not have '.' (could be something like <type 'int'>)
class_name = class_name[class_name.index("'") + 1:]
if class_name.endswith("'>"):
class_name = class_name[:-2]
return class_name
| 639 | Python | 22.703703 | 94 | 0.597809 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/attach_script.py |
def get_main_thread_instance(threading):
if hasattr(threading, 'main_thread'):
return threading.main_thread()
else:
# On Python 2 we don't really have an API to get the main thread,
# so, we just get it from the 'shutdown' bound method.
return threading._shutdown.im_self
def get_main_thread_id(unlikely_thread_id=None):
'''
:param unlikely_thread_id:
Pass to mark some thread id as not likely the main thread.
:return tuple(thread_id, critical_warning)
'''
import sys
import os
current_frames = sys._current_frames()
possible_thread_ids = []
for thread_ident, frame in current_frames.items():
while frame.f_back is not None:
frame = frame.f_back
basename = os.path.basename(frame.f_code.co_filename)
if basename.endswith(('.pyc', '.pyo')):
basename = basename[:-1]
if (frame.f_code.co_name, basename) in [
('_run_module_as_main', 'runpy.py'),
('_run_module_as_main', '<frozen runpy>'),
('run_module_as_main', 'runpy.py'),
('run_module', 'runpy.py'),
('run_path', 'runpy.py'),
]:
# This is the case for python -m <module name> (this is an ideal match, so,
# let's return it).
return thread_ident, ''
if frame.f_code.co_name == '<module>':
if frame.f_globals.get('__name__') == '__main__':
possible_thread_ids.insert(0, thread_ident) # Add with higher priority
continue
# Usually the main thread will be started in the <module>, whereas others would
# be started in another place (but when Python is embedded, this may not be
# correct, so, just add to the available possibilities as we'll have to choose
# one if there are multiple).
possible_thread_ids.append(thread_ident)
if len(possible_thread_ids) > 0:
if len(possible_thread_ids) == 1:
return possible_thread_ids[0], '' # Ideal: only one match
while unlikely_thread_id in possible_thread_ids:
possible_thread_ids.remove(unlikely_thread_id)
if len(possible_thread_ids) == 1:
return possible_thread_ids[0], '' # Ideal: only one match
elif len(possible_thread_ids) > 1:
# Bad: we can't really be certain of anything at this point.
return possible_thread_ids[0], \
'Multiple thread ids found (%s). Choosing main thread id randomly (%s).' % (
possible_thread_ids, possible_thread_ids[0])
# If we got here we couldn't discover the main thread id.
return None, 'Unable to discover main thread id.'
def fix_main_thread_id(on_warn=lambda msg:None, on_exception=lambda msg:None, on_critical=lambda msg:None):
# This means that we weren't able to import threading in the main thread (which most
# likely means that the main thread is paused or in some very long operation).
# In this case we'll import threading here and hotfix what may be wrong in the threading
# module (if we're on Windows where we create a thread to do the attach and on Linux
# we are not certain on which thread we're executing this code).
#
# The code below is a workaround for https://bugs.python.org/issue37416
import sys
import threading
try:
with threading._active_limbo_lock:
main_thread_instance = get_main_thread_instance(threading)
if sys.platform == 'win32':
# On windows this code would be called in a secondary thread, so,
# the current thread is unlikely to be the main thread.
if hasattr(threading, '_get_ident'):
unlikely_thread_id = threading._get_ident() # py2
else:
unlikely_thread_id = threading.get_ident() # py3
else:
unlikely_thread_id = None
main_thread_id, critical_warning = get_main_thread_id(unlikely_thread_id)
if main_thread_id is not None:
main_thread_id_attr = '_ident'
if not hasattr(main_thread_instance, main_thread_id_attr):
main_thread_id_attr = '_Thread__ident'
assert hasattr(main_thread_instance, main_thread_id_attr)
if main_thread_id != getattr(main_thread_instance, main_thread_id_attr):
# Note that we also have to reset the '_tstack_lock' for a regular lock.
# This is needed to avoid an error on shutdown because this lock is bound
# to the thread state and will be released when the secondary thread
# that initialized the lock is finished -- making an assert fail during
# process shutdown.
main_thread_instance._tstate_lock = threading._allocate_lock()
main_thread_instance._tstate_lock.acquire()
# Actually patch the thread ident as well as the threading._active dict
# (we should have the _active_limbo_lock to do that).
threading._active.pop(getattr(main_thread_instance, main_thread_id_attr), None)
setattr(main_thread_instance, main_thread_id_attr, main_thread_id)
threading._active[getattr(main_thread_instance, main_thread_id_attr)] = main_thread_instance
# Note: only import from pydevd after the patching is done (we want to do the minimum
# possible when doing that patching).
on_warn('The threading module was not imported by user code in the main thread. The debugger will attempt to work around https://bugs.python.org/issue37416.')
if critical_warning:
on_critical('Issue found when debugger was trying to work around https://bugs.python.org/issue37416:\n%s' % (critical_warning,))
except:
on_exception('Error patching main thread id.')
def attach(port, host, protocol=''):
try:
import sys
fix_main_thread = 'threading' not in sys.modules
if fix_main_thread:
def on_warn(msg):
from _pydev_bundle import pydev_log
pydev_log.warn(msg)
def on_exception(msg):
from _pydev_bundle import pydev_log
pydev_log.exception(msg)
def on_critical(msg):
from _pydev_bundle import pydev_log
pydev_log.critical(msg)
fix_main_thread_id(on_warn=on_warn, on_exception=on_exception, on_critical=on_critical)
else:
from _pydev_bundle import pydev_log # @Reimport
pydev_log.debug('The threading module is already imported by user code.')
if protocol:
from _pydevd_bundle import pydevd_defaults
pydevd_defaults.PydevdCustomization.DEFAULT_PROTOCOL = protocol
import pydevd
# I.e.: disconnect/reset if already connected.
pydevd.SetupHolder.setup = None
py_db = pydevd.get_global_debugger()
if py_db is not None:
py_db.dispose_and_kill_all_pydevd_threads(wait=False)
# pydevd.DebugInfoHolder.DEBUG_RECORD_SOCKET_READS = True
# pydevd.DebugInfoHolder.DEBUG_TRACE_BREAKPOINTS = 3
# pydevd.DebugInfoHolder.DEBUG_TRACE_LEVEL = 3
pydevd.settrace(
port=port,
host=host,
stdoutToServer=True,
stderrToServer=True,
overwrite_prev_trace=True,
suspend=False,
trace_only_current_thread=False,
patch_multiprocessing=False,
)
except:
import traceback
traceback.print_exc()
| 7,834 | Python | 40.898396 | 166 | 0.5988 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/_test_attach_to_process.py | import subprocess
import sys
print(sys.executable)
if __name__ == '__main__':
p = subprocess.Popen([sys.executable, '-u', '_always_live_program.py'])
import attach_pydevd
attach_pydevd.main(attach_pydevd.process_command_line(['--pid', str(p.pid), '--protocol', 'http']))
p.wait()
| 297 | Python | 28.799997 | 103 | 0.649832 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/_check.py | import add_code_to_python_process
print(add_code_to_python_process.run_python_code(3736, "print(20)", connect_debugger_tracing=False))
| 135 | Python | 44.333319 | 100 | 0.785185 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/add_code_to_python_process.py | r'''
Copyright: Brainwy Software Ltda.
License: EPL.
=============
Works for Windows by using an executable that'll inject a dll to a process and call a function.
Note: https://github.com/fabioz/winappdbg is used just to determine if the target process is 32 or 64 bits.
Works for Linux relying on gdb.
Limitations:
============
Linux:
------
1. It possible that ptrace is disabled: /etc/sysctl.d/10-ptrace.conf
Note that even enabling it in /etc/sysctl.d/10-ptrace.conf (i.e.: making the
ptrace_scope=0), it's possible that we need to run the application that'll use ptrace (or
gdb in this case) as root (so, we must sudo the python which'll run this module).
2. It currently doesn't work in debug builds (i.e.: python_d)
Other implementations:
- pyrasite.com:
GPL
Windows/linux (in Linux it also uses gdb to connect -- although specifics are different as we use a dll to execute
code with other threads stopped). It's Windows approach is more limited because it doesn't seem to deal properly with
Python 3 if threading is disabled.
- https://github.com/google/pyringe:
Apache v2.
Only linux/Python 2.
- http://pytools.codeplex.com:
Apache V2
Windows Only (but supports mixed mode debugging)
Our own code relies heavily on a part of it: http://pytools.codeplex.com/SourceControl/latest#Python/Product/PyDebugAttach/PyDebugAttach.cpp
to overcome some limitations of attaching and running code in the target python executable on Python 3.
See: attach.cpp
Linux: References if we wanted to use a pure-python debugger:
https://bitbucket.org/haypo/python-ptrace/
http://stackoverflow.com/questions/7841573/how-to-get-an-error-message-for-errno-value-in-python
Jugaad:
https://www.defcon.org/images/defcon-19/dc-19-presentations/Jakhar/DEFCON-19-Jakhar-Jugaad-Linux-Thread-Injection.pdf
https://github.com/aseemjakhar/jugaad
Something else (general and not Python related):
- http://www.codeproject.com/Articles/4610/Three-Ways-to-Inject-Your-Code-into-Another-Proces
Other references:
- https://github.com/haypo/faulthandler
- http://nedbatchelder.com/text/trace-function.html
- https://github.com/python-git/python/blob/master/Python/sysmodule.c (sys_settrace)
- https://github.com/python-git/python/blob/master/Python/ceval.c (PyEval_SetTrace)
- https://github.com/python-git/python/blob/master/Python/thread.c (PyThread_get_key_value)
To build the dlls needed on windows, visual studio express 13 was used (see compile_dll.bat)
See: attach_pydevd.py to attach the pydev debugger to a running python process.
'''
# Note: to work with nasm compiling asm to code and decompiling to see asm with shellcode:
# x:\nasm\nasm-2.07-win32\nasm-2.07\nasm.exe
# nasm.asm&x:\nasm\nasm-2.07-win32\nasm-2.07\ndisasm.exe -b arch nasm
import ctypes
import os
import struct
import subprocess
import sys
import time
from contextlib import contextmanager
import platform
import traceback
try:
TimeoutError = TimeoutError # @ReservedAssignment
except NameError:
class TimeoutError(RuntimeError): # @ReservedAssignment
pass
@contextmanager
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)
IS_WINDOWS = sys.platform == 'win32'
IS_LINUX = sys.platform in ('linux', 'linux2')
IS_MAC = sys.platform == 'darwin'
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 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))
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))
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))
args = [target_executable, str(pid), target_dll_run_on_dllmain]
subprocess.check_call(args)
if not event.wait_for_event_set(10):
print('Timeout error: the attach may not have completed.')
print('--- Finished dll injection ---\n')
return 0
@contextmanager
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)
@contextmanager
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)
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:
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
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)))
p = subprocess.Popen(
' '.join(cmd),
shell=True,
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
print('Running gdb in target process.')
out, err = p.communicate()
print('stdout: %s' % (out,))
print('stderr: %s' % (err,))
return out, err
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 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)))
p = subprocess.Popen(
' '.join(cmd),
shell=True,
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
print('Running lldb in target process.')
out, err = p.communicate()
print('stdout: %s' % (out,))
print('stderr: %s' % (err,))
return out, err
if IS_WINDOWS:
run_python_code = run_python_code_windows
elif IS_MAC:
run_python_code = run_python_code_mac
elif IS_LINUX:
run_python_code = run_python_code_linux
else:
def run_python_code(*args, **kwargs):
print('Unable to attach to process in platform: %s', sys.platform)
def test():
print('Running with: %s' % (sys.executable,))
code = '''
import os, time, sys
print(os.getpid())
#from threading import Thread
#Thread(target=str).start()
if __name__ == '__main__':
while True:
time.sleep(.5)
sys.stdout.write('.\\n')
sys.stdout.flush()
'''
p = subprocess.Popen([sys.executable, '-u', '-c', code])
try:
code = 'print("It worked!")\n'
# Real code will be something as:
# code = '''import sys;sys.path.append(r'X:\winappdbg-code\examples'); import imported;'''
run_python_code(p.pid, python_code=code)
print('\nRun a 2nd time...\n')
run_python_code(p.pid, python_code=code)
time.sleep(3)
finally:
p.kill()
def main(args):
# Otherwise, assume the first parameter is the pid and anything else is code to be executed
# in the target process.
pid = int(args[0])
del args[0]
python_code = ';'.join(args)
# Note: on Linux the python code may not have a single quote char: '
run_python_code(pid, python_code)
if __name__ == '__main__':
args = sys.argv[1:]
if not args:
print('Expected pid and Python code to execute in target process.')
else:
if '--test' == args[0]:
test()
else:
main(args)
| 22,296 | Python | 35.733114 | 144 | 0.628095 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/_test_attach_to_process_linux.py | '''
This module is just for testing concepts. It should be erased later on.
Experiments:
// gdb -p 4957
// call dlopen("/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/attach_linux.so", 2)
// call dlsym($1, "hello")
// call hello()
// call open("/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/attach_linux.so", 2)
// call mmap(0, 6672, 1 | 2 | 4, 1, 3 , 0)
// add-symbol-file
// cat /proc/pid/maps
// call dlopen("/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/attach_linux.so", 1|8)
// call dlsym($1, "hello")
// call hello()
'''
import subprocess
import sys
import os
import time
if __name__ == '__main__':
linux_dir = os.path.join(os.path.dirname(__file__), 'linux')
os.chdir(linux_dir)
so_location = os.path.join(linux_dir, 'attach_linux.so')
try:
os.remove(so_location)
except:
pass
subprocess.call('g++ -shared -o attach_linux.so -fPIC -nostartfiles attach_linux.c'.split())
print('Finished compiling')
assert os.path.exists('/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/attach_linux.so')
os.chdir(os.path.dirname(linux_dir))
# import attach_pydevd
# attach_pydevd.main(attach_pydevd.process_command_line(['--pid', str(p.pid)]))
p = subprocess.Popen([sys.executable, '-u', '_always_live_program.py'])
print('Size of file: %s' % (os.stat(so_location).st_size))
# (gdb) set architecture
# Requires an argument. Valid arguments are i386, i386:x86-64, i386:x64-32, i8086, i386:intel, i386:x86-64:intel, i386:x64-32:intel, i386:nacl, i386:x86-64:nacl, i386:x64-32:nacl, auto.
cmd = [
'gdb',
'--pid',
str(p.pid),
'--batch',
]
arch = 'i386:x86-64'
if arch:
cmd.extend(["--eval-command='set architecture %s'" % arch])
cmd.extend([
"--eval-command='call dlopen(\"/home/fabioz/Desktop/dev/PyDev.Debugger/pydevd_attach_to_process/linux/attach_linux.so\", 2)'",
"--eval-command='call (int)DoAttach(1, \"print(\\\"check11111check\\\")\", 0)'",
# "--eval-command='call (int)SetSysTraceFunc(1, 0)'", -- never call this way, always use "--command='...gdb_threads_settrace.py'",
# So that threads are all stopped!
])
print(' '.join(cmd))
time.sleep(.5)
env = os.environ.copy()
env.pop('PYTHONIOENCODING', None)
env.pop('PYTHONPATH', None)
p2 = subprocess.call(' '.join(cmd), env=env, shell=True)
time.sleep(1)
p.kill()
| 2,523 | Python | 32.653333 | 189 | 0.635355 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/attach_pydevd.py | 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'] = ''
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]
if not setup['pid']:
sys.stderr.write('Expected --pid to be passed.\n')
sys.exit(1)
return setup
def main(setup):
sys.path.append(os.path.dirname(__file__))
import add_code_to_python_process
show_debug_info_on_target_process = 0
pydevd_dirname = os.path.dirname(os.path.dirname(__file__))
if sys.platform == 'win32':
setup['pythonpath'] = pydevd_dirname.replace('\\', '/')
setup['pythonpath2'] = os.path.dirname(__file__).replace('\\', '/')
python_code = '''import sys;
sys.path.append("%(pythonpath)s");
sys.path.append("%(pythonpath2)s");
import attach_script;
attach_script.attach(port=%(port)s, host="%(host)s", protocol="%(protocol)s");
'''.replace('\r\n', '').replace('\r', '').replace('\n', '')
else:
setup['pythonpath'] = pydevd_dirname
setup['pythonpath2'] = os.path.dirname(__file__)
# We have to pass it a bit differently for gdb
python_code = '''import sys;
sys.path.append(\\\"%(pythonpath)s\\\");
sys.path.append(\\\"%(pythonpath2)s\\\");
import attach_script;
attach_script.attach(port=%(port)s, host=\\\"%(host)s\\\", protocol=\\\"%(protocol)s\\\");
'''.replace('\r\n', '').replace('\r', '').replace('\n', '')
python_code = python_code % setup
add_code_to_python_process.run_python_code(
setup['pid'], python_code, connect_debugger_tracing=True, show_debug_info=show_debug_info_on_target_process)
if __name__ == '__main__':
main(process_command_line(sys.argv[1:]))
| 2,255 | Python | 29.486486 | 116 | 0.55122 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/_always_live_program.py | import sys
import struct
print('Executable: %s' % sys.executable)
import os
def loop_in_thread():
while True:
import time
time.sleep(.5)
sys.stdout.write('#')
sys.stdout.flush()
import threading
threading.Thread(target=loop_in_thread).start()
def is_python_64bit():
return (struct.calcsize('P') == 8)
print('Is 64: %s' % is_python_64bit())
if __name__ == '__main__':
print('pid:%s' % (os.getpid()))
i = 0
while True:
i += 1
import time
time.sleep(.5)
sys.stdout.write('.')
sys.stdout.flush()
if i % 40 == 0:
sys.stdout.write('\n')
sys.stdout.flush()
| 679 | Python | 19.60606 | 47 | 0.540501 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/util.py | #!~/.wine/drive_c/Python25/python.exe
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Miscellaneous utility classes and functions.
@group Helpers:
PathOperations,
MemoryAddresses,
CustomAddressIterator,
DataAddressIterator,
ImageAddressIterator,
MappedAddressIterator,
ExecutableAddressIterator,
ReadableAddressIterator,
WriteableAddressIterator,
ExecutableAndWriteableAddressIterator,
DebugRegister,
Regenerator,
BannerHelpFormatter,
StaticClass,
classproperty
"""
__revision__ = "$Id$"
__all__ = [
# Filename and pathname manipulation
'PathOperations',
# Memory address operations
'MemoryAddresses',
'CustomAddressIterator',
'DataAddressIterator',
'ImageAddressIterator',
'MappedAddressIterator',
'ExecutableAddressIterator',
'ReadableAddressIterator',
'WriteableAddressIterator',
'ExecutableAndWriteableAddressIterator',
# Debug registers manipulation
'DebugRegister',
# Miscellaneous
'Regenerator',
]
import sys
import os
import ctypes
import optparse
from winappdbg import win32
from winappdbg import compat
#==============================================================================
class classproperty(property):
"""
Class property method.
Only works for getting properties, if you set them
the symbol gets overwritten in the class namespace.
Inspired on: U{http://stackoverflow.com/a/7864317/426293}
"""
def __init__(self, fget=None, fset=None, fdel=None, doc=""):
if fset is not None or fdel is not None:
raise NotImplementedError()
super(classproperty, self).__init__(fget=classmethod(fget), doc=doc)
def __get__(self, cls, owner):
return self.fget.__get__(None, owner)()
class BannerHelpFormatter(optparse.IndentedHelpFormatter):
"Just a small tweak to optparse to be able to print a banner."
def __init__(self, banner, *argv, **argd):
self.banner = banner
optparse.IndentedHelpFormatter.__init__(self, *argv, **argd)
def format_usage(self, usage):
msg = optparse.IndentedHelpFormatter.format_usage(self, usage)
return '%s\n%s' % (self.banner, msg)
# See Process.generate_memory_snapshot()
class Regenerator(object):
"""
Calls a generator and iterates it. When it's finished iterating, the
generator is called again. This allows you to iterate a generator more
than once (well, sort of).
"""
def __init__(self, g_function, *v_args, **d_args):
"""
@type g_function: function
@param g_function: Function that when called returns a generator.
@type v_args: tuple
@param v_args: Variable arguments to pass to the generator function.
@type d_args: dict
@param d_args: Variable arguments to pass to the generator function.
"""
self.__g_function = g_function
self.__v_args = v_args
self.__d_args = d_args
self.__g_object = None
def __iter__(self):
'x.__iter__() <==> iter(x)'
return self
def next(self):
'x.next() -> the next value, or raise StopIteration'
if self.__g_object is None:
self.__g_object = self.__g_function( *self.__v_args, **self.__d_args )
try:
return self.__g_object.next()
except StopIteration:
self.__g_object = None
raise
class StaticClass (object):
def __new__(cls, *argv, **argd):
"Don't try to instance this class, just use the static methods."
raise NotImplementedError(
"Cannot instance static class %s" % cls.__name__)
#==============================================================================
class PathOperations (StaticClass):
"""
Static methods for filename and pathname manipulation.
"""
@staticmethod
def path_is_relative(path):
"""
@see: L{path_is_absolute}
@type path: str
@param path: Absolute or relative path.
@rtype: bool
@return: C{True} if the path is relative, C{False} if it's absolute.
"""
return win32.PathIsRelative(path)
@staticmethod
def path_is_absolute(path):
"""
@see: L{path_is_relative}
@type path: str
@param path: Absolute or relative path.
@rtype: bool
@return: C{True} if the path is absolute, C{False} if it's relative.
"""
return not win32.PathIsRelative(path)
@staticmethod
def make_relative(path, current = None):
"""
@type path: str
@param path: Absolute path.
@type current: str
@param current: (Optional) Path to the current directory.
@rtype: str
@return: Relative path.
@raise WindowsError: It's impossible to make the path relative.
This happens when the path and the current path are not on the
same disk drive or network share.
"""
return win32.PathRelativePathTo(pszFrom = current, pszTo = path)
@staticmethod
def make_absolute(path):
"""
@type path: str
@param path: Relative path.
@rtype: str
@return: Absolute path.
"""
return win32.GetFullPathName(path)[0]
@staticmethod
def split_extension(pathname):
"""
@type pathname: str
@param pathname: Absolute path.
@rtype: tuple( str, str )
@return:
Tuple containing the file and extension components of the filename.
"""
filepart = win32.PathRemoveExtension(pathname)
extpart = win32.PathFindExtension(pathname)
return (filepart, extpart)
@staticmethod
def split_filename(pathname):
"""
@type pathname: str
@param pathname: Absolute path.
@rtype: tuple( str, str )
@return: Tuple containing the path to the file and the base filename.
"""
filepart = win32.PathFindFileName(pathname)
pathpart = win32.PathRemoveFileSpec(pathname)
return (pathpart, filepart)
@staticmethod
def split_path(path):
"""
@see: L{join_path}
@type path: str
@param path: Absolute or relative path.
@rtype: list( str... )
@return: List of path components.
"""
components = list()
while path:
next = win32.PathFindNextComponent(path)
if next:
prev = path[ : -len(next) ]
components.append(prev)
path = next
return components
@staticmethod
def join_path(*components):
"""
@see: L{split_path}
@type components: tuple( str... )
@param components: Path components.
@rtype: str
@return: Absolute or relative path.
"""
if components:
path = components[0]
for next in components[1:]:
path = win32.PathAppend(path, next)
else:
path = ""
return path
@staticmethod
def native_to_win32_pathname(name):
"""
@type name: str
@param name: Native (NT) absolute pathname.
@rtype: str
@return: Win32 absolute pathname.
"""
# XXX TODO
# There are probably some native paths that
# won't be converted by this naive approach.
if name.startswith(compat.b("\\")):
if name.startswith(compat.b("\\??\\")):
name = name[4:]
elif name.startswith(compat.b("\\SystemRoot\\")):
system_root_path = os.environ['SYSTEMROOT']
if system_root_path.endswith('\\'):
system_root_path = system_root_path[:-1]
name = system_root_path + name[11:]
else:
for drive_number in compat.xrange(ord('A'), ord('Z') + 1):
drive_letter = '%c:' % drive_number
try:
device_native_path = win32.QueryDosDevice(drive_letter)
except WindowsError:
e = sys.exc_info()[1]
if e.winerror in (win32.ERROR_FILE_NOT_FOUND, \
win32.ERROR_PATH_NOT_FOUND):
continue
raise
if not device_native_path.endswith(compat.b('\\')):
device_native_path += compat.b('\\')
if name.startswith(device_native_path):
name = drive_letter + compat.b('\\') + \
name[ len(device_native_path) : ]
break
return name
@staticmethod
def pathname_to_filename(pathname):
"""
Equivalent to: C{PathOperations.split_filename(pathname)[0]}
@note: This function is preserved for backwards compatibility with
WinAppDbg 1.4 and earlier. It may be removed in future versions.
@type pathname: str
@param pathname: Absolute path to a file.
@rtype: str
@return: Filename component of the path.
"""
return win32.PathFindFileName(pathname)
#==============================================================================
class MemoryAddresses (StaticClass):
"""
Class to manipulate memory addresses.
@type pageSize: int
@cvar pageSize: Page size in bytes. Defaults to 0x1000 but it's
automatically updated on runtime when importing the module.
"""
@classproperty
def pageSize(cls):
"""
Try to get the pageSize value on runtime.
"""
try:
try:
pageSize = win32.GetSystemInfo().dwPageSize
except WindowsError:
pageSize = 0x1000
except NameError:
pageSize = 0x1000
cls.pageSize = pageSize # now this function won't be called again
return pageSize
@classmethod
def align_address_to_page_start(cls, address):
"""
Align the given address to the start of the page it occupies.
@type address: int
@param address: Memory address.
@rtype: int
@return: Aligned memory address.
"""
return address - ( address % cls.pageSize )
@classmethod
def align_address_to_page_end(cls, address):
"""
Align the given address to the end of the page it occupies.
That is, to point to the start of the next page.
@type address: int
@param address: Memory address.
@rtype: int
@return: Aligned memory address.
"""
return address + cls.pageSize - ( address % cls.pageSize )
@classmethod
def align_address_range(cls, begin, end):
"""
Align the given address range to the start and end of the page(s) it occupies.
@type begin: int
@param begin: Memory address of the beginning of the buffer.
Use C{None} for the first legal address in the address space.
@type end: int
@param end: Memory address of the end of the buffer.
Use C{None} for the last legal address in the address space.
@rtype: tuple( int, int )
@return: Aligned memory addresses.
"""
if begin is None:
begin = 0
if end is None:
end = win32.LPVOID(-1).value # XXX HACK
if end < begin:
begin, end = end, begin
begin = cls.align_address_to_page_start(begin)
if end != cls.align_address_to_page_start(end):
end = cls.align_address_to_page_end(end)
return (begin, end)
@classmethod
def get_buffer_size_in_pages(cls, address, size):
"""
Get the number of pages in use by the given buffer.
@type address: int
@param address: Aligned memory address.
@type size: int
@param size: Buffer size.
@rtype: int
@return: Buffer size in number of pages.
"""
if size < 0:
size = -size
address = address - size
begin, end = cls.align_address_range(address, address + size)
# XXX FIXME
# I think this rounding fails at least for address 0xFFFFFFFF size 1
return int(float(end - begin) / float(cls.pageSize))
@staticmethod
def do_ranges_intersect(begin, end, old_begin, old_end):
"""
Determine if the two given memory address ranges intersect.
@type begin: int
@param begin: Start address of the first range.
@type end: int
@param end: End address of the first range.
@type old_begin: int
@param old_begin: Start address of the second range.
@type old_end: int
@param old_end: End address of the second range.
@rtype: bool
@return: C{True} if the two ranges intersect, C{False} otherwise.
"""
return (old_begin <= begin < old_end) or \
(old_begin < end <= old_end) or \
(begin <= old_begin < end) or \
(begin < old_end <= end)
#==============================================================================
def CustomAddressIterator(memory_map, condition):
"""
Generator function that iterates through a memory map, filtering memory
region blocks by any given condition.
@type memory_map: list( L{win32.MemoryBasicInformation} )
@param memory_map: List of memory region information objects.
Returned by L{Process.get_memory_map}.
@type condition: function
@param condition: Callback function that returns C{True} if the memory
block should be returned, or C{False} if it should be filtered.
@rtype: generator of L{win32.MemoryBasicInformation}
@return: Generator object to iterate memory blocks.
"""
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
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)
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)
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)
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)
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)
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)
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)
#==============================================================================
try:
_registerMask = win32.SIZE_T(-1).value
except TypeError:
if win32.SIZEOF(win32.SIZE_T) == 4:
_registerMask = 0xFFFFFFFF
elif win32.SIZEOF(win32.SIZE_T) == 8:
_registerMask = 0xFFFFFFFFFFFFFFFF
else:
raise
class DebugRegister (StaticClass):
"""
Class to manipulate debug registers.
Used by L{HardwareBreakpoint}.
@group Trigger flags used by HardwareBreakpoint:
BREAK_ON_EXECUTION, BREAK_ON_WRITE, BREAK_ON_ACCESS, BREAK_ON_IO_ACCESS
@group Size flags used by HardwareBreakpoint:
WATCH_BYTE, WATCH_WORD, WATCH_DWORD, WATCH_QWORD
@group Bitwise masks for Dr7:
enableMask, disableMask, triggerMask, watchMask, clearMask,
generalDetectMask
@group Bitwise masks for Dr6:
hitMask, hitMaskAll, debugAccessMask, singleStepMask, taskSwitchMask,
clearDr6Mask, clearHitMask
@group Debug control MSR definitions:
DebugCtlMSR, LastBranchRecord, BranchTrapFlag, PinControl,
LastBranchToIP, LastBranchFromIP,
LastExceptionToIP, LastExceptionFromIP
@type BREAK_ON_EXECUTION: int
@cvar BREAK_ON_EXECUTION: Break on execution.
@type BREAK_ON_WRITE: int
@cvar BREAK_ON_WRITE: Break on write.
@type BREAK_ON_ACCESS: int
@cvar BREAK_ON_ACCESS: Break on read or write.
@type BREAK_ON_IO_ACCESS: int
@cvar BREAK_ON_IO_ACCESS: Break on I/O port access.
Not supported by any hardware.
@type WATCH_BYTE: int
@cvar WATCH_BYTE: Watch a byte.
@type WATCH_WORD: int
@cvar WATCH_WORD: Watch a word.
@type WATCH_DWORD: int
@cvar WATCH_DWORD: Watch a double word.
@type WATCH_QWORD: int
@cvar WATCH_QWORD: Watch one quad word.
@type enableMask: 4-tuple of integers
@cvar enableMask:
Enable bit on C{Dr7} for each slot.
Works as a bitwise-OR mask.
@type disableMask: 4-tuple of integers
@cvar disableMask:
Mask of the enable bit on C{Dr7} for each slot.
Works as a bitwise-AND mask.
@type triggerMask: 4-tuple of 2-tuples of integers
@cvar triggerMask:
Trigger bits on C{Dr7} for each trigger flag value.
Each 2-tuple has the bitwise-OR mask and the bitwise-AND mask.
@type watchMask: 4-tuple of 2-tuples of integers
@cvar watchMask:
Watch bits on C{Dr7} for each watch flag value.
Each 2-tuple has the bitwise-OR mask and the bitwise-AND mask.
@type clearMask: 4-tuple of integers
@cvar clearMask:
Mask of all important bits on C{Dr7} for each slot.
Works as a bitwise-AND mask.
@type generalDetectMask: integer
@cvar generalDetectMask:
General detect mode bit. It enables the processor to notify the
debugger when the debugee is trying to access one of the debug
registers.
@type hitMask: 4-tuple of integers
@cvar hitMask:
Hit bit on C{Dr6} for each slot.
Works as a bitwise-AND mask.
@type hitMaskAll: integer
@cvar hitMaskAll:
Bitmask for all hit bits in C{Dr6}. Useful to know if at least one
hardware breakpoint was hit, or to clear the hit bits only.
@type clearHitMask: integer
@cvar clearHitMask:
Bitmask to clear all the hit bits in C{Dr6}.
@type debugAccessMask: integer
@cvar debugAccessMask:
The debugee tried to access a debug register. Needs bit
L{generalDetectMask} enabled in C{Dr7}.
@type singleStepMask: integer
@cvar singleStepMask:
A single step exception was raised. Needs the trap flag enabled.
@type taskSwitchMask: integer
@cvar taskSwitchMask:
A task switch has occurred. Needs the TSS T-bit set to 1.
@type clearDr6Mask: integer
@cvar clearDr6Mask:
Bitmask to clear all meaningful bits in C{Dr6}.
"""
BREAK_ON_EXECUTION = 0
BREAK_ON_WRITE = 1
BREAK_ON_ACCESS = 3
BREAK_ON_IO_ACCESS = 2
WATCH_BYTE = 0
WATCH_WORD = 1
WATCH_DWORD = 3
WATCH_QWORD = 2
registerMask = _registerMask
#------------------------------------------------------------------------------
###########################################################################
# http://en.wikipedia.org/wiki/Debug_register
#
# DR7 - Debug control
#
# The low-order eight bits of DR7 (0,2,4,6 and 1,3,5,7) selectively enable
# the four address breakpoint conditions. There are two levels of enabling:
# the local (0,2,4,6) and global (1,3,5,7) levels. The local enable bits
# are automatically reset by the processor at every task switch to avoid
# unwanted breakpoint conditions in the new task. The global enable bits
# are not reset by a task switch; therefore, they can be used for
# conditions that are global to all tasks.
#
# Bits 16-17 (DR0), 20-21 (DR1), 24-25 (DR2), 28-29 (DR3), define when
# breakpoints trigger. Each breakpoint has a two-bit entry that specifies
# whether they break on execution (00b), data write (01b), data read or
# write (11b). 10b is defined to mean break on IO read or write but no
# hardware supports it. Bits 18-19 (DR0), 22-23 (DR1), 26-27 (DR2), 30-31
# (DR3), define how large area of memory is watched by breakpoints. Again
# each breakpoint has a two-bit entry that specifies whether they watch
# one (00b), two (01b), eight (10b) or four (11b) bytes.
###########################################################################
# Dr7 |= enableMask[register]
enableMask = (
1 << 0, # Dr0 (bit 0)
1 << 2, # Dr1 (bit 2)
1 << 4, # Dr2 (bit 4)
1 << 6, # Dr3 (bit 6)
)
# Dr7 &= disableMask[register]
disableMask = tuple( [_registerMask ^ x for x in enableMask] ) # The registerMask from the class is not there in py3
try:
del x # It's not there in py3
except:
pass
# orMask, andMask = triggerMask[register][trigger]
# Dr7 = (Dr7 & andMask) | orMask # to set
# Dr7 = Dr7 & andMask # to remove
triggerMask = (
# Dr0 (bits 16-17)
(
((0 << 16), (3 << 16) ^ registerMask), # execute
((1 << 16), (3 << 16) ^ registerMask), # write
((2 << 16), (3 << 16) ^ registerMask), # io read
((3 << 16), (3 << 16) ^ registerMask), # access
),
# Dr1 (bits 20-21)
(
((0 << 20), (3 << 20) ^ registerMask), # execute
((1 << 20), (3 << 20) ^ registerMask), # write
((2 << 20), (3 << 20) ^ registerMask), # io read
((3 << 20), (3 << 20) ^ registerMask), # access
),
# Dr2 (bits 24-25)
(
((0 << 24), (3 << 24) ^ registerMask), # execute
((1 << 24), (3 << 24) ^ registerMask), # write
((2 << 24), (3 << 24) ^ registerMask), # io read
((3 << 24), (3 << 24) ^ registerMask), # access
),
# Dr3 (bits 28-29)
(
((0 << 28), (3 << 28) ^ registerMask), # execute
((1 << 28), (3 << 28) ^ registerMask), # write
((2 << 28), (3 << 28) ^ registerMask), # io read
((3 << 28), (3 << 28) ^ registerMask), # access
),
)
# orMask, andMask = watchMask[register][watch]
# Dr7 = (Dr7 & andMask) | orMask # to set
# Dr7 = Dr7 & andMask # to remove
watchMask = (
# Dr0 (bits 18-19)
(
((0 << 18), (3 << 18) ^ registerMask), # byte
((1 << 18), (3 << 18) ^ registerMask), # word
((2 << 18), (3 << 18) ^ registerMask), # qword
((3 << 18), (3 << 18) ^ registerMask), # dword
),
# Dr1 (bits 22-23)
(
((0 << 23), (3 << 23) ^ registerMask), # byte
((1 << 23), (3 << 23) ^ registerMask), # word
((2 << 23), (3 << 23) ^ registerMask), # qword
((3 << 23), (3 << 23) ^ registerMask), # dword
),
# Dr2 (bits 26-27)
(
((0 << 26), (3 << 26) ^ registerMask), # byte
((1 << 26), (3 << 26) ^ registerMask), # word
((2 << 26), (3 << 26) ^ registerMask), # qword
((3 << 26), (3 << 26) ^ registerMask), # dword
),
# Dr3 (bits 30-31)
(
((0 << 30), (3 << 31) ^ registerMask), # byte
((1 << 30), (3 << 31) ^ registerMask), # word
((2 << 30), (3 << 31) ^ registerMask), # qword
((3 << 30), (3 << 31) ^ registerMask), # dword
),
)
# Dr7 = Dr7 & clearMask[register]
clearMask = (
registerMask ^ ( (1 << 0) + (3 << 16) + (3 << 18) ), # Dr0
registerMask ^ ( (1 << 2) + (3 << 20) + (3 << 22) ), # Dr1
registerMask ^ ( (1 << 4) + (3 << 24) + (3 << 26) ), # Dr2
registerMask ^ ( (1 << 6) + (3 << 28) + (3 << 30) ), # Dr3
)
# Dr7 = Dr7 | generalDetectMask
generalDetectMask = (1 << 13)
###########################################################################
# http://en.wikipedia.org/wiki/Debug_register
#
# DR6 - Debug status
#
# The debug status register permits the debugger to determine which debug
# conditions have occurred. When the processor detects an enabled debug
# exception, it sets the low-order bits of this register (0,1,2,3) before
# entering the debug exception handler.
#
# Note that the bits of DR6 are never cleared by the processor. To avoid
# any confusion in identifying the next debug exception, the debug handler
# should move zeros to DR6 immediately before returning.
###########################################################################
# bool(Dr6 & hitMask[register])
hitMask = (
(1 << 0), # Dr0
(1 << 1), # Dr1
(1 << 2), # Dr2
(1 << 3), # Dr3
)
# bool(Dr6 & anyHitMask)
hitMaskAll = hitMask[0] | hitMask[1] | hitMask[2] | hitMask[3]
# Dr6 = Dr6 & clearHitMask
clearHitMask = registerMask ^ hitMaskAll
# bool(Dr6 & debugAccessMask)
debugAccessMask = (1 << 13)
# bool(Dr6 & singleStepMask)
singleStepMask = (1 << 14)
# bool(Dr6 & taskSwitchMask)
taskSwitchMask = (1 << 15)
# Dr6 = Dr6 & clearDr6Mask
clearDr6Mask = registerMask ^ (hitMaskAll | \
debugAccessMask | singleStepMask | taskSwitchMask)
#------------------------------------------------------------------------------
###############################################################################
#
# (from the AMD64 manuals)
#
# The fields within the DebugCtlMSR register are:
#
# Last-Branch Record (LBR) - Bit 0, read/write. Software sets this bit to 1
# to cause the processor to record the source and target addresses of the
# last control transfer taken before a debug exception occurs. The recorded
# control transfers include branch instructions, interrupts, and exceptions.
#
# Branch Single Step (BTF) - Bit 1, read/write. Software uses this bit to
# change the behavior of the rFLAGS.TF bit. When this bit is cleared to 0,
# the rFLAGS.TF bit controls instruction single stepping, (normal behavior).
# When this bit is set to 1, the rFLAGS.TF bit controls single stepping on
# control transfers. The single-stepped control transfers include branch
# instructions, interrupts, and exceptions. Control-transfer single stepping
# requires both BTF=1 and rFLAGS.TF=1.
#
# Performance-Monitoring/Breakpoint Pin-Control (PBi) - Bits 5-2, read/write.
# Software uses these bits to control the type of information reported by
# the four external performance-monitoring/breakpoint pins on the processor.
# When a PBi bit is cleared to 0, the corresponding external pin (BPi)
# reports performance-monitor information. When a PBi bit is set to 1, the
# corresponding external pin (BPi) reports breakpoint information.
#
# All remaining bits in the DebugCtlMSR register are reserved.
#
# Software can enable control-transfer single stepping by setting
# DebugCtlMSR.BTF to 1 and rFLAGS.TF to 1. The processor automatically
# disables control-transfer single stepping when a debug exception (#DB)
# occurs by clearing DebugCtlMSR.BTF to 0. rFLAGS.TF is also cleared when a
# #DB exception occurs. Before exiting the debug-exception handler, software
# must set both DebugCtlMSR.BTF and rFLAGS.TF to 1 to restart single
# stepping.
#
###############################################################################
DebugCtlMSR = 0x1D9
LastBranchRecord = (1 << 0)
BranchTrapFlag = (1 << 1)
PinControl = (
(1 << 2), # PB1
(1 << 3), # PB2
(1 << 4), # PB3
(1 << 5), # PB4
)
###############################################################################
#
# (from the AMD64 manuals)
#
# Control-transfer recording MSRs: LastBranchToIP, LastBranchFromIP,
# LastExceptionToIP, and LastExceptionFromIP. These registers are loaded
# automatically by the processor when the DebugCtlMSR.LBR bit is set to 1.
# These MSRs are read-only.
#
# The processor automatically disables control-transfer recording when a
# debug exception (#DB) occurs by clearing DebugCtlMSR.LBR to 0. The
# contents of the control-transfer recording MSRs are not altered by the
# processor when the #DB occurs. Before exiting the debug-exception handler,
# software can set DebugCtlMSR.LBR to 1 to re-enable the recording mechanism.
#
###############################################################################
LastBranchToIP = 0x1DC
LastBranchFromIP = 0x1DB
LastExceptionToIP = 0x1DE
LastExceptionFromIP = 0x1DD
#------------------------------------------------------------------------------
@classmethod
def clear_bp(cls, ctx, register):
"""
Clears a hardware breakpoint.
@see: find_slot, set_bp
@type ctx: dict( str S{->} int )
@param ctx: Thread context dictionary.
@type register: int
@param register: Slot (debug register) for hardware breakpoint.
"""
ctx['Dr7'] &= cls.clearMask[register]
ctx['Dr%d' % register] = 0
@classmethod
def set_bp(cls, ctx, register, address, trigger, watch):
"""
Sets a hardware breakpoint.
@see: clear_bp, find_slot
@type ctx: dict( str S{->} int )
@param ctx: Thread context dictionary.
@type register: int
@param register: Slot (debug register).
@type address: int
@param address: Memory address.
@type trigger: int
@param trigger: Trigger flag. See L{HardwareBreakpoint.validTriggers}.
@type watch: int
@param watch: Watch flag. See L{HardwareBreakpoint.validWatchSizes}.
"""
Dr7 = ctx['Dr7']
Dr7 |= cls.enableMask[register]
orMask, andMask = cls.triggerMask[register][trigger]
Dr7 &= andMask
Dr7 |= orMask
orMask, andMask = cls.watchMask[register][watch]
Dr7 &= andMask
Dr7 |= orMask
ctx['Dr7'] = Dr7
ctx['Dr%d' % register] = address
@classmethod
def find_slot(cls, ctx):
"""
Finds an empty slot to set a hardware breakpoint.
@see: clear_bp, set_bp
@type ctx: dict( str S{->} int )
@param ctx: Thread context dictionary.
@rtype: int
@return: Slot (debug register) for hardware breakpoint.
"""
Dr7 = ctx['Dr7']
slot = 0
for m in cls.enableMask:
if (Dr7 & m) == 0:
return slot
slot += 1
return None
| 36,223 | Python | 33.864293 | 120 | 0.585208 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/module.py | #!~/.wine/drive_c/Python25/python.exe
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Module instrumentation.
@group Instrumentation:
Module
@group Warnings:
DebugSymbolsWarning
"""
from __future__ import with_statement
__revision__ = "$Id$"
__all__ = ['Module', 'DebugSymbolsWarning']
import sys
from winappdbg import win32
from winappdbg import compat
from winappdbg.textio import HexInput, HexDump
from winappdbg.util import PathOperations
# delayed imports
Process = None
import os
import warnings
import traceback
#==============================================================================
class DebugSymbolsWarning (UserWarning):
"""
This warning is issued if the support for debug symbols
isn't working properly.
"""
#==============================================================================
class Module (object):
"""
Interface to a DLL library loaded in the context of another process.
@group Properties:
get_base, get_filename, get_name, get_size, get_entry_point,
get_process, set_process, get_pid,
get_handle, set_handle, open_handle, close_handle
@group Labels:
get_label, get_label_at_address, is_address_here,
resolve, resolve_label, match_name
@group Symbols:
load_symbols, unload_symbols, get_symbols, iter_symbols,
resolve_symbol, get_symbol_at_address
@group Modules snapshot:
clear
@type unknown: str
@cvar unknown: Suggested tag for unknown modules.
@type lpBaseOfDll: int
@ivar lpBaseOfDll: Base of DLL module.
Use L{get_base} instead.
@type hFile: L{FileHandle}
@ivar hFile: Handle to the module file.
Use L{get_handle} instead.
@type fileName: str
@ivar fileName: Module filename.
Use L{get_filename} instead.
@type SizeOfImage: int
@ivar SizeOfImage: Size of the module.
Use L{get_size} instead.
@type EntryPoint: int
@ivar EntryPoint: Entry point of the module.
Use L{get_entry_point} instead.
@type process: L{Process}
@ivar process: Process where the module is loaded.
Use the L{get_process} method instead.
"""
unknown = '<unknown>'
class _SymbolEnumerator (object):
"""
Internally used by L{Module} to enumerate symbols in a module.
"""
def __init__(self, undecorate = False):
self.symbols = list()
self.undecorate = undecorate
def __call__(self, SymbolName, SymbolAddress, SymbolSize, UserContext):
"""
Callback that receives symbols and stores them in a Python list.
"""
if self.undecorate:
try:
SymbolName = win32.UnDecorateSymbolName(SymbolName)
except Exception:
pass # not all symbols are decorated!
self.symbols.append( (SymbolName, SymbolAddress, SymbolSize) )
return win32.TRUE
def __init__(self, lpBaseOfDll, hFile = None, fileName = None,
SizeOfImage = None,
EntryPoint = None,
process = None):
"""
@type lpBaseOfDll: str
@param lpBaseOfDll: Base address of the module.
@type hFile: L{FileHandle}
@param hFile: (Optional) Handle to the module file.
@type fileName: str
@param fileName: (Optional) Module filename.
@type SizeOfImage: int
@param SizeOfImage: (Optional) Size of the module.
@type EntryPoint: int
@param EntryPoint: (Optional) Entry point of the module.
@type process: L{Process}
@param process: (Optional) Process where the module is loaded.
"""
self.lpBaseOfDll = lpBaseOfDll
self.fileName = fileName
self.SizeOfImage = SizeOfImage
self.EntryPoint = EntryPoint
self.__symbols = list()
self.set_handle(hFile)
self.set_process(process)
# Not really sure if it's a good idea...
## def __eq__(self, aModule):
## """
## Compare two Module objects. The comparison is made using the process
## IDs and the module bases.
##
## @type aModule: L{Module}
## @param aModule: Another Module object.
##
## @rtype: bool
## @return: C{True} if the two process IDs and module bases are equal,
## C{False} otherwise.
## """
## return isinstance(aModule, Module) and \
## self.get_pid() == aModule.get_pid() and \
## self.get_base() == aModule.get_base()
def get_handle(self):
"""
@rtype: L{Handle}
@return: File handle.
Returns C{None} if unknown.
"""
# no way to guess!
return self.__hFile
def set_handle(self, hFile):
"""
@type hFile: L{Handle}
@param hFile: File handle. Use C{None} to clear.
"""
if hFile == win32.INVALID_HANDLE_VALUE:
hFile = None
self.__hFile = hFile
hFile = property(get_handle, set_handle, doc="")
def get_process(self):
"""
@rtype: L{Process}
@return: Parent Process object.
Returns C{None} if unknown.
"""
# no way to guess!
return self.__process
def set_process(self, process = None):
"""
Manually set the parent process. Use with care!
@type process: L{Process}
@param process: (Optional) Process object. Use C{None} for no process.
"""
if process is None:
self.__process = None
else:
global Process # delayed import
if Process is None:
from winappdbg.process import Process
if not isinstance(process, Process):
msg = "Parent process must be a Process instance, "
msg += "got %s instead" % type(process)
raise TypeError(msg)
self.__process = process
process = property(get_process, set_process, doc="")
def get_pid(self):
"""
@rtype: int or None
@return: Parent process global ID.
Returns C{None} on error.
"""
process = self.get_process()
if process is not None:
return process.get_pid()
def get_base(self):
"""
@rtype: int or None
@return: Base address of the module.
Returns C{None} if unknown.
"""
return self.lpBaseOfDll
def get_size(self):
"""
@rtype: int or None
@return: Base size of the module.
Returns C{None} if unknown.
"""
if not self.SizeOfImage:
self.__get_size_and_entry_point()
return self.SizeOfImage
def get_entry_point(self):
"""
@rtype: int or None
@return: Entry point of the module.
Returns C{None} if unknown.
"""
if not self.EntryPoint:
self.__get_size_and_entry_point()
return self.EntryPoint
def __get_size_and_entry_point(self):
"Get the size and entry point of the module using the Win32 API."
process = self.get_process()
if process:
try:
handle = process.get_handle( win32.PROCESS_VM_READ |
win32.PROCESS_QUERY_INFORMATION )
base = self.get_base()
mi = win32.GetModuleInformation(handle, base)
self.SizeOfImage = mi.SizeOfImage
self.EntryPoint = mi.EntryPoint
except WindowsError:
e = sys.exc_info()[1]
warnings.warn(
"Cannot get size and entry point of module %s, reason: %s"\
% (self.get_name(), e.strerror), RuntimeWarning)
def get_filename(self):
"""
@rtype: str or None
@return: Module filename.
Returns C{None} if unknown.
"""
if self.fileName is None:
if self.hFile not in (None, win32.INVALID_HANDLE_VALUE):
fileName = self.hFile.get_filename()
if fileName:
fileName = PathOperations.native_to_win32_pathname(fileName)
self.fileName = fileName
return self.fileName
def __filename_to_modname(self, pathname):
"""
@type pathname: str
@param pathname: Pathname to a module.
@rtype: str
@return: Module name.
"""
filename = PathOperations.pathname_to_filename(pathname)
if filename:
filename = filename.lower()
filepart, extpart = PathOperations.split_extension(filename)
if filepart and extpart:
modName = filepart
else:
modName = filename
else:
modName = pathname
return modName
def get_name(self):
"""
@rtype: str
@return: Module name, as used in labels.
@warning: Names are B{NOT} guaranteed to be unique.
If you need unique identification for a loaded module,
use the base address instead.
@see: L{get_label}
"""
pathname = self.get_filename()
if pathname:
modName = self.__filename_to_modname(pathname)
if isinstance(modName, compat.unicode):
try:
modName = modName.encode('cp1252')
except UnicodeEncodeError:
e = sys.exc_info()[1]
warnings.warn(str(e))
else:
modName = "0x%x" % self.get_base()
return modName
def match_name(self, name):
"""
@rtype: bool
@return:
C{True} if the given name could refer to this module.
It may not be exactly the same returned by L{get_name}.
"""
# If the given name is exactly our name, return True.
# Comparison is case insensitive.
my_name = self.get_name().lower()
if name.lower() == my_name:
return True
# If the given name is a base address, compare it with ours.
try:
base = HexInput.integer(name)
except ValueError:
base = None
if base is not None and base == self.get_base():
return True
# If the given name is a filename, convert it to a module name.
# Then compare it with ours, case insensitive.
modName = self.__filename_to_modname(name)
if modName.lower() == my_name:
return True
# No match.
return False
#------------------------------------------------------------------------------
def open_handle(self):
"""
Opens a new handle to the module.
The new handle is stored in the L{hFile} property.
"""
if not self.get_filename():
msg = "Cannot retrieve filename for module at %s"
msg = msg % HexDump.address( self.get_base() )
raise Exception(msg)
hFile = win32.CreateFile(self.get_filename(),
dwShareMode = win32.FILE_SHARE_READ,
dwCreationDisposition = win32.OPEN_EXISTING)
# In case hFile was set to an actual handle value instead of a Handle
# object. This shouldn't happen unless the user tinkered with hFile.
if not hasattr(self.hFile, '__del__'):
self.close_handle()
self.hFile = hFile
def close_handle(self):
"""
Closes the handle to the module.
@note: Normally you don't need to call this method. All handles
created by I{WinAppDbg} are automatically closed when the garbage
collector claims them. So unless you've been tinkering with it,
setting L{hFile} to C{None} should be enough.
"""
try:
if hasattr(self.hFile, 'close'):
self.hFile.close()
elif self.hFile not in (None, win32.INVALID_HANDLE_VALUE):
win32.CloseHandle(self.hFile)
finally:
self.hFile = None
def get_handle(self):
"""
@rtype: L{FileHandle}
@return: Handle to the module file.
"""
if self.hFile in (None, win32.INVALID_HANDLE_VALUE):
self.open_handle()
return self.hFile
def clear(self):
"""
Clears the resources held by this object.
"""
try:
self.set_process(None)
finally:
self.close_handle()
#------------------------------------------------------------------------------
# XXX FIXME
# I've been told sometimes the debugging symbols APIs don't correctly
# handle redirected exports (for example ws2_32!recv).
# I haven't been able to reproduce the bug yet.
def load_symbols(self):
"""
Loads the debugging symbols for a module.
Automatically called by L{get_symbols}.
"""
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_process().get_handle(dwAccess)
hFile = self.hFile
BaseOfDll = self.get_base()
SizeOfDll = self.get_size()
Enumerator = self._SymbolEnumerator()
try:
win32.SymInitialize(hProcess)
SymOptions = win32.SymGetOptions()
SymOptions |= (
win32.SYMOPT_ALLOW_ZERO_ADDRESS |
win32.SYMOPT_CASE_INSENSITIVE |
win32.SYMOPT_FAVOR_COMPRESSED |
win32.SYMOPT_INCLUDE_32BIT_MODULES |
win32.SYMOPT_UNDNAME
)
SymOptions &= ~(
win32.SYMOPT_LOAD_LINES |
win32.SYMOPT_NO_IMAGE_SEARCH |
win32.SYMOPT_NO_CPP |
win32.SYMOPT_IGNORE_NT_SYMPATH
)
win32.SymSetOptions(SymOptions)
try:
win32.SymSetOptions(
SymOptions | win32.SYMOPT_ALLOW_ABSOLUTE_SYMBOLS)
except WindowsError:
pass
try:
try:
success = win32.SymLoadModule64(
hProcess, hFile, None, None, BaseOfDll, SizeOfDll)
except WindowsError:
success = 0
if not success:
ImageName = self.get_filename()
success = win32.SymLoadModule64(
hProcess, None, ImageName, None, BaseOfDll, SizeOfDll)
if success:
try:
win32.SymEnumerateSymbols64(
hProcess, BaseOfDll, Enumerator)
finally:
win32.SymUnloadModule64(hProcess, BaseOfDll)
finally:
win32.SymCleanup(hProcess)
except WindowsError:
e = sys.exc_info()[1]
msg = "Cannot load debug symbols for process ID %d, reason:\n%s"
msg = msg % (self.get_pid(), traceback.format_exc(e))
warnings.warn(msg, DebugSymbolsWarning)
self.__symbols = Enumerator.symbols
def unload_symbols(self):
"""
Unloads the debugging symbols for a module.
"""
self.__symbols = list()
def get_symbols(self):
"""
Returns the debugging symbols for a module.
The symbols are automatically loaded when needed.
@rtype: list of tuple( str, int, int )
@return: List of symbols.
Each symbol is represented by a tuple that contains:
- Symbol name
- Symbol memory address
- Symbol size in bytes
"""
if not self.__symbols:
self.load_symbols()
return list(self.__symbols)
def iter_symbols(self):
"""
Returns an iterator for the debugging symbols in a module,
in no particular order.
The symbols are automatically loaded when needed.
@rtype: iterator of tuple( str, int, int )
@return: Iterator of symbols.
Each symbol is represented by a tuple that contains:
- Symbol name
- Symbol memory address
- Symbol size in bytes
"""
if not self.__symbols:
self.load_symbols()
return self.__symbols.__iter__()
def resolve_symbol(self, symbol, bCaseSensitive = False):
"""
Resolves a debugging symbol's address.
@type symbol: str
@param symbol: Name of the symbol to resolve.
@type bCaseSensitive: bool
@param bCaseSensitive: C{True} for case sensitive matches,
C{False} for case insensitive.
@rtype: int or None
@return: Memory address of symbol. C{None} if not found.
"""
if bCaseSensitive:
for (SymbolName, SymbolAddress, SymbolSize) in self.iter_symbols():
if symbol == SymbolName:
return SymbolAddress
for (SymbolName, SymbolAddress, SymbolSize) in self.iter_symbols():
try:
SymbolName = win32.UnDecorateSymbolName(SymbolName)
except Exception:
continue
if symbol == SymbolName:
return SymbolAddress
else:
symbol = symbol.lower()
for (SymbolName, SymbolAddress, SymbolSize) in self.iter_symbols():
if symbol == SymbolName.lower():
return SymbolAddress
for (SymbolName, SymbolAddress, SymbolSize) in self.iter_symbols():
try:
SymbolName = win32.UnDecorateSymbolName(SymbolName)
except Exception:
continue
if symbol == SymbolName.lower():
return SymbolAddress
def get_symbol_at_address(self, address):
"""
Tries to find the closest matching symbol for the given address.
@type address: int
@param address: Memory address to query.
@rtype: None or tuple( str, int, int )
@return: Returns a tuple consisting of:
- Name
- Address
- Size (in bytes)
Returns C{None} if no symbol could be matched.
"""
found = None
for (SymbolName, SymbolAddress, SymbolSize) in self.iter_symbols():
if SymbolAddress > address:
continue
if SymbolAddress + SymbolSize > address:
if not found or found[1] < SymbolAddress:
found = (SymbolName, SymbolAddress, SymbolSize)
return found
#------------------------------------------------------------------------------
def get_label(self, function = None, offset = None):
"""
Retrieves the label for the given function of this module or the module
base address if no function name is given.
@type function: str
@param function: (Optional) Exported function name.
@type offset: int
@param offset: (Optional) Offset from the module base address.
@rtype: str
@return: Label for the module base address, plus the offset if given.
"""
return _ModuleContainer.parse_label(self.get_name(), function, offset)
def get_label_at_address(self, address, offset = None):
"""
Creates a label from the given memory address.
If the address belongs to the module, the label is made relative to
it's base address.
@type address: int
@param address: Memory address.
@type offset: None or int
@param offset: (Optional) Offset value.
@rtype: str
@return: Label pointing to the given address.
"""
# Add the offset to the address.
if offset:
address = address + offset
# Make the label relative to the base address if no match is found.
module = self.get_name()
function = None
offset = address - self.get_base()
# Make the label relative to the entrypoint if no other match is found.
# Skip if the entry point is unknown.
start = self.get_entry_point()
if start and start <= address:
function = "start"
offset = address - start
# Enumerate exported functions and debug symbols,
# then find the closest match, if possible.
try:
symbol = self.get_symbol_at_address(address)
if symbol:
(SymbolName, SymbolAddress, SymbolSize) = symbol
new_offset = address - SymbolAddress
if new_offset <= offset:
function = SymbolName
offset = new_offset
except WindowsError:
pass
# Parse the label and return it.
return _ModuleContainer.parse_label(module, function, offset)
def is_address_here(self, address):
"""
Tries to determine if the given address belongs to this module.
@type address: int
@param address: Memory address.
@rtype: bool or None
@return: C{True} if the address belongs to the module,
C{False} if it doesn't,
and C{None} if it can't be determined.
"""
base = self.get_base()
size = self.get_size()
if base and size:
return base <= address < (base + size)
return None
def resolve(self, function):
"""
Resolves a function exported by this module.
@type function: str or int
@param function:
str: Name of the function.
int: Ordinal of the function.
@rtype: int
@return: Memory address of the exported function in the process.
Returns None on error.
"""
# Unknown DLL filename, there's nothing we can do.
filename = self.get_filename()
if not filename:
return None
# If the DLL is already mapped locally, resolve the function.
try:
hlib = win32.GetModuleHandle(filename)
address = win32.GetProcAddress(hlib, function)
except WindowsError:
# Load the DLL locally, resolve the function and unload it.
try:
hlib = win32.LoadLibraryEx(filename,
win32.DONT_RESOLVE_DLL_REFERENCES)
try:
address = win32.GetProcAddress(hlib, function)
finally:
win32.FreeLibrary(hlib)
except WindowsError:
return None
# A NULL pointer means the function was not found.
if address in (None, 0):
return None
# Compensate for DLL base relocations locally and remotely.
return address - hlib + self.lpBaseOfDll
def resolve_label(self, label):
"""
Resolves a label for this module only. If the label refers to another
module, an exception is raised.
@type label: str
@param label: Label to resolve.
@rtype: int
@return: Memory address pointed to by the label.
@raise ValueError: The label is malformed or impossible to resolve.
@raise RuntimeError: Cannot resolve the module or function.
"""
# Split the label into it's components.
# Use the fuzzy mode whenever possible.
aProcess = self.get_process()
if aProcess is not None:
(module, procedure, offset) = aProcess.split_label(label)
else:
(module, procedure, offset) = _ModuleContainer.split_label(label)
# If a module name is given that doesn't match ours,
# raise an exception.
if module and not self.match_name(module):
raise RuntimeError("Label does not belong to this module")
# Resolve the procedure if given.
if procedure:
address = self.resolve(procedure)
if address is None:
# If it's a debug symbol, use the symbol.
address = self.resolve_symbol(procedure)
# If it's the keyword "start" use the entry point.
if address is None and procedure == "start":
address = self.get_entry_point()
# The procedure was not found.
if address is None:
if not module:
module = self.get_name()
msg = "Can't find procedure %s in module %s"
raise RuntimeError(msg % (procedure, module))
# If no procedure is given use the base address of the module.
else:
address = self.get_base()
# Add the offset if given and return the resolved address.
if offset:
address = address + offset
return address
#==============================================================================
# TODO
# An alternative approach to the toolhelp32 snapshots: parsing the PEB and
# fetching the list of loaded modules from there. That would solve the problem
# of toolhelp32 not working when the process hasn't finished initializing.
# See: http://pferrie.host22.com/misc/lowlevel3.htm
class _ModuleContainer (object):
"""
Encapsulates the capability to contain Module objects.
@note: Labels are an approximated way of referencing memory locations
across different executions of the same process, or different processes
with common modules. They are not meant to be perfectly unique, and
some errors may occur when multiple modules with the same name are
loaded, or when module filenames can't be retrieved.
@group Modules snapshot:
scan_modules,
get_module, get_module_bases, get_module_count,
get_module_at_address, get_module_by_name,
has_module, iter_modules, iter_module_addresses,
clear_modules
@group Labels:
parse_label, split_label, sanitize_label, resolve_label,
resolve_label_components, get_label_at_address, split_label_strict,
split_label_fuzzy
@group Symbols:
load_symbols, unload_symbols, get_symbols, iter_symbols,
resolve_symbol, get_symbol_at_address
@group Debugging:
is_system_defined_breakpoint, get_system_breakpoint,
get_user_breakpoint, get_breakin_breakpoint,
get_wow64_system_breakpoint, get_wow64_user_breakpoint,
get_wow64_breakin_breakpoint, get_break_on_error_ptr
"""
def __init__(self):
self.__moduleDict = dict()
self.__system_breakpoints = dict()
# Replace split_label with the fuzzy version on object instances.
self.split_label = self.__use_fuzzy_mode
def __initialize_snapshot(self):
"""
Private method to automatically initialize the snapshot
when you try to use it without calling any of the scan_*
methods first. You don't need to call this yourself.
"""
if not self.__moduleDict:
try:
self.scan_modules()
except WindowsError:
pass
def __contains__(self, anObject):
"""
@type anObject: L{Module}, int
@param anObject:
- C{Module}: Module object to look for.
- C{int}: Base address of the DLL to look for.
@rtype: bool
@return: C{True} if the snapshot contains
a L{Module} object with the same base address.
"""
if isinstance(anObject, Module):
anObject = anObject.lpBaseOfDll
return self.has_module(anObject)
def __iter__(self):
"""
@see: L{iter_modules}
@rtype: dictionary-valueiterator
@return: Iterator of L{Module} objects in this snapshot.
"""
return self.iter_modules()
def __len__(self):
"""
@see: L{get_module_count}
@rtype: int
@return: Count of L{Module} objects in this snapshot.
"""
return self.get_module_count()
def has_module(self, lpBaseOfDll):
"""
@type lpBaseOfDll: int
@param lpBaseOfDll: Base address of the DLL to look for.
@rtype: bool
@return: C{True} if the snapshot contains a
L{Module} object with the given base address.
"""
self.__initialize_snapshot()
return lpBaseOfDll in self.__moduleDict
def get_module(self, lpBaseOfDll):
"""
@type lpBaseOfDll: int
@param lpBaseOfDll: Base address of the DLL to look for.
@rtype: L{Module}
@return: Module object with the given base address.
"""
self.__initialize_snapshot()
if lpBaseOfDll not in self.__moduleDict:
msg = "Unknown DLL base address %s"
msg = msg % HexDump.address(lpBaseOfDll)
raise KeyError(msg)
return self.__moduleDict[lpBaseOfDll]
def iter_module_addresses(self):
"""
@see: L{iter_modules}
@rtype: dictionary-keyiterator
@return: Iterator of DLL base addresses in this snapshot.
"""
self.__initialize_snapshot()
return compat.iterkeys(self.__moduleDict)
def iter_modules(self):
"""
@see: L{iter_module_addresses}
@rtype: dictionary-valueiterator
@return: Iterator of L{Module} objects in this snapshot.
"""
self.__initialize_snapshot()
return compat.itervalues(self.__moduleDict)
def get_module_bases(self):
"""
@see: L{iter_module_addresses}
@rtype: list( int... )
@return: List of DLL base addresses in this snapshot.
"""
self.__initialize_snapshot()
return compat.keys(self.__moduleDict)
def get_module_count(self):
"""
@rtype: int
@return: Count of L{Module} objects in this snapshot.
"""
self.__initialize_snapshot()
return len(self.__moduleDict)
#------------------------------------------------------------------------------
def get_module_by_name(self, modName):
"""
@type modName: int
@param modName:
Name of the module to look for, as returned by L{Module.get_name}.
If two or more modules with the same name are loaded, only one
of the matching modules is returned.
You can also pass a full pathname to the DLL file.
This works correctly even if two modules with the same name
are loaded from different paths.
@rtype: L{Module}
@return: C{Module} object that best matches the given name.
Returns C{None} if no C{Module} can be found.
"""
# Convert modName to lowercase.
# This helps make case insensitive string comparisons.
modName = modName.lower()
# modName is an absolute pathname.
if PathOperations.path_is_absolute(modName):
for lib in self.iter_modules():
if modName == lib.get_filename().lower():
return lib
return None # Stop trying to match the name.
# Get all the module names.
# This prevents having to iterate through the module list
# more than once.
modDict = [ ( lib.get_name(), lib ) for lib in self.iter_modules() ]
modDict = dict(modDict)
# modName is a base filename.
if modName in modDict:
return modDict[modName]
# modName is a base filename without extension.
filepart, extpart = PathOperations.split_extension(modName)
if filepart and extpart:
if filepart in modDict:
return modDict[filepart]
# modName is a base address.
try:
baseAddress = HexInput.integer(modName)
except ValueError:
return None
if self.has_module(baseAddress):
return self.get_module(baseAddress)
# Module not found.
return None
def get_module_at_address(self, address):
"""
@type address: int
@param address: Memory address to query.
@rtype: L{Module}
@return: C{Module} object that best matches the given address.
Returns C{None} if no C{Module} can be found.
"""
bases = self.get_module_bases()
bases.sort()
bases.append(long(0x10000000000000000)) # max. 64 bit address + 1
if address >= bases[0]:
i = 0
max_i = len(bases) - 1
while i < max_i:
begin, end = bases[i:i+2]
if begin <= address < end:
module = self.get_module(begin)
here = module.is_address_here(address)
if here is False:
break
else: # True or None
return module
i = i + 1
return None
# XXX this method musn't end up calling __initialize_snapshot by accident!
def scan_modules(self):
"""
Populates the snapshot with loaded modules.
"""
# The module filenames may be spoofed by malware,
# since this information resides in usermode space.
# See: http://www.ragestorm.net/blogs/?p=163
# Ignore special process IDs.
# PID 0: System Idle Process. Also has a special meaning to the
# toolhelp APIs (current process).
# PID 4: System Integrity Group. See this forum post for more info:
# http://tinyurl.com/ycza8jo
# (points to social.technet.microsoft.com)
# Only on XP and above
# PID 8: System (?) only in Windows 2000 and below AFAIK.
# It's probably the same as PID 4 in XP and above.
dwProcessId = self.get_pid()
if dwProcessId in (0, 4, 8):
return
# It would seem easier to clear the snapshot first.
# But then all open handles would be closed.
found_bases = set()
with win32.CreateToolhelp32Snapshot(win32.TH32CS_SNAPMODULE,
dwProcessId) as hSnapshot:
me = win32.Module32First(hSnapshot)
while me is not None:
lpBaseAddress = me.modBaseAddr
fileName = me.szExePath # full pathname
if not fileName:
fileName = me.szModule # filename only
if not fileName:
fileName = None
else:
fileName = PathOperations.native_to_win32_pathname(fileName)
found_bases.add(lpBaseAddress)
## if not self.has_module(lpBaseAddress): # XXX triggers a scan
if lpBaseAddress not in self.__moduleDict:
aModule = Module(lpBaseAddress, fileName = fileName,
SizeOfImage = me.modBaseSize,
process = self)
self._add_module(aModule)
else:
aModule = self.get_module(lpBaseAddress)
if not aModule.fileName:
aModule.fileName = fileName
if not aModule.SizeOfImage:
aModule.SizeOfImage = me.modBaseSize
if not aModule.process:
aModule.process = self
me = win32.Module32Next(hSnapshot)
## for base in self.get_module_bases(): # XXX triggers a scan
for base in compat.keys(self.__moduleDict):
if base not in found_bases:
self._del_module(base)
def clear_modules(self):
"""
Clears the modules snapshot.
"""
for aModule in compat.itervalues(self.__moduleDict):
aModule.clear()
self.__moduleDict = dict()
#------------------------------------------------------------------------------
@staticmethod
def parse_label(module = None, function = None, offset = None):
"""
Creates a label from a module and a function name, plus an offset.
@warning: This method only creates the label, it doesn't make sure the
label actually points to a valid memory location.
@type module: None or str
@param module: (Optional) Module name.
@type function: None, str or int
@param function: (Optional) Function name or ordinal.
@type offset: None or int
@param offset: (Optional) Offset value.
If C{function} is specified, offset from the function.
If C{function} is C{None}, offset from the module.
@rtype: str
@return:
Label representing the given function in the given module.
@raise ValueError:
The module or function name contain invalid characters.
"""
# TODO
# Invalid characters should be escaped or filtered.
# Convert ordinals to strings.
try:
function = "#0x%x" % function
except TypeError:
pass
# Validate the parameters.
if module is not None and ('!' in module or '+' in module):
raise ValueError("Invalid module name: %s" % module)
if function is not None and ('!' in function or '+' in function):
raise ValueError("Invalid function name: %s" % function)
# Parse the label.
if module:
if function:
if offset:
label = "%s!%s+0x%x" % (module, function, offset)
else:
label = "%s!%s" % (module, function)
else:
if offset:
## label = "%s+0x%x!" % (module, offset)
label = "%s!0x%x" % (module, offset)
else:
label = "%s!" % module
else:
if function:
if offset:
label = "!%s+0x%x" % (function, offset)
else:
label = "!%s" % function
else:
if offset:
label = "0x%x" % offset
else:
label = "0x0"
return label
@staticmethod
def split_label_strict(label):
"""
Splits a label created with L{parse_label}.
To parse labels with a less strict syntax, use the L{split_label_fuzzy}
method instead.
@warning: This method only parses the label, it doesn't make sure the
label actually points to a valid memory location.
@type label: str
@param label: Label to split.
@rtype: tuple( str or None, str or int or None, int or None )
@return: Tuple containing the C{module} name,
the C{function} name or ordinal, and the C{offset} value.
If the label doesn't specify a module,
then C{module} is C{None}.
If the label doesn't specify a function,
then C{function} is C{None}.
If the label doesn't specify an offset,
then C{offset} is C{0}.
@raise ValueError: The label is malformed.
"""
module = function = None
offset = 0
# Special case: None
if not label:
label = "0x0"
else:
# Remove all blanks.
label = label.replace(' ', '')
label = label.replace('\t', '')
label = label.replace('\r', '')
label = label.replace('\n', '')
# Special case: empty label.
if not label:
label = "0x0"
# * ! *
if '!' in label:
try:
module, function = label.split('!')
except ValueError:
raise ValueError("Malformed label: %s" % label)
# module ! function
if function:
if '+' in module:
raise ValueError("Malformed label: %s" % label)
# module ! function + offset
if '+' in function:
try:
function, offset = function.split('+')
except ValueError:
raise ValueError("Malformed label: %s" % label)
try:
offset = HexInput.integer(offset)
except ValueError:
raise ValueError("Malformed label: %s" % label)
else:
# module ! offset
try:
offset = HexInput.integer(function)
function = None
except ValueError:
pass
else:
# module + offset !
if '+' in module:
try:
module, offset = module.split('+')
except ValueError:
raise ValueError("Malformed label: %s" % label)
try:
offset = HexInput.integer(offset)
except ValueError:
raise ValueError("Malformed label: %s" % label)
else:
# module !
try:
offset = HexInput.integer(module)
module = None
# offset !
except ValueError:
pass
if not module:
module = None
if not function:
function = None
# *
else:
# offset
try:
offset = HexInput.integer(label)
# # ordinal
except ValueError:
if label.startswith('#'):
function = label
try:
HexInput.integer(function[1:])
# module?
# function?
except ValueError:
raise ValueError("Ambiguous label: %s" % label)
# module?
# function?
else:
raise ValueError("Ambiguous label: %s" % label)
# Convert function ordinal strings into integers.
if function and function.startswith('#'):
try:
function = HexInput.integer(function[1:])
except ValueError:
pass
# Convert null offsets to None.
if not offset:
offset = None
return (module, function, offset)
def split_label_fuzzy(self, label):
"""
Splits a label entered as user input.
It's more flexible in it's syntax parsing than the L{split_label_strict}
method, as it allows the exclamation mark (B{C{!}}) to be omitted. The
ambiguity is resolved by searching the modules in the snapshot to guess
if a label refers to a module or a function. It also tries to rebuild
labels when they contain hardcoded addresses.
@warning: This method only parses the label, it doesn't make sure the
label actually points to a valid memory location.
@type label: str
@param label: Label to split.
@rtype: tuple( str or None, str or int or None, int or None )
@return: Tuple containing the C{module} name,
the C{function} name or ordinal, and the C{offset} value.
If the label doesn't specify a module,
then C{module} is C{None}.
If the label doesn't specify a function,
then C{function} is C{None}.
If the label doesn't specify an offset,
then C{offset} is C{0}.
@raise ValueError: The label is malformed.
"""
module = function = None
offset = 0
# Special case: None
if not label:
label = compat.b("0x0")
else:
# Remove all blanks.
label = label.replace(compat.b(' '), compat.b(''))
label = label.replace(compat.b('\t'), compat.b(''))
label = label.replace(compat.b('\r'), compat.b(''))
label = label.replace(compat.b('\n'), compat.b(''))
# Special case: empty label.
if not label:
label = compat.b("0x0")
# If an exclamation sign is present, we know we can parse it strictly.
if compat.b('!') in label:
return self.split_label_strict(label)
## # Try to parse it strictly, on error do it the fuzzy way.
## try:
## return self.split_label(label)
## except ValueError:
## pass
# * + offset
if compat.b('+') in label:
try:
prefix, offset = label.split(compat.b('+'))
except ValueError:
raise ValueError("Malformed label: %s" % label)
try:
offset = HexInput.integer(offset)
except ValueError:
raise ValueError("Malformed label: %s" % label)
label = prefix
# This parses both filenames and base addresses.
modobj = self.get_module_by_name(label)
if modobj:
# module
# module + offset
module = modobj.get_name()
else:
# TODO
# If 0xAAAAAAAA + 0xBBBBBBBB is given,
# A is interpreted as a module base address,
# and B as an offset.
# If that fails, it'd be good to add A+B and try to
# use the nearest loaded module.
# offset
# base address + offset (when no module has that base address)
try:
address = HexInput.integer(label)
if offset:
# If 0xAAAAAAAA + 0xBBBBBBBB is given,
# A is interpreted as a module base address,
# and B as an offset.
# If that fails, we get here, meaning no module was found
# at A. Then add up A+B and work with that as a hardcoded
# address.
offset = address + offset
else:
# If the label is a hardcoded address, we get here.
offset = address
# If only a hardcoded address is given,
# rebuild the label using get_label_at_address.
# Then parse it again, but this time strictly,
# both because there is no need for fuzzy syntax and
# to prevent an infinite recursion if there's a bug here.
try:
new_label = self.get_label_at_address(offset)
module, function, offset = \
self.split_label_strict(new_label)
except ValueError:
pass
# function
# function + offset
except ValueError:
function = label
# Convert function ordinal strings into integers.
if function and function.startswith(compat.b('#')):
try:
function = HexInput.integer(function[1:])
except ValueError:
pass
# Convert null offsets to None.
if not offset:
offset = None
return (module, function, offset)
@classmethod
def split_label(cls, label):
"""
Splits a label into it's C{module}, C{function} and C{offset}
components, as used in L{parse_label}.
When called as a static method, the strict syntax mode is used::
winappdbg.Process.split_label( "kernel32!CreateFileA" )
When called as an instance method, the fuzzy syntax mode is used::
aProcessInstance.split_label( "CreateFileA" )
@see: L{split_label_strict}, L{split_label_fuzzy}
@type label: str
@param label: Label to split.
@rtype: tuple( str or None, str or int or None, int or None )
@return:
Tuple containing the C{module} name,
the C{function} name or ordinal, and the C{offset} value.
If the label doesn't specify a module,
then C{module} is C{None}.
If the label doesn't specify a function,
then C{function} is C{None}.
If the label doesn't specify an offset,
then C{offset} is C{0}.
@raise ValueError: The label is malformed.
"""
# XXX
# Docstring indentation was removed so epydoc doesn't complain
# when parsing the docs for __use_fuzzy_mode().
# This function is overwritten by __init__
# so here is the static implementation only.
return cls.split_label_strict(label)
# The split_label method is replaced with this function by __init__.
def __use_fuzzy_mode(self, label):
"@see: L{split_label}"
return self.split_label_fuzzy(label)
## __use_fuzzy_mode.__doc__ = split_label.__doc__
def sanitize_label(self, label):
"""
Converts a label taken from user input into a well-formed label.
@type label: str
@param label: Label taken from user input.
@rtype: str
@return: Sanitized label.
"""
(module, function, offset) = self.split_label_fuzzy(label)
label = self.parse_label(module, function, offset)
return label
def resolve_label(self, label):
"""
Resolve the memory address of the given label.
@note:
If multiple modules with the same name are loaded,
the label may be resolved at any of them. For a more precise
way to resolve functions use the base address to get the L{Module}
object (see L{Process.get_module}) and then call L{Module.resolve}.
If no module name is specified in the label, the function may be
resolved in any loaded module. If you want to resolve all functions
with that name in all processes, call L{Process.iter_modules} to
iterate through all loaded modules, and then try to resolve the
function in each one of them using L{Module.resolve}.
@type label: str
@param label: Label to resolve.
@rtype: int
@return: Memory address pointed to by the label.
@raise ValueError: The label is malformed or impossible to resolve.
@raise RuntimeError: Cannot resolve the module or function.
"""
# Split the label into module, function and offset components.
module, function, offset = self.split_label_fuzzy(label)
# Resolve the components into a memory address.
address = self.resolve_label_components(module, function, offset)
# Return the memory address.
return address
def resolve_label_components(self, module = None,
function = None,
offset = None):
"""
Resolve the memory address of the given module, function and/or offset.
@note:
If multiple modules with the same name are loaded,
the label may be resolved at any of them. For a more precise
way to resolve functions use the base address to get the L{Module}
object (see L{Process.get_module}) and then call L{Module.resolve}.
If no module name is specified in the label, the function may be
resolved in any loaded module. If you want to resolve all functions
with that name in all processes, call L{Process.iter_modules} to
iterate through all loaded modules, and then try to resolve the
function in each one of them using L{Module.resolve}.
@type module: None or str
@param module: (Optional) Module name.
@type function: None, str or int
@param function: (Optional) Function name or ordinal.
@type offset: None or int
@param offset: (Optional) Offset value.
If C{function} is specified, offset from the function.
If C{function} is C{None}, offset from the module.
@rtype: int
@return: Memory address pointed to by the label.
@raise ValueError: The label is malformed or impossible to resolve.
@raise RuntimeError: Cannot resolve the module or function.
"""
# Default address if no module or function are given.
# An offset may be added later.
address = 0
# Resolve the module.
# If the module is not found, check for the special symbol "main".
if module:
modobj = self.get_module_by_name(module)
if not modobj:
if module == "main":
modobj = self.get_main_module()
else:
raise RuntimeError("Module %r not found" % module)
# Resolve the exported function or debugging symbol.
# If all else fails, check for the special symbol "start".
if function:
address = modobj.resolve(function)
if address is None:
address = modobj.resolve_symbol(function)
if address is None:
if function == "start":
address = modobj.get_entry_point()
if address is None:
msg = "Symbol %r not found in module %s"
raise RuntimeError(msg % (function, module))
# No function, use the base address.
else:
address = modobj.get_base()
# Resolve the function in any module.
# If all else fails, check for the special symbols "main" and "start".
elif function:
for modobj in self.iter_modules():
address = modobj.resolve(function)
if address is not None:
break
if address is None:
if function == "start":
modobj = self.get_main_module()
address = modobj.get_entry_point()
elif function == "main":
modobj = self.get_main_module()
address = modobj.get_base()
else:
msg = "Function %r not found in any module" % function
raise RuntimeError(msg)
# Return the address plus the offset.
if offset:
address = address + offset
return address
def get_label_at_address(self, address, offset = None):
"""
Creates a label from the given memory address.
@warning: This method uses the name of the nearest currently loaded
module. If that module is unloaded later, the label becomes
impossible to resolve.
@type address: int
@param address: Memory address.
@type offset: None or int
@param offset: (Optional) Offset value.
@rtype: str
@return: Label pointing to the given address.
"""
if offset:
address = address + offset
modobj = self.get_module_at_address(address)
if modobj:
label = modobj.get_label_at_address(address)
else:
label = self.parse_label(None, None, address)
return label
#------------------------------------------------------------------------------
# The memory addresses of system breakpoints are be cached, since they're
# all in system libraries it's not likely they'll ever change their address
# during the lifetime of the process... I don't suppose a program could
# happily unload ntdll.dll and survive.
def __get_system_breakpoint(self, label):
try:
return self.__system_breakpoints[label]
except KeyError:
try:
address = self.resolve_label(label)
except Exception:
return None
self.__system_breakpoints[label] = address
return address
# It's in kernel32 in Windows Server 2003, in ntdll since Windows Vista.
# It can only be resolved if we have the debug symbols.
def get_break_on_error_ptr(self):
"""
@rtype: int
@return:
If present, returns the address of the C{g_dwLastErrorToBreakOn}
global variable for this process. If not, returns C{None}.
"""
address = self.__get_system_breakpoint("ntdll!g_dwLastErrorToBreakOn")
if not address:
address = self.__get_system_breakpoint(
"kernel32!g_dwLastErrorToBreakOn")
# cheat a little :)
self.__system_breakpoints["ntdll!g_dwLastErrorToBreakOn"] = address
return address
def is_system_defined_breakpoint(self, address):
"""
@type address: int
@param address: Memory address.
@rtype: bool
@return: C{True} if the given address points to a system defined
breakpoint. System defined breakpoints are hardcoded into
system libraries.
"""
if address:
module = self.get_module_at_address(address)
if module:
return module.match_name("ntdll") or \
module.match_name("kernel32")
return False
# FIXME
# In Wine, the system breakpoint seems to be somewhere in kernel32.
def get_system_breakpoint(self):
"""
@rtype: int or None
@return: Memory address of the system breakpoint
within the process address space.
Returns C{None} on error.
"""
return self.__get_system_breakpoint("ntdll!DbgBreakPoint")
# I don't know when this breakpoint is actually used...
def get_user_breakpoint(self):
"""
@rtype: int or None
@return: Memory address of the user breakpoint
within the process address space.
Returns C{None} on error.
"""
return self.__get_system_breakpoint("ntdll!DbgUserBreakPoint")
# On some platforms, this breakpoint can only be resolved
# when the debugging symbols for ntdll.dll are loaded.
def get_breakin_breakpoint(self):
"""
@rtype: int or None
@return: Memory address of the remote breakin breakpoint
within the process address space.
Returns C{None} on error.
"""
return self.__get_system_breakpoint("ntdll!DbgUiRemoteBreakin")
# Equivalent of ntdll!DbgBreakPoint in Wow64.
def get_wow64_system_breakpoint(self):
"""
@rtype: int or None
@return: Memory address of the Wow64 system breakpoint
within the process address space.
Returns C{None} on error.
"""
return self.__get_system_breakpoint("ntdll32!DbgBreakPoint")
# Equivalent of ntdll!DbgUserBreakPoint in Wow64.
def get_wow64_user_breakpoint(self):
"""
@rtype: int or None
@return: Memory address of the Wow64 user breakpoint
within the process address space.
Returns C{None} on error.
"""
return self.__get_system_breakpoint("ntdll32!DbgUserBreakPoint")
# Equivalent of ntdll!DbgUiRemoteBreakin in Wow64.
def get_wow64_breakin_breakpoint(self):
"""
@rtype: int or None
@return: Memory address of the Wow64 remote breakin breakpoint
within the process address space.
Returns C{None} on error.
"""
return self.__get_system_breakpoint("ntdll32!DbgUiRemoteBreakin")
#------------------------------------------------------------------------------
def load_symbols(self):
"""
Loads the debugging symbols for all modules in this snapshot.
Automatically called by L{get_symbols}.
"""
for aModule in self.iter_modules():
aModule.load_symbols()
def unload_symbols(self):
"""
Unloads the debugging symbols for all modules in this snapshot.
"""
for aModule in self.iter_modules():
aModule.unload_symbols()
def get_symbols(self):
"""
Returns the debugging symbols for all modules in this snapshot.
The symbols are automatically loaded when needed.
@rtype: list of tuple( str, int, int )
@return: List of symbols.
Each symbol is represented by a tuple that contains:
- Symbol name
- Symbol memory address
- Symbol size in bytes
"""
symbols = list()
for aModule in self.iter_modules():
for symbol in aModule.iter_symbols():
symbols.append(symbol)
return symbols
def iter_symbols(self):
"""
Returns an iterator for the debugging symbols in all modules in this
snapshot, in no particular order.
The symbols are automatically loaded when needed.
@rtype: iterator of tuple( str, int, int )
@return: Iterator of symbols.
Each symbol is represented by a tuple that contains:
- Symbol name
- Symbol memory address
- Symbol size in bytes
"""
for aModule in self.iter_modules():
for symbol in aModule.iter_symbols():
yield symbol
def resolve_symbol(self, symbol, bCaseSensitive = False):
"""
Resolves a debugging symbol's address.
@type symbol: str
@param symbol: Name of the symbol to resolve.
@type bCaseSensitive: bool
@param bCaseSensitive: C{True} for case sensitive matches,
C{False} for case insensitive.
@rtype: int or None
@return: Memory address of symbol. C{None} if not found.
"""
if bCaseSensitive:
for (SymbolName, SymbolAddress, SymbolSize) in self.iter_symbols():
if symbol == SymbolName:
return SymbolAddress
else:
symbol = symbol.lower()
for (SymbolName, SymbolAddress, SymbolSize) in self.iter_symbols():
if symbol == SymbolName.lower():
return SymbolAddress
def get_symbol_at_address(self, address):
"""
Tries to find the closest matching symbol for the given address.
@type address: int
@param address: Memory address to query.
@rtype: None or tuple( str, int, int )
@return: Returns a tuple consisting of:
- Name
- Address
- Size (in bytes)
Returns C{None} if no symbol could be matched.
"""
# Any module may have symbols pointing anywhere in memory, so there's
# no easy way to optimize this. I guess we're stuck with brute force.
found = None
for (SymbolName, SymbolAddress, SymbolSize) in self.iter_symbols():
if SymbolAddress > address:
continue
if SymbolAddress == address:
found = (SymbolName, SymbolAddress, SymbolSize)
break
if SymbolAddress < address:
if found and (address - found[1]) < (address - SymbolAddress):
continue
else:
found = (SymbolName, SymbolAddress, SymbolSize)
return found
#------------------------------------------------------------------------------
# XXX _notify_* methods should not trigger a scan
def _add_module(self, aModule):
"""
Private method to add a module object to the snapshot.
@type aModule: L{Module}
@param aModule: Module object.
"""
## if not isinstance(aModule, Module):
## if hasattr(aModule, '__class__'):
## typename = aModule.__class__.__name__
## else:
## typename = str(type(aModule))
## msg = "Expected Module, got %s instead" % typename
## raise TypeError(msg)
lpBaseOfDll = aModule.get_base()
## if lpBaseOfDll in self.__moduleDict:
## msg = "Module already exists: %d" % lpBaseOfDll
## raise KeyError(msg)
aModule.set_process(self)
self.__moduleDict[lpBaseOfDll] = aModule
def _del_module(self, lpBaseOfDll):
"""
Private method to remove a module object from the snapshot.
@type lpBaseOfDll: int
@param lpBaseOfDll: Module base address.
"""
try:
aModule = self.__moduleDict[lpBaseOfDll]
del self.__moduleDict[lpBaseOfDll]
except KeyError:
aModule = None
msg = "Unknown base address %d" % HexDump.address(lpBaseOfDll)
warnings.warn(msg, RuntimeWarning)
if aModule:
aModule.clear() # remove circular references
def __add_loaded_module(self, event):
"""
Private method to automatically add new module objects from debug events.
@type event: L{Event}
@param event: Event object.
"""
lpBaseOfDll = event.get_module_base()
hFile = event.get_file_handle()
## if not self.has_module(lpBaseOfDll): # XXX this would trigger a scan
if lpBaseOfDll not in self.__moduleDict:
fileName = event.get_filename()
if not fileName:
fileName = None
if hasattr(event, 'get_start_address'):
EntryPoint = event.get_start_address()
else:
EntryPoint = None
aModule = Module(lpBaseOfDll, hFile, fileName = fileName,
EntryPoint = EntryPoint,
process = self)
self._add_module(aModule)
else:
aModule = self.get_module(lpBaseOfDll)
if not aModule.hFile and hFile not in (None, 0,
win32.INVALID_HANDLE_VALUE):
aModule.hFile = hFile
if not aModule.process:
aModule.process = self
if aModule.EntryPoint is None and \
hasattr(event, 'get_start_address'):
aModule.EntryPoint = event.get_start_address()
if not aModule.fileName:
fileName = event.get_filename()
if fileName:
aModule.fileName = fileName
def _notify_create_process(self, event):
"""
Notify the load of the main module.
This is done automatically by the L{Debug} class, you shouldn't need
to call it yourself.
@type event: L{CreateProcessEvent}
@param event: Create process event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} otherwise.
"""
self.__add_loaded_module(event)
return True
def _notify_load_dll(self, event):
"""
Notify the load of a new module.
This is done automatically by the L{Debug} class, you shouldn't need
to call it yourself.
@type event: L{LoadDLLEvent}
@param event: Load DLL event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} otherwise.
"""
self.__add_loaded_module(event)
return True
def _notify_unload_dll(self, event):
"""
Notify the release of a loaded module.
This is done automatically by the L{Debug} class, you shouldn't need
to call it yourself.
@type event: L{UnloadDLLEvent}
@param event: Unload DLL event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} otherwise.
"""
lpBaseOfDll = event.get_module_base()
## if self.has_module(lpBaseOfDll): # XXX this would trigger a scan
if lpBaseOfDll in self.__moduleDict:
self._del_module(lpBaseOfDll)
return True
| 70,615 | Python | 34.010411 | 81 | 0.54783 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/breakpoint.py | #!~/.wine/drive_c/Python25/python.exe
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Breakpoints.
@group Breakpoints:
Breakpoint, CodeBreakpoint, PageBreakpoint, HardwareBreakpoint,
BufferWatch, Hook, ApiHook
@group Warnings:
BreakpointWarning, BreakpointCallbackWarning
"""
__revision__ = "$Id$"
__all__ = [
# Base class for breakpoints
'Breakpoint',
# Breakpoint implementations
'CodeBreakpoint',
'PageBreakpoint',
'HardwareBreakpoint',
# Hooks and watches
'Hook',
'ApiHook',
'BufferWatch',
# Warnings
'BreakpointWarning',
'BreakpointCallbackWarning',
]
from winappdbg import win32
from winappdbg import compat
import sys
from winappdbg.process import Process, Thread
from winappdbg.util import DebugRegister, MemoryAddresses
from winappdbg.textio import HexDump
import ctypes
import warnings
import traceback
#==============================================================================
class BreakpointWarning (UserWarning):
"""
This warning is issued when a non-fatal error occurs that's related to
breakpoints.
"""
class BreakpointCallbackWarning (RuntimeWarning):
"""
This warning is issued when an uncaught exception was raised by a
breakpoint's user-defined callback.
"""
#==============================================================================
class Breakpoint (object):
"""
Base class for breakpoints.
Here's the breakpoints state machine.
@see: L{CodeBreakpoint}, L{PageBreakpoint}, L{HardwareBreakpoint}
@group Breakpoint states:
DISABLED, ENABLED, ONESHOT, RUNNING
@group State machine:
hit, disable, enable, one_shot, running,
is_disabled, is_enabled, is_one_shot, is_running,
get_state, get_state_name
@group Information:
get_address, get_size, get_span, is_here
@group Conditional breakpoints:
is_conditional, is_unconditional,
get_condition, set_condition, eval_condition
@group Automatic breakpoints:
is_automatic, is_interactive,
get_action, set_action, run_action
@cvar DISABLED: I{Disabled} S{->} Enabled, OneShot
@cvar ENABLED: I{Enabled} S{->} I{Running}, Disabled
@cvar ONESHOT: I{OneShot} S{->} I{Disabled}
@cvar RUNNING: I{Running} S{->} I{Enabled}, Disabled
@type DISABLED: int
@type ENABLED: int
@type ONESHOT: int
@type RUNNING: int
@type stateNames: dict E{lb} int S{->} str E{rb}
@cvar stateNames: User-friendly names for each breakpoint state.
@type typeName: str
@cvar typeName: User friendly breakpoint type string.
"""
# I don't think transitions Enabled <-> OneShot should be allowed... plus
# it would require special handling to avoid setting the same bp twice
DISABLED = 0
ENABLED = 1
ONESHOT = 2
RUNNING = 3
typeName = 'breakpoint'
stateNames = {
DISABLED : 'disabled',
ENABLED : 'enabled',
ONESHOT : 'one shot',
RUNNING : 'running',
}
def __init__(self, address, size = 1, condition = True, action = None):
"""
Breakpoint object.
@type address: int
@param address: Memory address for breakpoint.
@type size: int
@param size: Size of breakpoint in bytes (defaults to 1).
@type condition: function
@param condition: (Optional) Condition callback function.
The callback signature is::
def condition_callback(event):
return True # returns True or False
Where B{event} is an L{Event} object,
and the return value is a boolean
(C{True} to dispatch the event, C{False} otherwise).
@type action: function
@param action: (Optional) Action callback function.
If specified, the event is handled by this callback instead of
being dispatched normally.
The callback signature is::
def action_callback(event):
pass # no return value
Where B{event} is an L{Event} object.
"""
self.__address = address
self.__size = size
self.__state = self.DISABLED
self.set_condition(condition)
self.set_action(action)
def __repr__(self):
if self.is_disabled():
state = 'Disabled'
else:
state = 'Active (%s)' % self.get_state_name()
if self.is_conditional():
condition = 'conditional'
else:
condition = 'unconditional'
name = self.typeName
size = self.get_size()
if size == 1:
address = HexDump.address( self.get_address() )
else:
begin = self.get_address()
end = begin + size
begin = HexDump.address(begin)
end = HexDump.address(end)
address = "range %s-%s" % (begin, end)
msg = "<%s %s %s at remote address %s>"
msg = msg % (state, condition, name, address)
return msg
#------------------------------------------------------------------------------
def is_disabled(self):
"""
@rtype: bool
@return: C{True} if the breakpoint is in L{DISABLED} state.
"""
return self.get_state() == self.DISABLED
def is_enabled(self):
"""
@rtype: bool
@return: C{True} if the breakpoint is in L{ENABLED} state.
"""
return self.get_state() == self.ENABLED
def is_one_shot(self):
"""
@rtype: bool
@return: C{True} if the breakpoint is in L{ONESHOT} state.
"""
return self.get_state() == self.ONESHOT
def is_running(self):
"""
@rtype: bool
@return: C{True} if the breakpoint is in L{RUNNING} state.
"""
return self.get_state() == self.RUNNING
def is_here(self, address):
"""
@rtype: bool
@return: C{True} if the address is within the range of the breakpoint.
"""
begin = self.get_address()
end = begin + self.get_size()
return begin <= address < end
def get_address(self):
"""
@rtype: int
@return: The target memory address for the breakpoint.
"""
return self.__address
def get_size(self):
"""
@rtype: int
@return: The size in bytes of the breakpoint.
"""
return self.__size
def get_span(self):
"""
@rtype: tuple( int, int )
@return:
Starting and ending address of the memory range
covered by the breakpoint.
"""
address = self.get_address()
size = self.get_size()
return ( address, address + size )
def get_state(self):
"""
@rtype: int
@return: The current state of the breakpoint
(L{DISABLED}, L{ENABLED}, L{ONESHOT}, L{RUNNING}).
"""
return self.__state
def get_state_name(self):
"""
@rtype: str
@return: The name of the current state of the breakpoint.
"""
return self.stateNames[ self.get_state() ]
#------------------------------------------------------------------------------
def is_conditional(self):
"""
@see: L{__init__}
@rtype: bool
@return: C{True} if the breakpoint has a condition callback defined.
"""
# Do not evaluate as boolean! Test for identity with True instead.
return self.__condition is not True
def is_unconditional(self):
"""
@rtype: bool
@return: C{True} if the breakpoint doesn't have a condition callback defined.
"""
# Do not evaluate as boolean! Test for identity with True instead.
return self.__condition is True
def get_condition(self):
"""
@rtype: bool, function
@return: Returns the condition callback for conditional breakpoints.
Returns C{True} for unconditional breakpoints.
"""
return self.__condition
def set_condition(self, condition = True):
"""
Sets a new condition callback for the breakpoint.
@see: L{__init__}
@type condition: function
@param condition: (Optional) Condition callback function.
"""
if condition is None:
self.__condition = True
else:
self.__condition = condition
def eval_condition(self, event):
"""
Evaluates the breakpoint condition, if any was set.
@type event: L{Event}
@param event: Debug event triggered by the breakpoint.
@rtype: bool
@return: C{True} to dispatch the event, C{False} otherwise.
"""
condition = self.get_condition()
if condition is True: # shortcut for unconditional breakpoints
return True
if callable(condition):
try:
return bool( condition(event) )
except Exception:
e = sys.exc_info()[1]
msg = ("Breakpoint condition callback %r"
" raised an exception: %s")
msg = msg % (condition, traceback.format_exc(e))
warnings.warn(msg, BreakpointCallbackWarning)
return False
return bool( condition ) # force evaluation now
#------------------------------------------------------------------------------
def is_automatic(self):
"""
@rtype: bool
@return: C{True} if the breakpoint has an action callback defined.
"""
return self.__action is not None
def is_interactive(self):
"""
@rtype: bool
@return:
C{True} if the breakpoint doesn't have an action callback defined.
"""
return self.__action is None
def get_action(self):
"""
@rtype: bool, function
@return: Returns the action callback for automatic breakpoints.
Returns C{None} for interactive breakpoints.
"""
return self.__action
def set_action(self, action = None):
"""
Sets a new action callback for the breakpoint.
@type action: function
@param action: (Optional) Action callback function.
"""
self.__action = action
def run_action(self, event):
"""
Executes the breakpoint action callback, if any was set.
@type event: L{Event}
@param event: Debug event triggered by the breakpoint.
"""
action = self.get_action()
if action is not None:
try:
return bool( action(event) )
except Exception:
e = sys.exc_info()[1]
msg = ("Breakpoint action callback %r"
" raised an exception: %s")
msg = msg % (action, traceback.format_exc(e))
warnings.warn(msg, BreakpointCallbackWarning)
return False
return True
#------------------------------------------------------------------------------
def __bad_transition(self, state):
"""
Raises an C{AssertionError} exception for an invalid state transition.
@see: L{stateNames}
@type state: int
@param state: Intended breakpoint state.
@raise Exception: Always.
"""
statemsg = ""
oldState = self.stateNames[ self.get_state() ]
newState = self.stateNames[ state ]
msg = "Invalid state transition (%s -> %s)" \
" for breakpoint at address %s"
msg = msg % (oldState, newState, HexDump.address(self.get_address()))
raise AssertionError(msg)
def disable(self, aProcess, aThread):
"""
Transition to L{DISABLED} state.
- When hit: OneShot S{->} Disabled
- Forced by user: Enabled, OneShot, Running S{->} Disabled
- Transition from running state may require special handling
by the breakpoint implementation class.
@type aProcess: L{Process}
@param aProcess: Process object.
@type aThread: L{Thread}
@param aThread: Thread object.
"""
## if self.__state not in (self.ENABLED, self.ONESHOT, self.RUNNING):
## self.__bad_transition(self.DISABLED)
self.__state = self.DISABLED
def enable(self, aProcess, aThread):
"""
Transition to L{ENABLED} state.
- When hit: Running S{->} Enabled
- Forced by user: Disabled, Running S{->} Enabled
- Transition from running state may require special handling
by the breakpoint implementation class.
@type aProcess: L{Process}
@param aProcess: Process object.
@type aThread: L{Thread}
@param aThread: Thread object.
"""
## if self.__state not in (self.DISABLED, self.RUNNING):
## self.__bad_transition(self.ENABLED)
self.__state = self.ENABLED
def one_shot(self, aProcess, aThread):
"""
Transition to L{ONESHOT} state.
- Forced by user: Disabled S{->} OneShot
@type aProcess: L{Process}
@param aProcess: Process object.
@type aThread: L{Thread}
@param aThread: Thread object.
"""
## if self.__state != self.DISABLED:
## self.__bad_transition(self.ONESHOT)
self.__state = self.ONESHOT
def running(self, aProcess, aThread):
"""
Transition to L{RUNNING} state.
- When hit: Enabled S{->} Running
@type aProcess: L{Process}
@param aProcess: Process object.
@type aThread: L{Thread}
@param aThread: Thread object.
"""
if self.__state != self.ENABLED:
self.__bad_transition(self.RUNNING)
self.__state = self.RUNNING
def hit(self, event):
"""
Notify a breakpoint that it's been hit.
This triggers the corresponding state transition and sets the
C{breakpoint} property of the given L{Event} object.
@see: L{disable}, L{enable}, L{one_shot}, L{running}
@type event: L{Event}
@param event: Debug event to handle (depends on the breakpoint type).
@raise AssertionError: Disabled breakpoints can't be hit.
"""
aProcess = event.get_process()
aThread = event.get_thread()
state = self.get_state()
event.breakpoint = self
if state == self.ENABLED:
self.running(aProcess, aThread)
elif state == self.RUNNING:
self.enable(aProcess, aThread)
elif state == self.ONESHOT:
self.disable(aProcess, aThread)
elif state == self.DISABLED:
# this should not happen
msg = "Hit a disabled breakpoint at address %s"
msg = msg % HexDump.address( self.get_address() )
warnings.warn(msg, BreakpointWarning)
#==============================================================================
# XXX TODO
# Check if the user is trying to set a code breakpoint on a memory mapped file,
# so we don't end up writing the int3 instruction in the file by accident.
class CodeBreakpoint (Breakpoint):
"""
Code execution breakpoints (using an int3 opcode).
@see: L{Debug.break_at}
@type bpInstruction: str
@cvar bpInstruction: Breakpoint instruction for the current processor.
"""
typeName = 'code breakpoint'
if win32.arch in (win32.ARCH_I386, win32.ARCH_AMD64):
bpInstruction = '\xCC' # int 3
def __init__(self, address, condition = True, action = None):
"""
Code breakpoint object.
@see: L{Breakpoint.__init__}
@type address: int
@param address: Memory address for breakpoint.
@type condition: function
@param condition: (Optional) Condition callback function.
@type action: function
@param action: (Optional) Action callback function.
"""
if win32.arch not in (win32.ARCH_I386, win32.ARCH_AMD64):
msg = "Code breakpoints not supported for %s" % win32.arch
raise NotImplementedError(msg)
Breakpoint.__init__(self, address, len(self.bpInstruction),
condition, action)
self.__previousValue = self.bpInstruction
def __set_bp(self, aProcess):
"""
Writes a breakpoint instruction at the target address.
@type aProcess: L{Process}
@param aProcess: Process object.
"""
address = self.get_address()
self.__previousValue = aProcess.read(address, len(self.bpInstruction))
if self.__previousValue == self.bpInstruction:
msg = "Possible overlapping code breakpoints at %s"
msg = msg % HexDump.address(address)
warnings.warn(msg, BreakpointWarning)
aProcess.write(address, self.bpInstruction)
def __clear_bp(self, aProcess):
"""
Restores the original byte at the target address.
@type aProcess: L{Process}
@param aProcess: Process object.
"""
address = self.get_address()
currentValue = aProcess.read(address, len(self.bpInstruction))
if currentValue == self.bpInstruction:
# Only restore the previous value if the int3 is still there.
aProcess.write(self.get_address(), self.__previousValue)
else:
self.__previousValue = currentValue
msg = "Overwritten code breakpoint at %s"
msg = msg % HexDump.address(address)
warnings.warn(msg, BreakpointWarning)
def disable(self, aProcess, aThread):
if not self.is_disabled() and not self.is_running():
self.__clear_bp(aProcess)
super(CodeBreakpoint, self).disable(aProcess, aThread)
def enable(self, aProcess, aThread):
if not self.is_enabled() and not self.is_one_shot():
self.__set_bp(aProcess)
super(CodeBreakpoint, self).enable(aProcess, aThread)
def one_shot(self, aProcess, aThread):
if not self.is_enabled() and not self.is_one_shot():
self.__set_bp(aProcess)
super(CodeBreakpoint, self).one_shot(aProcess, aThread)
# FIXME race condition here (however unlikely)
# If another thread runs on over the target address while
# the breakpoint is in RUNNING state, we'll miss it. There
# is a solution to this but it's somewhat complicated, so
# I'm leaving it for another version of the debugger. :(
def running(self, aProcess, aThread):
if self.is_enabled():
self.__clear_bp(aProcess)
aThread.set_tf()
super(CodeBreakpoint, self).running(aProcess, aThread)
#==============================================================================
# TODO:
# * If the original page was already a guard page, the exception should be
# passed to the debugee instead of being handled by the debugger.
# * If the original page was already a guard page, it should NOT be converted
# to a no-access page when disabling the breakpoint.
# * If the page permissions were modified after the breakpoint was enabled,
# no change should be done on them when disabling the breakpoint. For this
# we need to remember the original page permissions instead of blindly
# setting and clearing the guard page bit on them.
# * Some pages seem to be "magic" and resist all attempts at changing their
# protect bits (for example the pages where the PEB and TEB reside). Maybe
# a more descriptive error message could be shown in this case.
class PageBreakpoint (Breakpoint):
"""
Page access breakpoint (using guard pages).
@see: L{Debug.watch_buffer}
@group Information:
get_size_in_pages
"""
typeName = 'page breakpoint'
#------------------------------------------------------------------------------
def __init__(self, address, pages = 1, condition = True, action = None):
"""
Page breakpoint object.
@see: L{Breakpoint.__init__}
@type address: int
@param address: Memory address for breakpoint.
@type pages: int
@param address: Size of breakpoint in pages.
@type condition: function
@param condition: (Optional) Condition callback function.
@type action: function
@param action: (Optional) Action callback function.
"""
Breakpoint.__init__(self, address, pages * MemoryAddresses.pageSize,
condition, action)
## if (address & 0x00000FFF) != 0:
floordiv_align = long(address) // long(MemoryAddresses.pageSize)
truediv_align = float(address) / float(MemoryAddresses.pageSize)
if floordiv_align != truediv_align:
msg = "Address of page breakpoint " \
"must be aligned to a page size boundary " \
"(value %s received)" % HexDump.address(address)
raise ValueError(msg)
def get_size_in_pages(self):
"""
@rtype: int
@return: The size in pages of the breakpoint.
"""
# The size is always a multiple of the page size.
return self.get_size() // MemoryAddresses.pageSize
def __set_bp(self, aProcess):
"""
Sets the target pages as guard pages.
@type aProcess: L{Process}
@param aProcess: Process object.
"""
lpAddress = self.get_address()
dwSize = self.get_size()
flNewProtect = aProcess.mquery(lpAddress).Protect
flNewProtect = flNewProtect | win32.PAGE_GUARD
aProcess.mprotect(lpAddress, dwSize, flNewProtect)
def __clear_bp(self, aProcess):
"""
Restores the original permissions of the target pages.
@type aProcess: L{Process}
@param aProcess: Process object.
"""
lpAddress = self.get_address()
flNewProtect = aProcess.mquery(lpAddress).Protect
flNewProtect = flNewProtect & (0xFFFFFFFF ^ win32.PAGE_GUARD) # DWORD
aProcess.mprotect(lpAddress, self.get_size(), flNewProtect)
def disable(self, aProcess, aThread):
if not self.is_disabled():
self.__clear_bp(aProcess)
super(PageBreakpoint, self).disable(aProcess, aThread)
def enable(self, aProcess, aThread):
if win32.arch not in (win32.ARCH_I386, win32.ARCH_AMD64):
msg = "Only one-shot page breakpoints are supported for %s"
raise NotImplementedError(msg % win32.arch)
if not self.is_enabled() and not self.is_one_shot():
self.__set_bp(aProcess)
super(PageBreakpoint, self).enable(aProcess, aThread)
def one_shot(self, aProcess, aThread):
if not self.is_enabled() and not self.is_one_shot():
self.__set_bp(aProcess)
super(PageBreakpoint, self).one_shot(aProcess, aThread)
def running(self, aProcess, aThread):
aThread.set_tf()
super(PageBreakpoint, self).running(aProcess, aThread)
#==============================================================================
class HardwareBreakpoint (Breakpoint):
"""
Hardware breakpoint (using debug registers).
@see: L{Debug.watch_variable}
@group Information:
get_slot, get_trigger, get_watch
@group Trigger flags:
BREAK_ON_EXECUTION, BREAK_ON_WRITE, BREAK_ON_ACCESS
@group Watch size flags:
WATCH_BYTE, WATCH_WORD, WATCH_DWORD, WATCH_QWORD
@type BREAK_ON_EXECUTION: int
@cvar BREAK_ON_EXECUTION: Break on execution.
@type BREAK_ON_WRITE: int
@cvar BREAK_ON_WRITE: Break on write.
@type BREAK_ON_ACCESS: int
@cvar BREAK_ON_ACCESS: Break on read or write.
@type WATCH_BYTE: int
@cvar WATCH_BYTE: Watch a byte.
@type WATCH_WORD: int
@cvar WATCH_WORD: Watch a word (2 bytes).
@type WATCH_DWORD: int
@cvar WATCH_DWORD: Watch a double word (4 bytes).
@type WATCH_QWORD: int
@cvar WATCH_QWORD: Watch one quad word (8 bytes).
@type validTriggers: tuple
@cvar validTriggers: Valid trigger flag values.
@type validWatchSizes: tuple
@cvar validWatchSizes: Valid watch flag values.
"""
typeName = 'hardware breakpoint'
BREAK_ON_EXECUTION = DebugRegister.BREAK_ON_EXECUTION
BREAK_ON_WRITE = DebugRegister.BREAK_ON_WRITE
BREAK_ON_ACCESS = DebugRegister.BREAK_ON_ACCESS
WATCH_BYTE = DebugRegister.WATCH_BYTE
WATCH_WORD = DebugRegister.WATCH_WORD
WATCH_DWORD = DebugRegister.WATCH_DWORD
WATCH_QWORD = DebugRegister.WATCH_QWORD
validTriggers = (
BREAK_ON_EXECUTION,
BREAK_ON_WRITE,
BREAK_ON_ACCESS,
)
validWatchSizes = (
WATCH_BYTE,
WATCH_WORD,
WATCH_DWORD,
WATCH_QWORD,
)
def __init__(self, address, triggerFlag = BREAK_ON_ACCESS,
sizeFlag = WATCH_DWORD,
condition = True,
action = None):
"""
Hardware breakpoint object.
@see: L{Breakpoint.__init__}
@type address: int
@param address: Memory address for breakpoint.
@type triggerFlag: int
@param triggerFlag: Trigger of breakpoint. Must be one of the following:
- L{BREAK_ON_EXECUTION}
Break on code execution.
- L{BREAK_ON_WRITE}
Break on memory read or write.
- L{BREAK_ON_ACCESS}
Break on memory write.
@type sizeFlag: int
@param sizeFlag: Size of breakpoint. Must be one of the following:
- L{WATCH_BYTE}
One (1) byte in size.
- L{WATCH_WORD}
Two (2) bytes in size.
- L{WATCH_DWORD}
Four (4) bytes in size.
- L{WATCH_QWORD}
Eight (8) bytes in size.
@type condition: function
@param condition: (Optional) Condition callback function.
@type action: function
@param action: (Optional) Action callback function.
"""
if win32.arch not in (win32.ARCH_I386, win32.ARCH_AMD64):
msg = "Hardware breakpoints not supported for %s" % win32.arch
raise NotImplementedError(msg)
if sizeFlag == self.WATCH_BYTE:
size = 1
elif sizeFlag == self.WATCH_WORD:
size = 2
elif sizeFlag == self.WATCH_DWORD:
size = 4
elif sizeFlag == self.WATCH_QWORD:
size = 8
else:
msg = "Invalid size flag for hardware breakpoint (%s)"
msg = msg % repr(sizeFlag)
raise ValueError(msg)
if triggerFlag not in self.validTriggers:
msg = "Invalid trigger flag for hardware breakpoint (%s)"
msg = msg % repr(triggerFlag)
raise ValueError(msg)
Breakpoint.__init__(self, address, size, condition, action)
self.__trigger = triggerFlag
self.__watch = sizeFlag
self.__slot = None
def __clear_bp(self, aThread):
"""
Clears this breakpoint from the debug registers.
@type aThread: L{Thread}
@param aThread: Thread object.
"""
if self.__slot is not None:
aThread.suspend()
try:
ctx = aThread.get_context(win32.CONTEXT_DEBUG_REGISTERS)
DebugRegister.clear_bp(ctx, self.__slot)
aThread.set_context(ctx)
self.__slot = None
finally:
aThread.resume()
def __set_bp(self, aThread):
"""
Sets this breakpoint in the debug registers.
@type aThread: L{Thread}
@param aThread: Thread object.
"""
if self.__slot is None:
aThread.suspend()
try:
ctx = aThread.get_context(win32.CONTEXT_DEBUG_REGISTERS)
self.__slot = DebugRegister.find_slot(ctx)
if self.__slot is None:
msg = "No available hardware breakpoint slots for thread ID %d"
msg = msg % aThread.get_tid()
raise RuntimeError(msg)
DebugRegister.set_bp(ctx, self.__slot, self.get_address(),
self.__trigger, self.__watch)
aThread.set_context(ctx)
finally:
aThread.resume()
def get_slot(self):
"""
@rtype: int
@return: The debug register number used by this breakpoint,
or C{None} if the breakpoint is not active.
"""
return self.__slot
def get_trigger(self):
"""
@see: L{validTriggers}
@rtype: int
@return: The breakpoint trigger flag.
"""
return self.__trigger
def get_watch(self):
"""
@see: L{validWatchSizes}
@rtype: int
@return: The breakpoint watch flag.
"""
return self.__watch
def disable(self, aProcess, aThread):
if not self.is_disabled():
self.__clear_bp(aThread)
super(HardwareBreakpoint, self).disable(aProcess, aThread)
def enable(self, aProcess, aThread):
if not self.is_enabled() and not self.is_one_shot():
self.__set_bp(aThread)
super(HardwareBreakpoint, self).enable(aProcess, aThread)
def one_shot(self, aProcess, aThread):
if not self.is_enabled() and not self.is_one_shot():
self.__set_bp(aThread)
super(HardwareBreakpoint, self).one_shot(aProcess, aThread)
def running(self, aProcess, aThread):
self.__clear_bp(aThread)
super(HardwareBreakpoint, self).running(aProcess, aThread)
aThread.set_tf()
#==============================================================================
# XXX FIXME
#
# The implementation of function hooks is very simple. A breakpoint is set at
# the entry point. Each time it's hit the "pre" callback is executed. If a
# "post" callback was defined, a one-shot breakpoint is set at the return
# address - and when that breakpoint hits, the "post" callback is executed.
#
# Functions hooks, as they are implemented now, don't work correctly for
# recursive functions. The problem is we don't know when to remove the
# breakpoint at the return address. Also there could be more than one return
# address.
#
# One possible solution would involve a dictionary of lists, where the key
# would be the thread ID and the value a stack of return addresses. But we
# still don't know what to do if the "wrong" return address is hit for some
# reason (maybe check the stack pointer?). Or if both a code and a hardware
# breakpoint are hit simultaneously.
#
# For now, the workaround for the user is to set only the "pre" callback for
# functions that are known to be recursive.
#
# If an exception is thrown by a hooked function and caught by one of it's
# parent functions, the "post" callback won't be called and weird stuff may
# happen. A possible solution is to put a breakpoint in the system call that
# unwinds the stack, to detect this case and remove the "post" breakpoint.
#
# Hooks may also behave oddly if the return address is overwritten by a buffer
# overflow bug (this is similar to the exception problem). But it's probably a
# minor issue since when you're fuzzing a function for overflows you're usually
# not interested in the return value anyway.
# TODO: an API to modify the hooked function's arguments
class Hook (object):
"""
Factory class to produce hook objects. Used by L{Debug.hook_function} and
L{Debug.stalk_function}.
When you try to instance this class, one of the architecture specific
implementations is returned instead.
Instances act as an action callback for code breakpoints set at the
beginning of a function. It automatically retrieves the parameters from
the stack, sets a breakpoint at the return address and retrieves the
return value from the function call.
@see: L{_Hook_i386}, L{_Hook_amd64}
@type useHardwareBreakpoints: bool
@cvar useHardwareBreakpoints: C{True} to try to use hardware breakpoints,
C{False} otherwise.
"""
# This is a factory class that returns
# the architecture specific implementation.
def __new__(cls, *argv, **argd):
try:
arch = argd['arch']
del argd['arch']
except KeyError:
try:
arch = argv[4]
argv = argv[:4] + argv[5:]
except IndexError:
raise TypeError("Missing 'arch' argument!")
if arch is None:
arch = win32.arch
if arch == win32.ARCH_I386:
return _Hook_i386(*argv, **argd)
if arch == win32.ARCH_AMD64:
return _Hook_amd64(*argv, **argd)
return object.__new__(cls, *argv, **argd)
# XXX FIXME
#
# Hardware breakpoints don't work correctly (or al all) in old VirtualBox
# versions (3.0 and below).
#
# Maybe there should be a way to autodetect the buggy VirtualBox versions
# and tell Hook objects not to use hardware breakpoints?
#
# For now the workaround is to manually set this variable to True when
# WinAppDbg is installed on a physical machine.
#
useHardwareBreakpoints = False
def __init__(self, preCB = None, postCB = None,
paramCount = None, signature = None,
arch = None):
"""
@type preCB: function
@param preCB: (Optional) Callback triggered on function entry.
The signature for the callback should be something like this::
def pre_LoadLibraryEx(event, ra, lpFilename, hFile, dwFlags):
# return address
ra = params[0]
# function arguments start from here...
szFilename = event.get_process().peek_string(lpFilename)
# (...)
Note that all pointer types are treated like void pointers, so your
callback won't get the string or structure pointed to by it, but
the remote memory address instead. This is so to prevent the ctypes
library from being "too helpful" and trying to dereference the
pointer. To get the actual data being pointed to, use one of the
L{Process.read} methods.
@type postCB: function
@param postCB: (Optional) Callback triggered on function exit.
The signature for the callback should be something like this::
def post_LoadLibraryEx(event, return_value):
# (...)
@type paramCount: int
@param paramCount:
(Optional) Number of parameters for the C{preCB} callback,
not counting the return address. Parameters are read from
the stack and assumed to be DWORDs in 32 bits and QWORDs in 64.
This is a faster way to pull stack parameters in 32 bits, but in 64
bits (or with some odd APIs in 32 bits) it won't be useful, since
not all arguments to the hooked function will be of the same size.
For a more reliable and cross-platform way of hooking use the
C{signature} argument instead.
@type signature: tuple
@param signature:
(Optional) Tuple of C{ctypes} data types that constitute the
hooked function signature. When the function is called, this will
be used to parse the arguments from the stack. Overrides the
C{paramCount} argument.
@type arch: str
@param arch: (Optional) Target architecture. Defaults to the current
architecture. See: L{win32.arch}
"""
self.__preCB = preCB
self.__postCB = postCB
self.__paramStack = dict() # tid -> list of tuple( arg, arg, arg... )
self._paramCount = paramCount
if win32.arch != win32.ARCH_I386:
self.useHardwareBreakpoints = False
if win32.bits == 64 and paramCount and not signature:
signature = (win32.QWORD,) * paramCount
if signature:
self._signature = self._calc_signature(signature)
else:
self._signature = None
def _cast_signature_pointers_to_void(self, signature):
c_void_p = ctypes.c_void_p
c_char_p = ctypes.c_char_p
c_wchar_p = ctypes.c_wchar_p
_Pointer = ctypes._Pointer
cast = ctypes.cast
for i in compat.xrange(len(signature)):
t = signature[i]
if t is not c_void_p and (issubclass(t, _Pointer) \
or t in [c_char_p, c_wchar_p]):
signature[i] = cast(t, c_void_p)
def _calc_signature(self, signature):
raise NotImplementedError(
"Hook signatures are not supported for architecture: %s" \
% win32.arch)
def _get_return_address(self, aProcess, aThread):
return None
def _get_function_arguments(self, aProcess, aThread):
if self._signature or self._paramCount:
raise NotImplementedError(
"Hook signatures are not supported for architecture: %s" \
% win32.arch)
return ()
def _get_return_value(self, aThread):
return None
# By using break_at() to set a process-wide breakpoint on the function's
# return address, we might hit a race condition when more than one thread
# is being debugged.
#
# Hardware breakpoints should be used instead. But since a thread can run
# out of those, we need to fall back to this method when needed.
def __call__(self, event):
"""
Handles the breakpoint event on entry of the function.
@type event: L{ExceptionEvent}
@param event: Breakpoint hit event.
@raise WindowsError: An error occured.
"""
debug = event.debug
dwProcessId = event.get_pid()
dwThreadId = event.get_tid()
aProcess = event.get_process()
aThread = event.get_thread()
# Get the return address and function arguments.
ra = self._get_return_address(aProcess, aThread)
params = self._get_function_arguments(aProcess, aThread)
# Keep the function arguments for later use.
self.__push_params(dwThreadId, params)
# If we need to hook the return from the function...
bHookedReturn = False
if ra is not None and self.__postCB is not None:
# Try to set a one shot hardware breakpoint at the return address.
useHardwareBreakpoints = self.useHardwareBreakpoints
if useHardwareBreakpoints:
try:
debug.define_hardware_breakpoint(
dwThreadId,
ra,
event.debug.BP_BREAK_ON_EXECUTION,
event.debug.BP_WATCH_BYTE,
True,
self.__postCallAction_hwbp
)
debug.enable_one_shot_hardware_breakpoint(dwThreadId, ra)
bHookedReturn = True
except Exception:
e = sys.exc_info()[1]
useHardwareBreakpoints = False
msg = ("Failed to set hardware breakpoint"
" at address %s for thread ID %d")
msg = msg % (HexDump.address(ra), dwThreadId)
warnings.warn(msg, BreakpointWarning)
# If not possible, set a code breakpoint instead.
if not useHardwareBreakpoints:
try:
debug.break_at(dwProcessId, ra,
self.__postCallAction_codebp)
bHookedReturn = True
except Exception:
e = sys.exc_info()[1]
msg = ("Failed to set code breakpoint"
" at address %s for process ID %d")
msg = msg % (HexDump.address(ra), dwProcessId)
warnings.warn(msg, BreakpointWarning)
# Call the "pre" callback.
try:
self.__callHandler(self.__preCB, event, ra, *params)
# If no "post" callback is defined, forget the function arguments.
finally:
if not bHookedReturn:
self.__pop_params(dwThreadId)
def __postCallAction_hwbp(self, event):
"""
Handles hardware breakpoint events on return from the function.
@type event: L{ExceptionEvent}
@param event: Single step event.
"""
# Remove the one shot hardware breakpoint
# at the return address location in the stack.
tid = event.get_tid()
address = event.breakpoint.get_address()
event.debug.erase_hardware_breakpoint(tid, address)
# Call the "post" callback.
try:
self.__postCallAction(event)
# Forget the parameters.
finally:
self.__pop_params(tid)
def __postCallAction_codebp(self, event):
"""
Handles code breakpoint events on return from the function.
@type event: L{ExceptionEvent}
@param event: Breakpoint hit event.
"""
# If the breakpoint was accidentally hit by another thread,
# pass it to the debugger instead of calling the "post" callback.
#
# XXX FIXME:
# I suppose this check will fail under some weird conditions...
#
tid = event.get_tid()
if tid not in self.__paramStack:
return True
# Remove the code breakpoint at the return address.
pid = event.get_pid()
address = event.breakpoint.get_address()
event.debug.dont_break_at(pid, address)
# Call the "post" callback.
try:
self.__postCallAction(event)
# Forget the parameters.
finally:
self.__pop_params(tid)
def __postCallAction(self, event):
"""
Calls the "post" callback.
@type event: L{ExceptionEvent}
@param event: Breakpoint hit event.
"""
aThread = event.get_thread()
retval = self._get_return_value(aThread)
self.__callHandler(self.__postCB, event, retval)
def __callHandler(self, callback, event, *params):
"""
Calls a "pre" or "post" handler, if set.
@type callback: function
@param callback: Callback function to call.
@type event: L{ExceptionEvent}
@param event: Breakpoint hit event.
@type params: tuple
@param params: Parameters for the callback function.
"""
if callback is not None:
event.hook = self
callback(event, *params)
def __push_params(self, tid, params):
"""
Remembers the arguments tuple for the last call to the hooked function
from this thread.
@type tid: int
@param tid: Thread global ID.
@type params: tuple( arg, arg, arg... )
@param params: Tuple of arguments.
"""
stack = self.__paramStack.get( tid, [] )
stack.append(params)
self.__paramStack[tid] = stack
def __pop_params(self, tid):
"""
Forgets the arguments tuple for the last call to the hooked function
from this thread.
@type tid: int
@param tid: Thread global ID.
"""
stack = self.__paramStack[tid]
stack.pop()
if not stack:
del self.__paramStack[tid]
def get_params(self, tid):
"""
Returns the parameters found in the stack when the hooked function
was last called by this thread.
@type tid: int
@param tid: Thread global ID.
@rtype: tuple( arg, arg, arg... )
@return: Tuple of arguments.
"""
try:
params = self.get_params_stack(tid)[-1]
except IndexError:
msg = "Hooked function called from thread %d already returned"
raise IndexError(msg % tid)
return params
def get_params_stack(self, tid):
"""
Returns the parameters found in the stack each time the hooked function
was called by this thread and hasn't returned yet.
@type tid: int
@param tid: Thread global ID.
@rtype: list of tuple( arg, arg, arg... )
@return: List of argument tuples.
"""
try:
stack = self.__paramStack[tid]
except KeyError:
msg = "Hooked function was not called from thread %d"
raise KeyError(msg % tid)
return stack
def hook(self, debug, pid, address):
"""
Installs the function hook at a given process and address.
@see: L{unhook}
@warning: Do not call from an function hook callback.
@type debug: L{Debug}
@param debug: Debug object.
@type pid: int
@param pid: Process ID.
@type address: int
@param address: Function address.
"""
return debug.break_at(pid, address, self)
def unhook(self, debug, pid, address):
"""
Removes the function hook at a given process and address.
@see: L{hook}
@warning: Do not call from an function hook callback.
@type debug: L{Debug}
@param debug: Debug object.
@type pid: int
@param pid: Process ID.
@type address: int
@param address: Function address.
"""
return debug.dont_break_at(pid, address)
class _Hook_i386 (Hook):
"""
Implementation details for L{Hook} on the L{win32.ARCH_I386} architecture.
"""
# We don't want to inherit the parent class __new__ method.
__new__ = object.__new__
def _calc_signature(self, signature):
self._cast_signature_pointers_to_void(signature)
class Arguments (ctypes.Structure):
_fields_ = [ ("arg_%s" % i, signature[i]) \
for i in compat.xrange(len(signature) - 1, -1, -1) ]
return Arguments
def _get_return_address(self, aProcess, aThread):
return aProcess.read_pointer( aThread.get_sp() )
def _get_function_arguments(self, aProcess, aThread):
if self._signature:
params = aThread.read_stack_structure(self._signature,
offset = win32.sizeof(win32.LPVOID))
elif self._paramCount:
params = aThread.read_stack_dwords(self._paramCount,
offset = win32.sizeof(win32.LPVOID))
else:
params = ()
return params
def _get_return_value(self, aThread):
ctx = aThread.get_context(win32.CONTEXT_INTEGER)
return ctx['Eax']
class _Hook_amd64 (Hook):
"""
Implementation details for L{Hook} on the L{win32.ARCH_AMD64} architecture.
"""
# We don't want to inherit the parent class __new__ method.
__new__ = object.__new__
# Make a list of floating point types.
__float_types = (
ctypes.c_double,
ctypes.c_float,
)
# Long doubles are not supported in old versions of ctypes!
try:
__float_types += (ctypes.c_longdouble,)
except AttributeError:
pass
def _calc_signature(self, signature):
self._cast_signature_pointers_to_void(signature)
float_types = self.__float_types
c_sizeof = ctypes.sizeof
reg_size = c_sizeof(ctypes.c_size_t)
reg_int_sig = []
reg_float_sig = []
stack_sig = []
for i in compat.xrange(len(signature)):
arg = signature[i]
name = "arg_%d" % i
stack_sig.insert( 0, (name, arg) )
if i < 4:
if type(arg) in float_types:
reg_float_sig.append( (name, arg) )
elif c_sizeof(arg) <= reg_size:
reg_int_sig.append( (name, arg) )
else:
msg = ("Hook signatures don't support structures"
" within the first 4 arguments of a function"
" for the %s architecture") % win32.arch
raise NotImplementedError(msg)
if reg_int_sig:
class RegisterArguments (ctypes.Structure):
_fields_ = reg_int_sig
else:
RegisterArguments = None
if reg_float_sig:
class FloatArguments (ctypes.Structure):
_fields_ = reg_float_sig
else:
FloatArguments = None
if stack_sig:
class StackArguments (ctypes.Structure):
_fields_ = stack_sig
else:
StackArguments = None
return (len(signature),
RegisterArguments,
FloatArguments,
StackArguments)
def _get_return_address(self, aProcess, aThread):
return aProcess.read_pointer( aThread.get_sp() )
def _get_function_arguments(self, aProcess, aThread):
if self._signature:
(args_count,
RegisterArguments,
FloatArguments,
StackArguments) = self._signature
arguments = {}
if StackArguments:
address = aThread.get_sp() + win32.sizeof(win32.LPVOID)
stack_struct = aProcess.read_structure(address,
StackArguments)
stack_args = dict(
[ (name, stack_struct.__getattribute__(name))
for (name, type) in stack_struct._fields_ ]
)
arguments.update(stack_args)
flags = 0
if RegisterArguments:
flags = flags | win32.CONTEXT_INTEGER
if FloatArguments:
flags = flags | win32.CONTEXT_MMX_REGISTERS
if flags:
ctx = aThread.get_context(flags)
if RegisterArguments:
buffer = (win32.QWORD * 4)(ctx['Rcx'], ctx['Rdx'],
ctx['R8'], ctx['R9'])
reg_args = self._get_arguments_from_buffer(buffer,
RegisterArguments)
arguments.update(reg_args)
if FloatArguments:
buffer = (win32.M128A * 4)(ctx['XMM0'], ctx['XMM1'],
ctx['XMM2'], ctx['XMM3'])
float_args = self._get_arguments_from_buffer(buffer,
FloatArguments)
arguments.update(float_args)
params = tuple( [ arguments["arg_%d" % i]
for i in compat.xrange(args_count) ] )
else:
params = ()
return params
def _get_arguments_from_buffer(self, buffer, structure):
b_ptr = ctypes.pointer(buffer)
v_ptr = ctypes.cast(b_ptr, ctypes.c_void_p)
s_ptr = ctypes.cast(v_ptr, ctypes.POINTER(structure))
struct = s_ptr.contents
return dict(
[ (name, struct.__getattribute__(name))
for (name, type) in struct._fields_ ]
)
def _get_return_value(self, aThread):
ctx = aThread.get_context(win32.CONTEXT_INTEGER)
return ctx['Rax']
#------------------------------------------------------------------------------
# This class acts as a factory of Hook objects, one per target process.
# Said objects are deleted by the unhook() method.
class ApiHook (object):
"""
Used by L{EventHandler}.
This class acts as an action callback for code breakpoints set at the
beginning of a function. It automatically retrieves the parameters from
the stack, sets a breakpoint at the return address and retrieves the
return value from the function call.
@see: L{EventHandler.apiHooks}
@type modName: str
@ivar modName: Module name.
@type procName: str
@ivar procName: Procedure name.
"""
def __init__(self, eventHandler, modName, procName, paramCount = None,
signature = None):
"""
@type eventHandler: L{EventHandler}
@param eventHandler: Event handler instance. This is where the hook
callbacks are to be defined (see below).
@type modName: str
@param modName: Module name.
@type procName: str
@param procName: Procedure name.
The pre and post callbacks will be deduced from it.
For example, if the procedure is "LoadLibraryEx" the callback
routines will be "pre_LoadLibraryEx" and "post_LoadLibraryEx".
The signature for the callbacks should be something like this::
def pre_LoadLibraryEx(self, event, ra, lpFilename, hFile, dwFlags):
# return address
ra = params[0]
# function arguments start from here...
szFilename = event.get_process().peek_string(lpFilename)
# (...)
def post_LoadLibraryEx(self, event, return_value):
# (...)
Note that all pointer types are treated like void pointers, so your
callback won't get the string or structure pointed to by it, but
the remote memory address instead. This is so to prevent the ctypes
library from being "too helpful" and trying to dereference the
pointer. To get the actual data being pointed to, use one of the
L{Process.read} methods.
@type paramCount: int
@param paramCount:
(Optional) Number of parameters for the C{preCB} callback,
not counting the return address. Parameters are read from
the stack and assumed to be DWORDs in 32 bits and QWORDs in 64.
This is a faster way to pull stack parameters in 32 bits, but in 64
bits (or with some odd APIs in 32 bits) it won't be useful, since
not all arguments to the hooked function will be of the same size.
For a more reliable and cross-platform way of hooking use the
C{signature} argument instead.
@type signature: tuple
@param signature:
(Optional) Tuple of C{ctypes} data types that constitute the
hooked function signature. When the function is called, this will
be used to parse the arguments from the stack. Overrides the
C{paramCount} argument.
"""
self.__modName = modName
self.__procName = procName
self.__paramCount = paramCount
self.__signature = signature
self.__preCB = getattr(eventHandler, 'pre_%s' % procName, None)
self.__postCB = getattr(eventHandler, 'post_%s' % procName, None)
self.__hook = dict()
def __call__(self, event):
"""
Handles the breakpoint event on entry of the function.
@type event: L{ExceptionEvent}
@param event: Breakpoint hit event.
@raise WindowsError: An error occured.
"""
pid = event.get_pid()
try:
hook = self.__hook[pid]
except KeyError:
hook = Hook(self.__preCB, self.__postCB,
self.__paramCount, self.__signature,
event.get_process().get_arch() )
self.__hook[pid] = hook
return hook(event)
@property
def modName(self):
return self.__modName
@property
def procName(self):
return self.__procName
def hook(self, debug, pid):
"""
Installs the API hook on a given process and module.
@warning: Do not call from an API hook callback.
@type debug: L{Debug}
@param debug: Debug object.
@type pid: int
@param pid: Process ID.
"""
label = "%s!%s" % (self.__modName, self.__procName)
try:
hook = self.__hook[pid]
except KeyError:
try:
aProcess = debug.system.get_process(pid)
except KeyError:
aProcess = Process(pid)
hook = Hook(self.__preCB, self.__postCB,
self.__paramCount, self.__signature,
aProcess.get_arch() )
self.__hook[pid] = hook
hook.hook(debug, pid, label)
def unhook(self, debug, pid):
"""
Removes the API hook from the given process and module.
@warning: Do not call from an API hook callback.
@type debug: L{Debug}
@param debug: Debug object.
@type pid: int
@param pid: Process ID.
"""
try:
hook = self.__hook[pid]
except KeyError:
return
label = "%s!%s" % (self.__modName, self.__procName)
hook.unhook(debug, pid, label)
del self.__hook[pid]
#==============================================================================
class BufferWatch (object):
"""
Returned by L{Debug.watch_buffer}.
This object uniquely references a buffer being watched, even if there are
multiple watches set on the exact memory region.
@type pid: int
@ivar pid: Process ID.
@type start: int
@ivar start: Memory address of the start of the buffer.
@type end: int
@ivar end: Memory address of the end of the buffer.
@type action: callable
@ivar action: Action callback.
@type oneshot: bool
@ivar oneshot: C{True} for one shot breakpoints, C{False} otherwise.
"""
def __init__(self, pid, start, end, action = None, oneshot = False):
self.__pid = pid
self.__start = start
self.__end = end
self.__action = action
self.__oneshot = oneshot
@property
def pid(self):
return self.__pid
@property
def start(self):
return self.__start
@property
def end(self):
return self.__end
@property
def action(self):
return self.__action
@property
def oneshot(self):
return self.__oneshot
def match(self, address):
"""
Determine if the given memory address lies within the watched buffer.
@rtype: bool
@return: C{True} if the given memory address lies within the watched
buffer, C{False} otherwise.
"""
return self.__start <= address < self.__end
#==============================================================================
class _BufferWatchCondition (object):
"""
Used by L{Debug.watch_buffer}.
This class acts as a condition callback for page breakpoints.
It emulates page breakpoints that can overlap and/or take up less
than a page's size.
"""
def __init__(self):
self.__ranges = list() # list of BufferWatch in definition order
def add(self, bw):
"""
Adds a buffer watch identifier.
@type bw: L{BufferWatch}
@param bw:
Buffer watch identifier.
"""
self.__ranges.append(bw)
def remove(self, bw):
"""
Removes a buffer watch identifier.
@type bw: L{BufferWatch}
@param bw:
Buffer watch identifier.
@raise KeyError: The buffer watch identifier was already removed.
"""
try:
self.__ranges.remove(bw)
except KeyError:
if not bw.oneshot:
raise
def remove_last_match(self, address, size):
"""
Removes the last buffer from the watch object
to match the given address and size.
@type address: int
@param address: Memory address of buffer to stop watching.
@type size: int
@param size: Size in bytes of buffer to stop watching.
@rtype: int
@return: Number of matching elements found. Only the last one to be
added is actually deleted upon calling this method.
This counter allows you to know if there are more matching elements
and how many.
"""
count = 0
start = address
end = address + size - 1
matched = None
for item in self.__ranges:
if item.match(start) and item.match(end):
matched = item
count += 1
self.__ranges.remove(matched)
return count
def count(self):
"""
@rtype: int
@return: Number of buffers being watched.
"""
return len(self.__ranges)
def __call__(self, event):
"""
Breakpoint condition callback.
This method will also call the action callbacks for each
buffer being watched.
@type event: L{ExceptionEvent}
@param event: Guard page exception event.
@rtype: bool
@return: C{True} if the address being accessed belongs
to at least one of the buffers that was being watched
and had no action callback.
"""
address = event.get_exception_information(1)
bCondition = False
for bw in self.__ranges:
bMatched = bw.match(address)
try:
action = bw.action
if bMatched and action is not None:
try:
action(event)
except Exception:
e = sys.exc_info()[1]
msg = ("Breakpoint action callback %r"
" raised an exception: %s")
msg = msg % (action, traceback.format_exc(e))
warnings.warn(msg, BreakpointCallbackWarning)
else:
bCondition = bCondition or bMatched
finally:
if bMatched and bw.oneshot:
event.debug.dont_watch_buffer(bw)
return bCondition
#==============================================================================
class _BreakpointContainer (object):
"""
Encapsulates the capability to contain Breakpoint objects.
@group Breakpoints:
break_at, watch_variable, watch_buffer, hook_function,
dont_break_at, dont_watch_variable, dont_watch_buffer,
dont_hook_function, unhook_function,
break_on_error, dont_break_on_error
@group Stalking:
stalk_at, stalk_variable, stalk_buffer, stalk_function,
dont_stalk_at, dont_stalk_variable, dont_stalk_buffer,
dont_stalk_function
@group Tracing:
is_tracing, get_traced_tids,
start_tracing, stop_tracing,
start_tracing_process, stop_tracing_process,
start_tracing_all, stop_tracing_all
@group Symbols:
resolve_label, resolve_exported_function
@group Advanced breakpoint use:
define_code_breakpoint,
define_page_breakpoint,
define_hardware_breakpoint,
has_code_breakpoint,
has_page_breakpoint,
has_hardware_breakpoint,
get_code_breakpoint,
get_page_breakpoint,
get_hardware_breakpoint,
erase_code_breakpoint,
erase_page_breakpoint,
erase_hardware_breakpoint,
enable_code_breakpoint,
enable_page_breakpoint,
enable_hardware_breakpoint,
enable_one_shot_code_breakpoint,
enable_one_shot_page_breakpoint,
enable_one_shot_hardware_breakpoint,
disable_code_breakpoint,
disable_page_breakpoint,
disable_hardware_breakpoint
@group Listing breakpoints:
get_all_breakpoints,
get_all_code_breakpoints,
get_all_page_breakpoints,
get_all_hardware_breakpoints,
get_process_breakpoints,
get_process_code_breakpoints,
get_process_page_breakpoints,
get_process_hardware_breakpoints,
get_thread_hardware_breakpoints,
get_all_deferred_code_breakpoints,
get_process_deferred_code_breakpoints
@group Batch operations on breakpoints:
enable_all_breakpoints,
enable_one_shot_all_breakpoints,
disable_all_breakpoints,
erase_all_breakpoints,
enable_process_breakpoints,
enable_one_shot_process_breakpoints,
disable_process_breakpoints,
erase_process_breakpoints
@group Breakpoint types:
BP_TYPE_ANY, BP_TYPE_CODE, BP_TYPE_PAGE, BP_TYPE_HARDWARE
@group Breakpoint states:
BP_STATE_DISABLED, BP_STATE_ENABLED, BP_STATE_ONESHOT, BP_STATE_RUNNING
@group Memory breakpoint trigger flags:
BP_BREAK_ON_EXECUTION, BP_BREAK_ON_WRITE, BP_BREAK_ON_ACCESS
@group Memory breakpoint size flags:
BP_WATCH_BYTE, BP_WATCH_WORD, BP_WATCH_DWORD, BP_WATCH_QWORD
@type BP_TYPE_ANY: int
@cvar BP_TYPE_ANY: To get all breakpoints
@type BP_TYPE_CODE: int
@cvar BP_TYPE_CODE: To get code breakpoints only
@type BP_TYPE_PAGE: int
@cvar BP_TYPE_PAGE: To get page breakpoints only
@type BP_TYPE_HARDWARE: int
@cvar BP_TYPE_HARDWARE: To get hardware breakpoints only
@type BP_STATE_DISABLED: int
@cvar BP_STATE_DISABLED: Breakpoint is disabled.
@type BP_STATE_ENABLED: int
@cvar BP_STATE_ENABLED: Breakpoint is enabled.
@type BP_STATE_ONESHOT: int
@cvar BP_STATE_ONESHOT: Breakpoint is enabled for one shot.
@type BP_STATE_RUNNING: int
@cvar BP_STATE_RUNNING: Breakpoint is running (recently hit).
@type BP_BREAK_ON_EXECUTION: int
@cvar BP_BREAK_ON_EXECUTION: Break on code execution.
@type BP_BREAK_ON_WRITE: int
@cvar BP_BREAK_ON_WRITE: Break on memory write.
@type BP_BREAK_ON_ACCESS: int
@cvar BP_BREAK_ON_ACCESS: Break on memory read or write.
"""
# Breakpoint types
BP_TYPE_ANY = 0 # to get all breakpoints
BP_TYPE_CODE = 1
BP_TYPE_PAGE = 2
BP_TYPE_HARDWARE = 3
# Breakpoint states
BP_STATE_DISABLED = Breakpoint.DISABLED
BP_STATE_ENABLED = Breakpoint.ENABLED
BP_STATE_ONESHOT = Breakpoint.ONESHOT
BP_STATE_RUNNING = Breakpoint.RUNNING
# Memory breakpoint trigger flags
BP_BREAK_ON_EXECUTION = HardwareBreakpoint.BREAK_ON_EXECUTION
BP_BREAK_ON_WRITE = HardwareBreakpoint.BREAK_ON_WRITE
BP_BREAK_ON_ACCESS = HardwareBreakpoint.BREAK_ON_ACCESS
# Memory breakpoint size flags
BP_WATCH_BYTE = HardwareBreakpoint.WATCH_BYTE
BP_WATCH_WORD = HardwareBreakpoint.WATCH_WORD
BP_WATCH_QWORD = HardwareBreakpoint.WATCH_QWORD
BP_WATCH_DWORD = HardwareBreakpoint.WATCH_DWORD
def __init__(self):
self.__codeBP = dict() # (pid, address) -> CodeBreakpoint
self.__pageBP = dict() # (pid, address) -> PageBreakpoint
self.__hardwareBP = dict() # tid -> [ HardwareBreakpoint ]
self.__runningBP = dict() # tid -> set( Breakpoint )
self.__tracing = set() # set( tid )
self.__deferredBP = dict() # pid -> label -> (action, oneshot)
#------------------------------------------------------------------------------
# This operates on the dictionary of running breakpoints.
# Since the bps are meant to stay alive no cleanup is done here.
def __get_running_bp_set(self, tid):
"Auxiliary method."
return self.__runningBP.get(tid, ())
def __add_running_bp(self, tid, bp):
"Auxiliary method."
if tid not in self.__runningBP:
self.__runningBP[tid] = set()
self.__runningBP[tid].add(bp)
def __del_running_bp(self, tid, bp):
"Auxiliary method."
self.__runningBP[tid].remove(bp)
if not self.__runningBP[tid]:
del self.__runningBP[tid]
def __del_running_bp_from_all_threads(self, bp):
"Auxiliary method."
for (tid, bpset) in compat.iteritems(self.__runningBP):
if bp in bpset:
bpset.remove(bp)
self.system.get_thread(tid).clear_tf()
#------------------------------------------------------------------------------
# This is the cleanup code. Mostly called on response to exit/unload debug
# events. If possible it shouldn't raise exceptions on runtime errors.
# The main goal here is to avoid memory or handle leaks.
def __cleanup_breakpoint(self, event, bp):
"Auxiliary method."
try:
process = event.get_process()
thread = event.get_thread()
bp.disable(process, thread) # clear the debug regs / trap flag
except Exception:
pass
bp.set_condition(True) # break possible circular reference
bp.set_action(None) # break possible circular reference
def __cleanup_thread(self, event):
"""
Auxiliary method for L{_notify_exit_thread}
and L{_notify_exit_process}.
"""
tid = event.get_tid()
# Cleanup running breakpoints
try:
for bp in self.__runningBP[tid]:
self.__cleanup_breakpoint(event, bp)
del self.__runningBP[tid]
except KeyError:
pass
# Cleanup hardware breakpoints
try:
for bp in self.__hardwareBP[tid]:
self.__cleanup_breakpoint(event, bp)
del self.__hardwareBP[tid]
except KeyError:
pass
# Cleanup set of threads being traced
if tid in self.__tracing:
self.__tracing.remove(tid)
def __cleanup_process(self, event):
"""
Auxiliary method for L{_notify_exit_process}.
"""
pid = event.get_pid()
process = event.get_process()
# Cleanup code breakpoints
for (bp_pid, bp_address) in compat.keys(self.__codeBP):
if bp_pid == pid:
bp = self.__codeBP[ (bp_pid, bp_address) ]
self.__cleanup_breakpoint(event, bp)
del self.__codeBP[ (bp_pid, bp_address) ]
# Cleanup page breakpoints
for (bp_pid, bp_address) in compat.keys(self.__pageBP):
if bp_pid == pid:
bp = self.__pageBP[ (bp_pid, bp_address) ]
self.__cleanup_breakpoint(event, bp)
del self.__pageBP[ (bp_pid, bp_address) ]
# Cleanup deferred code breakpoints
try:
del self.__deferredBP[pid]
except KeyError:
pass
def __cleanup_module(self, event):
"""
Auxiliary method for L{_notify_unload_dll}.
"""
pid = event.get_pid()
process = event.get_process()
module = event.get_module()
# Cleanup thread breakpoints on this module
for tid in process.iter_thread_ids():
thread = process.get_thread(tid)
# Running breakpoints
if tid in self.__runningBP:
bplist = list(self.__runningBP[tid])
for bp in bplist:
bp_address = bp.get_address()
if process.get_module_at_address(bp_address) == module:
self.__cleanup_breakpoint(event, bp)
self.__runningBP[tid].remove(bp)
# Hardware breakpoints
if tid in self.__hardwareBP:
bplist = list(self.__hardwareBP[tid])
for bp in bplist:
bp_address = bp.get_address()
if process.get_module_at_address(bp_address) == module:
self.__cleanup_breakpoint(event, bp)
self.__hardwareBP[tid].remove(bp)
# Cleanup code breakpoints on this module
for (bp_pid, bp_address) in compat.keys(self.__codeBP):
if bp_pid == pid:
if process.get_module_at_address(bp_address) == module:
bp = self.__codeBP[ (bp_pid, bp_address) ]
self.__cleanup_breakpoint(event, bp)
del self.__codeBP[ (bp_pid, bp_address) ]
# Cleanup page breakpoints on this module
for (bp_pid, bp_address) in compat.keys(self.__pageBP):
if bp_pid == pid:
if process.get_module_at_address(bp_address) == module:
bp = self.__pageBP[ (bp_pid, bp_address) ]
self.__cleanup_breakpoint(event, bp)
del self.__pageBP[ (bp_pid, bp_address) ]
#------------------------------------------------------------------------------
# Defining breakpoints.
# Code breakpoints.
def define_code_breakpoint(self, dwProcessId, address, condition = True,
action = None):
"""
Creates a disabled code breakpoint at the given address.
@see:
L{has_code_breakpoint},
L{get_code_breakpoint},
L{enable_code_breakpoint},
L{enable_one_shot_code_breakpoint},
L{disable_code_breakpoint},
L{erase_code_breakpoint}
@type dwProcessId: int
@param dwProcessId: Process global ID.
@type address: int
@param address: Memory address of the code instruction to break at.
@type condition: function
@param condition: (Optional) Condition callback function.
The callback signature is::
def condition_callback(event):
return True # returns True or False
Where B{event} is an L{Event} object,
and the return value is a boolean
(C{True} to dispatch the event, C{False} otherwise).
@type action: function
@param action: (Optional) Action callback function.
If specified, the event is handled by this callback instead of
being dispatched normally.
The callback signature is::
def action_callback(event):
pass # no return value
Where B{event} is an L{Event} object,
and the return value is a boolean
(C{True} to dispatch the event, C{False} otherwise).
@rtype: L{CodeBreakpoint}
@return: The code breakpoint object.
"""
process = self.system.get_process(dwProcessId)
bp = CodeBreakpoint(address, condition, action)
key = (dwProcessId, bp.get_address())
if key in self.__codeBP:
msg = "Already exists (PID %d) : %r"
raise KeyError(msg % (dwProcessId, self.__codeBP[key]))
self.__codeBP[key] = bp
return bp
# Page breakpoints.
def define_page_breakpoint(self, dwProcessId, address, pages = 1,
condition = True,
action = None):
"""
Creates a disabled page breakpoint at the given address.
@see:
L{has_page_breakpoint},
L{get_page_breakpoint},
L{enable_page_breakpoint},
L{enable_one_shot_page_breakpoint},
L{disable_page_breakpoint},
L{erase_page_breakpoint}
@type dwProcessId: int
@param dwProcessId: Process global ID.
@type address: int
@param address: Memory address of the first page to watch.
@type pages: int
@param pages: Number of pages to watch.
@type condition: function
@param condition: (Optional) Condition callback function.
The callback signature is::
def condition_callback(event):
return True # returns True or False
Where B{event} is an L{Event} object,
and the return value is a boolean
(C{True} to dispatch the event, C{False} otherwise).
@type action: function
@param action: (Optional) Action callback function.
If specified, the event is handled by this callback instead of
being dispatched normally.
The callback signature is::
def action_callback(event):
pass # no return value
Where B{event} is an L{Event} object,
and the return value is a boolean
(C{True} to dispatch the event, C{False} otherwise).
@rtype: L{PageBreakpoint}
@return: The page breakpoint object.
"""
process = self.system.get_process(dwProcessId)
bp = PageBreakpoint(address, pages, condition, action)
begin = bp.get_address()
end = begin + bp.get_size()
address = begin
pageSize = MemoryAddresses.pageSize
while address < end:
key = (dwProcessId, address)
if key in self.__pageBP:
msg = "Already exists (PID %d) : %r"
msg = msg % (dwProcessId, self.__pageBP[key])
raise KeyError(msg)
address = address + pageSize
address = begin
while address < end:
key = (dwProcessId, address)
self.__pageBP[key] = bp
address = address + pageSize
return bp
# Hardware breakpoints.
def define_hardware_breakpoint(self, dwThreadId, address,
triggerFlag = BP_BREAK_ON_ACCESS,
sizeFlag = BP_WATCH_DWORD,
condition = True,
action = None):
"""
Creates a disabled hardware breakpoint at the given address.
@see:
L{has_hardware_breakpoint},
L{get_hardware_breakpoint},
L{enable_hardware_breakpoint},
L{enable_one_shot_hardware_breakpoint},
L{disable_hardware_breakpoint},
L{erase_hardware_breakpoint}
@note:
Hardware breakpoints do not seem to work properly on VirtualBox.
See U{http://www.virtualbox.org/ticket/477}.
@type dwThreadId: int
@param dwThreadId: Thread global ID.
@type address: int
@param address: Memory address to watch.
@type triggerFlag: int
@param triggerFlag: Trigger of breakpoint. Must be one of the following:
- L{BP_BREAK_ON_EXECUTION}
Break on code execution.
- L{BP_BREAK_ON_WRITE}
Break on memory read or write.
- L{BP_BREAK_ON_ACCESS}
Break on memory write.
@type sizeFlag: int
@param sizeFlag: Size of breakpoint. Must be one of the following:
- L{BP_WATCH_BYTE}
One (1) byte in size.
- L{BP_WATCH_WORD}
Two (2) bytes in size.
- L{BP_WATCH_DWORD}
Four (4) bytes in size.
- L{BP_WATCH_QWORD}
Eight (8) bytes in size.
@type condition: function
@param condition: (Optional) Condition callback function.
The callback signature is::
def condition_callback(event):
return True # returns True or False
Where B{event} is an L{Event} object,
and the return value is a boolean
(C{True} to dispatch the event, C{False} otherwise).
@type action: function
@param action: (Optional) Action callback function.
If specified, the event is handled by this callback instead of
being dispatched normally.
The callback signature is::
def action_callback(event):
pass # no return value
Where B{event} is an L{Event} object,
and the return value is a boolean
(C{True} to dispatch the event, C{False} otherwise).
@rtype: L{HardwareBreakpoint}
@return: The hardware breakpoint object.
"""
thread = self.system.get_thread(dwThreadId)
bp = HardwareBreakpoint(address, triggerFlag, sizeFlag, condition,
action)
begin = bp.get_address()
end = begin + bp.get_size()
if dwThreadId in self.__hardwareBP:
bpSet = self.__hardwareBP[dwThreadId]
for oldbp in bpSet:
old_begin = oldbp.get_address()
old_end = old_begin + oldbp.get_size()
if MemoryAddresses.do_ranges_intersect(begin, end, old_begin,
old_end):
msg = "Already exists (TID %d) : %r" % (dwThreadId, oldbp)
raise KeyError(msg)
else:
bpSet = set()
self.__hardwareBP[dwThreadId] = bpSet
bpSet.add(bp)
return bp
#------------------------------------------------------------------------------
# Checking breakpoint definitions.
def has_code_breakpoint(self, dwProcessId, address):
"""
Checks if a code breakpoint is defined at the given address.
@see:
L{define_code_breakpoint},
L{get_code_breakpoint},
L{erase_code_breakpoint},
L{enable_code_breakpoint},
L{enable_one_shot_code_breakpoint},
L{disable_code_breakpoint}
@type dwProcessId: int
@param dwProcessId: Process global ID.
@type address: int
@param address: Memory address of breakpoint.
@rtype: bool
@return: C{True} if the breakpoint is defined, C{False} otherwise.
"""
return (dwProcessId, address) in self.__codeBP
def has_page_breakpoint(self, dwProcessId, address):
"""
Checks if a page breakpoint is defined at the given address.
@see:
L{define_page_breakpoint},
L{get_page_breakpoint},
L{erase_page_breakpoint},
L{enable_page_breakpoint},
L{enable_one_shot_page_breakpoint},
L{disable_page_breakpoint}
@type dwProcessId: int
@param dwProcessId: Process global ID.
@type address: int
@param address: Memory address of breakpoint.
@rtype: bool
@return: C{True} if the breakpoint is defined, C{False} otherwise.
"""
return (dwProcessId, address) in self.__pageBP
def has_hardware_breakpoint(self, dwThreadId, address):
"""
Checks if a hardware breakpoint is defined at the given address.
@see:
L{define_hardware_breakpoint},
L{get_hardware_breakpoint},
L{erase_hardware_breakpoint},
L{enable_hardware_breakpoint},
L{enable_one_shot_hardware_breakpoint},
L{disable_hardware_breakpoint}
@type dwThreadId: int
@param dwThreadId: Thread global ID.
@type address: int
@param address: Memory address of breakpoint.
@rtype: bool
@return: C{True} if the breakpoint is defined, C{False} otherwise.
"""
if dwThreadId in self.__hardwareBP:
bpSet = self.__hardwareBP[dwThreadId]
for bp in bpSet:
if bp.get_address() == address:
return True
return False
#------------------------------------------------------------------------------
# Getting breakpoints.
def get_code_breakpoint(self, dwProcessId, address):
"""
Returns the internally used breakpoint object,
for the code breakpoint defined at the given address.
@warning: It's usually best to call the L{Debug} methods
instead of accessing the breakpoint objects directly.
@see:
L{define_code_breakpoint},
L{has_code_breakpoint},
L{enable_code_breakpoint},
L{enable_one_shot_code_breakpoint},
L{disable_code_breakpoint},
L{erase_code_breakpoint}
@type dwProcessId: int
@param dwProcessId: Process global ID.
@type address: int
@param address: Memory address where the breakpoint is defined.
@rtype: L{CodeBreakpoint}
@return: The code breakpoint object.
"""
key = (dwProcessId, address)
if key not in self.__codeBP:
msg = "No breakpoint at process %d, address %s"
address = HexDump.address(address)
raise KeyError(msg % (dwProcessId, address))
return self.__codeBP[key]
def get_page_breakpoint(self, dwProcessId, address):
"""
Returns the internally used breakpoint object,
for the page breakpoint defined at the given address.
@warning: It's usually best to call the L{Debug} methods
instead of accessing the breakpoint objects directly.
@see:
L{define_page_breakpoint},
L{has_page_breakpoint},
L{enable_page_breakpoint},
L{enable_one_shot_page_breakpoint},
L{disable_page_breakpoint},
L{erase_page_breakpoint}
@type dwProcessId: int
@param dwProcessId: Process global ID.
@type address: int
@param address: Memory address where the breakpoint is defined.
@rtype: L{PageBreakpoint}
@return: The page breakpoint object.
"""
key = (dwProcessId, address)
if key not in self.__pageBP:
msg = "No breakpoint at process %d, address %s"
address = HexDump.addresS(address)
raise KeyError(msg % (dwProcessId, address))
return self.__pageBP[key]
def get_hardware_breakpoint(self, dwThreadId, address):
"""
Returns the internally used breakpoint object,
for the code breakpoint defined at the given address.
@warning: It's usually best to call the L{Debug} methods
instead of accessing the breakpoint objects directly.
@see:
L{define_hardware_breakpoint},
L{has_hardware_breakpoint},
L{get_code_breakpoint},
L{enable_hardware_breakpoint},
L{enable_one_shot_hardware_breakpoint},
L{disable_hardware_breakpoint},
L{erase_hardware_breakpoint}
@type dwThreadId: int
@param dwThreadId: Thread global ID.
@type address: int
@param address: Memory address where the breakpoint is defined.
@rtype: L{HardwareBreakpoint}
@return: The hardware breakpoint object.
"""
if dwThreadId not in self.__hardwareBP:
msg = "No hardware breakpoints set for thread %d"
raise KeyError(msg % dwThreadId)
for bp in self.__hardwareBP[dwThreadId]:
if bp.is_here(address):
return bp
msg = "No hardware breakpoint at thread %d, address %s"
raise KeyError(msg % (dwThreadId, HexDump.address(address)))
#------------------------------------------------------------------------------
# Enabling and disabling breakpoints.
def enable_code_breakpoint(self, dwProcessId, address):
"""
Enables the code breakpoint at the given address.
@see:
L{define_code_breakpoint},
L{has_code_breakpoint},
L{enable_one_shot_code_breakpoint},
L{disable_code_breakpoint}
L{erase_code_breakpoint},
@type dwProcessId: int
@param dwProcessId: Process global ID.
@type address: int
@param address: Memory address of breakpoint.
"""
p = self.system.get_process(dwProcessId)
bp = self.get_code_breakpoint(dwProcessId, address)
if bp.is_running():
self.__del_running_bp_from_all_threads(bp)
bp.enable(p, None) # XXX HACK thread is not used
def enable_page_breakpoint(self, dwProcessId, address):
"""
Enables the page breakpoint at the given address.
@see:
L{define_page_breakpoint},
L{has_page_breakpoint},
L{get_page_breakpoint},
L{enable_one_shot_page_breakpoint},
L{disable_page_breakpoint}
L{erase_page_breakpoint},
@type dwProcessId: int
@param dwProcessId: Process global ID.
@type address: int
@param address: Memory address of breakpoint.
"""
p = self.system.get_process(dwProcessId)
bp = self.get_page_breakpoint(dwProcessId, address)
if bp.is_running():
self.__del_running_bp_from_all_threads(bp)
bp.enable(p, None) # XXX HACK thread is not used
def enable_hardware_breakpoint(self, dwThreadId, address):
"""
Enables the hardware breakpoint at the given address.
@see:
L{define_hardware_breakpoint},
L{has_hardware_breakpoint},
L{get_hardware_breakpoint},
L{enable_one_shot_hardware_breakpoint},
L{disable_hardware_breakpoint}
L{erase_hardware_breakpoint},
@note: Do not set hardware breakpoints while processing the system
breakpoint event.
@type dwThreadId: int
@param dwThreadId: Thread global ID.
@type address: int
@param address: Memory address of breakpoint.
"""
t = self.system.get_thread(dwThreadId)
bp = self.get_hardware_breakpoint(dwThreadId, address)
if bp.is_running():
self.__del_running_bp_from_all_threads(bp)
bp.enable(None, t) # XXX HACK process is not used
def enable_one_shot_code_breakpoint(self, dwProcessId, address):
"""
Enables the code breakpoint at the given address for only one shot.
@see:
L{define_code_breakpoint},
L{has_code_breakpoint},
L{get_code_breakpoint},
L{enable_code_breakpoint},
L{disable_code_breakpoint}
L{erase_code_breakpoint},
@type dwProcessId: int
@param dwProcessId: Process global ID.
@type address: int
@param address: Memory address of breakpoint.
"""
p = self.system.get_process(dwProcessId)
bp = self.get_code_breakpoint(dwProcessId, address)
if bp.is_running():
self.__del_running_bp_from_all_threads(bp)
bp.one_shot(p, None) # XXX HACK thread is not used
def enable_one_shot_page_breakpoint(self, dwProcessId, address):
"""
Enables the page breakpoint at the given address for only one shot.
@see:
L{define_page_breakpoint},
L{has_page_breakpoint},
L{get_page_breakpoint},
L{enable_page_breakpoint},
L{disable_page_breakpoint}
L{erase_page_breakpoint},
@type dwProcessId: int
@param dwProcessId: Process global ID.
@type address: int
@param address: Memory address of breakpoint.
"""
p = self.system.get_process(dwProcessId)
bp = self.get_page_breakpoint(dwProcessId, address)
if bp.is_running():
self.__del_running_bp_from_all_threads(bp)
bp.one_shot(p, None) # XXX HACK thread is not used
def enable_one_shot_hardware_breakpoint(self, dwThreadId, address):
"""
Enables the hardware breakpoint at the given address for only one shot.
@see:
L{define_hardware_breakpoint},
L{has_hardware_breakpoint},
L{get_hardware_breakpoint},
L{enable_hardware_breakpoint},
L{disable_hardware_breakpoint}
L{erase_hardware_breakpoint},
@type dwThreadId: int
@param dwThreadId: Thread global ID.
@type address: int
@param address: Memory address of breakpoint.
"""
t = self.system.get_thread(dwThreadId)
bp = self.get_hardware_breakpoint(dwThreadId, address)
if bp.is_running():
self.__del_running_bp_from_all_threads(bp)
bp.one_shot(None, t) # XXX HACK process is not used
def disable_code_breakpoint(self, dwProcessId, address):
"""
Disables the code breakpoint at the given address.
@see:
L{define_code_breakpoint},
L{has_code_breakpoint},
L{get_code_breakpoint},
L{enable_code_breakpoint}
L{enable_one_shot_code_breakpoint},
L{erase_code_breakpoint},
@type dwProcessId: int
@param dwProcessId: Process global ID.
@type address: int
@param address: Memory address of breakpoint.
"""
p = self.system.get_process(dwProcessId)
bp = self.get_code_breakpoint(dwProcessId, address)
if bp.is_running():
self.__del_running_bp_from_all_threads(bp)
bp.disable(p, None) # XXX HACK thread is not used
def disable_page_breakpoint(self, dwProcessId, address):
"""
Disables the page breakpoint at the given address.
@see:
L{define_page_breakpoint},
L{has_page_breakpoint},
L{get_page_breakpoint},
L{enable_page_breakpoint}
L{enable_one_shot_page_breakpoint},
L{erase_page_breakpoint},
@type dwProcessId: int
@param dwProcessId: Process global ID.
@type address: int
@param address: Memory address of breakpoint.
"""
p = self.system.get_process(dwProcessId)
bp = self.get_page_breakpoint(dwProcessId, address)
if bp.is_running():
self.__del_running_bp_from_all_threads(bp)
bp.disable(p, None) # XXX HACK thread is not used
def disable_hardware_breakpoint(self, dwThreadId, address):
"""
Disables the hardware breakpoint at the given address.
@see:
L{define_hardware_breakpoint},
L{has_hardware_breakpoint},
L{get_hardware_breakpoint},
L{enable_hardware_breakpoint}
L{enable_one_shot_hardware_breakpoint},
L{erase_hardware_breakpoint},
@type dwThreadId: int
@param dwThreadId: Thread global ID.
@type address: int
@param address: Memory address of breakpoint.
"""
t = self.system.get_thread(dwThreadId)
p = t.get_process()
bp = self.get_hardware_breakpoint(dwThreadId, address)
if bp.is_running():
self.__del_running_bp(dwThreadId, bp)
bp.disable(p, t)
#------------------------------------------------------------------------------
# Undefining (erasing) breakpoints.
def erase_code_breakpoint(self, dwProcessId, address):
"""
Erases the code breakpoint at the given address.
@see:
L{define_code_breakpoint},
L{has_code_breakpoint},
L{get_code_breakpoint},
L{enable_code_breakpoint},
L{enable_one_shot_code_breakpoint},
L{disable_code_breakpoint}
@type dwProcessId: int
@param dwProcessId: Process global ID.
@type address: int
@param address: Memory address of breakpoint.
"""
bp = self.get_code_breakpoint(dwProcessId, address)
if not bp.is_disabled():
self.disable_code_breakpoint(dwProcessId, address)
del self.__codeBP[ (dwProcessId, address) ]
def erase_page_breakpoint(self, dwProcessId, address):
"""
Erases the page breakpoint at the given address.
@see:
L{define_page_breakpoint},
L{has_page_breakpoint},
L{get_page_breakpoint},
L{enable_page_breakpoint},
L{enable_one_shot_page_breakpoint},
L{disable_page_breakpoint}
@type dwProcessId: int
@param dwProcessId: Process global ID.
@type address: int
@param address: Memory address of breakpoint.
"""
bp = self.get_page_breakpoint(dwProcessId, address)
begin = bp.get_address()
end = begin + bp.get_size()
if not bp.is_disabled():
self.disable_page_breakpoint(dwProcessId, address)
address = begin
pageSize = MemoryAddresses.pageSize
while address < end:
del self.__pageBP[ (dwProcessId, address) ]
address = address + pageSize
def erase_hardware_breakpoint(self, dwThreadId, address):
"""
Erases the hardware breakpoint at the given address.
@see:
L{define_hardware_breakpoint},
L{has_hardware_breakpoint},
L{get_hardware_breakpoint},
L{enable_hardware_breakpoint},
L{enable_one_shot_hardware_breakpoint},
L{disable_hardware_breakpoint}
@type dwThreadId: int
@param dwThreadId: Thread global ID.
@type address: int
@param address: Memory address of breakpoint.
"""
bp = self.get_hardware_breakpoint(dwThreadId, address)
if not bp.is_disabled():
self.disable_hardware_breakpoint(dwThreadId, address)
bpSet = self.__hardwareBP[dwThreadId]
bpSet.remove(bp)
if not bpSet:
del self.__hardwareBP[dwThreadId]
#------------------------------------------------------------------------------
# Listing breakpoints.
def get_all_breakpoints(self):
"""
Returns all breakpoint objects as a list of tuples.
Each tuple contains:
- Process global ID to which the breakpoint applies.
- Thread global ID to which the breakpoint applies, or C{None}.
- The L{Breakpoint} object itself.
@note: If you're only interested in a specific breakpoint type, or in
breakpoints for a specific process or thread, it's probably faster
to call one of the following methods:
- L{get_all_code_breakpoints}
- L{get_all_page_breakpoints}
- L{get_all_hardware_breakpoints}
- L{get_process_code_breakpoints}
- L{get_process_page_breakpoints}
- L{get_process_hardware_breakpoints}
- L{get_thread_hardware_breakpoints}
@rtype: list of tuple( pid, tid, bp )
@return: List of all breakpoints.
"""
bplist = list()
# Get the code breakpoints.
for (pid, bp) in self.get_all_code_breakpoints():
bplist.append( (pid, None, bp) )
# Get the page breakpoints.
for (pid, bp) in self.get_all_page_breakpoints():
bplist.append( (pid, None, bp) )
# Get the hardware breakpoints.
for (tid, bp) in self.get_all_hardware_breakpoints():
pid = self.system.get_thread(tid).get_pid()
bplist.append( (pid, tid, bp) )
# Return the list of breakpoints.
return bplist
def get_all_code_breakpoints(self):
"""
@rtype: list of tuple( int, L{CodeBreakpoint} )
@return: All code breakpoints as a list of tuples (pid, bp).
"""
return [ (pid, bp) for ((pid, address), bp) in compat.iteritems(self.__codeBP) ]
def get_all_page_breakpoints(self):
"""
@rtype: list of tuple( int, L{PageBreakpoint} )
@return: All page breakpoints as a list of tuples (pid, bp).
"""
## return list( set( [ (pid, bp) for ((pid, address), bp) in compat.iteritems(self.__pageBP) ] ) )
result = set()
for ((pid, address), bp) in compat.iteritems(self.__pageBP):
result.add( (pid, bp) )
return list(result)
def get_all_hardware_breakpoints(self):
"""
@rtype: list of tuple( int, L{HardwareBreakpoint} )
@return: All hardware breakpoints as a list of tuples (tid, bp).
"""
result = list()
for (tid, bplist) in compat.iteritems(self.__hardwareBP):
for bp in bplist:
result.append( (tid, bp) )
return result
def get_process_breakpoints(self, dwProcessId):
"""
Returns all breakpoint objects for the given process as a list of tuples.
Each tuple contains:
- Process global ID to which the breakpoint applies.
- Thread global ID to which the breakpoint applies, or C{None}.
- The L{Breakpoint} object itself.
@note: If you're only interested in a specific breakpoint type, or in
breakpoints for a specific process or thread, it's probably faster
to call one of the following methods:
- L{get_all_code_breakpoints}
- L{get_all_page_breakpoints}
- L{get_all_hardware_breakpoints}
- L{get_process_code_breakpoints}
- L{get_process_page_breakpoints}
- L{get_process_hardware_breakpoints}
- L{get_thread_hardware_breakpoints}
@type dwProcessId: int
@param dwProcessId: Process global ID.
@rtype: list of tuple( pid, tid, bp )
@return: List of all breakpoints for the given process.
"""
bplist = list()
# Get the code breakpoints.
for bp in self.get_process_code_breakpoints(dwProcessId):
bplist.append( (dwProcessId, None, bp) )
# Get the page breakpoints.
for bp in self.get_process_page_breakpoints(dwProcessId):
bplist.append( (dwProcessId, None, bp) )
# Get the hardware breakpoints.
for (tid, bp) in self.get_process_hardware_breakpoints(dwProcessId):
pid = self.system.get_thread(tid).get_pid()
bplist.append( (dwProcessId, tid, bp) )
# Return the list of breakpoints.
return bplist
def get_process_code_breakpoints(self, dwProcessId):
"""
@type dwProcessId: int
@param dwProcessId: Process global ID.
@rtype: list of L{CodeBreakpoint}
@return: All code breakpoints for the given process.
"""
return [ bp for ((pid, address), bp) in compat.iteritems(self.__codeBP) \
if pid == dwProcessId ]
def get_process_page_breakpoints(self, dwProcessId):
"""
@type dwProcessId: int
@param dwProcessId: Process global ID.
@rtype: list of L{PageBreakpoint}
@return: All page breakpoints for the given process.
"""
return [ bp for ((pid, address), bp) in compat.iteritems(self.__pageBP) \
if pid == dwProcessId ]
def get_thread_hardware_breakpoints(self, dwThreadId):
"""
@see: L{get_process_hardware_breakpoints}
@type dwThreadId: int
@param dwThreadId: Thread global ID.
@rtype: list of L{HardwareBreakpoint}
@return: All hardware breakpoints for the given thread.
"""
result = list()
for (tid, bplist) in compat.iteritems(self.__hardwareBP):
if tid == dwThreadId:
for bp in bplist:
result.append(bp)
return result
def get_process_hardware_breakpoints(self, dwProcessId):
"""
@see: L{get_thread_hardware_breakpoints}
@type dwProcessId: int
@param dwProcessId: Process global ID.
@rtype: list of tuple( int, L{HardwareBreakpoint} )
@return: All hardware breakpoints for each thread in the given process
as a list of tuples (tid, bp).
"""
result = list()
aProcess = self.system.get_process(dwProcessId)
for dwThreadId in aProcess.iter_thread_ids():
if dwThreadId in self.__hardwareBP:
bplist = self.__hardwareBP[dwThreadId]
for bp in bplist:
result.append( (dwThreadId, bp) )
return result
## def get_all_hooks(self):
## """
## @see: L{get_process_hooks}
##
## @rtype: list of tuple( int, int, L{Hook} )
## @return: All defined hooks as a list of tuples (pid, address, hook).
## """
## return [ (pid, address, hook) \
## for ((pid, address), hook) in self.__hook_objects ]
##
## def get_process_hooks(self, dwProcessId):
## """
## @see: L{get_all_hooks}
##
## @type dwProcessId: int
## @param dwProcessId: Process global ID.
##
## @rtype: list of tuple( int, int, L{Hook} )
## @return: All hooks for the given process as a list of tuples
## (pid, address, hook).
## """
## return [ (pid, address, hook) \
## for ((pid, address), hook) in self.__hook_objects \
## if pid == dwProcessId ]
#------------------------------------------------------------------------------
# Batch operations on all breakpoints.
def enable_all_breakpoints(self):
"""
Enables all disabled breakpoints in all processes.
@see:
enable_code_breakpoint,
enable_page_breakpoint,
enable_hardware_breakpoint
"""
# disable code breakpoints
for (pid, bp) in self.get_all_code_breakpoints():
if bp.is_disabled():
self.enable_code_breakpoint(pid, bp.get_address())
# disable page breakpoints
for (pid, bp) in self.get_all_page_breakpoints():
if bp.is_disabled():
self.enable_page_breakpoint(pid, bp.get_address())
# disable hardware breakpoints
for (tid, bp) in self.get_all_hardware_breakpoints():
if bp.is_disabled():
self.enable_hardware_breakpoint(tid, bp.get_address())
def enable_one_shot_all_breakpoints(self):
"""
Enables for one shot all disabled breakpoints in all processes.
@see:
enable_one_shot_code_breakpoint,
enable_one_shot_page_breakpoint,
enable_one_shot_hardware_breakpoint
"""
# disable code breakpoints for one shot
for (pid, bp) in self.get_all_code_breakpoints():
if bp.is_disabled():
self.enable_one_shot_code_breakpoint(pid, bp.get_address())
# disable page breakpoints for one shot
for (pid, bp) in self.get_all_page_breakpoints():
if bp.is_disabled():
self.enable_one_shot_page_breakpoint(pid, bp.get_address())
# disable hardware breakpoints for one shot
for (tid, bp) in self.get_all_hardware_breakpoints():
if bp.is_disabled():
self.enable_one_shot_hardware_breakpoint(tid, bp.get_address())
def disable_all_breakpoints(self):
"""
Disables all breakpoints in all processes.
@see:
disable_code_breakpoint,
disable_page_breakpoint,
disable_hardware_breakpoint
"""
# disable code breakpoints
for (pid, bp) in self.get_all_code_breakpoints():
self.disable_code_breakpoint(pid, bp.get_address())
# disable page breakpoints
for (pid, bp) in self.get_all_page_breakpoints():
self.disable_page_breakpoint(pid, bp.get_address())
# disable hardware breakpoints
for (tid, bp) in self.get_all_hardware_breakpoints():
self.disable_hardware_breakpoint(tid, bp.get_address())
def erase_all_breakpoints(self):
"""
Erases all breakpoints in all processes.
@see:
erase_code_breakpoint,
erase_page_breakpoint,
erase_hardware_breakpoint
"""
# This should be faster but let's not trust the GC so much :P
# self.disable_all_breakpoints()
# self.__codeBP = dict()
# self.__pageBP = dict()
# self.__hardwareBP = dict()
# self.__runningBP = dict()
# self.__hook_objects = dict()
## # erase hooks
## for (pid, address, hook) in self.get_all_hooks():
## self.dont_hook_function(pid, address)
# erase code breakpoints
for (pid, bp) in self.get_all_code_breakpoints():
self.erase_code_breakpoint(pid, bp.get_address())
# erase page breakpoints
for (pid, bp) in self.get_all_page_breakpoints():
self.erase_page_breakpoint(pid, bp.get_address())
# erase hardware breakpoints
for (tid, bp) in self.get_all_hardware_breakpoints():
self.erase_hardware_breakpoint(tid, bp.get_address())
#------------------------------------------------------------------------------
# Batch operations on breakpoints per process.
def enable_process_breakpoints(self, dwProcessId):
"""
Enables all disabled breakpoints for the given process.
@type dwProcessId: int
@param dwProcessId: Process global ID.
"""
# enable code breakpoints
for bp in self.get_process_code_breakpoints(dwProcessId):
if bp.is_disabled():
self.enable_code_breakpoint(dwProcessId, bp.get_address())
# enable page breakpoints
for bp in self.get_process_page_breakpoints(dwProcessId):
if bp.is_disabled():
self.enable_page_breakpoint(dwProcessId, bp.get_address())
# enable hardware breakpoints
if self.system.has_process(dwProcessId):
aProcess = self.system.get_process(dwProcessId)
else:
aProcess = Process(dwProcessId)
aProcess.scan_threads()
for aThread in aProcess.iter_threads():
dwThreadId = aThread.get_tid()
for bp in self.get_thread_hardware_breakpoints(dwThreadId):
if bp.is_disabled():
self.enable_hardware_breakpoint(dwThreadId, bp.get_address())
def enable_one_shot_process_breakpoints(self, dwProcessId):
"""
Enables for one shot all disabled breakpoints for the given process.
@type dwProcessId: int
@param dwProcessId: Process global ID.
"""
# enable code breakpoints for one shot
for bp in self.get_process_code_breakpoints(dwProcessId):
if bp.is_disabled():
self.enable_one_shot_code_breakpoint(dwProcessId, bp.get_address())
# enable page breakpoints for one shot
for bp in self.get_process_page_breakpoints(dwProcessId):
if bp.is_disabled():
self.enable_one_shot_page_breakpoint(dwProcessId, bp.get_address())
# enable hardware breakpoints for one shot
if self.system.has_process(dwProcessId):
aProcess = self.system.get_process(dwProcessId)
else:
aProcess = Process(dwProcessId)
aProcess.scan_threads()
for aThread in aProcess.iter_threads():
dwThreadId = aThread.get_tid()
for bp in self.get_thread_hardware_breakpoints(dwThreadId):
if bp.is_disabled():
self.enable_one_shot_hardware_breakpoint(dwThreadId, bp.get_address())
def disable_process_breakpoints(self, dwProcessId):
"""
Disables all breakpoints for the given process.
@type dwProcessId: int
@param dwProcessId: Process global ID.
"""
# disable code breakpoints
for bp in self.get_process_code_breakpoints(dwProcessId):
self.disable_code_breakpoint(dwProcessId, bp.get_address())
# disable page breakpoints
for bp in self.get_process_page_breakpoints(dwProcessId):
self.disable_page_breakpoint(dwProcessId, bp.get_address())
# disable hardware breakpoints
if self.system.has_process(dwProcessId):
aProcess = self.system.get_process(dwProcessId)
else:
aProcess = Process(dwProcessId)
aProcess.scan_threads()
for aThread in aProcess.iter_threads():
dwThreadId = aThread.get_tid()
for bp in self.get_thread_hardware_breakpoints(dwThreadId):
self.disable_hardware_breakpoint(dwThreadId, bp.get_address())
def erase_process_breakpoints(self, dwProcessId):
"""
Erases all breakpoints for the given process.
@type dwProcessId: int
@param dwProcessId: Process global ID.
"""
# disable breakpoints first
# if an error occurs, no breakpoint is erased
self.disable_process_breakpoints(dwProcessId)
## # erase hooks
## for address, hook in self.get_process_hooks(dwProcessId):
## self.dont_hook_function(dwProcessId, address)
# erase code breakpoints
for bp in self.get_process_code_breakpoints(dwProcessId):
self.erase_code_breakpoint(dwProcessId, bp.get_address())
# erase page breakpoints
for bp in self.get_process_page_breakpoints(dwProcessId):
self.erase_page_breakpoint(dwProcessId, bp.get_address())
# erase hardware breakpoints
if self.system.has_process(dwProcessId):
aProcess = self.system.get_process(dwProcessId)
else:
aProcess = Process(dwProcessId)
aProcess.scan_threads()
for aThread in aProcess.iter_threads():
dwThreadId = aThread.get_tid()
for bp in self.get_thread_hardware_breakpoints(dwThreadId):
self.erase_hardware_breakpoint(dwThreadId, bp.get_address())
#------------------------------------------------------------------------------
# Internal handlers of debug events.
def _notify_guard_page(self, event):
"""
Notify breakpoints of a guard page exception event.
@type event: L{ExceptionEvent}
@param event: Guard page exception event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} otherwise.
"""
address = event.get_fault_address()
pid = event.get_pid()
bCallHandler = True
# Align address to page boundary.
mask = ~(MemoryAddresses.pageSize - 1)
address = address & mask
# Do we have an active page breakpoint there?
key = (pid, address)
if key in self.__pageBP:
bp = self.__pageBP[key]
if bp.is_enabled() or bp.is_one_shot():
# Breakpoint is ours.
event.continueStatus = win32.DBG_CONTINUE
## event.continueStatus = win32.DBG_EXCEPTION_HANDLED
# Hit the breakpoint.
bp.hit(event)
# Remember breakpoints in RUNNING state.
if bp.is_running():
tid = event.get_tid()
self.__add_running_bp(tid, bp)
# Evaluate the breakpoint condition.
bCondition = bp.eval_condition(event)
# If the breakpoint is automatic, run the action.
# If not, notify the user.
if bCondition and bp.is_automatic():
bp.run_action(event)
bCallHandler = False
else:
bCallHandler = bCondition
# If we don't have a breakpoint here pass the exception to the debugee.
# This is a normally occurring exception so we shouldn't swallow it.
else:
event.continueStatus = win32.DBG_EXCEPTION_NOT_HANDLED
return bCallHandler
def _notify_breakpoint(self, event):
"""
Notify breakpoints of a breakpoint exception event.
@type event: L{ExceptionEvent}
@param event: Breakpoint exception event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} otherwise.
"""
address = event.get_exception_address()
pid = event.get_pid()
bCallHandler = True
# Do we have an active code breakpoint there?
key = (pid, address)
if key in self.__codeBP:
bp = self.__codeBP[key]
if not bp.is_disabled():
# Change the program counter (PC) to the exception address.
# This accounts for the change in PC caused by
# executing the breakpoint instruction, no matter
# the size of it.
aThread = event.get_thread()
aThread.set_pc(address)
# Swallow the exception.
event.continueStatus = win32.DBG_CONTINUE
# Hit the breakpoint.
bp.hit(event)
# Remember breakpoints in RUNNING state.
if bp.is_running():
tid = event.get_tid()
self.__add_running_bp(tid, bp)
# Evaluate the breakpoint condition.
bCondition = bp.eval_condition(event)
# If the breakpoint is automatic, run the action.
# If not, notify the user.
if bCondition and bp.is_automatic():
bCallHandler = bp.run_action(event)
else:
bCallHandler = bCondition
# Handle the system breakpoint.
# TODO: examine the stack trace to figure out if it's really a
# system breakpoint or an antidebug trick. The caller should be
# inside ntdll if it's legit.
elif event.get_process().is_system_defined_breakpoint(address):
event.continueStatus = win32.DBG_CONTINUE
# In hostile mode, if we don't have a breakpoint here pass the
# exception to the debugee. In normal mode assume all breakpoint
# exceptions are to be handled by the debugger.
else:
if self.in_hostile_mode():
event.continueStatus = win32.DBG_EXCEPTION_NOT_HANDLED
else:
event.continueStatus = win32.DBG_CONTINUE
return bCallHandler
def _notify_single_step(self, event):
"""
Notify breakpoints of a single step exception event.
@type event: L{ExceptionEvent}
@param event: Single step exception event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} otherwise.
"""
pid = event.get_pid()
tid = event.get_tid()
aThread = event.get_thread()
aProcess = event.get_process()
bCallHandler = True
bIsOurs = False
# In hostile mode set the default to pass the exception to the debugee.
# If we later determine the exception is ours, hide it instead.
old_continueStatus = event.continueStatus
try:
if self.in_hostile_mode():
event.continueStatus = win32.DBG_EXCEPTION_NOT_HANDLED
# Single step support is implemented on x86/x64 architectures only.
if self.system.arch not in (win32.ARCH_I386, win32.ARCH_AMD64):
return bCallHandler
# In hostile mode, read the last executed bytes to try to detect
# some antidebug tricks. Skip this check in normal mode because
# it'd slow things down.
#
# FIXME: weird opcode encodings may bypass this check!
#
# bFakeSingleStep: Ice Breakpoint undocumented instruction.
# bHideTrapFlag: Don't let pushf instructions get the real value of
# the trap flag.
# bNextIsPopFlags: Don't let popf instructions clear the trap flag.
#
bFakeSingleStep = False
bLastIsPushFlags = False
bNextIsPopFlags = False
if self.in_hostile_mode():
pc = aThread.get_pc()
c = aProcess.read_char(pc - 1)
if c == 0xF1: # int1
bFakeSingleStep = True
elif c == 0x9C: # pushf
bLastIsPushFlags = True
c = aProcess.peek_char(pc)
if c == 0x66: # the only valid prefix for popf
c = aProcess.peek_char(pc + 1)
if c == 0x9D: # popf
if bLastIsPushFlags:
bLastIsPushFlags = False # they cancel each other out
else:
bNextIsPopFlags = True
# When the thread is in tracing mode,
# don't pass the exception to the debugee
# and set the trap flag again.
if self.is_tracing(tid):
bIsOurs = True
if not bFakeSingleStep:
event.continueStatus = win32.DBG_CONTINUE
aThread.set_tf()
# Don't let the debugee read or write the trap flag.
# This code works in 32 and 64 bits thanks to the endianness.
if bLastIsPushFlags or bNextIsPopFlags:
sp = aThread.get_sp()
flags = aProcess.read_dword(sp)
if bLastIsPushFlags:
flags &= ~Thread.Flags.Trap
else: # if bNextIsPopFlags:
flags |= Thread.Flags.Trap
aProcess.write_dword(sp, flags)
# Handle breakpoints in RUNNING state.
running = self.__get_running_bp_set(tid)
if running:
bIsOurs = True
if not bFakeSingleStep:
event.continueStatus = win32.DBG_CONTINUE
bCallHandler = False
while running:
try:
running.pop().hit(event)
except Exception:
e = sys.exc_info()[1]
warnings.warn(str(e), BreakpointWarning)
# Handle hardware breakpoints.
if tid in self.__hardwareBP:
ctx = aThread.get_context(win32.CONTEXT_DEBUG_REGISTERS)
Dr6 = ctx['Dr6']
ctx['Dr6'] = Dr6 & DebugRegister.clearHitMask
aThread.set_context(ctx)
bFoundBreakpoint = False
bCondition = False
hwbpList = [ bp for bp in self.__hardwareBP[tid] ]
for bp in hwbpList:
if not bp in self.__hardwareBP[tid]:
continue # it was removed by a user-defined callback
slot = bp.get_slot()
if (slot is not None) and \
(Dr6 & DebugRegister.hitMask[slot]):
if not bFoundBreakpoint: #set before actions are called
if not bFakeSingleStep:
event.continueStatus = win32.DBG_CONTINUE
bFoundBreakpoint = True
bIsOurs = True
bp.hit(event)
if bp.is_running():
self.__add_running_bp(tid, bp)
bThisCondition = bp.eval_condition(event)
if bThisCondition and bp.is_automatic():
bp.run_action(event)
bThisCondition = False
bCondition = bCondition or bThisCondition
if bFoundBreakpoint:
bCallHandler = bCondition
# Always call the user-defined handler
# when the thread is in tracing mode.
if self.is_tracing(tid):
bCallHandler = True
# If we're not in hostile mode, by default we assume all single
# step exceptions are caused by the debugger.
if not bIsOurs and not self.in_hostile_mode():
aThread.clear_tf()
# If the user hit Control-C while we were inside the try block,
# set the default continueStatus back.
except:
event.continueStatus = old_continueStatus
raise
return bCallHandler
def _notify_load_dll(self, event):
"""
Notify the loading of a DLL.
@type event: L{LoadDLLEvent}
@param event: Load DLL event.
@rtype: bool
@return: C{True} to call the user-defined handler, C{False} otherwise.
"""
self.__set_deferred_breakpoints(event)
return True
def _notify_unload_dll(self, event):
"""
Notify the unloading of a DLL.
@type event: L{UnloadDLLEvent}
@param event: Unload DLL event.
@rtype: bool
@return: C{True} to call the user-defined handler, C{False} otherwise.
"""
self.__cleanup_module(event)
return True
def _notify_exit_thread(self, event):
"""
Notify the termination of a thread.
@type event: L{ExitThreadEvent}
@param event: Exit thread event.
@rtype: bool
@return: C{True} to call the user-defined handler, C{False} otherwise.
"""
self.__cleanup_thread(event)
return True
def _notify_exit_process(self, event):
"""
Notify the termination of a process.
@type event: L{ExitProcessEvent}
@param event: Exit process event.
@rtype: bool
@return: C{True} to call the user-defined handler, C{False} otherwise.
"""
self.__cleanup_process(event)
self.__cleanup_thread(event)
return True
#------------------------------------------------------------------------------
# This is the high level breakpoint interface. Here we don't have to care
# about defining or enabling breakpoints, and many errors are ignored
# (like for example setting the same breakpoint twice, here the second
# breakpoint replaces the first, much like in WinDBG). It should be easier
# and more intuitive, if less detailed. It also allows the use of deferred
# breakpoints.
#------------------------------------------------------------------------------
# Code breakpoints
def __set_break(self, pid, address, action, oneshot):
"""
Used by L{break_at} and L{stalk_at}.
@type pid: int
@param pid: Process global ID.
@type address: int or str
@param address:
Memory address of code instruction to break at. It can be an
integer value for the actual address or a string with a label
to be resolved.
@type action: function
@param action: (Optional) Action callback function.
See L{define_code_breakpoint} for more details.
@type oneshot: bool
@param oneshot: C{True} for one-shot breakpoints, C{False} otherwise.
@rtype: L{Breakpoint}
@return: Returns the new L{Breakpoint} object, or C{None} if the label
couldn't be resolved and the breakpoint was deferred. Deferred
breakpoints are set when the DLL they point to is loaded.
"""
if type(address) not in (int, long):
label = address
try:
address = self.system.get_process(pid).resolve_label(address)
if not address:
raise Exception()
except Exception:
try:
deferred = self.__deferredBP[pid]
except KeyError:
deferred = dict()
self.__deferredBP[pid] = deferred
if label in deferred:
msg = "Redefined deferred code breakpoint at %s in process ID %d"
msg = msg % (label, pid)
warnings.warn(msg, BreakpointWarning)
deferred[label] = (action, oneshot)
return None
if self.has_code_breakpoint(pid, address):
bp = self.get_code_breakpoint(pid, address)
if bp.get_action() != action: # can't use "is not", fails for bound methods
bp.set_action(action)
msg = "Redefined code breakpoint at %s in process ID %d"
msg = msg % (label, pid)
warnings.warn(msg, BreakpointWarning)
else:
self.define_code_breakpoint(pid, address, True, action)
bp = self.get_code_breakpoint(pid, address)
if oneshot:
if not bp.is_one_shot():
self.enable_one_shot_code_breakpoint(pid, address)
else:
if not bp.is_enabled():
self.enable_code_breakpoint(pid, address)
return bp
def __clear_break(self, pid, address):
"""
Used by L{dont_break_at} and L{dont_stalk_at}.
@type pid: int
@param pid: Process global ID.
@type address: int or str
@param address:
Memory address of code instruction to break at. It can be an
integer value for the actual address or a string with a label
to be resolved.
"""
if type(address) not in (int, long):
unknown = True
label = address
try:
deferred = self.__deferredBP[pid]
del deferred[label]
unknown = False
except KeyError:
## traceback.print_last() # XXX DEBUG
pass
aProcess = self.system.get_process(pid)
try:
address = aProcess.resolve_label(label)
if not address:
raise Exception()
except Exception:
## traceback.print_last() # XXX DEBUG
if unknown:
msg = ("Can't clear unknown code breakpoint"
" at %s in process ID %d")
msg = msg % (label, pid)
warnings.warn(msg, BreakpointWarning)
return
if self.has_code_breakpoint(pid, address):
self.erase_code_breakpoint(pid, address)
def __set_deferred_breakpoints(self, event):
"""
Used internally. Sets all deferred breakpoints for a DLL when it's
loaded.
@type event: L{LoadDLLEvent}
@param event: Load DLL event.
"""
pid = event.get_pid()
try:
deferred = self.__deferredBP[pid]
except KeyError:
return
aProcess = event.get_process()
for (label, (action, oneshot)) in deferred.items():
try:
address = aProcess.resolve_label(label)
except Exception:
continue
del deferred[label]
try:
self.__set_break(pid, address, action, oneshot)
except Exception:
msg = "Can't set deferred breakpoint %s at process ID %d"
msg = msg % (label, pid)
warnings.warn(msg, BreakpointWarning)
def get_all_deferred_code_breakpoints(self):
"""
Returns a list of deferred code breakpoints.
@rtype: tuple of (int, str, callable, bool)
@return: Tuple containing the following elements:
- Process ID where to set the breakpoint.
- Label pointing to the address where to set the breakpoint.
- Action callback for the breakpoint.
- C{True} of the breakpoint is one-shot, C{False} otherwise.
"""
result = []
for pid, deferred in compat.iteritems(self.__deferredBP):
for (label, (action, oneshot)) in compat.iteritems(deferred):
result.add( (pid, label, action, oneshot) )
return result
def get_process_deferred_code_breakpoints(self, dwProcessId):
"""
Returns a list of deferred code breakpoints.
@type dwProcessId: int
@param dwProcessId: Process ID.
@rtype: tuple of (int, str, callable, bool)
@return: Tuple containing the following elements:
- Label pointing to the address where to set the breakpoint.
- Action callback for the breakpoint.
- C{True} of the breakpoint is one-shot, C{False} otherwise.
"""
return [ (label, action, oneshot)
for (label, (action, oneshot))
in compat.iteritems(self.__deferredBP.get(dwProcessId, {})) ]
def stalk_at(self, pid, address, action = None):
"""
Sets a one shot code breakpoint at the given process and address.
If instead of an address you pass a label, the breakpoint may be
deferred until the DLL it points to is loaded.
@see: L{break_at}, L{dont_stalk_at}
@type pid: int
@param pid: Process global ID.
@type address: int or str
@param address:
Memory address of code instruction to break at. It can be an
integer value for the actual address or a string with a label
to be resolved.
@type action: function
@param action: (Optional) Action callback function.
See L{define_code_breakpoint} for more details.
@rtype: bool
@return: C{True} if the breakpoint was set immediately, or C{False} if
it was deferred.
"""
bp = self.__set_break(pid, address, action, oneshot = True)
return bp is not None
def break_at(self, pid, address, action = None):
"""
Sets a code breakpoint at the given process and address.
If instead of an address you pass a label, the breakpoint may be
deferred until the DLL it points to is loaded.
@see: L{stalk_at}, L{dont_break_at}
@type pid: int
@param pid: Process global ID.
@type address: int or str
@param address:
Memory address of code instruction to break at. It can be an
integer value for the actual address or a string with a label
to be resolved.
@type action: function
@param action: (Optional) Action callback function.
See L{define_code_breakpoint} for more details.
@rtype: bool
@return: C{True} if the breakpoint was set immediately, or C{False} if
it was deferred.
"""
bp = self.__set_break(pid, address, action, oneshot = False)
return bp is not None
def dont_break_at(self, pid, address):
"""
Clears a code breakpoint set by L{break_at}.
@type pid: int
@param pid: Process global ID.
@type address: int or str
@param address:
Memory address of code instruction to break at. It can be an
integer value for the actual address or a string with a label
to be resolved.
"""
self.__clear_break(pid, address)
def dont_stalk_at(self, pid, address):
"""
Clears a code breakpoint set by L{stalk_at}.
@type pid: int
@param pid: Process global ID.
@type address: int or str
@param address:
Memory address of code instruction to break at. It can be an
integer value for the actual address or a string with a label
to be resolved.
"""
self.__clear_break(pid, address)
#------------------------------------------------------------------------------
# Function hooks
def hook_function(self, pid, address,
preCB = None, postCB = None,
paramCount = None, signature = None):
"""
Sets a function hook at the given address.
If instead of an address you pass a label, the hook may be
deferred until the DLL it points to is loaded.
@type pid: int
@param pid: Process global ID.
@type address: int or str
@param address:
Memory address of code instruction to break at. It can be an
integer value for the actual address or a string with a label
to be resolved.
@type preCB: function
@param preCB: (Optional) Callback triggered on function entry.
The signature for the callback should be something like this::
def pre_LoadLibraryEx(event, ra, lpFilename, hFile, dwFlags):
# return address
ra = params[0]
# function arguments start from here...
szFilename = event.get_process().peek_string(lpFilename)
# (...)
Note that all pointer types are treated like void pointers, so your
callback won't get the string or structure pointed to by it, but
the remote memory address instead. This is so to prevent the ctypes
library from being "too helpful" and trying to dereference the
pointer. To get the actual data being pointed to, use one of the
L{Process.read} methods.
@type postCB: function
@param postCB: (Optional) Callback triggered on function exit.
The signature for the callback should be something like this::
def post_LoadLibraryEx(event, return_value):
# (...)
@type paramCount: int
@param paramCount:
(Optional) Number of parameters for the C{preCB} callback,
not counting the return address. Parameters are read from
the stack and assumed to be DWORDs in 32 bits and QWORDs in 64.
This is a faster way to pull stack parameters in 32 bits, but in 64
bits (or with some odd APIs in 32 bits) it won't be useful, since
not all arguments to the hooked function will be of the same size.
For a more reliable and cross-platform way of hooking use the
C{signature} argument instead.
@type signature: tuple
@param signature:
(Optional) Tuple of C{ctypes} data types that constitute the
hooked function signature. When the function is called, this will
be used to parse the arguments from the stack. Overrides the
C{paramCount} argument.
@rtype: bool
@return: C{True} if the hook was set immediately, or C{False} if
it was deferred.
"""
try:
aProcess = self.system.get_process(pid)
except KeyError:
aProcess = Process(pid)
arch = aProcess.get_arch()
hookObj = Hook(preCB, postCB, paramCount, signature, arch)
bp = self.break_at(pid, address, hookObj)
return bp is not None
def stalk_function(self, pid, address,
preCB = None, postCB = None,
paramCount = None, signature = None):
"""
Sets a one-shot function hook at the given address.
If instead of an address you pass a label, the hook may be
deferred until the DLL it points to is loaded.
@type pid: int
@param pid: Process global ID.
@type address: int or str
@param address:
Memory address of code instruction to break at. It can be an
integer value for the actual address or a string with a label
to be resolved.
@type preCB: function
@param preCB: (Optional) Callback triggered on function entry.
The signature for the callback should be something like this::
def pre_LoadLibraryEx(event, ra, lpFilename, hFile, dwFlags):
# return address
ra = params[0]
# function arguments start from here...
szFilename = event.get_process().peek_string(lpFilename)
# (...)
Note that all pointer types are treated like void pointers, so your
callback won't get the string or structure pointed to by it, but
the remote memory address instead. This is so to prevent the ctypes
library from being "too helpful" and trying to dereference the
pointer. To get the actual data being pointed to, use one of the
L{Process.read} methods.
@type postCB: function
@param postCB: (Optional) Callback triggered on function exit.
The signature for the callback should be something like this::
def post_LoadLibraryEx(event, return_value):
# (...)
@type paramCount: int
@param paramCount:
(Optional) Number of parameters for the C{preCB} callback,
not counting the return address. Parameters are read from
the stack and assumed to be DWORDs in 32 bits and QWORDs in 64.
This is a faster way to pull stack parameters in 32 bits, but in 64
bits (or with some odd APIs in 32 bits) it won't be useful, since
not all arguments to the hooked function will be of the same size.
For a more reliable and cross-platform way of hooking use the
C{signature} argument instead.
@type signature: tuple
@param signature:
(Optional) Tuple of C{ctypes} data types that constitute the
hooked function signature. When the function is called, this will
be used to parse the arguments from the stack. Overrides the
C{paramCount} argument.
@rtype: bool
@return: C{True} if the breakpoint was set immediately, or C{False} if
it was deferred.
"""
try:
aProcess = self.system.get_process(pid)
except KeyError:
aProcess = Process(pid)
arch = aProcess.get_arch()
hookObj = Hook(preCB, postCB, paramCount, signature, arch)
bp = self.stalk_at(pid, address, hookObj)
return bp is not None
def dont_hook_function(self, pid, address):
"""
Removes a function hook set by L{hook_function}.
@type pid: int
@param pid: Process global ID.
@type address: int or str
@param address:
Memory address of code instruction to break at. It can be an
integer value for the actual address or a string with a label
to be resolved.
"""
self.dont_break_at(pid, address)
# alias
unhook_function = dont_hook_function
def dont_stalk_function(self, pid, address):
"""
Removes a function hook set by L{stalk_function}.
@type pid: int
@param pid: Process global ID.
@type address: int or str
@param address:
Memory address of code instruction to break at. It can be an
integer value for the actual address or a string with a label
to be resolved.
"""
self.dont_stalk_at(pid, address)
#------------------------------------------------------------------------------
# Variable watches
def __set_variable_watch(self, tid, address, size, action):
"""
Used by L{watch_variable} and L{stalk_variable}.
@type tid: int
@param tid: Thread global ID.
@type address: int
@param address: Memory address of variable to watch.
@type size: int
@param size: Size of variable to watch. The only supported sizes are:
byte (1), word (2), dword (4) and qword (8).
@type action: function
@param action: (Optional) Action callback function.
See L{define_hardware_breakpoint} for more details.
@rtype: L{HardwareBreakpoint}
@return: Hardware breakpoint at the requested address.
"""
# TODO
# We should merge the breakpoints instead of overwriting them.
# We'll have the same problem as watch_buffer and we'll need to change
# the API again.
if size == 1:
sizeFlag = self.BP_WATCH_BYTE
elif size == 2:
sizeFlag = self.BP_WATCH_WORD
elif size == 4:
sizeFlag = self.BP_WATCH_DWORD
elif size == 8:
sizeFlag = self.BP_WATCH_QWORD
else:
raise ValueError("Bad size for variable watch: %r" % size)
if self.has_hardware_breakpoint(tid, address):
warnings.warn(
"Hardware breakpoint in thread %d at address %s was overwritten!" \
% (tid, HexDump.address(address,
self.system.get_thread(tid).get_bits())),
BreakpointWarning)
bp = self.get_hardware_breakpoint(tid, address)
if bp.get_trigger() != self.BP_BREAK_ON_ACCESS or \
bp.get_watch() != sizeFlag:
self.erase_hardware_breakpoint(tid, address)
self.define_hardware_breakpoint(tid, address,
self.BP_BREAK_ON_ACCESS, sizeFlag, True, action)
bp = self.get_hardware_breakpoint(tid, address)
else:
self.define_hardware_breakpoint(tid, address,
self.BP_BREAK_ON_ACCESS, sizeFlag, True, action)
bp = self.get_hardware_breakpoint(tid, address)
return bp
def __clear_variable_watch(self, tid, address):
"""
Used by L{dont_watch_variable} and L{dont_stalk_variable}.
@type tid: int
@param tid: Thread global ID.
@type address: int
@param address: Memory address of variable to stop watching.
"""
if self.has_hardware_breakpoint(tid, address):
self.erase_hardware_breakpoint(tid, address)
def watch_variable(self, tid, address, size, action = None):
"""
Sets a hardware breakpoint at the given thread, address and size.
@see: L{dont_watch_variable}
@type tid: int
@param tid: Thread global ID.
@type address: int
@param address: Memory address of variable to watch.
@type size: int
@param size: Size of variable to watch. The only supported sizes are:
byte (1), word (2), dword (4) and qword (8).
@type action: function
@param action: (Optional) Action callback function.
See L{define_hardware_breakpoint} for more details.
"""
bp = self.__set_variable_watch(tid, address, size, action)
if not bp.is_enabled():
self.enable_hardware_breakpoint(tid, address)
def stalk_variable(self, tid, address, size, action = None):
"""
Sets a one-shot hardware breakpoint at the given thread,
address and size.
@see: L{dont_watch_variable}
@type tid: int
@param tid: Thread global ID.
@type address: int
@param address: Memory address of variable to watch.
@type size: int
@param size: Size of variable to watch. The only supported sizes are:
byte (1), word (2), dword (4) and qword (8).
@type action: function
@param action: (Optional) Action callback function.
See L{define_hardware_breakpoint} for more details.
"""
bp = self.__set_variable_watch(tid, address, size, action)
if not bp.is_one_shot():
self.enable_one_shot_hardware_breakpoint(tid, address)
def dont_watch_variable(self, tid, address):
"""
Clears a hardware breakpoint set by L{watch_variable}.
@type tid: int
@param tid: Thread global ID.
@type address: int
@param address: Memory address of variable to stop watching.
"""
self.__clear_variable_watch(tid, address)
def dont_stalk_variable(self, tid, address):
"""
Clears a hardware breakpoint set by L{stalk_variable}.
@type tid: int
@param tid: Thread global ID.
@type address: int
@param address: Memory address of variable to stop watching.
"""
self.__clear_variable_watch(tid, address)
#------------------------------------------------------------------------------
# Buffer watches
def __set_buffer_watch(self, pid, address, size, action, bOneShot):
"""
Used by L{watch_buffer} and L{stalk_buffer}.
@type pid: int
@param pid: Process global ID.
@type address: int
@param address: Memory address of buffer to watch.
@type size: int
@param size: Size in bytes of buffer to watch.
@type action: function
@param action: (Optional) Action callback function.
See L{define_page_breakpoint} for more details.
@type bOneShot: bool
@param bOneShot:
C{True} to set a one-shot breakpoint,
C{False} to set a normal breakpoint.
"""
# Check the size isn't zero or negative.
if size < 1:
raise ValueError("Bad size for buffer watch: %r" % size)
# Create the buffer watch identifier.
bw = BufferWatch(pid, address, address + size, action, bOneShot)
# Get the base address and size in pages required for this buffer.
base = MemoryAddresses.align_address_to_page_start(address)
limit = MemoryAddresses.align_address_to_page_end(address + size)
pages = MemoryAddresses.get_buffer_size_in_pages(address, size)
try:
# For each page:
# + if a page breakpoint exists reuse it
# + if it doesn't exist define it
bset = set() # all breakpoints used
nset = set() # newly defined breakpoints
cset = set() # condition objects
page_addr = base
pageSize = MemoryAddresses.pageSize
while page_addr < limit:
# If a breakpoints exists, reuse it.
if self.has_page_breakpoint(pid, page_addr):
bp = self.get_page_breakpoint(pid, page_addr)
if bp not in bset:
condition = bp.get_condition()
if not condition in cset:
if not isinstance(condition,_BufferWatchCondition):
# this shouldn't happen unless you tinkered
# with it or defined your own page breakpoints
# manually.
msg = "Can't watch buffer at page %s"
msg = msg % HexDump.address(page_addr)
raise RuntimeError(msg)
cset.add(condition)
bset.add(bp)
# If it doesn't, define it.
else:
condition = _BufferWatchCondition()
bp = self.define_page_breakpoint(pid, page_addr, 1,
condition = condition)
bset.add(bp)
nset.add(bp)
cset.add(condition)
# Next page.
page_addr = page_addr + pageSize
# For each breakpoint, enable it if needed.
aProcess = self.system.get_process(pid)
for bp in bset:
if bp.is_disabled() or bp.is_one_shot():
bp.enable(aProcess, None)
# On error...
except:
# Erase the newly defined breakpoints.
for bp in nset:
try:
self.erase_page_breakpoint(pid, bp.get_address())
except:
pass
# Pass the exception to the caller
raise
# For each condition object, add the new buffer.
for condition in cset:
condition.add(bw)
def __clear_buffer_watch_old_method(self, pid, address, size):
"""
Used by L{dont_watch_buffer} and L{dont_stalk_buffer}.
@warn: Deprecated since WinAppDbg 1.5.
@type pid: int
@param pid: Process global ID.
@type address: int
@param address: Memory address of buffer to stop watching.
@type size: int
@param size: Size in bytes of buffer to stop watching.
"""
warnings.warn("Deprecated since WinAppDbg 1.5", DeprecationWarning)
# Check the size isn't zero or negative.
if size < 1:
raise ValueError("Bad size for buffer watch: %r" % size)
# Get the base address and size in pages required for this buffer.
base = MemoryAddresses.align_address_to_page_start(address)
limit = MemoryAddresses.align_address_to_page_end(address + size)
pages = MemoryAddresses.get_buffer_size_in_pages(address, size)
# For each page, get the breakpoint and it's condition object.
# For each condition, remove the buffer.
# For each breakpoint, if no buffers are on watch, erase it.
cset = set() # condition objects
page_addr = base
pageSize = MemoryAddresses.pageSize
while page_addr < limit:
if self.has_page_breakpoint(pid, page_addr):
bp = self.get_page_breakpoint(pid, page_addr)
condition = bp.get_condition()
if condition not in cset:
if not isinstance(condition, _BufferWatchCondition):
# this shouldn't happen unless you tinkered with it
# or defined your own page breakpoints manually.
continue
cset.add(condition)
condition.remove_last_match(address, size)
if condition.count() == 0:
try:
self.erase_page_breakpoint(pid, bp.get_address())
except WindowsError:
pass
page_addr = page_addr + pageSize
def __clear_buffer_watch(self, bw):
"""
Used by L{dont_watch_buffer} and L{dont_stalk_buffer}.
@type bw: L{BufferWatch}
@param bw: Buffer watch identifier.
"""
# Get the PID and the start and end addresses of the buffer.
pid = bw.pid
start = bw.start
end = bw.end
# Get the base address and size in pages required for the buffer.
base = MemoryAddresses.align_address_to_page_start(start)
limit = MemoryAddresses.align_address_to_page_end(end)
pages = MemoryAddresses.get_buffer_size_in_pages(start, end - start)
# For each page, get the breakpoint and it's condition object.
# For each condition, remove the buffer.
# For each breakpoint, if no buffers are on watch, erase it.
cset = set() # condition objects
page_addr = base
pageSize = MemoryAddresses.pageSize
while page_addr < limit:
if self.has_page_breakpoint(pid, page_addr):
bp = self.get_page_breakpoint(pid, page_addr)
condition = bp.get_condition()
if condition not in cset:
if not isinstance(condition, _BufferWatchCondition):
# this shouldn't happen unless you tinkered with it
# or defined your own page breakpoints manually.
continue
cset.add(condition)
condition.remove(bw)
if condition.count() == 0:
try:
self.erase_page_breakpoint(pid, bp.get_address())
except WindowsError:
msg = "Cannot remove page breakpoint at address %s"
msg = msg % HexDump.address( bp.get_address() )
warnings.warn(msg, BreakpointWarning)
page_addr = page_addr + pageSize
def watch_buffer(self, pid, address, size, action = None):
"""
Sets a page breakpoint and notifies when the given buffer is accessed.
@see: L{dont_watch_variable}
@type pid: int
@param pid: Process global ID.
@type address: int
@param address: Memory address of buffer to watch.
@type size: int
@param size: Size in bytes of buffer to watch.
@type action: function
@param action: (Optional) Action callback function.
See L{define_page_breakpoint} for more details.
@rtype: L{BufferWatch}
@return: Buffer watch identifier.
"""
self.__set_buffer_watch(pid, address, size, action, False)
def stalk_buffer(self, pid, address, size, action = None):
"""
Sets a one-shot page breakpoint and notifies
when the given buffer is accessed.
@see: L{dont_watch_variable}
@type pid: int
@param pid: Process global ID.
@type address: int
@param address: Memory address of buffer to watch.
@type size: int
@param size: Size in bytes of buffer to watch.
@type action: function
@param action: (Optional) Action callback function.
See L{define_page_breakpoint} for more details.
@rtype: L{BufferWatch}
@return: Buffer watch identifier.
"""
self.__set_buffer_watch(pid, address, size, action, True)
def dont_watch_buffer(self, bw, *argv, **argd):
"""
Clears a page breakpoint set by L{watch_buffer}.
@type bw: L{BufferWatch}
@param bw:
Buffer watch identifier returned by L{watch_buffer}.
"""
# The sane way to do it.
if not (argv or argd):
self.__clear_buffer_watch(bw)
# Backwards compatibility with WinAppDbg 1.4.
else:
argv = list(argv)
argv.insert(0, bw)
if 'pid' in argd:
argv.insert(0, argd.pop('pid'))
if 'address' in argd:
argv.insert(1, argd.pop('address'))
if 'size' in argd:
argv.insert(2, argd.pop('size'))
if argd:
raise TypeError("Wrong arguments for dont_watch_buffer()")
try:
pid, address, size = argv
except ValueError:
raise TypeError("Wrong arguments for dont_watch_buffer()")
self.__clear_buffer_watch_old_method(pid, address, size)
def dont_stalk_buffer(self, bw, *argv, **argd):
"""
Clears a page breakpoint set by L{stalk_buffer}.
@type bw: L{BufferWatch}
@param bw:
Buffer watch identifier returned by L{stalk_buffer}.
"""
self.dont_watch_buffer(bw, *argv, **argd)
#------------------------------------------------------------------------------
# Tracing
# XXX TODO
# Add "action" parameter to tracing mode
def __start_tracing(self, thread):
"""
@type thread: L{Thread}
@param thread: Thread to start tracing.
"""
tid = thread.get_tid()
if not tid in self.__tracing:
thread.set_tf()
self.__tracing.add(tid)
def __stop_tracing(self, thread):
"""
@type thread: L{Thread}
@param thread: Thread to stop tracing.
"""
tid = thread.get_tid()
if tid in self.__tracing:
self.__tracing.remove(tid)
if thread.is_alive():
thread.clear_tf()
def is_tracing(self, tid):
"""
@type tid: int
@param tid: Thread global ID.
@rtype: bool
@return: C{True} if the thread is being traced, C{False} otherwise.
"""
return tid in self.__tracing
def get_traced_tids(self):
"""
Retrieves the list of global IDs of all threads being traced.
@rtype: list( int... )
@return: List of thread global IDs.
"""
tids = list(self.__tracing)
tids.sort()
return tids
def start_tracing(self, tid):
"""
Start tracing mode in the given thread.
@type tid: int
@param tid: Global ID of thread to start tracing.
"""
if not self.is_tracing(tid):
thread = self.system.get_thread(tid)
self.__start_tracing(thread)
def stop_tracing(self, tid):
"""
Stop tracing mode in the given thread.
@type tid: int
@param tid: Global ID of thread to stop tracing.
"""
if self.is_tracing(tid):
thread = self.system.get_thread(tid)
self.__stop_tracing(thread)
def start_tracing_process(self, pid):
"""
Start tracing mode for all threads in the given process.
@type pid: int
@param pid: Global ID of process to start tracing.
"""
for thread in self.system.get_process(pid).iter_threads():
self.__start_tracing(thread)
def stop_tracing_process(self, pid):
"""
Stop tracing mode for all threads in the given process.
@type pid: int
@param pid: Global ID of process to stop tracing.
"""
for thread in self.system.get_process(pid).iter_threads():
self.__stop_tracing(thread)
def start_tracing_all(self):
"""
Start tracing mode for all threads in all debugees.
"""
for pid in self.get_debugee_pids():
self.start_tracing_process(pid)
def stop_tracing_all(self):
"""
Stop tracing mode for all threads in all debugees.
"""
for pid in self.get_debugee_pids():
self.stop_tracing_process(pid)
#------------------------------------------------------------------------------
# Break on LastError values (only available since Windows Server 2003)
def break_on_error(self, pid, errorCode):
"""
Sets or clears the system breakpoint for a given Win32 error code.
Use L{Process.is_system_defined_breakpoint} to tell if a breakpoint
exception was caused by a system breakpoint or by the application
itself (for example because of a failed assertion in the code).
@note: This functionality is only available since Windows Server 2003.
In 2003 it only breaks on error values set externally to the
kernel32.dll library, but this was fixed in Windows Vista.
@warn: This method will fail if the debug symbols for ntdll (kernel32
in Windows 2003) are not present. For more information see:
L{System.fix_symbol_store_path}.
@see: U{http://www.nynaeve.net/?p=147}
@type pid: int
@param pid: Process ID.
@type errorCode: int
@param errorCode: Win32 error code to stop on. Set to C{0} or
C{ERROR_SUCCESS} to clear the breakpoint instead.
@raise NotImplementedError:
The functionality is not supported in this system.
@raise WindowsError:
An error occurred while processing this request.
"""
aProcess = self.system.get_process(pid)
address = aProcess.get_break_on_error_ptr()
if not address:
raise NotImplementedError(
"The functionality is not supported in this system.")
aProcess.write_dword(address, errorCode)
def dont_break_on_error(self, pid):
"""
Alias to L{break_on_error}C{(pid, ERROR_SUCCESS)}.
@type pid: int
@param pid: Process ID.
@raise NotImplementedError:
The functionality is not supported in this system.
@raise WindowsError:
An error occurred while processing this request.
"""
self.break_on_error(pid, 0)
#------------------------------------------------------------------------------
# Simplified symbol resolving, useful for hooking functions
def resolve_exported_function(self, pid, modName, procName):
"""
Resolves the exported DLL function for the given process.
@type pid: int
@param pid: Process global ID.
@type modName: str
@param modName: Name of the module that exports the function.
@type procName: str
@param procName: Name of the exported function to resolve.
@rtype: int, None
@return: On success, the address of the exported function.
On failure, returns C{None}.
"""
aProcess = self.system.get_process(pid)
aModule = aProcess.get_module_by_name(modName)
if not aModule:
aProcess.scan_modules()
aModule = aProcess.get_module_by_name(modName)
if aModule:
address = aModule.resolve(procName)
return address
return None
def resolve_label(self, pid, label):
"""
Resolves a label for the given process.
@type pid: int
@param pid: Process global ID.
@type label: str
@param label: Label to resolve.
@rtype: int
@return: Memory address pointed to by the label.
@raise ValueError: The label is malformed or impossible to resolve.
@raise RuntimeError: Cannot resolve the module or function.
"""
return self.get_process(pid).resolve_label(label)
| 168,168 | Python | 33.868132 | 105 | 0.561563 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/event.py | #!~/.wine/drive_c/Python25/python.exe
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Event handling module.
@see: U{http://apps.sourceforge.net/trac/winappdbg/wiki/Debugging}
@group Debugging:
EventHandler, EventSift
@group Debug events:
EventFactory,
EventDispatcher,
Event,
NoEvent,
CreateProcessEvent,
CreateThreadEvent,
ExitProcessEvent,
ExitThreadEvent,
LoadDLLEvent,
UnloadDLLEvent,
OutputDebugStringEvent,
RIPEvent,
ExceptionEvent
@group Warnings:
EventCallbackWarning
"""
__revision__ = "$Id$"
__all__ = [
# Factory of Event objects and all of it's subclasses.
# Users should not need to instance Event objects directly.
'EventFactory',
# Event dispatcher used internally by the Debug class.
'EventDispatcher',
# Base classes for user-defined event handlers.
'EventHandler',
'EventSift',
# Warning for uncaught exceptions on event callbacks.
'EventCallbackWarning',
# Dummy event object that can be used as a placeholder.
# It's never returned by the EventFactory.
'NoEvent',
# Base class for event objects.
'Event',
# Event objects.
'CreateProcessEvent',
'CreateThreadEvent',
'ExitProcessEvent',
'ExitThreadEvent',
'LoadDLLEvent',
'UnloadDLLEvent',
'OutputDebugStringEvent',
'RIPEvent',
'ExceptionEvent'
]
from winappdbg import win32
from winappdbg import compat
from winappdbg.win32 import FileHandle, ProcessHandle, ThreadHandle
from winappdbg.breakpoint import ApiHook
from winappdbg.module import Module
from winappdbg.thread import Thread
from winappdbg.process import Process
from winappdbg.textio import HexDump
from winappdbg.util import StaticClass, PathOperations
import sys
import ctypes
import warnings
import traceback
#==============================================================================
class EventCallbackWarning (RuntimeWarning):
"""
This warning is issued when an uncaught exception was raised by a
user-defined event handler.
"""
#==============================================================================
class Event (object):
"""
Event object.
@type eventMethod: str
@cvar eventMethod:
Method name to call when using L{EventHandler} subclasses.
Used internally.
@type eventName: str
@cvar eventName:
User-friendly name of the event.
@type eventDescription: str
@cvar eventDescription:
User-friendly description of the event.
@type debug: L{Debug}
@ivar debug:
Debug object that received the event.
@type raw: L{DEBUG_EVENT}
@ivar raw:
Raw DEBUG_EVENT structure as used by the Win32 API.
@type continueStatus: int
@ivar continueStatus:
Continue status to pass to L{win32.ContinueDebugEvent}.
"""
eventMethod = 'unknown_event'
eventName = 'Unknown event'
eventDescription = 'A debug event of an unknown type has occured.'
def __init__(self, debug, raw):
"""
@type debug: L{Debug}
@param debug: Debug object that received the event.
@type raw: L{DEBUG_EVENT}
@param raw: Raw DEBUG_EVENT structure as used by the Win32 API.
"""
self.debug = debug
self.raw = raw
self.continueStatus = win32.DBG_EXCEPTION_NOT_HANDLED
## @property
## def debug(self):
## """
## @rtype debug: L{Debug}
## @return debug:
## Debug object that received the event.
## """
## return self.__debug()
def get_event_name(self):
"""
@rtype: str
@return: User-friendly name of the event.
"""
return self.eventName
def get_event_description(self):
"""
@rtype: str
@return: User-friendly description of the event.
"""
return self.eventDescription
def get_event_code(self):
"""
@rtype: int
@return: Debug event code as defined in the Win32 API.
"""
return self.raw.dwDebugEventCode
## # Compatibility with version 1.0
## # XXX to be removed in version 1.4
## def get_code(self):
## """
## Alias of L{get_event_code} for backwards compatibility
## with WinAppDbg version 1.0.
## Will be phased out in the next version.
##
## @rtype: int
## @return: Debug event code as defined in the Win32 API.
## """
## return self.get_event_code()
def get_pid(self):
"""
@see: L{get_process}
@rtype: int
@return: Process global ID where the event occured.
"""
return self.raw.dwProcessId
def get_tid(self):
"""
@see: L{get_thread}
@rtype: int
@return: Thread global ID where the event occured.
"""
return self.raw.dwThreadId
def get_process(self):
"""
@see: L{get_pid}
@rtype: L{Process}
@return: Process where the event occured.
"""
pid = self.get_pid()
system = self.debug.system
if system.has_process(pid):
process = system.get_process(pid)
else:
# XXX HACK
# The process object was missing for some reason, so make a new one.
process = Process(pid)
system._add_process(process)
## process.scan_threads() # not needed
process.scan_modules()
return process
def get_thread(self):
"""
@see: L{get_tid}
@rtype: L{Thread}
@return: Thread where the event occured.
"""
tid = self.get_tid()
process = self.get_process()
if process.has_thread(tid):
thread = process.get_thread(tid)
else:
# XXX HACK
# The thread object was missing for some reason, so make a new one.
thread = Thread(tid)
process._add_thread(thread)
return thread
#==============================================================================
class NoEvent (Event):
"""
No event.
Dummy L{Event} object that can be used as a placeholder when no debug
event has occured yet. It's never returned by the L{EventFactory}.
"""
eventMethod = 'no_event'
eventName = 'No event'
eventDescription = 'No debug event has occured.'
def __init__(self, debug, raw = None):
Event.__init__(self, debug, raw)
def __len__(self):
"""
Always returns C{0}, so when evaluating the object as a boolean it's
always C{False}. This prevents L{Debug.cont} from trying to continue
a dummy event.
"""
return 0
def get_event_code(self):
return -1
def get_pid(self):
return -1
def get_tid(self):
return -1
def get_process(self):
return Process(self.get_pid())
def get_thread(self):
return Thread(self.get_tid())
#==============================================================================
class ExceptionEvent (Event):
"""
Exception event.
@type exceptionName: dict( int S{->} str )
@cvar exceptionName:
Mapping of exception constants to their names.
@type exceptionDescription: dict( int S{->} str )
@cvar exceptionDescription:
Mapping of exception constants to user-friendly strings.
@type breakpoint: L{Breakpoint}
@ivar breakpoint:
If the exception was caused by one of our breakpoints, this member
contains a reference to the breakpoint object. Otherwise it's not
defined. It should only be used from the condition or action callback
routines, instead of the event handler.
@type hook: L{Hook}
@ivar hook:
If the exception was caused by a function hook, this member contains a
reference to the hook object. Otherwise it's not defined. It should
only be used from the hook callback routines, instead of the event
handler.
"""
eventName = 'Exception event'
eventDescription = 'An exception was raised by the debugee.'
__exceptionMethod = {
win32.EXCEPTION_ACCESS_VIOLATION : 'access_violation',
win32.EXCEPTION_ARRAY_BOUNDS_EXCEEDED : 'array_bounds_exceeded',
win32.EXCEPTION_BREAKPOINT : 'breakpoint',
win32.EXCEPTION_DATATYPE_MISALIGNMENT : 'datatype_misalignment',
win32.EXCEPTION_FLT_DENORMAL_OPERAND : 'float_denormal_operand',
win32.EXCEPTION_FLT_DIVIDE_BY_ZERO : 'float_divide_by_zero',
win32.EXCEPTION_FLT_INEXACT_RESULT : 'float_inexact_result',
win32.EXCEPTION_FLT_INVALID_OPERATION : 'float_invalid_operation',
win32.EXCEPTION_FLT_OVERFLOW : 'float_overflow',
win32.EXCEPTION_FLT_STACK_CHECK : 'float_stack_check',
win32.EXCEPTION_FLT_UNDERFLOW : 'float_underflow',
win32.EXCEPTION_ILLEGAL_INSTRUCTION : 'illegal_instruction',
win32.EXCEPTION_IN_PAGE_ERROR : 'in_page_error',
win32.EXCEPTION_INT_DIVIDE_BY_ZERO : 'integer_divide_by_zero',
win32.EXCEPTION_INT_OVERFLOW : 'integer_overflow',
win32.EXCEPTION_INVALID_DISPOSITION : 'invalid_disposition',
win32.EXCEPTION_NONCONTINUABLE_EXCEPTION : 'noncontinuable_exception',
win32.EXCEPTION_PRIV_INSTRUCTION : 'privileged_instruction',
win32.EXCEPTION_SINGLE_STEP : 'single_step',
win32.EXCEPTION_STACK_OVERFLOW : 'stack_overflow',
win32.EXCEPTION_GUARD_PAGE : 'guard_page',
win32.EXCEPTION_INVALID_HANDLE : 'invalid_handle',
win32.EXCEPTION_POSSIBLE_DEADLOCK : 'possible_deadlock',
win32.EXCEPTION_WX86_BREAKPOINT : 'wow64_breakpoint',
win32.CONTROL_C_EXIT : 'control_c_exit',
win32.DBG_CONTROL_C : 'debug_control_c',
win32.MS_VC_EXCEPTION : 'ms_vc_exception',
}
__exceptionName = {
win32.EXCEPTION_ACCESS_VIOLATION : 'EXCEPTION_ACCESS_VIOLATION',
win32.EXCEPTION_ARRAY_BOUNDS_EXCEEDED : 'EXCEPTION_ARRAY_BOUNDS_EXCEEDED',
win32.EXCEPTION_BREAKPOINT : 'EXCEPTION_BREAKPOINT',
win32.EXCEPTION_DATATYPE_MISALIGNMENT : 'EXCEPTION_DATATYPE_MISALIGNMENT',
win32.EXCEPTION_FLT_DENORMAL_OPERAND : 'EXCEPTION_FLT_DENORMAL_OPERAND',
win32.EXCEPTION_FLT_DIVIDE_BY_ZERO : 'EXCEPTION_FLT_DIVIDE_BY_ZERO',
win32.EXCEPTION_FLT_INEXACT_RESULT : 'EXCEPTION_FLT_INEXACT_RESULT',
win32.EXCEPTION_FLT_INVALID_OPERATION : 'EXCEPTION_FLT_INVALID_OPERATION',
win32.EXCEPTION_FLT_OVERFLOW : 'EXCEPTION_FLT_OVERFLOW',
win32.EXCEPTION_FLT_STACK_CHECK : 'EXCEPTION_FLT_STACK_CHECK',
win32.EXCEPTION_FLT_UNDERFLOW : 'EXCEPTION_FLT_UNDERFLOW',
win32.EXCEPTION_ILLEGAL_INSTRUCTION : 'EXCEPTION_ILLEGAL_INSTRUCTION',
win32.EXCEPTION_IN_PAGE_ERROR : 'EXCEPTION_IN_PAGE_ERROR',
win32.EXCEPTION_INT_DIVIDE_BY_ZERO : 'EXCEPTION_INT_DIVIDE_BY_ZERO',
win32.EXCEPTION_INT_OVERFLOW : 'EXCEPTION_INT_OVERFLOW',
win32.EXCEPTION_INVALID_DISPOSITION : 'EXCEPTION_INVALID_DISPOSITION',
win32.EXCEPTION_NONCONTINUABLE_EXCEPTION : 'EXCEPTION_NONCONTINUABLE_EXCEPTION',
win32.EXCEPTION_PRIV_INSTRUCTION : 'EXCEPTION_PRIV_INSTRUCTION',
win32.EXCEPTION_SINGLE_STEP : 'EXCEPTION_SINGLE_STEP',
win32.EXCEPTION_STACK_OVERFLOW : 'EXCEPTION_STACK_OVERFLOW',
win32.EXCEPTION_GUARD_PAGE : 'EXCEPTION_GUARD_PAGE',
win32.EXCEPTION_INVALID_HANDLE : 'EXCEPTION_INVALID_HANDLE',
win32.EXCEPTION_POSSIBLE_DEADLOCK : 'EXCEPTION_POSSIBLE_DEADLOCK',
win32.EXCEPTION_WX86_BREAKPOINT : 'EXCEPTION_WX86_BREAKPOINT',
win32.CONTROL_C_EXIT : 'CONTROL_C_EXIT',
win32.DBG_CONTROL_C : 'DBG_CONTROL_C',
win32.MS_VC_EXCEPTION : 'MS_VC_EXCEPTION',
}
__exceptionDescription = {
win32.EXCEPTION_ACCESS_VIOLATION : 'Access violation',
win32.EXCEPTION_ARRAY_BOUNDS_EXCEEDED : 'Array bounds exceeded',
win32.EXCEPTION_BREAKPOINT : 'Breakpoint',
win32.EXCEPTION_DATATYPE_MISALIGNMENT : 'Datatype misalignment',
win32.EXCEPTION_FLT_DENORMAL_OPERAND : 'Float denormal operand',
win32.EXCEPTION_FLT_DIVIDE_BY_ZERO : 'Float divide by zero',
win32.EXCEPTION_FLT_INEXACT_RESULT : 'Float inexact result',
win32.EXCEPTION_FLT_INVALID_OPERATION : 'Float invalid operation',
win32.EXCEPTION_FLT_OVERFLOW : 'Float overflow',
win32.EXCEPTION_FLT_STACK_CHECK : 'Float stack check',
win32.EXCEPTION_FLT_UNDERFLOW : 'Float underflow',
win32.EXCEPTION_ILLEGAL_INSTRUCTION : 'Illegal instruction',
win32.EXCEPTION_IN_PAGE_ERROR : 'In-page error',
win32.EXCEPTION_INT_DIVIDE_BY_ZERO : 'Integer divide by zero',
win32.EXCEPTION_INT_OVERFLOW : 'Integer overflow',
win32.EXCEPTION_INVALID_DISPOSITION : 'Invalid disposition',
win32.EXCEPTION_NONCONTINUABLE_EXCEPTION : 'Noncontinuable exception',
win32.EXCEPTION_PRIV_INSTRUCTION : 'Privileged instruction',
win32.EXCEPTION_SINGLE_STEP : 'Single step event',
win32.EXCEPTION_STACK_OVERFLOW : 'Stack limits overflow',
win32.EXCEPTION_GUARD_PAGE : 'Guard page hit',
win32.EXCEPTION_INVALID_HANDLE : 'Invalid handle',
win32.EXCEPTION_POSSIBLE_DEADLOCK : 'Possible deadlock',
win32.EXCEPTION_WX86_BREAKPOINT : 'WOW64 breakpoint',
win32.CONTROL_C_EXIT : 'Control-C exit',
win32.DBG_CONTROL_C : 'Debug Control-C',
win32.MS_VC_EXCEPTION : 'Microsoft Visual C++ exception',
}
@property
def eventMethod(self):
return self.__exceptionMethod.get(
self.get_exception_code(), 'unknown_exception')
def get_exception_name(self):
"""
@rtype: str
@return: Name of the exception as defined by the Win32 API.
"""
code = self.get_exception_code()
unk = HexDump.integer(code)
return self.__exceptionName.get(code, unk)
def get_exception_description(self):
"""
@rtype: str
@return: User-friendly name of the exception.
"""
code = self.get_exception_code()
description = self.__exceptionDescription.get(code, None)
if description is None:
try:
description = 'Exception code %s (%s)'
description = description % (HexDump.integer(code),
ctypes.FormatError(code))
except OverflowError:
description = 'Exception code %s' % HexDump.integer(code)
return description
def is_first_chance(self):
"""
@rtype: bool
@return: C{True} for first chance exceptions, C{False} for last chance.
"""
return self.raw.u.Exception.dwFirstChance != 0
def is_last_chance(self):
"""
@rtype: bool
@return: The opposite of L{is_first_chance}.
"""
return not self.is_first_chance()
def is_noncontinuable(self):
"""
@see: U{http://msdn.microsoft.com/en-us/library/aa363082(VS.85).aspx}
@rtype: bool
@return: C{True} if the exception is noncontinuable,
C{False} otherwise.
Attempting to continue a noncontinuable exception results in an
EXCEPTION_NONCONTINUABLE_EXCEPTION exception to be raised.
"""
return bool( self.raw.u.Exception.ExceptionRecord.ExceptionFlags & \
win32.EXCEPTION_NONCONTINUABLE )
def is_continuable(self):
"""
@rtype: bool
@return: The opposite of L{is_noncontinuable}.
"""
return not self.is_noncontinuable()
def is_user_defined_exception(self):
"""
Determines if this is an user-defined exception. User-defined
exceptions may contain any exception code that is not system reserved.
Often the exception code is also a valid Win32 error code, but that's
up to the debugged application.
@rtype: bool
@return: C{True} if the exception is user-defined, C{False} otherwise.
"""
return self.get_exception_code() & 0x10000000 == 0
def is_system_defined_exception(self):
"""
@rtype: bool
@return: The opposite of L{is_user_defined_exception}.
"""
return not self.is_user_defined_exception()
def get_exception_code(self):
"""
@rtype: int
@return: Exception code as defined by the Win32 API.
"""
return self.raw.u.Exception.ExceptionRecord.ExceptionCode
def get_exception_address(self):
"""
@rtype: int
@return: Memory address where the exception occured.
"""
address = self.raw.u.Exception.ExceptionRecord.ExceptionAddress
if address is None:
address = 0
return address
def get_exception_information(self, index):
"""
@type index: int
@param index: Index into the exception information block.
@rtype: int
@return: Exception information DWORD.
"""
if index < 0 or index > win32.EXCEPTION_MAXIMUM_PARAMETERS:
raise IndexError("Array index out of range: %s" % repr(index))
info = self.raw.u.Exception.ExceptionRecord.ExceptionInformation
value = info[index]
if value is None:
value = 0
return value
def get_exception_information_as_list(self):
"""
@rtype: list( int )
@return: Exception information block.
"""
info = self.raw.u.Exception.ExceptionRecord.ExceptionInformation
data = list()
for index in compat.xrange(0, win32.EXCEPTION_MAXIMUM_PARAMETERS):
value = info[index]
if value is None:
value = 0
data.append(value)
return data
def get_fault_type(self):
"""
@rtype: int
@return: Access violation type.
Should be one of the following constants:
- L{win32.EXCEPTION_READ_FAULT}
- L{win32.EXCEPTION_WRITE_FAULT}
- L{win32.EXCEPTION_EXECUTE_FAULT}
@note: This method is only meaningful for access violation exceptions,
in-page memory error exceptions and guard page exceptions.
@raise NotImplementedError: Wrong kind of exception.
"""
if self.get_exception_code() not in (win32.EXCEPTION_ACCESS_VIOLATION,
win32.EXCEPTION_IN_PAGE_ERROR, win32.EXCEPTION_GUARD_PAGE):
msg = "This method is not meaningful for %s."
raise NotImplementedError(msg % self.get_exception_name())
return self.get_exception_information(0)
def get_fault_address(self):
"""
@rtype: int
@return: Access violation memory address.
@note: This method is only meaningful for access violation exceptions,
in-page memory error exceptions and guard page exceptions.
@raise NotImplementedError: Wrong kind of exception.
"""
if self.get_exception_code() not in (win32.EXCEPTION_ACCESS_VIOLATION,
win32.EXCEPTION_IN_PAGE_ERROR, win32.EXCEPTION_GUARD_PAGE):
msg = "This method is not meaningful for %s."
raise NotImplementedError(msg % self.get_exception_name())
return self.get_exception_information(1)
def get_ntstatus_code(self):
"""
@rtype: int
@return: NTSTATUS status code that caused the exception.
@note: This method is only meaningful for in-page memory error
exceptions.
@raise NotImplementedError: Not an in-page memory error.
"""
if self.get_exception_code() != win32.EXCEPTION_IN_PAGE_ERROR:
msg = "This method is only meaningful "\
"for in-page memory error exceptions."
raise NotImplementedError(msg)
return self.get_exception_information(2)
def is_nested(self):
"""
@rtype: bool
@return: Returns C{True} if there are additional exception records
associated with this exception. This would mean the exception
is nested, that is, it was triggered while trying to handle
at least one previous exception.
"""
return bool(self.raw.u.Exception.ExceptionRecord.ExceptionRecord)
def get_raw_exception_record_list(self):
"""
Traverses the exception record linked list and builds a Python list.
Nested exception records are received for nested exceptions. This
happens when an exception is raised in the debugee while trying to
handle a previous exception.
@rtype: list( L{win32.EXCEPTION_RECORD} )
@return:
List of raw exception record structures as used by the Win32 API.
There is always at least one exception record, so the list is
never empty. All other methods of this class read from the first
exception record only, that is, the most recent exception.
"""
# The first EXCEPTION_RECORD is contained in EXCEPTION_DEBUG_INFO.
# The remaining EXCEPTION_RECORD structures are linked by pointers.
nested = list()
record = self.raw.u.Exception
while True:
record = record.ExceptionRecord
if not record:
break
nested.append(record)
return nested
def get_nested_exceptions(self):
"""
Traverses the exception record linked list and builds a Python list.
Nested exception records are received for nested exceptions. This
happens when an exception is raised in the debugee while trying to
handle a previous exception.
@rtype: list( L{ExceptionEvent} )
@return:
List of ExceptionEvent objects representing each exception record
found in this event.
There is always at least one exception record, so the list is
never empty. All other methods of this class read from the first
exception record only, that is, the most recent exception.
"""
# The list always begins with ourselves.
# Just put a reference to "self" as the first element,
# and start looping from the second exception record.
nested = [ self ]
raw = self.raw
dwDebugEventCode = raw.dwDebugEventCode
dwProcessId = raw.dwProcessId
dwThreadId = raw.dwThreadId
dwFirstChance = raw.u.Exception.dwFirstChance
record = raw.u.Exception.ExceptionRecord
while True:
record = record.ExceptionRecord
if not record:
break
raw = win32.DEBUG_EVENT()
raw.dwDebugEventCode = dwDebugEventCode
raw.dwProcessId = dwProcessId
raw.dwThreadId = dwThreadId
raw.u.Exception.ExceptionRecord = record
raw.u.Exception.dwFirstChance = dwFirstChance
event = EventFactory.get(self.debug, raw)
nested.append(event)
return nested
#==============================================================================
class CreateThreadEvent (Event):
"""
Thread creation event.
"""
eventMethod = 'create_thread'
eventName = 'Thread creation event'
eventDescription = 'A new thread has started.'
def get_thread_handle(self):
"""
@rtype: L{ThreadHandle}
@return: Thread handle received from the system.
Returns C{None} if the handle is not available.
"""
# The handle doesn't need to be closed.
# See http://msdn.microsoft.com/en-us/library/ms681423(VS.85).aspx
hThread = self.raw.u.CreateThread.hThread
if hThread in (0, win32.NULL, win32.INVALID_HANDLE_VALUE):
hThread = None
else:
hThread = ThreadHandle(hThread, False, win32.THREAD_ALL_ACCESS)
return hThread
def get_teb(self):
"""
@rtype: int
@return: Pointer to the TEB.
"""
return self.raw.u.CreateThread.lpThreadLocalBase
def get_start_address(self):
"""
@rtype: int
@return: Pointer to the first instruction to execute in this thread.
Returns C{NULL} when the debugger attached to a process
and the thread already existed.
See U{http://msdn.microsoft.com/en-us/library/ms679295(VS.85).aspx}
"""
return self.raw.u.CreateThread.lpStartAddress
#==============================================================================
class CreateProcessEvent (Event):
"""
Process creation event.
"""
eventMethod = 'create_process'
eventName = 'Process creation event'
eventDescription = 'A new process has started.'
def get_file_handle(self):
"""
@rtype: L{FileHandle} or None
@return: File handle to the main module, received from the system.
Returns C{None} if the handle is not available.
"""
# This handle DOES need to be closed.
# Therefore we must cache it so it doesn't
# get closed after the first call.
try:
hFile = self.__hFile
except AttributeError:
hFile = self.raw.u.CreateProcessInfo.hFile
if hFile in (0, win32.NULL, win32.INVALID_HANDLE_VALUE):
hFile = None
else:
hFile = FileHandle(hFile, True)
self.__hFile = hFile
return hFile
def get_process_handle(self):
"""
@rtype: L{ProcessHandle}
@return: Process handle received from the system.
Returns C{None} if the handle is not available.
"""
# The handle doesn't need to be closed.
# See http://msdn.microsoft.com/en-us/library/ms681423(VS.85).aspx
hProcess = self.raw.u.CreateProcessInfo.hProcess
if hProcess in (0, win32.NULL, win32.INVALID_HANDLE_VALUE):
hProcess = None
else:
hProcess = ProcessHandle(hProcess, False, win32.PROCESS_ALL_ACCESS)
return hProcess
def get_thread_handle(self):
"""
@rtype: L{ThreadHandle}
@return: Thread handle received from the system.
Returns C{None} if the handle is not available.
"""
# The handle doesn't need to be closed.
# See http://msdn.microsoft.com/en-us/library/ms681423(VS.85).aspx
hThread = self.raw.u.CreateProcessInfo.hThread
if hThread in (0, win32.NULL, win32.INVALID_HANDLE_VALUE):
hThread = None
else:
hThread = ThreadHandle(hThread, False, win32.THREAD_ALL_ACCESS)
return hThread
def get_start_address(self):
"""
@rtype: int
@return: Pointer to the first instruction to execute in this process.
Returns C{NULL} when the debugger attaches to a process.
See U{http://msdn.microsoft.com/en-us/library/ms679295(VS.85).aspx}
"""
return self.raw.u.CreateProcessInfo.lpStartAddress
def get_image_base(self):
"""
@rtype: int
@return: Base address of the main module.
@warn: This value is taken from the PE file
and may be incorrect because of ASLR!
"""
# TODO try to calculate the real value when ASLR is active.
return self.raw.u.CreateProcessInfo.lpBaseOfImage
def get_teb(self):
"""
@rtype: int
@return: Pointer to the TEB.
"""
return self.raw.u.CreateProcessInfo.lpThreadLocalBase
def get_debug_info(self):
"""
@rtype: str
@return: Debugging information.
"""
raw = self.raw.u.CreateProcessInfo
ptr = raw.lpBaseOfImage + raw.dwDebugInfoFileOffset
size = raw.nDebugInfoSize
data = self.get_process().peek(ptr, size)
if len(data) == size:
return data
return None
def get_filename(self):
"""
@rtype: str, None
@return: This method does it's best to retrieve the filename to
the main module of the process. However, sometimes that's not
possible, and C{None} is returned instead.
"""
# Try to get the filename from the file handle.
szFilename = None
hFile = self.get_file_handle()
if hFile:
szFilename = hFile.get_filename()
if not szFilename:
# Try to get it from CREATE_PROCESS_DEBUG_INFO.lpImageName
# It's NULL or *NULL most of the times, see MSDN:
# http://msdn.microsoft.com/en-us/library/ms679286(VS.85).aspx
aProcess = self.get_process()
lpRemoteFilenamePtr = self.raw.u.CreateProcessInfo.lpImageName
if lpRemoteFilenamePtr:
lpFilename = aProcess.peek_uint(lpRemoteFilenamePtr)
fUnicode = bool( self.raw.u.CreateProcessInfo.fUnicode )
szFilename = aProcess.peek_string(lpFilename, fUnicode)
# XXX TODO
# Sometimes the filename is relative (ntdll.dll, kernel32.dll).
# It could be converted to an absolute pathname (SearchPath).
# Try to get it from Process.get_image_name().
if not szFilename:
szFilename = aProcess.get_image_name()
# Return the filename, or None on error.
return szFilename
def get_module_base(self):
"""
@rtype: int
@return: Base address of the main module.
"""
return self.get_image_base()
def get_module(self):
"""
@rtype: L{Module}
@return: Main module of the process.
"""
return self.get_process().get_module( self.get_module_base() )
#==============================================================================
class ExitThreadEvent (Event):
"""
Thread termination event.
"""
eventMethod = 'exit_thread'
eventName = 'Thread termination event'
eventDescription = 'A thread has finished executing.'
def get_exit_code(self):
"""
@rtype: int
@return: Exit code of the thread.
"""
return self.raw.u.ExitThread.dwExitCode
#==============================================================================
class ExitProcessEvent (Event):
"""
Process termination event.
"""
eventMethod = 'exit_process'
eventName = 'Process termination event'
eventDescription = 'A process has finished executing.'
def get_exit_code(self):
"""
@rtype: int
@return: Exit code of the process.
"""
return self.raw.u.ExitProcess.dwExitCode
def get_filename(self):
"""
@rtype: None or str
@return: Filename of the main module.
C{None} if the filename is unknown.
"""
return self.get_module().get_filename()
def get_image_base(self):
"""
@rtype: int
@return: Base address of the main module.
"""
return self.get_module_base()
def get_module_base(self):
"""
@rtype: int
@return: Base address of the main module.
"""
return self.get_module().get_base()
def get_module(self):
"""
@rtype: L{Module}
@return: Main module of the process.
"""
return self.get_process().get_main_module()
#==============================================================================
class LoadDLLEvent (Event):
"""
Module load event.
"""
eventMethod = 'load_dll'
eventName = 'Module load event'
eventDescription = 'A new DLL library was loaded by the debugee.'
def get_module_base(self):
"""
@rtype: int
@return: Base address for the newly loaded DLL.
"""
return self.raw.u.LoadDll.lpBaseOfDll
def get_module(self):
"""
@rtype: L{Module}
@return: Module object for the newly loaded DLL.
"""
lpBaseOfDll = self.get_module_base()
aProcess = self.get_process()
if aProcess.has_module(lpBaseOfDll):
aModule = aProcess.get_module(lpBaseOfDll)
else:
# XXX HACK
# For some reason the module object is missing, so make a new one.
aModule = Module(lpBaseOfDll,
hFile = self.get_file_handle(),
fileName = self.get_filename(),
process = aProcess)
aProcess._add_module(aModule)
return aModule
def get_file_handle(self):
"""
@rtype: L{FileHandle} or None
@return: File handle to the newly loaded DLL received from the system.
Returns C{None} if the handle is not available.
"""
# This handle DOES need to be closed.
# Therefore we must cache it so it doesn't
# get closed after the first call.
try:
hFile = self.__hFile
except AttributeError:
hFile = self.raw.u.LoadDll.hFile
if hFile in (0, win32.NULL, win32.INVALID_HANDLE_VALUE):
hFile = None
else:
hFile = FileHandle(hFile, True)
self.__hFile = hFile
return hFile
def get_filename(self):
"""
@rtype: str, None
@return: This method does it's best to retrieve the filename to
the newly loaded module. However, sometimes that's not
possible, and C{None} is returned instead.
"""
szFilename = None
# Try to get it from LOAD_DLL_DEBUG_INFO.lpImageName
# It's NULL or *NULL most of the times, see MSDN:
# http://msdn.microsoft.com/en-us/library/ms679286(VS.85).aspx
aProcess = self.get_process()
lpRemoteFilenamePtr = self.raw.u.LoadDll.lpImageName
if lpRemoteFilenamePtr:
lpFilename = aProcess.peek_uint(lpRemoteFilenamePtr)
fUnicode = bool( self.raw.u.LoadDll.fUnicode )
szFilename = aProcess.peek_string(lpFilename, fUnicode)
if not szFilename:
szFilename = None
# Try to get the filename from the file handle.
if not szFilename:
hFile = self.get_file_handle()
if hFile:
szFilename = hFile.get_filename()
# Return the filename, or None on error.
return szFilename
#==============================================================================
class UnloadDLLEvent (Event):
"""
Module unload event.
"""
eventMethod = 'unload_dll'
eventName = 'Module unload event'
eventDescription = 'A DLL library was unloaded by the debugee.'
def get_module_base(self):
"""
@rtype: int
@return: Base address for the recently unloaded DLL.
"""
return self.raw.u.UnloadDll.lpBaseOfDll
def get_module(self):
"""
@rtype: L{Module}
@return: Module object for the recently unloaded DLL.
"""
lpBaseOfDll = self.get_module_base()
aProcess = self.get_process()
if aProcess.has_module(lpBaseOfDll):
aModule = aProcess.get_module(lpBaseOfDll)
else:
aModule = Module(lpBaseOfDll, process = aProcess)
aProcess._add_module(aModule)
return aModule
def get_file_handle(self):
"""
@rtype: None or L{FileHandle}
@return: File handle to the recently unloaded DLL.
Returns C{None} if the handle is not available.
"""
hFile = self.get_module().hFile
if hFile in (0, win32.NULL, win32.INVALID_HANDLE_VALUE):
hFile = None
return hFile
def get_filename(self):
"""
@rtype: None or str
@return: Filename of the recently unloaded DLL.
C{None} if the filename is unknown.
"""
return self.get_module().get_filename()
#==============================================================================
class OutputDebugStringEvent (Event):
"""
Debug string output event.
"""
eventMethod = 'output_string'
eventName = 'Debug string output event'
eventDescription = 'The debugee sent a message to the debugger.'
def get_debug_string(self):
"""
@rtype: str, compat.unicode
@return: String sent by the debugee.
It may be ANSI or Unicode and may end with a null character.
"""
return self.get_process().peek_string(
self.raw.u.DebugString.lpDebugStringData,
bool( self.raw.u.DebugString.fUnicode ),
self.raw.u.DebugString.nDebugStringLength)
#==============================================================================
class RIPEvent (Event):
"""
RIP event.
"""
eventMethod = 'rip'
eventName = 'RIP event'
eventDescription = 'An error has occured and the process ' \
'can no longer be debugged.'
def get_rip_error(self):
"""
@rtype: int
@return: RIP error code as defined by the Win32 API.
"""
return self.raw.u.RipInfo.dwError
def get_rip_type(self):
"""
@rtype: int
@return: RIP type code as defined by the Win32 API.
May be C{0} or one of the following:
- L{win32.SLE_ERROR}
- L{win32.SLE_MINORERROR}
- L{win32.SLE_WARNING}
"""
return self.raw.u.RipInfo.dwType
#==============================================================================
class EventFactory (StaticClass):
"""
Factory of L{Event} objects.
@type baseEvent: L{Event}
@cvar baseEvent:
Base class for Event objects.
It's used for unknown event codes.
@type eventClasses: dict( int S{->} L{Event} )
@cvar eventClasses:
Dictionary that maps event codes to L{Event} subclasses.
"""
baseEvent = Event
eventClasses = {
win32.EXCEPTION_DEBUG_EVENT : ExceptionEvent, # 1
win32.CREATE_THREAD_DEBUG_EVENT : CreateThreadEvent, # 2
win32.CREATE_PROCESS_DEBUG_EVENT : CreateProcessEvent, # 3
win32.EXIT_THREAD_DEBUG_EVENT : ExitThreadEvent, # 4
win32.EXIT_PROCESS_DEBUG_EVENT : ExitProcessEvent, # 5
win32.LOAD_DLL_DEBUG_EVENT : LoadDLLEvent, # 6
win32.UNLOAD_DLL_DEBUG_EVENT : UnloadDLLEvent, # 7
win32.OUTPUT_DEBUG_STRING_EVENT : OutputDebugStringEvent, # 8
win32.RIP_EVENT : RIPEvent, # 9
}
@classmethod
def get(cls, debug, raw):
"""
@type debug: L{Debug}
@param debug: Debug object that received the event.
@type raw: L{DEBUG_EVENT}
@param raw: Raw DEBUG_EVENT structure as used by the Win32 API.
@rtype: L{Event}
@returns: An Event object or one of it's subclasses,
depending on the event type.
"""
eventClass = cls.eventClasses.get(raw.dwDebugEventCode, cls.baseEvent)
return eventClass(debug, raw)
#==============================================================================
class EventHandler (object):
"""
Base class for debug event handlers.
Your program should subclass it to implement it's own event handling.
The constructor can be overriden as long as you call the superclass
constructor. The special method L{__call__} B{MUST NOT} be overriden.
The signature for event handlers is the following::
def event_handler(self, event):
Where B{event} is an L{Event} object.
Each event handler is named after the event they handle.
This is the list of all valid event handler names:
- I{event}
Receives an L{Event} object or an object of any of it's subclasses,
and handles any event for which no handler was defined.
- I{unknown_event}
Receives an L{Event} object or an object of any of it's subclasses,
and handles any event unknown to the debugging engine. (This is not
likely to happen unless the Win32 debugging API is changed in future
versions of Windows).
- I{exception}
Receives an L{ExceptionEvent} object and handles any exception for
which no handler was defined. See above for exception handlers.
- I{unknown_exception}
Receives an L{ExceptionEvent} object and handles any exception unknown
to the debugging engine. This usually happens for C++ exceptions, which
are not standardized and may change from one compiler to the next.
Currently we have partial support for C++ exceptions thrown by Microsoft
compilers.
Also see: U{RaiseException()
<http://msdn.microsoft.com/en-us/library/ms680552(VS.85).aspx>}
- I{create_thread}
Receives a L{CreateThreadEvent} object.
- I{create_process}
Receives a L{CreateProcessEvent} object.
- I{exit_thread}
Receives a L{ExitThreadEvent} object.
- I{exit_process}
Receives a L{ExitProcessEvent} object.
- I{load_dll}
Receives a L{LoadDLLEvent} object.
- I{unload_dll}
Receives an L{UnloadDLLEvent} object.
- I{output_string}
Receives an L{OutputDebugStringEvent} object.
- I{rip}
Receives a L{RIPEvent} object.
This is the list of all valid exception handler names
(they all receive an L{ExceptionEvent} object):
- I{access_violation}
- I{array_bounds_exceeded}
- I{breakpoint}
- I{control_c_exit}
- I{datatype_misalignment}
- I{debug_control_c}
- I{float_denormal_operand}
- I{float_divide_by_zero}
- I{float_inexact_result}
- I{float_invalid_operation}
- I{float_overflow}
- I{float_stack_check}
- I{float_underflow}
- I{guard_page}
- I{illegal_instruction}
- I{in_page_error}
- I{integer_divide_by_zero}
- I{integer_overflow}
- I{invalid_disposition}
- I{invalid_handle}
- I{ms_vc_exception}
- I{noncontinuable_exception}
- I{possible_deadlock}
- I{privileged_instruction}
- I{single_step}
- I{stack_overflow}
- I{wow64_breakpoint}
@type apiHooks: dict( str S{->} list( tuple( str, int ) ) )
@cvar apiHooks:
Dictionary that maps module names to lists of
tuples of ( procedure name, parameter count ).
All procedures listed here will be hooked for calls from the debugee.
When this happens, the corresponding event handler can be notified both
when the procedure is entered and when it's left by the debugee.
For example, let's hook the LoadLibraryEx() API call.
This would be the declaration of apiHooks::
from winappdbg import EventHandler
from winappdbg.win32 import *
# (...)
class MyEventHandler (EventHandler):
apiHook = {
"kernel32.dll" : (
# Procedure name Signature
( "LoadLibraryEx", (PVOID, HANDLE, DWORD) ),
# (more procedures can go here...)
),
# (more libraries can go here...)
}
# (your method definitions go here...)
Note that all pointer types are treated like void pointers, so your
callback won't get the string or structure pointed to by it, but the
remote memory address instead. This is so to prevent the ctypes library
from being "too helpful" and trying to dereference the pointer. To get
the actual data being pointed to, use one of the L{Process.read}
methods.
Now, to intercept calls to LoadLibraryEx define a method like this in
your event handler class::
def pre_LoadLibraryEx(self, event, ra, lpFilename, hFile, dwFlags):
szFilename = event.get_process().peek_string(lpFilename)
# (...)
Note that the first parameter is always the L{Event} object, and the
second parameter is the return address. The third parameter and above
are the values passed to the hooked function.
Finally, to intercept returns from calls to LoadLibraryEx define a
method like this::
def post_LoadLibraryEx(self, event, retval):
# (...)
The first parameter is the L{Event} object and the second is the
return value from the hooked function.
"""
#------------------------------------------------------------------------------
# Default (empty) API hooks dictionary.
apiHooks = {}
def __init__(self):
"""
Class constructor. Don't forget to call it when subclassing!
Forgetting to call the superclass constructor is a common mistake when
you're new to Python. :)
Example::
class MyEventHandler (EventHandler):
# Override the constructor to use an extra argument.
def __init__(self, myArgument):
# Do something with the argument, like keeping it
# as an instance variable.
self.myVariable = myArgument
# Call the superclass constructor.
super(MyEventHandler, self).__init__()
# The rest of your code below...
"""
# TODO
# All this does is set up the hooks.
# This code should be moved to the EventDispatcher class.
# Then the hooks can be set up at set_event_handler() instead, making
# this class even simpler. The downside here is deciding where to store
# the ApiHook objects.
# Convert the tuples into instances of the ApiHook class.
# A new dictionary must be instanced, otherwise we could also be
# affecting all other instances of the EventHandler.
apiHooks = dict()
for lib, hooks in compat.iteritems(self.apiHooks):
hook_objs = []
for proc, args in hooks:
if type(args) in (int, long):
h = ApiHook(self, lib, proc, paramCount = args)
else:
h = ApiHook(self, lib, proc, signature = args)
hook_objs.append(h)
apiHooks[lib] = hook_objs
self.__apiHooks = apiHooks
def __get_hooks_for_dll(self, event):
"""
Get the requested API hooks for the current DLL.
Used by L{__hook_dll} and L{__unhook_dll}.
"""
result = []
if self.__apiHooks:
path = event.get_module().get_filename()
if path:
lib_name = PathOperations.pathname_to_filename(path).lower()
for hook_lib, hook_api_list in compat.iteritems(self.__apiHooks):
if hook_lib == lib_name:
result.extend(hook_api_list)
return result
def __hook_dll(self, event):
"""
Hook the requested API calls (in self.apiHooks).
This method is called automatically whenever a DLL is loaded.
"""
debug = event.debug
pid = event.get_pid()
for hook_api_stub in self.__get_hooks_for_dll(event):
hook_api_stub.hook(debug, pid)
def __unhook_dll(self, event):
"""
Unhook the requested API calls (in self.apiHooks).
This method is called automatically whenever a DLL is unloaded.
"""
debug = event.debug
pid = event.get_pid()
for hook_api_stub in self.__get_hooks_for_dll(event):
hook_api_stub.unhook(debug, pid)
def __call__(self, event):
"""
Dispatch debug events.
@warn: B{Don't override this method!}
@type event: L{Event}
@param event: Event object.
"""
try:
code = event.get_event_code()
if code == win32.LOAD_DLL_DEBUG_EVENT:
self.__hook_dll(event)
elif code == win32.UNLOAD_DLL_DEBUG_EVENT:
self.__unhook_dll(event)
finally:
method = EventDispatcher.get_handler_method(self, event)
if method is not None:
return method(event)
#==============================================================================
# TODO
# * Make it more generic by adding a few more callbacks.
# That way it will be possible to make a thread sifter too.
# * This interface feels too much like an antipattern.
# When apiHooks is deprecated this will have to be reviewed.
class EventSift(EventHandler):
"""
Event handler that allows you to use customized event handlers for each
process you're attached to.
This makes coding the event handlers much easier, because each instance
will only "know" about one process. So you can code your event handler as
if only one process was being debugged, but your debugger can attach to
multiple processes.
Example::
from winappdbg import Debug, EventHandler, EventSift
# This class was written assuming only one process is attached.
# If you used it directly it would break when attaching to another
# process, or when a child process is spawned.
class MyEventHandler (EventHandler):
def create_process(self, event):
self.first = True
self.name = event.get_process().get_filename()
print "Attached to %s" % self.name
def breakpoint(self, event):
if self.first:
self.first = False
print "First breakpoint reached at %s" % self.name
def exit_process(self, event):
print "Detached from %s" % self.name
# Now when debugging we use the EventSift to be able to work with
# multiple processes while keeping our code simple. :)
if __name__ == "__main__":
handler = EventSift(MyEventHandler)
#handler = MyEventHandler() # try uncommenting this line...
with Debug(handler) as debug:
debug.execl("calc.exe")
debug.execl("notepad.exe")
debug.execl("charmap.exe")
debug.loop()
Subclasses of C{EventSift} can prevent specific event types from
being forwarded by simply defining a method for it. That means your
subclass can handle some event types globally while letting other types
be handled on per-process basis. To forward events manually you can
call C{self.event(event)}.
Example::
class MySift (EventSift):
# Don't forward this event.
def debug_control_c(self, event):
pass
# Handle this event globally without forwarding it.
def output_string(self, event):
print "Debug string: %s" % event.get_debug_string()
# Handle this event globally and then forward it.
def create_process(self, event):
print "New process created, PID: %d" % event.get_pid()
return self.event(event)
# All other events will be forwarded.
Note that overriding the C{event} method would cause no events to be
forwarded at all. To prevent this, call the superclass implementation.
Example::
def we_want_to_forward_this_event(event):
"Use whatever logic you want here..."
# (...return True or False...)
class MySift (EventSift):
def event(self, event):
# If the event matches some custom criteria...
if we_want_to_forward_this_event(event):
# Forward it.
return super(MySift, self).event(event)
# Otherwise, don't.
@type cls: class
@ivar cls:
Event handler class. There will be one instance of this class
per debugged process in the L{forward} dictionary.
@type argv: list
@ivar argv:
Positional arguments to pass to the constructor of L{cls}.
@type argd: list
@ivar argd:
Keyword arguments to pass to the constructor of L{cls}.
@type forward: dict
@ivar forward:
Dictionary that maps each debugged process ID to an instance of L{cls}.
"""
def __init__(self, cls, *argv, **argd):
"""
Maintains an instance of your event handler for each process being
debugged, and forwards the events of each process to each corresponding
instance.
@warn: If you subclass L{EventSift} and reimplement this method,
don't forget to call the superclass constructor!
@see: L{event}
@type cls: class
@param cls: Event handler class. This must be the class itself, not an
instance! All additional arguments passed to the constructor of
the event forwarder will be passed on to the constructor of this
class as well.
"""
self.cls = cls
self.argv = argv
self.argd = argd
self.forward = dict()
super(EventSift, self).__init__()
# XXX HORRIBLE HACK
# This makes apiHooks work in the inner handlers.
def __call__(self, event):
try:
eventCode = event.get_event_code()
if eventCode in (win32.LOAD_DLL_DEBUG_EVENT,
win32.LOAD_DLL_DEBUG_EVENT):
pid = event.get_pid()
handler = self.forward.get(pid, None)
if handler is None:
handler = self.cls(*self.argv, **self.argd)
self.forward[pid] = handler
if isinstance(handler, EventHandler):
if eventCode == win32.LOAD_DLL_DEBUG_EVENT:
handler.__EventHandler_hook_dll(event)
else:
handler.__EventHandler_unhook_dll(event)
finally:
return super(EventSift, self).__call__(event)
def event(self, event):
"""
Forwards events to the corresponding instance of your event handler
for this process.
If you subclass L{EventSift} and reimplement this method, no event
will be forwarded at all unless you call the superclass implementation.
If your filtering is based on the event type, there's a much easier way
to do it: just implement a handler for it.
"""
eventCode = event.get_event_code()
pid = event.get_pid()
handler = self.forward.get(pid, None)
if handler is None:
handler = self.cls(*self.argv, **self.argd)
if eventCode != win32.EXIT_PROCESS_DEBUG_EVENT:
self.forward[pid] = handler
elif eventCode == win32.EXIT_PROCESS_DEBUG_EVENT:
del self.forward[pid]
return handler(event)
#==============================================================================
class EventDispatcher (object):
"""
Implements debug event dispatching capabilities.
@group Debugging events:
get_event_handler, set_event_handler, get_handler_method
"""
# Maps event code constants to the names of the pre-notify routines.
# These routines are called BEFORE the user-defined handlers.
# Unknown codes are ignored.
__preEventNotifyCallbackName = {
win32.CREATE_THREAD_DEBUG_EVENT : '_notify_create_thread',
win32.CREATE_PROCESS_DEBUG_EVENT : '_notify_create_process',
win32.LOAD_DLL_DEBUG_EVENT : '_notify_load_dll',
}
# Maps event code constants to the names of the post-notify routines.
# These routines are called AFTER the user-defined handlers.
# Unknown codes are ignored.
__postEventNotifyCallbackName = {
win32.EXIT_THREAD_DEBUG_EVENT : '_notify_exit_thread',
win32.EXIT_PROCESS_DEBUG_EVENT : '_notify_exit_process',
win32.UNLOAD_DLL_DEBUG_EVENT : '_notify_unload_dll',
win32.RIP_EVENT : '_notify_rip',
}
# Maps exception code constants to the names of the pre-notify routines.
# These routines are called BEFORE the user-defined handlers.
# Unknown codes are ignored.
__preExceptionNotifyCallbackName = {
win32.EXCEPTION_BREAKPOINT : '_notify_breakpoint',
win32.EXCEPTION_WX86_BREAKPOINT : '_notify_breakpoint',
win32.EXCEPTION_SINGLE_STEP : '_notify_single_step',
win32.EXCEPTION_GUARD_PAGE : '_notify_guard_page',
win32.DBG_CONTROL_C : '_notify_debug_control_c',
win32.MS_VC_EXCEPTION : '_notify_ms_vc_exception',
}
# Maps exception code constants to the names of the post-notify routines.
# These routines are called AFTER the user-defined handlers.
# Unknown codes are ignored.
__postExceptionNotifyCallbackName = {
}
def __init__(self, eventHandler = None):
"""
Event dispatcher.
@type eventHandler: L{EventHandler}
@param eventHandler: (Optional) User-defined event handler.
@raise TypeError: The event handler is of an incorrect type.
@note: The L{eventHandler} parameter may be any callable Python object
(for example a function, or an instance method).
However you'll probably find it more convenient to use an instance
of a subclass of L{EventHandler} here.
"""
self.set_event_handler(eventHandler)
def get_event_handler(self):
"""
Get the event handler.
@see: L{set_event_handler}
@rtype: L{EventHandler}
@return: Current event handler object, or C{None}.
"""
return self.__eventHandler
def set_event_handler(self, eventHandler):
"""
Set the event handler.
@warn: This is normally not needed. Use with care!
@type eventHandler: L{EventHandler}
@param eventHandler: New event handler object, or C{None}.
@rtype: L{EventHandler}
@return: Previous event handler object, or C{None}.
@raise TypeError: The event handler is of an incorrect type.
@note: The L{eventHandler} parameter may be any callable Python object
(for example a function, or an instance method).
However you'll probably find it more convenient to use an instance
of a subclass of L{EventHandler} here.
"""
if eventHandler is not None and not callable(eventHandler):
raise TypeError("Event handler must be a callable object")
try:
wrong_type = issubclass(eventHandler, EventHandler)
except TypeError:
wrong_type = False
if wrong_type:
classname = str(eventHandler)
msg = "Event handler must be an instance of class %s"
msg += "rather than the %s class itself. (Missing parens?)"
msg = msg % (classname, classname)
raise TypeError(msg)
try:
previous = self.__eventHandler
except AttributeError:
previous = None
self.__eventHandler = eventHandler
return previous
@staticmethod
def get_handler_method(eventHandler, event, fallback=None):
"""
Retrieves the appropriate callback method from an L{EventHandler}
instance for the given L{Event} object.
@type eventHandler: L{EventHandler}
@param eventHandler:
Event handler object whose methods we are examining.
@type event: L{Event}
@param event: Debugging event to be handled.
@type fallback: callable
@param fallback: (Optional) If no suitable method is found in the
L{EventHandler} instance, return this value.
@rtype: callable
@return: Bound method that will handle the debugging event.
Returns C{None} if no such method is defined.
"""
eventCode = event.get_event_code()
method = getattr(eventHandler, 'event', fallback)
if eventCode == win32.EXCEPTION_DEBUG_EVENT:
method = getattr(eventHandler, 'exception', method)
method = getattr(eventHandler, event.eventMethod, method)
return method
def dispatch(self, event):
"""
Sends event notifications to the L{Debug} object and
the L{EventHandler} object provided by the user.
The L{Debug} object will forward the notifications to it's contained
snapshot objects (L{System}, L{Process}, L{Thread} and L{Module}) when
appropriate.
@warning: This method is called automatically from L{Debug.dispatch}.
@see: L{Debug.cont}, L{Debug.loop}, L{Debug.wait}
@type event: L{Event}
@param event: Event object passed to L{Debug.dispatch}.
@raise WindowsError: Raises an exception on error.
"""
returnValue = None
bCallHandler = True
pre_handler = None
post_handler = None
eventCode = event.get_event_code()
# Get the pre and post notification methods for exceptions.
# If not found, the following steps take care of that.
if eventCode == win32.EXCEPTION_DEBUG_EVENT:
exceptionCode = event.get_exception_code()
pre_name = self.__preExceptionNotifyCallbackName.get(
exceptionCode, None)
post_name = self.__postExceptionNotifyCallbackName.get(
exceptionCode, None)
if pre_name is not None:
pre_handler = getattr(self, pre_name, None)
if post_name is not None:
post_handler = getattr(self, post_name, None)
# Get the pre notification method for all other events.
# This includes the exception event if no notify method was found
# for this exception code.
if pre_handler is None:
pre_name = self.__preEventNotifyCallbackName.get(eventCode, None)
if pre_name is not None:
pre_handler = getattr(self, pre_name, pre_handler)
# Get the post notification method for all other events.
# This includes the exception event if no notify method was found
# for this exception code.
if post_handler is None:
post_name = self.__postEventNotifyCallbackName.get(eventCode, None)
if post_name is not None:
post_handler = getattr(self, post_name, post_handler)
# Call the pre-notify method only if it was defined.
# If an exception is raised don't call the other methods.
if pre_handler is not None:
bCallHandler = pre_handler(event)
# Call the user-defined event handler only if the pre-notify
# method was not defined, or was and it returned True.
try:
if bCallHandler and self.__eventHandler is not None:
try:
returnValue = self.__eventHandler(event)
except Exception:
e = sys.exc_info()[1]
msg = ("Event handler pre-callback %r"
" raised an exception: %s")
msg = msg % (self.__eventHandler, traceback.format_exc(e))
warnings.warn(msg, EventCallbackWarning)
returnValue = None
# Call the post-notify method if defined, even if an exception is
# raised by the user-defined event handler.
finally:
if post_handler is not None:
post_handler(event)
# Return the value from the call to the user-defined event handler.
# If not defined return None.
return returnValue
| 67,241 | Python | 34.958289 | 89 | 0.583186 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/process.py | #!~/.wine/drive_c/Python25/python.exe
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Process instrumentation.
@group Instrumentation:
Process
"""
from __future__ import with_statement
# FIXME
# I've been told the host process for the latest versions of VMWare
# can't be instrumented, because they try to stop code injection into the VMs.
# The solution appears to be to run the debugger from a user account that
# belongs to the VMware group. I haven't confirmed this yet.
__revision__ = "$Id$"
__all__ = ['Process']
import sys
from winappdbg import win32
from winappdbg import compat
from winappdbg.textio import HexDump, HexInput
from winappdbg.util import Regenerator, PathOperations, MemoryAddresses
from winappdbg.module import Module, _ModuleContainer
from winappdbg.thread import Thread, _ThreadContainer
from winappdbg.window import Window
from winappdbg.search import Search, \
Pattern, BytePattern, TextPattern, RegExpPattern, HexPattern
from winappdbg.disasm import Disassembler
import re
import os
import os.path
import ctypes
import struct
import warnings
import traceback
# delayed import
System = None
#==============================================================================
# TODO
# * Remote GetLastError()
# * The memory operation methods do not take into account that code breakpoints
# change the memory. This object should talk to BreakpointContainer to
# retrieve the original memory contents where code breakpoints are enabled.
# * A memory cache could be implemented here.
class Process (_ThreadContainer, _ModuleContainer):
"""
Interface to a process. Contains threads and modules snapshots.
@group Properties:
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
@group Instrumentation:
kill, wait, suspend, resume, inject_code, inject_dll, clean_exit
@group Disassembly:
disassemble, disassemble_around, disassemble_around_pc,
disassemble_string, disassemble_instruction, disassemble_current
@group Debugging:
flush_instruction_cache, debug_break, peek_pointers_in_data
@group Memory mapping:
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
@group Memory allocation:
malloc, free, mprotect, mquery
@group Memory read:
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
@group Memory write:
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
@group Memory search:
search, search_bytes, search_hexa, search_text, search_regexp, strings
@group Processes snapshot:
scan, clear, __contains__, __iter__, __len__
@group Deprecated:
get_environment_data, parse_environment_data
@type dwProcessId: int
@ivar dwProcessId: Global process ID. Use L{get_pid} instead.
@type hProcess: L{ProcessHandle}
@ivar hProcess: Handle to the process. Use L{get_handle} instead.
@type fileName: str
@ivar fileName: Filename of the main module. Use L{get_filename} instead.
"""
def __init__(self, dwProcessId, hProcess = None, fileName = None):
"""
@type dwProcessId: int
@param dwProcessId: Global process ID.
@type hProcess: L{ProcessHandle}
@param hProcess: Handle to the process.
@type fileName: str
@param fileName: (Optional) Filename of the main module.
"""
_ThreadContainer.__init__(self)
_ModuleContainer.__init__(self)
self.dwProcessId = dwProcessId
self.hProcess = hProcess
self.fileName = fileName
def get_pid(self):
"""
@rtype: int
@return: Process global ID.
"""
return self.dwProcessId
def get_filename(self):
"""
@rtype: str
@return: Filename of the main module of the process.
"""
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.
@warn: Normally you should call L{get_handle} instead, since it's much
"smarter" and tries to reuse handles and merge access rights.
@type dwDesiredAccess: int
@param dwDesiredAccess: Desired access rights.
Defaults to L{win32.PROCESS_ALL_ACCESS}.
See: U{http://msdn.microsoft.com/en-us/library/windows/desktop/ms684880(v=vs.85).aspx}
@raise WindowsError: It's not possible to open a handle to the process
with the requested access rights. This tipically happens because
the target process is a system process and the debugger is not
runnning with administrative rights.
"""
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.
@note: Normally you don't need to call this method. All handles
created by I{WinAppDbg} are automatically closed when the garbage
collector claims them. So unless you've been tinkering with it,
setting L{hProcess} to C{None} should be enough.
"""
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.
@note:
If a handle was previously opened and has the required access
rights, it's reused. If not, a new handle is opened with the
combination of the old and new access rights.
@type dwDesiredAccess: int
@param dwDesiredAccess: Desired access rights.
Defaults to L{win32.PROCESS_ALL_ACCESS}.
See: U{http://msdn.microsoft.com/en-us/library/windows/desktop/ms684880(v=vs.85).aspx}
@rtype: L{ProcessHandle}
@return: Handle to the process.
@raise WindowsError: It's not possible to open a handle to the process
with the requested access rights. This tipically happens because
the target process is a system process and the debugger is not
runnning with administrative rights.
"""
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)}
@type anObject: L{Thread}, L{Module} or int
@param anObject: Object to look for.
Can be a Thread, Module, thread global ID or module base address.
@rtype: bool
@return: C{True} if the requested object was found in the snapshot.
"""
return _ThreadContainer.__contains__(self, anObject) or \
_ModuleContainer.__contains__(self, anObject)
def __len__(self):
"""
@see: L{get_thread_count}, L{get_module_count}
@rtype: int
@return: Count of L{Thread} and L{Module} objects in this snapshot.
"""
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):
"""
@type container: L{Process}
@param container: L{Thread} and L{Module} 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):
"""
@see: L{iter_threads}, L{iter_modules}
@rtype: iterator
@return: Iterator of L{Thread} and L{Module} objects in this snapshot.
All threads are iterated first, then all modules.
"""
return self.__ThreadsAndModulesIterator(self)
#------------------------------------------------------------------------------
def wait(self, dwTimeout = None):
"""
Waits for the process to finish executing.
@raise WindowsError: On error an exception is raised.
"""
self.get_handle(win32.SYNCHRONIZE).wait(dwTimeout)
def kill(self, dwExitCode = 0):
"""
Terminates the execution of the process.
@raise WindowsError: On error an exception is raised.
"""
hProcess = self.get_handle(win32.PROCESS_TERMINATE)
win32.TerminateProcess(hProcess, dwExitCode)
def suspend(self):
"""
Suspends execution on all threads of the process.
@raise WindowsError: On error an exception is raised.
"""
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.
@raise WindowsError: On error an exception is raised.
"""
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.
@rtype: bool
@return: C{True} if the process has a debugger attached.
@warning:
May return inaccurate results when some anti-debug techniques are
used by the target process.
@note: To know if a process currently being debugged by a L{Debug}
object, call L{Debug.is_debugee} instead.
"""
# 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):
"""
@rtype: bool
@return: C{True} if the process is currently running.
"""
try:
self.wait(0)
except WindowsError:
e = sys.exc_info()[1]
return e.winerror == win32.WAIT_TIMEOUT
return False
def get_exit_code(self):
"""
@rtype: int
@return: Process exit code, or C{STILL_ACTIVE} if it's still alive.
@warning: If a process returns C{STILL_ACTIVE} as it's exit code,
you may not be able to determine if it's active or not with this
method. Use L{is_alive} to check if the process is still active.
Alternatively you can call L{get_handle} to get the handle object
and then L{ProcessHandle.wait} on it to wait until the process
finishes running.
"""
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.
@type disasm: list of tuple(int, int, str, str)
@param disasm: Output of one of the dissassembly functions.
"""
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.
@type lpAddress: int
@param lpAddress: Memory address where the code was read from.
@type code: str
@param code: Binary code to disassemble.
@rtype: list of tuple( long, int, str, str )
@return: List of tuples. Each tuple represents an assembly instruction
and contains:
- Memory address of instruction.
- Size of instruction in bytes.
- Disassembly line of instruction.
- Hexadecimal dump of instruction.
@raise NotImplementedError:
No compatible disassembler was found for the current platform.
"""
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.
@type lpAddress: int
@param lpAddress: Memory address where to read the code from.
@type dwSize: int
@param dwSize: Size of binary code to disassemble.
@rtype: list of tuple( long, int, str, str )
@return: List of tuples. Each tuple represents an assembly instruction
and contains:
- Memory address of instruction.
- Size of instruction in bytes.
- Disassembly line of instruction.
- Hexadecimal dump of instruction.
"""
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.
@type lpAddress: int
@param lpAddress: Memory address where to read the code from.
@type dwSize: int
@param dwSize: Delta offset.
Code will be read from lpAddress - dwSize to lpAddress + dwSize.
@rtype: list of tuple( long, int, str, str )
@return: List of tuples. Each tuple represents an assembly instruction
and contains:
- Memory address of instruction.
- Size of instruction in bytes.
- Disassembly line of instruction.
- Hexadecimal dump of instruction.
"""
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.
@type dwThreadId: int
@param dwThreadId: Global thread ID.
The program counter for this thread will be used as the disassembly
address.
@type dwSize: int
@param dwSize: Delta offset.
Code will be read from pc - dwSize to pc + dwSize.
@rtype: list of tuple( long, int, str, str )
@return: List of tuples. Each tuple represents an assembly instruction
and contains:
- Memory address of instruction.
- Size of instruction in bytes.
- Disassembly line of instruction.
- Hexadecimal dump of instruction.
"""
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.
@type lpAddress: int
@param lpAddress: Memory address where to read the code from.
@rtype: tuple( long, int, str, str )
@return: The tuple represents an assembly instruction
and contains:
- Memory address of instruction.
- Size of instruction in bytes.
- Disassembly line of instruction.
- Hexadecimal dump of instruction.
"""
return self.disassemble(lpAddress, 15)[0]
def disassemble_current(self, dwThreadId):
"""
Disassemble the instruction at the program counter of the given thread.
@type dwThreadId: int
@param dwThreadId: Global thread ID.
The program counter for this thread will be used as the disassembly
address.
@rtype: tuple( long, int, str, str )
@return: The tuple represents an assembly instruction
and contains:
- Memory address of instruction.
- Size of instruction in bytes.
- Disassembly line of instruction.
- Hexadecimal dump of instruction.
"""
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.
@see: U{http://blogs.msdn.com/oldnewthing/archive/2003/12/08/55954.aspx#55958}
@raise WindowsError: Raises exception on error.
"""
# 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.
@raise WindowsError: On error an exception is raised.
"""
# 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.
@rtype: bool
@return:
C{True} if the process is running under WOW64. That is, a 32-bit
application running in a 64-bit Windows.
C{False} if the process is either a 32-bit application running in
a 32-bit Windows, or a 64-bit application running in a 64-bit
Windows.
@raise WindowsError: On error an exception is raised.
@see: U{http://msdn.microsoft.com/en-us/library/aa384249(VS.85).aspx}
"""
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):
"""
@rtype: str
@return: The architecture in which this process believes to be running.
For example, if running a 32 bit binary in a 64 bit machine, the
architecture returned by this method will be 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):
"""
@rtype: str
@return: The number of bits in which this process believes to be
running. For example, if running a 32 bit binary in a 64 bit
machine, the number of bits returned by this method will be 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.
@rtype: win32.SYSTEMTIME
@return: Process start time.
"""
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.
@rtype: win32.SYSTEMTIME
@return: Process exit time.
"""
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.
@rtype: long
@return: Process running time in milliseconds.
"""
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.
@see: L{System.get_services}
@rtype: list( L{win32.ServiceStatusProcessEntry} )
@return: List of service status descriptors.
"""
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.
@note: This method is only available in Windows XP SP3 and above, and
only for 32 bit processes. It will fail in any other circumstance.
@see: U{http://msdn.microsoft.com/en-us/library/bb736297(v=vs.85).aspx}
@rtype: tuple(int, int)
@return:
The first member of the tuple is the DEP flags. It can be a
combination of the following values:
- 0: DEP is disabled for this process.
- 1: DEP is enabled for this process. (C{PROCESS_DEP_ENABLE})
- 2: DEP-ATL thunk emulation is disabled for this process.
(C{PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION})
The second member of the tuple is the permanent flag. If C{TRUE}
the DEP settings cannot be changed in runtime for this process.
@raise WindowsError: On error an exception is raised.
"""
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}.
@rtype: L{win32.PEB}
@return: PEB structure.
@raise WindowsError: An exception is raised on error.
"""
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.
@rtype: int
@return: Remote pointer to the L{win32.PEB} structure.
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()}.
@rtype: int
@return: Address of the entry point of the main module.
"""
return self.get_main_module().get_entry_point()
def get_main_module(self):
"""
@rtype: L{Module}
@return: Module object for the process main module.
"""
return self.get_module(self.get_image_base())
def get_image_base(self):
"""
@rtype: int
@return: Image base address for the process main module.
"""
return self.get_peb().ImageBaseAddress
def get_image_name(self):
"""
@rtype: int
@return: Filename of the process main module.
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.
@rtype: tuple(int, int)
@return: Tuple with the memory address of the command line block
and it's maximum size in Unicode characters.
@raise WindowsError: On error an exception is raised.
"""
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.
@note: The size is always enough to contain the environment data, but
it may not be an exact size. It's best to read the memory and
scan for two null wide chars to find the actual size.
@rtype: tuple(int, int)
@return: Tuple with the memory address of the environment block
and it's size.
@raise WindowsError: On error an exception is raised.
"""
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.
@rtype: str
@return: Command line string.
@raise WindowsError: On error an exception is raised.
"""
(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.
@rtype: list of tuple(compat.unicode, compat.unicode)
@return: Environment keys and values as found in the process memory.
@raise WindowsError: On error an exception is raised.
"""
# 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.
@warn: Deprecated since WinAppDbg 1.5.
@see: L{win32.GuessStringType}
@type fUnicode: bool or None
@param fUnicode: C{True} to return a list of Unicode strings, C{False}
to return a list of ANSI strings, or C{None} to return whatever
the default is for string types.
@rtype: list of str
@return: Environment keys and values separated by a (C{=}) character,
as found in the process memory.
@raise WindowsError: On error an exception is raised.
"""
# 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
@staticmethod
def parse_environment_data(block):
"""
Parse the environment block into a Python dictionary.
@warn: Deprecated since WinAppDbg 1.5.
@note: Values of duplicated keys are joined using null characters.
@type block: list of str
@param block: List of strings as returned by L{get_environment_data}.
@rtype: dict(str S{->} str)
@return: Dictionary of environment keys and values.
"""
# 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.
@note: Duplicated keys are joined using null characters.
To avoid this behavior, call L{get_environment_variables} instead
and convert the results to a dictionary directly, like this:
C{dict(process.get_environment_variables())}
@see: L{win32.GuessStringType}
@type fUnicode: bool or None
@param fUnicode: C{True} to return a list of Unicode strings, C{False}
to return a list of ANSI strings, or C{None} to return whatever
the default is for string types.
@rtype: dict(str S{->} str)
@return: Dictionary of environment keys and values.
@raise WindowsError: On error an exception is raised.
"""
# 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.
@type pattern: str, compat.unicode or L{Pattern}
@param pattern: Pattern to search for.
It may be a byte string, a Unicode string, or an instance of
L{Pattern}.
The following L{Pattern} subclasses are provided by WinAppDbg:
- L{BytePattern}
- L{TextPattern}
- L{RegExpPattern}
- L{HexPattern}
You can also write your own subclass of L{Pattern} for customized
searches.
@type minAddr: int
@param minAddr: (Optional) Start the search at this memory address.
@type maxAddr: int
@param maxAddr: (Optional) Stop the search at this memory address.
@rtype: iterator of tuple( int, int, str )
@return: An iterator of tuples. Each tuple contains the following:
- The memory address where the pattern was found.
- The size of the data that matches the pattern.
- The data that matches the pattern.
@raise WindowsError: An error occurred when querying or reading the
process memory.
"""
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.
@type bytes: str
@param bytes: Bytes to search for.
@type minAddr: int
@param minAddr: (Optional) Start the search at this memory address.
@type maxAddr: int
@param maxAddr: (Optional) Stop the search at this memory address.
@rtype: iterator of int
@return: An iterator of memory addresses where the pattern was found.
@raise WindowsError: An error occurred when querying or reading the
process memory.
"""
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.
@type text: str or compat.unicode
@param text: Text to search for.
@type encoding: str
@param encoding: (Optional) Encoding for the text parameter.
Only used when the text to search for is a Unicode string.
Don't change unless you know what you're doing!
@type caseSensitive: bool
@param caseSensitive: C{True} of the search is case sensitive,
C{False} otherwise.
@type minAddr: int
@param minAddr: (Optional) Start the search at this memory address.
@type maxAddr: int
@param maxAddr: (Optional) Stop the search at this memory address.
@rtype: iterator of tuple( int, str )
@return: An iterator of tuples. Each tuple contains the following:
- The memory address where the pattern was found.
- The text that matches the pattern.
@raise WindowsError: An error occurred when querying or reading the
process memory.
"""
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.
@type regexp: str
@param regexp: Regular expression string.
@type flags: int
@param flags: Regular expression flags.
@type minAddr: int
@param minAddr: (Optional) Start the search at this memory address.
@type maxAddr: int
@param maxAddr: (Optional) Stop the search at this memory address.
@type bufferPages: int
@param bufferPages: (Optional) Number of memory pages to buffer when
performing the search. Valid values are:
- C{0} or C{None}:
Automatically determine the required buffer size. May not give
complete results for regular expressions that match variable
sized strings.
- C{> 0}: Set the buffer size, in memory pages.
- C{< 0}: Disable buffering entirely. This may give you a little
speed gain at the cost of an increased memory usage. If the
target process has very large contiguous memory regions it may
actually be slower or even fail. It's also the only way to
guarantee complete results for regular expressions that match
variable sized strings.
@rtype: iterator of tuple( int, int, str )
@return: An iterator of tuples. Each tuple contains the following:
- The memory address where the pattern was found.
- The size of the data that matches the pattern.
- The data that matches the pattern.
@raise WindowsError: An error occurred when querying or reading the
process memory.
"""
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
@type hexa: str
@param hexa: Pattern to search for.
@type minAddr: int
@param minAddr: (Optional) Start the search at this memory address.
@type maxAddr: int
@param maxAddr: (Optional) Stop the search at this memory address.
@rtype: iterator of tuple( int, str )
@return: An iterator of tuples. Each tuple contains the following:
- The memory address where the pattern was found.
- The bytes that match the pattern.
@raise WindowsError: An error occurred when querying or reading the
process memory.
"""
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.
@type minSize: int
@param minSize: (Optional) Minimum size of the strings to search for.
@type maxSize: int
@param maxSize: (Optional) Maximum size of the strings to search for.
@rtype: iterator of tuple(int, int, str)
@return: Iterator of strings extracted from the process memory.
Each tuple contains the following:
- The memory address where the string was found.
- The size of the string.
- The string.
"""
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.
@see: L{peek}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin reading.
@type nSize: int
@param nSize: Number of bytes to read.
@rtype: str
@return: Bytes read from the process memory.
@raise WindowsError: On error an exception is raised.
"""
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.
@note: Page permissions may be changed temporarily while writing.
@see: L{poke}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin writing.
@type lpBuffer: str
@param lpBuffer: Bytes to write.
@raise WindowsError: On error an exception is raised.
"""
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.
@see: L{peek_char}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin writing.
@rtype: int
@return: Character value read from the process memory.
@raise WindowsError: On error an exception is raised.
"""
return ord( self.read(lpBaseAddress, 1) )
def write_char(self, lpBaseAddress, char):
"""
Writes a single character to the memory of the process.
@note: Page permissions may be changed temporarily while writing.
@see: L{poke_char}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin writing.
@type char: int
@param char: Character to write.
@raise WindowsError: On error an exception is raised.
"""
self.write(lpBaseAddress, chr(char))
def read_int(self, lpBaseAddress):
"""
Reads a signed integer from the memory of the process.
@see: L{peek_int}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin reading.
@rtype: int
@return: Integer value read from the process memory.
@raise WindowsError: On error an exception is raised.
"""
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.
@note: Page permissions may be changed temporarily while writing.
@see: L{poke_int}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin writing.
@type unpackedValue: int, long
@param unpackedValue: Value to write.
@raise WindowsError: On error an exception is raised.
"""
self.__write_c_type(lpBaseAddress, '@l', unpackedValue)
def read_uint(self, lpBaseAddress):
"""
Reads an unsigned integer from the memory of the process.
@see: L{peek_uint}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin reading.
@rtype: int
@return: Integer value read from the process memory.
@raise WindowsError: On error an exception is raised.
"""
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.
@note: Page permissions may be changed temporarily while writing.
@see: L{poke_uint}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin writing.
@type unpackedValue: int, long
@param unpackedValue: Value to write.
@raise WindowsError: On error an exception is raised.
"""
self.__write_c_type(lpBaseAddress, '@L', unpackedValue)
def read_float(self, lpBaseAddress):
"""
Reads a float from the memory of the process.
@see: L{peek_float}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin reading.
@rtype: int
@return: Floating point value read from the process memory.
@raise WindowsError: On error an exception is raised.
"""
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.
@note: Page permissions may be changed temporarily while writing.
@see: L{poke_float}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin writing.
@type unpackedValue: int, long
@param unpackedValue: Floating point value to write.
@raise WindowsError: On error an exception is raised.
"""
self.__write_c_type(lpBaseAddress, '@f', unpackedValue)
def read_double(self, lpBaseAddress):
"""
Reads a double from the memory of the process.
@see: L{peek_double}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin reading.
@rtype: int
@return: Floating point value read from the process memory.
@raise WindowsError: On error an exception is raised.
"""
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.
@note: Page permissions may be changed temporarily while writing.
@see: L{poke_double}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin writing.
@type unpackedValue: int, long
@param unpackedValue: Floating point value to write.
@raise WindowsError: On error an exception is raised.
"""
self.__write_c_type(lpBaseAddress, '@d', unpackedValue)
def read_pointer(self, lpBaseAddress):
"""
Reads a pointer value from the memory of the process.
@see: L{peek_pointer}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin reading.
@rtype: int
@return: Pointer value read from the process memory.
@raise WindowsError: On error an exception is raised.
"""
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.
@note: Page permissions may be changed temporarily while writing.
@see: L{poke_pointer}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin writing.
@type unpackedValue: int, long
@param unpackedValue: Value to write.
@raise WindowsError: On error an exception is raised.
"""
self.__write_c_type(lpBaseAddress, '@P', unpackedValue)
def read_dword(self, lpBaseAddress):
"""
Reads a DWORD from the memory of the process.
@see: L{peek_dword}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin reading.
@rtype: int
@return: Integer value read from the process memory.
@raise WindowsError: On error an exception is raised.
"""
return self.__read_c_type(lpBaseAddress, '=L', win32.DWORD)
def write_dword(self, lpBaseAddress, unpackedValue):
"""
Writes a DWORD to the memory of the process.
@note: Page permissions may be changed temporarily while writing.
@see: L{poke_dword}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin writing.
@type unpackedValue: int, long
@param unpackedValue: Value to write.
@raise WindowsError: On error an exception is raised.
"""
self.__write_c_type(lpBaseAddress, '=L', unpackedValue)
def read_qword(self, lpBaseAddress):
"""
Reads a QWORD from the memory of the process.
@see: L{peek_qword}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin reading.
@rtype: int
@return: Integer value read from the process memory.
@raise WindowsError: On error an exception is raised.
"""
return self.__read_c_type(lpBaseAddress, '=Q', win32.QWORD)
def write_qword(self, lpBaseAddress, unpackedValue):
"""
Writes a QWORD to the memory of the process.
@note: Page permissions may be changed temporarily while writing.
@see: L{poke_qword}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin writing.
@type unpackedValue: int, long
@param unpackedValue: Value to write.
@raise WindowsError: On error an exception is raised.
"""
self.__write_c_type(lpBaseAddress, '=Q', unpackedValue)
def read_structure(self, lpBaseAddress, stype):
"""
Reads a ctypes structure from the memory of the process.
@see: L{read}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin reading.
@type stype: class ctypes.Structure or a subclass.
@param stype: Structure definition.
@rtype: int
@return: Structure instance filled in with data
read from the process memory.
@raise WindowsError: On error an exception is raised.
"""
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.
@see: L{peek_string}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin reading.
@type nChars: int
@param nChars: String length to read, in characters.
Remember that Unicode strings have two byte characters.
@type fUnicode: bool
@param fUnicode: C{True} is the string is expected to be Unicode,
C{False} if it's expected to be ANSI.
@rtype: str, compat.unicode
@return: String read from the process memory space.
@raise WindowsError: On error an exception is raised.
"""
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.
@see: L{read}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin reading.
@type nSize: int
@param nSize: Number of bytes to read.
@rtype: str
@return: Bytes read from the process memory.
Returns an empty string on error.
"""
# 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.
@note: Page permissions may be changed temporarily while writing.
@see: L{write}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin writing.
@type lpBuffer: str
@param lpBuffer: Bytes to write.
@rtype: int
@return: Number of bytes written.
May be less than the number of bytes to write.
"""
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.
@see: L{read_char}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin reading.
@rtype: int
@return: Character read from the process memory.
Returns zero on error.
"""
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.
@note: Page permissions may be changed temporarily while writing.
@see: L{write_char}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin writing.
@type char: str
@param char: Character to write.
@rtype: int
@return: Number of bytes written.
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.
@see: L{read_int}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin reading.
@rtype: int
@return: Integer value read from the process memory.
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.
@note: Page permissions may be changed temporarily while writing.
@see: L{write_int}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin writing.
@type unpackedValue: int, long
@param unpackedValue: Value to write.
@rtype: int
@return: Number of bytes written.
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.
@see: L{read_uint}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin reading.
@rtype: int
@return: Integer value read from the process memory.
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.
@note: Page permissions may be changed temporarily while writing.
@see: L{write_uint}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin writing.
@type unpackedValue: int, long
@param unpackedValue: Value to write.
@rtype: int
@return: Number of bytes written.
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.
@see: L{read_float}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin reading.
@rtype: int
@return: Integer value read from the process memory.
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.
@note: Page permissions may be changed temporarily while writing.
@see: L{write_float}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin writing.
@type unpackedValue: int, long
@param unpackedValue: Value to write.
@rtype: int
@return: Number of bytes written.
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.
@see: L{read_double}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin reading.
@rtype: int
@return: Integer value read from the process memory.
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.
@note: Page permissions may be changed temporarily while writing.
@see: L{write_double}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin writing.
@type unpackedValue: int, long
@param unpackedValue: Value to write.
@rtype: int
@return: Number of bytes written.
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.
@see: L{read_dword}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin reading.
@rtype: int
@return: Integer value read from the process memory.
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.
@note: Page permissions may be changed temporarily while writing.
@see: L{write_dword}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin writing.
@type unpackedValue: int, long
@param unpackedValue: Value to write.
@rtype: int
@return: Number of bytes written.
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.
@see: L{read_qword}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin reading.
@rtype: int
@return: Integer value read from the process memory.
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.
@note: Page permissions may be changed temporarily while writing.
@see: L{write_qword}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin writing.
@type unpackedValue: int, long
@param unpackedValue: Value to write.
@rtype: int
@return: Number of bytes written.
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.
@see: L{read_pointer}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin reading.
@rtype: int
@return: Pointer value read from the process memory.
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.
@note: Page permissions may be changed temporarily while writing.
@see: L{write_pointer}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin writing.
@type unpackedValue: int, long
@param unpackedValue: Value to write.
@rtype: int
@return: Number of bytes written.
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.
@see: L{read_string}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin reading.
@type fUnicode: bool
@param fUnicode: C{True} is the string is expected to be Unicode,
C{False} if it's expected to be ANSI.
@type dwMaxSize: int
@param dwMaxSize: Maximum allowed string length to read, in bytes.
@rtype: str, compat.unicode
@return: String read from the process memory space.
It B{doesn't} include the terminating null character.
Returns an empty string on failure.
"""
# 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.
@see: L{peek}
@type data: str
@param data: Binary data to find pointers in.
@type peekSize: int
@param peekSize: Number of bytes to read from each pointer found.
@type peekStep: int
@param peekStep: Expected data alignment.
Tipically you specify 1 when data alignment is unknown,
or 4 when you expect data to be DWORD aligned.
Any other value may be specified.
@rtype: dict( str S{->} str )
@return: Dictionary mapping stack offsets to the data they point to.
"""
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.
@see: L{free}
@type dwSize: int
@param dwSize: Number of bytes to allocate.
@type lpAddress: int
@param lpAddress: (Optional)
Desired address for the newly allocated memory.
This is only a hint, the memory could still be allocated somewhere
else.
@rtype: int
@return: Address of the newly allocated memory.
@raise WindowsError: On error an exception is raised.
"""
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.
@see: U{http://msdn.microsoft.com/en-us/library/aa366899.aspx}
@type lpAddress: int
@param lpAddress: Address of memory to protect.
@type dwSize: int
@param dwSize: Number of bytes to protect.
@type flNewProtect: int
@param flNewProtect: New protect flags.
@rtype: int
@return: Old protect flags.
@raise WindowsError: On error an exception is raised.
"""
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.
@see: U{http://msdn.microsoft.com/en-us/library/aa366907(VS.85).aspx}
@type lpAddress: int
@param lpAddress: Address of memory to query.
@rtype: L{win32.MemoryBasicInformation}
@return: Memory region information.
@raise WindowsError: On error an exception is raised.
"""
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.
@see: U{http://msdn.microsoft.com/en-us/library/aa366894(v=vs.85).aspx}
@type lpAddress: int
@param lpAddress: Address of memory to free.
Must be the base address returned by L{malloc}.
@raise WindowsError: On error an exception is raised.
"""
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.
@type address: int
@param address: Memory address to query.
@rtype: bool
@return: C{True} if the address is a valid code or data pointer.
@raise WindowsError: An exception is raised on error.
"""
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.
@type address: int
@param address: Memory address to query.
@rtype: bool
@return: C{True} if the address is a valid user mode address.
@raise WindowsError: An exception is raised on error.
"""
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.
@note: Returns always C{False} for kernel mode addresses.
@type address: int
@param address: Memory address to query.
@rtype: bool
@return: C{True} if the address belongs to a free page.
@raise WindowsError: An exception is raised on error.
"""
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.
@note: Returns always C{False} for kernel mode addresses.
@type address: int
@param address: Memory address to query.
@rtype: bool
@return: C{True} if the address belongs to a reserved page.
@raise WindowsError: An exception is raised on error.
"""
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.
@note: Returns always C{False} for kernel mode addresses.
@type address: int
@param address: Memory address to query.
@rtype: bool
@return: C{True} if the address belongs to a commited page.
@raise WindowsError: An exception is raised on error.
"""
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.
@note: Returns always C{False} for kernel mode addresses.
@type address: int
@param address: Memory address to query.
@rtype: bool
@return: C{True} if the address belongs to a guard page.
@raise WindowsError: An exception is raised on error.
"""
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.
@note: Returns always C{False} for kernel mode addresses.
@type address: int
@param address: Memory address to query.
@rtype: bool
@return:
C{True} if the address belongs to a commited and readable page.
@raise WindowsError: An exception is raised on error.
"""
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.
@note: Returns always C{False} for kernel mode addresses.
@type address: int
@param address: Memory address to query.
@rtype: bool
@return:
C{True} if the address belongs to a commited and writeable page.
@raise WindowsError: An exception is raised on error.
"""
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.
@note: Returns always C{False} for kernel mode addresses.
@type address: int
@param address: Memory address to query.
@rtype: bool
@return:
C{True} if the address belongs to a commited, copy-on-write page.
@raise WindowsError: An exception is raised on error.
"""
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.
@note: Returns always C{False} for kernel mode addresses.
@type address: int
@param address: Memory address to query.
@rtype: bool
@return:
C{True} if the address belongs to a commited and executable page.
@raise WindowsError: An exception is raised on error.
"""
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.
@note: Returns always C{False} for kernel mode addresses.
@type address: int
@param address: Memory address to query.
@rtype: bool
@return:
C{True} if the address belongs to a commited, writeable and
executable page.
@raise WindowsError: An exception is raised on error.
"""
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.
@note: Returns always C{False} for kernel mode addresses.
@see: L{mquery}
@type address: int
@param address: Memory address.
@type size: int
@param size: Number of bytes. Must be greater than zero.
@rtype: bool
@return: C{True} if the memory area is a valid code or data buffer,
C{False} otherwise.
@raise ValueError: The size argument must be greater than zero.
@raise WindowsError: On error an exception is raised.
"""
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.
@note: Returns always C{False} for kernel mode addresses.
@see: L{mquery}
@type address: int
@param address: Memory address.
@type size: int
@param size: Number of bytes. Must be greater than zero.
@rtype: bool
@return: C{True} if the memory area is readable, C{False} otherwise.
@raise ValueError: The size argument must be greater than zero.
@raise WindowsError: On error an exception is raised.
"""
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.
@note: Returns always C{False} for kernel mode addresses.
@see: L{mquery}
@type address: int
@param address: Memory address.
@type size: int
@param size: Number of bytes. Must be greater than zero.
@rtype: bool
@return: C{True} if the memory area is writeable, C{False} otherwise.
@raise ValueError: The size argument must be greater than zero.
@raise WindowsError: On error an exception is raised.
"""
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.
@note: Returns always C{False} for kernel mode addresses.
@see: L{mquery}
@type address: int
@param address: Memory address.
@type size: int
@param size: Number of bytes. Must be greater than zero.
@rtype: bool
@return: C{True} if the memory area is marked as copy-on-write,
C{False} otherwise.
@raise ValueError: The size argument must be greater than zero.
@raise WindowsError: On error an exception is raised.
"""
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.
@note: Returns always C{False} for kernel mode addresses.
@see: L{mquery}
@type address: int
@param address: Memory address.
@type size: int
@param size: Number of bytes. Must be greater than zero.
@rtype: bool
@return: C{True} if the memory area is executable, C{False} otherwise.
@raise ValueError: The size argument must be greater than zero.
@raise WindowsError: On error an exception is raised.
"""
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.
@note: Returns always C{False} for kernel mode addresses.
@see: L{mquery}
@type address: int
@param address: Memory address.
@type size: int
@param size: Number of bytes. Must be greater than zero.
@rtype: bool
@return: C{True} if the memory area is writeable and executable,
C{False} otherwise.
@raise ValueError: The size argument must be greater than zero.
@raise WindowsError: On error an exception is raised.
"""
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.
@see: L{mquery}
@type minAddr: int
@param minAddr: (Optional) Starting address in address range to query.
@type maxAddr: int
@param maxAddr: (Optional) Ending address in address range to query.
@rtype: list( L{win32.MemoryBasicInformation} )
@return: List of memory region information objects.
"""
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.
@see: L{mquery}
@type minAddr: int
@param minAddr: (Optional) Starting address in address range to query.
@type maxAddr: int
@param maxAddr: (Optional) Ending address in address range to query.
@rtype: L{Regenerator} of L{win32.MemoryBasicInformation}
@return: List of memory region information objects.
"""
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.
@see: L{mquery}
@type minAddr: int
@param minAddr: (Optional) Starting address in address range to query.
@type maxAddr: int
@param maxAddr: (Optional) Ending address in address range to query.
@rtype: iterator of L{win32.MemoryBasicInformation}
@return: List of memory region information objects.
"""
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.
@type memoryMap: list( L{win32.MemoryBasicInformation} )
@param memoryMap: (Optional) Memory map returned by L{get_memory_map}.
If not given, the current memory map is used.
@rtype: dict( int S{->} str )
@return: Dictionary mapping memory addresses to file names.
Native filenames are converted to Win32 filenames when possible.
"""
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.
@see: L{take_memory_snapshot}
@type minAddr: int
@param minAddr: (Optional) Starting address in address range to query.
@type maxAddr: int
@param maxAddr: (Optional) Ending address in address range to query.
@rtype: L{Regenerator} of L{win32.MemoryBasicInformation}
@return: Generator that when iterated returns memory region information
objects. Two extra properties are added to these objects:
- C{filename}: Mapped filename, or C{None}.
- C{content}: Memory contents, or C{None}.
"""
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.
@see: L{take_memory_snapshot}
@type minAddr: int
@param minAddr: (Optional) Starting address in address range to query.
@type maxAddr: int
@param maxAddr: (Optional) Ending address in address range to query.
@rtype: iterator of L{win32.MemoryBasicInformation}
@return: Iterator of memory region information objects.
Two extra properties are added to these objects:
- C{filename}: Mapped filename, or C{None}.
- C{content}: Memory contents, or C{None}.
"""
# 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.
@warning: If the target process has a very big memory footprint, the
resulting snapshot will be equally big. This may result in a severe
performance penalty.
@see: L{generate_memory_snapshot}
@type minAddr: int
@param minAddr: (Optional) Starting address in address range to query.
@type maxAddr: int
@param maxAddr: (Optional) Ending address in address range to query.
@rtype: list( L{win32.MemoryBasicInformation} )
@return: List of memory region information objects.
Two extra properties are added to these objects:
- C{filename}: Mapped filename, or C{None}.
- C{content}: Memory contents, or C{None}.
"""
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.
@warning: Currently only the memory contents, state and protect bits
are restored. Under some circumstances this method may fail (for
example if memory was freed and then reused by a mapped file).
@type snapshot: list( L{win32.MemoryBasicInformation} )
@param snapshot: Memory snapshot returned by L{take_memory_snapshot}.
Snapshots returned by L{generate_memory_snapshot} don't work here.
@type bSkipMappedFiles: bool
@param bSkipMappedFiles: C{True} to avoid restoring the contents of
memory mapped files, C{False} otherwise. Use with care! Setting
this to C{False} can cause undesired side effects - changes to
memory mapped files may be written to disk by the OS. Also note
that most mapped files are typically executables and don't change,
so trying to restore their contents is usually a waste of time.
@type bSkipOnError: bool
@param bSkipOnError: C{True} to issue a warning when an error occurs
during the restoration of the snapshot, C{False} to stop and raise
an exception instead. Use with care! Setting this to C{True} will
cause the debugger to falsely believe the memory snapshot has been
correctly restored.
@raise WindowsError: An error occured while restoring the snapshot.
@raise RuntimeError: An error occured while restoring the snapshot.
@raise TypeError: A snapshot of the wrong type was passed.
"""
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.
@warning: Don't forget to free the memory when you're done with it!
Otherwise you'll be leaking memory in the target process.
@see: L{inject_dll}
@type payload: str
@param payload: Relocatable code to run in a new thread.
@type lpParameter: int
@param lpParameter: (Optional) Parameter to be pushed in the stack.
@rtype: tuple( L{Thread}, int )
@return: The injected Thread object
and the memory address where the code was written.
@raise WindowsError: An exception is raised on error.
"""
# 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.
@warning: Setting C{bWait} to C{True} when the process is frozen by a
debug event will cause a deadlock in your debugger.
@warning: This involves allocating memory in the target process.
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.
@see: L{inject_code}
@type dllname: str
@param dllname: Name of the DLL module to load.
@type procname: str
@param procname: (Optional) Procedure to call when the DLL is loaded.
@type lpParameter: int
@param lpParameter: (Optional) Parameter to the C{procname} procedure.
@type bWait: bool
@param bWait: C{True} to wait for the process to finish.
C{False} to return immediately.
@type dwTimeout: int
@param dwTimeout: (Optional) Timeout value in milliseconds.
Ignored if C{bWait} is C{False}.
@rtype: L{Thread}
@return: Newly created thread object. If C{bWait} is set to C{True} the
thread will be dead, otherwise it will be alive.
@raise NotImplementedError: The target platform is not supported.
Currently calling a procedure in the library is only supported in
the I{i386} architecture.
@raise WindowsError: An exception is raised on error.
"""
# 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.
@warning: Setting C{bWait} to C{True} when the process is frozen by a
debug event will cause a deadlock in your debugger.
@type dwExitCode: int
@param dwExitCode: Process exit code.
@type bWait: bool
@param bWait: C{True} to wait for the process to finish.
C{False} to return immediately.
@type dwTimeout: int
@param dwTimeout: (Optional) Timeout value in milliseconds.
Ignored if C{bWait} is C{False}.
@raise WindowsError: An exception is raised on error.
"""
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.
@type event: L{CreateProcessEvent}
@param event: Create process event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} otherwise.
"""
# Do not use super() here.
bCallHandler = _ThreadContainer._notify_create_process(self, event)
bCallHandler = bCallHandler and \
_ModuleContainer._notify_create_process(self, event)
return bCallHandler
#==============================================================================
class _ProcessContainer (object):
"""
Encapsulates the capability to contain Process objects.
@group Instrumentation:
start_process, argv_to_cmdline, cmdline_to_argv, get_explorer_pid
@group Processes snapshot:
scan, scan_processes, scan_processes_fast,
get_process, get_process_count, get_process_ids,
has_process, iter_processes, iter_process_ids,
find_processes_by_filename, get_pid_from_tid,
get_windows,
scan_process_filenames,
clear, clear_processes, clear_dead_processes,
clear_unattached_processes,
close_process_handles,
close_process_and_thread_handles
@group Threads snapshots:
scan_processes_and_threads,
get_thread, get_thread_count, get_thread_ids,
has_thread
@group Modules snapshots:
scan_modules, find_modules_by_address,
find_modules_by_base, find_modules_by_name,
get_module_count
"""
def __init__(self):
self.__processDict = dict()
def __initialize_snapshot(self):
"""
Private method to automatically initialize the snapshot
when you try to use it without calling any of the scan_*
methods first. You don't need to call this yourself.
"""
if not self.__processDict:
try:
self.scan_processes() # remote desktop api (relative fn)
except Exception:
self.scan_processes_fast() # psapi (no filenames)
self.scan_process_filenames() # get the pathnames when possible
def __contains__(self, anObject):
"""
@type anObject: L{Process}, L{Thread}, int
@param anObject:
- C{int}: Global ID of the process to look for.
- C{int}: Global ID of the thread to look for.
- C{Process}: Process object to look for.
- C{Thread}: Thread object to look for.
@rtype: bool
@return: C{True} if the snapshot contains
a L{Process} or L{Thread} object with the same ID.
"""
if isinstance(anObject, Process):
anObject = anObject.dwProcessId
if self.has_process(anObject):
return True
for aProcess in self.iter_processes():
if anObject in aProcess:
return True
return False
def __iter__(self):
"""
@see: L{iter_processes}
@rtype: dictionary-valueiterator
@return: Iterator of L{Process} objects in this snapshot.
"""
return self.iter_processes()
def __len__(self):
"""
@see: L{get_process_count}
@rtype: int
@return: Count of L{Process} objects in this snapshot.
"""
return self.get_process_count()
def has_process(self, dwProcessId):
"""
@type dwProcessId: int
@param dwProcessId: Global ID of the process to look for.
@rtype: bool
@return: C{True} if the snapshot contains a
L{Process} object with the given global ID.
"""
self.__initialize_snapshot()
return dwProcessId in self.__processDict
def get_process(self, dwProcessId):
"""
@type dwProcessId: int
@param dwProcessId: Global ID of the process to look for.
@rtype: L{Process}
@return: Process object with the given global ID.
"""
self.__initialize_snapshot()
if dwProcessId not in self.__processDict:
msg = "Unknown process ID %d" % dwProcessId
raise KeyError(msg)
return self.__processDict[dwProcessId]
def iter_process_ids(self):
"""
@see: L{iter_processes}
@rtype: dictionary-keyiterator
@return: Iterator of global process IDs in this snapshot.
"""
self.__initialize_snapshot()
return compat.iterkeys(self.__processDict)
def iter_processes(self):
"""
@see: L{iter_process_ids}
@rtype: dictionary-valueiterator
@return: Iterator of L{Process} objects in this snapshot.
"""
self.__initialize_snapshot()
return compat.itervalues(self.__processDict)
def get_process_ids(self):
"""
@see: L{iter_process_ids}
@rtype: list( int )
@return: List of global process IDs in this snapshot.
"""
self.__initialize_snapshot()
return compat.keys(self.__processDict)
def get_process_count(self):
"""
@rtype: int
@return: Count of L{Process} objects in this snapshot.
"""
self.__initialize_snapshot()
return len(self.__processDict)
#------------------------------------------------------------------------------
# XXX TODO
# Support for string searches on the window captions.
def get_windows(self):
"""
@rtype: list of L{Window}
@return: Returns a list of windows
handled by all processes in this snapshot.
"""
window_list = list()
for process in self.iter_processes():
window_list.extend( process.get_windows() )
return window_list
def get_pid_from_tid(self, dwThreadId):
"""
Retrieves the global ID of the process that owns the thread.
@type dwThreadId: int
@param dwThreadId: Thread global ID.
@rtype: int
@return: Process global ID.
@raise KeyError: The thread does not exist.
"""
try:
# No good, because in XP and below it tries to get the PID
# through the toolhelp API, and that's slow. We don't want
# to scan for threads over and over for each call.
## dwProcessId = Thread(dwThreadId).get_pid()
# This API only exists in Windows 2003, Vista and above.
try:
hThread = win32.OpenThread(
win32.THREAD_QUERY_LIMITED_INFORMATION, False, dwThreadId)
except WindowsError:
e = sys.exc_info()[1]
if e.winerror != win32.ERROR_ACCESS_DENIED:
raise
hThread = win32.OpenThread(
win32.THREAD_QUERY_INFORMATION, False, dwThreadId)
try:
return win32.GetProcessIdOfThread(hThread)
finally:
hThread.close()
# If all else fails, go through all processes in the snapshot
# looking for the one that owns the thread we're looking for.
# If the snapshot was empty the iteration should trigger an
# automatic scan. Otherwise, it'll look for the thread in what
# could possibly be an outdated snapshot.
except Exception:
for aProcess in self.iter_processes():
if aProcess.has_thread(dwThreadId):
return aProcess.get_pid()
# The thread wasn't found, so let's refresh the snapshot and retry.
# Normally this shouldn't happen since this function is only useful
# for the debugger, so the thread should already exist in the snapshot.
self.scan_processes_and_threads()
for aProcess in self.iter_processes():
if aProcess.has_thread(dwThreadId):
return aProcess.get_pid()
# No luck! It appears to be the thread doesn't exist after all.
msg = "Unknown thread ID %d" % dwThreadId
raise KeyError(msg)
#------------------------------------------------------------------------------
@staticmethod
def argv_to_cmdline(argv):
"""
Convert a list of arguments to a single command line string.
@type argv: list( str )
@param argv: List of argument strings.
The first element is the program to execute.
@rtype: str
@return: Command line string.
"""
cmdline = list()
for token in argv:
if not token:
token = '""'
else:
if '"' in token:
token = token.replace('"', '\\"')
if ' ' in token or \
'\t' in token or \
'\n' in token or \
'\r' in token:
token = '"%s"' % token
cmdline.append(token)
return ' '.join(cmdline)
@staticmethod
def cmdline_to_argv(lpCmdLine):
"""
Convert a single command line string to a list of arguments.
@type lpCmdLine: str
@param lpCmdLine: Command line string.
The first token is the program to execute.
@rtype: list( str )
@return: List of argument strings.
"""
if not lpCmdLine:
return []
return win32.CommandLineToArgv(lpCmdLine)
def start_process(self, lpCmdLine, **kwargs):
"""
Starts a new process for instrumenting (or debugging).
@type lpCmdLine: str
@param lpCmdLine: Command line to execute. Can't be an empty string.
@type bConsole: bool
@keyword bConsole: True to inherit the console of the debugger.
Defaults to C{False}.
@type bDebug: bool
@keyword bDebug: C{True} to attach to the new process.
To debug a process it's best to use the L{Debug} class instead.
Defaults to C{False}.
@type bFollow: bool
@keyword bFollow: C{True} to automatically attach to the child
processes of the newly created process. Ignored unless C{bDebug} is
C{True}. Defaults to C{False}.
@type bInheritHandles: bool
@keyword bInheritHandles: C{True} if the new process should inherit
it's parent process' handles. Defaults to C{False}.
@type bSuspended: bool
@keyword bSuspended: C{True} to suspend the main thread before any code
is executed in the debugee. Defaults to C{False}.
@type dwParentProcessId: int or None
@keyword dwParentProcessId: C{None} if the debugger process should be
the parent process (default), or a process ID to forcefully set as
the debugee's parent (only available for Windows Vista and above).
@type iTrustLevel: int
@keyword iTrustLevel: Trust level.
Must be one of the following values:
- 0: B{No trust}. May not access certain resources, such as
cryptographic keys and credentials. Only available since
Windows XP and 2003, desktop editions.
- 1: B{Normal trust}. Run with the same privileges as a normal
user, that is, one that doesn't have the I{Administrator} or
I{Power User} user rights. Only available since Windows XP
and 2003, desktop editions.
- 2: B{Full trust}. Run with the exact same privileges as the
current user. This is the default value.
@type bAllowElevation: bool
@keyword bAllowElevation: C{True} to allow the child process to keep
UAC elevation, if the debugger itself is running elevated. C{False}
to ensure the child process doesn't run with elevation. Defaults to
C{True}.
This flag is only meaningful on Windows Vista and above, and if the
debugger itself is running with elevation. It can be used to make
sure the child processes don't run elevated as well.
This flag DOES NOT force an elevation prompt when the debugger is
not running with elevation.
Note that running the debugger with elevation (or the Python
interpreter at all for that matter) is not normally required.
You should only need to if the target program requires elevation
to work properly (for example if you try to debug an installer).
@rtype: L{Process}
@return: Process object.
"""
# Get the flags.
bConsole = kwargs.pop('bConsole', False)
bDebug = kwargs.pop('bDebug', False)
bFollow = kwargs.pop('bFollow', False)
bSuspended = kwargs.pop('bSuspended', False)
bInheritHandles = kwargs.pop('bInheritHandles', False)
dwParentProcessId = kwargs.pop('dwParentProcessId', None)
iTrustLevel = kwargs.pop('iTrustLevel', 2)
bAllowElevation = kwargs.pop('bAllowElevation', True)
if kwargs:
raise TypeError("Unknown keyword arguments: %s" % compat.keys(kwargs))
if not lpCmdLine:
raise ValueError("Missing command line to execute!")
# Sanitize the trust level flag.
if iTrustLevel is None:
iTrustLevel = 2
# The UAC elevation flag is only meaningful if we're running elevated.
try:
bAllowElevation = bAllowElevation or not self.is_admin()
except AttributeError:
bAllowElevation = True
warnings.warn(
"UAC elevation is only available in Windows Vista and above",
RuntimeWarning)
# Calculate the process creation flags.
dwCreationFlags = 0
dwCreationFlags |= win32.CREATE_DEFAULT_ERROR_MODE
dwCreationFlags |= win32.CREATE_BREAKAWAY_FROM_JOB
##dwCreationFlags |= win32.CREATE_UNICODE_ENVIRONMENT
if not bConsole:
dwCreationFlags |= win32.DETACHED_PROCESS
#dwCreationFlags |= win32.CREATE_NO_WINDOW # weird stuff happens
if bSuspended:
dwCreationFlags |= win32.CREATE_SUSPENDED
if bDebug:
dwCreationFlags |= win32.DEBUG_PROCESS
if not bFollow:
dwCreationFlags |= win32.DEBUG_ONLY_THIS_PROCESS
# Change the parent process if requested.
# May fail on old versions of Windows.
lpStartupInfo = None
if dwParentProcessId is not None:
myPID = win32.GetCurrentProcessId()
if dwParentProcessId != myPID:
if self.has_process(dwParentProcessId):
ParentProcess = self.get_process(dwParentProcessId)
else:
ParentProcess = Process(dwParentProcessId)
ParentProcessHandle = ParentProcess.get_handle(
win32.PROCESS_CREATE_PROCESS)
AttributeListData = (
(
win32.PROC_THREAD_ATTRIBUTE_PARENT_PROCESS,
ParentProcessHandle._as_parameter_
),
)
AttributeList = win32.ProcThreadAttributeList(AttributeListData)
StartupInfoEx = win32.STARTUPINFOEX()
StartupInfo = StartupInfoEx.StartupInfo
StartupInfo.cb = win32.sizeof(win32.STARTUPINFOEX)
StartupInfo.lpReserved = 0
StartupInfo.lpDesktop = 0
StartupInfo.lpTitle = 0
StartupInfo.dwFlags = 0
StartupInfo.cbReserved2 = 0
StartupInfo.lpReserved2 = 0
StartupInfoEx.lpAttributeList = AttributeList.value
lpStartupInfo = StartupInfoEx
dwCreationFlags |= win32.EXTENDED_STARTUPINFO_PRESENT
pi = None
try:
# Create the process the easy way.
if iTrustLevel >= 2 and bAllowElevation:
pi = win32.CreateProcess(None, lpCmdLine,
bInheritHandles = bInheritHandles,
dwCreationFlags = dwCreationFlags,
lpStartupInfo = lpStartupInfo)
# Create the process the hard way...
else:
# If we allow elevation, use the current process token.
# If not, get the token from the current shell process.
hToken = None
try:
if not bAllowElevation:
if bFollow:
msg = (
"Child processes can't be autofollowed"
" when dropping UAC elevation.")
raise NotImplementedError(msg)
if bConsole:
msg = (
"Child processes can't inherit the debugger's"
" console when dropping UAC elevation.")
raise NotImplementedError(msg)
if bInheritHandles:
msg = (
"Child processes can't inherit the debugger's"
" handles when dropping UAC elevation.")
raise NotImplementedError(msg)
try:
hWnd = self.get_shell_window()
except WindowsError:
hWnd = self.get_desktop_window()
shell = hWnd.get_process()
try:
hShell = shell.get_handle(
win32.PROCESS_QUERY_INFORMATION)
with win32.OpenProcessToken(hShell) as hShellToken:
hToken = win32.DuplicateTokenEx(hShellToken)
finally:
shell.close_handle()
# Lower trust level if requested.
if iTrustLevel < 2:
if iTrustLevel > 0:
dwLevelId = win32.SAFER_LEVELID_NORMALUSER
else:
dwLevelId = win32.SAFER_LEVELID_UNTRUSTED
with win32.SaferCreateLevel(dwLevelId = dwLevelId) as hSafer:
hSaferToken = win32.SaferComputeTokenFromLevel(
hSafer, hToken)[0]
try:
if hToken is not None:
hToken.close()
except:
hSaferToken.close()
raise
hToken = hSaferToken
# If we have a computed token, call CreateProcessAsUser().
if bAllowElevation:
pi = win32.CreateProcessAsUser(
hToken = hToken,
lpCommandLine = lpCmdLine,
bInheritHandles = bInheritHandles,
dwCreationFlags = dwCreationFlags,
lpStartupInfo = lpStartupInfo)
# If we have a primary token call CreateProcessWithToken().
# The problem is, there are many flags CreateProcess() and
# CreateProcessAsUser() accept but CreateProcessWithToken()
# and CreateProcessWithLogonW() don't, so we need to work
# around them.
else:
# Remove the debug flags.
dwCreationFlags &= ~win32.DEBUG_PROCESS
dwCreationFlags &= ~win32.DEBUG_ONLY_THIS_PROCESS
# Remove the console flags.
dwCreationFlags &= ~win32.DETACHED_PROCESS
# The process will be created suspended.
dwCreationFlags |= win32.CREATE_SUSPENDED
# Create the process using the new primary token.
pi = win32.CreateProcessWithToken(
hToken = hToken,
dwLogonFlags = win32.LOGON_WITH_PROFILE,
lpCommandLine = lpCmdLine,
dwCreationFlags = dwCreationFlags,
lpStartupInfo = lpStartupInfo)
# Attach as a debugger, if requested.
if bDebug:
win32.DebugActiveProcess(pi.dwProcessId)
# Resume execution, if requested.
if not bSuspended:
win32.ResumeThread(pi.hThread)
# Close the token when we're done with it.
finally:
if hToken is not None:
hToken.close()
# Wrap the new process and thread in Process and Thread objects,
# and add them to the corresponding snapshots.
aProcess = Process(pi.dwProcessId, pi.hProcess)
aThread = Thread (pi.dwThreadId, pi.hThread)
aProcess._add_thread(aThread)
self._add_process(aProcess)
# Clean up on error.
except:
if pi is not None:
try:
win32.TerminateProcess(pi.hProcess)
except WindowsError:
pass
pi.hThread.close()
pi.hProcess.close()
raise
# Return the new Process object.
return aProcess
def get_explorer_pid(self):
"""
Tries to find the process ID for "explorer.exe".
@rtype: int or None
@return: Returns the process ID, or C{None} on error.
"""
try:
exp = win32.SHGetFolderPath(win32.CSIDL_WINDOWS)
except Exception:
exp = None
if not exp:
exp = os.getenv('SystemRoot')
if exp:
exp = os.path.join(exp, 'explorer.exe')
exp_list = self.find_processes_by_filename(exp)
if exp_list:
return exp_list[0][0].get_pid()
return None
#------------------------------------------------------------------------------
# XXX this methods musn't end up calling __initialize_snapshot by accident!
def scan(self):
"""
Populates the snapshot with running processes and threads,
and loaded modules.
Tipically this is the first method called after instantiating a
L{System} object, as it makes a best effort approach to gathering
information on running processes.
@rtype: bool
@return: C{True} if the snapshot is complete, C{False} if the debugger
doesn't have permission to scan some processes. In either case, the
snapshot is complete for all processes the debugger has access to.
"""
has_threads = True
try:
try:
# Try using the Toolhelp API
# to scan for processes and threads.
self.scan_processes_and_threads()
except Exception:
# On error, try using the PSAPI to scan for process IDs only.
self.scan_processes_fast()
# Now try using the Toolhelp again to get the threads.
for aProcess in self.__processDict.values():
if aProcess._get_thread_ids():
try:
aProcess.scan_threads()
except WindowsError:
has_threads = False
finally:
# Try using the Remote Desktop API to scan for processes only.
# This will update the filenames when it's not possible
# to obtain them from the Toolhelp API.
self.scan_processes()
# When finished scanning for processes, try modules too.
has_modules = self.scan_modules()
# Try updating the process filenames when possible.
has_full_names = self.scan_process_filenames()
# Return the completion status.
return has_threads and has_modules and has_full_names
def scan_processes_and_threads(self):
"""
Populates the snapshot with running processes and threads.
Tipically you don't need to call this method directly, if unsure use
L{scan} instead.
@note: This method uses the Toolhelp API.
@see: L{scan_modules}
@raise WindowsError: An error occured while updating the snapshot.
The snapshot was not modified.
"""
# The main module filename may be spoofed by malware,
# since this information resides in usermode space.
# See: http://www.ragestorm.net/blogs/?p=163
our_pid = win32.GetCurrentProcessId()
dead_pids = set( compat.iterkeys(self.__processDict) )
found_tids = set()
# Ignore our own process if it's in the snapshot for some reason
if our_pid in dead_pids:
dead_pids.remove(our_pid)
# Take a snapshot of all processes and threads
dwFlags = win32.TH32CS_SNAPPROCESS | win32.TH32CS_SNAPTHREAD
with win32.CreateToolhelp32Snapshot(dwFlags) as hSnapshot:
# Add all the processes (excluding our own)
pe = win32.Process32First(hSnapshot)
while pe is not None:
dwProcessId = pe.th32ProcessID
if dwProcessId != our_pid:
if dwProcessId in dead_pids:
dead_pids.remove(dwProcessId)
if dwProcessId not in self.__processDict:
aProcess = Process(dwProcessId, fileName=pe.szExeFile)
self._add_process(aProcess)
elif pe.szExeFile:
aProcess = self.get_process(dwProcessId)
if not aProcess.fileName:
aProcess.fileName = pe.szExeFile
pe = win32.Process32Next(hSnapshot)
# Add all the threads
te = win32.Thread32First(hSnapshot)
while te is not None:
dwProcessId = te.th32OwnerProcessID
if dwProcessId != our_pid:
if dwProcessId in dead_pids:
dead_pids.remove(dwProcessId)
if dwProcessId in self.__processDict:
aProcess = self.get_process(dwProcessId)
else:
aProcess = Process(dwProcessId)
self._add_process(aProcess)
dwThreadId = te.th32ThreadID
found_tids.add(dwThreadId)
if not aProcess._has_thread_id(dwThreadId):
aThread = Thread(dwThreadId, process = aProcess)
aProcess._add_thread(aThread)
te = win32.Thread32Next(hSnapshot)
# Remove dead processes
for pid in dead_pids:
self._del_process(pid)
# Remove dead threads
for aProcess in compat.itervalues(self.__processDict):
dead_tids = set( aProcess._get_thread_ids() )
dead_tids.difference_update(found_tids)
for tid in dead_tids:
aProcess._del_thread(tid)
def scan_modules(self):
"""
Populates the snapshot with loaded modules.
Tipically you don't need to call this method directly, if unsure use
L{scan} instead.
@note: This method uses the Toolhelp API.
@see: L{scan_processes_and_threads}
@rtype: bool
@return: C{True} if the snapshot is complete, C{False} if the debugger
doesn't have permission to scan some processes. In either case, the
snapshot is complete for all processes the debugger has access to.
"""
complete = True
for aProcess in compat.itervalues(self.__processDict):
try:
aProcess.scan_modules()
except WindowsError:
complete = False
return complete
def scan_processes(self):
"""
Populates the snapshot with running processes.
Tipically you don't need to call this method directly, if unsure use
L{scan} instead.
@note: This method uses the Remote Desktop API instead of the Toolhelp
API. It might give slightly different results, especially if the
current process does not have full privileges.
@note: This method will only retrieve process filenames. To get the
process pathnames instead, B{after} this method call
L{scan_process_filenames}.
@raise WindowsError: An error occured while updating the snapshot.
The snapshot was not modified.
"""
# Get the previous list of PIDs.
# We'll be removing live PIDs from it as we find them.
our_pid = win32.GetCurrentProcessId()
dead_pids = set( compat.iterkeys(self.__processDict) )
# Ignore our own PID.
if our_pid in dead_pids:
dead_pids.remove(our_pid)
# Get the list of processes from the Remote Desktop API.
pProcessInfo = None
try:
pProcessInfo, dwCount = win32.WTSEnumerateProcesses(
win32.WTS_CURRENT_SERVER_HANDLE)
# For each process found...
for index in compat.xrange(dwCount):
sProcessInfo = pProcessInfo[index]
## # Ignore processes belonging to other sessions.
## if sProcessInfo.SessionId != win32.WTS_CURRENT_SESSION:
## continue
# Ignore our own PID.
pid = sProcessInfo.ProcessId
if pid == our_pid:
continue
# Remove the PID from the dead PIDs list.
if pid in dead_pids:
dead_pids.remove(pid)
# Get the "process name".
# Empirically, this seems to be the filename without the path.
# (The MSDN docs aren't very clear about this API call).
fileName = sProcessInfo.pProcessName
# If the process is new, add a new Process object.
if pid not in self.__processDict:
aProcess = Process(pid, fileName = fileName)
self._add_process(aProcess)
# If the process was already in the snapshot, and the
# filename is missing, update the Process object.
elif fileName:
aProcess = self.__processDict.get(pid)
if not aProcess.fileName:
aProcess.fileName = fileName
# Free the memory allocated by the Remote Desktop API.
finally:
if pProcessInfo is not None:
try:
win32.WTSFreeMemory(pProcessInfo)
except WindowsError:
pass
# At this point the only remaining PIDs from the old list are dead.
# Remove them from the snapshot.
for pid in dead_pids:
self._del_process(pid)
def scan_processes_fast(self):
"""
Populates the snapshot with running processes.
Only the PID is retrieved for each process.
Dead processes are removed.
Threads and modules of living processes are ignored.
Tipically you don't need to call this method directly, if unsure use
L{scan} instead.
@note: This method uses the PSAPI. It may be faster for scanning,
but some information may be missing, outdated or slower to obtain.
This could be a good tradeoff under some circumstances.
"""
# Get the new and old list of pids
new_pids = set( win32.EnumProcesses() )
old_pids = set( compat.iterkeys(self.__processDict) )
# Ignore our own pid
our_pid = win32.GetCurrentProcessId()
if our_pid in new_pids:
new_pids.remove(our_pid)
if our_pid in old_pids:
old_pids.remove(our_pid)
# Add newly found pids
for pid in new_pids.difference(old_pids):
self._add_process( Process(pid) )
# Remove missing pids
for pid in old_pids.difference(new_pids):
self._del_process(pid)
def scan_process_filenames(self):
"""
Update the filename for each process in the snapshot when possible.
@note: Tipically you don't need to call this method. It's called
automatically by L{scan} to get the full pathname for each process
when possible, since some scan methods only get filenames without
the path component.
If unsure, use L{scan} instead.
@see: L{scan}, L{Process.get_filename}
@rtype: bool
@return: C{True} if all the pathnames were retrieved, C{False} if the
debugger doesn't have permission to scan some processes. In either
case, all processes the debugger has access to have a full pathname
instead of just a filename.
"""
complete = True
for aProcess in self.__processDict.values():
try:
new_name = None
old_name = aProcess.fileName
try:
aProcess.fileName = None
new_name = aProcess.get_filename()
finally:
if not new_name:
aProcess.fileName = old_name
complete = False
except Exception:
complete = False
return complete
#------------------------------------------------------------------------------
def clear_dead_processes(self):
"""
Removes Process objects from the snapshot
referring to processes no longer running.
"""
for pid in self.get_process_ids():
aProcess = self.get_process(pid)
if not aProcess.is_alive():
self._del_process(aProcess)
def clear_unattached_processes(self):
"""
Removes Process objects from the snapshot
referring to processes not being debugged.
"""
for pid in self.get_process_ids():
aProcess = self.get_process(pid)
if not aProcess.is_being_debugged():
self._del_process(aProcess)
def close_process_handles(self):
"""
Closes all open handles to processes in this snapshot.
"""
for pid in self.get_process_ids():
aProcess = self.get_process(pid)
try:
aProcess.close_handle()
except Exception:
e = sys.exc_info()[1]
try:
msg = "Cannot close process handle %s, reason: %s"
msg %= (aProcess.hProcess.value, str(e))
warnings.warn(msg)
except Exception:
pass
def close_process_and_thread_handles(self):
"""
Closes all open handles to processes and threads in this snapshot.
"""
for aProcess in self.iter_processes():
aProcess.close_thread_handles()
try:
aProcess.close_handle()
except Exception:
e = sys.exc_info()[1]
try:
msg = "Cannot close process handle %s, reason: %s"
msg %= (aProcess.hProcess.value, str(e))
warnings.warn(msg)
except Exception:
pass
def clear_processes(self):
"""
Removes all L{Process}, L{Thread} and L{Module} objects in this snapshot.
"""
#self.close_process_and_thread_handles()
for aProcess in self.iter_processes():
aProcess.clear()
self.__processDict = dict()
def clear(self):
"""
Clears this snapshot.
@see: L{clear_processes}
"""
self.clear_processes()
#------------------------------------------------------------------------------
# Docs for these methods are taken from the _ThreadContainer class.
def has_thread(self, dwThreadId):
dwProcessId = self.get_pid_from_tid(dwThreadId)
if dwProcessId is None:
return False
return self.has_process(dwProcessId)
def get_thread(self, dwThreadId):
dwProcessId = self.get_pid_from_tid(dwThreadId)
if dwProcessId is None:
msg = "Unknown thread ID %d" % dwThreadId
raise KeyError(msg)
return self.get_process(dwProcessId).get_thread(dwThreadId)
def get_thread_ids(self):
ids = list()
for aProcess in self.iter_processes():
ids += aProcess.get_thread_ids()
return ids
def get_thread_count(self):
count = 0
for aProcess in self.iter_processes():
count += aProcess.get_thread_count()
return count
has_thread.__doc__ = _ThreadContainer.has_thread.__doc__
get_thread.__doc__ = _ThreadContainer.get_thread.__doc__
get_thread_ids.__doc__ = _ThreadContainer.get_thread_ids.__doc__
get_thread_count.__doc__ = _ThreadContainer.get_thread_count.__doc__
#------------------------------------------------------------------------------
# Docs for these methods are taken from the _ModuleContainer class.
def get_module_count(self):
count = 0
for aProcess in self.iter_processes():
count += aProcess.get_module_count()
return count
get_module_count.__doc__ = _ModuleContainer.get_module_count.__doc__
#------------------------------------------------------------------------------
def find_modules_by_base(self, lpBaseOfDll):
"""
@rtype: list( L{Module}... )
@return: List of Module objects with the given base address.
"""
found = list()
for aProcess in self.iter_processes():
if aProcess.has_module(lpBaseOfDll):
aModule = aProcess.get_module(lpBaseOfDll)
found.append( (aProcess, aModule) )
return found
def find_modules_by_name(self, fileName):
"""
@rtype: list( L{Module}... )
@return: List of Module objects found.
"""
found = list()
for aProcess in self.iter_processes():
aModule = aProcess.get_module_by_name(fileName)
if aModule is not None:
found.append( (aProcess, aModule) )
return found
def find_modules_by_address(self, address):
"""
@rtype: list( L{Module}... )
@return: List of Module objects that best match the given address.
"""
found = list()
for aProcess in self.iter_processes():
aModule = aProcess.get_module_at_address(address)
if aModule is not None:
found.append( (aProcess, aModule) )
return found
def __find_processes_by_filename(self, filename):
"""
Internally used by L{find_processes_by_filename}.
"""
found = list()
filename = filename.lower()
if PathOperations.path_is_absolute(filename):
for aProcess in self.iter_processes():
imagename = aProcess.get_filename()
if imagename and imagename.lower() == filename:
found.append( (aProcess, imagename) )
else:
for aProcess in self.iter_processes():
imagename = aProcess.get_filename()
if imagename:
imagename = PathOperations.pathname_to_filename(imagename)
if imagename.lower() == filename:
found.append( (aProcess, imagename) )
return found
def find_processes_by_filename(self, fileName):
"""
@type fileName: str
@param fileName: Filename to search for.
If it's a full pathname, the match must be exact.
If it's a base filename only, the file part is matched,
regardless of the directory where it's located.
@note: If the process is not found and the file extension is not
given, this method will search again assuming a default
extension (.exe).
@rtype: list of tuple( L{Process}, str )
@return: List of processes matching the given main module filename.
Each tuple contains a Process object and it's filename.
"""
found = self.__find_processes_by_filename(fileName)
if not found:
fn, ext = PathOperations.split_extension(fileName)
if not ext:
fileName = '%s.exe' % fn
found = self.__find_processes_by_filename(fileName)
return found
#------------------------------------------------------------------------------
# XXX _notify_* methods should not trigger a scan
def _add_process(self, aProcess):
"""
Private method to add a process object to the snapshot.
@type aProcess: L{Process}
@param aProcess: Process object.
"""
## if not isinstance(aProcess, Process):
## if hasattr(aProcess, '__class__'):
## typename = aProcess.__class__.__name__
## else:
## typename = str(type(aProcess))
## msg = "Expected Process, got %s instead" % typename
## raise TypeError(msg)
dwProcessId = aProcess.dwProcessId
## if dwProcessId in self.__processDict:
## msg = "Process already exists: %d" % dwProcessId
## raise KeyError(msg)
self.__processDict[dwProcessId] = aProcess
def _del_process(self, dwProcessId):
"""
Private method to remove a process object from the snapshot.
@type dwProcessId: int
@param dwProcessId: Global process ID.
"""
try:
aProcess = self.__processDict[dwProcessId]
del self.__processDict[dwProcessId]
except KeyError:
aProcess = None
msg = "Unknown process ID %d" % dwProcessId
warnings.warn(msg, RuntimeWarning)
if aProcess:
aProcess.clear() # remove circular references
# Notify the creation of a new process.
def _notify_create_process(self, event):
"""
Notify the creation of a new process.
This is done automatically by the L{Debug} class, you shouldn't need
to call it yourself.
@type event: L{CreateProcessEvent}
@param event: Create process event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} otherwise.
"""
dwProcessId = event.get_pid()
dwThreadId = event.get_tid()
hProcess = event.get_process_handle()
## if not self.has_process(dwProcessId): # XXX this would trigger a scan
if dwProcessId not in self.__processDict:
aProcess = Process(dwProcessId, hProcess)
self._add_process(aProcess)
aProcess.fileName = event.get_filename()
else:
aProcess = self.get_process(dwProcessId)
#if hProcess != win32.INVALID_HANDLE_VALUE:
# aProcess.hProcess = hProcess # may have more privileges
if not aProcess.fileName:
fileName = event.get_filename()
if fileName:
aProcess.fileName = fileName
return aProcess._notify_create_process(event) # pass it to the process
def _notify_exit_process(self, event):
"""
Notify the termination of a process.
This is done automatically by the L{Debug} class, you shouldn't need
to call it yourself.
@type event: L{ExitProcessEvent}
@param event: Exit process event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} otherwise.
"""
dwProcessId = event.get_pid()
## if self.has_process(dwProcessId): # XXX this would trigger a scan
if dwProcessId in self.__processDict:
self._del_process(dwProcessId)
return True
| 183,635 | Python | 35.566308 | 101 | 0.561952 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/search.py | #!~/.wine/drive_c/Python25/python.exe
# -*- coding: utf-8 -*-
# Process memory finder
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Process memory search.
@group Memory search:
Search,
Pattern,
BytePattern,
TextPattern,
RegExpPattern,
HexPattern
"""
__revision__ = "$Id$"
__all__ = [
'Search',
'Pattern',
'BytePattern',
'TextPattern',
'RegExpPattern',
'HexPattern',
]
from winappdbg.textio import HexInput
from winappdbg.util import StaticClass, MemoryAddresses
from winappdbg import win32
import warnings
try:
# http://pypi.python.org/pypi/regex
import regex as re
except ImportError:
import re
#==============================================================================
class Pattern (object):
"""
Base class for search patterns.
The following L{Pattern} subclasses are provided by WinAppDbg:
- L{BytePattern}
- L{TextPattern}
- L{RegExpPattern}
- L{HexPattern}
@see: L{Search.search_process}
"""
def __init__(self, pattern):
"""
Class constructor.
The only mandatory argument should be the pattern string.
This method B{MUST} be reimplemented by subclasses of L{Pattern}.
"""
raise NotImplementedError()
def __len__(self):
"""
Returns the maximum expected length of the strings matched by this
pattern. Exact behavior is implementation dependent.
Ideally it should be an exact value, but in some cases it's not
possible to calculate so an upper limit should be returned instead.
If that's not possible either an exception must be raised.
This value will be used to calculate the required buffer size when
doing buffered searches.
This method B{MUST} be reimplemented by subclasses of L{Pattern}.
"""
raise NotImplementedError()
def read(self, process, address, size):
"""
Reads the requested number of bytes from the process memory at the
given address.
Subclasses of L{Pattern} tipically don't need to reimplement this
method.
"""
return process.read(address, size)
def find(self, buffer, pos = None):
"""
Searches for the pattern in the given buffer, optionally starting at
the given position within the buffer.
This method B{MUST} be reimplemented by subclasses of L{Pattern}.
@type buffer: str
@param buffer: Buffer to search on.
@type pos: int
@param pos:
(Optional) Position within the buffer to start searching from.
@rtype: tuple( int, int )
@return: Tuple containing the following:
- Position within the buffer where a match is found, or C{-1} if
no match was found.
- Length of the matched data if a match is found, or undefined if
no match was found.
"""
raise NotImplementedError()
def found(self, address, size, data):
"""
This method gets called when a match is found.
This allows subclasses of L{Pattern} to filter out unwanted results,
or modify the results before giving them to the caller of
L{Search.search_process}.
If the return value is C{None} the result is skipped.
Subclasses of L{Pattern} don't need to reimplement this method unless
filtering is needed.
@type address: int
@param address: The memory address where the pattern was found.
@type size: int
@param size: The size of the data that matches the pattern.
@type data: str
@param data: The data that matches the pattern.
@rtype: tuple( int, int, str )
@return: Tuple containing the following:
* The memory address where the pattern was found.
* The size of the data that matches the pattern.
* The data that matches the pattern.
"""
return (address, size, data)
#------------------------------------------------------------------------------
class BytePattern (Pattern):
"""
Fixed byte pattern.
@type pattern: str
@ivar pattern: Byte string to search for.
@type length: int
@ivar length: Length of the byte pattern.
"""
def __init__(self, pattern):
"""
@type pattern: str
@param pattern: Byte string to search for.
"""
self.pattern = str(pattern)
self.length = len(pattern)
def __len__(self):
"""
Returns the exact length of the pattern.
@see: L{Pattern.__len__}
"""
return self.length
def find(self, buffer, pos = None):
return buffer.find(self.pattern, pos), self.length
#------------------------------------------------------------------------------
# FIXME: case insensitive compat.unicode searches are probably buggy!
class TextPattern (BytePattern):
"""
Text pattern.
@type isUnicode: bool
@ivar isUnicode: C{True} if the text to search for is a compat.unicode string,
C{False} otherwise.
@type encoding: str
@ivar encoding: Encoding for the text parameter.
Only used when the text to search for is a Unicode string.
Don't change unless you know what you're doing!
@type caseSensitive: bool
@ivar caseSensitive: C{True} of the search is case sensitive,
C{False} otherwise.
"""
def __init__(self, text, encoding = "utf-16le", caseSensitive = False):
"""
@type text: str or compat.unicode
@param text: Text to search for.
@type encoding: str
@param encoding: (Optional) Encoding for the text parameter.
Only used when the text to search for is a Unicode string.
Don't change unless you know what you're doing!
@type caseSensitive: bool
@param caseSensitive: C{True} of the search is case sensitive,
C{False} otherwise.
"""
self.isUnicode = isinstance(text, compat.unicode)
self.encoding = encoding
self.caseSensitive = caseSensitive
if not self.caseSensitive:
pattern = text.lower()
if self.isUnicode:
pattern = text.encode(encoding)
super(TextPattern, self).__init__(pattern)
def read(self, process, address, size):
data = super(TextPattern, self).read(address, size)
if not self.caseSensitive:
if self.isUnicode:
try:
encoding = self.encoding
text = data.decode(encoding, "replace")
text = text.lower()
new_data = text.encode(encoding, "replace")
if len(data) == len(new_data):
data = new_data
else:
data = data.lower()
except Exception:
data = data.lower()
else:
data = data.lower()
return data
def found(self, address, size, data):
if self.isUnicode:
try:
data = compat.unicode(data, self.encoding)
except Exception:
## traceback.print_exc() # XXX DEBUG
return None
return (address, size, data)
#------------------------------------------------------------------------------
class RegExpPattern (Pattern):
"""
Regular expression pattern.
@type pattern: str
@ivar pattern: Regular expression in text form.
@type flags: int
@ivar flags: Regular expression flags.
@type regexp: re.compile
@ivar regexp: Regular expression in compiled form.
@type maxLength: int
@ivar maxLength:
Maximum expected length of the strings matched by this regular
expression.
This value will be used to calculate the required buffer size when
doing buffered searches.
Ideally it should be an exact value, but in some cases it's not
possible to calculate so an upper limit should be given instead.
If that's not possible either, C{None} should be used. That will
cause an exception to be raised if this pattern is used in a
buffered search.
"""
def __init__(self, regexp, flags = 0, maxLength = None):
"""
@type regexp: str
@param regexp: Regular expression string.
@type flags: int
@param flags: Regular expression flags.
@type maxLength: int
@param maxLength: Maximum expected length of the strings matched by
this regular expression.
This value will be used to calculate the required buffer size when
doing buffered searches.
Ideally it should be an exact value, but in some cases it's not
possible to calculate so an upper limit should be given instead.
If that's not possible either, C{None} should be used. That will
cause an exception to be raised if this pattern is used in a
buffered search.
"""
self.pattern = regexp
self.flags = flags
self.regexp = re.compile(regexp, flags)
self.maxLength = maxLength
def __len__(self):
"""
Returns the maximum expected length of the strings matched by this
pattern. This value is taken from the C{maxLength} argument of the
constructor if this class.
Ideally it should be an exact value, but in some cases it's not
possible to calculate so an upper limit should be returned instead.
If that's not possible either an exception must be raised.
This value will be used to calculate the required buffer size when
doing buffered searches.
"""
if self.maxLength is None:
raise NotImplementedError()
return self.maxLength
def find(self, buffer, pos = None):
if not pos: # make sure pos is an int
pos = 0
match = self.regexp.search(buffer, pos)
if match:
start, end = match.span()
return start, end - start
return -1, 0
#------------------------------------------------------------------------------
class HexPattern (RegExpPattern):
"""
Hexadecimal pattern.
Hex patterns must be in this form::
"68 65 6c 6c 6f 20 77 6f 72 6c 64" # "hello world"
Spaces are optional. Capitalization of hex digits doesn't matter.
This is exactly equivalent to the previous example::
"68656C6C6F20776F726C64" # "hello world"
Wildcards are allowed, in the form of a C{?} sign in any hex digit::
"5? 5? c3" # pop register / pop register / ret
"b8 ?? ?? ?? ??" # mov eax, immediate value
@type pattern: str
@ivar pattern: Hexadecimal pattern.
"""
def __new__(cls, pattern):
"""
If the pattern is completely static (no wildcards are present) a
L{BytePattern} is created instead. That's because searching for a
fixed byte pattern is faster than searching for a regular expression.
"""
if '?' not in pattern:
return BytePattern( HexInput.hexadecimal(pattern) )
return object.__new__(cls, pattern)
def __init__(self, hexa):
"""
Hex patterns must be in this form::
"68 65 6c 6c 6f 20 77 6f 72 6c 64" # "hello world"
Spaces are optional. Capitalization of hex digits doesn't matter.
This is exactly equivalent to the previous example::
"68656C6C6F20776F726C64" # "hello world"
Wildcards are allowed, in the form of a C{?} sign in any hex digit::
"5? 5? c3" # pop register / pop register / ret
"b8 ?? ?? ?? ??" # mov eax, immediate value
@type hexa: str
@param hexa: Pattern to search for.
"""
maxLength = len([x for x in hexa
if x in "?0123456789ABCDEFabcdef"]) / 2
super(HexPattern, self).__init__(HexInput.pattern(hexa),
maxLength = maxLength)
#==============================================================================
class Search (StaticClass):
"""
Static class to group the search functionality.
Do not instance this class! Use its static methods instead.
"""
# TODO: aligned searches
# TODO: method to coalesce search results
# TODO: search memory dumps
# TODO: search non-ascii C strings
@staticmethod
def search_process(process, pattern, minAddr = None,
maxAddr = None,
bufferPages = None,
overlapping = False):
"""
Search for the given pattern within the process memory.
@type process: L{Process}
@param process: Process to search.
@type pattern: L{Pattern}
@param pattern: Pattern to search for.
It must be an instance of a subclass of L{Pattern}.
The following L{Pattern} subclasses are provided by WinAppDbg:
- L{BytePattern}
- L{TextPattern}
- L{RegExpPattern}
- L{HexPattern}
You can also write your own subclass of L{Pattern} for customized
searches.
@type minAddr: int
@param minAddr: (Optional) Start the search at this memory address.
@type maxAddr: int
@param maxAddr: (Optional) Stop the search at this memory address.
@type bufferPages: int
@param bufferPages: (Optional) Number of memory pages to buffer when
performing the search. Valid values are:
- C{0} or C{None}:
Automatically determine the required buffer size. May not give
complete results for regular expressions that match variable
sized strings.
- C{> 0}: Set the buffer size, in memory pages.
- C{< 0}: Disable buffering entirely. This may give you a little
speed gain at the cost of an increased memory usage. If the
target process has very large contiguous memory regions it may
actually be slower or even fail. It's also the only way to
guarantee complete results for regular expressions that match
variable sized strings.
@type overlapping: bool
@param overlapping: C{True} to allow overlapping results, C{False}
otherwise.
Overlapping results yield the maximum possible number of results.
For example, if searching for "AAAA" within "AAAAAAAA" at address
C{0x10000}, when overlapping is turned off the following matches
are yielded::
(0x10000, 4, "AAAA")
(0x10004, 4, "AAAA")
If overlapping is turned on, the following matches are yielded::
(0x10000, 4, "AAAA")
(0x10001, 4, "AAAA")
(0x10002, 4, "AAAA")
(0x10003, 4, "AAAA")
(0x10004, 4, "AAAA")
As you can see, the middle results are overlapping the last two.
@rtype: iterator of tuple( int, int, str )
@return: An iterator of tuples. Each tuple contains the following:
- The memory address where the pattern was found.
- The size of the data that matches the pattern.
- The data that matches the pattern.
@raise WindowsError: An error occurred when querying or reading the
process memory.
"""
# Do some namespace lookups of symbols we'll be using frequently.
MEM_COMMIT = win32.MEM_COMMIT
PAGE_GUARD = win32.PAGE_GUARD
page = MemoryAddresses.pageSize
read = pattern.read
find = pattern.find
# Calculate the address range.
if minAddr is None:
minAddr = 0
if maxAddr is None:
maxAddr = win32.LPVOID(-1).value # XXX HACK
# Calculate the buffer size from the number of pages.
if bufferPages is None:
try:
size = MemoryAddresses.\
align_address_to_page_end(len(pattern)) + page
except NotImplementedError:
size = None
elif bufferPages > 0:
size = page * (bufferPages + 1)
else:
size = None
# Get the memory map of the process.
memory_map = process.iter_memory_map(minAddr, maxAddr)
# Perform search with buffering enabled.
if size:
# Loop through all memory blocks containing data.
buffer = "" # buffer to hold the memory data
prev_addr = 0 # previous memory block address
last = 0 # position of the last match
delta = 0 # delta of last read address and start of buffer
for mbi in memory_map:
# Skip blocks with no data to search on.
if not mbi.has_content():
continue
# Get the address and size of this block.
address = mbi.BaseAddress # current address to search on
block_size = mbi.RegionSize # total size of the block
if address >= maxAddr:
break
end = address + block_size # end address of the block
# If the block is contiguous to the previous block,
# coalesce the new data in the buffer.
if delta and address == prev_addr:
buffer += read(process, address, page)
# If not, clear the buffer and read new data.
else:
buffer = read(process, address, min(size, block_size))
last = 0
delta = 0
# Search for the pattern in this block.
while 1:
# Yield each match of the pattern in the buffer.
pos, length = find(buffer, last)
while pos >= last:
match_addr = address + pos - delta
if minAddr <= match_addr < maxAddr:
result = pattern.found(
match_addr, length,
buffer [ pos : pos + length ] )
if result is not None:
yield result
if overlapping:
last = pos + 1
else:
last = pos + length
pos, length = find(buffer, last)
# Advance to the next page.
address = address + page
block_size = block_size - page
prev_addr = address
# Fix the position of the last match.
last = last - page
if last < 0:
last = 0
# Remove the first page in the buffer.
buffer = buffer[ page : ]
delta = page
# If we haven't reached the end of the block yet,
# read the next page in the block and keep seaching.
if address < end:
buffer = buffer + read(process, address, page)
# Otherwise, we're done searching this block.
else:
break
# Perform search with buffering disabled.
else:
# Loop through all memory blocks containing data.
for mbi in memory_map:
# Skip blocks with no data to search on.
if not mbi.has_content():
continue
# Get the address and size of this block.
address = mbi.BaseAddress
block_size = mbi.RegionSize
if address >= maxAddr:
break;
# Read the whole memory region.
buffer = process.read(address, block_size)
# Search for the pattern in this region.
pos, length = find(buffer)
last = 0
while pos >= last:
match_addr = address + pos
if minAddr <= match_addr < maxAddr:
result = pattern.found(
match_addr, length,
buffer [ pos : pos + length ] )
if result is not None:
yield result
if overlapping:
last = pos + 1
else:
last = pos + length
pos, length = find(buffer, last)
@classmethod
def extract_ascii_strings(cls, process, minSize = 4, maxSize = 1024):
"""
Extract ASCII strings from the process memory.
@type process: L{Process}
@param process: Process to search.
@type minSize: int
@param minSize: (Optional) Minimum size of the strings to search for.
@type maxSize: int
@param maxSize: (Optional) Maximum size of the strings to search for.
@rtype: iterator of tuple(int, int, str)
@return: Iterator of strings extracted from the process memory.
Each tuple contains the following:
- The memory address where the string was found.
- The size of the string.
- The string.
"""
regexp = r"[\s\w\!\@\#\$\%%\^\&\*\(\)\{\}\[\]\~\`\'\"\:\;\.\,\\\/\-\+\=\_\<\>]{%d,%d}\0" % (minSize, maxSize)
pattern = RegExpPattern(regexp, 0, maxSize)
return cls.search_process(process, pattern, overlapping = False)
| 23,798 | Python | 34.734234 | 117 | 0.555803 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/sql.py | #!~/.wine/drive_c/Python25/python.exe
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
SQL database storage support.
@group Crash reporting:
CrashDAO
"""
__revision__ = "$Id$"
__all__ = ['CrashDAO']
import sqlite3
import datetime
import warnings
from sqlalchemy import create_engine, Column, ForeignKey, Sequence
from sqlalchemy.engine.url import URL
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.interfaces import PoolListener
from sqlalchemy.orm import sessionmaker, deferred
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
from sqlalchemy.types import Integer, BigInteger, Boolean, DateTime, String, \
LargeBinary, Enum, VARCHAR
from sqlalchemy.sql.expression import asc, desc
from crash import Crash, Marshaller, pickle, HIGHEST_PROTOCOL
from textio import CrashDump
import win32
#------------------------------------------------------------------------------
try:
from decorator import decorator
except ImportError:
import functools
def decorator(w):
"""
The C{decorator} module was not found. You can install it from:
U{http://pypi.python.org/pypi/decorator/}
"""
def d(fn):
@functools.wraps(fn)
def x(*argv, **argd):
return w(fn, *argv, **argd)
return x
return d
#------------------------------------------------------------------------------
@compiles(String, 'mysql')
@compiles(VARCHAR, 'mysql')
def _compile_varchar_mysql(element, compiler, **kw):
"""MySQL hack to avoid the "VARCHAR requires a length" error."""
if not element.length or element.length == 'max':
return "TEXT"
else:
return compiler.visit_VARCHAR(element, **kw)
#------------------------------------------------------------------------------
class _SQLitePatch (PoolListener):
"""
Used internally by L{BaseDAO}.
After connecting to an SQLite database, ensure that the foreign keys
support is enabled. If not, abort the connection.
@see: U{http://sqlite.org/foreignkeys.html}
"""
def connect(dbapi_connection, connection_record):
"""
Called once by SQLAlchemy for each new SQLite DB-API connection.
Here is where we issue some PRAGMA statements to configure how we're
going to access the SQLite database.
@param dbapi_connection:
A newly connected raw SQLite DB-API connection.
@param connection_record:
Unused by this method.
"""
try:
cursor = dbapi_connection.cursor()
try:
cursor.execute("PRAGMA foreign_keys = ON;")
cursor.execute("PRAGMA foreign_keys;")
if cursor.fetchone()[0] != 1:
raise Exception()
finally:
cursor.close()
except Exception:
dbapi_connection.close()
raise sqlite3.Error()
#------------------------------------------------------------------------------
class BaseDTO (object):
"""
Customized declarative base for SQLAlchemy.
"""
__table_args__ = {
# Don't use MyISAM in MySQL. It doesn't support ON DELETE CASCADE.
'mysql_engine': 'InnoDB',
# Don't use BlitzDB in Drizzle. It doesn't support foreign keys.
'drizzle_engine': 'InnoDB',
# Collate to UTF-8.
'mysql_charset': 'utf8',
}
BaseDTO = declarative_base(cls = BaseDTO)
#------------------------------------------------------------------------------
# TODO: if using mssql, check it's at least SQL Server 2005
# (LIMIT and OFFSET support is required).
# TODO: if using mysql, check it's at least MySQL 5.0.3
# (nested transactions are required).
# TODO: maybe in mysql check the tables are not myisam?
# TODO: maybe create the database if it doesn't exist?
# TODO: maybe add a method to compact the database?
# http://stackoverflow.com/questions/1875885
# http://www.sqlite.org/lang_vacuum.html
# http://dev.mysql.com/doc/refman/5.1/en/optimize-table.html
# http://msdn.microsoft.com/en-us/library/ms174459(v=sql.90).aspx
class BaseDAO (object):
"""
Data Access Object base class.
@type _url: sqlalchemy.url.URL
@ivar _url: Database connection URL.
@type _dialect: str
@ivar _dialect: SQL dialect currently being used.
@type _driver: str
@ivar _driver: Name of the database driver currently being used.
To get the actual Python module use L{_url}.get_driver() instead.
@type _session: sqlalchemy.orm.Session
@ivar _session: Database session object.
@type _new_session: class
@cvar _new_session: Custom configured Session class used to create the
L{_session} instance variable.
@type _echo: bool
@cvar _echo: Set to C{True} to print all SQL queries to standard output.
"""
_echo = False
_new_session = sessionmaker(autoflush = True,
autocommit = True,
expire_on_commit = True,
weak_identity_map = True)
def __init__(self, url, creator = None):
"""
Connect to the database using the given connection URL.
The current implementation uses SQLAlchemy and so it will support
whatever database said module supports.
@type url: str
@param url:
URL that specifies the database to connect to.
Some examples:
- Opening an SQLite file:
C{dao = CrashDAO("sqlite:///C:\\some\\path\\database.sqlite")}
- Connecting to a locally installed SQL Express database:
C{dao = CrashDAO("mssql://.\\SQLEXPRESS/Crashes?trusted_connection=yes")}
- Connecting to a MySQL database running locally, using the
C{oursql} library, authenticating as the "winappdbg" user with
no password:
C{dao = CrashDAO("mysql+oursql://winappdbg@localhost/Crashes")}
- Connecting to a Postgres database running locally,
authenticating with user and password:
C{dao = CrashDAO("postgresql://winappdbg:winappdbg@localhost/Crashes")}
For more information see the C{SQLAlchemy} documentation online:
U{http://docs.sqlalchemy.org/en/latest/core/engines.html}
Note that in all dialects except for SQLite the database
must already exist. The tables schema, however, is created
automatically when connecting for the first time.
To create the database in MSSQL, you can use the
U{SQLCMD<http://msdn.microsoft.com/en-us/library/ms180944.aspx>}
command::
sqlcmd -Q "CREATE DATABASE Crashes"
In MySQL you can use something like the following::
mysql -u root -e "CREATE DATABASE Crashes;"
And in Postgres::
createdb Crashes -h localhost -U winappdbg -p winappdbg -O winappdbg
Some small changes to the schema may be tolerated (for example,
increasing the maximum length of string columns, or adding new
columns with default values). Of course, it's best to test it
first before making changes in a live database. This all depends
very much on the SQLAlchemy version you're using, but it's best
to use the latest version always.
@type creator: callable
@param creator: (Optional) Callback function that creates the SQL
database connection.
Normally it's not necessary to use this argument. However in some
odd cases you may need to customize the database connection.
"""
# Parse the connection URL.
parsed_url = URL(url)
schema = parsed_url.drivername
if '+' in schema:
dialect, driver = schema.split('+')
else:
dialect, driver = schema, 'base'
dialect = dialect.strip().lower()
driver = driver.strip()
# Prepare the database engine arguments.
arguments = {'echo' : self._echo}
if dialect == 'sqlite':
arguments['module'] = sqlite3.dbapi2
arguments['listeners'] = [_SQLitePatch()]
if creator is not None:
arguments['creator'] = creator
# Load the database engine.
engine = create_engine(url, **arguments)
# Create a new session.
session = self._new_session(bind = engine)
# Create the required tables if they don't exist.
BaseDTO.metadata.create_all(engine)
# TODO: create a dialect specific index on the "signature" column.
# Set the instance properties.
self._url = parsed_url
self._driver = driver
self._dialect = dialect
self._session = session
def _transactional(self, method, *argv, **argd):
"""
Begins a transaction and calls the given DAO method.
If the method executes successfully the transaction is commited.
If the method fails, the transaction is rolled back.
@type method: callable
@param method: Bound method of this class or one of its subclasses.
The first argument will always be C{self}.
@return: The return value of the method call.
@raise Exception: Any exception raised by the method.
"""
self._session.begin(subtransactions = True)
try:
result = method(self, *argv, **argd)
self._session.commit()
return result
except:
self._session.rollback()
raise
#------------------------------------------------------------------------------
@decorator
def Transactional(fn, self, *argv, **argd):
"""
Decorator that wraps DAO methods to handle transactions automatically.
It may only work with subclasses of L{BaseDAO}.
"""
return self._transactional(fn, *argv, **argd)
#==============================================================================
# Generates all possible memory access flags.
def _gen_valid_access_flags():
f = []
for a1 in ("---", "R--", "RW-", "RC-", "--X", "R-X", "RWX", "RCX", "???"):
for a2 in ("G", "-"):
for a3 in ("N", "-"):
for a4 in ("W", "-"):
f.append("%s %s%s%s" % (a1, a2, a3, a4))
return tuple(f)
_valid_access_flags = _gen_valid_access_flags()
# Enumerated types for the memory table.
n_MEM_ACCESS_ENUM = {"name" : "MEM_ACCESS_ENUM"}
n_MEM_ALLOC_ACCESS_ENUM = {"name" : "MEM_ALLOC_ACCESS_ENUM"}
MEM_ACCESS_ENUM = Enum(*_valid_access_flags,
**n_MEM_ACCESS_ENUM)
MEM_ALLOC_ACCESS_ENUM = Enum(*_valid_access_flags,
**n_MEM_ALLOC_ACCESS_ENUM)
MEM_STATE_ENUM = Enum("Reserved", "Commited", "Free", "Unknown",
name = "MEM_STATE_ENUM")
MEM_TYPE_ENUM = Enum("Image", "Mapped", "Private", "Unknown",
name = "MEM_TYPE_ENUM")
# Cleanup the namespace.
del _gen_valid_access_flags
del _valid_access_flags
del n_MEM_ACCESS_ENUM
del n_MEM_ALLOC_ACCESS_ENUM
#------------------------------------------------------------------------------
class MemoryDTO (BaseDTO):
"""
Database mapping for memory dumps.
"""
# Declare the table mapping.
__tablename__ = 'memory'
id = Column(Integer, Sequence(__tablename__ + '_seq'),
primary_key = True, autoincrement = True)
crash_id = Column(Integer, ForeignKey('crashes.id',
ondelete = 'CASCADE',
onupdate = 'CASCADE'),
nullable = False)
address = Column(BigInteger, nullable = False, index = True)
size = Column(BigInteger, nullable = False)
state = Column(MEM_STATE_ENUM, nullable = False)
access = Column(MEM_ACCESS_ENUM)
type = Column(MEM_TYPE_ENUM)
alloc_base = Column(BigInteger)
alloc_access = Column(MEM_ALLOC_ACCESS_ENUM)
filename = Column(String)
content = deferred(Column(LargeBinary))
def __init__(self, crash_id, mbi):
"""
Process a L{win32.MemoryBasicInformation} object for database storage.
"""
# Crash ID.
self.crash_id = crash_id
# Address.
self.address = mbi.BaseAddress
# Size.
self.size = mbi.RegionSize
# State (free or allocated).
if mbi.State == win32.MEM_RESERVE:
self.state = "Reserved"
elif mbi.State == win32.MEM_COMMIT:
self.state = "Commited"
elif mbi.State == win32.MEM_FREE:
self.state = "Free"
else:
self.state = "Unknown"
# Page protection bits (R/W/X/G).
if mbi.State != win32.MEM_COMMIT:
self.access = None
else:
self.access = self._to_access(mbi.Protect)
# Type (file mapping, executable image, or private memory).
if mbi.Type == win32.MEM_IMAGE:
self.type = "Image"
elif mbi.Type == win32.MEM_MAPPED:
self.type = "Mapped"
elif mbi.Type == win32.MEM_PRIVATE:
self.type = "Private"
elif mbi.Type == 0:
self.type = None
else:
self.type = "Unknown"
# Allocation info.
self.alloc_base = mbi.AllocationBase
if not mbi.AllocationProtect:
self.alloc_access = None
else:
self.alloc_access = self._to_access(mbi.AllocationProtect)
# Filename (for memory mappings).
try:
self.filename = mbi.filename
except AttributeError:
self.filename = None
# Memory contents.
try:
self.content = mbi.content
except AttributeError:
self.content = None
def _to_access(self, protect):
if protect & win32.PAGE_NOACCESS:
access = "--- "
elif protect & win32.PAGE_READONLY:
access = "R-- "
elif protect & win32.PAGE_READWRITE:
access = "RW- "
elif protect & win32.PAGE_WRITECOPY:
access = "RC- "
elif protect & win32.PAGE_EXECUTE:
access = "--X "
elif protect & win32.PAGE_EXECUTE_READ:
access = "R-X "
elif protect & win32.PAGE_EXECUTE_READWRITE:
access = "RWX "
elif protect & win32.PAGE_EXECUTE_WRITECOPY:
access = "RCX "
else:
access = "??? "
if protect & win32.PAGE_GUARD:
access += "G"
else:
access += "-"
if protect & win32.PAGE_NOCACHE:
access += "N"
else:
access += "-"
if protect & win32.PAGE_WRITECOMBINE:
access += "W"
else:
access += "-"
return access
def toMBI(self, getMemoryDump = False):
"""
Returns a L{win32.MemoryBasicInformation} object using the data
retrieved from the database.
@type getMemoryDump: bool
@param getMemoryDump: (Optional) If C{True} retrieve the memory dump.
Defaults to C{False} since this may be a costly operation.
@rtype: L{win32.MemoryBasicInformation}
@return: Memory block information.
"""
mbi = win32.MemoryBasicInformation()
mbi.BaseAddress = self.address
mbi.RegionSize = self.size
mbi.State = self._parse_state(self.state)
mbi.Protect = self._parse_access(self.access)
mbi.Type = self._parse_type(self.type)
if self.alloc_base is not None:
mbi.AllocationBase = self.alloc_base
else:
mbi.AllocationBase = mbi.BaseAddress
if self.alloc_access is not None:
mbi.AllocationProtect = self._parse_access(self.alloc_access)
else:
mbi.AllocationProtect = mbi.Protect
if self.filename is not None:
mbi.filename = self.filename
if getMemoryDump and self.content is not None:
mbi.content = self.content
return mbi
@staticmethod
def _parse_state(state):
if state:
if state == "Reserved":
return win32.MEM_RESERVE
if state == "Commited":
return win32.MEM_COMMIT
if state == "Free":
return win32.MEM_FREE
return 0
@staticmethod
def _parse_type(type):
if type:
if type == "Image":
return win32.MEM_IMAGE
if type == "Mapped":
return win32.MEM_MAPPED
if type == "Private":
return win32.MEM_PRIVATE
return -1
return 0
@staticmethod
def _parse_access(access):
if not access:
return 0
perm = access[:3]
if perm == "R--":
protect = win32.PAGE_READONLY
elif perm == "RW-":
protect = win32.PAGE_READWRITE
elif perm == "RC-":
protect = win32.PAGE_WRITECOPY
elif perm == "--X":
protect = win32.PAGE_EXECUTE
elif perm == "R-X":
protect = win32.PAGE_EXECUTE_READ
elif perm == "RWX":
protect = win32.PAGE_EXECUTE_READWRITE
elif perm == "RCX":
protect = win32.PAGE_EXECUTE_WRITECOPY
else:
protect = win32.PAGE_NOACCESS
if access[5] == "G":
protect = protect | win32.PAGE_GUARD
if access[6] == "N":
protect = protect | win32.PAGE_NOCACHE
if access[7] == "W":
protect = protect | win32.PAGE_WRITECOMBINE
return protect
#------------------------------------------------------------------------------
class CrashDTO (BaseDTO):
"""
Database mapping for crash dumps.
"""
# Table name.
__tablename__ = "crashes"
# Primary key.
id = Column(Integer, Sequence(__tablename__ + '_seq'),
primary_key = True, autoincrement = True)
# Timestamp.
timestamp = Column(DateTime, nullable = False, index = True)
# Exploitability test.
exploitable = Column(Integer, nullable = False)
exploitability_rule = Column(String(32), nullable = False)
exploitability_rating = Column(String(32), nullable = False)
exploitability_desc = Column(String, nullable = False)
# Platform description.
os = Column(String(32), nullable = False)
arch = Column(String(16), nullable = False)
bits = Column(Integer, nullable = False) # Integer(4) is deprecated :(
# Event description.
event = Column(String, nullable = False)
pid = Column(Integer, nullable = False)
tid = Column(Integer, nullable = False)
pc = Column(BigInteger, nullable = False)
sp = Column(BigInteger, nullable = False)
fp = Column(BigInteger, nullable = False)
pc_label = Column(String, nullable = False)
# Exception description.
exception = Column(String(64))
exception_text = Column(String(64))
exception_address = Column(BigInteger)
exception_label = Column(String)
first_chance = Column(Boolean)
fault_type = Column(Integer)
fault_address = Column(BigInteger)
fault_label = Column(String)
fault_disasm = Column(String)
stack_trace = Column(String)
# Environment description.
command_line = Column(String)
environment = Column(String)
# Debug strings.
debug_string = Column(String)
# Notes.
notes = Column(String)
# Heuristic signature.
signature = Column(String, nullable = False)
# Pickled Crash object, minus the memory dump.
data = deferred(Column(LargeBinary, nullable = False))
def __init__(self, crash):
"""
@type crash: Crash
@param crash: L{Crash} object to store into the database.
"""
# Timestamp and signature.
self.timestamp = datetime.datetime.fromtimestamp( crash.timeStamp )
self.signature = pickle.dumps(crash.signature, protocol = 0)
# Marshalled Crash object, minus the memory dump.
# This code is *not* thread safe!
memoryMap = crash.memoryMap
try:
crash.memoryMap = None
self.data = buffer( Marshaller.dumps(crash) )
finally:
crash.memoryMap = memoryMap
# Exploitability test.
self.exploitability_rating, \
self.exploitability_rule, \
self.exploitability_desc = crash.isExploitable()
# Exploitability test as an integer result (for sorting).
self.exploitable = [
"Not an exception",
"Not exploitable",
"Not likely exploitable",
"Unknown",
"Probably exploitable",
"Exploitable",
].index(self.exploitability_rating)
# Platform description.
self.os = crash.os
self.arch = crash.arch
self.bits = crash.bits
# Event description.
self.event = crash.eventName
self.pid = crash.pid
self.tid = crash.tid
self.pc = crash.pc
self.sp = crash.sp
self.fp = crash.fp
self.pc_label = crash.labelPC
# Exception description.
self.exception = crash.exceptionName
self.exception_text = crash.exceptionDescription
self.exception_address = crash.exceptionAddress
self.exception_label = crash.exceptionLabel
self.first_chance = crash.firstChance
self.fault_type = crash.faultType
self.fault_address = crash.faultAddress
self.fault_label = crash.faultLabel
self.fault_disasm = CrashDump.dump_code( crash.faultDisasm,
crash.pc )
self.stack_trace = CrashDump.dump_stack_trace_with_labels(
crash.stackTracePretty )
# Command line.
self.command_line = crash.commandLine
# Environment.
if crash.environment:
envList = crash.environment.items()
envList.sort()
environment = ''
for envKey, envVal in envList:
# Must concatenate here instead of using a substitution,
# so strings can be automatically promoted to Unicode.
environment += envKey + '=' + envVal + '\n'
if environment:
self.environment = environment
# Debug string.
self.debug_string = crash.debugString
# Notes.
self.notes = crash.notesReport()
def toCrash(self, getMemoryDump = False):
"""
Returns a L{Crash} object using the data retrieved from the database.
@type getMemoryDump: bool
@param getMemoryDump: If C{True} retrieve the memory dump.
Defaults to C{False} since this may be a costly operation.
@rtype: L{Crash}
@return: Crash object.
"""
crash = Marshaller.loads(str(self.data))
if not isinstance(crash, Crash):
raise TypeError(
"Expected Crash instance, got %s instead" % type(crash))
crash._rowid = self.id
if not crash.memoryMap:
memory = getattr(self, "memory", [])
if memory:
crash.memoryMap = [dto.toMBI(getMemoryDump) for dto in memory]
return crash
#==============================================================================
# TODO: add a method to modify already stored crash dumps.
class CrashDAO (BaseDAO):
"""
Data Access Object to read, write and search for L{Crash} objects in a
database.
"""
@Transactional
def add(self, crash, allow_duplicates = True):
"""
Add a new crash dump to the database, optionally filtering them by
signature to avoid duplicates.
@type crash: L{Crash}
@param crash: Crash object.
@type allow_duplicates: bool
@param allow_duplicates: (Optional)
C{True} to always add the new crash dump.
C{False} to only add the crash dump if no other crash with the
same signature is found in the database.
Sometimes, your fuzzer turns out to be I{too} good. Then you find
youself browsing through gigabytes of crash dumps, only to find
a handful of actual bugs in them. This simple heuristic filter
saves you the trouble by discarding crashes that seem to be similar
to another one you've already found.
"""
# Filter out duplicated crashes, if requested.
if not allow_duplicates:
signature = pickle.dumps(crash.signature, protocol = 0)
if self._session.query(CrashDTO.id) \
.filter_by(signature = signature) \
.count() > 0:
return
# Fill out a new row for the crashes table.
crash_id = self.__add_crash(crash)
# Fill out new rows for the memory dump.
self.__add_memory(crash_id, crash.memoryMap)
# On success set the row ID for the Crash object.
# WARNING: In nested calls, make sure to delete
# this property before a session rollback!
crash._rowid = crash_id
# Store the Crash object into the crashes table.
def __add_crash(self, crash):
session = self._session
r_crash = None
try:
# Fill out a new row for the crashes table.
r_crash = CrashDTO(crash)
session.add(r_crash)
# Flush and get the new row ID.
session.flush()
crash_id = r_crash.id
finally:
try:
# Make the ORM forget the CrashDTO object.
if r_crash is not None:
session.expire(r_crash)
finally:
# Delete the last reference to the CrashDTO
# object, so the Python garbage collector claims it.
del r_crash
# Return the row ID.
return crash_id
# Store the memory dump into the memory table.
def __add_memory(self, crash_id, memoryMap):
session = self._session
if memoryMap:
for mbi in memoryMap:
r_mem = MemoryDTO(crash_id, mbi)
session.add(r_mem)
session.flush()
@Transactional
def find(self,
signature = None, order = 0,
since = None, until = None,
offset = None, limit = None):
"""
Retrieve all crash dumps in the database, optionally filtering them by
signature and timestamp, and/or sorting them by timestamp.
Results can be paged to avoid consuming too much memory if the database
is large.
@see: L{find_by_example}
@type signature: object
@param signature: (Optional) Return only through crashes matching
this signature. See L{Crash.signature} for more details.
@type order: int
@param order: (Optional) Sort by timestamp.
If C{== 0}, results are not sorted.
If C{> 0}, results are sorted from older to newer.
If C{< 0}, results are sorted from newer to older.
@type since: datetime
@param since: (Optional) Return only the crashes after and
including this date and time.
@type until: datetime
@param until: (Optional) Return only the crashes before this date
and time, not including it.
@type offset: int
@param offset: (Optional) Skip the first I{offset} results.
@type limit: int
@param limit: (Optional) Return at most I{limit} results.
@rtype: list(L{Crash})
@return: List of Crash objects.
"""
# Validate the parameters.
if since and until and since > until:
warnings.warn("CrashDAO.find() got the 'since' and 'until'"
" arguments reversed, corrected automatically.")
since, until = until, since
if limit is not None and not limit:
warnings.warn("CrashDAO.find() was set a limit of 0 results,"
" returning without executing a query.")
return []
# Build the SQL query.
query = self._session.query(CrashDTO)
if signature is not None:
sig_pickled = pickle.dumps(signature, protocol = 0)
query = query.filter(CrashDTO.signature == sig_pickled)
if since:
query = query.filter(CrashDTO.timestamp >= since)
if until:
query = query.filter(CrashDTO.timestamp < until)
if order:
if order > 0:
query = query.order_by(asc(CrashDTO.timestamp))
else:
query = query.order_by(desc(CrashDTO.timestamp))
else:
# Default ordering is by row ID, to get consistent results.
# Also some database engines require ordering when using offsets.
query = query.order_by(asc(CrashDTO.id))
if offset:
query = query.offset(offset)
if limit:
query = query.limit(limit)
# Execute the SQL query and convert the results.
try:
return [dto.toCrash() for dto in query.all()]
except NoResultFound:
return []
@Transactional
def find_by_example(self, crash, offset = None, limit = None):
"""
Find all crash dumps that have common properties with the crash dump
provided.
Results can be paged to avoid consuming too much memory if the database
is large.
@see: L{find}
@type crash: L{Crash}
@param crash: Crash object to compare with. Fields set to C{None} are
ignored, all other fields but the signature are used in the
comparison.
To search for signature instead use the L{find} method.
@type offset: int
@param offset: (Optional) Skip the first I{offset} results.
@type limit: int
@param limit: (Optional) Return at most I{limit} results.
@rtype: list(L{Crash})
@return: List of similar crash dumps found.
"""
# Validate the parameters.
if limit is not None and not limit:
warnings.warn("CrashDAO.find_by_example() was set a limit of 0"
" results, returning without executing a query.")
return []
# Build the query.
query = self._session.query(CrashDTO)
# Order by row ID to get consistent results.
# Also some database engines require ordering when using offsets.
query = query.asc(CrashDTO.id)
# Build a CrashDTO from the Crash object.
dto = CrashDTO(crash)
# Filter all the fields in the crashes table that are present in the
# CrashDTO object and not set to None, except for the row ID.
for name, column in compat.iteritems(CrashDTO.__dict__):
if not name.startswith('__') and name not in ('id',
'signature',
'data'):
if isinstance(column, Column):
value = getattr(dto, name, None)
if value is not None:
query = query.filter(column == value)
# Page the query.
if offset:
query = query.offset(offset)
if limit:
query = query.limit(limit)
# Execute the SQL query and convert the results.
try:
return [dto.toCrash() for dto in query.all()]
except NoResultFound:
return []
@Transactional
def count(self, signature = None):
"""
Counts how many crash dumps have been stored in this database.
Optionally filters the count by heuristic signature.
@type signature: object
@param signature: (Optional) Count only the crashes that match
this signature. See L{Crash.signature} for more details.
@rtype: int
@return: Count of crash dumps stored in this database.
"""
query = self._session.query(CrashDTO.id)
if signature:
sig_pickled = pickle.dumps(signature, protocol = 0)
query = query.filter_by(signature = sig_pickled)
return query.count()
@Transactional
def delete(self, crash):
"""
Remove the given crash dump from the database.
@type crash: L{Crash}
@param crash: Crash dump to remove.
"""
query = self._session.query(CrashDTO).filter_by(id = crash._rowid)
query.delete(synchronize_session = False)
del crash._rowid
| 34,997 | Python | 34.209255 | 88 | 0.57022 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/registry.py | #!~/.wine/drive_c/Python25/python.exe
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Registry access.
@group Instrumentation:
Registry, RegistryKey
"""
from __future__ import with_statement
__revision__ = "$Id$"
__all__ = ['Registry']
import sys
from winappdbg import win32
from winappdbg import compat
import collections
import warnings
#==============================================================================
class _RegistryContainer (object):
"""
Base class for L{Registry} and L{RegistryKey}.
"""
# Dummy object to detect empty arguments.
class __EmptyArgument:
pass
__emptyArgument = __EmptyArgument()
def __init__(self):
self.__default = None
def has_key(self, name):
return name in self
def get(self, name, default=__emptyArgument):
try:
return self[name]
except KeyError:
if default is RegistryKey.__emptyArgument:
return self.__default
return default
def setdefault(self, default):
self.__default = default
def __iter__(self):
return compat.iterkeys(self)
#==============================================================================
class RegistryKey (_RegistryContainer):
"""
Exposes a single Windows Registry key as a dictionary-like object.
@see: L{Registry}
@type path: str
@ivar path: Registry key path.
@type handle: L{win32.RegistryKeyHandle}
@ivar handle: Registry key handle.
"""
def __init__(self, path, handle):
"""
@type path: str
@param path: Registry key path.
@type handle: L{win32.RegistryKeyHandle}
@param handle: Registry key handle.
"""
super(RegistryKey, self).__init__()
if path.endswith('\\'):
path = path[:-1]
self._path = path
self._handle = handle
@property
def path(self):
return self._path
@property
def handle(self):
#if not self._handle:
# msg = "This Registry key handle has already been closed."
# raise RuntimeError(msg)
return self._handle
#def close(self):
# """
# Close the Registry key handle, freeing its resources. It cannot be
# used again after calling this method.
#
# @note: This method will be called automatically by the garbage
# collector, and upon exiting a "with" block.
#
# @raise RuntimeError: This Registry key handle has already been closed.
# """
# self.handle.close()
#
#def __enter__(self):
# """
# Compatibility with the "C{with}" Python statement.
# """
# return self
#
#def __exit__(self, type, value, traceback):
# """
# Compatibility with the "C{with}" Python statement.
# """
# try:
# self.close()
# except Exception:
# pass
def __contains__(self, name):
try:
win32.RegQueryValueEx(self.handle, name, False)
return True
except WindowsError:
e = sys.exc_info()[1]
if e.winerror == win32.ERROR_FILE_NOT_FOUND:
return False
raise
def __getitem__(self, name):
try:
return win32.RegQueryValueEx(self.handle, name)[0]
except WindowsError:
e = sys.exc_info()[1]
if e.winerror == win32.ERROR_FILE_NOT_FOUND:
raise KeyError(name)
raise
def __setitem__(self, name, value):
win32.RegSetValueEx(self.handle, name, value)
def __delitem__(self, name):
win32.RegDeleteValue(self.handle, name)
def iterkeys(self):
handle = self.handle
index = 0
while 1:
resp = win32.RegEnumValue(handle, index, False)
if resp is None:
break
yield resp[0]
index += 1
def itervalues(self):
handle = self.handle
index = 0
while 1:
resp = win32.RegEnumValue(handle, index)
if resp is None:
break
yield resp[2]
index += 1
def iteritems(self):
handle = self.handle
index = 0
while 1:
resp = win32.RegEnumValue(handle, index)
if resp is None:
break
yield resp[0], resp[2]
index += 1
def keys(self):
# return list(self.iterkeys()) # that can't be optimized by psyco
handle = self.handle
keys = list()
index = 0
while 1:
resp = win32.RegEnumValue(handle, index, False)
if resp is None:
break
keys.append(resp[0])
index += 1
return keys
def values(self):
# return list(self.itervalues()) # that can't be optimized by psyco
handle = self.handle
values = list()
index = 0
while 1:
resp = win32.RegEnumValue(handle, index)
if resp is None:
break
values.append(resp[2])
index += 1
return values
def items(self):
# return list(self.iteritems()) # that can't be optimized by psyco
handle = self.handle
items = list()
index = 0
while 1:
resp = win32.RegEnumValue(handle, index)
if resp is None:
break
items.append( (resp[0], resp[2]) )
index += 1
return items
def get_value_type(self, name):
"""
Retrieves the low-level data type for the given value.
@type name: str
@param name: Registry value name.
@rtype: int
@return: One of the following constants:
- L{win32.REG_NONE} (0)
- L{win32.REG_SZ} (1)
- L{win32.REG_EXPAND_SZ} (2)
- L{win32.REG_BINARY} (3)
- L{win32.REG_DWORD} (4)
- L{win32.REG_DWORD_BIG_ENDIAN} (5)
- L{win32.REG_LINK} (6)
- L{win32.REG_MULTI_SZ} (7)
- L{win32.REG_RESOURCE_LIST} (8)
- L{win32.REG_FULL_RESOURCE_DESCRIPTOR} (9)
- L{win32.REG_RESOURCE_REQUIREMENTS_LIST} (10)
- L{win32.REG_QWORD} (11)
@raise KeyError: The specified value could not be found.
"""
try:
return win32.RegQueryValueEx(self.handle, name)[1]
except WindowsError:
e = sys.exc_info()[1]
if e.winerror == win32.ERROR_FILE_NOT_FOUND:
raise KeyError(name)
raise
def clear(self):
handle = self.handle
while 1:
resp = win32.RegEnumValue(handle, 0, False)
if resp is None:
break
win32.RegDeleteValue(handle, resp[0])
def __str__(self):
default = self['']
return str(default)
def __unicode__(self):
default = self[u'']
return compat.unicode(default)
def __repr__(self):
return '<Registry key: "%s">' % self._path
def iterchildren(self):
"""
Iterates the subkeys for this Registry key.
@rtype: iter of L{RegistryKey}
@return: Iterator of subkeys.
"""
handle = self.handle
index = 0
while 1:
subkey = win32.RegEnumKey(handle, index)
if subkey is None:
break
yield self.child(subkey)
index += 1
def children(self):
"""
Returns a list of subkeys for this Registry key.
@rtype: list(L{RegistryKey})
@return: List of subkeys.
"""
# return list(self.iterchildren()) # that can't be optimized by psyco
handle = self.handle
result = []
index = 0
while 1:
subkey = win32.RegEnumKey(handle, index)
if subkey is None:
break
result.append( self.child(subkey) )
index += 1
return result
def child(self, subkey):
"""
Retrieves a subkey for this Registry key, given its name.
@type subkey: str
@param subkey: Name of the subkey.
@rtype: L{RegistryKey}
@return: Subkey.
"""
path = self._path + '\\' + subkey
handle = win32.RegOpenKey(self.handle, subkey)
return RegistryKey(path, handle)
def flush(self):
"""
Flushes changes immediately to disk.
This method is normally not needed, as the Registry writes changes
to disk by itself. This mechanism is provided to ensure the write
happens immediately, as opposed to whenever the OS wants to.
@warn: Calling this method too often may degrade performance.
"""
win32.RegFlushKey(self.handle)
#==============================================================================
# TODO: possibly cache the RegistryKey objects
# to avoid opening and closing handles many times on code sequences like this:
#
# r = Registry()
# r['HKLM\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Run']['Example 1'] = 'example1.exe'
# r['HKLM\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Run']['Example 2'] = 'example2.exe'
# r['HKLM\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Run']['Example 3'] = 'example3.exe'
# TODO: support for access flags?
# TODO: should be possible to disable the safety checks (see __delitem__)
# TODO: workaround for an API bug described by a user in MSDN
#
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa379776(v=vs.85).aspx
#
# Apparently RegDeleteTree won't work remotely from Win7 to WinXP, and the only
# solution is to recursively call RegDeleteKey.
class Registry (_RegistryContainer):
"""
Exposes the Windows Registry as a Python container.
@type machine: str or None
@ivar machine: For a remote Registry, the machine name.
For a local Registry, the value is C{None}.
"""
_hives_by_name = {
# Short names
'HKCR' : win32.HKEY_CLASSES_ROOT,
'HKCU' : win32.HKEY_CURRENT_USER,
'HKLM' : win32.HKEY_LOCAL_MACHINE,
'HKU' : win32.HKEY_USERS,
'HKPD' : win32.HKEY_PERFORMANCE_DATA,
'HKCC' : win32.HKEY_CURRENT_CONFIG,
# Long names
'HKEY_CLASSES_ROOT' : win32.HKEY_CLASSES_ROOT,
'HKEY_CURRENT_USER' : win32.HKEY_CURRENT_USER,
'HKEY_LOCAL_MACHINE' : win32.HKEY_LOCAL_MACHINE,
'HKEY_USERS' : win32.HKEY_USERS,
'HKEY_PERFORMANCE_DATA' : win32.HKEY_PERFORMANCE_DATA,
'HKEY_CURRENT_CONFIG' : win32.HKEY_CURRENT_CONFIG,
}
_hives_by_value = {
win32.HKEY_CLASSES_ROOT : 'HKEY_CLASSES_ROOT',
win32.HKEY_CURRENT_USER : 'HKEY_CURRENT_USER',
win32.HKEY_LOCAL_MACHINE : 'HKEY_LOCAL_MACHINE',
win32.HKEY_USERS : 'HKEY_USERS',
win32.HKEY_PERFORMANCE_DATA : 'HKEY_PERFORMANCE_DATA',
win32.HKEY_CURRENT_CONFIG : 'HKEY_CURRENT_CONFIG',
}
_hives = sorted(compat.itervalues(_hives_by_value))
def __init__(self, machine = None):
"""
Opens a local or remote registry.
@type machine: str
@param machine: Optional machine name. If C{None} it opens the local
registry.
"""
self._machine = machine
self._remote_hives = {}
@property
def machine(self):
return self._machine
def _split_path(self, path):
"""
Splits a Registry path and returns the hive and key.
@type path: str
@param path: Registry path.
@rtype: tuple( int, str )
@return: Tuple containing the hive handle and the subkey path.
The hive handle is always one of the following integer constants:
- L{win32.HKEY_CLASSES_ROOT}
- L{win32.HKEY_CURRENT_USER}
- L{win32.HKEY_LOCAL_MACHINE}
- L{win32.HKEY_USERS}
- L{win32.HKEY_PERFORMANCE_DATA}
- L{win32.HKEY_CURRENT_CONFIG}
"""
if '\\' in path:
p = path.find('\\')
hive = path[:p]
path = path[p+1:]
else:
hive = path
path = None
handle = self._hives_by_name[ hive.upper() ]
return handle, path
def _parse_path(self, path):
"""
Parses a Registry path and returns the hive and key.
@type path: str
@param path: Registry path.
@rtype: tuple( int, str )
@return: Tuple containing the hive handle and the subkey path.
For a local Registry, the hive handle is an integer.
For a remote Registry, the hive handle is a L{RegistryKeyHandle}.
"""
handle, path = self._split_path(path)
if self._machine is not None:
handle = self._connect_hive(handle)
return handle, path
def _join_path(self, hive, subkey):
"""
Joins the hive and key to make a Registry path.
@type hive: int
@param hive: Registry hive handle.
The hive handle must be one of the following integer constants:
- L{win32.HKEY_CLASSES_ROOT}
- L{win32.HKEY_CURRENT_USER}
- L{win32.HKEY_LOCAL_MACHINE}
- L{win32.HKEY_USERS}
- L{win32.HKEY_PERFORMANCE_DATA}
- L{win32.HKEY_CURRENT_CONFIG}
@type subkey: str
@param subkey: Subkey path.
@rtype: str
@return: Registry path.
"""
path = self._hives_by_value[hive]
if subkey:
path = path + '\\' + subkey
return path
def _sanitize_path(self, path):
"""
Sanitizes the given Registry path.
@type path: str
@param path: Registry path.
@rtype: str
@return: Registry path.
"""
return self._join_path( *self._split_path(path) )
def _connect_hive(self, hive):
"""
Connect to the specified hive of a remote Registry.
@note: The connection will be cached, to close all connections and
erase this cache call the L{close} method.
@type hive: int
@param hive: Hive to connect to.
@rtype: L{win32.RegistryKeyHandle}
@return: Open handle to the remote Registry hive.
"""
try:
handle = self._remote_hives[hive]
except KeyError:
handle = win32.RegConnectRegistry(self._machine, hive)
self._remote_hives[hive] = handle
return handle
def close(self):
"""
Closes all open connections to the remote Registry.
No exceptions are raised, even if an error occurs.
This method has no effect when opening the local Registry.
The remote Registry will still be accessible after calling this method
(new connections will be opened automatically on access).
"""
while self._remote_hives:
hive = self._remote_hives.popitem()[1]
try:
hive.close()
except Exception:
try:
e = sys.exc_info()[1]
msg = "Cannot close registry hive handle %s, reason: %s"
msg %= (hive.value, str(e))
warnings.warn(msg)
except Exception:
pass
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def __repr__(self):
if self._machine:
return '<Remote Registry at "%s">' % self._machine
return '<Local Registry>'
def __contains__(self, path):
hive, subpath = self._parse_path(path)
try:
with win32.RegOpenKey(hive, subpath):
return True
except WindowsError:
e = sys.exc_info()[1]
if e.winerror == win32.ERROR_FILE_NOT_FOUND:
return False
raise
def __getitem__(self, path):
path = self._sanitize_path(path)
hive, subpath = self._parse_path(path)
try:
handle = win32.RegOpenKey(hive, subpath)
except WindowsError:
e = sys.exc_info()[1]
if e.winerror == win32.ERROR_FILE_NOT_FOUND:
raise KeyError(path)
raise
return RegistryKey(path, handle)
def __setitem__(self, path, value):
do_copy = isinstance(value, RegistryKey)
if not do_copy and not isinstance(value, str) \
and not isinstance(value, compat.unicode):
if isinstance(value, object):
t = value.__class__.__name__
else:
t = type(value)
raise TypeError("Expected string or RegistryKey, got %s" % t)
hive, subpath = self._parse_path(path)
with win32.RegCreateKey(hive, subpath) as handle:
if do_copy:
win32.RegCopyTree(value.handle, None, handle)
else:
win32.RegSetValueEx(handle, None, value)
# XXX FIXME currently not working!
# It's probably best to call RegDeleteKey recursively, even if slower.
def __delitem__(self, path):
hive, subpath = self._parse_path(path)
if not subpath:
raise TypeError(
"Are you SURE you want to wipe out an entire hive?!"
" Call win32.RegDeleteTree() directly if you must...")
try:
win32.RegDeleteTree(hive, subpath)
except WindowsError:
e = sys.exc_info()[1]
if e.winerror == win32.ERROR_FILE_NOT_FOUND:
raise KeyError(path)
raise
def create(self, path):
"""
Creates a new Registry key.
@type path: str
@param path: Registry key path.
@rtype: L{RegistryKey}
@return: The newly created Registry key.
"""
path = self._sanitize_path(path)
hive, subpath = self._parse_path(path)
handle = win32.RegCreateKey(hive, subpath)
return RegistryKey(path, handle)
def subkeys(self, path):
"""
Returns a list of subkeys for the given Registry key.
@type path: str
@param path: Registry key path.
@rtype: list(str)
@return: List of subkey names.
"""
result = list()
hive, subpath = self._parse_path(path)
with win32.RegOpenKey(hive, subpath) as handle:
index = 0
while 1:
name = win32.RegEnumKey(handle, index)
if name is None:
break
result.append(name)
index += 1
return result
def iterate(self, path):
"""
Returns a recursive iterator on the specified key and its subkeys.
@type path: str
@param path: Registry key path.
@rtype: iterator
@return: Recursive iterator that returns Registry key paths.
@raise KeyError: The specified path does not exist.
"""
if path.endswith('\\'):
path = path[:-1]
if not self.has_key(path):
raise KeyError(path)
stack = collections.deque()
stack.appendleft(path)
return self.__iterate(stack)
def iterkeys(self):
"""
Returns an iterator that crawls the entire Windows Registry.
"""
stack = collections.deque(self._hives)
stack.reverse()
return self.__iterate(stack)
def __iterate(self, stack):
while stack:
path = stack.popleft()
yield path
try:
subkeys = self.subkeys(path)
except WindowsError:
continue
prefix = path + '\\'
subkeys = [prefix + name for name in subkeys]
stack.extendleft(subkeys)
| 21,569 | Python | 29.991379 | 95 | 0.557652 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/debug.py | #!~/.wine/drive_c/Python25/python.exe
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Debugging.
@group Debugging:
Debug
@group Warnings:
MixedBitsWarning
"""
__revision__ = "$Id$"
__all__ = [ 'Debug', 'MixedBitsWarning' ]
import sys
from winappdbg import win32
from winappdbg.system import System
from winappdbg.process import Process
from winappdbg.thread import Thread
from winappdbg.module import Module
from winappdbg.window import Window
from winappdbg.breakpoint import _BreakpointContainer, CodeBreakpoint
from winappdbg.event import Event, EventHandler, EventDispatcher, EventFactory
from winappdbg.interactive import ConsoleDebugger
import warnings
##import traceback
#==============================================================================
# If you set this warning to be considered as an error, you can stop the
# debugger from attaching to 64-bit processes from a 32-bit Python VM and
# visceversa.
class MixedBitsWarning (RuntimeWarning):
"""
This warning is issued when mixing 32 and 64 bit processes.
"""
#==============================================================================
# TODO
# * Add memory read and write operations, similar to those in the Process
# class, but hiding the presence of the code breakpoints.
# * Add a method to get the memory map of a process, but hiding the presence
# of the page breakpoints.
# * Maybe the previous two features should be implemented at the Process class
# instead, but how to communicate with the Debug object without creating
# circular references? Perhaps the "overrides" could be set using private
# members (so users won't see them), but then there's the problem of the
# users being able to access the snapshot (i.e. clear it), which is why it's
# not such a great idea to use the snapshot to store data that really belongs
# to the Debug class.
class Debug (EventDispatcher, _BreakpointContainer):
"""
The main debugger class.
@group Debugging:
interactive, attach, detach, detach_from_all, execv, execl,
kill, kill_all,
get_debugee_count, get_debugee_pids,
is_debugee, is_debugee_attached, is_debugee_started,
in_hostile_mode,
add_existing_session
@group Debugging loop:
loop, stop, next, wait, dispatch, cont
@undocumented: force_garbage_collection
@type system: L{System}
@ivar system: A System snapshot that is automatically updated for
processes being debugged. Processes not being debugged in this snapshot
may be outdated.
"""
# Automatically set to True the first time a Debug object is instanced.
_debug_static_init = False
def __init__(self, eventHandler = None, bKillOnExit = False,
bHostileCode = False):
"""
Debugger object.
@type eventHandler: L{EventHandler}
@param eventHandler:
(Optional, recommended) Custom event handler object.
@type bKillOnExit: bool
@param bKillOnExit: (Optional) Kill on exit mode.
If C{True} debugged processes are killed when the debugger is
stopped. If C{False} when the debugger stops it detaches from all
debugged processes and leaves them running (default).
@type bHostileCode: bool
@param bHostileCode: (Optional) Hostile code mode.
Set to C{True} to take some basic precautions against anti-debug
tricks. Disabled by default.
@warn: When hostile mode is enabled, some things may not work as
expected! This is because the anti-anti debug tricks may disrupt
the behavior of the Win32 debugging APIs or WinAppDbg itself.
@note: The L{eventHandler} parameter may be any callable Python object
(for example a function, or an instance method).
However you'll probably find it more convenient to use an instance
of a subclass of L{EventHandler} here.
@raise WindowsError: Raises an exception on error.
"""
EventDispatcher.__init__(self, eventHandler)
_BreakpointContainer.__init__(self)
self.system = System()
self.lastEvent = None
self.__firstDebugee = True
self.__bKillOnExit = bKillOnExit
self.__bHostileCode = bHostileCode
self.__breakOnEP = set() # set of pids
self.__attachedDebugees = set() # set of pids
self.__startedDebugees = set() # set of pids
if not self._debug_static_init:
self._debug_static_init = True
# Request debug privileges for the current process.
# Only do this once, and only after instancing a Debug object,
# so passive debuggers don't get detected because of this.
self.system.request_debug_privileges(bIgnoreExceptions = False)
# Try to fix the symbol store path if it wasn't set.
# But don't enable symbol downloading by default, since it may
# degrade performance severely.
self.system.fix_symbol_store_path(remote = False, force = False)
## # It's hard not to create circular references,
## # and if we have a destructor, we can end up leaking everything.
## # It's best to code the debugging loop properly to always
## # stop the debugger before going out of scope.
## def __del__(self):
## self.stop()
def __enter__(self):
"""
Compatibility with the "C{with}" Python statement.
"""
return self
def __exit__(self, type, value, traceback):
"""
Compatibility with the "C{with}" Python statement.
"""
self.stop()
def __len__(self):
"""
@rtype: int
@return: Number of processes being debugged.
"""
return self.get_debugee_count()
# TODO: maybe custom __bool__ to break out of loop() ?
# it already does work (because of __len__) but it'd be
# useful to do it from the event handler anyway
#------------------------------------------------------------------------------
def __setSystemKillOnExitMode(self):
# Make sure the default system behavior on detaching from processes
# versus killing them matches our preferences. This only affects the
# scenario where the Python VM dies unexpectedly without running all
# the finally clauses, or the user failed to either instance the Debug
# object inside a with block or call the stop() method before quitting.
if self.__firstDebugee:
try:
System.set_kill_on_exit_mode(self.__bKillOnExit)
self.__firstDebugee = False
except Exception:
pass
def attach(self, dwProcessId):
"""
Attaches to an existing process for debugging.
@see: L{detach}, L{execv}, L{execl}
@type dwProcessId: int
@param dwProcessId: Global ID of a process to attach to.
@rtype: L{Process}
@return: A new Process object. Normally you don't need to use it now,
it's best to interact with the process from the event handler.
@raise WindowsError: Raises an exception on error.
Depending on the circumstances, the debugger may or may not have
attached to the target process.
"""
# Get the Process object from the snapshot,
# if missing create a new one.
try:
aProcess = self.system.get_process(dwProcessId)
except KeyError:
aProcess = Process(dwProcessId)
# Warn when mixing 32 and 64 bits.
# This also allows the user to stop attaching altogether,
# depending on how the warnings are configured.
if System.bits != aProcess.get_bits():
msg = "Mixture of 32 and 64 bits is considered experimental." \
" Use at your own risk!"
warnings.warn(msg, MixedBitsWarning)
# Attach to the process.
win32.DebugActiveProcess(dwProcessId)
# Add the new PID to the set of debugees.
self.__attachedDebugees.add(dwProcessId)
# Match the system kill-on-exit flag to our own.
self.__setSystemKillOnExitMode()
# If the Process object was not in the snapshot, add it now.
if not self.system.has_process(dwProcessId):
self.system._add_process(aProcess)
# Scan the process threads and loaded modules.
# This is prefered because the thread and library events do not
# properly give some information, like the filename for each module.
aProcess.scan_threads()
aProcess.scan_modules()
# Return the Process object, like the execv() and execl() methods.
return aProcess
def execv(self, argv, **kwargs):
"""
Starts a new process for debugging.
This method uses a list of arguments. To use a command line string
instead, use L{execl}.
@see: L{attach}, L{detach}
@type argv: list( str... )
@param argv: List of command line arguments to pass to the debugee.
The first element must be the debugee executable filename.
@type bBreakOnEntryPoint: bool
@keyword bBreakOnEntryPoint: C{True} to automatically set a breakpoint
at the program entry point.
@type bConsole: bool
@keyword bConsole: True to inherit the console of the debugger.
Defaults to C{False}.
@type bFollow: bool
@keyword bFollow: C{True} to automatically attach to child processes.
Defaults to C{False}.
@type bInheritHandles: bool
@keyword bInheritHandles: C{True} if the new process should inherit
it's parent process' handles. Defaults to C{False}.
@type bSuspended: bool
@keyword bSuspended: C{True} to suspend the main thread before any code
is executed in the debugee. Defaults to C{False}.
@keyword dwParentProcessId: C{None} or C{0} if the debugger process
should be the parent process (default), or a process ID to
forcefully set as the debugee's parent (only available for Windows
Vista and above).
In hostile mode, the default is not the debugger process but the
process ID for "explorer.exe".
@type iTrustLevel: int or None
@keyword iTrustLevel: Trust level.
Must be one of the following values:
- 0: B{No trust}. May not access certain resources, such as
cryptographic keys and credentials. Only available since
Windows XP and 2003, desktop editions. This is the default
in hostile mode.
- 1: B{Normal trust}. Run with the same privileges as a normal
user, that is, one that doesn't have the I{Administrator} or
I{Power User} user rights. Only available since Windows XP
and 2003, desktop editions.
- 2: B{Full trust}. Run with the exact same privileges as the
current user. This is the default in normal mode.
@type bAllowElevation: bool
@keyword bAllowElevation: C{True} to allow the child process to keep
UAC elevation, if the debugger itself is running elevated. C{False}
to ensure the child process doesn't run with elevation. Defaults to
C{True}.
This flag is only meaningful on Windows Vista and above, and if the
debugger itself is running with elevation. It can be used to make
sure the child processes don't run elevated as well.
This flag DOES NOT force an elevation prompt when the debugger is
not running with elevation.
Note that running the debugger with elevation (or the Python
interpreter at all for that matter) is not normally required.
You should only need to if the target program requires elevation
to work properly (for example if you try to debug an installer).
@rtype: L{Process}
@return: A new Process object. Normally you don't need to use it now,
it's best to interact with the process from the event handler.
@raise WindowsError: Raises an exception on error.
"""
if type(argv) in (str, compat.unicode):
raise TypeError("Debug.execv expects a list, not a string")
lpCmdLine = self.system.argv_to_cmdline(argv)
return self.execl(lpCmdLine, **kwargs)
def execl(self, lpCmdLine, **kwargs):
"""
Starts a new process for debugging.
This method uses a command line string. To use a list of arguments
instead, use L{execv}.
@see: L{attach}, L{detach}
@type lpCmdLine: str
@param lpCmdLine: Command line string to execute.
The first token must be the debugee executable filename.
Tokens with spaces must be enclosed in double quotes.
Tokens including double quote characters must be escaped with a
backslash.
@type bBreakOnEntryPoint: bool
@keyword bBreakOnEntryPoint: C{True} to automatically set a breakpoint
at the program entry point. Defaults to C{False}.
@type bConsole: bool
@keyword bConsole: True to inherit the console of the debugger.
Defaults to C{False}.
@type bFollow: bool
@keyword bFollow: C{True} to automatically attach to child processes.
Defaults to C{False}.
@type bInheritHandles: bool
@keyword bInheritHandles: C{True} if the new process should inherit
it's parent process' handles. Defaults to C{False}.
@type bSuspended: bool
@keyword bSuspended: C{True} to suspend the main thread before any code
is executed in the debugee. Defaults to C{False}.
@type dwParentProcessId: int or None
@keyword dwParentProcessId: C{None} or C{0} if the debugger process
should be the parent process (default), or a process ID to
forcefully set as the debugee's parent (only available for Windows
Vista and above).
In hostile mode, the default is not the debugger process but the
process ID for "explorer.exe".
@type iTrustLevel: int
@keyword iTrustLevel: Trust level.
Must be one of the following values:
- 0: B{No trust}. May not access certain resources, such as
cryptographic keys and credentials. Only available since
Windows XP and 2003, desktop editions. This is the default
in hostile mode.
- 1: B{Normal trust}. Run with the same privileges as a normal
user, that is, one that doesn't have the I{Administrator} or
I{Power User} user rights. Only available since Windows XP
and 2003, desktop editions.
- 2: B{Full trust}. Run with the exact same privileges as the
current user. This is the default in normal mode.
@type bAllowElevation: bool
@keyword bAllowElevation: C{True} to allow the child process to keep
UAC elevation, if the debugger itself is running elevated. C{False}
to ensure the child process doesn't run with elevation. Defaults to
C{True} in normal mode and C{False} in hostile mode.
This flag is only meaningful on Windows Vista and above, and if the
debugger itself is running with elevation. It can be used to make
sure the child processes don't run elevated as well.
This flag DOES NOT force an elevation prompt when the debugger is
not running with elevation.
Note that running the debugger with elevation (or the Python
interpreter at all for that matter) is not normally required.
You should only need to if the target program requires elevation
to work properly (for example if you try to debug an installer).
@rtype: L{Process}
@return: A new Process object. Normally you don't need to use it now,
it's best to interact with the process from the event handler.
@raise WindowsError: Raises an exception on error.
"""
if type(lpCmdLine) not in (str, compat.unicode):
warnings.warn("Debug.execl expects a string")
# Set the "debug" flag to True.
kwargs['bDebug'] = True
# Pop the "break on entry point" flag.
bBreakOnEntryPoint = kwargs.pop('bBreakOnEntryPoint', False)
# Set the default trust level if requested.
if 'iTrustLevel' not in kwargs:
if self.__bHostileCode:
kwargs['iTrustLevel'] = 0
else:
kwargs['iTrustLevel'] = 2
# Set the default UAC elevation flag if requested.
if 'bAllowElevation' not in kwargs:
kwargs['bAllowElevation'] = not self.__bHostileCode
# In hostile mode the default parent process is explorer.exe.
# Only supported for Windows Vista and above.
if self.__bHostileCode and not kwargs.get('dwParentProcessId', None):
try:
vista_and_above = self.__vista_and_above
except AttributeError:
osi = win32.OSVERSIONINFOEXW()
osi.dwMajorVersion = 6
osi.dwMinorVersion = 0
osi.dwPlatformId = win32.VER_PLATFORM_WIN32_NT
mask = 0
mask = win32.VerSetConditionMask(mask,
win32.VER_MAJORVERSION,
win32.VER_GREATER_EQUAL)
mask = win32.VerSetConditionMask(mask,
win32.VER_MAJORVERSION,
win32.VER_GREATER_EQUAL)
mask = win32.VerSetConditionMask(mask,
win32.VER_PLATFORMID,
win32.VER_EQUAL)
vista_and_above = win32.VerifyVersionInfoW(osi,
win32.VER_MAJORVERSION | \
win32.VER_MINORVERSION | \
win32.VER_PLATFORMID,
mask)
self.__vista_and_above = vista_and_above
if vista_and_above:
dwParentProcessId = self.system.get_explorer_pid()
if dwParentProcessId:
kwargs['dwParentProcessId'] = dwParentProcessId
else:
msg = ("Failed to find \"explorer.exe\"!"
" Using the debugger as parent process.")
warnings.warn(msg, RuntimeWarning)
# Start the new process.
aProcess = None
try:
aProcess = self.system.start_process(lpCmdLine, **kwargs)
dwProcessId = aProcess.get_pid()
# Match the system kill-on-exit flag to our own.
self.__setSystemKillOnExitMode()
# Warn when mixing 32 and 64 bits.
# This also allows the user to stop attaching altogether,
# depending on how the warnings are configured.
if System.bits != aProcess.get_bits():
msg = "Mixture of 32 and 64 bits is considered experimental." \
" Use at your own risk!"
warnings.warn(msg, MixedBitsWarning)
# Add the new PID to the set of debugees.
self.__startedDebugees.add(dwProcessId)
# Add the new PID to the set of "break on EP" debugees if needed.
if bBreakOnEntryPoint:
self.__breakOnEP.add(dwProcessId)
# Return the Process object.
return aProcess
# On error kill the new process and raise an exception.
except:
if aProcess is not None:
try:
try:
self.__startedDebugees.remove(aProcess.get_pid())
except KeyError:
pass
finally:
try:
try:
self.__breakOnEP.remove(aProcess.get_pid())
except KeyError:
pass
finally:
try:
aProcess.kill()
except Exception:
pass
raise
def add_existing_session(self, dwProcessId, bStarted = False):
"""
Use this method only when for some reason the debugger's been attached
to the target outside of WinAppDbg (for example when integrating with
other tools).
You don't normally need to call this method. Most users should call
L{attach}, L{execv} or L{execl} instead.
@type dwProcessId: int
@param dwProcessId: Global process ID.
@type bStarted: bool
@param bStarted: C{True} if the process was started by the debugger,
or C{False} if the process was attached to instead.
@raise WindowsError: The target process does not exist, is not attached
to the debugger anymore.
"""
# Register the process object with the snapshot.
if not self.system.has_process(dwProcessId):
aProcess = Process(dwProcessId)
self.system._add_process(aProcess)
else:
aProcess = self.system.get_process(dwProcessId)
# Test for debug privileges on the target process.
# Raises WindowsException on error.
aProcess.get_handle()
# Register the process ID with the debugger.
if bStarted:
self.__attachedDebugees.add(dwProcessId)
else:
self.__startedDebugees.add(dwProcessId)
# Match the system kill-on-exit flag to our own.
self.__setSystemKillOnExitMode()
# Scan the process threads and loaded modules.
# This is prefered because the thread and library events do not
# properly give some information, like the filename for each module.
aProcess.scan_threads()
aProcess.scan_modules()
def __cleanup_process(self, dwProcessId, bIgnoreExceptions = False):
"""
Perform the necessary cleanup of a process about to be killed or
detached from.
This private method is called by L{kill} and L{detach}.
@type dwProcessId: int
@param dwProcessId: Global ID of a process to kill.
@type bIgnoreExceptions: bool
@param bIgnoreExceptions: C{True} to ignore any exceptions that may be
raised when killing the process.
@raise WindowsError: Raises an exception on error, unless
C{bIgnoreExceptions} is C{True}.
"""
# If the process is being debugged...
if self.is_debugee(dwProcessId):
# Make sure a Process object exists or the following calls fail.
if not self.system.has_process(dwProcessId):
aProcess = Process(dwProcessId)
try:
aProcess.get_handle()
except WindowsError:
pass # fails later on with more specific reason
self.system._add_process(aProcess)
# Erase all breakpoints in the process.
try:
self.erase_process_breakpoints(dwProcessId)
except Exception:
if not bIgnoreExceptions:
raise
e = sys.exc_info()[1]
warnings.warn(str(e), RuntimeWarning)
# Stop tracing all threads in the process.
try:
self.stop_tracing_process(dwProcessId)
except Exception:
if not bIgnoreExceptions:
raise
e = sys.exc_info()[1]
warnings.warn(str(e), RuntimeWarning)
# The process is no longer a debugee.
try:
if dwProcessId in self.__attachedDebugees:
self.__attachedDebugees.remove(dwProcessId)
if dwProcessId in self.__startedDebugees:
self.__startedDebugees.remove(dwProcessId)
except Exception:
if not bIgnoreExceptions:
raise
e = sys.exc_info()[1]
warnings.warn(str(e), RuntimeWarning)
# Clear and remove the process from the snapshot.
# If the user wants to do something with it after detaching
# a new Process instance should be created.
try:
if self.system.has_process(dwProcessId):
try:
self.system.get_process(dwProcessId).clear()
finally:
self.system._del_process(dwProcessId)
except Exception:
if not bIgnoreExceptions:
raise
e = sys.exc_info()[1]
warnings.warn(str(e), RuntimeWarning)
# If the last debugging event is related to this process, forget it.
try:
if self.lastEvent and self.lastEvent.get_pid() == dwProcessId:
self.lastEvent = None
except Exception:
if not bIgnoreExceptions:
raise
e = sys.exc_info()[1]
warnings.warn(str(e), RuntimeWarning)
def kill(self, dwProcessId, bIgnoreExceptions = False):
"""
Kills a process currently being debugged.
@see: L{detach}
@type dwProcessId: int
@param dwProcessId: Global ID of a process to kill.
@type bIgnoreExceptions: bool
@param bIgnoreExceptions: C{True} to ignore any exceptions that may be
raised when killing the process.
@raise WindowsError: Raises an exception on error, unless
C{bIgnoreExceptions} is C{True}.
"""
# Keep a reference to the process. We'll need it later.
try:
aProcess = self.system.get_process(dwProcessId)
except KeyError:
aProcess = Process(dwProcessId)
# Cleanup all data referring to the process.
self.__cleanup_process(dwProcessId,
bIgnoreExceptions = bIgnoreExceptions)
# Kill the process.
try:
try:
if self.is_debugee(dwProcessId):
try:
if aProcess.is_alive():
aProcess.suspend()
finally:
self.detach(dwProcessId,
bIgnoreExceptions = bIgnoreExceptions)
finally:
aProcess.kill()
except Exception:
if not bIgnoreExceptions:
raise
e = sys.exc_info()[1]
warnings.warn(str(e), RuntimeWarning)
# Cleanup what remains of the process data.
try:
aProcess.clear()
except Exception:
if not bIgnoreExceptions:
raise
e = sys.exc_info()[1]
warnings.warn(str(e), RuntimeWarning)
def kill_all(self, bIgnoreExceptions = False):
"""
Kills from all processes currently being debugged.
@type bIgnoreExceptions: bool
@param bIgnoreExceptions: C{True} to ignore any exceptions that may be
raised when killing each process. C{False} to stop and raise an
exception when encountering an error.
@raise WindowsError: Raises an exception on error, unless
C{bIgnoreExceptions} is C{True}.
"""
for pid in self.get_debugee_pids():
self.kill(pid, bIgnoreExceptions = bIgnoreExceptions)
def detach(self, dwProcessId, bIgnoreExceptions = False):
"""
Detaches from a process currently being debugged.
@note: On Windows 2000 and below the process is killed.
@see: L{attach}, L{detach_from_all}
@type dwProcessId: int
@param dwProcessId: Global ID of a process to detach from.
@type bIgnoreExceptions: bool
@param bIgnoreExceptions: C{True} to ignore any exceptions that may be
raised when detaching. C{False} to stop and raise an exception when
encountering an error.
@raise WindowsError: Raises an exception on error, unless
C{bIgnoreExceptions} is C{True}.
"""
# Keep a reference to the process. We'll need it later.
try:
aProcess = self.system.get_process(dwProcessId)
except KeyError:
aProcess = Process(dwProcessId)
# Determine if there is support for detaching.
# This check should only fail on Windows 2000 and older.
try:
win32.DebugActiveProcessStop
can_detach = True
except AttributeError:
can_detach = False
# Continue the last event before detaching.
# XXX not sure about this...
try:
if can_detach and self.lastEvent and \
self.lastEvent.get_pid() == dwProcessId:
self.cont(self.lastEvent)
except Exception:
if not bIgnoreExceptions:
raise
e = sys.exc_info()[1]
warnings.warn(str(e), RuntimeWarning)
# Cleanup all data referring to the process.
self.__cleanup_process(dwProcessId,
bIgnoreExceptions = bIgnoreExceptions)
try:
# Detach from the process.
# On Windows 2000 and before, kill the process.
if can_detach:
try:
win32.DebugActiveProcessStop(dwProcessId)
except Exception:
if not bIgnoreExceptions:
raise
e = sys.exc_info()[1]
warnings.warn(str(e), RuntimeWarning)
else:
try:
aProcess.kill()
except Exception:
if not bIgnoreExceptions:
raise
e = sys.exc_info()[1]
warnings.warn(str(e), RuntimeWarning)
finally:
# Cleanup what remains of the process data.
aProcess.clear()
def detach_from_all(self, bIgnoreExceptions = False):
"""
Detaches from all processes currently being debugged.
@note: To better handle last debugging event, call L{stop} instead.
@type bIgnoreExceptions: bool
@param bIgnoreExceptions: C{True} to ignore any exceptions that may be
raised when detaching.
@raise WindowsError: Raises an exception on error, unless
C{bIgnoreExceptions} is C{True}.
"""
for pid in self.get_debugee_pids():
self.detach(pid, bIgnoreExceptions = bIgnoreExceptions)
#------------------------------------------------------------------------------
def wait(self, dwMilliseconds = None):
"""
Waits for the next debug event.
@see: L{cont}, L{dispatch}, L{loop}
@type dwMilliseconds: int
@param dwMilliseconds: (Optional) Timeout in milliseconds.
Use C{INFINITE} or C{None} for no timeout.
@rtype: L{Event}
@return: An event that occured in one of the debugees.
@raise WindowsError: Raises an exception on error.
If no target processes are left to debug,
the error code is L{win32.ERROR_INVALID_HANDLE}.
"""
# Wait for the next debug event.
raw = win32.WaitForDebugEvent(dwMilliseconds)
event = EventFactory.get(self, raw)
# Remember it.
self.lastEvent = event
# Return it.
return event
def dispatch(self, event = None):
"""
Calls the debug event notify callbacks.
@see: L{cont}, L{loop}, L{wait}
@type event: L{Event}
@param event: (Optional) Event object returned by L{wait}.
@raise WindowsError: Raises an exception on error.
"""
# If no event object was given, use the last event.
if event is None:
event = self.lastEvent
# Ignore dummy events.
if not event:
return
# Determine the default behaviour for this event.
# XXX HACK
# Some undocumented flags are used, but as far as I know in those
# versions of Windows that don't support them they should behave
# like DGB_CONTINUE.
code = event.get_event_code()
if code == win32.EXCEPTION_DEBUG_EVENT:
# At this point, by default some exception types are swallowed by
# the debugger, because we don't know yet if it was caused by the
# debugger itself or the debugged process.
#
# Later on (see breakpoint.py) if we determined the exception was
# not caused directly by the debugger itself, we set the default
# back to passing the exception to the debugee.
#
# The "invalid handle" exception is also swallowed by the debugger
# because it's not normally generated by the debugee. But in
# hostile mode we want to pass it to the debugee, as it may be the
# result of an anti-debug trick. In that case it's best to disable
# bad handles detection with Microsoft's gflags.exe utility. See:
# http://msdn.microsoft.com/en-us/library/windows/hardware/ff549557(v=vs.85).aspx
exc_code = event.get_exception_code()
if exc_code in (
win32.EXCEPTION_BREAKPOINT,
win32.EXCEPTION_WX86_BREAKPOINT,
win32.EXCEPTION_SINGLE_STEP,
win32.EXCEPTION_GUARD_PAGE,
):
event.continueStatus = win32.DBG_CONTINUE
elif exc_code == win32.EXCEPTION_INVALID_HANDLE:
if self.__bHostileCode:
event.continueStatus = win32.DBG_EXCEPTION_NOT_HANDLED
else:
event.continueStatus = win32.DBG_CONTINUE
else:
event.continueStatus = win32.DBG_EXCEPTION_NOT_HANDLED
elif code == win32.RIP_EVENT and \
event.get_rip_type() == win32.SLE_ERROR:
# RIP events that signal fatal events should kill the process.
event.continueStatus = win32.DBG_TERMINATE_PROCESS
else:
# Other events need this continue code.
# Sometimes other codes can be used and are ignored, sometimes not.
# For example, when using the DBG_EXCEPTION_NOT_HANDLED code,
# debug strings are sent twice (!)
event.continueStatus = win32.DBG_CONTINUE
# Dispatch the debug event.
return EventDispatcher.dispatch(self, event)
def cont(self, event = None):
"""
Resumes execution after processing a debug event.
@see: dispatch(), loop(), wait()
@type event: L{Event}
@param event: (Optional) Event object returned by L{wait}.
@raise WindowsError: Raises an exception on error.
"""
# If no event object was given, use the last event.
if event is None:
event = self.lastEvent
# Ignore dummy events.
if not event:
return
# Get the event continue status information.
dwProcessId = event.get_pid()
dwThreadId = event.get_tid()
dwContinueStatus = event.continueStatus
# Check if the process is still being debugged.
if self.is_debugee(dwProcessId):
# Try to flush the instruction cache.
try:
if self.system.has_process(dwProcessId):
aProcess = self.system.get_process(dwProcessId)
else:
aProcess = Process(dwProcessId)
aProcess.flush_instruction_cache()
except WindowsError:
pass
# XXX TODO
#
# Try to execute the UnhandledExceptionFilter for second chance
# exceptions, at least when in hostile mode (in normal mode it
# would be breaking compatibility, as users may actually expect
# second chance exceptions to be raised again).
#
# Reportedly in Windows 7 (maybe in Vista too) this seems to be
# happening already. In XP and below the UnhandledExceptionFilter
# was never called for processes being debugged.
# Continue execution of the debugee.
win32.ContinueDebugEvent(dwProcessId, dwThreadId, dwContinueStatus)
# If the event is the last event, forget it.
if event == self.lastEvent:
self.lastEvent = None
def stop(self, bIgnoreExceptions = True):
"""
Stops debugging all processes.
If the kill on exit mode is on, debugged processes are killed when the
debugger is stopped. Otherwise when the debugger stops it detaches from
all debugged processes and leaves them running (default). For more
details see: L{__init__}
@note: This method is better than L{detach_from_all} because it can
gracefully handle the last debugging event before detaching.
@type bIgnoreExceptions: bool
@param bIgnoreExceptions: C{True} to ignore any exceptions that may be
raised when detaching.
"""
# Determine if we have a last debug event that we need to continue.
try:
event = self.lastEvent
has_event = bool(event)
except Exception:
if not bIgnoreExceptions:
raise
e = sys.exc_info()[1]
warnings.warn(str(e), RuntimeWarning)
has_event = False
# If we do...
if has_event:
# Disable all breakpoints in the process before resuming execution.
try:
pid = event.get_pid()
self.disable_process_breakpoints(pid)
except Exception:
if not bIgnoreExceptions:
raise
e = sys.exc_info()[1]
warnings.warn(str(e), RuntimeWarning)
# Disable all breakpoints in the thread before resuming execution.
try:
tid = event.get_tid()
self.disable_thread_breakpoints(tid)
except Exception:
if not bIgnoreExceptions:
raise
e = sys.exc_info()[1]
warnings.warn(str(e), RuntimeWarning)
# Resume execution.
try:
event.continueDebugEvent = win32.DBG_CONTINUE
self.cont(event)
except Exception:
if not bIgnoreExceptions:
raise
e = sys.exc_info()[1]
warnings.warn(str(e), RuntimeWarning)
# Detach from or kill all debuggees.
try:
if self.__bKillOnExit:
self.kill_all(bIgnoreExceptions)
else:
self.detach_from_all(bIgnoreExceptions)
except Exception:
if not bIgnoreExceptions:
raise
e = sys.exc_info()[1]
warnings.warn(str(e), RuntimeWarning)
# Cleanup the process snapshots.
try:
self.system.clear()
except Exception:
if not bIgnoreExceptions:
raise
e = sys.exc_info()[1]
warnings.warn(str(e), RuntimeWarning)
# Close all Win32 handles the Python garbage collector failed to close.
self.force_garbage_collection(bIgnoreExceptions)
def next(self):
"""
Handles the next debug event.
@see: L{cont}, L{dispatch}, L{wait}, L{stop}
@raise WindowsError: Raises an exception on error.
If the wait operation causes an error, debugging is stopped
(meaning all debugees are either killed or detached from).
If the event dispatching causes an error, the event is still
continued before returning. This may happen, for example, if the
event handler raises an exception nobody catches.
"""
try:
event = self.wait()
except Exception:
self.stop()
raise
try:
self.dispatch()
finally:
self.cont()
def loop(self):
"""
Simple debugging loop.
This debugging loop is meant to be useful for most simple scripts.
It iterates as long as there is at least one debugee, or an exception
is raised. Multiple calls are allowed.
This is a trivial example script::
import sys
debug = Debug()
try:
debug.execv( sys.argv [ 1 : ] )
debug.loop()
finally:
debug.stop()
@see: L{next}, L{stop}
U{http://msdn.microsoft.com/en-us/library/ms681675(VS.85).aspx}
@raise WindowsError: Raises an exception on error.
If the wait operation causes an error, debugging is stopped
(meaning all debugees are either killed or detached from).
If the event dispatching causes an error, the event is still
continued before returning. This may happen, for example, if the
event handler raises an exception nobody catches.
"""
while self:
self.next()
def get_debugee_count(self):
"""
@rtype: int
@return: Number of processes being debugged.
"""
return len(self.__attachedDebugees) + len(self.__startedDebugees)
def get_debugee_pids(self):
"""
@rtype: list( int... )
@return: Global IDs of processes being debugged.
"""
return list(self.__attachedDebugees) + list(self.__startedDebugees)
def is_debugee(self, dwProcessId):
"""
Determine if the debugger is debugging the given process.
@see: L{is_debugee_attached}, L{is_debugee_started}
@type dwProcessId: int
@param dwProcessId: Process global ID.
@rtype: bool
@return: C{True} if the given process is being debugged
by this L{Debug} instance.
"""
return self.is_debugee_attached(dwProcessId) or \
self.is_debugee_started(dwProcessId)
def is_debugee_started(self, dwProcessId):
"""
Determine if the given process was started by the debugger.
@see: L{is_debugee}, L{is_debugee_attached}
@type dwProcessId: int
@param dwProcessId: Process global ID.
@rtype: bool
@return: C{True} if the given process was started for debugging by this
L{Debug} instance.
"""
return dwProcessId in self.__startedDebugees
def is_debugee_attached(self, dwProcessId):
"""
Determine if the debugger is attached to the given process.
@see: L{is_debugee}, L{is_debugee_started}
@type dwProcessId: int
@param dwProcessId: Process global ID.
@rtype: bool
@return: C{True} if the given process is attached to this
L{Debug} instance.
"""
return dwProcessId in self.__attachedDebugees
def in_hostile_mode(self):
"""
Determine if we're in hostile mode (anti-anti-debug).
@rtype: bool
@return: C{True} if this C{Debug} instance was started in hostile mode,
C{False} otherwise.
"""
return self.__bHostileCode
#------------------------------------------------------------------------------
def interactive(self, bConfirmQuit = True, bShowBanner = True):
"""
Start an interactive debugging session.
@type bConfirmQuit: bool
@param bConfirmQuit: Set to C{True} to ask the user for confirmation
before closing the session, C{False} otherwise.
@type bShowBanner: bool
@param bShowBanner: Set to C{True} to show a banner before entering
the session and after leaving it, C{False} otherwise.
@warn: This will temporarily disable the user-defined event handler!
This method returns when the user closes the session.
"""
print('')
print("-" * 79)
print("Interactive debugging session started.")
print("Use the \"help\" command to list all available commands.")
print("Use the \"quit\" command to close this session.")
print("-" * 79)
if self.lastEvent is None:
print('')
console = ConsoleDebugger()
console.confirm_quit = bConfirmQuit
console.load_history()
try:
console.start_using_debugger(self)
console.loop()
finally:
console.stop_using_debugger()
console.save_history()
print('')
print("-" * 79)
print("Interactive debugging session closed.")
print("-" * 79)
print('')
#------------------------------------------------------------------------------
@staticmethod
def force_garbage_collection(bIgnoreExceptions = True):
"""
Close all Win32 handles the Python garbage collector failed to close.
@type bIgnoreExceptions: bool
@param bIgnoreExceptions: C{True} to ignore any exceptions that may be
raised when detaching.
"""
try:
import gc
gc.collect()
bRecollect = False
for obj in list(gc.garbage):
try:
if isinstance(obj, win32.Handle):
obj.close()
elif isinstance(obj, Event):
obj.debug = None
elif isinstance(obj, Process):
obj.clear()
elif isinstance(obj, Thread):
obj.set_process(None)
obj.clear()
elif isinstance(obj, Module):
obj.set_process(None)
elif isinstance(obj, Window):
obj.set_process(None)
else:
continue
gc.garbage.remove(obj)
del obj
bRecollect = True
except Exception:
if not bIgnoreExceptions:
raise
e = sys.exc_info()[1]
warnings.warn(str(e), RuntimeWarning)
if bRecollect:
gc.collect()
except Exception:
if not bIgnoreExceptions:
raise
e = sys.exc_info()[1]
warnings.warn(str(e), RuntimeWarning)
#------------------------------------------------------------------------------
def _notify_create_process(self, event):
"""
Notify the creation of a new process.
@warning: This method is meant to be used internally by the debugger.
@type event: L{CreateProcessEvent}
@param event: Create process event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} otherwise.
"""
dwProcessId = event.get_pid()
if dwProcessId not in self.__attachedDebugees:
if dwProcessId not in self.__startedDebugees:
self.__startedDebugees.add(dwProcessId)
retval = self.system._notify_create_process(event)
# Set a breakpoint on the program's entry point if requested.
# Try not to use the Event object's entry point value, as in some cases
# it may be wrong. See: http://pferrie.host22.com/misc/lowlevel3.htm
if dwProcessId in self.__breakOnEP:
try:
lpEntryPoint = event.get_process().get_entry_point()
except Exception:
lpEntryPoint = event.get_start_address()
# It'd be best to use a hardware breakpoint instead, at least in
# hostile mode. But since the main thread's context gets smashed
# by the loader, I haven't found a way to make it work yet.
self.break_at(dwProcessId, lpEntryPoint)
# Defeat isDebuggerPresent by patching PEB->BeingDebugged.
# When we do this, some debugging APIs cease to work as expected.
# For example, the system breakpoint isn't hit when we attach.
# For that reason we need to define a code breakpoint at the
# code location where a new thread is spawned by the debugging
# APIs, ntdll!DbgUiRemoteBreakin.
if self.__bHostileCode:
aProcess = event.get_process()
try:
hProcess = aProcess.get_handle(win32.PROCESS_QUERY_INFORMATION)
pbi = win32.NtQueryInformationProcess(
hProcess, win32.ProcessBasicInformation)
ptr = pbi.PebBaseAddress + 2
if aProcess.peek(ptr, 1) == '\x01':
aProcess.poke(ptr, '\x00')
except WindowsError:
e = sys.exc_info()[1]
warnings.warn(
"Cannot patch PEB->BeingDebugged, reason: %s" % e.strerror)
return retval
def _notify_create_thread(self, event):
"""
Notify the creation of a new thread.
@warning: This method is meant to be used internally by the debugger.
@type event: L{CreateThreadEvent}
@param event: Create thread event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} otherwise.
"""
return event.get_process()._notify_create_thread(event)
def _notify_load_dll(self, event):
"""
Notify the load of a new module.
@warning: This method is meant to be used internally by the debugger.
@type event: L{LoadDLLEvent}
@param event: Load DLL event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} otherwise.
"""
# Pass the event to the breakpoint container.
bCallHandler = _BreakpointContainer._notify_load_dll(self, event)
# Get the process where the DLL was loaded.
aProcess = event.get_process()
# Pass the event to the process.
bCallHandler = aProcess._notify_load_dll(event) and bCallHandler
# Anti-anti-debugging tricks on ntdll.dll.
if self.__bHostileCode:
aModule = event.get_module()
if aModule.match_name('ntdll.dll'):
# Since we've overwritten the PEB to hide
# ourselves, we no longer have the system
# breakpoint when attaching to the process.
# Set a breakpoint at ntdll!DbgUiRemoteBreakin
# instead (that's where the debug API spawns
# it's auxiliary threads). This also defeats
# a simple anti-debugging trick: the hostile
# process could have overwritten the int3
# instruction at the system breakpoint.
self.break_at(aProcess.get_pid(),
aProcess.resolve_label('ntdll!DbgUiRemoteBreakin'))
return bCallHandler
def _notify_exit_process(self, event):
"""
Notify the termination of a process.
@warning: This method is meant to be used internally by the debugger.
@type event: L{ExitProcessEvent}
@param event: Exit process event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} otherwise.
"""
bCallHandler1 = _BreakpointContainer._notify_exit_process(self, event)
bCallHandler2 = self.system._notify_exit_process(event)
try:
self.detach( event.get_pid() )
except WindowsError:
e = sys.exc_info()[1]
if e.winerror != win32.ERROR_INVALID_PARAMETER:
warnings.warn(
"Failed to detach from dead process, reason: %s" % str(e),
RuntimeWarning)
except Exception:
e = sys.exc_info()[1]
warnings.warn(
"Failed to detach from dead process, reason: %s" % str(e),
RuntimeWarning)
return bCallHandler1 and bCallHandler2
def _notify_exit_thread(self, event):
"""
Notify the termination of a thread.
@warning: This method is meant to be used internally by the debugger.
@type event: L{ExitThreadEvent}
@param event: Exit thread event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} otherwise.
"""
bCallHandler1 = _BreakpointContainer._notify_exit_thread(self, event)
bCallHandler2 = event.get_process()._notify_exit_thread(event)
return bCallHandler1 and bCallHandler2
def _notify_unload_dll(self, event):
"""
Notify the unload of a module.
@warning: This method is meant to be used internally by the debugger.
@type event: L{UnloadDLLEvent}
@param event: Unload DLL event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} otherwise.
"""
bCallHandler1 = _BreakpointContainer._notify_unload_dll(self, event)
bCallHandler2 = event.get_process()._notify_unload_dll(event)
return bCallHandler1 and bCallHandler2
def _notify_rip(self, event):
"""
Notify of a RIP event.
@warning: This method is meant to be used internally by the debugger.
@type event: L{RIPEvent}
@param event: RIP event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} otherwise.
"""
event.debug.detach( event.get_pid() )
return True
def _notify_debug_control_c(self, event):
"""
Notify of a Debug Ctrl-C exception.
@warning: This method is meant to be used internally by the debugger.
@note: This exception is only raised when a debugger is attached, and
applications are not supposed to handle it, so we need to handle it
ourselves or the application may crash.
@see: U{http://msdn.microsoft.com/en-us/library/aa363082(VS.85).aspx}
@type event: L{ExceptionEvent}
@param event: Debug Ctrl-C exception event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} otherwise.
"""
if event.is_first_chance():
event.continueStatus = win32.DBG_EXCEPTION_HANDLED
return True
def _notify_ms_vc_exception(self, event):
"""
Notify of a Microsoft Visual C exception.
@warning: This method is meant to be used internally by the debugger.
@note: This allows the debugger to understand the
Microsoft Visual C thread naming convention.
@see: U{http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx}
@type event: L{ExceptionEvent}
@param event: Microsoft Visual C exception event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} otherwise.
"""
dwType = event.get_exception_information(0)
if dwType == 0x1000:
pszName = event.get_exception_information(1)
dwThreadId = event.get_exception_information(2)
dwFlags = event.get_exception_information(3)
aProcess = event.get_process()
szName = aProcess.peek_string(pszName, fUnicode = False)
if szName:
if dwThreadId == -1:
dwThreadId = event.get_tid()
if aProcess.has_thread(dwThreadId):
aThread = aProcess.get_thread(dwThreadId)
else:
aThread = Thread(dwThreadId)
aProcess._add_thread(aThread)
## if aThread.get_name() is None:
## aThread.set_name(szName)
aThread.set_name(szName)
return True
| 58,709 | Python | 37.024611 | 93 | 0.580337 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/__init__.py | #!~/.wine/drive_c/Python25/python.exe
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Windows application debugging engine for Python.
by Mario Vilas (mvilas at gmail.com)
Project: U{http://sourceforge.net/projects/winappdbg/}
Web: U{http://winappdbg.sourceforge.net/}
Blog: U{http://breakingcode.wordpress.com}
@group Debugging:
Debug, EventHandler, EventSift, DebugLog
@group Instrumentation:
System, Process, Thread, Module, Window, Registry
@group Disassemblers:
Disassembler,
BeaEngine, DistormEngine, PyDasmEngine
@group Crash reporting:
Crash, CrashDump, CrashDAO, CrashDictionary
@group Memory search:
Search,
Pattern,
BytePattern,
TextPattern,
RegExpPattern,
HexPattern
@group Debug events:
Event,
NoEvent,
CreateProcessEvent,
CreateThreadEvent,
ExitProcessEvent,
ExitThreadEvent,
LoadDLLEvent,
UnloadDLLEvent,
OutputDebugStringEvent,
RIPEvent,
ExceptionEvent
@group Win32 API wrappers:
win32, Handle, ProcessHandle, ThreadHandle, FileHandle
@group Helpers:
HexInput, HexOutput, HexDump, Color, Table, Logger,
PathOperations,
MemoryAddresses,
CustomAddressIterator,
DataAddressIterator,
ImageAddressIterator,
MappedAddressIterator,
ExecutableAddressIterator,
ReadableAddressIterator,
WriteableAddressIterator,
ExecutableAndWriteableAddressIterator,
DebugRegister,
Regenerator
@group Warnings:
MixedBitsWarning, BreakpointWarning, BreakpointCallbackWarning,
EventCallbackWarning, DebugSymbolsWarning, CrashWarning
@group Deprecated classes:
CrashContainer, CrashTable, CrashTableMSSQL,
VolatileCrashContainer, DummyCrashContainer
@type version_number: float
@var version_number: This WinAppDbg major and minor version,
as a floating point number. Use this for compatibility checking.
@type version: str
@var version: This WinAppDbg release version,
as a printable string. Use this to show to the user.
@undocumented: plugins
"""
__revision__ = "$Id$"
# List of all public symbols
__all__ = [
# Library version
'version',
'version_number',
# from breakpoint import *
## 'Breakpoint',
## 'CodeBreakpoint',
## 'PageBreakpoint',
## 'HardwareBreakpoint',
## 'Hook',
## 'ApiHook',
## 'BufferWatch',
'BreakpointWarning',
'BreakpointCallbackWarning',
# from crash import *
'Crash',
'CrashWarning',
'CrashDictionary',
'CrashContainer',
'CrashTable',
'CrashTableMSSQL',
'VolatileCrashContainer',
'DummyCrashContainer',
# from debug import *
'Debug',
'MixedBitsWarning',
# from disasm import *
'Disassembler',
'BeaEngine',
'DistormEngine',
'PyDasmEngine',
# from event import *
'EventHandler',
'EventSift',
## 'EventFactory',
## 'EventDispatcher',
'EventCallbackWarning',
'Event',
## 'NoEvent',
'CreateProcessEvent',
'CreateThreadEvent',
'ExitProcessEvent',
'ExitThreadEvent',
'LoadDLLEvent',
'UnloadDLLEvent',
'OutputDebugStringEvent',
'RIPEvent',
'ExceptionEvent',
# from interactive import *
## 'ConsoleDebugger',
# from module import *
'Module',
'DebugSymbolsWarning',
# from process import *
'Process',
# from system import *
'System',
# from search import *
'Search',
'Pattern',
'BytePattern',
'TextPattern',
'RegExpPattern',
'HexPattern',
# from registry import *
'Registry',
# from textio import *
'HexDump',
'HexInput',
'HexOutput',
'Color',
'Table',
'CrashDump',
'DebugLog',
'Logger',
# from thread import *
'Thread',
# from util import *
'PathOperations',
'MemoryAddresses',
'CustomAddressIterator',
'DataAddressIterator',
'ImageAddressIterator',
'MappedAddressIterator',
'ExecutableAddressIterator',
'ReadableAddressIterator',
'WriteableAddressIterator',
'ExecutableAndWriteableAddressIterator',
'DebugRegister',
# from window import *
'Window',
# import win32
'win32',
# from win32 import Handle, ProcessHandle, ThreadHandle, FileHandle
'Handle',
'ProcessHandle',
'ThreadHandle',
'FileHandle',
]
# Import all public symbols
from winappdbg.breakpoint import *
from winappdbg.crash import *
from winappdbg.debug import *
from winappdbg.disasm import *
from winappdbg.event import *
from winappdbg.interactive import *
from winappdbg.module import *
from winappdbg.process import *
from winappdbg.registry import *
from winappdbg.system import *
from winappdbg.search import *
from winappdbg.textio import *
from winappdbg.thread import *
from winappdbg.util import *
from winappdbg.window import *
import winappdbg.win32
from winappdbg.win32 import Handle, ProcessHandle, ThreadHandle, FileHandle
try:
from sql import *
__all__.append('CrashDAO')
except ImportError:
import warnings
warnings.warn("No SQL database support present (missing dependencies?)",
ImportWarning)
# Library version
version_number = 1.5
version = "Version %s" % version_number
| 7,917 | Python | 28.992424 | 83 | 0.600733 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/thread.py | #!~/.wine/drive_c/Python25/python.exe
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Thread instrumentation.
@group Instrumentation:
Thread
"""
from __future__ import with_statement
__revision__ = "$Id$"
__all__ = ['Thread']
from winappdbg import win32
from winappdbg import compat
from winappdbg.textio import HexDump
from winappdbg.util import DebugRegister
from winappdbg.window import Window
import sys
import struct
import warnings
# delayed imports
Process = None
#==============================================================================
# TODO
# + fetch special registers (MMX, XMM, 3DNow!, etc)
class Thread (object):
"""
Interface to a thread in another process.
@group Properties:
get_tid, get_pid, get_process, set_process, get_exit_code, is_alive,
get_name, set_name, get_windows, get_teb, get_teb_address, is_wow64,
get_arch, get_bits, get_handle, open_handle, close_handle
@group Instrumentation:
suspend, resume, kill, wait
@group Debugging:
get_seh_chain_pointer, set_seh_chain_pointer,
get_seh_chain, get_wait_chain, is_hidden
@group Disassembly:
disassemble, disassemble_around, disassemble_around_pc,
disassemble_string, disassemble_instruction, disassemble_current
@group Stack:
get_stack_frame, get_stack_frame_range, get_stack_range,
get_stack_trace, get_stack_trace_with_labels,
read_stack_data, read_stack_dwords, read_stack_qwords,
peek_stack_data, peek_stack_dwords, peek_stack_qwords,
read_stack_structure, read_stack_frame
@group Registers:
get_context,
get_register,
get_flags, get_flag_value,
get_pc, get_sp, get_fp,
get_cf, get_df, get_sf, get_tf, get_zf,
set_context,
set_register,
set_flags, set_flag_value,
set_pc, set_sp, set_fp,
set_cf, set_df, set_sf, set_tf, set_zf,
clear_cf, clear_df, clear_sf, clear_tf, clear_zf,
Flags
@group Threads snapshot:
clear
@group Miscellaneous:
read_code_bytes, peek_code_bytes,
peek_pointers_in_data, peek_pointers_in_registers,
get_linear_address, get_label_at_pc
@type dwThreadId: int
@ivar dwThreadId: Global thread ID. Use L{get_tid} instead.
@type hThread: L{ThreadHandle}
@ivar hThread: Handle to the thread. Use L{get_handle} instead.
@type process: L{Process}
@ivar process: Parent process object. Use L{get_process} instead.
@type pInjectedMemory: int
@ivar pInjectedMemory: If the thread was created by L{Process.inject_code},
this member contains a pointer to the memory buffer for the injected
code. Otherwise it's C{None}.
The L{kill} method uses this member to free the buffer
when the injected thread is killed.
"""
def __init__(self, dwThreadId, hThread = None, process = None):
"""
@type dwThreadId: int
@param dwThreadId: Global thread ID.
@type hThread: L{ThreadHandle}
@param hThread: (Optional) Handle to the thread.
@type process: L{Process}
@param process: (Optional) Parent Process object.
"""
self.dwProcessId = None
self.dwThreadId = dwThreadId
self.hThread = hThread
self.pInjectedMemory = None
self.set_name(None)
self.set_process(process)
# Not really sure if it's a good idea...
## def __eq__(self, aThread):
## """
## Compare two Thread objects. The comparison is made using the IDs.
##
## @warning:
## If you have two Thread instances with different handles the
## equality operator still returns C{True}, so be careful!
##
## @type aThread: L{Thread}
## @param aThread: Another Thread object.
##
## @rtype: bool
## @return: C{True} if the two thread IDs are equal,
## C{False} otherwise.
## """
## return isinstance(aThread, Thread) and \
## self.get_tid() == aThread.get_tid()
def __load_Process_class(self):
global Process # delayed import
if Process is None:
from winappdbg.process import Process
def get_process(self):
"""
@rtype: L{Process}
@return: Parent Process object.
Returns C{None} if unknown.
"""
if self.__process is not None:
return self.__process
self.__load_Process_class()
self.__process = Process(self.get_pid())
return self.__process
def set_process(self, process = None):
"""
Manually set the parent Process object. Use with care!
@type process: L{Process}
@param process: (Optional) Process object. Use C{None} for no process.
"""
if process is None:
self.dwProcessId = None
self.__process = None
else:
self.__load_Process_class()
if not isinstance(process, Process):
msg = "Parent process must be a Process instance, "
msg += "got %s instead" % type(process)
raise TypeError(msg)
self.dwProcessId = process.get_pid()
self.__process = process
process = property(get_process, set_process, doc="")
def get_pid(self):
"""
@rtype: int
@return: Parent process global ID.
@raise WindowsError: An error occured when calling a Win32 API function.
@raise RuntimeError: The parent process ID can't be found.
"""
if self.dwProcessId is None:
if self.__process is not None:
# Infinite loop if self.__process is None
self.dwProcessId = self.get_process().get_pid()
else:
try:
# I wish this had been implemented before Vista...
# XXX TODO find the real ntdll call under this api
hThread = self.get_handle(
win32.THREAD_QUERY_LIMITED_INFORMATION)
self.dwProcessId = win32.GetProcessIdOfThread(hThread)
except AttributeError:
# This method is really bad :P
self.dwProcessId = self.__get_pid_by_scanning()
return self.dwProcessId
def __get_pid_by_scanning(self):
'Internally used by get_pid().'
dwProcessId = None
dwThreadId = self.get_tid()
with win32.CreateToolhelp32Snapshot(win32.TH32CS_SNAPTHREAD) as hSnapshot:
te = win32.Thread32First(hSnapshot)
while te is not None:
if te.th32ThreadID == dwThreadId:
dwProcessId = te.th32OwnerProcessID
break
te = win32.Thread32Next(hSnapshot)
if dwProcessId is None:
msg = "Cannot find thread ID %d in any process" % dwThreadId
raise RuntimeError(msg)
return dwProcessId
def get_tid(self):
"""
@rtype: int
@return: Thread global ID.
"""
return self.dwThreadId
def get_name(self):
"""
@rtype: str
@return: Thread name, or C{None} if the thread is nameless.
"""
return self.name
def set_name(self, name = None):
"""
Sets the thread's name.
@type name: str
@param name: Thread name, or C{None} if the thread is nameless.
"""
self.name = name
#------------------------------------------------------------------------------
def open_handle(self, dwDesiredAccess = win32.THREAD_ALL_ACCESS):
"""
Opens a new handle to the thread, closing the previous one.
The new handle is stored in the L{hThread} property.
@warn: Normally you should call L{get_handle} instead, since it's much
"smarter" and tries to reuse handles and merge access rights.
@type dwDesiredAccess: int
@param dwDesiredAccess: Desired access rights.
Defaults to L{win32.THREAD_ALL_ACCESS}.
See: U{http://msdn.microsoft.com/en-us/library/windows/desktop/ms686769(v=vs.85).aspx}
@raise WindowsError: It's not possible to open a handle to the thread
with the requested access rights. This tipically happens because
the target thread belongs to system process and the debugger is not
runnning with administrative rights.
"""
hThread = win32.OpenThread(dwDesiredAccess, win32.FALSE, self.dwThreadId)
# In case hThread was set to an actual handle value instead of a Handle
# object. This shouldn't happen unless the user tinkered with it.
if not hasattr(self.hThread, '__del__'):
self.close_handle()
self.hThread = hThread
def close_handle(self):
"""
Closes the handle to the thread.
@note: Normally you don't need to call this method. All handles
created by I{WinAppDbg} are automatically closed when the garbage
collector claims them.
"""
try:
if hasattr(self.hThread, 'close'):
self.hThread.close()
elif self.hThread not in (None, win32.INVALID_HANDLE_VALUE):
win32.CloseHandle(self.hThread)
finally:
self.hThread = None
def get_handle(self, dwDesiredAccess = win32.THREAD_ALL_ACCESS):
"""
Returns a handle to the thread with I{at least} the access rights
requested.
@note:
If a handle was previously opened and has the required access
rights, it's reused. If not, a new handle is opened with the
combination of the old and new access rights.
@type dwDesiredAccess: int
@param dwDesiredAccess: Desired access rights.
See: U{http://msdn.microsoft.com/en-us/library/windows/desktop/ms686769(v=vs.85).aspx}
@rtype: ThreadHandle
@return: Handle to the thread.
@raise WindowsError: It's not possible to open a handle to the thread
with the requested access rights. This tipically happens because
the target thread belongs to system process and the debugger is not
runnning with administrative rights.
"""
if self.hThread in (None, win32.INVALID_HANDLE_VALUE):
self.open_handle(dwDesiredAccess)
else:
dwAccess = self.hThread.dwAccess
if (dwAccess | dwDesiredAccess) != dwAccess:
self.open_handle(dwAccess | dwDesiredAccess)
return self.hThread
def clear(self):
"""
Clears the resources held by this object.
"""
try:
self.set_process(None)
finally:
self.close_handle()
#------------------------------------------------------------------------------
def wait(self, dwTimeout = None):
"""
Waits for the thread to finish executing.
@type dwTimeout: int
@param dwTimeout: (Optional) Timeout value in milliseconds.
Use C{INFINITE} or C{None} for no timeout.
"""
self.get_handle(win32.SYNCHRONIZE).wait(dwTimeout)
def kill(self, dwExitCode = 0):
"""
Terminates the thread execution.
@note: If the C{lpInjectedMemory} member contains a valid pointer,
the memory is freed.
@type dwExitCode: int
@param dwExitCode: (Optional) Thread exit code.
"""
hThread = self.get_handle(win32.THREAD_TERMINATE)
win32.TerminateThread(hThread, dwExitCode)
# Ugliest hack ever, won't work if many pieces of code are injected.
# Seriously, what was I thinking? :(
if self.pInjectedMemory is not None:
try:
self.get_process().free(self.pInjectedMemory)
self.pInjectedMemory = None
except Exception:
## raise # XXX DEBUG
pass
# XXX TODO
# suspend() and resume() should have a counter of how many times a thread
# was suspended, so on debugger exit they could (optionally!) be restored
def suspend(self):
"""
Suspends the thread execution.
@rtype: int
@return: Suspend count. If zero, the thread is running.
"""
hThread = self.get_handle(win32.THREAD_SUSPEND_RESUME)
if self.is_wow64():
# FIXME this will be horribly slow on XP 64
# since it'll try to resolve a missing API every time
try:
return win32.Wow64SuspendThread(hThread)
except AttributeError:
pass
return win32.SuspendThread(hThread)
def resume(self):
"""
Resumes the thread execution.
@rtype: int
@return: Suspend count. If zero, the thread is running.
"""
hThread = self.get_handle(win32.THREAD_SUSPEND_RESUME)
return win32.ResumeThread(hThread)
def is_alive(self):
"""
@rtype: bool
@return: C{True} if the thread if currently running.
@raise WindowsError:
The debugger doesn't have enough privileges to perform this action.
"""
try:
self.wait(0)
except WindowsError:
e = sys.exc_info()[1]
error = e.winerror
if error == win32.ERROR_ACCESS_DENIED:
raise
return error == win32.WAIT_TIMEOUT
return True
def get_exit_code(self):
"""
@rtype: int
@return: Thread exit code, or C{STILL_ACTIVE} if it's still alive.
"""
if win32.THREAD_ALL_ACCESS == win32.THREAD_ALL_ACCESS_VISTA:
dwAccess = win32.THREAD_QUERY_LIMITED_INFORMATION
else:
dwAccess = win32.THREAD_QUERY_INFORMATION
return win32.GetExitCodeThread( self.get_handle(dwAccess) )
#------------------------------------------------------------------------------
# XXX TODO
# Support for string searches on the window captions.
def get_windows(self):
"""
@rtype: list of L{Window}
@return: Returns a list of windows handled by this thread.
"""
try:
process = self.get_process()
except Exception:
process = None
return [
Window( hWnd, process, self ) \
for hWnd in win32.EnumThreadWindows( self.get_tid() )
]
#------------------------------------------------------------------------------
# TODO
# A registers cache could be implemented here.
def get_context(self, ContextFlags = None, bSuspend = False):
"""
Retrieves the execution context (i.e. the registers values) for this
thread.
@type ContextFlags: int
@param ContextFlags: Optional, specify which registers to retrieve.
Defaults to C{win32.CONTEXT_ALL} which retrieves all registes
for the current platform.
@type bSuspend: bool
@param bSuspend: C{True} to automatically suspend the thread before
getting its context, C{False} otherwise.
Defaults to C{False} because suspending the thread during some
debug events (like thread creation or destruction) may lead to
strange errors.
Note that WinAppDbg 1.4 used to suspend the thread automatically
always. This behavior was changed in version 1.5.
@rtype: dict( str S{->} int )
@return: Dictionary mapping register names to their values.
@see: L{set_context}
"""
# Some words on the "strange errors" that lead to the bSuspend
# parameter. Peter Van Eeckhoutte and I were working on a fix
# for some bugs he found in the 1.5 betas when we stumbled upon
# what seemed to be a deadlock in the debug API that caused the
# GetThreadContext() call never to return. Since removing the
# call to SuspendThread() solved the problem, and a few Google
# searches showed a handful of problems related to these two
# APIs and Wow64 environments, I decided to break compatibility.
#
# Here are some pages about the weird behavior of SuspendThread:
# http://zachsaw.blogspot.com.es/2010/11/wow64-bug-getthreadcontext-may-return.html
# http://stackoverflow.com/questions/3444190/windows-suspendthread-doesnt-getthreadcontext-fails
# Get the thread handle.
dwAccess = win32.THREAD_GET_CONTEXT
if bSuspend:
dwAccess = dwAccess | win32.THREAD_SUSPEND_RESUME
hThread = self.get_handle(dwAccess)
# Suspend the thread if requested.
if bSuspend:
try:
self.suspend()
except WindowsError:
# Threads can't be suspended when the exit process event
# arrives, but you can still get the context.
bSuspend = False
# If an exception is raised, make sure the thread execution is resumed.
try:
if win32.bits == self.get_bits():
# 64 bit debugger attached to 64 bit process, or
# 32 bit debugger attached to 32 bit process.
ctx = win32.GetThreadContext(hThread,
ContextFlags = ContextFlags)
else:
if self.is_wow64():
# 64 bit debugger attached to 32 bit process.
if ContextFlags is not None:
ContextFlags &= ~win32.ContextArchMask
ContextFlags |= win32.WOW64_CONTEXT_i386
ctx = win32.Wow64GetThreadContext(hThread, ContextFlags)
else:
# 32 bit debugger attached to 64 bit process.
# XXX only i386/AMD64 is supported in this particular case
if win32.arch not in (win32.ARCH_I386, win32.ARCH_AMD64):
raise NotImplementedError()
if ContextFlags is not None:
ContextFlags &= ~win32.ContextArchMask
ContextFlags |= win32.context_amd64.CONTEXT_AMD64
ctx = win32.context_amd64.GetThreadContext(hThread,
ContextFlags = ContextFlags)
finally:
# Resume the thread if we suspended it.
if bSuspend:
self.resume()
# Return the context.
return ctx
def set_context(self, context, bSuspend = False):
"""
Sets the values of the registers.
@see: L{get_context}
@type context: dict( str S{->} int )
@param context: Dictionary mapping register names to their values.
@type bSuspend: bool
@param bSuspend: C{True} to automatically suspend the thread before
setting its context, C{False} otherwise.
Defaults to C{False} because suspending the thread during some
debug events (like thread creation or destruction) may lead to
strange errors.
Note that WinAppDbg 1.4 used to suspend the thread automatically
always. This behavior was changed in version 1.5.
"""
# Get the thread handle.
dwAccess = win32.THREAD_SET_CONTEXT
if bSuspend:
dwAccess = dwAccess | win32.THREAD_SUSPEND_RESUME
hThread = self.get_handle(dwAccess)
# Suspend the thread if requested.
if bSuspend:
self.suspend()
# No fix for the exit process event bug.
# Setting the context of a dead thread is pointless anyway.
# Set the thread context.
try:
if win32.bits == 64 and self.is_wow64():
win32.Wow64SetThreadContext(hThread, context)
else:
win32.SetThreadContext(hThread, context)
# Resume the thread if we suspended it.
finally:
if bSuspend:
self.resume()
def get_register(self, register):
"""
@type register: str
@param register: Register name.
@rtype: int
@return: Value of the requested register.
"""
'Returns the value of a specific register.'
context = self.get_context()
return context[register]
def set_register(self, register, value):
"""
Sets the value of a specific register.
@type register: str
@param register: Register name.
@rtype: int
@return: Register value.
"""
context = self.get_context()
context[register] = value
self.set_context(context)
#------------------------------------------------------------------------------
# TODO: a metaclass would do a better job instead of checking the platform
# during module import, also would support mixing 32 and 64 bits
if win32.arch in (win32.ARCH_I386, win32.ARCH_AMD64):
def get_pc(self):
"""
@rtype: int
@return: Value of the program counter register.
"""
context = self.get_context(win32.CONTEXT_CONTROL)
return context.pc
def set_pc(self, pc):
"""
Sets the value of the program counter register.
@type pc: int
@param pc: Value of the program counter register.
"""
context = self.get_context(win32.CONTEXT_CONTROL)
context.pc = pc
self.set_context(context)
def get_sp(self):
"""
@rtype: int
@return: Value of the stack pointer register.
"""
context = self.get_context(win32.CONTEXT_CONTROL)
return context.sp
def set_sp(self, sp):
"""
Sets the value of the stack pointer register.
@type sp: int
@param sp: Value of the stack pointer register.
"""
context = self.get_context(win32.CONTEXT_CONTROL)
context.sp = sp
self.set_context(context)
def get_fp(self):
"""
@rtype: int
@return: Value of the frame pointer register.
"""
flags = win32.CONTEXT_CONTROL | win32.CONTEXT_INTEGER
context = self.get_context(flags)
return context.fp
def set_fp(self, fp):
"""
Sets the value of the frame pointer register.
@type fp: int
@param fp: Value of the frame pointer register.
"""
flags = win32.CONTEXT_CONTROL | win32.CONTEXT_INTEGER
context = self.get_context(flags)
context.fp = fp
self.set_context(context)
#------------------------------------------------------------------------------
if win32.arch in (win32.ARCH_I386, win32.ARCH_AMD64):
class Flags (object):
'Commonly used processor flags'
Overflow = 0x800
Direction = 0x400
Interrupts = 0x200
Trap = 0x100
Sign = 0x80
Zero = 0x40
# 0x20 ???
Auxiliary = 0x10
# 0x8 ???
Parity = 0x4
# 0x2 ???
Carry = 0x1
def get_flags(self, FlagMask = 0xFFFFFFFF):
"""
@type FlagMask: int
@param FlagMask: (Optional) Bitwise-AND mask.
@rtype: int
@return: Flags register contents, optionally masking out some bits.
"""
context = self.get_context(win32.CONTEXT_CONTROL)
return context['EFlags'] & FlagMask
def set_flags(self, eflags, FlagMask = 0xFFFFFFFF):
"""
Sets the flags register, optionally masking some bits.
@type eflags: int
@param eflags: Flags register contents.
@type FlagMask: int
@param FlagMask: (Optional) Bitwise-AND mask.
"""
context = self.get_context(win32.CONTEXT_CONTROL)
context['EFlags'] = (context['EFlags'] & FlagMask) | eflags
self.set_context(context)
def get_flag_value(self, FlagBit):
"""
@type FlagBit: int
@param FlagBit: One of the L{Flags}.
@rtype: bool
@return: Boolean value of the requested flag.
"""
return bool( self.get_flags(FlagBit) )
def set_flag_value(self, FlagBit, FlagValue):
"""
Sets a single flag, leaving the others intact.
@type FlagBit: int
@param FlagBit: One of the L{Flags}.
@type FlagValue: bool
@param FlagValue: Boolean value of the flag.
"""
if FlagValue:
eflags = FlagBit
else:
eflags = 0
FlagMask = 0xFFFFFFFF ^ FlagBit
self.set_flags(eflags, FlagMask)
def get_zf(self):
"""
@rtype: bool
@return: Boolean value of the Zero flag.
"""
return self.get_flag_value(self.Flags.Zero)
def get_cf(self):
"""
@rtype: bool
@return: Boolean value of the Carry flag.
"""
return self.get_flag_value(self.Flags.Carry)
def get_sf(self):
"""
@rtype: bool
@return: Boolean value of the Sign flag.
"""
return self.get_flag_value(self.Flags.Sign)
def get_df(self):
"""
@rtype: bool
@return: Boolean value of the Direction flag.
"""
return self.get_flag_value(self.Flags.Direction)
def get_tf(self):
"""
@rtype: bool
@return: Boolean value of the Trap flag.
"""
return self.get_flag_value(self.Flags.Trap)
def clear_zf(self):
'Clears the Zero flag.'
self.set_flag_value(self.Flags.Zero, False)
def clear_cf(self):
'Clears the Carry flag.'
self.set_flag_value(self.Flags.Carry, False)
def clear_sf(self):
'Clears the Sign flag.'
self.set_flag_value(self.Flags.Sign, False)
def clear_df(self):
'Clears the Direction flag.'
self.set_flag_value(self.Flags.Direction, False)
def clear_tf(self):
'Clears the Trap flag.'
self.set_flag_value(self.Flags.Trap, False)
def set_zf(self):
'Sets the Zero flag.'
self.set_flag_value(self.Flags.Zero, True)
def set_cf(self):
'Sets the Carry flag.'
self.set_flag_value(self.Flags.Carry, True)
def set_sf(self):
'Sets the Sign flag.'
self.set_flag_value(self.Flags.Sign, True)
def set_df(self):
'Sets the Direction flag.'
self.set_flag_value(self.Flags.Direction, True)
def set_tf(self):
'Sets the Trap flag.'
self.set_flag_value(self.Flags.Trap, True)
#------------------------------------------------------------------------------
def is_wow64(self):
"""
Determines if the thread is running under WOW64.
@rtype: bool
@return:
C{True} if the thread is running under WOW64. That is, it belongs
to a 32-bit application running in a 64-bit Windows.
C{False} if the thread belongs to either a 32-bit application
running in a 32-bit Windows, or a 64-bit application running in a
64-bit Windows.
@raise WindowsError: On error an exception is raised.
@see: U{http://msdn.microsoft.com/en-us/library/aa384249(VS.85).aspx}
"""
try:
wow64 = self.__wow64
except AttributeError:
if (win32.bits == 32 and not win32.wow64):
wow64 = False
else:
wow64 = self.get_process().is_wow64()
self.__wow64 = wow64
return wow64
def get_arch(self):
"""
@rtype: str
@return: The architecture in which this thread believes to be running.
For example, if running a 32 bit binary in a 64 bit machine, the
architecture returned by this method will be L{win32.ARCH_I386},
but the value of L{System.arch} will be L{win32.ARCH_AMD64}.
"""
if win32.bits == 32 and not win32.wow64:
return win32.arch
return self.get_process().get_arch()
def get_bits(self):
"""
@rtype: str
@return: The number of bits in which this thread believes to be
running. For example, if running a 32 bit binary in a 64 bit
machine, the number of bits returned by this method will be C{32},
but the value of L{System.arch} will be C{64}.
"""
if win32.bits == 32 and not win32.wow64:
return 32
return self.get_process().get_bits()
def is_hidden(self):
"""
Determines if the thread has been hidden from debuggers.
Some binary packers hide their own threads to thwart debugging.
@rtype: bool
@return: C{True} if the thread is hidden from debuggers.
This means the thread's execution won't be stopped for debug
events, and thus said events won't be sent to the debugger.
"""
return win32.NtQueryInformationThread(
self.get_handle(), # XXX what permissions do I need?
win32.ThreadHideFromDebugger)
def get_teb(self):
"""
Returns a copy of the TEB.
To dereference pointers in it call L{Process.read_structure}.
@rtype: L{TEB}
@return: TEB structure.
@raise WindowsError: An exception is raised on error.
"""
return self.get_process().read_structure( self.get_teb_address(),
win32.TEB )
def get_teb_address(self):
"""
Returns a remote pointer to the TEB.
@rtype: int
@return: Remote pointer to the L{TEB} structure.
@raise WindowsError: An exception is raised on error.
"""
try:
return self._teb_ptr
except AttributeError:
try:
hThread = self.get_handle(win32.THREAD_QUERY_INFORMATION)
tbi = win32.NtQueryInformationThread( hThread,
win32.ThreadBasicInformation)
address = tbi.TebBaseAddress
except WindowsError:
address = self.get_linear_address('SegFs', 0) # fs:[0]
if not address:
raise
self._teb_ptr = address
return address
def get_linear_address(self, segment, address):
"""
Translates segment-relative addresses to linear addresses.
Linear addresses can be used to access a process memory,
calling L{Process.read} and L{Process.write}.
@type segment: str
@param segment: Segment register name.
@type address: int
@param address: Segment relative memory address.
@rtype: int
@return: Linear memory address.
@raise ValueError: Address is too large for selector.
@raise WindowsError:
The current architecture does not support selectors.
Selectors only exist in x86-based systems.
"""
hThread = self.get_handle(win32.THREAD_QUERY_INFORMATION)
selector = self.get_register(segment)
ldt = win32.GetThreadSelectorEntry(hThread, selector)
BaseLow = ldt.BaseLow
BaseMid = ldt.HighWord.Bytes.BaseMid << 16
BaseHi = ldt.HighWord.Bytes.BaseHi << 24
Base = BaseLow | BaseMid | BaseHi
LimitLow = ldt.LimitLow
LimitHi = ldt.HighWord.Bits.LimitHi << 16
Limit = LimitLow | LimitHi
if address > Limit:
msg = "Address %s too large for segment %s (selector %d)"
msg = msg % (HexDump.address(address, self.get_bits()),
segment, selector)
raise ValueError(msg)
return Base + address
def get_label_at_pc(self):
"""
@rtype: str
@return: Label that points to the instruction currently being executed.
"""
return self.get_process().get_label_at_address( self.get_pc() )
def get_seh_chain_pointer(self):
"""
Get the pointer to the first structured exception handler block.
@rtype: int
@return: Remote pointer to the first block of the structured exception
handlers linked list. If the list is empty, the returned value is
C{0xFFFFFFFF}.
@raise NotImplementedError:
This method is only supported in 32 bits versions of Windows.
"""
if win32.arch != win32.ARCH_I386:
raise NotImplementedError(
"SEH chain parsing is only supported in 32-bit Windows.")
process = self.get_process()
address = self.get_linear_address( 'SegFs', 0 )
return process.read_pointer( address )
def set_seh_chain_pointer(self, value):
"""
Change the pointer to the first structured exception handler block.
@type value: int
@param value: Value of the remote pointer to the first block of the
structured exception handlers linked list. To disable SEH set the
value C{0xFFFFFFFF}.
@raise NotImplementedError:
This method is only supported in 32 bits versions of Windows.
"""
if win32.arch != win32.ARCH_I386:
raise NotImplementedError(
"SEH chain parsing is only supported in 32-bit Windows.")
process = self.get_process()
address = self.get_linear_address( 'SegFs', 0 )
process.write_pointer( address, value )
def get_seh_chain(self):
"""
@rtype: list of tuple( int, int )
@return: List of structured exception handlers.
Each SEH is represented as a tuple of two addresses:
- Address of this SEH block
- Address of the SEH callback function
Do not confuse this with the contents of the SEH block itself,
where the first member is a pointer to the B{next} block instead.
@raise NotImplementedError:
This method is only supported in 32 bits versions of Windows.
"""
seh_chain = list()
try:
process = self.get_process()
seh = self.get_seh_chain_pointer()
while seh != 0xFFFFFFFF:
seh_func = process.read_pointer( seh + 4 )
seh_chain.append( (seh, seh_func) )
seh = process.read_pointer( seh )
except WindowsError:
seh_chain.append( (seh, None) )
return seh_chain
def get_wait_chain(self):
"""
@rtype:
tuple of (
list of L{win32.WaitChainNodeInfo} structures,
bool)
@return:
Wait chain for the thread.
The boolean indicates if there's a cycle in the chain (a deadlock).
@raise AttributeError:
This method is only suppported in Windows Vista and above.
@see:
U{http://msdn.microsoft.com/en-us/library/ms681622%28VS.85%29.aspx}
"""
with win32.OpenThreadWaitChainSession() as hWct:
return win32.GetThreadWaitChain(hWct, ThreadId = self.get_tid())
def get_stack_range(self):
"""
@rtype: tuple( int, int )
@return: Stack beginning and end pointers, in memory addresses order.
That is, the first pointer is the stack top, and the second pointer
is the stack bottom, since the stack grows towards lower memory
addresses.
@raise WindowsError: Raises an exception on error.
"""
# TODO use teb.DeallocationStack too (max. possible stack size)
teb = self.get_teb()
tib = teb.NtTib
return ( tib.StackLimit, tib.StackBase ) # top, bottom
def __get_stack_trace(self, depth = 16, bUseLabels = True,
bMakePretty = True):
"""
Tries to get a stack trace for the current function using the debug
helper API (dbghelp.dll).
@type depth: int
@param depth: Maximum depth of stack trace.
@type bUseLabels: bool
@param bUseLabels: C{True} to use labels, C{False} to use addresses.
@type bMakePretty: bool
@param bMakePretty:
C{True} for user readable labels,
C{False} for labels that can be passed to L{Process.resolve_label}.
"Pretty" labels look better when producing output for the user to
read, while pure labels are more useful programatically.
@rtype: tuple of tuple( int, int, str )
@return: Stack trace of the thread as a tuple of
( return address, frame pointer address, module filename )
when C{bUseLabels} is C{True}, or a tuple of
( return address, frame pointer label )
when C{bUseLabels} is C{False}.
@raise WindowsError: Raises an exception on error.
"""
aProcess = self.get_process()
arch = aProcess.get_arch()
bits = aProcess.get_bits()
if arch == win32.ARCH_I386:
MachineType = win32.IMAGE_FILE_MACHINE_I386
elif arch == win32.ARCH_AMD64:
MachineType = win32.IMAGE_FILE_MACHINE_AMD64
elif arch == win32.ARCH_IA64:
MachineType = win32.IMAGE_FILE_MACHINE_IA64
else:
msg = "Stack walking is not available for this architecture: %s"
raise NotImplementedError(msg % arch)
hProcess = aProcess.get_handle( win32.PROCESS_VM_READ |
win32.PROCESS_QUERY_INFORMATION )
hThread = self.get_handle( win32.THREAD_GET_CONTEXT |
win32.THREAD_QUERY_INFORMATION )
StackFrame = win32.STACKFRAME64()
StackFrame.AddrPC = win32.ADDRESS64( self.get_pc() )
StackFrame.AddrFrame = win32.ADDRESS64( self.get_fp() )
StackFrame.AddrStack = win32.ADDRESS64( self.get_sp() )
trace = list()
while win32.StackWalk64(MachineType, hProcess, hThread, StackFrame):
if depth <= 0:
break
fp = StackFrame.AddrFrame.Offset
ra = aProcess.peek_pointer(fp + 4)
if ra == 0:
break
lib = aProcess.get_module_at_address(ra)
if lib is None:
lib = ""
else:
if lib.fileName:
lib = lib.fileName
else:
lib = "%s" % HexDump.address(lib.lpBaseOfDll, bits)
if bUseLabels:
label = aProcess.get_label_at_address(ra)
if bMakePretty:
label = '%s (%s)' % (HexDump.address(ra, bits), label)
trace.append( (fp, label) )
else:
trace.append( (fp, ra, lib) )
fp = aProcess.peek_pointer(fp)
return tuple(trace)
def __get_stack_trace_manually(self, depth = 16, bUseLabels = True,
bMakePretty = True):
"""
Tries to get a stack trace for the current function.
Only works for functions with standard prologue and epilogue.
@type depth: int
@param depth: Maximum depth of stack trace.
@type bUseLabels: bool
@param bUseLabels: C{True} to use labels, C{False} to use addresses.
@type bMakePretty: bool
@param bMakePretty:
C{True} for user readable labels,
C{False} for labels that can be passed to L{Process.resolve_label}.
"Pretty" labels look better when producing output for the user to
read, while pure labels are more useful programatically.
@rtype: tuple of tuple( int, int, str )
@return: Stack trace of the thread as a tuple of
( return address, frame pointer address, module filename )
when C{bUseLabels} is C{True}, or a tuple of
( return address, frame pointer label )
when C{bUseLabels} is C{False}.
@raise WindowsError: Raises an exception on error.
"""
aProcess = self.get_process()
st, sb = self.get_stack_range() # top, bottom
fp = self.get_fp()
trace = list()
if aProcess.get_module_count() == 0:
aProcess.scan_modules()
bits = aProcess.get_bits()
while depth > 0:
if fp == 0:
break
if not st <= fp < sb:
break
ra = aProcess.peek_pointer(fp + 4)
if ra == 0:
break
lib = aProcess.get_module_at_address(ra)
if lib is None:
lib = ""
else:
if lib.fileName:
lib = lib.fileName
else:
lib = "%s" % HexDump.address(lib.lpBaseOfDll, bits)
if bUseLabels:
label = aProcess.get_label_at_address(ra)
if bMakePretty:
label = '%s (%s)' % (HexDump.address(ra, bits), label)
trace.append( (fp, label) )
else:
trace.append( (fp, ra, lib) )
fp = aProcess.peek_pointer(fp)
return tuple(trace)
def get_stack_trace(self, depth = 16):
"""
Tries to get a stack trace for the current function.
Only works for functions with standard prologue and epilogue.
@type depth: int
@param depth: Maximum depth of stack trace.
@rtype: tuple of tuple( int, int, str )
@return: Stack trace of the thread as a tuple of
( return address, frame pointer address, module filename ).
@raise WindowsError: Raises an exception on error.
"""
try:
trace = self.__get_stack_trace(depth, False)
except Exception:
import traceback
traceback.print_exc()
trace = ()
if not trace:
trace = self.__get_stack_trace_manually(depth, False)
return trace
def get_stack_trace_with_labels(self, depth = 16, bMakePretty = True):
"""
Tries to get a stack trace for the current function.
Only works for functions with standard prologue and epilogue.
@type depth: int
@param depth: Maximum depth of stack trace.
@type bMakePretty: bool
@param bMakePretty:
C{True} for user readable labels,
C{False} for labels that can be passed to L{Process.resolve_label}.
"Pretty" labels look better when producing output for the user to
read, while pure labels are more useful programatically.
@rtype: tuple of tuple( int, int, str )
@return: Stack trace of the thread as a tuple of
( return address, frame pointer label ).
@raise WindowsError: Raises an exception on error.
"""
try:
trace = self.__get_stack_trace(depth, True, bMakePretty)
except Exception:
trace = ()
if not trace:
trace = self.__get_stack_trace_manually(depth, True, bMakePretty)
return trace
def get_stack_frame_range(self):
"""
Returns the starting and ending addresses of the stack frame.
Only works for functions with standard prologue and epilogue.
@rtype: tuple( int, int )
@return: Stack frame range.
May not be accurate, depending on the compiler used.
@raise RuntimeError: The stack frame is invalid,
or the function doesn't have a standard prologue
and epilogue.
@raise WindowsError: An error occured when getting the thread context.
"""
st, sb = self.get_stack_range() # top, bottom
sp = self.get_sp()
fp = self.get_fp()
size = fp - sp
if not st <= sp < sb:
raise RuntimeError('Stack pointer lies outside the stack')
if not st <= fp < sb:
raise RuntimeError('Frame pointer lies outside the stack')
if sp > fp:
raise RuntimeError('No valid stack frame found')
return (sp, fp)
def get_stack_frame(self, max_size = None):
"""
Reads the contents of the current stack frame.
Only works for functions with standard prologue and epilogue.
@type max_size: int
@param max_size: (Optional) Maximum amount of bytes to read.
@rtype: str
@return: Stack frame data.
May not be accurate, depending on the compiler used.
May return an empty string.
@raise RuntimeError: The stack frame is invalid,
or the function doesn't have a standard prologue
and epilogue.
@raise WindowsError: An error occured when getting the thread context
or reading data from the process memory.
"""
sp, fp = self.get_stack_frame_range()
size = fp - sp
if max_size and size > max_size:
size = max_size
return self.get_process().peek(sp, size)
def read_stack_data(self, size = 128, offset = 0):
"""
Reads the contents of the top of the stack.
@type size: int
@param size: Number of bytes to read.
@type offset: int
@param offset: Offset from the stack pointer to begin reading.
@rtype: str
@return: Stack data.
@raise WindowsError: Could not read the requested data.
"""
aProcess = self.get_process()
return aProcess.read(self.get_sp() + offset, size)
def peek_stack_data(self, size = 128, offset = 0):
"""
Tries to read the contents of the top of the stack.
@type size: int
@param size: Number of bytes to read.
@type offset: int
@param offset: Offset from the stack pointer to begin reading.
@rtype: str
@return: Stack data.
Returned data may be less than the requested size.
"""
aProcess = self.get_process()
return aProcess.peek(self.get_sp() + offset, size)
def read_stack_dwords(self, count, offset = 0):
"""
Reads DWORDs from the top of the stack.
@type count: int
@param count: Number of DWORDs to read.
@type offset: int
@param offset: Offset from the stack pointer to begin reading.
@rtype: tuple( int... )
@return: Tuple of integers read from the stack.
@raise WindowsError: Could not read the requested data.
"""
if count > 0:
stackData = self.read_stack_data(count * 4, offset)
return struct.unpack('<'+('L'*count), stackData)
return ()
def peek_stack_dwords(self, count, offset = 0):
"""
Tries to read DWORDs from the top of the stack.
@type count: int
@param count: Number of DWORDs to read.
@type offset: int
@param offset: Offset from the stack pointer to begin reading.
@rtype: tuple( int... )
@return: Tuple of integers read from the stack.
May be less than the requested number of DWORDs.
"""
stackData = self.peek_stack_data(count * 4, offset)
if len(stackData) & 3:
stackData = stackData[:-len(stackData) & 3]
if not stackData:
return ()
return struct.unpack('<'+('L'*count), stackData)
def read_stack_qwords(self, count, offset = 0):
"""
Reads QWORDs from the top of the stack.
@type count: int
@param count: Number of QWORDs to read.
@type offset: int
@param offset: Offset from the stack pointer to begin reading.
@rtype: tuple( int... )
@return: Tuple of integers read from the stack.
@raise WindowsError: Could not read the requested data.
"""
stackData = self.read_stack_data(count * 8, offset)
return struct.unpack('<'+('Q'*count), stackData)
def peek_stack_qwords(self, count, offset = 0):
"""
Tries to read QWORDs from the top of the stack.
@type count: int
@param count: Number of QWORDs to read.
@type offset: int
@param offset: Offset from the stack pointer to begin reading.
@rtype: tuple( int... )
@return: Tuple of integers read from the stack.
May be less than the requested number of QWORDs.
"""
stackData = self.peek_stack_data(count * 8, offset)
if len(stackData) & 7:
stackData = stackData[:-len(stackData) & 7]
if not stackData:
return ()
return struct.unpack('<'+('Q'*count), stackData)
def read_stack_structure(self, structure, offset = 0):
"""
Reads the given structure at the top of the stack.
@type structure: ctypes.Structure
@param structure: Structure of the data to read from the stack.
@type offset: int
@param offset: Offset from the stack pointer to begin reading.
The stack pointer is the same returned by the L{get_sp} method.
@rtype: tuple
@return: Tuple of elements read from the stack. The type of each
element matches the types in the stack frame structure.
"""
aProcess = self.get_process()
stackData = aProcess.read_structure(self.get_sp() + offset, structure)
return tuple([ stackData.__getattribute__(name)
for (name, type) in stackData._fields_ ])
def read_stack_frame(self, structure, offset = 0):
"""
Reads the stack frame of the thread.
@type structure: ctypes.Structure
@param structure: Structure of the stack frame.
@type offset: int
@param offset: Offset from the frame pointer to begin reading.
The frame pointer is the same returned by the L{get_fp} method.
@rtype: tuple
@return: Tuple of elements read from the stack frame. The type of each
element matches the types in the stack frame structure.
"""
aProcess = self.get_process()
stackData = aProcess.read_structure(self.get_fp() + offset, structure)
return tuple([ stackData.__getattribute__(name)
for (name, type) in stackData._fields_ ])
def read_code_bytes(self, size = 128, offset = 0):
"""
Tries to read some bytes of the code currently being executed.
@type size: int
@param size: Number of bytes to read.
@type offset: int
@param offset: Offset from the program counter to begin reading.
@rtype: str
@return: Bytes read from the process memory.
@raise WindowsError: Could not read the requested data.
"""
return self.get_process().read(self.get_pc() + offset, size)
def peek_code_bytes(self, size = 128, offset = 0):
"""
Tries to read some bytes of the code currently being executed.
@type size: int
@param size: Number of bytes to read.
@type offset: int
@param offset: Offset from the program counter to begin reading.
@rtype: str
@return: Bytes read from the process memory.
May be less than the requested number of bytes.
"""
return self.get_process().peek(self.get_pc() + offset, size)
def peek_pointers_in_registers(self, peekSize = 16, context = None):
"""
Tries to guess which values in the registers are valid pointers,
and reads some data from them.
@type peekSize: int
@param peekSize: Number of bytes to read from each pointer found.
@type context: dict( str S{->} int )
@param context: (Optional)
Dictionary mapping register names to their values.
If not given, the current thread context will be used.
@rtype: dict( str S{->} str )
@return: Dictionary mapping register names to the data they point to.
"""
peekable_registers = (
'Eax', 'Ebx', 'Ecx', 'Edx', 'Esi', 'Edi', 'Ebp'
)
if not context:
context = self.get_context(win32.CONTEXT_CONTROL | \
win32.CONTEXT_INTEGER)
aProcess = self.get_process()
data = dict()
for (reg_name, reg_value) in compat.iteritems(context):
if reg_name not in peekable_registers:
continue
## if reg_name == 'Ebp':
## stack_begin, stack_end = self.get_stack_range()
## print hex(stack_end), hex(reg_value), hex(stack_begin)
## if stack_begin and stack_end and stack_end < stack_begin and \
## stack_begin <= reg_value <= stack_end:
## continue
reg_data = aProcess.peek(reg_value, peekSize)
if reg_data:
data[reg_name] = reg_data
return data
# 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.
@type data: str
@param data: Binary data to find pointers in.
@type peekSize: int
@param peekSize: Number of bytes to read from each pointer found.
@type peekStep: int
@param peekStep: Expected data alignment.
Tipically you specify 1 when data alignment is unknown,
or 4 when you expect data to be DWORD aligned.
Any other value may be specified.
@rtype: dict( str S{->} str )
@return: Dictionary mapping stack offsets to the data they point to.
"""
aProcess = self.get_process()
return aProcess.peek_pointers_in_data(data, peekSize, peekStep)
#------------------------------------------------------------------------------
# TODO
# The disassemble_around and disassemble_around_pc methods
# should take as parameter instruction counts rather than sizes
def disassemble_string(self, lpAddress, code):
"""
Disassemble instructions from a block of binary code.
@type lpAddress: int
@param lpAddress: Memory address where the code was read from.
@type code: str
@param code: Binary code to disassemble.
@rtype: list of tuple( long, int, str, str )
@return: List of tuples. Each tuple represents an assembly instruction
and contains:
- Memory address of instruction.
- Size of instruction in bytes.
- Disassembly line of instruction.
- Hexadecimal dump of instruction.
"""
aProcess = self.get_process()
return aProcess.disassemble_string(lpAddress, code)
def disassemble(self, lpAddress, dwSize):
"""
Disassemble instructions from the address space of the process.
@type lpAddress: int
@param lpAddress: Memory address where to read the code from.
@type dwSize: int
@param dwSize: Size of binary code to disassemble.
@rtype: list of tuple( long, int, str, str )
@return: List of tuples. Each tuple represents an assembly instruction
and contains:
- Memory address of instruction.
- Size of instruction in bytes.
- Disassembly line of instruction.
- Hexadecimal dump of instruction.
"""
aProcess = self.get_process()
return aProcess.disassemble(lpAddress, dwSize)
def disassemble_around(self, lpAddress, dwSize = 64):
"""
Disassemble around the given address.
@type lpAddress: int
@param lpAddress: Memory address where to read the code from.
@type dwSize: int
@param dwSize: Delta offset.
Code will be read from lpAddress - dwSize to lpAddress + dwSize.
@rtype: list of tuple( long, int, str, str )
@return: List of tuples. Each tuple represents an assembly instruction
and contains:
- Memory address of instruction.
- Size of instruction in bytes.
- Disassembly line of instruction.
- Hexadecimal dump of instruction.
"""
aProcess = self.get_process()
return aProcess.disassemble_around(lpAddress, dwSize)
def disassemble_around_pc(self, dwSize = 64):
"""
Disassemble around the program counter of the given thread.
@type dwSize: int
@param dwSize: Delta offset.
Code will be read from pc - dwSize to pc + dwSize.
@rtype: list of tuple( long, int, str, str )
@return: List of tuples. Each tuple represents an assembly instruction
and contains:
- Memory address of instruction.
- Size of instruction in bytes.
- Disassembly line of instruction.
- Hexadecimal dump of instruction.
"""
aProcess = self.get_process()
return aProcess.disassemble_around(self.get_pc(), dwSize)
def disassemble_instruction(self, lpAddress):
"""
Disassemble the instruction at the given memory address.
@type lpAddress: int
@param lpAddress: Memory address where to read the code from.
@rtype: tuple( long, int, str, str )
@return: The tuple represents an assembly instruction
and contains:
- Memory address of instruction.
- Size of instruction in bytes.
- Disassembly line of instruction.
- Hexadecimal dump of instruction.
"""
aProcess = self.get_process()
return aProcess.disassemble(lpAddress, 15)[0]
def disassemble_current(self):
"""
Disassemble the instruction at the program counter of the given thread.
@rtype: tuple( long, int, str, str )
@return: The tuple represents an assembly instruction
and contains:
- Memory address of instruction.
- Size of instruction in bytes.
- Disassembly line of instruction.
- Hexadecimal dump of instruction.
"""
return self.disassemble_instruction( self.get_pc() )
#==============================================================================
class _ThreadContainer (object):
"""
Encapsulates the capability to contain Thread objects.
@group Instrumentation:
start_thread
@group Threads snapshot:
scan_threads,
get_thread, get_thread_count, get_thread_ids,
has_thread, iter_threads, iter_thread_ids,
find_threads_by_name, get_windows,
clear_threads, clear_dead_threads, close_thread_handles
"""
def __init__(self):
self.__threadDict = dict()
def __initialize_snapshot(self):
"""
Private method to automatically initialize the snapshot
when you try to use it without calling any of the scan_*
methods first. You don't need to call this yourself.
"""
if not self.__threadDict:
self.scan_threads()
def __contains__(self, anObject):
"""
@type anObject: L{Thread}, int
@param anObject:
- C{int}: Global ID of the thread to look for.
- C{Thread}: Thread object to look for.
@rtype: bool
@return: C{True} if the snapshot contains
a L{Thread} object with the same ID.
"""
if isinstance(anObject, Thread):
anObject = anObject.dwThreadId
return self.has_thread(anObject)
def __iter__(self):
"""
@see: L{iter_threads}
@rtype: dictionary-valueiterator
@return: Iterator of L{Thread} objects in this snapshot.
"""
return self.iter_threads()
def __len__(self):
"""
@see: L{get_thread_count}
@rtype: int
@return: Count of L{Thread} objects in this snapshot.
"""
return self.get_thread_count()
def has_thread(self, dwThreadId):
"""
@type dwThreadId: int
@param dwThreadId: Global ID of the thread to look for.
@rtype: bool
@return: C{True} if the snapshot contains a
L{Thread} object with the given global ID.
"""
self.__initialize_snapshot()
return dwThreadId in self.__threadDict
def get_thread(self, dwThreadId):
"""
@type dwThreadId: int
@param dwThreadId: Global ID of the thread to look for.
@rtype: L{Thread}
@return: Thread object with the given global ID.
"""
self.__initialize_snapshot()
if dwThreadId not in self.__threadDict:
msg = "Unknown thread ID: %d" % dwThreadId
raise KeyError(msg)
return self.__threadDict[dwThreadId]
def iter_thread_ids(self):
"""
@see: L{iter_threads}
@rtype: dictionary-keyiterator
@return: Iterator of global thread IDs in this snapshot.
"""
self.__initialize_snapshot()
return compat.iterkeys(self.__threadDict)
def iter_threads(self):
"""
@see: L{iter_thread_ids}
@rtype: dictionary-valueiterator
@return: Iterator of L{Thread} objects in this snapshot.
"""
self.__initialize_snapshot()
return compat.itervalues(self.__threadDict)
def get_thread_ids(self):
"""
@rtype: list( int )
@return: List of global thread IDs in this snapshot.
"""
self.__initialize_snapshot()
return compat.keys(self.__threadDict)
def get_thread_count(self):
"""
@rtype: int
@return: Count of L{Thread} objects in this snapshot.
"""
self.__initialize_snapshot()
return len(self.__threadDict)
#------------------------------------------------------------------------------
def find_threads_by_name(self, name, bExactMatch = True):
"""
Find threads by name, using different search methods.
@type name: str, None
@param name: Name to look for. Use C{None} to find nameless threads.
@type bExactMatch: bool
@param bExactMatch: C{True} if the name must be
B{exactly} as given, C{False} if the name can be
loosely matched.
This parameter is ignored when C{name} is C{None}.
@rtype: list( L{Thread} )
@return: All threads matching the given name.
"""
found_threads = list()
# Find threads with no name.
if name is None:
for aThread in self.iter_threads():
if aThread.get_name() is None:
found_threads.append(aThread)
# Find threads matching the given name exactly.
elif bExactMatch:
for aThread in self.iter_threads():
if aThread.get_name() == name:
found_threads.append(aThread)
# Find threads whose names match the given substring.
else:
for aThread in self.iter_threads():
t_name = aThread.get_name()
if t_name is not None and name in t_name:
found_threads.append(aThread)
return found_threads
#------------------------------------------------------------------------------
# XXX TODO
# Support for string searches on the window captions.
def get_windows(self):
"""
@rtype: list of L{Window}
@return: Returns a list of windows handled by this process.
"""
window_list = list()
for thread in self.iter_threads():
window_list.extend( thread.get_windows() )
return window_list
#------------------------------------------------------------------------------
def start_thread(self, lpStartAddress, lpParameter=0, bSuspended = False):
"""
Remotely creates a new thread in the process.
@type lpStartAddress: int
@param lpStartAddress: Start address for the new thread.
@type lpParameter: int
@param lpParameter: Optional argument for the new thread.
@type bSuspended: bool
@param bSuspended: C{True} if the new thread should be suspended.
In that case use L{Thread.resume} to start execution.
"""
if bSuspended:
dwCreationFlags = win32.CREATE_SUSPENDED
else:
dwCreationFlags = 0
hProcess = self.get_handle( win32.PROCESS_CREATE_THREAD |
win32.PROCESS_QUERY_INFORMATION |
win32.PROCESS_VM_OPERATION |
win32.PROCESS_VM_WRITE |
win32.PROCESS_VM_READ )
hThread, dwThreadId = win32.CreateRemoteThread(
hProcess, 0, 0, lpStartAddress, lpParameter, dwCreationFlags)
aThread = Thread(dwThreadId, hThread, self)
self._add_thread(aThread)
return aThread
#------------------------------------------------------------------------------
# TODO
# maybe put all the toolhelp code into their own set of classes?
#
# XXX this method musn't end up calling __initialize_snapshot by accident!
def scan_threads(self):
"""
Populates the snapshot with running threads.
"""
# Ignore special process IDs.
# PID 0: System Idle Process. Also has a special meaning to the
# toolhelp APIs (current process).
# PID 4: System Integrity Group. See this forum post for more info:
# http://tinyurl.com/ycza8jo
# (points to social.technet.microsoft.com)
# Only on XP and above
# PID 8: System (?) only in Windows 2000 and below AFAIK.
# It's probably the same as PID 4 in XP and above.
dwProcessId = self.get_pid()
if dwProcessId in (0, 4, 8):
return
## dead_tids = set( self.get_thread_ids() ) # XXX triggers a scan
dead_tids = self._get_thread_ids()
dwProcessId = self.get_pid()
hSnapshot = win32.CreateToolhelp32Snapshot(win32.TH32CS_SNAPTHREAD,
dwProcessId)
try:
te = win32.Thread32First(hSnapshot)
while te is not None:
if te.th32OwnerProcessID == dwProcessId:
dwThreadId = te.th32ThreadID
if dwThreadId in dead_tids:
dead_tids.remove(dwThreadId)
## if not self.has_thread(dwThreadId): # XXX triggers a scan
if not self._has_thread_id(dwThreadId):
aThread = Thread(dwThreadId, process = self)
self._add_thread(aThread)
te = win32.Thread32Next(hSnapshot)
finally:
win32.CloseHandle(hSnapshot)
for tid in dead_tids:
self._del_thread(tid)
def clear_dead_threads(self):
"""
Remove Thread objects from the snapshot
referring to threads no longer running.
"""
for tid in self.get_thread_ids():
aThread = self.get_thread(tid)
if not aThread.is_alive():
self._del_thread(aThread)
def clear_threads(self):
"""
Clears the threads snapshot.
"""
for aThread in compat.itervalues(self.__threadDict):
aThread.clear()
self.__threadDict = dict()
def close_thread_handles(self):
"""
Closes all open handles to threads in the snapshot.
"""
for aThread in self.iter_threads():
try:
aThread.close_handle()
except Exception:
try:
e = sys.exc_info()[1]
msg = "Cannot close thread handle %s, reason: %s"
msg %= (aThread.hThread.value, str(e))
warnings.warn(msg)
except Exception:
pass
#------------------------------------------------------------------------------
# XXX _notify_* methods should not trigger a scan
def _add_thread(self, aThread):
"""
Private method to add a thread object to the snapshot.
@type aThread: L{Thread}
@param aThread: Thread object.
"""
## if not isinstance(aThread, Thread):
## if hasattr(aThread, '__class__'):
## typename = aThread.__class__.__name__
## else:
## typename = str(type(aThread))
## msg = "Expected Thread, got %s instead" % typename
## raise TypeError(msg)
dwThreadId = aThread.dwThreadId
## if dwThreadId in self.__threadDict:
## msg = "Already have a Thread object with ID %d" % dwThreadId
## raise KeyError(msg)
aThread.set_process(self)
self.__threadDict[dwThreadId] = aThread
def _del_thread(self, dwThreadId):
"""
Private method to remove a thread object from the snapshot.
@type dwThreadId: int
@param dwThreadId: Global thread ID.
"""
try:
aThread = self.__threadDict[dwThreadId]
del self.__threadDict[dwThreadId]
except KeyError:
aThread = None
msg = "Unknown thread ID %d" % dwThreadId
warnings.warn(msg, RuntimeWarning)
if aThread:
aThread.clear() # remove circular references
def _has_thread_id(self, dwThreadId):
"""
Private method to test for a thread in the snapshot without triggering
an automatic scan.
"""
return dwThreadId in self.__threadDict
def _get_thread_ids(self):
"""
Private method to get the list of thread IDs currently in the snapshot
without triggering an automatic scan.
"""
return compat.keys(self.__threadDict)
def __add_created_thread(self, event):
"""
Private method to automatically add new thread objects from debug events.
@type event: L{Event}
@param event: Event object.
"""
dwThreadId = event.get_tid()
hThread = event.get_thread_handle()
## if not self.has_thread(dwThreadId): # XXX this would trigger a scan
if not self._has_thread_id(dwThreadId):
aThread = Thread(dwThreadId, hThread, self)
teb_ptr = event.get_teb() # remember the TEB pointer
if teb_ptr:
aThread._teb_ptr = teb_ptr
self._add_thread(aThread)
#else:
# aThread = self.get_thread(dwThreadId)
# if hThread != win32.INVALID_HANDLE_VALUE:
# aThread.hThread = hThread # may have more privileges
def _notify_create_process(self, event):
"""
Notify the creation of the main thread of this process.
This is done automatically by the L{Debug} class, you shouldn't need
to call it yourself.
@type event: L{CreateProcessEvent}
@param event: Create process event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} otherwise.
"""
self.__add_created_thread(event)
return True
def _notify_create_thread(self, event):
"""
Notify the creation of a new thread in this process.
This is done automatically by the L{Debug} class, you shouldn't need
to call it yourself.
@type event: L{CreateThreadEvent}
@param event: Create thread event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} otherwise.
"""
self.__add_created_thread(event)
return True
def _notify_exit_thread(self, event):
"""
Notify the termination of a thread.
This is done automatically by the L{Debug} class, you shouldn't need
to call it yourself.
@type event: L{ExitThreadEvent}
@param event: Exit thread event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} otherwise.
"""
dwThreadId = event.get_tid()
## if self.has_thread(dwThreadId): # XXX this would trigger a scan
if self._has_thread_id(dwThreadId):
self._del_thread(dwThreadId)
return True
| 75,478 | Python | 34.469455 | 104 | 0.564019 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/interactive.py | #!~/.wine/drive_c/Python25/python.exe
# -*- coding: utf-8 -*-
# Acknowledgements:
# Nicolas Economou, for his command line debugger on which this is inspired.
# http://tinyurl.com/nicolaseconomou
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Interactive debugging console.
@group Debugging:
ConsoleDebugger
@group Exceptions:
CmdError
"""
from __future__ import with_statement
__revision__ = "$Id$"
__all__ = [ 'ConsoleDebugger', 'CmdError' ]
# TODO document this module with docstrings.
# TODO command to set a last error breakpoint.
# TODO command to show available plugins.
from winappdbg import win32
from winappdbg import compat
from winappdbg.system import System
from winappdbg.util import PathOperations
from winappdbg.event import EventHandler, NoEvent
from winappdbg.textio import HexInput, HexOutput, HexDump, CrashDump, DebugLog
import os
import sys
import code
import time
import warnings
import traceback
# too many variables named "cmd" to have a module by the same name :P
from cmd import Cmd
# lazy imports
readline = None
#==============================================================================
class DummyEvent (NoEvent):
"Dummy event object used internally by L{ConsoleDebugger}."
def get_pid(self):
return self._pid
def get_tid(self):
return self._tid
def get_process(self):
return self._process
def get_thread(self):
return self._thread
#==============================================================================
class CmdError (Exception):
"""
Exception raised when a command parsing error occurs.
Used internally by L{ConsoleDebugger}.
"""
#==============================================================================
class ConsoleDebugger (Cmd, EventHandler):
"""
Interactive console debugger.
@see: L{Debug.interactive}
"""
#------------------------------------------------------------------------------
# Class variables
# Exception to raise when an error occurs executing a command.
command_error_exception = CmdError
# Milliseconds to wait for debug events in the main loop.
dwMilliseconds = 100
# History file name.
history_file = '.winappdbg_history'
# Confirm before quitting?
confirm_quit = True
# Valid plugin name characters.
valid_plugin_name_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXY' \
'abcdefghijklmnopqrstuvwxy' \
'012345678' \
'_'
# Names of the registers.
segment_names = ('cs', 'ds', 'es', 'fs', 'gs')
register_alias_64_to_32 = {
'eax':'Rax', 'ebx':'Rbx', 'ecx':'Rcx', 'edx':'Rdx',
'eip':'Rip', 'ebp':'Rbp', 'esp':'Rsp', 'esi':'Rsi', 'edi':'Rdi'
}
register_alias_64_to_16 = { 'ax':'Rax', 'bx':'Rbx', 'cx':'Rcx', 'dx':'Rdx' }
register_alias_64_to_8_low = { 'al':'Rax', 'bl':'Rbx', 'cl':'Rcx', 'dl':'Rdx' }
register_alias_64_to_8_high = { 'ah':'Rax', 'bh':'Rbx', 'ch':'Rcx', 'dh':'Rdx' }
register_alias_32_to_16 = { 'ax':'Eax', 'bx':'Ebx', 'cx':'Ecx', 'dx':'Edx' }
register_alias_32_to_8_low = { 'al':'Eax', 'bl':'Ebx', 'cl':'Ecx', 'dl':'Edx' }
register_alias_32_to_8_high = { 'ah':'Eax', 'bh':'Ebx', 'ch':'Ecx', 'dh':'Edx' }
register_aliases_full_32 = list(segment_names)
register_aliases_full_32.extend(compat.iterkeys(register_alias_32_to_16))
register_aliases_full_32.extend(compat.iterkeys(register_alias_32_to_8_low))
register_aliases_full_32.extend(compat.iterkeys(register_alias_32_to_8_high))
register_aliases_full_32 = tuple(register_aliases_full_32)
register_aliases_full_64 = list(segment_names)
register_aliases_full_64.extend(compat.iterkeys(register_alias_64_to_32))
register_aliases_full_64.extend(compat.iterkeys(register_alias_64_to_16))
register_aliases_full_64.extend(compat.iterkeys(register_alias_64_to_8_low))
register_aliases_full_64.extend(compat.iterkeys(register_alias_64_to_8_high))
register_aliases_full_64 = tuple(register_aliases_full_64)
# Names of the control flow instructions.
jump_instructions = (
'jmp', 'jecxz', 'jcxz',
'ja', 'jnbe', 'jae', 'jnb', 'jb', 'jnae', 'jbe', 'jna', 'jc', 'je',
'jz', 'jnc', 'jne', 'jnz', 'jnp', 'jpo', 'jp', 'jpe', 'jg', 'jnle',
'jge', 'jnl', 'jl', 'jnge', 'jle', 'jng', 'jno', 'jns', 'jo', 'js'
)
call_instructions = ('call', 'ret', 'retn')
loop_instructions = ('loop', 'loopz', 'loopnz', 'loope', 'loopne')
control_flow_instructions = call_instructions + loop_instructions + \
jump_instructions
#------------------------------------------------------------------------------
# Instance variables
def __init__(self):
"""
Interactive console debugger.
@see: L{Debug.interactive}
"""
Cmd.__init__(self)
EventHandler.__init__(self)
# Quit the debugger when True.
self.debuggerExit = False
# Full path to the history file.
self.history_file_full_path = None
# Last executed command.
self.__lastcmd = ""
#------------------------------------------------------------------------------
# Debugger
# Use this Debug object.
def start_using_debugger(self, debug):
# Clear the previous Debug object.
self.stop_using_debugger()
# Keep the Debug object.
self.debug = debug
# Set ourselves as the event handler for the debugger.
self.prevHandler = debug.set_event_handler(self)
# Stop using the Debug object given by start_using_debugger().
# Circular references must be removed, or the destructors never get called.
def stop_using_debugger(self):
if hasattr(self, 'debug'):
debug = self.debug
debug.set_event_handler(self.prevHandler)
del self.prevHandler
del self.debug
return debug
return None
# Destroy the Debug object.
def destroy_debugger(self, autodetach=True):
debug = self.stop_using_debugger()
if debug is not None:
if not autodetach:
debug.kill_all(bIgnoreExceptions=True)
debug.lastEvent = None
debug.stop()
del debug
@property
def lastEvent(self):
return self.debug.lastEvent
def set_fake_last_event(self, process):
if self.lastEvent is None:
self.debug.lastEvent = DummyEvent(self.debug)
self.debug.lastEvent._process = process
self.debug.lastEvent._thread = process.get_thread(
process.get_thread_ids()[0])
self.debug.lastEvent._pid = process.get_pid()
self.debug.lastEvent._tid = self.lastEvent._thread.get_tid()
#------------------------------------------------------------------------------
# Input
# TODO
# * try to guess breakpoints when insufficient data is given
# * child Cmd instances will have to be used for other prompts, for example
# when assembling or editing memory - it may also be a good idea to think
# if it's possible to make the main Cmd instance also a child, instead of
# the debugger itself - probably the same goes for the EventHandler, maybe
# it can be used as a contained object rather than a parent class.
# Join a token list into an argument string.
def join_tokens(self, token_list):
return self.debug.system.argv_to_cmdline(token_list)
# Split an argument string into a token list.
def split_tokens(self, arg, min_count=0, max_count=None):
token_list = self.debug.system.cmdline_to_argv(arg)
if len(token_list) < min_count:
raise CmdError("missing parameters.")
if max_count and len(token_list) > max_count:
raise CmdError("too many parameters.")
return token_list
# Token is a thread ID or name.
def input_thread(self, token):
targets = self.input_thread_list([token])
if len(targets) == 0:
raise CmdError("missing thread name or ID")
if len(targets) > 1:
msg = "more than one thread with that name:\n"
for tid in targets:
msg += "\t%d\n" % tid
msg = msg[:-len("\n")]
raise CmdError(msg)
return targets[0]
# Token list is a list of thread IDs or names.
def input_thread_list(self, token_list):
targets = set()
system = self.debug.system
for token in token_list:
try:
tid = self.input_integer(token)
if not system.has_thread(tid):
raise CmdError("thread not found (%d)" % tid)
targets.add(tid)
except ValueError:
found = set()
for process in system.iter_processes():
found.update(system.find_threads_by_name(token))
if not found:
raise CmdError("thread not found (%s)" % token)
for thread in found:
targets.add(thread.get_tid())
targets = list(targets)
targets.sort()
return targets
# Token is a process ID or name.
def input_process(self, token):
targets = self.input_process_list([token])
if len(targets) == 0:
raise CmdError("missing process name or ID")
if len(targets) > 1:
msg = "more than one process with that name:\n"
for pid in targets:
msg += "\t%d\n" % pid
msg = msg[:-len("\n")]
raise CmdError(msg)
return targets[0]
# Token list is a list of process IDs or names.
def input_process_list(self, token_list):
targets = set()
system = self.debug.system
for token in token_list:
try:
pid = self.input_integer(token)
if not system.has_process(pid):
raise CmdError("process not found (%d)" % pid)
targets.add(pid)
except ValueError:
found = system.find_processes_by_filename(token)
if not found:
raise CmdError("process not found (%s)" % token)
for (process, _) in found:
targets.add(process.get_pid())
targets = list(targets)
targets.sort()
return targets
# Token is a command line to execute.
def input_command_line(self, command_line):
argv = self.debug.system.cmdline_to_argv(command_line)
if not argv:
raise CmdError("missing command line to execute")
fname = argv[0]
if not os.path.exists(fname):
try:
fname, _ = win32.SearchPath(None, fname, '.exe')
except WindowsError:
raise CmdError("file not found: %s" % fname)
argv[0] = fname
command_line = self.debug.system.argv_to_cmdline(argv)
return command_line
# Token is an integer.
# Only hexadecimal format is supported.
def input_hexadecimal_integer(self, token):
return int(token, 0x10)
# Token is an integer.
# It can be in any supported format.
def input_integer(self, token):
return HexInput.integer(token)
# # input_integer = input_hexadecimal_integer
# Token is an address.
# The address can be a integer, a label or a register.
def input_address(self, token, pid=None, tid=None):
address = None
if self.is_register(token):
if tid is None:
if self.lastEvent is None or pid != self.lastEvent.get_pid():
msg = "can't resolve register (%s) for unknown thread"
raise CmdError(msg % token)
tid = self.lastEvent.get_tid()
address = self.input_register(token, tid)
if address is None:
try:
address = self.input_hexadecimal_integer(token)
except ValueError:
if pid is None:
if self.lastEvent is None:
raise CmdError("no current process set")
process = self.lastEvent.get_process()
elif self.lastEvent is not None and pid == self.lastEvent.get_pid():
process = self.lastEvent.get_process()
else:
try:
process = self.debug.system.get_process(pid)
except KeyError:
raise CmdError("process not found (%d)" % pid)
try:
address = process.resolve_label(token)
except Exception:
raise CmdError("unknown address (%s)" % token)
return address
# Token is an address range, or a single address.
# The addresses can be integers, labels or registers.
def input_address_range(self, token_list, pid=None, tid=None):
if len(token_list) == 2:
token_1, token_2 = token_list
address = self.input_address(token_1, pid, tid)
try:
size = self.input_integer(token_2)
except ValueError:
raise CmdError("bad address range: %s %s" % (token_1, token_2))
elif len(token_list) == 1:
token = token_list[0]
if '-' in token:
try:
token_1, token_2 = token.split('-')
except Exception:
raise CmdError("bad address range: %s" % token)
address = self.input_address(token_1, pid, tid)
size = self.input_address(token_2, pid, tid) - address
else:
address = self.input_address(token, pid, tid)
size = None
return address, size
# XXX TODO
# Support non-integer registers here.
def is_register(self, token):
if win32.arch == 'i386':
if token in self.register_aliases_full_32:
return True
token = token.title()
for (name, typ) in win32.CONTEXT._fields_:
if name == token:
return win32.sizeof(typ) == win32.sizeof(win32.DWORD)
elif win32.arch == 'amd64':
if token in self.register_aliases_full_64:
return True
token = token.title()
for (name, typ) in win32.CONTEXT._fields_:
if name == token:
return win32.sizeof(typ) == win32.sizeof(win32.DWORD64)
return False
# The token is a register name.
# Returns None if no register name is matched.
def input_register(self, token, tid=None):
if tid is None:
if self.lastEvent is None:
raise CmdError("no current process set")
thread = self.lastEvent.get_thread()
else:
thread = self.debug.system.get_thread(tid)
ctx = thread.get_context()
token = token.lower()
title = token.title()
if title in ctx:
return ctx.get(title) # eax -> Eax
if ctx.arch == 'i386':
if token in self.segment_names:
return ctx.get('Seg%s' % title) # cs -> SegCs
if token in self.register_alias_32_to_16:
return ctx.get(self.register_alias_32_to_16[token]) & 0xFFFF
if token in self.register_alias_32_to_8_low:
return ctx.get(self.register_alias_32_to_8_low[token]) & 0xFF
if token in self.register_alias_32_to_8_high:
return (ctx.get(self.register_alias_32_to_8_high[token]) & 0xFF00) >> 8
elif ctx.arch == 'amd64':
if token in self.segment_names:
return ctx.get('Seg%s' % title) # cs -> SegCs
if token in self.register_alias_64_to_32:
return ctx.get(self.register_alias_64_to_32[token]) & 0xFFFFFFFF
if token in self.register_alias_64_to_16:
return ctx.get(self.register_alias_64_to_16[token]) & 0xFFFF
if token in self.register_alias_64_to_8_low:
return ctx.get(self.register_alias_64_to_8_low[token]) & 0xFF
if token in self.register_alias_64_to_8_high:
return (ctx.get(self.register_alias_64_to_8_high[token]) & 0xFF00) >> 8
return None
# Token list contains an address or address range.
# The prefix is also parsed looking for process and thread IDs.
def input_full_address_range(self, token_list):
pid, tid = self.get_process_and_thread_ids_from_prefix()
address, size = self.input_address_range(token_list, pid, tid)
return pid, tid, address, size
# Token list contains a breakpoint.
def input_breakpoint(self, token_list):
pid, tid, address, size = self.input_full_address_range(token_list)
if not self.debug.is_debugee(pid):
raise CmdError("target process is not being debugged")
return pid, tid, address, size
# Token list contains a memory address, and optional size and process.
# Sets the results as the default for the next display command.
def input_display(self, token_list, default_size=64):
pid, tid, address, size = self.input_full_address_range(token_list)
if not size:
size = default_size
next_address = HexOutput.integer(address + size)
self.default_display_target = next_address
return pid, tid, address, size
#------------------------------------------------------------------------------
# Output
# Tell the user a module was loaded.
def print_module_load(self, event):
mod = event.get_module()
base = mod.get_base()
name = mod.get_filename()
if not name:
name = ''
msg = "Loaded module (%s) %s"
msg = msg % (HexDump.address(base), name)
print(msg)
# Tell the user a module was unloaded.
def print_module_unload(self, event):
mod = event.get_module()
base = mod.get_base()
name = mod.get_filename()
if not name:
name = ''
msg = "Unloaded module (%s) %s"
msg = msg % (HexDump.address(base), name)
print(msg)
# Tell the user a process was started.
def print_process_start(self, event):
pid = event.get_pid()
start = event.get_start_address()
if start:
start = HexOutput.address(start)
print("Started process %d at %s" % (pid, start))
else:
print("Attached to process %d" % pid)
# Tell the user a thread was started.
def print_thread_start(self, event):
tid = event.get_tid()
start = event.get_start_address()
if start:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
start = event.get_process().get_label_at_address(start)
print("Started thread %d at %s" % (tid, start))
else:
print("Attached to thread %d" % tid)
# Tell the user a process has finished.
def print_process_end(self, event):
pid = event.get_pid()
code = event.get_exit_code()
print("Process %d terminated, exit code %d" % (pid, code))
# Tell the user a thread has finished.
def print_thread_end(self, event):
tid = event.get_tid()
code = event.get_exit_code()
print("Thread %d terminated, exit code %d" % (tid, code))
# Print(debug strings.
def print_debug_string(self, event):
tid = event.get_tid()
string = event.get_debug_string()
print("Thread %d says: %r" % (tid, string))
# Inform the user of any other debugging event.
def print_event(self, event):
code = HexDump.integer(event.get_event_code())
name = event.get_event_name()
desc = event.get_event_description()
if code in desc:
print('')
print("%s: %s" % (name, desc))
else:
print('')
print("%s (%s): %s" % (name, code, desc))
self.print_event_location(event)
# Stop on exceptions and prompt for commands.
def print_exception(self, event):
address = HexDump.address(event.get_exception_address())
code = HexDump.integer(event.get_exception_code())
desc = event.get_exception_description()
if event.is_first_chance():
chance = 'first'
else:
chance = 'second'
if code in desc:
msg = "%s at address %s (%s chance)" % (desc, address, chance)
else:
msg = "%s (%s) at address %s (%s chance)" % (desc, code, address, chance)
print('')
print(msg)
self.print_event_location(event)
# Show the current location in the code.
def print_event_location(self, event):
process = event.get_process()
thread = event.get_thread()
self.print_current_location(process, thread)
# Show the current location in the code.
def print_breakpoint_location(self, event):
process = event.get_process()
thread = event.get_thread()
pc = event.get_exception_address()
self.print_current_location(process, thread, pc)
# Show the current location in any process and thread.
def print_current_location(self, process=None, thread=None, pc=None):
if not process:
if self.lastEvent is None:
raise CmdError("no current process set")
process = self.lastEvent.get_process()
if not thread:
if self.lastEvent is None:
raise CmdError("no current process set")
thread = self.lastEvent.get_thread()
thread.suspend()
try:
if pc is None:
pc = thread.get_pc()
ctx = thread.get_context()
finally:
thread.resume()
label = process.get_label_at_address(pc)
try:
disasm = process.disassemble(pc, 15)
except WindowsError:
disasm = None
except NotImplementedError:
disasm = None
print('')
print(CrashDump.dump_registers(ctx),)
print("%s:" % label)
if disasm:
print(CrashDump.dump_code_line(disasm[0], pc, bShowDump=True))
else:
try:
data = process.peek(pc, 15)
except Exception:
data = None
if data:
print('%s: %s' % (HexDump.address(pc), HexDump.hexblock_byte(data)))
else:
print('%s: ???' % HexDump.address(pc))
# Display memory contents using a given method.
def print_memory_display(self, arg, method):
if not arg:
arg = self.default_display_target
token_list = self.split_tokens(arg, 1, 2)
pid, tid, address, size = self.input_display(token_list)
label = self.get_process(pid).get_label_at_address(address)
data = self.read_memory(address, size, pid)
if data:
print("%s:" % label)
print(method(data, address),)
#------------------------------------------------------------------------------
# Debugging
# Get the process ID from the prefix or the last event.
def get_process_id_from_prefix(self):
if self.cmdprefix:
pid = self.input_process(self.cmdprefix)
else:
if self.lastEvent is None:
raise CmdError("no current process set")
pid = self.lastEvent.get_pid()
return pid
# Get the thread ID from the prefix or the last event.
def get_thread_id_from_prefix(self):
if self.cmdprefix:
tid = self.input_thread(self.cmdprefix)
else:
if self.lastEvent is None:
raise CmdError("no current process set")
tid = self.lastEvent.get_tid()
return tid
# Get the process from the prefix or the last event.
def get_process_from_prefix(self):
pid = self.get_process_id_from_prefix()
return self.get_process(pid)
# Get the thread from the prefix or the last event.
def get_thread_from_prefix(self):
tid = self.get_thread_id_from_prefix()
return self.get_thread(tid)
# Get the process and thread IDs from the prefix or the last event.
def get_process_and_thread_ids_from_prefix(self):
if self.cmdprefix:
try:
pid = self.input_process(self.cmdprefix)
tid = None
except CmdError:
try:
tid = self.input_thread(self.cmdprefix)
pid = self.debug.system.get_thread(tid).get_pid()
except CmdError:
msg = "unknown process or thread (%s)" % self.cmdprefix
raise CmdError(msg)
else:
if self.lastEvent is None:
raise CmdError("no current process set")
pid = self.lastEvent.get_pid()
tid = self.lastEvent.get_tid()
return pid, tid
# Get the process and thread from the prefix or the last event.
def get_process_and_thread_from_prefix(self):
pid, tid = self.get_process_and_thread_ids_from_prefix()
process = self.get_process(pid)
thread = self.get_thread(tid)
return process, thread
# Get the process object.
def get_process(self, pid=None):
if pid is None:
if self.lastEvent is None:
raise CmdError("no current process set")
process = self.lastEvent.get_process()
elif self.lastEvent is not None and pid == self.lastEvent.get_pid():
process = self.lastEvent.get_process()
else:
try:
process = self.debug.system.get_process(pid)
except KeyError:
raise CmdError("process not found (%d)" % pid)
return process
# Get the thread object.
def get_thread(self, tid=None):
if tid is None:
if self.lastEvent is None:
raise CmdError("no current process set")
thread = self.lastEvent.get_thread()
elif self.lastEvent is not None and tid == self.lastEvent.get_tid():
thread = self.lastEvent.get_thread()
else:
try:
thread = self.debug.system.get_thread(tid)
except KeyError:
raise CmdError("thread not found (%d)" % tid)
return thread
# Read the process memory.
def read_memory(self, address, size, pid=None):
process = self.get_process(pid)
try:
data = process.peek(address, size)
except WindowsError:
orig_address = HexOutput.integer(address)
next_address = HexOutput.integer(address + size)
msg = "error reading process %d, from %s to %s (%d bytes)"
msg = msg % (pid, orig_address, next_address, size)
raise CmdError(msg)
return data
# Write the process memory.
def write_memory(self, address, data, pid=None):
process = self.get_process(pid)
try:
process.write(address, data)
except WindowsError:
size = len(data)
orig_address = HexOutput.integer(address)
next_address = HexOutput.integer(address + size)
msg = "error reading process %d, from %s to %s (%d bytes)"
msg = msg % (pid, orig_address, next_address, size)
raise CmdError(msg)
# Change a register value.
def change_register(self, register, value, tid=None):
# Get the thread.
if tid is None:
if self.lastEvent is None:
raise CmdError("no current process set")
thread = self.lastEvent.get_thread()
else:
try:
thread = self.debug.system.get_thread(tid)
except KeyError:
raise CmdError("thread not found (%d)" % tid)
# Convert the value to integer type.
try:
value = self.input_integer(value)
except ValueError:
pid = thread.get_pid()
value = self.input_address(value, pid, tid)
# Suspend the thread.
# The finally clause ensures the thread is resumed before returning.
thread.suspend()
try:
# Get the current context.
ctx = thread.get_context()
# Register name matching is case insensitive.
register = register.lower()
# Integer 32 bits registers.
if register in self.register_names:
register = register.title() # eax -> Eax
# Segment (16 bit) registers.
if register in self.segment_names:
register = 'Seg%s' % register.title() # cs -> SegCs
value = value & 0x0000FFFF
# Integer 16 bits registers.
if register in self.register_alias_16:
register = self.register_alias_16[register]
previous = ctx.get(register) & 0xFFFF0000
value = (value & 0x0000FFFF) | previous
# Integer 8 bits registers (low part).
if register in self.register_alias_8_low:
register = self.register_alias_8_low[register]
previous = ctx.get(register) % 0xFFFFFF00
value = (value & 0x000000FF) | previous
# Integer 8 bits registers (high part).
if register in self.register_alias_8_high:
register = self.register_alias_8_high[register]
previous = ctx.get(register) % 0xFFFF00FF
value = ((value & 0x000000FF) << 8) | previous
# Set the new context.
ctx.__setitem__(register, value)
thread.set_context(ctx)
# Resume the thread.
finally:
thread.resume()
# Very crude way to find data within the process memory.
# TODO: Perhaps pfind.py can be integrated here instead.
def find_in_memory(self, query, process):
for mbi in process.get_memory_map():
if mbi.State != win32.MEM_COMMIT or mbi.Protect & win32.PAGE_GUARD:
continue
address = mbi.BaseAddress
size = mbi.RegionSize
try:
data = process.read(address, size)
except WindowsError:
msg = "*** Warning: read error at address %s"
msg = msg % HexDump.address(address)
print(msg)
width = min(len(query), 16)
p = data.find(query)
while p >= 0:
q = p + len(query)
d = data[ p: min(q, p + width) ]
h = HexDump.hexline(d, width=width)
a = HexDump.address(address + p)
print("%s: %s" % (a, h))
p = data.find(query, q)
# Kill a process.
def kill_process(self, pid):
process = self.debug.system.get_process(pid)
try:
process.kill()
if self.debug.is_debugee(pid):
self.debug.detach(pid)
print("Killed process (%d)" % pid)
except Exception:
print("Error trying to kill process (%d)" % pid)
# Kill a thread.
def kill_thread(self, tid):
thread = self.debug.system.get_thread(tid)
try:
thread.kill()
process = thread.get_process()
pid = process.get_pid()
if self.debug.is_debugee(pid) and not process.is_alive():
self.debug.detach(pid)
print("Killed thread (%d)" % tid)
except Exception:
print("Error trying to kill thread (%d)" % tid)
#------------------------------------------------------------------------------
# Command prompt input
# Prompt the user for commands.
def prompt_user(self):
while not self.debuggerExit:
try:
self.cmdloop()
break
except CmdError:
e = sys.exc_info()[1]
print("*** Error: %s" % str(e))
except Exception:
traceback.print_exc()
# # self.debuggerExit = True
# Prompt the user for a YES/NO kind of question.
def ask_user(self, msg, prompt="Are you sure? (y/N): "):
print(msg)
answer = raw_input(prompt)
answer = answer.strip()[:1].lower()
return answer == 'y'
# Autocomplete the given command when not ambiguous.
# Convert it to lowercase (so commands are seen as case insensitive).
def autocomplete(self, cmd):
cmd = cmd.lower()
completed = self.completenames(cmd)
if len(completed) == 1:
cmd = completed[0]
return cmd
# Get the help text for the given list of command methods.
# Note it's NOT a list of commands, but a list of actual method names.
# Each line of text is stripped and all lines are sorted.
# Repeated text lines are removed.
# Returns a single, possibly multiline, string.
def get_help(self, commands):
msg = set()
for name in commands:
if name != 'do_help':
try:
doc = getattr(self, name).__doc__.split('\n')
except Exception:
return ("No help available when Python"
" is run with the -OO switch.")
for x in doc:
x = x.strip()
if x:
msg.add(' %s' % x)
msg = list(msg)
msg.sort()
msg = '\n'.join(msg)
return msg
# Parse the prefix and remove it from the command line.
def split_prefix(self, line):
prefix = None
if line.startswith('~'):
pos = line.find(' ')
if pos == 1:
pos = line.find(' ', pos + 1)
if not pos < 0:
prefix = line[ 1: pos ].strip()
line = line[ pos: ].strip()
return prefix, line
#------------------------------------------------------------------------------
# Cmd() hacks
# Header for help page.
doc_header = 'Available commands (type help * or help <command>)'
# # # Read and write directly to stdin and stdout.
# # # This prevents the use of raw_input and print.
# # use_rawinput = False
@property
def prompt(self):
if self.lastEvent:
pid = self.lastEvent.get_pid()
tid = self.lastEvent.get_tid()
if self.debug.is_debugee(pid):
# # return '~%d(%d)> ' % (tid, pid)
return '%d:%d> ' % (pid, tid)
return '> '
# Return a sorted list of method names.
# Only returns the methods that implement commands.
def get_names(self):
names = Cmd.get_names(self)
names = [ x for x in set(names) if x.startswith('do_') ]
names.sort()
return names
# Automatically autocomplete commands, even if Tab wasn't pressed.
# The prefix is removed from the line and stored in self.cmdprefix.
# Also implement the commands that consist of a symbol character.
def parseline(self, line):
self.cmdprefix, line = self.split_prefix(line)
line = line.strip()
if line:
if line[0] == '.':
line = 'plugin ' + line[1:]
elif line[0] == '#':
line = 'python ' + line[1:]
cmd, arg, line = Cmd.parseline(self, line)
if cmd:
cmd = self.autocomplete(cmd)
return cmd, arg, line
# # # Don't repeat the last executed command.
# # def emptyline(self):
# # pass
# Reset the defaults for some commands.
def preloop(self):
self.default_disasm_target = 'eip'
self.default_display_target = 'eip'
self.last_display_command = self.do_db
# Put the prefix back in the command line.
def get_lastcmd(self):
return self.__lastcmd
def set_lastcmd(self, lastcmd):
if self.cmdprefix:
lastcmd = '~%s %s' % (self.cmdprefix, lastcmd)
self.__lastcmd = lastcmd
lastcmd = property(get_lastcmd, set_lastcmd)
# Quit the command prompt if the debuggerExit flag is on.
def postcmd(self, stop, line):
return stop or self.debuggerExit
#------------------------------------------------------------------------------
# Commands
# Each command contains a docstring with it's help text.
# The help text consist of independent text lines,
# where each line shows a command and it's parameters.
# Each command method has the help message for itself and all it's aliases.
# Only the docstring for the "help" command is shown as-is.
# NOTE: Command methods MUST be all lowercase!
# Extended help command.
def do_help(self, arg):
"""
? - show the list of available commands
? * - show help for all commands
? <command> [command...] - show help for the given command(s)
help - show the list of available commands
help * - show help for all commands
help <command> [command...] - show help for the given command(s)
"""
if not arg:
Cmd.do_help(self, arg)
elif arg in ('?', 'help'):
# An easter egg :)
print(" Help! I need somebody...")
print(" Help! Not just anybody...")
print(" Help! You know, I need someone...")
print(" Heeelp!")
else:
if arg == '*':
commands = self.get_names()
commands = [ x for x in commands if x.startswith('do_') ]
else:
commands = set()
for x in arg.split(' '):
x = x.strip()
if x:
for n in self.completenames(x):
commands.add('do_%s' % n)
commands = list(commands)
commands.sort()
print(self.get_help(commands))
def do_shell(self, arg):
"""
! - spawn a system shell
shell - spawn a system shell
! <command> [arguments...] - execute a single shell command
shell <command> [arguments...] - execute a single shell command
"""
if self.cmdprefix:
raise CmdError("prefix not allowed")
# Try to use the environment to locate cmd.exe.
# If not found, it's usually OK to just use the filename,
# since cmd.exe is one of those "magic" programs that
# can be automatically found by CreateProcess.
shell = os.getenv('ComSpec', 'cmd.exe')
# When given a command, run it and return.
# When no command is given, spawn a shell.
if arg:
arg = '%s /c %s' % (shell, arg)
else:
arg = shell
process = self.debug.system.start_process(arg, bConsole=True)
process.wait()
# This hack fixes a bug in Python, the interpreter console is closing the
# stdin pipe when calling the exit() function (Ctrl+Z seems to work fine).
class _PythonExit(object):
def __repr__(self):
return "Use exit() or Ctrl-Z plus Return to exit"
def __call__(self):
raise SystemExit()
_python_exit = _PythonExit()
# Spawns a Python shell with some handy local variables and the winappdbg
# module already imported. Also the console banner is improved.
def _spawn_python_shell(self, arg):
import winappdbg
banner = ('Python %s on %s\nType "help", "copyright", '
'"credits" or "license" for more information.\n')
platform = winappdbg.version.lower()
platform = 'WinAppDbg %s' % platform
banner = banner % (sys.version, platform)
local = {}
local.update(__builtins__)
local.update({
'__name__': '__console__',
'__doc__': None,
'exit': self._python_exit,
'self': self,
'arg': arg,
'winappdbg': winappdbg,
})
try:
code.interact(banner=banner, local=local)
except SystemExit:
# We need to catch it so it doesn't kill our program.
pass
def do_python(self, arg):
"""
# - spawn a python interpreter
python - spawn a python interpreter
# <statement> - execute a single python statement
python <statement> - execute a single python statement
"""
if self.cmdprefix:
raise CmdError("prefix not allowed")
# When given a Python statement, execute it directly.
if arg:
try:
compat.exec_(arg, globals(), locals())
except Exception:
traceback.print_exc()
# When no statement is given, spawn a Python interpreter.
else:
try:
self._spawn_python_shell(arg)
except Exception:
e = sys.exc_info()[1]
raise CmdError(
"unhandled exception when running Python console: %s" % e)
def do_quit(self, arg):
"""
quit - close the debugging session
q - close the debugging session
"""
if self.cmdprefix:
raise CmdError("prefix not allowed")
if arg:
raise CmdError("too many arguments")
if self.confirm_quit:
count = self.debug.get_debugee_count()
if count > 0:
if count == 1:
msg = "There's a program still running."
else:
msg = "There are %s programs still running." % count
if not self.ask_user(msg):
return False
self.debuggerExit = True
return True
do_q = do_quit
def do_attach(self, arg):
"""
attach <target> [target...] - attach to the given process(es)
"""
if self.cmdprefix:
raise CmdError("prefix not allowed")
targets = self.input_process_list(self.split_tokens(arg, 1))
if not targets:
print("Error: missing parameters")
else:
debug = self.debug
for pid in targets:
try:
debug.attach(pid)
print("Attached to process (%d)" % pid)
except Exception:
print("Error: can't attach to process (%d)" % pid)
def do_detach(self, arg):
"""
[~process] detach - detach from the current process
detach - detach from the current process
detach <target> [target...] - detach from the given process(es)
"""
debug = self.debug
token_list = self.split_tokens(arg)
if self.cmdprefix:
token_list.insert(0, self.cmdprefix)
targets = self.input_process_list(token_list)
if not targets:
if self.lastEvent is None:
raise CmdError("no current process set")
targets = [ self.lastEvent.get_pid() ]
for pid in targets:
try:
debug.detach(pid)
print("Detached from process (%d)" % pid)
except Exception:
print("Error: can't detach from process (%d)" % pid)
def do_windowed(self, arg):
"""
windowed <target> [arguments...] - run a windowed program for debugging
"""
if self.cmdprefix:
raise CmdError("prefix not allowed")
cmdline = self.input_command_line(arg)
try:
process = self.debug.execl(arg,
bConsole=False,
bFollow=self.options.follow)
print("Spawned process (%d)" % process.get_pid())
except Exception:
raise CmdError("can't execute")
self.set_fake_last_event(process)
def do_console(self, arg):
"""
console <target> [arguments...] - run a console program for debugging
"""
if self.cmdprefix:
raise CmdError("prefix not allowed")
cmdline = self.input_command_line(arg)
try:
process = self.debug.execl(arg,
bConsole=True,
bFollow=self.options.follow)
print("Spawned process (%d)" % process.get_pid())
except Exception:
raise CmdError("can't execute")
self.set_fake_last_event(process)
def do_continue(self, arg):
"""
continue - continue execution
g - continue execution
go - continue execution
"""
if self.cmdprefix:
raise CmdError("prefix not allowed")
if arg:
raise CmdError("too many arguments")
if self.debug.get_debugee_count() > 0:
return True
do_g = do_continue
do_go = do_continue
def do_gh(self, arg):
"""
gh - go with exception handled
"""
if self.cmdprefix:
raise CmdError("prefix not allowed")
if arg:
raise CmdError("too many arguments")
if self.lastEvent:
self.lastEvent.continueStatus = win32.DBG_EXCEPTION_HANDLED
return self.do_go(arg)
def do_gn(self, arg):
"""
gn - go with exception not handled
"""
if self.cmdprefix:
raise CmdError("prefix not allowed")
if arg:
raise CmdError("too many arguments")
if self.lastEvent:
self.lastEvent.continueStatus = win32.DBG_EXCEPTION_NOT_HANDLED
return self.do_go(arg)
def do_refresh(self, arg):
"""
refresh - refresh the list of running processes and threads
[~process] refresh - refresh the list of running threads
"""
if arg:
raise CmdError("too many arguments")
if self.cmdprefix:
process = self.get_process_from_prefix()
process.scan()
else:
self.debug.system.scan()
def do_processlist(self, arg):
"""
pl - show the processes being debugged
processlist - show the processes being debugged
"""
if self.cmdprefix:
raise CmdError("prefix not allowed")
if arg:
raise CmdError("too many arguments")
system = self.debug.system
pid_list = self.debug.get_debugee_pids()
if pid_list:
print("Process ID File name")
for pid in pid_list:
if pid == 0:
filename = "System Idle Process"
elif pid == 4:
filename = "System"
else:
filename = system.get_process(pid).get_filename()
filename = PathOperations.pathname_to_filename(filename)
print("%-12d %s" % (pid, filename))
do_pl = do_processlist
def do_threadlist(self, arg):
"""
tl - show the threads being debugged
threadlist - show the threads being debugged
"""
if arg:
raise CmdError("too many arguments")
if self.cmdprefix:
process = self.get_process_from_prefix()
for thread in process.iter_threads():
tid = thread.get_tid()
name = thread.get_name()
print("%-12d %s" % (tid, name))
else:
system = self.debug.system
pid_list = self.debug.get_debugee_pids()
if pid_list:
print("Thread ID Thread name")
for pid in pid_list:
process = system.get_process(pid)
for thread in process.iter_threads():
tid = thread.get_tid()
name = thread.get_name()
print("%-12d %s" % (tid, name))
do_tl = do_threadlist
def do_kill(self, arg):
"""
[~process] kill - kill a process
[~thread] kill - kill a thread
kill - kill the current process
kill * - kill all debugged processes
kill <processes and/or threads...> - kill the given processes and threads
"""
if arg:
if arg == '*':
target_pids = self.debug.get_debugee_pids()
target_tids = list()
else:
target_pids = set()
target_tids = set()
if self.cmdprefix:
pid, tid = self.get_process_and_thread_ids_from_prefix()
if tid is None:
target_tids.add(tid)
else:
target_pids.add(pid)
for token in self.split_tokens(arg):
try:
pid = self.input_process(token)
target_pids.add(pid)
except CmdError:
try:
tid = self.input_process(token)
target_pids.add(pid)
except CmdError:
msg = "unknown process or thread (%s)" % token
raise CmdError(msg)
target_pids = list(target_pids)
target_tids = list(target_tids)
target_pids.sort()
target_tids.sort()
msg = "You are about to kill %d processes and %d threads."
msg = msg % (len(target_pids), len(target_tids))
if self.ask_user(msg):
for pid in target_pids:
self.kill_process(pid)
for tid in target_tids:
self.kill_thread(tid)
else:
if self.cmdprefix:
pid, tid = self.get_process_and_thread_ids_from_prefix()
if tid is None:
if self.lastEvent is not None and pid == self.lastEvent.get_pid():
msg = "You are about to kill the current process."
else:
msg = "You are about to kill process %d." % pid
if self.ask_user(msg):
self.kill_process(pid)
else:
if self.lastEvent is not None and tid == self.lastEvent.get_tid():
msg = "You are about to kill the current thread."
else:
msg = "You are about to kill thread %d." % tid
if self.ask_user(msg):
self.kill_thread(tid)
else:
if self.lastEvent is None:
raise CmdError("no current process set")
pid = self.lastEvent.get_pid()
if self.ask_user("You are about to kill the current process."):
self.kill_process(pid)
# TODO: create hidden threads using undocumented API calls.
def do_modload(self, arg):
"""
[~process] modload <filename.dll> - load a DLL module
"""
filename = self.split_tokens(arg, 1, 1)[0]
process = self.get_process_from_prefix()
try:
process.inject_dll(filename, bWait=False)
except RuntimeError:
print("Can't inject module: %r" % filename)
# TODO: modunload
def do_stack(self, arg):
"""
[~thread] k - show the stack trace
[~thread] stack - show the stack trace
"""
if arg: # XXX TODO add depth parameter
raise CmdError("too many arguments")
pid, tid = self.get_process_and_thread_ids_from_prefix()
process = self.get_process(pid)
thread = process.get_thread(tid)
try:
stack_trace = thread.get_stack_trace_with_labels()
if stack_trace:
print(CrashDump.dump_stack_trace_with_labels(stack_trace),)
else:
print("No stack trace available for thread (%d)" % tid)
except WindowsError:
print("Can't get stack trace for thread (%d)" % tid)
do_k = do_stack
def do_break(self, arg):
"""
break - force a debug break in all debugees
break <process> [process...] - force a debug break
"""
debug = self.debug
system = debug.system
targets = self.input_process_list(self.split_tokens(arg))
if not targets:
targets = debug.get_debugee_pids()
targets.sort()
if self.lastEvent:
current = self.lastEvent.get_pid()
else:
current = None
for pid in targets:
if pid != current and debug.is_debugee(pid):
process = system.get_process(pid)
try:
process.debug_break()
except WindowsError:
print("Can't force a debug break on process (%d)")
def do_step(self, arg):
"""
p - step on the current assembly instruction
next - step on the current assembly instruction
step - step on the current assembly instruction
"""
if self.cmdprefix:
raise CmdError("prefix not allowed")
if self.lastEvent is None:
raise CmdError("no current process set")
if arg: # XXX this check is to be removed
raise CmdError("too many arguments")
pid = self.lastEvent.get_pid()
thread = self.lastEvent.get_thread()
pc = thread.get_pc()
code = thread.disassemble(pc, 16)[0]
size = code[1]
opcode = code[2].lower()
if ' ' in opcode:
opcode = opcode[: opcode.find(' ') ]
if opcode in self.jump_instructions or opcode in ('int', 'ret', 'retn'):
return self.do_trace(arg)
address = pc + size
# # print(hex(pc), hex(address), size # XXX DEBUG
self.debug.stalk_at(pid, address)
return True
do_p = do_step
do_next = do_step
def do_trace(self, arg):
"""
t - trace at the current assembly instruction
trace - trace at the current assembly instruction
"""
if arg: # XXX this check is to be removed
raise CmdError("too many arguments")
if self.lastEvent is None:
raise CmdError("no current thread set")
self.lastEvent.get_thread().set_tf()
return True
do_t = do_trace
def do_bp(self, arg):
"""
[~process] bp <address> - set a code breakpoint
"""
pid = self.get_process_id_from_prefix()
if not self.debug.is_debugee(pid):
raise CmdError("target process is not being debugged")
process = self.get_process(pid)
token_list = self.split_tokens(arg, 1, 1)
try:
address = self.input_address(token_list[0], pid)
deferred = False
except Exception:
address = token_list[0]
deferred = True
if not address:
address = token_list[0]
deferred = True
self.debug.break_at(pid, address)
if deferred:
print("Deferred breakpoint set at %s" % address)
else:
print("Breakpoint set at %s" % address)
def do_ba(self, arg):
"""
[~thread] ba <a|w|e> <1|2|4|8> <address> - set hardware breakpoint
"""
debug = self.debug
thread = self.get_thread_from_prefix()
pid = thread.get_pid()
tid = thread.get_tid()
if not debug.is_debugee(pid):
raise CmdError("target thread is not being debugged")
token_list = self.split_tokens(arg, 3, 3)
access = token_list[0].lower()
size = token_list[1]
address = token_list[2]
if access == 'a':
access = debug.BP_BREAK_ON_ACCESS
elif access == 'w':
access = debug.BP_BREAK_ON_WRITE
elif access == 'e':
access = debug.BP_BREAK_ON_EXECUTION
else:
raise CmdError("bad access type: %s" % token_list[0])
if size == '1':
size = debug.BP_WATCH_BYTE
elif size == '2':
size = debug.BP_WATCH_WORD
elif size == '4':
size = debug.BP_WATCH_DWORD
elif size == '8':
size = debug.BP_WATCH_QWORD
else:
raise CmdError("bad breakpoint size: %s" % size)
thread = self.get_thread_from_prefix()
tid = thread.get_tid()
pid = thread.get_pid()
if not debug.is_debugee(pid):
raise CmdError("target process is not being debugged")
address = self.input_address(address, pid)
if debug.has_hardware_breakpoint(tid, address):
debug.erase_hardware_breakpoint(tid, address)
debug.define_hardware_breakpoint(tid, address, access, size)
debug.enable_hardware_breakpoint(tid, address)
def do_bm(self, arg):
"""
[~process] bm <address-address> - set memory breakpoint
"""
pid = self.get_process_id_from_prefix()
if not self.debug.is_debugee(pid):
raise CmdError("target process is not being debugged")
process = self.get_process(pid)
token_list = self.split_tokens(arg, 1, 2)
address, size = self.input_address_range(token_list[0], pid)
self.debug.watch_buffer(pid, address, size)
def do_bl(self, arg):
"""
bl - list the breakpoints for the current process
bl * - list the breakpoints for all processes
[~process] bl - list the breakpoints for the given process
bl <process> [process...] - list the breakpoints for each given process
"""
debug = self.debug
if arg == '*':
if self.cmdprefix:
raise CmdError("prefix not supported")
breakpoints = debug.get_debugee_pids()
else:
targets = self.input_process_list(self.split_tokens(arg))
if self.cmdprefix:
targets.insert(0, self.input_process(self.cmdprefix))
if not targets:
if self.lastEvent is None:
raise CmdError("no current process is set")
targets = [ self.lastEvent.get_pid() ]
for pid in targets:
bplist = debug.get_process_code_breakpoints(pid)
printed_process_banner = False
if bplist:
if not printed_process_banner:
print("Process %d:" % pid)
printed_process_banner = True
for bp in bplist:
address = repr(bp)[1:-1].replace('remote address ', '')
print(" %s" % address)
dbplist = debug.get_process_deferred_code_breakpoints(pid)
if dbplist:
if not printed_process_banner:
print("Process %d:" % pid)
printed_process_banner = True
for (label, action, oneshot) in dbplist:
if oneshot:
address = " Deferred unconditional one-shot" \
" code breakpoint at %s"
else:
address = " Deferred unconditional" \
" code breakpoint at %s"
address = address % label
print(" %s" % address)
bplist = debug.get_process_page_breakpoints(pid)
if bplist:
if not printed_process_banner:
print("Process %d:" % pid)
printed_process_banner = True
for bp in bplist:
address = repr(bp)[1:-1].replace('remote address ', '')
print(" %s" % address)
for tid in debug.system.get_process(pid).iter_thread_ids():
bplist = debug.get_thread_hardware_breakpoints(tid)
if bplist:
print("Thread %d:" % tid)
for bp in bplist:
address = repr(bp)[1:-1].replace('remote address ', '')
print(" %s" % address)
def do_bo(self, arg):
"""
[~process] bo <address> - make a code breakpoint one-shot
[~thread] bo <address> - make a hardware breakpoint one-shot
[~process] bo <address-address> - make a memory breakpoint one-shot
[~process] bo <address> <size> - make a memory breakpoint one-shot
"""
token_list = self.split_tokens(arg, 1, 2)
pid, tid, address, size = self.input_breakpoint(token_list)
debug = self.debug
found = False
if size is None:
if tid is not None:
if debug.has_hardware_breakpoint(tid, address):
debug.enable_one_shot_hardware_breakpoint(tid, address)
found = True
if pid is not None:
if debug.has_code_breakpoint(pid, address):
debug.enable_one_shot_code_breakpoint(pid, address)
found = True
else:
if debug.has_page_breakpoint(pid, address):
debug.enable_one_shot_page_breakpoint(pid, address)
found = True
if not found:
print("Error: breakpoint not found.")
def do_be(self, arg):
"""
[~process] be <address> - enable a code breakpoint
[~thread] be <address> - enable a hardware breakpoint
[~process] be <address-address> - enable a memory breakpoint
[~process] be <address> <size> - enable a memory breakpoint
"""
token_list = self.split_tokens(arg, 1, 2)
pid, tid, address, size = self.input_breakpoint(token_list)
debug = self.debug
found = False
if size is None:
if tid is not None:
if debug.has_hardware_breakpoint(tid, address):
debug.enable_hardware_breakpoint(tid, address)
found = True
if pid is not None:
if debug.has_code_breakpoint(pid, address):
debug.enable_code_breakpoint(pid, address)
found = True
else:
if debug.has_page_breakpoint(pid, address):
debug.enable_page_breakpoint(pid, address)
found = True
if not found:
print("Error: breakpoint not found.")
def do_bd(self, arg):
"""
[~process] bd <address> - disable a code breakpoint
[~thread] bd <address> - disable a hardware breakpoint
[~process] bd <address-address> - disable a memory breakpoint
[~process] bd <address> <size> - disable a memory breakpoint
"""
token_list = self.split_tokens(arg, 1, 2)
pid, tid, address, size = self.input_breakpoint(token_list)
debug = self.debug
found = False
if size is None:
if tid is not None:
if debug.has_hardware_breakpoint(tid, address):
debug.disable_hardware_breakpoint(tid, address)
found = True
if pid is not None:
if debug.has_code_breakpoint(pid, address):
debug.disable_code_breakpoint(pid, address)
found = True
else:
if debug.has_page_breakpoint(pid, address):
debug.disable_page_breakpoint(pid, address)
found = True
if not found:
print("Error: breakpoint not found.")
def do_bc(self, arg):
"""
[~process] bc <address> - clear a code breakpoint
[~thread] bc <address> - clear a hardware breakpoint
[~process] bc <address-address> - clear a memory breakpoint
[~process] bc <address> <size> - clear a memory breakpoint
"""
token_list = self.split_tokens(arg, 1, 2)
pid, tid, address, size = self.input_breakpoint(token_list)
debug = self.debug
found = False
if size is None:
if tid is not None:
if debug.has_hardware_breakpoint(tid, address):
debug.dont_watch_variable(tid, address)
found = True
if pid is not None:
if debug.has_code_breakpoint(pid, address):
debug.dont_break_at(pid, address)
found = True
else:
if debug.has_page_breakpoint(pid, address):
debug.dont_watch_buffer(pid, address, size)
found = True
if not found:
print("Error: breakpoint not found.")
def do_disassemble(self, arg):
"""
[~thread] u [register] - show code disassembly
[~process] u [address] - show code disassembly
[~thread] disassemble [register] - show code disassembly
[~process] disassemble [address] - show code disassembly
"""
if not arg:
arg = self.default_disasm_target
token_list = self.split_tokens(arg, 1, 1)
pid, tid = self.get_process_and_thread_ids_from_prefix()
process = self.get_process(pid)
address = self.input_address(token_list[0], pid, tid)
try:
code = process.disassemble(address, 15 * 8)[:8]
except Exception:
msg = "can't disassemble address %s"
msg = msg % HexDump.address(address)
raise CmdError(msg)
if code:
label = process.get_label_at_address(address)
last_code = code[-1]
next_address = last_code[0] + last_code[1]
next_address = HexOutput.integer(next_address)
self.default_disasm_target = next_address
print("%s:" % label)
# # print(CrashDump.dump_code(code))
for line in code:
print(CrashDump.dump_code_line(line, bShowDump=False))
do_u = do_disassemble
def do_search(self, arg):
"""
[~process] s [address-address] <search string>
[~process] search [address-address] <search string>
"""
token_list = self.split_tokens(arg, 1, 3)
pid, tid = self.get_process_and_thread_ids_from_prefix()
process = self.get_process(pid)
if len(token_list) == 1:
pattern = token_list[0]
minAddr = None
maxAddr = None
else:
pattern = token_list[-1]
addr, size = self.input_address_range(token_list[:-1], pid, tid)
minAddr = addr
maxAddr = addr + size
iter = process.search_bytes(pattern)
if process.get_bits() == 32:
addr_width = 8
else:
addr_width = 16
# TODO: need a prettier output here!
for addr in iter:
print(HexDump.address(addr, addr_width))
do_s = do_search
def do_searchhex(self, arg):
"""
[~process] sh [address-address] <hexadecimal pattern>
[~process] searchhex [address-address] <hexadecimal pattern>
"""
token_list = self.split_tokens(arg, 1, 3)
pid, tid = self.get_process_and_thread_ids_from_prefix()
process = self.get_process(pid)
if len(token_list) == 1:
pattern = token_list[0]
minAddr = None
maxAddr = None
else:
pattern = token_list[-1]
addr, size = self.input_address_range(token_list[:-1], pid, tid)
minAddr = addr
maxAddr = addr + size
iter = process.search_hexa(pattern)
if process.get_bits() == 32:
addr_width = 8
else:
addr_width = 16
for addr, bytes in iter:
print(HexDump.hexblock(bytes, addr, addr_width),)
do_sh = do_searchhex
# # def do_strings(self, arg):
# # """
# # [~process] strings - extract ASCII strings from memory
# # """
# # if arg:
# # raise CmdError("too many arguments")
# # pid, tid = self.get_process_and_thread_ids_from_prefix()
# # process = self.get_process(pid)
# # for addr, size, data in process.strings():
# # print("%s: %r" % (HexDump.address(addr), data)
def do_d(self, arg):
"""
[~thread] d <register> - show memory contents
[~thread] d <register-register> - show memory contents
[~thread] d <register> <size> - show memory contents
[~process] d <address> - show memory contents
[~process] d <address-address> - show memory contents
[~process] d <address> <size> - show memory contents
"""
return self.last_display_command(arg)
def do_db(self, arg):
"""
[~thread] db <register> - show memory contents as bytes
[~thread] db <register-register> - show memory contents as bytes
[~thread] db <register> <size> - show memory contents as bytes
[~process] db <address> - show memory contents as bytes
[~process] db <address-address> - show memory contents as bytes
[~process] db <address> <size> - show memory contents as bytes
"""
self.print_memory_display(arg, HexDump.hexblock)
self.last_display_command = self.do_db
def do_dw(self, arg):
"""
[~thread] dw <register> - show memory contents as words
[~thread] dw <register-register> - show memory contents as words
[~thread] dw <register> <size> - show memory contents as words
[~process] dw <address> - show memory contents as words
[~process] dw <address-address> - show memory contents as words
[~process] dw <address> <size> - show memory contents as words
"""
self.print_memory_display(arg, HexDump.hexblock_word)
self.last_display_command = self.do_dw
def do_dd(self, arg):
"""
[~thread] dd <register> - show memory contents as dwords
[~thread] dd <register-register> - show memory contents as dwords
[~thread] dd <register> <size> - show memory contents as dwords
[~process] dd <address> - show memory contents as dwords
[~process] dd <address-address> - show memory contents as dwords
[~process] dd <address> <size> - show memory contents as dwords
"""
self.print_memory_display(arg, HexDump.hexblock_dword)
self.last_display_command = self.do_dd
def do_dq(self, arg):
"""
[~thread] dq <register> - show memory contents as qwords
[~thread] dq <register-register> - show memory contents as qwords
[~thread] dq <register> <size> - show memory contents as qwords
[~process] dq <address> - show memory contents as qwords
[~process] dq <address-address> - show memory contents as qwords
[~process] dq <address> <size> - show memory contents as qwords
"""
self.print_memory_display(arg, HexDump.hexblock_qword)
self.last_display_command = self.do_dq
# XXX TODO
# Change the way the default is used with ds and du
def do_ds(self, arg):
"""
[~thread] ds <register> - show memory contents as ANSI string
[~process] ds <address> - show memory contents as ANSI string
"""
if not arg:
arg = self.default_display_target
token_list = self.split_tokens(arg, 1, 1)
pid, tid, address, size = self.input_display(token_list, 256)
process = self.get_process(pid)
data = process.peek_string(address, False, size)
if data:
print(repr(data))
self.last_display_command = self.do_ds
def do_du(self, arg):
"""
[~thread] du <register> - show memory contents as Unicode string
[~process] du <address> - show memory contents as Unicode string
"""
if not arg:
arg = self.default_display_target
token_list = self.split_tokens(arg, 1, 2)
pid, tid, address, size = self.input_display(token_list, 256)
process = self.get_process(pid)
data = process.peek_string(address, True, size)
if data:
print(repr(data))
self.last_display_command = self.do_du
def do_register(self, arg):
"""
[~thread] r - print(the value of all registers
[~thread] r <register> - print(the value of a register
[~thread] r <register>=<value> - change the value of a register
[~thread] register - print(the value of all registers
[~thread] register <register> - print(the value of a register
[~thread] register <register>=<value> - change the value of a register
"""
arg = arg.strip()
if not arg:
self.print_current_location()
else:
equ = arg.find('=')
if equ >= 0:
register = arg[:equ].strip()
value = arg[equ + 1:].strip()
if not value:
value = '0'
self.change_register(register, value)
else:
value = self.input_register(arg)
if value is None:
raise CmdError("unknown register: %s" % arg)
try:
label = None
thread = self.get_thread_from_prefix()
process = thread.get_process()
module = process.get_module_at_address(value)
if module:
label = module.get_label_at_address(value)
except RuntimeError:
label = None
reg = arg.upper()
val = HexDump.address(value)
if label:
print("%s: %s (%s)" % (reg, val, label))
else:
print("%s: %s" % (reg, val))
do_r = do_register
def do_eb(self, arg):
"""
[~process] eb <address> <data> - write the data to the specified address
"""
# TODO
# data parameter should be optional, use a child Cmd here
pid = self.get_process_id_from_prefix()
token_list = self.split_tokens(arg, 2)
address = self.input_address(token_list[0], pid)
data = HexInput.hexadecimal(' '.join(token_list[1:]))
self.write_memory(address, data, pid)
# XXX TODO
# add ew, ed and eq here
def do_find(self, arg):
"""
[~process] f <string> - find the string in the process memory
[~process] find <string> - find the string in the process memory
"""
if not arg:
raise CmdError("missing parameter: string")
process = self.get_process_from_prefix()
self.find_in_memory(arg, process)
do_f = do_find
def do_memory(self, arg):
"""
[~process] m - show the process memory map
[~process] memory - show the process memory map
"""
if arg: # TODO: take min and max addresses
raise CmdError("too many arguments")
process = self.get_process_from_prefix()
try:
memoryMap = process.get_memory_map()
mappedFilenames = process.get_mapped_filenames()
print('')
print(CrashDump.dump_memory_map(memoryMap, mappedFilenames))
except WindowsError:
msg = "can't get memory information for process (%d)"
raise CmdError(msg % process.get_pid())
do_m = do_memory
#------------------------------------------------------------------------------
# Event handling
# TODO
# * add configurable stop/don't stop behavior on events and exceptions
# Stop for all events, unless stated otherwise.
def event(self, event):
self.print_event(event)
self.prompt_user()
# Stop for all exceptions, unless stated otherwise.
def exception(self, event):
self.print_exception(event)
self.prompt_user()
# Stop for breakpoint exceptions.
def breakpoint(self, event):
if hasattr(event, 'breakpoint') and event.breakpoint:
self.print_breakpoint_location(event)
else:
self.print_exception(event)
self.prompt_user()
# Stop for WOW64 breakpoint exceptions.
def wow64_breakpoint(self, event):
self.print_exception(event)
self.prompt_user()
# Stop for single step exceptions.
def single_step(self, event):
if event.debug.is_tracing(event.get_tid()):
self.print_breakpoint_location(event)
else:
self.print_exception(event)
self.prompt_user()
# Don't stop for C++ exceptions.
def ms_vc_exception(self, event):
self.print_exception(event)
event.continueStatus = win32.DBG_CONTINUE
# Don't stop for process start.
def create_process(self, event):
self.print_process_start(event)
self.print_thread_start(event)
self.print_module_load(event)
# Don't stop for process exit.
def exit_process(self, event):
self.print_process_end(event)
# Don't stop for thread creation.
def create_thread(self, event):
self.print_thread_start(event)
# Don't stop for thread exit.
def exit_thread(self, event):
self.print_thread_end(event)
# Don't stop for DLL load.
def load_dll(self, event):
self.print_module_load(event)
# Don't stop for DLL unload.
def unload_dll(self, event):
self.print_module_unload(event)
# Don't stop for debug strings.
def output_string(self, event):
self.print_debug_string(event)
#------------------------------------------------------------------------------
# History file
def load_history(self):
global readline
if readline is None:
try:
import readline
except ImportError:
return
if self.history_file_full_path is None:
folder = os.environ.get('USERPROFILE', '')
if not folder:
folder = os.environ.get('HOME', '')
if not folder:
folder = os.path.split(sys.argv[0])[1]
if not folder:
folder = os.path.curdir
self.history_file_full_path = os.path.join(folder,
self.history_file)
try:
if os.path.exists(self.history_file_full_path):
readline.read_history_file(self.history_file_full_path)
except IOError:
e = sys.exc_info()[1]
warnings.warn("Cannot load history file, reason: %s" % str(e))
def save_history(self):
if self.history_file_full_path is not None:
global readline
if readline is None:
try:
import readline
except ImportError:
return
try:
readline.write_history_file(self.history_file_full_path)
except IOError:
e = sys.exc_info()[1]
warnings.warn("Cannot save history file, reason: %s" % str(e))
#------------------------------------------------------------------------------
# Main loop
# Debugging loop.
def loop(self):
self.debuggerExit = False
debug = self.debug
# Stop on the initial event, if any.
if self.lastEvent is not None:
self.cmdqueue.append('r')
self.prompt_user()
# Loop until the debugger is told to quit.
while not self.debuggerExit:
try:
# If for some reason the last event wasn't continued,
# continue it here. This won't be done more than once
# for a given Event instance, though.
try:
debug.cont()
# On error, show the command prompt.
except Exception:
traceback.print_exc()
self.prompt_user()
# While debugees are attached, handle debug events.
# Some debug events may cause the command prompt to be shown.
if self.debug.get_debugee_count() > 0:
try:
# Get the next debug event.
debug.wait()
# Dispatch the debug event.
try:
debug.dispatch()
# Continue the debug event.
finally:
debug.cont()
# On error, show the command prompt.
except Exception:
traceback.print_exc()
self.prompt_user()
# While no debugees are attached, show the command prompt.
else:
self.prompt_user()
# When the user presses Ctrl-C send a debug break to all debugees.
except KeyboardInterrupt:
success = False
try:
print("*** User requested debug break")
system = debug.system
for pid in debug.get_debugee_pids():
try:
system.get_process(pid).debug_break()
success = True
except:
traceback.print_exc()
except:
traceback.print_exc()
if not success:
raise # This should never happen!
| 83,555 | Python | 36.251895 | 87 | 0.53968 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/textio.py | #!~/.wine/drive_c/Python25/python.exe
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Functions for text input, logging or text output.
@group Helpers:
HexDump,
HexInput,
HexOutput,
Color,
Table,
Logger
DebugLog
CrashDump
"""
__revision__ = "$Id$"
__all__ = [
'HexDump',
'HexInput',
'HexOutput',
'Color',
'Table',
'CrashDump',
'DebugLog',
'Logger',
]
import sys
from winappdbg import win32
from winappdbg import compat
from winappdbg.util import StaticClass
import re
import time
import struct
import traceback
#------------------------------------------------------------------------------
class HexInput (StaticClass):
"""
Static functions for user input parsing.
The counterparts for each method are in the L{HexOutput} class.
"""
@staticmethod
def integer(token):
"""
Convert numeric strings into integers.
@type token: str
@param token: String to parse.
@rtype: int
@return: Parsed integer value.
"""
token = token.strip()
neg = False
if token.startswith(compat.b('-')):
token = token[1:]
neg = True
if token.startswith(compat.b('0x')):
result = int(token, 16) # hexadecimal
elif token.startswith(compat.b('0b')):
result = int(token[2:], 2) # binary
elif token.startswith(compat.b('0o')):
result = int(token, 8) # octal
else:
try:
result = int(token) # decimal
except ValueError:
result = int(token, 16) # hexadecimal (no "0x" prefix)
if neg:
result = -result
return result
@staticmethod
def address(token):
"""
Convert numeric strings into memory addresses.
@type token: str
@param token: String to parse.
@rtype: int
@return: Parsed integer value.
"""
return int(token, 16)
@staticmethod
def hexadecimal(token):
"""
Convert a strip of hexadecimal numbers into binary data.
@type token: str
@param token: String to parse.
@rtype: str
@return: Parsed string value.
"""
token = ''.join([ c for c in token if c.isalnum() ])
if len(token) % 2 != 0:
raise ValueError("Missing characters in hex data")
data = ''
for i in compat.xrange(0, len(token), 2):
x = token[i:i+2]
d = int(x, 16)
s = struct.pack('<B', d)
data += s
return data
@staticmethod
def pattern(token):
"""
Convert an hexadecimal search pattern into a POSIX regular expression.
For example, the following pattern::
"B8 0? ?0 ?? ??"
Would match the following data::
"B8 0D F0 AD BA" # mov eax, 0xBAADF00D
@type token: str
@param token: String to parse.
@rtype: str
@return: Parsed string value.
"""
token = ''.join([ c for c in token if c == '?' or c.isalnum() ])
if len(token) % 2 != 0:
raise ValueError("Missing characters in hex data")
regexp = ''
for i in compat.xrange(0, len(token), 2):
x = token[i:i+2]
if x == '??':
regexp += '.'
elif x[0] == '?':
f = '\\x%%.1x%s' % x[1]
x = ''.join([ f % c for c in compat.xrange(0, 0x10) ])
regexp = '%s[%s]' % (regexp, x)
elif x[1] == '?':
f = '\\x%s%%.1x' % x[0]
x = ''.join([ f % c for c in compat.xrange(0, 0x10) ])
regexp = '%s[%s]' % (regexp, x)
else:
regexp = '%s\\x%s' % (regexp, x)
return regexp
@staticmethod
def is_pattern(token):
"""
Determine if the given argument is a valid hexadecimal pattern to be
used with L{pattern}.
@type token: str
@param token: String to parse.
@rtype: bool
@return:
C{True} if it's a valid hexadecimal pattern, C{False} otherwise.
"""
return re.match(r"^(?:[\?A-Fa-f0-9][\?A-Fa-f0-9]\s*)+$", token)
@classmethod
def integer_list_file(cls, filename):
"""
Read a list of integers from a file.
The file format is:
- # anywhere in the line begins a comment
- leading and trailing spaces are ignored
- empty lines are ignored
- integers can be specified as:
- decimal numbers ("100" is 100)
- hexadecimal numbers ("0x100" is 256)
- binary numbers ("0b100" is 4)
- octal numbers ("0100" is 64)
@type filename: str
@param filename: Name of the file to read.
@rtype: list( int )
@return: List of integers read from the file.
"""
count = 0
result = list()
fd = open(filename, 'r')
for line in fd:
count = count + 1
if '#' in line:
line = line[ : line.find('#') ]
line = line.strip()
if line:
try:
value = cls.integer(line)
except ValueError:
e = sys.exc_info()[1]
msg = "Error in line %d of %s: %s"
msg = msg % (count, filename, str(e))
raise ValueError(msg)
result.append(value)
return result
@classmethod
def string_list_file(cls, filename):
"""
Read a list of string values from a file.
The file format is:
- # anywhere in the line begins a comment
- leading and trailing spaces are ignored
- empty lines are ignored
- strings cannot span over a single line
@type filename: str
@param filename: Name of the file to read.
@rtype: list
@return: List of integers and strings read from the file.
"""
count = 0
result = list()
fd = open(filename, 'r')
for line in fd:
count = count + 1
if '#' in line:
line = line[ : line.find('#') ]
line = line.strip()
if line:
result.append(line)
return result
@classmethod
def mixed_list_file(cls, filename):
"""
Read a list of mixed values from a file.
The file format is:
- # anywhere in the line begins a comment
- leading and trailing spaces are ignored
- empty lines are ignored
- strings cannot span over a single line
- integers can be specified as:
- decimal numbers ("100" is 100)
- hexadecimal numbers ("0x100" is 256)
- binary numbers ("0b100" is 4)
- octal numbers ("0100" is 64)
@type filename: str
@param filename: Name of the file to read.
@rtype: list
@return: List of integers and strings read from the file.
"""
count = 0
result = list()
fd = open(filename, 'r')
for line in fd:
count = count + 1
if '#' in line:
line = line[ : line.find('#') ]
line = line.strip()
if line:
try:
value = cls.integer(line)
except ValueError:
value = line
result.append(value)
return result
#------------------------------------------------------------------------------
class HexOutput (StaticClass):
"""
Static functions for user output parsing.
The counterparts for each method are in the L{HexInput} class.
@type integer_size: int
@cvar integer_size: Default size in characters of an outputted integer.
This value is platform dependent.
@type address_size: int
@cvar address_size: Default Number of bits of the target architecture.
This value is platform dependent.
"""
integer_size = (win32.SIZEOF(win32.DWORD) * 2) + 2
address_size = (win32.SIZEOF(win32.SIZE_T) * 2) + 2
@classmethod
def integer(cls, integer, bits = None):
"""
@type integer: int
@param integer: Integer.
@type bits: int
@param bits:
(Optional) Number of bits of the target architecture.
The default is platform dependent. See: L{HexOutput.integer_size}
@rtype: str
@return: Text output.
"""
if bits is None:
integer_size = cls.integer_size
else:
integer_size = (bits / 4) + 2
if integer >= 0:
return ('0x%%.%dx' % (integer_size - 2)) % integer
return ('-0x%%.%dx' % (integer_size - 2)) % -integer
@classmethod
def address(cls, address, bits = None):
"""
@type address: int
@param address: Memory address.
@type bits: int
@param bits:
(Optional) Number of bits of the target architecture.
The default is platform dependent. See: L{HexOutput.address_size}
@rtype: str
@return: Text output.
"""
if bits is None:
address_size = cls.address_size
bits = win32.bits
else:
address_size = (bits / 4) + 2
if address < 0:
address = ((2 ** bits) - 1) ^ ~address
return ('0x%%.%dx' % (address_size - 2)) % address
@staticmethod
def hexadecimal(data):
"""
Convert binary data to a string of hexadecimal numbers.
@type data: str
@param data: Binary data.
@rtype: str
@return: Hexadecimal representation.
"""
return HexDump.hexadecimal(data, separator = '')
@classmethod
def integer_list_file(cls, filename, values, bits = None):
"""
Write a list of integers to a file.
If a file of the same name exists, it's contents are replaced.
See L{HexInput.integer_list_file} for a description of the file format.
@type filename: str
@param filename: Name of the file to write.
@type values: list( int )
@param values: List of integers to write to the file.
@type bits: int
@param bits:
(Optional) Number of bits of the target architecture.
The default is platform dependent. See: L{HexOutput.integer_size}
"""
fd = open(filename, 'w')
for integer in values:
print >> fd, cls.integer(integer, bits)
fd.close()
@classmethod
def string_list_file(cls, filename, values):
"""
Write a list of strings to a file.
If a file of the same name exists, it's contents are replaced.
See L{HexInput.string_list_file} for a description of the file format.
@type filename: str
@param filename: Name of the file to write.
@type values: list( int )
@param values: List of strings to write to the file.
"""
fd = open(filename, 'w')
for string in values:
print >> fd, string
fd.close()
@classmethod
def mixed_list_file(cls, filename, values, bits):
"""
Write a list of mixed values to a file.
If a file of the same name exists, it's contents are replaced.
See L{HexInput.mixed_list_file} for a description of the file format.
@type filename: str
@param filename: Name of the file to write.
@type values: list( int )
@param values: List of mixed values to write to the file.
@type bits: int
@param bits:
(Optional) Number of bits of the target architecture.
The default is platform dependent. See: L{HexOutput.integer_size}
"""
fd = open(filename, 'w')
for original in values:
try:
parsed = cls.integer(original, bits)
except TypeError:
parsed = repr(original)
print >> fd, parsed
fd.close()
#------------------------------------------------------------------------------
class HexDump (StaticClass):
"""
Static functions for hexadecimal dumps.
@type integer_size: int
@cvar integer_size: Size in characters of an outputted integer.
This value is platform dependent.
@type address_size: int
@cvar address_size: Size in characters of an outputted address.
This value is platform dependent.
"""
integer_size = (win32.SIZEOF(win32.DWORD) * 2)
address_size = (win32.SIZEOF(win32.SIZE_T) * 2)
@classmethod
def integer(cls, integer, bits = None):
"""
@type integer: int
@param integer: Integer.
@type bits: int
@param bits:
(Optional) Number of bits of the target architecture.
The default is platform dependent. See: L{HexDump.integer_size}
@rtype: str
@return: Text output.
"""
if bits is None:
integer_size = cls.integer_size
else:
integer_size = bits / 4
return ('%%.%dX' % integer_size) % integer
@classmethod
def address(cls, address, bits = None):
"""
@type address: int
@param address: Memory address.
@type bits: int
@param bits:
(Optional) Number of bits of the target architecture.
The default is platform dependent. See: L{HexDump.address_size}
@rtype: str
@return: Text output.
"""
if bits is None:
address_size = cls.address_size
bits = win32.bits
else:
address_size = bits / 4
if address < 0:
address = ((2 ** bits) - 1) ^ ~address
return ('%%.%dX' % address_size) % address
@staticmethod
def printable(data):
"""
Replace unprintable characters with dots.
@type data: str
@param data: Binary data.
@rtype: str
@return: Printable text.
"""
result = ''
for c in data:
if 32 < ord(c) < 128:
result += c
else:
result += '.'
return result
@staticmethod
def hexadecimal(data, separator = ''):
"""
Convert binary data to a string of hexadecimal numbers.
@type data: str
@param data: Binary data.
@type separator: str
@param separator:
Separator between the hexadecimal representation of each character.
@rtype: str
@return: Hexadecimal representation.
"""
return separator.join( [ '%.2x' % ord(c) for c in data ] )
@staticmethod
def hexa_word(data, separator = ' '):
"""
Convert binary data to a string of hexadecimal WORDs.
@type data: str
@param data: Binary data.
@type separator: str
@param separator:
Separator between the hexadecimal representation of each WORD.
@rtype: str
@return: Hexadecimal representation.
"""
if len(data) & 1 != 0:
data += '\0'
return separator.join( [ '%.4x' % struct.unpack('<H', data[i:i+2])[0] \
for i in compat.xrange(0, len(data), 2) ] )
@staticmethod
def hexa_dword(data, separator = ' '):
"""
Convert binary data to a string of hexadecimal DWORDs.
@type data: str
@param data: Binary data.
@type separator: str
@param separator:
Separator between the hexadecimal representation of each DWORD.
@rtype: str
@return: Hexadecimal representation.
"""
if len(data) & 3 != 0:
data += '\0' * (4 - (len(data) & 3))
return separator.join( [ '%.8x' % struct.unpack('<L', data[i:i+4])[0] \
for i in compat.xrange(0, len(data), 4) ] )
@staticmethod
def hexa_qword(data, separator = ' '):
"""
Convert binary data to a string of hexadecimal QWORDs.
@type data: str
@param data: Binary data.
@type separator: str
@param separator:
Separator between the hexadecimal representation of each QWORD.
@rtype: str
@return: Hexadecimal representation.
"""
if len(data) & 7 != 0:
data += '\0' * (8 - (len(data) & 7))
return separator.join( [ '%.16x' % struct.unpack('<Q', data[i:i+8])[0]\
for i in compat.xrange(0, len(data), 8) ] )
@classmethod
def hexline(cls, data, separator = ' ', width = None):
"""
Dump a line of hexadecimal numbers from binary data.
@type data: str
@param data: Binary data.
@type separator: str
@param separator:
Separator between the hexadecimal representation of each character.
@type width: int
@param width:
(Optional) Maximum number of characters to convert per text line.
This value is also used for padding.
@rtype: str
@return: Multiline output text.
"""
if width is None:
fmt = '%s %s'
else:
fmt = '%%-%ds %%-%ds' % ((len(separator)+2)*width-1, width)
return fmt % (cls.hexadecimal(data, separator), cls.printable(data))
@classmethod
def hexblock(cls, data, address = None,
bits = None,
separator = ' ',
width = 8):
"""
Dump a block of hexadecimal numbers from binary data.
Also show a printable text version of the data.
@type data: str
@param data: Binary data.
@type address: str
@param address: Memory address where the data was read from.
@type bits: int
@param bits:
(Optional) Number of bits of the target architecture.
The default is platform dependent. See: L{HexDump.address_size}
@type separator: str
@param separator:
Separator between the hexadecimal representation of each character.
@type width: int
@param width:
(Optional) Maximum number of characters to convert per text line.
@rtype: str
@return: Multiline output text.
"""
return cls.hexblock_cb(cls.hexline, data, address, bits, width,
cb_kwargs = {'width' : width, 'separator' : separator})
@classmethod
def hexblock_cb(cls, callback, data, address = None,
bits = None,
width = 16,
cb_args = (),
cb_kwargs = {}):
"""
Dump a block of binary data using a callback function to convert each
line of text.
@type callback: function
@param callback: Callback function to convert each line of data.
@type data: str
@param data: Binary data.
@type address: str
@param address:
(Optional) Memory address where the data was read from.
@type bits: int
@param bits:
(Optional) Number of bits of the target architecture.
The default is platform dependent. See: L{HexDump.address_size}
@type cb_args: str
@param cb_args:
(Optional) Arguments to pass to the callback function.
@type cb_kwargs: str
@param cb_kwargs:
(Optional) Keyword arguments to pass to the callback function.
@type width: int
@param width:
(Optional) Maximum number of bytes to convert per text line.
@rtype: str
@return: Multiline output text.
"""
result = ''
if address is None:
for i in compat.xrange(0, len(data), width):
result = '%s%s\n' % ( result, \
callback(data[i:i+width], *cb_args, **cb_kwargs) )
else:
for i in compat.xrange(0, len(data), width):
result = '%s%s: %s\n' % (
result,
cls.address(address, bits),
callback(data[i:i+width], *cb_args, **cb_kwargs)
)
address += width
return result
@classmethod
def hexblock_byte(cls, data, address = None,
bits = None,
separator = ' ',
width = 16):
"""
Dump a block of hexadecimal BYTEs from binary data.
@type data: str
@param data: Binary data.
@type address: str
@param address: Memory address where the data was read from.
@type bits: int
@param bits:
(Optional) Number of bits of the target architecture.
The default is platform dependent. See: L{HexDump.address_size}
@type separator: str
@param separator:
Separator between the hexadecimal representation of each BYTE.
@type width: int
@param width:
(Optional) Maximum number of BYTEs to convert per text line.
@rtype: str
@return: Multiline output text.
"""
return cls.hexblock_cb(cls.hexadecimal, data,
address, bits, width,
cb_kwargs = {'separator': separator})
@classmethod
def hexblock_word(cls, data, address = None,
bits = None,
separator = ' ',
width = 8):
"""
Dump a block of hexadecimal WORDs from binary data.
@type data: str
@param data: Binary data.
@type address: str
@param address: Memory address where the data was read from.
@type bits: int
@param bits:
(Optional) Number of bits of the target architecture.
The default is platform dependent. See: L{HexDump.address_size}
@type separator: str
@param separator:
Separator between the hexadecimal representation of each WORD.
@type width: int
@param width:
(Optional) Maximum number of WORDs to convert per text line.
@rtype: str
@return: Multiline output text.
"""
return cls.hexblock_cb(cls.hexa_word, data,
address, bits, width * 2,
cb_kwargs = {'separator': separator})
@classmethod
def hexblock_dword(cls, data, address = None,
bits = None,
separator = ' ',
width = 4):
"""
Dump a block of hexadecimal DWORDs from binary data.
@type data: str
@param data: Binary data.
@type address: str
@param address: Memory address where the data was read from.
@type bits: int
@param bits:
(Optional) Number of bits of the target architecture.
The default is platform dependent. See: L{HexDump.address_size}
@type separator: str
@param separator:
Separator between the hexadecimal representation of each DWORD.
@type width: int
@param width:
(Optional) Maximum number of DWORDs to convert per text line.
@rtype: str
@return: Multiline output text.
"""
return cls.hexblock_cb(cls.hexa_dword, data,
address, bits, width * 4,
cb_kwargs = {'separator': separator})
@classmethod
def hexblock_qword(cls, data, address = None,
bits = None,
separator = ' ',
width = 2):
"""
Dump a block of hexadecimal QWORDs from binary data.
@type data: str
@param data: Binary data.
@type address: str
@param address: Memory address where the data was read from.
@type bits: int
@param bits:
(Optional) Number of bits of the target architecture.
The default is platform dependent. See: L{HexDump.address_size}
@type separator: str
@param separator:
Separator between the hexadecimal representation of each QWORD.
@type width: int
@param width:
(Optional) Maximum number of QWORDs to convert per text line.
@rtype: str
@return: Multiline output text.
"""
return cls.hexblock_cb(cls.hexa_qword, data,
address, bits, width * 8,
cb_kwargs = {'separator': separator})
#------------------------------------------------------------------------------
# TODO: implement an ANSI parser to simplify using colors
class Color (object):
"""
Colored console output.
"""
@staticmethod
def _get_text_attributes():
return win32.GetConsoleScreenBufferInfo().wAttributes
@staticmethod
def _set_text_attributes(wAttributes):
win32.SetConsoleTextAttribute(wAttributes = wAttributes)
#--------------------------------------------------------------------------
@classmethod
def can_use_colors(cls):
"""
Determine if we can use colors.
Colored output only works when the output is a real console, and fails
when redirected to a file or pipe. Call this method before issuing a
call to any other method of this class to make sure it's actually
possible to use colors.
@rtype: bool
@return: C{True} if it's possible to output text with color,
C{False} otherwise.
"""
try:
cls._get_text_attributes()
return True
except Exception:
return False
@classmethod
def reset(cls):
"Reset the colors to the default values."
cls._set_text_attributes(win32.FOREGROUND_GREY)
#--------------------------------------------------------------------------
#@classmethod
#def underscore(cls, on = True):
# wAttributes = cls._get_text_attributes()
# if on:
# wAttributes |= win32.COMMON_LVB_UNDERSCORE
# else:
# wAttributes &= ~win32.COMMON_LVB_UNDERSCORE
# cls._set_text_attributes(wAttributes)
#--------------------------------------------------------------------------
@classmethod
def default(cls):
"Make the current foreground color the default."
wAttributes = cls._get_text_attributes()
wAttributes &= ~win32.FOREGROUND_MASK
wAttributes |= win32.FOREGROUND_GREY
wAttributes &= ~win32.FOREGROUND_INTENSITY
cls._set_text_attributes(wAttributes)
@classmethod
def light(cls):
"Make the current foreground color light."
wAttributes = cls._get_text_attributes()
wAttributes |= win32.FOREGROUND_INTENSITY
cls._set_text_attributes(wAttributes)
@classmethod
def dark(cls):
"Make the current foreground color dark."
wAttributes = cls._get_text_attributes()
wAttributes &= ~win32.FOREGROUND_INTENSITY
cls._set_text_attributes(wAttributes)
@classmethod
def black(cls):
"Make the text foreground color black."
wAttributes = cls._get_text_attributes()
wAttributes &= ~win32.FOREGROUND_MASK
#wAttributes |= win32.FOREGROUND_BLACK
cls._set_text_attributes(wAttributes)
@classmethod
def white(cls):
"Make the text foreground color white."
wAttributes = cls._get_text_attributes()
wAttributes &= ~win32.FOREGROUND_MASK
wAttributes |= win32.FOREGROUND_GREY
cls._set_text_attributes(wAttributes)
@classmethod
def red(cls):
"Make the text foreground color red."
wAttributes = cls._get_text_attributes()
wAttributes &= ~win32.FOREGROUND_MASK
wAttributes |= win32.FOREGROUND_RED
cls._set_text_attributes(wAttributes)
@classmethod
def green(cls):
"Make the text foreground color green."
wAttributes = cls._get_text_attributes()
wAttributes &= ~win32.FOREGROUND_MASK
wAttributes |= win32.FOREGROUND_GREEN
cls._set_text_attributes(wAttributes)
@classmethod
def blue(cls):
"Make the text foreground color blue."
wAttributes = cls._get_text_attributes()
wAttributes &= ~win32.FOREGROUND_MASK
wAttributes |= win32.FOREGROUND_BLUE
cls._set_text_attributes(wAttributes)
@classmethod
def cyan(cls):
"Make the text foreground color cyan."
wAttributes = cls._get_text_attributes()
wAttributes &= ~win32.FOREGROUND_MASK
wAttributes |= win32.FOREGROUND_CYAN
cls._set_text_attributes(wAttributes)
@classmethod
def magenta(cls):
"Make the text foreground color magenta."
wAttributes = cls._get_text_attributes()
wAttributes &= ~win32.FOREGROUND_MASK
wAttributes |= win32.FOREGROUND_MAGENTA
cls._set_text_attributes(wAttributes)
@classmethod
def yellow(cls):
"Make the text foreground color yellow."
wAttributes = cls._get_text_attributes()
wAttributes &= ~win32.FOREGROUND_MASK
wAttributes |= win32.FOREGROUND_YELLOW
cls._set_text_attributes(wAttributes)
#--------------------------------------------------------------------------
@classmethod
def bk_default(cls):
"Make the current background color the default."
wAttributes = cls._get_text_attributes()
wAttributes &= ~win32.BACKGROUND_MASK
#wAttributes |= win32.BACKGROUND_BLACK
wAttributes &= ~win32.BACKGROUND_INTENSITY
cls._set_text_attributes(wAttributes)
@classmethod
def bk_light(cls):
"Make the current background color light."
wAttributes = cls._get_text_attributes()
wAttributes |= win32.BACKGROUND_INTENSITY
cls._set_text_attributes(wAttributes)
@classmethod
def bk_dark(cls):
"Make the current background color dark."
wAttributes = cls._get_text_attributes()
wAttributes &= ~win32.BACKGROUND_INTENSITY
cls._set_text_attributes(wAttributes)
@classmethod
def bk_black(cls):
"Make the text background color black."
wAttributes = cls._get_text_attributes()
wAttributes &= ~win32.BACKGROUND_MASK
#wAttributes |= win32.BACKGROUND_BLACK
cls._set_text_attributes(wAttributes)
@classmethod
def bk_white(cls):
"Make the text background color white."
wAttributes = cls._get_text_attributes()
wAttributes &= ~win32.BACKGROUND_MASK
wAttributes |= win32.BACKGROUND_GREY
cls._set_text_attributes(wAttributes)
@classmethod
def bk_red(cls):
"Make the text background color red."
wAttributes = cls._get_text_attributes()
wAttributes &= ~win32.BACKGROUND_MASK
wAttributes |= win32.BACKGROUND_RED
cls._set_text_attributes(wAttributes)
@classmethod
def bk_green(cls):
"Make the text background color green."
wAttributes = cls._get_text_attributes()
wAttributes &= ~win32.BACKGROUND_MASK
wAttributes |= win32.BACKGROUND_GREEN
cls._set_text_attributes(wAttributes)
@classmethod
def bk_blue(cls):
"Make the text background color blue."
wAttributes = cls._get_text_attributes()
wAttributes &= ~win32.BACKGROUND_MASK
wAttributes |= win32.BACKGROUND_BLUE
cls._set_text_attributes(wAttributes)
@classmethod
def bk_cyan(cls):
"Make the text background color cyan."
wAttributes = cls._get_text_attributes()
wAttributes &= ~win32.BACKGROUND_MASK
wAttributes |= win32.BACKGROUND_CYAN
cls._set_text_attributes(wAttributes)
@classmethod
def bk_magenta(cls):
"Make the text background color magenta."
wAttributes = cls._get_text_attributes()
wAttributes &= ~win32.BACKGROUND_MASK
wAttributes |= win32.BACKGROUND_MAGENTA
cls._set_text_attributes(wAttributes)
@classmethod
def bk_yellow(cls):
"Make the text background color yellow."
wAttributes = cls._get_text_attributes()
wAttributes &= ~win32.BACKGROUND_MASK
wAttributes |= win32.BACKGROUND_YELLOW
cls._set_text_attributes(wAttributes)
#------------------------------------------------------------------------------
# TODO: another class for ASCII boxes
class Table (object):
"""
Text based table. The number of columns and the width of each column
is automatically calculated.
"""
def __init__(self, sep = ' '):
"""
@type sep: str
@param sep: Separator between cells in each row.
"""
self.__cols = list()
self.__width = list()
self.__sep = sep
def addRow(self, *row):
"""
Add a row to the table. All items are converted to strings.
@type row: tuple
@keyword row: Each argument is a cell in the table.
"""
row = [ str(item) for item in row ]
len_row = [ len(item) for item in row ]
width = self.__width
len_old = len(width)
len_new = len(row)
known = min(len_old, len_new)
missing = len_new - len_old
if missing > 0:
width.extend( len_row[ -missing : ] )
elif missing < 0:
len_row.extend( [0] * (-missing) )
self.__width = [ max( width[i], len_row[i] ) for i in compat.xrange(len(len_row)) ]
self.__cols.append(row)
def justify(self, column, direction):
"""
Make the text in a column left or right justified.
@type column: int
@param column: Index of the column.
@type direction: int
@param direction:
C{-1} to justify left,
C{1} to justify right.
@raise IndexError: Bad column index.
@raise ValueError: Bad direction value.
"""
if direction == -1:
self.__width[column] = abs(self.__width[column])
elif direction == 1:
self.__width[column] = - abs(self.__width[column])
else:
raise ValueError("Bad direction value.")
def getWidth(self):
"""
Get the width of the text output for the table.
@rtype: int
@return: Width in characters for the text output,
including the newline character.
"""
width = 0
if self.__width:
width = sum( abs(x) for x in self.__width )
width = width + len(self.__width) * len(self.__sep) + 1
return width
def getOutput(self):
"""
Get the text output for the table.
@rtype: str
@return: Text output.
"""
return '%s\n' % '\n'.join( self.yieldOutput() )
def yieldOutput(self):
"""
Generate the text output for the table.
@rtype: generator of str
@return: Text output.
"""
width = self.__width
if width:
num_cols = len(width)
fmt = ['%%%ds' % -w for w in width]
if width[-1] > 0:
fmt[-1] = '%s'
fmt = self.__sep.join(fmt)
for row in self.__cols:
row.extend( [''] * (num_cols - len(row)) )
yield fmt % tuple(row)
def show(self):
"""
Print the text output for the table.
"""
print(self.getOutput())
#------------------------------------------------------------------------------
class CrashDump (StaticClass):
"""
Static functions for crash dumps.
@type reg_template: str
@cvar reg_template: Template for the L{dump_registers} method.
"""
# Templates for the dump_registers method.
reg_template = {
win32.ARCH_I386 : (
'eax=%(Eax).8x ebx=%(Ebx).8x ecx=%(Ecx).8x edx=%(Edx).8x esi=%(Esi).8x edi=%(Edi).8x\n'
'eip=%(Eip).8x esp=%(Esp).8x ebp=%(Ebp).8x %(efl_dump)s\n'
'cs=%(SegCs).4x ss=%(SegSs).4x ds=%(SegDs).4x es=%(SegEs).4x fs=%(SegFs).4x gs=%(SegGs).4x efl=%(EFlags).8x\n'
),
win32.ARCH_AMD64 : (
'rax=%(Rax).16x rbx=%(Rbx).16x rcx=%(Rcx).16x\n'
'rdx=%(Rdx).16x rsi=%(Rsi).16x rdi=%(Rdi).16x\n'
'rip=%(Rip).16x rsp=%(Rsp).16x rbp=%(Rbp).16x\n'
' r8=%(R8).16x r9=%(R9).16x r10=%(R10).16x\n'
'r11=%(R11).16x r12=%(R12).16x r13=%(R13).16x\n'
'r14=%(R14).16x r15=%(R15).16x\n'
'%(efl_dump)s\n'
'cs=%(SegCs).4x ss=%(SegSs).4x ds=%(SegDs).4x es=%(SegEs).4x fs=%(SegFs).4x gs=%(SegGs).4x efl=%(EFlags).8x\n'
),
}
@staticmethod
def dump_flags(efl):
"""
Dump the x86 processor flags.
The output mimics that of the WinDBG debugger.
Used by L{dump_registers}.
@type efl: int
@param efl: Value of the eFlags register.
@rtype: str
@return: Text suitable for logging.
"""
if efl is None:
return ''
efl_dump = 'iopl=%1d' % ((efl & 0x3000) >> 12)
if efl & 0x100000:
efl_dump += ' vip'
else:
efl_dump += ' '
if efl & 0x80000:
efl_dump += ' vif'
else:
efl_dump += ' '
# 0x20000 ???
if efl & 0x800:
efl_dump += ' ov' # Overflow
else:
efl_dump += ' no' # No overflow
if efl & 0x400:
efl_dump += ' dn' # Downwards
else:
efl_dump += ' up' # Upwards
if efl & 0x200:
efl_dump += ' ei' # Enable interrupts
else:
efl_dump += ' di' # Disable interrupts
# 0x100 trap flag
if efl & 0x80:
efl_dump += ' ng' # Negative
else:
efl_dump += ' pl' # Positive
if efl & 0x40:
efl_dump += ' zr' # Zero
else:
efl_dump += ' nz' # Nonzero
if efl & 0x10:
efl_dump += ' ac' # Auxiliary carry
else:
efl_dump += ' na' # No auxiliary carry
# 0x8 ???
if efl & 0x4:
efl_dump += ' pe' # Parity odd
else:
efl_dump += ' po' # Parity even
# 0x2 ???
if efl & 0x1:
efl_dump += ' cy' # Carry
else:
efl_dump += ' nc' # No carry
return efl_dump
@classmethod
def dump_registers(cls, registers, arch = None):
"""
Dump the x86/x64 processor register values.
The output mimics that of the WinDBG debugger.
@type registers: dict( str S{->} int )
@param registers: Dictionary mapping register names to their values.
@type arch: str
@param arch: Architecture of the machine whose registers were dumped.
Defaults to the current architecture.
Currently only the following architectures are supported:
- L{win32.ARCH_I386}
- L{win32.ARCH_AMD64}
@rtype: str
@return: Text suitable for logging.
"""
if registers is None:
return ''
if arch is None:
if 'Eax' in registers:
arch = win32.ARCH_I386
elif 'Rax' in registers:
arch = win32.ARCH_AMD64
else:
arch = 'Unknown'
if arch not in cls.reg_template:
msg = "Don't know how to dump the registers for architecture: %s"
raise NotImplementedError(msg % arch)
registers = registers.copy()
registers['efl_dump'] = cls.dump_flags( registers['EFlags'] )
return cls.reg_template[arch] % registers
@staticmethod
def dump_registers_peek(registers, data, separator = ' ', width = 16):
"""
Dump data pointed to by the given registers, if any.
@type registers: dict( str S{->} int )
@param registers: Dictionary mapping register names to their values.
This value is returned by L{Thread.get_context}.
@type data: dict( str S{->} str )
@param data: Dictionary mapping register names to the data they point to.
This value is returned by L{Thread.peek_pointers_in_registers}.
@rtype: str
@return: Text suitable for logging.
"""
if None in (registers, data):
return ''
names = compat.keys(data)
names.sort()
result = ''
for reg_name in names:
tag = reg_name.lower()
dumped = HexDump.hexline(data[reg_name], separator, width)
result += '%s -> %s\n' % (tag, dumped)
return result
@staticmethod
def dump_data_peek(data, base = 0,
separator = ' ',
width = 16,
bits = None):
"""
Dump data from pointers guessed within the given binary data.
@type data: str
@param data: Dictionary mapping offsets to the data they point to.
@type base: int
@param base: Base offset.
@type bits: int
@param bits:
(Optional) Number of bits of the target architecture.
The default is platform dependent. See: L{HexDump.address_size}
@rtype: str
@return: Text suitable for logging.
"""
if data is None:
return ''
pointers = compat.keys(data)
pointers.sort()
result = ''
for offset in pointers:
dumped = HexDump.hexline(data[offset], separator, width)
address = HexDump.address(base + offset, bits)
result += '%s -> %s\n' % (address, dumped)
return result
@staticmethod
def dump_stack_peek(data, separator = ' ', width = 16, arch = None):
"""
Dump data from pointers guessed within the given stack dump.
@type data: str
@param data: Dictionary mapping stack offsets to the data they point to.
@type separator: str
@param separator:
Separator between the hexadecimal representation of each character.
@type width: int
@param width:
(Optional) Maximum number of characters to convert per text line.
This value is also used for padding.
@type arch: str
@param arch: Architecture of the machine whose registers were dumped.
Defaults to the current architecture.
@rtype: str
@return: Text suitable for logging.
"""
if data is None:
return ''
if arch is None:
arch = win32.arch
pointers = compat.keys(data)
pointers.sort()
result = ''
if pointers:
if arch == win32.ARCH_I386:
spreg = 'esp'
elif arch == win32.ARCH_AMD64:
spreg = 'rsp'
else:
spreg = 'STACK' # just a generic tag
tag_fmt = '[%s+0x%%.%dx]' % (spreg, len( '%x' % pointers[-1] ) )
for offset in pointers:
dumped = HexDump.hexline(data[offset], separator, width)
tag = tag_fmt % offset
result += '%s -> %s\n' % (tag, dumped)
return result
@staticmethod
def dump_stack_trace(stack_trace, bits = None):
"""
Dump a stack trace, as returned by L{Thread.get_stack_trace} with the
C{bUseLabels} parameter set to C{False}.
@type stack_trace: list( int, int, str )
@param stack_trace: Stack trace as a list of tuples of
( return address, frame pointer, module filename )
@type bits: int
@param bits:
(Optional) Number of bits of the target architecture.
The default is platform dependent. See: L{HexDump.address_size}
@rtype: str
@return: Text suitable for logging.
"""
if not stack_trace:
return ''
table = Table()
table.addRow('Frame', 'Origin', 'Module')
for (fp, ra, mod) in stack_trace:
fp_d = HexDump.address(fp, bits)
ra_d = HexDump.address(ra, bits)
table.addRow(fp_d, ra_d, mod)
return table.getOutput()
@staticmethod
def dump_stack_trace_with_labels(stack_trace, bits = None):
"""
Dump a stack trace,
as returned by L{Thread.get_stack_trace_with_labels}.
@type stack_trace: list( int, int, str )
@param stack_trace: Stack trace as a list of tuples of
( return address, frame pointer, module filename )
@type bits: int
@param bits:
(Optional) Number of bits of the target architecture.
The default is platform dependent. See: L{HexDump.address_size}
@rtype: str
@return: Text suitable for logging.
"""
if not stack_trace:
return ''
table = Table()
table.addRow('Frame', 'Origin')
for (fp, label) in stack_trace:
table.addRow( HexDump.address(fp, bits), label )
return table.getOutput()
# TODO
# + Instead of a star when EIP points to, it would be better to show
# any register value (or other values like the exception address) that
# points to a location in the dissassembled code.
# + It'd be very useful to show some labels here.
# + It'd be very useful to show register contents for code at EIP
@staticmethod
def dump_code(disassembly, pc = None,
bLowercase = True,
bits = None):
"""
Dump a disassembly. Optionally mark where the program counter is.
@type disassembly: list of tuple( int, int, str, str )
@param disassembly: Disassembly dump as returned by
L{Process.disassemble} or L{Thread.disassemble_around_pc}.
@type pc: int
@param pc: (Optional) Program counter.
@type bLowercase: bool
@param bLowercase: (Optional) If C{True} convert the code to lowercase.
@type bits: int
@param bits:
(Optional) Number of bits of the target architecture.
The default is platform dependent. See: L{HexDump.address_size}
@rtype: str
@return: Text suitable for logging.
"""
if not disassembly:
return ''
table = Table(sep = ' | ')
for (addr, size, code, dump) in disassembly:
if bLowercase:
code = code.lower()
if addr == pc:
addr = ' * %s' % HexDump.address(addr, bits)
else:
addr = ' %s' % HexDump.address(addr, bits)
table.addRow(addr, dump, code)
table.justify(1, 1)
return table.getOutput()
@staticmethod
def dump_code_line(disassembly_line, bShowAddress = True,
bShowDump = True,
bLowercase = True,
dwDumpWidth = None,
dwCodeWidth = None,
bits = None):
"""
Dump a single line of code. To dump a block of code use L{dump_code}.
@type disassembly_line: tuple( int, int, str, str )
@param disassembly_line: Single item of the list returned by
L{Process.disassemble} or L{Thread.disassemble_around_pc}.
@type bShowAddress: bool
@param bShowAddress: (Optional) If C{True} show the memory address.
@type bShowDump: bool
@param bShowDump: (Optional) If C{True} show the hexadecimal dump.
@type bLowercase: bool
@param bLowercase: (Optional) If C{True} convert the code to lowercase.
@type dwDumpWidth: int or None
@param dwDumpWidth: (Optional) Width in characters of the hex dump.
@type dwCodeWidth: int or None
@param dwCodeWidth: (Optional) Width in characters of the code.
@type bits: int
@param bits:
(Optional) Number of bits of the target architecture.
The default is platform dependent. See: L{HexDump.address_size}
@rtype: str
@return: Text suitable for logging.
"""
if bits is None:
address_size = HexDump.address_size
else:
address_size = bits / 4
(addr, size, code, dump) = disassembly_line
dump = dump.replace(' ', '')
result = list()
fmt = ''
if bShowAddress:
result.append( HexDump.address(addr, bits) )
fmt += '%%%ds:' % address_size
if bShowDump:
result.append(dump)
if dwDumpWidth:
fmt += ' %%-%ds' % dwDumpWidth
else:
fmt += ' %s'
if bLowercase:
code = code.lower()
result.append(code)
if dwCodeWidth:
fmt += ' %%-%ds' % dwCodeWidth
else:
fmt += ' %s'
return fmt % tuple(result)
@staticmethod
def dump_memory_map(memoryMap, mappedFilenames = None, bits = None):
"""
Dump the memory map of a process. Optionally show the filenames for
memory mapped files as well.
@type memoryMap: list( L{win32.MemoryBasicInformation} )
@param memoryMap: Memory map returned by L{Process.get_memory_map}.
@type mappedFilenames: dict( int S{->} str )
@param mappedFilenames: (Optional) Memory mapped filenames
returned by L{Process.get_mapped_filenames}.
@type bits: int
@param bits:
(Optional) Number of bits of the target architecture.
The default is platform dependent. See: L{HexDump.address_size}
@rtype: str
@return: Text suitable for logging.
"""
if not memoryMap:
return ''
table = Table()
if mappedFilenames:
table.addRow("Address", "Size", "State", "Access", "Type", "File")
else:
table.addRow("Address", "Size", "State", "Access", "Type")
# For each memory block in the map...
for mbi in memoryMap:
# Address and size of memory block.
BaseAddress = HexDump.address(mbi.BaseAddress, bits)
RegionSize = HexDump.address(mbi.RegionSize, bits)
# State (free or allocated).
mbiState = mbi.State
if mbiState == win32.MEM_RESERVE:
State = "Reserved"
elif mbiState == win32.MEM_COMMIT:
State = "Commited"
elif mbiState == win32.MEM_FREE:
State = "Free"
else:
State = "Unknown"
# Page protection bits (R/W/X/G).
if mbiState != win32.MEM_COMMIT:
Protect = ""
else:
mbiProtect = mbi.Protect
if mbiProtect & win32.PAGE_NOACCESS:
Protect = "--- "
elif mbiProtect & win32.PAGE_READONLY:
Protect = "R-- "
elif mbiProtect & win32.PAGE_READWRITE:
Protect = "RW- "
elif mbiProtect & win32.PAGE_WRITECOPY:
Protect = "RC- "
elif mbiProtect & win32.PAGE_EXECUTE:
Protect = "--X "
elif mbiProtect & win32.PAGE_EXECUTE_READ:
Protect = "R-X "
elif mbiProtect & win32.PAGE_EXECUTE_READWRITE:
Protect = "RWX "
elif mbiProtect & win32.PAGE_EXECUTE_WRITECOPY:
Protect = "RCX "
else:
Protect = "??? "
if mbiProtect & win32.PAGE_GUARD:
Protect += "G"
else:
Protect += "-"
if mbiProtect & win32.PAGE_NOCACHE:
Protect += "N"
else:
Protect += "-"
if mbiProtect & win32.PAGE_WRITECOMBINE:
Protect += "W"
else:
Protect += "-"
# Type (file mapping, executable image, or private memory).
mbiType = mbi.Type
if mbiType == win32.MEM_IMAGE:
Type = "Image"
elif mbiType == win32.MEM_MAPPED:
Type = "Mapped"
elif mbiType == win32.MEM_PRIVATE:
Type = "Private"
elif mbiType == 0:
Type = ""
else:
Type = "Unknown"
# Output a row in the table.
if mappedFilenames:
FileName = mappedFilenames.get(mbi.BaseAddress, '')
table.addRow( BaseAddress, RegionSize, State, Protect, Type, FileName )
else:
table.addRow( BaseAddress, RegionSize, State, Protect, Type )
# Return the table output.
return table.getOutput()
#------------------------------------------------------------------------------
class DebugLog (StaticClass):
'Static functions for debug logging.'
@staticmethod
def log_text(text):
"""
Log lines of text, inserting a timestamp.
@type text: str
@param text: Text to log.
@rtype: str
@return: Log line.
"""
if text.endswith('\n'):
text = text[:-len('\n')]
#text = text.replace('\n', '\n\t\t') # text CSV
ltime = time.strftime("%X")
msecs = (time.time() % 1) * 1000
return '[%s.%04d] %s' % (ltime, msecs, text)
#return '[%s.%04d]\t%s' % (ltime, msecs, text) # text CSV
@classmethod
def log_event(cls, event, text = None):
"""
Log lines of text associated with a debug event.
@type event: L{Event}
@param event: Event object.
@type text: str
@param text: (Optional) Text to log. If no text is provided the default
is to show a description of the event itself.
@rtype: str
@return: Log line.
"""
if not text:
if event.get_event_code() == win32.EXCEPTION_DEBUG_EVENT:
what = event.get_exception_description()
if event.is_first_chance():
what = '%s (first chance)' % what
else:
what = '%s (second chance)' % what
try:
address = event.get_fault_address()
except NotImplementedError:
address = event.get_exception_address()
else:
what = event.get_event_name()
address = event.get_thread().get_pc()
process = event.get_process()
label = process.get_label_at_address(address)
address = HexDump.address(address, process.get_bits())
if label:
where = '%s (%s)' % (address, label)
else:
where = address
text = '%s at %s' % (what, where)
text = 'pid %d tid %d: %s' % (event.get_pid(), event.get_tid(), text)
#text = 'pid %d tid %d:\t%s' % (event.get_pid(), event.get_tid(), text) # text CSV
return cls.log_text(text)
#------------------------------------------------------------------------------
class Logger(object):
"""
Logs text to standard output and/or a text file.
@type logfile: str or None
@ivar logfile: Append messages to this text file.
@type verbose: bool
@ivar verbose: C{True} to print messages to standard output.
@type fd: file
@ivar fd: File object where log messages are printed to.
C{None} if no log file is used.
"""
def __init__(self, logfile = None, verbose = True):
"""
@type logfile: str or None
@param logfile: Append messages to this text file.
@type verbose: bool
@param verbose: C{True} to print messages to standard output.
"""
self.verbose = verbose
self.logfile = logfile
if self.logfile:
self.fd = open(self.logfile, 'a+')
def __logfile_error(self, e):
"""
Shows an error message to standard error
if the log file can't be written to.
Used internally.
@type e: Exception
@param e: Exception raised when trying to write to the log file.
"""
from sys import stderr
msg = "Warning, error writing log file %s: %s\n"
msg = msg % (self.logfile, str(e))
stderr.write(DebugLog.log_text(msg))
self.logfile = None
self.fd = None
def __do_log(self, text):
"""
Writes the given text verbatim into the log file (if any)
and/or standard input (if the verbose flag is turned on).
Used internally.
@type text: str
@param text: Text to print.
"""
if isinstance(text, compat.unicode):
text = text.encode('cp1252')
if self.verbose:
print(text)
if self.logfile:
try:
self.fd.writelines('%s\n' % text)
except IOError:
e = sys.exc_info()[1]
self.__logfile_error(e)
def log_text(self, text):
"""
Log lines of text, inserting a timestamp.
@type text: str
@param text: Text to log.
"""
self.__do_log( DebugLog.log_text(text) )
def log_event(self, event, text = None):
"""
Log lines of text associated with a debug event.
@type event: L{Event}
@param event: Event object.
@type text: str
@param text: (Optional) Text to log. If no text is provided the default
is to show a description of the event itself.
"""
self.__do_log( DebugLog.log_event(event, text) )
def log_exc(self):
"""
Log lines of text associated with the last Python exception.
"""
self.__do_log( 'Exception raised: %s' % traceback.format_exc() )
def is_enabled(self):
"""
Determines if the logger will actually print anything when the log_*
methods are called.
This may save some processing if the log text requires a lengthy
calculation to prepare. If no log file is set and stdout logging
is disabled, there's no point in preparing a log text that won't
be shown to anyone.
@rtype: bool
@return: C{True} if a log file was set and/or standard output logging
is enabled, or C{False} otherwise.
"""
return self.verbose or self.logfile
| 62,691 | Python | 32.346808 | 139 | 0.520665 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/crash.py | #!~/.wine/drive_c/Python25/python.exe
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Crash dump support.
@group Crash reporting:
Crash, CrashDictionary
@group Warnings:
CrashWarning
@group Deprecated classes:
CrashContainer, CrashTable, CrashTableMSSQL,
VolatileCrashContainer, DummyCrashContainer
"""
__revision__ = "$Id$"
__all__ = [
# Object that represents a crash in the debugee.
'Crash',
# Crash storage.
'CrashDictionary',
# Warnings.
'CrashWarning',
# Backwards compatibility with WinAppDbg 1.4 and before.
'CrashContainer',
'CrashTable',
'CrashTableMSSQL',
'VolatileCrashContainer',
'DummyCrashContainer',
]
from winappdbg import win32
from winappdbg import compat
from winappdbg.system import System
from winappdbg.textio import HexDump, CrashDump
from winappdbg.util import StaticClass, MemoryAddresses, PathOperations
import sys
import os
import time
import zlib
import warnings
# lazy imports
sql = None
anydbm = None
#==============================================================================
# Secure alternative to pickle, use it if present.
try:
import cerealizer
pickle = cerealizer
# There is no optimization function for cerealized objects.
def optimize(picklestring):
return picklestring
# There is no HIGHEST_PROTOCOL in cerealizer.
HIGHEST_PROTOCOL = 0
# Note: it's important NOT to provide backwards compatibility, otherwise
# it'd be just the same as not having this!
#
# To disable this security upgrade simply uncomment the following line:
#
# raise ImportError("Fallback to pickle for backwards compatibility")
# If cerealizer is not present fallback to the insecure pickle module.
except ImportError:
# Faster implementation of the pickle module as a C extension.
try:
import cPickle as pickle
# If all fails fallback to the classic pickle module.
except ImportError:
import pickle
# Fetch the highest protocol version.
HIGHEST_PROTOCOL = pickle.HIGHEST_PROTOCOL
# Try to use the pickle optimizer if found.
try:
from pickletools import optimize
except ImportError:
def optimize(picklestring):
return picklestring
class Marshaller (StaticClass):
"""
Custom pickler for L{Crash} objects. Optimizes the pickled data when using
the standard C{pickle} (or C{cPickle}) module. The pickled data is then
compressed using zlib.
"""
@staticmethod
def dumps(obj, protocol=HIGHEST_PROTOCOL):
return zlib.compress(optimize(pickle.dumps(obj)), 9)
@staticmethod
def loads(data):
return pickle.loads(zlib.decompress(data))
#==============================================================================
class CrashWarning (Warning):
"""
An error occurred while gathering crash data.
Some data may be incomplete or missing.
"""
#==============================================================================
# Crash object. Must be serializable.
class Crash (object):
"""
Represents a crash, bug, or another interesting event in the debugee.
@group Basic information:
timeStamp, signature, eventCode, eventName, pid, tid, arch, os, bits,
registers, labelPC, pc, sp, fp
@group Optional information:
debugString,
modFileName,
lpBaseOfDll,
exceptionCode,
exceptionName,
exceptionDescription,
exceptionAddress,
exceptionLabel,
firstChance,
faultType,
faultAddress,
faultLabel,
isOurBreakpoint,
isSystemBreakpoint,
stackTrace,
stackTracePC,
stackTraceLabels,
stackTracePretty
@group Extra information:
commandLine,
environment,
environmentData,
registersPeek,
stackRange,
stackFrame,
stackPeek,
faultCode,
faultMem,
faultPeek,
faultDisasm,
memoryMap
@group Report:
briefReport, fullReport, notesReport, environmentReport, isExploitable
@group Notes:
addNote, getNotes, iterNotes, hasNotes, clearNotes, notes
@group Miscellaneous:
fetch_extra_data
@type timeStamp: float
@ivar timeStamp: Timestamp as returned by time.time().
@type signature: object
@ivar signature: Approximately unique signature for the Crash object.
This signature can be used as an heuristic to determine if two crashes
were caused by the same software error. Ideally it should be treated as
as opaque serializable object that can be tested for equality.
@type notes: list( str )
@ivar notes: List of strings, each string is a note.
@type eventCode: int
@ivar eventCode: Event code as defined by the Win32 API.
@type eventName: str
@ivar eventName: Event code user-friendly name.
@type pid: int
@ivar pid: Process global ID.
@type tid: int
@ivar tid: Thread global ID.
@type arch: str
@ivar arch: Processor architecture.
@type os: str
@ivar os: Operating system version.
May indicate a 64 bit version even if L{arch} and L{bits} indicate 32
bits. This means the crash occurred inside a WOW64 process.
@type bits: int
@ivar bits: C{32} or C{64} bits.
@type commandLine: None or str
@ivar commandLine: Command line for the target process.
C{None} if unapplicable or unable to retrieve.
@type environmentData: None or list of str
@ivar environmentData: Environment data for the target process.
C{None} if unapplicable or unable to retrieve.
@type environment: None or dict( str S{->} str )
@ivar environment: Environment variables for the target process.
C{None} if unapplicable or unable to retrieve.
@type registers: dict( str S{->} int )
@ivar registers: Dictionary mapping register names to their values.
@type registersPeek: None or dict( str S{->} str )
@ivar registersPeek: Dictionary mapping register names to the data they point to.
C{None} if unapplicable or unable to retrieve.
@type labelPC: None or str
@ivar labelPC: Label pointing to the program counter.
C{None} or invalid if unapplicable or unable to retrieve.
@type debugString: None or str
@ivar debugString: Debug string sent by the debugee.
C{None} if unapplicable or unable to retrieve.
@type exceptionCode: None or int
@ivar exceptionCode: Exception code as defined by the Win32 API.
C{None} if unapplicable or unable to retrieve.
@type exceptionName: None or str
@ivar exceptionName: Exception code user-friendly name.
C{None} if unapplicable or unable to retrieve.
@type exceptionDescription: None or str
@ivar exceptionDescription: Exception description.
C{None} if unapplicable or unable to retrieve.
@type exceptionAddress: None or int
@ivar exceptionAddress: Memory address where the exception occured.
C{None} if unapplicable or unable to retrieve.
@type exceptionLabel: None or str
@ivar exceptionLabel: Label pointing to the exception address.
C{None} or invalid if unapplicable or unable to retrieve.
@type faultType: None or int
@ivar faultType: Access violation type.
Only applicable to memory faults.
Should be one of the following constants:
- L{win32.ACCESS_VIOLATION_TYPE_READ}
- L{win32.ACCESS_VIOLATION_TYPE_WRITE}
- L{win32.ACCESS_VIOLATION_TYPE_DEP}
C{None} if unapplicable or unable to retrieve.
@type faultAddress: None or int
@ivar faultAddress: Access violation memory address.
Only applicable to memory faults.
C{None} if unapplicable or unable to retrieve.
@type faultLabel: None or str
@ivar faultLabel: Label pointing to the access violation memory address.
Only applicable to memory faults.
C{None} if unapplicable or unable to retrieve.
@type firstChance: None or bool
@ivar firstChance:
C{True} for first chance exceptions, C{False} for second chance.
C{None} if unapplicable or unable to retrieve.
@type isOurBreakpoint: bool
@ivar isOurBreakpoint:
C{True} for breakpoints defined by the L{Debug} class,
C{False} otherwise.
C{None} if unapplicable.
@type isSystemBreakpoint: bool
@ivar isSystemBreakpoint:
C{True} for known system-defined breakpoints,
C{False} otherwise.
C{None} if unapplicable.
@type modFileName: None or str
@ivar modFileName: File name of module where the program counter points to.
C{None} or invalid if unapplicable or unable to retrieve.
@type lpBaseOfDll: None or int
@ivar lpBaseOfDll: Base of module where the program counter points to.
C{None} if unapplicable or unable to retrieve.
@type stackTrace: None or tuple of tuple( int, int, str )
@ivar stackTrace:
Stack trace of the current thread as a tuple of
( frame pointer, return address, module filename ).
C{None} or empty if unapplicable or unable to retrieve.
@type stackTracePretty: None or tuple of tuple( int, str )
@ivar stackTracePretty:
Stack trace of the current thread as a tuple of
( frame pointer, return location ).
C{None} or empty if unapplicable or unable to retrieve.
@type stackTracePC: None or tuple( int... )
@ivar stackTracePC: Tuple of return addresses in the stack trace.
C{None} or empty if unapplicable or unable to retrieve.
@type stackTraceLabels: None or tuple( str... )
@ivar stackTraceLabels:
Tuple of labels pointing to the return addresses in the stack trace.
C{None} or empty if unapplicable or unable to retrieve.
@type stackRange: tuple( int, int )
@ivar stackRange:
Stack beginning and end pointers, in memory addresses order.
C{None} if unapplicable or unable to retrieve.
@type stackFrame: None or str
@ivar stackFrame: Data pointed to by the stack pointer.
C{None} or empty if unapplicable or unable to retrieve.
@type stackPeek: None or dict( int S{->} str )
@ivar stackPeek: Dictionary mapping stack offsets to the data they point to.
C{None} or empty if unapplicable or unable to retrieve.
@type faultCode: None or str
@ivar faultCode: Data pointed to by the program counter.
C{None} or empty if unapplicable or unable to retrieve.
@type faultMem: None or str
@ivar faultMem: Data pointed to by the exception address.
C{None} or empty if unapplicable or unable to retrieve.
@type faultPeek: None or dict( intS{->} str )
@ivar faultPeek: Dictionary mapping guessed pointers at L{faultMem} to the data they point to.
C{None} or empty if unapplicable or unable to retrieve.
@type faultDisasm: None or tuple of tuple( long, int, str, str )
@ivar faultDisasm: Dissassembly around the program counter.
C{None} or empty if unapplicable or unable to retrieve.
@type memoryMap: None or list of L{win32.MemoryBasicInformation} objects.
@ivar memoryMap: Memory snapshot of the program. May contain the actual
data from the entire process memory if requested.
See L{fetch_extra_data} for more details.
C{None} or empty if unapplicable or unable to retrieve.
@type _rowid: int
@ivar _rowid: Row ID in the database. Internally used by the DAO layer.
Only present in crash dumps retrieved from the database. Do not rely
on this property to be present in future versions of WinAppDbg.
"""
def __init__(self, event):
"""
@type event: L{Event}
@param event: Event object for crash.
"""
# First of all, take the timestamp.
self.timeStamp = time.time()
# Notes are initially empty.
self.notes = list()
# Get the process and thread, but dont't store them in the DB.
process = event.get_process()
thread = event.get_thread()
# Determine the architecture.
self.os = System.os
self.arch = process.get_arch()
self.bits = process.get_bits()
# The following properties are always retrieved for all events.
self.eventCode = event.get_event_code()
self.eventName = event.get_event_name()
self.pid = event.get_pid()
self.tid = event.get_tid()
self.registers = dict(thread.get_context())
self.labelPC = process.get_label_at_address(self.pc)
# The following properties are only retrieved for some events.
self.commandLine = None
self.environment = None
self.environmentData = None
self.registersPeek = None
self.debugString = None
self.modFileName = None
self.lpBaseOfDll = None
self.exceptionCode = None
self.exceptionName = None
self.exceptionDescription = None
self.exceptionAddress = None
self.exceptionLabel = None
self.firstChance = None
self.faultType = None
self.faultAddress = None
self.faultLabel = None
self.isOurBreakpoint = None
self.isSystemBreakpoint = None
self.stackTrace = None
self.stackTracePC = None
self.stackTraceLabels = None
self.stackTracePretty = None
self.stackRange = None
self.stackFrame = None
self.stackPeek = None
self.faultCode = None
self.faultMem = None
self.faultPeek = None
self.faultDisasm = None
self.memoryMap = None
# Get information for debug string events.
if self.eventCode == win32.OUTPUT_DEBUG_STRING_EVENT:
self.debugString = event.get_debug_string()
# Get information for module load and unload events.
# For create and exit process events, get the information
# for the main module.
elif self.eventCode in (win32.CREATE_PROCESS_DEBUG_EVENT,
win32.EXIT_PROCESS_DEBUG_EVENT,
win32.LOAD_DLL_DEBUG_EVENT,
win32.UNLOAD_DLL_DEBUG_EVENT):
aModule = event.get_module()
self.modFileName = event.get_filename()
if not self.modFileName:
self.modFileName = aModule.get_filename()
self.lpBaseOfDll = event.get_module_base()
if not self.lpBaseOfDll:
self.lpBaseOfDll = aModule.get_base()
# Get some information for exception events.
# To get the remaining information call fetch_extra_data().
elif self.eventCode == win32.EXCEPTION_DEBUG_EVENT:
# Exception information.
self.exceptionCode = event.get_exception_code()
self.exceptionName = event.get_exception_name()
self.exceptionDescription = event.get_exception_description()
self.exceptionAddress = event.get_exception_address()
self.firstChance = event.is_first_chance()
self.exceptionLabel = process.get_label_at_address(
self.exceptionAddress)
if self.exceptionCode in (win32.EXCEPTION_ACCESS_VIOLATION,
win32.EXCEPTION_GUARD_PAGE,
win32.EXCEPTION_IN_PAGE_ERROR):
self.faultType = event.get_fault_type()
self.faultAddress = event.get_fault_address()
self.faultLabel = process.get_label_at_address(
self.faultAddress)
elif self.exceptionCode in (win32.EXCEPTION_BREAKPOINT,
win32.EXCEPTION_SINGLE_STEP):
self.isOurBreakpoint = hasattr(event, 'breakpoint') \
and event.breakpoint
self.isSystemBreakpoint = \
process.is_system_defined_breakpoint(self.exceptionAddress)
# Stack trace.
try:
self.stackTracePretty = thread.get_stack_trace_with_labels()
except Exception:
e = sys.exc_info()[1]
warnings.warn(
"Cannot get stack trace with labels, reason: %s" % str(e),
CrashWarning)
try:
self.stackTrace = thread.get_stack_trace()
stackTracePC = [ ra for (_,ra,_) in self.stackTrace ]
self.stackTracePC = tuple(stackTracePC)
stackTraceLabels = [ process.get_label_at_address(ra) \
for ra in self.stackTracePC ]
self.stackTraceLabels = tuple(stackTraceLabels)
except Exception:
e = sys.exc_info()[1]
warnings.warn("Cannot get stack trace, reason: %s" % str(e),
CrashWarning)
def fetch_extra_data(self, event, takeMemorySnapshot = 0):
"""
Fetch extra data from the L{Event} object.
@note: Since this method may take a little longer to run, it's best to
call it only after you've determined the crash is interesting and
you want to save it.
@type event: L{Event}
@param event: Event object for crash.
@type takeMemorySnapshot: int
@param takeMemorySnapshot:
Memory snapshot behavior:
- C{0} to take no memory information (default).
- C{1} to take only the memory map.
See L{Process.get_memory_map}.
- C{2} to take a full memory snapshot.
See L{Process.take_memory_snapshot}.
- C{3} to take a live memory snapshot.
See L{Process.generate_memory_snapshot}.
"""
# Get the process and thread, we'll use them below.
process = event.get_process()
thread = event.get_thread()
# Get the command line for the target process.
try:
self.commandLine = process.get_command_line()
except Exception:
e = sys.exc_info()[1]
warnings.warn("Cannot get command line, reason: %s" % str(e),
CrashWarning)
# Get the environment variables for the target process.
try:
self.environmentData = process.get_environment_data()
self.environment = process.parse_environment_data(
self.environmentData)
except Exception:
e = sys.exc_info()[1]
warnings.warn("Cannot get environment, reason: %s" % str(e),
CrashWarning)
# Data pointed to by registers.
self.registersPeek = thread.peek_pointers_in_registers()
# Module where execution is taking place.
aModule = process.get_module_at_address(self.pc)
if aModule is not None:
self.modFileName = aModule.get_filename()
self.lpBaseOfDll = aModule.get_base()
# Contents of the stack frame.
try:
self.stackRange = thread.get_stack_range()
except Exception:
e = sys.exc_info()[1]
warnings.warn("Cannot get stack range, reason: %s" % str(e),
CrashWarning)
try:
self.stackFrame = thread.get_stack_frame()
stackFrame = self.stackFrame
except Exception:
self.stackFrame = thread.peek_stack_data()
stackFrame = self.stackFrame[:64]
if stackFrame:
self.stackPeek = process.peek_pointers_in_data(stackFrame)
# Code being executed.
self.faultCode = thread.peek_code_bytes()
try:
self.faultDisasm = thread.disassemble_around_pc(32)
except Exception:
e = sys.exc_info()[1]
warnings.warn("Cannot disassemble, reason: %s" % str(e),
CrashWarning)
# For memory related exceptions, get the memory contents
# of the location that caused the exception to be raised.
if self.eventCode == win32.EXCEPTION_DEBUG_EVENT:
if self.pc != self.exceptionAddress and self.exceptionCode in (
win32.EXCEPTION_ACCESS_VIOLATION,
win32.EXCEPTION_ARRAY_BOUNDS_EXCEEDED,
win32.EXCEPTION_DATATYPE_MISALIGNMENT,
win32.EXCEPTION_IN_PAGE_ERROR,
win32.EXCEPTION_STACK_OVERFLOW,
win32.EXCEPTION_GUARD_PAGE,
):
self.faultMem = process.peek(self.exceptionAddress, 64)
if self.faultMem:
self.faultPeek = process.peek_pointers_in_data(
self.faultMem)
# TODO: maybe add names and versions of DLLs and EXE?
# Take a snapshot of the process memory. Additionally get the
# memory contents if requested.
if takeMemorySnapshot == 1:
self.memoryMap = process.get_memory_map()
mappedFilenames = process.get_mapped_filenames(self.memoryMap)
for mbi in self.memoryMap:
mbi.filename = mappedFilenames.get(mbi.BaseAddress, None)
mbi.content = None
elif takeMemorySnapshot == 2:
self.memoryMap = process.take_memory_snapshot()
elif takeMemorySnapshot == 3:
self.memoryMap = process.generate_memory_snapshot()
@property
def pc(self):
"""
Value of the program counter register.
@rtype: int
"""
try:
return self.registers['Eip'] # i386
except KeyError:
return self.registers['Rip'] # amd64
@property
def sp(self):
"""
Value of the stack pointer register.
@rtype: int
"""
try:
return self.registers['Esp'] # i386
except KeyError:
return self.registers['Rsp'] # amd64
@property
def fp(self):
"""
Value of the frame pointer register.
@rtype: int
"""
try:
return self.registers['Ebp'] # i386
except KeyError:
return self.registers['Rbp'] # amd64
def __str__(self):
return self.fullReport()
def key(self):
"""
Alias of L{signature}. Deprecated since WinAppDbg 1.5.
"""
warnings.warn("Crash.key() method was deprecated in WinAppDbg 1.5",
DeprecationWarning)
return self.signature
@property
def signature(self):
if self.labelPC:
pc = self.labelPC
else:
pc = self.pc
if self.stackTraceLabels:
trace = self.stackTraceLabels
else:
trace = self.stackTracePC
return (
self.arch,
self.eventCode,
self.exceptionCode,
pc,
trace,
self.debugString,
)
# TODO
# add the name and version of the binary where the crash happened?
def isExploitable(self):
"""
Guess how likely is it that the bug causing the crash can be leveraged
into an exploitable vulnerability.
@note: Don't take this as an equivalent of a real exploitability
analysis, that can only be done by a human being! This is only
a guideline, useful for example to sort crashes - placing the most
interesting ones at the top.
@see: The heuristics are similar to those of the B{!exploitable}
extension for I{WinDBG}, which can be downloaded from here:
U{http://www.codeplex.com/msecdbg}
@rtype: tuple( str, str, str )
@return: The first element of the tuple is the result of the analysis,
being one of the following:
- Not an exception
- Not exploitable
- Not likely exploitable
- Unknown
- Probably exploitable
- Exploitable
The second element of the tuple is a code to identify the matched
heuristic rule.
The third element of the tuple is a description string of the
reason behind the result.
"""
# Terminal rules
if self.eventCode != win32.EXCEPTION_DEBUG_EVENT:
return ("Not an exception", "NotAnException", "The event is not an exception.")
if self.stackRange and self.pc is not None and self.stackRange[0] <= self.pc < self.stackRange[1]:
return ("Exploitable", "StackCodeExecution", "Code execution from the stack is considered exploitable.")
# This rule is NOT from !exploitable
if self.stackRange and self.sp is not None and not (self.stackRange[0] <= self.sp < self.stackRange[1]):
return ("Exploitable", "StackPointerCorruption", "Stack pointer corruption is considered exploitable.")
if self.exceptionCode == win32.EXCEPTION_ILLEGAL_INSTRUCTION:
return ("Exploitable", "IllegalInstruction", "An illegal instruction exception indicates that the attacker controls execution flow.")
if self.exceptionCode == win32.EXCEPTION_PRIV_INSTRUCTION:
return ("Exploitable", "PrivilegedInstruction", "A privileged instruction exception indicates that the attacker controls execution flow.")
if self.exceptionCode == win32.EXCEPTION_GUARD_PAGE:
return ("Exploitable", "GuardPage", "A guard page violation indicates a stack overflow has occured, and the stack of another thread was reached (possibly the overflow length is not controlled by the attacker).")
if self.exceptionCode == win32.STATUS_STACK_BUFFER_OVERRUN:
return ("Exploitable", "GSViolation", "An overrun of a protected stack buffer has been detected. This is considered exploitable, and must be fixed.")
if self.exceptionCode == win32.STATUS_HEAP_CORRUPTION:
return ("Exploitable", "HeapCorruption", "Heap Corruption has been detected. This is considered exploitable, and must be fixed.")
if self.exceptionCode == win32.EXCEPTION_ACCESS_VIOLATION:
nearNull = self.faultAddress is None or MemoryAddresses.align_address_to_page_start(self.faultAddress) == 0
controlFlow = self.__is_control_flow()
blockDataMove = self.__is_block_data_move()
if self.faultType == win32.EXCEPTION_EXECUTE_FAULT:
if nearNull:
return ("Probably exploitable", "DEPViolation", "User mode DEP access violations are probably exploitable if near NULL.")
else:
return ("Exploitable", "DEPViolation", "User mode DEP access violations are exploitable.")
elif self.faultType == win32.EXCEPTION_WRITE_FAULT:
if nearNull:
return ("Probably exploitable", "WriteAV", "User mode write access violations that are near NULL are probably exploitable.")
else:
return ("Exploitable", "WriteAV", "User mode write access violations that are not near NULL are exploitable.")
elif self.faultType == win32.EXCEPTION_READ_FAULT:
if self.faultAddress == self.pc:
if nearNull:
return ("Probably exploitable", "ReadAVonIP", "Access violations at the instruction pointer are probably exploitable if near NULL.")
else:
return ("Exploitable", "ReadAVonIP", "Access violations at the instruction pointer are exploitable if not near NULL.")
if controlFlow:
if nearNull:
return ("Probably exploitable", "ReadAVonControlFlow", "Access violations near null in control flow instructions are considered probably exploitable.")
else:
return ("Exploitable", "ReadAVonControlFlow", "Access violations not near null in control flow instructions are considered exploitable.")
if blockDataMove:
return ("Probably exploitable", "ReadAVonBlockMove", "This is a read access violation in a block data move, and is therefore classified as probably exploitable.")
# Rule: Tainted information used to control branch addresses is considered probably exploitable
# Rule: Tainted information used to control the target of a later write is probably exploitable
# Non terminal rules
# XXX TODO add rule to check if code is in writeable memory (probably exploitable)
# XXX TODO maybe we should be returning a list of tuples instead?
result = ("Unknown", "Unknown", "Exploitability unknown.")
if self.exceptionCode == win32.EXCEPTION_ACCESS_VIOLATION:
if self.faultType == win32.EXCEPTION_READ_FAULT:
if nearNull:
result = ("Not likely exploitable", "ReadAVNearNull", "This is a user mode read access violation near null, and is probably not exploitable.")
elif self.exceptionCode == win32.EXCEPTION_INT_DIVIDE_BY_ZERO:
result = ("Not likely exploitable", "DivideByZero", "This is an integer divide by zero, and is probably not exploitable.")
elif self.exceptionCode == win32.EXCEPTION_FLT_DIVIDE_BY_ZERO:
result = ("Not likely exploitable", "DivideByZero", "This is a floating point divide by zero, and is probably not exploitable.")
elif self.exceptionCode in (win32.EXCEPTION_BREAKPOINT, win32.STATUS_WX86_BREAKPOINT):
result = ("Unknown", "Breakpoint", "While a breakpoint itself is probably not exploitable, it may also be an indication that an attacker is testing a target. In either case breakpoints should not exist in production code.")
# Rule: If the stack contains unknown symbols in user mode, call that out
# Rule: Tainted information used to control the source of a later block move unknown, but called out explicitly
# Rule: Tainted information used as an argument to a function is an unknown risk, but called out explicitly
# Rule: Tainted information used to control branch selection is an unknown risk, but called out explicitly
return result
def __is_control_flow(self):
"""
Private method to tell if the instruction pointed to by the program
counter is a control flow instruction.
Currently only works for x86 and amd64 architectures.
"""
jump_instructions = (
'jmp', 'jecxz', 'jcxz',
'ja', 'jnbe', 'jae', 'jnb', 'jb', 'jnae', 'jbe', 'jna', 'jc', 'je',
'jz', 'jnc', 'jne', 'jnz', 'jnp', 'jpo', 'jp', 'jpe', 'jg', 'jnle',
'jge', 'jnl', 'jl', 'jnge', 'jle', 'jng', 'jno', 'jns', 'jo', 'js'
)
call_instructions = ( 'call', 'ret', 'retn' )
loop_instructions = ( 'loop', 'loopz', 'loopnz', 'loope', 'loopne' )
control_flow_instructions = call_instructions + loop_instructions + \
jump_instructions
isControlFlow = False
instruction = None
if self.pc is not None and self.faultDisasm:
for disasm in self.faultDisasm:
if disasm[0] == self.pc:
instruction = disasm[2].lower().strip()
break
if instruction:
for x in control_flow_instructions:
if x in instruction:
isControlFlow = True
break
return isControlFlow
def __is_block_data_move(self):
"""
Private method to tell if the instruction pointed to by the program
counter is a block data move instruction.
Currently only works for x86 and amd64 architectures.
"""
block_data_move_instructions = ('movs', 'stos', 'lods')
isBlockDataMove = False
instruction = None
if self.pc is not None and self.faultDisasm:
for disasm in self.faultDisasm:
if disasm[0] == self.pc:
instruction = disasm[2].lower().strip()
break
if instruction:
for x in block_data_move_instructions:
if x in instruction:
isBlockDataMove = True
break
return isBlockDataMove
def briefReport(self):
"""
@rtype: str
@return: Short description of the event.
"""
if self.exceptionCode is not None:
if self.exceptionCode == win32.EXCEPTION_BREAKPOINT:
if self.isOurBreakpoint:
what = "Breakpoint hit"
elif self.isSystemBreakpoint:
what = "System breakpoint hit"
else:
what = "Assertion failed"
elif self.exceptionDescription:
what = self.exceptionDescription
elif self.exceptionName:
what = self.exceptionName
else:
what = "Exception %s" % \
HexDump.integer(self.exceptionCode, self.bits)
if self.firstChance:
chance = 'first'
else:
chance = 'second'
if self.exceptionLabel:
where = self.exceptionLabel
elif self.exceptionAddress:
where = HexDump.address(self.exceptionAddress, self.bits)
elif self.labelPC:
where = self.labelPC
else:
where = HexDump.address(self.pc, self.bits)
msg = "%s (%s chance) at %s" % (what, chance, where)
elif self.debugString is not None:
if self.labelPC:
where = self.labelPC
else:
where = HexDump.address(self.pc, self.bits)
msg = "Debug string from %s: %r" % (where, self.debugString)
else:
if self.labelPC:
where = self.labelPC
else:
where = HexDump.address(self.pc, self.bits)
msg = "%s (%s) at %s" % (
self.eventName,
HexDump.integer(self.eventCode, self.bits),
where
)
return msg
def fullReport(self, bShowNotes = True):
"""
@type bShowNotes: bool
@param bShowNotes: C{True} to show the user notes, C{False} otherwise.
@rtype: str
@return: Long description of the event.
"""
msg = self.briefReport()
msg += '\n'
if self.bits == 32:
width = 16
else:
width = 8
if self.eventCode == win32.EXCEPTION_DEBUG_EVENT:
(exploitability, expcode, expdescription) = self.isExploitable()
msg += '\nSecurity risk level: %s\n' % exploitability
msg += ' %s\n' % expdescription
if bShowNotes and self.notes:
msg += '\nNotes:\n'
msg += self.notesReport()
if self.commandLine:
msg += '\nCommand line: %s\n' % self.commandLine
if self.environment:
msg += '\nEnvironment:\n'
msg += self.environmentReport()
if not self.labelPC:
base = HexDump.address(self.lpBaseOfDll, self.bits)
if self.modFileName:
fn = PathOperations.pathname_to_filename(self.modFileName)
msg += '\nRunning in %s (%s)\n' % (fn, base)
else:
msg += '\nRunning in module at %s\n' % base
if self.registers:
msg += '\nRegisters:\n'
msg += CrashDump.dump_registers(self.registers)
if self.registersPeek:
msg += '\n'
msg += CrashDump.dump_registers_peek(self.registers,
self.registersPeek,
width = width)
if self.faultDisasm:
msg += '\nCode disassembly:\n'
msg += CrashDump.dump_code(self.faultDisasm, self.pc,
bits = self.bits)
if self.stackTrace:
msg += '\nStack trace:\n'
if self.stackTracePretty:
msg += CrashDump.dump_stack_trace_with_labels(
self.stackTracePretty,
bits = self.bits)
else:
msg += CrashDump.dump_stack_trace(self.stackTrace,
bits = self.bits)
if self.stackFrame:
if self.stackPeek:
msg += '\nStack pointers:\n'
msg += CrashDump.dump_stack_peek(self.stackPeek, width = width)
msg += '\nStack dump:\n'
msg += HexDump.hexblock(self.stackFrame, self.sp,
bits = self.bits, width = width)
if self.faultCode and not self.modFileName:
msg += '\nCode dump:\n'
msg += HexDump.hexblock(self.faultCode, self.pc,
bits = self.bits, width = width)
if self.faultMem:
if self.faultPeek:
msg += '\nException address pointers:\n'
msg += CrashDump.dump_data_peek(self.faultPeek,
self.exceptionAddress,
bits = self.bits,
width = width)
msg += '\nException address dump:\n'
msg += HexDump.hexblock(self.faultMem, self.exceptionAddress,
bits = self.bits, width = width)
if self.memoryMap:
msg += '\nMemory map:\n'
mappedFileNames = dict()
for mbi in self.memoryMap:
if hasattr(mbi, 'filename') and mbi.filename:
mappedFileNames[mbi.BaseAddress] = mbi.filename
msg += CrashDump.dump_memory_map(self.memoryMap, mappedFileNames,
bits = self.bits)
if not msg.endswith('\n\n'):
if not msg.endswith('\n'):
msg += '\n'
msg += '\n'
return msg
def environmentReport(self):
"""
@rtype: str
@return: The process environment variables,
merged and formatted for a report.
"""
msg = ''
if self.environment:
for key, value in compat.iteritems(self.environment):
msg += ' %s=%s\n' % (key, value)
return msg
def notesReport(self):
"""
@rtype: str
@return: All notes, merged and formatted for a report.
"""
msg = ''
if self.notes:
for n in self.notes:
n = n.strip('\n')
if '\n' in n:
n = n.strip('\n')
msg += ' * %s\n' % n.pop(0)
for x in n:
msg += ' %s\n' % x
else:
msg += ' * %s\n' % n
return msg
def addNote(self, msg):
"""
Add a note to the crash event.
@type msg: str
@param msg: Note text.
"""
self.notes.append(msg)
def clearNotes(self):
"""
Clear the notes of this crash event.
"""
self.notes = list()
def getNotes(self):
"""
Get the list of notes of this crash event.
@rtype: list( str )
@return: List of notes.
"""
return self.notes
def iterNotes(self):
"""
Iterate the notes of this crash event.
@rtype: listiterator
@return: Iterator of the list of notes.
"""
return self.notes.__iter__()
def hasNotes(self):
"""
@rtype: bool
@return: C{True} if there are notes for this crash event.
"""
return bool( self.notes )
#==============================================================================
class CrashContainer (object):
"""
Old crash dump persistencer using a DBM database.
Doesn't support duplicate crashes.
@warning:
DBM database support is provided for backwards compatibility with older
versions of WinAppDbg. New applications should not use this class.
Also, DBM databases in Python suffer from multiple problems that can
easily be avoided by switching to a SQL database.
@see: If you really must use a DBM database, try the standard C{shelve}
module instead: U{http://docs.python.org/library/shelve.html}
@group Marshalling configuration:
optimizeKeys, optimizeValues, compressKeys, compressValues, escapeKeys,
escapeValues, binaryKeys, binaryValues
@type optimizeKeys: bool
@cvar optimizeKeys: Ignored by the current implementation.
Up to WinAppDbg 1.4 this setting caused the database keys to be
optimized when pickled with the standard C{pickle} module.
But with a DBM database backend that causes inconsistencies, since the
same key can be serialized into multiple optimized pickles, thus losing
uniqueness.
@type optimizeValues: bool
@cvar optimizeValues: C{True} to optimize the marshalling of keys, C{False}
otherwise. Only used with the C{pickle} module, ignored when using the
more secure C{cerealizer} module.
@type compressKeys: bool
@cvar compressKeys: C{True} to compress keys when marshalling, C{False}
to leave them uncompressed.
@type compressValues: bool
@cvar compressValues: C{True} to compress values when marshalling, C{False}
to leave them uncompressed.
@type escapeKeys: bool
@cvar escapeKeys: C{True} to escape keys when marshalling, C{False}
to leave them uncompressed.
@type escapeValues: bool
@cvar escapeValues: C{True} to escape values when marshalling, C{False}
to leave them uncompressed.
@type binaryKeys: bool
@cvar binaryKeys: C{True} to marshall keys to binary format (the Python
C{buffer} type), C{False} to use text marshalled keys (C{str} type).
@type binaryValues: bool
@cvar binaryValues: C{True} to marshall values to binary format (the Python
C{buffer} type), C{False} to use text marshalled values (C{str} type).
"""
optimizeKeys = False
optimizeValues = True
compressKeys = False
compressValues = True
escapeKeys = False
escapeValues = False
binaryKeys = False
binaryValues = False
def __init__(self, filename = None, allowRepeatedKeys = False):
"""
@type filename: str
@param filename: (Optional) File name for crash database.
If no filename is specified, the container is volatile.
Volatile containers are stored only in memory and
destroyed when they go out of scope.
@type allowRepeatedKeys: bool
@param allowRepeatedKeys:
Currently not supported, always use C{False}.
"""
if allowRepeatedKeys:
raise NotImplementedError()
self.__filename = filename
if filename:
global anydbm
if not anydbm:
import anydbm
self.__db = anydbm.open(filename, 'c')
self.__keys = dict([ (self.unmarshall_key(mk), mk)
for mk in self.__db.keys() ])
else:
self.__db = dict()
self.__keys = dict()
def remove_key(self, key):
"""
Removes the given key from the set of known keys.
@type key: L{Crash} key.
@param key: Key to remove.
"""
del self.__keys[key]
def marshall_key(self, key):
"""
Marshalls a Crash key to be used in the database.
@see: L{__init__}
@type key: L{Crash} key.
@param key: Key to convert.
@rtype: str or buffer
@return: Converted key.
"""
if key in self.__keys:
return self.__keys[key]
skey = pickle.dumps(key, protocol = 0)
if self.compressKeys:
skey = zlib.compress(skey, zlib.Z_BEST_COMPRESSION)
if self.escapeKeys:
skey = skey.encode('hex')
if self.binaryKeys:
skey = buffer(skey)
self.__keys[key] = skey
return skey
def unmarshall_key(self, key):
"""
Unmarshalls a Crash key read from the database.
@type key: str or buffer
@param key: Key to convert.
@rtype: L{Crash} key.
@return: Converted key.
"""
key = str(key)
if self.escapeKeys:
key = key.decode('hex')
if self.compressKeys:
key = zlib.decompress(key)
key = pickle.loads(key)
return key
def marshall_value(self, value, storeMemoryMap = False):
"""
Marshalls a Crash object to be used in the database.
By default the C{memoryMap} member is B{NOT} stored here.
@warning: Setting the C{storeMemoryMap} argument to C{True} can lead to
a severe performance penalty!
@type value: L{Crash}
@param value: Object to convert.
@type storeMemoryMap: bool
@param storeMemoryMap: C{True} to store the memory map, C{False}
otherwise.
@rtype: str
@return: Converted object.
"""
if hasattr(value, 'memoryMap'):
crash = value
memoryMap = crash.memoryMap
try:
crash.memoryMap = None
if storeMemoryMap and memoryMap is not None:
# convert the generator to a list
crash.memoryMap = list(memoryMap)
if self.optimizeValues:
value = pickle.dumps(crash, protocol = HIGHEST_PROTOCOL)
value = optimize(value)
else:
value = pickle.dumps(crash, protocol = 0)
finally:
crash.memoryMap = memoryMap
del memoryMap
del crash
if self.compressValues:
value = zlib.compress(value, zlib.Z_BEST_COMPRESSION)
if self.escapeValues:
value = value.encode('hex')
if self.binaryValues:
value = buffer(value)
return value
def unmarshall_value(self, value):
"""
Unmarshalls a Crash object read from the database.
@type value: str
@param value: Object to convert.
@rtype: L{Crash}
@return: Converted object.
"""
value = str(value)
if self.escapeValues:
value = value.decode('hex')
if self.compressValues:
value = zlib.decompress(value)
value = pickle.loads(value)
return value
# The interface is meant to be similar to a Python set.
# However it may not be necessary to implement all of the set methods.
# Other methods like get, has_key, iterkeys and itervalues
# are dictionary-like.
def __len__(self):
"""
@rtype: int
@return: Count of known keys.
"""
return len(self.__keys)
def __bool__(self):
"""
@rtype: bool
@return: C{False} if there are no known keys.
"""
return bool(self.__keys)
def __contains__(self, crash):
"""
@type crash: L{Crash}
@param crash: Crash object.
@rtype: bool
@return:
C{True} if a Crash object with the same key is in the container.
"""
return self.has_key( crash.key() )
def has_key(self, key):
"""
@type key: L{Crash} key.
@param key: Key to find.
@rtype: bool
@return: C{True} if the key is present in the set of known keys.
"""
return key in self.__keys
def iterkeys(self):
"""
@rtype: iterator
@return: Iterator of known L{Crash} keys.
"""
return compat.iterkeys(self.__keys)
class __CrashContainerIterator (object):
"""
Iterator of Crash objects. Returned by L{CrashContainer.__iter__}.
"""
def __init__(self, container):
"""
@type container: L{CrashContainer}
@param container: Crash set to iterate.
"""
# It's important to keep a reference to the CrashContainer,
# rather than it's underlying database.
# Otherwise the destructor of CrashContainer may close the
# database while we're still iterating it.
#
# TODO: lock the database when iterating it.
#
self.__container = container
self.__keys_iter = compat.iterkeys(container)
def next(self):
"""
@rtype: L{Crash}
@return: A B{copy} of a Crash object in the L{CrashContainer}.
@raise StopIteration: No more items left.
"""
key = self.__keys_iter.next()
return self.__container.get(key)
def __del__(self):
"Class destructor. Closes the database when this object is destroyed."
try:
if self.__filename:
self.__db.close()
except:
pass
def __iter__(self):
"""
@see: L{itervalues}
@rtype: iterator
@return: Iterator of the contained L{Crash} objects.
"""
return self.itervalues()
def itervalues(self):
"""
@rtype: iterator
@return: Iterator of the contained L{Crash} objects.
@warning: A B{copy} of each object is returned,
so any changes made to them will be lost.
To preserve changes do the following:
1. Keep a reference to the object.
2. Delete the object from the set.
3. Modify the object and add it again.
"""
return self.__CrashContainerIterator(self)
def add(self, crash):
"""
Adds a new crash to the container.
If the crash appears to be already known, it's ignored.
@see: L{Crash.key}
@type crash: L{Crash}
@param crash: Crash object to add.
"""
if crash not in self:
key = crash.key()
skey = self.marshall_key(key)
data = self.marshall_value(crash, storeMemoryMap = True)
self.__db[skey] = data
def __delitem__(self, key):
"""
Removes a crash from the container.
@type key: L{Crash} unique key.
@param key: Key of the crash to get.
"""
skey = self.marshall_key(key)
del self.__db[skey]
self.remove_key(key)
def remove(self, crash):
"""
Removes a crash from the container.
@type crash: L{Crash}
@param crash: Crash object to remove.
"""
del self[ crash.key() ]
def get(self, key):
"""
Retrieves a crash from the container.
@type key: L{Crash} unique key.
@param key: Key of the crash to get.
@rtype: L{Crash} object.
@return: Crash matching the given key.
@see: L{iterkeys}
@warning: A B{copy} of each object is returned,
so any changes made to them will be lost.
To preserve changes do the following:
1. Keep a reference to the object.
2. Delete the object from the set.
3. Modify the object and add it again.
"""
skey = self.marshall_key(key)
data = self.__db[skey]
crash = self.unmarshall_value(data)
return crash
def __getitem__(self, key):
"""
Retrieves a crash from the container.
@type key: L{Crash} unique key.
@param key: Key of the crash to get.
@rtype: L{Crash} object.
@return: Crash matching the given key.
@see: L{iterkeys}
@warning: A B{copy} of each object is returned,
so any changes made to them will be lost.
To preserve changes do the following:
1. Keep a reference to the object.
2. Delete the object from the set.
3. Modify the object and add it again.
"""
return self.get(key)
#==============================================================================
class CrashDictionary(object):
"""
Dictionary-like persistence interface for L{Crash} objects.
Currently the only implementation is through L{sql.CrashDAO}.
"""
def __init__(self, url, creator = None, allowRepeatedKeys = True):
"""
@type url: str
@param url: Connection URL of the crash database.
See L{sql.CrashDAO.__init__} for more details.
@type creator: callable
@param creator: (Optional) Callback function that creates the SQL
database connection.
Normally it's not necessary to use this argument. However in some
odd cases you may need to customize the database connection, for
example when using the integrated authentication in MSSQL.
@type allowRepeatedKeys: bool
@param allowRepeatedKeys:
If C{True} all L{Crash} objects are stored.
If C{False} any L{Crash} object with the same signature as a
previously existing object will be ignored.
"""
global sql
if sql is None:
from winappdbg import sql
self._allowRepeatedKeys = allowRepeatedKeys
self._dao = sql.CrashDAO(url, creator)
def add(self, crash):
"""
Adds a new crash to the container.
@note:
When the C{allowRepeatedKeys} parameter of the constructor
is set to C{False}, duplicated crashes are ignored.
@see: L{Crash.key}
@type crash: L{Crash}
@param crash: Crash object to add.
"""
self._dao.add(crash, self._allowRepeatedKeys)
def get(self, key):
"""
Retrieves a crash from the container.
@type key: L{Crash} signature.
@param key: Heuristic signature of the crash to get.
@rtype: L{Crash} object.
@return: Crash matching the given signature. If more than one is found,
retrieve the newest one.
@see: L{iterkeys}
@warning: A B{copy} of each object is returned,
so any changes made to them will be lost.
To preserve changes do the following:
1. Keep a reference to the object.
2. Delete the object from the set.
3. Modify the object and add it again.
"""
found = self._dao.find(signature=key, limit=1, order=-1)
if not found:
raise KeyError(key)
return found[0]
def __iter__(self):
"""
@rtype: iterator
@return: Iterator of the contained L{Crash} objects.
"""
offset = 0
limit = 10
while 1:
found = self._dao.find(offset=offset, limit=limit)
if not found:
break
offset += len(found)
for crash in found:
yield crash
def itervalues(self):
"""
@rtype: iterator
@return: Iterator of the contained L{Crash} objects.
"""
return self.__iter__()
def iterkeys(self):
"""
@rtype: iterator
@return: Iterator of the contained L{Crash} heuristic signatures.
"""
for crash in self:
yield crash.signature # FIXME this gives repeated results!
def __contains__(self, crash):
"""
@type crash: L{Crash}
@param crash: Crash object.
@rtype: bool
@return: C{True} if the Crash object is in the container.
"""
return self._dao.count(signature=crash.signature) > 0
def has_key(self, key):
"""
@type key: L{Crash} signature.
@param key: Heuristic signature of the crash to get.
@rtype: bool
@return: C{True} if a matching L{Crash} object is in the container.
"""
return self._dao.count(signature=key) > 0
def __len__(self):
"""
@rtype: int
@return: Count of L{Crash} elements in the container.
"""
return self._dao.count()
def __bool__(self):
"""
@rtype: bool
@return: C{False} if the container is empty.
"""
return bool( len(self) )
class CrashTable(CrashDictionary):
"""
Old crash dump persistencer using a SQLite database.
@warning:
Superceded by L{CrashDictionary} since WinAppDbg 1.5.
New applications should not use this class.
"""
def __init__(self, location = None, allowRepeatedKeys = True):
"""
@type location: str
@param location: (Optional) Location of the crash database.
If the location is a filename, it's an SQLite database file.
If no location is specified, the container is volatile.
Volatile containers are stored only in memory and
destroyed when they go out of scope.
@type allowRepeatedKeys: bool
@param allowRepeatedKeys:
If C{True} all L{Crash} objects are stored.
If C{False} any L{Crash} object with the same signature as a
previously existing object will be ignored.
"""
warnings.warn(
"The %s class is deprecated since WinAppDbg 1.5." % self.__class__,
DeprecationWarning)
if location:
url = "sqlite:///%s" % location
else:
url = "sqlite://"
super(CrashTable, self).__init__(url, allowRepeatedKeys)
class CrashTableMSSQL (CrashDictionary):
"""
Old crash dump persistencer using a Microsoft SQL Server database.
@warning:
Superceded by L{CrashDictionary} since WinAppDbg 1.5.
New applications should not use this class.
"""
def __init__(self, location = None, allowRepeatedKeys = True):
"""
@type location: str
@param location: Location of the crash database.
It must be an ODBC connection string.
@type allowRepeatedKeys: bool
@param allowRepeatedKeys:
If C{True} all L{Crash} objects are stored.
If C{False} any L{Crash} object with the same signature as a
previously existing object will be ignored.
"""
warnings.warn(
"The %s class is deprecated since WinAppDbg 1.5." % self.__class__,
DeprecationWarning)
import urllib
url = "mssql+pyodbc:///?odbc_connect=" + urllib.quote_plus(location)
super(CrashTableMSSQL, self).__init__(url, allowRepeatedKeys)
class VolatileCrashContainer (CrashTable):
"""
Old in-memory crash dump storage.
@warning:
Superceded by L{CrashDictionary} since WinAppDbg 1.5.
New applications should not use this class.
"""
def __init__(self, allowRepeatedKeys = True):
"""
Volatile containers are stored only in memory and
destroyed when they go out of scope.
@type allowRepeatedKeys: bool
@param allowRepeatedKeys:
If C{True} all L{Crash} objects are stored.
If C{False} any L{Crash} object with the same key as a
previously existing object will be ignored.
"""
super(VolatileCrashContainer, self).__init__(
allowRepeatedKeys=allowRepeatedKeys)
class DummyCrashContainer(object):
"""
Fakes a database of volatile Crash objects,
trying to mimic part of it's interface, but
doesn't actually store anything.
Normally applications don't need to use this.
@see: L{CrashDictionary}
"""
def __init__(self, allowRepeatedKeys = True):
"""
Fake containers don't store L{Crash} objects, but they implement the
interface properly.
@type allowRepeatedKeys: bool
@param allowRepeatedKeys:
Mimics the duplicate filter behavior found in real containers.
"""
self.__keys = set()
self.__count = 0
self.__allowRepeatedKeys = allowRepeatedKeys
def __contains__(self, crash):
"""
@type crash: L{Crash}
@param crash: Crash object.
@rtype: bool
@return: C{True} if the Crash object is in the container.
"""
return crash.signature in self.__keys
def __len__(self):
"""
@rtype: int
@return: Count of L{Crash} elements in the container.
"""
if self.__allowRepeatedKeys:
return self.__count
return len( self.__keys )
def __bool__(self):
"""
@rtype: bool
@return: C{False} if the container is empty.
"""
return bool( len(self) )
def add(self, crash):
"""
Adds a new crash to the container.
@note:
When the C{allowRepeatedKeys} parameter of the constructor
is set to C{False}, duplicated crashes are ignored.
@see: L{Crash.key}
@type crash: L{Crash}
@param crash: Crash object to add.
"""
self.__keys.add( crash.signature )
self.__count += 1
def get(self, key):
"""
This method is not supported.
"""
raise NotImplementedError()
def has_key(self, key):
"""
@type key: L{Crash} signature.
@param key: Heuristic signature of the crash to get.
@rtype: bool
@return: C{True} if a matching L{Crash} object is in the container.
"""
return self.__keys.has_key( key )
def iterkeys(self):
"""
@rtype: iterator
@return: Iterator of the contained L{Crash} object keys.
@see: L{get}
@warning: A B{copy} of each object is returned,
so any changes made to them will be lost.
To preserve changes do the following:
1. Keep a reference to the object.
2. Delete the object from the set.
3. Modify the object and add it again.
"""
return iter(self.__keys)
#==============================================================================
# Register the Crash class with the secure serializer.
try:
cerealizer.register(Crash)
cerealizer.register(win32.MemoryBasicInformation)
except NameError:
pass
| 65,394 | Python | 34.272384 | 235 | 0.577622 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/compat.py | # Partial copy of https://bitbucket.org/gutworth/six/src/8e634686c53a35092dd705172440a9231c90ddd1/six.py?at=default
# With some differences to take into account that the iterXXX version may be defined in user code.
# Original __author__ = "Benjamin Peterson <[email protected]>"
# Base __version__ = "1.7.3"
# Copyright (c) 2010-2014 Benjamin Peterson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import sys
import types
# Useful for very coarse version differentiation.
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
if PY3:
string_types = str,
integer_types = int,
class_types = type,
text_type = str
binary_type = bytes
MAXSIZE = sys.maxsize
else:
string_types = basestring,
integer_types = (int, long)
class_types = (type, types.ClassType)
text_type = unicode
binary_type = str
if sys.platform.startswith("java"):
# Jython always uses 32 bits.
MAXSIZE = int((1 << 31) - 1)
else:
# It's possible to have sizeof(long) != sizeof(Py_ssize_t).
class X(object):
def __len__(self):
return 1 << 31
try:
len(X())
except OverflowError:
# 32-bit
MAXSIZE = int((1 << 31) - 1)
else:
# 64-bit
MAXSIZE = int((1 << 63) - 1)
del X
if PY3:
xrange = range
unicode = str
bytes = bytes
def iterkeys(d, **kw):
if hasattr(d, 'iterkeys'):
return iter(d.iterkeys(**kw))
return iter(d.keys(**kw))
def itervalues(d, **kw):
if hasattr(d, 'itervalues'):
return iter(d.itervalues(**kw))
return iter(d.values(**kw))
def iteritems(d, **kw):
if hasattr(d, 'iteritems'):
return iter(d.iteritems(**kw))
return iter(d.items(**kw))
def iterlists(d, **kw):
if hasattr(d, 'iterlists'):
return iter(d.iterlists(**kw))
return iter(d.lists(**kw))
def keys(d, **kw):
return list(iterkeys(d, **kw))
else:
unicode = unicode
xrange = xrange
bytes = str
def keys(d, **kw):
return d.keys(**kw)
def iterkeys(d, **kw):
return iter(d.iterkeys(**kw))
def itervalues(d, **kw):
return iter(d.itervalues(**kw))
def iteritems(d, **kw):
return iter(d.iteritems(**kw))
def iterlists(d, **kw):
return iter(d.iterlists(**kw))
if PY3:
import builtins
exec_ = getattr(builtins, "exec")
def reraise(tp, value, tb=None):
if value is None:
value = tp()
if value.__traceback__ is not tb:
raise value.with_traceback(tb)
raise value
else:
def exec_(_code_, _globs_=None, _locs_=None):
"""Execute code in a namespace."""
if _globs_ is None:
frame = sys._getframe(1)
_globs_ = frame.f_globals
if _locs_ is None:
_locs_ = frame.f_locals
del frame
elif _locs_ is None:
_locs_ = _globs_
exec("""exec _code_ in _globs_, _locs_""")
exec_("""def reraise(tp, value, tb=None):
raise tp, value, tb
""")
if PY3:
import operator
def b(s):
if isinstance(s, str):
return s.encode("latin-1")
assert isinstance(s, bytes)
return s
def u(s):
return s
unichr = chr
if sys.version_info[1] <= 1:
def int2byte(i):
return bytes((i,))
else:
# This is about 2x faster than the implementation above on 3.2+
int2byte = operator.methodcaller("to_bytes", 1, "big")
byte2int = operator.itemgetter(0)
indexbytes = operator.getitem
iterbytes = iter
import io
StringIO = io.StringIO
BytesIO = io.BytesIO
else:
def b(s):
return s
# Workaround for standalone backslash
def u(s):
return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape")
unichr = unichr
int2byte = chr
def byte2int(bs):
return ord(bs[0])
def indexbytes(buf, i):
return ord(buf[i])
def iterbytes(buf):
return (ord(byte) for byte in buf)
import StringIO
StringIO = BytesIO = StringIO.StringIO | 5,230 | Python | 27.584699 | 115 | 0.600765 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/disasm.py | #!~/.wine/drive_c/Python25/python.exe
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Binary code disassembly.
@group Disassembler loader:
Disassembler, Engine
@group Disassembler engines:
BeaEngine, CapstoneEngine, DistormEngine,
LibdisassembleEngine, PyDasmEngine
"""
from __future__ import with_statement
__revision__ = "$Id$"
__all__ = [
'Disassembler',
'Engine',
'BeaEngine',
'CapstoneEngine',
'DistormEngine',
'LibdisassembleEngine',
'PyDasmEngine',
]
from winappdbg.textio import HexDump
from winappdbg import win32
import ctypes
import warnings
# lazy imports
BeaEnginePython = None
distorm3 = None
pydasm = None
libdisassemble = None
capstone = None
#==============================================================================
class Engine (object):
"""
Base class for disassembly engine adaptors.
@type name: str
@cvar name: Engine name to use with the L{Disassembler} class.
@type desc: str
@cvar desc: User friendly name of the disassembler engine.
@type url: str
@cvar url: Download URL.
@type supported: set(str)
@cvar supported: Set of supported processor architectures.
For more details see L{win32.version._get_arch}.
@type arch: str
@ivar arch: Name of the processor architecture.
"""
name = "<insert engine name here>"
desc = "<insert engine description here>"
url = "<insert download url here>"
supported = set()
def __init__(self, arch = None):
"""
@type arch: str
@param arch: Name of the processor architecture.
If not provided the current processor architecture is assumed.
For more details see L{win32.version._get_arch}.
@raise NotImplementedError: This disassembler doesn't support the
requested processor architecture.
"""
self.arch = self._validate_arch(arch)
try:
self._import_dependencies()
except ImportError:
msg = "%s is not installed or can't be found. Download it from: %s"
msg = msg % (self.name, self.url)
raise NotImplementedError(msg)
def _validate_arch(self, arch = None):
"""
@type arch: str
@param arch: Name of the processor architecture.
If not provided the current processor architecture is assumed.
For more details see L{win32.version._get_arch}.
@rtype: str
@return: Name of the processor architecture.
If not provided the current processor architecture is assumed.
For more details see L{win32.version._get_arch}.
@raise NotImplementedError: This disassembler doesn't support the
requested processor architecture.
"""
# Use the default architecture if none specified.
if not arch:
arch = win32.arch
# Validate the architecture.
if arch not in self.supported:
msg = "The %s engine cannot decode %s code."
msg = msg % (self.name, arch)
raise NotImplementedError(msg)
# Return the architecture.
return arch
def _import_dependencies(self):
"""
Loads the dependencies for this disassembler.
@raise ImportError: This disassembler cannot find or load the
necessary dependencies to make it work.
"""
raise SyntaxError("Subclasses MUST implement this method!")
def decode(self, address, code):
"""
@type address: int
@param address: Memory address where the code was read from.
@type code: str
@param code: Machine code to disassemble.
@rtype: list of tuple( long, int, str, str )
@return: List of tuples. Each tuple represents an assembly instruction
and contains:
- Memory address of instruction.
- Size of instruction in bytes.
- Disassembly line of instruction.
- Hexadecimal dump of instruction.
@raise NotImplementedError: This disassembler could not be loaded.
This may be due to missing dependencies.
"""
raise NotImplementedError()
#==============================================================================
class BeaEngine (Engine):
"""
Integration with the BeaEngine disassembler by Beatrix.
@see: U{https://sourceforge.net/projects/winappdbg/files/additional%20packages/BeaEngine/}
"""
name = "BeaEngine"
desc = "BeaEngine disassembler by Beatrix"
url = "https://sourceforge.net/projects/winappdbg/files/additional%20packages/BeaEngine/"
supported = set((
win32.ARCH_I386,
win32.ARCH_AMD64,
))
def _import_dependencies(self):
# Load the BeaEngine ctypes wrapper.
global BeaEnginePython
if BeaEnginePython is None:
import BeaEnginePython
def decode(self, address, code):
addressof = ctypes.addressof
# Instance the code buffer.
buffer = ctypes.create_string_buffer(code)
buffer_ptr = addressof(buffer)
# Instance the disassembler structure.
Instruction = BeaEnginePython.DISASM()
Instruction.VirtualAddr = address
Instruction.EIP = buffer_ptr
Instruction.SecurityBlock = buffer_ptr + len(code)
if self.arch == win32.ARCH_I386:
Instruction.Archi = 0
else:
Instruction.Archi = 0x40
Instruction.Options = ( BeaEnginePython.Tabulation +
BeaEnginePython.NasmSyntax +
BeaEnginePython.SuffixedNumeral +
BeaEnginePython.ShowSegmentRegs )
# Prepare for looping over each instruction.
result = []
Disasm = BeaEnginePython.Disasm
InstructionPtr = addressof(Instruction)
hexdump = HexDump.hexadecimal
append = result.append
OUT_OF_BLOCK = BeaEnginePython.OUT_OF_BLOCK
UNKNOWN_OPCODE = BeaEnginePython.UNKNOWN_OPCODE
# For each decoded instruction...
while True:
# Calculate the current offset into the buffer.
offset = Instruction.EIP - buffer_ptr
# If we've gone past the buffer, break the loop.
if offset >= len(code):
break
# Decode the current instruction.
InstrLength = Disasm(InstructionPtr)
# If BeaEngine detects we've gone past the buffer, break the loop.
if InstrLength == OUT_OF_BLOCK:
break
# The instruction could not be decoded.
if InstrLength == UNKNOWN_OPCODE:
# Output a single byte as a "db" instruction.
char = "%.2X" % ord(buffer[offset])
result.append((
Instruction.VirtualAddr,
1,
"db %sh" % char,
char,
))
Instruction.VirtualAddr += 1
Instruction.EIP += 1
# The instruction was decoded but reading past the buffer's end.
# This can happen when the last instruction is a prefix without an
# opcode. For example: decode(0, '\x66')
elif offset + InstrLength > len(code):
# Output each byte as a "db" instruction.
for char in buffer[ offset : offset + len(code) ]:
char = "%.2X" % ord(char)
result.append((
Instruction.VirtualAddr,
1,
"db %sh" % char,
char,
))
Instruction.VirtualAddr += 1
Instruction.EIP += 1
# The instruction was decoded correctly.
else:
# Output the decoded instruction.
append((
Instruction.VirtualAddr,
InstrLength,
Instruction.CompleteInstr.strip(),
hexdump(buffer.raw[offset:offset+InstrLength]),
))
Instruction.VirtualAddr += InstrLength
Instruction.EIP += InstrLength
# Return the list of decoded instructions.
return result
#==============================================================================
class DistormEngine (Engine):
"""
Integration with the diStorm disassembler by Gil Dabah.
@see: U{https://code.google.com/p/distorm3}
"""
name = "diStorm"
desc = "diStorm disassembler by Gil Dabah"
url = "https://code.google.com/p/distorm3"
supported = set((
win32.ARCH_I386,
win32.ARCH_AMD64,
))
def _import_dependencies(self):
# Load the distorm bindings.
global distorm3
if distorm3 is None:
try:
import distorm3
except ImportError:
import distorm as distorm3
# Load the decoder function.
self.__decode = distorm3.Decode
# Load the bits flag.
self.__flag = {
win32.ARCH_I386: distorm3.Decode32Bits,
win32.ARCH_AMD64: distorm3.Decode64Bits,
}[self.arch]
def decode(self, address, code):
return self.__decode(address, code, self.__flag)
#==============================================================================
class PyDasmEngine (Engine):
"""
Integration with PyDasm: Python bindings to libdasm.
@see: U{https://code.google.com/p/libdasm/}
"""
name = "PyDasm"
desc = "PyDasm: Python bindings to libdasm"
url = "https://code.google.com/p/libdasm/"
supported = set((
win32.ARCH_I386,
))
def _import_dependencies(self):
# Load the libdasm bindings.
global pydasm
if pydasm is None:
import pydasm
def decode(self, address, code):
# Decode each instruction in the buffer.
result = []
offset = 0
while offset < len(code):
# Try to decode the current instruction.
instruction = pydasm.get_instruction(code[offset:offset+32],
pydasm.MODE_32)
# Get the memory address of the current instruction.
current = address + offset
# Illegal opcode or opcode longer than remaining buffer.
if not instruction or instruction.length + offset > len(code):
hexdump = '%.2X' % ord(code[offset])
disasm = 'db 0x%s' % hexdump
ilen = 1
# Correctly decoded instruction.
else:
disasm = pydasm.get_instruction_string(instruction,
pydasm.FORMAT_INTEL,
current)
ilen = instruction.length
hexdump = HexDump.hexadecimal(code[offset:offset+ilen])
# Add the decoded instruction to the list.
result.append((
current,
ilen,
disasm,
hexdump,
))
# Move to the next instruction.
offset += ilen
# Return the list of decoded instructions.
return result
#==============================================================================
class LibdisassembleEngine (Engine):
"""
Integration with Immunity libdisassemble.
@see: U{http://www.immunitysec.com/resources-freesoftware.shtml}
"""
name = "Libdisassemble"
desc = "Immunity libdisassemble"
url = "http://www.immunitysec.com/resources-freesoftware.shtml"
supported = set((
win32.ARCH_I386,
))
def _import_dependencies(self):
# Load the libdisassemble module.
# Since it doesn't come with an installer or an __init__.py file
# users can only install it manually however they feel like it,
# so we'll have to do a bit of guessing to find it.
global libdisassemble
if libdisassemble is None:
try:
# If installed properly with __init__.py
import libdisassemble.disassemble as libdisassemble
except ImportError:
# If installed by just copying and pasting the files
import disassemble as libdisassemble
def decode(self, address, code):
# Decode each instruction in the buffer.
result = []
offset = 0
while offset < len(code):
# Decode the current instruction.
opcode = libdisassemble.Opcode( code[offset:offset+32] )
length = opcode.getSize()
disasm = opcode.printOpcode('INTEL')
hexdump = HexDump.hexadecimal( code[offset:offset+length] )
# Add the decoded instruction to the list.
result.append((
address + offset,
length,
disasm,
hexdump,
))
# Move to the next instruction.
offset += length
# Return the list of decoded instructions.
return result
#==============================================================================
class CapstoneEngine (Engine):
"""
Integration with the Capstone disassembler by Nguyen Anh Quynh.
@see: U{http://www.capstone-engine.org/}
"""
name = "Capstone"
desc = "Capstone disassembler by Nguyen Anh Quynh"
url = "http://www.capstone-engine.org/"
supported = set((
win32.ARCH_I386,
win32.ARCH_AMD64,
win32.ARCH_THUMB,
win32.ARCH_ARM,
win32.ARCH_ARM64,
))
def _import_dependencies(self):
# Load the Capstone bindings.
global capstone
if capstone is None:
import capstone
# Load the constants for the requested architecture.
self.__constants = {
win32.ARCH_I386:
(capstone.CS_ARCH_X86, capstone.CS_MODE_32),
win32.ARCH_AMD64:
(capstone.CS_ARCH_X86, capstone.CS_MODE_64),
win32.ARCH_THUMB:
(capstone.CS_ARCH_ARM, capstone.CS_MODE_THUMB),
win32.ARCH_ARM:
(capstone.CS_ARCH_ARM, capstone.CS_MODE_ARM),
win32.ARCH_ARM64:
(capstone.CS_ARCH_ARM64, capstone.CS_MODE_ARM),
}
# Test for the bug in early versions of Capstone.
# If found, warn the user about it.
try:
self.__bug = not isinstance(
capstone.cs_disasm_quick(
capstone.CS_ARCH_X86, capstone.CS_MODE_32, "\x90", 1)[0],
capstone.capstone.CsInsn)
except AttributeError:
self.__bug = False
if self.__bug:
warnings.warn(
"This version of the Capstone bindings is unstable,"
" please upgrade to a newer one!",
RuntimeWarning, stacklevel=4)
def decode(self, address, code):
# Get the constants for the requested architecture.
arch, mode = self.__constants[self.arch]
# Get the decoder function outside the loop.
decoder = capstone.cs_disasm_quick
# If the buggy version of the bindings are being used, we need to catch
# all exceptions broadly. If not, we only need to catch CsError.
if self.__bug:
CsError = Exception
else:
CsError = capstone.CsError
# Create the variables for the instruction length, mnemonic and
# operands. That way they won't be created within the loop,
# minimizing the chances data might be overwritten.
# This only makes sense for the buggy vesion of the bindings, normally
# memory accesses are safe).
length = mnemonic = op_str = None
# For each instruction...
result = []
offset = 0
while offset < len(code):
# Disassemble a single instruction, because disassembling multiple
# instructions may cause excessive memory usage (Capstone allocates
# approximately 1K of metadata per each decoded instruction).
instr = None
try:
instr = decoder(
arch, mode, code[offset:offset+16], address+offset, 1)[0]
except IndexError:
pass # No instructions decoded.
except CsError:
pass # Any other error.
# On success add the decoded instruction.
if instr is not None:
# Get the instruction length, mnemonic and operands.
# Copy the values quickly before someone overwrites them,
# if using the buggy version of the bindings (otherwise it's
# irrelevant in which order we access the properties).
length = instr.size
mnemonic = instr.mnemonic
op_str = instr.op_str
# Concatenate the mnemonic and the operands.
if op_str:
disasm = "%s %s" % (mnemonic, op_str)
else:
disasm = mnemonic
# Get the instruction bytes as a hexadecimal dump.
hexdump = HexDump.hexadecimal( code[offset:offset+length] )
# On error add a "define constant" instruction.
# The exact instruction depends on the architecture.
else:
# The number of bytes to skip depends on the architecture.
# On Intel processors we'll skip one byte, since we can't
# really know the instruction length. On the rest of the
# architectures we always know the instruction length.
if self.arch in (win32.ARCH_I386, win32.ARCH_AMD64):
length = 1
else:
length = 4
# Get the skipped bytes as a hexadecimal dump.
skipped = code[offset:offset+length]
hexdump = HexDump.hexadecimal(skipped)
# Build the "define constant" instruction.
# On Intel processors it's "db".
# On ARM processors it's "dcb".
if self.arch in (win32.ARCH_I386, win32.ARCH_AMD64):
mnemonic = "db "
else:
mnemonic = "dcb "
bytes = []
for b in skipped:
if b.isalpha():
bytes.append("'%s'" % b)
else:
bytes.append("0x%x" % ord(b))
op_str = ", ".join(bytes)
disasm = mnemonic + op_str
# Add the decoded instruction to the list.
result.append((
address + offset,
length,
disasm,
hexdump,
))
# Update the offset.
offset += length
# Return the list of decoded instructions.
return result
#==============================================================================
# TODO: use a lock to access __decoder
# TODO: look in sys.modules for whichever disassembler is already loaded
class Disassembler (object):
"""
Generic disassembler. Uses a set of adapters to decide which library to
load for which supported platform.
@type engines: tuple( L{Engine} )
@cvar engines: Set of supported engines. If you implement your own adapter
you can add its class here to make it available to L{Disassembler}.
Supported disassemblers are:
"""
engines = (
DistormEngine, # diStorm engine goes first for backwards compatibility
BeaEngine,
CapstoneEngine,
LibdisassembleEngine,
PyDasmEngine,
)
# Add the list of supported disassemblers to the docstring.
__doc__ += "\n"
for e in engines:
__doc__ += " - %s - %s (U{%s})\n" % (e.name, e.desc, e.url)
del e
# Cache of already loaded disassemblers.
__decoder = {}
def __new__(cls, arch = None, engine = None):
"""
Factory class. You can't really instance a L{Disassembler} object,
instead one of the adapter L{Engine} subclasses is returned.
@type arch: str
@param arch: (Optional) Name of the processor architecture.
If not provided the current processor architecture is assumed.
For more details see L{win32.version._get_arch}.
@type engine: str
@param engine: (Optional) Name of the disassembler engine.
If not provided a compatible one is loaded automatically.
See: L{Engine.name}
@raise NotImplementedError: No compatible disassembler was found that
could decode machine code for the requested architecture. This may
be due to missing dependencies.
@raise ValueError: An unknown engine name was supplied.
"""
# Use the default architecture if none specified.
if not arch:
arch = win32.arch
# Return a compatible engine if none specified.
if not engine:
found = False
for clazz in cls.engines:
try:
if arch in clazz.supported:
selected = (clazz.name, arch)
try:
decoder = cls.__decoder[selected]
except KeyError:
decoder = clazz(arch)
cls.__decoder[selected] = decoder
return decoder
except NotImplementedError:
pass
msg = "No disassembler engine available for %s code." % arch
raise NotImplementedError(msg)
# Return the specified engine.
selected = (engine, arch)
try:
decoder = cls.__decoder[selected]
except KeyError:
found = False
engineLower = engine.lower()
for clazz in cls.engines:
if clazz.name.lower() == engineLower:
found = True
break
if not found:
msg = "Unsupported disassembler engine: %s" % engine
raise ValueError(msg)
if arch not in clazz.supported:
msg = "The %s engine cannot decode %s code." % selected
raise NotImplementedError(msg)
decoder = clazz(arch)
cls.__decoder[selected] = decoder
return decoder
| 24,409 | Python | 32.762102 | 94 | 0.559015 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/system.py | #!~/.wine/drive_c/Python25/python.exe
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
System settings.
@group Instrumentation:
System
"""
from __future__ import with_statement
__revision__ = "$Id$"
__all__ = ['System']
from winappdbg import win32
from winappdbg.registry import Registry
from winappdbg.textio import HexInput, HexDump
from winappdbg.util import Regenerator, PathOperations, MemoryAddresses, DebugRegister, \
classproperty
from winappdbg.process import _ProcessContainer
from winappdbg.window import Window
import sys
import os
import ctypes
import warnings
from os import path, getenv
#==============================================================================
class System (_ProcessContainer):
"""
Interface to a batch of processes, plus some system wide settings.
Contains a snapshot of processes.
@group Platform settings:
arch, bits, os, wow64, pageSize
@group Instrumentation:
find_window, get_window_at, get_foreground_window,
get_desktop_window, get_shell_window
@group Debugging:
load_dbghelp, fix_symbol_store_path,
request_debug_privileges, drop_debug_privileges
@group Postmortem debugging:
get_postmortem_debugger, set_postmortem_debugger,
get_postmortem_exclusion_list, add_to_postmortem_exclusion_list,
remove_from_postmortem_exclusion_list
@group System services:
get_services, get_active_services,
start_service, stop_service,
pause_service, resume_service,
get_service_display_name, get_service_from_display_name
@group Permissions and privileges:
request_privileges, drop_privileges, adjust_privileges, is_admin
@group Miscellaneous global settings:
set_kill_on_exit_mode, read_msr, write_msr, enable_step_on_branch_mode,
get_last_branch_location
@type arch: str
@cvar arch: Name of the processor architecture we're running on.
For more details see L{win32.version._get_arch}.
@type bits: int
@cvar bits: Size of the machine word in bits for the current architecture.
For more details see L{win32.version._get_bits}.
@type os: str
@cvar os: Name of the Windows version we're runing on.
For more details see L{win32.version._get_os}.
@type wow64: bool
@cvar wow64: C{True} if the debugger is a 32 bits process running in a 64
bits version of Windows, C{False} otherwise.
@type pageSize: int
@cvar pageSize: Page size in bytes. Defaults to 0x1000 but it's
automatically updated on runtime when importing the module.
@type registry: L{Registry}
@cvar registry: Windows Registry for this machine.
"""
arch = win32.arch
bits = win32.bits
os = win32.os
wow64 = win32.wow64
@classproperty
def pageSize(cls):
pageSize = MemoryAddresses.pageSize
cls.pageSize = pageSize
return pageSize
registry = Registry()
#------------------------------------------------------------------------------
@staticmethod
def find_window(className = None, windowName = None):
"""
Find the first top-level window in the current desktop to match the
given class name and/or window name. If neither are provided any
top-level window will match.
@see: L{get_window_at}
@type className: str
@param className: (Optional) Class name of the window to find.
If C{None} or not used any class name will match the search.
@type windowName: str
@param windowName: (Optional) Caption text of the window to find.
If C{None} or not used any caption text will match the search.
@rtype: L{Window} or None
@return: A window that matches the request. There may be more matching
windows, but this method only returns one. If no matching window
is found, the return value is C{None}.
@raise WindowsError: An error occured while processing this request.
"""
# I'd love to reverse the order of the parameters
# but that might create some confusion. :(
hWnd = win32.FindWindow(className, windowName)
if hWnd:
return Window(hWnd)
@staticmethod
def get_window_at(x, y):
"""
Get the window located at the given coordinates in the desktop.
If no such window exists an exception is raised.
@see: L{find_window}
@type x: int
@param x: Horizontal coordinate.
@type y: int
@param y: Vertical coordinate.
@rtype: L{Window}
@return: Window at the requested position. If no such window
exists a C{WindowsError} exception is raised.
@raise WindowsError: An error occured while processing this request.
"""
return Window( win32.WindowFromPoint( (x, y) ) )
@staticmethod
def get_foreground_window():
"""
@rtype: L{Window}
@return: Returns the foreground window.
@raise WindowsError: An error occured while processing this request.
"""
return Window( win32.GetForegroundWindow() )
@staticmethod
def get_desktop_window():
"""
@rtype: L{Window}
@return: Returns the desktop window.
@raise WindowsError: An error occured while processing this request.
"""
return Window( win32.GetDesktopWindow() )
@staticmethod
def get_shell_window():
"""
@rtype: L{Window}
@return: Returns the shell window.
@raise WindowsError: An error occured while processing this request.
"""
return Window( win32.GetShellWindow() )
#------------------------------------------------------------------------------
@classmethod
def request_debug_privileges(cls, bIgnoreExceptions = False):
"""
Requests debug privileges.
This may be needed to debug processes running as SYSTEM
(such as services) since Windows XP.
@type bIgnoreExceptions: bool
@param bIgnoreExceptions: C{True} to ignore any exceptions that may be
raised when requesting debug privileges.
@rtype: bool
@return: C{True} on success, C{False} on failure.
@raise WindowsError: Raises an exception on error, unless
C{bIgnoreExceptions} is C{True}.
"""
try:
cls.request_privileges(win32.SE_DEBUG_NAME)
return True
except Exception:
if not bIgnoreExceptions:
raise
return False
@classmethod
def drop_debug_privileges(cls, bIgnoreExceptions = False):
"""
Drops debug privileges.
This may be needed to avoid being detected
by certain anti-debug tricks.
@type bIgnoreExceptions: bool
@param bIgnoreExceptions: C{True} to ignore any exceptions that may be
raised when dropping debug privileges.
@rtype: bool
@return: C{True} on success, C{False} on failure.
@raise WindowsError: Raises an exception on error, unless
C{bIgnoreExceptions} is C{True}.
"""
try:
cls.drop_privileges(win32.SE_DEBUG_NAME)
return True
except Exception:
if not bIgnoreExceptions:
raise
return False
@classmethod
def request_privileges(cls, *privileges):
"""
Requests privileges.
@type privileges: int...
@param privileges: Privileges to request.
@raise WindowsError: Raises an exception on error.
"""
cls.adjust_privileges(True, privileges)
@classmethod
def drop_privileges(cls, *privileges):
"""
Drops privileges.
@type privileges: int...
@param privileges: Privileges to drop.
@raise WindowsError: Raises an exception on error.
"""
cls.adjust_privileges(False, privileges)
@staticmethod
def adjust_privileges(state, privileges):
"""
Requests or drops privileges.
@type state: bool
@param state: C{True} to request, C{False} to drop.
@type privileges: list(int)
@param privileges: Privileges to request or drop.
@raise WindowsError: Raises an exception on error.
"""
with win32.OpenProcessToken(win32.GetCurrentProcess(),
win32.TOKEN_ADJUST_PRIVILEGES) as hToken:
NewState = ( (priv, state) for priv in privileges )
win32.AdjustTokenPrivileges(hToken, NewState)
@staticmethod
def is_admin():
"""
@rtype: bool
@return: C{True} if the current user as Administrator privileges,
C{False} otherwise. Since Windows Vista and above this means if
the current process is running with UAC elevation or not.
"""
return win32.IsUserAnAdmin()
#------------------------------------------------------------------------------
__binary_types = {
win32.VFT_APP: "application",
win32.VFT_DLL: "dynamic link library",
win32.VFT_STATIC_LIB: "static link library",
win32.VFT_FONT: "font",
win32.VFT_DRV: "driver",
win32.VFT_VXD: "legacy driver",
}
__driver_types = {
win32.VFT2_DRV_COMM: "communications driver",
win32.VFT2_DRV_DISPLAY: "display driver",
win32.VFT2_DRV_INSTALLABLE: "installable driver",
win32.VFT2_DRV_KEYBOARD: "keyboard driver",
win32.VFT2_DRV_LANGUAGE: "language driver",
win32.VFT2_DRV_MOUSE: "mouse driver",
win32.VFT2_DRV_NETWORK: "network driver",
win32.VFT2_DRV_PRINTER: "printer driver",
win32.VFT2_DRV_SOUND: "sound driver",
win32.VFT2_DRV_SYSTEM: "system driver",
win32.VFT2_DRV_VERSIONED_PRINTER: "versioned printer driver",
}
__font_types = {
win32.VFT2_FONT_RASTER: "raster font",
win32.VFT2_FONT_TRUETYPE: "TrueType font",
win32.VFT2_FONT_VECTOR: "vector font",
}
__months = (
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
)
__days_of_the_week = (
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
)
@classmethod
def get_file_version_info(cls, filename):
"""
Get the program version from an executable file, if available.
@type filename: str
@param filename: Pathname to the executable file to query.
@rtype: tuple(str, str, bool, bool, str, str)
@return: Tuple with version information extracted from the executable
file metadata, containing the following:
- File version number (C{"major.minor"}).
- Product version number (C{"major.minor"}).
- C{True} for debug builds, C{False} for production builds.
- C{True} for legacy OS builds (DOS, OS/2, Win16),
C{False} for modern OS builds.
- Binary file type.
May be one of the following values:
- "application"
- "dynamic link library"
- "static link library"
- "font"
- "raster font"
- "TrueType font"
- "vector font"
- "driver"
- "communications driver"
- "display driver"
- "installable driver"
- "keyboard driver"
- "language driver"
- "legacy driver"
- "mouse driver"
- "network driver"
- "printer driver"
- "sound driver"
- "system driver"
- "versioned printer driver"
- Binary creation timestamp.
Any of the fields may be C{None} if not available.
@raise WindowsError: Raises an exception on error.
"""
# Get the file version info structure.
pBlock = win32.GetFileVersionInfo(filename)
pBuffer, dwLen = win32.VerQueryValue(pBlock, "\\")
if dwLen != ctypes.sizeof(win32.VS_FIXEDFILEINFO):
raise ctypes.WinError(win32.ERROR_BAD_LENGTH)
pVersionInfo = ctypes.cast(pBuffer,
ctypes.POINTER(win32.VS_FIXEDFILEINFO))
VersionInfo = pVersionInfo.contents
if VersionInfo.dwSignature != 0xFEEF04BD:
raise ctypes.WinError(win32.ERROR_BAD_ARGUMENTS)
# File and product versions.
FileVersion = "%d.%d" % (VersionInfo.dwFileVersionMS,
VersionInfo.dwFileVersionLS)
ProductVersion = "%d.%d" % (VersionInfo.dwProductVersionMS,
VersionInfo.dwProductVersionLS)
# Debug build?
if VersionInfo.dwFileFlagsMask & win32.VS_FF_DEBUG:
DebugBuild = (VersionInfo.dwFileFlags & win32.VS_FF_DEBUG) != 0
else:
DebugBuild = None
# Legacy OS build?
LegacyBuild = (VersionInfo.dwFileOS != win32.VOS_NT_WINDOWS32)
# File type.
FileType = cls.__binary_types.get(VersionInfo.dwFileType)
if VersionInfo.dwFileType == win32.VFT_DRV:
FileType = cls.__driver_types.get(VersionInfo.dwFileSubtype)
elif VersionInfo.dwFileType == win32.VFT_FONT:
FileType = cls.__font_types.get(VersionInfo.dwFileSubtype)
# Timestamp, ex: "Monday, July 7, 2013 (12:20:50.126)".
# FIXME: how do we know the time zone?
FileDate = (VersionInfo.dwFileDateMS << 32) + VersionInfo.dwFileDateLS
if FileDate:
CreationTime = win32.FileTimeToSystemTime(FileDate)
CreationTimestamp = "%s, %s %d, %d (%d:%d:%d.%d)" % (
cls.__days_of_the_week[CreationTime.wDayOfWeek],
cls.__months[CreationTime.wMonth],
CreationTime.wDay,
CreationTime.wYear,
CreationTime.wHour,
CreationTime.wMinute,
CreationTime.wSecond,
CreationTime.wMilliseconds,
)
else:
CreationTimestamp = None
# Return the file version info.
return (
FileVersion,
ProductVersion,
DebugBuild,
LegacyBuild,
FileType,
CreationTimestamp,
)
#------------------------------------------------------------------------------
# Locations for dbghelp.dll.
# Unfortunately, Microsoft started bundling WinDbg with the
# platform SDK, so the install directories may vary across
# versions and platforms.
__dbghelp_locations = {
# Intel 64 bits.
win32.ARCH_AMD64: set([
# WinDbg bundled with the SDK, version 8.0.
path.join(
getenv("ProgramFiles", "C:\\Program Files"),
"Windows Kits",
"8.0",
"Debuggers",
"x64",
"dbghelp.dll"),
path.join(
getenv("ProgramW6432", getenv("ProgramFiles",
"C:\\Program Files")),
"Windows Kits",
"8.0",
"Debuggers",
"x64",
"dbghelp.dll"),
# Old standalone versions of WinDbg.
path.join(
getenv("ProgramFiles", "C:\\Program Files"),
"Debugging Tools for Windows (x64)",
"dbghelp.dll"),
]),
# Intel 32 bits.
win32.ARCH_I386 : set([
# WinDbg bundled with the SDK, version 8.0.
path.join(
getenv("ProgramFiles", "C:\\Program Files"),
"Windows Kits",
"8.0",
"Debuggers",
"x86",
"dbghelp.dll"),
path.join(
getenv("ProgramW6432", getenv("ProgramFiles",
"C:\\Program Files")),
"Windows Kits",
"8.0",
"Debuggers",
"x86",
"dbghelp.dll"),
# Old standalone versions of WinDbg.
path.join(
getenv("ProgramFiles", "C:\\Program Files"),
"Debugging Tools for Windows (x86)",
"dbghelp.dll"),
# Version shipped with Windows.
path.join(
getenv("ProgramFiles", "C:\\Program Files"),
"Debugging Tools for Windows (x86)",
"dbghelp.dll"),
]),
}
@classmethod
def load_dbghelp(cls, pathname = None):
"""
Load the specified version of the C{dbghelp.dll} library.
This library is shipped with the Debugging Tools for Windows, and it's
required to load debug symbols.
Normally you don't need to call this method, as WinAppDbg already tries
to load the latest version automatically - but it may come in handy if
the Debugging Tools are installed in a non standard folder.
Example::
from winappdbg import Debug
def simple_debugger( argv ):
# Instance a Debug object, passing it the event handler callback
debug = Debug( my_event_handler )
try:
# Load a specific dbghelp.dll file
debug.system.load_dbghelp("C:\\Some folder\\dbghelp.dll")
# Start a new process for debugging
debug.execv( argv )
# Wait for the debugee to finish
debug.loop()
# Stop the debugger
finally:
debug.stop()
@see: U{http://msdn.microsoft.com/en-us/library/ms679294(VS.85).aspx}
@type pathname: str
@param pathname:
(Optional) Full pathname to the C{dbghelp.dll} library.
If not provided this method will try to autodetect it.
@rtype: ctypes.WinDLL
@return: Loaded instance of C{dbghelp.dll}.
@raise NotImplementedError: This feature was not implemented for the
current architecture.
@raise WindowsError: An error occured while processing this request.
"""
# If an explicit pathname was not given, search for the library.
if not pathname:
# Under WOW64 we'll treat AMD64 as I386.
arch = win32.arch
if arch == win32.ARCH_AMD64 and win32.bits == 32:
arch = win32.ARCH_I386
# Check if the architecture is supported.
if not arch in cls.__dbghelp_locations:
msg = "Architecture %s is not currently supported."
raise NotImplementedError(msg % arch)
# Grab all versions of the library we can find.
found = []
for pathname in cls.__dbghelp_locations[arch]:
if path.isfile(pathname):
try:
f_ver, p_ver = cls.get_file_version_info(pathname)[:2]
except WindowsError:
msg = "Failed to parse file version metadata for: %s"
warnings.warn(msg % pathname)
if not f_ver:
f_ver = p_ver
elif p_ver and p_ver > f_ver:
f_ver = p_ver
found.append( (f_ver, pathname) )
# If we found any, use the newest version.
if found:
found.sort()
pathname = found.pop()[1]
# If we didn't find any, trust the default DLL search algorithm.
else:
pathname = "dbghelp.dll"
# Load the library.
dbghelp = ctypes.windll.LoadLibrary(pathname)
# Set it globally as the library to be used.
ctypes.windll.dbghelp = dbghelp
# Return the library.
return dbghelp
@staticmethod
def fix_symbol_store_path(symbol_store_path = None,
remote = True,
force = False):
"""
Fix the symbol store path. Equivalent to the C{.symfix} command in
Microsoft WinDbg.
If the symbol store path environment variable hasn't been set, this
method will provide a default one.
@type symbol_store_path: str or None
@param symbol_store_path: (Optional) Symbol store path to set.
@type remote: bool
@param remote: (Optional) Defines the symbol store path to set when the
C{symbol_store_path} is C{None}.
If C{True} the default symbol store path is set to the Microsoft
symbol server. Debug symbols will be downloaded through HTTP.
This gives the best results but is also quite slow.
If C{False} the default symbol store path is set to the local
cache only. This prevents debug symbols from being downloaded and
is faster, but unless you've installed the debug symbols on this
machine or downloaded them in a previous debugging session, some
symbols may be missing.
If the C{symbol_store_path} argument is not C{None}, this argument
is ignored entirely.
@type force: bool
@param force: (Optional) If C{True} the new symbol store path is set
always. If C{False} the new symbol store path is only set if
missing.
This allows you to call this method preventively to ensure the
symbol server is always set up correctly when running your script,
but without messing up whatever configuration the user has.
Example::
from winappdbg import Debug, System
def simple_debugger( argv ):
# Instance a Debug object
debug = Debug( MyEventHandler() )
try:
# Make sure the remote symbol store is set
System.fix_symbol_store_path(remote = True,
force = False)
# Start a new process for debugging
debug.execv( argv )
# Wait for the debugee to finish
debug.loop()
# Stop the debugger
finally:
debug.stop()
@rtype: str or None
@return: The previously set symbol store path if any,
otherwise returns C{None}.
"""
try:
if symbol_store_path is None:
local_path = "C:\\SYMBOLS"
if not path.isdir(local_path):
local_path = "C:\\Windows\\Symbols"
if not path.isdir(local_path):
local_path = path.abspath(".")
if remote:
symbol_store_path = (
"cache*;SRV*"
+ local_path +
"*"
"http://msdl.microsoft.com/download/symbols"
)
else:
symbol_store_path = "cache*;SRV*" + local_path
previous = os.environ.get("_NT_SYMBOL_PATH", None)
if not previous or force:
os.environ["_NT_SYMBOL_PATH"] = symbol_store_path
return previous
except Exception:
e = sys.exc_info()[1]
warnings.warn("Cannot fix symbol path, reason: %s" % str(e),
RuntimeWarning)
#------------------------------------------------------------------------------
@staticmethod
def set_kill_on_exit_mode(bKillOnExit = False):
"""
Defines the behavior of the debugged processes when the debugging
thread dies. This method only affects the calling thread.
Works on the following platforms:
- Microsoft Windows XP and above.
- Wine (Windows Emulator).
Fails on the following platforms:
- Microsoft Windows 2000 and below.
- ReactOS.
@type bKillOnExit: bool
@param bKillOnExit: C{True} to automatically kill processes when the
debugger thread dies. C{False} to automatically detach from
processes when the debugger thread dies.
@rtype: bool
@return: C{True} on success, C{False} on error.
@note:
This call will fail if a debug port was not created. That is, if
the debugger isn't attached to at least one process. For more info
see: U{http://msdn.microsoft.com/en-us/library/ms679307.aspx}
"""
try:
# won't work before calling CreateProcess or DebugActiveProcess
win32.DebugSetProcessKillOnExit(bKillOnExit)
except (AttributeError, WindowsError):
return False
return True
@staticmethod
def read_msr(address):
"""
Read the contents of the specified MSR (Machine Specific Register).
@type address: int
@param address: MSR to read.
@rtype: int
@return: Value of the specified MSR.
@raise WindowsError:
Raises an exception on error.
@raise NotImplementedError:
Current architecture is not C{i386} or C{amd64}.
@warning:
It could potentially brick your machine.
It works on my machine, but your mileage may vary.
"""
if win32.arch not in (win32.ARCH_I386, win32.ARCH_AMD64):
raise NotImplementedError(
"MSR reading is only supported on i386 or amd64 processors.")
msr = win32.SYSDBG_MSR()
msr.Address = address
msr.Data = 0
win32.NtSystemDebugControl(win32.SysDbgReadMsr,
InputBuffer = msr,
OutputBuffer = msr)
return msr.Data
@staticmethod
def write_msr(address, value):
"""
Set the contents of the specified MSR (Machine Specific Register).
@type address: int
@param address: MSR to write.
@type value: int
@param value: Contents to write on the MSR.
@raise WindowsError:
Raises an exception on error.
@raise NotImplementedError:
Current architecture is not C{i386} or C{amd64}.
@warning:
It could potentially brick your machine.
It works on my machine, but your mileage may vary.
"""
if win32.arch not in (win32.ARCH_I386, win32.ARCH_AMD64):
raise NotImplementedError(
"MSR writing is only supported on i386 or amd64 processors.")
msr = win32.SYSDBG_MSR()
msr.Address = address
msr.Data = value
win32.NtSystemDebugControl(win32.SysDbgWriteMsr, InputBuffer = msr)
@classmethod
def enable_step_on_branch_mode(cls):
"""
When tracing, call this on every single step event
for step on branch mode.
@raise WindowsError:
Raises C{ERROR_DEBUGGER_INACTIVE} if the debugger is not attached
to least one process.
@raise NotImplementedError:
Current architecture is not C{i386} or C{amd64}.
@warning:
This method uses the processor's machine specific registers (MSR).
It could potentially brick your machine.
It works on my machine, but your mileage may vary.
@note:
It doesn't seem to work in VMWare or VirtualBox machines.
Maybe it fails in other virtualization/emulation environments,
no extensive testing was made so far.
"""
cls.write_msr(DebugRegister.DebugCtlMSR,
DebugRegister.BranchTrapFlag | DebugRegister.LastBranchRecord)
@classmethod
def get_last_branch_location(cls):
"""
Returns the source and destination addresses of the last taken branch.
@rtype: tuple( int, int )
@return: Source and destination addresses of the last taken branch.
@raise WindowsError:
Raises an exception on error.
@raise NotImplementedError:
Current architecture is not C{i386} or C{amd64}.
@warning:
This method uses the processor's machine specific registers (MSR).
It could potentially brick your machine.
It works on my machine, but your mileage may vary.
@note:
It doesn't seem to work in VMWare or VirtualBox machines.
Maybe it fails in other virtualization/emulation environments,
no extensive testing was made so far.
"""
LastBranchFromIP = cls.read_msr(DebugRegister.LastBranchFromIP)
LastBranchToIP = cls.read_msr(DebugRegister.LastBranchToIP)
return ( LastBranchFromIP, LastBranchToIP )
#------------------------------------------------------------------------------
@classmethod
def get_postmortem_debugger(cls, bits = None):
"""
Returns the postmortem debugging settings from the Registry.
@see: L{set_postmortem_debugger}
@type bits: int
@param bits: Set to C{32} for the 32 bits debugger, or C{64} for the
64 bits debugger. Set to {None} for the default (L{System.bits}.
@rtype: tuple( str, bool, int )
@return: A tuple containing the command line string to the postmortem
debugger, a boolean specifying if user interaction is allowed
before attaching, and an integer specifying a user defined hotkey.
Any member of the tuple may be C{None}.
See L{set_postmortem_debugger} for more details.
@raise WindowsError:
Raises an exception on error.
"""
if bits is None:
bits = cls.bits
elif bits not in (32, 64):
raise NotImplementedError("Unknown architecture (%r bits)" % bits)
if bits == 32 and cls.bits == 64:
keyname = 'HKLM\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug'
else:
keyname = 'HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug'
key = cls.registry[keyname]
debugger = key.get('Debugger')
auto = key.get('Auto')
hotkey = key.get('UserDebuggerHotkey')
if auto is not None:
auto = bool(auto)
return (debugger, auto, hotkey)
@classmethod
def get_postmortem_exclusion_list(cls, bits = None):
"""
Returns the exclusion list for the postmortem debugger.
@see: L{get_postmortem_debugger}
@type bits: int
@param bits: Set to C{32} for the 32 bits debugger, or C{64} for the
64 bits debugger. Set to {None} for the default (L{System.bits}).
@rtype: list( str )
@return: List of excluded application filenames.
@raise WindowsError:
Raises an exception on error.
"""
if bits is None:
bits = cls.bits
elif bits not in (32, 64):
raise NotImplementedError("Unknown architecture (%r bits)" % bits)
if bits == 32 and cls.bits == 64:
keyname = 'HKLM\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug\\AutoExclusionList'
else:
keyname = 'HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug\\AutoExclusionList'
try:
key = cls.registry[keyname]
except KeyError:
return []
return [name for (name, enabled) in key.items() if enabled]
@classmethod
def set_postmortem_debugger(cls, cmdline,
auto = None, hotkey = None, bits = None):
"""
Sets the postmortem debugging settings in the Registry.
@warning: This method requires administrative rights.
@see: L{get_postmortem_debugger}
@type cmdline: str
@param cmdline: Command line to the new postmortem debugger.
When the debugger is invoked, the first "%ld" is replaced with the
process ID and the second "%ld" is replaced with the event handle.
Don't forget to enclose the program filename in double quotes if
the path contains spaces.
@type auto: bool
@param auto: Set to C{True} if no user interaction is allowed, C{False}
to prompt a confirmation dialog before attaching.
Use C{None} to leave this value unchanged.
@type hotkey: int
@param hotkey: Virtual key scan code for the user defined hotkey.
Use C{0} to disable the hotkey.
Use C{None} to leave this value unchanged.
@type bits: int
@param bits: Set to C{32} for the 32 bits debugger, or C{64} for the
64 bits debugger. Set to {None} for the default (L{System.bits}).
@rtype: tuple( str, bool, int )
@return: Previously defined command line and auto flag.
@raise WindowsError:
Raises an exception on error.
"""
if bits is None:
bits = cls.bits
elif bits not in (32, 64):
raise NotImplementedError("Unknown architecture (%r bits)" % bits)
if bits == 32 and cls.bits == 64:
keyname = 'HKLM\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug'
else:
keyname = 'HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug'
key = cls.registry[keyname]
if cmdline is not None:
key['Debugger'] = cmdline
if auto is not None:
key['Auto'] = int(bool(auto))
if hotkey is not None:
key['UserDebuggerHotkey'] = int(hotkey)
@classmethod
def add_to_postmortem_exclusion_list(cls, pathname, bits = None):
"""
Adds the given filename to the exclusion list for postmortem debugging.
@warning: This method requires administrative rights.
@see: L{get_postmortem_exclusion_list}
@type pathname: str
@param pathname:
Application pathname to exclude from postmortem debugging.
@type bits: int
@param bits: Set to C{32} for the 32 bits debugger, or C{64} for the
64 bits debugger. Set to {None} for the default (L{System.bits}).
@raise WindowsError:
Raises an exception on error.
"""
if bits is None:
bits = cls.bits
elif bits not in (32, 64):
raise NotImplementedError("Unknown architecture (%r bits)" % bits)
if bits == 32 and cls.bits == 64:
keyname = 'HKLM\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug\\AutoExclusionList'
else:
keyname = 'HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug\\AutoExclusionList'
try:
key = cls.registry[keyname]
except KeyError:
key = cls.registry.create(keyname)
key[pathname] = 1
@classmethod
def remove_from_postmortem_exclusion_list(cls, pathname, bits = None):
"""
Removes the given filename to the exclusion list for postmortem
debugging from the Registry.
@warning: This method requires administrative rights.
@warning: Don't ever delete entries you haven't created yourself!
Some entries are set by default for your version of Windows.
Deleting them might deadlock your system under some circumstances.
For more details see:
U{http://msdn.microsoft.com/en-us/library/bb204634(v=vs.85).aspx}
@see: L{get_postmortem_exclusion_list}
@type pathname: str
@param pathname: Application pathname to remove from the postmortem
debugging exclusion list.
@type bits: int
@param bits: Set to C{32} for the 32 bits debugger, or C{64} for the
64 bits debugger. Set to {None} for the default (L{System.bits}).
@raise WindowsError:
Raises an exception on error.
"""
if bits is None:
bits = cls.bits
elif bits not in (32, 64):
raise NotImplementedError("Unknown architecture (%r bits)" % bits)
if bits == 32 and cls.bits == 64:
keyname = 'HKLM\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug\\AutoExclusionList'
else:
keyname = 'HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug\\AutoExclusionList'
try:
key = cls.registry[keyname]
except KeyError:
return
try:
del key[pathname]
except KeyError:
return
#------------------------------------------------------------------------------
@staticmethod
def get_services():
"""
Retrieve a list of all system services.
@see: L{get_active_services},
L{start_service}, L{stop_service},
L{pause_service}, L{resume_service}
@rtype: list( L{win32.ServiceStatusProcessEntry} )
@return: List of service status descriptors.
"""
with win32.OpenSCManager(
dwDesiredAccess = win32.SC_MANAGER_ENUMERATE_SERVICE
) as hSCManager:
try:
return win32.EnumServicesStatusEx(hSCManager)
except AttributeError:
return win32.EnumServicesStatus(hSCManager)
@staticmethod
def get_active_services():
"""
Retrieve a list of all active system services.
@see: L{get_services},
L{start_service}, L{stop_service},
L{pause_service}, L{resume_service}
@rtype: list( L{win32.ServiceStatusProcessEntry} )
@return: List of service status descriptors.
"""
with win32.OpenSCManager(
dwDesiredAccess = win32.SC_MANAGER_ENUMERATE_SERVICE
) as hSCManager:
return [ entry for entry in win32.EnumServicesStatusEx(hSCManager,
dwServiceType = win32.SERVICE_WIN32,
dwServiceState = win32.SERVICE_ACTIVE) \
if entry.ProcessId ]
@staticmethod
def get_service(name):
"""
Get the service descriptor for the given service name.
@see: L{start_service}, L{stop_service},
L{pause_service}, L{resume_service}
@type name: str
@param name: Service unique name. You can get this value from the
C{ServiceName} member of the service descriptors returned by
L{get_services} or L{get_active_services}.
@rtype: L{win32.ServiceStatusProcess}
@return: Service status descriptor.
"""
with win32.OpenSCManager(
dwDesiredAccess = win32.SC_MANAGER_ENUMERATE_SERVICE
) as hSCManager:
with win32.OpenService(hSCManager, name,
dwDesiredAccess = win32.SERVICE_QUERY_STATUS
) as hService:
try:
return win32.QueryServiceStatusEx(hService)
except AttributeError:
return win32.QueryServiceStatus(hService)
@staticmethod
def get_service_display_name(name):
"""
Get the service display name for the given service name.
@see: L{get_service}
@type name: str
@param name: Service unique name. You can get this value from the
C{ServiceName} member of the service descriptors returned by
L{get_services} or L{get_active_services}.
@rtype: str
@return: Service display name.
"""
with win32.OpenSCManager(
dwDesiredAccess = win32.SC_MANAGER_ENUMERATE_SERVICE
) as hSCManager:
return win32.GetServiceDisplayName(hSCManager, name)
@staticmethod
def get_service_from_display_name(displayName):
"""
Get the service unique name given its display name.
@see: L{get_service}
@type displayName: str
@param displayName: Service display name. You can get this value from
the C{DisplayName} member of the service descriptors returned by
L{get_services} or L{get_active_services}.
@rtype: str
@return: Service unique name.
"""
with win32.OpenSCManager(
dwDesiredAccess = win32.SC_MANAGER_ENUMERATE_SERVICE
) as hSCManager:
return win32.GetServiceKeyName(hSCManager, displayName)
@staticmethod
def start_service(name, argv = None):
"""
Start the service given by name.
@warn: This method requires UAC elevation in Windows Vista and above.
@see: L{stop_service}, L{pause_service}, L{resume_service}
@type name: str
@param name: Service unique name. You can get this value from the
C{ServiceName} member of the service descriptors returned by
L{get_services} or L{get_active_services}.
"""
with win32.OpenSCManager(
dwDesiredAccess = win32.SC_MANAGER_CONNECT
) as hSCManager:
with win32.OpenService(hSCManager, name,
dwDesiredAccess = win32.SERVICE_START
) as hService:
win32.StartService(hService)
@staticmethod
def stop_service(name):
"""
Stop the service given by name.
@warn: This method requires UAC elevation in Windows Vista and above.
@see: L{get_services}, L{get_active_services},
L{start_service}, L{pause_service}, L{resume_service}
"""
with win32.OpenSCManager(
dwDesiredAccess = win32.SC_MANAGER_CONNECT
) as hSCManager:
with win32.OpenService(hSCManager, name,
dwDesiredAccess = win32.SERVICE_STOP
) as hService:
win32.ControlService(hService, win32.SERVICE_CONTROL_STOP)
@staticmethod
def pause_service(name):
"""
Pause the service given by name.
@warn: This method requires UAC elevation in Windows Vista and above.
@note: Not all services support this.
@see: L{get_services}, L{get_active_services},
L{start_service}, L{stop_service}, L{resume_service}
"""
with win32.OpenSCManager(
dwDesiredAccess = win32.SC_MANAGER_CONNECT
) as hSCManager:
with win32.OpenService(hSCManager, name,
dwDesiredAccess = win32.SERVICE_PAUSE_CONTINUE
) as hService:
win32.ControlService(hService, win32.SERVICE_CONTROL_PAUSE)
@staticmethod
def resume_service(name):
"""
Resume the service given by name.
@warn: This method requires UAC elevation in Windows Vista and above.
@note: Not all services support this.
@see: L{get_services}, L{get_active_services},
L{start_service}, L{stop_service}, L{pause_service}
"""
with win32.OpenSCManager(
dwDesiredAccess = win32.SC_MANAGER_CONNECT
) as hSCManager:
with win32.OpenService(hSCManager, name,
dwDesiredAccess = win32.SERVICE_PAUSE_CONTINUE
) as hService:
win32.ControlService(hService, win32.SERVICE_CONTROL_CONTINUE)
# TODO: create_service, delete_service
| 45,884 | Python | 34.350539 | 118 | 0.573773 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/window.py | #!~/.wine/drive_c/Python25/python.exe
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Window instrumentation.
@group Instrumentation:
Window
"""
__revision__ = "$Id$"
__all__ = ['Window']
from winappdbg import win32
# delayed imports
Process = None
Thread = None
#==============================================================================
# Unlike Process, Thread and Module, there's no container for Window objects.
# That's because Window objects don't really store any data besides the handle.
# XXX TODO
# * implement sending fake user input (mouse and keyboard messages)
# * maybe implement low-level hooks? (they don't require a dll to be injected)
# XXX TODO
#
# Will it be possible to implement window hooks too? That requires a DLL to be
# injected in the target process. Perhaps with CPython it could be done easier,
# compiling a native extension is the safe bet, but both require having a non
# pure Python module, which is something I was trying to avoid so far.
#
# Another possibility would be to malloc some CC's in the target process and
# point the hook callback to it. We'd need to have the remote procedure call
# feature first as (I believe) the hook can't be set remotely in this case.
class Window (object):
"""
Interface to an open window in the current desktop.
@group Properties:
get_handle, get_pid, get_tid,
get_process, get_thread,
set_process, set_thread,
get_classname, get_style, get_extended_style,
get_text, set_text,
get_placement, set_placement,
get_screen_rect, get_client_rect,
screen_to_client, client_to_screen
@group State:
is_valid, is_visible, is_enabled, is_maximized, is_minimized, is_child,
is_zoomed, is_iconic
@group Navigation:
get_parent, get_children, get_root, get_tree,
get_child_at
@group Instrumentation:
enable, disable, show, hide, maximize, minimize, restore, move, kill
@group Low-level access:
send, post
@type hWnd: int
@ivar hWnd: Window handle.
@type dwProcessId: int
@ivar dwProcessId: Global ID of the process that owns this window.
@type dwThreadId: int
@ivar dwThreadId: Global ID of the thread that owns this window.
@type process: L{Process}
@ivar process: Process that owns this window.
Use the L{get_process} method instead.
@type thread: L{Thread}
@ivar thread: Thread that owns this window.
Use the L{get_thread} method instead.
@type classname: str
@ivar classname: Window class name.
@type text: str
@ivar text: Window text (caption).
@type placement: L{win32.WindowPlacement}
@ivar placement: Window placement in the desktop.
"""
def __init__(self, hWnd = None, process = None, thread = None):
"""
@type hWnd: int or L{win32.HWND}
@param hWnd: Window handle.
@type process: L{Process}
@param process: (Optional) Process that owns this window.
@type thread: L{Thread}
@param thread: (Optional) Thread that owns this window.
"""
self.hWnd = hWnd
self.dwProcessId = None
self.dwThreadId = None
self.set_process(process)
self.set_thread(thread)
@property
def _as_parameter_(self):
"""
Compatibility with ctypes.
Allows passing transparently a Window object to an API call.
"""
return self.get_handle()
def get_handle(self):
"""
@rtype: int
@return: Window handle.
@raise ValueError: No window handle set.
"""
if self.hWnd is None:
raise ValueError("No window handle set!")
return self.hWnd
def get_pid(self):
"""
@rtype: int
@return: Global ID of the process that owns this window.
"""
if self.dwProcessId is not None:
return self.dwProcessId
self.__get_pid_and_tid()
return self.dwProcessId
def get_tid(self):
"""
@rtype: int
@return: Global ID of the thread that owns this window.
"""
if self.dwThreadId is not None:
return self.dwThreadId
self.__get_pid_and_tid()
return self.dwThreadId
def __get_pid_and_tid(self):
"Internally used by get_pid() and get_tid()."
self.dwThreadId, self.dwProcessId = \
win32.GetWindowThreadProcessId(self.get_handle())
def __load_Process_class(self):
global Process # delayed import
if Process is None:
from winappdbg.process import Process
def __load_Thread_class(self):
global Thread # delayed import
if Thread is None:
from winappdbg.thread import Thread
def get_process(self):
"""
@rtype: L{Process}
@return: Parent Process object.
"""
if self.__process is not None:
return self.__process
self.__load_Process_class()
self.__process = Process(self.get_pid())
return self.__process
def set_process(self, process = None):
"""
Manually set the parent process. Use with care!
@type process: L{Process}
@param process: (Optional) Process object. Use C{None} to autodetect.
"""
if process is None:
self.__process = None
else:
self.__load_Process_class()
if not isinstance(process, Process):
msg = "Parent process must be a Process instance, "
msg += "got %s instead" % type(process)
raise TypeError(msg)
self.dwProcessId = process.get_pid()
self.__process = process
def get_thread(self):
"""
@rtype: L{Thread}
@return: Parent Thread object.
"""
if self.__thread is not None:
return self.__thread
self.__load_Thread_class()
self.__thread = Thread(self.get_tid())
return self.__thread
def set_thread(self, thread = None):
"""
Manually set the thread process. Use with care!
@type thread: L{Thread}
@param thread: (Optional) Thread object. Use C{None} to autodetect.
"""
if thread is None:
self.__thread = None
else:
self.__load_Thread_class()
if not isinstance(thread, Thread):
msg = "Parent thread must be a Thread instance, "
msg += "got %s instead" % type(thread)
raise TypeError(msg)
self.dwThreadId = thread.get_tid()
self.__thread = thread
def __get_window(self, hWnd):
"""
User internally to get another Window from this one.
It'll try to copy the parent Process and Thread references if possible.
"""
window = Window(hWnd)
if window.get_pid() == self.get_pid():
window.set_process( self.get_process() )
if window.get_tid() == self.get_tid():
window.set_thread( self.get_thread() )
return window
#------------------------------------------------------------------------------
def get_classname(self):
"""
@rtype: str
@return: Window class name.
@raise WindowsError: An error occured while processing this request.
"""
return win32.GetClassName( self.get_handle() )
def get_style(self):
"""
@rtype: int
@return: Window style mask.
@raise WindowsError: An error occured while processing this request.
"""
return win32.GetWindowLongPtr( self.get_handle(), win32.GWL_STYLE )
def get_extended_style(self):
"""
@rtype: int
@return: Window extended style mask.
@raise WindowsError: An error occured while processing this request.
"""
return win32.GetWindowLongPtr( self.get_handle(), win32.GWL_EXSTYLE )
def get_text(self):
"""
@see: L{set_text}
@rtype: str
@return: Window text (caption) on success, C{None} on error.
"""
try:
return win32.GetWindowText( self.get_handle() )
except WindowsError:
return None
def set_text(self, text):
"""
Set the window text (caption).
@see: L{get_text}
@type text: str
@param text: New window text.
@raise WindowsError: An error occured while processing this request.
"""
win32.SetWindowText( self.get_handle(), text )
def get_placement(self):
"""
Retrieve the window placement in the desktop.
@see: L{set_placement}
@rtype: L{win32.WindowPlacement}
@return: Window placement in the desktop.
@raise WindowsError: An error occured while processing this request.
"""
return win32.GetWindowPlacement( self.get_handle() )
def set_placement(self, placement):
"""
Set the window placement in the desktop.
@see: L{get_placement}
@type placement: L{win32.WindowPlacement}
@param placement: Window placement in the desktop.
@raise WindowsError: An error occured while processing this request.
"""
win32.SetWindowPlacement( self.get_handle(), placement )
def get_screen_rect(self):
"""
Get the window coordinates in the desktop.
@rtype: L{win32.Rect}
@return: Rectangle occupied by the window in the desktop.
@raise WindowsError: An error occured while processing this request.
"""
return win32.GetWindowRect( self.get_handle() )
def get_client_rect(self):
"""
Get the window's client area coordinates in the desktop.
@rtype: L{win32.Rect}
@return: Rectangle occupied by the window's client area in the desktop.
@raise WindowsError: An error occured while processing this request.
"""
cr = win32.GetClientRect( self.get_handle() )
cr.left, cr.top = self.client_to_screen(cr.left, cr.top)
cr.right, cr.bottom = self.client_to_screen(cr.right, cr.bottom)
return cr
# XXX TODO
# * properties x, y, width, height
# * properties left, top, right, bottom
process = property(get_process, set_process, doc="")
thread = property(get_thread, set_thread, doc="")
classname = property(get_classname, doc="")
style = property(get_style, doc="")
exstyle = property(get_extended_style, doc="")
text = property(get_text, set_text, doc="")
placement = property(get_placement, set_placement, doc="")
#------------------------------------------------------------------------------
def client_to_screen(self, x, y):
"""
Translates window client coordinates to screen coordinates.
@note: This is a simplified interface to some of the functionality of
the L{win32.Point} class.
@see: {win32.Point.client_to_screen}
@type x: int
@param x: Horizontal coordinate.
@type y: int
@param y: Vertical coordinate.
@rtype: tuple( int, int )
@return: Translated coordinates in a tuple (x, y).
@raise WindowsError: An error occured while processing this request.
"""
return tuple( win32.ClientToScreen( self.get_handle(), (x, y) ) )
def screen_to_client(self, x, y):
"""
Translates window screen coordinates to client coordinates.
@note: This is a simplified interface to some of the functionality of
the L{win32.Point} class.
@see: {win32.Point.screen_to_client}
@type x: int
@param x: Horizontal coordinate.
@type y: int
@param y: Vertical coordinate.
@rtype: tuple( int, int )
@return: Translated coordinates in a tuple (x, y).
@raise WindowsError: An error occured while processing this request.
"""
return tuple( win32.ScreenToClient( self.get_handle(), (x, y) ) )
#------------------------------------------------------------------------------
def get_parent(self):
"""
@see: L{get_children}
@rtype: L{Window} or None
@return: Parent window. Returns C{None} if the window has no parent.
@raise WindowsError: An error occured while processing this request.
"""
hWnd = win32.GetParent( self.get_handle() )
if hWnd:
return self.__get_window(hWnd)
def get_children(self):
"""
@see: L{get_parent}
@rtype: list( L{Window} )
@return: List of child windows.
@raise WindowsError: An error occured while processing this request.
"""
return [
self.__get_window(hWnd) \
for hWnd in win32.EnumChildWindows( self.get_handle() )
]
def get_tree(self):
"""
@see: L{get_root}
@rtype: dict( L{Window} S{->} dict( ... ) )
@return: Dictionary of dictionaries forming a tree of child windows.
@raise WindowsError: An error occured while processing this request.
"""
subtree = dict()
for aWindow in self.get_children():
subtree[ aWindow ] = aWindow.get_tree()
return subtree
def get_root(self):
"""
@see: L{get_tree}
@rtype: L{Window}
@return: If this is a child window, return the top-level window it
belongs to.
If this window is already a top-level window, returns itself.
@raise WindowsError: An error occured while processing this request.
"""
hWnd = self.get_handle()
history = set()
hPrevWnd = hWnd
while hWnd and hWnd not in history:
history.add(hWnd)
hPrevWnd = hWnd
hWnd = win32.GetParent(hWnd)
if hWnd in history:
# See: https://docs.google.com/View?id=dfqd62nk_228h28szgz
return self
if hPrevWnd != self.get_handle():
return self.__get_window(hPrevWnd)
return self
def get_child_at(self, x, y, bAllowTransparency = True):
"""
Get the child window located at the given coordinates. If no such
window exists an exception is raised.
@see: L{get_children}
@type x: int
@param x: Horizontal coordinate.
@type y: int
@param y: Vertical coordinate.
@type bAllowTransparency: bool
@param bAllowTransparency: If C{True} transparent areas in windows are
ignored, returning the window behind them. If C{False} transparent
areas are treated just like any other area.
@rtype: L{Window}
@return: Child window at the requested position, or C{None} if there
is no window at those coordinates.
"""
try:
if bAllowTransparency:
hWnd = win32.RealChildWindowFromPoint( self.get_handle(), (x, y) )
else:
hWnd = win32.ChildWindowFromPoint( self.get_handle(), (x, y) )
if hWnd:
return self.__get_window(hWnd)
except WindowsError:
pass
return None
#------------------------------------------------------------------------------
def is_valid(self):
"""
@rtype: bool
@return: C{True} if the window handle is still valid.
"""
return win32.IsWindow( self.get_handle() )
def is_visible(self):
"""
@see: {show}, {hide}
@rtype: bool
@return: C{True} if the window is in a visible state.
"""
return win32.IsWindowVisible( self.get_handle() )
def is_enabled(self):
"""
@see: {enable}, {disable}
@rtype: bool
@return: C{True} if the window is in an enabled state.
"""
return win32.IsWindowEnabled( self.get_handle() )
def is_maximized(self):
"""
@see: L{maximize}
@rtype: bool
@return: C{True} if the window is maximized.
"""
return win32.IsZoomed( self.get_handle() )
def is_minimized(self):
"""
@see: L{minimize}
@rtype: bool
@return: C{True} if the window is minimized.
"""
return win32.IsIconic( self.get_handle() )
def is_child(self):
"""
@see: L{get_parent}
@rtype: bool
@return: C{True} if the window is a child window.
"""
return win32.IsChild( self.get_handle() )
is_zoomed = is_maximized
is_iconic = is_minimized
#------------------------------------------------------------------------------
def enable(self):
"""
Enable the user input for the window.
@see: L{disable}
@raise WindowsError: An error occured while processing this request.
"""
win32.EnableWindow( self.get_handle(), True )
def disable(self):
"""
Disable the user input for the window.
@see: L{enable}
@raise WindowsError: An error occured while processing this request.
"""
win32.EnableWindow( self.get_handle(), False )
def show(self, bAsync = True):
"""
Make the window visible.
@see: L{hide}
@type bAsync: bool
@param bAsync: Perform the request asynchronously.
@raise WindowsError: An error occured while processing this request.
"""
if bAsync:
win32.ShowWindowAsync( self.get_handle(), win32.SW_SHOW )
else:
win32.ShowWindow( self.get_handle(), win32.SW_SHOW )
def hide(self, bAsync = True):
"""
Make the window invisible.
@see: L{show}
@type bAsync: bool
@param bAsync: Perform the request asynchronously.
@raise WindowsError: An error occured while processing this request.
"""
if bAsync:
win32.ShowWindowAsync( self.get_handle(), win32.SW_HIDE )
else:
win32.ShowWindow( self.get_handle(), win32.SW_HIDE )
def maximize(self, bAsync = True):
"""
Maximize the window.
@see: L{minimize}, L{restore}
@type bAsync: bool
@param bAsync: Perform the request asynchronously.
@raise WindowsError: An error occured while processing this request.
"""
if bAsync:
win32.ShowWindowAsync( self.get_handle(), win32.SW_MAXIMIZE )
else:
win32.ShowWindow( self.get_handle(), win32.SW_MAXIMIZE )
def minimize(self, bAsync = True):
"""
Minimize the window.
@see: L{maximize}, L{restore}
@type bAsync: bool
@param bAsync: Perform the request asynchronously.
@raise WindowsError: An error occured while processing this request.
"""
if bAsync:
win32.ShowWindowAsync( self.get_handle(), win32.SW_MINIMIZE )
else:
win32.ShowWindow( self.get_handle(), win32.SW_MINIMIZE )
def restore(self, bAsync = True):
"""
Unmaximize and unminimize the window.
@see: L{maximize}, L{minimize}
@type bAsync: bool
@param bAsync: Perform the request asynchronously.
@raise WindowsError: An error occured while processing this request.
"""
if bAsync:
win32.ShowWindowAsync( self.get_handle(), win32.SW_RESTORE )
else:
win32.ShowWindow( self.get_handle(), win32.SW_RESTORE )
def move(self, x = None, y = None, width = None, height = None,
bRepaint = True):
"""
Moves and/or resizes the window.
@note: This is request is performed syncronously.
@type x: int
@param x: (Optional) New horizontal coordinate.
@type y: int
@param y: (Optional) New vertical coordinate.
@type width: int
@param width: (Optional) Desired window width.
@type height: int
@param height: (Optional) Desired window height.
@type bRepaint: bool
@param bRepaint:
(Optional) C{True} if the window should be redrawn afterwards.
@raise WindowsError: An error occured while processing this request.
"""
if None in (x, y, width, height):
rect = self.get_screen_rect()
if x is None:
x = rect.left
if y is None:
y = rect.top
if width is None:
width = rect.right - rect.left
if height is None:
height = rect.bottom - rect.top
win32.MoveWindow(self.get_handle(), x, y, width, height, bRepaint)
def kill(self):
"""
Signals the program to quit.
@note: This is an asyncronous request.
@raise WindowsError: An error occured while processing this request.
"""
self.post(win32.WM_QUIT)
def send(self, uMsg, wParam = None, lParam = None, dwTimeout = None):
"""
Send a low-level window message syncronically.
@type uMsg: int
@param uMsg: Message code.
@param wParam:
The type and meaning of this parameter depends on the message.
@param lParam:
The type and meaning of this parameter depends on the message.
@param dwTimeout: Optional timeout for the operation.
Use C{None} to wait indefinitely.
@rtype: int
@return: The meaning of the return value depends on the window message.
Typically a value of C{0} means an error occured. You can get the
error code by calling L{win32.GetLastError}.
"""
if dwTimeout is None:
return win32.SendMessage(self.get_handle(), uMsg, wParam, lParam)
return win32.SendMessageTimeout(
self.get_handle(), uMsg, wParam, lParam,
win32.SMTO_ABORTIFHUNG | win32.SMTO_ERRORONEXIT, dwTimeout)
def post(self, uMsg, wParam = None, lParam = None):
"""
Post a low-level window message asyncronically.
@type uMsg: int
@param uMsg: Message code.
@param wParam:
The type and meaning of this parameter depends on the message.
@param lParam:
The type and meaning of this parameter depends on the message.
@raise WindowsError: An error occured while sending the message.
"""
win32.PostMessage(self.get_handle(), uMsg, wParam, lParam)
| 24,309 | Python | 30.986842 | 82 | 0.581883 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/win32/peb_teb.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
PEB and TEB structures, constants and data types.
"""
__revision__ = "$Id$"
from winappdbg.win32.defines import *
from winappdbg.win32.version import os
#==============================================================================
# This is used later on to calculate the list of exported symbols.
_all = None
_all = set(vars().keys())
#==============================================================================
#--- PEB and TEB structures, constants and data types -------------------------
# From http://www.nirsoft.net/kernel_struct/vista/CLIENT_ID.html
#
# typedef struct _CLIENT_ID
# {
# PVOID UniqueProcess;
# PVOID UniqueThread;
# } CLIENT_ID, *PCLIENT_ID;
class CLIENT_ID(Structure):
_fields_ = [
("UniqueProcess", PVOID),
("UniqueThread", PVOID),
]
# From MSDN:
#
# typedef struct _LDR_DATA_TABLE_ENTRY {
# BYTE Reserved1[2];
# LIST_ENTRY InMemoryOrderLinks;
# PVOID Reserved2[2];
# PVOID DllBase;
# PVOID EntryPoint;
# PVOID Reserved3;
# UNICODE_STRING FullDllName;
# BYTE Reserved4[8];
# PVOID Reserved5[3];
# union {
# ULONG CheckSum;
# PVOID Reserved6;
# };
# ULONG TimeDateStamp;
# } LDR_DATA_TABLE_ENTRY, *PLDR_DATA_TABLE_ENTRY;
##class LDR_DATA_TABLE_ENTRY(Structure):
## _fields_ = [
## ("Reserved1", BYTE * 2),
## ("InMemoryOrderLinks", LIST_ENTRY),
## ("Reserved2", PVOID * 2),
## ("DllBase", PVOID),
## ("EntryPoint", PVOID),
## ("Reserved3", PVOID),
## ("FullDllName", UNICODE_STRING),
## ("Reserved4", BYTE * 8),
## ("Reserved5", PVOID * 3),
## ("CheckSum", ULONG),
## ("TimeDateStamp", ULONG),
##]
# From MSDN:
#
# typedef struct _PEB_LDR_DATA {
# BYTE Reserved1[8];
# PVOID Reserved2[3];
# LIST_ENTRY InMemoryOrderModuleList;
# } PEB_LDR_DATA,
# *PPEB_LDR_DATA;
##class PEB_LDR_DATA(Structure):
## _fields_ = [
## ("Reserved1", BYTE),
## ("Reserved2", PVOID),
## ("InMemoryOrderModuleList", LIST_ENTRY),
##]
# From http://undocumented.ntinternals.net/UserMode/Structures/RTL_USER_PROCESS_PARAMETERS.html
# typedef struct _RTL_USER_PROCESS_PARAMETERS {
# ULONG MaximumLength;
# ULONG Length;
# ULONG Flags;
# ULONG DebugFlags;
# PVOID ConsoleHandle;
# ULONG ConsoleFlags;
# HANDLE StdInputHandle;
# HANDLE StdOutputHandle;
# HANDLE StdErrorHandle;
# UNICODE_STRING CurrentDirectoryPath;
# HANDLE CurrentDirectoryHandle;
# UNICODE_STRING DllPath;
# UNICODE_STRING ImagePathName;
# UNICODE_STRING CommandLine;
# PVOID Environment;
# ULONG StartingPositionLeft;
# ULONG StartingPositionTop;
# ULONG Width;
# ULONG Height;
# ULONG CharWidth;
# ULONG CharHeight;
# ULONG ConsoleTextAttributes;
# ULONG WindowFlags;
# ULONG ShowWindowFlags;
# UNICODE_STRING WindowTitle;
# UNICODE_STRING DesktopName;
# UNICODE_STRING ShellInfo;
# UNICODE_STRING RuntimeData;
# RTL_DRIVE_LETTER_CURDIR DLCurrentDirectory[0x20];
# } RTL_USER_PROCESS_PARAMETERS, *PRTL_USER_PROCESS_PARAMETERS;
# kd> dt _RTL_USER_PROCESS_PARAMETERS
# ntdll!_RTL_USER_PROCESS_PARAMETERS
# +0x000 MaximumLength : Uint4B
# +0x004 Length : Uint4B
# +0x008 Flags : Uint4B
# +0x00c DebugFlags : Uint4B
# +0x010 ConsoleHandle : Ptr32 Void
# +0x014 ConsoleFlags : Uint4B
# +0x018 StandardInput : Ptr32 Void
# +0x01c StandardOutput : Ptr32 Void
# +0x020 StandardError : Ptr32 Void
# +0x024 CurrentDirectory : _CURDIR
# +0x030 DllPath : _UNICODE_STRING
# +0x038 ImagePathName : _UNICODE_STRING
# +0x040 CommandLine : _UNICODE_STRING
# +0x048 Environment : Ptr32 Void
# +0x04c StartingX : Uint4B
# +0x050 StartingY : Uint4B
# +0x054 CountX : Uint4B
# +0x058 CountY : Uint4B
# +0x05c CountCharsX : Uint4B
# +0x060 CountCharsY : Uint4B
# +0x064 FillAttribute : Uint4B
# +0x068 WindowFlags : Uint4B
# +0x06c ShowWindowFlags : Uint4B
# +0x070 WindowTitle : _UNICODE_STRING
# +0x078 DesktopInfo : _UNICODE_STRING
# +0x080 ShellInfo : _UNICODE_STRING
# +0x088 RuntimeData : _UNICODE_STRING
# +0x090 CurrentDirectores : [32] _RTL_DRIVE_LETTER_CURDIR
# +0x290 EnvironmentSize : Uint4B
##class RTL_USER_PROCESS_PARAMETERS(Structure):
## _fields_ = [
## ("MaximumLength", ULONG),
## ("Length", ULONG),
## ("Flags", ULONG),
## ("DebugFlags", ULONG),
## ("ConsoleHandle", PVOID),
## ("ConsoleFlags", ULONG),
## ("StandardInput", HANDLE),
## ("StandardOutput", HANDLE),
## ("StandardError", HANDLE),
## ("CurrentDirectory", CURDIR),
## ("DllPath", UNICODE_STRING),
## ("ImagePathName", UNICODE_STRING),
## ("CommandLine", UNICODE_STRING),
## ("Environment", PVOID),
## ("StartingX", ULONG),
## ("StartingY", ULONG),
## ("CountX", ULONG),
## ("CountY", ULONG),
## ("CountCharsX", ULONG),
## ("CountCharsY", ULONG),
## ("FillAttribute", ULONG),
## ("WindowFlags", ULONG),
## ("ShowWindowFlags", ULONG),
## ("WindowTitle", UNICODE_STRING),
## ("DesktopInfo", UNICODE_STRING),
## ("ShellInfo", UNICODE_STRING),
## ("RuntimeData", UNICODE_STRING),
## ("CurrentDirectores", RTL_DRIVE_LETTER_CURDIR * 32), # typo here?
##
## # Windows 2008 and Vista
## ("EnvironmentSize", ULONG),
##]
## @property
## def CurrentDirectories(self):
## return self.CurrentDirectores
# From MSDN:
#
# typedef struct _RTL_USER_PROCESS_PARAMETERS {
# BYTE Reserved1[16];
# PVOID Reserved2[10];
# UNICODE_STRING ImagePathName;
# UNICODE_STRING CommandLine;
# } RTL_USER_PROCESS_PARAMETERS,
# *PRTL_USER_PROCESS_PARAMETERS;
class RTL_USER_PROCESS_PARAMETERS(Structure):
_fields_ = [
("Reserved1", BYTE * 16),
("Reserved2", PVOID * 10),
("ImagePathName", UNICODE_STRING),
("CommandLine", UNICODE_STRING),
("Environment", PVOID), # undocumented!
#
# XXX TODO
# This structure should be defined with all undocumented fields for
# each version of Windows, just like it's being done for PEB and TEB.
#
]
PPS_POST_PROCESS_INIT_ROUTINE = PVOID
#from MSDN:
#
# typedef struct _PEB {
# BYTE Reserved1[2];
# BYTE BeingDebugged;
# BYTE Reserved2[21];
# PPEB_LDR_DATA LoaderData;
# PRTL_USER_PROCESS_PARAMETERS ProcessParameters;
# BYTE Reserved3[520];
# PPS_POST_PROCESS_INIT_ROUTINE PostProcessInitRoutine;
# BYTE Reserved4[136];
# ULONG SessionId;
# } PEB;
##class PEB(Structure):
## _fields_ = [
## ("Reserved1", BYTE * 2),
## ("BeingDebugged", BYTE),
## ("Reserved2", BYTE * 21),
## ("LoaderData", PVOID, # PPEB_LDR_DATA
## ("ProcessParameters", PVOID, # PRTL_USER_PROCESS_PARAMETERS
## ("Reserved3", BYTE * 520),
## ("PostProcessInitRoutine", PPS_POST_PROCESS_INIT_ROUTINE),
## ("Reserved4", BYTE),
## ("SessionId", ULONG),
##]
# from MSDN:
#
# typedef struct _TEB {
# BYTE Reserved1[1952];
# PVOID Reserved2[412];
# PVOID TlsSlots[64];
# BYTE Reserved3[8];
# PVOID Reserved4[26];
# PVOID ReservedForOle;
# PVOID Reserved5[4];
# PVOID TlsExpansionSlots;
# } TEB,
# *PTEB;
##class TEB(Structure):
## _fields_ = [
## ("Reserved1", PVOID * 1952),
## ("Reserved2", PVOID * 412),
## ("TlsSlots", PVOID * 64),
## ("Reserved3", BYTE * 8),
## ("Reserved4", PVOID * 26),
## ("ReservedForOle", PVOID),
## ("Reserved5", PVOID * 4),
## ("TlsExpansionSlots", PVOID),
##]
# from http://undocumented.ntinternals.net/UserMode/Structures/LDR_MODULE.html
#
# typedef struct _LDR_MODULE {
# LIST_ENTRY InLoadOrderModuleList;
# LIST_ENTRY InMemoryOrderModuleList;
# LIST_ENTRY InInitializationOrderModuleList;
# PVOID BaseAddress;
# PVOID EntryPoint;
# ULONG SizeOfImage;
# UNICODE_STRING FullDllName;
# UNICODE_STRING BaseDllName;
# ULONG Flags;
# SHORT LoadCount;
# SHORT TlsIndex;
# LIST_ENTRY HashTableEntry;
# ULONG TimeDateStamp;
# } LDR_MODULE, *PLDR_MODULE;
class LDR_MODULE(Structure):
_fields_ = [
("InLoadOrderModuleList", LIST_ENTRY),
("InMemoryOrderModuleList", LIST_ENTRY),
("InInitializationOrderModuleList", LIST_ENTRY),
("BaseAddress", PVOID),
("EntryPoint", PVOID),
("SizeOfImage", ULONG),
("FullDllName", UNICODE_STRING),
("BaseDllName", UNICODE_STRING),
("Flags", ULONG),
("LoadCount", SHORT),
("TlsIndex", SHORT),
("HashTableEntry", LIST_ENTRY),
("TimeDateStamp", ULONG),
]
# from http://undocumented.ntinternals.net/UserMode/Structures/PEB_LDR_DATA.html
#
# typedef struct _PEB_LDR_DATA {
# ULONG Length;
# BOOLEAN Initialized;
# PVOID SsHandle;
# LIST_ENTRY InLoadOrderModuleList;
# LIST_ENTRY InMemoryOrderModuleList;
# LIST_ENTRY InInitializationOrderModuleList;
# } PEB_LDR_DATA, *PPEB_LDR_DATA;
class PEB_LDR_DATA(Structure):
_fields_ = [
("Length", ULONG),
("Initialized", BOOLEAN),
("SsHandle", PVOID),
("InLoadOrderModuleList", LIST_ENTRY),
("InMemoryOrderModuleList", LIST_ENTRY),
("InInitializationOrderModuleList", LIST_ENTRY),
]
# From http://undocumented.ntinternals.net/UserMode/Undocumented%20Functions/NT%20Objects/Process/PEB_FREE_BLOCK.html
#
# typedef struct _PEB_FREE_BLOCK {
# PEB_FREE_BLOCK *Next;
# ULONG Size;
# } PEB_FREE_BLOCK, *PPEB_FREE_BLOCK;
class PEB_FREE_BLOCK(Structure):
pass
##PPEB_FREE_BLOCK = POINTER(PEB_FREE_BLOCK)
PPEB_FREE_BLOCK = PVOID
PEB_FREE_BLOCK._fields_ = [
("Next", PPEB_FREE_BLOCK),
("Size", ULONG),
]
# From http://undocumented.ntinternals.net/UserMode/Structures/RTL_DRIVE_LETTER_CURDIR.html
#
# typedef struct _RTL_DRIVE_LETTER_CURDIR {
# USHORT Flags;
# USHORT Length;
# ULONG TimeStamp;
# UNICODE_STRING DosPath;
# } RTL_DRIVE_LETTER_CURDIR, *PRTL_DRIVE_LETTER_CURDIR;
class RTL_DRIVE_LETTER_CURDIR(Structure):
_fields_ = [
("Flags", USHORT),
("Length", USHORT),
("TimeStamp", ULONG),
("DosPath", UNICODE_STRING),
]
# From http://www.nirsoft.net/kernel_struct/vista/CURDIR.html
#
# typedef struct _CURDIR
# {
# UNICODE_STRING DosPath;
# PVOID Handle;
# } CURDIR, *PCURDIR;
class CURDIR(Structure):
_fields_ = [
("DosPath", UNICODE_STRING),
("Handle", PVOID),
]
# From http://www.nirsoft.net/kernel_struct/vista/RTL_CRITICAL_SECTION_DEBUG.html
#
# typedef struct _RTL_CRITICAL_SECTION_DEBUG
# {
# WORD Type;
# WORD CreatorBackTraceIndex;
# PRTL_CRITICAL_SECTION CriticalSection;
# LIST_ENTRY ProcessLocksList;
# ULONG EntryCount;
# ULONG ContentionCount;
# ULONG Flags;
# WORD CreatorBackTraceIndexHigh;
# WORD SpareUSHORT;
# } RTL_CRITICAL_SECTION_DEBUG, *PRTL_CRITICAL_SECTION_DEBUG;
#
# From http://www.nirsoft.net/kernel_struct/vista/RTL_CRITICAL_SECTION.html
#
# typedef struct _RTL_CRITICAL_SECTION
# {
# PRTL_CRITICAL_SECTION_DEBUG DebugInfo;
# LONG LockCount;
# LONG RecursionCount;
# PVOID OwningThread;
# PVOID LockSemaphore;
# ULONG SpinCount;
# } RTL_CRITICAL_SECTION, *PRTL_CRITICAL_SECTION;
#
class RTL_CRITICAL_SECTION(Structure):
_fields_ = [
("DebugInfo", PVOID), # PRTL_CRITICAL_SECTION_DEBUG
("LockCount", LONG),
("RecursionCount", LONG),
("OwningThread", PVOID),
("LockSemaphore", PVOID),
("SpinCount", ULONG),
]
class RTL_CRITICAL_SECTION_DEBUG(Structure):
_fields_ = [
("Type", WORD),
("CreatorBackTraceIndex", WORD),
("CriticalSection", PVOID), # PRTL_CRITICAL_SECTION
("ProcessLocksList", LIST_ENTRY),
("EntryCount", ULONG),
("ContentionCount", ULONG),
("Flags", ULONG),
("CreatorBackTraceIndexHigh", WORD),
("SpareUSHORT", WORD),
]
PRTL_CRITICAL_SECTION = POINTER(RTL_CRITICAL_SECTION)
PRTL_CRITICAL_SECTION_DEBUG = POINTER(RTL_CRITICAL_SECTION_DEBUG)
PPEB_LDR_DATA = POINTER(PEB_LDR_DATA)
PRTL_USER_PROCESS_PARAMETERS = POINTER(RTL_USER_PROCESS_PARAMETERS)
PPEBLOCKROUTINE = PVOID
# BitField
ImageUsesLargePages = 1 << 0
IsProtectedProcess = 1 << 1
IsLegacyProcess = 1 << 2
IsImageDynamicallyRelocated = 1 << 3
SkipPatchingUser32Forwarders = 1 << 4
# CrossProcessFlags
ProcessInJob = 1 << 0
ProcessInitializing = 1 << 1
ProcessUsingVEH = 1 << 2
ProcessUsingVCH = 1 << 3
ProcessUsingFTH = 1 << 4
# TracingFlags
HeapTracingEnabled = 1 << 0
CritSecTracingEnabled = 1 << 1
# NtGlobalFlags
FLG_VALID_BITS = 0x003FFFFF # not a flag
FLG_STOP_ON_EXCEPTION = 0x00000001
FLG_SHOW_LDR_SNAPS = 0x00000002
FLG_DEBUG_INITIAL_COMMAND = 0x00000004
FLG_STOP_ON_HUNG_GUI = 0x00000008
FLG_HEAP_ENABLE_TAIL_CHECK = 0x00000010
FLG_HEAP_ENABLE_FREE_CHECK = 0x00000020
FLG_HEAP_VALIDATE_PARAMETERS = 0x00000040
FLG_HEAP_VALIDATE_ALL = 0x00000080
FLG_POOL_ENABLE_TAIL_CHECK = 0x00000100
FLG_POOL_ENABLE_FREE_CHECK = 0x00000200
FLG_POOL_ENABLE_TAGGING = 0x00000400
FLG_HEAP_ENABLE_TAGGING = 0x00000800
FLG_USER_STACK_TRACE_DB = 0x00001000
FLG_KERNEL_STACK_TRACE_DB = 0x00002000
FLG_MAINTAIN_OBJECT_TYPELIST = 0x00004000
FLG_HEAP_ENABLE_TAG_BY_DLL = 0x00008000
FLG_IGNORE_DEBUG_PRIV = 0x00010000
FLG_ENABLE_CSRDEBUG = 0x00020000
FLG_ENABLE_KDEBUG_SYMBOL_LOAD = 0x00040000
FLG_DISABLE_PAGE_KERNEL_STACKS = 0x00080000
FLG_HEAP_ENABLE_CALL_TRACING = 0x00100000
FLG_HEAP_DISABLE_COALESCING = 0x00200000
FLG_ENABLE_CLOSE_EXCEPTION = 0x00400000
FLG_ENABLE_EXCEPTION_LOGGING = 0x00800000
FLG_ENABLE_HANDLE_TYPE_TAGGING = 0x01000000
FLG_HEAP_PAGE_ALLOCS = 0x02000000
FLG_DEBUG_WINLOGON = 0x04000000
FLG_ENABLE_DBGPRINT_BUFFERING = 0x08000000
FLG_EARLY_CRITICAL_SECTION_EVT = 0x10000000
FLG_DISABLE_DLL_VERIFICATION = 0x80000000
class _PEB_NT(Structure):
_pack_ = 4
_fields_ = [
("InheritedAddressSpace", BOOLEAN),
("ReadImageFileExecOptions", UCHAR),
("BeingDebugged", BOOLEAN),
("BitField", UCHAR),
("Mutant", HANDLE),
("ImageBaseAddress", PVOID),
("Ldr", PVOID), # PPEB_LDR_DATA
("ProcessParameters", PVOID), # PRTL_USER_PROCESS_PARAMETERS
("SubSystemData", PVOID),
("ProcessHeap", PVOID),
("FastPebLock", PVOID),
("FastPebLockRoutine", PVOID), # PPEBLOCKROUTINE
("FastPebUnlockRoutine", PVOID), # PPEBLOCKROUTINE
("EnvironmentUpdateCount", ULONG),
("KernelCallbackTable", PVOID), # Ptr32 Ptr32 Void
("EventLogSection", PVOID),
("EventLog", PVOID),
("FreeList", PVOID), # PPEB_FREE_BLOCK
("TlsExpansionCounter", ULONG),
("TlsBitmap", PVOID),
("TlsBitmapBits", ULONG * 2),
("ReadOnlySharedMemoryBase", PVOID),
("ReadOnlySharedMemoryHeap", PVOID),
("ReadOnlyStaticServerData", PVOID), # Ptr32 Ptr32 Void
("AnsiCodePageData", PVOID),
("OemCodePageData", PVOID),
("UnicodeCaseTableData", PVOID),
("NumberOfProcessors", ULONG),
("NtGlobalFlag", ULONG),
("Spare2", BYTE * 4),
("CriticalSectionTimeout", LONGLONG), # LARGE_INTEGER
("HeapSegmentReserve", ULONG),
("HeapSegmentCommit", ULONG),
("HeapDeCommitTotalFreeThreshold", ULONG),
("HeapDeCommitFreeBlockThreshold", ULONG),
("NumberOfHeaps", ULONG),
("MaximumNumberOfHeaps", ULONG),
("ProcessHeaps", PVOID), # Ptr32 Ptr32 Void
("GdiSharedHandleTable", PVOID),
("ProcessStarterHelper", PVOID),
("GdiDCAttributeList", PVOID),
("LoaderLock", PVOID), # PRTL_CRITICAL_SECTION
("OSMajorVersion", ULONG),
("OSMinorVersion", ULONG),
("OSBuildNumber", ULONG),
("OSPlatformId", ULONG),
("ImageSubSystem", ULONG),
("ImageSubSystemMajorVersion", ULONG),
("ImageSubSystemMinorVersion", ULONG),
("ImageProcessAffinityMask", ULONG),
("GdiHandleBuffer", ULONG * 34),
("PostProcessInitRoutine", PPS_POST_PROCESS_INIT_ROUTINE),
("TlsExpansionBitmap", ULONG),
("TlsExpansionBitmapBits", BYTE * 128),
("SessionId", ULONG),
]
# not really, but "dt _PEB" in w2k isn't working for me :(
_PEB_2000 = _PEB_NT
# +0x000 InheritedAddressSpace : UChar
# +0x001 ReadImageFileExecOptions : UChar
# +0x002 BeingDebugged : UChar
# +0x003 SpareBool : UChar
# +0x004 Mutant : Ptr32 Void
# +0x008 ImageBaseAddress : Ptr32 Void
# +0x00c Ldr : Ptr32 _PEB_LDR_DATA
# +0x010 ProcessParameters : Ptr32 _RTL_USER_PROCESS_PARAMETERS
# +0x014 SubSystemData : Ptr32 Void
# +0x018 ProcessHeap : Ptr32 Void
# +0x01c FastPebLock : Ptr32 _RTL_CRITICAL_SECTION
# +0x020 FastPebLockRoutine : Ptr32 Void
# +0x024 FastPebUnlockRoutine : Ptr32 Void
# +0x028 EnvironmentUpdateCount : Uint4B
# +0x02c KernelCallbackTable : Ptr32 Void
# +0x030 SystemReserved : [1] Uint4B
# +0x034 AtlThunkSListPtr32 : Uint4B
# +0x038 FreeList : Ptr32 _PEB_FREE_BLOCK
# +0x03c TlsExpansionCounter : Uint4B
# +0x040 TlsBitmap : Ptr32 Void
# +0x044 TlsBitmapBits : [2] Uint4B
# +0x04c ReadOnlySharedMemoryBase : Ptr32 Void
# +0x050 ReadOnlySharedMemoryHeap : Ptr32 Void
# +0x054 ReadOnlyStaticServerData : Ptr32 Ptr32 Void
# +0x058 AnsiCodePageData : Ptr32 Void
# +0x05c OemCodePageData : Ptr32 Void
# +0x060 UnicodeCaseTableData : Ptr32 Void
# +0x064 NumberOfProcessors : Uint4B
# +0x068 NtGlobalFlag : Uint4B
# +0x070 CriticalSectionTimeout : _LARGE_INTEGER
# +0x078 HeapSegmentReserve : Uint4B
# +0x07c HeapSegmentCommit : Uint4B
# +0x080 HeapDeCommitTotalFreeThreshold : Uint4B
# +0x084 HeapDeCommitFreeBlockThreshold : Uint4B
# +0x088 NumberOfHeaps : Uint4B
# +0x08c MaximumNumberOfHeaps : Uint4B
# +0x090 ProcessHeaps : Ptr32 Ptr32 Void
# +0x094 GdiSharedHandleTable : Ptr32 Void
# +0x098 ProcessStarterHelper : Ptr32 Void
# +0x09c GdiDCAttributeList : Uint4B
# +0x0a0 LoaderLock : Ptr32 Void
# +0x0a4 OSMajorVersion : Uint4B
# +0x0a8 OSMinorVersion : Uint4B
# +0x0ac OSBuildNumber : Uint2B
# +0x0ae OSCSDVersion : Uint2B
# +0x0b0 OSPlatformId : Uint4B
# +0x0b4 ImageSubsystem : Uint4B
# +0x0b8 ImageSubsystemMajorVersion : Uint4B
# +0x0bc ImageSubsystemMinorVersion : Uint4B
# +0x0c0 ImageProcessAffinityMask : Uint4B
# +0x0c4 GdiHandleBuffer : [34] Uint4B
# +0x14c PostProcessInitRoutine : Ptr32 void
# +0x150 TlsExpansionBitmap : Ptr32 Void
# +0x154 TlsExpansionBitmapBits : [32] Uint4B
# +0x1d4 SessionId : Uint4B
# +0x1d8 AppCompatFlags : _ULARGE_INTEGER
# +0x1e0 AppCompatFlagsUser : _ULARGE_INTEGER
# +0x1e8 pShimData : Ptr32 Void
# +0x1ec AppCompatInfo : Ptr32 Void
# +0x1f0 CSDVersion : _UNICODE_STRING
# +0x1f8 ActivationContextData : Ptr32 Void
# +0x1fc ProcessAssemblyStorageMap : Ptr32 Void
# +0x200 SystemDefaultActivationContextData : Ptr32 Void
# +0x204 SystemAssemblyStorageMap : Ptr32 Void
# +0x208 MinimumStackCommit : Uint4B
class _PEB_XP(Structure):
_pack_ = 8
_fields_ = [
("InheritedAddressSpace", BOOLEAN),
("ReadImageFileExecOptions", UCHAR),
("BeingDebugged", BOOLEAN),
("SpareBool", UCHAR),
("Mutant", HANDLE),
("ImageBaseAddress", PVOID),
("Ldr", PVOID), # PPEB_LDR_DATA
("ProcessParameters", PVOID), # PRTL_USER_PROCESS_PARAMETERS
("SubSystemData", PVOID),
("ProcessHeap", PVOID),
("FastPebLock", PVOID),
("FastPebLockRoutine", PVOID),
("FastPebUnlockRoutine", PVOID),
("EnvironmentUpdateCount", DWORD),
("KernelCallbackTable", PVOID),
("SystemReserved", DWORD),
("AtlThunkSListPtr32", DWORD),
("FreeList", PVOID), # PPEB_FREE_BLOCK
("TlsExpansionCounter", DWORD),
("TlsBitmap", PVOID),
("TlsBitmapBits", DWORD * 2),
("ReadOnlySharedMemoryBase", PVOID),
("ReadOnlySharedMemoryHeap", PVOID),
("ReadOnlyStaticServerData", PVOID), # Ptr32 Ptr32 Void
("AnsiCodePageData", PVOID),
("OemCodePageData", PVOID),
("UnicodeCaseTableData", PVOID),
("NumberOfProcessors", DWORD),
("NtGlobalFlag", DWORD),
("CriticalSectionTimeout", LONGLONG), # LARGE_INTEGER
("HeapSegmentReserve", DWORD),
("HeapSegmentCommit", DWORD),
("HeapDeCommitTotalFreeThreshold", DWORD),
("HeapDeCommitFreeBlockThreshold", DWORD),
("NumberOfHeaps", DWORD),
("MaximumNumberOfHeaps", DWORD),
("ProcessHeaps", PVOID), # Ptr32 Ptr32 Void
("GdiSharedHandleTable", PVOID),
("ProcessStarterHelper", PVOID),
("GdiDCAttributeList", DWORD),
("LoaderLock", PVOID), # PRTL_CRITICAL_SECTION
("OSMajorVersion", DWORD),
("OSMinorVersion", DWORD),
("OSBuildNumber", WORD),
("OSCSDVersion", WORD),
("OSPlatformId", DWORD),
("ImageSubsystem", DWORD),
("ImageSubsystemMajorVersion", DWORD),
("ImageSubsystemMinorVersion", DWORD),
("ImageProcessAffinityMask", DWORD),
("GdiHandleBuffer", DWORD * 34),
("PostProcessInitRoutine", PPS_POST_PROCESS_INIT_ROUTINE),
("TlsExpansionBitmap", PVOID),
("TlsExpansionBitmapBits", DWORD * 32),
("SessionId", DWORD),
("AppCompatFlags", ULONGLONG), # ULARGE_INTEGER
("AppCompatFlagsUser", ULONGLONG), # ULARGE_INTEGER
("pShimData", PVOID),
("AppCompatInfo", PVOID),
("CSDVersion", UNICODE_STRING),
("ActivationContextData", PVOID), # ACTIVATION_CONTEXT_DATA
("ProcessAssemblyStorageMap", PVOID), # ASSEMBLY_STORAGE_MAP
("SystemDefaultActivationContextData", PVOID), # ACTIVATION_CONTEXT_DATA
("SystemAssemblyStorageMap", PVOID), # ASSEMBLY_STORAGE_MAP
("MinimumStackCommit", DWORD),
]
# +0x000 InheritedAddressSpace : UChar
# +0x001 ReadImageFileExecOptions : UChar
# +0x002 BeingDebugged : UChar
# +0x003 BitField : UChar
# +0x003 ImageUsesLargePages : Pos 0, 1 Bit
# +0x003 SpareBits : Pos 1, 7 Bits
# +0x008 Mutant : Ptr64 Void
# +0x010 ImageBaseAddress : Ptr64 Void
# +0x018 Ldr : Ptr64 _PEB_LDR_DATA
# +0x020 ProcessParameters : Ptr64 _RTL_USER_PROCESS_PARAMETERS
# +0x028 SubSystemData : Ptr64 Void
# +0x030 ProcessHeap : Ptr64 Void
# +0x038 FastPebLock : Ptr64 _RTL_CRITICAL_SECTION
# +0x040 AtlThunkSListPtr : Ptr64 Void
# +0x048 SparePtr2 : Ptr64 Void
# +0x050 EnvironmentUpdateCount : Uint4B
# +0x058 KernelCallbackTable : Ptr64 Void
# +0x060 SystemReserved : [1] Uint4B
# +0x064 SpareUlong : Uint4B
# +0x068 FreeList : Ptr64 _PEB_FREE_BLOCK
# +0x070 TlsExpansionCounter : Uint4B
# +0x078 TlsBitmap : Ptr64 Void
# +0x080 TlsBitmapBits : [2] Uint4B
# +0x088 ReadOnlySharedMemoryBase : Ptr64 Void
# +0x090 ReadOnlySharedMemoryHeap : Ptr64 Void
# +0x098 ReadOnlyStaticServerData : Ptr64 Ptr64 Void
# +0x0a0 AnsiCodePageData : Ptr64 Void
# +0x0a8 OemCodePageData : Ptr64 Void
# +0x0b0 UnicodeCaseTableData : Ptr64 Void
# +0x0b8 NumberOfProcessors : Uint4B
# +0x0bc NtGlobalFlag : Uint4B
# +0x0c0 CriticalSectionTimeout : _LARGE_INTEGER
# +0x0c8 HeapSegmentReserve : Uint8B
# +0x0d0 HeapSegmentCommit : Uint8B
# +0x0d8 HeapDeCommitTotalFreeThreshold : Uint8B
# +0x0e0 HeapDeCommitFreeBlockThreshold : Uint8B
# +0x0e8 NumberOfHeaps : Uint4B
# +0x0ec MaximumNumberOfHeaps : Uint4B
# +0x0f0 ProcessHeaps : Ptr64 Ptr64 Void
# +0x0f8 GdiSharedHandleTable : Ptr64 Void
# +0x100 ProcessStarterHelper : Ptr64 Void
# +0x108 GdiDCAttributeList : Uint4B
# +0x110 LoaderLock : Ptr64 _RTL_CRITICAL_SECTION
# +0x118 OSMajorVersion : Uint4B
# +0x11c OSMinorVersion : Uint4B
# +0x120 OSBuildNumber : Uint2B
# +0x122 OSCSDVersion : Uint2B
# +0x124 OSPlatformId : Uint4B
# +0x128 ImageSubsystem : Uint4B
# +0x12c ImageSubsystemMajorVersion : Uint4B
# +0x130 ImageSubsystemMinorVersion : Uint4B
# +0x138 ImageProcessAffinityMask : Uint8B
# +0x140 GdiHandleBuffer : [60] Uint4B
# +0x230 PostProcessInitRoutine : Ptr64 void
# +0x238 TlsExpansionBitmap : Ptr64 Void
# +0x240 TlsExpansionBitmapBits : [32] Uint4B
# +0x2c0 SessionId : Uint4B
# +0x2c8 AppCompatFlags : _ULARGE_INTEGER
# +0x2d0 AppCompatFlagsUser : _ULARGE_INTEGER
# +0x2d8 pShimData : Ptr64 Void
# +0x2e0 AppCompatInfo : Ptr64 Void
# +0x2e8 CSDVersion : _UNICODE_STRING
# +0x2f8 ActivationContextData : Ptr64 _ACTIVATION_CONTEXT_DATA
# +0x300 ProcessAssemblyStorageMap : Ptr64 _ASSEMBLY_STORAGE_MAP
# +0x308 SystemDefaultActivationContextData : Ptr64 _ACTIVATION_CONTEXT_DATA
# +0x310 SystemAssemblyStorageMap : Ptr64 _ASSEMBLY_STORAGE_MAP
# +0x318 MinimumStackCommit : Uint8B
# +0x320 FlsCallback : Ptr64 Ptr64 Void
# +0x328 FlsListHead : _LIST_ENTRY
# +0x338 FlsBitmap : Ptr64 Void
# +0x340 FlsBitmapBits : [4] Uint4B
# +0x350 FlsHighIndex : Uint4B
class _PEB_XP_64(Structure):
_pack_ = 8
_fields_ = [
("InheritedAddressSpace", BOOLEAN),
("ReadImageFileExecOptions", UCHAR),
("BeingDebugged", BOOLEAN),
("BitField", UCHAR),
("Mutant", HANDLE),
("ImageBaseAddress", PVOID),
("Ldr", PVOID), # PPEB_LDR_DATA
("ProcessParameters", PVOID), # PRTL_USER_PROCESS_PARAMETERS
("SubSystemData", PVOID),
("ProcessHeap", PVOID),
("FastPebLock", PVOID), # PRTL_CRITICAL_SECTION
("AtlThunkSListPtr", PVOID),
("SparePtr2", PVOID),
("EnvironmentUpdateCount", DWORD),
("KernelCallbackTable", PVOID),
("SystemReserved", DWORD),
("SpareUlong", DWORD),
("FreeList", PVOID), # PPEB_FREE_BLOCK
("TlsExpansionCounter", DWORD),
("TlsBitmap", PVOID),
("TlsBitmapBits", DWORD * 2),
("ReadOnlySharedMemoryBase", PVOID),
("ReadOnlySharedMemoryHeap", PVOID),
("ReadOnlyStaticServerData", PVOID), # Ptr64 Ptr64 Void
("AnsiCodePageData", PVOID),
("OemCodePageData", PVOID),
("UnicodeCaseTableData", PVOID),
("NumberOfProcessors", DWORD),
("NtGlobalFlag", DWORD),
("CriticalSectionTimeout", LONGLONG), # LARGE_INTEGER
("HeapSegmentReserve", QWORD),
("HeapSegmentCommit", QWORD),
("HeapDeCommitTotalFreeThreshold", QWORD),
("HeapDeCommitFreeBlockThreshold", QWORD),
("NumberOfHeaps", DWORD),
("MaximumNumberOfHeaps", DWORD),
("ProcessHeaps", PVOID), # Ptr64 Ptr64 Void
("GdiSharedHandleTable", PVOID),
("ProcessStarterHelper", PVOID),
("GdiDCAttributeList", DWORD),
("LoaderLock", PVOID), # PRTL_CRITICAL_SECTION
("OSMajorVersion", DWORD),
("OSMinorVersion", DWORD),
("OSBuildNumber", WORD),
("OSCSDVersion", WORD),
("OSPlatformId", DWORD),
("ImageSubsystem", DWORD),
("ImageSubsystemMajorVersion", DWORD),
("ImageSubsystemMinorVersion", DWORD),
("ImageProcessAffinityMask", QWORD),
("GdiHandleBuffer", DWORD * 60),
("PostProcessInitRoutine", PPS_POST_PROCESS_INIT_ROUTINE),
("TlsExpansionBitmap", PVOID),
("TlsExpansionBitmapBits", DWORD * 32),
("SessionId", DWORD),
("AppCompatFlags", ULONGLONG), # ULARGE_INTEGER
("AppCompatFlagsUser", ULONGLONG), # ULARGE_INTEGER
("pShimData", PVOID),
("AppCompatInfo", PVOID),
("CSDVersion", UNICODE_STRING),
("ActivationContextData", PVOID), # ACTIVATION_CONTEXT_DATA
("ProcessAssemblyStorageMap", PVOID), # ASSEMBLY_STORAGE_MAP
("SystemDefaultActivationContextData", PVOID), # ACTIVATION_CONTEXT_DATA
("SystemAssemblyStorageMap", PVOID), # ASSEMBLY_STORAGE_MAP
("MinimumStackCommit", QWORD),
("FlsCallback", PVOID), # Ptr64 Ptr64 Void
("FlsListHead", LIST_ENTRY),
("FlsBitmap", PVOID),
("FlsBitmapBits", DWORD * 4),
("FlsHighIndex", DWORD),
]
# +0x000 InheritedAddressSpace : UChar
# +0x001 ReadImageFileExecOptions : UChar
# +0x002 BeingDebugged : UChar
# +0x003 BitField : UChar
# +0x003 ImageUsesLargePages : Pos 0, 1 Bit
# +0x003 SpareBits : Pos 1, 7 Bits
# +0x004 Mutant : Ptr32 Void
# +0x008 ImageBaseAddress : Ptr32 Void
# +0x00c Ldr : Ptr32 _PEB_LDR_DATA
# +0x010 ProcessParameters : Ptr32 _RTL_USER_PROCESS_PARAMETERS
# +0x014 SubSystemData : Ptr32 Void
# +0x018 ProcessHeap : Ptr32 Void
# +0x01c FastPebLock : Ptr32 _RTL_CRITICAL_SECTION
# +0x020 AtlThunkSListPtr : Ptr32 Void
# +0x024 SparePtr2 : Ptr32 Void
# +0x028 EnvironmentUpdateCount : Uint4B
# +0x02c KernelCallbackTable : Ptr32 Void
# +0x030 SystemReserved : [1] Uint4B
# +0x034 SpareUlong : Uint4B
# +0x038 FreeList : Ptr32 _PEB_FREE_BLOCK
# +0x03c TlsExpansionCounter : Uint4B
# +0x040 TlsBitmap : Ptr32 Void
# +0x044 TlsBitmapBits : [2] Uint4B
# +0x04c ReadOnlySharedMemoryBase : Ptr32 Void
# +0x050 ReadOnlySharedMemoryHeap : Ptr32 Void
# +0x054 ReadOnlyStaticServerData : Ptr32 Ptr32 Void
# +0x058 AnsiCodePageData : Ptr32 Void
# +0x05c OemCodePageData : Ptr32 Void
# +0x060 UnicodeCaseTableData : Ptr32 Void
# +0x064 NumberOfProcessors : Uint4B
# +0x068 NtGlobalFlag : Uint4B
# +0x070 CriticalSectionTimeout : _LARGE_INTEGER
# +0x078 HeapSegmentReserve : Uint4B
# +0x07c HeapSegmentCommit : Uint4B
# +0x080 HeapDeCommitTotalFreeThreshold : Uint4B
# +0x084 HeapDeCommitFreeBlockThreshold : Uint4B
# +0x088 NumberOfHeaps : Uint4B
# +0x08c MaximumNumberOfHeaps : Uint4B
# +0x090 ProcessHeaps : Ptr32 Ptr32 Void
# +0x094 GdiSharedHandleTable : Ptr32 Void
# +0x098 ProcessStarterHelper : Ptr32 Void
# +0x09c GdiDCAttributeList : Uint4B
# +0x0a0 LoaderLock : Ptr32 _RTL_CRITICAL_SECTION
# +0x0a4 OSMajorVersion : Uint4B
# +0x0a8 OSMinorVersion : Uint4B
# +0x0ac OSBuildNumber : Uint2B
# +0x0ae OSCSDVersion : Uint2B
# +0x0b0 OSPlatformId : Uint4B
# +0x0b4 ImageSubsystem : Uint4B
# +0x0b8 ImageSubsystemMajorVersion : Uint4B
# +0x0bc ImageSubsystemMinorVersion : Uint4B
# +0x0c0 ImageProcessAffinityMask : Uint4B
# +0x0c4 GdiHandleBuffer : [34] Uint4B
# +0x14c PostProcessInitRoutine : Ptr32 void
# +0x150 TlsExpansionBitmap : Ptr32 Void
# +0x154 TlsExpansionBitmapBits : [32] Uint4B
# +0x1d4 SessionId : Uint4B
# +0x1d8 AppCompatFlags : _ULARGE_INTEGER
# +0x1e0 AppCompatFlagsUser : _ULARGE_INTEGER
# +0x1e8 pShimData : Ptr32 Void
# +0x1ec AppCompatInfo : Ptr32 Void
# +0x1f0 CSDVersion : _UNICODE_STRING
# +0x1f8 ActivationContextData : Ptr32 _ACTIVATION_CONTEXT_DATA
# +0x1fc ProcessAssemblyStorageMap : Ptr32 _ASSEMBLY_STORAGE_MAP
# +0x200 SystemDefaultActivationContextData : Ptr32 _ACTIVATION_CONTEXT_DATA
# +0x204 SystemAssemblyStorageMap : Ptr32 _ASSEMBLY_STORAGE_MAP
# +0x208 MinimumStackCommit : Uint4B
# +0x20c FlsCallback : Ptr32 Ptr32 Void
# +0x210 FlsListHead : _LIST_ENTRY
# +0x218 FlsBitmap : Ptr32 Void
# +0x21c FlsBitmapBits : [4] Uint4B
# +0x22c FlsHighIndex : Uint4B
class _PEB_2003(Structure):
_pack_ = 8
_fields_ = [
("InheritedAddressSpace", BOOLEAN),
("ReadImageFileExecOptions", UCHAR),
("BeingDebugged", BOOLEAN),
("BitField", UCHAR),
("Mutant", HANDLE),
("ImageBaseAddress", PVOID),
("Ldr", PVOID), # PPEB_LDR_DATA
("ProcessParameters", PVOID), # PRTL_USER_PROCESS_PARAMETERS
("SubSystemData", PVOID),
("ProcessHeap", PVOID),
("FastPebLock", PVOID), # PRTL_CRITICAL_SECTION
("AtlThunkSListPtr", PVOID),
("SparePtr2", PVOID),
("EnvironmentUpdateCount", DWORD),
("KernelCallbackTable", PVOID),
("SystemReserved", DWORD),
("SpareUlong", DWORD),
("FreeList", PVOID), # PPEB_FREE_BLOCK
("TlsExpansionCounter", DWORD),
("TlsBitmap", PVOID),
("TlsBitmapBits", DWORD * 2),
("ReadOnlySharedMemoryBase", PVOID),
("ReadOnlySharedMemoryHeap", PVOID),
("ReadOnlyStaticServerData", PVOID), # Ptr32 Ptr32 Void
("AnsiCodePageData", PVOID),
("OemCodePageData", PVOID),
("UnicodeCaseTableData", PVOID),
("NumberOfProcessors", DWORD),
("NtGlobalFlag", DWORD),
("CriticalSectionTimeout", LONGLONG), # LARGE_INTEGER
("HeapSegmentReserve", DWORD),
("HeapSegmentCommit", DWORD),
("HeapDeCommitTotalFreeThreshold", DWORD),
("HeapDeCommitFreeBlockThreshold", DWORD),
("NumberOfHeaps", DWORD),
("MaximumNumberOfHeaps", DWORD),
("ProcessHeaps", PVOID), # Ptr32 Ptr32 Void
("GdiSharedHandleTable", PVOID),
("ProcessStarterHelper", PVOID),
("GdiDCAttributeList", DWORD),
("LoaderLock", PVOID), # PRTL_CRITICAL_SECTION
("OSMajorVersion", DWORD),
("OSMinorVersion", DWORD),
("OSBuildNumber", WORD),
("OSCSDVersion", WORD),
("OSPlatformId", DWORD),
("ImageSubsystem", DWORD),
("ImageSubsystemMajorVersion", DWORD),
("ImageSubsystemMinorVersion", DWORD),
("ImageProcessAffinityMask", DWORD),
("GdiHandleBuffer", DWORD * 34),
("PostProcessInitRoutine", PPS_POST_PROCESS_INIT_ROUTINE),
("TlsExpansionBitmap", PVOID),
("TlsExpansionBitmapBits", DWORD * 32),
("SessionId", DWORD),
("AppCompatFlags", ULONGLONG), # ULARGE_INTEGER
("AppCompatFlagsUser", ULONGLONG), # ULARGE_INTEGER
("pShimData", PVOID),
("AppCompatInfo", PVOID),
("CSDVersion", UNICODE_STRING),
("ActivationContextData", PVOID), # ACTIVATION_CONTEXT_DATA
("ProcessAssemblyStorageMap", PVOID), # ASSEMBLY_STORAGE_MAP
("SystemDefaultActivationContextData", PVOID), # ACTIVATION_CONTEXT_DATA
("SystemAssemblyStorageMap", PVOID), # ASSEMBLY_STORAGE_MAP
("MinimumStackCommit", QWORD),
("FlsCallback", PVOID), # Ptr32 Ptr32 Void
("FlsListHead", LIST_ENTRY),
("FlsBitmap", PVOID),
("FlsBitmapBits", DWORD * 4),
("FlsHighIndex", DWORD),
]
_PEB_2003_64 = _PEB_XP_64
_PEB_2003_R2 = _PEB_2003
_PEB_2003_R2_64 = _PEB_2003_64
# +0x000 InheritedAddressSpace : UChar
# +0x001 ReadImageFileExecOptions : UChar
# +0x002 BeingDebugged : UChar
# +0x003 BitField : UChar
# +0x003 ImageUsesLargePages : Pos 0, 1 Bit
# +0x003 IsProtectedProcess : Pos 1, 1 Bit
# +0x003 IsLegacyProcess : Pos 2, 1 Bit
# +0x003 IsImageDynamicallyRelocated : Pos 3, 1 Bit
# +0x003 SkipPatchingUser32Forwarders : Pos 4, 1 Bit
# +0x003 SpareBits : Pos 5, 3 Bits
# +0x004 Mutant : Ptr32 Void
# +0x008 ImageBaseAddress : Ptr32 Void
# +0x00c Ldr : Ptr32 _PEB_LDR_DATA
# +0x010 ProcessParameters : Ptr32 _RTL_USER_PROCESS_PARAMETERS
# +0x014 SubSystemData : Ptr32 Void
# +0x018 ProcessHeap : Ptr32 Void
# +0x01c FastPebLock : Ptr32 _RTL_CRITICAL_SECTION
# +0x020 AtlThunkSListPtr : Ptr32 Void
# +0x024 IFEOKey : Ptr32 Void
# +0x028 CrossProcessFlags : Uint4B
# +0x028 ProcessInJob : Pos 0, 1 Bit
# +0x028 ProcessInitializing : Pos 1, 1 Bit
# +0x028 ProcessUsingVEH : Pos 2, 1 Bit
# +0x028 ProcessUsingVCH : Pos 3, 1 Bit
# +0x028 ReservedBits0 : Pos 4, 28 Bits
# +0x02c KernelCallbackTable : Ptr32 Void
# +0x02c UserSharedInfoPtr : Ptr32 Void
# +0x030 SystemReserved : [1] Uint4B
# +0x034 SpareUlong : Uint4B
# +0x038 SparePebPtr0 : Uint4B
# +0x03c TlsExpansionCounter : Uint4B
# +0x040 TlsBitmap : Ptr32 Void
# +0x044 TlsBitmapBits : [2] Uint4B
# +0x04c ReadOnlySharedMemoryBase : Ptr32 Void
# +0x050 HotpatchInformation : Ptr32 Void
# +0x054 ReadOnlyStaticServerData : Ptr32 Ptr32 Void
# +0x058 AnsiCodePageData : Ptr32 Void
# +0x05c OemCodePageData : Ptr32 Void
# +0x060 UnicodeCaseTableData : Ptr32 Void
# +0x064 NumberOfProcessors : Uint4B
# +0x068 NtGlobalFlag : Uint4B
# +0x070 CriticalSectionTimeout : _LARGE_INTEGER
# +0x078 HeapSegmentReserve : Uint4B
# +0x07c HeapSegmentCommit : Uint4B
# +0x080 HeapDeCommitTotalFreeThreshold : Uint4B
# +0x084 HeapDeCommitFreeBlockThreshold : Uint4B
# +0x088 NumberOfHeaps : Uint4B
# +0x08c MaximumNumberOfHeaps : Uint4B
# +0x090 ProcessHeaps : Ptr32 Ptr32 Void
# +0x094 GdiSharedHandleTable : Ptr32 Void
# +0x098 ProcessStarterHelper : Ptr32 Void
# +0x09c GdiDCAttributeList : Uint4B
# +0x0a0 LoaderLock : Ptr32 _RTL_CRITICAL_SECTION
# +0x0a4 OSMajorVersion : Uint4B
# +0x0a8 OSMinorVersion : Uint4B
# +0x0ac OSBuildNumber : Uint2B
# +0x0ae OSCSDVersion : Uint2B
# +0x0b0 OSPlatformId : Uint4B
# +0x0b4 ImageSubsystem : Uint4B
# +0x0b8 ImageSubsystemMajorVersion : Uint4B
# +0x0bc ImageSubsystemMinorVersion : Uint4B
# +0x0c0 ActiveProcessAffinityMask : Uint4B
# +0x0c4 GdiHandleBuffer : [34] Uint4B
# +0x14c PostProcessInitRoutine : Ptr32 void
# +0x150 TlsExpansionBitmap : Ptr32 Void
# +0x154 TlsExpansionBitmapBits : [32] Uint4B
# +0x1d4 SessionId : Uint4B
# +0x1d8 AppCompatFlags : _ULARGE_INTEGER
# +0x1e0 AppCompatFlagsUser : _ULARGE_INTEGER
# +0x1e8 pShimData : Ptr32 Void
# +0x1ec AppCompatInfo : Ptr32 Void
# +0x1f0 CSDVersion : _UNICODE_STRING
# +0x1f8 ActivationContextData : Ptr32 _ACTIVATION_CONTEXT_DATA
# +0x1fc ProcessAssemblyStorageMap : Ptr32 _ASSEMBLY_STORAGE_MAP
# +0x200 SystemDefaultActivationContextData : Ptr32 _ACTIVATION_CONTEXT_DATA
# +0x204 SystemAssemblyStorageMap : Ptr32 _ASSEMBLY_STORAGE_MAP
# +0x208 MinimumStackCommit : Uint4B
# +0x20c FlsCallback : Ptr32 _FLS_CALLBACK_INFO
# +0x210 FlsListHead : _LIST_ENTRY
# +0x218 FlsBitmap : Ptr32 Void
# +0x21c FlsBitmapBits : [4] Uint4B
# +0x22c FlsHighIndex : Uint4B
# +0x230 WerRegistrationData : Ptr32 Void
# +0x234 WerShipAssertPtr : Ptr32 Void
class _PEB_2008(Structure):
_pack_ = 8
_fields_ = [
("InheritedAddressSpace", BOOLEAN),
("ReadImageFileExecOptions", UCHAR),
("BeingDebugged", BOOLEAN),
("BitField", UCHAR),
("Mutant", HANDLE),
("ImageBaseAddress", PVOID),
("Ldr", PVOID), # PPEB_LDR_DATA
("ProcessParameters", PVOID), # PRTL_USER_PROCESS_PARAMETERS
("SubSystemData", PVOID),
("ProcessHeap", PVOID),
("FastPebLock", PVOID), # PRTL_CRITICAL_SECTION
("AtlThunkSListPtr", PVOID),
("IFEOKey", PVOID),
("CrossProcessFlags", DWORD),
("KernelCallbackTable", PVOID),
("SystemReserved", DWORD),
("SpareUlong", DWORD),
("SparePebPtr0", PVOID),
("TlsExpansionCounter", DWORD),
("TlsBitmap", PVOID),
("TlsBitmapBits", DWORD * 2),
("ReadOnlySharedMemoryBase", PVOID),
("HotpatchInformation", PVOID),
("ReadOnlyStaticServerData", PVOID), # Ptr32 Ptr32 Void
("AnsiCodePageData", PVOID),
("OemCodePageData", PVOID),
("UnicodeCaseTableData", PVOID),
("NumberOfProcessors", DWORD),
("NtGlobalFlag", DWORD),
("CriticalSectionTimeout", LONGLONG), # LARGE_INTEGER
("HeapSegmentReserve", DWORD),
("HeapSegmentCommit", DWORD),
("HeapDeCommitTotalFreeThreshold", DWORD),
("HeapDeCommitFreeBlockThreshold", DWORD),
("NumberOfHeaps", DWORD),
("MaximumNumberOfHeaps", DWORD),
("ProcessHeaps", PVOID), # Ptr32 Ptr32 Void
("GdiSharedHandleTable", PVOID),
("ProcessStarterHelper", PVOID),
("GdiDCAttributeList", DWORD),
("LoaderLock", PVOID), # PRTL_CRITICAL_SECTION
("OSMajorVersion", DWORD),
("OSMinorVersion", DWORD),
("OSBuildNumber", WORD),
("OSCSDVersion", WORD),
("OSPlatformId", DWORD),
("ImageSubsystem", DWORD),
("ImageSubsystemMajorVersion", DWORD),
("ImageSubsystemMinorVersion", DWORD),
("ActiveProcessAffinityMask", DWORD),
("GdiHandleBuffer", DWORD * 34),
("PostProcessInitRoutine", PPS_POST_PROCESS_INIT_ROUTINE),
("TlsExpansionBitmap", PVOID),
("TlsExpansionBitmapBits", DWORD * 32),
("SessionId", DWORD),
("AppCompatFlags", ULONGLONG), # ULARGE_INTEGER
("AppCompatFlagsUser", ULONGLONG), # ULARGE_INTEGER
("pShimData", PVOID),
("AppCompatInfo", PVOID),
("CSDVersion", UNICODE_STRING),
("ActivationContextData", PVOID), # ACTIVATION_CONTEXT_DATA
("ProcessAssemblyStorageMap", PVOID), # ASSEMBLY_STORAGE_MAP
("SystemDefaultActivationContextData", PVOID), # ACTIVATION_CONTEXT_DATA
("SystemAssemblyStorageMap", PVOID), # ASSEMBLY_STORAGE_MAP
("MinimumStackCommit", DWORD),
("FlsCallback", PVOID), # PFLS_CALLBACK_INFO
("FlsListHead", LIST_ENTRY),
("FlsBitmap", PVOID),
("FlsBitmapBits", DWORD * 4),
("FlsHighIndex", DWORD),
("WerRegistrationData", PVOID),
("WerShipAssertPtr", PVOID),
]
def __get_UserSharedInfoPtr(self):
return self.KernelCallbackTable
def __set_UserSharedInfoPtr(self, value):
self.KernelCallbackTable = value
UserSharedInfoPtr = property(__get_UserSharedInfoPtr, __set_UserSharedInfoPtr)
# +0x000 InheritedAddressSpace : UChar
# +0x001 ReadImageFileExecOptions : UChar
# +0x002 BeingDebugged : UChar
# +0x003 BitField : UChar
# +0x003 ImageUsesLargePages : Pos 0, 1 Bit
# +0x003 IsProtectedProcess : Pos 1, 1 Bit
# +0x003 IsLegacyProcess : Pos 2, 1 Bit
# +0x003 IsImageDynamicallyRelocated : Pos 3, 1 Bit
# +0x003 SkipPatchingUser32Forwarders : Pos 4, 1 Bit
# +0x003 SpareBits : Pos 5, 3 Bits
# +0x008 Mutant : Ptr64 Void
# +0x010 ImageBaseAddress : Ptr64 Void
# +0x018 Ldr : Ptr64 _PEB_LDR_DATA
# +0x020 ProcessParameters : Ptr64 _RTL_USER_PROCESS_PARAMETERS
# +0x028 SubSystemData : Ptr64 Void
# +0x030 ProcessHeap : Ptr64 Void
# +0x038 FastPebLock : Ptr64 _RTL_CRITICAL_SECTION
# +0x040 AtlThunkSListPtr : Ptr64 Void
# +0x048 IFEOKey : Ptr64 Void
# +0x050 CrossProcessFlags : Uint4B
# +0x050 ProcessInJob : Pos 0, 1 Bit
# +0x050 ProcessInitializing : Pos 1, 1 Bit
# +0x050 ProcessUsingVEH : Pos 2, 1 Bit
# +0x050 ProcessUsingVCH : Pos 3, 1 Bit
# +0x050 ReservedBits0 : Pos 4, 28 Bits
# +0x058 KernelCallbackTable : Ptr64 Void
# +0x058 UserSharedInfoPtr : Ptr64 Void
# +0x060 SystemReserved : [1] Uint4B
# +0x064 SpareUlong : Uint4B
# +0x068 SparePebPtr0 : Uint8B
# +0x070 TlsExpansionCounter : Uint4B
# +0x078 TlsBitmap : Ptr64 Void
# +0x080 TlsBitmapBits : [2] Uint4B
# +0x088 ReadOnlySharedMemoryBase : Ptr64 Void
# +0x090 HotpatchInformation : Ptr64 Void
# +0x098 ReadOnlyStaticServerData : Ptr64 Ptr64 Void
# +0x0a0 AnsiCodePageData : Ptr64 Void
# +0x0a8 OemCodePageData : Ptr64 Void
# +0x0b0 UnicodeCaseTableData : Ptr64 Void
# +0x0b8 NumberOfProcessors : Uint4B
# +0x0bc NtGlobalFlag : Uint4B
# +0x0c0 CriticalSectionTimeout : _LARGE_INTEGER
# +0x0c8 HeapSegmentReserve : Uint8B
# +0x0d0 HeapSegmentCommit : Uint8B
# +0x0d8 HeapDeCommitTotalFreeThreshold : Uint8B
# +0x0e0 HeapDeCommitFreeBlockThreshold : Uint8B
# +0x0e8 NumberOfHeaps : Uint4B
# +0x0ec MaximumNumberOfHeaps : Uint4B
# +0x0f0 ProcessHeaps : Ptr64 Ptr64 Void
# +0x0f8 GdiSharedHandleTable : Ptr64 Void
# +0x100 ProcessStarterHelper : Ptr64 Void
# +0x108 GdiDCAttributeList : Uint4B
# +0x110 LoaderLock : Ptr64 _RTL_CRITICAL_SECTION
# +0x118 OSMajorVersion : Uint4B
# +0x11c OSMinorVersion : Uint4B
# +0x120 OSBuildNumber : Uint2B
# +0x122 OSCSDVersion : Uint2B
# +0x124 OSPlatformId : Uint4B
# +0x128 ImageSubsystem : Uint4B
# +0x12c ImageSubsystemMajorVersion : Uint4B
# +0x130 ImageSubsystemMinorVersion : Uint4B
# +0x138 ActiveProcessAffinityMask : Uint8B
# +0x140 GdiHandleBuffer : [60] Uint4B
# +0x230 PostProcessInitRoutine : Ptr64 void
# +0x238 TlsExpansionBitmap : Ptr64 Void
# +0x240 TlsExpansionBitmapBits : [32] Uint4B
# +0x2c0 SessionId : Uint4B
# +0x2c8 AppCompatFlags : _ULARGE_INTEGER
# +0x2d0 AppCompatFlagsUser : _ULARGE_INTEGER
# +0x2d8 pShimData : Ptr64 Void
# +0x2e0 AppCompatInfo : Ptr64 Void
# +0x2e8 CSDVersion : _UNICODE_STRING
# +0x2f8 ActivationContextData : Ptr64 _ACTIVATION_CONTEXT_DATA
# +0x300 ProcessAssemblyStorageMap : Ptr64 _ASSEMBLY_STORAGE_MAP
# +0x308 SystemDefaultActivationContextData : Ptr64 _ACTIVATION_CONTEXT_DATA
# +0x310 SystemAssemblyStorageMap : Ptr64 _ASSEMBLY_STORAGE_MAP
# +0x318 MinimumStackCommit : Uint8B
# +0x320 FlsCallback : Ptr64 _FLS_CALLBACK_INFO
# +0x328 FlsListHead : _LIST_ENTRY
# +0x338 FlsBitmap : Ptr64 Void
# +0x340 FlsBitmapBits : [4] Uint4B
# +0x350 FlsHighIndex : Uint4B
# +0x358 WerRegistrationData : Ptr64 Void
# +0x360 WerShipAssertPtr : Ptr64 Void
class _PEB_2008_64(Structure):
_pack_ = 8
_fields_ = [
("InheritedAddressSpace", BOOLEAN),
("ReadImageFileExecOptions", UCHAR),
("BeingDebugged", BOOLEAN),
("BitField", UCHAR),
("Mutant", HANDLE),
("ImageBaseAddress", PVOID),
("Ldr", PVOID), # PPEB_LDR_DATA
("ProcessParameters", PVOID), # PRTL_USER_PROCESS_PARAMETERS
("SubSystemData", PVOID),
("ProcessHeap", PVOID),
("FastPebLock", PVOID), # PRTL_CRITICAL_SECTION
("AtlThunkSListPtr", PVOID),
("IFEOKey", PVOID),
("CrossProcessFlags", DWORD),
("KernelCallbackTable", PVOID),
("SystemReserved", DWORD),
("SpareUlong", DWORD),
("SparePebPtr0", PVOID),
("TlsExpansionCounter", DWORD),
("TlsBitmap", PVOID),
("TlsBitmapBits", DWORD * 2),
("ReadOnlySharedMemoryBase", PVOID),
("HotpatchInformation", PVOID),
("ReadOnlyStaticServerData", PVOID), # Ptr64 Ptr64 Void
("AnsiCodePageData", PVOID),
("OemCodePageData", PVOID),
("UnicodeCaseTableData", PVOID),
("NumberOfProcessors", DWORD),
("NtGlobalFlag", DWORD),
("CriticalSectionTimeout", LONGLONG), # LARGE_INTEGER
("HeapSegmentReserve", QWORD),
("HeapSegmentCommit", QWORD),
("HeapDeCommitTotalFreeThreshold", QWORD),
("HeapDeCommitFreeBlockThreshold", QWORD),
("NumberOfHeaps", DWORD),
("MaximumNumberOfHeaps", DWORD),
("ProcessHeaps", PVOID), # Ptr64 Ptr64 Void
("GdiSharedHandleTable", PVOID),
("ProcessStarterHelper", PVOID),
("GdiDCAttributeList", DWORD),
("LoaderLock", PVOID), # PRTL_CRITICAL_SECTION
("OSMajorVersion", DWORD),
("OSMinorVersion", DWORD),
("OSBuildNumber", WORD),
("OSCSDVersion", WORD),
("OSPlatformId", DWORD),
("ImageSubsystem", DWORD),
("ImageSubsystemMajorVersion", DWORD),
("ImageSubsystemMinorVersion", DWORD),
("ActiveProcessAffinityMask", QWORD),
("GdiHandleBuffer", DWORD * 60),
("PostProcessInitRoutine", PPS_POST_PROCESS_INIT_ROUTINE),
("TlsExpansionBitmap", PVOID),
("TlsExpansionBitmapBits", DWORD * 32),
("SessionId", DWORD),
("AppCompatFlags", ULONGLONG), # ULARGE_INTEGER
("AppCompatFlagsUser", ULONGLONG), # ULARGE_INTEGER
("pShimData", PVOID),
("AppCompatInfo", PVOID),
("CSDVersion", UNICODE_STRING),
("ActivationContextData", PVOID), # ACTIVATION_CONTEXT_DATA
("ProcessAssemblyStorageMap", PVOID), # ASSEMBLY_STORAGE_MAP
("SystemDefaultActivationContextData", PVOID), # ACTIVATION_CONTEXT_DATA
("SystemAssemblyStorageMap", PVOID), # ASSEMBLY_STORAGE_MAP
("MinimumStackCommit", QWORD),
("FlsCallback", PVOID), # PFLS_CALLBACK_INFO
("FlsListHead", LIST_ENTRY),
("FlsBitmap", PVOID),
("FlsBitmapBits", DWORD * 4),
("FlsHighIndex", DWORD),
("WerRegistrationData", PVOID),
("WerShipAssertPtr", PVOID),
]
def __get_UserSharedInfoPtr(self):
return self.KernelCallbackTable
def __set_UserSharedInfoPtr(self, value):
self.KernelCallbackTable = value
UserSharedInfoPtr = property(__get_UserSharedInfoPtr, __set_UserSharedInfoPtr)
# +0x000 InheritedAddressSpace : UChar
# +0x001 ReadImageFileExecOptions : UChar
# +0x002 BeingDebugged : UChar
# +0x003 BitField : UChar
# +0x003 ImageUsesLargePages : Pos 0, 1 Bit
# +0x003 IsProtectedProcess : Pos 1, 1 Bit
# +0x003 IsLegacyProcess : Pos 2, 1 Bit
# +0x003 IsImageDynamicallyRelocated : Pos 3, 1 Bit
# +0x003 SkipPatchingUser32Forwarders : Pos 4, 1 Bit
# +0x003 SpareBits : Pos 5, 3 Bits
# +0x004 Mutant : Ptr32 Void
# +0x008 ImageBaseAddress : Ptr32 Void
# +0x00c Ldr : Ptr32 _PEB_LDR_DATA
# +0x010 ProcessParameters : Ptr32 _RTL_USER_PROCESS_PARAMETERS
# +0x014 SubSystemData : Ptr32 Void
# +0x018 ProcessHeap : Ptr32 Void
# +0x01c FastPebLock : Ptr32 _RTL_CRITICAL_SECTION
# +0x020 AtlThunkSListPtr : Ptr32 Void
# +0x024 IFEOKey : Ptr32 Void
# +0x028 CrossProcessFlags : Uint4B
# +0x028 ProcessInJob : Pos 0, 1 Bit
# +0x028 ProcessInitializing : Pos 1, 1 Bit
# +0x028 ProcessUsingVEH : Pos 2, 1 Bit
# +0x028 ProcessUsingVCH : Pos 3, 1 Bit
# +0x028 ProcessUsingFTH : Pos 4, 1 Bit
# +0x028 ReservedBits0 : Pos 5, 27 Bits
# +0x02c KernelCallbackTable : Ptr32 Void
# +0x02c UserSharedInfoPtr : Ptr32 Void
# +0x030 SystemReserved : [1] Uint4B
# +0x034 AtlThunkSListPtr32 : Uint4B
# +0x038 ApiSetMap : Ptr32 Void
# +0x03c TlsExpansionCounter : Uint4B
# +0x040 TlsBitmap : Ptr32 Void
# +0x044 TlsBitmapBits : [2] Uint4B
# +0x04c ReadOnlySharedMemoryBase : Ptr32 Void
# +0x050 HotpatchInformation : Ptr32 Void
# +0x054 ReadOnlyStaticServerData : Ptr32 Ptr32 Void
# +0x058 AnsiCodePageData : Ptr32 Void
# +0x05c OemCodePageData : Ptr32 Void
# +0x060 UnicodeCaseTableData : Ptr32 Void
# +0x064 NumberOfProcessors : Uint4B
# +0x068 NtGlobalFlag : Uint4B
# +0x070 CriticalSectionTimeout : _LARGE_INTEGER
# +0x078 HeapSegmentReserve : Uint4B
# +0x07c HeapSegmentCommit : Uint4B
# +0x080 HeapDeCommitTotalFreeThreshold : Uint4B
# +0x084 HeapDeCommitFreeBlockThreshold : Uint4B
# +0x088 NumberOfHeaps : Uint4B
# +0x08c MaximumNumberOfHeaps : Uint4B
# +0x090 ProcessHeaps : Ptr32 Ptr32 Void
# +0x094 GdiSharedHandleTable : Ptr32 Void
# +0x098 ProcessStarterHelper : Ptr32 Void
# +0x09c GdiDCAttributeList : Uint4B
# +0x0a0 LoaderLock : Ptr32 _RTL_CRITICAL_SECTION
# +0x0a4 OSMajorVersion : Uint4B
# +0x0a8 OSMinorVersion : Uint4B
# +0x0ac OSBuildNumber : Uint2B
# +0x0ae OSCSDVersion : Uint2B
# +0x0b0 OSPlatformId : Uint4B
# +0x0b4 ImageSubsystem : Uint4B
# +0x0b8 ImageSubsystemMajorVersion : Uint4B
# +0x0bc ImageSubsystemMinorVersion : Uint4B
# +0x0c0 ActiveProcessAffinityMask : Uint4B
# +0x0c4 GdiHandleBuffer : [34] Uint4B
# +0x14c PostProcessInitRoutine : Ptr32 void
# +0x150 TlsExpansionBitmap : Ptr32 Void
# +0x154 TlsExpansionBitmapBits : [32] Uint4B
# +0x1d4 SessionId : Uint4B
# +0x1d8 AppCompatFlags : _ULARGE_INTEGER
# +0x1e0 AppCompatFlagsUser : _ULARGE_INTEGER
# +0x1e8 pShimData : Ptr32 Void
# +0x1ec AppCompatInfo : Ptr32 Void
# +0x1f0 CSDVersion : _UNICODE_STRING
# +0x1f8 ActivationContextData : Ptr32 _ACTIVATION_CONTEXT_DATA
# +0x1fc ProcessAssemblyStorageMap : Ptr32 _ASSEMBLY_STORAGE_MAP
# +0x200 SystemDefaultActivationContextData : Ptr32 _ACTIVATION_CONTEXT_DATA
# +0x204 SystemAssemblyStorageMap : Ptr32 _ASSEMBLY_STORAGE_MAP
# +0x208 MinimumStackCommit : Uint4B
# +0x20c FlsCallback : Ptr32 _FLS_CALLBACK_INFO
# +0x210 FlsListHead : _LIST_ENTRY
# +0x218 FlsBitmap : Ptr32 Void
# +0x21c FlsBitmapBits : [4] Uint4B
# +0x22c FlsHighIndex : Uint4B
# +0x230 WerRegistrationData : Ptr32 Void
# +0x234 WerShipAssertPtr : Ptr32 Void
# +0x238 pContextData : Ptr32 Void
# +0x23c pImageHeaderHash : Ptr32 Void
# +0x240 TracingFlags : Uint4B
# +0x240 HeapTracingEnabled : Pos 0, 1 Bit
# +0x240 CritSecTracingEnabled : Pos 1, 1 Bit
# +0x240 SpareTracingBits : Pos 2, 30 Bits
class _PEB_2008_R2(Structure):
_pack_ = 8
_fields_ = [
("InheritedAddressSpace", BOOLEAN),
("ReadImageFileExecOptions", UCHAR),
("BeingDebugged", BOOLEAN),
("BitField", UCHAR),
("Mutant", HANDLE),
("ImageBaseAddress", PVOID),
("Ldr", PVOID), # PPEB_LDR_DATA
("ProcessParameters", PVOID), # PRTL_USER_PROCESS_PARAMETERS
("SubSystemData", PVOID),
("ProcessHeap", PVOID),
("FastPebLock", PVOID), # PRTL_CRITICAL_SECTION
("AtlThunkSListPtr", PVOID),
("IFEOKey", PVOID),
("CrossProcessFlags", DWORD),
("KernelCallbackTable", PVOID),
("SystemReserved", DWORD),
("AtlThunkSListPtr32", PVOID),
("ApiSetMap", PVOID),
("TlsExpansionCounter", DWORD),
("TlsBitmap", PVOID),
("TlsBitmapBits", DWORD * 2),
("ReadOnlySharedMemoryBase", PVOID),
("HotpatchInformation", PVOID),
("ReadOnlyStaticServerData", PVOID), # Ptr32 Ptr32 Void
("AnsiCodePageData", PVOID),
("OemCodePageData", PVOID),
("UnicodeCaseTableData", PVOID),
("NumberOfProcessors", DWORD),
("NtGlobalFlag", DWORD),
("CriticalSectionTimeout", LONGLONG), # LARGE_INTEGER
("HeapSegmentReserve", DWORD),
("HeapSegmentCommit", DWORD),
("HeapDeCommitTotalFreeThreshold", DWORD),
("HeapDeCommitFreeBlockThreshold", DWORD),
("NumberOfHeaps", DWORD),
("MaximumNumberOfHeaps", DWORD),
("ProcessHeaps", PVOID), # Ptr32 Ptr32 Void
("GdiSharedHandleTable", PVOID),
("ProcessStarterHelper", PVOID),
("GdiDCAttributeList", DWORD),
("LoaderLock", PVOID), # PRTL_CRITICAL_SECTION
("OSMajorVersion", DWORD),
("OSMinorVersion", DWORD),
("OSBuildNumber", WORD),
("OSCSDVersion", WORD),
("OSPlatformId", DWORD),
("ImageSubsystem", DWORD),
("ImageSubsystemMajorVersion", DWORD),
("ImageSubsystemMinorVersion", DWORD),
("ActiveProcessAffinityMask", DWORD),
("GdiHandleBuffer", DWORD * 34),
("PostProcessInitRoutine", PPS_POST_PROCESS_INIT_ROUTINE),
("TlsExpansionBitmap", PVOID),
("TlsExpansionBitmapBits", DWORD * 32),
("SessionId", DWORD),
("AppCompatFlags", ULONGLONG), # ULARGE_INTEGER
("AppCompatFlagsUser", ULONGLONG), # ULARGE_INTEGER
("pShimData", PVOID),
("AppCompatInfo", PVOID),
("CSDVersion", UNICODE_STRING),
("ActivationContextData", PVOID), # ACTIVATION_CONTEXT_DATA
("ProcessAssemblyStorageMap", PVOID), # ASSEMBLY_STORAGE_MAP
("SystemDefaultActivationContextData", PVOID), # ACTIVATION_CONTEXT_DATA
("SystemAssemblyStorageMap", PVOID), # ASSEMBLY_STORAGE_MAP
("MinimumStackCommit", DWORD),
("FlsCallback", PVOID), # PFLS_CALLBACK_INFO
("FlsListHead", LIST_ENTRY),
("FlsBitmap", PVOID),
("FlsBitmapBits", DWORD * 4),
("FlsHighIndex", DWORD),
("WerRegistrationData", PVOID),
("WerShipAssertPtr", PVOID),
("pContextData", PVOID),
("pImageHeaderHash", PVOID),
("TracingFlags", DWORD),
]
def __get_UserSharedInfoPtr(self):
return self.KernelCallbackTable
def __set_UserSharedInfoPtr(self, value):
self.KernelCallbackTable = value
UserSharedInfoPtr = property(__get_UserSharedInfoPtr, __set_UserSharedInfoPtr)
# +0x000 InheritedAddressSpace : UChar
# +0x001 ReadImageFileExecOptions : UChar
# +0x002 BeingDebugged : UChar
# +0x003 BitField : UChar
# +0x003 ImageUsesLargePages : Pos 0, 1 Bit
# +0x003 IsProtectedProcess : Pos 1, 1 Bit
# +0x003 IsLegacyProcess : Pos 2, 1 Bit
# +0x003 IsImageDynamicallyRelocated : Pos 3, 1 Bit
# +0x003 SkipPatchingUser32Forwarders : Pos 4, 1 Bit
# +0x003 SpareBits : Pos 5, 3 Bits
# +0x008 Mutant : Ptr64 Void
# +0x010 ImageBaseAddress : Ptr64 Void
# +0x018 Ldr : Ptr64 _PEB_LDR_DATA
# +0x020 ProcessParameters : Ptr64 _RTL_USER_PROCESS_PARAMETERS
# +0x028 SubSystemData : Ptr64 Void
# +0x030 ProcessHeap : Ptr64 Void
# +0x038 FastPebLock : Ptr64 _RTL_CRITICAL_SECTION
# +0x040 AtlThunkSListPtr : Ptr64 Void
# +0x048 IFEOKey : Ptr64 Void
# +0x050 CrossProcessFlags : Uint4B
# +0x050 ProcessInJob : Pos 0, 1 Bit
# +0x050 ProcessInitializing : Pos 1, 1 Bit
# +0x050 ProcessUsingVEH : Pos 2, 1 Bit
# +0x050 ProcessUsingVCH : Pos 3, 1 Bit
# +0x050 ProcessUsingFTH : Pos 4, 1 Bit
# +0x050 ReservedBits0 : Pos 5, 27 Bits
# +0x058 KernelCallbackTable : Ptr64 Void
# +0x058 UserSharedInfoPtr : Ptr64 Void
# +0x060 SystemReserved : [1] Uint4B
# +0x064 AtlThunkSListPtr32 : Uint4B
# +0x068 ApiSetMap : Ptr64 Void
# +0x070 TlsExpansionCounter : Uint4B
# +0x078 TlsBitmap : Ptr64 Void
# +0x080 TlsBitmapBits : [2] Uint4B
# +0x088 ReadOnlySharedMemoryBase : Ptr64 Void
# +0x090 HotpatchInformation : Ptr64 Void
# +0x098 ReadOnlyStaticServerData : Ptr64 Ptr64 Void
# +0x0a0 AnsiCodePageData : Ptr64 Void
# +0x0a8 OemCodePageData : Ptr64 Void
# +0x0b0 UnicodeCaseTableData : Ptr64 Void
# +0x0b8 NumberOfProcessors : Uint4B
# +0x0bc NtGlobalFlag : Uint4B
# +0x0c0 CriticalSectionTimeout : _LARGE_INTEGER
# +0x0c8 HeapSegmentReserve : Uint8B
# +0x0d0 HeapSegmentCommit : Uint8B
# +0x0d8 HeapDeCommitTotalFreeThreshold : Uint8B
# +0x0e0 HeapDeCommitFreeBlockThreshold : Uint8B
# +0x0e8 NumberOfHeaps : Uint4B
# +0x0ec MaximumNumberOfHeaps : Uint4B
# +0x0f0 ProcessHeaps : Ptr64 Ptr64 Void
# +0x0f8 GdiSharedHandleTable : Ptr64 Void
# +0x100 ProcessStarterHelper : Ptr64 Void
# +0x108 GdiDCAttributeList : Uint4B
# +0x110 LoaderLock : Ptr64 _RTL_CRITICAL_SECTION
# +0x118 OSMajorVersion : Uint4B
# +0x11c OSMinorVersion : Uint4B
# +0x120 OSBuildNumber : Uint2B
# +0x122 OSCSDVersion : Uint2B
# +0x124 OSPlatformId : Uint4B
# +0x128 ImageSubsystem : Uint4B
# +0x12c ImageSubsystemMajorVersion : Uint4B
# +0x130 ImageSubsystemMinorVersion : Uint4B
# +0x138 ActiveProcessAffinityMask : Uint8B
# +0x140 GdiHandleBuffer : [60] Uint4B
# +0x230 PostProcessInitRoutine : Ptr64 void
# +0x238 TlsExpansionBitmap : Ptr64 Void
# +0x240 TlsExpansionBitmapBits : [32] Uint4B
# +0x2c0 SessionId : Uint4B
# +0x2c8 AppCompatFlags : _ULARGE_INTEGER
# +0x2d0 AppCompatFlagsUser : _ULARGE_INTEGER
# +0x2d8 pShimData : Ptr64 Void
# +0x2e0 AppCompatInfo : Ptr64 Void
# +0x2e8 CSDVersion : _UNICODE_STRING
# +0x2f8 ActivationContextData : Ptr64 _ACTIVATION_CONTEXT_DATA
# +0x300 ProcessAssemblyStorageMap : Ptr64 _ASSEMBLY_STORAGE_MAP
# +0x308 SystemDefaultActivationContextData : Ptr64 _ACTIVATION_CONTEXT_DATA
# +0x310 SystemAssemblyStorageMap : Ptr64 _ASSEMBLY_STORAGE_MAP
# +0x318 MinimumStackCommit : Uint8B
# +0x320 FlsCallback : Ptr64 _FLS_CALLBACK_INFO
# +0x328 FlsListHead : _LIST_ENTRY
# +0x338 FlsBitmap : Ptr64 Void
# +0x340 FlsBitmapBits : [4] Uint4B
# +0x350 FlsHighIndex : Uint4B
# +0x358 WerRegistrationData : Ptr64 Void
# +0x360 WerShipAssertPtr : Ptr64 Void
# +0x368 pContextData : Ptr64 Void
# +0x370 pImageHeaderHash : Ptr64 Void
# +0x378 TracingFlags : Uint4B
# +0x378 HeapTracingEnabled : Pos 0, 1 Bit
# +0x378 CritSecTracingEnabled : Pos 1, 1 Bit
# +0x378 SpareTracingBits : Pos 2, 30 Bits
class _PEB_2008_R2_64(Structure):
_pack_ = 8
_fields_ = [
("InheritedAddressSpace", BOOLEAN),
("ReadImageFileExecOptions", UCHAR),
("BeingDebugged", BOOLEAN),
("BitField", UCHAR),
("Mutant", HANDLE),
("ImageBaseAddress", PVOID),
("Ldr", PVOID), # PPEB_LDR_DATA
("ProcessParameters", PVOID), # PRTL_USER_PROCESS_PARAMETERS
("SubSystemData", PVOID),
("ProcessHeap", PVOID),
("FastPebLock", PVOID), # PRTL_CRITICAL_SECTION
("AtlThunkSListPtr", PVOID),
("IFEOKey", PVOID),
("CrossProcessFlags", DWORD),
("KernelCallbackTable", PVOID),
("SystemReserved", DWORD),
("AtlThunkSListPtr32", DWORD),
("ApiSetMap", PVOID),
("TlsExpansionCounter", DWORD),
("TlsBitmap", PVOID),
("TlsBitmapBits", DWORD * 2),
("ReadOnlySharedMemoryBase", PVOID),
("HotpatchInformation", PVOID),
("ReadOnlyStaticServerData", PVOID), # Ptr32 Ptr32 Void
("AnsiCodePageData", PVOID),
("OemCodePageData", PVOID),
("UnicodeCaseTableData", PVOID),
("NumberOfProcessors", DWORD),
("NtGlobalFlag", DWORD),
("CriticalSectionTimeout", LONGLONG), # LARGE_INTEGER
("HeapSegmentReserve", QWORD),
("HeapSegmentCommit", QWORD),
("HeapDeCommitTotalFreeThreshold", QWORD),
("HeapDeCommitFreeBlockThreshold", QWORD),
("NumberOfHeaps", DWORD),
("MaximumNumberOfHeaps", DWORD),
("ProcessHeaps", PVOID), # Ptr64 Ptr64 Void
("GdiSharedHandleTable", PVOID),
("ProcessStarterHelper", PVOID),
("GdiDCAttributeList", DWORD),
("LoaderLock", PVOID), # PRTL_CRITICAL_SECTION
("OSMajorVersion", DWORD),
("OSMinorVersion", DWORD),
("OSBuildNumber", WORD),
("OSCSDVersion", WORD),
("OSPlatformId", DWORD),
("ImageSubsystem", DWORD),
("ImageSubsystemMajorVersion", DWORD),
("ImageSubsystemMinorVersion", DWORD),
("ActiveProcessAffinityMask", QWORD),
("GdiHandleBuffer", DWORD * 60),
("PostProcessInitRoutine", PPS_POST_PROCESS_INIT_ROUTINE),
("TlsExpansionBitmap", PVOID),
("TlsExpansionBitmapBits", DWORD * 32),
("SessionId", DWORD),
("AppCompatFlags", ULONGLONG), # ULARGE_INTEGER
("AppCompatFlagsUser", ULONGLONG), # ULARGE_INTEGER
("pShimData", PVOID),
("AppCompatInfo", PVOID),
("CSDVersion", UNICODE_STRING),
("ActivationContextData", PVOID), # ACTIVATION_CONTEXT_DATA
("ProcessAssemblyStorageMap", PVOID), # ASSEMBLY_STORAGE_MAP
("SystemDefaultActivationContextData", PVOID), # ACTIVATION_CONTEXT_DATA
("SystemAssemblyStorageMap", PVOID), # ASSEMBLY_STORAGE_MAP
("MinimumStackCommit", QWORD),
("FlsCallback", PVOID), # PFLS_CALLBACK_INFO
("FlsListHead", LIST_ENTRY),
("FlsBitmap", PVOID),
("FlsBitmapBits", DWORD * 4),
("FlsHighIndex", DWORD),
("WerRegistrationData", PVOID),
("WerShipAssertPtr", PVOID),
("pContextData", PVOID),
("pImageHeaderHash", PVOID),
("TracingFlags", DWORD),
]
def __get_UserSharedInfoPtr(self):
return self.KernelCallbackTable
def __set_UserSharedInfoPtr(self, value):
self.KernelCallbackTable = value
UserSharedInfoPtr = property(__get_UserSharedInfoPtr, __set_UserSharedInfoPtr)
_PEB_Vista = _PEB_2008
_PEB_Vista_64 = _PEB_2008_64
_PEB_W7 = _PEB_2008_R2
_PEB_W7_64 = _PEB_2008_R2_64
# +0x000 InheritedAddressSpace : UChar
# +0x001 ReadImageFileExecOptions : UChar
# +0x002 BeingDebugged : UChar
# +0x003 BitField : UChar
# +0x003 ImageUsesLargePages : Pos 0, 1 Bit
# +0x003 IsProtectedProcess : Pos 1, 1 Bit
# +0x003 IsLegacyProcess : Pos 2, 1 Bit
# +0x003 IsImageDynamicallyRelocated : Pos 3, 1 Bit
# +0x003 SkipPatchingUser32Forwarders : Pos 4, 1 Bit
# +0x003 SpareBits : Pos 5, 3 Bits
# +0x004 Mutant : Ptr32 Void
# +0x008 ImageBaseAddress : Ptr32 Void
# +0x00c Ldr : Ptr32 _PEB_LDR_DATA
# +0x010 ProcessParameters : Ptr32 _RTL_USER_PROCESS_PARAMETERS
# +0x014 SubSystemData : Ptr32 Void
# +0x018 ProcessHeap : Ptr32 Void
# +0x01c FastPebLock : Ptr32 _RTL_CRITICAL_SECTION
# +0x020 AtlThunkSListPtr : Ptr32 Void
# +0x024 IFEOKey : Ptr32 Void
# +0x028 CrossProcessFlags : Uint4B
# +0x028 ProcessInJob : Pos 0, 1 Bit
# +0x028 ProcessInitializing : Pos 1, 1 Bit
# +0x028 ProcessUsingVEH : Pos 2, 1 Bit
# +0x028 ProcessUsingVCH : Pos 3, 1 Bit
# +0x028 ProcessUsingFTH : Pos 4, 1 Bit
# +0x028 ReservedBits0 : Pos 5, 27 Bits
# +0x02c KernelCallbackTable : Ptr32 Void
# +0x02c UserSharedInfoPtr : Ptr32 Void
# +0x030 SystemReserved : [1] Uint4B
# +0x034 TracingFlags : Uint4B
# +0x034 HeapTracingEnabled : Pos 0, 1 Bit
# +0x034 CritSecTracingEnabled : Pos 1, 1 Bit
# +0x034 SpareTracingBits : Pos 2, 30 Bits
# +0x038 ApiSetMap : Ptr32 Void
# +0x03c TlsExpansionCounter : Uint4B
# +0x040 TlsBitmap : Ptr32 Void
# +0x044 TlsBitmapBits : [2] Uint4B
# +0x04c ReadOnlySharedMemoryBase : Ptr32 Void
# +0x050 HotpatchInformation : Ptr32 Void
# +0x054 ReadOnlyStaticServerData : Ptr32 Ptr32 Void
# +0x058 AnsiCodePageData : Ptr32 Void
# +0x05c OemCodePageData : Ptr32 Void
# +0x060 UnicodeCaseTableData : Ptr32 Void
# +0x064 NumberOfProcessors : Uint4B
# +0x068 NtGlobalFlag : Uint4B
# +0x070 CriticalSectionTimeout : _LARGE_INTEGER
# +0x078 HeapSegmentReserve : Uint4B
# +0x07c HeapSegmentCommit : Uint4B
# +0x080 HeapDeCommitTotalFreeThreshold : Uint4B
# +0x084 HeapDeCommitFreeBlockThreshold : Uint4B
# +0x088 NumberOfHeaps : Uint4B
# +0x08c MaximumNumberOfHeaps : Uint4B
# +0x090 ProcessHeaps : Ptr32 Ptr32 Void
# +0x094 GdiSharedHandleTable : Ptr32 Void
# +0x098 ProcessStarterHelper : Ptr32 Void
# +0x09c GdiDCAttributeList : Uint4B
# +0x0a0 LoaderLock : Ptr32 _RTL_CRITICAL_SECTION
# +0x0a4 OSMajorVersion : Uint4B
# +0x0a8 OSMinorVersion : Uint4B
# +0x0ac OSBuildNumber : Uint2B
# +0x0ae OSCSDVersion : Uint2B
# +0x0b0 OSPlatformId : Uint4B
# +0x0b4 ImageSubsystem : Uint4B
# +0x0b8 ImageSubsystemMajorVersion : Uint4B
# +0x0bc ImageSubsystemMinorVersion : Uint4B
# +0x0c0 ActiveProcessAffinityMask : Uint4B
# +0x0c4 GdiHandleBuffer : [34] Uint4B
# +0x14c PostProcessInitRoutine : Ptr32 void
# +0x150 TlsExpansionBitmap : Ptr32 Void
# +0x154 TlsExpansionBitmapBits : [32] Uint4B
# +0x1d4 SessionId : Uint4B
# +0x1d8 AppCompatFlags : _ULARGE_INTEGER
# +0x1e0 AppCompatFlagsUser : _ULARGE_INTEGER
# +0x1e8 pShimData : Ptr32 Void
# +0x1ec AppCompatInfo : Ptr32 Void
# +0x1f0 CSDVersion : _UNICODE_STRING
# +0x1f8 ActivationContextData : Ptr32 _ACTIVATION_CONTEXT_DATA
# +0x1fc ProcessAssemblyStorageMap : Ptr32 _ASSEMBLY_STORAGE_MAP
# +0x200 SystemDefaultActivationContextData : Ptr32 _ACTIVATION_CONTEXT_DATA
# +0x204 SystemAssemblyStorageMap : Ptr32 _ASSEMBLY_STORAGE_MAP
# +0x208 MinimumStackCommit : Uint4B
# +0x20c FlsCallback : Ptr32 _FLS_CALLBACK_INFO
# +0x210 FlsListHead : _LIST_ENTRY
# +0x218 FlsBitmap : Ptr32 Void
# +0x21c FlsBitmapBits : [4] Uint4B
# +0x22c FlsHighIndex : Uint4B
# +0x230 WerRegistrationData : Ptr32 Void
# +0x234 WerShipAssertPtr : Ptr32 Void
# +0x238 pContextData : Ptr32 Void
# +0x23c pImageHeaderHash : Ptr32 Void
class _PEB_W7_Beta(Structure):
"""
This definition of the PEB structure is only valid for the beta versions
of Windows 7. For the final version of Windows 7 use L{_PEB_W7} instead.
This structure is not chosen automatically.
"""
_pack_ = 8
_fields_ = [
("InheritedAddressSpace", BOOLEAN),
("ReadImageFileExecOptions", UCHAR),
("BeingDebugged", BOOLEAN),
("BitField", UCHAR),
("Mutant", HANDLE),
("ImageBaseAddress", PVOID),
("Ldr", PVOID), # PPEB_LDR_DATA
("ProcessParameters", PVOID), # PRTL_USER_PROCESS_PARAMETERS
("SubSystemData", PVOID),
("ProcessHeap", PVOID),
("FastPebLock", PVOID), # PRTL_CRITICAL_SECTION
("AtlThunkSListPtr", PVOID),
("IFEOKey", PVOID),
("CrossProcessFlags", DWORD),
("KernelCallbackTable", PVOID),
("SystemReserved", DWORD),
("TracingFlags", DWORD),
("ApiSetMap", PVOID),
("TlsExpansionCounter", DWORD),
("TlsBitmap", PVOID),
("TlsBitmapBits", DWORD * 2),
("ReadOnlySharedMemoryBase", PVOID),
("HotpatchInformation", PVOID),
("ReadOnlyStaticServerData", PVOID), # Ptr32 Ptr32 Void
("AnsiCodePageData", PVOID),
("OemCodePageData", PVOID),
("UnicodeCaseTableData", PVOID),
("NumberOfProcessors", DWORD),
("NtGlobalFlag", DWORD),
("CriticalSectionTimeout", LONGLONG), # LARGE_INTEGER
("HeapSegmentReserve", DWORD),
("HeapSegmentCommit", DWORD),
("HeapDeCommitTotalFreeThreshold", DWORD),
("HeapDeCommitFreeBlockThreshold", DWORD),
("NumberOfHeaps", DWORD),
("MaximumNumberOfHeaps", DWORD),
("ProcessHeaps", PVOID), # Ptr32 Ptr32 Void
("GdiSharedHandleTable", PVOID),
("ProcessStarterHelper", PVOID),
("GdiDCAttributeList", DWORD),
("LoaderLock", PVOID), # PRTL_CRITICAL_SECTION
("OSMajorVersion", DWORD),
("OSMinorVersion", DWORD),
("OSBuildNumber", WORD),
("OSCSDVersion", WORD),
("OSPlatformId", DWORD),
("ImageSubsystem", DWORD),
("ImageSubsystemMajorVersion", DWORD),
("ImageSubsystemMinorVersion", DWORD),
("ActiveProcessAffinityMask", DWORD),
("GdiHandleBuffer", DWORD * 34),
("PostProcessInitRoutine", PPS_POST_PROCESS_INIT_ROUTINE),
("TlsExpansionBitmap", PVOID),
("TlsExpansionBitmapBits", DWORD * 32),
("SessionId", DWORD),
("AppCompatFlags", ULONGLONG), # ULARGE_INTEGER
("AppCompatFlagsUser", ULONGLONG), # ULARGE_INTEGER
("pShimData", PVOID),
("AppCompatInfo", PVOID),
("CSDVersion", UNICODE_STRING),
("ActivationContextData", PVOID), # ACTIVATION_CONTEXT_DATA
("ProcessAssemblyStorageMap", PVOID), # ASSEMBLY_STORAGE_MAP
("SystemDefaultActivationContextData", PVOID), # ACTIVATION_CONTEXT_DATA
("SystemAssemblyStorageMap", PVOID), # ASSEMBLY_STORAGE_MAP
("MinimumStackCommit", DWORD),
("FlsCallback", PVOID), # PFLS_CALLBACK_INFO
("FlsListHead", LIST_ENTRY),
("FlsBitmap", PVOID),
("FlsBitmapBits", DWORD * 4),
("FlsHighIndex", DWORD),
("WerRegistrationData", PVOID),
("WerShipAssertPtr", PVOID),
("pContextData", PVOID),
("pImageHeaderHash", PVOID),
]
def __get_UserSharedInfoPtr(self):
return self.KernelCallbackTable
def __set_UserSharedInfoPtr(self, value):
self.KernelCallbackTable = value
UserSharedInfoPtr = property(__get_UserSharedInfoPtr, __set_UserSharedInfoPtr)
# Use the correct PEB structure definition.
# Defaults to the latest Windows version.
class PEB(Structure):
_pack_ = 8
if os == 'Windows NT':
_pack_ = _PEB_NT._pack_
_fields_ = _PEB_NT._fields_
elif os == 'Windows 2000':
_pack_ = _PEB_2000._pack_
_fields_ = _PEB_2000._fields_
elif os == 'Windows XP':
_fields_ = _PEB_XP._fields_
elif os == 'Windows XP (64 bits)':
_fields_ = _PEB_XP_64._fields_
elif os == 'Windows 2003':
_fields_ = _PEB_2003._fields_
elif os == 'Windows 2003 (64 bits)':
_fields_ = _PEB_2003_64._fields_
elif os == 'Windows 2003 R2':
_fields_ = _PEB_2003_R2._fields_
elif os == 'Windows 2003 R2 (64 bits)':
_fields_ = _PEB_2003_R2_64._fields_
elif os == 'Windows 2008':
_fields_ = _PEB_2008._fields_
elif os == 'Windows 2008 (64 bits)':
_fields_ = _PEB_2008_64._fields_
elif os == 'Windows 2008 R2':
_fields_ = _PEB_2008_R2._fields_
elif os == 'Windows 2008 R2 (64 bits)':
_fields_ = _PEB_2008_R2_64._fields_
elif os == 'Windows Vista':
_fields_ = _PEB_Vista._fields_
elif os == 'Windows Vista (64 bits)':
_fields_ = _PEB_Vista_64._fields_
elif os == 'Windows 7':
_fields_ = _PEB_W7._fields_
elif os == 'Windows 7 (64 bits)':
_fields_ = _PEB_W7_64._fields_
elif sizeof(SIZE_T) == sizeof(DWORD):
_fields_ = _PEB_W7._fields_
else:
_fields_ = _PEB_W7_64._fields_
PPEB = POINTER(PEB)
# PEB structure for WOW64 processes.
class PEB_32(Structure):
_pack_ = 8
if os == 'Windows NT':
_pack_ = _PEB_NT._pack_
_fields_ = _PEB_NT._fields_
elif os == 'Windows 2000':
_pack_ = _PEB_2000._pack_
_fields_ = _PEB_2000._fields_
elif os.startswith('Windows XP'):
_fields_ = _PEB_XP._fields_
elif os.startswith('Windows 2003 R2'):
_fields_ = _PEB_2003_R2._fields_
elif os.startswith('Windows 2003'):
_fields_ = _PEB_2003._fields_
elif os.startswith('Windows 2008 R2'):
_fields_ = _PEB_2008_R2._fields_
elif os.startswith('Windows 2008'):
_fields_ = _PEB_2008._fields_
elif os.startswith('Windows Vista'):
_fields_ = _PEB_Vista._fields_
else: #if os.startswith('Windows 7'):
_fields_ = _PEB_W7._fields_
# from https://vmexplorer.svn.codeplex.com/svn/VMExplorer/src/Win32/Threads.cs
#
# [StructLayout (LayoutKind.Sequential, Size = 0x0C)]
# public struct Wx86ThreadState
# {
# public IntPtr CallBx86Eip; // Ptr32 to Uint4B
# public IntPtr DeallocationCpu; // Ptr32 to Void
# public Byte UseKnownWx86Dll; // UChar
# public Byte OleStubInvoked; // Char
# };
class Wx86ThreadState(Structure):
_fields_ = [
("CallBx86Eip", PVOID),
("DeallocationCpu", PVOID),
("UseKnownWx86Dll", UCHAR),
("OleStubInvoked", CHAR),
]
# ntdll!_RTL_ACTIVATION_CONTEXT_STACK_FRAME
# +0x000 Previous : Ptr64 _RTL_ACTIVATION_CONTEXT_STACK_FRAME
# +0x008 ActivationContext : Ptr64 _ACTIVATION_CONTEXT
# +0x010 Flags : Uint4B
class RTL_ACTIVATION_CONTEXT_STACK_FRAME(Structure):
_fields_ = [
("Previous", PVOID),
("ActivationContext", PVOID),
("Flags", DWORD),
]
# ntdll!_ACTIVATION_CONTEXT_STACK
# +0x000 ActiveFrame : Ptr64 _RTL_ACTIVATION_CONTEXT_STACK_FRAME
# +0x008 FrameListCache : _LIST_ENTRY
# +0x018 Flags : Uint4B
# +0x01c NextCookieSequenceNumber : Uint4B
# +0x020 StackId : Uint4B
class ACTIVATION_CONTEXT_STACK(Structure):
_fields_ = [
("ActiveFrame", PVOID),
("FrameListCache", LIST_ENTRY),
("Flags", DWORD),
("NextCookieSequenceNumber", DWORD),
("StackId", DWORD),
]
# typedef struct _PROCESSOR_NUMBER {
# WORD Group;
# BYTE Number;
# BYTE Reserved;
# }PROCESSOR_NUMBER, *PPROCESSOR_NUMBER;
class PROCESSOR_NUMBER(Structure):
_fields_ = [
("Group", WORD),
("Number", BYTE),
("Reserved", BYTE),
]
# from http://www.nirsoft.net/kernel_struct/vista/NT_TIB.html
#
# typedef struct _NT_TIB
# {
# PEXCEPTION_REGISTRATION_RECORD ExceptionList;
# PVOID StackBase;
# PVOID StackLimit;
# PVOID SubSystemTib;
# union
# {
# PVOID FiberData;
# ULONG Version;
# };
# PVOID ArbitraryUserPointer;
# PNT_TIB Self;
# } NT_TIB, *PNT_TIB;
class _NT_TIB_UNION(Union):
_fields_ = [
("FiberData", PVOID),
("Version", ULONG),
]
class NT_TIB(Structure):
_fields_ = [
("ExceptionList", PVOID), # PEXCEPTION_REGISTRATION_RECORD
("StackBase", PVOID),
("StackLimit", PVOID),
("SubSystemTib", PVOID),
("u", _NT_TIB_UNION),
("ArbitraryUserPointer", PVOID),
("Self", PVOID), # PNTTIB
]
def __get_FiberData(self):
return self.u.FiberData
def __set_FiberData(self, value):
self.u.FiberData = value
FiberData = property(__get_FiberData, __set_FiberData)
def __get_Version(self):
return self.u.Version
def __set_Version(self, value):
self.u.Version = value
Version = property(__get_Version, __set_Version)
PNTTIB = POINTER(NT_TIB)
# From http://www.nirsoft.net/kernel_struct/vista/EXCEPTION_REGISTRATION_RECORD.html
#
# typedef struct _EXCEPTION_REGISTRATION_RECORD
# {
# PEXCEPTION_REGISTRATION_RECORD Next;
# PEXCEPTION_DISPOSITION Handler;
# } EXCEPTION_REGISTRATION_RECORD, *PEXCEPTION_REGISTRATION_RECORD;
class EXCEPTION_REGISTRATION_RECORD(Structure):
pass
EXCEPTION_DISPOSITION = DWORD
##PEXCEPTION_DISPOSITION = POINTER(EXCEPTION_DISPOSITION)
##PEXCEPTION_REGISTRATION_RECORD = POINTER(EXCEPTION_REGISTRATION_RECORD)
PEXCEPTION_DISPOSITION = PVOID
PEXCEPTION_REGISTRATION_RECORD = PVOID
EXCEPTION_REGISTRATION_RECORD._fields_ = [
("Next", PEXCEPTION_REGISTRATION_RECORD),
("Handler", PEXCEPTION_DISPOSITION),
]
##PPEB = POINTER(PEB)
PPEB = PVOID
# From http://www.nirsoft.net/kernel_struct/vista/GDI_TEB_BATCH.html
#
# typedef struct _GDI_TEB_BATCH
# {
# ULONG Offset;
# ULONG HDC;
# ULONG Buffer[310];
# } GDI_TEB_BATCH, *PGDI_TEB_BATCH;
class GDI_TEB_BATCH(Structure):
_fields_ = [
("Offset", ULONG),
("HDC", ULONG),
("Buffer", ULONG * 310),
]
# ntdll!_TEB_ACTIVE_FRAME_CONTEXT
# +0x000 Flags : Uint4B
# +0x008 FrameName : Ptr64 Char
class TEB_ACTIVE_FRAME_CONTEXT(Structure):
_fields_ = [
("Flags", DWORD),
("FrameName", LPVOID), # LPCHAR
]
PTEB_ACTIVE_FRAME_CONTEXT = POINTER(TEB_ACTIVE_FRAME_CONTEXT)
# ntdll!_TEB_ACTIVE_FRAME
# +0x000 Flags : Uint4B
# +0x008 Previous : Ptr64 _TEB_ACTIVE_FRAME
# +0x010 Context : Ptr64 _TEB_ACTIVE_FRAME_CONTEXT
class TEB_ACTIVE_FRAME(Structure):
_fields_ = [
("Flags", DWORD),
("Previous", LPVOID), # PTEB_ACTIVE_FRAME
("Context", LPVOID), # PTEB_ACTIVE_FRAME_CONTEXT
]
PTEB_ACTIVE_FRAME = POINTER(TEB_ACTIVE_FRAME)
# SameTebFlags
DbgSafeThunkCall = 1 << 0
DbgInDebugPrint = 1 << 1
DbgHasFiberData = 1 << 2
DbgSkipThreadAttach = 1 << 3
DbgWerInShipAssertCode = 1 << 4
DbgRanProcessInit = 1 << 5
DbgClonedThread = 1 << 6
DbgSuppressDebugMsg = 1 << 7
RtlDisableUserStackWalk = 1 << 8
RtlExceptionAttached = 1 << 9
RtlInitialThread = 1 << 10
# XXX This is quite wrong :P
class _TEB_NT(Structure):
_pack_ = 4
_fields_ = [
("NtTib", NT_TIB),
("EnvironmentPointer", PVOID),
("ClientId", CLIENT_ID),
("ActiveRpcHandle", HANDLE),
("ThreadLocalStoragePointer", PVOID),
("ProcessEnvironmentBlock", PPEB),
("LastErrorValue", ULONG),
("CountOfOwnedCriticalSections", ULONG),
("CsrClientThread", PVOID),
("Win32ThreadInfo", PVOID),
("User32Reserved", ULONG * 26),
("UserReserved", ULONG * 5),
("WOW32Reserved", PVOID), # ptr to wow64cpu!X86SwitchTo64BitMode
("CurrentLocale", ULONG),
("FpSoftwareStatusRegister", ULONG),
("SystemReserved1", PVOID * 54),
("Spare1", PVOID),
("ExceptionCode", ULONG),
("ActivationContextStackPointer", PVOID), # PACTIVATION_CONTEXT_STACK
("SpareBytes1", ULONG * 36),
("TxFsContext", ULONG),
("GdiTebBatch", GDI_TEB_BATCH),
("RealClientId", CLIENT_ID),
("GdiCachedProcessHandle", PVOID),
("GdiClientPID", ULONG),
("GdiClientTID", ULONG),
("GdiThreadLocalInfo", PVOID),
("Win32ClientInfo", PVOID * 62),
("glDispatchTable", PVOID * 233),
("glReserved1", ULONG * 29),
("glReserved2", PVOID),
("glSectionInfo", PVOID),
("glSection", PVOID),
("glTable", PVOID),
("glCurrentRC", PVOID),
("glContext", PVOID),
("LastStatusValue", NTSTATUS),
("StaticUnicodeString", UNICODE_STRING),
("StaticUnicodeBuffer", WCHAR * 261),
("DeallocationStack", PVOID),
("TlsSlots", PVOID * 64),
("TlsLinks", LIST_ENTRY),
("Vdm", PVOID),
("ReservedForNtRpc", PVOID),
("DbgSsReserved", PVOID * 2),
("HardErrorDisabled", ULONG),
("Instrumentation", PVOID * 9),
("ActivityId", GUID),
("SubProcessTag", PVOID),
("EtwLocalData", PVOID),
("EtwTraceData", PVOID),
("WinSockData", PVOID),
("GdiBatchCount", ULONG),
("SpareBool0", BOOLEAN),
("SpareBool1", BOOLEAN),
("SpareBool2", BOOLEAN),
("IdealProcessor", UCHAR),
("GuaranteedStackBytes", ULONG),
("ReservedForPerf", PVOID),
("ReservedForOle", PVOID),
("WaitingOnLoaderLock", ULONG),
("StackCommit", PVOID),
("StackCommitMax", PVOID),
("StackReserved", PVOID),
]
# not really, but "dt _TEB" in w2k isn't working for me :(
_TEB_2000 = _TEB_NT
# +0x000 NtTib : _NT_TIB
# +0x01c EnvironmentPointer : Ptr32 Void
# +0x020 ClientId : _CLIENT_ID
# +0x028 ActiveRpcHandle : Ptr32 Void
# +0x02c ThreadLocalStoragePointer : Ptr32 Void
# +0x030 ProcessEnvironmentBlock : Ptr32 _PEB
# +0x034 LastErrorValue : Uint4B
# +0x038 CountOfOwnedCriticalSections : Uint4B
# +0x03c CsrClientThread : Ptr32 Void
# +0x040 Win32ThreadInfo : Ptr32 Void
# +0x044 User32Reserved : [26] Uint4B
# +0x0ac UserReserved : [5] Uint4B
# +0x0c0 WOW32Reserved : Ptr32 Void
# +0x0c4 CurrentLocale : Uint4B
# +0x0c8 FpSoftwareStatusRegister : Uint4B
# +0x0cc SystemReserved1 : [54] Ptr32 Void
# +0x1a4 ExceptionCode : Int4B
# +0x1a8 ActivationContextStack : _ACTIVATION_CONTEXT_STACK
# +0x1bc SpareBytes1 : [24] UChar
# +0x1d4 GdiTebBatch : _GDI_TEB_BATCH
# +0x6b4 RealClientId : _CLIENT_ID
# +0x6bc GdiCachedProcessHandle : Ptr32 Void
# +0x6c0 GdiClientPID : Uint4B
# +0x6c4 GdiClientTID : Uint4B
# +0x6c8 GdiThreadLocalInfo : Ptr32 Void
# +0x6cc Win32ClientInfo : [62] Uint4B
# +0x7c4 glDispatchTable : [233] Ptr32 Void
# +0xb68 glReserved1 : [29] Uint4B
# +0xbdc glReserved2 : Ptr32 Void
# +0xbe0 glSectionInfo : Ptr32 Void
# +0xbe4 glSection : Ptr32 Void
# +0xbe8 glTable : Ptr32 Void
# +0xbec glCurrentRC : Ptr32 Void
# +0xbf0 glContext : Ptr32 Void
# +0xbf4 LastStatusValue : Uint4B
# +0xbf8 StaticUnicodeString : _UNICODE_STRING
# +0xc00 StaticUnicodeBuffer : [261] Uint2B
# +0xe0c DeallocationStack : Ptr32 Void
# +0xe10 TlsSlots : [64] Ptr32 Void
# +0xf10 TlsLinks : _LIST_ENTRY
# +0xf18 Vdm : Ptr32 Void
# +0xf1c ReservedForNtRpc : Ptr32 Void
# +0xf20 DbgSsReserved : [2] Ptr32 Void
# +0xf28 HardErrorsAreDisabled : Uint4B
# +0xf2c Instrumentation : [16] Ptr32 Void
# +0xf6c WinSockData : Ptr32 Void
# +0xf70 GdiBatchCount : Uint4B
# +0xf74 InDbgPrint : UChar
# +0xf75 FreeStackOnTermination : UChar
# +0xf76 HasFiberData : UChar
# +0xf77 IdealProcessor : UChar
# +0xf78 Spare3 : Uint4B
# +0xf7c ReservedForPerf : Ptr32 Void
# +0xf80 ReservedForOle : Ptr32 Void
# +0xf84 WaitingOnLoaderLock : Uint4B
# +0xf88 Wx86Thread : _Wx86ThreadState
# +0xf94 TlsExpansionSlots : Ptr32 Ptr32 Void
# +0xf98 ImpersonationLocale : Uint4B
# +0xf9c IsImpersonating : Uint4B
# +0xfa0 NlsCache : Ptr32 Void
# +0xfa4 pShimData : Ptr32 Void
# +0xfa8 HeapVirtualAffinity : Uint4B
# +0xfac CurrentTransactionHandle : Ptr32 Void
# +0xfb0 ActiveFrame : Ptr32 _TEB_ACTIVE_FRAME
# +0xfb4 SafeThunkCall : UChar
# +0xfb5 BooleanSpare : [3] UChar
class _TEB_XP(Structure):
_pack_ = 8
_fields_ = [
("NtTib", NT_TIB),
("EnvironmentPointer", PVOID),
("ClientId", CLIENT_ID),
("ActiveRpcHandle", HANDLE),
("ThreadLocalStoragePointer", PVOID),
("ProcessEnvironmentBlock", PVOID), # PPEB
("LastErrorValue", DWORD),
("CountOfOwnedCriticalSections", DWORD),
("CsrClientThread", PVOID),
("Win32ThreadInfo", PVOID),
("User32Reserved", DWORD * 26),
("UserReserved", DWORD * 5),
("WOW32Reserved", PVOID), # ptr to wow64cpu!X86SwitchTo64BitMode
("CurrentLocale", DWORD),
("FpSoftwareStatusRegister", DWORD),
("SystemReserved1", PVOID * 54),
("ExceptionCode", SDWORD),
("ActivationContextStackPointer", PVOID), # PACTIVATION_CONTEXT_STACK
("SpareBytes1", UCHAR * 24),
("TxFsContext", DWORD),
("GdiTebBatch", GDI_TEB_BATCH),
("RealClientId", CLIENT_ID),
("GdiCachedProcessHandle", HANDLE),
("GdiClientPID", DWORD),
("GdiClientTID", DWORD),
("GdiThreadLocalInfo", PVOID),
("Win32ClientInfo", DWORD * 62),
("glDispatchTable", PVOID * 233),
("glReserved1", DWORD * 29),
("glReserved2", PVOID),
("glSectionInfo", PVOID),
("glSection", PVOID),
("glTable", PVOID),
("glCurrentRC", PVOID),
("glContext", PVOID),
("LastStatusValue", NTSTATUS),
("StaticUnicodeString", UNICODE_STRING),
("StaticUnicodeBuffer", WCHAR * 261),
("DeallocationStack", PVOID),
("TlsSlots", PVOID * 64),
("TlsLinks", LIST_ENTRY),
("Vdm", PVOID),
("ReservedForNtRpc", PVOID),
("DbgSsReserved", PVOID * 2),
("HardErrorsAreDisabled", DWORD),
("Instrumentation", PVOID * 16),
("WinSockData", PVOID),
("GdiBatchCount", DWORD),
("InDbgPrint", BOOLEAN),
("FreeStackOnTermination", BOOLEAN),
("HasFiberData", BOOLEAN),
("IdealProcessor", UCHAR),
("Spare3", DWORD),
("ReservedForPerf", PVOID),
("ReservedForOle", PVOID),
("WaitingOnLoaderLock", DWORD),
("Wx86Thread", Wx86ThreadState),
("TlsExpansionSlots", PVOID), # Ptr32 Ptr32 Void
("ImpersonationLocale", DWORD),
("IsImpersonating", BOOL),
("NlsCache", PVOID),
("pShimData", PVOID),
("HeapVirtualAffinity", DWORD),
("CurrentTransactionHandle", HANDLE),
("ActiveFrame", PVOID), # PTEB_ACTIVE_FRAME
("SafeThunkCall", BOOLEAN),
("BooleanSpare", BOOLEAN * 3),
]
# +0x000 NtTib : _NT_TIB
# +0x038 EnvironmentPointer : Ptr64 Void
# +0x040 ClientId : _CLIENT_ID
# +0x050 ActiveRpcHandle : Ptr64 Void
# +0x058 ThreadLocalStoragePointer : Ptr64 Void
# +0x060 ProcessEnvironmentBlock : Ptr64 _PEB
# +0x068 LastErrorValue : Uint4B
# +0x06c CountOfOwnedCriticalSections : Uint4B
# +0x070 CsrClientThread : Ptr64 Void
# +0x078 Win32ThreadInfo : Ptr64 Void
# +0x080 User32Reserved : [26] Uint4B
# +0x0e8 UserReserved : [5] Uint4B
# +0x100 WOW32Reserved : Ptr64 Void
# +0x108 CurrentLocale : Uint4B
# +0x10c FpSoftwareStatusRegister : Uint4B
# +0x110 SystemReserved1 : [54] Ptr64 Void
# +0x2c0 ExceptionCode : Int4B
# +0x2c8 ActivationContextStackPointer : Ptr64 _ACTIVATION_CONTEXT_STACK
# +0x2d0 SpareBytes1 : [28] UChar
# +0x2f0 GdiTebBatch : _GDI_TEB_BATCH
# +0x7d8 RealClientId : _CLIENT_ID
# +0x7e8 GdiCachedProcessHandle : Ptr64 Void
# +0x7f0 GdiClientPID : Uint4B
# +0x7f4 GdiClientTID : Uint4B
# +0x7f8 GdiThreadLocalInfo : Ptr64 Void
# +0x800 Win32ClientInfo : [62] Uint8B
# +0x9f0 glDispatchTable : [233] Ptr64 Void
# +0x1138 glReserved1 : [29] Uint8B
# +0x1220 glReserved2 : Ptr64 Void
# +0x1228 glSectionInfo : Ptr64 Void
# +0x1230 glSection : Ptr64 Void
# +0x1238 glTable : Ptr64 Void
# +0x1240 glCurrentRC : Ptr64 Void
# +0x1248 glContext : Ptr64 Void
# +0x1250 LastStatusValue : Uint4B
# +0x1258 StaticUnicodeString : _UNICODE_STRING
# +0x1268 StaticUnicodeBuffer : [261] Uint2B
# +0x1478 DeallocationStack : Ptr64 Void
# +0x1480 TlsSlots : [64] Ptr64 Void
# +0x1680 TlsLinks : _LIST_ENTRY
# +0x1690 Vdm : Ptr64 Void
# +0x1698 ReservedForNtRpc : Ptr64 Void
# +0x16a0 DbgSsReserved : [2] Ptr64 Void
# +0x16b0 HardErrorMode : Uint4B
# +0x16b8 Instrumentation : [14] Ptr64 Void
# +0x1728 SubProcessTag : Ptr64 Void
# +0x1730 EtwTraceData : Ptr64 Void
# +0x1738 WinSockData : Ptr64 Void
# +0x1740 GdiBatchCount : Uint4B
# +0x1744 InDbgPrint : UChar
# +0x1745 FreeStackOnTermination : UChar
# +0x1746 HasFiberData : UChar
# +0x1747 IdealProcessor : UChar
# +0x1748 GuaranteedStackBytes : Uint4B
# +0x1750 ReservedForPerf : Ptr64 Void
# +0x1758 ReservedForOle : Ptr64 Void
# +0x1760 WaitingOnLoaderLock : Uint4B
# +0x1768 SparePointer1 : Uint8B
# +0x1770 SoftPatchPtr1 : Uint8B
# +0x1778 SoftPatchPtr2 : Uint8B
# +0x1780 TlsExpansionSlots : Ptr64 Ptr64 Void
# +0x1788 DeallocationBStore : Ptr64 Void
# +0x1790 BStoreLimit : Ptr64 Void
# +0x1798 ImpersonationLocale : Uint4B
# +0x179c IsImpersonating : Uint4B
# +0x17a0 NlsCache : Ptr64 Void
# +0x17a8 pShimData : Ptr64 Void
# +0x17b0 HeapVirtualAffinity : Uint4B
# +0x17b8 CurrentTransactionHandle : Ptr64 Void
# +0x17c0 ActiveFrame : Ptr64 _TEB_ACTIVE_FRAME
# +0x17c8 FlsData : Ptr64 Void
# +0x17d0 SafeThunkCall : UChar
# +0x17d1 BooleanSpare : [3] UChar
class _TEB_XP_64(Structure):
_pack_ = 8
_fields_ = [
("NtTib", NT_TIB),
("EnvironmentPointer", PVOID),
("ClientId", CLIENT_ID),
("ActiveRpcHandle", PVOID),
("ThreadLocalStoragePointer", PVOID),
("ProcessEnvironmentBlock", PVOID), # PPEB
("LastErrorValue", DWORD),
("CountOfOwnedCriticalSections", DWORD),
("CsrClientThread", PVOID),
("Win32ThreadInfo", PVOID),
("User32Reserved", DWORD * 26),
("UserReserved", DWORD * 5),
("WOW32Reserved", PVOID), # ptr to wow64cpu!X86SwitchTo64BitMode
("CurrentLocale", DWORD),
("FpSoftwareStatusRegister", DWORD),
("SystemReserved1", PVOID * 54),
("ExceptionCode", SDWORD),
("ActivationContextStackPointer", PVOID), # PACTIVATION_CONTEXT_STACK
("SpareBytes1", UCHAR * 28),
("GdiTebBatch", GDI_TEB_BATCH),
("RealClientId", CLIENT_ID),
("GdiCachedProcessHandle", HANDLE),
("GdiClientPID", DWORD),
("GdiClientTID", DWORD),
("GdiThreadLocalInfo", PVOID),
("Win32ClientInfo", QWORD * 62),
("glDispatchTable", PVOID * 233),
("glReserved1", QWORD * 29),
("glReserved2", PVOID),
("glSectionInfo", PVOID),
("glSection", PVOID),
("glTable", PVOID),
("glCurrentRC", PVOID),
("glContext", PVOID),
("LastStatusValue", NTSTATUS),
("StaticUnicodeString", UNICODE_STRING),
("StaticUnicodeBuffer", WCHAR * 261),
("DeallocationStack", PVOID),
("TlsSlots", PVOID * 64),
("TlsLinks", LIST_ENTRY),
("Vdm", PVOID),
("ReservedForNtRpc", PVOID),
("DbgSsReserved", PVOID * 2),
("HardErrorMode", DWORD),
("Instrumentation", PVOID * 14),
("SubProcessTag", PVOID),
("EtwTraceData", PVOID),
("WinSockData", PVOID),
("GdiBatchCount", DWORD),
("InDbgPrint", BOOLEAN),
("FreeStackOnTermination", BOOLEAN),
("HasFiberData", BOOLEAN),
("IdealProcessor", UCHAR),
("GuaranteedStackBytes", DWORD),
("ReservedForPerf", PVOID),
("ReservedForOle", PVOID),
("WaitingOnLoaderLock", DWORD),
("SparePointer1", PVOID),
("SoftPatchPtr1", PVOID),
("SoftPatchPtr2", PVOID),
("TlsExpansionSlots", PVOID), # Ptr64 Ptr64 Void
("DeallocationBStore", PVOID),
("BStoreLimit", PVOID),
("ImpersonationLocale", DWORD),
("IsImpersonating", BOOL),
("NlsCache", PVOID),
("pShimData", PVOID),
("HeapVirtualAffinity", DWORD),
("CurrentTransactionHandle", HANDLE),
("ActiveFrame", PVOID), # PTEB_ACTIVE_FRAME
("FlsData", PVOID),
("SafeThunkCall", BOOLEAN),
("BooleanSpare", BOOLEAN * 3),
]
# +0x000 NtTib : _NT_TIB
# +0x01c EnvironmentPointer : Ptr32 Void
# +0x020 ClientId : _CLIENT_ID
# +0x028 ActiveRpcHandle : Ptr32 Void
# +0x02c ThreadLocalStoragePointer : Ptr32 Void
# +0x030 ProcessEnvironmentBlock : Ptr32 _PEB
# +0x034 LastErrorValue : Uint4B
# +0x038 CountOfOwnedCriticalSections : Uint4B
# +0x03c CsrClientThread : Ptr32 Void
# +0x040 Win32ThreadInfo : Ptr32 Void
# +0x044 User32Reserved : [26] Uint4B
# +0x0ac UserReserved : [5] Uint4B
# +0x0c0 WOW32Reserved : Ptr32 Void
# +0x0c4 CurrentLocale : Uint4B
# +0x0c8 FpSoftwareStatusRegister : Uint4B
# +0x0cc SystemReserved1 : [54] Ptr32 Void
# +0x1a4 ExceptionCode : Int4B
# +0x1a8 ActivationContextStackPointer : Ptr32 _ACTIVATION_CONTEXT_STACK
# +0x1ac SpareBytes1 : [40] UChar
# +0x1d4 GdiTebBatch : _GDI_TEB_BATCH
# +0x6b4 RealClientId : _CLIENT_ID
# +0x6bc GdiCachedProcessHandle : Ptr32 Void
# +0x6c0 GdiClientPID : Uint4B
# +0x6c4 GdiClientTID : Uint4B
# +0x6c8 GdiThreadLocalInfo : Ptr32 Void
# +0x6cc Win32ClientInfo : [62] Uint4B
# +0x7c4 glDispatchTable : [233] Ptr32 Void
# +0xb68 glReserved1 : [29] Uint4B
# +0xbdc glReserved2 : Ptr32 Void
# +0xbe0 glSectionInfo : Ptr32 Void
# +0xbe4 glSection : Ptr32 Void
# +0xbe8 glTable : Ptr32 Void
# +0xbec glCurrentRC : Ptr32 Void
# +0xbf0 glContext : Ptr32 Void
# +0xbf4 LastStatusValue : Uint4B
# +0xbf8 StaticUnicodeString : _UNICODE_STRING
# +0xc00 StaticUnicodeBuffer : [261] Uint2B
# +0xe0c DeallocationStack : Ptr32 Void
# +0xe10 TlsSlots : [64] Ptr32 Void
# +0xf10 TlsLinks : _LIST_ENTRY
# +0xf18 Vdm : Ptr32 Void
# +0xf1c ReservedForNtRpc : Ptr32 Void
# +0xf20 DbgSsReserved : [2] Ptr32 Void
# +0xf28 HardErrorMode : Uint4B
# +0xf2c Instrumentation : [14] Ptr32 Void
# +0xf64 SubProcessTag : Ptr32 Void
# +0xf68 EtwTraceData : Ptr32 Void
# +0xf6c WinSockData : Ptr32 Void
# +0xf70 GdiBatchCount : Uint4B
# +0xf74 InDbgPrint : UChar
# +0xf75 FreeStackOnTermination : UChar
# +0xf76 HasFiberData : UChar
# +0xf77 IdealProcessor : UChar
# +0xf78 GuaranteedStackBytes : Uint4B
# +0xf7c ReservedForPerf : Ptr32 Void
# +0xf80 ReservedForOle : Ptr32 Void
# +0xf84 WaitingOnLoaderLock : Uint4B
# +0xf88 SparePointer1 : Uint4B
# +0xf8c SoftPatchPtr1 : Uint4B
# +0xf90 SoftPatchPtr2 : Uint4B
# +0xf94 TlsExpansionSlots : Ptr32 Ptr32 Void
# +0xf98 ImpersonationLocale : Uint4B
# +0xf9c IsImpersonating : Uint4B
# +0xfa0 NlsCache : Ptr32 Void
# +0xfa4 pShimData : Ptr32 Void
# +0xfa8 HeapVirtualAffinity : Uint4B
# +0xfac CurrentTransactionHandle : Ptr32 Void
# +0xfb0 ActiveFrame : Ptr32 _TEB_ACTIVE_FRAME
# +0xfb4 FlsData : Ptr32 Void
# +0xfb8 SafeThunkCall : UChar
# +0xfb9 BooleanSpare : [3] UChar
class _TEB_2003(Structure):
_pack_ = 8
_fields_ = [
("NtTib", NT_TIB),
("EnvironmentPointer", PVOID),
("ClientId", CLIENT_ID),
("ActiveRpcHandle", HANDLE),
("ThreadLocalStoragePointer", PVOID),
("ProcessEnvironmentBlock", PVOID), # PPEB
("LastErrorValue", DWORD),
("CountOfOwnedCriticalSections", DWORD),
("CsrClientThread", PVOID),
("Win32ThreadInfo", PVOID),
("User32Reserved", DWORD * 26),
("UserReserved", DWORD * 5),
("WOW32Reserved", PVOID), # ptr to wow64cpu!X86SwitchTo64BitMode
("CurrentLocale", DWORD),
("FpSoftwareStatusRegister", DWORD),
("SystemReserved1", PVOID * 54),
("ExceptionCode", SDWORD),
("ActivationContextStackPointer", PVOID), # PACTIVATION_CONTEXT_STACK
("SpareBytes1", UCHAR * 40),
("GdiTebBatch", GDI_TEB_BATCH),
("RealClientId", CLIENT_ID),
("GdiCachedProcessHandle", HANDLE),
("GdiClientPID", DWORD),
("GdiClientTID", DWORD),
("GdiThreadLocalInfo", PVOID),
("Win32ClientInfo", DWORD * 62),
("glDispatchTable", PVOID * 233),
("glReserved1", DWORD * 29),
("glReserved2", PVOID),
("glSectionInfo", PVOID),
("glSection", PVOID),
("glTable", PVOID),
("glCurrentRC", PVOID),
("glContext", PVOID),
("LastStatusValue", NTSTATUS),
("StaticUnicodeString", UNICODE_STRING),
("StaticUnicodeBuffer", WCHAR * 261),
("DeallocationStack", PVOID),
("TlsSlots", PVOID * 64),
("TlsLinks", LIST_ENTRY),
("Vdm", PVOID),
("ReservedForNtRpc", PVOID),
("DbgSsReserved", PVOID * 2),
("HardErrorMode", DWORD),
("Instrumentation", PVOID * 14),
("SubProcessTag", PVOID),
("EtwTraceData", PVOID),
("WinSockData", PVOID),
("GdiBatchCount", DWORD),
("InDbgPrint", BOOLEAN),
("FreeStackOnTermination", BOOLEAN),
("HasFiberData", BOOLEAN),
("IdealProcessor", UCHAR),
("GuaranteedStackBytes", DWORD),
("ReservedForPerf", PVOID),
("ReservedForOle", PVOID),
("WaitingOnLoaderLock", DWORD),
("SparePointer1", PVOID),
("SoftPatchPtr1", PVOID),
("SoftPatchPtr2", PVOID),
("TlsExpansionSlots", PVOID), # Ptr32 Ptr32 Void
("ImpersonationLocale", DWORD),
("IsImpersonating", BOOL),
("NlsCache", PVOID),
("pShimData", PVOID),
("HeapVirtualAffinity", DWORD),
("CurrentTransactionHandle", HANDLE),
("ActiveFrame", PVOID), # PTEB_ACTIVE_FRAME
("FlsData", PVOID),
("SafeThunkCall", BOOLEAN),
("BooleanSpare", BOOLEAN * 3),
]
_TEB_2003_64 = _TEB_XP_64
_TEB_2003_R2 = _TEB_2003
_TEB_2003_R2_64 = _TEB_2003_64
# +0x000 NtTib : _NT_TIB
# +0x01c EnvironmentPointer : Ptr32 Void
# +0x020 ClientId : _CLIENT_ID
# +0x028 ActiveRpcHandle : Ptr32 Void
# +0x02c ThreadLocalStoragePointer : Ptr32 Void
# +0x030 ProcessEnvironmentBlock : Ptr32 _PEB
# +0x034 LastErrorValue : Uint4B
# +0x038 CountOfOwnedCriticalSections : Uint4B
# +0x03c CsrClientThread : Ptr32 Void
# +0x040 Win32ThreadInfo : Ptr32 Void
# +0x044 User32Reserved : [26] Uint4B
# +0x0ac UserReserved : [5] Uint4B
# +0x0c0 WOW32Reserved : Ptr32 Void
# +0x0c4 CurrentLocale : Uint4B
# +0x0c8 FpSoftwareStatusRegister : Uint4B
# +0x0cc SystemReserved1 : [54] Ptr32 Void
# +0x1a4 ExceptionCode : Int4B
# +0x1a8 ActivationContextStackPointer : Ptr32 _ACTIVATION_CONTEXT_STACK
# +0x1ac SpareBytes1 : [36] UChar
# +0x1d0 TxFsContext : Uint4B
# +0x1d4 GdiTebBatch : _GDI_TEB_BATCH
# +0x6b4 RealClientId : _CLIENT_ID
# +0x6bc GdiCachedProcessHandle : Ptr32 Void
# +0x6c0 GdiClientPID : Uint4B
# +0x6c4 GdiClientTID : Uint4B
# +0x6c8 GdiThreadLocalInfo : Ptr32 Void
# +0x6cc Win32ClientInfo : [62] Uint4B
# +0x7c4 glDispatchTable : [233] Ptr32 Void
# +0xb68 glReserved1 : [29] Uint4B
# +0xbdc glReserved2 : Ptr32 Void
# +0xbe0 glSectionInfo : Ptr32 Void
# +0xbe4 glSection : Ptr32 Void
# +0xbe8 glTable : Ptr32 Void
# +0xbec glCurrentRC : Ptr32 Void
# +0xbf0 glContext : Ptr32 Void
# +0xbf4 LastStatusValue : Uint4B
# +0xbf8 StaticUnicodeString : _UNICODE_STRING
# +0xc00 StaticUnicodeBuffer : [261] Wchar
# +0xe0c DeallocationStack : Ptr32 Void
# +0xe10 TlsSlots : [64] Ptr32 Void
# +0xf10 TlsLinks : _LIST_ENTRY
# +0xf18 Vdm : Ptr32 Void
# +0xf1c ReservedForNtRpc : Ptr32 Void
# +0xf20 DbgSsReserved : [2] Ptr32 Void
# +0xf28 HardErrorMode : Uint4B
# +0xf2c Instrumentation : [9] Ptr32 Void
# +0xf50 ActivityId : _GUID
# +0xf60 SubProcessTag : Ptr32 Void
# +0xf64 EtwLocalData : Ptr32 Void
# +0xf68 EtwTraceData : Ptr32 Void
# +0xf6c WinSockData : Ptr32 Void
# +0xf70 GdiBatchCount : Uint4B
# +0xf74 SpareBool0 : UChar
# +0xf75 SpareBool1 : UChar
# +0xf76 SpareBool2 : UChar
# +0xf77 IdealProcessor : UChar
# +0xf78 GuaranteedStackBytes : Uint4B
# +0xf7c ReservedForPerf : Ptr32 Void
# +0xf80 ReservedForOle : Ptr32 Void
# +0xf84 WaitingOnLoaderLock : Uint4B
# +0xf88 SavedPriorityState : Ptr32 Void
# +0xf8c SoftPatchPtr1 : Uint4B
# +0xf90 ThreadPoolData : Ptr32 Void
# +0xf94 TlsExpansionSlots : Ptr32 Ptr32 Void
# +0xf98 ImpersonationLocale : Uint4B
# +0xf9c IsImpersonating : Uint4B
# +0xfa0 NlsCache : Ptr32 Void
# +0xfa4 pShimData : Ptr32 Void
# +0xfa8 HeapVirtualAffinity : Uint4B
# +0xfac CurrentTransactionHandle : Ptr32 Void
# +0xfb0 ActiveFrame : Ptr32 _TEB_ACTIVE_FRAME
# +0xfb4 FlsData : Ptr32 Void
# +0xfb8 PreferredLanguages : Ptr32 Void
# +0xfbc UserPrefLanguages : Ptr32 Void
# +0xfc0 MergedPrefLanguages : Ptr32 Void
# +0xfc4 MuiImpersonation : Uint4B
# +0xfc8 CrossTebFlags : Uint2B
# +0xfc8 SpareCrossTebBits : Pos 0, 16 Bits
# +0xfca SameTebFlags : Uint2B
# +0xfca DbgSafeThunkCall : Pos 0, 1 Bit
# +0xfca DbgInDebugPrint : Pos 1, 1 Bit
# +0xfca DbgHasFiberData : Pos 2, 1 Bit
# +0xfca DbgSkipThreadAttach : Pos 3, 1 Bit
# +0xfca DbgWerInShipAssertCode : Pos 4, 1 Bit
# +0xfca DbgRanProcessInit : Pos 5, 1 Bit
# +0xfca DbgClonedThread : Pos 6, 1 Bit
# +0xfca DbgSuppressDebugMsg : Pos 7, 1 Bit
# +0xfca RtlDisableUserStackWalk : Pos 8, 1 Bit
# +0xfca RtlExceptionAttached : Pos 9, 1 Bit
# +0xfca SpareSameTebBits : Pos 10, 6 Bits
# +0xfcc TxnScopeEnterCallback : Ptr32 Void
# +0xfd0 TxnScopeExitCallback : Ptr32 Void
# +0xfd4 TxnScopeContext : Ptr32 Void
# +0xfd8 LockCount : Uint4B
# +0xfdc ProcessRundown : Uint4B
# +0xfe0 LastSwitchTime : Uint8B
# +0xfe8 TotalSwitchOutTime : Uint8B
# +0xff0 WaitReasonBitMap : _LARGE_INTEGER
class _TEB_2008(Structure):
_pack_ = 8
_fields_ = [
("NtTib", NT_TIB),
("EnvironmentPointer", PVOID),
("ClientId", CLIENT_ID),
("ActiveRpcHandle", HANDLE),
("ThreadLocalStoragePointer", PVOID),
("ProcessEnvironmentBlock", PVOID), # PPEB
("LastErrorValue", DWORD),
("CountOfOwnedCriticalSections", DWORD),
("CsrClientThread", PVOID),
("Win32ThreadInfo", PVOID),
("User32Reserved", DWORD * 26),
("UserReserved", DWORD * 5),
("WOW32Reserved", PVOID), # ptr to wow64cpu!X86SwitchTo64BitMode
("CurrentLocale", DWORD),
("FpSoftwareStatusRegister", DWORD),
("SystemReserved1", PVOID * 54),
("ExceptionCode", SDWORD),
("ActivationContextStackPointer", PVOID), # PACTIVATION_CONTEXT_STACK
("SpareBytes1", UCHAR * 36),
("TxFsContext", DWORD),
("GdiTebBatch", GDI_TEB_BATCH),
("RealClientId", CLIENT_ID),
("GdiCachedProcessHandle", HANDLE),
("GdiClientPID", DWORD),
("GdiClientTID", DWORD),
("GdiThreadLocalInfo", PVOID),
("Win32ClientInfo", DWORD * 62),
("glDispatchTable", PVOID * 233),
("glReserved1", DWORD * 29),
("glReserved2", PVOID),
("glSectionInfo", PVOID),
("glSection", PVOID),
("glTable", PVOID),
("glCurrentRC", PVOID),
("glContext", PVOID),
("LastStatusValue", NTSTATUS),
("StaticUnicodeString", UNICODE_STRING),
("StaticUnicodeBuffer", WCHAR * 261),
("DeallocationStack", PVOID),
("TlsSlots", PVOID * 64),
("TlsLinks", LIST_ENTRY),
("Vdm", PVOID),
("ReservedForNtRpc", PVOID),
("DbgSsReserved", PVOID * 2),
("HardErrorMode", DWORD),
("Instrumentation", PVOID * 9),
("ActivityId", GUID),
("SubProcessTag", PVOID),
("EtwLocalData", PVOID),
("EtwTraceData", PVOID),
("WinSockData", PVOID),
("GdiBatchCount", DWORD),
("SpareBool0", BOOLEAN),
("SpareBool1", BOOLEAN),
("SpareBool2", BOOLEAN),
("IdealProcessor", UCHAR),
("GuaranteedStackBytes", DWORD),
("ReservedForPerf", PVOID),
("ReservedForOle", PVOID),
("WaitingOnLoaderLock", DWORD),
("SavedPriorityState", PVOID),
("SoftPatchPtr1", PVOID),
("ThreadPoolData", PVOID),
("TlsExpansionSlots", PVOID), # Ptr32 Ptr32 Void
("ImpersonationLocale", DWORD),
("IsImpersonating", BOOL),
("NlsCache", PVOID),
("pShimData", PVOID),
("HeapVirtualAffinity", DWORD),
("CurrentTransactionHandle", HANDLE),
("ActiveFrame", PVOID), # PTEB_ACTIVE_FRAME
("FlsData", PVOID),
("PreferredLanguages", PVOID),
("UserPrefLanguages", PVOID),
("MergedPrefLanguages", PVOID),
("MuiImpersonation", BOOL),
("CrossTebFlags", WORD),
("SameTebFlags", WORD),
("TxnScopeEnterCallback", PVOID),
("TxnScopeExitCallback", PVOID),
("TxnScopeContext", PVOID),
("LockCount", DWORD),
("ProcessRundown", DWORD),
("LastSwitchTime", QWORD),
("TotalSwitchOutTime", QWORD),
("WaitReasonBitMap", LONGLONG), # LARGE_INTEGER
]
# +0x000 NtTib : _NT_TIB
# +0x038 EnvironmentPointer : Ptr64 Void
# +0x040 ClientId : _CLIENT_ID
# +0x050 ActiveRpcHandle : Ptr64 Void
# +0x058 ThreadLocalStoragePointer : Ptr64 Void
# +0x060 ProcessEnvironmentBlock : Ptr64 _PEB
# +0x068 LastErrorValue : Uint4B
# +0x06c CountOfOwnedCriticalSections : Uint4B
# +0x070 CsrClientThread : Ptr64 Void
# +0x078 Win32ThreadInfo : Ptr64 Void
# +0x080 User32Reserved : [26] Uint4B
# +0x0e8 UserReserved : [5] Uint4B
# +0x100 WOW32Reserved : Ptr64 Void
# +0x108 CurrentLocale : Uint4B
# +0x10c FpSoftwareStatusRegister : Uint4B
# +0x110 SystemReserved1 : [54] Ptr64 Void
# +0x2c0 ExceptionCode : Int4B
# +0x2c8 ActivationContextStackPointer : Ptr64 _ACTIVATION_CONTEXT_STACK
# +0x2d0 SpareBytes1 : [24] UChar
# +0x2e8 TxFsContext : Uint4B
# +0x2f0 GdiTebBatch : _GDI_TEB_BATCH
# +0x7d8 RealClientId : _CLIENT_ID
# +0x7e8 GdiCachedProcessHandle : Ptr64 Void
# +0x7f0 GdiClientPID : Uint4B
# +0x7f4 GdiClientTID : Uint4B
# +0x7f8 GdiThreadLocalInfo : Ptr64 Void
# +0x800 Win32ClientInfo : [62] Uint8B
# +0x9f0 glDispatchTable : [233] Ptr64 Void
# +0x1138 glReserved1 : [29] Uint8B
# +0x1220 glReserved2 : Ptr64 Void
# +0x1228 glSectionInfo : Ptr64 Void
# +0x1230 glSection : Ptr64 Void
# +0x1238 glTable : Ptr64 Void
# +0x1240 glCurrentRC : Ptr64 Void
# +0x1248 glContext : Ptr64 Void
# +0x1250 LastStatusValue : Uint4B
# +0x1258 StaticUnicodeString : _UNICODE_STRING
# +0x1268 StaticUnicodeBuffer : [261] Wchar
# +0x1478 DeallocationStack : Ptr64 Void
# +0x1480 TlsSlots : [64] Ptr64 Void
# +0x1680 TlsLinks : _LIST_ENTRY
# +0x1690 Vdm : Ptr64 Void
# +0x1698 ReservedForNtRpc : Ptr64 Void
# +0x16a0 DbgSsReserved : [2] Ptr64 Void
# +0x16b0 HardErrorMode : Uint4B
# +0x16b8 Instrumentation : [11] Ptr64 Void
# +0x1710 ActivityId : _GUID
# +0x1720 SubProcessTag : Ptr64 Void
# +0x1728 EtwLocalData : Ptr64 Void
# +0x1730 EtwTraceData : Ptr64 Void
# +0x1738 WinSockData : Ptr64 Void
# +0x1740 GdiBatchCount : Uint4B
# +0x1744 SpareBool0 : UChar
# +0x1745 SpareBool1 : UChar
# +0x1746 SpareBool2 : UChar
# +0x1747 IdealProcessor : UChar
# +0x1748 GuaranteedStackBytes : Uint4B
# +0x1750 ReservedForPerf : Ptr64 Void
# +0x1758 ReservedForOle : Ptr64 Void
# +0x1760 WaitingOnLoaderLock : Uint4B
# +0x1768 SavedPriorityState : Ptr64 Void
# +0x1770 SoftPatchPtr1 : Uint8B
# +0x1778 ThreadPoolData : Ptr64 Void
# +0x1780 TlsExpansionSlots : Ptr64 Ptr64 Void
# +0x1788 DeallocationBStore : Ptr64 Void
# +0x1790 BStoreLimit : Ptr64 Void
# +0x1798 ImpersonationLocale : Uint4B
# +0x179c IsImpersonating : Uint4B
# +0x17a0 NlsCache : Ptr64 Void
# +0x17a8 pShimData : Ptr64 Void
# +0x17b0 HeapVirtualAffinity : Uint4B
# +0x17b8 CurrentTransactionHandle : Ptr64 Void
# +0x17c0 ActiveFrame : Ptr64 _TEB_ACTIVE_FRAME
# +0x17c8 FlsData : Ptr64 Void
# +0x17d0 PreferredLanguages : Ptr64 Void
# +0x17d8 UserPrefLanguages : Ptr64 Void
# +0x17e0 MergedPrefLanguages : Ptr64 Void
# +0x17e8 MuiImpersonation : Uint4B
# +0x17ec CrossTebFlags : Uint2B
# +0x17ec SpareCrossTebBits : Pos 0, 16 Bits
# +0x17ee SameTebFlags : Uint2B
# +0x17ee DbgSafeThunkCall : Pos 0, 1 Bit
# +0x17ee DbgInDebugPrint : Pos 1, 1 Bit
# +0x17ee DbgHasFiberData : Pos 2, 1 Bit
# +0x17ee DbgSkipThreadAttach : Pos 3, 1 Bit
# +0x17ee DbgWerInShipAssertCode : Pos 4, 1 Bit
# +0x17ee DbgRanProcessInit : Pos 5, 1 Bit
# +0x17ee DbgClonedThread : Pos 6, 1 Bit
# +0x17ee DbgSuppressDebugMsg : Pos 7, 1 Bit
# +0x17ee RtlDisableUserStackWalk : Pos 8, 1 Bit
# +0x17ee RtlExceptionAttached : Pos 9, 1 Bit
# +0x17ee SpareSameTebBits : Pos 10, 6 Bits
# +0x17f0 TxnScopeEnterCallback : Ptr64 Void
# +0x17f8 TxnScopeExitCallback : Ptr64 Void
# +0x1800 TxnScopeContext : Ptr64 Void
# +0x1808 LockCount : Uint4B
# +0x180c ProcessRundown : Uint4B
# +0x1810 LastSwitchTime : Uint8B
# +0x1818 TotalSwitchOutTime : Uint8B
# +0x1820 WaitReasonBitMap : _LARGE_INTEGER
class _TEB_2008_64(Structure):
_pack_ = 8
_fields_ = [
("NtTib", NT_TIB),
("EnvironmentPointer", PVOID),
("ClientId", CLIENT_ID),
("ActiveRpcHandle", HANDLE),
("ThreadLocalStoragePointer", PVOID),
("ProcessEnvironmentBlock", PVOID), # PPEB
("LastErrorValue", DWORD),
("CountOfOwnedCriticalSections", DWORD),
("CsrClientThread", PVOID),
("Win32ThreadInfo", PVOID),
("User32Reserved", DWORD * 26),
("UserReserved", DWORD * 5),
("WOW32Reserved", PVOID), # ptr to wow64cpu!X86SwitchTo64BitMode
("CurrentLocale", DWORD),
("FpSoftwareStatusRegister", DWORD),
("SystemReserved1", PVOID * 54),
("ExceptionCode", SDWORD),
("ActivationContextStackPointer", PVOID), # PACTIVATION_CONTEXT_STACK
("SpareBytes1", UCHAR * 24),
("TxFsContext", DWORD),
("GdiTebBatch", GDI_TEB_BATCH),
("RealClientId", CLIENT_ID),
("GdiCachedProcessHandle", HANDLE),
("GdiClientPID", DWORD),
("GdiClientTID", DWORD),
("GdiThreadLocalInfo", PVOID),
("Win32ClientInfo", QWORD * 62),
("glDispatchTable", PVOID * 233),
("glReserved1", QWORD * 29),
("glReserved2", PVOID),
("glSectionInfo", PVOID),
("glSection", PVOID),
("glTable", PVOID),
("glCurrentRC", PVOID),
("glContext", PVOID),
("LastStatusValue", NTSTATUS),
("StaticUnicodeString", UNICODE_STRING),
("StaticUnicodeBuffer", WCHAR * 261),
("DeallocationStack", PVOID),
("TlsSlots", PVOID * 64),
("TlsLinks", LIST_ENTRY),
("Vdm", PVOID),
("ReservedForNtRpc", PVOID),
("DbgSsReserved", PVOID * 2),
("HardErrorMode", DWORD),
("Instrumentation", PVOID * 11),
("ActivityId", GUID),
("SubProcessTag", PVOID),
("EtwLocalData", PVOID),
("EtwTraceData", PVOID),
("WinSockData", PVOID),
("GdiBatchCount", DWORD),
("SpareBool0", BOOLEAN),
("SpareBool1", BOOLEAN),
("SpareBool2", BOOLEAN),
("IdealProcessor", UCHAR),
("GuaranteedStackBytes", DWORD),
("ReservedForPerf", PVOID),
("ReservedForOle", PVOID),
("WaitingOnLoaderLock", DWORD),
("SavedPriorityState", PVOID),
("SoftPatchPtr1", PVOID),
("ThreadPoolData", PVOID),
("TlsExpansionSlots", PVOID), # Ptr64 Ptr64 Void
("DeallocationBStore", PVOID),
("BStoreLimit", PVOID),
("ImpersonationLocale", DWORD),
("IsImpersonating", BOOL),
("NlsCache", PVOID),
("pShimData", PVOID),
("HeapVirtualAffinity", DWORD),
("CurrentTransactionHandle", HANDLE),
("ActiveFrame", PVOID), # PTEB_ACTIVE_FRAME
("FlsData", PVOID),
("PreferredLanguages", PVOID),
("UserPrefLanguages", PVOID),
("MergedPrefLanguages", PVOID),
("MuiImpersonation", BOOL),
("CrossTebFlags", WORD),
("SameTebFlags", WORD),
("TxnScopeEnterCallback", PVOID),
("TxnScopeExitCallback", PVOID),
("TxnScopeContext", PVOID),
("LockCount", DWORD),
("ProcessRundown", DWORD),
("LastSwitchTime", QWORD),
("TotalSwitchOutTime", QWORD),
("WaitReasonBitMap", LONGLONG), # LARGE_INTEGER
]
# +0x000 NtTib : _NT_TIB
# +0x01c EnvironmentPointer : Ptr32 Void
# +0x020 ClientId : _CLIENT_ID
# +0x028 ActiveRpcHandle : Ptr32 Void
# +0x02c ThreadLocalStoragePointer : Ptr32 Void
# +0x030 ProcessEnvironmentBlock : Ptr32 _PEB
# +0x034 LastErrorValue : Uint4B
# +0x038 CountOfOwnedCriticalSections : Uint4B
# +0x03c CsrClientThread : Ptr32 Void
# +0x040 Win32ThreadInfo : Ptr32 Void
# +0x044 User32Reserved : [26] Uint4B
# +0x0ac UserReserved : [5] Uint4B
# +0x0c0 WOW32Reserved : Ptr32 Void
# +0x0c4 CurrentLocale : Uint4B
# +0x0c8 FpSoftwareStatusRegister : Uint4B
# +0x0cc SystemReserved1 : [54] Ptr32 Void
# +0x1a4 ExceptionCode : Int4B
# +0x1a8 ActivationContextStackPointer : Ptr32 _ACTIVATION_CONTEXT_STACK
# +0x1ac SpareBytes : [36] UChar
# +0x1d0 TxFsContext : Uint4B
# +0x1d4 GdiTebBatch : _GDI_TEB_BATCH
# +0x6b4 RealClientId : _CLIENT_ID
# +0x6bc GdiCachedProcessHandle : Ptr32 Void
# +0x6c0 GdiClientPID : Uint4B
# +0x6c4 GdiClientTID : Uint4B
# +0x6c8 GdiThreadLocalInfo : Ptr32 Void
# +0x6cc Win32ClientInfo : [62] Uint4B
# +0x7c4 glDispatchTable : [233] Ptr32 Void
# +0xb68 glReserved1 : [29] Uint4B
# +0xbdc glReserved2 : Ptr32 Void
# +0xbe0 glSectionInfo : Ptr32 Void
# +0xbe4 glSection : Ptr32 Void
# +0xbe8 glTable : Ptr32 Void
# +0xbec glCurrentRC : Ptr32 Void
# +0xbf0 glContext : Ptr32 Void
# +0xbf4 LastStatusValue : Uint4B
# +0xbf8 StaticUnicodeString : _UNICODE_STRING
# +0xc00 StaticUnicodeBuffer : [261] Wchar
# +0xe0c DeallocationStack : Ptr32 Void
# +0xe10 TlsSlots : [64] Ptr32 Void
# +0xf10 TlsLinks : _LIST_ENTRY
# +0xf18 Vdm : Ptr32 Void
# +0xf1c ReservedForNtRpc : Ptr32 Void
# +0xf20 DbgSsReserved : [2] Ptr32 Void
# +0xf28 HardErrorMode : Uint4B
# +0xf2c Instrumentation : [9] Ptr32 Void
# +0xf50 ActivityId : _GUID
# +0xf60 SubProcessTag : Ptr32 Void
# +0xf64 EtwLocalData : Ptr32 Void
# +0xf68 EtwTraceData : Ptr32 Void
# +0xf6c WinSockData : Ptr32 Void
# +0xf70 GdiBatchCount : Uint4B
# +0xf74 CurrentIdealProcessor : _PROCESSOR_NUMBER
# +0xf74 IdealProcessorValue : Uint4B
# +0xf74 ReservedPad0 : UChar
# +0xf75 ReservedPad1 : UChar
# +0xf76 ReservedPad2 : UChar
# +0xf77 IdealProcessor : UChar
# +0xf78 GuaranteedStackBytes : Uint4B
# +0xf7c ReservedForPerf : Ptr32 Void
# +0xf80 ReservedForOle : Ptr32 Void
# +0xf84 WaitingOnLoaderLock : Uint4B
# +0xf88 SavedPriorityState : Ptr32 Void
# +0xf8c SoftPatchPtr1 : Uint4B
# +0xf90 ThreadPoolData : Ptr32 Void
# +0xf94 TlsExpansionSlots : Ptr32 Ptr32 Void
# +0xf98 MuiGeneration : Uint4B
# +0xf9c IsImpersonating : Uint4B
# +0xfa0 NlsCache : Ptr32 Void
# +0xfa4 pShimData : Ptr32 Void
# +0xfa8 HeapVirtualAffinity : Uint4B
# +0xfac CurrentTransactionHandle : Ptr32 Void
# +0xfb0 ActiveFrame : Ptr32 _TEB_ACTIVE_FRAME
# +0xfb4 FlsData : Ptr32 Void
# +0xfb8 PreferredLanguages : Ptr32 Void
# +0xfbc UserPrefLanguages : Ptr32 Void
# +0xfc0 MergedPrefLanguages : Ptr32 Void
# +0xfc4 MuiImpersonation : Uint4B
# +0xfc8 CrossTebFlags : Uint2B
# +0xfc8 SpareCrossTebBits : Pos 0, 16 Bits
# +0xfca SameTebFlags : Uint2B
# +0xfca SafeThunkCall : Pos 0, 1 Bit
# +0xfca InDebugPrint : Pos 1, 1 Bit
# +0xfca HasFiberData : Pos 2, 1 Bit
# +0xfca SkipThreadAttach : Pos 3, 1 Bit
# +0xfca WerInShipAssertCode : Pos 4, 1 Bit
# +0xfca RanProcessInit : Pos 5, 1 Bit
# +0xfca ClonedThread : Pos 6, 1 Bit
# +0xfca SuppressDebugMsg : Pos 7, 1 Bit
# +0xfca DisableUserStackWalk : Pos 8, 1 Bit
# +0xfca RtlExceptionAttached : Pos 9, 1 Bit
# +0xfca InitialThread : Pos 10, 1 Bit
# +0xfca SpareSameTebBits : Pos 11, 5 Bits
# +0xfcc TxnScopeEnterCallback : Ptr32 Void
# +0xfd0 TxnScopeExitCallback : Ptr32 Void
# +0xfd4 TxnScopeContext : Ptr32 Void
# +0xfd8 LockCount : Uint4B
# +0xfdc SpareUlong0 : Uint4B
# +0xfe0 ResourceRetValue : Ptr32 Void
class _TEB_2008_R2(Structure):
_pack_ = 8
_fields_ = [
("NtTib", NT_TIB),
("EnvironmentPointer", PVOID),
("ClientId", CLIENT_ID),
("ActiveRpcHandle", HANDLE),
("ThreadLocalStoragePointer", PVOID),
("ProcessEnvironmentBlock", PVOID), # PPEB
("LastErrorValue", DWORD),
("CountOfOwnedCriticalSections", DWORD),
("CsrClientThread", PVOID),
("Win32ThreadInfo", PVOID),
("User32Reserved", DWORD * 26),
("UserReserved", DWORD * 5),
("WOW32Reserved", PVOID), # ptr to wow64cpu!X86SwitchTo64BitMode
("CurrentLocale", DWORD),
("FpSoftwareStatusRegister", DWORD),
("SystemReserved1", PVOID * 54),
("ExceptionCode", SDWORD),
("ActivationContextStackPointer", PVOID), # PACTIVATION_CONTEXT_STACK
("SpareBytes", UCHAR * 36),
("TxFsContext", DWORD),
("GdiTebBatch", GDI_TEB_BATCH),
("RealClientId", CLIENT_ID),
("GdiCachedProcessHandle", HANDLE),
("GdiClientPID", DWORD),
("GdiClientTID", DWORD),
("GdiThreadLocalInfo", PVOID),
("Win32ClientInfo", DWORD * 62),
("glDispatchTable", PVOID * 233),
("glReserved1", DWORD * 29),
("glReserved2", PVOID),
("glSectionInfo", PVOID),
("glSection", PVOID),
("glTable", PVOID),
("glCurrentRC", PVOID),
("glContext", PVOID),
("LastStatusValue", NTSTATUS),
("StaticUnicodeString", UNICODE_STRING),
("StaticUnicodeBuffer", WCHAR * 261),
("DeallocationStack", PVOID),
("TlsSlots", PVOID * 64),
("TlsLinks", LIST_ENTRY),
("Vdm", PVOID),
("ReservedForNtRpc", PVOID),
("DbgSsReserved", PVOID * 2),
("HardErrorMode", DWORD),
("Instrumentation", PVOID * 9),
("ActivityId", GUID),
("SubProcessTag", PVOID),
("EtwLocalData", PVOID),
("EtwTraceData", PVOID),
("WinSockData", PVOID),
("GdiBatchCount", DWORD),
("CurrentIdealProcessor", PROCESSOR_NUMBER),
("IdealProcessorValue", DWORD),
("ReservedPad0", UCHAR),
("ReservedPad1", UCHAR),
("ReservedPad2", UCHAR),
("IdealProcessor", UCHAR),
("GuaranteedStackBytes", DWORD),
("ReservedForPerf", PVOID),
("ReservedForOle", PVOID),
("WaitingOnLoaderLock", DWORD),
("SavedPriorityState", PVOID),
("SoftPatchPtr1", PVOID),
("ThreadPoolData", PVOID),
("TlsExpansionSlots", PVOID), # Ptr32 Ptr32 Void
("MuiGeneration", DWORD),
("IsImpersonating", BOOL),
("NlsCache", PVOID),
("pShimData", PVOID),
("HeapVirtualAffinity", DWORD),
("CurrentTransactionHandle", HANDLE),
("ActiveFrame", PVOID), # PTEB_ACTIVE_FRAME
("FlsData", PVOID),
("PreferredLanguages", PVOID),
("UserPrefLanguages", PVOID),
("MergedPrefLanguages", PVOID),
("MuiImpersonation", BOOL),
("CrossTebFlags", WORD),
("SameTebFlags", WORD),
("TxnScopeEnterCallback", PVOID),
("TxnScopeExitCallback", PVOID),
("TxnScopeContext", PVOID),
("LockCount", DWORD),
("SpareUlong0", ULONG),
("ResourceRetValue", PVOID),
]
# +0x000 NtTib : _NT_TIB
# +0x038 EnvironmentPointer : Ptr64 Void
# +0x040 ClientId : _CLIENT_ID
# +0x050 ActiveRpcHandle : Ptr64 Void
# +0x058 ThreadLocalStoragePointer : Ptr64 Void
# +0x060 ProcessEnvironmentBlock : Ptr64 _PEB
# +0x068 LastErrorValue : Uint4B
# +0x06c CountOfOwnedCriticalSections : Uint4B
# +0x070 CsrClientThread : Ptr64 Void
# +0x078 Win32ThreadInfo : Ptr64 Void
# +0x080 User32Reserved : [26] Uint4B
# +0x0e8 UserReserved : [5] Uint4B
# +0x100 WOW32Reserved : Ptr64 Void
# +0x108 CurrentLocale : Uint4B
# +0x10c FpSoftwareStatusRegister : Uint4B
# +0x110 SystemReserved1 : [54] Ptr64 Void
# +0x2c0 ExceptionCode : Int4B
# +0x2c8 ActivationContextStackPointer : Ptr64 _ACTIVATION_CONTEXT_STACK
# +0x2d0 SpareBytes : [24] UChar
# +0x2e8 TxFsContext : Uint4B
# +0x2f0 GdiTebBatch : _GDI_TEB_BATCH
# +0x7d8 RealClientId : _CLIENT_ID
# +0x7e8 GdiCachedProcessHandle : Ptr64 Void
# +0x7f0 GdiClientPID : Uint4B
# +0x7f4 GdiClientTID : Uint4B
# +0x7f8 GdiThreadLocalInfo : Ptr64 Void
# +0x800 Win32ClientInfo : [62] Uint8B
# +0x9f0 glDispatchTable : [233] Ptr64 Void
# +0x1138 glReserved1 : [29] Uint8B
# +0x1220 glReserved2 : Ptr64 Void
# +0x1228 glSectionInfo : Ptr64 Void
# +0x1230 glSection : Ptr64 Void
# +0x1238 glTable : Ptr64 Void
# +0x1240 glCurrentRC : Ptr64 Void
# +0x1248 glContext : Ptr64 Void
# +0x1250 LastStatusValue : Uint4B
# +0x1258 StaticUnicodeString : _UNICODE_STRING
# +0x1268 StaticUnicodeBuffer : [261] Wchar
# +0x1478 DeallocationStack : Ptr64 Void
# +0x1480 TlsSlots : [64] Ptr64 Void
# +0x1680 TlsLinks : _LIST_ENTRY
# +0x1690 Vdm : Ptr64 Void
# +0x1698 ReservedForNtRpc : Ptr64 Void
# +0x16a0 DbgSsReserved : [2] Ptr64 Void
# +0x16b0 HardErrorMode : Uint4B
# +0x16b8 Instrumentation : [11] Ptr64 Void
# +0x1710 ActivityId : _GUID
# +0x1720 SubProcessTag : Ptr64 Void
# +0x1728 EtwLocalData : Ptr64 Void
# +0x1730 EtwTraceData : Ptr64 Void
# +0x1738 WinSockData : Ptr64 Void
# +0x1740 GdiBatchCount : Uint4B
# +0x1744 CurrentIdealProcessor : _PROCESSOR_NUMBER
# +0x1744 IdealProcessorValue : Uint4B
# +0x1744 ReservedPad0 : UChar
# +0x1745 ReservedPad1 : UChar
# +0x1746 ReservedPad2 : UChar
# +0x1747 IdealProcessor : UChar
# +0x1748 GuaranteedStackBytes : Uint4B
# +0x1750 ReservedForPerf : Ptr64 Void
# +0x1758 ReservedForOle : Ptr64 Void
# +0x1760 WaitingOnLoaderLock : Uint4B
# +0x1768 SavedPriorityState : Ptr64 Void
# +0x1770 SoftPatchPtr1 : Uint8B
# +0x1778 ThreadPoolData : Ptr64 Void
# +0x1780 TlsExpansionSlots : Ptr64 Ptr64 Void
# +0x1788 DeallocationBStore : Ptr64 Void
# +0x1790 BStoreLimit : Ptr64 Void
# +0x1798 MuiGeneration : Uint4B
# +0x179c IsImpersonating : Uint4B
# +0x17a0 NlsCache : Ptr64 Void
# +0x17a8 pShimData : Ptr64 Void
# +0x17b0 HeapVirtualAffinity : Uint4B
# +0x17b8 CurrentTransactionHandle : Ptr64 Void
# +0x17c0 ActiveFrame : Ptr64 _TEB_ACTIVE_FRAME
# +0x17c8 FlsData : Ptr64 Void
# +0x17d0 PreferredLanguages : Ptr64 Void
# +0x17d8 UserPrefLanguages : Ptr64 Void
# +0x17e0 MergedPrefLanguages : Ptr64 Void
# +0x17e8 MuiImpersonation : Uint4B
# +0x17ec CrossTebFlags : Uint2B
# +0x17ec SpareCrossTebBits : Pos 0, 16 Bits
# +0x17ee SameTebFlags : Uint2B
# +0x17ee SafeThunkCall : Pos 0, 1 Bit
# +0x17ee InDebugPrint : Pos 1, 1 Bit
# +0x17ee HasFiberData : Pos 2, 1 Bit
# +0x17ee SkipThreadAttach : Pos 3, 1 Bit
# +0x17ee WerInShipAssertCode : Pos 4, 1 Bit
# +0x17ee RanProcessInit : Pos 5, 1 Bit
# +0x17ee ClonedThread : Pos 6, 1 Bit
# +0x17ee SuppressDebugMsg : Pos 7, 1 Bit
# +0x17ee DisableUserStackWalk : Pos 8, 1 Bit
# +0x17ee RtlExceptionAttached : Pos 9, 1 Bit
# +0x17ee InitialThread : Pos 10, 1 Bit
# +0x17ee SpareSameTebBits : Pos 11, 5 Bits
# +0x17f0 TxnScopeEnterCallback : Ptr64 Void
# +0x17f8 TxnScopeExitCallback : Ptr64 Void
# +0x1800 TxnScopeContext : Ptr64 Void
# +0x1808 LockCount : Uint4B
# +0x180c SpareUlong0 : Uint4B
# +0x1810 ResourceRetValue : Ptr64 Void
class _TEB_2008_R2_64(Structure):
_pack_ = 8
_fields_ = [
("NtTib", NT_TIB),
("EnvironmentPointer", PVOID),
("ClientId", CLIENT_ID),
("ActiveRpcHandle", HANDLE),
("ThreadLocalStoragePointer", PVOID),
("ProcessEnvironmentBlock", PVOID), # PPEB
("LastErrorValue", DWORD),
("CountOfOwnedCriticalSections", DWORD),
("CsrClientThread", PVOID),
("Win32ThreadInfo", PVOID),
("User32Reserved", DWORD * 26),
("UserReserved", DWORD * 5),
("WOW32Reserved", PVOID), # ptr to wow64cpu!X86SwitchTo64BitMode
("CurrentLocale", DWORD),
("FpSoftwareStatusRegister", DWORD),
("SystemReserved1", PVOID * 54),
("ExceptionCode", SDWORD),
("ActivationContextStackPointer", PVOID), # PACTIVATION_CONTEXT_STACK
("SpareBytes", UCHAR * 24),
("TxFsContext", DWORD),
("GdiTebBatch", GDI_TEB_BATCH),
("RealClientId", CLIENT_ID),
("GdiCachedProcessHandle", HANDLE),
("GdiClientPID", DWORD),
("GdiClientTID", DWORD),
("GdiThreadLocalInfo", PVOID),
("Win32ClientInfo", DWORD * 62),
("glDispatchTable", PVOID * 233),
("glReserved1", QWORD * 29),
("glReserved2", PVOID),
("glSectionInfo", PVOID),
("glSection", PVOID),
("glTable", PVOID),
("glCurrentRC", PVOID),
("glContext", PVOID),
("LastStatusValue", NTSTATUS),
("StaticUnicodeString", UNICODE_STRING),
("StaticUnicodeBuffer", WCHAR * 261),
("DeallocationStack", PVOID),
("TlsSlots", PVOID * 64),
("TlsLinks", LIST_ENTRY),
("Vdm", PVOID),
("ReservedForNtRpc", PVOID),
("DbgSsReserved", PVOID * 2),
("HardErrorMode", DWORD),
("Instrumentation", PVOID * 11),
("ActivityId", GUID),
("SubProcessTag", PVOID),
("EtwLocalData", PVOID),
("EtwTraceData", PVOID),
("WinSockData", PVOID),
("GdiBatchCount", DWORD),
("CurrentIdealProcessor", PROCESSOR_NUMBER),
("IdealProcessorValue", DWORD),
("ReservedPad0", UCHAR),
("ReservedPad1", UCHAR),
("ReservedPad2", UCHAR),
("IdealProcessor", UCHAR),
("GuaranteedStackBytes", DWORD),
("ReservedForPerf", PVOID),
("ReservedForOle", PVOID),
("WaitingOnLoaderLock", DWORD),
("SavedPriorityState", PVOID),
("SoftPatchPtr1", PVOID),
("ThreadPoolData", PVOID),
("TlsExpansionSlots", PVOID), # Ptr64 Ptr64 Void
("DeallocationBStore", PVOID),
("BStoreLimit", PVOID),
("MuiGeneration", DWORD),
("IsImpersonating", BOOL),
("NlsCache", PVOID),
("pShimData", PVOID),
("HeapVirtualAffinity", DWORD),
("CurrentTransactionHandle", HANDLE),
("ActiveFrame", PVOID), # PTEB_ACTIVE_FRAME
("FlsData", PVOID),
("PreferredLanguages", PVOID),
("UserPrefLanguages", PVOID),
("MergedPrefLanguages", PVOID),
("MuiImpersonation", BOOL),
("CrossTebFlags", WORD),
("SameTebFlags", WORD),
("TxnScopeEnterCallback", PVOID),
("TxnScopeExitCallback", PVOID),
("TxnScopeContext", PVOID),
("LockCount", DWORD),
("SpareUlong0", ULONG),
("ResourceRetValue", PVOID),
]
_TEB_Vista = _TEB_2008
_TEB_Vista_64 = _TEB_2008_64
_TEB_W7 = _TEB_2008_R2
_TEB_W7_64 = _TEB_2008_R2_64
# Use the correct TEB structure definition.
# Defaults to the latest Windows version.
class TEB(Structure):
_pack_ = 8
if os == 'Windows NT':
_pack_ = _TEB_NT._pack_
_fields_ = _TEB_NT._fields_
elif os == 'Windows 2000':
_pack_ = _TEB_2000._pack_
_fields_ = _TEB_2000._fields_
elif os == 'Windows XP':
_fields_ = _TEB_XP._fields_
elif os == 'Windows XP (64 bits)':
_fields_ = _TEB_XP_64._fields_
elif os == 'Windows 2003':
_fields_ = _TEB_2003._fields_
elif os == 'Windows 2003 (64 bits)':
_fields_ = _TEB_2003_64._fields_
elif os == 'Windows 2008':
_fields_ = _TEB_2008._fields_
elif os == 'Windows 2008 (64 bits)':
_fields_ = _TEB_2008_64._fields_
elif os == 'Windows 2003 R2':
_fields_ = _TEB_2003_R2._fields_
elif os == 'Windows 2003 R2 (64 bits)':
_fields_ = _TEB_2003_R2_64._fields_
elif os == 'Windows 2008 R2':
_fields_ = _TEB_2008_R2._fields_
elif os == 'Windows 2008 R2 (64 bits)':
_fields_ = _TEB_2008_R2_64._fields_
elif os == 'Windows Vista':
_fields_ = _TEB_Vista._fields_
elif os == 'Windows Vista (64 bits)':
_fields_ = _TEB_Vista_64._fields_
elif os == 'Windows 7':
_fields_ = _TEB_W7._fields_
elif os == 'Windows 7 (64 bits)':
_fields_ = _TEB_W7_64._fields_
elif sizeof(SIZE_T) == sizeof(DWORD):
_fields_ = _TEB_W7._fields_
else:
_fields_ = _TEB_W7_64._fields_
PTEB = POINTER(TEB)
#==============================================================================
# This calculates the list of exported symbols.
_all = set(vars().keys()).difference(_all)
__all__ = [_x for _x in _all if not _x.startswith('_')]
__all__.sort()
#==============================================================================
| 159,230 | Python | 45.341967 | 117 | 0.527036 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/win32/shell32.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Wrapper for shell32.dll in ctypes.
"""
# TODO
# * Add a class wrapper to SHELLEXECUTEINFO
# * More logic into ShellExecuteEx
__revision__ = "$Id$"
from winappdbg.win32.defines import *
from winappdbg.win32.kernel32 import LocalFree
#==============================================================================
# This is used later on to calculate the list of exported symbols.
_all = None
_all = set(vars().keys())
#==============================================================================
#--- Constants ----------------------------------------------------------------
SEE_MASK_DEFAULT = 0x00000000
SEE_MASK_CLASSNAME = 0x00000001
SEE_MASK_CLASSKEY = 0x00000003
SEE_MASK_IDLIST = 0x00000004
SEE_MASK_INVOKEIDLIST = 0x0000000C
SEE_MASK_ICON = 0x00000010
SEE_MASK_HOTKEY = 0x00000020
SEE_MASK_NOCLOSEPROCESS = 0x00000040
SEE_MASK_CONNECTNETDRV = 0x00000080
SEE_MASK_NOASYNC = 0x00000100
SEE_MASK_DOENVSUBST = 0x00000200
SEE_MASK_FLAG_NO_UI = 0x00000400
SEE_MASK_UNICODE = 0x00004000
SEE_MASK_NO_CONSOLE = 0x00008000
SEE_MASK_ASYNCOK = 0x00100000
SEE_MASK_HMONITOR = 0x00200000
SEE_MASK_NOZONECHECKS = 0x00800000
SEE_MASK_WAITFORINPUTIDLE = 0x02000000
SEE_MASK_FLAG_LOG_USAGE = 0x04000000
SE_ERR_FNF = 2
SE_ERR_PNF = 3
SE_ERR_ACCESSDENIED = 5
SE_ERR_OOM = 8
SE_ERR_DLLNOTFOUND = 32
SE_ERR_SHARE = 26
SE_ERR_ASSOCINCOMPLETE = 27
SE_ERR_DDETIMEOUT = 28
SE_ERR_DDEFAIL = 29
SE_ERR_DDEBUSY = 30
SE_ERR_NOASSOC = 31
SHGFP_TYPE_CURRENT = 0
SHGFP_TYPE_DEFAULT = 1
CSIDL_DESKTOP = 0x0000
CSIDL_INTERNET = 0x0001
CSIDL_PROGRAMS = 0x0002
CSIDL_CONTROLS = 0x0003
CSIDL_PRINTERS = 0x0004
CSIDL_PERSONAL = 0x0005
CSIDL_FAVORITES = 0x0006
CSIDL_STARTUP = 0x0007
CSIDL_RECENT = 0x0008
CSIDL_SENDTO = 0x0009
CSIDL_BITBUCKET = 0x000a
CSIDL_STARTMENU = 0x000b
CSIDL_MYDOCUMENTS = CSIDL_PERSONAL
CSIDL_MYMUSIC = 0x000d
CSIDL_MYVIDEO = 0x000e
CSIDL_DESKTOPDIRECTORY = 0x0010
CSIDL_DRIVES = 0x0011
CSIDL_NETWORK = 0x0012
CSIDL_NETHOOD = 0x0013
CSIDL_FONTS = 0x0014
CSIDL_TEMPLATES = 0x0015
CSIDL_COMMON_STARTMENU = 0x0016
CSIDL_COMMON_PROGRAMS = 0x0017
CSIDL_COMMON_STARTUP = 0x0018
CSIDL_COMMON_DESKTOPDIRECTORY = 0x0019
CSIDL_APPDATA = 0x001a
CSIDL_PRINTHOOD = 0x001b
CSIDL_LOCAL_APPDATA = 0x001c
CSIDL_ALTSTARTUP = 0x001d
CSIDL_COMMON_ALTSTARTUP = 0x001e
CSIDL_COMMON_FAVORITES = 0x001f
CSIDL_INTERNET_CACHE = 0x0020
CSIDL_COOKIES = 0x0021
CSIDL_HISTORY = 0x0022
CSIDL_COMMON_APPDATA = 0x0023
CSIDL_WINDOWS = 0x0024
CSIDL_SYSTEM = 0x0025
CSIDL_PROGRAM_FILES = 0x0026
CSIDL_MYPICTURES = 0x0027
CSIDL_PROFILE = 0x0028
CSIDL_SYSTEMX86 = 0x0029
CSIDL_PROGRAM_FILESX86 = 0x002a
CSIDL_PROGRAM_FILES_COMMON = 0x002b
CSIDL_PROGRAM_FILES_COMMONX86 = 0x002c
CSIDL_COMMON_TEMPLATES = 0x002d
CSIDL_COMMON_DOCUMENTS = 0x002e
CSIDL_COMMON_ADMINTOOLS = 0x002f
CSIDL_ADMINTOOLS = 0x0030
CSIDL_CONNECTIONS = 0x0031
CSIDL_COMMON_MUSIC = 0x0035
CSIDL_COMMON_PICTURES = 0x0036
CSIDL_COMMON_VIDEO = 0x0037
CSIDL_RESOURCES = 0x0038
CSIDL_RESOURCES_LOCALIZED = 0x0039
CSIDL_COMMON_OEM_LINKS = 0x003a
CSIDL_CDBURN_AREA = 0x003b
CSIDL_COMPUTERSNEARME = 0x003d
CSIDL_PROFILES = 0x003e
CSIDL_FOLDER_MASK = 0x00ff
CSIDL_FLAG_PER_USER_INIT = 0x0800
CSIDL_FLAG_NO_ALIAS = 0x1000
CSIDL_FLAG_DONT_VERIFY = 0x4000
CSIDL_FLAG_CREATE = 0x8000
CSIDL_FLAG_MASK = 0xff00
#--- Structures ---------------------------------------------------------------
# typedef struct _SHELLEXECUTEINFO {
# DWORD cbSize;
# ULONG fMask;
# HWND hwnd;
# LPCTSTR lpVerb;
# LPCTSTR lpFile;
# LPCTSTR lpParameters;
# LPCTSTR lpDirectory;
# int nShow;
# HINSTANCE hInstApp;
# LPVOID lpIDList;
# LPCTSTR lpClass;
# HKEY hkeyClass;
# DWORD dwHotKey;
# union {
# HANDLE hIcon;
# HANDLE hMonitor;
# } DUMMYUNIONNAME;
# HANDLE hProcess;
# } SHELLEXECUTEINFO, *LPSHELLEXECUTEINFO;
class SHELLEXECUTEINFO(Structure):
_fields_ = [
("cbSize", DWORD),
("fMask", ULONG),
("hwnd", HWND),
("lpVerb", LPSTR),
("lpFile", LPSTR),
("lpParameters", LPSTR),
("lpDirectory", LPSTR),
("nShow", ctypes.c_int),
("hInstApp", HINSTANCE),
("lpIDList", LPVOID),
("lpClass", LPSTR),
("hkeyClass", HKEY),
("dwHotKey", DWORD),
("hIcon", HANDLE),
("hProcess", HANDLE),
]
def __get_hMonitor(self):
return self.hIcon
def __set_hMonitor(self, hMonitor):
self.hIcon = hMonitor
hMonitor = property(__get_hMonitor, __set_hMonitor)
LPSHELLEXECUTEINFO = POINTER(SHELLEXECUTEINFO)
#--- shell32.dll --------------------------------------------------------------
# LPWSTR *CommandLineToArgvW(
# LPCWSTR lpCmdLine,
# int *pNumArgs
# );
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)]
CommandLineToArgv = GuessStringType(CommandLineToArgvA, CommandLineToArgvW)
# HINSTANCE ShellExecute(
# HWND hwnd,
# LPCTSTR lpOperation,
# LPCTSTR lpFile,
# LPCTSTR lpParameters,
# LPCTSTR lpDirectory,
# INT nShowCmd
# );
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)
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)
ShellExecute = GuessStringType(ShellExecuteA, ShellExecuteW)
# BOOL ShellExecuteEx(
# __inout LPSHELLEXECUTEINFO 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))
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))
# HINSTANCE FindExecutable(
# __in LPCTSTR lpFile,
# __in_opt LPCTSTR lpDirectory,
# __out LPTSTR lpResult
# );
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
def FindExecutableW(lpFile, lpDirectory = None):
_FindExecutableW = windll.shell32.FindExecutableW
_FindExecutableW.argtypes = [LPWSTR, LPWSTR, LPWSTR]
_FindExecutableW.restype = HINSTANCE
lpResult = ctypes.create_unicode_buffer(MAX_PATH)
success = _FindExecutableW(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
FindExecutable = GuessStringType(FindExecutableA, FindExecutableW)
# HRESULT SHGetFolderPath(
# __in HWND hwndOwner,
# __in int nFolder,
# __in HANDLE hToken,
# __in DWORD dwFlags,
# __out LPTSTR pszPath
# );
def SHGetFolderPathA(nFolder, hToken = None, dwFlags = SHGFP_TYPE_CURRENT):
_SHGetFolderPathA = windll.shell32.SHGetFolderPathA # shfolder.dll in older win versions
_SHGetFolderPathA.argtypes = [HWND, ctypes.c_int, HANDLE, DWORD, LPSTR]
_SHGetFolderPathA.restype = HRESULT
_SHGetFolderPathA.errcheck = RaiseIfNotZero # S_OK == 0
pszPath = ctypes.create_string_buffer(MAX_PATH + 1)
_SHGetFolderPathA(None, nFolder, hToken, dwFlags, pszPath)
return pszPath.value
def SHGetFolderPathW(nFolder, hToken = None, dwFlags = SHGFP_TYPE_CURRENT):
_SHGetFolderPathW = windll.shell32.SHGetFolderPathW # shfolder.dll in older win versions
_SHGetFolderPathW.argtypes = [HWND, ctypes.c_int, HANDLE, DWORD, LPWSTR]
_SHGetFolderPathW.restype = HRESULT
_SHGetFolderPathW.errcheck = RaiseIfNotZero # S_OK == 0
pszPath = ctypes.create_unicode_buffer(MAX_PATH + 1)
_SHGetFolderPathW(None, nFolder, hToken, dwFlags, pszPath)
return pszPath.value
SHGetFolderPath = DefaultStringType(SHGetFolderPathA, SHGetFolderPathW)
# BOOL IsUserAnAdmin(void);
def IsUserAnAdmin():
# Supposedly, IsUserAnAdmin() is deprecated in Vista.
# But I tried it on Windows 7 and it works just fine.
_IsUserAnAdmin = windll.shell32.IsUserAnAdmin
_IsUserAnAdmin.argtypes = []
_IsUserAnAdmin.restype = bool
return _IsUserAnAdmin()
#==============================================================================
# This calculates the list of exported symbols.
_all = set(vars().keys()).difference(_all)
__all__ = [_x for _x in _all if not _x.startswith('_')]
__all__.sort()
#==============================================================================
| 14,007 | Python | 35.574412 | 124 | 0.628257 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/win32/psapi.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Wrapper for psapi.dll in ctypes.
"""
__revision__ = "$Id$"
from winappdbg.win32.defines import *
#==============================================================================
# This is used later on to calculate the list of exported symbols.
_all = None
_all = set(vars().keys())
#==============================================================================
#--- PSAPI structures and constants -------------------------------------------
LIST_MODULES_DEFAULT = 0x00
LIST_MODULES_32BIT = 0x01
LIST_MODULES_64BIT = 0x02
LIST_MODULES_ALL = 0x03
# typedef struct _MODULEINFO {
# LPVOID lpBaseOfDll;
# DWORD SizeOfImage;
# LPVOID EntryPoint;
# } MODULEINFO, *LPMODULEINFO;
class MODULEINFO(Structure):
_fields_ = [
("lpBaseOfDll", LPVOID), # remote pointer
("SizeOfImage", DWORD),
("EntryPoint", LPVOID), # remote pointer
]
LPMODULEINFO = POINTER(MODULEINFO)
#--- psapi.dll ----------------------------------------------------------------
# BOOL WINAPI EnumDeviceDrivers(
# __out LPVOID *lpImageBase,
# __in DWORD cb,
# __out LPDWORD lpcbNeeded
# );
def EnumDeviceDrivers():
_EnumDeviceDrivers = windll.psapi.EnumDeviceDrivers
_EnumDeviceDrivers.argtypes = [LPVOID, DWORD, LPDWORD]
_EnumDeviceDrivers.restype = bool
_EnumDeviceDrivers.errcheck = RaiseIfZero
size = 0x1000
lpcbNeeded = DWORD(size)
unit = sizeof(LPVOID)
while 1:
lpImageBase = (LPVOID * (size // unit))()
_EnumDeviceDrivers(byref(lpImageBase), lpcbNeeded, byref(lpcbNeeded))
needed = lpcbNeeded.value
if needed <= size:
break
size = needed
return [ lpImageBase[index] for index in compat.xrange(0, (needed // unit)) ]
# BOOL WINAPI EnumProcesses(
# __out DWORD *pProcessIds,
# __in DWORD cb,
# __out DWORD *pBytesReturned
# );
def EnumProcesses():
_EnumProcesses = windll.psapi.EnumProcesses
_EnumProcesses.argtypes = [LPVOID, DWORD, LPDWORD]
_EnumProcesses.restype = bool
_EnumProcesses.errcheck = RaiseIfZero
size = 0x1000
cbBytesReturned = DWORD()
unit = sizeof(DWORD)
while 1:
ProcessIds = (DWORD * (size // unit))()
cbBytesReturned.value = size
_EnumProcesses(byref(ProcessIds), cbBytesReturned, byref(cbBytesReturned))
returned = cbBytesReturned.value
if returned < size:
break
size = size + 0x1000
ProcessIdList = list()
for ProcessId in ProcessIds:
if ProcessId is None:
break
ProcessIdList.append(ProcessId)
return ProcessIdList
# BOOL WINAPI EnumProcessModules(
# __in HANDLE hProcess,
# __out HMODULE *lphModule,
# __in DWORD cb,
# __out LPDWORD lpcbNeeded
# );
def EnumProcessModules(hProcess):
_EnumProcessModules = windll.psapi.EnumProcessModules
_EnumProcessModules.argtypes = [HANDLE, LPVOID, DWORD, LPDWORD]
_EnumProcessModules.restype = bool
_EnumProcessModules.errcheck = RaiseIfZero
size = 0x1000
lpcbNeeded = DWORD(size)
unit = sizeof(HMODULE)
while 1:
lphModule = (HMODULE * (size // unit))()
_EnumProcessModules(hProcess, byref(lphModule), lpcbNeeded, byref(lpcbNeeded))
needed = lpcbNeeded.value
if needed <= size:
break
size = needed
return [ lphModule[index] for index in compat.xrange(0, int(needed // unit)) ]
# BOOL WINAPI EnumProcessModulesEx(
# __in HANDLE hProcess,
# __out HMODULE *lphModule,
# __in DWORD cb,
# __out LPDWORD lpcbNeeded,
# __in DWORD dwFilterFlag
# );
def EnumProcessModulesEx(hProcess, dwFilterFlag = LIST_MODULES_DEFAULT):
_EnumProcessModulesEx = windll.psapi.EnumProcessModulesEx
_EnumProcessModulesEx.argtypes = [HANDLE, LPVOID, DWORD, LPDWORD, DWORD]
_EnumProcessModulesEx.restype = bool
_EnumProcessModulesEx.errcheck = RaiseIfZero
size = 0x1000
lpcbNeeded = DWORD(size)
unit = sizeof(HMODULE)
while 1:
lphModule = (HMODULE * (size // unit))()
_EnumProcessModulesEx(hProcess, byref(lphModule), lpcbNeeded, byref(lpcbNeeded), dwFilterFlag)
needed = lpcbNeeded.value
if needed <= size:
break
size = needed
return [ lphModule[index] for index in compat.xrange(0, (needed // unit)) ]
# DWORD WINAPI GetDeviceDriverBaseName(
# __in LPVOID ImageBase,
# __out LPTSTR lpBaseName,
# __in DWORD nSize
# );
def GetDeviceDriverBaseNameA(ImageBase):
_GetDeviceDriverBaseNameA = windll.psapi.GetDeviceDriverBaseNameA
_GetDeviceDriverBaseNameA.argtypes = [LPVOID, LPSTR, DWORD]
_GetDeviceDriverBaseNameA.restype = DWORD
nSize = MAX_PATH
while 1:
lpBaseName = ctypes.create_string_buffer("", nSize)
nCopied = _GetDeviceDriverBaseNameA(ImageBase, lpBaseName, nSize)
if nCopied == 0:
raise ctypes.WinError()
if nCopied < (nSize - 1):
break
nSize = nSize + MAX_PATH
return lpBaseName.value
def GetDeviceDriverBaseNameW(ImageBase):
_GetDeviceDriverBaseNameW = windll.psapi.GetDeviceDriverBaseNameW
_GetDeviceDriverBaseNameW.argtypes = [LPVOID, LPWSTR, DWORD]
_GetDeviceDriverBaseNameW.restype = DWORD
nSize = MAX_PATH
while 1:
lpBaseName = ctypes.create_unicode_buffer(u"", nSize)
nCopied = _GetDeviceDriverBaseNameW(ImageBase, lpBaseName, nSize)
if nCopied == 0:
raise ctypes.WinError()
if nCopied < (nSize - 1):
break
nSize = nSize + MAX_PATH
return lpBaseName.value
GetDeviceDriverBaseName = GuessStringType(GetDeviceDriverBaseNameA, GetDeviceDriverBaseNameW)
# DWORD WINAPI GetDeviceDriverFileName(
# __in LPVOID ImageBase,
# __out LPTSTR lpFilename,
# __in DWORD nSize
# );
def GetDeviceDriverFileNameA(ImageBase):
_GetDeviceDriverFileNameA = windll.psapi.GetDeviceDriverFileNameA
_GetDeviceDriverFileNameA.argtypes = [LPVOID, LPSTR, DWORD]
_GetDeviceDriverFileNameA.restype = DWORD
nSize = MAX_PATH
while 1:
lpFilename = ctypes.create_string_buffer("", nSize)
nCopied = ctypes.windll.psapi.GetDeviceDriverFileNameA(ImageBase, lpFilename, nSize)
if nCopied == 0:
raise ctypes.WinError()
if nCopied < (nSize - 1):
break
nSize = nSize + MAX_PATH
return lpFilename.value
def GetDeviceDriverFileNameW(ImageBase):
_GetDeviceDriverFileNameW = windll.psapi.GetDeviceDriverFileNameW
_GetDeviceDriverFileNameW.argtypes = [LPVOID, LPWSTR, DWORD]
_GetDeviceDriverFileNameW.restype = DWORD
nSize = MAX_PATH
while 1:
lpFilename = ctypes.create_unicode_buffer(u"", nSize)
nCopied = ctypes.windll.psapi.GetDeviceDriverFileNameW(ImageBase, lpFilename, nSize)
if nCopied == 0:
raise ctypes.WinError()
if nCopied < (nSize - 1):
break
nSize = nSize + MAX_PATH
return lpFilename.value
GetDeviceDriverFileName = GuessStringType(GetDeviceDriverFileNameA, GetDeviceDriverFileNameW)
# DWORD WINAPI GetMappedFileName(
# __in HANDLE hProcess,
# __in LPVOID lpv,
# __out LPTSTR lpFilename,
# __in DWORD nSize
# );
def GetMappedFileNameA(hProcess, lpv):
_GetMappedFileNameA = ctypes.windll.psapi.GetMappedFileNameA
_GetMappedFileNameA.argtypes = [HANDLE, LPVOID, LPSTR, DWORD]
_GetMappedFileNameA.restype = DWORD
nSize = MAX_PATH
while 1:
lpFilename = ctypes.create_string_buffer("", nSize)
nCopied = _GetMappedFileNameA(hProcess, lpv, lpFilename, nSize)
if nCopied == 0:
raise ctypes.WinError()
if nCopied < (nSize - 1):
break
nSize = nSize + MAX_PATH
return lpFilename.value
def GetMappedFileNameW(hProcess, lpv):
_GetMappedFileNameW = ctypes.windll.psapi.GetMappedFileNameW
_GetMappedFileNameW.argtypes = [HANDLE, LPVOID, LPWSTR, DWORD]
_GetMappedFileNameW.restype = DWORD
nSize = MAX_PATH
while 1:
lpFilename = ctypes.create_unicode_buffer(u"", nSize)
nCopied = _GetMappedFileNameW(hProcess, lpv, lpFilename, nSize)
if nCopied == 0:
raise ctypes.WinError()
if nCopied < (nSize - 1):
break
nSize = nSize + MAX_PATH
return lpFilename.value
GetMappedFileName = GuessStringType(GetMappedFileNameA, GetMappedFileNameW)
# DWORD WINAPI GetModuleFileNameEx(
# __in HANDLE hProcess,
# __in_opt HMODULE hModule,
# __out LPTSTR lpFilename,
# __in DWORD nSize
# );
def GetModuleFileNameExA(hProcess, hModule = None):
_GetModuleFileNameExA = ctypes.windll.psapi.GetModuleFileNameExA
_GetModuleFileNameExA.argtypes = [HANDLE, HMODULE, LPSTR, DWORD]
_GetModuleFileNameExA.restype = DWORD
nSize = MAX_PATH
while 1:
lpFilename = ctypes.create_string_buffer("", nSize)
nCopied = _GetModuleFileNameExA(hProcess, hModule, lpFilename, nSize)
if nCopied == 0:
raise ctypes.WinError()
if nCopied < (nSize - 1):
break
nSize = nSize + MAX_PATH
return lpFilename.value
def GetModuleFileNameExW(hProcess, hModule = None):
_GetModuleFileNameExW = ctypes.windll.psapi.GetModuleFileNameExW
_GetModuleFileNameExW.argtypes = [HANDLE, HMODULE, LPWSTR, DWORD]
_GetModuleFileNameExW.restype = DWORD
nSize = MAX_PATH
while 1:
lpFilename = ctypes.create_unicode_buffer(u"", nSize)
nCopied = _GetModuleFileNameExW(hProcess, hModule, lpFilename, nSize)
if nCopied == 0:
raise ctypes.WinError()
if nCopied < (nSize - 1):
break
nSize = nSize + MAX_PATH
return lpFilename.value
GetModuleFileNameEx = GuessStringType(GetModuleFileNameExA, GetModuleFileNameExW)
# BOOL WINAPI GetModuleInformation(
# __in HANDLE hProcess,
# __in HMODULE hModule,
# __out LPMODULEINFO lpmodinfo,
# __in DWORD cb
# );
def GetModuleInformation(hProcess, hModule, lpmodinfo = None):
_GetModuleInformation = windll.psapi.GetModuleInformation
_GetModuleInformation.argtypes = [HANDLE, HMODULE, LPMODULEINFO, DWORD]
_GetModuleInformation.restype = bool
_GetModuleInformation.errcheck = RaiseIfZero
if lpmodinfo is None:
lpmodinfo = MODULEINFO()
_GetModuleInformation(hProcess, hModule, byref(lpmodinfo), sizeof(lpmodinfo))
return lpmodinfo
# DWORD WINAPI GetProcessImageFileName(
# __in HANDLE hProcess,
# __out LPTSTR lpImageFileName,
# __in DWORD nSize
# );
def GetProcessImageFileNameA(hProcess):
_GetProcessImageFileNameA = windll.psapi.GetProcessImageFileNameA
_GetProcessImageFileNameA.argtypes = [HANDLE, LPSTR, DWORD]
_GetProcessImageFileNameA.restype = DWORD
nSize = MAX_PATH
while 1:
lpFilename = ctypes.create_string_buffer("", nSize)
nCopied = _GetProcessImageFileNameA(hProcess, lpFilename, nSize)
if nCopied == 0:
raise ctypes.WinError()
if nCopied < (nSize - 1):
break
nSize = nSize + MAX_PATH
return lpFilename.value
def GetProcessImageFileNameW(hProcess):
_GetProcessImageFileNameW = windll.psapi.GetProcessImageFileNameW
_GetProcessImageFileNameW.argtypes = [HANDLE, LPWSTR, DWORD]
_GetProcessImageFileNameW.restype = DWORD
nSize = MAX_PATH
while 1:
lpFilename = ctypes.create_unicode_buffer(u"", nSize)
nCopied = _GetProcessImageFileNameW(hProcess, lpFilename, nSize)
if nCopied == 0:
raise ctypes.WinError()
if nCopied < (nSize - 1):
break
nSize = nSize + MAX_PATH
return lpFilename.value
GetProcessImageFileName = GuessStringType(GetProcessImageFileNameA, GetProcessImageFileNameW)
#==============================================================================
# This calculates the list of exported symbols.
_all = set(vars().keys()).difference(_all)
__all__ = [_x for _x in _all if not _x.startswith('_')]
__all__.sort()
#==============================================================================
| 13,762 | Python | 34.471649 | 102 | 0.65848 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/win32/user32.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Wrapper for user32.dll in ctypes.
"""
__revision__ = "$Id$"
from winappdbg.win32.defines import *
from winappdbg.win32.version import bits
from winappdbg.win32.kernel32 import GetLastError, SetLastError
from winappdbg.win32.gdi32 import POINT, PPOINT, LPPOINT, RECT, PRECT, LPRECT
#==============================================================================
# This is used later on to calculate the list of exported symbols.
_all = None
_all = set(vars().keys())
#==============================================================================
#--- Helpers ------------------------------------------------------------------
def MAKE_WPARAM(wParam):
"""
Convert arguments to the WPARAM type.
Used automatically by SendMessage, PostMessage, etc.
You shouldn't need to call this function.
"""
wParam = ctypes.cast(wParam, LPVOID).value
if wParam is None:
wParam = 0
return wParam
def MAKE_LPARAM(lParam):
"""
Convert arguments to the LPARAM type.
Used automatically by SendMessage, PostMessage, etc.
You shouldn't need to call this function.
"""
return ctypes.cast(lParam, LPARAM)
class __WindowEnumerator (object):
"""
Window enumerator class. Used internally by the window enumeration APIs.
"""
def __init__(self):
self.hwnd = list()
def __call__(self, hwnd, lParam):
## print hwnd # XXX DEBUG
self.hwnd.append(hwnd)
return TRUE
#--- Types --------------------------------------------------------------------
WNDENUMPROC = WINFUNCTYPE(BOOL, HWND, PVOID)
#--- Constants ----------------------------------------------------------------
HWND_DESKTOP = 0
HWND_TOP = 1
HWND_BOTTOM = 1
HWND_TOPMOST = -1
HWND_NOTOPMOST = -2
HWND_MESSAGE = -3
# GetWindowLong / SetWindowLong
GWL_WNDPROC = -4
GWL_HINSTANCE = -6
GWL_HWNDPARENT = -8
GWL_ID = -12
GWL_STYLE = -16
GWL_EXSTYLE = -20
GWL_USERDATA = -21
# GetWindowLongPtr / SetWindowLongPtr
GWLP_WNDPROC = GWL_WNDPROC
GWLP_HINSTANCE = GWL_HINSTANCE
GWLP_HWNDPARENT = GWL_HWNDPARENT
GWLP_STYLE = GWL_STYLE
GWLP_EXSTYLE = GWL_EXSTYLE
GWLP_USERDATA = GWL_USERDATA
GWLP_ID = GWL_ID
# ShowWindow
SW_HIDE = 0
SW_SHOWNORMAL = 1
SW_NORMAL = 1
SW_SHOWMINIMIZED = 2
SW_SHOWMAXIMIZED = 3
SW_MAXIMIZE = 3
SW_SHOWNOACTIVATE = 4
SW_SHOW = 5
SW_MINIMIZE = 6
SW_SHOWMINNOACTIVE = 7
SW_SHOWNA = 8
SW_RESTORE = 9
SW_SHOWDEFAULT = 10
SW_FORCEMINIMIZE = 11
# SendMessageTimeout flags
SMTO_NORMAL = 0
SMTO_BLOCK = 1
SMTO_ABORTIFHUNG = 2
SMTO_NOTIMEOUTIFNOTHUNG = 8
SMTO_ERRORONEXIT = 0x20
# WINDOWPLACEMENT flags
WPF_SETMINPOSITION = 1
WPF_RESTORETOMAXIMIZED = 2
WPF_ASYNCWINDOWPLACEMENT = 4
# GetAncestor flags
GA_PARENT = 1
GA_ROOT = 2
GA_ROOTOWNER = 3
# GetWindow flags
GW_HWNDFIRST = 0
GW_HWNDLAST = 1
GW_HWNDNEXT = 2
GW_HWNDPREV = 3
GW_OWNER = 4
GW_CHILD = 5
GW_ENABLEDPOPUP = 6
#--- Window messages ----------------------------------------------------------
WM_USER = 0x400
WM_APP = 0x800
WM_NULL = 0
WM_CREATE = 1
WM_DESTROY = 2
WM_MOVE = 3
WM_SIZE = 5
WM_ACTIVATE = 6
WA_INACTIVE = 0
WA_ACTIVE = 1
WA_CLICKACTIVE = 2
WM_SETFOCUS = 7
WM_KILLFOCUS = 8
WM_ENABLE = 0x0A
WM_SETREDRAW = 0x0B
WM_SETTEXT = 0x0C
WM_GETTEXT = 0x0D
WM_GETTEXTLENGTH = 0x0E
WM_PAINT = 0x0F
WM_CLOSE = 0x10
WM_QUERYENDSESSION = 0x11
WM_QUIT = 0x12
WM_QUERYOPEN = 0x13
WM_ERASEBKGND = 0x14
WM_SYSCOLORCHANGE = 0x15
WM_ENDSESSION = 0x16
WM_SHOWWINDOW = 0x18
WM_WININICHANGE = 0x1A
WM_SETTINGCHANGE = WM_WININICHANGE
WM_DEVMODECHANGE = 0x1B
WM_ACTIVATEAPP = 0x1C
WM_FONTCHANGE = 0x1D
WM_TIMECHANGE = 0x1E
WM_CANCELMODE = 0x1F
WM_SETCURSOR = 0x20
WM_MOUSEACTIVATE = 0x21
WM_CHILDACTIVATE = 0x22
WM_QUEUESYNC = 0x23
WM_GETMINMAXINFO = 0x24
WM_PAINTICON = 0x26
WM_ICONERASEBKGND = 0x27
WM_NEXTDLGCTL = 0x28
WM_SPOOLERSTATUS = 0x2A
WM_DRAWITEM = 0x2B
WM_MEASUREITEM = 0x2C
WM_DELETEITEM = 0x2D
WM_VKEYTOITEM = 0x2E
WM_CHARTOITEM = 0x2F
WM_SETFONT = 0x30
WM_GETFONT = 0x31
WM_SETHOTKEY = 0x32
WM_GETHOTKEY = 0x33
WM_QUERYDRAGICON = 0x37
WM_COMPAREITEM = 0x39
WM_GETOBJECT = 0x3D
WM_COMPACTING = 0x41
WM_OTHERWINDOWCREATED = 0x42
WM_OTHERWINDOWDESTROYED = 0x43
WM_COMMNOTIFY = 0x44
CN_RECEIVE = 0x1
CN_TRANSMIT = 0x2
CN_EVENT = 0x4
WM_WINDOWPOSCHANGING = 0x46
WM_WINDOWPOSCHANGED = 0x47
WM_POWER = 0x48
PWR_OK = 1
PWR_FAIL = -1
PWR_SUSPENDREQUEST = 1
PWR_SUSPENDRESUME = 2
PWR_CRITICALRESUME = 3
WM_COPYDATA = 0x4A
WM_CANCELJOURNAL = 0x4B
WM_NOTIFY = 0x4E
WM_INPUTLANGCHANGEREQUEST = 0x50
WM_INPUTLANGCHANGE = 0x51
WM_TCARD = 0x52
WM_HELP = 0x53
WM_USERCHANGED = 0x54
WM_NOTIFYFORMAT = 0x55
WM_CONTEXTMENU = 0x7B
WM_STYLECHANGING = 0x7C
WM_STYLECHANGED = 0x7D
WM_DISPLAYCHANGE = 0x7E
WM_GETICON = 0x7F
WM_SETICON = 0x80
WM_NCCREATE = 0x81
WM_NCDESTROY = 0x82
WM_NCCALCSIZE = 0x83
WM_NCHITTEST = 0x84
WM_NCPAINT = 0x85
WM_NCACTIVATE = 0x86
WM_GETDLGCODE = 0x87
WM_SYNCPAINT = 0x88
WM_NCMOUSEMOVE = 0x0A0
WM_NCLBUTTONDOWN = 0x0A1
WM_NCLBUTTONUP = 0x0A2
WM_NCLBUTTONDBLCLK = 0x0A3
WM_NCRBUTTONDOWN = 0x0A4
WM_NCRBUTTONUP = 0x0A5
WM_NCRBUTTONDBLCLK = 0x0A6
WM_NCMBUTTONDOWN = 0x0A7
WM_NCMBUTTONUP = 0x0A8
WM_NCMBUTTONDBLCLK = 0x0A9
WM_KEYFIRST = 0x100
WM_KEYDOWN = 0x100
WM_KEYUP = 0x101
WM_CHAR = 0x102
WM_DEADCHAR = 0x103
WM_SYSKEYDOWN = 0x104
WM_SYSKEYUP = 0x105
WM_SYSCHAR = 0x106
WM_SYSDEADCHAR = 0x107
WM_KEYLAST = 0x108
WM_INITDIALOG = 0x110
WM_COMMAND = 0x111
WM_SYSCOMMAND = 0x112
WM_TIMER = 0x113
WM_HSCROLL = 0x114
WM_VSCROLL = 0x115
WM_INITMENU = 0x116
WM_INITMENUPOPUP = 0x117
WM_MENUSELECT = 0x11F
WM_MENUCHAR = 0x120
WM_ENTERIDLE = 0x121
WM_CTLCOLORMSGBOX = 0x132
WM_CTLCOLOREDIT = 0x133
WM_CTLCOLORLISTBOX = 0x134
WM_CTLCOLORBTN = 0x135
WM_CTLCOLORDLG = 0x136
WM_CTLCOLORSCROLLBAR = 0x137
WM_CTLCOLORSTATIC = 0x138
WM_MOUSEFIRST = 0x200
WM_MOUSEMOVE = 0x200
WM_LBUTTONDOWN = 0x201
WM_LBUTTONUP = 0x202
WM_LBUTTONDBLCLK = 0x203
WM_RBUTTONDOWN = 0x204
WM_RBUTTONUP = 0x205
WM_RBUTTONDBLCLK = 0x206
WM_MBUTTONDOWN = 0x207
WM_MBUTTONUP = 0x208
WM_MBUTTONDBLCLK = 0x209
WM_MOUSELAST = 0x209
WM_PARENTNOTIFY = 0x210
WM_ENTERMENULOOP = 0x211
WM_EXITMENULOOP = 0x212
WM_MDICREATE = 0x220
WM_MDIDESTROY = 0x221
WM_MDIACTIVATE = 0x222
WM_MDIRESTORE = 0x223
WM_MDINEXT = 0x224
WM_MDIMAXIMIZE = 0x225
WM_MDITILE = 0x226
WM_MDICASCADE = 0x227
WM_MDIICONARRANGE = 0x228
WM_MDIGETACTIVE = 0x229
WM_MDISETMENU = 0x230
WM_DROPFILES = 0x233
WM_MDIREFRESHMENU = 0x234
WM_CUT = 0x300
WM_COPY = 0x301
WM_PASTE = 0x302
WM_CLEAR = 0x303
WM_UNDO = 0x304
WM_RENDERFORMAT = 0x305
WM_RENDERALLFORMATS = 0x306
WM_DESTROYCLIPBOARD = 0x307
WM_DRAWCLIPBOARD = 0x308
WM_PAINTCLIPBOARD = 0x309
WM_VSCROLLCLIPBOARD = 0x30A
WM_SIZECLIPBOARD = 0x30B
WM_ASKCBFORMATNAME = 0x30C
WM_CHANGECBCHAIN = 0x30D
WM_HSCROLLCLIPBOARD = 0x30E
WM_QUERYNEWPALETTE = 0x30F
WM_PALETTEISCHANGING = 0x310
WM_PALETTECHANGED = 0x311
WM_HOTKEY = 0x312
WM_PRINT = 0x317
WM_PRINTCLIENT = 0x318
WM_PENWINFIRST = 0x380
WM_PENWINLAST = 0x38F
#--- Structures ---------------------------------------------------------------
# typedef struct _WINDOWPLACEMENT {
# UINT length;
# UINT flags;
# UINT showCmd;
# POINT ptMinPosition;
# POINT ptMaxPosition;
# RECT rcNormalPosition;
# } WINDOWPLACEMENT;
class WINDOWPLACEMENT(Structure):
_fields_ = [
('length', UINT),
('flags', UINT),
('showCmd', UINT),
('ptMinPosition', POINT),
('ptMaxPosition', POINT),
('rcNormalPosition', RECT),
]
PWINDOWPLACEMENT = POINTER(WINDOWPLACEMENT)
LPWINDOWPLACEMENT = PWINDOWPLACEMENT
# typedef struct tagGUITHREADINFO {
# DWORD cbSize;
# DWORD flags;
# HWND hwndActive;
# HWND hwndFocus;
# HWND hwndCapture;
# HWND hwndMenuOwner;
# HWND hwndMoveSize;
# HWND hwndCaret;
# RECT rcCaret;
# } GUITHREADINFO, *PGUITHREADINFO;
class GUITHREADINFO(Structure):
_fields_ = [
('cbSize', DWORD),
('flags', DWORD),
('hwndActive', HWND),
('hwndFocus', HWND),
('hwndCapture', HWND),
('hwndMenuOwner', HWND),
('hwndMoveSize', HWND),
('hwndCaret', HWND),
('rcCaret', RECT),
]
PGUITHREADINFO = POINTER(GUITHREADINFO)
LPGUITHREADINFO = PGUITHREADINFO
#--- High level classes -------------------------------------------------------
# Point() and Rect() are here instead of gdi32.py because they were mainly
# created to handle window coordinates rather than drawing on the screen.
# XXX not sure if these classes should be psyco-optimized,
# it may not work if the user wants to serialize them for some reason
class Point(object):
"""
Python wrapper over the L{POINT} class.
@type x: int
@ivar x: Horizontal coordinate
@type y: int
@ivar y: Vertical coordinate
"""
def __init__(self, x = 0, y = 0):
"""
@see: L{POINT}
@type x: int
@param x: Horizontal coordinate
@type y: int
@param y: Vertical coordinate
"""
self.x = x
self.y = y
def __iter__(self):
return (self.x, self.y).__iter__()
def __len__(self):
return 2
def __getitem__(self, index):
return (self.x, self.y) [index]
def __setitem__(self, index, value):
if index == 0:
self.x = value
elif index == 1:
self.y = value
else:
raise IndexError("index out of range")
@property
def _as_parameter_(self):
"""
Compatibility with ctypes.
Allows passing transparently a Point object to an API call.
"""
return POINT(self.x, self.y)
def screen_to_client(self, hWnd):
"""
Translates window screen coordinates to client coordinates.
@see: L{client_to_screen}, L{translate}
@type hWnd: int or L{HWND} or L{system.Window}
@param hWnd: Window handle.
@rtype: L{Point}
@return: New object containing the translated coordinates.
"""
return ScreenToClient(hWnd, self)
def client_to_screen(self, hWnd):
"""
Translates window client coordinates to screen coordinates.
@see: L{screen_to_client}, L{translate}
@type hWnd: int or L{HWND} or L{system.Window}
@param hWnd: Window handle.
@rtype: L{Point}
@return: New object containing the translated coordinates.
"""
return ClientToScreen(hWnd, self)
def translate(self, hWndFrom = HWND_DESKTOP, hWndTo = HWND_DESKTOP):
"""
Translate coordinates from one window to another.
@note: To translate multiple points it's more efficient to use the
L{MapWindowPoints} function instead.
@see: L{client_to_screen}, L{screen_to_client}
@type hWndFrom: int or L{HWND} or L{system.Window}
@param hWndFrom: Window handle to translate from.
Use C{HWND_DESKTOP} for screen coordinates.
@type hWndTo: int or L{HWND} or L{system.Window}
@param hWndTo: Window handle to translate to.
Use C{HWND_DESKTOP} for screen coordinates.
@rtype: L{Point}
@return: New object containing the translated coordinates.
"""
return MapWindowPoints(hWndFrom, hWndTo, [self])
class Rect(object):
"""
Python wrapper over the L{RECT} class.
@type left: int
@ivar left: Horizontal coordinate for the top left corner.
@type top: int
@ivar top: Vertical coordinate for the top left corner.
@type right: int
@ivar right: Horizontal coordinate for the bottom right corner.
@type bottom: int
@ivar bottom: Vertical coordinate for the bottom right corner.
@type width: int
@ivar width: Width in pixels. Same as C{right - left}.
@type height: int
@ivar height: Height in pixels. Same as C{bottom - top}.
"""
def __init__(self, left = 0, top = 0, right = 0, bottom = 0):
"""
@see: L{RECT}
@type left: int
@param left: Horizontal coordinate for the top left corner.
@type top: int
@param top: Vertical coordinate for the top left corner.
@type right: int
@param right: Horizontal coordinate for the bottom right corner.
@type bottom: int
@param bottom: Vertical coordinate for the bottom right corner.
"""
self.left = left
self.top = top
self.right = right
self.bottom = bottom
def __iter__(self):
return (self.left, self.top, self.right, self.bottom).__iter__()
def __len__(self):
return 2
def __getitem__(self, index):
return (self.left, self.top, self.right, self.bottom) [index]
def __setitem__(self, index, value):
if index == 0:
self.left = value
elif index == 1:
self.top = value
elif index == 2:
self.right = value
elif index == 3:
self.bottom = value
else:
raise IndexError("index out of range")
@property
def _as_parameter_(self):
"""
Compatibility with ctypes.
Allows passing transparently a Point object to an API call.
"""
return RECT(self.left, self.top, self.right, self.bottom)
def __get_width(self):
return self.right - self.left
def __get_height(self):
return self.bottom - self.top
def __set_width(self, value):
self.right = value - self.left
def __set_height(self, value):
self.bottom = value - self.top
width = property(__get_width, __set_width)
height = property(__get_height, __set_height)
def screen_to_client(self, hWnd):
"""
Translates window screen coordinates to client coordinates.
@see: L{client_to_screen}, L{translate}
@type hWnd: int or L{HWND} or L{system.Window}
@param hWnd: Window handle.
@rtype: L{Rect}
@return: New object containing the translated coordinates.
"""
topleft = ScreenToClient(hWnd, (self.left, self.top))
bottomright = ScreenToClient(hWnd, (self.bottom, self.right))
return Rect( topleft.x, topleft.y, bottomright.x, bottomright.y )
def client_to_screen(self, hWnd):
"""
Translates window client coordinates to screen coordinates.
@see: L{screen_to_client}, L{translate}
@type hWnd: int or L{HWND} or L{system.Window}
@param hWnd: Window handle.
@rtype: L{Rect}
@return: New object containing the translated coordinates.
"""
topleft = ClientToScreen(hWnd, (self.left, self.top))
bottomright = ClientToScreen(hWnd, (self.bottom, self.right))
return Rect( topleft.x, topleft.y, bottomright.x, bottomright.y )
def translate(self, hWndFrom = HWND_DESKTOP, hWndTo = HWND_DESKTOP):
"""
Translate coordinates from one window to another.
@see: L{client_to_screen}, L{screen_to_client}
@type hWndFrom: int or L{HWND} or L{system.Window}
@param hWndFrom: Window handle to translate from.
Use C{HWND_DESKTOP} for screen coordinates.
@type hWndTo: int or L{HWND} or L{system.Window}
@param hWndTo: Window handle to translate to.
Use C{HWND_DESKTOP} for screen coordinates.
@rtype: L{Rect}
@return: New object containing the translated coordinates.
"""
points = [ (self.left, self.top), (self.right, self.bottom) ]
return MapWindowPoints(hWndFrom, hWndTo, points)
class WindowPlacement(object):
"""
Python wrapper over the L{WINDOWPLACEMENT} class.
"""
def __init__(self, wp = None):
"""
@type wp: L{WindowPlacement} or L{WINDOWPLACEMENT}
@param wp: Another window placement object.
"""
# Initialize all properties with empty values.
self.flags = 0
self.showCmd = 0
self.ptMinPosition = Point()
self.ptMaxPosition = Point()
self.rcNormalPosition = Rect()
# If a window placement was given copy it's properties.
if wp:
self.flags = wp.flags
self.showCmd = wp.showCmd
self.ptMinPosition = Point( wp.ptMinPosition.x, wp.ptMinPosition.y )
self.ptMaxPosition = Point( wp.ptMaxPosition.x, wp.ptMaxPosition.y )
self.rcNormalPosition = Rect(
wp.rcNormalPosition.left,
wp.rcNormalPosition.top,
wp.rcNormalPosition.right,
wp.rcNormalPosition.bottom,
)
@property
def _as_parameter_(self):
"""
Compatibility with ctypes.
Allows passing transparently a Point object to an API call.
"""
wp = WINDOWPLACEMENT()
wp.length = sizeof(wp)
wp.flags = self.flags
wp.showCmd = self.showCmd
wp.ptMinPosition.x = self.ptMinPosition.x
wp.ptMinPosition.y = self.ptMinPosition.y
wp.ptMaxPosition.x = self.ptMaxPosition.x
wp.ptMaxPosition.y = self.ptMaxPosition.y
wp.rcNormalPosition.left = self.rcNormalPosition.left
wp.rcNormalPosition.top = self.rcNormalPosition.top
wp.rcNormalPosition.right = self.rcNormalPosition.right
wp.rcNormalPosition.bottom = self.rcNormalPosition.bottom
return wp
#--- user32.dll ---------------------------------------------------------------
# void WINAPI SetLastErrorEx(
# __in DWORD dwErrCode,
# __in DWORD dwType
# );
def SetLastErrorEx(dwErrCode, dwType = 0):
_SetLastErrorEx = windll.user32.SetLastErrorEx
_SetLastErrorEx.argtypes = [DWORD, DWORD]
_SetLastErrorEx.restype = None
_SetLastErrorEx(dwErrCode, dwType)
# HWND FindWindow(
# LPCTSTR lpClassName,
# LPCTSTR lpWindowName
# );
def FindWindowA(lpClassName = None, lpWindowName = None):
_FindWindowA = windll.user32.FindWindowA
_FindWindowA.argtypes = [LPSTR, LPSTR]
_FindWindowA.restype = HWND
hWnd = _FindWindowA(lpClassName, lpWindowName)
if not hWnd:
errcode = GetLastError()
if errcode != ERROR_SUCCESS:
raise ctypes.WinError(errcode)
return hWnd
def FindWindowW(lpClassName = None, lpWindowName = None):
_FindWindowW = windll.user32.FindWindowW
_FindWindowW.argtypes = [LPWSTR, LPWSTR]
_FindWindowW.restype = HWND
hWnd = _FindWindowW(lpClassName, lpWindowName)
if not hWnd:
errcode = GetLastError()
if errcode != ERROR_SUCCESS:
raise ctypes.WinError(errcode)
return hWnd
FindWindow = GuessStringType(FindWindowA, FindWindowW)
# HWND WINAPI FindWindowEx(
# __in_opt HWND hwndParent,
# __in_opt HWND hwndChildAfter,
# __in_opt LPCTSTR lpszClass,
# __in_opt LPCTSTR lpszWindow
# );
def FindWindowExA(hwndParent = None, hwndChildAfter = None, lpClassName = None, lpWindowName = None):
_FindWindowExA = windll.user32.FindWindowExA
_FindWindowExA.argtypes = [HWND, HWND, LPSTR, LPSTR]
_FindWindowExA.restype = HWND
hWnd = _FindWindowExA(hwndParent, hwndChildAfter, lpClassName, lpWindowName)
if not hWnd:
errcode = GetLastError()
if errcode != ERROR_SUCCESS:
raise ctypes.WinError(errcode)
return hWnd
def FindWindowExW(hwndParent = None, hwndChildAfter = None, lpClassName = None, lpWindowName = None):
_FindWindowExW = windll.user32.FindWindowExW
_FindWindowExW.argtypes = [HWND, HWND, LPWSTR, LPWSTR]
_FindWindowExW.restype = HWND
hWnd = _FindWindowExW(hwndParent, hwndChildAfter, lpClassName, lpWindowName)
if not hWnd:
errcode = GetLastError()
if errcode != ERROR_SUCCESS:
raise ctypes.WinError(errcode)
return hWnd
FindWindowEx = GuessStringType(FindWindowExA, FindWindowExW)
# int GetClassName(
# HWND hWnd,
# LPTSTR lpClassName,
# int nMaxCount
# );
def GetClassNameA(hWnd):
_GetClassNameA = windll.user32.GetClassNameA
_GetClassNameA.argtypes = [HWND, LPSTR, ctypes.c_int]
_GetClassNameA.restype = ctypes.c_int
nMaxCount = 0x1000
dwCharSize = sizeof(CHAR)
while 1:
lpClassName = ctypes.create_string_buffer("", nMaxCount)
nCount = _GetClassNameA(hWnd, lpClassName, nMaxCount)
if nCount == 0:
raise ctypes.WinError()
if nCount < nMaxCount - dwCharSize:
break
nMaxCount += 0x1000
return lpClassName.value
def GetClassNameW(hWnd):
_GetClassNameW = windll.user32.GetClassNameW
_GetClassNameW.argtypes = [HWND, LPWSTR, ctypes.c_int]
_GetClassNameW.restype = ctypes.c_int
nMaxCount = 0x1000
dwCharSize = sizeof(WCHAR)
while 1:
lpClassName = ctypes.create_unicode_buffer(u"", nMaxCount)
nCount = _GetClassNameW(hWnd, lpClassName, nMaxCount)
if nCount == 0:
raise ctypes.WinError()
if nCount < nMaxCount - dwCharSize:
break
nMaxCount += 0x1000
return lpClassName.value
GetClassName = GuessStringType(GetClassNameA, GetClassNameW)
# int WINAPI GetWindowText(
# __in HWND hWnd,
# __out LPTSTR lpString,
# __in int nMaxCount
# );
def GetWindowTextA(hWnd):
_GetWindowTextA = windll.user32.GetWindowTextA
_GetWindowTextA.argtypes = [HWND, LPSTR, ctypes.c_int]
_GetWindowTextA.restype = ctypes.c_int
nMaxCount = 0x1000
dwCharSize = sizeof(CHAR)
while 1:
lpString = ctypes.create_string_buffer("", nMaxCount)
nCount = _GetWindowTextA(hWnd, lpString, nMaxCount)
if nCount == 0:
raise ctypes.WinError()
if nCount < nMaxCount - dwCharSize:
break
nMaxCount += 0x1000
return lpString.value
def GetWindowTextW(hWnd):
_GetWindowTextW = windll.user32.GetWindowTextW
_GetWindowTextW.argtypes = [HWND, LPWSTR, ctypes.c_int]
_GetWindowTextW.restype = ctypes.c_int
nMaxCount = 0x1000
dwCharSize = sizeof(CHAR)
while 1:
lpString = ctypes.create_string_buffer("", nMaxCount)
nCount = _GetWindowTextW(hWnd, lpString, nMaxCount)
if nCount == 0:
raise ctypes.WinError()
if nCount < nMaxCount - dwCharSize:
break
nMaxCount += 0x1000
return lpString.value
GetWindowText = GuessStringType(GetWindowTextA, GetWindowTextW)
# BOOL WINAPI SetWindowText(
# __in HWND hWnd,
# __in_opt LPCTSTR lpString
# );
def SetWindowTextA(hWnd, lpString = None):
_SetWindowTextA = windll.user32.SetWindowTextA
_SetWindowTextA.argtypes = [HWND, LPSTR]
_SetWindowTextA.restype = bool
_SetWindowTextA.errcheck = RaiseIfZero
_SetWindowTextA(hWnd, lpString)
def SetWindowTextW(hWnd, lpString = None):
_SetWindowTextW = windll.user32.SetWindowTextW
_SetWindowTextW.argtypes = [HWND, LPWSTR]
_SetWindowTextW.restype = bool
_SetWindowTextW.errcheck = RaiseIfZero
_SetWindowTextW(hWnd, lpString)
SetWindowText = GuessStringType(SetWindowTextA, SetWindowTextW)
# LONG GetWindowLong(
# HWND hWnd,
# int nIndex
# );
def GetWindowLongA(hWnd, nIndex = 0):
_GetWindowLongA = windll.user32.GetWindowLongA
_GetWindowLongA.argtypes = [HWND, ctypes.c_int]
_GetWindowLongA.restype = DWORD
SetLastError(ERROR_SUCCESS)
retval = _GetWindowLongA(hWnd, nIndex)
if retval == 0:
errcode = GetLastError()
if errcode != ERROR_SUCCESS:
raise ctypes.WinError(errcode)
return retval
def GetWindowLongW(hWnd, nIndex = 0):
_GetWindowLongW = windll.user32.GetWindowLongW
_GetWindowLongW.argtypes = [HWND, ctypes.c_int]
_GetWindowLongW.restype = DWORD
SetLastError(ERROR_SUCCESS)
retval = _GetWindowLongW(hWnd, nIndex)
if retval == 0:
errcode = GetLastError()
if errcode != ERROR_SUCCESS:
raise ctypes.WinError(errcode)
return retval
GetWindowLong = DefaultStringType(GetWindowLongA, GetWindowLongW)
# LONG_PTR WINAPI GetWindowLongPtr(
# _In_ HWND hWnd,
# _In_ int nIndex
# );
if bits == 32:
GetWindowLongPtrA = GetWindowLongA
GetWindowLongPtrW = GetWindowLongW
GetWindowLongPtr = GetWindowLong
else:
def GetWindowLongPtrA(hWnd, nIndex = 0):
_GetWindowLongPtrA = windll.user32.GetWindowLongPtrA
_GetWindowLongPtrA.argtypes = [HWND, ctypes.c_int]
_GetWindowLongPtrA.restype = SIZE_T
SetLastError(ERROR_SUCCESS)
retval = _GetWindowLongPtrA(hWnd, nIndex)
if retval == 0:
errcode = GetLastError()
if errcode != ERROR_SUCCESS:
raise ctypes.WinError(errcode)
return retval
def GetWindowLongPtrW(hWnd, nIndex = 0):
_GetWindowLongPtrW = windll.user32.GetWindowLongPtrW
_GetWindowLongPtrW.argtypes = [HWND, ctypes.c_int]
_GetWindowLongPtrW.restype = DWORD
SetLastError(ERROR_SUCCESS)
retval = _GetWindowLongPtrW(hWnd, nIndex)
if retval == 0:
errcode = GetLastError()
if errcode != ERROR_SUCCESS:
raise ctypes.WinError(errcode)
return retval
GetWindowLongPtr = DefaultStringType(GetWindowLongPtrA, GetWindowLongPtrW)
# LONG WINAPI SetWindowLong(
# _In_ HWND hWnd,
# _In_ int nIndex,
# _In_ LONG dwNewLong
# );
def SetWindowLongA(hWnd, nIndex, dwNewLong):
_SetWindowLongA = windll.user32.SetWindowLongA
_SetWindowLongA.argtypes = [HWND, ctypes.c_int, DWORD]
_SetWindowLongA.restype = DWORD
SetLastError(ERROR_SUCCESS)
retval = _SetWindowLongA(hWnd, nIndex, dwNewLong)
if retval == 0:
errcode = GetLastError()
if errcode != ERROR_SUCCESS:
raise ctypes.WinError(errcode)
return retval
def SetWindowLongW(hWnd, nIndex, dwNewLong):
_SetWindowLongW = windll.user32.SetWindowLongW
_SetWindowLongW.argtypes = [HWND, ctypes.c_int, DWORD]
_SetWindowLongW.restype = DWORD
SetLastError(ERROR_SUCCESS)
retval = _SetWindowLongW(hWnd, nIndex, dwNewLong)
if retval == 0:
errcode = GetLastError()
if errcode != ERROR_SUCCESS:
raise ctypes.WinError(errcode)
return retval
SetWindowLong = DefaultStringType(SetWindowLongA, SetWindowLongW)
# LONG_PTR WINAPI SetWindowLongPtr(
# _In_ HWND hWnd,
# _In_ int nIndex,
# _In_ LONG_PTR dwNewLong
# );
if bits == 32:
SetWindowLongPtrA = SetWindowLongA
SetWindowLongPtrW = SetWindowLongW
SetWindowLongPtr = SetWindowLong
else:
def SetWindowLongPtrA(hWnd, nIndex, dwNewLong):
_SetWindowLongPtrA = windll.user32.SetWindowLongPtrA
_SetWindowLongPtrA.argtypes = [HWND, ctypes.c_int, SIZE_T]
_SetWindowLongPtrA.restype = SIZE_T
SetLastError(ERROR_SUCCESS)
retval = _SetWindowLongPtrA(hWnd, nIndex, dwNewLong)
if retval == 0:
errcode = GetLastError()
if errcode != ERROR_SUCCESS:
raise ctypes.WinError(errcode)
return retval
def SetWindowLongPtrW(hWnd, nIndex, dwNewLong):
_SetWindowLongPtrW = windll.user32.SetWindowLongPtrW
_SetWindowLongPtrW.argtypes = [HWND, ctypes.c_int, SIZE_T]
_SetWindowLongPtrW.restype = SIZE_T
SetLastError(ERROR_SUCCESS)
retval = _SetWindowLongPtrW(hWnd, nIndex, dwNewLong)
if retval == 0:
errcode = GetLastError()
if errcode != ERROR_SUCCESS:
raise ctypes.WinError(errcode)
return retval
SetWindowLongPtr = DefaultStringType(SetWindowLongPtrA, SetWindowLongPtrW)
# HWND GetShellWindow(VOID);
def GetShellWindow():
_GetShellWindow = windll.user32.GetShellWindow
_GetShellWindow.argtypes = []
_GetShellWindow.restype = HWND
_GetShellWindow.errcheck = RaiseIfZero
return _GetShellWindow()
# DWORD GetWindowThreadProcessId(
# HWND hWnd,
# LPDWORD lpdwProcessId
# );
def GetWindowThreadProcessId(hWnd):
_GetWindowThreadProcessId = windll.user32.GetWindowThreadProcessId
_GetWindowThreadProcessId.argtypes = [HWND, LPDWORD]
_GetWindowThreadProcessId.restype = DWORD
_GetWindowThreadProcessId.errcheck = RaiseIfZero
dwProcessId = DWORD(0)
dwThreadId = _GetWindowThreadProcessId(hWnd, byref(dwProcessId))
return (dwThreadId, dwProcessId.value)
# HWND WINAPI GetWindow(
# __in HWND hwnd,
# __in UINT uCmd
# );
def GetWindow(hWnd, uCmd):
_GetWindow = windll.user32.GetWindow
_GetWindow.argtypes = [HWND, UINT]
_GetWindow.restype = HWND
SetLastError(ERROR_SUCCESS)
hWndTarget = _GetWindow(hWnd, uCmd)
if not hWndTarget:
winerr = GetLastError()
if winerr != ERROR_SUCCESS:
raise ctypes.WinError(winerr)
return hWndTarget
# HWND GetParent(
# HWND hWnd
# );
def GetParent(hWnd):
_GetParent = windll.user32.GetParent
_GetParent.argtypes = [HWND]
_GetParent.restype = HWND
SetLastError(ERROR_SUCCESS)
hWndParent = _GetParent(hWnd)
if not hWndParent:
winerr = GetLastError()
if winerr != ERROR_SUCCESS:
raise ctypes.WinError(winerr)
return hWndParent
# HWND WINAPI GetAncestor(
# __in HWND hwnd,
# __in UINT gaFlags
# );
def GetAncestor(hWnd, gaFlags = GA_PARENT):
_GetAncestor = windll.user32.GetAncestor
_GetAncestor.argtypes = [HWND, UINT]
_GetAncestor.restype = HWND
SetLastError(ERROR_SUCCESS)
hWndParent = _GetAncestor(hWnd, gaFlags)
if not hWndParent:
winerr = GetLastError()
if winerr != ERROR_SUCCESS:
raise ctypes.WinError(winerr)
return hWndParent
# BOOL EnableWindow(
# HWND hWnd,
# BOOL bEnable
# );
def EnableWindow(hWnd, bEnable = True):
_EnableWindow = windll.user32.EnableWindow
_EnableWindow.argtypes = [HWND, BOOL]
_EnableWindow.restype = bool
return _EnableWindow(hWnd, bool(bEnable))
# BOOL ShowWindow(
# HWND hWnd,
# int nCmdShow
# );
def ShowWindow(hWnd, nCmdShow = SW_SHOW):
_ShowWindow = windll.user32.ShowWindow
_ShowWindow.argtypes = [HWND, ctypes.c_int]
_ShowWindow.restype = bool
return _ShowWindow(hWnd, nCmdShow)
# BOOL ShowWindowAsync(
# HWND hWnd,
# int nCmdShow
# );
def ShowWindowAsync(hWnd, nCmdShow = SW_SHOW):
_ShowWindowAsync = windll.user32.ShowWindowAsync
_ShowWindowAsync.argtypes = [HWND, ctypes.c_int]
_ShowWindowAsync.restype = bool
return _ShowWindowAsync(hWnd, nCmdShow)
# HWND GetDesktopWindow(VOID);
def GetDesktopWindow():
_GetDesktopWindow = windll.user32.GetDesktopWindow
_GetDesktopWindow.argtypes = []
_GetDesktopWindow.restype = HWND
_GetDesktopWindow.errcheck = RaiseIfZero
return _GetDesktopWindow()
# HWND GetForegroundWindow(VOID);
def GetForegroundWindow():
_GetForegroundWindow = windll.user32.GetForegroundWindow
_GetForegroundWindow.argtypes = []
_GetForegroundWindow.restype = HWND
_GetForegroundWindow.errcheck = RaiseIfZero
return _GetForegroundWindow()
# BOOL IsWindow(
# HWND hWnd
# );
def IsWindow(hWnd):
_IsWindow = windll.user32.IsWindow
_IsWindow.argtypes = [HWND]
_IsWindow.restype = bool
return _IsWindow(hWnd)
# BOOL IsWindowVisible(
# HWND hWnd
# );
def IsWindowVisible(hWnd):
_IsWindowVisible = windll.user32.IsWindowVisible
_IsWindowVisible.argtypes = [HWND]
_IsWindowVisible.restype = bool
return _IsWindowVisible(hWnd)
# BOOL IsWindowEnabled(
# HWND hWnd
# );
def IsWindowEnabled(hWnd):
_IsWindowEnabled = windll.user32.IsWindowEnabled
_IsWindowEnabled.argtypes = [HWND]
_IsWindowEnabled.restype = bool
return _IsWindowEnabled(hWnd)
# BOOL IsZoomed(
# HWND hWnd
# );
def IsZoomed(hWnd):
_IsZoomed = windll.user32.IsZoomed
_IsZoomed.argtypes = [HWND]
_IsZoomed.restype = bool
return _IsZoomed(hWnd)
# BOOL IsIconic(
# HWND hWnd
# );
def IsIconic(hWnd):
_IsIconic = windll.user32.IsIconic
_IsIconic.argtypes = [HWND]
_IsIconic.restype = bool
return _IsIconic(hWnd)
# BOOL IsChild(
# HWND hWnd
# );
def IsChild(hWnd):
_IsChild = windll.user32.IsChild
_IsChild.argtypes = [HWND]
_IsChild.restype = bool
return _IsChild(hWnd)
# HWND WindowFromPoint(
# POINT Point
# );
def WindowFromPoint(point):
_WindowFromPoint = windll.user32.WindowFromPoint
_WindowFromPoint.argtypes = [POINT]
_WindowFromPoint.restype = HWND
_WindowFromPoint.errcheck = RaiseIfZero
if isinstance(point, tuple):
point = POINT(*point)
return _WindowFromPoint(point)
# HWND ChildWindowFromPoint(
# HWND hWndParent,
# POINT Point
# );
def ChildWindowFromPoint(hWndParent, point):
_ChildWindowFromPoint = windll.user32.ChildWindowFromPoint
_ChildWindowFromPoint.argtypes = [HWND, POINT]
_ChildWindowFromPoint.restype = HWND
_ChildWindowFromPoint.errcheck = RaiseIfZero
if isinstance(point, tuple):
point = POINT(*point)
return _ChildWindowFromPoint(hWndParent, point)
#HWND RealChildWindowFromPoint(
# HWND hwndParent,
# POINT ptParentClientCoords
#);
def RealChildWindowFromPoint(hWndParent, ptParentClientCoords):
_RealChildWindowFromPoint = windll.user32.RealChildWindowFromPoint
_RealChildWindowFromPoint.argtypes = [HWND, POINT]
_RealChildWindowFromPoint.restype = HWND
_RealChildWindowFromPoint.errcheck = RaiseIfZero
if isinstance(ptParentClientCoords, tuple):
ptParentClientCoords = POINT(*ptParentClientCoords)
return _RealChildWindowFromPoint(hWndParent, ptParentClientCoords)
# BOOL ScreenToClient(
# __in HWND hWnd,
# LPPOINT lpPoint
# );
def ScreenToClient(hWnd, lpPoint):
_ScreenToClient = windll.user32.ScreenToClient
_ScreenToClient.argtypes = [HWND, LPPOINT]
_ScreenToClient.restype = bool
_ScreenToClient.errcheck = RaiseIfZero
if isinstance(lpPoint, tuple):
lpPoint = POINT(*lpPoint)
else:
lpPoint = POINT(lpPoint.x, lpPoint.y)
_ScreenToClient(hWnd, byref(lpPoint))
return Point(lpPoint.x, lpPoint.y)
# BOOL ClientToScreen(
# HWND hWnd,
# LPPOINT lpPoint
# );
def ClientToScreen(hWnd, lpPoint):
_ClientToScreen = windll.user32.ClientToScreen
_ClientToScreen.argtypes = [HWND, LPPOINT]
_ClientToScreen.restype = bool
_ClientToScreen.errcheck = RaiseIfZero
if isinstance(lpPoint, tuple):
lpPoint = POINT(*lpPoint)
else:
lpPoint = POINT(lpPoint.x, lpPoint.y)
_ClientToScreen(hWnd, byref(lpPoint))
return Point(lpPoint.x, lpPoint.y)
# int MapWindowPoints(
# __in HWND hWndFrom,
# __in HWND hWndTo,
# __inout LPPOINT lpPoints,
# __in UINT cPoints
# );
def MapWindowPoints(hWndFrom, hWndTo, lpPoints):
_MapWindowPoints = windll.user32.MapWindowPoints
_MapWindowPoints.argtypes = [HWND, HWND, LPPOINT, UINT]
_MapWindowPoints.restype = ctypes.c_int
cPoints = len(lpPoints)
lpPoints = (POINT * cPoints)(* lpPoints)
SetLastError(ERROR_SUCCESS)
number = _MapWindowPoints(hWndFrom, hWndTo, byref(lpPoints), cPoints)
if number == 0:
errcode = GetLastError()
if errcode != ERROR_SUCCESS:
raise ctypes.WinError(errcode)
x_delta = number & 0xFFFF
y_delta = (number >> 16) & 0xFFFF
return x_delta, y_delta, [ (Point.x, Point.y) for Point in lpPoints ]
#BOOL SetForegroundWindow(
# HWND hWnd
#);
def SetForegroundWindow(hWnd):
_SetForegroundWindow = windll.user32.SetForegroundWindow
_SetForegroundWindow.argtypes = [HWND]
_SetForegroundWindow.restype = bool
_SetForegroundWindow.errcheck = RaiseIfZero
return _SetForegroundWindow(hWnd)
# BOOL GetWindowPlacement(
# HWND hWnd,
# WINDOWPLACEMENT *lpwndpl
# );
def GetWindowPlacement(hWnd):
_GetWindowPlacement = windll.user32.GetWindowPlacement
_GetWindowPlacement.argtypes = [HWND, PWINDOWPLACEMENT]
_GetWindowPlacement.restype = bool
_GetWindowPlacement.errcheck = RaiseIfZero
lpwndpl = WINDOWPLACEMENT()
lpwndpl.length = sizeof(lpwndpl)
_GetWindowPlacement(hWnd, byref(lpwndpl))
return WindowPlacement(lpwndpl)
# BOOL SetWindowPlacement(
# HWND hWnd,
# WINDOWPLACEMENT *lpwndpl
# );
def SetWindowPlacement(hWnd, lpwndpl):
_SetWindowPlacement = windll.user32.SetWindowPlacement
_SetWindowPlacement.argtypes = [HWND, PWINDOWPLACEMENT]
_SetWindowPlacement.restype = bool
_SetWindowPlacement.errcheck = RaiseIfZero
if isinstance(lpwndpl, WINDOWPLACEMENT):
lpwndpl.length = sizeof(lpwndpl)
_SetWindowPlacement(hWnd, byref(lpwndpl))
# BOOL WINAPI GetWindowRect(
# __in HWND hWnd,
# __out LPRECT lpRect
# );
def GetWindowRect(hWnd):
_GetWindowRect = windll.user32.GetWindowRect
_GetWindowRect.argtypes = [HWND, LPRECT]
_GetWindowRect.restype = bool
_GetWindowRect.errcheck = RaiseIfZero
lpRect = RECT()
_GetWindowRect(hWnd, byref(lpRect))
return Rect(lpRect.left, lpRect.top, lpRect.right, lpRect.bottom)
# BOOL WINAPI GetClientRect(
# __in HWND hWnd,
# __out LPRECT lpRect
# );
def GetClientRect(hWnd):
_GetClientRect = windll.user32.GetClientRect
_GetClientRect.argtypes = [HWND, LPRECT]
_GetClientRect.restype = bool
_GetClientRect.errcheck = RaiseIfZero
lpRect = RECT()
_GetClientRect(hWnd, byref(lpRect))
return Rect(lpRect.left, lpRect.top, lpRect.right, lpRect.bottom)
#BOOL MoveWindow(
# HWND hWnd,
# int X,
# int Y,
# int nWidth,
# int nHeight,
# BOOL bRepaint
#);
def MoveWindow(hWnd, X, Y, nWidth, nHeight, bRepaint = True):
_MoveWindow = windll.user32.MoveWindow
_MoveWindow.argtypes = [HWND, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, BOOL]
_MoveWindow.restype = bool
_MoveWindow.errcheck = RaiseIfZero
_MoveWindow(hWnd, X, Y, nWidth, nHeight, bool(bRepaint))
# BOOL GetGUIThreadInfo(
# DWORD idThread,
# LPGUITHREADINFO lpgui
# );
def GetGUIThreadInfo(idThread):
_GetGUIThreadInfo = windll.user32.GetGUIThreadInfo
_GetGUIThreadInfo.argtypes = [DWORD, LPGUITHREADINFO]
_GetGUIThreadInfo.restype = bool
_GetGUIThreadInfo.errcheck = RaiseIfZero
gui = GUITHREADINFO()
_GetGUIThreadInfo(idThread, byref(gui))
return gui
# BOOL CALLBACK EnumWndProc(
# HWND hwnd,
# LPARAM lParam
# );
class __EnumWndProc (__WindowEnumerator):
pass
# BOOL EnumWindows(
# WNDENUMPROC lpEnumFunc,
# LPARAM lParam
# );
def EnumWindows():
_EnumWindows = windll.user32.EnumWindows
_EnumWindows.argtypes = [WNDENUMPROC, LPARAM]
_EnumWindows.restype = bool
EnumFunc = __EnumWndProc()
lpEnumFunc = WNDENUMPROC(EnumFunc)
if not _EnumWindows(lpEnumFunc, NULL):
errcode = GetLastError()
if errcode not in (ERROR_NO_MORE_FILES, ERROR_SUCCESS):
raise ctypes.WinError(errcode)
return EnumFunc.hwnd
# BOOL CALLBACK EnumThreadWndProc(
# HWND hwnd,
# LPARAM lParam
# );
class __EnumThreadWndProc (__WindowEnumerator):
pass
# BOOL EnumThreadWindows(
# DWORD dwThreadId,
# WNDENUMPROC lpfn,
# LPARAM lParam
# );
def EnumThreadWindows(dwThreadId):
_EnumThreadWindows = windll.user32.EnumThreadWindows
_EnumThreadWindows.argtypes = [DWORD, WNDENUMPROC, LPARAM]
_EnumThreadWindows.restype = bool
fn = __EnumThreadWndProc()
lpfn = WNDENUMPROC(fn)
if not _EnumThreadWindows(dwThreadId, lpfn, NULL):
errcode = GetLastError()
if errcode not in (ERROR_NO_MORE_FILES, ERROR_SUCCESS):
raise ctypes.WinError(errcode)
return fn.hwnd
# BOOL CALLBACK EnumChildProc(
# HWND hwnd,
# LPARAM lParam
# );
class __EnumChildProc (__WindowEnumerator):
pass
# BOOL EnumChildWindows(
# HWND hWndParent,
# WNDENUMPROC lpEnumFunc,
# LPARAM lParam
# );
def EnumChildWindows(hWndParent = NULL):
_EnumChildWindows = windll.user32.EnumChildWindows
_EnumChildWindows.argtypes = [HWND, WNDENUMPROC, LPARAM]
_EnumChildWindows.restype = bool
EnumFunc = __EnumChildProc()
lpEnumFunc = WNDENUMPROC(EnumFunc)
SetLastError(ERROR_SUCCESS)
_EnumChildWindows(hWndParent, lpEnumFunc, NULL)
errcode = GetLastError()
if errcode != ERROR_SUCCESS and errcode not in (ERROR_NO_MORE_FILES, ERROR_SUCCESS):
raise ctypes.WinError(errcode)
return EnumFunc.hwnd
# LRESULT SendMessage(
# HWND hWnd,
# UINT Msg,
# WPARAM wParam,
# LPARAM lParam
# );
def SendMessageA(hWnd, Msg, wParam = 0, lParam = 0):
_SendMessageA = windll.user32.SendMessageA
_SendMessageA.argtypes = [HWND, UINT, WPARAM, LPARAM]
_SendMessageA.restype = LRESULT
wParam = MAKE_WPARAM(wParam)
lParam = MAKE_LPARAM(lParam)
return _SendMessageA(hWnd, Msg, wParam, lParam)
def SendMessageW(hWnd, Msg, wParam = 0, lParam = 0):
_SendMessageW = windll.user32.SendMessageW
_SendMessageW.argtypes = [HWND, UINT, WPARAM, LPARAM]
_SendMessageW.restype = LRESULT
wParam = MAKE_WPARAM(wParam)
lParam = MAKE_LPARAM(lParam)
return _SendMessageW(hWnd, Msg, wParam, lParam)
SendMessage = GuessStringType(SendMessageA, SendMessageW)
# BOOL PostMessage(
# HWND hWnd,
# UINT Msg,
# WPARAM wParam,
# LPARAM lParam
# );
def PostMessageA(hWnd, Msg, wParam = 0, lParam = 0):
_PostMessageA = windll.user32.PostMessageA
_PostMessageA.argtypes = [HWND, UINT, WPARAM, LPARAM]
_PostMessageA.restype = bool
_PostMessageA.errcheck = RaiseIfZero
wParam = MAKE_WPARAM(wParam)
lParam = MAKE_LPARAM(lParam)
_PostMessageA(hWnd, Msg, wParam, lParam)
def PostMessageW(hWnd, Msg, wParam = 0, lParam = 0):
_PostMessageW = windll.user32.PostMessageW
_PostMessageW.argtypes = [HWND, UINT, WPARAM, LPARAM]
_PostMessageW.restype = bool
_PostMessageW.errcheck = RaiseIfZero
wParam = MAKE_WPARAM(wParam)
lParam = MAKE_LPARAM(lParam)
_PostMessageW(hWnd, Msg, wParam, lParam)
PostMessage = GuessStringType(PostMessageA, PostMessageW)
# BOOL PostThreadMessage(
# DWORD idThread,
# UINT Msg,
# WPARAM wParam,
# LPARAM lParam
# );
def PostThreadMessageA(idThread, Msg, wParam = 0, lParam = 0):
_PostThreadMessageA = windll.user32.PostThreadMessageA
_PostThreadMessageA.argtypes = [DWORD, UINT, WPARAM, LPARAM]
_PostThreadMessageA.restype = bool
_PostThreadMessageA.errcheck = RaiseIfZero
wParam = MAKE_WPARAM(wParam)
lParam = MAKE_LPARAM(lParam)
_PostThreadMessageA(idThread, Msg, wParam, lParam)
def PostThreadMessageW(idThread, Msg, wParam = 0, lParam = 0):
_PostThreadMessageW = windll.user32.PostThreadMessageW
_PostThreadMessageW.argtypes = [DWORD, UINT, WPARAM, LPARAM]
_PostThreadMessageW.restype = bool
_PostThreadMessageW.errcheck = RaiseIfZero
wParam = MAKE_WPARAM(wParam)
lParam = MAKE_LPARAM(lParam)
_PostThreadMessageW(idThread, Msg, wParam, lParam)
PostThreadMessage = GuessStringType(PostThreadMessageA, PostThreadMessageW)
# LRESULT c(
# HWND hWnd,
# UINT Msg,
# WPARAM wParam,
# LPARAM lParam,
# UINT fuFlags,
# UINT uTimeout,
# PDWORD_PTR lpdwResult
# );
def SendMessageTimeoutA(hWnd, Msg, wParam = 0, lParam = 0, fuFlags = 0, uTimeout = 0):
_SendMessageTimeoutA = windll.user32.SendMessageTimeoutA
_SendMessageTimeoutA.argtypes = [HWND, UINT, WPARAM, LPARAM, UINT, UINT, PDWORD_PTR]
_SendMessageTimeoutA.restype = LRESULT
_SendMessageTimeoutA.errcheck = RaiseIfZero
wParam = MAKE_WPARAM(wParam)
lParam = MAKE_LPARAM(lParam)
dwResult = DWORD(0)
_SendMessageTimeoutA(hWnd, Msg, wParam, lParam, fuFlags, uTimeout, byref(dwResult))
return dwResult.value
def SendMessageTimeoutW(hWnd, Msg, wParam = 0, lParam = 0):
_SendMessageTimeoutW = windll.user32.SendMessageTimeoutW
_SendMessageTimeoutW.argtypes = [HWND, UINT, WPARAM, LPARAM, UINT, UINT, PDWORD_PTR]
_SendMessageTimeoutW.restype = LRESULT
_SendMessageTimeoutW.errcheck = RaiseIfZero
wParam = MAKE_WPARAM(wParam)
lParam = MAKE_LPARAM(lParam)
dwResult = DWORD(0)
_SendMessageTimeoutW(hWnd, Msg, wParam, lParam, fuFlags, uTimeout, byref(dwResult))
return dwResult.value
SendMessageTimeout = GuessStringType(SendMessageTimeoutA, SendMessageTimeoutW)
# BOOL SendNotifyMessage(
# HWND hWnd,
# UINT Msg,
# WPARAM wParam,
# LPARAM lParam
# );
def SendNotifyMessageA(hWnd, Msg, wParam = 0, lParam = 0):
_SendNotifyMessageA = windll.user32.SendNotifyMessageA
_SendNotifyMessageA.argtypes = [HWND, UINT, WPARAM, LPARAM]
_SendNotifyMessageA.restype = bool
_SendNotifyMessageA.errcheck = RaiseIfZero
wParam = MAKE_WPARAM(wParam)
lParam = MAKE_LPARAM(lParam)
_SendNotifyMessageA(hWnd, Msg, wParam, lParam)
def SendNotifyMessageW(hWnd, Msg, wParam = 0, lParam = 0):
_SendNotifyMessageW = windll.user32.SendNotifyMessageW
_SendNotifyMessageW.argtypes = [HWND, UINT, WPARAM, LPARAM]
_SendNotifyMessageW.restype = bool
_SendNotifyMessageW.errcheck = RaiseIfZero
wParam = MAKE_WPARAM(wParam)
lParam = MAKE_LPARAM(lParam)
_SendNotifyMessageW(hWnd, Msg, wParam, lParam)
SendNotifyMessage = GuessStringType(SendNotifyMessageA, SendNotifyMessageW)
# LRESULT SendDlgItemMessage(
# HWND hDlg,
# int nIDDlgItem,
# UINT Msg,
# WPARAM wParam,
# LPARAM lParam
# );
def SendDlgItemMessageA(hDlg, nIDDlgItem, Msg, wParam = 0, lParam = 0):
_SendDlgItemMessageA = windll.user32.SendDlgItemMessageA
_SendDlgItemMessageA.argtypes = [HWND, ctypes.c_int, UINT, WPARAM, LPARAM]
_SendDlgItemMessageA.restype = LRESULT
wParam = MAKE_WPARAM(wParam)
lParam = MAKE_LPARAM(lParam)
return _SendDlgItemMessageA(hDlg, nIDDlgItem, Msg, wParam, lParam)
def SendDlgItemMessageW(hDlg, nIDDlgItem, Msg, wParam = 0, lParam = 0):
_SendDlgItemMessageW = windll.user32.SendDlgItemMessageW
_SendDlgItemMessageW.argtypes = [HWND, ctypes.c_int, UINT, WPARAM, LPARAM]
_SendDlgItemMessageW.restype = LRESULT
wParam = MAKE_WPARAM(wParam)
lParam = MAKE_LPARAM(lParam)
return _SendDlgItemMessageW(hDlg, nIDDlgItem, Msg, wParam, lParam)
SendDlgItemMessage = GuessStringType(SendDlgItemMessageA, SendDlgItemMessageW)
# DWORD WINAPI WaitForInputIdle(
# _In_ HANDLE hProcess,
# _In_ DWORD dwMilliseconds
# );
def WaitForInputIdle(hProcess, dwMilliseconds = INFINITE):
_WaitForInputIdle = windll.user32.WaitForInputIdle
_WaitForInputIdle.argtypes = [HANDLE, DWORD]
_WaitForInputIdle.restype = DWORD
r = _WaitForInputIdle(hProcess, dwMilliseconds)
if r == WAIT_FAILED:
raise ctypes.WinError()
return r
# UINT RegisterWindowMessage(
# LPCTSTR lpString
# );
def RegisterWindowMessageA(lpString):
_RegisterWindowMessageA = windll.user32.RegisterWindowMessageA
_RegisterWindowMessageA.argtypes = [LPSTR]
_RegisterWindowMessageA.restype = UINT
_RegisterWindowMessageA.errcheck = RaiseIfZero
return _RegisterWindowMessageA(lpString)
def RegisterWindowMessageW(lpString):
_RegisterWindowMessageW = windll.user32.RegisterWindowMessageW
_RegisterWindowMessageW.argtypes = [LPWSTR]
_RegisterWindowMessageW.restype = UINT
_RegisterWindowMessageW.errcheck = RaiseIfZero
return _RegisterWindowMessageW(lpString)
RegisterWindowMessage = GuessStringType(RegisterWindowMessageA, RegisterWindowMessageW)
# UINT RegisterClipboardFormat(
# LPCTSTR lpString
# );
def RegisterClipboardFormatA(lpString):
_RegisterClipboardFormatA = windll.user32.RegisterClipboardFormatA
_RegisterClipboardFormatA.argtypes = [LPSTR]
_RegisterClipboardFormatA.restype = UINT
_RegisterClipboardFormatA.errcheck = RaiseIfZero
return _RegisterClipboardFormatA(lpString)
def RegisterClipboardFormatW(lpString):
_RegisterClipboardFormatW = windll.user32.RegisterClipboardFormatW
_RegisterClipboardFormatW.argtypes = [LPWSTR]
_RegisterClipboardFormatW.restype = UINT
_RegisterClipboardFormatW.errcheck = RaiseIfZero
return _RegisterClipboardFormatW(lpString)
RegisterClipboardFormat = GuessStringType(RegisterClipboardFormatA, RegisterClipboardFormatW)
# HANDLE WINAPI GetProp(
# __in HWND hWnd,
# __in LPCTSTR lpString
# );
def GetPropA(hWnd, lpString):
_GetPropA = windll.user32.GetPropA
_GetPropA.argtypes = [HWND, LPSTR]
_GetPropA.restype = HANDLE
return _GetPropA(hWnd, lpString)
def GetPropW(hWnd, lpString):
_GetPropW = windll.user32.GetPropW
_GetPropW.argtypes = [HWND, LPWSTR]
_GetPropW.restype = HANDLE
return _GetPropW(hWnd, lpString)
GetProp = GuessStringType(GetPropA, GetPropW)
# BOOL WINAPI SetProp(
# __in HWND hWnd,
# __in LPCTSTR lpString,
# __in_opt HANDLE hData
# );
def SetPropA(hWnd, lpString, hData):
_SetPropA = windll.user32.SetPropA
_SetPropA.argtypes = [HWND, LPSTR, HANDLE]
_SetPropA.restype = BOOL
_SetPropA.errcheck = RaiseIfZero
_SetPropA(hWnd, lpString, hData)
def SetPropW(hWnd, lpString, hData):
_SetPropW = windll.user32.SetPropW
_SetPropW.argtypes = [HWND, LPWSTR, HANDLE]
_SetPropW.restype = BOOL
_SetPropW.errcheck = RaiseIfZero
_SetPropW(hWnd, lpString, hData)
SetProp = GuessStringType(SetPropA, SetPropW)
# HANDLE WINAPI RemoveProp(
# __in HWND hWnd,
# __in LPCTSTR lpString
# );
def RemovePropA(hWnd, lpString):
_RemovePropA = windll.user32.RemovePropA
_RemovePropA.argtypes = [HWND, LPSTR]
_RemovePropA.restype = HANDLE
return _RemovePropA(hWnd, lpString)
def RemovePropW(hWnd, lpString):
_RemovePropW = windll.user32.RemovePropW
_RemovePropW.argtypes = [HWND, LPWSTR]
_RemovePropW.restype = HANDLE
return _RemovePropW(hWnd, lpString)
RemoveProp = GuessStringType(RemovePropA, RemovePropW)
#==============================================================================
# This calculates the list of exported symbols.
_all = set(vars().keys()).difference(_all)
__all__ = [_x for _x in _all if not _x.startswith('_')]
__all__.sort()
#==============================================================================
| 57,177 | Python | 32.08912 | 101 | 0.606992 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/win32/context_amd64.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
CONTEXT structure for amd64.
"""
__revision__ = "$Id$"
from winappdbg.win32.defines import *
from winappdbg.win32.version import ARCH_AMD64
from winappdbg.win32 import context_i386
#==============================================================================
# This is used later on to calculate the list of exported symbols.
_all = None
_all = set(vars().keys())
#==============================================================================
#--- CONTEXT structures and constants -----------------------------------------
# The following values specify the type of access in the first parameter
# of the exception record when the exception code specifies an access
# violation.
EXCEPTION_READ_FAULT = 0 # exception caused by a read
EXCEPTION_WRITE_FAULT = 1 # exception caused by a write
EXCEPTION_EXECUTE_FAULT = 8 # exception caused by an instruction fetch
CONTEXT_AMD64 = 0x00100000
CONTEXT_CONTROL = (CONTEXT_AMD64 | long(0x1))
CONTEXT_INTEGER = (CONTEXT_AMD64 | long(0x2))
CONTEXT_SEGMENTS = (CONTEXT_AMD64 | long(0x4))
CONTEXT_FLOATING_POINT = (CONTEXT_AMD64 | long(0x8))
CONTEXT_DEBUG_REGISTERS = (CONTEXT_AMD64 | long(0x10))
CONTEXT_MMX_REGISTERS = CONTEXT_FLOATING_POINT
CONTEXT_FULL = (CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_FLOATING_POINT)
CONTEXT_ALL = (CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS | \
CONTEXT_FLOATING_POINT | CONTEXT_DEBUG_REGISTERS)
CONTEXT_EXCEPTION_ACTIVE = 0x8000000
CONTEXT_SERVICE_ACTIVE = 0x10000000
CONTEXT_EXCEPTION_REQUEST = 0x40000000
CONTEXT_EXCEPTION_REPORTING = 0x80000000
INITIAL_MXCSR = 0x1f80 # initial MXCSR value
INITIAL_FPCSR = 0x027f # initial FPCSR value
# typedef struct _XMM_SAVE_AREA32 {
# WORD ControlWord;
# WORD StatusWord;
# BYTE TagWord;
# BYTE Reserved1;
# WORD ErrorOpcode;
# DWORD ErrorOffset;
# WORD ErrorSelector;
# WORD Reserved2;
# DWORD DataOffset;
# WORD DataSelector;
# WORD Reserved3;
# DWORD MxCsr;
# DWORD MxCsr_Mask;
# M128A FloatRegisters[8];
# M128A XmmRegisters[16];
# BYTE Reserved4[96];
# } XMM_SAVE_AREA32, *PXMM_SAVE_AREA32;
class XMM_SAVE_AREA32(Structure):
_pack_ = 1
_fields_ = [
('ControlWord', WORD),
('StatusWord', WORD),
('TagWord', BYTE),
('Reserved1', BYTE),
('ErrorOpcode', WORD),
('ErrorOffset', DWORD),
('ErrorSelector', WORD),
('Reserved2', WORD),
('DataOffset', DWORD),
('DataSelector', WORD),
('Reserved3', WORD),
('MxCsr', DWORD),
('MxCsr_Mask', DWORD),
('FloatRegisters', M128A * 8),
('XmmRegisters', M128A * 16),
('Reserved4', BYTE * 96),
]
def from_dict(self):
raise NotImplementedError()
def to_dict(self):
d = dict()
for name, type in self._fields_:
if name in ('FloatRegisters', 'XmmRegisters'):
d[name] = tuple([ (x.LowPart + (x.HighPart << 64)) for x in getattr(self, name) ])
elif name == 'Reserved4':
d[name] = tuple([ chr(x) for x in getattr(self, name) ])
else:
d[name] = getattr(self, name)
return d
LEGACY_SAVE_AREA_LENGTH = sizeof(XMM_SAVE_AREA32)
PXMM_SAVE_AREA32 = ctypes.POINTER(XMM_SAVE_AREA32)
LPXMM_SAVE_AREA32 = PXMM_SAVE_AREA32
# //
# // 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 flags field within this record controls 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 is modified.
# //
# // If the context record is used as an output parameter to capture the
# // context of a thread, then only those portions of the thread's context
# // corresponding to set flags will be returned.
# //
# // CONTEXT_CONTROL specifies SegSs, Rsp, SegCs, Rip, and EFlags.
# //
# // CONTEXT_INTEGER specifies Rax, Rcx, Rdx, Rbx, Rbp, Rsi, Rdi, and R8-R15.
# //
# // CONTEXT_SEGMENTS specifies SegDs, SegEs, SegFs, and SegGs.
# //
# // CONTEXT_DEBUG_REGISTERS specifies Dr0-Dr3 and Dr6-Dr7.
# //
# // CONTEXT_MMX_REGISTERS specifies the floating point and extended registers
# // Mm0/St0-Mm7/St7 and Xmm0-Xmm15).
# //
#
# typedef struct DECLSPEC_ALIGN(16) _CONTEXT {
#
# //
# // Register parameter home addresses.
# //
# // N.B. These fields are for convience - they could be used to extend the
# // context record in the future.
# //
#
# DWORD64 P1Home;
# DWORD64 P2Home;
# DWORD64 P3Home;
# DWORD64 P4Home;
# DWORD64 P5Home;
# DWORD64 P6Home;
#
# //
# // Control flags.
# //
#
# DWORD ContextFlags;
# DWORD MxCsr;
#
# //
# // Segment Registers and processor flags.
# //
#
# WORD SegCs;
# WORD SegDs;
# WORD SegEs;
# WORD SegFs;
# WORD SegGs;
# WORD SegSs;
# DWORD EFlags;
#
# //
# // Debug registers
# //
#
# DWORD64 Dr0;
# DWORD64 Dr1;
# DWORD64 Dr2;
# DWORD64 Dr3;
# DWORD64 Dr6;
# DWORD64 Dr7;
#
# //
# // Integer registers.
# //
#
# DWORD64 Rax;
# DWORD64 Rcx;
# DWORD64 Rdx;
# DWORD64 Rbx;
# DWORD64 Rsp;
# DWORD64 Rbp;
# DWORD64 Rsi;
# DWORD64 Rdi;
# DWORD64 R8;
# DWORD64 R9;
# DWORD64 R10;
# DWORD64 R11;
# DWORD64 R12;
# DWORD64 R13;
# DWORD64 R14;
# DWORD64 R15;
#
# //
# // Program counter.
# //
#
# DWORD64 Rip;
#
# //
# // Floating point state.
# //
#
# union {
# XMM_SAVE_AREA32 FltSave;
# struct {
# M128A Header[2];
# M128A Legacy[8];
# M128A Xmm0;
# M128A Xmm1;
# M128A Xmm2;
# M128A Xmm3;
# M128A Xmm4;
# M128A Xmm5;
# M128A Xmm6;
# M128A Xmm7;
# M128A Xmm8;
# M128A Xmm9;
# M128A Xmm10;
# M128A Xmm11;
# M128A Xmm12;
# M128A Xmm13;
# M128A Xmm14;
# M128A Xmm15;
# };
# };
#
# //
# // Vector registers.
# //
#
# M128A VectorRegister[26];
# DWORD64 VectorControl;
#
# //
# // Special debug control registers.
# //
#
# DWORD64 DebugControl;
# DWORD64 LastBranchToRip;
# DWORD64 LastBranchFromRip;
# DWORD64 LastExceptionToRip;
# DWORD64 LastExceptionFromRip;
# } CONTEXT, *PCONTEXT;
class _CONTEXT_FLTSAVE_STRUCT(Structure):
_fields_ = [
('Header', M128A * 2),
('Legacy', M128A * 8),
('Xmm0', M128A),
('Xmm1', M128A),
('Xmm2', M128A),
('Xmm3', M128A),
('Xmm4', M128A),
('Xmm5', M128A),
('Xmm6', M128A),
('Xmm7', M128A),
('Xmm8', M128A),
('Xmm9', M128A),
('Xmm10', M128A),
('Xmm11', M128A),
('Xmm12', M128A),
('Xmm13', M128A),
('Xmm14', M128A),
('Xmm15', M128A),
]
def from_dict(self):
raise NotImplementedError()
def to_dict(self):
d = dict()
for name, type in self._fields_:
if name in ('Header', 'Legacy'):
d[name] = tuple([ (x.Low + (x.High << 64)) for x in getattr(self, name) ])
else:
x = getattr(self, name)
d[name] = x.Low + (x.High << 64)
return d
class _CONTEXT_FLTSAVE_UNION(Union):
_fields_ = [
('flt', XMM_SAVE_AREA32),
('xmm', _CONTEXT_FLTSAVE_STRUCT),
]
def from_dict(self):
raise NotImplementedError()
def to_dict(self):
d = dict()
d['flt'] = self.flt.to_dict()
d['xmm'] = self.xmm.to_dict()
return d
class CONTEXT(Structure):
arch = ARCH_AMD64
_pack_ = 16
_fields_ = [
# Register parameter home addresses.
('P1Home', DWORD64),
('P2Home', DWORD64),
('P3Home', DWORD64),
('P4Home', DWORD64),
('P5Home', DWORD64),
('P6Home', DWORD64),
# Control flags.
('ContextFlags', DWORD),
('MxCsr', DWORD),
# Segment Registers and processor flags.
('SegCs', WORD),
('SegDs', WORD),
('SegEs', WORD),
('SegFs', WORD),
('SegGs', WORD),
('SegSs', WORD),
('EFlags', DWORD),
# Debug registers.
('Dr0', DWORD64),
('Dr1', DWORD64),
('Dr2', DWORD64),
('Dr3', DWORD64),
('Dr6', DWORD64),
('Dr7', DWORD64),
# Integer registers.
('Rax', DWORD64),
('Rcx', DWORD64),
('Rdx', DWORD64),
('Rbx', DWORD64),
('Rsp', DWORD64),
('Rbp', DWORD64),
('Rsi', DWORD64),
('Rdi', DWORD64),
('R8', DWORD64),
('R9', DWORD64),
('R10', DWORD64),
('R11', DWORD64),
('R12', DWORD64),
('R13', DWORD64),
('R14', DWORD64),
('R15', DWORD64),
# Program counter.
('Rip', DWORD64),
# Floating point state.
('FltSave', _CONTEXT_FLTSAVE_UNION),
# Vector registers.
('VectorRegister', M128A * 26),
('VectorControl', DWORD64),
# Special debug control registers.
('DebugControl', DWORD64),
('LastBranchToRip', DWORD64),
('LastBranchFromRip', DWORD64),
('LastExceptionToRip', DWORD64),
('LastExceptionFromRip', DWORD64),
]
_others = ('P1Home', 'P2Home', 'P3Home', 'P4Home', 'P5Home', 'P6Home', \
'MxCsr', 'VectorRegister', 'VectorControl')
_control = ('SegSs', 'Rsp', 'SegCs', 'Rip', 'EFlags')
_integer = ('Rax', 'Rcx', 'Rdx', 'Rbx', 'Rsp', 'Rbp', 'Rsi', 'Rdi', \
'R8', 'R9', 'R10', 'R11', 'R12', 'R13', 'R14', 'R15')
_segments = ('SegDs', 'SegEs', 'SegFs', 'SegGs')
_debug = ('Dr0', 'Dr1', 'Dr2', 'Dr3', 'Dr6', 'Dr7', \
'DebugControl', 'LastBranchToRip', 'LastBranchFromRip', \
'LastExceptionToRip', 'LastExceptionFromRip')
_mmx = ('Xmm0', 'Xmm1', 'Xmm2', 'Xmm3', 'Xmm4', 'Xmm5', 'Xmm6', 'Xmm7', \
'Xmm8', 'Xmm9', 'Xmm10', 'Xmm11', 'Xmm12', 'Xmm13', 'Xmm14', 'Xmm15')
# XXX TODO
# Convert VectorRegister and Xmm0-Xmm15 to pure Python types!
@classmethod
def from_dict(cls, ctx):
'Instance a new structure from a Python native type.'
ctx = Context(ctx)
s = cls()
ContextFlags = ctx['ContextFlags']
s.ContextFlags = ContextFlags
for key in cls._others:
if key != 'VectorRegister':
setattr(s, key, ctx[key])
else:
w = ctx[key]
v = (M128A * len(w))()
i = 0
for x in w:
y = M128A()
y.High = x >> 64
y.Low = x - (x >> 64)
v[i] = y
i += 1
setattr(s, key, v)
if (ContextFlags & CONTEXT_CONTROL) == CONTEXT_CONTROL:
for key in cls._control:
setattr(s, key, ctx[key])
if (ContextFlags & CONTEXT_INTEGER) == CONTEXT_INTEGER:
for key in cls._integer:
setattr(s, key, ctx[key])
if (ContextFlags & CONTEXT_SEGMENTS) == CONTEXT_SEGMENTS:
for key in cls._segments:
setattr(s, key, ctx[key])
if (ContextFlags & CONTEXT_DEBUG_REGISTERS) == CONTEXT_DEBUG_REGISTERS:
for key in cls._debug:
setattr(s, key, ctx[key])
if (ContextFlags & CONTEXT_MMX_REGISTERS) == CONTEXT_MMX_REGISTERS:
xmm = s.FltSave.xmm
for key in cls._mmx:
y = M128A()
y.High = x >> 64
y.Low = x - (x >> 64)
setattr(xmm, key, y)
return s
def to_dict(self):
'Convert a structure into a Python dictionary.'
ctx = Context()
ContextFlags = self.ContextFlags
ctx['ContextFlags'] = ContextFlags
for key in self._others:
if key != 'VectorRegister':
ctx[key] = getattr(self, key)
else:
ctx[key] = tuple([ (x.Low + (x.High << 64)) for x in getattr(self, key) ])
if (ContextFlags & CONTEXT_CONTROL) == CONTEXT_CONTROL:
for key in self._control:
ctx[key] = getattr(self, key)
if (ContextFlags & CONTEXT_INTEGER) == CONTEXT_INTEGER:
for key in self._integer:
ctx[key] = getattr(self, key)
if (ContextFlags & CONTEXT_SEGMENTS) == CONTEXT_SEGMENTS:
for key in self._segments:
ctx[key] = getattr(self, key)
if (ContextFlags & CONTEXT_DEBUG_REGISTERS) == CONTEXT_DEBUG_REGISTERS:
for key in self._debug:
ctx[key] = getattr(self, key)
if (ContextFlags & CONTEXT_MMX_REGISTERS) == CONTEXT_MMX_REGISTERS:
xmm = self.FltSave.xmm.to_dict()
for key in self._mmx:
ctx[key] = xmm.get(key)
return ctx
PCONTEXT = ctypes.POINTER(CONTEXT)
LPCONTEXT = PCONTEXT
class Context(dict):
"""
Register context dictionary for the amd64 architecture.
"""
arch = CONTEXT.arch
def __get_pc(self):
return self['Rip']
def __set_pc(self, value):
self['Rip'] = value
pc = property(__get_pc, __set_pc)
def __get_sp(self):
return self['Rsp']
def __set_sp(self, value):
self['Rsp'] = value
sp = property(__get_sp, __set_sp)
def __get_fp(self):
return self['Rbp']
def __set_fp(self, value):
self['Rbp'] = value
fp = property(__get_fp, __set_fp)
#--- LDT_ENTRY structure ------------------------------------------------------
# typedef struct _LDT_ENTRY {
# WORD LimitLow;
# WORD BaseLow;
# union {
# struct {
# BYTE BaseMid;
# BYTE Flags1;
# BYTE Flags2;
# BYTE BaseHi;
# } Bytes;
# struct {
# DWORD BaseMid :8;
# DWORD Type :5;
# DWORD Dpl :2;
# DWORD Pres :1;
# DWORD LimitHi :4;
# DWORD Sys :1;
# DWORD Reserved_0 :1;
# DWORD Default_Big :1;
# DWORD Granularity :1;
# DWORD BaseHi :8;
# } Bits;
# } HighWord;
# } LDT_ENTRY,
# *PLDT_ENTRY;
class _LDT_ENTRY_BYTES_(Structure):
_pack_ = 1
_fields_ = [
('BaseMid', BYTE),
('Flags1', BYTE),
('Flags2', BYTE),
('BaseHi', BYTE),
]
class _LDT_ENTRY_BITS_(Structure):
_pack_ = 1
_fields_ = [
('BaseMid', DWORD, 8),
('Type', DWORD, 5),
('Dpl', DWORD, 2),
('Pres', DWORD, 1),
('LimitHi', DWORD, 4),
('Sys', DWORD, 1),
('Reserved_0', DWORD, 1),
('Default_Big', DWORD, 1),
('Granularity', DWORD, 1),
('BaseHi', DWORD, 8),
]
class _LDT_ENTRY_HIGHWORD_(Union):
_pack_ = 1
_fields_ = [
('Bytes', _LDT_ENTRY_BYTES_),
('Bits', _LDT_ENTRY_BITS_),
]
class LDT_ENTRY(Structure):
_pack_ = 1
_fields_ = [
('LimitLow', WORD),
('BaseLow', WORD),
('HighWord', _LDT_ENTRY_HIGHWORD_),
]
PLDT_ENTRY = POINTER(LDT_ENTRY)
LPLDT_ENTRY = PLDT_ENTRY
#--- WOW64 CONTEXT structure and constants ------------------------------------
# Value of SegCs in a Wow64 thread when running in 32 bits mode
WOW64_CS32 = 0x23
WOW64_CONTEXT_i386 = long(0x00010000)
WOW64_CONTEXT_i486 = long(0x00010000)
WOW64_CONTEXT_CONTROL = (WOW64_CONTEXT_i386 | long(0x00000001))
WOW64_CONTEXT_INTEGER = (WOW64_CONTEXT_i386 | long(0x00000002))
WOW64_CONTEXT_SEGMENTS = (WOW64_CONTEXT_i386 | long(0x00000004))
WOW64_CONTEXT_FLOATING_POINT = (WOW64_CONTEXT_i386 | long(0x00000008))
WOW64_CONTEXT_DEBUG_REGISTERS = (WOW64_CONTEXT_i386 | long(0x00000010))
WOW64_CONTEXT_EXTENDED_REGISTERS = (WOW64_CONTEXT_i386 | long(0x00000020))
WOW64_CONTEXT_FULL = (WOW64_CONTEXT_CONTROL | WOW64_CONTEXT_INTEGER | WOW64_CONTEXT_SEGMENTS)
WOW64_CONTEXT_ALL = (WOW64_CONTEXT_CONTROL | WOW64_CONTEXT_INTEGER | WOW64_CONTEXT_SEGMENTS | WOW64_CONTEXT_FLOATING_POINT | WOW64_CONTEXT_DEBUG_REGISTERS | WOW64_CONTEXT_EXTENDED_REGISTERS)
WOW64_SIZE_OF_80387_REGISTERS = 80
WOW64_MAXIMUM_SUPPORTED_EXTENSION = 512
class WOW64_FLOATING_SAVE_AREA (context_i386.FLOATING_SAVE_AREA):
pass
class WOW64_CONTEXT (context_i386.CONTEXT):
pass
class WOW64_LDT_ENTRY (context_i386.LDT_ENTRY):
pass
PWOW64_FLOATING_SAVE_AREA = POINTER(WOW64_FLOATING_SAVE_AREA)
PWOW64_CONTEXT = POINTER(WOW64_CONTEXT)
PWOW64_LDT_ENTRY = POINTER(WOW64_LDT_ENTRY)
###############################################################################
# BOOL WINAPI GetThreadSelectorEntry(
# __in HANDLE hThread,
# __in DWORD dwSelector,
# __out LPLDT_ENTRY lpSelectorEntry
# );
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
# BOOL WINAPI GetThreadContext(
# __in HANDLE hThread,
# __inout LPCONTEXT lpContext
# );
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_AMD64
Context = CONTEXT()
Context.ContextFlags = ContextFlags
_GetThreadContext(hThread, byref(Context))
if raw:
return Context
return Context.to_dict()
# BOOL WINAPI SetThreadContext(
# __in HANDLE hThread,
# __in const CONTEXT* lpContext
# );
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))
# BOOL Wow64GetThreadSelectorEntry(
# __in HANDLE hThread,
# __in DWORD dwSelector,
# __out PWOW64_LDT_ENTRY lpSelectorEntry
# );
def Wow64GetThreadSelectorEntry(hThread, dwSelector):
_Wow64GetThreadSelectorEntry = windll.kernel32.Wow64GetThreadSelectorEntry
_Wow64GetThreadSelectorEntry.argtypes = [HANDLE, DWORD, PWOW64_LDT_ENTRY]
_Wow64GetThreadSelectorEntry.restype = bool
_Wow64GetThreadSelectorEntry.errcheck = RaiseIfZero
lpSelectorEntry = WOW64_LDT_ENTRY()
_Wow64GetThreadSelectorEntry(hThread, dwSelector, byref(lpSelectorEntry))
return lpSelectorEntry
# DWORD WINAPI Wow64ResumeThread(
# __in HANDLE hThread
# );
def Wow64ResumeThread(hThread):
_Wow64ResumeThread = windll.kernel32.Wow64ResumeThread
_Wow64ResumeThread.argtypes = [HANDLE]
_Wow64ResumeThread.restype = DWORD
previousCount = _Wow64ResumeThread(hThread)
if previousCount == DWORD(-1).value:
raise ctypes.WinError()
return previousCount
# DWORD WINAPI Wow64SuspendThread(
# __in HANDLE hThread
# );
def Wow64SuspendThread(hThread):
_Wow64SuspendThread = windll.kernel32.Wow64SuspendThread
_Wow64SuspendThread.argtypes = [HANDLE]
_Wow64SuspendThread.restype = DWORD
previousCount = _Wow64SuspendThread(hThread)
if previousCount == DWORD(-1).value:
raise ctypes.WinError()
return previousCount
# XXX TODO Use this http://www.nynaeve.net/Code/GetThreadWow64Context.cpp
# Also see http://www.woodmann.com/forum/archive/index.php/t-11162.html
# BOOL WINAPI Wow64GetThreadContext(
# __in HANDLE hThread,
# __inout PWOW64_CONTEXT lpContext
# );
def Wow64GetThreadContext(hThread, ContextFlags = None):
_Wow64GetThreadContext = windll.kernel32.Wow64GetThreadContext
_Wow64GetThreadContext.argtypes = [HANDLE, PWOW64_CONTEXT]
_Wow64GetThreadContext.restype = bool
_Wow64GetThreadContext.errcheck = RaiseIfZero
# XXX doesn't exist in XP 64 bits
Context = WOW64_CONTEXT()
if ContextFlags is None:
Context.ContextFlags = WOW64_CONTEXT_ALL | WOW64_CONTEXT_i386
else:
Context.ContextFlags = ContextFlags
_Wow64GetThreadContext(hThread, byref(Context))
return Context.to_dict()
# BOOL WINAPI Wow64SetThreadContext(
# __in HANDLE hThread,
# __in const WOW64_CONTEXT *lpContext
# );
def Wow64SetThreadContext(hThread, lpContext):
_Wow64SetThreadContext = windll.kernel32.Wow64SetThreadContext
_Wow64SetThreadContext.argtypes = [HANDLE, PWOW64_CONTEXT]
_Wow64SetThreadContext.restype = bool
_Wow64SetThreadContext.errcheck = RaiseIfZero
# XXX doesn't exist in XP 64 bits
if isinstance(lpContext, dict):
lpContext = WOW64_CONTEXT.from_dict(lpContext)
_Wow64SetThreadContext(hThread, byref(lpContext))
#==============================================================================
# This calculates the list of exported symbols.
_all = set(vars().keys()).difference(_all)
__all__ = [_x for _x in _all if not _x.startswith('_')]
__all__.sort()
#==============================================================================
| 25,137 | Python | 31.946265 | 208 | 0.550066 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/win32/advapi32.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Wrapper for advapi32.dll in ctypes.
"""
__revision__ = "$Id$"
from winappdbg.win32.defines import *
from winappdbg.win32.kernel32 import *
# XXX TODO
# + add transacted registry operations
#==============================================================================
# This is used later on to calculate the list of exported symbols.
_all = None
_all = set(vars().keys())
#==============================================================================
#--- Constants ----------------------------------------------------------------
# Privilege constants
SE_ASSIGNPRIMARYTOKEN_NAME = "SeAssignPrimaryTokenPrivilege"
SE_AUDIT_NAME = "SeAuditPrivilege"
SE_BACKUP_NAME = "SeBackupPrivilege"
SE_CHANGE_NOTIFY_NAME = "SeChangeNotifyPrivilege"
SE_CREATE_GLOBAL_NAME = "SeCreateGlobalPrivilege"
SE_CREATE_PAGEFILE_NAME = "SeCreatePagefilePrivilege"
SE_CREATE_PERMANENT_NAME = "SeCreatePermanentPrivilege"
SE_CREATE_SYMBOLIC_LINK_NAME = "SeCreateSymbolicLinkPrivilege"
SE_CREATE_TOKEN_NAME = "SeCreateTokenPrivilege"
SE_DEBUG_NAME = "SeDebugPrivilege"
SE_ENABLE_DELEGATION_NAME = "SeEnableDelegationPrivilege"
SE_IMPERSONATE_NAME = "SeImpersonatePrivilege"
SE_INC_BASE_PRIORITY_NAME = "SeIncreaseBasePriorityPrivilege"
SE_INCREASE_QUOTA_NAME = "SeIncreaseQuotaPrivilege"
SE_INC_WORKING_SET_NAME = "SeIncreaseWorkingSetPrivilege"
SE_LOAD_DRIVER_NAME = "SeLoadDriverPrivilege"
SE_LOCK_MEMORY_NAME = "SeLockMemoryPrivilege"
SE_MACHINE_ACCOUNT_NAME = "SeMachineAccountPrivilege"
SE_MANAGE_VOLUME_NAME = "SeManageVolumePrivilege"
SE_PROF_SINGLE_PROCESS_NAME = "SeProfileSingleProcessPrivilege"
SE_RELABEL_NAME = "SeRelabelPrivilege"
SE_REMOTE_SHUTDOWN_NAME = "SeRemoteShutdownPrivilege"
SE_RESTORE_NAME = "SeRestorePrivilege"
SE_SECURITY_NAME = "SeSecurityPrivilege"
SE_SHUTDOWN_NAME = "SeShutdownPrivilege"
SE_SYNC_AGENT_NAME = "SeSyncAgentPrivilege"
SE_SYSTEM_ENVIRONMENT_NAME = "SeSystemEnvironmentPrivilege"
SE_SYSTEM_PROFILE_NAME = "SeSystemProfilePrivilege"
SE_SYSTEMTIME_NAME = "SeSystemtimePrivilege"
SE_TAKE_OWNERSHIP_NAME = "SeTakeOwnershipPrivilege"
SE_TCB_NAME = "SeTcbPrivilege"
SE_TIME_ZONE_NAME = "SeTimeZonePrivilege"
SE_TRUSTED_CREDMAN_ACCESS_NAME = "SeTrustedCredManAccessPrivilege"
SE_UNDOCK_NAME = "SeUndockPrivilege"
SE_UNSOLICITED_INPUT_NAME = "SeUnsolicitedInputPrivilege"
SE_PRIVILEGE_ENABLED_BY_DEFAULT = 0x00000001
SE_PRIVILEGE_ENABLED = 0x00000002
SE_PRIVILEGE_REMOVED = 0x00000004
SE_PRIVILEGE_USED_FOR_ACCESS = 0x80000000
TOKEN_ADJUST_PRIVILEGES = 0x00000020
LOGON_WITH_PROFILE = 0x00000001
LOGON_NETCREDENTIALS_ONLY = 0x00000002
# Token access rights
TOKEN_ASSIGN_PRIMARY = 0x0001
TOKEN_DUPLICATE = 0x0002
TOKEN_IMPERSONATE = 0x0004
TOKEN_QUERY = 0x0008
TOKEN_QUERY_SOURCE = 0x0010
TOKEN_ADJUST_PRIVILEGES = 0x0020
TOKEN_ADJUST_GROUPS = 0x0040
TOKEN_ADJUST_DEFAULT = 0x0080
TOKEN_ADJUST_SESSIONID = 0x0100
TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY)
TOKEN_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY |
TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE |
TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT |
TOKEN_ADJUST_SESSIONID)
# Predefined HKEY values
HKEY_CLASSES_ROOT = 0x80000000
HKEY_CURRENT_USER = 0x80000001
HKEY_LOCAL_MACHINE = 0x80000002
HKEY_USERS = 0x80000003
HKEY_PERFORMANCE_DATA = 0x80000004
HKEY_CURRENT_CONFIG = 0x80000005
# Registry access rights
KEY_ALL_ACCESS = 0xF003F
KEY_CREATE_LINK = 0x0020
KEY_CREATE_SUB_KEY = 0x0004
KEY_ENUMERATE_SUB_KEYS = 0x0008
KEY_EXECUTE = 0x20019
KEY_NOTIFY = 0x0010
KEY_QUERY_VALUE = 0x0001
KEY_READ = 0x20019
KEY_SET_VALUE = 0x0002
KEY_WOW64_32KEY = 0x0200
KEY_WOW64_64KEY = 0x0100
KEY_WRITE = 0x20006
# Registry value types
REG_NONE = 0
REG_SZ = 1
REG_EXPAND_SZ = 2
REG_BINARY = 3
REG_DWORD = 4
REG_DWORD_LITTLE_ENDIAN = REG_DWORD
REG_DWORD_BIG_ENDIAN = 5
REG_LINK = 6
REG_MULTI_SZ = 7
REG_RESOURCE_LIST = 8
REG_FULL_RESOURCE_DESCRIPTOR = 9
REG_RESOURCE_REQUIREMENTS_LIST = 10
REG_QWORD = 11
REG_QWORD_LITTLE_ENDIAN = REG_QWORD
#--- TOKEN_PRIVILEGE structure ------------------------------------------------
# typedef struct _LUID {
# DWORD LowPart;
# LONG HighPart;
# } LUID,
# *PLUID;
class LUID(Structure):
_fields_ = [
("LowPart", DWORD),
("HighPart", LONG),
]
PLUID = POINTER(LUID)
# typedef struct _LUID_AND_ATTRIBUTES {
# LUID Luid;
# DWORD Attributes;
# } LUID_AND_ATTRIBUTES,
# *PLUID_AND_ATTRIBUTES;
class LUID_AND_ATTRIBUTES(Structure):
_fields_ = [
("Luid", LUID),
("Attributes", DWORD),
]
# typedef struct _TOKEN_PRIVILEGES {
# DWORD PrivilegeCount;
# LUID_AND_ATTRIBUTES Privileges[ANYSIZE_ARRAY];
# } TOKEN_PRIVILEGES,
# *PTOKEN_PRIVILEGES;
class TOKEN_PRIVILEGES(Structure):
_fields_ = [
("PrivilegeCount", DWORD),
## ("Privileges", LUID_AND_ATTRIBUTES * ANYSIZE_ARRAY),
("Privileges", LUID_AND_ATTRIBUTES),
]
# See comments on AdjustTokenPrivileges about this structure
PTOKEN_PRIVILEGES = POINTER(TOKEN_PRIVILEGES)
#--- GetTokenInformation enums and structures ---------------------------------
# typedef enum _TOKEN_INFORMATION_CLASS {
# TokenUser = 1,
# TokenGroups,
# TokenPrivileges,
# TokenOwner,
# TokenPrimaryGroup,
# TokenDefaultDacl,
# TokenSource,
# TokenType,
# TokenImpersonationLevel,
# TokenStatistics,
# TokenRestrictedSids,
# TokenSessionId,
# TokenGroupsAndPrivileges,
# TokenSessionReference,
# TokenSandBoxInert,
# TokenAuditPolicy,
# TokenOrigin,
# TokenElevationType,
# TokenLinkedToken,
# TokenElevation,
# TokenHasRestrictions,
# TokenAccessInformation,
# TokenVirtualizationAllowed,
# TokenVirtualizationEnabled,
# TokenIntegrityLevel,
# TokenUIAccess,
# TokenMandatoryPolicy,
# TokenLogonSid,
# TokenIsAppContainer,
# TokenCapabilities,
# TokenAppContainerSid,
# TokenAppContainerNumber,
# TokenUserClaimAttributes,
# TokenDeviceClaimAttributes,
# TokenRestrictedUserClaimAttributes,
# TokenRestrictedDeviceClaimAttributes,
# TokenDeviceGroups,
# TokenRestrictedDeviceGroups,
# TokenSecurityAttributes,
# TokenIsRestricted,
# MaxTokenInfoClass
# } TOKEN_INFORMATION_CLASS, *PTOKEN_INFORMATION_CLASS;
TOKEN_INFORMATION_CLASS = ctypes.c_int
TokenUser = 1
TokenGroups = 2
TokenPrivileges = 3
TokenOwner = 4
TokenPrimaryGroup = 5
TokenDefaultDacl = 6
TokenSource = 7
TokenType = 8
TokenImpersonationLevel = 9
TokenStatistics = 10
TokenRestrictedSids = 11
TokenSessionId = 12
TokenGroupsAndPrivileges = 13
TokenSessionReference = 14
TokenSandBoxInert = 15
TokenAuditPolicy = 16
TokenOrigin = 17
TokenElevationType = 18
TokenLinkedToken = 19
TokenElevation = 20
TokenHasRestrictions = 21
TokenAccessInformation = 22
TokenVirtualizationAllowed = 23
TokenVirtualizationEnabled = 24
TokenIntegrityLevel = 25
TokenUIAccess = 26
TokenMandatoryPolicy = 27
TokenLogonSid = 28
TokenIsAppContainer = 29
TokenCapabilities = 30
TokenAppContainerSid = 31
TokenAppContainerNumber = 32
TokenUserClaimAttributes = 33
TokenDeviceClaimAttributes = 34
TokenRestrictedUserClaimAttributes = 35
TokenRestrictedDeviceClaimAttributes = 36
TokenDeviceGroups = 37
TokenRestrictedDeviceGroups = 38
TokenSecurityAttributes = 39
TokenIsRestricted = 40
MaxTokenInfoClass = 41
# typedef enum tagTOKEN_TYPE {
# TokenPrimary = 1,
# TokenImpersonation
# } TOKEN_TYPE, *PTOKEN_TYPE;
TOKEN_TYPE = ctypes.c_int
PTOKEN_TYPE = POINTER(TOKEN_TYPE)
TokenPrimary = 1
TokenImpersonation = 2
# typedef enum {
# TokenElevationTypeDefault = 1,
# TokenElevationTypeFull,
# TokenElevationTypeLimited
# } TOKEN_ELEVATION_TYPE , *PTOKEN_ELEVATION_TYPE;
TokenElevationTypeDefault = 1
TokenElevationTypeFull = 2
TokenElevationTypeLimited = 3
TOKEN_ELEVATION_TYPE = ctypes.c_int
PTOKEN_ELEVATION_TYPE = POINTER(TOKEN_ELEVATION_TYPE)
# typedef enum _SECURITY_IMPERSONATION_LEVEL {
# SecurityAnonymous,
# SecurityIdentification,
# SecurityImpersonation,
# SecurityDelegation
# } SECURITY_IMPERSONATION_LEVEL, *PSECURITY_IMPERSONATION_LEVEL;
SecurityAnonymous = 0
SecurityIdentification = 1
SecurityImpersonation = 2
SecurityDelegation = 3
SECURITY_IMPERSONATION_LEVEL = ctypes.c_int
PSECURITY_IMPERSONATION_LEVEL = POINTER(SECURITY_IMPERSONATION_LEVEL)
# typedef struct _SID_AND_ATTRIBUTES {
# PSID Sid;
# DWORD Attributes;
# } SID_AND_ATTRIBUTES, *PSID_AND_ATTRIBUTES;
class SID_AND_ATTRIBUTES(Structure):
_fields_ = [
("Sid", PSID),
("Attributes", DWORD),
]
PSID_AND_ATTRIBUTES = POINTER(SID_AND_ATTRIBUTES)
# typedef struct _TOKEN_USER {
# SID_AND_ATTRIBUTES User;
# } TOKEN_USER, *PTOKEN_USER;
class TOKEN_USER(Structure):
_fields_ = [
("User", SID_AND_ATTRIBUTES),
]
PTOKEN_USER = POINTER(TOKEN_USER)
# typedef struct _TOKEN_MANDATORY_LABEL {
# SID_AND_ATTRIBUTES Label;
# } TOKEN_MANDATORY_LABEL, *PTOKEN_MANDATORY_LABEL;
class TOKEN_MANDATORY_LABEL(Structure):
_fields_ = [
("Label", SID_AND_ATTRIBUTES),
]
PTOKEN_MANDATORY_LABEL = POINTER(TOKEN_MANDATORY_LABEL)
# typedef struct _TOKEN_OWNER {
# PSID Owner;
# } TOKEN_OWNER, *PTOKEN_OWNER;
class TOKEN_OWNER(Structure):
_fields_ = [
("Owner", PSID),
]
PTOKEN_OWNER = POINTER(TOKEN_OWNER)
# typedef struct _TOKEN_PRIMARY_GROUP {
# PSID PrimaryGroup;
# } TOKEN_PRIMARY_GROUP, *PTOKEN_PRIMARY_GROUP;
class TOKEN_PRIMARY_GROUP(Structure):
_fields_ = [
("PrimaryGroup", PSID),
]
PTOKEN_PRIMARY_GROUP = POINTER(TOKEN_PRIMARY_GROUP)
# typedef struct _TOKEN_APPCONTAINER_INFORMATION {
# PSID TokenAppContainer;
# } TOKEN_APPCONTAINER_INFORMATION, *PTOKEN_APPCONTAINER_INFORMATION;
class TOKEN_APPCONTAINER_INFORMATION(Structure):
_fields_ = [
("TokenAppContainer", PSID),
]
PTOKEN_APPCONTAINER_INFORMATION = POINTER(TOKEN_APPCONTAINER_INFORMATION)
# typedef struct _TOKEN_ORIGIN {
# LUID OriginatingLogonSession;
# } TOKEN_ORIGIN, *PTOKEN_ORIGIN;
class TOKEN_ORIGIN(Structure):
_fields_ = [
("OriginatingLogonSession", LUID),
]
PTOKEN_ORIGIN = POINTER(TOKEN_ORIGIN)
# typedef struct _TOKEN_LINKED_TOKEN {
# HANDLE LinkedToken;
# } TOKEN_LINKED_TOKEN, *PTOKEN_LINKED_TOKEN;
class TOKEN_LINKED_TOKEN(Structure):
_fields_ = [
("LinkedToken", HANDLE),
]
PTOKEN_LINKED_TOKEN = POINTER(TOKEN_LINKED_TOKEN)
# typedef struct _TOKEN_STATISTICS {
# LUID TokenId;
# LUID AuthenticationId;
# LARGE_INTEGER ExpirationTime;
# TOKEN_TYPE TokenType;
# SECURITY_IMPERSONATION_LEVEL ImpersonationLevel;
# DWORD DynamicCharged;
# DWORD DynamicAvailable;
# DWORD GroupCount;
# DWORD PrivilegeCount;
# LUID ModifiedId;
# } TOKEN_STATISTICS, *PTOKEN_STATISTICS;
class TOKEN_STATISTICS(Structure):
_fields_ = [
("TokenId", LUID),
("AuthenticationId", LUID),
("ExpirationTime", LONGLONG), # LARGE_INTEGER
("TokenType", TOKEN_TYPE),
("ImpersonationLevel", SECURITY_IMPERSONATION_LEVEL),
("DynamicCharged", DWORD),
("DynamicAvailable", DWORD),
("GroupCount", DWORD),
("PrivilegeCount", DWORD),
("ModifiedId", LUID),
]
PTOKEN_STATISTICS = POINTER(TOKEN_STATISTICS)
#--- SID_NAME_USE enum --------------------------------------------------------
# typedef enum _SID_NAME_USE {
# SidTypeUser = 1,
# SidTypeGroup,
# SidTypeDomain,
# SidTypeAlias,
# SidTypeWellKnownGroup,
# SidTypeDeletedAccount,
# SidTypeInvalid,
# SidTypeUnknown,
# SidTypeComputer,
# SidTypeLabel
# } SID_NAME_USE, *PSID_NAME_USE;
SidTypeUser = 1
SidTypeGroup = 2
SidTypeDomain = 3
SidTypeAlias = 4
SidTypeWellKnownGroup = 5
SidTypeDeletedAccount = 6
SidTypeInvalid = 7
SidTypeUnknown = 8
SidTypeComputer = 9
SidTypeLabel = 10
#--- WAITCHAIN_NODE_INFO structure and types ----------------------------------
WCT_MAX_NODE_COUNT = 16
WCT_OBJNAME_LENGTH = 128
WCT_ASYNC_OPEN_FLAG = 1
WCTP_OPEN_ALL_FLAGS = WCT_ASYNC_OPEN_FLAG
WCT_OUT_OF_PROC_FLAG = 1
WCT_OUT_OF_PROC_COM_FLAG = 2
WCT_OUT_OF_PROC_CS_FLAG = 4
WCTP_GETINFO_ALL_FLAGS = WCT_OUT_OF_PROC_FLAG | WCT_OUT_OF_PROC_COM_FLAG | WCT_OUT_OF_PROC_CS_FLAG
HWCT = LPVOID
# typedef enum _WCT_OBJECT_TYPE
# {
# WctCriticalSectionType = 1,
# WctSendMessageType,
# WctMutexType,
# WctAlpcType,
# WctComType,
# WctThreadWaitType,
# WctProcessWaitType,
# WctThreadType,
# WctComActivationType,
# WctUnknownType,
# WctMaxType
# } WCT_OBJECT_TYPE;
WCT_OBJECT_TYPE = DWORD
WctCriticalSectionType = 1
WctSendMessageType = 2
WctMutexType = 3
WctAlpcType = 4
WctComType = 5
WctThreadWaitType = 6
WctProcessWaitType = 7
WctThreadType = 8
WctComActivationType = 9
WctUnknownType = 10
WctMaxType = 11
# typedef enum _WCT_OBJECT_STATUS
# {
# WctStatusNoAccess = 1, // ACCESS_DENIED for this object
# WctStatusRunning, // Thread status
# WctStatusBlocked, // Thread status
# WctStatusPidOnly, // Thread status
# WctStatusPidOnlyRpcss, // Thread status
# WctStatusOwned, // Dispatcher object status
# WctStatusNotOwned, // Dispatcher object status
# WctStatusAbandoned, // Dispatcher object status
# WctStatusUnknown, // All objects
# WctStatusError, // All objects
# WctStatusMax
# } WCT_OBJECT_STATUS;
WCT_OBJECT_STATUS = DWORD
WctStatusNoAccess = 1 # ACCESS_DENIED for this object
WctStatusRunning = 2 # Thread status
WctStatusBlocked = 3 # Thread status
WctStatusPidOnly = 4 # Thread status
WctStatusPidOnlyRpcss = 5 # Thread status
WctStatusOwned = 6 # Dispatcher object status
WctStatusNotOwned = 7 # Dispatcher object status
WctStatusAbandoned = 8 # Dispatcher object status
WctStatusUnknown = 9 # All objects
WctStatusError = 10 # All objects
WctStatusMax = 11
# typedef struct _WAITCHAIN_NODE_INFO {
# WCT_OBJECT_TYPE ObjectType;
# WCT_OBJECT_STATUS ObjectStatus;
# union {
# struct {
# WCHAR ObjectName[WCT_OBJNAME_LENGTH];
# LARGE_INTEGER Timeout;
# BOOL Alertable;
# } LockObject;
# struct {
# DWORD ProcessId;
# DWORD ThreadId;
# DWORD WaitTime;
# DWORD ContextSwitches;
# } ThreadObject;
# } ;
# }WAITCHAIN_NODE_INFO, *PWAITCHAIN_NODE_INFO;
class _WAITCHAIN_NODE_INFO_STRUCT_1(Structure):
_fields_ = [
("ObjectName", WCHAR * WCT_OBJNAME_LENGTH),
("Timeout", LONGLONG), # LARGE_INTEGER
("Alertable", BOOL),
]
class _WAITCHAIN_NODE_INFO_STRUCT_2(Structure):
_fields_ = [
("ProcessId", DWORD),
("ThreadId", DWORD),
("WaitTime", DWORD),
("ContextSwitches", DWORD),
]
class _WAITCHAIN_NODE_INFO_UNION(Union):
_fields_ = [
("LockObject", _WAITCHAIN_NODE_INFO_STRUCT_1),
("ThreadObject", _WAITCHAIN_NODE_INFO_STRUCT_2),
]
class WAITCHAIN_NODE_INFO(Structure):
_fields_ = [
("ObjectType", WCT_OBJECT_TYPE),
("ObjectStatus", WCT_OBJECT_STATUS),
("u", _WAITCHAIN_NODE_INFO_UNION),
]
PWAITCHAIN_NODE_INFO = POINTER(WAITCHAIN_NODE_INFO)
class WaitChainNodeInfo (object):
"""
Represents a node in the wait chain.
It's a wrapper on the L{WAITCHAIN_NODE_INFO} structure.
The following members are defined only
if the node is of L{WctThreadType} type:
- C{ProcessId}
- C{ThreadId}
- C{WaitTime}
- C{ContextSwitches}
@see: L{GetThreadWaitChain}
@type ObjectName: unicode
@ivar ObjectName: Object name. May be an empty string.
@type ObjectType: int
@ivar ObjectType: Object type.
Should be one of the following values:
- L{WctCriticalSectionType}
- L{WctSendMessageType}
- L{WctMutexType}
- L{WctAlpcType}
- L{WctComType}
- L{WctThreadWaitType}
- L{WctProcessWaitType}
- L{WctThreadType}
- L{WctComActivationType}
- L{WctUnknownType}
@type ObjectStatus: int
@ivar ObjectStatus: Wait status.
Should be one of the following values:
- L{WctStatusNoAccess} I{(ACCESS_DENIED for this object)}
- L{WctStatusRunning} I{(Thread status)}
- L{WctStatusBlocked} I{(Thread status)}
- L{WctStatusPidOnly} I{(Thread status)}
- L{WctStatusPidOnlyRpcss} I{(Thread status)}
- L{WctStatusOwned} I{(Dispatcher object status)}
- L{WctStatusNotOwned} I{(Dispatcher object status)}
- L{WctStatusAbandoned} I{(Dispatcher object status)}
- L{WctStatusUnknown} I{(All objects)}
- L{WctStatusError} I{(All objects)}
@type ProcessId: int
@ivar ProcessId: Process global ID.
@type ThreadId: int
@ivar ThreadId: Thread global ID.
@type WaitTime: int
@ivar WaitTime: Wait time.
@type ContextSwitches: int
@ivar ContextSwitches: Number of context switches.
"""
#@type Timeout: int
#@ivar Timeout: Currently not documented in MSDN.
#
#@type Alertable: bool
#@ivar Alertable: Currently not documented in MSDN.
# TODO: __repr__
def __init__(self, aStructure):
self.ObjectType = aStructure.ObjectType
self.ObjectStatus = aStructure.ObjectStatus
if self.ObjectType == WctThreadType:
self.ProcessId = aStructure.u.ThreadObject.ProcessId
self.ThreadId = aStructure.u.ThreadObject.ThreadId
self.WaitTime = aStructure.u.ThreadObject.WaitTime
self.ContextSwitches = aStructure.u.ThreadObject.ContextSwitches
self.ObjectName = u''
else:
self.ObjectName = aStructure.u.LockObject.ObjectName.value
#self.Timeout = aStructure.u.LockObject.Timeout
#self.Alertable = bool(aStructure.u.LockObject.Alertable)
class ThreadWaitChainSessionHandle (Handle):
"""
Thread wait chain session handle.
Returned by L{OpenThreadWaitChainSession}.
@see: L{Handle}
"""
def __init__(self, aHandle = None):
"""
@type aHandle: int
@param aHandle: Win32 handle value.
"""
super(ThreadWaitChainSessionHandle, self).__init__(aHandle,
bOwnership = True)
def _close(self):
if self.value is None:
raise ValueError("Handle was already closed!")
CloseThreadWaitChainSession(self.value)
def dup(self):
raise NotImplementedError()
def wait(self, dwMilliseconds = None):
raise NotImplementedError()
@property
def inherit(self):
return False
@property
def protectFromClose(self):
return False
#--- Privilege dropping -------------------------------------------------------
SAFER_LEVEL_HANDLE = HANDLE
SAFER_SCOPEID_MACHINE = 1
SAFER_SCOPEID_USER = 2
SAFER_LEVEL_OPEN = 1
SAFER_LEVELID_DISALLOWED = 0x00000
SAFER_LEVELID_UNTRUSTED = 0x01000
SAFER_LEVELID_CONSTRAINED = 0x10000
SAFER_LEVELID_NORMALUSER = 0x20000
SAFER_LEVELID_FULLYTRUSTED = 0x40000
SAFER_POLICY_INFO_CLASS = DWORD
SaferPolicyLevelList = 1
SaferPolicyEnableTransparentEnforcement = 2
SaferPolicyDefaultLevel = 3
SaferPolicyEvaluateUserScope = 4
SaferPolicyScopeFlags = 5
SAFER_TOKEN_NULL_IF_EQUAL = 1
SAFER_TOKEN_COMPARE_ONLY = 2
SAFER_TOKEN_MAKE_INERT = 4
SAFER_TOKEN_WANT_FLAGS = 8
SAFER_TOKEN_MASK = 15
#--- Service Control Manager types, constants and structures ------------------
SC_HANDLE = HANDLE
SERVICES_ACTIVE_DATABASEW = u"ServicesActive"
SERVICES_FAILED_DATABASEW = u"ServicesFailed"
SERVICES_ACTIVE_DATABASEA = "ServicesActive"
SERVICES_FAILED_DATABASEA = "ServicesFailed"
SC_GROUP_IDENTIFIERW = u'+'
SC_GROUP_IDENTIFIERA = '+'
SERVICE_NO_CHANGE = 0xffffffff
# enum SC_STATUS_TYPE
SC_STATUS_TYPE = ctypes.c_int
SC_STATUS_PROCESS_INFO = 0
# enum SC_ENUM_TYPE
SC_ENUM_TYPE = ctypes.c_int
SC_ENUM_PROCESS_INFO = 0
# Access rights
# http://msdn.microsoft.com/en-us/library/windows/desktop/ms685981(v=vs.85).aspx
SERVICE_ALL_ACCESS = 0xF01FF
SERVICE_QUERY_CONFIG = 0x0001
SERVICE_CHANGE_CONFIG = 0x0002
SERVICE_QUERY_STATUS = 0x0004
SERVICE_ENUMERATE_DEPENDENTS = 0x0008
SERVICE_START = 0x0010
SERVICE_STOP = 0x0020
SERVICE_PAUSE_CONTINUE = 0x0040
SERVICE_INTERROGATE = 0x0080
SERVICE_USER_DEFINED_CONTROL = 0x0100
SC_MANAGER_ALL_ACCESS = 0xF003F
SC_MANAGER_CONNECT = 0x0001
SC_MANAGER_CREATE_SERVICE = 0x0002
SC_MANAGER_ENUMERATE_SERVICE = 0x0004
SC_MANAGER_LOCK = 0x0008
SC_MANAGER_QUERY_LOCK_STATUS = 0x0010
SC_MANAGER_MODIFY_BOOT_CONFIG = 0x0020
# CreateService() service start type
SERVICE_BOOT_START = 0x00000000
SERVICE_SYSTEM_START = 0x00000001
SERVICE_AUTO_START = 0x00000002
SERVICE_DEMAND_START = 0x00000003
SERVICE_DISABLED = 0x00000004
# CreateService() error control flags
SERVICE_ERROR_IGNORE = 0x00000000
SERVICE_ERROR_NORMAL = 0x00000001
SERVICE_ERROR_SEVERE = 0x00000002
SERVICE_ERROR_CRITICAL = 0x00000003
# EnumServicesStatusEx() service state filters
SERVICE_ACTIVE = 1
SERVICE_INACTIVE = 2
SERVICE_STATE_ALL = 3
# SERVICE_STATUS_PROCESS.dwServiceType
SERVICE_KERNEL_DRIVER = 0x00000001
SERVICE_FILE_SYSTEM_DRIVER = 0x00000002
SERVICE_ADAPTER = 0x00000004
SERVICE_RECOGNIZER_DRIVER = 0x00000008
SERVICE_WIN32_OWN_PROCESS = 0x00000010
SERVICE_WIN32_SHARE_PROCESS = 0x00000020
SERVICE_INTERACTIVE_PROCESS = 0x00000100
# EnumServicesStatusEx() service type filters (in addition to actual types)
SERVICE_DRIVER = 0x0000000B # SERVICE_KERNEL_DRIVER and SERVICE_FILE_SYSTEM_DRIVER
SERVICE_WIN32 = 0x00000030 # SERVICE_WIN32_OWN_PROCESS and SERVICE_WIN32_SHARE_PROCESS
# SERVICE_STATUS_PROCESS.dwCurrentState
SERVICE_STOPPED = 0x00000001
SERVICE_START_PENDING = 0x00000002
SERVICE_STOP_PENDING = 0x00000003
SERVICE_RUNNING = 0x00000004
SERVICE_CONTINUE_PENDING = 0x00000005
SERVICE_PAUSE_PENDING = 0x00000006
SERVICE_PAUSED = 0x00000007
# SERVICE_STATUS_PROCESS.dwControlsAccepted
SERVICE_ACCEPT_STOP = 0x00000001
SERVICE_ACCEPT_PAUSE_CONTINUE = 0x00000002
SERVICE_ACCEPT_SHUTDOWN = 0x00000004
SERVICE_ACCEPT_PARAMCHANGE = 0x00000008
SERVICE_ACCEPT_NETBINDCHANGE = 0x00000010
SERVICE_ACCEPT_HARDWAREPROFILECHANGE = 0x00000020
SERVICE_ACCEPT_POWEREVENT = 0x00000040
SERVICE_ACCEPT_SESSIONCHANGE = 0x00000080
SERVICE_ACCEPT_PRESHUTDOWN = 0x00000100
# SERVICE_STATUS_PROCESS.dwServiceFlags
SERVICE_RUNS_IN_SYSTEM_PROCESS = 0x00000001
# Service control flags
SERVICE_CONTROL_STOP = 0x00000001
SERVICE_CONTROL_PAUSE = 0x00000002
SERVICE_CONTROL_CONTINUE = 0x00000003
SERVICE_CONTROL_INTERROGATE = 0x00000004
SERVICE_CONTROL_SHUTDOWN = 0x00000005
SERVICE_CONTROL_PARAMCHANGE = 0x00000006
SERVICE_CONTROL_NETBINDADD = 0x00000007
SERVICE_CONTROL_NETBINDREMOVE = 0x00000008
SERVICE_CONTROL_NETBINDENABLE = 0x00000009
SERVICE_CONTROL_NETBINDDISABLE = 0x0000000A
SERVICE_CONTROL_DEVICEEVENT = 0x0000000B
SERVICE_CONTROL_HARDWAREPROFILECHANGE = 0x0000000C
SERVICE_CONTROL_POWEREVENT = 0x0000000D
SERVICE_CONTROL_SESSIONCHANGE = 0x0000000E
# Service control accepted bitmasks
SERVICE_ACCEPT_STOP = 0x00000001
SERVICE_ACCEPT_PAUSE_CONTINUE = 0x00000002
SERVICE_ACCEPT_SHUTDOWN = 0x00000004
SERVICE_ACCEPT_PARAMCHANGE = 0x00000008
SERVICE_ACCEPT_NETBINDCHANGE = 0x00000010
SERVICE_ACCEPT_HARDWAREPROFILECHANGE = 0x00000020
SERVICE_ACCEPT_POWEREVENT = 0x00000040
SERVICE_ACCEPT_SESSIONCHANGE = 0x00000080
SERVICE_ACCEPT_PRESHUTDOWN = 0x00000100
SERVICE_ACCEPT_TIMECHANGE = 0x00000200
SERVICE_ACCEPT_TRIGGEREVENT = 0x00000400
SERVICE_ACCEPT_USERMODEREBOOT = 0x00000800
# enum SC_ACTION_TYPE
SC_ACTION_NONE = 0
SC_ACTION_RESTART = 1
SC_ACTION_REBOOT = 2
SC_ACTION_RUN_COMMAND = 3
# QueryServiceConfig2
SERVICE_CONFIG_DESCRIPTION = 1
SERVICE_CONFIG_FAILURE_ACTIONS = 2
# typedef struct _SERVICE_STATUS {
# DWORD dwServiceType;
# DWORD dwCurrentState;
# DWORD dwControlsAccepted;
# DWORD dwWin32ExitCode;
# DWORD dwServiceSpecificExitCode;
# DWORD dwCheckPoint;
# DWORD dwWaitHint;
# } SERVICE_STATUS, *LPSERVICE_STATUS;
class SERVICE_STATUS(Structure):
_fields_ = [
("dwServiceType", DWORD),
("dwCurrentState", DWORD),
("dwControlsAccepted", DWORD),
("dwWin32ExitCode", DWORD),
("dwServiceSpecificExitCode", DWORD),
("dwCheckPoint", DWORD),
("dwWaitHint", DWORD),
]
LPSERVICE_STATUS = POINTER(SERVICE_STATUS)
# typedef struct _SERVICE_STATUS_PROCESS {
# DWORD dwServiceType;
# DWORD dwCurrentState;
# DWORD dwControlsAccepted;
# DWORD dwWin32ExitCode;
# DWORD dwServiceSpecificExitCode;
# DWORD dwCheckPoint;
# DWORD dwWaitHint;
# DWORD dwProcessId;
# DWORD dwServiceFlags;
# } SERVICE_STATUS_PROCESS, *LPSERVICE_STATUS_PROCESS;
class SERVICE_STATUS_PROCESS(Structure):
_fields_ = SERVICE_STATUS._fields_ + [
("dwProcessId", DWORD),
("dwServiceFlags", DWORD),
]
LPSERVICE_STATUS_PROCESS = POINTER(SERVICE_STATUS_PROCESS)
# typedef struct _ENUM_SERVICE_STATUS {
# LPTSTR lpServiceName;
# LPTSTR lpDisplayName;
# SERVICE_STATUS ServiceStatus;
# } ENUM_SERVICE_STATUS, *LPENUM_SERVICE_STATUS;
class ENUM_SERVICE_STATUSA(Structure):
_fields_ = [
("lpServiceName", LPSTR),
("lpDisplayName", LPSTR),
("ServiceStatus", SERVICE_STATUS),
]
class ENUM_SERVICE_STATUSW(Structure):
_fields_ = [
("lpServiceName", LPWSTR),
("lpDisplayName", LPWSTR),
("ServiceStatus", SERVICE_STATUS),
]
LPENUM_SERVICE_STATUSA = POINTER(ENUM_SERVICE_STATUSA)
LPENUM_SERVICE_STATUSW = POINTER(ENUM_SERVICE_STATUSW)
# typedef struct _ENUM_SERVICE_STATUS_PROCESS {
# LPTSTR lpServiceName;
# LPTSTR lpDisplayName;
# SERVICE_STATUS_PROCESS ServiceStatusProcess;
# } ENUM_SERVICE_STATUS_PROCESS, *LPENUM_SERVICE_STATUS_PROCESS;
class ENUM_SERVICE_STATUS_PROCESSA(Structure):
_fields_ = [
("lpServiceName", LPSTR),
("lpDisplayName", LPSTR),
("ServiceStatusProcess", SERVICE_STATUS_PROCESS),
]
class ENUM_SERVICE_STATUS_PROCESSW(Structure):
_fields_ = [
("lpServiceName", LPWSTR),
("lpDisplayName", LPWSTR),
("ServiceStatusProcess", SERVICE_STATUS_PROCESS),
]
LPENUM_SERVICE_STATUS_PROCESSA = POINTER(ENUM_SERVICE_STATUS_PROCESSA)
LPENUM_SERVICE_STATUS_PROCESSW = POINTER(ENUM_SERVICE_STATUS_PROCESSW)
class ServiceStatus(object):
"""
Wrapper for the L{SERVICE_STATUS} structure.
"""
def __init__(self, raw):
"""
@type raw: L{SERVICE_STATUS}
@param raw: Raw structure for this service status data.
"""
self.ServiceType = raw.dwServiceType
self.CurrentState = raw.dwCurrentState
self.ControlsAccepted = raw.dwControlsAccepted
self.Win32ExitCode = raw.dwWin32ExitCode
self.ServiceSpecificExitCode = raw.dwServiceSpecificExitCode
self.CheckPoint = raw.dwCheckPoint
self.WaitHint = raw.dwWaitHint
class ServiceStatusProcess(object):
"""
Wrapper for the L{SERVICE_STATUS_PROCESS} structure.
"""
def __init__(self, raw):
"""
@type raw: L{SERVICE_STATUS_PROCESS}
@param raw: Raw structure for this service status data.
"""
self.ServiceType = raw.dwServiceType
self.CurrentState = raw.dwCurrentState
self.ControlsAccepted = raw.dwControlsAccepted
self.Win32ExitCode = raw.dwWin32ExitCode
self.ServiceSpecificExitCode = raw.dwServiceSpecificExitCode
self.CheckPoint = raw.dwCheckPoint
self.WaitHint = raw.dwWaitHint
self.ProcessId = raw.dwProcessId
self.ServiceFlags = raw.dwServiceFlags
class ServiceStatusEntry(object):
"""
Service status entry returned by L{EnumServicesStatus}.
"""
def __init__(self, raw):
"""
@type raw: L{ENUM_SERVICE_STATUSA} or L{ENUM_SERVICE_STATUSW}
@param raw: Raw structure for this service status entry.
"""
self.ServiceName = raw.lpServiceName
self.DisplayName = raw.lpDisplayName
self.ServiceType = raw.ServiceStatus.dwServiceType
self.CurrentState = raw.ServiceStatus.dwCurrentState
self.ControlsAccepted = raw.ServiceStatus.dwControlsAccepted
self.Win32ExitCode = raw.ServiceStatus.dwWin32ExitCode
self.ServiceSpecificExitCode = raw.ServiceStatus.dwServiceSpecificExitCode
self.CheckPoint = raw.ServiceStatus.dwCheckPoint
self.WaitHint = raw.ServiceStatus.dwWaitHint
def __str__(self):
output = []
if self.ServiceType & SERVICE_INTERACTIVE_PROCESS:
output.append("Interactive service")
else:
output.append("Service")
if self.DisplayName:
output.append("\"%s\" (%s)" % (self.DisplayName, self.ServiceName))
else:
output.append("\"%s\"" % self.ServiceName)
if self.CurrentState == SERVICE_CONTINUE_PENDING:
output.append("is about to continue.")
elif self.CurrentState == SERVICE_PAUSE_PENDING:
output.append("is pausing.")
elif self.CurrentState == SERVICE_PAUSED:
output.append("is paused.")
elif self.CurrentState == SERVICE_RUNNING:
output.append("is running.")
elif self.CurrentState == SERVICE_START_PENDING:
output.append("is starting.")
elif self.CurrentState == SERVICE_STOP_PENDING:
output.append("is stopping.")
elif self.CurrentState == SERVICE_STOPPED:
output.append("is stopped.")
return " ".join(output)
class ServiceStatusProcessEntry(object):
"""
Service status entry returned by L{EnumServicesStatusEx}.
"""
def __init__(self, raw):
"""
@type raw: L{ENUM_SERVICE_STATUS_PROCESSA} or L{ENUM_SERVICE_STATUS_PROCESSW}
@param raw: Raw structure for this service status entry.
"""
self.ServiceName = raw.lpServiceName
self.DisplayName = raw.lpDisplayName
self.ServiceType = raw.ServiceStatusProcess.dwServiceType
self.CurrentState = raw.ServiceStatusProcess.dwCurrentState
self.ControlsAccepted = raw.ServiceStatusProcess.dwControlsAccepted
self.Win32ExitCode = raw.ServiceStatusProcess.dwWin32ExitCode
self.ServiceSpecificExitCode = raw.ServiceStatusProcess.dwServiceSpecificExitCode
self.CheckPoint = raw.ServiceStatusProcess.dwCheckPoint
self.WaitHint = raw.ServiceStatusProcess.dwWaitHint
self.ProcessId = raw.ServiceStatusProcess.dwProcessId
self.ServiceFlags = raw.ServiceStatusProcess.dwServiceFlags
def __str__(self):
output = []
if self.ServiceType & SERVICE_INTERACTIVE_PROCESS:
output.append("Interactive service ")
else:
output.append("Service ")
if self.DisplayName:
output.append("\"%s\" (%s)" % (self.DisplayName, self.ServiceName))
else:
output.append("\"%s\"" % self.ServiceName)
if self.CurrentState == SERVICE_CONTINUE_PENDING:
output.append(" is about to continue")
elif self.CurrentState == SERVICE_PAUSE_PENDING:
output.append(" is pausing")
elif self.CurrentState == SERVICE_PAUSED:
output.append(" is paused")
elif self.CurrentState == SERVICE_RUNNING:
output.append(" is running")
elif self.CurrentState == SERVICE_START_PENDING:
output.append(" is starting")
elif self.CurrentState == SERVICE_STOP_PENDING:
output.append(" is stopping")
elif self.CurrentState == SERVICE_STOPPED:
output.append(" is stopped")
if self.ProcessId:
output.append(" at process %d" % self.ProcessId)
output.append(".")
return "".join(output)
#--- Handle wrappers ----------------------------------------------------------
# XXX maybe add functions related to the tokens here?
class TokenHandle (Handle):
"""
Access token handle.
@see: L{Handle}
"""
pass
class RegistryKeyHandle (UserModeHandle):
"""
Registry key handle.
"""
_TYPE = HKEY
def _close(self):
RegCloseKey(self.value)
class SaferLevelHandle (UserModeHandle):
"""
Safer level handle.
@see: U{http://msdn.microsoft.com/en-us/library/ms722425(VS.85).aspx}
"""
_TYPE = SAFER_LEVEL_HANDLE
def _close(self):
SaferCloseLevel(self.value)
class ServiceHandle (UserModeHandle):
"""
Service handle.
@see: U{http://msdn.microsoft.com/en-us/library/windows/desktop/ms684330(v=vs.85).aspx}
"""
_TYPE = SC_HANDLE
def _close(self):
CloseServiceHandle(self.value)
class ServiceControlManagerHandle (UserModeHandle):
"""
Service Control Manager (SCM) handle.
@see: U{http://msdn.microsoft.com/en-us/library/windows/desktop/ms684323(v=vs.85).aspx}
"""
_TYPE = SC_HANDLE
def _close(self):
CloseServiceHandle(self.value)
#--- advapi32.dll -------------------------------------------------------------
# BOOL WINAPI GetUserName(
# __out LPTSTR lpBuffer,
# __inout LPDWORD lpnSize
# );
def GetUserNameA():
_GetUserNameA = windll.advapi32.GetUserNameA
_GetUserNameA.argtypes = [LPSTR, LPDWORD]
_GetUserNameA.restype = bool
nSize = DWORD(0)
_GetUserNameA(None, byref(nSize))
error = GetLastError()
if error != ERROR_INSUFFICIENT_BUFFER:
raise ctypes.WinError(error)
lpBuffer = ctypes.create_string_buffer('', nSize.value + 1)
success = _GetUserNameA(lpBuffer, byref(nSize))
if not success:
raise ctypes.WinError()
return lpBuffer.value
def GetUserNameW():
_GetUserNameW = windll.advapi32.GetUserNameW
_GetUserNameW.argtypes = [LPWSTR, LPDWORD]
_GetUserNameW.restype = bool
nSize = DWORD(0)
_GetUserNameW(None, byref(nSize))
error = GetLastError()
if error != ERROR_INSUFFICIENT_BUFFER:
raise ctypes.WinError(error)
lpBuffer = ctypes.create_unicode_buffer(u'', nSize.value + 1)
success = _GetUserNameW(lpBuffer, byref(nSize))
if not success:
raise ctypes.WinError()
return lpBuffer.value
GetUserName = DefaultStringType(GetUserNameA, GetUserNameW)
# BOOL WINAPI LookupAccountName(
# __in_opt LPCTSTR lpSystemName,
# __in LPCTSTR lpAccountName,
# __out_opt PSID Sid,
# __inout LPDWORD cbSid,
# __out_opt LPTSTR ReferencedDomainName,
# __inout LPDWORD cchReferencedDomainName,
# __out PSID_NAME_USE peUse
# );
# XXX TO DO
# BOOL WINAPI LookupAccountSid(
# __in_opt LPCTSTR lpSystemName,
# __in PSID lpSid,
# __out_opt LPTSTR lpName,
# __inout LPDWORD cchName,
# __out_opt LPTSTR lpReferencedDomainName,
# __inout LPDWORD cchReferencedDomainName,
# __out PSID_NAME_USE peUse
# );
def LookupAccountSidA(lpSystemName, lpSid):
_LookupAccountSidA = windll.advapi32.LookupAccountSidA
_LookupAccountSidA.argtypes = [LPSTR, PSID, LPSTR, LPDWORD, LPSTR, LPDWORD, LPDWORD]
_LookupAccountSidA.restype = bool
cchName = DWORD(0)
cchReferencedDomainName = DWORD(0)
peUse = DWORD(0)
_LookupAccountSidA(lpSystemName, lpSid, None, byref(cchName), None, byref(cchReferencedDomainName), byref(peUse))
error = GetLastError()
if error != ERROR_INSUFFICIENT_BUFFER:
raise ctypes.WinError(error)
lpName = ctypes.create_string_buffer('', cchName + 1)
lpReferencedDomainName = ctypes.create_string_buffer('', cchReferencedDomainName + 1)
success = _LookupAccountSidA(lpSystemName, lpSid, lpName, byref(cchName), lpReferencedDomainName, byref(cchReferencedDomainName), byref(peUse))
if not success:
raise ctypes.WinError()
return lpName.value, lpReferencedDomainName.value, peUse.value
def LookupAccountSidW(lpSystemName, lpSid):
_LookupAccountSidW = windll.advapi32.LookupAccountSidA
_LookupAccountSidW.argtypes = [LPSTR, PSID, LPWSTR, LPDWORD, LPWSTR, LPDWORD, LPDWORD]
_LookupAccountSidW.restype = bool
cchName = DWORD(0)
cchReferencedDomainName = DWORD(0)
peUse = DWORD(0)
_LookupAccountSidW(lpSystemName, lpSid, None, byref(cchName), None, byref(cchReferencedDomainName), byref(peUse))
error = GetLastError()
if error != ERROR_INSUFFICIENT_BUFFER:
raise ctypes.WinError(error)
lpName = ctypes.create_unicode_buffer(u'', cchName + 1)
lpReferencedDomainName = ctypes.create_unicode_buffer(u'', cchReferencedDomainName + 1)
success = _LookupAccountSidW(lpSystemName, lpSid, lpName, byref(cchName), lpReferencedDomainName, byref(cchReferencedDomainName), byref(peUse))
if not success:
raise ctypes.WinError()
return lpName.value, lpReferencedDomainName.value, peUse.value
LookupAccountSid = GuessStringType(LookupAccountSidA, LookupAccountSidW)
# BOOL ConvertSidToStringSid(
# __in PSID Sid,
# __out LPTSTR *StringSid
# );
def ConvertSidToStringSidA(Sid):
_ConvertSidToStringSidA = windll.advapi32.ConvertSidToStringSidA
_ConvertSidToStringSidA.argtypes = [PSID, LPSTR]
_ConvertSidToStringSidA.restype = bool
_ConvertSidToStringSidA.errcheck = RaiseIfZero
pStringSid = LPSTR()
_ConvertSidToStringSidA(Sid, byref(pStringSid))
try:
StringSid = pStringSid.value
finally:
LocalFree(pStringSid)
return StringSid
def ConvertSidToStringSidW(Sid):
_ConvertSidToStringSidW = windll.advapi32.ConvertSidToStringSidW
_ConvertSidToStringSidW.argtypes = [PSID, LPWSTR]
_ConvertSidToStringSidW.restype = bool
_ConvertSidToStringSidW.errcheck = RaiseIfZero
pStringSid = LPWSTR()
_ConvertSidToStringSidW(Sid, byref(pStringSid))
try:
StringSid = pStringSid.value
finally:
LocalFree(pStringSid)
return StringSid
ConvertSidToStringSid = DefaultStringType(ConvertSidToStringSidA, ConvertSidToStringSidW)
# BOOL WINAPI ConvertStringSidToSid(
# __in LPCTSTR StringSid,
# __out PSID *Sid
# );
def ConvertStringSidToSidA(StringSid):
_ConvertStringSidToSidA = windll.advapi32.ConvertStringSidToSidA
_ConvertStringSidToSidA.argtypes = [LPSTR, PVOID]
_ConvertStringSidToSidA.restype = bool
_ConvertStringSidToSidA.errcheck = RaiseIfZero
Sid = PVOID()
_ConvertStringSidToSidA(StringSid, ctypes.pointer(Sid))
return Sid.value
def ConvertStringSidToSidW(StringSid):
_ConvertStringSidToSidW = windll.advapi32.ConvertStringSidToSidW
_ConvertStringSidToSidW.argtypes = [LPWSTR, PVOID]
_ConvertStringSidToSidW.restype = bool
_ConvertStringSidToSidW.errcheck = RaiseIfZero
Sid = PVOID()
_ConvertStringSidToSidW(StringSid, ctypes.pointer(Sid))
return Sid.value
ConvertStringSidToSid = GuessStringType(ConvertStringSidToSidA, ConvertStringSidToSidW)
# BOOL WINAPI IsValidSid(
# __in PSID pSid
# );
def IsValidSid(pSid):
_IsValidSid = windll.advapi32.IsValidSid
_IsValidSid.argtypes = [PSID]
_IsValidSid.restype = bool
return _IsValidSid(pSid)
# BOOL WINAPI EqualSid(
# __in PSID pSid1,
# __in PSID pSid2
# );
def EqualSid(pSid1, pSid2):
_EqualSid = windll.advapi32.EqualSid
_EqualSid.argtypes = [PSID, PSID]
_EqualSid.restype = bool
return _EqualSid(pSid1, pSid2)
# DWORD WINAPI GetLengthSid(
# __in PSID pSid
# );
def GetLengthSid(pSid):
_GetLengthSid = windll.advapi32.GetLengthSid
_GetLengthSid.argtypes = [PSID]
_GetLengthSid.restype = DWORD
return _GetLengthSid(pSid)
# BOOL WINAPI CopySid(
# __in DWORD nDestinationSidLength,
# __out PSID pDestinationSid,
# __in PSID pSourceSid
# );
def CopySid(pSourceSid):
_CopySid = windll.advapi32.CopySid
_CopySid.argtypes = [DWORD, PVOID, PSID]
_CopySid.restype = bool
_CopySid.errcheck = RaiseIfZero
nDestinationSidLength = GetLengthSid(pSourceSid)
DestinationSid = ctypes.create_string_buffer('', nDestinationSidLength)
pDestinationSid = ctypes.cast(ctypes.pointer(DestinationSid), PVOID)
_CopySid(nDestinationSidLength, pDestinationSid, pSourceSid)
return ctypes.cast(pDestinationSid, PSID)
# PVOID WINAPI FreeSid(
# __in PSID pSid
# );
def FreeSid(pSid):
_FreeSid = windll.advapi32.FreeSid
_FreeSid.argtypes = [PSID]
_FreeSid.restype = PSID
_FreeSid.errcheck = RaiseIfNotZero
_FreeSid(pSid)
# BOOL WINAPI OpenProcessToken(
# __in HANDLE ProcessHandle,
# __in DWORD DesiredAccess,
# __out PHANDLE TokenHandle
# );
def OpenProcessToken(ProcessHandle, DesiredAccess = TOKEN_ALL_ACCESS):
_OpenProcessToken = windll.advapi32.OpenProcessToken
_OpenProcessToken.argtypes = [HANDLE, DWORD, PHANDLE]
_OpenProcessToken.restype = bool
_OpenProcessToken.errcheck = RaiseIfZero
NewTokenHandle = HANDLE(INVALID_HANDLE_VALUE)
_OpenProcessToken(ProcessHandle, DesiredAccess, byref(NewTokenHandle))
return TokenHandle(NewTokenHandle.value)
# BOOL WINAPI OpenThreadToken(
# __in HANDLE ThreadHandle,
# __in DWORD DesiredAccess,
# __in BOOL OpenAsSelf,
# __out PHANDLE TokenHandle
# );
def OpenThreadToken(ThreadHandle, DesiredAccess, OpenAsSelf = True):
_OpenThreadToken = windll.advapi32.OpenThreadToken
_OpenThreadToken.argtypes = [HANDLE, DWORD, BOOL, PHANDLE]
_OpenThreadToken.restype = bool
_OpenThreadToken.errcheck = RaiseIfZero
NewTokenHandle = HANDLE(INVALID_HANDLE_VALUE)
_OpenThreadToken(ThreadHandle, DesiredAccess, OpenAsSelf, byref(NewTokenHandle))
return TokenHandle(NewTokenHandle.value)
# BOOL WINAPI DuplicateToken(
# _In_ HANDLE ExistingTokenHandle,
# _In_ SECURITY_IMPERSONATION_LEVEL ImpersonationLevel,
# _Out_ PHANDLE DuplicateTokenHandle
# );
def DuplicateToken(ExistingTokenHandle, ImpersonationLevel = SecurityImpersonation):
_DuplicateToken = windll.advapi32.DuplicateToken
_DuplicateToken.argtypes = [HANDLE, SECURITY_IMPERSONATION_LEVEL, PHANDLE]
_DuplicateToken.restype = bool
_DuplicateToken.errcheck = RaiseIfZero
DuplicateTokenHandle = HANDLE(INVALID_HANDLE_VALUE)
_DuplicateToken(ExistingTokenHandle, ImpersonationLevel, byref(DuplicateTokenHandle))
return TokenHandle(DuplicateTokenHandle.value)
# BOOL WINAPI DuplicateTokenEx(
# _In_ HANDLE hExistingToken,
# _In_ DWORD dwDesiredAccess,
# _In_opt_ LPSECURITY_ATTRIBUTES lpTokenAttributes,
# _In_ SECURITY_IMPERSONATION_LEVEL ImpersonationLevel,
# _In_ TOKEN_TYPE TokenType,
# _Out_ PHANDLE phNewToken
# );
def DuplicateTokenEx(hExistingToken, dwDesiredAccess = TOKEN_ALL_ACCESS, lpTokenAttributes = None, ImpersonationLevel = SecurityImpersonation, TokenType = TokenPrimary):
_DuplicateTokenEx = windll.advapi32.DuplicateTokenEx
_DuplicateTokenEx.argtypes = [HANDLE, DWORD, LPSECURITY_ATTRIBUTES, SECURITY_IMPERSONATION_LEVEL, TOKEN_TYPE, PHANDLE]
_DuplicateTokenEx.restype = bool
_DuplicateTokenEx.errcheck = RaiseIfZero
DuplicateTokenHandle = HANDLE(INVALID_HANDLE_VALUE)
_DuplicateTokenEx(hExistingToken, dwDesiredAccess, lpTokenAttributes, ImpersonationLevel, TokenType, byref(DuplicateTokenHandle))
return TokenHandle(DuplicateTokenHandle.value)
# BOOL WINAPI IsTokenRestricted(
# __in HANDLE TokenHandle
# );
def IsTokenRestricted(hTokenHandle):
_IsTokenRestricted = windll.advapi32.IsTokenRestricted
_IsTokenRestricted.argtypes = [HANDLE]
_IsTokenRestricted.restype = bool
_IsTokenRestricted.errcheck = RaiseIfNotErrorSuccess
SetLastError(ERROR_SUCCESS)
return _IsTokenRestricted(hTokenHandle)
# BOOL WINAPI LookupPrivilegeValue(
# __in_opt LPCTSTR lpSystemName,
# __in LPCTSTR lpName,
# __out PLUID lpLuid
# );
def LookupPrivilegeValueA(lpSystemName, lpName):
_LookupPrivilegeValueA = windll.advapi32.LookupPrivilegeValueA
_LookupPrivilegeValueA.argtypes = [LPSTR, LPSTR, PLUID]
_LookupPrivilegeValueA.restype = bool
_LookupPrivilegeValueA.errcheck = RaiseIfZero
lpLuid = LUID()
if not lpSystemName:
lpSystemName = None
_LookupPrivilegeValueA(lpSystemName, lpName, byref(lpLuid))
return lpLuid
def LookupPrivilegeValueW(lpSystemName, lpName):
_LookupPrivilegeValueW = windll.advapi32.LookupPrivilegeValueW
_LookupPrivilegeValueW.argtypes = [LPWSTR, LPWSTR, PLUID]
_LookupPrivilegeValueW.restype = bool
_LookupPrivilegeValueW.errcheck = RaiseIfZero
lpLuid = LUID()
if not lpSystemName:
lpSystemName = None
_LookupPrivilegeValueW(lpSystemName, lpName, byref(lpLuid))
return lpLuid
LookupPrivilegeValue = GuessStringType(LookupPrivilegeValueA, LookupPrivilegeValueW)
# BOOL WINAPI LookupPrivilegeName(
# __in_opt LPCTSTR lpSystemName,
# __in PLUID lpLuid,
# __out_opt LPTSTR lpName,
# __inout LPDWORD cchName
# );
def LookupPrivilegeNameA(lpSystemName, lpLuid):
_LookupPrivilegeNameA = windll.advapi32.LookupPrivilegeNameA
_LookupPrivilegeNameA.argtypes = [LPSTR, PLUID, LPSTR, LPDWORD]
_LookupPrivilegeNameA.restype = bool
_LookupPrivilegeNameA.errcheck = RaiseIfZero
cchName = DWORD(0)
_LookupPrivilegeNameA(lpSystemName, byref(lpLuid), NULL, byref(cchName))
lpName = ctypes.create_string_buffer("", cchName.value)
_LookupPrivilegeNameA(lpSystemName, byref(lpLuid), byref(lpName), byref(cchName))
return lpName.value
def LookupPrivilegeNameW(lpSystemName, lpLuid):
_LookupPrivilegeNameW = windll.advapi32.LookupPrivilegeNameW
_LookupPrivilegeNameW.argtypes = [LPWSTR, PLUID, LPWSTR, LPDWORD]
_LookupPrivilegeNameW.restype = bool
_LookupPrivilegeNameW.errcheck = RaiseIfZero
cchName = DWORD(0)
_LookupPrivilegeNameW(lpSystemName, byref(lpLuid), NULL, byref(cchName))
lpName = ctypes.create_unicode_buffer(u"", cchName.value)
_LookupPrivilegeNameW(lpSystemName, byref(lpLuid), byref(lpName), byref(cchName))
return lpName.value
LookupPrivilegeName = GuessStringType(LookupPrivilegeNameA, LookupPrivilegeNameW)
# BOOL WINAPI AdjustTokenPrivileges(
# __in HANDLE TokenHandle,
# __in BOOL DisableAllPrivileges,
# __in_opt PTOKEN_PRIVILEGES NewState,
# __in DWORD BufferLength,
# __out_opt PTOKEN_PRIVILEGES PreviousState,
# __out_opt PDWORD ReturnLength
# );
def AdjustTokenPrivileges(TokenHandle, NewState = ()):
_AdjustTokenPrivileges = windll.advapi32.AdjustTokenPrivileges
_AdjustTokenPrivileges.argtypes = [HANDLE, BOOL, LPVOID, DWORD, LPVOID, LPVOID]
_AdjustTokenPrivileges.restype = bool
_AdjustTokenPrivileges.errcheck = RaiseIfZero
#
# I don't know how to allocate variable sized structures in ctypes :(
# so this hack will work by using always TOKEN_PRIVILEGES of one element
# and calling the API many times. This also means the PreviousState
# parameter won't be supported yet as it's too much hassle. In a future
# version I look forward to implementing this function correctly.
#
if not NewState:
_AdjustTokenPrivileges(TokenHandle, TRUE, NULL, 0, NULL, NULL)
else:
success = True
for (privilege, enabled) in NewState:
if not isinstance(privilege, LUID):
privilege = LookupPrivilegeValue(NULL, privilege)
if enabled == True:
flags = SE_PRIVILEGE_ENABLED
elif enabled == False:
flags = SE_PRIVILEGE_REMOVED
elif enabled == None:
flags = 0
else:
flags = enabled
laa = LUID_AND_ATTRIBUTES(privilege, flags)
tp = TOKEN_PRIVILEGES(1, laa)
_AdjustTokenPrivileges(TokenHandle, FALSE, byref(tp), sizeof(tp), NULL, NULL)
# BOOL WINAPI GetTokenInformation(
# __in HANDLE TokenHandle,
# __in TOKEN_INFORMATION_CLASS TokenInformationClass,
# __out_opt LPVOID TokenInformation,
# __in DWORD TokenInformationLength,
# __out PDWORD ReturnLength
# );
def GetTokenInformation(hTokenHandle, TokenInformationClass):
if TokenInformationClass <= 0 or TokenInformationClass > MaxTokenInfoClass:
raise ValueError("Invalid value for TokenInformationClass (%i)" % TokenInformationClass)
# User SID.
if TokenInformationClass == TokenUser:
TokenInformation = TOKEN_USER()
_internal_GetTokenInformation(hTokenHandle, TokenInformationClass, TokenInformation)
return TokenInformation.User.Sid.value
# Owner SID.
if TokenInformationClass == TokenOwner:
TokenInformation = TOKEN_OWNER()
_internal_GetTokenInformation(hTokenHandle, TokenInformationClass, TokenInformation)
return TokenInformation.Owner.value
# Primary group SID.
if TokenInformationClass == TokenOwner:
TokenInformation = TOKEN_PRIMARY_GROUP()
_internal_GetTokenInformation(hTokenHandle, TokenInformationClass, TokenInformation)
return TokenInformation.PrimaryGroup.value
# App container SID.
if TokenInformationClass == TokenAppContainerSid:
TokenInformation = TOKEN_APPCONTAINER_INFORMATION()
_internal_GetTokenInformation(hTokenHandle, TokenInformationClass, TokenInformation)
return TokenInformation.TokenAppContainer.value
# Integrity level SID.
if TokenInformationClass == TokenIntegrityLevel:
TokenInformation = TOKEN_MANDATORY_LABEL()
_internal_GetTokenInformation(hTokenHandle, TokenInformationClass, TokenInformation)
return TokenInformation.Label.Sid.value, TokenInformation.Label.Attributes
# Logon session LUID.
if TokenInformationClass == TokenOrigin:
TokenInformation = TOKEN_ORIGIN()
_internal_GetTokenInformation(hTokenHandle, TokenInformationClass, TokenInformation)
return TokenInformation.OriginatingLogonSession
# Primary or impersonation token.
if TokenInformationClass == TokenType:
TokenInformation = TOKEN_TYPE(0)
_internal_GetTokenInformation(hTokenHandle, TokenInformationClass, TokenInformation)
return TokenInformation.value
# Elevated token.
if TokenInformationClass == TokenElevation:
TokenInformation = TOKEN_ELEVATION(0)
_internal_GetTokenInformation(hTokenHandle, TokenInformationClass, TokenInformation)
return TokenInformation.value
# Security impersonation level.
if TokenInformationClass == TokenElevation:
TokenInformation = SECURITY_IMPERSONATION_LEVEL(0)
_internal_GetTokenInformation(hTokenHandle, TokenInformationClass, TokenInformation)
return TokenInformation.value
# Session ID and other DWORD values.
if TokenInformationClass in (TokenSessionId, TokenAppContainerNumber):
TokenInformation = DWORD(0)
_internal_GetTokenInformation(hTokenHandle, TokenInformationClass, TokenInformation)
return TokenInformation.value
# Various boolean flags.
if TokenInformationClass in (TokenSandBoxInert, TokenHasRestrictions, TokenUIAccess,
TokenVirtualizationAllowed, TokenVirtualizationEnabled):
TokenInformation = DWORD(0)
_internal_GetTokenInformation(hTokenHandle, TokenInformationClass, TokenInformation)
return bool(TokenInformation.value)
# Linked token.
if TokenInformationClass == TokenLinkedToken:
TokenInformation = TOKEN_LINKED_TOKEN(0)
_internal_GetTokenInformation(hTokenHandle, TokenInformationClass, TokenInformation)
return TokenHandle(TokenInformation.LinkedToken.value, bOwnership = True)
# Token statistics.
if TokenInformationClass == TokenStatistics:
TokenInformation = TOKEN_STATISTICS()
_internal_GetTokenInformation(hTokenHandle, TokenInformationClass, TokenInformation)
return TokenInformation # TODO add a class wrapper?
# Currently unsupported flags.
raise NotImplementedError("TokenInformationClass(%i) not yet supported!" % TokenInformationClass)
def _internal_GetTokenInformation(hTokenHandle, TokenInformationClass, TokenInformation):
_GetTokenInformation = windll.advapi32.GetTokenInformation
_GetTokenInformation.argtypes = [HANDLE, TOKEN_INFORMATION_CLASS, LPVOID, DWORD, PDWORD]
_GetTokenInformation.restype = bool
_GetTokenInformation.errcheck = RaiseIfZero
ReturnLength = DWORD(0)
TokenInformationLength = SIZEOF(TokenInformation)
_GetTokenInformation(hTokenHandle, TokenInformationClass, byref(TokenInformation), TokenInformationLength, byref(ReturnLength))
if ReturnLength.value != TokenInformationLength:
raise ctypes.WinError(ERROR_INSUFFICIENT_BUFFER)
return TokenInformation
# BOOL WINAPI SetTokenInformation(
# __in HANDLE TokenHandle,
# __in TOKEN_INFORMATION_CLASS TokenInformationClass,
# __in LPVOID TokenInformation,
# __in DWORD TokenInformationLength
# );
# XXX TODO
# BOOL WINAPI CreateProcessWithLogonW(
# __in LPCWSTR lpUsername,
# __in_opt LPCWSTR lpDomain,
# __in LPCWSTR lpPassword,
# __in DWORD dwLogonFlags,
# __in_opt LPCWSTR lpApplicationName,
# __inout_opt LPWSTR lpCommandLine,
# __in DWORD dwCreationFlags,
# __in_opt LPVOID lpEnvironment,
# __in_opt LPCWSTR lpCurrentDirectory,
# __in LPSTARTUPINFOW lpStartupInfo,
# __out LPPROCESS_INFORMATION lpProcessInfo
# );
def CreateProcessWithLogonW(lpUsername = None, lpDomain = None, lpPassword = None, dwLogonFlags = 0, lpApplicationName = None, lpCommandLine = None, dwCreationFlags = 0, lpEnvironment = None, lpCurrentDirectory = None, lpStartupInfo = None):
_CreateProcessWithLogonW = windll.advapi32.CreateProcessWithLogonW
_CreateProcessWithLogonW.argtypes = [LPWSTR, LPWSTR, LPWSTR, DWORD, LPWSTR, LPWSTR, DWORD, LPVOID, LPWSTR, LPVOID, LPPROCESS_INFORMATION]
_CreateProcessWithLogonW.restype = bool
_CreateProcessWithLogonW.errcheck = RaiseIfZero
if not lpUsername:
lpUsername = None
if not lpDomain:
lpDomain = None
if not lpPassword:
lpPassword = None
if not lpApplicationName:
lpApplicationName = None
if not lpCommandLine:
lpCommandLine = None
else:
lpCommandLine = ctypes.create_unicode_buffer(lpCommandLine, max(MAX_PATH, len(lpCommandLine)))
if not lpEnvironment:
lpEnvironment = None
else:
lpEnvironment = ctypes.create_unicode_buffer(lpEnvironment)
if not lpCurrentDirectory:
lpCurrentDirectory = None
if not lpStartupInfo:
lpStartupInfo = STARTUPINFOW()
lpStartupInfo.cb = sizeof(STARTUPINFOW)
lpStartupInfo.lpReserved = 0
lpStartupInfo.lpDesktop = 0
lpStartupInfo.lpTitle = 0
lpStartupInfo.dwFlags = 0
lpStartupInfo.cbReserved2 = 0
lpStartupInfo.lpReserved2 = 0
lpProcessInformation = PROCESS_INFORMATION()
lpProcessInformation.hProcess = INVALID_HANDLE_VALUE
lpProcessInformation.hThread = INVALID_HANDLE_VALUE
lpProcessInformation.dwProcessId = 0
lpProcessInformation.dwThreadId = 0
_CreateProcessWithLogonW(lpUsername, lpDomain, lpPassword, dwLogonFlags, lpApplicationName, lpCommandLine, dwCreationFlags, lpEnvironment, lpCurrentDirectory, byref(lpStartupInfo), byref(lpProcessInformation))
return ProcessInformation(lpProcessInformation)
CreateProcessWithLogonA = MakeANSIVersion(CreateProcessWithLogonW)
CreateProcessWithLogon = DefaultStringType(CreateProcessWithLogonA, CreateProcessWithLogonW)
# BOOL WINAPI CreateProcessWithTokenW(
# __in HANDLE hToken,
# __in DWORD dwLogonFlags,
# __in_opt LPCWSTR lpApplicationName,
# __inout_opt LPWSTR lpCommandLine,
# __in DWORD dwCreationFlags,
# __in_opt LPVOID lpEnvironment,
# __in_opt LPCWSTR lpCurrentDirectory,
# __in LPSTARTUPINFOW lpStartupInfo,
# __out LPPROCESS_INFORMATION lpProcessInfo
# );
def CreateProcessWithTokenW(hToken = None, dwLogonFlags = 0, lpApplicationName = None, lpCommandLine = None, dwCreationFlags = 0, lpEnvironment = None, lpCurrentDirectory = None, lpStartupInfo = None):
_CreateProcessWithTokenW = windll.advapi32.CreateProcessWithTokenW
_CreateProcessWithTokenW.argtypes = [HANDLE, DWORD, LPWSTR, LPWSTR, DWORD, LPVOID, LPWSTR, LPVOID, LPPROCESS_INFORMATION]
_CreateProcessWithTokenW.restype = bool
_CreateProcessWithTokenW.errcheck = RaiseIfZero
if not hToken:
hToken = None
if not lpApplicationName:
lpApplicationName = None
if not lpCommandLine:
lpCommandLine = None
else:
lpCommandLine = ctypes.create_unicode_buffer(lpCommandLine, max(MAX_PATH, len(lpCommandLine)))
if not lpEnvironment:
lpEnvironment = None
else:
lpEnvironment = ctypes.create_unicode_buffer(lpEnvironment)
if not lpCurrentDirectory:
lpCurrentDirectory = None
if not lpStartupInfo:
lpStartupInfo = STARTUPINFOW()
lpStartupInfo.cb = sizeof(STARTUPINFOW)
lpStartupInfo.lpReserved = 0
lpStartupInfo.lpDesktop = 0
lpStartupInfo.lpTitle = 0
lpStartupInfo.dwFlags = 0
lpStartupInfo.cbReserved2 = 0
lpStartupInfo.lpReserved2 = 0
lpProcessInformation = PROCESS_INFORMATION()
lpProcessInformation.hProcess = INVALID_HANDLE_VALUE
lpProcessInformation.hThread = INVALID_HANDLE_VALUE
lpProcessInformation.dwProcessId = 0
lpProcessInformation.dwThreadId = 0
_CreateProcessWithTokenW(hToken, dwLogonFlags, lpApplicationName, lpCommandLine, dwCreationFlags, lpEnvironment, lpCurrentDirectory, byref(lpStartupInfo), byref(lpProcessInformation))
return ProcessInformation(lpProcessInformation)
CreateProcessWithTokenA = MakeANSIVersion(CreateProcessWithTokenW)
CreateProcessWithToken = DefaultStringType(CreateProcessWithTokenA, CreateProcessWithTokenW)
# BOOL WINAPI CreateProcessAsUser(
# __in_opt HANDLE hToken,
# __in_opt LPCTSTR lpApplicationName,
# __inout_opt LPTSTR lpCommandLine,
# __in_opt LPSECURITY_ATTRIBUTES lpProcessAttributes,
# __in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes,
# __in BOOL bInheritHandles,
# __in DWORD dwCreationFlags,
# __in_opt LPVOID lpEnvironment,
# __in_opt LPCTSTR lpCurrentDirectory,
# __in LPSTARTUPINFO lpStartupInfo,
# __out LPPROCESS_INFORMATION lpProcessInformation
# );
def CreateProcessAsUserA(hToken = None, lpApplicationName = None, lpCommandLine=None, lpProcessAttributes=None, lpThreadAttributes=None, bInheritHandles=False, dwCreationFlags=0, lpEnvironment=None, lpCurrentDirectory=None, lpStartupInfo=None):
_CreateProcessAsUserA = windll.advapi32.CreateProcessAsUserA
_CreateProcessAsUserA.argtypes = [HANDLE, LPSTR, LPSTR, LPSECURITY_ATTRIBUTES, LPSECURITY_ATTRIBUTES, BOOL, DWORD, LPVOID, LPSTR, LPVOID, LPPROCESS_INFORMATION]
_CreateProcessAsUserA.restype = bool
_CreateProcessAsUserA.errcheck = RaiseIfZero
if not lpApplicationName:
lpApplicationName = None
if not lpCommandLine:
lpCommandLine = None
else:
lpCommandLine = ctypes.create_string_buffer(lpCommandLine, max(MAX_PATH, len(lpCommandLine)))
if not lpEnvironment:
lpEnvironment = None
else:
lpEnvironment = ctypes.create_string_buffer(lpEnvironment)
if not lpCurrentDirectory:
lpCurrentDirectory = None
if not lpProcessAttributes:
lpProcessAttributes = None
else:
lpProcessAttributes = byref(lpProcessAttributes)
if not lpThreadAttributes:
lpThreadAttributes = None
else:
lpThreadAttributes = byref(lpThreadAttributes)
if not lpStartupInfo:
lpStartupInfo = STARTUPINFO()
lpStartupInfo.cb = sizeof(STARTUPINFO)
lpStartupInfo.lpReserved = 0
lpStartupInfo.lpDesktop = 0
lpStartupInfo.lpTitle = 0
lpStartupInfo.dwFlags = 0
lpStartupInfo.cbReserved2 = 0
lpStartupInfo.lpReserved2 = 0
lpProcessInformation = PROCESS_INFORMATION()
lpProcessInformation.hProcess = INVALID_HANDLE_VALUE
lpProcessInformation.hThread = INVALID_HANDLE_VALUE
lpProcessInformation.dwProcessId = 0
lpProcessInformation.dwThreadId = 0
_CreateProcessAsUserA(hToken, lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bool(bInheritHandles), dwCreationFlags, lpEnvironment, lpCurrentDirectory, byref(lpStartupInfo), byref(lpProcessInformation))
return ProcessInformation(lpProcessInformation)
def CreateProcessAsUserW(hToken = None, lpApplicationName = None, lpCommandLine=None, lpProcessAttributes=None, lpThreadAttributes=None, bInheritHandles=False, dwCreationFlags=0, lpEnvironment=None, lpCurrentDirectory=None, lpStartupInfo=None):
_CreateProcessAsUserW = windll.advapi32.CreateProcessAsUserW
_CreateProcessAsUserW.argtypes = [HANDLE, LPWSTR, LPWSTR, LPSECURITY_ATTRIBUTES, LPSECURITY_ATTRIBUTES, BOOL, DWORD, LPVOID, LPWSTR, LPVOID, LPPROCESS_INFORMATION]
_CreateProcessAsUserW.restype = bool
_CreateProcessAsUserW.errcheck = RaiseIfZero
if not lpApplicationName:
lpApplicationName = None
if not lpCommandLine:
lpCommandLine = None
else:
lpCommandLine = ctypes.create_unicode_buffer(lpCommandLine, max(MAX_PATH, len(lpCommandLine)))
if not lpEnvironment:
lpEnvironment = None
else:
lpEnvironment = ctypes.create_unicode_buffer(lpEnvironment)
if not lpCurrentDirectory:
lpCurrentDirectory = None
if not lpProcessAttributes:
lpProcessAttributes = None
else:
lpProcessAttributes = byref(lpProcessAttributes)
if not lpThreadAttributes:
lpThreadAttributes = None
else:
lpThreadAttributes = byref(lpThreadAttributes)
if not lpStartupInfo:
lpStartupInfo = STARTUPINFO()
lpStartupInfo.cb = sizeof(STARTUPINFO)
lpStartupInfo.lpReserved = 0
lpStartupInfo.lpDesktop = 0
lpStartupInfo.lpTitle = 0
lpStartupInfo.dwFlags = 0
lpStartupInfo.cbReserved2 = 0
lpStartupInfo.lpReserved2 = 0
lpProcessInformation = PROCESS_INFORMATION()
lpProcessInformation.hProcess = INVALID_HANDLE_VALUE
lpProcessInformation.hThread = INVALID_HANDLE_VALUE
lpProcessInformation.dwProcessId = 0
lpProcessInformation.dwThreadId = 0
_CreateProcessAsUserW(hToken, lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bool(bInheritHandles), dwCreationFlags, lpEnvironment, lpCurrentDirectory, byref(lpStartupInfo), byref(lpProcessInformation))
return ProcessInformation(lpProcessInformation)
CreateProcessAsUser = GuessStringType(CreateProcessAsUserA, CreateProcessAsUserW)
# VOID CALLBACK WaitChainCallback(
# HWCT WctHandle,
# DWORD_PTR Context,
# DWORD CallbackStatus,
# LPDWORD NodeCount,
# PWAITCHAIN_NODE_INFO NodeInfoArray,
# LPBOOL IsCycle
# );
PWAITCHAINCALLBACK = WINFUNCTYPE(HWCT, DWORD_PTR, DWORD, LPDWORD, PWAITCHAIN_NODE_INFO, LPBOOL)
# HWCT WINAPI OpenThreadWaitChainSession(
# __in DWORD Flags,
# __in_opt PWAITCHAINCALLBACK callback
# );
def OpenThreadWaitChainSession(Flags = 0, callback = None):
_OpenThreadWaitChainSession = windll.advapi32.OpenThreadWaitChainSession
_OpenThreadWaitChainSession.argtypes = [DWORD, PVOID]
_OpenThreadWaitChainSession.restype = HWCT
_OpenThreadWaitChainSession.errcheck = RaiseIfZero
if callback is not None:
callback = PWAITCHAINCALLBACK(callback)
aHandle = _OpenThreadWaitChainSession(Flags, callback)
return ThreadWaitChainSessionHandle(aHandle)
# BOOL WINAPI GetThreadWaitChain(
# _In_ HWCT WctHandle,
# _In_opt_ DWORD_PTR Context,
# _In_ DWORD Flags,
# _In_ DWORD ThreadId,
# _Inout_ LPDWORD NodeCount,
# _Out_ PWAITCHAIN_NODE_INFO NodeInfoArray,
# _Out_ LPBOOL IsCycle
# );
def GetThreadWaitChain(WctHandle, Context = None, Flags = WCTP_GETINFO_ALL_FLAGS, ThreadId = -1, NodeCount = WCT_MAX_NODE_COUNT):
_GetThreadWaitChain = windll.advapi32.GetThreadWaitChain
_GetThreadWaitChain.argtypes = [HWCT, LPDWORD, DWORD, DWORD, LPDWORD, PWAITCHAIN_NODE_INFO, LPBOOL]
_GetThreadWaitChain.restype = bool
_GetThreadWaitChain.errcheck = RaiseIfZero
dwNodeCount = DWORD(NodeCount)
NodeInfoArray = (WAITCHAIN_NODE_INFO * NodeCount)()
IsCycle = BOOL(0)
_GetThreadWaitChain(WctHandle, Context, Flags, ThreadId, byref(dwNodeCount), ctypes.cast(ctypes.pointer(NodeInfoArray), PWAITCHAIN_NODE_INFO), byref(IsCycle))
while dwNodeCount.value > NodeCount:
NodeCount = dwNodeCount.value
NodeInfoArray = (WAITCHAIN_NODE_INFO * NodeCount)()
_GetThreadWaitChain(WctHandle, Context, Flags, ThreadId, byref(dwNodeCount), ctypes.cast(ctypes.pointer(NodeInfoArray), PWAITCHAIN_NODE_INFO), byref(IsCycle))
return (
[ WaitChainNodeInfo(NodeInfoArray[index]) for index in compat.xrange(dwNodeCount.value) ],
bool(IsCycle.value)
)
# VOID WINAPI CloseThreadWaitChainSession(
# __in HWCT WctHandle
# );
def CloseThreadWaitChainSession(WctHandle):
_CloseThreadWaitChainSession = windll.advapi32.CloseThreadWaitChainSession
_CloseThreadWaitChainSession.argtypes = [HWCT]
_CloseThreadWaitChainSession(WctHandle)
# BOOL WINAPI SaferCreateLevel(
# __in DWORD dwScopeId,
# __in DWORD dwLevelId,
# __in DWORD OpenFlags,
# __out SAFER_LEVEL_HANDLE *pLevelHandle,
# __reserved LPVOID lpReserved
# );
def SaferCreateLevel(dwScopeId=SAFER_SCOPEID_USER, dwLevelId=SAFER_LEVELID_NORMALUSER, OpenFlags=0):
_SaferCreateLevel = windll.advapi32.SaferCreateLevel
_SaferCreateLevel.argtypes = [DWORD, DWORD, DWORD, POINTER(SAFER_LEVEL_HANDLE), LPVOID]
_SaferCreateLevel.restype = BOOL
_SaferCreateLevel.errcheck = RaiseIfZero
hLevelHandle = SAFER_LEVEL_HANDLE(INVALID_HANDLE_VALUE)
_SaferCreateLevel(dwScopeId, dwLevelId, OpenFlags, byref(hLevelHandle), None)
return SaferLevelHandle(hLevelHandle.value)
# BOOL WINAPI SaferIdentifyLevel(
# __in DWORD dwNumProperties,
# __in_opt PSAFER_CODE_PROPERTIES pCodeProperties,
# __out SAFER_LEVEL_HANDLE *pLevelHandle,
# __reserved LPVOID lpReserved
# );
# XXX TODO
# BOOL WINAPI SaferComputeTokenFromLevel(
# __in SAFER_LEVEL_HANDLE LevelHandle,
# __in_opt HANDLE InAccessToken,
# __out PHANDLE OutAccessToken,
# __in DWORD dwFlags,
# __inout_opt LPVOID lpReserved
# );
def SaferComputeTokenFromLevel(LevelHandle, InAccessToken=None, dwFlags=0):
_SaferComputeTokenFromLevel = windll.advapi32.SaferComputeTokenFromLevel
_SaferComputeTokenFromLevel.argtypes = [SAFER_LEVEL_HANDLE, HANDLE, PHANDLE, DWORD, LPDWORD]
_SaferComputeTokenFromLevel.restype = BOOL
_SaferComputeTokenFromLevel.errcheck = RaiseIfZero
OutAccessToken = HANDLE(INVALID_HANDLE_VALUE)
lpReserved = DWORD(0)
_SaferComputeTokenFromLevel(LevelHandle, InAccessToken, byref(OutAccessToken), dwFlags, byref(lpReserved))
return TokenHandle(OutAccessToken.value), lpReserved.value
# BOOL WINAPI SaferCloseLevel(
# __in SAFER_LEVEL_HANDLE hLevelHandle
# );
def SaferCloseLevel(hLevelHandle):
_SaferCloseLevel = windll.advapi32.SaferCloseLevel
_SaferCloseLevel.argtypes = [SAFER_LEVEL_HANDLE]
_SaferCloseLevel.restype = BOOL
_SaferCloseLevel.errcheck = RaiseIfZero
if hasattr(hLevelHandle, 'value'):
_SaferCloseLevel(hLevelHandle.value)
else:
_SaferCloseLevel(hLevelHandle)
# BOOL SaferiIsExecutableFileType(
# __in LPCWSTR szFullPath,
# __in BOOLEAN bFromShellExecute
# );
def SaferiIsExecutableFileType(szFullPath, bFromShellExecute = False):
_SaferiIsExecutableFileType = windll.advapi32.SaferiIsExecutableFileType
_SaferiIsExecutableFileType.argtypes = [LPWSTR, BOOLEAN]
_SaferiIsExecutableFileType.restype = BOOL
_SaferiIsExecutableFileType.errcheck = RaiseIfLastError
SetLastError(ERROR_SUCCESS)
return bool(_SaferiIsExecutableFileType(compat.unicode(szFullPath), bFromShellExecute))
# useful alias since I'm likely to misspell it :P
SaferIsExecutableFileType = SaferiIsExecutableFileType
#------------------------------------------------------------------------------
# LONG WINAPI RegCloseKey(
# __in HKEY hKey
# );
def RegCloseKey(hKey):
if hasattr(hKey, 'value'):
value = hKey.value
else:
value = hKey
if value in (
HKEY_CLASSES_ROOT,
HKEY_CURRENT_USER,
HKEY_LOCAL_MACHINE,
HKEY_USERS,
HKEY_PERFORMANCE_DATA,
HKEY_CURRENT_CONFIG
):
return
_RegCloseKey = windll.advapi32.RegCloseKey
_RegCloseKey.argtypes = [HKEY]
_RegCloseKey.restype = LONG
_RegCloseKey.errcheck = RaiseIfNotErrorSuccess
_RegCloseKey(hKey)
# LONG WINAPI RegConnectRegistry(
# __in_opt LPCTSTR lpMachineName,
# __in HKEY hKey,
# __out PHKEY phkResult
# );
def RegConnectRegistryA(lpMachineName = None, hKey = HKEY_LOCAL_MACHINE):
_RegConnectRegistryA = windll.advapi32.RegConnectRegistryA
_RegConnectRegistryA.argtypes = [LPSTR, HKEY, PHKEY]
_RegConnectRegistryA.restype = LONG
_RegConnectRegistryA.errcheck = RaiseIfNotErrorSuccess
hkResult = HKEY(INVALID_HANDLE_VALUE)
_RegConnectRegistryA(lpMachineName, hKey, byref(hkResult))
return RegistryKeyHandle(hkResult.value)
def RegConnectRegistryW(lpMachineName = None, hKey = HKEY_LOCAL_MACHINE):
_RegConnectRegistryW = windll.advapi32.RegConnectRegistryW
_RegConnectRegistryW.argtypes = [LPWSTR, HKEY, PHKEY]
_RegConnectRegistryW.restype = LONG
_RegConnectRegistryW.errcheck = RaiseIfNotErrorSuccess
hkResult = HKEY(INVALID_HANDLE_VALUE)
_RegConnectRegistryW(lpMachineName, hKey, byref(hkResult))
return RegistryKeyHandle(hkResult.value)
RegConnectRegistry = GuessStringType(RegConnectRegistryA, RegConnectRegistryW)
# LONG WINAPI RegCreateKey(
# __in HKEY hKey,
# __in_opt LPCTSTR lpSubKey,
# __out PHKEY phkResult
# );
def RegCreateKeyA(hKey = HKEY_LOCAL_MACHINE, lpSubKey = None):
_RegCreateKeyA = windll.advapi32.RegCreateKeyA
_RegCreateKeyA.argtypes = [HKEY, LPSTR, PHKEY]
_RegCreateKeyA.restype = LONG
_RegCreateKeyA.errcheck = RaiseIfNotErrorSuccess
hkResult = HKEY(INVALID_HANDLE_VALUE)
_RegCreateKeyA(hKey, lpSubKey, byref(hkResult))
return RegistryKeyHandle(hkResult.value)
def RegCreateKeyW(hKey = HKEY_LOCAL_MACHINE, lpSubKey = None):
_RegCreateKeyW = windll.advapi32.RegCreateKeyW
_RegCreateKeyW.argtypes = [HKEY, LPWSTR, PHKEY]
_RegCreateKeyW.restype = LONG
_RegCreateKeyW.errcheck = RaiseIfNotErrorSuccess
hkResult = HKEY(INVALID_HANDLE_VALUE)
_RegCreateKeyW(hKey, lpSubKey, byref(hkResult))
return RegistryKeyHandle(hkResult.value)
RegCreateKey = GuessStringType(RegCreateKeyA, RegCreateKeyW)
# LONG WINAPI RegCreateKeyEx(
# __in HKEY hKey,
# __in LPCTSTR lpSubKey,
# __reserved DWORD Reserved,
# __in_opt LPTSTR lpClass,
# __in DWORD dwOptions,
# __in REGSAM samDesired,
# __in_opt LPSECURITY_ATTRIBUTES lpSecurityAttributes,
# __out PHKEY phkResult,
# __out_opt LPDWORD lpdwDisposition
# );
# XXX TODO
# LONG WINAPI RegOpenKey(
# __in HKEY hKey,
# __in_opt LPCTSTR lpSubKey,
# __out PHKEY phkResult
# );
def RegOpenKeyA(hKey = HKEY_LOCAL_MACHINE, lpSubKey = None):
_RegOpenKeyA = windll.advapi32.RegOpenKeyA
_RegOpenKeyA.argtypes = [HKEY, LPSTR, PHKEY]
_RegOpenKeyA.restype = LONG
_RegOpenKeyA.errcheck = RaiseIfNotErrorSuccess
hkResult = HKEY(INVALID_HANDLE_VALUE)
_RegOpenKeyA(hKey, lpSubKey, byref(hkResult))
return RegistryKeyHandle(hkResult.value)
def RegOpenKeyW(hKey = HKEY_LOCAL_MACHINE, lpSubKey = None):
_RegOpenKeyW = windll.advapi32.RegOpenKeyW
_RegOpenKeyW.argtypes = [HKEY, LPWSTR, PHKEY]
_RegOpenKeyW.restype = LONG
_RegOpenKeyW.errcheck = RaiseIfNotErrorSuccess
hkResult = HKEY(INVALID_HANDLE_VALUE)
_RegOpenKeyW(hKey, lpSubKey, byref(hkResult))
return RegistryKeyHandle(hkResult.value)
RegOpenKey = GuessStringType(RegOpenKeyA, RegOpenKeyW)
# LONG WINAPI RegOpenKeyEx(
# __in HKEY hKey,
# __in_opt LPCTSTR lpSubKey,
# __reserved DWORD ulOptions,
# __in REGSAM samDesired,
# __out PHKEY phkResult
# );
def RegOpenKeyExA(hKey = HKEY_LOCAL_MACHINE, lpSubKey = None, samDesired = KEY_ALL_ACCESS):
_RegOpenKeyExA = windll.advapi32.RegOpenKeyExA
_RegOpenKeyExA.argtypes = [HKEY, LPSTR, DWORD, REGSAM, PHKEY]
_RegOpenKeyExA.restype = LONG
_RegOpenKeyExA.errcheck = RaiseIfNotErrorSuccess
hkResult = HKEY(INVALID_HANDLE_VALUE)
_RegOpenKeyExA(hKey, lpSubKey, 0, samDesired, byref(hkResult))
return RegistryKeyHandle(hkResult.value)
def RegOpenKeyExW(hKey = HKEY_LOCAL_MACHINE, lpSubKey = None, samDesired = KEY_ALL_ACCESS):
_RegOpenKeyExW = windll.advapi32.RegOpenKeyExW
_RegOpenKeyExW.argtypes = [HKEY, LPWSTR, DWORD, REGSAM, PHKEY]
_RegOpenKeyExW.restype = LONG
_RegOpenKeyExW.errcheck = RaiseIfNotErrorSuccess
hkResult = HKEY(INVALID_HANDLE_VALUE)
_RegOpenKeyExW(hKey, lpSubKey, 0, samDesired, byref(hkResult))
return RegistryKeyHandle(hkResult.value)
RegOpenKeyEx = GuessStringType(RegOpenKeyExA, RegOpenKeyExW)
# LONG WINAPI RegOpenCurrentUser(
# __in REGSAM samDesired,
# __out PHKEY phkResult
# );
def RegOpenCurrentUser(samDesired = KEY_ALL_ACCESS):
_RegOpenCurrentUser = windll.advapi32.RegOpenCurrentUser
_RegOpenCurrentUser.argtypes = [REGSAM, PHKEY]
_RegOpenCurrentUser.restype = LONG
_RegOpenCurrentUser.errcheck = RaiseIfNotErrorSuccess
hkResult = HKEY(INVALID_HANDLE_VALUE)
_RegOpenCurrentUser(samDesired, byref(hkResult))
return RegistryKeyHandle(hkResult.value)
# LONG WINAPI RegOpenUserClassesRoot(
# __in HANDLE hToken,
# __reserved DWORD dwOptions,
# __in REGSAM samDesired,
# __out PHKEY phkResult
# );
def RegOpenUserClassesRoot(hToken, samDesired = KEY_ALL_ACCESS):
_RegOpenUserClassesRoot = windll.advapi32.RegOpenUserClassesRoot
_RegOpenUserClassesRoot.argtypes = [HANDLE, DWORD, REGSAM, PHKEY]
_RegOpenUserClassesRoot.restype = LONG
_RegOpenUserClassesRoot.errcheck = RaiseIfNotErrorSuccess
hkResult = HKEY(INVALID_HANDLE_VALUE)
_RegOpenUserClassesRoot(hToken, 0, samDesired, byref(hkResult))
return RegistryKeyHandle(hkResult.value)
# LONG WINAPI RegQueryValue(
# __in HKEY hKey,
# __in_opt LPCTSTR lpSubKey,
# __out_opt LPTSTR lpValue,
# __inout_opt PLONG lpcbValue
# );
def RegQueryValueA(hKey, lpSubKey = None):
_RegQueryValueA = windll.advapi32.RegQueryValueA
_RegQueryValueA.argtypes = [HKEY, LPSTR, LPVOID, PLONG]
_RegQueryValueA.restype = LONG
_RegQueryValueA.errcheck = RaiseIfNotErrorSuccess
cbValue = LONG(0)
_RegQueryValueA(hKey, lpSubKey, None, byref(cbValue))
lpValue = ctypes.create_string_buffer(cbValue.value)
_RegQueryValueA(hKey, lpSubKey, lpValue, byref(cbValue))
return lpValue.value
def RegQueryValueW(hKey, lpSubKey = None):
_RegQueryValueW = windll.advapi32.RegQueryValueW
_RegQueryValueW.argtypes = [HKEY, LPWSTR, LPVOID, PLONG]
_RegQueryValueW.restype = LONG
_RegQueryValueW.errcheck = RaiseIfNotErrorSuccess
cbValue = LONG(0)
_RegQueryValueW(hKey, lpSubKey, None, byref(cbValue))
lpValue = ctypes.create_unicode_buffer(cbValue.value * sizeof(WCHAR))
_RegQueryValueW(hKey, lpSubKey, lpValue, byref(cbValue))
return lpValue.value
RegQueryValue = GuessStringType(RegQueryValueA, RegQueryValueW)
# LONG WINAPI RegQueryValueEx(
# __in HKEY hKey,
# __in_opt LPCTSTR lpValueName,
# __reserved LPDWORD lpReserved,
# __out_opt LPDWORD lpType,
# __out_opt LPBYTE lpData,
# __inout_opt LPDWORD lpcbData
# );
def _internal_RegQueryValueEx(ansi, hKey, lpValueName = None, bGetData = True):
_RegQueryValueEx = _caller_RegQueryValueEx(ansi)
cbData = DWORD(0)
dwType = DWORD(-1)
_RegQueryValueEx(hKey, lpValueName, None, byref(dwType), None, byref(cbData))
Type = dwType.value
if not bGetData:
return cbData.value, Type
if Type in (REG_DWORD, REG_DWORD_BIG_ENDIAN): # REG_DWORD_LITTLE_ENDIAN
if cbData.value != 4:
raise ValueError("REG_DWORD value of size %d" % cbData.value)
dwData = DWORD(0)
_RegQueryValueEx(hKey, lpValueName, None, None, byref(dwData), byref(cbData))
return dwData.value, Type
if Type == REG_QWORD: # REG_QWORD_LITTLE_ENDIAN
if cbData.value != 8:
raise ValueError("REG_QWORD value of size %d" % cbData.value)
qwData = QWORD(long(0))
_RegQueryValueEx(hKey, lpValueName, None, None, byref(qwData), byref(cbData))
return qwData.value, Type
if Type in (REG_SZ, REG_EXPAND_SZ):
if ansi:
szData = ctypes.create_string_buffer(cbData.value)
else:
szData = ctypes.create_unicode_buffer(cbData.value)
_RegQueryValueEx(hKey, lpValueName, None, None, byref(szData), byref(cbData))
return szData.value, Type
if Type == REG_MULTI_SZ:
if ansi:
szData = ctypes.create_string_buffer(cbData.value)
else:
szData = ctypes.create_unicode_buffer(cbData.value)
_RegQueryValueEx(hKey, lpValueName, None, None, byref(szData), byref(cbData))
Data = szData[:]
if ansi:
aData = Data.split('\0')
else:
aData = Data.split(u'\0')
aData = [token for token in aData if token]
return aData, Type
if Type == REG_LINK:
szData = ctypes.create_unicode_buffer(cbData.value)
_RegQueryValueEx(hKey, lpValueName, None, None, byref(szData), byref(cbData))
return szData.value, Type
# REG_BINARY, REG_NONE, and any future types
szData = ctypes.create_string_buffer(cbData.value)
_RegQueryValueEx(hKey, lpValueName, None, None, byref(szData), byref(cbData))
return szData.raw, Type
def _caller_RegQueryValueEx(ansi):
if ansi:
_RegQueryValueEx = windll.advapi32.RegQueryValueExA
_RegQueryValueEx.argtypes = [HKEY, LPSTR, LPVOID, PDWORD, LPVOID, PDWORD]
else:
_RegQueryValueEx = windll.advapi32.RegQueryValueExW
_RegQueryValueEx.argtypes = [HKEY, LPWSTR, LPVOID, PDWORD, LPVOID, PDWORD]
_RegQueryValueEx.restype = LONG
_RegQueryValueEx.errcheck = RaiseIfNotErrorSuccess
return _RegQueryValueEx
# see _internal_RegQueryValueEx
def RegQueryValueExA(hKey, lpValueName = None, bGetData = True):
return _internal_RegQueryValueEx(True, hKey, lpValueName, bGetData)
# see _internal_RegQueryValueEx
def RegQueryValueExW(hKey, lpValueName = None, bGetData = True):
return _internal_RegQueryValueEx(False, hKey, lpValueName, bGetData)
RegQueryValueEx = GuessStringType(RegQueryValueExA, RegQueryValueExW)
# LONG WINAPI RegSetValueEx(
# __in HKEY hKey,
# __in_opt LPCTSTR lpValueName,
# __reserved DWORD Reserved,
# __in DWORD dwType,
# __in_opt const BYTE *lpData,
# __in DWORD cbData
# );
def RegSetValueEx(hKey, lpValueName = None, lpData = None, dwType = None):
# Determine which version of the API to use, ANSI or Widechar.
if lpValueName is None:
if isinstance(lpData, GuessStringType.t_ansi):
ansi = True
elif isinstance(lpData, GuessStringType.t_unicode):
ansi = False
else:
ansi = (GuessStringType.t_ansi == GuessStringType.t_default)
elif isinstance(lpValueName, GuessStringType.t_ansi):
ansi = True
elif isinstance(lpValueName, GuessStringType.t_unicode):
ansi = False
else:
raise TypeError("String expected, got %s instead" % type(lpValueName))
# Autodetect the type when not given.
# TODO: improve detection of DWORD and QWORD by seeing if the value "fits".
if dwType is None:
if lpValueName is None:
dwType = REG_SZ
elif lpData is None:
dwType = REG_NONE
elif isinstance(lpData, GuessStringType.t_ansi):
dwType = REG_SZ
elif isinstance(lpData, GuessStringType.t_unicode):
dwType = REG_SZ
elif isinstance(lpData, int):
dwType = REG_DWORD
elif isinstance(lpData, long):
dwType = REG_QWORD
else:
dwType = REG_BINARY
# Load the ctypes caller.
if ansi:
_RegSetValueEx = windll.advapi32.RegSetValueExA
_RegSetValueEx.argtypes = [HKEY, LPSTR, DWORD, DWORD, LPVOID, DWORD]
else:
_RegSetValueEx = windll.advapi32.RegSetValueExW
_RegSetValueEx.argtypes = [HKEY, LPWSTR, DWORD, DWORD, LPVOID, DWORD]
_RegSetValueEx.restype = LONG
_RegSetValueEx.errcheck = RaiseIfNotErrorSuccess
# Convert the arguments so ctypes can understand them.
if lpData is None:
DataRef = None
DataSize = 0
else:
if dwType in (REG_DWORD, REG_DWORD_BIG_ENDIAN): # REG_DWORD_LITTLE_ENDIAN
Data = DWORD(lpData)
elif dwType == REG_QWORD: # REG_QWORD_LITTLE_ENDIAN
Data = QWORD(lpData)
elif dwType in (REG_SZ, REG_EXPAND_SZ):
if ansi:
Data = ctypes.create_string_buffer(lpData)
else:
Data = ctypes.create_unicode_buffer(lpData)
elif dwType == REG_MULTI_SZ:
if ansi:
Data = ctypes.create_string_buffer('\0'.join(lpData) + '\0\0')
else:
Data = ctypes.create_unicode_buffer(u'\0'.join(lpData) + u'\0\0')
elif dwType == REG_LINK:
Data = ctypes.create_unicode_buffer(lpData)
else:
Data = ctypes.create_string_buffer(lpData)
DataRef = byref(Data)
DataSize = sizeof(Data)
# Call the API with the converted arguments.
_RegSetValueEx(hKey, lpValueName, 0, dwType, DataRef, DataSize)
# No "GuessStringType" here since detection is done inside.
RegSetValueExA = RegSetValueExW = RegSetValueEx
# LONG WINAPI RegEnumKey(
# __in HKEY hKey,
# __in DWORD dwIndex,
# __out LPTSTR lpName,
# __in DWORD cchName
# );
def RegEnumKeyA(hKey, dwIndex):
_RegEnumKeyA = windll.advapi32.RegEnumKeyA
_RegEnumKeyA.argtypes = [HKEY, DWORD, LPSTR, DWORD]
_RegEnumKeyA.restype = LONG
cchName = 1024
while True:
lpName = ctypes.create_string_buffer(cchName)
errcode = _RegEnumKeyA(hKey, dwIndex, lpName, cchName)
if errcode != ERROR_MORE_DATA:
break
cchName = cchName + 1024
if cchName > 65536:
raise ctypes.WinError(errcode)
if errcode == ERROR_NO_MORE_ITEMS:
return None
if errcode != ERROR_SUCCESS:
raise ctypes.WinError(errcode)
return lpName.value
def RegEnumKeyW(hKey, dwIndex):
_RegEnumKeyW = windll.advapi32.RegEnumKeyW
_RegEnumKeyW.argtypes = [HKEY, DWORD, LPWSTR, DWORD]
_RegEnumKeyW.restype = LONG
cchName = 512
while True:
lpName = ctypes.create_unicode_buffer(cchName)
errcode = _RegEnumKeyW(hKey, dwIndex, lpName, cchName * 2)
if errcode != ERROR_MORE_DATA:
break
cchName = cchName + 512
if cchName > 32768:
raise ctypes.WinError(errcode)
if errcode == ERROR_NO_MORE_ITEMS:
return None
if errcode != ERROR_SUCCESS:
raise ctypes.WinError(errcode)
return lpName.value
RegEnumKey = DefaultStringType(RegEnumKeyA, RegEnumKeyW)
# LONG WINAPI RegEnumKeyEx(
# __in HKEY hKey,
# __in DWORD dwIndex,
# __out LPTSTR lpName,
# __inout LPDWORD lpcName,
# __reserved LPDWORD lpReserved,
# __inout LPTSTR lpClass,
# __inout_opt LPDWORD lpcClass,
# __out_opt PFILETIME lpftLastWriteTime
# );
# XXX TODO
# LONG WINAPI RegEnumValue(
# __in HKEY hKey,
# __in DWORD dwIndex,
# __out LPTSTR lpValueName,
# __inout LPDWORD lpcchValueName,
# __reserved LPDWORD lpReserved,
# __out_opt LPDWORD lpType,
# __out_opt LPBYTE lpData,
# __inout_opt LPDWORD lpcbData
# );
def _internal_RegEnumValue(ansi, hKey, dwIndex, bGetData = True):
if ansi:
_RegEnumValue = windll.advapi32.RegEnumValueA
_RegEnumValue.argtypes = [HKEY, DWORD, LPSTR, LPDWORD, LPVOID, LPDWORD, LPVOID, LPDWORD]
else:
_RegEnumValue = windll.advapi32.RegEnumValueW
_RegEnumValue.argtypes = [HKEY, DWORD, LPWSTR, LPDWORD, LPVOID, LPDWORD, LPVOID, LPDWORD]
_RegEnumValue.restype = LONG
cchValueName = DWORD(1024)
dwType = DWORD(-1)
lpcchValueName = byref(cchValueName)
lpType = byref(dwType)
if ansi:
lpValueName = ctypes.create_string_buffer(cchValueName.value)
else:
lpValueName = ctypes.create_unicode_buffer(cchValueName.value)
if bGetData:
cbData = DWORD(0)
lpcbData = byref(cbData)
else:
lpcbData = None
lpData = None
errcode = _RegEnumValue(hKey, dwIndex, lpValueName, lpcchValueName, None, lpType, lpData, lpcbData)
if errcode == ERROR_MORE_DATA or (bGetData and errcode == ERROR_SUCCESS):
if ansi:
cchValueName.value = cchValueName.value + sizeof(CHAR)
lpValueName = ctypes.create_string_buffer(cchValueName.value)
else:
cchValueName.value = cchValueName.value + sizeof(WCHAR)
lpValueName = ctypes.create_unicode_buffer(cchValueName.value)
if bGetData:
Type = dwType.value
if Type in (REG_DWORD, REG_DWORD_BIG_ENDIAN): # REG_DWORD_LITTLE_ENDIAN
if cbData.value != sizeof(DWORD):
raise ValueError("REG_DWORD value of size %d" % cbData.value)
Data = DWORD(0)
elif Type == REG_QWORD: # REG_QWORD_LITTLE_ENDIAN
if cbData.value != sizeof(QWORD):
raise ValueError("REG_QWORD value of size %d" % cbData.value)
Data = QWORD(long(0))
elif Type in (REG_SZ, REG_EXPAND_SZ, REG_MULTI_SZ):
if ansi:
Data = ctypes.create_string_buffer(cbData.value)
else:
Data = ctypes.create_unicode_buffer(cbData.value)
elif Type == REG_LINK:
Data = ctypes.create_unicode_buffer(cbData.value)
else: # REG_BINARY, REG_NONE, and any future types
Data = ctypes.create_string_buffer(cbData.value)
lpData = byref(Data)
errcode = _RegEnumValue(hKey, dwIndex, lpValueName, lpcchValueName, None, lpType, lpData, lpcbData)
if errcode == ERROR_NO_MORE_ITEMS:
return None
#if errcode != ERROR_SUCCESS:
# raise ctypes.WinError(errcode)
if not bGetData:
return lpValueName.value, dwType.value
if Type in (REG_DWORD, REG_DWORD_BIG_ENDIAN, REG_QWORD, REG_SZ, REG_EXPAND_SZ, REG_LINK): # REG_DWORD_LITTLE_ENDIAN, REG_QWORD_LITTLE_ENDIAN
return lpValueName.value, dwType.value, Data.value
if Type == REG_MULTI_SZ:
sData = Data[:]
del Data
if ansi:
aData = sData.split('\0')
else:
aData = sData.split(u'\0')
aData = [token for token in aData if token]
return lpValueName.value, dwType.value, aData
# REG_BINARY, REG_NONE, and any future types
return lpValueName.value, dwType.value, Data.raw
def RegEnumValueA(hKey, dwIndex, bGetData = True):
return _internal_RegEnumValue(True, hKey, dwIndex, bGetData)
def RegEnumValueW(hKey, dwIndex, bGetData = True):
return _internal_RegEnumValue(False, hKey, dwIndex, bGetData)
RegEnumValue = DefaultStringType(RegEnumValueA, RegEnumValueW)
# XXX TODO
# LONG WINAPI RegSetKeyValue(
# __in HKEY hKey,
# __in_opt LPCTSTR lpSubKey,
# __in_opt LPCTSTR lpValueName,
# __in DWORD dwType,
# __in_opt LPCVOID lpData,
# __in DWORD cbData
# );
# XXX TODO
# LONG WINAPI RegQueryMultipleValues(
# __in HKEY hKey,
# __out PVALENT val_list,
# __in DWORD num_vals,
# __out_opt LPTSTR lpValueBuf,
# __inout_opt LPDWORD ldwTotsize
# );
# XXX TODO
# LONG WINAPI RegDeleteValue(
# __in HKEY hKey,
# __in_opt LPCTSTR lpValueName
# );
def RegDeleteValueA(hKeySrc, lpValueName = None):
_RegDeleteValueA = windll.advapi32.RegDeleteValueA
_RegDeleteValueA.argtypes = [HKEY, LPSTR]
_RegDeleteValueA.restype = LONG
_RegDeleteValueA.errcheck = RaiseIfNotErrorSuccess
_RegDeleteValueA(hKeySrc, lpValueName)
def RegDeleteValueW(hKeySrc, lpValueName = None):
_RegDeleteValueW = windll.advapi32.RegDeleteValueW
_RegDeleteValueW.argtypes = [HKEY, LPWSTR]
_RegDeleteValueW.restype = LONG
_RegDeleteValueW.errcheck = RaiseIfNotErrorSuccess
_RegDeleteValueW(hKeySrc, lpValueName)
RegDeleteValue = GuessStringType(RegDeleteValueA, RegDeleteValueW)
# LONG WINAPI RegDeleteKeyValue(
# __in HKEY hKey,
# __in_opt LPCTSTR lpSubKey,
# __in_opt LPCTSTR lpValueName
# );
def RegDeleteKeyValueA(hKeySrc, lpSubKey = None, lpValueName = None):
_RegDeleteKeyValueA = windll.advapi32.RegDeleteKeyValueA
_RegDeleteKeyValueA.argtypes = [HKEY, LPSTR, LPSTR]
_RegDeleteKeyValueA.restype = LONG
_RegDeleteKeyValueA.errcheck = RaiseIfNotErrorSuccess
_RegDeleteKeyValueA(hKeySrc, lpSubKey, lpValueName)
def RegDeleteKeyValueW(hKeySrc, lpSubKey = None, lpValueName = None):
_RegDeleteKeyValueW = windll.advapi32.RegDeleteKeyValueW
_RegDeleteKeyValueW.argtypes = [HKEY, LPWSTR, LPWSTR]
_RegDeleteKeyValueW.restype = LONG
_RegDeleteKeyValueW.errcheck = RaiseIfNotErrorSuccess
_RegDeleteKeyValueW(hKeySrc, lpSubKey, lpValueName)
RegDeleteKeyValue = GuessStringType(RegDeleteKeyValueA, RegDeleteKeyValueW)
# LONG WINAPI RegDeleteKey(
# __in HKEY hKey,
# __in LPCTSTR lpSubKey
# );
def RegDeleteKeyA(hKeySrc, lpSubKey = None):
_RegDeleteKeyA = windll.advapi32.RegDeleteKeyA
_RegDeleteKeyA.argtypes = [HKEY, LPSTR]
_RegDeleteKeyA.restype = LONG
_RegDeleteKeyA.errcheck = RaiseIfNotErrorSuccess
_RegDeleteKeyA(hKeySrc, lpSubKey)
def RegDeleteKeyW(hKeySrc, lpSubKey = None):
_RegDeleteKeyW = windll.advapi32.RegDeleteKeyW
_RegDeleteKeyW.argtypes = [HKEY, LPWSTR]
_RegDeleteKeyW.restype = LONG
_RegDeleteKeyW.errcheck = RaiseIfNotErrorSuccess
_RegDeleteKeyW(hKeySrc, lpSubKey)
RegDeleteKey = GuessStringType(RegDeleteKeyA, RegDeleteKeyW)
# LONG WINAPI RegDeleteKeyEx(
# __in HKEY hKey,
# __in LPCTSTR lpSubKey,
# __in REGSAM samDesired,
# __reserved DWORD Reserved
# );
def RegDeleteKeyExA(hKeySrc, lpSubKey = None, samDesired = KEY_WOW64_32KEY):
_RegDeleteKeyExA = windll.advapi32.RegDeleteKeyExA
_RegDeleteKeyExA.argtypes = [HKEY, LPSTR, REGSAM, DWORD]
_RegDeleteKeyExA.restype = LONG
_RegDeleteKeyExA.errcheck = RaiseIfNotErrorSuccess
_RegDeleteKeyExA(hKeySrc, lpSubKey, samDesired, 0)
def RegDeleteKeyExW(hKeySrc, lpSubKey = None, samDesired = KEY_WOW64_32KEY):
_RegDeleteKeyExW = windll.advapi32.RegDeleteKeyExW
_RegDeleteKeyExW.argtypes = [HKEY, LPWSTR, REGSAM, DWORD]
_RegDeleteKeyExW.restype = LONG
_RegDeleteKeyExW.errcheck = RaiseIfNotErrorSuccess
_RegDeleteKeyExW(hKeySrc, lpSubKey, samDesired, 0)
RegDeleteKeyEx = GuessStringType(RegDeleteKeyExA, RegDeleteKeyExW)
# LONG WINAPI RegCopyTree(
# __in HKEY hKeySrc,
# __in_opt LPCTSTR lpSubKey,
# __in HKEY hKeyDest
# );
def RegCopyTreeA(hKeySrc, lpSubKey, hKeyDest):
_RegCopyTreeA = windll.advapi32.RegCopyTreeA
_RegCopyTreeA.argtypes = [HKEY, LPSTR, HKEY]
_RegCopyTreeA.restype = LONG
_RegCopyTreeA.errcheck = RaiseIfNotErrorSuccess
_RegCopyTreeA(hKeySrc, lpSubKey, hKeyDest)
def RegCopyTreeW(hKeySrc, lpSubKey, hKeyDest):
_RegCopyTreeW = windll.advapi32.RegCopyTreeW
_RegCopyTreeW.argtypes = [HKEY, LPWSTR, HKEY]
_RegCopyTreeW.restype = LONG
_RegCopyTreeW.errcheck = RaiseIfNotErrorSuccess
_RegCopyTreeW(hKeySrc, lpSubKey, hKeyDest)
RegCopyTree = GuessStringType(RegCopyTreeA, RegCopyTreeW)
# LONG WINAPI RegDeleteTree(
# __in HKEY hKey,
# __in_opt LPCTSTR lpSubKey
# );
def RegDeleteTreeA(hKey, lpSubKey = None):
_RegDeleteTreeA = windll.advapi32.RegDeleteTreeA
_RegDeleteTreeA.argtypes = [HKEY, LPWSTR]
_RegDeleteTreeA.restype = LONG
_RegDeleteTreeA.errcheck = RaiseIfNotErrorSuccess
_RegDeleteTreeA(hKey, lpSubKey)
def RegDeleteTreeW(hKey, lpSubKey = None):
_RegDeleteTreeW = windll.advapi32.RegDeleteTreeW
_RegDeleteTreeW.argtypes = [HKEY, LPWSTR]
_RegDeleteTreeW.restype = LONG
_RegDeleteTreeW.errcheck = RaiseIfNotErrorSuccess
_RegDeleteTreeW(hKey, lpSubKey)
RegDeleteTree = GuessStringType(RegDeleteTreeA, RegDeleteTreeW)
# LONG WINAPI RegFlushKey(
# __in HKEY hKey
# );
def RegFlushKey(hKey):
_RegFlushKey = windll.advapi32.RegFlushKey
_RegFlushKey.argtypes = [HKEY]
_RegFlushKey.restype = LONG
_RegFlushKey.errcheck = RaiseIfNotErrorSuccess
_RegFlushKey(hKey)
# LONG WINAPI RegLoadMUIString(
# _In_ HKEY hKey,
# _In_opt_ LPCTSTR pszValue,
# _Out_opt_ LPTSTR pszOutBuf,
# _In_ DWORD cbOutBuf,
# _Out_opt_ LPDWORD pcbData,
# _In_ DWORD Flags,
# _In_opt_ LPCTSTR pszDirectory
# );
# TO DO
#------------------------------------------------------------------------------
# BOOL WINAPI CloseServiceHandle(
# _In_ SC_HANDLE hSCObject
# );
def CloseServiceHandle(hSCObject):
_CloseServiceHandle = windll.advapi32.CloseServiceHandle
_CloseServiceHandle.argtypes = [SC_HANDLE]
_CloseServiceHandle.restype = bool
_CloseServiceHandle.errcheck = RaiseIfZero
if isinstance(hSCObject, Handle):
# Prevents the handle from being closed without notifying the Handle object.
hSCObject.close()
else:
_CloseServiceHandle(hSCObject)
# SC_HANDLE WINAPI OpenSCManager(
# _In_opt_ LPCTSTR lpMachineName,
# _In_opt_ LPCTSTR lpDatabaseName,
# _In_ DWORD dwDesiredAccess
# );
def OpenSCManagerA(lpMachineName = None, lpDatabaseName = None, dwDesiredAccess = SC_MANAGER_ALL_ACCESS):
_OpenSCManagerA = windll.advapi32.OpenSCManagerA
_OpenSCManagerA.argtypes = [LPSTR, LPSTR, DWORD]
_OpenSCManagerA.restype = SC_HANDLE
_OpenSCManagerA.errcheck = RaiseIfZero
hSCObject = _OpenSCManagerA(lpMachineName, lpDatabaseName, dwDesiredAccess)
return ServiceControlManagerHandle(hSCObject)
def OpenSCManagerW(lpMachineName = None, lpDatabaseName = None, dwDesiredAccess = SC_MANAGER_ALL_ACCESS):
_OpenSCManagerW = windll.advapi32.OpenSCManagerW
_OpenSCManagerW.argtypes = [LPWSTR, LPWSTR, DWORD]
_OpenSCManagerW.restype = SC_HANDLE
_OpenSCManagerW.errcheck = RaiseIfZero
hSCObject = _OpenSCManagerA(lpMachineName, lpDatabaseName, dwDesiredAccess)
return ServiceControlManagerHandle(hSCObject)
OpenSCManager = GuessStringType(OpenSCManagerA, OpenSCManagerW)
# SC_HANDLE WINAPI OpenService(
# _In_ SC_HANDLE hSCManager,
# _In_ LPCTSTR lpServiceName,
# _In_ DWORD dwDesiredAccess
# );
def OpenServiceA(hSCManager, lpServiceName, dwDesiredAccess = SERVICE_ALL_ACCESS):
_OpenServiceA = windll.advapi32.OpenServiceA
_OpenServiceA.argtypes = [SC_HANDLE, LPSTR, DWORD]
_OpenServiceA.restype = SC_HANDLE
_OpenServiceA.errcheck = RaiseIfZero
return ServiceHandle( _OpenServiceA(hSCManager, lpServiceName, dwDesiredAccess) )
def OpenServiceW(hSCManager, lpServiceName, dwDesiredAccess = SERVICE_ALL_ACCESS):
_OpenServiceW = windll.advapi32.OpenServiceW
_OpenServiceW.argtypes = [SC_HANDLE, LPWSTR, DWORD]
_OpenServiceW.restype = SC_HANDLE
_OpenServiceW.errcheck = RaiseIfZero
return ServiceHandle( _OpenServiceW(hSCManager, lpServiceName, dwDesiredAccess) )
OpenService = GuessStringType(OpenServiceA, OpenServiceW)
# SC_HANDLE WINAPI CreateService(
# _In_ SC_HANDLE hSCManager,
# _In_ LPCTSTR lpServiceName,
# _In_opt_ LPCTSTR lpDisplayName,
# _In_ DWORD dwDesiredAccess,
# _In_ DWORD dwServiceType,
# _In_ DWORD dwStartType,
# _In_ DWORD dwErrorControl,
# _In_opt_ LPCTSTR lpBinaryPathName,
# _In_opt_ LPCTSTR lpLoadOrderGroup,
# _Out_opt_ LPDWORD lpdwTagId,
# _In_opt_ LPCTSTR lpDependencies,
# _In_opt_ LPCTSTR lpServiceStartName,
# _In_opt_ LPCTSTR lpPassword
# );
def CreateServiceA(hSCManager, lpServiceName,
lpDisplayName = None,
dwDesiredAccess = SERVICE_ALL_ACCESS,
dwServiceType = SERVICE_WIN32_OWN_PROCESS,
dwStartType = SERVICE_DEMAND_START,
dwErrorControl = SERVICE_ERROR_NORMAL,
lpBinaryPathName = None,
lpLoadOrderGroup = None,
lpDependencies = None,
lpServiceStartName = None,
lpPassword = None):
_CreateServiceA = windll.advapi32.CreateServiceA
_CreateServiceA.argtypes = [SC_HANDLE, LPSTR, LPSTR, DWORD, DWORD, DWORD, DWORD, LPSTR, LPSTR, LPDWORD, LPSTR, LPSTR, LPSTR]
_CreateServiceA.restype = SC_HANDLE
_CreateServiceA.errcheck = RaiseIfZero
dwTagId = DWORD(0)
hService = _CreateServiceA(hSCManager, lpServiceName, dwDesiredAccess, dwServiceType, dwStartType, dwErrorControl, lpBinaryPathName, lpLoadOrderGroup, byref(dwTagId), lpDependencies, lpServiceStartName, lpPassword)
return ServiceHandle(hService), dwTagId.value
def CreateServiceW(hSCManager, lpServiceName,
lpDisplayName = None,
dwDesiredAccess = SERVICE_ALL_ACCESS,
dwServiceType = SERVICE_WIN32_OWN_PROCESS,
dwStartType = SERVICE_DEMAND_START,
dwErrorControl = SERVICE_ERROR_NORMAL,
lpBinaryPathName = None,
lpLoadOrderGroup = None,
lpDependencies = None,
lpServiceStartName = None,
lpPassword = None):
_CreateServiceW = windll.advapi32.CreateServiceW
_CreateServiceW.argtypes = [SC_HANDLE, LPWSTR, LPWSTR, DWORD, DWORD, DWORD, DWORD, LPWSTR, LPWSTR, LPDWORD, LPWSTR, LPWSTR, LPWSTR]
_CreateServiceW.restype = SC_HANDLE
_CreateServiceW.errcheck = RaiseIfZero
dwTagId = DWORD(0)
hService = _CreateServiceW(hSCManager, lpServiceName, dwDesiredAccess, dwServiceType, dwStartType, dwErrorControl, lpBinaryPathName, lpLoadOrderGroup, byref(dwTagId), lpDependencies, lpServiceStartName, lpPassword)
return ServiceHandle(hService), dwTagId.value
CreateService = GuessStringType(CreateServiceA, CreateServiceW)
# BOOL WINAPI DeleteService(
# _In_ SC_HANDLE hService
# );
def DeleteService(hService):
_DeleteService = windll.advapi32.DeleteService
_DeleteService.argtypes = [SC_HANDLE]
_DeleteService.restype = bool
_DeleteService.errcheck = RaiseIfZero
_DeleteService(hService)
# BOOL WINAPI GetServiceKeyName(
# _In_ SC_HANDLE hSCManager,
# _In_ LPCTSTR lpDisplayName,
# _Out_opt_ LPTSTR lpServiceName,
# _Inout_ LPDWORD lpcchBuffer
# );
def GetServiceKeyNameA(hSCManager, lpDisplayName):
_GetServiceKeyNameA = windll.advapi32.GetServiceKeyNameA
_GetServiceKeyNameA.argtypes = [SC_HANDLE, LPSTR, LPSTR, LPDWORD]
_GetServiceKeyNameA.restype = bool
cchBuffer = DWORD(0)
_GetServiceKeyNameA(hSCManager, lpDisplayName, None, byref(cchBuffer))
if cchBuffer.value == 0:
raise ctypes.WinError()
lpServiceName = ctypes.create_string_buffer(cchBuffer.value + 1)
cchBuffer.value = sizeof(lpServiceName)
success = _GetServiceKeyNameA(hSCManager, lpDisplayName, lpServiceName, byref(cchBuffer))
if not success:
raise ctypes.WinError()
return lpServiceName.value
def GetServiceKeyNameW(hSCManager, lpDisplayName):
_GetServiceKeyNameW = windll.advapi32.GetServiceKeyNameW
_GetServiceKeyNameW.argtypes = [SC_HANDLE, LPWSTR, LPWSTR, LPDWORD]
_GetServiceKeyNameW.restype = bool
cchBuffer = DWORD(0)
_GetServiceKeyNameW(hSCManager, lpDisplayName, None, byref(cchBuffer))
if cchBuffer.value == 0:
raise ctypes.WinError()
lpServiceName = ctypes.create_unicode_buffer(cchBuffer.value + 2)
cchBuffer.value = sizeof(lpServiceName)
success = _GetServiceKeyNameW(hSCManager, lpDisplayName, lpServiceName, byref(cchBuffer))
if not success:
raise ctypes.WinError()
return lpServiceName.value
GetServiceKeyName = GuessStringType(GetServiceKeyNameA, GetServiceKeyNameW)
# BOOL WINAPI GetServiceDisplayName(
# _In_ SC_HANDLE hSCManager,
# _In_ LPCTSTR lpServiceName,
# _Out_opt_ LPTSTR lpDisplayName,
# _Inout_ LPDWORD lpcchBuffer
# );
def GetServiceDisplayNameA(hSCManager, lpServiceName):
_GetServiceDisplayNameA = windll.advapi32.GetServiceDisplayNameA
_GetServiceDisplayNameA.argtypes = [SC_HANDLE, LPSTR, LPSTR, LPDWORD]
_GetServiceDisplayNameA.restype = bool
cchBuffer = DWORD(0)
_GetServiceDisplayNameA(hSCManager, lpServiceName, None, byref(cchBuffer))
if cchBuffer.value == 0:
raise ctypes.WinError()
lpDisplayName = ctypes.create_string_buffer(cchBuffer.value + 1)
cchBuffer.value = sizeof(lpDisplayName)
success = _GetServiceDisplayNameA(hSCManager, lpServiceName, lpDisplayName, byref(cchBuffer))
if not success:
raise ctypes.WinError()
return lpDisplayName.value
def GetServiceDisplayNameW(hSCManager, lpServiceName):
_GetServiceDisplayNameW = windll.advapi32.GetServiceDisplayNameW
_GetServiceDisplayNameW.argtypes = [SC_HANDLE, LPWSTR, LPWSTR, LPDWORD]
_GetServiceDisplayNameW.restype = bool
cchBuffer = DWORD(0)
_GetServiceDisplayNameW(hSCManager, lpServiceName, None, byref(cchBuffer))
if cchBuffer.value == 0:
raise ctypes.WinError()
lpDisplayName = ctypes.create_unicode_buffer(cchBuffer.value + 2)
cchBuffer.value = sizeof(lpDisplayName)
success = _GetServiceDisplayNameW(hSCManager, lpServiceName, lpDisplayName, byref(cchBuffer))
if not success:
raise ctypes.WinError()
return lpDisplayName.value
GetServiceDisplayName = GuessStringType(GetServiceDisplayNameA, GetServiceDisplayNameW)
# BOOL WINAPI QueryServiceConfig(
# _In_ SC_HANDLE hService,
# _Out_opt_ LPQUERY_SERVICE_CONFIG lpServiceConfig,
# _In_ DWORD cbBufSize,
# _Out_ LPDWORD pcbBytesNeeded
# );
# TO DO
# BOOL WINAPI QueryServiceConfig2(
# _In_ SC_HANDLE hService,
# _In_ DWORD dwInfoLevel,
# _Out_opt_ LPBYTE lpBuffer,
# _In_ DWORD cbBufSize,
# _Out_ LPDWORD pcbBytesNeeded
# );
# TO DO
# BOOL WINAPI ChangeServiceConfig(
# _In_ SC_HANDLE hService,
# _In_ DWORD dwServiceType,
# _In_ DWORD dwStartType,
# _In_ DWORD dwErrorControl,
# _In_opt_ LPCTSTR lpBinaryPathName,
# _In_opt_ LPCTSTR lpLoadOrderGroup,
# _Out_opt_ LPDWORD lpdwTagId,
# _In_opt_ LPCTSTR lpDependencies,
# _In_opt_ LPCTSTR lpServiceStartName,
# _In_opt_ LPCTSTR lpPassword,
# _In_opt_ LPCTSTR lpDisplayName
# );
# TO DO
# BOOL WINAPI ChangeServiceConfig2(
# _In_ SC_HANDLE hService,
# _In_ DWORD dwInfoLevel,
# _In_opt_ LPVOID lpInfo
# );
# TO DO
# BOOL WINAPI StartService(
# _In_ SC_HANDLE hService,
# _In_ DWORD dwNumServiceArgs,
# _In_opt_ LPCTSTR *lpServiceArgVectors
# );
def StartServiceA(hService, ServiceArgVectors = None):
_StartServiceA = windll.advapi32.StartServiceA
_StartServiceA.argtypes = [SC_HANDLE, DWORD, LPVOID]
_StartServiceA.restype = bool
_StartServiceA.errcheck = RaiseIfZero
if ServiceArgVectors:
dwNumServiceArgs = len(ServiceArgVectors)
CServiceArgVectors = (LPSTR * dwNumServiceArgs)(*ServiceArgVectors)
lpServiceArgVectors = ctypes.pointer(CServiceArgVectors)
else:
dwNumServiceArgs = 0
lpServiceArgVectors = None
_StartServiceA(hService, dwNumServiceArgs, lpServiceArgVectors)
def StartServiceW(hService, ServiceArgVectors = None):
_StartServiceW = windll.advapi32.StartServiceW
_StartServiceW.argtypes = [SC_HANDLE, DWORD, LPVOID]
_StartServiceW.restype = bool
_StartServiceW.errcheck = RaiseIfZero
if ServiceArgVectors:
dwNumServiceArgs = len(ServiceArgVectors)
CServiceArgVectors = (LPWSTR * dwNumServiceArgs)(*ServiceArgVectors)
lpServiceArgVectors = ctypes.pointer(CServiceArgVectors)
else:
dwNumServiceArgs = 0
lpServiceArgVectors = None
_StartServiceW(hService, dwNumServiceArgs, lpServiceArgVectors)
StartService = GuessStringType(StartServiceA, StartServiceW)
# BOOL WINAPI ControlService(
# _In_ SC_HANDLE hService,
# _In_ DWORD dwControl,
# _Out_ LPSERVICE_STATUS lpServiceStatus
# );
def ControlService(hService, dwControl):
_ControlService = windll.advapi32.ControlService
_ControlService.argtypes = [SC_HANDLE, DWORD, LPSERVICE_STATUS]
_ControlService.restype = bool
_ControlService.errcheck = RaiseIfZero
rawServiceStatus = SERVICE_STATUS()
_ControlService(hService, dwControl, byref(rawServiceStatus))
return ServiceStatus(rawServiceStatus)
# BOOL WINAPI ControlServiceEx(
# _In_ SC_HANDLE hService,
# _In_ DWORD dwControl,
# _In_ DWORD dwInfoLevel,
# _Inout_ PVOID pControlParams
# );
# TO DO
# DWORD WINAPI NotifyServiceStatusChange(
# _In_ SC_HANDLE hService,
# _In_ DWORD dwNotifyMask,
# _In_ PSERVICE_NOTIFY pNotifyBuffer
# );
# TO DO
# BOOL WINAPI QueryServiceStatus(
# _In_ SC_HANDLE hService,
# _Out_ LPSERVICE_STATUS lpServiceStatus
# );
def QueryServiceStatus(hService):
_QueryServiceStatus = windll.advapi32.QueryServiceStatus
_QueryServiceStatus.argtypes = [SC_HANDLE, LPSERVICE_STATUS]
_QueryServiceStatus.restype = bool
_QueryServiceStatus.errcheck = RaiseIfZero
rawServiceStatus = SERVICE_STATUS()
_QueryServiceStatus(hService, byref(rawServiceStatus))
return ServiceStatus(rawServiceStatus)
# BOOL WINAPI QueryServiceStatusEx(
# _In_ SC_HANDLE hService,
# _In_ SC_STATUS_TYPE InfoLevel,
# _Out_opt_ LPBYTE lpBuffer,
# _In_ DWORD cbBufSize,
# _Out_ LPDWORD pcbBytesNeeded
# );
def QueryServiceStatusEx(hService, InfoLevel = SC_STATUS_PROCESS_INFO):
if InfoLevel != SC_STATUS_PROCESS_INFO:
raise NotImplementedError()
_QueryServiceStatusEx = windll.advapi32.QueryServiceStatusEx
_QueryServiceStatusEx.argtypes = [SC_HANDLE, SC_STATUS_TYPE, LPVOID, DWORD, LPDWORD]
_QueryServiceStatusEx.restype = bool
_QueryServiceStatusEx.errcheck = RaiseIfZero
lpBuffer = SERVICE_STATUS_PROCESS()
cbBytesNeeded = DWORD(sizeof(lpBuffer))
_QueryServiceStatusEx(hService, InfoLevel, byref(lpBuffer), sizeof(lpBuffer), byref(cbBytesNeeded))
return ServiceStatusProcess(lpBuffer)
# BOOL WINAPI EnumServicesStatus(
# _In_ SC_HANDLE hSCManager,
# _In_ DWORD dwServiceType,
# _In_ DWORD dwServiceState,
# _Out_opt_ LPENUM_SERVICE_STATUS lpServices,
# _In_ DWORD cbBufSize,
# _Out_ LPDWORD pcbBytesNeeded,
# _Out_ LPDWORD lpServicesReturned,
# _Inout_opt_ LPDWORD lpResumeHandle
# );
def EnumServicesStatusA(hSCManager, dwServiceType = SERVICE_DRIVER | SERVICE_WIN32, dwServiceState = SERVICE_STATE_ALL):
_EnumServicesStatusA = windll.advapi32.EnumServicesStatusA
_EnumServicesStatusA.argtypes = [SC_HANDLE, DWORD, DWORD, LPVOID, DWORD, LPDWORD, LPDWORD, LPDWORD]
_EnumServicesStatusA.restype = bool
cbBytesNeeded = DWORD(0)
ServicesReturned = DWORD(0)
ResumeHandle = DWORD(0)
_EnumServicesStatusA(hSCManager, dwServiceType, dwServiceState, None, 0, byref(cbBytesNeeded), byref(ServicesReturned), byref(ResumeHandle))
Services = []
success = False
while GetLastError() == ERROR_MORE_DATA:
if cbBytesNeeded.value < sizeof(ENUM_SERVICE_STATUSA):
break
ServicesBuffer = ctypes.create_string_buffer("", cbBytesNeeded.value)
success = _EnumServicesStatusA(hSCManager, dwServiceType, dwServiceState, byref(ServicesBuffer), sizeof(ServicesBuffer), byref(cbBytesNeeded), byref(ServicesReturned), byref(ResumeHandle))
if sizeof(ServicesBuffer) < (sizeof(ENUM_SERVICE_STATUSA) * ServicesReturned.value):
raise ctypes.WinError()
lpServicesArray = ctypes.cast(ctypes.cast(ctypes.pointer(ServicesBuffer), ctypes.c_void_p), LPENUM_SERVICE_STATUSA)
for index in compat.xrange(0, ServicesReturned.value):
Services.append( ServiceStatusEntry(lpServicesArray[index]) )
if success: break
if not success:
raise ctypes.WinError()
return Services
def EnumServicesStatusW(hSCManager, dwServiceType = SERVICE_DRIVER | SERVICE_WIN32, dwServiceState = SERVICE_STATE_ALL):
_EnumServicesStatusW = windll.advapi32.EnumServicesStatusW
_EnumServicesStatusW.argtypes = [SC_HANDLE, DWORD, DWORD, LPVOID, DWORD, LPDWORD, LPDWORD, LPDWORD]
_EnumServicesStatusW.restype = bool
cbBytesNeeded = DWORD(0)
ServicesReturned = DWORD(0)
ResumeHandle = DWORD(0)
_EnumServicesStatusW(hSCManager, dwServiceType, dwServiceState, None, 0, byref(cbBytesNeeded), byref(ServicesReturned), byref(ResumeHandle))
Services = []
success = False
while GetLastError() == ERROR_MORE_DATA:
if cbBytesNeeded.value < sizeof(ENUM_SERVICE_STATUSW):
break
ServicesBuffer = ctypes.create_string_buffer("", cbBytesNeeded.value)
success = _EnumServicesStatusW(hSCManager, dwServiceType, dwServiceState, byref(ServicesBuffer), sizeof(ServicesBuffer), byref(cbBytesNeeded), byref(ServicesReturned), byref(ResumeHandle))
if sizeof(ServicesBuffer) < (sizeof(ENUM_SERVICE_STATUSW) * ServicesReturned.value):
raise ctypes.WinError()
lpServicesArray = ctypes.cast(ctypes.cast(ctypes.pointer(ServicesBuffer), ctypes.c_void_p), LPENUM_SERVICE_STATUSW)
for index in compat.xrange(0, ServicesReturned.value):
Services.append( ServiceStatusEntry(lpServicesArray[index]) )
if success: break
if not success:
raise ctypes.WinError()
return Services
EnumServicesStatus = DefaultStringType(EnumServicesStatusA, EnumServicesStatusW)
# BOOL WINAPI EnumServicesStatusEx(
# _In_ SC_HANDLE hSCManager,
# _In_ SC_ENUM_TYPE InfoLevel,
# _In_ DWORD dwServiceType,
# _In_ DWORD dwServiceState,
# _Out_opt_ LPBYTE lpServices,
# _In_ DWORD cbBufSize,
# _Out_ LPDWORD pcbBytesNeeded,
# _Out_ LPDWORD lpServicesReturned,
# _Inout_opt_ LPDWORD lpResumeHandle,
# _In_opt_ LPCTSTR pszGroupName
# );
def EnumServicesStatusExA(hSCManager, InfoLevel = SC_ENUM_PROCESS_INFO, dwServiceType = SERVICE_DRIVER | SERVICE_WIN32, dwServiceState = SERVICE_STATE_ALL, pszGroupName = None):
if InfoLevel != SC_ENUM_PROCESS_INFO:
raise NotImplementedError()
_EnumServicesStatusExA = windll.advapi32.EnumServicesStatusExA
_EnumServicesStatusExA.argtypes = [SC_HANDLE, SC_ENUM_TYPE, DWORD, DWORD, LPVOID, DWORD, LPDWORD, LPDWORD, LPDWORD, LPSTR]
_EnumServicesStatusExA.restype = bool
cbBytesNeeded = DWORD(0)
ServicesReturned = DWORD(0)
ResumeHandle = DWORD(0)
_EnumServicesStatusExA(hSCManager, InfoLevel, dwServiceType, dwServiceState, None, 0, byref(cbBytesNeeded), byref(ServicesReturned), byref(ResumeHandle), pszGroupName)
Services = []
success = False
while GetLastError() == ERROR_MORE_DATA:
if cbBytesNeeded.value < sizeof(ENUM_SERVICE_STATUS_PROCESSA):
break
ServicesBuffer = ctypes.create_string_buffer("", cbBytesNeeded.value)
success = _EnumServicesStatusExA(hSCManager, InfoLevel, dwServiceType, dwServiceState, byref(ServicesBuffer), sizeof(ServicesBuffer), byref(cbBytesNeeded), byref(ServicesReturned), byref(ResumeHandle), pszGroupName)
if sizeof(ServicesBuffer) < (sizeof(ENUM_SERVICE_STATUS_PROCESSA) * ServicesReturned.value):
raise ctypes.WinError()
lpServicesArray = ctypes.cast(ctypes.cast(ctypes.pointer(ServicesBuffer), ctypes.c_void_p), LPENUM_SERVICE_STATUS_PROCESSA)
for index in compat.xrange(0, ServicesReturned.value):
Services.append( ServiceStatusProcessEntry(lpServicesArray[index]) )
if success: break
if not success:
raise ctypes.WinError()
return Services
def EnumServicesStatusExW(hSCManager, InfoLevel = SC_ENUM_PROCESS_INFO, dwServiceType = SERVICE_DRIVER | SERVICE_WIN32, dwServiceState = SERVICE_STATE_ALL, pszGroupName = None):
_EnumServicesStatusExW = windll.advapi32.EnumServicesStatusExW
_EnumServicesStatusExW.argtypes = [SC_HANDLE, SC_ENUM_TYPE, DWORD, DWORD, LPVOID, DWORD, LPDWORD, LPDWORD, LPDWORD, LPWSTR]
_EnumServicesStatusExW.restype = bool
if InfoLevel != SC_ENUM_PROCESS_INFO:
raise NotImplementedError()
cbBytesNeeded = DWORD(0)
ServicesReturned = DWORD(0)
ResumeHandle = DWORD(0)
_EnumServicesStatusExW(hSCManager, InfoLevel, dwServiceType, dwServiceState, None, 0, byref(cbBytesNeeded), byref(ServicesReturned), byref(ResumeHandle), pszGroupName)
Services = []
success = False
while GetLastError() == ERROR_MORE_DATA:
if cbBytesNeeded.value < sizeof(ENUM_SERVICE_STATUS_PROCESSW):
break
ServicesBuffer = ctypes.create_string_buffer("", cbBytesNeeded.value)
success = _EnumServicesStatusExW(hSCManager, InfoLevel, dwServiceType, dwServiceState, byref(ServicesBuffer), sizeof(ServicesBuffer), byref(cbBytesNeeded), byref(ServicesReturned), byref(ResumeHandle), pszGroupName)
if sizeof(ServicesBuffer) < (sizeof(ENUM_SERVICE_STATUS_PROCESSW) * ServicesReturned.value):
raise ctypes.WinError()
lpServicesArray = ctypes.cast(ctypes.cast(ctypes.pointer(ServicesBuffer), ctypes.c_void_p), LPENUM_SERVICE_STATUS_PROCESSW)
for index in compat.xrange(0, ServicesReturned.value):
Services.append( ServiceStatusProcessEntry(lpServicesArray[index]) )
if success: break
if not success:
raise ctypes.WinError()
return Services
EnumServicesStatusEx = DefaultStringType(EnumServicesStatusExA, EnumServicesStatusExW)
# BOOL WINAPI EnumDependentServices(
# _In_ SC_HANDLE hService,
# _In_ DWORD dwServiceState,
# _Out_opt_ LPENUM_SERVICE_STATUS lpServices,
# _In_ DWORD cbBufSize,
# _Out_ LPDWORD pcbBytesNeeded,
# _Out_ LPDWORD lpServicesReturned
# );
# TO DO
#==============================================================================
# This calculates the list of exported symbols.
_all = set(vars().keys()).difference(_all)
__all__ = [_x for _x in _all if not _x.startswith('_')]
__all__.sort()
#==============================================================================
| 120,809 | Python | 36.635514 | 244 | 0.678393 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/win32/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Debugging API wrappers in ctypes.
"""
__revision__ = "$Id$"
from winappdbg.win32 import defines
from winappdbg.win32 import kernel32
from winappdbg.win32 import user32
from winappdbg.win32 import advapi32
from winappdbg.win32 import wtsapi32
from winappdbg.win32 import shell32
from winappdbg.win32 import shlwapi
from winappdbg.win32 import psapi
from winappdbg.win32 import dbghelp
from winappdbg.win32 import ntdll
from winappdbg.win32.defines import *
from winappdbg.win32.kernel32 import *
from winappdbg.win32.user32 import *
from winappdbg.win32.advapi32 import *
from winappdbg.win32.wtsapi32 import *
from winappdbg.win32.shell32 import *
from winappdbg.win32.shlwapi import *
from winappdbg.win32.psapi import *
from winappdbg.win32.dbghelp import *
from winappdbg.win32.ntdll import *
# This calculates the list of exported symbols.
_all = set()
_all.update(defines._all)
_all.update(kernel32._all)
_all.update(user32._all)
_all.update(advapi32._all)
_all.update(wtsapi32._all)
_all.update(shell32._all)
_all.update(shlwapi._all)
_all.update(psapi._all)
_all.update(dbghelp._all)
_all.update(ntdll._all)
__all__ = [_x for _x in _all if not _x.startswith('_')]
__all__.sort()
| 2,845 | Python | 37.986301 | 78 | 0.758524 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/win32/shlwapi.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Wrapper for shlwapi.dll in ctypes.
"""
__revision__ = "$Id$"
from winappdbg.win32.defines import *
from winappdbg.win32.kernel32 import *
#==============================================================================
# This is used later on to calculate the list of exported symbols.
_all = None
_all = set(vars().keys())
#==============================================================================
OS_WINDOWS = 0
OS_NT = 1
OS_WIN95ORGREATER = 2
OS_NT4ORGREATER = 3
OS_WIN98ORGREATER = 5
OS_WIN98_GOLD = 6
OS_WIN2000ORGREATER = 7
OS_WIN2000PRO = 8
OS_WIN2000SERVER = 9
OS_WIN2000ADVSERVER = 10
OS_WIN2000DATACENTER = 11
OS_WIN2000TERMINAL = 12
OS_EMBEDDED = 13
OS_TERMINALCLIENT = 14
OS_TERMINALREMOTEADMIN = 15
OS_WIN95_GOLD = 16
OS_MEORGREATER = 17
OS_XPORGREATER = 18
OS_HOME = 19
OS_PROFESSIONAL = 20
OS_DATACENTER = 21
OS_ADVSERVER = 22
OS_SERVER = 23
OS_TERMINALSERVER = 24
OS_PERSONALTERMINALSERVER = 25
OS_FASTUSERSWITCHING = 26
OS_WELCOMELOGONUI = 27
OS_DOMAINMEMBER = 28
OS_ANYSERVER = 29
OS_WOW6432 = 30
OS_WEBSERVER = 31
OS_SMALLBUSINESSSERVER = 32
OS_TABLETPC = 33
OS_SERVERADMINUI = 34
OS_MEDIACENTER = 35
OS_APPLIANCE = 36
#--- shlwapi.dll --------------------------------------------------------------
# BOOL IsOS(
# DWORD dwOS
# );
def IsOS(dwOS):
try:
_IsOS = windll.shlwapi.IsOS
_IsOS.argtypes = [DWORD]
_IsOS.restype = bool
except AttributeError:
# According to MSDN, on Windows versions prior to Vista
# this function is exported only by ordinal number 437.
# http://msdn.microsoft.com/en-us/library/bb773795%28VS.85%29.aspx
_GetProcAddress = windll.kernel32.GetProcAddress
_GetProcAddress.argtypes = [HINSTANCE, DWORD]
_GetProcAddress.restype = LPVOID
_IsOS = windll.kernel32.GetProcAddress(windll.shlwapi._handle, 437)
_IsOS = WINFUNCTYPE(bool, DWORD)(_IsOS)
return _IsOS(dwOS)
# LPTSTR PathAddBackslash(
# LPTSTR lpszPath
# );
def PathAddBackslashA(lpszPath):
_PathAddBackslashA = windll.shlwapi.PathAddBackslashA
_PathAddBackslashA.argtypes = [LPSTR]
_PathAddBackslashA.restype = LPSTR
lpszPath = ctypes.create_string_buffer(lpszPath, MAX_PATH)
retval = _PathAddBackslashA(lpszPath)
if retval == NULL:
raise ctypes.WinError()
return lpszPath.value
def PathAddBackslashW(lpszPath):
_PathAddBackslashW = windll.shlwapi.PathAddBackslashW
_PathAddBackslashW.argtypes = [LPWSTR]
_PathAddBackslashW.restype = LPWSTR
lpszPath = ctypes.create_unicode_buffer(lpszPath, MAX_PATH)
retval = _PathAddBackslashW(lpszPath)
if retval == NULL:
raise ctypes.WinError()
return lpszPath.value
PathAddBackslash = GuessStringType(PathAddBackslashA, PathAddBackslashW)
# BOOL PathAddExtension(
# LPTSTR pszPath,
# LPCTSTR pszExtension
# );
def PathAddExtensionA(lpszPath, pszExtension = None):
_PathAddExtensionA = windll.shlwapi.PathAddExtensionA
_PathAddExtensionA.argtypes = [LPSTR, LPSTR]
_PathAddExtensionA.restype = bool
_PathAddExtensionA.errcheck = RaiseIfZero
if not pszExtension:
pszExtension = None
lpszPath = ctypes.create_string_buffer(lpszPath, MAX_PATH)
_PathAddExtensionA(lpszPath, pszExtension)
return lpszPath.value
def PathAddExtensionW(lpszPath, pszExtension = None):
_PathAddExtensionW = windll.shlwapi.PathAddExtensionW
_PathAddExtensionW.argtypes = [LPWSTR, LPWSTR]
_PathAddExtensionW.restype = bool
_PathAddExtensionW.errcheck = RaiseIfZero
if not pszExtension:
pszExtension = None
lpszPath = ctypes.create_unicode_buffer(lpszPath, MAX_PATH)
_PathAddExtensionW(lpszPath, pszExtension)
return lpszPath.value
PathAddExtension = GuessStringType(PathAddExtensionA, PathAddExtensionW)
# BOOL PathAppend(
# LPTSTR pszPath,
# LPCTSTR pszMore
# );
def PathAppendA(lpszPath, pszMore = None):
_PathAppendA = windll.shlwapi.PathAppendA
_PathAppendA.argtypes = [LPSTR, LPSTR]
_PathAppendA.restype = bool
_PathAppendA.errcheck = RaiseIfZero
if not pszMore:
pszMore = None
lpszPath = ctypes.create_string_buffer(lpszPath, MAX_PATH)
_PathAppendA(lpszPath, pszMore)
return lpszPath.value
def PathAppendW(lpszPath, pszMore = None):
_PathAppendW = windll.shlwapi.PathAppendW
_PathAppendW.argtypes = [LPWSTR, LPWSTR]
_PathAppendW.restype = bool
_PathAppendW.errcheck = RaiseIfZero
if not pszMore:
pszMore = None
lpszPath = ctypes.create_unicode_buffer(lpszPath, MAX_PATH)
_PathAppendW(lpszPath, pszMore)
return lpszPath.value
PathAppend = GuessStringType(PathAppendA, PathAppendW)
# LPTSTR PathCombine(
# LPTSTR lpszDest,
# LPCTSTR lpszDir,
# LPCTSTR lpszFile
# );
def PathCombineA(lpszDir, lpszFile):
_PathCombineA = windll.shlwapi.PathCombineA
_PathCombineA.argtypes = [LPSTR, LPSTR, LPSTR]
_PathCombineA.restype = LPSTR
lpszDest = ctypes.create_string_buffer("", max(MAX_PATH, len(lpszDir) + len(lpszFile) + 1))
retval = _PathCombineA(lpszDest, lpszDir, lpszFile)
if retval == NULL:
return None
return lpszDest.value
def PathCombineW(lpszDir, lpszFile):
_PathCombineW = windll.shlwapi.PathCombineW
_PathCombineW.argtypes = [LPWSTR, LPWSTR, LPWSTR]
_PathCombineW.restype = LPWSTR
lpszDest = ctypes.create_unicode_buffer(u"", max(MAX_PATH, len(lpszDir) + len(lpszFile) + 1))
retval = _PathCombineW(lpszDest, lpszDir, lpszFile)
if retval == NULL:
return None
return lpszDest.value
PathCombine = GuessStringType(PathCombineA, PathCombineW)
# BOOL PathCanonicalize(
# LPTSTR lpszDst,
# LPCTSTR lpszSrc
# );
def PathCanonicalizeA(lpszSrc):
_PathCanonicalizeA = windll.shlwapi.PathCanonicalizeA
_PathCanonicalizeA.argtypes = [LPSTR, LPSTR]
_PathCanonicalizeA.restype = bool
_PathCanonicalizeA.errcheck = RaiseIfZero
lpszDst = ctypes.create_string_buffer("", MAX_PATH)
_PathCanonicalizeA(lpszDst, lpszSrc)
return lpszDst.value
def PathCanonicalizeW(lpszSrc):
_PathCanonicalizeW = windll.shlwapi.PathCanonicalizeW
_PathCanonicalizeW.argtypes = [LPWSTR, LPWSTR]
_PathCanonicalizeW.restype = bool
_PathCanonicalizeW.errcheck = RaiseIfZero
lpszDst = ctypes.create_unicode_buffer(u"", MAX_PATH)
_PathCanonicalizeW(lpszDst, lpszSrc)
return lpszDst.value
PathCanonicalize = GuessStringType(PathCanonicalizeA, PathCanonicalizeW)
# BOOL PathRelativePathTo(
# _Out_ LPTSTR pszPath,
# _In_ LPCTSTR pszFrom,
# _In_ DWORD dwAttrFrom,
# _In_ LPCTSTR pszTo,
# _In_ DWORD dwAttrTo
# );
def PathRelativePathToA(pszFrom = None, dwAttrFrom = FILE_ATTRIBUTE_DIRECTORY, pszTo = None, dwAttrTo = FILE_ATTRIBUTE_DIRECTORY):
_PathRelativePathToA = windll.shlwapi.PathRelativePathToA
_PathRelativePathToA.argtypes = [LPSTR, LPSTR, DWORD, LPSTR, DWORD]
_PathRelativePathToA.restype = bool
_PathRelativePathToA.errcheck = RaiseIfZero
# Make the paths absolute or the function fails.
if pszFrom:
pszFrom = GetFullPathNameA(pszFrom)[0]
else:
pszFrom = GetCurrentDirectoryA()
if pszTo:
pszTo = GetFullPathNameA(pszTo)[0]
else:
pszTo = GetCurrentDirectoryA()
# Argh, this function doesn't receive an output buffer size!
# We'll try to guess the maximum possible buffer size.
dwPath = max((len(pszFrom) + len(pszTo)) * 2 + 1, MAX_PATH + 1)
pszPath = ctypes.create_string_buffer('', dwPath)
# Also, it doesn't set the last error value.
# Whoever coded it must have been drunk or tripping on acid. Or both.
# The only failure conditions I've seen were invalid paths, paths not
# on the same drive, or the path is not absolute.
SetLastError(ERROR_INVALID_PARAMETER)
_PathRelativePathToA(pszPath, pszFrom, dwAttrFrom, pszTo, dwAttrTo)
return pszPath.value
def PathRelativePathToW(pszFrom = None, dwAttrFrom = FILE_ATTRIBUTE_DIRECTORY, pszTo = None, dwAttrTo = FILE_ATTRIBUTE_DIRECTORY):
_PathRelativePathToW = windll.shlwapi.PathRelativePathToW
_PathRelativePathToW.argtypes = [LPWSTR, LPWSTR, DWORD, LPWSTR, DWORD]
_PathRelativePathToW.restype = bool
_PathRelativePathToW.errcheck = RaiseIfZero
# Refer to PathRelativePathToA to know why this code is so ugly.
if pszFrom:
pszFrom = GetFullPathNameW(pszFrom)[0]
else:
pszFrom = GetCurrentDirectoryW()
if pszTo:
pszTo = GetFullPathNameW(pszTo)[0]
else:
pszTo = GetCurrentDirectoryW()
dwPath = max((len(pszFrom) + len(pszTo)) * 2 + 1, MAX_PATH + 1)
pszPath = ctypes.create_unicode_buffer(u'', dwPath)
SetLastError(ERROR_INVALID_PARAMETER)
_PathRelativePathToW(pszPath, pszFrom, dwAttrFrom, pszTo, dwAttrTo)
return pszPath.value
PathRelativePathTo = GuessStringType(PathRelativePathToA, PathRelativePathToW)
# BOOL PathFileExists(
# LPCTSTR pszPath
# );
def PathFileExistsA(pszPath):
_PathFileExistsA = windll.shlwapi.PathFileExistsA
_PathFileExistsA.argtypes = [LPSTR]
_PathFileExistsA.restype = bool
return _PathFileExistsA(pszPath)
def PathFileExistsW(pszPath):
_PathFileExistsW = windll.shlwapi.PathFileExistsW
_PathFileExistsW.argtypes = [LPWSTR]
_PathFileExistsW.restype = bool
return _PathFileExistsW(pszPath)
PathFileExists = GuessStringType(PathFileExistsA, PathFileExistsW)
# LPTSTR PathFindExtension(
# LPCTSTR pszPath
# );
def PathFindExtensionA(pszPath):
_PathFindExtensionA = windll.shlwapi.PathFindExtensionA
_PathFindExtensionA.argtypes = [LPSTR]
_PathFindExtensionA.restype = LPSTR
pszPath = ctypes.create_string_buffer(pszPath)
return _PathFindExtensionA(pszPath)
def PathFindExtensionW(pszPath):
_PathFindExtensionW = windll.shlwapi.PathFindExtensionW
_PathFindExtensionW.argtypes = [LPWSTR]
_PathFindExtensionW.restype = LPWSTR
pszPath = ctypes.create_unicode_buffer(pszPath)
return _PathFindExtensionW(pszPath)
PathFindExtension = GuessStringType(PathFindExtensionA, PathFindExtensionW)
# LPTSTR PathFindFileName(
# LPCTSTR pszPath
# );
def PathFindFileNameA(pszPath):
_PathFindFileNameA = windll.shlwapi.PathFindFileNameA
_PathFindFileNameA.argtypes = [LPSTR]
_PathFindFileNameA.restype = LPSTR
pszPath = ctypes.create_string_buffer(pszPath)
return _PathFindFileNameA(pszPath)
def PathFindFileNameW(pszPath):
_PathFindFileNameW = windll.shlwapi.PathFindFileNameW
_PathFindFileNameW.argtypes = [LPWSTR]
_PathFindFileNameW.restype = LPWSTR
pszPath = ctypes.create_unicode_buffer(pszPath)
return _PathFindFileNameW(pszPath)
PathFindFileName = GuessStringType(PathFindFileNameA, PathFindFileNameW)
# LPTSTR PathFindNextComponent(
# LPCTSTR pszPath
# );
def PathFindNextComponentA(pszPath):
_PathFindNextComponentA = windll.shlwapi.PathFindNextComponentA
_PathFindNextComponentA.argtypes = [LPSTR]
_PathFindNextComponentA.restype = LPSTR
pszPath = ctypes.create_string_buffer(pszPath)
return _PathFindNextComponentA(pszPath)
def PathFindNextComponentW(pszPath):
_PathFindNextComponentW = windll.shlwapi.PathFindNextComponentW
_PathFindNextComponentW.argtypes = [LPWSTR]
_PathFindNextComponentW.restype = LPWSTR
pszPath = ctypes.create_unicode_buffer(pszPath)
return _PathFindNextComponentW(pszPath)
PathFindNextComponent = GuessStringType(PathFindNextComponentA, PathFindNextComponentW)
# BOOL PathFindOnPath(
# LPTSTR pszFile,
# LPCTSTR *ppszOtherDirs
# );
def PathFindOnPathA(pszFile, ppszOtherDirs = None):
_PathFindOnPathA = windll.shlwapi.PathFindOnPathA
_PathFindOnPathA.argtypes = [LPSTR, LPSTR]
_PathFindOnPathA.restype = bool
pszFile = ctypes.create_string_buffer(pszFile, MAX_PATH)
if not ppszOtherDirs:
ppszOtherDirs = None
else:
szArray = ""
for pszOtherDirs in ppszOtherDirs:
if pszOtherDirs:
szArray = "%s%s\0" % (szArray, pszOtherDirs)
szArray = szArray + "\0"
pszOtherDirs = ctypes.create_string_buffer(szArray)
ppszOtherDirs = ctypes.pointer(pszOtherDirs)
if _PathFindOnPathA(pszFile, ppszOtherDirs):
return pszFile.value
return None
def PathFindOnPathW(pszFile, ppszOtherDirs = None):
_PathFindOnPathW = windll.shlwapi.PathFindOnPathA
_PathFindOnPathW.argtypes = [LPWSTR, LPWSTR]
_PathFindOnPathW.restype = bool
pszFile = ctypes.create_unicode_buffer(pszFile, MAX_PATH)
if not ppszOtherDirs:
ppszOtherDirs = None
else:
szArray = u""
for pszOtherDirs in ppszOtherDirs:
if pszOtherDirs:
szArray = u"%s%s\0" % (szArray, pszOtherDirs)
szArray = szArray + u"\0"
pszOtherDirs = ctypes.create_unicode_buffer(szArray)
ppszOtherDirs = ctypes.pointer(pszOtherDirs)
if _PathFindOnPathW(pszFile, ppszOtherDirs):
return pszFile.value
return None
PathFindOnPath = GuessStringType(PathFindOnPathA, PathFindOnPathW)
# LPTSTR PathGetArgs(
# LPCTSTR pszPath
# );
def PathGetArgsA(pszPath):
_PathGetArgsA = windll.shlwapi.PathGetArgsA
_PathGetArgsA.argtypes = [LPSTR]
_PathGetArgsA.restype = LPSTR
pszPath = ctypes.create_string_buffer(pszPath)
return _PathGetArgsA(pszPath)
def PathGetArgsW(pszPath):
_PathGetArgsW = windll.shlwapi.PathGetArgsW
_PathGetArgsW.argtypes = [LPWSTR]
_PathGetArgsW.restype = LPWSTR
pszPath = ctypes.create_unicode_buffer(pszPath)
return _PathGetArgsW(pszPath)
PathGetArgs = GuessStringType(PathGetArgsA, PathGetArgsW)
# BOOL PathIsContentType(
# LPCTSTR pszPath,
# LPCTSTR pszContentType
# );
def PathIsContentTypeA(pszPath, pszContentType):
_PathIsContentTypeA = windll.shlwapi.PathIsContentTypeA
_PathIsContentTypeA.argtypes = [LPSTR, LPSTR]
_PathIsContentTypeA.restype = bool
return _PathIsContentTypeA(pszPath, pszContentType)
def PathIsContentTypeW(pszPath, pszContentType):
_PathIsContentTypeW = windll.shlwapi.PathIsContentTypeW
_PathIsContentTypeW.argtypes = [LPWSTR, LPWSTR]
_PathIsContentTypeW.restype = bool
return _PathIsContentTypeW(pszPath, pszContentType)
PathIsContentType = GuessStringType(PathIsContentTypeA, PathIsContentTypeW)
# BOOL PathIsDirectory(
# LPCTSTR pszPath
# );
def PathIsDirectoryA(pszPath):
_PathIsDirectoryA = windll.shlwapi.PathIsDirectoryA
_PathIsDirectoryA.argtypes = [LPSTR]
_PathIsDirectoryA.restype = bool
return _PathIsDirectoryA(pszPath)
def PathIsDirectoryW(pszPath):
_PathIsDirectoryW = windll.shlwapi.PathIsDirectoryW
_PathIsDirectoryW.argtypes = [LPWSTR]
_PathIsDirectoryW.restype = bool
return _PathIsDirectoryW(pszPath)
PathIsDirectory = GuessStringType(PathIsDirectoryA, PathIsDirectoryW)
# BOOL PathIsDirectoryEmpty(
# LPCTSTR pszPath
# );
def PathIsDirectoryEmptyA(pszPath):
_PathIsDirectoryEmptyA = windll.shlwapi.PathIsDirectoryEmptyA
_PathIsDirectoryEmptyA.argtypes = [LPSTR]
_PathIsDirectoryEmptyA.restype = bool
return _PathIsDirectoryEmptyA(pszPath)
def PathIsDirectoryEmptyW(pszPath):
_PathIsDirectoryEmptyW = windll.shlwapi.PathIsDirectoryEmptyW
_PathIsDirectoryEmptyW.argtypes = [LPWSTR]
_PathIsDirectoryEmptyW.restype = bool
return _PathIsDirectoryEmptyW(pszPath)
PathIsDirectoryEmpty = GuessStringType(PathIsDirectoryEmptyA, PathIsDirectoryEmptyW)
# BOOL PathIsNetworkPath(
# LPCTSTR pszPath
# );
def PathIsNetworkPathA(pszPath):
_PathIsNetworkPathA = windll.shlwapi.PathIsNetworkPathA
_PathIsNetworkPathA.argtypes = [LPSTR]
_PathIsNetworkPathA.restype = bool
return _PathIsNetworkPathA(pszPath)
def PathIsNetworkPathW(pszPath):
_PathIsNetworkPathW = windll.shlwapi.PathIsNetworkPathW
_PathIsNetworkPathW.argtypes = [LPWSTR]
_PathIsNetworkPathW.restype = bool
return _PathIsNetworkPathW(pszPath)
PathIsNetworkPath = GuessStringType(PathIsNetworkPathA, PathIsNetworkPathW)
# BOOL PathIsRelative(
# LPCTSTR lpszPath
# );
def PathIsRelativeA(pszPath):
_PathIsRelativeA = windll.shlwapi.PathIsRelativeA
_PathIsRelativeA.argtypes = [LPSTR]
_PathIsRelativeA.restype = bool
return _PathIsRelativeA(pszPath)
def PathIsRelativeW(pszPath):
_PathIsRelativeW = windll.shlwapi.PathIsRelativeW
_PathIsRelativeW.argtypes = [LPWSTR]
_PathIsRelativeW.restype = bool
return _PathIsRelativeW(pszPath)
PathIsRelative = GuessStringType(PathIsRelativeA, PathIsRelativeW)
# BOOL PathIsRoot(
# LPCTSTR pPath
# );
def PathIsRootA(pszPath):
_PathIsRootA = windll.shlwapi.PathIsRootA
_PathIsRootA.argtypes = [LPSTR]
_PathIsRootA.restype = bool
return _PathIsRootA(pszPath)
def PathIsRootW(pszPath):
_PathIsRootW = windll.shlwapi.PathIsRootW
_PathIsRootW.argtypes = [LPWSTR]
_PathIsRootW.restype = bool
return _PathIsRootW(pszPath)
PathIsRoot = GuessStringType(PathIsRootA, PathIsRootW)
# BOOL PathIsSameRoot(
# LPCTSTR pszPath1,
# LPCTSTR pszPath2
# );
def PathIsSameRootA(pszPath1, pszPath2):
_PathIsSameRootA = windll.shlwapi.PathIsSameRootA
_PathIsSameRootA.argtypes = [LPSTR, LPSTR]
_PathIsSameRootA.restype = bool
return _PathIsSameRootA(pszPath1, pszPath2)
def PathIsSameRootW(pszPath1, pszPath2):
_PathIsSameRootW = windll.shlwapi.PathIsSameRootW
_PathIsSameRootW.argtypes = [LPWSTR, LPWSTR]
_PathIsSameRootW.restype = bool
return _PathIsSameRootW(pszPath1, pszPath2)
PathIsSameRoot = GuessStringType(PathIsSameRootA, PathIsSameRootW)
# BOOL PathIsUNC(
# LPCTSTR pszPath
# );
def PathIsUNCA(pszPath):
_PathIsUNCA = windll.shlwapi.PathIsUNCA
_PathIsUNCA.argtypes = [LPSTR]
_PathIsUNCA.restype = bool
return _PathIsUNCA(pszPath)
def PathIsUNCW(pszPath):
_PathIsUNCW = windll.shlwapi.PathIsUNCW
_PathIsUNCW.argtypes = [LPWSTR]
_PathIsUNCW.restype = bool
return _PathIsUNCW(pszPath)
PathIsUNC = GuessStringType(PathIsUNCA, PathIsUNCW)
# XXX WARNING
# PathMakePretty turns filenames into all lowercase.
# I'm not sure how well that might work on Wine.
# BOOL PathMakePretty(
# LPCTSTR pszPath
# );
def PathMakePrettyA(pszPath):
_PathMakePrettyA = windll.shlwapi.PathMakePrettyA
_PathMakePrettyA.argtypes = [LPSTR]
_PathMakePrettyA.restype = bool
_PathMakePrettyA.errcheck = RaiseIfZero
pszPath = ctypes.create_string_buffer(pszPath, MAX_PATH)
_PathMakePrettyA(pszPath)
return pszPath.value
def PathMakePrettyW(pszPath):
_PathMakePrettyW = windll.shlwapi.PathMakePrettyW
_PathMakePrettyW.argtypes = [LPWSTR]
_PathMakePrettyW.restype = bool
_PathMakePrettyW.errcheck = RaiseIfZero
pszPath = ctypes.create_unicode_buffer(pszPath, MAX_PATH)
_PathMakePrettyW(pszPath)
return pszPath.value
PathMakePretty = GuessStringType(PathMakePrettyA, PathMakePrettyW)
# void PathRemoveArgs(
# LPTSTR pszPath
# );
def PathRemoveArgsA(pszPath):
_PathRemoveArgsA = windll.shlwapi.PathRemoveArgsA
_PathRemoveArgsA.argtypes = [LPSTR]
pszPath = ctypes.create_string_buffer(pszPath, MAX_PATH)
_PathRemoveArgsA(pszPath)
return pszPath.value
def PathRemoveArgsW(pszPath):
_PathRemoveArgsW = windll.shlwapi.PathRemoveArgsW
_PathRemoveArgsW.argtypes = [LPWSTR]
pszPath = ctypes.create_unicode_buffer(pszPath, MAX_PATH)
_PathRemoveArgsW(pszPath)
return pszPath.value
PathRemoveArgs = GuessStringType(PathRemoveArgsA, PathRemoveArgsW)
# void PathRemoveBackslash(
# LPTSTR pszPath
# );
def PathRemoveBackslashA(pszPath):
_PathRemoveBackslashA = windll.shlwapi.PathRemoveBackslashA
_PathRemoveBackslashA.argtypes = [LPSTR]
pszPath = ctypes.create_string_buffer(pszPath, MAX_PATH)
_PathRemoveBackslashA(pszPath)
return pszPath.value
def PathRemoveBackslashW(pszPath):
_PathRemoveBackslashW = windll.shlwapi.PathRemoveBackslashW
_PathRemoveBackslashW.argtypes = [LPWSTR]
pszPath = ctypes.create_unicode_buffer(pszPath, MAX_PATH)
_PathRemoveBackslashW(pszPath)
return pszPath.value
PathRemoveBackslash = GuessStringType(PathRemoveBackslashA, PathRemoveBackslashW)
# void PathRemoveExtension(
# LPTSTR pszPath
# );
def PathRemoveExtensionA(pszPath):
_PathRemoveExtensionA = windll.shlwapi.PathRemoveExtensionA
_PathRemoveExtensionA.argtypes = [LPSTR]
pszPath = ctypes.create_string_buffer(pszPath, MAX_PATH)
_PathRemoveExtensionA(pszPath)
return pszPath.value
def PathRemoveExtensionW(pszPath):
_PathRemoveExtensionW = windll.shlwapi.PathRemoveExtensionW
_PathRemoveExtensionW.argtypes = [LPWSTR]
pszPath = ctypes.create_unicode_buffer(pszPath, MAX_PATH)
_PathRemoveExtensionW(pszPath)
return pszPath.value
PathRemoveExtension = GuessStringType(PathRemoveExtensionA, PathRemoveExtensionW)
# void PathRemoveFileSpec(
# LPTSTR pszPath
# );
def PathRemoveFileSpecA(pszPath):
_PathRemoveFileSpecA = windll.shlwapi.PathRemoveFileSpecA
_PathRemoveFileSpecA.argtypes = [LPSTR]
pszPath = ctypes.create_string_buffer(pszPath, MAX_PATH)
_PathRemoveFileSpecA(pszPath)
return pszPath.value
def PathRemoveFileSpecW(pszPath):
_PathRemoveFileSpecW = windll.shlwapi.PathRemoveFileSpecW
_PathRemoveFileSpecW.argtypes = [LPWSTR]
pszPath = ctypes.create_unicode_buffer(pszPath, MAX_PATH)
_PathRemoveFileSpecW(pszPath)
return pszPath.value
PathRemoveFileSpec = GuessStringType(PathRemoveFileSpecA, PathRemoveFileSpecW)
# BOOL PathRenameExtension(
# LPTSTR pszPath,
# LPCTSTR pszExt
# );
def PathRenameExtensionA(pszPath, pszExt):
_PathRenameExtensionA = windll.shlwapi.PathRenameExtensionA
_PathRenameExtensionA.argtypes = [LPSTR, LPSTR]
_PathRenameExtensionA.restype = bool
pszPath = ctypes.create_string_buffer(pszPath, MAX_PATH)
if _PathRenameExtensionA(pszPath, pszExt):
return pszPath.value
return None
def PathRenameExtensionW(pszPath, pszExt):
_PathRenameExtensionW = windll.shlwapi.PathRenameExtensionW
_PathRenameExtensionW.argtypes = [LPWSTR, LPWSTR]
_PathRenameExtensionW.restype = bool
pszPath = ctypes.create_unicode_buffer(pszPath, MAX_PATH)
if _PathRenameExtensionW(pszPath, pszExt):
return pszPath.value
return None
PathRenameExtension = GuessStringType(PathRenameExtensionA, PathRenameExtensionW)
# BOOL PathUnExpandEnvStrings(
# LPCTSTR pszPath,
# LPTSTR pszBuf,
# UINT cchBuf
# );
def PathUnExpandEnvStringsA(pszPath):
_PathUnExpandEnvStringsA = windll.shlwapi.PathUnExpandEnvStringsA
_PathUnExpandEnvStringsA.argtypes = [LPSTR, LPSTR]
_PathUnExpandEnvStringsA.restype = bool
_PathUnExpandEnvStringsA.errcheck = RaiseIfZero
cchBuf = MAX_PATH
pszBuf = ctypes.create_string_buffer("", cchBuf)
_PathUnExpandEnvStringsA(pszPath, pszBuf, cchBuf)
return pszBuf.value
def PathUnExpandEnvStringsW(pszPath):
_PathUnExpandEnvStringsW = windll.shlwapi.PathUnExpandEnvStringsW
_PathUnExpandEnvStringsW.argtypes = [LPWSTR, LPWSTR]
_PathUnExpandEnvStringsW.restype = bool
_PathUnExpandEnvStringsW.errcheck = RaiseIfZero
cchBuf = MAX_PATH
pszBuf = ctypes.create_unicode_buffer(u"", cchBuf)
_PathUnExpandEnvStringsW(pszPath, pszBuf, cchBuf)
return pszBuf.value
PathUnExpandEnvStrings = GuessStringType(PathUnExpandEnvStringsA, PathUnExpandEnvStringsW)
#==============================================================================
# This calculates the list of exported symbols.
_all = set(vars().keys()).difference(_all)
__all__ = [_x for _x in _all if not _x.startswith('_')]
__all__.sort()
#==============================================================================
| 25,807 | Python | 33.09247 | 130 | 0.716899 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/win32/version.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Detect the current architecture and operating system.
Some functions here are really from kernel32.dll, others from version.dll.
"""
__revision__ = "$Id$"
from winappdbg.win32.defines import *
#==============================================================================
# This is used later on to calculate the list of exported symbols.
_all = None
_all = set(vars().keys())
#==============================================================================
#--- NTDDI version ------------------------------------------------------------
NTDDI_WIN8 = 0x06020000
NTDDI_WIN7SP1 = 0x06010100
NTDDI_WIN7 = 0x06010000
NTDDI_WS08 = 0x06000100
NTDDI_VISTASP1 = 0x06000100
NTDDI_VISTA = 0x06000000
NTDDI_LONGHORN = NTDDI_VISTA
NTDDI_WS03SP2 = 0x05020200
NTDDI_WS03SP1 = 0x05020100
NTDDI_WS03 = 0x05020000
NTDDI_WINXPSP3 = 0x05010300
NTDDI_WINXPSP2 = 0x05010200
NTDDI_WINXPSP1 = 0x05010100
NTDDI_WINXP = 0x05010000
NTDDI_WIN2KSP4 = 0x05000400
NTDDI_WIN2KSP3 = 0x05000300
NTDDI_WIN2KSP2 = 0x05000200
NTDDI_WIN2KSP1 = 0x05000100
NTDDI_WIN2K = 0x05000000
NTDDI_WINNT4 = 0x04000000
OSVERSION_MASK = 0xFFFF0000
SPVERSION_MASK = 0x0000FF00
SUBVERSION_MASK = 0x000000FF
#--- OSVERSIONINFO and OSVERSIONINFOEX structures and constants ---------------
VER_PLATFORM_WIN32s = 0
VER_PLATFORM_WIN32_WINDOWS = 1
VER_PLATFORM_WIN32_NT = 2
VER_SUITE_BACKOFFICE = 0x00000004
VER_SUITE_BLADE = 0x00000400
VER_SUITE_COMPUTE_SERVER = 0x00004000
VER_SUITE_DATACENTER = 0x00000080
VER_SUITE_ENTERPRISE = 0x00000002
VER_SUITE_EMBEDDEDNT = 0x00000040
VER_SUITE_PERSONAL = 0x00000200
VER_SUITE_SINGLEUSERTS = 0x00000100
VER_SUITE_SMALLBUSINESS = 0x00000001
VER_SUITE_SMALLBUSINESS_RESTRICTED = 0x00000020
VER_SUITE_STORAGE_SERVER = 0x00002000
VER_SUITE_TERMINAL = 0x00000010
VER_SUITE_WH_SERVER = 0x00008000
VER_NT_DOMAIN_CONTROLLER = 0x0000002
VER_NT_SERVER = 0x0000003
VER_NT_WORKSTATION = 0x0000001
VER_BUILDNUMBER = 0x0000004
VER_MAJORVERSION = 0x0000002
VER_MINORVERSION = 0x0000001
VER_PLATFORMID = 0x0000008
VER_PRODUCT_TYPE = 0x0000080
VER_SERVICEPACKMAJOR = 0x0000020
VER_SERVICEPACKMINOR = 0x0000010
VER_SUITENAME = 0x0000040
VER_EQUAL = 1
VER_GREATER = 2
VER_GREATER_EQUAL = 3
VER_LESS = 4
VER_LESS_EQUAL = 5
VER_AND = 6
VER_OR = 7
# typedef struct _OSVERSIONINFO {
# DWORD dwOSVersionInfoSize;
# DWORD dwMajorVersion;
# DWORD dwMinorVersion;
# DWORD dwBuildNumber;
# DWORD dwPlatformId;
# TCHAR szCSDVersion[128];
# }OSVERSIONINFO;
class OSVERSIONINFOA(Structure):
_fields_ = [
("dwOSVersionInfoSize", DWORD),
("dwMajorVersion", DWORD),
("dwMinorVersion", DWORD),
("dwBuildNumber", DWORD),
("dwPlatformId", DWORD),
("szCSDVersion", CHAR * 128),
]
class OSVERSIONINFOW(Structure):
_fields_ = [
("dwOSVersionInfoSize", DWORD),
("dwMajorVersion", DWORD),
("dwMinorVersion", DWORD),
("dwBuildNumber", DWORD),
("dwPlatformId", DWORD),
("szCSDVersion", WCHAR * 128),
]
# typedef struct _OSVERSIONINFOEX {
# DWORD dwOSVersionInfoSize;
# DWORD dwMajorVersion;
# DWORD dwMinorVersion;
# DWORD dwBuildNumber;
# DWORD dwPlatformId;
# TCHAR szCSDVersion[128];
# WORD wServicePackMajor;
# WORD wServicePackMinor;
# WORD wSuiteMask;
# BYTE wProductType;
# BYTE wReserved;
# }OSVERSIONINFOEX, *POSVERSIONINFOEX, *LPOSVERSIONINFOEX;
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),
]
class OSVERSIONINFOEXW(Structure):
_fields_ = [
("dwOSVersionInfoSize", DWORD),
("dwMajorVersion", DWORD),
("dwMinorVersion", DWORD),
("dwBuildNumber", DWORD),
("dwPlatformId", DWORD),
("szCSDVersion", WCHAR * 128),
("wServicePackMajor", WORD),
("wServicePackMinor", WORD),
("wSuiteMask", WORD),
("wProductType", BYTE),
("wReserved", BYTE),
]
LPOSVERSIONINFOA = POINTER(OSVERSIONINFOA)
LPOSVERSIONINFOW = POINTER(OSVERSIONINFOW)
LPOSVERSIONINFOEXA = POINTER(OSVERSIONINFOEXA)
LPOSVERSIONINFOEXW = POINTER(OSVERSIONINFOEXW)
POSVERSIONINFOA = LPOSVERSIONINFOA
POSVERSIONINFOW = LPOSVERSIONINFOW
POSVERSIONINFOEXA = LPOSVERSIONINFOEXA
POSVERSIONINFOEXW = LPOSVERSIONINFOA
#--- GetSystemMetrics constants -----------------------------------------------
SM_CXSCREEN = 0
SM_CYSCREEN = 1
SM_CXVSCROLL = 2
SM_CYHSCROLL = 3
SM_CYCAPTION = 4
SM_CXBORDER = 5
SM_CYBORDER = 6
SM_CXDLGFRAME = 7
SM_CYDLGFRAME = 8
SM_CYVTHUMB = 9
SM_CXHTHUMB = 10
SM_CXICON = 11
SM_CYICON = 12
SM_CXCURSOR = 13
SM_CYCURSOR = 14
SM_CYMENU = 15
SM_CXFULLSCREEN = 16
SM_CYFULLSCREEN = 17
SM_CYKANJIWINDOW = 18
SM_MOUSEPRESENT = 19
SM_CYVSCROLL = 20
SM_CXHSCROLL = 21
SM_DEBUG = 22
SM_SWAPBUTTON = 23
SM_RESERVED1 = 24
SM_RESERVED2 = 25
SM_RESERVED3 = 26
SM_RESERVED4 = 27
SM_CXMIN = 28
SM_CYMIN = 29
SM_CXSIZE = 30
SM_CYSIZE = 31
SM_CXFRAME = 32
SM_CYFRAME = 33
SM_CXMINTRACK = 34
SM_CYMINTRACK = 35
SM_CXDOUBLECLK = 36
SM_CYDOUBLECLK = 37
SM_CXICONSPACING = 38
SM_CYICONSPACING = 39
SM_MENUDROPALIGNMENT = 40
SM_PENWINDOWS = 41
SM_DBCSENABLED = 42
SM_CMOUSEBUTTONS = 43
SM_CXFIXEDFRAME = SM_CXDLGFRAME # ;win40 name change
SM_CYFIXEDFRAME = SM_CYDLGFRAME # ;win40 name change
SM_CXSIZEFRAME = SM_CXFRAME # ;win40 name change
SM_CYSIZEFRAME = SM_CYFRAME # ;win40 name change
SM_SECURE = 44
SM_CXEDGE = 45
SM_CYEDGE = 46
SM_CXMINSPACING = 47
SM_CYMINSPACING = 48
SM_CXSMICON = 49
SM_CYSMICON = 50
SM_CYSMCAPTION = 51
SM_CXSMSIZE = 52
SM_CYSMSIZE = 53
SM_CXMENUSIZE = 54
SM_CYMENUSIZE = 55
SM_ARRANGE = 56
SM_CXMINIMIZED = 57
SM_CYMINIMIZED = 58
SM_CXMAXTRACK = 59
SM_CYMAXTRACK = 60
SM_CXMAXIMIZED = 61
SM_CYMAXIMIZED = 62
SM_NETWORK = 63
SM_CLEANBOOT = 67
SM_CXDRAG = 68
SM_CYDRAG = 69
SM_SHOWSOUNDS = 70
SM_CXMENUCHECK = 71 # Use instead of GetMenuCheckMarkDimensions()!
SM_CYMENUCHECK = 72
SM_SLOWMACHINE = 73
SM_MIDEASTENABLED = 74
SM_MOUSEWHEELPRESENT = 75
SM_XVIRTUALSCREEN = 76
SM_YVIRTUALSCREEN = 77
SM_CXVIRTUALSCREEN = 78
SM_CYVIRTUALSCREEN = 79
SM_CMONITORS = 80
SM_SAMEDISPLAYFORMAT = 81
SM_IMMENABLED = 82
SM_CXFOCUSBORDER = 83
SM_CYFOCUSBORDER = 84
SM_TABLETPC = 86
SM_MEDIACENTER = 87
SM_STARTER = 88
SM_SERVERR2 = 89
SM_MOUSEHORIZONTALWHEELPRESENT = 91
SM_CXPADDEDBORDER = 92
SM_CMETRICS = 93
SM_REMOTESESSION = 0x1000
SM_SHUTTINGDOWN = 0x2000
SM_REMOTECONTROL = 0x2001
SM_CARETBLINKINGENABLED = 0x2002
#--- SYSTEM_INFO structure, GetSystemInfo() and GetNativeSystemInfo() ---------
# Values used by Wine
# Documented values at MSDN are marked with an asterisk
PROCESSOR_ARCHITECTURE_UNKNOWN = 0xFFFF; # Unknown architecture.
PROCESSOR_ARCHITECTURE_INTEL = 0 # x86 (AMD or Intel) *
PROCESSOR_ARCHITECTURE_MIPS = 1 # MIPS
PROCESSOR_ARCHITECTURE_ALPHA = 2 # Alpha
PROCESSOR_ARCHITECTURE_PPC = 3 # Power PC
PROCESSOR_ARCHITECTURE_SHX = 4 # SHX
PROCESSOR_ARCHITECTURE_ARM = 5 # ARM
PROCESSOR_ARCHITECTURE_IA64 = 6 # Intel Itanium *
PROCESSOR_ARCHITECTURE_ALPHA64 = 7 # Alpha64
PROCESSOR_ARCHITECTURE_MSIL = 8 # MSIL
PROCESSOR_ARCHITECTURE_AMD64 = 9 # x64 (AMD or Intel) *
PROCESSOR_ARCHITECTURE_IA32_ON_WIN64 = 10 # IA32 on Win64
PROCESSOR_ARCHITECTURE_SPARC = 20 # Sparc (Wine)
# Values used by Wine
# PROCESSOR_OPTIL value found at http://code.google.com/p/ddab-lib/
# Documented values at MSDN are marked with an asterisk
PROCESSOR_INTEL_386 = 386 # Intel i386 *
PROCESSOR_INTEL_486 = 486 # Intel i486 *
PROCESSOR_INTEL_PENTIUM = 586 # Intel Pentium *
PROCESSOR_INTEL_IA64 = 2200 # Intel IA64 (Itanium) *
PROCESSOR_AMD_X8664 = 8664 # AMD X86 64 *
PROCESSOR_MIPS_R4000 = 4000 # MIPS R4000, R4101, R3910
PROCESSOR_ALPHA_21064 = 21064 # Alpha 210 64
PROCESSOR_PPC_601 = 601 # PPC 601
PROCESSOR_PPC_603 = 603 # PPC 603
PROCESSOR_PPC_604 = 604 # PPC 604
PROCESSOR_PPC_620 = 620 # PPC 620
PROCESSOR_HITACHI_SH3 = 10003 # Hitachi SH3 (Windows CE)
PROCESSOR_HITACHI_SH3E = 10004 # Hitachi SH3E (Windows CE)
PROCESSOR_HITACHI_SH4 = 10005 # Hitachi SH4 (Windows CE)
PROCESSOR_MOTOROLA_821 = 821 # Motorola 821 (Windows CE)
PROCESSOR_SHx_SH3 = 103 # SHx SH3 (Windows CE)
PROCESSOR_SHx_SH4 = 104 # SHx SH4 (Windows CE)
PROCESSOR_STRONGARM = 2577 # StrongARM (Windows CE)
PROCESSOR_ARM720 = 1824 # ARM 720 (Windows CE)
PROCESSOR_ARM820 = 2080 # ARM 820 (Windows CE)
PROCESSOR_ARM920 = 2336 # ARM 920 (Windows CE)
PROCESSOR_ARM_7TDMI = 70001 # ARM 7TDMI (Windows CE)
PROCESSOR_OPTIL = 0x494F # MSIL
# typedef struct _SYSTEM_INFO {
# union {
# DWORD dwOemId;
# struct {
# WORD wProcessorArchitecture;
# WORD wReserved;
# } ;
# } ;
# DWORD dwPageSize;
# LPVOID lpMinimumApplicationAddress;
# LPVOID lpMaximumApplicationAddress;
# DWORD_PTR dwActiveProcessorMask;
# DWORD dwNumberOfProcessors;
# DWORD dwProcessorType;
# DWORD dwAllocationGranularity;
# WORD wProcessorLevel;
# WORD wProcessorRevision;
# } SYSTEM_INFO;
class _SYSTEM_INFO_OEM_ID_STRUCT(Structure):
_fields_ = [
("wProcessorArchitecture", WORD),
("wReserved", WORD),
]
class _SYSTEM_INFO_OEM_ID(Union):
_fields_ = [
("dwOemId", DWORD),
("w", _SYSTEM_INFO_OEM_ID_STRUCT),
]
class SYSTEM_INFO(Structure):
_fields_ = [
("id", _SYSTEM_INFO_OEM_ID),
("dwPageSize", DWORD),
("lpMinimumApplicationAddress", LPVOID),
("lpMaximumApplicationAddress", LPVOID),
("dwActiveProcessorMask", DWORD_PTR),
("dwNumberOfProcessors", DWORD),
("dwProcessorType", DWORD),
("dwAllocationGranularity", DWORD),
("wProcessorLevel", WORD),
("wProcessorRevision", WORD),
]
def __get_dwOemId(self):
return self.id.dwOemId
def __set_dwOemId(self, value):
self.id.dwOemId = value
dwOemId = property(__get_dwOemId, __set_dwOemId)
def __get_wProcessorArchitecture(self):
return self.id.w.wProcessorArchitecture
def __set_wProcessorArchitecture(self, value):
self.id.w.wProcessorArchitecture = value
wProcessorArchitecture = property(__get_wProcessorArchitecture, __set_wProcessorArchitecture)
LPSYSTEM_INFO = ctypes.POINTER(SYSTEM_INFO)
# void WINAPI GetSystemInfo(
# __out LPSYSTEM_INFO lpSystemInfo
# );
def GetSystemInfo():
_GetSystemInfo = windll.kernel32.GetSystemInfo
_GetSystemInfo.argtypes = [LPSYSTEM_INFO]
_GetSystemInfo.restype = None
sysinfo = SYSTEM_INFO()
_GetSystemInfo(byref(sysinfo))
return sysinfo
# void WINAPI GetNativeSystemInfo(
# __out LPSYSTEM_INFO lpSystemInfo
# );
def GetNativeSystemInfo():
_GetNativeSystemInfo = windll.kernel32.GetNativeSystemInfo
_GetNativeSystemInfo.argtypes = [LPSYSTEM_INFO]
_GetNativeSystemInfo.restype = None
sysinfo = SYSTEM_INFO()
_GetNativeSystemInfo(byref(sysinfo))
return sysinfo
# int WINAPI GetSystemMetrics(
# __in int nIndex
# );
def GetSystemMetrics(nIndex):
_GetSystemMetrics = windll.user32.GetSystemMetrics
_GetSystemMetrics.argtypes = [ctypes.c_int]
_GetSystemMetrics.restype = ctypes.c_int
return _GetSystemMetrics(nIndex)
# SIZE_T WINAPI GetLargePageMinimum(void);
def GetLargePageMinimum():
_GetLargePageMinimum = windll.user32.GetLargePageMinimum
_GetLargePageMinimum.argtypes = []
_GetLargePageMinimum.restype = SIZE_T
return _GetLargePageMinimum()
# HANDLE WINAPI GetCurrentProcess(void);
def GetCurrentProcess():
## return 0xFFFFFFFFFFFFFFFFL
_GetCurrentProcess = windll.kernel32.GetCurrentProcess
_GetCurrentProcess.argtypes = []
_GetCurrentProcess.restype = HANDLE
return _GetCurrentProcess()
# HANDLE WINAPI GetCurrentThread(void);
def GetCurrentThread():
## return 0xFFFFFFFFFFFFFFFEL
_GetCurrentThread = windll.kernel32.GetCurrentThread
_GetCurrentThread.argtypes = []
_GetCurrentThread.restype = HANDLE
return _GetCurrentThread()
# BOOL WINAPI IsWow64Process(
# __in HANDLE hProcess,
# __out PBOOL Wow64Process
# );
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)
# DWORD WINAPI GetVersion(void);
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)
# BOOL WINAPI GetVersionEx(
# __inout LPOSVERSIONINFO lpVersionInfo
# );
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
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
GetVersionEx = GuessStringType(GetVersionExA, GetVersionExW)
# BOOL WINAPI GetProductInfo(
# __in DWORD dwOSMajorVersion,
# __in DWORD dwOSMinorVersion,
# __in DWORD dwSpMajorVersion,
# __in DWORD dwSpMinorVersion,
# __out PDWORD pdwReturnedProductType
# );
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
# BOOL WINAPI VerifyVersionInfo(
# __in LPOSVERSIONINFOEX lpVersionInfo,
# __in DWORD dwTypeMask,
# __in DWORDLONG 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")
def VerifyVersionInfoA(lpVersionInfo, dwTypeMask, dwlConditionMask):
_VerifyVersionInfoA = windll.kernel32.VerifyVersionInfoA
_VerifyVersionInfoA.argtypes = [LPOSVERSIONINFOEXA, DWORD, DWORDLONG]
_VerifyVersionInfoA.restype = bool
return _VerifyVersionInfoA(byref(lpVersionInfo), dwTypeMask, dwlConditionMask)
def VerifyVersionInfoW(lpVersionInfo, dwTypeMask, dwlConditionMask):
_VerifyVersionInfoW = windll.kernel32.VerifyVersionInfoW
_VerifyVersionInfoW.argtypes = [LPOSVERSIONINFOEXW, DWORD, DWORDLONG]
_VerifyVersionInfoW.restype = bool
return _VerifyVersionInfoW(byref(lpVersionInfo), dwTypeMask, dwlConditionMask)
# ULONGLONG WINAPI VerSetConditionMask(
# __in ULONGLONG dwlConditionMask,
# __in DWORD dwTypeBitMask,
# __in BYTE dwConditionMask
# );
def VerSetConditionMask(dwlConditionMask, dwTypeBitMask, dwConditionMask):
_VerSetConditionMask = windll.kernel32.VerSetConditionMask
_VerSetConditionMask.argtypes = [ULONGLONG, DWORD, BYTE]
_VerSetConditionMask.restype = ULONGLONG
return _VerSetConditionMask(dwlConditionMask, dwTypeBitMask, dwConditionMask)
#--- get_bits, get_arch and get_os --------------------------------------------
ARCH_UNKNOWN = "unknown"
ARCH_I386 = "i386"
ARCH_MIPS = "mips"
ARCH_ALPHA = "alpha"
ARCH_PPC = "ppc"
ARCH_SHX = "shx"
ARCH_ARM = "arm"
ARCH_ARM64 = "arm64"
ARCH_THUMB = "thumb"
ARCH_IA64 = "ia64"
ARCH_ALPHA64 = "alpha64"
ARCH_MSIL = "msil"
ARCH_AMD64 = "amd64"
ARCH_SPARC = "sparc"
# aliases
ARCH_IA32 = ARCH_I386
ARCH_X86 = ARCH_I386
ARCH_X64 = ARCH_AMD64
ARCH_ARM7 = ARCH_ARM
ARCH_ARM8 = ARCH_ARM64
ARCH_T32 = ARCH_THUMB
ARCH_AARCH32 = ARCH_ARM7
ARCH_AARCH64 = ARCH_ARM8
ARCH_POWERPC = ARCH_PPC
ARCH_HITACHI = ARCH_SHX
ARCH_ITANIUM = ARCH_IA64
# win32 constants -> our constants
_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,
}
OS_UNKNOWN = "Unknown"
OS_NT = "Windows NT"
OS_W2K = "Windows 2000"
OS_XP = "Windows XP"
OS_XP_64 = "Windows XP (64 bits)"
OS_W2K3 = "Windows 2003"
OS_W2K3_64 = "Windows 2003 (64 bits)"
OS_W2K3R2 = "Windows 2003 R2"
OS_W2K3R2_64 = "Windows 2003 R2 (64 bits)"
OS_W2K8 = "Windows 2008"
OS_W2K8_64 = "Windows 2008 (64 bits)"
OS_W2K8R2 = "Windows 2008 R2"
OS_W2K8R2_64 = "Windows 2008 R2 (64 bits)"
OS_VISTA = "Windows Vista"
OS_VISTA_64 = "Windows Vista (64 bits)"
OS_W7 = "Windows 7"
OS_W7_64 = "Windows 7 (64 bits)"
OS_SEVEN = OS_W7
OS_SEVEN_64 = OS_W7_64
OS_WINDOWS_NT = OS_NT
OS_WINDOWS_2000 = OS_W2K
OS_WINDOWS_XP = OS_XP
OS_WINDOWS_XP_64 = OS_XP_64
OS_WINDOWS_2003 = OS_W2K3
OS_WINDOWS_2003_64 = OS_W2K3_64
OS_WINDOWS_2003_R2 = OS_W2K3R2
OS_WINDOWS_2003_R2_64 = OS_W2K3R2_64
OS_WINDOWS_2008 = OS_W2K8
OS_WINDOWS_2008_64 = OS_W2K8_64
OS_WINDOWS_2008_R2 = OS_W2K8R2
OS_WINDOWS_2008_R2_64 = OS_W2K8R2_64
OS_WINDOWS_VISTA = OS_VISTA
OS_WINDOWS_VISTA_64 = OS_VISTA_64
OS_WINDOWS_SEVEN = OS_W7
OS_WINDOWS_SEVEN_64 = OS_W7_64
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
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
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
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'
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
# The order of the following definitions DOES matter!
# Current integer size in bits. See L{_get_bits} for more details.
bits = _get_bits()
# Current processor architecture. See L{_get_arch} for more details.
arch = _get_arch()
# Set to C{True} if the current process is running in WOW64. See L{_get_wow64} for more details.
wow64 = _get_wow64()
_osvi = GetVersionEx()
# Current operating system. See L{_get_os} for more details.
os = _get_os(_osvi)
# Current operating system as an NTDDI constant. See L{_get_ntddi} for more details.
NTDDI_VERSION = _get_ntddi(_osvi)
# Upper word of L{NTDDI_VERSION}, contains the OS major and minor version number.
WINVER = NTDDI_VERSION >> 16
#--- version.dll --------------------------------------------------------------
VS_FF_DEBUG = 0x00000001
VS_FF_PRERELEASE = 0x00000002
VS_FF_PATCHED = 0x00000004
VS_FF_PRIVATEBUILD = 0x00000008
VS_FF_INFOINFERRED = 0x00000010
VS_FF_SPECIALBUILD = 0x00000020
VOS_UNKNOWN = 0x00000000
VOS__WINDOWS16 = 0x00000001
VOS__PM16 = 0x00000002
VOS__PM32 = 0x00000003
VOS__WINDOWS32 = 0x00000004
VOS_DOS = 0x00010000
VOS_OS216 = 0x00020000
VOS_OS232 = 0x00030000
VOS_NT = 0x00040000
VOS_DOS_WINDOWS16 = 0x00010001
VOS_DOS_WINDOWS32 = 0x00010004
VOS_NT_WINDOWS32 = 0x00040004
VOS_OS216_PM16 = 0x00020002
VOS_OS232_PM32 = 0x00030003
VFT_UNKNOWN = 0x00000000
VFT_APP = 0x00000001
VFT_DLL = 0x00000002
VFT_DRV = 0x00000003
VFT_FONT = 0x00000004
VFT_VXD = 0x00000005
VFT_RESERVED = 0x00000006 # undocumented
VFT_STATIC_LIB = 0x00000007
VFT2_UNKNOWN = 0x00000000
VFT2_DRV_PRINTER = 0x00000001
VFT2_DRV_KEYBOARD = 0x00000002
VFT2_DRV_LANGUAGE = 0x00000003
VFT2_DRV_DISPLAY = 0x00000004
VFT2_DRV_MOUSE = 0x00000005
VFT2_DRV_NETWORK = 0x00000006
VFT2_DRV_SYSTEM = 0x00000007
VFT2_DRV_INSTALLABLE = 0x00000008
VFT2_DRV_SOUND = 0x00000009
VFT2_DRV_COMM = 0x0000000A
VFT2_DRV_RESERVED = 0x0000000B # undocumented
VFT2_DRV_VERSIONED_PRINTER = 0x0000000C
VFT2_FONT_RASTER = 0x00000001
VFT2_FONT_VECTOR = 0x00000002
VFT2_FONT_TRUETYPE = 0x00000003
# typedef struct tagVS_FIXEDFILEINFO {
# DWORD dwSignature;
# DWORD dwStrucVersion;
# DWORD dwFileVersionMS;
# DWORD dwFileVersionLS;
# DWORD dwProductVersionMS;
# DWORD dwProductVersionLS;
# DWORD dwFileFlagsMask;
# DWORD dwFileFlags;
# DWORD dwFileOS;
# DWORD dwFileType;
# DWORD dwFileSubtype;
# DWORD dwFileDateMS;
# DWORD dwFileDateLS;
# } VS_FIXEDFILEINFO;
class VS_FIXEDFILEINFO(Structure):
_fields_ = [
("dwSignature", DWORD),
("dwStrucVersion", DWORD),
("dwFileVersionMS", DWORD),
("dwFileVersionLS", DWORD),
("dwProductVersionMS", DWORD),
("dwProductVersionLS", DWORD),
("dwFileFlagsMask", DWORD),
("dwFileFlags", DWORD),
("dwFileOS", DWORD),
("dwFileType", DWORD),
("dwFileSubtype", DWORD),
("dwFileDateMS", DWORD),
("dwFileDateLS", DWORD),
]
PVS_FIXEDFILEINFO = POINTER(VS_FIXEDFILEINFO)
LPVS_FIXEDFILEINFO = PVS_FIXEDFILEINFO
# BOOL WINAPI GetFileVersionInfo(
# _In_ LPCTSTR lptstrFilename,
# _Reserved_ DWORD dwHandle,
# _In_ DWORD dwLen,
# _Out_ LPVOID lpData
# );
# DWORD WINAPI GetFileVersionInfoSize(
# _In_ LPCTSTR lptstrFilename,
# _Out_opt_ LPDWORD lpdwHandle
# );
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
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
GetFileVersionInfo = GuessStringType(GetFileVersionInfoA, GetFileVersionInfoW)
# BOOL WINAPI VerQueryValue(
# _In_ LPCVOID pBlock,
# _In_ LPCTSTR lpSubBlock,
# _Out_ LPVOID *lplpBuffer,
# _Out_ PUINT puLen
# );
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
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
VerQueryValue = GuessStringType(VerQueryValueA, VerQueryValueW)
#==============================================================================
# This calculates the list of exported symbols.
_all = set(vars().keys()).difference(_all)
__all__ = [_x for _x in _all if not _x.startswith('_')]
__all__.sort()
#==============================================================================
| 36,813 | Python | 34.432146 | 121 | 0.6219 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/win32/dbghelp.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Wrapper for dbghelp.dll in ctypes.
"""
__revision__ = "$Id$"
from winappdbg.win32.defines import *
from winappdbg.win32.version import *
from winappdbg.win32.kernel32 import *
# DbgHelp versions and features list:
# http://msdn.microsoft.com/en-us/library/windows/desktop/ms679294(v=vs.85).aspx
#------------------------------------------------------------------------------
# Tries to load the newest version of dbghelp.dll if available.
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
_load_latest_dbghelp_dll()
# Recover the old binding of the "os" symbol.
# XXX FIXME not sure if I really need to do this!
##from version import os
#------------------------------------------------------------------------------
#==============================================================================
# This is used later on to calculate the list of exported symbols.
_all = None
_all = set(vars().keys())
#==============================================================================
# SymGetHomeDirectory "type" values
hdBase = 0
hdSym = 1
hdSrc = 2
UNDNAME_32_BIT_DECODE = 0x0800
UNDNAME_COMPLETE = 0x0000
UNDNAME_NAME_ONLY = 0x1000
UNDNAME_NO_ACCESS_SPECIFIERS = 0x0080
UNDNAME_NO_ALLOCATION_LANGUAGE = 0x0010
UNDNAME_NO_ALLOCATION_MODEL = 0x0008
UNDNAME_NO_ARGUMENTS = 0x2000
UNDNAME_NO_CV_THISTYPE = 0x0040
UNDNAME_NO_FUNCTION_RETURNS = 0x0004
UNDNAME_NO_LEADING_UNDERSCORES = 0x0001
UNDNAME_NO_MEMBER_TYPE = 0x0200
UNDNAME_NO_MS_KEYWORDS = 0x0002
UNDNAME_NO_MS_THISTYPE = 0x0020
UNDNAME_NO_RETURN_UDT_MODEL = 0x0400
UNDNAME_NO_SPECIAL_SYMS = 0x4000
UNDNAME_NO_THISTYPE = 0x0060
UNDNAME_NO_THROW_SIGNATURES = 0x0100
#--- IMAGEHLP_MODULE structure and related ------------------------------------
SYMOPT_ALLOW_ABSOLUTE_SYMBOLS = 0x00000800
SYMOPT_ALLOW_ZERO_ADDRESS = 0x01000000
SYMOPT_AUTO_PUBLICS = 0x00010000
SYMOPT_CASE_INSENSITIVE = 0x00000001
SYMOPT_DEBUG = 0x80000000
SYMOPT_DEFERRED_LOADS = 0x00000004
SYMOPT_DISABLE_SYMSRV_AUTODETECT = 0x02000000
SYMOPT_EXACT_SYMBOLS = 0x00000400
SYMOPT_FAIL_CRITICAL_ERRORS = 0x00000200
SYMOPT_FAVOR_COMPRESSED = 0x00800000
SYMOPT_FLAT_DIRECTORY = 0x00400000
SYMOPT_IGNORE_CVREC = 0x00000080
SYMOPT_IGNORE_IMAGEDIR = 0x00200000
SYMOPT_IGNORE_NT_SYMPATH = 0x00001000
SYMOPT_INCLUDE_32BIT_MODULES = 0x00002000
SYMOPT_LOAD_ANYTHING = 0x00000040
SYMOPT_LOAD_LINES = 0x00000010
SYMOPT_NO_CPP = 0x00000008
SYMOPT_NO_IMAGE_SEARCH = 0x00020000
SYMOPT_NO_PROMPTS = 0x00080000
SYMOPT_NO_PUBLICS = 0x00008000
SYMOPT_NO_UNQUALIFIED_LOADS = 0x00000100
SYMOPT_OVERWRITE = 0x00100000
SYMOPT_PUBLICS_ONLY = 0x00004000
SYMOPT_SECURE = 0x00040000
SYMOPT_UNDNAME = 0x00000002
##SSRVOPT_DWORD
##SSRVOPT_DWORDPTR
##SSRVOPT_GUIDPTR
##
##SSRVOPT_CALLBACK
##SSRVOPT_DOWNSTREAM_STORE
##SSRVOPT_FLAT_DEFAULT_STORE
##SSRVOPT_FAVOR_COMPRESSED
##SSRVOPT_NOCOPY
##SSRVOPT_OVERWRITE
##SSRVOPT_PARAMTYPE
##SSRVOPT_PARENTWIN
##SSRVOPT_PROXY
##SSRVOPT_RESET
##SSRVOPT_SECURE
##SSRVOPT_SETCONTEXT
##SSRVOPT_TRACE
##SSRVOPT_UNATTENDED
# typedef enum
# {
# SymNone = 0,
# SymCoff,
# SymCv,
# SymPdb,
# SymExport,
# SymDeferred,
# SymSym,
# SymDia,
# SymVirtual,
# NumSymTypes
# } SYM_TYPE;
SymNone = 0
SymCoff = 1
SymCv = 2
SymPdb = 3
SymExport = 4
SymDeferred = 5
SymSym = 6
SymDia = 7
SymVirtual = 8
NumSymTypes = 9
# typedef struct _IMAGEHLP_MODULE64 {
# DWORD SizeOfStruct;
# DWORD64 BaseOfImage;
# DWORD ImageSize;
# DWORD TimeDateStamp;
# DWORD CheckSum;
# DWORD NumSyms;
# SYM_TYPE SymType;
# TCHAR ModuleName[32];
# TCHAR ImageName[256];
# TCHAR LoadedImageName[256];
# TCHAR LoadedPdbName[256];
# DWORD CVSig;
# TCHAR CVData[MAX_PATH*3];
# DWORD PdbSig;
# GUID PdbSig70;
# DWORD PdbAge;
# BOOL PdbUnmatched;
# BOOL DbgUnmatched;
# BOOL LineNumbers;
# BOOL GlobalSymbols;
# BOOL TypeInfo;
# BOOL SourceIndexed;
# BOOL Publics;
# } IMAGEHLP_MODULE64, *PIMAGEHLP_MODULE64;
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)
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)
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)
class IMAGEHLP_MODULEW64 (Structure):
_fields_ = [
("SizeOfStruct", DWORD),
("BaseOfImage", DWORD64),
("ImageSize", DWORD),
("TimeDateStamp", DWORD),
("CheckSum", DWORD),
("NumSyms", DWORD),
("SymType", DWORD), # SYM_TYPE
("ModuleName", WCHAR * 32),
("ImageName", WCHAR * 256),
("LoadedImageName", WCHAR * 256),
("LoadedPdbName", WCHAR * 256),
("CVSig", DWORD),
("CVData", WCHAR * (MAX_PATH * 3)),
("PdbSig", DWORD),
("PdbSig70", GUID),
("PdbAge", DWORD),
("PdbUnmatched", BOOL),
("DbgUnmatched", BOOL),
("LineNumbers", BOOL),
("GlobalSymbols", BOOL),
("TypeInfo", BOOL),
("SourceIndexed", BOOL),
("Publics", BOOL),
]
PIMAGEHLP_MODULEW64 = POINTER(IMAGEHLP_MODULEW64)
#--- dbghelp.dll --------------------------------------------------------------
# XXX the ANSI versions of these functions don't end in "A" as expected!
# BOOL WINAPI MakeSureDirectoryPathExists(
# _In_ PCSTR DirPath
# );
def MakeSureDirectoryPathExistsA(DirPath):
_MakeSureDirectoryPathExists = windll.dbghelp.MakeSureDirectoryPathExists
_MakeSureDirectoryPathExists.argtypes = [LPSTR]
_MakeSureDirectoryPathExists.restype = bool
_MakeSureDirectoryPathExists.errcheck = RaiseIfZero
return _MakeSureDirectoryPathExists(DirPath)
MakeSureDirectoryPathExistsW = MakeWideVersion(MakeSureDirectoryPathExistsA)
MakeSureDirectoryPathExists = GuessStringType(MakeSureDirectoryPathExistsA, MakeSureDirectoryPathExistsW)
# BOOL WINAPI SymInitialize(
# __in HANDLE hProcess,
# __in_opt PCTSTR UserSearchPath,
# __in BOOL fInvadeProcess
# );
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)
SymInitializeW = MakeWideVersion(SymInitializeA)
SymInitialize = GuessStringType(SymInitializeA, SymInitializeW)
# BOOL WINAPI SymCleanup(
# __in HANDLE hProcess
# );
def SymCleanup(hProcess):
_SymCleanup = windll.dbghelp.SymCleanup
_SymCleanup.argtypes = [HANDLE]
_SymCleanup.restype = bool
_SymCleanup.errcheck = RaiseIfZero
_SymCleanup(hProcess)
# BOOL WINAPI SymRefreshModuleList(
# __in HANDLE hProcess
# );
def SymRefreshModuleList(hProcess):
_SymRefreshModuleList = windll.dbghelp.SymRefreshModuleList
_SymRefreshModuleList.argtypes = [HANDLE]
_SymRefreshModuleList.restype = bool
_SymRefreshModuleList.errcheck = RaiseIfZero
_SymRefreshModuleList(hProcess)
# BOOL WINAPI SymSetParentWindow(
# __in HWND hwnd
# );
def SymSetParentWindow(hwnd):
_SymSetParentWindow = windll.dbghelp.SymSetParentWindow
_SymSetParentWindow.argtypes = [HWND]
_SymSetParentWindow.restype = bool
_SymSetParentWindow.errcheck = RaiseIfZero
_SymSetParentWindow(hwnd)
# DWORD WINAPI SymSetOptions(
# __in DWORD SymOptions
# );
def SymSetOptions(SymOptions):
_SymSetOptions = windll.dbghelp.SymSetOptions
_SymSetOptions.argtypes = [DWORD]
_SymSetOptions.restype = DWORD
_SymSetOptions.errcheck = RaiseIfZero
_SymSetOptions(SymOptions)
# DWORD WINAPI SymGetOptions(void);
def SymGetOptions():
_SymGetOptions = windll.dbghelp.SymGetOptions
_SymGetOptions.argtypes = []
_SymGetOptions.restype = DWORD
return _SymGetOptions()
# DWORD WINAPI SymLoadModule(
# __in HANDLE hProcess,
# __in_opt HANDLE hFile,
# __in_opt PCSTR ImageName,
# __in_opt PCSTR ModuleName,
# __in DWORD BaseOfDll,
# __in DWORD SizeOfDll
# );
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
SymLoadModuleW = MakeWideVersion(SymLoadModuleA)
SymLoadModule = GuessStringType(SymLoadModuleA, SymLoadModuleW)
# DWORD64 WINAPI SymLoadModule64(
# __in HANDLE hProcess,
# __in_opt HANDLE hFile,
# __in_opt PCSTR ImageName,
# __in_opt PCSTR ModuleName,
# __in DWORD64 BaseOfDll,
# __in DWORD SizeOfDll
# );
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
SymLoadModule64W = MakeWideVersion(SymLoadModule64A)
SymLoadModule64 = GuessStringType(SymLoadModule64A, SymLoadModule64W)
# BOOL WINAPI SymUnloadModule(
# __in HANDLE hProcess,
# __in DWORD BaseOfDll
# );
def SymUnloadModule(hProcess, BaseOfDll):
_SymUnloadModule = windll.dbghelp.SymUnloadModule
_SymUnloadModule.argtypes = [HANDLE, DWORD]
_SymUnloadModule.restype = bool
_SymUnloadModule.errcheck = RaiseIfZero
_SymUnloadModule(hProcess, BaseOfDll)
# BOOL WINAPI SymUnloadModule64(
# __in HANDLE hProcess,
# __in DWORD64 BaseOfDll
# );
def SymUnloadModule64(hProcess, BaseOfDll):
_SymUnloadModule64 = windll.dbghelp.SymUnloadModule64
_SymUnloadModule64.argtypes = [HANDLE, DWORD64]
_SymUnloadModule64.restype = bool
_SymUnloadModule64.errcheck = RaiseIfZero
_SymUnloadModule64(hProcess, BaseOfDll)
# BOOL WINAPI SymGetModuleInfo(
# __in HANDLE hProcess,
# __in DWORD dwAddr,
# __out PIMAGEHLP_MODULE ModuleInfo
# );
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
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
SymGetModuleInfo = GuessStringType(SymGetModuleInfoA, SymGetModuleInfoW)
# BOOL WINAPI SymGetModuleInfo64(
# __in HANDLE hProcess,
# __in DWORD64 dwAddr,
# __out PIMAGEHLP_MODULE64 ModuleInfo
# );
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
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
SymGetModuleInfo64 = GuessStringType(SymGetModuleInfo64A, SymGetModuleInfo64W)
# BOOL CALLBACK SymEnumerateModulesProc(
# __in PCTSTR ModuleName,
# __in DWORD BaseOfDll,
# __in_opt PVOID UserContext
# );
PSYM_ENUMMODULES_CALLBACK = WINFUNCTYPE(BOOL, LPSTR, DWORD, PVOID)
PSYM_ENUMMODULES_CALLBACKW = WINFUNCTYPE(BOOL, LPWSTR, DWORD, PVOID)
# BOOL CALLBACK SymEnumerateModulesProc64(
# __in PCTSTR ModuleName,
# __in DWORD64 BaseOfDll,
# __in_opt PVOID UserContext
# );
PSYM_ENUMMODULES_CALLBACK64 = WINFUNCTYPE(BOOL, LPSTR, DWORD64, PVOID)
PSYM_ENUMMODULES_CALLBACKW64 = WINFUNCTYPE(BOOL, LPWSTR, DWORD64, PVOID)
# BOOL WINAPI SymEnumerateModules(
# __in HANDLE hProcess,
# __in PSYM_ENUMMODULES_CALLBACK EnumModulesCallback,
# __in_opt PVOID UserContext
# );
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)
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)
SymEnumerateModules = GuessStringType(SymEnumerateModulesA, SymEnumerateModulesW)
# BOOL WINAPI SymEnumerateModules64(
# __in HANDLE hProcess,
# __in PSYM_ENUMMODULES_CALLBACK64 EnumModulesCallback,
# __in_opt PVOID UserContext
# );
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)
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)
SymEnumerateModules64 = GuessStringType(SymEnumerateModules64A, SymEnumerateModules64W)
# BOOL CALLBACK SymEnumerateSymbolsProc(
# __in PCTSTR SymbolName,
# __in DWORD SymbolAddress,
# __in ULONG SymbolSize,
# __in_opt PVOID UserContext
# );
PSYM_ENUMSYMBOLS_CALLBACK = WINFUNCTYPE(BOOL, LPSTR, DWORD, ULONG, PVOID)
PSYM_ENUMSYMBOLS_CALLBACKW = WINFUNCTYPE(BOOL, LPWSTR, DWORD, ULONG, PVOID)
# BOOL CALLBACK SymEnumerateSymbolsProc64(
# __in PCTSTR SymbolName,
# __in DWORD64 SymbolAddress,
# __in ULONG SymbolSize,
# __in_opt PVOID UserContext
# );
PSYM_ENUMSYMBOLS_CALLBACK64 = WINFUNCTYPE(BOOL, LPSTR, DWORD64, ULONG, PVOID)
PSYM_ENUMSYMBOLS_CALLBACKW64 = WINFUNCTYPE(BOOL, LPWSTR, DWORD64, ULONG, PVOID)
# BOOL WINAPI SymEnumerateSymbols(
# __in HANDLE hProcess,
# __in ULONG BaseOfDll,
# __in PSYM_ENUMSYMBOLS_CALLBACK EnumSymbolsCallback,
# __in_opt PVOID UserContext
# );
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)
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)
SymEnumerateSymbols = GuessStringType(SymEnumerateSymbolsA, SymEnumerateSymbolsW)
# BOOL WINAPI SymEnumerateSymbols64(
# __in HANDLE hProcess,
# __in ULONG64 BaseOfDll,
# __in PSYM_ENUMSYMBOLS_CALLBACK64 EnumSymbolsCallback,
# __in_opt PVOID UserContext
# );
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)
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)
SymEnumerateSymbols64 = GuessStringType(SymEnumerateSymbols64A, SymEnumerateSymbols64W)
# DWORD WINAPI UnDecorateSymbolName(
# __in PCTSTR DecoratedName,
# __out PTSTR UnDecoratedName,
# __in DWORD UndecoratedLength,
# __in DWORD Flags
# );
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
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
UnDecorateSymbolName = GuessStringType(UnDecorateSymbolNameA, UnDecorateSymbolNameW)
# BOOL WINAPI SymGetSearchPath(
# __in HANDLE hProcess,
# __out PTSTR SearchPath,
# __in DWORD SearchPathLength
# );
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
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
SymGetSearchPath = GuessStringType(SymGetSearchPathA, SymGetSearchPathW)
# BOOL WINAPI SymSetSearchPath(
# __in HANDLE hProcess,
# __in_opt PCTSTR SearchPath
# );
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)
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)
SymSetSearchPath = GuessStringType(SymSetSearchPathA, SymSetSearchPathW)
# PTCHAR WINAPI SymGetHomeDirectory(
# __in DWORD type,
# __out PTSTR dir,
# __in size_t size
# );
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
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
SymGetHomeDirectory = GuessStringType(SymGetHomeDirectoryA, SymGetHomeDirectoryW)
# PTCHAR WINAPI SymSetHomeDirectory(
# __in HANDLE hProcess,
# __in_opt PCTSTR dir
# );
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
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
SymSetHomeDirectory = GuessStringType(SymSetHomeDirectoryA, SymSetHomeDirectoryW)
#--- DbgHelp 5+ support, patch by Neitsa --------------------------------------
# XXX TODO
# + use the GuessStringType decorator for ANSI/Wide versions
# + replace hardcoded struct sizes with sizeof() calls
# + StackWalk64 should raise on error, but something has to be done about it
# not setting the last error code (maybe we should call SetLastError
# ourselves with a default error code?)
# /Mario
#maximum length of a symbol name
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)
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)
#===============================================================================
# BOOL WINAPI SymFromName(
# __in HANDLE hProcess,
# __in PCTSTR Name,
# __inout PSYMBOL_INFO Symbol
# );
#===============================================================================
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
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
#===============================================================================
# BOOL WINAPI SymFromAddr(
# __in HANDLE hProcess,
# __in DWORD64 Address,
# __out_opt PDWORD64 Displacement,
# __inout PSYMBOL_INFO Symbol
# );
#===============================================================================
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)
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)
#===============================================================================
# typedef struct _IMAGEHLP_SYMBOL64 {
# DWORD SizeOfStruct;
# DWORD64 Address;
# DWORD Size;
# DWORD Flags;
# DWORD MaxNameLength;
# CHAR Name[1];
# } IMAGEHLP_SYMBOL64, *PIMAGEHLP_SYMBOL64;
#===============================================================================
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)
#===============================================================================
# typedef struct _IMAGEHLP_SYMBOLW64 {
# DWORD SizeOfStruct;
# DWORD64 Address;
# DWORD Size;
# DWORD Flags;
# DWORD MaxNameLength;
# WCHAR Name[1];
# } IMAGEHLP_SYMBOLW64, *PIMAGEHLP_SYMBOLW64;
#===============================================================================
class IMAGEHLP_SYMBOLW64 (Structure):
_fields_ = [
("SizeOfStruct", DWORD),
("Address", DWORD64),
("Size", DWORD),
("Flags", DWORD),
("MaxNameLength", DWORD),
("Name", WCHAR * (MAX_SYM_NAME + 1)),
]
PIMAGEHLP_SYMBOLW64 = POINTER(IMAGEHLP_SYMBOLW64)
#===============================================================================
# BOOL WINAPI SymGetSymFromAddr64(
# __in HANDLE hProcess,
# __in DWORD64 Address,
# __out_opt PDWORD64 Displacement,
# __inout PIMAGEHLP_SYMBOL64 Symbol
# );
#===============================================================================
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)
#TODO: check for the 'W' version of SymGetSymFromAddr64()
#===============================================================================
# typedef struct API_VERSION {
# USHORT MajorVersion;
# USHORT MinorVersion;
# USHORT Revision;
# USHORT Reserved;
# } API_VERSION, *LPAPI_VERSION;
#===============================================================================
class API_VERSION (Structure):
_fields_ = [
("MajorVersion", USHORT),
("MinorVersion", USHORT),
("Revision", USHORT),
("Reserved", USHORT),
]
PAPI_VERSION = POINTER(API_VERSION)
LPAPI_VERSION = PAPI_VERSION
#===============================================================================
# LPAPI_VERSION WINAPI ImagehlpApiVersion(void);
#===============================================================================
def ImagehlpApiVersion():
_ImagehlpApiVersion = windll.dbghelp.ImagehlpApiVersion
_ImagehlpApiVersion.restype = LPAPI_VERSION
api_version = _ImagehlpApiVersion()
return api_version.contents
#===============================================================================
# LPAPI_VERSION WINAPI ImagehlpApiVersionEx(
# __in LPAPI_VERSION AppVersion
# );
#===============================================================================
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
#===============================================================================
# typedef enum {
# AddrMode1616,
# AddrMode1632,
# AddrModeReal,
# AddrModeFlat
# } ADDRESS_MODE;
#===============================================================================
AddrMode1616 = 0
AddrMode1632 = 1
AddrModeReal = 2
AddrModeFlat = 3
ADDRESS_MODE = DWORD #needed for the size of an ADDRESS_MODE (see ADDRESS64)
#===============================================================================
# typedef struct _tagADDRESS64 {
# DWORD64 Offset;
# WORD Segment;
# ADDRESS_MODE Mode;
# } ADDRESS64, *LPADDRESS64;
#===============================================================================
class ADDRESS64 (Structure):
_fields_ = [
("Offset", DWORD64),
("Segment", WORD),
("Mode", ADDRESS_MODE), #it's a member of the ADDRESS_MODE enum.
]
LPADDRESS64 = POINTER(ADDRESS64)
#===============================================================================
# typedef struct _KDHELP64 {
# DWORD64 Thread;
# DWORD ThCallbackStack;
# DWORD ThCallbackBStore;
# DWORD NextCallback;
# DWORD FramePointer;
# DWORD64 KiCallUserMode;
# DWORD64 KeUserCallbackDispatcher;
# DWORD64 SystemRangeStart;
# DWORD64 KiUserExceptionDispatcher;
# DWORD64 StackBase;
# DWORD64 StackLimit;
# DWORD64 Reserved[5];
# } KDHELP64, *PKDHELP64;
#===============================================================================
class KDHELP64 (Structure):
_fields_ = [
("Thread", DWORD64),
("ThCallbackStack", DWORD),
("ThCallbackBStore", DWORD),
("NextCallback", DWORD),
("FramePointer", DWORD),
("KiCallUserMode", DWORD64),
("KeUserCallbackDispatcher", DWORD64),
("SystemRangeStart", DWORD64),
("KiUserExceptionDispatcher", DWORD64),
("StackBase", DWORD64),
("StackLimit", DWORD64),
("Reserved", DWORD64 * 5),
]
PKDHELP64 = POINTER(KDHELP64)
#===============================================================================
# typedef struct _tagSTACKFRAME64 {
# ADDRESS64 AddrPC;
# ADDRESS64 AddrReturn;
# ADDRESS64 AddrFrame;
# ADDRESS64 AddrStack;
# ADDRESS64 AddrBStore;
# PVOID FuncTableEntry;
# DWORD64 Params[4];
# BOOL Far;
# BOOL Virtual;
# DWORD64 Reserved[3];
# KDHELP64 KdHelp;
# } STACKFRAME64, *LPSTACKFRAME64;
#===============================================================================
class STACKFRAME64(Structure):
_fields_ = [
("AddrPC", ADDRESS64),
("AddrReturn", ADDRESS64),
("AddrFrame", ADDRESS64),
("AddrStack", ADDRESS64),
("AddrBStore", ADDRESS64),
("FuncTableEntry", PVOID),
("Params", DWORD64 * 4),
("Far", BOOL),
("Virtual", BOOL),
("Reserved", DWORD64 * 3),
("KdHelp", KDHELP64),
]
LPSTACKFRAME64 = POINTER(STACKFRAME64)
#===============================================================================
# BOOL CALLBACK ReadProcessMemoryProc64(
# __in HANDLE hProcess,
# __in DWORD64 lpBaseAddress,
# __out PVOID lpBuffer,
# __in DWORD nSize,
# __out LPDWORD lpNumberOfBytesRead
# );
#===============================================================================
PREAD_PROCESS_MEMORY_ROUTINE64 = WINFUNCTYPE(BOOL, HANDLE, DWORD64, PVOID, DWORD, LPDWORD)
#===============================================================================
# PVOID CALLBACK FunctionTableAccessProc64(
# __in HANDLE hProcess,
# __in DWORD64 AddrBase
# );
#===============================================================================
PFUNCTION_TABLE_ACCESS_ROUTINE64 = WINFUNCTYPE(PVOID, HANDLE, DWORD64)
#===============================================================================
# DWORD64 CALLBACK GetModuleBaseProc64(
# __in HANDLE hProcess,
# __in DWORD64 Address
# );
#===============================================================================
PGET_MODULE_BASE_ROUTINE64 = WINFUNCTYPE(DWORD64, HANDLE, DWORD64)
#===============================================================================
# DWORD64 CALLBACK GetModuleBaseProc64(
# __in HANDLE hProcess,
# __in DWORD64 Address
# );
#===============================================================================
PTRANSLATE_ADDRESS_ROUTINE64 = WINFUNCTYPE(DWORD64, HANDLE, DWORD64)
# Valid machine types for StackWalk64 function
IMAGE_FILE_MACHINE_I386 = 0x014c #Intel x86
IMAGE_FILE_MACHINE_IA64 = 0x0200 #Intel Itanium Processor Family (IPF)
IMAGE_FILE_MACHINE_AMD64 = 0x8664 #x64 (AMD64 or EM64T)
#===============================================================================
# BOOL WINAPI StackWalk64(
# __in DWORD MachineType,
# __in HANDLE hProcess,
# __in HANDLE hThread,
# __inout LPSTACKFRAME64 StackFrame,
# __inout PVOID ContextRecord,
# __in_opt PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine,
# __in_opt PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine,
# __in_opt PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine,
# __in_opt PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress
# );
#===============================================================================
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
#==============================================================================
# This calculates the list of exported symbols.
_all = set(vars().keys()).difference(_all)
__all__ = [_x for _x in _all if not _x.startswith('_')]
__all__.sort()
#==============================================================================
| 46,705 | Python | 35.546166 | 118 | 0.624323 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/win32/context_i386.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
CONTEXT structure for i386.
"""
__revision__ = "$Id$"
from winappdbg.win32.defines import *
from winappdbg.win32.version import ARCH_I386
#==============================================================================
# This is used later on to calculate the list of exported symbols.
_all = None
_all = set(vars().keys())
#==============================================================================
#--- CONTEXT structures and constants -----------------------------------------
# The following values specify the type of access in the first parameter
# of the exception record when the exception code specifies an access
# violation.
EXCEPTION_READ_FAULT = 0 # exception caused by a read
EXCEPTION_WRITE_FAULT = 1 # exception caused by a write
EXCEPTION_EXECUTE_FAULT = 8 # exception caused by an instruction fetch
CONTEXT_i386 = 0x00010000 # this assumes that i386 and
CONTEXT_i486 = 0x00010000 # i486 have identical context records
CONTEXT_CONTROL = (CONTEXT_i386 | long(0x00000001)) # SS:SP, CS:IP, FLAGS, BP
CONTEXT_INTEGER = (CONTEXT_i386 | long(0x00000002)) # AX, BX, CX, DX, SI, DI
CONTEXT_SEGMENTS = (CONTEXT_i386 | long(0x00000004)) # DS, ES, FS, GS
CONTEXT_FLOATING_POINT = (CONTEXT_i386 | long(0x00000008)) # 387 state
CONTEXT_DEBUG_REGISTERS = (CONTEXT_i386 | long(0x00000010)) # DB 0-3,6,7
CONTEXT_EXTENDED_REGISTERS = (CONTEXT_i386 | long(0x00000020)) # cpu specific extensions
CONTEXT_FULL = (CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS)
CONTEXT_ALL = (CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS | \
CONTEXT_FLOATING_POINT | CONTEXT_DEBUG_REGISTERS | \
CONTEXT_EXTENDED_REGISTERS)
SIZE_OF_80387_REGISTERS = 80
MAXIMUM_SUPPORTED_EXTENSION = 512
# typedef struct _FLOATING_SAVE_AREA {
# DWORD ControlWord;
# DWORD StatusWord;
# DWORD TagWord;
# DWORD ErrorOffset;
# DWORD ErrorSelector;
# DWORD DataOffset;
# DWORD DataSelector;
# BYTE RegisterArea[SIZE_OF_80387_REGISTERS];
# DWORD Cr0NpxState;
# } FLOATING_SAVE_AREA;
class FLOATING_SAVE_AREA(Structure):
_pack_ = 1
_fields_ = [
('ControlWord', DWORD),
('StatusWord', DWORD),
('TagWord', DWORD),
('ErrorOffset', DWORD),
('ErrorSelector', DWORD),
('DataOffset', DWORD),
('DataSelector', DWORD),
('RegisterArea', BYTE * SIZE_OF_80387_REGISTERS),
('Cr0NpxState', DWORD),
]
_integer_members = ('ControlWord', 'StatusWord', 'TagWord', 'ErrorOffset', 'ErrorSelector', 'DataOffset', 'DataSelector', 'Cr0NpxState')
@classmethod
def from_dict(cls, fsa):
'Instance a new structure from a Python dictionary.'
fsa = dict(fsa)
s = cls()
for key in cls._integer_members:
setattr(s, key, fsa.get(key))
ra = fsa.get('RegisterArea', None)
if ra is not None:
for index in compat.xrange(0, SIZE_OF_80387_REGISTERS):
s.RegisterArea[index] = ra[index]
return s
def to_dict(self):
'Convert a structure into a Python dictionary.'
fsa = dict()
for key in self._integer_members:
fsa[key] = getattr(self, key)
ra = [ self.RegisterArea[index] for index in compat.xrange(0, SIZE_OF_80387_REGISTERS) ]
ra = tuple(ra)
fsa['RegisterArea'] = ra
return fsa
PFLOATING_SAVE_AREA = POINTER(FLOATING_SAVE_AREA)
LPFLOATING_SAVE_AREA = PFLOATING_SAVE_AREA
# typedef struct _CONTEXT {
# DWORD ContextFlags;
# DWORD Dr0;
# DWORD Dr1;
# DWORD Dr2;
# DWORD Dr3;
# DWORD Dr6;
# DWORD Dr7;
# FLOATING_SAVE_AREA FloatSave;
# DWORD SegGs;
# DWORD SegFs;
# DWORD SegEs;
# DWORD SegDs;
# DWORD Edi;
# DWORD Esi;
# DWORD Ebx;
# DWORD Edx;
# DWORD Ecx;
# DWORD Eax;
# DWORD Ebp;
# DWORD Eip;
# DWORD SegCs;
# DWORD EFlags;
# DWORD Esp;
# DWORD SegSs;
# BYTE ExtendedRegisters[MAXIMUM_SUPPORTED_EXTENSION];
# } CONTEXT;
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')
@classmethod
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
PCONTEXT = POINTER(CONTEXT)
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)
#--- LDT_ENTRY structure ------------------------------------------------------
# typedef struct _LDT_ENTRY {
# WORD LimitLow;
# WORD BaseLow;
# union {
# struct {
# BYTE BaseMid;
# BYTE Flags1;
# BYTE Flags2;
# BYTE BaseHi;
# } Bytes;
# struct {
# DWORD BaseMid :8;
# DWORD Type :5;
# DWORD Dpl :2;
# DWORD Pres :1;
# DWORD LimitHi :4;
# DWORD Sys :1;
# DWORD Reserved_0 :1;
# DWORD Default_Big :1;
# DWORD Granularity :1;
# DWORD BaseHi :8;
# } Bits;
# } HighWord;
# } LDT_ENTRY,
# *PLDT_ENTRY;
class _LDT_ENTRY_BYTES_(Structure):
_pack_ = 1
_fields_ = [
('BaseMid', BYTE),
('Flags1', BYTE),
('Flags2', BYTE),
('BaseHi', BYTE),
]
class _LDT_ENTRY_BITS_(Structure):
_pack_ = 1
_fields_ = [
('BaseMid', DWORD, 8),
('Type', DWORD, 5),
('Dpl', DWORD, 2),
('Pres', DWORD, 1),
('LimitHi', DWORD, 4),
('Sys', DWORD, 1),
('Reserved_0', DWORD, 1),
('Default_Big', DWORD, 1),
('Granularity', DWORD, 1),
('BaseHi', DWORD, 8),
]
class _LDT_ENTRY_HIGHWORD_(Union):
_pack_ = 1
_fields_ = [
('Bytes', _LDT_ENTRY_BYTES_),
('Bits', _LDT_ENTRY_BITS_),
]
class LDT_ENTRY(Structure):
_pack_ = 1
_fields_ = [
('LimitLow', WORD),
('BaseLow', WORD),
('HighWord', _LDT_ENTRY_HIGHWORD_),
]
PLDT_ENTRY = POINTER(LDT_ENTRY)
LPLDT_ENTRY = PLDT_ENTRY
###############################################################################
# BOOL WINAPI GetThreadSelectorEntry(
# __in HANDLE hThread,
# __in DWORD dwSelector,
# __out LPLDT_ENTRY lpSelectorEntry
# );
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
# BOOL WINAPI GetThreadContext(
# __in HANDLE hThread,
# __inout LPCONTEXT lpContext
# );
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()
# BOOL WINAPI SetThreadContext(
# __in HANDLE hThread,
# __in const CONTEXT* lpContext
# );
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))
#==============================================================================
# This calculates the list of exported symbols.
_all = set(vars().keys()).difference(_all)
__all__ = [_x for _x in _all if not _x.startswith('_')]
__all__.sort()
#==============================================================================
| 16,108 | Python | 34.797778 | 140 | 0.57369 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/win32/gdi32.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Wrapper for gdi32.dll in ctypes.
"""
__revision__ = "$Id$"
from winappdbg.win32.defines import *
from winappdbg.win32.kernel32 import GetLastError, SetLastError
#==============================================================================
# This is used later on to calculate the list of exported symbols.
_all = None
_all = set(vars().keys())
#==============================================================================
#--- Helpers ------------------------------------------------------------------
#--- Types --------------------------------------------------------------------
#--- Constants ----------------------------------------------------------------
# GDI object types
OBJ_PEN = 1
OBJ_BRUSH = 2
OBJ_DC = 3
OBJ_METADC = 4
OBJ_PAL = 5
OBJ_FONT = 6
OBJ_BITMAP = 7
OBJ_REGION = 8
OBJ_METAFILE = 9
OBJ_MEMDC = 10
OBJ_EXTPEN = 11
OBJ_ENHMETADC = 12
OBJ_ENHMETAFILE = 13
OBJ_COLORSPACE = 14
GDI_OBJ_LAST = OBJ_COLORSPACE
# Ternary raster operations
SRCCOPY = 0x00CC0020 # dest = source
SRCPAINT = 0x00EE0086 # dest = source OR dest
SRCAND = 0x008800C6 # dest = source AND dest
SRCINVERT = 0x00660046 # dest = source XOR dest
SRCERASE = 0x00440328 # dest = source AND (NOT dest)
NOTSRCCOPY = 0x00330008 # dest = (NOT source)
NOTSRCERASE = 0x001100A6 # dest = (NOT src) AND (NOT dest)
MERGECOPY = 0x00C000CA # dest = (source AND pattern)
MERGEPAINT = 0x00BB0226 # dest = (NOT source) OR dest
PATCOPY = 0x00F00021 # dest = pattern
PATPAINT = 0x00FB0A09 # dest = DPSnoo
PATINVERT = 0x005A0049 # dest = pattern XOR dest
DSTINVERT = 0x00550009 # dest = (NOT dest)
BLACKNESS = 0x00000042 # dest = BLACK
WHITENESS = 0x00FF0062 # dest = WHITE
NOMIRRORBITMAP = 0x80000000 # Do not Mirror the bitmap in this call
CAPTUREBLT = 0x40000000 # Include layered windows
# Region flags
ERROR = 0
NULLREGION = 1
SIMPLEREGION = 2
COMPLEXREGION = 3
RGN_ERROR = ERROR
# CombineRgn() styles
RGN_AND = 1
RGN_OR = 2
RGN_XOR = 3
RGN_DIFF = 4
RGN_COPY = 5
RGN_MIN = RGN_AND
RGN_MAX = RGN_COPY
# StretchBlt() modes
BLACKONWHITE = 1
WHITEONBLACK = 2
COLORONCOLOR = 3
HALFTONE = 4
MAXSTRETCHBLTMODE = 4
STRETCH_ANDSCANS = BLACKONWHITE
STRETCH_ORSCANS = WHITEONBLACK
STRETCH_DELETESCANS = COLORONCOLOR
STRETCH_HALFTONE = HALFTONE
# PolyFill() modes
ALTERNATE = 1
WINDING = 2
POLYFILL_LAST = 2
# Layout orientation options
LAYOUT_RTL = 0x00000001 # Right to left
LAYOUT_BTT = 0x00000002 # Bottom to top
LAYOUT_VBH = 0x00000004 # Vertical before horizontal
LAYOUT_ORIENTATIONMASK = LAYOUT_RTL + LAYOUT_BTT + LAYOUT_VBH
LAYOUT_BITMAPORIENTATIONPRESERVED = 0x00000008
# Stock objects
WHITE_BRUSH = 0
LTGRAY_BRUSH = 1
GRAY_BRUSH = 2
DKGRAY_BRUSH = 3
BLACK_BRUSH = 4
NULL_BRUSH = 5
HOLLOW_BRUSH = NULL_BRUSH
WHITE_PEN = 6
BLACK_PEN = 7
NULL_PEN = 8
OEM_FIXED_FONT = 10
ANSI_FIXED_FONT = 11
ANSI_VAR_FONT = 12
SYSTEM_FONT = 13
DEVICE_DEFAULT_FONT = 14
DEFAULT_PALETTE = 15
SYSTEM_FIXED_FONT = 16
# Metafile functions
META_SETBKCOLOR = 0x0201
META_SETBKMODE = 0x0102
META_SETMAPMODE = 0x0103
META_SETROP2 = 0x0104
META_SETRELABS = 0x0105
META_SETPOLYFILLMODE = 0x0106
META_SETSTRETCHBLTMODE = 0x0107
META_SETTEXTCHAREXTRA = 0x0108
META_SETTEXTCOLOR = 0x0209
META_SETTEXTJUSTIFICATION = 0x020A
META_SETWINDOWORG = 0x020B
META_SETWINDOWEXT = 0x020C
META_SETVIEWPORTORG = 0x020D
META_SETVIEWPORTEXT = 0x020E
META_OFFSETWINDOWORG = 0x020F
META_SCALEWINDOWEXT = 0x0410
META_OFFSETVIEWPORTORG = 0x0211
META_SCALEVIEWPORTEXT = 0x0412
META_LINETO = 0x0213
META_MOVETO = 0x0214
META_EXCLUDECLIPRECT = 0x0415
META_INTERSECTCLIPRECT = 0x0416
META_ARC = 0x0817
META_ELLIPSE = 0x0418
META_FLOODFILL = 0x0419
META_PIE = 0x081A
META_RECTANGLE = 0x041B
META_ROUNDRECT = 0x061C
META_PATBLT = 0x061D
META_SAVEDC = 0x001E
META_SETPIXEL = 0x041F
META_OFFSETCLIPRGN = 0x0220
META_TEXTOUT = 0x0521
META_BITBLT = 0x0922
META_STRETCHBLT = 0x0B23
META_POLYGON = 0x0324
META_POLYLINE = 0x0325
META_ESCAPE = 0x0626
META_RESTOREDC = 0x0127
META_FILLREGION = 0x0228
META_FRAMEREGION = 0x0429
META_INVERTREGION = 0x012A
META_PAINTREGION = 0x012B
META_SELECTCLIPREGION = 0x012C
META_SELECTOBJECT = 0x012D
META_SETTEXTALIGN = 0x012E
META_CHORD = 0x0830
META_SETMAPPERFLAGS = 0x0231
META_EXTTEXTOUT = 0x0a32
META_SETDIBTODEV = 0x0d33
META_SELECTPALETTE = 0x0234
META_REALIZEPALETTE = 0x0035
META_ANIMATEPALETTE = 0x0436
META_SETPALENTRIES = 0x0037
META_POLYPOLYGON = 0x0538
META_RESIZEPALETTE = 0x0139
META_DIBBITBLT = 0x0940
META_DIBSTRETCHBLT = 0x0b41
META_DIBCREATEPATTERNBRUSH = 0x0142
META_STRETCHDIB = 0x0f43
META_EXTFLOODFILL = 0x0548
META_SETLAYOUT = 0x0149
META_DELETEOBJECT = 0x01f0
META_CREATEPALETTE = 0x00f7
META_CREATEPATTERNBRUSH = 0x01F9
META_CREATEPENINDIRECT = 0x02FA
META_CREATEFONTINDIRECT = 0x02FB
META_CREATEBRUSHINDIRECT = 0x02FC
META_CREATEREGION = 0x06FF
# Metafile escape codes
NEWFRAME = 1
ABORTDOC = 2
NEXTBAND = 3
SETCOLORTABLE = 4
GETCOLORTABLE = 5
FLUSHOUTPUT = 6
DRAFTMODE = 7
QUERYESCSUPPORT = 8
SETABORTPROC = 9
STARTDOC = 10
ENDDOC = 11
GETPHYSPAGESIZE = 12
GETPRINTINGOFFSET = 13
GETSCALINGFACTOR = 14
MFCOMMENT = 15
GETPENWIDTH = 16
SETCOPYCOUNT = 17
SELECTPAPERSOURCE = 18
DEVICEDATA = 19
PASSTHROUGH = 19
GETTECHNOLGY = 20
GETTECHNOLOGY = 20
SETLINECAP = 21
SETLINEJOIN = 22
SETMITERLIMIT = 23
BANDINFO = 24
DRAWPATTERNRECT = 25
GETVECTORPENSIZE = 26
GETVECTORBRUSHSIZE = 27
ENABLEDUPLEX = 28
GETSETPAPERBINS = 29
GETSETPRINTORIENT = 30
ENUMPAPERBINS = 31
SETDIBSCALING = 32
EPSPRINTING = 33
ENUMPAPERMETRICS = 34
GETSETPAPERMETRICS = 35
POSTSCRIPT_DATA = 37
POSTSCRIPT_IGNORE = 38
MOUSETRAILS = 39
GETDEVICEUNITS = 42
GETEXTENDEDTEXTMETRICS = 256
GETEXTENTTABLE = 257
GETPAIRKERNTABLE = 258
GETTRACKKERNTABLE = 259
EXTTEXTOUT = 512
GETFACENAME = 513
DOWNLOADFACE = 514
ENABLERELATIVEWIDTHS = 768
ENABLEPAIRKERNING = 769
SETKERNTRACK = 770
SETALLJUSTVALUES = 771
SETCHARSET = 772
STRETCHBLT = 2048
METAFILE_DRIVER = 2049
GETSETSCREENPARAMS = 3072
QUERYDIBSUPPORT = 3073
BEGIN_PATH = 4096
CLIP_TO_PATH = 4097
END_PATH = 4098
EXT_DEVICE_CAPS = 4099
RESTORE_CTM = 4100
SAVE_CTM = 4101
SET_ARC_DIRECTION = 4102
SET_BACKGROUND_COLOR = 4103
SET_POLY_MODE = 4104
SET_SCREEN_ANGLE = 4105
SET_SPREAD = 4106
TRANSFORM_CTM = 4107
SET_CLIP_BOX = 4108
SET_BOUNDS = 4109
SET_MIRROR_MODE = 4110
OPENCHANNEL = 4110
DOWNLOADHEADER = 4111
CLOSECHANNEL = 4112
POSTSCRIPT_PASSTHROUGH = 4115
ENCAPSULATED_POSTSCRIPT = 4116
POSTSCRIPT_IDENTIFY = 4117
POSTSCRIPT_INJECTION = 4118
CHECKJPEGFORMAT = 4119
CHECKPNGFORMAT = 4120
GET_PS_FEATURESETTING = 4121
GDIPLUS_TS_QUERYVER = 4122
GDIPLUS_TS_RECORD = 4123
SPCLPASSTHROUGH2 = 4568
#--- Structures ---------------------------------------------------------------
# typedef struct _RECT {
# LONG left;
# LONG top;
# LONG right;
# LONG bottom;
# }RECT, *PRECT;
class RECT(Structure):
_fields_ = [
('left', LONG),
('top', LONG),
('right', LONG),
('bottom', LONG),
]
PRECT = POINTER(RECT)
LPRECT = PRECT
# typedef struct tagPOINT {
# LONG x;
# LONG y;
# } POINT;
class POINT(Structure):
_fields_ = [
('x', LONG),
('y', LONG),
]
PPOINT = POINTER(POINT)
LPPOINT = PPOINT
# typedef struct tagBITMAP {
# LONG bmType;
# LONG bmWidth;
# LONG bmHeight;
# LONG bmWidthBytes;
# WORD bmPlanes;
# WORD bmBitsPixel;
# LPVOID bmBits;
# } BITMAP, *PBITMAP;
class BITMAP(Structure):
_fields_ = [
("bmType", LONG),
("bmWidth", LONG),
("bmHeight", LONG),
("bmWidthBytes", LONG),
("bmPlanes", WORD),
("bmBitsPixel", WORD),
("bmBits", LPVOID),
]
PBITMAP = POINTER(BITMAP)
LPBITMAP = PBITMAP
#--- High level classes -------------------------------------------------------
#--- gdi32.dll ----------------------------------------------------------------
# HDC GetDC(
# __in HWND hWnd
# );
def GetDC(hWnd):
_GetDC = windll.gdi32.GetDC
_GetDC.argtypes = [HWND]
_GetDC.restype = HDC
_GetDC.errcheck = RaiseIfZero
return _GetDC(hWnd)
# HDC GetWindowDC(
# __in HWND hWnd
# );
def GetWindowDC(hWnd):
_GetWindowDC = windll.gdi32.GetWindowDC
_GetWindowDC.argtypes = [HWND]
_GetWindowDC.restype = HDC
_GetWindowDC.errcheck = RaiseIfZero
return _GetWindowDC(hWnd)
# int ReleaseDC(
# __in HWND hWnd,
# __in HDC hDC
# );
def ReleaseDC(hWnd, hDC):
_ReleaseDC = windll.gdi32.ReleaseDC
_ReleaseDC.argtypes = [HWND, HDC]
_ReleaseDC.restype = ctypes.c_int
_ReleaseDC.errcheck = RaiseIfZero
_ReleaseDC(hWnd, hDC)
# HGDIOBJ SelectObject(
# __in HDC hdc,
# __in HGDIOBJ hgdiobj
# );
def SelectObject(hdc, hgdiobj):
_SelectObject = windll.gdi32.SelectObject
_SelectObject.argtypes = [HDC, HGDIOBJ]
_SelectObject.restype = HGDIOBJ
_SelectObject.errcheck = RaiseIfZero
return _SelectObject(hdc, hgdiobj)
# HGDIOBJ GetStockObject(
# __in int fnObject
# );
def GetStockObject(fnObject):
_GetStockObject = windll.gdi32.GetStockObject
_GetStockObject.argtypes = [ctypes.c_int]
_GetStockObject.restype = HGDIOBJ
_GetStockObject.errcheck = RaiseIfZero
return _GetStockObject(fnObject)
# DWORD GetObjectType(
# __in HGDIOBJ h
# );
def GetObjectType(h):
_GetObjectType = windll.gdi32.GetObjectType
_GetObjectType.argtypes = [HGDIOBJ]
_GetObjectType.restype = DWORD
_GetObjectType.errcheck = RaiseIfZero
return _GetObjectType(h)
# int GetObject(
# __in HGDIOBJ hgdiobj,
# __in int cbBuffer,
# __out LPVOID lpvObject
# );
def GetObject(hgdiobj, cbBuffer = None, lpvObject = None):
_GetObject = windll.gdi32.GetObject
_GetObject.argtypes = [HGDIOBJ, ctypes.c_int, LPVOID]
_GetObject.restype = ctypes.c_int
_GetObject.errcheck = RaiseIfZero
# Both cbBuffer and lpvObject can be omitted, the correct
# size and structure to return are automatically deduced.
# If lpvObject is given it must be a ctypes object, not a pointer.
# Always returns a ctypes object.
if cbBuffer is not None:
if lpvObject is None:
lpvObject = ctypes.create_string_buffer("", cbBuffer)
elif lpvObject is not None:
cbBuffer = sizeof(lpvObject)
else: # most likely case, both are None
t = GetObjectType(hgdiobj)
if t == OBJ_PEN:
cbBuffer = sizeof(LOGPEN)
lpvObject = LOGPEN()
elif t == OBJ_BRUSH:
cbBuffer = sizeof(LOGBRUSH)
lpvObject = LOGBRUSH()
elif t == OBJ_PAL:
cbBuffer = _GetObject(hgdiobj, 0, None)
lpvObject = (WORD * (cbBuffer // sizeof(WORD)))()
elif t == OBJ_FONT:
cbBuffer = sizeof(LOGFONT)
lpvObject = LOGFONT()
elif t == OBJ_BITMAP: # try the two possible types of bitmap
cbBuffer = sizeof(DIBSECTION)
lpvObject = DIBSECTION()
try:
_GetObject(hgdiobj, cbBuffer, byref(lpvObject))
return lpvObject
except WindowsError:
cbBuffer = sizeof(BITMAP)
lpvObject = BITMAP()
elif t == OBJ_EXTPEN:
cbBuffer = sizeof(LOGEXTPEN)
lpvObject = LOGEXTPEN()
else:
cbBuffer = _GetObject(hgdiobj, 0, None)
lpvObject = ctypes.create_string_buffer("", cbBuffer)
_GetObject(hgdiobj, cbBuffer, byref(lpvObject))
return lpvObject
# LONG GetBitmapBits(
# __in HBITMAP hbmp,
# __in LONG cbBuffer,
# __out LPVOID lpvBits
# );
def GetBitmapBits(hbmp):
_GetBitmapBits = windll.gdi32.GetBitmapBits
_GetBitmapBits.argtypes = [HBITMAP, LONG, LPVOID]
_GetBitmapBits.restype = LONG
_GetBitmapBits.errcheck = RaiseIfZero
bitmap = GetObject(hbmp, lpvObject = BITMAP())
cbBuffer = bitmap.bmWidthBytes * bitmap.bmHeight
lpvBits = ctypes.create_string_buffer("", cbBuffer)
_GetBitmapBits(hbmp, cbBuffer, byref(lpvBits))
return lpvBits.raw
# HBITMAP CreateBitmapIndirect(
# __in const BITMAP *lpbm
# );
def CreateBitmapIndirect(lpbm):
_CreateBitmapIndirect = windll.gdi32.CreateBitmapIndirect
_CreateBitmapIndirect.argtypes = [PBITMAP]
_CreateBitmapIndirect.restype = HBITMAP
_CreateBitmapIndirect.errcheck = RaiseIfZero
return _CreateBitmapIndirect(lpbm)
#==============================================================================
# This calculates the list of exported symbols.
_all = set(vars().keys()).difference(_all)
__all__ = [_x for _x in _all if not _x.startswith('_')]
__all__.sort()
#==============================================================================
| 16,829 | Python | 32.129921 | 79 | 0.564561 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/win32/wtsapi32.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Wrapper for wtsapi32.dll in ctypes.
"""
__revision__ = "$Id$"
from winappdbg.win32.defines import *
from winappdbg.win32.advapi32 import *
#==============================================================================
# This is used later on to calculate the list of exported symbols.
_all = None
_all = set(vars().keys())
#==============================================================================
#--- Constants ----------------------------------------------------------------
WTS_CURRENT_SERVER_HANDLE = 0
WTS_CURRENT_SESSION = 1
#--- WTS_PROCESS_INFO structure -----------------------------------------------
# typedef struct _WTS_PROCESS_INFO {
# DWORD SessionId;
# DWORD ProcessId;
# LPTSTR pProcessName;
# PSID pUserSid;
# } WTS_PROCESS_INFO, *PWTS_PROCESS_INFO;
class WTS_PROCESS_INFOA(Structure):
_fields_ = [
("SessionId", DWORD),
("ProcessId", DWORD),
("pProcessName", LPSTR),
("pUserSid", PSID),
]
PWTS_PROCESS_INFOA = POINTER(WTS_PROCESS_INFOA)
class WTS_PROCESS_INFOW(Structure):
_fields_ = [
("SessionId", DWORD),
("ProcessId", DWORD),
("pProcessName", LPWSTR),
("pUserSid", PSID),
]
PWTS_PROCESS_INFOW = POINTER(WTS_PROCESS_INFOW)
#--- WTSQuerySessionInformation enums and structures --------------------------
# typedef enum _WTS_INFO_CLASS {
# WTSInitialProgram = 0,
# WTSApplicationName = 1,
# WTSWorkingDirectory = 2,
# WTSOEMId = 3,
# WTSSessionId = 4,
# WTSUserName = 5,
# WTSWinStationName = 6,
# WTSDomainName = 7,
# WTSConnectState = 8,
# WTSClientBuildNumber = 9,
# WTSClientName = 10,
# WTSClientDirectory = 11,
# WTSClientProductId = 12,
# WTSClientHardwareId = 13,
# WTSClientAddress = 14,
# WTSClientDisplay = 15,
# WTSClientProtocolType = 16,
# WTSIdleTime = 17,
# WTSLogonTime = 18,
# WTSIncomingBytes = 19,
# WTSOutgoingBytes = 20,
# WTSIncomingFrames = 21,
# WTSOutgoingFrames = 22,
# WTSClientInfo = 23,
# WTSSessionInfo = 24,
# WTSSessionInfoEx = 25,
# WTSConfigInfo = 26,
# WTSValidationInfo = 27,
# WTSSessionAddressV4 = 28,
# WTSIsRemoteSession = 29
# } WTS_INFO_CLASS;
WTSInitialProgram = 0
WTSApplicationName = 1
WTSWorkingDirectory = 2
WTSOEMId = 3
WTSSessionId = 4
WTSUserName = 5
WTSWinStationName = 6
WTSDomainName = 7
WTSConnectState = 8
WTSClientBuildNumber = 9
WTSClientName = 10
WTSClientDirectory = 11
WTSClientProductId = 12
WTSClientHardwareId = 13
WTSClientAddress = 14
WTSClientDisplay = 15
WTSClientProtocolType = 16
WTSIdleTime = 17
WTSLogonTime = 18
WTSIncomingBytes = 19
WTSOutgoingBytes = 20
WTSIncomingFrames = 21
WTSOutgoingFrames = 22
WTSClientInfo = 23
WTSSessionInfo = 24
WTSSessionInfoEx = 25
WTSConfigInfo = 26
WTSValidationInfo = 27
WTSSessionAddressV4 = 28
WTSIsRemoteSession = 29
WTS_INFO_CLASS = ctypes.c_int
# typedef enum _WTS_CONNECTSTATE_CLASS {
# WTSActive,
# WTSConnected,
# WTSConnectQuery,
# WTSShadow,
# WTSDisconnected,
# WTSIdle,
# WTSListen,
# WTSReset,
# WTSDown,
# WTSInit
# } WTS_CONNECTSTATE_CLASS;
WTSActive = 0
WTSConnected = 1
WTSConnectQuery = 2
WTSShadow = 3
WTSDisconnected = 4
WTSIdle = 5
WTSListen = 6
WTSReset = 7
WTSDown = 8
WTSInit = 9
WTS_CONNECTSTATE_CLASS = ctypes.c_int
# typedef struct _WTS_CLIENT_DISPLAY {
# DWORD HorizontalResolution;
# DWORD VerticalResolution;
# DWORD ColorDepth;
# } WTS_CLIENT_DISPLAY, *PWTS_CLIENT_DISPLAY;
class WTS_CLIENT_DISPLAY(Structure):
_fields_ = [
("HorizontalResolution", DWORD),
("VerticalResolution", DWORD),
("ColorDepth", DWORD),
]
PWTS_CLIENT_DISPLAY = POINTER(WTS_CLIENT_DISPLAY)
# typedef struct _WTS_CLIENT_ADDRESS {
# DWORD AddressFamily;
# BYTE Address[20];
# } WTS_CLIENT_ADDRESS, *PWTS_CLIENT_ADDRESS;
# XXX TODO
# typedef struct _WTSCLIENT {
# WCHAR ClientName[CLIENTNAME_LENGTH + 1];
# WCHAR Domain[DOMAIN_LENGTH + 1 ];
# WCHAR UserName[USERNAME_LENGTH + 1];
# WCHAR WorkDirectory[MAX_PATH + 1];
# WCHAR InitialProgram[MAX_PATH + 1];
# BYTE EncryptionLevel;
# ULONG ClientAddressFamily;
# USHORT ClientAddress[CLIENTADDRESS_LENGTH + 1];
# USHORT HRes;
# USHORT VRes;
# USHORT ColorDepth;
# WCHAR ClientDirectory[MAX_PATH + 1];
# ULONG ClientBuildNumber;
# ULONG ClientHardwareId;
# USHORT ClientProductId;
# USHORT OutBufCountHost;
# USHORT OutBufCountClient;
# USHORT OutBufLength;
# WCHAR DeviceId[MAX_PATH + 1];
# } WTSCLIENT, *PWTSCLIENT;
# XXX TODO
# typedef struct _WTSINFO {
# WTS_CONNECTSTATE_CLASS State;
# DWORD SessionId;
# DWORD IncomingBytes;
# DWORD OutgoingBytes;
# DWORD IncomingCompressedBytes;
# DWORD OutgoingCompressedBytes;
# WCHAR WinStationName;
# WCHAR Domain;
# WCHAR UserName;
# LARGE_INTEGER ConnectTime;
# LARGE_INTEGER DisconnectTime;
# LARGE_INTEGER LastInputTime;
# LARGE_INTEGER LogonTime;
# LARGE_INTEGER CurrentTime;
# } WTSINFO, *PWTSINFO;
# XXX TODO
# typedef struct _WTSINFOEX {
# DWORD Level;
# WTSINFOEX_LEVEL Data;
# } WTSINFOEX, *PWTSINFOEX;
# XXX TODO
#--- wtsapi32.dll -------------------------------------------------------------
# void WTSFreeMemory(
# __in PVOID pMemory
# );
def WTSFreeMemory(pMemory):
_WTSFreeMemory = windll.wtsapi32.WTSFreeMemory
_WTSFreeMemory.argtypes = [PVOID]
_WTSFreeMemory.restype = None
_WTSFreeMemory(pMemory)
# BOOL WTSEnumerateProcesses(
# __in HANDLE hServer,
# __in DWORD Reserved,
# __in DWORD Version,
# __out PWTS_PROCESS_INFO *ppProcessInfo,
# __out DWORD *pCount
# );
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
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
WTSEnumerateProcesses = DefaultStringType(WTSEnumerateProcessesA, WTSEnumerateProcessesW)
# BOOL WTSTerminateProcess(
# __in HANDLE hServer,
# __in DWORD ProcessId,
# __in DWORD ExitCode
# );
def WTSTerminateProcess(hServer, ProcessId, ExitCode):
_WTSTerminateProcess = windll.wtsapi32.WTSTerminateProcess
_WTSTerminateProcess.argtypes = [HANDLE, DWORD, DWORD]
_WTSTerminateProcess.restype = bool
_WTSTerminateProcess.errcheck = RaiseIfZero
_WTSTerminateProcess(hServer, ProcessId, ExitCode)
# BOOL WTSQuerySessionInformation(
# __in HANDLE hServer,
# __in DWORD SessionId,
# __in WTS_INFO_CLASS WTSInfoClass,
# __out LPTSTR *ppBuffer,
# __out DWORD *pBytesReturned
# );
# XXX TODO
#--- kernel32.dll -------------------------------------------------------------
# I've no idea why these functions are in kernel32.dll instead of wtsapi32.dll
# BOOL ProcessIdToSessionId(
# __in DWORD dwProcessId,
# __out DWORD *pSessionId
# );
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
# DWORD WTSGetActiveConsoleSessionId(void);
def WTSGetActiveConsoleSessionId():
_WTSGetActiveConsoleSessionId = windll.kernel32.WTSGetActiveConsoleSessionId
_WTSGetActiveConsoleSessionId.argtypes = []
_WTSGetActiveConsoleSessionId.restype = DWORD
_WTSGetActiveConsoleSessionId.errcheck = RaiseIfZero
return _WTSGetActiveConsoleSessionId()
#==============================================================================
# This calculates the list of exported symbols.
_all = set(vars().keys()).difference(_all)
__all__ = [_x for _x in _all if not _x.startswith('_')]
__all__.sort()
#==============================================================================
| 11,164 | Python | 32.032544 | 98 | 0.622358 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/win32/kernel32.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Wrapper for kernel32.dll in ctypes.
"""
__revision__ = "$Id$"
import warnings
from winappdbg.win32.defines import *
from winappdbg.win32 import context_i386
from winappdbg.win32 import context_amd64
#==============================================================================
# This is used later on to calculate the list of exported symbols.
_all = None
_all = set(vars().keys())
_all.add('version')
#==============================================================================
from winappdbg.win32.version import *
#------------------------------------------------------------------------------
# This can't be defined in defines.py because it calls GetLastError().
def RaiseIfLastError(result, func = None, arguments = ()):
"""
Error checking for Win32 API calls with no error-specific return value.
Regardless of the return value, the function calls GetLastError(). If the
code is not C{ERROR_SUCCESS} then a C{WindowsError} exception is raised.
For this to work, the user MUST call SetLastError(ERROR_SUCCESS) prior to
calling the API. Otherwise an exception may be raised even on success,
since most API calls don't clear the error status code.
"""
code = GetLastError()
if code != ERROR_SUCCESS:
raise ctypes.WinError(code)
return result
#--- CONTEXT structure and constants ------------------------------------------
ContextArchMask = 0x0FFF0000 # just guessing here! seems to work, though
if arch == ARCH_I386:
from winappdbg.win32.context_i386 import *
elif arch == ARCH_AMD64:
if bits == 64:
from winappdbg.win32.context_amd64 import *
else:
from winappdbg.win32.context_i386 import *
else:
warnings.warn("Unknown or unsupported architecture: %s" % arch)
#--- Constants ----------------------------------------------------------------
STILL_ACTIVE = 259
WAIT_TIMEOUT = 0x102
WAIT_FAILED = -1
WAIT_OBJECT_0 = 0
EXCEPTION_NONCONTINUABLE = 0x1 # Noncontinuable exception
EXCEPTION_MAXIMUM_PARAMETERS = 15 # maximum number of exception parameters
MAXIMUM_WAIT_OBJECTS = 64 # Maximum number of wait objects
MAXIMUM_SUSPEND_COUNT = 0x7f # Maximum times thread can be suspended
FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100
FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000
GR_GDIOBJECTS = 0
GR_USEROBJECTS = 1
PROCESS_NAME_NATIVE = 1
MAXINTATOM = 0xC000
STD_INPUT_HANDLE = 0xFFFFFFF6 # (DWORD)-10
STD_OUTPUT_HANDLE = 0xFFFFFFF5 # (DWORD)-11
STD_ERROR_HANDLE = 0xFFFFFFF4 # (DWORD)-12
ATTACH_PARENT_PROCESS = 0xFFFFFFFF # (DWORD)-1
# LoadLibraryEx constants
DONT_RESOLVE_DLL_REFERENCES = 0x00000001
LOAD_LIBRARY_AS_DATAFILE = 0x00000002
LOAD_WITH_ALTERED_SEARCH_PATH = 0x00000008
LOAD_IGNORE_CODE_AUTHZ_LEVEL = 0x00000010
LOAD_LIBRARY_AS_IMAGE_RESOURCE = 0x00000020
LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE = 0x00000040
# SetSearchPathMode flags
# TODO I couldn't find these constants :(
##BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE = ???
##BASE_SEARCH_PATH_DISABLE_SAFE_SEARCHMODE = ???
##BASE_SEARCH_PATH_PERMANENT = ???
# Console control events
CTRL_C_EVENT = 0
CTRL_BREAK_EVENT = 1
CTRL_CLOSE_EVENT = 2
CTRL_LOGOFF_EVENT = 5
CTRL_SHUTDOWN_EVENT = 6
# Heap flags
HEAP_NO_SERIALIZE = 0x00000001
HEAP_GENERATE_EXCEPTIONS = 0x00000004
HEAP_ZERO_MEMORY = 0x00000008
HEAP_CREATE_ENABLE_EXECUTE = 0x00040000
# Standard access rights
DELETE = long(0x00010000)
READ_CONTROL = long(0x00020000)
WRITE_DAC = long(0x00040000)
WRITE_OWNER = long(0x00080000)
SYNCHRONIZE = long(0x00100000)
STANDARD_RIGHTS_REQUIRED = long(0x000F0000)
STANDARD_RIGHTS_READ = (READ_CONTROL)
STANDARD_RIGHTS_WRITE = (READ_CONTROL)
STANDARD_RIGHTS_EXECUTE = (READ_CONTROL)
STANDARD_RIGHTS_ALL = long(0x001F0000)
SPECIFIC_RIGHTS_ALL = long(0x0000FFFF)
# Mutex access rights
MUTEX_ALL_ACCESS = 0x1F0001
MUTEX_MODIFY_STATE = 1
# Event access rights
EVENT_ALL_ACCESS = 0x1F0003
EVENT_MODIFY_STATE = 2
# Semaphore access rights
SEMAPHORE_ALL_ACCESS = 0x1F0003
SEMAPHORE_MODIFY_STATE = 2
# Timer access rights
TIMER_ALL_ACCESS = 0x1F0003
TIMER_MODIFY_STATE = 2
TIMER_QUERY_STATE = 1
# Process access rights for OpenProcess
PROCESS_TERMINATE = 0x0001
PROCESS_CREATE_THREAD = 0x0002
PROCESS_SET_SESSIONID = 0x0004
PROCESS_VM_OPERATION = 0x0008
PROCESS_VM_READ = 0x0010
PROCESS_VM_WRITE = 0x0020
PROCESS_DUP_HANDLE = 0x0040
PROCESS_CREATE_PROCESS = 0x0080
PROCESS_SET_QUOTA = 0x0100
PROCESS_SET_INFORMATION = 0x0200
PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_SUSPEND_RESUME = 0x0800
PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
# Thread access rights for OpenThread
THREAD_TERMINATE = 0x0001
THREAD_SUSPEND_RESUME = 0x0002
THREAD_ALERT = 0x0004
THREAD_GET_CONTEXT = 0x0008
THREAD_SET_CONTEXT = 0x0010
THREAD_SET_INFORMATION = 0x0020
THREAD_QUERY_INFORMATION = 0x0040
THREAD_SET_THREAD_TOKEN = 0x0080
THREAD_IMPERSONATE = 0x0100
THREAD_DIRECT_IMPERSONATION = 0x0200
THREAD_SET_LIMITED_INFORMATION = 0x0400
THREAD_QUERY_LIMITED_INFORMATION = 0x0800
# The values of PROCESS_ALL_ACCESS and THREAD_ALL_ACCESS were changed in Vista/2008
PROCESS_ALL_ACCESS_NT = (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0xFFF)
PROCESS_ALL_ACCESS_VISTA = (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0xFFFF)
THREAD_ALL_ACCESS_NT = (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x3FF)
THREAD_ALL_ACCESS_VISTA = (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0xFFFF)
if NTDDI_VERSION < NTDDI_VISTA:
PROCESS_ALL_ACCESS = PROCESS_ALL_ACCESS_NT
THREAD_ALL_ACCESS = THREAD_ALL_ACCESS_NT
else:
PROCESS_ALL_ACCESS = PROCESS_ALL_ACCESS_VISTA
THREAD_ALL_ACCESS = THREAD_ALL_ACCESS_VISTA
# Process priority classes
IDLE_PRIORITY_CLASS = 0x00000040
BELOW_NORMAL_PRIORITY_CLASS = 0x00004000
NORMAL_PRIORITY_CLASS = 0x00000020
ABOVE_NORMAL_PRIORITY_CLASS = 0x00008000
HIGH_PRIORITY_CLASS = 0x00000080
REALTIME_PRIORITY_CLASS = 0x00000100
PROCESS_MODE_BACKGROUND_BEGIN = 0x00100000
PROCESS_MODE_BACKGROUND_END = 0x00200000
# dwCreationFlag values
DEBUG_PROCESS = 0x00000001
DEBUG_ONLY_THIS_PROCESS = 0x00000002
CREATE_SUSPENDED = 0x00000004 # Threads and processes
DETACHED_PROCESS = 0x00000008
CREATE_NEW_CONSOLE = 0x00000010
NORMAL_PRIORITY_CLASS = 0x00000020
IDLE_PRIORITY_CLASS = 0x00000040
HIGH_PRIORITY_CLASS = 0x00000080
REALTIME_PRIORITY_CLASS = 0x00000100
CREATE_NEW_PROCESS_GROUP = 0x00000200
CREATE_UNICODE_ENVIRONMENT = 0x00000400
CREATE_SEPARATE_WOW_VDM = 0x00000800
CREATE_SHARED_WOW_VDM = 0x00001000
CREATE_FORCEDOS = 0x00002000
BELOW_NORMAL_PRIORITY_CLASS = 0x00004000
ABOVE_NORMAL_PRIORITY_CLASS = 0x00008000
INHERIT_PARENT_AFFINITY = 0x00010000
STACK_SIZE_PARAM_IS_A_RESERVATION = 0x00010000 # Threads only
INHERIT_CALLER_PRIORITY = 0x00020000 # Deprecated
CREATE_PROTECTED_PROCESS = 0x00040000
EXTENDED_STARTUPINFO_PRESENT = 0x00080000
PROCESS_MODE_BACKGROUND_BEGIN = 0x00100000
PROCESS_MODE_BACKGROUND_END = 0x00200000
CREATE_BREAKAWAY_FROM_JOB = 0x01000000
CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000
CREATE_DEFAULT_ERROR_MODE = 0x04000000
CREATE_NO_WINDOW = 0x08000000
PROFILE_USER = 0x10000000
PROFILE_KERNEL = 0x20000000
PROFILE_SERVER = 0x40000000
CREATE_IGNORE_SYSTEM_DEFAULT = 0x80000000
# Thread priority values
THREAD_BASE_PRIORITY_LOWRT = 15 # value that gets a thread to LowRealtime-1
THREAD_BASE_PRIORITY_MAX = 2 # maximum thread base priority boost
THREAD_BASE_PRIORITY_MIN = (-2) # minimum thread base priority boost
THREAD_BASE_PRIORITY_IDLE = (-15) # value that gets a thread to idle
THREAD_PRIORITY_LOWEST = THREAD_BASE_PRIORITY_MIN
THREAD_PRIORITY_BELOW_NORMAL = (THREAD_PRIORITY_LOWEST+1)
THREAD_PRIORITY_NORMAL = 0
THREAD_PRIORITY_HIGHEST = THREAD_BASE_PRIORITY_MAX
THREAD_PRIORITY_ABOVE_NORMAL = (THREAD_PRIORITY_HIGHEST-1)
THREAD_PRIORITY_ERROR_RETURN = long(0xFFFFFFFF)
THREAD_PRIORITY_TIME_CRITICAL = THREAD_BASE_PRIORITY_LOWRT
THREAD_PRIORITY_IDLE = THREAD_BASE_PRIORITY_IDLE
# Memory access
SECTION_QUERY = 0x0001
SECTION_MAP_WRITE = 0x0002
SECTION_MAP_READ = 0x0004
SECTION_MAP_EXECUTE = 0x0008
SECTION_EXTEND_SIZE = 0x0010
SECTION_MAP_EXECUTE_EXPLICIT = 0x0020 # not included in SECTION_ALL_ACCESS
SECTION_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED|SECTION_QUERY|\
SECTION_MAP_WRITE | \
SECTION_MAP_READ | \
SECTION_MAP_EXECUTE | \
SECTION_EXTEND_SIZE)
PAGE_NOACCESS = 0x01
PAGE_READONLY = 0x02
PAGE_READWRITE = 0x04
PAGE_WRITECOPY = 0x08
PAGE_EXECUTE = 0x10
PAGE_EXECUTE_READ = 0x20
PAGE_EXECUTE_READWRITE = 0x40
PAGE_EXECUTE_WRITECOPY = 0x80
PAGE_GUARD = 0x100
PAGE_NOCACHE = 0x200
PAGE_WRITECOMBINE = 0x400
MEM_COMMIT = 0x1000
MEM_RESERVE = 0x2000
MEM_DECOMMIT = 0x4000
MEM_RELEASE = 0x8000
MEM_FREE = 0x10000
MEM_PRIVATE = 0x20000
MEM_MAPPED = 0x40000
MEM_RESET = 0x80000
MEM_TOP_DOWN = 0x100000
MEM_WRITE_WATCH = 0x200000
MEM_PHYSICAL = 0x400000
MEM_LARGE_PAGES = 0x20000000
MEM_4MB_PAGES = 0x80000000
SEC_FILE = 0x800000
SEC_IMAGE = 0x1000000
SEC_RESERVE = 0x4000000
SEC_COMMIT = 0x8000000
SEC_NOCACHE = 0x10000000
SEC_LARGE_PAGES = 0x80000000
MEM_IMAGE = SEC_IMAGE
WRITE_WATCH_FLAG_RESET = 0x01
FILE_MAP_ALL_ACCESS = 0xF001F
SECTION_QUERY = 0x0001
SECTION_MAP_WRITE = 0x0002
SECTION_MAP_READ = 0x0004
SECTION_MAP_EXECUTE = 0x0008
SECTION_EXTEND_SIZE = 0x0010
SECTION_MAP_EXECUTE_EXPLICIT = 0x0020 # not included in SECTION_ALL_ACCESS
SECTION_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED|SECTION_QUERY|\
SECTION_MAP_WRITE | \
SECTION_MAP_READ | \
SECTION_MAP_EXECUTE | \
SECTION_EXTEND_SIZE)
FILE_MAP_COPY = SECTION_QUERY
FILE_MAP_WRITE = SECTION_MAP_WRITE
FILE_MAP_READ = SECTION_MAP_READ
FILE_MAP_ALL_ACCESS = SECTION_ALL_ACCESS
FILE_MAP_EXECUTE = SECTION_MAP_EXECUTE_EXPLICIT # not included in FILE_MAP_ALL_ACCESS
GENERIC_READ = 0x80000000
GENERIC_WRITE = 0x40000000
GENERIC_EXECUTE = 0x20000000
GENERIC_ALL = 0x10000000
FILE_SHARE_READ = 0x00000001
FILE_SHARE_WRITE = 0x00000002
FILE_SHARE_DELETE = 0x00000004
CREATE_NEW = 1
CREATE_ALWAYS = 2
OPEN_EXISTING = 3
OPEN_ALWAYS = 4
TRUNCATE_EXISTING = 5
FILE_ATTRIBUTE_READONLY = 0x00000001
FILE_ATTRIBUTE_NORMAL = 0x00000080
FILE_ATTRIBUTE_TEMPORARY = 0x00000100
FILE_FLAG_WRITE_THROUGH = 0x80000000
FILE_FLAG_NO_BUFFERING = 0x20000000
FILE_FLAG_RANDOM_ACCESS = 0x10000000
FILE_FLAG_SEQUENTIAL_SCAN = 0x08000000
FILE_FLAG_DELETE_ON_CLOSE = 0x04000000
FILE_FLAG_OVERLAPPED = 0x40000000
FILE_ATTRIBUTE_READONLY = 0x00000001
FILE_ATTRIBUTE_HIDDEN = 0x00000002
FILE_ATTRIBUTE_SYSTEM = 0x00000004
FILE_ATTRIBUTE_DIRECTORY = 0x00000010
FILE_ATTRIBUTE_ARCHIVE = 0x00000020
FILE_ATTRIBUTE_DEVICE = 0x00000040
FILE_ATTRIBUTE_NORMAL = 0x00000080
FILE_ATTRIBUTE_TEMPORARY = 0x00000100
# Debug events
EXCEPTION_DEBUG_EVENT = 1
CREATE_THREAD_DEBUG_EVENT = 2
CREATE_PROCESS_DEBUG_EVENT = 3
EXIT_THREAD_DEBUG_EVENT = 4
EXIT_PROCESS_DEBUG_EVENT = 5
LOAD_DLL_DEBUG_EVENT = 6
UNLOAD_DLL_DEBUG_EVENT = 7
OUTPUT_DEBUG_STRING_EVENT = 8
RIP_EVENT = 9
# Debug status codes (ContinueDebugEvent)
DBG_EXCEPTION_HANDLED = long(0x00010001)
DBG_CONTINUE = long(0x00010002)
DBG_REPLY_LATER = long(0x40010001)
DBG_UNABLE_TO_PROVIDE_HANDLE = long(0x40010002)
DBG_TERMINATE_THREAD = long(0x40010003)
DBG_TERMINATE_PROCESS = long(0x40010004)
DBG_CONTROL_C = long(0x40010005)
DBG_PRINTEXCEPTION_C = long(0x40010006)
DBG_RIPEXCEPTION = long(0x40010007)
DBG_CONTROL_BREAK = long(0x40010008)
DBG_COMMAND_EXCEPTION = long(0x40010009)
DBG_EXCEPTION_NOT_HANDLED = long(0x80010001)
DBG_NO_STATE_CHANGE = long(0xC0010001)
DBG_APP_NOT_IDLE = long(0xC0010002)
# Status codes
STATUS_WAIT_0 = long(0x00000000)
STATUS_ABANDONED_WAIT_0 = long(0x00000080)
STATUS_USER_APC = long(0x000000C0)
STATUS_TIMEOUT = long(0x00000102)
STATUS_PENDING = long(0x00000103)
STATUS_SEGMENT_NOTIFICATION = long(0x40000005)
STATUS_GUARD_PAGE_VIOLATION = long(0x80000001)
STATUS_DATATYPE_MISALIGNMENT = long(0x80000002)
STATUS_BREAKPOINT = long(0x80000003)
STATUS_SINGLE_STEP = long(0x80000004)
STATUS_INVALID_INFO_CLASS = long(0xC0000003)
STATUS_ACCESS_VIOLATION = long(0xC0000005)
STATUS_IN_PAGE_ERROR = long(0xC0000006)
STATUS_INVALID_HANDLE = long(0xC0000008)
STATUS_NO_MEMORY = long(0xC0000017)
STATUS_ILLEGAL_INSTRUCTION = long(0xC000001D)
STATUS_NONCONTINUABLE_EXCEPTION = long(0xC0000025)
STATUS_INVALID_DISPOSITION = long(0xC0000026)
STATUS_ARRAY_BOUNDS_EXCEEDED = long(0xC000008C)
STATUS_FLOAT_DENORMAL_OPERAND = long(0xC000008D)
STATUS_FLOAT_DIVIDE_BY_ZERO = long(0xC000008E)
STATUS_FLOAT_INEXACT_RESULT = long(0xC000008F)
STATUS_FLOAT_INVALID_OPERATION = long(0xC0000090)
STATUS_FLOAT_OVERFLOW = long(0xC0000091)
STATUS_FLOAT_STACK_CHECK = long(0xC0000092)
STATUS_FLOAT_UNDERFLOW = long(0xC0000093)
STATUS_INTEGER_DIVIDE_BY_ZERO = long(0xC0000094)
STATUS_INTEGER_OVERFLOW = long(0xC0000095)
STATUS_PRIVILEGED_INSTRUCTION = long(0xC0000096)
STATUS_STACK_OVERFLOW = long(0xC00000FD)
STATUS_CONTROL_C_EXIT = long(0xC000013A)
STATUS_FLOAT_MULTIPLE_FAULTS = long(0xC00002B4)
STATUS_FLOAT_MULTIPLE_TRAPS = long(0xC00002B5)
STATUS_REG_NAT_CONSUMPTION = long(0xC00002C9)
STATUS_SXS_EARLY_DEACTIVATION = long(0xC015000F)
STATUS_SXS_INVALID_DEACTIVATION = long(0xC0150010)
STATUS_STACK_BUFFER_OVERRUN = long(0xC0000409)
STATUS_WX86_BREAKPOINT = long(0x4000001F)
STATUS_HEAP_CORRUPTION = long(0xC0000374)
STATUS_POSSIBLE_DEADLOCK = long(0xC0000194)
STATUS_UNWIND_CONSOLIDATE = long(0x80000029)
# Exception codes
EXCEPTION_ACCESS_VIOLATION = STATUS_ACCESS_VIOLATION
EXCEPTION_ARRAY_BOUNDS_EXCEEDED = STATUS_ARRAY_BOUNDS_EXCEEDED
EXCEPTION_BREAKPOINT = STATUS_BREAKPOINT
EXCEPTION_DATATYPE_MISALIGNMENT = STATUS_DATATYPE_MISALIGNMENT
EXCEPTION_FLT_DENORMAL_OPERAND = STATUS_FLOAT_DENORMAL_OPERAND
EXCEPTION_FLT_DIVIDE_BY_ZERO = STATUS_FLOAT_DIVIDE_BY_ZERO
EXCEPTION_FLT_INEXACT_RESULT = STATUS_FLOAT_INEXACT_RESULT
EXCEPTION_FLT_INVALID_OPERATION = STATUS_FLOAT_INVALID_OPERATION
EXCEPTION_FLT_OVERFLOW = STATUS_FLOAT_OVERFLOW
EXCEPTION_FLT_STACK_CHECK = STATUS_FLOAT_STACK_CHECK
EXCEPTION_FLT_UNDERFLOW = STATUS_FLOAT_UNDERFLOW
EXCEPTION_ILLEGAL_INSTRUCTION = STATUS_ILLEGAL_INSTRUCTION
EXCEPTION_IN_PAGE_ERROR = STATUS_IN_PAGE_ERROR
EXCEPTION_INT_DIVIDE_BY_ZERO = STATUS_INTEGER_DIVIDE_BY_ZERO
EXCEPTION_INT_OVERFLOW = STATUS_INTEGER_OVERFLOW
EXCEPTION_INVALID_DISPOSITION = STATUS_INVALID_DISPOSITION
EXCEPTION_NONCONTINUABLE_EXCEPTION = STATUS_NONCONTINUABLE_EXCEPTION
EXCEPTION_PRIV_INSTRUCTION = STATUS_PRIVILEGED_INSTRUCTION
EXCEPTION_SINGLE_STEP = STATUS_SINGLE_STEP
EXCEPTION_STACK_OVERFLOW = STATUS_STACK_OVERFLOW
EXCEPTION_GUARD_PAGE = STATUS_GUARD_PAGE_VIOLATION
EXCEPTION_INVALID_HANDLE = STATUS_INVALID_HANDLE
EXCEPTION_POSSIBLE_DEADLOCK = STATUS_POSSIBLE_DEADLOCK
EXCEPTION_WX86_BREAKPOINT = STATUS_WX86_BREAKPOINT
CONTROL_C_EXIT = STATUS_CONTROL_C_EXIT
DBG_CONTROL_C = long(0x40010005)
MS_VC_EXCEPTION = long(0x406D1388)
# Access violation types
ACCESS_VIOLATION_TYPE_READ = EXCEPTION_READ_FAULT
ACCESS_VIOLATION_TYPE_WRITE = EXCEPTION_WRITE_FAULT
ACCESS_VIOLATION_TYPE_DEP = EXCEPTION_EXECUTE_FAULT
# RIP event types
SLE_ERROR = 1
SLE_MINORERROR = 2
SLE_WARNING = 3
# DuplicateHandle constants
DUPLICATE_CLOSE_SOURCE = 0x00000001
DUPLICATE_SAME_ACCESS = 0x00000002
# GetFinalPathNameByHandle constants
FILE_NAME_NORMALIZED = 0x0
FILE_NAME_OPENED = 0x8
VOLUME_NAME_DOS = 0x0
VOLUME_NAME_GUID = 0x1
VOLUME_NAME_NONE = 0x4
VOLUME_NAME_NT = 0x2
# GetProductInfo constants
PRODUCT_BUSINESS = 0x00000006
PRODUCT_BUSINESS_N = 0x00000010
PRODUCT_CLUSTER_SERVER = 0x00000012
PRODUCT_DATACENTER_SERVER = 0x00000008
PRODUCT_DATACENTER_SERVER_CORE = 0x0000000C
PRODUCT_DATACENTER_SERVER_CORE_V = 0x00000027
PRODUCT_DATACENTER_SERVER_V = 0x00000025
PRODUCT_ENTERPRISE = 0x00000004
PRODUCT_ENTERPRISE_E = 0x00000046
PRODUCT_ENTERPRISE_N = 0x0000001B
PRODUCT_ENTERPRISE_SERVER = 0x0000000A
PRODUCT_ENTERPRISE_SERVER_CORE = 0x0000000E
PRODUCT_ENTERPRISE_SERVER_CORE_V = 0x00000029
PRODUCT_ENTERPRISE_SERVER_IA64 = 0x0000000F
PRODUCT_ENTERPRISE_SERVER_V = 0x00000026
PRODUCT_HOME_BASIC = 0x00000002
PRODUCT_HOME_BASIC_E = 0x00000043
PRODUCT_HOME_BASIC_N = 0x00000005
PRODUCT_HOME_PREMIUM = 0x00000003
PRODUCT_HOME_PREMIUM_E = 0x00000044
PRODUCT_HOME_PREMIUM_N = 0x0000001A
PRODUCT_HYPERV = 0x0000002A
PRODUCT_MEDIUMBUSINESS_SERVER_MANAGEMENT = 0x0000001E
PRODUCT_MEDIUMBUSINESS_SERVER_MESSAGING = 0x00000020
PRODUCT_MEDIUMBUSINESS_SERVER_SECURITY = 0x0000001F
PRODUCT_PROFESSIONAL = 0x00000030
PRODUCT_PROFESSIONAL_E = 0x00000045
PRODUCT_PROFESSIONAL_N = 0x00000031
PRODUCT_SERVER_FOR_SMALLBUSINESS = 0x00000018
PRODUCT_SERVER_FOR_SMALLBUSINESS_V = 0x00000023
PRODUCT_SERVER_FOUNDATION = 0x00000021
PRODUCT_SMALLBUSINESS_SERVER = 0x00000009
PRODUCT_STANDARD_SERVER = 0x00000007
PRODUCT_STANDARD_SERVER_CORE = 0x0000000D
PRODUCT_STANDARD_SERVER_CORE_V = 0x00000028
PRODUCT_STANDARD_SERVER_V = 0x00000024
PRODUCT_STARTER = 0x0000000B
PRODUCT_STARTER_E = 0x00000042
PRODUCT_STARTER_N = 0x0000002F
PRODUCT_STORAGE_ENTERPRISE_SERVER = 0x00000017
PRODUCT_STORAGE_EXPRESS_SERVER = 0x00000014
PRODUCT_STORAGE_STANDARD_SERVER = 0x00000015
PRODUCT_STORAGE_WORKGROUP_SERVER = 0x00000016
PRODUCT_UNDEFINED = 0x00000000
PRODUCT_UNLICENSED = 0xABCDABCD
PRODUCT_ULTIMATE = 0x00000001
PRODUCT_ULTIMATE_E = 0x00000047
PRODUCT_ULTIMATE_N = 0x0000001C
PRODUCT_WEB_SERVER = 0x00000011
PRODUCT_WEB_SERVER_CORE = 0x0000001D
# DEP policy flags
PROCESS_DEP_ENABLE = 1
PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION = 2
# Error modes
SEM_FAILCRITICALERRORS = 0x001
SEM_NOGPFAULTERRORBOX = 0x002
SEM_NOALIGNMENTFAULTEXCEPT = 0x004
SEM_NOOPENFILEERRORBOX = 0x800
# GetHandleInformation / SetHandleInformation
HANDLE_FLAG_INHERIT = 0x00000001
HANDLE_FLAG_PROTECT_FROM_CLOSE = 0x00000002
#--- Handle wrappers ----------------------------------------------------------
class Handle (object):
"""
Encapsulates Win32 handles to avoid leaking them.
@type inherit: bool
@ivar inherit: C{True} if the handle is to be inherited by child processes,
C{False} otherwise.
@type protectFromClose: bool
@ivar protectFromClose: Set to C{True} to prevent the handle from being
closed. Must be set to C{False} before you're done using the handle,
or it will be left open until the debugger exits. Use with care!
@see:
L{ProcessHandle}, L{ThreadHandle}, L{FileHandle}, L{SnapshotHandle}
"""
# XXX DEBUG
# When this private flag is True each Handle will print a message to
# standard output when it's created and destroyed. This is useful for
# detecting handle leaks within WinAppDbg itself.
__bLeakDetection = False
def __init__(self, aHandle = None, bOwnership = True):
"""
@type aHandle: int
@param aHandle: Win32 handle value.
@type bOwnership: bool
@param bOwnership:
C{True} if we own the handle and we need to close it.
C{False} if someone else will be calling L{CloseHandle}.
"""
super(Handle, self).__init__()
self._value = self._normalize(aHandle)
self.bOwnership = bOwnership
if Handle.__bLeakDetection: # XXX DEBUG
print("INIT HANDLE (%r) %r" % (self.value, self))
@property
def value(self):
return self._value
def __del__(self):
"""
Closes the Win32 handle when the Python object is destroyed.
"""
try:
if Handle.__bLeakDetection: # XXX DEBUG
print("DEL HANDLE %r" % self)
self.close()
except Exception:
pass
def __enter__(self):
"""
Compatibility with the "C{with}" Python statement.
"""
if Handle.__bLeakDetection: # XXX DEBUG
print("ENTER HANDLE %r" % self)
return self
def __exit__(self, type, value, traceback):
"""
Compatibility with the "C{with}" Python statement.
"""
if Handle.__bLeakDetection: # XXX DEBUG
print("EXIT HANDLE %r" % self)
try:
self.close()
except Exception:
pass
def __copy__(self):
"""
Duplicates the Win32 handle when copying the Python object.
@rtype: L{Handle}
@return: A new handle to the same Win32 object.
"""
return self.dup()
def __deepcopy__(self):
"""
Duplicates the Win32 handle when copying the Python object.
@rtype: L{Handle}
@return: A new handle to the same win32 object.
"""
return self.dup()
@property
def _as_parameter_(self):
"""
Compatibility with ctypes.
Allows passing transparently a Handle object to an API call.
"""
return HANDLE(self.value)
@staticmethod
def from_param(value):
"""
Compatibility with ctypes.
Allows passing transparently a Handle object to an API call.
@type value: int
@param value: Numeric handle value.
"""
return HANDLE(value)
def close(self):
"""
Closes the Win32 handle.
"""
if self.bOwnership and self.value not in (None, INVALID_HANDLE_VALUE):
if Handle.__bLeakDetection: # XXX DEBUG
print("CLOSE HANDLE (%d) %r" % (self.value, self))
try:
self._close()
finally:
self._value = None
def _close(self):
"""
Low-level close method.
This is a private method, do not call it.
"""
CloseHandle(self.value)
def dup(self):
"""
@rtype: L{Handle}
@return: A new handle to the same Win32 object.
"""
if self.value is None:
raise ValueError("Closed handles can't be duplicated!")
new_handle = DuplicateHandle(self.value)
if Handle.__bLeakDetection: # XXX DEBUG
print("DUP HANDLE (%d -> %d) %r %r" % \
(self.value, new_handle.value, self, new_handle))
return new_handle
@staticmethod
def _normalize(value):
"""
Normalize handle values.
"""
if hasattr(value, 'value'):
value = value.value
if value is not None:
value = long(value)
return value
def wait(self, dwMilliseconds = None):
"""
Wait for the Win32 object to be signaled.
@type dwMilliseconds: int
@param dwMilliseconds: (Optional) Timeout value in milliseconds.
Use C{INFINITE} or C{None} for no timeout.
"""
if self.value is None:
raise ValueError("Handle is already closed!")
if dwMilliseconds is None:
dwMilliseconds = INFINITE
r = WaitForSingleObject(self.value, dwMilliseconds)
if r != WAIT_OBJECT_0:
raise ctypes.WinError(r)
def __repr__(self):
return '<%s: %s>' % (self.__class__.__name__, self.value)
def __get_inherit(self):
if self.value is None:
raise ValueError("Handle is already closed!")
return bool( GetHandleInformation(self.value) & HANDLE_FLAG_INHERIT )
def __set_inherit(self, value):
if self.value is None:
raise ValueError("Handle is already closed!")
flag = (0, HANDLE_FLAG_INHERIT)[ bool(value) ]
SetHandleInformation(self.value, flag, flag)
inherit = property(__get_inherit, __set_inherit)
def __get_protectFromClose(self):
if self.value is None:
raise ValueError("Handle is already closed!")
return bool( GetHandleInformation(self.value) & HANDLE_FLAG_PROTECT_FROM_CLOSE )
def __set_protectFromClose(self, value):
if self.value is None:
raise ValueError("Handle is already closed!")
flag = (0, HANDLE_FLAG_PROTECT_FROM_CLOSE)[ bool(value) ]
SetHandleInformation(self.value, flag, flag)
protectFromClose = property(__get_protectFromClose, __set_protectFromClose)
class UserModeHandle (Handle):
"""
Base class for non-kernel handles. Generally this means they are closed
by special Win32 API functions instead of CloseHandle() and some standard
operations (synchronizing, duplicating, inheritance) are not supported.
@type _TYPE: C type
@cvar _TYPE: C type to translate this handle to.
Subclasses should override this.
Defaults to L{HANDLE}.
"""
# Subclasses should override this.
_TYPE = HANDLE
# This method must be implemented by subclasses.
def _close(self):
raise NotImplementedError()
# Translation to C type.
@property
def _as_parameter_(self):
return self._TYPE(self.value)
# Translation to C type.
@staticmethod
def from_param(value):
return self._TYPE(self.value)
# Operation not supported.
@property
def inherit(self):
return False
# Operation not supported.
@property
def protectFromClose(self):
return False
# Operation not supported.
def dup(self):
raise NotImplementedError()
# Operation not supported.
def wait(self, dwMilliseconds = None):
raise NotImplementedError()
class ProcessHandle (Handle):
"""
Win32 process handle.
@type dwAccess: int
@ivar dwAccess: Current access flags to this handle.
This is the same value passed to L{OpenProcess}.
Can only be C{None} if C{aHandle} is also C{None}.
Defaults to L{PROCESS_ALL_ACCESS}.
@see: L{Handle}
"""
def __init__(self, aHandle = None, bOwnership = True,
dwAccess = PROCESS_ALL_ACCESS):
"""
@type aHandle: int
@param aHandle: Win32 handle value.
@type bOwnership: bool
@param bOwnership:
C{True} if we own the handle and we need to close it.
C{False} if someone else will be calling L{CloseHandle}.
@type dwAccess: int
@param dwAccess: Current access flags to this handle.
This is the same value passed to L{OpenProcess}.
Can only be C{None} if C{aHandle} is also C{None}.
Defaults to L{PROCESS_ALL_ACCESS}.
"""
super(ProcessHandle, self).__init__(aHandle, bOwnership)
self.dwAccess = dwAccess
if aHandle is not None and dwAccess is None:
msg = "Missing access flags for process handle: %x" % aHandle
raise TypeError(msg)
def get_pid(self):
"""
@rtype: int
@return: Process global ID.
"""
return GetProcessId(self.value)
class ThreadHandle (Handle):
"""
Win32 thread handle.
@type dwAccess: int
@ivar dwAccess: Current access flags to this handle.
This is the same value passed to L{OpenThread}.
Can only be C{None} if C{aHandle} is also C{None}.
Defaults to L{THREAD_ALL_ACCESS}.
@see: L{Handle}
"""
def __init__(self, aHandle = None, bOwnership = True,
dwAccess = THREAD_ALL_ACCESS):
"""
@type aHandle: int
@param aHandle: Win32 handle value.
@type bOwnership: bool
@param bOwnership:
C{True} if we own the handle and we need to close it.
C{False} if someone else will be calling L{CloseHandle}.
@type dwAccess: int
@param dwAccess: Current access flags to this handle.
This is the same value passed to L{OpenThread}.
Can only be C{None} if C{aHandle} is also C{None}.
Defaults to L{THREAD_ALL_ACCESS}.
"""
super(ThreadHandle, self).__init__(aHandle, bOwnership)
self.dwAccess = dwAccess
if aHandle is not None and dwAccess is None:
msg = "Missing access flags for thread handle: %x" % aHandle
raise TypeError(msg)
def get_tid(self):
"""
@rtype: int
@return: Thread global ID.
"""
return GetThreadId(self.value)
class FileHandle (Handle):
"""
Win32 file handle.
@see: L{Handle}
"""
def get_filename(self):
"""
@rtype: None or str
@return: Name of the open file, or C{None} if unavailable.
"""
#
# XXX BUG
#
# This code truncates the first two bytes of the path.
# It seems to be the expected behavior of NtQueryInformationFile.
#
# My guess is it only returns the NT pathname, without the device name.
# It's like dropping the drive letter in a Win32 pathname.
#
# Note that using the "official" GetFileInformationByHandleEx
# API introduced in Vista doesn't change the results!
#
dwBufferSize = 0x1004
lpFileInformation = ctypes.create_string_buffer(dwBufferSize)
try:
GetFileInformationByHandleEx(self.value,
FILE_INFO_BY_HANDLE_CLASS.FileNameInfo,
lpFileInformation, dwBufferSize)
except AttributeError:
from winappdbg.win32.ntdll import NtQueryInformationFile, \
FileNameInformation, \
FILE_NAME_INFORMATION
NtQueryInformationFile(self.value,
FileNameInformation,
lpFileInformation,
dwBufferSize)
FileName = compat.unicode(lpFileInformation.raw[sizeof(DWORD):], 'U16')
FileName = ctypes.create_unicode_buffer(FileName).value
if not FileName:
FileName = None
elif FileName[1:2] != ':':
# When the drive letter is missing, we'll assume SYSTEMROOT.
# Not a good solution but it could be worse.
import os
FileName = os.environ['SYSTEMROOT'][:2] + FileName
return FileName
class FileMappingHandle (Handle):
"""
File mapping handle.
@see: L{Handle}
"""
pass
# XXX maybe add functions related to the toolhelp snapshots here?
class SnapshotHandle (Handle):
"""
Toolhelp32 snapshot handle.
@see: L{Handle}
"""
pass
#--- Structure wrappers -------------------------------------------------------
class ProcessInformation (object):
"""
Process information object returned by L{CreateProcess}.
"""
def __init__(self, pi):
self.hProcess = ProcessHandle(pi.hProcess)
self.hThread = ThreadHandle(pi.hThread)
self.dwProcessId = pi.dwProcessId
self.dwThreadId = pi.dwThreadId
# Don't psyco-optimize this class because it needs to be serialized.
class MemoryBasicInformation (object):
"""
Memory information object returned by L{VirtualQueryEx}.
"""
READABLE = (
PAGE_EXECUTE_READ |
PAGE_EXECUTE_READWRITE |
PAGE_EXECUTE_WRITECOPY |
PAGE_READONLY |
PAGE_READWRITE |
PAGE_WRITECOPY
)
WRITEABLE = (
PAGE_EXECUTE_READWRITE |
PAGE_EXECUTE_WRITECOPY |
PAGE_READWRITE |
PAGE_WRITECOPY
)
COPY_ON_WRITE = (
PAGE_EXECUTE_WRITECOPY |
PAGE_WRITECOPY
)
EXECUTABLE = (
PAGE_EXECUTE |
PAGE_EXECUTE_READ |
PAGE_EXECUTE_READWRITE |
PAGE_EXECUTE_WRITECOPY
)
EXECUTABLE_AND_WRITEABLE = (
PAGE_EXECUTE_READWRITE |
PAGE_EXECUTE_WRITECOPY
)
def __init__(self, mbi=None):
"""
@type mbi: L{MEMORY_BASIC_INFORMATION} or L{MemoryBasicInformation}
@param mbi: Either a L{MEMORY_BASIC_INFORMATION} structure or another
L{MemoryBasicInformation} instance.
"""
if mbi is None:
self.BaseAddress = None
self.AllocationBase = None
self.AllocationProtect = None
self.RegionSize = None
self.State = None
self.Protect = None
self.Type = None
else:
self.BaseAddress = mbi.BaseAddress
self.AllocationBase = mbi.AllocationBase
self.AllocationProtect = mbi.AllocationProtect
self.RegionSize = mbi.RegionSize
self.State = mbi.State
self.Protect = mbi.Protect
self.Type = mbi.Type
# Only used when copying MemoryBasicInformation objects, instead of
# instancing them from a MEMORY_BASIC_INFORMATION structure.
if hasattr(mbi, 'content'):
self.content = mbi.content
if hasattr(mbi, 'filename'):
self.content = mbi.filename
def __contains__(self, address):
"""
Test if the given memory address falls within this memory region.
@type address: int
@param address: Memory address to test.
@rtype: bool
@return: C{True} if the given memory address falls within this memory
region, C{False} otherwise.
"""
return self.BaseAddress <= address < (self.BaseAddress + self.RegionSize)
def is_free(self):
"""
@rtype: bool
@return: C{True} if the memory in this region is free.
"""
return self.State == MEM_FREE
def is_reserved(self):
"""
@rtype: bool
@return: C{True} if the memory in this region is reserved.
"""
return self.State == MEM_RESERVE
def is_commited(self):
"""
@rtype: bool
@return: C{True} if the memory in this region is commited.
"""
return self.State == MEM_COMMIT
def is_image(self):
"""
@rtype: bool
@return: C{True} if the memory in this region belongs to an executable
image.
"""
return self.Type == MEM_IMAGE
def is_mapped(self):
"""
@rtype: bool
@return: C{True} if the memory in this region belongs to a mapped file.
"""
return self.Type == MEM_MAPPED
def is_private(self):
"""
@rtype: bool
@return: C{True} if the memory in this region is private.
"""
return self.Type == MEM_PRIVATE
def is_guard(self):
"""
@rtype: bool
@return: C{True} if all pages in this region are guard pages.
"""
return self.is_commited() and bool(self.Protect & PAGE_GUARD)
def has_content(self):
"""
@rtype: bool
@return: C{True} if the memory in this region has any data in it.
"""
return self.is_commited() and not bool(self.Protect & (PAGE_GUARD | PAGE_NOACCESS))
def is_readable(self):
"""
@rtype: bool
@return: C{True} if all pages in this region are readable.
"""
return self.has_content() and bool(self.Protect & self.READABLE)
def is_writeable(self):
"""
@rtype: bool
@return: C{True} if all pages in this region are writeable.
"""
return self.has_content() and bool(self.Protect & self.WRITEABLE)
def is_copy_on_write(self):
"""
@rtype: bool
@return: C{True} if all pages in this region are marked as
copy-on-write. This means the pages are writeable, but changes
are not propagated to disk.
@note:
Tipically data sections in executable images are marked like this.
"""
return self.has_content() and bool(self.Protect & self.COPY_ON_WRITE)
def is_executable(self):
"""
@rtype: bool
@return: C{True} if all pages in this region are executable.
@note: Executable pages are always readable.
"""
return self.has_content() and bool(self.Protect & self.EXECUTABLE)
def is_executable_and_writeable(self):
"""
@rtype: bool
@return: C{True} if all pages in this region are executable and
writeable.
@note: The presence of such pages make memory corruption
vulnerabilities much easier to exploit.
"""
return self.has_content() and bool(self.Protect & self.EXECUTABLE_AND_WRITEABLE)
class ProcThreadAttributeList (object):
"""
Extended process and thread attribute support.
To be used with L{STARTUPINFOEX}.
Only available for Windows Vista and above.
@type AttributeList: list of tuple( int, ctypes-compatible object )
@ivar AttributeList: List of (Attribute, Value) pairs.
@type AttributeListBuffer: L{LPPROC_THREAD_ATTRIBUTE_LIST}
@ivar AttributeListBuffer: Memory buffer used to store the attribute list.
L{InitializeProcThreadAttributeList},
L{UpdateProcThreadAttribute},
L{DeleteProcThreadAttributeList} and
L{STARTUPINFOEX}.
"""
def __init__(self, AttributeList):
"""
@type AttributeList: list of tuple( int, ctypes-compatible object )
@param AttributeList: List of (Attribute, Value) pairs.
"""
self.AttributeList = AttributeList
self.AttributeListBuffer = InitializeProcThreadAttributeList(
len(AttributeList))
try:
for Attribute, Value in AttributeList:
UpdateProcThreadAttribute(self.AttributeListBuffer,
Attribute, Value)
except:
ProcThreadAttributeList.__del__(self)
raise
def __del__(self):
try:
DeleteProcThreadAttributeList(self.AttributeListBuffer)
del self.AttributeListBuffer
except Exception:
pass
def __copy__(self):
return self.__deepcopy__()
def __deepcopy__(self):
return self.__class__(self.AttributeList)
@property
def value(self):
return ctypes.cast(ctypes.pointer(self.AttributeListBuffer), LPVOID)
@property
def _as_parameter_(self):
return self.value
# XXX TODO
@staticmethod
def from_param(value):
raise NotImplementedError()
#--- OVERLAPPED structure -----------------------------------------------------
# typedef struct _OVERLAPPED {
# ULONG_PTR Internal;
# ULONG_PTR InternalHigh;
# union {
# struct {
# DWORD Offset;
# DWORD OffsetHigh;
# } ;
# PVOID Pointer;
# } ;
# HANDLE hEvent;
# }OVERLAPPED, *LPOVERLAPPED;
class _OVERLAPPED_STRUCT(Structure):
_fields_ = [
('Offset', DWORD),
('OffsetHigh', DWORD),
]
class _OVERLAPPED_UNION(Union):
_fields_ = [
('s', _OVERLAPPED_STRUCT),
('Pointer', PVOID),
]
class OVERLAPPED(Structure):
_fields_ = [
('Internal', ULONG_PTR),
('InternalHigh', ULONG_PTR),
('u', _OVERLAPPED_UNION),
('hEvent', HANDLE),
]
LPOVERLAPPED = POINTER(OVERLAPPED)
#--- SECURITY_ATTRIBUTES structure --------------------------------------------
# typedef struct _SECURITY_ATTRIBUTES {
# DWORD nLength;
# LPVOID lpSecurityDescriptor;
# BOOL bInheritHandle;
# } SECURITY_ATTRIBUTES, *PSECURITY_ATTRIBUTES, *LPSECURITY_ATTRIBUTES;
class SECURITY_ATTRIBUTES(Structure):
_fields_ = [
('nLength', DWORD),
('lpSecurityDescriptor', LPVOID),
('bInheritHandle', BOOL),
]
LPSECURITY_ATTRIBUTES = POINTER(SECURITY_ATTRIBUTES)
# --- Extended process and thread attribute support ---------------------------
PPROC_THREAD_ATTRIBUTE_LIST = LPVOID
LPPROC_THREAD_ATTRIBUTE_LIST = PPROC_THREAD_ATTRIBUTE_LIST
PROC_THREAD_ATTRIBUTE_NUMBER = 0x0000FFFF
PROC_THREAD_ATTRIBUTE_THREAD = 0x00010000 # Attribute may be used with thread creation
PROC_THREAD_ATTRIBUTE_INPUT = 0x00020000 # Attribute is input only
PROC_THREAD_ATTRIBUTE_ADDITIVE = 0x00040000 # Attribute may be "accumulated," e.g. bitmasks, counters, etc.
# PROC_THREAD_ATTRIBUTE_NUM
ProcThreadAttributeParentProcess = 0
ProcThreadAttributeExtendedFlags = 1
ProcThreadAttributeHandleList = 2
ProcThreadAttributeGroupAffinity = 3
ProcThreadAttributePreferredNode = 4
ProcThreadAttributeIdealProcessor = 5
ProcThreadAttributeUmsThread = 6
ProcThreadAttributeMitigationPolicy = 7
ProcThreadAttributeMax = 8
PROC_THREAD_ATTRIBUTE_PARENT_PROCESS = ProcThreadAttributeParentProcess | PROC_THREAD_ATTRIBUTE_INPUT
PROC_THREAD_ATTRIBUTE_EXTENDED_FLAGS = ProcThreadAttributeExtendedFlags | PROC_THREAD_ATTRIBUTE_INPUT | PROC_THREAD_ATTRIBUTE_ADDITIVE
PROC_THREAD_ATTRIBUTE_HANDLE_LIST = ProcThreadAttributeHandleList | PROC_THREAD_ATTRIBUTE_INPUT
PROC_THREAD_ATTRIBUTE_GROUP_AFFINITY = ProcThreadAttributeGroupAffinity | PROC_THREAD_ATTRIBUTE_THREAD | PROC_THREAD_ATTRIBUTE_INPUT
PROC_THREAD_ATTRIBUTE_PREFERRED_NODE = ProcThreadAttributePreferredNode | PROC_THREAD_ATTRIBUTE_INPUT
PROC_THREAD_ATTRIBUTE_IDEAL_PROCESSOR = ProcThreadAttributeIdealProcessor | PROC_THREAD_ATTRIBUTE_THREAD | PROC_THREAD_ATTRIBUTE_INPUT
PROC_THREAD_ATTRIBUTE_UMS_THREAD = ProcThreadAttributeUmsThread | PROC_THREAD_ATTRIBUTE_THREAD | PROC_THREAD_ATTRIBUTE_INPUT
PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY = ProcThreadAttributeMitigationPolicy | PROC_THREAD_ATTRIBUTE_INPUT
PROCESS_CREATION_MITIGATION_POLICY_DEP_ENABLE = 0x01
PROCESS_CREATION_MITIGATION_POLICY_DEP_ATL_THUNK_ENABLE = 0x02
PROCESS_CREATION_MITIGATION_POLICY_SEHOP_ENABLE = 0x04
#--- VS_FIXEDFILEINFO structure -----------------------------------------------
# struct VS_FIXEDFILEINFO {
# DWORD dwSignature;
# DWORD dwStrucVersion;
# DWORD dwFileVersionMS;
# DWORD dwFileVersionLS;
# DWORD dwProductVersionMS;
# DWORD dwProductVersionLS;
# DWORD dwFileFlagsMask;
# DWORD dwFileFlags;
# DWORD dwFileOS;
# DWORD dwFileType;
# DWORD dwFileSubtype;
# DWORD dwFileDateMS;
# DWORD dwFileDateLS;
# };
class VS_FIXEDFILEINFO (Structure):
_fields_ = [
("dwSignature", DWORD), # 0xFEEF04BD
("dwStrucVersion", DWORD),
("dwFileVersionMS", DWORD),
("dwFileVersionLS", DWORD),
("dwProductVersionMS", DWORD),
("dwProductVersionLS", DWORD),
("dwFileFlagsMask", DWORD),
("dwFileFlags", DWORD),
("dwFileOS", DWORD),
("dwFileType", DWORD),
("dwFileSubtype", DWORD),
("dwFileDateMS", DWORD),
("dwFileDateLS", DWORD),
]
#--- THREADNAME_INFO structure ------------------------------------------------
# typedef struct tagTHREADNAME_INFO
# {
# DWORD dwType; // Must be 0x1000.
# LPCSTR szName; // Pointer to name (in user addr space).
# DWORD dwThreadID; // Thread ID (-1=caller thread).
# DWORD dwFlags; // Reserved for future use, must be zero.
# } THREADNAME_INFO;
class THREADNAME_INFO(Structure):
_fields_ = [
("dwType", DWORD), # 0x1000
("szName", LPVOID), # remote pointer
("dwThreadID", DWORD), # -1 usually
("dwFlags", DWORD), # 0
]
#--- MEMORY_BASIC_INFORMATION structure ---------------------------------------
# typedef struct _MEMORY_BASIC_INFORMATION32 {
# DWORD BaseAddress;
# DWORD AllocationBase;
# DWORD AllocationProtect;
# DWORD RegionSize;
# DWORD State;
# DWORD Protect;
# DWORD Type;
# } MEMORY_BASIC_INFORMATION32, *PMEMORY_BASIC_INFORMATION32;
class MEMORY_BASIC_INFORMATION32(Structure):
_fields_ = [
('BaseAddress', DWORD), # remote pointer
('AllocationBase', DWORD), # remote pointer
('AllocationProtect', DWORD),
('RegionSize', DWORD),
('State', DWORD),
('Protect', DWORD),
('Type', DWORD),
]
# typedef struct DECLSPEC_ALIGN(16) _MEMORY_BASIC_INFORMATION64 {
# ULONGLONG BaseAddress;
# ULONGLONG AllocationBase;
# DWORD AllocationProtect;
# DWORD __alignment1;
# ULONGLONG RegionSize;
# DWORD State;
# DWORD Protect;
# DWORD Type;
# DWORD __alignment2;
# } MEMORY_BASIC_INFORMATION64, *PMEMORY_BASIC_INFORMATION64;
class MEMORY_BASIC_INFORMATION64(Structure):
_fields_ = [
('BaseAddress', ULONGLONG), # remote pointer
('AllocationBase', ULONGLONG), # remote pointer
('AllocationProtect', DWORD),
('__alignment1', DWORD),
('RegionSize', ULONGLONG),
('State', DWORD),
('Protect', DWORD),
('Type', DWORD),
('__alignment2', DWORD),
]
# typedef struct _MEMORY_BASIC_INFORMATION {
# PVOID BaseAddress;
# PVOID AllocationBase;
# DWORD AllocationProtect;
# SIZE_T RegionSize;
# DWORD State;
# DWORD Protect;
# DWORD Type;
# } MEMORY_BASIC_INFORMATION, *PMEMORY_BASIC_INFORMATION;
class MEMORY_BASIC_INFORMATION(Structure):
_fields_ = [
('BaseAddress', SIZE_T), # remote pointer
('AllocationBase', SIZE_T), # remote pointer
('AllocationProtect', DWORD),
('RegionSize', SIZE_T),
('State', DWORD),
('Protect', DWORD),
('Type', DWORD),
]
PMEMORY_BASIC_INFORMATION = POINTER(MEMORY_BASIC_INFORMATION)
#--- BY_HANDLE_FILE_INFORMATION structure -------------------------------------
# typedef struct _FILETIME {
# DWORD dwLowDateTime;
# DWORD dwHighDateTime;
# } FILETIME, *PFILETIME;
class FILETIME(Structure):
_fields_ = [
('dwLowDateTime', DWORD),
('dwHighDateTime', DWORD),
]
LPFILETIME = POINTER(FILETIME)
# typedef struct _SYSTEMTIME {
# WORD wYear;
# WORD wMonth;
# WORD wDayOfWeek;
# WORD wDay;
# WORD wHour;
# WORD wMinute;
# WORD wSecond;
# WORD wMilliseconds;
# }SYSTEMTIME, *PSYSTEMTIME;
class SYSTEMTIME(Structure):
_fields_ = [
('wYear', WORD),
('wMonth', WORD),
('wDayOfWeek', WORD),
('wDay', WORD),
('wHour', WORD),
('wMinute', WORD),
('wSecond', WORD),
('wMilliseconds', WORD),
]
LPSYSTEMTIME = POINTER(SYSTEMTIME)
# typedef struct _BY_HANDLE_FILE_INFORMATION {
# DWORD dwFileAttributes;
# FILETIME ftCreationTime;
# FILETIME ftLastAccessTime;
# FILETIME ftLastWriteTime;
# DWORD dwVolumeSerialNumber;
# DWORD nFileSizeHigh;
# DWORD nFileSizeLow;
# DWORD nNumberOfLinks;
# DWORD nFileIndexHigh;
# DWORD nFileIndexLow;
# } BY_HANDLE_FILE_INFORMATION, *PBY_HANDLE_FILE_INFORMATION;
class BY_HANDLE_FILE_INFORMATION(Structure):
_fields_ = [
('dwFileAttributes', DWORD),
('ftCreationTime', FILETIME),
('ftLastAccessTime', FILETIME),
('ftLastWriteTime', FILETIME),
('dwVolumeSerialNumber', DWORD),
('nFileSizeHigh', DWORD),
('nFileSizeLow', DWORD),
('nNumberOfLinks', DWORD),
('nFileIndexHigh', DWORD),
('nFileIndexLow', DWORD),
]
LPBY_HANDLE_FILE_INFORMATION = POINTER(BY_HANDLE_FILE_INFORMATION)
# typedef enum _FILE_INFO_BY_HANDLE_CLASS {
# FileBasicInfo = 0,
# FileStandardInfo = 1,
# FileNameInfo = 2,
# FileRenameInfo = 3,
# FileDispositionInfo = 4,
# FileAllocationInfo = 5,
# FileEndOfFileInfo = 6,
# FileStreamInfo = 7,
# FileCompressionInfo = 8,
# FileAttributeTagInfo = 9,
# FileIdBothDirectoryInfo = 10,
# FileIdBothDirectoryRestartInfo = 11,
# FileIoPriorityHintInfo = 12,
# MaximumFileInfoByHandlesClass = 13
# } FILE_INFO_BY_HANDLE_CLASS, *PFILE_INFO_BY_HANDLE_CLASS;
class FILE_INFO_BY_HANDLE_CLASS(object):
FileBasicInfo = 0
FileStandardInfo = 1
FileNameInfo = 2
FileRenameInfo = 3
FileDispositionInfo = 4
FileAllocationInfo = 5
FileEndOfFileInfo = 6
FileStreamInfo = 7
FileCompressionInfo = 8
FileAttributeTagInfo = 9
FileIdBothDirectoryInfo = 10
FileIdBothDirectoryRestartInfo = 11
FileIoPriorityHintInfo = 12
MaximumFileInfoByHandlesClass = 13
# typedef struct _FILE_NAME_INFO {
# DWORD FileNameLength;
# WCHAR FileName[1];
# } FILE_NAME_INFO, *PFILE_NAME_INFO;
##class FILE_NAME_INFO(Structure):
## _fields_ = [
## ('FileNameLength', DWORD),
## ('FileName', WCHAR * 1),
## ]
# TO DO: add more structures used by GetFileInformationByHandleEx()
#--- PROCESS_INFORMATION structure --------------------------------------------
# typedef struct _PROCESS_INFORMATION {
# HANDLE hProcess;
# HANDLE hThread;
# DWORD dwProcessId;
# DWORD dwThreadId;
# } PROCESS_INFORMATION, *PPROCESS_INFORMATION, *LPPROCESS_INFORMATION;
class PROCESS_INFORMATION(Structure):
_fields_ = [
('hProcess', HANDLE),
('hThread', HANDLE),
('dwProcessId', DWORD),
('dwThreadId', DWORD),
]
LPPROCESS_INFORMATION = POINTER(PROCESS_INFORMATION)
#--- STARTUPINFO and STARTUPINFOEX structures ---------------------------------
# typedef struct _STARTUPINFO {
# DWORD cb;
# LPTSTR lpReserved;
# LPTSTR lpDesktop;
# LPTSTR lpTitle;
# DWORD dwX;
# DWORD dwY;
# DWORD dwXSize;
# DWORD dwYSize;
# DWORD dwXCountChars;
# DWORD dwYCountChars;
# DWORD dwFillAttribute;
# DWORD dwFlags;
# WORD wShowWindow;
# WORD cbReserved2;
# LPBYTE lpReserved2;
# HANDLE hStdInput;
# HANDLE hStdOutput;
# HANDLE hStdError;
# }STARTUPINFO, *LPSTARTUPINFO;
class STARTUPINFO(Structure):
_fields_ = [
('cb', DWORD),
('lpReserved', LPSTR),
('lpDesktop', LPSTR),
('lpTitle', LPSTR),
('dwX', DWORD),
('dwY', DWORD),
('dwXSize', DWORD),
('dwYSize', DWORD),
('dwXCountChars', DWORD),
('dwYCountChars', DWORD),
('dwFillAttribute', DWORD),
('dwFlags', DWORD),
('wShowWindow', WORD),
('cbReserved2', WORD),
('lpReserved2', LPVOID), # LPBYTE
('hStdInput', HANDLE),
('hStdOutput', HANDLE),
('hStdError', HANDLE),
]
LPSTARTUPINFO = POINTER(STARTUPINFO)
# typedef struct _STARTUPINFOEX {
# STARTUPINFO StartupInfo;
# PPROC_THREAD_ATTRIBUTE_LIST lpAttributeList;
# } STARTUPINFOEX, *LPSTARTUPINFOEX;
class STARTUPINFOEX(Structure):
_fields_ = [
('StartupInfo', STARTUPINFO),
('lpAttributeList', PPROC_THREAD_ATTRIBUTE_LIST),
]
LPSTARTUPINFOEX = POINTER(STARTUPINFOEX)
class STARTUPINFOW(Structure):
_fields_ = [
('cb', DWORD),
('lpReserved', LPWSTR),
('lpDesktop', LPWSTR),
('lpTitle', LPWSTR),
('dwX', DWORD),
('dwY', DWORD),
('dwXSize', DWORD),
('dwYSize', DWORD),
('dwXCountChars', DWORD),
('dwYCountChars', DWORD),
('dwFillAttribute', DWORD),
('dwFlags', DWORD),
('wShowWindow', WORD),
('cbReserved2', WORD),
('lpReserved2', LPVOID), # LPBYTE
('hStdInput', HANDLE),
('hStdOutput', HANDLE),
('hStdError', HANDLE),
]
LPSTARTUPINFOW = POINTER(STARTUPINFOW)
class STARTUPINFOEXW(Structure):
_fields_ = [
('StartupInfo', STARTUPINFOW),
('lpAttributeList', PPROC_THREAD_ATTRIBUTE_LIST),
]
LPSTARTUPINFOEXW = POINTER(STARTUPINFOEXW)
#--- JIT_DEBUG_INFO structure -------------------------------------------------
# typedef struct _JIT_DEBUG_INFO {
# DWORD dwSize;
# DWORD dwProcessorArchitecture;
# DWORD dwThreadID;
# DWORD dwReserved0;
# ULONG64 lpExceptionAddress;
# ULONG64 lpExceptionRecord;
# ULONG64 lpContextRecord;
# } JIT_DEBUG_INFO, *LPJIT_DEBUG_INFO;
class JIT_DEBUG_INFO(Structure):
_fields_ = [
('dwSize', DWORD),
('dwProcessorArchitecture', DWORD),
('dwThreadID', DWORD),
('dwReserved0', DWORD),
('lpExceptionAddress', ULONG64),
('lpExceptionRecord', ULONG64),
('lpContextRecord', ULONG64),
]
JIT_DEBUG_INFO32 = JIT_DEBUG_INFO
JIT_DEBUG_INFO64 = JIT_DEBUG_INFO
LPJIT_DEBUG_INFO = POINTER(JIT_DEBUG_INFO)
LPJIT_DEBUG_INFO32 = POINTER(JIT_DEBUG_INFO32)
LPJIT_DEBUG_INFO64 = POINTER(JIT_DEBUG_INFO64)
#--- DEBUG_EVENT structure ----------------------------------------------------
# typedef struct _EXCEPTION_RECORD32 {
# DWORD ExceptionCode;
# DWORD ExceptionFlags;
# DWORD ExceptionRecord;
# DWORD ExceptionAddress;
# DWORD NumberParameters;
# DWORD ExceptionInformation[EXCEPTION_MAXIMUM_PARAMETERS];
# } EXCEPTION_RECORD32, *PEXCEPTION_RECORD32;
class EXCEPTION_RECORD32(Structure):
_fields_ = [
('ExceptionCode', DWORD),
('ExceptionFlags', DWORD),
('ExceptionRecord', DWORD),
('ExceptionAddress', DWORD),
('NumberParameters', DWORD),
('ExceptionInformation', DWORD * EXCEPTION_MAXIMUM_PARAMETERS),
]
PEXCEPTION_RECORD32 = POINTER(EXCEPTION_RECORD32)
# typedef struct _EXCEPTION_RECORD64 {
# DWORD ExceptionCode;
# DWORD ExceptionFlags;
# DWORD64 ExceptionRecord;
# DWORD64 ExceptionAddress;
# DWORD NumberParameters;
# DWORD __unusedAlignment;
# DWORD64 ExceptionInformation[EXCEPTION_MAXIMUM_PARAMETERS];
# } EXCEPTION_RECORD64, *PEXCEPTION_RECORD64;
class EXCEPTION_RECORD64(Structure):
_fields_ = [
('ExceptionCode', DWORD),
('ExceptionFlags', DWORD),
('ExceptionRecord', DWORD64),
('ExceptionAddress', DWORD64),
('NumberParameters', DWORD),
('__unusedAlignment', DWORD),
('ExceptionInformation', DWORD64 * EXCEPTION_MAXIMUM_PARAMETERS),
]
PEXCEPTION_RECORD64 = POINTER(EXCEPTION_RECORD64)
# typedef struct _EXCEPTION_RECORD {
# DWORD ExceptionCode;
# DWORD ExceptionFlags;
# LPVOID ExceptionRecord;
# LPVOID ExceptionAddress;
# DWORD NumberParameters;
# LPVOID ExceptionInformation[EXCEPTION_MAXIMUM_PARAMETERS];
# } EXCEPTION_RECORD, *PEXCEPTION_RECORD;
class EXCEPTION_RECORD(Structure):
pass
PEXCEPTION_RECORD = POINTER(EXCEPTION_RECORD)
EXCEPTION_RECORD._fields_ = [
('ExceptionCode', DWORD),
('ExceptionFlags', DWORD),
('ExceptionRecord', PEXCEPTION_RECORD),
('ExceptionAddress', LPVOID),
('NumberParameters', DWORD),
('ExceptionInformation', LPVOID * EXCEPTION_MAXIMUM_PARAMETERS),
]
# typedef struct _EXCEPTION_DEBUG_INFO {
# EXCEPTION_RECORD ExceptionRecord;
# DWORD dwFirstChance;
# } EXCEPTION_DEBUG_INFO;
class EXCEPTION_DEBUG_INFO(Structure):
_fields_ = [
('ExceptionRecord', EXCEPTION_RECORD),
('dwFirstChance', DWORD),
]
# typedef struct _CREATE_THREAD_DEBUG_INFO {
# HANDLE hThread;
# LPVOID lpThreadLocalBase;
# LPTHREAD_START_ROUTINE lpStartAddress;
# } CREATE_THREAD_DEBUG_INFO;
class CREATE_THREAD_DEBUG_INFO(Structure):
_fields_ = [
('hThread', HANDLE),
('lpThreadLocalBase', LPVOID),
('lpStartAddress', LPVOID),
]
# typedef struct _CREATE_PROCESS_DEBUG_INFO {
# HANDLE hFile;
# HANDLE hProcess;
# HANDLE hThread;
# LPVOID lpBaseOfImage;
# DWORD dwDebugInfoFileOffset;
# DWORD nDebugInfoSize;
# LPVOID lpThreadLocalBase;
# LPTHREAD_START_ROUTINE lpStartAddress;
# LPVOID lpImageName;
# WORD fUnicode;
# } CREATE_PROCESS_DEBUG_INFO;
class CREATE_PROCESS_DEBUG_INFO(Structure):
_fields_ = [
('hFile', HANDLE),
('hProcess', HANDLE),
('hThread', HANDLE),
('lpBaseOfImage', LPVOID),
('dwDebugInfoFileOffset', DWORD),
('nDebugInfoSize', DWORD),
('lpThreadLocalBase', LPVOID),
('lpStartAddress', LPVOID),
('lpImageName', LPVOID),
('fUnicode', WORD),
]
# typedef struct _EXIT_THREAD_DEBUG_INFO {
# DWORD dwExitCode;
# } EXIT_THREAD_DEBUG_INFO;
class EXIT_THREAD_DEBUG_INFO(Structure):
_fields_ = [
('dwExitCode', DWORD),
]
# typedef struct _EXIT_PROCESS_DEBUG_INFO {
# DWORD dwExitCode;
# } EXIT_PROCESS_DEBUG_INFO;
class EXIT_PROCESS_DEBUG_INFO(Structure):
_fields_ = [
('dwExitCode', DWORD),
]
# typedef struct _LOAD_DLL_DEBUG_INFO {
# HANDLE hFile;
# LPVOID lpBaseOfDll;
# DWORD dwDebugInfoFileOffset;
# DWORD nDebugInfoSize;
# LPVOID lpImageName;
# WORD fUnicode;
# } LOAD_DLL_DEBUG_INFO;
class LOAD_DLL_DEBUG_INFO(Structure):
_fields_ = [
('hFile', HANDLE),
('lpBaseOfDll', LPVOID),
('dwDebugInfoFileOffset', DWORD),
('nDebugInfoSize', DWORD),
('lpImageName', LPVOID),
('fUnicode', WORD),
]
# typedef struct _UNLOAD_DLL_DEBUG_INFO {
# LPVOID lpBaseOfDll;
# } UNLOAD_DLL_DEBUG_INFO;
class UNLOAD_DLL_DEBUG_INFO(Structure):
_fields_ = [
('lpBaseOfDll', LPVOID),
]
# typedef struct _OUTPUT_DEBUG_STRING_INFO {
# LPSTR lpDebugStringData;
# WORD fUnicode;
# WORD nDebugStringLength;
# } OUTPUT_DEBUG_STRING_INFO;
class OUTPUT_DEBUG_STRING_INFO(Structure):
_fields_ = [
('lpDebugStringData', LPVOID), # don't use LPSTR
('fUnicode', WORD),
('nDebugStringLength', WORD),
]
# typedef struct _RIP_INFO {
# DWORD dwError;
# DWORD dwType;
# } RIP_INFO, *LPRIP_INFO;
class RIP_INFO(Structure):
_fields_ = [
('dwError', DWORD),
('dwType', DWORD),
]
# typedef struct _DEBUG_EVENT {
# DWORD dwDebugEventCode;
# DWORD dwProcessId;
# DWORD dwThreadId;
# union {
# EXCEPTION_DEBUG_INFO Exception;
# CREATE_THREAD_DEBUG_INFO CreateThread;
# CREATE_PROCESS_DEBUG_INFO CreateProcessInfo;
# EXIT_THREAD_DEBUG_INFO ExitThread;
# EXIT_PROCESS_DEBUG_INFO ExitProcess;
# LOAD_DLL_DEBUG_INFO LoadDll;
# UNLOAD_DLL_DEBUG_INFO UnloadDll;
# OUTPUT_DEBUG_STRING_INFO DebugString;
# RIP_INFO RipInfo;
# } u;
# } DEBUG_EVENT;.
class _DEBUG_EVENT_UNION_(Union):
_fields_ = [
('Exception', EXCEPTION_DEBUG_INFO),
('CreateThread', CREATE_THREAD_DEBUG_INFO),
('CreateProcessInfo', CREATE_PROCESS_DEBUG_INFO),
('ExitThread', EXIT_THREAD_DEBUG_INFO),
('ExitProcess', EXIT_PROCESS_DEBUG_INFO),
('LoadDll', LOAD_DLL_DEBUG_INFO),
('UnloadDll', UNLOAD_DLL_DEBUG_INFO),
('DebugString', OUTPUT_DEBUG_STRING_INFO),
('RipInfo', RIP_INFO),
]
class DEBUG_EVENT(Structure):
_fields_ = [
('dwDebugEventCode', DWORD),
('dwProcessId', DWORD),
('dwThreadId', DWORD),
('u', _DEBUG_EVENT_UNION_),
]
LPDEBUG_EVENT = POINTER(DEBUG_EVENT)
#--- Console API defines and structures ---------------------------------------
FOREGROUND_MASK = 0x000F
BACKGROUND_MASK = 0x00F0
COMMON_LVB_MASK = 0xFF00
FOREGROUND_BLACK = 0x0000
FOREGROUND_BLUE = 0x0001
FOREGROUND_GREEN = 0x0002
FOREGROUND_CYAN = 0x0003
FOREGROUND_RED = 0x0004
FOREGROUND_MAGENTA = 0x0005
FOREGROUND_YELLOW = 0x0006
FOREGROUND_GREY = 0x0007
FOREGROUND_INTENSITY = 0x0008
BACKGROUND_BLACK = 0x0000
BACKGROUND_BLUE = 0x0010
BACKGROUND_GREEN = 0x0020
BACKGROUND_CYAN = 0x0030
BACKGROUND_RED = 0x0040
BACKGROUND_MAGENTA = 0x0050
BACKGROUND_YELLOW = 0x0060
BACKGROUND_GREY = 0x0070
BACKGROUND_INTENSITY = 0x0080
COMMON_LVB_LEADING_BYTE = 0x0100
COMMON_LVB_TRAILING_BYTE = 0x0200
COMMON_LVB_GRID_HORIZONTAL = 0x0400
COMMON_LVB_GRID_LVERTICAL = 0x0800
COMMON_LVB_GRID_RVERTICAL = 0x1000
COMMON_LVB_REVERSE_VIDEO = 0x4000
COMMON_LVB_UNDERSCORE = 0x8000
# typedef struct _CHAR_INFO {
# union {
# WCHAR UnicodeChar;
# CHAR AsciiChar;
# } Char;
# WORD Attributes;
# } CHAR_INFO, *PCHAR_INFO;
class _CHAR_INFO_CHAR(Union):
_fields_ = [
('UnicodeChar', WCHAR),
('AsciiChar', CHAR),
]
class CHAR_INFO(Structure):
_fields_ = [
('Char', _CHAR_INFO_CHAR),
('Attributes', WORD),
]
PCHAR_INFO = POINTER(CHAR_INFO)
# typedef struct _COORD {
# SHORT X;
# SHORT Y;
# } COORD, *PCOORD;
class COORD(Structure):
_fields_ = [
('X', SHORT),
('Y', SHORT),
]
PCOORD = POINTER(COORD)
# typedef struct _SMALL_RECT {
# SHORT Left;
# SHORT Top;
# SHORT Right;
# SHORT Bottom;
# } SMALL_RECT;
class SMALL_RECT(Structure):
_fields_ = [
('Left', SHORT),
('Top', SHORT),
('Right', SHORT),
('Bottom', SHORT),
]
PSMALL_RECT = POINTER(SMALL_RECT)
# typedef struct _CONSOLE_SCREEN_BUFFER_INFO {
# COORD dwSize;
# COORD dwCursorPosition;
# WORD wAttributes;
# SMALL_RECT srWindow;
# COORD dwMaximumWindowSize;
# } CONSOLE_SCREEN_BUFFER_INFO;
class CONSOLE_SCREEN_BUFFER_INFO(Structure):
_fields_ = [
('dwSize', COORD),
('dwCursorPosition', COORD),
('wAttributes', WORD),
('srWindow', SMALL_RECT),
('dwMaximumWindowSize', COORD),
]
PCONSOLE_SCREEN_BUFFER_INFO = POINTER(CONSOLE_SCREEN_BUFFER_INFO)
#--- Toolhelp library defines and structures ----------------------------------
TH32CS_SNAPHEAPLIST = 0x00000001
TH32CS_SNAPPROCESS = 0x00000002
TH32CS_SNAPTHREAD = 0x00000004
TH32CS_SNAPMODULE = 0x00000008
TH32CS_INHERIT = 0x80000000
TH32CS_SNAPALL = (TH32CS_SNAPHEAPLIST | TH32CS_SNAPPROCESS | TH32CS_SNAPTHREAD | TH32CS_SNAPMODULE)
# typedef struct tagTHREADENTRY32 {
# DWORD dwSize;
# DWORD cntUsage;
# DWORD th32ThreadID;
# DWORD th32OwnerProcessID;
# LONG tpBasePri;
# LONG tpDeltaPri;
# DWORD dwFlags;
# } THREADENTRY32, *PTHREADENTRY32;
class THREADENTRY32(Structure):
_fields_ = [
('dwSize', DWORD),
('cntUsage', DWORD),
('th32ThreadID', DWORD),
('th32OwnerProcessID', DWORD),
('tpBasePri', LONG),
('tpDeltaPri', LONG),
('dwFlags', DWORD),
]
LPTHREADENTRY32 = POINTER(THREADENTRY32)
# typedef struct tagPROCESSENTRY32 {
# DWORD dwSize;
# DWORD cntUsage;
# DWORD th32ProcessID;
# ULONG_PTR th32DefaultHeapID;
# DWORD th32ModuleID;
# DWORD cntThreads;
# DWORD th32ParentProcessID;
# LONG pcPriClassBase;
# DWORD dwFlags;
# TCHAR szExeFile[MAX_PATH];
# } PROCESSENTRY32, *PPROCESSENTRY32;
class PROCESSENTRY32(Structure):
_fields_ = [
('dwSize', DWORD),
('cntUsage', DWORD),
('th32ProcessID', DWORD),
('th32DefaultHeapID', ULONG_PTR),
('th32ModuleID', DWORD),
('cntThreads', DWORD),
('th32ParentProcessID', DWORD),
('pcPriClassBase', LONG),
('dwFlags', DWORD),
('szExeFile', TCHAR * 260),
]
LPPROCESSENTRY32 = POINTER(PROCESSENTRY32)
# typedef struct tagMODULEENTRY32 {
# DWORD dwSize;
# DWORD th32ModuleID;
# DWORD th32ProcessID;
# DWORD GlblcntUsage;
# DWORD ProccntUsage;
# BYTE* modBaseAddr;
# DWORD modBaseSize;
# HMODULE hModule;
# TCHAR szModule[MAX_MODULE_NAME32 + 1];
# TCHAR szExePath[MAX_PATH];
# } MODULEENTRY32, *PMODULEENTRY32;
class MODULEENTRY32(Structure):
_fields_ = [
("dwSize", DWORD),
("th32ModuleID", DWORD),
("th32ProcessID", DWORD),
("GlblcntUsage", DWORD),
("ProccntUsage", DWORD),
("modBaseAddr", LPVOID), # BYTE*
("modBaseSize", DWORD),
("hModule", HMODULE),
("szModule", TCHAR * (MAX_MODULE_NAME32 + 1)),
("szExePath", TCHAR * MAX_PATH),
]
LPMODULEENTRY32 = POINTER(MODULEENTRY32)
# typedef struct tagHEAPENTRY32 {
# SIZE_T dwSize;
# HANDLE hHandle;
# ULONG_PTR dwAddress;
# SIZE_T dwBlockSize;
# DWORD dwFlags;
# DWORD dwLockCount;
# DWORD dwResvd;
# DWORD th32ProcessID;
# ULONG_PTR th32HeapID;
# } HEAPENTRY32,
# *PHEAPENTRY32;
class HEAPENTRY32(Structure):
_fields_ = [
("dwSize", SIZE_T),
("hHandle", HANDLE),
("dwAddress", ULONG_PTR),
("dwBlockSize", SIZE_T),
("dwFlags", DWORD),
("dwLockCount", DWORD),
("dwResvd", DWORD),
("th32ProcessID", DWORD),
("th32HeapID", ULONG_PTR),
]
LPHEAPENTRY32 = POINTER(HEAPENTRY32)
# typedef struct tagHEAPLIST32 {
# SIZE_T dwSize;
# DWORD th32ProcessID;
# ULONG_PTR th32HeapID;
# DWORD dwFlags;
# } HEAPLIST32,
# *PHEAPLIST32;
class HEAPLIST32(Structure):
_fields_ = [
("dwSize", SIZE_T),
("th32ProcessID", DWORD),
("th32HeapID", ULONG_PTR),
("dwFlags", DWORD),
]
LPHEAPLIST32 = POINTER(HEAPLIST32)
#--- kernel32.dll -------------------------------------------------------------
# DWORD WINAPI GetLastError(void);
def GetLastError():
_GetLastError = windll.kernel32.GetLastError
_GetLastError.argtypes = []
_GetLastError.restype = DWORD
return _GetLastError()
# void WINAPI SetLastError(
# __in DWORD dwErrCode
# );
def SetLastError(dwErrCode):
_SetLastError = windll.kernel32.SetLastError
_SetLastError.argtypes = [DWORD]
_SetLastError.restype = None
_SetLastError(dwErrCode)
# UINT WINAPI GetErrorMode(void);
def GetErrorMode():
_GetErrorMode = windll.kernel32.GetErrorMode
_GetErrorMode.argtypes = []
_GetErrorMode.restype = UINT
return _GetErrorMode()
# UINT WINAPI SetErrorMode(
# __in UINT uMode
# );
def SetErrorMode(uMode):
_SetErrorMode = windll.kernel32.SetErrorMode
_SetErrorMode.argtypes = [UINT]
_SetErrorMode.restype = UINT
return _SetErrorMode(dwErrCode)
# DWORD GetThreadErrorMode(void);
def GetThreadErrorMode():
_GetThreadErrorMode = windll.kernel32.GetThreadErrorMode
_GetThreadErrorMode.argtypes = []
_GetThreadErrorMode.restype = DWORD
return _GetThreadErrorMode()
# BOOL SetThreadErrorMode(
# __in DWORD dwNewMode,
# __out LPDWORD lpOldMode
# );
def SetThreadErrorMode(dwNewMode):
_SetThreadErrorMode = windll.kernel32.SetThreadErrorMode
_SetThreadErrorMode.argtypes = [DWORD, LPDWORD]
_SetThreadErrorMode.restype = BOOL
_SetThreadErrorMode.errcheck = RaiseIfZero
old = DWORD(0)
_SetThreadErrorMode(dwErrCode, byref(old))
return old.value
# BOOL WINAPI CloseHandle(
# __in HANDLE hObject
# );
def CloseHandle(hHandle):
if isinstance(hHandle, Handle):
# Prevents the handle from being closed without notifying the Handle object.
hHandle.close()
else:
_CloseHandle = windll.kernel32.CloseHandle
_CloseHandle.argtypes = [HANDLE]
_CloseHandle.restype = bool
_CloseHandle.errcheck = RaiseIfZero
_CloseHandle(hHandle)
# BOOL WINAPI DuplicateHandle(
# __in HANDLE hSourceProcessHandle,
# __in HANDLE hSourceHandle,
# __in HANDLE hTargetProcessHandle,
# __out LPHANDLE lpTargetHandle,
# __in DWORD dwDesiredAccess,
# __in BOOL bInheritHandle,
# __in DWORD dwOptions
# );
def DuplicateHandle(hSourceHandle, hSourceProcessHandle = None, hTargetProcessHandle = None, dwDesiredAccess = STANDARD_RIGHTS_ALL, bInheritHandle = False, dwOptions = DUPLICATE_SAME_ACCESS):
_DuplicateHandle = windll.kernel32.DuplicateHandle
_DuplicateHandle.argtypes = [HANDLE, HANDLE, HANDLE, LPHANDLE, DWORD, BOOL, DWORD]
_DuplicateHandle.restype = bool
_DuplicateHandle.errcheck = RaiseIfZero
# NOTE: the arguments to this function are in a different order,
# so we can set default values for all of them but one (hSourceHandle).
if hSourceProcessHandle is None:
hSourceProcessHandle = GetCurrentProcess()
if hTargetProcessHandle is None:
hTargetProcessHandle = hSourceProcessHandle
lpTargetHandle = HANDLE(INVALID_HANDLE_VALUE)
_DuplicateHandle(hSourceProcessHandle, hSourceHandle, hTargetProcessHandle, byref(lpTargetHandle), dwDesiredAccess, bool(bInheritHandle), dwOptions)
if isinstance(hSourceHandle, Handle):
HandleClass = hSourceHandle.__class__
else:
HandleClass = Handle
if hasattr(hSourceHandle, 'dwAccess'):
return HandleClass(lpTargetHandle.value, dwAccess = hSourceHandle.dwAccess)
else:
return HandleClass(lpTargetHandle.value)
# HLOCAL WINAPI LocalFree(
# __in HLOCAL hMem
# );
def LocalFree(hMem):
_LocalFree = windll.kernel32.LocalFree
_LocalFree.argtypes = [HLOCAL]
_LocalFree.restype = HLOCAL
result = _LocalFree(hMem)
if result != NULL:
ctypes.WinError()
#------------------------------------------------------------------------------
# Console API
# HANDLE WINAPI GetStdHandle(
# _In_ DWORD nStdHandle
# );
def GetStdHandle(nStdHandle):
_GetStdHandle = windll.kernel32.GetStdHandle
_GetStdHandle.argytpes = [DWORD]
_GetStdHandle.restype = HANDLE
_GetStdHandle.errcheck = RaiseIfZero
return Handle( _GetStdHandle(nStdHandle), bOwnership = False )
# BOOL WINAPI SetStdHandle(
# _In_ DWORD nStdHandle,
# _In_ HANDLE hHandle
# );
# TODO
# UINT WINAPI GetConsoleCP(void);
def GetConsoleCP():
_GetConsoleCP = windll.kernel32.GetConsoleCP
_GetConsoleCP.argytpes = []
_GetConsoleCP.restype = UINT
return _GetConsoleCP()
# UINT WINAPI GetConsoleOutputCP(void);
def GetConsoleOutputCP():
_GetConsoleOutputCP = windll.kernel32.GetConsoleOutputCP
_GetConsoleOutputCP.argytpes = []
_GetConsoleOutputCP.restype = UINT
return _GetConsoleOutputCP()
#BOOL WINAPI SetConsoleCP(
# _In_ UINT wCodePageID
#);
def SetConsoleCP(wCodePageID):
_SetConsoleCP = windll.kernel32.SetConsoleCP
_SetConsoleCP.argytpes = [UINT]
_SetConsoleCP.restype = bool
_SetConsoleCP.errcheck = RaiseIfZero
_SetConsoleCP(wCodePageID)
#BOOL WINAPI SetConsoleOutputCP(
# _In_ UINT wCodePageID
#);
def SetConsoleOutputCP(wCodePageID):
_SetConsoleOutputCP = windll.kernel32.SetConsoleOutputCP
_SetConsoleOutputCP.argytpes = [UINT]
_SetConsoleOutputCP.restype = bool
_SetConsoleOutputCP.errcheck = RaiseIfZero
_SetConsoleOutputCP(wCodePageID)
# HANDLE WINAPI CreateConsoleScreenBuffer(
# _In_ DWORD dwDesiredAccess,
# _In_ DWORD dwShareMode,
# _In_opt_ const SECURITY_ATTRIBUTES *lpSecurityAttributes,
# _In_ DWORD dwFlags,
# _Reserved_ LPVOID lpScreenBufferData
# );
# TODO
# BOOL WINAPI SetConsoleActiveScreenBuffer(
# _In_ HANDLE hConsoleOutput
# );
def SetConsoleActiveScreenBuffer(hConsoleOutput = None):
_SetConsoleActiveScreenBuffer = windll.kernel32.SetConsoleActiveScreenBuffer
_SetConsoleActiveScreenBuffer.argytpes = [HANDLE]
_SetConsoleActiveScreenBuffer.restype = bool
_SetConsoleActiveScreenBuffer.errcheck = RaiseIfZero
if hConsoleOutput is None:
hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE)
_SetConsoleActiveScreenBuffer(hConsoleOutput)
# BOOL WINAPI GetConsoleScreenBufferInfo(
# _In_ HANDLE hConsoleOutput,
# _Out_ PCONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo
# );
def GetConsoleScreenBufferInfo(hConsoleOutput = None):
_GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo
_GetConsoleScreenBufferInfo.argytpes = [HANDLE, PCONSOLE_SCREEN_BUFFER_INFO]
_GetConsoleScreenBufferInfo.restype = bool
_GetConsoleScreenBufferInfo.errcheck = RaiseIfZero
if hConsoleOutput is None:
hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE)
ConsoleScreenBufferInfo = CONSOLE_SCREEN_BUFFER_INFO()
_GetConsoleScreenBufferInfo(hConsoleOutput, byref(ConsoleScreenBufferInfo))
return ConsoleScreenBufferInfo
# BOOL WINAPI GetConsoleScreenBufferInfoEx(
# _In_ HANDLE hConsoleOutput,
# _Out_ PCONSOLE_SCREEN_BUFFER_INFOEX lpConsoleScreenBufferInfoEx
# );
# TODO
# BOOL WINAPI SetConsoleWindowInfo(
# _In_ HANDLE hConsoleOutput,
# _In_ BOOL bAbsolute,
# _In_ const SMALL_RECT *lpConsoleWindow
# );
def SetConsoleWindowInfo(hConsoleOutput, bAbsolute, lpConsoleWindow):
_SetConsoleWindowInfo = windll.kernel32.SetConsoleWindowInfo
_SetConsoleWindowInfo.argytpes = [HANDLE, BOOL, PSMALL_RECT]
_SetConsoleWindowInfo.restype = bool
_SetConsoleWindowInfo.errcheck = RaiseIfZero
if hConsoleOutput is None:
hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE)
if isinstance(lpConsoleWindow, SMALL_RECT):
ConsoleWindow = lpConsoleWindow
else:
ConsoleWindow = SMALL_RECT(*lpConsoleWindow)
_SetConsoleWindowInfo(hConsoleOutput, bAbsolute, byref(ConsoleWindow))
# BOOL WINAPI SetConsoleTextAttribute(
# _In_ HANDLE hConsoleOutput,
# _In_ WORD wAttributes
# );
def SetConsoleTextAttribute(hConsoleOutput = None, wAttributes = 0):
_SetConsoleTextAttribute = windll.kernel32.SetConsoleTextAttribute
_SetConsoleTextAttribute.argytpes = [HANDLE, WORD]
_SetConsoleTextAttribute.restype = bool
_SetConsoleTextAttribute.errcheck = RaiseIfZero
if hConsoleOutput is None:
hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE)
_SetConsoleTextAttribute(hConsoleOutput, wAttributes)
# HANDLE WINAPI CreateConsoleScreenBuffer(
# _In_ DWORD dwDesiredAccess,
# _In_ DWORD dwShareMode,
# _In_opt_ const SECURITY_ATTRIBUTES *lpSecurityAttributes,
# _In_ DWORD dwFlags,
# _Reserved_ LPVOID lpScreenBufferData
# );
# TODO
# BOOL WINAPI AllocConsole(void);
def AllocConsole():
_AllocConsole = windll.kernel32.AllocConsole
_AllocConsole.argytpes = []
_AllocConsole.restype = bool
_AllocConsole.errcheck = RaiseIfZero
_AllocConsole()
# BOOL WINAPI AttachConsole(
# _In_ DWORD dwProcessId
# );
def AttachConsole(dwProcessId = ATTACH_PARENT_PROCESS):
_AttachConsole = windll.kernel32.AttachConsole
_AttachConsole.argytpes = [DWORD]
_AttachConsole.restype = bool
_AttachConsole.errcheck = RaiseIfZero
_AttachConsole(dwProcessId)
# BOOL WINAPI FreeConsole(void);
def FreeConsole():
_FreeConsole = windll.kernel32.FreeConsole
_FreeConsole.argytpes = []
_FreeConsole.restype = bool
_FreeConsole.errcheck = RaiseIfZero
_FreeConsole()
# DWORD WINAPI GetConsoleProcessList(
# _Out_ LPDWORD lpdwProcessList,
# _In_ DWORD dwProcessCount
# );
# TODO
# DWORD WINAPI GetConsoleTitle(
# _Out_ LPTSTR lpConsoleTitle,
# _In_ DWORD nSize
# );
# TODO
#BOOL WINAPI SetConsoleTitle(
# _In_ LPCTSTR lpConsoleTitle
#);
# TODO
# COORD WINAPI GetLargestConsoleWindowSize(
# _In_ HANDLE hConsoleOutput
# );
# TODO
# BOOL WINAPI GetConsoleHistoryInfo(
# _Out_ PCONSOLE_HISTORY_INFO lpConsoleHistoryInfo
# );
# TODO
#------------------------------------------------------------------------------
# DLL API
# DWORD WINAPI GetDllDirectory(
# __in DWORD nBufferLength,
# __out LPTSTR lpBuffer
# );
def GetDllDirectoryA():
_GetDllDirectoryA = windll.kernel32.GetDllDirectoryA
_GetDllDirectoryA.argytpes = [DWORD, LPSTR]
_GetDllDirectoryA.restype = DWORD
nBufferLength = _GetDllDirectoryA(0, None)
if nBufferLength == 0:
return None
lpBuffer = ctypes.create_string_buffer("", nBufferLength)
_GetDllDirectoryA(nBufferLength, byref(lpBuffer))
return lpBuffer.value
def GetDllDirectoryW():
_GetDllDirectoryW = windll.kernel32.GetDllDirectoryW
_GetDllDirectoryW.argytpes = [DWORD, LPWSTR]
_GetDllDirectoryW.restype = DWORD
nBufferLength = _GetDllDirectoryW(0, None)
if nBufferLength == 0:
return None
lpBuffer = ctypes.create_unicode_buffer(u"", nBufferLength)
_GetDllDirectoryW(nBufferLength, byref(lpBuffer))
return lpBuffer.value
GetDllDirectory = GuessStringType(GetDllDirectoryA, GetDllDirectoryW)
# BOOL WINAPI SetDllDirectory(
# __in_opt LPCTSTR lpPathName
# );
def SetDllDirectoryA(lpPathName = None):
_SetDllDirectoryA = windll.kernel32.SetDllDirectoryA
_SetDllDirectoryA.argytpes = [LPSTR]
_SetDllDirectoryA.restype = bool
_SetDllDirectoryA.errcheck = RaiseIfZero
_SetDllDirectoryA(lpPathName)
def SetDllDirectoryW(lpPathName):
_SetDllDirectoryW = windll.kernel32.SetDllDirectoryW
_SetDllDirectoryW.argytpes = [LPWSTR]
_SetDllDirectoryW.restype = bool
_SetDllDirectoryW.errcheck = RaiseIfZero
_SetDllDirectoryW(lpPathName)
SetDllDirectory = GuessStringType(SetDllDirectoryA, SetDllDirectoryW)
# HMODULE WINAPI LoadLibrary(
# __in LPCTSTR lpFileName
# );
def LoadLibraryA(pszLibrary):
_LoadLibraryA = windll.kernel32.LoadLibraryA
_LoadLibraryA.argtypes = [LPSTR]
_LoadLibraryA.restype = HMODULE
hModule = _LoadLibraryA(pszLibrary)
if hModule == NULL:
raise ctypes.WinError()
return hModule
def LoadLibraryW(pszLibrary):
_LoadLibraryW = windll.kernel32.LoadLibraryW
_LoadLibraryW.argtypes = [LPWSTR]
_LoadLibraryW.restype = HMODULE
hModule = _LoadLibraryW(pszLibrary)
if hModule == NULL:
raise ctypes.WinError()
return hModule
LoadLibrary = GuessStringType(LoadLibraryA, LoadLibraryW)
# HMODULE WINAPI LoadLibraryEx(
# __in LPCTSTR lpFileName,
# __reserved HANDLE hFile,
# __in DWORD dwFlags
# );
def LoadLibraryExA(pszLibrary, dwFlags = 0):
_LoadLibraryExA = windll.kernel32.LoadLibraryExA
_LoadLibraryExA.argtypes = [LPSTR, HANDLE, DWORD]
_LoadLibraryExA.restype = HMODULE
hModule = _LoadLibraryExA(pszLibrary, NULL, dwFlags)
if hModule == NULL:
raise ctypes.WinError()
return hModule
def LoadLibraryExW(pszLibrary, dwFlags = 0):
_LoadLibraryExW = windll.kernel32.LoadLibraryExW
_LoadLibraryExW.argtypes = [LPWSTR, HANDLE, DWORD]
_LoadLibraryExW.restype = HMODULE
hModule = _LoadLibraryExW(pszLibrary, NULL, dwFlags)
if hModule == NULL:
raise ctypes.WinError()
return hModule
LoadLibraryEx = GuessStringType(LoadLibraryExA, LoadLibraryExW)
# HMODULE WINAPI GetModuleHandle(
# __in_opt LPCTSTR lpModuleName
# );
def GetModuleHandleA(lpModuleName):
_GetModuleHandleA = windll.kernel32.GetModuleHandleA
_GetModuleHandleA.argtypes = [LPSTR]
_GetModuleHandleA.restype = HMODULE
hModule = _GetModuleHandleA(lpModuleName)
if hModule == NULL:
raise ctypes.WinError()
return hModule
def GetModuleHandleW(lpModuleName):
_GetModuleHandleW = windll.kernel32.GetModuleHandleW
_GetModuleHandleW.argtypes = [LPWSTR]
_GetModuleHandleW.restype = HMODULE
hModule = _GetModuleHandleW(lpModuleName)
if hModule == NULL:
raise ctypes.WinError()
return hModule
GetModuleHandle = GuessStringType(GetModuleHandleA, GetModuleHandleW)
# FARPROC WINAPI GetProcAddress(
# __in HMODULE hModule,
# __in LPCSTR lpProcName
# );
def GetProcAddressA(hModule, lpProcName):
_GetProcAddress = windll.kernel32.GetProcAddress
_GetProcAddress.argtypes = [HMODULE, LPVOID]
_GetProcAddress.restype = LPVOID
if type(lpProcName) in (type(0), type(long(0))):
lpProcName = LPVOID(lpProcName)
if lpProcName.value & (~0xFFFF):
raise ValueError('Ordinal number too large: %d' % lpProcName.value)
elif type(lpProcName) == type(compat.b("")):
lpProcName = ctypes.c_char_p(lpProcName)
else:
raise TypeError(str(type(lpProcName)))
return _GetProcAddress(hModule, lpProcName)
GetProcAddressW = MakeWideVersion(GetProcAddressA)
GetProcAddress = GuessStringType(GetProcAddressA, GetProcAddressW)
# BOOL WINAPI FreeLibrary(
# __in HMODULE hModule
# );
def FreeLibrary(hModule):
_FreeLibrary = windll.kernel32.FreeLibrary
_FreeLibrary.argtypes = [HMODULE]
_FreeLibrary.restype = bool
_FreeLibrary.errcheck = RaiseIfZero
_FreeLibrary(hModule)
# PVOID WINAPI RtlPcToFileHeader(
# __in PVOID PcValue,
# __out PVOID *BaseOfImage
# );
def RtlPcToFileHeader(PcValue):
_RtlPcToFileHeader = windll.kernel32.RtlPcToFileHeader
_RtlPcToFileHeader.argtypes = [PVOID, POINTER(PVOID)]
_RtlPcToFileHeader.restype = PRUNTIME_FUNCTION
BaseOfImage = PVOID(0)
_RtlPcToFileHeader(PcValue, byref(BaseOfImage))
return BaseOfImage.value
#------------------------------------------------------------------------------
# File API and related
# BOOL WINAPI GetHandleInformation(
# __in HANDLE hObject,
# __out LPDWORD lpdwFlags
# );
def GetHandleInformation(hObject):
_GetHandleInformation = windll.kernel32.GetHandleInformation
_GetHandleInformation.argtypes = [HANDLE, PDWORD]
_GetHandleInformation.restype = bool
_GetHandleInformation.errcheck = RaiseIfZero
dwFlags = DWORD(0)
_GetHandleInformation(hObject, byref(dwFlags))
return dwFlags.value
# BOOL WINAPI SetHandleInformation(
# __in HANDLE hObject,
# __in DWORD dwMask,
# __in DWORD dwFlags
# );
def SetHandleInformation(hObject, dwMask, dwFlags):
_SetHandleInformation = windll.kernel32.SetHandleInformation
_SetHandleInformation.argtypes = [HANDLE, DWORD, DWORD]
_SetHandleInformation.restype = bool
_SetHandleInformation.errcheck = RaiseIfZero
_SetHandleInformation(hObject, dwMask, dwFlags)
# UINT WINAPI GetWindowModuleFileName(
# __in HWND hwnd,
# __out LPTSTR lpszFileName,
# __in UINT cchFileNameMax
# );
# Not included because it doesn't work in other processes.
# See: http://support.microsoft.com/?id=228469
# BOOL WINAPI QueryFullProcessImageName(
# __in HANDLE hProcess,
# __in DWORD dwFlags,
# __out LPTSTR lpExeName,
# __inout PDWORD lpdwSize
# );
def QueryFullProcessImageNameA(hProcess, dwFlags = 0):
_QueryFullProcessImageNameA = windll.kernel32.QueryFullProcessImageNameA
_QueryFullProcessImageNameA.argtypes = [HANDLE, DWORD, LPSTR, PDWORD]
_QueryFullProcessImageNameA.restype = bool
dwSize = MAX_PATH
while 1:
lpdwSize = DWORD(dwSize)
lpExeName = ctypes.create_string_buffer('', lpdwSize.value + 1)
success = _QueryFullProcessImageNameA(hProcess, dwFlags, lpExeName, byref(lpdwSize))
if success and 0 < lpdwSize.value < dwSize:
break
error = GetLastError()
if error != ERROR_INSUFFICIENT_BUFFER:
raise ctypes.WinError(error)
dwSize = dwSize + 256
if dwSize > 0x1000:
# this prevents an infinite loop in Windows 2008 when the path has spaces,
# see http://msdn.microsoft.com/en-us/library/ms684919(VS.85).aspx#4
raise ctypes.WinError(error)
return lpExeName.value
def QueryFullProcessImageNameW(hProcess, dwFlags = 0):
_QueryFullProcessImageNameW = windll.kernel32.QueryFullProcessImageNameW
_QueryFullProcessImageNameW.argtypes = [HANDLE, DWORD, LPWSTR, PDWORD]
_QueryFullProcessImageNameW.restype = bool
dwSize = MAX_PATH
while 1:
lpdwSize = DWORD(dwSize)
lpExeName = ctypes.create_unicode_buffer('', lpdwSize.value + 1)
success = _QueryFullProcessImageNameW(hProcess, dwFlags, lpExeName, byref(lpdwSize))
if success and 0 < lpdwSize.value < dwSize:
break
error = GetLastError()
if error != ERROR_INSUFFICIENT_BUFFER:
raise ctypes.WinError(error)
dwSize = dwSize + 256
if dwSize > 0x1000:
# this prevents an infinite loop in Windows 2008 when the path has spaces,
# see http://msdn.microsoft.com/en-us/library/ms684919(VS.85).aspx#4
raise ctypes.WinError(error)
return lpExeName.value
QueryFullProcessImageName = GuessStringType(QueryFullProcessImageNameA, QueryFullProcessImageNameW)
# DWORD WINAPI GetLogicalDriveStrings(
# __in DWORD nBufferLength,
# __out LPTSTR lpBuffer
# );
def GetLogicalDriveStringsA():
_GetLogicalDriveStringsA = ctypes.windll.kernel32.GetLogicalDriveStringsA
_GetLogicalDriveStringsA.argtypes = [DWORD, LPSTR]
_GetLogicalDriveStringsA.restype = DWORD
_GetLogicalDriveStringsA.errcheck = RaiseIfZero
nBufferLength = (4 * 26) + 1 # "X:\\\0" from A to Z plus empty string
lpBuffer = ctypes.create_string_buffer('', nBufferLength)
_GetLogicalDriveStringsA(nBufferLength, lpBuffer)
drive_strings = list()
string_p = addressof(lpBuffer)
sizeof_char = sizeof(ctypes.c_char)
while True:
string_v = ctypes.string_at(string_p)
if string_v == '':
break
drive_strings.append(string_v)
string_p += len(string_v) + sizeof_char
return drive_strings
def GetLogicalDriveStringsW():
_GetLogicalDriveStringsW = ctypes.windll.kernel32.GetLogicalDriveStringsW
_GetLogicalDriveStringsW.argtypes = [DWORD, LPWSTR]
_GetLogicalDriveStringsW.restype = DWORD
_GetLogicalDriveStringsW.errcheck = RaiseIfZero
nBufferLength = (4 * 26) + 1 # "X:\\\0" from A to Z plus empty string
lpBuffer = ctypes.create_unicode_buffer(u'', nBufferLength)
_GetLogicalDriveStringsW(nBufferLength, lpBuffer)
drive_strings = list()
string_p = addressof(lpBuffer)
sizeof_wchar = sizeof(ctypes.c_wchar)
while True:
string_v = ctypes.wstring_at(string_p)
if string_v == u'':
break
drive_strings.append(string_v)
string_p += (len(string_v) * sizeof_wchar) + sizeof_wchar
return drive_strings
##def GetLogicalDriveStringsA():
## _GetLogicalDriveStringsA = windll.kernel32.GetLogicalDriveStringsA
## _GetLogicalDriveStringsA.argtypes = [DWORD, LPSTR]
## _GetLogicalDriveStringsA.restype = DWORD
## _GetLogicalDriveStringsA.errcheck = RaiseIfZero
##
## nBufferLength = (4 * 26) + 1 # "X:\\\0" from A to Z plus empty string
## lpBuffer = ctypes.create_string_buffer('', nBufferLength)
## _GetLogicalDriveStringsA(nBufferLength, lpBuffer)
## result = list()
## index = 0
## while 1:
## string = list()
## while 1:
## character = lpBuffer[index]
## index = index + 1
## if character == '\0':
## break
## string.append(character)
## if not string:
## break
## result.append(''.join(string))
## return result
##
##def GetLogicalDriveStringsW():
## _GetLogicalDriveStringsW = windll.kernel32.GetLogicalDriveStringsW
## _GetLogicalDriveStringsW.argtypes = [DWORD, LPWSTR]
## _GetLogicalDriveStringsW.restype = DWORD
## _GetLogicalDriveStringsW.errcheck = RaiseIfZero
##
## nBufferLength = (4 * 26) + 1 # "X:\\\0" from A to Z plus empty string
## lpBuffer = ctypes.create_unicode_buffer(u'', nBufferLength)
## _GetLogicalDriveStringsW(nBufferLength, lpBuffer)
## result = list()
## index = 0
## while 1:
## string = list()
## while 1:
## character = lpBuffer[index]
## index = index + 1
## if character == u'\0':
## break
## string.append(character)
## if not string:
## break
## result.append(u''.join(string))
## return result
GetLogicalDriveStrings = GuessStringType(GetLogicalDriveStringsA, GetLogicalDriveStringsW)
# DWORD WINAPI QueryDosDevice(
# __in_opt LPCTSTR lpDeviceName,
# __out LPTSTR lpTargetPath,
# __in DWORD ucchMax
# );
def QueryDosDeviceA(lpDeviceName = None):
_QueryDosDeviceA = windll.kernel32.QueryDosDeviceA
_QueryDosDeviceA.argtypes = [LPSTR, LPSTR, DWORD]
_QueryDosDeviceA.restype = DWORD
_QueryDosDeviceA.errcheck = RaiseIfZero
if not lpDeviceName:
lpDeviceName = None
ucchMax = 0x1000
lpTargetPath = ctypes.create_string_buffer('', ucchMax)
_QueryDosDeviceA(lpDeviceName, lpTargetPath, ucchMax)
return lpTargetPath.value
def QueryDosDeviceW(lpDeviceName):
_QueryDosDeviceW = windll.kernel32.QueryDosDeviceW
_QueryDosDeviceW.argtypes = [LPWSTR, LPWSTR, DWORD]
_QueryDosDeviceW.restype = DWORD
_QueryDosDeviceW.errcheck = RaiseIfZero
if not lpDeviceName:
lpDeviceName = None
ucchMax = 0x1000
lpTargetPath = ctypes.create_unicode_buffer(u'', ucchMax)
_QueryDosDeviceW(lpDeviceName, lpTargetPath, ucchMax)
return lpTargetPath.value
QueryDosDevice = GuessStringType(QueryDosDeviceA, QueryDosDeviceW)
# LPVOID WINAPI MapViewOfFile(
# __in HANDLE hFileMappingObject,
# __in DWORD dwDesiredAccess,
# __in DWORD dwFileOffsetHigh,
# __in DWORD dwFileOffsetLow,
# __in SIZE_T dwNumberOfBytesToMap
# );
def MapViewOfFile(hFileMappingObject, dwDesiredAccess = FILE_MAP_ALL_ACCESS | FILE_MAP_EXECUTE, dwFileOffsetHigh = 0, dwFileOffsetLow = 0, dwNumberOfBytesToMap = 0):
_MapViewOfFile = windll.kernel32.MapViewOfFile
_MapViewOfFile.argtypes = [HANDLE, DWORD, DWORD, DWORD, SIZE_T]
_MapViewOfFile.restype = LPVOID
lpBaseAddress = _MapViewOfFile(hFileMappingObject, dwDesiredAccess, dwFileOffsetHigh, dwFileOffsetLow, dwNumberOfBytesToMap)
if lpBaseAddress == NULL:
raise ctypes.WinError()
return lpBaseAddress
# BOOL WINAPI UnmapViewOfFile(
# __in LPCVOID lpBaseAddress
# );
def UnmapViewOfFile(lpBaseAddress):
_UnmapViewOfFile = windll.kernel32.UnmapViewOfFile
_UnmapViewOfFile.argtypes = [LPVOID]
_UnmapViewOfFile.restype = bool
_UnmapViewOfFile.errcheck = RaiseIfZero
_UnmapViewOfFile(lpBaseAddress)
# HANDLE WINAPI OpenFileMapping(
# __in DWORD dwDesiredAccess,
# __in BOOL bInheritHandle,
# __in LPCTSTR lpName
# );
def OpenFileMappingA(dwDesiredAccess, bInheritHandle, lpName):
_OpenFileMappingA = windll.kernel32.OpenFileMappingA
_OpenFileMappingA.argtypes = [DWORD, BOOL, LPSTR]
_OpenFileMappingA.restype = HANDLE
_OpenFileMappingA.errcheck = RaiseIfZero
hFileMappingObject = _OpenFileMappingA(dwDesiredAccess, bool(bInheritHandle), lpName)
return FileMappingHandle(hFileMappingObject)
def OpenFileMappingW(dwDesiredAccess, bInheritHandle, lpName):
_OpenFileMappingW = windll.kernel32.OpenFileMappingW
_OpenFileMappingW.argtypes = [DWORD, BOOL, LPWSTR]
_OpenFileMappingW.restype = HANDLE
_OpenFileMappingW.errcheck = RaiseIfZero
hFileMappingObject = _OpenFileMappingW(dwDesiredAccess, bool(bInheritHandle), lpName)
return FileMappingHandle(hFileMappingObject)
OpenFileMapping = GuessStringType(OpenFileMappingA, OpenFileMappingW)
# HANDLE WINAPI CreateFileMapping(
# __in HANDLE hFile,
# __in_opt LPSECURITY_ATTRIBUTES lpAttributes,
# __in DWORD flProtect,
# __in DWORD dwMaximumSizeHigh,
# __in DWORD dwMaximumSizeLow,
# __in_opt LPCTSTR lpName
# );
def CreateFileMappingA(hFile, lpAttributes = None, flProtect = PAGE_EXECUTE_READWRITE, dwMaximumSizeHigh = 0, dwMaximumSizeLow = 0, lpName = None):
_CreateFileMappingA = windll.kernel32.CreateFileMappingA
_CreateFileMappingA.argtypes = [HANDLE, LPVOID, DWORD, DWORD, DWORD, LPSTR]
_CreateFileMappingA.restype = HANDLE
_CreateFileMappingA.errcheck = RaiseIfZero
if lpAttributes:
lpAttributes = ctypes.pointer(lpAttributes)
if not lpName:
lpName = None
hFileMappingObject = _CreateFileMappingA(hFile, lpAttributes, flProtect, dwMaximumSizeHigh, dwMaximumSizeLow, lpName)
return FileMappingHandle(hFileMappingObject)
def CreateFileMappingW(hFile, lpAttributes = None, flProtect = PAGE_EXECUTE_READWRITE, dwMaximumSizeHigh = 0, dwMaximumSizeLow = 0, lpName = None):
_CreateFileMappingW = windll.kernel32.CreateFileMappingW
_CreateFileMappingW.argtypes = [HANDLE, LPVOID, DWORD, DWORD, DWORD, LPWSTR]
_CreateFileMappingW.restype = HANDLE
_CreateFileMappingW.errcheck = RaiseIfZero
if lpAttributes:
lpAttributes = ctypes.pointer(lpAttributes)
if not lpName:
lpName = None
hFileMappingObject = _CreateFileMappingW(hFile, lpAttributes, flProtect, dwMaximumSizeHigh, dwMaximumSizeLow, lpName)
return FileMappingHandle(hFileMappingObject)
CreateFileMapping = GuessStringType(CreateFileMappingA, CreateFileMappingW)
# HANDLE WINAPI CreateFile(
# __in LPCTSTR lpFileName,
# __in DWORD dwDesiredAccess,
# __in DWORD dwShareMode,
# __in_opt LPSECURITY_ATTRIBUTES lpSecurityAttributes,
# __in DWORD dwCreationDisposition,
# __in DWORD dwFlagsAndAttributes,
# __in_opt HANDLE hTemplateFile
# );
def CreateFileA(lpFileName, dwDesiredAccess = GENERIC_ALL, dwShareMode = 0, lpSecurityAttributes = None, dwCreationDisposition = OPEN_ALWAYS, dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL, hTemplateFile = None):
_CreateFileA = windll.kernel32.CreateFileA
_CreateFileA.argtypes = [LPSTR, DWORD, DWORD, LPVOID, DWORD, DWORD, HANDLE]
_CreateFileA.restype = HANDLE
if not lpFileName:
lpFileName = None
if lpSecurityAttributes:
lpSecurityAttributes = ctypes.pointer(lpSecurityAttributes)
hFile = _CreateFileA(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile)
if hFile == INVALID_HANDLE_VALUE:
raise ctypes.WinError()
return FileHandle(hFile)
def CreateFileW(lpFileName, dwDesiredAccess = GENERIC_ALL, dwShareMode = 0, lpSecurityAttributes = None, dwCreationDisposition = OPEN_ALWAYS, dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL, hTemplateFile = None):
_CreateFileW = windll.kernel32.CreateFileW
_CreateFileW.argtypes = [LPWSTR, DWORD, DWORD, LPVOID, DWORD, DWORD, HANDLE]
_CreateFileW.restype = HANDLE
if not lpFileName:
lpFileName = None
if lpSecurityAttributes:
lpSecurityAttributes = ctypes.pointer(lpSecurityAttributes)
hFile = _CreateFileW(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile)
if hFile == INVALID_HANDLE_VALUE:
raise ctypes.WinError()
return FileHandle(hFile)
CreateFile = GuessStringType(CreateFileA, CreateFileW)
# BOOL WINAPI FlushFileBuffers(
# __in HANDLE hFile
# );
def FlushFileBuffers(hFile):
_FlushFileBuffers = windll.kernel32.FlushFileBuffers
_FlushFileBuffers.argtypes = [HANDLE]
_FlushFileBuffers.restype = bool
_FlushFileBuffers.errcheck = RaiseIfZero
_FlushFileBuffers(hFile)
# BOOL WINAPI FlushViewOfFile(
# __in LPCVOID lpBaseAddress,
# __in SIZE_T dwNumberOfBytesToFlush
# );
def FlushViewOfFile(lpBaseAddress, dwNumberOfBytesToFlush = 0):
_FlushViewOfFile = windll.kernel32.FlushViewOfFile
_FlushViewOfFile.argtypes = [LPVOID, SIZE_T]
_FlushViewOfFile.restype = bool
_FlushViewOfFile.errcheck = RaiseIfZero
_FlushViewOfFile(lpBaseAddress, dwNumberOfBytesToFlush)
# DWORD WINAPI SearchPath(
# __in_opt LPCTSTR lpPath,
# __in LPCTSTR lpFileName,
# __in_opt LPCTSTR lpExtension,
# __in DWORD nBufferLength,
# __out LPTSTR lpBuffer,
# __out_opt LPTSTR *lpFilePart
# );
def SearchPathA(lpPath, lpFileName, lpExtension):
_SearchPathA = windll.kernel32.SearchPathA
_SearchPathA.argtypes = [LPSTR, LPSTR, LPSTR, DWORD, LPSTR, POINTER(LPSTR)]
_SearchPathA.restype = DWORD
_SearchPathA.errcheck = RaiseIfZero
if not lpPath:
lpPath = None
if not lpExtension:
lpExtension = None
nBufferLength = _SearchPathA(lpPath, lpFileName, lpExtension, 0, None, None)
lpBuffer = ctypes.create_string_buffer('', nBufferLength + 1)
lpFilePart = LPSTR()
_SearchPathA(lpPath, lpFileName, lpExtension, nBufferLength, lpBuffer, byref(lpFilePart))
lpFilePart = lpFilePart.value
lpBuffer = lpBuffer.value
if lpBuffer == '':
if GetLastError() == ERROR_SUCCESS:
raise ctypes.WinError(ERROR_FILE_NOT_FOUND)
raise ctypes.WinError()
return (lpBuffer, lpFilePart)
def SearchPathW(lpPath, lpFileName, lpExtension):
_SearchPathW = windll.kernel32.SearchPathW
_SearchPathW.argtypes = [LPWSTR, LPWSTR, LPWSTR, DWORD, LPWSTR, POINTER(LPWSTR)]
_SearchPathW.restype = DWORD
_SearchPathW.errcheck = RaiseIfZero
if not lpPath:
lpPath = None
if not lpExtension:
lpExtension = None
nBufferLength = _SearchPathW(lpPath, lpFileName, lpExtension, 0, None, None)
lpBuffer = ctypes.create_unicode_buffer(u'', nBufferLength + 1)
lpFilePart = LPWSTR()
_SearchPathW(lpPath, lpFileName, lpExtension, nBufferLength, lpBuffer, byref(lpFilePart))
lpFilePart = lpFilePart.value
lpBuffer = lpBuffer.value
if lpBuffer == u'':
if GetLastError() == ERROR_SUCCESS:
raise ctypes.WinError(ERROR_FILE_NOT_FOUND)
raise ctypes.WinError()
return (lpBuffer, lpFilePart)
SearchPath = GuessStringType(SearchPathA, SearchPathW)
# BOOL SetSearchPathMode(
# __in DWORD Flags
# );
def SetSearchPathMode(Flags):
_SetSearchPathMode = windll.kernel32.SetSearchPathMode
_SetSearchPathMode.argtypes = [DWORD]
_SetSearchPathMode.restype = bool
_SetSearchPathMode.errcheck = RaiseIfZero
_SetSearchPathMode(Flags)
# BOOL WINAPI DeviceIoControl(
# __in HANDLE hDevice,
# __in DWORD dwIoControlCode,
# __in_opt LPVOID lpInBuffer,
# __in DWORD nInBufferSize,
# __out_opt LPVOID lpOutBuffer,
# __in DWORD nOutBufferSize,
# __out_opt LPDWORD lpBytesReturned,
# __inout_opt LPOVERLAPPED lpOverlapped
# );
def DeviceIoControl(hDevice, dwIoControlCode, lpInBuffer, nInBufferSize, lpOutBuffer, nOutBufferSize, lpOverlapped):
_DeviceIoControl = windll.kernel32.DeviceIoControl
_DeviceIoControl.argtypes = [HANDLE, DWORD, LPVOID, DWORD, LPVOID, DWORD, LPDWORD, LPOVERLAPPED]
_DeviceIoControl.restype = bool
_DeviceIoControl.errcheck = RaiseIfZero
if not lpInBuffer:
lpInBuffer = None
if not lpOutBuffer:
lpOutBuffer = None
if lpOverlapped:
lpOverlapped = ctypes.pointer(lpOverlapped)
lpBytesReturned = DWORD(0)
_DeviceIoControl(hDevice, dwIoControlCode, lpInBuffer, nInBufferSize, lpOutBuffer, nOutBufferSize, byref(lpBytesReturned), lpOverlapped)
return lpBytesReturned.value
# BOOL GetFileInformationByHandle(
# HANDLE hFile,
# LPBY_HANDLE_FILE_INFORMATION lpFileInformation
# );
def GetFileInformationByHandle(hFile):
_GetFileInformationByHandle = windll.kernel32.GetFileInformationByHandle
_GetFileInformationByHandle.argtypes = [HANDLE, LPBY_HANDLE_FILE_INFORMATION]
_GetFileInformationByHandle.restype = bool
_GetFileInformationByHandle.errcheck = RaiseIfZero
lpFileInformation = BY_HANDLE_FILE_INFORMATION()
_GetFileInformationByHandle(hFile, byref(lpFileInformation))
return lpFileInformation
# BOOL WINAPI GetFileInformationByHandleEx(
# __in HANDLE hFile,
# __in FILE_INFO_BY_HANDLE_CLASS FileInformationClass,
# __out LPVOID lpFileInformation,
# __in DWORD dwBufferSize
# );
def GetFileInformationByHandleEx(hFile, FileInformationClass, lpFileInformation, dwBufferSize):
_GetFileInformationByHandleEx = windll.kernel32.GetFileInformationByHandleEx
_GetFileInformationByHandleEx.argtypes = [HANDLE, DWORD, LPVOID, DWORD]
_GetFileInformationByHandleEx.restype = bool
_GetFileInformationByHandleEx.errcheck = RaiseIfZero
# XXX TODO
# support each FileInformationClass so the function can allocate the
# corresponding structure for the lpFileInformation parameter
_GetFileInformationByHandleEx(hFile, FileInformationClass, byref(lpFileInformation), dwBufferSize)
# DWORD WINAPI GetFinalPathNameByHandle(
# __in HANDLE hFile,
# __out LPTSTR lpszFilePath,
# __in DWORD cchFilePath,
# __in DWORD dwFlags
# );
def GetFinalPathNameByHandleA(hFile, dwFlags = FILE_NAME_NORMALIZED | VOLUME_NAME_DOS):
_GetFinalPathNameByHandleA = windll.kernel32.GetFinalPathNameByHandleA
_GetFinalPathNameByHandleA.argtypes = [HANDLE, LPSTR, DWORD, DWORD]
_GetFinalPathNameByHandleA.restype = DWORD
cchFilePath = _GetFinalPathNameByHandleA(hFile, None, 0, dwFlags)
if cchFilePath == 0:
raise ctypes.WinError()
lpszFilePath = ctypes.create_string_buffer('', cchFilePath + 1)
nCopied = _GetFinalPathNameByHandleA(hFile, lpszFilePath, cchFilePath, dwFlags)
if nCopied <= 0 or nCopied > cchFilePath:
raise ctypes.WinError()
return lpszFilePath.value
def GetFinalPathNameByHandleW(hFile, dwFlags = FILE_NAME_NORMALIZED | VOLUME_NAME_DOS):
_GetFinalPathNameByHandleW = windll.kernel32.GetFinalPathNameByHandleW
_GetFinalPathNameByHandleW.argtypes = [HANDLE, LPWSTR, DWORD, DWORD]
_GetFinalPathNameByHandleW.restype = DWORD
cchFilePath = _GetFinalPathNameByHandleW(hFile, None, 0, dwFlags)
if cchFilePath == 0:
raise ctypes.WinError()
lpszFilePath = ctypes.create_unicode_buffer(u'', cchFilePath + 1)
nCopied = _GetFinalPathNameByHandleW(hFile, lpszFilePath, cchFilePath, dwFlags)
if nCopied <= 0 or nCopied > cchFilePath:
raise ctypes.WinError()
return lpszFilePath.value
GetFinalPathNameByHandle = GuessStringType(GetFinalPathNameByHandleA, GetFinalPathNameByHandleW)
# DWORD GetFullPathName(
# LPCTSTR lpFileName,
# DWORD nBufferLength,
# LPTSTR lpBuffer,
# LPTSTR* lpFilePart
# );
def GetFullPathNameA(lpFileName):
_GetFullPathNameA = windll.kernel32.GetFullPathNameA
_GetFullPathNameA.argtypes = [LPSTR, DWORD, LPSTR, POINTER(LPSTR)]
_GetFullPathNameA.restype = DWORD
nBufferLength = _GetFullPathNameA(lpFileName, 0, None, None)
if nBufferLength <= 0:
raise ctypes.WinError()
lpBuffer = ctypes.create_string_buffer('', nBufferLength + 1)
lpFilePart = LPSTR()
nCopied = _GetFullPathNameA(lpFileName, nBufferLength, lpBuffer, byref(lpFilePart))
if nCopied > nBufferLength or nCopied == 0:
raise ctypes.WinError()
return lpBuffer.value, lpFilePart.value
def GetFullPathNameW(lpFileName):
_GetFullPathNameW = windll.kernel32.GetFullPathNameW
_GetFullPathNameW.argtypes = [LPWSTR, DWORD, LPWSTR, POINTER(LPWSTR)]
_GetFullPathNameW.restype = DWORD
nBufferLength = _GetFullPathNameW(lpFileName, 0, None, None)
if nBufferLength <= 0:
raise ctypes.WinError()
lpBuffer = ctypes.create_unicode_buffer(u'', nBufferLength + 1)
lpFilePart = LPWSTR()
nCopied = _GetFullPathNameW(lpFileName, nBufferLength, lpBuffer, byref(lpFilePart))
if nCopied > nBufferLength or nCopied == 0:
raise ctypes.WinError()
return lpBuffer.value, lpFilePart.value
GetFullPathName = GuessStringType(GetFullPathNameA, GetFullPathNameW)
# DWORD WINAPI GetTempPath(
# __in DWORD nBufferLength,
# __out LPTSTR lpBuffer
# );
def GetTempPathA():
_GetTempPathA = windll.kernel32.GetTempPathA
_GetTempPathA.argtypes = [DWORD, LPSTR]
_GetTempPathA.restype = DWORD
nBufferLength = _GetTempPathA(0, None)
if nBufferLength <= 0:
raise ctypes.WinError()
lpBuffer = ctypes.create_string_buffer('', nBufferLength)
nCopied = _GetTempPathA(nBufferLength, lpBuffer)
if nCopied > nBufferLength or nCopied == 0:
raise ctypes.WinError()
return lpBuffer.value
def GetTempPathW():
_GetTempPathW = windll.kernel32.GetTempPathW
_GetTempPathW.argtypes = [DWORD, LPWSTR]
_GetTempPathW.restype = DWORD
nBufferLength = _GetTempPathW(0, None)
if nBufferLength <= 0:
raise ctypes.WinError()
lpBuffer = ctypes.create_unicode_buffer(u'', nBufferLength)
nCopied = _GetTempPathW(nBufferLength, lpBuffer)
if nCopied > nBufferLength or nCopied == 0:
raise ctypes.WinError()
return lpBuffer.value
GetTempPath = GuessStringType(GetTempPathA, GetTempPathW)
# UINT WINAPI GetTempFileName(
# __in LPCTSTR lpPathName,
# __in LPCTSTR lpPrefixString,
# __in UINT uUnique,
# __out LPTSTR lpTempFileName
# );
def GetTempFileNameA(lpPathName = None, lpPrefixString = "TMP", uUnique = 0):
_GetTempFileNameA = windll.kernel32.GetTempFileNameA
_GetTempFileNameA.argtypes = [LPSTR, LPSTR, UINT, LPSTR]
_GetTempFileNameA.restype = UINT
if lpPathName is None:
lpPathName = GetTempPathA()
lpTempFileName = ctypes.create_string_buffer('', MAX_PATH)
uUnique = _GetTempFileNameA(lpPathName, lpPrefixString, uUnique, lpTempFileName)
if uUnique == 0:
raise ctypes.WinError()
return lpTempFileName.value, uUnique
def GetTempFileNameW(lpPathName = None, lpPrefixString = u"TMP", uUnique = 0):
_GetTempFileNameW = windll.kernel32.GetTempFileNameW
_GetTempFileNameW.argtypes = [LPWSTR, LPWSTR, UINT, LPWSTR]
_GetTempFileNameW.restype = UINT
if lpPathName is None:
lpPathName = GetTempPathW()
lpTempFileName = ctypes.create_unicode_buffer(u'', MAX_PATH)
uUnique = _GetTempFileNameW(lpPathName, lpPrefixString, uUnique, lpTempFileName)
if uUnique == 0:
raise ctypes.WinError()
return lpTempFileName.value, uUnique
GetTempFileName = GuessStringType(GetTempFileNameA, GetTempFileNameW)
# DWORD WINAPI GetCurrentDirectory(
# __in DWORD nBufferLength,
# __out LPTSTR lpBuffer
# );
def GetCurrentDirectoryA():
_GetCurrentDirectoryA = windll.kernel32.GetCurrentDirectoryA
_GetCurrentDirectoryA.argtypes = [DWORD, LPSTR]
_GetCurrentDirectoryA.restype = DWORD
nBufferLength = _GetCurrentDirectoryA(0, None)
if nBufferLength <= 0:
raise ctypes.WinError()
lpBuffer = ctypes.create_string_buffer('', nBufferLength)
nCopied = _GetCurrentDirectoryA(nBufferLength, lpBuffer)
if nCopied > nBufferLength or nCopied == 0:
raise ctypes.WinError()
return lpBuffer.value
def GetCurrentDirectoryW():
_GetCurrentDirectoryW = windll.kernel32.GetCurrentDirectoryW
_GetCurrentDirectoryW.argtypes = [DWORD, LPWSTR]
_GetCurrentDirectoryW.restype = DWORD
nBufferLength = _GetCurrentDirectoryW(0, None)
if nBufferLength <= 0:
raise ctypes.WinError()
lpBuffer = ctypes.create_unicode_buffer(u'', nBufferLength)
nCopied = _GetCurrentDirectoryW(nBufferLength, lpBuffer)
if nCopied > nBufferLength or nCopied == 0:
raise ctypes.WinError()
return lpBuffer.value
GetCurrentDirectory = GuessStringType(GetCurrentDirectoryA, GetCurrentDirectoryW)
#------------------------------------------------------------------------------
# Contrl-C handler
# BOOL WINAPI HandlerRoutine(
# __in DWORD dwCtrlType
# );
PHANDLER_ROUTINE = ctypes.WINFUNCTYPE(BOOL, DWORD)
# BOOL WINAPI SetConsoleCtrlHandler(
# __in_opt PHANDLER_ROUTINE HandlerRoutine,
# __in BOOL Add
# );
def SetConsoleCtrlHandler(HandlerRoutine = None, Add = True):
_SetConsoleCtrlHandler = windll.kernel32.SetConsoleCtrlHandler
_SetConsoleCtrlHandler.argtypes = [PHANDLER_ROUTINE, BOOL]
_SetConsoleCtrlHandler.restype = bool
_SetConsoleCtrlHandler.errcheck = RaiseIfZero
_SetConsoleCtrlHandler(HandlerRoutine, bool(Add))
# we can't automagically transform Python functions to PHANDLER_ROUTINE
# because a) the actual pointer value is meaningful to the API
# and b) if it gets garbage collected bad things would happen
# BOOL WINAPI GenerateConsoleCtrlEvent(
# __in DWORD dwCtrlEvent,
# __in DWORD dwProcessGroupId
# );
def GenerateConsoleCtrlEvent(dwCtrlEvent, dwProcessGroupId):
_GenerateConsoleCtrlEvent = windll.kernel32.GenerateConsoleCtrlEvent
_GenerateConsoleCtrlEvent.argtypes = [DWORD, DWORD]
_GenerateConsoleCtrlEvent.restype = bool
_GenerateConsoleCtrlEvent.errcheck = RaiseIfZero
_GenerateConsoleCtrlEvent(dwCtrlEvent, dwProcessGroupId)
#------------------------------------------------------------------------------
# Synchronization API
# XXX NOTE
#
# Instead of waiting forever, we wait for a small period of time and loop.
# This is a workaround for an unwanted behavior of psyco-accelerated code:
# you can't interrupt a blocking call using Ctrl+C, because signal processing
# is only done between C calls.
#
# Also see: bug #2793618 in Psyco project
# http://sourceforge.net/tracker/?func=detail&aid=2793618&group_id=41036&atid=429622
# DWORD WINAPI WaitForSingleObject(
# HANDLE hHandle,
# DWORD dwMilliseconds
# );
def WaitForSingleObject(hHandle, dwMilliseconds = INFINITE):
_WaitForSingleObject = windll.kernel32.WaitForSingleObject
_WaitForSingleObject.argtypes = [HANDLE, DWORD]
_WaitForSingleObject.restype = DWORD
if not dwMilliseconds and dwMilliseconds != 0:
dwMilliseconds = INFINITE
if dwMilliseconds != INFINITE:
r = _WaitForSingleObject(hHandle, dwMilliseconds)
if r == WAIT_FAILED:
raise ctypes.WinError()
else:
while 1:
r = _WaitForSingleObject(hHandle, 100)
if r == WAIT_FAILED:
raise ctypes.WinError()
if r != WAIT_TIMEOUT:
break
return r
# DWORD WINAPI WaitForSingleObjectEx(
# HANDLE hHandle,
# DWORD dwMilliseconds,
# BOOL bAlertable
# );
def WaitForSingleObjectEx(hHandle, dwMilliseconds = INFINITE, bAlertable = True):
_WaitForSingleObjectEx = windll.kernel32.WaitForSingleObjectEx
_WaitForSingleObjectEx.argtypes = [HANDLE, DWORD, BOOL]
_WaitForSingleObjectEx.restype = DWORD
if not dwMilliseconds and dwMilliseconds != 0:
dwMilliseconds = INFINITE
if dwMilliseconds != INFINITE:
r = _WaitForSingleObjectEx(hHandle, dwMilliseconds, bool(bAlertable))
if r == WAIT_FAILED:
raise ctypes.WinError()
else:
while 1:
r = _WaitForSingleObjectEx(hHandle, 100, bool(bAlertable))
if r == WAIT_FAILED:
raise ctypes.WinError()
if r != WAIT_TIMEOUT:
break
return r
# DWORD WINAPI WaitForMultipleObjects(
# DWORD nCount,
# const HANDLE *lpHandles,
# BOOL bWaitAll,
# DWORD dwMilliseconds
# );
def WaitForMultipleObjects(handles, bWaitAll = False, dwMilliseconds = INFINITE):
_WaitForMultipleObjects = windll.kernel32.WaitForMultipleObjects
_WaitForMultipleObjects.argtypes = [DWORD, POINTER(HANDLE), BOOL, DWORD]
_WaitForMultipleObjects.restype = DWORD
if not dwMilliseconds and dwMilliseconds != 0:
dwMilliseconds = INFINITE
nCount = len(handles)
lpHandlesType = HANDLE * nCount
lpHandles = lpHandlesType(*handles)
if dwMilliseconds != INFINITE:
r = _WaitForMultipleObjects(byref(lpHandles), bool(bWaitAll), dwMilliseconds)
if r == WAIT_FAILED:
raise ctypes.WinError()
else:
while 1:
r = _WaitForMultipleObjects(byref(lpHandles), bool(bWaitAll), 100)
if r == WAIT_FAILED:
raise ctypes.WinError()
if r != WAIT_TIMEOUT:
break
return r
# DWORD WINAPI WaitForMultipleObjectsEx(
# DWORD nCount,
# const HANDLE *lpHandles,
# BOOL bWaitAll,
# DWORD dwMilliseconds,
# BOOL bAlertable
# );
def WaitForMultipleObjectsEx(handles, bWaitAll = False, dwMilliseconds = INFINITE, bAlertable = True):
_WaitForMultipleObjectsEx = windll.kernel32.WaitForMultipleObjectsEx
_WaitForMultipleObjectsEx.argtypes = [DWORD, POINTER(HANDLE), BOOL, DWORD]
_WaitForMultipleObjectsEx.restype = DWORD
if not dwMilliseconds and dwMilliseconds != 0:
dwMilliseconds = INFINITE
nCount = len(handles)
lpHandlesType = HANDLE * nCount
lpHandles = lpHandlesType(*handles)
if dwMilliseconds != INFINITE:
r = _WaitForMultipleObjectsEx(byref(lpHandles), bool(bWaitAll), dwMilliseconds, bool(bAlertable))
if r == WAIT_FAILED:
raise ctypes.WinError()
else:
while 1:
r = _WaitForMultipleObjectsEx(byref(lpHandles), bool(bWaitAll), 100, bool(bAlertable))
if r == WAIT_FAILED:
raise ctypes.WinError()
if r != WAIT_TIMEOUT:
break
return r
# HANDLE WINAPI CreateMutex(
# _In_opt_ LPSECURITY_ATTRIBUTES lpMutexAttributes,
# _In_ BOOL bInitialOwner,
# _In_opt_ LPCTSTR lpName
# );
def CreateMutexA(lpMutexAttributes = None, bInitialOwner = True, lpName = None):
_CreateMutexA = windll.kernel32.CreateMutexA
_CreateMutexA.argtypes = [LPVOID, BOOL, LPSTR]
_CreateMutexA.restype = HANDLE
_CreateMutexA.errcheck = RaiseIfZero
return Handle( _CreateMutexA(lpMutexAttributes, bInitialOwner, lpName) )
def CreateMutexW(lpMutexAttributes = None, bInitialOwner = True, lpName = None):
_CreateMutexW = windll.kernel32.CreateMutexW
_CreateMutexW.argtypes = [LPVOID, BOOL, LPWSTR]
_CreateMutexW.restype = HANDLE
_CreateMutexW.errcheck = RaiseIfZero
return Handle( _CreateMutexW(lpMutexAttributes, bInitialOwner, lpName) )
CreateMutex = GuessStringType(CreateMutexA, CreateMutexW)
# HANDLE WINAPI OpenMutex(
# _In_ DWORD dwDesiredAccess,
# _In_ BOOL bInheritHandle,
# _In_ LPCTSTR lpName
# );
def OpenMutexA(dwDesiredAccess = MUTEX_ALL_ACCESS, bInitialOwner = True, lpName = None):
_OpenMutexA = windll.kernel32.OpenMutexA
_OpenMutexA.argtypes = [DWORD, BOOL, LPSTR]
_OpenMutexA.restype = HANDLE
_OpenMutexA.errcheck = RaiseIfZero
return Handle( _OpenMutexA(lpMutexAttributes, bInitialOwner, lpName) )
def OpenMutexW(dwDesiredAccess = MUTEX_ALL_ACCESS, bInitialOwner = True, lpName = None):
_OpenMutexW = windll.kernel32.OpenMutexW
_OpenMutexW.argtypes = [DWORD, BOOL, LPWSTR]
_OpenMutexW.restype = HANDLE
_OpenMutexW.errcheck = RaiseIfZero
return Handle( _OpenMutexW(lpMutexAttributes, bInitialOwner, lpName) )
OpenMutex = GuessStringType(OpenMutexA, OpenMutexW)
# HANDLE WINAPI CreateEvent(
# _In_opt_ LPSECURITY_ATTRIBUTES lpEventAttributes,
# _In_ BOOL bManualReset,
# _In_ BOOL bInitialState,
# _In_opt_ LPCTSTR lpName
# );
def CreateEventA(lpMutexAttributes = None, bManualReset = False, bInitialState = False, lpName = None):
_CreateEventA = windll.kernel32.CreateEventA
_CreateEventA.argtypes = [LPVOID, BOOL, BOOL, LPSTR]
_CreateEventA.restype = HANDLE
_CreateEventA.errcheck = RaiseIfZero
return Handle( _CreateEventA(lpMutexAttributes, bManualReset, bInitialState, lpName) )
def CreateEventW(lpMutexAttributes = None, bManualReset = False, bInitialState = False, lpName = None):
_CreateEventW = windll.kernel32.CreateEventW
_CreateEventW.argtypes = [LPVOID, BOOL, BOOL, LPWSTR]
_CreateEventW.restype = HANDLE
_CreateEventW.errcheck = RaiseIfZero
return Handle( _CreateEventW(lpMutexAttributes, bManualReset, bInitialState, lpName) )
CreateEvent = GuessStringType(CreateEventA, CreateEventW)
# HANDLE WINAPI OpenEvent(
# _In_ DWORD dwDesiredAccess,
# _In_ BOOL bInheritHandle,
# _In_ LPCTSTR lpName
# );
def OpenEventA(dwDesiredAccess = EVENT_ALL_ACCESS, bInheritHandle = False, lpName = None):
_OpenEventA = windll.kernel32.OpenEventA
_OpenEventA.argtypes = [DWORD, BOOL, LPSTR]
_OpenEventA.restype = HANDLE
_OpenEventA.errcheck = RaiseIfZero
return Handle( _OpenEventA(dwDesiredAccess, bInheritHandle, lpName) )
def OpenEventW(dwDesiredAccess = EVENT_ALL_ACCESS, bInheritHandle = False, lpName = None):
_OpenEventW = windll.kernel32.OpenEventW
_OpenEventW.argtypes = [DWORD, BOOL, LPWSTR]
_OpenEventW.restype = HANDLE
_OpenEventW.errcheck = RaiseIfZero
return Handle( _OpenEventW(dwDesiredAccess, bInheritHandle, lpName) )
OpenEvent = GuessStringType(OpenEventA, OpenEventW)
# HANDLE WINAPI CreateSemaphore(
# _In_opt_ LPSECURITY_ATTRIBUTES lpSemaphoreAttributes,
# _In_ LONG lInitialCount,
# _In_ LONG lMaximumCount,
# _In_opt_ LPCTSTR lpName
# );
# TODO
# HANDLE WINAPI OpenSemaphore(
# _In_ DWORD dwDesiredAccess,
# _In_ BOOL bInheritHandle,
# _In_ LPCTSTR lpName
# );
# TODO
# BOOL WINAPI ReleaseMutex(
# _In_ HANDLE hMutex
# );
def ReleaseMutex(hMutex):
_ReleaseMutex = windll.kernel32.ReleaseMutex
_ReleaseMutex.argtypes = [HANDLE]
_ReleaseMutex.restype = bool
_ReleaseMutex.errcheck = RaiseIfZero
_ReleaseMutex(hMutex)
# BOOL WINAPI SetEvent(
# _In_ HANDLE hEvent
# );
def SetEvent(hEvent):
_SetEvent = windll.kernel32.SetEvent
_SetEvent.argtypes = [HANDLE]
_SetEvent.restype = bool
_SetEvent.errcheck = RaiseIfZero
_SetEvent(hEvent)
# BOOL WINAPI ResetEvent(
# _In_ HANDLE hEvent
# );
def ResetEvent(hEvent):
_ResetEvent = windll.kernel32.ResetEvent
_ResetEvent.argtypes = [HANDLE]
_ResetEvent.restype = bool
_ResetEvent.errcheck = RaiseIfZero
_ResetEvent(hEvent)
# BOOL WINAPI PulseEvent(
# _In_ HANDLE hEvent
# );
def PulseEvent(hEvent):
_PulseEvent = windll.kernel32.PulseEvent
_PulseEvent.argtypes = [HANDLE]
_PulseEvent.restype = bool
_PulseEvent.errcheck = RaiseIfZero
_PulseEvent(hEvent)
# BOOL WINAPI ReleaseSemaphore(
# _In_ HANDLE hSemaphore,
# _In_ LONG lReleaseCount,
# _Out_opt_ LPLONG lpPreviousCount
# );
# TODO
#------------------------------------------------------------------------------
# Debug API
# BOOL WaitForDebugEvent(
# LPDEBUG_EVENT lpDebugEvent,
# DWORD dwMilliseconds
# );
def WaitForDebugEvent(dwMilliseconds = INFINITE):
_WaitForDebugEvent = windll.kernel32.WaitForDebugEvent
_WaitForDebugEvent.argtypes = [LPDEBUG_EVENT, DWORD]
_WaitForDebugEvent.restype = DWORD
if not dwMilliseconds and dwMilliseconds != 0:
dwMilliseconds = INFINITE
lpDebugEvent = DEBUG_EVENT()
lpDebugEvent.dwDebugEventCode = 0
lpDebugEvent.dwProcessId = 0
lpDebugEvent.dwThreadId = 0
if dwMilliseconds != INFINITE:
success = _WaitForDebugEvent(byref(lpDebugEvent), dwMilliseconds)
if success == 0:
raise ctypes.WinError()
else:
# this avoids locking the Python GIL for too long
while 1:
success = _WaitForDebugEvent(byref(lpDebugEvent), 100)
if success != 0:
break
code = GetLastError()
if code not in (ERROR_SEM_TIMEOUT, WAIT_TIMEOUT):
raise ctypes.WinError(code)
return lpDebugEvent
# BOOL ContinueDebugEvent(
# DWORD dwProcessId,
# DWORD dwThreadId,
# DWORD dwContinueStatus
# );
def ContinueDebugEvent(dwProcessId, dwThreadId, dwContinueStatus = DBG_EXCEPTION_NOT_HANDLED):
_ContinueDebugEvent = windll.kernel32.ContinueDebugEvent
_ContinueDebugEvent.argtypes = [DWORD, DWORD, DWORD]
_ContinueDebugEvent.restype = bool
_ContinueDebugEvent.errcheck = RaiseIfZero
_ContinueDebugEvent(dwProcessId, dwThreadId, dwContinueStatus)
# BOOL WINAPI FlushInstructionCache(
# __in HANDLE hProcess,
# __in LPCVOID lpBaseAddress,
# __in SIZE_T dwSize
# );
def FlushInstructionCache(hProcess, lpBaseAddress = None, dwSize = 0):
# http://blogs.msdn.com/oldnewthing/archive/2003/12/08/55954.aspx#55958
_FlushInstructionCache = windll.kernel32.FlushInstructionCache
_FlushInstructionCache.argtypes = [HANDLE, LPVOID, SIZE_T]
_FlushInstructionCache.restype = bool
_FlushInstructionCache.errcheck = RaiseIfZero
_FlushInstructionCache(hProcess, lpBaseAddress, dwSize)
# BOOL DebugActiveProcess(
# DWORD dwProcessId
# );
def DebugActiveProcess(dwProcessId):
_DebugActiveProcess = windll.kernel32.DebugActiveProcess
_DebugActiveProcess.argtypes = [DWORD]
_DebugActiveProcess.restype = bool
_DebugActiveProcess.errcheck = RaiseIfZero
_DebugActiveProcess(dwProcessId)
# BOOL DebugActiveProcessStop(
# DWORD dwProcessId
# );
def DebugActiveProcessStop(dwProcessId):
_DebugActiveProcessStop = windll.kernel32.DebugActiveProcessStop
_DebugActiveProcessStop.argtypes = [DWORD]
_DebugActiveProcessStop.restype = bool
_DebugActiveProcessStop.errcheck = RaiseIfZero
_DebugActiveProcessStop(dwProcessId)
# BOOL CheckRemoteDebuggerPresent(
# HANDLE hProcess,
# PBOOL pbDebuggerPresent
# );
def CheckRemoteDebuggerPresent(hProcess):
_CheckRemoteDebuggerPresent = windll.kernel32.CheckRemoteDebuggerPresent
_CheckRemoteDebuggerPresent.argtypes = [HANDLE, PBOOL]
_CheckRemoteDebuggerPresent.restype = bool
_CheckRemoteDebuggerPresent.errcheck = RaiseIfZero
pbDebuggerPresent = BOOL(0)
_CheckRemoteDebuggerPresent(hProcess, byref(pbDebuggerPresent))
return bool(pbDebuggerPresent.value)
# BOOL DebugSetProcessKillOnExit(
# BOOL KillOnExit
# );
def DebugSetProcessKillOnExit(KillOnExit):
_DebugSetProcessKillOnExit = windll.kernel32.DebugSetProcessKillOnExit
_DebugSetProcessKillOnExit.argtypes = [BOOL]
_DebugSetProcessKillOnExit.restype = bool
_DebugSetProcessKillOnExit.errcheck = RaiseIfZero
_DebugSetProcessKillOnExit(bool(KillOnExit))
# BOOL DebugBreakProcess(
# HANDLE Process
# );
def DebugBreakProcess(hProcess):
_DebugBreakProcess = windll.kernel32.DebugBreakProcess
_DebugBreakProcess.argtypes = [HANDLE]
_DebugBreakProcess.restype = bool
_DebugBreakProcess.errcheck = RaiseIfZero
_DebugBreakProcess(hProcess)
# void WINAPI OutputDebugString(
# __in_opt LPCTSTR lpOutputString
# );
def OutputDebugStringA(lpOutputString):
_OutputDebugStringA = windll.kernel32.OutputDebugStringA
_OutputDebugStringA.argtypes = [LPSTR]
_OutputDebugStringA.restype = None
_OutputDebugStringA(lpOutputString)
def OutputDebugStringW(lpOutputString):
_OutputDebugStringW = windll.kernel32.OutputDebugStringW
_OutputDebugStringW.argtypes = [LPWSTR]
_OutputDebugStringW.restype = None
_OutputDebugStringW(lpOutputString)
OutputDebugString = GuessStringType(OutputDebugStringA, OutputDebugStringW)
# BOOL WINAPI ReadProcessMemory(
# __in HANDLE hProcess,
# __in LPCVOID lpBaseAddress,
# __out LPVOID lpBuffer,
# __in SIZE_T nSize,
# __out SIZE_T* lpNumberOfBytesRead
# );
def ReadProcessMemory(hProcess, lpBaseAddress, nSize):
_ReadProcessMemory = windll.kernel32.ReadProcessMemory
_ReadProcessMemory.argtypes = [HANDLE, LPVOID, LPVOID, SIZE_T, POINTER(SIZE_T)]
_ReadProcessMemory.restype = bool
lpBuffer = ctypes.create_string_buffer(compat.b(''), nSize)
lpNumberOfBytesRead = SIZE_T(0)
success = _ReadProcessMemory(hProcess, lpBaseAddress, lpBuffer, nSize, byref(lpNumberOfBytesRead))
if not success and GetLastError() != ERROR_PARTIAL_COPY:
raise ctypes.WinError()
return compat.b(lpBuffer.raw)[:lpNumberOfBytesRead.value]
# BOOL WINAPI WriteProcessMemory(
# __in HANDLE hProcess,
# __in LPCVOID lpBaseAddress,
# __in LPVOID lpBuffer,
# __in SIZE_T nSize,
# __out SIZE_T* lpNumberOfBytesWritten
# );
def WriteProcessMemory(hProcess, lpBaseAddress, lpBuffer):
_WriteProcessMemory = windll.kernel32.WriteProcessMemory
_WriteProcessMemory.argtypes = [HANDLE, LPVOID, LPVOID, SIZE_T, POINTER(SIZE_T)]
_WriteProcessMemory.restype = bool
nSize = len(lpBuffer)
lpBuffer = ctypes.create_string_buffer(lpBuffer)
lpNumberOfBytesWritten = SIZE_T(0)
success = _WriteProcessMemory(hProcess, lpBaseAddress, lpBuffer, nSize, byref(lpNumberOfBytesWritten))
if not success and GetLastError() != ERROR_PARTIAL_COPY:
raise ctypes.WinError()
return lpNumberOfBytesWritten.value
# LPVOID WINAPI VirtualAllocEx(
# __in HANDLE hProcess,
# __in_opt LPVOID lpAddress,
# __in SIZE_T dwSize,
# __in DWORD flAllocationType,
# __in DWORD flProtect
# );
def VirtualAllocEx(hProcess, lpAddress = 0, dwSize = 0x1000, flAllocationType = MEM_COMMIT | MEM_RESERVE, flProtect = PAGE_EXECUTE_READWRITE):
_VirtualAllocEx = windll.kernel32.VirtualAllocEx
_VirtualAllocEx.argtypes = [HANDLE, LPVOID, SIZE_T, DWORD, DWORD]
_VirtualAllocEx.restype = LPVOID
lpAddress = _VirtualAllocEx(hProcess, lpAddress, dwSize, flAllocationType, flProtect)
if lpAddress == NULL:
raise ctypes.WinError()
return lpAddress
# SIZE_T WINAPI VirtualQueryEx(
# __in HANDLE hProcess,
# __in_opt LPCVOID lpAddress,
# __out PMEMORY_BASIC_INFORMATION lpBuffer,
# __in SIZE_T dwLength
# );
def VirtualQueryEx(hProcess, lpAddress):
_VirtualQueryEx = windll.kernel32.VirtualQueryEx
_VirtualQueryEx.argtypes = [HANDLE, LPVOID, PMEMORY_BASIC_INFORMATION, SIZE_T]
_VirtualQueryEx.restype = SIZE_T
lpBuffer = MEMORY_BASIC_INFORMATION()
dwLength = sizeof(MEMORY_BASIC_INFORMATION)
success = _VirtualQueryEx(hProcess, lpAddress, byref(lpBuffer), dwLength)
if success == 0:
raise ctypes.WinError()
return MemoryBasicInformation(lpBuffer)
# BOOL WINAPI VirtualProtectEx(
# __in HANDLE hProcess,
# __in LPVOID lpAddress,
# __in SIZE_T dwSize,
# __in DWORD flNewProtect,
# __out PDWORD lpflOldProtect
# );
def VirtualProtectEx(hProcess, lpAddress, dwSize, flNewProtect = PAGE_EXECUTE_READWRITE):
_VirtualProtectEx = windll.kernel32.VirtualProtectEx
_VirtualProtectEx.argtypes = [HANDLE, LPVOID, SIZE_T, DWORD, PDWORD]
_VirtualProtectEx.restype = bool
_VirtualProtectEx.errcheck = RaiseIfZero
flOldProtect = DWORD(0)
_VirtualProtectEx(hProcess, lpAddress, dwSize, flNewProtect, byref(flOldProtect))
return flOldProtect.value
# BOOL WINAPI VirtualFreeEx(
# __in HANDLE hProcess,
# __in LPVOID lpAddress,
# __in SIZE_T dwSize,
# __in DWORD dwFreeType
# );
def VirtualFreeEx(hProcess, lpAddress, dwSize = 0, dwFreeType = MEM_RELEASE):
_VirtualFreeEx = windll.kernel32.VirtualFreeEx
_VirtualFreeEx.argtypes = [HANDLE, LPVOID, SIZE_T, DWORD]
_VirtualFreeEx.restype = bool
_VirtualFreeEx.errcheck = RaiseIfZero
_VirtualFreeEx(hProcess, lpAddress, dwSize, dwFreeType)
# HANDLE WINAPI CreateRemoteThread(
# __in HANDLE hProcess,
# __in LPSECURITY_ATTRIBUTES lpThreadAttributes,
# __in SIZE_T dwStackSize,
# __in LPTHREAD_START_ROUTINE lpStartAddress,
# __in LPVOID lpParameter,
# __in DWORD dwCreationFlags,
# __out LPDWORD lpThreadId
# );
def CreateRemoteThread(hProcess, lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags):
_CreateRemoteThread = windll.kernel32.CreateRemoteThread
_CreateRemoteThread.argtypes = [HANDLE, LPSECURITY_ATTRIBUTES, SIZE_T, LPVOID, LPVOID, DWORD, LPDWORD]
_CreateRemoteThread.restype = HANDLE
if not lpThreadAttributes:
lpThreadAttributes = None
else:
lpThreadAttributes = byref(lpThreadAttributes)
dwThreadId = DWORD(0)
hThread = _CreateRemoteThread(hProcess, lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags, byref(dwThreadId))
if not hThread:
raise ctypes.WinError()
return ThreadHandle(hThread), dwThreadId.value
#------------------------------------------------------------------------------
# Process API
# BOOL WINAPI CreateProcess(
# __in_opt LPCTSTR lpApplicationName,
# __inout_opt LPTSTR lpCommandLine,
# __in_opt LPSECURITY_ATTRIBUTES lpProcessAttributes,
# __in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes,
# __in BOOL bInheritHandles,
# __in DWORD dwCreationFlags,
# __in_opt LPVOID lpEnvironment,
# __in_opt LPCTSTR lpCurrentDirectory,
# __in LPSTARTUPINFO lpStartupInfo,
# __out LPPROCESS_INFORMATION lpProcessInformation
# );
def CreateProcessA(lpApplicationName, lpCommandLine=None, lpProcessAttributes=None, lpThreadAttributes=None, bInheritHandles=False, dwCreationFlags=0, lpEnvironment=None, lpCurrentDirectory=None, lpStartupInfo=None):
_CreateProcessA = windll.kernel32.CreateProcessA
_CreateProcessA.argtypes = [LPSTR, LPSTR, LPSECURITY_ATTRIBUTES, LPSECURITY_ATTRIBUTES, BOOL, DWORD, LPVOID, LPSTR, LPVOID, LPPROCESS_INFORMATION]
_CreateProcessA.restype = bool
_CreateProcessA.errcheck = RaiseIfZero
if not lpApplicationName:
lpApplicationName = None
if not lpCommandLine:
lpCommandLine = None
else:
lpCommandLine = ctypes.create_string_buffer(lpCommandLine, max(MAX_PATH, len(lpCommandLine)))
if not lpEnvironment:
lpEnvironment = None
else:
lpEnvironment = ctypes.create_string_buffer(lpEnvironment)
if not lpCurrentDirectory:
lpCurrentDirectory = None
if not lpProcessAttributes:
lpProcessAttributes = None
else:
lpProcessAttributes = byref(lpProcessAttributes)
if not lpThreadAttributes:
lpThreadAttributes = None
else:
lpThreadAttributes = byref(lpThreadAttributes)
if not lpStartupInfo:
lpStartupInfo = STARTUPINFO()
lpStartupInfo.cb = sizeof(STARTUPINFO)
lpStartupInfo.lpReserved = 0
lpStartupInfo.lpDesktop = 0
lpStartupInfo.lpTitle = 0
lpStartupInfo.dwFlags = 0
lpStartupInfo.cbReserved2 = 0
lpStartupInfo.lpReserved2 = 0
lpProcessInformation = PROCESS_INFORMATION()
lpProcessInformation.hProcess = INVALID_HANDLE_VALUE
lpProcessInformation.hThread = INVALID_HANDLE_VALUE
lpProcessInformation.dwProcessId = 0
lpProcessInformation.dwThreadId = 0
_CreateProcessA(lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bool(bInheritHandles), dwCreationFlags, lpEnvironment, lpCurrentDirectory, byref(lpStartupInfo), byref(lpProcessInformation))
return ProcessInformation(lpProcessInformation)
def CreateProcessW(lpApplicationName, lpCommandLine=None, lpProcessAttributes=None, lpThreadAttributes=None, bInheritHandles=False, dwCreationFlags=0, lpEnvironment=None, lpCurrentDirectory=None, lpStartupInfo=None):
_CreateProcessW = windll.kernel32.CreateProcessW
_CreateProcessW.argtypes = [LPWSTR, LPWSTR, LPSECURITY_ATTRIBUTES, LPSECURITY_ATTRIBUTES, BOOL, DWORD, LPVOID, LPWSTR, LPVOID, LPPROCESS_INFORMATION]
_CreateProcessW.restype = bool
_CreateProcessW.errcheck = RaiseIfZero
if not lpApplicationName:
lpApplicationName = None
if not lpCommandLine:
lpCommandLine = None
else:
lpCommandLine = ctypes.create_unicode_buffer(lpCommandLine, max(MAX_PATH, len(lpCommandLine)))
if not lpEnvironment:
lpEnvironment = None
else:
lpEnvironment = ctypes.create_unicode_buffer(lpEnvironment)
if not lpCurrentDirectory:
lpCurrentDirectory = None
if not lpProcessAttributes:
lpProcessAttributes = None
else:
lpProcessAttributes = byref(lpProcessAttributes)
if not lpThreadAttributes:
lpThreadAttributes = None
else:
lpThreadAttributes = byref(lpThreadAttributes)
if not lpStartupInfo:
lpStartupInfo = STARTUPINFO()
lpStartupInfo.cb = sizeof(STARTUPINFO)
lpStartupInfo.lpReserved = 0
lpStartupInfo.lpDesktop = 0
lpStartupInfo.lpTitle = 0
lpStartupInfo.dwFlags = 0
lpStartupInfo.cbReserved2 = 0
lpStartupInfo.lpReserved2 = 0
lpProcessInformation = PROCESS_INFORMATION()
lpProcessInformation.hProcess = INVALID_HANDLE_VALUE
lpProcessInformation.hThread = INVALID_HANDLE_VALUE
lpProcessInformation.dwProcessId = 0
lpProcessInformation.dwThreadId = 0
_CreateProcessW(lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bool(bInheritHandles), dwCreationFlags, lpEnvironment, lpCurrentDirectory, byref(lpStartupInfo), byref(lpProcessInformation))
return ProcessInformation(lpProcessInformation)
CreateProcess = GuessStringType(CreateProcessA, CreateProcessW)
# BOOL WINAPI InitializeProcThreadAttributeList(
# __out_opt LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList,
# __in DWORD dwAttributeCount,
# __reserved DWORD dwFlags,
# __inout PSIZE_T lpSize
# );
def InitializeProcThreadAttributeList(dwAttributeCount):
_InitializeProcThreadAttributeList = windll.kernel32.InitializeProcThreadAttributeList
_InitializeProcThreadAttributeList.argtypes = [LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T]
_InitializeProcThreadAttributeList.restype = bool
Size = SIZE_T(0)
_InitializeProcThreadAttributeList(None, dwAttributeCount, 0, byref(Size))
RaiseIfZero(Size.value)
AttributeList = (BYTE * Size.value)()
success = _InitializeProcThreadAttributeList(byref(AttributeList), dwAttributeCount, 0, byref(Size))
RaiseIfZero(success)
return AttributeList
# BOOL WINAPI UpdateProcThreadAttribute(
# __inout LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList,
# __in DWORD dwFlags,
# __in DWORD_PTR Attribute,
# __in PVOID lpValue,
# __in SIZE_T cbSize,
# __out_opt PVOID lpPreviousValue,
# __in_opt PSIZE_T lpReturnSize
# );
def UpdateProcThreadAttribute(lpAttributeList, Attribute, Value, cbSize = None):
_UpdateProcThreadAttribute = windll.kernel32.UpdateProcThreadAttribute
_UpdateProcThreadAttribute.argtypes = [LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T]
_UpdateProcThreadAttribute.restype = bool
_UpdateProcThreadAttribute.errcheck = RaiseIfZero
if cbSize is None:
cbSize = sizeof(Value)
_UpdateProcThreadAttribute(byref(lpAttributeList), 0, Attribute, byref(Value), cbSize, None, None)
# VOID WINAPI DeleteProcThreadAttributeList(
# __inout LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList
# );
def DeleteProcThreadAttributeList(lpAttributeList):
_DeleteProcThreadAttributeList = windll.kernel32.DeleteProcThreadAttributeList
_DeleteProcThreadAttributeList.restype = None
_DeleteProcThreadAttributeList(byref(lpAttributeList))
# HANDLE WINAPI OpenProcess(
# __in DWORD dwDesiredAccess,
# __in BOOL bInheritHandle,
# __in DWORD dwProcessId
# );
def OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId):
_OpenProcess = windll.kernel32.OpenProcess
_OpenProcess.argtypes = [DWORD, BOOL, DWORD]
_OpenProcess.restype = HANDLE
hProcess = _OpenProcess(dwDesiredAccess, bool(bInheritHandle), dwProcessId)
if hProcess == NULL:
raise ctypes.WinError()
return ProcessHandle(hProcess, dwAccess = dwDesiredAccess)
# HANDLE WINAPI OpenThread(
# __in DWORD dwDesiredAccess,
# __in BOOL bInheritHandle,
# __in DWORD dwThreadId
# );
def OpenThread(dwDesiredAccess, bInheritHandle, dwThreadId):
_OpenThread = windll.kernel32.OpenThread
_OpenThread.argtypes = [DWORD, BOOL, DWORD]
_OpenThread.restype = HANDLE
hThread = _OpenThread(dwDesiredAccess, bool(bInheritHandle), dwThreadId)
if hThread == NULL:
raise ctypes.WinError()
return ThreadHandle(hThread, dwAccess = dwDesiredAccess)
# DWORD WINAPI SuspendThread(
# __in HANDLE hThread
# );
def SuspendThread(hThread):
_SuspendThread = windll.kernel32.SuspendThread
_SuspendThread.argtypes = [HANDLE]
_SuspendThread.restype = DWORD
previousCount = _SuspendThread(hThread)
if previousCount == DWORD(-1).value:
raise ctypes.WinError()
return previousCount
# DWORD WINAPI ResumeThread(
# __in HANDLE hThread
# );
def ResumeThread(hThread):
_ResumeThread = windll.kernel32.ResumeThread
_ResumeThread.argtypes = [HANDLE]
_ResumeThread.restype = DWORD
previousCount = _ResumeThread(hThread)
if previousCount == DWORD(-1).value:
raise ctypes.WinError()
return previousCount
# BOOL WINAPI TerminateThread(
# __inout HANDLE hThread,
# __in DWORD dwExitCode
# );
def TerminateThread(hThread, dwExitCode = 0):
_TerminateThread = windll.kernel32.TerminateThread
_TerminateThread.argtypes = [HANDLE, DWORD]
_TerminateThread.restype = bool
_TerminateThread.errcheck = RaiseIfZero
_TerminateThread(hThread, dwExitCode)
# BOOL WINAPI TerminateProcess(
# __inout HANDLE hProcess,
# __in DWORD dwExitCode
# );
def TerminateProcess(hProcess, dwExitCode = 0):
_TerminateProcess = windll.kernel32.TerminateProcess
_TerminateProcess.argtypes = [HANDLE, DWORD]
_TerminateProcess.restype = bool
_TerminateProcess.errcheck = RaiseIfZero
_TerminateProcess(hProcess, dwExitCode)
# DWORD WINAPI GetCurrentProcessId(void);
def GetCurrentProcessId():
_GetCurrentProcessId = windll.kernel32.GetCurrentProcessId
_GetCurrentProcessId.argtypes = []
_GetCurrentProcessId.restype = DWORD
return _GetCurrentProcessId()
# DWORD WINAPI GetCurrentThreadId(void);
def GetCurrentThreadId():
_GetCurrentThreadId = windll.kernel32.GetCurrentThreadId
_GetCurrentThreadId.argtypes = []
_GetCurrentThreadId.restype = DWORD
return _GetCurrentThreadId()
# DWORD WINAPI GetProcessId(
# __in HANDLE hProcess
# );
def GetProcessId(hProcess):
_GetProcessId = windll.kernel32.GetProcessId
_GetProcessId.argtypes = [HANDLE]
_GetProcessId.restype = DWORD
_GetProcessId.errcheck = RaiseIfZero
return _GetProcessId(hProcess)
# DWORD WINAPI GetThreadId(
# __in HANDLE hThread
# );
def GetThreadId(hThread):
_GetThreadId = windll.kernel32._GetThreadId
_GetThreadId.argtypes = [HANDLE]
_GetThreadId.restype = DWORD
dwThreadId = _GetThreadId(hThread)
if dwThreadId == 0:
raise ctypes.WinError()
return dwThreadId
# DWORD WINAPI GetProcessIdOfThread(
# __in HANDLE hThread
# );
def GetProcessIdOfThread(hThread):
_GetProcessIdOfThread = windll.kernel32.GetProcessIdOfThread
_GetProcessIdOfThread.argtypes = [HANDLE]
_GetProcessIdOfThread.restype = DWORD
dwProcessId = _GetProcessIdOfThread(hThread)
if dwProcessId == 0:
raise ctypes.WinError()
return dwProcessId
# BOOL WINAPI GetExitCodeProcess(
# __in HANDLE hProcess,
# __out LPDWORD lpExitCode
# );
def GetExitCodeProcess(hProcess):
_GetExitCodeProcess = windll.kernel32.GetExitCodeProcess
_GetExitCodeProcess.argtypes = [HANDLE]
_GetExitCodeProcess.restype = bool
_GetExitCodeProcess.errcheck = RaiseIfZero
lpExitCode = DWORD(0)
_GetExitCodeProcess(hProcess, byref(lpExitCode))
return lpExitCode.value
# BOOL WINAPI GetExitCodeThread(
# __in HANDLE hThread,
# __out LPDWORD lpExitCode
# );
def GetExitCodeThread(hThread):
_GetExitCodeThread = windll.kernel32.GetExitCodeThread
_GetExitCodeThread.argtypes = [HANDLE]
_GetExitCodeThread.restype = bool
_GetExitCodeThread.errcheck = RaiseIfZero
lpExitCode = DWORD(0)
_GetExitCodeThread(hThread, byref(lpExitCode))
return lpExitCode.value
# DWORD WINAPI GetProcessVersion(
# __in DWORD ProcessId
# );
def GetProcessVersion(ProcessId):
_GetProcessVersion = windll.kernel32.GetProcessVersion
_GetProcessVersion.argtypes = [DWORD]
_GetProcessVersion.restype = DWORD
retval = _GetProcessVersion(ProcessId)
if retval == 0:
raise ctypes.WinError()
return retval
# DWORD WINAPI GetPriorityClass(
# __in HANDLE hProcess
# );
def GetPriorityClass(hProcess):
_GetPriorityClass = windll.kernel32.GetPriorityClass
_GetPriorityClass.argtypes = [HANDLE]
_GetPriorityClass.restype = DWORD
retval = _GetPriorityClass(hProcess)
if retval == 0:
raise ctypes.WinError()
return retval
# BOOL WINAPI SetPriorityClass(
# __in HANDLE hProcess,
# __in DWORD dwPriorityClass
# );
def SetPriorityClass(hProcess, dwPriorityClass = NORMAL_PRIORITY_CLASS):
_SetPriorityClass = windll.kernel32.SetPriorityClass
_SetPriorityClass.argtypes = [HANDLE, DWORD]
_SetPriorityClass.restype = bool
_SetPriorityClass.errcheck = RaiseIfZero
_SetPriorityClass(hProcess, dwPriorityClass)
# BOOL WINAPI GetProcessPriorityBoost(
# __in HANDLE hProcess,
# __out PBOOL pDisablePriorityBoost
# );
def GetProcessPriorityBoost(hProcess):
_GetProcessPriorityBoost = windll.kernel32.GetProcessPriorityBoost
_GetProcessPriorityBoost.argtypes = [HANDLE, PBOOL]
_GetProcessPriorityBoost.restype = bool
_GetProcessPriorityBoost.errcheck = RaiseIfZero
pDisablePriorityBoost = BOOL(False)
_GetProcessPriorityBoost(hProcess, byref(pDisablePriorityBoost))
return bool(pDisablePriorityBoost.value)
# BOOL WINAPI SetProcessPriorityBoost(
# __in HANDLE hProcess,
# __in BOOL DisablePriorityBoost
# );
def SetProcessPriorityBoost(hProcess, DisablePriorityBoost):
_SetProcessPriorityBoost = windll.kernel32.SetProcessPriorityBoost
_SetProcessPriorityBoost.argtypes = [HANDLE, BOOL]
_SetProcessPriorityBoost.restype = bool
_SetProcessPriorityBoost.errcheck = RaiseIfZero
_SetProcessPriorityBoost(hProcess, bool(DisablePriorityBoost))
# BOOL WINAPI GetProcessAffinityMask(
# __in HANDLE hProcess,
# __out PDWORD_PTR lpProcessAffinityMask,
# __out PDWORD_PTR lpSystemAffinityMask
# );
def GetProcessAffinityMask(hProcess):
_GetProcessAffinityMask = windll.kernel32.GetProcessAffinityMask
_GetProcessAffinityMask.argtypes = [HANDLE, PDWORD_PTR, PDWORD_PTR]
_GetProcessAffinityMask.restype = bool
_GetProcessAffinityMask.errcheck = RaiseIfZero
lpProcessAffinityMask = DWORD_PTR(0)
lpSystemAffinityMask = DWORD_PTR(0)
_GetProcessAffinityMask(hProcess, byref(lpProcessAffinityMask), byref(lpSystemAffinityMask))
return lpProcessAffinityMask.value, lpSystemAffinityMask.value
# BOOL WINAPI SetProcessAffinityMask(
# __in HANDLE hProcess,
# __in DWORD_PTR dwProcessAffinityMask
# );
def SetProcessAffinityMask(hProcess, dwProcessAffinityMask):
_SetProcessAffinityMask = windll.kernel32.SetProcessAffinityMask
_SetProcessAffinityMask.argtypes = [HANDLE, DWORD_PTR]
_SetProcessAffinityMask.restype = bool
_SetProcessAffinityMask.errcheck = RaiseIfZero
_SetProcessAffinityMask(hProcess, dwProcessAffinityMask)
#------------------------------------------------------------------------------
# Toolhelp32 API
# HANDLE WINAPI CreateToolhelp32Snapshot(
# __in DWORD dwFlags,
# __in DWORD th32ProcessID
# );
def CreateToolhelp32Snapshot(dwFlags = TH32CS_SNAPALL, th32ProcessID = 0):
_CreateToolhelp32Snapshot = windll.kernel32.CreateToolhelp32Snapshot
_CreateToolhelp32Snapshot.argtypes = [DWORD, DWORD]
_CreateToolhelp32Snapshot.restype = HANDLE
hSnapshot = _CreateToolhelp32Snapshot(dwFlags, th32ProcessID)
if hSnapshot == INVALID_HANDLE_VALUE:
raise ctypes.WinError()
return SnapshotHandle(hSnapshot)
# BOOL WINAPI Process32First(
# __in HANDLE hSnapshot,
# __inout LPPROCESSENTRY32 lppe
# );
def Process32First(hSnapshot):
_Process32First = windll.kernel32.Process32First
_Process32First.argtypes = [HANDLE, LPPROCESSENTRY32]
_Process32First.restype = bool
pe = PROCESSENTRY32()
pe.dwSize = sizeof(PROCESSENTRY32)
success = _Process32First(hSnapshot, byref(pe))
if not success:
if GetLastError() == ERROR_NO_MORE_FILES:
return None
raise ctypes.WinError()
return pe
# BOOL WINAPI Process32Next(
# __in HANDLE hSnapshot,
# __out LPPROCESSENTRY32 lppe
# );
def Process32Next(hSnapshot, pe = None):
_Process32Next = windll.kernel32.Process32Next
_Process32Next.argtypes = [HANDLE, LPPROCESSENTRY32]
_Process32Next.restype = bool
if pe is None:
pe = PROCESSENTRY32()
pe.dwSize = sizeof(PROCESSENTRY32)
success = _Process32Next(hSnapshot, byref(pe))
if not success:
if GetLastError() == ERROR_NO_MORE_FILES:
return None
raise ctypes.WinError()
return pe
# BOOL WINAPI Thread32First(
# __in HANDLE hSnapshot,
# __inout LPTHREADENTRY32 lpte
# );
def Thread32First(hSnapshot):
_Thread32First = windll.kernel32.Thread32First
_Thread32First.argtypes = [HANDLE, LPTHREADENTRY32]
_Thread32First.restype = bool
te = THREADENTRY32()
te.dwSize = sizeof(THREADENTRY32)
success = _Thread32First(hSnapshot, byref(te))
if not success:
if GetLastError() == ERROR_NO_MORE_FILES:
return None
raise ctypes.WinError()
return te
# BOOL WINAPI Thread32Next(
# __in HANDLE hSnapshot,
# __out LPTHREADENTRY32 lpte
# );
def Thread32Next(hSnapshot, te = None):
_Thread32Next = windll.kernel32.Thread32Next
_Thread32Next.argtypes = [HANDLE, LPTHREADENTRY32]
_Thread32Next.restype = bool
if te is None:
te = THREADENTRY32()
te.dwSize = sizeof(THREADENTRY32)
success = _Thread32Next(hSnapshot, byref(te))
if not success:
if GetLastError() == ERROR_NO_MORE_FILES:
return None
raise ctypes.WinError()
return te
# BOOL WINAPI Module32First(
# __in HANDLE hSnapshot,
# __inout LPMODULEENTRY32 lpme
# );
def Module32First(hSnapshot):
_Module32First = windll.kernel32.Module32First
_Module32First.argtypes = [HANDLE, LPMODULEENTRY32]
_Module32First.restype = bool
me = MODULEENTRY32()
me.dwSize = sizeof(MODULEENTRY32)
success = _Module32First(hSnapshot, byref(me))
if not success:
if GetLastError() == ERROR_NO_MORE_FILES:
return None
raise ctypes.WinError()
return me
# BOOL WINAPI Module32Next(
# __in HANDLE hSnapshot,
# __out LPMODULEENTRY32 lpme
# );
def Module32Next(hSnapshot, me = None):
_Module32Next = windll.kernel32.Module32Next
_Module32Next.argtypes = [HANDLE, LPMODULEENTRY32]
_Module32Next.restype = bool
if me is None:
me = MODULEENTRY32()
me.dwSize = sizeof(MODULEENTRY32)
success = _Module32Next(hSnapshot, byref(me))
if not success:
if GetLastError() == ERROR_NO_MORE_FILES:
return None
raise ctypes.WinError()
return me
# BOOL WINAPI Heap32First(
# __inout LPHEAPENTRY32 lphe,
# __in DWORD th32ProcessID,
# __in ULONG_PTR th32HeapID
# );
def Heap32First(th32ProcessID, th32HeapID):
_Heap32First = windll.kernel32.Heap32First
_Heap32First.argtypes = [LPHEAPENTRY32, DWORD, ULONG_PTR]
_Heap32First.restype = bool
he = HEAPENTRY32()
he.dwSize = sizeof(HEAPENTRY32)
success = _Heap32First(byref(he), th32ProcessID, th32HeapID)
if not success:
if GetLastError() == ERROR_NO_MORE_FILES:
return None
raise ctypes.WinError()
return he
# BOOL WINAPI Heap32Next(
# __out LPHEAPENTRY32 lphe
# );
def Heap32Next(he):
_Heap32Next = windll.kernel32.Heap32Next
_Heap32Next.argtypes = [LPHEAPENTRY32]
_Heap32Next.restype = bool
he.dwSize = sizeof(HEAPENTRY32)
success = _Heap32Next(byref(he))
if not success:
if GetLastError() == ERROR_NO_MORE_FILES:
return None
raise ctypes.WinError()
return he
# BOOL WINAPI Heap32ListFirst(
# __in HANDLE hSnapshot,
# __inout LPHEAPLIST32 lphl
# );
def Heap32ListFirst(hSnapshot):
_Heap32ListFirst = windll.kernel32.Heap32ListFirst
_Heap32ListFirst.argtypes = [HANDLE, LPHEAPLIST32]
_Heap32ListFirst.restype = bool
hl = HEAPLIST32()
hl.dwSize = sizeof(HEAPLIST32)
success = _Heap32ListFirst(hSnapshot, byref(hl))
if not success:
if GetLastError() == ERROR_NO_MORE_FILES:
return None
raise ctypes.WinError()
return hl
# BOOL WINAPI Heap32ListNext(
# __in HANDLE hSnapshot,
# __out LPHEAPLIST32 lphl
# );
def Heap32ListNext(hSnapshot, hl = None):
_Heap32ListNext = windll.kernel32.Heap32ListNext
_Heap32ListNext.argtypes = [HANDLE, LPHEAPLIST32]
_Heap32ListNext.restype = bool
if hl is None:
hl = HEAPLIST32()
hl.dwSize = sizeof(HEAPLIST32)
success = _Heap32ListNext(hSnapshot, byref(hl))
if not success:
if GetLastError() == ERROR_NO_MORE_FILES:
return None
raise ctypes.WinError()
return hl
# BOOL WINAPI Toolhelp32ReadProcessMemory(
# __in DWORD th32ProcessID,
# __in LPCVOID lpBaseAddress,
# __out LPVOID lpBuffer,
# __in SIZE_T cbRead,
# __out SIZE_T lpNumberOfBytesRead
# );
def Toolhelp32ReadProcessMemory(th32ProcessID, lpBaseAddress, cbRead):
_Toolhelp32ReadProcessMemory = windll.kernel32.Toolhelp32ReadProcessMemory
_Toolhelp32ReadProcessMemory.argtypes = [DWORD, LPVOID, LPVOID, SIZE_T, POINTER(SIZE_T)]
_Toolhelp32ReadProcessMemory.restype = bool
lpBuffer = ctypes.create_string_buffer('', cbRead)
lpNumberOfBytesRead = SIZE_T(0)
success = _Toolhelp32ReadProcessMemory(th32ProcessID, lpBaseAddress, lpBuffer, cbRead, byref(lpNumberOfBytesRead))
if not success and GetLastError() != ERROR_PARTIAL_COPY:
raise ctypes.WinError()
return str(lpBuffer.raw)[:lpNumberOfBytesRead.value]
#------------------------------------------------------------------------------
# Miscellaneous system information
# BOOL WINAPI GetProcessDEPPolicy(
# __in HANDLE hProcess,
# __out LPDWORD lpFlags,
# __out PBOOL lpPermanent
# );
# Contribution by ivanlef0u (http://ivanlef0u.fr/)
# XP SP3 and > only
def GetProcessDEPPolicy(hProcess):
_GetProcessDEPPolicy = windll.kernel32.GetProcessDEPPolicy
_GetProcessDEPPolicy.argtypes = [HANDLE, LPDWORD, PBOOL]
_GetProcessDEPPolicy.restype = bool
_GetProcessDEPPolicy.errcheck = RaiseIfZero
lpFlags = DWORD(0)
lpPermanent = BOOL(0)
_GetProcessDEPPolicy(hProcess, byref(lpFlags), byref(lpPermanent))
return (lpFlags.value, lpPermanent.value)
# DWORD WINAPI GetCurrentProcessorNumber(void);
def GetCurrentProcessorNumber():
_GetCurrentProcessorNumber = windll.kernel32.GetCurrentProcessorNumber
_GetCurrentProcessorNumber.argtypes = []
_GetCurrentProcessorNumber.restype = DWORD
_GetCurrentProcessorNumber.errcheck = RaiseIfZero
return _GetCurrentProcessorNumber()
# VOID WINAPI FlushProcessWriteBuffers(void);
def FlushProcessWriteBuffers():
_FlushProcessWriteBuffers = windll.kernel32.FlushProcessWriteBuffers
_FlushProcessWriteBuffers.argtypes = []
_FlushProcessWriteBuffers.restype = None
_FlushProcessWriteBuffers()
# BOOL WINAPI GetLogicalProcessorInformation(
# __out PSYSTEM_LOGICAL_PROCESSOR_INFORMATION Buffer,
# __inout PDWORD ReturnLength
# );
# TO DO http://msdn.microsoft.com/en-us/library/ms683194(VS.85).aspx
# BOOL WINAPI GetProcessIoCounters(
# __in HANDLE hProcess,
# __out PIO_COUNTERS lpIoCounters
# );
# TO DO http://msdn.microsoft.com/en-us/library/ms683218(VS.85).aspx
# DWORD WINAPI GetGuiResources(
# __in HANDLE hProcess,
# __in DWORD uiFlags
# );
def GetGuiResources(hProcess, uiFlags = GR_GDIOBJECTS):
_GetGuiResources = windll.kernel32.GetGuiResources
_GetGuiResources.argtypes = [HANDLE, DWORD]
_GetGuiResources.restype = DWORD
dwCount = _GetGuiResources(hProcess, uiFlags)
if dwCount == 0:
errcode = GetLastError()
if errcode != ERROR_SUCCESS:
raise ctypes.WinError(errcode)
return dwCount
# BOOL WINAPI GetProcessHandleCount(
# __in HANDLE hProcess,
# __inout PDWORD pdwHandleCount
# );
def GetProcessHandleCount(hProcess):
_GetProcessHandleCount = windll.kernel32.GetProcessHandleCount
_GetProcessHandleCount.argtypes = [HANDLE, PDWORD]
_GetProcessHandleCount.restype = DWORD
_GetProcessHandleCount.errcheck = RaiseIfZero
pdwHandleCount = DWORD(0)
_GetProcessHandleCount(hProcess, byref(pdwHandleCount))
return pdwHandleCount.value
# BOOL WINAPI GetProcessTimes(
# __in HANDLE hProcess,
# __out LPFILETIME lpCreationTime,
# __out LPFILETIME lpExitTime,
# __out LPFILETIME lpKernelTime,
# __out LPFILETIME lpUserTime
# );
def GetProcessTimes(hProcess = None):
_GetProcessTimes = windll.kernel32.GetProcessTimes
_GetProcessTimes.argtypes = [HANDLE, LPFILETIME, LPFILETIME, LPFILETIME, LPFILETIME]
_GetProcessTimes.restype = bool
_GetProcessTimes.errcheck = RaiseIfZero
if hProcess is None:
hProcess = GetCurrentProcess()
CreationTime = FILETIME()
ExitTime = FILETIME()
KernelTime = FILETIME()
UserTime = FILETIME()
_GetProcessTimes(hProcess, byref(CreationTime), byref(ExitTime), byref(KernelTime), byref(UserTime))
return (CreationTime, ExitTime, KernelTime, UserTime)
# BOOL WINAPI FileTimeToSystemTime(
# __in const FILETIME *lpFileTime,
# __out LPSYSTEMTIME lpSystemTime
# );
def FileTimeToSystemTime(lpFileTime):
_FileTimeToSystemTime = windll.kernel32.FileTimeToSystemTime
_FileTimeToSystemTime.argtypes = [LPFILETIME, LPSYSTEMTIME]
_FileTimeToSystemTime.restype = bool
_FileTimeToSystemTime.errcheck = RaiseIfZero
if isinstance(lpFileTime, FILETIME):
FileTime = lpFileTime
else:
FileTime = FILETIME()
FileTime.dwLowDateTime = lpFileTime & 0xFFFFFFFF
FileTime.dwHighDateTime = lpFileTime >> 32
SystemTime = SYSTEMTIME()
_FileTimeToSystemTime(byref(FileTime), byref(SystemTime))
return SystemTime
# void WINAPI GetSystemTimeAsFileTime(
# __out LPFILETIME lpSystemTimeAsFileTime
# );
def GetSystemTimeAsFileTime():
_GetSystemTimeAsFileTime = windll.kernel32.GetSystemTimeAsFileTime
_GetSystemTimeAsFileTime.argtypes = [LPFILETIME]
_GetSystemTimeAsFileTime.restype = None
FileTime = FILETIME()
_GetSystemTimeAsFileTime(byref(FileTime))
return FileTime
#------------------------------------------------------------------------------
# Global ATOM API
# ATOM GlobalAddAtom(
# __in LPCTSTR lpString
# );
def GlobalAddAtomA(lpString):
_GlobalAddAtomA = windll.kernel32.GlobalAddAtomA
_GlobalAddAtomA.argtypes = [LPSTR]
_GlobalAddAtomA.restype = ATOM
_GlobalAddAtomA.errcheck = RaiseIfZero
return _GlobalAddAtomA(lpString)
def GlobalAddAtomW(lpString):
_GlobalAddAtomW = windll.kernel32.GlobalAddAtomW
_GlobalAddAtomW.argtypes = [LPWSTR]
_GlobalAddAtomW.restype = ATOM
_GlobalAddAtomW.errcheck = RaiseIfZero
return _GlobalAddAtomW(lpString)
GlobalAddAtom = GuessStringType(GlobalAddAtomA, GlobalAddAtomW)
# ATOM GlobalFindAtom(
# __in LPCTSTR lpString
# );
def GlobalFindAtomA(lpString):
_GlobalFindAtomA = windll.kernel32.GlobalFindAtomA
_GlobalFindAtomA.argtypes = [LPSTR]
_GlobalFindAtomA.restype = ATOM
_GlobalFindAtomA.errcheck = RaiseIfZero
return _GlobalFindAtomA(lpString)
def GlobalFindAtomW(lpString):
_GlobalFindAtomW = windll.kernel32.GlobalFindAtomW
_GlobalFindAtomW.argtypes = [LPWSTR]
_GlobalFindAtomW.restype = ATOM
_GlobalFindAtomW.errcheck = RaiseIfZero
return _GlobalFindAtomW(lpString)
GlobalFindAtom = GuessStringType(GlobalFindAtomA, GlobalFindAtomW)
# UINT GlobalGetAtomName(
# __in ATOM nAtom,
# __out LPTSTR lpBuffer,
# __in int nSize
# );
def GlobalGetAtomNameA(nAtom):
_GlobalGetAtomNameA = windll.kernel32.GlobalGetAtomNameA
_GlobalGetAtomNameA.argtypes = [ATOM, LPSTR, ctypes.c_int]
_GlobalGetAtomNameA.restype = UINT
_GlobalGetAtomNameA.errcheck = RaiseIfZero
nSize = 64
while 1:
lpBuffer = ctypes.create_string_buffer("", nSize)
nCopied = _GlobalGetAtomNameA(nAtom, lpBuffer, nSize)
if nCopied < nSize - 1:
break
nSize = nSize + 64
return lpBuffer.value
def GlobalGetAtomNameW(nAtom):
_GlobalGetAtomNameW = windll.kernel32.GlobalGetAtomNameW
_GlobalGetAtomNameW.argtypes = [ATOM, LPWSTR, ctypes.c_int]
_GlobalGetAtomNameW.restype = UINT
_GlobalGetAtomNameW.errcheck = RaiseIfZero
nSize = 64
while 1:
lpBuffer = ctypes.create_unicode_buffer(u"", nSize)
nCopied = _GlobalGetAtomNameW(nAtom, lpBuffer, nSize)
if nCopied < nSize - 1:
break
nSize = nSize + 64
return lpBuffer.value
GlobalGetAtomName = GuessStringType(GlobalGetAtomNameA, GlobalGetAtomNameW)
# ATOM GlobalDeleteAtom(
# __in ATOM nAtom
# );
def GlobalDeleteAtom(nAtom):
_GlobalDeleteAtom = windll.kernel32.GlobalDeleteAtom
_GlobalDeleteAtom.argtypes
_GlobalDeleteAtom.restype
SetLastError(ERROR_SUCCESS)
_GlobalDeleteAtom(nAtom)
error = GetLastError()
if error != ERROR_SUCCESS:
raise ctypes.WinError(error)
#------------------------------------------------------------------------------
# Wow64
# DWORD WINAPI Wow64SuspendThread(
# _In_ HANDLE hThread
# );
def Wow64SuspendThread(hThread):
_Wow64SuspendThread = windll.kernel32.Wow64SuspendThread
_Wow64SuspendThread.argtypes = [HANDLE]
_Wow64SuspendThread.restype = DWORD
previousCount = _Wow64SuspendThread(hThread)
if previousCount == DWORD(-1).value:
raise ctypes.WinError()
return previousCount
# BOOLEAN WINAPI Wow64EnableWow64FsRedirection(
# __in BOOLEAN Wow64FsEnableRedirection
# );
def Wow64EnableWow64FsRedirection(Wow64FsEnableRedirection):
"""
This function may not work reliably when there are nested calls. Therefore,
this function has been replaced by the L{Wow64DisableWow64FsRedirection}
and L{Wow64RevertWow64FsRedirection} functions.
@see: U{http://msdn.microsoft.com/en-us/library/windows/desktop/aa365744(v=vs.85).aspx}
"""
_Wow64EnableWow64FsRedirection = windll.kernel32.Wow64EnableWow64FsRedirection
_Wow64EnableWow64FsRedirection.argtypes = [BOOLEAN]
_Wow64EnableWow64FsRedirection.restype = BOOLEAN
_Wow64EnableWow64FsRedirection.errcheck = RaiseIfZero
# BOOL WINAPI Wow64DisableWow64FsRedirection(
# __out PVOID *OldValue
# );
def Wow64DisableWow64FsRedirection():
_Wow64DisableWow64FsRedirection = windll.kernel32.Wow64DisableWow64FsRedirection
_Wow64DisableWow64FsRedirection.argtypes = [PPVOID]
_Wow64DisableWow64FsRedirection.restype = BOOL
_Wow64DisableWow64FsRedirection.errcheck = RaiseIfZero
OldValue = PVOID(None)
_Wow64DisableWow64FsRedirection(byref(OldValue))
return OldValue
# BOOL WINAPI Wow64RevertWow64FsRedirection(
# __in PVOID OldValue
# );
def Wow64RevertWow64FsRedirection(OldValue):
_Wow64RevertWow64FsRedirection = windll.kernel32.Wow64RevertWow64FsRedirection
_Wow64RevertWow64FsRedirection.argtypes = [PVOID]
_Wow64RevertWow64FsRedirection.restype = BOOL
_Wow64RevertWow64FsRedirection.errcheck = RaiseIfZero
_Wow64RevertWow64FsRedirection(OldValue)
#==============================================================================
# This calculates the list of exported symbols.
_all = set(vars().keys()).difference(_all)
__all__ = [_x for _x in _all if not _x.startswith('_')]
__all__.sort()
#==============================================================================
#==============================================================================
# Mark functions that Psyco cannot compile.
# In your programs, don't use psyco.full().
# Call psyco.bind() on your main function instead.
try:
import psyco
psyco.cannotcompile(WaitForDebugEvent)
psyco.cannotcompile(WaitForSingleObject)
psyco.cannotcompile(WaitForSingleObjectEx)
psyco.cannotcompile(WaitForMultipleObjects)
psyco.cannotcompile(WaitForMultipleObjectsEx)
except ImportError:
pass
#==============================================================================
| 164,818 | Python | 33.941488 | 220 | 0.664145 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/win32/defines.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Common definitions.
"""
# TODO
# + add TCHAR and related types?
__revision__ = "$Id$"
import ctypes
import functools
from winappdbg import compat
#------------------------------------------------------------------------------
# Some stuff from ctypes we'll be using very frequently.
addressof = ctypes.addressof
sizeof = ctypes.sizeof
SIZEOF = ctypes.sizeof
POINTER = ctypes.POINTER
Structure = ctypes.Structure
Union = ctypes.Union
WINFUNCTYPE = ctypes.WINFUNCTYPE
windll = ctypes.windll
# The IronPython implementation of byref() was giving me problems,
# so I'm replacing it with the slower pointer() function.
try:
ctypes.c_void_p(ctypes.byref(ctypes.c_char())) # this fails in IronPython
byref = ctypes.byref
except TypeError:
byref = ctypes.pointer
# XXX DEBUG
# The following code can be enabled to make the Win32 API wrappers log to
# standard output the dll and function names, the parameter values and the
# return value for each call.
##WIN32_VERBOSE_MODE = True
WIN32_VERBOSE_MODE = False
if WIN32_VERBOSE_MODE:
class WinDllHook(object):
def __getattr__(self, name):
if name.startswith('_'):
return object.__getattr__(self, name)
return WinFuncHook(name)
class WinFuncHook(object):
def __init__(self, name):
self.__name = name
def __getattr__(self, name):
if name.startswith('_'):
return object.__getattr__(self, name)
return WinCallHook(self.__name, name)
class WinCallHook(object):
def __init__(self, dllname, funcname):
self.__dllname = dllname
self.__funcname = funcname
self.__func = getattr(getattr(ctypes.windll, dllname), funcname)
def __copy_attribute(self, attribute):
try:
value = getattr(self, attribute)
setattr(self.__func, attribute, value)
except AttributeError:
try:
delattr(self.__func, attribute)
except AttributeError:
pass
def __call__(self, *argv):
self.__copy_attribute('argtypes')
self.__copy_attribute('restype')
self.__copy_attribute('errcheck')
print("-"*10)
print("%s ! %s %r" % (self.__dllname, self.__funcname, argv))
retval = self.__func(*argv)
print("== %r" % (retval,))
return retval
windll = WinDllHook()
#==============================================================================
# This is used later on to calculate the list of exported symbols.
_all = None
_all = set(vars().keys())
#==============================================================================
def RaiseIfZero(result, func = None, arguments = ()):
"""
Error checking for most Win32 API calls.
The function is assumed to return an integer, which is C{0} on error.
In that case the C{WindowsError} exception is raised.
"""
if not result:
raise ctypes.WinError()
return result
def RaiseIfNotZero(result, func = None, arguments = ()):
"""
Error checking for some odd Win32 API calls.
The function is assumed to return an integer, which is zero on success.
If the return value is nonzero the C{WindowsError} exception is raised.
This is mostly useful for free() like functions, where the return value is
the pointer to the memory block on failure or a C{NULL} pointer on success.
"""
if result:
raise ctypes.WinError()
return result
def RaiseIfNotErrorSuccess(result, func = None, arguments = ()):
"""
Error checking for Win32 Registry API calls.
The function is assumed to return a Win32 error code. If the code is not
C{ERROR_SUCCESS} then a C{WindowsError} exception is raised.
"""
if result != ERROR_SUCCESS:
raise ctypes.WinError(result)
return result
class GuessStringType(object):
"""
Decorator that guesses the correct version (A or W) to call
based on the types of the strings passed as parameters.
Calls the B{ANSI} version if the only string types are ANSI.
Calls the B{Unicode} version if Unicode or mixed string types are passed.
The default if no string arguments are passed depends on the value of the
L{t_default} class variable.
@type fn_ansi: function
@ivar fn_ansi: ANSI version of the API function to call.
@type fn_unicode: function
@ivar fn_unicode: Unicode (wide) version of the API function to call.
@type t_default: type
@cvar t_default: Default string type to use.
Possible values are:
- type('') for ANSI
- type(u'') for Unicode
"""
# ANSI and Unicode types
t_ansi = type('')
t_unicode = type(u'')
# Default is ANSI for Python 2.x
t_default = t_ansi
def __init__(self, fn_ansi, fn_unicode):
"""
@type fn_ansi: function
@param fn_ansi: ANSI version of the API function to call.
@type fn_unicode: function
@param fn_unicode: Unicode (wide) version of the API function to call.
"""
self.fn_ansi = fn_ansi
self.fn_unicode = fn_unicode
# Copy the wrapped function attributes.
try:
self.__name__ = self.fn_ansi.__name__[:-1] # remove the A or W
except AttributeError:
pass
try:
self.__module__ = self.fn_ansi.__module__
except AttributeError:
pass
try:
self.__doc__ = self.fn_ansi.__doc__
except AttributeError:
pass
def __call__(self, *argv, **argd):
# Shortcut to self.t_ansi
t_ansi = self.t_ansi
# Get the types of all arguments for the function
v_types = [ type(item) for item in argv ]
v_types.extend( [ type(value) for (key, value) in compat.iteritems(argd) ] )
# Get the appropriate function for the default type
if self.t_default == t_ansi:
fn = self.fn_ansi
else:
fn = self.fn_unicode
# If at least one argument is a Unicode string...
if self.t_unicode in v_types:
# If al least one argument is an ANSI string,
# convert all ANSI strings to Unicode
if t_ansi in v_types:
argv = list(argv)
for index in compat.xrange(len(argv)):
if v_types[index] == t_ansi:
argv[index] = compat.unicode(argv[index])
for (key, value) in argd.items():
if type(value) == t_ansi:
argd[key] = compat.unicode(value)
# Use the W version
fn = self.fn_unicode
# If at least one argument is an ANSI string,
# but there are no Unicode strings...
elif t_ansi in v_types:
# Use the A version
fn = self.fn_ansi
# Call the function and return the result
return fn(*argv, **argd)
class DefaultStringType(object):
"""
Decorator that uses the default version (A or W) to call
based on the configuration of the L{GuessStringType} decorator.
@see: L{GuessStringType.t_default}
@type fn_ansi: function
@ivar fn_ansi: ANSI version of the API function to call.
@type fn_unicode: function
@ivar fn_unicode: Unicode (wide) version of the API function to call.
"""
def __init__(self, fn_ansi, fn_unicode):
"""
@type fn_ansi: function
@param fn_ansi: ANSI version of the API function to call.
@type fn_unicode: function
@param fn_unicode: Unicode (wide) version of the API function to call.
"""
self.fn_ansi = fn_ansi
self.fn_unicode = fn_unicode
# Copy the wrapped function attributes.
try:
self.__name__ = self.fn_ansi.__name__[:-1] # remove the A or W
except AttributeError:
pass
try:
self.__module__ = self.fn_ansi.__module__
except AttributeError:
pass
try:
self.__doc__ = self.fn_ansi.__doc__
except AttributeError:
pass
def __call__(self, *argv, **argd):
# Get the appropriate function based on the default.
if GuessStringType.t_default == GuessStringType.t_ansi:
fn = self.fn_ansi
else:
fn = self.fn_unicode
# Call the function and return the result
return fn(*argv, **argd)
def MakeANSIVersion(fn):
"""
Decorator that generates an ANSI version of a Unicode (wide) only API call.
@type fn: callable
@param fn: Unicode (wide) version of the API function to call.
"""
@functools.wraps(fn)
def wrapper(*argv, **argd):
t_ansi = GuessStringType.t_ansi
t_unicode = GuessStringType.t_unicode
v_types = [ type(item) for item in argv ]
v_types.extend( [ type(value) for (key, value) in compat.iteritems(argd) ] )
if t_ansi in v_types:
argv = list(argv)
for index in compat.xrange(len(argv)):
if v_types[index] == t_ansi:
argv[index] = t_unicode(argv[index])
for key, value in argd.items():
if type(value) == t_ansi:
argd[key] = t_unicode(value)
return fn(*argv, **argd)
return wrapper
def MakeWideVersion(fn):
"""
Decorator that generates a Unicode (wide) version of an ANSI only API call.
@type fn: callable
@param fn: ANSI version of the API function to call.
"""
@functools.wraps(fn)
def wrapper(*argv, **argd):
t_ansi = GuessStringType.t_ansi
t_unicode = GuessStringType.t_unicode
v_types = [ type(item) for item in argv ]
v_types.extend( [ type(value) for (key, value) in compat.iteritems(argd) ] )
if t_unicode in v_types:
argv = list(argv)
for index in compat.xrange(len(argv)):
if v_types[index] == t_unicode:
argv[index] = t_ansi(argv[index])
for key, value in argd.items():
if type(value) == t_unicode:
argd[key] = t_ansi(value)
return fn(*argv, **argd)
return wrapper
#--- Types --------------------------------------------------------------------
# http://msdn.microsoft.com/en-us/library/aa383751(v=vs.85).aspx
# Map of basic C types to Win32 types
LPVOID = ctypes.c_void_p
CHAR = ctypes.c_char
WCHAR = ctypes.c_wchar
BYTE = ctypes.c_ubyte
SBYTE = ctypes.c_byte
WORD = ctypes.c_uint16
SWORD = ctypes.c_int16
DWORD = ctypes.c_uint32
SDWORD = ctypes.c_int32
QWORD = ctypes.c_uint64
SQWORD = ctypes.c_int64
SHORT = ctypes.c_short
USHORT = ctypes.c_ushort
INT = ctypes.c_int
UINT = ctypes.c_uint
LONG = ctypes.c_long
ULONG = ctypes.c_ulong
LONGLONG = ctypes.c_int64 # c_longlong
ULONGLONG = ctypes.c_uint64 # c_ulonglong
LPSTR = ctypes.c_char_p
LPWSTR = ctypes.c_wchar_p
INT8 = ctypes.c_int8
INT16 = ctypes.c_int16
INT32 = ctypes.c_int32
INT64 = ctypes.c_int64
UINT8 = ctypes.c_uint8
UINT16 = ctypes.c_uint16
UINT32 = ctypes.c_uint32
UINT64 = ctypes.c_uint64
LONG32 = ctypes.c_int32
LONG64 = ctypes.c_int64
ULONG32 = ctypes.c_uint32
ULONG64 = ctypes.c_uint64
DWORD32 = ctypes.c_uint32
DWORD64 = ctypes.c_uint64
BOOL = ctypes.c_int
FLOAT = ctypes.c_float
# Map size_t to SIZE_T
try:
SIZE_T = ctypes.c_size_t
SSIZE_T = ctypes.c_ssize_t
except AttributeError:
# Size of a pointer
SIZE_T = {1:BYTE, 2:WORD, 4:DWORD, 8:QWORD}[sizeof(LPVOID)]
SSIZE_T = {1:SBYTE, 2:SWORD, 4:SDWORD, 8:SQWORD}[sizeof(LPVOID)]
PSIZE_T = POINTER(SIZE_T)
# Not really pointers but pointer-sized integers
DWORD_PTR = SIZE_T
ULONG_PTR = SIZE_T
LONG_PTR = SIZE_T
# Other Win32 types, more may be added as needed
PVOID = LPVOID
PPVOID = POINTER(PVOID)
PSTR = LPSTR
PWSTR = LPWSTR
PCHAR = LPSTR
PWCHAR = LPWSTR
LPBYTE = POINTER(BYTE)
LPSBYTE = POINTER(SBYTE)
LPWORD = POINTER(WORD)
LPSWORD = POINTER(SWORD)
LPDWORD = POINTER(DWORD)
LPSDWORD = POINTER(SDWORD)
LPULONG = POINTER(ULONG)
LPLONG = POINTER(LONG)
PDWORD = LPDWORD
PDWORD_PTR = POINTER(DWORD_PTR)
PULONG = LPULONG
PLONG = LPLONG
CCHAR = CHAR
BOOLEAN = BYTE
PBOOL = POINTER(BOOL)
LPBOOL = PBOOL
TCHAR = CHAR # XXX ANSI by default?
UCHAR = BYTE
DWORDLONG = ULONGLONG
LPDWORD32 = POINTER(DWORD32)
LPULONG32 = POINTER(ULONG32)
LPDWORD64 = POINTER(DWORD64)
LPULONG64 = POINTER(ULONG64)
PDWORD32 = LPDWORD32
PULONG32 = LPULONG32
PDWORD64 = LPDWORD64
PULONG64 = LPULONG64
ATOM = WORD
HANDLE = LPVOID
PHANDLE = POINTER(HANDLE)
LPHANDLE = PHANDLE
HMODULE = HANDLE
HINSTANCE = HANDLE
HTASK = HANDLE
HKEY = HANDLE
PHKEY = POINTER(HKEY)
HDESK = HANDLE
HRSRC = HANDLE
HSTR = HANDLE
HWINSTA = HANDLE
HKL = HANDLE
HDWP = HANDLE
HFILE = HANDLE
HRESULT = LONG
HGLOBAL = HANDLE
HLOCAL = HANDLE
HGDIOBJ = HANDLE
HDC = HGDIOBJ
HRGN = HGDIOBJ
HBITMAP = HGDIOBJ
HPALETTE = HGDIOBJ
HPEN = HGDIOBJ
HBRUSH = HGDIOBJ
HMF = HGDIOBJ
HEMF = HGDIOBJ
HENHMETAFILE = HGDIOBJ
HMETAFILE = HGDIOBJ
HMETAFILEPICT = HGDIOBJ
HWND = HANDLE
NTSTATUS = LONG
PNTSTATUS = POINTER(NTSTATUS)
KAFFINITY = ULONG_PTR
RVA = DWORD
RVA64 = QWORD
WPARAM = DWORD
LPARAM = LPVOID
LRESULT = LPVOID
ACCESS_MASK = DWORD
REGSAM = ACCESS_MASK
PACCESS_MASK = POINTER(ACCESS_MASK)
PREGSAM = POINTER(REGSAM)
# Since the SID is an opaque structure, let's treat its pointers as void*
PSID = PVOID
# typedef union _LARGE_INTEGER {
# struct {
# DWORD LowPart;
# LONG HighPart;
# } ;
# struct {
# DWORD LowPart;
# LONG HighPart;
# } u;
# LONGLONG QuadPart;
# } LARGE_INTEGER,
# *PLARGE_INTEGER;
# XXX TODO
# typedef struct _FLOAT128 {
# __int64 LowPart;
# __int64 HighPart;
# } FLOAT128;
class FLOAT128 (Structure):
_fields_ = [
("LowPart", QWORD),
("HighPart", QWORD),
]
PFLOAT128 = POINTER(FLOAT128)
# typedef struct DECLSPEC_ALIGN(16) _M128A {
# ULONGLONG Low;
# LONGLONG High;
# } M128A, *PM128A;
class M128A(Structure):
_fields_ = [
("Low", ULONGLONG),
("High", LONGLONG),
]
PM128A = POINTER(M128A)
#--- Constants ----------------------------------------------------------------
NULL = None
INFINITE = -1
TRUE = 1
FALSE = 0
# http://blogs.msdn.com/oldnewthing/archive/2004/08/26/220873.aspx
ANYSIZE_ARRAY = 1
# Invalid handle value is -1 casted to void pointer.
try:
INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value #-1 #0xFFFFFFFF
except TypeError:
if sizeof(ctypes.c_void_p) == 4:
INVALID_HANDLE_VALUE = 0xFFFFFFFF
elif sizeof(ctypes.c_void_p) == 8:
INVALID_HANDLE_VALUE = 0xFFFFFFFFFFFFFFFF
else:
raise
MAX_MODULE_NAME32 = 255
MAX_PATH = 260
# Error codes
# TODO maybe add more error codes?
# if they're too many they could be pickled instead,
# or at the very least put in a new file
ERROR_SUCCESS = 0
ERROR_INVALID_FUNCTION = 1
ERROR_FILE_NOT_FOUND = 2
ERROR_PATH_NOT_FOUND = 3
ERROR_ACCESS_DENIED = 5
ERROR_INVALID_HANDLE = 6
ERROR_NOT_ENOUGH_MEMORY = 8
ERROR_INVALID_DRIVE = 15
ERROR_NO_MORE_FILES = 18
ERROR_BAD_LENGTH = 24
ERROR_HANDLE_EOF = 38
ERROR_HANDLE_DISK_FULL = 39
ERROR_NOT_SUPPORTED = 50
ERROR_FILE_EXISTS = 80
ERROR_INVALID_PARAMETER = 87
ERROR_BUFFER_OVERFLOW = 111
ERROR_DISK_FULL = 112
ERROR_CALL_NOT_IMPLEMENTED = 120
ERROR_SEM_TIMEOUT = 121
ERROR_INSUFFICIENT_BUFFER = 122
ERROR_INVALID_NAME = 123
ERROR_MOD_NOT_FOUND = 126
ERROR_PROC_NOT_FOUND = 127
ERROR_DIR_NOT_EMPTY = 145
ERROR_BAD_THREADID_ADDR = 159
ERROR_BAD_ARGUMENTS = 160
ERROR_BAD_PATHNAME = 161
ERROR_ALREADY_EXISTS = 183
ERROR_INVALID_FLAG_NUMBER = 186
ERROR_ENVVAR_NOT_FOUND = 203
ERROR_FILENAME_EXCED_RANGE = 206
ERROR_MORE_DATA = 234
WAIT_TIMEOUT = 258
ERROR_NO_MORE_ITEMS = 259
ERROR_PARTIAL_COPY = 299
ERROR_INVALID_ADDRESS = 487
ERROR_THREAD_NOT_IN_PROCESS = 566
ERROR_CONTROL_C_EXIT = 572
ERROR_UNHANDLED_EXCEPTION = 574
ERROR_ASSERTION_FAILURE = 668
ERROR_WOW_ASSERTION = 670
ERROR_DBG_EXCEPTION_NOT_HANDLED = 688
ERROR_DBG_REPLY_LATER = 689
ERROR_DBG_UNABLE_TO_PROVIDE_HANDLE = 690
ERROR_DBG_TERMINATE_THREAD = 691
ERROR_DBG_TERMINATE_PROCESS = 692
ERROR_DBG_CONTROL_C = 693
ERROR_DBG_PRINTEXCEPTION_C = 694
ERROR_DBG_RIPEXCEPTION = 695
ERROR_DBG_CONTROL_BREAK = 696
ERROR_DBG_COMMAND_EXCEPTION = 697
ERROR_DBG_EXCEPTION_HANDLED = 766
ERROR_DBG_CONTINUE = 767
ERROR_ELEVATION_REQUIRED = 740
ERROR_NOACCESS = 998
ERROR_CIRCULAR_DEPENDENCY = 1059
ERROR_SERVICE_DOES_NOT_EXIST = 1060
ERROR_SERVICE_CANNOT_ACCEPT_CTRL = 1061
ERROR_SERVICE_NOT_ACTIVE = 1062
ERROR_FAILED_SERVICE_CONTROLLER_CONNECT = 1063
ERROR_EXCEPTION_IN_SERVICE = 1064
ERROR_DATABASE_DOES_NOT_EXIST = 1065
ERROR_SERVICE_SPECIFIC_ERROR = 1066
ERROR_PROCESS_ABORTED = 1067
ERROR_SERVICE_DEPENDENCY_FAIL = 1068
ERROR_SERVICE_LOGON_FAILED = 1069
ERROR_SERVICE_START_HANG = 1070
ERROR_INVALID_SERVICE_LOCK = 1071
ERROR_SERVICE_MARKED_FOR_DELETE = 1072
ERROR_SERVICE_EXISTS = 1073
ERROR_ALREADY_RUNNING_LKG = 1074
ERROR_SERVICE_DEPENDENCY_DELETED = 1075
ERROR_BOOT_ALREADY_ACCEPTED = 1076
ERROR_SERVICE_NEVER_STARTED = 1077
ERROR_DUPLICATE_SERVICE_NAME = 1078
ERROR_DIFFERENT_SERVICE_ACCOUNT = 1079
ERROR_CANNOT_DETECT_DRIVER_FAILURE = 1080
ERROR_CANNOT_DETECT_PROCESS_ABORT = 1081
ERROR_NO_RECOVERY_PROGRAM = 1082
ERROR_SERVICE_NOT_IN_EXE = 1083
ERROR_NOT_SAFEBOOT_SERVICE = 1084
ERROR_DEBUGGER_INACTIVE = 1284
ERROR_PRIVILEGE_NOT_HELD = 1314
ERROR_NONE_MAPPED = 1332
RPC_S_SERVER_UNAVAILABLE = 1722
# Standard access rights
import sys
if sys.version_info[0] >= 3:
long = int
DELETE = long(0x00010000)
READ_CONTROL = long(0x00020000)
WRITE_DAC = long(0x00040000)
WRITE_OWNER = long(0x00080000)
SYNCHRONIZE = long(0x00100000)
STANDARD_RIGHTS_REQUIRED = long(0x000F0000)
STANDARD_RIGHTS_READ = READ_CONTROL
STANDARD_RIGHTS_WRITE = READ_CONTROL
STANDARD_RIGHTS_EXECUTE = READ_CONTROL
STANDARD_RIGHTS_ALL = long(0x001F0000)
SPECIFIC_RIGHTS_ALL = long(0x0000FFFF)
#--- Structures ---------------------------------------------------------------
# typedef struct _LSA_UNICODE_STRING {
# USHORT Length;
# USHORT MaximumLength;
# PWSTR Buffer;
# } LSA_UNICODE_STRING,
# *PLSA_UNICODE_STRING,
# UNICODE_STRING,
# *PUNICODE_STRING;
class UNICODE_STRING(Structure):
_fields_ = [
("Length", USHORT),
("MaximumLength", USHORT),
("Buffer", PVOID),
]
# From MSDN:
#
# typedef struct _GUID {
# DWORD Data1;
# WORD Data2;
# WORD Data3;
# BYTE Data4[8];
# } GUID;
class GUID(Structure):
_fields_ = [
("Data1", DWORD),
("Data2", WORD),
("Data3", WORD),
("Data4", BYTE * 8),
]
# From MSDN:
#
# typedef struct _LIST_ENTRY {
# struct _LIST_ENTRY *Flink;
# struct _LIST_ENTRY *Blink;
# } LIST_ENTRY, *PLIST_ENTRY, *RESTRICTED_POINTER PRLIST_ENTRY;
class LIST_ENTRY(Structure):
_fields_ = [
("Flink", PVOID), # POINTER(LIST_ENTRY)
("Blink", PVOID), # POINTER(LIST_ENTRY)
]
#==============================================================================
# This calculates the list of exported symbols.
_all = set(vars().keys()).difference(_all)
##__all__ = [_x for _x in _all if not _x.startswith('_')]
##__all__.sort()
#==============================================================================
| 22,799 | Python | 30.710709 | 84 | 0.582087 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/winappdbg/win32/ntdll.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2014, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice,this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Wrapper for ntdll.dll in ctypes.
"""
__revision__ = "$Id$"
from winappdbg.win32.defines import *
#==============================================================================
# This is used later on to calculate the list of exported symbols.
_all = None
_all = set(vars().keys())
_all.add('peb_teb')
#==============================================================================
from winappdbg.win32.peb_teb import *
#--- Types --------------------------------------------------------------------
SYSDBG_COMMAND = DWORD
PROCESSINFOCLASS = DWORD
THREADINFOCLASS = DWORD
FILE_INFORMATION_CLASS = DWORD
#--- Constants ----------------------------------------------------------------
# DEP flags for ProcessExecuteFlags
MEM_EXECUTE_OPTION_ENABLE = 1
MEM_EXECUTE_OPTION_DISABLE = 2
MEM_EXECUTE_OPTION_ATL7_THUNK_EMULATION = 4
MEM_EXECUTE_OPTION_PERMANENT = 8
# SYSTEM_INFORMATION_CLASS
# http://www.informit.com/articles/article.aspx?p=22442&seqNum=4
SystemBasicInformation = 1 # 0x002C
SystemProcessorInformation = 2 # 0x000C
SystemPerformanceInformation = 3 # 0x0138
SystemTimeInformation = 4 # 0x0020
SystemPathInformation = 5 # not implemented
SystemProcessInformation = 6 # 0x00F8 + per process
SystemCallInformation = 7 # 0x0018 + (n * 0x0004)
SystemConfigurationInformation = 8 # 0x0018
SystemProcessorCounters = 9 # 0x0030 per cpu
SystemGlobalFlag = 10 # 0x0004
SystemInfo10 = 11 # not implemented
SystemModuleInformation = 12 # 0x0004 + (n * 0x011C)
SystemLockInformation = 13 # 0x0004 + (n * 0x0024)
SystemInfo13 = 14 # not implemented
SystemPagedPoolInformation = 15 # checked build only
SystemNonPagedPoolInformation = 16 # checked build only
SystemHandleInformation = 17 # 0x0004 + (n * 0x0010)
SystemObjectInformation = 18 # 0x0038+ + (n * 0x0030+)
SystemPagefileInformation = 19 # 0x0018+ per page file
SystemInstemulInformation = 20 # 0x0088
SystemInfo20 = 21 # invalid info class
SystemCacheInformation = 22 # 0x0024
SystemPoolTagInformation = 23 # 0x0004 + (n * 0x001C)
SystemProcessorStatistics = 24 # 0x0000, or 0x0018 per cpu
SystemDpcInformation = 25 # 0x0014
SystemMemoryUsageInformation1 = 26 # checked build only
SystemLoadImage = 27 # 0x0018, set mode only
SystemUnloadImage = 28 # 0x0004, set mode only
SystemTimeAdjustmentInformation = 29 # 0x000C, 0x0008 writeable
SystemMemoryUsageInformation2 = 30 # checked build only
SystemInfo30 = 31 # checked build only
SystemInfo31 = 32 # checked build only
SystemCrashDumpInformation = 33 # 0x0004
SystemExceptionInformation = 34 # 0x0010
SystemCrashDumpStateInformation = 35 # 0x0008
SystemDebuggerInformation = 36 # 0x0002
SystemThreadSwitchInformation = 37 # 0x0030
SystemRegistryQuotaInformation = 38 # 0x000C
SystemLoadDriver = 39 # 0x0008, set mode only
SystemPrioritySeparationInformation = 40 # 0x0004, set mode only
SystemInfo40 = 41 # not implemented
SystemInfo41 = 42 # not implemented
SystemInfo42 = 43 # invalid info class
SystemInfo43 = 44 # invalid info class
SystemTimeZoneInformation = 45 # 0x00AC
SystemLookasideInformation = 46 # n * 0x0020
# info classes specific to Windows 2000
# WTS = Windows Terminal Server
SystemSetTimeSlipEvent = 47 # set mode only
SystemCreateSession = 48 # WTS, set mode only
SystemDeleteSession = 49 # WTS, set mode only
SystemInfo49 = 50 # invalid info class
SystemRangeStartInformation = 51 # 0x0004
SystemVerifierInformation = 52 # 0x0068
SystemAddVerifier = 53 # set mode only
SystemSessionProcessesInformation = 54 # WTS
# NtQueryInformationProcess constants (from MSDN)
##ProcessBasicInformation = 0
##ProcessDebugPort = 7
##ProcessWow64Information = 26
##ProcessImageFileName = 27
# PROCESS_INFORMATION_CLASS
# http://undocumented.ntinternals.net/UserMode/Undocumented%20Functions/NT%20Objects/Process/PROCESS_INFORMATION_CLASS.html
ProcessBasicInformation = 0
ProcessQuotaLimits = 1
ProcessIoCounters = 2
ProcessVmCounters = 3
ProcessTimes = 4
ProcessBasePriority = 5
ProcessRaisePriority = 6
ProcessDebugPort = 7
ProcessExceptionPort = 8
ProcessAccessToken = 9
ProcessLdtInformation = 10
ProcessLdtSize = 11
ProcessDefaultHardErrorMode = 12
ProcessIoPortHandlers = 13
ProcessPooledUsageAndLimits = 14
ProcessWorkingSetWatch = 15
ProcessUserModeIOPL = 16
ProcessEnableAlignmentFaultFixup = 17
ProcessPriorityClass = 18
ProcessWx86Information = 19
ProcessHandleCount = 20
ProcessAffinityMask = 21
ProcessPriorityBoost = 22
ProcessWow64Information = 26
ProcessImageFileName = 27
# http://www.codeproject.com/KB/security/AntiReverseEngineering.aspx
ProcessDebugObjectHandle = 30
ProcessExecuteFlags = 34
# THREAD_INFORMATION_CLASS
ThreadBasicInformation = 0
ThreadTimes = 1
ThreadPriority = 2
ThreadBasePriority = 3
ThreadAffinityMask = 4
ThreadImpersonationToken = 5
ThreadDescriptorTableEntry = 6
ThreadEnableAlignmentFaultFixup = 7
ThreadEventPair = 8
ThreadQuerySetWin32StartAddress = 9
ThreadZeroTlsCell = 10
ThreadPerformanceCount = 11
ThreadAmILastThread = 12
ThreadIdealProcessor = 13
ThreadPriorityBoost = 14
ThreadSetTlsArrayAddress = 15
ThreadIsIoPending = 16
ThreadHideFromDebugger = 17
# OBJECT_INFORMATION_CLASS
ObjectBasicInformation = 0
ObjectNameInformation = 1
ObjectTypeInformation = 2
ObjectAllTypesInformation = 3
ObjectHandleInformation = 4
# FILE_INFORMATION_CLASS
FileDirectoryInformation = 1
FileFullDirectoryInformation = 2
FileBothDirectoryInformation = 3
FileBasicInformation = 4
FileStandardInformation = 5
FileInternalInformation = 6
FileEaInformation = 7
FileAccessInformation = 8
FileNameInformation = 9
FileRenameInformation = 10
FileLinkInformation = 11
FileNamesInformation = 12
FileDispositionInformation = 13
FilePositionInformation = 14
FileFullEaInformation = 15
FileModeInformation = 16
FileAlignmentInformation = 17
FileAllInformation = 18
FileAllocationInformation = 19
FileEndOfFileInformation = 20
FileAlternateNameInformation = 21
FileStreamInformation = 22
FilePipeInformation = 23
FilePipeLocalInformation = 24
FilePipeRemoteInformation = 25
FileMailslotQueryInformation = 26
FileMailslotSetInformation = 27
FileCompressionInformation = 28
FileCopyOnWriteInformation = 29
FileCompletionInformation = 30
FileMoveClusterInformation = 31
FileQuotaInformation = 32
FileReparsePointInformation = 33
FileNetworkOpenInformation = 34
FileObjectIdInformation = 35
FileTrackingInformation = 36
FileOleDirectoryInformation = 37
FileContentIndexInformation = 38
FileInheritContentIndexInformation = 37
FileOleInformation = 39
FileMaximumInformation = 40
# From http://www.nirsoft.net/kernel_struct/vista/EXCEPTION_DISPOSITION.html
# typedef enum _EXCEPTION_DISPOSITION
# {
# ExceptionContinueExecution = 0,
# ExceptionContinueSearch = 1,
# ExceptionNestedException = 2,
# ExceptionCollidedUnwind = 3
# } EXCEPTION_DISPOSITION;
ExceptionContinueExecution = 0
ExceptionContinueSearch = 1
ExceptionNestedException = 2
ExceptionCollidedUnwind = 3
#--- PROCESS_BASIC_INFORMATION structure --------------------------------------
# From MSDN:
#
# typedef struct _PROCESS_BASIC_INFORMATION {
# PVOID Reserved1;
# PPEB PebBaseAddress;
# PVOID Reserved2[2];
# ULONG_PTR UniqueProcessId;
# PVOID Reserved3;
# } PROCESS_BASIC_INFORMATION;
##class PROCESS_BASIC_INFORMATION(Structure):
## _fields_ = [
## ("Reserved1", PVOID),
## ("PebBaseAddress", PPEB),
## ("Reserved2", PVOID * 2),
## ("UniqueProcessId", ULONG_PTR),
## ("Reserved3", PVOID),
##]
# From http://catch22.net/tuts/tips2
# (Only valid for 32 bits)
#
# typedef struct
# {
# ULONG ExitStatus;
# PVOID PebBaseAddress;
# ULONG AffinityMask;
# ULONG BasePriority;
# ULONG_PTR UniqueProcessId;
# ULONG_PTR InheritedFromUniqueProcessId;
# } PROCESS_BASIC_INFORMATION;
# My own definition follows:
class PROCESS_BASIC_INFORMATION(Structure):
_fields_ = [
("ExitStatus", SIZE_T),
("PebBaseAddress", PVOID), # PPEB
("AffinityMask", KAFFINITY),
("BasePriority", SDWORD),
("UniqueProcessId", ULONG_PTR),
("InheritedFromUniqueProcessId", ULONG_PTR),
]
#--- THREAD_BASIC_INFORMATION structure ---------------------------------------
# From http://undocumented.ntinternals.net/UserMode/Structures/THREAD_BASIC_INFORMATION.html
#
# typedef struct _THREAD_BASIC_INFORMATION {
# NTSTATUS ExitStatus;
# PVOID TebBaseAddress;
# CLIENT_ID ClientId;
# KAFFINITY AffinityMask;
# KPRIORITY Priority;
# KPRIORITY BasePriority;
# } THREAD_BASIC_INFORMATION, *PTHREAD_BASIC_INFORMATION;
class THREAD_BASIC_INFORMATION(Structure):
_fields_ = [
("ExitStatus", NTSTATUS),
("TebBaseAddress", PVOID), # PTEB
("ClientId", CLIENT_ID),
("AffinityMask", KAFFINITY),
("Priority", SDWORD),
("BasePriority", SDWORD),
]
#--- FILE_NAME_INFORMATION structure ------------------------------------------
# typedef struct _FILE_NAME_INFORMATION {
# ULONG FileNameLength;
# WCHAR FileName[1];
# } FILE_NAME_INFORMATION, *PFILE_NAME_INFORMATION;
class FILE_NAME_INFORMATION(Structure):
_fields_ = [
("FileNameLength", ULONG),
("FileName", WCHAR * 1),
]
#--- SYSDBG_MSR structure and constants ---------------------------------------
SysDbgReadMsr = 16
SysDbgWriteMsr = 17
class SYSDBG_MSR(Structure):
_fields_ = [
("Address", ULONG),
("Data", ULONGLONG),
]
#--- IO_STATUS_BLOCK structure ------------------------------------------------
# typedef struct _IO_STATUS_BLOCK {
# union {
# NTSTATUS Status;
# PVOID Pointer;
# };
# ULONG_PTR Information;
# } IO_STATUS_BLOCK, *PIO_STATUS_BLOCK;
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)
#--- ntdll.dll ----------------------------------------------------------------
# ULONG WINAPI RtlNtStatusToDosError(
# __in NTSTATUS Status
# );
def RtlNtStatusToDosError(Status):
_RtlNtStatusToDosError = windll.ntdll.RtlNtStatusToDosError
_RtlNtStatusToDosError.argtypes = [NTSTATUS]
_RtlNtStatusToDosError.restype = ULONG
return _RtlNtStatusToDosError(Status)
# NTSYSAPI NTSTATUS NTAPI NtSystemDebugControl(
# IN SYSDBG_COMMAND Command,
# IN PVOID InputBuffer OPTIONAL,
# IN ULONG InputBufferLength,
# OUT PVOID OutputBuffer OPTIONAL,
# IN ULONG OutputBufferLength,
# OUT PULONG ReturnLength OPTIONAL
# );
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) )
ZwSystemDebugControl = NtSystemDebugControl
# NTSTATUS WINAPI NtQueryInformationProcess(
# __in HANDLE ProcessHandle,
# __in PROCESSINFOCLASS ProcessInformationClass,
# __out PVOID ProcessInformation,
# __in ULONG ProcessInformationLength,
# __out_opt PULONG ReturnLength
# );
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
ZwQueryInformationProcess = NtQueryInformationProcess
# NTSTATUS WINAPI NtQueryInformationThread(
# __in HANDLE ThreadHandle,
# __in THREADINFOCLASS ThreadInformationClass,
# __out PVOID ThreadInformation,
# __in ULONG ThreadInformationLength,
# __out_opt PULONG ReturnLength
# );
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
ZwQueryInformationThread = NtQueryInformationThread
# NTSTATUS
# NtQueryInformationFile(
# IN HANDLE FileHandle,
# OUT PIO_STATUS_BLOCK IoStatusBlock,
# OUT PVOID FileInformation,
# IN ULONG Length,
# IN FILE_INFORMATION_CLASS FileInformationClass
# );
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
ZwQueryInformationFile = NtQueryInformationFile
# DWORD STDCALL CsrGetProcessId (VOID);
def CsrGetProcessId():
_CsrGetProcessId = windll.ntdll.CsrGetProcessId
_CsrGetProcessId.argtypes = []
_CsrGetProcessId.restype = DWORD
return _CsrGetProcessId()
#==============================================================================
# This calculates the list of exported symbols.
_all = set(vars().keys()).difference(_all)
__all__ = [_x for _x in _all if not _x.startswith('_')]
__all__.sort()
#==============================================================================
| 22,847 | Python | 41.311111 | 155 | 0.639165 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/linux_and_mac/lldb_prepare.py | # This file is meant to be run inside lldb
# It registers command to load library and invoke attach function
# Also it marks process threads to to distinguish them from debugger
# threads later while settings trace in threads
def load_lib_and_attach(debugger, command, result, internal_dict):
import shlex
args = shlex.split(command)
dll = args[0]
is_debug = args[1]
python_code = args[2]
show_debug_info = args[3]
import lldb
options = lldb.SBExpressionOptions()
options.SetFetchDynamicValue()
options.SetTryAllThreads(run_others=False)
options.SetTimeoutInMicroSeconds(timeout=10000000)
print(dll)
target = debugger.GetSelectedTarget()
res = target.EvaluateExpression("(void*)dlopen(\"%s\", 2);" % (
dll), options)
error = res.GetError()
if error:
print(error)
print(python_code)
res = target.EvaluateExpression("(int)DoAttach(%s, \"%s\", %s);" % (
is_debug, python_code.replace('"', "'"), show_debug_info), options)
error = res.GetError()
if error:
print(error)
def __lldb_init_module(debugger, internal_dict):
import lldb
debugger.HandleCommand('command script add -f lldb_prepare.load_lib_and_attach load_lib_and_attach')
try:
target = debugger.GetSelectedTarget()
if target:
process = target.GetProcess()
if process:
for thread in process:
# print('Marking process thread %d'%thread.GetThreadID())
internal_dict['_thread_%d' % thread.GetThreadID()] = True
# thread.Suspend()
except:
import traceback;traceback.print_exc()
| 1,691 | Python | 29.763636 | 104 | 0.63631 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/launcher/winapi.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
import ctypes
from ctypes.wintypes import BOOL, DWORD, HANDLE, LARGE_INTEGER, LPCSTR, UINT
from debugpy.common import log
JOBOBJECTCLASS = ctypes.c_int
LPDWORD = ctypes.POINTER(DWORD)
LPVOID = ctypes.c_void_p
SIZE_T = ctypes.c_size_t
ULONGLONG = ctypes.c_ulonglong
class IO_COUNTERS(ctypes.Structure):
_fields_ = [
("ReadOperationCount", ULONGLONG),
("WriteOperationCount", ULONGLONG),
("OtherOperationCount", ULONGLONG),
("ReadTransferCount", ULONGLONG),
("WriteTransferCount", ULONGLONG),
("OtherTransferCount", ULONGLONG),
]
class JOBOBJECT_BASIC_LIMIT_INFORMATION(ctypes.Structure):
_fields_ = [
("PerProcessUserTimeLimit", LARGE_INTEGER),
("PerJobUserTimeLimit", LARGE_INTEGER),
("LimitFlags", DWORD),
("MinimumWorkingSetSize", SIZE_T),
("MaximumWorkingSetSize", SIZE_T),
("ActiveProcessLimit", DWORD),
("Affinity", SIZE_T),
("PriorityClass", DWORD),
("SchedulingClass", DWORD),
]
class JOBOBJECT_EXTENDED_LIMIT_INFORMATION(ctypes.Structure):
_fields_ = [
("BasicLimitInformation", JOBOBJECT_BASIC_LIMIT_INFORMATION),
("IoInfo", IO_COUNTERS),
("ProcessMemoryLimit", SIZE_T),
("JobMemoryLimit", SIZE_T),
("PeakProcessMemoryUsed", SIZE_T),
("PeakJobMemoryUsed", SIZE_T),
]
JobObjectExtendedLimitInformation = JOBOBJECTCLASS(9)
JOB_OBJECT_LIMIT_BREAKAWAY_OK = 0x00000800
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000
PROCESS_TERMINATE = 0x0001
PROCESS_SET_QUOTA = 0x0100
def _errcheck(is_error_result=(lambda result: not result)):
def impl(result, func, args):
if is_error_result(result):
log.debug("{0} returned {1}", func.__name__, result)
raise ctypes.WinError()
else:
return result
return impl
kernel32 = ctypes.windll.kernel32
kernel32.AssignProcessToJobObject.errcheck = _errcheck()
kernel32.AssignProcessToJobObject.restype = BOOL
kernel32.AssignProcessToJobObject.argtypes = (HANDLE, HANDLE)
kernel32.CreateJobObjectA.errcheck = _errcheck(lambda result: result == 0)
kernel32.CreateJobObjectA.restype = HANDLE
kernel32.CreateJobObjectA.argtypes = (LPVOID, LPCSTR)
kernel32.OpenProcess.errcheck = _errcheck(lambda result: result == 0)
kernel32.OpenProcess.restype = HANDLE
kernel32.OpenProcess.argtypes = (DWORD, BOOL, DWORD)
kernel32.QueryInformationJobObject.errcheck = _errcheck()
kernel32.QueryInformationJobObject.restype = BOOL
kernel32.QueryInformationJobObject.argtypes = (
HANDLE,
JOBOBJECTCLASS,
LPVOID,
DWORD,
LPDWORD,
)
kernel32.SetInformationJobObject.errcheck = _errcheck()
kernel32.SetInformationJobObject.restype = BOOL
kernel32.SetInformationJobObject.argtypes = (HANDLE, JOBOBJECTCLASS, LPVOID, DWORD)
kernel32.TerminateJobObject.errcheck = _errcheck()
kernel32.TerminateJobObject.restype = BOOL
kernel32.TerminateJobObject.argtypes = (HANDLE, UINT)
| 3,129 | Python | 28.809524 | 83 | 0.711409 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/launcher/handlers.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
import os
import sys
import debugpy
from debugpy import launcher
from debugpy.common import json
from debugpy.launcher import debuggee
def launch_request(request):
debug_options = set(request("debugOptions", json.array(str)))
# Handling of properties that can also be specified as legacy "debugOptions" flags.
# If property is explicitly set to false, but the flag is in "debugOptions", treat
# it as an error. Returns None if the property wasn't explicitly set either way.
def property_or_debug_option(prop_name, flag_name):
assert prop_name[0].islower() and flag_name[0].isupper()
value = request(prop_name, bool, optional=True)
if value == ():
value = None
if flag_name in debug_options:
if value is False:
raise request.isnt_valid(
'{0}:false and "debugOptions":[{1}] are mutually exclusive',
json.repr(prop_name),
json.repr(flag_name),
)
value = True
return value
python = request("python", json.array(str, size=(1,)))
cmdline = list(python)
if not request("noDebug", json.default(False)):
# see https://github.com/microsoft/debugpy/issues/861
if sys.version_info[:2] >= (3, 11):
cmdline += ["-X", "frozen_modules=off"]
port = request("port", int)
cmdline += [
os.path.dirname(debugpy.__file__),
"--connect",
launcher.adapter_host + ":" + str(port),
]
if not request("subProcess", True):
cmdline += ["--configure-subProcess", "False"]
qt_mode = request(
"qt",
json.enum(
"none", "auto", "pyside", "pyside2", "pyqt4", "pyqt5", optional=True
),
)
cmdline += ["--configure-qt", qt_mode]
adapter_access_token = request("adapterAccessToken", str, optional=True)
if adapter_access_token != ():
cmdline += ["--adapter-access-token", adapter_access_token]
debugpy_args = request("debugpyArgs", json.array(str))
cmdline += debugpy_args
# Use the copy of arguments that was propagated via the command line rather than
# "args" in the request itself, to allow for shell expansion.
cmdline += sys.argv[1:]
process_name = request("processName", sys.executable)
env = os.environ.copy()
env_changes = request("env", json.object((str, type(None))))
if sys.platform == "win32":
# Environment variables are case-insensitive on Win32, so we need to normalize
# both dicts to make sure that env vars specified in the debug configuration
# overwrite the global env vars correctly. If debug config has entries that
# differ in case only, that's an error.
env = {k.upper(): v for k, v in os.environ.items()}
new_env_changes = {}
for k, v in env_changes.items():
k_upper = k.upper()
if k_upper in new_env_changes:
if new_env_changes[k_upper] == v:
continue
else:
raise request.isnt_valid(
'Found duplicate in "env": {0}.'.format(k_upper)
)
new_env_changes[k_upper] = v
env_changes = new_env_changes
if "DEBUGPY_TEST" in env:
# If we're running as part of a debugpy test, make sure that codecov is not
# applied to the debuggee, since it will conflict with pydevd.
env.pop("COV_CORE_SOURCE", None)
env.update(env_changes)
env = {k: v for k, v in env.items() if v is not None}
if request("gevent", False):
env["GEVENT_SUPPORT"] = "True"
console = request(
"console",
json.enum(
"internalConsole", "integratedTerminal", "externalTerminal", optional=True
),
)
redirect_output = property_or_debug_option("redirectOutput", "RedirectOutput")
if redirect_output is None:
# If neither the property nor the option were specified explicitly, choose
# the default depending on console type - "internalConsole" needs it to
# provide any output at all, but it's unnecessary for the terminals.
redirect_output = console == "internalConsole"
if redirect_output:
# sys.stdout buffering must be disabled - otherwise we won't see the output
# at all until the buffer fills up.
env["PYTHONUNBUFFERED"] = "1"
# Force UTF-8 output to minimize data loss due to re-encoding.
env["PYTHONIOENCODING"] = "utf-8"
if property_or_debug_option("waitOnNormalExit", "WaitOnNormalExit"):
if console == "internalConsole":
raise request.isnt_valid(
'"waitOnNormalExit" is not supported for "console":"internalConsole"'
)
debuggee.wait_on_exit_predicates.append(lambda code: code == 0)
if property_or_debug_option("waitOnAbnormalExit", "WaitOnAbnormalExit"):
if console == "internalConsole":
raise request.isnt_valid(
'"waitOnAbnormalExit" is not supported for "console":"internalConsole"'
)
debuggee.wait_on_exit_predicates.append(lambda code: code != 0)
debuggee.spawn(process_name, cmdline, env, redirect_output)
return {}
def terminate_request(request):
del debuggee.wait_on_exit_predicates[:]
request.respond({})
debuggee.kill()
def disconnect():
del debuggee.wait_on_exit_predicates[:]
debuggee.kill()
| 5,728 | Python | 36.444444 | 87 | 0.606145 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/launcher/__init__.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
__all__ = []
adapter_host = None
"""The host on which adapter is running and listening for incoming connections
from the launcher and the servers."""
channel = None
"""DAP message channel to the adapter."""
def connect(host, port):
from debugpy.common import log, messaging, sockets
from debugpy.launcher import handlers
global channel, adapter_host
assert channel is None
assert adapter_host is None
log.info("Connecting to adapter at {0}:{1}", host, port)
sock = sockets.create_client()
sock.connect((host, port))
adapter_host = host
stream = messaging.JsonIOStream.from_socket(sock, "Adapter")
channel = messaging.JsonMessageChannel(stream, handlers=handlers)
channel.start()
| 890 | Python | 25.999999 | 78 | 0.719101 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/launcher/output.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
import codecs
import os
import threading
from debugpy import launcher
from debugpy.common import log
class CaptureOutput(object):
"""Captures output from the specified file descriptor, and tees it into another
file descriptor while generating DAP "output" events for it.
"""
instances = {}
"""Keys are output categories, values are CaptureOutput instances."""
def __init__(self, whose, category, fd, stream):
assert category not in self.instances
self.instances[category] = self
log.info("Capturing {0} of {1}.", category, whose)
self.category = category
self._whose = whose
self._fd = fd
self._decoder = codecs.getincrementaldecoder("utf-8")(errors="surrogateescape")
if stream is None:
# Can happen if running under pythonw.exe.
self._stream = None
else:
self._stream = stream.buffer
encoding = stream.encoding
if encoding is None or encoding == "cp65001":
encoding = "utf-8"
try:
self._encode = codecs.getencoder(encoding)
except Exception:
log.swallow_exception(
"Unsupported {0} encoding {1!r}; falling back to UTF-8.",
category,
encoding,
level="warning",
)
self._encode = codecs.getencoder("utf-8")
else:
log.info("Using encoding {0!r} for {1}", encoding, category)
self._worker_thread = threading.Thread(target=self._worker, name=category)
self._worker_thread.start()
def __del__(self):
fd = self._fd
if fd is not None:
try:
os.close(fd)
except Exception:
pass
def _worker(self):
while self._fd is not None:
try:
s = os.read(self._fd, 0x1000)
except Exception:
break
if not len(s):
break
self._process_chunk(s)
# Flush any remaining data in the incremental decoder.
self._process_chunk(b"", final=True)
def _process_chunk(self, s, final=False):
s = self._decoder.decode(s, final=final)
if len(s) == 0:
return
try:
launcher.channel.send_event(
"output", {"category": self.category, "output": s.replace("\r\n", "\n")}
)
except Exception:
pass # channel to adapter is already closed
if self._stream is None:
return
try:
s, _ = self._encode(s, "surrogateescape")
size = len(s)
i = 0
while i < size:
written = self._stream.write(s[i:])
self._stream.flush()
if written == 0:
# This means that the output stream was closed from the other end.
# Do the same to the debuggee, so that it knows as well.
os.close(self._fd)
self._fd = None
break
i += written
except Exception:
log.swallow_exception("Error printing {0!r} to {1}", s, self.category)
def wait_for_remaining_output():
"""Waits for all remaining output to be captured and propagated."""
for category, instance in CaptureOutput.instances.items():
log.info("Waiting for remaining {0} of {1}.", category, instance._whose)
instance._worker_thread.join()
| 3,748 | Python | 31.885965 | 88 | 0.540822 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/launcher/__main__.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
__all__ = ["main"]
import locale
import signal
import sys
# WARNING: debugpy and submodules must not be imported on top level in this module,
# and should be imported locally inside main() instead.
def main():
from debugpy import launcher
from debugpy.common import log
from debugpy.launcher import debuggee
log.to_file(prefix="debugpy.launcher")
log.describe_environment("debugpy.launcher startup environment:")
if sys.platform == "win32":
# For windows, disable exceptions on Ctrl+C - we want to allow the debuggee
# process to handle these, or not, as it sees fit. If the debuggee exits
# on Ctrl+C, the launcher will also exit, so it doesn't need to observe
# the signal directly.
signal.signal(signal.SIGINT, signal.SIG_IGN)
# Everything before "--" is command line arguments for the launcher itself,
# and everything after "--" is command line arguments for the debuggee.
log.info("sys.argv before parsing: {0}", sys.argv)
sep = sys.argv.index("--")
launcher_argv = sys.argv[1:sep]
sys.argv[:] = [sys.argv[0]] + sys.argv[sep + 1 :]
log.info("sys.argv after patching: {0}", sys.argv)
# The first argument specifies the host/port on which the adapter is waiting
# for launcher to connect. It's either host:port, or just port.
adapter = launcher_argv[0]
host, sep, port = adapter.partition(":")
if not sep:
host = "127.0.0.1"
port = adapter
port = int(port)
launcher.connect(host, port)
launcher.channel.wait()
if debuggee.process is not None:
sys.exit(debuggee.process.returncode)
if __name__ == "__main__":
# debugpy can also be invoked directly rather than via -m. In this case, the first
# entry on sys.path is the one added automatically by Python for the directory
# containing this file. This means that import debugpy will not work, since we need
# the parent directory of debugpy/ to be in sys.path, rather than debugpy/launcher/.
#
# The other issue is that many other absolute imports will break, because they
# will be resolved relative to debugpy/launcher/ - e.g. `import state` will then try
# to import debugpy/launcher/state.py.
#
# To fix both, we need to replace the automatically added entry such that it points
# at parent directory of debugpy/ instead of debugpy/launcher, import debugpy with that
# in sys.path, and then remove the first entry entry altogether, so that it doesn't
# affect any further imports we might do. For example, suppose the user did:
#
# python /foo/bar/debugpy/launcher ...
#
# At the beginning of this script, sys.path will contain "/foo/bar/debugpy/launcher"
# as the first entry. What we want is to replace it with "/foo/bar', then import
# debugpy with that in effect, and then remove the replaced entry before any more
# code runs. The imported debugpy module will remain in sys.modules, and thus all
# future imports of it or its submodules will resolve accordingly.
if "debugpy" not in sys.modules:
# Do not use dirname() to walk up - this can be a relative path, e.g. ".".
sys.path[0] = sys.path[0] + "/../../"
__import__("debugpy")
del sys.path[0]
# Apply OS-global and user-specific locale settings.
try:
locale.setlocale(locale.LC_ALL, "")
except Exception:
# On POSIX, locale is set via environment variables, and this can fail if
# those variables reference a non-existing locale. Ignore and continue using
# the default "C" locale if so.
pass
main()
| 3,812 | Python | 40.445652 | 91 | 0.678122 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/launcher/debuggee.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
import atexit
import ctypes
import os
import signal
import struct
import subprocess
import sys
import threading
from debugpy import launcher
from debugpy.common import log, messaging
from debugpy.launcher import output
if sys.platform == "win32":
from debugpy.launcher import winapi
process = None
"""subprocess.Popen instance for the debuggee process."""
job_handle = None
"""On Windows, the handle for the job object to which the debuggee is assigned."""
wait_on_exit_predicates = []
"""List of functions that determine whether to pause after debuggee process exits.
Every function is invoked with exit code as the argument. If any of the functions
returns True, the launcher pauses and waits for user input before exiting.
"""
def describe():
return f"Debuggee[PID={process.pid}]"
def spawn(process_name, cmdline, env, redirect_output):
log.info(
"Spawning debuggee process:\n\n"
"Command line: {0!r}\n\n"
"Environment variables: {1!r}\n\n",
cmdline,
env,
)
close_fds = set()
try:
if redirect_output:
# subprocess.PIPE behavior can vary substantially depending on Python version
# and platform; using our own pipes keeps it simple, predictable, and fast.
stdout_r, stdout_w = os.pipe()
stderr_r, stderr_w = os.pipe()
close_fds |= {stdout_r, stdout_w, stderr_r, stderr_w}
kwargs = dict(stdout=stdout_w, stderr=stderr_w)
else:
kwargs = {}
if sys.platform != "win32":
def preexec_fn():
try:
# Start the debuggee in a new process group, so that the launcher can
# kill the entire process tree later.
os.setpgrp()
# Make the new process group the foreground group in its session, so
# that it can interact with the terminal. The debuggee will receive
# SIGTTOU when tcsetpgrp() is called, and must ignore it.
old_handler = signal.signal(signal.SIGTTOU, signal.SIG_IGN)
try:
tty = os.open("/dev/tty", os.O_RDWR)
try:
os.tcsetpgrp(tty, os.getpgrp())
finally:
os.close(tty)
finally:
signal.signal(signal.SIGTTOU, old_handler)
except Exception:
# Not an error - /dev/tty doesn't work when there's no terminal.
log.swallow_exception(
"Failed to set up process group", level="info"
)
kwargs.update(preexec_fn=preexec_fn)
try:
global process
process = subprocess.Popen(cmdline, env=env, bufsize=0, **kwargs)
except Exception as exc:
raise messaging.MessageHandlingError(
"Couldn't spawn debuggee: {0}\n\nCommand line:{1!r}".format(
exc, cmdline
)
)
log.info("Spawned {0}.", describe())
if sys.platform == "win32":
# Assign the debuggee to a new job object, so that the launcher can kill
# the entire process tree later.
try:
global job_handle
job_handle = winapi.kernel32.CreateJobObjectA(None, None)
job_info = winapi.JOBOBJECT_EXTENDED_LIMIT_INFORMATION()
job_info_size = winapi.DWORD(ctypes.sizeof(job_info))
winapi.kernel32.QueryInformationJobObject(
job_handle,
winapi.JobObjectExtendedLimitInformation,
ctypes.pointer(job_info),
job_info_size,
ctypes.pointer(job_info_size),
)
job_info.BasicLimitInformation.LimitFlags |= (
# Ensure that the job will be terminated by the OS once the
# launcher exits, even if it doesn't terminate the job explicitly.
winapi.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
# Allow the debuggee to create its own jobs unrelated to ours.
winapi.JOB_OBJECT_LIMIT_BREAKAWAY_OK
)
winapi.kernel32.SetInformationJobObject(
job_handle,
winapi.JobObjectExtendedLimitInformation,
ctypes.pointer(job_info),
job_info_size,
)
process_handle = winapi.kernel32.OpenProcess(
winapi.PROCESS_TERMINATE | winapi.PROCESS_SET_QUOTA,
False,
process.pid,
)
winapi.kernel32.AssignProcessToJobObject(job_handle, process_handle)
except Exception:
log.swallow_exception("Failed to set up job object", level="warning")
atexit.register(kill)
launcher.channel.send_event(
"process",
{
"startMethod": "launch",
"isLocalProcess": True,
"systemProcessId": process.pid,
"name": process_name,
"pointerSize": struct.calcsize("P") * 8,
},
)
if redirect_output:
for category, fd, tee in [
("stdout", stdout_r, sys.stdout),
("stderr", stderr_r, sys.stderr),
]:
output.CaptureOutput(describe(), category, fd, tee)
close_fds.remove(fd)
wait_thread = threading.Thread(target=wait_for_exit, name="wait_for_exit()")
wait_thread.daemon = True
wait_thread.start()
finally:
for fd in close_fds:
try:
os.close(fd)
except Exception:
log.swallow_exception(level="warning")
def kill():
if process is None:
return
try:
if process.poll() is None:
log.info("Killing {0}", describe())
# Clean up the process tree
if sys.platform == "win32":
# On Windows, kill the job object.
winapi.kernel32.TerminateJobObject(job_handle, 0)
else:
# On POSIX, kill the debuggee's process group.
os.killpg(process.pid, signal.SIGKILL)
except Exception:
log.swallow_exception("Failed to kill {0}", describe())
def wait_for_exit():
try:
code = process.wait()
if sys.platform != "win32" and code < 0:
# On POSIX, if the process was terminated by a signal, Popen will use
# a negative returncode to indicate that - but the actual exit code of
# the process is always an unsigned number, and can be determined by
# taking the lowest 8 bits of that negative returncode.
code &= 0xFF
except Exception:
log.swallow_exception("Couldn't determine process exit code")
code = -1
log.info("{0} exited with code {1}", describe(), code)
output.wait_for_remaining_output()
# Determine whether we should wait or not before sending "exited", so that any
# follow-up "terminate" requests don't affect the predicates.
should_wait = any(pred(code) for pred in wait_on_exit_predicates)
try:
launcher.channel.send_event("exited", {"exitCode": code})
except Exception:
pass
if should_wait:
_wait_for_user_input()
try:
launcher.channel.send_event("terminated")
except Exception:
pass
def _wait_for_user_input():
if sys.stdout and sys.stdin and sys.stdin.isatty():
from debugpy.common import log
try:
import msvcrt
except ImportError:
can_getch = False
else:
can_getch = True
if can_getch:
log.debug("msvcrt available - waiting for user input via getch()")
sys.stdout.write("Press any key to continue . . . ")
sys.stdout.flush()
msvcrt.getch()
else:
log.debug("msvcrt not available - waiting for user input via read()")
sys.stdout.write("Press Enter to continue . . . ")
sys.stdout.flush()
sys.stdin.read(1)
| 8,574 | Python | 33.3 | 89 | 0.553651 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/adapter/clients.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
from __future__ import annotations
import atexit
import os
import sys
import debugpy
from debugpy import adapter, common, launcher
from debugpy.common import json, log, messaging, sockets
from debugpy.adapter import components, servers, sessions
class Client(components.Component):
"""Handles the client side of a debug session."""
message_handler = components.Component.message_handler
known_subprocesses: set[servers.Connection]
"""Server connections to subprocesses that this client has been made aware of.
"""
class Capabilities(components.Capabilities):
PROPERTIES = {
"supportsVariableType": False,
"supportsVariablePaging": False,
"supportsRunInTerminalRequest": False,
"supportsMemoryReferences": False,
"supportsArgsCanBeInterpretedByShell": False,
}
class Expectations(components.Capabilities):
PROPERTIES = {
"locale": "en-US",
"linesStartAt1": True,
"columnsStartAt1": True,
"pathFormat": json.enum("path", optional=True), # we don't support "uri"
}
def __init__(self, sock):
if sock == "stdio":
log.info("Connecting to client over stdio...", self)
stream = messaging.JsonIOStream.from_stdio()
# Make sure that nothing else tries to interfere with the stdio streams
# that are going to be used for DAP communication from now on.
sys.stdin = stdin = open(os.devnull, "r")
atexit.register(stdin.close)
sys.stdout = stdout = open(os.devnull, "w")
atexit.register(stdout.close)
else:
stream = messaging.JsonIOStream.from_socket(sock)
with sessions.Session() as session:
super().__init__(session, stream)
self.client_id = None
"""ID of the connecting client. This can be 'test' while running tests."""
self.has_started = False
"""Whether the "launch" or "attach" request was received from the client, and
fully handled.
"""
self.start_request = None
"""The "launch" or "attach" request as received from the client.
"""
self._initialize_request = None
"""The "initialize" request as received from the client, to propagate to the
server later."""
self._deferred_events = []
"""Deferred events from the launcher and the server that must be propagated
only if and when the "launch" or "attach" response is sent.
"""
self._forward_terminate_request = False
self.known_subprocesses = set()
session.client = self
session.register()
# For the transition period, send the telemetry events with both old and new
# name. The old one should be removed once the new one lights up.
self.channel.send_event(
"output",
{
"category": "telemetry",
"output": "ptvsd",
"data": {"packageVersion": debugpy.__version__},
},
)
self.channel.send_event(
"output",
{
"category": "telemetry",
"output": "debugpy",
"data": {"packageVersion": debugpy.__version__},
},
)
def propagate_after_start(self, event):
# pydevd starts sending events as soon as we connect, but the client doesn't
# expect to see any until it receives the response to "launch" or "attach"
# request. If client is not ready yet, save the event instead of propagating
# it immediately.
if self._deferred_events is not None:
self._deferred_events.append(event)
log.debug("Propagation deferred.")
else:
self.client.channel.propagate(event)
def _propagate_deferred_events(self):
log.debug("Propagating deferred events to {0}...", self.client)
for event in self._deferred_events:
log.debug("Propagating deferred {0}", event.describe())
self.client.channel.propagate(event)
log.info("All deferred events propagated to {0}.", self.client)
self._deferred_events = None
# Generic event handler. There are no specific handlers for client events, because
# there are no events from the client in DAP - but we propagate them if we can, in
# case some events appear in future protocol versions.
@message_handler
def event(self, event):
if self.server:
self.server.channel.propagate(event)
# Generic request handler, used if there's no specific handler below.
@message_handler
def request(self, request):
return self.server.channel.delegate(request)
@message_handler
def initialize_request(self, request):
if self._initialize_request is not None:
raise request.isnt_valid("Session is already initialized")
self.client_id = request("clientID", "")
self.capabilities = self.Capabilities(self, request)
self.expectations = self.Expectations(self, request)
self._initialize_request = request
exception_breakpoint_filters = [
{
"filter": "raised",
"label": "Raised Exceptions",
"default": False,
"description": "Break whenever any exception is raised.",
},
{
"filter": "uncaught",
"label": "Uncaught Exceptions",
"default": True,
"description": "Break when the process is exiting due to unhandled exception.",
},
{
"filter": "userUnhandled",
"label": "User Uncaught Exceptions",
"default": False,
"description": "Break when exception escapes into library code.",
},
]
return {
"supportsCompletionsRequest": True,
"supportsConditionalBreakpoints": True,
"supportsConfigurationDoneRequest": True,
"supportsDebuggerProperties": True,
"supportsDelayedStackTraceLoading": True,
"supportsEvaluateForHovers": True,
"supportsExceptionInfoRequest": True,
"supportsExceptionOptions": True,
"supportsFunctionBreakpoints": True,
"supportsHitConditionalBreakpoints": True,
"supportsLogPoints": True,
"supportsModulesRequest": True,
"supportsSetExpression": True,
"supportsSetVariable": True,
"supportsValueFormattingOptions": True,
"supportsTerminateRequest": True,
"supportsGotoTargetsRequest": True,
"supportsClipboardContext": True,
"exceptionBreakpointFilters": exception_breakpoint_filters,
"supportsStepInTargetsRequest": True,
}
# Common code for "launch" and "attach" request handlers.
#
# See https://github.com/microsoft/vscode/issues/4902#issuecomment-368583522
# for the sequence of request and events necessary to orchestrate the start.
def _start_message_handler(f):
@components.Component.message_handler
def handle(self, request):
assert request.is_request("launch", "attach")
if self._initialize_request is None:
raise request.isnt_valid("Session is not initialized yet")
if self.launcher or self.server:
raise request.isnt_valid("Session is already started")
self.session.no_debug = request("noDebug", json.default(False))
if self.session.no_debug:
servers.dont_wait_for_first_connection()
self.session.debug_options = debug_options = set(
request("debugOptions", json.array(str))
)
f(self, request)
if request.response is not None:
return
if self.server:
self.server.initialize(self._initialize_request)
self._initialize_request = None
arguments = request.arguments
if self.launcher:
redirecting = arguments.get("console") == "internalConsole"
if "RedirectOutput" in debug_options:
# The launcher is doing output redirection, so we don't need the
# server to do it, as well.
arguments = dict(arguments)
arguments["debugOptions"] = list(
debug_options - {"RedirectOutput"}
)
redirecting = True
if arguments.get("redirectOutput"):
arguments = dict(arguments)
del arguments["redirectOutput"]
redirecting = True
arguments["isOutputRedirected"] = redirecting
# pydevd doesn't send "initialized", and responds to the start request
# immediately, without waiting for "configurationDone". If it changes
# to conform to the DAP spec, we'll need to defer waiting for response.
try:
self.server.channel.request(request.command, arguments)
except messaging.NoMoreMessages:
# Server closed connection before we could receive the response to
# "attach" or "launch" - this can happen when debuggee exits shortly
# after starting. It's not an error, but we can't do anything useful
# here at this point, either, so just bail out.
request.respond({})
self.session.finalize(
"{0} disconnected before responding to {1}".format(
self.server,
json.repr(request.command),
)
)
return
except messaging.MessageHandlingError as exc:
exc.propagate(request)
if self.session.no_debug:
self.start_request = request
self.has_started = True
request.respond({})
self._propagate_deferred_events()
return
# Let the client know that it can begin configuring the adapter.
self.channel.send_event("initialized")
self.start_request = request
return messaging.NO_RESPONSE # will respond on "configurationDone"
return handle
@_start_message_handler
def launch_request(self, request):
from debugpy.adapter import launchers
if self.session.id != 1 or len(servers.connections()):
raise request.cant_handle('"attach" expected')
debug_options = set(request("debugOptions", json.array(str)))
# Handling of properties that can also be specified as legacy "debugOptions" flags.
# If property is explicitly set to false, but the flag is in "debugOptions", treat
# it as an error. Returns None if the property wasn't explicitly set either way.
def property_or_debug_option(prop_name, flag_name):
assert prop_name[0].islower() and flag_name[0].isupper()
value = request(prop_name, bool, optional=True)
if value == ():
value = None
if flag_name in debug_options:
if value is False:
raise request.isnt_valid(
'{0}:false and "debugOptions":[{1}] are mutually exclusive',
json.repr(prop_name),
json.repr(flag_name),
)
value = True
return value
# "pythonPath" is a deprecated legacy spelling. If "python" is missing, then try
# the alternative. But if both are missing, the error message should say "python".
python_key = "python"
if python_key in request:
if "pythonPath" in request:
raise request.isnt_valid(
'"pythonPath" is not valid if "python" is specified'
)
elif "pythonPath" in request:
python_key = "pythonPath"
python = request(python_key, json.array(str, vectorize=True, size=(0,)))
if not len(python):
python = [sys.executable]
python += request("pythonArgs", json.array(str, size=(0,)))
request.arguments["pythonArgs"] = python[1:]
request.arguments["python"] = python
launcher_python = request("debugLauncherPython", str, optional=True)
if launcher_python == ():
launcher_python = python[0]
program = module = code = ()
if "program" in request:
program = request("program", str)
args = [program]
request.arguments["processName"] = program
if "module" in request:
module = request("module", str)
args = ["-m", module]
request.arguments["processName"] = module
if "code" in request:
code = request("code", json.array(str, vectorize=True, size=(1,)))
args = ["-c", "\n".join(code)]
request.arguments["processName"] = "-c"
num_targets = len([x for x in (program, module, code) if x != ()])
if num_targets == 0:
raise request.isnt_valid(
'either "program", "module", or "code" must be specified'
)
elif num_targets != 1:
raise request.isnt_valid(
'"program", "module", and "code" are mutually exclusive'
)
console = request(
"console",
json.enum(
"internalConsole",
"integratedTerminal",
"externalTerminal",
optional=True,
),
)
console_title = request("consoleTitle", json.default("Python Debug Console"))
# Propagate "args" via CLI so that shell expansion can be applied if requested.
target_args = request("args", json.array(str, vectorize=True))
args += target_args
# If "args" was a single string rather than an array, shell expansion must be applied.
shell_expand_args = len(target_args) > 0 and isinstance(
request.arguments["args"], str
)
if shell_expand_args:
if not self.capabilities["supportsArgsCanBeInterpretedByShell"]:
raise request.isnt_valid(
'Shell expansion in "args" is not supported by the client'
)
if console == "internalConsole":
raise request.isnt_valid(
'Shell expansion in "args" is not available for "console":"internalConsole"'
)
cwd = request("cwd", str, optional=True)
if cwd == ():
# If it's not specified, but we're launching a file rather than a module,
# and the specified path has a directory in it, use that.
cwd = None if program == () else (os.path.dirname(program) or None)
sudo = bool(property_or_debug_option("sudo", "Sudo"))
if sudo and sys.platform == "win32":
raise request.cant_handle('"sudo":true is not supported on Windows.')
on_terminate = request("onTerminate", str, optional=True)
if on_terminate:
self._forward_terminate_request = on_terminate == "KeyboardInterrupt"
launcher_path = request("debugLauncherPath", os.path.dirname(launcher.__file__))
adapter_host = request("debugAdapterHost", "127.0.0.1")
try:
servers.serve(adapter_host)
except Exception as exc:
raise request.cant_handle(
"{0} couldn't create listener socket for servers: {1}",
self.session,
exc,
)
launchers.spawn_debuggee(
self.session,
request,
[launcher_python],
launcher_path,
adapter_host,
args,
shell_expand_args,
cwd,
console,
console_title,
sudo,
)
@_start_message_handler
def attach_request(self, request):
if self.session.no_debug:
raise request.isnt_valid('"noDebug" is not supported for "attach"')
host = request("host", str, optional=True)
port = request("port", int, optional=True)
listen = request("listen", dict, optional=True)
connect = request("connect", dict, optional=True)
pid = request("processId", (int, str), optional=True)
sub_pid = request("subProcessId", int, optional=True)
on_terminate = request("onTerminate", bool, optional=True)
if on_terminate:
self._forward_terminate_request = on_terminate == "KeyboardInterrupt"
if host != () or port != ():
if listen != ():
raise request.isnt_valid(
'"listen" and "host"/"port" are mutually exclusive'
)
if connect != ():
raise request.isnt_valid(
'"connect" and "host"/"port" are mutually exclusive'
)
if listen != ():
if connect != ():
raise request.isnt_valid(
'"listen" and "connect" are mutually exclusive'
)
if pid != ():
raise request.isnt_valid(
'"listen" and "processId" are mutually exclusive'
)
if sub_pid != ():
raise request.isnt_valid(
'"listen" and "subProcessId" are mutually exclusive'
)
if pid != () and sub_pid != ():
raise request.isnt_valid(
'"processId" and "subProcessId" are mutually exclusive'
)
if listen != ():
if servers.is_serving():
raise request.isnt_valid(
'Multiple concurrent "listen" sessions are not supported'
)
host = listen("host", "127.0.0.1")
port = listen("port", int)
adapter.access_token = None
host, port = servers.serve(host, port)
else:
if not servers.is_serving():
servers.serve()
host, port = servers.listener.getsockname()
# There are four distinct possibilities here.
#
# If "processId" is specified, this is attach-by-PID. We need to inject the
# debug server into the designated process, and then wait until it connects
# back to us. Since the injected server can crash, there must be a timeout.
#
# If "subProcessId" is specified, this is attach to a known subprocess, likely
# in response to a "debugpyAttach" event. If so, the debug server should be
# connected already, and thus the wait timeout is zero.
#
# If "listen" is specified, this is attach-by-socket with the server expected
# to connect to the adapter via debugpy.connect(). There is no PID known in
# advance, so just wait until the first server connection indefinitely, with
# no timeout.
#
# If "connect" is specified, this is attach-by-socket in which the server has
# spawned the adapter via debugpy.listen(). There is no PID known to the client
# in advance, but the server connection should be either be there already, or
# the server should be connecting shortly, so there must be a timeout.
#
# In the last two cases, if there's more than one server connection already,
# this is a multiprocess re-attach. The client doesn't know the PID, so we just
# connect it to the oldest server connection that we have - in most cases, it
# will be the one for the root debuggee process, but if it has exited already,
# it will be some subprocess.
if pid != ():
if not isinstance(pid, int):
try:
pid = int(pid)
except Exception:
raise request.isnt_valid('"processId" must be parseable as int')
debugpy_args = request("debugpyArgs", json.array(str))
def on_output(category, output):
self.channel.send_event(
"output",
{
"category": category,
"output": output,
},
)
try:
servers.inject(pid, debugpy_args, on_output)
except Exception as e:
log.swallow_exception()
self.session.finalize(
"Error when trying to attach to PID:\n%s" % (str(e),)
)
return
timeout = common.PROCESS_SPAWN_TIMEOUT
pred = lambda conn: conn.pid == pid
else:
if sub_pid == ():
pred = lambda conn: True
timeout = common.PROCESS_SPAWN_TIMEOUT if listen == () else None
else:
pred = lambda conn: conn.pid == sub_pid
timeout = 0
self.channel.send_event("debugpyWaitingForServer", {"host": host, "port": port})
conn = servers.wait_for_connection(self.session, pred, timeout)
if conn is None:
if sub_pid != ():
# If we can't find a matching subprocess, it's not always an error -
# it might have already exited, or didn't even get a chance to connect.
# To prevent the client from complaining, pretend that the "attach"
# request was successful, but that the session terminated immediately.
request.respond({})
self.session.finalize(
'No known subprocess with "subProcessId":{0}'.format(sub_pid)
)
return
raise request.cant_handle(
(
"Timed out waiting for debug server to connect."
if timeout
else "There is no debug server connected to this adapter."
),
sub_pid,
)
try:
conn.attach_to_session(self.session)
except ValueError:
request.cant_handle("{0} is already being debugged.", conn)
@message_handler
def configurationDone_request(self, request):
if self.start_request is None or self.has_started:
request.cant_handle(
'"configurationDone" is only allowed during handling of a "launch" '
'or an "attach" request'
)
try:
self.has_started = True
try:
result = self.server.channel.delegate(request)
except messaging.NoMoreMessages:
# Server closed connection before we could receive the response to
# "configurationDone" - this can happen when debuggee exits shortly
# after starting. It's not an error, but we can't do anything useful
# here at this point, either, so just bail out.
request.respond({})
self.start_request.respond({})
self.session.finalize(
"{0} disconnected before responding to {1}".format(
self.server,
json.repr(request.command),
)
)
return
else:
request.respond(result)
except messaging.MessageHandlingError as exc:
self.start_request.cant_handle(str(exc))
finally:
if self.start_request.response is None:
self.start_request.respond({})
self._propagate_deferred_events()
# Notify the client of any child processes of the debuggee that aren't already
# being debugged.
for conn in servers.connections():
if conn.server is None and conn.ppid == self.session.pid:
self.notify_of_subprocess(conn)
@message_handler
def evaluate_request(self, request):
propagated_request = self.server.channel.propagate(request)
def handle_response(response):
request.respond(response.body)
propagated_request.on_response(handle_response)
return messaging.NO_RESPONSE
@message_handler
def pause_request(self, request):
request.arguments["threadId"] = "*"
return self.server.channel.delegate(request)
@message_handler
def continue_request(self, request):
request.arguments["threadId"] = "*"
try:
return self.server.channel.delegate(request)
except messaging.NoMoreMessages:
# pydevd can sometimes allow the debuggee to exit before the queued
# "continue" response gets sent. Thus, a failed "continue" response
# indicating that the server disconnected should be treated as success.
return {"allThreadsContinued": True}
@message_handler
def debugpySystemInfo_request(self, request):
result = {"debugpy": {"version": debugpy.__version__}}
if self.server:
try:
pydevd_info = self.server.channel.request("pydevdSystemInfo")
except Exception:
# If the server has already disconnected, or couldn't handle it,
# report what we've got.
pass
else:
result.update(pydevd_info)
return result
@message_handler
def terminate_request(self, request):
if self._forward_terminate_request:
# According to the spec, terminate should try to do a gracefull shutdown.
# We do this in the server by interrupting the main thread with a Ctrl+C.
# To force the kill a subsequent request would do a disconnect.
#
# We only do this if the onTerminate option is set though (the default
# is a hard-kill for the process and subprocesses).
return self.server.channel.delegate(request)
self.session.finalize('client requested "terminate"', terminate_debuggee=True)
return {}
@message_handler
def disconnect_request(self, request):
terminate_debuggee = request("terminateDebuggee", bool, optional=True)
if terminate_debuggee == ():
terminate_debuggee = None
self.session.finalize('client requested "disconnect"', terminate_debuggee)
return {}
def notify_of_subprocess(self, conn):
log.info("{1} is a subprocess of {0}.", self, conn)
with self.session:
if self.start_request is None or conn in self.known_subprocesses:
return
if "processId" in self.start_request.arguments:
log.warning(
"Not reporting subprocess for {0}, because the parent process "
'was attached to using "processId" rather than "port".',
self.session,
)
return
log.info("Notifying {0} about {1}.", self, conn)
body = dict(self.start_request.arguments)
self.known_subprocesses.add(conn)
self.session.notify_changed()
for key in "processId", "listen", "preLaunchTask", "postDebugTask":
body.pop(key, None)
body["name"] = "Subprocess {0}".format(conn.pid)
body["request"] = "attach"
body["subProcessId"] = conn.pid
for key in "args", "processName", "pythonArgs":
body.pop(key, None)
host = body.pop("host", None)
port = body.pop("port", None)
if "connect" not in body:
body["connect"] = {}
if "host" not in body["connect"]:
body["connect"]["host"] = host if host is not None else "127.0.0.1"
if "port" not in body["connect"]:
if port is None:
_, port = listener.getsockname()
body["connect"]["port"] = port
self.channel.send_event("debugpyAttach", body)
def serve(host, port):
global listener
listener = sockets.serve("Client", Client, host, port)
return listener.getsockname()
def stop_serving():
try:
listener.close()
except Exception:
log.swallow_exception(level="warning")
| 29,037 | Python | 38.997245 | 96 | 0.560526 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/adapter/launchers.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
import os
import subprocess
import sys
from debugpy import adapter, common
from debugpy.common import log, messaging, sockets
from debugpy.adapter import components, servers
class Launcher(components.Component):
"""Handles the launcher side of a debug session."""
message_handler = components.Component.message_handler
def __init__(self, session, stream):
with session:
assert not session.launcher
super().__init__(session, stream)
self.pid = None
"""Process ID of the debuggee process, as reported by the launcher."""
self.exit_code = None
"""Exit code of the debuggee process."""
session.launcher = self
@message_handler
def process_event(self, event):
self.pid = event("systemProcessId", int)
self.client.propagate_after_start(event)
@message_handler
def output_event(self, event):
self.client.propagate_after_start(event)
@message_handler
def exited_event(self, event):
self.exit_code = event("exitCode", int)
# We don't want to tell the client about this just yet, because it will then
# want to disconnect, and the launcher might still be waiting for keypress
# (if wait-on-exit was enabled). Instead, we'll report the event when we
# receive "terminated" from the launcher, right before it exits.
@message_handler
def terminated_event(self, event):
try:
self.client.channel.send_event("exited", {"exitCode": self.exit_code})
except Exception:
pass
self.channel.close()
def terminate_debuggee(self):
with self.session:
if self.exit_code is None:
try:
self.channel.request("terminate")
except Exception:
pass
def spawn_debuggee(
session,
start_request,
python,
launcher_path,
adapter_host,
args,
shell_expand_args,
cwd,
console,
console_title,
sudo,
):
# -E tells sudo to propagate environment variables to the target process - this
# is necessary for launcher to get DEBUGPY_LAUNCHER_PORT and DEBUGPY_LOG_DIR.
cmdline = ["sudo", "-E"] if sudo else []
cmdline += python
cmdline += [launcher_path]
env = {}
arguments = dict(start_request.arguments)
if not session.no_debug:
_, arguments["port"] = servers.listener.getsockname()
arguments["adapterAccessToken"] = adapter.access_token
def on_launcher_connected(sock):
listener.close()
stream = messaging.JsonIOStream.from_socket(sock)
Launcher(session, stream)
try:
listener = sockets.serve(
"Launcher", on_launcher_connected, adapter_host, backlog=1
)
except Exception as exc:
raise start_request.cant_handle(
"{0} couldn't create listener socket for launcher: {1}", session, exc
)
try:
launcher_host, launcher_port = listener.getsockname()
launcher_addr = (
launcher_port
if launcher_host == "127.0.0.1"
else f"{launcher_host}:{launcher_port}"
)
cmdline += [str(launcher_addr), "--"]
cmdline += args
if log.log_dir is not None:
env[str("DEBUGPY_LOG_DIR")] = log.log_dir
if log.stderr.levels != {"warning", "error"}:
env[str("DEBUGPY_LOG_STDERR")] = str(" ".join(log.stderr.levels))
if console == "internalConsole":
log.info("{0} spawning launcher: {1!r}", session, cmdline)
try:
# If we are talking to the client over stdio, sys.stdin and sys.stdout
# are redirected to avoid mangling the DAP message stream. Make sure
# the launcher also respects that.
subprocess.Popen(
cmdline,
cwd=cwd,
env=dict(list(os.environ.items()) + list(env.items())),
stdin=sys.stdin,
stdout=sys.stdout,
stderr=sys.stderr,
)
except Exception as exc:
raise start_request.cant_handle("Failed to spawn launcher: {0}", exc)
else:
log.info('{0} spawning launcher via "runInTerminal" request.', session)
session.client.capabilities.require("supportsRunInTerminalRequest")
kinds = {"integratedTerminal": "integrated", "externalTerminal": "external"}
request_args = {
"kind": kinds[console],
"title": console_title,
"args": cmdline,
"env": env,
}
if cwd is not None:
request_args["cwd"] = cwd
if shell_expand_args:
request_args["argsCanBeInterpretedByShell"] = True
try:
# It is unspecified whether this request receives a response immediately, or only
# after the spawned command has completed running, so do not block waiting for it.
session.client.channel.send_request("runInTerminal", request_args)
except messaging.MessageHandlingError as exc:
exc.propagate(start_request)
# If using sudo, it might prompt for password, and launcher won't start running
# until the user enters it, so don't apply timeout in that case.
if not session.wait_for(
lambda: session.launcher,
timeout=(None if sudo else common.PROCESS_SPAWN_TIMEOUT),
):
raise start_request.cant_handle("Timed out waiting for launcher to connect")
try:
session.launcher.channel.request(start_request.command, arguments)
except messaging.MessageHandlingError as exc:
exc.propagate(start_request)
if not session.wait_for(
lambda: session.launcher.pid is not None,
timeout=common.PROCESS_SPAWN_TIMEOUT,
):
raise start_request.cant_handle(
'Timed out waiting for "process" event from launcher'
)
if session.no_debug:
return
# Wait for the first incoming connection regardless of the PID - it won't
# necessarily match due to the use of stubs like py.exe or "conda run".
conn = servers.wait_for_connection(
session, lambda conn: True, timeout=common.PROCESS_SPAWN_TIMEOUT
)
if conn is None:
raise start_request.cant_handle("Timed out waiting for debuggee to spawn")
conn.attach_to_session(session)
finally:
listener.close()
| 6,864 | Python | 34.755208 | 98 | 0.594988 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/adapter/__init__.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
from __future__ import annotations
import typing
if typing.TYPE_CHECKING:
__all__: list[str]
__all__ = []
access_token = None
"""Access token used to authenticate with this adapter."""
| 346 | Python | 22.133332 | 65 | 0.725434 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/adapter/components.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
import functools
from debugpy.common import json, log, messaging, util
ACCEPT_CONNECTIONS_TIMEOUT = 10
class ComponentNotAvailable(Exception):
def __init__(self, type):
super().__init__(f"{type.__name__} is not available")
class Component(util.Observable):
"""A component managed by a debug adapter: client, launcher, or debug server.
Every component belongs to a Session, which is used for synchronization and
shared data.
Every component has its own message channel, and provides message handlers for
that channel. All handlers should be decorated with @Component.message_handler,
which ensures that Session is locked for the duration of the handler. Thus, only
one handler is running at any given time across all components, unless the lock
is released explicitly or via Session.wait_for().
Components report changes to their attributes to Session, allowing one component
to wait_for() a change caused by another component.
"""
def __init__(self, session, stream=None, channel=None):
assert (stream is None) ^ (channel is None)
try:
lock_held = session.lock.acquire(blocking=False)
assert lock_held, "__init__ of a Component subclass must lock its Session"
finally:
session.lock.release()
super().__init__()
self.session = session
if channel is None:
stream.name = str(self)
channel = messaging.JsonMessageChannel(stream, self)
channel.start()
else:
channel.name = channel.stream.name = str(self)
channel.handlers = self
self.channel = channel
self.is_connected = True
# Do this last to avoid triggering useless notifications for assignments above.
self.observers += [lambda *_: self.session.notify_changed()]
def __str__(self):
return f"{type(self).__name__}[{self.session.id}]"
@property
def client(self):
return self.session.client
@property
def launcher(self):
return self.session.launcher
@property
def server(self):
return self.session.server
def wait_for(self, *args, **kwargs):
return self.session.wait_for(*args, **kwargs)
@staticmethod
def message_handler(f):
"""Applied to a message handler to automatically lock and unlock the session
for its duration, and to validate the session state.
If the handler raises ComponentNotAvailable or JsonIOError, converts it to
Message.cant_handle().
"""
@functools.wraps(f)
def lock_and_handle(self, message):
try:
with self.session:
return f(self, message)
except ComponentNotAvailable as exc:
raise message.cant_handle("{0}", exc, silent=True)
except messaging.MessageHandlingError as exc:
if exc.cause is message:
raise
else:
exc.propagate(message)
except messaging.JsonIOError as exc:
raise message.cant_handle(
"{0} disconnected unexpectedly", exc.stream.name, silent=True
)
return lock_and_handle
def disconnect(self):
with self.session:
self.is_connected = False
self.session.finalize("{0} has disconnected".format(self))
def missing(session, type):
class Missing(object):
"""A dummy component that raises ComponentNotAvailable whenever some
attribute is accessed on it.
"""
__getattr__ = __setattr__ = lambda self, *_: report()
__bool__ = __nonzero__ = lambda self: False
def report():
try:
raise ComponentNotAvailable(type)
except Exception as exc:
log.reraise_exception("{0} in {1}", exc, session)
return Missing()
class Capabilities(dict):
"""A collection of feature flags for a component. Corresponds to JSON properties
in the DAP "initialize" request or response, other than those that identify the
party.
"""
PROPERTIES = {}
"""JSON property names and default values for the the capabilities represented
by instances of this class. Keys are names, and values are either default values
or validators.
If the value is callable, it must be a JSON validator; see debugpy.common.json for
details. If the value is not callable, it is as if json.default(value) validator
was used instead.
"""
def __init__(self, component, message):
"""Parses an "initialize" request or response and extracts the feature flags.
For every "X" in self.PROPERTIES, sets self["X"] to the corresponding value
from message.payload if it's present there, or to the default value otherwise.
"""
assert message.is_request("initialize") or message.is_response("initialize")
self.component = component
payload = message.payload
for name, validate in self.PROPERTIES.items():
value = payload.get(name, ())
if not callable(validate):
validate = json.default(validate)
try:
value = validate(value)
except Exception as exc:
raise message.isnt_valid("{0} {1}", json.repr(name), exc)
assert (
value != ()
), f"{validate} must provide a default value for missing properties."
self[name] = value
log.debug("{0}", self)
def __repr__(self):
return f"{type(self).__name__}: {json.repr(dict(self))}"
def require(self, *keys):
for key in keys:
if not self[key]:
raise messaging.MessageHandlingError(
f"{self.component} does not have capability {json.repr(key)}",
)
| 6,081 | Python | 32.054348 | 87 | 0.617333 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/adapter/__main__.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
import argparse
import atexit
import codecs
import locale
import os
import sys
# WARNING: debugpy and submodules must not be imported on top level in this module,
# and should be imported locally inside main() instead.
def main(args):
# If we're talking DAP over stdio, stderr is not guaranteed to be read from,
# so disable it to avoid the pipe filling and locking up. This must be done
# as early as possible, before the logging module starts writing to it.
if args.port is None:
sys.stderr = stderr = open(os.devnull, "w")
atexit.register(stderr.close)
from debugpy import adapter
from debugpy.common import json, log, sockets
from debugpy.adapter import clients, servers, sessions
if args.for_server is not None:
if os.name == "posix":
# On POSIX, we need to leave the process group and its session, and then
# daemonize properly by double-forking (first fork already happened when
# this process was spawned).
# NOTE: if process is already the session leader, then
# setsid would fail with `operation not permitted`
if os.getsid(os.getpid()) != os.getpid():
os.setsid()
if os.fork() != 0:
sys.exit(0)
for stdio in sys.stdin, sys.stdout, sys.stderr:
if stdio is not None:
stdio.close()
if args.log_stderr:
log.stderr.levels |= set(log.LEVELS)
if args.log_dir is not None:
log.log_dir = args.log_dir
log.to_file(prefix="debugpy.adapter")
log.describe_environment("debugpy.adapter startup environment:")
servers.access_token = args.server_access_token
if args.for_server is None:
adapter.access_token = codecs.encode(os.urandom(32), "hex").decode("ascii")
endpoints = {}
try:
client_host, client_port = clients.serve(args.host, args.port)
except Exception as exc:
if args.for_server is None:
raise
endpoints = {"error": "Can't listen for client connections: " + str(exc)}
else:
endpoints["client"] = {"host": client_host, "port": client_port}
if args.for_server is not None:
try:
server_host, server_port = servers.serve()
except Exception as exc:
endpoints = {"error": "Can't listen for server connections: " + str(exc)}
else:
endpoints["server"] = {"host": server_host, "port": server_port}
log.info(
"Sending endpoints info to debug server at localhost:{0}:\n{1}",
args.for_server,
json.repr(endpoints),
)
try:
sock = sockets.create_client()
try:
sock.settimeout(None)
sock.connect(("127.0.0.1", args.for_server))
sock_io = sock.makefile("wb", 0)
try:
sock_io.write(json.dumps(endpoints).encode("utf-8"))
finally:
sock_io.close()
finally:
sockets.close_socket(sock)
except Exception:
log.reraise_exception("Error sending endpoints info to debug server:")
if "error" in endpoints:
log.error("Couldn't set up endpoints; exiting.")
sys.exit(1)
listener_file = os.getenv("DEBUGPY_ADAPTER_ENDPOINTS")
if listener_file is not None:
log.info(
"Writing endpoints info to {0!r}:\n{1}", listener_file, json.repr(endpoints)
)
def delete_listener_file():
log.info("Listener ports closed; deleting {0!r}", listener_file)
try:
os.remove(listener_file)
except Exception:
log.swallow_exception(
"Failed to delete {0!r}", listener_file, level="warning"
)
try:
with open(listener_file, "w") as f:
atexit.register(delete_listener_file)
print(json.dumps(endpoints), file=f)
except Exception:
log.reraise_exception("Error writing endpoints info to file:")
if args.port is None:
clients.Client("stdio")
# These must be registered after the one above, to ensure that the listener sockets
# are closed before the endpoint info file is deleted - this way, another process
# can wait for the file to go away as a signal that the ports are no longer in use.
atexit.register(servers.stop_serving)
atexit.register(clients.stop_serving)
servers.wait_until_disconnected()
log.info("All debug servers disconnected; waiting for remaining sessions...")
sessions.wait_until_ended()
log.info("All debug sessions have ended; exiting.")
def _parse_argv(argv):
parser = argparse.ArgumentParser()
parser.add_argument(
"--for-server", type=int, metavar="PORT", help=argparse.SUPPRESS
)
parser.add_argument(
"--port",
type=int,
default=None,
metavar="PORT",
help="start the adapter in debugServer mode on the specified port",
)
parser.add_argument(
"--host",
type=str,
default="127.0.0.1",
metavar="HOST",
help="start the adapter in debugServer mode on the specified host",
)
parser.add_argument(
"--access-token", type=str, help="access token expected from the server"
)
parser.add_argument(
"--server-access-token", type=str, help="access token expected by the server"
)
parser.add_argument(
"--log-dir",
type=str,
metavar="DIR",
help="enable logging and use DIR to save adapter logs",
)
parser.add_argument(
"--log-stderr", action="store_true", help="enable logging to stderr"
)
args = parser.parse_args(argv[1:])
if args.port is None:
if args.log_stderr:
parser.error("--log-stderr requires --port")
if args.for_server is not None:
parser.error("--for-server requires --port")
return args
if __name__ == "__main__":
# debugpy can also be invoked directly rather than via -m. In this case, the first
# entry on sys.path is the one added automatically by Python for the directory
# containing this file. This means that import debugpy will not work, since we need
# the parent directory of debugpy/ to be in sys.path, rather than debugpy/adapter/.
#
# The other issue is that many other absolute imports will break, because they
# will be resolved relative to debugpy/adapter/ - e.g. `import state` will then try
# to import debugpy/adapter/state.py.
#
# To fix both, we need to replace the automatically added entry such that it points
# at parent directory of debugpy/ instead of debugpy/adapter, import debugpy with that
# in sys.path, and then remove the first entry entry altogether, so that it doesn't
# affect any further imports we might do. For example, suppose the user did:
#
# python /foo/bar/debugpy/adapter ...
#
# At the beginning of this script, sys.path will contain "/foo/bar/debugpy/adapter"
# as the first entry. What we want is to replace it with "/foo/bar', then import
# debugpy with that in effect, and then remove the replaced entry before any more
# code runs. The imported debugpy module will remain in sys.modules, and thus all
# future imports of it or its submodules will resolve accordingly.
if "debugpy" not in sys.modules:
# Do not use dirname() to walk up - this can be a relative path, e.g. ".".
sys.path[0] = sys.path[0] + "/../../"
__import__("debugpy")
del sys.path[0]
# Apply OS-global and user-specific locale settings.
try:
locale.setlocale(locale.LC_ALL, "")
except Exception:
# On POSIX, locale is set via environment variables, and this can fail if
# those variables reference a non-existing locale. Ignore and continue using
# the default "C" locale if so.
pass
main(_parse_argv(sys.argv))
| 8,257 | Python | 35.219298 | 90 | 0.619232 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/adapter/servers.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
from __future__ import annotations
import os
import subprocess
import sys
import threading
import time
import debugpy
from debugpy import adapter
from debugpy.common import json, log, messaging, sockets
from debugpy.adapter import components
import traceback
import io
access_token = None
"""Access token used to authenticate with the servers."""
listener = None
"""Listener socket that accepts server connections."""
_lock = threading.RLock()
_connections = []
"""All servers that are connected to this adapter, in order in which they connected.
"""
_connections_changed = threading.Event()
class Connection(object):
"""A debug server that is connected to the adapter.
Servers that are not participating in a debug session are managed directly by the
corresponding Connection instance.
Servers that are participating in a debug session are managed by that sessions's
Server component instance, but Connection object remains, and takes over again
once the session ends.
"""
disconnected: bool
process_replaced: bool
"""Whether this is a connection to a process that is being replaced in situ
by another process, e.g. via exec().
"""
server: Server | None
"""The Server component, if this debug server belongs to Session.
"""
pid: int | None
ppid: int | None
channel: messaging.JsonMessageChannel
def __init__(self, sock):
from debugpy.adapter import sessions
self.disconnected = False
self.process_replaced = False
self.server = None
self.pid = None
stream = messaging.JsonIOStream.from_socket(sock, str(self))
self.channel = messaging.JsonMessageChannel(stream, self)
self.channel.start()
try:
self.authenticate()
info = self.channel.request("pydevdSystemInfo")
process_info = info("process", json.object())
self.pid = process_info("pid", int)
self.ppid = process_info("ppid", int, optional=True)
if self.ppid == ():
self.ppid = None
self.channel.name = stream.name = str(self)
with _lock:
# The server can disconnect concurrently before we get here, e.g. if
# it was force-killed. If the disconnect() handler has already run,
# don't register this server or report it, since there's nothing to
# deregister it.
if self.disconnected:
return
# An existing connection with the same PID and process_replaced == True
# corresponds to the process that replaced itself with this one, so it's
# not an error.
if any(
conn.pid == self.pid and not conn.process_replaced
for conn in _connections
):
raise KeyError(f"{self} is already connected to this adapter")
is_first_server = len(_connections) == 0
_connections.append(self)
_connections_changed.set()
except Exception:
log.swallow_exception("Failed to accept incoming server connection:")
self.channel.close()
# If this was the first server to connect, and the main thread is inside
# wait_until_disconnected(), we want to unblock it and allow it to exit.
dont_wait_for_first_connection()
# If we couldn't retrieve all the necessary info from the debug server,
# or there's a PID clash, we don't want to track this debuggee anymore,
# but we want to continue accepting connections.
return
parent_session = sessions.get(self.ppid)
if parent_session is None:
parent_session = sessions.get(self.pid)
if parent_session is None:
log.info("No active debug session for parent process of {0}.", self)
else:
if self.pid == parent_session.pid:
parent_server = parent_session.server
if not (parent_server and parent_server.connection.process_replaced):
log.error("{0} is not expecting replacement.", parent_session)
self.channel.close()
return
try:
parent_session.client.notify_of_subprocess(self)
return
except Exception:
# This might fail if the client concurrently disconnects from the parent
# session. We still want to keep the connection around, in case the
# client reconnects later. If the parent session was "launch", it'll take
# care of closing the remaining server connections.
log.swallow_exception(
"Failed to notify parent session about {0}:", self
)
# If we got to this point, the subprocess notification was either not sent,
# or not delivered successfully. For the first server, this is expected, since
# it corresponds to the root process, and there is no other debug session to
# notify. But subsequent server connections represent subprocesses, and those
# will not start running user code until the client tells them to. Since there
# isn't going to be a client without the notification, such subprocesses have
# to be unblocked.
if is_first_server:
return
log.info("No clients to wait for - unblocking {0}.", self)
try:
self.channel.request("initialize", {"adapterID": "debugpy"})
self.channel.request("attach", {"subProcessId": self.pid})
self.channel.request("configurationDone")
self.channel.request("disconnect")
except Exception:
log.swallow_exception("Failed to unblock orphaned subprocess:")
self.channel.close()
def __str__(self):
return "Server" + ("[?]" if self.pid is None else f"[pid={self.pid}]")
def authenticate(self):
if access_token is None and adapter.access_token is None:
return
auth = self.channel.request(
"pydevdAuthorize", {"debugServerAccessToken": access_token}
)
if auth["clientAccessToken"] != adapter.access_token:
self.channel.close()
raise RuntimeError('Mismatched "clientAccessToken"; server not authorized.')
def request(self, request):
raise request.isnt_valid(
"Requests from the debug server to the client are not allowed."
)
def event(self, event):
pass
def terminated_event(self, event):
self.channel.close()
def disconnect(self):
with _lock:
self.disconnected = True
if self.server is not None:
# If the disconnect happened while Server was being instantiated,
# we need to tell it, so that it can clean up via Session.finalize().
# It will also take care of deregistering the connection in that case.
self.server.disconnect()
elif self in _connections:
_connections.remove(self)
_connections_changed.set()
def attach_to_session(self, session):
"""Attaches this server to the specified Session as a Server component.
Raises ValueError if the server already belongs to some session.
"""
with _lock:
if self.server is not None:
raise ValueError
log.info("Attaching {0} to {1}", self, session)
self.server = Server(session, self)
class Server(components.Component):
"""Handles the debug server side of a debug session."""
message_handler = components.Component.message_handler
connection: Connection
class Capabilities(components.Capabilities):
PROPERTIES = {
"supportsCompletionsRequest": False,
"supportsConditionalBreakpoints": False,
"supportsConfigurationDoneRequest": False,
"supportsDataBreakpoints": False,
"supportsDelayedStackTraceLoading": False,
"supportsDisassembleRequest": False,
"supportsEvaluateForHovers": False,
"supportsExceptionInfoRequest": False,
"supportsExceptionOptions": False,
"supportsFunctionBreakpoints": False,
"supportsGotoTargetsRequest": False,
"supportsHitConditionalBreakpoints": False,
"supportsLoadedSourcesRequest": False,
"supportsLogPoints": False,
"supportsModulesRequest": False,
"supportsReadMemoryRequest": False,
"supportsRestartFrame": False,
"supportsRestartRequest": False,
"supportsSetExpression": False,
"supportsSetVariable": False,
"supportsStepBack": False,
"supportsStepInTargetsRequest": False,
"supportsTerminateRequest": True,
"supportsTerminateThreadsRequest": False,
"supportsValueFormattingOptions": False,
"exceptionBreakpointFilters": [],
"additionalModuleColumns": [],
"supportedChecksumAlgorithms": [],
}
def __init__(self, session, connection):
assert connection.server is None
with session:
assert not session.server
super().__init__(session, channel=connection.channel)
self.connection = connection
assert self.session.pid is None
if self.session.launcher and self.session.launcher.pid != self.pid:
log.info(
"Launcher reported PID={0}, but server reported PID={1}",
self.session.launcher.pid,
self.pid,
)
self.session.pid = self.pid
session.server = self
@property
def pid(self):
"""Process ID of the debuggee process, as reported by the server."""
return self.connection.pid
@property
def ppid(self):
"""Parent process ID of the debuggee process, as reported by the server."""
return self.connection.ppid
def initialize(self, request):
assert request.is_request("initialize")
self.connection.authenticate()
request = self.channel.propagate(request)
request.wait_for_response()
self.capabilities = self.Capabilities(self, request.response)
# Generic request handler, used if there's no specific handler below.
@message_handler
def request(self, request):
# Do not delegate requests from the server by default. There is a security
# boundary between the server and the adapter, and we cannot trust arbitrary
# requests sent over that boundary, since they may contain arbitrary code
# that the client will execute - e.g. "runInTerminal". The adapter must only
# propagate requests that it knows are safe.
raise request.isnt_valid(
"Requests from the debug server to the client are not allowed."
)
# Generic event handler, used if there's no specific handler below.
@message_handler
def event(self, event):
self.client.propagate_after_start(event)
@message_handler
def initialized_event(self, event):
# pydevd doesn't send it, but the adapter will send its own in any case.
pass
@message_handler
def process_event(self, event):
# If there is a launcher, it's handling the process event.
if not self.launcher:
self.client.propagate_after_start(event)
@message_handler
def continued_event(self, event):
# https://github.com/microsoft/ptvsd/issues/1530
#
# DAP specification says that a step request implies that only the thread on
# which that step occurred is resumed for the duration of the step. However,
# for VS compatibility, pydevd can operate in a mode that resumes all threads
# instead. This is set according to the value of "steppingResumesAllThreads"
# in "launch" or "attach" request, which defaults to true. If explicitly set
# to false, pydevd will only resume the thread that was stepping.
#
# To ensure that the client is aware that other threads are getting resumed in
# that mode, pydevd sends a "continued" event with "allThreadsResumed": true.
# when responding to a step request. This ensures correct behavior in VSCode
# and other DAP-conformant clients.
#
# On the other hand, VS does not follow the DAP specification in this regard.
# When it requests a step, it assumes that all threads will be resumed, and
# does not expect to see "continued" events explicitly reflecting that fact.
# If such events are sent regardless, VS behaves erratically. Thus, we have
# to suppress them specifically for VS.
if self.client.client_id not in ("visualstudio", "vsformac"):
self.client.propagate_after_start(event)
@message_handler
def exited_event(self, event: messaging.Event):
if event("pydevdReason", str, optional=True) == "processReplaced":
# The parent process used some API like exec() that replaced it with another
# process in situ. The connection will shut down immediately afterwards, but
# we need to keep the corresponding session alive long enough to report the
# subprocess to it.
self.connection.process_replaced = True
else:
# If there is a launcher, it's handling the exit code.
if not self.launcher:
self.client.propagate_after_start(event)
@message_handler
def terminated_event(self, event):
# Do not propagate this, since we'll report our own.
self.channel.close()
def detach_from_session(self):
with _lock:
self.is_connected = False
self.channel.handlers = self.connection
self.channel.name = self.channel.stream.name = str(self.connection)
self.connection.server = None
def disconnect(self):
if self.connection.process_replaced:
# Wait for the replacement server to connect to the adapter, and to report
# itself to the client for this session if there is one.
log.info("{0} is waiting for replacement subprocess.", self)
session = self.session
if not session.client or not session.client.is_connected:
wait_for_connection(
session, lambda conn: conn.pid == self.pid, timeout=30
)
else:
self.wait_for(
lambda: (
not session.client
or not session.client.is_connected
or any(
conn.pid == self.pid
for conn in session.client.known_subprocesses
)
),
timeout=30,
)
with _lock:
_connections.remove(self.connection)
_connections_changed.set()
super().disconnect()
def serve(host="127.0.0.1", port=0):
global listener
listener = sockets.serve("Server", Connection, host, port)
return listener.getsockname()
def is_serving():
return listener is not None
def stop_serving():
global listener
try:
if listener is not None:
listener.close()
listener = None
except Exception:
log.swallow_exception(level="warning")
def connections():
with _lock:
return list(_connections)
def wait_for_connection(session, predicate, timeout=None):
"""Waits until there is a server matching the specified predicate connected to
this adapter, and returns the corresponding Connection.
If there is more than one server connection already available, returns the oldest
one.
"""
def wait_for_timeout():
time.sleep(timeout)
wait_for_timeout.timed_out = True
with _lock:
_connections_changed.set()
wait_for_timeout.timed_out = timeout == 0
if timeout:
thread = threading.Thread(
target=wait_for_timeout, name="servers.wait_for_connection() timeout"
)
thread.daemon = True
thread.start()
if timeout != 0:
log.info("{0} waiting for connection from debug server...", session)
while True:
with _lock:
_connections_changed.clear()
conns = (conn for conn in _connections if predicate(conn))
conn = next(conns, None)
if conn is not None or wait_for_timeout.timed_out:
return conn
_connections_changed.wait()
def wait_until_disconnected():
"""Blocks until all debug servers disconnect from the adapter.
If there are no server connections, waits until at least one is established first,
before waiting for it to disconnect.
"""
while True:
_connections_changed.wait()
with _lock:
_connections_changed.clear()
if not len(_connections):
return
def dont_wait_for_first_connection():
"""Unblocks any pending wait_until_disconnected() call that is waiting on the
first server to connect.
"""
with _lock:
_connections_changed.set()
def inject(pid, debugpy_args, on_output):
host, port = listener.getsockname()
cmdline = [
sys.executable,
os.path.dirname(debugpy.__file__),
"--connect",
host + ":" + str(port),
]
if adapter.access_token is not None:
cmdline += ["--adapter-access-token", adapter.access_token]
cmdline += debugpy_args
cmdline += ["--pid", str(pid)]
log.info("Spawning attach-to-PID debugger injector: {0!r}", cmdline)
try:
injector = subprocess.Popen(
cmdline,
bufsize=0,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
except Exception as exc:
log.swallow_exception(
"Failed to inject debug server into process with PID={0}", pid
)
raise messaging.MessageHandlingError(
"Failed to inject debug server into process with PID={0}: {1}".format(
pid, exc
)
)
# We need to capture the output of the injector - needed so that it doesn't
# get blocked on a write() syscall (besides showing it to the user if it
# is taking longer than expected).
output_collected = []
output_collected.append("--- Starting attach to pid: {0} ---\n".format(pid))
def capture(stream):
nonlocal output_collected
try:
while True:
line = stream.readline()
if not line:
break
line = line.decode("utf-8", "replace")
output_collected.append(line)
log.info("Injector[PID={0}] output: {1}", pid, line.rstrip())
log.info("Injector[PID={0}] exited.", pid)
except Exception:
s = io.StringIO()
traceback.print_exc(file=s)
on_output("stderr", s.getvalue())
threading.Thread(
target=capture,
name=f"Injector[PID={pid}] stdout",
args=(injector.stdout,),
daemon=True,
).start()
def info_on_timeout():
nonlocal output_collected
taking_longer_than_expected = False
initial_time = time.time()
while True:
time.sleep(1)
returncode = injector.poll()
if returncode is not None:
if returncode != 0:
# Something didn't work out. Let's print more info to the user.
on_output(
"stderr",
"Attach to PID failed.\n\n",
)
old = output_collected
output_collected = []
contents = "".join(old)
on_output("stderr", "".join(contents))
break
elapsed = time.time() - initial_time
on_output(
"stdout", "Attaching to PID: %s (elapsed: %.2fs).\n" % (pid, elapsed)
)
if not taking_longer_than_expected:
if elapsed > 10:
taking_longer_than_expected = True
if sys.platform in ("linux", "linux2"):
on_output(
"stdout",
"\nThe attach to PID is taking longer than expected.\n",
)
on_output(
"stdout",
"On Linux it's possible to customize the value of\n",
)
on_output(
"stdout",
"`PYDEVD_GDB_SCAN_SHARED_LIBRARIES` so that fewer libraries.\n",
)
on_output(
"stdout",
"are scanned when searching for the needed symbols.\n\n",
)
on_output(
"stdout",
"i.e.: set in your environment variables (and restart your editor/client\n",
)
on_output(
"stdout",
"so that it picks up the updated environment variable value):\n\n",
)
on_output(
"stdout",
"PYDEVD_GDB_SCAN_SHARED_LIBRARIES=libdl, libltdl, libc, libfreebl3\n\n",
)
on_output(
"stdout",
"-- the actual library may be different (the gdb output typically\n",
)
on_output(
"stdout",
"-- writes the libraries that will be used, so, it should be possible\n",
)
on_output(
"stdout",
"-- to test other libraries if the above doesn't work).\n\n",
)
if taking_longer_than_expected:
# If taking longer than expected, start showing the actual output to the user.
old = output_collected
output_collected = []
contents = "".join(old)
if contents:
on_output("stderr", contents)
threading.Thread(
target=info_on_timeout, name=f"Injector[PID={pid}] info on timeout", daemon=True
).start()
| 23,348 | Python | 36.720517 | 104 | 0.575338 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/adapter/sessions.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
import itertools
import os
import signal
import threading
import time
from debugpy import common
from debugpy.common import log, util
from debugpy.adapter import components, launchers, servers
_lock = threading.RLock()
_sessions = set()
_sessions_changed = threading.Event()
class Session(util.Observable):
"""A debug session involving a client, an adapter, a launcher, and a debug server.
The client and the adapter are always present, and at least one of launcher and debug
server is present, depending on the scenario.
"""
_counter = itertools.count(1)
def __init__(self):
from debugpy.adapter import clients
super().__init__()
self.lock = threading.RLock()
self.id = next(self._counter)
self._changed_condition = threading.Condition(self.lock)
self.client = components.missing(self, clients.Client)
"""The client component. Always present."""
self.launcher = components.missing(self, launchers.Launcher)
"""The launcher componet. Always present in "launch" sessions, and never
present in "attach" sessions.
"""
self.server = components.missing(self, servers.Server)
"""The debug server component. Always present, unless this is a "launch"
session with "noDebug".
"""
self.no_debug = None
"""Whether this is a "noDebug" session."""
self.pid = None
"""Process ID of the debuggee process."""
self.debug_options = {}
"""Debug options as specified by "launch" or "attach" request."""
self.is_finalizing = False
"""Whether finalize() has been invoked."""
self.observers += [lambda *_: self.notify_changed()]
def __str__(self):
return f"Session[{self.id}]"
def __enter__(self):
"""Lock the session for exclusive access."""
self.lock.acquire()
return self
def __exit__(self, exc_type, exc_value, exc_tb):
"""Unlock the session."""
self.lock.release()
def register(self):
with _lock:
_sessions.add(self)
_sessions_changed.set()
def notify_changed(self):
with self:
self._changed_condition.notify_all()
# A session is considered ended once all components disconnect, and there
# are no further incoming messages from anything to handle.
components = self.client, self.launcher, self.server
if all(not com or not com.is_connected for com in components):
with _lock:
if self in _sessions:
log.info("{0} has ended.", self)
_sessions.remove(self)
_sessions_changed.set()
def wait_for(self, predicate, timeout=None):
"""Waits until predicate() becomes true.
The predicate is invoked with the session locked. If satisfied, the method
returns immediately. Otherwise, the lock is released (even if it was held
at entry), and the method blocks waiting for some attribute of either self,
self.client, self.server, or self.launcher to change. On every change, session
is re-locked and predicate is re-evaluated, until it is satisfied.
While the session is unlocked, message handlers for components other than
the one that is waiting can run, but message handlers for that one are still
blocked.
If timeout is not None, the method will unblock and return after that many
seconds regardless of whether the predicate was satisfied. The method returns
False if it timed out, and True otherwise.
"""
def wait_for_timeout():
time.sleep(timeout)
wait_for_timeout.timed_out = True
self.notify_changed()
wait_for_timeout.timed_out = False
if timeout is not None:
thread = threading.Thread(
target=wait_for_timeout, name="Session.wait_for() timeout"
)
thread.daemon = True
thread.start()
with self:
while not predicate():
if wait_for_timeout.timed_out:
return False
self._changed_condition.wait()
return True
def finalize(self, why, terminate_debuggee=None):
"""Finalizes the debug session.
If the server is present, sends "disconnect" request with "terminateDebuggee"
set as specified request to it; waits for it to disconnect, allowing any
remaining messages from it to be handled; and closes the server channel.
If the launcher is present, sends "terminate" request to it, regardless of the
value of terminate; waits for it to disconnect, allowing any remaining messages
from it to be handled; and closes the launcher channel.
If the client is present, sends "terminated" event to it.
If terminate_debuggee=None, it is treated as True if the session has a Launcher
component, and False otherwise.
"""
if self.is_finalizing:
return
self.is_finalizing = True
log.info("{0}; finalizing {1}.", why, self)
if terminate_debuggee is None:
terminate_debuggee = bool(self.launcher)
try:
self._finalize(why, terminate_debuggee)
except Exception:
# Finalization should never fail, and if it does, the session is in an
# indeterminate and likely unrecoverable state, so just fail fast.
log.swallow_exception("Fatal error while finalizing {0}", self)
os._exit(1)
log.info("{0} finalized.", self)
def _finalize(self, why, terminate_debuggee):
# If the client started a session, and then disconnected before issuing "launch"
# or "attach", the main thread will be blocked waiting for the first server
# connection to come in - unblock it, so that we can exit.
servers.dont_wait_for_first_connection()
if self.server:
if self.server.is_connected:
if terminate_debuggee and self.launcher and self.launcher.is_connected:
# If we were specifically asked to terminate the debuggee, and we
# can ask the launcher to kill it, do so instead of disconnecting
# from the server to prevent debuggee from running any more code.
self.launcher.terminate_debuggee()
else:
# Otherwise, let the server handle it the best it can.
try:
self.server.channel.request(
"disconnect", {"terminateDebuggee": terminate_debuggee}
)
except Exception:
pass
self.server.detach_from_session()
if self.launcher and self.launcher.is_connected:
# If there was a server, we just disconnected from it above, which should
# cause the debuggee process to exit, unless it is being replaced in situ -
# so let's wait for that first.
if self.server and not self.server.connection.process_replaced:
log.info('{0} waiting for "exited" event...', self)
if not self.wait_for(
lambda: self.launcher.exit_code is not None,
timeout=common.PROCESS_EXIT_TIMEOUT,
):
log.warning('{0} timed out waiting for "exited" event.', self)
# Terminate the debuggee process if it's still alive for any reason -
# whether it's because there was no server to handle graceful shutdown,
# or because the server couldn't handle it for some reason - unless the
# process is being replaced in situ.
if not (self.server and self.server.connection.process_replaced):
self.launcher.terminate_debuggee()
# Wait until the launcher message queue fully drains. There is no timeout
# here, because the final "terminated" event will only come after reading
# user input in wait-on-exit scenarios. In addition, if the process was
# replaced in situ, the launcher might still have more output to capture
# from its replacement.
log.info("{0} waiting for {1} to disconnect...", self, self.launcher)
self.wait_for(lambda: not self.launcher.is_connected)
try:
self.launcher.channel.close()
except Exception:
log.swallow_exception()
if self.client:
if self.client.is_connected:
# Tell the client that debugging is over, but don't close the channel until it
# tells us to, via the "disconnect" request.
try:
self.client.channel.send_event("terminated")
except Exception:
pass
if (
self.client.start_request is not None
and self.client.start_request.command == "launch"
and not (self.server and self.server.connection.process_replaced)
):
servers.stop_serving()
log.info(
'"launch" session ended - killing remaining debuggee processes.'
)
pids_killed = set()
if self.launcher and self.launcher.pid is not None:
# Already killed above.
pids_killed.add(self.launcher.pid)
while True:
conns = [
conn
for conn in servers.connections()
if conn.pid not in pids_killed
]
if not len(conns):
break
for conn in conns:
log.info("Killing {0}", conn)
try:
os.kill(conn.pid, signal.SIGTERM)
except Exception:
log.swallow_exception("Failed to kill {0}", conn)
pids_killed.add(conn.pid)
def get(pid):
with _lock:
return next((session for session in _sessions if session.pid == pid), None)
def wait_until_ended():
"""Blocks until all sessions have ended.
A session ends when all components that it manages disconnect from it.
"""
while True:
with _lock:
if not len(_sessions):
return
_sessions_changed.clear()
_sessions_changed.wait()
| 10,889 | Python | 37.617021 | 94 | 0.584994 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/common/util.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
import inspect
import os
import sys
def evaluate(code, path=__file__, mode="eval"):
# Setting file path here to avoid breaking here if users have set
# "break on exception raised" setting. This code can potentially run
# in user process and is indistinguishable if the path is not set.
# We use the path internally to skip exception inside the debugger.
expr = compile(code, path, "eval")
return eval(expr, {}, sys.modules)
class Observable(object):
"""An object with change notifications."""
observers = () # used when attributes are set before __init__ is invoked
def __init__(self):
self.observers = []
def __setattr__(self, name, value):
try:
return super().__setattr__(name, value)
finally:
for ob in self.observers:
ob(self, name)
class Env(dict):
"""A dict for environment variables."""
@staticmethod
def snapshot():
"""Returns a snapshot of the current environment."""
return Env(os.environ)
def copy(self, updated_from=None):
result = Env(self)
if updated_from is not None:
result.update(updated_from)
return result
def prepend_to(self, key, entry):
"""Prepends a new entry to a PATH-style environment variable, creating
it if it doesn't exist already.
"""
try:
tail = os.path.pathsep + self[key]
except KeyError:
tail = ""
self[key] = entry + tail
def force_str(s, encoding, errors="strict"):
"""Converts s to str, using the provided encoding. If s is already str,
it is returned as is.
"""
return s.decode(encoding, errors) if isinstance(s, bytes) else str(s)
def force_bytes(s, encoding, errors="strict"):
"""Converts s to bytes, using the provided encoding. If s is already bytes,
it is returned as is.
If errors="strict" and s is bytes, its encoding is verified by decoding it;
UnicodeError is raised if it cannot be decoded.
"""
if isinstance(s, str):
return s.encode(encoding, errors)
else:
s = bytes(s)
if errors == "strict":
# Return value ignored - invoked solely for verification.
s.decode(encoding, errors)
return s
def force_ascii(s, errors="strict"):
"""Same as force_bytes(s, "ascii", errors)"""
return force_bytes(s, "ascii", errors)
def force_utf8(s, errors="strict"):
"""Same as force_bytes(s, "utf8", errors)"""
return force_bytes(s, "utf8", errors)
def nameof(obj, quote=False):
"""Returns the most descriptive name of a Python module, class, or function,
as a Unicode string
If quote=True, name is quoted with repr().
Best-effort, but guaranteed to not fail - always returns something.
"""
try:
name = obj.__qualname__
except Exception:
try:
name = obj.__name__
except Exception:
# Fall back to raw repr(), and skip quoting.
try:
name = repr(obj)
except Exception:
return "<unknown>"
else:
quote = False
if quote:
try:
name = repr(name)
except Exception:
pass
return force_str(name, "utf-8", "replace")
def srcnameof(obj):
"""Returns the most descriptive name of a Python module, class, or function,
including source information (filename and linenumber), if available.
Best-effort, but guaranteed to not fail - always returns something.
"""
name = nameof(obj, quote=True)
# Get the source information if possible.
try:
src_file = inspect.getsourcefile(obj)
except Exception:
pass
else:
name += f" (file {src_file!r}"
try:
_, src_lineno = inspect.getsourcelines(obj)
except Exception:
pass
else:
name += f", line {src_lineno}"
name += ")"
return name
def hide_debugpy_internals():
"""Returns True if the caller should hide something from debugpy."""
return "DEBUGPY_TRACE_DEBUGPY" not in os.environ
def hide_thread_from_debugger(thread):
"""Disables tracing for the given thread if DEBUGPY_TRACE_DEBUGPY is not set.
DEBUGPY_TRACE_DEBUGPY is used to debug debugpy with debugpy
"""
if hide_debugpy_internals():
thread.pydev_do_not_trace = True
thread.is_pydev_daemon_thread = True
| 4,646 | Python | 27.163636 | 81 | 0.610848 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/common/stacks.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
"""Provides facilities to dump all stacks of all threads in the process.
"""
import os
import sys
import time
import threading
import traceback
from debugpy.common import log
def dump():
"""Dump stacks of all threads in this process, except for the current thread."""
tid = threading.current_thread().ident
pid = os.getpid()
log.info("Dumping stacks for process {0}...", pid)
for t_ident, frame in sys._current_frames().items():
if t_ident == tid:
continue
for t in threading.enumerate():
if t.ident == tid:
t_name = t.name
t_daemon = t.daemon
break
else:
t_name = t_daemon = "<unknown>"
stack = "".join(traceback.format_stack(frame))
log.info(
"Stack of thread {0} (tid={1}, pid={2}, daemon={3}):\n\n{4}",
t_name,
t_ident,
pid,
t_daemon,
stack,
)
log.info("Finished dumping stacks for process {0}.", pid)
def dump_after(secs):
"""Invokes dump() on a background thread after waiting for the specified time."""
def dumper():
time.sleep(secs)
try:
dump()
except:
log.swallow_exception()
thread = threading.Thread(target=dumper)
thread.daemon = True
thread.start()
| 1,526 | Python | 23.238095 | 85 | 0.574705 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/common/log.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
import atexit
import contextlib
import functools
import inspect
import io
import os
import platform
import sys
import threading
import traceback
import debugpy
from debugpy.common import json, timestamp, util
LEVELS = ("debug", "info", "warning", "error")
"""Logging levels, lowest to highest importance.
"""
log_dir = os.getenv("DEBUGPY_LOG_DIR")
"""If not None, debugger logs its activity to a file named debugpy.*-<pid>.log
in the specified directory, where <pid> is the return value of os.getpid().
"""
timestamp_format = "09.3f"
"""Format spec used for timestamps. Can be changed to dial precision up or down.
"""
_lock = threading.RLock()
_tls = threading.local()
_files = {} # filename -> LogFile
_levels = set() # combined for all log files
def _update_levels():
global _levels
_levels = frozenset(level for file in _files.values() for level in file.levels)
class LogFile(object):
def __init__(self, filename, file, levels=LEVELS, close_file=True):
info("Also logging to {0}.", json.repr(filename))
self.filename = filename
self.file = file
self.close_file = close_file
self._levels = frozenset(levels)
with _lock:
_files[self.filename] = self
_update_levels()
info(
"{0} {1}\n{2} {3} ({4}-bit)\ndebugpy {5}",
platform.platform(),
platform.machine(),
platform.python_implementation(),
platform.python_version(),
64 if sys.maxsize > 2 ** 32 else 32,
debugpy.__version__,
_to_files=[self],
)
@property
def levels(self):
return self._levels
@levels.setter
def levels(self, value):
with _lock:
self._levels = frozenset(LEVELS if value is all else value)
_update_levels()
def write(self, level, output):
if level in self.levels:
try:
self.file.write(output)
self.file.flush()
except Exception:
pass
def close(self):
with _lock:
del _files[self.filename]
_update_levels()
info("Not logging to {0} anymore.", json.repr(self.filename))
if self.close_file:
try:
self.file.close()
except Exception:
pass
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
class NoLog(object):
file = filename = None
__bool__ = __nonzero__ = lambda self: False
def close(self):
pass
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
pass
# Used to inject a newline into stderr if logging there, to clean up the output
# when it's intermixed with regular prints from other sources.
def newline(level="info"):
with _lock:
stderr.write(level, "\n")
def write(level, text, _to_files=all):
assert level in LEVELS
t = timestamp.current()
format_string = "{0}+{1:" + timestamp_format + "}: "
prefix = format_string.format(level[0].upper(), t)
text = getattr(_tls, "prefix", "") + text
indent = "\n" + (" " * len(prefix))
output = indent.join(text.split("\n"))
output = prefix + output + "\n\n"
with _lock:
if _to_files is all:
_to_files = _files.values()
for file in _to_files:
file.write(level, output)
return text
def write_format(level, format_string, *args, **kwargs):
# Don't spend cycles doing expensive formatting if we don't have to. Errors are
# always formatted, so that error() can return the text even if it's not logged.
if level != "error" and level not in _levels:
return
try:
text = format_string.format(*args, **kwargs)
except Exception:
reraise_exception()
return write(level, text, kwargs.pop("_to_files", all))
debug = functools.partial(write_format, "debug")
info = functools.partial(write_format, "info")
warning = functools.partial(write_format, "warning")
def error(*args, **kwargs):
"""Logs an error.
Returns the output wrapped in AssertionError. Thus, the following::
raise log.error(s, ...)
has the same effect as::
log.error(...)
assert False, (s.format(...))
"""
return AssertionError(write_format("error", *args, **kwargs))
def _exception(format_string="", *args, **kwargs):
level = kwargs.pop("level", "error")
exc_info = kwargs.pop("exc_info", sys.exc_info())
if format_string:
format_string += "\n\n"
format_string += "{exception}\nStack where logged:\n{stack}"
exception = "".join(traceback.format_exception(*exc_info))
f = inspect.currentframe()
f = f.f_back if f else f # don't log this frame
try:
stack = "".join(traceback.format_stack(f))
finally:
del f # avoid cycles
write_format(
level, format_string, *args, exception=exception, stack=stack, **kwargs
)
def swallow_exception(format_string="", *args, **kwargs):
"""Logs an exception with full traceback.
If format_string is specified, it is formatted with format(*args, **kwargs), and
prepended to the exception traceback on a separate line.
If exc_info is specified, the exception it describes will be logged. Otherwise,
sys.exc_info() - i.e. the exception being handled currently - will be logged.
If level is specified, the exception will be logged as a message of that level.
The default is "error".
"""
_exception(format_string, *args, **kwargs)
def reraise_exception(format_string="", *args, **kwargs):
"""Like swallow_exception(), but re-raises the current exception after logging it."""
assert "exc_info" not in kwargs
_exception(format_string, *args, **kwargs)
raise
def to_file(filename=None, prefix=None, levels=LEVELS):
"""Starts logging all messages at the specified levels to the designated file.
Either filename or prefix must be specified, but not both.
If filename is specified, it designates the log file directly.
If prefix is specified, the log file is automatically created in options.log_dir,
with filename computed as prefix + os.getpid(). If log_dir is None, no log file
is created, and the function returns immediately.
If the file with the specified or computed name is already being used as a log
file, it is not overwritten, but its levels are updated as specified.
The function returns an object with a close() method. When the object is closed,
logs are not written into that file anymore. Alternatively, the returned object
can be used in a with-statement:
with log.to_file("some.log"):
# now also logging to some.log
# not logging to some.log anymore
"""
assert (filename is not None) ^ (prefix is not None)
if filename is None:
if log_dir is None:
return NoLog()
try:
os.makedirs(log_dir)
except OSError:
pass
filename = f"{log_dir}/{prefix}-{os.getpid()}.log"
file = _files.get(filename)
if file is None:
file = LogFile(filename, io.open(filename, "w", encoding="utf-8"), levels)
else:
file.levels = levels
return file
@contextlib.contextmanager
def prefixed(format_string, *args, **kwargs):
"""Adds a prefix to all messages logged from the current thread for the duration
of the context manager.
"""
prefix = format_string.format(*args, **kwargs)
old_prefix = getattr(_tls, "prefix", "")
_tls.prefix = prefix + old_prefix
try:
yield
finally:
_tls.prefix = old_prefix
def describe_environment(header):
import sysconfig
import site # noqa
result = [header, "\n\n"]
def report(s, *args, **kwargs):
result.append(s.format(*args, **kwargs))
def report_paths(get_paths, label=None):
prefix = f" {label or get_paths}: "
expr = None
if not callable(get_paths):
expr = get_paths
get_paths = lambda: util.evaluate(expr)
try:
paths = get_paths()
except AttributeError:
report("{0}<missing>\n", prefix)
return
except Exception:
swallow_exception(
"Error evaluating {0}",
repr(expr) if expr else util.srcnameof(get_paths),
)
return
if not isinstance(paths, (list, tuple)):
paths = [paths]
for p in sorted(paths):
report("{0}{1}", prefix, p)
if p is not None:
rp = os.path.realpath(p)
if p != rp:
report("({0})", rp)
report("\n")
prefix = " " * len(prefix)
report("System paths:\n")
report_paths("sys.prefix")
report_paths("sys.base_prefix")
report_paths("sys.real_prefix")
report_paths("site.getsitepackages()")
report_paths("site.getusersitepackages()")
site_packages = [
p
for p in sys.path
if os.path.exists(p) and os.path.basename(p) == "site-packages"
]
report_paths(lambda: site_packages, "sys.path (site-packages)")
for name in sysconfig.get_path_names():
expr = "sysconfig.get_path({0!r})".format(name)
report_paths(expr)
report_paths("os.__file__")
report_paths("threading.__file__")
report_paths("debugpy.__file__")
result = "".join(result).rstrip("\n")
info("{0}", result)
stderr = LogFile(
"<stderr>",
sys.stderr,
levels=os.getenv("DEBUGPY_LOG_STDERR", "warning error").split(),
close_file=False,
)
@atexit.register
def _close_files():
for file in tuple(_files.values()):
file.close()
# The following are helper shortcuts for printf debugging. They must never be used
# in production code.
def _repr(value): # pragma: no cover
warning("$REPR {0!r}", value)
def _vars(*names): # pragma: no cover
locals = inspect.currentframe().f_back.f_locals
if names:
locals = {name: locals[name] for name in names if name in locals}
warning("$VARS {0!r}", locals)
def _stack(): # pragma: no cover
stack = "\n".join(traceback.format_stack())
warning("$STACK:\n\n{0}", stack)
def _threads(): # pragma: no cover
output = "\n".join([str(t) for t in threading.enumerate()])
warning("$THREADS:\n\n{0}", output)
| 10,723 | Python | 26.782383 | 89 | 0.604775 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/common/timestamp.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
"""Provides monotonic timestamps with a resetable zero.
"""
import time
__all__ = ["current", "reset"]
def current():
return time.monotonic() - timestamp_zero
def reset():
global timestamp_zero
timestamp_zero = time.monotonic()
reset()
| 410 | Python | 16.869564 | 65 | 0.707317 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/common/__init__.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
from __future__ import annotations
import os
import typing
if typing.TYPE_CHECKING:
__all__: list[str]
__all__ = []
# The lower time bound for assuming that the process hasn't spawned successfully.
PROCESS_SPAWN_TIMEOUT = float(os.getenv("DEBUGPY_PROCESS_SPAWN_TIMEOUT", 15))
# The lower time bound for assuming that the process hasn't exited gracefully.
PROCESS_EXIT_TIMEOUT = float(os.getenv("DEBUGPY_PROCESS_EXIT_TIMEOUT", 5))
| 592 | Python | 30.210525 | 81 | 0.753378 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/common/sockets.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
import socket
import sys
import threading
from debugpy.common import log
from debugpy.common.util import hide_thread_from_debugger
def create_server(host, port=0, backlog=socket.SOMAXCONN, timeout=None):
"""Return a local server socket listening on the given port."""
assert backlog > 0
if host is None:
host = "127.0.0.1"
if port is None:
port = 0
try:
server = _new_sock()
if port != 0:
# If binding to a specific port, make sure that the user doesn't have
# to wait until the OS times out the socket to be able to use that port
# again.if the server or the adapter crash or are force-killed.
if sys.platform == "win32":
server.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
else:
try:
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except (AttributeError, OSError):
pass # Not available everywhere
server.bind((host, port))
if timeout is not None:
server.settimeout(timeout)
server.listen(backlog)
except Exception:
server.close()
raise
return server
def create_client():
"""Return a client socket that may be connected to a remote address."""
return _new_sock()
def _new_sock():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
# Set TCP keepalive on an open socket.
# It activates after 1 second (TCP_KEEPIDLE,) of idleness,
# then sends a keepalive ping once every 3 seconds (TCP_KEEPINTVL),
# and closes the connection after 5 failed ping (TCP_KEEPCNT), or 15 seconds
try:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
except (AttributeError, OSError):
pass # May not be available everywhere.
try:
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 1)
except (AttributeError, OSError):
pass # May not be available everywhere.
try:
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 3)
except (AttributeError, OSError):
pass # May not be available everywhere.
try:
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 5)
except (AttributeError, OSError):
pass # May not be available everywhere.
return sock
def shut_down(sock, how=socket.SHUT_RDWR):
"""Shut down the given socket."""
sock.shutdown(how)
def close_socket(sock):
"""Shutdown and close the socket."""
try:
shut_down(sock)
except Exception:
pass
sock.close()
def serve(name, handler, host, port=0, backlog=socket.SOMAXCONN, timeout=None):
"""Accepts TCP connections on the specified host and port, and invokes the
provided handler function for every new connection.
Returns the created server socket.
"""
assert backlog > 0
try:
listener = create_server(host, port, backlog, timeout)
except Exception:
log.reraise_exception(
"Error listening for incoming {0} connections on {1}:{2}:", name, host, port
)
host, port = listener.getsockname()
log.info("Listening for incoming {0} connections on {1}:{2}...", name, host, port)
def accept_worker():
while True:
try:
sock, (other_host, other_port) = listener.accept()
except (OSError, socket.error):
# Listener socket has been closed.
break
log.info(
"Accepted incoming {0} connection from {1}:{2}.",
name,
other_host,
other_port,
)
handler(sock)
thread = threading.Thread(target=accept_worker)
thread.daemon = True
hide_thread_from_debugger(thread)
thread.start()
return listener
| 4,064 | Python | 30.269231 | 88 | 0.621801 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/common/json.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
"""Improved JSON serialization.
"""
import builtins
import json
import numbers
import operator
JsonDecoder = json.JSONDecoder
class JsonEncoder(json.JSONEncoder):
"""Customizable JSON encoder.
If the object implements __getstate__, then that method is invoked, and its
result is serialized instead of the object itself.
"""
def default(self, value):
try:
get_state = value.__getstate__
except AttributeError:
pass
else:
return get_state()
return super().default(value)
class JsonObject(object):
"""A wrapped Python object that formats itself as JSON when asked for a string
representation via str() or format().
"""
json_encoder_factory = JsonEncoder
"""Used by __format__ when format_spec is not empty."""
json_encoder = json_encoder_factory(indent=4)
"""The default encoder used by __format__ when format_spec is empty."""
def __init__(self, value):
assert not isinstance(value, JsonObject)
self.value = value
def __getstate__(self):
raise NotImplementedError
def __repr__(self):
return builtins.repr(self.value)
def __str__(self):
return format(self)
def __format__(self, format_spec):
"""If format_spec is empty, uses self.json_encoder to serialize self.value
as a string. Otherwise, format_spec is treated as an argument list to be
passed to self.json_encoder_factory - which defaults to JSONEncoder - and
then the resulting formatter is used to serialize self.value as a string.
Example::
format("{0} {0:indent=4,sort_keys=True}", json.repr(x))
"""
if format_spec:
# At this point, format_spec is a string that looks something like
# "indent=4,sort_keys=True". What we want is to build a function call
# from that which looks like:
#
# json_encoder_factory(indent=4,sort_keys=True)
#
# which we can then eval() to create our encoder instance.
make_encoder = "json_encoder_factory(" + format_spec + ")"
encoder = eval(
make_encoder, {"json_encoder_factory": self.json_encoder_factory}
)
else:
encoder = self.json_encoder
return encoder.encode(self.value)
# JSON property validators, for use with MessageDict.
#
# A validator is invoked with the actual value of the JSON property passed to it as
# the sole argument; or if the property is missing in JSON, then () is passed. Note
# that None represents an actual null in JSON, while () is a missing value.
#
# The validator must either raise TypeError or ValueError describing why the property
# value is invalid, or else return the value of the property, possibly after performing
# some substitutions - e.g. replacing () with some default value.
def _converter(value, classinfo):
"""Convert value (str) to number, otherwise return None if is not possible"""
for one_info in classinfo:
if issubclass(one_info, numbers.Number):
try:
return one_info(value)
except ValueError:
pass
def of_type(*classinfo, **kwargs):
"""Returns a validator for a JSON property that requires it to have a value of
the specified type. If optional=True, () is also allowed.
The meaning of classinfo is the same as for isinstance().
"""
assert len(classinfo)
optional = kwargs.pop("optional", False)
assert not len(kwargs)
def validate(value):
if (optional and value == ()) or isinstance(value, classinfo):
return value
else:
converted_value = _converter(value, classinfo)
if converted_value:
return converted_value
if not optional and value == ():
raise ValueError("must be specified")
raise TypeError("must be " + " or ".join(t.__name__ for t in classinfo))
return validate
def default(default):
"""Returns a validator for a JSON property with a default value.
The validator will only allow property values that have the same type as the
specified default value.
"""
def validate(value):
if value == ():
return default
elif isinstance(value, type(default)):
return value
else:
raise TypeError("must be {0}".format(type(default).__name__))
return validate
def enum(*values, **kwargs):
"""Returns a validator for a JSON enum.
The validator will only allow the property to have one of the specified values.
If optional=True, and the property is missing, the first value specified is used
as the default.
"""
assert len(values)
optional = kwargs.pop("optional", False)
assert not len(kwargs)
def validate(value):
if optional and value == ():
return values[0]
elif value in values:
return value
else:
raise ValueError("must be one of: {0!r}".format(list(values)))
return validate
def array(validate_item=False, vectorize=False, size=None):
"""Returns a validator for a JSON array.
If the property is missing, it is treated as if it were []. Otherwise, it must
be a list.
If validate_item=False, it's treated as if it were (lambda x: x) - i.e. any item
is considered valid, and is unchanged. If validate_item is a type or a tuple,
it's treated as if it were json.of_type(validate).
Every item in the list is replaced with validate_item(item) in-place, propagating
any exceptions raised by the latter. If validate_item is a type or a tuple, it is
treated as if it were json.of_type(validate_item).
If vectorize=True, and the value is neither a list nor a dict, it is treated as
if it were a single-element list containing that single value - e.g. "foo" is
then the same as ["foo"]; but {} is an error, and not [{}].
If size is not None, it can be an int, a tuple of one int, a tuple of two ints,
or a set. If it's an int, the array must have exactly that many elements. If it's
a tuple of one int, it's the minimum length. If it's a tuple of two ints, they
are the minimum and the maximum lengths. If it's a set, it's the set of sizes that
are valid - e.g. for {2, 4}, the array can be either 2 or 4 elements long.
"""
if not validate_item:
validate_item = lambda x: x
elif isinstance(validate_item, type) or isinstance(validate_item, tuple):
validate_item = of_type(validate_item)
if size is None:
validate_size = lambda _: True
elif isinstance(size, set):
size = {operator.index(n) for n in size}
validate_size = lambda value: (
len(value) in size
or "must have {0} elements".format(
" or ".join(str(n) for n in sorted(size))
)
)
elif isinstance(size, tuple):
assert 1 <= len(size) <= 2
size = tuple(operator.index(n) for n in size)
min_len, max_len = (size + (None,))[0:2]
validate_size = lambda value: (
"must have at least {0} elements".format(min_len)
if len(value) < min_len
else "must have at most {0} elements".format(max_len)
if max_len is not None and len(value) < max_len
else True
)
else:
size = operator.index(size)
validate_size = lambda value: (
len(value) == size or "must have {0} elements".format(size)
)
def validate(value):
if value == ():
value = []
elif vectorize and not isinstance(value, (list, dict)):
value = [value]
of_type(list)(value)
size_err = validate_size(value) # True if valid, str if error
if size_err is not True:
raise ValueError(size_err)
for i, item in enumerate(value):
try:
value[i] = validate_item(item)
except (TypeError, ValueError) as exc:
raise type(exc)(f"[{repr(i)}] {exc}")
return value
return validate
def object(validate_value=False):
"""Returns a validator for a JSON object.
If the property is missing, it is treated as if it were {}. Otherwise, it must
be a dict.
If validate_value=False, it's treated as if it were (lambda x: x) - i.e. any
value is considered valid, and is unchanged. If validate_value is a type or a
tuple, it's treated as if it were json.of_type(validate_value).
Every value in the dict is replaced with validate_value(value) in-place, propagating
any exceptions raised by the latter. If validate_value is a type or a tuple, it is
treated as if it were json.of_type(validate_value). Keys are not affected.
"""
if isinstance(validate_value, type) or isinstance(validate_value, tuple):
validate_value = of_type(validate_value)
def validate(value):
if value == ():
return {}
of_type(dict)(value)
if validate_value:
for k, v in value.items():
try:
value[k] = validate_value(v)
except (TypeError, ValueError) as exc:
raise type(exc)(f"[{repr(k)}] {exc}")
return value
return validate
def repr(value):
return JsonObject(value)
dumps = json.dumps
loads = json.loads
| 9,674 | Python | 32.020478 | 88 | 0.620219 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/common/messaging.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
"""An implementation of the session and presentation layers as used in the Debug
Adapter Protocol (DAP): channels and their lifetime, JSON messages, requests,
responses, and events.
https://microsoft.github.io/debug-adapter-protocol/overview#base-protocol
"""
from __future__ import annotations
import collections
import contextlib
import functools
import itertools
import os
import socket
import sys
import threading
from debugpy.common import json, log, util
from debugpy.common.util import hide_thread_from_debugger
class JsonIOError(IOError):
"""Indicates that a read or write operation on JsonIOStream has failed."""
def __init__(self, *args, **kwargs):
stream = kwargs.pop("stream")
cause = kwargs.pop("cause", None)
if not len(args) and cause is not None:
args = [str(cause)]
super().__init__(*args, **kwargs)
self.stream = stream
"""The stream that couldn't be read or written.
Set by JsonIOStream.read_json() and JsonIOStream.write_json().
JsonMessageChannel relies on this value to decide whether a NoMoreMessages
instance that bubbles up to the message loop is related to that loop.
"""
self.cause = cause
"""The underlying exception, if any."""
class NoMoreMessages(JsonIOError, EOFError):
"""Indicates that there are no more messages that can be read from or written
to a stream.
"""
def __init__(self, *args, **kwargs):
args = args if len(args) else ["No more messages"]
super().__init__(*args, **kwargs)
class JsonIOStream(object):
"""Implements a JSON value stream over two byte streams (input and output).
Each value is encoded as a DAP packet, with metadata headers and a JSON payload.
"""
MAX_BODY_SIZE = 0xFFFFFF
json_decoder_factory = json.JsonDecoder
"""Used by read_json() when decoder is None."""
json_encoder_factory = json.JsonEncoder
"""Used by write_json() when encoder is None."""
@classmethod
def from_stdio(cls, name="stdio"):
"""Creates a new instance that receives messages from sys.stdin, and sends
them to sys.stdout.
"""
return cls(sys.stdin.buffer, sys.stdout.buffer, name)
@classmethod
def from_process(cls, process, name="stdio"):
"""Creates a new instance that receives messages from process.stdin, and sends
them to process.stdout.
"""
return cls(process.stdout, process.stdin, name)
@classmethod
def from_socket(cls, sock, name=None):
"""Creates a new instance that sends and receives messages over a socket."""
sock.settimeout(None) # make socket blocking
if name is None:
name = repr(sock)
# TODO: investigate switching to buffered sockets; readline() on unbuffered
# sockets is very slow! Although the implementation of readline() itself is
# native code, it calls read(1) in a loop - and that then ultimately calls
# SocketIO.readinto(), which is implemented in Python.
socket_io = sock.makefile("rwb", 0)
# SocketIO.close() doesn't close the underlying socket.
def cleanup():
try:
sock.shutdown(socket.SHUT_RDWR)
except Exception:
pass
sock.close()
return cls(socket_io, socket_io, name, cleanup)
def __init__(self, reader, writer, name=None, cleanup=lambda: None):
"""Creates a new JsonIOStream.
reader must be a BytesIO-like object, from which incoming messages will be
read by read_json().
writer must be a BytesIO-like object, into which outgoing messages will be
written by write_json().
cleanup must be a callable; it will be invoked without arguments when the
stream is closed.
reader.readline() must treat "\n" as the line terminator, and must leave "\r"
as is - it must not replace "\r\n" with "\n" automatically, as TextIO does.
"""
if name is None:
name = f"reader={reader!r}, writer={writer!r}"
self.name = name
self._reader = reader
self._writer = writer
self._cleanup = cleanup
self._closed = False
def close(self):
"""Closes the stream, the reader, and the writer."""
if self._closed:
return
self._closed = True
log.debug("Closing {0} message stream", self.name)
try:
try:
# Close the writer first, so that the other end of the connection has
# its message loop waiting on read() unblocked. If there is an exception
# while closing the writer, we still want to try to close the reader -
# only one exception can bubble up, so if both fail, it'll be the one
# from reader.
try:
self._writer.close()
finally:
if self._reader is not self._writer:
self._reader.close()
finally:
self._cleanup()
except Exception:
log.reraise_exception("Error while closing {0} message stream", self.name)
def _log_message(self, dir, data, logger=log.debug):
return logger("{0} {1} {2}", self.name, dir, data)
def _read_line(self, reader):
line = b""
while True:
try:
line += reader.readline()
except Exception as exc:
raise NoMoreMessages(str(exc), stream=self)
if not line:
raise NoMoreMessages(stream=self)
if line.endswith(b"\r\n"):
line = line[0:-2]
return line
def read_json(self, decoder=None):
"""Read a single JSON value from reader.
Returns JSON value as parsed by decoder.decode(), or raises NoMoreMessages
if there are no more values to be read.
"""
decoder = decoder if decoder is not None else self.json_decoder_factory()
reader = self._reader
read_line = functools.partial(self._read_line, reader)
# If any error occurs while reading and parsing the message, log the original
# raw message data as is, so that it's possible to diagnose missing or invalid
# headers, encoding issues, JSON syntax errors etc.
def log_message_and_reraise_exception(format_string="", *args, **kwargs):
if format_string:
format_string += "\n\n"
format_string += "{name} -->\n{raw_lines}"
raw_lines = b"".join(raw_chunks).split(b"\n")
raw_lines = "\n".join(repr(line) for line in raw_lines)
log.reraise_exception(
format_string, *args, name=self.name, raw_lines=raw_lines, **kwargs
)
raw_chunks = []
headers = {}
while True:
try:
line = read_line()
except Exception:
# Only log it if we have already read some headers, and are looking
# for a blank line terminating them. If this is the very first read,
# there's no message data to log in any case, and the caller might
# be anticipating the error - e.g. NoMoreMessages on disconnect.
if headers:
log_message_and_reraise_exception(
"Error while reading message headers:"
)
else:
raise
raw_chunks += [line, b"\n"]
if line == b"":
break
key, _, value = line.partition(b":")
headers[key] = value
try:
length = int(headers[b"Content-Length"])
if not (0 <= length <= self.MAX_BODY_SIZE):
raise ValueError
except (KeyError, ValueError):
try:
raise IOError("Content-Length is missing or invalid:")
except Exception:
log_message_and_reraise_exception()
body_start = len(raw_chunks)
body_remaining = length
while body_remaining > 0:
try:
chunk = reader.read(body_remaining)
if not chunk:
raise EOFError
except Exception as exc:
# Not logged due to https://github.com/microsoft/ptvsd/issues/1699
raise NoMoreMessages(str(exc), stream=self)
raw_chunks.append(chunk)
body_remaining -= len(chunk)
assert body_remaining == 0
body = b"".join(raw_chunks[body_start:])
try:
body = body.decode("utf-8")
except Exception:
log_message_and_reraise_exception()
try:
body = decoder.decode(body)
except Exception:
log_message_and_reraise_exception()
# If parsed successfully, log as JSON for readability.
self._log_message("-->", body)
return body
def write_json(self, value, encoder=None):
"""Write a single JSON value into writer.
Value is written as encoded by encoder.encode().
"""
if self._closed:
# Don't log this - it's a common pattern to write to a stream while
# anticipating EOFError from it in case it got closed concurrently.
raise NoMoreMessages(stream=self)
encoder = encoder if encoder is not None else self.json_encoder_factory()
writer = self._writer
# Format the value as a message, and try to log any failures using as much
# information as we already have at the point of the failure. For example,
# if it fails after it is serialized to JSON, log that JSON.
try:
body = encoder.encode(value)
except Exception:
self._log_message("<--", repr(value), logger=log.reraise_exception)
body = body.encode("utf-8")
header = f"Content-Length: {len(body)}\r\n\r\n".encode("ascii")
data = header + body
data_written = 0
try:
while data_written < len(data):
written = writer.write(data[data_written:])
data_written += written
writer.flush()
except Exception as exc:
self._log_message("<--", value, logger=log.swallow_exception)
raise JsonIOError(stream=self, cause=exc)
self._log_message("<--", value)
def __repr__(self):
return f"{type(self).__name__}({self.name!r})"
class MessageDict(collections.OrderedDict):
"""A specialized dict that is used for JSON message payloads - Request.arguments,
Response.body, and Event.body.
For all members that normally throw KeyError when a requested key is missing, this
dict raises InvalidMessageError instead. Thus, a message handler can skip checks
for missing properties, and just work directly with the payload on the assumption
that it is valid according to the protocol specification; if anything is missing,
it will be reported automatically in the proper manner.
If the value for the requested key is itself a dict, it is returned as is, and not
automatically converted to MessageDict. Thus, to enable convenient chaining - e.g.
d["a"]["b"]["c"] - the dict must consistently use MessageDict instances rather than
vanilla dicts for all its values, recursively. This is guaranteed for the payload
of all freshly received messages (unless and until it is mutated), but there is no
such guarantee for outgoing messages.
"""
def __init__(self, message, items=None):
assert message is None or isinstance(message, Message)
if items is None:
super().__init__()
else:
super().__init__(items)
self.message = message
"""The Message object that owns this dict.
For any instance exposed via a Message object corresponding to some incoming
message, it is guaranteed to reference that Message object. There is no similar
guarantee for outgoing messages.
"""
def __repr__(self):
try:
return format(json.repr(self))
except Exception:
return super().__repr__()
def __call__(self, key, validate, optional=False):
"""Like get(), but with validation.
The item is first retrieved as if with self.get(key, default=()) - the default
value is () rather than None, so that JSON nulls are distinguishable from
missing properties.
If optional=True, and the value is (), it's returned as is. Otherwise, the
item is validated by invoking validate(item) on it.
If validate=False, it's treated as if it were (lambda x: x) - i.e. any value
is considered valid, and is returned unchanged. If validate is a type or a
tuple, it's treated as json.of_type(validate). Otherwise, if validate is not
callable(), it's treated as json.default(validate).
If validate() returns successfully, the item is substituted with the value
it returns - thus, the validator can e.g. replace () with a suitable default
value for the property.
If validate() raises TypeError or ValueError, raises InvalidMessageError with
the same text that applies_to(self.messages).
See debugpy.common.json for reusable validators.
"""
if not validate:
validate = lambda x: x
elif isinstance(validate, type) or isinstance(validate, tuple):
validate = json.of_type(validate, optional=optional)
elif not callable(validate):
validate = json.default(validate)
value = self.get(key, ())
try:
value = validate(value)
except (TypeError, ValueError) as exc:
message = Message if self.message is None else self.message
err = str(exc)
if not err.startswith("["):
err = " " + err
raise message.isnt_valid("{0}{1}", json.repr(key), err)
return value
def _invalid_if_no_key(func):
def wrap(self, key, *args, **kwargs):
try:
return func(self, key, *args, **kwargs)
except KeyError:
message = Message if self.message is None else self.message
raise message.isnt_valid("missing property {0!r}", key)
return wrap
__getitem__ = _invalid_if_no_key(collections.OrderedDict.__getitem__)
__delitem__ = _invalid_if_no_key(collections.OrderedDict.__delitem__)
pop = _invalid_if_no_key(collections.OrderedDict.pop)
del _invalid_if_no_key
def _payload(value):
"""JSON validator for message payload.
If that value is missing or null, it is treated as if it were {}.
"""
if value is not None and value != ():
if isinstance(value, dict): # can be int, str, list...
assert isinstance(value, MessageDict)
return value
# Missing payload. Construct a dummy MessageDict, and make it look like it was
# deserialized. See JsonMessageChannel._parse_incoming_message for why it needs
# to have associate_with().
def associate_with(message):
value.message = message
value = MessageDict(None)
value.associate_with = associate_with
return value
class Message(object):
"""Represents a fully parsed incoming or outgoing message.
https://microsoft.github.io/debug-adapter-protocol/specification#protocolmessage
"""
def __init__(self, channel, seq, json=None):
self.channel = channel
self.seq = seq
"""Sequence number of the message in its channel.
This can be None for synthesized Responses.
"""
self.json = json
"""For incoming messages, the MessageDict containing raw JSON from which
this message was originally parsed.
"""
def __str__(self):
return json.repr(self.json) if self.json is not None else repr(self)
def describe(self):
"""A brief description of the message that is enough to identify it.
Examples:
'#1 request "launch" from IDE'
'#2 response to #1 request "launch" from IDE'.
"""
raise NotImplementedError
@property
def payload(self) -> MessageDict:
"""Payload of the message - self.body or self.arguments, depending on the
message type.
"""
raise NotImplementedError
def __call__(self, *args, **kwargs):
"""Same as self.payload(...)."""
return self.payload(*args, **kwargs)
def __contains__(self, key):
"""Same as (key in self.payload)."""
return key in self.payload
def is_event(self, *event):
"""Returns True if this message is an Event of one of the specified types."""
if not isinstance(self, Event):
return False
return event == () or self.event in event
def is_request(self, *command):
"""Returns True if this message is a Request of one of the specified types."""
if not isinstance(self, Request):
return False
return command == () or self.command in command
def is_response(self, *command):
"""Returns True if this message is a Response to a request of one of the
specified types.
"""
if not isinstance(self, Response):
return False
return command == () or self.request.command in command
def error(self, exc_type, format_string, *args, **kwargs):
"""Returns a new exception of the specified type from the point at which it is
invoked, with the specified formatted message as the reason.
The resulting exception will have its cause set to the Message object on which
error() was called. Additionally, if that message is a Request, a failure
response is immediately sent.
"""
assert issubclass(exc_type, MessageHandlingError)
silent = kwargs.pop("silent", False)
reason = format_string.format(*args, **kwargs)
exc = exc_type(reason, self, silent) # will log it
if isinstance(self, Request):
self.respond(exc)
return exc
def isnt_valid(self, *args, **kwargs):
"""Same as self.error(InvalidMessageError, ...)."""
return self.error(InvalidMessageError, *args, **kwargs)
def cant_handle(self, *args, **kwargs):
"""Same as self.error(MessageHandlingError, ...)."""
return self.error(MessageHandlingError, *args, **kwargs)
class Event(Message):
"""Represents an incoming event.
https://microsoft.github.io/debug-adapter-protocol/specification#event
It is guaranteed that body is a MessageDict associated with this Event, and so
are all the nested dicts in it. If "body" was missing or null in JSON, body is
an empty dict.
To handle the event, JsonMessageChannel tries to find a handler for this event in
JsonMessageChannel.handlers. Given event="X", if handlers.X_event exists, then it
is the specific handler for this event. Otherwise, handlers.event must exist, and
it is the generic handler for this event. A missing handler is a fatal error.
No further incoming messages are processed until the handler returns, except for
responses to requests that have wait_for_response() invoked on them.
To report failure to handle the event, the handler must raise an instance of
MessageHandlingError that applies_to() the Event object it was handling. Any such
failure is logged, after which the message loop moves on to the next message.
Helper methods Message.isnt_valid() and Message.cant_handle() can be used to raise
the appropriate exception type that applies_to() the Event object.
"""
def __init__(self, channel, seq, event, body, json=None):
super().__init__(channel, seq, json)
self.event = event
if isinstance(body, MessageDict) and hasattr(body, "associate_with"):
body.associate_with(self)
self.body = body
def describe(self):
return f"#{self.seq} event {json.repr(self.event)} from {self.channel}"
@property
def payload(self):
return self.body
@staticmethod
def _parse(channel, message_dict):
seq = message_dict("seq", int)
event = message_dict("event", str)
body = message_dict("body", _payload)
message = Event(channel, seq, event, body, json=message_dict)
channel._enqueue_handlers(message, message._handle)
def _handle(self):
channel = self.channel
handler = channel._get_handler_for("event", self.event)
try:
try:
result = handler(self)
assert (
result is None
), f"Handler {util.srcnameof(handler)} tried to respond to {self.describe()}."
except MessageHandlingError as exc:
if not exc.applies_to(self):
raise
log.error(
"Handler {0}\ncouldn't handle {1}:\n{2}",
util.srcnameof(handler),
self.describe(),
str(exc),
)
except Exception:
log.reraise_exception(
"Handler {0}\ncouldn't handle {1}:",
util.srcnameof(handler),
self.describe(),
)
NO_RESPONSE = object()
"""Can be returned from a request handler in lieu of the response body, to indicate
that no response is to be sent.
Request.respond() must be invoked explicitly at some later point to provide a response.
"""
class Request(Message):
"""Represents an incoming or an outgoing request.
Incoming requests are represented directly by instances of this class.
Outgoing requests are represented by instances of OutgoingRequest, which provides
additional functionality to handle responses.
For incoming requests, it is guaranteed that arguments is a MessageDict associated
with this Request, and so are all the nested dicts in it. If "arguments" was missing
or null in JSON, arguments is an empty dict.
To handle the request, JsonMessageChannel tries to find a handler for this request
in JsonMessageChannel.handlers. Given command="X", if handlers.X_request exists,
then it is the specific handler for this request. Otherwise, handlers.request must
exist, and it is the generic handler for this request. A missing handler is a fatal
error.
The handler is then invoked with the Request object as its sole argument.
If the handler itself invokes respond() on the Request at any point, then it must
not return any value.
Otherwise, if the handler returns NO_RESPONSE, no response to the request is sent.
It must be sent manually at some later point via respond().
Otherwise, a response to the request is sent with the returned value as the body.
To fail the request, the handler can return an instance of MessageHandlingError,
or respond() with one, or raise one such that it applies_to() the Request object
being handled.
Helper methods Message.isnt_valid() and Message.cant_handle() can be used to raise
the appropriate exception type that applies_to() the Request object.
"""
def __init__(self, channel, seq, command, arguments, json=None):
super().__init__(channel, seq, json)
self.command = command
if isinstance(arguments, MessageDict) and hasattr(arguments, "associate_with"):
arguments.associate_with(self)
self.arguments = arguments
self.response = None
"""Response to this request.
For incoming requests, it is set as soon as the request handler returns.
For outgoing requests, it is set as soon as the response is received, and
before self._handle_response is invoked.
"""
def describe(self):
return f"#{self.seq} request {json.repr(self.command)} from {self.channel}"
@property
def payload(self):
return self.arguments
def respond(self, body):
assert self.response is None
d = {"type": "response", "request_seq": self.seq, "command": self.command}
if isinstance(body, Exception):
d["success"] = False
d["message"] = str(body)
else:
d["success"] = True
if body is not None and body != {}:
d["body"] = body
with self.channel._send_message(d) as seq:
pass
self.response = Response(self.channel, seq, self, body)
@staticmethod
def _parse(channel, message_dict):
seq = message_dict("seq", int)
command = message_dict("command", str)
arguments = message_dict("arguments", _payload)
message = Request(channel, seq, command, arguments, json=message_dict)
channel._enqueue_handlers(message, message._handle)
def _handle(self):
channel = self.channel
handler = channel._get_handler_for("request", self.command)
try:
try:
result = handler(self)
except MessageHandlingError as exc:
if not exc.applies_to(self):
raise
result = exc
log.error(
"Handler {0}\ncouldn't handle {1}:\n{2}",
util.srcnameof(handler),
self.describe(),
str(exc),
)
if result is NO_RESPONSE:
assert self.response is None, (
"Handler {0} for {1} must not return NO_RESPONSE if it has already "
"invoked request.respond().".format(
util.srcnameof(handler), self.describe()
)
)
elif self.response is not None:
assert result is None or result is self.response.body, (
"Handler {0} for {1} must not return a response body if it has "
"already invoked request.respond().".format(
util.srcnameof(handler), self.describe()
)
)
else:
assert result is not None, (
"Handler {0} for {1} must either call request.respond() before it "
"returns, or return the response body, or return NO_RESPONSE.".format(
util.srcnameof(handler), self.describe()
)
)
try:
self.respond(result)
except NoMoreMessages:
log.warning(
"Channel was closed before the response from handler {0} to {1} could be sent",
util.srcnameof(handler),
self.describe(),
)
except Exception:
log.reraise_exception(
"Handler {0}\ncouldn't handle {1}:",
util.srcnameof(handler),
self.describe(),
)
class OutgoingRequest(Request):
"""Represents an outgoing request, for which it is possible to wait for a
response to be received, and register a response handler.
"""
_parse = _handle = None
def __init__(self, channel, seq, command, arguments):
super().__init__(channel, seq, command, arguments)
self._response_handlers = []
def describe(self):
return f"{self.seq} request {json.repr(self.command)} to {self.channel}"
def wait_for_response(self, raise_if_failed=True):
"""Waits until a response is received for this request, records the Response
object for it in self.response, and returns response.body.
If no response was received from the other party before the channel closed,
self.response is a synthesized Response with body=NoMoreMessages().
If raise_if_failed=True and response.success is False, raises response.body
instead of returning.
"""
with self.channel:
while self.response is None:
self.channel._handlers_enqueued.wait()
if raise_if_failed and not self.response.success:
raise self.response.body
return self.response.body
def on_response(self, response_handler):
"""Registers a handler to invoke when a response is received for this request.
The handler is invoked with Response as its sole argument.
If response has already been received, invokes the handler immediately.
It is guaranteed that self.response is set before the handler is invoked.
If no response was received from the other party before the channel closed,
self.response is a dummy Response with body=NoMoreMessages().
The handler is always invoked asynchronously on an unspecified background
thread - thus, the caller of on_response() can never be blocked or deadlocked
by the handler.
No further incoming messages are processed until the handler returns, except for
responses to requests that have wait_for_response() invoked on them.
"""
with self.channel:
self._response_handlers.append(response_handler)
self._enqueue_response_handlers()
def _enqueue_response_handlers(self):
response = self.response
if response is None:
# Response._parse() will submit the handlers when response is received.
return
def run_handlers():
for handler in handlers:
try:
try:
handler(response)
except MessageHandlingError as exc:
if not exc.applies_to(response):
raise
log.error(
"Handler {0}\ncouldn't handle {1}:\n{2}",
util.srcnameof(handler),
response.describe(),
str(exc),
)
except Exception:
log.reraise_exception(
"Handler {0}\ncouldn't handle {1}:",
util.srcnameof(handler),
response.describe(),
)
handlers = self._response_handlers[:]
self.channel._enqueue_handlers(response, run_handlers)
del self._response_handlers[:]
class Response(Message):
"""Represents an incoming or an outgoing response to a Request.
https://microsoft.github.io/debug-adapter-protocol/specification#response
error_message corresponds to "message" in JSON, and is renamed for clarity.
If success is False, body is None. Otherwise, it is a MessageDict associated
with this Response, and so are all the nested dicts in it. If "body" was missing
or null in JSON, body is an empty dict.
If this is a response to an outgoing request, it will be handled by the handler
registered via self.request.on_response(), if any.
Regardless of whether there is such a handler, OutgoingRequest.wait_for_response()
can also be used to retrieve and handle the response. If there is a handler, it is
executed before wait_for_response() returns.
No further incoming messages are processed until the handler returns, except for
responses to requests that have wait_for_response() invoked on them.
To report failure to handle the event, the handler must raise an instance of
MessageHandlingError that applies_to() the Response object it was handling. Any
such failure is logged, after which the message loop moves on to the next message.
Helper methods Message.isnt_valid() and Message.cant_handle() can be used to raise
the appropriate exception type that applies_to() the Response object.
"""
def __init__(self, channel, seq, request, body, json=None):
super().__init__(channel, seq, json)
self.request = request
"""The request to which this is the response."""
if isinstance(body, MessageDict) and hasattr(body, "associate_with"):
body.associate_with(self)
self.body = body
"""Body of the response if the request was successful, or an instance
of some class derived from Exception it it was not.
If a response was received from the other side, but request failed, it is an
instance of MessageHandlingError containing the received error message. If the
error message starts with InvalidMessageError.PREFIX, then it's an instance of
the InvalidMessageError specifically, and that prefix is stripped.
If no response was received from the other party before the channel closed,
it is an instance of NoMoreMessages.
"""
def describe(self):
return f"#{self.seq} response to {self.request.describe()}"
@property
def payload(self):
return self.body
@property
def success(self):
"""Whether the request succeeded or not."""
return not isinstance(self.body, Exception)
@property
def result(self):
"""Result of the request. Returns the value of response.body, unless it
is an exception, in which case it is raised instead.
"""
if self.success:
return self.body
else:
raise self.body
@staticmethod
def _parse(channel, message_dict, body=None):
seq = message_dict("seq", int) if (body is None) else None
request_seq = message_dict("request_seq", int)
command = message_dict("command", str)
success = message_dict("success", bool)
if body is None:
if success:
body = message_dict("body", _payload)
else:
error_message = message_dict("message", str)
exc_type = MessageHandlingError
if error_message.startswith(InvalidMessageError.PREFIX):
error_message = error_message[len(InvalidMessageError.PREFIX) :]
exc_type = InvalidMessageError
body = exc_type(error_message, silent=True)
try:
with channel:
request = channel._sent_requests.pop(request_seq)
known_request = True
except KeyError:
# Synthetic Request that only has seq and command as specified in response
# JSON, for error reporting purposes.
request = OutgoingRequest(channel, request_seq, command, "<unknown>")
known_request = False
if not success:
body.cause = request
response = Response(channel, seq, request, body, json=message_dict)
with channel:
request.response = response
request._enqueue_response_handlers()
if known_request:
return response
else:
raise response.isnt_valid(
"request_seq={0} does not match any known request", request_seq
)
class Disconnect(Message):
"""A dummy message used to represent disconnect. It's always the last message
received from any channel.
"""
def __init__(self, channel):
super().__init__(channel, None)
def describe(self):
return f"disconnect from {self.channel}"
class MessageHandlingError(Exception):
"""Indicates that a message couldn't be handled for some reason.
If the reason is a contract violation - i.e. the message that was handled did not
conform to the protocol specification - InvalidMessageError, which is a subclass,
should be used instead.
If any message handler raises an exception not derived from this class, it will
escape the message loop unhandled, and terminate the process.
If any message handler raises this exception, but applies_to(message) is False, it
is treated as if it was a generic exception, as desribed above. Thus, if a request
handler issues another request of its own, and that one fails, the failure is not
silently propagated. However, a request that is delegated via Request.delegate()
will also propagate failures back automatically. For manual propagation, catch the
exception, and call exc.propagate().
If any event handler raises this exception, and applies_to(event) is True, the
exception is silently swallowed by the message loop.
If any request handler raises this exception, and applies_to(request) is True, the
exception is silently swallowed by the message loop, and a failure response is sent
with "message" set to str(reason).
Note that, while errors are not logged when they're swallowed by the message loop,
by that time they have already been logged by their __init__ (when instantiated).
"""
def __init__(self, reason, cause=None, silent=False):
"""Creates a new instance of this class, and immediately logs the exception.
Message handling errors are logged immediately unless silent=True, so that the
precise context in which they occured can be determined from the surrounding
log entries.
"""
self.reason = reason
"""Why it couldn't be handled. This can be any object, but usually it's either
str or Exception.
"""
assert cause is None or isinstance(cause, Message)
self.cause = cause
"""The Message object for the message that couldn't be handled. For responses
to unknown requests, this is a synthetic Request.
"""
if not silent:
try:
raise self
except MessageHandlingError:
log.swallow_exception()
def __hash__(self):
return hash((self.reason, id(self.cause)))
def __eq__(self, other):
if not isinstance(other, MessageHandlingError):
return NotImplemented
if type(self) is not type(other):
return NotImplemented
if self.reason != other.reason:
return False
if self.cause is not None and other.cause is not None:
if self.cause.seq != other.cause.seq:
return False
return True
def __ne__(self, other):
return not self == other
def __str__(self):
return str(self.reason)
def __repr__(self):
s = type(self).__name__
if self.cause is None:
s += f"reason={self.reason!r})"
else:
s += f"channel={self.cause.channel.name!r}, cause={self.cause.seq!r}, reason={self.reason!r})"
return s
def applies_to(self, message):
"""Whether this MessageHandlingError can be treated as a reason why the
handling of message failed.
If self.cause is None, this is always true.
If self.cause is not None, this is only true if cause is message.
"""
return self.cause is None or self.cause is message
def propagate(self, new_cause):
"""Propagates this error, raising a new instance of the same class with the
same reason, but a different cause.
"""
raise type(self)(self.reason, new_cause, silent=True)
class InvalidMessageError(MessageHandlingError):
"""Indicates that an incoming message did not follow the protocol specification -
for example, it was missing properties that are required, or the message itself
is not allowed in the current state.
Raised by MessageDict in lieu of KeyError for missing keys.
"""
PREFIX = "Invalid message: "
"""Automatically prepended to the "message" property in JSON responses, when the
handler raises InvalidMessageError.
If a failed response has "message" property that starts with this prefix, it is
reported as InvalidMessageError rather than MessageHandlingError.
"""
def __str__(self):
return InvalidMessageError.PREFIX + str(self.reason)
class JsonMessageChannel(object):
"""Implements a JSON message channel on top of a raw JSON message stream, with
support for DAP requests, responses, and events.
The channel can be locked for exclusive use via the with-statement::
with channel:
channel.send_request(...)
# No interleaving messages can be sent here from other threads.
channel.send_event(...)
"""
def __init__(self, stream, handlers=None, name=None):
self.stream = stream
self.handlers = handlers
self.name = name if name is not None else stream.name
self.started = False
self._lock = threading.RLock()
self._closed = False
self._seq_iter = itertools.count(1)
self._sent_requests = {} # {seq: Request}
self._handler_queue = [] # [(what, handler)]
self._handlers_enqueued = threading.Condition(self._lock)
self._handler_thread = None
self._parser_thread = None
def __str__(self):
return self.name
def __repr__(self):
return f"{type(self).__name__}({self.name!r})"
def __enter__(self):
self._lock.acquire()
return self
def __exit__(self, exc_type, exc_value, exc_tb):
self._lock.release()
def close(self):
"""Closes the underlying stream.
This does not immediately terminate any handlers that are already executing,
but they will be unable to respond. No new request or event handlers will
execute after this method is called, even for messages that have already been
received. However, response handlers will continue to executed for any request
that is still pending, as will any handlers registered via on_response().
"""
with self:
if not self._closed:
self._closed = True
self.stream.close()
def start(self):
"""Starts a message loop which parses incoming messages and invokes handlers
for them on a background thread, until the channel is closed.
Incoming messages, including responses to requests, will not be processed at
all until this is invoked.
"""
assert not self.started
self.started = True
self._parser_thread = threading.Thread(
target=self._parse_incoming_messages, name=f"{self} message parser"
)
hide_thread_from_debugger(self._parser_thread)
self._parser_thread.daemon = True
self._parser_thread.start()
def wait(self):
"""Waits for the message loop to terminate, and for all enqueued Response
message handlers to finish executing.
"""
parser_thread = self._parser_thread
try:
if parser_thread is not None:
parser_thread.join()
except AssertionError:
log.debug("Handled error joining parser thread.")
try:
handler_thread = self._handler_thread
if handler_thread is not None:
handler_thread.join()
except AssertionError:
log.debug("Handled error joining handler thread.")
# Order of keys for _prettify() - follows the order of properties in
# https://microsoft.github.io/debug-adapter-protocol/specification
_prettify_order = (
"seq",
"type",
"request_seq",
"success",
"command",
"event",
"message",
"arguments",
"body",
"error",
)
def _prettify(self, message_dict):
"""Reorders items in a MessageDict such that it is more readable."""
for key in self._prettify_order:
if key not in message_dict:
continue
value = message_dict[key]
del message_dict[key]
message_dict[key] = value
@contextlib.contextmanager
def _send_message(self, message):
"""Sends a new message to the other party.
Generates a new sequence number for the message, and provides it to the
caller before the message is sent, using the context manager protocol::
with send_message(...) as seq:
# The message hasn't been sent yet.
...
# Now the message has been sent.
Safe to call concurrently for the same channel from different threads.
"""
assert "seq" not in message
with self:
seq = next(self._seq_iter)
message = MessageDict(None, message)
message["seq"] = seq
self._prettify(message)
with self:
yield seq
self.stream.write_json(message)
def send_request(self, command, arguments=None, on_before_send=None):
"""Sends a new request, and returns the OutgoingRequest object for it.
If arguments is None or {}, "arguments" will be omitted in JSON.
If on_before_send is not None, invokes on_before_send() with the request
object as the sole argument, before the request actually gets sent.
Does not wait for response - use OutgoingRequest.wait_for_response().
Safe to call concurrently for the same channel from different threads.
"""
d = {"type": "request", "command": command}
if arguments is not None and arguments != {}:
d["arguments"] = arguments
with self._send_message(d) as seq:
request = OutgoingRequest(self, seq, command, arguments)
if on_before_send is not None:
on_before_send(request)
self._sent_requests[seq] = request
return request
def send_event(self, event, body=None):
"""Sends a new event.
If body is None or {}, "body" will be omitted in JSON.
Safe to call concurrently for the same channel from different threads.
"""
d = {"type": "event", "event": event}
if body is not None and body != {}:
d["body"] = body
with self._send_message(d):
pass
def request(self, *args, **kwargs):
"""Same as send_request(...).wait_for_response()"""
return self.send_request(*args, **kwargs).wait_for_response()
def propagate(self, message):
"""Sends a new message with the same type and payload.
If it was a request, returns the new OutgoingRequest object for it.
"""
assert message.is_request() or message.is_event()
if message.is_request():
return self.send_request(message.command, message.arguments)
else:
self.send_event(message.event, message.body)
def delegate(self, message):
"""Like propagate(message).wait_for_response(), but will also propagate
any resulting MessageHandlingError back.
"""
try:
result = self.propagate(message)
if result.is_request():
result = result.wait_for_response()
return result
except MessageHandlingError as exc:
exc.propagate(message)
def _parse_incoming_messages(self):
log.debug("Starting message loop for channel {0}", self)
try:
while True:
self._parse_incoming_message()
except NoMoreMessages as exc:
log.debug("Exiting message loop for channel {0}: {1}", self, exc)
with self:
# Generate dummy responses for all outstanding requests.
err_message = str(exc)
# Response._parse() will remove items from _sent_requests, so
# make a snapshot before iterating.
sent_requests = list(self._sent_requests.values())
for request in sent_requests:
response_json = MessageDict(
None,
{
"seq": -1,
"request_seq": request.seq,
"command": request.command,
"success": False,
"message": err_message,
},
)
Response._parse(self, response_json, body=exc)
assert not len(self._sent_requests)
self._enqueue_handlers(Disconnect(self), self._handle_disconnect)
self.close()
_message_parsers = {
"event": Event._parse,
"request": Request._parse,
"response": Response._parse,
}
def _parse_incoming_message(self):
"""Reads incoming messages, parses them, and puts handlers into the queue
for _run_handlers() to invoke, until the channel is closed.
"""
# Set up a dedicated decoder for this message, to create MessageDict instances
# for all JSON objects, and track them so that they can be later wired up to
# the Message they belong to, once it is instantiated.
def object_hook(d):
d = MessageDict(None, d)
if "seq" in d:
self._prettify(d)
d.associate_with = associate_with
message_dicts.append(d)
return d
# A hack to work around circular dependency between messages, and instances of
# MessageDict in their payload. We need to set message for all of them, but it
# cannot be done until the actual Message is created - which happens after the
# dicts are created during deserialization.
#
# So, upon deserialization, every dict in the message payload gets a method
# that can be called to set MessageDict.message for *all* dicts belonging to
# that message. This method can then be invoked on the top-level dict by the
# parser, after it has parsed enough of the dict to create the appropriate
# instance of Event, Request, or Response for this message.
def associate_with(message):
for d in message_dicts:
d.message = message
del d.associate_with
message_dicts = []
decoder = self.stream.json_decoder_factory(object_hook=object_hook)
message_dict = self.stream.read_json(decoder)
assert isinstance(message_dict, MessageDict) # make sure stream used decoder
msg_type = message_dict("type", json.enum("event", "request", "response"))
parser = self._message_parsers[msg_type]
try:
parser(self, message_dict)
except InvalidMessageError as exc:
log.error(
"Failed to parse message in channel {0}: {1} in:\n{2}",
self,
str(exc),
json.repr(message_dict),
)
except Exception as exc:
if isinstance(exc, NoMoreMessages) and exc.stream is self.stream:
raise
log.swallow_exception(
"Fatal error in channel {0} while parsing:\n{1}",
self,
json.repr(message_dict),
)
os._exit(1)
def _enqueue_handlers(self, what, *handlers):
"""Enqueues handlers for _run_handlers() to run.
`what` is the Message being handled, and is used for logging purposes.
If the background thread with _run_handlers() isn't running yet, starts it.
"""
with self:
self._handler_queue.extend((what, handler) for handler in handlers)
self._handlers_enqueued.notify_all()
# If there is anything to handle, but there's no handler thread yet,
# spin it up. This will normally happen only once, on the first call
# to _enqueue_handlers(), and that thread will run all the handlers
# for parsed messages. However, this can also happen is somebody calls
# Request.on_response() - possibly concurrently from multiple threads -
# after the channel has already been closed, and the initial handler
# thread has exited. In this case, we spin up a new thread just to run
# the enqueued response handlers, and it will exit as soon as it's out
# of handlers to run.
if len(self._handler_queue) and self._handler_thread is None:
self._handler_thread = threading.Thread(
target=self._run_handlers,
name=f"{self} message handler",
)
hide_thread_from_debugger(self._handler_thread)
self._handler_thread.start()
def _run_handlers(self):
"""Runs enqueued handlers until the channel is closed, or until the handler
queue is empty once the channel is closed.
"""
while True:
with self:
closed = self._closed
if closed:
# Wait for the parser thread to wrap up and enqueue any remaining
# handlers, if it is still running.
self._parser_thread.join()
# From this point on, _enqueue_handlers() can only get called
# from Request.on_response().
with self:
if not closed and not len(self._handler_queue):
# Wait for something to process.
self._handlers_enqueued.wait()
# Make a snapshot before releasing the lock.
handlers = self._handler_queue[:]
del self._handler_queue[:]
if closed and not len(handlers):
# Nothing to process, channel is closed, and parser thread is
# not running anymore - time to quit! If Request.on_response()
# needs to call _enqueue_handlers() later, it will spin up
# a new handler thread.
self._handler_thread = None
return
for what, handler in handlers:
# If the channel is closed, we don't want to process any more events
# or requests - only responses and the final disconnect handler. This
# is to guarantee that if a handler calls close() on its own channel,
# the corresponding request or event is the last thing to be processed.
if closed and handler in (Event._handle, Request._handle):
continue
with log.prefixed("/handling {0}/\n", what.describe()):
try:
handler()
except Exception:
# It's already logged by the handler, so just fail fast.
self.close()
os._exit(1)
def _get_handler_for(self, type, name):
"""Returns the handler for a message of a given type."""
with self:
handlers = self.handlers
for handler_name in (name + "_" + type, type):
try:
return getattr(handlers, handler_name)
except AttributeError:
continue
raise AttributeError(
"handler object {0} for channel {1} has no handler for {2} {3!r}".format(
util.srcnameof(handlers),
self,
type,
name,
)
)
def _handle_disconnect(self):
handler = getattr(self.handlers, "disconnect", lambda: None)
try:
handler()
except Exception:
log.reraise_exception(
"Handler {0}\ncouldn't handle disconnect from {1}:",
util.srcnameof(handler),
self,
)
class MessageHandlers(object):
"""A simple delegating message handlers object for use with JsonMessageChannel.
For every argument provided, the object gets an attribute with the corresponding
name and value.
"""
def __init__(self, **kwargs):
for name, func in kwargs.items():
setattr(self, name, func)
| 56,396 | Python | 36.448207 | 106 | 0.601337 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/common/singleton.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
import functools
import threading
class Singleton(object):
"""A base class for a class of a singleton object.
For any derived class T, the first invocation of T() will create the instance,
and any future invocations of T() will return that instance.
Concurrent invocations of T() from different threads are safe.
"""
# A dual-lock scheme is necessary to be thread safe while avoiding deadlocks.
# _lock_lock is shared by all singleton types, and is used to construct their
# respective _lock instances when invoked for a new type. Then _lock is used
# to synchronize all further access for that type, including __init__. This way,
# __init__ for any given singleton can access another singleton, and not get
# deadlocked if that other singleton is trying to access it.
_lock_lock = threading.RLock()
_lock = None
# Specific subclasses will get their own _instance set in __new__.
_instance = None
_is_shared = None # True if shared, False if exclusive
def __new__(cls, *args, **kwargs):
# Allow arbitrary args and kwargs if shared=False, because that is guaranteed
# to construct a new singleton if it succeeds. Otherwise, this call might end
# up returning an existing instance, which might have been constructed with
# different arguments, so allowing them is misleading.
assert not kwargs.get("shared", False) or (len(args) + len(kwargs)) == 0, (
"Cannot use constructor arguments when accessing a Singleton without "
"specifying shared=False."
)
# Avoid locking as much as possible with repeated double-checks - the most
# common path is when everything is already allocated.
if not cls._instance:
# If there's no per-type lock, allocate it.
if cls._lock is None:
with cls._lock_lock:
if cls._lock is None:
cls._lock = threading.RLock()
# Now that we have a per-type lock, we can synchronize construction.
if not cls._instance:
with cls._lock:
if not cls._instance:
cls._instance = object.__new__(cls)
# To prevent having __init__ invoked multiple times, call
# it here directly, and then replace it with a stub that
# does nothing - that stub will get auto-invoked on return,
# and on all future singleton accesses.
cls._instance.__init__()
cls.__init__ = lambda *args, **kwargs: None
return cls._instance
def __init__(self, *args, **kwargs):
"""Initializes the singleton instance. Guaranteed to only be invoked once for
any given type derived from Singleton.
If shared=False, the caller is requesting a singleton instance for their own
exclusive use. This is only allowed if the singleton has not been created yet;
if so, it is created and marked as being in exclusive use. While it is marked
as such, all attempts to obtain an existing instance of it immediately raise
an exception. The singleton can eventually be promoted to shared use by calling
share() on it.
"""
shared = kwargs.pop("shared", True)
with self:
if shared:
assert (
type(self)._is_shared is not False
), "Cannot access a non-shared Singleton."
type(self)._is_shared = True
else:
assert type(self)._is_shared is None, "Singleton is already created."
def __enter__(self):
"""Lock this singleton to prevent concurrent access."""
type(self)._lock.acquire()
return self
def __exit__(self, exc_type, exc_value, exc_tb):
"""Unlock this singleton to allow concurrent access."""
type(self)._lock.release()
def share(self):
"""Share this singleton, if it was originally created with shared=False."""
type(self)._is_shared = True
class ThreadSafeSingleton(Singleton):
"""A singleton that incorporates a lock for thread-safe access to its members.
The lock can be acquired using the context manager protocol, and thus idiomatic
use is in conjunction with a with-statement. For example, given derived class T::
with T() as t:
t.x = t.frob(t.y)
All access to the singleton from the outside should follow this pattern for both
attributes and method calls. Singleton members can assume that self is locked by
the caller while they're executing, but recursive locking of the same singleton
on the same thread is also permitted.
"""
threadsafe_attrs = frozenset()
"""Names of attributes that are guaranteed to be used in a thread-safe manner.
This is typically used in conjunction with share() to simplify synchronization.
"""
readonly_attrs = frozenset()
"""Names of attributes that are readonly. These can be read without locking, but
cannot be written at all.
Every derived class gets its own separate set. Thus, for any given singleton type
T, an attribute can be made readonly after setting it, with T.readonly_attrs.add().
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Make sure each derived class gets a separate copy.
type(self).readonly_attrs = set(type(self).readonly_attrs)
# Prevent callers from reading or writing attributes without locking, except for
# reading attributes listed in threadsafe_attrs, and methods specifically marked
# with @threadsafe_method. Such methods should perform the necessary locking to
# ensure thread safety for the callers.
@staticmethod
def assert_locked(self):
lock = type(self)._lock
assert lock.acquire(blocking=False), (
"ThreadSafeSingleton accessed without locking. Either use with-statement, "
"or if it is a method or property, mark it as @threadsafe_method or with "
"@autolocked_method, as appropriate."
)
lock.release()
def __getattribute__(self, name):
value = object.__getattribute__(self, name)
if name not in (type(self).threadsafe_attrs | type(self).readonly_attrs):
if not getattr(value, "is_threadsafe_method", False):
ThreadSafeSingleton.assert_locked(self)
return value
def __setattr__(self, name, value):
assert name not in type(self).readonly_attrs, "This attribute is read-only."
if name not in type(self).threadsafe_attrs:
ThreadSafeSingleton.assert_locked(self)
return object.__setattr__(self, name, value)
def threadsafe_method(func):
"""Marks a method of a ThreadSafeSingleton-derived class as inherently thread-safe.
A method so marked must either not use any singleton state, or lock it appropriately.
"""
func.is_threadsafe_method = True
return func
def autolocked_method(func):
"""Automatically synchronizes all calls of a method of a ThreadSafeSingleton-derived
class by locking the singleton for the duration of each call.
"""
@functools.wraps(func)
@threadsafe_method
def lock_and_call(self, *args, **kwargs):
with self:
return func(self, *args, **kwargs)
return lock_and_call
| 7,666 | Python | 40.22043 | 89 | 0.644665 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/server/attach_pid_injected.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
"""Script injected into the debuggee process during attach-to-PID."""
import os
__file__ = os.path.abspath(__file__)
_debugpy_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
def attach(setup):
log = None
try:
import sys
if "threading" not in sys.modules:
try:
def on_warn(msg):
print(msg, file=sys.stderr)
def on_exception(msg):
print(msg, file=sys.stderr)
def on_critical(msg):
print(msg, file=sys.stderr)
pydevd_attach_to_process_path = os.path.join(
_debugpy_dir,
"debugpy",
"_vendored",
"pydevd",
"pydevd_attach_to_process",
)
assert os.path.exists(pydevd_attach_to_process_path)
sys.path.insert(0, pydevd_attach_to_process_path)
# NOTE: that it's not a part of the pydevd PYTHONPATH
import attach_script
attach_script.fix_main_thread_id(
on_warn=on_warn, on_exception=on_exception, on_critical=on_critical
)
# NOTE: At this point it should be safe to remove this.
sys.path.remove(pydevd_attach_to_process_path)
except:
import traceback
traceback.print_exc()
raise
sys.path.insert(0, _debugpy_dir)
try:
import debugpy
import debugpy.server
from debugpy.common import json, log
import pydevd
finally:
assert sys.path[0] == _debugpy_dir
del sys.path[0]
py_db = pydevd.get_global_debugger()
if py_db is not None:
py_db.dispose_and_kill_all_pydevd_threads(wait=False)
if setup["log_to"] is not None:
debugpy.log_to(setup["log_to"])
log.info("Configuring injected debugpy: {0}", json.repr(setup))
if setup["mode"] == "listen":
debugpy.listen(setup["address"])
elif setup["mode"] == "connect":
debugpy.connect(
setup["address"], access_token=setup["adapter_access_token"]
)
else:
raise AssertionError(repr(setup))
except:
import traceback
traceback.print_exc()
if log is None:
raise
else:
log.reraise_exception()
log.info("debugpy injected successfully")
| 2,734 | Python | 28.408602 | 87 | 0.525969 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/server/__init__.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
# "force_pydevd" must be imported first to ensure (via side effects)
# that the debugpy-vendored copy of pydevd gets used.
import debugpy._vendored.force_pydevd # noqa
| 323 | Python | 39.499995 | 68 | 0.773994 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/server/api.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
import codecs
import os
import pydevd
import socket
import sys
import threading
import debugpy
from debugpy import adapter
from debugpy.common import json, log, sockets
from _pydevd_bundle.pydevd_constants import get_global_debugger
from pydevd_file_utils import absolute_path
from debugpy.common.util import hide_debugpy_internals
_tls = threading.local()
# TODO: "gevent", if possible.
_config = {
"qt": "none",
"subProcess": True,
"python": sys.executable,
"pythonEnv": {},
}
_config_valid_values = {
# If property is not listed here, any value is considered valid, so long as
# its type matches that of the default value in _config.
"qt": ["auto", "none", "pyside", "pyside2", "pyqt4", "pyqt5"],
}
# This must be a global to prevent it from being garbage collected and triggering
# https://bugs.python.org/issue37380.
_adapter_process = None
def _settrace(*args, **kwargs):
log.debug("pydevd.settrace(*{0!r}, **{1!r})", args, kwargs)
# The stdin in notification is not acted upon in debugpy, so, disable it.
kwargs.setdefault("notify_stdin", False)
try:
return pydevd.settrace(*args, **kwargs)
except Exception:
raise
else:
_settrace.called = True
_settrace.called = False
def ensure_logging():
"""Starts logging to log.log_dir, if it hasn't already been done."""
if ensure_logging.ensured:
return
ensure_logging.ensured = True
log.to_file(prefix="debugpy.server")
log.describe_environment("Initial environment:")
if log.log_dir is not None:
pydevd.log_to(log.log_dir + "/debugpy.pydevd.log")
ensure_logging.ensured = False
def log_to(path):
if ensure_logging.ensured:
raise RuntimeError("logging has already begun")
log.debug("log_to{0!r}", (path,))
if path is sys.stderr:
log.stderr.levels |= set(log.LEVELS)
else:
log.log_dir = path
def configure(properties=None, **kwargs):
if _settrace.called:
raise RuntimeError("debug adapter is already running")
ensure_logging()
log.debug("configure{0!r}", (properties, kwargs))
if properties is None:
properties = kwargs
else:
properties = dict(properties)
properties.update(kwargs)
for k, v in properties.items():
if k not in _config:
raise ValueError("Unknown property {0!r}".format(k))
expected_type = type(_config[k])
if type(v) is not expected_type:
raise ValueError("{0!r} must be a {1}".format(k, expected_type.__name__))
valid_values = _config_valid_values.get(k)
if (valid_values is not None) and (v not in valid_values):
raise ValueError("{0!r} must be one of: {1!r}".format(k, valid_values))
_config[k] = v
def _starts_debugging(func):
def debug(address, **kwargs):
if _settrace.called:
raise RuntimeError("this process already has a debug adapter")
try:
_, port = address
except Exception:
port = address
address = ("127.0.0.1", port)
try:
port.__index__() # ensure it's int-like
except Exception:
raise ValueError("expected port or (host, port)")
if not (0 <= port < 2 ** 16):
raise ValueError("invalid port number")
ensure_logging()
log.debug("{0}({1!r}, **{2!r})", func.__name__, address, kwargs)
log.info("Initial debug configuration: {0}", json.repr(_config))
qt_mode = _config.get("qt", "none")
if qt_mode != "none":
pydevd.enable_qt_support(qt_mode)
settrace_kwargs = {
"suspend": False,
"patch_multiprocessing": _config.get("subProcess", True),
}
if hide_debugpy_internals():
debugpy_path = os.path.dirname(absolute_path(debugpy.__file__))
settrace_kwargs["dont_trace_start_patterns"] = (debugpy_path,)
settrace_kwargs["dont_trace_end_patterns"] = (str("debugpy_launcher.py"),)
try:
return func(address, settrace_kwargs, **kwargs)
except Exception:
log.reraise_exception("{0}() failed:", func.__name__, level="info")
return debug
@_starts_debugging
def listen(address, settrace_kwargs, in_process_debug_adapter=False):
# Errors below are logged with level="info", because the caller might be catching
# and handling exceptions, and we don't want to spam their stderr unnecessarily.
if in_process_debug_adapter:
host, port = address
log.info("Listening: pydevd without debugpy adapter: {0}:{1}", host, port)
settrace_kwargs['patch_multiprocessing'] = False
_settrace(
host=host,
port=port,
wait_for_ready_to_run=False,
block_until_connected=False,
**settrace_kwargs
)
return
import subprocess
server_access_token = codecs.encode(os.urandom(32), "hex").decode("ascii")
try:
endpoints_listener = sockets.create_server("127.0.0.1", 0, timeout=10)
except Exception as exc:
log.swallow_exception("Can't listen for adapter endpoints:")
raise RuntimeError("can't listen for adapter endpoints: " + str(exc))
try:
endpoints_host, endpoints_port = endpoints_listener.getsockname()
log.info(
"Waiting for adapter endpoints on {0}:{1}...",
endpoints_host,
endpoints_port,
)
host, port = address
adapter_args = [
_config.get("python", sys.executable),
os.path.dirname(adapter.__file__),
"--for-server",
str(endpoints_port),
"--host",
host,
"--port",
str(port),
"--server-access-token",
server_access_token,
]
if log.log_dir is not None:
adapter_args += ["--log-dir", log.log_dir]
log.info("debugpy.listen() spawning adapter: {0}", json.repr(adapter_args))
# On Windows, detach the adapter from our console, if any, so that it doesn't
# receive Ctrl+C from it, and doesn't keep it open once we exit.
creationflags = 0
if sys.platform == "win32":
creationflags |= 0x08000000 # CREATE_NO_WINDOW
creationflags |= 0x00000200 # CREATE_NEW_PROCESS_GROUP
# On embedded applications, environment variables might not contain
# Python environment settings.
python_env = _config.get("pythonEnv")
if not bool(python_env):
python_env = None
# Adapter will outlive this process, so we shouldn't wait for it. However, we
# need to ensure that the Popen instance for it doesn't get garbage-collected
# by holding a reference to it in a non-local variable, to avoid triggering
# https://bugs.python.org/issue37380.
try:
global _adapter_process
_adapter_process = subprocess.Popen(
adapter_args, close_fds=True, creationflags=creationflags, env=python_env
)
if os.name == "posix":
# It's going to fork again to daemonize, so we need to wait on it to
# clean it up properly.
_adapter_process.wait()
else:
# Suppress misleading warning about child process still being alive when
# this process exits (https://bugs.python.org/issue38890).
_adapter_process.returncode = 0
pydevd.add_dont_terminate_child_pid(_adapter_process.pid)
except Exception as exc:
log.swallow_exception("Error spawning debug adapter:", level="info")
raise RuntimeError("error spawning debug adapter: " + str(exc))
try:
sock, _ = endpoints_listener.accept()
try:
sock.settimeout(None)
sock_io = sock.makefile("rb", 0)
try:
endpoints = json.loads(sock_io.read().decode("utf-8"))
finally:
sock_io.close()
finally:
sockets.close_socket(sock)
except socket.timeout:
log.swallow_exception(
"Timed out waiting for adapter to connect:", level="info"
)
raise RuntimeError("timed out waiting for adapter to connect")
except Exception as exc:
log.swallow_exception("Error retrieving adapter endpoints:", level="info")
raise RuntimeError("error retrieving adapter endpoints: " + str(exc))
finally:
endpoints_listener.close()
log.info("Endpoints received from adapter: {0}", json.repr(endpoints))
if "error" in endpoints:
raise RuntimeError(str(endpoints["error"]))
try:
server_host = str(endpoints["server"]["host"])
server_port = int(endpoints["server"]["port"])
client_host = str(endpoints["client"]["host"])
client_port = int(endpoints["client"]["port"])
except Exception as exc:
log.swallow_exception(
"Error parsing adapter endpoints:\n{0}\n",
json.repr(endpoints),
level="info",
)
raise RuntimeError("error parsing adapter endpoints: " + str(exc))
log.info(
"Adapter is accepting incoming client connections on {0}:{1}",
client_host,
client_port,
)
_settrace(
host=server_host,
port=server_port,
wait_for_ready_to_run=False,
block_until_connected=True,
access_token=server_access_token,
**settrace_kwargs
)
log.info("pydevd is connected to adapter at {0}:{1}", server_host, server_port)
return client_host, client_port
@_starts_debugging
def connect(address, settrace_kwargs, access_token=None):
host, port = address
_settrace(host=host, port=port, client_access_token=access_token, **settrace_kwargs)
class wait_for_client:
def __call__(self):
ensure_logging()
log.debug("wait_for_client()")
pydb = get_global_debugger()
if pydb is None:
raise RuntimeError("listen() or connect() must be called first")
cancel_event = threading.Event()
self.cancel = cancel_event.set
pydevd._wait_for_attach(cancel=cancel_event)
@staticmethod
def cancel():
raise RuntimeError("wait_for_client() must be called first")
wait_for_client = wait_for_client()
def is_client_connected():
return pydevd._is_attached()
def breakpoint():
ensure_logging()
if not is_client_connected():
log.info("breakpoint() ignored - debugger not attached")
return
log.debug("breakpoint()")
# Get the first frame in the stack that's not an internal frame.
pydb = get_global_debugger()
stop_at_frame = sys._getframe().f_back
while (
stop_at_frame is not None
and pydb.get_file_type(stop_at_frame) == pydb.PYDEV_FILE
):
stop_at_frame = stop_at_frame.f_back
_settrace(
suspend=True,
trace_only_current_thread=True,
patch_multiprocessing=False,
stop_at_frame=stop_at_frame,
)
stop_at_frame = None
def debug_this_thread():
ensure_logging()
log.debug("debug_this_thread()")
_settrace(suspend=False)
def trace_this_thread(should_trace):
ensure_logging()
log.debug("trace_this_thread({0!r})", should_trace)
pydb = get_global_debugger()
if should_trace:
pydb.enable_tracing()
else:
pydb.disable_tracing()
| 11,789 | Python | 31.213115 | 89 | 0.603359 |
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/server/cli.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
import json
import os
import re
import sys
from importlib.util import find_spec
# debugpy.__main__ should have preloaded pydevd properly before importing this module.
# Otherwise, some stdlib modules above might have had imported threading before pydevd
# could perform the necessary detours in it.
assert "pydevd" in sys.modules
import pydevd
# Note: use the one bundled from pydevd so that it's invisible for the user.
from _pydevd_bundle import pydevd_runpy as runpy
import debugpy
from debugpy.common import log
from debugpy.server import api
TARGET = "<filename> | -m <module> | -c <code> | --pid <pid>"
HELP = """debugpy {0}
See https://aka.ms/debugpy for documentation.
Usage: debugpy --listen | --connect
[<host>:]<port>
[--wait-for-client]
[--configure-<name> <value>]...
[--log-to <path>] [--log-to-stderr]
{1}
[<arg>]...
""".format(
debugpy.__version__, TARGET
)
class Options(object):
mode = None
address = None
log_to = None
log_to_stderr = False
target = None
target_kind = None
wait_for_client = False
adapter_access_token = None
options = Options()
options.config = {"qt": "none", "subProcess": True}
def in_range(parser, start, stop):
def parse(s):
n = parser(s)
if start is not None and n < start:
raise ValueError("must be >= {0}".format(start))
if stop is not None and n >= stop:
raise ValueError("must be < {0}".format(stop))
return n
return parse
pid = in_range(int, 0, None)
def print_help_and_exit(switch, it):
print(HELP, file=sys.stderr)
sys.exit(0)
def print_version_and_exit(switch, it):
print(debugpy.__version__)
sys.exit(0)
def set_arg(varname, parser=(lambda x: x)):
def do(arg, it):
value = parser(next(it))
setattr(options, varname, value)
return do
def set_const(varname, value):
def do(arg, it):
setattr(options, varname, value)
return do
def set_address(mode):
def do(arg, it):
if options.address is not None:
raise ValueError("--listen and --connect are mutually exclusive")
# It's either host:port, or just port.
value = next(it)
host, sep, port = value.partition(":")
if not sep:
host = "127.0.0.1"
port = value
try:
port = int(port)
except Exception:
port = -1
if not (0 <= port < 2 ** 16):
raise ValueError("invalid port number")
options.mode = mode
options.address = (host, port)
return do
def set_config(arg, it):
prefix = "--configure-"
assert arg.startswith(prefix)
name = arg[len(prefix) :]
value = next(it)
if name not in options.config:
raise ValueError("unknown property {0!r}".format(name))
expected_type = type(options.config[name])
try:
if expected_type is bool:
value = {"true": True, "false": False}[value.lower()]
else:
value = expected_type(value)
except Exception:
raise ValueError("{0!r} must be a {1}".format(name, expected_type.__name__))
options.config[name] = value
def set_target(kind, parser=(lambda x: x), positional=False):
def do(arg, it):
options.target_kind = kind
target = parser(arg if positional else next(it))
if isinstance(target, bytes):
# target may be the code, so, try some additional encodings...
try:
target = target.decode(sys.getfilesystemencoding())
except UnicodeDecodeError:
try:
target = target.decode("utf-8")
except UnicodeDecodeError:
import locale
target = target.decode(locale.getpreferredencoding(False))
options.target = target
return do
# fmt: off
switches = [
# Switch Placeholder Action
# ====== =========== ======
# Switches that are documented for use by end users.
("-(\\?|h|-help)", None, print_help_and_exit),
("-(V|-version)", None, print_version_and_exit),
("--log-to" , "<path>", set_arg("log_to")),
("--log-to-stderr", None, set_const("log_to_stderr", True)),
("--listen", "<address>", set_address("listen")),
("--connect", "<address>", set_address("connect")),
("--wait-for-client", None, set_const("wait_for_client", True)),
("--configure-.+", "<value>", set_config),
# Switches that are used internally by the client or debugpy itself.
("--adapter-access-token", "<token>", set_arg("adapter_access_token")),
# Targets. The "" entry corresponds to positional command line arguments,
# i.e. the ones not preceded by any switch name.
("", "<filename>", set_target("file", positional=True)),
("-m", "<module>", set_target("module")),
("-c", "<code>", set_target("code")),
("--pid", "<pid>", set_target("pid", pid)),
]
# fmt: on
def consume_argv():
while len(sys.argv) >= 2:
value = sys.argv[1]
del sys.argv[1]
yield value
def parse_argv():
seen = set()
it = consume_argv()
while True:
try:
arg = next(it)
except StopIteration:
raise ValueError("missing target: " + TARGET)
switch = arg
if not switch.startswith("-"):
switch = ""
for pattern, placeholder, action in switches:
if re.match("^(" + pattern + ")$", switch):
break
else:
raise ValueError("unrecognized switch " + switch)
if switch in seen:
raise ValueError("duplicate switch " + switch)
else:
seen.add(switch)
try:
action(arg, it)
except StopIteration:
assert placeholder is not None
raise ValueError("{0}: missing {1}".format(switch, placeholder))
except Exception as exc:
raise ValueError("invalid {0} {1}: {2}".format(switch, placeholder, exc))
if options.target is not None:
break
if options.mode is None:
raise ValueError("either --listen or --connect is required")
if options.adapter_access_token is not None and options.mode != "connect":
raise ValueError("--adapter-access-token requires --connect")
if options.target_kind == "pid" and options.wait_for_client:
raise ValueError("--pid does not support --wait-for-client")
assert options.target is not None
assert options.target_kind is not None
assert options.address is not None
def start_debugging(argv_0):
# We need to set up sys.argv[0] before invoking either listen() or connect(),
# because they use it to report the "process" event. Thus, we can't rely on
# run_path() and run_module() doing that, even though they will eventually.
sys.argv[0] = argv_0
log.debug("sys.argv after patching: {0!r}", sys.argv)
debugpy.configure(options.config)
if options.mode == "listen":
debugpy.listen(options.address)
elif options.mode == "connect":
debugpy.connect(options.address, access_token=options.adapter_access_token)
else:
raise AssertionError(repr(options.mode))
if options.wait_for_client:
debugpy.wait_for_client()
def run_file():
target = options.target
start_debugging(target)
# run_path has one difference with invoking Python from command-line:
# if the target is a file (rather than a directory), it does not add its
# parent directory to sys.path. Thus, importing other modules from the
# same directory is broken unless sys.path is patched here.
if os.path.isfile(target):
dir = os.path.dirname(target)
sys.path.insert(0, dir)
else:
log.debug("Not a file: {0!r}", target)
log.describe_environment("Pre-launch environment:")
log.info("Running file {0!r}", target)
runpy.run_path(target, run_name="__main__")
def run_module():
# Add current directory to path, like Python itself does for -m. This must
# be in place before trying to use find_spec below to resolve submodules.
sys.path.insert(0, str(""))
# We want to do the same thing that run_module() would do here, without
# actually invoking it.
argv_0 = sys.argv[0]
try:
spec = find_spec(options.target)
if spec is not None:
argv_0 = spec.origin
except Exception:
log.swallow_exception("Error determining module path for sys.argv")
start_debugging(argv_0)
log.describe_environment("Pre-launch environment:")
log.info("Running module {0!r}", options.target)
# Docs say that runpy.run_module is equivalent to -m, but it's not actually
# the case for packages - -m sets __name__ to "__main__", but run_module sets
# it to "pkg.__main__". This breaks everything that uses the standard pattern
# __name__ == "__main__" to detect being run as a CLI app. On the other hand,
# runpy._run_module_as_main is a private function that actually implements -m.
try:
run_module_as_main = runpy._run_module_as_main
except AttributeError:
log.warning("runpy._run_module_as_main is missing, falling back to run_module.")
runpy.run_module(options.target, alter_sys=True)
else:
run_module_as_main(options.target, alter_argv=True)
def run_code():
# Add current directory to path, like Python itself does for -c.
sys.path.insert(0, str(""))
code = compile(options.target, str("<string>"), str("exec"))
start_debugging(str("-c"))
log.describe_environment("Pre-launch environment:")
log.info("Running code:\n\n{0}", options.target)
eval(code, {})
def attach_to_pid():
pid = options.target
log.info("Attaching to process with PID={0}", pid)
encode = lambda s: list(bytearray(s.encode("utf-8"))) if s is not None else None
script_dir = os.path.dirname(debugpy.server.__file__)
assert os.path.exists(script_dir)
script_dir = encode(script_dir)
setup = {
"mode": options.mode,
"address": options.address,
"wait_for_client": options.wait_for_client,
"log_to": options.log_to,
"adapter_access_token": options.adapter_access_token,
}
setup = encode(json.dumps(setup))
python_code = """
import codecs;
import json;
import sys;
decode = lambda s: codecs.utf_8_decode(bytearray(s))[0] if s is not None else None;
script_dir = decode({script_dir});
setup = json.loads(decode({setup}));
sys.path.insert(0, script_dir);
import attach_pid_injected;
del sys.path[0];
attach_pid_injected.attach(setup);
"""
python_code = (
python_code.replace("\r", "")
.replace("\n", "")
.format(script_dir=script_dir, setup=setup)
)
log.info("Code to be injected: \n{0}", python_code.replace(";", ";\n"))
# pydevd restriction on characters in injected code.
assert not (
{'"', "'", "\r", "\n"} & set(python_code)
), "Injected code should not contain any single quotes, double quotes, or newlines."
pydevd_attach_to_process_path = os.path.join(
os.path.dirname(pydevd.__file__), "pydevd_attach_to_process"
)
assert os.path.exists(pydevd_attach_to_process_path)
sys.path.append(pydevd_attach_to_process_path)
try:
import add_code_to_python_process # noqa
log.info("Injecting code into process with PID={0} ...", pid)
add_code_to_python_process.run_python_code(
pid,
python_code,
connect_debugger_tracing=True,
show_debug_info=int(os.getenv("DEBUGPY_ATTACH_BY_PID_DEBUG_INFO", "0")),
)
except Exception:
log.reraise_exception("Code injection into PID={0} failed:", pid)
log.info("Code injection into PID={0} completed.", pid)
def main():
original_argv = list(sys.argv)
try:
parse_argv()
except Exception as exc:
print(str(HELP) + str("\nError: ") + str(exc), file=sys.stderr)
sys.exit(2)
if options.log_to is not None:
debugpy.log_to(options.log_to)
if options.log_to_stderr:
debugpy.log_to(sys.stderr)
api.ensure_logging()
log.info(
str("sys.argv before parsing: {0!r}\n" " after parsing: {1!r}"),
original_argv,
sys.argv,
)
try:
run = {
"file": run_file,
"module": run_module,
"code": run_code,
"pid": attach_to_pid,
}[options.target_kind]
run()
except SystemExit as exc:
log.reraise_exception(
"Debuggee exited via SystemExit: {0!r}", exc.code, level="debug"
)
| 13,289 | Python | 29.551724 | 89 | 0.589059 |
omniverse-code/kit/exts/omni.kit.debug.python/omni/kit/debug/python.py | import sys
import carb.tokens
import carb.settings
import omni.ext
import omni.kit.pipapi
# Try import to allow documentation build without debugpy
try:
import debugpy
except ModuleNotFoundError:
pass
def _print(msg):
print(f"[omni.kit.debug.python] {msg}")
def wait_for_client():
_print("Waiting for debugger to connect...")
debugpy.wait_for_client()
def breakpoint():
wait_for_client()
debugpy.breakpoint()
def is_attached() -> bool:
return debugpy.is_client_connected()
def enable_logging():
path = carb.tokens.get_tokens_interface().resolve("${logs}")
_print(f"Enabled logging to '{path}'")
debugpy.log_to(path)
_listen_address = None
def get_listen_address():
return _listen_address
class Extension(omni.ext.IExt):
def on_startup(self):
settings = carb.settings.get_settings()
host = settings.get("/exts/omni.kit.debug.python/host")
port = settings.get("/exts/omni.kit.debug.python/port")
debugpyLogging = settings.get("/exts/omni.kit.debug.python/debugpyLogging")
waitForClient = settings.get("/exts/omni.kit.debug.python/waitForClient")
break_ = settings.get("/exts/omni.kit.debug.python/break")
if debugpyLogging:
enable_logging()
# Start debugging server
python_exe = "python.exe" if sys.platform == "win32" else "bin/python3"
python_cmd = sys.prefix + "/" + python_exe
debugpy.configure(python=python_cmd)
global _listen_address
try:
_listen_address = debugpy.listen((host, port))
_print(f"Running python debugger on: {_listen_address}")
except Exception as e:
_print(f"Error running python debugger: {e}")
if waitForClient:
wait_for_client()
if break_:
breakpoint()
| 1,852 | Python | 23.706666 | 83 | 0.641469 |
omniverse-code/kit/exts/omni.activity.core/omni/activity/core/tests/test_activity.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.activity.core as act
import omni.kit.app
import omni.kit.test
class TestActivity(omni.kit.test.AsyncTestCase):
async def test_general(self):
called = []
def callback(node: act.INode):
self.assertEqual(node.name, "Test")
self.assertEqual(node.child_count, 1)
child = node.get_child(0)
self.assertEqual(child.name, "SubTest")
self.assertEqual(child.event_count, 2)
began = child.get_event(0)
ended = child.get_event(1)
self.assertEqual(began.event_type, act.EventType.BEGAN)
self.assertEqual(ended.event_type, act.EventType.ENDED)
self.assertEqual(began.payload["progress"], 0.0)
self.assertEqual(ended.payload["progress"], 1.0)
called.append(True)
id = act.get_instance().create_callback_to_pop(callback)
act.enable()
act.began("Test|SubTest", progress=0.0)
act.ended("Test|SubTest", progress=1.0)
act.disable()
act.get_instance().pump()
act.get_instance().remove_callback(id)
self.assertEquals(len(called), 1)
| 1,599 | Python | 31.653061 | 77 | 0.65666 |
omniverse-code/kit/exts/omni.hydra.index/omni/hydra/index/tests/__init__.py | from .nvindex_render_test import *
| 35 | Python | 16.999992 | 34 | 0.771429 |
omniverse-code/kit/exts/omni.hydra.index/omni/hydra/index/tests/nvindex_render_test.py | #!/usr/bin/env python3
import omni.kit.commands
import omni.kit.test
import omni.usd
from omni.rtx.tests import RtxTest, testSettings, postLoadTestSettings
from omni.rtx.tests.test_common import set_transform_helper, wait_for_update
from omni.kit.test_helpers_gfx.compare_utils import ComparisonMetric
from pxr import Sdf, Gf, UsdVol
from pathlib import Path
EXTENSION_DIR = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__))
TESTS_DIR = EXTENSION_DIR.joinpath('data', 'tests')
USD_DIR = TESTS_DIR.joinpath('usd')
GOLDEN_IMAGES_DIR = TESTS_DIR.joinpath('golden')
VOLUMES_DIR = TESTS_DIR.joinpath('volumes')
OUTPUTS_DIR = Path(omni.kit.test.get_test_output_path())
# This class is auto-discoverable by omni.kit.test
class IndexRenderTest(RtxTest):
WINDOW_SIZE = (512, 512)
THRESHOLD = 1e-5
async def setUp(self):
await super().setUp()
self.set_settings(testSettings)
self.ctx.new_stage()
self.add_dir_light()
await omni.kit.app.get_app().next_update_async()
self.set_settings(postLoadTestSettings)
# Overridden with custom paths
async def capture_and_compare(self, img_subdir: Path = "", golden_img_name=None, threshold=THRESHOLD,
metric: ComparisonMetric = ComparisonMetric.MEAN_ERROR_SQUARED):
golden_img_dir = GOLDEN_IMAGES_DIR.joinpath(img_subdir)
output_img_dir = OUTPUTS_DIR.joinpath(img_subdir)
if not golden_img_name:
golden_img_name = f"{self.__test_name}.png"
return await self._capture_and_compare(golden_img_name, threshold, output_img_dir, golden_img_dir, metric)
# Overridden with custom paths
def open_usd(self, usdSubpath: Path):
path = USD_DIR.joinpath(usdSubpath)
self.ctx.open_stage(str(path))
def get_volumes_path(self, volumeSubPath: Path):
return Sdf.AssetPath(str(VOLUMES_DIR.joinpath(volumeSubPath)))
def change_reference(self, prim_path, reference):
stage = self.ctx.get_stage()
prim = stage.GetPrimAtPath(prim_path)
ref = prim.GetReferences()
ref.ClearReferences()
ref.AddReference(Sdf.Reference(reference))
async def run_imge_test(self, usd_file: str, image_name: str, fn = None):
if usd_file:
self.open_usd(usd_file)
if fn:
fn()
await wait_for_update()
await self.capture_and_compare(golden_img_name=image_name)
#
# The tests
#
async def test_render_torus(self):
await self.run_imge_test('torus.usda', 'nvindex-torus.png')
async def test_render_torus_colormap(self):
await self.run_imge_test('torus-colormap.usda', 'nvindex-torus-colormap-2.png')
colormap_prim_path = '/World/Volume/mat/Colormap'
# Switch to another colormap
await self.run_imge_test(None, 'nvindex-torus-colormap-3.png',
lambda: self.change_reference(colormap_prim_path, './colormap3.usda'))
# Switch to colormap defined by RGBA control-points
colormap = self.ctx.get_stage().GetPrimAtPath(colormap_prim_path)
colormap.CreateAttribute("domain", Sdf.ValueTypeNames.Float2).Set((0.0, 1.0))
colormap.CreateAttribute("colormapSource", Sdf.ValueTypeNames.Token).Set("rgbaPoints")
colormap.CreateAttribute("xPoints", Sdf.ValueTypeNames.FloatArray).Set([0.5, 0.7, 1.0])
colormap.CreateAttribute("rgbaPoints", Sdf.ValueTypeNames.Float4Array).Set([(0, 1, 0, 0.14), (1, 0, 0, 0.25), (1, 1, 0, 0.25)])
await self.run_imge_test(None, 'nvindex-torus-colormap-rgba-points.png')
async def test_render_torus_shader(self):
await self.run_imge_test('torus-shader.usda', 'nvindex-torus-shader.png')
async def test_render_torus_settings(self):
await self.run_imge_test('torus-settings.usda', 'nvindex-torus-settings.png')
async def test_render_torus_create(self):
PRIM_PATH = "/World/volume"
open_vdb_asset = UsdVol.OpenVDBAsset.Define(self.ctx.get_stage(), PRIM_PATH + "/OpenVDBAsset")
open_vdb_asset.GetFilePathAttr().Set(self.get_volumes_path("torus.vdb"))
# Use default field in the OpenVDB file, instead of setting it explicitly:
# open_vdb_asset.GetFieldNameAttr().Set("torus_fog")
volume = UsdVol.Volume.Define(self.ctx.get_stage(), PRIM_PATH)
volume.CreateFieldRelationship("torus", open_vdb_asset.GetPath())
set_transform_helper(volume.GetPath(), translate=Gf.Vec3d(0, 150, 0), scale=Gf.Vec3d(20.0, 20.0, 20.0))
await wait_for_update()
await self.run_imge_test(None, 'nvindex-torus-create.png')
| 4,689 | Python | 40.504424 | 135 | 0.670719 |
omniverse-code/kit/exts/omni.kit.compatibility_checker/omni/kit/compatibility_checker/scripts/extension.py | import asyncio
import importlib
import fnmatch
import carb
import carb.settings
import omni.appwindow
import omni.ext
import omni.gpu_foundation_factory
import omni.kit.app
import omni.kit.renderer.bind
RENDERER_ENABLED_SETTINGS_PATH = "/renderer/enabled"
CHECKER_SETTINGS_PATH = "exts/omni.kit.compatibility_checker/"
def escape_for_fnmatch(s: str) -> str:
return s.replace("[", "[[]")
def get_gpus_list_from_device(device):
gpus_list = omni.gpu_foundation_factory.get_gpus_list(device)
try:
gpus_list.remove("Microsoft Basic Render Driver")
except ValueError:
pass
return gpus_list
def get_driver_version_from_device(device):
driver_version = omni.gpu_foundation_factory.get_driver_version(device)
return driver_version
def check_supported_gpu(gpus_list, supported_gpus):
gpu_good = False
for gpu in gpus_list:
for supported_gpu in supported_gpus:
if fnmatch.fnmatch(escape_for_fnmatch(gpu), supported_gpu):
gpu_good = True
break
return gpu_good
def check_driver_version(driver_version, driver_blacklist_ranges):
for driver_blacklist_range in driver_blacklist_ranges:
version_from = [int(i) for i in driver_blacklist_range[0].split(".")]
version_to = [int(i) for i in driver_blacklist_range[1].split(".")]
def is_driver_in_range(version, version_from, version_to):
version_int = version[0] * 100 + version[1]
version_from_int = version_from[0] * 100 + version_from[1]
version_to_int = version_to[0] * 100 + version_to[1]
if version_int < version_from_int or version_int >= version_to_int:
return False
return True
if is_driver_in_range(driver_version, version_from, version_to):
return False, driver_blacklist_range
return True, []
def check_os_version(min_os_version):
os_good = True
os_version = omni.gpu_foundation_factory.get_os_build_number()
if os_version < min_os_version:
os_good = False
return os_good, os_version
class Extension(omni.ext.IExt):
def __init__(self):
super().__init__()
pass
def _check_rtx_renderer_state(self):
if self._module_viewport:
enabled_renderers = self._settings.get(RENDERER_ENABLED_SETTINGS_PATH).lower().split(',')
rtx_enabled = 'rtx' in enabled_renderers
# Viewport 1.5 doesn't have methods to return attached context, but it also doesn't
# quite work with multiple contexts out of the box, so we just assume default context.
# In VP 2.0, the hope is to have better communication protocol with HydraEngine
# so there will be no need for this whole compatibility checker anyway.
usd_context = omni.usd.get_context("")
attached_hydra_engines = usd_context.get_attached_hydra_engine_names()
if rtx_enabled and ("rtx" not in attached_hydra_engines):
return False
return True
async def _compatibility_check(self):
# Wait a couple of frames to make sure all subsystems are properly initialized
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
rtx_renderer_good = self._check_rtx_renderer_state()
if rtx_renderer_good is True:
# Early exit if renderer is OK, no need to check driver, GPU and OS version in this case
return
# Renderer wasn't initialized properly
message = "RTX engine creation failed. RTX renderers in viewport will be disabled. Please make sure selected GPU is RTX-capable, and GPU drivers meet requirements."
carb.log_error(message)
if self._module_notification_manager is not None:
def open_log():
log_file_path = self._settings.get("/log/file")
import webbrowser
webbrowser.open(log_file_path)
dismiss_button = self._module_notification_manager.NotificationButtonInfo("Dismiss", None)
show_log_file_button = self._module_notification_manager.NotificationButtonInfo("Open log", open_log)
self._module_notification_manager.post_notification(message, hide_after_timeout=False, button_infos=[dismiss_button, show_log_file_button])
platform_info = omni.kit.app.get_app().get_platform_info()
platform_settings_path = CHECKER_SETTINGS_PATH + platform_info['platform'] + "/"
min_os_version = self._settings.get(platform_settings_path + "minOsVersion")
driver_blacklist_ranges = self._settings.get(platform_settings_path + "driverBlacklistRanges")
supported_gpus = self._settings.get(CHECKER_SETTINGS_PATH + "supportedGpus")
self._renderer = omni.kit.renderer.bind.acquire_renderer_interface()
device = self._renderer.get_graphics_device(omni.appwindow.get_default_app_window())
if supported_gpus is None:
carb.log_warn("Supported GPUs list is empty, skipping GPU compatibility check!")
else:
gpus_list = get_gpus_list_from_device(device)
gpu_good = check_supported_gpu(gpus_list, supported_gpus)
if gpu_good is not True:
message = "Available GPUs are not supported. List of available GPUs:\n%s" % (gpus_list)
carb.log_error(message)
if self._module_notification_manager is not None:
self._module_notification_manager.post_notification(message, hide_after_timeout=False)
driver_good = True
if driver_blacklist_ranges is None:
carb.log_warn("Supported drivers list is empty, skipping GPU compatibility check!")
else:
driver_version = get_driver_version_from_device(device)
driver_good, driver_blacklist_range = check_driver_version(driver_version, driver_blacklist_ranges)
if driver_good is not True:
message = "Driver version %d.%d is not supported. Driver is in blacklisted range %s-%s. Reason for blacklisting: %s." % (
driver_version[0],
driver_version[1],
driver_blacklist_range[0],
driver_blacklist_range[1],
driver_blacklist_range[2]
)
carb.log_error(message)
if self._module_notification_manager is not None:
self._module_notification_manager.post_notification(message, hide_after_timeout=False)
os_good, os_version = check_os_version(min_os_version)
if os_good is not True:
message = "Please update the OS. Minimum required OS build number for %s is %d, current version is %d." % (platform_info['platform'], min_os_version, os_version)
carb.log_error(message)
if self._module_notification_manager is not None:
self._module_notification_manager.post_notification(message, hide_after_timeout=False)
def on_startup(self):
self._settings = carb.settings.get_settings()
try:
self._module_viewport = importlib.import_module('omni.kit.viewport_legacy')
except ImportError:
self._module_viewport = None
try:
self._module_notification_manager = importlib.import_module('omni.kit.notification_manager')
except ImportError:
self._module_notification_manager = None
asyncio.ensure_future(self._compatibility_check())
def on_shutdown(self):
self._settings = None
| 7,626 | Python | 43.086705 | 173 | 0.64385 |
omniverse-code/kit/exts/omni.kit.compatibility_checker/omni/kit/compatibility_checker/tests/test_compatibility_checker.py | import inspect
import pathlib
import carb
import carb.settings
import carb.tokens
import omni.kit.app
import omni.kit.test
import omni.kit.compatibility_checker
class CompatibilityCheckerTest(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._settings = carb.settings.acquire_settings_interface()
self._app_window_factory = omni.appwindow.acquire_app_window_factory_interface()
self._renderer = omni.kit.renderer.bind.acquire_renderer_interface()
def __test_name(self) -> str:
return f"{self.__module__}.{self.__class__.__name__}.{inspect.stack()[2][3]}"
async def tearDown(self):
self._renderer = None
self._app_window_factory = None
self._settings = None
async def test_1_check_gpu(self):
supported_gpus = [
"*GeForce RTX ????*",
"*Quadro RTX ????*",
"*RTX ?????*",
"*TITAN RTX*"
]
gpu_good = omni.kit.compatibility_checker.check_supported_gpu(["NVIDIA GeForce RTX 2060 OC"], supported_gpus)
self.assertTrue(gpu_good)
gpu_good = omni.kit.compatibility_checker.check_supported_gpu(["GeForce RTX 2080 Ti"], supported_gpus)
self.assertTrue(gpu_good)
gpu_good = omni.kit.compatibility_checker.check_supported_gpu(["NVIDIA GeForce RTX 3080"], supported_gpus)
self.assertTrue(gpu_good)
gpu_good = omni.kit.compatibility_checker.check_supported_gpu(["NVIDIA Quadro RTX A6000"], supported_gpus)
self.assertTrue(gpu_good)
gpu_good = omni.kit.compatibility_checker.check_supported_gpu(["Quadro RTX 8000"], supported_gpus)
self.assertTrue(gpu_good)
gpu_good = omni.kit.compatibility_checker.check_supported_gpu(["RTX A6000"], supported_gpus)
self.assertTrue(gpu_good)
gpu_good = omni.kit.compatibility_checker.check_supported_gpu(["TITAN RTX"], supported_gpus)
self.assertTrue(gpu_good)
gpu_good = omni.kit.compatibility_checker.check_supported_gpu(["NVIDIA GeForce GTX 1060 OC"], supported_gpus)
self.assertTrue(gpu_good is not True)
gpu_good = omni.kit.compatibility_checker.check_supported_gpu(["NVIDIA GeForce RTX 2060 OC", "Not NVIDIA not GeForce"], supported_gpus)
self.assertTrue(gpu_good)
gpu_good = omni.kit.compatibility_checker.check_supported_gpu(["Not NVIDIA not GeForce", "NVIDIA GeForce RTX 2060 OC"], supported_gpus)
self.assertTrue(gpu_good)
async def test_2_check_drivers_blacklist(self):
driver_blacklist_ranges = [
["0.0", "100.0", "Minimum RTX req"],
["110.0", "111.0", "Bugs"],
["120.3", "120.5", "More bugs"],
]
driver_good, driver_blacklist_range = omni.kit.compatibility_checker.check_driver_version([95, 0], driver_blacklist_ranges)
self.assertTrue(driver_good is not True)
driver_good, driver_blacklist_range = omni.kit.compatibility_checker.check_driver_version([105, 0], driver_blacklist_ranges)
self.assertTrue(driver_good)
driver_good, driver_blacklist_range = omni.kit.compatibility_checker.check_driver_version([110, 5], driver_blacklist_ranges)
self.assertTrue(driver_good is not True)
driver_good, driver_blacklist_range = omni.kit.compatibility_checker.check_driver_version([115, 0], driver_blacklist_ranges)
self.assertTrue(driver_good)
driver_good, driver_blacklist_range = omni.kit.compatibility_checker.check_driver_version([120, 3], driver_blacklist_ranges)
self.assertTrue(driver_good is not True)
driver_good, driver_blacklist_range = omni.kit.compatibility_checker.check_driver_version([120, 4], driver_blacklist_ranges)
self.assertTrue(driver_good is not True)
driver_good, driver_blacklist_range = omni.kit.compatibility_checker.check_driver_version([120, 5], driver_blacklist_ranges)
self.assertTrue(driver_good is True)
driver_good, driver_blacklist_range = omni.kit.compatibility_checker.check_driver_version([130, 5], driver_blacklist_ranges)
self.assertTrue(driver_good)
| 4,128 | Python | 42.010416 | 143 | 0.67563 |
omniverse-code/kit/exts/omni.kit.compatibility_checker/omni/kit/compatibility_checker/tests/__init__.py | from .test_compatibility_checker import *
| 42 | Python | 20.49999 | 41 | 0.809524 |
omniverse-code/kit/exts/omni.kit.documentation.ui.style/omni/kit/documentation/ui/style/ui_style_docs_window.py | # Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["UIStyleDocsWindow"]
from omni.kit.documentation.builder import DocumentationBuilderWindow
from pathlib import Path
CURRENT_PATH = Path(__file__).parent
DOCS_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("docs")
PAGES = ["overview.md", "styling.md", "shades.md", "fonts.md", "units.md", "shapes.md", "line.md", "buttons.md",
"sliders.md", "widgets.md", "containers.md", "window.md"]
class UIStyleDocsWindow(DocumentationBuilderWindow):
"""The window with the documentation"""
def __init__(self, title: str, **kwargs):
filenames = [f"{DOCS_PATH.joinpath(page_source)}" for page_source in PAGES]
super().__init__(title, filenames=filenames, **kwargs)
| 1,149 | Python | 43.230768 | 112 | 0.733681 |
omniverse-code/kit/exts/omni.kit.widget.versioning/scripts/demo_checkpoint.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui as ui
from omni.kit.widget.versioning import CheckpointWidget, CheckpointCombobox, LAYOUT_TABLE_VIEW, LAYOUT_SLIM_VIEW
def create_checkpoint_view(url: str, layout: int):
view = CheckpointWidget(url, layout=layout)
view.add_context_menu(
"Menu Action",
"pencil.svg",
lambda menu, cp: print(f"Apply '{menu}' to '{cp.get_relative_path()}'"),
None,
)
view.set_mouse_double_clicked_fn(
lambda b, k, cp: print(f"Double clicked '{cp.get_relative_path()}")
)
if __name__ == "__main__":
url = "omniverse://ov-rc/Users/[email protected]/sphere.usd"
window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR
window = ui.Window("DemoFileBrowser", width=800, height=500, flags=window_flags)
with window.frame:
with ui.VStack(style={"margin": 0}):
ui.Label(url, height=30)
with ui.HStack():
create_checkpoint_view(url, LAYOUT_TABLE_VIEW)
ui.Spacer(width=10)
with ui.VStack(width=250):
create_checkpoint_view(url, LAYOUT_SLIM_VIEW)
ui.Spacer(width=10)
with ui.VStack(width=100, height=20):
combo_box = CheckpointCombobox(url, lambda sel: print(f"Selected: {sel.get_full_url()}"))
| 1,733 | Python | 42.349999 | 112 | 0.656088 |
omniverse-code/kit/exts/omni.kit.widget.versioning/omni/kit/widget/versioning/slim_view.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from functools import partial
from omni import ui
from .checkpoints_model import CheckpointItem, CheckpointModel
from .style import get_style
class CheckpointSlimView:
def __init__(self, model: CheckpointModel, **kwargs):
self._model = model
self._tree_view = None
self._delegate = CheckpointSlimViewDelegate(**kwargs)
self._selection_changed_fn = kwargs.get("selection_changed_fn", None)
self._build_ui()
def _build_ui(self):
with ui.ZStack(style=get_style()):
ui.Rectangle(style_type_name_override="TreeView.Background")
self._tree_view = ui.TreeView(
self._model,
delegate=self._delegate,
root_visible=False,
header_visible=False,
column_widths=[ui.Fraction(1)],
style_type_name_override="TreeView"
)
self._tree_view.set_selection_changed_fn(self._on_selection_changed)
def _on_selection_changed(self, selections):
if len(selections) > 1:
# only allow selecting one checkpoint
self._tree_view.selection = [selections[-1]]
if self._selection_changed_fn:
self._selection_changed_fn(selections)
def destroy(self):
if self._delegate:
self._delegate.destroy()
self._delegate = None
self._tree_view = None
class CheckpointSlimViewDelegate(ui.AbstractItemDelegate):
def __init__(self, **kwargs):
super().__init__()
self._widget = None
self._mouse_pressed_fn = kwargs.get("mouse_pressed_fn", None)
self._mouse_double_clicked_fn = kwargs.get("mouse_double_clicked_fn", None)
def build_branch(self, model, item, column_id, level, expanded):
pass
def build_widget(self, model: CheckpointModel, item: CheckpointItem, column_id: int, level: int, expanded: bool):
"""Create a widget per item"""
if not item or column_id > 0:
return
tooltip = f"#{item.entry.relative_path[1:]}. {item.entry.comment}\n"
tooltip += f"{CheckpointItem.datetime_to_string(item.entry.modified_time)}\n"
tooltip += f"{item.entry.modified_by}"
def on_mouse_pressed(item: CheckpointItem, x, y, b, key_mod):
if self._mouse_pressed_fn:
self._mouse_pressed_fn(b, key_mod, item)
def on_mouse_double_clicked(item: CheckpointItem, x, y, b, key_mod):
if self._mouse_double_clicked_fn:
self._mouse_double_clicked_fn(b, key_mod, item)
with ui.ZStack(style=get_style()):
self._widget = ui.Rectangle(
mouse_pressed_fn=partial(on_mouse_pressed, item),
mouse_double_clicked_fn=partial(on_mouse_double_clicked, item),
style_type_name_override="Card"
)
with ui.VStack(spacing=0):
ui.Spacer(height=4)
with ui.HStack():
ui.Label(
f"#{item.entry.relative_path[1:]}.", width=0,
style_type_name_override="Card.Label"
)
ui.Spacer(width=2)
if item.entry.comment:
ui.Label(
f"{item.entry.comment}",
tooltip=tooltip,
word_wrap=not item.comment_elided,
elided_text=item.comment_elided,
style_type_name_override="Card.Label"
)
else:
ui.Label(
f"{CheckpointItem.datetime_to_string(item.entry.modified_time)}",
style_type_name_override="Card.Label"
)
if item.entry.comment:
ui.Label(
f"{CheckpointItem.datetime_to_string(item.entry.modified_time)}",
style_type_name_override="Card.Label"
)
ui.Label(f"{item.entry.modified_by}", style_type_name_override="Card.Label")
ui.Spacer(height=8)
ui.Separator(style_type_name_override="Card.Separator")
ui.Spacer(height=4)
def destroy(self):
self._widget = None
self._mouse_pressed_fn = None
self._mouse_double_clicked_fn = None
| 4,884 | Python | 40.398305 | 117 | 0.564087 |
omniverse-code/kit/exts/omni.kit.widget.versioning/omni/kit/widget/versioning/checkpoints_model.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import copy
import carb
import omni.client
import omni.kit.app
from omni.kit.async_engine import run_coroutine
import omni.ui as ui
from datetime import datetime
class DummyNoneNode:
def __init__(self, entry: omni.client.ListEntry):
self.relative_path = " <head>"
self.access = entry.access
self.flags = entry.flags
self.size = entry.size
self.modified_time = entry.modified_time
self.created_time = entry.created_time
self.modified_by = entry.modified_by
self.created_by = entry.created_by
self.version = entry.version
self.comment = "<Not using Checkpoint>"
class CheckpointItem(ui.AbstractItem):
def __init__(self, entry, url):
super().__init__()
self.comment_elided = True
self.url = url # url without query
self.entry = entry
@property
def comment(self):
if self.entry:
return self.entry.comment
return ""
def get_full_url(self):
if isinstance(self.entry, DummyNoneNode):
return self.url
return self.url + "?" + self.entry.relative_path
def get_relative_path(self):
if isinstance(self.entry, DummyNoneNode):
return None
return self.entry.relative_path
@staticmethod
def size_to_string(size: int):
return f"{size/1.e9:.2f} GB" if size > 1.e9 else (\
f"{size/1.e6:.2f} MB" if size > 1.e6 else f"{size/1.e3:.2f} KB")
@staticmethod
def datetime_to_string(dt: datetime):
return dt.strftime("%x %I:%M%p")
class CheckpointModel(ui.AbstractItemModel):
def __init__(self, show_none_entry):
super().__init__()
self._show_none_entry = show_none_entry
self._checkpoints = []
self._checkpoints_filtered = []
self._url = ""
self._incoming_url = ""
self._url_without_query = ""
self._search_kw = ""
self._checkpoint = None
self._on_list_checkpoint_fn = None
self._single_column = False
self._list_task = None
self._restore_task = None
self._set_url_task = None
self._multi_select = False
self._file_status_request = omni.client.register_file_status_callback(self._on_file_status)
self._resolve_subscription = None
self._run_loop = asyncio.get_event_loop()
def reset(self):
self._checkpoints = []
self._checkpoints_filtered = []
if self._list_task:
self._list_task.cancel()
self._list_task = None
if self._restore_task:
self._restore_task.cancel()
self._restore_task = None
def destroy(self):
self._on_list_checkpoint_fn = None
self.reset()
self._file_status_request = None
self._resolve_subscription = None
self._run_loop = None
if self._set_url_task:
self._set_url_task.cancel()
self._set_url_task = None
@property
def single_column(self):
return self._single_column
@single_column.setter
def single_column(self, value: bool):
"""Set the one-column mode"""
self._single_column = not not value
self._item_changed(None)
def empty(self):
return not self.get_item_children(None)
def set_multi_select(self, state: bool):
self._multi_select = state
def set_url(self, url):
self._incoming_url = url
# In file dialog, if select file A, then select file B, it emits selection event of "file A", "None", "file B"
# Do a async task to eat the "None" event to avoid flickering
async def delayed_set_url():
await omni.kit.app.get_app().next_update_async()
if self._url != self._incoming_url:
self._url = self._incoming_url
self.reset()
if self._url:
client_url = omni.client.break_url(self._url)
if client_url.query:
_, self._checkpoint = omni.client.get_branch_and_checkpoint_from_query(client_url.query)
else:
self._checkpoint = 0
self._url_without_query = omni.client.make_url(
scheme=client_url.scheme,
user=client_url.user,
host=client_url.host,
port=client_url.port,
path=client_url.path,
fragment=client_url.fragment,
)
self.list_checkpoint()
self._resolve_subscription = omni.client.resolve_subscribe_with_callback(
self._url_without_query, [self._url_without_query], None,
lambda result, event, entry, url: self._on_file_change_event(result))
else:
self._no_checkpoint(True)
self._set_url_task = None
if not self._set_url_task:
self._set_url_task = run_coroutine(delayed_set_url())
def _on_file_change_event(self, result: omni.client.Result):
if result == omni.client.Result.OK:
async def set_url():
self.list_checkpoint()
# must run on main thread as this one does not have async loop...
asyncio.run_coroutine_threadsafe(set_url(), loop=self._run_loop)
def get_url(self):
return self._url
def set_search(self, keywords):
if self._search_kw != keywords:
self._search_kw = keywords
self._re_filter()
def set_on_list_checkpoint_fn(self, fn):
self._on_list_checkpoint_fn = fn
def on_list_checkpoints(self, file_entry, checkpoints_entries):
self._checkpoints = []
current_cp_item = None
for cp in checkpoints_entries:
item = CheckpointItem(cp, self._url_without_query)
self._checkpoints.append(item)
if not current_cp_item and str(self._checkpoint) == cp.relative_path[1:]:
current_cp_item = item
# OM-45546: Add back the <head> dummy option for files with checkpoints
if self._show_none_entry:
none_entry = DummyNoneNode(file_entry)
item = CheckpointItem(none_entry, self._url_without_query)
self._checkpoints.append(item)
if self._checkpoint == 0:
current_cp_item = item
# newest checkpoints at top
self._checkpoints.reverse()
self._re_filter()
self._item_changed(None)
if self._on_list_checkpoint_fn:
self._on_list_checkpoint_fn(supports_checkpointing=True,
has_checkpoints=len(self._checkpoints),
current_checkpoint=current_cp_item,
multi_select=self._multi_select)
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is not None:
# Since we are doing a flat list, we return the children of root only.
# If it's not root we return.
return []
return self._checkpoints if self._search_kw == "" else self._checkpoints_filtered
def get_item_value_model_count(self, item):
"""The number of columns"""
if self._single_column:
return 1
return 5
def list_checkpoint(self):
self._list_task = run_coroutine(self._list_checkpoint_async())
def restore_checkpoint(self, file_path, checkpoint_path):
self._restore_task = run_coroutine(self._restore_checkpoint(file_path, checkpoint_path))
def get_drag_mime_data(self, item):
"""Returns Multipurpose Internet Mail Extensions (MIME) data for be able to drop this item somewhere"""
return item.get_full_url()
async def _list_checkpoint_async(self):
if self._url_without_query == "omniverse://":
support_checkpointing = True
else:
client_url = omni.client.break_url(self._url_without_query)
server_url = omni.client.make_url(scheme=client_url.scheme, host=client_url.host, port=client_url.port)
result, server_info = await omni.client.get_server_info_async(server_url)
support_checkpointing = True if result and server_info and server_info.checkpoints_enabled else False
result, server_info = await omni.client.get_server_info_async(self._url_without_query)
if not result or not server_info or not server_info.checkpoints_enabled:
self._no_checkpoint(support_checkpointing)
return
# Have to use async version. _with_callback comes from a different thread
result, entry = await omni.client.stat_async(self._url_without_query)
if entry.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN:
# Can't have checkpoint on folder
self._no_checkpoint(support_checkpointing)
return
result, entries = await omni.client.list_checkpoints_async(self._url_without_query)
if result != omni.client.Result.OK:
carb.log_warn(f"Failed to get checkpoints for {self._url_without_query}: {result}")
self.on_list_checkpoints(entry, entries)
self._list_task = None
def _on_file_status(self, url, status, percent):
if status == omni.client.FileStatus.WRITING and percent == 100 and url == self._url_without_query:
async def set_url():
self.list_checkpoint()
# must run on main thread as this one does not have async loop...
asyncio.run_coroutine_threadsafe(set_url(), loop=self._run_loop)
def _no_checkpoint(self, support_checkpointing):
self._checkpoints.clear()
self._item_changed(None)
if self._on_list_checkpoint_fn:
self._on_list_checkpoint_fn(supports_checkpointing=support_checkpointing,
has_checkpoints=False,
current_checkpoint=None,
multi_select=self._multi_select)
async def _restore_checkpoint(self, file_path, checkpoint_path):
id = checkpoint_path.rfind('&') + 1
relative_path = checkpoint_path[id:] if id > 0 else ''
result = await omni.client.copy_async(checkpoint_path, file_path, message=f"Restored checkpoint #{relative_path}")
carb.log_warn(f"Restore checkpoint {checkpoint_path} to {file_path}: {result}")
if result:
self.list_checkpoint()
def _re_filter(self):
self._checkpoints_filtered.clear()
if self._search_kw == "":
self._checkpoints_filtered = copy.copy(self._checkpoints)
else:
kws = self._search_kw.split(' ')
for cp in self._checkpoints:
for kw in kws:
if kw.lower() in cp.entry.comment.lower():
self._checkpoints_filtered.append(cp)
break
if kw.lower() in cp.entry.relative_path.lower():
self._checkpoints_filtered.append(cp)
break
self._item_changed(None)
| 11,745 | Python | 38.548821 | 122 | 0.587399 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.