Пример #1
0
 def _base_do_setfield(self, gcref, vbox, fielddescr):
     ofs, size, ptr, float = self.unpack_fielddescr(fielddescr)
     #
     if ptr:
         assert lltype.typeOf(gcref) is not lltype.Signed, (
             "can't handle write barriers for setfield_raw")
         ptr = vbox.getref_base()
         self.gc_ll_descr.do_write_barrier(gcref, ptr)
         # --- start of GC unsafe code (no GC operation!) ---
         field = rffi.ptradd(rffi.cast(rffi.CCHARP, gcref), ofs)
         field = rffi.cast(rffi.CArrayPtr(lltype.Signed), field)
         field[0] = self.cast_gcref_to_int(ptr)
         # --- end of GC unsafe code ---
         return
     #
     if float:
         fval = vbox.getfloat()
         # --- start of GC unsafe code (no GC operation!) ---
         field = rffi.ptradd(rffi.cast(rffi.CCHARP, gcref), ofs)
         field = rffi.cast(rffi.CArrayPtr(lltype.Float), field)
         field[0] = fval
         # --- end of GC unsafe code ---
         return
     #
     val = vbox.getint()
     for TYPE, itemsize in unroll_basic_sizes:
         if size == itemsize:
             # --- start of GC unsafe code (no GC operation!) ---
             field = rffi.ptradd(rffi.cast(rffi.CCHARP, gcref), ofs)
             field = rffi.cast(rffi.CArrayPtr(TYPE), field)
             field[0] = rffi.cast(TYPE, val)
             # --- end of GC unsafe code ---
             return
     else:
         raise NotImplementedError("size = %d" % size)
Пример #2
0
 def do_setarrayitem_gc(self, arraybox, indexbox, vbox, arraydescr):
     itemindex = indexbox.getint()
     gcref = arraybox.getref_base()
     ofs, size, ptr, float = self.unpack_arraydescr(arraydescr)
     #
     if ptr:
         vboxptr = vbox.getref_base()
         self.gc_ll_descr.do_write_barrier(gcref, vboxptr)
         # --- start of GC unsafe code (no GC operation!) ---
         items = rffi.ptradd(rffi.cast(rffi.CCHARP, gcref), ofs)
         items = rffi.cast(rffi.CArrayPtr(lltype.Signed), items)
         items[itemindex] = self.cast_gcref_to_int(vboxptr)
         # --- end of GC unsafe code ---
         return
     #
     if float:
         fval = vbox.getfloat()
         # --- start of GC unsafe code (no GC operation!) ---
         items = rffi.ptradd(rffi.cast(rffi.CCHARP, gcref), ofs)
         items = rffi.cast(rffi.CArrayPtr(lltype.Float), items)
         items[itemindex] = fval
         # --- end of GC unsafe code ---
         return
     #
     val = vbox.getint()
     for TYPE, itemsize in unroll_basic_sizes:
         if size == itemsize:
             # --- start of GC unsafe code (no GC operation!) ---
             items = rffi.ptradd(rffi.cast(rffi.CCHARP, gcref), ofs)
             items = rffi.cast(rffi.CArrayPtr(TYPE), items)
             items[itemindex] = rffi.cast(TYPE, val)
             # --- end of GC unsafe code ---
             return
     else:
         raise NotImplementedError("size = %d" % size)
Пример #3
0
def test_image_pixels():
    for filename in ["demo.jpg", "demo.png"]:
        image = RIMG.Load(os.path.join(autopath.this_dir, filename))
        assert image
        assert rffi.getintfield(image.c_format, 'c_BytesPerPixel') in (3, 4)
        RSDL.LockSurface(image)
        result = {}
        try:
            rgb = lltype.malloc(rffi.CArray(RSDL.Uint8), 3, flavor='raw')
            try:
                for y in range(23):
                    for x in range(y % 13, 17, 13):
                        color = RSDL_helper.get_pixel(image, x, y)
                        RSDL.GetRGB(color, image.c_format, rffi.ptradd(rgb, 0),
                                    rffi.ptradd(rgb, 1), rffi.ptradd(rgb, 2))
                        r = rffi.cast(lltype.Signed, rgb[0])
                        g = rffi.cast(lltype.Signed, rgb[1])
                        b = rffi.cast(lltype.Signed, rgb[2])
                        result[x, y] = r, g, b
            finally:
                lltype.free(rgb, flavor='raw')
        finally:
            RSDL.UnlockSurface(image)
        RSDL.FreeSurface(image)
        for x, y in result:
            f = (x * 17 + y * 23) / float(17 * 17 + 23 * 23)
            expected_r = int(255.0 * (1.0 - f))
            expected_g = 0
            expected_b = int(255.0 * f)
            r, g, b = result[x, y]
            assert abs(r - expected_r) < 10
            assert abs(g - expected_g) < 10
            assert abs(b - expected_b) < 10
Пример #4
0
 def _base_do_setfield(self, gcref, vbox, fielddescr):
     ofs, size, ptr, float = self.unpack_fielddescr(fielddescr)
     #
     if ptr:
         assert lltype.typeOf(gcref) is not lltype.Signed, (
             "can't handle write barriers for setfield_raw")
         ptr = vbox.getref_base()
         self.gc_ll_descr.do_write_barrier(gcref, ptr)
         # --- start of GC unsafe code (no GC operation!) ---
         field = rffi.ptradd(rffi.cast(rffi.CCHARP, gcref), ofs)
         field = rffi.cast(rffi.CArrayPtr(lltype.Signed), field)
         field[0] = self.cast_gcref_to_int(ptr)
         # --- end of GC unsafe code ---
         return
     #
     if float:
         fval = vbox.getfloat()
         # --- start of GC unsafe code (no GC operation!) ---
         field = rffi.ptradd(rffi.cast(rffi.CCHARP, gcref), ofs)
         field = rffi.cast(rffi.CArrayPtr(lltype.Float), field)
         field[0] = fval
         # --- end of GC unsafe code ---
         return
     #
     val = vbox.getint()
     for TYPE, itemsize in unroll_basic_sizes:
         if size == itemsize:
             # --- start of GC unsafe code (no GC operation!) ---
             field = rffi.ptradd(rffi.cast(rffi.CCHARP, gcref), ofs)
             field = rffi.cast(rffi.CArrayPtr(TYPE), field)
             field[0] = rffi.cast(TYPE, val)
             # --- end of GC unsafe code ---
             return
     else:
         raise NotImplementedError("size = %d" % size)
Пример #5
0
 def do_setarrayitem_gc(self, arraybox, indexbox, vbox, arraydescr):
     itemindex = indexbox.getint()
     gcref = arraybox.getref_base()
     ofs, size, ptr, float = self.unpack_arraydescr(arraydescr)
     #
     if ptr:
         vboxptr = vbox.getref_base()
         self.gc_ll_descr.do_write_barrier(gcref, vboxptr)
         # --- start of GC unsafe code (no GC operation!) ---
         items = rffi.ptradd(rffi.cast(rffi.CCHARP, gcref), ofs)
         items = rffi.cast(rffi.CArrayPtr(lltype.Signed), items)
         items[itemindex] = self.cast_gcref_to_int(vboxptr)
         # --- end of GC unsafe code ---
         return
     #
     if float:
         fval = vbox.getfloat()
         # --- start of GC unsafe code (no GC operation!) ---
         items = rffi.ptradd(rffi.cast(rffi.CCHARP, gcref), ofs)
         items = rffi.cast(rffi.CArrayPtr(lltype.Float), items)
         items[itemindex] = fval
         # --- end of GC unsafe code ---
         return
     #
     val = vbox.getint()
     for TYPE, itemsize in unroll_basic_sizes:
         if size == itemsize:
             # --- start of GC unsafe code (no GC operation!) ---
             items = rffi.ptradd(rffi.cast(rffi.CCHARP, gcref), ofs)
             items = rffi.cast(rffi.CArrayPtr(TYPE), items)
             items[itemindex] = rffi.cast(TYPE, val)
             # --- end of GC unsafe code ---
             return
     else:
         raise NotImplementedError("size = %d" % size)
Пример #6
0
def array_getitem(ffitype, width, addr, index, offset):
    for TYPE, ffitype2 in clibffi.ffitype_map:
        if ffitype is ffitype2:
            addr = rffi.ptradd(addr, index * width)
            addr = rffi.ptradd(addr, offset)
            return rffi.cast(rffi.CArrayPtr(TYPE), addr)[0]
    assert False
Пример #7
0
        def get_indices(w_start, w_stop, w_step, length):
            w_slice = space.newslice(w_start, w_stop, w_step)
            values = lltype.malloc(Py_ssize_tP.TO, 3, flavor='raw')

            res = api.PySlice_GetIndices(w_slice, 100, values,
                                         rffi.ptradd(values, 1),
                                         rffi.ptradd(values, 2))
            assert res == 0
            rv = values[0], values[1], values[2]
            lltype.free(values, flavor='raw')
            return rv
Пример #8
0
 def get_indices(w_start, w_stop, w_step, length):
     w_slice = space.newslice(w_start, w_stop, w_step)
     values = lltype.malloc(Py_ssize_tP.TO, 3, flavor='raw')
     
     res = api.PySlice_GetIndices(w_slice, 100, values, 
         rffi.ptradd(values, 1), 
         rffi.ptradd(values, 2))
     assert res == 0
     rv = values[0], values[1], values[2]
     lltype.free(values, flavor='raw')
     return rv
Пример #9
0
def get_rgb(color, format):
    rgb = lltype.malloc(rffi.CArray(RSDL.Uint8), 3, flavor='raw')
    try:
        RSDL.GetRGB(color, format, rffi.ptradd(rgb, 0), rffi.ptradd(rgb, 1),
                    rffi.ptradd(rgb, 2))
        r = rffi.cast(lltype.Signed, rgb[0])
        g = rffi.cast(lltype.Signed, rgb[1])
        b = rffi.cast(lltype.Signed, rgb[2])
        result = r, g, b
    finally:
        lltype.free(rgb, flavor='raw')

    return result
Пример #10
0
def set_pixel(image, x, y, pixel):
    """Return the pixel value at (x, y)
    NOTE: The surface must be locked before calling this!
    """
    bpp = rffi.getintfield(image.c_format, 'c_BytesPerPixel')
    pitch = rffi.getintfield(image, 'c_pitch')
    # Here p is the address to the pixel we want to retrieve
    p = rffi.ptradd(image.c_pixels, y * pitch + x * bpp)
    if bpp == 1:
        p[0] = rffi.cast(rffi.UCHAR,pixel)
    elif bpp == 2:
        p = rffi.cast(RSDL.Uint16P, p)
        p[0] = rffi.cast(RSDL.Uint16,pixel) 
    elif bpp == 3:
        if RSDL.BYTEORDER == RSDL.BIG_ENDIAN:
            p[0] = rffi.cast(rffi.UCHAR,(pixel >> 16) & 0xFF)
            p[1] = rffi.cast(rffi.UCHAR,(pixel >> 8 ) & 0xFF)
            p[2] = rffi.cast(rffi.UCHAR,pixel & 0xFF)
        else:
            p[0] = rffi.cast(rffi.UCHAR,pixel & 0xFF)
            p[1] = rffi.cast(rffi.UCHAR,(pixel >> 8 ) & 0xFF)
            p[2] = rffi.cast(rffi.UCHAR,(pixel >> 16) & 0xFF)
    elif bpp == 4:
        p = rffi.cast(RSDL.Uint32P, p)
        p[0] = rffi.cast(RSDL.Uint32, pixel)
    else:
        raise ValueError("bad BytesPerPixel")
Пример #11
0
def get_pixel(image, x, y):
    """Return the pixel value at (x, y)
    NOTE: The surface must be locked before calling this!
    """
    bpp = rffi.getintfield(image.c_format, 'c_BytesPerPixel')
    pitch = rffi.getintfield(image, 'c_pitch')
    # Here p is the address to the pixel we want to retrieve
    p = rffi.ptradd(image.c_pixels, y * pitch + x * bpp)
    if bpp == 1:
        return rffi.cast(RSDL.Uint32, p[0])
    elif bpp == 2:
        p = rffi.cast(RSDL.Uint16P, p)
        return rffi.cast(RSDL.Uint32, p[0])
    elif bpp == 3:
        p0 = rffi.cast(lltype.Signed, p[0])
        p1 = rffi.cast(lltype.Signed, p[1])
        p2 = rffi.cast(lltype.Signed, p[2])
        if RSDL.BYTEORDER == RSDL.BIG_ENDIAN:
            result = p0 << 16 | p1 << 8 | p2
        else:
            result = p0 | p1 << 8 | p2 << 16
        return rffi.cast(RSDL.Uint32, result)
    elif bpp == 4:
        p = rffi.cast(RSDL.Uint32P, p)
        return p[0]
    else:
        raise ValueError("bad BytesPerPixel")
Пример #12
0
def get_rgb(color, format):
    rgb = lltype.malloc(rffi.CArray(RSDL.Uint8), 3, flavor='raw')
    try:
        RSDL.GetRGB(color,
                    format,
                    rffi.ptradd(rgb, 0),
                    rffi.ptradd(rgb, 1),
                    rffi.ptradd(rgb, 2))
        r = rffi.cast(lltype.Signed, rgb[0])
        g = rffi.cast(lltype.Signed, rgb[1])
        b = rffi.cast(lltype.Signed, rgb[2])
        result = r, g, b
    finally:
        lltype.free(rgb, flavor='raw')

    return result
Пример #13
0
def set_pixel(image, x, y, pixel):
    """Return the pixel value at (x, y)
    NOTE: The surface must be locked before calling this!
    """
    bpp = rffi.getintfield(image.c_format, 'c_BytesPerPixel')
    pitch = rffi.getintfield(image, 'c_pitch')
    # Here p is the address to the pixel we want to retrieve
    p = rffi.ptradd(image.c_pixels, y * pitch + x * bpp)
    if bpp == 1:
        p[0] = rffi.cast(rffi.UCHAR, pixel)
    elif bpp == 2:
        p = rffi.cast(RSDL.Uint16P, p)
        p[0] = rffi.cast(RSDL.Uint16, pixel)
    elif bpp == 3:
        if RSDL.BYTEORDER == RSDL.BIG_ENDIAN:
            p[0] = rffi.cast(rffi.UCHAR, (pixel >> 16) & 0xFF)
            p[1] = rffi.cast(rffi.UCHAR, (pixel >> 8) & 0xFF)
            p[2] = rffi.cast(rffi.UCHAR, pixel & 0xFF)
        else:
            p[0] = rffi.cast(rffi.UCHAR, pixel & 0xFF)
            p[1] = rffi.cast(rffi.UCHAR, (pixel >> 8) & 0xFF)
            p[2] = rffi.cast(rffi.UCHAR, (pixel >> 16) & 0xFF)
    elif bpp == 4:
        p = rffi.cast(RSDL.Uint32P, p)
        p[0] = rffi.cast(RSDL.Uint32, pixel)
    else:
        raise ValueError("bad BytesPerPixel")
Пример #14
0
def get_pixel(image, x, y):
    """Return the pixel value at (x, y)
    NOTE: The surface must be locked before calling this!
    """
    bpp = rffi.getintfield(image.c_format, 'c_BytesPerPixel')
    pitch = rffi.getintfield(image, 'c_pitch')
    # Here p is the address to the pixel we want to retrieve
    p = rffi.ptradd(image.c_pixels, y * pitch + x * bpp)
    if bpp == 1:
        return rffi.cast(RSDL.Uint32, p[0])
    elif bpp == 2:
        p = rffi.cast(RSDL.Uint16P, p)
        return rffi.cast(RSDL.Uint32, p[0])
    elif bpp == 3:
        p0 = rffi.cast(lltype.Signed, p[0])
        p1 = rffi.cast(lltype.Signed, p[1])
        p2 = rffi.cast(lltype.Signed, p[2])
        if RSDL.BYTEORDER == RSDL.BIG_ENDIAN:
            result = p0 << 16 | p1 << 8 | p2
        else:
            result = p0 | p1 << 8 | p2 << 16
        return rffi.cast(RSDL.Uint32, result)
    elif bpp == 4:
        p = rffi.cast(RSDL.Uint32P, p)
        return p[0]
    else:
        raise ValueError("bad BytesPerPixel")
Пример #15
0
 def test_freelist(self):
     S = lltype.Struct('S', ('x', lltype.Signed), ('y', lltype.Signed))
     SP = lltype.Ptr(S)
     chunk = lltype.malloc(rffi.CArrayPtr(S).TO, 10, flavor='raw')
     assert lltype.typeOf(chunk) == rffi.CArrayPtr(S)
     free_list = lltype.nullptr(rffi.VOIDP.TO)
     # build list
     current = chunk
     for i in range(10):
         rffi.cast(rffi.VOIDPP, current)[0] = free_list
         free_list = rffi.cast(rffi.VOIDP, current)
         current = rffi.ptradd(current, 1)
     # get one
     p = free_list
     free_list = rffi.cast(rffi.VOIDPP, p)[0]
     rffi.cast(SP, p).x = 0
     # get two
     p = free_list
     free_list = rffi.cast(rffi.VOIDPP, p)[0]
     rffi.cast(SP, p).x = 0
     # get three
     p = free_list
     free_list = rffi.cast(rffi.VOIDPP, p)[0]
     rffi.cast(SP, p).x = 0
     lltype.free(chunk, flavor='raw')
Пример #16
0
    def test_cdll_life_time(self):
        from pypy.translator.tool.cbuild import ExternalCompilationInfo
        from pypy.translator.platform import platform
        from pypy.tool.udir import udir

        c_file = udir.ensure("test_libffi", dir=1).join("xlib.c")
        c_file.write(
            py.code.Source('''
        long fun(long i) {
            return i + 42;
        }
        '''))
        eci = ExternalCompilationInfo(export_symbols=['fun'])
        lib_name = str(platform.compile([c_file], eci, 'x', standalone=False))

        lib = CDLL(lib_name)
        slong = cast_type_to_ffitype(rffi.LONG)
        fun = lib.getrawpointer('fun', [slong], slong)
        del lib  # already delete here

        buffer = lltype.malloc(rffi.LONGP.TO, 2, flavor='raw')
        buffer[0] = 200
        buffer[1] = -1
        fun.call([rffi.cast(rffi.VOIDP, buffer)],
                 rffi.cast(rffi.VOIDP, rffi.ptradd(buffer, 1)))
        assert buffer[1] == 242

        lltype.free(buffer, flavor='raw')
        del fun

        assert not ALLOCATED
Пример #17
0
 def do_getarrayitem_gc(self, arraybox, indexbox, arraydescr):
     itemindex = indexbox.getint()
     gcref = arraybox.getref_base()
     ofs, size, ptr, float = self.unpack_arraydescr(arraydescr)
     # --- start of GC unsafe code (no GC operation!) ---
     items = rffi.ptradd(rffi.cast(rffi.CCHARP, gcref), ofs)
     #
     if ptr:
         items = rffi.cast(rffi.CArrayPtr(lltype.Signed), items)
         pval = self._cast_int_to_gcref(items[itemindex])
         # --- end of GC unsafe code ---
         return BoxPtr(pval)
     #
     if float:
         items = rffi.cast(rffi.CArrayPtr(lltype.Float), items)
         fval = items[itemindex]
         # --- end of GC unsafe code ---
         return BoxFloat(fval)
     #
     for TYPE, itemsize in unroll_basic_sizes:
         if size == itemsize:
             items = rffi.cast(rffi.CArrayPtr(TYPE), items)
             val = items[itemindex]
             # --- end of GC unsafe code ---
             return BoxInt(rffi.cast(lltype.Signed, val))
     else:
         raise NotImplementedError("size = %d" % size)
Пример #18
0
 def bh_setarrayitem_gc_r(self, arraydescr, gcref, itemindex, newvalue):
     ofs = self.unpack_arraydescr(arraydescr)
     self.gc_ll_descr.do_write_barrier(gcref, newvalue)
     # --- start of GC unsafe code (no GC operation!) ---
     items = rffi.ptradd(rffi.cast(rffi.CCHARP, gcref), ofs)
     items = rffi.cast(rffi.CArrayPtr(lltype.Signed), items)
     items[itemindex] = self.cast_gcref_to_int(newvalue)
Пример #19
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)
Пример #20
0
 def _base_do_getfield_f(self, struct, fielddescr):
     ofs = self.unpack_fielddescr(fielddescr)
     # --- start of GC unsafe code (no GC operation!) ---
     fieldptr = rffi.ptradd(rffi.cast(rffi.CCHARP, struct), ofs)
     fval = rffi.cast(rffi.CArrayPtr(longlong.FLOATSTORAGE), fieldptr)[0]
     # --- end of GC unsafe code ---
     return fval
Пример #21
0
 def bh_setarrayitem_gc_r(self, arraydescr, gcref, itemindex, newvalue):
     ofs = self.unpack_arraydescr(arraydescr)
     self.gc_ll_descr.do_write_barrier(gcref, newvalue)
     # --- start of GC unsafe code (no GC operation!) ---
     items = rffi.ptradd(rffi.cast(rffi.CCHARP, gcref), ofs)
     items = rffi.cast(rffi.CArrayPtr(lltype.Signed), items)
     items[itemindex] = self.cast_gcref_to_int(newvalue)
Пример #22
0
    def test_cdll_life_time(self):
        from pypy.translator.tool.cbuild import ExternalCompilationInfo
        from pypy.translator.platform import platform
        from pypy.tool.udir import udir

        c_file = udir.ensure("test_libffi", dir=1).join("xlib.c")
        c_file.write(
            py.code.Source(
                """
        long fun(long i) {
            return i + 42;
        }
        """
            )
        )
        eci = ExternalCompilationInfo(export_symbols=["fun"])
        lib_name = str(platform.compile([c_file], eci, "x", standalone=False))

        lib = CDLL(lib_name)
        slong = cast_type_to_ffitype(rffi.LONG)
        fun = lib.getrawpointer("fun", [slong], slong)
        del lib  # already delete here

        buffer = lltype.malloc(rffi.LONGP.TO, 2, flavor="raw")
        buffer[0] = 200
        buffer[1] = -1
        fun.call([rffi.cast(rffi.VOIDP, buffer)], rffi.cast(rffi.VOIDP, rffi.ptradd(buffer, 1)))
        assert buffer[1] == 242

        lltype.free(buffer, flavor="raw")
        del fun

        assert not ALLOCATED
Пример #23
0
 def _base_do_getfield_f(self, struct, fielddescr):
     ofs = self.unpack_fielddescr(fielddescr)
     # --- start of GC unsafe code (no GC operation!) ---
     fieldptr = rffi.ptradd(rffi.cast(rffi.CCHARP, struct), ofs)
     fval = rffi.cast(rffi.CArrayPtr(longlong.FLOATSTORAGE), fieldptr)[0]
     # --- end of GC unsafe code ---
     return fval
Пример #24
0
 def test_rawfuncptr(self):
     libm = self.get_libm()
     pow = libm.getrawpointer("pow", [ffi_type_double, ffi_type_double], ffi_type_double)
     buffer = lltype.malloc(rffi.DOUBLEP.TO, 3, flavor="raw")
     buffer[0] = 2.0
     buffer[1] = 3.0
     buffer[2] = 43.5
     pow.call(
         [rffi.cast(rffi.VOIDP, buffer), rffi.cast(rffi.VOIDP, rffi.ptradd(buffer, 1))],
         rffi.cast(rffi.VOIDP, rffi.ptradd(buffer, 2)),
     )
     assert buffer[2] == 8.0
     lltype.free(buffer, flavor="raw")
     del pow
     del libm
     assert not ALLOCATED
Пример #25
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)
Пример #26
0
 def do_getarrayitem_gc(self, arraybox, indexbox, arraydescr):
     itemindex = indexbox.getint()
     gcref = arraybox.getref_base()
     ofs, size, ptr, float = self.unpack_arraydescr(arraydescr)
     # --- start of GC unsafe code (no GC operation!) ---
     items = rffi.ptradd(rffi.cast(rffi.CCHARP, gcref), ofs)
     #
     if ptr:
         items = rffi.cast(rffi.CArrayPtr(lltype.Signed), items)
         pval = self._cast_int_to_gcref(items[itemindex])
         # --- end of GC unsafe code ---
         return BoxPtr(pval)
     #
     if float:
         items = rffi.cast(rffi.CArrayPtr(lltype.Float), items)
         fval = items[itemindex]
         # --- end of GC unsafe code ---
         return BoxFloat(fval)
     #
     for TYPE, itemsize in unroll_basic_sizes:
         if size == itemsize:
             items = rffi.cast(rffi.CArrayPtr(TYPE), items) 
             val = items[itemindex]
             # --- end of GC unsafe code ---
             return BoxInt(rffi.cast(lltype.Signed, val))
     else:
         raise NotImplementedError("size = %d" % size)
Пример #27
0
 def get_struct(self, w_ffitype, w_structdescr):
     assert isinstance(w_structdescr, W__StructDescr)
     rawmem = rffi.cast(rffi.CCHARP, self.rawmem)
     innermem = rffi.cast(rffi.VOIDP, rffi.ptradd(rawmem, self.offset))
     # we return a reference to the inner struct, not a copy
     # autofree=False because it's still owned by the parent struct
     return W__StructInstance(w_structdescr, allocate=False, autofree=False,
                              rawmem=innermem)
Пример #28
0
 def _base_do_getfield_r(self, struct, fielddescr):
     ofs = self.unpack_fielddescr(fielddescr)
     # --- start of GC unsafe code (no GC operation!) ---
     fieldptr = rffi.ptradd(rffi.cast(rffi.CCHARP, struct), ofs)
     pval = rffi.cast(rffi.CArrayPtr(lltype.Signed), fieldptr)[0]
     pval = self._cast_int_to_gcref(pval)
     # --- end of GC unsafe code ---
     return pval
Пример #29
0
 def test_rawfuncptr(self):
     libm = CDLL('libm.so')
     pow = libm.getrawpointer('pow', [ffi_type_double, ffi_type_double],
                              ffi_type_double)
     buffer = lltype.malloc(rffi.DOUBLEP.TO, 3, flavor='raw')
     buffer[0] = 2.0
     buffer[1] = 3.0
     buffer[2] = 43.5
     pow.call([
         rffi.cast(rffi.VOIDP, buffer),
         rffi.cast(rffi.VOIDP, rffi.ptradd(buffer, 1))
     ], rffi.cast(rffi.VOIDP, rffi.ptradd(buffer, 2)))
     assert buffer[2] == 8.0
     lltype.free(buffer, flavor='raw')
     del pow
     del libm
     assert not ALLOCATED
Пример #30
0
 def bh_getarrayitem_gc_r(self, arraydescr, gcref, itemindex):
     ofs = self.unpack_arraydescr(arraydescr)
     # --- start of GC unsafe code (no GC operation!) ---
     items = rffi.ptradd(rffi.cast(rffi.CCHARP, gcref), ofs)
     items = rffi.cast(rffi.CArrayPtr(lltype.Signed), items)
     pval = self._cast_int_to_gcref(items[itemindex])
     # --- end of GC unsafe code ---
     return pval
Пример #31
0
 def get_struct(self, w_ffitype, w_structdescr):
     assert isinstance(w_structdescr, W__StructDescr)
     rawmem = rffi.cast(rffi.CCHARP, self.rawmem)
     innermem = rffi.cast(rffi.VOIDP, rffi.ptradd(rawmem, self.offset))
     # we return a reference to the inner struct, not a copy
     # autofree=False because it's still owned by the parent struct
     return W__StructInstance(w_structdescr, allocate=False, autofree=False,
                              rawmem=innermem)
Пример #32
0
 def bh_getarrayitem_gc_f(self, arraydescr, gcref, itemindex):
     ofs = self.unpack_arraydescr(arraydescr)
     # --- start of GC unsafe code (no GC operation!) ---
     items = rffi.ptradd(rffi.cast(rffi.CCHARP, gcref), ofs)
     items = rffi.cast(rffi.CArrayPtr(longlong.FLOATSTORAGE), items)
     fval = items[itemindex]
     # --- end of GC unsafe code ---
     return fval
Пример #33
0
 def _base_do_getfield_r(self, struct, fielddescr):
     ofs = self.unpack_fielddescr(fielddescr)
     # --- start of GC unsafe code (no GC operation!) ---
     fieldptr = rffi.ptradd(rffi.cast(rffi.CCHARP, struct), ofs)
     pval = rffi.cast(rffi.CArrayPtr(lltype.Signed), fieldptr)[0]
     pval = self._cast_int_to_gcref(pval)
     # --- end of GC unsafe code ---
     return pval
Пример #34
0
def _struct_getfield(TYPE, addr, offset):
    """
    Read the field of type TYPE at addr+offset.
    addr is of type rffi.VOIDP, offset is an int.
    """
    addr = rffi.ptradd(addr, offset)
    PTR_FIELD = lltype.Ptr(rffi.CArray(TYPE))
    return rffi.cast(PTR_FIELD, addr)[0]
Пример #35
0
 def bh_getarrayitem_gc_f(self, arraydescr, gcref, itemindex):
     ofs = self.unpack_arraydescr(arraydescr)
     # --- start of GC unsafe code (no GC operation!) ---
     items = rffi.ptradd(rffi.cast(rffi.CCHARP, gcref), ofs)
     items = rffi.cast(rffi.CArrayPtr(longlong.FLOATSTORAGE), items)
     fval = items[itemindex]
     # --- end of GC unsafe code ---
     return fval
Пример #36
0
 def bh_getarrayitem_gc_r(self, arraydescr, gcref, itemindex):
     ofs = self.unpack_arraydescr(arraydescr)
     # --- start of GC unsafe code (no GC operation!) ---
     items = rffi.ptradd(rffi.cast(rffi.CCHARP, gcref), ofs)
     items = rffi.cast(rffi.CArrayPtr(lltype.Signed), items)
     pval = self._cast_int_to_gcref(items[itemindex])
     # --- end of GC unsafe code ---
     return pval
Пример #37
0
def _struct_setfield(TYPE, addr, offset, value):
    """
    Write the field of type TYPE at addr+offset.
    addr is of type rffi.VOIDP, offset is an int.
    """
    addr = rffi.ptradd(addr, offset)
    PTR_FIELD = lltype.Ptr(rffi.CArray(TYPE))
    rffi.cast(PTR_FIELD, addr)[0] = value
Пример #38
0
def mk_mod(vm, bc, mod_off):
    mod_size = read_word(bc, mod_off + BC_MOD_SIZE)
    assert mod_off >= 0 and mod_size >= 0

    mod_bc = rffi.ptradd(bc, mod_off)

    name = _extract_sstr(mod_bc, BC_MOD_NAME, BC_MOD_NAME_SIZE)
    id_ = _extract_sstr(mod_bc, BC_MOD_ID, BC_MOD_ID_SIZE)
    src_path = _extract_sstr(mod_bc, BC_MOD_SRC_PATH, BC_MOD_SRC_PATH_SIZE)

    imps = []
    j = read_word(mod_bc, BC_MOD_IMPORTS)
    for k in range(read_word(mod_bc, BC_MOD_NUM_IMPORTS)):
        assert j > 0
        imp_size = read_word(mod_bc, j)
        assert imp_size > 0
        j += INTSIZE
        imps.append(rffi.charpsize2str(rffi.ptradd(mod_bc, j), imp_size))
        j += align(imp_size)
        j += INTSIZE + align(read_word(mod_bc, j))

    num_vars = read_word(mod_bc, BC_MOD_NUM_TL_VARS_MAP)
    tlvars_map = {}
    j = read_word(mod_bc, BC_MOD_TL_VARS_MAP)
    for k in range(num_vars):
        assert j > 0
        var_num = read_word(mod_bc, j)
        j += INTSIZE
        tlvar_size = read_word(mod_bc, j)
        assert tlvar_size > 0
        j += INTSIZE
        n = rffi.charpsize2str(rffi.ptradd(mod_bc, j), tlvar_size)
        tlvars_map[n] = var_num
        j += align(tlvar_size)

    num_consts = read_word(mod_bc, BC_MOD_NUM_CONSTANTS)

    mod = Builtins.new_bc_con_module(vm, mod_bc, name, id_, src_path, imps, tlvars_map, num_consts)
    init_func_off = read_word(mod_bc, BC_MOD_INSTRUCTIONS)
    pc = BC_PC(mod, init_func_off)
    max_stack_size = 512 # XXX!
    mod.init_func = Builtins.Con_Func(vm, Builtins.Con_String(vm, "$$init$$"), False, pc, \
      max_stack_size, 0, num_vars, mod, None)
    
    return mod
Пример #39
0
 def _base_do_setfield_r(self, struct, fielddescr, newvalue):
     ofs = self.unpack_fielddescr(fielddescr)
     assert lltype.typeOf(struct) is not lltype.Signed, (
         "can't handle write barriers for setfield_raw")
     self.gc_ll_descr.do_write_barrier(struct, newvalue)
     # --- start of GC unsafe code (no GC operation!) ---
     fieldptr = rffi.ptradd(rffi.cast(rffi.CCHARP, struct), ofs)
     fieldptr = rffi.cast(rffi.CArrayPtr(lltype.Signed), fieldptr)
     fieldptr[0] = self.cast_gcref_to_int(newvalue)
Пример #40
0
 def _base_do_setfield_r(self, struct, fielddescr, newvalue):
     ofs = self.unpack_fielddescr(fielddescr)
     assert lltype.typeOf(struct) is not lltype.Signed, (
         "can't handle write barriers for setfield_raw")
     self.gc_ll_descr.do_write_barrier(struct, newvalue)
     # --- start of GC unsafe code (no GC operation!) ---
     fieldptr = rffi.ptradd(rffi.cast(rffi.CCHARP, struct), ofs)
     fieldptr = rffi.cast(rffi.CArrayPtr(lltype.Signed), fieldptr)
     fieldptr[0] = self.cast_gcref_to_int(newvalue)
Пример #41
0
    def test_struct_by_val(self):
        import platform
        if platform.machine() == 'x86_64':
            py.test.skip("Segfaults on x86_64 because small structures "
                         "may be passed in registers and "
                         "c_elements must not be null")
        from pypy.translator.tool.cbuild import ExternalCompilationInfo
        from pypy.translator.platform import platform
        from pypy.tool.udir import udir

        c_file = udir.ensure("test_libffi", dir=1).join("xlib.c")
        c_file.write(
            py.code.Source('''
        #include <stdlib.h>
        #include <stdio.h>

        struct x_y {
            long x;
            long y;
        };

        long sum_x_y(struct x_y s) {
            return s.x + s.y;
        }

        long sum_x_y_p(struct x_y *p) {
            return p->x + p->y;
        }
        
        '''))
        eci = ExternalCompilationInfo(export_symbols=['sum_x_y'])
        lib_name = str(platform.compile([c_file], eci, 'x', standalone=False))

        lib = CDLL(lib_name)

        slong = cast_type_to_ffitype(rffi.LONG)
        size = slong.c_size * 2
        alignment = slong.c_alignment
        tp = make_struct_ffitype(size, alignment)

        sum_x_y = lib.getrawpointer('sum_x_y', [tp], slong)

        buffer = lltype.malloc(rffi.LONGP.TO, 3, flavor='raw')
        buffer[0] = 200
        buffer[1] = 220
        buffer[2] = 666
        sum_x_y.call([rffi.cast(rffi.VOIDP, buffer)],
                     rffi.cast(rffi.VOIDP, rffi.ptradd(buffer, 2)))
        assert buffer[2] == 420

        lltype.free(buffer, flavor='raw')
        del sum_x_y
        lltype.free(tp, flavor='raw')
        del lib

        assert not ALLOCATED
Пример #42
0
 def llf():
     data = "hello, world!"
     a = malloc(ARRAY_OF_CHAR, len(data), flavor='raw')
     for i in xrange(len(data)):
         a[i] = data[i]
     a2 = rffi.ptradd(a, 2)
     assert typeOf(a2) == typeOf(a) == Ptr(ARRAY_OF_CHAR)
     for i in xrange(len(data) - 2):
         assert a2[i] == a[i + 2]
     free(a, flavor='raw')
Пример #43
0
 def _sendall(self, space, message, size):
     while size > 0:
         # XXX inefficient
         data = rffi.charpsize2str(message, size)
         try:
             count = self.WRITE(data)
         except OSError, e:
             raise wrap_oserror(space, e)
         size -= count
         message = rffi.ptradd(message, count)
Пример #44
0
 def _sendall(self, space, message, size):
     while size > 0:
         # XXX inefficient
         data = rffi.charpsize2str(message, size)
         try:
             count = self.WRITE(data)
         except OSError, e:
             raise wrap_oserror(space, e)
         size -= count
         message = rffi.ptradd(message, count)
Пример #45
0
def SetNamedPipeHandleState(space, w_handle, w_pipemode, w_maxinstances, w_timeout):
    handle = handle_w(space, w_handle)
    state = lltype.malloc(rffi.CArrayPtr(rffi.UINT).TO, 3, flavor='raw')
    statep = lltype.malloc(rffi.CArrayPtr(rffi.UINTP).TO, 3, flavor='raw', zero=True)
    try:
        if not space.is_w(w_pipemode, space.w_None):
            state[0] = space.uint_w(w_pipemode)
            statep[0] = rffi.ptradd(state, 0)
        if not space.is_w(w_maxinstances, space.w_None):
            state[1] = space.uint_w(w_maxinstances)
            statep[1] = rffi.ptradd(state, 1)
        if not space.is_w(w_timeout, space.w_None):
            state[2] = space.uint_w(w_timeout)
            statep[2] = rffi.ptradd(state, 2)
        if not _SetNamedPipeHandleState(handle, statep[0], statep[1], statep[2]):
            raise wrap_windowserror(space, rwin32.lastWindowsError())
    finally:
        lltype.free(state, flavor='raw')
        lltype.free(statep, flavor='raw')
Пример #46
0
 def llf():
     data = "hello, world!"
     a = malloc(ARRAY_OF_CHAR, len(data), flavor='raw')
     for i in xrange(len(data)):
         a[i] = data[i]
     a2 = rffi.ptradd(a, 2)
     assert typeOf(a2) == typeOf(a) == Ptr(ARRAY_OF_CHAR)
     for i in xrange(len(data) - 2):
         assert a2[i] == a[i + 2]
     free(a, flavor='raw')
Пример #47
0
def Array_get_slice(vm):
    mod = vm.get_funcs_mod()
    (self, i_o, j_o),_ = vm.decode_args("!", opt="ii", self_of=Array)
    assert isinstance(self, Array)

    i, j = translate_slice_idx_objs(vm, i_o, j_o, self.num_entries)
    # This does a double allocation, so isn't very efficient. It is pleasingly simple though.
    data = rffi.charpsize2str(rffi.ptradd(self.data, i * self.type_size), int((j - i) * self.type_size))
    objectmodel.keepalive_until_here(self)
    return Array(vm, mod.get_defn(vm, "Array"), self.type_name, Con_String(vm, data))
Пример #48
0
 def bh_setinteriorfield_gc_f(self, gcref, itemindex, descr, newvalue):
     assert isinstance(descr, InteriorFieldDescr)
     arraydescr = descr.arraydescr
     ofs, size, _ = self.unpack_arraydescr_size(arraydescr)
     ofs += descr.fielddescr.offset
     # --- start of GC unsafe code (no GC operation!) ---
     items = rffi.ptradd(rffi.cast(rffi.CCHARP, gcref),
                         ofs + size * itemindex)
     items = rffi.cast(rffi.CArrayPtr(longlong.FLOATSTORAGE), items)
     items[0] = newvalue
Пример #49
0
 def _fast_setslice(self, space, w_value):
     assert isinstance(w_value, ConcreteArray)
     itemsize = self.dtype.itemtype.get_element_size()
     shapelen = len(self.shape)
     if shapelen == 1:
         rffi.c_memcpy(
             rffi.ptradd(self.storage, self.start * itemsize),
             rffi.ptradd(w_value.storage, w_value.start * itemsize),
             self.size * itemsize)
     else:
         dest = SkipLastAxisIterator(self)
         source = SkipLastAxisIterator(w_value)
         while not dest.done:
             rffi.c_memcpy(
                 rffi.ptradd(self.storage, dest.offset * itemsize),
                 rffi.ptradd(w_value.storage, source.offset * itemsize),
                 self.shape[-1] * itemsize)
             source.next()
             dest.next()
Пример #50
0
    def test_struct_by_val(self):
        import platform
        if platform.machine() == 'x86_64':
            py.test.skip("Segfaults on x86_64 because small structures "
                         "may be passed in registers and "
                         "c_elements must not be null")
        from pypy.translator.tool.cbuild import ExternalCompilationInfo
        from pypy.translator.platform import platform
        from pypy.tool.udir import udir

        c_file = udir.ensure("test_libffi", dir=1).join("xlib.c")
        c_file.write(py.code.Source('''
        #include <stdlib.h>
        #include <stdio.h>

        struct x_y {
            long x;
            long y;
        };

        long sum_x_y(struct x_y s) {
            return s.x + s.y;
        }

        long sum_x_y_p(struct x_y *p) {
            return p->x + p->y;
        }
        
        '''))
        eci = ExternalCompilationInfo(export_symbols=['sum_x_y'])
        lib_name = str(platform.compile([c_file], eci, 'x', standalone=False))

        lib = CDLL(lib_name)

        slong = cast_type_to_ffitype(rffi.LONG)
        size = slong.c_size*2
        alignment = slong.c_alignment
        tp = make_struct_ffitype(size, alignment)

        sum_x_y = lib.getrawpointer('sum_x_y', [tp], slong)

        buffer = lltype.malloc(rffi.LONGP.TO, 3, flavor='raw')
        buffer[0] = 200
        buffer[1] = 220
        buffer[2] = 666
        sum_x_y.call([rffi.cast(rffi.VOIDP, buffer)],
                     rffi.cast(rffi.VOIDP, rffi.ptradd(buffer, 2)))
        assert buffer[2] == 420

        lltype.free(buffer, flavor='raw')
        del sum_x_y
        lltype.free(tp, flavor='raw')
        del lib

        assert not ALLOCATED
Пример #51
0
    def do_recv_string(self, space, buflength, maxlength):
        from pypy.module._multiprocessing.interp_win32 import (
            _ReadFile,
            _PeekNamedPipe,
            ERROR_BROKEN_PIPE,
            ERROR_MORE_DATA,
        )
        from pypy.rlib import rwin32
        from pypy.interpreter.error import wrap_windowserror

        read_ptr = lltype.malloc(rffi.CArrayPtr(rwin32.DWORD).TO, 1, flavor="raw")
        left_ptr = lltype.malloc(rffi.CArrayPtr(rwin32.DWORD).TO, 1, flavor="raw")
        try:
            result = _ReadFile(self.handle, self.buffer, min(self.BUFFER_SIZE, buflength), read_ptr, rffi.NULL)
            if result:
                return read_ptr[0], lltype.nullptr(rffi.CCHARP.TO)

            err = rwin32.GetLastError()
            if err == ERROR_BROKEN_PIPE:
                raise OperationError(space.w_EOFError, space.w_None)
            elif err != ERROR_MORE_DATA:
                raise wrap_windowserror(space, WindowsError(err, "_ReadFile"))

            # More data...
            if not _PeekNamedPipe(
                self.handle,
                rffi.NULL,
                0,
                lltype.nullptr(rwin32.LPDWORD.TO),
                lltype.nullptr(rwin32.LPDWORD.TO),
                left_ptr,
            ):
                raise wrap_windowserror(space, rwin32.lastWindowsError())

            length = intmask(read_ptr[0] + left_ptr[0])
            if length > maxlength:  # bad message, close connection
                self.flags &= ~READABLE
                if self.flags == 0:
                    self.close()
                raise OperationError(space.w_IOError, space.wrap("bad message length"))

            newbuf = lltype.malloc(rffi.CCHARP.TO, length + 1, flavor="raw")
            for i in range(read_ptr[0]):
                newbuf[i] = self.buffer[i]

            result = _ReadFile(self.handle, rffi.ptradd(newbuf, read_ptr[0]), left_ptr[0], read_ptr, rffi.NULL)
            if not result:
                rffi.free_charp(newbuf)
                raise wrap_windowserror(space, rwin32.lastWindowsError())

            assert read_ptr[0] == left_ptr[0]
            return length, newbuf
        finally:
            lltype.free(read_ptr, flavor="raw")
            lltype.free(left_ptr, flavor="raw")
Пример #52
0
    def do_recv_string(self, space, buflength, maxlength):
        from pypy.module._multiprocessing.interp_win32 import (
            _ReadFile, _PeekNamedPipe, ERROR_BROKEN_PIPE, ERROR_MORE_DATA)
        from pypy.rlib import rwin32
        from pypy.interpreter.error import wrap_windowserror

        read_ptr = lltype.malloc(rffi.CArrayPtr(rwin32.DWORD).TO,
                                 1,
                                 flavor='raw')
        left_ptr = lltype.malloc(rffi.CArrayPtr(rwin32.DWORD).TO,
                                 1,
                                 flavor='raw')
        try:
            result = _ReadFile(self.handle, self.buffer,
                               min(self.BUFFER_SIZE, buflength), read_ptr,
                               rffi.NULL)
            if result:
                return intmask(read_ptr[0]), lltype.nullptr(rffi.CCHARP.TO)

            err = rwin32.GetLastError()
            if err == ERROR_BROKEN_PIPE:
                raise OperationError(space.w_EOFError, space.w_None)
            elif err != ERROR_MORE_DATA:
                raise wrap_windowserror(space, WindowsError(err, "_ReadFile"))

            # More data...
            if not _PeekNamedPipe(self.handle, rffi.NULL, 0,
                                  lltype.nullptr(rwin32.LPDWORD.TO),
                                  lltype.nullptr(rwin32.LPDWORD.TO), left_ptr):
                raise wrap_windowserror(space, rwin32.lastWindowsError())

            length = intmask(read_ptr[0] + left_ptr[0])
            if length > maxlength:  # bad message, close connection
                self.flags &= ~READABLE
                if self.flags == 0:
                    self.close()
                raise OperationError(space.w_IOError,
                                     space.wrap("bad message length"))

            newbuf = lltype.malloc(rffi.CCHARP.TO, length + 1, flavor='raw')
            for i in range(read_ptr[0]):
                newbuf[i] = self.buffer[i]

            result = _ReadFile(self.handle, rffi.ptradd(newbuf, read_ptr[0]),
                               left_ptr[0], read_ptr, rffi.NULL)
            if not result:
                rffi.free_charp(newbuf)
                raise wrap_windowserror(space, rwin32.lastWindowsError())

            assert read_ptr[0] == left_ptr[0]
            return length, newbuf
        finally:
            lltype.free(read_ptr, flavor='raw')
            lltype.free(left_ptr, flavor='raw')
Пример #53
0
 def binary_search(self, gcmapstart, gcmapend, startaddr):
     i = 0
     while (i < gcrootmap._gcmap_curlength // 2
            and gcrootmap._gcmap[i * 2] < startaddr):
         i += 1
     if i > 0:
         i -= 1
     assert 0 <= i < gcrootmap._gcmap_curlength // 2
     p = rffi.cast(rffi.CArrayPtr(llmemory.Address), gcmapstart)
     p = rffi.ptradd(p, 2 * i)
     return llmemory.cast_ptr_to_adr(p)
Пример #54
0
 def bh_setinteriorfield_gc_r(self, gcref, itemindex, descr, newvalue):
     assert isinstance(descr, InteriorFieldDescr)
     arraydescr = descr.arraydescr
     ofs, size, _ = self.unpack_arraydescr_size(arraydescr)
     ofs += descr.fielddescr.offset
     self.gc_ll_descr.do_write_barrier(gcref, newvalue)
     # --- start of GC unsafe code (no GC operation!) ---
     items = rffi.ptradd(rffi.cast(rffi.CCHARP, gcref),
                         ofs + size * itemindex)
     items = rffi.cast(rffi.CArrayPtr(lltype.Signed), items)
     items[0] = self.cast_gcref_to_int(newvalue)