signature:
def abstract_relational_comparison ( self , other , self_first = True ) : # todo speed up !
    '''self < other if self _ first else other < self .
 Returns the result of the question : is self smaller than other ?
 in case self _ first is false it returns the answer of :
 is other smaller than self .
 result is PyJs type : bool or undefined'''

implementation:
px = to_primitive ( self , 'Number' )
py = to_primitive ( other , 'Number' )
if not self_first : # reverse order
    px , py = py , px
if not ( Type ( px ) == 'String' and Type ( py ) == 'String' ) :
    px , py = to_number ( px ) , to_number ( py )
    if is_nan ( px ) or is_nan ( py ) :
        return None
        # watch out here !
    return px < py
    # same cmp algorithm
else : # I am pretty sure that python has the same
# string cmp algorithm but I have to confirm it
    return px < py


signature:
def abstract_equality_op ( self , other ) :
    '''returns the result of JS = = compare .
 result is PyJs type : bool'''

implementation:
tx , ty = Type ( self ) , Type ( other )
if tx == ty :
    if tx == 'Undefined' or tx == 'Null' :
        return True
    if tx == 'Number' or tx == 'String' or tx == 'Boolean' :
        return self == other
    return self is other
    # Object
elif ( tx == 'Undefined' and ty == 'Null' ) or ( ty == 'Undefined' and tx == 'Null' ) :
    return True
elif tx == 'Number' and ty == 'String' :
    return abstract_equality_op ( self , to_number ( other ) )
elif tx == 'String' and ty == 'Number' :
    return abstract_equality_op ( to_number ( self ) , other )
elif tx == 'Boolean' :
    return abstract_equality_op ( to_number ( self ) , other )
elif ty == 'Boolean' :
    return abstract_equality_op ( self , to_number ( other ) )
elif ( tx == 'String' or tx == 'Number' ) and is_object ( other ) :
    return abstract_equality_op ( self , to_primitive ( other ) )
elif ( ty == 'String' or ty == 'Number' ) and is_object ( self ) :
    return abstract_equality_op ( to_primitive ( self ) , other )
else :
    return False


signature:
def in_op ( self , other ) :
    '''checks if self is in other'''

implementation:
if not is_object ( other ) :
    raise MakeError ( 'TypeError' , "You can\'t use 'in' operator to search in non-objects" )
return other . has_property ( to_string ( self ) )


signature:
def maybe_download_and_extract ( ) :
    """Download and extract processed data and embeddings ."""

implementation:
dest_directory = '.'
filename = DATA_URL . split ( '/' ) [ - 1 ]
filepath = os . path . join ( dest_directory , filename )
if not os . path . exists ( filepath ) :
    def _progress ( count , block_size , total_size ) :
        sys . stdout . write ( '\r>> Downloading %s %.1f%%' % ( filename , float ( count * block_size ) / float ( total_size ) * 100.0 ) )
        sys . stdout . flush ( )
    filepath , _ = urllib . request . urlretrieve ( DATA_URL , filepath , _progress )
    print ( )
    statinfo = os . stat ( filepath )
    print ( 'Successfully downloaded' , filename , statinfo . st_size , 'bytes.' )
extracted_dir_path = os . path . join ( dest_directory , 'trees' )
if not os . path . exists ( extracted_dir_path ) :
    zip_ref = zipfile . ZipFile ( filepath , 'r' )
    zip_ref . extractall ( dest_directory )
    zip_ref . close ( )


signature:
def make_network_graph ( compact , expression_names , lookup_names ) :
    """Make a network graph , represented as of nodes and a set of edges .
 The nodes are represented as tuples : ( name : string , input _ dim : Dim , label : string , output _ dim : Dim , children : set [ name ] , features : string )
 # The edges are represented as dict of children to sets of parents : ( child : string ) - > [ ( parent : string , features : string ) ]"""

implementation:
nodes = set ( )
# edges = defaultdict ( set ) # parent - > ( child , extra )
var_name_dict = dict ( )
if expression_names :
    for e in graphviz_items : # e : Expression
        if e in expression_names :
            var_name_dict [ e . vindex ] = expression_names [ e ]
rnn_bldr_name = defaultdict ( lambda : chr ( len ( rnn_bldr_name ) + ord ( 'A' ) ) )
def vidx2str ( vidx ) :
    return '%s%s' % ( 'N' , vidx )
for e in graphviz_items : # e : Expression
    vidx = e . vindex
    f_name = e . name
    args = e . args
    output_dim = e . dim
    input_dim = None
    # basically just RNNStates use this since everything else has input _ dim = = output _ dim
    children = set ( )
    node_type = '2_regular'
    if f_name == 'vecInput' :
        [ _dim ] = args
        arg_strs = [ ]
    elif f_name == 'inputVector' :
        [ _v ] = args
        arg_strs = [ ]
    elif f_name == 'matInput' :
        [ _d1 , _d2 ] = args
        arg_strs = [ ]
    elif f_name == 'inputMatrix' :
        [ _v , _d ] = args
        arg_strs = [ ]
    elif f_name == 'parameters' :
        [ _dim ] = args
        arg_strs = [ ]
        if compact :
            if vidx in var_name_dict :
                f_name = var_name_dict [ vidx ]
        node_type = '1_param'
    elif f_name == 'lookup_parameters' :
        [ _dim ] = args
        arg_strs = [ ]
        if compact :
            if vidx in var_name_dict :
                f_name = var_name_dict [ vidx ]
        node_type = '1_param'
    elif f_name == 'lookup' :
        [ p , idx , update ] = args
        [ _dim ] = p . args
        if vidx in var_name_dict :
            name = var_name_dict [ vidx ]
        else :
            name = None
        item_name = None
        if lookup_names and p in expression_names :
            param_name = expression_names [ p ]
            if param_name in lookup_names :
                item_name = '\\"%s\\"' % ( lookup_names [ param_name ] [ idx ] , )
        if compact :
            if item_name is not None :
                f_name = item_name
            elif name is not None :
                f_name = '%s[%s]' % ( name , idx )
            else :
                f_name = 'lookup(%s)' % ( idx )
            arg_strs = [ ]
        else :
            arg_strs = [ var_name_dict . get ( p . vindex , 'v%d' % ( p . vindex ) ) ]
            if item_name is not None :
                arg_strs . append ( item_name )
            vocab_size = _dim [ 0 ]
            arg_strs . extend ( [ '%s' % ( idx ) , '%s' % ( vocab_size ) , 'update' if update else 'fixed' ] )
        # children . add ( vidx2str ( p . vindex ) )
        # node _ type = ' 1 _ param '
    elif f_name == 'RNNState' :
        [ arg , input_dim , bldr_type , bldr_num , state_idx ] = args
        # arg = = input _ e
        rnn_name = rnn_bldr_name [ bldr_num ]
        if bldr_type . endswith ( 'Builder' ) :
            bldr_type [ : - len ( 'Builder' ) ]
        f_name = '%s-%s-%s' % ( bldr_type , rnn_name , state_idx )
        if not compact :
            i = arg . vindex
            s = var_name_dict . get ( i , 'v%d' % ( i ) )
            arg_strs = [ s ]
        else :
            arg_strs = [ ]
        children . add ( vidx2str ( arg . vindex ) )
        node_type = '3_rnn_state'
    else :
        arg_strs = [ ]
        for arg in args :
            if isinstance ( arg , Expression ) :
                if not compact :
                    i = arg . vindex
                    s = var_name_dict . get ( i , 'v%d' % ( i ) )
                    arg_strs . append ( s )
                children . add ( vidx2str ( arg . vindex ) )
            elif isinstance ( arg , float ) and compact :
                s = re . sub ( '0+$' , '' , '%.3f' % ( arg ) )
                if s == '0.' :
                    s = str ( arg )
                arg_strs . append ( s )
            else :
                arg_strs . append ( str ( arg ) )
    # f _ name = { ,
    # } . get ( f _ name , f _ name )
    if compact :
        f_name = { 'add' : '+' , 'sub' : '-' , 'mul' : '*' , 'div' : '/' , 'cadd' : '+' , 'cmul' : '*' , 'cdiv' : '/' , 'scalarsub' : '-' , 'concatenate' : 'cat' , 'esum' : 'sum' , 'emax' : 'max' , 'emin' : 'min' , } . get ( f_name , f_name )
        if arg_strs :
            str_repr = '%s(%s)' % ( f_name , ', ' . join ( arg_strs ) )
        else :
            str_repr = f_name
    elif f_name == 'add' :
        [ a , b ] = arg_strs
        str_repr = '%s + %s' % ( a , b )
    elif f_name == 'sub' :
        [ a , b ] = arg_strs
        str_repr = '%s - %s' % ( a , b )
    elif f_name == 'mul' :
        [ a , b ] = arg_strs
        str_repr = '%s * %s' % ( a , b )
    elif f_name == 'div' :
        [ a , b ] = arg_strs
        str_repr = '%s / %s' % ( a , b )
    elif f_name == 'neg' :
        [ a , ] = arg_strs
        str_repr = '-%s' % ( a )
    elif f_name == 'affine_transform' :
        str_repr = arg_strs [ 0 ]
        for i in xrange ( 1 , len ( arg_strs ) , 2 ) :
            str_repr += ' + %s*%s' % tuple ( arg_strs [ i : i + 2 ] )
    else :
        if arg_strs is not None :
            str_repr = '%s(%s)' % ( f_name , ', ' . join ( arg_strs ) )
        else :
            str_repr = f_name
    name = vidx2str ( vidx )
    var_name = '%s' % ( var_name_dict . get ( vidx , 'v%d' % ( vidx ) ) ) if not compact else ''
    # if show _ dims :
    # str _ repr = ' % s \ \ n % s ' % ( shape _ str ( e . dim ) , str _ repr )
    label = str_repr
    if not compact :
        label = '%s = %s' % ( var_name , label )
    features = ''
    # if output _ dim . invalid ( ) :
    # features + = " [ color = red , style = filled , fillcolor = red ] "
    # node _ def _ lines . append ( ' % s [ label = " % s % s " ] % s ; ' % ( vidx2str ( vidx ) , label _ prefix , str _ repr , ' ' ) )
    expr_name = expression_names [ e ] if compact and expression_names and ( e in expression_names ) and ( expression_names [ e ] != f_name ) else None
    nodes . add ( GVNode ( name , input_dim , label , output_dim , frozenset ( children ) , features , node_type , expr_name ) )
return nodes


signature:
def add_inputs ( self , es ) :
    """returns the list of state pairs ( stateF , stateB ) obtained by adding
 inputs to both forward ( stateF ) and backward ( stateB ) RNNs .
 @ param es : a list of Expression
 see also transduce ( xs )
 . transduce ( xs ) is different from . add _ inputs ( xs ) in the following way :
 . add _ inputs ( xs ) returns a list of RNNState pairs . RNNState objects can be
 queried in various ways . In particular , they allow access to the previous
 state , as well as to the state - vectors ( h ( ) and s ( ) )
 . transduce ( xs ) returns a list of Expression . These are just the output
 expressions . For many cases , this suffices .
 transduce is much more memory efficient than add _ inputs ."""

implementation:
for e in es :
    ensure_freshness ( e )
for ( fb , bb ) in self . builder_layers [ : - 1 ] :
    fs = fb . initial_state ( ) . transduce ( es )
    bs = bb . initial_state ( ) . transduce ( reversed ( es ) )
    es = [ concatenate ( [ f , b ] ) for f , b in zip ( fs , reversed ( bs ) ) ]
( fb , bb ) = self . builder_layers [ - 1 ]
fs = fb . initial_state ( ) . add_inputs ( es )
bs = bb . initial_state ( ) . add_inputs ( reversed ( es ) )
return [ ( f , b ) for f , b in zip ( fs , reversed ( bs ) ) ]


signature:
def transduce ( self , es ) :
    """returns the list of output Expressions obtained by adding the given inputs
 to the current state , one by one , to both the forward and backward RNNs ,
 and concatenating .
 @ param es : a list of Expression
 see also add _ inputs ( xs )
 . transduce ( xs ) is different from . add _ inputs ( xs ) in the following way :
 . add _ inputs ( xs ) returns a list of RNNState pairs . RNNState objects can be
 queried in various ways . In particular , they allow access to the previous
 state , as well as to the state - vectors ( h ( ) and s ( ) )
 . transduce ( xs ) returns a list of Expression . These are just the output
 expressions . For many cases , this suffices .
 transduce is much more memory efficient than add _ inputs ."""

implementation:
for e in es :
    ensure_freshness ( e )
for ( fb , bb ) in self . builder_layers :
    fs = fb . initial_state ( ) . transduce ( es )
    bs = bb . initial_state ( ) . transduce ( reversed ( es ) )
    es = [ concatenate ( [ f , b ] ) for f , b in zip ( fs , reversed ( bs ) ) ]
return es


signature:
def add_inputs ( self , xs ) :
    """returns the list of states obtained by adding the given inputs
 to the current state , one by one ."""

implementation:
states = [ ]
cur = self
for x in xs :
    cur = cur . add_input ( x )
    states . append ( cur )
return states


signature:
def load_mnist ( dataset , path ) :
    """wget - O - http : / / yann . lecun . com / exdb / mnist / train - images - idx3 - ubyte . gz | gunzip > train - images - idx3 - ubyte
 wget - O - http : / / yann . lecun . com / exdb / mnist / train - labels - idx1 - ubyte . gz | gunzip > train - labels - idx1 - ubyte
 wget - O - http : / / yann . lecun . com / exdb / mnist / t10k - images - idx3 - ubyte . gz | gunzip > t10k - images - idx3 - ubyte
 wget - O - http : / / yann . lecun . com / exdb / mnist / t10k - labels - idx1 - ubyte . gz | gunzip > t10k - labels - idx1 - ubyte"""

implementation:
if dataset is "training" :
    fname_img = os . path . join ( path , "train-images-idx3-ubyte" )
    fname_lbl = os . path . join ( path , "train-labels-idx1-ubyte" )
elif dataset is "testing" :
    fname_img = os . path . join ( path , "t10k-images-idx3-ubyte" )
    fname_lbl = os . path . join ( path , "t10k-labels-idx1-ubyte" )
else :
    raise ValueError ( "dataset must be 'testing' or 'training'" )
# Load everything in numpy arrays
with open ( fname_lbl , "rb" ) as flbl :
    magic , num = struct . unpack ( ">II" , flbl . read ( 8 ) )
    labels = np . fromfile ( flbl , dtype = np . int8 )
with open ( fname_img , "rb" ) as fimg :
    magic , num , rows , cols = struct . unpack ( ">IIII" , fimg . read ( 16 ) )
    images = np . multiply ( np . fromfile ( fimg , dtype = np . uint8 ) . reshape ( len ( labels ) , rows * cols ) , 1.0 / 255.0 )
get_instance = lambda idx : ( labels [ idx ] , images [ idx ] . reshape ( 1 , 28 , 28 ) )
# Create an iterator which returns each image in turn
# for i in range ( len ( labels ) ) :
# yield get _ instance ( i )
size_reset = lambda x : x . reshape ( 1 , 28 , 28 )
return list ( map ( size_reset , images ) )


signature:
def make_grid ( tensor , nrow = 8 , padding = 2 , pad_value = 0 ) :
    """Make a grid of images , via numpy .
 Args :
 tensor ( Tensor or list ) : 4D mini - batch Tensor of shape ( B x C x H x W )
 or a list of images all of the same size .
 nrow ( int , optional ) : Number of images displayed in each row of the grid .
 The Final grid size is ( B / nrow , nrow ) . Default is 8.
 padding ( int , optional ) : amount of padding . Default is 2.
 pad _ value ( float , optional ) : Value for the padded pixels ."""

implementation:
if not ( isinstance ( tensor , np . ndarray ) or ( isinstance ( tensor , list ) and all ( isinstance ( t , np . ndarray ) for t in tensor ) ) ) :
    raise TypeError ( 'tensor or list of tensors expected, got {}' . format ( type ( tensor ) ) )
# if list of tensors , convert to a 4D mini - batch Tensor
if isinstance ( tensor , list ) :
    tensor = np . stack ( tensor , 0 )
if tensor . ndim == 2 : # single image H x W
    tensor = tensor . reshape ( ( 1 , tensor . shape [ 0 ] , tensor . shape [ 1 ] ) )
if tensor . ndim == 3 :
    if tensor . shape [ 0 ] == 1 : # if single - channel , single image , convert to 3 - channel
        tensor = np . concatenate ( ( tensor , tensor , tensor ) , 0 )
    tensor = tensor . reshape ( ( 1 , tensor . shape [ 0 ] , tensor . shape [ 1 ] , tensor . shape [ 2 ] ) )
if tensor . ndim == 4 and tensor . shape [ 1 ] == 1 : # single - channel images
    tensor = np . concatenate ( ( tensor , tensor , tensor ) , 1 )
if tensor . shape [ 0 ] == 1 :
    return np . squeeze ( tensor )
# make the mini - batch of images into a grid
nmaps = tensor . shape [ 0 ]
xmaps = min ( nrow , nmaps )
ymaps = int ( math . ceil ( float ( nmaps ) / xmaps ) )
height , width = int ( tensor . shape [ 2 ] + padding ) , int ( tensor . shape [ 3 ] + padding )
grid = np . ones ( ( 3 , height * ymaps + padding , width * xmaps + padding ) ) * pad_value
k = 0
for y in range ( ymaps ) :
    for x in range ( xmaps ) :
        if k >= nmaps :
            break
        grid [ : , y * height + padding : ( y + 1 ) * height , x * width + padding : ( x + 1 ) * width ] = tensor [ k ]
        k = k + 1
return grid


signature:
def save_image ( tensor , filename , nrow = 8 , padding = 2 , pad_value = 0 ) :
    """Save a given Tensor into an image file .
 Args :
 tensor ( Tensor or list ) : Image to be saved . If given a mini - batch tensor ,
 saves the tensor as a grid of images by calling ` ` make _ grid ` ` .
 * * kwargs : Other arguments are documented in ` ` make _ grid ` ` ."""

implementation:
from PIL import Image
grid = make_grid ( tensor , nrow = nrow , padding = padding , pad_value = pad_value )
im = Image . fromarray ( pre_pillow_float_img_process ( grid ) )
im . save ( filename )


signature:
def pythonize_arguments ( arg_str ) :
    """Remove types from function arguments in cython"""

implementation:
out_args = [ ]
# If there aren ' t any arguments return the empty string
if arg_str is None :
    return out_str
args = arg_str . split ( ',' )
for arg in args :
    components = arg . split ( '=' )
    name_and_type = components [ 0 ] . split ( ' ' )
    # There is probably type info
    if name_and_type [ - 1 ] == '' and len ( name_and_type ) > 1 :
        name = name_and_type [ - 2 ]
    else :
        name = name_and_type [ - 1 ]
    # if there are default parameters
    if len ( components ) > 1 :
        name += '=' + components [ 1 ]
    out_args . append ( name )
return ',' . join ( out_args )


signature:
def correspond ( text ) :
    """Communicate with the child process without closing stdin ."""

implementation:
if text :
    subproc . stdin . write ( text )
subproc . stdin . flush ( )
return get_lines ( )


signature:
def _normalize ( c ) :
    """Convert a byte - like value into a canonical byte ( a value of type ' bytes ' of len 1)
 : param c :
 : return :"""

implementation:
if isinstance ( c , int ) :
    return bytes ( [ c ] )
elif isinstance ( c , str ) :
    return bytes ( [ ord ( c ) ] )
else :
    return c


signature:
def _set_perms ( self , perms ) :
    """Sets the access permissions of the map .
 : param perms : the new permissions ."""

implementation:
assert isinstance ( perms , str ) and len ( perms ) <= 3 and perms . strip ( ) in [ '' , 'r' , 'w' , 'x' , 'rw' , 'r x' , 'rx' , 'rwx' , 'wx' , ]
self . _perms = perms


signature:
def access_ok ( self , access ) :
    """Check if there is enough permissions for access"""

implementation:
for c in access :
    if c not in self . perms :
        return False
return True


signature:
def _in_range ( self , index ) :
    """Returns True if index is in range"""

implementation:
if isinstance ( index , slice ) :
    in_range = index . start < index . stop and index . start >= self . start and index . stop <= self . end
else :
    in_range = index >= self . start and index <= self . end
return in_range


signature:
def _get_offset ( self , index ) :
    """Translates the index to the internal offsets .
 self . start - > 0
 self . start + 1 - > 1
 self . end - > len ( self )"""

implementation:
if not self . _in_range ( index ) :
    raise IndexError ( 'Map index out of range' )
if isinstance ( index , slice ) :
    index = slice ( index . start - self . start , index . stop - self . start )
else :
    index -= self . start
return index


signature:
def _ceil ( self , address ) :
    """Returns the smallest page boundary value not less than the address .
 : rtype : int
 : param address : the address to calculate its ceil .
 : return : the ceil of C { address } ."""

implementation: return ( ( ( address - 1 ) + self . page_size ) & ~ self . page_mask ) & self . memory_mask


signature:
def _search ( self , size , start = None , counter = 0 ) :
    """Recursively searches the address space for enough free space to allocate C { size } bytes .
 : param size : the size in bytes to allocate .
 : param start : an address from where to start the search .
 : param counter : internal parameter to know if all the memory was already scanned .
 : return : the address of an available space to map C { size } bytes .
 : raises MemoryException : if there is no space available to allocate the desired memory .
 : rtype : int
 todo : Document what happens when you try to allocate something that goes round the address 32/64 bit representation ."""

implementation:
assert size & self . page_mask == 0
if start is None :
    end = { 32 : 0xf8000000 , 64 : 0x0000800000000000 } [ self . memory_bit_size ]
    start = end - size
else :
    if start > self . memory_size - size :
        start = self . memory_size - size
    end = start + size
consecutive_free = 0
for p in range ( self . _page ( end - 1 ) , - 1 , - 1 ) :
    if p not in self . _page2map :
        consecutive_free += 0x1000
    else :
        consecutive_free = 0
    if consecutive_free >= size :
        return p << self . page_bit_size
    counter += 1
    if counter >= self . memory_size // self . page_size :
        raise MemoryException ( 'Not enough memory' )
return self . _search ( size , self . memory_size - size , counter )


signature:
def mmapFile ( self , addr , size , perms , filename , offset = 0 ) :
    """Creates a new file mapping in the memory address space .
 : param addr : the starting address ( took as hint ) . If C { addr } is C { 0 } the first big enough
 chunk of memory will be selected as starting address .
 : param size : the contents of a file mapping are initialized using C { size } bytes starting
 at offset C { offset } in the file C { filename } .
 : param perms : the access permissions to this memory .
 : param filename : the pathname to the file to map .
 : param offset : the contents of a file mapping are initialized using C { size } bytes starting
 at offset C { offset } in the file C { filename } .
 : return : the starting address where the file was mapped .
 : rtype : int
 : raises error :
 - ' Address shall be concrete ' if C { addr } is not an integer number .
 - ' Address too big ' if C { addr } goes beyond the limit of the memory .
 - ' Map already used ' if the piece of memory starting in C { addr } and with length C { size } isn ' t free ."""

implementation:
# If addr is NULL , the system determines where to allocate the region .
assert addr is None or isinstance ( addr , int ) , 'Address shall be concrete'
assert size > 0
self . cpu . _publish ( 'will_map_memory' , addr , size , perms , filename , offset )
# address is rounded down to the nearest multiple of the allocation granularity
if addr is not None :
    assert addr < self . memory_size , 'Address too big'
    addr = self . _floor ( addr )
# size value is rounded up to the next page boundary
size = self . _ceil ( size )
# If zero search for a spot
addr = self . _search ( size , addr )
# It should not be allocated
for i in range ( self . _page ( addr ) , self . _page ( addr + size ) ) :
    assert i not in self . _page2map , 'Map already used'
# Create the map
m = FileMap ( addr , size , perms , filename , offset )
# Okay , ready to alloc
self . _add ( m )
logger . debug ( 'New file-memory map @%x size:%x' , addr , size )
self . cpu . _publish ( 'did_map_memory' , addr , size , perms , filename , offset , addr )
return addr


signature:
def mmap ( self , addr , size , perms , data_init = None , name = None ) :
    """Creates a new mapping in the memory address space .
 : param addr : the starting address ( took as hint ) . If C { addr } is C { 0 } the first big enough
 chunk of memory will be selected as starting address .
 : param size : the length of the mapping .
 : param perms : the access permissions to this memory .
 : param data _ init : optional data to initialize this memory .
 : param name : optional name to give to this mapping
 : return : the starting address where the memory was mapped .
 : raises error :
 - ' Address shall be concrete ' if C { addr } is not an integer number .
 - ' Address too big ' if C { addr } goes beyond the limit of the memory .
 - ' Map already used ' if the piece of memory starting in C { addr } and with length C { size } isn ' t free .
 : rtype : int"""

implementation:
# If addr is NULL , the system determines where to allocate the region .
assert addr is None or isinstance ( addr , int ) , 'Address shall be concrete'
self . cpu . _publish ( 'will_map_memory' , addr , size , perms , None , None )
# address is rounded down to the nearest multiple of the allocation granularity
if addr is not None :
    assert addr < self . memory_size , 'Address too big'
    addr = self . _floor ( addr )
# size value is rounded up to the next page boundary
size = self . _ceil ( size )
# If zero search for a spot
addr = self . _search ( size , addr )
# It should not be allocated
for i in range ( self . _page ( addr ) , self . _page ( addr + size ) ) :
    assert i not in self . _page2map , 'Map already used'
# Create the anonymous map
m = AnonMap ( start = addr , size = size , perms = perms , data_init = data_init , name = name )
# Okay , ready to alloc
self . _add ( m )
logger . debug ( 'New memory map @%x size:%x' , addr , size )
self . cpu . _publish ( 'did_map_memory' , addr , size , perms , None , None , addr )
return addr


signature:
def map_containing ( self , address ) :
    """Returns the L { MMap } object containing the address .
 : param address : the address to obtain its mapping .
 : rtype : L { MMap }
 @ todo : symbolic address"""

implementation:
page_offset = self . _page ( address )
if page_offset not in self . _page2map :
    raise MemoryException ( "Page not mapped" , address )
return self . _page2map [ page_offset ]


signature:
def mappings ( self ) :
    """Returns a sorted list of all the mappings for this memory .
 : return : a list of mappings .
 : rtype : list"""

implementation:
result = [ ]
for m in self . maps :
    if isinstance ( m , AnonMap ) :
        result . append ( ( m . start , m . end , m . perms , 0 , '' ) )
    elif isinstance ( m , FileMap ) :
        result . append ( ( m . start , m . end , m . perms , m . _offset , m . _filename ) )
    else :
        result . append ( ( m . start , m . end , m . perms , 0 , m . name ) )
return sorted ( result )


signature:
def _maps_in_range ( self , start , end ) :
    """Generates the list of maps that overlaps with the range [ start : end ]"""

implementation:
# Search for the first matching map
addr = start
while addr < end :
    if addr not in self :
        addr += self . page_size
    else :
        m = self . _page2map [ self . _page ( addr ) ]
        yield m
        addr = m . end


signature:
def munmap ( self , start , size ) :
    """Deletes the mappings for the specified address range and causes further
 references to addresses within the range to generate invalid memory
 references .
 : param start : the starting address to delete .
 : param size : the length of the unmapping ."""

implementation:
start = self . _floor ( start )
end = self . _ceil ( start + size )
self . cpu . _publish ( 'will_unmap_memory' , start , size )
for m in self . _maps_in_range ( start , end ) :
    self . _del ( m )
    head , tail = m . split ( start )
    middle , tail = tail . split ( end )
    assert middle is not None
    if head :
        self . _add ( head )
    if tail :
        self . _add ( tail )
self . cpu . _publish ( 'did_unmap_memory' , start , size )
logger . debug ( f'Unmap memory @{start:x} size:{size:x}' )


signature:
def pop_record_writes ( self ) :
    """Stop recording trace and return a ` list [ ( address , value ) ] ` of all the writes
 that occurred , where ` value ` is of type list [ str ] . Can be called without
 intermediate ` pop _ record _ writes ( ) ` .
 For example : :
 mem . push _ record _ writes ( )
 mem . write ( 1 , ' a ' )
 mem . push _ record _ writes ( )
 mem . write ( 2 , ' b ' )
 mem . pop _ record _ writes ( ) # Will return [ ( 2 , ' b ' ) ]
 mem . pop _ record _ writes ( ) # Will return [ ( 1 , ' a ' ) , ( 2 , ' b ' ) ]
 Multiple writes to the same address will all be included in the trace in the
 same order they occurred .
 : return : list [ tuple ]"""

implementation:
lst = self . _recording_stack . pop ( )
# Append the current list to a previously - started trace .
if self . _recording_stack :
    self . _recording_stack [ - 1 ] . extend ( lst )
return lst


implementation:
for addr in range ( start , start + size ) :
    if len ( self . _symbols ) == 0 :
        break
    if addr in self . _symbols :
        del self . _symbols [ addr ]
super ( ) . munmap ( start , size )


signature:
def read ( self , address , size , force = False ) :
    """Read a stream of potentially symbolic bytes from a potentially symbolic
 address
 : param address : Where to read from
 : param size : How many bytes
 : param force : Whether to ignore permissions
 : rtype : list"""

implementation:
size = self . _get_size ( size )
assert not issymbolic ( size )
if issymbolic ( address ) :
    assert solver . check ( self . constraints )
    logger . debug ( f'Reading {size} bytes from symbolic address {address}' )
    try :
        solutions = self . _try_get_solutions ( address , size , 'r' , force = force )
        assert len ( solutions ) > 0
    except TooManySolutions as e :
        m , M = solver . minmax ( self . constraints , address )
        logger . debug ( f'Got TooManySolutions on a symbolic read. Range [{m:x}, {M:x}]. Not crashing!' )
        # The force param shouldn ' t affect this , as this is checking for unmapped reads , not bad perms
        crashing_condition = True
        for start , end , perms , offset , name in self . mappings ( ) :
            if start <= M + size and end >= m :
                if 'r' in perms :
                    crashing_condition = Operators . AND ( Operators . OR ( ( address + size ) . ult ( start ) , address . uge ( end ) ) , crashing_condition )
        if solver . can_be_true ( self . constraints , crashing_condition ) :
            raise InvalidSymbolicMemoryAccess ( address , 'r' , size , crashing_condition )
        # INCOMPLETE Result ! We could also fork once for every map
        logger . info ( 'INCOMPLETE Result! Using the sampled solutions we have as result' )
        condition = False
        for base in e . solutions :
            condition = Operators . OR ( address == base , condition )
        from . state import ForkState
        raise ForkState ( "Forking state on incomplete result" , condition )
    # So here we have all potential solutions to address
    condition = False
    for base in solutions :
        condition = Operators . OR ( address == base , condition )
    result = [ ]
    # consider size = = 1 to read following code
    for offset in range ( size ) : # Given ALL solutions for the symbolic address
        for base in solutions :
            addr_value = base + offset
            byte = Operators . ORD ( self . map_containing ( addr_value ) [ addr_value ] )
            if addr_value in self . _symbols :
                for condition , value in self . _symbols [ addr_value ] :
                    byte = Operators . ITEBV ( 8 , condition , Operators . ORD ( value ) , byte )
            if len ( result ) > offset :
                result [ offset ] = Operators . ITEBV ( 8 , address == base , byte , result [ offset ] )
            else :
                result . append ( byte )
            assert len ( result ) == offset + 1
    return list ( map ( Operators . CHR , result ) )
else :
    result = list ( map ( Operators . ORD , super ( ) . read ( address , size , force ) ) )
    for offset in range ( size ) :
        if address + offset in self . _symbols :
            for condition , value in self . _symbols [ address + offset ] :
                if condition is True :
                    result [ offset ] = Operators . ORD ( value )
                else :
                    result [ offset ] = Operators . ITEBV ( 8 , condition , Operators . ORD ( value ) , result [ offset ] )
    return list ( map ( Operators . CHR , result ) )


signature:
def write ( self , address , value , force = False ) :
    """Write a value at address .
 : param address : The address at which to write
 : type address : int or long or Expression
 : param value : Bytes to write
 : type value : str or list
 : param force : Whether to ignore permissions"""

implementation:
size = len ( value )
if issymbolic ( address ) :
    solutions = self . _try_get_solutions ( address , size , 'w' , force = force )
    for offset in range ( size ) :
        for base in solutions :
            condition = base == address
            self . _symbols . setdefault ( base + offset , [ ] ) . append ( ( condition , value [ offset ] ) )
else :
    for offset in range ( size ) :
        if issymbolic ( value [ offset ] ) :
            if not self . access_ok ( address + offset , 'w' , force ) :
                raise InvalidMemoryAccess ( address + offset , 'w' )
            self . _symbols [ address + offset ] = [ ( True , value [ offset ] ) ]
        else : # overwrite all previous items
            if address + offset in self . _symbols :
                del self . _symbols [ address + offset ]
            super ( ) . write ( address + offset , [ value [ offset ] ] , force )


signature:
def _try_get_solutions ( self , address , size , access , max_solutions = 0x1000 , force = False ) :
    """Try to solve for a symbolic address , checking permissions when reading / writing size bytes .
 : param Expression address : The address to solve for
 : param int size : How many bytes to check permissions for
 : param str access : ' r ' or ' w '
 : param int max _ solutions : Will raise if more solutions are found
 : param force : Whether to ignore permission failure
 : rtype : list"""

implementation:
assert issymbolic ( address )
solutions = solver . get_all_values ( self . constraints , address , maxcnt = max_solutions )
crashing_condition = False
for base in solutions :
    if not self . access_ok ( slice ( base , base + size ) , access , force ) :
        crashing_condition = Operators . OR ( address == base , crashing_condition )
if solver . can_be_true ( self . constraints , crashing_condition ) :
    raise InvalidSymbolicMemoryAccess ( address , access , size , crashing_condition )
return solutions


implementation:
# If addr is NULL , the system determines where to allocate the region .
assert addr is None or isinstance ( addr , int ) , 'Address shall be concrete'
assert addr < self . memory_size , 'Address too big'
assert size > 0
self . cpu . _publish ( 'will_map_memory' , addr , size , perms , filename , offset )
map = AnonMap ( addr , size , perms )
self . _add ( map )
# address is rounded down to the nearest multiple of the allocation granularity
if addr is not None :
    addr = self . _floor ( addr )
# size value is rounded up to the next page boundary
size = self . _ceil ( size )
with open ( filename , 'rb' ) as f :
    fdata = f . read ( )
# fdata is a bytes now
# this worked
fdata = fdata [ offset : ]
fdata = fdata . ljust ( size , b'\0' )
for i in range ( size ) :
    Memory . write ( self , addr + i , chr ( fdata [ i ] ) , force = True )
logger . debug ( 'New file-memory map @%x size:%x' , addr , size )
self . cpu . _publish ( 'did_map_memory' , addr , size , perms , filename , offset , addr )
return addr


signature:
def _import_concrete_memory ( self , from_addr , to_addr ) :
    """for each address in this range need to read from concrete and write to symbolic
 it ' s possible that there will be invalid / unmapped addresses in this range . need to skip to next map if so
 also need to mark all of these addresses as now in the symbolic store
 : param int from _ addr :
 : param int to _ addr :
 : return :"""

implementation:
logger . debug ( "Importing concrete memory: {:x} - {:x} ({} bytes)" . format ( from_addr , to_addr , to_addr - from_addr ) )
for m in self . maps :
    span = interval_intersection ( m . start , m . end , from_addr , to_addr )
    if span is None :
        continue
    start , stop = span
    for addr in range ( start , stop ) :
        if addr in self . backed_by_symbolic_store :
            continue
        self . backing_array [ addr ] = Memory . read ( self , addr , 1 ) [ 0 ]
        self . backed_by_symbolic_store . add ( addr )


signature:
def scan_mem ( self , data_to_find ) :
    """Scan for concrete bytes in all mapped memory . Successively yield addresses of all matches .
 : param bytes data _ to _ find : String to locate
 : return :"""

implementation:
# TODO : for the moment we just treat symbolic bytes as bytes that don ' t match .
# for our simple test cases right now , the bytes we ' re interested in scanning
# for will all just be there concretely
# TODO : Can probably do something smarter here like Boyer - Moore , but unnecessary
# if we ' re looking for short strings .
# Querying mem with an index returns [ bytes ]
if isinstance ( data_to_find , bytes ) :
    data_to_find = [ bytes ( [ c ] ) for c in data_to_find ]
for mapping in sorted ( self . maps ) :
    for ptr in mapping :
        if ptr + len ( data_to_find ) >= mapping . end :
            break
        candidate = mapping [ ptr : ptr + len ( data_to_find ) ]
        # TODO : treat symbolic bytes as bytes that don ' t match . for our simple tests right now , the
        # bytes will be there concretely
        if issymbolic ( candidate [ 0 ] ) :
            break
        if candidate == data_to_find :
            yield ptr


signature:
def _reg_name ( self , reg_id ) :
    """Translates a register ID from the disassembler object into the
 register name based on manticore ' s alias in the register file
 : param int reg _ id : Register ID"""

implementation:
if reg_id >= X86_REG_ENDING :
    logger . warning ( "Trying to get register name for a non-register" )
    return None
cs_reg_name = self . cpu . instruction . reg_name ( reg_id )
if cs_reg_name is None or cs_reg_name . lower ( ) == '(invalid)' :
    return None
return self . cpu . _regfile . _alias ( cs_reg_name . upper ( ) )


signature:
def values_from ( self , base ) :
    """A reusable generator for increasing pointer - sized values from an address
 ( usually the stack ) ."""

implementation:
word_bytes = self . _cpu . address_bit_size // 8
while True :
    yield base
    base += word_bytes


signature:
def get_argument_values ( self , model , prefix_args ) :
    """Extract arguments for model from the environment and return as a tuple that
 is ready to be passed to the model .
 : param callable model : Python model of the function
 : param tuple prefix _ args : Parameters to pass to model before actual ones
 : return : Arguments to be passed to the model
 : rtype : tuple"""

implementation:
spec = inspect . getfullargspec ( model )
if spec . varargs :
    logger . warning ( "ABI: A vararg model must be a unary function." )
nargs = len ( spec . args ) - len ( prefix_args )
# If the model is a method , we need to account for ` self `
if inspect . ismethod ( model ) :
    nargs -= 1
def resolve_argument ( arg ) :
    if isinstance ( arg , str ) :
        return self . _cpu . read_register ( arg )
    else :
        return self . _cpu . read_int ( arg )
# Create a stream of resolved arguments from argument descriptors
descriptors = self . get_arguments ( )
argument_iter = map ( resolve_argument , descriptors )
from . . models import isvariadic
# prevent circular imports
if isvariadic ( model ) :
    arguments = prefix_args + ( argument_iter , )
else :
    arguments = prefix_args + tuple ( islice ( argument_iter , nargs ) )
return arguments


signature:
def invoke ( self , model , prefix_args = None ) :
    """Invoke a callable ` model ` as if it was a native function . If
 : func : ` ~ manticore . models . isvariadic ` returns true for ` model ` , ` model ` receives a single
 argument that is a generator for function arguments . Pass a tuple of
 arguments for ` prefix _ args ` you ' d like to precede the actual
 arguments .
 : param callable model : Python model of the function
 : param tuple prefix _ args : Parameters to pass to model before actual ones
 : return : The result of calling ` model `"""

implementation:
prefix_args = prefix_args or ( )
arguments = self . get_argument_values ( model , prefix_args )
try :
    result = model ( * arguments )
except ConcretizeArgument as e :
    assert e . argnum >= len ( prefix_args ) , "Can't concretize a constant arg"
    idx = e . argnum - len ( prefix_args )
    # Arguments were lazily computed in case of variadic , so recompute here
    descriptors = self . get_arguments ( )
    src = next ( islice ( descriptors , idx , idx + 1 ) )
    msg = 'Concretizing due to model invocation'
    if isinstance ( src , str ) :
        raise ConcretizeRegister ( self . _cpu , src , msg )
    else :
        raise ConcretizeMemory ( self . _cpu . memory , src , self . _cpu . address_bit_size , msg )
else :
    if result is not None :
        self . write_result ( result )
    self . ret ( )
return result


signature:
def write_register ( self , register , value ) :
    """Dynamic interface for writing cpu registers
 : param str register : register name ( as listed in ` self . all _ registers ` )
 : param value : register value
 : type value : int or long or Expression"""

implementation:
self . _publish ( 'will_write_register' , register , value )
value = self . _regfile . write ( register , value )
self . _publish ( 'did_write_register' , register , value )
return value


signature:
def read_register ( self , register ) :
    """Dynamic interface for reading cpu registers
 : param str register : register name ( as listed in ` self . all _ registers ` )
 : return : register value
 : rtype : int or long or Expression"""

implementation:
self . _publish ( 'will_read_register' , register )
value = self . _regfile . read ( register )
self . _publish ( 'did_read_register' , register , value )
return value


signature:
def emulate_until ( self , target : int ) :
    """Tells the CPU to set up a concrete unicorn emulator and use it to execute instructions
 until target is reached .
 : param target : Where Unicorn should hand control back to Manticore . Set to 0 for all instructions ."""

implementation:
self . _concrete = True
self . _break_unicorn_at = target
if self . emu :
    self . emu . _stop_at = target


signature:
def write_int ( self , where , expression , size = None , force = False ) :
    """Writes int to memory
 : param int where : address to write to
 : param expr : value to write
 : type expr : int or BitVec
 : param size : bit size of ` expr `
 : param force : whether to ignore memory permissions"""

implementation:
if size is None :
    size = self . address_bit_size
assert size in SANE_SIZES
self . _publish ( 'will_write_memory' , where , expression , size )
data = [ Operators . CHR ( Operators . EXTRACT ( expression , offset , 8 ) ) for offset in range ( 0 , size , 8 ) ]
self . _memory . write ( where , data , force )
self . _publish ( 'did_write_memory' , where , expression , size )


signature:
def _raw_read ( self , where : int , size = 1 ) -> bytes :
    """Selects bytes from memory . Attempts to do so faster than via read _ bytes .
 : param where : address to read from
 : param size : number of bytes to read
 : return : the bytes in memory"""

implementation:
map = self . memory . map_containing ( where )
start = map . _get_offset ( where )
mapType = type ( map )
if mapType is FileMap :
    end = map . _get_offset ( where + size )
    if end > map . _mapped_size :
        logger . warning ( f"Missing {end - map._mapped_size} bytes at the end of {map._filename}" )
    raw_data = map . _data [ map . _get_offset ( where ) : min ( end , map . _mapped_size ) ]
    if len ( raw_data ) < end :
        raw_data += b'\x00' * ( end - len ( raw_data ) )
    data = b''
    for offset in sorted ( map . _overlay . keys ( ) ) :
        data += raw_data [ len ( data ) : offset ]
        data += map . _overlay [ offset ]
    data += raw_data [ len ( data ) : ]
elif mapType is AnonMap :
    data = bytes ( map . _data [ start : start + size ] )
else :
    data = b'' . join ( self . memory [ where : where + size ] )
assert len ( data ) == size , 'Raw read resulted in wrong data read which should never happen'
return data


signature:
def read_int ( self , where , size = None , force = False ) :
    """Reads int from memory
 : param int where : address to read from
 : param size : number of bits to read
 : return : the value read
 : rtype : int or BitVec
 : param force : whether to ignore memory permissions"""

implementation:
if size is None :
    size = self . address_bit_size
assert size in SANE_SIZES
self . _publish ( 'will_read_memory' , where , size )
data = self . _memory . read ( where , size // 8 , force )
assert ( 8 * len ( data ) ) == size
value = Operators . CONCAT ( size , * map ( Operators . ORD , reversed ( data ) ) )
self . _publish ( 'did_read_memory' , where , value , size )
return value


signature:
def write_bytes ( self , where , data , force = False ) :
    """Write a concrete or symbolic ( or mixed ) buffer to memory
 : param int where : address to write to
 : param data : data to write
 : type data : str or list
 : param force : whether to ignore memory permissions"""

implementation:
mp = self . memory . map_containing ( where )
# TODO ( ehennenfent ) - fast write can have some yet - unstudied unintended side effects .
# At the very least , using it in non - concrete mode will break the symbolic strcmp / strlen models . The 1024 byte
# minimum is intended to minimize the potential effects of this by ensuring that if there _ are _ any other
# issues , they ' ll only crop up when we ' re doing very large writes , which are fairly uncommon .
can_write_raw = type ( mp ) is AnonMap and isinstance ( data , ( str , bytes ) ) and ( mp . end - mp . start + 1 ) >= len ( data ) >= 1024 and not issymbolic ( data ) and self . _concrete
if can_write_raw :
    logger . debug ( "Using fast write" )
    offset = mp . _get_offset ( where )
    if isinstance ( data , str ) :
        data = bytes ( data . encode ( 'utf-8' ) )
    mp . _data [ offset : offset + len ( data ) ] = data
    self . _publish ( 'did_write_memory' , where , data , 8 * len ( data ) )
else :
    for i in range ( len ( data ) ) :
        self . write_int ( where + i , Operators . ORD ( data [ i ] ) , 8 , force )


signature:
def read_bytes ( self , where , size , force = False ) :
    """Read from memory .
 : param int where : address to read data from
 : param int size : number of bytes
 : param force : whether to ignore memory permissions
 : return : data
 : rtype : list [ int or Expression ]"""

implementation:
result = [ ]
for i in range ( size ) :
    result . append ( Operators . CHR ( self . read_int ( where + i , 8 , force ) ) )
return result


signature:
def write_string ( self , where , string , max_length = None , force = False ) :
    """Writes a string to memory , appending a NULL - terminator at the end .
 : param int where : Address to write the string to
 : param str string : The string to write to memory
 : param int max _ length :
 The size in bytes to cap the string at , or None [ default ] for no
 limit . This includes the NULL terminator .
 : param force : whether to ignore memory permissions"""

implementation:
if max_length is not None :
    string = string [ : max_length - 1 ]
self . write_bytes ( where , string + '\x00' , force )


signature:
def read_string ( self , where , max_length = None , force = False ) :
    """Read a NUL - terminated concrete buffer from memory . Stops reading at first symbolic byte .
 : param int where : Address to read string from
 : param int max _ length :
 The size in bytes to cap the string at , or None [ default ] for no
 limit .
 : param force : whether to ignore memory permissions
 : return : string read
 : rtype : str"""

implementation:
s = io . BytesIO ( )
while True :
    c = self . read_int ( where , 8 , force )
    if issymbolic ( c ) or c == 0 :
        break
    if max_length is not None :
        if max_length == 0 :
            break
        max_length = max_length - 1
    s . write ( Operators . CHR ( c ) )
    where += 1
return s . getvalue ( ) . decode ( )


signature:
def push_bytes ( self , data , force = False ) :
    """Write ` data ` to the stack and decrement the stack pointer accordingly .
 : param str data : Data to write
 : param force : whether to ignore memory permissions"""

implementation:
self . STACK -= len ( data )
self . write_bytes ( self . STACK , data , force )
return self . STACK


signature:
def pop_bytes ( self , nbytes , force = False ) :
    """Read ` nbytes ` from the stack , increment the stack pointer , and return
 data .
 : param int nbytes : How many bytes to read
 : param force : whether to ignore memory permissions
 : return : Data read from the stack"""

implementation:
data = self . read_bytes ( self . STACK , nbytes , force = force )
self . STACK += nbytes
return data


signature:
def push_int ( self , value , force = False ) :
    """Decrement the stack pointer and write ` value ` to the stack .
 : param int value : The value to write
 : param force : whether to ignore memory permissions
 : return : New stack pointer"""

implementation:
self . STACK -= self . address_bit_size // 8
self . write_int ( self . STACK , value , force = force )
return self . STACK


signature:
def pop_int ( self , force = False ) :
    """Read a value from the stack and increment the stack pointer .
 : param force : whether to ignore memory permissions
 : return : Value read"""

implementation:
value = self . read_int ( self . STACK , force = force )
self . STACK += self . address_bit_size // 8
return value


signature:
def decode_instruction ( self , pc ) :
    """This will decode an instruction from memory pointed by ` pc `
 : param int pc : address of the instruction"""

implementation:
# No dynamic code ! ! ! # TODO !
# Check if instruction was already decoded
if pc in self . _instruction_cache :
    return self . _instruction_cache [ pc ]
text = b''
# Read Instruction from memory
for address in range ( pc , pc + self . max_instr_width ) : # This reads a byte from memory ignoring permissions
# and concretize it if symbolic
    if not self . memory . access_ok ( address , 'x' ) :
        break
    c = self . memory [ address ]
    if issymbolic ( c ) : # In case of fully symbolic memory , eagerly get a valid ptr
        if isinstance ( self . memory , LazySMemory ) :
            try :
                vals = visitors . simplify_array_select ( c )
                c = bytes ( [ vals [ 0 ] ] )
            except visitors . ArraySelectSimplifier . ExpressionNotSimple :
                c = struct . pack ( 'B' , solver . get_value ( self . memory . constraints , c ) )
        elif isinstance ( c , Constant ) :
            c = bytes ( [ c . value ] )
        else :
            logger . error ( 'Concretize executable memory %r %r' , c , text )
            raise ConcretizeMemory ( self . memory , address = pc , size = 8 * self . max_instr_width , policy = 'INSTRUCTION' )
    text += c
# Pad potentially incomplete instruction with zeroes
code = text . ljust ( self . max_instr_width , b'\x00' )
try : # decode the instruction from code
    insn = self . disasm . disassemble_instruction ( code , pc )
except StopIteration as e :
    raise DecodeException ( pc , code )
# Check that the decoded instruction is contained in executable memory
if not self . memory . access_ok ( slice ( pc , pc + insn . size ) , 'x' ) :
    logger . info ( "Trying to execute instructions from non-executable memory" )
    raise InvalidMemoryAccess ( pc , 'x' )
insn . operands = self . _wrap_operands ( insn . operands )
self . _instruction_cache [ pc ] = insn
return insn


signature:
def execute ( self ) :
    """Decode , and execute one instruction pointed by register PC"""

implementation:
if issymbolic ( self . PC ) :
    raise ConcretizeRegister ( self , 'PC' , policy = 'ALL' )
if not self . memory . access_ok ( self . PC , 'x' ) :
    raise InvalidMemoryAccess ( self . PC , 'x' )
self . _publish ( 'will_decode_instruction' , self . PC )
insn = self . decode_instruction ( self . PC )
self . _last_pc = self . PC
self . _publish ( 'will_execute_instruction' , self . PC , insn )
# FIXME ( theo ) why just return here ?
if insn . address != self . PC :
    return
name = self . canonicalize_instruction_name ( insn )
if logger . level == logging . DEBUG :
    logger . debug ( self . render_instruction ( insn ) )
    for l in self . render_registers ( ) :
        register_logger . debug ( l )
try :
    if self . _concrete and 'SYSCALL' in name :
        self . emu . sync_unicorn_to_manticore ( )
    if self . _concrete and 'SYSCALL' not in name :
        self . emulate ( insn )
        if self . PC == self . _break_unicorn_at :
            logger . debug ( "Switching from Unicorn to Manticore" )
            self . _break_unicorn_at = None
            self . _concrete = False
    else :
        implementation = getattr ( self , name , None )
        if implementation is not None :
            implementation ( * insn . operands )
        else :
            text_bytes = ' ' . join ( '%02x' % x for x in insn . bytes )
            logger . warning ( "Unimplemented instruction: 0x%016x:\t%s\t%s\t%s" , insn . address , text_bytes , insn . mnemonic , insn . op_str )
            self . backup_emulate ( insn )
except ( Interruption , Syscall ) as e :
    e . on_handled = lambda : self . _publish_instruction_as_executed ( insn )
    raise e
else :
    self . _publish_instruction_as_executed ( insn )


signature:
def _publish_instruction_as_executed ( self , insn ) :
    """Notify listeners that an instruction has been executed ."""

implementation:
self . _icount += 1
self . _publish ( 'did_execute_instruction' , self . _last_pc , self . PC , insn )


signature:
def emulate ( self , insn ) :
    """Pick the right emulate function ( maintains API compatiblity )
 : param insn : single instruction to emulate / start emulation from"""

implementation:
if self . _concrete :
    self . concrete_emulate ( insn )
else :
    self . backup_emulate ( insn )


signature:
def concrete_emulate ( self , insn ) :
    """Start executing in Unicorn from this point until we hit a syscall or reach break _ unicorn _ at
 : param capstone . CsInsn insn : The instruction object to emulate"""

implementation:
if not self . emu :
    self . emu = ConcreteUnicornEmulator ( self )
    self . emu . _stop_at = self . _break_unicorn_at
try :
    self . emu . emulate ( insn )
except unicorn . UcError as e :
    if e . errno == unicorn . UC_ERR_INSN_INVALID :
        text_bytes = ' ' . join ( '%02x' % x for x in insn . bytes )
        logger . error ( "Unimplemented instruction: 0x%016x:\t%s\t%s\t%s" , insn . address , text_bytes , insn . mnemonic , insn . op_str )
    raise InstructionEmulationError ( str ( e ) )


signature:
def backup_emulate ( self , insn ) :
    """If we could not handle emulating an instruction , use Unicorn to emulate
 it .
 : param capstone . CsInsn instruction : The instruction object to emulate"""

implementation:
if not hasattr ( self , 'backup_emu' ) :
    self . backup_emu = UnicornEmulator ( self )
try :
    self . backup_emu . emulate ( insn )
except unicorn . UcError as e :
    if e . errno == unicorn . UC_ERR_INSN_INVALID :
        text_bytes = ' ' . join ( '%02x' % x for x in insn . bytes )
        logger . error ( "Unimplemented instruction: 0x%016x:\t%s\t%s\t%s" , insn . address , text_bytes , insn . mnemonic , insn . op_str )
    raise InstructionEmulationError ( str ( e ) )
finally : # We have been seeing occasional Unicorn issues with it not clearing
# the backing unicorn instance . Saw fewer issues with the following
# line present .
    del self . backup_emu


signature:
def viz_trace ( view ) :
    """Given a Manticore trace file , highlight the basic blocks ."""

implementation:
tv = TraceVisualizer ( view , None )
if tv . workspace is None :
    tv . workspace = get_workspace ( )
tv . visualize ( )


signature:
def viz_live_trace ( view ) :
    """Given a Manticore trace file , highlight the basic blocks ."""

implementation:
tv = TraceVisualizer ( view , None , live = True )
if tv . workspace is None :
    tv . workspace = get_workspace ( )
# update due to singleton in case we are called after a clear
tv . live_update = True
tv . visualize ( )


signature:
def visualize ( self ) :
    """Given a Manticore workspace , or trace file , highlight the basic blocks ."""

implementation:
if os . path . isfile ( self . workspace ) :
    t = threading . Thread ( target = self . highlight_from_file , args = ( self . workspace , ) )
elif os . path . isdir ( self . workspace ) :
    t = threading . Thread ( target = self . highlight_from_dir , args = ( self . workspace , ) )
t . start ( )


signature:
def t_TOKEN ( t ) :
    '[ a - zA - Z0-9 ] +'

implementation:
# print t . value , t . lexer . lexdata [ t . lexer . lexpos - len ( t . value ) : ] , re _ TYPE . match ( t . lexer . lexdata , t . lexer . lexpos - len ( t . value ) )
if re_TYPE . match ( t . value ) :
    t . type = 'TYPE'
elif re_PTR . match ( t . value ) :
    t . type = 'PTR'
elif re_NUMBER . match ( t . value ) :
    if t . value . startswith ( '0x' ) :
        t . value = t . value [ 2 : ]
    t . value = int ( t . value , 16 )
    t . type = 'NUMBER'
elif re_REGISTER . match ( t . value ) :
    t . type = 'REGISTER'
elif re_SEGMENT . match ( t . value ) :
    t . type = 'SEGMENT'
else :
    raise Exception ( f"Unknown:<{t.value}>" )
return t


signature:
def p_expression_deref ( p ) :
    'expression : TYPE PTR LBRAKET expression RBRAKET'

implementation:
size = sizes [ p [ 1 ] ]
address = p [ 4 ]
char_list = functions [ 'read_memory' ] ( address , size )
value = Operators . CONCAT ( 8 * len ( char_list ) , * reversed ( map ( Operators . ORD , char_list ) ) )
p [ 0 ] = value


signature:
def p_expression_derefseg ( p ) :
    'expression : TYPE PTR SEGMENT COLOM LBRAKET expression RBRAKET'

implementation:
size = sizes [ p [ 1 ] ]
address = p [ 6 ]
seg = functions [ 'read_register' ] ( p [ 3 ] )
base , limit , _ = functions [ 'get_descriptor' ] ( seg )
address = base + address
char_list = functions [ 'read_memory' ] ( address , size )
value = Operators . CONCAT ( 8 * len ( char_list ) , * reversed ( map ( Operators . ORD , char_list ) ) )
p [ 0 ] = value


signature:
def _get_flags ( self , reg ) :
    """Build EFLAGS / RFLAGS from flags"""

implementation:
def make_symbolic ( flag_expr ) :
    register_size = 32 if reg == 'EFLAGS' else 64
    value , offset = flag_expr
    return Operators . ITEBV ( register_size , value , BitVecConstant ( register_size , 1 << offset ) , BitVecConstant ( register_size , 0 ) )
flags = [ ]
for flag , offset in self . _flags . items ( ) :
    flags . append ( ( self . _registers [ flag ] , offset ) )
if any ( issymbolic ( flag ) for flag , offset in flags ) :
    res = reduce ( operator . or_ , map ( make_symbolic , flags ) )
else :
    res = 0
    for flag , offset in flags :
        res += flag << offset
return res


signature:
def _set_flags ( self , reg , res ) :
    """Set individual flags from a EFLAGS / RFLAGS value"""

implementation:
# assert sizeof ( res ) = = 32 if reg = = ' EFLAGS ' else 64
for flag , offset in self . _flags . items ( ) :
    self . write ( flag , Operators . EXTRACT ( res , offset , 1 ) )


signature:
def push ( cpu , value , size ) :
    """Writes a value in the stack .
 : param value : the value to put in the stack .
 : param size : the size of the value ."""

implementation:
assert size in ( 8 , 16 , cpu . address_bit_size )
cpu . STACK = cpu . STACK - size // 8
base , _ , _ = cpu . get_descriptor ( cpu . read_register ( 'SS' ) )
address = cpu . STACK + base
cpu . write_int ( address , value , size )


signature:
def pop ( cpu , size ) :
    """Gets a value from the stack .
 : rtype : int
 : param size : the size of the value to consume from the stack .
 : return : the value from the stack ."""

implementation:
assert size in ( 16 , cpu . address_bit_size )
base , _ , _ = cpu . get_descriptor ( cpu . SS )
address = cpu . STACK + base
value = cpu . read_int ( address , size )
cpu . STACK = cpu . STACK + size // 8
return value


signature:
def invalidate_cache ( cpu , address , size ) :
    """remove decoded instruction from instruction cache"""

implementation:
cache = cpu . instruction_cache
for offset in range ( size ) :
    if address + offset in cache :
        del cache [ address + offset ]


signature:
def CPUID ( cpu ) :
    """CPUID instruction .
 The ID flag ( bit 21 ) in the EFLAGS register indicates support for the
 CPUID instruction . If a software procedure can set and clear this
 flag , the processor executing the procedure supports the CPUID
 instruction . This instruction operates the same in non - 64 - bit modes and
 64 - bit mode . CPUID returns processor identification and feature
 information in the EAX , EBX , ECX , and EDX registers .
 The instruction ' s output is dependent on the contents of the EAX
 register upon execution .
 : param cpu : current CPU ."""


signature:
def AND ( cpu , dest , src ) :
    """Logical AND .
 Performs a bitwise AND operation on the destination ( first ) and source
 ( second ) operands and stores the result in the destination operand location .
 Each bit of the result is set to 1 if both corresponding bits of the first and
 second operands are 1 ; otherwise , it is set to 0.
 The OF and CF flags are cleared ; the SF , ZF , and PF flags are set according to the result : :
 DEST = DEST AND SRC ;
 : param cpu : current CPU .
 : param dest : destination operand .
 : param src : source operand ."""

implementation:
# XXX bypass a capstone bug that incorrectly extends and computes operands sizes
# the bug has been fixed since capstone 4.0 . alpha2 ( commit de8dd26)
if src . size == 64 and src . type == 'immediate' and dest . size == 64 :
    arg1 = Operators . SEXTEND ( src . read ( ) , 32 , 64 )
else :
    arg1 = src . read ( )
res = dest . write ( dest . read ( ) & arg1 )
# Defined Flags : szp
cpu . _calculate_logic_flags ( dest . size , res )


signature:
def TEST ( cpu , src1 , src2 ) :
    """Logical compare .
 Computes the bit - wise logical AND of first operand ( source 1 operand )
 and the second operand ( source 2 operand ) and sets the SF , ZF , and PF
 status flags according to the result . The result is then discarded : :
 TEMP = SRC1 AND SRC2;
 SF = MSB ( TEMP ) ;
 IF TEMP = 0
 THEN ZF = 1;
 ELSE ZF = 0;
 FI :
 PF = BitwiseXNOR ( TEMP [ 0:7 ] ) ;
 CF = 0;
 OF = 0;
 ( * AF is Undefined * )
 : param cpu : current CPU .
 : param src1 : first operand .
 : param src2 : second operand ."""

implementation:
# Defined Flags : szp
temp = src1 . read ( ) & src2 . read ( )
cpu . SF = ( temp & ( 1 << ( src1 . size - 1 ) ) ) != 0
cpu . ZF = temp == 0
cpu . PF = cpu . _calculate_parity_flag ( temp )
cpu . CF = False
cpu . OF = False


signature:
def XOR ( cpu , dest , src ) :
    """Logical exclusive OR .
 Performs a bitwise exclusive Operators . OR ( XOR ) operation on the destination ( first )
 and source ( second ) operands and stores the result in the destination
 operand location .
 Each bit of the result is 1 if the corresponding bits of the operands
 are different ; each bit is 0 if the corresponding bits are the same .
 The OF and CF flags are cleared ; the SF , ZF , and PF flags are set according to the result : :
 DEST = DEST XOR SRC ;
 : param cpu : current CPU .
 : param dest : destination operand .
 : param src : source operand ."""

implementation:
if dest == src : # if the operands are the same write zero
    res = dest . write ( 0 )
else :
    res = dest . write ( dest . read ( ) ^ src . read ( ) )
# Defined Flags : szp
cpu . _calculate_logic_flags ( dest . size , res )


signature:
def OR ( cpu , dest , src ) :
    """Logical inclusive OR .
 Performs a bitwise inclusive OR operation between the destination ( first )
 and source ( second ) operands and stores the result in the destination operand location .
 Each bit of the result of the OR instruction is set to 0 if both corresponding
 bits of the first and second operands are 0 ; otherwise , each bit is set
 to 1.
 The OF and CF flags are cleared ; the SF , ZF , and PF flags are set according to the result : :
 DEST = DEST OR SRC ;
 : param cpu : current CPU .
 : param dest : destination operand .
 : param src : source operand ."""

implementation:
res = dest . write ( dest . read ( ) | src . read ( ) )
# Defined Flags : szp
cpu . _calculate_logic_flags ( dest . size , res )


signature:
def AAD ( cpu , imm = None ) :
    """ASCII adjust AX before division .
 Adjusts two unpacked BCD digits ( the least - significant digit in the
 AL register and the most - significant digit in the AH register ) so that
 a division operation performed on the result will yield a correct unpacked
 BCD value . The AAD instruction is only useful when it precedes a DIV instruction
 that divides ( binary division ) the adjusted value in the AX register by
 an unpacked BCD value .
 The AAD instruction sets the value in the AL register to ( AL + ( 10 * AH ) ) , and then
 clears the AH register to 00H . The value in the AX register is then equal to the binary
 equivalent of the original unpacked two - digit ( base 10 ) number in registers AH and AL .
 The SF , ZF , and PF flags are set according to the resulting binary value in the AL register .
 This instruction executes as described in compatibility mode and legacy mode .
 It is not valid in 64 - bit mode . : :
 tempAL = AL ;
 tempAH = AH ;
 AL = ( tempAL + ( tempAH * 10 ) ) AND FFH ;
 AH = 0
 : param cpu : current CPU ."""

implementation:
if imm is None :
    imm = 10
else :
    imm = imm . read ( )
cpu . AL += cpu . AH * imm
cpu . AH = 0
# Defined flags : . . . sz . p .
cpu . _calculate_logic_flags ( 8 , cpu . AL )


signature:
def AAM ( cpu , imm = None ) :
    """ASCII adjust AX after multiply .
 Adjusts the result of the multiplication of two unpacked BCD values
 to create a pair of unpacked ( base 10 ) BCD values . The AX register is
 the implied source and destination operand for this instruction . The AAM
 instruction is only useful when it follows a MUL instruction that multiplies
 ( binary multiplication ) two unpacked BCD values and stores a word result
 in the AX register . The AAM instruction then adjusts the contents of the
 AX register to contain the correct 2 - digit unpacked ( base 10 ) BCD result .
 The SF , ZF , and PF flags are set according to the resulting binary value in the AL register .
 This instruction executes as described in compatibility mode and legacy mode .
 It is not valid in 64 - bit mode . : :
 tempAL = AL ;
 AH = tempAL / 10;
 AL = tempAL MOD 10;
 : param cpu : current CPU ."""

implementation:
if imm is None :
    imm = 10
else :
    imm = imm . read ( )
cpu . AH = Operators . UDIV ( cpu . AL , imm )
cpu . AL = Operators . UREM ( cpu . AL , imm )
# Defined flags : . . . sz . p .
cpu . _calculate_logic_flags ( 8 , cpu . AL )


signature:
def AAS ( cpu ) :
    """ASCII Adjust AL after subtraction .
 Adjusts the result of the subtraction of two unpacked BCD values to create a unpacked
 BCD result . The AL register is the implied source and destination operand for this instruction .
 The AAS instruction is only useful when it follows a SUB instruction that subtracts
 ( binary subtraction ) one unpacked BCD value from another and stores a byte result in the AL
 register . The AAA instruction then adjusts the contents of the AL register to contain the
 correct 1 - digit unpacked BCD result . If the subtraction produced a decimal carry , the AH register
 is decremented by 1 , and the CF and AF flags are set . If no decimal carry occurred , the CF and AF
 flags are cleared , and the AH register is unchanged . In either case , the AL register is left with
 its top nibble set to 0.
 The AF and CF flags are set to 1 if there is a decimal borrow ; otherwise , they are cleared to 0.
 This instruction executes as described in compatibility mode and legacy mode .
 It is not valid in 64 - bit mode . : :
 IF ( ( AL AND 0FH ) > 9 ) Operators . OR ( AF = 1)
 THEN
 AX = AX - 6;
 AH = AH - 1;
 AF = 1;
 CF = 1;
 ELSE
 CF = 0;
 AF = 0;
 FI ;
 AL = AL AND 0FH ;
 : param cpu : current CPU ."""

implementation:
if ( cpu . AL & 0x0F > 9 ) or cpu . AF == 1 :
    cpu . AX = cpu . AX - 6
    cpu . AH = cpu . AH - 1
    cpu . AF = True
    cpu . CF = True
else :
    cpu . AF = False
    cpu . CF = False
cpu . AL = cpu . AL & 0x0f


signature:
def ADC ( cpu , dest , src ) :
    """Adds with carry .
 Adds the destination operand ( first operand ) , the source operand ( second operand ) ,
 and the carry ( CF ) flag and stores the result in the destination operand . The state
 of the CF flag represents a carry from a previous addition . When an immediate value
 is used as an operand , it is sign - extended to the length of the destination operand
 format . The ADC instruction does not distinguish between signed or unsigned operands .
 Instead , the processor evaluates the result for both data types and sets the OF and CF
 flags to indicate a carry in the signed or unsigned result , respectively . The SF flag
 indicates the sign of the signed result . The ADC instruction is usually executed as
 part of a multibyte or multiword addition in which an ADD instruction is followed by an
 ADC instruction : :
 DEST = DEST + SRC + CF ;
 The OF , SF , ZF , AF , CF , and PF flags are set according to the result .
 : param cpu : current CPU .
 : param dest : destination operand .
 : param src : source operand ."""

implementation: cpu . _ADD ( dest , src , carry = True )


signature:
def ADD ( cpu , dest , src ) :
    """Add .
 Adds the first operand ( destination operand ) and the second operand ( source operand )
 and stores the result in the destination operand . When an immediate value is used as
 an operand , it is sign - extended to the length of the destination operand format .
 The ADD instruction does not distinguish between signed or unsigned operands . Instead ,
 the processor evaluates the result for both data types and sets the OF and CF flags to
 indicate a carry in the signed or unsigned result , respectively . The SF flag indicates
 the sign of the signed result : :
 DEST = DEST + SRC ;
 : param cpu : current CPU .
 : param dest : destination operand .
 : param src : source operand ."""

implementation: cpu . _ADD ( dest , src , carry = False )


signature:
def CMP ( cpu , src1 , src2 ) :
    """Compares two operands .
 Compares the first source operand with the second source operand and sets the status flags
 in the EFLAGS register according to the results . The comparison is performed by subtracting
 the second operand from the first operand and then setting the status flags in the same manner
 as the SUB instruction . When an immediate value is used as an operand , it is sign - extended to
 the length of the first operand : :
 temp = SRC1 - SignExtend ( SRC2 ) ;
 ModifyStatusFlags ; ( * Modify status flags in the same manner as the SUB instruction * )
 The CF , OF , SF , ZF , AF , and PF flags are set according to the result .
 : param cpu : current CPU .
 : param dest : destination operand .
 : param src : source operand ."""

implementation:
arg0 = src1 . read ( )
arg1 = Operators . SEXTEND ( src2 . read ( ) , src2 . size , src1 . size )
# Affected Flags o . . szapc
cpu . _calculate_CMP_flags ( src1 . size , arg0 - arg1 , arg0 , arg1 )


signature:
def CMPXCHG ( cpu , dest , src ) :
    """Compares and exchanges .
 Compares the value in the AL , AX , EAX or RAX register ( depending on the
 size of the operand ) with the first operand ( destination operand ) . If
 the two values are equal , the second operand ( source operand ) is loaded
 into the destination operand . Otherwise , the destination operand is
 loaded into the AL , AX , EAX or RAX register .
 The ZF flag is set if the values in the destination operand and
 register AL , AX , or EAX are equal ; otherwise it is cleared . The CF , PF ,
 AF , SF , and OF flags are set according to the results of the comparison
 operation : :
 ( * accumulator = AL , AX , EAX or RAX , depending on whether * )
 ( * a byte , word , a doubleword or a 64bit comparison is being performed * )
 IF accumulator = = DEST
 THEN
 ZF = 1
 DEST = SRC
 ELSE
 ZF = 0
 accumulator = DEST
 FI ;
 : param cpu : current CPU .
 : param dest : destination operand .
 : param src : source operand ."""

implementation:
size = dest . size
reg_name = { 8 : 'AL' , 16 : 'AX' , 32 : 'EAX' , 64 : 'RAX' } [ size ]
accumulator = cpu . read_register ( reg_name )
sval = src . read ( )
dval = dest . read ( )
cpu . write_register ( reg_name , dval )
dest . write ( Operators . ITEBV ( size , accumulator == dval , sval , dval ) )
# Affected Flags o . . szapc
cpu . _calculate_CMP_flags ( size , accumulator - dval , accumulator , dval )


signature:
def CMPXCHG8B ( cpu , dest ) :
    """Compares and exchanges bytes .
 Compares the 64 - bit value in EDX : EAX ( or 128 - bit value in RDX : RAX if
 operand size is 128 bits ) with the operand ( destination operand ) . If
 the values are equal , the 64 - bit value in ECX : EBX ( or 128 - bit value in
 RCX : RBX ) is stored in the destination operand . Otherwise , the value in
 the destination operand is loaded into EDX : EAX ( or RDX : RAX ) : :
 IF ( 64 - Bit Mode and OperandSize = 64)
 THEN
 IF ( RDX : RAX = DEST )
 THEN
 ZF = 1;
 DEST = RCX : RBX ;
 ELSE
 ZF = 0;
 RDX : RAX = DEST ;
 FI
 ELSE
 IF ( EDX : EAX = DEST )
 THEN
 ZF = 1;
 DEST = ECX : EBX ;
 ELSE
 ZF = 0;
 EDX : EAX = DEST ;
 FI ;
 FI ;
 : param cpu : current CPU .
 : param dest : destination operand ."""

implementation:
size = dest . size
cmp_reg_name_l = { 64 : 'EAX' , 128 : 'RAX' } [ size ]
cmp_reg_name_h = { 64 : 'EDX' , 128 : 'RDX' } [ size ]
src_reg_name_l = { 64 : 'EBX' , 128 : 'RBX' } [ size ]
src_reg_name_h = { 64 : 'ECX' , 128 : 'RCX' } [ size ]
# EDX : EAX or RDX : RAX
cmph = cpu . read_register ( cmp_reg_name_h )
cmpl = cpu . read_register ( cmp_reg_name_l )
srch = cpu . read_register ( src_reg_name_h )
srcl = cpu . read_register ( src_reg_name_l )
cmp0 = Operators . CONCAT ( size , cmph , cmpl )
src0 = Operators . CONCAT ( size , srch , srcl )
arg_dest = dest . read ( )
cpu . ZF = arg_dest == cmp0
dest . write ( Operators . ITEBV ( size , cpu . ZF , Operators . CONCAT ( size , srch , srcl ) , arg_dest ) )
cpu . write_register ( cmp_reg_name_l , Operators . ITEBV ( size // 2 , cpu . ZF , cmpl , Operators . EXTRACT ( arg_dest , 0 , size // 2 ) ) )
cpu . write_register ( cmp_reg_name_h , Operators . ITEBV ( size // 2 , cpu . ZF , cmph , Operators . EXTRACT ( arg_dest , size // 2 , size // 2 ) ) )


signature:
def DIV ( cpu , src ) :
    """Unsigned divide .
 Divides ( unsigned ) the value in the AX register , DX : AX register pair ,
 or EDX : EAX or RDX : RAX register pair ( dividend ) by the source operand
 ( divisor ) and stores the result in the AX ( AH : AL ) , DX : AX , EDX : EAX or
 RDX : RAX registers . The source operand can be a general - purpose register
 or a memory location . The action of this instruction depends of the
 operand size ( dividend / divisor ) . Division using 64 - bit operand is
 available only in 64 - bit mode . Non - integral results are truncated
 ( chopped ) towards 0 . The reminder is always less than the divisor in
 magnitude . Overflow is indicated with the # DE ( divide error ) exception
 rather than with the CF flag : :
 IF SRC = 0
 THEN # DE ; FI ; ( * divide error * )
 IF OperandSize = 8 ( * word / byte operation * )
 THEN
 temp = AX / SRC ;
 IF temp > FFH
 THEN # DE ; ( * divide error * ) ;
 ELSE
 AL = temp ;
 AH = AX MOD SRC ;
 FI ;
 ELSE IF OperandSize = 16 ( * doubleword / word operation * )
 THEN
 temp = DX : AX / SRC ;
 IF temp > FFFFH
 THEN # DE ; ( * divide error * ) ;
 ELSE
 AX = temp ;
 DX = DX : AX MOD SRC ;
 FI ;
 FI ;
 ELSE If OperandSize = 32 ( * quadword / doubleword operation * )
 THEN
 temp = EDX : EAX / SRC ;
 IF temp > FFFFFH
 THEN # DE ; ( * divide error * ) ;
 ELSE
 EAX = temp ;
 EDX = EDX : EAX MOD SRC ;
 FI ;
 FI ;
 ELSE IF OperandSize = 64 ( * Doublequadword / quadword operation * )
 THEN
 temp = RDX : RAX / SRC ;
 IF temp > FFFFFH
 THEN # DE ; ( * Divide error * )
 ELSE
 RAX = temp ;
 RDX = RDX : RAX MOD SRC ;
 FI ;
 FI ;
 FI ;
 : param cpu : current CPU .
 : param src : source operand ."""

implementation:
size = src . size
reg_name_h = { 8 : 'DL' , 16 : 'DX' , 32 : 'EDX' , 64 : 'RDX' } [ size ]
reg_name_l = { 8 : 'AL' , 16 : 'AX' , 32 : 'EAX' , 64 : 'RAX' } [ size ]
dividend = Operators . CONCAT ( size * 2 , cpu . read_register ( reg_name_h ) , cpu . read_register ( reg_name_l ) )
divisor = Operators . ZEXTEND ( src . read ( ) , size * 2 )
# TODO make symbol friendly
if isinstance ( divisor , int ) and divisor == 0 :
    raise DivideByZeroError ( )
quotient = Operators . UDIV ( dividend , divisor )
MASK = ( 1 << size ) - 1
# TODO make symbol friendly
if isinstance ( quotient , int ) and quotient > MASK :
    raise DivideByZeroError ( )
remainder = Operators . UREM ( dividend , divisor )
cpu . write_register ( reg_name_l , Operators . EXTRACT ( quotient , 0 , size ) )
cpu . write_register ( reg_name_h , Operators . EXTRACT ( remainder , 0 , size ) )


signature:
def IDIV ( cpu , src ) :
    """Signed divide .
 Divides ( signed ) the value in the AL , AX , or EAX register by the source
 operand and stores the result in the AX , DX : AX , or EDX : EAX registers .
 The source operand can be a general - purpose register or a memory
 location . The action of this instruction depends on the operand size . : :
 IF SRC = 0
 THEN # DE ; ( * divide error * )
 FI ;
 IF OpernadSize = 8 ( * word / byte operation * )
 THEN
 temp = AX / SRC ; ( * signed division * )
 IF ( temp > 7FH ) Operators . OR ( temp < 80H )
 ( * if a positive result is greater than 7FH or a negative result is
 less than 80H * )
 THEN # DE ; ( * divide error * ) ;
 ELSE
 AL = temp ;
 AH = AX SignedModulus SRC ;
 FI ;
 ELSE
 IF OpernadSize = 16 ( * doubleword / word operation * )
 THEN
 temp = DX : AX / SRC ; ( * signed division * )
 IF ( temp > 7FFFH ) Operators . OR ( temp < 8000H )
 ( * if a positive result is greater than 7FFFH * )
 ( * or a negative result is less than 8000H * )
 THEN # DE ; ( * divide error * ) ;
 ELSE
 AX = temp ;
 DX = DX : AX SignedModulus SRC ;
 FI ;
 ELSE ( * quadword / doubleword operation * )
 temp = EDX : EAX / SRC ; ( * signed division * )
 IF ( temp > 7FFFFFH ) Operators . OR ( temp < 800000H )
 ( * if a positive result is greater than 7FFFFFH * )
 ( * or a negative result is less than 800000H * )
 THEN # DE ; ( * divide error * ) ;
 ELSE
 EAX = temp ;
 EDX = EDX : EAX SignedModulus SRC ;
 FI ;
 FI ;
 FI ;
 : param cpu : current CPU .
 : param src : source operand ."""

implementation:
reg_name_h = { 8 : 'AH' , 16 : 'DX' , 32 : 'EDX' , 64 : 'RDX' } [ src . size ]
reg_name_l = { 8 : 'AL' , 16 : 'AX' , 32 : 'EAX' , 64 : 'RAX' } [ src . size ]
dividend = Operators . CONCAT ( src . size * 2 , cpu . read_register ( reg_name_h ) , cpu . read_register ( reg_name_l ) )
divisor = src . read ( )
if isinstance ( divisor , int ) and divisor == 0 :
    raise DivideByZeroError ( )
dst_size = src . size * 2
divisor = Operators . SEXTEND ( divisor , src . size , dst_size )
mask = ( 1 << dst_size ) - 1
sign_mask = 1 << ( dst_size - 1 )
dividend_sign = ( dividend & sign_mask ) != 0
divisor_sign = ( divisor & sign_mask ) != 0
if isinstance ( divisor , int ) :
    if divisor_sign :
        divisor = ( ( ~ divisor ) + 1 ) & mask
        divisor = - divisor
if isinstance ( dividend , int ) :
    if dividend_sign :
        dividend = ( ( ~ dividend ) + 1 ) & mask
        dividend = - dividend
quotient = Operators . SDIV ( dividend , divisor )
if ( isinstance ( dividend , int ) and isinstance ( dividend , int ) ) : # handle the concrete case
    remainder = dividend - ( quotient * divisor )
else : # symbolic case - - optimize via SREM
    remainder = Operators . SREM ( dividend , divisor )
cpu . write_register ( reg_name_l , Operators . EXTRACT ( quotient , 0 , src . size ) )
cpu . write_register ( reg_name_h , Operators . EXTRACT ( remainder , 0 , src . size ) )


signature:
def IMUL ( cpu , * operands ) :
    """Signed multiply .
 Performs a signed multiplication of two operands . This instruction has
 three forms , depending on the number of operands .
 - One - operand form . This form is identical to that used by the MUL
 instruction . Here , the source operand ( in a general - purpose
 register or memory location ) is multiplied by the value in the AL ,
 AX , or EAX register ( depending on the operand size ) and the product
 is stored in the AX , DX : AX , or EDX : EAX registers , respectively .
 - Two - operand form . With this form the destination operand ( the
 first operand ) is multiplied by the source operand ( second
 operand ) . The destination operand is a general - purpose register and
 the source operand is an immediate value , a general - purpose
 register , or a memory location . The product is then stored in the
 destination operand location .
 - Three - operand form . This form requires a destination operand ( the
 first operand ) and two source operands ( the second and the third
 operands ) . Here , the first source operand ( which can be a
 general - purpose register or a memory location ) is multiplied by the
 second source operand ( an immediate value ) . The product is then
 stored in the destination operand ( a general - purpose register ) .
 When an immediate value is used as an operand , it is sign - extended to
 the length of the destination operand format . The CF and OF flags are
 set when significant bits are carried into the upper half of the
 result . The CF and OF flags are cleared when the result fits exactly in
 the lower half of the result . The three forms of the IMUL instruction
 are similar in that the length of the product is calculated to twice
 the length of the operands . With the one - operand form , the product is
 stored exactly in the destination . With the two - and three - operand
 forms , however , result is truncated to the length of the destination
 before it is stored in the destination register . Because of this
 truncation , the CF or OF flag should be tested to ensure that no
 significant bits are lost . The two - and three - operand forms may also be
 used with unsigned operands because the lower half of the product is
 the same regardless if the operands are signed or unsigned . The CF and
 OF flags , however , cannot be used to determine if the upper half of the
 result is non - zero : :
 IF ( NumberOfOperands = = 1)
 THEN
 IF ( OperandSize = = 8)
 THEN
 AX = AL * SRC ( * Signed multiplication * )
 IF AL = = AX
 THEN
 CF = 0 ; OF = 0;
 ELSE
 CF = 1 ; OF = 1;
 FI ;
 ELSE
 IF OperandSize = = 16
 THEN
 DX : AX = AX * SRC ( * Signed multiplication * )
 IF sign _ extend _ to _ 32 ( AX ) = = DX : AX
 THEN
 CF = 0 ; OF = 0;
 ELSE
 CF = 1 ; OF = 1;
 FI ;
 ELSE
 IF OperandSize = = 32
 THEN
 EDX : EAX = EAX * SRC ( * Signed multiplication * )
 IF EAX = = EDX : EAX
 THEN
 CF = 0 ; OF = 0;
 ELSE
 CF = 1 ; OF = 1;
 FI ;
 ELSE ( * OperandSize = 64 * )
 RDX : RAX = RAX * SRC ( * Signed multiplication * )
 IF RAX = = RDX : RAX
 THEN
 CF = 0 ; OF = 0;
 ELSE
 CF = 1 ; OF = 1;
 FI ;
 FI ;
 FI ;
 ELSE
 IF ( NumberOfOperands = 2)
 THEN
 temp = DEST * SRC ( * Signed multiplication ; temp is double DEST size * )
 DEST = DEST * SRC ( * Signed multiplication * )
 IF temp ! = DEST
 THEN
 CF = 1 ; OF = 1;
 ELSE
 CF = 0 ; OF = 0;
 FI ;
 ELSE ( * NumberOfOperands = 3 * )
 DEST = SRC1 * SRC2 ( * Signed multiplication * )
 temp = SRC1 * SRC2 ( * Signed multiplication ; temp is double SRC1 size * )
 IF temp ! = DEST
 THEN
 CF = 1 ; OF = 1;
 ELSE
 CF = 0 ; OF = 0;
 FI ;
 FI ;
 FI ;
 : param cpu : current CPU .
 : param operands : variable list of operands ."""

implementation:
dest = operands [ 0 ]
OperandSize = dest . size
reg_name_h = { 8 : 'AH' , 16 : 'DX' , 32 : 'EDX' , 64 : 'RDX' } [ OperandSize ]
reg_name_l = { 8 : 'AL' , 16 : 'AX' , 32 : 'EAX' , 64 : 'RAX' } [ OperandSize ]
arg0 = dest . read ( )
arg1 = None
arg2 = None
res = None
if len ( operands ) == 1 :
    arg1 = cpu . read_register ( reg_name_l )
    temp = ( Operators . SEXTEND ( arg0 , OperandSize , OperandSize * 2 ) * Operators . SEXTEND ( arg1 , OperandSize , OperandSize * 2 ) )
    temp = temp & ( ( 1 << ( OperandSize * 2 ) ) - 1 )
    cpu . write_register ( reg_name_l , Operators . EXTRACT ( temp , 0 , OperandSize ) )
    cpu . write_register ( reg_name_h , Operators . EXTRACT ( temp , OperandSize , OperandSize ) )
    res = Operators . EXTRACT ( temp , 0 , OperandSize )
elif len ( operands ) == 2 :
    arg1 = operands [ 1 ] . read ( )
    arg1 = Operators . SEXTEND ( arg1 , OperandSize , OperandSize * 2 )
    temp = Operators . SEXTEND ( arg0 , OperandSize , OperandSize * 2 ) * arg1
    temp = temp & ( ( 1 << ( OperandSize * 2 ) ) - 1 )
    res = dest . write ( Operators . EXTRACT ( temp , 0 , OperandSize ) )
else :
    arg1 = operands [ 1 ] . read ( )
    arg2 = operands [ 2 ] . read ( )
    temp = ( Operators . SEXTEND ( arg1 , OperandSize , OperandSize * 2 ) * Operators . SEXTEND ( arg2 , operands [ 2 ] . size , OperandSize * 2 ) )
    temp = temp & ( ( 1 << ( OperandSize * 2 ) ) - 1 )
    res = dest . write ( Operators . EXTRACT ( temp , 0 , OperandSize ) )
cpu . CF = ( Operators . SEXTEND ( res , OperandSize , OperandSize * 2 ) != temp )
cpu . OF = cpu . CF


signature:
def INC ( cpu , dest ) :
    """Increments by 1.
 Adds 1 to the destination operand , while preserving the state of the
 CF flag . The destination operand can be a register or a memory location .
 This instruction allows a loop counter to be updated without disturbing
 the CF flag . ( Use a ADD instruction with an immediate operand of 1 to
 perform an increment operation that does updates the CF flag . ) : :
 DEST = DEST + 1;
 : param cpu : current CPU .
 : param dest : destination operand ."""

implementation:
arg0 = dest . read ( )
res = dest . write ( arg0 + 1 )
res &= ( 1 << dest . size ) - 1
SIGN_MASK = 1 << ( dest . size - 1 )
cpu . AF = ( ( arg0 ^ 1 ) ^ res ) & 0x10 != 0
cpu . ZF = res == 0
cpu . SF = ( res & SIGN_MASK ) != 0
cpu . OF = res == SIGN_MASK
cpu . PF = cpu . _calculate_parity_flag ( res )


signature:
def MUL ( cpu , src ) :
    """Unsigned multiply .
 Performs an unsigned multiplication of the first operand ( destination
 operand ) and the second operand ( source operand ) and stores the result
 in the destination operand . The destination operand is an implied operand
 located in register AL , AX or EAX ( depending on the size of the operand ) ;
 the source operand is located in a general - purpose register or a memory location .
 The result is stored in register AX , register pair DX : AX , or register
 pair EDX : EAX ( depending on the operand size ) , with the high - order bits
 of the product contained in register AH , DX , or EDX , respectively . If
 the high - order bits of the product are 0 , the CF and OF flags are cleared ;
 otherwise , the flags are set : :
 IF byte operation
 THEN
 AX = AL * SRC
 ELSE ( * word or doubleword operation * )
 IF OperandSize = 16
 THEN
 DX : AX = AX * SRC
 ELSE ( * OperandSize = 32 * )
 EDX : EAX = EAX * SRC
 FI ;
 FI ;
 : param cpu : current CPU .
 : param src : source operand ."""

implementation:
size = src . size
reg_name_low , reg_name_high = { 8 : ( 'AL' , 'AH' ) , 16 : ( 'AX' , 'DX' ) , 32 : ( 'EAX' , 'EDX' ) , 64 : ( 'RAX' , 'RDX' ) } [ size ]
res = ( Operators . ZEXTEND ( cpu . read_register ( reg_name_low ) , 256 ) * Operators . ZEXTEND ( src . read ( ) , 256 ) )
cpu . write_register ( reg_name_low , Operators . EXTRACT ( res , 0 , size ) )
cpu . write_register ( reg_name_high , Operators . EXTRACT ( res , size , size ) )
cpu . OF = Operators . EXTRACT ( res , size , size ) != 0
cpu . CF = cpu . OF


signature:
def NEG ( cpu , dest ) :
    """Two ' s complement negation .
 Replaces the value of operand ( the destination operand ) with its two ' s complement .
 ( This operation is equivalent to subtracting the operand from 0 . ) The destination operand is
 located in a general - purpose register or a memory location : :
 IF DEST = 0
 THEN CF = 0
 ELSE CF = 1;
 FI ;
 DEST = - ( DEST )
 : param cpu : current CPU .
 : param dest : destination operand ."""

implementation:
source = dest . read ( )
res = dest . write ( - source )
cpu . _calculate_logic_flags ( dest . size , res )
cpu . CF = source != 0
cpu . AF = ( res & 0x0f ) != 0x00


signature:
def SBB ( cpu , dest , src ) :
    """Integer subtraction with borrow .
 Adds the source operand ( second operand ) and the carry ( CF ) flag , and
 subtracts the result from the destination operand ( first operand ) . The
 result of the subtraction is stored in the destination operand . The
 destination operand can be a register or a memory location ; the source
 operand can be an immediate , a register , or a memory location .
 ( However , two memory operands cannot be used in one instruction . ) The
 state of the CF flag represents a borrow from a previous subtraction .
 When an immediate value is used as an operand , it is sign - extended to
 the length of the destination operand format .
 The SBB instruction does not distinguish between signed or unsigned
 operands . Instead , the processor evaluates the result for both data
 types and sets the OF and CF flags to indicate a borrow in the signed
 or unsigned result , respectively . The SF flag indicates the sign of the
 signed result . The SBB instruction is usually executed as part of a
 multibyte or multiword subtraction in which a SUB instruction is
 followed by a SBB instruction : :
 DEST = DEST - ( SRC + CF ) ;
 : param cpu : current CPU .
 : param dest : destination operand .
 : param src : source operand ."""

implementation: cpu . _SUB ( dest , src , carry = True )


signature:
def SUB ( cpu , dest , src ) :
    """Subtract .
 Subtracts the second operand ( source operand ) from the first operand
 ( destination operand ) and stores the result in the destination operand .
 The destination operand can be a register or a memory location ; the
 source operand can be an immediate , register , or memory location .
 ( However , two memory operands cannot be used in one instruction . ) When
 an immediate value is used as an operand , it is sign - extended to the
 length of the destination operand format .
 The SUB instruction does not distinguish between signed or unsigned
 operands . Instead , the processor evaluates the result for both
 data types and sets the OF and CF flags to indicate a borrow in the
 signed or unsigned result , respectively . The SF flag indicates the sign
 of the signed result : :
 DEST = DEST - SRC ;
 : param cpu : current CPU .
 : param dest : destination operand .
 : param src : source operand ."""

implementation: cpu . _SUB ( dest , src , carry = False )


signature:
def XADD ( cpu , dest , src ) :
    """Exchanges and adds .
 Exchanges the first operand ( destination operand ) with the second operand
 ( source operand ) , then loads the sum of the two values into the destination
 operand . The destination operand can be a register or a memory location ;
 the source operand is a register .
 This instruction can be used with a LOCK prefix : :
 TEMP = SRC + DEST
 SRC = DEST
 DEST = TEMP
 : param cpu : current CPU .
 : param dest : destination operand .
 : param src : source operand ."""

implementation:
MASK = ( 1 << dest . size ) - 1
SIGN_MASK = 1 << ( dest . size - 1 )
arg0 = dest . read ( )
arg1 = src . read ( )
temp = ( arg1 + arg0 ) & MASK
src . write ( arg0 )
dest . write ( temp )
# Affected flags : oszapc
tempCF = Operators . OR ( Operators . ULT ( temp , arg0 ) , Operators . ULT ( temp , arg1 ) )
cpu . CF = tempCF
cpu . AF = ( ( arg0 ^ arg1 ) ^ temp ) & 0x10 != 0
cpu . ZF = temp == 0
cpu . SF = ( temp & SIGN_MASK ) != 0
cpu . OF = ( ( ( arg0 ^ arg1 ^ SIGN_MASK ) & ( temp ^ arg1 ) ) & SIGN_MASK ) != 0
cpu . PF = cpu . _calculate_parity_flag ( temp )


signature:
def BSWAP ( cpu , dest ) :
    """Byte swap .
 Reverses the byte order of a 32 - bit ( destination ) register : bits 0 through
 7 are swapped with bits 24 through 31 , and bits 8 through 15 are swapped
 with bits 16 through 23 . This instruction is provided for converting little - endian
 values to big - endian format and vice versa .
 To swap bytes in a word value ( 16 - bit register ) , use the XCHG instruction .
 When the BSWAP instruction references a 16 - bit register , the result is
 undefined : :
 TEMP = DEST
 DEST [ 7 . . 0 ] = TEMP [ 31 . . 24]
 DEST [ 15 . . 8 ] = TEMP [ 23 . . 16]
 DEST [ 23 . . 16 ] = TEMP [ 15 . . 8]
 DEST [ 31 . . 24 ] = TEMP [ 7 . . 0]
 : param cpu : current CPU .
 : param dest : destination operand ."""

implementation:
parts = [ ]
arg0 = dest . read ( )
for i in range ( 0 , dest . size , 8 ) :
    parts . append ( Operators . EXTRACT ( arg0 , i , 8 ) )
dest . write ( Operators . CONCAT ( 8 * len ( parts ) , * parts ) )


signature:
def CMOVB ( cpu , dest , src ) :
    """Conditional move - Below / not above or equal .
 Tests the status flags in the EFLAGS register and moves the source operand
 ( second operand ) to the destination operand ( first operand ) if the given
 test condition is true .
 : param cpu : current CPU .
 : param dest : destination operand .
 : param src : source operand ."""

implementation: dest . write ( Operators . ITEBV ( dest . size , cpu . CF , src . read ( ) , dest . read ( ) ) )


signature:
def CMOVA ( cpu , dest , src ) :
    """Conditional move - Above / not below or equal .
 Tests the status flags in the EFLAGS register and moves the source operand
 ( second operand ) to the destination operand ( first operand ) if the given
 test condition is true .
 : param cpu : current CPU .
 : param dest : destination operand .
 : param src : source operand ."""

implementation: dest . write ( Operators . ITEBV ( dest . size , Operators . AND ( cpu . CF == False , cpu . ZF == False ) , src . read ( ) , dest . read ( ) ) )


signature:
def CMOVAE ( cpu , dest , src ) :
    """Conditional move - Above or equal / not below .
 Tests the status flags in the EFLAGS register and moves the source operand
 ( second operand ) to the destination operand ( first operand ) if the given
 test condition is true .
 : param cpu : current CPU .
 : param dest : destination operand .
 : param src : source operand ."""

implementation: dest . write ( Operators . ITEBV ( dest . size , cpu . CF == False , src . read ( ) , dest . read ( ) ) )


signature:
def CMOVBE ( cpu , dest , src ) :
    """Conditional move - Below or equal / not above .
 Tests the status flags in the EFLAGS register and moves the source operand
 ( second operand ) to the destination operand ( first operand ) if the given
 test condition is true .
 : param cpu : current CPU .
 : param dest : destination operand .
 : param src : source operand ."""

implementation: dest . write ( Operators . ITEBV ( dest . size , Operators . OR ( cpu . CF , cpu . ZF ) , src . read ( ) , dest . read ( ) ) )


signature:
def CMOVZ ( cpu , dest , src ) :
    """Conditional move - Equal / zero .
 Tests the status flags in the EFLAGS register and moves the source operand
 ( second operand ) to the destination operand ( first operand ) if the given
 test condition is true .
 : param cpu : current CPU .
 : param dest : destination operand .
 : param src : source operand ."""

implementation: dest . write ( Operators . ITEBV ( dest . size , cpu . ZF , src . read ( ) , dest . read ( ) ) )


signature:
def CMOVNZ ( cpu , dest , src ) :
    """Conditional move - Not equal / not zero .
 Tests the status flags in the EFLAGS register and moves the source operand
 ( second operand ) to the destination operand ( first operand ) if the given
 test condition is true .
 : param cpu : current CPU .
 : param dest : destination operand .
 : param src : source operand ."""

implementation: dest . write ( Operators . ITEBV ( dest . size , cpu . ZF == False , src . read ( ) , dest . read ( ) ) )


signature:
def CMOVP ( cpu , dest , src ) :
    """Conditional move - Parity / parity even .
 Tests the status flags in the EFLAGS register and moves the source operand
 ( second operand ) to the destination operand ( first operand ) if the given
 test condition is true .
 : param cpu : current CPU .
 : param dest : destination operand .
 : param src : source operand ."""

implementation: dest . write ( Operators . ITEBV ( dest . size , cpu . PF , src . read ( ) , dest . read ( ) ) )


signature:
def CMOVNP ( cpu , dest , src ) :
    """Conditional move - Not parity / parity odd .
 Tests the status flags in the EFLAGS register and moves the source operand
 ( second operand ) to the destination operand ( first operand ) if the given
 test condition is true .
 : param cpu : current CPU .
 : param dest : destination operand .
 : param src : source operand ."""

implementation: dest . write ( Operators . ITEBV ( dest . size , cpu . PF == False , src . read ( ) , dest . read ( ) ) )


signature:
def CMOVG ( cpu , dest , src ) :
    """Conditional move - Greater .
 Tests the status flags in the EFLAGS register and moves the source operand
 ( second operand ) to the destination operand ( first operand ) if the given
 test condition is true .
 : param cpu : current CPU .
 : param dest : destination operand .
 : param src : source operand ."""

implementation: dest . write ( Operators . ITEBV ( dest . size , Operators . AND ( cpu . ZF == 0 , cpu . SF == cpu . OF ) , src . read ( ) , dest . read ( ) ) )


signature:
def CMOVGE ( cpu , dest , src ) :
    """Conditional move - Greater or equal / not less .
 Tests the status flags in the EFLAGS register and moves the source operand
 ( second operand ) to the destination operand ( first operand ) if the given
 test condition is true .
 : param cpu : current CPU .
 : param dest : destination operand .
 : param src : source operand ."""

implementation: dest . write ( Operators . ITEBV ( dest . size , ( cpu . SF ^ cpu . OF ) == 0 , src . read ( ) , dest . read ( ) ) )


signature:
def CMOVLE ( cpu , dest , src ) :
    """Conditional move - Less or equal / not greater .
 Tests the status flags in the EFLAGS register and moves the source operand
 ( second operand ) to the destination operand ( first operand ) if the given
 test condition is true .
 : param cpu : current CPU .
 : param dest : destination operand .
 : param src : source operand ."""

implementation: dest . write ( Operators . ITEBV ( dest . size , Operators . OR ( cpu . SF ^ cpu . OF , cpu . ZF ) , src . read ( ) , dest . read ( ) ) )


signature:
def CMOVO ( cpu , dest , src ) :
    """Conditional move - Overflow .
 Tests the status flags in the EFLAGS register and moves the source operand
 ( second operand ) to the destination operand ( first operand ) if the given
 test condition is true .
 : param cpu : current CPU .
 : param dest : destination operand .
 : param src : source operand ."""

implementation: dest . write ( Operators . ITEBV ( dest . size , cpu . OF , src . read ( ) , dest . read ( ) ) )