repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.get_environment_variables
def get_environment_variables(self): """ Retrieves the environment variables with wich the program is running. @rtype: list of tuple(compat.unicode, compat.unicode) @return: Environment keys and values as found in the process memory. @raise WindowsError: On error an exception is raised. """ # Note: the first bytes are garbage and must be skipped. Then the first # two environment entries are the current drive and directory as key # and value pairs, followed by the ExitCode variable (it's what batch # files know as "errorlevel"). After that, the real environment vars # are there in alphabetical order. In theory that's where it stops, # but I've always seen one more "variable" tucked at the end which # may be another environment block but in ANSI. I haven't examined it # yet, I'm just skipping it because if it's parsed as Unicode it just # renders garbage. # Read the environment block contents. data = self.peek( *self.get_environment_block() ) # Put them into a Unicode buffer. tmp = ctypes.create_string_buffer(data) buffer = ctypes.create_unicode_buffer(len(data)) ctypes.memmove(buffer, tmp, len(data)) del tmp # Skip until the first Unicode null char is found. pos = 0 while buffer[pos] != u'\0': pos += 1 pos += 1 # Loop for each environment variable... environment = [] while buffer[pos] != u'\0': # Until we find a null char... env_name_pos = pos env_name = u'' found_name = False while buffer[pos] != u'\0': # Get the current char. char = buffer[pos] # Is it an equal sign? if char == u'=': # Skip leading equal signs. if env_name_pos == pos: env_name_pos += 1 pos += 1 continue # Otherwise we found the separator equal sign. pos += 1 found_name = True break # Add the char to the variable name. env_name += char # Next char. pos += 1 # If the name was not parsed properly, stop. if not found_name: break # Read the variable value until we find a null char. env_value = u'' while buffer[pos] != u'\0': env_value += buffer[pos] pos += 1 # Skip the null char. pos += 1 # Add to the list of environment variables found. environment.append( (env_name, env_value) ) # Remove the last entry, it's garbage. if environment: environment.pop() # Return the environment variables. return environment
python
def get_environment_variables(self): """ Retrieves the environment variables with wich the program is running. @rtype: list of tuple(compat.unicode, compat.unicode) @return: Environment keys and values as found in the process memory. @raise WindowsError: On error an exception is raised. """ # Note: the first bytes are garbage and must be skipped. Then the first # two environment entries are the current drive and directory as key # and value pairs, followed by the ExitCode variable (it's what batch # files know as "errorlevel"). After that, the real environment vars # are there in alphabetical order. In theory that's where it stops, # but I've always seen one more "variable" tucked at the end which # may be another environment block but in ANSI. I haven't examined it # yet, I'm just skipping it because if it's parsed as Unicode it just # renders garbage. # Read the environment block contents. data = self.peek( *self.get_environment_block() ) # Put them into a Unicode buffer. tmp = ctypes.create_string_buffer(data) buffer = ctypes.create_unicode_buffer(len(data)) ctypes.memmove(buffer, tmp, len(data)) del tmp # Skip until the first Unicode null char is found. pos = 0 while buffer[pos] != u'\0': pos += 1 pos += 1 # Loop for each environment variable... environment = [] while buffer[pos] != u'\0': # Until we find a null char... env_name_pos = pos env_name = u'' found_name = False while buffer[pos] != u'\0': # Get the current char. char = buffer[pos] # Is it an equal sign? if char == u'=': # Skip leading equal signs. if env_name_pos == pos: env_name_pos += 1 pos += 1 continue # Otherwise we found the separator equal sign. pos += 1 found_name = True break # Add the char to the variable name. env_name += char # Next char. pos += 1 # If the name was not parsed properly, stop. if not found_name: break # Read the variable value until we find a null char. env_value = u'' while buffer[pos] != u'\0': env_value += buffer[pos] pos += 1 # Skip the null char. pos += 1 # Add to the list of environment variables found. environment.append( (env_name, env_value) ) # Remove the last entry, it's garbage. if environment: environment.pop() # Return the environment variables. return environment
[ "def", "get_environment_variables", "(", "self", ")", ":", "# Note: the first bytes are garbage and must be skipped. Then the first", "# two environment entries are the current drive and directory as key", "# and value pairs, followed by the ExitCode variable (it's what batch", "# files know as \"...
Retrieves the environment variables with wich the program is running. @rtype: list of tuple(compat.unicode, compat.unicode) @return: Environment keys and values as found in the process memory. @raise WindowsError: On error an exception is raised.
[ "Retrieves", "the", "environment", "variables", "with", "wich", "the", "program", "is", "running", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L1122-L1211
train
209,700
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.get_environment_data
def get_environment_data(self, fUnicode = None): """ Retrieves the environment block data with wich the program is running. @warn: Deprecated since WinAppDbg 1.5. @see: L{win32.GuessStringType} @type fUnicode: bool or None @param fUnicode: C{True} to return a list of Unicode strings, C{False} to return a list of ANSI strings, or C{None} to return whatever the default is for string types. @rtype: list of str @return: Environment keys and values separated by a (C{=}) character, as found in the process memory. @raise WindowsError: On error an exception is raised. """ # Issue a deprecation warning. warnings.warn( "Process.get_environment_data() is deprecated" \ " since WinAppDbg 1.5.", DeprecationWarning) # Get the environment variables. block = [ key + u'=' + value for (key, value) \ in self.get_environment_variables() ] # Convert the data to ANSI if requested. if fUnicode is None: gst = win32.GuessStringType fUnicode = gst.t_default == gst.t_unicode if not fUnicode: block = [x.encode('cp1252') for x in block] # Return the environment data. return block
python
def get_environment_data(self, fUnicode = None): """ Retrieves the environment block data with wich the program is running. @warn: Deprecated since WinAppDbg 1.5. @see: L{win32.GuessStringType} @type fUnicode: bool or None @param fUnicode: C{True} to return a list of Unicode strings, C{False} to return a list of ANSI strings, or C{None} to return whatever the default is for string types. @rtype: list of str @return: Environment keys and values separated by a (C{=}) character, as found in the process memory. @raise WindowsError: On error an exception is raised. """ # Issue a deprecation warning. warnings.warn( "Process.get_environment_data() is deprecated" \ " since WinAppDbg 1.5.", DeprecationWarning) # Get the environment variables. block = [ key + u'=' + value for (key, value) \ in self.get_environment_variables() ] # Convert the data to ANSI if requested. if fUnicode is None: gst = win32.GuessStringType fUnicode = gst.t_default == gst.t_unicode if not fUnicode: block = [x.encode('cp1252') for x in block] # Return the environment data. return block
[ "def", "get_environment_data", "(", "self", ",", "fUnicode", "=", "None", ")", ":", "# Issue a deprecation warning.", "warnings", ".", "warn", "(", "\"Process.get_environment_data() is deprecated\"", "\" since WinAppDbg 1.5.\"", ",", "DeprecationWarning", ")", "# Get the envi...
Retrieves the environment block data with wich the program is running. @warn: Deprecated since WinAppDbg 1.5. @see: L{win32.GuessStringType} @type fUnicode: bool or None @param fUnicode: C{True} to return a list of Unicode strings, C{False} to return a list of ANSI strings, or C{None} to return whatever the default is for string types. @rtype: list of str @return: Environment keys and values separated by a (C{=}) character, as found in the process memory. @raise WindowsError: On error an exception is raised.
[ "Retrieves", "the", "environment", "block", "data", "with", "wich", "the", "program", "is", "running", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L1213-L1251
train
209,701
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.parse_environment_data
def parse_environment_data(block): """ Parse the environment block into a Python dictionary. @warn: Deprecated since WinAppDbg 1.5. @note: Values of duplicated keys are joined using null characters. @type block: list of str @param block: List of strings as returned by L{get_environment_data}. @rtype: dict(str S{->} str) @return: Dictionary of environment keys and values. """ # Issue a deprecation warning. warnings.warn( "Process.parse_environment_data() is deprecated" \ " since WinAppDbg 1.5.", DeprecationWarning) # Create an empty environment dictionary. environment = dict() # End here if the environment block is empty. if not block: return environment # Prepare the tokens (ANSI or Unicode). gst = win32.GuessStringType if type(block[0]) == gst.t_ansi: equals = '=' terminator = '\0' else: equals = u'=' terminator = u'\0' # Split the blocks into key/value pairs. for chunk in block: sep = chunk.find(equals, 1) if sep < 0: ## raise Exception() continue # corrupted environment block? key, value = chunk[:sep], chunk[sep+1:] # For duplicated keys, append the value. # Values are separated using null terminators. if key not in environment: environment[key] = value else: environment[key] += terminator + value # Return the environment dictionary. return environment
python
def parse_environment_data(block): """ Parse the environment block into a Python dictionary. @warn: Deprecated since WinAppDbg 1.5. @note: Values of duplicated keys are joined using null characters. @type block: list of str @param block: List of strings as returned by L{get_environment_data}. @rtype: dict(str S{->} str) @return: Dictionary of environment keys and values. """ # Issue a deprecation warning. warnings.warn( "Process.parse_environment_data() is deprecated" \ " since WinAppDbg 1.5.", DeprecationWarning) # Create an empty environment dictionary. environment = dict() # End here if the environment block is empty. if not block: return environment # Prepare the tokens (ANSI or Unicode). gst = win32.GuessStringType if type(block[0]) == gst.t_ansi: equals = '=' terminator = '\0' else: equals = u'=' terminator = u'\0' # Split the blocks into key/value pairs. for chunk in block: sep = chunk.find(equals, 1) if sep < 0: ## raise Exception() continue # corrupted environment block? key, value = chunk[:sep], chunk[sep+1:] # For duplicated keys, append the value. # Values are separated using null terminators. if key not in environment: environment[key] = value else: environment[key] += terminator + value # Return the environment dictionary. return environment
[ "def", "parse_environment_data", "(", "block", ")", ":", "# Issue a deprecation warning.", "warnings", ".", "warn", "(", "\"Process.parse_environment_data() is deprecated\"", "\" since WinAppDbg 1.5.\"", ",", "DeprecationWarning", ")", "# Create an empty environment dictionary.", "...
Parse the environment block into a Python dictionary. @warn: Deprecated since WinAppDbg 1.5. @note: Values of duplicated keys are joined using null characters. @type block: list of str @param block: List of strings as returned by L{get_environment_data}. @rtype: dict(str S{->} str) @return: Dictionary of environment keys and values.
[ "Parse", "the", "environment", "block", "into", "a", "Python", "dictionary", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L1254-L1307
train
209,702
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.get_environment
def get_environment(self, fUnicode = None): """ Retrieves the environment with wich the program is running. @note: Duplicated keys are joined using null characters. To avoid this behavior, call L{get_environment_variables} instead and convert the results to a dictionary directly, like this: C{dict(process.get_environment_variables())} @see: L{win32.GuessStringType} @type fUnicode: bool or None @param fUnicode: C{True} to return a list of Unicode strings, C{False} to return a list of ANSI strings, or C{None} to return whatever the default is for string types. @rtype: dict(str S{->} str) @return: Dictionary of environment keys and values. @raise WindowsError: On error an exception is raised. """ # Get the environment variables. variables = self.get_environment_variables() # Convert the strings to ANSI if requested. if fUnicode is None: gst = win32.GuessStringType fUnicode = gst.t_default == gst.t_unicode if not fUnicode: variables = [ ( key.encode('cp1252'), value.encode('cp1252') ) \ for (key, value) in variables ] # Add the variables to a dictionary, concatenating duplicates. environment = dict() for key, value in variables: if key in environment: environment[key] = environment[key] + u'\0' + value else: environment[key] = value # Return the dictionary. return environment
python
def get_environment(self, fUnicode = None): """ Retrieves the environment with wich the program is running. @note: Duplicated keys are joined using null characters. To avoid this behavior, call L{get_environment_variables} instead and convert the results to a dictionary directly, like this: C{dict(process.get_environment_variables())} @see: L{win32.GuessStringType} @type fUnicode: bool or None @param fUnicode: C{True} to return a list of Unicode strings, C{False} to return a list of ANSI strings, or C{None} to return whatever the default is for string types. @rtype: dict(str S{->} str) @return: Dictionary of environment keys and values. @raise WindowsError: On error an exception is raised. """ # Get the environment variables. variables = self.get_environment_variables() # Convert the strings to ANSI if requested. if fUnicode is None: gst = win32.GuessStringType fUnicode = gst.t_default == gst.t_unicode if not fUnicode: variables = [ ( key.encode('cp1252'), value.encode('cp1252') ) \ for (key, value) in variables ] # Add the variables to a dictionary, concatenating duplicates. environment = dict() for key, value in variables: if key in environment: environment[key] = environment[key] + u'\0' + value else: environment[key] = value # Return the dictionary. return environment
[ "def", "get_environment", "(", "self", ",", "fUnicode", "=", "None", ")", ":", "# Get the environment variables.", "variables", "=", "self", ".", "get_environment_variables", "(", ")", "# Convert the strings to ANSI if requested.", "if", "fUnicode", "is", "None", ":", ...
Retrieves the environment with wich the program is running. @note: Duplicated keys are joined using null characters. To avoid this behavior, call L{get_environment_variables} instead and convert the results to a dictionary directly, like this: C{dict(process.get_environment_variables())} @see: L{win32.GuessStringType} @type fUnicode: bool or None @param fUnicode: C{True} to return a list of Unicode strings, C{False} to return a list of ANSI strings, or C{None} to return whatever the default is for string types. @rtype: dict(str S{->} str) @return: Dictionary of environment keys and values. @raise WindowsError: On error an exception is raised.
[ "Retrieves", "the", "environment", "with", "wich", "the", "program", "is", "running", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L1309-L1351
train
209,703
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.search_bytes
def search_bytes(self, bytes, minAddr = None, maxAddr = None): """ Search for the given byte pattern within the process memory. @type bytes: str @param bytes: Bytes to search for. @type minAddr: int @param minAddr: (Optional) Start the search at this memory address. @type maxAddr: int @param maxAddr: (Optional) Stop the search at this memory address. @rtype: iterator of int @return: An iterator of memory addresses where the pattern was found. @raise WindowsError: An error occurred when querying or reading the process memory. """ pattern = BytePattern(bytes) matches = Search.search_process(self, pattern, minAddr, maxAddr) for addr, size, data in matches: yield addr
python
def search_bytes(self, bytes, minAddr = None, maxAddr = None): """ Search for the given byte pattern within the process memory. @type bytes: str @param bytes: Bytes to search for. @type minAddr: int @param minAddr: (Optional) Start the search at this memory address. @type maxAddr: int @param maxAddr: (Optional) Stop the search at this memory address. @rtype: iterator of int @return: An iterator of memory addresses where the pattern was found. @raise WindowsError: An error occurred when querying or reading the process memory. """ pattern = BytePattern(bytes) matches = Search.search_process(self, pattern, minAddr, maxAddr) for addr, size, data in matches: yield addr
[ "def", "search_bytes", "(", "self", ",", "bytes", ",", "minAddr", "=", "None", ",", "maxAddr", "=", "None", ")", ":", "pattern", "=", "BytePattern", "(", "bytes", ")", "matches", "=", "Search", ".", "search_process", "(", "self", ",", "pattern", ",", "...
Search for the given byte pattern within the process memory. @type bytes: str @param bytes: Bytes to search for. @type minAddr: int @param minAddr: (Optional) Start the search at this memory address. @type maxAddr: int @param maxAddr: (Optional) Stop the search at this memory address. @rtype: iterator of int @return: An iterator of memory addresses where the pattern was found. @raise WindowsError: An error occurred when querying or reading the process memory.
[ "Search", "for", "the", "given", "byte", "pattern", "within", "the", "process", "memory", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L1397-L1419
train
209,704
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.search_text
def search_text(self, text, encoding = "utf-16le", caseSensitive = False, minAddr = None, maxAddr = None): """ Search for the given text within the process memory. @type text: str or compat.unicode @param text: Text to search for. @type encoding: str @param encoding: (Optional) Encoding for the text parameter. Only used when the text to search for is a Unicode string. Don't change unless you know what you're doing! @type caseSensitive: bool @param caseSensitive: C{True} of the search is case sensitive, C{False} otherwise. @type minAddr: int @param minAddr: (Optional) Start the search at this memory address. @type maxAddr: int @param maxAddr: (Optional) Stop the search at this memory address. @rtype: iterator of tuple( int, str ) @return: An iterator of tuples. Each tuple contains the following: - The memory address where the pattern was found. - The text that matches the pattern. @raise WindowsError: An error occurred when querying or reading the process memory. """ pattern = TextPattern(text, encoding, caseSensitive) matches = Search.search_process(self, pattern, minAddr, maxAddr) for addr, size, data in matches: yield addr, data
python
def search_text(self, text, encoding = "utf-16le", caseSensitive = False, minAddr = None, maxAddr = None): """ Search for the given text within the process memory. @type text: str or compat.unicode @param text: Text to search for. @type encoding: str @param encoding: (Optional) Encoding for the text parameter. Only used when the text to search for is a Unicode string. Don't change unless you know what you're doing! @type caseSensitive: bool @param caseSensitive: C{True} of the search is case sensitive, C{False} otherwise. @type minAddr: int @param minAddr: (Optional) Start the search at this memory address. @type maxAddr: int @param maxAddr: (Optional) Stop the search at this memory address. @rtype: iterator of tuple( int, str ) @return: An iterator of tuples. Each tuple contains the following: - The memory address where the pattern was found. - The text that matches the pattern. @raise WindowsError: An error occurred when querying or reading the process memory. """ pattern = TextPattern(text, encoding, caseSensitive) matches = Search.search_process(self, pattern, minAddr, maxAddr) for addr, size, data in matches: yield addr, data
[ "def", "search_text", "(", "self", ",", "text", ",", "encoding", "=", "\"utf-16le\"", ",", "caseSensitive", "=", "False", ",", "minAddr", "=", "None", ",", "maxAddr", "=", "None", ")", ":", "pattern", "=", "TextPattern", "(", "text", ",", "encoding", ","...
Search for the given text within the process memory. @type text: str or compat.unicode @param text: Text to search for. @type encoding: str @param encoding: (Optional) Encoding for the text parameter. Only used when the text to search for is a Unicode string. Don't change unless you know what you're doing! @type caseSensitive: bool @param caseSensitive: C{True} of the search is case sensitive, C{False} otherwise. @type minAddr: int @param minAddr: (Optional) Start the search at this memory address. @type maxAddr: int @param maxAddr: (Optional) Stop the search at this memory address. @rtype: iterator of tuple( int, str ) @return: An iterator of tuples. Each tuple contains the following: - The memory address where the pattern was found. - The text that matches the pattern. @raise WindowsError: An error occurred when querying or reading the process memory.
[ "Search", "for", "the", "given", "text", "within", "the", "process", "memory", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L1421-L1457
train
209,705
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.search_regexp
def search_regexp(self, regexp, flags = 0, minAddr = None, maxAddr = None, bufferPages = -1): """ Search for the given regular expression within the process memory. @type regexp: str @param regexp: Regular expression string. @type flags: int @param flags: Regular expression flags. @type minAddr: int @param minAddr: (Optional) Start the search at this memory address. @type maxAddr: int @param maxAddr: (Optional) Stop the search at this memory address. @type bufferPages: int @param bufferPages: (Optional) Number of memory pages to buffer when performing the search. Valid values are: - C{0} or C{None}: Automatically determine the required buffer size. May not give complete results for regular expressions that match variable sized strings. - C{> 0}: Set the buffer size, in memory pages. - C{< 0}: Disable buffering entirely. This may give you a little speed gain at the cost of an increased memory usage. If the target process has very large contiguous memory regions it may actually be slower or even fail. It's also the only way to guarantee complete results for regular expressions that match variable sized strings. @rtype: iterator of tuple( int, int, str ) @return: An iterator of tuples. Each tuple contains the following: - The memory address where the pattern was found. - The size of the data that matches the pattern. - The data that matches the pattern. @raise WindowsError: An error occurred when querying or reading the process memory. """ pattern = RegExpPattern(regexp, flags) return Search.search_process(self, pattern, minAddr, maxAddr, bufferPages)
python
def search_regexp(self, regexp, flags = 0, minAddr = None, maxAddr = None, bufferPages = -1): """ Search for the given regular expression within the process memory. @type regexp: str @param regexp: Regular expression string. @type flags: int @param flags: Regular expression flags. @type minAddr: int @param minAddr: (Optional) Start the search at this memory address. @type maxAddr: int @param maxAddr: (Optional) Stop the search at this memory address. @type bufferPages: int @param bufferPages: (Optional) Number of memory pages to buffer when performing the search. Valid values are: - C{0} or C{None}: Automatically determine the required buffer size. May not give complete results for regular expressions that match variable sized strings. - C{> 0}: Set the buffer size, in memory pages. - C{< 0}: Disable buffering entirely. This may give you a little speed gain at the cost of an increased memory usage. If the target process has very large contiguous memory regions it may actually be slower or even fail. It's also the only way to guarantee complete results for regular expressions that match variable sized strings. @rtype: iterator of tuple( int, int, str ) @return: An iterator of tuples. Each tuple contains the following: - The memory address where the pattern was found. - The size of the data that matches the pattern. - The data that matches the pattern. @raise WindowsError: An error occurred when querying or reading the process memory. """ pattern = RegExpPattern(regexp, flags) return Search.search_process(self, pattern, minAddr, maxAddr, bufferPages)
[ "def", "search_regexp", "(", "self", ",", "regexp", ",", "flags", "=", "0", ",", "minAddr", "=", "None", ",", "maxAddr", "=", "None", ",", "bufferPages", "=", "-", "1", ")", ":", "pattern", "=", "RegExpPattern", "(", "regexp", ",", "flags", ")", "ret...
Search for the given regular expression within the process memory. @type regexp: str @param regexp: Regular expression string. @type flags: int @param flags: Regular expression flags. @type minAddr: int @param minAddr: (Optional) Start the search at this memory address. @type maxAddr: int @param maxAddr: (Optional) Stop the search at this memory address. @type bufferPages: int @param bufferPages: (Optional) Number of memory pages to buffer when performing the search. Valid values are: - C{0} or C{None}: Automatically determine the required buffer size. May not give complete results for regular expressions that match variable sized strings. - C{> 0}: Set the buffer size, in memory pages. - C{< 0}: Disable buffering entirely. This may give you a little speed gain at the cost of an increased memory usage. If the target process has very large contiguous memory regions it may actually be slower or even fail. It's also the only way to guarantee complete results for regular expressions that match variable sized strings. @rtype: iterator of tuple( int, int, str ) @return: An iterator of tuples. Each tuple contains the following: - The memory address where the pattern was found. - The size of the data that matches the pattern. - The data that matches the pattern. @raise WindowsError: An error occurred when querying or reading the process memory.
[ "Search", "for", "the", "given", "regular", "expression", "within", "the", "process", "memory", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L1459-L1505
train
209,706
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.search_hexa
def search_hexa(self, hexa, minAddr = None, maxAddr = None): """ Search for the given hexadecimal pattern within the process memory. Hex patterns must be in this form:: "68 65 6c 6c 6f 20 77 6f 72 6c 64" # "hello world" Spaces are optional. Capitalization of hex digits doesn't matter. This is exactly equivalent to the previous example:: "68656C6C6F20776F726C64" # "hello world" Wildcards are allowed, in the form of a C{?} sign in any hex digit:: "5? 5? c3" # pop register / pop register / ret "b8 ?? ?? ?? ??" # mov eax, immediate value @type hexa: str @param hexa: Pattern to search for. @type minAddr: int @param minAddr: (Optional) Start the search at this memory address. @type maxAddr: int @param maxAddr: (Optional) Stop the search at this memory address. @rtype: iterator of tuple( int, str ) @return: An iterator of tuples. Each tuple contains the following: - The memory address where the pattern was found. - The bytes that match the pattern. @raise WindowsError: An error occurred when querying or reading the process memory. """ pattern = HexPattern(hexa) matches = Search.search_process(self, pattern, minAddr, maxAddr) for addr, size, data in matches: yield addr, data
python
def search_hexa(self, hexa, minAddr = None, maxAddr = None): """ Search for the given hexadecimal pattern within the process memory. Hex patterns must be in this form:: "68 65 6c 6c 6f 20 77 6f 72 6c 64" # "hello world" Spaces are optional. Capitalization of hex digits doesn't matter. This is exactly equivalent to the previous example:: "68656C6C6F20776F726C64" # "hello world" Wildcards are allowed, in the form of a C{?} sign in any hex digit:: "5? 5? c3" # pop register / pop register / ret "b8 ?? ?? ?? ??" # mov eax, immediate value @type hexa: str @param hexa: Pattern to search for. @type minAddr: int @param minAddr: (Optional) Start the search at this memory address. @type maxAddr: int @param maxAddr: (Optional) Stop the search at this memory address. @rtype: iterator of tuple( int, str ) @return: An iterator of tuples. Each tuple contains the following: - The memory address where the pattern was found. - The bytes that match the pattern. @raise WindowsError: An error occurred when querying or reading the process memory. """ pattern = HexPattern(hexa) matches = Search.search_process(self, pattern, minAddr, maxAddr) for addr, size, data in matches: yield addr, data
[ "def", "search_hexa", "(", "self", ",", "hexa", ",", "minAddr", "=", "None", ",", "maxAddr", "=", "None", ")", ":", "pattern", "=", "HexPattern", "(", "hexa", ")", "matches", "=", "Search", ".", "search_process", "(", "self", ",", "pattern", ",", "minA...
Search for the given hexadecimal pattern within the process memory. Hex patterns must be in this form:: "68 65 6c 6c 6f 20 77 6f 72 6c 64" # "hello world" Spaces are optional. Capitalization of hex digits doesn't matter. This is exactly equivalent to the previous example:: "68656C6C6F20776F726C64" # "hello world" Wildcards are allowed, in the form of a C{?} sign in any hex digit:: "5? 5? c3" # pop register / pop register / ret "b8 ?? ?? ?? ??" # mov eax, immediate value @type hexa: str @param hexa: Pattern to search for. @type minAddr: int @param minAddr: (Optional) Start the search at this memory address. @type maxAddr: int @param maxAddr: (Optional) Stop the search at this memory address. @rtype: iterator of tuple( int, str ) @return: An iterator of tuples. Each tuple contains the following: - The memory address where the pattern was found. - The bytes that match the pattern. @raise WindowsError: An error occurred when querying or reading the process memory.
[ "Search", "for", "the", "given", "hexadecimal", "pattern", "within", "the", "process", "memory", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L1507-L1542
train
209,707
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.read
def read(self, lpBaseAddress, nSize): """ Reads from the memory of the process. @see: L{peek} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type nSize: int @param nSize: Number of bytes to read. @rtype: str @return: Bytes read from the process memory. @raise WindowsError: On error an exception is raised. """ hProcess = self.get_handle( win32.PROCESS_VM_READ | win32.PROCESS_QUERY_INFORMATION ) if not self.is_buffer(lpBaseAddress, nSize): raise ctypes.WinError(win32.ERROR_INVALID_ADDRESS) data = win32.ReadProcessMemory(hProcess, lpBaseAddress, nSize) if len(data) != nSize: raise ctypes.WinError() return data
python
def read(self, lpBaseAddress, nSize): """ Reads from the memory of the process. @see: L{peek} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type nSize: int @param nSize: Number of bytes to read. @rtype: str @return: Bytes read from the process memory. @raise WindowsError: On error an exception is raised. """ hProcess = self.get_handle( win32.PROCESS_VM_READ | win32.PROCESS_QUERY_INFORMATION ) if not self.is_buffer(lpBaseAddress, nSize): raise ctypes.WinError(win32.ERROR_INVALID_ADDRESS) data = win32.ReadProcessMemory(hProcess, lpBaseAddress, nSize) if len(data) != nSize: raise ctypes.WinError() return data
[ "def", "read", "(", "self", ",", "lpBaseAddress", ",", "nSize", ")", ":", "hProcess", "=", "self", ".", "get_handle", "(", "win32", ".", "PROCESS_VM_READ", "|", "win32", ".", "PROCESS_QUERY_INFORMATION", ")", "if", "not", "self", ".", "is_buffer", "(", "lp...
Reads from the memory of the process. @see: L{peek} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type nSize: int @param nSize: Number of bytes to read. @rtype: str @return: Bytes read from the process memory. @raise WindowsError: On error an exception is raised.
[ "Reads", "from", "the", "memory", "of", "the", "process", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L1579-L1603
train
209,708
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.read_int
def read_int(self, lpBaseAddress): """ Reads a signed integer from the memory of the process. @see: L{peek_int} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Integer value read from the process memory. @raise WindowsError: On error an exception is raised. """ return self.__read_c_type(lpBaseAddress, compat.b('@l'), ctypes.c_int)
python
def read_int(self, lpBaseAddress): """ Reads a signed integer from the memory of the process. @see: L{peek_int} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Integer value read from the process memory. @raise WindowsError: On error an exception is raised. """ return self.__read_c_type(lpBaseAddress, compat.b('@l'), ctypes.c_int)
[ "def", "read_int", "(", "self", ",", "lpBaseAddress", ")", ":", "return", "self", ".", "__read_c_type", "(", "lpBaseAddress", ",", "compat", ".", "b", "(", "'@l'", ")", ",", "ctypes", ".", "c_int", ")" ]
Reads a signed integer from the memory of the process. @see: L{peek_int} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Integer value read from the process memory. @raise WindowsError: On error an exception is raised.
[ "Reads", "a", "signed", "integer", "from", "the", "memory", "of", "the", "process", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L1659-L1673
train
209,709
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.read_structure
def read_structure(self, lpBaseAddress, stype): """ Reads a ctypes structure from the memory of the process. @see: L{read} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type stype: class ctypes.Structure or a subclass. @param stype: Structure definition. @rtype: int @return: Structure instance filled in with data read from the process memory. @raise WindowsError: On error an exception is raised. """ if type(lpBaseAddress) not in (type(0), type(long(0))): lpBaseAddress = ctypes.cast(lpBaseAddress, ctypes.c_void_p) data = self.read(lpBaseAddress, ctypes.sizeof(stype)) buff = ctypes.create_string_buffer(data) ptr = ctypes.cast(ctypes.pointer(buff), ctypes.POINTER(stype)) return ptr.contents
python
def read_structure(self, lpBaseAddress, stype): """ Reads a ctypes structure from the memory of the process. @see: L{read} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type stype: class ctypes.Structure or a subclass. @param stype: Structure definition. @rtype: int @return: Structure instance filled in with data read from the process memory. @raise WindowsError: On error an exception is raised. """ if type(lpBaseAddress) not in (type(0), type(long(0))): lpBaseAddress = ctypes.cast(lpBaseAddress, ctypes.c_void_p) data = self.read(lpBaseAddress, ctypes.sizeof(stype)) buff = ctypes.create_string_buffer(data) ptr = ctypes.cast(ctypes.pointer(buff), ctypes.POINTER(stype)) return ptr.contents
[ "def", "read_structure", "(", "self", ",", "lpBaseAddress", ",", "stype", ")", ":", "if", "type", "(", "lpBaseAddress", ")", "not", "in", "(", "type", "(", "0", ")", ",", "type", "(", "long", "(", "0", ")", ")", ")", ":", "lpBaseAddress", "=", "cty...
Reads a ctypes structure from the memory of the process. @see: L{read} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type stype: class ctypes.Structure or a subclass. @param stype: Structure definition. @rtype: int @return: Structure instance filled in with data read from the process memory. @raise WindowsError: On error an exception is raised.
[ "Reads", "a", "ctypes", "structure", "from", "the", "memory", "of", "the", "process", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L1897-L1920
train
209,710
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.read_string
def read_string(self, lpBaseAddress, nChars, fUnicode = False): """ Reads an ASCII or Unicode string from the address space of the process. @see: L{peek_string} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type nChars: int @param nChars: String length to read, in characters. Remember that Unicode strings have two byte characters. @type fUnicode: bool @param fUnicode: C{True} is the string is expected to be Unicode, C{False} if it's expected to be ANSI. @rtype: str, compat.unicode @return: String read from the process memory space. @raise WindowsError: On error an exception is raised. """ if fUnicode: nChars = nChars * 2 szString = self.read(lpBaseAddress, nChars) if fUnicode: szString = compat.unicode(szString, 'U16', 'ignore') return szString
python
def read_string(self, lpBaseAddress, nChars, fUnicode = False): """ Reads an ASCII or Unicode string from the address space of the process. @see: L{peek_string} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type nChars: int @param nChars: String length to read, in characters. Remember that Unicode strings have two byte characters. @type fUnicode: bool @param fUnicode: C{True} is the string is expected to be Unicode, C{False} if it's expected to be ANSI. @rtype: str, compat.unicode @return: String read from the process memory space. @raise WindowsError: On error an exception is raised. """ if fUnicode: nChars = nChars * 2 szString = self.read(lpBaseAddress, nChars) if fUnicode: szString = compat.unicode(szString, 'U16', 'ignore') return szString
[ "def", "read_string", "(", "self", ",", "lpBaseAddress", ",", "nChars", ",", "fUnicode", "=", "False", ")", ":", "if", "fUnicode", ":", "nChars", "=", "nChars", "*", "2", "szString", "=", "self", ".", "read", "(", "lpBaseAddress", ",", "nChars", ")", "...
Reads an ASCII or Unicode string from the address space of the process. @see: L{peek_string} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type nChars: int @param nChars: String length to read, in characters. Remember that Unicode strings have two byte characters. @type fUnicode: bool @param fUnicode: C{True} is the string is expected to be Unicode, C{False} if it's expected to be ANSI. @rtype: str, compat.unicode @return: String read from the process memory space. @raise WindowsError: On error an exception is raised.
[ "Reads", "an", "ASCII", "or", "Unicode", "string", "from", "the", "address", "space", "of", "the", "process", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L1948-L1976
train
209,711
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.peek
def peek(self, lpBaseAddress, nSize): """ Reads the memory of the process. @see: L{read} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type nSize: int @param nSize: Number of bytes to read. @rtype: str @return: Bytes read from the process memory. Returns an empty string on error. """ # XXX TODO # + Maybe change page permissions before trying to read? # + Maybe use mquery instead of get_memory_map? # (less syscalls if we break out of the loop earlier) data = '' if nSize > 0: try: hProcess = self.get_handle( win32.PROCESS_VM_READ | win32.PROCESS_QUERY_INFORMATION ) for mbi in self.get_memory_map(lpBaseAddress, lpBaseAddress + nSize): if not mbi.is_readable(): nSize = mbi.BaseAddress - lpBaseAddress break if nSize > 0: data = win32.ReadProcessMemory( hProcess, lpBaseAddress, nSize) except WindowsError: e = sys.exc_info()[1] msg = "Error reading process %d address %s: %s" msg %= (self.get_pid(), HexDump.address(lpBaseAddress), e.strerror) warnings.warn(msg) return data
python
def peek(self, lpBaseAddress, nSize): """ Reads the memory of the process. @see: L{read} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type nSize: int @param nSize: Number of bytes to read. @rtype: str @return: Bytes read from the process memory. Returns an empty string on error. """ # XXX TODO # + Maybe change page permissions before trying to read? # + Maybe use mquery instead of get_memory_map? # (less syscalls if we break out of the loop earlier) data = '' if nSize > 0: try: hProcess = self.get_handle( win32.PROCESS_VM_READ | win32.PROCESS_QUERY_INFORMATION ) for mbi in self.get_memory_map(lpBaseAddress, lpBaseAddress + nSize): if not mbi.is_readable(): nSize = mbi.BaseAddress - lpBaseAddress break if nSize > 0: data = win32.ReadProcessMemory( hProcess, lpBaseAddress, nSize) except WindowsError: e = sys.exc_info()[1] msg = "Error reading process %d address %s: %s" msg %= (self.get_pid(), HexDump.address(lpBaseAddress), e.strerror) warnings.warn(msg) return data
[ "def", "peek", "(", "self", ",", "lpBaseAddress", ",", "nSize", ")", ":", "# XXX TODO", "# + Maybe change page permissions before trying to read?", "# + Maybe use mquery instead of get_memory_map?", "# (less syscalls if we break out of the loop earlier)", "data", "=", "''", "if",...
Reads the memory of the process. @see: L{read} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type nSize: int @param nSize: Number of bytes to read. @rtype: str @return: Bytes read from the process memory. Returns an empty string on error.
[ "Reads", "the", "memory", "of", "the", "process", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L1994-L2034
train
209,712
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.peek_char
def peek_char(self, lpBaseAddress): """ Reads a single character from the memory of the process. @see: L{read_char} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Character read from the process memory. Returns zero on error. """ char = self.peek(lpBaseAddress, 1) if char: return ord(char) return 0
python
def peek_char(self, lpBaseAddress): """ Reads a single character from the memory of the process. @see: L{read_char} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Character read from the process memory. Returns zero on error. """ char = self.peek(lpBaseAddress, 1) if char: return ord(char) return 0
[ "def", "peek_char", "(", "self", ",", "lpBaseAddress", ")", ":", "char", "=", "self", ".", "peek", "(", "lpBaseAddress", ",", "1", ")", "if", "char", ":", "return", "ord", "(", "char", ")", "return", "0" ]
Reads a single character from the memory of the process. @see: L{read_char} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Character read from the process memory. Returns zero on error.
[ "Reads", "a", "single", "character", "from", "the", "memory", "of", "the", "process", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L2087-L2103
train
209,713
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.peek_string
def peek_string(self, lpBaseAddress, fUnicode = False, dwMaxSize = 0x1000): """ Tries to read an ASCII or Unicode string from the address space of the process. @see: L{read_string} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type fUnicode: bool @param fUnicode: C{True} is the string is expected to be Unicode, C{False} if it's expected to be ANSI. @type dwMaxSize: int @param dwMaxSize: Maximum allowed string length to read, in bytes. @rtype: str, compat.unicode @return: String read from the process memory space. It B{doesn't} include the terminating null character. Returns an empty string on failure. """ # Validate the parameters. if not lpBaseAddress or dwMaxSize == 0: if fUnicode: return u'' return '' if not dwMaxSize: dwMaxSize = 0x1000 # Read the string. szString = self.peek(lpBaseAddress, dwMaxSize) # If the string is Unicode... if fUnicode: # Decode the string. szString = compat.unicode(szString, 'U16', 'replace') ## try: ## szString = compat.unicode(szString, 'U16') ## except UnicodeDecodeError: ## szString = struct.unpack('H' * (len(szString) / 2), szString) ## szString = [ unichr(c) for c in szString ] ## szString = u''.join(szString) # Truncate the string when the first null char is found. szString = szString[ : szString.find(u'\0') ] # If the string is ANSI... else: # Truncate the string when the first null char is found. szString = szString[ : szString.find('\0') ] # Return the decoded string. return szString
python
def peek_string(self, lpBaseAddress, fUnicode = False, dwMaxSize = 0x1000): """ Tries to read an ASCII or Unicode string from the address space of the process. @see: L{read_string} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type fUnicode: bool @param fUnicode: C{True} is the string is expected to be Unicode, C{False} if it's expected to be ANSI. @type dwMaxSize: int @param dwMaxSize: Maximum allowed string length to read, in bytes. @rtype: str, compat.unicode @return: String read from the process memory space. It B{doesn't} include the terminating null character. Returns an empty string on failure. """ # Validate the parameters. if not lpBaseAddress or dwMaxSize == 0: if fUnicode: return u'' return '' if not dwMaxSize: dwMaxSize = 0x1000 # Read the string. szString = self.peek(lpBaseAddress, dwMaxSize) # If the string is Unicode... if fUnicode: # Decode the string. szString = compat.unicode(szString, 'U16', 'replace') ## try: ## szString = compat.unicode(szString, 'U16') ## except UnicodeDecodeError: ## szString = struct.unpack('H' * (len(szString) / 2), szString) ## szString = [ unichr(c) for c in szString ] ## szString = u''.join(szString) # Truncate the string when the first null char is found. szString = szString[ : szString.find(u'\0') ] # If the string is ANSI... else: # Truncate the string when the first null char is found. szString = szString[ : szString.find('\0') ] # Return the decoded string. return szString
[ "def", "peek_string", "(", "self", ",", "lpBaseAddress", ",", "fUnicode", "=", "False", ",", "dwMaxSize", "=", "0x1000", ")", ":", "# Validate the parameters.", "if", "not", "lpBaseAddress", "or", "dwMaxSize", "==", "0", ":", "if", "fUnicode", ":", "return", ...
Tries to read an ASCII or Unicode string from the address space of the process. @see: L{read_string} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @type fUnicode: bool @param fUnicode: C{True} is the string is expected to be Unicode, C{False} if it's expected to be ANSI. @type dwMaxSize: int @param dwMaxSize: Maximum allowed string length to read, in bytes. @rtype: str, compat.unicode @return: String read from the process memory space. It B{doesn't} include the terminating null character. Returns an empty string on failure.
[ "Tries", "to", "read", "an", "ASCII", "or", "Unicode", "string", "from", "the", "address", "space", "of", "the", "process", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L2370-L2426
train
209,714
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.malloc
def malloc(self, dwSize, lpAddress = None): """ Allocates memory into the address space of the process. @see: L{free} @type dwSize: int @param dwSize: Number of bytes to allocate. @type lpAddress: int @param lpAddress: (Optional) Desired address for the newly allocated memory. This is only a hint, the memory could still be allocated somewhere else. @rtype: int @return: Address of the newly allocated memory. @raise WindowsError: On error an exception is raised. """ hProcess = self.get_handle(win32.PROCESS_VM_OPERATION) return win32.VirtualAllocEx(hProcess, lpAddress, dwSize)
python
def malloc(self, dwSize, lpAddress = None): """ Allocates memory into the address space of the process. @see: L{free} @type dwSize: int @param dwSize: Number of bytes to allocate. @type lpAddress: int @param lpAddress: (Optional) Desired address for the newly allocated memory. This is only a hint, the memory could still be allocated somewhere else. @rtype: int @return: Address of the newly allocated memory. @raise WindowsError: On error an exception is raised. """ hProcess = self.get_handle(win32.PROCESS_VM_OPERATION) return win32.VirtualAllocEx(hProcess, lpAddress, dwSize)
[ "def", "malloc", "(", "self", ",", "dwSize", ",", "lpAddress", "=", "None", ")", ":", "hProcess", "=", "self", ".", "get_handle", "(", "win32", ".", "PROCESS_VM_OPERATION", ")", "return", "win32", ".", "VirtualAllocEx", "(", "hProcess", ",", "lpAddress", "...
Allocates memory into the address space of the process. @see: L{free} @type dwSize: int @param dwSize: Number of bytes to allocate. @type lpAddress: int @param lpAddress: (Optional) Desired address for the newly allocated memory. This is only a hint, the memory could still be allocated somewhere else. @rtype: int @return: Address of the newly allocated memory. @raise WindowsError: On error an exception is raised.
[ "Allocates", "memory", "into", "the", "address", "space", "of", "the", "process", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L2471-L2492
train
209,715
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.mprotect
def mprotect(self, lpAddress, dwSize, flNewProtect): """ Set memory protection in the address space of the process. @see: U{http://msdn.microsoft.com/en-us/library/aa366899.aspx} @type lpAddress: int @param lpAddress: Address of memory to protect. @type dwSize: int @param dwSize: Number of bytes to protect. @type flNewProtect: int @param flNewProtect: New protect flags. @rtype: int @return: Old protect flags. @raise WindowsError: On error an exception is raised. """ hProcess = self.get_handle(win32.PROCESS_VM_OPERATION) return win32.VirtualProtectEx(hProcess, lpAddress, dwSize, flNewProtect)
python
def mprotect(self, lpAddress, dwSize, flNewProtect): """ Set memory protection in the address space of the process. @see: U{http://msdn.microsoft.com/en-us/library/aa366899.aspx} @type lpAddress: int @param lpAddress: Address of memory to protect. @type dwSize: int @param dwSize: Number of bytes to protect. @type flNewProtect: int @param flNewProtect: New protect flags. @rtype: int @return: Old protect flags. @raise WindowsError: On error an exception is raised. """ hProcess = self.get_handle(win32.PROCESS_VM_OPERATION) return win32.VirtualProtectEx(hProcess, lpAddress, dwSize, flNewProtect)
[ "def", "mprotect", "(", "self", ",", "lpAddress", ",", "dwSize", ",", "flNewProtect", ")", ":", "hProcess", "=", "self", ".", "get_handle", "(", "win32", ".", "PROCESS_VM_OPERATION", ")", "return", "win32", ".", "VirtualProtectEx", "(", "hProcess", ",", "lpA...
Set memory protection in the address space of the process. @see: U{http://msdn.microsoft.com/en-us/library/aa366899.aspx} @type lpAddress: int @param lpAddress: Address of memory to protect. @type dwSize: int @param dwSize: Number of bytes to protect. @type flNewProtect: int @param flNewProtect: New protect flags. @rtype: int @return: Old protect flags. @raise WindowsError: On error an exception is raised.
[ "Set", "memory", "protection", "in", "the", "address", "space", "of", "the", "process", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L2494-L2515
train
209,716
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.free
def free(self, lpAddress): """ Frees memory from the address space of the process. @see: U{http://msdn.microsoft.com/en-us/library/aa366894(v=vs.85).aspx} @type lpAddress: int @param lpAddress: Address of memory to free. Must be the base address returned by L{malloc}. @raise WindowsError: On error an exception is raised. """ hProcess = self.get_handle(win32.PROCESS_VM_OPERATION) win32.VirtualFreeEx(hProcess, lpAddress)
python
def free(self, lpAddress): """ Frees memory from the address space of the process. @see: U{http://msdn.microsoft.com/en-us/library/aa366894(v=vs.85).aspx} @type lpAddress: int @param lpAddress: Address of memory to free. Must be the base address returned by L{malloc}. @raise WindowsError: On error an exception is raised. """ hProcess = self.get_handle(win32.PROCESS_VM_OPERATION) win32.VirtualFreeEx(hProcess, lpAddress)
[ "def", "free", "(", "self", ",", "lpAddress", ")", ":", "hProcess", "=", "self", ".", "get_handle", "(", "win32", ".", "PROCESS_VM_OPERATION", ")", "win32", ".", "VirtualFreeEx", "(", "hProcess", ",", "lpAddress", ")" ]
Frees memory from the address space of the process. @see: U{http://msdn.microsoft.com/en-us/library/aa366894(v=vs.85).aspx} @type lpAddress: int @param lpAddress: Address of memory to free. Must be the base address returned by L{malloc}. @raise WindowsError: On error an exception is raised.
[ "Frees", "memory", "from", "the", "address", "space", "of", "the", "process", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L2535-L2548
train
209,717
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.is_pointer
def is_pointer(self, address): """ Determines if an address is a valid code or data pointer. That is, the address must be valid and must point to code or data in the target process. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address is a valid code or data pointer. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.has_content()
python
def is_pointer(self, address): """ Determines if an address is a valid code or data pointer. That is, the address must be valid and must point to code or data in the target process. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address is a valid code or data pointer. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.has_content()
[ "def", "is_pointer", "(", "self", ",", "address", ")", ":", "try", ":", "mbi", "=", "self", ".", "mquery", "(", "address", ")", "except", "WindowsError", ":", "e", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "if", "e", ".", "winerror", ...
Determines if an address is a valid code or data pointer. That is, the address must be valid and must point to code or data in the target process. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address is a valid code or data pointer. @raise WindowsError: An exception is raised on error.
[ "Determines", "if", "an", "address", "is", "a", "valid", "code", "or", "data", "pointer", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L2552-L2574
train
209,718
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.is_address_valid
def is_address_valid(self, address): """ Determines if an address is a valid user mode address. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address is a valid user mode address. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return True
python
def is_address_valid(self, address): """ Determines if an address is a valid user mode address. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address is a valid user mode address. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return True
[ "def", "is_address_valid", "(", "self", ",", "address", ")", ":", "try", ":", "mbi", "=", "self", ".", "mquery", "(", "address", ")", "except", "WindowsError", ":", "e", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "if", "e", ".", "winerro...
Determines if an address is a valid user mode address. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address is a valid user mode address. @raise WindowsError: An exception is raised on error.
[ "Determines", "if", "an", "address", "is", "a", "valid", "user", "mode", "address", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L2576-L2595
train
209,719
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.is_address_free
def is_address_free(self, address): """ Determines if an address belongs to a free page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a free page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_free()
python
def is_address_free(self, address): """ Determines if an address belongs to a free page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a free page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_free()
[ "def", "is_address_free", "(", "self", ",", "address", ")", ":", "try", ":", "mbi", "=", "self", ".", "mquery", "(", "address", ")", "except", "WindowsError", ":", "e", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "if", "e", ".", "winerror...
Determines if an address belongs to a free page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a free page. @raise WindowsError: An exception is raised on error.
[ "Determines", "if", "an", "address", "belongs", "to", "a", "free", "page", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L2597-L2618
train
209,720
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.is_address_reserved
def is_address_reserved(self, address): """ Determines if an address belongs to a reserved page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a reserved page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_reserved()
python
def is_address_reserved(self, address): """ Determines if an address belongs to a reserved page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a reserved page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_reserved()
[ "def", "is_address_reserved", "(", "self", ",", "address", ")", ":", "try", ":", "mbi", "=", "self", ".", "mquery", "(", "address", ")", "except", "WindowsError", ":", "e", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "if", "e", ".", "wine...
Determines if an address belongs to a reserved page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a reserved page. @raise WindowsError: An exception is raised on error.
[ "Determines", "if", "an", "address", "belongs", "to", "a", "reserved", "page", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L2620-L2641
train
209,721
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.is_address_commited
def is_address_commited(self, address): """ Determines if an address belongs to a commited page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_commited()
python
def is_address_commited(self, address): """ Determines if an address belongs to a commited page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_commited()
[ "def", "is_address_commited", "(", "self", ",", "address", ")", ":", "try", ":", "mbi", "=", "self", ".", "mquery", "(", "address", ")", "except", "WindowsError", ":", "e", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "if", "e", ".", "wine...
Determines if an address belongs to a commited page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited page. @raise WindowsError: An exception is raised on error.
[ "Determines", "if", "an", "address", "belongs", "to", "a", "commited", "page", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L2643-L2664
train
209,722
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.is_address_guard
def is_address_guard(self, address): """ Determines if an address belongs to a guard page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a guard page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_guard()
python
def is_address_guard(self, address): """ Determines if an address belongs to a guard page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a guard page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_guard()
[ "def", "is_address_guard", "(", "self", ",", "address", ")", ":", "try", ":", "mbi", "=", "self", ".", "mquery", "(", "address", ")", "except", "WindowsError", ":", "e", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "if", "e", ".", "winerro...
Determines if an address belongs to a guard page. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a guard page. @raise WindowsError: An exception is raised on error.
[ "Determines", "if", "an", "address", "belongs", "to", "a", "guard", "page", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L2666-L2687
train
209,723
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.is_address_readable
def is_address_readable(self, address): """ Determines if an address belongs to a commited and readable page. The page may or may not have additional permissions. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited and readable page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_readable()
python
def is_address_readable(self, address): """ Determines if an address belongs to a commited and readable page. The page may or may not have additional permissions. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited and readable page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_readable()
[ "def", "is_address_readable", "(", "self", ",", "address", ")", ":", "try", ":", "mbi", "=", "self", ".", "mquery", "(", "address", ")", "except", "WindowsError", ":", "e", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "if", "e", ".", "wine...
Determines if an address belongs to a commited and readable page. The page may or may not have additional permissions. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited and readable page. @raise WindowsError: An exception is raised on error.
[ "Determines", "if", "an", "address", "belongs", "to", "a", "commited", "and", "readable", "page", ".", "The", "page", "may", "or", "may", "not", "have", "additional", "permissions", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L2689-L2712
train
209,724
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.is_address_writeable
def is_address_writeable(self, address): """ Determines if an address belongs to a commited and writeable page. The page may or may not have additional permissions. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited and writeable page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_writeable()
python
def is_address_writeable(self, address): """ Determines if an address belongs to a commited and writeable page. The page may or may not have additional permissions. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited and writeable page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_writeable()
[ "def", "is_address_writeable", "(", "self", ",", "address", ")", ":", "try", ":", "mbi", "=", "self", ".", "mquery", "(", "address", ")", "except", "WindowsError", ":", "e", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "if", "e", ".", "win...
Determines if an address belongs to a commited and writeable page. The page may or may not have additional permissions. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited and writeable page. @raise WindowsError: An exception is raised on error.
[ "Determines", "if", "an", "address", "belongs", "to", "a", "commited", "and", "writeable", "page", ".", "The", "page", "may", "or", "may", "not", "have", "additional", "permissions", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L2714-L2737
train
209,725
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.is_address_copy_on_write
def is_address_copy_on_write(self, address): """ Determines if an address belongs to a commited, copy-on-write page. The page may or may not have additional permissions. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited, copy-on-write page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_copy_on_write()
python
def is_address_copy_on_write(self, address): """ Determines if an address belongs to a commited, copy-on-write page. The page may or may not have additional permissions. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited, copy-on-write page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_copy_on_write()
[ "def", "is_address_copy_on_write", "(", "self", ",", "address", ")", ":", "try", ":", "mbi", "=", "self", ".", "mquery", "(", "address", ")", "except", "WindowsError", ":", "e", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "if", "e", ".", ...
Determines if an address belongs to a commited, copy-on-write page. The page may or may not have additional permissions. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited, copy-on-write page. @raise WindowsError: An exception is raised on error.
[ "Determines", "if", "an", "address", "belongs", "to", "a", "commited", "copy", "-", "on", "-", "write", "page", ".", "The", "page", "may", "or", "may", "not", "have", "additional", "permissions", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L2739-L2762
train
209,726
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.is_address_executable
def is_address_executable(self, address): """ Determines if an address belongs to a commited and executable page. The page may or may not have additional permissions. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited and executable page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_executable()
python
def is_address_executable(self, address): """ Determines if an address belongs to a commited and executable page. The page may or may not have additional permissions. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited and executable page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_executable()
[ "def", "is_address_executable", "(", "self", ",", "address", ")", ":", "try", ":", "mbi", "=", "self", ".", "mquery", "(", "address", ")", "except", "WindowsError", ":", "e", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "if", "e", ".", "wi...
Determines if an address belongs to a commited and executable page. The page may or may not have additional permissions. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited and executable page. @raise WindowsError: An exception is raised on error.
[ "Determines", "if", "an", "address", "belongs", "to", "a", "commited", "and", "executable", "page", ".", "The", "page", "may", "or", "may", "not", "have", "additional", "permissions", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L2764-L2787
train
209,727
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.is_address_executable_and_writeable
def is_address_executable_and_writeable(self, address): """ Determines if an address belongs to a commited, writeable and executable page. The page may or may not have additional permissions. Looking for writeable and executable pages is important when exploiting a software vulnerability. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited, writeable and executable page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_executable_and_writeable()
python
def is_address_executable_and_writeable(self, address): """ Determines if an address belongs to a commited, writeable and executable page. The page may or may not have additional permissions. Looking for writeable and executable pages is important when exploiting a software vulnerability. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited, writeable and executable page. @raise WindowsError: An exception is raised on error. """ try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise return mbi.is_executable_and_writeable()
[ "def", "is_address_executable_and_writeable", "(", "self", ",", "address", ")", ":", "try", ":", "mbi", "=", "self", ".", "mquery", "(", "address", ")", "except", "WindowsError", ":", "e", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "if", "e"...
Determines if an address belongs to a commited, writeable and executable page. The page may or may not have additional permissions. Looking for writeable and executable pages is important when exploiting a software vulnerability. @note: Returns always C{False} for kernel mode addresses. @type address: int @param address: Memory address to query. @rtype: bool @return: C{True} if the address belongs to a commited, writeable and executable page. @raise WindowsError: An exception is raised on error.
[ "Determines", "if", "an", "address", "belongs", "to", "a", "commited", "writeable", "and", "executable", "page", ".", "The", "page", "may", "or", "may", "not", "have", "additional", "permissions", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L2789-L2816
train
209,728
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.is_buffer
def is_buffer(self, address, size): """ Determines if the given memory area is a valid code or data buffer. @note: Returns always C{False} for kernel mode addresses. @see: L{mquery} @type address: int @param address: Memory address. @type size: int @param size: Number of bytes. Must be greater than zero. @rtype: bool @return: C{True} if the memory area is a valid code or data buffer, C{False} otherwise. @raise ValueError: The size argument must be greater than zero. @raise WindowsError: On error an exception is raised. """ if size <= 0: raise ValueError("The size argument must be greater than zero") while size > 0: try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise if not mbi.has_content(): return False size = size - mbi.RegionSize return True
python
def is_buffer(self, address, size): """ Determines if the given memory area is a valid code or data buffer. @note: Returns always C{False} for kernel mode addresses. @see: L{mquery} @type address: int @param address: Memory address. @type size: int @param size: Number of bytes. Must be greater than zero. @rtype: bool @return: C{True} if the memory area is a valid code or data buffer, C{False} otherwise. @raise ValueError: The size argument must be greater than zero. @raise WindowsError: On error an exception is raised. """ if size <= 0: raise ValueError("The size argument must be greater than zero") while size > 0: try: mbi = self.mquery(address) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: return False raise if not mbi.has_content(): return False size = size - mbi.RegionSize return True
[ "def", "is_buffer", "(", "self", ",", "address", ",", "size", ")", ":", "if", "size", "<=", "0", ":", "raise", "ValueError", "(", "\"The size argument must be greater than zero\"", ")", "while", "size", ">", "0", ":", "try", ":", "mbi", "=", "self", ".", ...
Determines if the given memory area is a valid code or data buffer. @note: Returns always C{False} for kernel mode addresses. @see: L{mquery} @type address: int @param address: Memory address. @type size: int @param size: Number of bytes. Must be greater than zero. @rtype: bool @return: C{True} if the memory area is a valid code or data buffer, C{False} otherwise. @raise ValueError: The size argument must be greater than zero. @raise WindowsError: On error an exception is raised.
[ "Determines", "if", "the", "given", "memory", "area", "is", "a", "valid", "code", "or", "data", "buffer", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L2818-L2852
train
209,729
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.iter_memory_map
def iter_memory_map(self, minAddr = None, maxAddr = None): """ Produces an iterator over the memory map to the process address space. Optionally restrict the map to the given address range. @see: L{mquery} @type minAddr: int @param minAddr: (Optional) Starting address in address range to query. @type maxAddr: int @param maxAddr: (Optional) Ending address in address range to query. @rtype: iterator of L{win32.MemoryBasicInformation} @return: List of memory region information objects. """ minAddr, maxAddr = MemoryAddresses.align_address_range(minAddr,maxAddr) prevAddr = minAddr - 1 currentAddr = minAddr while prevAddr < currentAddr < maxAddr: try: mbi = self.mquery(currentAddr) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: break raise yield mbi prevAddr = currentAddr currentAddr = mbi.BaseAddress + mbi.RegionSize
python
def iter_memory_map(self, minAddr = None, maxAddr = None): """ Produces an iterator over the memory map to the process address space. Optionally restrict the map to the given address range. @see: L{mquery} @type minAddr: int @param minAddr: (Optional) Starting address in address range to query. @type maxAddr: int @param maxAddr: (Optional) Ending address in address range to query. @rtype: iterator of L{win32.MemoryBasicInformation} @return: List of memory region information objects. """ minAddr, maxAddr = MemoryAddresses.align_address_range(minAddr,maxAddr) prevAddr = minAddr - 1 currentAddr = minAddr while prevAddr < currentAddr < maxAddr: try: mbi = self.mquery(currentAddr) except WindowsError: e = sys.exc_info()[1] if e.winerror == win32.ERROR_INVALID_PARAMETER: break raise yield mbi prevAddr = currentAddr currentAddr = mbi.BaseAddress + mbi.RegionSize
[ "def", "iter_memory_map", "(", "self", ",", "minAddr", "=", "None", ",", "maxAddr", "=", "None", ")", ":", "minAddr", ",", "maxAddr", "=", "MemoryAddresses", ".", "align_address_range", "(", "minAddr", ",", "maxAddr", ")", "prevAddr", "=", "minAddr", "-", ...
Produces an iterator over the memory map to the process address space. Optionally restrict the map to the given address range. @see: L{mquery} @type minAddr: int @param minAddr: (Optional) Starting address in address range to query. @type maxAddr: int @param maxAddr: (Optional) Ending address in address range to query. @rtype: iterator of L{win32.MemoryBasicInformation} @return: List of memory region information objects.
[ "Produces", "an", "iterator", "over", "the", "memory", "map", "to", "the", "process", "address", "space", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L3073-L3103
train
209,730
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.get_mapped_filenames
def get_mapped_filenames(self, memoryMap = None): """ Retrieves the filenames for memory mapped files in the debugee. @type memoryMap: list( L{win32.MemoryBasicInformation} ) @param memoryMap: (Optional) Memory map returned by L{get_memory_map}. If not given, the current memory map is used. @rtype: dict( int S{->} str ) @return: Dictionary mapping memory addresses to file names. Native filenames are converted to Win32 filenames when possible. """ hProcess = self.get_handle( win32.PROCESS_VM_READ | win32.PROCESS_QUERY_INFORMATION ) if not memoryMap: memoryMap = self.get_memory_map() mappedFilenames = dict() for mbi in memoryMap: if mbi.Type not in (win32.MEM_IMAGE, win32.MEM_MAPPED): continue baseAddress = mbi.BaseAddress fileName = "" try: fileName = win32.GetMappedFileName(hProcess, baseAddress) fileName = PathOperations.native_to_win32_pathname(fileName) except WindowsError: #e = sys.exc_info()[1] #try: # msg = "Can't get mapped file name at address %s in process " \ # "%d, reason: %s" % (HexDump.address(baseAddress), # self.get_pid(), # e.strerror) # warnings.warn(msg, Warning) #except Exception: pass mappedFilenames[baseAddress] = fileName return mappedFilenames
python
def get_mapped_filenames(self, memoryMap = None): """ Retrieves the filenames for memory mapped files in the debugee. @type memoryMap: list( L{win32.MemoryBasicInformation} ) @param memoryMap: (Optional) Memory map returned by L{get_memory_map}. If not given, the current memory map is used. @rtype: dict( int S{->} str ) @return: Dictionary mapping memory addresses to file names. Native filenames are converted to Win32 filenames when possible. """ hProcess = self.get_handle( win32.PROCESS_VM_READ | win32.PROCESS_QUERY_INFORMATION ) if not memoryMap: memoryMap = self.get_memory_map() mappedFilenames = dict() for mbi in memoryMap: if mbi.Type not in (win32.MEM_IMAGE, win32.MEM_MAPPED): continue baseAddress = mbi.BaseAddress fileName = "" try: fileName = win32.GetMappedFileName(hProcess, baseAddress) fileName = PathOperations.native_to_win32_pathname(fileName) except WindowsError: #e = sys.exc_info()[1] #try: # msg = "Can't get mapped file name at address %s in process " \ # "%d, reason: %s" % (HexDump.address(baseAddress), # self.get_pid(), # e.strerror) # warnings.warn(msg, Warning) #except Exception: pass mappedFilenames[baseAddress] = fileName return mappedFilenames
[ "def", "get_mapped_filenames", "(", "self", ",", "memoryMap", "=", "None", ")", ":", "hProcess", "=", "self", ".", "get_handle", "(", "win32", ".", "PROCESS_VM_READ", "|", "win32", ".", "PROCESS_QUERY_INFORMATION", ")", "if", "not", "memoryMap", ":", "memoryMa...
Retrieves the filenames for memory mapped files in the debugee. @type memoryMap: list( L{win32.MemoryBasicInformation} ) @param memoryMap: (Optional) Memory map returned by L{get_memory_map}. If not given, the current memory map is used. @rtype: dict( int S{->} str ) @return: Dictionary mapping memory addresses to file names. Native filenames are converted to Win32 filenames when possible.
[ "Retrieves", "the", "filenames", "for", "memory", "mapped", "files", "in", "the", "debugee", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L3105-L3141
train
209,731
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.iter_memory_snapshot
def iter_memory_snapshot(self, minAddr = None, maxAddr = None): """ Returns an iterator that allows you to go through the memory contents of a process. It's basically the same as the L{take_memory_snapshot} method, but it takes the snapshot of each memory region as it goes, as opposed to taking the whole snapshot at once. This allows you to work with very large snapshots without a significant performance penalty. Example:: # Print the memory contents of a process. process.suspend() try: snapshot = process.generate_memory_snapshot() for mbi in snapshot: print HexDump.hexblock(mbi.content, mbi.BaseAddress) finally: process.resume() The downside of this is the process must remain suspended while iterating the snapshot, otherwise strange things may happen. The snapshot can only iterated once. To be able to iterate indefinitely call the L{generate_memory_snapshot} method instead. You can also iterate the memory of a dead process, just as long as the last open handle to it hasn't been closed. @see: L{take_memory_snapshot} @type minAddr: int @param minAddr: (Optional) Starting address in address range to query. @type maxAddr: int @param maxAddr: (Optional) Ending address in address range to query. @rtype: iterator of L{win32.MemoryBasicInformation} @return: Iterator of memory region information objects. Two extra properties are added to these objects: - C{filename}: Mapped filename, or C{None}. - C{content}: Memory contents, or C{None}. """ # One may feel tempted to include calls to self.suspend() and # self.resume() here, but that wouldn't work on a dead process. # It also wouldn't be needed when debugging since the process is # already suspended when the debug event arrives. So it's up to # the user to suspend the process if needed. # Get the memory map. memory = self.get_memory_map(minAddr, maxAddr) # Abort if the map couldn't be retrieved. if not memory: return # Get the mapped filenames. # Don't fail on access denied errors. try: filenames = self.get_mapped_filenames(memory) except WindowsError: e = sys.exc_info()[1] if e.winerror != win32.ERROR_ACCESS_DENIED: raise filenames = dict() # Trim the first memory information block if needed. if minAddr is not None: minAddr = MemoryAddresses.align_address_to_page_start(minAddr) mbi = memory[0] if mbi.BaseAddress < minAddr: mbi.RegionSize = mbi.BaseAddress + mbi.RegionSize - minAddr mbi.BaseAddress = minAddr # Trim the last memory information block if needed. if maxAddr is not None: if maxAddr != MemoryAddresses.align_address_to_page_start(maxAddr): maxAddr = MemoryAddresses.align_address_to_page_end(maxAddr) mbi = memory[-1] if mbi.BaseAddress + mbi.RegionSize > maxAddr: mbi.RegionSize = maxAddr - mbi.BaseAddress # Read the contents of each block and yield it. while memory: mbi = memory.pop(0) # so the garbage collector can take it mbi.filename = filenames.get(mbi.BaseAddress, None) if mbi.has_content(): mbi.content = self.read(mbi.BaseAddress, mbi.RegionSize) else: mbi.content = None yield mbi
python
def iter_memory_snapshot(self, minAddr = None, maxAddr = None): """ Returns an iterator that allows you to go through the memory contents of a process. It's basically the same as the L{take_memory_snapshot} method, but it takes the snapshot of each memory region as it goes, as opposed to taking the whole snapshot at once. This allows you to work with very large snapshots without a significant performance penalty. Example:: # Print the memory contents of a process. process.suspend() try: snapshot = process.generate_memory_snapshot() for mbi in snapshot: print HexDump.hexblock(mbi.content, mbi.BaseAddress) finally: process.resume() The downside of this is the process must remain suspended while iterating the snapshot, otherwise strange things may happen. The snapshot can only iterated once. To be able to iterate indefinitely call the L{generate_memory_snapshot} method instead. You can also iterate the memory of a dead process, just as long as the last open handle to it hasn't been closed. @see: L{take_memory_snapshot} @type minAddr: int @param minAddr: (Optional) Starting address in address range to query. @type maxAddr: int @param maxAddr: (Optional) Ending address in address range to query. @rtype: iterator of L{win32.MemoryBasicInformation} @return: Iterator of memory region information objects. Two extra properties are added to these objects: - C{filename}: Mapped filename, or C{None}. - C{content}: Memory contents, or C{None}. """ # One may feel tempted to include calls to self.suspend() and # self.resume() here, but that wouldn't work on a dead process. # It also wouldn't be needed when debugging since the process is # already suspended when the debug event arrives. So it's up to # the user to suspend the process if needed. # Get the memory map. memory = self.get_memory_map(minAddr, maxAddr) # Abort if the map couldn't be retrieved. if not memory: return # Get the mapped filenames. # Don't fail on access denied errors. try: filenames = self.get_mapped_filenames(memory) except WindowsError: e = sys.exc_info()[1] if e.winerror != win32.ERROR_ACCESS_DENIED: raise filenames = dict() # Trim the first memory information block if needed. if minAddr is not None: minAddr = MemoryAddresses.align_address_to_page_start(minAddr) mbi = memory[0] if mbi.BaseAddress < minAddr: mbi.RegionSize = mbi.BaseAddress + mbi.RegionSize - minAddr mbi.BaseAddress = minAddr # Trim the last memory information block if needed. if maxAddr is not None: if maxAddr != MemoryAddresses.align_address_to_page_start(maxAddr): maxAddr = MemoryAddresses.align_address_to_page_end(maxAddr) mbi = memory[-1] if mbi.BaseAddress + mbi.RegionSize > maxAddr: mbi.RegionSize = maxAddr - mbi.BaseAddress # Read the contents of each block and yield it. while memory: mbi = memory.pop(0) # so the garbage collector can take it mbi.filename = filenames.get(mbi.BaseAddress, None) if mbi.has_content(): mbi.content = self.read(mbi.BaseAddress, mbi.RegionSize) else: mbi.content = None yield mbi
[ "def", "iter_memory_snapshot", "(", "self", ",", "minAddr", "=", "None", ",", "maxAddr", "=", "None", ")", ":", "# One may feel tempted to include calls to self.suspend() and", "# self.resume() here, but that wouldn't work on a dead process.", "# It also wouldn't be needed when debug...
Returns an iterator that allows you to go through the memory contents of a process. It's basically the same as the L{take_memory_snapshot} method, but it takes the snapshot of each memory region as it goes, as opposed to taking the whole snapshot at once. This allows you to work with very large snapshots without a significant performance penalty. Example:: # Print the memory contents of a process. process.suspend() try: snapshot = process.generate_memory_snapshot() for mbi in snapshot: print HexDump.hexblock(mbi.content, mbi.BaseAddress) finally: process.resume() The downside of this is the process must remain suspended while iterating the snapshot, otherwise strange things may happen. The snapshot can only iterated once. To be able to iterate indefinitely call the L{generate_memory_snapshot} method instead. You can also iterate the memory of a dead process, just as long as the last open handle to it hasn't been closed. @see: L{take_memory_snapshot} @type minAddr: int @param minAddr: (Optional) Starting address in address range to query. @type maxAddr: int @param maxAddr: (Optional) Ending address in address range to query. @rtype: iterator of L{win32.MemoryBasicInformation} @return: Iterator of memory region information objects. Two extra properties are added to these objects: - C{filename}: Mapped filename, or C{None}. - C{content}: Memory contents, or C{None}.
[ "Returns", "an", "iterator", "that", "allows", "you", "to", "go", "through", "the", "memory", "contents", "of", "a", "process", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L3188-L3279
train
209,732
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.restore_memory_snapshot
def restore_memory_snapshot(self, snapshot, bSkipMappedFiles = True, bSkipOnError = False): """ Attempts to restore the memory state as it was when the given snapshot was taken. @warning: Currently only the memory contents, state and protect bits are restored. Under some circumstances this method may fail (for example if memory was freed and then reused by a mapped file). @type snapshot: list( L{win32.MemoryBasicInformation} ) @param snapshot: Memory snapshot returned by L{take_memory_snapshot}. Snapshots returned by L{generate_memory_snapshot} don't work here. @type bSkipMappedFiles: bool @param bSkipMappedFiles: C{True} to avoid restoring the contents of memory mapped files, C{False} otherwise. Use with care! Setting this to C{False} can cause undesired side effects - changes to memory mapped files may be written to disk by the OS. Also note that most mapped files are typically executables and don't change, so trying to restore their contents is usually a waste of time. @type bSkipOnError: bool @param bSkipOnError: C{True} to issue a warning when an error occurs during the restoration of the snapshot, C{False} to stop and raise an exception instead. Use with care! Setting this to C{True} will cause the debugger to falsely believe the memory snapshot has been correctly restored. @raise WindowsError: An error occured while restoring the snapshot. @raise RuntimeError: An error occured while restoring the snapshot. @raise TypeError: A snapshot of the wrong type was passed. """ if not snapshot or not isinstance(snapshot, list) \ or not isinstance(snapshot[0], win32.MemoryBasicInformation): raise TypeError( "Only snapshots returned by " \ "take_memory_snapshot() can be used here." ) # Get the process handle. hProcess = self.get_handle( win32.PROCESS_VM_WRITE | win32.PROCESS_VM_OPERATION | win32.PROCESS_SUSPEND_RESUME | win32.PROCESS_QUERY_INFORMATION ) # Freeze the process. self.suspend() try: # For each memory region in the snapshot... for old_mbi in snapshot: # If the region matches, restore it directly. new_mbi = self.mquery(old_mbi.BaseAddress) if new_mbi.BaseAddress == old_mbi.BaseAddress and \ new_mbi.RegionSize == old_mbi.RegionSize: self.__restore_mbi(hProcess, new_mbi, old_mbi, bSkipMappedFiles) # If the region doesn't match, restore it page by page. else: # We need a copy so we don't corrupt the snapshot. old_mbi = win32.MemoryBasicInformation(old_mbi) # Get the overlapping range of pages. old_start = old_mbi.BaseAddress old_end = old_start + old_mbi.RegionSize new_start = new_mbi.BaseAddress new_end = new_start + new_mbi.RegionSize if old_start > new_start: start = old_start else: start = new_start if old_end < new_end: end = old_end else: end = new_end # Restore each page in the overlapping range. step = MemoryAddresses.pageSize old_mbi.RegionSize = step new_mbi.RegionSize = step address = start while address < end: old_mbi.BaseAddress = address new_mbi.BaseAddress = address self.__restore_mbi(hProcess, new_mbi, old_mbi, bSkipMappedFiles, bSkipOnError) address = address + step # Resume execution. finally: self.resume()
python
def restore_memory_snapshot(self, snapshot, bSkipMappedFiles = True, bSkipOnError = False): """ Attempts to restore the memory state as it was when the given snapshot was taken. @warning: Currently only the memory contents, state and protect bits are restored. Under some circumstances this method may fail (for example if memory was freed and then reused by a mapped file). @type snapshot: list( L{win32.MemoryBasicInformation} ) @param snapshot: Memory snapshot returned by L{take_memory_snapshot}. Snapshots returned by L{generate_memory_snapshot} don't work here. @type bSkipMappedFiles: bool @param bSkipMappedFiles: C{True} to avoid restoring the contents of memory mapped files, C{False} otherwise. Use with care! Setting this to C{False} can cause undesired side effects - changes to memory mapped files may be written to disk by the OS. Also note that most mapped files are typically executables and don't change, so trying to restore their contents is usually a waste of time. @type bSkipOnError: bool @param bSkipOnError: C{True} to issue a warning when an error occurs during the restoration of the snapshot, C{False} to stop and raise an exception instead. Use with care! Setting this to C{True} will cause the debugger to falsely believe the memory snapshot has been correctly restored. @raise WindowsError: An error occured while restoring the snapshot. @raise RuntimeError: An error occured while restoring the snapshot. @raise TypeError: A snapshot of the wrong type was passed. """ if not snapshot or not isinstance(snapshot, list) \ or not isinstance(snapshot[0], win32.MemoryBasicInformation): raise TypeError( "Only snapshots returned by " \ "take_memory_snapshot() can be used here." ) # Get the process handle. hProcess = self.get_handle( win32.PROCESS_VM_WRITE | win32.PROCESS_VM_OPERATION | win32.PROCESS_SUSPEND_RESUME | win32.PROCESS_QUERY_INFORMATION ) # Freeze the process. self.suspend() try: # For each memory region in the snapshot... for old_mbi in snapshot: # If the region matches, restore it directly. new_mbi = self.mquery(old_mbi.BaseAddress) if new_mbi.BaseAddress == old_mbi.BaseAddress and \ new_mbi.RegionSize == old_mbi.RegionSize: self.__restore_mbi(hProcess, new_mbi, old_mbi, bSkipMappedFiles) # If the region doesn't match, restore it page by page. else: # We need a copy so we don't corrupt the snapshot. old_mbi = win32.MemoryBasicInformation(old_mbi) # Get the overlapping range of pages. old_start = old_mbi.BaseAddress old_end = old_start + old_mbi.RegionSize new_start = new_mbi.BaseAddress new_end = new_start + new_mbi.RegionSize if old_start > new_start: start = old_start else: start = new_start if old_end < new_end: end = old_end else: end = new_end # Restore each page in the overlapping range. step = MemoryAddresses.pageSize old_mbi.RegionSize = step new_mbi.RegionSize = step address = start while address < end: old_mbi.BaseAddress = address new_mbi.BaseAddress = address self.__restore_mbi(hProcess, new_mbi, old_mbi, bSkipMappedFiles, bSkipOnError) address = address + step # Resume execution. finally: self.resume()
[ "def", "restore_memory_snapshot", "(", "self", ",", "snapshot", ",", "bSkipMappedFiles", "=", "True", ",", "bSkipOnError", "=", "False", ")", ":", "if", "not", "snapshot", "or", "not", "isinstance", "(", "snapshot", ",", "list", ")", "or", "not", "isinstance...
Attempts to restore the memory state as it was when the given snapshot was taken. @warning: Currently only the memory contents, state and protect bits are restored. Under some circumstances this method may fail (for example if memory was freed and then reused by a mapped file). @type snapshot: list( L{win32.MemoryBasicInformation} ) @param snapshot: Memory snapshot returned by L{take_memory_snapshot}. Snapshots returned by L{generate_memory_snapshot} don't work here. @type bSkipMappedFiles: bool @param bSkipMappedFiles: C{True} to avoid restoring the contents of memory mapped files, C{False} otherwise. Use with care! Setting this to C{False} can cause undesired side effects - changes to memory mapped files may be written to disk by the OS. Also note that most mapped files are typically executables and don't change, so trying to restore their contents is usually a waste of time. @type bSkipOnError: bool @param bSkipOnError: C{True} to issue a warning when an error occurs during the restoration of the snapshot, C{False} to stop and raise an exception instead. Use with care! Setting this to C{True} will cause the debugger to falsely believe the memory snapshot has been correctly restored. @raise WindowsError: An error occured while restoring the snapshot. @raise RuntimeError: An error occured while restoring the snapshot. @raise TypeError: A snapshot of the wrong type was passed.
[ "Attempts", "to", "restore", "the", "memory", "state", "as", "it", "was", "when", "the", "given", "snapshot", "was", "taken", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L3321-L3414
train
209,733
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
Process.inject_code
def inject_code(self, payload, lpParameter = 0): """ Injects relocatable code into the process memory and executes it. @warning: Don't forget to free the memory when you're done with it! Otherwise you'll be leaking memory in the target process. @see: L{inject_dll} @type payload: str @param payload: Relocatable code to run in a new thread. @type lpParameter: int @param lpParameter: (Optional) Parameter to be pushed in the stack. @rtype: tuple( L{Thread}, int ) @return: The injected Thread object and the memory address where the code was written. @raise WindowsError: An exception is raised on error. """ # Uncomment for debugging... ## payload = '\xCC' + payload # Allocate the memory for the shellcode. lpStartAddress = self.malloc(len(payload)) # Catch exceptions so we can free the memory on error. try: # Write the shellcode to our memory location. self.write(lpStartAddress, payload) # Start a new thread for the shellcode to run. aThread = self.start_thread(lpStartAddress, lpParameter, bSuspended = False) # Remember the shellcode address. # It will be freed ONLY by the Thread.kill() method # and the EventHandler class, otherwise you'll have to # free it in your code, or have your shellcode clean up # after itself (recommended). aThread.pInjectedMemory = lpStartAddress # Free the memory on error. except Exception: self.free(lpStartAddress) raise # Return the Thread object and the shellcode address. return aThread, lpStartAddress
python
def inject_code(self, payload, lpParameter = 0): """ Injects relocatable code into the process memory and executes it. @warning: Don't forget to free the memory when you're done with it! Otherwise you'll be leaking memory in the target process. @see: L{inject_dll} @type payload: str @param payload: Relocatable code to run in a new thread. @type lpParameter: int @param lpParameter: (Optional) Parameter to be pushed in the stack. @rtype: tuple( L{Thread}, int ) @return: The injected Thread object and the memory address where the code was written. @raise WindowsError: An exception is raised on error. """ # Uncomment for debugging... ## payload = '\xCC' + payload # Allocate the memory for the shellcode. lpStartAddress = self.malloc(len(payload)) # Catch exceptions so we can free the memory on error. try: # Write the shellcode to our memory location. self.write(lpStartAddress, payload) # Start a new thread for the shellcode to run. aThread = self.start_thread(lpStartAddress, lpParameter, bSuspended = False) # Remember the shellcode address. # It will be freed ONLY by the Thread.kill() method # and the EventHandler class, otherwise you'll have to # free it in your code, or have your shellcode clean up # after itself (recommended). aThread.pInjectedMemory = lpStartAddress # Free the memory on error. except Exception: self.free(lpStartAddress) raise # Return the Thread object and the shellcode address. return aThread, lpStartAddress
[ "def", "inject_code", "(", "self", ",", "payload", ",", "lpParameter", "=", "0", ")", ":", "# Uncomment for debugging...", "## payload = '\\xCC' + payload", "# Allocate the memory for the shellcode.", "lpStartAddress", "=", "self", ".", "malloc", "(", "len", "(", ...
Injects relocatable code into the process memory and executes it. @warning: Don't forget to free the memory when you're done with it! Otherwise you'll be leaking memory in the target process. @see: L{inject_dll} @type payload: str @param payload: Relocatable code to run in a new thread. @type lpParameter: int @param lpParameter: (Optional) Parameter to be pushed in the stack. @rtype: tuple( L{Thread}, int ) @return: The injected Thread object and the memory address where the code was written. @raise WindowsError: An exception is raised on error.
[ "Injects", "relocatable", "code", "into", "the", "process", "memory", "and", "executes", "it", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L3540-L3591
train
209,734
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
_ProcessContainer.get_pid_from_tid
def get_pid_from_tid(self, dwThreadId): """ Retrieves the global ID of the process that owns the thread. @type dwThreadId: int @param dwThreadId: Thread global ID. @rtype: int @return: Process global ID. @raise KeyError: The thread does not exist. """ try: # No good, because in XP and below it tries to get the PID # through the toolhelp API, and that's slow. We don't want # to scan for threads over and over for each call. ## dwProcessId = Thread(dwThreadId).get_pid() # This API only exists in Windows 2003, Vista and above. try: hThread = win32.OpenThread( win32.THREAD_QUERY_LIMITED_INFORMATION, False, dwThreadId) except WindowsError: e = sys.exc_info()[1] if e.winerror != win32.ERROR_ACCESS_DENIED: raise hThread = win32.OpenThread( win32.THREAD_QUERY_INFORMATION, False, dwThreadId) try: return win32.GetProcessIdOfThread(hThread) finally: hThread.close() # If all else fails, go through all processes in the snapshot # looking for the one that owns the thread we're looking for. # If the snapshot was empty the iteration should trigger an # automatic scan. Otherwise, it'll look for the thread in what # could possibly be an outdated snapshot. except Exception: for aProcess in self.iter_processes(): if aProcess.has_thread(dwThreadId): return aProcess.get_pid() # The thread wasn't found, so let's refresh the snapshot and retry. # Normally this shouldn't happen since this function is only useful # for the debugger, so the thread should already exist in the snapshot. self.scan_processes_and_threads() for aProcess in self.iter_processes(): if aProcess.has_thread(dwThreadId): return aProcess.get_pid() # No luck! It appears to be the thread doesn't exist after all. msg = "Unknown thread ID %d" % dwThreadId raise KeyError(msg)
python
def get_pid_from_tid(self, dwThreadId): """ Retrieves the global ID of the process that owns the thread. @type dwThreadId: int @param dwThreadId: Thread global ID. @rtype: int @return: Process global ID. @raise KeyError: The thread does not exist. """ try: # No good, because in XP and below it tries to get the PID # through the toolhelp API, and that's slow. We don't want # to scan for threads over and over for each call. ## dwProcessId = Thread(dwThreadId).get_pid() # This API only exists in Windows 2003, Vista and above. try: hThread = win32.OpenThread( win32.THREAD_QUERY_LIMITED_INFORMATION, False, dwThreadId) except WindowsError: e = sys.exc_info()[1] if e.winerror != win32.ERROR_ACCESS_DENIED: raise hThread = win32.OpenThread( win32.THREAD_QUERY_INFORMATION, False, dwThreadId) try: return win32.GetProcessIdOfThread(hThread) finally: hThread.close() # If all else fails, go through all processes in the snapshot # looking for the one that owns the thread we're looking for. # If the snapshot was empty the iteration should trigger an # automatic scan. Otherwise, it'll look for the thread in what # could possibly be an outdated snapshot. except Exception: for aProcess in self.iter_processes(): if aProcess.has_thread(dwThreadId): return aProcess.get_pid() # The thread wasn't found, so let's refresh the snapshot and retry. # Normally this shouldn't happen since this function is only useful # for the debugger, so the thread should already exist in the snapshot. self.scan_processes_and_threads() for aProcess in self.iter_processes(): if aProcess.has_thread(dwThreadId): return aProcess.get_pid() # No luck! It appears to be the thread doesn't exist after all. msg = "Unknown thread ID %d" % dwThreadId raise KeyError(msg)
[ "def", "get_pid_from_tid", "(", "self", ",", "dwThreadId", ")", ":", "try", ":", "# No good, because in XP and below it tries to get the PID", "# through the toolhelp API, and that's slow. We don't want", "# to scan for threads over and over for each call.", "## dwProcessId = Th...
Retrieves the global ID of the process that owns the thread. @type dwThreadId: int @param dwThreadId: Thread global ID. @rtype: int @return: Process global ID. @raise KeyError: The thread does not exist.
[ "Retrieves", "the", "global", "ID", "of", "the", "process", "that", "owns", "the", "thread", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L4028-L4082
train
209,735
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
_ProcessContainer.argv_to_cmdline
def argv_to_cmdline(argv): """ Convert a list of arguments to a single command line string. @type argv: list( str ) @param argv: List of argument strings. The first element is the program to execute. @rtype: str @return: Command line string. """ cmdline = list() for token in argv: if not token: token = '""' else: if '"' in token: token = token.replace('"', '\\"') if ' ' in token or \ '\t' in token or \ '\n' in token or \ '\r' in token: token = '"%s"' % token cmdline.append(token) return ' '.join(cmdline)
python
def argv_to_cmdline(argv): """ Convert a list of arguments to a single command line string. @type argv: list( str ) @param argv: List of argument strings. The first element is the program to execute. @rtype: str @return: Command line string. """ cmdline = list() for token in argv: if not token: token = '""' else: if '"' in token: token = token.replace('"', '\\"') if ' ' in token or \ '\t' in token or \ '\n' in token or \ '\r' in token: token = '"%s"' % token cmdline.append(token) return ' '.join(cmdline)
[ "def", "argv_to_cmdline", "(", "argv", ")", ":", "cmdline", "=", "list", "(", ")", "for", "token", "in", "argv", ":", "if", "not", "token", ":", "token", "=", "'\"\"'", "else", ":", "if", "'\"'", "in", "token", ":", "token", "=", "token", ".", "rep...
Convert a list of arguments to a single command line string. @type argv: list( str ) @param argv: List of argument strings. The first element is the program to execute. @rtype: str @return: Command line string.
[ "Convert", "a", "list", "of", "arguments", "to", "a", "single", "command", "line", "string", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L4087-L4111
train
209,736
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
_ProcessContainer.get_explorer_pid
def get_explorer_pid(self): """ Tries to find the process ID for "explorer.exe". @rtype: int or None @return: Returns the process ID, or C{None} on error. """ try: exp = win32.SHGetFolderPath(win32.CSIDL_WINDOWS) except Exception: exp = None if not exp: exp = os.getenv('SystemRoot') if exp: exp = os.path.join(exp, 'explorer.exe') exp_list = self.find_processes_by_filename(exp) if exp_list: return exp_list[0][0].get_pid() return None
python
def get_explorer_pid(self): """ Tries to find the process ID for "explorer.exe". @rtype: int or None @return: Returns the process ID, or C{None} on error. """ try: exp = win32.SHGetFolderPath(win32.CSIDL_WINDOWS) except Exception: exp = None if not exp: exp = os.getenv('SystemRoot') if exp: exp = os.path.join(exp, 'explorer.exe') exp_list = self.find_processes_by_filename(exp) if exp_list: return exp_list[0][0].get_pid() return None
[ "def", "get_explorer_pid", "(", "self", ")", ":", "try", ":", "exp", "=", "win32", ".", "SHGetFolderPath", "(", "win32", ".", "CSIDL_WINDOWS", ")", "except", "Exception", ":", "exp", "=", "None", "if", "not", "exp", ":", "exp", "=", "os", ".", "getenv"...
Tries to find the process ID for "explorer.exe". @rtype: int or None @return: Returns the process ID, or C{None} on error.
[ "Tries", "to", "find", "the", "process", "ID", "for", "explorer", ".", "exe", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L4403-L4421
train
209,737
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
_ProcessContainer.scan
def scan(self): """ Populates the snapshot with running processes and threads, and loaded modules. Tipically this is the first method called after instantiating a L{System} object, as it makes a best effort approach to gathering information on running processes. @rtype: bool @return: C{True} if the snapshot is complete, C{False} if the debugger doesn't have permission to scan some processes. In either case, the snapshot is complete for all processes the debugger has access to. """ has_threads = True try: try: # Try using the Toolhelp API # to scan for processes and threads. self.scan_processes_and_threads() except Exception: # On error, try using the PSAPI to scan for process IDs only. self.scan_processes_fast() # Now try using the Toolhelp again to get the threads. for aProcess in self.__processDict.values(): if aProcess._get_thread_ids(): try: aProcess.scan_threads() except WindowsError: has_threads = False finally: # Try using the Remote Desktop API to scan for processes only. # This will update the filenames when it's not possible # to obtain them from the Toolhelp API. self.scan_processes() # When finished scanning for processes, try modules too. has_modules = self.scan_modules() # Try updating the process filenames when possible. has_full_names = self.scan_process_filenames() # Return the completion status. return has_threads and has_modules and has_full_names
python
def scan(self): """ Populates the snapshot with running processes and threads, and loaded modules. Tipically this is the first method called after instantiating a L{System} object, as it makes a best effort approach to gathering information on running processes. @rtype: bool @return: C{True} if the snapshot is complete, C{False} if the debugger doesn't have permission to scan some processes. In either case, the snapshot is complete for all processes the debugger has access to. """ has_threads = True try: try: # Try using the Toolhelp API # to scan for processes and threads. self.scan_processes_and_threads() except Exception: # On error, try using the PSAPI to scan for process IDs only. self.scan_processes_fast() # Now try using the Toolhelp again to get the threads. for aProcess in self.__processDict.values(): if aProcess._get_thread_ids(): try: aProcess.scan_threads() except WindowsError: has_threads = False finally: # Try using the Remote Desktop API to scan for processes only. # This will update the filenames when it's not possible # to obtain them from the Toolhelp API. self.scan_processes() # When finished scanning for processes, try modules too. has_modules = self.scan_modules() # Try updating the process filenames when possible. has_full_names = self.scan_process_filenames() # Return the completion status. return has_threads and has_modules and has_full_names
[ "def", "scan", "(", "self", ")", ":", "has_threads", "=", "True", "try", ":", "try", ":", "# Try using the Toolhelp API", "# to scan for processes and threads.", "self", ".", "scan_processes_and_threads", "(", ")", "except", "Exception", ":", "# On error, try using the ...
Populates the snapshot with running processes and threads, and loaded modules. Tipically this is the first method called after instantiating a L{System} object, as it makes a best effort approach to gathering information on running processes. @rtype: bool @return: C{True} if the snapshot is complete, C{False} if the debugger doesn't have permission to scan some processes. In either case, the snapshot is complete for all processes the debugger has access to.
[ "Populates", "the", "snapshot", "with", "running", "processes", "and", "threads", "and", "loaded", "modules", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L4427-L4476
train
209,738
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
_ProcessContainer.scan_processes_and_threads
def scan_processes_and_threads(self): """ Populates the snapshot with running processes and threads. Tipically you don't need to call this method directly, if unsure use L{scan} instead. @note: This method uses the Toolhelp API. @see: L{scan_modules} @raise WindowsError: An error occured while updating the snapshot. The snapshot was not modified. """ # The main module filename may be spoofed by malware, # since this information resides in usermode space. # See: http://www.ragestorm.net/blogs/?p=163 our_pid = win32.GetCurrentProcessId() dead_pids = set( compat.iterkeys(self.__processDict) ) found_tids = set() # Ignore our own process if it's in the snapshot for some reason if our_pid in dead_pids: dead_pids.remove(our_pid) # Take a snapshot of all processes and threads dwFlags = win32.TH32CS_SNAPPROCESS | win32.TH32CS_SNAPTHREAD with win32.CreateToolhelp32Snapshot(dwFlags) as hSnapshot: # Add all the processes (excluding our own) pe = win32.Process32First(hSnapshot) while pe is not None: dwProcessId = pe.th32ProcessID if dwProcessId != our_pid: if dwProcessId in dead_pids: dead_pids.remove(dwProcessId) if dwProcessId not in self.__processDict: aProcess = Process(dwProcessId, fileName=pe.szExeFile) self._add_process(aProcess) elif pe.szExeFile: aProcess = self.get_process(dwProcessId) if not aProcess.fileName: aProcess.fileName = pe.szExeFile pe = win32.Process32Next(hSnapshot) # Add all the threads te = win32.Thread32First(hSnapshot) while te is not None: dwProcessId = te.th32OwnerProcessID if dwProcessId != our_pid: if dwProcessId in dead_pids: dead_pids.remove(dwProcessId) if dwProcessId in self.__processDict: aProcess = self.get_process(dwProcessId) else: aProcess = Process(dwProcessId) self._add_process(aProcess) dwThreadId = te.th32ThreadID found_tids.add(dwThreadId) if not aProcess._has_thread_id(dwThreadId): aThread = Thread(dwThreadId, process = aProcess) aProcess._add_thread(aThread) te = win32.Thread32Next(hSnapshot) # Remove dead processes for pid in dead_pids: self._del_process(pid) # Remove dead threads for aProcess in compat.itervalues(self.__processDict): dead_tids = set( aProcess._get_thread_ids() ) dead_tids.difference_update(found_tids) for tid in dead_tids: aProcess._del_thread(tid)
python
def scan_processes_and_threads(self): """ Populates the snapshot with running processes and threads. Tipically you don't need to call this method directly, if unsure use L{scan} instead. @note: This method uses the Toolhelp API. @see: L{scan_modules} @raise WindowsError: An error occured while updating the snapshot. The snapshot was not modified. """ # The main module filename may be spoofed by malware, # since this information resides in usermode space. # See: http://www.ragestorm.net/blogs/?p=163 our_pid = win32.GetCurrentProcessId() dead_pids = set( compat.iterkeys(self.__processDict) ) found_tids = set() # Ignore our own process if it's in the snapshot for some reason if our_pid in dead_pids: dead_pids.remove(our_pid) # Take a snapshot of all processes and threads dwFlags = win32.TH32CS_SNAPPROCESS | win32.TH32CS_SNAPTHREAD with win32.CreateToolhelp32Snapshot(dwFlags) as hSnapshot: # Add all the processes (excluding our own) pe = win32.Process32First(hSnapshot) while pe is not None: dwProcessId = pe.th32ProcessID if dwProcessId != our_pid: if dwProcessId in dead_pids: dead_pids.remove(dwProcessId) if dwProcessId not in self.__processDict: aProcess = Process(dwProcessId, fileName=pe.szExeFile) self._add_process(aProcess) elif pe.szExeFile: aProcess = self.get_process(dwProcessId) if not aProcess.fileName: aProcess.fileName = pe.szExeFile pe = win32.Process32Next(hSnapshot) # Add all the threads te = win32.Thread32First(hSnapshot) while te is not None: dwProcessId = te.th32OwnerProcessID if dwProcessId != our_pid: if dwProcessId in dead_pids: dead_pids.remove(dwProcessId) if dwProcessId in self.__processDict: aProcess = self.get_process(dwProcessId) else: aProcess = Process(dwProcessId) self._add_process(aProcess) dwThreadId = te.th32ThreadID found_tids.add(dwThreadId) if not aProcess._has_thread_id(dwThreadId): aThread = Thread(dwThreadId, process = aProcess) aProcess._add_thread(aThread) te = win32.Thread32Next(hSnapshot) # Remove dead processes for pid in dead_pids: self._del_process(pid) # Remove dead threads for aProcess in compat.itervalues(self.__processDict): dead_tids = set( aProcess._get_thread_ids() ) dead_tids.difference_update(found_tids) for tid in dead_tids: aProcess._del_thread(tid)
[ "def", "scan_processes_and_threads", "(", "self", ")", ":", "# The main module filename may be spoofed by malware,", "# since this information resides in usermode space.", "# See: http://www.ragestorm.net/blogs/?p=163", "our_pid", "=", "win32", ".", "GetCurrentProcessId", "(", ")", "...
Populates the snapshot with running processes and threads. Tipically you don't need to call this method directly, if unsure use L{scan} instead. @note: This method uses the Toolhelp API. @see: L{scan_modules} @raise WindowsError: An error occured while updating the snapshot. The snapshot was not modified.
[ "Populates", "the", "snapshot", "with", "running", "processes", "and", "threads", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L4478-L4553
train
209,739
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
_ProcessContainer.scan_processes
def scan_processes(self): """ Populates the snapshot with running processes. Tipically you don't need to call this method directly, if unsure use L{scan} instead. @note: This method uses the Remote Desktop API instead of the Toolhelp API. It might give slightly different results, especially if the current process does not have full privileges. @note: This method will only retrieve process filenames. To get the process pathnames instead, B{after} this method call L{scan_process_filenames}. @raise WindowsError: An error occured while updating the snapshot. The snapshot was not modified. """ # Get the previous list of PIDs. # We'll be removing live PIDs from it as we find them. our_pid = win32.GetCurrentProcessId() dead_pids = set( compat.iterkeys(self.__processDict) ) # Ignore our own PID. if our_pid in dead_pids: dead_pids.remove(our_pid) # Get the list of processes from the Remote Desktop API. pProcessInfo = None try: pProcessInfo, dwCount = win32.WTSEnumerateProcesses( win32.WTS_CURRENT_SERVER_HANDLE) # For each process found... for index in compat.xrange(dwCount): sProcessInfo = pProcessInfo[index] ## # Ignore processes belonging to other sessions. ## if sProcessInfo.SessionId != win32.WTS_CURRENT_SESSION: ## continue # Ignore our own PID. pid = sProcessInfo.ProcessId if pid == our_pid: continue # Remove the PID from the dead PIDs list. if pid in dead_pids: dead_pids.remove(pid) # Get the "process name". # Empirically, this seems to be the filename without the path. # (The MSDN docs aren't very clear about this API call). fileName = sProcessInfo.pProcessName # If the process is new, add a new Process object. if pid not in self.__processDict: aProcess = Process(pid, fileName = fileName) self._add_process(aProcess) # If the process was already in the snapshot, and the # filename is missing, update the Process object. elif fileName: aProcess = self.__processDict.get(pid) if not aProcess.fileName: aProcess.fileName = fileName # Free the memory allocated by the Remote Desktop API. finally: if pProcessInfo is not None: try: win32.WTSFreeMemory(pProcessInfo) except WindowsError: pass # At this point the only remaining PIDs from the old list are dead. # Remove them from the snapshot. for pid in dead_pids: self._del_process(pid)
python
def scan_processes(self): """ Populates the snapshot with running processes. Tipically you don't need to call this method directly, if unsure use L{scan} instead. @note: This method uses the Remote Desktop API instead of the Toolhelp API. It might give slightly different results, especially if the current process does not have full privileges. @note: This method will only retrieve process filenames. To get the process pathnames instead, B{after} this method call L{scan_process_filenames}. @raise WindowsError: An error occured while updating the snapshot. The snapshot was not modified. """ # Get the previous list of PIDs. # We'll be removing live PIDs from it as we find them. our_pid = win32.GetCurrentProcessId() dead_pids = set( compat.iterkeys(self.__processDict) ) # Ignore our own PID. if our_pid in dead_pids: dead_pids.remove(our_pid) # Get the list of processes from the Remote Desktop API. pProcessInfo = None try: pProcessInfo, dwCount = win32.WTSEnumerateProcesses( win32.WTS_CURRENT_SERVER_HANDLE) # For each process found... for index in compat.xrange(dwCount): sProcessInfo = pProcessInfo[index] ## # Ignore processes belonging to other sessions. ## if sProcessInfo.SessionId != win32.WTS_CURRENT_SESSION: ## continue # Ignore our own PID. pid = sProcessInfo.ProcessId if pid == our_pid: continue # Remove the PID from the dead PIDs list. if pid in dead_pids: dead_pids.remove(pid) # Get the "process name". # Empirically, this seems to be the filename without the path. # (The MSDN docs aren't very clear about this API call). fileName = sProcessInfo.pProcessName # If the process is new, add a new Process object. if pid not in self.__processDict: aProcess = Process(pid, fileName = fileName) self._add_process(aProcess) # If the process was already in the snapshot, and the # filename is missing, update the Process object. elif fileName: aProcess = self.__processDict.get(pid) if not aProcess.fileName: aProcess.fileName = fileName # Free the memory allocated by the Remote Desktop API. finally: if pProcessInfo is not None: try: win32.WTSFreeMemory(pProcessInfo) except WindowsError: pass # At this point the only remaining PIDs from the old list are dead. # Remove them from the snapshot. for pid in dead_pids: self._del_process(pid)
[ "def", "scan_processes", "(", "self", ")", ":", "# Get the previous list of PIDs.", "# We'll be removing live PIDs from it as we find them.", "our_pid", "=", "win32", ".", "GetCurrentProcessId", "(", ")", "dead_pids", "=", "set", "(", "compat", ".", "iterkeys", "(", "se...
Populates the snapshot with running processes. Tipically you don't need to call this method directly, if unsure use L{scan} instead. @note: This method uses the Remote Desktop API instead of the Toolhelp API. It might give slightly different results, especially if the current process does not have full privileges. @note: This method will only retrieve process filenames. To get the process pathnames instead, B{after} this method call L{scan_process_filenames}. @raise WindowsError: An error occured while updating the snapshot. The snapshot was not modified.
[ "Populates", "the", "snapshot", "with", "running", "processes", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L4579-L4658
train
209,740
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
_ProcessContainer.scan_processes_fast
def scan_processes_fast(self): """ Populates the snapshot with running processes. Only the PID is retrieved for each process. Dead processes are removed. Threads and modules of living processes are ignored. Tipically you don't need to call this method directly, if unsure use L{scan} instead. @note: This method uses the PSAPI. It may be faster for scanning, but some information may be missing, outdated or slower to obtain. This could be a good tradeoff under some circumstances. """ # Get the new and old list of pids new_pids = set( win32.EnumProcesses() ) old_pids = set( compat.iterkeys(self.__processDict) ) # Ignore our own pid our_pid = win32.GetCurrentProcessId() if our_pid in new_pids: new_pids.remove(our_pid) if our_pid in old_pids: old_pids.remove(our_pid) # Add newly found pids for pid in new_pids.difference(old_pids): self._add_process( Process(pid) ) # Remove missing pids for pid in old_pids.difference(new_pids): self._del_process(pid)
python
def scan_processes_fast(self): """ Populates the snapshot with running processes. Only the PID is retrieved for each process. Dead processes are removed. Threads and modules of living processes are ignored. Tipically you don't need to call this method directly, if unsure use L{scan} instead. @note: This method uses the PSAPI. It may be faster for scanning, but some information may be missing, outdated or slower to obtain. This could be a good tradeoff under some circumstances. """ # Get the new and old list of pids new_pids = set( win32.EnumProcesses() ) old_pids = set( compat.iterkeys(self.__processDict) ) # Ignore our own pid our_pid = win32.GetCurrentProcessId() if our_pid in new_pids: new_pids.remove(our_pid) if our_pid in old_pids: old_pids.remove(our_pid) # Add newly found pids for pid in new_pids.difference(old_pids): self._add_process( Process(pid) ) # Remove missing pids for pid in old_pids.difference(new_pids): self._del_process(pid)
[ "def", "scan_processes_fast", "(", "self", ")", ":", "# Get the new and old list of pids", "new_pids", "=", "set", "(", "win32", ".", "EnumProcesses", "(", ")", ")", "old_pids", "=", "set", "(", "compat", ".", "iterkeys", "(", "self", ".", "__processDict", ")"...
Populates the snapshot with running processes. Only the PID is retrieved for each process. Dead processes are removed. Threads and modules of living processes are ignored. Tipically you don't need to call this method directly, if unsure use L{scan} instead. @note: This method uses the PSAPI. It may be faster for scanning, but some information may be missing, outdated or slower to obtain. This could be a good tradeoff under some circumstances.
[ "Populates", "the", "snapshot", "with", "running", "processes", ".", "Only", "the", "PID", "is", "retrieved", "for", "each", "process", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L4660-L4693
train
209,741
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
_ProcessContainer.scan_process_filenames
def scan_process_filenames(self): """ Update the filename for each process in the snapshot when possible. @note: Tipically you don't need to call this method. It's called automatically by L{scan} to get the full pathname for each process when possible, since some scan methods only get filenames without the path component. If unsure, use L{scan} instead. @see: L{scan}, L{Process.get_filename} @rtype: bool @return: C{True} if all the pathnames were retrieved, C{False} if the debugger doesn't have permission to scan some processes. In either case, all processes the debugger has access to have a full pathname instead of just a filename. """ complete = True for aProcess in self.__processDict.values(): try: new_name = None old_name = aProcess.fileName try: aProcess.fileName = None new_name = aProcess.get_filename() finally: if not new_name: aProcess.fileName = old_name complete = False except Exception: complete = False return complete
python
def scan_process_filenames(self): """ Update the filename for each process in the snapshot when possible. @note: Tipically you don't need to call this method. It's called automatically by L{scan} to get the full pathname for each process when possible, since some scan methods only get filenames without the path component. If unsure, use L{scan} instead. @see: L{scan}, L{Process.get_filename} @rtype: bool @return: C{True} if all the pathnames were retrieved, C{False} if the debugger doesn't have permission to scan some processes. In either case, all processes the debugger has access to have a full pathname instead of just a filename. """ complete = True for aProcess in self.__processDict.values(): try: new_name = None old_name = aProcess.fileName try: aProcess.fileName = None new_name = aProcess.get_filename() finally: if not new_name: aProcess.fileName = old_name complete = False except Exception: complete = False return complete
[ "def", "scan_process_filenames", "(", "self", ")", ":", "complete", "=", "True", "for", "aProcess", "in", "self", ".", "__processDict", ".", "values", "(", ")", ":", "try", ":", "new_name", "=", "None", "old_name", "=", "aProcess", ".", "fileName", "try", ...
Update the filename for each process in the snapshot when possible. @note: Tipically you don't need to call this method. It's called automatically by L{scan} to get the full pathname for each process when possible, since some scan methods only get filenames without the path component. If unsure, use L{scan} instead. @see: L{scan}, L{Process.get_filename} @rtype: bool @return: C{True} if all the pathnames were retrieved, C{False} if the debugger doesn't have permission to scan some processes. In either case, all processes the debugger has access to have a full pathname instead of just a filename.
[ "Update", "the", "filename", "for", "each", "process", "in", "the", "snapshot", "when", "possible", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L4695-L4728
train
209,742
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
_ProcessContainer.clear_dead_processes
def clear_dead_processes(self): """ Removes Process objects from the snapshot referring to processes no longer running. """ for pid in self.get_process_ids(): aProcess = self.get_process(pid) if not aProcess.is_alive(): self._del_process(aProcess)
python
def clear_dead_processes(self): """ Removes Process objects from the snapshot referring to processes no longer running. """ for pid in self.get_process_ids(): aProcess = self.get_process(pid) if not aProcess.is_alive(): self._del_process(aProcess)
[ "def", "clear_dead_processes", "(", "self", ")", ":", "for", "pid", "in", "self", ".", "get_process_ids", "(", ")", ":", "aProcess", "=", "self", ".", "get_process", "(", "pid", ")", "if", "not", "aProcess", ".", "is_alive", "(", ")", ":", "self", ".",...
Removes Process objects from the snapshot referring to processes no longer running.
[ "Removes", "Process", "objects", "from", "the", "snapshot", "referring", "to", "processes", "no", "longer", "running", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L4732-L4740
train
209,743
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
_ProcessContainer.clear_unattached_processes
def clear_unattached_processes(self): """ Removes Process objects from the snapshot referring to processes not being debugged. """ for pid in self.get_process_ids(): aProcess = self.get_process(pid) if not aProcess.is_being_debugged(): self._del_process(aProcess)
python
def clear_unattached_processes(self): """ Removes Process objects from the snapshot referring to processes not being debugged. """ for pid in self.get_process_ids(): aProcess = self.get_process(pid) if not aProcess.is_being_debugged(): self._del_process(aProcess)
[ "def", "clear_unattached_processes", "(", "self", ")", ":", "for", "pid", "in", "self", ".", "get_process_ids", "(", ")", ":", "aProcess", "=", "self", ".", "get_process", "(", "pid", ")", "if", "not", "aProcess", ".", "is_being_debugged", "(", ")", ":", ...
Removes Process objects from the snapshot referring to processes not being debugged.
[ "Removes", "Process", "objects", "from", "the", "snapshot", "referring", "to", "processes", "not", "being", "debugged", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L4742-L4750
train
209,744
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
_ProcessContainer.close_process_handles
def close_process_handles(self): """ Closes all open handles to processes in this snapshot. """ for pid in self.get_process_ids(): aProcess = self.get_process(pid) try: aProcess.close_handle() except Exception: e = sys.exc_info()[1] try: msg = "Cannot close process handle %s, reason: %s" msg %= (aProcess.hProcess.value, str(e)) warnings.warn(msg) except Exception: pass
python
def close_process_handles(self): """ Closes all open handles to processes in this snapshot. """ for pid in self.get_process_ids(): aProcess = self.get_process(pid) try: aProcess.close_handle() except Exception: e = sys.exc_info()[1] try: msg = "Cannot close process handle %s, reason: %s" msg %= (aProcess.hProcess.value, str(e)) warnings.warn(msg) except Exception: pass
[ "def", "close_process_handles", "(", "self", ")", ":", "for", "pid", "in", "self", ".", "get_process_ids", "(", ")", ":", "aProcess", "=", "self", ".", "get_process", "(", "pid", ")", "try", ":", "aProcess", ".", "close_handle", "(", ")", "except", "Exce...
Closes all open handles to processes in this snapshot.
[ "Closes", "all", "open", "handles", "to", "processes", "in", "this", "snapshot", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L4752-L4767
train
209,745
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
_ProcessContainer.close_process_and_thread_handles
def close_process_and_thread_handles(self): """ Closes all open handles to processes and threads in this snapshot. """ for aProcess in self.iter_processes(): aProcess.close_thread_handles() try: aProcess.close_handle() except Exception: e = sys.exc_info()[1] try: msg = "Cannot close process handle %s, reason: %s" msg %= (aProcess.hProcess.value, str(e)) warnings.warn(msg) except Exception: pass
python
def close_process_and_thread_handles(self): """ Closes all open handles to processes and threads in this snapshot. """ for aProcess in self.iter_processes(): aProcess.close_thread_handles() try: aProcess.close_handle() except Exception: e = sys.exc_info()[1] try: msg = "Cannot close process handle %s, reason: %s" msg %= (aProcess.hProcess.value, str(e)) warnings.warn(msg) except Exception: pass
[ "def", "close_process_and_thread_handles", "(", "self", ")", ":", "for", "aProcess", "in", "self", ".", "iter_processes", "(", ")", ":", "aProcess", ".", "close_thread_handles", "(", ")", "try", ":", "aProcess", ".", "close_handle", "(", ")", "except", "Except...
Closes all open handles to processes and threads in this snapshot.
[ "Closes", "all", "open", "handles", "to", "processes", "and", "threads", "in", "this", "snapshot", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L4769-L4784
train
209,746
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
_ProcessContainer._add_process
def _add_process(self, aProcess): """ Private method to add a process object to the snapshot. @type aProcess: L{Process} @param aProcess: Process object. """ ## if not isinstance(aProcess, Process): ## if hasattr(aProcess, '__class__'): ## typename = aProcess.__class__.__name__ ## else: ## typename = str(type(aProcess)) ## msg = "Expected Process, got %s instead" % typename ## raise TypeError(msg) dwProcessId = aProcess.dwProcessId ## if dwProcessId in self.__processDict: ## msg = "Process already exists: %d" % dwProcessId ## raise KeyError(msg) self.__processDict[dwProcessId] = aProcess
python
def _add_process(self, aProcess): """ Private method to add a process object to the snapshot. @type aProcess: L{Process} @param aProcess: Process object. """ ## if not isinstance(aProcess, Process): ## if hasattr(aProcess, '__class__'): ## typename = aProcess.__class__.__name__ ## else: ## typename = str(type(aProcess)) ## msg = "Expected Process, got %s instead" % typename ## raise TypeError(msg) dwProcessId = aProcess.dwProcessId ## if dwProcessId in self.__processDict: ## msg = "Process already exists: %d" % dwProcessId ## raise KeyError(msg) self.__processDict[dwProcessId] = aProcess
[ "def", "_add_process", "(", "self", ",", "aProcess", ")", ":", "## if not isinstance(aProcess, Process):", "## if hasattr(aProcess, '__class__'):", "## typename = aProcess.__class__.__name__", "## else:", "## typename = str(type(aPro...
Private method to add a process object to the snapshot. @type aProcess: L{Process} @param aProcess: Process object.
[ "Private", "method", "to", "add", "a", "process", "object", "to", "the", "snapshot", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L4935-L4953
train
209,747
fabioz/PyDev.Debugger
pydevd_attach_to_process/winappdbg/process.py
_ProcessContainer._del_process
def _del_process(self, dwProcessId): """ Private method to remove a process object from the snapshot. @type dwProcessId: int @param dwProcessId: Global process ID. """ try: aProcess = self.__processDict[dwProcessId] del self.__processDict[dwProcessId] except KeyError: aProcess = None msg = "Unknown process ID %d" % dwProcessId warnings.warn(msg, RuntimeWarning) if aProcess: aProcess.clear()
python
def _del_process(self, dwProcessId): """ Private method to remove a process object from the snapshot. @type dwProcessId: int @param dwProcessId: Global process ID. """ try: aProcess = self.__processDict[dwProcessId] del self.__processDict[dwProcessId] except KeyError: aProcess = None msg = "Unknown process ID %d" % dwProcessId warnings.warn(msg, RuntimeWarning) if aProcess: aProcess.clear()
[ "def", "_del_process", "(", "self", ",", "dwProcessId", ")", ":", "try", ":", "aProcess", "=", "self", ".", "__processDict", "[", "dwProcessId", "]", "del", "self", ".", "__processDict", "[", "dwProcessId", "]", "except", "KeyError", ":", "aProcess", "=", ...
Private method to remove a process object from the snapshot. @type dwProcessId: int @param dwProcessId: Global process ID.
[ "Private", "method", "to", "remove", "a", "process", "object", "from", "the", "snapshot", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L4955-L4970
train
209,748
fabioz/PyDev.Debugger
_pydev_imps/_pydev_inspect.py
ismethoddescriptor
def ismethoddescriptor(object): """Return true if the object is a method descriptor. But not if ismethod() or isclass() or isfunction() are true. This is new in Python 2.2, and, for example, is true of int.__add__. An object passing this test has a __get__ attribute but not a __set__ attribute, but beyond that the set of attributes varies. __name__ is usually sensible, and __doc__ often is. Methods implemented via descriptors that also pass one of the other tests return false from the ismethoddescriptor() test, simply because the other tests promise more -- you can, e.g., count on having the im_func attribute (etc) when an object passes ismethod().""" return (hasattr(object, "__get__") and not hasattr(object, "__set__") # else it's a data descriptor and not ismethod(object) # mutual exclusion and not isfunction(object) and not isclass(object))
python
def ismethoddescriptor(object): """Return true if the object is a method descriptor. But not if ismethod() or isclass() or isfunction() are true. This is new in Python 2.2, and, for example, is true of int.__add__. An object passing this test has a __get__ attribute but not a __set__ attribute, but beyond that the set of attributes varies. __name__ is usually sensible, and __doc__ often is. Methods implemented via descriptors that also pass one of the other tests return false from the ismethoddescriptor() test, simply because the other tests promise more -- you can, e.g., count on having the im_func attribute (etc) when an object passes ismethod().""" return (hasattr(object, "__get__") and not hasattr(object, "__set__") # else it's a data descriptor and not ismethod(object) # mutual exclusion and not isfunction(object) and not isclass(object))
[ "def", "ismethoddescriptor", "(", "object", ")", ":", "return", "(", "hasattr", "(", "object", ",", "\"__get__\"", ")", "and", "not", "hasattr", "(", "object", ",", "\"__set__\"", ")", "# else it's a data descriptor", "and", "not", "ismethod", "(", "object", "...
Return true if the object is a method descriptor. But not if ismethod() or isclass() or isfunction() are true. This is new in Python 2.2, and, for example, is true of int.__add__. An object passing this test has a __get__ attribute but not a __set__ attribute, but beyond that the set of attributes varies. __name__ is usually sensible, and __doc__ often is. Methods implemented via descriptors that also pass one of the other tests return false from the ismethoddescriptor() test, simply because the other tests promise more -- you can, e.g., count on having the im_func attribute (etc) when an object passes ismethod().
[ "Return", "true", "if", "the", "object", "is", "a", "method", "descriptor", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_inspect.py#L60-L78
train
209,749
fabioz/PyDev.Debugger
_pydev_imps/_pydev_inspect.py
isroutine
def isroutine(object): """Return true if the object is any kind of function or method.""" return (isbuiltin(object) or isfunction(object) or ismethod(object) or ismethoddescriptor(object))
python
def isroutine(object): """Return true if the object is any kind of function or method.""" return (isbuiltin(object) or isfunction(object) or ismethod(object) or ismethoddescriptor(object))
[ "def", "isroutine", "(", "object", ")", ":", "return", "(", "isbuiltin", "(", "object", ")", "or", "isfunction", "(", "object", ")", "or", "ismethod", "(", "object", ")", "or", "ismethoddescriptor", "(", "object", ")", ")" ]
Return true if the object is any kind of function or method.
[ "Return", "true", "if", "the", "object", "is", "any", "kind", "of", "function", "or", "method", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_inspect.py#L148-L153
train
209,750
fabioz/PyDev.Debugger
_pydev_imps/_pydev_inspect.py
classify_class_attrs
def classify_class_attrs(cls): """Return list of attribute-descriptor tuples. For each name in dir(cls), the return list contains a 4-tuple with these elements: 0. The name (a string). 1. The kind of attribute this is, one of these strings: 'class method' created via classmethod() 'static method' created via staticmethod() 'property' created via property() 'method' any other flavor of method 'data' not a method 2. The class which defined this attribute (a class). 3. The object as obtained directly from the defining class's __dict__, not via getattr. This is especially important for data attributes: C.data is just a data object, but C.__dict__['data'] may be a data descriptor with additional info, like a __doc__ string. """ mro = getmro(cls) names = dir(cls) result = [] for name in names: # Get the object associated with the name. # Getting an obj from the __dict__ sometimes reveals more than # using getattr. Static and class methods are dramatic examples. if name in cls.__dict__: obj = cls.__dict__[name] else: obj = getattr(cls, name) # Figure out where it was defined. homecls = getattr(obj, "__objclass__", None) if homecls is None: # search the dicts. for base in mro: if name in base.__dict__: homecls = base break # Get the object again, in order to get it from the defining # __dict__ instead of via getattr (if possible). if homecls is not None and name in homecls.__dict__: obj = homecls.__dict__[name] # Also get the object via getattr. obj_via_getattr = getattr(cls, name) # Classify the object. if isinstance(obj, staticmethod): kind = "static method" elif isinstance(obj, classmethod): kind = "class method" elif isinstance(obj, property): kind = "property" elif (ismethod(obj_via_getattr) or ismethoddescriptor(obj_via_getattr)): kind = "method" else: kind = "data" result.append((name, kind, homecls, obj)) return result
python
def classify_class_attrs(cls): """Return list of attribute-descriptor tuples. For each name in dir(cls), the return list contains a 4-tuple with these elements: 0. The name (a string). 1. The kind of attribute this is, one of these strings: 'class method' created via classmethod() 'static method' created via staticmethod() 'property' created via property() 'method' any other flavor of method 'data' not a method 2. The class which defined this attribute (a class). 3. The object as obtained directly from the defining class's __dict__, not via getattr. This is especially important for data attributes: C.data is just a data object, but C.__dict__['data'] may be a data descriptor with additional info, like a __doc__ string. """ mro = getmro(cls) names = dir(cls) result = [] for name in names: # Get the object associated with the name. # Getting an obj from the __dict__ sometimes reveals more than # using getattr. Static and class methods are dramatic examples. if name in cls.__dict__: obj = cls.__dict__[name] else: obj = getattr(cls, name) # Figure out where it was defined. homecls = getattr(obj, "__objclass__", None) if homecls is None: # search the dicts. for base in mro: if name in base.__dict__: homecls = base break # Get the object again, in order to get it from the defining # __dict__ instead of via getattr (if possible). if homecls is not None and name in homecls.__dict__: obj = homecls.__dict__[name] # Also get the object via getattr. obj_via_getattr = getattr(cls, name) # Classify the object. if isinstance(obj, staticmethod): kind = "static method" elif isinstance(obj, classmethod): kind = "class method" elif isinstance(obj, property): kind = "property" elif (ismethod(obj_via_getattr) or ismethoddescriptor(obj_via_getattr)): kind = "method" else: kind = "data" result.append((name, kind, homecls, obj)) return result
[ "def", "classify_class_attrs", "(", "cls", ")", ":", "mro", "=", "getmro", "(", "cls", ")", "names", "=", "dir", "(", "cls", ")", "result", "=", "[", "]", "for", "name", "in", "names", ":", "# Get the object associated with the name.", "# Getting an obj from t...
Return list of attribute-descriptor tuples. For each name in dir(cls), the return list contains a 4-tuple with these elements: 0. The name (a string). 1. The kind of attribute this is, one of these strings: 'class method' created via classmethod() 'static method' created via staticmethod() 'property' created via property() 'method' any other flavor of method 'data' not a method 2. The class which defined this attribute (a class). 3. The object as obtained directly from the defining class's __dict__, not via getattr. This is especially important for data attributes: C.data is just a data object, but C.__dict__['data'] may be a data descriptor with additional info, like a __doc__ string.
[ "Return", "list", "of", "attribute", "-", "descriptor", "tuples", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_inspect.py#L166-L234
train
209,751
fabioz/PyDev.Debugger
_pydev_imps/_pydev_inspect.py
indentsize
def indentsize(line): """Return the indent size, in spaces, at the start of a line of text.""" expline = string.expandtabs(line) return len(expline) - len(string.lstrip(expline))
python
def indentsize(line): """Return the indent size, in spaces, at the start of a line of text.""" expline = string.expandtabs(line) return len(expline) - len(string.lstrip(expline))
[ "def", "indentsize", "(", "line", ")", ":", "expline", "=", "string", ".", "expandtabs", "(", "line", ")", "return", "len", "(", "expline", ")", "-", "len", "(", "string", ".", "lstrip", "(", "expline", ")", ")" ]
Return the indent size, in spaces, at the start of a line of text.
[ "Return", "the", "indent", "size", "in", "spaces", "at", "the", "start", "of", "a", "line", "of", "text", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_inspect.py#L255-L258
train
209,752
fabioz/PyDev.Debugger
_pydev_imps/_pydev_inspect.py
getdoc
def getdoc(object): """Get the documentation string for an object. All tabs are expanded to spaces. To clean up docstrings that are indented to line up with blocks of code, any whitespace than can be uniformly removed from the second line onwards is removed.""" try: doc = object.__doc__ except AttributeError: return None if not isinstance(doc, (str, unicode)): return None try: lines = string.split(string.expandtabs(doc), '\n') except UnicodeError: return None else: margin = None for line in lines[1:]: content = len(string.lstrip(line)) if not content: continue indent = len(line) - content if margin is None: margin = indent else: margin = min(margin, indent) if margin is not None: for i in range(1, len(lines)): lines[i] = lines[i][margin:] return string.join(lines, '\n')
python
def getdoc(object): """Get the documentation string for an object. All tabs are expanded to spaces. To clean up docstrings that are indented to line up with blocks of code, any whitespace than can be uniformly removed from the second line onwards is removed.""" try: doc = object.__doc__ except AttributeError: return None if not isinstance(doc, (str, unicode)): return None try: lines = string.split(string.expandtabs(doc), '\n') except UnicodeError: return None else: margin = None for line in lines[1:]: content = len(string.lstrip(line)) if not content: continue indent = len(line) - content if margin is None: margin = indent else: margin = min(margin, indent) if margin is not None: for i in range(1, len(lines)): lines[i] = lines[i][margin:] return string.join(lines, '\n')
[ "def", "getdoc", "(", "object", ")", ":", "try", ":", "doc", "=", "object", ".", "__doc__", "except", "AttributeError", ":", "return", "None", "if", "not", "isinstance", "(", "doc", ",", "(", "str", ",", "unicode", ")", ")", ":", "return", "None", "t...
Get the documentation string for an object. All tabs are expanded to spaces. To clean up docstrings that are indented to line up with blocks of code, any whitespace than can be uniformly removed from the second line onwards is removed.
[ "Get", "the", "documentation", "string", "for", "an", "object", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_inspect.py#L260-L286
train
209,753
fabioz/PyDev.Debugger
_pydev_imps/_pydev_inspect.py
getfile
def getfile(object): """Work out which source or compiled file an object was defined in.""" if ismodule(object): if hasattr(object, '__file__'): return object.__file__ raise TypeError, 'arg is a built-in module' if isclass(object): object = sys.modules.get(object.__module__) if hasattr(object, '__file__'): return object.__file__ raise TypeError, 'arg is a built-in class' if ismethod(object): object = object.im_func if isfunction(object): object = object.func_code if istraceback(object): object = object.tb_frame if isframe(object): object = object.f_code if iscode(object): return object.co_filename raise TypeError, 'arg is not a module, class, method, ' \ 'function, traceback, frame, or code object'
python
def getfile(object): """Work out which source or compiled file an object was defined in.""" if ismodule(object): if hasattr(object, '__file__'): return object.__file__ raise TypeError, 'arg is a built-in module' if isclass(object): object = sys.modules.get(object.__module__) if hasattr(object, '__file__'): return object.__file__ raise TypeError, 'arg is a built-in class' if ismethod(object): object = object.im_func if isfunction(object): object = object.func_code if istraceback(object): object = object.tb_frame if isframe(object): object = object.f_code if iscode(object): return object.co_filename raise TypeError, 'arg is not a module, class, method, ' \ 'function, traceback, frame, or code object'
[ "def", "getfile", "(", "object", ")", ":", "if", "ismodule", "(", "object", ")", ":", "if", "hasattr", "(", "object", ",", "'__file__'", ")", ":", "return", "object", ".", "__file__", "raise", "TypeError", ",", "'arg is a built-in module'", "if", "isclass", ...
Work out which source or compiled file an object was defined in.
[ "Work", "out", "which", "source", "or", "compiled", "file", "an", "object", "was", "defined", "in", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_inspect.py#L288-L310
train
209,754
fabioz/PyDev.Debugger
_pydev_imps/_pydev_inspect.py
getmoduleinfo
def getmoduleinfo(path): """Get the module name, suffix, mode, and module type for a given file.""" filename = os.path.basename(path) suffixes = map(lambda (suffix, mode, mtype): (-len(suffix), suffix, mode, mtype), imp.get_suffixes()) suffixes.sort() # try longest suffixes first, in case they overlap for neglen, suffix, mode, mtype in suffixes: if filename[neglen:] == suffix: return filename[:neglen], suffix, mode, mtype
python
def getmoduleinfo(path): """Get the module name, suffix, mode, and module type for a given file.""" filename = os.path.basename(path) suffixes = map(lambda (suffix, mode, mtype): (-len(suffix), suffix, mode, mtype), imp.get_suffixes()) suffixes.sort() # try longest suffixes first, in case they overlap for neglen, suffix, mode, mtype in suffixes: if filename[neglen:] == suffix: return filename[:neglen], suffix, mode, mtype
[ "def", "getmoduleinfo", "(", "path", ")", ":", "filename", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "suffixes", "=", "map", "(", "lambda", "(", "suffix", ",", "mode", ",", "mtype", ")", ":", "(", "-", "len", "(", "suffix", ")", ...
Get the module name, suffix, mode, and module type for a given file.
[ "Get", "the", "module", "name", "suffix", "mode", "and", "module", "type", "for", "a", "given", "file", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_inspect.py#L312-L320
train
209,755
fabioz/PyDev.Debugger
_pydev_imps/_pydev_inspect.py
getsourcefile
def getsourcefile(object): """Return the Python source file an object was defined in, if it exists.""" filename = getfile(object) if string.lower(filename[-4:]) in ['.pyc', '.pyo']: filename = filename[:-4] + '.py' for suffix, mode, kind in imp.get_suffixes(): if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix: # Looks like a binary file. We want to only return a text file. return None if os.path.exists(filename): return filename
python
def getsourcefile(object): """Return the Python source file an object was defined in, if it exists.""" filename = getfile(object) if string.lower(filename[-4:]) in ['.pyc', '.pyo']: filename = filename[:-4] + '.py' for suffix, mode, kind in imp.get_suffixes(): if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix: # Looks like a binary file. We want to only return a text file. return None if os.path.exists(filename): return filename
[ "def", "getsourcefile", "(", "object", ")", ":", "filename", "=", "getfile", "(", "object", ")", "if", "string", ".", "lower", "(", "filename", "[", "-", "4", ":", "]", ")", "in", "[", "'.pyc'", ",", "'.pyo'", "]", ":", "filename", "=", "filename", ...
Return the Python source file an object was defined in, if it exists.
[ "Return", "the", "Python", "source", "file", "an", "object", "was", "defined", "in", "if", "it", "exists", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_inspect.py#L327-L337
train
209,756
fabioz/PyDev.Debugger
_pydev_imps/_pydev_inspect.py
getabsfile
def getabsfile(object): """Return an absolute path to the source or compiled file for an object. The idea is for each object to have a unique origin, so this routine normalizes the result as much as possible.""" return os.path.normcase( os.path.abspath(getsourcefile(object) or getfile(object)))
python
def getabsfile(object): """Return an absolute path to the source or compiled file for an object. The idea is for each object to have a unique origin, so this routine normalizes the result as much as possible.""" return os.path.normcase( os.path.abspath(getsourcefile(object) or getfile(object)))
[ "def", "getabsfile", "(", "object", ")", ":", "return", "os", ".", "path", ".", "normcase", "(", "os", ".", "path", ".", "abspath", "(", "getsourcefile", "(", "object", ")", "or", "getfile", "(", "object", ")", ")", ")" ]
Return an absolute path to the source or compiled file for an object. The idea is for each object to have a unique origin, so this routine normalizes the result as much as possible.
[ "Return", "an", "absolute", "path", "to", "the", "source", "or", "compiled", "file", "for", "an", "object", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_inspect.py#L339-L345
train
209,757
fabioz/PyDev.Debugger
_pydev_imps/_pydev_inspect.py
getmodule
def getmodule(object): """Return the module an object was defined in, or None if not found.""" if ismodule(object): return object if isclass(object): return sys.modules.get(object.__module__) try: file = getabsfile(object) except TypeError: return None if modulesbyfile.has_key(file): return sys.modules[modulesbyfile[file]] for module in sys.modules.values(): if hasattr(module, '__file__'): modulesbyfile[getabsfile(module)] = module.__name__ if modulesbyfile.has_key(file): return sys.modules[modulesbyfile[file]] main = sys.modules['__main__'] if hasattr(main, object.__name__): mainobject = getattr(main, object.__name__) if mainobject is object: return main builtin = sys.modules['__builtin__'] if hasattr(builtin, object.__name__): builtinobject = getattr(builtin, object.__name__) if builtinobject is object: return builtin
python
def getmodule(object): """Return the module an object was defined in, or None if not found.""" if ismodule(object): return object if isclass(object): return sys.modules.get(object.__module__) try: file = getabsfile(object) except TypeError: return None if modulesbyfile.has_key(file): return sys.modules[modulesbyfile[file]] for module in sys.modules.values(): if hasattr(module, '__file__'): modulesbyfile[getabsfile(module)] = module.__name__ if modulesbyfile.has_key(file): return sys.modules[modulesbyfile[file]] main = sys.modules['__main__'] if hasattr(main, object.__name__): mainobject = getattr(main, object.__name__) if mainobject is object: return main builtin = sys.modules['__builtin__'] if hasattr(builtin, object.__name__): builtinobject = getattr(builtin, object.__name__) if builtinobject is object: return builtin
[ "def", "getmodule", "(", "object", ")", ":", "if", "ismodule", "(", "object", ")", ":", "return", "object", "if", "isclass", "(", "object", ")", ":", "return", "sys", ".", "modules", ".", "get", "(", "object", ".", "__module__", ")", "try", ":", "fil...
Return the module an object was defined in, or None if not found.
[ "Return", "the", "module", "an", "object", "was", "defined", "in", "or", "None", "if", "not", "found", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_inspect.py#L349-L375
train
209,758
fabioz/PyDev.Debugger
_pydev_imps/_pydev_inspect.py
findsource
def findsource(object): """Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An IOError is raised if the source code cannot be retrieved.""" try: file = open(getsourcefile(object)) except (TypeError, IOError): raise IOError, 'could not get source code' lines = file.readlines() file.close() if ismodule(object): return lines, 0 if isclass(object): name = object.__name__ pat = re.compile(r'^\s*class\s*' + name + r'\b') for i in range(len(lines)): if pat.match(lines[i]): return lines, i else: raise IOError, 'could not find class definition' if ismethod(object): object = object.im_func if isfunction(object): object = object.func_code if istraceback(object): object = object.tb_frame if isframe(object): object = object.f_code if iscode(object): if not hasattr(object, 'co_firstlineno'): raise IOError, 'could not find function definition' lnum = object.co_firstlineno - 1 pat = re.compile(r'^(\s*def\s)|(.*\slambda(:|\s))') while lnum > 0: if pat.match(lines[lnum]): break lnum = lnum - 1 return lines, lnum raise IOError, 'could not find code object'
python
def findsource(object): """Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An IOError is raised if the source code cannot be retrieved.""" try: file = open(getsourcefile(object)) except (TypeError, IOError): raise IOError, 'could not get source code' lines = file.readlines() file.close() if ismodule(object): return lines, 0 if isclass(object): name = object.__name__ pat = re.compile(r'^\s*class\s*' + name + r'\b') for i in range(len(lines)): if pat.match(lines[i]): return lines, i else: raise IOError, 'could not find class definition' if ismethod(object): object = object.im_func if isfunction(object): object = object.func_code if istraceback(object): object = object.tb_frame if isframe(object): object = object.f_code if iscode(object): if not hasattr(object, 'co_firstlineno'): raise IOError, 'could not find function definition' lnum = object.co_firstlineno - 1 pat = re.compile(r'^(\s*def\s)|(.*\slambda(:|\s))') while lnum > 0: if pat.match(lines[lnum]): break lnum = lnum - 1 return lines, lnum raise IOError, 'could not find code object'
[ "def", "findsource", "(", "object", ")", ":", "try", ":", "file", "=", "open", "(", "getsourcefile", "(", "object", ")", ")", "except", "(", "TypeError", ",", "IOError", ")", ":", "raise", "IOError", ",", "'could not get source code'", "lines", "=", "file"...
Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An IOError is raised if the source code cannot be retrieved.
[ "Return", "the", "entire", "source", "file", "and", "starting", "line", "number", "for", "an", "object", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_inspect.py#L377-L418
train
209,759
fabioz/PyDev.Debugger
_pydev_imps/_pydev_inspect.py
getcomments
def getcomments(object): """Get lines of comments immediately preceding an object's source code.""" try: lines, lnum = findsource(object) except IOError: return None if ismodule(object): # Look for a comment block at the top of the file. start = 0 if lines and lines[0][:2] == '#!': start = 1 while start < len(lines) and string.strip(lines[start]) in ['', '#']: start = start + 1 if start < len(lines) and lines[start][:1] == '#': comments = [] end = start while end < len(lines) and lines[end][:1] == '#': comments.append(string.expandtabs(lines[end])) end = end + 1 return string.join(comments, '') # Look for a preceding block of comments at the same indentation. elif lnum > 0: indent = indentsize(lines[lnum]) end = lnum - 1 if end >= 0 and string.lstrip(lines[end])[:1] == '#' and \ indentsize(lines[end]) == indent: comments = [string.lstrip(string.expandtabs(lines[end]))] if end > 0: end = end - 1 comment = string.lstrip(string.expandtabs(lines[end])) while comment[:1] == '#' and indentsize(lines[end]) == indent: comments[:0] = [comment] end = end - 1 if end < 0: break comment = string.lstrip(string.expandtabs(lines[end])) while comments and string.strip(comments[0]) == '#': comments[:1] = [] while comments and string.strip(comments[-1]) == '#': comments[-1:] = [] return string.join(comments, '')
python
def getcomments(object): """Get lines of comments immediately preceding an object's source code.""" try: lines, lnum = findsource(object) except IOError: return None if ismodule(object): # Look for a comment block at the top of the file. start = 0 if lines and lines[0][:2] == '#!': start = 1 while start < len(lines) and string.strip(lines[start]) in ['', '#']: start = start + 1 if start < len(lines) and lines[start][:1] == '#': comments = [] end = start while end < len(lines) and lines[end][:1] == '#': comments.append(string.expandtabs(lines[end])) end = end + 1 return string.join(comments, '') # Look for a preceding block of comments at the same indentation. elif lnum > 0: indent = indentsize(lines[lnum]) end = lnum - 1 if end >= 0 and string.lstrip(lines[end])[:1] == '#' and \ indentsize(lines[end]) == indent: comments = [string.lstrip(string.expandtabs(lines[end]))] if end > 0: end = end - 1 comment = string.lstrip(string.expandtabs(lines[end])) while comment[:1] == '#' and indentsize(lines[end]) == indent: comments[:0] = [comment] end = end - 1 if end < 0: break comment = string.lstrip(string.expandtabs(lines[end])) while comments and string.strip(comments[0]) == '#': comments[:1] = [] while comments and string.strip(comments[-1]) == '#': comments[-1:] = [] return string.join(comments, '')
[ "def", "getcomments", "(", "object", ")", ":", "try", ":", "lines", ",", "lnum", "=", "findsource", "(", "object", ")", "except", "IOError", ":", "return", "None", "if", "ismodule", "(", "object", ")", ":", "# Look for a comment block at the top of the file.", ...
Get lines of comments immediately preceding an object's source code.
[ "Get", "lines", "of", "comments", "immediately", "preceding", "an", "object", "s", "source", "code", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_inspect.py#L420-L458
train
209,760
fabioz/PyDev.Debugger
_pydev_imps/_pydev_inspect.py
getblock
def getblock(lines): """Extract the block of code at the top of the given list of lines.""" try: tokenize.tokenize(ListReader(lines).readline, BlockFinder().tokeneater) except EndOfBlock, eob: return lines[:eob.args[0]] # Fooling the indent/dedent logic implies a one-line definition return lines[:1]
python
def getblock(lines): """Extract the block of code at the top of the given list of lines.""" try: tokenize.tokenize(ListReader(lines).readline, BlockFinder().tokeneater) except EndOfBlock, eob: return lines[:eob.args[0]] # Fooling the indent/dedent logic implies a one-line definition return lines[:1]
[ "def", "getblock", "(", "lines", ")", ":", "try", ":", "tokenize", ".", "tokenize", "(", "ListReader", "(", "lines", ")", ".", "readline", ",", "BlockFinder", "(", ")", ".", "tokeneater", ")", "except", "EndOfBlock", ",", "eob", ":", "return", "lines", ...
Extract the block of code at the top of the given list of lines.
[ "Extract", "the", "block", "of", "code", "at", "the", "top", "of", "the", "given", "list", "of", "lines", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_inspect.py#L495-L502
train
209,761
fabioz/PyDev.Debugger
_pydev_imps/_pydev_inspect.py
getsourcelines
def getsourcelines(object): """Return a list of source lines and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of the lines corresponding to the object and the line number indicates where in the original source file the first line of code was found. An IOError is raised if the source code cannot be retrieved.""" lines, lnum = findsource(object) if ismodule(object): return lines, 0 else: return getblock(lines[lnum:]), lnum + 1
python
def getsourcelines(object): """Return a list of source lines and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of the lines corresponding to the object and the line number indicates where in the original source file the first line of code was found. An IOError is raised if the source code cannot be retrieved.""" lines, lnum = findsource(object) if ismodule(object): return lines, 0 else: return getblock(lines[lnum:]), lnum + 1
[ "def", "getsourcelines", "(", "object", ")", ":", "lines", ",", "lnum", "=", "findsource", "(", "object", ")", "if", "ismodule", "(", "object", ")", ":", "return", "lines", ",", "0", "else", ":", "return", "getblock", "(", "lines", "[", "lnum", ":", ...
Return a list of source lines and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of the lines corresponding to the object and the line number indicates where in the original source file the first line of code was found. An IOError is raised if the source code cannot be retrieved.
[ "Return", "a", "list", "of", "source", "lines", "and", "starting", "line", "number", "for", "an", "object", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_inspect.py#L504-L515
train
209,762
fabioz/PyDev.Debugger
_pydev_imps/_pydev_inspect.py
getclasstree
def getclasstree(classes, unique=0): """Arrange the given list of classes into a hierarchy of nested lists. Where a nested list appears, it contains classes derived from the class whose entry immediately precedes the list. Each entry is a 2-tuple containing a class and a tuple of its base classes. If the 'unique' argument is true, exactly one entry appears in the returned structure for each class in the given list. Otherwise, classes using multiple inheritance and their descendants will appear multiple times.""" children = {} roots = [] for c in classes: if c.__bases__: for parent in c.__bases__: if not children.has_key(parent): children[parent] = [] children[parent].append(c) if unique and parent in classes: break elif c not in roots: roots.append(c) for parent in children.keys(): if parent not in classes: roots.append(parent) return walktree(roots, children, None)
python
def getclasstree(classes, unique=0): """Arrange the given list of classes into a hierarchy of nested lists. Where a nested list appears, it contains classes derived from the class whose entry immediately precedes the list. Each entry is a 2-tuple containing a class and a tuple of its base classes. If the 'unique' argument is true, exactly one entry appears in the returned structure for each class in the given list. Otherwise, classes using multiple inheritance and their descendants will appear multiple times.""" children = {} roots = [] for c in classes: if c.__bases__: for parent in c.__bases__: if not children.has_key(parent): children[parent] = [] children[parent].append(c) if unique and parent in classes: break elif c not in roots: roots.append(c) for parent in children.keys(): if parent not in classes: roots.append(parent) return walktree(roots, children, None)
[ "def", "getclasstree", "(", "classes", ",", "unique", "=", "0", ")", ":", "children", "=", "{", "}", "roots", "=", "[", "]", "for", "c", "in", "classes", ":", "if", "c", ".", "__bases__", ":", "for", "parent", "in", "c", ".", "__bases__", ":", "i...
Arrange the given list of classes into a hierarchy of nested lists. Where a nested list appears, it contains classes derived from the class whose entry immediately precedes the list. Each entry is a 2-tuple containing a class and a tuple of its base classes. If the 'unique' argument is true, exactly one entry appears in the returned structure for each class in the given list. Otherwise, classes using multiple inheritance and their descendants will appear multiple times.
[ "Arrange", "the", "given", "list", "of", "classes", "into", "a", "hierarchy", "of", "nested", "lists", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_inspect.py#L537-L560
train
209,763
fabioz/PyDev.Debugger
_pydev_imps/_pydev_inspect.py
getargs
def getargs(co): """Get information about the arguments accepted by a code object. Three things are returned: (args, varargs, varkw), where 'args' is a list of argument names (possibly containing nested lists), and 'varargs' and 'varkw' are the names of the * and ** arguments or None.""" if not iscode(co): raise TypeError, 'arg is not a code object' nargs = co.co_argcount names = co.co_varnames args = list(names[:nargs]) step = 0 # The following acrobatics are for anonymous (tuple) arguments. if not sys.platform.startswith('java'):#Jython doesn't have co_code code = co.co_code import dis for i in range(nargs): if args[i][:1] in ['', '.']: stack, remain, count = [], [], [] while step < len(code): op = ord(code[step]) step = step + 1 if op >= dis.HAVE_ARGUMENT: opname = dis.opname[op] value = ord(code[step]) + ord(code[step + 1]) * 256 step = step + 2 if opname in ['UNPACK_TUPLE', 'UNPACK_SEQUENCE']: remain.append(value) count.append(value) elif opname == 'STORE_FAST': stack.append(names[value]) remain[-1] = remain[-1] - 1 while remain[-1] == 0: remain.pop() size = count.pop() stack[-size:] = [stack[-size:]] if not remain: break remain[-1] = remain[-1] - 1 if not remain: break args[i] = stack[0] varargs = None if co.co_flags & CO_VARARGS: varargs = co.co_varnames[nargs] nargs = nargs + 1 varkw = None if co.co_flags & CO_VARKEYWORDS: varkw = co.co_varnames[nargs] return args, varargs, varkw
python
def getargs(co): """Get information about the arguments accepted by a code object. Three things are returned: (args, varargs, varkw), where 'args' is a list of argument names (possibly containing nested lists), and 'varargs' and 'varkw' are the names of the * and ** arguments or None.""" if not iscode(co): raise TypeError, 'arg is not a code object' nargs = co.co_argcount names = co.co_varnames args = list(names[:nargs]) step = 0 # The following acrobatics are for anonymous (tuple) arguments. if not sys.platform.startswith('java'):#Jython doesn't have co_code code = co.co_code import dis for i in range(nargs): if args[i][:1] in ['', '.']: stack, remain, count = [], [], [] while step < len(code): op = ord(code[step]) step = step + 1 if op >= dis.HAVE_ARGUMENT: opname = dis.opname[op] value = ord(code[step]) + ord(code[step + 1]) * 256 step = step + 2 if opname in ['UNPACK_TUPLE', 'UNPACK_SEQUENCE']: remain.append(value) count.append(value) elif opname == 'STORE_FAST': stack.append(names[value]) remain[-1] = remain[-1] - 1 while remain[-1] == 0: remain.pop() size = count.pop() stack[-size:] = [stack[-size:]] if not remain: break remain[-1] = remain[-1] - 1 if not remain: break args[i] = stack[0] varargs = None if co.co_flags & CO_VARARGS: varargs = co.co_varnames[nargs] nargs = nargs + 1 varkw = None if co.co_flags & CO_VARKEYWORDS: varkw = co.co_varnames[nargs] return args, varargs, varkw
[ "def", "getargs", "(", "co", ")", ":", "if", "not", "iscode", "(", "co", ")", ":", "raise", "TypeError", ",", "'arg is not a code object'", "nargs", "=", "co", ".", "co_argcount", "names", "=", "co", ".", "co_varnames", "args", "=", "list", "(", "names",...
Get information about the arguments accepted by a code object. Three things are returned: (args, varargs, varkw), where 'args' is a list of argument names (possibly containing nested lists), and 'varargs' and 'varkw' are the names of the * and ** arguments or None.
[ "Get", "information", "about", "the", "arguments", "accepted", "by", "a", "code", "object", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_inspect.py#L566-L615
train
209,764
fabioz/PyDev.Debugger
_pydev_imps/_pydev_inspect.py
getargvalues
def getargvalues(frame): """Get information about arguments passed into a particular frame. A tuple of four things is returned: (args, varargs, varkw, locals). 'args' is a list of the argument names (it may contain nested lists). 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'locals' is the locals dictionary of the given frame.""" args, varargs, varkw = getargs(frame.f_code) return args, varargs, varkw, frame.f_locals
python
def getargvalues(frame): """Get information about arguments passed into a particular frame. A tuple of four things is returned: (args, varargs, varkw, locals). 'args' is a list of the argument names (it may contain nested lists). 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'locals' is the locals dictionary of the given frame.""" args, varargs, varkw = getargs(frame.f_code) return args, varargs, varkw, frame.f_locals
[ "def", "getargvalues", "(", "frame", ")", ":", "args", ",", "varargs", ",", "varkw", "=", "getargs", "(", "frame", ".", "f_code", ")", "return", "args", ",", "varargs", ",", "varkw", ",", "frame", ".", "f_locals" ]
Get information about arguments passed into a particular frame. A tuple of four things is returned: (args, varargs, varkw, locals). 'args' is a list of the argument names (it may contain nested lists). 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'locals' is the locals dictionary of the given frame.
[ "Get", "information", "about", "arguments", "passed", "into", "a", "particular", "frame", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_inspect.py#L630-L638
train
209,765
fabioz/PyDev.Debugger
_pydev_imps/_pydev_inspect.py
strseq
def strseq(object, convert, join=joinseq): """Recursively walk a sequence, stringifying each element.""" if type(object) in [types.ListType, types.TupleType]: return join(map(lambda o, c=convert, j=join: strseq(o, c, j), object)) else: return convert(object)
python
def strseq(object, convert, join=joinseq): """Recursively walk a sequence, stringifying each element.""" if type(object) in [types.ListType, types.TupleType]: return join(map(lambda o, c=convert, j=join: strseq(o, c, j), object)) else: return convert(object)
[ "def", "strseq", "(", "object", ",", "convert", ",", "join", "=", "joinseq", ")", ":", "if", "type", "(", "object", ")", "in", "[", "types", ".", "ListType", ",", "types", ".", "TupleType", "]", ":", "return", "join", "(", "map", "(", "lambda", "o"...
Recursively walk a sequence, stringifying each element.
[ "Recursively", "walk", "a", "sequence", "stringifying", "each", "element", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_inspect.py#L646-L651
train
209,766
fabioz/PyDev.Debugger
_pydev_imps/_pydev_inspect.py
formatargspec
def formatargspec(args, varargs=None, varkw=None, defaults=None, formatarg=str, formatvarargs=lambda name: '*' + name, formatvarkw=lambda name: '**' + name, formatvalue=lambda value: '=' + repr(value), join=joinseq): """Format an argument spec from the 4 values returned by getargspec. The first four arguments are (args, varargs, varkw, defaults). The other four arguments are the corresponding optional formatting functions that are called to turn names and values into strings. The ninth argument is an optional function to format the sequence of arguments.""" specs = [] if defaults: firstdefault = len(args) - len(defaults) for i in range(len(args)): spec = strseq(args[i], formatarg, join) if defaults and i >= firstdefault: spec = spec + formatvalue(defaults[i - firstdefault]) specs.append(spec) if varargs: specs.append(formatvarargs(varargs)) if varkw: specs.append(formatvarkw(varkw)) return '(' + string.join(specs, ', ') + ')'
python
def formatargspec(args, varargs=None, varkw=None, defaults=None, formatarg=str, formatvarargs=lambda name: '*' + name, formatvarkw=lambda name: '**' + name, formatvalue=lambda value: '=' + repr(value), join=joinseq): """Format an argument spec from the 4 values returned by getargspec. The first four arguments are (args, varargs, varkw, defaults). The other four arguments are the corresponding optional formatting functions that are called to turn names and values into strings. The ninth argument is an optional function to format the sequence of arguments.""" specs = [] if defaults: firstdefault = len(args) - len(defaults) for i in range(len(args)): spec = strseq(args[i], formatarg, join) if defaults and i >= firstdefault: spec = spec + formatvalue(defaults[i - firstdefault]) specs.append(spec) if varargs: specs.append(formatvarargs(varargs)) if varkw: specs.append(formatvarkw(varkw)) return '(' + string.join(specs, ', ') + ')'
[ "def", "formatargspec", "(", "args", ",", "varargs", "=", "None", ",", "varkw", "=", "None", ",", "defaults", "=", "None", ",", "formatarg", "=", "str", ",", "formatvarargs", "=", "lambda", "name", ":", "'*'", "+", "name", ",", "formatvarkw", "=", "lam...
Format an argument spec from the 4 values returned by getargspec. The first four arguments are (args, varargs, varkw, defaults). The other four arguments are the corresponding optional formatting functions that are called to turn names and values into strings. The ninth argument is an optional function to format the sequence of arguments.
[ "Format", "an", "argument", "spec", "from", "the", "4", "values", "returned", "by", "getargspec", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_inspect.py#L653-L677
train
209,767
fabioz/PyDev.Debugger
_pydev_imps/_pydev_inspect.py
formatargvalues
def formatargvalues(args, varargs, varkw, locals, formatarg=str, formatvarargs=lambda name: '*' + name, formatvarkw=lambda name: '**' + name, formatvalue=lambda value: '=' + repr(value), join=joinseq): """Format an argument spec from the 4 values returned by getargvalues. The first four arguments are (args, varargs, varkw, locals). The next four arguments are the corresponding optional formatting functions that are called to turn names and values into strings. The ninth argument is an optional function to format the sequence of arguments.""" def convert(name, locals=locals, formatarg=formatarg, formatvalue=formatvalue): return formatarg(name) + formatvalue(locals[name]) specs = [] for i in range(len(args)): specs.append(strseq(args[i], convert, join)) if varargs: specs.append(formatvarargs(varargs) + formatvalue(locals[varargs])) if varkw: specs.append(formatvarkw(varkw) + formatvalue(locals[varkw])) return '(' + string.join(specs, ', ') + ')'
python
def formatargvalues(args, varargs, varkw, locals, formatarg=str, formatvarargs=lambda name: '*' + name, formatvarkw=lambda name: '**' + name, formatvalue=lambda value: '=' + repr(value), join=joinseq): """Format an argument spec from the 4 values returned by getargvalues. The first four arguments are (args, varargs, varkw, locals). The next four arguments are the corresponding optional formatting functions that are called to turn names and values into strings. The ninth argument is an optional function to format the sequence of arguments.""" def convert(name, locals=locals, formatarg=formatarg, formatvalue=formatvalue): return formatarg(name) + formatvalue(locals[name]) specs = [] for i in range(len(args)): specs.append(strseq(args[i], convert, join)) if varargs: specs.append(formatvarargs(varargs) + formatvalue(locals[varargs])) if varkw: specs.append(formatvarkw(varkw) + formatvalue(locals[varkw])) return '(' + string.join(specs, ', ') + ')'
[ "def", "formatargvalues", "(", "args", ",", "varargs", ",", "varkw", ",", "locals", ",", "formatarg", "=", "str", ",", "formatvarargs", "=", "lambda", "name", ":", "'*'", "+", "name", ",", "formatvarkw", "=", "lambda", "name", ":", "'**'", "+", "name", ...
Format an argument spec from the 4 values returned by getargvalues. The first four arguments are (args, varargs, varkw, locals). The next four arguments are the corresponding optional formatting functions that are called to turn names and values into strings. The ninth argument is an optional function to format the sequence of arguments.
[ "Format", "an", "argument", "spec", "from", "the", "4", "values", "returned", "by", "getargvalues", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_inspect.py#L679-L701
train
209,768
fabioz/PyDev.Debugger
_pydev_imps/_pydev_inspect.py
getlineno
def getlineno(frame): """Get the line number from a frame object, allowing for optimization.""" # Written by Marc-Andr Lemburg; revised by Jim Hugunin and Fredrik Lundh. lineno = frame.f_lineno code = frame.f_code if hasattr(code, 'co_lnotab'): table = code.co_lnotab lineno = code.co_firstlineno addr = 0 for i in range(0, len(table), 2): addr = addr + ord(table[i]) if addr > frame.f_lasti: break lineno = lineno + ord(table[i + 1]) return lineno
python
def getlineno(frame): """Get the line number from a frame object, allowing for optimization.""" # Written by Marc-Andr Lemburg; revised by Jim Hugunin and Fredrik Lundh. lineno = frame.f_lineno code = frame.f_code if hasattr(code, 'co_lnotab'): table = code.co_lnotab lineno = code.co_firstlineno addr = 0 for i in range(0, len(table), 2): addr = addr + ord(table[i]) if addr > frame.f_lasti: break lineno = lineno + ord(table[i + 1]) return lineno
[ "def", "getlineno", "(", "frame", ")", ":", "# Written by Marc-Andr Lemburg; revised by Jim Hugunin and Fredrik Lundh.", "lineno", "=", "frame", ".", "f_lineno", "code", "=", "frame", ".", "f_code", "if", "hasattr", "(", "code", ",", "'co_lnotab'", ")", ":", "table"...
Get the line number from a frame object, allowing for optimization.
[ "Get", "the", "line", "number", "from", "a", "frame", "object", "allowing", "for", "optimization", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_inspect.py#L736-L749
train
209,769
fabioz/PyDev.Debugger
_pydev_imps/_pydev_inspect.py
getinnerframes
def getinnerframes(tb, context=1): """Get a list of records for a traceback's frame and all lower frames. Each record contains a frame object, filename, line number, function name, a list of lines of context, and index within the context.""" framelist = [] while tb: framelist.append((tb.tb_frame,) + getframeinfo(tb, context)) tb = tb.tb_next return framelist
python
def getinnerframes(tb, context=1): """Get a list of records for a traceback's frame and all lower frames. Each record contains a frame object, filename, line number, function name, a list of lines of context, and index within the context.""" framelist = [] while tb: framelist.append((tb.tb_frame,) + getframeinfo(tb, context)) tb = tb.tb_next return framelist
[ "def", "getinnerframes", "(", "tb", ",", "context", "=", "1", ")", ":", "framelist", "=", "[", "]", "while", "tb", ":", "framelist", ".", "append", "(", "(", "tb", ".", "tb_frame", ",", ")", "+", "getframeinfo", "(", "tb", ",", "context", ")", ")",...
Get a list of records for a traceback's frame and all lower frames. Each record contains a frame object, filename, line number, function name, a list of lines of context, and index within the context.
[ "Get", "a", "list", "of", "records", "for", "a", "traceback", "s", "frame", "and", "all", "lower", "frames", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_inspect.py#L762-L771
train
209,770
fabioz/PyDev.Debugger
third_party/pep8/lib2to3/lib2to3/pytree.py
convert
def convert(gr, raw_node): """ Convert raw node information to a Node or Leaf instance. This is passed to the parser driver which calls it whenever a reduction of a grammar rule produces a new complete node, so that the tree is build strictly bottom-up. """ type, value, context, children = raw_node if children or type in gr.number2symbol: # If there's exactly one child, return that child instead of # creating a new node. if len(children) == 1: return children[0] return Node(type, children, context=context) else: return Leaf(type, value, context=context)
python
def convert(gr, raw_node): """ Convert raw node information to a Node or Leaf instance. This is passed to the parser driver which calls it whenever a reduction of a grammar rule produces a new complete node, so that the tree is build strictly bottom-up. """ type, value, context, children = raw_node if children or type in gr.number2symbol: # If there's exactly one child, return that child instead of # creating a new node. if len(children) == 1: return children[0] return Node(type, children, context=context) else: return Leaf(type, value, context=context)
[ "def", "convert", "(", "gr", ",", "raw_node", ")", ":", "type", ",", "value", ",", "context", ",", "children", "=", "raw_node", "if", "children", "or", "type", "in", "gr", ".", "number2symbol", ":", "# If there's exactly one child, return that child instead of", ...
Convert raw node information to a Node or Leaf instance. This is passed to the parser driver which calls it whenever a reduction of a grammar rule produces a new complete node, so that the tree is build strictly bottom-up.
[ "Convert", "raw", "node", "information", "to", "a", "Node", "or", "Leaf", "instance", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/pytree.py#L429-L445
train
209,771
fabioz/PyDev.Debugger
third_party/pep8/lib2to3/lib2to3/pytree.py
generate_matches
def generate_matches(patterns, nodes): """ Generator yielding matches for a sequence of patterns and nodes. Args: patterns: a sequence of patterns nodes: a sequence of nodes Yields: (count, results) tuples where: count: the entire sequence of patterns matches nodes[:count]; results: dict containing named submatches. """ if not patterns: yield 0, {} else: p, rest = patterns[0], patterns[1:] for c0, r0 in p.generate_matches(nodes): if not rest: yield c0, r0 else: for c1, r1 in generate_matches(rest, nodes[c0:]): r = {} r.update(r0) r.update(r1) yield c0 + c1, r
python
def generate_matches(patterns, nodes): """ Generator yielding matches for a sequence of patterns and nodes. Args: patterns: a sequence of patterns nodes: a sequence of nodes Yields: (count, results) tuples where: count: the entire sequence of patterns matches nodes[:count]; results: dict containing named submatches. """ if not patterns: yield 0, {} else: p, rest = patterns[0], patterns[1:] for c0, r0 in p.generate_matches(nodes): if not rest: yield c0, r0 else: for c1, r1 in generate_matches(rest, nodes[c0:]): r = {} r.update(r0) r.update(r1) yield c0 + c1, r
[ "def", "generate_matches", "(", "patterns", ",", "nodes", ")", ":", "if", "not", "patterns", ":", "yield", "0", ",", "{", "}", "else", ":", "p", ",", "rest", "=", "patterns", "[", "0", "]", ",", "patterns", "[", "1", ":", "]", "for", "c0", ",", ...
Generator yielding matches for a sequence of patterns and nodes. Args: patterns: a sequence of patterns nodes: a sequence of nodes Yields: (count, results) tuples where: count: the entire sequence of patterns matches nodes[:count]; results: dict containing named submatches.
[ "Generator", "yielding", "matches", "for", "a", "sequence", "of", "patterns", "and", "nodes", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/pytree.py#L862-L887
train
209,772
fabioz/PyDev.Debugger
third_party/pep8/lib2to3/lib2to3/pytree.py
Base.replace
def replace(self, new): """Replace this node with a new one in the parent.""" assert self.parent is not None, str(self) assert new is not None if not isinstance(new, list): new = [new] l_children = [] found = False for ch in self.parent.children: if ch is self: assert not found, (self.parent.children, self, new) if new is not None: l_children.extend(new) found = True else: l_children.append(ch) assert found, (self.children, self, new) self.parent.changed() self.parent.children = l_children for x in new: x.parent = self.parent self.parent = None
python
def replace(self, new): """Replace this node with a new one in the parent.""" assert self.parent is not None, str(self) assert new is not None if not isinstance(new, list): new = [new] l_children = [] found = False for ch in self.parent.children: if ch is self: assert not found, (self.parent.children, self, new) if new is not None: l_children.extend(new) found = True else: l_children.append(ch) assert found, (self.children, self, new) self.parent.changed() self.parent.children = l_children for x in new: x.parent = self.parent self.parent = None
[ "def", "replace", "(", "self", ",", "new", ")", ":", "assert", "self", ".", "parent", "is", "not", "None", ",", "str", "(", "self", ")", "assert", "new", "is", "not", "None", "if", "not", "isinstance", "(", "new", ",", "list", ")", ":", "new", "=...
Replace this node with a new one in the parent.
[ "Replace", "this", "node", "with", "a", "new", "one", "in", "the", "parent", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/pytree.py#L132-L153
train
209,773
fabioz/PyDev.Debugger
third_party/pep8/lib2to3/lib2to3/pytree.py
Base.get_lineno
def get_lineno(self): """Return the line number which generated the invocant node.""" node = self while not isinstance(node, Leaf): if not node.children: return node = node.children[0] return node.lineno
python
def get_lineno(self): """Return the line number which generated the invocant node.""" node = self while not isinstance(node, Leaf): if not node.children: return node = node.children[0] return node.lineno
[ "def", "get_lineno", "(", "self", ")", ":", "node", "=", "self", "while", "not", "isinstance", "(", "node", ",", "Leaf", ")", ":", "if", "not", "node", ".", "children", ":", "return", "node", "=", "node", ".", "children", "[", "0", "]", "return", "...
Return the line number which generated the invocant node.
[ "Return", "the", "line", "number", "which", "generated", "the", "invocant", "node", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/pytree.py#L155-L162
train
209,774
fabioz/PyDev.Debugger
third_party/pep8/lib2to3/lib2to3/pytree.py
Base.remove
def remove(self): """ Remove the node from the tree. Returns the position of the node in its parent's children before it was removed. """ if self.parent: for i, node in enumerate(self.parent.children): if node is self: self.parent.changed() del self.parent.children[i] self.parent = None return i
python
def remove(self): """ Remove the node from the tree. Returns the position of the node in its parent's children before it was removed. """ if self.parent: for i, node in enumerate(self.parent.children): if node is self: self.parent.changed() del self.parent.children[i] self.parent = None return i
[ "def", "remove", "(", "self", ")", ":", "if", "self", ".", "parent", ":", "for", "i", ",", "node", "in", "enumerate", "(", "self", ".", "parent", ".", "children", ")", ":", "if", "node", "is", "self", ":", "self", ".", "parent", ".", "changed", "...
Remove the node from the tree. Returns the position of the node in its parent's children before it was removed.
[ "Remove", "the", "node", "from", "the", "tree", ".", "Returns", "the", "position", "of", "the", "node", "in", "its", "parent", "s", "children", "before", "it", "was", "removed", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/pytree.py#L169-L180
train
209,775
fabioz/PyDev.Debugger
third_party/pep8/lib2to3/lib2to3/pytree.py
Base.next_sibling
def next_sibling(self): """ The node immediately following the invocant in their parent's children list. If the invocant does not have a next sibling, it is None """ if self.parent is None: return None # Can't use index(); we need to test by identity for i, child in enumerate(self.parent.children): if child is self: try: return self.parent.children[i+1] except IndexError: return None
python
def next_sibling(self): """ The node immediately following the invocant in their parent's children list. If the invocant does not have a next sibling, it is None """ if self.parent is None: return None # Can't use index(); we need to test by identity for i, child in enumerate(self.parent.children): if child is self: try: return self.parent.children[i+1] except IndexError: return None
[ "def", "next_sibling", "(", "self", ")", ":", "if", "self", ".", "parent", "is", "None", ":", "return", "None", "# Can't use index(); we need to test by identity", "for", "i", ",", "child", "in", "enumerate", "(", "self", ".", "parent", ".", "children", ")", ...
The node immediately following the invocant in their parent's children list. If the invocant does not have a next sibling, it is None
[ "The", "node", "immediately", "following", "the", "invocant", "in", "their", "parent", "s", "children", "list", ".", "If", "the", "invocant", "does", "not", "have", "a", "next", "sibling", "it", "is", "None" ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/pytree.py#L183-L197
train
209,776
fabioz/PyDev.Debugger
third_party/pep8/lib2to3/lib2to3/pytree.py
Base.prev_sibling
def prev_sibling(self): """ The node immediately preceding the invocant in their parent's children list. If the invocant does not have a previous sibling, it is None. """ if self.parent is None: return None # Can't use index(); we need to test by identity for i, child in enumerate(self.parent.children): if child is self: if i == 0: return None return self.parent.children[i-1]
python
def prev_sibling(self): """ The node immediately preceding the invocant in their parent's children list. If the invocant does not have a previous sibling, it is None. """ if self.parent is None: return None # Can't use index(); we need to test by identity for i, child in enumerate(self.parent.children): if child is self: if i == 0: return None return self.parent.children[i-1]
[ "def", "prev_sibling", "(", "self", ")", ":", "if", "self", ".", "parent", "is", "None", ":", "return", "None", "# Can't use index(); we need to test by identity", "for", "i", ",", "child", "in", "enumerate", "(", "self", ".", "parent", ".", "children", ")", ...
The node immediately preceding the invocant in their parent's children list. If the invocant does not have a previous sibling, it is None.
[ "The", "node", "immediately", "preceding", "the", "invocant", "in", "their", "parent", "s", "children", "list", ".", "If", "the", "invocant", "does", "not", "have", "a", "previous", "sibling", "it", "is", "None", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/pytree.py#L200-L213
train
209,777
fabioz/PyDev.Debugger
third_party/pep8/lib2to3/lib2to3/pytree.py
Node.post_order
def post_order(self): """Return a post-order iterator for the tree.""" for child in self.children: for node in child.post_order(): yield node yield self
python
def post_order(self): """Return a post-order iterator for the tree.""" for child in self.children: for node in child.post_order(): yield node yield self
[ "def", "post_order", "(", "self", ")", ":", "for", "child", "in", "self", ".", "children", ":", "for", "node", "in", "child", ".", "post_order", "(", ")", ":", "yield", "node", "yield", "self" ]
Return a post-order iterator for the tree.
[ "Return", "a", "post", "-", "order", "iterator", "for", "the", "tree", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/pytree.py#L294-L299
train
209,778
fabioz/PyDev.Debugger
third_party/pep8/lib2to3/lib2to3/pytree.py
Node.pre_order
def pre_order(self): """Return a pre-order iterator for the tree.""" yield self for child in self.children: for node in child.pre_order(): yield node
python
def pre_order(self): """Return a pre-order iterator for the tree.""" yield self for child in self.children: for node in child.pre_order(): yield node
[ "def", "pre_order", "(", "self", ")", ":", "yield", "self", "for", "child", "in", "self", ".", "children", ":", "for", "node", "in", "child", ".", "pre_order", "(", ")", ":", "yield", "node" ]
Return a pre-order iterator for the tree.
[ "Return", "a", "pre", "-", "order", "iterator", "for", "the", "tree", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/pytree.py#L301-L306
train
209,779
fabioz/PyDev.Debugger
third_party/pep8/lib2to3/lib2to3/pytree.py
BasePattern.match
def match(self, node, results=None): """ Does this pattern exactly match a node? Returns True if it matches, False if not. If results is not None, it must be a dict which will be updated with the nodes matching named subpatterns. Default implementation for non-wildcard patterns. """ if self.type is not None and node.type != self.type: return False if self.content is not None: r = None if results is not None: r = {} if not self._submatch(node, r): return False if r: results.update(r) if results is not None and self.name: results[self.name] = node return True
python
def match(self, node, results=None): """ Does this pattern exactly match a node? Returns True if it matches, False if not. If results is not None, it must be a dict which will be updated with the nodes matching named subpatterns. Default implementation for non-wildcard patterns. """ if self.type is not None and node.type != self.type: return False if self.content is not None: r = None if results is not None: r = {} if not self._submatch(node, r): return False if r: results.update(r) if results is not None and self.name: results[self.name] = node return True
[ "def", "match", "(", "self", ",", "node", ",", "results", "=", "None", ")", ":", "if", "self", ".", "type", "is", "not", "None", "and", "node", ".", "type", "!=", "self", ".", "type", ":", "return", "False", "if", "self", ".", "content", "is", "n...
Does this pattern exactly match a node? Returns True if it matches, False if not. If results is not None, it must be a dict which will be updated with the nodes matching named subpatterns. Default implementation for non-wildcard patterns.
[ "Does", "this", "pattern", "exactly", "match", "a", "node?" ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/pytree.py#L488-L511
train
209,780
fabioz/PyDev.Debugger
third_party/pep8/lib2to3/lib2to3/pytree.py
BasePattern.generate_matches
def generate_matches(self, nodes): """ Generator yielding all matches for this pattern. Default implementation for non-wildcard patterns. """ r = {} if nodes and self.match(nodes[0], r): yield 1, r
python
def generate_matches(self, nodes): """ Generator yielding all matches for this pattern. Default implementation for non-wildcard patterns. """ r = {} if nodes and self.match(nodes[0], r): yield 1, r
[ "def", "generate_matches", "(", "self", ",", "nodes", ")", ":", "r", "=", "{", "}", "if", "nodes", "and", "self", ".", "match", "(", "nodes", "[", "0", "]", ",", "r", ")", ":", "yield", "1", ",", "r" ]
Generator yielding all matches for this pattern. Default implementation for non-wildcard patterns.
[ "Generator", "yielding", "all", "matches", "for", "this", "pattern", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/pytree.py#L523-L531
train
209,781
fabioz/PyDev.Debugger
third_party/pep8/lib2to3/lib2to3/pytree.py
NodePattern._submatch
def _submatch(self, node, results=None): """ Match the pattern's content to the node's children. This assumes the node type matches and self.content is not None. Returns True if it matches, False if not. If results is not None, it must be a dict which will be updated with the nodes matching named subpatterns. When returning False, the results dict may still be updated. """ if self.wildcards: for c, r in generate_matches(self.content, node.children): if c == len(node.children): if results is not None: results.update(r) return True return False if len(self.content) != len(node.children): return False for subpattern, child in zip(self.content, node.children): if not subpattern.match(child, results): return False return True
python
def _submatch(self, node, results=None): """ Match the pattern's content to the node's children. This assumes the node type matches and self.content is not None. Returns True if it matches, False if not. If results is not None, it must be a dict which will be updated with the nodes matching named subpatterns. When returning False, the results dict may still be updated. """ if self.wildcards: for c, r in generate_matches(self.content, node.children): if c == len(node.children): if results is not None: results.update(r) return True return False if len(self.content) != len(node.children): return False for subpattern, child in zip(self.content, node.children): if not subpattern.match(child, results): return False return True
[ "def", "_submatch", "(", "self", ",", "node", ",", "results", "=", "None", ")", ":", "if", "self", ".", "wildcards", ":", "for", "c", ",", "r", "in", "generate_matches", "(", "self", ".", "content", ",", "node", ".", "children", ")", ":", "if", "c"...
Match the pattern's content to the node's children. This assumes the node type matches and self.content is not None. Returns True if it matches, False if not. If results is not None, it must be a dict which will be updated with the nodes matching named subpatterns. When returning False, the results dict may still be updated.
[ "Match", "the", "pattern", "s", "content", "to", "the", "node", "s", "children", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/pytree.py#L611-L636
train
209,782
fabioz/PyDev.Debugger
third_party/pep8/lib2to3/lib2to3/pytree.py
WildcardPattern.optimize
def optimize(self): """Optimize certain stacked wildcard patterns.""" subpattern = None if (self.content is not None and len(self.content) == 1 and len(self.content[0]) == 1): subpattern = self.content[0][0] if self.min == 1 and self.max == 1: if self.content is None: return NodePattern(name=self.name) if subpattern is not None and self.name == subpattern.name: return subpattern.optimize() if (self.min <= 1 and isinstance(subpattern, WildcardPattern) and subpattern.min <= 1 and self.name == subpattern.name): return WildcardPattern(subpattern.content, self.min*subpattern.min, self.max*subpattern.max, subpattern.name) return self
python
def optimize(self): """Optimize certain stacked wildcard patterns.""" subpattern = None if (self.content is not None and len(self.content) == 1 and len(self.content[0]) == 1): subpattern = self.content[0][0] if self.min == 1 and self.max == 1: if self.content is None: return NodePattern(name=self.name) if subpattern is not None and self.name == subpattern.name: return subpattern.optimize() if (self.min <= 1 and isinstance(subpattern, WildcardPattern) and subpattern.min <= 1 and self.name == subpattern.name): return WildcardPattern(subpattern.content, self.min*subpattern.min, self.max*subpattern.max, subpattern.name) return self
[ "def", "optimize", "(", "self", ")", ":", "subpattern", "=", "None", "if", "(", "self", ".", "content", "is", "not", "None", "and", "len", "(", "self", ".", "content", ")", "==", "1", "and", "len", "(", "self", ".", "content", "[", "0", "]", ")",...
Optimize certain stacked wildcard patterns.
[ "Optimize", "certain", "stacked", "wildcard", "patterns", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/pytree.py#L688-L705
train
209,783
fabioz/PyDev.Debugger
third_party/pep8/lib2to3/lib2to3/pytree.py
WildcardPattern.generate_matches
def generate_matches(self, nodes): """ Generator yielding matches for a sequence of nodes. Args: nodes: sequence of nodes Yields: (count, results) tuples where: count: the match comprises nodes[:count]; results: dict containing named submatches. """ if self.content is None: # Shortcut for special case (see __init__.__doc__) for count in xrange(self.min, 1 + min(len(nodes), self.max)): r = {} if self.name: r[self.name] = nodes[:count] yield count, r elif self.name == "bare_name": yield self._bare_name_matches(nodes) else: # The reason for this is that hitting the recursion limit usually # results in some ugly messages about how RuntimeErrors are being # ignored. We don't do this on non-CPython implementation because # they don't have this problem. if hasattr(sys, "getrefcount"): save_stderr = sys.stderr sys.stderr = StringIO() try: for count, r in self._recursive_matches(nodes, 0): if self.name: r[self.name] = nodes[:count] yield count, r except RuntimeError: # We fall back to the iterative pattern matching scheme if the recursive # scheme hits the recursion limit. for count, r in self._iterative_matches(nodes): if self.name: r[self.name] = nodes[:count] yield count, r finally: if hasattr(sys, "getrefcount"): sys.stderr = save_stderr
python
def generate_matches(self, nodes): """ Generator yielding matches for a sequence of nodes. Args: nodes: sequence of nodes Yields: (count, results) tuples where: count: the match comprises nodes[:count]; results: dict containing named submatches. """ if self.content is None: # Shortcut for special case (see __init__.__doc__) for count in xrange(self.min, 1 + min(len(nodes), self.max)): r = {} if self.name: r[self.name] = nodes[:count] yield count, r elif self.name == "bare_name": yield self._bare_name_matches(nodes) else: # The reason for this is that hitting the recursion limit usually # results in some ugly messages about how RuntimeErrors are being # ignored. We don't do this on non-CPython implementation because # they don't have this problem. if hasattr(sys, "getrefcount"): save_stderr = sys.stderr sys.stderr = StringIO() try: for count, r in self._recursive_matches(nodes, 0): if self.name: r[self.name] = nodes[:count] yield count, r except RuntimeError: # We fall back to the iterative pattern matching scheme if the recursive # scheme hits the recursion limit. for count, r in self._iterative_matches(nodes): if self.name: r[self.name] = nodes[:count] yield count, r finally: if hasattr(sys, "getrefcount"): sys.stderr = save_stderr
[ "def", "generate_matches", "(", "self", ",", "nodes", ")", ":", "if", "self", ".", "content", "is", "None", ":", "# Shortcut for special case (see __init__.__doc__)", "for", "count", "in", "xrange", "(", "self", ".", "min", ",", "1", "+", "min", "(", "len", ...
Generator yielding matches for a sequence of nodes. Args: nodes: sequence of nodes Yields: (count, results) tuples where: count: the match comprises nodes[:count]; results: dict containing named submatches.
[ "Generator", "yielding", "matches", "for", "a", "sequence", "of", "nodes", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/pytree.py#L722-L765
train
209,784
fabioz/PyDev.Debugger
third_party/pep8/lib2to3/lib2to3/pytree.py
WildcardPattern._iterative_matches
def _iterative_matches(self, nodes): """Helper to iteratively yield the matches.""" nodelen = len(nodes) if 0 >= self.min: yield 0, {} results = [] # generate matches that use just one alt from self.content for alt in self.content: for c, r in generate_matches(alt, nodes): yield c, r results.append((c, r)) # for each match, iterate down the nodes while results: new_results = [] for c0, r0 in results: # stop if the entire set of nodes has been matched if c0 < nodelen and c0 <= self.max: for alt in self.content: for c1, r1 in generate_matches(alt, nodes[c0:]): if c1 > 0: r = {} r.update(r0) r.update(r1) yield c0 + c1, r new_results.append((c0 + c1, r)) results = new_results
python
def _iterative_matches(self, nodes): """Helper to iteratively yield the matches.""" nodelen = len(nodes) if 0 >= self.min: yield 0, {} results = [] # generate matches that use just one alt from self.content for alt in self.content: for c, r in generate_matches(alt, nodes): yield c, r results.append((c, r)) # for each match, iterate down the nodes while results: new_results = [] for c0, r0 in results: # stop if the entire set of nodes has been matched if c0 < nodelen and c0 <= self.max: for alt in self.content: for c1, r1 in generate_matches(alt, nodes[c0:]): if c1 > 0: r = {} r.update(r0) r.update(r1) yield c0 + c1, r new_results.append((c0 + c1, r)) results = new_results
[ "def", "_iterative_matches", "(", "self", ",", "nodes", ")", ":", "nodelen", "=", "len", "(", "nodes", ")", "if", "0", ">=", "self", ".", "min", ":", "yield", "0", ",", "{", "}", "results", "=", "[", "]", "# generate matches that use just one alt from self...
Helper to iteratively yield the matches.
[ "Helper", "to", "iteratively", "yield", "the", "matches", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/pytree.py#L767-L794
train
209,785
fabioz/PyDev.Debugger
third_party/pep8/lib2to3/lib2to3/pytree.py
WildcardPattern._bare_name_matches
def _bare_name_matches(self, nodes): """Special optimized matcher for bare_name.""" count = 0 r = {} done = False max = len(nodes) while not done and count < max: done = True for leaf in self.content: if leaf[0].match(nodes[count], r): count += 1 done = False break r[self.name] = nodes[:count] return count, r
python
def _bare_name_matches(self, nodes): """Special optimized matcher for bare_name.""" count = 0 r = {} done = False max = len(nodes) while not done and count < max: done = True for leaf in self.content: if leaf[0].match(nodes[count], r): count += 1 done = False break r[self.name] = nodes[:count] return count, r
[ "def", "_bare_name_matches", "(", "self", ",", "nodes", ")", ":", "count", "=", "0", "r", "=", "{", "}", "done", "=", "False", "max", "=", "len", "(", "nodes", ")", "while", "not", "done", "and", "count", "<", "max", ":", "done", "=", "True", "fo...
Special optimized matcher for bare_name.
[ "Special", "optimized", "matcher", "for", "bare_name", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/pytree.py#L796-L810
train
209,786
fabioz/PyDev.Debugger
third_party/pep8/lib2to3/lib2to3/pytree.py
WildcardPattern._recursive_matches
def _recursive_matches(self, nodes, count): """Helper to recursively yield the matches.""" assert self.content is not None if count >= self.min: yield 0, {} if count < self.max: for alt in self.content: for c0, r0 in generate_matches(alt, nodes): for c1, r1 in self._recursive_matches(nodes[c0:], count+1): r = {} r.update(r0) r.update(r1) yield c0 + c1, r
python
def _recursive_matches(self, nodes, count): """Helper to recursively yield the matches.""" assert self.content is not None if count >= self.min: yield 0, {} if count < self.max: for alt in self.content: for c0, r0 in generate_matches(alt, nodes): for c1, r1 in self._recursive_matches(nodes[c0:], count+1): r = {} r.update(r0) r.update(r1) yield c0 + c1, r
[ "def", "_recursive_matches", "(", "self", ",", "nodes", ",", "count", ")", ":", "assert", "self", ".", "content", "is", "not", "None", "if", "count", ">=", "self", ".", "min", ":", "yield", "0", ",", "{", "}", "if", "count", "<", "self", ".", "max"...
Helper to recursively yield the matches.
[ "Helper", "to", "recursively", "yield", "the", "matches", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/pytree.py#L812-L824
train
209,787
fabioz/PyDev.Debugger
_pydevd_bundle/pydevd_reload.py
xreload
def xreload(mod): """Reload a module in place, updating classes, methods and functions. mod: a module object Returns a boolean indicating whether a change was done. """ r = Reload(mod) r.apply() found_change = r.found_change r = None pydevd_dont_trace.clear_trace_filter_cache() return found_change
python
def xreload(mod): """Reload a module in place, updating classes, methods and functions. mod: a module object Returns a boolean indicating whether a change was done. """ r = Reload(mod) r.apply() found_change = r.found_change r = None pydevd_dont_trace.clear_trace_filter_cache() return found_change
[ "def", "xreload", "(", "mod", ")", ":", "r", "=", "Reload", "(", "mod", ")", "r", ".", "apply", "(", ")", "found_change", "=", "r", ".", "found_change", "r", "=", "None", "pydevd_dont_trace", ".", "clear_trace_filter_cache", "(", ")", "return", "found_ch...
Reload a module in place, updating classes, methods and functions. mod: a module object Returns a boolean indicating whether a change was done.
[ "Reload", "a", "module", "in", "place", "updating", "classes", "methods", "and", "functions", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_bundle/pydevd_reload.py#L167-L179
train
209,788
fabioz/PyDev.Debugger
_pydevd_bundle/pydevd_reload.py
Reload._update
def _update(self, namespace, name, oldobj, newobj, is_class_namespace=False): """Update oldobj, if possible in place, with newobj. If oldobj is immutable, this simply returns newobj. Args: oldobj: the object to be updated newobj: the object used as the source for the update """ try: notify_info2('Updating: ', oldobj) if oldobj is newobj: # Probably something imported return if type(oldobj) is not type(newobj): # Cop-out: if the type changed, give up notify_error('Type of: %s changed... Skipping.' % (oldobj,)) return if isinstance(newobj, types.FunctionType): self._update_function(oldobj, newobj) return if isinstance(newobj, types.MethodType): self._update_method(oldobj, newobj) return if isinstance(newobj, classmethod): self._update_classmethod(oldobj, newobj) return if isinstance(newobj, staticmethod): self._update_staticmethod(oldobj, newobj) return if hasattr(types, 'ClassType'): classtype = (types.ClassType, type) # object is not instance of types.ClassType. else: classtype = type if isinstance(newobj, classtype): self._update_class(oldobj, newobj) return # New: dealing with metaclasses. if hasattr(newobj, '__metaclass__') and hasattr(newobj, '__class__') and newobj.__metaclass__ == newobj.__class__: self._update_class(oldobj, newobj) return if namespace is not None: if oldobj != newobj and str(oldobj) != str(newobj) and repr(oldobj) != repr(newobj): xreload_old_new = None if is_class_namespace: xreload_old_new = getattr(namespace, '__xreload_old_new__', None) if xreload_old_new is not None: self.found_change = True xreload_old_new(name, oldobj, newobj) elif '__xreload_old_new__' in namespace: xreload_old_new = namespace['__xreload_old_new__'] xreload_old_new(namespace, name, oldobj, newobj) self.found_change = True # Too much information to the user... # else: # notify_info0('%s NOT updated. Create __xreload_old_new__(name, old, new) for custom reload' % (name,)) except: notify_error('Exception found when updating %s. Proceeding for other items.' % (name,)) pydev_log.exception()
python
def _update(self, namespace, name, oldobj, newobj, is_class_namespace=False): """Update oldobj, if possible in place, with newobj. If oldobj is immutable, this simply returns newobj. Args: oldobj: the object to be updated newobj: the object used as the source for the update """ try: notify_info2('Updating: ', oldobj) if oldobj is newobj: # Probably something imported return if type(oldobj) is not type(newobj): # Cop-out: if the type changed, give up notify_error('Type of: %s changed... Skipping.' % (oldobj,)) return if isinstance(newobj, types.FunctionType): self._update_function(oldobj, newobj) return if isinstance(newobj, types.MethodType): self._update_method(oldobj, newobj) return if isinstance(newobj, classmethod): self._update_classmethod(oldobj, newobj) return if isinstance(newobj, staticmethod): self._update_staticmethod(oldobj, newobj) return if hasattr(types, 'ClassType'): classtype = (types.ClassType, type) # object is not instance of types.ClassType. else: classtype = type if isinstance(newobj, classtype): self._update_class(oldobj, newobj) return # New: dealing with metaclasses. if hasattr(newobj, '__metaclass__') and hasattr(newobj, '__class__') and newobj.__metaclass__ == newobj.__class__: self._update_class(oldobj, newobj) return if namespace is not None: if oldobj != newobj and str(oldobj) != str(newobj) and repr(oldobj) != repr(newobj): xreload_old_new = None if is_class_namespace: xreload_old_new = getattr(namespace, '__xreload_old_new__', None) if xreload_old_new is not None: self.found_change = True xreload_old_new(name, oldobj, newobj) elif '__xreload_old_new__' in namespace: xreload_old_new = namespace['__xreload_old_new__'] xreload_old_new(namespace, name, oldobj, newobj) self.found_change = True # Too much information to the user... # else: # notify_info0('%s NOT updated. Create __xreload_old_new__(name, old, new) for custom reload' % (name,)) except: notify_error('Exception found when updating %s. Proceeding for other items.' % (name,)) pydev_log.exception()
[ "def", "_update", "(", "self", ",", "namespace", ",", "name", ",", "oldobj", ",", "newobj", ",", "is_class_namespace", "=", "False", ")", ":", "try", ":", "notify_info2", "(", "'Updating: '", ",", "oldobj", ")", "if", "oldobj", "is", "newobj", ":", "# Pr...
Update oldobj, if possible in place, with newobj. If oldobj is immutable, this simply returns newobj. Args: oldobj: the object to be updated newobj: the object used as the source for the update
[ "Update", "oldobj", "if", "possible", "in", "place", "with", "newobj", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_bundle/pydevd_reload.py#L294-L365
train
209,789
fabioz/PyDev.Debugger
_pydevd_bundle/pydevd_reload.py
Reload._update_function
def _update_function(self, oldfunc, newfunc): """Update a function object.""" oldfunc.__doc__ = newfunc.__doc__ oldfunc.__dict__.update(newfunc.__dict__) try: newfunc.__code__ attr_name = '__code__' except AttributeError: newfunc.func_code attr_name = 'func_code' old_code = getattr(oldfunc, attr_name) new_code = getattr(newfunc, attr_name) if not code_objects_equal(old_code, new_code): notify_info0('Updated function code:', oldfunc) setattr(oldfunc, attr_name, new_code) self.found_change = True try: oldfunc.__defaults__ = newfunc.__defaults__ except AttributeError: oldfunc.func_defaults = newfunc.func_defaults return oldfunc
python
def _update_function(self, oldfunc, newfunc): """Update a function object.""" oldfunc.__doc__ = newfunc.__doc__ oldfunc.__dict__.update(newfunc.__dict__) try: newfunc.__code__ attr_name = '__code__' except AttributeError: newfunc.func_code attr_name = 'func_code' old_code = getattr(oldfunc, attr_name) new_code = getattr(newfunc, attr_name) if not code_objects_equal(old_code, new_code): notify_info0('Updated function code:', oldfunc) setattr(oldfunc, attr_name, new_code) self.found_change = True try: oldfunc.__defaults__ = newfunc.__defaults__ except AttributeError: oldfunc.func_defaults = newfunc.func_defaults return oldfunc
[ "def", "_update_function", "(", "self", ",", "oldfunc", ",", "newfunc", ")", ":", "oldfunc", ".", "__doc__", "=", "newfunc", ".", "__doc__", "oldfunc", ".", "__dict__", ".", "update", "(", "newfunc", ".", "__dict__", ")", "try", ":", "newfunc", ".", "__c...
Update a function object.
[ "Update", "a", "function", "object", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_bundle/pydevd_reload.py#L369-L393
train
209,790
fabioz/PyDev.Debugger
_pydevd_bundle/pydevd_reload.py
Reload._update_method
def _update_method(self, oldmeth, newmeth): """Update a method object.""" # XXX What if im_func is not a function? if hasattr(oldmeth, 'im_func') and hasattr(newmeth, 'im_func'): self._update(None, None, oldmeth.im_func, newmeth.im_func) elif hasattr(oldmeth, '__func__') and hasattr(newmeth, '__func__'): self._update(None, None, oldmeth.__func__, newmeth.__func__) return oldmeth
python
def _update_method(self, oldmeth, newmeth): """Update a method object.""" # XXX What if im_func is not a function? if hasattr(oldmeth, 'im_func') and hasattr(newmeth, 'im_func'): self._update(None, None, oldmeth.im_func, newmeth.im_func) elif hasattr(oldmeth, '__func__') and hasattr(newmeth, '__func__'): self._update(None, None, oldmeth.__func__, newmeth.__func__) return oldmeth
[ "def", "_update_method", "(", "self", ",", "oldmeth", ",", "newmeth", ")", ":", "# XXX What if im_func is not a function?", "if", "hasattr", "(", "oldmeth", ",", "'im_func'", ")", "and", "hasattr", "(", "newmeth", ",", "'im_func'", ")", ":", "self", ".", "_upd...
Update a method object.
[ "Update", "a", "method", "object", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_bundle/pydevd_reload.py#L395-L402
train
209,791
fabioz/PyDev.Debugger
_pydevd_bundle/pydevd_reload.py
Reload._update_class
def _update_class(self, oldclass, newclass): """Update a class object.""" olddict = oldclass.__dict__ newdict = newclass.__dict__ oldnames = set(olddict) newnames = set(newdict) for name in newnames - oldnames: setattr(oldclass, name, newdict[name]) notify_info0('Added:', name, 'to', oldclass) self.found_change = True # Note: not removing old things... # for name in oldnames - newnames: # notify_info('Removed:', name, 'from', oldclass) # delattr(oldclass, name) for name in (oldnames & newnames) - set(['__dict__', '__doc__']): self._update(oldclass, name, olddict[name], newdict[name], is_class_namespace=True) old_bases = getattr(oldclass, '__bases__', None) new_bases = getattr(newclass, '__bases__', None) if str(old_bases) != str(new_bases): notify_error('Changing the hierarchy of a class is not supported. %s may be inconsistent.' % (oldclass,)) self._handle_namespace(oldclass, is_class_namespace=True)
python
def _update_class(self, oldclass, newclass): """Update a class object.""" olddict = oldclass.__dict__ newdict = newclass.__dict__ oldnames = set(olddict) newnames = set(newdict) for name in newnames - oldnames: setattr(oldclass, name, newdict[name]) notify_info0('Added:', name, 'to', oldclass) self.found_change = True # Note: not removing old things... # for name in oldnames - newnames: # notify_info('Removed:', name, 'from', oldclass) # delattr(oldclass, name) for name in (oldnames & newnames) - set(['__dict__', '__doc__']): self._update(oldclass, name, olddict[name], newdict[name], is_class_namespace=True) old_bases = getattr(oldclass, '__bases__', None) new_bases = getattr(newclass, '__bases__', None) if str(old_bases) != str(new_bases): notify_error('Changing the hierarchy of a class is not supported. %s may be inconsistent.' % (oldclass,)) self._handle_namespace(oldclass, is_class_namespace=True)
[ "def", "_update_class", "(", "self", ",", "oldclass", ",", "newclass", ")", ":", "olddict", "=", "oldclass", ".", "__dict__", "newdict", "=", "newclass", ".", "__dict__", "oldnames", "=", "set", "(", "olddict", ")", "newnames", "=", "set", "(", "newdict", ...
Update a class object.
[ "Update", "a", "class", "object", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_bundle/pydevd_reload.py#L404-L430
train
209,792
fabioz/PyDev.Debugger
_pydevd_bundle/pydevd_reload.py
Reload._update_classmethod
def _update_classmethod(self, oldcm, newcm): """Update a classmethod update.""" # While we can't modify the classmethod object itself (it has no # mutable attributes), we *can* extract the underlying function # (by calling __get__(), which returns a method object) and update # it in-place. We don't have the class available to pass to # __get__() but any object except None will do. self._update(None, None, oldcm.__get__(0), newcm.__get__(0))
python
def _update_classmethod(self, oldcm, newcm): """Update a classmethod update.""" # While we can't modify the classmethod object itself (it has no # mutable attributes), we *can* extract the underlying function # (by calling __get__(), which returns a method object) and update # it in-place. We don't have the class available to pass to # __get__() but any object except None will do. self._update(None, None, oldcm.__get__(0), newcm.__get__(0))
[ "def", "_update_classmethod", "(", "self", ",", "oldcm", ",", "newcm", ")", ":", "# While we can't modify the classmethod object itself (it has no", "# mutable attributes), we *can* extract the underlying function", "# (by calling __get__(), which returns a method object) and update", "# i...
Update a classmethod update.
[ "Update", "a", "classmethod", "update", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_bundle/pydevd_reload.py#L432-L439
train
209,793
fabioz/PyDev.Debugger
_pydevd_bundle/pydevd_reload.py
Reload._update_staticmethod
def _update_staticmethod(self, oldsm, newsm): """Update a staticmethod update.""" # While we can't modify the staticmethod object itself (it has no # mutable attributes), we *can* extract the underlying function # (by calling __get__(), which returns it) and update it in-place. # We don't have the class available to pass to __get__() but any # object except None will do. self._update(None, None, oldsm.__get__(0), newsm.__get__(0))
python
def _update_staticmethod(self, oldsm, newsm): """Update a staticmethod update.""" # While we can't modify the staticmethod object itself (it has no # mutable attributes), we *can* extract the underlying function # (by calling __get__(), which returns it) and update it in-place. # We don't have the class available to pass to __get__() but any # object except None will do. self._update(None, None, oldsm.__get__(0), newsm.__get__(0))
[ "def", "_update_staticmethod", "(", "self", ",", "oldsm", ",", "newsm", ")", ":", "# While we can't modify the staticmethod object itself (it has no", "# mutable attributes), we *can* extract the underlying function", "# (by calling __get__(), which returns it) and update it in-place.", "#...
Update a staticmethod update.
[ "Update", "a", "staticmethod", "update", "." ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_bundle/pydevd_reload.py#L441-L448
train
209,794
fabioz/PyDev.Debugger
_pydevd_bundle/pydevd_save_locals.py
make_save_locals_impl
def make_save_locals_impl(): """ Factory for the 'save_locals_impl' method. This may seem like a complicated pattern but it is essential that the method is created at module load time. Inner imports after module load time would cause an occasional debugger deadlock due to the importer lock and debugger lock being taken in different order in different threads. """ try: if '__pypy__' in sys.builtin_module_names: import __pypy__ # @UnresolvedImport save_locals = __pypy__.locals_to_fast except: pass else: if '__pypy__' in sys.builtin_module_names: def save_locals_pypy_impl(frame): save_locals(frame) return save_locals_pypy_impl try: import ctypes locals_to_fast = ctypes.pythonapi.PyFrame_LocalsToFast except: pass else: def save_locals_ctypes_impl(frame): locals_to_fast(ctypes.py_object(frame), ctypes.c_int(0)) return save_locals_ctypes_impl return None
python
def make_save_locals_impl(): """ Factory for the 'save_locals_impl' method. This may seem like a complicated pattern but it is essential that the method is created at module load time. Inner imports after module load time would cause an occasional debugger deadlock due to the importer lock and debugger lock being taken in different order in different threads. """ try: if '__pypy__' in sys.builtin_module_names: import __pypy__ # @UnresolvedImport save_locals = __pypy__.locals_to_fast except: pass else: if '__pypy__' in sys.builtin_module_names: def save_locals_pypy_impl(frame): save_locals(frame) return save_locals_pypy_impl try: import ctypes locals_to_fast = ctypes.pythonapi.PyFrame_LocalsToFast except: pass else: def save_locals_ctypes_impl(frame): locals_to_fast(ctypes.py_object(frame), ctypes.c_int(0)) return save_locals_ctypes_impl return None
[ "def", "make_save_locals_impl", "(", ")", ":", "try", ":", "if", "'__pypy__'", "in", "sys", ".", "builtin_module_names", ":", "import", "__pypy__", "# @UnresolvedImport", "save_locals", "=", "__pypy__", ".", "locals_to_fast", "except", ":", "pass", "else", ":", ...
Factory for the 'save_locals_impl' method. This may seem like a complicated pattern but it is essential that the method is created at module load time. Inner imports after module load time would cause an occasional debugger deadlock due to the importer lock and debugger lock being taken in different order in different threads.
[ "Factory", "for", "the", "save_locals_impl", "method", ".", "This", "may", "seem", "like", "a", "complicated", "pattern", "but", "it", "is", "essential", "that", "the", "method", "is", "created", "at", "module", "load", "time", ".", "Inner", "imports", "afte...
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_bundle/pydevd_save_locals.py#L36-L66
train
209,795
fabioz/PyDev.Debugger
third_party/pep8/lib2to3/lib2to3/fixer_util.py
Assign
def Assign(target, source): """Build an assignment statement""" if not isinstance(target, list): target = [target] if not isinstance(source, list): source.prefix = u" " source = [source] return Node(syms.atom, target + [Leaf(token.EQUAL, u"=", prefix=u" ")] + source)
python
def Assign(target, source): """Build an assignment statement""" if not isinstance(target, list): target = [target] if not isinstance(source, list): source.prefix = u" " source = [source] return Node(syms.atom, target + [Leaf(token.EQUAL, u"=", prefix=u" ")] + source)
[ "def", "Assign", "(", "target", ",", "source", ")", ":", "if", "not", "isinstance", "(", "target", ",", "list", ")", ":", "target", "=", "[", "target", "]", "if", "not", "isinstance", "(", "source", ",", "list", ")", ":", "source", ".", "prefix", "...
Build an assignment statement
[ "Build", "an", "assignment", "statement" ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/fixer_util.py#L27-L36
train
209,796
fabioz/PyDev.Debugger
third_party/pep8/lib2to3/lib2to3/fixer_util.py
Call
def Call(func_name, args=None, prefix=None): """A function call""" node = Node(syms.power, [func_name, ArgList(args)]) if prefix is not None: node.prefix = prefix return node
python
def Call(func_name, args=None, prefix=None): """A function call""" node = Node(syms.power, [func_name, ArgList(args)]) if prefix is not None: node.prefix = prefix return node
[ "def", "Call", "(", "func_name", ",", "args", "=", "None", ",", "prefix", "=", "None", ")", ":", "node", "=", "Node", "(", "syms", ".", "power", ",", "[", "func_name", ",", "ArgList", "(", "args", ")", "]", ")", "if", "prefix", "is", "not", "None...
A function call
[ "A", "function", "call" ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/fixer_util.py#L61-L66
train
209,797
fabioz/PyDev.Debugger
third_party/pep8/lib2to3/lib2to3/fixer_util.py
Subscript
def Subscript(index_node): """A numeric or string subscript""" return Node(syms.trailer, [Leaf(token.LBRACE, u"["), index_node, Leaf(token.RBRACE, u"]")])
python
def Subscript(index_node): """A numeric or string subscript""" return Node(syms.trailer, [Leaf(token.LBRACE, u"["), index_node, Leaf(token.RBRACE, u"]")])
[ "def", "Subscript", "(", "index_node", ")", ":", "return", "Node", "(", "syms", ".", "trailer", ",", "[", "Leaf", "(", "token", ".", "LBRACE", ",", "u\"[\"", ")", ",", "index_node", ",", "Leaf", "(", "token", ".", "RBRACE", ",", "u\"]\"", ")", "]", ...
A numeric or string subscript
[ "A", "numeric", "or", "string", "subscript" ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/fixer_util.py#L79-L83
train
209,798
fabioz/PyDev.Debugger
third_party/pep8/lib2to3/lib2to3/fixer_util.py
is_tuple
def is_tuple(node): """Does the node represent a tuple literal?""" if isinstance(node, Node) and node.children == [LParen(), RParen()]: return True return (isinstance(node, Node) and len(node.children) == 3 and isinstance(node.children[0], Leaf) and isinstance(node.children[1], Node) and isinstance(node.children[2], Leaf) and node.children[0].value == u"(" and node.children[2].value == u")")
python
def is_tuple(node): """Does the node represent a tuple literal?""" if isinstance(node, Node) and node.children == [LParen(), RParen()]: return True return (isinstance(node, Node) and len(node.children) == 3 and isinstance(node.children[0], Leaf) and isinstance(node.children[1], Node) and isinstance(node.children[2], Leaf) and node.children[0].value == u"(" and node.children[2].value == u")")
[ "def", "is_tuple", "(", "node", ")", ":", "if", "isinstance", "(", "node", ",", "Node", ")", "and", "node", ".", "children", "==", "[", "LParen", "(", ")", ",", "RParen", "(", ")", "]", ":", "return", "True", "return", "(", "isinstance", "(", "node...
Does the node represent a tuple literal?
[ "Does", "the", "node", "represent", "a", "tuple", "literal?" ]
ed9c4307662a5593b8a7f1f3389ecd0e79b8c503
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/fixer_util.py#L137-L147
train
209,799