idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
20,700
def bk_cyan ( cls ) : "Make the text background color cyan." wAttributes = cls . _get_text_attributes ( ) wAttributes &= ~ win32 . BACKGROUND_MASK wAttributes |= win32 . BACKGROUND_CYAN cls . _set_text_attributes ( wAttributes )
Make the text background color cyan .
20,701
def bk_magenta ( cls ) : "Make the text background color magenta." wAttributes = cls . _get_text_attributes ( ) wAttributes &= ~ win32 . BACKGROUND_MASK wAttributes |= win32 . BACKGROUND_MAGENTA cls . _set_text_attributes ( wAttributes )
Make the text background color magenta .
20,702
def bk_yellow ( cls ) : "Make the text background color yellow." wAttributes = cls . _get_text_attributes ( ) wAttributes &= ~ win32 . BACKGROUND_MASK wAttributes |= win32 . BACKGROUND_YELLOW cls . _set_text_attributes ( wAttributes )
Make the text background color yellow .
20,703
def addRow ( self , * row ) : row = [ str ( item ) for item in row ] len_row = [ len ( item ) for item in row ] width = self . __width len_old = len ( width ) len_new = len ( row ) known = min ( len_old , len_new ) missing = len_new - len_old if missing > 0 : width . extend ( len_row [ - missing : ] ) elif missing < 0 : len_row . extend ( [ 0 ] * ( - missing ) ) self . __width = [ max ( width [ i ] , len_row [ i ] ) for i in compat . xrange ( len ( len_row ) ) ] self . __cols . append ( row )
Add a row to the table . All items are converted to strings .
20,704
def justify ( self , column , direction ) : if direction == - 1 : self . __width [ column ] = abs ( self . __width [ column ] ) elif direction == 1 : self . __width [ column ] = - abs ( self . __width [ column ] ) else : raise ValueError ( "Bad direction value." )
Make the text in a column left or right justified .
20,705
def getWidth ( self ) : width = 0 if self . __width : width = sum ( abs ( x ) for x in self . __width ) width = width + len ( self . __width ) * len ( self . __sep ) + 1 return width
Get the width of the text output for the table .
20,706
def yieldOutput ( self ) : width = self . __width if width : num_cols = len ( width ) fmt = [ '%%%ds' % - w for w in width ] if width [ - 1 ] > 0 : fmt [ - 1 ] = '%s' fmt = self . __sep . join ( fmt ) for row in self . __cols : row . extend ( [ '' ] * ( num_cols - len ( row ) ) ) yield fmt % tuple ( row )
Generate the text output for the table .
20,707
def dump_registers_peek ( registers , data , separator = ' ' , width = 16 ) : if None in ( registers , data ) : return '' names = compat . keys ( data ) names . sort ( ) result = '' for reg_name in names : tag = reg_name . lower ( ) dumped = HexDump . hexline ( data [ reg_name ] , separator , width ) result += '%s -> %s\n' % ( tag , dumped ) return result
Dump data pointed to by the given registers if any .
20,708
def dump_data_peek ( data , base = 0 , separator = ' ' , width = 16 , bits = None ) : if data is None : return '' pointers = compat . keys ( data ) pointers . sort ( ) result = '' for offset in pointers : dumped = HexDump . hexline ( data [ offset ] , separator , width ) address = HexDump . address ( base + offset , bits ) result += '%s -> %s\n' % ( address , dumped ) return result
Dump data from pointers guessed within the given binary data .
20,709
def dump_stack_peek ( data , separator = ' ' , width = 16 , arch = None ) : if data is None : return '' if arch is None : arch = win32 . arch pointers = compat . keys ( data ) pointers . sort ( ) result = '' if pointers : if arch == win32 . ARCH_I386 : spreg = 'esp' elif arch == win32 . ARCH_AMD64 : spreg = 'rsp' else : spreg = 'STACK' tag_fmt = '[%s+0x%%.%dx]' % ( spreg , len ( '%x' % pointers [ - 1 ] ) ) for offset in pointers : dumped = HexDump . hexline ( data [ offset ] , separator , width ) tag = tag_fmt % offset result += '%s -> %s\n' % ( tag , dumped ) return result
Dump data from pointers guessed within the given stack dump .
20,710
def dump_code ( disassembly , pc = None , bLowercase = True , bits = None ) : if not disassembly : return '' table = Table ( sep = ' | ' ) for ( addr , size , code , dump ) in disassembly : if bLowercase : code = code . lower ( ) if addr == pc : addr = ' * %s' % HexDump . address ( addr , bits ) else : addr = ' %s' % HexDump . address ( addr , bits ) table . addRow ( addr , dump , code ) table . justify ( 1 , 1 ) return table . getOutput ( )
Dump a disassembly . Optionally mark where the program counter is .
20,711
def dump_memory_map ( memoryMap , mappedFilenames = None , bits = None ) : if not memoryMap : return '' table = Table ( ) if mappedFilenames : table . addRow ( "Address" , "Size" , "State" , "Access" , "Type" , "File" ) else : table . addRow ( "Address" , "Size" , "State" , "Access" , "Type" ) for mbi in memoryMap : BaseAddress = HexDump . address ( mbi . BaseAddress , bits ) RegionSize = HexDump . address ( mbi . RegionSize , bits ) mbiState = mbi . State if mbiState == win32 . MEM_RESERVE : State = "Reserved" elif mbiState == win32 . MEM_COMMIT : State = "Commited" elif mbiState == win32 . MEM_FREE : State = "Free" else : State = "Unknown" if mbiState != win32 . MEM_COMMIT : Protect = "" else : mbiProtect = mbi . Protect if mbiProtect & win32 . PAGE_NOACCESS : Protect = "--- " elif mbiProtect & win32 . PAGE_READONLY : Protect = "R-- " elif mbiProtect & win32 . PAGE_READWRITE : Protect = "RW- " elif mbiProtect & win32 . PAGE_WRITECOPY : Protect = "RC- " elif mbiProtect & win32 . PAGE_EXECUTE : Protect = "--X " elif mbiProtect & win32 . PAGE_EXECUTE_READ : Protect = "R-X " elif mbiProtect & win32 . PAGE_EXECUTE_READWRITE : Protect = "RWX " elif mbiProtect & win32 . PAGE_EXECUTE_WRITECOPY : Protect = "RCX " else : Protect = "??? " if mbiProtect & win32 . PAGE_GUARD : Protect += "G" else : Protect += "-" if mbiProtect & win32 . PAGE_NOCACHE : Protect += "N" else : Protect += "-" if mbiProtect & win32 . PAGE_WRITECOMBINE : Protect += "W" else : Protect += "-" mbiType = mbi . Type if mbiType == win32 . MEM_IMAGE : Type = "Image" elif mbiType == win32 . MEM_MAPPED : Type = "Mapped" elif mbiType == win32 . MEM_PRIVATE : Type = "Private" elif mbiType == 0 : Type = "" else : Type = "Unknown" if mappedFilenames : FileName = mappedFilenames . get ( mbi . BaseAddress , '' ) table . addRow ( BaseAddress , RegionSize , State , Protect , Type , FileName ) else : table . addRow ( BaseAddress , RegionSize , State , Protect , Type ) return table . getOutput ( )
Dump the memory map of a process . Optionally show the filenames for memory mapped files as well .
20,712
def log_text ( text ) : if text . endswith ( '\n' ) : text = text [ : - len ( '\n' ) ] ltime = time . strftime ( "%X" ) msecs = ( time . time ( ) % 1 ) * 1000 return '[%s.%04d] %s' % ( ltime , msecs , text )
Log lines of text inserting a timestamp .
20,713
def __logfile_error ( self , e ) : from sys import stderr msg = "Warning, error writing log file %s: %s\n" msg = msg % ( self . logfile , str ( e ) ) stderr . write ( DebugLog . log_text ( msg ) ) self . logfile = None self . fd = None
Shows an error message to standard error if the log file can t be written to .
20,714
def log_request ( self , code = '-' , size = '-' ) : if self . server . logRequests : BaseHTTPServer . BaseHTTPRequestHandler . log_request ( self , code , size )
Selectively log an accepted request .
20,715
def versionok_for_gui ( ) : if sys . hexversion < 0x02060000 : return False if sys . hexversion >= 0x03000000 and sys . hexversion < 0x03020000 : return False if sys . platform . startswith ( "java" ) or sys . platform . startswith ( 'cli' ) : return False return True
Return True if running Python is suitable for GUI Event Integration and deeper IPython integration
20,716
def RaiseIfNotErrorSuccess ( result , func = None , arguments = ( ) ) : if result != ERROR_SUCCESS : raise ctypes . WinError ( result ) return result
Error checking for Win32 Registry API calls .
20,717
def do ( self , arg ) : ".example - This is an example plugin for the command line debugger" print "This is an example command." print "%s.do(%r, %r):" % ( __name__ , self , arg ) print " last event" , self . lastEvent print " prefix" , self . cmdprefix print " arguments" , self . split_tokens ( arg )
. example - This is an example plugin for the command line debugger
20,718
def set_process ( self , process = None ) : if process is None : self . dwProcessId = None self . __process = None else : self . __load_Process_class ( ) if not isinstance ( process , Process ) : msg = "Parent process must be a Process instance, " msg += "got %s instead" % type ( process ) raise TypeError ( msg ) self . dwProcessId = process . get_pid ( ) self . __process = process
Manually set the parent Process object . Use with care!
20,719
def open_handle ( self , dwDesiredAccess = win32 . THREAD_ALL_ACCESS ) : hThread = win32 . OpenThread ( dwDesiredAccess , win32 . FALSE , self . dwThreadId ) if not hasattr ( self . hThread , '__del__' ) : self . close_handle ( ) self . hThread = hThread
Opens a new handle to the thread closing the previous one .
20,720
def close_handle ( self ) : try : if hasattr ( self . hThread , 'close' ) : self . hThread . close ( ) elif self . hThread not in ( None , win32 . INVALID_HANDLE_VALUE ) : win32 . CloseHandle ( self . hThread ) finally : self . hThread = None
Closes the handle to the thread .
20,721
def kill ( self , dwExitCode = 0 ) : hThread = self . get_handle ( win32 . THREAD_TERMINATE ) win32 . TerminateThread ( hThread , dwExitCode ) if self . pInjectedMemory is not None : try : self . get_process ( ) . free ( self . pInjectedMemory ) self . pInjectedMemory = None except Exception : pass
Terminates the thread execution .
20,722
def suspend ( self ) : hThread = self . get_handle ( win32 . THREAD_SUSPEND_RESUME ) if self . is_wow64 ( ) : try : return win32 . Wow64SuspendThread ( hThread ) except AttributeError : pass return win32 . SuspendThread ( hThread )
Suspends the thread execution .
20,723
def resume ( self ) : hThread = self . get_handle ( win32 . THREAD_SUSPEND_RESUME ) return win32 . ResumeThread ( hThread )
Resumes the thread execution .
20,724
def set_context ( self , context , bSuspend = False ) : dwAccess = win32 . THREAD_SET_CONTEXT if bSuspend : dwAccess = dwAccess | win32 . THREAD_SUSPEND_RESUME hThread = self . get_handle ( dwAccess ) if bSuspend : self . suspend ( ) try : if win32 . bits == 64 and self . is_wow64 ( ) : win32 . Wow64SetThreadContext ( hThread , context ) else : win32 . SetThreadContext ( hThread , context ) finally : if bSuspend : self . resume ( )
Sets the values of the registers .
20,725
def set_register ( self , register , value ) : context = self . get_context ( ) context [ register ] = value self . set_context ( context )
Sets the value of a specific register .
20,726
def is_wow64 ( self ) : try : wow64 = self . __wow64 except AttributeError : if ( win32 . bits == 32 and not win32 . wow64 ) : wow64 = False else : wow64 = self . get_process ( ) . is_wow64 ( ) self . __wow64 = wow64 return wow64
Determines if the thread is running under WOW64 .
20,727
def get_teb_address ( self ) : try : return self . _teb_ptr except AttributeError : try : hThread = self . get_handle ( win32 . THREAD_QUERY_INFORMATION ) tbi = win32 . NtQueryInformationThread ( hThread , win32 . ThreadBasicInformation ) address = tbi . TebBaseAddress except WindowsError : address = self . get_linear_address ( 'SegFs' , 0 ) if not address : raise self . _teb_ptr = address return address
Returns a remote pointer to the TEB .
20,728
def get_linear_address ( self , segment , address ) : hThread = self . get_handle ( win32 . THREAD_QUERY_INFORMATION ) selector = self . get_register ( segment ) ldt = win32 . GetThreadSelectorEntry ( hThread , selector ) BaseLow = ldt . BaseLow BaseMid = ldt . HighWord . Bytes . BaseMid << 16 BaseHi = ldt . HighWord . Bytes . BaseHi << 24 Base = BaseLow | BaseMid | BaseHi LimitLow = ldt . LimitLow LimitHi = ldt . HighWord . Bits . LimitHi << 16 Limit = LimitLow | LimitHi if address > Limit : msg = "Address %s too large for segment %s (selector %d)" msg = msg % ( HexDump . address ( address , self . get_bits ( ) ) , segment , selector ) raise ValueError ( msg ) return Base + address
Translates segment - relative addresses to linear addresses .
20,729
def get_seh_chain_pointer ( self ) : if win32 . arch != win32 . ARCH_I386 : raise NotImplementedError ( "SEH chain parsing is only supported in 32-bit Windows." ) process = self . get_process ( ) address = self . get_linear_address ( 'SegFs' , 0 ) return process . read_pointer ( address )
Get the pointer to the first structured exception handler block .
20,730
def set_seh_chain_pointer ( self , value ) : if win32 . arch != win32 . ARCH_I386 : raise NotImplementedError ( "SEH chain parsing is only supported in 32-bit Windows." ) process = self . get_process ( ) address = self . get_linear_address ( 'SegFs' , 0 ) process . write_pointer ( address , value )
Change the pointer to the first structured exception handler block .
20,731
def get_stack_frame_range ( self ) : st , sb = self . get_stack_range ( ) sp = self . get_sp ( ) fp = self . get_fp ( ) size = fp - sp if not st <= sp < sb : raise RuntimeError ( 'Stack pointer lies outside the stack' ) if not st <= fp < sb : raise RuntimeError ( 'Frame pointer lies outside the stack' ) if sp > fp : raise RuntimeError ( 'No valid stack frame found' ) return ( sp , fp )
Returns the starting and ending addresses of the stack frame . Only works for functions with standard prologue and epilogue .
20,732
def get_stack_frame ( self , max_size = None ) : sp , fp = self . get_stack_frame_range ( ) size = fp - sp if max_size and size > max_size : size = max_size return self . get_process ( ) . peek ( sp , size )
Reads the contents of the current stack frame . Only works for functions with standard prologue and epilogue .
20,733
def read_stack_data ( self , size = 128 , offset = 0 ) : aProcess = self . get_process ( ) return aProcess . read ( self . get_sp ( ) + offset , size )
Reads the contents of the top of the stack .
20,734
def peek_stack_data ( self , size = 128 , offset = 0 ) : aProcess = self . get_process ( ) return aProcess . peek ( self . get_sp ( ) + offset , size )
Tries to read the contents of the top of the stack .
20,735
def read_stack_dwords ( self , count , offset = 0 ) : if count > 0 : stackData = self . read_stack_data ( count * 4 , offset ) return struct . unpack ( '<' + ( 'L' * count ) , stackData ) return ( )
Reads DWORDs from the top of the stack .
20,736
def peek_stack_dwords ( self , count , offset = 0 ) : 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 )
Tries to read DWORDs from the top of the stack .
20,737
def read_stack_qwords ( self , count , offset = 0 ) : stackData = self . read_stack_data ( count * 8 , offset ) return struct . unpack ( '<' + ( 'Q' * count ) , stackData )
Reads QWORDs from the top of the stack .
20,738
def read_stack_structure ( self , structure , offset = 0 ) : aProcess = self . get_process ( ) stackData = aProcess . read_structure ( self . get_sp ( ) + offset , structure ) return tuple ( [ stackData . __getattribute__ ( name ) for ( name , type ) in stackData . _fields_ ] )
Reads the given structure at the top of the stack .
20,739
def read_stack_frame ( self , structure , offset = 0 ) : aProcess = self . get_process ( ) stackData = aProcess . read_structure ( self . get_fp ( ) + offset , structure ) return tuple ( [ stackData . __getattribute__ ( name ) for ( name , type ) in stackData . _fields_ ] )
Reads the stack frame of the thread .
20,740
def peek_pointers_in_registers ( self , peekSize = 16 , context = None ) : 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 reg_data = aProcess . peek ( reg_value , peekSize ) if reg_data : data [ reg_name ] = reg_data return data
Tries to guess which values in the registers are valid pointers and reads some data from them .
20,741
def find_threads_by_name ( self , name , bExactMatch = True ) : found_threads = list ( ) if name is None : for aThread in self . iter_threads ( ) : if aThread . get_name ( ) is None : found_threads . append ( aThread ) elif bExactMatch : for aThread in self . iter_threads ( ) : if aThread . get_name ( ) == name : found_threads . append ( aThread ) 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
Find threads by name using different search methods .
20,742
def start_thread ( self , lpStartAddress , lpParameter = 0 , bSuspended = False ) : 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
Remotely creates a new thread in the process .
20,743
def scan_threads ( self ) : dwProcessId = self . get_pid ( ) if dwProcessId in ( 0 , 4 , 8 ) : return 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_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 )
Populates the snapshot with running threads .
20,744
def clear_dead_threads ( self ) : for tid in self . get_thread_ids ( ) : aThread = self . get_thread ( tid ) if not aThread . is_alive ( ) : self . _del_thread ( aThread )
Remove Thread objects from the snapshot referring to threads no longer running .
20,745
def clear_threads ( self ) : for aThread in compat . itervalues ( self . __threadDict ) : aThread . clear ( ) self . __threadDict = dict ( )
Clears the threads snapshot .
20,746
def close_thread_handles ( self ) : 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
Closes all open handles to threads in the snapshot .
20,747
def _add_thread ( self , aThread ) : dwThreadId = aThread . dwThreadId aThread . set_process ( self ) self . __threadDict [ dwThreadId ] = aThread
Private method to add a thread object to the snapshot .
20,748
def _del_thread ( self , dwThreadId ) : 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 ( )
Private method to remove a thread object from the snapshot .
20,749
def __add_created_thread ( self , event ) : dwThreadId = event . get_tid ( ) hThread = event . get_thread_handle ( ) if not self . _has_thread_id ( dwThreadId ) : aThread = Thread ( dwThreadId , hThread , self ) teb_ptr = event . get_teb ( ) if teb_ptr : aThread . _teb_ptr = teb_ptr self . _add_thread ( aThread )
Private method to automatically add new thread objects from debug events .
20,750
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 = 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
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 .
20,751
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_modify if code_to_modify . co_name == '<module>' : 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 , code_to_modify . co_kwonlyargcount , len ( new_vars ) , code_to_modify . co_stacksize , code_to_modify . co_flags , new_bytes , new_consts , new_names , new_vars , code_to_modify . co_filename , code_to_modify . co_name , code_to_modify . co_firstlineno , new_lnotab , code_to_modify . co_freevars , code_to_modify . co_cellvars ) return True , new_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
20,752
def set_thread ( self , thread = None ) : 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
Manually set the thread process . Use with care!
20,753
def __get_window ( self , hWnd ) : 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
User internally to get another Window from this one . It ll try to copy the parent Process and Thread references if possible .
20,754
def get_client_rect ( self ) : 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
Get the window s client area coordinates in the desktop .
20,755
def get_child_at ( self , x , y , bAllowTransparency = True ) : 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
Get the child window located at the given coordinates . If no such window exists an exception is raised .
20,756
def show ( self , bAsync = True ) : if bAsync : win32 . ShowWindowAsync ( self . get_handle ( ) , win32 . SW_SHOW ) else : win32 . ShowWindow ( self . get_handle ( ) , win32 . SW_SHOW )
Make the window visible .
20,757
def hide ( self , bAsync = True ) : if bAsync : win32 . ShowWindowAsync ( self . get_handle ( ) , win32 . SW_HIDE ) else : win32 . ShowWindow ( self . get_handle ( ) , win32 . SW_HIDE )
Make the window invisible .
20,758
def maximize ( self , bAsync = True ) : if bAsync : win32 . ShowWindowAsync ( self . get_handle ( ) , win32 . SW_MAXIMIZE ) else : win32 . ShowWindow ( self . get_handle ( ) , win32 . SW_MAXIMIZE )
Maximize the window .
20,759
def minimize ( self , bAsync = True ) : if bAsync : win32 . ShowWindowAsync ( self . get_handle ( ) , win32 . SW_MINIMIZE ) else : win32 . ShowWindow ( self . get_handle ( ) , win32 . SW_MINIMIZE )
Minimize the window .
20,760
def restore ( self , bAsync = True ) : if bAsync : win32 . ShowWindowAsync ( self . get_handle ( ) , win32 . SW_RESTORE ) else : win32 . ShowWindow ( self . get_handle ( ) , win32 . SW_RESTORE )
Unmaximize and unminimize the window .
20,761
def send ( self , uMsg , wParam = None , lParam = None , dwTimeout = None ) : 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 )
Send a low - level window message syncronically .
20,762
def post ( self , uMsg , wParam = None , lParam = None ) : win32 . PostMessage ( self . get_handle ( ) , uMsg , wParam , lParam )
Post a low - level window message asyncronically .
20,763
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 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 ] 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 ( )
Processes a debug adapter protocol json command .
20,764
def _get_hit_condition_expression ( self , hit_condition ) : 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
Following hit condition values are supported
20,765
def inputhook_wx2 ( ) : try : app = wx . GetApp ( ) if app is not None : assert wx . Thread_IsMain ( ) elr = EventLoopRunner ( ) elr . Run ( time = 10 ) except KeyboardInterrupt : pass return 0
Run the wx event loop polling for stdin .
20,766
def _modname ( path ) : base = os . path . basename ( path ) filename , ext = os . path . splitext ( base ) return filename
Return a plausible module name for the path
20,767
def enable_gtk ( self , app = None ) : from pydev_ipython . inputhookgtk import create_inputhook_gtk self . set_inputhook ( create_inputhook_gtk ( self . _stdin_file ) ) self . _current_gui = GUI_GTK
Enable event loop integration with PyGTK .
20,768
def enable_tk ( self , app = None ) : self . _current_gui = GUI_TK if app is None : try : import Tkinter as _TK except : import tkinter as _TK 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
Enable event loop integration with Tk .
20,769
def enable_glut ( self , app = None ) : import OpenGL . GLUT as glut 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 ) 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
Enable event loop integration with GLUT .
20,770
def disable_glut ( self ) : import OpenGL . GLUT as glut from glut_support import glutMainLoopEvent glut . glutHideWindow ( ) glutMainLoopEvent ( ) self . clear_inputhook ( )
Disable event loop integration with glut .
20,771
def enable_pyglet ( self , app = None ) : from pydev_ipython . inputhookpyglet import inputhook_pyglet self . set_inputhook ( inputhook_pyglet ) self . _current_gui = GUI_PYGLET return app
Enable event loop integration with pyglet .
20,772
def enable_mac ( self , app = None ) : 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
Enable event loop integration with MacOSX .
20,773
def _thread_to_xml ( self , thread ) : name = pydevd_xml . make_valid_xml_value ( thread . getName ( ) ) cmdText = '<thread name="%s" id="%s" />' % ( quote ( name ) , get_thread_id ( thread ) ) return cmdText
thread information as XML
20,774
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 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 ( ) )
returns thread listing as XML
20,775
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 : cmd_text = [ '<xml><thread id="%s">' % ( thread_id , ) ] if topmost_frame is not None : frame_id_to_lineno = { } try : 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 : if must_be_suspended : return None else : 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 ( ) )
Returns thread stack as XML .
20,776
def make_get_exception_details_message ( self , seq , thread_id , topmost_frame ) : try : 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 ( ) )
Returns exception details as XML
20,777
def set_process ( self , process = None ) : if process is None : self . __process = None else : global Process 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
Manually set the parent process . Use with care!
20,778
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 )
Get the size and entry point of the module using the Win32 API .
20,779
def open_handle ( self ) : 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 ) if not hasattr ( self . hFile , '__del__' ) : self . close_handle ( ) self . hFile = hFile
Opens a new handle to the module .
20,780
def close_handle ( self ) : 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
Closes the handle to the module .
20,781
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 .
20,782
def is_address_here ( self , address ) : base = self . get_base ( ) size = self . get_size ( ) if base and size : return base <= address < ( base + size ) return None
Tries to determine if the given address belongs to this module .
20,783
def resolve ( self , function ) : filename = self . get_filename ( ) if not filename : return None try : hlib = win32 . GetModuleHandle ( filename ) address = win32 . GetProcAddress ( hlib , function ) except WindowsError : try : hlib = win32 . LoadLibraryEx ( filename , win32 . DONT_RESOLVE_DLL_REFERENCES ) try : address = win32 . GetProcAddress ( hlib , function ) finally : win32 . FreeLibrary ( hlib ) except WindowsError : return None if address in ( None , 0 ) : return None return address - hlib + self . lpBaseOfDll
Resolves a function exported by this module .
20,784
def resolve_label ( self , label ) : 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 module and not self . match_name ( module ) : raise RuntimeError ( "Label does not belong to this module" ) if procedure : address = self . resolve ( procedure ) if address is None : address = self . resolve_symbol ( procedure ) if address is None and procedure == "start" : address = self . get_entry_point ( ) 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 ) ) else : address = self . get_base ( ) if offset : address = address + offset return address
Resolves a label for this module only . If the label refers to another module an exception is raised .
20,785
def clear_modules ( self ) : for aModule in compat . itervalues ( self . __moduleDict ) : aModule . clear ( ) self . __moduleDict = dict ( )
Clears the modules snapshot .
20,786
def parse_label ( module = None , function = None , offset = None ) : try : function = "#0x%x" % function except TypeError : pass 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 ) 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 ) 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
Creates a label from a module and a function name plus an offset .
20,787
def split_label_fuzzy ( self , label ) : module = function = None offset = 0 if not label : label = compat . b ( "0x0" ) else : 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 ( '' ) ) if not label : label = compat . b ( "0x0" ) if compat . b ( '!' ) in label : return self . split_label_strict ( label ) 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 modobj = self . get_module_by_name ( label ) if modobj : module = modobj . get_name ( ) else : try : address = HexInput . integer ( label ) if offset : offset = address + offset else : offset = address try : new_label = self . get_label_at_address ( offset ) module , function , offset = self . split_label_strict ( new_label ) except ValueError : pass except ValueError : function = label if function and function . startswith ( compat . b ( '#' ) ) : try : function = HexInput . integer ( function [ 1 : ] ) except ValueError : pass if not offset : offset = None return ( module , function , offset )
Splits a label entered as user input .
20,788
def sanitize_label ( self , label ) : ( module , function , offset ) = self . split_label_fuzzy ( label ) label = self . parse_label ( module , function , offset ) return label
Converts a label taken from user input into a well - formed label .
20,789
def resolve_label ( self , label ) : module , function , offset = self . split_label_fuzzy ( label ) address = self . resolve_label_components ( module , function , offset ) return address
Resolve the memory address of the given label .
20,790
def get_symbols ( self ) : symbols = list ( ) for aModule in self . iter_modules ( ) : for symbol in aModule . iter_symbols ( ) : symbols . append ( symbol ) return symbols
Returns the debugging symbols for all modules in this snapshot . The symbols are automatically loaded when needed .
20,791
def get_symbol_at_address ( self , address ) : 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
Tries to find the closest matching symbol for the given address .
20,792
def _add_module ( self , aModule ) : lpBaseOfDll = aModule . get_base ( ) aModule . set_process ( self ) self . __moduleDict [ lpBaseOfDll ] = aModule
Private method to add a module object to the snapshot .
20,793
def _del_module ( self , lpBaseOfDll ) : 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 ( )
Private method to remove a module object from the snapshot .
20,794
def __add_loaded_module ( self , event ) : lpBaseOfDll = event . get_module_base ( ) hFile = event . get_file_handle ( ) 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
Private method to automatically add new module objects from debug events .
20,795
def _notify_unload_dll ( self , event ) : lpBaseOfDll = event . get_module_base ( ) if lpBaseOfDll in self . __moduleDict : self . _del_module ( lpBaseOfDll ) return True
Notify the release of a loaded module .
20,796
def connectToDebugger ( self , debuggerPort , debugger_options = None ) : 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 : import pydevd from _pydev_imps . _pydev_saved_modules import threading except : 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" VIRTUAL_CONSOLE_ID = "console_main" f = FakeFrame ( ) f . f_back = None f . f_globals = { } 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' ) 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' ) self . exec_queue . put ( do_connect_to_debugger ) return ( 'connect complete' , )
Used to show console with variables connection . Mainly monkey - patches things in the debugger structure so that the debugger protocol works .
20,797
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
20,798
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 . modules : return QT_API_PYSIDE elif 'PyQt5.QtCore' in sys . modules : return QT_API_PYQT5 return None
Return which API is loaded if any
20,799
def has_binding ( api ) : 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 : mod = __import__ ( module_name ) imp . find_module ( 'QtCore' , mod . __path__ ) imp . find_module ( 'QtGui' , mod . __path__ ) imp . find_module ( 'QtSvg' , mod . __path__ ) if api == QT_API_PYSIDE : return check_version ( mod . __version__ , '1.0.3' ) else : return True except ImportError : return False
Safely check for PyQt4 or PySide without importing submodules