Example #1
0
def follow_jump(addr):
    # If 'addr' is immediately starting with another JMP instruction,
    # follow it now.  'addr' is an absolute address here
    while rffi.cast(rffi.CCHARP, addr)[0] == '\xE9':    # JMP <4 bytes>
        addr += 5
        addr += intmask(rffi.cast(rffi.INTP, addr - 4)[0])
    return addr
Example #2
0
def realize_global_int(ffi, g, gindex):
    fetch_fnptr = rffi.cast(FUNCPTR_FETCH_LONGLONG, g.c_address)
    with lltype.scoped_alloc(parse_c_type.GETCONST_S) as p_value:
        p_value.c_ctx = ffi.ctxobj.ctx
        rffi.setintfield(p_value, 'c_gindex', gindex)
        neg = fetch_fnptr(p_value)
        value = p_value.c_value
    neg = rffi.cast(lltype.Signed, neg)

    if neg == 0:     # positive
        if value <= rffi.cast(rffi.ULONGLONG, sys.maxint):
            return ffi.space.wrap(intmask(value))
        else:
            return ffi.space.wrap(value)
    elif neg == 1:   # negative
        value = rffi.cast(rffi.LONGLONG, value)
        if value >= -sys.maxint-1:
            return ffi.space.wrap(intmask(value))
        else:
            return ffi.space.wrap(value)

    if neg == 2:
        got = "%d (0x%x)" % (value, value)
    else:
        got = "%d" % (rffi.cast(rffi.LONGLONG, value),)
    raise oefmt(ffi.w_FFIError,
                "the C compiler says '%s' is equal to %s, "
                "but the cdef disagrees", rffi.charp2str(g.c_name), got)
Example #3
0
 def test_malloc_1(self):
     cpu = self.cpu
     sizeof = cpu.sizeof(self.S)
     sizeof.tid = 0
     size = sizeof.size
     loop = self.parse("""
     []
     p0 = call_malloc_nursery(%d)
     p1 = call_malloc_nursery(%d)
     p2 = call_malloc_nursery(%d) # this overflows
     guard_nonnull(p2, descr=faildescr) [p0, p1, p2]
     finish(p2, descr=finaldescr)
     """ % (size, size, size), namespace={'sizedescr': sizeof,
                     'finaldescr': BasicFinalDescr(),
                     'faildescr': BasicFailDescr()})
     token = JitCellToken()
     cpu.gc_ll_descr.collections = [[0, sizeof.size]]
     cpu.gc_ll_descr.init_nursery(2 * sizeof.size)
     cpu.setup_once()
     cpu.compile_loop(loop.inputargs, loop.operations, token)
     frame = cpu.execute_token(token)
     # now we should be able to track everything from the frame
     frame = lltype.cast_opaque_ptr(JITFRAMEPTR, frame)
     thing = frame.jf_frame[unpack_gcmap(frame)[0]]
     assert thing == rffi.cast(lltype.Signed, cpu.gc_ll_descr.nursery)
     assert cpu.gc_ll_descr.nursery_ptrs[0] == thing + sizeof.size
     assert rffi.cast(JITFRAMEPTR, cpu.gc_ll_descr.write_barrier_on_frame_called) == frame
Example #4
0
def convert_from_regdata(space, buf, buflen, typ):
    if typ == rwinreg.REG_DWORD:
        if not buflen:
            return space.wrap(0)
        d = rffi.cast(rwin32.LPDWORD, buf)[0]
        return space.wrap(d)

    elif typ == rwinreg.REG_SZ or typ == rwinreg.REG_EXPAND_SZ:
        if not buflen:
            return space.wrap("")
        s = rffi.charp2strn(rffi.cast(rffi.CCHARP, buf), buflen)
        return space.wrap(s)

    elif typ == rwinreg.REG_MULTI_SZ:
        if not buflen:
            return space.newlist([])
        i = 0
        l = []
        while i < buflen and buf[i]:
            s = []
            while i < buflen and buf[i] != '\0':
                s.append(buf[i])
                i += 1
            if len(s) == 0:
                break
            s = ''.join(s)
            l.append(space.wrap(s))
            i += 1
        return space.newlist(l)

    else: # REG_BINARY and all other types
        return space.wrap(rffi.charpsize2str(buf, buflen))
Example #5
0
File: ffi.py Project: kidaa/pixie
def ffi_prep_callback(tp, f):
    """(ffi-prep-callback callback-tp fn)
       Prepares a Pixie function for use as a c callback. callback-tp is a ffi callback type,
       fn is a pixie function (can be a closure, native fn or any object that implements -invoke.
       Returns a function pointer that can be passed to c and invoked as a callback."""
    affirm(isinstance(tp, CFunctionType), u"First argument to ffi-prep-callback must be a CFunctionType")
    raw_closure = rffi.cast(rffi.VOIDP, clibffi.closureHeap.alloc())

    if not we_are_translated():
        unique_id = id_generator.get_next()
    else:
        unique_id = rffi.cast(lltype.Signed, raw_closure)

    res = clibffi.c_ffi_prep_closure(rffi.cast(clibffi.FFI_CLOSUREP, raw_closure), tp.get_cd().cif,
                             invoke_callback,
                             rffi.cast(rffi.VOIDP, unique_id))


    if rffi.cast(lltype.Signed, res) != clibffi.FFI_OK:
        registered_callbacks[unique_id] = None
        runtime_error(u"libffi failed to build this callback")

    cb = CCallback(tp, raw_closure, unique_id, f)
    registered_callbacks[unique_id] = cb

    return cb
Example #6
0
    def test_SimpleNewFromData(self, space, api):
        shape = [10, 5, 3]
        nd = len(shape)

        s = iarray(space, [nd])
        ptr_s = rffi.cast(rffi.LONGP, api._PyArray_DATA(s))
        ptr_s[0] = 10
        ptr_s[1] = 5
        ptr_s[2] = 3

        a = array(space, shape)
        num = api._PyArray_TYPE(a)
        ptr_a = api._PyArray_DATA(a)

        x = rffi.cast(rffi.DOUBLEP, ptr_a)
        for i in range(150):
            x[i] = float(i)

        res = api._PyArray_SimpleNewFromData(nd, ptr_s, num, ptr_a)
        assert api._PyArray_TYPE(res) == num
        assert api._PyArray_DATA(res) == ptr_a
        for i in range(nd):
            assert api._PyArray_DIM(res, i) == shape[i]
        ptr_r = rffi.cast(rffi.DOUBLEP, api._PyArray_DATA(res))
        for i in range(150):
            assert ptr_r[i] == float(i)
        res = api._PyArray_SimpleNewFromDataOwning(nd, ptr_s, num, ptr_a)
        x = rffi.cast(rffi.DOUBLEP, ptr_a)
        ptr_r = rffi.cast(rffi.DOUBLEP, api._PyArray_DATA(res))
        x[20] = -100.
        assert ptr_r[20] == -100.
Example #7
0
 def test_malloc_nursery_varsize(self):
     self.cpu = self.getcpu(None)
     A = lltype.GcArray(lltype.Signed)
     arraydescr = self.cpu.arraydescrof(A)
     arraydescr.tid = 15
     ops = '''
     [i0, i1, i2]
     p0 = call_malloc_nursery_varsize(0, 8, i0, descr=arraydescr)
     p1 = call_malloc_nursery_varsize(0, 5, i1, descr=arraydescr)
     guard_false(i0) [p0, p1]
     '''
     self.interpret(ops, [1, 2, 3],
                    namespace={'arraydescr': arraydescr})
     # check the returned pointers
     gc_ll_descr = self.cpu.gc_ll_descr
     nurs_adr = rffi.cast(lltype.Signed, gc_ll_descr.nursery)
     ref = lambda n: self.cpu.get_ref_value(self.deadframe, n)
     assert rffi.cast(lltype.Signed, ref(0)) == nurs_adr + 0
     assert rffi.cast(lltype.Signed, ref(1)) == nurs_adr + 2*WORD + 8*1
     # check the nursery content and state
     assert gc_ll_descr.nursery[0] == chr(15)
     assert gc_ll_descr.nursery[2 * WORD + 8] == chr(15)
     assert gc_ll_descr.addrs[0] == nurs_adr + (((4 * WORD + 8*1 + 5*2) + (WORD - 1)) & ~(WORD - 1))
     # slowpath never called
     assert gc_ll_descr.calls == []
Example #8
0
    def chdir_llimpl(path):
        """This is a reimplementation of the C library's chdir function,
        but one that produces Win32 errors instead of DOS error codes.
        chdir is essentially a wrapper around SetCurrentDirectory; however,
        it also needs to set "magic" environment variables indicating
        the per-drive current directory, which are of the form =<drive>:
        """
        if not win32traits.SetCurrentDirectory(path):
            raise rwin32.lastWindowsError()
        MAX_PATH = rwin32.MAX_PATH
        assert MAX_PATH > 0

        with traits.scoped_alloc_buffer(MAX_PATH) as path:
            res = win32traits.GetCurrentDirectory(MAX_PATH + 1, path.raw)
            if not res:
                raise rwin32.lastWindowsError()
            res = rffi.cast(lltype.Signed, res)
            assert res > 0
            if res <= MAX_PATH + 1:
                new_path = path.str(res)
            else:
                with traits.scoped_alloc_buffer(res) as path:
                    res = win32traits.GetCurrentDirectory(res, path.raw)
                    if not res:
                        raise rwin32.lastWindowsError()
                    res = rffi.cast(lltype.Signed, res)
                    assert res > 0
                    new_path = path.str(res)
        if isUNC(new_path):
            return
        if not win32traits.SetEnvironmentVariable(magic_envvar(new_path), new_path):
            raise rwin32.lastWindowsError()
Example #9
0
def _PyTuple_Resize(space, p_ref, newsize):
    """Can be used to resize a tuple.  newsize will be the new length of the tuple.
    Because tuples are supposed to be immutable, this should only be used if there
    is only one reference to the object.  Do not use this if the tuple may already
    be known to some other part of the code.  The tuple will always grow or shrink
    at the end.  Think of this as destroying the old tuple and creating a new one,
    only more efficiently.  Returns 0 on success. Client code should never
    assume that the resulting value of *p will be the same as before calling
    this function. If the object referenced by *p is replaced, the original
    *p is destroyed.  On failure, returns -1 and sets *p to NULL, and
    raises MemoryError or SystemError."""
    ref = p_ref[0]
    if not tuple_check_ref(space, ref):
        PyErr_BadInternalCall(space)
    oldref = rffi.cast(PyTupleObject, ref)
    oldsize = oldref.c_ob_size
    p_ref[0] = new_empty_tuple(space, newsize)
    newref = rffi.cast(PyTupleObject, p_ref[0])
    try:
        if oldsize < newsize:
            to_cp = oldsize
        else:
            to_cp = newsize
        for i in range(to_cp):
            ob = oldref.c_ob_item[i]
            incref(space, ob)
            newref.c_ob_item[i] = ob
    except:
        decref(space, p_ref[0])
        p_ref[0] = lltype.nullptr(PyObject.TO)
        raise
    finally:
        decref(space, ref)
    return 0
Example #10
0
 def f(n):
     lst = ['a', 'b', 'c']
     lst = rgc.resizable_list_supporting_raw_ptr(lst)
     lst.append(chr(n))
     assert lst[3] == chr(n)
     assert lst[-1] == chr(n)
     #
     ptr = rgc.nonmoving_raw_ptr_for_resizable_list(lst)
     assert lst[:] == ['a', 'b', 'c', chr(n)]
     assert lltype.typeOf(ptr) == rffi.CCHARP
     assert [ptr[i] for i in range(4)] == ['a', 'b', 'c', chr(n)]
     #
     lst[-3] = 'X'
     assert ptr[1] == 'X'
     ptr[2] = 'Y'
     assert lst[-2] == 'Y'
     #
     addr = rffi.cast(lltype.Signed, ptr)
     ptr = rffi.cast(rffi.CCHARP, addr)
     rgc.collect()    # should not move lst.items
     lst[-4] = 'g'
     assert ptr[0] == 'g'
     ptr[3] = 'H'
     assert lst[-1] == 'H'
     return lst
Example #11
0
def op_raw_store(p, ofs, newvalue):
    from rpython.rtyper.lltypesystem import rffi

    p = rffi.cast(llmemory.Address, p)
    TVAL = lltype.typeOf(newvalue)
    p = rffi.cast(rffi.CArrayPtr(TVAL), p + ofs)
    p[0] = newvalue
Example #12
0
 def test_struct_fields(self):
     longsize = 4 if IS_32_BIT else 8
     POINT = lltype.Struct('POINT',
                           ('x', rffi.LONG),
                           ('y', rffi.SHORT),
                           ('z', rffi.VOIDP),
                           )
     y_ofs = longsize
     z_ofs = longsize*2
     p = lltype.malloc(POINT, flavor='raw')
     p.x = 42
     p.y = rffi.cast(rffi.SHORT, -1)
     p.z = rffi.cast(rffi.VOIDP, 0x1234)
     addr = rffi.cast(rffi.VOIDP, p)
     assert struct_getfield_int(types.slong, addr, 0) == 42
     assert struct_getfield_int(types.sshort, addr, y_ofs) == -1
     assert struct_getfield_int(types.pointer, addr, z_ofs) == 0x1234
     #
     struct_setfield_int(types.slong, addr, 0, 43)
     struct_setfield_int(types.sshort, addr, y_ofs, 0x1234FFFE) # 0x1234 is masked out
     struct_setfield_int(types.pointer, addr, z_ofs, 0x4321)
     assert p.x == 43
     assert p.y == -2
     assert rffi.cast(rffi.LONG, p.z) == 0x4321
     #
     lltype.free(p, flavor='raw')
Example #13
0
    def dcgettext(space, w_domain, msg, category):
        """dcgettext(domain, msg, category) -> string
        Return translation of msg in domain and category."""

        if space.is_w(w_domain, space.w_None):
            domain = None
            msg_c = rffi.str2charp(msg)
            try:
                result = _dcgettext(domain, msg_c, rffi.cast(rffi.INT, category))
                # note that 'result' may be the same pointer as 'msg_c',
                # so it must be converted to an RPython string *before*
                # we free msg_c.
                result = rffi.charp2str(result)
            finally:
                rffi.free_charp(msg_c)
        else:
            domain = space.str_w(w_domain)
            domain_c = rffi.str2charp(domain)
            msg_c = rffi.str2charp(msg)
            try:
                result = _dcgettext(domain_c, msg_c,
                                    rffi.cast(rffi.INT, category))
                # note that 'result' may be the same pointer as 'msg_c',
                # so it must be converted to an RPython string *before*
                # we free msg_c.
                result = rffi.charp2str(result)
            finally:
                rffi.free_charp(domain_c)
                rffi.free_charp(msg_c)

        return space.wrap(result)
Example #14
0
 def pypy_setup_home(ll_home, verbose):
     from pypy.module.sys.initpath import pypy_find_stdlib
     verbose = rffi.cast(lltype.Signed, verbose)
     if ll_home:
         home = rffi.charp2str(ll_home)
     else:
         home = pypydir
     w_path = pypy_find_stdlib(space, home)
     if space.is_none(w_path):
         if verbose:
             debug("Failed to find library based on pypy_find_stdlib")
         return rffi.cast(rffi.INT, 1)
     space.startup()
     space.call_function(w_pathsetter, w_path)
     # import site
     try:
         import_ = space.getattr(space.getbuiltinmodule('__builtin__'),
                                 space.wrap('__import__'))
         space.call_function(import_, space.wrap('site'))
         return rffi.cast(rffi.INT, 0)
     except OperationError, e:
         if verbose:
             debug("OperationError:")
             debug(" operror-type: " + e.w_type.getname(space))
             debug(" operror-value: " + space.str_w(space.str(e.get_w_value(space))))
         return rffi.cast(rffi.INT, -1)
 def pypy_setup_home(ll_home, verbose):
     from pypy.module.sys.initpath import pypy_find_stdlib
     verbose = rffi.cast(lltype.Signed, verbose)
     if ll_home:
         home1 = rffi.charp2str(ll_home)
         home = os.path.join(home1, 'x') # <- so that 'll_home' can be
                                         # directly the root directory
     else:
         home = home1 = pypydir
     w_path = pypy_find_stdlib(space, home)
     if space.is_none(w_path):
         if verbose:
             debug("pypy_setup_home: directories 'lib-python' and 'lib_pypy'"
                   " not found in '%s' or in any parent directory" % home1)
         return rffi.cast(rffi.INT, 1)
     space.startup()
     space.call_function(w_pathsetter, w_path)
     # import site
     try:
         space.setattr(space.getbuiltinmodule('sys'),
                       space.wrap('executable'),
                       space.wrap(home))
         import_ = space.getattr(space.getbuiltinmodule('__builtin__'),
                                 space.wrap('__import__'))
         space.call_function(import_, space.wrap('site'))
         return rffi.cast(rffi.INT, 0)
     except OperationError, e:
         if verbose:
             debug("OperationError:")
             debug(" operror-type: " + e.w_type.getname(space))
             debug(" operror-value: " + space.str_w(space.str(e.get_w_value(space))))
         return rffi.cast(rffi.INT, -1)
Example #16
0
def wrap_getbuffer(space, w_self, w_args, func):
    func_target = rffi.cast(getbufferproc, func)
    with lltype.scoped_alloc(Py_buffer) as pybuf:
        _flags = 0
        if space.len_w(w_args) > 0:
            _flags = space.int_w(space.listview(w_args)[0])
        flags = rffi.cast(rffi.INT_real,_flags)
        size = generic_cpy_call(space, func_target, w_self, pybuf, flags)
        if widen(size) < 0:
            space.fromcache(State).check_and_raise_exception(always=True)
        ptr = pybuf.c_buf
        size = pybuf.c_len
        ndim = widen(pybuf.c_ndim)
        shape =   [pybuf.c_shape[i]   for i in range(ndim)]
        if pybuf.c_strides:
            strides = [pybuf.c_strides[i] for i in range(ndim)]
        else:
            strides = [1]
        if pybuf.c_format:
            format = rffi.charp2str(pybuf.c_format)
        else:
            format = 'B'
        return space.newbuffer(CPyBuffer(ptr, size, w_self, format=format,
                            ndim=ndim, shape=shape, strides=strides,
                            itemsize=pybuf.c_itemsize,
                            readonly=widen(pybuf.c_readonly)))
Example #17
0
 def execute(self, space, cppmethod, cppthis, num_args, args):
     lresult = capi.c_call_l(space, cppmethod, cppthis, num_args, args)
     ccpresult = rffi.cast(rffi.CCHARP, lresult)
     if ccpresult == rffi.cast(rffi.CCHARP, 0):
         return space.wrap("")
     result = rffi.charp2str(ccpresult)   # TODO: make it a choice to free
     return space.wrap(result)
Example #18
0
def int_realize(space, obj):
    intval = rffi.cast(lltype.Signed, rffi.cast(PyIntObject, obj).c_ob_ival)
    w_type = from_ref(space, rffi.cast(PyObject, obj.c_ob_type))
    w_obj = space.allocate_instance(W_IntObject, w_type)
    w_obj.__init__(intval)
    track_reference(space, obj, w_obj)
    return w_obj
Example #19
0
def wrap_descr_delete(space, w_self, w_args, func):
    func_target = rffi.cast(descrsetfunc, func)
    check_num_args(space, w_args, 1)
    w_obj, = space.fixedview(w_args)
    res = generic_cpy_call(space, func_target, w_self, w_obj, None)
    if rffi.cast(lltype.Signed, res) == -1:
        space.fromcache(State).check_and_raise_exception(always=True)
Example #20
0
    def test_float_int32_casts(self):
        myjitdriver = JitDriver(greens = [], reds = 'auto', vectorize=True)
        def f(bytecount, va, vb, vc):
            i = 0
            j = 0
            while j < bytecount:
                myjitdriver.jit_merge_point()
                a = raw_storage_getitem(rffi.DOUBLE,va,j)
                b = raw_storage_getitem(rffi.INT,vb,i)
                c = a+rffi.cast(rffi.DOUBLE,b)
                raw_storage_setitem(vc, j, c)
                i += 4
                j += 8

        count = 32
        va = alloc_raw_storage(8*count, zero=True)
        vb = alloc_raw_storage(4*count, zero=True)
        for i,v in enumerate([1.0,2.0,3.0,4.0]*(count/4)):
            raw_storage_setitem(va, i*8, rffi.cast(rffi.DOUBLE,v))
        for i,v in enumerate([-1,-2,-3,-4]*(count/4)):
            raw_storage_setitem(vb, i*4, rffi.cast(rffi.INT,v))
        vc = alloc_raw_storage(8*count, zero=True)
        self.meta_interp(f, [8*count, va, vb, vc], vec=True)

        for i in range(count):
            assert raw_storage_getitem(rffi.DOUBLE,vc,i*8) == 0.0

        free_raw_storage(va)
        free_raw_storage(vb)
        free_raw_storage(vc)
Example #21
0
def detect_floatformat():
    from rpython.rtyper.lltypesystem import rffi, lltype
    buf = lltype.malloc(rffi.CCHARP.TO, 8, flavor='raw')
    rffi.cast(rffi.DOUBLEP, buf)[0] = 9006104071832581.0
    packed = rffi.charpsize2str(buf, 8)
    if packed == "\x43\x3f\xff\x01\x02\x03\x04\x05":
        double_format = 'IEEE, big-endian'
    elif packed == "\x05\x04\x03\x02\x01\xff\x3f\x43":
        double_format = 'IEEE, little-endian'
    else:
        double_format = 'unknown'
    lltype.free(buf, flavor='raw')
    #
    buf = lltype.malloc(rffi.CCHARP.TO, 4, flavor='raw')
    rffi.cast(rffi.FLOATP, buf)[0] = rarithmetic.r_singlefloat(16711938.0)
    packed = rffi.charpsize2str(buf, 4)
    if packed == "\x4b\x7f\x01\x02":
        float_format = 'IEEE, big-endian'
    elif packed == "\x02\x01\x7f\x4b":
        float_format = 'IEEE, little-endian'
    else:
        float_format = 'unknown'
    lltype.free(buf, flavor='raw')

    return double_format, float_format
Example #22
0
    def __init__(self, name, argtypes, restype, flags=FUNCFLAG_CDECL):
        self.name = name
        self.argtypes = argtypes
        self.restype = restype
        self.flags = flags
        argnum = len(argtypes)
        self.ll_argtypes = lltype.malloc(FFI_TYPE_PP.TO, argnum, flavor='raw',
                                         track_allocation=False) # freed by the __del__
        for i in range(argnum):
            self.ll_argtypes[i] = argtypes[i]
        self.ll_cif = lltype.malloc(FFI_CIFP.TO, flavor='raw',
                                    track_allocation=False) # freed by the __del__

        if _MSVC:
            # This little trick works correctly with MSVC.
            # It returns small structures in registers
            if intmask(restype.c_type) == FFI_TYPE_STRUCT:
                if restype.c_size <= 4:
                    restype = ffi_type_sint32
                elif restype.c_size <= 8:
                    restype = ffi_type_sint64

        res = c_ffi_prep_cif(self.ll_cif,
                             rffi.cast(rffi.USHORT, get_call_conv(flags,False)),
                             rffi.cast(rffi.UINT, argnum), restype,
                             self.ll_argtypes)
        if not res == FFI_OK:
            raise LibFFIError
Example #23
0
def push_arg_as_ffiptr(ffitp, arg, ll_buf):
    # This is for primitive types.  Note that the exact type of 'arg' may be
    # different from the expected 'c_size'.  To cope with that, we fall back
    # to a byte-by-byte copy.
    TP = lltype.typeOf(arg)
    TP_P = lltype.Ptr(rffi.CArray(TP))
    TP_size = rffi.sizeof(TP)
    c_size = intmask(ffitp.c_size)
    # if both types have the same size, we can directly write the
    # value to the buffer
    if c_size == TP_size:
        buf = rffi.cast(TP_P, ll_buf)
        buf[0] = arg
    else:
        # needs byte-by-byte copying.  Make sure 'arg' is an integer type.
        # Note that this won't work for rffi.FLOAT/rffi.DOUBLE.
        assert TP is not rffi.FLOAT and TP is not rffi.DOUBLE
        if TP_size <= rffi.sizeof(lltype.Signed):
            arg = rffi.cast(lltype.Unsigned, arg)
        else:
            arg = rffi.cast(lltype.UnsignedLongLong, arg)
        if _LITTLE_ENDIAN:
            for i in range(c_size):
                ll_buf[i] = chr(arg & 0xFF)
                arg >>= 8
        elif _BIG_ENDIAN:
            for i in range(c_size-1, -1, -1):
                ll_buf[i] = chr(arg & 0xFF)
                arg >>= 8
        else:
            raise AssertionError
Example #24
0
 def call(self, space, w_self, w_args, w_kw):
     func_to_call = self.func
     if self.offset:
         pto = as_pyobj(space, self.w_objclass)
         # make ptr the equivalent of this, using the offsets
         #func_to_call = rffi.cast(rffi.VOIDP, ptr.c_tp_as_number.c_nb_multiply)
         if pto:
             cptr = rffi.cast(rffi.CCHARP, pto)
             for o in self.offset:
                 ptr = rffi.cast(rffi.VOIDPP, rffi.ptradd(cptr, o))[0]
                 cptr = rffi.cast(rffi.CCHARP, ptr)
             func_to_call = rffi.cast(rffi.VOIDP, cptr)
         else:
             # Should never happen, assert to get a traceback
             assert False, "failed to convert w_type %s to PyObject" % str(
                                                           self.w_objclass)
     assert func_to_call
     if self.wrapper_func is None:
         assert self.wrapper_func_kwds is not None
         return self.wrapper_func_kwds(space, w_self, w_args, func_to_call,
                                       w_kw)
     if space.is_true(w_kw):
         raise oefmt(space.w_TypeError,
                     "wrapper %s doesn't take any keyword arguments",
                     self.method_name)
     return self.wrapper_func(space, w_self, w_args, func_to_call)
Example #25
0
def Py_FindMethod(space, table, w_obj, name_ptr):
    """Return a bound method object for an extension type implemented in
    C.  This can be useful in the implementation of a tp_getattro or
    tp_getattr handler that does not use the PyObject_GenericGetAttr()
    function.
    """
    # XXX handle __doc__

    name = rffi.charp2str(name_ptr)
    methods = rffi.cast(rffi.CArrayPtr(PyMethodDef), table)
    method_list_w = []

    if methods:
        i = -1
        while True:
            i = i + 1
            method = methods[i]
            if not method.c_ml_name:
                break
            if name == "__methods__":
                method_list_w.append(
                    space.wrap(rffi.charp2str(rffi.cast(rffi.CCHARP, method.c_ml_name))))
            elif rffi.charp2str(rffi.cast(rffi.CCHARP, method.c_ml_name)) == name: # XXX expensive copy
                return space.wrap(W_PyCFunctionObject(space, method, w_obj))
    if name == "__methods__":
        return space.newlist(method_list_w)
    raise OperationError(space.w_AttributeError, space.wrap(name))
Example #26
0
 def store_info_on_descr(self, startspos, guardtok):
     withfloats = False
     for box in guardtok.failargs:
         if box is not None and box.type == FLOAT:
             withfloats = True
             break
     exc = guardtok.exc
     target = self.failure_recovery_code[exc + 2 * withfloats]
     fail_descr = cast_instance_to_gcref(guardtok.faildescr)
     fail_descr = rffi.cast(lltype.Signed, fail_descr)
     base_ofs = self.cpu.get_baseofs_of_frame_field()
     positions = [rffi.cast(rffi.USHORT, 0)] * len(guardtok.fail_locs)
     for i, loc in enumerate(guardtok.fail_locs):
         if loc is None:
             position = 0xFFFF
         elif loc.is_stack():
             assert (loc.value & (WORD - 1)) == 0, \
                 "store_info_on_descr: misaligned"
             position = (loc.value - base_ofs) // WORD
             assert 0 < position < 0xFFFF, "store_info_on_descr: overflow!"
         else:
             assert loc is not self.cpu.frame_reg # for now
             if self.cpu.IS_64_BIT:
                 coeff = 1
             else:
                 coeff = 2
             if loc.is_float():
                 position = len(self.cpu.gen_regs) + loc.value * coeff
             else:
                 position = self.cpu.all_reg_indexes[loc.value]
         positions[i] = rffi.cast(rffi.USHORT, position)
     # write down the positions of locs
     guardtok.faildescr.rd_locs = positions
     return fail_descr, target
Example #27
0
def PyUnicode_GetSize(space, ref):
    if from_ref(space, rffi.cast(PyObject, ref.c_ob_type)) is space.w_unicode:
        ref = rffi.cast(PyUnicodeObject, ref)
        return ref.c_length
    else:
        w_obj = from_ref(space, ref)
        return space.len_w(w_obj)
Example #28
0
 def _more(self):
     chunk = rffi.cast(CLOSURES, alloc(CHUNK))
     count = CHUNK//rffi.sizeof(FFI_CLOSUREP.TO)
     for i in range(count):
         rffi.cast(rffi.VOIDPP, chunk)[0] = self.free_list
         self.free_list = rffi.cast(rffi.VOIDP, chunk)
         chunk = rffi.ptradd(chunk, 1)
Example #29
0
def gethost_common(hostname, hostent, addr=None):
    if not hostent:
        raise HSocketError(hostname)
    family = rffi.getintfield(hostent, 'c_h_addrtype')
    if addr is not None and addr.family != family:
        raise CSocketError(_c.EAFNOSUPPORT)

    h_aliases = hostent.c_h_aliases
    if h_aliases:   # h_aliases can be NULL, according to SF #1511317
        aliases = rffi.charpp2liststr(h_aliases)
    else:
        aliases = []

    address_list = []
    h_addr_list = hostent.c_h_addr_list
    i = 0
    paddr = h_addr_list[0]
    while paddr:
        if family == AF_INET:
            p = rffi.cast(lltype.Ptr(_c.in_addr), paddr)
            addr = INETAddress.from_in_addr(p)
        elif AF_INET6 is not None and family == AF_INET6:
            p = rffi.cast(lltype.Ptr(_c.in6_addr), paddr)
            addr = INET6Address.from_in6_addr(p)
        else:
            raise RSocketError("unknown address family")
        address_list.append(addr)
        i += 1
        paddr = h_addr_list[i]
    return (rffi.charp2str(hostent.c_h_name), aliases, address_list)
Example #30
0
    def _call(self, funcaddr, args_w):
        space = self.space
        cif_descr = self.cif_descr
        size = cif_descr.exchange_size
        mustfree_max_plus_1 = 0
        buffer = lltype.malloc(rffi.CCHARP.TO, size, flavor='raw')
        try:
            for i in range(len(args_w)):
                data = rffi.ptradd(buffer, cif_descr.exchange_args[i])
                w_obj = args_w[i]
                argtype = self.fargs[i]
                if argtype.convert_argument_from_object(data, w_obj):
                    # argtype is a pointer type, and w_obj a list/tuple/str
                    mustfree_max_plus_1 = i + 1

            jit_libffi.jit_ffi_call(cif_descr,
                                    rffi.cast(rffi.VOIDP, funcaddr),
                                    buffer)

            resultdata = rffi.ptradd(buffer, cif_descr.exchange_result)
            w_res = self.ctitem.copy_and_convert_to_object(resultdata)
        finally:
            for i in range(mustfree_max_plus_1):
                argtype = self.fargs[i]
                if isinstance(argtype, W_CTypePointer):
                    data = rffi.ptradd(buffer, cif_descr.exchange_args[i])
                    flag = get_mustfree_flag(data)
                    if flag == 1:
                        raw_cdata = rffi.cast(rffi.CCHARPP, data)[0]
                        lltype.free(raw_cdata, flavor='raw')
            lltype.free(buffer, flavor='raw')
            keepalive_until_here(args_w)
        return w_res
Example #31
0
File: ffi.py Project: mpenet/pixie
 def ffi_get_value(self, ptr):
     casted = rffi.cast(rffi.DOUBLEP, ptr)
     return Float(casted[0])
Example #32
0
File: ffi.py Project: mpenet/pixie
def invoke_callback(ffi_cif, ll_res, ll_args, ll_userdata):
    cb = registered_callbacks[rffi.cast(rffi.INT_real, ll_userdata)]
    cb.ll_invoke(ll_args, ll_res)
Example #33
0
File: ffi.py Project: mpenet/pixie
 def invoke(self, args):
     return CStruct(
         self,
         rffi.cast(rffi.VOIDP,
                   lltype.malloc(rffi.CCHARP.TO, self._size, flavor="raw")))
Example #34
0
File: ffi.py Project: mpenet/pixie
 def raw_data(self):
     return rffi.cast(rffi.VOIDP, self._raw_data)
Example #35
0
File: ffi.py Project: mpenet/pixie
 def ffi_get_value(self, ptr):
     casted = rffi.cast(rffi.VOIDPP, ptr)
     if casted[0] == lltype.nullptr(rffi.VOIDP.TO):
         return nil
     else:
         return VoidP(casted[0])
Example #36
0
File: ffi.py Project: mpenet/pixie
 def ffi_get_value(self, ptr):
     casted = rffi.cast(rffi.CCHARPP, ptr)
     if casted[0] == lltype.nullptr(rffi.CCHARP.TO):
         return nil
     else:
         return String(unicode(rffi.charp2str(casted[0])))
Example #37
0
File: ffi.py Project: mpenet/pixie
 def ffi_set_value(self, ptr, val):
     val = to_float(val)
     casted = rffi.cast(rffi.DOUBLEP, ptr)
     casted[0] = rffi.cast(rffi.DOUBLE, val.float_val())
Example #38
0
File: ffi.py Project: mpenet/pixie
 def ffi_set_value(self, ptr, val):
     casted = rffi.cast(rffi.INTP, ptr)
     casted[0] = rffi.cast(rffi.INT, val.int_val())
Example #39
0
File: ffi.py Project: mpenet/pixie
 def ffi_set_value(self, ptr, val):
     casted = rffi.cast(lltp, ptr)
     casted[0] = rffi.cast(llt, val.int_val())
Example #40
0
File: ffi.py Project: mpenet/pixie
 def ffi_set_value(self, ptr, val):
     val = to_float(val)
     casted = rffi.cast(rffi.FLOATP, ptr)
     casted[0] = rffi.cast(rffi.FLOAT, val.float_val())
Example #41
0
def jit_ffi_call_impl_singlefloat(cif_description, func_addr, exchange_buffer):
    jit_ffi_call_impl_any(cif_description, func_addr, exchange_buffer)
    resultdata = rffi.ptradd(exchange_buffer, cif_description.exchange_result)
    return rffi.cast(rffi.FLOATP, resultdata)[0]
Example #42
0
File: ffi.py Project: mpenet/pixie
 def ffi_get_value(self, ptr):
     casted = rffi.cast(rffi.INTP, ptr)
     return Integer(rffi.cast(rffi.LONG, casted[0]))
Example #43
0
def jit_ffi_call_impl_int(cif_description, func_addr, exchange_buffer):
    jit_ffi_call_impl_any(cif_description, func_addr, exchange_buffer)
    # read a complete 'ffi_arg' word
    resultdata = rffi.ptradd(exchange_buffer, cif_description.exchange_result)
    return rffi.cast(lltype.Signed, rffi.cast(FFI_ARG_P, resultdata)[0])
Example #44
0
def sort_gcmap(gcmapstart, gcmapend):
    count = (gcmapend - gcmapstart) // arrayitemsize
    qsort(gcmapstart,
          rffi.cast(rffi.SIZE_T, count),
          rffi.cast(rffi.SIZE_T, arrayitemsize),
          llhelper(QSORT_CALLBACK_PTR, _compare_gcmap_entries))
Example #45
0
 def descr_get_udata(self, space):
     return space.wrap(rffi.cast(rffi.UINTPTR_T, self.udata))
Example #46
0
def jit_ffi_call_impl_longlong(cif_description, func_addr, exchange_buffer):
    jit_ffi_call_impl_any(cif_description, func_addr, exchange_buffer)
    resultdata = rffi.ptradd(exchange_buffer, cif_description.exchange_result)
    return rffi.cast(rffi.LONGLONGP, resultdata)[0]
Example #47
0
def cfunction_dealloc(space, py_obj):
    py_func = rffi.cast(PyCFunctionObject, py_obj)
    decref(space, py_func.c_m_self)
    decref(space, py_func.c_m_module)
    from pypy.module.cpyext.object import _dealloc
    _dealloc(space, py_obj)
Example #48
0
 def free(self):
     if tracker.DO_TRACING:
         addr = rffi.cast(lltype.Signed, self.ll_callback.ll_closure)
         tracker.trace_free(addr)
     global_counter.remove(self.number)
Example #49
0
 def __init__(self, space, ml, w_self, w_module=None):
     self.ml = ml
     self.name = rffi.charp2str(rffi.cast(rffi.CCHARP, self.ml.c_ml_name))
     self.flags = rffi.cast(lltype.Signed, self.ml.c_ml_flags)
     self.w_self = w_self
     self.w_module = w_module
Example #50
0
    def _compare_all_fields(self, other, op):
        if IDENT_UINT:
            l_ident = rffi.cast(lltype.Unsigned, self.ident)
            r_ident = rffi.cast(lltype.Unsigned, other.ident)
        else:
            l_ident = self.ident
            r_ident = other.ident
        l_filter = rffi.cast(lltype.Signed, self.filter)
        r_filter = rffi.cast(lltype.Signed, other.filter)
        l_flags = rffi.cast(lltype.Unsigned, self.flags)
        r_flags = rffi.cast(lltype.Unsigned, other.flags)
        l_fflags = rffi.cast(lltype.Unsigned, self.fflags)
        r_fflags = rffi.cast(lltype.Unsigned, other.fflags)
        if IDENT_UINT:
            l_data = rffi.cast(lltype.Signed, self.data)
            r_data = rffi.cast(lltype.Signed, other.data)
        else:
            l_data = self.data
            r_data = other.data
        l_udata = rffi.cast(lltype.Unsigned, self.udata)
        r_udata = rffi.cast(lltype.Unsigned, other.udata)

        if op == "eq":
            return l_ident == r_ident and \
                   l_filter == r_filter and \
                   l_flags == r_flags and \
                   l_fflags == r_fflags and \
                   l_data == r_data and \
                   l_udata == r_udata
        elif op == "lt":
            return (l_ident < r_ident) or \
                   (l_ident == r_ident and l_filter < r_filter) or \
                   (l_ident == r_ident and l_filter == r_filter and l_flags < r_flags) or \
                   (l_ident == r_ident and l_filter == r_filter and l_flags == r_flags and l_fflags < r_fflags) or \
                   (l_ident == r_ident and l_filter == r_filter and l_flags == r_flags and l_fflags == r_fflags and l_data < r_data) or \
                   (l_ident == r_ident and l_filter == r_filter and l_flags == r_flags and l_fflags == r_fflags and l_data == r_data and l_udata < r_udata)
        elif op == "gt":
            return (l_ident > r_ident) or \
                   (l_ident == r_ident and l_filter > r_filter) or \
                   (l_ident == r_ident and l_filter == r_filter and l_flags > r_flags) or \
                   (l_ident == r_ident and l_filter == r_filter and l_flags == r_flags and l_fflags > r_fflags) or \
                   (l_ident == r_ident and l_filter == r_filter and l_flags == r_flags and l_fflags == r_fflags and l_data > r_data) or \
                   (l_ident == r_ident and l_filter == r_filter and l_flags == r_flags and l_fflags == r_fflags and l_data == r_data and l_udata > r_udata)
        else:
            assert False
Example #51
0
def _dump_nonneg_int(fd, i):
    pypy_faulthandler_write_uint(fd, rffi.cast(lltype.Unsigned, i),
                                 rffi.cast(rffi.INT, 1))
Example #52
0
def cfunction_attach(space, py_obj, w_obj, w_userdata=None):
    assert isinstance(w_obj, W_PyCFunctionObject)
    py_func = rffi.cast(PyCFunctionObject, py_obj)
    py_func.c_m_ml = w_obj.ml
    py_func.c_m_self = make_ref(space, w_obj.w_self)
    py_func.c_m_module = make_ref(space, w_obj.w_module)
Example #53
0
 def fromaddress(self, space, addr):
     self.check_complete(space)
     rawmem = rffi.cast(rffi.VOIDP, addr)
     return W__StructInstance(self, allocate=False, autofree=True, rawmem=rawmem)
def foreach_index(ll_d):
    indexes = get_indexes(ll_d)
    for i in range(len(indexes)):
        yield rffi.cast(lltype.Signed, indexes[i])
Example #55
0
 def get_unichar(self, w_ffitype):
     intval = libffi.struct_getfield_int(w_ffitype.get_ffitype(),
                                         self.rawmem, self.offset)
     return rffi.cast(rffi.WCHAR_T, intval)
Example #56
0
def sort_gcmap(gcmapstart, gcmapend):
    count = (gcmapend - gcmapstart) // arrayitemsize
    qsort(gcmapstart, rffi.cast(rffi.SIZE_T, count),
          rffi.cast(rffi.SIZE_T, arrayitemsize), c_compare_gcmap_entries)
Example #57
0
 def next_opcode(self):
     return rffi.cast(_CFFI_OPCODE_T, self.next_4bytes())
Example #58
0
 def handle_struct(self, w_ffitype, w_structinstance):
     rawmem = rffi.cast(rffi.CCHARP, self.rawmem)
     dst = rffi.cast(rffi.VOIDP, rffi.ptradd(rawmem, self.offset))
     src = w_structinstance.rawmem
     length = w_ffitype.sizeof()
     rffi.c_memcpy(dst, src, length)
Example #59
0
 def _finalize_(self):
     h = self.libhandle
     if h != rffi.cast(DLLHANDLE, 0):
         self.libhandle = rffi.cast(DLLHANDLE, 0)
         dlclose(h)
Example #60
0
 def getaddr(self, space):
     addr = rffi.cast(rffi.ULONG, self.rawmem)
     return space.wrap(addr)