file_path
stringlengths
21
202
content
stringlengths
12
1.02M
size
int64
12
1.02M
lang
stringclasses
9 values
avg_line_length
float64
3.33
100
max_line_length
int64
10
993
alphanum_fraction
float64
0.27
0.93
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/windows/attach.cpp
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * Contributor: Fabio Zadrozny * * Based on PyDebugAttach.cpp from PVTS. Windows only. * * https://github.com/Microsoft/PTVS/blob/master/Python/Product/PyDebugAttach/PyDebugAttach.cpp * * Initially we did an attach completely based on shellcode which got the * GIL called PyRun_SimpleString with the needed code and was done with it * (so, none of this code was needed). * Now, newer version of Python don't initialize threading by default, so, * most of this code is done only to overcome this limitation (and as a plus, * if there's no code running, we also pause the threads to make our code run). * * On Linux the approach is still the simpler one (using gdb), so, on newer * versions of Python it may not work unless the user has some code running * and threads are initialized. * I.e.: * * The user may have to add the code below in the start of its script for * a successful attach (if he doesn't already use threads). * * from threading import Thread * Thread(target=str).start() * * -- this is the workaround for the fact that we can't get the gil * if there aren't any threads (PyGILState_Ensure gives an error). * ***************************************************************************/ // Access to std::cout and std::endl #include <iostream> #include <mutex> // DECLDIR will perform an export for us #define DLL_EXPORT #include "attach.h" #include "stdafx.h" #include "../common/python.h" #include "../common/ref_utils.hpp" #include "../common/py_utils.hpp" #include "../common/py_settrace.hpp" #pragma comment(lib, "kernel32.lib") #pragma comment(lib, "user32.lib") #pragma comment(lib, "advapi32.lib") #pragma comment(lib, "psapi.lib") #include "py_win_helpers.hpp" #include "run_code_in_memory.hpp" // _Always_ is not defined for all versions, so make it a no-op if missing. #ifndef _Always_ #define _Always_(x) x #endif typedef void (PyEval_Lock)(); // Acquire/Release lock typedef void (PyThreadState_API)(PyThreadState *); // Acquire/Release lock typedef PyObject* (Py_CompileString)(const char *str, const char *filename, int start); typedef PyObject* (PyEval_EvalCode)(PyObject *co, PyObject *globals, PyObject *locals); typedef PyObject* (PyDict_GetItemString)(PyObject *p, const char *key); typedef PyObject* (PyEval_GetBuiltins)(); typedef int (PyDict_SetItemString)(PyObject *dp, const char *key, PyObject *item); typedef int (PyEval_ThreadsInitialized)(); typedef int (Py_AddPendingCall)(int (*func)(void *), void*); typedef PyObject* (PyString_FromString)(const char* s); typedef void PyEval_SetTrace(Py_tracefunc func, PyObject *obj); typedef PyObject* (PyErr_Print)(); typedef PyObject* (PyObject_SetAttrString)(PyObject *o, const char *attr_name, PyObject* value); typedef PyObject* (PyBool_FromLong)(long v); typedef unsigned long (_PyEval_GetSwitchInterval)(void); typedef void (_PyEval_SetSwitchInterval)(unsigned long microseconds); typedef PyGILState_STATE PyGILState_EnsureFunc(void); typedef void PyGILState_ReleaseFunc(PyGILState_STATE); typedef PyThreadState *PyThreadState_NewFunc(PyInterpreterState *interp); typedef PyObject *PyList_New(Py_ssize_t len); typedef int PyList_Append(PyObject *list, PyObject *item); std::wstring GetCurrentModuleFilename() { HMODULE hModule = nullptr; if (GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCTSTR)GetCurrentModuleFilename, &hModule) != 0) { wchar_t filename[MAX_PATH]; GetModuleFileName(hModule, filename, MAX_PATH); return filename; } return std::wstring(); } struct InitializeThreadingInfo { PyImport_ImportModule* pyImportMod; PyEval_Lock* initThreads; std::mutex mutex; HANDLE initedEvent; // Note: only access with mutex locked (and check if not already nullptr). bool completed; // Note: only access with mutex locked }; int AttachCallback(void *voidInitializeThreadingInfo) { // initialize us for threading, this will acquire the GIL if not already created, and is a nop if the GIL is created. // This leaves us in the proper state when we return back to the runtime whether the GIL was created or not before // we were called. InitializeThreadingInfo* initializeThreadingInfo = reinterpret_cast<InitializeThreadingInfo*>(voidInitializeThreadingInfo); initializeThreadingInfo->initThreads(); // Note: calling multiple times is ok. initializeThreadingInfo->pyImportMod("threading"); initializeThreadingInfo->mutex.lock(); if(initializeThreadingInfo->initedEvent != nullptr) { SetEvent(initializeThreadingInfo->initedEvent); } initializeThreadingInfo->completed = true; initializeThreadingInfo->mutex.unlock(); return 0; } // create a custom heap for our unordered map. This is necessary because if we suspend a thread while in a heap function // then we could deadlock here. We need to be VERY careful about what we do while the threads are suspended. static HANDLE g_heap = 0; template<typename T> class PrivateHeapAllocator { public: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; typedef T value_type; template<class U> struct rebind { typedef PrivateHeapAllocator<U> other; }; explicit PrivateHeapAllocator() {} PrivateHeapAllocator(PrivateHeapAllocator const&) {} ~PrivateHeapAllocator() {} template<typename U> PrivateHeapAllocator(PrivateHeapAllocator<U> const&) {} pointer allocate(size_type size, std::allocator<void>::const_pointer hint = 0) { UNREFERENCED_PARAMETER(hint); if (g_heap == nullptr) { g_heap = HeapCreate(0, 0, 0); } auto mem = HeapAlloc(g_heap, 0, size * sizeof(T)); return static_cast<pointer>(mem); } void deallocate(pointer p, size_type n) { UNREFERENCED_PARAMETER(n); HeapFree(g_heap, 0, p); } size_type max_size() const { return (std::numeric_limits<size_type>::max)() / sizeof(T); } void construct(pointer p, const T& t) { new(p) T(t); } void destroy(pointer p) { p->~T(); } }; typedef std::unordered_map<DWORD, HANDLE, std::hash<DWORD>, std::equal_to<DWORD>, PrivateHeapAllocator<std::pair<DWORD, HANDLE>>> ThreadMap; void ResumeThreads(ThreadMap &suspendedThreads) { for (auto start = suspendedThreads.begin(); start != suspendedThreads.end(); start++) { ResumeThread((*start).second); CloseHandle((*start).second); } suspendedThreads.clear(); } // Suspends all threads ensuring that they are not currently in a call to Py_AddPendingCall. void SuspendThreads(ThreadMap &suspendedThreads, Py_AddPendingCall* addPendingCall, PyEval_ThreadsInitialized* threadsInited) { DWORD curThreadId = GetCurrentThreadId(); DWORD curProcess = GetCurrentProcessId(); // suspend all the threads in the process so we can do things safely... bool suspended; do { suspended = false; HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); if (h != INVALID_HANDLE_VALUE) { THREADENTRY32 te; te.dwSize = sizeof(te); if (Thread32First(h, &te)) { do { if (te.dwSize >= FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) + sizeof(te.th32OwnerProcessID) && te.th32OwnerProcessID == curProcess) { if (te.th32ThreadID != curThreadId && suspendedThreads.find(te.th32ThreadID) == suspendedThreads.end()) { auto hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, te.th32ThreadID); if (hThread != nullptr) { SuspendThread(hThread); bool addingPendingCall = false; CONTEXT context; memset(&context, 0x00, sizeof(CONTEXT)); context.ContextFlags = CONTEXT_ALL; GetThreadContext(hThread, &context); #if defined(_X86_) if (context.Eip >= *(reinterpret_cast<DWORD*>(addPendingCall)) && context.Eip <= (*(reinterpret_cast<DWORD*>(addPendingCall))) + 0x100) { addingPendingCall = true; } #elif defined(_AMD64_) if (context.Rip >= *(reinterpret_cast<DWORD64*>(addPendingCall)) && context.Rip <= *(reinterpret_cast<DWORD64*>(addPendingCall) + 0x100)) { addingPendingCall = true; } #endif if (addingPendingCall) { // we appear to be adding a pending call via this thread - wait for this to finish so we can add our own pending call... ResumeThread(hThread); SwitchToThread(); // yield to the resumed thread if it's on our CPU... CloseHandle(hThread); } else { suspendedThreads[te.th32ThreadID] = hThread; } suspended = true; } } } te.dwSize = sizeof(te); } while (Thread32Next(h, &te) && !threadsInited()); } CloseHandle(h); } } while (suspended && !threadsInited()); } extern "C" { /** * The returned value signals the error that happened! * * Return codes: * 0 = all OK. * 1 = Py_IsInitialized not found * 2 = Py_IsInitialized returned false * 3 = Missing Python API * 4 = Interpreter not initialized * 5 = Python version unknown * 6 = Connect timeout **/ int DoAttach(HMODULE module, bool isDebug, const char *command, bool showDebugInfo ) { auto isInit = reinterpret_cast<Py_IsInitialized*>(GetProcAddress(module, "Py_IsInitialized")); if (isInit == nullptr) { std::cerr << "Py_IsInitialized not found. " << std::endl << std::flush; return 1; } if (!isInit()) { std::cerr << "Py_IsInitialized returned false. " << std::endl << std::flush; return 2; } auto version = GetPythonVersion(module); // found initialized Python runtime, gather and check the APIs we need for a successful attach... DEFINE_PROC(addPendingCall, Py_AddPendingCall*, "Py_AddPendingCall", -100); DEFINE_PROC(interpHead, PyInterpreterState_Head*, "PyInterpreterState_Head", -110); DEFINE_PROC(gilEnsure, PyGILState_Ensure*, "PyGILState_Ensure", -120); DEFINE_PROC(gilRelease, PyGILState_Release*, "PyGILState_Release", -130); DEFINE_PROC(threadHead, PyInterpreterState_ThreadHead*, "PyInterpreterState_ThreadHead", -140); DEFINE_PROC(initThreads, PyEval_Lock*, "PyEval_InitThreads", -150); DEFINE_PROC(releaseLock, PyEval_Lock*, "PyEval_ReleaseLock", -160); DEFINE_PROC(threadsInited, PyEval_ThreadsInitialized*, "PyEval_ThreadsInitialized", -170); DEFINE_PROC(threadNext, PyThreadState_Next*, "PyThreadState_Next", -180); DEFINE_PROC(pyImportMod, PyImport_ImportModule*, "PyImport_ImportModule", -190); DEFINE_PROC(pyNone, PyObject*, "_Py_NoneStruct", -2000); DEFINE_PROC(pyRun_SimpleString, PyRun_SimpleString*, "PyRun_SimpleString", -210); // Either _PyThreadState_Current or _PyThreadState_UncheckedGet are required DEFINE_PROC_NO_CHECK(curPythonThread, PyThreadState**, "_PyThreadState_Current", -220); // optional DEFINE_PROC_NO_CHECK(getPythonThread, _PyThreadState_UncheckedGet*, "_PyThreadState_UncheckedGet", -230); // optional if (curPythonThread == nullptr && getPythonThread == nullptr) { // we're missing some APIs, we cannot attach. std::cerr << "Error, missing Python threading API!!" << std::endl << std::flush; return -240; } // Either _Py_CheckInterval or _PyEval_[GS]etSwitchInterval are useful, but not required DEFINE_PROC_NO_CHECK(intervalCheck, int*, "_Py_CheckInterval", -250); // optional DEFINE_PROC_NO_CHECK(getSwitchInterval, _PyEval_GetSwitchInterval*, "_PyEval_GetSwitchInterval", -260); // optional DEFINE_PROC_NO_CHECK(setSwitchInterval, _PyEval_SetSwitchInterval*, "_PyEval_SetSwitchInterval", -270); // optional auto head = interpHead(); if (head == nullptr) { // this interpreter is loaded but not initialized. std::cerr << "Interpreter not initialized! " << std::endl << std::flush; return 4; } // check that we're a supported version if (version == PythonVersion_Unknown) { std::cerr << "Python version unknown! " << std::endl << std::flush; return 5; } else if (version == PythonVersion_25 || version == PythonVersion_26 || version == PythonVersion_30 || version == PythonVersion_31 || version == PythonVersion_32) { std::cerr << "Python version unsupported! " << std::endl << std::flush; return 5; } // We always try to initialize threading and import the threading module in the main thread in the code // below... // // We need to initialize multiple threading support but we need to do so safely, so we call // Py_AddPendingCall and have our callback then initialize multi threading. This is completely safe on 2.7 // and up. Unfortunately that doesn't work if we're not actively running code on the main thread (blocked on a lock // or reading input). // // Another option is to make sure no code is running - if there is no active thread then we can safely call // PyEval_InitThreads and we're in business. But to know this is safe we need to first suspend all the other // threads in the process and then inspect if any code is running (note that this is still not ideal because // this thread will be the thread head for Python, but still better than not attach at all). // // Finally if code is running after we've suspended the threads then we can go ahead and do Py_AddPendingCall // on down-level interpreters as long as we're sure no one else is making a call to Py_AddPendingCall at the same // time. // // Therefore our strategy becomes: Make the Py_AddPendingCall on interpreters and wait for it. If it doesn't // call after a timeout, suspend all threads - if a threads is in Py_AddPendingCall resume and try again. Once we've got all of the threads // stopped and not in Py_AddPendingCall (which calls no functions its self, you can see this and it's size in the // debugger) then see if we have a current thread. If not go ahead and initialize multiple threading (it's now safe, // no Python code is running). InitializeThreadingInfo *initializeThreadingInfo = new InitializeThreadingInfo(); initializeThreadingInfo->pyImportMod = pyImportMod; initializeThreadingInfo->initThreads = initThreads; initializeThreadingInfo->initedEvent = CreateEvent(nullptr, TRUE, FALSE, nullptr); // Add the call to initialize threading. addPendingCall(&AttachCallback, initializeThreadingInfo); ::WaitForSingleObject(initializeThreadingInfo->initedEvent, 5000); // Whether this completed or not, release the event handle as we won't use it anymore. initializeThreadingInfo->mutex.lock(); CloseHandle(initializeThreadingInfo->initedEvent); bool completed = initializeThreadingInfo->completed; initializeThreadingInfo->initedEvent = nullptr; initializeThreadingInfo->mutex.unlock(); if(completed) { // Note that this structure will leak if addPendingCall did not complete in the timeout // (we can't release now because it's possible that it'll still be called). delete initializeThreadingInfo; if (showDebugInfo) { std::cout << "addPendingCall to initialize threads/import threading completed. " << std::endl << std::flush; } } else { if (showDebugInfo) { std::cout << "addPendingCall to initialize threads/import threading did NOT complete. " << std::endl << std::flush; } } if (threadsInited()) { // Note that since Python 3.7, threads are *always* initialized! if (showDebugInfo) { std::cout << "Threads initialized! " << std::endl << std::flush; } } else { int saveIntervalCheck; unsigned long saveLongIntervalCheck; if (intervalCheck != nullptr) { // not available on 3.2 saveIntervalCheck = *intervalCheck; *intervalCheck = -1; // lower the interval check so pending calls are processed faster saveLongIntervalCheck = 0; // prevent compiler warning } else if (getSwitchInterval != nullptr && setSwitchInterval != nullptr) { saveLongIntervalCheck = getSwitchInterval(); setSwitchInterval(0); saveIntervalCheck = 0; // prevent compiler warning } else { saveIntervalCheck = 0; // prevent compiler warning saveLongIntervalCheck = 0; // prevent compiler warning } // If threads weren't initialized in our pending call, instead of giving a timeout, try // to initialize it in this thread. for(int attempts = 0; !threadsInited() && attempts < 20; attempts++) { if(attempts > 0){ // If we haven't been able to do it in the first time, wait a bit before retrying. Sleep(10); } ThreadMap suspendedThreads; if (showDebugInfo) { std::cout << "SuspendThreads(suspendedThreads, addPendingCall, threadsInited);" << std::endl << std::flush; } SuspendThreads(suspendedThreads, addPendingCall, threadsInited); if(!threadsInited()){ // Check again with threads suspended. if (showDebugInfo) { std::cout << "ENTERED if (!threadsInited()) {" << std::endl << std::flush; } auto curPyThread = getPythonThread ? getPythonThread() : *curPythonThread; if (curPyThread == nullptr) { if (showDebugInfo) { std::cout << "ENTERED if (curPyThread == nullptr) {" << std::endl << std::flush; } // no threads are currently running, it is safe to initialize multi threading. PyGILState_STATE gilState; if (version >= PythonVersion_34) { // in 3.4 due to http://bugs.python.org/issue20891, // we need to create our thread state manually // before we can call PyGILState_Ensure() before we // can call PyEval_InitThreads(). // Don't require this function unless we need it. auto threadNew = (PyThreadState_NewFunc*)GetProcAddress(module, "PyThreadState_New"); if (threadNew != nullptr) { threadNew(head); } } if (version >= PythonVersion_32) { // in 3.2 due to the new GIL and later we can't call Py_InitThreads // without a thread being initialized. // So we use PyGilState_Ensure here to first // initialize the current thread, and then we use // Py_InitThreads to bring up multi-threading. // Some context here: http://bugs.python.org/issue11329 // http://pytools.codeplex.com/workitem/834 gilState = gilEnsure(); } else { gilState = PyGILState_LOCKED; // prevent compiler warning } if (showDebugInfo) { std::cout << "Called initThreads()" << std::endl << std::flush; } // Initialize threads in our secondary thread (this is NOT ideal because // this thread will be the thread head), but is still better than not being // able to attach if the main thread is not actually running any code. initThreads(); if (version >= PythonVersion_32) { // we will release the GIL here gilRelease(gilState); } else { releaseLock(); } } } ResumeThreads(suspendedThreads); } if (intervalCheck != nullptr) { *intervalCheck = saveIntervalCheck; } else if (setSwitchInterval != nullptr) { setSwitchInterval(saveLongIntervalCheck); } } if (g_heap != nullptr) { HeapDestroy(g_heap); g_heap = nullptr; } if (!threadsInited()) { std::cerr << "Unable to initialize threads in the given timeout! " << std::endl << std::flush; return 8; } GilHolder gilLock(gilEnsure, gilRelease); // acquire and hold the GIL until done... pyRun_SimpleString(command); return 0; } // ======================================== Code related to setting tracing to existing threads. /** * This function is meant to be called to execute some arbitrary python code to be * run. It'll initialize threads as needed and then run the code with pyRun_SimpleString. * * @param command: the python code to be run * @param attachInfo: pointer to an int specifying whether we should show debug info (1) or not (0). **/ DECLDIR int AttachAndRunPythonCode(const char *command, int *attachInfo ) { int SHOW_DEBUG_INFO = 1; bool showDebugInfo = (*attachInfo & SHOW_DEBUG_INFO) != 0; if (showDebugInfo) { std::cout << "AttachAndRunPythonCode started (showing debug info). " << std::endl << std::flush; } ModuleInfo moduleInfo = GetPythonModule(); if (moduleInfo.errorGettingModule != 0) { return moduleInfo.errorGettingModule; } HMODULE module = moduleInfo.module; int attached = DoAttach(module, moduleInfo.isDebug, command, showDebugInfo); if (attached != 0) { std::cerr << "Error when injecting code in target process. Error code (on windows): " << attached << std::endl << std::flush; } return attached; } DECLDIR int PrintDebugInfo() { PRINT("Getting debug info..."); ModuleInfo moduleInfo = GetPythonModule(); if (moduleInfo.errorGettingModule != 0) { PRINT("Error getting python module"); return 0; } HMODULE module = moduleInfo.module; DEFINE_PROC(interpHead, PyInterpreterState_Head*, "PyInterpreterState_Head", 0); DEFINE_PROC(threadHead, PyInterpreterState_ThreadHead*, "PyInterpreterState_ThreadHead", 0); DEFINE_PROC(threadNext, PyThreadState_Next*, "PyThreadState_Next", 160); DEFINE_PROC(gilEnsure, PyGILState_Ensure*, "PyGILState_Ensure", 0); DEFINE_PROC(gilRelease, PyGILState_Release*, "PyGILState_Release", 0); auto head = interpHead(); if (head == nullptr) { // this interpreter is loaded but not initialized. PRINT("Interpreter not initialized!"); return 0; } auto version = GetPythonVersion(module); printf("Python version: %d\n", version); GilHolder gilLock(gilEnsure, gilRelease); // acquire and hold the GIL until done... auto curThread = threadHead(head); if (curThread == nullptr) { PRINT("Thread head is NULL.") return 0; } for (auto curThread = threadHead(head); curThread != nullptr; curThread = threadNext(curThread)) { printf("Found thread id: %d\n", GetPythonThreadId(version, curThread)); } PRINT("Finished getting debug info.") return 0; } /** * This function may be called to set a tracing function to existing python threads. **/ DECLDIR int AttachDebuggerTracing(bool showDebugInfo, void* pSetTraceFunc, void* pTraceFunc, unsigned int threadId, void* pPyNone) { ModuleInfo moduleInfo = GetPythonModule(); if (moduleInfo.errorGettingModule != 0) { return moduleInfo.errorGettingModule; } HMODULE module = moduleInfo.module; if (showDebugInfo) { std::cout << "Setting sys trace for existing threads." << std::endl << std::flush; } int attached = 0; PyObjectHolder traceFunc(moduleInfo.isDebug, reinterpret_cast<PyObject*>(pTraceFunc), true); PyObjectHolder setTraceFunc(moduleInfo.isDebug, reinterpret_cast<PyObject*>(pSetTraceFunc), true); PyObjectHolder pyNone(moduleInfo.isDebug, reinterpret_cast<PyObject*>(pPyNone), true); int temp = InternalSetSysTraceFunc(module, moduleInfo.isDebug, showDebugInfo, &traceFunc, &setTraceFunc, threadId, &pyNone); if (temp == 0) { // we've successfully attached the debugger return 0; } else { if (temp > attached) { //I.e.: the higher the value the more significant it is. attached = temp; } } if (showDebugInfo) { std::cout << "Setting sys trace for existing threads failed with code: " << attached << "." << std::endl << std::flush; } return attached; } }
27,447
C++
42.225197
171
0.602142
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/windows/stdafx.h
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ // stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #include "targetver.h" #include <cstdint> #include <fstream> #include <string> #include <unordered_set> #include <unordered_map> #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <psapi.h> #include <strsafe.h> #include <tlhelp32.h> #include <winsock.h> #include <winternl.h>
1,162
C
30.432432
97
0.636833
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/windows/py_win_helpers.hpp
#ifndef _PY_WIN_HELPERS_HPP_ #define _PY_WIN_HELPERS_HPP_ bool IsPythonModule(HMODULE module, bool &isDebug) { wchar_t mod_name[MAX_PATH]; isDebug = false; if (GetModuleBaseName(GetCurrentProcess(), module, mod_name, MAX_PATH)) { if (_wcsnicmp(mod_name, L"python", 6) == 0) { if (wcslen(mod_name) >= 10 && _wcsnicmp(mod_name + 8, L"_d", 2) == 0) { isDebug = true; } // Check if the module has Py_IsInitialized. DEFINE_PROC_NO_CHECK(isInit, Py_IsInitialized*, "Py_IsInitialized", 0); DEFINE_PROC_NO_CHECK(gilEnsure, PyGILState_Ensure*, "PyGILState_Ensure", 51); DEFINE_PROC_NO_CHECK(gilRelease, PyGILState_Release*, "PyGILState_Release", 51); if (isInit == nullptr || gilEnsure == nullptr || gilRelease == nullptr) { return false; } return true; } } return false; } struct ModuleInfo { HMODULE module; bool isDebug; int errorGettingModule; // 0 means ok, negative values some error (should never be positive). }; ModuleInfo GetPythonModule() { HANDLE hProcess = GetCurrentProcess(); ModuleInfo moduleInfo; moduleInfo.module = nullptr; moduleInfo.isDebug = false; moduleInfo.errorGettingModule = 0; DWORD modSize = sizeof(HMODULE) * 1024; HMODULE* hMods = (HMODULE*)_malloca(modSize); if (hMods == nullptr) { std::cout << "hmods not allocated! " << std::endl << std::flush; moduleInfo.errorGettingModule = -1; return moduleInfo; } DWORD modsNeeded; while (!EnumProcessModules(hProcess, hMods, modSize, &modsNeeded)) { // try again w/ more space... _freea(hMods); hMods = (HMODULE*)_malloca(modsNeeded); if (hMods == nullptr) { std::cout << "hmods not allocated (2)! " << std::endl << std::flush; moduleInfo.errorGettingModule = -2; return moduleInfo; } modSize = modsNeeded; } for (size_t i = 0; i < modsNeeded / sizeof(HMODULE); i++) { bool isDebug; if (IsPythonModule(hMods[i], isDebug)) { moduleInfo.isDebug = isDebug; moduleInfo.module = hMods[i]; return moduleInfo; } } std::cout << "Unable to find python module. " << std::endl << std::flush; moduleInfo.errorGettingModule = -3; return moduleInfo; } #endif
2,479
C++
31.207792
97
0.578459
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/windows/run_code_on_dllmain.cpp
#include <iostream> #include <thread> #include "attach.h" #include "stdafx.h" #include <windows.h> #include <stdio.h> #include <conio.h> #include <tchar.h> typedef int (_RunCodeInMemoryInAttachedDll)(); HINSTANCE globalDllInstance = NULL; class NotificationHelper { public: #pragma warning( push ) #pragma warning( disable : 4722 ) // disable c4722 here: Destructor never returns warning. Compiler sees ExitThread and assumes that // there is a potential memory leak. ~NotificationHelper(){ std::string eventName("_pydevd_pid_event_"); eventName += std::to_string(GetCurrentProcessId()); // When we finish we need to set the event that the caller is waiting for and // unload the dll (if we don't exit this dll we won't be able to reattach later on). auto event = CreateEventA(nullptr, false, false, eventName.c_str()); if (event != nullptr) { SetEvent(event); CloseHandle(event); } FreeLibraryAndExitThread(globalDllInstance, 0); } #pragma warning( pop ) }; DWORD WINAPI RunCodeInThread(LPVOID lpParam){ NotificationHelper notificationHelper; // When we exit the scope the destructor should take care of the cleanup. #ifdef BITS_32 HMODULE attachModule = GetModuleHandleA("attach_x86.dll"); #else HMODULE attachModule = GetModuleHandleA("attach_amd64.dll"); #endif if (attachModule == nullptr) { std::cout << "Error: unable to get attach_x86.dll or attach_amd64.dll module handle." << std::endl; return 900; } _RunCodeInMemoryInAttachedDll* runCode = reinterpret_cast < _RunCodeInMemoryInAttachedDll* > (GetProcAddress(attachModule, "RunCodeInMemoryInAttachedDll")); if (runCode == nullptr) { std::cout << "Error: unable to GetProcAddress(attachModule, RunCodeInMemoryInAttachedDll) from attach_x86.dll or attach_amd64.dll." << std::endl; return 901; } runCode(); return 0; } /** * When the dll is loaded we create a thread that will call 'RunCodeInMemoryInAttachedDll' * in the attach dll (when completed we unload this library for a reattach to work later on). */ BOOL WINAPI DllMain( _In_ HINSTANCE hinstDLL, _In_ DWORD fdwReason, _In_ LPVOID lpvReserved ){ if(fdwReason == DLL_PROCESS_ATTACH){ globalDllInstance = hinstDLL; DWORD threadId; CreateThread(nullptr, 0, &RunCodeInThread, nullptr, 0, &threadId); } else if(fdwReason == DLL_PROCESS_DETACH){ } return true; }
2,516
C++
30.860759
160
0.683625
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/windows/targetver.h
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ #pragma once // Including SDKDDKVer.h defines the highest available Windows platform. // If you wish to build your application for a previous Windows platform, include WinSDKVer.h and // set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. #include <SDKDDKVer.h>
1,013
C
43.086955
98
0.631787
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/windows/run_code_in_memory.hpp
#ifndef _PY_RUN_CODE_IN_MEMORY_HPP_ #define _PY_RUN_CODE_IN_MEMORY_HPP_ #include <iostream> #include "attach.h" #include "stdafx.h" #include <windows.h> #include <stdio.h> #include <conio.h> #include <tchar.h> #include "../common/python.h" #include "../common/ref_utils.hpp" #include "../common/py_utils.hpp" #include "../common/py_settrace.hpp" #include "py_win_helpers.hpp" #pragma comment(lib, "kernel32.lib") #pragma comment(lib, "user32.lib") #pragma comment(lib, "advapi32.lib") DECLDIR int AttachAndRunPythonCode(const char *command, int *attachInfo ); // NOTE: BUFSIZE must be the same from add_code_to_python_process.py #define BUFSIZE 2048 // Helper to free data when we leave the scope. class DataToFree { public: HANDLE hMapFile; void* mapViewOfFile; char* codeToRun; DataToFree() { this->hMapFile = nullptr; this->mapViewOfFile = nullptr; this->codeToRun = nullptr; } ~DataToFree() { if (this->hMapFile != nullptr) { CloseHandle(this->hMapFile); this->hMapFile = nullptr; } if (this->mapViewOfFile != nullptr) { UnmapViewOfFile(this->mapViewOfFile); this->mapViewOfFile = nullptr; } if (this->codeToRun != nullptr) { delete this->codeToRun; this->codeToRun = nullptr; } } }; extern "C" { /** * This method will read the code to be executed from the named shared memory * and execute it. */ DECLDIR int RunCodeInMemoryInAttachedDll() { // PRINT("Attempting to run Python code from named shared memory.") //get the code to be run (based on https://docs.microsoft.com/en-us/windows/win32/memory/creating-named-shared-memory). HANDLE hMapFile; char* mapViewOfFile; DataToFree dataToFree; std::string namedSharedMemoryName("__pydevd_pid_code_to_run__"); namedSharedMemoryName += std::to_string(GetCurrentProcessId()); hMapFile = OpenFileMappingA( FILE_MAP_ALL_ACCESS, // read/write access FALSE, // do not inherit the name namedSharedMemoryName.c_str()); // name of mapping object if (hMapFile == nullptr) { std::cout << "Error opening named shared memory (OpenFileMapping): " << GetLastError() + " name: " << namedSharedMemoryName << std::endl; return 1; } else { // PRINT("Opened named shared memory.") } dataToFree.hMapFile = hMapFile; mapViewOfFile = reinterpret_cast < char* > (MapViewOfFile(hMapFile, // handle to map object FILE_MAP_ALL_ACCESS, // read/write permission 0, 0, BUFSIZE)); if (mapViewOfFile == nullptr) { std::cout << "Error mapping view of named shared memory (MapViewOfFile): " << GetLastError() << std::endl; return 1; } else { // PRINT("Mapped view of file.") } dataToFree.mapViewOfFile = mapViewOfFile; // std::cout << "Will run contents: " << mapViewOfFile << std::endl; dataToFree.codeToRun = new char[BUFSIZE]; memmove(dataToFree.codeToRun, mapViewOfFile, BUFSIZE); int attachInfo = 0; return AttachAndRunPythonCode(dataToFree.codeToRun, &attachInfo); } } #endif
3,355
C++
27.931034
149
0.610432
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/windows/stdafx.cpp
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ // stdafx.cpp : source file that includes just the standard includes // PyDebugAttach.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
999
C++
42.478259
98
0.624625
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/windows/attach.h
/* **************************************************************************** * * Copyright (c) Brainwy software Ltda. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ #ifndef _ATTACH_DLL_H_ #define _ATTACH_DLL_H_ #if defined DLL_EXPORT #define DECLDIR __declspec(dllexport) #else #define DECLDIR __declspec(dllimport) #endif extern "C" { DECLDIR int AttachAndRunPythonCode(const char *command, int *result ); /* * Helper to print debug information from the current process */ DECLDIR int PrintDebugInfo(); /* Could be used with ctypes (note that the threading should be initialized, so, doing it in a thread as below is recommended): def check(): import ctypes lib = ctypes.cdll.LoadLibrary(r'C:\...\attach_x86.dll') print 'result', lib.AttachDebuggerTracing(0) t = threading.Thread(target=check) t.start() t.join() */ DECLDIR int AttachDebuggerTracing( bool showDebugInfo, void* pSetTraceFunc, // Actually PyObject*, but we don't want to include it here. void* pTraceFunc, // Actually PyObject*, but we don't want to include it here. unsigned int threadId, void* pPyNone // Actually PyObject*, but we don't want to include it here. ); } #endif
1,846
C
31.403508
97
0.613218
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/windows/inject_dll.cpp
#include <iostream> #include <windows.h> #include <stdio.h> #include <conio.h> #include <tchar.h> #include <tlhelp32.h> #pragma comment(lib, "kernel32.lib") #pragma comment(lib, "user32.lib") // Helper to free data when we leave the scope. class DataToFree { public: HANDLE hProcess; HANDLE snapshotHandle; LPVOID remoteMemoryAddr; int remoteMemorySize; DataToFree(){ this->hProcess = nullptr; this->snapshotHandle = nullptr; this->remoteMemoryAddr = nullptr; this->remoteMemorySize = 0; } ~DataToFree() { if(this->hProcess != nullptr){ if(this->remoteMemoryAddr != nullptr && this->remoteMemorySize != 0){ VirtualFreeEx(this->hProcess, this->remoteMemoryAddr, this->remoteMemorySize, MEM_RELEASE); this->remoteMemoryAddr = nullptr; this->remoteMemorySize = 0; } CloseHandle(this->hProcess); this->hProcess = nullptr; } if(this->snapshotHandle != nullptr){ CloseHandle(this->snapshotHandle); this->snapshotHandle = nullptr; } } }; /** * All we do here is load a dll in a remote program (in a remote thread). * * Arguments must be the pid and the dll name to run. * * i.e.: inject_dll.exe <pid> <dll path> */ int wmain( int argc, wchar_t *argv[ ], wchar_t *envp[ ] ) { std::cout << "Running executable to inject dll." << std::endl; // Helper to clear resources. DataToFree dataToFree; if(argc != 3){ std::cout << "Expected 2 arguments (pid, dll name)." << std::endl; return 1; } const int pid = _wtoi(argv[1]); if(pid == 0){ std::cout << "Invalid pid." << std::endl; return 2; } const int MAX_PATH_SIZE_PADDED = MAX_PATH + 1; char dllPath[MAX_PATH_SIZE_PADDED]; memset(&dllPath[0], '\0', MAX_PATH_SIZE_PADDED); size_t pathLen = 0; wcstombs_s(&pathLen, dllPath, argv[2], MAX_PATH); const bool inheritable = false; const HANDLE hProcess = OpenProcess(PROCESS_VM_OPERATION | PROCESS_CREATE_THREAD | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_QUERY_INFORMATION, inheritable, pid); if(hProcess == nullptr || hProcess == INVALID_HANDLE_VALUE){ std::cout << "Unable to open process with pid: " << pid << ". Error code: " << GetLastError() << "." << std::endl; return 3; } dataToFree.hProcess = hProcess; std::cout << "OpenProcess with pid: " << pid << std::endl; const LPVOID remoteMemoryAddr = VirtualAllocEx(hProcess, nullptr, MAX_PATH_SIZE_PADDED, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE); if(remoteMemoryAddr == nullptr){ std::cout << "Error. Unable to allocate memory in pid: " << pid << ". Error code: " << GetLastError() << "." << std::endl; return 4; } dataToFree.remoteMemorySize = MAX_PATH_SIZE_PADDED; dataToFree.remoteMemoryAddr = remoteMemoryAddr; std::cout << "VirtualAllocEx in pid: " << pid << std::endl; const bool written = WriteProcessMemory(hProcess, remoteMemoryAddr, dllPath, pathLen, nullptr); if(!written){ std::cout << "Error. Unable to write to memory in pid: " << pid << ". Error code: " << GetLastError() << "." << std::endl; return 5; } std::cout << "WriteProcessMemory in pid: " << pid << std::endl; const LPVOID loadLibraryAddress = (LPVOID) GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA"); if(loadLibraryAddress == nullptr){ std::cout << "Error. Unable to get LoadLibraryA address. Error code: " << GetLastError() << "." << std::endl; return 6; } std::cout << "loadLibraryAddress: " << pid << std::endl; const HANDLE remoteThread = CreateRemoteThread(hProcess, nullptr, 0, (LPTHREAD_START_ROUTINE) loadLibraryAddress, remoteMemoryAddr, 0, nullptr); if (remoteThread == nullptr) { std::cout << "Error. Unable to CreateRemoteThread. Error code: " << GetLastError() << "." << std::endl; return 7; } // We wait for the load to finish before proceeding to get the function to actually do the attach. std::cout << "Waiting for LoadLibraryA to complete." << std::endl; DWORD result = WaitForSingleObject(remoteThread, 5 * 1000); if(result == WAIT_TIMEOUT) { std::cout << "WaitForSingleObject(LoadLibraryA thread) timed out." << std::endl; return 8; } else if(result == WAIT_FAILED) { std::cout << "WaitForSingleObject(LoadLibraryA thread) failed. Error code: " << GetLastError() << "." << std::endl; return 9; } std::cout << "Ok, finished dll injection." << std::endl; return 0; }
4,792
C++
34.768656
169
0.604967
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/_vendored/pydevd/pydevd_attach_to_process/linux_and_mac/attach.cpp
// This is much simpler than the windows version because we're using gdb and // we assume that gdb will call things in the correct thread already. //compile with: g++ -shared -o attach_linux.so -fPIC -nostartfiles attach_linux.c #include <stdio.h> #include <stdlib.h> #include <dlfcn.h> #include <stdbool.h> #include "../common/python.h" #include "../common/ref_utils.hpp" #include "../common/py_utils.hpp" #include "../common/py_settrace.hpp" //#include <unistd.h> used for usleep // Exported function: hello(): Just to print something and check that we've been // able to connect. extern "C" int hello(void); int hello() { printf("Hello world!\n"); void *module = dlopen(nullptr, 0x2); void *hndl = dlsym (module, "PyGILState_Ensure"); if(hndl == nullptr){ printf("nullptr\n"); }else{ printf("Worked (found PyGILState_Ensure)!\n"); } printf("%d", GetPythonVersion(module)); return 2; } // Internal function to keep on the tracing int _PYDEVD_ExecWithGILSetSysStrace(bool showDebugInfo, bool isDebug); // Implementation details below typedef PyObject* (PyImport_ImportModuleNoBlock) (const char *name); typedef int (*PyEval_ThreadsInitialized)(); typedef unsigned long (*_PyEval_GetSwitchInterval)(void); typedef void (*_PyEval_SetSwitchInterval)(unsigned long microseconds); // isDebug is pretty important! Must be true on python debug builds (python_d) // If this value is passed wrongly the program will crash. extern "C" int DoAttach(bool isDebug, const char *command, bool showDebugInfo); int DoAttach(bool isDebug, const char *command, bool showDebugInfo) { void *module = dlopen(nullptr, 0x2); DEFINE_PROC(isInitFunc, Py_IsInitialized*, "Py_IsInitialized", 1); DEFINE_PROC(gilEnsure, PyGILState_Ensure*, "PyGILState_Ensure", 51); DEFINE_PROC(gilRelease, PyGILState_Release*, "PyGILState_Release", 51); if(!isInitFunc()){ if(showDebugInfo){ printf("Py_IsInitialized returned false.\n"); } return 2; } PythonVersion version = GetPythonVersion(module); DEFINE_PROC(interpHead, PyInterpreterState_Head*, "PyInterpreterState_Head", 51); auto head = interpHead(); if (head == nullptr) { // this interpreter is loaded but not initialized. if(showDebugInfo){ printf("Interpreter not initialized!\n"); } return 54; } // Note: unlike windows where we have to do many things to enable threading // to work to get the gil, here we'll be executing in an existing thread, // so, it's mostly a matter of getting the GIL and running it and we shouldn't // have any more problems. DEFINE_PROC(pyRun_SimpleString, PyRun_SimpleString*, "PyRun_SimpleString", 51); GilHolder gilLock(gilEnsure, gilRelease); // acquire and hold the GIL until done... pyRun_SimpleString(command); return 0; } // This is the function which enables us to set the sys.settrace for all the threads // which are already running. extern "C" int AttachDebuggerTracing(bool showDebugInfo, void* pSetTraceFunc, void* pTraceFunc, unsigned int threadId, void* pPyNone); int AttachDebuggerTracing(bool showDebugInfo, void* pSetTraceFunc, void* pTraceFunc, unsigned int threadId, void* pPyNone) { void *module = dlopen(nullptr, 0x2); bool isDebug = false; PyObjectHolder traceFunc(isDebug, (PyObject*) pTraceFunc, true); PyObjectHolder setTraceFunc(isDebug, (PyObject*) pSetTraceFunc, true); PyObjectHolder pyNone(isDebug, reinterpret_cast<PyObject*>(pPyNone), true); return InternalSetSysTraceFunc(module, isDebug, showDebugInfo, &traceFunc, &setTraceFunc, threadId, &pyNone); }
3,703
C++
32.071428
134
0.702944
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/common/py_custom_pyeval_settrace_310.hpp
#ifndef _PY_CUSTOM_PYEVAL_SETTRACE_310_HPP_ #define _PY_CUSTOM_PYEVAL_SETTRACE_310_HPP_ #include "python.h" #include "py_utils.hpp" static PyObject * InternalCallTrampoline310(PyObject* callback, PyFrameObject310 *frame, int what, PyObject *arg) { PyObject *result; PyObject *stack[3]; // Note: this is commented out from CPython (we shouldn't need it and it adds a reasonable overhead). // if (PyFrame_FastToLocalsWithError(frame) < 0) { // return NULL; // } // stack[0] = (PyObject *)frame; stack[1] = InternalWhatstrings_37[what]; stack[2] = (arg != NULL) ? arg : internalInitializeCustomPyEvalSetTrace->pyNone; // Helper to print info. // printf("%s\n", internalInitializeCustomPyEvalSetTrace->pyUnicode_AsUTF8(internalInitializeCustomPyEvalSetTrace->pyObject_Repr((PyObject *)stack[0]))); // printf("%s\n", internalInitializeCustomPyEvalSetTrace->pyUnicode_AsUTF8(internalInitializeCustomPyEvalSetTrace->pyObject_Repr((PyObject *)stack[1]))); // printf("%s\n", internalInitializeCustomPyEvalSetTrace->pyUnicode_AsUTF8(internalInitializeCustomPyEvalSetTrace->pyObject_Repr((PyObject *)stack[2]))); // printf("%s\n", internalInitializeCustomPyEvalSetTrace->pyUnicode_AsUTF8(internalInitializeCustomPyEvalSetTrace->pyObject_Repr((PyObject *)callback))); result = internalInitializeCustomPyEvalSetTrace->pyObject_FastCallDict(callback, stack, 3, NULL); // Note: this is commented out from CPython (we shouldn't need it and it adds a reasonable overhead). // PyFrame_LocalsToFast(frame, 1); if (result == NULL) { internalInitializeCustomPyEvalSetTrace->pyTraceBack_Here(frame); } return result; } // See: static int trace_trampoline(PyObject *self, PyFrameObject *frame, int what, PyObject *arg) // in: https://github.com/python/cpython/blob/3.10/Python/sysmodule.c static int InternalTraceTrampoline310(PyObject *self, PyFrameObject *frameParam, int what, PyObject *arg) { PyObject *callback; PyObject *result; PyFrameObject310 *frame = reinterpret_cast<PyFrameObject310*>(frameParam); if (what == PyTrace_CALL){ callback = self; } else { callback = frame->f_trace; } if (callback == NULL){ return 0; } result = InternalCallTrampoline310(callback, frame, what, arg); if (result == NULL) { // Note: calling the original sys.settrace here. internalInitializeCustomPyEvalSetTrace->pyEval_SetTrace(NULL, NULL); PyObject *temp_f_trace = frame->f_trace; frame->f_trace = NULL; if(temp_f_trace != NULL){ DecRef(temp_f_trace, internalInitializeCustomPyEvalSetTrace->isDebug); } return -1; } if (result != internalInitializeCustomPyEvalSetTrace->pyNone) { PyObject *tmp = frame->f_trace; frame->f_trace = result; DecRef(tmp, internalInitializeCustomPyEvalSetTrace->isDebug); } else { DecRef(result, internalInitializeCustomPyEvalSetTrace->isDebug); } return 0; } // Based on ceval.c (PyEval_SetTrace(Py_tracefunc func, PyObject *arg)) // https://github.com/python/cpython/blob/3.10/Python/ceval.c template<typename T> void InternalPySetTrace_Template310(T tstate, PyObjectHolder* traceFunc, bool isDebug) { PyObject *temp = tstate->c_traceobj; PyObject *arg = traceFunc->ToPython(); IncRef(arg); tstate->c_tracefunc = NULL; tstate->c_traceobj = NULL; // This is different (previously it was just: tstate->use_tracing, now // this flag is per-frame). tstate->cframe->use_tracing = tstate->c_profilefunc != NULL; if(temp != NULL){ DecRef(temp, isDebug); } tstate->c_tracefunc = InternalTraceTrampoline310; tstate->c_traceobj = arg; /* Flag that tracing or profiling is turned on */ tstate->cframe->use_tracing = ((InternalTraceTrampoline310 != NULL) || (tstate->c_profilefunc != NULL)); }; #endif //_PY_CUSTOM_PYEVAL_SETTRACE_310_HPP_
4,062
C++
34.955752
157
0.678976
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/common/py_custom_pyeval_settrace.hpp
#ifndef _PY_CUSTOM_PYEVAL_SETTRACE_HPP_ #define _PY_CUSTOM_PYEVAL_SETTRACE_HPP_ #include "python.h" #include "py_utils.hpp" #include "py_custom_pyeval_settrace_common.hpp" #include "py_custom_pyeval_settrace_310.hpp" #include "py_custom_pyeval_settrace_311.hpp" // On Python 3.7 onwards the thread state is not kept in PyThread_set_key_value (rather // it uses PyThread_tss_set using PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate) // and we don't have access to that key from here (thus, we can't use the previous approach which // made CPython think that the current thread had the thread state where we wanted to set the tracing). // // So, the solution implemented here is not faking that change and reimplementing PyEval_SetTrace. // The implementation is mostly the same from the one in CPython, but we have one shortcoming: // // When CPython sets the tracing for a thread it increments _Py_TracingPossible (actually // _PyRuntime.ceval.tracing_possible). This implementation has one issue: it only works on // deltas when the tracing is set (so, a settrace(func) will increase the _Py_TracingPossible global value and a // settrace(None) will decrease it, but when a thread dies it's kept as is and is not decreased). // -- as we don't currently have access to _PyRuntime we have to create a thread, set the tracing // and let it die so that the count is increased (this is really hacky, but better than having // to create a local copy of the whole _PyRuntime (defined in pystate.h with several inner structs) // which would need to be kept up to date for each new CPython version just to increment that variable). /** * This version is used in internalInitializeCustomPyEvalSetTrace->pyObject_FastCallDict on older * versions of CPython (pre 3.7). */ static PyObject * PyObject_FastCallDictCustom(PyObject* callback, PyObject *stack[3], int ignoredStackSizeAlways3, void* ignored) { PyObject *args = internalInitializeCustomPyEvalSetTrace->pyTuple_New(3); PyObject *result; if (args == NULL) { return NULL; } IncRef(stack[0]); IncRef(stack[1]); IncRef(stack[2]); // I.e.: same thing as: PyTuple_SET_ITEM(args, 0, stack[0]); reinterpret_cast<PyTupleObject *>(args)->ob_item[0] = stack[0]; reinterpret_cast<PyTupleObject *>(args)->ob_item[1] = stack[1]; reinterpret_cast<PyTupleObject *>(args)->ob_item[2] = stack[2]; /* call the Python-level function */ result = internalInitializeCustomPyEvalSetTrace->pyEval_CallObjectWithKeywords(callback, args, (PyObject*)NULL); /* cleanup */ DecRef(args, internalInitializeCustomPyEvalSetTrace->isDebug); return result; } static PyObject * InternalCallTrampoline(PyObject* callback, PyFrameObjectBaseUpTo39 *frame, int what, PyObject *arg) { PyObject *result; PyObject *stack[3]; // Note: this is commented out from CPython (we shouldn't need it and it adds a reasonable overhead). // if (PyFrame_FastToLocalsWithError(frame) < 0) { // return NULL; // } // stack[0] = (PyObject *)frame; stack[1] = InternalWhatstrings_37[what]; stack[2] = (arg != NULL) ? arg : internalInitializeCustomPyEvalSetTrace->pyNone; // Helpers to print info. // printf("%s\n", internalInitializeCustomPyEvalSetTrace->pyUnicode_AsUTF8(internalInitializeCustomPyEvalSetTrace->pyObject_Repr((PyObject *)stack[0]))); // printf("%s\n", internalInitializeCustomPyEvalSetTrace->pyUnicode_AsUTF8(internalInitializeCustomPyEvalSetTrace->pyObject_Repr((PyObject *)stack[1]))); // printf("%s\n", internalInitializeCustomPyEvalSetTrace->pyUnicode_AsUTF8(internalInitializeCustomPyEvalSetTrace->pyObject_Repr((PyObject *)stack[2]))); // printf("%s\n", internalInitializeCustomPyEvalSetTrace->pyUnicode_AsUTF8(internalInitializeCustomPyEvalSetTrace->pyObject_Repr((PyObject *)callback))); // call the Python-level function // result = _PyObject_FastCall(callback, stack, 3); // // Note that _PyObject_FastCall is actually a define: // #define _PyObject_FastCall(func, args, nargs) _PyObject_FastCallDict((func), (args), (nargs), NULL) result = internalInitializeCustomPyEvalSetTrace->pyObject_FastCallDict(callback, stack, 3, NULL); // Note: this is commented out from CPython (we shouldn't need it and it adds a reasonable overhead). // PyFrame_LocalsToFast(frame, 1); if (result == NULL) { internalInitializeCustomPyEvalSetTrace->pyTraceBack_Here(frame); } return result; } static int InternalTraceTrampoline(PyObject *self, PyFrameObject *frameParam, int what, PyObject *arg) { PyObject *callback; PyObject *result; PyFrameObjectBaseUpTo39 *frame = reinterpret_cast<PyFrameObjectBaseUpTo39*>(frameParam); if (what == PyTrace_CALL){ callback = self; } else { callback = frame->f_trace; } if (callback == NULL){ return 0; } result = InternalCallTrampoline(callback, frame, what, arg); if (result == NULL) { // Note: calling the original sys.settrace here. internalInitializeCustomPyEvalSetTrace->pyEval_SetTrace(NULL, NULL); PyObject *temp_f_trace = frame->f_trace; frame->f_trace = NULL; if(temp_f_trace != NULL){ DecRef(temp_f_trace, internalInitializeCustomPyEvalSetTrace->isDebug); } return -1; } if (result != internalInitializeCustomPyEvalSetTrace->pyNone) { PyObject *tmp = frame->f_trace; frame->f_trace = result; DecRef(tmp, internalInitializeCustomPyEvalSetTrace->isDebug); } else { DecRef(result, internalInitializeCustomPyEvalSetTrace->isDebug); } return 0; } // Based on ceval.c (PyEval_SetTrace(Py_tracefunc func, PyObject *arg)) template<typename T> void InternalPySetTrace_Template(T tstate, PyObjectHolder* traceFunc, bool isDebug) { PyObject *temp = tstate->c_traceobj; // We can't increase _Py_TracingPossible. Everything else should be equal to CPython. // runtime->ceval.tracing_possible += (func != NULL) - (tstate->c_tracefunc != NULL); PyObject *arg = traceFunc->ToPython(); IncRef(arg); tstate->c_tracefunc = NULL; tstate->c_traceobj = NULL; /* Must make sure that profiling is not ignored if 'temp' is freed */ tstate->use_tracing = tstate->c_profilefunc != NULL; if(temp != NULL){ DecRef(temp, isDebug); } tstate->c_tracefunc = InternalTraceTrampoline; tstate->c_traceobj = arg; /* Flag that tracing or profiling is turned on */ tstate->use_tracing = ((InternalTraceTrampoline != NULL) || (tstate->c_profilefunc != NULL)); }; void InternalPySetTrace(PyThreadState* curThread, PyObjectHolder* traceFunc, bool isDebug, PythonVersion version) { if (PyThreadState_25_27::IsFor(version)) { InternalPySetTrace_Template<PyThreadState_25_27*>(reinterpret_cast<PyThreadState_25_27*>(curThread), traceFunc, isDebug); } else if (PyThreadState_30_33::IsFor(version)) { InternalPySetTrace_Template<PyThreadState_30_33*>(reinterpret_cast<PyThreadState_30_33*>(curThread), traceFunc, isDebug); } else if (PyThreadState_34_36::IsFor(version)) { InternalPySetTrace_Template<PyThreadState_34_36*>(reinterpret_cast<PyThreadState_34_36*>(curThread), traceFunc, isDebug); } else if (PyThreadState_37_38::IsFor(version)) { InternalPySetTrace_Template<PyThreadState_37_38*>(reinterpret_cast<PyThreadState_37_38*>(curThread), traceFunc, isDebug); } else if (PyThreadState_39::IsFor(version)) { InternalPySetTrace_Template<PyThreadState_39*>(reinterpret_cast<PyThreadState_39*>(curThread), traceFunc, isDebug); } else if (PyThreadState_310::IsFor(version)) { // 3.10 has other changes on the actual algorithm (use_tracing is per-frame now), so, we have a full new version for it. InternalPySetTrace_Template310<PyThreadState_310*>(reinterpret_cast<PyThreadState_310*>(curThread), traceFunc, isDebug); } else if (PyThreadState_311::IsFor(version)) { InternalPySetTrace_Template311<PyThreadState_311*>(reinterpret_cast<PyThreadState_311*>(curThread), traceFunc, isDebug); } else { printf("Unable to set trace to target thread with Python version: %d", version); } } #endif //_PY_CUSTOM_PYEVAL_SETTRACE_HPP_
8,399
C++
42.523316
157
0.703298
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/common/python.h
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. #ifndef __PYTHON_H__ #define __PYTHON_H__ #include "../common/py_version.hpp" #include <cstdint> #ifndef _WIN32 typedef unsigned int DWORD; typedef ssize_t SSIZE_T; #endif typedef SSIZE_T Py_ssize_t; // defines limited header of Python API for compatible access across a number of Pythons. class PyTypeObject; class PyThreadState; #define PyObject_HEAD \ size_t ob_refcnt; \ PyTypeObject *ob_type; #define PyObject_VAR_HEAD \ PyObject_HEAD \ size_t ob_size; /* Number of items in variable part */ class PyObject { public: PyObject_HEAD }; class PyVarObject : public PyObject { public: size_t ob_size; /* Number of items in variable part */ }; // 2.5 - 3.7 class PyFunctionObject : public PyObject { public: PyObject *func_code; /* A code object */ }; // 2.5 - 2.7 compatible class PyStringObject : public PyVarObject { public: long ob_shash; int ob_sstate; char ob_sval[1]; /* Invariants: * ob_sval contains space for 'ob_size+1' elements. * ob_sval[ob_size] == 0. * ob_shash is the hash of the string or -1 if not computed yet. * ob_sstate != 0 iff the string object is in stringobject.c's * 'interned' dictionary; in this case the two references * from 'interned' to this object are *not counted* in ob_refcnt. */ }; // 2.4 - 3.7 compatible typedef struct { PyObject_HEAD size_t length; /* Length of raw Unicode data in buffer */ wchar_t *str; /* Raw Unicode buffer */ long hash; /* Hash value; -1 if not set */ } PyUnicodeObject; class PyFrameObject : public PyObject { // After 3.10 we don't really have things we want to reuse common, so, // create an empty base (it's not based on PyVarObject because on Python 3.11 // it's just a PyObject and no longer a PyVarObject -- the part related to // the var object must be declared in ech subclass in this case). }; // 2.4 - 3.7 compatible class PyFrameObjectBaseUpTo39 : public PyFrameObject { public: size_t ob_size; /* Number of items in variable part -- i.e.: PyVarObject*/ PyFrameObjectBaseUpTo39 *f_back; /* previous frame, or nullptr */ PyObject *f_code; /* code segment */ PyObject *f_builtins; /* builtin symbol table (PyDictObject) */ PyObject *f_globals; /* global symbol table (PyDictObject) */ PyObject *f_locals; /* local symbol table (any mapping) */ PyObject **f_valuestack; /* points after the last local */ /* Next free slot in f_valuestack. Frame creation sets to f_valuestack. Frame evaluation usually NULLs it, but a frame that yields sets it to the current stack top. */ PyObject **f_stacktop; PyObject *f_trace; /* Trace function */ // It has more things, but we're only interested in things up to f_trace. }; // https://github.com/python/cpython/blob/3.10/Include/cpython/frameobject.h class PyFrameObject310 : public PyFrameObject { public: size_t ob_size; /* Number of items in variable part -- i.e.: PyVarObject*/ PyFrameObject310 *f_back; /* previous frame, or NULL */ PyObject *f_code; /* code segment */ PyObject *f_builtins; /* builtin symbol table (PyDictObject) */ PyObject *f_globals; /* global symbol table (PyDictObject) */ PyObject *f_locals; /* local symbol table (any mapping) */ PyObject **f_valuestack; /* points after the last local */ PyObject *f_trace; /* Trace function */ // It has more things, but we're only interested in things up to f_trace. }; typedef uint16_t _Py_CODEUNIT; // https://github.com/python/cpython/blob/3.11/Include/internal/pycore_frame.h typedef struct _PyInterpreterFrame311 { /* "Specials" section */ PyFunctionObject *f_func; /* Strong reference */ PyObject *f_globals; /* Borrowed reference */ PyObject *f_builtins; /* Borrowed reference */ PyObject *f_locals; /* Strong reference, may be NULL */ void *f_code; /* Strong reference */ void *frame_obj; /* Strong reference, may be NULL */ /* Linkage section */ struct _PyInterpreterFrame311 *previous; // NOTE: This is not necessarily the last instruction started in the given // frame. Rather, it is the code unit *prior to* the *next* instruction. For // example, it may be an inline CACHE entry, an instruction we just jumped // over, or (in the case of a newly-created frame) a totally invalid value: _Py_CODEUNIT *prev_instr; int stacktop; /* Offset of TOS from localsplus */ bool is_entry; // Whether this is the "root" frame for the current _PyCFrame. char owner; /* Locals and stack */ PyObject *localsplus[1]; } _PyInterpreterFrame311; // https://github.com/python/cpython/blob/3.11/Include/internal/pycore_frame.h // Note that in 3.11 it's no longer a "PyVarObject". class PyFrameObject311 : public PyFrameObject { public: PyFrameObject311 *f_back; /* previous frame, or NULL */ struct _PyInterpreterFrame311 *f_frame; /* points to the frame data */ PyObject *f_trace; /* Trace function */ int f_lineno; /* Current line number. Only valid if non-zero */ char f_trace_lines; /* Emit per-line trace events? */ char f_trace_opcodes; /* Emit per-opcode trace events? */ char f_fast_as_locals; /* Have the fast locals of this frame been converted to a dict? */ // It has more things, but we're not interested on those. }; typedef void (*destructor)(PyObject *); // 2.4 - 3.7 class PyMethodDef { public: char *ml_name; /* The name of the built-in function/method */ }; // // 2.5 - 3.7 // While these are compatible there are fields only available on later versions. class PyTypeObject : public PyVarObject { public: const char *tp_name; /* For printing, in format "<module>.<name>" */ size_t tp_basicsize, tp_itemsize; /* For allocation */ /* Methods to implement standard operations */ destructor tp_dealloc; void *tp_print; void *tp_getattr; void *tp_setattr; union { void *tp_compare; /* 2.4 - 3.4 */ void *tp_as_async; /* 3.5 - 3.7 */ }; void *tp_repr; /* Method suites for standard classes */ void *tp_as_number; void *tp_as_sequence; void *tp_as_mapping; /* More standard operations (here for binary compatibility) */ void *tp_hash; void *tp_call; void *tp_str; void *tp_getattro; void *tp_setattro; /* Functions to access object as input/output buffer */ void *tp_as_buffer; /* Flags to define presence of optional/expanded features */ long tp_flags; const char *tp_doc; /* Documentation string */ /* Assigned meaning in release 2.0 */ /* call function for all accessible objects */ void *tp_traverse; /* delete references to contained objects */ void *tp_clear; /* Assigned meaning in release 2.1 */ /* rich comparisons */ void *tp_richcompare; /* weak reference enabler */ size_t tp_weaklistoffset; /* Added in release 2.2 */ /* Iterators */ void *tp_iter; void *tp_iternext; /* Attribute descriptor and subclassing stuff */ PyMethodDef *tp_methods; struct PyMemberDef *tp_members; struct PyGetSetDef *tp_getset; struct _typeobject *tp_base; PyObject *tp_dict; void *tp_descr_get; void *tp_descr_set; size_t tp_dictoffset; void *tp_init; void *tp_alloc; void *tp_new; void *tp_free; /* Low-level free-memory routine */ void *tp_is_gc; /* For PyObject_IS_GC */ PyObject *tp_bases; PyObject *tp_mro; /* method resolution order */ PyObject *tp_cache; PyObject *tp_subclasses; PyObject *tp_weaklist; void *tp_del; /* Type attribute cache version tag. Added in version 2.6 */ unsigned int tp_version_tag; }; // 2.4 - 3.7 class PyTupleObject : public PyVarObject { public: PyObject *ob_item[1]; /* ob_item contains space for 'ob_size' elements. * Items must normally not be nullptr, except during construction when * the tuple is not yet visible outside the function that builds it. */ }; // 2.4 - 3.7 class PyCFunctionObject : public PyObject { public: PyMethodDef *m_ml; /* Description of the C function to call */ PyObject *m_self; /* Passed as 'self' arg to the C func, can be nullptr */ PyObject *m_module; /* The __module__ attribute, can be anything */ }; typedef int (*Py_tracefunc)(PyObject *, PyFrameObject *, int, PyObject *); #define PyTrace_CALL 0 #define PyTrace_EXCEPTION 1 #define PyTrace_LINE 2 #define PyTrace_RETURN 3 #define PyTrace_C_CALL 4 #define PyTrace_C_EXCEPTION 5 #define PyTrace_C_RETURN 6 class PyInterpreterState { }; class PyThreadState { }; class PyThreadState_25_27 : public PyThreadState { public: /* See Python/ceval.c for comments explaining most fields */ PyThreadState *next; PyInterpreterState *interp; PyFrameObjectBaseUpTo39 *frame; int recursion_depth; /* 'tracing' keeps track of the execution depth when tracing/profiling. This is to prevent the actual trace/profile code from being recorded in the trace/profile. */ int tracing; int use_tracing; Py_tracefunc c_profilefunc; Py_tracefunc c_tracefunc; PyObject *c_profileobj; PyObject *c_traceobj; PyObject *curexc_type; PyObject *curexc_value; PyObject *curexc_traceback; PyObject *exc_type; PyObject *exc_value; PyObject *exc_traceback; PyObject *dict; /* Stores per-thread state */ /* tick_counter is incremented whenever the check_interval ticker * reaches zero. The purpose is to give a useful measure of the number * of interpreted bytecode instructions in a given thread. This * extremely lightweight statistic collector may be of interest to * profilers (like psyco.jit()), although nothing in the core uses it. */ int tick_counter; int gilstate_counter; PyObject *async_exc; /* Asynchronous exception to raise */ long thread_id; /* Thread id where this tstate was created */ /* XXX signal handlers should also be here */ static bool IsFor(int majorVersion, int minorVersion) { return majorVersion == 2 && (minorVersion >= 5 && minorVersion <= 7); } static bool IsFor(PythonVersion version) { return version >= PythonVersion_25 && version <= PythonVersion_27; } }; class PyThreadState_30_33 : public PyThreadState { public: PyThreadState *next; PyInterpreterState *interp; PyFrameObjectBaseUpTo39 *frame; int recursion_depth; char overflowed; /* The stack has overflowed. Allow 50 more calls to handle the runtime error. */ char recursion_critical; /* The current calls must not cause a stack overflow. */ /* 'tracing' keeps track of the execution depth when tracing/profiling. This is to prevent the actual trace/profile code from being recorded in the trace/profile. */ int tracing; int use_tracing; Py_tracefunc c_profilefunc; Py_tracefunc c_tracefunc; PyObject *c_profileobj; PyObject *c_traceobj; PyObject *curexc_type; PyObject *curexc_value; PyObject *curexc_traceback; PyObject *exc_type; PyObject *exc_value; PyObject *exc_traceback; PyObject *dict; /* Stores per-thread state */ /* tick_counter is incremented whenever the check_interval ticker * reaches zero. The purpose is to give a useful measure of the number * of interpreted bytecode instructions in a given thread. This * extremely lightweight statistic collector may be of interest to * profilers (like psyco.jit()), although nothing in the core uses it. */ int tick_counter; int gilstate_counter; PyObject *async_exc; /* Asynchronous exception to raise */ long thread_id; /* Thread id where this tstate was created */ /* XXX signal handlers should also be here */ static bool IsFor(int majorVersion, int minorVersion) { return majorVersion == 3 && (minorVersion >= 0 && minorVersion <= 3); } static bool IsFor(PythonVersion version) { return version >= PythonVersion_30 && version <= PythonVersion_33; } }; class PyThreadState_34_36 : public PyThreadState { public: PyThreadState *prev; PyThreadState *next; PyInterpreterState *interp; PyFrameObjectBaseUpTo39 *frame; int recursion_depth; char overflowed; /* The stack has overflowed. Allow 50 more calls to handle the runtime error. */ char recursion_critical; /* The current calls must not cause a stack overflow. */ /* 'tracing' keeps track of the execution depth when tracing/profiling. This is to prevent the actual trace/profile code from being recorded in the trace/profile. */ int tracing; int use_tracing; Py_tracefunc c_profilefunc; Py_tracefunc c_tracefunc; PyObject *c_profileobj; PyObject *c_traceobj; PyObject *curexc_type; PyObject *curexc_value; PyObject *curexc_traceback; PyObject *exc_type; PyObject *exc_value; PyObject *exc_traceback; PyObject *dict; /* Stores per-thread state */ int gilstate_counter; PyObject *async_exc; /* Asynchronous exception to raise */ long thread_id; /* Thread id where this tstate was created */ /* XXX signal handlers should also be here */ static bool IsFor(int majorVersion, int minorVersion) { return majorVersion == 3 && minorVersion >= 4 && minorVersion <= 6; } static bool IsFor(PythonVersion version) { return version >= PythonVersion_34 && version <= PythonVersion_36; } }; struct _PyErr_StackItem { PyObject *exc_type, *exc_value, *exc_traceback; struct _PyErr_StackItem *previous_item; }; class PyThreadState_37_38 : public PyThreadState { public: PyThreadState *prev; PyThreadState *next; PyInterpreterState *interp; PyFrameObjectBaseUpTo39 *frame; int recursion_depth; char overflowed; /* The stack has overflowed. Allow 50 more calls to handle the runtime error. */ char recursion_critical; /* The current calls must not cause a stack overflow. */ /* 'tracing' keeps track of the execution depth when tracing/profiling. This is to prevent the actual trace/profile code from being recorded in the trace/profile. */ int stackcheck_counter; int tracing; int use_tracing; Py_tracefunc c_profilefunc; Py_tracefunc c_tracefunc; PyObject *c_profileobj; PyObject *c_traceobj; PyObject *curexc_type; PyObject *curexc_value; PyObject *curexc_traceback; _PyErr_StackItem exc_state; _PyErr_StackItem *exc_info; PyObject *dict; /* Stores per-thread state */ int gilstate_counter; PyObject *async_exc; /* Asynchronous exception to raise */ unsigned long thread_id; /* Thread id where this tstate was created */ static bool IsFor(int majorVersion, int minorVersion) { return majorVersion == 3 && (minorVersion == 7 || minorVersion == 8); } static bool IsFor(PythonVersion version) { return version == PythonVersion_37 || version == PythonVersion_38; } }; // i.e.: https://github.com/python/cpython/blob/master/Include/cpython/pystate.h class PyThreadState_39 : public PyThreadState { public: PyThreadState *prev; PyThreadState *next; PyInterpreterState *interp; PyFrameObjectBaseUpTo39 *frame; int recursion_depth; char overflowed; /* The stack has overflowed. Allow 50 more calls to handle the runtime error. */ int stackcheck_counter; int tracing; int use_tracing; Py_tracefunc c_profilefunc; Py_tracefunc c_tracefunc; PyObject *c_profileobj; PyObject *c_traceobj; PyObject *curexc_type; PyObject *curexc_value; PyObject *curexc_traceback; _PyErr_StackItem exc_state; _PyErr_StackItem *exc_info; PyObject *dict; /* Stores per-thread state */ int gilstate_counter; PyObject *async_exc; /* Asynchronous exception to raise */ unsigned long thread_id; /* Thread id where this tstate was created */ static bool IsFor(int majorVersion, int minorVersion) { return majorVersion == 3 && minorVersion == 9; } static bool IsFor(PythonVersion version) { return version == PythonVersion_39; } }; typedef struct _cframe { /* This struct will be threaded through the C stack * allowing fast access to per-thread state that needs * to be accessed quickly by the interpreter, but can * be modified outside of the interpreter. * * WARNING: This makes data on the C stack accessible from * heap objects. Care must be taken to maintain stack * discipline and make sure that instances of this struct cannot * accessed outside of their lifetime. */ int use_tracing; struct _cframe *previous; } CFrame; // i.e.: https://github.com/python/cpython/blob/master/Include/cpython/pystate.h class PyThreadState_310 : public PyThreadState { public: PyThreadState *prev; PyThreadState *next; PyInterpreterState *interp; PyFrameObject310 *frame; int recursion_depth; int recursion_headroom; /* Allow 50 more calls to handle any errors. */ int stackcheck_counter; /* 'tracing' keeps track of the execution depth when tracing/profiling. This is to prevent the actual trace/profile code from being recorded in the trace/profile. */ int tracing; /* Pointer to current CFrame in the C stack frame of the currently, * or most recently, executing _PyEval_EvalFrameDefault. */ CFrame *cframe; Py_tracefunc c_profilefunc; Py_tracefunc c_tracefunc; PyObject *c_profileobj; PyObject *c_traceobj; PyObject *curexc_type; PyObject *curexc_value; PyObject *curexc_traceback; _PyErr_StackItem exc_state; _PyErr_StackItem *exc_info; PyObject *dict; /* Stores per-thread state */ int gilstate_counter; PyObject *async_exc; /* Asynchronous exception to raise */ unsigned long thread_id; /* Thread id where this tstate was created */ static bool IsFor(int majorVersion, int minorVersion) { return majorVersion == 3 && minorVersion == 10; } static bool IsFor(PythonVersion version) { return version == PythonVersion_310; } }; // i.e.: https://github.com/python/cpython/blob/3.11/Include/cpython/pystate.h class PyThreadState_311 : public PyThreadState { public: PyThreadState *prev; PyThreadState *next; PyInterpreterState *interp; int _initialized; int _static; int recursion_remaining; int recursion_limit; int recursion_headroom; /* Allow 50 more calls to handle any errors. */ /* 'tracing' keeps track of the execution depth when tracing/profiling. This is to prevent the actual trace/profile code from being recorded in the trace/profile. */ int tracing; int tracing_what; /* Pointer to current CFrame in the C stack frame of the currently, * or most recently, executing _PyEval_EvalFrameDefault. */ CFrame *cframe; Py_tracefunc c_profilefunc; Py_tracefunc c_tracefunc; PyObject *c_profileobj; PyObject *c_traceobj; PyObject *curexc_type; PyObject *curexc_value; PyObject *curexc_traceback; _PyErr_StackItem *exc_info; PyObject *dict; /* Stores per-thread state */ int gilstate_counter; PyObject *async_exc; /* Asynchronous exception to raise */ unsigned long thread_id; /* Thread id where this tstate was created */ static bool IsFor(int majorVersion, int minorVersion) { return majorVersion == 3 && minorVersion == 11; } static bool IsFor(PythonVersion version) { return version == PythonVersion_311; } }; class PyIntObject : public PyObject { public: long ob_ival; }; class Py3kLongObject : public PyVarObject { public: DWORD ob_digit[1]; }; class PyOldStyleClassObject : public PyObject { public: PyObject *cl_bases; /* A tuple of class objects */ PyObject *cl_dict; /* A dictionary */ PyObject *cl_name; /* A string */ /* The following three are functions or nullptr */ PyObject *cl_getattr; PyObject *cl_setattr; PyObject *cl_delattr; }; class PyInstanceObject : public PyObject { public: PyOldStyleClassObject *in_class; /* The class object */ PyObject *in_dict; /* A dictionary */ PyObject *in_weakreflist; /* List of weak references */ }; #endif
21,631
C
29.683688
100
0.662706
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/common/py_version.hpp
#ifndef __PY_VERSION_HPP__ #define __PY_VERSION_HPP__ #include <cstring> enum PythonVersion { PythonVersion_Unknown, PythonVersion_25 = 0x0205, PythonVersion_26 = 0x0206, PythonVersion_27 = 0x0207, PythonVersion_30 = 0x0300, PythonVersion_31 = 0x0301, PythonVersion_32 = 0x0302, PythonVersion_33 = 0x0303, PythonVersion_34 = 0x0304, PythonVersion_35 = 0x0305, PythonVersion_36 = 0x0306, PythonVersion_37 = 0x0307, PythonVersion_38 = 0x0308, PythonVersion_39 = 0x0309, PythonVersion_310 = 0x030A, PythonVersion_311 = 0x030B }; #ifdef _WIN32 typedef const char* (GetVersionFunc)(); static PythonVersion GetPythonVersion(HMODULE hMod) { auto versionFunc = reinterpret_cast<GetVersionFunc*>(GetProcAddress(hMod, "Py_GetVersion")); if (versionFunc == nullptr) { return PythonVersion_Unknown; } const char* version = versionFunc(); #else // LINUX ----------------------------------------------------------------- typedef const char* (*GetVersionFunc) (); static PythonVersion GetPythonVersion(void *module) { GetVersionFunc versionFunc; *(void**)(&versionFunc) = dlsym(module, "Py_GetVersion"); if(versionFunc == nullptr) { return PythonVersion_Unknown; } const char* version = versionFunc(); #endif //_WIN32 if (version != nullptr && strlen(version) >= 3 && version[1] == '.') { if (version[0] == '2') { switch (version[2]) { case '5': return PythonVersion_25; case '6': return PythonVersion_26; case '7': return PythonVersion_27; } } else if (version[0] == '3') { switch (version[2]) { case '0': return PythonVersion_30; case '1': if(strlen(version) >= 4){ if(version[3] == '0'){ return PythonVersion_310; } if(version[3] == '1'){ return PythonVersion_311; } } return PythonVersion_Unknown; // we don't care about 3.1 anymore... case '2': return PythonVersion_32; case '3': return PythonVersion_33; case '4': return PythonVersion_34; case '5': return PythonVersion_35; case '6': return PythonVersion_36; case '7': return PythonVersion_37; case '8': return PythonVersion_38; case '9': return PythonVersion_39; } } } return PythonVersion_Unknown; } #endif
2,617
C++
28.088889
96
0.549866
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/common/py_custom_pyeval_settrace_common.hpp
#ifndef _PY_CUSTOM_PYEVAL_SETTRACE_COMMON_HPP_ #define _PY_CUSTOM_PYEVAL_SETTRACE_COMMON_HPP_ #include "python.h" #include "py_utils.hpp" struct InternalInitializeCustomPyEvalSetTrace { PyObject* pyNone; PyTuple_New* pyTuple_New; _PyObject_FastCallDict* pyObject_FastCallDict; PyEval_CallObjectWithKeywords* pyEval_CallObjectWithKeywords; PyUnicode_InternFromString* pyUnicode_InternFromString; // Note: in Py2 will be PyString_InternFromString. PyTraceBack_Here* pyTraceBack_Here; PyEval_SetTrace* pyEval_SetTrace; bool isDebug; PyUnicode_AsUTF8* pyUnicode_AsUTF8; PyObject_Repr* pyObject_Repr; }; /** * Helper information to access CPython internals. */ static InternalInitializeCustomPyEvalSetTrace *internalInitializeCustomPyEvalSetTrace = NULL; /* * Cached interned string objects used for calling the profile and * trace functions. Initialized by InternalTraceInit(). */ static PyObject *InternalWhatstrings_37[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}; static int InternalIsTraceInitialized() { return internalInitializeCustomPyEvalSetTrace != NULL; } static int InternalTraceInit(InternalInitializeCustomPyEvalSetTrace *p_internalInitializeSettrace_37) { internalInitializeCustomPyEvalSetTrace = p_internalInitializeSettrace_37; static const char * const whatnames[8] = { "call", "exception", "line", "return", "c_call", "c_exception", "c_return", "opcode" }; PyObject *name; int i; for (i = 0; i < 8; ++i) { if (InternalWhatstrings_37[i] == NULL) { name = internalInitializeCustomPyEvalSetTrace->pyUnicode_InternFromString(whatnames[i]); if (name == NULL) return -1; InternalWhatstrings_37[i] = name; } } return 0; } #endif //_PY_CUSTOM_PYEVAL_SETTRACE_COMMON_HPP_
1,870
C++
29.177419
111
0.707487
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/common/py_settrace.hpp
#ifndef _PY_SETTRACE_HPP_ #define _PY_SETTRACE_HPP_ #include "ref_utils.hpp" #include "py_utils.hpp" #include "python.h" #include "py_custom_pyeval_settrace.hpp" #include <unordered_set> #ifdef _WIN32 typedef HMODULE MODULE_TYPE; #else // LINUX ----------------------------------------------------------------- typedef void* MODULE_TYPE; typedef ssize_t SSIZE_T; typedef unsigned int DWORD; #endif DWORD GetPythonThreadId(PythonVersion version, PyThreadState* curThread) { DWORD threadId = 0; if (PyThreadState_25_27::IsFor(version)) { threadId = (DWORD)((PyThreadState_25_27*)curThread)->thread_id; } else if (PyThreadState_30_33::IsFor(version)) { threadId = (DWORD)((PyThreadState_30_33*)curThread)->thread_id; } else if (PyThreadState_34_36::IsFor(version)) { threadId = (DWORD)((PyThreadState_34_36*)curThread)->thread_id; } else if (PyThreadState_37_38::IsFor(version)) { threadId = (DWORD)((PyThreadState_37_38*)curThread)->thread_id; } else if (PyThreadState_39::IsFor(version)) { threadId = (DWORD)((PyThreadState_39*)curThread)->thread_id; } else if (PyThreadState_310::IsFor(version)) { threadId = (DWORD)((PyThreadState_310*)curThread)->thread_id; } else if (PyThreadState_311::IsFor(version)) { threadId = (DWORD)((PyThreadState_311*)curThread)->thread_id; } return threadId; } /** * This function may be called to set a tracing function to existing python threads. */ int InternalSetSysTraceFunc( MODULE_TYPE module, bool isDebug, bool showDebugInfo, PyObjectHolder* traceFunc, PyObjectHolder* setTraceFunc, unsigned int threadId, PyObjectHolder* pyNone) { if(showDebugInfo){ PRINT("InternalSetSysTraceFunc started."); } DEFINE_PROC(isInit, Py_IsInitialized*, "Py_IsInitialized", 100); if (!isInit()) { PRINT("Py_IsInitialized returned false."); return 110; } auto version = GetPythonVersion(module); // found initialized Python runtime, gather and check the APIs we need. DEFINE_PROC(interpHead, PyInterpreterState_Head*, "PyInterpreterState_Head", 120); DEFINE_PROC(gilEnsure, PyGILState_Ensure*, "PyGILState_Ensure", 130); DEFINE_PROC(gilRelease, PyGILState_Release*, "PyGILState_Release", 140); DEFINE_PROC(threadHead, PyInterpreterState_ThreadHead*, "PyInterpreterState_ThreadHead", 150); DEFINE_PROC(threadNext, PyThreadState_Next*, "PyThreadState_Next", 160); DEFINE_PROC(threadSwap, PyThreadState_Swap*, "PyThreadState_Swap", 170); DEFINE_PROC(call, PyObject_CallFunctionObjArgs*, "PyObject_CallFunctionObjArgs", 180); PyInt_FromLong* intFromLong; if (version >= PythonVersion_30) { DEFINE_PROC(intFromLongPy3, PyInt_FromLong*, "PyLong_FromLong", 190); intFromLong = intFromLongPy3; } else { DEFINE_PROC(intFromLongPy2, PyInt_FromLong*, "PyInt_FromLong", 200); intFromLong = intFromLongPy2; } DEFINE_PROC(pyGetAttr, PyObject_GetAttrString*, "PyObject_GetAttrString", 250); DEFINE_PROC(pyHasAttr, PyObject_HasAttrString*, "PyObject_HasAttrString", 260); DEFINE_PROC_NO_CHECK(PyCFrame_Type, PyTypeObject*, "PyCFrame_Type", 300); // optional DEFINE_PROC_NO_CHECK(curPythonThread, PyThreadState**, "_PyThreadState_Current", 310); // optional DEFINE_PROC_NO_CHECK(getPythonThread, _PyThreadState_UncheckedGet*, "_PyThreadState_UncheckedGet", 320); // optional if (curPythonThread == nullptr && getPythonThread == nullptr) { // we're missing some APIs, we cannot attach. PRINT("Error, missing Python threading API!!"); return 330; } auto head = interpHead(); if (head == nullptr) { // this interpreter is loaded but not initialized. PRINT("Interpreter not initialized!"); return 340; } GilHolder gilLock(gilEnsure, gilRelease); // acquire and hold the GIL until done... int retVal = 0; // find what index is holding onto the thread state... auto curPyThread = getPythonThread ? getPythonThread() : *curPythonThread; if(curPyThread == nullptr){ PRINT("Getting the current python thread returned nullptr."); return 345; } // We do what PyEval_SetTrace does, but for any target thread. PyUnicode_InternFromString* pyUnicode_InternFromString; if (version >= PythonVersion_30) { DEFINE_PROC(unicodeFromString, PyUnicode_InternFromString*, "PyUnicode_InternFromString", 520); pyUnicode_InternFromString = unicodeFromString; } else { DEFINE_PROC(stringFromString, PyUnicode_InternFromString*, "PyString_InternFromString", 525); pyUnicode_InternFromString = stringFromString; } DEFINE_PROC_NO_CHECK(pyObject_FastCallDict, _PyObject_FastCallDict*, "_PyObject_FastCallDict", 530); DEFINE_PROC(pyTuple_New, PyTuple_New*, "PyTuple_New", 531); DEFINE_PROC(pyEval_CallObjectWithKeywords, PyEval_CallObjectWithKeywords*, "PyEval_CallObjectWithKeywords", 532); if(pyObject_FastCallDict == nullptr) { DEFINE_PROC_NO_CHECK(pyObject_FastCallDict, _PyObject_FastCallDict*, "PyObject_VectorcallDict", 533); } if(pyObject_FastCallDict == nullptr) { // we have to use PyObject_FastCallDictCustom for older versions of CPython (pre 3.7). pyObject_FastCallDict = reinterpret_cast<_PyObject_FastCallDict*>(&PyObject_FastCallDictCustom); } DEFINE_PROC(pyTraceBack_Here, PyTraceBack_Here*, "PyTraceBack_Here", 540); DEFINE_PROC(pyEval_SetTrace, PyEval_SetTrace*, "PyEval_SetTrace", 550); // These are defined mostly for printing info while debugging, so, if they're not there, don't bother reporting. DEFINE_PROC_NO_CHECK(pyObject_Repr, PyObject_Repr*, "PyObject_Repr", 551); DEFINE_PROC_NO_CHECK(pyUnicode_AsUTF8, PyUnicode_AsUTF8*, "PyUnicode_AsUTF8", 552); bool found = false; for (PyThreadState* curThread = threadHead(head); curThread != nullptr; curThread = threadNext(curThread)) { if (GetPythonThreadId(version, curThread) != threadId) { continue; } found = true; if(showDebugInfo){ printf("setting trace for thread: %d\n", threadId); } if(!InternalIsTraceInitialized()) { InternalInitializeCustomPyEvalSetTrace *internalInitializeCustomPyEvalSetTrace = new InternalInitializeCustomPyEvalSetTrace(); IncRef(pyNone->ToPython()); internalInitializeCustomPyEvalSetTrace->pyNone = pyNone->ToPython(); internalInitializeCustomPyEvalSetTrace->pyUnicode_InternFromString = pyUnicode_InternFromString; internalInitializeCustomPyEvalSetTrace->pyObject_FastCallDict = pyObject_FastCallDict; internalInitializeCustomPyEvalSetTrace->isDebug = isDebug; internalInitializeCustomPyEvalSetTrace->pyTraceBack_Here = pyTraceBack_Here; internalInitializeCustomPyEvalSetTrace->pyEval_SetTrace = pyEval_SetTrace; internalInitializeCustomPyEvalSetTrace->pyTuple_New = pyTuple_New; internalInitializeCustomPyEvalSetTrace->pyEval_CallObjectWithKeywords = pyEval_CallObjectWithKeywords; internalInitializeCustomPyEvalSetTrace->pyObject_Repr = pyObject_Repr; internalInitializeCustomPyEvalSetTrace->pyUnicode_AsUTF8 = pyUnicode_AsUTF8; InternalTraceInit(internalInitializeCustomPyEvalSetTrace); } InternalPySetTrace(curThread, traceFunc, isDebug, version); break; } if(!found) { retVal = 501; } return retVal; } #endif // _PY_SETTRACE_HPP_
7,763
C++
39.020618
138
0.680149
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/common/py_utils.hpp
#ifndef _PY_UTILS_HPP_ #define _PY_UTILS_HPP_ typedef int (Py_IsInitialized)(); typedef PyInterpreterState* (PyInterpreterState_Head)(); typedef enum { PyGILState_LOCKED, PyGILState_UNLOCKED } PyGILState_STATE; typedef PyGILState_STATE(PyGILState_Ensure)(); typedef void (PyGILState_Release)(PyGILState_STATE); typedef int (PyRun_SimpleString)(const char *command); typedef PyThreadState* (PyInterpreterState_ThreadHead)(PyInterpreterState* interp); typedef PyThreadState* (PyThreadState_Next)(PyThreadState *tstate); typedef PyThreadState* (PyThreadState_Swap)(PyThreadState *tstate); typedef PyThreadState* (_PyThreadState_UncheckedGet)(); typedef PyObject* (PyObject_CallFunctionObjArgs)(PyObject *callable, ...); // call w/ varargs, last arg should be nullptr typedef PyObject* (PyInt_FromLong)(long); typedef PyObject* (PyErr_Occurred)(); typedef void (PyErr_Fetch)(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback); typedef void (PyErr_Restore)(PyObject *type, PyObject *value, PyObject *traceback); typedef PyObject* (PyImport_ImportModule) (const char *name); typedef PyObject* (PyImport_ImportModuleNoBlock) (const char *name); typedef PyObject* (PyObject_GetAttrString)(PyObject *o, const char *attr_name); typedef PyObject* (PyObject_HasAttrString)(PyObject *o, const char *attr_name); typedef void* (PyThread_get_key_value)(int); typedef int (PyThread_set_key_value)(int, void*); typedef void (PyThread_delete_key_value)(int); typedef int (PyObject_Not) (PyObject *o); typedef PyObject* (PyDict_New)(); typedef PyObject* (PyUnicode_InternFromString)(const char *u); typedef PyObject * (_PyObject_FastCallDict)( PyObject *callable, PyObject *const *args, Py_ssize_t nargs, PyObject *kwargs); typedef int (PyTraceBack_Here)(PyFrameObject *frame); typedef PyObject* PyTuple_New(Py_ssize_t len); typedef PyObject* PyEval_CallObjectWithKeywords(PyObject *callable, PyObject *args, PyObject *kwargs); typedef void (PyEval_SetTrace)(Py_tracefunc, PyObject *); typedef int (*Py_tracefunc)(PyObject *, PyFrameObject *frame, int, PyObject *); typedef int (_PyEval_SetTrace)(PyThreadState *tstate, Py_tracefunc func, PyObject *arg); typedef PyObject* PyObject_Repr(PyObject *); typedef const char* PyUnicode_AsUTF8(PyObject *unicode); // holder to ensure we release the GIL even in error conditions class GilHolder { PyGILState_STATE _gilState; PyGILState_Release* _release; public: GilHolder(PyGILState_Ensure* acquire, PyGILState_Release* release) { _gilState = acquire(); _release = release; } ~GilHolder() { _release(_gilState); } }; #ifdef _WIN32 #define PRINT(msg) {std::cout << msg << std::endl << std::flush;} #define DEFINE_PROC_NO_CHECK(func, funcType, funcNameStr, errorCode) \ funcType func=reinterpret_cast<funcType>(GetProcAddress(module, funcNameStr)); #define DEFINE_PROC(func, funcType, funcNameStr, errorCode) \ DEFINE_PROC_NO_CHECK(func, funcType, funcNameStr, errorCode); \ if(func == nullptr){std::cout << funcNameStr << " not found." << std::endl << std::flush; return errorCode;}; #else // LINUX ----------------------------------------------------------------- #define PRINT(msg) {printf(msg); printf("\n");} #define CHECK_NULL(ptr, msg, errorCode) if(ptr == nullptr){printf(msg); return errorCode;} #define DEFINE_PROC_NO_CHECK(func, funcType, funcNameStr, errorCode) \ funcType func; *(void**)(&func) = dlsym(module, funcNameStr); #define DEFINE_PROC(func, funcType, funcNameStr, errorCode) \ DEFINE_PROC_NO_CHECK(func, funcType, funcNameStr, errorCode); \ if(func == nullptr){printf(funcNameStr); printf(" not found.\n"); return errorCode;}; #endif //_WIN32 #endif //_PY_UTILS_HPP_
3,811
C++
44.380952
129
0.706639
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_attach_to_process/common/ref_utils.hpp
#ifndef _REF_UTILS_HPP_ #define _REF_UTILS_HPP_ PyObject* GetPyObjectPointerNoDebugInfo(bool isDebug, PyObject* object) { if (object != nullptr && isDebug) { // debug builds have 2 extra pointers at the front that we don't care about return (PyObject*)((size_t*)object + 2); } return object; } void DecRef(PyObject* object, bool isDebug) { auto noDebug = GetPyObjectPointerNoDebugInfo(isDebug, object); if (noDebug != nullptr && --noDebug->ob_refcnt == 0) { ((PyTypeObject*)GetPyObjectPointerNoDebugInfo(isDebug, noDebug->ob_type))->tp_dealloc(object); } } void IncRef(PyObject* object) { object->ob_refcnt++; } class PyObjectHolder { private: PyObject* _object; public: bool _isDebug; PyObjectHolder(bool isDebug) { _object = nullptr; _isDebug = isDebug; } PyObjectHolder(bool isDebug, PyObject *object) { _object = object; _isDebug = isDebug; }; PyObjectHolder(bool isDebug, PyObject *object, bool addRef) { _object = object; _isDebug = isDebug; if (_object != nullptr && addRef) { GetPyObjectPointerNoDebugInfo(_isDebug, _object)->ob_refcnt++; } }; PyObject* ToPython() { return _object; } ~PyObjectHolder() { DecRef(_object, _isDebug); } PyObject* operator* () { return GetPyObjectPointerNoDebugInfo(_isDebug, _object); } }; #endif //_REF_UTILS_HPP_
1,475
C++
22.428571
102
0.616271
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/config/extension.toml
[package] version = "0.2.0" title = "A debugger for Python" description="Uses debugpy which implements the Debug Adapter Protocol" authors = ["NVIDIA"] repository = "" category = "Internal" keywords = ["kit"] readme = "docs/README.md" changelog="docs/CHANGELOG.md" [dependencies] "omni.kit.pip_archive" = {} [[python.module]] name = "omni.kit.debug.python" [settings.exts."omni.kit.debug.python"] # Host and port for listen to debugger for host = "127.0.0.1" port = 3000 # Enable debugpy builtin logging, logs go into ${logs} folder debugpyLogging = false # Block until client (debugger) connected waitForClient = false # break immediately (also waits for client) break = false [[test]] pyCoverageEnabled = false waiver = "Developer tool. Brings 3rd party (debugpy) to another 3rd party (VSCode), doesn't have much to test and building an integration test is not worth it."
882
TOML
24.228571
160
0.732426
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.kit.debug.python/docs/CHANGELOG.md
# CHANGELOG ## [0.2.0] - 2022-09-28 - Prebundle debugpy ## [0.1.0] - 2020-02-22 - Initial commit
101
Markdown
9.199999
23
0.594059
omniverse-code/kit/exts/omni.kit.debug.python/docs/README.md
# Debug Utils ## omni.kit.debug.python Python debugger support.
65
Markdown
12.199998
24
0.753846
omniverse-code/kit/exts/omni.activity.core/config/extension.toml
[package] title = "Omni Activity Core" category = "Telemetry" version = "1.0.1" description = "The activity and the progress processor" authors = ["NVIDIA"] keywords = ["activity"] [[python.module]] name = "omni.activity.core" [[native.plugin]] path = "bin/*.plugin"
269
TOML
18.285713
55
0.69145
omniverse-code/kit/exts/omni.activity.core/omni/activity/core/_activity.pyi
from __future__ import annotations import omni.activity.core._activity import typing import omni.core._core __all__ = [ "EventType", "IActivity", "IEvent", "INode", "began", "disable", "enable", "ended", "get_instance", "progress", "updated" ] class EventType(): """ Members: BEGAN : /< The activity is started UPDATED : /< The activity is changed ENDED : /< The activity is finished """ def __eq__(self, other: object) -> bool: ... def __getstate__(self) -> int: ... def __hash__(self) -> int: ... def __index__(self) -> int: ... def __init__(self, value: int) -> None: ... def __int__(self) -> int: ... def __ne__(self, other: object) -> bool: ... def __repr__(self) -> str: ... def __setstate__(self, state: int) -> None: ... @property def name(self) -> str: """ :type: str """ @property def value(self) -> int: """ :type: int """ BEGAN: omni.activity.core._activity.EventType # value = <EventType.BEGAN: 0> ENDED: omni.activity.core._activity.EventType # value = <EventType.ENDED: 2> UPDATED: omni.activity.core._activity.EventType # value = <EventType.UPDATED: 1> __members__: dict # value = {'BEGAN': <EventType.BEGAN: 0>, 'UPDATED': <EventType.UPDATED: 1>, 'ENDED': <EventType.ENDED: 2>} pass class IActivity(_IActivity, omni.core._core.IObject): """ @brief The activity and the progress processor. """ @typing.overload def __init__(self, arg0: omni.core._core.IObject) -> None: ... @typing.overload def __init__(self) -> None: ... def create_callback_to_pop(self, fn: typing.Callable[[INode], None]) -> int: """ Subscribes to event dispatching on the stream. See :class:`.Subscription` for more information on subscribing mechanism. Args: fn: The callback to be called on event dispatch. Returns: The subscription holder. """ def pump(self) -> None: """ @brief Process the callback. Should be called once per frame. """ def push_event_dict(self, node_path: str, type: EventType, event_payload: capsule) -> bool: """ @brief Push event to the system. TODO: eventPayload is a placeholder TODO: eventPayload should be carb::dictionary """ def remove_callback(self, id: int) -> None: """ @brief Remove the callback. """ @property def current_timestamp(self) -> int: """ :type: int """ @property def enabled(self) -> None: """ :type: None """ @enabled.setter def enabled(self, arg1: bool) -> None: pass pass class IEvent(_IEvent, omni.core._core.IObject): """ @brief The event contains custom data. It can be speed, progress, etc. """ @typing.overload def __init__(self, arg0: omni.core._core.IObject) -> None: ... @typing.overload def __init__(self) -> None: ... @property def event_timestamp(self) -> int: """ :type: int """ @property def event_type(self) -> EventType: """ :type: EventType """ @property def payload(self) -> carb.dictionary._dictionary.Item: """ :type: carb.dictionary._dictionary.Item """ pass class INode(_INode, omni.core._core.IObject): """ @brief Node can contain other nodes and events. """ @typing.overload def __init__(self, arg0: omni.core._core.IObject) -> None: ... @typing.overload def __init__(self) -> None: ... def get_child(self, n: int) -> INode: """ @brief Get the child node """ def get_event(self, n: int) -> IEvent: """ @brief Get the activity """ @property def child_count(self) -> int: """ :type: int """ @property def event_count(self) -> int: """ :type: int """ @property def name(self) -> str: """ :type: str """ pass class _IActivity(omni.core._core.IObject): pass class _IEvent(omni.core._core.IObject): pass class _INode(omni.core._core.IObject): pass def began(arg0: str, **kwargs) -> None: pass def disable() -> None: pass def enable() -> None: pass def ended(arg0: str, **kwargs) -> None: pass def get_instance() -> IActivity: pass def progress(arg0: str, arg1: float, **kwargs) -> None: pass def updated(arg0: str, **kwargs) -> None: pass
4,644
unknown
24.805555
129
0.543712
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/config/extension.toml
[package] version = "0.1.0" title = "Kit Compatibility Checker" category = "Internal" [dependencies] "omni.appwindow" = { } "omni.gpu_foundation" = { } "omni.kit.notification_manager" = { optional=true } "omni.kit.window.viewport" = { optional=true } "omni.kit.renderer.core" = { optional=true } [[python.module]] name = "omni.kit.compatibility_checker" [settings] [settings.exts."omni.kit.compatibility_checker"] # supportedGpus = [ # "*GeForce RTX ????*", # "*Quadro RTX ????*", # "*RTX ?????*", # "*TITAN RTX*" # ] "windows-x86_64".minOsVersion = 0 #19042 # "windows-x86_64".driverBlacklistRanges = [ # ["0.0", "456.39", "The minimum RTX requirement"], # ["460.0", "461.92", "Driver crashes or image artifacts"], # ] "linux-x86_64".minOsVersion = 0 # "linux-x86_64".driverBlacklistRanges = [ # ["0.0", "450.57", "The minimum RTX requirement"], # ["455.23", "455.24", "NVIDIA OptiX bug"], # ["460.0", "460.62", "Driver crashes or image artifacts"], # ] "linux-aarch64".minOsVersion = 0 # "linux-aarch64".driverBlacklistRanges = [ # ["0.0", "450.57", "The minimum RTX requirement"] # ] [[test]] args = [] dependencies = ["omni.kit.renderer.core"]
1,194
TOML
25.555555
63
0.623953
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/config/extension.toml
[package] version = "1.0.3" authors = ["NVIDIA"] title = "Omni.UI Style Documentation" description="The interactive documentation for omni.ui style" readme = "docs/README.md" repository = "" category = "Documentation" keywords = ["ui", "style", "docs", "documentation"] changelog="docs/CHANGELOG.md" preview_image = "data/preview.png" icon = "data/icon.png" [dependencies] "omni.ui" = {} "omni.kit.documentation.builder" = {} [[python.module]] name = "omni.kit.documentation.ui.style" [documentation] pages = [ "docs/overview.md", "docs/styling.md", "docs/shades.md", "docs/fonts.md", "docs/units.md", "docs/shapes.md", "docs/line.md", "docs/buttons.md", "docs/sliders.md", "docs/widgets.md", "docs/containers.md", "docs/window.md", "docs/CHANGELOG.md", ] args = [] menu = "Help/API/Omni.UI Style" title = "Omni.UI Style Documentation"
892
TOML
21.324999
61
0.653587
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.documentation.ui.style/docs/styling.md
# The Style Sheet Syntax omni.ui Style Sheet rules are almost identical to those of HTML CSS. It applies to the style of all omni ui elements. Style sheets consist of a sequence of style rules. A style rule is made up of a selector and a declaration. The selector specifies which widgets are affected by the rule. The declaration specifies which properties should be set on the widget. For example: ```execute 200 ## Double comment means hide from shippet from omni.ui import color as cl ## with ui.VStack(width=0, style={"Button": {"background_color": cl("#097eff")}}): ui.Button("Style Example") ``` In the above style rule, Button is the selector, and {"background_color": cl("#097eff")} is the declaration. The rule specifies that Button should use blue as its background color. ## Selector There are three types of selectors, type Selector, name Selector and state Selector They are structured as: Type Selector :: Name Selector : State Selector e.g.,Button::okButton:hovered ### Type Selector where `Button` is the type selector, which matches the ui.Button's type. ### Name Selector `okButton` is the type selector, which selects all Button instances whose object name is okButton. It separates from the type selector with `::`. ### State Selector `hovered` is the state selector, which by itself matches all Button instances whose state is hovered. It separates from the other selectors with `:`. When type, name and state selector are used together, it defines the style of all Button typed instances named as `okButton` and in hovered, while `Button:hovered` defines the style of all Button typed instances which are in hovered states. These are the states recognized by omni.ui: * hovered : the mouse in the widget area * pressed : the mouse is pressing in the widget area * selected : the widget is selected * disabled : the widget is disabled * checked : the widget is checked * drop : the rectangle is accepting a drop. For example, style = {"Rectangle:drop" : {"background_color": cl.blue}} meaning if the drop is acceptable, the rectangle is blue. ## Style Override ### Omit the selector It's possible to omit the selector and override the property in all the widget types. In this example, the style is set to VStack. The style will be propagated to all the widgets in VStack including VStack itself. Since only `background_color` is in the style, only the widgets which have `background_color` as the style will have the background color set. For VStack and Label which don't have `background_color`, the style is ignored. Button and FloatField get the blue background color. ```execute 200 from omni.ui import color as cl with ui.VStack(width=400, style={"background_color": cl("#097eff")}, spacing=5): ui.Button("One") ui.Button("Two") ui.FloatField() ui.Label("Label doesn't have background_color style") ``` ### Style overridden with name and state selector In this example, we set the "Button" style for all the buttons, then override different buttons with name selector style, e.g. "Button::one" and "Button::two". Furthermore, the we also set different style for Button::one when pressed or hovered, e.g. "Button::one:hovered" and "Button::one:pressed", which will override "Button::one" style when button is pressed or hovered. ```execute 200 from omni.ui import color as cl style1 = { "Button": {"border_width": 0.5, "border_radius": 0.0, "margin": 5.0, "padding": 5.0}, "Button::one": { "background_color": cl("#097eff"), "background_gradient_color": cl("#6db2fa"), "border_color": cl("#1d76fd"), }, "Button.Label::one": {"color": cl.white}, "Button::one:hovered": {"background_color": cl("#006eff"), "background_gradient_color": cl("#5aaeff")}, "Button::one:pressed": {"background_color": cl("#6db2fa"), "background_gradient_color": cl("#097eff")}, "Button::two": {"background_color": cl.white, "border_color": cl("#B1B1B1")}, "Button.Label::two": {"color": cl("#272727")}, "Button::three:hovered": { "background_color": cl("#006eff"), "background_gradient_color": cl("#5aaeff"), "border_color": cl("#1d76fd"), }, "Button::four:pressed": { "background_color": cl("#6db2fa"), "background_gradient_color": cl("#097eff"), "border_color": cl("#1d76fd"), }, } with ui.HStack(style=style1): ui.Button("One", name="one") ui.Button("Two", name="two") ui.Button("Three", name="three") ui.Button("Four", name="four") ui.Button("Five", name="five") ``` ### Style override to different levels of the widgets It's possible to assign any style override to any level of the widgets. It can be assigned to both parents and children at the same time. In this example, we have style_system which will be propagated to all buttons, but buttons with its own style will override the style_system. ```execute 200 from omni.ui import color as cl style_system = { "Button": { "background_color": cl("#E1E1E1"), "border_color": cl("#ADADAD"), "border_width": 0.5, "border_radius": 3.0, "margin": 5.0, "padding": 5.0, }, "Button.Label": { "color": cl.black, }, "Button:hovered": { "background_color": cl("#e5f1fb"), "border_color": cl("#0078d7"), }, "Button:pressed": { "background_color": cl("#cce4f7"), "border_color": cl("#005499"), "border_width": 1.0 }, } with ui.HStack(style=style_system): ui.Button("One") ui.Button("Two", style={"color": cl("#AAAAAA")}) ui.Button("Three", style={"background_color": cl("#097eff"), "background_gradient_color": cl("#6db2fa")}) ui.Button( "Four", style={":hovered": {"background_color": cl("#006eff"), "background_gradient_color": cl("#5aaeff")}} ) ui.Button( "Five", style={"Button:pressed": {"background_color": cl("#6db2fa"), "background_gradient_color": cl("#097eff")}}, ) ``` ### Customize the selector type using style_type_name_override What if the user has a customized widget which is not a standard omni.ui one. How to define that Type Selector? In this case, We can use `style_type_name_override` to override the type name. `name` attribute is the Name Selector and State Selector can be added as usual. Another use case is when we have a giant list of the same typed widgets, for example `Button`, but some of the Buttons are in the main window, and some of the Buttons are in the pop-up window, which we want to differentiate for easy look-up. Instead of calling all of them the same Type Selector as `Button` and only have different Name Selectors, we can override the type name for the main window buttons as `WindowButton` and the pop-up window buttons as `PopupButton`. This groups the style-sheet into categories and makes the change of the look or debug much easier. Here is an example where we use `style_type_name_override` to override the style type name. ```execute 200 from omni.ui import color as cl style={ "WindowButton::one": {"background_color": cl("#006eff")}, "WindowButton::one:hovered": {"background_color": cl("#006eff"), "background_gradient_color": cl("#FFAEFF")}, "PopupButton::two": {"background_color": cl("#6db2fa")}, "PopupButton::two:hovered": {"background_color": cl("#6db2fa"), "background_gradient_color": cl("#097eff")}, } with ui.HStack(width=400, style=style, spacing=5): ui.Button("Open", style_type_name_override="WindowButton", name="one") ui.Button("Save", style_type_name_override="PopupButton", name="two") ``` ### Default style override From the above examples, we know that if we want to propagate the style to all children, we just need to set the style to the parent widget, but this rule doesn't apply to windows. The style set to the window will not propagate to its widgets. If we want to propagate the style to ui.Window and their widgets, we should set the default style with `ui.style.default`. ```python from omni.ui import color as cl ui.style.default = { "background_color": cl.blue, "border_radius": 10, "border_width": 5, "border_color": cl.red, } ``` ## Debug Color All shapes or widgets can be styled to use a debug color that enables you to visualize their frame. It is very useful when debugging complicated ui layout with overlaps. Here we use red as the debug_color to indicate the label widget: ```execute 200 from omni.ui import color as cl style = {"background_color": cl("#DDDD00"), "color": cl.white, "debug_color":cl("#FF000055")} ui.Label("Label with Debug", width=200, style=style) ``` If several widgets are adjacent, we can use the `debug_color` in the `hovered` state to differentiate the widget with others. ```execute 200 from omni.ui import color as cl style = { "Label": {"padding": 3, "background_color": cl("#DDDD00"),"color": cl.white}, "Label:hovered": {"debug_color": cl("#00FFFF55")},} with ui.HStack(width=500, style=style): ui.Label("Label 1", width=50) ui.Label("Label 2") ui.Label("Label 3", width=100, alignment=ui.Alignment.CENTER) ui.Spacer() ui.Label("Label 3", width=50) ``` ## Visibility This property holds whether the shape or widget is visible. Invisible shape or widget is not rendered, and it doesn't take part in the layout. The layout skips it. In the following example, click the button from one to five to hide itself. The `Visible all` button brings them all back. ```execute 200 def invisible(button): button.visible = False def visible(buttons): for button in buttons: button.visible = True buttons = [] with ui.HStack(): for n in ["One", "Two", "Three", "Four", "Five"]: button = ui.Button(n, width=0) button.set_clicked_fn(lambda b=button: invisible(b)) buttons.append(button) ui.Spacer() button = ui.Button("Visible all", width=0) button.set_clicked_fn(lambda b=buttons: visible(b)) ```
9,962
Markdown
43.878378
570
0.691929
omniverse-code/kit/exts/omni.kit.documentation.ui.style/docs/widgets.md
# Widgets ## Label Labels are used everywhere in omni.ui. They are text only objects. Here is a list of styles you can customize on Label: > color (color): the color of the text > font_size (float): the size of the text > margin (float): the distance between the label and the parent widget defined boundary > margin_width (float): the width distance between the label and the parent widget defined boundary > margin_height (float): the height distance between the label and the parent widget defined boundary > alignment (enum): defines how the label is positioned in the parent defined space. There are 9 alignments supported which are quite self-explanatory. * ui.Alignment.LEFT_CENTER * ui.Alignment.LEFT_TOP * ui.Alignment.LEFT_BOTTOM * ui.Alignment.RIGHT_CENTER * ui.Alignment.RIGHT_TOP * ui.Alignment.RIGHT_BOTTOM * ui.Alignment.CENTER * ui.Alignment.CENTER_TOP * ui.Alignment.CENTER_BOTTOM Here are a few examples of labels: ```execute 200 from omni.ui import color as cl ui.Label("this is a simple label", style={"color":cl.red, "margin": 5}) ``` ```execute 200 from omni.ui import color as cl ui.Label("label with alignment", style={"color":cl.green, "margin": 5}, alignment=ui.Alignment.CENTER) ``` Notice that alignment could be either a property or a style. ```execute 200 from omni.ui import color as cl label_style = { "Label": {"font_size": 20, "color": cl.blue, "alignment":ui.Alignment.RIGHT, "margin_height": 20} } ui.Label("Label with style", style=label_style) ``` When the text of the Label is too long, it can be elided by `...`: ```execute 200 from omni.ui import color as cl ui.Label( "Label can be elided: Lorem ipsum dolor " "sit amet, consectetur adipiscing elit, sed do " "eiusmod tempor incididunt ut labore et dolore " "magna aliqua. Ut enim ad minim veniam, quis " "nostrud exercitation ullamco laboris nisi ut " "aliquip ex ea commodo consequat. Duis aute irure " "dolor in reprehenderit in voluptate velit esse " "cillum dolore eu fugiat nulla pariatur. Excepteur " "sint occaecat cupidatat non proident, sunt in " "culpa qui officia deserunt mollit anim id est " "laborum.", style={"color":cl.white}, elided_text=True, ) ``` ## CheckBox A CheckBox is an option button that can be switched on (checked) or off (unchecked). Checkboxes are typically used to represent features in an application that can be enabled or disabled without affecting others. The checkbox is implemented using the model-delegate-view pattern. The model is the central component of this system. It is the application's dynamic data structure independent of the widget. It directly manages the data, logic and rules of the checkbox. If the model is not specified, the simple one is created automatically when the object is constructed. Here is a list of styles you can customize on Line: > color (color): the color of the tick > background_color (color): the background color of the check box > font_size: the size of the tick > border_radius (float): the radius of the corner angle if the user wants to round the check box. Default checkbox ```execute 200 with ui.HStack(width=0, spacing=5): ui.CheckBox().model.set_value(True) ui.CheckBox() ui.Label("Default") ``` Disabled checkbox: ```execute 200 with ui.HStack(width=0, spacing=5): ui.CheckBox(enabled=False).model.set_value(True) ui.CheckBox(enabled=False) ui.Label("Disabled") ``` In the following example, the models of two checkboxes are connected, and if one checkbox is changed, it makes another checkbox change as well. ```execute 200 from omni.ui import color as cl with ui.HStack(width=0, spacing=5): # Create two checkboxes style = {"CheckBox":{ "color": cl.white, "border_radius": 0, "background_color": cl("#ff5555"), "font_size": 30}} first = ui.CheckBox(style=style) second = ui.CheckBox(style=style) # Connect one to another first.model.add_value_changed_fn(lambda a, b=second: b.model.set_value(not a.get_value_as_bool())) second.model.add_value_changed_fn(lambda a, b=first: b.model.set_value(not a.get_value_as_bool())) # Set the first one to True first.model.set_value(True) ui.Label("One of two") ``` In the following example, that is a bit more complicated, only one checkbox can be enabled. ```execute 200 from omni.ui import color as cl style = {"CheckBox":{ "color": cl("#ff5555"), "border_radius": 5, "background_color": cl(0.35), "font_size": 20}} with ui.HStack(width=0, spacing=5): # Create two checkboxes first = ui.CheckBox(style=style) second = ui.CheckBox(style=style) third = ui.CheckBox(style=style) def like_radio(model, first, second): """Turn on the model and turn off two checkboxes""" if model.get_value_as_bool(): model.set_value(True) first.model.set_value(False) second.model.set_value(False) # Connect one to another first.model.add_value_changed_fn(lambda a, b=second, c=third: like_radio(a, b, c)) second.model.add_value_changed_fn(lambda a, b=first, c=third: like_radio(a, b, c)) third.model.add_value_changed_fn(lambda a, b=first, c=second: like_radio(a, b, c)) # Set the first one to True first.model.set_value(True) ui.Label("Almost like radio box") ``` ## ComboBox The ComboBox widget is a combination of a button and a drop-down list. A ComboBox is a selection widget that displays the current item and can pop up a list of selectable items. Here is a list of styles you can customize on ComboBox: > color (color): the color of the combo box text and the arrow of the drop-down button > background_color (color): the background color of the combo box > secondary_color (color): the color of the drop-down button's background > selected_color (color): the selected highlight color of option items > secondary_selected_color (color): the color of the option item text > font_size (float): the size of the text > border_radius (float): the border radius if the user wants to round the ComboBox > padding (float): the overall padding of the ComboBox. If padding is defined, padding_height and padding_width will have no effects. > padding_height (float): the width padding of the drop-down list > padding_width (float): the height padding of the drop-down list > secondary_padding (float): the height padding between the ComboBox and options Default ComboBox: ```execute 200 ui.ComboBox(1, "Option 1", "Option 2", "Option 3") ``` ComboBox with style ```execute 200 from omni.ui import color as cl style={"ComboBox":{ "color": cl.red, "background_color": cl(0.15), "secondary_color": cl("#1111aa"), "selected_color": cl.green, "secondary_selected_color": cl.white, "font_size": 15, "border_radius": 20, "padding_height": 2, "padding_width": 20, "secondary_padding": 30, }} with ui.VStack(): ui.ComboBox(1, "Option 1", "Option 2", "Option 3", style=style) ui.Spacer(height=20) ``` The following example demonstrates how to add items to the ComboBox. ```execute 200 editable_combo = ui.ComboBox() ui.Button( "Add item to combo", clicked_fn=lambda m=editable_combo.model: m.append_child_item( None, ui.SimpleStringModel("Hello World")), ) ``` The minimal model implementation to have more flexibility of the data. It requires holding the value models and reimplementing two methods: `get_item_children` and `get_item_value_model`. ```execute 200 class MinimalItem(ui.AbstractItem): def __init__(self, text): super().__init__() self.model = ui.SimpleStringModel(text) class MinimalModel(ui.AbstractItemModel): def __init__(self): super().__init__() self._current_index = ui.SimpleIntModel() self._current_index.add_value_changed_fn( lambda a: self._item_changed(None)) self._items = [ MinimalItem(text) for text in ["Option 1", "Option 2"] ] def get_item_children(self, item): return self._items def get_item_value_model(self, item, column_id): if item is None: return self._current_index return item.model self._minimal_model = MinimalModel() with ui.VStack(): ui.ComboBox(self._minimal_model, style={"font_size": 22}) ui.Spacer(height=10) ``` The example of communication between widgets. Type anything in the field and it will appear in the combo box. ```execute 200 editable_combo = None class StringModel(ui.SimpleStringModel): ''' String Model activated when editing is finished. Adds item to combo box. ''' def __init__(self): super().__init__("") def end_edit(self): combo_model = editable_combo.model # Get all the options ad list of strings all_options = [ combo_model.get_item_value_model(child).as_string for child in combo_model.get_item_children() ] # Get the current string of this model fieldString = self.as_string if fieldString: if fieldString in all_options: index = all_options.index(fieldString) else: # It's a new string in the combo box combo_model.append_child_item( None, ui.SimpleStringModel(fieldString) ) index = len(all_options) combo_model.get_item_value_model().set_value(index) self._field_model = StringModel() def combo_changed(combo_model, item): all_options = [ combo_model.get_item_value_model(child).as_string for child in combo_model.get_item_children() ] current_index = combo_model.get_item_value_model().as_int self._field_model.as_string = all_options[current_index] with ui.HStack(): ui.StringField(self._field_model) editable_combo = ui.ComboBox(width=0, arrow_only=True) editable_combo.model.add_item_changed_fn(combo_changed) ``` ## TreeView TreeView is a widget that presents a hierarchical view of information. Each item can have a number of subitems. An indentation often visualizes this in a list. An item can be expanded to reveal subitems, if any exist, and collapsed to hide subitems. TreeView can be used in file manager applications, where it allows the user to navigate the file system directories. They are also used to present hierarchical data, such as the scene object hierarchy. TreeView uses a model-delegate-view pattern to manage the relationship between data and the way it is presented. The separation of functionality gives developers greater flexibility to customize the presentation of items and provides a standard interface to allow a wide range of data sources to be used with other widgets. Here is a list of styles you can customize on TreeView: > background_color (color): the background color of the TreeView > background_selected_color (color): the hover color of the TreeView selected item. The actual selected color of the TreeView selected item should be defined by the "background_color" of "TreeView:selected" > secondary_color (color): the TreeView slider color Here is a list of styles you can customize on TreeView.Item: > margin (float): the margin between TreeView items. This will be overridden by the value of margin_width or margin_height > margin_width (float): the margin width between TreeView items > margin_height (float): the margin height between TreeView items > color (color): the text color of the TreeView items > font_size (float): the text size of the TreeView items The following example demonstrates how to make a single level tree appear like a simple list. ```execute 200 from omni.ui import color as cl style = {"TreeView": { "background_color": cl("#E0FFE0"), "background_selected_color": cl("#FF905C"), "secondary_color": cl("#00FF00"), }, "TreeView:selected": {"background_color": cl("#888888")}, "TreeView.Item": { "margin": 4, "margin_width": 20, "color": cl("#555555"), "font_size": 15, }, "TreeView.Item:selected": {"color": cl("#DD2825")}, } class CommandItem(ui.AbstractItem): """Single item of the model""" def __init__(self, text): super().__init__() self.name_model = ui.SimpleStringModel(text) class CommandModel(ui.AbstractItemModel): """ Represents the list of commands registered in Kit. It is used to make a single level tree appear like a simple list. """ def __init__(self): super().__init__() self._commands = [] try: import omni.kit.commands except ModuleNotFoundError: return omni.kit.commands.subscribe_on_change(self._commands_changed) self._commands_changed() def _commands_changed(self): """Called by subscribe_on_change""" self._commands = [] import omni.kit.commands for cmd_list in omni.kit.commands.get_commands().values(): for k in cmd_list.values(): self._commands.append(CommandItem(k.__name__)) self._item_changed(None) 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._commands def get_item_value_model_count(self, item): """The number of columns""" return 1 def get_item_value_model(self, item, column_id): """ Return value model. It's the object that tracks the specific value. In our case we use ui.SimpleStringModel. """ if item and isinstance(item, CommandItem): return item.name_model with ui.ScrollingFrame( height=400, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="TreeView", style=style ): self._command_model = CommandModel() tree_view = ui.TreeView(self._command_model, root_visible=False, header_visible=False) ``` The following example demonstrates reordering with drag and drop. You can drag one item of the TreeView and move to the position you want to insert the item to. ```execute 200 from omni.ui import color as cl class ListItem(ui.AbstractItem): """Single item of the model""" def __init__(self, text): super().__init__() self.name_model = ui.SimpleStringModel(text) def __repr__(self): return f'"{self.name_model.as_string}"' class ListModel(ui.AbstractItemModel): """ Represents the model for lists. It's very easy to initialize it with any string list: string_list = ["Hello", "World"] model = ListModel(*string_list) ui.TreeView(model) """ def __init__(self, *args): super().__init__() self._children = [ListItem(t) for t in args] 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._children def get_item_value_model_count(self, item): """The number of columns""" return 1 def get_item_value_model(self, item, column_id): """ Return value model. It's the object that tracks the specific value. In our case we use ui.SimpleStringModel. """ return item.name_model class ListModelWithReordering(ListModel): """ Represents the model for the list with the ability to reorder the list with drag and drop. """ def __init__(self, *args): super().__init__(*args) def get_drag_mime_data(self, item): """Returns Multipurpose Internet Mail Extensions (MIME) data for be able to drop this item somewhere""" # As we don't do Drag and Drop to the operating system, we return the string. return item.name_model.as_string def drop_accepted(self, target_item, source, drop_location=-1): """Reimplemented from AbstractItemModel. Called to highlight target when drag and drop.""" # If target_item is None, it's the drop to root. Since it's # list model, we support reorganization of root only and we # don't want to create a tree. return not target_item and drop_location >= 0 def drop(self, target_item, source, drop_location=-1): """Reimplemented from AbstractItemModel. Called when dropping something to the item.""" try: source_id = self._children.index(source) except ValueError: # Not in the list. This is the source from another model. return if source_id == drop_location: # Nothing to do return self._children.remove(source) if drop_location > len(self._children): # Drop it to the end self._children.append(source) else: if source_id < drop_location: # Because when we removed source, the array became shorter drop_location = drop_location - 1 self._children.insert(drop_location, source) self._item_changed(None) with ui.ScrollingFrame( height=150, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="TreeView", ): self._list_model = ListModelWithReordering("Simplest", "List", "Model", "With", "Reordering") tree_view = ui.TreeView( self._list_model, root_visible=False, header_visible=False, style={"TreeView.Item": {"margin": 4}}, drop_between_items=True, ) ``` The following example demonstrates the ability to edit TreeView items. ```execute 200 from omni.ui import color as cl class FloatModel(ui.AbstractValueModel): """An example of custom float model that can be used for formatted string output""" def __init__(self, value: float): super().__init__() self._value = value def get_value_as_float(self): """Reimplemented get float""" return self._value or 0.0 def get_value_as_string(self): """Reimplemented get string""" # This string goes to the field. if self._value is None: return "" # General format. This prints the number as a fixed-point # number, unless the number is too large, in which case it # switches to 'e' exponent notation. return "{0:g}".format(self._value) def set_value(self, value): """Reimplemented set""" try: value = float(value) except ValueError: value = None if value != self._value: # Tell the widget that the model is changed self._value = value self._value_changed() class NameValueItem(ui.AbstractItem): """Single item of the model""" def __init__(self, text, value): super().__init__() self.name_model = ui.SimpleStringModel(text) self.value_model = FloatModel(value) def __repr__(self): return f'"{self.name_model.as_string} {self.value_model.as_string}"' class NameValueModel(ui.AbstractItemModel): """ Represents the model for name-value tables. It's very easy to initialize it with any string-float list: my_list = ["Hello", 1.0, "World", 2.0] model = NameValueModel(*my_list) ui.TreeView(model) """ def __init__(self, *args): super().__init__() # ["Hello", 1.0, "World", 2.0"] -> [("Hello", 1.0), ("World", 2.0)] regrouped = zip(*(iter(args),) * 2) self._children = [NameValueItem(*t) for t in regrouped] 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._children def get_item_value_model_count(self, item): """The number of columns""" return 2 def get_item_value_model(self, item, column_id): """ Return value model. It's the object that tracks the specific value. In our case we use ui.SimpleStringModel for the first column and SimpleFloatModel for the second column. """ return item.value_model if column_id == 1 else item.name_model class EditableDelegate(ui.AbstractItemDelegate): """ Delegate is the representation layer. TreeView calls the methods of the delegate to create custom widgets for each item. """ def __init__(self): super().__init__() self.subscription = None def build_branch(self, model, item, column_id, level, expanded): """Create a branch widget that opens or closes subtree""" pass def build_widget(self, model, item, column_id, level, expanded): """Create a widget per column per item""" stack = ui.ZStack(height=20) with stack: value_model = model.get_item_value_model(item, column_id) label = ui.Label(value_model.as_string) if column_id == 1: field = ui.FloatField(value_model, visible=False) else: field = ui.StringField(value_model, visible=False) # Start editing when double clicked stack.set_mouse_double_clicked_fn(lambda x, y, b, m, f=field, l=label: self.on_double_click(b, f, l)) def on_double_click(self, button, field, label): """Called when the user double-clicked the item in TreeView""" if button != 0: return # Make Field visible when double clicked field.visible = True field.focus_keyboard() # When editing is finished (enter pressed of mouse clicked outside of the viewport) self.subscription = field.model.subscribe_end_edit_fn( lambda m, f=field, l=label: self.on_end_edit(m, f, l) ) def on_end_edit(self, model, field, label): """Called when the user is editing the item and pressed Enter or clicked outside of the item""" field.visible = False label.text = model.as_string self.subscription = None with ui.ScrollingFrame( height=100, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="TreeView", style={"Field": {"background_color": cl.black}}, ): self._name_value_model = NameValueModel("First", 0.2, "Second", 0.3, "Last", 0.4) self._name_value_delegate = EditableDelegate() tree_view = ui.TreeView( self._name_value_model, delegate=self._name_value_delegate, root_visible=False, header_visible=False, style={"TreeView.Item": {"margin": 4}}, ) ``` This is an example of async filling the TreeView model. It's collecting only as many as it's possible of USD prims for 0.016s and waits for the next frame, so the UI is not locked even if the USD Stage is extremely big. To play with it, create several materials in the stage or open a stage which contains materials, click "Traverse All" or "Stop Traversing". ```execute 200 import asyncio import time from omni.ui import color as cl class ListItem(ui.AbstractItem): """Single item of the model""" def __init__(self, text): super().__init__() self.name_model = ui.SimpleStringModel(text) def __repr__(self): return f'"{self.name_model.as_string}"' class ListModel(ui.AbstractItemModel): """ Represents the model for lists. It's very easy to initialize it with any string list: string_list = ["Hello", "World"] model = ListModel(*string_list) ui.TreeView(model) """ def __init__(self, *args): super().__init__() self._children = [ListItem(t) for t in args] 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._children def get_item_value_model_count(self, item): """The number of columns""" return 1 def get_item_value_model(self, item, column_id): """ Return value model. It's the object that tracks the specific value. In our case we use ui.SimpleStringModel. """ return item.name_model class AsyncQueryModel(ListModel): """ This is an example of async filling the TreeView model. It's collecting only as many as it's possible of USD prims for 0.016s and waits for the next frame, so the UI is not locked even if the USD Stage is extremely big. """ def __init__(self): super().__init__() self._stop_event = None def destroy(self): self.stop() def stop(self): """Stop traversing the stage""" if self._stop_event: self._stop_event.set() def reset(self): """Traverse the stage and keep materials""" self.stop() self._stop_event = asyncio.Event() self._children.clear() self._item_changed(None) asyncio.ensure_future(self.__get_all(self._stop_event)) def __push_collected(self, collected): """Add given array to the model""" for c in collected: self._children.append(c) self._item_changed(None) async def __get_all(self, stop_event): """Traverse the stage portion at time, so it doesn't freeze""" stop_event.clear() start_time = time.time() # The widget will be updated not faster than 60 times a second update_every = 1.0 / 60.0 import omni.usd from pxr import Usd from pxr import UsdShade context = omni.usd.get_context() stage = context.get_stage() if not stage: return # Buffer to keep the portion of the items before sending to the # widget collected = [] for p in stage.Traverse( Usd.TraverseInstanceProxies(Usd.PrimIsActive and Usd.PrimIsDefined and Usd.PrimIsLoaded) ): if stop_event.is_set(): break if p.IsA(UsdShade.Material): # Collect materials only collected.append(ListItem(str(p.GetPath()))) elapsed_time = time.time() # Loop some amount of time so fps will be about 60FPS if elapsed_time - start_time > update_every: start_time = elapsed_time # Append the portion and update the widget if collected: self.__push_collected(collected) collected = [] # Wait one frame to let other tasks go await omni.kit.app.get_app().next_update_async() self.__push_collected(collected) try: import omni.usd from pxr import Usd usd_available = True except ModuleNotFoundError: usd_available = False if usd_available: with ui.ScrollingFrame( height=200, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="TreeView", style={"Field": {"background_color": cl.black}}, ): self._async_query_model = AsyncQueryModel() ui.TreeView( self._async_query_model, root_visible=False, header_visible=False, style={"TreeView.Item": {"margin": 4}}, ) self._loaded_label = ui.Label("Press Button to Load Materials", name="text") with ui.HStack(): ui.Button("Traverse All", clicked_fn=self._async_query_model.reset) ui.Button("Stop Traversing", clicked_fn=self._async_query_model.stop) def _item_changed(model, item): if item is None: count = len(model._children) self._loaded_label.text = f"{count} Materials Traversed" self._async_query_sub = self._async_query_model.subscribe_item_changed_fn(_item_changed) ```
28,899
Markdown
34.503685
357
0.641718
omniverse-code/kit/exts/omni.kit.documentation.ui.style/docs/sliders.md
# Fields and Sliders ## Common Styling for Fields and Sliders Here is a list of common style you can customize on Fields and Sliders: > background_color (color): the background color of the field or slider > border_color (color): the border color if the field or slider background has a border > border_radius (float): the border radius if the user wants to round the field or slider > border_width (float): the border width if the field or slider background has a border > padding (float): the distance between the text and the border of the field or slider > font_size (float): the size of the text in the field or slider ## Field There are fields for string, float and int models. Except the common style for Fields and Sliders, here is a list of styles you can customize on Field: > color (color): the color of the text > background_selected_color (color): the background color of the selected text ### StringField The StringField widget is a one-line text editor. A field allows the user to enter and edit a single line of plain text. It's implemented using the model-delegate-view pattern and uses AbstractValueModel as the central component of the system. The following example demonstrates how to connect a StringField and a Label. You can type anything into the StringField. ```execute 200 from omni.ui import color as cl field_style = { "Field": { "background_color": cl(0.8), "border_color": cl.blue, "background_selected_color": cl.yellow, "border_radius": 5, "border_width": 1, "color": cl.red, "font_size": 20.0, "padding": 5, }, "Field:pressed": {"background_color": cl.white, "border_color": cl.green, "border_width": 2, "padding": 8}, } def setText(label, text): """Sets text on the label""" # This function exists because lambda cannot contain assignment label.text = f"You wrote '{text}'" with ui.HStack(): field = ui.StringField(style=field_style) ui.Spacer(width=5) label = ui.Label("", name="text") field.model.add_value_changed_fn(lambda m, label=label: setText(label, m.get_value_as_string())) ui.Spacer(width=10) ``` The following example demonstrates that the CheckBox's model decides the content of the Field. Click to edit and update the string field value also updates the value of the CheckBox. The field can only have one of the two options, either 'True' or 'False', because the model only supports those two possibilities. ```execute 200 from omni.ui import color as cl with ui.HStack(): field = ui.StringField(width=100, style={"background_color": cl.black}) checkbox = ui.CheckBox(width=0) field.model = checkbox.model ``` In this example, the field can have anything because the model accepts any string. The model returns bool for checkbox, and the checkbox is unchecked when the string is empty or 'False'. ```execute 200 from omni.ui import color as cl with ui.HStack(): field = ui.StringField(width=100, style={"background_color": cl.black}) checkbox = ui.CheckBox(width=0) checkbox.model = field.model ``` The Field widget doesn't keep the data due to the model-delegate-view pattern. However, there are two ways to track the state of the widget. It's possible to re-implement the AbstractValueModel. The second way is using the callbacks of the model. Here is a minimal example of callbacks. When you start editing the field, you will see "Editing is started", and when you finish editing by press `enter`, you will see "Editing is finished". ```execute 200 def on_value(label): label.text = "Value is changed" def on_begin(label): label.text = "Editing is started" def on_end(label): label.text = "Editing is finished" label = ui.Label("Nothing happened", name="text") model = ui.StringField().model model.add_value_changed_fn(lambda m, l=label: on_value(l)) model.add_begin_edit_fn(lambda m, l=label: on_begin(l)) model.add_end_edit_fn(lambda m, l=label: on_end(l)) ``` ### Multiline StringField Property `multiline` of `StringField` allows users to press enter and create a new line. It's possible to finish editing with Ctrl-Enter. ```execute 200 from omni.ui import color as cl import inspect field_style = { "Field": { "background_color": cl(0.8), "color": cl.black, }, "Field:pressed": {"background_color": cl(0.8)}, } field_callbacks = lambda: field_callbacks() with ui.Frame(style=field_style, height=200): model = ui.SimpleStringModel("hello \nworld \n") field = ui.StringField(model, multiline=True) ``` ### FloatField and IntField The following example shows how string field, float field and int field interact with each other. All three fields share the same default FloatModel: ```execute 200 with ui.HStack(spacing=5): ui.Label("FloatField") ui.Label("IntField") ui.Label("StringField") with ui.HStack(spacing=5): left = ui.FloatField() center = ui.IntField() right = ui.StringField() center.model = left.model right.model = left.model ui.Spacer(height=5) ``` ## MultiField MultiField widget groups the widgets that have multiple similar widgets to represent each item in the model. It's handy to use them for arrays and multi-component data like float3, matrix, and color. MultiField is using `Field` as the Type Selector. Therefore, the list of styless we can customize on MultiField is the same as Field ### MultiIntField Each of the field value could be changed by editing ```execute 200 from omni.ui import color as cl field_style = { "Field": { "background_color": cl(0.8), "border_color": cl.blue, "border_radius": 5, "border_width": 1, "color": cl.red, "font_size": 20.0, "padding": 5, }, "Field:pressed": {"background_color": cl.white, "border_color": cl.green, "border_width": 2, "padding": 8}, } ui.MultiIntField(0, 0, 0, 0, style=field_style) ``` ### MultiFloatField Use MultiFloatField to construct a matrix field: ```execute 200 args = [1.0 if i % 5 == 0 else 0.0 for i in range(16)] ui.MultiFloatField(*args, width=ui.Percent(50), h_spacing=5, v_spacing=2) ``` ### MultiFloatDragField Each of the field value could be changed by dragging ```execute 200 ui.MultiFloatDragField(0.0, 0.0, 0.0, 0.0) ``` ## Sliders The Sliders are more like a traditional slider that can be dragged and snapped where you click. The value of the slider can be shown on the slider or not, but can not be edited directly by clicking. Except the common style for Fields and Sliders, here is a list of styles you can customize on ProgressBar: > color (color): the color of the text > secondary_color (color): the color of the handle in `ui.SliderDrawMode.HANDLE` draw_mode or the background color of the left portion of the slider in `ui.SliderDrawMode.DRAG` draw_mode > secondary_selected_color (color): the color of the handle when selected, not useful when the draw_mode is FILLED since there is no handle drawn. > draw_mode (enum): defines how the slider handle is drawn. There are three types of draw_mode. * ui.SliderDrawMode.HANDLE: draw the handle as a knob at the slider position * ui.SliderDrawMode.DRAG: the same as `ui.SliderDrawMode.HANDLE` for now * ui.SliderDrawMode.FILLED: the handle is eventually the boundary between the `secondary_color` and `background_color` Sliders with different draw_mode: ```execute 200 from omni.ui import color as cl with ui.VStack(spacing=5): ui.FloatSlider(style={"background_color": cl(0.8), "secondary_color": cl(0.6), "color": cl(0.1), "draw_mode": ui.SliderDrawMode.HANDLE} ).model.set_value(0.5) ui.FloatSlider(style={"background_color": cl(0.8), "secondary_color": cl(0.6), "color": cl(0.1), "draw_mode": ui.SliderDrawMode.DRAG} ).model.set_value(0.5) ui.FloatSlider(style={"background_color": cl(0.8), "secondary_color": cl(0.6), "color": cl(0.1), "draw_mode": ui.SliderDrawMode.FILLED} ).model.set_value(0.5) ``` ### FloatSlider Default slider whose range is between 0 to 1: ```execute 200 ui.FloatSlider() ``` With defined Min/Max whose range is between min to max: ```execute 200 ui.FloatSlider(min=0, max=10) ``` With defined Min/Max from the model. Notice the model allows the value range between 0 to 100, but the FloatSlider has a more strict range between 0 to 10. ```execute 200 model = ui.SimpleFloatModel(1.0, min=0, max=100) ui.FloatSlider(model, min=0, max=10) ``` With styles and rounded slider: ```execute 200 from omni.ui import color as cl with ui.HStack(width=200): ui.Spacer(width=20) with ui.VStack(): ui.Spacer(height=5) ui.FloatSlider( min=-180, max=180, style={ "color": cl.blue, "background_color": cl(0.8), "draw_mode": ui.SliderDrawMode.HANDLE, "secondary_color": cl.red, "secondary_selected_color": cl.green, "font_size": 20, "border_width": 3, "border_color": cl.black, "border_radius": 10, "padding": 10, } ) ui.Spacer(height=5) ui.Spacer(width=20) ``` Filled mode slider with style: ```execute 200 from omni.ui import color as cl with ui.HStack(width=200): ui.Spacer(width=20) with ui.VStack(): ui.Spacer(height=5) ui.FloatSlider( min=-180, max=180, style={ "color": cl.blue, "background_color": cl(0.8), "draw_mode": ui.SliderDrawMode.FILLED, "secondary_color": cl.red, "font_size": 20, "border_radius": 10, "padding": 10, } ) ui.Spacer(height=5) ui.Spacer(width=20) ``` Transparent background: ```execute 200 from omni.ui import color as cl with ui.HStack(width=200): ui.Spacer(width=20) with ui.VStack(): ui.Spacer(height=5) ui.FloatSlider( min=-180, max=180, style={ "draw_mode": ui.SliderDrawMode.HANDLE, "background_color": cl.transparent, "color": cl.red, "border_width": 1, "border_color": cl.white, } ) ui.Spacer(height=5) ui.Spacer(width=20) ``` Slider with transparent value. Notice the use of `step` attribute ```execute 200 from omni.ui import color as cl with ui.HStack(): # a separate float field field = ui.FloatField(height=15, width=50) # a slider using field's model ui.FloatSlider( min=0, max=20, step=0.25, model=field.model, style={ "color":cl.transparent, "background_color": cl(0.3), "draw_mode": ui.SliderDrawMode.HANDLE} ) # default value field.model.set_value(12.0) ``` ### IntSlider Default slider whose range is between 0 to 100: ```execute 200 ui.IntSlider() ``` With defined Min/Max whose range is between min to max. Note that the handle width is much wider. ```execute 200 ui.IntSlider(min=0, max=20) ``` With style: ```execute 200 from omni.ui import color as cl with ui.HStack(width=200): ui.Spacer(width=20) with ui.VStack(): ui.Spacer(height=5) ui.IntSlider( min=0, max=20, style={ "background_color": cl("#BBFFBB"), "color": cl.purple, "draw_mode": ui.SliderDrawMode.HANDLE, "secondary_color": cl.green, "secondary_selected_color": cl.red, "font_size": 14.0, "border_width": 3, "border_color": cl.green, "padding": 5, } ).model.set_value(4) ui.Spacer(height=5) ui.Spacer(width=20) ``` ## Drags The Drags are very similar to Sliders, but more like Field in the way that they behave. You can double click to edit the value but they also have a mean to be 'Dragged' to increase or decrease the value. Except the common style for Fields and Sliders, here is a list of styles you can customize on ProgressBar: > color (color): the color of the text > secondary_color (color): the left portion of the slider in `ui.SliderDrawMode.DRAG` draw_mode ### FloatDrag Default float drag whose range is -inf and +inf ```execute 200 ui.FloatDrag() ``` With defined Min/Max whose range is between min to max: ```execute 200 ui.FloatDrag(min=-10, max=10, step=0.1) ``` With styles and rounded shape: ```execute 200 from omni.ui import color as cl with ui.HStack(width=200): ui.Spacer(width=20) with ui.VStack(): ui.Spacer(height=5) ui.FloatDrag( min=-180, max=180, style={ "color": cl.blue, "background_color": cl(0.8), "secondary_color": cl.red, "font_size": 20, "border_width": 3, "border_color": cl.black, "border_radius": 10, "padding": 10, } ) ui.Spacer(height=5) ui.Spacer(width=20) ``` ### IntDrag Default int drag whose range is -inf and +inf ```execute 200 ui.IntDrag() ``` With defined Min/Max whose range is between min to max: ```execute 200 ui.IntDrag(min=-10, max=10) ``` With styles and rounded slider: ```execute 200 from omni.ui import color as cl with ui.HStack(width=200): ui.Spacer(width=20) with ui.VStack(): ui.Spacer(height=5) ui.IntDrag( min=-180, max=180, style={ "color": cl.blue, "background_color": cl(0.8), "secondary_color": cl.purple, "font_size": 20, "border_width": 4, "border_color": cl.black, "border_radius": 20, "padding": 5, } ) ui.Spacer(height=5) ui.Spacer(width=20) ``` ## ProgressBar A ProgressBar is a widget that indicates the progress of an operation. Except the common style for Fields and Sliders, here is a list of styles you can customize on ProgressBar: > color (color): the color of the progress bar indicating the progress value of the progress bar in the portion of the overall value > secondary_color (color): the color of the text indicating the progress value In the following example, it shows how to use ProgressBar and override the style of the overlay text. ```execute 200 from omni.ui import color as cl class CustomProgressValueModel(ui.AbstractValueModel): """An example of custom float model that can be used for progress bar""" def __init__(self, value: float): super().__init__() self._value = value def set_value(self, value): """Reimplemented set""" try: value = float(value) except ValueError: value = None if value != self._value: # Tell the widget that the model is changed self._value = value self._value_changed() def get_value_as_float(self): return self._value def get_value_as_string(self): return "Custom Overlay" with ui.VStack(spacing=5): # Create ProgressBar first = ui.ProgressBar() # Range is [0.0, 1.0] first.model.set_value(0.5) second = ui.ProgressBar() second.model.set_value(1.0) # Overrides the overlay of ProgressBar model = CustomProgressValueModel(0.8) third = ui.ProgressBar(model) third.model.set_value(0.1) # Styling its color fourth = ui.ProgressBar(style={"color": cl("#0000dd")}) fourth.model.set_value(0.3) # Styling its border width ui.ProgressBar(style={"border_width": 2, "border_color": cl("#dd0000"), "color": cl("#0000dd")}).model.set_value(0.7) # Styling its border radius ui.ProgressBar(style={"border_radius": 100, "color": cl("#0000dd")}).model.set_value(0.6) # Styling its background color ui.ProgressBar(style={"border_radius": 10, "background_color": cl("#0000dd")}).model.set_value(0.6) # Styling the text color ui.ProgressBar(style={"ProgressBar":{"border_radius": 30, "secondary_color": cl("#00dddd"), "font_size": 20}}).model.set_value(0.6) # Two progress bars in a row with padding with ui.HStack(): ui.ProgressBar(style={"color": cl("#0000dd"), "padding": 100}).model.set_value(1.0) ui.ProgressBar().model.set_value(0.0) ``` ## Tooltip All Widget can be augmented with a tooltip. It can take 2 forms, either a simple ui.Label or a callback when using the callback of `tooltip_fn=` or `widget.set_tooltip_fn()`. You can create the tooltip for any widget. Except the common style for Fields and Sliders, here is a list of styles you can customize on Line: > color (color): the color of the text of the tooltip. > margin_width (float): the width distance between the tooltip content and the parent widget defined boundary > margin_height (float): the height distance between the tooltip content and the parent widget defined boundary Here is a simple label tooltip with style when you hover over a button: ```execute 200 from omni.ui import color as cl tooltip_style = { "Tooltip": { "background_color": cl("#DDDD00"), "color": cl(0.2), "padding": 10, "border_width": 3, "border_color": cl.red, "font_size": 20, "border_radius": 10}} ui.Button("Simple Label Tooltip", name="tooltip", width=200, tooltip="I am a text ToolTip", style=tooltip_style) ``` You can create a callback function as the tooltip where you can create any types of widgets you like in the tooltip and layout them. Make the tooltip very illustrative to have Image or Field or Label etc. ```execute 200 from omni.ui import color as cl def create_tooltip(): with ui.VStack(width=200, style=tooltip_style): with ui.HStack(): ui.Label("Fancy tooltip", width=150) ui.IntField().model.set_value(12) ui.Line(height=2, style={"color":cl.white}) with ui.HStack(): ui.Label("Anything is possible", width=150) ui.StringField().model.set_value("you bet") image_source = "resources/desktop-icons/omniverse_512.png" ui.Image( image_source, width=200, height=200, alignment=ui.Alignment.CENTER, style={"margin": 0}, ) tooltip_style = { "Tooltip": { "background_color": cl(0.2), "border_width": 2, "border_radius": 5, "margin_width": 5, "margin_height": 10 }, } ui.Button("Callback function Tooltip", width=200, style=tooltip_style, tooltip_fn=create_tooltip) ``` You can define a fixed position for tooltip: ```execute 200 ui.Button("Fixed-position Tooltip", width=200, tooltip="Hello World", tooltip_offset_y=22) ``` You can also define a random position for tooltip: ```execute 200 import random button = ui.Button("Random-position Tooltip", width=200, tooltip_offset_y=22) def create_tooltip(button=button): button.tooltip_offset_x = random.randint(0, 200) ui.Label("Hello World") button.set_tooltip_fn(create_tooltip) ```
20,428
Markdown
34.777583
437
0.609898
omniverse-code/kit/exts/omni.kit.documentation.ui.style/docs/fonts.md
# Fonts ## Font style It's possible to set different font types with the style. The style key 'font' should point to the font file, which allows packaging of the font to the extension. We support both TTF and OTF formats. All text-based widgets support custom fonts. ```execute 200 with ui.VStack(): ui.Label("Omniverse", style={"font":"${fonts}/OpenSans-SemiBold.ttf", "font_size": 40.0}) ui.Label("Omniverse", style={"font":"${fonts}/roboto_medium.ttf", "font_size": 40.0}) ``` ## Font size It's possible to set the font size with the style. Drag the following slider to change the size of the text. ```execute 200 def value_changed(label, value): label.style = {"color": ui.color(0), "font_size": value.as_float} slider = ui.FloatSlider(min=1.0, max=150.0) slider.model.as_float = 10.0 label = ui.Label("Omniverse", style={"color": ui.color(0), "font_size": 7.0}) slider.model.add_value_changed_fn(partial(value_changed, label)) ## Double comment means hide from shippet ui.Spacer(height=30) ## ```
1,019
Markdown
35.42857
244
0.705594
omniverse-code/kit/exts/omni.kit.documentation.ui.style/docs/containers.md
# Container widgets Container widgets are used for grouping items. It's possible to add children to the container with Python's `with` statement. It's not possible to reparent items. Instead, it's necessary to remove the item and recreate a similar item under another parent. ## Stack We have three main components: VStack, HStack, and ZStack. Here is a list of styles you can customize on Stack: > margin (float): the distance between the stack items and the parent widget defined boundary > margin_width (float): the width distance between the stack items and the parent widget defined boundary > margin_height (float): the height distance between the stack items and the parent widget defined boundary It's possible to determine the direction of a stack with the property `direction`. Here is an example of a stack which is able to change its direction dynamically by clicking the button `Change`. ```execute 200 def rotate(dirs, stack, label): dirs[0] = (dirs[0] + 1) % len(dirs[1]) stack.direction = dirs[1][dirs[0]] label.text = str(stack.direction) dirs = [ 0, [ ui.Direction.LEFT_TO_RIGHT, ui.Direction.RIGHT_TO_LEFT, ui.Direction.TOP_TO_BOTTOM, ui.Direction.BOTTOM_TO_TOP, ], ] stack = ui.Stack(ui.Direction.LEFT_TO_RIGHT, width=0, height=0, style={"margin_height": 5, "margin_width": 10}) with stack: for name in ["One", "Two", "Three", "Four"]: ui.Button(name) ui.Spacer(height=100) with ui.HStack(): ui.Label("Current direction is ", name="text", width=0) label = ui.Label("", name="text") button = ui.Button("Change") button.set_clicked_fn(lambda d=dirs, s=stack, l=label: rotate(d, s, l)) rotate(dirs, stack, label) ``` ### HStack This class is used to construct horizontal layout objects. The simplest use of the class is like this: ```execute 200 with ui.HStack(style={"margin": 10}): ui.Button("One") ui.Button("Two") ui.Button("Three") ui.Button("Four") ui.Button("Five") ``` ### VStack The VStack class lines up widgets vertically. ```execute 200 with ui.VStack(width=100.0, style={"margin": 5}): with ui.VStack(): ui.Button("One") ui.Button("Two") ui.Button("Three") ui.Button("Four") ui.Button("Five") ``` ### ZStack ZStack is a view that overlays its children, aligning them on top of each other. The later one is on top of the previous ones. ```execute 200 with ui.VStack(width=100.0, style={"margin": 5}): with ui.ZStack(): ui.Button("Very Long Text to See How Big it Can Be", height=0) ui.Button("Another\nMultiline\nButton", width=0) ``` ### Layout Here is an example of using combined HStack and VStack: ```execute 200 with ui.VStack(): for i in range(2): with ui.HStack(): ui.Spacer(width=50) with ui.VStack(height=0): ui.Button("Left {}".format(i), height=0) ui.Button("Vertical {}".format(i), height=50) with ui.HStack(width=ui.Fraction(2)): ui.Button("Right {}".format(i)) ui.Button("Horizontal {}".format(i), width=ui.Fraction(2)) ui.Spacer(width=50) ``` ### Spacing Spacing is a property of Stack. It defines the non-stretchable space in pixels between child items of the layout. Here is an example that you can change the HStack spacing by a slider ```execute 200 from omni.ui import color as cl SPACING = 5 def set_spacing(stack, spacing): stack.spacing = spacing ui.Spacer(height=SPACING) spacing_stack = ui.HStack(style={"margin": 0}) with spacing_stack: for name in ["One", "Two", "Three", "Four"]: ui.Button(name) ui.Spacer(height=SPACING) with ui.HStack(spacing=SPACING): with ui.HStack(width=100): ui.Spacer() ui.Label("spacing", width=0, name="text") with ui.HStack(width=ui.Percent(20)): field = ui.FloatField(width=50) slider = ui.FloatSlider(min=0, max=50, style={"color": cl.transparent}) # Link them together slider.model = field.model slider.model.add_value_changed_fn( lambda m, s=spacing_stack: set_spacing(s, m.get_value_as_float())) ``` ## Frame Frame is a container that can keep only one child. Each child added to Frame overrides the previous one. This feature is used for creating dynamic layouts. The whole layout can be easily recreated with a simple callback. Here is a list of styles you can customize on Frame: > padding (float): the distance between the child widgets and the border of the button In the following example, you can drag the IntDrag to change the slider value. The buttons are recreated each time the slider changes. ```execute 200 self._recreate_ui = ui.Frame(height=40, style={"Frame":{"padding": 5}}) def changed(model, recreate_ui=self._recreate_ui): with recreate_ui: with ui.HStack(): for i in range(model.get_value_as_int()): ui.Button(f"Button #{i}") model = ui.IntDrag(min=0, max=10).model self._sub_recreate = model.subscribe_value_changed_fn(changed) ``` Another feature of Frame is the ability to clip its child. When the content of Frame is bigger than Frame itself, the exceeding part is not drawn if the clipping is on. There are two clipping types: `horizontal_clipping` and `vertical_clipping`. Here is an example of vertical clipping. ```execute 200 with ui.Frame(vertical_clipping=True, height=20): ui.Label("This should be clipped vertically. " * 10, word_wrap=True) ``` ## CanvasFrame CanvasFrame is the widget that allows the user to pan and zoom its children with a mouse. It has a layout that can be infinitely moved in any direction. Here is a list of styles you can customize on CanvasFrame: > background_color (color): the main color of the rectangle Here is an example of a CanvasFrame, you can scroll the middle mouse to zoom the canvas and middle mouse move to pan in it (press CTRL to avoid scrolling the docs). ```execute 200 from omni.ui import color as cl TEXT = ( "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." ) IMAGE = "resources/icons/ov_logo_square.png" with ui.CanvasFrame(height=256, style={"CanvasFrame":{"background_color": cl("#aa4444")}}): with ui.VStack(height=0, spacing=10): ui.Label(TEXT, name="text", word_wrap=True) ui.Button("Button") ui.Image(IMAGE, width=128, height=128) ``` ## ScrollingFrame The ScrollingFrame class provides the ability to scroll onto other widgets. ScrollingFrame is used to display the contents of children widgets within a frame. If the widget exceeds the size of the frame, the frame can provide scroll bars so that the entire area of the child widget can be viewed by scrolling. Here is a list of styles you can customize on ScrollingFrame: > scrollbar_size (float): the width of the scroll bar > secondary_color (color): the color the scroll bar > background_color (color): the background color the scroll frame Here is an example of a ScrollingFrame, you can scroll the middle mouse to scroll the frame. ```execute 200 from omni.ui import color as cl with ui.HStack(): left_frame = ui.ScrollingFrame( height=250, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style={"ScrollingFrame":{ "scrollbar_size":10, "secondary_color": cl.red, "background_color": cl("#4444dd")}} ) with left_frame: with ui.VStack(height=0): for i in range(20): ui.Button(f"Button Left {i}") right_frame = ui.ScrollingFrame( height=250, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style={"ScrollingFrame":{ "scrollbar_size":30, "secondary_color": cl.blue, "background_color": cl("#44dd44")}} ) with right_frame: with ui.VStack(height=0): for i in range(20): ui.Button(f"Button Right {i}") # Synchronize the scroll position of two frames def set_scroll_y(frame, y): frame.scroll_y = y left_frame.set_scroll_y_changed_fn(lambda y, frame=right_frame: set_scroll_y(frame, y)) right_frame.set_scroll_y_changed_fn(lambda y, frame=left_frame: set_scroll_y(frame, y)) ``` ## CollapsableFrame CollapsableFrame is a frame widget that can hide or show its content. It has two states: expanded and collapsed. When it's collapsed, it looks like a button. If it's expanded, it looks like a button and a frame with the content. It's handy to group properties, and temporarily hide them to get more space for something else. Here is a list of styles you can customize on Image: > background_color (color): the background color of the CollapsableFrame widget > secondary_color (color): the background color of the CollapsableFrame's header > border_radius (float): the border radius if user wants to round the CollapsableFrame > border_color (color): the border color if the CollapsableFrame has a border > border_width (float): the border width if the CollapsableFrame has a border > padding (float): the distance between the header or the content to the border of the CollapsableFrame > margin (float): the distance between the CollapsableFrame and other widgets Here is a default `CollapsableFrame` example: ```execute 200 with ui.CollapsableFrame("Header"): with ui.VStack(height=0): ui.Button("Hello World") ui.Button("Hello World") ``` It's possible to use a custom header. ```execute 200 from omni.ui import color as cl def custom_header(collapsed, title): with ui.HStack(): with ui.ZStack(width=30): ui.Circle(name="title") with ui.HStack(): ui.Spacer() align = ui.Alignment.V_CENTER ui.Line(name="title", width=6, alignment=align) ui.Spacer() if collapsed: with ui.VStack(): ui.Spacer() align = ui.Alignment.H_CENTER ui.Line(name="title", height=6, alignment=align) ui.Spacer() ui.Label(title, name="title") style = { "CollapsableFrame": { "background_color": cl(0.5), "secondary_color": cl("#CC211B"), "border_radius": 10, "border_color": cl.blue, "border_width": 2, }, "CollapsableFrame:hovered": {"secondary_color": cl("#FF4321")}, "CollapsableFrame:pressed": {"secondary_color": cl.red}, "Label::title": {"color": cl.white}, "Circle::title": { "color": cl.yellow, "background_color": cl.transparent, "border_color": cl(0.9), "border_width": 0.75, }, "Line::title": {"color": cl(0.9), "border_width": 1}, } ui.Spacer(height=5) with ui.HStack(): ui.Spacer(width=5) with ui.CollapsableFrame("Header", build_header_fn=custom_header, style=style): with ui.VStack(height=0): ui.Button("Hello World") ui.Button("Hello World") ui.Spacer(width=5) ui.Spacer(height=5) ``` This example demonstrates how padding and margin work in the collapsable frame. ```execute 200 from omni.ui import color as cl style = { "CollapsableFrame": { "border_color": cl("#005B96"), "border_radius": 4, "border_width": 2, "padding": 0, "margin": 0, } } frame = ui.CollapsableFrame("Header", style=style) with frame: with ui.VStack(height=0): ui.Button("Hello World") ui.Button("Hello World") def set_style(field, model, style=style, frame=frame): frame_style = style["CollapsableFrame"] frame_style[field] = model.get_value_as_float() frame.set_style(style) with ui.HStack(): ui.Label("Padding:", width=ui.Percent(10), name="text") model = ui.FloatSlider(min=0, max=50).model model.add_value_changed_fn(lambda m: set_style("padding", m)) with ui.HStack(): ui.Label("Margin:", width=ui.Percent(10), name="text") model = ui.FloatSlider(min=0, max=50).model model.add_value_changed_fn(lambda m: set_style("margin", m)) ``` ## Order in Stack and use of content_clipping Due to Imgui, ScrollingFrame and CanvasFrame will create a new window, meaning if we have them in a ZStack, they don't respect the Stack order. To fix that we need to create a separate window, with the widget wrapped in a `ui.Frame(separate_window=True)` will fix the order issue. And if we also want the mouse input in the new separate window, we use `ui.HStack(content_clipping=True)` for that. In the following example, you won't see the red rectangle. ```execute 200 from omni.ui import color as cl with ui.ZStack(): ui.Rectangle(width=200, height=200, style={'background_color':cl.green}) with ui.CanvasFrame(width=150, height=150): ui.Rectangle(style={'background_color':cl.blue}) ui.Rectangle(width=100, height=100, style={'background_color':cl.red}) ``` With the use of `separate_window=True` or `content_clipping=True`, you will see the red rectangle. ```execute 200 from omni.ui import color as cl with ui.ZStack(): ui.Rectangle(width=200, height=200, style={'background_color':cl.green}) with ui.CanvasFrame(width=150, height=150): ui.Rectangle(style={'background_color':cl.blue}) with ui.Frame(separate_window=True): ui.Rectangle(width=100, height=100, style={'background_color':cl.red}) ``` ```execute 200 from omni.ui import color as cl with ui.ZStack(): ui.Rectangle(width=200, height=200, style={'background_color':cl.green}) with ui.CanvasFrame(width=150, height=150): ui.Rectangle(style={'background_color':cl.blue}) with ui.HStack(content_clipping=True): ui.Rectangle(width=100, height=100, style={'background_color':cl.red}) ``` In the following example, you will see the button click action is captured on Button 1. ```execute 200 from functools import partial def clicked(name): print(f'clicked {name}') with ui.ZStack(): b1 = ui.Button('Button 1') b1.set_clicked_fn(partial(clicked, b1.text)) b2 = ui.Button('Button 2') b2.set_clicked_fn(partial(clicked, b2.text)) ``` With the use of `content_clipping=True`, you will see the button click action is now fixed and captured on Button 2. ```execute 200 from functools import partial def clicked(name): print(f'clicked {name}') with ui.ZStack(): b1 = ui.Button('Button 1') b1.set_clicked_fn(partial(clicked, b1.text)) with ui.VStack(content_clipping=1): b2 = ui.Button('Button 2') b2.set_clicked_fn(partial(clicked, b2.text)) ``` ## Grid Grid is a container that arranges its child views in a grid. Depends on the direction the grid size grows with creating more children, we call it VGrid (grow in vertical direction) and HGrid (grow in horizontal direction) There is currently no style you can customize on Grid. ### VGrid VGrid has two modes for cell width: - If the user sets column_count, the column width is computed from the grid width. - If the user sets column_width, the column count is computed from the grid width. VGrid also has two modes for height: - If the user sets row_height, VGrid uses it to set the height for all the cells. It's the fast mode because it's considered that the cell height never changes. VGrid easily predicts which cells are visible. - If the user sets nothing, VGrid computes the size of the children. This mode is slower than the previous one, but the advantage is that all the rows can be different custom sizes. VGrid still only draws visible items, but to predict it, it uses cache, which can be big if VGrid has hundreds of thousands of items. Here is an example of VGrid: ```execute 200 from omni.ui import color as cl with ui.ScrollingFrame( height=250, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ): with ui.VGrid(column_width=100, row_height=100): for i in range(100): with ui.ZStack(): ui.Rectangle( style={ "border_color": cl.red, "background_color": cl.white, "border_width": 1, "margin": 0, } ) ui.Label(f"{i}", style={"margin": 5}) ``` ### HGrid HGrid works exactly like VGrid, but with swapped width and height. ```execute 200 from omni.ui import color as cl with ui.ScrollingFrame( height=250, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, ): with ui.HGrid(column_width=100, row_height=100): for i in range(100): with ui.ZStack(): ui.Rectangle( style={ "border_color": cl.red, "background_color": cl.white, "border_width": 1, "margin": 0, } ) ui.Label(f"{i}", style={"margin": 5}) ``` ## Placer Placer enables you to place a widget precisely with offset. Placer's property `draggable` allows changing the position of the child widget by dragging it with the mouse. There is currently no style you can customize on Placer. Here is an example of 4 Placers. Two of them have fixed positions, each with a ui.Button as the child. You can see the buttons are moved to the exact place by the parent Placer, one at (100, 10) and the other at (200, 50). The third one is `draggable`, which has a Circle as the child, so that you can move the circle freely with mouse drag in the frame. The fourth one is also `draggable`, which has a ZStack as the child. The ZStack is composed of Rectangle and HStack and Label. This Placer is only draggable on the Y-axis, defined by `drag_axis=ui.Axis.Y`, so that you can only move the ZStack on the y-axis. ```execute 200 from omni.ui import color as cl with ui.ScrollingFrame( height=170, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, ): with ui.ZStack(): with ui.HStack(): for index in range(60): ui.Line(width=10, style={"color": cl.black, "border_width": 0.5}, alignment=ui.Alignment.LEFT) with ui.VStack(): ui.Line( height=10, width=600, style={"color": cl.black, "border_width": 0.5}, alignment=ui.Alignment.TOP, ) for index in range(15): ui.Line( height=10, width=600, style={"color": cl.black, "border_width": 0.5}, alignment=ui.Alignment.TOP, ) ui.Line( height=10, width=600, style={"color": cl.black, "border_width": 0.5}, alignment=ui.Alignment.TOP, ) with ui.Placer(offset_x=100, offset_y=10): ui.Button("moved 100px in X, and 10px in Y", width=0, height=20, name="placed") with ui.Placer(offset_x=200, offset_y=50): ui.Button("moved 200px X , and 50 Y", width=0, height=0) def set_text(widget, text): widget.text = text with ui.Placer(draggable=True, offset_x=300, offset_y=100): ui.Circle(radius=50, width=50, height=50, size_policy=ui.CircleSizePolicy.STRETCH, name="placed") placer = ui.Placer(draggable=True, drag_axis=ui.Axis.Y, offset_x=400, offset_y=120) with placer: with ui.ZStack(width=180, height=40): ui.Rectangle(name="placed") with ui.HStack(spacing=5): ui.Circle( radius=3, width=15, size_policy=ui.CircleSizePolicy.FIXED, style={"background_color": cl.white}, ) ui.Label("UP / Down", style={"color": cl.white, "font_size": 16.0}) offset_label = ui.Label("120", style={"color": cl.white}) placer.set_offset_y_changed_fn(lambda o: set_text(offset_label, str(o))) ``` The following example shows the way to interact between three Placers to create a resizable rectangle's body, left handle and right handle. The rectangle can be moved on X-axis and can be resized with small orange handles. When multiple widgets fire the callbacks simultaneously, it's possible to collect the event data and process them one frame later using asyncio. ```execute 200 import asyncio import omni.kit.app from omni.ui import color as cl def placer_track(self, id): # Initial size BEGIN = 50 + 100 * id END = 120 + 100 * id HANDLE_WIDTH = 10 class EditScope: """The class to avoid circular event calling""" def __init__(self): self.active = False def __enter__(self): self.active = True def __exit__(self, type, value, traceback): self.active = False def __bool__(self): return not self.active class DoLater: """A helper to collect data and process it one frame later""" def __init__(self): self.__task = None self.__data = [] def do(self, data): # Collect data self.__data.append(data) # Update in the next frame. We need it because we want to accumulate the affected prims if self.__task is None or self.__task.done(): self.__task = asyncio.ensure_future(self.__delayed_do()) async def __delayed_do(self): # Wait one frame await omni.kit.app.get_app().next_update_async() print(f"In the previous frame the user clicked the rectangles: {self.__data}") self.__data.clear() self.edit = EditScope() self.dolater = DoLater() def start_moved(start, body, end): if not self.edit: # Something already edits it return with self.edit: body.offset_x = start.offset_x rect.width = ui.Pixel(end.offset_x - start.offset_x + HANDLE_WIDTH) def body_moved(start, body, end, rect): if not self.edit: # Something already edits it return with self.edit: start.offset_x = body.offset_x end.offset_x = body.offset_x + rect.width.value - HANDLE_WIDTH def end_moved(start, body, end, rect): if not self.edit: # Something already edits it return with self.edit: body.offset_x = start.offset_x rect.width = ui.Pixel(end.offset_x - start.offset_x + HANDLE_WIDTH) with ui.ZStack(height=30): # Body body = ui.Placer(draggable=True, drag_axis=ui.Axis.X, offset_x=BEGIN) with body: rect = ui.Rectangle(width=END - BEGIN + HANDLE_WIDTH) rect.set_mouse_pressed_fn(lambda x, y, b, m, id=id: self.dolater.do(id)) # Left handle start = ui.Placer(draggable=True, drag_axis=ui.Axis.X, offset_x=BEGIN) with start: ui.Rectangle(width=HANDLE_WIDTH, style={"background_color": cl("#FF660099")}) # Right handle end = ui.Placer(draggable=True, drag_axis=ui.Axis.X, offset_x=END) with end: ui.Rectangle(width=HANDLE_WIDTH, style={"background_color": cl("#FF660099")}) # Connect them together start.set_offset_x_changed_fn(lambda _, s=start, b=body, e=end: start_moved(s, b, e)) body.set_offset_x_changed_fn(lambda _, s=start, b=body, e=end, r=rect: body_moved(s, b, e, r)) end.set_offset_x_changed_fn(lambda _, s=start, b=body, e=end, r=rect: end_moved(s, b, e, r)) ui.Spacer(height=5) with ui.ZStack(): placer_track(self, 0) placer_track(self, 1) ui.Spacer(height=5) ``` It's possible to set `offset_x` and `offset_y` in percentages. It allows stacking the children to the proportions of the parent widget. If the parent size is changed, then the offset is updated accordingly. ```execute 200 from omni.ui import color as cl # The size of the rectangle SIZE = 20.0 with ui.ZStack(height=200): # Background ui.Rectangle(style={"background_color": cl(0.6)}) # Small rectangle p = ui.Percent(50) placer = ui.Placer(draggable=True, offset_x=p, offset_y=p) with placer: ui.Rectangle(width=SIZE, height=SIZE) def clamp_x(offset): if offset.value < 0: placer.offset_x = ui.Percent(0) max_per = 100.0 - SIZE / placer.computed_width * 100.0 if offset.value > max_per: placer.offset_x = ui.Percent(max_per) def clamp_y(offset): if offset.value < 0: placer.offset_y = ui.Percent(0) max_per = 100.0 - SIZE / placer.computed_height * 100.0 if offset.value > max_per: placer.offset_y = ui.Percent(max_per) # Callbacks placer.set_offset_x_changed_fn(clamp_x) placer.set_offset_y_changed_fn(clamp_y) ```
25,689
Markdown
37.115727
612
0.647592
omniverse-code/kit/exts/omni.kit.documentation.ui.style/docs/shapes.md
# Shapes Shapes enable you to build custom widgets with specific looks. There are many shapes you can stylize: Rectangle, Circle, Ellipse, Triangle and FreeShapes of FreeRectangle, FreeCircle, FreeEllipse, FreeTriangle. In most cases those shapes will fit into the widget size which is defined by the parent widget they are in. The FreeShapes are the shapes that are independent of the layout. It means it can be stuck to other shapes. It means it is possible to stick the freeshape to the layout's widgets, and the freeshape will follow the changes of the layout automatically. ## Common Style of shapes Here is a list of common style you can customize on all the Shapes: > background_color (color): the background color of the shape > border_width (float): the border width if the shape has a border > border_color (color): the border color if the shape has a border ## Rectangle Rectangle is a shape with four sides and four corners. You can use Rectangle to draw rectangle shapes, or mix it with other controls e.g. using ZStack to create an advanced look. Except the common style for shapes, here is a list of styles you can customize on Rectangle: > background_gradient_color (color): the gradient color on the top part of the rectangle > border_radius (float): default rectangle has 4 right corner angles, border_radius defines the radius of the corner angle if the user wants to round the rectangle corner. We only support one border_radius across all the corners, but users can choose which corner to be rounded. > corner_flag (enum): defines which corner or corners to be rounded Here is a list of the supported corner flags: ```execute 200 from omni.ui import color as cl corner_flags = { "ui.CornerFlag.NONE": ui.CornerFlag.NONE, "ui.CornerFlag.TOP_LEFT": ui.CornerFlag.TOP_LEFT, "ui.CornerFlag.TOP_RIGHT": ui.CornerFlag.TOP_RIGHT, "ui.CornerFlag.BOTTOM_LEFT": ui.CornerFlag.BOTTOM_LEFT, "ui.CornerFlag.BOTTOM_RIGHT": ui.CornerFlag.BOTTOM_RIGHT, "ui.CornerFlag.TOP": ui.CornerFlag.TOP, "ui.CornerFlag.BOTTOM": ui.CornerFlag.BOTTOM, "ui.CornerFlag.LEFT": ui.CornerFlag.LEFT, "ui.CornerFlag.RIGHT": ui.CornerFlag.RIGHT, "ui.CornerFlag.ALL": ui.CornerFlag.ALL, } with ui.ScrollingFrame( height=100, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, style={"ScrollingFrame": {"background_color": cl.transparent}}, ): with ui.HStack(): for key, value in corner_flags.items(): with ui.ZStack(): ui.Rectangle(name="table") with ui.VStack(style={"VStack": {"margin": 10}}): ui.Rectangle( style={"background_color": cl("#aa4444"), "border_radius": 20.0, "corner_flag": value} ) ui.Spacer(height=10) ui.Label(key, style={"color": cl.white, "font_size": 12}, alignment=ui.Alignment.CENTER) ``` Here are a few examples of Rectangle using different selections of styles: Default rectangle which is scaled to fit: ```execute 200 with ui.Frame(height=20): ui.Rectangle(name="default") ``` This rectangle uses its own style to control colors and shape. Notice how three colors "background_color", "border_color" and "border_color" are affecting the look of the rectangle: ```execute 200 from omni.ui import color as cl with ui.Frame(height=40): ui.Rectangle(style={"Rectangle":{ "background_color":cl("#aa4444"), "border_color":cl("#22FF22"), "background_gradient_color": cl("#4444aa"), "border_width": 2.0, "border_radius": 5.0}}) ``` This rectangle uses fixed width and height. Notice the `border_color` is not doing anything if `border_width` is not defined. ```execute 200 from omni.ui import color as cl with ui.Frame(height=20): ui.Rectangle(width=40, height=10, style={"background_color":cl(0.6), "border_color":cl("#ff2222")}) ``` Compose with ZStack for an advanced look ```execute 200 from omni.ui import color as cl with ui.Frame(height=20): with ui.ZStack(height=20): ui.Rectangle(width=150, style={"background_color":cl(0.6), "border_color":cl(0.1), "border_width": 1.0, "border_radius": 8.0} ) with ui.HStack(): ui.Spacer(width=10) ui.Image("resources/icons/Cloud.png", width=20, height=20 ) ui.Label( "Search Field", style={"color":cl(0.875)}) ``` ## FreeRectangle FreeRectangle is a rectangle whose width and height will be determined by other widgets. The supported style list is the same as Rectangle. Here is an example of a FreeRectangle with style following two draggable circles: ```execute 200 from omni.ui import color as cl with ui.Frame(height=200): with ui.ZStack(): # Four draggable rectangles that represent the control points with ui.Placer(draggable=True, offset_x=0, offset_y=0): control1 = ui.Circle(width=10, height=10) with ui.Placer(draggable=True, offset_x=150, offset_y=150): control2 = ui.Circle(width=10, height=10) # The rectangle that fits to the control points ui.FreeRectangle(control1, control2, style={ "background_color":cl(0.6), "border_color":cl(0.1), "border_width": 1.0, "border_radius": 8.0}) ``` ## Circle You can use Circle to draw a circular shape. Circle doesn't have any other style except the common style for shapes. Here is some of the properties you can customize on Circle: > size_policy (enum): there are two types of the size_policy, fixed and stretch. * ui.CircleSizePolicy.FIXED: the size of the circle is defined by the radius and is fixed without being affected by the parent scaling. * ui.CircleSizePolicy.STRETCH: the size of the circle is defined by the parent and will be stretched if the parent widget size changed. > alignment (enum): the position of the circle in the parent defined space > arc (enum): this property defines the way to draw a half or a quarter of the circle. Here is a list of the supported Alignment and Arc value for the Circle: ```execute 200 from omni.ui import color as cl alignments = { "ui.Alignment.CENTER": ui.Alignment.CENTER, "ui.Alignment.LEFT_TOP": ui.Alignment.LEFT_TOP, "ui.Alignment.LEFT_CENTER": ui.Alignment.LEFT_CENTER, "ui.Alignment.LEFT_BOTTOM": ui.Alignment.LEFT_BOTTOM, "ui.Alignment.CENTER_TOP": ui.Alignment.CENTER_TOP, "ui.Alignment.CENTER_BOTTOM": ui.Alignment.CENTER_BOTTOM, "ui.Alignment.RIGHT_TOP": ui.Alignment.RIGHT_TOP, "ui.Alignment.RIGHT_CENTER": ui.Alignment.RIGHT_CENTER, "ui.Alignment.RIGHT_BOTTOM": ui.Alignment.RIGHT_BOTTOM, } ui.Label("Alignment: ") with ui.ScrollingFrame( height=150, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, style={"ScrollingFrame": {"background_color": cl.transparent}}, ): with ui.HStack(): for key, value in alignments.items(): with ui.ZStack(): ui.Rectangle(name="table") with ui.VStack(style={"VStack": {"margin": 10}}, spacing=10): with ui.ZStack(): ui.Rectangle(name="table", style={"border_color":cl.white, "border_width": 1.0}) ui.Circle( radius=10, size_policy=ui.CircleSizePolicy.FIXED, name="orientation", alignment=value, style={"background_color": cl("#aa4444")}, ) ui.Label(key, style={"color": cl.white, "font_size": 12}, alignment=ui.Alignment.CENTER) ui.Spacer(height=10) ui.Label("Arc: ") with ui.ScrollingFrame( height=150, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, style={"ScrollingFrame": {"background_color": cl.transparent}}, ): with ui.HStack(): for key, value in alignments.items(): with ui.ZStack(): ui.Rectangle(name="table") with ui.VStack(style={"VStack": {"margin": 10}}, spacing=10): with ui.ZStack(): ui.Rectangle(name="table", style={"border_color":cl.white, "border_width": 1.0}) ui.Circle( radius=10, size_policy=ui.CircleSizePolicy.FIXED, name="orientation", arc=value, style={ "background_color": cl("#aa4444"), "border_color": cl.blue, "border_width": 2, }, ) ui.Label(key, style={"color": cl.white, "font_size": 12}, alignment=ui.Alignment.CENTER) ``` Default circle which is scaled to fit, the alignment is centered: ```execute 200 with ui.Frame(height=20): ui.Circle(name="default") ``` This circle is scaled to fit with 100 height: ```execute 200 with ui.Frame(height=100): ui.Circle(name="default") ``` This circle has a fixed radius of 20, the alignment is LEFT_CENTER: ```execute 200 from omni.ui import color as cl style = {"Circle": {"background_color": cl("#1111ff"), "border_color": cl("#cc0000"), "border_width": 4}} with ui.Frame(height=100, style=style): with ui.HStack(): ui.Rectangle(width=40, style={"background_color": cl.white}) ui.Circle(radius=20, size_policy=ui.CircleSizePolicy.FIXED, alignment=ui.Alignment.LEFT_CENTER) ``` This circle has a fixed radius of 10, the alignment is RIGHT_CENTER ```execute 200 from omni.ui import color as cl style = {"Circle": {"background_color": cl("#ff1111"), "border_color": cl.blue, "border_width": 2}} with ui.Frame(height=100, width=200, style=style): with ui.ZStack(): ui.Rectangle(style={"background_color": cl(0.4)}) ui.Circle(radius=10, size_policy=ui.CircleSizePolicy.FIXED, alignment=ui.Alignment.RIGHT_CENTER) ``` This circle has a fixed radius of 10, it has all the same style as the previous one, except its size_policy is `ui.CircleSizePolicy.STRETCH` ```execute 200 from omni.ui import color as cl style = {"Circle": {"background_color": cl("#ff1111"), "border_color": cl.blue, "border_width": 2}} with ui.Frame(height=100, width=200, style=style): with ui.ZStack(): ui.Rectangle(style={"background_color": cl(0.4)}) ui.Circle(radius=10, size_policy=ui.CircleSizePolicy.STRETCH, alignment=ui.Alignment.RIGHT_CENTER) ``` ## FreeCircle FreeCircle is a circle whose radius will be determined by other widgets. The supported style list is the same as Circle. Here is an example of a FreeCircle with style following two draggable rectangles: ```execute 200 from omni.ui import color as cl with ui.Frame(height=200): with ui.ZStack(): # Four draggable rectangles that represent the control points with ui.Placer(draggable=True, offset_x=0, offset_y=0): control1 = ui.Rectangle(width=10, height=10) with ui.Placer(draggable=True, offset_x=150, offset_y=150): control2 = ui.Rectangle(width=10, height=10) # The rectangle that fits to the control points ui.FreeCircle(control1, control2, style={ "background_color":cl.transparent, "border_color":cl.red, "border_width": 2.0}) ``` ## Ellipse Ellipse is drawn in a rectangle bounding box, and It is always scaled to fit the rectangle's width and height. Ellipse doesn't have any other style except the common style for shapes. Default ellipse is scaled to fit: ```execute 200 with ui.Frame(height=20, width=150): ui.Ellipse(name="default") ``` Stylish ellipse with border and colors: ```execute 200 from omni.ui import color as cl style = {"Ellipse": {"background_color": cl("#1111ff"), "border_color": cl("#cc0000"), "border_width": 4}} with ui.Frame(height=100, width=50): ui.Ellipse(style=style) ``` ## FreeEllipse FreeEllipse is an ellipse whose width and height will be determined by other widgets. The supported style list is the same as Ellipse. Here is an example of a FreeEllipse with style following two draggable circles: ```execute 200 from omni.ui import color as cl with ui.Frame(height=200): with ui.ZStack(): # Four draggable rectangles that represent the control points with ui.Placer(draggable=True, offset_x=0, offset_y=0): control1 = ui.Circle(width=10, height=10) with ui.Placer(draggable=True, offset_x=150, offset_y=200): control2 = ui.Circle(width=10, height=10) # The rectangle that fits to the control points ui.FreeEllipse(control1, control2, style={ "background_color":cl.purple}) ``` ## Triangle You can use Triangle to draw Triangle shape. Triangle doesn't have any other style except the common style for shapes. Here is some of the properties you can customize on Triangle: > alignment (enum): the alignment defines where the tip of the triangle is, base will be at the opposite side Here is a list of the supported alignment value for the triangle: ```execute 200 from omni.ui import color as cl alignments = { "ui.Alignment.LEFT_TOP": ui.Alignment.LEFT_TOP, "ui.Alignment.LEFT_CENTER": ui.Alignment.LEFT_CENTER, "ui.Alignment.LEFT_BOTTOM": ui.Alignment.LEFT_BOTTOM, "ui.Alignment.CENTER_TOP": ui.Alignment.CENTER_TOP, "ui.Alignment.CENTER_BOTTOM": ui.Alignment.CENTER_BOTTOM, "ui.Alignment.RIGHT_TOP": ui.Alignment.RIGHT_TOP, "ui.Alignment.RIGHT_CENTER": ui.Alignment.RIGHT_CENTER, "ui.Alignment.RIGHT_BOTTOM": ui.Alignment.RIGHT_BOTTOM, } colors = [cl.red, cl.yellow, cl.purple, cl("#ff0ff0"), cl.green, cl("#f00fff"), cl("#fff000"), cl("#aa3333")] index = 0 with ui.ScrollingFrame( height=160, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, style={"ScrollingFrame": {"background_color": cl.transparent}}, ): with ui.HStack(): for key, value in alignments.items(): with ui.ZStack(): ui.Rectangle(name="table") with ui.VStack(style={"VStack": {"margin": 10}}): color = colors[index] index = index + 1 ui.Triangle(alignment=value, style={"Triangle":{"background_color": color}}) ui.Label(key, style={"color": cl.white, "font_size": 12}, alignment=ui.Alignment.CENTER, height=20) ``` Here are a few examples of Triangle using different selections of styles: The triangle is scaled to fit, base on the left and tip on the center right. Users can define the border_color and border_width but without background_color to make the triangle look like it's drawn in wireframe style. ```execute 200 from omni.ui import color as cl style = { "Triangle::default": { "background_color": cl.green, "border_color": cl.white, "border_width": 1 }, "Triangle::transparent": { "border_color": cl.purple, "border_width": 4, }, } with ui.Frame(height=100, width=200, style=style): with ui.HStack(spacing=10, style={"margin": 5}): ui.Triangle(name="default") ui.Triangle(name="transparent", alignment=ui.Alignment.CENTER_TOP) ``` ## FreeTriangle FreeTriangle is a triangle whose width and height will be determined by other widgets. The supported style list is the same as Triangle. Here is an example of a FreeTriangle with style following two draggable rectangles. The default alignment is `ui.Alignment.RIGHT_CENTER`. We make the alignment as `ui.Alignment.CENTER_BOTTOM`. ```execute 200 from omni.ui import color as cl with ui.Frame(height=200): with ui.ZStack(): # Four draggable rectangles that represent the control points with ui.Placer(draggable=True, offset_x=0, offset_y=0): control1 = ui.Rectangle(width=10, height=10) with ui.Placer(draggable=True, offset_x=150, offset_y=200): control2 = ui.Rectangle(width=10, height=10) # The rectangle that fits to the control points ui.FreeTriangle(control1, control2, alignment=ui.Alignment.CENTER_BOTTOM, style={ "background_color":cl.blue, "border_color":cl.red, "border_width": 2.0}) ```
16,520
Markdown
43.292225
318
0.656416
omniverse-code/kit/exts/omni.kit.documentation.ui.style/docs/buttons.md
# Buttons and Images ## Common Styling for Buttons and Images Here is a list of common style you can customize on Buttons and Images: > border_color (color): the border color if the button or image background has a border > border_radius (float): the border radius if the user wants to round the button or image > border_width (float): the border width if the button or image or image background has a border > margin (float): the distance between the widget content and the parent widget defined boundary > margin_width (float): the width distance between the widget content and the parent widget defined boundary > margin_height (float): the height distance between the widget content and the parent widget defined boundary ## Button The Button widget provides a command button. Click a button to execute a command. The command button is perhaps the most commonly used widget in any graphical user interface. It is rectangular and typically displays a text label or image describing its action. Except the common style for Buttons and Images, here is a list of styles you can customize on Button: > background_color (color): the background color of the button > padding (float): the distance between the content widgets (e.g. Image or Label) and the border of the button > stack_direction (enum): defines how the content widgets (e.g. Image or Label) on the button are placed. There are 6 types of stack_directions supported * ui.Direction.TOP_TO_BOTTOM : layout from top to bottom * ui.Direction.BOTTOM_TO_TOP : layout from bottom to top * ui.Direction.LEFT_TO_RIGHT : layout from left to right * ui.Direction.RIGHT_TO_LEFT : layout from right to left * ui.Direction.BACK_TO_FRONT : layout from back to front * ui.Direction.FRONT_TO_BACK : layout from front to back To control the style of the button content, you can customize `Button.Image` when image on button and `Button.Label` when text on button. Here is an example showing a list of buttons with different types of the stack directions: ```execute 200 from omni.ui import color as cl direction_flags = { "ui.Direction.TOP_TO_BOTTOM": ui.Direction.TOP_TO_BOTTOM, "ui.Direction.BOTTOM_TO_TOP": ui.Direction.BOTTOM_TO_TOP, "ui.Direction.LEFT_TO_RIGHT": ui.Direction.LEFT_TO_RIGHT, "ui.Direction.RIGHT_TO_LEFT": ui.Direction.RIGHT_TO_LEFT, "ui.Direction.BACK_TO_FRONT": ui.Direction.BACK_TO_FRONT, "ui.Direction.FRONT_TO_BACK": ui.Direction.FRONT_TO_BACK, } with ui.ScrollingFrame( height=50, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, style={"ScrollingFrame": {"background_color": cl.transparent}}, ): with ui.HStack(): for key, value in direction_flags.items(): button_style = {"Button": {"stack_direction": value}} ui_button = ui.Button( key, image_url="resources/icons/Nav_Flymode.png", image_width=24, height=40, style=button_style ) ``` Here is an example of two buttons. Pressing the second button makes the name of the first button longer. And press the first button makes the name of itself shorter: ```execute 200 from omni.ui import color as cl style_system = { "Button": { "background_color": cl(0.85), "border_color": cl.yellow, "border_width": 2, "border_radius": 5, "padding": 5, }, "Button.Label": {"color": cl.red, "font_size": 17}, "Button:hovered": {"background_color": cl("#E5F1FB"), "border_color": cl("#0078D7"), "border_width": 2.0}, "Button:pressed": {"background_color": cl("#CCE4F7"), "border_color": cl("#005499"), "border_width": 2.0}, } def make_longer_text(button): """Set the text of the button longer""" button.text = "Longer " + button.text def make_shorter_text(button): """Set the text of the button shorter""" splitted = button.text.split(" ", 1) button.text = splitted[1] if len(splitted) > 1 else splitted[0] with ui.HStack(style=style_system): btn_with_text = ui.Button("Text", width=0) ui.Button("Press me", width=0, clicked_fn=lambda b=btn_with_text: make_longer_text(b)) btn_with_text.set_clicked_fn(lambda b=btn_with_text: make_shorter_text(b)) ``` Here is an example where you can tweak most of the Button's style and see the results: ```execute 200 from omni.ui import color as cl style = { "Button": {"stack_direction": ui.Direction.TOP_TO_BOTTOM}, "Button.Image": { "color": cl("#99CCFF"), "image_url": "resources/icons/Learn_128.png", "alignment": ui.Alignment.CENTER, }, "Button.Label": {"alignment": ui.Alignment.CENTER}, } def direction(model, button, style=style): value = model.get_item_value_model().get_value_as_int() direction = ( ui.Direction.TOP_TO_BOTTOM, ui.Direction.BOTTOM_TO_TOP, ui.Direction.LEFT_TO_RIGHT, ui.Direction.RIGHT_TO_LEFT, ui.Direction.BACK_TO_FRONT, ui.Direction.FRONT_TO_BACK, )[value] style["Button"]["stack_direction"] = direction button.set_style(style) def align(model, button, image, style=style): value = model.get_item_value_model().get_value_as_int() alignment = ( ui.Alignment.LEFT_TOP, ui.Alignment.LEFT_CENTER, ui.Alignment.LEFT_BOTTOM, ui.Alignment.CENTER_TOP, ui.Alignment.CENTER, ui.Alignment.CENTER_BOTTOM, ui.Alignment.RIGHT_TOP, ui.Alignment.RIGHT_CENTER, ui.Alignment.RIGHT_BOTTOM, )[value] if image: style["Button.Image"]["alignment"] = alignment else: style["Button.Label"]["alignment"] = alignment button.set_style(style) def layout(model, button, padding, style=style): if padding == 0: padding = "padding" elif padding == 1: padding = "margin" elif padding == 2: padding = "margin_width" else: padding = "margin_height" style["Button"][padding] = model.get_value_as_float() button.set_style(style) def spacing(model, button): button.spacing = model.get_value_as_float() button = ui.Button("Label", style=style, width=64, height=64) with ui.HStack(width=ui.Percent(50)): ui.Label('"Button": {"stack_direction"}', name="text") options = ( 0, "TOP_TO_BOTTOM", "BOTTOM_TO_TOP", "LEFT_TO_RIGHT", "RIGHT_TO_LEFT", "BACK_TO_FRONT", "FRONT_TO_BACK", ) model = ui.ComboBox(*options).model model.add_item_changed_fn(lambda m, i, b=button: direction(m, b)) alignment = ( 4, "LEFT_TOP", "LEFT_CENTER", "LEFT_BOTTOM", "CENTER_TOP", "CENTER", "CENTER_BOTTOM", "RIGHT_TOP", "RIGHT_CENTER", "RIGHT_BOTTOM", ) with ui.HStack(width=ui.Percent(50)): ui.Label('"Button.Image": {"alignment"}', name="text") model = ui.ComboBox(*alignment).model model.add_item_changed_fn(lambda m, i, b=button: align(m, b, 1)) with ui.HStack(width=ui.Percent(50)): ui.Label('"Button.Label": {"alignment"}', name="text") model = ui.ComboBox(*alignment).model model.add_item_changed_fn(lambda m, i, b=button: align(m, b, 0)) with ui.HStack(width=ui.Percent(50)): ui.Label("padding", name="text") model = ui.FloatSlider(min=0, max=500).model model.add_value_changed_fn(lambda m, b=button: layout(m, b, 0)) with ui.HStack(width=ui.Percent(50)): ui.Label("margin", name="text") model = ui.FloatSlider(min=0, max=500).model model.add_value_changed_fn(lambda m, b=button: layout(m, b, 1)) with ui.HStack(width=ui.Percent(50)): ui.Label("margin_width", name="text") model = ui.FloatSlider(min=0, max=500).model model.add_value_changed_fn(lambda m, b=button: layout(m, b, 2)) with ui.HStack(width=ui.Percent(50)): ui.Label("margin_height", name="text") model = ui.FloatSlider(min=0, max=500).model model.add_value_changed_fn(lambda m, b=button: layout(m, b, 3)) with ui.HStack(width=ui.Percent(50)): ui.Label("Button.spacing", name="text") model = ui.FloatSlider(min=0, max=50).model model.add_value_changed_fn(lambda m, b=button: spacing(m, b)) ``` ## Radio Button RadioButton is the widget that allows the user to choose only one from a predefined set of mutually exclusive options. RadioButtons are arranged in collections of two or more buttons within a RadioCollection, which is the central component of the system and controls the behavior of all the RadioButtons in the collection. Except the common style for Buttons and Images, here is a list of styles you can customize on RadioButton: > background_color (color): the background color of the RadioButton > padding (float): the distance between the the RadioButton content widget (e.g. Image) and the RadioButton border To control the style of the button image, you can customize `RadioButton.Image`. For example RadioButton.Image's image_url defines the image when it's not checked. You can define the image for checked status with `RadioButton.Image:checked` style. Here is an example of RadioCollection which contains 5 RadioButtons with style. Also there is an IntSlider which shares the model with the RadioCollection, so that when RadioButton value or the IntSlider value changes, the other one will update too. ```execute 200 from omni.ui import color as cl style = { "RadioButton": { "background_color": cl.cyan, "margin_width": 2, "padding": 1, "border_radius": 0, "border_color": cl.white, "border_width": 1.0}, "RadioButton.Image": { "image_url": f"../exts/omni.kit.documentation.ui.style/icons/radio_off.svg", }, "RadioButton.Image:checked": { "image_url": f"../exts/omni.kit.documentation.ui.style/icons/radio_on.svg"}, } collection = ui.RadioCollection() for i in range(5): with ui.HStack(style=style): ui.RadioButton(radio_collection=collection, width=30, height=30) ui.Label(f"Option {i}", name="text") ui.IntSlider(collection.model, min=0, max=4) ``` ## ToolButton ToolButton is functionally similar to Button, but provides a model that determines if the button is checked. This button toggles between checked (on) and unchecked (off) when the user clicks it. Here is an example of a ToolButton: ```execute 200 def update_label(model, label): checked = model.get_value_as_bool() label.text = f"The check status button is {checked}" with ui.VStack(spacing=5): model = ui.ToolButton(text="click", name="toolbutton", width=100).model checked = model.get_value_as_bool() label = ui.Label(f"The check status button is {checked}") model.add_value_changed_fn(lambda m, l=label: update_label(m, l)) ``` ## ColorWidget The ColorWidget is a button that displays the color from the item model and can open a picker window. The color dialog's function is to allow users to choose color. Except the common style for Buttons and Images, here is a list of styles you can customize on ColorWidget: > background_color (color): the background color of the tooltip widget when hover over onto the ColorWidget > color (color): the text color of the tooltip widget when hover over onto the ColorWidget Here is an example of a ColorWidget with three FloatFields. The ColorWidget model is shared with the FloatFields so that users can click and edit the field value to change the ColorWidget's color, and the value change of the ColorWidget will also reflect in the value change of the FloatFields. ```execute 200 from omni.ui import color as cl with ui.HStack(spacing=5): color_model = ui.ColorWidget(width=0, height=0, style={"ColorWidget":{ "border_width": 2, "border_color": cl.white, "border_radius": 4, "color": cl.pink, "margin": 2 }}).model for item in color_model.get_item_children(): component = color_model.get_item_value_model(item) ui.FloatField(component) ``` Here is an example of a ColorWidget with three FloatDrags. The ColorWidget model is shared with the FloatDrags so that users can drag the field value to change the color, and the value change of the ColorWidget will also reflect in the value change of the FloatDrags. ```execute 200 from omni.ui import color as cl with ui.HStack(spacing=5): color_model = ui.ColorWidget(0.125, 0.25, 0.5, width=0, height=0, style={ "background_color": cl.pink }).model for item in color_model.get_item_children(): component = color_model.get_item_value_model(item) ui.FloatDrag(component, min=0, max=1) ``` Here is an example of a ColorWidget with a ComboBox. The ColorWidget model is shared with the ComboBox. Only the value change of the ColorWidget will reflect in the value change of the ComboBox. ```execute 200 with ui.HStack(spacing=5): color_model = ui.ColorWidget(width=0, height=0).model ui.ComboBox(color_model) ``` Here is an interactive example with USD. You can create a Mesh in the Stage. Choose `Pixar Storm` as the render. Select the mesh and use this ColorWidget to change the color of the mesh. You can use `Ctrl+z` for undoing and `Ctrl+y` for redoing. ```execute 200 import omni.kit.commands from omni.usd.commands import UsdStageHelper from pxr import UsdGeom from pxr import Gf import omni.usd class SetDisplayColorCommand(omni.kit.commands.Command, UsdStageHelper): """ Change prim display color undoable **Command**. Unlike ChangePropertyCommand, it can undo property creation. Args: gprim (Gprim): Prim to change display color on. value: Value to change to. value: Value to undo to. """ def __init__(self, gprim: UsdGeom.Gprim, color: Any, prev: Any): self._gprim = gprim self._color = color self._prev = prev def do(self): color_attr = self._gprim.CreateDisplayColorAttr() color_attr.Set([self._color]) def undo(self): color_attr = self._gprim.GetDisplayColorAttr() if self._prev is None: color_attr.Clear() else: color_attr.Set([self._prev]) omni.kit.commands.register(SetDisplayColorCommand) class FloatModel(ui.SimpleFloatModel): def __init__(self, parent): super().__init__() self._parent = weakref.ref(parent) def begin_edit(self): parent = self._parent() parent.begin_edit(None) def end_edit(self): parent = self._parent() parent.end_edit(None) class USDColorItem(ui.AbstractItem): def __init__(self, model): super().__init__() self.model = model class USDColorModel(ui.AbstractItemModel): def __init__(self): super().__init__() # Create root model self._root_model = ui.SimpleIntModel() self._root_model.add_value_changed_fn(lambda a: self._item_changed(None)) # Create three models per component self._items = [USDColorItem(FloatModel(self)) for i in range(3)] for item in self._items: item.model.add_value_changed_fn(lambda a, item=item: self._on_value_changed(item)) # Omniverse contexts self._usd_context = omni.usd.get_context() self._selection = self._usd_context.get_selection() self._events = self._usd_context.get_stage_event_stream() self._stage_event_sub = self._events.create_subscription_to_pop( self._on_stage_event, name="omni.example.ui ColorWidget stage update" ) # Privates self._subscription = None self._gprim = None self._prev_color = None self._edit_mode_counter = 0 def _on_stage_event(self, event): """Called with subscription to pop""" if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): self._on_selection_changed() def _on_selection_changed(self): """Called when the user changes the selection""" selection = self._selection.get_selected_prim_paths() stage = self._usd_context.get_stage() self._subscription = None self._gprim = None # When TC runs tests, it's possible that stage is None if selection and stage: self._gprim = UsdGeom.Gprim.Get(stage, selection[0]) if self._gprim: color_attr = self._gprim.GetDisplayColorAttr() usd_watcher = omni.usd.get_watcher() self._subscription = usd_watcher.subscribe_to_change_info_path( color_attr.GetPath(), self._on_usd_changed ) # Change the widget color self._on_usd_changed() def _on_value_changed(self, item): """Called when the submodel is changed""" if not self._gprim: return if self._edit_mode_counter > 0: # Change USD only if we are in edit mode. color_attr = self._gprim.CreateDisplayColorAttr() color = Gf.Vec3f( self._items[0].model.get_value_as_float(), self._items[1].model.get_value_as_float(), self._items[2].model.get_value_as_float(), ) color_attr.Set([color]) self._item_changed(item) def _on_usd_changed(self, path=None): """Called with UsdWatcher when something in USD is changed""" color = self._get_current_color() or Gf.Vec3f(0.0) for i in range(len(self._items)): self._items[i].model.set_value(color[i]) def _get_current_color(self): """Returns color of the current object""" if self._gprim: color_attr = self._gprim.GetDisplayColorAttr() if color_attr: color_array = color_attr.Get() if color_array: return color_array[0] def get_item_children(self, item): """Reimplemented from the base class""" return self._items def get_item_value_model(self, item, column_id): """Reimplemented from the base class""" if item is None: return self._root_model return item.model def begin_edit(self, item): """ Reimplemented from the base class. Called when the user starts editing. """ if self._edit_mode_counter == 0: self._prev_color = self._get_current_color() self._edit_mode_counter += 1 def end_edit(self, item): """ Reimplemented from the base class. Called when the user finishes editing. """ self._edit_mode_counter -= 1 if not self._gprim or self._edit_mode_counter > 0: return color = Gf.Vec3f( self._items[0].model.get_value_as_float(), self._items[1].model.get_value_as_float(), self._items[2].model.get_value_as_float(), ) omni.kit.commands.execute("SetDisplayColor", gprim=self._gprim, color=color, prev=self._prev_color) with ui.HStack(spacing=5): ui.ColorWidget(USDColorModel(), width=0) ui.Label("Interactive ColorWidget with USD", name="text") ``` ## Image The Image type displays an image. The source of the image is specified as a URL using the source property. By default, specifying the width and height of the item makes the image to be scaled to fit that size. This behavior can be changed by setting the `fill_policy` property, allowing the image to be stretched or scaled instead. The property alignment controls how the scaled image is aligned in the parent defined space. Except the common style for Buttons and Images, here is a list of styles you can customize on Image: > image_url (str): the url path of the image source > color (color): the overlay color of the image > corner_flag (enum): defines which corner or corners to be rounded. The supported corner flags are the same as Rectangle since Image is eventually an image on top of a rectangle under the hood. > fill_policy (enum): defines how the Image fills the rectangle. There are three types of fill_policy * ui.FillPolicy.STRETCH: stretch the image to fill the entire rectangle. * ui.FillPolicy.PRESERVE_ASPECT_FIT: uniformly to fit the image without stretching or cropping. * ui.FillPolicy.PRESERVE_ASPECT_CROP: scaled uniformly to fill, cropping if necessary > alignment (enum): defines how the image is positioned in the parent defined space. There are 9 alignments supported which are quite self-explanatory. * ui.Alignment.LEFT_CENTER * ui.Alignment.LEFT_TOP * ui.Alignment.LEFT_BOTTOM * ui.Alignment.RIGHT_CENTER * ui.Alignment.RIGHT_TOP * ui.Alignment.RIGHT_BOTTOM * ui.Alignment.CENTER * ui.Alignment.CENTER_TOP * ui.Alignment.CENTER_BOTTOM Default Image is scaled uniformly to fit without stretching or cropping (ui.FillPolicy.PRESERVE_ASPECT_FIT), and aligned to ui.Alignment.CENTER: ```execute 200 source = "resources/desktop-icons/omniverse_512.png" with ui.Frame(width=200, height=100): ui.Image(source) ``` The image is stretched to fit and aligned to the left ```execute 200 source = "resources/desktop-icons/omniverse_512.png" with ui.Frame(width=200, height=100): ui.Image(source, fill_policy=ui.FillPolicy.STRETCH, alignment=ui.Alignment.LEFT_CENTER) ``` The image is scaled uniformly to fill, cropping if necessary and aligned to the top ```execute 200 source = "resources/desktop-icons/omniverse_512.png" with ui.Frame(width=200, height=100): ui.Image(source, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, alignment=ui.Alignment.CENTER_TOP) ``` The image is scaled uniformly to fit without cropping and aligned to the right. Notice the fill_policy and alignment are defined in style. ```execute 200 source = "resources/desktop-icons/omniverse_512.png" with ui.Frame(width=200, height=100): ui.Image(source, style={ "Image": { "fill_policy": ui.FillPolicy.PRESERVE_ASPECT_FIT, "alignment": ui.Alignment.RIGHT_CENTER, "margin": 5}}) ``` The image has rounded corners and an overlayed color. Note image_url is in the style dictionary. ```execute 200 from omni.ui import color as cl source = "resources/desktop-icons/omniverse_512.png" with ui.Frame(width=200, height=100): ui.Image(style={"image_url": source, "border_radius": 10, "color": cl("#5eb3ff")}) ``` The image is scaled uniformly to fill, cropping if necessary and aligned to the bottom, with a blue border. ```execute 200 from omni.ui import color as cl source = "resources/desktop-icons/omniverse_512.png" with ui.Frame(width=200, height=100): ui.Image( source, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, alignment=ui.Alignment.CENTER_BOTTOM, style={"Image":{ "border_width": 5, "border_color": cl("#1ab3ff"), "corner_flag": ui.CornerFlag.TOP, "border_radius": 15}}) ``` The image is arranged in a HStack with different margin styles defined. Note image_url is in the style dict. ```execute 200 source = "resources/desktop-icons/omniverse_512.png" with ui.Frame(height=100): with ui.HStack(spacing =5, style={"Image":{'image_url': source}}): ui.Image() ui.Image(style={"Image":{"margin_height": 15}}) ui.Image() ui.Image(style={"Image":{"margin_width": 20}}) ui.Image() ui.Image(style={"Image":{"margin": 10}}) ui.Image() ``` It's possible to set a different image per style state. And switch them depending on the mouse hovering, selection state, etc. ```execute 200 styles = [ { "": {"image_url": "resources/icons/Nav_Walkmode.png"}, ":hovered": {"image_url": "resources/icons/Nav_Flymode.png"}, }, { "": {"image_url": "resources/icons/Move_local_64.png"}, ":hovered": {"image_url": "resources/icons/Move_64.png"}, }, { "": {"image_url": "resources/icons/Rotate_local_64.png"}, ":hovered": {"image_url": "resources/icons/Rotate_global.png"}, }, ] def set_image(model, image): value = model.get_item_value_model().get_value_as_int() image.set_style(styles[value]) with ui.Frame(height=80): with ui.VStack(): image = ui.Image(width=64, height=64, style=styles[0]) with ui.HStack(width=ui.Percent(50)): ui.Label("Select a texture to display", name="text") model = ui.ComboBox(0, "Navigation", "Move", "Rotate").model model.add_item_changed_fn(lambda m, i, im=image: set_image(m, im)) ``` ## ImageWithProvider ImageWithProvider also displays an image just like Image. It is a much more advanced image widget. ImageWithProvider blocks until the image is loaded, Image doesn't block. Sometimes Image blinks because when the first frame is created, the image is not loaded. Users are recommended to use ImageWithProvider if the UI is updated pretty often. Because it doesn't blink when recreating. It has the almost the same style list as Image, except the fill_policy has different enum values. > fill_policy (enum): defines how the Image fills the rectangle. There are three types of fill_policy * ui.IwpFillPolicy.IWP_STRETCH: stretch the image to fill the entire rectangle. * ui.IwpFillPolicy.IWP_PRESERVE_ASPECT_FIT: uniformly to fit the image without stretching or cropping. * ui.IwpFillPolicy.IWP_PRESERVE_ASPECT_CROP: scaled uniformly to fill, cropping if necessary The image source comes from `ImageProvider` which could be `ByteImageProvider`, `RasterImageProvider` or `VectorImageProvider`. `RasterImageProvider` and `VectorImageProvider` are using image urls like Image. Here is an example taken from Image. Notice the fill_policy value difference. ```execute 200 from omni.ui import color as cl source = "resources/desktop-icons/omniverse_512.png" with ui.Frame(width=200, height=100): ui.ImageWithProvider( source, style={ "ImageWithProvider": { "border_width": 5, "border_color": cl("#1ab3ff"), "corner_flag": ui.CornerFlag.TOP, "border_radius": 15, "fill_policy": ui.IwpFillPolicy.IWP_PRESERVE_ASPECT_CROP, "alignment": ui.Alignment.CENTER_BOTTOM}}) ``` `ByteImageProvider` is really useful to create gradient images. Here is an example: ```execute 200 self._byte_provider = ui.ByteImageProvider() self._byte_provider.set_bytes_data([ 255, 0, 0, 255, # red 255, 255, 0, 255, # yellow 0, 255, 0, 255, # green 0, 255, 255, 255, # cyan 0, 0, 255, 255], # blue [5, 1]) # size with ui.Frame(height=20): ui.ImageWithProvider(self._byte_provider,fill_policy=ui.IwpFillPolicy.IWP_STRETCH) ``` ## Plot The Plot class displays a line or histogram image. The data of the image is specified as a data array or a provider function. Except the common style for Buttons and Images, here is a list of styles you can customize on Plot: > color (color): the color of the plot, line color in the line typed plot or rectangle bar color in the histogram typed plot > selected_color (color): the selected color of the plot, dot in the line typed plot and rectangle bar in the histogram typed plot > background_color (color): the background color of the plot > secondary_color (color): the color of the text and the border of the text box which shows the plot selection value > background_selected_color (color): the background color of the text box which shows the plot selection value Here are couple of examples of Plots: ```execute 200 import math from omni.ui import color as cl data = [] for i in range(360): data.append(math.cos(math.radians(i))) def on_data_provider(index): return math.sin(math.radians(index)) with ui.Frame(height=20): with ui.HStack(): plot_1 = ui.Plot(ui.Type.LINE, -1.0, 1.0, *data, width=360, height=100, style={"Plot":{ "color": cl.red, "background_color": cl(0.08), "secondary_color": cl("#aa1111"), "selected_color": cl.green, "background_selected_color": cl.white, "border_width":5, "border_color": cl.blue, "border_radius": 20 }}) ui.Spacer(width = 20) plot_2 = ui.Plot(ui.Type.HISTOGRAM, -1.0, 1.0, on_data_provider, 360, width=360, height=100, style={"Plot":{ "color": cl.blue, "background_color": cl("#551111"), "secondary_color": cl("#11AA11"), "selected_color": cl(0.67), "margin_height": 10, }}) plot_2.value_stride = 6 ```
28,831
Markdown
39.211994
424
0.660296
omniverse-code/kit/exts/omni.kit.documentation.ui.style/docs/CHANGELOG.md
# Changelog The documentation for omni.ui style ## [1.0.3] - 2022-10-20 ### Fixed - Fixed font session crash ### Added - The extension to the doc system ## [1.0.2] - 2022-07-20 ### Added - Order in Stack and use of content_clipping section - ToolButton section ## [1.0.1] - 2022-07-20 ### Changed - Added help menu API doc entrance - Clarified the window style ## [1.0.0] - 2022-06-15 ### Added - The initial documentation
428
Markdown
16.874999
52
0.675234
omniverse-code/kit/exts/omni.kit.documentation.ui.style/docs/overview.md
# Overview OmniUI style allows users to build customized widgets, make these widgets visually pleasant and functionally indicative with user interactions. Each widget has its own style to be tweaked with based on their use cases and behaviors, while they also follow the same syntax rules. The container widgets provide a customized style for the widgets layout, providing flexibility for the arrangement of elements. Each omni ui item has its own style to be tweaked with based on their use cases and behaviors, while they also follow the same syntax rules for the style definition. Shades are used to have different themes for the entire ui, e.g. dark themed ui and light themed ui. Omni.ui also supports different font styles and sizes. Different length units allows users to define the widgets accurate to exact pixel or proportional to the parent widget or siblings. Shapes are the most basic elements in the ui, which allows users to create stylish ui shapes, rectangles, circles, triangles, line and curve. Freeshapes are the extended shapes, which allows users to control some of the attributes dynamically through bounded widgets. Widgets are mostly a combination of shapes, images or texts, which are created to be stepping stones for the entire ui window. Each of the widget has its own style to be characterized. The container widgets provide a customized style for the widgets layout, providing flexibility for the arrangement of elements and possibility of creating more complicated and customized widgets.
1,528
Markdown
94.562494
287
0.816099
omniverse-code/kit/exts/omni.kit.documentation.ui.style/docs/window.md
# Window Widgets ## MainWindow The MainWindow represents the main window for an application. There should only be one MainWindow in each application. Here is a list of styles you can customize on MainWindow: > background_color (color): the background color of the main window. > margin_height (float): the height distance between the window content and the window border. > margin_width (float): the width distance between the window content and the window border. Here is an example of a main window with style. Click the button to show the main window. Since the example is running within a MainWindow already, creating a new MainWindow will not run correctly in this example, but it demonstrates how to set the style of the `MainWindow`. And note the style of MainWindow is not propagated to other windows. ```execute 200 from omni.ui import color as cl self._main_window = None self._window1 = None self._window2 = None def create_main_window(): if not self._main_window: self._main_window = ui.MainWindow() self._main_window.main_frame.set_style({ "MainWindow": { "background_color": cl.purple, "margin_height": 20, "margin_width": 10 }}) self._window1 = ui.Window("window 1", width=300, height=300) self._window2 = ui.Window("window 2", width=300, height=300) main_dockspace = ui.Workspace.get_window("DockSpace") self._window1.dock_in(main_dockspace, ui.DockPosition.SAME) self._window2.dock_in(main_dockspace, ui.DockPosition.SAME) self._window2.focus() self._window2.visible = True ui.Button("click for Main Window", width=180, clicked_fn=create_main_window) ``` ## Window The window is a child window of the MainWindow. And it can be docked. You can have any type of widgets as the window content widgets. Here is a list of styles you can customize on Window: > background_color (color): the background color of the window. > border_color (color): the border color if the window has a border. > border_radius (float): the radius of the corner angle if the user wants to round the window. > border_width (float): the border width if the window has a border. Here is an example of a window with style. Click the button to show the window. ```execute 200 from omni.ui import color as cl self._style_window_example = None def create_styled_window(): if not self._style_window_example: self._style_window_example = ui.Window("Styled Window Example", width=300, height=300) self._style_window_example.frame.set_style({ "Window": { "background_color": cl.blue, "border_radius": 10, "border_width": 5, "border_color": cl.red, }}) self._style_window_example.visible = True ui.Button("click for Styled Window", width=180, clicked_fn=create_styled_window) ``` Note that a window's style is set from its frame since ui.Window itself is not a widget. We can't set style to it like other widgets. ui.Window's frame is a normal ui.Frame widget which itself doesn't have styles like `background_color` or `border_radius` (see `Container Widgets`->`Frame`). We specifically interpret the input ui.Window's frame style as the window style here. Therefore, the window style is not propagated to the content widget either just like the MainWindow. If you want to set up a default style for the entire window. You should use `ui.style.default`. More details in `The Style Sheet Syntax` -> `Style Override` -> `Default style override`. ## Menu The Menu class provides a menu widget for use in menu bars, context menus, and other popup menus. It can be either a pull-down menu in a menu bar or a standalone context menu. Pull-down menus are shown by the menu bar when the user clicks on the respective item. Context menus are usually invoked by some special keyboard key or by right-clicking. Here is a list of styles you can customize on Menu: > color (color): the color of the menu text > background_color (color): the background color of sub menu window > background_selected_color (color): the background color when the current menu is selected > border_color (color): the border color of the sub menu window if it has a border > border_width (float): the border width of the sub menu window if it has a border > border_radius (float): the border radius of the sub menu window if user wants to round the sub menu window > padding (float): the padding size of the sub menu window Here is a list of styles you can customize on MenuItem: > color (color): the color of the menu Item text > background_selected_color (color): the background color when the current menu is selected Right click for the context menu with customized menu style: ```execute 200 from omni.ui import color as cl self.context_menu = None def show_context_menu(x, y, button, modifier, widget): if button != 1: return self.context_menu = ui.Menu("Context menu", style={ "Menu": { "background_color": cl.blue, "color": cl.pink, "background_selected_color": cl.green, "border_radius": 5, "border_width": 2, "border_color": cl.yellow, "padding": 15 }, "MenuItem": { "color": cl.white, "background_selected_color": cl.cyan}, "Separator": { "color": cl.red}, },) with self.context_menu: ui.MenuItem("Delete Shot") ui.Separator() ui.MenuItem("Attach Selected Camera") with ui.Menu("Sub-menu"): ui.MenuItem("One") ui.MenuItem("Two") ui.MenuItem("Three") ui.Separator() ui.MenuItem("Four") with ui.Menu("Five"): ui.MenuItem("Six") ui.MenuItem("Seven") self.context_menu.show() with ui.VStack(): button = ui.Button("Right click to context menu", height=0, width=0) button.set_mouse_pressed_fn(lambda x, y, b, m, widget=button: show_context_menu(x, y, b, m, widget)) ``` Left click for the push button menu with default menu style: ```execute 200 self.pushed_menu = None def show_pushed_menu(x, y, button, modifier, widget): self.pushed_menu = ui.Menu("Pushed menu") with self.pushed_menu: ui.MenuItem("Camera 1") ui.MenuItem("Camera 2") ui.MenuItem("Camera 3") ui.Separator() with ui.Menu("More Cameras"): ui.MenuItem("This Menu is Pushed") ui.MenuItem("and Aligned with a widget") self.pushed_menu.show_at( (int)(widget.screen_position_x), (int)(widget.screen_position_y + widget.computed_content_height) ) with ui.VStack(): button = ui.Button("Pushed Button Menu", height=0, width=0) button.set_mouse_pressed_fn(lambda x, y, b, m, widget=button: show_pushed_menu(x, y, b, m, widget)) ``` ### Separator Separator is a type of MenuItem which creates a separator line in the UI elements. From the above example, you can see the use of Separator in Menu. Here is a list of styles you can customize on Separator: > color (color): the color of the Separator ## MenuBar All the Windows in Omni.UI can have a MenuBar. To add a MenuBar to your window add this flag to your constructor: omni.ui.Window(flags=ui.WINDOW_FLAGS_MENU_BAR). The MenuBar object can then be accessed through the menu_bar read-only property on your window. A MenuBar is a container so it is built like a Frame or Stack but only takes Menu objects as children. You can leverage the 'priority' property on the Menu to order them. They will automatically be sorted when they are added, but if you change the priority of an item then you need to explicitly call sort(). MenuBar has exactly the same style list you can customize as Menu. Here is an example of MenuBar with style for the Window: ```execute 200 from omni.ui import color as cl style={"MenuBar": { "background_color": cl.blue, "color": cl.pink, "background_selected_color": cl.green, "border_radius": 2, "border_width": 1, "border_color": cl.yellow, "padding": 2}} self._window_menu_example = None def create_and_show_window_with_menu(): if not self._window_menu_example: self._window_menu_example = ui.Window( "Window Menu Example", width=300, height=300, flags=ui.WINDOW_FLAGS_MENU_BAR | ui.WINDOW_FLAGS_NO_BACKGROUND, ) menu_bar = self._window_menu_example.menu_bar menu_bar.style = style with menu_bar: with ui.Menu("File"): ui.MenuItem("Load") ui.MenuItem("Save") ui.MenuItem("Export") with ui.Menu("Window"): ui.MenuItem("Hide") with self._window_menu_example.frame: with ui.VStack(): ui.Button("This Window has a Menu") def show_hide_menu(menubar): menubar.visible = not menubar.visible ui.Button("Click here to show/hide Menu", clicked_fn=lambda m=menu_bar: show_hide_menu(m)) def add_menu(menubar): with menubar: with ui.Menu("New Menu"): ui.MenuItem("I don't do anything") ui.Button("Add New Menu", clicked_fn=lambda m=menu_bar: add_menu(m)) self._window_menu_example.visible = True with ui.HStack(width=0): ui.Button("window with MenuBar Example", width=180, clicked_fn=create_and_show_window_with_menu) ui.Label("this populates the menuBar", name="text", width=180, style={"margin_width": 10}) ```
9,911
Markdown
43.25
478
0.649379
omniverse-code/kit/exts/omni.kit.documentation.ui.style/docs/shades.md
# Shades Shades are used to have multiple named color palettes with the ability for runtime switch. For example, one App could have several ui themes users can switch during using the App. The shade can be defined with the following code: ```python cl.shade(cl("#FF6600"), red=cl("#0000FF"), green=cl("#66FF00")) ``` It can be assigned to the color style. It's possible to switch the color with the following command globally: ```python cl.set_shade("red") ``` ## Example ```execute 200 from omni.ui import color as cl from omni.ui import constant as fl def set_color(color): cl.example_color = color def set_width(value): fl.example_width = value cl.example_color = cl.green fl.example_width = 1.0 with ui.HStack(height=100, spacing=5): with ui.ZStack(): ui.Rectangle( style={ "background_color": cl.shade( "aqua", orange=cl.orange, another=cl.example_color, transparent=cl(0, 0, 0, 0), black=cl.black, ), "border_width": fl.shade(1, orange=4, another=8), "border_radius": fl.one, "border_color": cl.black, }, ) ui.Label( "ui.Rectangle(\n" "\tstyle={\n" '\t\t"background_color":\n' "\t\t\tcl.shade(\n" '\t\t\t\t"aqua",\n' "\t\t\t\torange=cl(1, 0.5, 0),\n" "\t\t\t\tanother=cl.example_color),\n" '\t\t"border_width":\n' "\t\t\tfl.shade(1, orange=4, another=8)})", alignment=ui.Alignment.CENTER, word_wrap=True, style={"color": cl.black, "margin": 15}, ) with ui.ZStack(): ui.Rectangle( style={ "background_color": cl.example_color, "border_width": fl.example_width, "border_radius": fl.one, "border_color": cl.black, } ) ui.Label( "ui.Rectangle(\n" "\tstyle={\n" '\t\t"background_color": cl.example_color,\n' '\t\t"border_width": fl.example_width)})', alignment=ui.Alignment.CENTER, word_wrap=True, style={"color": cl.black, "margin": 15}, ) with ui.VStack(style={"Button": {"background_color": cl("097EFF")}}): ui.Label("Click the following buttons to change the shader of the left rectangle") with ui.HStack(): ui.Button("cl.set_shade()", clicked_fn=partial(cl.set_shade, "")) ui.Button('cl.set_shade("orange")', clicked_fn=partial(cl.set_shade, "orange")) ui.Button('cl.set_shade("another")', clicked_fn=partial(cl.set_shade, "another")) ui.Label("Click the following buttons to change the border width of the right rectangle") with ui.HStack(): ui.Button("fl.example_width = 1", clicked_fn=partial(set_width, 1)) ui.Button("fl.example_width = 4", clicked_fn=partial(set_width, 4)) ui.Label("Click the following buttons to change the background color of both rectangles") with ui.HStack(): ui.Button('cl.example_color = "green"', clicked_fn=partial(set_color, "green")) ui.Button("cl.example_color = cl(0.8)", clicked_fn=partial(set_color, cl(0.8))) ## Double comment means hide from shippet ui.Spacer(height=15) ## ``` ## URL Shades Example It's also possible to use shades for specifying shortcuts to the images and style-based paths. ```execute 200 from omni.ui import color as cl from omni.ui.url_utils import url def set_url(url_path: str): url.example_url = url_path walk = "resources/icons/Nav_Walkmode.png" fly = "resources/icons/Nav_Flymode.png" url.example_url = walk with ui.HStack(height=100, spacing=5): with ui.ZStack(): ui.Image(style={"image_url": url.example_url}) ui.Label( 'ui.Image(\n\tstyle={"image_url": cl.example_url})\n', alignment=ui.Alignment.CENTER, word_wrap=True, style={"color": cl.black, "margin": 15}, ) with ui.ZStack(): ui.ImageWithProvider( style={ "image_url": url.shade( "resources/icons/Move_local_64.png", another="resources/icons/Move_64.png", orange="resources/icons/Rotate_local_64.png", ) } ) ui.Label( "ui.ImageWithProvider(\n" "\tstyle={\n" '\t\t"image_url":\n' "\t\t\tst.shade(\n" '\t\t\t\t"Move_local_64.png",\n' '\t\t\t\tanother="Move_64.png")})\n', alignment=ui.Alignment.CENTER, word_wrap=True, style={"color": cl.black, "margin": 15}, ) with ui.HStack(): # buttons to change the url for the image with ui.VStack(): ui.Button("url.example_url = Nav_Walkmode.png", clicked_fn=partial(set_url, walk)) ui.Button("url.example_url = Nav_Flymode.png", clicked_fn=partial(set_url, fly)) # buttons to switch between shades to different image with ui.VStack(): ui.Button("ui.set_shade()", clicked_fn=partial(ui.set_shade, "")) ui.Button('ui.set_shade("another")', clicked_fn=partial(ui.set_shade, "another")) ```
5,364
Markdown
33.612903
179
0.560962
omniverse-code/kit/exts/omni.kit.documentation.ui.style/docs/line.md
# Lines and Curves ## Common Style of Lines and Curves Here is a list of common style you can customize on all the Lines and Curves: > color (color): the color of the line or curve > border_width (float): the thickness of the line or curve ## Line Line is the simplest shape that represents a straight line. It has two points, color and thickness. You can use Line to draw line shapes. Line doesn't have any other style except the common style for Lines and Curves. Here is some of the properties you can customize on Line: > alignment (enum): the Alignment defines where the line is in parent defined space. It is always scaled to fit. Here is a list of the supported Alignment value for the line: ```execute 200 from omni.ui import color as cl style ={ "Rectangle::table": {"background_color": cl.transparent, "border_color": cl(0.8), "border_width": 0.25}, "Line::demo": {"color": cl("#007777"), "border_width": 3}, "ScrollingFrame": {"background_color": cl.transparent}, } alignments = { "ui.Alignment.LEFT": ui.Alignment.LEFT, "ui.Alignment.RIGHT": ui.Alignment.RIGHT, "ui.Alignment.H_CENTER": ui.Alignment.H_CENTER, "ui.Alignment.TOP": ui.Alignment.TOP, "ui.Alignment.BOTTOM": ui.Alignment.BOTTOM, "ui.Alignment.V_CENTER": ui.Alignment.V_CENTER, } with ui.ScrollingFrame( height=100, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, style=style, ): with ui.HStack(height=100): for key, value in alignments.items(): with ui.ZStack(): ui.Rectangle(name="table") with ui.VStack(style={"VStack": {"margin": 10}}, spacing=10): ui.Line(name="demo", alignment=value) ui.Label(key, style={"color": cl.white, "font_size": 12}, alignment=ui.Alignment.CENTER) ``` By default, the line is scaled to fit. ```execute 200 from omni.ui import color as cl style = {"Line::default": {"color": cl.red, "border_width": 1}} with ui.Frame(height=50, style=style): ui.Line(name="default") ``` Users can define the color and border_width to make customized lines. ```execute 200 from omni.ui import color as cl with ui.Frame(height=50): with ui.ZStack(width=200): ui.Rectangle(style={"background_color": cl(0.4)}) ui.Line(alignment=ui.Alignment.H_CENTER, style={"border_width":5, "color": cl("#880088")}) ``` ## FreeLine FreeLine is a line whose length will be determined by other widgets. The supported style list is the same as Line. Here is an example of a FreeLine with style following two draggable circles. Notice the control widgets are not the start and end points of the line. By default, the alignment of the line is `ui.Alighment.V_CENTER`, and the line direction won't be changed by the control widgets. ```execute 200 from omni.ui import color as cl with ui.Frame(height=200): with ui.ZStack(): # Four draggable rectangles that represent the control points with ui.Placer(draggable=True, offset_x=0, offset_y=0): control1 = ui.Circle(width=10, height=10) with ui.Placer(draggable=True, offset_x=150, offset_y=200): control2 = ui.Circle(width=10, height=10) # The rectangle that fits to the control points ui.FreeLine(control1, control2, style={"color":cl.yellow}) ``` ## BezierCurve BezierCurve is a shape drawn with multiple lines which has a bent or turns in it. They are used to model smooth curves that can be scaled indefinitely. BezierCurve doesn't have any other style except the common style for Lines and Curves. Here is a BezierCurve with style: ```execute 200 from omni.ui import color as cl style = {"BezierCurve": {"color": cl.red, "border_width": 2}} ui.Spacer(height=2) with ui.Frame(height=50, style=style): ui.BezierCurve() ui.Spacer(height=2) ``` ## FreeBezierCurve FreeBezierCurve is using two widgets to get the position of the curve ends. This is super useful to build graph connections. The supported style list is the same as BezierCurve. Here is an example of a FreeBezierCurve which is controlled by 4 control points. ```execute 200 from omni.ui import color as cl with ui.ZStack(height=400): # The Bezier tangents tangents = [(50, 50), (-50, -50)] # Four draggable rectangles that represent the control points placer1 = ui.Placer(draggable=True, offset_x=0, offset_y=0) with placer1: rect1 = ui.Rectangle(width=20, height=20) placer2 = ui.Placer(draggable=True, offset_x=50, offset_y=50) with placer2: rect2 = ui.Rectangle(width=20, height=20) placer3 = ui.Placer(draggable=True, offset_x=100, offset_y=100) with placer3: rect3 = ui.Rectangle(width=20, height=20) placer4 = ui.Placer(draggable=True, offset_x=150, offset_y=150) with placer4: rect4 = ui.Rectangle(width=20, height=20) # The bezier curve curve = ui.FreeBezierCurve(rect1, rect4, style={"color": cl.red, "border_width": 5}) curve.start_tangent_width = ui.Pixel(tangents[0][0]) curve.start_tangent_height = ui.Pixel(tangents[0][1]) curve.end_tangent_width = ui.Pixel(tangents[1][0]) curve.end_tangent_height = ui.Pixel(tangents[1][1]) # The logic of moving the control points def left_moved(_): x = placer1.offset_x y = placer1.offset_y tangent = tangents[0] placer2.offset_x = x + tangent[0] placer2.offset_y = y + tangent[1] def right_moved(_): x = placer4.offset_x y = placer4.offset_y tangent = tangents[1] placer3.offset_x = x + tangent[0] placer3.offset_y = y + tangent[1] def left_tangent_moved(_): x1 = placer1.offset_x y1 = placer1.offset_y x2 = placer2.offset_x y2 = placer2.offset_y tangent = (x2 - x1, y2 - y1) tangents[0] = tangent curve.start_tangent_width = ui.Pixel(tangent[0]) curve.start_tangent_height = ui.Pixel(tangent[1]) def right_tangent_moved(_): x1 = placer4.offset_x y1 = placer4.offset_y x2 = placer3.offset_x y2 = placer3.offset_y tangent = (x2 - x1, y2 - y1) tangents[1] = tangent curve.end_tangent_width = ui.Pixel(tangent[0]) curve.end_tangent_height = ui.Pixel(tangent[1]) # Callback for moving the control points placer1.set_offset_x_changed_fn(left_moved) placer1.set_offset_y_changed_fn(left_moved) placer2.set_offset_x_changed_fn(left_tangent_moved) placer2.set_offset_y_changed_fn(left_tangent_moved) placer3.set_offset_x_changed_fn(right_tangent_moved) placer3.set_offset_y_changed_fn(right_tangent_moved) placer4.set_offset_x_changed_fn(right_moved) placer4.set_offset_y_changed_fn(right_moved) ```
6,767
Markdown
38.811764
279
0.67578
omniverse-code/kit/exts/omni.kit.documentation.ui.style/docs/README.md
# The documentation for omni.ui style The interactive documentation for omni.ui style
86
Markdown
27.999991
47
0.825581
omniverse-code/kit/exts/omni.kit.documentation.ui.style/docs/units.md
# Length Units The Framework UI offers several different units for expressing length: Pixel, Percent and Fraction. There is no restriction on where certain units should be used. ## Pixel Pixel is the size in pixels and scaled with the HiDPI scale factor. Pixel is the default unit. If a number is not specified to be a certain unit, it is Pixel. e.g. `width=100` meaning `width=ui.Pixel(100)`. ```execute 200 with ui.HStack(): ui.Button("40px", width=ui.Pixel(40)) ui.Button("60px", width=ui.Pixel(60)) ui.Button("100px", width=100) ui.Button("120px", width=120) ui.Button("150px", width=150) ``` ## Percent Percent and Fraction units make it possible to specify sizes relative to the parent size. 1 Percent is 1/100 of the parent size. ```execute 200 with ui.HStack(): ui.Button("5%", width=ui.Percent(5)) ui.Button("10%", width=ui.Percent(10)) ui.Button("15%", width=ui.Percent(15)) ui.Button("20%", width=ui.Percent(20)) ui.Button("25%", width=ui.Percent(25)) ``` ## Fraction Fraction length is made to take the available space of the parent widget and then divide it among all the child widgets with Fraction length in proportion to their Fraction factor. ```execute 200 with ui.HStack(): ui.Button("One", width=ui.Fraction(1)) ui.Button("Two", width=ui.Fraction(2)) ui.Button("Three", width=ui.Fraction(3)) ui.Button("Four", width=ui.Fraction(4)) ui.Button("Five", width=ui.Fraction(5)) ```
1,462
Markdown
36.51282
206
0.697674
omniverse-code/kit/exts/omni.graph.docs/docs/tutorials/tutorial28.rst
.. _ogn_tutorial_simple_ogn_compute_vectorized_node: Tutorial 28 - Node with simple OGN computeVectorized ==================================================== This tutorial demonstrates how to compose nodes that implements a very simple computeVectorized function. It shows how to access the data, using the different available methods. OgnTutorialVectorizedPassthrough.ogn ------------------------------------ The *ogn* file shows the implementation of a node named "omni.graph.tutorials.TutorialVectorizedPassThrough", which takes input of a floating point value, and just copy it to its output. .. literalinclude:: ../../../../../source/extensions/omni.graph.tutorials/tutorials/tutorial28/OgnTutorialVectorizedPassthrough.ogn :linenos: :language: json OgnTutorialVectorizedPassthrough.cpp ------------------------------------ The *cpp* file contains the implementation of the node. It takes a floating point input and just copy it to its output, demonstrating how to handle a vectorized compute. It shows what would be the implementation for a regular `compute` function, and the different way it could implement a `computeVectorized` function. - method #1: by switching the entire database to the next instance, while performing the computation in a loop - method #2: by directly indexing attributes for the right instance in a loop - method #3: by retrieving the raw data, and working directly with it .. literalinclude:: ../../../../../source/extensions/omni.graph.tutorials/tutorials/tutorial28/OgnTutorialVectorizedPassthrough.cpp :linenos: :language: c++
1,593
reStructuredText
52.133332
138
0.723792
omniverse-code/kit/exts/omni.graph.docs/docs/tutorials/tutorial29.rst
.. _ogn_tutorial_simple_abi_compute_vectorized_node: Tutorial 29 - Node with simple ABI computeVectorized ==================================================== This tutorial demonstrates how to compose nodes that implements a very simple computeVectorized function using directly ABIs. It shows how to access the data, using the different available methods. OgnTutorialVectorizedABIPassThrough.cpp --------------------------------------- The *cpp* file contains the implementation of the node. It takes a floating point input and just copy it to its output, demonstrating how to handle a vectorized compute. It shows what would be the implementation for a regular `compute` function, and the different way it could implement a `computeVectorized` function. - method #1: by indexing attribute retrieval ABI function directly in a loop - method #2: by mutating the attribute data handle in a loop - method #3: by retrieving the raw data, and working directly with it .. literalinclude:: ../../../../../source/extensions/omni.graph.tutorials/tutorials/tutorial29/OgnTutorialVectorizedABIPassthrough.cpp :linenos: :language: c++
1,142
reStructuredText
53.428569
134
0.724168
omniverse-code/kit/exts/omni.graph.docs/docs/tutorials/tutorial30.rst
.. _ogn_tutorial_advanced_compute_vectorized_node: Tutorial 30 - Node with more advanced computeVectorized ======================================================= This tutorial demonstrates how to compose nodes that implements a computeVectorized function. It shows how to access the raw vectorized data, and how it can be used to write a performant tight loop using SIMD instructions. OgnTutorialSIMDAdd.ogn -------------------------------- The *ogn* file shows the implementation of a node named "omni.graph.tutorials.TutorialSIMDFloatAdd", which takes inputs of 2 floating point values, and performs a sum. .. literalinclude:: ../../../../../source/extensions/omni.graph.tutorials/tutorials/tutorial30/OgnTutorialSIMDAdd.ogn :linenos: :language: json OgnTutorialSIMDAdd.cpp --------------------------------- The *cpp* file contains the implementation of the node. It takes two floating point inputs and performs a sum, demonstrating how to handle a vectorized compute. It shows how to retrieve the vectorized array of inputs and output, how to reason about the number of instances provided, and how to optimize the compute taking advantage of those vectorized inputs. Since a SIMD instruction requires a given alignment for its arguments, the compute is divided in 3 sections: - a first section that does a regular sum input on the few first instances that don't have a proper alignment - a second, the heart of the function, that does as much SIMD adds as it can, performing them 4 elements by 4 elements - a last section that perform regular sum on the few remaining items that did not fit in the SIMD register .. literalinclude:: ../../../../../source/extensions/omni.graph.tutorials/tutorials/tutorial30/OgnTutorialSIMDAdd.cpp :linenos: :language: c++
1,781
reStructuredText
56.483869
141
0.732173
omniverse-code/kit/exts/omni.graph.docs/docs/tutorials/tutorial10.rst
.. _ogn_tutorial_simpleDataPy: Tutorial 10 - Simple Data Node in Python ======================================== The simple data node creates one input attribute and one output attribute of each of the simple types, where "simple" refers to data types that have a single component and are not arrays. (e.g. "float" is simple, "float[3]" is not, nor is "float[]"). See also :ref:`ogn_tutorial_simpleData` for a similar example in C++. Automatic Python Node Registration ---------------------------------- By implementing the standard Carbonite extension interfact in Python, OmniGraph will know to scan your Python import path for to recursively scan the directory, import all Python node files it finds, and register those nodes. It will also deregister those nodes when the extension shuts down. Here is an example of the directory structure for an extension with a single node in it. (For extensions that have a `premake5.lua` build script this will be in the build directory. For standalone extensions it is in your source directory.) .. code-block:: text omni.my.extension/ omni/ my/ extension/ nodes/ OgnMyNode.ogn OgnMyNode.py OgnTutorialSimpleDataPy.ogn --------------------------- The *ogn* file shows the implementation of a node named "omni.graph.tutorials.SimpleDataPy", which has one input and one output attribute of each simple type. .. literalinclude:: ../../../../../source/extensions/omni.graph.tutorials/tutorials/tutorial10/OgnTutorialSimpleDataPy.ogn :linenos: :language: json OgnTutorialSimpleDataPy.py -------------------------- The *py* file contains the implementation of the compute method, which modifies each of the inputs in a simple way to create outputs that have different values. .. literalinclude:: ../../../../../source/extensions/omni.graph.tutorials/tutorials/tutorial10/OgnTutorialSimpleDataPy.py :linenos: :language: python Note how the attribute values are available through the ``OgnTutorialSimpleDataPyDatabase`` class. The generated interface creates access methods for every attribute, named for the attribute itself. They are all implemented as Python properties, where inputs only have get methods and outputs have both get and set methods. Pythonic Attribute Data ----------------------- Three subsections are creating in the generated database class. The main section implements the node type ABI methods and uses introspection on your node class to call any versions of the ABI methods you have defined (see later tutorials for examples of how this works). The other two subsections are classes containing attribute access properties for inputs and outputs. For naming consistency the class members are called *inputs* and *outputs*. For example, you can access the value of the input attribute named *foo* by referencing ``db.inputs.foo``. Pythonic Attribute Access ------------------------- In the USD file the attribute names are automatically namespaced as *inputs:FOO* or *outputs:BAR*. In the Python interface the colon is illegal so the contained classes above are used to make use of the dot-separated equivalent, as *inputs.FOO* or *outputs.BAR*. While the underlying data types are stored in their exact form there is conversion when they are passed back to Python as Python has a more limited set of data types, though they all have compatible ranges. For this class, these are the types the properties provide: +-------------------+---------------+ | Database Property | Returned Type | +===================+===============+ | inputs.a_bool | bool | +-------------------+---------------+ | inputs.a_half | float | +-------------------+---------------+ | inputs.a_int | int | +-------------------+---------------+ | inputs.a_int64 | int | +-------------------+---------------+ | inputs.a_float | float | +-------------------+---------------+ | inputs.a_double | float | +-------------------+---------------+ | inputs.a_token | str | +-------------------+---------------+ | outputs.a_bool | bool | +-------------------+---------------+ | outputs.a_half | float | +-------------------+---------------+ | outputs.a_int | int | +-------------------+---------------+ | outputs.a_int64 | int | +-------------------+---------------+ | outputs.a_float | float | +-------------------+---------------+ | outputs.a_double | float | +-------------------+---------------+ | outputs.a_token | str | +-------------------+---------------+ The data returned are all references to the real data in the Fabric, our managed memory store, pointed to the correct location at evaluation time. Python Helpers -------------- A few helpers are provided in the database class definition to help make coding with it more natural. Python logging ++++++++++++++ Two helper functions are providing in the database class to help provide more information when the compute method of a node has failed. Two methods are provided, both taking a formatted string describing the problem. :py:meth:`log_error(message)<omni.graph.core.Database.log_error>` is used when the compute has run into some inconsistent or unexpected data, such as two input arrays that are supposed to have the same size but do not, like the normals and vertexes on a mesh. :py:meth:`log_warning(message)<omni.graph.core.Database.log_warning>` can be used when the compute has hit an unusual case but can still provide a consistent output for it, for example the deformation of an empty mesh would result in an empty mesh and a warning since that is not a typical use for the node. Direct Pythonic ABI Access ++++++++++++++++++++++++++ All of the generated database classes provide access to the underlying *INodeType* ABI for those rare situations where you want to access the ABI directly. There are two members provided, which correspond to the objects passed in to the ABI compute method. There is the graph evaluation context member, :py:attr:`db.abi_context<omni.graph.core.Database.abi_context>`, for accessing the underlying OmniGraph evaluation context and its interface. There is also the OmniGraph node member, :py:attr:`db.abi_node<omni.graph.core.Database.abi_node>`, for accessing the underlying OmniGraph node object and its interface.
6,464
reStructuredText
45.847826
122
0.64604