idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
20,500
def _notify_unload_dll ( self , event ) : bCallHandler1 = _BreakpointContainer . _notify_unload_dll ( self , event ) bCallHandler2 = event . get_process ( ) . _notify_unload_dll ( event ) return bCallHandler1 and bCallHandler2
Notify the unload of a module .
20,501
def _notify_debug_control_c ( self , event ) : if event . is_first_chance ( ) : event . continueStatus = win32 . DBG_EXCEPTION_HANDLED return True
Notify of a Debug Ctrl - C exception .
20,502
def _notify_ms_vc_exception ( self , event ) : dwType = event . get_exception_information ( 0 ) if dwType == 0x1000 : pszName = event . get_exception_information ( 1 ) dwThreadId = event . get_exception_information ( 2 ) dwFlags = event . get_exception_information ( 3 ) aProcess = event . get_process ( ) szName = aProcess . peek_string ( pszName , fUnicode = False ) if szName : if dwThreadId == - 1 : dwThreadId = event . get_tid ( ) if aProcess . has_thread ( dwThreadId ) : aThread = aProcess . get_thread ( dwThreadId ) else : aThread = Thread ( dwThreadId ) aProcess . _add_thread ( aThread ) aThread . set_name ( szName ) return True
Notify of a Microsoft Visual C exception .
20,503
def _newer ( a , b ) : if not os . path . exists ( a ) : return False if not os . path . exists ( b ) : return True return os . path . getmtime ( a ) >= os . path . getmtime ( b )
Inquire whether file a was written since file b .
20,504
def parse_tokens ( self , tokens , debug = False ) : p = parse . Parser ( self . grammar , self . convert ) p . setup ( ) lineno = 1 column = 0 type = value = start = end = line_text = None prefix = u"" for quintuple in tokens : type , value , start , end , line_text = quintuple if start != ( lineno , column ) : assert ( lineno , column ) <= start , ( ( lineno , column ) , start ) s_lineno , s_column = start if lineno < s_lineno : prefix += "\n" * ( s_lineno - lineno ) lineno = s_lineno column = 0 if column < s_column : prefix += line_text [ column : s_column ] column = s_column if type in ( tokenize . COMMENT , tokenize . NL ) : prefix += value lineno , column = end if value . endswith ( "\n" ) : lineno += 1 column = 0 continue if type == token . OP : type = grammar . opmap [ value ] if debug : self . logger . debug ( "%s %r (prefix=%r)" , token . tok_name [ type ] , value , prefix ) if p . addtoken ( type , value , ( prefix , start ) ) : if debug : self . logger . debug ( "Stop." ) break prefix = "" lineno , column = end if value . endswith ( "\n" ) : lineno += 1 column = 0 else : raise parse . ParseError ( "incomplete input" , type , value , ( prefix , start ) ) return p . rootnode
Parse a series of tokens and return the syntax tree .
20,505
def parse_stream_raw ( self , stream , debug = False ) : tokens = tokenize . generate_tokens ( stream . readline ) return self . parse_tokens ( tokens , debug )
Parse a stream and return the syntax tree .
20,506
def parse_file ( self , filename , encoding = None , debug = False ) : stream = codecs . open ( filename , "r" , encoding ) try : return self . parse_stream ( stream , debug ) finally : stream . close ( )
Parse a file and return the syntax tree .
20,507
def parse_string ( self , text , debug = False ) : tokens = tokenize . generate_tokens ( StringIO . StringIO ( text ) . readline ) return self . parse_tokens ( tokens , debug )
Parse a string and return the syntax tree .
20,508
def dump_threads ( stream = None ) : if stream is None : stream = sys . stderr thread_id_to_name = { } try : for t in threading . enumerate ( ) : thread_id_to_name [ t . ident ] = '%s (daemon: %s, pydevd thread: %s)' % ( t . name , t . daemon , getattr ( t , 'is_pydev_daemon_thread' , False ) ) except : pass from _pydevd_bundle . pydevd_additional_thread_info_regular import _current_frames stream . write ( '===============================================================================\n' ) stream . write ( 'Threads running\n' ) stream . write ( '================================= Thread Dump =================================\n' ) stream . flush ( ) for thread_id , stack in _current_frames ( ) . items ( ) : stream . write ( '\n-------------------------------------------------------------------------------\n' ) stream . write ( " Thread %s" % thread_id_to_name . get ( thread_id , thread_id ) ) stream . write ( '\n\n' ) for i , ( filename , lineno , name , line ) in enumerate ( traceback . extract_stack ( stack ) ) : stream . write ( ' File "%s", line %d, in %s\n' % ( filename , lineno , name ) ) if line : stream . write ( " %s\n" % ( line . strip ( ) ) ) if i == 0 and 'self' in stack . f_locals : stream . write ( ' self: ' ) try : stream . write ( str ( stack . f_locals [ 'self' ] ) ) except : stream . write ( 'Unable to get str of: %s' % ( type ( stack . f_locals [ 'self' ] ) , ) ) stream . write ( '\n' ) stream . flush ( ) stream . write ( '\n=============================== END Thread Dump ===============================' ) stream . flush ( )
Helper to dump thread info .
20,509
def request_debug_privileges ( cls , bIgnoreExceptions = False ) : try : cls . request_privileges ( win32 . SE_DEBUG_NAME ) return True except Exception : if not bIgnoreExceptions : raise return False
Requests debug privileges .
20,510
def drop_debug_privileges ( cls , bIgnoreExceptions = False ) : try : cls . drop_privileges ( win32 . SE_DEBUG_NAME ) return True except Exception : if not bIgnoreExceptions : raise return False
Drops debug privileges .
20,511
def adjust_privileges ( state , privileges ) : with win32 . OpenProcessToken ( win32 . GetCurrentProcess ( ) , win32 . TOKEN_ADJUST_PRIVILEGES ) as hToken : NewState = ( ( priv , state ) for priv in privileges ) win32 . AdjustTokenPrivileges ( hToken , NewState )
Requests or drops privileges .
20,512
def get_file_version_info ( cls , filename ) : pBlock = win32 . GetFileVersionInfo ( filename ) pBuffer , dwLen = win32 . VerQueryValue ( pBlock , "\\" ) if dwLen != ctypes . sizeof ( win32 . VS_FIXEDFILEINFO ) : raise ctypes . WinError ( win32 . ERROR_BAD_LENGTH ) pVersionInfo = ctypes . cast ( pBuffer , ctypes . POINTER ( win32 . VS_FIXEDFILEINFO ) ) VersionInfo = pVersionInfo . contents if VersionInfo . dwSignature != 0xFEEF04BD : raise ctypes . WinError ( win32 . ERROR_BAD_ARGUMENTS ) FileVersion = "%d.%d" % ( VersionInfo . dwFileVersionMS , VersionInfo . dwFileVersionLS ) ProductVersion = "%d.%d" % ( VersionInfo . dwProductVersionMS , VersionInfo . dwProductVersionLS ) if VersionInfo . dwFileFlagsMask & win32 . VS_FF_DEBUG : DebugBuild = ( VersionInfo . dwFileFlags & win32 . VS_FF_DEBUG ) != 0 else : DebugBuild = None LegacyBuild = ( VersionInfo . dwFileOS != win32 . VOS_NT_WINDOWS32 ) FileType = cls . __binary_types . get ( VersionInfo . dwFileType ) if VersionInfo . dwFileType == win32 . VFT_DRV : FileType = cls . __driver_types . get ( VersionInfo . dwFileSubtype ) elif VersionInfo . dwFileType == win32 . VFT_FONT : FileType = cls . __font_types . get ( VersionInfo . dwFileSubtype ) FileDate = ( VersionInfo . dwFileDateMS << 32 ) + VersionInfo . dwFileDateLS if FileDate : CreationTime = win32 . FileTimeToSystemTime ( FileDate ) CreationTimestamp = "%s, %s %d, %d (%d:%d:%d.%d)" % ( cls . __days_of_the_week [ CreationTime . wDayOfWeek ] , cls . __months [ CreationTime . wMonth ] , CreationTime . wDay , CreationTime . wYear , CreationTime . wHour , CreationTime . wMinute , CreationTime . wSecond , CreationTime . wMilliseconds , ) else : CreationTimestamp = None return ( FileVersion , ProductVersion , DebugBuild , LegacyBuild , FileType , CreationTimestamp , )
Get the program version from an executable file if available .
20,513
def set_kill_on_exit_mode ( bKillOnExit = False ) : try : win32 . DebugSetProcessKillOnExit ( bKillOnExit ) except ( AttributeError , WindowsError ) : return False return True
Defines the behavior of the debugged processes when the debugging thread dies . This method only affects the calling thread .
20,514
def enable_step_on_branch_mode ( cls ) : cls . write_msr ( DebugRegister . DebugCtlMSR , DebugRegister . BranchTrapFlag | DebugRegister . LastBranchRecord )
When tracing call this on every single step event for step on branch mode .
20,515
def get_last_branch_location ( cls ) : LastBranchFromIP = cls . read_msr ( DebugRegister . LastBranchFromIP ) LastBranchToIP = cls . read_msr ( DebugRegister . LastBranchToIP ) return ( LastBranchFromIP , LastBranchToIP )
Returns the source and destination addresses of the last taken branch .
20,516
def get_postmortem_debugger ( cls , bits = None ) : if bits is None : bits = cls . bits elif bits not in ( 32 , 64 ) : raise NotImplementedError ( "Unknown architecture (%r bits)" % bits ) if bits == 32 and cls . bits == 64 : keyname = 'HKLM\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug' else : keyname = 'HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug' key = cls . registry [ keyname ] debugger = key . get ( 'Debugger' ) auto = key . get ( 'Auto' ) hotkey = key . get ( 'UserDebuggerHotkey' ) if auto is not None : auto = bool ( auto ) return ( debugger , auto , hotkey )
Returns the postmortem debugging settings from the Registry .
20,517
def get_postmortem_exclusion_list ( cls , bits = None ) : if bits is None : bits = cls . bits elif bits not in ( 32 , 64 ) : raise NotImplementedError ( "Unknown architecture (%r bits)" % bits ) if bits == 32 and cls . bits == 64 : keyname = 'HKLM\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug\\AutoExclusionList' else : keyname = 'HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug\\AutoExclusionList' try : key = cls . registry [ keyname ] except KeyError : return [ ] return [ name for ( name , enabled ) in key . items ( ) if enabled ]
Returns the exclusion list for the postmortem debugger .
20,518
def set_postmortem_debugger ( cls , cmdline , auto = None , hotkey = None , bits = None ) : if bits is None : bits = cls . bits elif bits not in ( 32 , 64 ) : raise NotImplementedError ( "Unknown architecture (%r bits)" % bits ) if bits == 32 and cls . bits == 64 : keyname = 'HKLM\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug' else : keyname = 'HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug' key = cls . registry [ keyname ] if cmdline is not None : key [ 'Debugger' ] = cmdline if auto is not None : key [ 'Auto' ] = int ( bool ( auto ) ) if hotkey is not None : key [ 'UserDebuggerHotkey' ] = int ( hotkey )
Sets the postmortem debugging settings in the Registry .
20,519
def add_to_postmortem_exclusion_list ( cls , pathname , bits = None ) : if bits is None : bits = cls . bits elif bits not in ( 32 , 64 ) : raise NotImplementedError ( "Unknown architecture (%r bits)" % bits ) if bits == 32 and cls . bits == 64 : keyname = 'HKLM\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug\\AutoExclusionList' else : keyname = 'HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug\\AutoExclusionList' try : key = cls . registry [ keyname ] except KeyError : key = cls . registry . create ( keyname ) key [ pathname ] = 1
Adds the given filename to the exclusion list for postmortem debugging .
20,520
def remove_from_postmortem_exclusion_list ( cls , pathname , bits = None ) : if bits is None : bits = cls . bits elif bits not in ( 32 , 64 ) : raise NotImplementedError ( "Unknown architecture (%r bits)" % bits ) if bits == 32 and cls . bits == 64 : keyname = 'HKLM\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug\\AutoExclusionList' else : keyname = 'HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug\\AutoExclusionList' try : key = cls . registry [ keyname ] except KeyError : return try : del key [ pathname ] except KeyError : return
Removes the given filename to the exclusion list for postmortem debugging from the Registry .
20,521
def get_services ( ) : with win32 . OpenSCManager ( dwDesiredAccess = win32 . SC_MANAGER_ENUMERATE_SERVICE ) as hSCManager : try : return win32 . EnumServicesStatusEx ( hSCManager ) except AttributeError : return win32 . EnumServicesStatus ( hSCManager )
Retrieve a list of all system services .
20,522
def get_active_services ( ) : with win32 . OpenSCManager ( dwDesiredAccess = win32 . SC_MANAGER_ENUMERATE_SERVICE ) as hSCManager : return [ entry for entry in win32 . EnumServicesStatusEx ( hSCManager , dwServiceType = win32 . SERVICE_WIN32 , dwServiceState = win32 . SERVICE_ACTIVE ) if entry . ProcessId ]
Retrieve a list of all active system services .
20,523
def get_service ( name ) : with win32 . OpenSCManager ( dwDesiredAccess = win32 . SC_MANAGER_ENUMERATE_SERVICE ) as hSCManager : with win32 . OpenService ( hSCManager , name , dwDesiredAccess = win32 . SERVICE_QUERY_STATUS ) as hService : try : return win32 . QueryServiceStatusEx ( hService ) except AttributeError : return win32 . QueryServiceStatus ( hService )
Get the service descriptor for the given service name .
20,524
def get_service_display_name ( name ) : with win32 . OpenSCManager ( dwDesiredAccess = win32 . SC_MANAGER_ENUMERATE_SERVICE ) as hSCManager : return win32 . GetServiceDisplayName ( hSCManager , name )
Get the service display name for the given service name .
20,525
def get_service_from_display_name ( displayName ) : with win32 . OpenSCManager ( dwDesiredAccess = win32 . SC_MANAGER_ENUMERATE_SERVICE ) as hSCManager : return win32 . GetServiceKeyName ( hSCManager , displayName )
Get the service unique name given its display name .
20,526
def start_service ( name , argv = None ) : with win32 . OpenSCManager ( dwDesiredAccess = win32 . SC_MANAGER_CONNECT ) as hSCManager : with win32 . OpenService ( hSCManager , name , dwDesiredAccess = win32 . SERVICE_START ) as hService : win32 . StartService ( hService )
Start the service given by name .
20,527
def stop_service ( name ) : with win32 . OpenSCManager ( dwDesiredAccess = win32 . SC_MANAGER_CONNECT ) as hSCManager : with win32 . OpenService ( hSCManager , name , dwDesiredAccess = win32 . SERVICE_STOP ) as hService : win32 . ControlService ( hService , win32 . SERVICE_CONTROL_STOP )
Stop the service given by name .
20,528
def pause_service ( name ) : with win32 . OpenSCManager ( dwDesiredAccess = win32 . SC_MANAGER_CONNECT ) as hSCManager : with win32 . OpenService ( hSCManager , name , dwDesiredAccess = win32 . SERVICE_PAUSE_CONTINUE ) as hService : win32 . ControlService ( hService , win32 . SERVICE_CONTROL_PAUSE )
Pause the service given by name .
20,529
def resume_service ( name ) : with win32 . OpenSCManager ( dwDesiredAccess = win32 . SC_MANAGER_CONNECT ) as hSCManager : with win32 . OpenService ( hSCManager , name , dwDesiredAccess = win32 . SERVICE_PAUSE_CONTINUE ) as hService : win32 . ControlService ( hService , win32 . SERVICE_CONTROL_CONTINUE )
Resume the service given by name .
20,530
def _ifconfig_getnode ( ) : for args in ( '' , '-a' , '-av' ) : mac = _find_mac ( 'ifconfig' , args , [ 'hwaddr' , 'ether' ] , lambda i : i + 1 ) if mac : return mac import socket ip_addr = socket . gethostbyname ( socket . gethostname ( ) ) mac = _find_mac ( 'arp' , '-an' , [ ip_addr ] , lambda i : - 1 ) if mac : return mac mac = _find_mac ( 'lanscan' , '-ai' , [ 'lan0' ] , lambda i : 0 ) if mac : return mac return None
Get the hardware address on Unix by running ifconfig .
20,531
def _ipconfig_getnode ( ) : import os , re dirs = [ '' , r'c:\windows\system32' , r'c:\winnt\system32' ] try : import ctypes buffer = ctypes . create_string_buffer ( 300 ) ctypes . windll . kernel32 . GetSystemDirectoryA ( buffer , 300 ) dirs . insert ( 0 , buffer . value . decode ( 'mbcs' ) ) except : pass for dir in dirs : try : pipe = os . popen ( os . path . join ( dir , 'ipconfig' ) + ' /all' ) except IOError : continue for line in pipe : value = line . split ( ':' ) [ - 1 ] . strip ( ) . lower ( ) if re . match ( '([0-9a-f][0-9a-f]-){5}[0-9a-f][0-9a-f]' , value ) : return int ( value . replace ( '-' , '' ) , 16 )
Get the hardware address on Windows by running ipconfig . exe .
20,532
def getnode ( ) : global _node if _node is not None : return _node import sys if sys . platform == 'win32' : getters = [ _windll_getnode , _netbios_getnode , _ipconfig_getnode ] else : getters = [ _unixdll_getnode , _ifconfig_getnode ] for getter in getters + [ _random_getnode ] : try : _node = getter ( ) except : continue if _node is not None : return _node
Get the hardware address as a 48 - bit positive integer .
20,533
def uuid3 ( namespace , name ) : import md5 hash = md5 . md5 ( namespace . bytes + name ) . digest ( ) return UUID ( bytes = hash [ : 16 ] , version = 3 )
Generate a UUID from the MD5 hash of a namespace UUID and a name .
20,534
def default_should_trace_hook ( frame , filename ) : ignored_lines = _filename_to_ignored_lines . get ( filename ) if ignored_lines is None : ignored_lines = { } lines = linecache . getlines ( filename ) for i_line , line in enumerate ( lines ) : j = line . find ( '#' ) if j >= 0 : comment = line [ j : ] if DONT_TRACE_TAG in comment : ignored_lines [ i_line ] = 1 k = i_line - 1 while k >= 0 : if RE_DECORATOR . match ( lines [ k ] ) : ignored_lines [ k ] = 1 k -= 1 else : break k = i_line + 1 while k <= len ( lines ) : if RE_DECORATOR . match ( lines [ k ] ) : ignored_lines [ k ] = 1 k += 1 else : break _filename_to_ignored_lines [ filename ] = ignored_lines func_line = frame . f_code . co_firstlineno - 1 return not ( func_line - 1 in ignored_lines or func_line in ignored_lines )
Return True if this frame should be traced False if tracing should be blocked .
20,535
def clear_trace_filter_cache ( ) : global should_trace_hook try : old_hook = should_trace_hook should_trace_hook = None linecache . clearcache ( ) _filename_to_ignored_lines . clear ( ) finally : should_trace_hook = old_hook
Clear the trace filter cache . Call this after reloading .
20,536
def trace_filter ( mode ) : global should_trace_hook if mode is None : mode = should_trace_hook is None if mode : should_trace_hook = default_should_trace_hook else : should_trace_hook = None return mode
Set the trace filter mode .
20,537
def do ( self , arg ) : ".symfix - Set the default Microsoft Symbol Store settings if missing" self . debug . system . fix_symbol_store_path ( remote = True , force = False )
. symfix - Set the default Microsoft Symbol Store settings if missing
20,538
def dump ( self , filename ) : f = open ( filename , "wb" ) pickle . dump ( self . __dict__ , f , 2 ) f . close ( )
Dump the grammar tables to a pickle file .
20,539
def load ( self , filename ) : f = open ( filename , "rb" ) d = pickle . load ( f ) f . close ( ) self . __dict__ . update ( d )
Load the grammar tables from a pickle file .
20,540
def copy ( self ) : new = self . __class__ ( ) for dict_attr in ( "symbol2number" , "number2symbol" , "dfas" , "keywords" , "tokens" , "symbol2label" ) : setattr ( new , dict_attr , getattr ( self , dict_attr ) . copy ( ) ) new . labels = self . labels [ : ] new . states = self . states [ : ] new . start = self . start return new
Copy the grammar .
20,541
def report ( self ) : from pprint import pprint print "s2n" pprint ( self . symbol2number ) print "n2s" pprint ( self . number2symbol ) print "states" pprint ( self . states ) print "dfas" pprint ( self . dfas ) print "labels" pprint ( self . labels ) print "start" , self . start
Dump the grammar tables to standard output for debugging .
20,542
def dyld_image_suffix_search ( iterator , env = None ) : suffix = dyld_image_suffix ( env ) if suffix is None : return iterator def _inject ( iterator = iterator , suffix = suffix ) : for path in iterator : if path . endswith ( '.dylib' ) : yield path [ : - len ( '.dylib' ) ] + suffix + '.dylib' else : yield path + suffix yield path return _inject ( )
For a potential path iterator add DYLD_IMAGE_SUFFIX semantics
20,543
def traverse_imports ( names ) : pending = [ names ] while pending : node = pending . pop ( ) if node . type == token . NAME : yield node . value elif node . type == syms . dotted_name : yield "" . join ( [ ch . value for ch in node . children ] ) elif node . type == syms . dotted_as_name : pending . append ( node . children [ 0 ] ) elif node . type == syms . dotted_as_names : pending . extend ( node . children [ : : - 2 ] ) else : raise AssertionError ( "unkown node type" )
Walks over all the names imported in a dotted_as_names node .
20,544
def unmodified_isinstance ( * bases ) : class UnmodifiedIsInstance ( type ) : if sys . version_info [ 0 ] == 2 and sys . version_info [ 1 ] <= 6 : @ classmethod def __instancecheck__ ( cls , instance ) : if cls . __name__ in ( str ( base . __name__ ) for base in bases ) : return isinstance ( instance , bases ) subclass = getattr ( instance , '__class__' , None ) subtype = type ( instance ) instance_type = getattr ( abc , '_InstanceType' , None ) if not instance_type : class test_object : pass instance_type = type ( test_object ) if subtype is instance_type : subtype = subclass if subtype is subclass or subclass is None : return cls . __subclasscheck__ ( subtype ) return ( cls . __subclasscheck__ ( subclass ) or cls . __subclasscheck__ ( subtype ) ) else : @ classmethod def __instancecheck__ ( cls , instance ) : if cls . __name__ in ( str ( base . __name__ ) for base in bases ) : return isinstance ( instance , bases ) return type . __instancecheck__ ( cls , instance ) return with_metaclass ( UnmodifiedIsInstance , * bases )
When called in the form
20,545
def do ( self , arg ) : ".exchain - Show the SEH chain" thread = self . get_thread_from_prefix ( ) print "Exception handlers for thread %d" % thread . get_tid ( ) print table = Table ( ) table . addRow ( "Block" , "Function" ) bits = thread . get_bits ( ) for ( seh , seh_func ) in thread . get_seh_chain ( ) : if seh is not None : seh = HexDump . address ( seh , bits ) if seh_func is not None : seh_func = HexDump . address ( seh_func , bits ) table . addRow ( seh , seh_func ) print table . getOutput ( )
. exchain - Show the SEH chain
20,546
def _parse_debug_options ( opts ) : options = { } if not opts : return options for opt in opts . split ( ';' ) : try : key , value = opt . split ( '=' ) except ValueError : continue try : options [ key ] = DEBUG_OPTIONS_PARSER [ key ] ( value ) except KeyError : continue return options
Debug options are semicolon separated key = value pairs WAIT_ON_ABNORMAL_EXIT = True|False WAIT_ON_NORMAL_EXIT = True|False REDIRECT_OUTPUT = True|False VERSION = string INTERPRETER_OPTIONS = string WEB_BROWSER_URL = string url DJANGO_DEBUG = True|False CLIENT_OS_TYPE = WINDOWS|UNIX DEBUG_STDLIB = True|False
20,547
def _compile_varchar_mysql ( element , compiler , ** kw ) : if not element . length or element . length == 'max' : return "TEXT" else : return compiler . visit_VARCHAR ( element , ** kw )
MySQL hack to avoid the VARCHAR requires a length error .
20,548
def Transactional ( fn , self , * argv , ** argd ) : return self . _transactional ( fn , * argv , ** argd )
Decorator that wraps DAO methods to handle transactions automatically .
20,549
def connect ( dbapi_connection , connection_record ) : try : cursor = dbapi_connection . cursor ( ) try : cursor . execute ( "PRAGMA foreign_keys = ON;" ) cursor . execute ( "PRAGMA foreign_keys;" ) if cursor . fetchone ( ) [ 0 ] != 1 : raise Exception ( ) finally : cursor . close ( ) except Exception : dbapi_connection . close ( ) raise sqlite3 . Error ( )
Called once by SQLAlchemy for each new SQLite DB - API connection .
20,550
def _transactional ( self , method , * argv , ** argd ) : self . _session . begin ( subtransactions = True ) try : result = method ( self , * argv , ** argd ) self . _session . commit ( ) return result except : self . _session . rollback ( ) raise
Begins a transaction and calls the given DAO method .
20,551
def add ( self , crash , allow_duplicates = True ) : if not allow_duplicates : signature = pickle . dumps ( crash . signature , protocol = 0 ) if self . _session . query ( CrashDTO . id ) . filter_by ( signature = signature ) . count ( ) > 0 : return crash_id = self . __add_crash ( crash ) self . __add_memory ( crash_id , crash . memoryMap ) crash . _rowid = crash_id
Add a new crash dump to the database optionally filtering them by signature to avoid duplicates .
20,552
def find_by_example ( self , crash , offset = None , limit = None ) : if limit is not None and not limit : warnings . warn ( "CrashDAO.find_by_example() was set a limit of 0" " results, returning without executing a query." ) return [ ] query = self . _session . query ( CrashDTO ) query = query . asc ( CrashDTO . id ) dto = CrashDTO ( crash ) for name , column in compat . iteritems ( CrashDTO . __dict__ ) : if not name . startswith ( '__' ) and name not in ( 'id' , 'signature' , 'data' ) : if isinstance ( column , Column ) : value = getattr ( dto , name , None ) if value is not None : query = query . filter ( column == value ) if offset : query = query . offset ( offset ) if limit : query = query . limit ( limit ) try : return [ dto . toCrash ( ) for dto in query . all ( ) ] except NoResultFound : return [ ]
Find all crash dumps that have common properties with the crash dump provided .
20,553
def count ( self , signature = None ) : query = self . _session . query ( CrashDTO . id ) if signature : sig_pickled = pickle . dumps ( signature , protocol = 0 ) query = query . filter_by ( signature = sig_pickled ) return query . count ( )
Counts how many crash dumps have been stored in this database . Optionally filters the count by heuristic signature .
20,554
def delete ( self , crash ) : query = self . _session . query ( CrashDTO ) . filter_by ( id = crash . _rowid ) query . delete ( synchronize_session = False ) del crash . _rowid
Remove the given crash dump from the database .
20,555
def _repr ( self , obj , level ) : try : obj_repr = type ( obj ) . __repr__ except Exception : obj_repr = None def has_obj_repr ( t ) : r = t . __repr__ try : return obj_repr == r except Exception : return obj_repr is r for t , prefix , suffix , comma in self . collection_types : if isinstance ( obj , t ) and has_obj_repr ( t ) : return self . _repr_iter ( obj , level , prefix , suffix , comma ) for t , prefix , suffix , item_prefix , item_sep , item_suffix in self . dict_types : if isinstance ( obj , t ) and has_obj_repr ( t ) : return self . _repr_dict ( obj , level , prefix , suffix , item_prefix , item_sep , item_suffix ) for t in self . string_types : if isinstance ( obj , t ) and has_obj_repr ( t ) : return self . _repr_str ( obj , level ) if self . _is_long_iter ( obj ) : return self . _repr_long_iter ( obj ) return self . _repr_other ( obj , level )
Returns an iterable of the parts in the final repr string .
20,556
def leaf_to_root ( self ) : node = self subp = [ ] while node : if node . type == TYPE_ALTERNATIVES : node . alternatives . append ( subp ) if len ( node . alternatives ) == len ( node . children ) : subp = [ tuple ( node . alternatives ) ] node . alternatives = [ ] node = node . parent continue else : node = node . parent subp = None break if node . type == TYPE_GROUP : node . group . append ( subp ) if len ( node . group ) == len ( node . children ) : subp = get_characteristic_subpattern ( node . group ) node . group = [ ] node = node . parent continue else : node = node . parent subp = None break if node . type == token_labels . NAME and node . name : subp . append ( node . name ) else : subp . append ( node . type ) node = node . parent return subp
Internal method . Returns a characteristic path of the pattern tree . This method must be run for all leaves until the linear subpatterns are merged into a single
20,557
def leaves ( self ) : "Generator that returns the leaves of the tree" for child in self . children : for x in child . leaves ( ) : yield x if not self . children : yield self
Generator that returns the leaves of the tree
20,558
def tokenize_wrapper ( input ) : skip = set ( ( token . NEWLINE , token . INDENT , token . DEDENT ) ) tokens = tokenize . generate_tokens ( StringIO . StringIO ( input ) . readline ) for quintuple in tokens : type , value , start , end , line_text = quintuple if type not in skip : yield quintuple
Tokenizes a string suppressing significant whitespace .
20,559
def pattern_convert ( grammar , raw_node_info ) : type , value , context , children = raw_node_info if children or type in grammar . number2symbol : return pytree . Node ( type , children , context = context ) else : return pytree . Leaf ( type , value , context = context )
Converts raw node information to a Node or Leaf instance .
20,560
def compile_node ( self , node ) : if node . type == self . syms . Matcher : node = node . children [ 0 ] if node . type == self . syms . Alternatives : alts = [ self . compile_node ( ch ) for ch in node . children [ : : 2 ] ] if len ( alts ) == 1 : return alts [ 0 ] p = pytree . WildcardPattern ( [ [ a ] for a in alts ] , min = 1 , max = 1 ) return p . optimize ( ) if node . type == self . syms . Alternative : units = [ self . compile_node ( ch ) for ch in node . children ] if len ( units ) == 1 : return units [ 0 ] p = pytree . WildcardPattern ( [ units ] , min = 1 , max = 1 ) return p . optimize ( ) if node . type == self . syms . NegatedUnit : pattern = self . compile_basic ( node . children [ 1 : ] ) p = pytree . NegatedPattern ( pattern ) return p . optimize ( ) assert node . type == self . syms . Unit name = None nodes = node . children if len ( nodes ) >= 3 and nodes [ 1 ] . type == token . EQUAL : name = nodes [ 0 ] . value nodes = nodes [ 2 : ] repeat = None if len ( nodes ) >= 2 and nodes [ - 1 ] . type == self . syms . Repeater : repeat = nodes [ - 1 ] nodes = nodes [ : - 1 ] pattern = self . compile_basic ( nodes , repeat ) if repeat is not None : assert repeat . type == self . syms . Repeater children = repeat . children child = children [ 0 ] if child . type == token . STAR : min = 0 max = pytree . HUGE elif child . type == token . PLUS : min = 1 max = pytree . HUGE elif child . type == token . LBRACE : assert children [ - 1 ] . type == token . RBRACE assert len ( children ) in ( 3 , 5 ) min = max = self . get_int ( children [ 1 ] ) if len ( children ) == 5 : max = self . get_int ( children [ 3 ] ) else : assert False if min != 1 or max != 1 : pattern = pattern . optimize ( ) pattern = pytree . WildcardPattern ( [ [ pattern ] ] , min = min , max = max ) if name is not None : pattern . name = name return pattern . optimize ( )
Compiles a node recursively .
20,561
def MAKE_WPARAM ( wParam ) : wParam = ctypes . cast ( wParam , LPVOID ) . value if wParam is None : wParam = 0 return wParam
Convert arguments to the WPARAM type . Used automatically by SendMessage PostMessage etc . You shouldn t need to call this function .
20,562
def iterchildren ( self ) : handle = self . handle index = 0 while 1 : subkey = win32 . RegEnumKey ( handle , index ) if subkey is None : break yield self . child ( subkey ) index += 1
Iterates the subkeys for this Registry key .
20,563
def children ( self ) : handle = self . handle result = [ ] index = 0 while 1 : subkey = win32 . RegEnumKey ( handle , index ) if subkey is None : break result . append ( self . child ( subkey ) ) index += 1 return result
Returns a list of subkeys for this Registry key .
20,564
def child ( self , subkey ) : path = self . _path + '\\' + subkey handle = win32 . RegOpenKey ( self . handle , subkey ) return RegistryKey ( path , handle )
Retrieves a subkey for this Registry key given its name .
20,565
def _split_path ( self , path ) : if '\\' in path : p = path . find ( '\\' ) hive = path [ : p ] path = path [ p + 1 : ] else : hive = path path = None handle = self . _hives_by_name [ hive . upper ( ) ] return handle , path
Splits a Registry path and returns the hive and key .
20,566
def _parse_path ( self , path ) : handle , path = self . _split_path ( path ) if self . _machine is not None : handle = self . _connect_hive ( handle ) return handle , path
Parses a Registry path and returns the hive and key .
20,567
def _join_path ( self , hive , subkey ) : path = self . _hives_by_value [ hive ] if subkey : path = path + '\\' + subkey return path
Joins the hive and key to make a Registry path .
20,568
def _connect_hive ( self , hive ) : try : handle = self . _remote_hives [ hive ] except KeyError : handle = win32 . RegConnectRegistry ( self . _machine , hive ) self . _remote_hives [ hive ] = handle return handle
Connect to the specified hive of a remote Registry .
20,569
def close ( self ) : while self . _remote_hives : hive = self . _remote_hives . popitem ( ) [ 1 ] try : hive . close ( ) except Exception : try : e = sys . exc_info ( ) [ 1 ] msg = "Cannot close registry hive handle %s, reason: %s" msg %= ( hive . value , str ( e ) ) warnings . warn ( msg ) except Exception : pass
Closes all open connections to the remote Registry .
20,570
def create ( self , path ) : path = self . _sanitize_path ( path ) hive , subpath = self . _parse_path ( path ) handle = win32 . RegCreateKey ( hive , subpath ) return RegistryKey ( path , handle )
Creates a new Registry key .
20,571
def subkeys ( self , path ) : result = list ( ) hive , subpath = self . _parse_path ( path ) with win32 . RegOpenKey ( hive , subpath ) as handle : index = 0 while 1 : name = win32 . RegEnumKey ( handle , index ) if name is None : break result . append ( name ) index += 1 return result
Returns a list of subkeys for the given Registry key .
20,572
def iterate ( self , path ) : if path . endswith ( '\\' ) : path = path [ : - 1 ] if not self . has_key ( path ) : raise KeyError ( path ) stack = collections . deque ( ) stack . appendleft ( path ) return self . __iterate ( stack )
Returns a recursive iterator on the specified key and its subkeys .
20,573
def iterkeys ( self ) : stack = collections . deque ( self . _hives ) stack . reverse ( ) return self . __iterate ( stack )
Returns an iterator that crawls the entire Windows Registry .
20,574
def process_command_line ( argv ) : setup = { } for handler in ACCEPTED_ARG_HANDLERS : setup [ handler . arg_name ] = handler . default_val setup [ 'file' ] = '' setup [ 'qt-support' ] = '' i = 0 del argv [ 0 ] while i < len ( argv ) : handler = ARGV_REP_TO_HANDLER . get ( argv [ i ] ) if handler is not None : handler . handle_argv ( argv , i , setup ) elif argv [ i ] . startswith ( '--qt-support' ) : if argv [ i ] == '--qt-support' : setup [ 'qt-support' ] = 'auto' elif argv [ i ] . startswith ( '--qt-support=' ) : qt_support = argv [ i ] [ len ( '--qt-support=' ) : ] valid_modes = ( 'none' , 'auto' , 'pyqt5' , 'pyqt4' , 'pyside' ) if qt_support not in valid_modes : raise ValueError ( "qt-support mode invalid: " + qt_support ) if qt_support == 'none' : setup [ 'qt-support' ] = '' else : setup [ 'qt-support' ] = qt_support else : raise ValueError ( "Unexpected definition for qt-support flag: " + argv [ i ] ) del argv [ i ] elif argv [ i ] == '--file' : del argv [ i ] setup [ 'file' ] = argv [ i ] i = len ( argv ) elif argv [ i ] == '--DEBUG' : from pydevd import set_debug del argv [ i ] set_debug ( setup ) else : raise ValueError ( "Unexpected option: " + argv [ i ] ) return setup
parses the arguments . removes our arguments from the command line
20,575
def getVariable ( dbg , thread_id , frame_id , scope , attrs ) : if scope == 'BY_ID' : if thread_id != get_current_thread_id ( threading . currentThread ( ) ) : raise VariableError ( "getVariable: must execute on same thread" ) try : import gc objects = gc . get_objects ( ) except : pass else : frame_id = int ( frame_id ) for var in objects : if id ( var ) == frame_id : if attrs is not None : attrList = attrs . split ( '\t' ) for k in attrList : _type , _typeName , resolver = get_type ( var ) var = resolver . resolve ( var , k ) return var sys . stderr . write ( 'Unable to find object with id: %s\n' % ( frame_id , ) ) return None frame = dbg . find_frame ( thread_id , frame_id ) if frame is None : return { } if attrs is not None : attrList = attrs . split ( '\t' ) else : attrList = [ ] for attr in attrList : attr . replace ( "@_@TAB_CHAR@_@" , '\t' ) if scope == 'EXPRESSION' : for count in xrange ( len ( attrList ) ) : if count == 0 : var = evaluate_expression ( dbg , frame , attrList [ count ] , False ) else : _type , _typeName , resolver = get_type ( var ) var = resolver . resolve ( var , attrList [ count ] ) else : if scope == "GLOBAL" : var = frame . f_globals del attrList [ 0 ] else : var = { } var . update ( frame . f_globals ) var . update ( frame . f_locals ) for k in attrList : _type , _typeName , resolver = get_type ( var ) var = resolver . resolve ( var , k ) return var
returns the value of a variable
20,576
def resolve_compound_variable_fields ( dbg , thread_id , frame_id , scope , attrs ) : var = getVariable ( dbg , thread_id , frame_id , scope , attrs ) try : _type , _typeName , resolver = get_type ( var ) return _typeName , resolver . get_dictionary ( var ) except : pydev_log . exception ( 'Error evaluating: thread_id: %s\nframe_id: %s\nscope: %s\nattrs: %s.' , thread_id , frame_id , scope , attrs )
Resolve compound variable in debugger scopes by its name and attributes
20,577
def resolve_var_object ( var , attrs ) : if attrs is not None : attr_list = attrs . split ( '\t' ) else : attr_list = [ ] for k in attr_list : type , _typeName , resolver = get_type ( var ) var = resolver . resolve ( var , k ) return var
Resolve variable s attribute
20,578
def resolve_compound_var_object_fields ( var , attrs ) : attr_list = attrs . split ( '\t' ) for k in attr_list : type , _typeName , resolver = get_type ( var ) var = resolver . resolve ( var , k ) try : type , _typeName , resolver = get_type ( var ) return resolver . get_dictionary ( var ) except : pydev_log . exception ( )
Resolve compound variable by its object and attributes
20,579
def custom_operation ( dbg , thread_id , frame_id , scope , attrs , style , code_or_file , operation_fn_name ) : expressionValue = getVariable ( dbg , thread_id , frame_id , scope , attrs ) try : namespace = { '__name__' : '<custom_operation>' } if style == "EXECFILE" : namespace [ '__file__' ] = code_or_file execfile ( code_or_file , namespace , namespace ) else : namespace [ '__file__' ] = '<customOperationCode>' Exec ( code_or_file , namespace , namespace ) return str ( namespace [ operation_fn_name ] ( expressionValue ) ) except : pydev_log . exception ( )
We ll execute the code_or_file and then search in the namespace the operation_fn_name to execute with the given var .
20,580
def evaluate_expression ( dbg , frame , expression , is_exec ) : if frame is None : return updated_globals = { } updated_globals . update ( frame . f_globals ) updated_globals . update ( frame . f_locals ) try : expression = str ( expression . replace ( '@LINE@' , '\n' ) ) if is_exec : try : compiled = compile ( expression , '<string>' , 'eval' ) except : Exec ( expression , updated_globals , frame . f_locals ) pydevd_save_locals . save_locals ( frame ) else : result = eval ( compiled , updated_globals , frame . f_locals ) if result is not None : sys . stdout . write ( '%s\n' % ( result , ) ) return else : return eval_in_context ( expression , updated_globals , frame . f_locals ) finally : del updated_globals del frame
returns the result of the evaluated expression
20,581
def change_attr_expression ( frame , attr , expression , dbg , value = SENTINEL_VALUE ) : if frame is None : return try : expression = expression . replace ( '@LINE@' , '\n' ) if dbg . plugin and value is SENTINEL_VALUE : result = dbg . plugin . change_variable ( frame , attr , expression ) if result : return result if attr [ : 7 ] == "Globals" : attr = attr [ 8 : ] if attr in frame . f_globals : if value is SENTINEL_VALUE : value = eval ( expression , frame . f_globals , frame . f_locals ) frame . f_globals [ attr ] = value return frame . f_globals [ attr ] else : if '.' not in attr : if pydevd_save_locals . is_save_locals_available ( ) : if value is SENTINEL_VALUE : value = eval ( expression , frame . f_globals , frame . f_locals ) frame . f_locals [ attr ] = value pydevd_save_locals . save_locals ( frame ) return frame . f_locals [ attr ] if value is SENTINEL_VALUE : value = eval ( expression , frame . f_globals , frame . f_locals ) result = value Exec ( '%s=%s' % ( attr , expression ) , frame . f_globals , frame . f_locals ) return result except Exception : pydev_log . exception ( )
Changes some attribute in a given frame .
20,582
def set_condition ( self , condition = True ) : if condition is None : self . __condition = True else : self . __condition = condition
Sets a new condition callback for the breakpoint .
20,583
def eval_condition ( self , event ) : condition = self . get_condition ( ) if condition is True : return True if callable ( condition ) : try : return bool ( condition ( event ) ) except Exception : e = sys . exc_info ( ) [ 1 ] msg = ( "Breakpoint condition callback %r" " raised an exception: %s" ) msg = msg % ( condition , traceback . format_exc ( e ) ) warnings . warn ( msg , BreakpointCallbackWarning ) return False return bool ( condition )
Evaluates the breakpoint condition if any was set .
20,584
def run_action ( self , event ) : action = self . get_action ( ) if action is not None : try : return bool ( action ( event ) ) except Exception : e = sys . exc_info ( ) [ 1 ] msg = ( "Breakpoint action callback %r" " raised an exception: %s" ) msg = msg % ( action , traceback . format_exc ( e ) ) warnings . warn ( msg , BreakpointCallbackWarning ) return False return True
Executes the breakpoint action callback if any was set .
20,585
def hit ( self , event ) : aProcess = event . get_process ( ) aThread = event . get_thread ( ) state = self . get_state ( ) event . breakpoint = self if state == self . ENABLED : self . running ( aProcess , aThread ) elif state == self . RUNNING : self . enable ( aProcess , aThread ) elif state == self . ONESHOT : self . disable ( aProcess , aThread ) elif state == self . DISABLED : msg = "Hit a disabled breakpoint at address %s" msg = msg % HexDump . address ( self . get_address ( ) ) warnings . warn ( msg , BreakpointWarning )
Notify a breakpoint that it s been hit .
20,586
def __set_bp ( self , aProcess ) : address = self . get_address ( ) self . __previousValue = aProcess . read ( address , len ( self . bpInstruction ) ) if self . __previousValue == self . bpInstruction : msg = "Possible overlapping code breakpoints at %s" msg = msg % HexDump . address ( address ) warnings . warn ( msg , BreakpointWarning ) aProcess . write ( address , self . bpInstruction )
Writes a breakpoint instruction at the target address .
20,587
def __set_bp ( self , aProcess ) : lpAddress = self . get_address ( ) dwSize = self . get_size ( ) flNewProtect = aProcess . mquery ( lpAddress ) . Protect flNewProtect = flNewProtect | win32 . PAGE_GUARD aProcess . mprotect ( lpAddress , dwSize , flNewProtect )
Sets the target pages as guard pages .
20,588
def __clear_bp ( self , aProcess ) : lpAddress = self . get_address ( ) flNewProtect = aProcess . mquery ( lpAddress ) . Protect flNewProtect = flNewProtect & ( 0xFFFFFFFF ^ win32 . PAGE_GUARD ) aProcess . mprotect ( lpAddress , self . get_size ( ) , flNewProtect )
Restores the original permissions of the target pages .
20,589
def __clear_bp ( self , aThread ) : if self . __slot is not None : aThread . suspend ( ) try : ctx = aThread . get_context ( win32 . CONTEXT_DEBUG_REGISTERS ) DebugRegister . clear_bp ( ctx , self . __slot ) aThread . set_context ( ctx ) self . __slot = None finally : aThread . resume ( )
Clears this breakpoint from the debug registers .
20,590
def __set_bp ( self , aThread ) : if self . __slot is None : aThread . suspend ( ) try : ctx = aThread . get_context ( win32 . CONTEXT_DEBUG_REGISTERS ) self . __slot = DebugRegister . find_slot ( ctx ) if self . __slot is None : msg = "No available hardware breakpoint slots for thread ID %d" msg = msg % aThread . get_tid ( ) raise RuntimeError ( msg ) DebugRegister . set_bp ( ctx , self . __slot , self . get_address ( ) , self . __trigger , self . __watch ) aThread . set_context ( ctx ) finally : aThread . resume ( )
Sets this breakpoint in the debug registers .
20,591
def __postCallAction_hwbp ( self , event ) : tid = event . get_tid ( ) address = event . breakpoint . get_address ( ) event . debug . erase_hardware_breakpoint ( tid , address ) try : self . __postCallAction ( event ) finally : self . __pop_params ( tid )
Handles hardware breakpoint events on return from the function .
20,592
def __postCallAction_codebp ( self , event ) : tid = event . get_tid ( ) if tid not in self . __paramStack : return True pid = event . get_pid ( ) address = event . breakpoint . get_address ( ) event . debug . dont_break_at ( pid , address ) try : self . __postCallAction ( event ) finally : self . __pop_params ( tid )
Handles code breakpoint events on return from the function .
20,593
def __postCallAction ( self , event ) : aThread = event . get_thread ( ) retval = self . _get_return_value ( aThread ) self . __callHandler ( self . __postCB , event , retval )
Calls the post callback .
20,594
def __callHandler ( self , callback , event , * params ) : if callback is not None : event . hook = self callback ( event , * params )
Calls a pre or post handler if set .
20,595
def __push_params ( self , tid , params ) : stack = self . __paramStack . get ( tid , [ ] ) stack . append ( params ) self . __paramStack [ tid ] = stack
Remembers the arguments tuple for the last call to the hooked function from this thread .
20,596
def __pop_params ( self , tid ) : stack = self . __paramStack [ tid ] stack . pop ( ) if not stack : del self . __paramStack [ tid ]
Forgets the arguments tuple for the last call to the hooked function from this thread .
20,597
def get_params ( self , tid ) : try : params = self . get_params_stack ( tid ) [ - 1 ] except IndexError : msg = "Hooked function called from thread %d already returned" raise IndexError ( msg % tid ) return params
Returns the parameters found in the stack when the hooked function was last called by this thread .
20,598
def get_params_stack ( self , tid ) : try : stack = self . __paramStack [ tid ] except KeyError : msg = "Hooked function was not called from thread %d" raise KeyError ( msg % tid ) return stack
Returns the parameters found in the stack each time the hooked function was called by this thread and hasn t returned yet .
20,599
def hook ( self , debug , pid , address ) : return debug . break_at ( pid , address , self )
Installs the function hook at a given process and address .