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/thread.py | Thread.read_stack_dwords | def read_stack_dwords(self, count, offset = 0):
"""
Reads DWORDs from the top of the stack.
@type count: int
@param count: Number of DWORDs to read.
@type offset: int
@param offset: Offset from the stack pointer to begin reading.
@rtype: tuple( int... )
@return: Tuple of integers read from the stack.
@raise WindowsError: Could not read the requested data.
"""
if count > 0:
stackData = self.read_stack_data(count * 4, offset)
return struct.unpack('<'+('L'*count), stackData)
return () | python | def read_stack_dwords(self, count, offset = 0):
"""
Reads DWORDs from the top of the stack.
@type count: int
@param count: Number of DWORDs to read.
@type offset: int
@param offset: Offset from the stack pointer to begin reading.
@rtype: tuple( int... )
@return: Tuple of integers read from the stack.
@raise WindowsError: Could not read the requested data.
"""
if count > 0:
stackData = self.read_stack_data(count * 4, offset)
return struct.unpack('<'+('L'*count), stackData)
return () | [
"def",
"read_stack_dwords",
"(",
"self",
",",
"count",
",",
"offset",
"=",
"0",
")",
":",
"if",
"count",
">",
"0",
":",
"stackData",
"=",
"self",
".",
"read_stack_data",
"(",
"count",
"*",
"4",
",",
"offset",
")",
"return",
"struct",
".",
"unpack",
"... | Reads DWORDs from the top of the stack.
@type count: int
@param count: Number of DWORDs to read.
@type offset: int
@param offset: Offset from the stack pointer to begin reading.
@rtype: tuple( int... )
@return: Tuple of integers read from the stack.
@raise WindowsError: Could not read the requested data. | [
"Reads",
"DWORDs",
"from",
"the",
"top",
"of",
"the",
"stack",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/thread.py#L1376-L1394 | train | 209,600 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/thread.py | Thread.peek_stack_dwords | def peek_stack_dwords(self, count, offset = 0):
"""
Tries to read DWORDs from the top of the stack.
@type count: int
@param count: Number of DWORDs to read.
@type offset: int
@param offset: Offset from the stack pointer to begin reading.
@rtype: tuple( int... )
@return: Tuple of integers read from the stack.
May be less than the requested number of DWORDs.
"""
stackData = self.peek_stack_data(count * 4, offset)
if len(stackData) & 3:
stackData = stackData[:-len(stackData) & 3]
if not stackData:
return ()
return struct.unpack('<'+('L'*count), stackData) | python | def peek_stack_dwords(self, count, offset = 0):
"""
Tries to read DWORDs from the top of the stack.
@type count: int
@param count: Number of DWORDs to read.
@type offset: int
@param offset: Offset from the stack pointer to begin reading.
@rtype: tuple( int... )
@return: Tuple of integers read from the stack.
May be less than the requested number of DWORDs.
"""
stackData = self.peek_stack_data(count * 4, offset)
if len(stackData) & 3:
stackData = stackData[:-len(stackData) & 3]
if not stackData:
return ()
return struct.unpack('<'+('L'*count), stackData) | [
"def",
"peek_stack_dwords",
"(",
"self",
",",
"count",
",",
"offset",
"=",
"0",
")",
":",
"stackData",
"=",
"self",
".",
"peek_stack_data",
"(",
"count",
"*",
"4",
",",
"offset",
")",
"if",
"len",
"(",
"stackData",
")",
"&",
"3",
":",
"stackData",
"=... | Tries to read DWORDs from the top of the stack.
@type count: int
@param count: Number of DWORDs to read.
@type offset: int
@param offset: Offset from the stack pointer to begin reading.
@rtype: tuple( int... )
@return: Tuple of integers read from the stack.
May be less than the requested number of DWORDs. | [
"Tries",
"to",
"read",
"DWORDs",
"from",
"the",
"top",
"of",
"the",
"stack",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/thread.py#L1396-L1415 | train | 209,601 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/thread.py | Thread.read_stack_qwords | def read_stack_qwords(self, count, offset = 0):
"""
Reads QWORDs from the top of the stack.
@type count: int
@param count: Number of QWORDs to read.
@type offset: int
@param offset: Offset from the stack pointer to begin reading.
@rtype: tuple( int... )
@return: Tuple of integers read from the stack.
@raise WindowsError: Could not read the requested data.
"""
stackData = self.read_stack_data(count * 8, offset)
return struct.unpack('<'+('Q'*count), stackData) | python | def read_stack_qwords(self, count, offset = 0):
"""
Reads QWORDs from the top of the stack.
@type count: int
@param count: Number of QWORDs to read.
@type offset: int
@param offset: Offset from the stack pointer to begin reading.
@rtype: tuple( int... )
@return: Tuple of integers read from the stack.
@raise WindowsError: Could not read the requested data.
"""
stackData = self.read_stack_data(count * 8, offset)
return struct.unpack('<'+('Q'*count), stackData) | [
"def",
"read_stack_qwords",
"(",
"self",
",",
"count",
",",
"offset",
"=",
"0",
")",
":",
"stackData",
"=",
"self",
".",
"read_stack_data",
"(",
"count",
"*",
"8",
",",
"offset",
")",
"return",
"struct",
".",
"unpack",
"(",
"'<'",
"+",
"(",
"'Q'",
"*... | Reads QWORDs from the top of the stack.
@type count: int
@param count: Number of QWORDs to read.
@type offset: int
@param offset: Offset from the stack pointer to begin reading.
@rtype: tuple( int... )
@return: Tuple of integers read from the stack.
@raise WindowsError: Could not read the requested data. | [
"Reads",
"QWORDs",
"from",
"the",
"top",
"of",
"the",
"stack",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/thread.py#L1417-L1433 | train | 209,602 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/thread.py | Thread.read_stack_structure | def read_stack_structure(self, structure, offset = 0):
"""
Reads the given structure at the top of the stack.
@type structure: ctypes.Structure
@param structure: Structure of the data to read from the stack.
@type offset: int
@param offset: Offset from the stack pointer to begin reading.
The stack pointer is the same returned by the L{get_sp} method.
@rtype: tuple
@return: Tuple of elements read from the stack. The type of each
element matches the types in the stack frame structure.
"""
aProcess = self.get_process()
stackData = aProcess.read_structure(self.get_sp() + offset, structure)
return tuple([ stackData.__getattribute__(name)
for (name, type) in stackData._fields_ ]) | python | def read_stack_structure(self, structure, offset = 0):
"""
Reads the given structure at the top of the stack.
@type structure: ctypes.Structure
@param structure: Structure of the data to read from the stack.
@type offset: int
@param offset: Offset from the stack pointer to begin reading.
The stack pointer is the same returned by the L{get_sp} method.
@rtype: tuple
@return: Tuple of elements read from the stack. The type of each
element matches the types in the stack frame structure.
"""
aProcess = self.get_process()
stackData = aProcess.read_structure(self.get_sp() + offset, structure)
return tuple([ stackData.__getattribute__(name)
for (name, type) in stackData._fields_ ]) | [
"def",
"read_stack_structure",
"(",
"self",
",",
"structure",
",",
"offset",
"=",
"0",
")",
":",
"aProcess",
"=",
"self",
".",
"get_process",
"(",
")",
"stackData",
"=",
"aProcess",
".",
"read_structure",
"(",
"self",
".",
"get_sp",
"(",
")",
"+",
"offse... | Reads the given structure at the top of the stack.
@type structure: ctypes.Structure
@param structure: Structure of the data to read from the stack.
@type offset: int
@param offset: Offset from the stack pointer to begin reading.
The stack pointer is the same returned by the L{get_sp} method.
@rtype: tuple
@return: Tuple of elements read from the stack. The type of each
element matches the types in the stack frame structure. | [
"Reads",
"the",
"given",
"structure",
"at",
"the",
"top",
"of",
"the",
"stack",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/thread.py#L1456-L1474 | train | 209,603 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/thread.py | Thread.read_stack_frame | def read_stack_frame(self, structure, offset = 0):
"""
Reads the stack frame of the thread.
@type structure: ctypes.Structure
@param structure: Structure of the stack frame.
@type offset: int
@param offset: Offset from the frame pointer to begin reading.
The frame pointer is the same returned by the L{get_fp} method.
@rtype: tuple
@return: Tuple of elements read from the stack frame. The type of each
element matches the types in the stack frame structure.
"""
aProcess = self.get_process()
stackData = aProcess.read_structure(self.get_fp() + offset, structure)
return tuple([ stackData.__getattribute__(name)
for (name, type) in stackData._fields_ ]) | python | def read_stack_frame(self, structure, offset = 0):
"""
Reads the stack frame of the thread.
@type structure: ctypes.Structure
@param structure: Structure of the stack frame.
@type offset: int
@param offset: Offset from the frame pointer to begin reading.
The frame pointer is the same returned by the L{get_fp} method.
@rtype: tuple
@return: Tuple of elements read from the stack frame. The type of each
element matches the types in the stack frame structure.
"""
aProcess = self.get_process()
stackData = aProcess.read_structure(self.get_fp() + offset, structure)
return tuple([ stackData.__getattribute__(name)
for (name, type) in stackData._fields_ ]) | [
"def",
"read_stack_frame",
"(",
"self",
",",
"structure",
",",
"offset",
"=",
"0",
")",
":",
"aProcess",
"=",
"self",
".",
"get_process",
"(",
")",
"stackData",
"=",
"aProcess",
".",
"read_structure",
"(",
"self",
".",
"get_fp",
"(",
")",
"+",
"offset",
... | Reads the stack frame of the thread.
@type structure: ctypes.Structure
@param structure: Structure of the stack frame.
@type offset: int
@param offset: Offset from the frame pointer to begin reading.
The frame pointer is the same returned by the L{get_fp} method.
@rtype: tuple
@return: Tuple of elements read from the stack frame. The type of each
element matches the types in the stack frame structure. | [
"Reads",
"the",
"stack",
"frame",
"of",
"the",
"thread",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/thread.py#L1476-L1494 | train | 209,604 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/thread.py | Thread.peek_pointers_in_registers | def peek_pointers_in_registers(self, peekSize = 16, context = None):
"""
Tries to guess which values in the registers are valid pointers,
and reads some data from them.
@type peekSize: int
@param peekSize: Number of bytes to read from each pointer found.
@type context: dict( str S{->} int )
@param context: (Optional)
Dictionary mapping register names to their values.
If not given, the current thread context will be used.
@rtype: dict( str S{->} str )
@return: Dictionary mapping register names to the data they point to.
"""
peekable_registers = (
'Eax', 'Ebx', 'Ecx', 'Edx', 'Esi', 'Edi', 'Ebp'
)
if not context:
context = self.get_context(win32.CONTEXT_CONTROL | \
win32.CONTEXT_INTEGER)
aProcess = self.get_process()
data = dict()
for (reg_name, reg_value) in compat.iteritems(context):
if reg_name not in peekable_registers:
continue
## if reg_name == 'Ebp':
## stack_begin, stack_end = self.get_stack_range()
## print hex(stack_end), hex(reg_value), hex(stack_begin)
## if stack_begin and stack_end and stack_end < stack_begin and \
## stack_begin <= reg_value <= stack_end:
## continue
reg_data = aProcess.peek(reg_value, peekSize)
if reg_data:
data[reg_name] = reg_data
return data | python | def peek_pointers_in_registers(self, peekSize = 16, context = None):
"""
Tries to guess which values in the registers are valid pointers,
and reads some data from them.
@type peekSize: int
@param peekSize: Number of bytes to read from each pointer found.
@type context: dict( str S{->} int )
@param context: (Optional)
Dictionary mapping register names to their values.
If not given, the current thread context will be used.
@rtype: dict( str S{->} str )
@return: Dictionary mapping register names to the data they point to.
"""
peekable_registers = (
'Eax', 'Ebx', 'Ecx', 'Edx', 'Esi', 'Edi', 'Ebp'
)
if not context:
context = self.get_context(win32.CONTEXT_CONTROL | \
win32.CONTEXT_INTEGER)
aProcess = self.get_process()
data = dict()
for (reg_name, reg_value) in compat.iteritems(context):
if reg_name not in peekable_registers:
continue
## if reg_name == 'Ebp':
## stack_begin, stack_end = self.get_stack_range()
## print hex(stack_end), hex(reg_value), hex(stack_begin)
## if stack_begin and stack_end and stack_end < stack_begin and \
## stack_begin <= reg_value <= stack_end:
## continue
reg_data = aProcess.peek(reg_value, peekSize)
if reg_data:
data[reg_name] = reg_data
return data | [
"def",
"peek_pointers_in_registers",
"(",
"self",
",",
"peekSize",
"=",
"16",
",",
"context",
"=",
"None",
")",
":",
"peekable_registers",
"=",
"(",
"'Eax'",
",",
"'Ebx'",
",",
"'Ecx'",
",",
"'Edx'",
",",
"'Esi'",
",",
"'Edi'",
",",
"'Ebp'",
")",
"if",
... | Tries to guess which values in the registers are valid pointers,
and reads some data from them.
@type peekSize: int
@param peekSize: Number of bytes to read from each pointer found.
@type context: dict( str S{->} int )
@param context: (Optional)
Dictionary mapping register names to their values.
If not given, the current thread context will be used.
@rtype: dict( str S{->} str )
@return: Dictionary mapping register names to the data they point to. | [
"Tries",
"to",
"guess",
"which",
"values",
"in",
"the",
"registers",
"are",
"valid",
"pointers",
"and",
"reads",
"some",
"data",
"from",
"them",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/thread.py#L1529-L1565 | train | 209,605 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/thread.py | _ThreadContainer.find_threads_by_name | def find_threads_by_name(self, name, bExactMatch = True):
"""
Find threads by name, using different search methods.
@type name: str, None
@param name: Name to look for. Use C{None} to find nameless threads.
@type bExactMatch: bool
@param bExactMatch: C{True} if the name must be
B{exactly} as given, C{False} if the name can be
loosely matched.
This parameter is ignored when C{name} is C{None}.
@rtype: list( L{Thread} )
@return: All threads matching the given name.
"""
found_threads = list()
# Find threads with no name.
if name is None:
for aThread in self.iter_threads():
if aThread.get_name() is None:
found_threads.append(aThread)
# Find threads matching the given name exactly.
elif bExactMatch:
for aThread in self.iter_threads():
if aThread.get_name() == name:
found_threads.append(aThread)
# Find threads whose names match the given substring.
else:
for aThread in self.iter_threads():
t_name = aThread.get_name()
if t_name is not None and name in t_name:
found_threads.append(aThread)
return found_threads | python | def find_threads_by_name(self, name, bExactMatch = True):
"""
Find threads by name, using different search methods.
@type name: str, None
@param name: Name to look for. Use C{None} to find nameless threads.
@type bExactMatch: bool
@param bExactMatch: C{True} if the name must be
B{exactly} as given, C{False} if the name can be
loosely matched.
This parameter is ignored when C{name} is C{None}.
@rtype: list( L{Thread} )
@return: All threads matching the given name.
"""
found_threads = list()
# Find threads with no name.
if name is None:
for aThread in self.iter_threads():
if aThread.get_name() is None:
found_threads.append(aThread)
# Find threads matching the given name exactly.
elif bExactMatch:
for aThread in self.iter_threads():
if aThread.get_name() == name:
found_threads.append(aThread)
# Find threads whose names match the given substring.
else:
for aThread in self.iter_threads():
t_name = aThread.get_name()
if t_name is not None and name in t_name:
found_threads.append(aThread)
return found_threads | [
"def",
"find_threads_by_name",
"(",
"self",
",",
"name",
",",
"bExactMatch",
"=",
"True",
")",
":",
"found_threads",
"=",
"list",
"(",
")",
"# Find threads with no name.",
"if",
"name",
"is",
"None",
":",
"for",
"aThread",
"in",
"self",
".",
"iter_threads",
... | Find threads by name, using different search methods.
@type name: str, None
@param name: Name to look for. Use C{None} to find nameless threads.
@type bExactMatch: bool
@param bExactMatch: C{True} if the name must be
B{exactly} as given, C{False} if the name can be
loosely matched.
This parameter is ignored when C{name} is C{None}.
@rtype: list( L{Thread} )
@return: All threads matching the given name. | [
"Find",
"threads",
"by",
"name",
"using",
"different",
"search",
"methods",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/thread.py#L1835-L1873 | train | 209,606 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/thread.py | _ThreadContainer.start_thread | def start_thread(self, lpStartAddress, lpParameter=0, bSuspended = False):
"""
Remotely creates a new thread in the process.
@type lpStartAddress: int
@param lpStartAddress: Start address for the new thread.
@type lpParameter: int
@param lpParameter: Optional argument for the new thread.
@type bSuspended: bool
@param bSuspended: C{True} if the new thread should be suspended.
In that case use L{Thread.resume} to start execution.
"""
if bSuspended:
dwCreationFlags = win32.CREATE_SUSPENDED
else:
dwCreationFlags = 0
hProcess = self.get_handle( win32.PROCESS_CREATE_THREAD |
win32.PROCESS_QUERY_INFORMATION |
win32.PROCESS_VM_OPERATION |
win32.PROCESS_VM_WRITE |
win32.PROCESS_VM_READ )
hThread, dwThreadId = win32.CreateRemoteThread(
hProcess, 0, 0, lpStartAddress, lpParameter, dwCreationFlags)
aThread = Thread(dwThreadId, hThread, self)
self._add_thread(aThread)
return aThread | python | def start_thread(self, lpStartAddress, lpParameter=0, bSuspended = False):
"""
Remotely creates a new thread in the process.
@type lpStartAddress: int
@param lpStartAddress: Start address for the new thread.
@type lpParameter: int
@param lpParameter: Optional argument for the new thread.
@type bSuspended: bool
@param bSuspended: C{True} if the new thread should be suspended.
In that case use L{Thread.resume} to start execution.
"""
if bSuspended:
dwCreationFlags = win32.CREATE_SUSPENDED
else:
dwCreationFlags = 0
hProcess = self.get_handle( win32.PROCESS_CREATE_THREAD |
win32.PROCESS_QUERY_INFORMATION |
win32.PROCESS_VM_OPERATION |
win32.PROCESS_VM_WRITE |
win32.PROCESS_VM_READ )
hThread, dwThreadId = win32.CreateRemoteThread(
hProcess, 0, 0, lpStartAddress, lpParameter, dwCreationFlags)
aThread = Thread(dwThreadId, hThread, self)
self._add_thread(aThread)
return aThread | [
"def",
"start_thread",
"(",
"self",
",",
"lpStartAddress",
",",
"lpParameter",
"=",
"0",
",",
"bSuspended",
"=",
"False",
")",
":",
"if",
"bSuspended",
":",
"dwCreationFlags",
"=",
"win32",
".",
"CREATE_SUSPENDED",
"else",
":",
"dwCreationFlags",
"=",
"0",
"... | Remotely creates a new thread in the process.
@type lpStartAddress: int
@param lpStartAddress: Start address for the new thread.
@type lpParameter: int
@param lpParameter: Optional argument for the new thread.
@type bSuspended: bool
@param bSuspended: C{True} if the new thread should be suspended.
In that case use L{Thread.resume} to start execution. | [
"Remotely",
"creates",
"a",
"new",
"thread",
"in",
"the",
"process",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/thread.py#L1892-L1919 | train | 209,607 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/thread.py | _ThreadContainer.scan_threads | def scan_threads(self):
"""
Populates the snapshot with running threads.
"""
# Ignore special process IDs.
# PID 0: System Idle Process. Also has a special meaning to the
# toolhelp APIs (current process).
# PID 4: System Integrity Group. See this forum post for more info:
# http://tinyurl.com/ycza8jo
# (points to social.technet.microsoft.com)
# Only on XP and above
# PID 8: System (?) only in Windows 2000 and below AFAIK.
# It's probably the same as PID 4 in XP and above.
dwProcessId = self.get_pid()
if dwProcessId in (0, 4, 8):
return
## dead_tids = set( self.get_thread_ids() ) # XXX triggers a scan
dead_tids = self._get_thread_ids()
dwProcessId = self.get_pid()
hSnapshot = win32.CreateToolhelp32Snapshot(win32.TH32CS_SNAPTHREAD,
dwProcessId)
try:
te = win32.Thread32First(hSnapshot)
while te is not None:
if te.th32OwnerProcessID == dwProcessId:
dwThreadId = te.th32ThreadID
if dwThreadId in dead_tids:
dead_tids.remove(dwThreadId)
## if not self.has_thread(dwThreadId): # XXX triggers a scan
if not self._has_thread_id(dwThreadId):
aThread = Thread(dwThreadId, process = self)
self._add_thread(aThread)
te = win32.Thread32Next(hSnapshot)
finally:
win32.CloseHandle(hSnapshot)
for tid in dead_tids:
self._del_thread(tid) | python | def scan_threads(self):
"""
Populates the snapshot with running threads.
"""
# Ignore special process IDs.
# PID 0: System Idle Process. Also has a special meaning to the
# toolhelp APIs (current process).
# PID 4: System Integrity Group. See this forum post for more info:
# http://tinyurl.com/ycza8jo
# (points to social.technet.microsoft.com)
# Only on XP and above
# PID 8: System (?) only in Windows 2000 and below AFAIK.
# It's probably the same as PID 4 in XP and above.
dwProcessId = self.get_pid()
if dwProcessId in (0, 4, 8):
return
## dead_tids = set( self.get_thread_ids() ) # XXX triggers a scan
dead_tids = self._get_thread_ids()
dwProcessId = self.get_pid()
hSnapshot = win32.CreateToolhelp32Snapshot(win32.TH32CS_SNAPTHREAD,
dwProcessId)
try:
te = win32.Thread32First(hSnapshot)
while te is not None:
if te.th32OwnerProcessID == dwProcessId:
dwThreadId = te.th32ThreadID
if dwThreadId in dead_tids:
dead_tids.remove(dwThreadId)
## if not self.has_thread(dwThreadId): # XXX triggers a scan
if not self._has_thread_id(dwThreadId):
aThread = Thread(dwThreadId, process = self)
self._add_thread(aThread)
te = win32.Thread32Next(hSnapshot)
finally:
win32.CloseHandle(hSnapshot)
for tid in dead_tids:
self._del_thread(tid) | [
"def",
"scan_threads",
"(",
"self",
")",
":",
"# Ignore special process IDs.",
"# PID 0: System Idle Process. Also has a special meaning to the",
"# toolhelp APIs (current process).",
"# PID 4: System Integrity Group. See this forum post for more info:",
"# http://tinyurl.com/ycza8... | Populates the snapshot with running threads. | [
"Populates",
"the",
"snapshot",
"with",
"running",
"threads",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/thread.py#L1927-L1965 | train | 209,608 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/thread.py | _ThreadContainer.clear_dead_threads | def clear_dead_threads(self):
"""
Remove Thread objects from the snapshot
referring to threads no longer running.
"""
for tid in self.get_thread_ids():
aThread = self.get_thread(tid)
if not aThread.is_alive():
self._del_thread(aThread) | python | def clear_dead_threads(self):
"""
Remove Thread objects from the snapshot
referring to threads no longer running.
"""
for tid in self.get_thread_ids():
aThread = self.get_thread(tid)
if not aThread.is_alive():
self._del_thread(aThread) | [
"def",
"clear_dead_threads",
"(",
"self",
")",
":",
"for",
"tid",
"in",
"self",
".",
"get_thread_ids",
"(",
")",
":",
"aThread",
"=",
"self",
".",
"get_thread",
"(",
"tid",
")",
"if",
"not",
"aThread",
".",
"is_alive",
"(",
")",
":",
"self",
".",
"_d... | Remove Thread objects from the snapshot
referring to threads no longer running. | [
"Remove",
"Thread",
"objects",
"from",
"the",
"snapshot",
"referring",
"to",
"threads",
"no",
"longer",
"running",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/thread.py#L1967-L1975 | train | 209,609 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/thread.py | _ThreadContainer.clear_threads | def clear_threads(self):
"""
Clears the threads snapshot.
"""
for aThread in compat.itervalues(self.__threadDict):
aThread.clear()
self.__threadDict = dict() | python | def clear_threads(self):
"""
Clears the threads snapshot.
"""
for aThread in compat.itervalues(self.__threadDict):
aThread.clear()
self.__threadDict = dict() | [
"def",
"clear_threads",
"(",
"self",
")",
":",
"for",
"aThread",
"in",
"compat",
".",
"itervalues",
"(",
"self",
".",
"__threadDict",
")",
":",
"aThread",
".",
"clear",
"(",
")",
"self",
".",
"__threadDict",
"=",
"dict",
"(",
")"
] | Clears the threads snapshot. | [
"Clears",
"the",
"threads",
"snapshot",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/thread.py#L1977-L1983 | train | 209,610 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/thread.py | _ThreadContainer.close_thread_handles | def close_thread_handles(self):
"""
Closes all open handles to threads in the snapshot.
"""
for aThread in self.iter_threads():
try:
aThread.close_handle()
except Exception:
try:
e = sys.exc_info()[1]
msg = "Cannot close thread handle %s, reason: %s"
msg %= (aThread.hThread.value, str(e))
warnings.warn(msg)
except Exception:
pass | python | def close_thread_handles(self):
"""
Closes all open handles to threads in the snapshot.
"""
for aThread in self.iter_threads():
try:
aThread.close_handle()
except Exception:
try:
e = sys.exc_info()[1]
msg = "Cannot close thread handle %s, reason: %s"
msg %= (aThread.hThread.value, str(e))
warnings.warn(msg)
except Exception:
pass | [
"def",
"close_thread_handles",
"(",
"self",
")",
":",
"for",
"aThread",
"in",
"self",
".",
"iter_threads",
"(",
")",
":",
"try",
":",
"aThread",
".",
"close_handle",
"(",
")",
"except",
"Exception",
":",
"try",
":",
"e",
"=",
"sys",
".",
"exc_info",
"(... | Closes all open handles to threads in the snapshot. | [
"Closes",
"all",
"open",
"handles",
"to",
"threads",
"in",
"the",
"snapshot",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/thread.py#L1985-L1999 | train | 209,611 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/thread.py | _ThreadContainer._add_thread | def _add_thread(self, aThread):
"""
Private method to add a thread object to the snapshot.
@type aThread: L{Thread}
@param aThread: Thread object.
"""
## if not isinstance(aThread, Thread):
## if hasattr(aThread, '__class__'):
## typename = aThread.__class__.__name__
## else:
## typename = str(type(aThread))
## msg = "Expected Thread, got %s instead" % typename
## raise TypeError(msg)
dwThreadId = aThread.dwThreadId
## if dwThreadId in self.__threadDict:
## msg = "Already have a Thread object with ID %d" % dwThreadId
## raise KeyError(msg)
aThread.set_process(self)
self.__threadDict[dwThreadId] = aThread | python | def _add_thread(self, aThread):
"""
Private method to add a thread object to the snapshot.
@type aThread: L{Thread}
@param aThread: Thread object.
"""
## if not isinstance(aThread, Thread):
## if hasattr(aThread, '__class__'):
## typename = aThread.__class__.__name__
## else:
## typename = str(type(aThread))
## msg = "Expected Thread, got %s instead" % typename
## raise TypeError(msg)
dwThreadId = aThread.dwThreadId
## if dwThreadId in self.__threadDict:
## msg = "Already have a Thread object with ID %d" % dwThreadId
## raise KeyError(msg)
aThread.set_process(self)
self.__threadDict[dwThreadId] = aThread | [
"def",
"_add_thread",
"(",
"self",
",",
"aThread",
")",
":",
"## if not isinstance(aThread, Thread):",
"## if hasattr(aThread, '__class__'):",
"## typename = aThread.__class__.__name__",
"## else:",
"## typename = str(type(aThread))"... | Private method to add a thread object to the snapshot.
@type aThread: L{Thread}
@param aThread: Thread object. | [
"Private",
"method",
"to",
"add",
"a",
"thread",
"object",
"to",
"the",
"snapshot",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/thread.py#L2005-L2024 | train | 209,612 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/thread.py | _ThreadContainer._del_thread | def _del_thread(self, dwThreadId):
"""
Private method to remove a thread object from the snapshot.
@type dwThreadId: int
@param dwThreadId: Global thread ID.
"""
try:
aThread = self.__threadDict[dwThreadId]
del self.__threadDict[dwThreadId]
except KeyError:
aThread = None
msg = "Unknown thread ID %d" % dwThreadId
warnings.warn(msg, RuntimeWarning)
if aThread:
aThread.clear() | python | def _del_thread(self, dwThreadId):
"""
Private method to remove a thread object from the snapshot.
@type dwThreadId: int
@param dwThreadId: Global thread ID.
"""
try:
aThread = self.__threadDict[dwThreadId]
del self.__threadDict[dwThreadId]
except KeyError:
aThread = None
msg = "Unknown thread ID %d" % dwThreadId
warnings.warn(msg, RuntimeWarning)
if aThread:
aThread.clear() | [
"def",
"_del_thread",
"(",
"self",
",",
"dwThreadId",
")",
":",
"try",
":",
"aThread",
"=",
"self",
".",
"__threadDict",
"[",
"dwThreadId",
"]",
"del",
"self",
".",
"__threadDict",
"[",
"dwThreadId",
"]",
"except",
"KeyError",
":",
"aThread",
"=",
"None",
... | Private method to remove a thread object from the snapshot.
@type dwThreadId: int
@param dwThreadId: Global thread ID. | [
"Private",
"method",
"to",
"remove",
"a",
"thread",
"object",
"from",
"the",
"snapshot",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/thread.py#L2026-L2041 | train | 209,613 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/thread.py | _ThreadContainer.__add_created_thread | def __add_created_thread(self, event):
"""
Private method to automatically add new thread objects from debug events.
@type event: L{Event}
@param event: Event object.
"""
dwThreadId = event.get_tid()
hThread = event.get_thread_handle()
## if not self.has_thread(dwThreadId): # XXX this would trigger a scan
if not self._has_thread_id(dwThreadId):
aThread = Thread(dwThreadId, hThread, self)
teb_ptr = event.get_teb() # remember the TEB pointer
if teb_ptr:
aThread._teb_ptr = teb_ptr
self._add_thread(aThread) | python | def __add_created_thread(self, event):
"""
Private method to automatically add new thread objects from debug events.
@type event: L{Event}
@param event: Event object.
"""
dwThreadId = event.get_tid()
hThread = event.get_thread_handle()
## if not self.has_thread(dwThreadId): # XXX this would trigger a scan
if not self._has_thread_id(dwThreadId):
aThread = Thread(dwThreadId, hThread, self)
teb_ptr = event.get_teb() # remember the TEB pointer
if teb_ptr:
aThread._teb_ptr = teb_ptr
self._add_thread(aThread) | [
"def",
"__add_created_thread",
"(",
"self",
",",
"event",
")",
":",
"dwThreadId",
"=",
"event",
".",
"get_tid",
"(",
")",
"hThread",
"=",
"event",
".",
"get_thread_handle",
"(",
")",
"## if not self.has_thread(dwThreadId): # XXX this would trigger a scan",
"if"... | Private method to automatically add new thread objects from debug events.
@type event: L{Event}
@param event: Event object. | [
"Private",
"method",
"to",
"automatically",
"add",
"new",
"thread",
"objects",
"from",
"debug",
"events",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/thread.py#L2057-L2072 | train | 209,614 |
fabioz/PyDev.Debugger | _pydevd_frame_eval/pydevd_modify_bytecode.py | _add_attr_values_from_insert_to_original | def _add_attr_values_from_insert_to_original(original_code, insert_code, insert_code_list, attribute_name, op_list):
"""
This function appends values of the attribute `attribute_name` of the inserted code to the original values,
and changes indexes inside inserted code. If some bytecode instruction in the inserted code used to call argument
number i, after modification it calls argument n + i, where n - length of the values in the original code.
So it helps to avoid variables mixing between two pieces of code.
:param original_code: code to modify
:param insert_code: code to insert
:param insert_code_obj: bytes sequence of inserted code, which should be modified too
:param attribute_name: name of attribute to modify ('co_names', 'co_consts' or 'co_varnames')
:param op_list: sequence of bytecodes whose arguments should be changed
:return: modified bytes sequence of the code to insert and new values of the attribute `attribute_name` for
original code
"""
orig_value = getattr(original_code, attribute_name)
insert_value = getattr(insert_code, attribute_name)
orig_names_len = len(orig_value)
code_with_new_values = list(insert_code_list)
offset = 0
while offset < len(code_with_new_values):
op = code_with_new_values[offset]
if op in op_list:
new_val = code_with_new_values[offset + 1] + orig_names_len
if new_val > MAX_BYTE:
code_with_new_values[offset + 1] = new_val & MAX_BYTE
code_with_new_values = code_with_new_values[:offset] + [EXTENDED_ARG, new_val >> 8] + \
code_with_new_values[offset:]
offset += 2
else:
code_with_new_values[offset + 1] = new_val
offset += 2
new_values = orig_value + insert_value
return bytes(code_with_new_values), new_values | python | def _add_attr_values_from_insert_to_original(original_code, insert_code, insert_code_list, attribute_name, op_list):
"""
This function appends values of the attribute `attribute_name` of the inserted code to the original values,
and changes indexes inside inserted code. If some bytecode instruction in the inserted code used to call argument
number i, after modification it calls argument n + i, where n - length of the values in the original code.
So it helps to avoid variables mixing between two pieces of code.
:param original_code: code to modify
:param insert_code: code to insert
:param insert_code_obj: bytes sequence of inserted code, which should be modified too
:param attribute_name: name of attribute to modify ('co_names', 'co_consts' or 'co_varnames')
:param op_list: sequence of bytecodes whose arguments should be changed
:return: modified bytes sequence of the code to insert and new values of the attribute `attribute_name` for
original code
"""
orig_value = getattr(original_code, attribute_name)
insert_value = getattr(insert_code, attribute_name)
orig_names_len = len(orig_value)
code_with_new_values = list(insert_code_list)
offset = 0
while offset < len(code_with_new_values):
op = code_with_new_values[offset]
if op in op_list:
new_val = code_with_new_values[offset + 1] + orig_names_len
if new_val > MAX_BYTE:
code_with_new_values[offset + 1] = new_val & MAX_BYTE
code_with_new_values = code_with_new_values[:offset] + [EXTENDED_ARG, new_val >> 8] + \
code_with_new_values[offset:]
offset += 2
else:
code_with_new_values[offset + 1] = new_val
offset += 2
new_values = orig_value + insert_value
return bytes(code_with_new_values), new_values | [
"def",
"_add_attr_values_from_insert_to_original",
"(",
"original_code",
",",
"insert_code",
",",
"insert_code_list",
",",
"attribute_name",
",",
"op_list",
")",
":",
"orig_value",
"=",
"getattr",
"(",
"original_code",
",",
"attribute_name",
")",
"insert_value",
"=",
... | This function appends values of the attribute `attribute_name` of the inserted code to the original values,
and changes indexes inside inserted code. If some bytecode instruction in the inserted code used to call argument
number i, after modification it calls argument n + i, where n - length of the values in the original code.
So it helps to avoid variables mixing between two pieces of code.
:param original_code: code to modify
:param insert_code: code to insert
:param insert_code_obj: bytes sequence of inserted code, which should be modified too
:param attribute_name: name of attribute to modify ('co_names', 'co_consts' or 'co_varnames')
:param op_list: sequence of bytecodes whose arguments should be changed
:return: modified bytes sequence of the code to insert and new values of the attribute `attribute_name` for
original code | [
"This",
"function",
"appends",
"values",
"of",
"the",
"attribute",
"attribute_name",
"of",
"the",
"inserted",
"code",
"to",
"the",
"original",
"values",
"and",
"changes",
"indexes",
"inside",
"inserted",
"code",
".",
"If",
"some",
"bytecode",
"instruction",
"in"... | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_frame_eval/pydevd_modify_bytecode.py#L10-L43 | train | 209,615 |
fabioz/PyDev.Debugger | _pydevd_frame_eval/pydevd_modify_bytecode.py | _insert_code | def _insert_code(code_to_modify, code_to_insert, before_line):
"""
Insert piece of code `code_to_insert` to `code_to_modify` right inside the line `before_line` before the
instruction on this line by modifying original bytecode
:param code_to_modify: Code to modify
:param code_to_insert: Code to insert
:param before_line: Number of line for code insertion
:return: boolean flag whether insertion was successful, modified code
"""
linestarts = dict(dis.findlinestarts(code_to_modify))
if not linestarts:
return False, code_to_modify
if code_to_modify.co_name == '<module>':
# There's a peculiarity here: if a breakpoint is added in the first line of a module, we
# can't replace the code because we require a line event to stop and the line event
# was already generated, so, fallback to tracing.
if before_line == min(linestarts.values()):
return False, code_to_modify
if before_line not in linestarts.values():
return False, code_to_modify
offset = None
for off, line_no in linestarts.items():
if line_no == before_line:
offset = off
break
code_to_insert_list = add_jump_instruction(offset, code_to_insert)
try:
code_to_insert_list, new_names = \
_add_attr_values_from_insert_to_original(code_to_modify, code_to_insert, code_to_insert_list, 'co_names',
dis.hasname)
code_to_insert_list, new_consts = \
_add_attr_values_from_insert_to_original(code_to_modify, code_to_insert, code_to_insert_list, 'co_consts',
[opmap['LOAD_CONST']])
code_to_insert_list, new_vars = \
_add_attr_values_from_insert_to_original(code_to_modify, code_to_insert, code_to_insert_list, 'co_varnames',
dis.haslocal)
new_bytes, all_inserted_code = _update_label_offsets(code_to_modify.co_code, offset, list(code_to_insert_list))
new_lnotab = _modify_new_lines(code_to_modify, offset, code_to_insert_list)
if new_lnotab is None:
return False, code_to_modify
except ValueError:
pydev_log.exception()
return False, code_to_modify
new_code = CodeType(
code_to_modify.co_argcount, # integer
code_to_modify.co_kwonlyargcount, # integer
len(new_vars), # integer
code_to_modify.co_stacksize, # integer
code_to_modify.co_flags, # integer
new_bytes, # bytes
new_consts, # tuple
new_names, # tuple
new_vars, # tuple
code_to_modify.co_filename, # string
code_to_modify.co_name, # string
code_to_modify.co_firstlineno, # integer
new_lnotab, # bytes
code_to_modify.co_freevars, # tuple
code_to_modify.co_cellvars # tuple
)
return True, new_code | python | def _insert_code(code_to_modify, code_to_insert, before_line):
"""
Insert piece of code `code_to_insert` to `code_to_modify` right inside the line `before_line` before the
instruction on this line by modifying original bytecode
:param code_to_modify: Code to modify
:param code_to_insert: Code to insert
:param before_line: Number of line for code insertion
:return: boolean flag whether insertion was successful, modified code
"""
linestarts = dict(dis.findlinestarts(code_to_modify))
if not linestarts:
return False, code_to_modify
if code_to_modify.co_name == '<module>':
# There's a peculiarity here: if a breakpoint is added in the first line of a module, we
# can't replace the code because we require a line event to stop and the line event
# was already generated, so, fallback to tracing.
if before_line == min(linestarts.values()):
return False, code_to_modify
if before_line not in linestarts.values():
return False, code_to_modify
offset = None
for off, line_no in linestarts.items():
if line_no == before_line:
offset = off
break
code_to_insert_list = add_jump_instruction(offset, code_to_insert)
try:
code_to_insert_list, new_names = \
_add_attr_values_from_insert_to_original(code_to_modify, code_to_insert, code_to_insert_list, 'co_names',
dis.hasname)
code_to_insert_list, new_consts = \
_add_attr_values_from_insert_to_original(code_to_modify, code_to_insert, code_to_insert_list, 'co_consts',
[opmap['LOAD_CONST']])
code_to_insert_list, new_vars = \
_add_attr_values_from_insert_to_original(code_to_modify, code_to_insert, code_to_insert_list, 'co_varnames',
dis.haslocal)
new_bytes, all_inserted_code = _update_label_offsets(code_to_modify.co_code, offset, list(code_to_insert_list))
new_lnotab = _modify_new_lines(code_to_modify, offset, code_to_insert_list)
if new_lnotab is None:
return False, code_to_modify
except ValueError:
pydev_log.exception()
return False, code_to_modify
new_code = CodeType(
code_to_modify.co_argcount, # integer
code_to_modify.co_kwonlyargcount, # integer
len(new_vars), # integer
code_to_modify.co_stacksize, # integer
code_to_modify.co_flags, # integer
new_bytes, # bytes
new_consts, # tuple
new_names, # tuple
new_vars, # tuple
code_to_modify.co_filename, # string
code_to_modify.co_name, # string
code_to_modify.co_firstlineno, # integer
new_lnotab, # bytes
code_to_modify.co_freevars, # tuple
code_to_modify.co_cellvars # tuple
)
return True, new_code | [
"def",
"_insert_code",
"(",
"code_to_modify",
",",
"code_to_insert",
",",
"before_line",
")",
":",
"linestarts",
"=",
"dict",
"(",
"dis",
".",
"findlinestarts",
"(",
"code_to_modify",
")",
")",
"if",
"not",
"linestarts",
":",
"return",
"False",
",",
"code_to_m... | Insert piece of code `code_to_insert` to `code_to_modify` right inside the line `before_line` before the
instruction on this line by modifying original bytecode
:param code_to_modify: Code to modify
:param code_to_insert: Code to insert
:param before_line: Number of line for code insertion
:return: boolean flag whether insertion was successful, modified code | [
"Insert",
"piece",
"of",
"code",
"code_to_insert",
"to",
"code_to_modify",
"right",
"inside",
"the",
"line",
"before_line",
"before",
"the",
"instruction",
"on",
"this",
"line",
"by",
"modifying",
"original",
"bytecode"
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_frame_eval/pydevd_modify_bytecode.py#L222-L290 | train | 209,616 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/window.py | Window.set_thread | def set_thread(self, thread = None):
"""
Manually set the thread process. Use with care!
@type thread: L{Thread}
@param thread: (Optional) Thread object. Use C{None} to autodetect.
"""
if thread is None:
self.__thread = None
else:
self.__load_Thread_class()
if not isinstance(thread, Thread):
msg = "Parent thread must be a Thread instance, "
msg += "got %s instead" % type(thread)
raise TypeError(msg)
self.dwThreadId = thread.get_tid()
self.__thread = thread | python | def set_thread(self, thread = None):
"""
Manually set the thread process. Use with care!
@type thread: L{Thread}
@param thread: (Optional) Thread object. Use C{None} to autodetect.
"""
if thread is None:
self.__thread = None
else:
self.__load_Thread_class()
if not isinstance(thread, Thread):
msg = "Parent thread must be a Thread instance, "
msg += "got %s instead" % type(thread)
raise TypeError(msg)
self.dwThreadId = thread.get_tid()
self.__thread = thread | [
"def",
"set_thread",
"(",
"self",
",",
"thread",
"=",
"None",
")",
":",
"if",
"thread",
"is",
"None",
":",
"self",
".",
"__thread",
"=",
"None",
"else",
":",
"self",
".",
"__load_Thread_class",
"(",
")",
"if",
"not",
"isinstance",
"(",
"thread",
",",
... | Manually set the thread process. Use with care!
@type thread: L{Thread}
@param thread: (Optional) Thread object. Use C{None} to autodetect. | [
"Manually",
"set",
"the",
"thread",
"process",
".",
"Use",
"with",
"care!"
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/window.py#L233-L249 | train | 209,617 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/window.py | Window.__get_window | def __get_window(self, hWnd):
"""
User internally to get another Window from this one.
It'll try to copy the parent Process and Thread references if possible.
"""
window = Window(hWnd)
if window.get_pid() == self.get_pid():
window.set_process( self.get_process() )
if window.get_tid() == self.get_tid():
window.set_thread( self.get_thread() )
return window | python | def __get_window(self, hWnd):
"""
User internally to get another Window from this one.
It'll try to copy the parent Process and Thread references if possible.
"""
window = Window(hWnd)
if window.get_pid() == self.get_pid():
window.set_process( self.get_process() )
if window.get_tid() == self.get_tid():
window.set_thread( self.get_thread() )
return window | [
"def",
"__get_window",
"(",
"self",
",",
"hWnd",
")",
":",
"window",
"=",
"Window",
"(",
"hWnd",
")",
"if",
"window",
".",
"get_pid",
"(",
")",
"==",
"self",
".",
"get_pid",
"(",
")",
":",
"window",
".",
"set_process",
"(",
"self",
".",
"get_process"... | User internally to get another Window from this one.
It'll try to copy the parent Process and Thread references if possible. | [
"User",
"internally",
"to",
"get",
"another",
"Window",
"from",
"this",
"one",
".",
"It",
"ll",
"try",
"to",
"copy",
"the",
"parent",
"Process",
"and",
"Thread",
"references",
"if",
"possible",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/window.py#L251-L261 | train | 209,618 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/window.py | Window.get_client_rect | def get_client_rect(self):
"""
Get the window's client area coordinates in the desktop.
@rtype: L{win32.Rect}
@return: Rectangle occupied by the window's client area in the desktop.
@raise WindowsError: An error occured while processing this request.
"""
cr = win32.GetClientRect( self.get_handle() )
cr.left, cr.top = self.client_to_screen(cr.left, cr.top)
cr.right, cr.bottom = self.client_to_screen(cr.right, cr.bottom)
return cr | python | def get_client_rect(self):
"""
Get the window's client area coordinates in the desktop.
@rtype: L{win32.Rect}
@return: Rectangle occupied by the window's client area in the desktop.
@raise WindowsError: An error occured while processing this request.
"""
cr = win32.GetClientRect( self.get_handle() )
cr.left, cr.top = self.client_to_screen(cr.left, cr.top)
cr.right, cr.bottom = self.client_to_screen(cr.right, cr.bottom)
return cr | [
"def",
"get_client_rect",
"(",
"self",
")",
":",
"cr",
"=",
"win32",
".",
"GetClientRect",
"(",
"self",
".",
"get_handle",
"(",
")",
")",
"cr",
".",
"left",
",",
"cr",
".",
"top",
"=",
"self",
".",
"client_to_screen",
"(",
"cr",
".",
"left",
",",
"... | Get the window's client area coordinates in the desktop.
@rtype: L{win32.Rect}
@return: Rectangle occupied by the window's client area in the desktop.
@raise WindowsError: An error occured while processing this request. | [
"Get",
"the",
"window",
"s",
"client",
"area",
"coordinates",
"in",
"the",
"desktop",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/window.py#L353-L365 | train | 209,619 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/window.py | Window.get_child_at | def get_child_at(self, x, y, bAllowTransparency = True):
"""
Get the child window located at the given coordinates. If no such
window exists an exception is raised.
@see: L{get_children}
@type x: int
@param x: Horizontal coordinate.
@type y: int
@param y: Vertical coordinate.
@type bAllowTransparency: bool
@param bAllowTransparency: If C{True} transparent areas in windows are
ignored, returning the window behind them. If C{False} transparent
areas are treated just like any other area.
@rtype: L{Window}
@return: Child window at the requested position, or C{None} if there
is no window at those coordinates.
"""
try:
if bAllowTransparency:
hWnd = win32.RealChildWindowFromPoint( self.get_handle(), (x, y) )
else:
hWnd = win32.ChildWindowFromPoint( self.get_handle(), (x, y) )
if hWnd:
return self.__get_window(hWnd)
except WindowsError:
pass
return None | python | def get_child_at(self, x, y, bAllowTransparency = True):
"""
Get the child window located at the given coordinates. If no such
window exists an exception is raised.
@see: L{get_children}
@type x: int
@param x: Horizontal coordinate.
@type y: int
@param y: Vertical coordinate.
@type bAllowTransparency: bool
@param bAllowTransparency: If C{True} transparent areas in windows are
ignored, returning the window behind them. If C{False} transparent
areas are treated just like any other area.
@rtype: L{Window}
@return: Child window at the requested position, or C{None} if there
is no window at those coordinates.
"""
try:
if bAllowTransparency:
hWnd = win32.RealChildWindowFromPoint( self.get_handle(), (x, y) )
else:
hWnd = win32.ChildWindowFromPoint( self.get_handle(), (x, y) )
if hWnd:
return self.__get_window(hWnd)
except WindowsError:
pass
return None | [
"def",
"get_child_at",
"(",
"self",
",",
"x",
",",
"y",
",",
"bAllowTransparency",
"=",
"True",
")",
":",
"try",
":",
"if",
"bAllowTransparency",
":",
"hWnd",
"=",
"win32",
".",
"RealChildWindowFromPoint",
"(",
"self",
".",
"get_handle",
"(",
")",
",",
"... | Get the child window located at the given coordinates. If no such
window exists an exception is raised.
@see: L{get_children}
@type x: int
@param x: Horizontal coordinate.
@type y: int
@param y: Vertical coordinate.
@type bAllowTransparency: bool
@param bAllowTransparency: If C{True} transparent areas in windows are
ignored, returning the window behind them. If C{False} transparent
areas are treated just like any other area.
@rtype: L{Window}
@return: Child window at the requested position, or C{None} if there
is no window at those coordinates. | [
"Get",
"the",
"child",
"window",
"located",
"at",
"the",
"given",
"coordinates",
".",
"If",
"no",
"such",
"window",
"exists",
"an",
"exception",
"is",
"raised",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/window.py#L483-L514 | train | 209,620 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/window.py | Window.show | def show(self, bAsync = True):
"""
Make the window visible.
@see: L{hide}
@type bAsync: bool
@param bAsync: Perform the request asynchronously.
@raise WindowsError: An error occured while processing this request.
"""
if bAsync:
win32.ShowWindowAsync( self.get_handle(), win32.SW_SHOW )
else:
win32.ShowWindow( self.get_handle(), win32.SW_SHOW ) | python | def show(self, bAsync = True):
"""
Make the window visible.
@see: L{hide}
@type bAsync: bool
@param bAsync: Perform the request asynchronously.
@raise WindowsError: An error occured while processing this request.
"""
if bAsync:
win32.ShowWindowAsync( self.get_handle(), win32.SW_SHOW )
else:
win32.ShowWindow( self.get_handle(), win32.SW_SHOW ) | [
"def",
"show",
"(",
"self",
",",
"bAsync",
"=",
"True",
")",
":",
"if",
"bAsync",
":",
"win32",
".",
"ShowWindowAsync",
"(",
"self",
".",
"get_handle",
"(",
")",
",",
"win32",
".",
"SW_SHOW",
")",
"else",
":",
"win32",
".",
"ShowWindow",
"(",
"self",... | Make the window visible.
@see: L{hide}
@type bAsync: bool
@param bAsync: Perform the request asynchronously.
@raise WindowsError: An error occured while processing this request. | [
"Make",
"the",
"window",
"visible",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/window.py#L590-L604 | train | 209,621 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/window.py | Window.hide | def hide(self, bAsync = True):
"""
Make the window invisible.
@see: L{show}
@type bAsync: bool
@param bAsync: Perform the request asynchronously.
@raise WindowsError: An error occured while processing this request.
"""
if bAsync:
win32.ShowWindowAsync( self.get_handle(), win32.SW_HIDE )
else:
win32.ShowWindow( self.get_handle(), win32.SW_HIDE ) | python | def hide(self, bAsync = True):
"""
Make the window invisible.
@see: L{show}
@type bAsync: bool
@param bAsync: Perform the request asynchronously.
@raise WindowsError: An error occured while processing this request.
"""
if bAsync:
win32.ShowWindowAsync( self.get_handle(), win32.SW_HIDE )
else:
win32.ShowWindow( self.get_handle(), win32.SW_HIDE ) | [
"def",
"hide",
"(",
"self",
",",
"bAsync",
"=",
"True",
")",
":",
"if",
"bAsync",
":",
"win32",
".",
"ShowWindowAsync",
"(",
"self",
".",
"get_handle",
"(",
")",
",",
"win32",
".",
"SW_HIDE",
")",
"else",
":",
"win32",
".",
"ShowWindow",
"(",
"self",... | Make the window invisible.
@see: L{show}
@type bAsync: bool
@param bAsync: Perform the request asynchronously.
@raise WindowsError: An error occured while processing this request. | [
"Make",
"the",
"window",
"invisible",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/window.py#L606-L620 | train | 209,622 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/window.py | Window.maximize | def maximize(self, bAsync = True):
"""
Maximize the window.
@see: L{minimize}, L{restore}
@type bAsync: bool
@param bAsync: Perform the request asynchronously.
@raise WindowsError: An error occured while processing this request.
"""
if bAsync:
win32.ShowWindowAsync( self.get_handle(), win32.SW_MAXIMIZE )
else:
win32.ShowWindow( self.get_handle(), win32.SW_MAXIMIZE ) | python | def maximize(self, bAsync = True):
"""
Maximize the window.
@see: L{minimize}, L{restore}
@type bAsync: bool
@param bAsync: Perform the request asynchronously.
@raise WindowsError: An error occured while processing this request.
"""
if bAsync:
win32.ShowWindowAsync( self.get_handle(), win32.SW_MAXIMIZE )
else:
win32.ShowWindow( self.get_handle(), win32.SW_MAXIMIZE ) | [
"def",
"maximize",
"(",
"self",
",",
"bAsync",
"=",
"True",
")",
":",
"if",
"bAsync",
":",
"win32",
".",
"ShowWindowAsync",
"(",
"self",
".",
"get_handle",
"(",
")",
",",
"win32",
".",
"SW_MAXIMIZE",
")",
"else",
":",
"win32",
".",
"ShowWindow",
"(",
... | Maximize the window.
@see: L{minimize}, L{restore}
@type bAsync: bool
@param bAsync: Perform the request asynchronously.
@raise WindowsError: An error occured while processing this request. | [
"Maximize",
"the",
"window",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/window.py#L622-L636 | train | 209,623 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/window.py | Window.minimize | def minimize(self, bAsync = True):
"""
Minimize the window.
@see: L{maximize}, L{restore}
@type bAsync: bool
@param bAsync: Perform the request asynchronously.
@raise WindowsError: An error occured while processing this request.
"""
if bAsync:
win32.ShowWindowAsync( self.get_handle(), win32.SW_MINIMIZE )
else:
win32.ShowWindow( self.get_handle(), win32.SW_MINIMIZE ) | python | def minimize(self, bAsync = True):
"""
Minimize the window.
@see: L{maximize}, L{restore}
@type bAsync: bool
@param bAsync: Perform the request asynchronously.
@raise WindowsError: An error occured while processing this request.
"""
if bAsync:
win32.ShowWindowAsync( self.get_handle(), win32.SW_MINIMIZE )
else:
win32.ShowWindow( self.get_handle(), win32.SW_MINIMIZE ) | [
"def",
"minimize",
"(",
"self",
",",
"bAsync",
"=",
"True",
")",
":",
"if",
"bAsync",
":",
"win32",
".",
"ShowWindowAsync",
"(",
"self",
".",
"get_handle",
"(",
")",
",",
"win32",
".",
"SW_MINIMIZE",
")",
"else",
":",
"win32",
".",
"ShowWindow",
"(",
... | Minimize the window.
@see: L{maximize}, L{restore}
@type bAsync: bool
@param bAsync: Perform the request asynchronously.
@raise WindowsError: An error occured while processing this request. | [
"Minimize",
"the",
"window",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/window.py#L638-L652 | train | 209,624 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/window.py | Window.restore | def restore(self, bAsync = True):
"""
Unmaximize and unminimize the window.
@see: L{maximize}, L{minimize}
@type bAsync: bool
@param bAsync: Perform the request asynchronously.
@raise WindowsError: An error occured while processing this request.
"""
if bAsync:
win32.ShowWindowAsync( self.get_handle(), win32.SW_RESTORE )
else:
win32.ShowWindow( self.get_handle(), win32.SW_RESTORE ) | python | def restore(self, bAsync = True):
"""
Unmaximize and unminimize the window.
@see: L{maximize}, L{minimize}
@type bAsync: bool
@param bAsync: Perform the request asynchronously.
@raise WindowsError: An error occured while processing this request.
"""
if bAsync:
win32.ShowWindowAsync( self.get_handle(), win32.SW_RESTORE )
else:
win32.ShowWindow( self.get_handle(), win32.SW_RESTORE ) | [
"def",
"restore",
"(",
"self",
",",
"bAsync",
"=",
"True",
")",
":",
"if",
"bAsync",
":",
"win32",
".",
"ShowWindowAsync",
"(",
"self",
".",
"get_handle",
"(",
")",
",",
"win32",
".",
"SW_RESTORE",
")",
"else",
":",
"win32",
".",
"ShowWindow",
"(",
"... | Unmaximize and unminimize the window.
@see: L{maximize}, L{minimize}
@type bAsync: bool
@param bAsync: Perform the request asynchronously.
@raise WindowsError: An error occured while processing this request. | [
"Unmaximize",
"and",
"unminimize",
"the",
"window",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/window.py#L654-L668 | train | 209,625 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/window.py | Window.send | def send(self, uMsg, wParam = None, lParam = None, dwTimeout = None):
"""
Send a low-level window message syncronically.
@type uMsg: int
@param uMsg: Message code.
@param wParam:
The type and meaning of this parameter depends on the message.
@param lParam:
The type and meaning of this parameter depends on the message.
@param dwTimeout: Optional timeout for the operation.
Use C{None} to wait indefinitely.
@rtype: int
@return: The meaning of the return value depends on the window message.
Typically a value of C{0} means an error occured. You can get the
error code by calling L{win32.GetLastError}.
"""
if dwTimeout is None:
return win32.SendMessage(self.get_handle(), uMsg, wParam, lParam)
return win32.SendMessageTimeout(
self.get_handle(), uMsg, wParam, lParam,
win32.SMTO_ABORTIFHUNG | win32.SMTO_ERRORONEXIT, dwTimeout) | python | def send(self, uMsg, wParam = None, lParam = None, dwTimeout = None):
"""
Send a low-level window message syncronically.
@type uMsg: int
@param uMsg: Message code.
@param wParam:
The type and meaning of this parameter depends on the message.
@param lParam:
The type and meaning of this parameter depends on the message.
@param dwTimeout: Optional timeout for the operation.
Use C{None} to wait indefinitely.
@rtype: int
@return: The meaning of the return value depends on the window message.
Typically a value of C{0} means an error occured. You can get the
error code by calling L{win32.GetLastError}.
"""
if dwTimeout is None:
return win32.SendMessage(self.get_handle(), uMsg, wParam, lParam)
return win32.SendMessageTimeout(
self.get_handle(), uMsg, wParam, lParam,
win32.SMTO_ABORTIFHUNG | win32.SMTO_ERRORONEXIT, dwTimeout) | [
"def",
"send",
"(",
"self",
",",
"uMsg",
",",
"wParam",
"=",
"None",
",",
"lParam",
"=",
"None",
",",
"dwTimeout",
"=",
"None",
")",
":",
"if",
"dwTimeout",
"is",
"None",
":",
"return",
"win32",
".",
"SendMessage",
"(",
"self",
".",
"get_handle",
"("... | Send a low-level window message syncronically.
@type uMsg: int
@param uMsg: Message code.
@param wParam:
The type and meaning of this parameter depends on the message.
@param lParam:
The type and meaning of this parameter depends on the message.
@param dwTimeout: Optional timeout for the operation.
Use C{None} to wait indefinitely.
@rtype: int
@return: The meaning of the return value depends on the window message.
Typically a value of C{0} means an error occured. You can get the
error code by calling L{win32.GetLastError}. | [
"Send",
"a",
"low",
"-",
"level",
"window",
"message",
"syncronically",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/window.py#L717-L742 | train | 209,626 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/window.py | Window.post | def post(self, uMsg, wParam = None, lParam = None):
"""
Post a low-level window message asyncronically.
@type uMsg: int
@param uMsg: Message code.
@param wParam:
The type and meaning of this parameter depends on the message.
@param lParam:
The type and meaning of this parameter depends on the message.
@raise WindowsError: An error occured while sending the message.
"""
win32.PostMessage(self.get_handle(), uMsg, wParam, lParam) | python | def post(self, uMsg, wParam = None, lParam = None):
"""
Post a low-level window message asyncronically.
@type uMsg: int
@param uMsg: Message code.
@param wParam:
The type and meaning of this parameter depends on the message.
@param lParam:
The type and meaning of this parameter depends on the message.
@raise WindowsError: An error occured while sending the message.
"""
win32.PostMessage(self.get_handle(), uMsg, wParam, lParam) | [
"def",
"post",
"(",
"self",
",",
"uMsg",
",",
"wParam",
"=",
"None",
",",
"lParam",
"=",
"None",
")",
":",
"win32",
".",
"PostMessage",
"(",
"self",
".",
"get_handle",
"(",
")",
",",
"uMsg",
",",
"wParam",
",",
"lParam",
")"
] | Post a low-level window message asyncronically.
@type uMsg: int
@param uMsg: Message code.
@param wParam:
The type and meaning of this parameter depends on the message.
@param lParam:
The type and meaning of this parameter depends on the message.
@raise WindowsError: An error occured while sending the message. | [
"Post",
"a",
"low",
"-",
"level",
"window",
"message",
"asyncronically",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/window.py#L744-L759 | train | 209,627 |
fabioz/PyDev.Debugger | _pydevd_bundle/pydevd_process_net_command_json.py | _PyDevJsonCommandProcessor.process_net_command_json | def process_net_command_json(self, py_db, json_contents):
'''
Processes a debug adapter protocol json command.
'''
DEBUG = False
try:
request = self.from_json(json_contents, update_ids_from_dap=True)
except KeyError as e:
request = self.from_json(json_contents, update_ids_from_dap=False)
error_msg = str(e)
if error_msg.startswith("'") and error_msg.endswith("'"):
error_msg = error_msg[1:-1]
# This means a failure updating ids from the DAP (the client sent a key we didn't send).
def on_request(py_db, request):
error_response = {
'type': 'response',
'request_seq': request.seq,
'success': False,
'command': request.command,
'message': error_msg,
}
return NetCommand(CMD_RETURN, 0, error_response, is_json=True)
else:
if DebugInfoHolder.DEBUG_RECORD_SOCKET_READS and DebugInfoHolder.DEBUG_TRACE_LEVEL >= 1:
pydev_log.info('Process %s: %s\n' % (
request.__class__.__name__, json.dumps(request.to_dict(), indent=4, sort_keys=True),))
assert request.type == 'request'
method_name = 'on_%s_request' % (request.command.lower(),)
on_request = getattr(self, method_name, None)
if on_request is None:
print('Unhandled: %s not available in _PyDevJsonCommandProcessor.\n' % (method_name,))
return
if DEBUG:
print('Handled in pydevd: %s (in _PyDevJsonCommandProcessor).\n' % (method_name,))
py_db._main_lock.acquire()
try:
cmd = on_request(py_db, request)
if cmd is not None:
py_db.writer.add_command(cmd)
finally:
py_db._main_lock.release() | python | def process_net_command_json(self, py_db, json_contents):
'''
Processes a debug adapter protocol json command.
'''
DEBUG = False
try:
request = self.from_json(json_contents, update_ids_from_dap=True)
except KeyError as e:
request = self.from_json(json_contents, update_ids_from_dap=False)
error_msg = str(e)
if error_msg.startswith("'") and error_msg.endswith("'"):
error_msg = error_msg[1:-1]
# This means a failure updating ids from the DAP (the client sent a key we didn't send).
def on_request(py_db, request):
error_response = {
'type': 'response',
'request_seq': request.seq,
'success': False,
'command': request.command,
'message': error_msg,
}
return NetCommand(CMD_RETURN, 0, error_response, is_json=True)
else:
if DebugInfoHolder.DEBUG_RECORD_SOCKET_READS and DebugInfoHolder.DEBUG_TRACE_LEVEL >= 1:
pydev_log.info('Process %s: %s\n' % (
request.__class__.__name__, json.dumps(request.to_dict(), indent=4, sort_keys=True),))
assert request.type == 'request'
method_name = 'on_%s_request' % (request.command.lower(),)
on_request = getattr(self, method_name, None)
if on_request is None:
print('Unhandled: %s not available in _PyDevJsonCommandProcessor.\n' % (method_name,))
return
if DEBUG:
print('Handled in pydevd: %s (in _PyDevJsonCommandProcessor).\n' % (method_name,))
py_db._main_lock.acquire()
try:
cmd = on_request(py_db, request)
if cmd is not None:
py_db.writer.add_command(cmd)
finally:
py_db._main_lock.release() | [
"def",
"process_net_command_json",
"(",
"self",
",",
"py_db",
",",
"json_contents",
")",
":",
"DEBUG",
"=",
"False",
"try",
":",
"request",
"=",
"self",
".",
"from_json",
"(",
"json_contents",
",",
"update_ids_from_dap",
"=",
"True",
")",
"except",
"KeyError",... | Processes a debug adapter protocol json command. | [
"Processes",
"a",
"debug",
"adapter",
"protocol",
"json",
"command",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_bundle/pydevd_process_net_command_json.py#L149-L197 | train | 209,628 |
fabioz/PyDev.Debugger | _pydevd_bundle/pydevd_process_net_command_json.py | _PyDevJsonCommandProcessor._get_hit_condition_expression | def _get_hit_condition_expression(self, hit_condition):
'''Following hit condition values are supported
* x or == x when breakpoint is hit x times
* >= x when breakpoint is hit more than or equal to x times
* % x when breakpoint is hit multiple of x times
Returns '@HIT@ == x' where @HIT@ will be replaced by number of hits
'''
if not hit_condition:
return None
expr = hit_condition.strip()
try:
int(expr)
return '@HIT@ == {}'.format(expr)
except ValueError:
pass
if expr.startswith('%'):
return '@HIT@ {} == 0'.format(expr)
if expr.startswith('==') or \
expr.startswith('>') or \
expr.startswith('<'):
return '@HIT@ {}'.format(expr)
return hit_condition | python | def _get_hit_condition_expression(self, hit_condition):
'''Following hit condition values are supported
* x or == x when breakpoint is hit x times
* >= x when breakpoint is hit more than or equal to x times
* % x when breakpoint is hit multiple of x times
Returns '@HIT@ == x' where @HIT@ will be replaced by number of hits
'''
if not hit_condition:
return None
expr = hit_condition.strip()
try:
int(expr)
return '@HIT@ == {}'.format(expr)
except ValueError:
pass
if expr.startswith('%'):
return '@HIT@ {} == 0'.format(expr)
if expr.startswith('==') or \
expr.startswith('>') or \
expr.startswith('<'):
return '@HIT@ {}'.format(expr)
return hit_condition | [
"def",
"_get_hit_condition_expression",
"(",
"self",
",",
"hit_condition",
")",
":",
"if",
"not",
"hit_condition",
":",
"return",
"None",
"expr",
"=",
"hit_condition",
".",
"strip",
"(",
")",
"try",
":",
"int",
"(",
"expr",
")",
"return",
"'@HIT@ == {}'",
".... | Following hit condition values are supported
* x or == x when breakpoint is hit x times
* >= x when breakpoint is hit more than or equal to x times
* % x when breakpoint is hit multiple of x times
Returns '@HIT@ == x' where @HIT@ will be replaced by number of hits | [
"Following",
"hit",
"condition",
"values",
"are",
"supported"
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_bundle/pydevd_process_net_command_json.py#L384-L411 | train | 209,629 |
fabioz/PyDev.Debugger | pydev_ipython/inputhookwx.py | inputhook_wx2 | def inputhook_wx2():
"""Run the wx event loop, polling for stdin.
This version runs the wx eventloop for an undetermined amount of time,
during which it periodically checks to see if anything is ready on
stdin. If anything is ready on stdin, the event loop exits.
The argument to elr.Run controls how often the event loop looks at stdin.
This determines the responsiveness at the keyboard. A setting of 1000
enables a user to type at most 1 char per second. I have found that a
setting of 10 gives good keyboard response. We can shorten it further,
but eventually performance would suffer from calling select/kbhit too
often.
"""
try:
app = wx.GetApp() # @UndefinedVariable
if app is not None:
assert wx.Thread_IsMain() # @UndefinedVariable
elr = EventLoopRunner()
# As this time is made shorter, keyboard response improves, but idle
# CPU load goes up. 10 ms seems like a good compromise.
elr.Run(time=10) # CHANGE time here to control polling interval
except KeyboardInterrupt:
pass
return 0 | python | def inputhook_wx2():
"""Run the wx event loop, polling for stdin.
This version runs the wx eventloop for an undetermined amount of time,
during which it periodically checks to see if anything is ready on
stdin. If anything is ready on stdin, the event loop exits.
The argument to elr.Run controls how often the event loop looks at stdin.
This determines the responsiveness at the keyboard. A setting of 1000
enables a user to type at most 1 char per second. I have found that a
setting of 10 gives good keyboard response. We can shorten it further,
but eventually performance would suffer from calling select/kbhit too
often.
"""
try:
app = wx.GetApp() # @UndefinedVariable
if app is not None:
assert wx.Thread_IsMain() # @UndefinedVariable
elr = EventLoopRunner()
# As this time is made shorter, keyboard response improves, but idle
# CPU load goes up. 10 ms seems like a good compromise.
elr.Run(time=10) # CHANGE time here to control polling interval
except KeyboardInterrupt:
pass
return 0 | [
"def",
"inputhook_wx2",
"(",
")",
":",
"try",
":",
"app",
"=",
"wx",
".",
"GetApp",
"(",
")",
"# @UndefinedVariable",
"if",
"app",
"is",
"not",
"None",
":",
"assert",
"wx",
".",
"Thread_IsMain",
"(",
")",
"# @UndefinedVariable",
"elr",
"=",
"EventLoopRunne... | Run the wx event loop, polling for stdin.
This version runs the wx eventloop for an undetermined amount of time,
during which it periodically checks to see if anything is ready on
stdin. If anything is ready on stdin, the event loop exits.
The argument to elr.Run controls how often the event loop looks at stdin.
This determines the responsiveness at the keyboard. A setting of 1000
enables a user to type at most 1 char per second. I have found that a
setting of 10 gives good keyboard response. We can shorten it further,
but eventually performance would suffer from calling select/kbhit too
often. | [
"Run",
"the",
"wx",
"event",
"loop",
"polling",
"for",
"stdin",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydev_ipython/inputhookwx.py#L78-L102 | train | 209,630 |
fabioz/PyDev.Debugger | _pydevd_bundle/pydevd_signature.py | _modname | def _modname(path):
"""Return a plausible module name for the path"""
base = os.path.basename(path)
filename, ext = os.path.splitext(base)
return filename | python | def _modname(path):
"""Return a plausible module name for the path"""
base = os.path.basename(path)
filename, ext = os.path.splitext(base)
return filename | [
"def",
"_modname",
"(",
"path",
")",
":",
"base",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
"filename",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"base",
")",
"return",
"filename"
] | Return a plausible module name for the path | [
"Return",
"a",
"plausible",
"module",
"name",
"for",
"the",
"path"
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_bundle/pydevd_signature.py#L81-L85 | train | 209,631 |
fabioz/PyDev.Debugger | pydev_ipython/inputhook.py | InputHookManager.enable_gtk | def enable_gtk(self, app=None):
"""Enable event loop integration with PyGTK.
Parameters
----------
app : ignored
Ignored, it's only a placeholder to keep the call signature of all
gui activation methods consistent, which simplifies the logic of
supporting magics.
Notes
-----
This methods sets the PyOS_InputHook for PyGTK, which allows
the PyGTK to integrate with terminal based applications like
IPython.
"""
from pydev_ipython.inputhookgtk import create_inputhook_gtk
self.set_inputhook(create_inputhook_gtk(self._stdin_file))
self._current_gui = GUI_GTK | python | def enable_gtk(self, app=None):
"""Enable event loop integration with PyGTK.
Parameters
----------
app : ignored
Ignored, it's only a placeholder to keep the call signature of all
gui activation methods consistent, which simplifies the logic of
supporting magics.
Notes
-----
This methods sets the PyOS_InputHook for PyGTK, which allows
the PyGTK to integrate with terminal based applications like
IPython.
"""
from pydev_ipython.inputhookgtk import create_inputhook_gtk
self.set_inputhook(create_inputhook_gtk(self._stdin_file))
self._current_gui = GUI_GTK | [
"def",
"enable_gtk",
"(",
"self",
",",
"app",
"=",
"None",
")",
":",
"from",
"pydev_ipython",
".",
"inputhookgtk",
"import",
"create_inputhook_gtk",
"self",
".",
"set_inputhook",
"(",
"create_inputhook_gtk",
"(",
"self",
".",
"_stdin_file",
")",
")",
"self",
"... | Enable event loop integration with PyGTK.
Parameters
----------
app : ignored
Ignored, it's only a placeholder to keep the call signature of all
gui activation methods consistent, which simplifies the logic of
supporting magics.
Notes
-----
This methods sets the PyOS_InputHook for PyGTK, which allows
the PyGTK to integrate with terminal based applications like
IPython. | [
"Enable",
"event",
"loop",
"integration",
"with",
"PyGTK",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydev_ipython/inputhook.py#L235-L253 | train | 209,632 |
fabioz/PyDev.Debugger | pydev_ipython/inputhook.py | InputHookManager.enable_tk | def enable_tk(self, app=None):
"""Enable event loop integration with Tk.
Parameters
----------
app : toplevel :class:`Tkinter.Tk` widget, optional.
Running toplevel widget to use. If not given, we probe Tk for an
existing one, and create a new one if none is found.
Notes
-----
If you have already created a :class:`Tkinter.Tk` object, the only
thing done by this method is to register with the
:class:`InputHookManager`, since creating that object automatically
sets ``PyOS_InputHook``.
"""
self._current_gui = GUI_TK
if app is None:
try:
import Tkinter as _TK
except:
# Python 3
import tkinter as _TK # @UnresolvedImport
app = _TK.Tk()
app.withdraw()
self._apps[GUI_TK] = app
from pydev_ipython.inputhooktk import create_inputhook_tk
self.set_inputhook(create_inputhook_tk(app))
return app | python | def enable_tk(self, app=None):
"""Enable event loop integration with Tk.
Parameters
----------
app : toplevel :class:`Tkinter.Tk` widget, optional.
Running toplevel widget to use. If not given, we probe Tk for an
existing one, and create a new one if none is found.
Notes
-----
If you have already created a :class:`Tkinter.Tk` object, the only
thing done by this method is to register with the
:class:`InputHookManager`, since creating that object automatically
sets ``PyOS_InputHook``.
"""
self._current_gui = GUI_TK
if app is None:
try:
import Tkinter as _TK
except:
# Python 3
import tkinter as _TK # @UnresolvedImport
app = _TK.Tk()
app.withdraw()
self._apps[GUI_TK] = app
from pydev_ipython.inputhooktk import create_inputhook_tk
self.set_inputhook(create_inputhook_tk(app))
return app | [
"def",
"enable_tk",
"(",
"self",
",",
"app",
"=",
"None",
")",
":",
"self",
".",
"_current_gui",
"=",
"GUI_TK",
"if",
"app",
"is",
"None",
":",
"try",
":",
"import",
"Tkinter",
"as",
"_TK",
"except",
":",
"# Python 3",
"import",
"tkinter",
"as",
"_TK",... | Enable event loop integration with Tk.
Parameters
----------
app : toplevel :class:`Tkinter.Tk` widget, optional.
Running toplevel widget to use. If not given, we probe Tk for an
existing one, and create a new one if none is found.
Notes
-----
If you have already created a :class:`Tkinter.Tk` object, the only
thing done by this method is to register with the
:class:`InputHookManager`, since creating that object automatically
sets ``PyOS_InputHook``. | [
"Enable",
"event",
"loop",
"integration",
"with",
"Tk",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydev_ipython/inputhook.py#L262-L291 | train | 209,633 |
fabioz/PyDev.Debugger | pydev_ipython/inputhook.py | InputHookManager.enable_glut | def enable_glut(self, app=None):
""" Enable event loop integration with GLUT.
Parameters
----------
app : ignored
Ignored, it's only a placeholder to keep the call signature of all
gui activation methods consistent, which simplifies the logic of
supporting magics.
Notes
-----
This methods sets the PyOS_InputHook for GLUT, which allows the GLUT to
integrate with terminal based applications like IPython. Due to GLUT
limitations, it is currently not possible to start the event loop
without first creating a window. You should thus not create another
window but use instead the created one. See 'gui-glut.py' in the
docs/examples/lib directory.
The default screen mode is set to:
glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH
"""
import OpenGL.GLUT as glut # @UnresolvedImport
from pydev_ipython.inputhookglut import glut_display_mode, \
glut_close, glut_display, \
glut_idle, inputhook_glut
if GUI_GLUT not in self._apps:
glut.glutInit(sys.argv)
glut.glutInitDisplayMode(glut_display_mode)
# This is specific to freeglut
if bool(glut.glutSetOption):
glut.glutSetOption(glut.GLUT_ACTION_ON_WINDOW_CLOSE,
glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS)
glut.glutCreateWindow(sys.argv[0])
glut.glutReshapeWindow(1, 1)
glut.glutHideWindow()
glut.glutWMCloseFunc(glut_close)
glut.glutDisplayFunc(glut_display)
glut.glutIdleFunc(glut_idle)
else:
glut.glutWMCloseFunc(glut_close)
glut.glutDisplayFunc(glut_display)
glut.glutIdleFunc(glut_idle)
self.set_inputhook(inputhook_glut)
self._current_gui = GUI_GLUT
self._apps[GUI_GLUT] = True | python | def enable_glut(self, app=None):
""" Enable event loop integration with GLUT.
Parameters
----------
app : ignored
Ignored, it's only a placeholder to keep the call signature of all
gui activation methods consistent, which simplifies the logic of
supporting magics.
Notes
-----
This methods sets the PyOS_InputHook for GLUT, which allows the GLUT to
integrate with terminal based applications like IPython. Due to GLUT
limitations, it is currently not possible to start the event loop
without first creating a window. You should thus not create another
window but use instead the created one. See 'gui-glut.py' in the
docs/examples/lib directory.
The default screen mode is set to:
glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH
"""
import OpenGL.GLUT as glut # @UnresolvedImport
from pydev_ipython.inputhookglut import glut_display_mode, \
glut_close, glut_display, \
glut_idle, inputhook_glut
if GUI_GLUT not in self._apps:
glut.glutInit(sys.argv)
glut.glutInitDisplayMode(glut_display_mode)
# This is specific to freeglut
if bool(glut.glutSetOption):
glut.glutSetOption(glut.GLUT_ACTION_ON_WINDOW_CLOSE,
glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS)
glut.glutCreateWindow(sys.argv[0])
glut.glutReshapeWindow(1, 1)
glut.glutHideWindow()
glut.glutWMCloseFunc(glut_close)
glut.glutDisplayFunc(glut_display)
glut.glutIdleFunc(glut_idle)
else:
glut.glutWMCloseFunc(glut_close)
glut.glutDisplayFunc(glut_display)
glut.glutIdleFunc(glut_idle)
self.set_inputhook(inputhook_glut)
self._current_gui = GUI_GLUT
self._apps[GUI_GLUT] = True | [
"def",
"enable_glut",
"(",
"self",
",",
"app",
"=",
"None",
")",
":",
"import",
"OpenGL",
".",
"GLUT",
"as",
"glut",
"# @UnresolvedImport",
"from",
"pydev_ipython",
".",
"inputhookglut",
"import",
"glut_display_mode",
",",
"glut_close",
",",
"glut_display",
",",... | Enable event loop integration with GLUT.
Parameters
----------
app : ignored
Ignored, it's only a placeholder to keep the call signature of all
gui activation methods consistent, which simplifies the logic of
supporting magics.
Notes
-----
This methods sets the PyOS_InputHook for GLUT, which allows the GLUT to
integrate with terminal based applications like IPython. Due to GLUT
limitations, it is currently not possible to start the event loop
without first creating a window. You should thus not create another
window but use instead the created one. See 'gui-glut.py' in the
docs/examples/lib directory.
The default screen mode is set to:
glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH | [
"Enable",
"event",
"loop",
"integration",
"with",
"GLUT",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydev_ipython/inputhook.py#L301-L350 | train | 209,634 |
fabioz/PyDev.Debugger | pydev_ipython/inputhook.py | InputHookManager.disable_glut | def disable_glut(self):
"""Disable event loop integration with glut.
This sets PyOS_InputHook to NULL and set the display function to a
dummy one and set the timer to a dummy timer that will be triggered
very far in the future.
"""
import OpenGL.GLUT as glut # @UnresolvedImport
from glut_support import glutMainLoopEvent # @UnresolvedImport
glut.glutHideWindow() # This is an event to be processed below
glutMainLoopEvent()
self.clear_inputhook() | python | def disable_glut(self):
"""Disable event loop integration with glut.
This sets PyOS_InputHook to NULL and set the display function to a
dummy one and set the timer to a dummy timer that will be triggered
very far in the future.
"""
import OpenGL.GLUT as glut # @UnresolvedImport
from glut_support import glutMainLoopEvent # @UnresolvedImport
glut.glutHideWindow() # This is an event to be processed below
glutMainLoopEvent()
self.clear_inputhook() | [
"def",
"disable_glut",
"(",
"self",
")",
":",
"import",
"OpenGL",
".",
"GLUT",
"as",
"glut",
"# @UnresolvedImport",
"from",
"glut_support",
"import",
"glutMainLoopEvent",
"# @UnresolvedImport",
"glut",
".",
"glutHideWindow",
"(",
")",
"# This is an event to be processed... | Disable event loop integration with glut.
This sets PyOS_InputHook to NULL and set the display function to a
dummy one and set the timer to a dummy timer that will be triggered
very far in the future. | [
"Disable",
"event",
"loop",
"integration",
"with",
"glut",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydev_ipython/inputhook.py#L353-L365 | train | 209,635 |
fabioz/PyDev.Debugger | pydev_ipython/inputhook.py | InputHookManager.enable_pyglet | def enable_pyglet(self, app=None):
"""Enable event loop integration with pyglet.
Parameters
----------
app : ignored
Ignored, it's only a placeholder to keep the call signature of all
gui activation methods consistent, which simplifies the logic of
supporting magics.
Notes
-----
This methods sets the ``PyOS_InputHook`` for pyglet, which allows
pyglet to integrate with terminal based applications like
IPython.
"""
from pydev_ipython.inputhookpyglet import inputhook_pyglet
self.set_inputhook(inputhook_pyglet)
self._current_gui = GUI_PYGLET
return app | python | def enable_pyglet(self, app=None):
"""Enable event loop integration with pyglet.
Parameters
----------
app : ignored
Ignored, it's only a placeholder to keep the call signature of all
gui activation methods consistent, which simplifies the logic of
supporting magics.
Notes
-----
This methods sets the ``PyOS_InputHook`` for pyglet, which allows
pyglet to integrate with terminal based applications like
IPython.
"""
from pydev_ipython.inputhookpyglet import inputhook_pyglet
self.set_inputhook(inputhook_pyglet)
self._current_gui = GUI_PYGLET
return app | [
"def",
"enable_pyglet",
"(",
"self",
",",
"app",
"=",
"None",
")",
":",
"from",
"pydev_ipython",
".",
"inputhookpyglet",
"import",
"inputhook_pyglet",
"self",
".",
"set_inputhook",
"(",
"inputhook_pyglet",
")",
"self",
".",
"_current_gui",
"=",
"GUI_PYGLET",
"re... | Enable event loop integration with pyglet.
Parameters
----------
app : ignored
Ignored, it's only a placeholder to keep the call signature of all
gui activation methods consistent, which simplifies the logic of
supporting magics.
Notes
-----
This methods sets the ``PyOS_InputHook`` for pyglet, which allows
pyglet to integrate with terminal based applications like
IPython. | [
"Enable",
"event",
"loop",
"integration",
"with",
"pyglet",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydev_ipython/inputhook.py#L367-L387 | train | 209,636 |
fabioz/PyDev.Debugger | pydev_ipython/inputhook.py | InputHookManager.enable_mac | def enable_mac(self, app=None):
""" Enable event loop integration with MacOSX.
We call function pyplot.pause, which updates and displays active
figure during pause. It's not MacOSX-specific, but it enables to
avoid inputhooks in native MacOSX backend.
Also we shouldn't import pyplot, until user does it. Cause it's
possible to choose backend before importing pyplot for the first
time only.
"""
def inputhook_mac(app=None):
if self.pyplot_imported:
pyplot = sys.modules['matplotlib.pyplot']
try:
pyplot.pause(0.01)
except:
pass
else:
if 'matplotlib.pyplot' in sys.modules:
self.pyplot_imported = True
self.set_inputhook(inputhook_mac)
self._current_gui = GUI_OSX | python | def enable_mac(self, app=None):
""" Enable event loop integration with MacOSX.
We call function pyplot.pause, which updates and displays active
figure during pause. It's not MacOSX-specific, but it enables to
avoid inputhooks in native MacOSX backend.
Also we shouldn't import pyplot, until user does it. Cause it's
possible to choose backend before importing pyplot for the first
time only.
"""
def inputhook_mac(app=None):
if self.pyplot_imported:
pyplot = sys.modules['matplotlib.pyplot']
try:
pyplot.pause(0.01)
except:
pass
else:
if 'matplotlib.pyplot' in sys.modules:
self.pyplot_imported = True
self.set_inputhook(inputhook_mac)
self._current_gui = GUI_OSX | [
"def",
"enable_mac",
"(",
"self",
",",
"app",
"=",
"None",
")",
":",
"def",
"inputhook_mac",
"(",
"app",
"=",
"None",
")",
":",
"if",
"self",
".",
"pyplot_imported",
":",
"pyplot",
"=",
"sys",
".",
"modules",
"[",
"'matplotlib.pyplot'",
"]",
"try",
":"... | Enable event loop integration with MacOSX.
We call function pyplot.pause, which updates and displays active
figure during pause. It's not MacOSX-specific, but it enables to
avoid inputhooks in native MacOSX backend.
Also we shouldn't import pyplot, until user does it. Cause it's
possible to choose backend before importing pyplot for the first
time only. | [
"Enable",
"event",
"loop",
"integration",
"with",
"MacOSX",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydev_ipython/inputhook.py#L423-L445 | train | 209,637 |
fabioz/PyDev.Debugger | _pydevd_bundle/pydevd_net_command_factory_xml.py | NetCommandFactory._thread_to_xml | def _thread_to_xml(self, thread):
""" thread information as XML """
name = pydevd_xml.make_valid_xml_value(thread.getName())
cmdText = '<thread name="%s" id="%s" />' % (quote(name), get_thread_id(thread))
return cmdText | python | def _thread_to_xml(self, thread):
""" thread information as XML """
name = pydevd_xml.make_valid_xml_value(thread.getName())
cmdText = '<thread name="%s" id="%s" />' % (quote(name), get_thread_id(thread))
return cmdText | [
"def",
"_thread_to_xml",
"(",
"self",
",",
"thread",
")",
":",
"name",
"=",
"pydevd_xml",
".",
"make_valid_xml_value",
"(",
"thread",
".",
"getName",
"(",
")",
")",
"cmdText",
"=",
"'<thread name=\"%s\" id=\"%s\" />'",
"%",
"(",
"quote",
"(",
"name",
")",
",... | thread information as XML | [
"thread",
"information",
"as",
"XML"
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_bundle/pydevd_net_command_factory_xml.py#L43-L47 | train | 209,638 |
fabioz/PyDev.Debugger | _pydevd_bundle/pydevd_net_command_factory_xml.py | NetCommandFactory.make_list_threads_message | def make_list_threads_message(self, py_db, seq):
""" returns thread listing as XML """
try:
threads = get_non_pydevd_threads()
cmd_text = ["<xml>"]
append = cmd_text.append
for thread in threads:
if is_thread_alive(thread):
append(self._thread_to_xml(thread))
append("</xml>")
return NetCommand(CMD_RETURN, seq, ''.join(cmd_text))
except:
return self.make_error_message(seq, get_exception_traceback_str()) | python | def make_list_threads_message(self, py_db, seq):
""" returns thread listing as XML """
try:
threads = get_non_pydevd_threads()
cmd_text = ["<xml>"]
append = cmd_text.append
for thread in threads:
if is_thread_alive(thread):
append(self._thread_to_xml(thread))
append("</xml>")
return NetCommand(CMD_RETURN, seq, ''.join(cmd_text))
except:
return self.make_error_message(seq, get_exception_traceback_str()) | [
"def",
"make_list_threads_message",
"(",
"self",
",",
"py_db",
",",
"seq",
")",
":",
"try",
":",
"threads",
"=",
"get_non_pydevd_threads",
"(",
")",
"cmd_text",
"=",
"[",
"\"<xml>\"",
"]",
"append",
"=",
"cmd_text",
".",
"append",
"for",
"thread",
"in",
"t... | returns thread listing as XML | [
"returns",
"thread",
"listing",
"as",
"XML"
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_bundle/pydevd_net_command_factory_xml.py#L76-L88 | train | 209,639 |
fabioz/PyDev.Debugger | _pydevd_bundle/pydevd_net_command_factory_xml.py | NetCommandFactory.make_get_thread_stack_message | def make_get_thread_stack_message(self, py_db, seq, thread_id, topmost_frame, fmt, must_be_suspended=False, start_frame=0, levels=0):
"""
Returns thread stack as XML.
:param must_be_suspended: If True and the thread is not suspended, returns None.
"""
try:
# If frame is None, the return is an empty frame list.
cmd_text = ['<xml><thread id="%s">' % (thread_id,)]
if topmost_frame is not None:
frame_id_to_lineno = {}
try:
# : :type suspended_frames_manager: SuspendedFramesManager
suspended_frames_manager = py_db.suspended_frames_manager
info = suspended_frames_manager.get_topmost_frame_and_frame_id_to_line(thread_id)
if info is None:
# Could not find stack of suspended frame...
if must_be_suspended:
return None
else:
# Note: we have to use the topmost frame where it was suspended (it may
# be different if it was an exception).
topmost_frame, frame_id_to_lineno = info
cmd_text.append(self.make_thread_stack_str(topmost_frame, frame_id_to_lineno))
finally:
topmost_frame = None
cmd_text.append('</thread></xml>')
return NetCommand(CMD_GET_THREAD_STACK, seq, ''.join(cmd_text))
except:
return self.make_error_message(seq, get_exception_traceback_str()) | python | def make_get_thread_stack_message(self, py_db, seq, thread_id, topmost_frame, fmt, must_be_suspended=False, start_frame=0, levels=0):
"""
Returns thread stack as XML.
:param must_be_suspended: If True and the thread is not suspended, returns None.
"""
try:
# If frame is None, the return is an empty frame list.
cmd_text = ['<xml><thread id="%s">' % (thread_id,)]
if topmost_frame is not None:
frame_id_to_lineno = {}
try:
# : :type suspended_frames_manager: SuspendedFramesManager
suspended_frames_manager = py_db.suspended_frames_manager
info = suspended_frames_manager.get_topmost_frame_and_frame_id_to_line(thread_id)
if info is None:
# Could not find stack of suspended frame...
if must_be_suspended:
return None
else:
# Note: we have to use the topmost frame where it was suspended (it may
# be different if it was an exception).
topmost_frame, frame_id_to_lineno = info
cmd_text.append(self.make_thread_stack_str(topmost_frame, frame_id_to_lineno))
finally:
topmost_frame = None
cmd_text.append('</thread></xml>')
return NetCommand(CMD_GET_THREAD_STACK, seq, ''.join(cmd_text))
except:
return self.make_error_message(seq, get_exception_traceback_str()) | [
"def",
"make_get_thread_stack_message",
"(",
"self",
",",
"py_db",
",",
"seq",
",",
"thread_id",
",",
"topmost_frame",
",",
"fmt",
",",
"must_be_suspended",
"=",
"False",
",",
"start_frame",
"=",
"0",
",",
"levels",
"=",
"0",
")",
":",
"try",
":",
"# If fr... | Returns thread stack as XML.
:param must_be_suspended: If True and the thread is not suspended, returns None. | [
"Returns",
"thread",
"stack",
"as",
"XML",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_bundle/pydevd_net_command_factory_xml.py#L90-L121 | train | 209,640 |
fabioz/PyDev.Debugger | _pydevd_bundle/pydevd_net_command_factory_xml.py | NetCommandFactory.make_get_exception_details_message | def make_get_exception_details_message(self, seq, thread_id, topmost_frame):
"""Returns exception details as XML """
try:
# If the debugger is not suspended, just return the thread and its id.
cmd_text = ['<xml><thread id="%s" ' % (thread_id,)]
if topmost_frame is not None:
try:
frame = topmost_frame
topmost_frame = None
while frame is not None:
if frame.f_code.co_name == 'do_wait_suspend' and frame.f_code.co_filename.endswith('pydevd.py'):
arg = frame.f_locals.get('arg', None)
if arg is not None:
exc_type, exc_desc, _thread_suspend_str, thread_stack_str = self._make_send_curr_exception_trace_str(
thread_id, *arg)
cmd_text.append('exc_type="%s" ' % (exc_type,))
cmd_text.append('exc_desc="%s" ' % (exc_desc,))
cmd_text.append('>')
cmd_text.append(thread_stack_str)
break
frame = frame.f_back
else:
cmd_text.append('>')
finally:
frame = None
cmd_text.append('</thread></xml>')
return NetCommand(CMD_GET_EXCEPTION_DETAILS, seq, ''.join(cmd_text))
except:
return self.make_error_message(seq, get_exception_traceback_str()) | python | def make_get_exception_details_message(self, seq, thread_id, topmost_frame):
"""Returns exception details as XML """
try:
# If the debugger is not suspended, just return the thread and its id.
cmd_text = ['<xml><thread id="%s" ' % (thread_id,)]
if topmost_frame is not None:
try:
frame = topmost_frame
topmost_frame = None
while frame is not None:
if frame.f_code.co_name == 'do_wait_suspend' and frame.f_code.co_filename.endswith('pydevd.py'):
arg = frame.f_locals.get('arg', None)
if arg is not None:
exc_type, exc_desc, _thread_suspend_str, thread_stack_str = self._make_send_curr_exception_trace_str(
thread_id, *arg)
cmd_text.append('exc_type="%s" ' % (exc_type,))
cmd_text.append('exc_desc="%s" ' % (exc_desc,))
cmd_text.append('>')
cmd_text.append(thread_stack_str)
break
frame = frame.f_back
else:
cmd_text.append('>')
finally:
frame = None
cmd_text.append('</thread></xml>')
return NetCommand(CMD_GET_EXCEPTION_DETAILS, seq, ''.join(cmd_text))
except:
return self.make_error_message(seq, get_exception_traceback_str()) | [
"def",
"make_get_exception_details_message",
"(",
"self",
",",
"seq",
",",
"thread_id",
",",
"topmost_frame",
")",
":",
"try",
":",
"# If the debugger is not suspended, just return the thread and its id.",
"cmd_text",
"=",
"[",
"'<xml><thread id=\"%s\" '",
"%",
"(",
"thread... | Returns exception details as XML | [
"Returns",
"exception",
"details",
"as",
"XML"
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_bundle/pydevd_net_command_factory_xml.py#L371-L400 | train | 209,641 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/module.py | Module.set_process | def set_process(self, process = None):
"""
Manually set the parent process. Use with care!
@type process: L{Process}
@param process: (Optional) Process object. Use C{None} for no process.
"""
if process is None:
self.__process = None
else:
global Process # delayed import
if Process is None:
from winappdbg.process import Process
if not isinstance(process, Process):
msg = "Parent process must be a Process instance, "
msg += "got %s instead" % type(process)
raise TypeError(msg)
self.__process = process | python | def set_process(self, process = None):
"""
Manually set the parent process. Use with care!
@type process: L{Process}
@param process: (Optional) Process object. Use C{None} for no process.
"""
if process is None:
self.__process = None
else:
global Process # delayed import
if Process is None:
from winappdbg.process import Process
if not isinstance(process, Process):
msg = "Parent process must be a Process instance, "
msg += "got %s instead" % type(process)
raise TypeError(msg)
self.__process = process | [
"def",
"set_process",
"(",
"self",
",",
"process",
"=",
"None",
")",
":",
"if",
"process",
"is",
"None",
":",
"self",
".",
"__process",
"=",
"None",
"else",
":",
"global",
"Process",
"# delayed import",
"if",
"Process",
"is",
"None",
":",
"from",
"winapp... | Manually set the parent process. Use with care!
@type process: L{Process}
@param process: (Optional) Process object. Use C{None} for no process. | [
"Manually",
"set",
"the",
"parent",
"process",
".",
"Use",
"with",
"care!"
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/module.py#L220-L237 | train | 209,642 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/module.py | Module.__get_size_and_entry_point | def __get_size_and_entry_point(self):
"Get the size and entry point of the module using the Win32 API."
process = self.get_process()
if process:
try:
handle = process.get_handle( win32.PROCESS_VM_READ |
win32.PROCESS_QUERY_INFORMATION )
base = self.get_base()
mi = win32.GetModuleInformation(handle, base)
self.SizeOfImage = mi.SizeOfImage
self.EntryPoint = mi.EntryPoint
except WindowsError:
e = sys.exc_info()[1]
warnings.warn(
"Cannot get size and entry point of module %s, reason: %s"\
% (self.get_name(), e.strerror), RuntimeWarning) | python | def __get_size_and_entry_point(self):
"Get the size and entry point of the module using the Win32 API."
process = self.get_process()
if process:
try:
handle = process.get_handle( win32.PROCESS_VM_READ |
win32.PROCESS_QUERY_INFORMATION )
base = self.get_base()
mi = win32.GetModuleInformation(handle, base)
self.SizeOfImage = mi.SizeOfImage
self.EntryPoint = mi.EntryPoint
except WindowsError:
e = sys.exc_info()[1]
warnings.warn(
"Cannot get size and entry point of module %s, reason: %s"\
% (self.get_name(), e.strerror), RuntimeWarning) | [
"def",
"__get_size_and_entry_point",
"(",
"self",
")",
":",
"process",
"=",
"self",
".",
"get_process",
"(",
")",
"if",
"process",
":",
"try",
":",
"handle",
"=",
"process",
".",
"get_handle",
"(",
"win32",
".",
"PROCESS_VM_READ",
"|",
"win32",
".",
"PROCE... | Get the size and entry point of the module using the Win32 API. | [
"Get",
"the",
"size",
"and",
"entry",
"point",
"of",
"the",
"module",
"using",
"the",
"Win32",
"API",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/module.py#L279-L294 | train | 209,643 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/module.py | Module.open_handle | def open_handle(self):
"""
Opens a new handle to the module.
The new handle is stored in the L{hFile} property.
"""
if not self.get_filename():
msg = "Cannot retrieve filename for module at %s"
msg = msg % HexDump.address( self.get_base() )
raise Exception(msg)
hFile = win32.CreateFile(self.get_filename(),
dwShareMode = win32.FILE_SHARE_READ,
dwCreationDisposition = win32.OPEN_EXISTING)
# In case hFile was set to an actual handle value instead of a Handle
# object. This shouldn't happen unless the user tinkered with hFile.
if not hasattr(self.hFile, '__del__'):
self.close_handle()
self.hFile = hFile | python | def open_handle(self):
"""
Opens a new handle to the module.
The new handle is stored in the L{hFile} property.
"""
if not self.get_filename():
msg = "Cannot retrieve filename for module at %s"
msg = msg % HexDump.address( self.get_base() )
raise Exception(msg)
hFile = win32.CreateFile(self.get_filename(),
dwShareMode = win32.FILE_SHARE_READ,
dwCreationDisposition = win32.OPEN_EXISTING)
# In case hFile was set to an actual handle value instead of a Handle
# object. This shouldn't happen unless the user tinkered with hFile.
if not hasattr(self.hFile, '__del__'):
self.close_handle()
self.hFile = hFile | [
"def",
"open_handle",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"get_filename",
"(",
")",
":",
"msg",
"=",
"\"Cannot retrieve filename for module at %s\"",
"msg",
"=",
"msg",
"%",
"HexDump",
".",
"address",
"(",
"self",
".",
"get_base",
"(",
")",
")... | Opens a new handle to the module.
The new handle is stored in the L{hFile} property. | [
"Opens",
"a",
"new",
"handle",
"to",
"the",
"module",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/module.py#L388-L409 | train | 209,644 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/module.py | Module.close_handle | def close_handle(self):
"""
Closes the handle to the module.
@note: Normally you don't need to call this method. All handles
created by I{WinAppDbg} are automatically closed when the garbage
collector claims them. So unless you've been tinkering with it,
setting L{hFile} to C{None} should be enough.
"""
try:
if hasattr(self.hFile, 'close'):
self.hFile.close()
elif self.hFile not in (None, win32.INVALID_HANDLE_VALUE):
win32.CloseHandle(self.hFile)
finally:
self.hFile = None | python | def close_handle(self):
"""
Closes the handle to the module.
@note: Normally you don't need to call this method. All handles
created by I{WinAppDbg} are automatically closed when the garbage
collector claims them. So unless you've been tinkering with it,
setting L{hFile} to C{None} should be enough.
"""
try:
if hasattr(self.hFile, 'close'):
self.hFile.close()
elif self.hFile not in (None, win32.INVALID_HANDLE_VALUE):
win32.CloseHandle(self.hFile)
finally:
self.hFile = None | [
"def",
"close_handle",
"(",
"self",
")",
":",
"try",
":",
"if",
"hasattr",
"(",
"self",
".",
"hFile",
",",
"'close'",
")",
":",
"self",
".",
"hFile",
".",
"close",
"(",
")",
"elif",
"self",
".",
"hFile",
"not",
"in",
"(",
"None",
",",
"win32",
".... | Closes the handle to the module.
@note: Normally you don't need to call this method. All handles
created by I{WinAppDbg} are automatically closed when the garbage
collector claims them. So unless you've been tinkering with it,
setting L{hFile} to C{None} should be enough. | [
"Closes",
"the",
"handle",
"to",
"the",
"module",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/module.py#L411-L426 | train | 209,645 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/module.py | Module.get_label | def get_label(self, function = None, offset = None):
"""
Retrieves the label for the given function of this module or the module
base address if no function name is given.
@type function: str
@param function: (Optional) Exported function name.
@type offset: int
@param offset: (Optional) Offset from the module base address.
@rtype: str
@return: Label for the module base address, plus the offset if given.
"""
return _ModuleContainer.parse_label(self.get_name(), function, offset) | python | def get_label(self, function = None, offset = None):
"""
Retrieves the label for the given function of this module or the module
base address if no function name is given.
@type function: str
@param function: (Optional) Exported function name.
@type offset: int
@param offset: (Optional) Offset from the module base address.
@rtype: str
@return: Label for the module base address, plus the offset if given.
"""
return _ModuleContainer.parse_label(self.get_name(), function, offset) | [
"def",
"get_label",
"(",
"self",
",",
"function",
"=",
"None",
",",
"offset",
"=",
"None",
")",
":",
"return",
"_ModuleContainer",
".",
"parse_label",
"(",
"self",
".",
"get_name",
"(",
")",
",",
"function",
",",
"offset",
")"
] | Retrieves the label for the given function of this module or the module
base address if no function name is given.
@type function: str
@param function: (Optional) Exported function name.
@type offset: int
@param offset: (Optional) Offset from the module base address.
@rtype: str
@return: Label for the module base address, plus the offset if given. | [
"Retrieves",
"the",
"label",
"for",
"the",
"given",
"function",
"of",
"this",
"module",
"or",
"the",
"module",
"base",
"address",
"if",
"no",
"function",
"name",
"is",
"given",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/module.py#L615-L629 | train | 209,646 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/module.py | Module.is_address_here | def is_address_here(self, address):
"""
Tries to determine if the given address belongs to this module.
@type address: int
@param address: Memory address.
@rtype: bool or None
@return: C{True} if the address belongs to the module,
C{False} if it doesn't,
and C{None} if it can't be determined.
"""
base = self.get_base()
size = self.get_size()
if base and size:
return base <= address < (base + size)
return None | python | def is_address_here(self, address):
"""
Tries to determine if the given address belongs to this module.
@type address: int
@param address: Memory address.
@rtype: bool or None
@return: C{True} if the address belongs to the module,
C{False} if it doesn't,
and C{None} if it can't be determined.
"""
base = self.get_base()
size = self.get_size()
if base and size:
return base <= address < (base + size)
return None | [
"def",
"is_address_here",
"(",
"self",
",",
"address",
")",
":",
"base",
"=",
"self",
".",
"get_base",
"(",
")",
"size",
"=",
"self",
".",
"get_size",
"(",
")",
"if",
"base",
"and",
"size",
":",
"return",
"base",
"<=",
"address",
"<",
"(",
"base",
... | Tries to determine if the given address belongs to this module.
@type address: int
@param address: Memory address.
@rtype: bool or None
@return: C{True} if the address belongs to the module,
C{False} if it doesn't,
and C{None} if it can't be determined. | [
"Tries",
"to",
"determine",
"if",
"the",
"given",
"address",
"belongs",
"to",
"this",
"module",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/module.py#L680-L696 | train | 209,647 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/module.py | Module.resolve | def resolve(self, function):
"""
Resolves a function exported by this module.
@type function: str or int
@param function:
str: Name of the function.
int: Ordinal of the function.
@rtype: int
@return: Memory address of the exported function in the process.
Returns None on error.
"""
# Unknown DLL filename, there's nothing we can do.
filename = self.get_filename()
if not filename:
return None
# If the DLL is already mapped locally, resolve the function.
try:
hlib = win32.GetModuleHandle(filename)
address = win32.GetProcAddress(hlib, function)
except WindowsError:
# Load the DLL locally, resolve the function and unload it.
try:
hlib = win32.LoadLibraryEx(filename,
win32.DONT_RESOLVE_DLL_REFERENCES)
try:
address = win32.GetProcAddress(hlib, function)
finally:
win32.FreeLibrary(hlib)
except WindowsError:
return None
# A NULL pointer means the function was not found.
if address in (None, 0):
return None
# Compensate for DLL base relocations locally and remotely.
return address - hlib + self.lpBaseOfDll | python | def resolve(self, function):
"""
Resolves a function exported by this module.
@type function: str or int
@param function:
str: Name of the function.
int: Ordinal of the function.
@rtype: int
@return: Memory address of the exported function in the process.
Returns None on error.
"""
# Unknown DLL filename, there's nothing we can do.
filename = self.get_filename()
if not filename:
return None
# If the DLL is already mapped locally, resolve the function.
try:
hlib = win32.GetModuleHandle(filename)
address = win32.GetProcAddress(hlib, function)
except WindowsError:
# Load the DLL locally, resolve the function and unload it.
try:
hlib = win32.LoadLibraryEx(filename,
win32.DONT_RESOLVE_DLL_REFERENCES)
try:
address = win32.GetProcAddress(hlib, function)
finally:
win32.FreeLibrary(hlib)
except WindowsError:
return None
# A NULL pointer means the function was not found.
if address in (None, 0):
return None
# Compensate for DLL base relocations locally and remotely.
return address - hlib + self.lpBaseOfDll | [
"def",
"resolve",
"(",
"self",
",",
"function",
")",
":",
"# Unknown DLL filename, there's nothing we can do.",
"filename",
"=",
"self",
".",
"get_filename",
"(",
")",
"if",
"not",
"filename",
":",
"return",
"None",
"# If the DLL is already mapped locally, resolve the fun... | Resolves a function exported by this module.
@type function: str or int
@param function:
str: Name of the function.
int: Ordinal of the function.
@rtype: int
@return: Memory address of the exported function in the process.
Returns None on error. | [
"Resolves",
"a",
"function",
"exported",
"by",
"this",
"module",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/module.py#L698-L739 | train | 209,648 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/module.py | Module.resolve_label | def resolve_label(self, label):
"""
Resolves a label for this module only. If the label refers to another
module, an exception is raised.
@type label: str
@param label: Label to resolve.
@rtype: int
@return: Memory address pointed to by the label.
@raise ValueError: The label is malformed or impossible to resolve.
@raise RuntimeError: Cannot resolve the module or function.
"""
# Split the label into it's components.
# Use the fuzzy mode whenever possible.
aProcess = self.get_process()
if aProcess is not None:
(module, procedure, offset) = aProcess.split_label(label)
else:
(module, procedure, offset) = _ModuleContainer.split_label(label)
# If a module name is given that doesn't match ours,
# raise an exception.
if module and not self.match_name(module):
raise RuntimeError("Label does not belong to this module")
# Resolve the procedure if given.
if procedure:
address = self.resolve(procedure)
if address is None:
# If it's a debug symbol, use the symbol.
address = self.resolve_symbol(procedure)
# If it's the keyword "start" use the entry point.
if address is None and procedure == "start":
address = self.get_entry_point()
# The procedure was not found.
if address is None:
if not module:
module = self.get_name()
msg = "Can't find procedure %s in module %s"
raise RuntimeError(msg % (procedure, module))
# If no procedure is given use the base address of the module.
else:
address = self.get_base()
# Add the offset if given and return the resolved address.
if offset:
address = address + offset
return address | python | def resolve_label(self, label):
"""
Resolves a label for this module only. If the label refers to another
module, an exception is raised.
@type label: str
@param label: Label to resolve.
@rtype: int
@return: Memory address pointed to by the label.
@raise ValueError: The label is malformed or impossible to resolve.
@raise RuntimeError: Cannot resolve the module or function.
"""
# Split the label into it's components.
# Use the fuzzy mode whenever possible.
aProcess = self.get_process()
if aProcess is not None:
(module, procedure, offset) = aProcess.split_label(label)
else:
(module, procedure, offset) = _ModuleContainer.split_label(label)
# If a module name is given that doesn't match ours,
# raise an exception.
if module and not self.match_name(module):
raise RuntimeError("Label does not belong to this module")
# Resolve the procedure if given.
if procedure:
address = self.resolve(procedure)
if address is None:
# If it's a debug symbol, use the symbol.
address = self.resolve_symbol(procedure)
# If it's the keyword "start" use the entry point.
if address is None and procedure == "start":
address = self.get_entry_point()
# The procedure was not found.
if address is None:
if not module:
module = self.get_name()
msg = "Can't find procedure %s in module %s"
raise RuntimeError(msg % (procedure, module))
# If no procedure is given use the base address of the module.
else:
address = self.get_base()
# Add the offset if given and return the resolved address.
if offset:
address = address + offset
return address | [
"def",
"resolve_label",
"(",
"self",
",",
"label",
")",
":",
"# Split the label into it's components.",
"# Use the fuzzy mode whenever possible.",
"aProcess",
"=",
"self",
".",
"get_process",
"(",
")",
"if",
"aProcess",
"is",
"not",
"None",
":",
"(",
"module",
",",
... | Resolves a label for this module only. If the label refers to another
module, an exception is raised.
@type label: str
@param label: Label to resolve.
@rtype: int
@return: Memory address pointed to by the label.
@raise ValueError: The label is malformed or impossible to resolve.
@raise RuntimeError: Cannot resolve the module or function. | [
"Resolves",
"a",
"label",
"for",
"this",
"module",
"only",
".",
"If",
"the",
"label",
"refers",
"to",
"another",
"module",
"an",
"exception",
"is",
"raised",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/module.py#L741-L795 | train | 209,649 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/module.py | _ModuleContainer.clear_modules | def clear_modules(self):
"""
Clears the modules snapshot.
"""
for aModule in compat.itervalues(self.__moduleDict):
aModule.clear()
self.__moduleDict = dict() | python | def clear_modules(self):
"""
Clears the modules snapshot.
"""
for aModule in compat.itervalues(self.__moduleDict):
aModule.clear()
self.__moduleDict = dict() | [
"def",
"clear_modules",
"(",
"self",
")",
":",
"for",
"aModule",
"in",
"compat",
".",
"itervalues",
"(",
"self",
".",
"__moduleDict",
")",
":",
"aModule",
".",
"clear",
"(",
")",
"self",
".",
"__moduleDict",
"=",
"dict",
"(",
")"
] | Clears the modules snapshot. | [
"Clears",
"the",
"modules",
"snapshot",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/module.py#L1093-L1099 | train | 209,650 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/module.py | _ModuleContainer.parse_label | def parse_label(module = None, function = None, offset = None):
"""
Creates a label from a module and a function name, plus an offset.
@warning: This method only creates the label, it doesn't make sure the
label actually points to a valid memory location.
@type module: None or str
@param module: (Optional) Module name.
@type function: None, str or int
@param function: (Optional) Function name or ordinal.
@type offset: None or int
@param offset: (Optional) Offset value.
If C{function} is specified, offset from the function.
If C{function} is C{None}, offset from the module.
@rtype: str
@return:
Label representing the given function in the given module.
@raise ValueError:
The module or function name contain invalid characters.
"""
# TODO
# Invalid characters should be escaped or filtered.
# Convert ordinals to strings.
try:
function = "#0x%x" % function
except TypeError:
pass
# Validate the parameters.
if module is not None and ('!' in module or '+' in module):
raise ValueError("Invalid module name: %s" % module)
if function is not None and ('!' in function or '+' in function):
raise ValueError("Invalid function name: %s" % function)
# Parse the label.
if module:
if function:
if offset:
label = "%s!%s+0x%x" % (module, function, offset)
else:
label = "%s!%s" % (module, function)
else:
if offset:
## label = "%s+0x%x!" % (module, offset)
label = "%s!0x%x" % (module, offset)
else:
label = "%s!" % module
else:
if function:
if offset:
label = "!%s+0x%x" % (function, offset)
else:
label = "!%s" % function
else:
if offset:
label = "0x%x" % offset
else:
label = "0x0"
return label | python | def parse_label(module = None, function = None, offset = None):
"""
Creates a label from a module and a function name, plus an offset.
@warning: This method only creates the label, it doesn't make sure the
label actually points to a valid memory location.
@type module: None or str
@param module: (Optional) Module name.
@type function: None, str or int
@param function: (Optional) Function name or ordinal.
@type offset: None or int
@param offset: (Optional) Offset value.
If C{function} is specified, offset from the function.
If C{function} is C{None}, offset from the module.
@rtype: str
@return:
Label representing the given function in the given module.
@raise ValueError:
The module or function name contain invalid characters.
"""
# TODO
# Invalid characters should be escaped or filtered.
# Convert ordinals to strings.
try:
function = "#0x%x" % function
except TypeError:
pass
# Validate the parameters.
if module is not None and ('!' in module or '+' in module):
raise ValueError("Invalid module name: %s" % module)
if function is not None and ('!' in function or '+' in function):
raise ValueError("Invalid function name: %s" % function)
# Parse the label.
if module:
if function:
if offset:
label = "%s!%s+0x%x" % (module, function, offset)
else:
label = "%s!%s" % (module, function)
else:
if offset:
## label = "%s+0x%x!" % (module, offset)
label = "%s!0x%x" % (module, offset)
else:
label = "%s!" % module
else:
if function:
if offset:
label = "!%s+0x%x" % (function, offset)
else:
label = "!%s" % function
else:
if offset:
label = "0x%x" % offset
else:
label = "0x0"
return label | [
"def",
"parse_label",
"(",
"module",
"=",
"None",
",",
"function",
"=",
"None",
",",
"offset",
"=",
"None",
")",
":",
"# TODO",
"# Invalid characters should be escaped or filtered.",
"# Convert ordinals to strings.",
"try",
":",
"function",
"=",
"\"#0x%x\"",
"%",
"f... | Creates a label from a module and a function name, plus an offset.
@warning: This method only creates the label, it doesn't make sure the
label actually points to a valid memory location.
@type module: None or str
@param module: (Optional) Module name.
@type function: None, str or int
@param function: (Optional) Function name or ordinal.
@type offset: None or int
@param offset: (Optional) Offset value.
If C{function} is specified, offset from the function.
If C{function} is C{None}, offset from the module.
@rtype: str
@return:
Label representing the given function in the given module.
@raise ValueError:
The module or function name contain invalid characters. | [
"Creates",
"a",
"label",
"from",
"a",
"module",
"and",
"a",
"function",
"name",
"plus",
"an",
"offset",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/module.py#L1104-L1172 | train | 209,651 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/module.py | _ModuleContainer.split_label_fuzzy | def split_label_fuzzy(self, label):
"""
Splits a label entered as user input.
It's more flexible in it's syntax parsing than the L{split_label_strict}
method, as it allows the exclamation mark (B{C{!}}) to be omitted. The
ambiguity is resolved by searching the modules in the snapshot to guess
if a label refers to a module or a function. It also tries to rebuild
labels when they contain hardcoded addresses.
@warning: This method only parses the label, it doesn't make sure the
label actually points to a valid memory location.
@type label: str
@param label: Label to split.
@rtype: tuple( str or None, str or int or None, int or None )
@return: Tuple containing the C{module} name,
the C{function} name or ordinal, and the C{offset} value.
If the label doesn't specify a module,
then C{module} is C{None}.
If the label doesn't specify a function,
then C{function} is C{None}.
If the label doesn't specify an offset,
then C{offset} is C{0}.
@raise ValueError: The label is malformed.
"""
module = function = None
offset = 0
# Special case: None
if not label:
label = compat.b("0x0")
else:
# Remove all blanks.
label = label.replace(compat.b(' '), compat.b(''))
label = label.replace(compat.b('\t'), compat.b(''))
label = label.replace(compat.b('\r'), compat.b(''))
label = label.replace(compat.b('\n'), compat.b(''))
# Special case: empty label.
if not label:
label = compat.b("0x0")
# If an exclamation sign is present, we know we can parse it strictly.
if compat.b('!') in label:
return self.split_label_strict(label)
## # Try to parse it strictly, on error do it the fuzzy way.
## try:
## return self.split_label(label)
## except ValueError:
## pass
# * + offset
if compat.b('+') in label:
try:
prefix, offset = label.split(compat.b('+'))
except ValueError:
raise ValueError("Malformed label: %s" % label)
try:
offset = HexInput.integer(offset)
except ValueError:
raise ValueError("Malformed label: %s" % label)
label = prefix
# This parses both filenames and base addresses.
modobj = self.get_module_by_name(label)
if modobj:
# module
# module + offset
module = modobj.get_name()
else:
# TODO
# If 0xAAAAAAAA + 0xBBBBBBBB is given,
# A is interpreted as a module base address,
# and B as an offset.
# If that fails, it'd be good to add A+B and try to
# use the nearest loaded module.
# offset
# base address + offset (when no module has that base address)
try:
address = HexInput.integer(label)
if offset:
# If 0xAAAAAAAA + 0xBBBBBBBB is given,
# A is interpreted as a module base address,
# and B as an offset.
# If that fails, we get here, meaning no module was found
# at A. Then add up A+B and work with that as a hardcoded
# address.
offset = address + offset
else:
# If the label is a hardcoded address, we get here.
offset = address
# If only a hardcoded address is given,
# rebuild the label using get_label_at_address.
# Then parse it again, but this time strictly,
# both because there is no need for fuzzy syntax and
# to prevent an infinite recursion if there's a bug here.
try:
new_label = self.get_label_at_address(offset)
module, function, offset = \
self.split_label_strict(new_label)
except ValueError:
pass
# function
# function + offset
except ValueError:
function = label
# Convert function ordinal strings into integers.
if function and function.startswith(compat.b('#')):
try:
function = HexInput.integer(function[1:])
except ValueError:
pass
# Convert null offsets to None.
if not offset:
offset = None
return (module, function, offset) | python | def split_label_fuzzy(self, label):
"""
Splits a label entered as user input.
It's more flexible in it's syntax parsing than the L{split_label_strict}
method, as it allows the exclamation mark (B{C{!}}) to be omitted. The
ambiguity is resolved by searching the modules in the snapshot to guess
if a label refers to a module or a function. It also tries to rebuild
labels when they contain hardcoded addresses.
@warning: This method only parses the label, it doesn't make sure the
label actually points to a valid memory location.
@type label: str
@param label: Label to split.
@rtype: tuple( str or None, str or int or None, int or None )
@return: Tuple containing the C{module} name,
the C{function} name or ordinal, and the C{offset} value.
If the label doesn't specify a module,
then C{module} is C{None}.
If the label doesn't specify a function,
then C{function} is C{None}.
If the label doesn't specify an offset,
then C{offset} is C{0}.
@raise ValueError: The label is malformed.
"""
module = function = None
offset = 0
# Special case: None
if not label:
label = compat.b("0x0")
else:
# Remove all blanks.
label = label.replace(compat.b(' '), compat.b(''))
label = label.replace(compat.b('\t'), compat.b(''))
label = label.replace(compat.b('\r'), compat.b(''))
label = label.replace(compat.b('\n'), compat.b(''))
# Special case: empty label.
if not label:
label = compat.b("0x0")
# If an exclamation sign is present, we know we can parse it strictly.
if compat.b('!') in label:
return self.split_label_strict(label)
## # Try to parse it strictly, on error do it the fuzzy way.
## try:
## return self.split_label(label)
## except ValueError:
## pass
# * + offset
if compat.b('+') in label:
try:
prefix, offset = label.split(compat.b('+'))
except ValueError:
raise ValueError("Malformed label: %s" % label)
try:
offset = HexInput.integer(offset)
except ValueError:
raise ValueError("Malformed label: %s" % label)
label = prefix
# This parses both filenames and base addresses.
modobj = self.get_module_by_name(label)
if modobj:
# module
# module + offset
module = modobj.get_name()
else:
# TODO
# If 0xAAAAAAAA + 0xBBBBBBBB is given,
# A is interpreted as a module base address,
# and B as an offset.
# If that fails, it'd be good to add A+B and try to
# use the nearest loaded module.
# offset
# base address + offset (when no module has that base address)
try:
address = HexInput.integer(label)
if offset:
# If 0xAAAAAAAA + 0xBBBBBBBB is given,
# A is interpreted as a module base address,
# and B as an offset.
# If that fails, we get here, meaning no module was found
# at A. Then add up A+B and work with that as a hardcoded
# address.
offset = address + offset
else:
# If the label is a hardcoded address, we get here.
offset = address
# If only a hardcoded address is given,
# rebuild the label using get_label_at_address.
# Then parse it again, but this time strictly,
# both because there is no need for fuzzy syntax and
# to prevent an infinite recursion if there's a bug here.
try:
new_label = self.get_label_at_address(offset)
module, function, offset = \
self.split_label_strict(new_label)
except ValueError:
pass
# function
# function + offset
except ValueError:
function = label
# Convert function ordinal strings into integers.
if function and function.startswith(compat.b('#')):
try:
function = HexInput.integer(function[1:])
except ValueError:
pass
# Convert null offsets to None.
if not offset:
offset = None
return (module, function, offset) | [
"def",
"split_label_fuzzy",
"(",
"self",
",",
"label",
")",
":",
"module",
"=",
"function",
"=",
"None",
"offset",
"=",
"0",
"# Special case: None",
"if",
"not",
"label",
":",
"label",
"=",
"compat",
".",
"b",
"(",
"\"0x0\"",
")",
"else",
":",
"# Remove ... | Splits a label entered as user input.
It's more flexible in it's syntax parsing than the L{split_label_strict}
method, as it allows the exclamation mark (B{C{!}}) to be omitted. The
ambiguity is resolved by searching the modules in the snapshot to guess
if a label refers to a module or a function. It also tries to rebuild
labels when they contain hardcoded addresses.
@warning: This method only parses the label, it doesn't make sure the
label actually points to a valid memory location.
@type label: str
@param label: Label to split.
@rtype: tuple( str or None, str or int or None, int or None )
@return: Tuple containing the C{module} name,
the C{function} name or ordinal, and the C{offset} value.
If the label doesn't specify a module,
then C{module} is C{None}.
If the label doesn't specify a function,
then C{function} is C{None}.
If the label doesn't specify an offset,
then C{offset} is C{0}.
@raise ValueError: The label is malformed. | [
"Splits",
"a",
"label",
"entered",
"as",
"user",
"input",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/module.py#L1317-L1450 | train | 209,652 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/module.py | _ModuleContainer.sanitize_label | def sanitize_label(self, label):
"""
Converts a label taken from user input into a well-formed label.
@type label: str
@param label: Label taken from user input.
@rtype: str
@return: Sanitized label.
"""
(module, function, offset) = self.split_label_fuzzy(label)
label = self.parse_label(module, function, offset)
return label | python | def sanitize_label(self, label):
"""
Converts a label taken from user input into a well-formed label.
@type label: str
@param label: Label taken from user input.
@rtype: str
@return: Sanitized label.
"""
(module, function, offset) = self.split_label_fuzzy(label)
label = self.parse_label(module, function, offset)
return label | [
"def",
"sanitize_label",
"(",
"self",
",",
"label",
")",
":",
"(",
"module",
",",
"function",
",",
"offset",
")",
"=",
"self",
".",
"split_label_fuzzy",
"(",
"label",
")",
"label",
"=",
"self",
".",
"parse_label",
"(",
"module",
",",
"function",
",",
"... | Converts a label taken from user input into a well-formed label.
@type label: str
@param label: Label taken from user input.
@rtype: str
@return: Sanitized label. | [
"Converts",
"a",
"label",
"taken",
"from",
"user",
"input",
"into",
"a",
"well",
"-",
"formed",
"label",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/module.py#L1502-L1514 | train | 209,653 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/module.py | _ModuleContainer.resolve_label | def resolve_label(self, label):
"""
Resolve the memory address of the given label.
@note:
If multiple modules with the same name are loaded,
the label may be resolved at any of them. For a more precise
way to resolve functions use the base address to get the L{Module}
object (see L{Process.get_module}) and then call L{Module.resolve}.
If no module name is specified in the label, the function may be
resolved in any loaded module. If you want to resolve all functions
with that name in all processes, call L{Process.iter_modules} to
iterate through all loaded modules, and then try to resolve the
function in each one of them using L{Module.resolve}.
@type label: str
@param label: Label to resolve.
@rtype: int
@return: Memory address pointed to by the label.
@raise ValueError: The label is malformed or impossible to resolve.
@raise RuntimeError: Cannot resolve the module or function.
"""
# Split the label into module, function and offset components.
module, function, offset = self.split_label_fuzzy(label)
# Resolve the components into a memory address.
address = self.resolve_label_components(module, function, offset)
# Return the memory address.
return address | python | def resolve_label(self, label):
"""
Resolve the memory address of the given label.
@note:
If multiple modules with the same name are loaded,
the label may be resolved at any of them. For a more precise
way to resolve functions use the base address to get the L{Module}
object (see L{Process.get_module}) and then call L{Module.resolve}.
If no module name is specified in the label, the function may be
resolved in any loaded module. If you want to resolve all functions
with that name in all processes, call L{Process.iter_modules} to
iterate through all loaded modules, and then try to resolve the
function in each one of them using L{Module.resolve}.
@type label: str
@param label: Label to resolve.
@rtype: int
@return: Memory address pointed to by the label.
@raise ValueError: The label is malformed or impossible to resolve.
@raise RuntimeError: Cannot resolve the module or function.
"""
# Split the label into module, function and offset components.
module, function, offset = self.split_label_fuzzy(label)
# Resolve the components into a memory address.
address = self.resolve_label_components(module, function, offset)
# Return the memory address.
return address | [
"def",
"resolve_label",
"(",
"self",
",",
"label",
")",
":",
"# Split the label into module, function and offset components.",
"module",
",",
"function",
",",
"offset",
"=",
"self",
".",
"split_label_fuzzy",
"(",
"label",
")",
"# Resolve the components into a memory address... | Resolve the memory address of the given label.
@note:
If multiple modules with the same name are loaded,
the label may be resolved at any of them. For a more precise
way to resolve functions use the base address to get the L{Module}
object (see L{Process.get_module}) and then call L{Module.resolve}.
If no module name is specified in the label, the function may be
resolved in any loaded module. If you want to resolve all functions
with that name in all processes, call L{Process.iter_modules} to
iterate through all loaded modules, and then try to resolve the
function in each one of them using L{Module.resolve}.
@type label: str
@param label: Label to resolve.
@rtype: int
@return: Memory address pointed to by the label.
@raise ValueError: The label is malformed or impossible to resolve.
@raise RuntimeError: Cannot resolve the module or function. | [
"Resolve",
"the",
"memory",
"address",
"of",
"the",
"given",
"label",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/module.py#L1516-L1549 | train | 209,654 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/module.py | _ModuleContainer.get_symbols | def get_symbols(self):
"""
Returns the debugging symbols for all modules in this snapshot.
The symbols are automatically loaded when needed.
@rtype: list of tuple( str, int, int )
@return: List of symbols.
Each symbol is represented by a tuple that contains:
- Symbol name
- Symbol memory address
- Symbol size in bytes
"""
symbols = list()
for aModule in self.iter_modules():
for symbol in aModule.iter_symbols():
symbols.append(symbol)
return symbols | python | def get_symbols(self):
"""
Returns the debugging symbols for all modules in this snapshot.
The symbols are automatically loaded when needed.
@rtype: list of tuple( str, int, int )
@return: List of symbols.
Each symbol is represented by a tuple that contains:
- Symbol name
- Symbol memory address
- Symbol size in bytes
"""
symbols = list()
for aModule in self.iter_modules():
for symbol in aModule.iter_symbols():
symbols.append(symbol)
return symbols | [
"def",
"get_symbols",
"(",
"self",
")",
":",
"symbols",
"=",
"list",
"(",
")",
"for",
"aModule",
"in",
"self",
".",
"iter_modules",
"(",
")",
":",
"for",
"symbol",
"in",
"aModule",
".",
"iter_symbols",
"(",
")",
":",
"symbols",
".",
"append",
"(",
"s... | Returns the debugging symbols for all modules in this snapshot.
The symbols are automatically loaded when needed.
@rtype: list of tuple( str, int, int )
@return: List of symbols.
Each symbol is represented by a tuple that contains:
- Symbol name
- Symbol memory address
- Symbol size in bytes | [
"Returns",
"the",
"debugging",
"symbols",
"for",
"all",
"modules",
"in",
"this",
"snapshot",
".",
"The",
"symbols",
"are",
"automatically",
"loaded",
"when",
"needed",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/module.py#L1798-L1814 | train | 209,655 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/module.py | _ModuleContainer.get_symbol_at_address | def get_symbol_at_address(self, address):
"""
Tries to find the closest matching symbol for the given address.
@type address: int
@param address: Memory address to query.
@rtype: None or tuple( str, int, int )
@return: Returns a tuple consisting of:
- Name
- Address
- Size (in bytes)
Returns C{None} if no symbol could be matched.
"""
# Any module may have symbols pointing anywhere in memory, so there's
# no easy way to optimize this. I guess we're stuck with brute force.
found = None
for (SymbolName, SymbolAddress, SymbolSize) in self.iter_symbols():
if SymbolAddress > address:
continue
if SymbolAddress == address:
found = (SymbolName, SymbolAddress, SymbolSize)
break
if SymbolAddress < address:
if found and (address - found[1]) < (address - SymbolAddress):
continue
else:
found = (SymbolName, SymbolAddress, SymbolSize)
return found | python | def get_symbol_at_address(self, address):
"""
Tries to find the closest matching symbol for the given address.
@type address: int
@param address: Memory address to query.
@rtype: None or tuple( str, int, int )
@return: Returns a tuple consisting of:
- Name
- Address
- Size (in bytes)
Returns C{None} if no symbol could be matched.
"""
# Any module may have symbols pointing anywhere in memory, so there's
# no easy way to optimize this. I guess we're stuck with brute force.
found = None
for (SymbolName, SymbolAddress, SymbolSize) in self.iter_symbols():
if SymbolAddress > address:
continue
if SymbolAddress == address:
found = (SymbolName, SymbolAddress, SymbolSize)
break
if SymbolAddress < address:
if found and (address - found[1]) < (address - SymbolAddress):
continue
else:
found = (SymbolName, SymbolAddress, SymbolSize)
return found | [
"def",
"get_symbol_at_address",
"(",
"self",
",",
"address",
")",
":",
"# Any module may have symbols pointing anywhere in memory, so there's",
"# no easy way to optimize this. I guess we're stuck with brute force.",
"found",
"=",
"None",
"for",
"(",
"SymbolName",
",",
"SymbolAddre... | Tries to find the closest matching symbol for the given address.
@type address: int
@param address: Memory address to query.
@rtype: None or tuple( str, int, int )
@return: Returns a tuple consisting of:
- Name
- Address
- Size (in bytes)
Returns C{None} if no symbol could be matched. | [
"Tries",
"to",
"find",
"the",
"closest",
"matching",
"symbol",
"for",
"the",
"given",
"address",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/module.py#L1857-L1887 | train | 209,656 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/module.py | _ModuleContainer._add_module | def _add_module(self, aModule):
"""
Private method to add a module object to the snapshot.
@type aModule: L{Module}
@param aModule: Module object.
"""
## if not isinstance(aModule, Module):
## if hasattr(aModule, '__class__'):
## typename = aModule.__class__.__name__
## else:
## typename = str(type(aModule))
## msg = "Expected Module, got %s instead" % typename
## raise TypeError(msg)
lpBaseOfDll = aModule.get_base()
## if lpBaseOfDll in self.__moduleDict:
## msg = "Module already exists: %d" % lpBaseOfDll
## raise KeyError(msg)
aModule.set_process(self)
self.__moduleDict[lpBaseOfDll] = aModule | python | def _add_module(self, aModule):
"""
Private method to add a module object to the snapshot.
@type aModule: L{Module}
@param aModule: Module object.
"""
## if not isinstance(aModule, Module):
## if hasattr(aModule, '__class__'):
## typename = aModule.__class__.__name__
## else:
## typename = str(type(aModule))
## msg = "Expected Module, got %s instead" % typename
## raise TypeError(msg)
lpBaseOfDll = aModule.get_base()
## if lpBaseOfDll in self.__moduleDict:
## msg = "Module already exists: %d" % lpBaseOfDll
## raise KeyError(msg)
aModule.set_process(self)
self.__moduleDict[lpBaseOfDll] = aModule | [
"def",
"_add_module",
"(",
"self",
",",
"aModule",
")",
":",
"## if not isinstance(aModule, Module):",
"## if hasattr(aModule, '__class__'):",
"## typename = aModule.__class__.__name__",
"## else:",
"## typename = str(type(aModule))"... | Private method to add a module object to the snapshot.
@type aModule: L{Module}
@param aModule: Module object. | [
"Private",
"method",
"to",
"add",
"a",
"module",
"object",
"to",
"the",
"snapshot",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/module.py#L1892-L1911 | train | 209,657 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/module.py | _ModuleContainer._del_module | def _del_module(self, lpBaseOfDll):
"""
Private method to remove a module object from the snapshot.
@type lpBaseOfDll: int
@param lpBaseOfDll: Module base address.
"""
try:
aModule = self.__moduleDict[lpBaseOfDll]
del self.__moduleDict[lpBaseOfDll]
except KeyError:
aModule = None
msg = "Unknown base address %d" % HexDump.address(lpBaseOfDll)
warnings.warn(msg, RuntimeWarning)
if aModule:
aModule.clear() | python | def _del_module(self, lpBaseOfDll):
"""
Private method to remove a module object from the snapshot.
@type lpBaseOfDll: int
@param lpBaseOfDll: Module base address.
"""
try:
aModule = self.__moduleDict[lpBaseOfDll]
del self.__moduleDict[lpBaseOfDll]
except KeyError:
aModule = None
msg = "Unknown base address %d" % HexDump.address(lpBaseOfDll)
warnings.warn(msg, RuntimeWarning)
if aModule:
aModule.clear() | [
"def",
"_del_module",
"(",
"self",
",",
"lpBaseOfDll",
")",
":",
"try",
":",
"aModule",
"=",
"self",
".",
"__moduleDict",
"[",
"lpBaseOfDll",
"]",
"del",
"self",
".",
"__moduleDict",
"[",
"lpBaseOfDll",
"]",
"except",
"KeyError",
":",
"aModule",
"=",
"None... | Private method to remove a module object from the snapshot.
@type lpBaseOfDll: int
@param lpBaseOfDll: Module base address. | [
"Private",
"method",
"to",
"remove",
"a",
"module",
"object",
"from",
"the",
"snapshot",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/module.py#L1913-L1928 | train | 209,658 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/module.py | _ModuleContainer.__add_loaded_module | def __add_loaded_module(self, event):
"""
Private method to automatically add new module objects from debug events.
@type event: L{Event}
@param event: Event object.
"""
lpBaseOfDll = event.get_module_base()
hFile = event.get_file_handle()
## if not self.has_module(lpBaseOfDll): # XXX this would trigger a scan
if lpBaseOfDll not in self.__moduleDict:
fileName = event.get_filename()
if not fileName:
fileName = None
if hasattr(event, 'get_start_address'):
EntryPoint = event.get_start_address()
else:
EntryPoint = None
aModule = Module(lpBaseOfDll, hFile, fileName = fileName,
EntryPoint = EntryPoint,
process = self)
self._add_module(aModule)
else:
aModule = self.get_module(lpBaseOfDll)
if not aModule.hFile and hFile not in (None, 0,
win32.INVALID_HANDLE_VALUE):
aModule.hFile = hFile
if not aModule.process:
aModule.process = self
if aModule.EntryPoint is None and \
hasattr(event, 'get_start_address'):
aModule.EntryPoint = event.get_start_address()
if not aModule.fileName:
fileName = event.get_filename()
if fileName:
aModule.fileName = fileName | python | def __add_loaded_module(self, event):
"""
Private method to automatically add new module objects from debug events.
@type event: L{Event}
@param event: Event object.
"""
lpBaseOfDll = event.get_module_base()
hFile = event.get_file_handle()
## if not self.has_module(lpBaseOfDll): # XXX this would trigger a scan
if lpBaseOfDll not in self.__moduleDict:
fileName = event.get_filename()
if not fileName:
fileName = None
if hasattr(event, 'get_start_address'):
EntryPoint = event.get_start_address()
else:
EntryPoint = None
aModule = Module(lpBaseOfDll, hFile, fileName = fileName,
EntryPoint = EntryPoint,
process = self)
self._add_module(aModule)
else:
aModule = self.get_module(lpBaseOfDll)
if not aModule.hFile and hFile not in (None, 0,
win32.INVALID_HANDLE_VALUE):
aModule.hFile = hFile
if not aModule.process:
aModule.process = self
if aModule.EntryPoint is None and \
hasattr(event, 'get_start_address'):
aModule.EntryPoint = event.get_start_address()
if not aModule.fileName:
fileName = event.get_filename()
if fileName:
aModule.fileName = fileName | [
"def",
"__add_loaded_module",
"(",
"self",
",",
"event",
")",
":",
"lpBaseOfDll",
"=",
"event",
".",
"get_module_base",
"(",
")",
"hFile",
"=",
"event",
".",
"get_file_handle",
"(",
")",
"## if not self.has_module(lpBaseOfDll): # XXX this would trigger a scan",
... | Private method to automatically add new module objects from debug events.
@type event: L{Event}
@param event: Event object. | [
"Private",
"method",
"to",
"automatically",
"add",
"new",
"module",
"objects",
"from",
"debug",
"events",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/module.py#L1930-L1965 | train | 209,659 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/module.py | _ModuleContainer._notify_unload_dll | def _notify_unload_dll(self, event):
"""
Notify the release of a loaded module.
This is done automatically by the L{Debug} class, you shouldn't need
to call it yourself.
@type event: L{UnloadDLLEvent}
@param event: Unload DLL event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} otherwise.
"""
lpBaseOfDll = event.get_module_base()
## if self.has_module(lpBaseOfDll): # XXX this would trigger a scan
if lpBaseOfDll in self.__moduleDict:
self._del_module(lpBaseOfDll)
return True | python | def _notify_unload_dll(self, event):
"""
Notify the release of a loaded module.
This is done automatically by the L{Debug} class, you shouldn't need
to call it yourself.
@type event: L{UnloadDLLEvent}
@param event: Unload DLL event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} otherwise.
"""
lpBaseOfDll = event.get_module_base()
## if self.has_module(lpBaseOfDll): # XXX this would trigger a scan
if lpBaseOfDll in self.__moduleDict:
self._del_module(lpBaseOfDll)
return True | [
"def",
"_notify_unload_dll",
"(",
"self",
",",
"event",
")",
":",
"lpBaseOfDll",
"=",
"event",
".",
"get_module_base",
"(",
")",
"## if self.has_module(lpBaseOfDll): # XXX this would trigger a scan",
"if",
"lpBaseOfDll",
"in",
"self",
".",
"__moduleDict",
":",
"... | Notify the release of a loaded module.
This is done automatically by the L{Debug} class, you shouldn't need
to call it yourself.
@type event: L{UnloadDLLEvent}
@param event: Unload DLL event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} otherwise. | [
"Notify",
"the",
"release",
"of",
"a",
"loaded",
"module",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/module.py#L1999-L2016 | train | 209,660 |
fabioz/PyDev.Debugger | _pydev_bundle/pydev_console_utils.py | BaseInterpreterInterface.connectToDebugger | def connectToDebugger(self, debuggerPort, debugger_options=None):
'''
Used to show console with variables connection.
Mainly, monkey-patches things in the debugger structure so that the debugger protocol works.
'''
if debugger_options is None:
debugger_options = {}
env_key = "PYDEVD_EXTRA_ENVS"
if env_key in debugger_options:
for (env_name, value) in dict_iter_items(debugger_options[env_key]):
existing_value = os.environ.get(env_name, None)
if existing_value:
os.environ[env_name] = "%s%c%s" % (existing_value, os.path.pathsep, value)
else:
os.environ[env_name] = value
if env_name == "PYTHONPATH":
sys.path.append(value)
del debugger_options[env_key]
def do_connect_to_debugger():
try:
# Try to import the packages needed to attach the debugger
import pydevd
from _pydev_imps._pydev_saved_modules import threading
except:
# This happens on Jython embedded in host eclipse
traceback.print_exc()
sys.stderr.write('pydevd is not available, cannot connect\n', )
from _pydevd_bundle.pydevd_constants import set_thread_id
from _pydev_bundle import pydev_localhost
set_thread_id(threading.currentThread(), "console_main")
VIRTUAL_FRAME_ID = "1" # matches PyStackFrameConsole.java
VIRTUAL_CONSOLE_ID = "console_main" # matches PyThreadConsole.java
f = FakeFrame()
f.f_back = None
f.f_globals = {} # As globals=locals here, let's simply let it empty (and save a bit of network traffic).
f.f_locals = self.get_namespace()
self.debugger = pydevd.PyDB()
self.debugger.add_fake_frame(thread_id=VIRTUAL_CONSOLE_ID, frame_id=VIRTUAL_FRAME_ID, frame=f)
try:
pydevd.apply_debugger_options(debugger_options)
self.debugger.connect(pydev_localhost.get_localhost(), debuggerPort)
self.debugger.prepare_to_run()
self.debugger.disable_tracing()
except:
traceback.print_exc()
sys.stderr.write('Failed to connect to target debugger.\n')
# Register to process commands when idle
self.debugrunning = False
try:
import pydevconsole
pydevconsole.set_debug_hook(self.debugger.process_internal_commands)
except:
traceback.print_exc()
sys.stderr.write('Version of Python does not support debuggable Interactive Console.\n')
# Important: it has to be really enabled in the main thread, so, schedule
# it to run in the main thread.
self.exec_queue.put(do_connect_to_debugger)
return ('connect complete',) | python | def connectToDebugger(self, debuggerPort, debugger_options=None):
'''
Used to show console with variables connection.
Mainly, monkey-patches things in the debugger structure so that the debugger protocol works.
'''
if debugger_options is None:
debugger_options = {}
env_key = "PYDEVD_EXTRA_ENVS"
if env_key in debugger_options:
for (env_name, value) in dict_iter_items(debugger_options[env_key]):
existing_value = os.environ.get(env_name, None)
if existing_value:
os.environ[env_name] = "%s%c%s" % (existing_value, os.path.pathsep, value)
else:
os.environ[env_name] = value
if env_name == "PYTHONPATH":
sys.path.append(value)
del debugger_options[env_key]
def do_connect_to_debugger():
try:
# Try to import the packages needed to attach the debugger
import pydevd
from _pydev_imps._pydev_saved_modules import threading
except:
# This happens on Jython embedded in host eclipse
traceback.print_exc()
sys.stderr.write('pydevd is not available, cannot connect\n', )
from _pydevd_bundle.pydevd_constants import set_thread_id
from _pydev_bundle import pydev_localhost
set_thread_id(threading.currentThread(), "console_main")
VIRTUAL_FRAME_ID = "1" # matches PyStackFrameConsole.java
VIRTUAL_CONSOLE_ID = "console_main" # matches PyThreadConsole.java
f = FakeFrame()
f.f_back = None
f.f_globals = {} # As globals=locals here, let's simply let it empty (and save a bit of network traffic).
f.f_locals = self.get_namespace()
self.debugger = pydevd.PyDB()
self.debugger.add_fake_frame(thread_id=VIRTUAL_CONSOLE_ID, frame_id=VIRTUAL_FRAME_ID, frame=f)
try:
pydevd.apply_debugger_options(debugger_options)
self.debugger.connect(pydev_localhost.get_localhost(), debuggerPort)
self.debugger.prepare_to_run()
self.debugger.disable_tracing()
except:
traceback.print_exc()
sys.stderr.write('Failed to connect to target debugger.\n')
# Register to process commands when idle
self.debugrunning = False
try:
import pydevconsole
pydevconsole.set_debug_hook(self.debugger.process_internal_commands)
except:
traceback.print_exc()
sys.stderr.write('Version of Python does not support debuggable Interactive Console.\n')
# Important: it has to be really enabled in the main thread, so, schedule
# it to run in the main thread.
self.exec_queue.put(do_connect_to_debugger)
return ('connect complete',) | [
"def",
"connectToDebugger",
"(",
"self",
",",
"debuggerPort",
",",
"debugger_options",
"=",
"None",
")",
":",
"if",
"debugger_options",
"is",
"None",
":",
"debugger_options",
"=",
"{",
"}",
"env_key",
"=",
"\"PYDEVD_EXTRA_ENVS\"",
"if",
"env_key",
"in",
"debugge... | Used to show console with variables connection.
Mainly, monkey-patches things in the debugger structure so that the debugger protocol works. | [
"Used",
"to",
"show",
"console",
"with",
"variables",
"connection",
".",
"Mainly",
"monkey",
"-",
"patches",
"things",
"in",
"the",
"debugger",
"structure",
"so",
"that",
"the",
"debugger",
"protocol",
"works",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_bundle/pydev_console_utils.py#L521-L588 | train | 209,661 |
fabioz/PyDev.Debugger | pydev_ipython/qt_loaders.py | commit_api | def commit_api(api):
"""Commit to a particular API, and trigger ImportErrors on subsequent
dangerous imports"""
if api == QT_API_PYSIDE:
ID.forbid('PyQt4')
ID.forbid('PyQt5')
else:
ID.forbid('PySide') | python | def commit_api(api):
"""Commit to a particular API, and trigger ImportErrors on subsequent
dangerous imports"""
if api == QT_API_PYSIDE:
ID.forbid('PyQt4')
ID.forbid('PyQt5')
else:
ID.forbid('PySide') | [
"def",
"commit_api",
"(",
"api",
")",
":",
"if",
"api",
"==",
"QT_API_PYSIDE",
":",
"ID",
".",
"forbid",
"(",
"'PyQt4'",
")",
"ID",
".",
"forbid",
"(",
"'PyQt5'",
")",
"else",
":",
"ID",
".",
"forbid",
"(",
"'PySide'",
")"
] | Commit to a particular API, and trigger ImportErrors on subsequent
dangerous imports | [
"Commit",
"to",
"a",
"particular",
"API",
"and",
"trigger",
"ImportErrors",
"on",
"subsequent",
"dangerous",
"imports"
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydev_ipython/qt_loaders.py#L52-L60 | train | 209,662 |
fabioz/PyDev.Debugger | pydev_ipython/qt_loaders.py | loaded_api | def loaded_api():
"""Return which API is loaded, if any
If this returns anything besides None,
importing any other Qt binding is unsafe.
Returns
-------
None, 'pyside', 'pyqt', or 'pyqtv1'
"""
if 'PyQt4.QtCore' in sys.modules:
if qtapi_version() == 2:
return QT_API_PYQT
else:
return QT_API_PYQTv1
elif 'PySide.QtCore' in sys.modules:
return QT_API_PYSIDE
elif 'PyQt5.QtCore' in sys.modules:
return QT_API_PYQT5
return None | python | def loaded_api():
"""Return which API is loaded, if any
If this returns anything besides None,
importing any other Qt binding is unsafe.
Returns
-------
None, 'pyside', 'pyqt', or 'pyqtv1'
"""
if 'PyQt4.QtCore' in sys.modules:
if qtapi_version() == 2:
return QT_API_PYQT
else:
return QT_API_PYQTv1
elif 'PySide.QtCore' in sys.modules:
return QT_API_PYSIDE
elif 'PyQt5.QtCore' in sys.modules:
return QT_API_PYQT5
return None | [
"def",
"loaded_api",
"(",
")",
":",
"if",
"'PyQt4.QtCore'",
"in",
"sys",
".",
"modules",
":",
"if",
"qtapi_version",
"(",
")",
"==",
"2",
":",
"return",
"QT_API_PYQT",
"else",
":",
"return",
"QT_API_PYQTv1",
"elif",
"'PySide.QtCore'",
"in",
"sys",
".",
"mo... | Return which API is loaded, if any
If this returns anything besides None,
importing any other Qt binding is unsafe.
Returns
-------
None, 'pyside', 'pyqt', or 'pyqtv1' | [
"Return",
"which",
"API",
"is",
"loaded",
"if",
"any"
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydev_ipython/qt_loaders.py#L63-L82 | train | 209,663 |
fabioz/PyDev.Debugger | pydev_ipython/qt_loaders.py | has_binding | def has_binding(api):
"""Safely check for PyQt4 or PySide, without importing
submodules
Parameters
----------
api : str [ 'pyqtv1' | 'pyqt' | 'pyside' | 'pyqtdefault']
Which module to check for
Returns
-------
True if the relevant module appears to be importable
"""
# we can't import an incomplete pyside and pyqt4
# this will cause a crash in sip (#1431)
# check for complete presence before importing
module_name = {QT_API_PYSIDE: 'PySide',
QT_API_PYQT: 'PyQt4',
QT_API_PYQTv1: 'PyQt4',
QT_API_PYQT_DEFAULT: 'PyQt4',
QT_API_PYQT5: 'PyQt5',
}
module_name = module_name[api]
import imp
try:
#importing top level PyQt4/PySide module is ok...
mod = __import__(module_name)
#...importing submodules is not
imp.find_module('QtCore', mod.__path__)
imp.find_module('QtGui', mod.__path__)
imp.find_module('QtSvg', mod.__path__)
#we can also safely check PySide version
if api == QT_API_PYSIDE:
return check_version(mod.__version__, '1.0.3')
else:
return True
except ImportError:
return False | python | def has_binding(api):
"""Safely check for PyQt4 or PySide, without importing
submodules
Parameters
----------
api : str [ 'pyqtv1' | 'pyqt' | 'pyside' | 'pyqtdefault']
Which module to check for
Returns
-------
True if the relevant module appears to be importable
"""
# we can't import an incomplete pyside and pyqt4
# this will cause a crash in sip (#1431)
# check for complete presence before importing
module_name = {QT_API_PYSIDE: 'PySide',
QT_API_PYQT: 'PyQt4',
QT_API_PYQTv1: 'PyQt4',
QT_API_PYQT_DEFAULT: 'PyQt4',
QT_API_PYQT5: 'PyQt5',
}
module_name = module_name[api]
import imp
try:
#importing top level PyQt4/PySide module is ok...
mod = __import__(module_name)
#...importing submodules is not
imp.find_module('QtCore', mod.__path__)
imp.find_module('QtGui', mod.__path__)
imp.find_module('QtSvg', mod.__path__)
#we can also safely check PySide version
if api == QT_API_PYSIDE:
return check_version(mod.__version__, '1.0.3')
else:
return True
except ImportError:
return False | [
"def",
"has_binding",
"(",
"api",
")",
":",
"# we can't import an incomplete pyside and pyqt4",
"# this will cause a crash in sip (#1431)",
"# check for complete presence before importing",
"module_name",
"=",
"{",
"QT_API_PYSIDE",
":",
"'PySide'",
",",
"QT_API_PYQT",
":",
"'PyQt... | Safely check for PyQt4 or PySide, without importing
submodules
Parameters
----------
api : str [ 'pyqtv1' | 'pyqt' | 'pyside' | 'pyqtdefault']
Which module to check for
Returns
-------
True if the relevant module appears to be importable | [
"Safely",
"check",
"for",
"PyQt4",
"or",
"PySide",
"without",
"importing",
"submodules"
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydev_ipython/qt_loaders.py#L85-L124 | train | 209,664 |
fabioz/PyDev.Debugger | pydev_ipython/qt_loaders.py | can_import | def can_import(api):
"""Safely query whether an API is importable, without importing it"""
if not has_binding(api):
return False
current = loaded_api()
if api == QT_API_PYQT_DEFAULT:
return current in [QT_API_PYQT, QT_API_PYQTv1, QT_API_PYQT5, None]
else:
return current in [api, None] | python | def can_import(api):
"""Safely query whether an API is importable, without importing it"""
if not has_binding(api):
return False
current = loaded_api()
if api == QT_API_PYQT_DEFAULT:
return current in [QT_API_PYQT, QT_API_PYQTv1, QT_API_PYQT5, None]
else:
return current in [api, None] | [
"def",
"can_import",
"(",
"api",
")",
":",
"if",
"not",
"has_binding",
"(",
"api",
")",
":",
"return",
"False",
"current",
"=",
"loaded_api",
"(",
")",
"if",
"api",
"==",
"QT_API_PYQT_DEFAULT",
":",
"return",
"current",
"in",
"[",
"QT_API_PYQT",
",",
"QT... | Safely query whether an API is importable, without importing it | [
"Safely",
"query",
"whether",
"an",
"API",
"is",
"importable",
"without",
"importing",
"it"
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydev_ipython/qt_loaders.py#L144-L153 | train | 209,665 |
fabioz/PyDev.Debugger | third_party/pep8/autopep8.py | extended_blank_lines | def extended_blank_lines(logical_line,
blank_lines,
blank_before,
indent_level,
previous_logical):
"""Check for missing blank lines after class declaration."""
if previous_logical.startswith('def '):
if blank_lines and pycodestyle.DOCSTRING_REGEX.match(logical_line):
yield (0, 'E303 too many blank lines ({0})'.format(blank_lines))
elif pycodestyle.DOCSTRING_REGEX.match(previous_logical):
# Missing blank line between class docstring and method declaration.
if (
indent_level and
not blank_lines and
not blank_before and
logical_line.startswith(('def ')) and
'(self' in logical_line
):
yield (0, 'E301 expected 1 blank line, found 0') | python | def extended_blank_lines(logical_line,
blank_lines,
blank_before,
indent_level,
previous_logical):
"""Check for missing blank lines after class declaration."""
if previous_logical.startswith('def '):
if blank_lines and pycodestyle.DOCSTRING_REGEX.match(logical_line):
yield (0, 'E303 too many blank lines ({0})'.format(blank_lines))
elif pycodestyle.DOCSTRING_REGEX.match(previous_logical):
# Missing blank line between class docstring and method declaration.
if (
indent_level and
not blank_lines and
not blank_before and
logical_line.startswith(('def ')) and
'(self' in logical_line
):
yield (0, 'E301 expected 1 blank line, found 0') | [
"def",
"extended_blank_lines",
"(",
"logical_line",
",",
"blank_lines",
",",
"blank_before",
",",
"indent_level",
",",
"previous_logical",
")",
":",
"if",
"previous_logical",
".",
"startswith",
"(",
"'def '",
")",
":",
"if",
"blank_lines",
"and",
"pycodestyle",
".... | Check for missing blank lines after class declaration. | [
"Check",
"for",
"missing",
"blank",
"lines",
"after",
"class",
"declaration",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/autopep8.py#L171-L189 | train | 209,666 |
fabioz/PyDev.Debugger | third_party/pep8/autopep8.py | fix_e265 | def fix_e265(source, aggressive=False): # pylint: disable=unused-argument
"""Format block comments."""
if '#' not in source:
# Optimization.
return source
ignored_line_numbers = multiline_string_lines(
source,
include_docstrings=True) | set(commented_out_code_lines(source))
fixed_lines = []
sio = io.StringIO(source)
for (line_number, line) in enumerate(sio.readlines(), start=1):
if (
line.lstrip().startswith('#') and
line_number not in ignored_line_numbers and
not pycodestyle.noqa(line)
):
indentation = _get_indentation(line)
line = line.lstrip()
# Normalize beginning if not a shebang.
if len(line) > 1:
pos = next((index for index, c in enumerate(line)
if c != '#'))
if (
# Leave multiple spaces like '# ' alone.
(line[:pos].count('#') > 1 or line[1].isalnum()) and
# Leave stylistic outlined blocks alone.
not line.rstrip().endswith('#')
):
line = '# ' + line.lstrip('# \t')
fixed_lines.append(indentation + line)
else:
fixed_lines.append(line)
return ''.join(fixed_lines) | python | def fix_e265(source, aggressive=False): # pylint: disable=unused-argument
"""Format block comments."""
if '#' not in source:
# Optimization.
return source
ignored_line_numbers = multiline_string_lines(
source,
include_docstrings=True) | set(commented_out_code_lines(source))
fixed_lines = []
sio = io.StringIO(source)
for (line_number, line) in enumerate(sio.readlines(), start=1):
if (
line.lstrip().startswith('#') and
line_number not in ignored_line_numbers and
not pycodestyle.noqa(line)
):
indentation = _get_indentation(line)
line = line.lstrip()
# Normalize beginning if not a shebang.
if len(line) > 1:
pos = next((index for index, c in enumerate(line)
if c != '#'))
if (
# Leave multiple spaces like '# ' alone.
(line[:pos].count('#') > 1 or line[1].isalnum()) and
# Leave stylistic outlined blocks alone.
not line.rstrip().endswith('#')
):
line = '# ' + line.lstrip('# \t')
fixed_lines.append(indentation + line)
else:
fixed_lines.append(line)
return ''.join(fixed_lines) | [
"def",
"fix_e265",
"(",
"source",
",",
"aggressive",
"=",
"False",
")",
":",
"# pylint: disable=unused-argument",
"if",
"'#'",
"not",
"in",
"source",
":",
"# Optimization.",
"return",
"source",
"ignored_line_numbers",
"=",
"multiline_string_lines",
"(",
"source",
",... | Format block comments. | [
"Format",
"block",
"comments",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/autopep8.py#L1300-L1337 | train | 209,667 |
fabioz/PyDev.Debugger | third_party/pep8/autopep8.py | refactor | def refactor(source, fixer_names, ignore=None, filename=''):
"""Return refactored code using lib2to3.
Skip if ignore string is produced in the refactored code.
"""
check_lib2to3()
from lib2to3 import pgen2
try:
new_text = refactor_with_2to3(source,
fixer_names=fixer_names,
filename=filename)
except (pgen2.parse.ParseError,
SyntaxError,
UnicodeDecodeError,
UnicodeEncodeError):
return source
if ignore:
if ignore in new_text and ignore not in source:
return source
return new_text | python | def refactor(source, fixer_names, ignore=None, filename=''):
"""Return refactored code using lib2to3.
Skip if ignore string is produced in the refactored code.
"""
check_lib2to3()
from lib2to3 import pgen2
try:
new_text = refactor_with_2to3(source,
fixer_names=fixer_names,
filename=filename)
except (pgen2.parse.ParseError,
SyntaxError,
UnicodeDecodeError,
UnicodeEncodeError):
return source
if ignore:
if ignore in new_text and ignore not in source:
return source
return new_text | [
"def",
"refactor",
"(",
"source",
",",
"fixer_names",
",",
"ignore",
"=",
"None",
",",
"filename",
"=",
"''",
")",
":",
"check_lib2to3",
"(",
")",
"from",
"lib2to3",
"import",
"pgen2",
"try",
":",
"new_text",
"=",
"refactor_with_2to3",
"(",
"source",
",",
... | Return refactored code using lib2to3.
Skip if ignore string is produced in the refactored code. | [
"Return",
"refactored",
"code",
"using",
"lib2to3",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/autopep8.py#L1340-L1362 | train | 209,668 |
fabioz/PyDev.Debugger | third_party/pep8/autopep8.py | _get_indentation | def _get_indentation(line):
"""Return leading whitespace."""
if line.strip():
non_whitespace_index = len(line) - len(line.lstrip())
return line[:non_whitespace_index]
else:
return '' | python | def _get_indentation(line):
"""Return leading whitespace."""
if line.strip():
non_whitespace_index = len(line) - len(line.lstrip())
return line[:non_whitespace_index]
else:
return '' | [
"def",
"_get_indentation",
"(",
"line",
")",
":",
"if",
"line",
".",
"strip",
"(",
")",
":",
"non_whitespace_index",
"=",
"len",
"(",
"line",
")",
"-",
"len",
"(",
"line",
".",
"lstrip",
"(",
")",
")",
"return",
"line",
"[",
":",
"non_whitespace_index"... | Return leading whitespace. | [
"Return",
"leading",
"whitespace",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/autopep8.py#L1430-L1436 | train | 209,669 |
fabioz/PyDev.Debugger | third_party/pep8/autopep8.py | _priority_key | def _priority_key(pep8_result):
"""Key for sorting PEP8 results.
Global fixes should be done first. This is important for things like
indentation.
"""
priority = [
# Fix multiline colon-based before semicolon based.
'e701',
# Break multiline statements early.
'e702',
# Things that make lines longer.
'e225', 'e231',
# Remove extraneous whitespace before breaking lines.
'e201',
# Shorten whitespace in comment before resorting to wrapping.
'e262'
]
middle_index = 10000
lowest_priority = [
# We need to shorten lines last since the logical fixer can get in a
# loop, which causes us to exit early.
'e501'
]
key = pep8_result['id'].lower()
try:
return priority.index(key)
except ValueError:
try:
return middle_index + lowest_priority.index(key) + 1
except ValueError:
return middle_index | python | def _priority_key(pep8_result):
"""Key for sorting PEP8 results.
Global fixes should be done first. This is important for things like
indentation.
"""
priority = [
# Fix multiline colon-based before semicolon based.
'e701',
# Break multiline statements early.
'e702',
# Things that make lines longer.
'e225', 'e231',
# Remove extraneous whitespace before breaking lines.
'e201',
# Shorten whitespace in comment before resorting to wrapping.
'e262'
]
middle_index = 10000
lowest_priority = [
# We need to shorten lines last since the logical fixer can get in a
# loop, which causes us to exit early.
'e501'
]
key = pep8_result['id'].lower()
try:
return priority.index(key)
except ValueError:
try:
return middle_index + lowest_priority.index(key) + 1
except ValueError:
return middle_index | [
"def",
"_priority_key",
"(",
"pep8_result",
")",
":",
"priority",
"=",
"[",
"# Fix multiline colon-based before semicolon based.",
"'e701'",
",",
"# Break multiline statements early.",
"'e702'",
",",
"# Things that make lines longer.",
"'e225'",
",",
"'e231'",
",",
"# Remove ... | Key for sorting PEP8 results.
Global fixes should be done first. This is important for things like
indentation. | [
"Key",
"for",
"sorting",
"PEP8",
"results",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/autopep8.py#L1459-L1491 | train | 209,670 |
fabioz/PyDev.Debugger | third_party/pep8/autopep8.py | normalize_multiline | def normalize_multiline(line):
"""Normalize multiline-related code that will cause syntax error.
This is for purposes of checking syntax.
"""
if line.startswith('def ') and line.rstrip().endswith(':'):
return line + ' pass'
elif line.startswith('return '):
return 'def _(): ' + line
elif line.startswith('@'):
return line + 'def _(): pass'
elif line.startswith('class '):
return line + ' pass'
elif line.startswith(('if ', 'elif ', 'for ', 'while ')):
return line + ' pass'
else:
return line | python | def normalize_multiline(line):
"""Normalize multiline-related code that will cause syntax error.
This is for purposes of checking syntax.
"""
if line.startswith('def ') and line.rstrip().endswith(':'):
return line + ' pass'
elif line.startswith('return '):
return 'def _(): ' + line
elif line.startswith('@'):
return line + 'def _(): pass'
elif line.startswith('class '):
return line + ' pass'
elif line.startswith(('if ', 'elif ', 'for ', 'while ')):
return line + ' pass'
else:
return line | [
"def",
"normalize_multiline",
"(",
"line",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"'def '",
")",
"and",
"line",
".",
"rstrip",
"(",
")",
".",
"endswith",
"(",
"':'",
")",
":",
"return",
"line",
"+",
"' pass'",
"elif",
"line",
".",
"startswith"... | Normalize multiline-related code that will cause syntax error.
This is for purposes of checking syntax. | [
"Normalize",
"multiline",
"-",
"related",
"code",
"that",
"will",
"cause",
"syntax",
"error",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/autopep8.py#L2521-L2538 | train | 209,671 |
fabioz/PyDev.Debugger | third_party/pep8/autopep8.py | fix_whitespace | def fix_whitespace(line, offset, replacement):
"""Replace whitespace at offset and return fixed line."""
# Replace escaped newlines too
left = line[:offset].rstrip('\n\r \t\\')
right = line[offset:].lstrip('\n\r \t\\')
if right.startswith('#'):
return line
else:
return left + replacement + right | python | def fix_whitespace(line, offset, replacement):
"""Replace whitespace at offset and return fixed line."""
# Replace escaped newlines too
left = line[:offset].rstrip('\n\r \t\\')
right = line[offset:].lstrip('\n\r \t\\')
if right.startswith('#'):
return line
else:
return left + replacement + right | [
"def",
"fix_whitespace",
"(",
"line",
",",
"offset",
",",
"replacement",
")",
":",
"# Replace escaped newlines too",
"left",
"=",
"line",
"[",
":",
"offset",
"]",
".",
"rstrip",
"(",
"'\\n\\r \\t\\\\'",
")",
"right",
"=",
"line",
"[",
"offset",
":",
"]",
"... | Replace whitespace at offset and return fixed line. | [
"Replace",
"whitespace",
"at",
"offset",
"and",
"return",
"fixed",
"line",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/autopep8.py#L2541-L2549 | train | 209,672 |
fabioz/PyDev.Debugger | third_party/pep8/autopep8.py | apply_global_fixes | def apply_global_fixes(source, options, where='global', filename=''):
"""Run global fixes on source code.
These are fixes that only need be done once (unlike those in
FixPEP8, which are dependent on pycodestyle).
"""
if any(code_match(code, select=options.select, ignore=options.ignore)
for code in ['E101', 'E111']):
source = reindent(source,
indent_size=options.indent_size)
for (code, function) in global_fixes():
if code_match(code, select=options.select, ignore=options.ignore):
if options.verbose:
print('---> Applying {0} fix for {1}'.format(where,
code.upper()),
file=sys.stderr)
source = function(source,
aggressive=options.aggressive)
source = fix_2to3(source,
aggressive=options.aggressive,
select=options.select,
ignore=options.ignore,
filename=filename)
return source | python | def apply_global_fixes(source, options, where='global', filename=''):
"""Run global fixes on source code.
These are fixes that only need be done once (unlike those in
FixPEP8, which are dependent on pycodestyle).
"""
if any(code_match(code, select=options.select, ignore=options.ignore)
for code in ['E101', 'E111']):
source = reindent(source,
indent_size=options.indent_size)
for (code, function) in global_fixes():
if code_match(code, select=options.select, ignore=options.ignore):
if options.verbose:
print('---> Applying {0} fix for {1}'.format(where,
code.upper()),
file=sys.stderr)
source = function(source,
aggressive=options.aggressive)
source = fix_2to3(source,
aggressive=options.aggressive,
select=options.select,
ignore=options.ignore,
filename=filename)
return source | [
"def",
"apply_global_fixes",
"(",
"source",
",",
"options",
",",
"where",
"=",
"'global'",
",",
"filename",
"=",
"''",
")",
":",
"if",
"any",
"(",
"code_match",
"(",
"code",
",",
"select",
"=",
"options",
".",
"select",
",",
"ignore",
"=",
"options",
"... | Run global fixes on source code.
These are fixes that only need be done once (unlike those in
FixPEP8, which are dependent on pycodestyle). | [
"Run",
"global",
"fixes",
"on",
"source",
"code",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/autopep8.py#L3137-L3164 | train | 209,673 |
fabioz/PyDev.Debugger | third_party/pep8/autopep8.py | main | def main(argv=None, apply_config=True):
"""Command-line entry."""
if argv is None:
argv = sys.argv
try:
# Exit on broken pipe.
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
except AttributeError: # pragma: no cover
# SIGPIPE is not available on Windows.
pass
try:
args = parse_args(argv[1:], apply_config=apply_config)
if args.list_fixes:
for code, description in sorted(supported_fixes()):
print('{code} - {description}'.format(
code=code, description=description))
return 0
if args.files == ['-']:
assert not args.in_place
encoding = sys.stdin.encoding or get_encoding()
# LineEndingWrapper is unnecessary here due to the symmetry between
# standard in and standard out.
wrap_output(sys.stdout, encoding=encoding).write(
fix_code(sys.stdin.read(), args, encoding=encoding))
else:
if args.in_place or args.diff:
args.files = list(set(args.files))
else:
assert len(args.files) == 1
assert not args.recursive
fix_multiple_files(args.files, args, sys.stdout)
except KeyboardInterrupt:
return 1 | python | def main(argv=None, apply_config=True):
"""Command-line entry."""
if argv is None:
argv = sys.argv
try:
# Exit on broken pipe.
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
except AttributeError: # pragma: no cover
# SIGPIPE is not available on Windows.
pass
try:
args = parse_args(argv[1:], apply_config=apply_config)
if args.list_fixes:
for code, description in sorted(supported_fixes()):
print('{code} - {description}'.format(
code=code, description=description))
return 0
if args.files == ['-']:
assert not args.in_place
encoding = sys.stdin.encoding or get_encoding()
# LineEndingWrapper is unnecessary here due to the symmetry between
# standard in and standard out.
wrap_output(sys.stdout, encoding=encoding).write(
fix_code(sys.stdin.read(), args, encoding=encoding))
else:
if args.in_place or args.diff:
args.files = list(set(args.files))
else:
assert len(args.files) == 1
assert not args.recursive
fix_multiple_files(args.files, args, sys.stdout)
except KeyboardInterrupt:
return 1 | [
"def",
"main",
"(",
"argv",
"=",
"None",
",",
"apply_config",
"=",
"True",
")",
":",
"if",
"argv",
"is",
"None",
":",
"argv",
"=",
"sys",
".",
"argv",
"try",
":",
"# Exit on broken pipe.",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGPIPE",
",",
... | Command-line entry. | [
"Command",
"-",
"line",
"entry",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/autopep8.py#L3757-L3796 | train | 209,674 |
fabioz/PyDev.Debugger | third_party/pep8/autopep8.py | FixPEP8.fix_e722 | def fix_e722(self, result):
"""fix bare except"""
(line_index, _, target) = get_index_offset_contents(result,
self.source)
if BARE_EXCEPT_REGEX.search(target):
self.source[line_index] = '{0}{1}'.format(
target[:result['column'] - 1], "except Exception:") | python | def fix_e722(self, result):
"""fix bare except"""
(line_index, _, target) = get_index_offset_contents(result,
self.source)
if BARE_EXCEPT_REGEX.search(target):
self.source[line_index] = '{0}{1}'.format(
target[:result['column'] - 1], "except Exception:") | [
"def",
"fix_e722",
"(",
"self",
",",
"result",
")",
":",
"(",
"line_index",
",",
"_",
",",
"target",
")",
"=",
"get_index_offset_contents",
"(",
"result",
",",
"self",
".",
"source",
")",
"if",
"BARE_EXCEPT_REGEX",
".",
"search",
"(",
"target",
")",
":",... | fix bare except | [
"fix",
"bare",
"except"
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/autopep8.py#L1056-L1062 | train | 209,675 |
fabioz/PyDev.Debugger | third_party/pep8/autopep8.py | ReformattedLines._split_after_delimiter | def _split_after_delimiter(self, item, indent_amt):
"""Split the line only after a delimiter."""
self._delete_whitespace()
if self.fits_on_current_line(item.size):
return
last_space = None
for item in reversed(self._lines):
if (
last_space and
(not isinstance(item, Atom) or not item.is_colon)
):
break
else:
last_space = None
if isinstance(item, self._Space):
last_space = item
if isinstance(item, (self._LineBreak, self._Indent)):
return
if not last_space:
return
self.add_line_break_at(self._lines.index(last_space), indent_amt) | python | def _split_after_delimiter(self, item, indent_amt):
"""Split the line only after a delimiter."""
self._delete_whitespace()
if self.fits_on_current_line(item.size):
return
last_space = None
for item in reversed(self._lines):
if (
last_space and
(not isinstance(item, Atom) or not item.is_colon)
):
break
else:
last_space = None
if isinstance(item, self._Space):
last_space = item
if isinstance(item, (self._LineBreak, self._Indent)):
return
if not last_space:
return
self.add_line_break_at(self._lines.index(last_space), indent_amt) | [
"def",
"_split_after_delimiter",
"(",
"self",
",",
"item",
",",
"indent_amt",
")",
":",
"self",
".",
"_delete_whitespace",
"(",
")",
"if",
"self",
".",
"fits_on_current_line",
"(",
"item",
".",
"size",
")",
":",
"return",
"last_space",
"=",
"None",
"for",
... | Split the line only after a delimiter. | [
"Split",
"the",
"line",
"only",
"after",
"a",
"delimiter",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/autopep8.py#L1897-L1921 | train | 209,676 |
fabioz/PyDev.Debugger | _pydevd_bundle/pydevconsole_code_for_ironpython.py | interact | def interact(banner=None, readfunc=None, local=None):
"""Closely emulate the interactive Python interpreter.
This is a backwards compatible interface to the InteractiveConsole
class. When readfunc is not specified, it attempts to import the
readline module to enable GNU readline if it is available.
Arguments (all optional, all default to None):
banner -- passed to InteractiveConsole.interact()
readfunc -- if not None, replaces InteractiveConsole.raw_input()
local -- passed to InteractiveInterpreter.__init__()
"""
console = InteractiveConsole(local)
if readfunc is not None:
console.raw_input = readfunc
else:
try:
import readline
except ImportError:
pass
console.interact(banner) | python | def interact(banner=None, readfunc=None, local=None):
"""Closely emulate the interactive Python interpreter.
This is a backwards compatible interface to the InteractiveConsole
class. When readfunc is not specified, it attempts to import the
readline module to enable GNU readline if it is available.
Arguments (all optional, all default to None):
banner -- passed to InteractiveConsole.interact()
readfunc -- if not None, replaces InteractiveConsole.raw_input()
local -- passed to InteractiveInterpreter.__init__()
"""
console = InteractiveConsole(local)
if readfunc is not None:
console.raw_input = readfunc
else:
try:
import readline
except ImportError:
pass
console.interact(banner) | [
"def",
"interact",
"(",
"banner",
"=",
"None",
",",
"readfunc",
"=",
"None",
",",
"local",
"=",
"None",
")",
":",
"console",
"=",
"InteractiveConsole",
"(",
"local",
")",
"if",
"readfunc",
"is",
"not",
"None",
":",
"console",
".",
"raw_input",
"=",
"re... | Closely emulate the interactive Python interpreter.
This is a backwards compatible interface to the InteractiveConsole
class. When readfunc is not specified, it attempts to import the
readline module to enable GNU readline if it is available.
Arguments (all optional, all default to None):
banner -- passed to InteractiveConsole.interact()
readfunc -- if not None, replaces InteractiveConsole.raw_input()
local -- passed to InteractiveInterpreter.__init__() | [
"Closely",
"emulate",
"the",
"interactive",
"Python",
"interpreter",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_bundle/pydevconsole_code_for_ironpython.py#L486-L508 | train | 209,677 |
fabioz/PyDev.Debugger | _pydevd_bundle/pydevconsole_code_for_ironpython.py | InteractiveInterpreter.runsource | def runsource(self, source, filename="<input>", symbol="single"):
"""Compile and run some source in the interpreter.
Arguments are as for compile_command().
One several things can happen:
1) The input is incorrect; compile_command() raised an
exception (SyntaxError or OverflowError). A syntax traceback
will be printed by calling the showsyntaxerror() method.
2) The input is incomplete, and more input is required;
compile_command() returned None. Nothing happens.
3) The input is complete; compile_command() returned a code
object. The code is executed by calling self.runcode() (which
also handles run-time exceptions, except for SystemExit).
The return value is True in case 2, False in the other cases (unless
an exception is raised). The return value can be used to
decide whether to use sys.ps1 or sys.ps2 to prompt the next
line.
"""
try:
code = self.compile(source, filename, symbol)
except (OverflowError, SyntaxError, ValueError):
# Case 1
self.showsyntaxerror(filename)
return False
if code is None:
# Case 2
return True
# Case 3
self.runcode(code)
return False | python | def runsource(self, source, filename="<input>", symbol="single"):
"""Compile and run some source in the interpreter.
Arguments are as for compile_command().
One several things can happen:
1) The input is incorrect; compile_command() raised an
exception (SyntaxError or OverflowError). A syntax traceback
will be printed by calling the showsyntaxerror() method.
2) The input is incomplete, and more input is required;
compile_command() returned None. Nothing happens.
3) The input is complete; compile_command() returned a code
object. The code is executed by calling self.runcode() (which
also handles run-time exceptions, except for SystemExit).
The return value is True in case 2, False in the other cases (unless
an exception is raised). The return value can be used to
decide whether to use sys.ps1 or sys.ps2 to prompt the next
line.
"""
try:
code = self.compile(source, filename, symbol)
except (OverflowError, SyntaxError, ValueError):
# Case 1
self.showsyntaxerror(filename)
return False
if code is None:
# Case 2
return True
# Case 3
self.runcode(code)
return False | [
"def",
"runsource",
"(",
"self",
",",
"source",
",",
"filename",
"=",
"\"<input>\"",
",",
"symbol",
"=",
"\"single\"",
")",
":",
"try",
":",
"code",
"=",
"self",
".",
"compile",
"(",
"source",
",",
"filename",
",",
"symbol",
")",
"except",
"(",
"Overfl... | Compile and run some source in the interpreter.
Arguments are as for compile_command().
One several things can happen:
1) The input is incorrect; compile_command() raised an
exception (SyntaxError or OverflowError). A syntax traceback
will be printed by calling the showsyntaxerror() method.
2) The input is incomplete, and more input is required;
compile_command() returned None. Nothing happens.
3) The input is complete; compile_command() returned a code
object. The code is executed by calling self.runcode() (which
also handles run-time exceptions, except for SystemExit).
The return value is True in case 2, False in the other cases (unless
an exception is raised). The return value can be used to
decide whether to use sys.ps1 or sys.ps2 to prompt the next
line. | [
"Compile",
"and",
"run",
"some",
"source",
"in",
"the",
"interpreter",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_bundle/pydevconsole_code_for_ironpython.py#L253-L290 | train | 209,678 |
fabioz/PyDev.Debugger | _pydevd_bundle/pydevconsole_code_for_ironpython.py | InteractiveConsole.push | def push(self, line):
"""Push a line to the interpreter.
The line should not have a trailing newline; it may have
internal newlines. The line is appended to a buffer and the
interpreter's runsource() method is called with the
concatenated contents of the buffer as source. If this
indicates that the command was executed or invalid, the buffer
is reset; otherwise, the command is incomplete, and the buffer
is left as it was after the line was appended. The return
value is 1 if more input is required, 0 if the line was dealt
with in some way (this is the same as runsource()).
"""
self.buffer.append(line)
source = "\n".join(self.buffer)
more = self.runsource(source, self.filename)
if not more:
self.resetbuffer()
return more | python | def push(self, line):
"""Push a line to the interpreter.
The line should not have a trailing newline; it may have
internal newlines. The line is appended to a buffer and the
interpreter's runsource() method is called with the
concatenated contents of the buffer as source. If this
indicates that the command was executed or invalid, the buffer
is reset; otherwise, the command is incomplete, and the buffer
is left as it was after the line was appended. The return
value is 1 if more input is required, 0 if the line was dealt
with in some way (this is the same as runsource()).
"""
self.buffer.append(line)
source = "\n".join(self.buffer)
more = self.runsource(source, self.filename)
if not more:
self.resetbuffer()
return more | [
"def",
"push",
"(",
"self",
",",
"line",
")",
":",
"self",
".",
"buffer",
".",
"append",
"(",
"line",
")",
"source",
"=",
"\"\\n\"",
".",
"join",
"(",
"self",
".",
"buffer",
")",
"more",
"=",
"self",
".",
"runsource",
"(",
"source",
",",
"self",
... | Push a line to the interpreter.
The line should not have a trailing newline; it may have
internal newlines. The line is appended to a buffer and the
interpreter's runsource() method is called with the
concatenated contents of the buffer as source. If this
indicates that the command was executed or invalid, the buffer
is reset; otherwise, the command is incomplete, and the buffer
is left as it was after the line was appended. The return
value is 1 if more input is required, 0 if the line was dealt
with in some way (this is the same as runsource()). | [
"Push",
"a",
"line",
"to",
"the",
"interpreter",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_bundle/pydevconsole_code_for_ironpython.py#L451-L470 | train | 209,679 |
fabioz/PyDev.Debugger | _pydev_bundle/pydev_ipython_console_011.py | show_in_pager | def show_in_pager(self, strng, *args, **kwargs):
""" Run a string through pager """
# On PyDev we just output the string, there are scroll bars in the console
# to handle "paging". This is the same behaviour as when TERM==dump (see
# page.py)
# for compatibility with mime-bundle form:
if isinstance(strng, dict):
strng = strng.get('text/plain', strng)
print(strng) | python | def show_in_pager(self, strng, *args, **kwargs):
""" Run a string through pager """
# On PyDev we just output the string, there are scroll bars in the console
# to handle "paging". This is the same behaviour as when TERM==dump (see
# page.py)
# for compatibility with mime-bundle form:
if isinstance(strng, dict):
strng = strng.get('text/plain', strng)
print(strng) | [
"def",
"show_in_pager",
"(",
"self",
",",
"strng",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# On PyDev we just output the string, there are scroll bars in the console",
"# to handle \"paging\". This is the same behaviour as when TERM==dump (see",
"# page.py)",
"# for... | Run a string through pager | [
"Run",
"a",
"string",
"through",
"pager"
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_bundle/pydev_ipython_console_011.py#L43-L51 | train | 209,680 |
fabioz/PyDev.Debugger | _pydev_bundle/pydev_ipython_console_011.py | PyDevIPCompleter6.matchers | def matchers(self):
"""All active matcher routines for completion"""
# To remove python_matches we now have to override it as it's now a property in the superclass.
return [
self.file_matches,
self.magic_matches,
self.python_func_kw_matches,
self.dict_key_matches,
] | python | def matchers(self):
"""All active matcher routines for completion"""
# To remove python_matches we now have to override it as it's now a property in the superclass.
return [
self.file_matches,
self.magic_matches,
self.python_func_kw_matches,
self.dict_key_matches,
] | [
"def",
"matchers",
"(",
"self",
")",
":",
"# To remove python_matches we now have to override it as it's now a property in the superclass.",
"return",
"[",
"self",
".",
"file_matches",
",",
"self",
".",
"magic_matches",
",",
"self",
".",
"python_func_kw_matches",
",",
"self... | All active matcher routines for completion | [
"All",
"active",
"matcher",
"routines",
"for",
"completion"
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_bundle/pydev_ipython_console_011.py#L98-L106 | train | 209,681 |
fabioz/PyDev.Debugger | _pydev_bundle/pydev_ipython_console_011.py | PyDevTerminalInteractiveShell.init_completer | def init_completer(self):
"""Initialize the completion machinery.
This creates a completer that provides the completions that are
IPython specific. We use this to supplement PyDev's core code
completions.
"""
# PyDev uses its own completer and custom hooks so that it uses
# most completions from PyDev's core completer which provides
# extra information.
# See getCompletions for where the two sets of results are merged
if IPythonRelease._version_major >= 6:
self.Completer = self._new_completer_600()
elif IPythonRelease._version_major >= 5:
self.Completer = self._new_completer_500()
elif IPythonRelease._version_major >= 2:
self.Completer = self._new_completer_234()
elif IPythonRelease._version_major >= 1:
self.Completer = self._new_completer_100()
if hasattr(self.Completer, 'use_jedi'):
self.Completer.use_jedi = False
self.add_completer_hooks()
if IPythonRelease._version_major <= 3:
# Only configure readline if we truly are using readline. IPython can
# do tab-completion over the network, in GUIs, etc, where readline
# itself may be absent
if self.has_readline:
self.set_readline_completer() | python | def init_completer(self):
"""Initialize the completion machinery.
This creates a completer that provides the completions that are
IPython specific. We use this to supplement PyDev's core code
completions.
"""
# PyDev uses its own completer and custom hooks so that it uses
# most completions from PyDev's core completer which provides
# extra information.
# See getCompletions for where the two sets of results are merged
if IPythonRelease._version_major >= 6:
self.Completer = self._new_completer_600()
elif IPythonRelease._version_major >= 5:
self.Completer = self._new_completer_500()
elif IPythonRelease._version_major >= 2:
self.Completer = self._new_completer_234()
elif IPythonRelease._version_major >= 1:
self.Completer = self._new_completer_100()
if hasattr(self.Completer, 'use_jedi'):
self.Completer.use_jedi = False
self.add_completer_hooks()
if IPythonRelease._version_major <= 3:
# Only configure readline if we truly are using readline. IPython can
# do tab-completion over the network, in GUIs, etc, where readline
# itself may be absent
if self.has_readline:
self.set_readline_completer() | [
"def",
"init_completer",
"(",
"self",
")",
":",
"# PyDev uses its own completer and custom hooks so that it uses",
"# most completions from PyDev's core completer which provides",
"# extra information.",
"# See getCompletions for where the two sets of results are merged",
"if",
"IPythonRelease... | Initialize the completion machinery.
This creates a completer that provides the completions that are
IPython specific. We use this to supplement PyDev's core code
completions. | [
"Initialize",
"the",
"completion",
"machinery",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_bundle/pydev_ipython_console_011.py#L249-L280 | train | 209,682 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/process.py | Process.open_handle | def open_handle(self, dwDesiredAccess = win32.PROCESS_ALL_ACCESS):
"""
Opens a new handle to the process.
The new handle is stored in the L{hProcess} property.
@warn: Normally you should call L{get_handle} instead, since it's much
"smarter" and tries to reuse handles and merge access rights.
@type dwDesiredAccess: int
@param dwDesiredAccess: Desired access rights.
Defaults to L{win32.PROCESS_ALL_ACCESS}.
See: U{http://msdn.microsoft.com/en-us/library/windows/desktop/ms684880(v=vs.85).aspx}
@raise WindowsError: It's not possible to open a handle to the process
with the requested access rights. This tipically happens because
the target process is a system process and the debugger is not
runnning with administrative rights.
"""
hProcess = win32.OpenProcess(dwDesiredAccess, win32.FALSE, self.dwProcessId)
try:
self.close_handle()
except Exception:
warnings.warn(
"Failed to close process handle: %s" % traceback.format_exc())
self.hProcess = hProcess | python | def open_handle(self, dwDesiredAccess = win32.PROCESS_ALL_ACCESS):
"""
Opens a new handle to the process.
The new handle is stored in the L{hProcess} property.
@warn: Normally you should call L{get_handle} instead, since it's much
"smarter" and tries to reuse handles and merge access rights.
@type dwDesiredAccess: int
@param dwDesiredAccess: Desired access rights.
Defaults to L{win32.PROCESS_ALL_ACCESS}.
See: U{http://msdn.microsoft.com/en-us/library/windows/desktop/ms684880(v=vs.85).aspx}
@raise WindowsError: It's not possible to open a handle to the process
with the requested access rights. This tipically happens because
the target process is a system process and the debugger is not
runnning with administrative rights.
"""
hProcess = win32.OpenProcess(dwDesiredAccess, win32.FALSE, self.dwProcessId)
try:
self.close_handle()
except Exception:
warnings.warn(
"Failed to close process handle: %s" % traceback.format_exc())
self.hProcess = hProcess | [
"def",
"open_handle",
"(",
"self",
",",
"dwDesiredAccess",
"=",
"win32",
".",
"PROCESS_ALL_ACCESS",
")",
":",
"hProcess",
"=",
"win32",
".",
"OpenProcess",
"(",
"dwDesiredAccess",
",",
"win32",
".",
"FALSE",
",",
"self",
".",
"dwProcessId",
")",
"try",
":",
... | Opens a new handle to the process.
The new handle is stored in the L{hProcess} property.
@warn: Normally you should call L{get_handle} instead, since it's much
"smarter" and tries to reuse handles and merge access rights.
@type dwDesiredAccess: int
@param dwDesiredAccess: Desired access rights.
Defaults to L{win32.PROCESS_ALL_ACCESS}.
See: U{http://msdn.microsoft.com/en-us/library/windows/desktop/ms684880(v=vs.85).aspx}
@raise WindowsError: It's not possible to open a handle to the process
with the requested access rights. This tipically happens because
the target process is a system process and the debugger is not
runnning with administrative rights. | [
"Opens",
"a",
"new",
"handle",
"to",
"the",
"process",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L187-L214 | train | 209,683 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/process.py | Process.close_handle | def close_handle(self):
"""
Closes the handle to the process.
@note: Normally you don't need to call this method. All handles
created by I{WinAppDbg} are automatically closed when the garbage
collector claims them. So unless you've been tinkering with it,
setting L{hProcess} to C{None} should be enough.
"""
try:
if hasattr(self.hProcess, 'close'):
self.hProcess.close()
elif self.hProcess not in (None, win32.INVALID_HANDLE_VALUE):
win32.CloseHandle(self.hProcess)
finally:
self.hProcess = None | python | def close_handle(self):
"""
Closes the handle to the process.
@note: Normally you don't need to call this method. All handles
created by I{WinAppDbg} are automatically closed when the garbage
collector claims them. So unless you've been tinkering with it,
setting L{hProcess} to C{None} should be enough.
"""
try:
if hasattr(self.hProcess, 'close'):
self.hProcess.close()
elif self.hProcess not in (None, win32.INVALID_HANDLE_VALUE):
win32.CloseHandle(self.hProcess)
finally:
self.hProcess = None | [
"def",
"close_handle",
"(",
"self",
")",
":",
"try",
":",
"if",
"hasattr",
"(",
"self",
".",
"hProcess",
",",
"'close'",
")",
":",
"self",
".",
"hProcess",
".",
"close",
"(",
")",
"elif",
"self",
".",
"hProcess",
"not",
"in",
"(",
"None",
",",
"win... | Closes the handle to the process.
@note: Normally you don't need to call this method. All handles
created by I{WinAppDbg} are automatically closed when the garbage
collector claims them. So unless you've been tinkering with it,
setting L{hProcess} to C{None} should be enough. | [
"Closes",
"the",
"handle",
"to",
"the",
"process",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L216-L231 | train | 209,684 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/process.py | Process.kill | def kill(self, dwExitCode = 0):
"""
Terminates the execution of the process.
@raise WindowsError: On error an exception is raised.
"""
hProcess = self.get_handle(win32.PROCESS_TERMINATE)
win32.TerminateProcess(hProcess, dwExitCode) | python | def kill(self, dwExitCode = 0):
"""
Terminates the execution of the process.
@raise WindowsError: On error an exception is raised.
"""
hProcess = self.get_handle(win32.PROCESS_TERMINATE)
win32.TerminateProcess(hProcess, dwExitCode) | [
"def",
"kill",
"(",
"self",
",",
"dwExitCode",
"=",
"0",
")",
":",
"hProcess",
"=",
"self",
".",
"get_handle",
"(",
"win32",
".",
"PROCESS_TERMINATE",
")",
"win32",
".",
"TerminateProcess",
"(",
"hProcess",
",",
"dwExitCode",
")"
] | Terminates the execution of the process.
@raise WindowsError: On error an exception is raised. | [
"Terminates",
"the",
"execution",
"of",
"the",
"process",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L365-L372 | train | 209,685 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/process.py | Process.suspend | def suspend(self):
"""
Suspends execution on all threads of the process.
@raise WindowsError: On error an exception is raised.
"""
self.scan_threads() # force refresh the snapshot
suspended = list()
try:
for aThread in self.iter_threads():
aThread.suspend()
suspended.append(aThread)
except Exception:
for aThread in suspended:
try:
aThread.resume()
except Exception:
pass
raise | python | def suspend(self):
"""
Suspends execution on all threads of the process.
@raise WindowsError: On error an exception is raised.
"""
self.scan_threads() # force refresh the snapshot
suspended = list()
try:
for aThread in self.iter_threads():
aThread.suspend()
suspended.append(aThread)
except Exception:
for aThread in suspended:
try:
aThread.resume()
except Exception:
pass
raise | [
"def",
"suspend",
"(",
"self",
")",
":",
"self",
".",
"scan_threads",
"(",
")",
"# force refresh the snapshot",
"suspended",
"=",
"list",
"(",
")",
"try",
":",
"for",
"aThread",
"in",
"self",
".",
"iter_threads",
"(",
")",
":",
"aThread",
".",
"suspend",
... | Suspends execution on all threads of the process.
@raise WindowsError: On error an exception is raised. | [
"Suspends",
"execution",
"on",
"all",
"threads",
"of",
"the",
"process",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L374-L392 | train | 209,686 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/process.py | Process.resume | def resume(self):
"""
Resumes execution on all threads of the process.
@raise WindowsError: On error an exception is raised.
"""
if self.get_thread_count() == 0:
self.scan_threads() # only refresh the snapshot if empty
resumed = list()
try:
for aThread in self.iter_threads():
aThread.resume()
resumed.append(aThread)
except Exception:
for aThread in resumed:
try:
aThread.suspend()
except Exception:
pass
raise | python | def resume(self):
"""
Resumes execution on all threads of the process.
@raise WindowsError: On error an exception is raised.
"""
if self.get_thread_count() == 0:
self.scan_threads() # only refresh the snapshot if empty
resumed = list()
try:
for aThread in self.iter_threads():
aThread.resume()
resumed.append(aThread)
except Exception:
for aThread in resumed:
try:
aThread.suspend()
except Exception:
pass
raise | [
"def",
"resume",
"(",
"self",
")",
":",
"if",
"self",
".",
"get_thread_count",
"(",
")",
"==",
"0",
":",
"self",
".",
"scan_threads",
"(",
")",
"# only refresh the snapshot if empty",
"resumed",
"=",
"list",
"(",
")",
"try",
":",
"for",
"aThread",
"in",
... | Resumes execution on all threads of the process.
@raise WindowsError: On error an exception is raised. | [
"Resumes",
"execution",
"on",
"all",
"threads",
"of",
"the",
"process",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L394-L413 | train | 209,687 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/process.py | Process.is_debugged | def is_debugged(self):
"""
Tries to determine if the process is being debugged by another process.
It may detect other debuggers besides WinAppDbg.
@rtype: bool
@return: C{True} if the process has a debugger attached.
@warning:
May return inaccurate results when some anti-debug techniques are
used by the target process.
@note: To know if a process currently being debugged by a L{Debug}
object, call L{Debug.is_debugee} instead.
"""
# FIXME the MSDN docs don't say what access rights are needed here!
hProcess = self.get_handle(win32.PROCESS_QUERY_INFORMATION)
return win32.CheckRemoteDebuggerPresent(hProcess) | python | def is_debugged(self):
"""
Tries to determine if the process is being debugged by another process.
It may detect other debuggers besides WinAppDbg.
@rtype: bool
@return: C{True} if the process has a debugger attached.
@warning:
May return inaccurate results when some anti-debug techniques are
used by the target process.
@note: To know if a process currently being debugged by a L{Debug}
object, call L{Debug.is_debugee} instead.
"""
# FIXME the MSDN docs don't say what access rights are needed here!
hProcess = self.get_handle(win32.PROCESS_QUERY_INFORMATION)
return win32.CheckRemoteDebuggerPresent(hProcess) | [
"def",
"is_debugged",
"(",
"self",
")",
":",
"# FIXME the MSDN docs don't say what access rights are needed here!",
"hProcess",
"=",
"self",
".",
"get_handle",
"(",
"win32",
".",
"PROCESS_QUERY_INFORMATION",
")",
"return",
"win32",
".",
"CheckRemoteDebuggerPresent",
"(",
... | Tries to determine if the process is being debugged by another process.
It may detect other debuggers besides WinAppDbg.
@rtype: bool
@return: C{True} if the process has a debugger attached.
@warning:
May return inaccurate results when some anti-debug techniques are
used by the target process.
@note: To know if a process currently being debugged by a L{Debug}
object, call L{Debug.is_debugee} instead. | [
"Tries",
"to",
"determine",
"if",
"the",
"process",
"is",
"being",
"debugged",
"by",
"another",
"process",
".",
"It",
"may",
"detect",
"other",
"debuggers",
"besides",
"WinAppDbg",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L415-L432 | train | 209,688 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/process.py | Process.__fixup_labels | def __fixup_labels(self, disasm):
"""
Private method used when disassembling from process memory.
It has no return value because the list is modified in place. On return
all raw memory addresses are replaced by labels when possible.
@type disasm: list of tuple(int, int, str, str)
@param disasm: Output of one of the dissassembly functions.
"""
for index in compat.xrange(len(disasm)):
(address, size, text, dump) = disasm[index]
m = self.__hexa_parameter.search(text)
while m:
s, e = m.span()
value = text[s:e]
try:
label = self.get_label_at_address( int(value, 0x10) )
except Exception:
label = None
if label:
text = text[:s] + label + text[e:]
e = s + len(value)
m = self.__hexa_parameter.search(text, e)
disasm[index] = (address, size, text, dump) | python | def __fixup_labels(self, disasm):
"""
Private method used when disassembling from process memory.
It has no return value because the list is modified in place. On return
all raw memory addresses are replaced by labels when possible.
@type disasm: list of tuple(int, int, str, str)
@param disasm: Output of one of the dissassembly functions.
"""
for index in compat.xrange(len(disasm)):
(address, size, text, dump) = disasm[index]
m = self.__hexa_parameter.search(text)
while m:
s, e = m.span()
value = text[s:e]
try:
label = self.get_label_at_address( int(value, 0x10) )
except Exception:
label = None
if label:
text = text[:s] + label + text[e:]
e = s + len(value)
m = self.__hexa_parameter.search(text, e)
disasm[index] = (address, size, text, dump) | [
"def",
"__fixup_labels",
"(",
"self",
",",
"disasm",
")",
":",
"for",
"index",
"in",
"compat",
".",
"xrange",
"(",
"len",
"(",
"disasm",
")",
")",
":",
"(",
"address",
",",
"size",
",",
"text",
",",
"dump",
")",
"=",
"disasm",
"[",
"index",
"]",
... | Private method used when disassembling from process memory.
It has no return value because the list is modified in place. On return
all raw memory addresses are replaced by labels when possible.
@type disasm: list of tuple(int, int, str, str)
@param disasm: Output of one of the dissassembly functions. | [
"Private",
"method",
"used",
"when",
"disassembling",
"from",
"process",
"memory",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L490-L514 | train | 209,689 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/process.py | Process.disassemble_current | def disassemble_current(self, dwThreadId):
"""
Disassemble the instruction at the program counter of the given thread.
@type dwThreadId: int
@param dwThreadId: Global thread ID.
The program counter for this thread will be used as the disassembly
address.
@rtype: tuple( long, int, str, str )
@return: The tuple represents an assembly instruction
and contains:
- Memory address of instruction.
- Size of instruction in bytes.
- Disassembly line of instruction.
- Hexadecimal dump of instruction.
"""
aThread = self.get_thread(dwThreadId)
return self.disassemble_instruction(aThread.get_pc()) | python | def disassemble_current(self, dwThreadId):
"""
Disassemble the instruction at the program counter of the given thread.
@type dwThreadId: int
@param dwThreadId: Global thread ID.
The program counter for this thread will be used as the disassembly
address.
@rtype: tuple( long, int, str, str )
@return: The tuple represents an assembly instruction
and contains:
- Memory address of instruction.
- Size of instruction in bytes.
- Disassembly line of instruction.
- Hexadecimal dump of instruction.
"""
aThread = self.get_thread(dwThreadId)
return self.disassemble_instruction(aThread.get_pc()) | [
"def",
"disassemble_current",
"(",
"self",
",",
"dwThreadId",
")",
":",
"aThread",
"=",
"self",
".",
"get_thread",
"(",
"dwThreadId",
")",
"return",
"self",
".",
"disassemble_instruction",
"(",
"aThread",
".",
"get_pc",
"(",
")",
")"
] | Disassemble the instruction at the program counter of the given thread.
@type dwThreadId: int
@param dwThreadId: Global thread ID.
The program counter for this thread will be used as the disassembly
address.
@rtype: tuple( long, int, str, str )
@return: The tuple represents an assembly instruction
and contains:
- Memory address of instruction.
- Size of instruction in bytes.
- Disassembly line of instruction.
- Hexadecimal dump of instruction. | [
"Disassemble",
"the",
"instruction",
"at",
"the",
"program",
"counter",
"of",
"the",
"given",
"thread",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L642-L660 | train | 209,690 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/process.py | Process.is_wow64 | def is_wow64(self):
"""
Determines if the process is running under WOW64.
@rtype: bool
@return:
C{True} if the process is running under WOW64. That is, a 32-bit
application running in a 64-bit Windows.
C{False} if the process is either a 32-bit application running in
a 32-bit Windows, or a 64-bit application running in a 64-bit
Windows.
@raise WindowsError: On error an exception is raised.
@see: U{http://msdn.microsoft.com/en-us/library/aa384249(VS.85).aspx}
"""
try:
wow64 = self.__wow64
except AttributeError:
if (win32.bits == 32 and not win32.wow64):
wow64 = False
else:
if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA:
dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION
else:
dwAccess = win32.PROCESS_QUERY_INFORMATION
hProcess = self.get_handle(dwAccess)
try:
wow64 = win32.IsWow64Process(hProcess)
except AttributeError:
wow64 = False
self.__wow64 = wow64
return wow64 | python | def is_wow64(self):
"""
Determines if the process is running under WOW64.
@rtype: bool
@return:
C{True} if the process is running under WOW64. That is, a 32-bit
application running in a 64-bit Windows.
C{False} if the process is either a 32-bit application running in
a 32-bit Windows, or a 64-bit application running in a 64-bit
Windows.
@raise WindowsError: On error an exception is raised.
@see: U{http://msdn.microsoft.com/en-us/library/aa384249(VS.85).aspx}
"""
try:
wow64 = self.__wow64
except AttributeError:
if (win32.bits == 32 and not win32.wow64):
wow64 = False
else:
if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA:
dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION
else:
dwAccess = win32.PROCESS_QUERY_INFORMATION
hProcess = self.get_handle(dwAccess)
try:
wow64 = win32.IsWow64Process(hProcess)
except AttributeError:
wow64 = False
self.__wow64 = wow64
return wow64 | [
"def",
"is_wow64",
"(",
"self",
")",
":",
"try",
":",
"wow64",
"=",
"self",
".",
"__wow64",
"except",
"AttributeError",
":",
"if",
"(",
"win32",
".",
"bits",
"==",
"32",
"and",
"not",
"win32",
".",
"wow64",
")",
":",
"wow64",
"=",
"False",
"else",
... | Determines if the process is running under WOW64.
@rtype: bool
@return:
C{True} if the process is running under WOW64. That is, a 32-bit
application running in a 64-bit Windows.
C{False} if the process is either a 32-bit application running in
a 32-bit Windows, or a 64-bit application running in a 64-bit
Windows.
@raise WindowsError: On error an exception is raised.
@see: U{http://msdn.microsoft.com/en-us/library/aa384249(VS.85).aspx} | [
"Determines",
"if",
"the",
"process",
"is",
"running",
"under",
"WOW64",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L692-L725 | train | 209,691 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/process.py | Process.get_start_time | def get_start_time(self):
"""
Determines when has this process started running.
@rtype: win32.SYSTEMTIME
@return: Process start time.
"""
if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA:
dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION
else:
dwAccess = win32.PROCESS_QUERY_INFORMATION
hProcess = self.get_handle(dwAccess)
CreationTime = win32.GetProcessTimes(hProcess)[0]
return win32.FileTimeToSystemTime(CreationTime) | python | def get_start_time(self):
"""
Determines when has this process started running.
@rtype: win32.SYSTEMTIME
@return: Process start time.
"""
if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA:
dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION
else:
dwAccess = win32.PROCESS_QUERY_INFORMATION
hProcess = self.get_handle(dwAccess)
CreationTime = win32.GetProcessTimes(hProcess)[0]
return win32.FileTimeToSystemTime(CreationTime) | [
"def",
"get_start_time",
"(",
"self",
")",
":",
"if",
"win32",
".",
"PROCESS_ALL_ACCESS",
"==",
"win32",
".",
"PROCESS_ALL_ACCESS_VISTA",
":",
"dwAccess",
"=",
"win32",
".",
"PROCESS_QUERY_LIMITED_INFORMATION",
"else",
":",
"dwAccess",
"=",
"win32",
".",
"PROCESS_... | Determines when has this process started running.
@rtype: win32.SYSTEMTIME
@return: Process start time. | [
"Determines",
"when",
"has",
"this",
"process",
"started",
"running",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L780-L793 | train | 209,692 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/process.py | Process.get_exit_time | def get_exit_time(self):
"""
Determines when has this process finished running.
If the process is still alive, the current time is returned instead.
@rtype: win32.SYSTEMTIME
@return: Process exit time.
"""
if self.is_alive():
ExitTime = win32.GetSystemTimeAsFileTime()
else:
if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA:
dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION
else:
dwAccess = win32.PROCESS_QUERY_INFORMATION
hProcess = self.get_handle(dwAccess)
ExitTime = win32.GetProcessTimes(hProcess)[1]
return win32.FileTimeToSystemTime(ExitTime) | python | def get_exit_time(self):
"""
Determines when has this process finished running.
If the process is still alive, the current time is returned instead.
@rtype: win32.SYSTEMTIME
@return: Process exit time.
"""
if self.is_alive():
ExitTime = win32.GetSystemTimeAsFileTime()
else:
if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA:
dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION
else:
dwAccess = win32.PROCESS_QUERY_INFORMATION
hProcess = self.get_handle(dwAccess)
ExitTime = win32.GetProcessTimes(hProcess)[1]
return win32.FileTimeToSystemTime(ExitTime) | [
"def",
"get_exit_time",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_alive",
"(",
")",
":",
"ExitTime",
"=",
"win32",
".",
"GetSystemTimeAsFileTime",
"(",
")",
"else",
":",
"if",
"win32",
".",
"PROCESS_ALL_ACCESS",
"==",
"win32",
".",
"PROCESS_ALL_ACCESS_VI... | Determines when has this process finished running.
If the process is still alive, the current time is returned instead.
@rtype: win32.SYSTEMTIME
@return: Process exit time. | [
"Determines",
"when",
"has",
"this",
"process",
"finished",
"running",
".",
"If",
"the",
"process",
"is",
"still",
"alive",
"the",
"current",
"time",
"is",
"returned",
"instead",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L795-L812 | train | 209,693 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/process.py | Process.get_running_time | def get_running_time(self):
"""
Determines how long has this process been running.
@rtype: long
@return: Process running time in milliseconds.
"""
if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA:
dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION
else:
dwAccess = win32.PROCESS_QUERY_INFORMATION
hProcess = self.get_handle(dwAccess)
(CreationTime, ExitTime, _, _) = win32.GetProcessTimes(hProcess)
if self.is_alive():
ExitTime = win32.GetSystemTimeAsFileTime()
CreationTime = CreationTime.dwLowDateTime + (CreationTime.dwHighDateTime << 32)
ExitTime = ExitTime.dwLowDateTime + ( ExitTime.dwHighDateTime << 32)
RunningTime = ExitTime - CreationTime
return RunningTime / 10000 | python | def get_running_time(self):
"""
Determines how long has this process been running.
@rtype: long
@return: Process running time in milliseconds.
"""
if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA:
dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATION
else:
dwAccess = win32.PROCESS_QUERY_INFORMATION
hProcess = self.get_handle(dwAccess)
(CreationTime, ExitTime, _, _) = win32.GetProcessTimes(hProcess)
if self.is_alive():
ExitTime = win32.GetSystemTimeAsFileTime()
CreationTime = CreationTime.dwLowDateTime + (CreationTime.dwHighDateTime << 32)
ExitTime = ExitTime.dwLowDateTime + ( ExitTime.dwHighDateTime << 32)
RunningTime = ExitTime - CreationTime
return RunningTime / 10000 | [
"def",
"get_running_time",
"(",
"self",
")",
":",
"if",
"win32",
".",
"PROCESS_ALL_ACCESS",
"==",
"win32",
".",
"PROCESS_ALL_ACCESS_VISTA",
":",
"dwAccess",
"=",
"win32",
".",
"PROCESS_QUERY_LIMITED_INFORMATION",
"else",
":",
"dwAccess",
"=",
"win32",
".",
"PROCES... | Determines how long has this process been running.
@rtype: long
@return: Process running time in milliseconds. | [
"Determines",
"how",
"long",
"has",
"this",
"process",
"been",
"running",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L814-L832 | train | 209,694 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/process.py | Process.get_services | def get_services(self):
"""
Retrieves the list of system services that are currently running in
this process.
@see: L{System.get_services}
@rtype: list( L{win32.ServiceStatusProcessEntry} )
@return: List of service status descriptors.
"""
self.__load_System_class()
pid = self.get_pid()
return [d for d in System.get_active_services() if d.ProcessId == pid] | python | def get_services(self):
"""
Retrieves the list of system services that are currently running in
this process.
@see: L{System.get_services}
@rtype: list( L{win32.ServiceStatusProcessEntry} )
@return: List of service status descriptors.
"""
self.__load_System_class()
pid = self.get_pid()
return [d for d in System.get_active_services() if d.ProcessId == pid] | [
"def",
"get_services",
"(",
"self",
")",
":",
"self",
".",
"__load_System_class",
"(",
")",
"pid",
"=",
"self",
".",
"get_pid",
"(",
")",
"return",
"[",
"d",
"for",
"d",
"in",
"System",
".",
"get_active_services",
"(",
")",
"if",
"d",
".",
"ProcessId",... | Retrieves the list of system services that are currently running in
this process.
@see: L{System.get_services}
@rtype: list( L{win32.ServiceStatusProcessEntry} )
@return: List of service status descriptors. | [
"Retrieves",
"the",
"list",
"of",
"system",
"services",
"that",
"are",
"currently",
"running",
"in",
"this",
"process",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L841-L853 | train | 209,695 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/process.py | Process.get_peb_address | def get_peb_address(self):
"""
Returns a remote pointer to the PEB.
@rtype: int
@return: Remote pointer to the L{win32.PEB} structure.
Returns C{None} on error.
"""
try:
return self._peb_ptr
except AttributeError:
hProcess = self.get_handle(win32.PROCESS_QUERY_INFORMATION)
pbi = win32.NtQueryInformationProcess(hProcess,
win32.ProcessBasicInformation)
address = pbi.PebBaseAddress
self._peb_ptr = address
return address | python | def get_peb_address(self):
"""
Returns a remote pointer to the PEB.
@rtype: int
@return: Remote pointer to the L{win32.PEB} structure.
Returns C{None} on error.
"""
try:
return self._peb_ptr
except AttributeError:
hProcess = self.get_handle(win32.PROCESS_QUERY_INFORMATION)
pbi = win32.NtQueryInformationProcess(hProcess,
win32.ProcessBasicInformation)
address = pbi.PebBaseAddress
self._peb_ptr = address
return address | [
"def",
"get_peb_address",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_peb_ptr",
"except",
"AttributeError",
":",
"hProcess",
"=",
"self",
".",
"get_handle",
"(",
"win32",
".",
"PROCESS_QUERY_INFORMATION",
")",
"pbi",
"=",
"win32",
".",
"NtQue... | Returns a remote pointer to the PEB.
@rtype: int
@return: Remote pointer to the L{win32.PEB} structure.
Returns C{None} on error. | [
"Returns",
"a",
"remote",
"pointer",
"to",
"the",
"PEB",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L902-L918 | train | 209,696 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/process.py | Process.get_command_line_block | def get_command_line_block(self):
"""
Retrieves the command line block memory address and size.
@rtype: tuple(int, int)
@return: Tuple with the memory address of the command line block
and it's maximum size in Unicode characters.
@raise WindowsError: On error an exception is raised.
"""
peb = self.get_peb()
pp = self.read_structure(peb.ProcessParameters,
win32.RTL_USER_PROCESS_PARAMETERS)
s = pp.CommandLine
return (s.Buffer, s.MaximumLength) | python | def get_command_line_block(self):
"""
Retrieves the command line block memory address and size.
@rtype: tuple(int, int)
@return: Tuple with the memory address of the command line block
and it's maximum size in Unicode characters.
@raise WindowsError: On error an exception is raised.
"""
peb = self.get_peb()
pp = self.read_structure(peb.ProcessParameters,
win32.RTL_USER_PROCESS_PARAMETERS)
s = pp.CommandLine
return (s.Buffer, s.MaximumLength) | [
"def",
"get_command_line_block",
"(",
"self",
")",
":",
"peb",
"=",
"self",
".",
"get_peb",
"(",
")",
"pp",
"=",
"self",
".",
"read_structure",
"(",
"peb",
".",
"ProcessParameters",
",",
"win32",
".",
"RTL_USER_PROCESS_PARAMETERS",
")",
"s",
"=",
"pp",
"."... | Retrieves the command line block memory address and size.
@rtype: tuple(int, int)
@return: Tuple with the memory address of the command line block
and it's maximum size in Unicode characters.
@raise WindowsError: On error an exception is raised. | [
"Retrieves",
"the",
"command",
"line",
"block",
"memory",
"address",
"and",
"size",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L1064-L1078 | train | 209,697 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/process.py | Process.get_environment_block | def get_environment_block(self):
"""
Retrieves the environment block memory address for the process.
@note: The size is always enough to contain the environment data, but
it may not be an exact size. It's best to read the memory and
scan for two null wide chars to find the actual size.
@rtype: tuple(int, int)
@return: Tuple with the memory address of the environment block
and it's size.
@raise WindowsError: On error an exception is raised.
"""
peb = self.get_peb()
pp = self.read_structure(peb.ProcessParameters,
win32.RTL_USER_PROCESS_PARAMETERS)
Environment = pp.Environment
try:
EnvironmentSize = pp.EnvironmentSize
except AttributeError:
mbi = self.mquery(Environment)
EnvironmentSize = mbi.RegionSize + mbi.BaseAddress - Environment
return (Environment, EnvironmentSize) | python | def get_environment_block(self):
"""
Retrieves the environment block memory address for the process.
@note: The size is always enough to contain the environment data, but
it may not be an exact size. It's best to read the memory and
scan for two null wide chars to find the actual size.
@rtype: tuple(int, int)
@return: Tuple with the memory address of the environment block
and it's size.
@raise WindowsError: On error an exception is raised.
"""
peb = self.get_peb()
pp = self.read_structure(peb.ProcessParameters,
win32.RTL_USER_PROCESS_PARAMETERS)
Environment = pp.Environment
try:
EnvironmentSize = pp.EnvironmentSize
except AttributeError:
mbi = self.mquery(Environment)
EnvironmentSize = mbi.RegionSize + mbi.BaseAddress - Environment
return (Environment, EnvironmentSize) | [
"def",
"get_environment_block",
"(",
"self",
")",
":",
"peb",
"=",
"self",
".",
"get_peb",
"(",
")",
"pp",
"=",
"self",
".",
"read_structure",
"(",
"peb",
".",
"ProcessParameters",
",",
"win32",
".",
"RTL_USER_PROCESS_PARAMETERS",
")",
"Environment",
"=",
"p... | Retrieves the environment block memory address for the process.
@note: The size is always enough to contain the environment data, but
it may not be an exact size. It's best to read the memory and
scan for two null wide chars to find the actual size.
@rtype: tuple(int, int)
@return: Tuple with the memory address of the environment block
and it's size.
@raise WindowsError: On error an exception is raised. | [
"Retrieves",
"the",
"environment",
"block",
"memory",
"address",
"for",
"the",
"process",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L1080-L1103 | train | 209,698 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/process.py | Process.get_command_line | def get_command_line(self):
"""
Retrieves the command line with wich the program was started.
@rtype: str
@return: Command line string.
@raise WindowsError: On error an exception is raised.
"""
(Buffer, MaximumLength) = self.get_command_line_block()
CommandLine = self.peek_string(Buffer, dwMaxSize=MaximumLength,
fUnicode=True)
gst = win32.GuessStringType
if gst.t_default == gst.t_ansi:
CommandLine = CommandLine.encode('cp1252')
return CommandLine | python | def get_command_line(self):
"""
Retrieves the command line with wich the program was started.
@rtype: str
@return: Command line string.
@raise WindowsError: On error an exception is raised.
"""
(Buffer, MaximumLength) = self.get_command_line_block()
CommandLine = self.peek_string(Buffer, dwMaxSize=MaximumLength,
fUnicode=True)
gst = win32.GuessStringType
if gst.t_default == gst.t_ansi:
CommandLine = CommandLine.encode('cp1252')
return CommandLine | [
"def",
"get_command_line",
"(",
"self",
")",
":",
"(",
"Buffer",
",",
"MaximumLength",
")",
"=",
"self",
".",
"get_command_line_block",
"(",
")",
"CommandLine",
"=",
"self",
".",
"peek_string",
"(",
"Buffer",
",",
"dwMaxSize",
"=",
"MaximumLength",
",",
"fUn... | Retrieves the command line with wich the program was started.
@rtype: str
@return: Command line string.
@raise WindowsError: On error an exception is raised. | [
"Retrieves",
"the",
"command",
"line",
"with",
"wich",
"the",
"program",
"was",
"started",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/process.py#L1105-L1120 | train | 209,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.