idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
9,500
def get_asset ( self , name , ** kwargs ) : if len ( name . split ( "." ) ) == 3 : return self . get_objects ( [ name ] , ** kwargs ) [ 0 ] else : return self . lookup_asset_symbols ( [ name ] , ** kwargs ) [ 0 ]
Get full asset from name of id
9,501
def process_notice ( self , notice ) : id = notice [ "id" ] _a , _b , _ = id . split ( "." ) if id in self . subscription_objects : self . on_object ( notice ) elif "." . join ( [ _a , _b , "x" ] ) in self . subscription_objects : self . on_object ( notice ) elif id [ : 4 ] == "2.6." : self . on_account ( notice )
This method is called on notices that need processing . Here we call on_object and on_account slots .
9,502
def close ( self , * args , ** kwargs ) : self . run_event . set ( ) self . ws . close ( ) if self . keepalive and self . keepalive . is_alive ( ) : self . keepalive . join ( )
Closes the websocket connection and waits for the ping thread to close
9,503
def rpcexec ( self , payload ) : log . debug ( json . dumps ( payload ) ) self . ws . send ( json . dumps ( payload , ensure_ascii = False ) . encode ( "utf8" ) )
Execute a call by sending the payload
9,504
def text2html_table ( items ) : "Put the texts in `items` in an HTML table." html_code = f html_code += f for i in items [ 0 ] : html_code += f" <th>{i}</th>\n" html_code += f" </tr>\n </thead>\n <tbody>\n" for line in items [ 1 : ] : html_code += " <tr>\n" for i in line : html_code += f" <td>{i}</td>\n" html_code += " </tr>\n" html_code += " </tbody>\n</table><p>" return html_code
Put the texts in items in an HTML table .
9,505
def log_value ( self , name , value , step = None ) : if isinstance ( value , six . string_types ) : raise TypeError ( '"value" should be a number, got {}' . format ( type ( value ) ) ) value = float ( value ) self . _check_step ( step ) tf_name = self . _ensure_tf_name ( name ) summary = self . _scalar_summary ( tf_name , value , step ) self . _log_summary ( tf_name , summary , value , step = step )
Log new value for given name on given step .
9,506
def log_histogram ( self , name , value , step = None ) : if isinstance ( value , six . string_types ) : raise TypeError ( '"value" should be a number, got {}' . format ( type ( value ) ) ) self . _check_step ( step ) tf_name = self . _ensure_tf_name ( name ) summary = self . _histogram_summary ( tf_name , value , step = step ) self . _log_summary ( tf_name , summary , value , step = step )
Log a histogram for given name on given step .
9,507
def log_images ( self , name , images , step = None ) : if isinstance ( images , six . string_types ) : raise TypeError ( '"images" should be a list of ndarrays, got {}' . format ( type ( images ) ) ) self . _check_step ( step ) tf_name = self . _ensure_tf_name ( name ) summary = self . _image_summary ( tf_name , images , step = step ) self . _log_summary ( tf_name , summary , images , step = step )
Log new images for given name on given step .
9,508
def _image_summary ( self , tf_name , images , step = None ) : img_summaries = [ ] for i , img in enumerate ( images ) : try : s = StringIO ( ) except : s = BytesIO ( ) scipy . misc . toimage ( img ) . save ( s , format = "png" ) img_sum = summary_pb2 . Summary . Image ( encoded_image_string = s . getvalue ( ) , height = img . shape [ 0 ] , width = img . shape [ 1 ] ) img_value = summary_pb2 . Summary . Value ( tag = '{}/{}' . format ( tf_name , i ) , image = img_sum ) img_summaries . append ( img_value ) summary = summary_pb2 . Summary ( ) summary . value . add ( tag = tf_name , image = img_sum ) summary = summary_pb2 . Summary ( value = img_summaries ) return summary
Log a list of images .
9,509
def jinja_filter_param_value_str ( value , str_quote_style = "" , bool_is_str = False ) : if ( type ( value ) == bool ) and not bool_is_str : if ( value ) == True : return '1' else : return '0' elif type ( value ) == str or ( ( type ( value ) == bool ) and bool_is_str ) : return str_quote_style + str ( value ) + str_quote_style else : return str ( value )
Convert a parameter value to string suitable to be passed to an EDA tool
9,510
def render_template ( self , template_file , target_file , template_vars = { } ) : template_dir = str ( self . __class__ . __name__ ) . lower ( ) template = self . jinja_env . get_template ( os . path . join ( template_dir , template_file ) ) file_path = os . path . join ( self . work_root , target_file ) with open ( file_path , 'w' ) as f : f . write ( template . render ( template_vars ) )
Render a Jinja2 template for the backend
9,511
def query_target_count ( self , target ) : reply = NVCtrlQueryTargetCountReplyRequest ( display = self . display , opcode = self . display . get_extension_major ( extname ) , target_type = target . type ( ) ) return int ( reply . _data . get ( 'count' ) )
Return the target count
9,512
def query_int_attribute ( self , target , display_mask , attr ) : reply = NVCtrlQueryAttributeReplyRequest ( display = self . display , opcode = self . display . get_extension_major ( extname ) , target_id = target . id ( ) , target_type = target . type ( ) , display_mask = display_mask , attr = attr ) if not reply . _data . get ( 'flags' ) : return None return int ( reply . _data . get ( 'value' ) )
Return the value of an integer attribute
9,513
def set_int_attribute ( self , target , display_mask , attr , value ) : reply = NVCtrlSetAttributeAndGetStatusReplyRequest ( display = self . display , opcode = self . display . get_extension_major ( extname ) , target_id = target . id ( ) , target_type = target . type ( ) , display_mask = display_mask , attr = attr , value = value ) return reply . _data . get ( 'flags' ) != 0
Set the value of an integer attribute
9,514
def query_string_attribute ( self , target , display_mask , attr ) : reply = NVCtrlQueryStringAttributeReplyRequest ( display = self . display , opcode = self . display . get_extension_major ( extname ) , target_id = target . id ( ) , target_type = target . type ( ) , display_mask = display_mask , attr = attr ) if not reply . _data . get ( 'flags' ) : return None return str ( reply . _data . get ( 'string' ) ) . strip ( '\0' )
Return the value of a string attribute
9,515
def query_binary_data ( self , target , display_mask , attr ) : reply = NVCtrlQueryBinaryDataReplyRequest ( display = self . display , opcode = self . display . get_extension_major ( extname ) , target_id = target . id ( ) , target_type = target . type ( ) , display_mask = display_mask , attr = attr ) if not reply . _data . get ( 'flags' ) : return None return reply . _data . get ( 'data' )
Return binary data
9,516
def _displaystr2num ( st ) : num = None for s , n in [ ( 'DFP-' , 16 ) , ( 'TV-' , 8 ) , ( 'CRT-' , 0 ) ] : if st . startswith ( s ) : try : curnum = int ( st [ len ( s ) : ] ) if 0 <= curnum <= 7 : num = n + curnum break except Exception : pass if num is not None : return num else : raise ValueError ( 'Unrecognised display name: ' + st )
Return a display number from a string
9,517
def keycode_to_keysym ( self , keycode , index ) : try : return self . _keymap_codes [ keycode ] [ index ] except IndexError : return X . NoSymbol
Convert a keycode to a keysym looking in entry index . Normally index 0 is unshifted 1 is shifted 2 is alt grid and 3 is shift + alt grid . If that key entry is not bound X . NoSymbol is returned .
9,518
def refresh_keyboard_mapping ( self , evt ) : if isinstance ( evt , event . MappingNotify ) : if evt . request == X . MappingKeyboard : self . _update_keymap ( evt . first_keycode , evt . count ) else : raise TypeError ( 'expected a MappingNotify event' )
This method should be called once when a MappingNotify event is received to update the keymap cache . evt should be the event object .
9,519
def _update_keymap ( self , first_keycode , count ) : lastcode = first_keycode + count for keysym , codes in self . _keymap_syms . items ( ) : i = 0 while i < len ( codes ) : code = codes [ i ] [ 1 ] if code >= first_keycode and code < lastcode : del codes [ i ] else : i = i + 1 keysyms = self . get_keyboard_mapping ( first_keycode , count ) self . _keymap_codes [ first_keycode : lastcode ] = keysyms code = first_keycode for syms in keysyms : index = 0 for sym in syms : if sym != X . NoSymbol : if sym in self . _keymap_syms : symcodes = self . _keymap_syms [ sym ] symcodes . append ( ( index , code ) ) symcodes . sort ( ) else : self . _keymap_syms [ sym ] = [ ( index , code ) ] index = index + 1 code = code + 1
Internal function called to refresh the keymap cache .
9,520
def lookup_string ( self , keysym ) : s = self . keysym_translations . get ( keysym ) if s is not None : return s import Xlib . XK return Xlib . XK . keysym_to_string ( keysym )
Return a string corresponding to KEYSYM or None if no reasonable translation is found .
9,521
def rebind_string ( self , keysym , newstring ) : if newstring is None : try : del self . keysym_translations [ keysym ] except KeyError : pass else : self . keysym_translations [ keysym ] = newstring
Change the translation of KEYSYM to NEWSTRING . If NEWSTRING is None remove old translation if any .
9,522
def intern_atom ( self , name , only_if_exists = 0 ) : r = request . InternAtom ( display = self . display , name = name , only_if_exists = only_if_exists ) return r . atom
Intern the string name returning its atom number . If only_if_exists is true and the atom does not already exist it will not be created and X . NONE is returned .
9,523
def get_atom_name ( self , atom ) : r = request . GetAtomName ( display = self . display , atom = atom ) return r . name
Look up the name of atom returning it as a string . Will raise BadAtom if atom does not exist .
9,524
def allow_events ( self , mode , time , onerror = None ) : request . AllowEvents ( display = self . display , onerror = onerror , mode = mode , time = time )
Release some queued events . mode should be one of X . AsyncPointer X . SyncPointer X . AsyncKeyboard X . SyncKeyboard X . ReplayPointer X . ReplayKeyboard X . AsyncBoth or X . SyncBoth . time should be a timestamp or X . CurrentTime .
9,525
def grab_server ( self , onerror = None ) : request . GrabServer ( display = self . display , onerror = onerror )
Disable processing of requests on all other client connections until the server is ungrabbed . Server grabbing should be avoided as much as possible .
9,526
def ungrab_server ( self , onerror = None ) : request . UngrabServer ( display = self . display , onerror = onerror )
Release the server if it was previously grabbed by this client .
9,527
def query_keymap ( self ) : r = request . QueryKeymap ( display = self . display ) return r . map
Return a bit vector for the logical state of the keyboard where each bit set to 1 indicates that the corresponding key is currently pressed down . The vector is represented as a list of 32 integers . List item N contains the bits for keys 8N to 8N + 7 with the least significant bit in the byte representing key 8N .
9,528
def open_font ( self , name ) : fid = self . display . allocate_resource_id ( ) ec = error . CatchError ( error . BadName ) request . OpenFont ( display = self . display , onerror = ec , fid = fid , name = name ) self . sync ( ) if ec . get_error ( ) : self . display . free_resource_id ( fid ) return None else : cls = self . display . get_resource_class ( 'font' , fontable . Font ) return cls ( self . display , fid , owner = 1 )
Open the font identifed by the pattern name and return its font object . If name does not match any font None is returned .
9,529
def list_fonts ( self , pattern , max_names ) : r = request . ListFonts ( display = self . display , max_names = max_names , pattern = pattern ) return r . fonts
Return a list of font names matching pattern . No more than max_names will be returned .
9,530
def set_font_path ( self , path , onerror = None ) : request . SetFontPath ( display = self . display , onerror = onerror , path = path )
Set the font path to path which should be a list of strings . If path is empty the default font path of the server will be restored .
9,531
def get_font_path ( self ) : r = request . GetFontPath ( display = self . display ) return r . paths
Return the current font path as a list of strings .
9,532
def list_extensions ( self ) : r = request . ListExtensions ( display = self . display ) return r . names
Return a list of all the extensions provided by the server .
9,533
def get_keyboard_mapping ( self , first_keycode , count ) : r = request . GetKeyboardMapping ( display = self . display , first_keycode = first_keycode , count = count ) return r . keysyms
Return the current keyboard mapping as a list of tuples starting at first_keycount and no more than count .
9,534
def change_hosts ( self , mode , host_family , host , onerror = None ) : request . ChangeHosts ( display = self . display , onerror = onerror , mode = mode , host_family = host_family , host = host )
mode is either X . HostInsert or X . HostDelete . host_family is one of X . FamilyInternet X . FamilyDECnet or X . FamilyChaos .
9,535
def set_access_control ( self , mode , onerror = None ) : request . SetAccessControl ( display = self . display , onerror = onerror , mode = mode )
Enable use of access control lists at connection setup if mode is X . EnableAccess disable if it is X . DisableAccess .
9,536
def set_close_down_mode ( self , mode , onerror = None ) : request . SetCloseDownMode ( display = self . display , onerror = onerror , mode = mode )
Control what will happen with the client s resources at connection close . The default is X . DestroyAll the other values are X . RetainPermanent and X . RetainTemporary .
9,537
def force_screen_saver ( self , mode , onerror = None ) : request . ForceScreenSaver ( display = self . display , onerror = onerror , mode = mode )
If mode is X . ScreenSaverActive the screen saver is activated . If it is X . ScreenSaverReset the screen saver is deactivated as if device input had been received .
9,538
def get_pointer_mapping ( self ) : r = request . GetPointerMapping ( display = self . display ) return r . map
Return a list of the pointer button mappings . Entry N in the list sets the logical button number for the physical button N + 1 .
9,539
def set_modifier_mapping ( self , keycodes ) : r = request . SetModifierMapping ( display = self . display , keycodes = keycodes ) return r . status
Set the keycodes for the eight modifiers X . Shift X . Lock X . Control X . Mod1 X . Mod2 X . Mod3 X . Mod4 and X . Mod5 . keycodes should be a eight - element list where each entry is a list of the keycodes that should be bound to that modifier .
9,540
def get_modifier_mapping ( self ) : r = request . GetModifierMapping ( display = self . display ) return r . keycodes
Return a list of eight lists one for each modifier . The list can be indexed using X . ShiftMapIndex X . Mod1MapIndex and so on . The sublists list the keycodes bound to that modifier .
9,541
def no_operation ( self , onerror = None ) : request . NoOperation ( display = self . display , onerror = onerror )
Do nothing but send a request to the server .
9,542
def parse_connection_setup ( self ) : r = self . sent_requests [ 0 ] while 1 : if r . _data : alen = r . _data [ 'additional_length' ] * 4 if len ( self . data_recv ) < alen : return 0 if r . _data [ 'status' ] != 1 : r . _data [ 'reason' ] = self . data_recv [ : r . _data [ 'reason_length' ] ] else : x , d = r . _success_reply . parse_binary ( self . data_recv [ : alen ] , self , rawdict = 1 ) r . _data . update ( x ) del self . sent_requests [ 0 ] self . data_recv = self . data_recv [ alen : ] return 1 else : if len ( self . data_recv ) < 8 : return 0 r . _data , d = r . _reply . parse_binary ( self . data_recv [ : 8 ] , self , rawdict = 1 ) self . data_recv = self . data_recv [ 8 : ]
Internal function used to parse connection setup response .
9,543
def redirect_subwindows ( self , update , onerror = None ) : RedirectSubwindows ( display = self . display , onerror = onerror , opcode = self . display . get_extension_major ( extname ) , window = self , update = update , )
Redirect the hierarchies starting at all current and future children to this window to off - screen storage .
9,544
def unredirect_window ( self , update , onerror = None ) : UnredirectWindow ( display = self . display , onerror = onerror , opcode = self . display . get_extension_major ( extname ) , window = self , update = update , )
Stop redirecting this window hierarchy .
9,545
def unredirect_subwindows ( self , update , onerror = None ) : RedirectWindow ( display = self . display , onerror = onerror , opcode = self . display . get_extension_major ( extname ) , window = self , update = update , )
Stop redirecting the hierarchies of children to this window .
9,546
def create_region_from_border_clip ( self , onerror = None ) : rid = self . display . allocate_resource_id ( ) CreateRegionFromBorderClip ( display = self . display , onerror = onerror , opcode = self . display . get_extension_major ( extname ) , region = rid , window = self , ) return rid
Create a region of the border clip of the window i . e . the area that is not clipped by the parent and any sibling windows .
9,547
def name_window_pixmap ( self , onerror = None ) : pid = self . display . allocate_resource_id ( ) NameWindowPixmap ( display = self . display , onerror = onerror , opcode = self . display . get_extension_major ( extname ) , window = self , pixmap = pid , ) cls = self . display . get_resource_class ( 'pixmap' , drawable . Pixmap ) return cls ( self . display , pid , owner = 1 )
Create a new pixmap that refers to the off - screen storage of the window including its border .
9,548
def get_overlay_window ( self ) : return GetOverlayWindow ( display = self . display , opcode = self . display . get_extension_major ( extname ) , window = self )
Return the overlay window of the root window .
9,549
def pack_value ( self , val ) : if isinstance ( val , bytes ) : val = list ( iterbytes ( val ) ) slen = len ( val ) if self . pad : pad = b'\0\0' * ( slen % 2 ) else : pad = b'' return struct . pack ( '>' + 'H' * slen , * val ) + pad , slen , None
Convert 8 - byte string into 16 - byte list
9,550
def pack_value ( self , value ) : if type ( value ) is tuple : return self . to_binary ( * value ) elif isinstance ( value , dict ) : return self . to_binary ( ** value ) elif isinstance ( value , DictWrapper ) : return self . to_binary ( ** value . _data ) else : raise BadDataError ( '%s is not a tuple or a list' % ( value ) )
This function allows Struct objects to be used in List and Object fields . Each item represents the arguments to pass to to_binary either a tuple a dictionary or a DictWrapper .
9,551
def parse_value ( self , val , display , rawdict = 0 ) : ret = { } vno = 0 for f in self . static_fields : if not f . name : pass elif isinstance ( f , LengthField ) : pass elif isinstance ( f , FormatField ) : pass else : if f . structvalues == 1 : field_val = val [ vno ] else : field_val = val [ vno : vno + f . structvalues ] if f . parse_value is not None : field_val = f . parse_value ( field_val , display , rawdict = rawdict ) ret [ f . name ] = field_val vno = vno + f . structvalues if not rawdict : return DictWrapper ( ret ) return ret
This function is used by List and Object fields to convert Struct objects with no var_fields into Python values .
9,552
def get_best_auth ( self , family , address , dispno , types = ( b"MIT-MAGIC-COOKIE-1" , ) ) : num = str ( dispno ) . encode ( ) matches = { } for efam , eaddr , enum , ename , edata in self . entries : if efam == family and eaddr == address and num == enum : matches [ ename ] = edata for t in types : try : return ( t , matches [ t ] ) except KeyError : pass raise error . XNoAuthError ( ( family , address , dispno ) )
Find an authentication entry matching FAMILY ADDRESS and DISPNO .
9,553
def run_example ( path ) : cmd = "{0} {1}" . format ( sys . executable , path ) proc = subprocess . Popen ( cmd , shell = True , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) res = proc . communicate ( ) if proc . returncode : print ( res [ 1 ] . decode ( ) ) return proc . returncode
Returns returncode of example
9,554
def load_keysym_group ( group ) : if '.' in group : raise ValueError ( 'invalid keysym group name: %s' % group ) G = globals ( ) mod = __import__ ( 'Xlib.keysymdef.%s' % group , G , locals ( ) , [ group ] ) keysyms = [ n for n in dir ( mod ) if n . startswith ( 'XK_' ) ] for keysym in keysyms : G [ keysym ] = mod . __dict__ [ keysym ] del mod
Load all the keysyms in group .
9,555
def _1_0set_screen_config ( self , size_id , rotation , config_timestamp , timestamp = X . CurrentTime ) : return _1_0SetScreenConfig ( display = self . display , opcode = self . display . get_extension_major ( extname ) , drawable = self , timestamp = timestamp , config_timestamp = config_timestamp , size_id = size_id , rotation = rotation , )
Sets the screen to the specified size and rotation .
9,556
def set_screen_config ( self , size_id , rotation , config_timestamp , rate = 0 , timestamp = X . CurrentTime ) : return SetScreenConfig ( display = self . display , opcode = self . display . get_extension_major ( extname ) , drawable = self , timestamp = timestamp , config_timestamp = config_timestamp , size_id = size_id , rotation = rotation , rate = rate , )
Sets the screen to the specified size rate rotation and reflection .
9,557
def get_screen_info ( self ) : return GetScreenInfo ( display = self . display , opcode = self . display . get_extension_major ( extname ) , window = self , )
Retrieve information about the current and available configurations for the screen associated with this window .
9,558
def get_screen_size_range ( self ) : return GetScreenSizeRange ( display = self . display , opcode = self . display . get_extension_major ( extname ) , window = self , )
Retrieve the range of possible screen sizes . The screen may be set to any size within this range .
9,559
def get_screen_size ( self , screen_no ) : return GetScreenSize ( display = self . display , opcode = self . display . get_extension_major ( extname ) , window = self . id , screen = screen_no , )
Returns the size of the given screen number
9,560
def get_query_cache_key ( compiler ) : sql , params = compiler . as_sql ( ) check_parameter_types ( params ) cache_key = '%s:%s:%s' % ( compiler . using , sql , [ text_type ( p ) for p in params ] ) return sha1 ( cache_key . encode ( 'utf-8' ) ) . hexdigest ( )
Generates a cache key from a SQLCompiler .
9,561
def get_table_cache_key ( db_alias , table ) : cache_key = '%s:%s' % ( db_alias , table ) return sha1 ( cache_key . encode ( 'utf-8' ) ) . hexdigest ( )
Generates a cache key from a SQL table .
9,562
def translate ( self , instr ) : try : translator = self . _instr_translators [ instr . mnemonic ] return translator ( * instr . operands ) except Exception : logger . error ( "Failed to translate instruction: %s" , instr , exc_info = True ) raise
Return the SMT representation of a REIL instruction .
9,563
def get_name_init ( self , name ) : self . _register_name ( name ) return self . _var_name_mappers [ name ] . get_init ( )
Get initial name of symbol .
9,564
def get_name_curr ( self , name ) : self . _register_name ( name ) return self . _var_name_mappers [ name ] . get_current ( )
Get current name of symbol .
9,565
def reset ( self ) : self . _solver . reset ( ) self . _mem_instance = 0 self . _mem_init = smtsymbol . BitVecArray ( self . _address_size , 8 , "MEM_{}" . format ( self . _mem_instance ) ) self . _mem_curr = self . make_array ( self . _address_size , "MEM_{}" . format ( self . _mem_instance ) ) self . _var_name_mappers = { }
Reset internal state .
9,566
def _register_name ( self , name ) : if name not in self . _var_name_mappers : self . _var_name_mappers [ name ] = VariableNamer ( name )
Get register name .
9,567
def _get_var_name ( self , name , fresh = False ) : if name not in self . _var_name_mappers : self . _var_name_mappers [ name ] = VariableNamer ( name ) if fresh : var_name = self . _var_name_mappers [ name ] . get_next ( ) else : var_name = self . _var_name_mappers [ name ] . get_current ( ) return var_name
Get variable name .
9,568
def _translate_src_oprnd ( self , operand ) : if isinstance ( operand , ReilRegisterOperand ) : return self . _translate_src_register_oprnd ( operand ) elif isinstance ( operand , ReilImmediateOperand ) : return smtsymbol . Constant ( operand . size , operand . immediate ) else : raise Exception ( "Invalid operand type" )
Translate source operand to a SMT expression .
9,569
def _translate_dst_oprnd ( self , operand ) : if isinstance ( operand , ReilRegisterOperand ) : return self . _translate_dst_register_oprnd ( operand ) else : raise Exception ( "Invalid operand type" )
Translate destination operand to a SMT expression .
9,570
def _translate_src_register_oprnd ( self , operand ) : reg_info = self . _arch_alias_mapper . get ( operand . name , None ) if reg_info : var_base_name , offset = reg_info var_size = self . _arch_regs_size [ var_base_name ] else : var_base_name = operand . name var_size = operand . size var_name = self . _get_var_name ( var_base_name ) ret_val = self . make_bitvec ( var_size , var_name ) if reg_info : ret_val = smtfunction . extract ( ret_val , offset , operand . size ) return ret_val
Translate source register operand to SMT expr .
9,571
def _translate_dst_register_oprnd ( self , operand ) : reg_info = self . _arch_alias_mapper . get ( operand . name , None ) parent_reg_constrs = [ ] if reg_info : var_base_name , offset = reg_info var_name_old = self . _get_var_name ( var_base_name , fresh = False ) var_name_new = self . _get_var_name ( var_base_name , fresh = True ) var_size = self . _arch_regs_size [ var_base_name ] ret_val_old = self . make_bitvec ( var_size , var_name_old ) ret_val_new = self . make_bitvec ( var_size , var_name_new ) ret_val = smtfunction . extract ( ret_val_new , offset , operand . size ) if 0 < offset < var_size - 1 : lower_expr_1 = smtfunction . extract ( ret_val_new , 0 , offset ) lower_expr_2 = smtfunction . extract ( ret_val_old , 0 , offset ) parent_reg_constrs += [ lower_expr_1 == lower_expr_2 ] upper_expr_1 = smtfunction . extract ( ret_val_new , offset + operand . size , var_size - offset - operand . size ) upper_expr_2 = smtfunction . extract ( ret_val_old , offset + operand . size , var_size - offset - operand . size ) parent_reg_constrs += [ upper_expr_1 == upper_expr_2 ] elif offset == 0 : upper_expr_1 = smtfunction . extract ( ret_val_new , offset + operand . size , var_size - offset - operand . size ) upper_expr_2 = smtfunction . extract ( ret_val_old , offset + operand . size , var_size - offset - operand . size ) parent_reg_constrs += [ upper_expr_1 == upper_expr_2 ] elif offset == var_size - 1 : lower_expr_1 = smtfunction . extract ( ret_val_new , 0 , offset ) lower_expr_2 = smtfunction . extract ( ret_val_old , 0 , offset ) parent_reg_constrs += [ lower_expr_1 == lower_expr_2 ] else : var_name_new = self . _get_var_name ( operand . name , fresh = True ) ret_val = self . make_bitvec ( operand . size , var_name_new ) return ret_val , parent_reg_constrs
Translate destination register operand to SMT expr .
9,572
def _translate_add ( self , oprnd1 , oprnd2 , oprnd3 ) : assert oprnd1 . size and oprnd2 . size and oprnd3 . size assert oprnd1 . size == oprnd2 . size op1_var = self . _translate_src_oprnd ( oprnd1 ) op2_var = self . _translate_src_oprnd ( oprnd2 ) op3_var , op3_var_constrs = self . _translate_dst_oprnd ( oprnd3 ) if oprnd3 . size > oprnd1 . size : result = smtfunction . zero_extend ( op1_var , oprnd3 . size ) + smtfunction . zero_extend ( op2_var , oprnd3 . size ) elif oprnd3 . size < oprnd1 . size : result = smtfunction . extract ( op1_var + op2_var , 0 , oprnd3 . size ) else : result = op1_var + op2_var return [ op3_var == result ] + op3_var_constrs
Return a formula representation of an ADD instruction .
9,573
def _translate_bsh ( self , oprnd1 , oprnd2 , oprnd3 ) : assert oprnd1 . size and oprnd2 . size and oprnd3 . size assert oprnd1 . size == oprnd2 . size op1_var = self . _translate_src_oprnd ( oprnd1 ) op2_var = self . _translate_src_oprnd ( oprnd2 ) op3_var , op3_var_constrs = self . _translate_dst_oprnd ( oprnd3 ) if oprnd3 . size > oprnd1 . size : op1_var_zx = smtfunction . zero_extend ( op1_var , oprnd3 . size ) op2_var_zx = smtfunction . zero_extend ( op2_var , oprnd3 . size ) op2_var_neg_sx = smtfunction . sign_extend ( - op2_var , oprnd3 . size ) shr = smtfunction . extract ( op1_var_zx >> op2_var_neg_sx , 0 , op3_var . size ) shl = smtfunction . extract ( op1_var_zx << op2_var_zx , 0 , op3_var . size ) elif oprnd3 . size < oprnd1 . size : shr = smtfunction . extract ( op1_var >> - op2_var , 0 , op3_var . size ) shl = smtfunction . extract ( op1_var << op2_var , 0 , op3_var . size ) else : shr = op1_var >> - op2_var shl = op1_var << op2_var result = smtfunction . ite ( oprnd3 . size , op2_var >= 0 , shl , shr ) return [ op3_var == result ] + op3_var_constrs
Return a formula representation of a BSH instruction .
9,574
def _translate_ldm ( self , oprnd1 , oprnd2 , oprnd3 ) : assert oprnd1 . size and oprnd3 . size assert oprnd1 . size == self . _address_size op1_var = self . _translate_src_oprnd ( oprnd1 ) op3_var , op3_var_constrs = self . _translate_dst_oprnd ( oprnd3 ) exprs = [ ] for i in reversed ( range ( 0 , oprnd3 . size , 8 ) ) : exprs += [ self . _mem_curr [ op1_var + i // 8 ] == smtfunction . extract ( op3_var , i , 8 ) ] return exprs + op3_var_constrs
Return a formula representation of a LDM instruction .
9,575
def _translate_stm ( self , oprnd1 , oprnd2 , oprnd3 ) : assert oprnd1 . size and oprnd3 . size assert oprnd3 . size == self . _address_size op1_var = self . _translate_src_oprnd ( oprnd1 ) op3_var = self . _translate_src_oprnd ( oprnd3 ) for i in range ( 0 , oprnd1 . size , 8 ) : self . _mem_curr [ op3_var + i // 8 ] = smtfunction . extract ( op1_var , i , 8 ) self . _mem_instance += 1 mem_old = self . _mem_curr mem_new = self . make_array ( self . _address_size , "MEM_{}" . format ( self . _mem_instance ) ) self . _mem_curr = mem_new return [ mem_new == mem_old ]
Return a formula representation of a STM instruction .
9,576
def _translate_str ( self , oprnd1 , oprnd2 , oprnd3 ) : assert oprnd1 . size and oprnd3 . size op1_var = self . _translate_src_oprnd ( oprnd1 ) op3_var , op3_var_constrs = self . _translate_dst_oprnd ( oprnd3 ) if oprnd3 . size > oprnd1 . size : result = smtfunction . zero_extend ( op1_var , op3_var . size ) elif oprnd3 . size < oprnd1 . size : result = smtfunction . extract ( op1_var , 0 , op3_var . size ) else : result = op1_var return [ op3_var == result ] + op3_var_constrs
Return a formula representation of a STR instruction .
9,577
def _translate_bisz ( self , oprnd1 , oprnd2 , oprnd3 ) : assert oprnd1 . size and oprnd3 . size op1_var = self . _translate_src_oprnd ( oprnd1 ) op3_var , op3_var_constrs = self . _translate_dst_oprnd ( oprnd3 ) result = smtfunction . ite ( oprnd3 . size , op1_var == 0x0 , smtsymbol . Constant ( oprnd3 . size , 0x1 ) , smtsymbol . Constant ( oprnd3 . size , 0x0 ) ) return [ op3_var == result ] + op3_var_constrs
Return a formula representation of a BISZ instruction .
9,578
def _translate_jcc ( self , oprnd1 , oprnd2 , oprnd3 ) : assert oprnd1 . size and oprnd3 . size op1_var = self . _translate_src_oprnd ( oprnd1 ) return [ op1_var != 0x0 ]
Return a formula representation of a JCC instruction .
9,579
def _translate_sext ( self , oprnd1 , oprnd2 , oprnd3 ) : assert oprnd1 . size and oprnd3 . size op1_var = self . _translate_src_oprnd ( oprnd1 ) op3_var , op3_var_constrs = self . _translate_dst_oprnd ( oprnd3 ) if oprnd3 . size > oprnd1 . size : result = smtfunction . sign_extend ( op1_var , op3_var . size ) elif oprnd3 . size < oprnd1 . size : raise Exception ( "Operands size mismatch." ) else : result = op1_var return [ op3_var == result ] + op3_var_constrs
Return a formula representation of a SEXT instruction .
9,580
def verify ( self , gadget ) : self . analyzer . reset ( ) for reil_instr in gadget . ir_instrs : self . analyzer . add_instruction ( reil_instr ) constrs = self . _constraints_generators [ gadget . type ] ( gadget ) if not constrs : return False for constr in constrs : self . analyzer . add_constraint ( constr ) return self . analyzer . check ( ) == 'unsat'
Verify gadgets .
9,581
def _get_constrs_no_operation ( self , gadget ) : mem_constrs = [ self . analyzer . get_memory_curr ( "pre" ) . __neq__ ( self . analyzer . get_memory_curr ( "post" ) ) ] flags_constrs = [ ] for name in self . _arch_info . registers_flags : var_initial = self . analyzer . get_register_expr ( name , mode = "pre" ) var_final = self . analyzer . get_register_expr ( name , mode = "post" ) flags_constrs += [ var_initial != var_final ] reg_constrs = [ ] for name in self . _arch_info . registers_gp_base : var_initial = self . analyzer . get_register_expr ( name , mode = "pre" ) var_final = self . analyzer . get_register_expr ( name , mode = "post" ) reg_constrs += [ var_initial != var_final ] constrs = mem_constrs + flags_constrs + reg_constrs constrs = [ reduce ( lambda c , acc : acc | c , constrs [ 1 : ] , constrs [ 0 ] ) ] return constrs
Verify NoOperation gadgets .
9,582
def infer_operands_size ( operands ) : size = None for oprnd in operands : if oprnd . size : size = oprnd . size break if size : for oprnd in operands : if not oprnd . size : oprnd . size = size else : for oprnd in operands : if isinstance ( oprnd , X86ImmediateOperand ) and not oprnd . size : oprnd . size = arch_info . architecture_size
Infer x86 instruction operand size based on other operands .
9,583
def parse_operand ( string , location , tokens ) : mod = " " . join ( tokens . get ( "modifier" , "" ) ) if "immediate" in tokens : imm = parse_immediate ( "" . join ( tokens [ "immediate" ] ) ) size = modifier_size . get ( mod , None ) oprnd = X86ImmediateOperand ( imm , size ) if "register" in tokens : name = tokens [ "register" ] size = arch_info . registers_size [ tokens [ "register" ] ] oprnd = X86RegisterOperand ( name , size ) if "memory" in tokens : seg_reg = tokens . get ( "segment" , None ) base_reg = tokens . get ( "base" , None ) index_reg = tokens . get ( "index" , None ) scale_imm = int ( tokens . get ( "scale" , "0x1" ) , 16 ) displ_imm = int ( "" . join ( tokens . get ( "displacement" , "0x0" ) ) , 16 ) oprnd = X86MemoryOperand ( seg_reg , base_reg , index_reg , scale_imm , displ_imm ) oprnd . modifier = mod if not oprnd . size and oprnd . modifier : oprnd . size = modifier_size [ oprnd . modifier ] return oprnd
Parse an x86 instruction operand .
9,584
def execute_lite ( self , instructions , context = None ) : if context : self . __cpu . registers = dict ( context ) for instr in instructions : self . __execute_one ( instr ) return dict ( self . __cpu . registers ) , self . __mem
Execute a list of instructions . It does not support loops .
9,585
def reset ( self ) : self . __mem . reset ( ) self . __cpu . reset ( ) self . __tainter . reset ( ) self . __instr_handler_pre = None , None self . __instr_handler_post = None , None self . __set_default_handlers ( )
Reset emulator . All registers and memory are reset .
9,586
def __execute_bsh ( self , instr ) : op0_val = self . read_operand ( instr . operands [ 0 ] ) op1_val = self . read_operand ( instr . operands [ 1 ] ) op1_size = instr . operands [ 1 ] . size if extract_sign_bit ( op1_val , op1_size ) == 0 : op2_val = op0_val << op1_val else : op2_val = op0_val >> twos_complement ( op1_val , op1_size ) self . write_operand ( instr . operands [ 2 ] , op2_val ) return None
Execute BSH instruction .
9,587
def __execute_ldm ( self , instr ) : assert instr . operands [ 0 ] . size == self . __mem . address_size assert instr . operands [ 2 ] . size in [ 8 , 16 , 32 , 64 , 128 , 256 ] op0_val = self . read_operand ( instr . operands [ 0 ] ) op2_val = self . read_memory ( op0_val , instr . operands [ 2 ] . size // 8 ) self . write_operand ( instr . operands [ 2 ] , op2_val ) return None
Execute LDM instruction .
9,588
def __execute_stm ( self , instr ) : assert instr . operands [ 0 ] . size in [ 8 , 16 , 32 , 64 , 128 , 256 ] assert instr . operands [ 2 ] . size == self . __mem . address_size op0_val = self . read_operand ( instr . operands [ 0 ] ) op2_val = self . read_operand ( instr . operands [ 2 ] ) op0_size = instr . operands [ 0 ] . size self . write_memory ( op2_val , op0_size // 8 , op0_val ) return None
Execute STM instruction .
9,589
def __execute_str ( self , instr ) : op0_val = self . read_operand ( instr . operands [ 0 ] ) self . write_operand ( instr . operands [ 2 ] , op0_val ) return None
Execute STR instruction .
9,590
def __execute_bisz ( self , instr ) : op0_val = self . read_operand ( instr . operands [ 0 ] ) op2_val = 1 if op0_val == 0 else 0 self . write_operand ( instr . operands [ 2 ] , op2_val ) return None
Execute BISZ instruction .
9,591
def __execute_jcc ( self , instr ) : op0_val = self . read_operand ( instr . operands [ 0 ] ) op2_val = self . read_operand ( instr . operands [ 2 ] ) return op2_val if op0_val != 0 else None
Execute JCC instruction .
9,592
def __execute_undef ( self , instr ) : op2_val = random . randint ( 0 , instr . operands [ 2 ] . size ) self . write_operand ( instr . operands [ 2 ] , op2_val ) return None
Execute UNDEF instruction .
9,593
def __execute_sext ( self , instr ) : op0_size = instr . operands [ 0 ] . size op2_size = instr . operands [ 2 ] . size op0_val = self . read_operand ( instr . operands [ 0 ] ) op0_msb = extract_sign_bit ( op0_val , op0_size ) op2_mask = ( 2 ** op2_size - 1 ) & ~ ( 2 ** op0_size - 1 ) if op0_msb == 1 else 0x0 op2_val = op0_val | op2_mask self . write_operand ( instr . operands [ 2 ] , op2_val ) return None
Execute SEXT instruction .
9,594
def get_init ( self ) : suffix = self . _separator + "%s" % str ( self . _counter_init ) return self . _base_name + suffix
Return initial name .
9,595
def get_current ( self ) : suffix = self . _separator + "%s" % str ( self . _counter_curr ) return self . _base_name + suffix
Return current name .
9,596
def get_next ( self ) : self . _counter_curr += 1 suffix = self . _separator + "%s" % str ( self . _counter_curr ) return self . _base_name + suffix
Return next name .
9,597
def check_path_satisfiability ( code_analyzer , path , start_address ) : start_instr_found = False sat = False for bb_curr , bb_next in zip ( path [ : - 1 ] , path [ 1 : ] ) : logger . info ( "BB @ {:#x}" . format ( bb_curr . address ) ) for instr in bb_curr : if not start_instr_found : if instr . address == start_address : start_instr_found = True else : continue logger . info ( "{:#x} {}" . format ( instr . address , instr ) ) for reil_instr in instr . ir_instrs : logger . info ( "{:#x} {:02d} {}" . format ( reil_instr . address >> 0x8 , reil_instr . address & 0xff , reil_instr ) ) if reil_instr . mnemonic == ReilMnemonic . JCC : if instr . address + instr . size - 1 != bb_curr . end_address : logger . error ( "Unexpected JCC instruction: {:#x} {} ({})" . format ( instr . address , instr , reil_instr ) ) continue assert ( bb_curr . taken_branch == bb_next . address or bb_curr . not_taken_branch == bb_next . address or bb_curr . direct_branch == bb_next . address ) if bb_curr . taken_branch == bb_next . address : branch_var_goal = 0x1 elif bb_curr . not_taken_branch == bb_next . address : branch_var_goal = 0x0 else : continue code_analyzer . add_constraint ( code_analyzer . get_operand_expr ( reil_instr . operands [ 0 ] ) == branch_var_goal ) break code_analyzer . add_instruction ( reil_instr ) sat = code_analyzer . check ( ) == 'sat' logger . info ( "BB @ {:#x} sat? {}" . format ( bb_curr . address , sat ) ) if not sat : break return sat
Check satisfiability of a basic block path .
9,598
def to_string ( mnemonic ) : strings = { ReilMnemonic . ADD : "add" , ReilMnemonic . SUB : "sub" , ReilMnemonic . MUL : "mul" , ReilMnemonic . DIV : "div" , ReilMnemonic . MOD : "mod" , ReilMnemonic . BSH : "bsh" , ReilMnemonic . AND : "and" , ReilMnemonic . OR : "or" , ReilMnemonic . XOR : "xor" , ReilMnemonic . LDM : "ldm" , ReilMnemonic . STM : "stm" , ReilMnemonic . STR : "str" , ReilMnemonic . BISZ : "bisz" , ReilMnemonic . JCC : "jcc" , ReilMnemonic . UNKN : "unkn" , ReilMnemonic . UNDEF : "undef" , ReilMnemonic . NOP : "nop" , ReilMnemonic . SEXT : "sext" , ReilMnemonic . SDIV : "sdiv" , ReilMnemonic . SMOD : "smod" , ReilMnemonic . SMUL : "smul" , } return strings [ mnemonic ]
Return the string representation of the given mnemonic .
9,599
def from_string ( string ) : mnemonics = { "add" : ReilMnemonic . ADD , "sub" : ReilMnemonic . SUB , "mul" : ReilMnemonic . MUL , "div" : ReilMnemonic . DIV , "mod" : ReilMnemonic . MOD , "bsh" : ReilMnemonic . BSH , "and" : ReilMnemonic . AND , "or" : ReilMnemonic . OR , "xor" : ReilMnemonic . XOR , "ldm" : ReilMnemonic . LDM , "stm" : ReilMnemonic . STM , "str" : ReilMnemonic . STR , "bisz" : ReilMnemonic . BISZ , "jcc" : ReilMnemonic . JCC , "unkn" : ReilMnemonic . UNKN , "undef" : ReilMnemonic . UNDEF , "nop" : ReilMnemonic . NOP , "sext" : ReilMnemonic . SEXT , "sdiv" : ReilMnemonic . SDIV , "smod" : ReilMnemonic . SMOD , "smul" : ReilMnemonic . SMUL , } return mnemonics [ string ]
Return the mnemonic represented by the given string .