Beispiel #1
0
def load_extension_module(space, path, name):
    if os.sep not in path:
        path = os.curdir + os.sep + path      # force a '/' in the path
    state = space.fromcache(State)
    if state.find_extension(name, path) is not None:
        return
    old_context = state.package_context
    state.package_context = name, path
    try:
        from pypy.rlib import rdynload
        try:
            ll_libname = rffi.str2charp(path)
            try:
                dll = rdynload.dlopen(ll_libname)
            finally:
                lltype.free(ll_libname, flavor='raw')
        except rdynload.DLOpenError, e:
            raise operationerrfmt(
                space.w_ImportError,
                "unable to load extension module '%s': %s",
                path, e.msg)
        try:
            initptr = rdynload.dlsym(dll, 'init%s' % (name.split('.')[-1],))
        except KeyError:
            raise operationerrfmt(
                space.w_ImportError,
                "function init%s not found in library %s",
                name, path)
        initfunc = rffi.cast(initfunctype, initptr)
        generic_cpy_call(space, initfunc)
        state.check_and_raise_exception()
Beispiel #2
0
        def setlen(self, size):
            if size > 0:
                if size > self.allocated or size < self.allocated / 2:
                    if size < 9:
                        some = 3
                    else:
                        some = 6
                    some += size >> 3
                    self.allocated = size + some
                    new_buffer = lltype.malloc(mytype.arraytype,
                                               self.allocated, flavor='raw',
                                               add_memory_pressure=True)
                    for i in range(min(size, self.len)):
                        new_buffer[i] = self.buffer[i]
                else:
                    self.len = size
                    return
            else:
                assert size == 0
                self.allocated = 0
                new_buffer = lltype.nullptr(mytype.arraytype)

            if self.buffer:
                lltype.free(self.buffer, flavor='raw')
            self.buffer = new_buffer
            self.len = size
Beispiel #3
0
 def walk_roots(self, collect_stack_root,
                collect_static_in_prebuilt_nongc,
                collect_static_in_prebuilt_gc):
     gc = self.tester.gc
     layoutbuilder = self.tester.layoutbuilder
     if collect_static_in_prebuilt_gc:
         for addrofaddr in layoutbuilder.addresses_of_static_ptrs:
             if addrofaddr.address[0]:
                 collect_static_in_prebuilt_gc(gc, addrofaddr)
     if collect_static_in_prebuilt_nongc:
         for addrofaddr in layoutbuilder.addresses_of_static_ptrs_in_nongc:
             if addrofaddr.address[0]:
                 collect_static_in_prebuilt_nongc(gc, addrofaddr)
     if collect_stack_root:
         stackroots = self.tester.stackroots
         a = lltype.malloc(ADDR_ARRAY, len(stackroots), flavor='raw')
         for i in range(len(a)):
             a[i] = llmemory.cast_ptr_to_adr(stackroots[i])
         a_base = lltype.direct_arrayitems(a)
         for i in range(len(a)):
             ai = lltype.direct_ptradd(a_base, i)
             collect_stack_root(gc, llmemory.cast_ptr_to_adr(ai))
         for i in range(len(a)):
             PTRTYPE = lltype.typeOf(stackroots[i])
             stackroots[i] = llmemory.cast_adr_to_ptr(a[i], PTRTYPE)
         lltype.free(a, flavor='raw')
Beispiel #4
0
def test_raw_memclear_on_empty_array():
    py.test.skip("Fails")
    A = lltype.FixedSizeArray(lltype.Signed, 0)
    a = lltype.malloc(A, flavor='raw')
    src = cast_ptr_to_adr(a) + itemoffsetof(A, 0)
    raw_memclear(src, sizeof(lltype.Signed) * 0)
    lltype.free(a, flavor="raw")
Beispiel #5
0
 def time_clock_llimpl():
     a = lltype.malloc(RUSAGE, flavor='raw')
     c_getrusage(RUSAGE_SELF, a)
     result = (decode_timeval(a.c_ru_utime) +
               decode_timeval(a.c_ru_stime))
     lltype.free(a, flavor='raw')
     return result
Beispiel #6
0
    def llimpl_FormatError(code):
        "Return a message corresponding to the given Windows error code."
        buf = lltype.malloc(rffi.CCHARPP.TO, 1, flavor='raw')

        try:
            msglen = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
                                   FORMAT_MESSAGE_FROM_SYSTEM,
                                   None,
                                   rffi.cast(DWORD, code),
                                   DEFAULT_LANGUAGE,
                                   rffi.cast(rffi.CCHARP, buf),
                                   0, None)

            if msglen <= 2:   # includes the case msglen < 0
                return fake_FormatError(code)

            # FormatMessage always appends \r\n.
            buflen = intmask(msglen - 2)
            assert buflen > 0

            result = rffi.charpsize2str(buf[0], buflen)
            LocalFree(rffi.cast(rffi.VOIDP, buf[0]))
        finally:
            lltype.free(buf, flavor='raw')

        return result
Beispiel #7
0
    def test_uninitialized2ctypes(self):
        # for now, uninitialized fields are filled with 0xDD in the ctypes data
        def checkobj(o, size):
            p = ctypes.cast(ctypes.c_void_p(ctypes.addressof(o)),
                            ctypes.POINTER(ctypes.c_ubyte*size))
            for i in range(size):
                assert p.contents[i] == 0xDD

        def checkval(v, fmt):
            res = struct.pack(fmt, v)
            assert res == "\xDD" * len(res)

        checkval(uninitialized2ctypes(rffi.CHAR), 'B')
        checkval(uninitialized2ctypes(rffi.SHORT), 'h')
        checkval(uninitialized2ctypes(rffi.INT), 'i')
        checkval(uninitialized2ctypes(rffi.UINT), 'I')
        checkval(uninitialized2ctypes(rffi.LONGLONG), 'q')
        checkval(uninitialized2ctypes(rffi.DOUBLE), 'd')
        checkobj(uninitialized2ctypes(rffi.INTP),
                 ctypes.sizeof(ctypes.c_void_p))
        checkobj(uninitialized2ctypes(rffi.CCHARP),
                 ctypes.sizeof(ctypes.c_void_p))

        S = lltype.Struct('S', ('x', lltype.Signed), ('y', lltype.Signed))
        s = lltype.malloc(S, flavor='raw')
        sc = lltype2ctypes(s)
        checkval(sc.contents.x, 'l')
        checkval(sc.contents.y, 'l')
        lltype.free(s, flavor='raw')
        assert not ALLOCATED     # detects memory leaks in the test
Beispiel #8
0
    def test_forced_ptr_cast(self):
        import array
        A = lltype.Array(lltype.Signed, hints={'nolength': True})
        B = lltype.Array(lltype.Char, hints={'nolength': True})
        a = lltype.malloc(A, 10, flavor='raw')
        for i in range(10):
            a[i] = i*i

        b = rffi.cast(lltype.Ptr(B), a)

        checker = array.array('l')
        for i in range(10):
            checker.append(i*i)
        expected = checker.tostring()

        for i in range(len(expected)):
            assert b[i] == expected[i]

        c = rffi.cast(rffi.VOIDP, a)
        addr = lltype2ctypes(c)
        #assert addr == ctypes.addressof(a._obj._ctypes_storage)
        d = ctypes2lltype(rffi.VOIDP, addr)
        assert lltype.typeOf(d) == rffi.VOIDP
        assert c == d
        e = rffi.cast(lltype.Ptr(A), d)
        for i in range(10):
            assert e[i] == i*i

        c = lltype.nullptr(rffi.VOIDP.TO)
        addr = rffi.cast(lltype.Signed, c)
        assert addr == 0

        lltype.free(a, flavor='raw')
        assert not ALLOCATED     # detects memory leaks in the test
Beispiel #9
0
 def test_mousemove(self):
     if not self.is_interactive:
         py.test.skip("interactive test only")
     print
     print "Move the Mouse up and down:"
     print "    Use Escape to quit."
     event = lltype.malloc(RSDL.Event, flavor="raw")
     directions = [False]*4
     try:
         while True:
             ok = RSDL.WaitEvent(event)
             assert rffi.cast(lltype.Signed, ok) == 1
             c_type = rffi.getintfield(event, "c_type")
             if c_type == RSDL.MOUSEMOTION:
                 m = rffi.cast(RSDL.MouseMotionEventPtr, event)
                 assert rffi.getintfield(m, "c_x") >= 0
                 assert rffi.getintfield(m, "c_y") >= 0
                 print rffi.getintfield(m, "c_xrel")
                 directions[0] |= rffi.getintfield(m, "c_xrel")>0
                 directions[1] |= rffi.getintfield(m, "c_xrel")<0
                 directions[2] |= rffi.getintfield(m, "c_yrel")>0
                 directions[3] |= rffi.getintfield(m, "c_yrel")<0
                 if False not in directions:
                     break
             elif c_type == RSDL.KEYUP:
                 p = rffi.cast(RSDL.KeyboardEventPtr, event)
                 if rffi.getintfield(p.c_keysym, 'c_sym') == RSDL.K_ESCAPE:
                     print "    test manually aborted"
                     py.test.fail(" mousemovement test aborted")
                     break  
     finally:
         lltype.free(event, flavor='raw')
Beispiel #10
0
def test_addr_raw_packet():
    if not hasattr(rsocket._c, 'sockaddr_ll'):
        py.test.skip("posix specific test")
    c_addr_ll = lltype.malloc(rsocket._c.sockaddr_ll, flavor='raw')
    addrlen = rffi.sizeof(rsocket._c.sockaddr_ll)
    c_addr = rffi.cast(lltype.Ptr(rsocket._c.sockaddr), c_addr_ll)
    rffi.setintfield(c_addr_ll, 'c_sll_ifindex', 1)
    rffi.setintfield(c_addr_ll, 'c_sll_protocol', 8)
    rffi.setintfield(c_addr_ll, 'c_sll_pkttype', 13)
    rffi.setintfield(c_addr_ll, 'c_sll_hatype', 0)
    rffi.setintfield(c_addr_ll, 'c_sll_halen', 3)
    c_addr_ll.c_sll_addr[0] = 'a'
    c_addr_ll.c_sll_addr[1] = 'b'
    c_addr_ll.c_sll_addr[2] = 'c'
    rffi.setintfield(c_addr, 'c_sa_family', socket.AF_PACKET)
    # fd needs to be somehow valid
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    fd = s.fileno()
    w_obj = rsocket.make_address(c_addr, addrlen).as_object(fd, space)
    lltype.free(c_addr_ll, flavor='raw')
    assert space.is_true(space.eq(w_obj, space.newtuple([
        space.wrap('lo'),
        space.wrap(socket.ntohs(8)),
        space.wrap(13),
        space.wrap(False),
        space.wrap("abc"),
        ])))
Beispiel #11
0
 def test_keypresses(self):
     if not self.is_interactive:
         py.test.skip("interactive test only")
     RSDL.EnableUNICODE(1)
     print
     print "Keys pressed in the Pygame window should be printed below."
     print "    Use Escape to quit."
     event = lltype.malloc(RSDL.Event, flavor='raw')
     try:
         while True:
                 ok = RSDL.WaitEvent(event)
                 assert rffi.cast(lltype.Signed, ok) == 1
                 c_type = rffi.getintfield(event, 'c_type')
                 if c_type == RSDL.KEYDOWN:
                     p = rffi.cast(RSDL.KeyboardEventPtr, event)
                     if rffi.getintfield(p.c_keysym, 'c_sym') == RSDL.K_ESCAPE:
                         print 'Escape key'
                         break
                     char = rffi.getintfield(p.c_keysym, 'c_unicode')
                     if char != 0:
                         print 'Key:', unichr(char).encode('utf-8')
                     else:
                         print 'Some special key'
                 else:
                     print '(event of type %d)' % c_type
     finally:
         lltype.free(event, flavor='raw')
Beispiel #12
0
    def test_blit_rect(self):
        surface = RSDL.CreateRGBSurface(0, 150, 50, 32,
                                        r_uint(0x000000FF),
                                        r_uint(0x0000FF00),
                                        r_uint(0x00FF0000),
                                        r_uint(0xFF000000))
        fmt = surface.c_format
        color = RSDL.MapRGB(fmt, 255, 0, 0)
        RSDL.FillRect(surface, lltype.nullptr(RSDL.Rect), color)
        
        paintrect = RSDL_helper.mallocrect(75, 0, 150, 50)
        dstrect = lltype.malloc(RSDL.Rect, flavor='raw')
        try:
            color = RSDL.MapRGB(fmt, 255, 128, 0)
            RSDL.FillRect(surface, paintrect, color)

            rffi.setintfield(dstrect, 'c_x',  10)
            rffi.setintfield(dstrect, 'c_y',  10)
            rffi.setintfield(dstrect, 'c_w', 150)
            rffi.setintfield(dstrect, 'c_h',  50)
            RSDL.BlitSurface(surface, lltype.nullptr(RSDL.Rect), self.screen, dstrect)
            RSDL.Flip(self.screen)
        finally:
            lltype.free(dstrect, flavor='raw')
            lltype.free(paintrect, flavor='raw')
        RSDL.FreeSurface(surface)
        self.check("Half Red/Orange rectangle(150px * 50px) at the top left, 10 pixels from the border")
Beispiel #13
0
 def test_poll(self):
     if not self.is_interactive:
         py.test.skip("interactive test only")
     import time, sys
     RSDL.EnableUNICODE(1)
     print
     print "Keys pressed in the Pygame window give a dot."
     print "    Wait 3 seconds to quit."
     timeout = time.time() + 3
     event = lltype.malloc(RSDL.Event, flavor='raw')
     try:
         while True:
             # busy polling
             ok = RSDL.PollEvent(event)
             ok = rffi.cast(lltype.Signed, ok)
             assert ok >= 0
             if ok > 0:
                 c_type = rffi.getintfield(event, 'c_type')
                 if c_type == RSDL.KEYDOWN:
                     sys.stderr.write('.')
                     p = rffi.cast(RSDL.KeyboardEventPtr, event)
                     if rffi.getintfield(p.c_keysym, 'c_sym') == RSDL.K_ESCAPE:
                         print 'Escape key'
                         break
                     timeout = time.time() + 3
             else:
                 if time.time() > timeout:
                     break
             time.sleep(0.05)
     finally:
         lltype.free(event, flavor='raw')
Beispiel #14
0
def ioctl(space, w_fd, op, w_arg=0, mutate_flag=-1):
    """ioctl(fd, opt[, arg[, mutate_flag]])

    Perform the requested operation on file descriptor fd.  The operation is
    defined by opt and is operating system dependent.  Typically these codes
    are retrieved from the fcntl or termios library modules.
    """
    # removed the largish docstring because it is not in sync with the
    # documentation any more (even in CPython's docstring is out of date)

    # XXX this function's interface is a mess.
    # We try to emulate the behavior of Python >= 2.5 w.r.t. mutate_flag

    fd = space.c_filedescriptor_w(w_fd)
    op = rffi.cast(rffi.INT, op)        # C long => C int

    if mutate_flag != 0:
        try:
            rwbuffer = space.rwbuffer_w(w_arg)
        except OperationError, e:
            if not e.match(space, space.w_TypeError):
                raise
            if mutate_flag > 0:
                raise
        else:
            arg = rwbuffer.as_str()
            ll_arg = rffi.str2charp(arg)
            rv = ioctl_str(fd, op, ll_arg)
            arg = rffi.charpsize2str(ll_arg, len(arg))
            lltype.free(ll_arg, flavor='raw')
            if rv < 0:
                raise _get_error(space, "ioctl")
            rwbuffer.setslice(0, arg)
            return space.wrap(rv)
Beispiel #15
0
 def _free_buffers(self, ll_result, ll_args):
     if ll_result:
         self._free_buffer_maybe(rffi.cast(rffi.VOIDP, ll_result), self.restype)
     for i in range(len(self.argtypes)):
         argtype = self.argtypes[i]
         self._free_buffer_maybe(ll_args[i], argtype)
     lltype.free(ll_args, flavor='raw')
Beispiel #16
0
    def __init__(self, space, environment, context, retrieveError):
        self.context = context
        if retrieveError:
            if environment.errorHandle:
                handle = environment.errorHandle
                handleType = roci.OCI_HTYPE_ERROR
            else:
                handle = environment.handle
                handleType = roci.OCI_HTYPE_ENV

            codeptr = lltype.malloc(rffi.CArray(roci.sb4), 1, flavor='raw')
            BUFSIZE = 1024
            textbuf, text = rffi.alloc_buffer(BUFSIZE)

            try:
                status = roci.OCIErrorGet(
                    handle, 1, lltype.nullptr(roci.oratext.TO), codeptr,
                    textbuf, BUFSIZE, handleType)
                if status != roci.OCI_SUCCESS:
                    raise OperationError(
                        get(space).w_InternalError,
                        space.wrap("No Oracle error?"))

                self.code = codeptr[0]
                self.w_message = config.w_string(space, textbuf)
            finally:
                lltype.free(codeptr, flavor='raw')
                rffi.keep_buffer_alive_until_here(textbuf, text)

            if config.WITH_UNICODE:
                # XXX remove double zeros at the end
                pass
Beispiel #17
0
    def getdefaultlocale(space):
        encoding = "cp%d" % GetACP()

        BUFSIZE = 50
        buf_lang = lltype.malloc(rffi.CCHARP.TO, BUFSIZE, flavor='raw')
        buf_country = lltype.malloc(rffi.CCHARP.TO, BUFSIZE, flavor='raw')

        try:
            if (GetLocaleInfo(LOCALE_USER_DEFAULT,
                              LOCALE_SISO639LANGNAME,
                              buf_lang, BUFSIZE) and
                GetLocaleInfo(LOCALE_USER_DEFAULT,
                              LOCALE_SISO3166CTRYNAME,
                              buf_country, BUFSIZE)):
                lang = rffi.charp2str(buf_lang)
                country = rffi.charp2str(buf_country)
                return space.newtuple([space.wrap("%s_%s" % (lang, country)),
                                       space.wrap(encoding)])

            # If we end up here, this windows version didn't know about
            # ISO639/ISO3166 names (it's probably Windows 95).  Return the
            # Windows language identifier instead (a hexadecimal number)
            elif GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IDEFAULTLANGUAGE,
                               buf_lang, BUFSIZE):
                lang = rffi.charp2str(buf_lang)
                return space.newtuple([space.wrap("0x%s" % lang),
                                       space.wrap(encoding)])
            else:
                return space.newtuple([space.w_None, space.wrap(encoding)])
        finally:
            lltype.free(buf_lang, flavor='raw')
            lltype.free(buf_country, flavor='raw')
Beispiel #18
0
 def _enlarge_gcmap(self):
     oldgcmap = self._gcmap
     if self._gcmap_deadentries * 3 * 2 > self._gcmap_maxlength:
         # More than 1/3rd of the entries are dead.  Don't actually
         # enlarge the gcmap table, but just clean up the dead entries.
         newgcmap = oldgcmap
     else:
         # Normal path: enlarge the array.
         newlength = 250 + (self._gcmap_maxlength // 3) * 4
         newgcmap = lltype.malloc(self.GCMAP_ARRAY, newlength, flavor='raw',
                                  track_allocation=False)
         self._gcmap_maxlength = newlength
     #
     j = 0
     i = 0
     end = self._gcmap_curlength
     while i < end:
         if oldgcmap[i + 1]:
             newgcmap[j] = oldgcmap[i]
             newgcmap[j + 1] = oldgcmap[i + 1]
             j += 2
         i += 2
     self._gcmap_curlength = j
     self._gcmap_deadentries = 0
     if oldgcmap != newgcmap:
         self._gcmap = newgcmap
         if oldgcmap:
             lltype.free(oldgcmap, flavor='raw', track_allocation=False)
     return j
Beispiel #19
0
def test_carray_to_ll():
    A = lltype.Array(lltype.Signed, hints={'nolength': True})
    a = lltype.malloc(A, 10, flavor='raw')
    a2 = lltype.malloc(A, 10, flavor='raw')
    a[0] = 100
    a[1] = 101
    a[2] = 110
    ac = lltype2ctypes(a)
    b = ctypes2lltype(lltype.Ptr(A), ac)
    assert lltype.typeOf(b) == lltype.Ptr(A)
    assert b == a
    assert not (b != a)
    assert a == b
    assert not (a != b)
    assert b != lltype.nullptr(A)
    assert not (b == lltype.nullptr(A))
    assert lltype.nullptr(A) != b
    assert not (lltype.nullptr(A) == b)
    assert b != a2
    assert not (b == a2)
    assert a2 != b
    assert not (a2 == b)
    assert b[2] == 110
    b[2] *= 2
    assert a[2] == 220
    a[2] *= 3
    assert b[2] == 660
    lltype.free(a, flavor='raw')
    lltype.free(a2, flavor='raw')
Beispiel #20
0
 def test_arrayofstruct(self):
     S1 = lltype.Struct('S1', ('x', lltype.Signed))
     A = lltype.Array(S1, hints={'nolength': True})
     a = lltype.malloc(A, 5, flavor='raw')
     a[0].x = 100
     a[1].x = 101
     a[2].x = 102
     a[3].x = 103
     a[4].x = 104
     ac = lltype2ctypes(a, normalize=False)
     assert ac.contents.items[0].x == 100
     assert ac.contents.items[2].x == 102
     ac.contents.items[3].x += 500
     assert a[3].x == 603
     a[4].x += 600
     assert ac.contents.items[4].x == 704
     a1 = ctypes2lltype(lltype.Ptr(A), ac)
     assert a1 == a
     assert a1[2].x == 102
     aitem1 = ctypes2lltype(lltype.Ptr(S1),
                            ctypes.pointer(ac.contents.items[1]))
     assert aitem1.x == 101
     assert aitem1 == a1[1]
     lltype.free(a, flavor='raw')
     assert not ALLOCATED     # detects memory leaks in the test
Beispiel #21
0
def test_cstruct_to_ll():
    S = lltype.Struct('S', ('x', lltype.Signed), ('y', lltype.Signed))
    s = lltype.malloc(S, flavor='raw')
    s2 = lltype.malloc(S, flavor='raw')
    s.x = 123
    sc = lltype2ctypes(s)
    t = ctypes2lltype(lltype.Ptr(S), sc)
    assert lltype.typeOf(t) == lltype.Ptr(S)
    assert s == t
    assert not (s != t)
    assert t == s
    assert not (t != s)
    assert t != lltype.nullptr(S)
    assert not (t == lltype.nullptr(S))
    assert lltype.nullptr(S) != t
    assert not (lltype.nullptr(S) == t)
    assert t != s2
    assert not (t == s2)
    assert s2 != t
    assert not (s2 == t)
    assert t.x == 123
    t.x += 1
    assert s.x == 124
    s.x += 1
    assert t.x == 125
    lltype.free(s, flavor='raw')
    lltype.free(s2, flavor='raw')
Beispiel #22
0
    def test_qsort(self):
        CMPFUNC = lltype.FuncType([rffi.VOIDP, rffi.VOIDP], rffi.INT)
        qsort = rffi.llexternal('qsort', [rffi.VOIDP,
                                          rffi.SIZE_T,
                                          rffi.SIZE_T,
                                          lltype.Ptr(CMPFUNC)],
                                lltype.Void)

        lst = [23, 43, 24, 324, 242, 34, 78, 5, 3, 10]
        A = lltype.Array(lltype.Signed, hints={'nolength': True})
        a = lltype.malloc(A, 10, flavor='raw')
        for i in range(10):
            a[i] = lst[i]

        SIGNEDPTR = lltype.Ptr(lltype.FixedSizeArray(lltype.Signed, 1))

        def my_compar(p1, p2):
            p1 = rffi.cast(SIGNEDPTR, p1)
            p2 = rffi.cast(SIGNEDPTR, p2)
            print 'my_compar:', p1[0], p2[0]
            return rffi.cast(rffi.INT, cmp(p1[0], p2[0]))

        qsort(rffi.cast(rffi.VOIDP, a),
              rffi.cast(rffi.SIZE_T, 10),
              rffi.cast(rffi.SIZE_T, llmemory.sizeof(lltype.Signed)),
              llhelper(lltype.Ptr(CMPFUNC), my_compar))

        for i in range(10):
            print a[i],
        print
        lst.sort()
        for i in range(10):
            assert a[i] == lst[i]
        lltype.free(a, flavor='raw')
        assert not ALLOCATED     # detects memory leaks in the test
Beispiel #23
0
 def __del__(self):
     if self.ll_cif:
         lltype.free(self.ll_cif, flavor='raw')
         self.ll_cif = lltype.nullptr(FFI_CIFP.TO)
     if self.ll_argtypes:
         lltype.free(self.ll_argtypes, flavor='raw')
         self.ll_argtypes = lltype.nullptr(FFI_TYPE_PP.TO)
Beispiel #24
0
        def test(encoded, endian, realendian=None):
            encoded_charp = rffi.str2charp(encoded)
            strict_charp = rffi.str2charp("strict")
            if endian is not None:
                if endian < 0:
                    value = -1
                elif endian > 0:
                    value = 1
                else:
                    value = 0
                pendian = lltype.malloc(rffi.INTP.TO, 1, flavor='raw')
                pendian[0] = rffi.cast(rffi.INT, value)
            else:
                pendian = None

            w_ustr = api.PyUnicode_DecodeUTF16(encoded_charp, len(encoded), strict_charp, pendian)
            assert space.eq_w(space.call_method(w_ustr, 'encode', space.wrap('ascii')),
                              space.wrap("abcd"))

            rffi.free_charp(encoded_charp)
            rffi.free_charp(strict_charp)
            if pendian:
                if realendian is not None:
                    assert rffi.cast(rffi.INT, realendian) == pendian[0]
                lltype.free(pendian, flavor='raw')
Beispiel #25
0
    def test_byval_argument(self):
        """
            struct Point {
                long x;
                long y;
            };

            long sum_point(struct Point p) {
                return p.x + p.y;
            }
        """
        libfoo = CDLL(self.libfoo_name)
        ffi_point_struct = make_struct_ffitype_e(0, 0, [types.slong, types.slong])
        ffi_point = ffi_point_struct.ffistruct
        sum_point = (libfoo, 'sum_point', [ffi_point], types.slong)
        #
        ARRAY = rffi.CArray(rffi.LONG)
        buf = lltype.malloc(ARRAY, 2, flavor='raw')
        buf[0] = 30
        buf[1] = 12
        adr = rffi.cast(rffi.VOIDP, buf)
        res = self.call(sum_point, [('arg_raw', adr)], rffi.LONG,
                        jitif=["byval"])
        assert res == 42
        # check that we still have the ownership on the buffer
        assert buf[0] == 30
        assert buf[1] == 12
        lltype.free(buf, flavor='raw')
        lltype.free(ffi_point_struct, flavor='raw')
Beispiel #26
0
    def walk_stack_from(self):
        curframe = lltype.malloc(WALKFRAME, flavor='raw')
        otherframe = lltype.malloc(WALKFRAME, flavor='raw')

        # Walk over all the pieces of stack.  They are in a circular linked
        # list of structures of 7 words, the 2 first words being prev/next.
        # The anchor of this linked list is:
        anchor = llmemory.cast_ptr_to_adr(gcrootanchor)
        initialframedata = anchor.address[1]
        stackscount = 0
        while initialframedata != anchor:     # while we have not looped back
            self.fill_initial_frame(curframe, initialframedata)
            # Loop over all the frames in the stack
            while self.walk_to_parent_frame(curframe, otherframe):
                swap = curframe
                curframe = otherframe    # caller becomes callee
                otherframe = swap
            # Then proceed to the next piece of stack
            initialframedata = initialframedata.address[1]
            stackscount += 1
        #
        expected = rffi.stackcounter.stacks_counter
        ll_assert(not (stackscount < expected), "non-closed stacks around")
        ll_assert(not (stackscount > expected), "stacks counter corruption?")
        lltype.free(otherframe, flavor='raw')
        lltype.free(curframe, flavor='raw')
Beispiel #27
0
Datei: env.py Projekt: ieure/pypy
def get_darwin_sysctl_signed(sysctl_name):
    rval_p = lltype.malloc(rffi.LONGLONGP.TO, 1, flavor='raw')
    try:
        len_p = lltype.malloc(rffi.SIZE_TP.TO, 1, flavor='raw')
        try:
            size = rffi.sizeof(rffi.LONGLONG)
            rval_p[0] = rffi.cast(rffi.LONGLONG, 0)
            len_p[0] = rffi.cast(rffi.SIZE_T, size)
            # XXX a hack for llhelper not being robust-enough
            result = sysctlbyname(sysctl_name,
                                  rffi.cast(rffi.VOIDP, rval_p),
                                  len_p,
                                  lltype.nullptr(rffi.VOIDP.TO),
                                  rffi.cast(rffi.SIZE_T, 0))
            rval = 0
            if (rffi.cast(lltype.Signed, result) == 0 and
                rffi.cast(lltype.Signed, len_p[0]) == size):
                rval = rffi.cast(lltype.Signed, rval_p[0])
                if rffi.cast(rffi.LONGLONG, rval) != rval_p[0]:
                    rval = 0    # overflow!
            return rval
        finally:
            lltype.free(len_p, flavor='raw')
    finally:
        lltype.free(rval_p, flavor='raw')
Beispiel #28
0
def inflateEnd(stream):
    """
    Free the resources associated with the inflate stream.
    Note that this may raise RZlibError.
    """
    _inflateEnd(stream)
    lltype.free(stream, flavor='raw')
Beispiel #29
0
    def win32_urandom(space, n):
        """urandom(n) -> str

        Return a string of n random bytes suitable for cryptographic use.
        """

        if n < 0:
            raise OperationError(space.w_ValueError,
                                 space.wrap("negative argument not allowed"))

        provider = get(space).cryptProviderPtr[0]
        if not provider:
            # Acquire context.
            # This handle is never explicitly released. The operating
            # system will release it when the process terminates.
            if not CryptAcquireContext(
                get(space).cryptProviderPtr, None, None,
                PROV_RSA_FULL, CRYPT_VERIFYCONTEXT):
                raise rwin32.lastWindowsError("CryptAcquireContext")

            provider = get(space).cryptProviderPtr[0]

        # Get random data
        buf = lltype.malloc(rffi.CArray(rwin32.BYTE), n,
                            zero=True, # zero seed
                            flavor='raw')
        try:
            if not CryptGenRandom(provider, n, buf):
                raise rwin32.lastWindowsError("CryptGenRandom")

            return space.wrap(
                rffi.charpsize2str(rffi.cast(rffi.CCHARP, buf), n))
        finally:
            lltype.free(buf, flavor='raw')
Beispiel #30
0
 def __del__(self):
     if self.ll_cif:
         lltype.free(self.ll_cif, flavor="raw", track_allocation=False)
         self.ll_cif = lltype.nullptr(FFI_CIFP.TO)
     if self.ll_argtypes:
         lltype.free(self.ll_argtypes, flavor="raw", track_allocation=False)
         self.ll_argtypes = lltype.nullptr(FFI_TYPE_PP.TO)
Beispiel #31
0
 def inet_pton(family, ip):
     "human-readable string -> packed string"
     if family == AF_INET:
         size = sizeof(_c.in_addr)
     elif AF_INET6 is not None and family == AF_INET6:
         size = sizeof(_c.in6_addr)
     else:
         raise RSocketError("unknown address family")
     buf = mallocbuf(size)
     try:
         res = _c.inet_pton(family, ip, buf)
         if res < 0:
             raise last_error()
         elif res == 0:
             raise RSocketError("illegal IP address string passed "
                                "to inet_pton")
         else:
             return ''.join([buf[i] for i in range(size)])
     finally:
         lltype.free(buf, flavor='raw')
Beispiel #32
0
 def accept(self, SocketClass=None):
     """Wait for an incoming connection.
     Return (new socket object, client address)."""
     if SocketClass is None:
         SocketClass = RSocket
     if self._select(False) == 1:
         raise SocketTimeout
     address, addr_p, addrlen_p = self._addrbuf()
     try:
         newfd = _c.socketaccept(self.fd, addr_p, addrlen_p)
         addrlen = addrlen_p[0]
     finally:
         lltype.free(addrlen_p, flavor='raw')
         address.unlock()
     if _c.invalid_socket(newfd):
         raise self.error_handler()
     address.addrlen = rffi.cast(lltype.Signed, addrlen)
     sock = make_socket(newfd, self.family, self.type, self.proto,
                        SocketClass)
     return (sock, address)
Beispiel #33
0
    def socketpair(family=socketpair_default_family,
                   type=SOCK_STREAM,
                   proto=0,
                   SocketClass=RSocket):
        """socketpair([family[, type[, proto]]]) -> (socket object, socket object)

        Create a pair of socket objects from the sockets returned by the platform
        socketpair() function.
        The arguments are the same as for socket() except the default family is
        AF_UNIX if defined on the platform; otherwise, the default is AF_INET.
        """
        result = lltype.malloc(_c.socketpair_t, 2, flavor='raw')
        res = _c.socketpair(family, type, proto, result)
        if res < 0:
            raise last_error()
        fd0 = rffi.cast(lltype.Signed, result[0])
        fd1 = rffi.cast(lltype.Signed, result[1])
        lltype.free(result, flavor='raw')
        return (make_socket(fd0, family, type, proto, SocketClass),
                make_socket(fd1, family, type, proto, SocketClass))
Beispiel #34
0
 def test_unicode_resize(self, space, api):
     py_uni = new_empty_unicode(space, 10)
     ar = lltype.malloc(PyObjectP.TO, 1, flavor='raw')
     py_uni.c_buffer[0] = u'a'
     py_uni.c_buffer[1] = u'b'
     py_uni.c_buffer[2] = u'c'
     ar[0] = rffi.cast(PyObject, py_uni)
     api.PyUnicode_Resize(ar, 3)
     py_uni = rffi.cast(PyUnicodeObject, ar[0])
     assert py_uni.c_size == 3
     assert py_uni.c_buffer[1] == u'b'
     assert py_uni.c_buffer[3] == u'\x00'
     # the same for growing
     ar[0] = rffi.cast(PyObject, py_uni)
     api.PyUnicode_Resize(ar, 10)
     py_uni = rffi.cast(PyUnicodeObject, ar[0])
     assert py_uni.c_size == 10
     assert py_uni.c_buffer[1] == 'b'
     assert py_uni.c_buffer[10] == '\x00'
     Py_DecRef(space, ar[0])
     lltype.free(ar, flavor='raw')
Beispiel #35
0
 def _get_file_size(handle):
     # XXX use native Windows types like WORD
     high_ref = lltype.malloc(LPDWORD.TO, 1, flavor='raw')
     try:
         low = GetFileSize(handle, high_ref)
         low = rffi.cast(lltype.Signed, low)
         # XXX should be propagate the real type, allowing
         # for 2*sys.maxint?
         high = high_ref[0]
         # low might just happen to have the value INVALID_FILE_SIZE
         # so we need to check the last error also
         INVALID_FILE_SIZE = -1
         NO_ERROR = 0
         dwErr = GetLastError()
         err = rffi.cast(lltype.Signed, dwErr)
         if low == INVALID_FILE_SIZE and err != NO_ERROR:
             msg = os.strerror(err)
             raise OSError(err, msg)
         return low, high
     finally:
         lltype.free(high_ref, flavor='raw')
Beispiel #36
0
def CreateKey(space, w_hkey, subkey):
    """key = CreateKey(key, sub_key) - Creates or opens the specified key.

key is an already open key, or one of the predefined HKEY_* constants
sub_key is a string that names the key this method opens or creates.
 If key is one of the predefined keys, sub_key may be None. In that case,
 the handle returned is the same key handle passed in to the function.

If the key already exists, this function opens the existing key

The return value is the handle of the opened key.
If the function fails, an exception is raised."""
    hkey = hkey_w(w_hkey, space)
    rethkey = lltype.malloc(rwinreg.PHKEY.TO, 1, flavor='raw')
    try:
        ret = rwinreg.RegCreateKey(hkey, subkey, rethkey)
        if ret != 0:
            raiseWindowsError(space, ret, 'CreateKey')
        return space.wrap(W_HKEY(rethkey[0]))
    finally:
        lltype.free(rethkey, flavor='raw')
Beispiel #37
0
def ConnectRegistry(space, w_machine, w_hkey):
    """key = ConnectRegistry(computer_name, key)

Establishes a connection to a predefined registry handle on another computer.

computer_name is the name of the remote computer, of the form \\\\computername.
 If None, the local computer is used.
key is the predefined handle to connect to.

The return value is the handle of the opened key.
If the function fails, an EnvironmentError exception is raised."""
    machine = str_or_None_w(space, w_machine)
    hkey = hkey_w(w_hkey, space)
    rethkey = lltype.malloc(rwinreg.PHKEY.TO, 1, flavor='raw')
    try:
        ret = rwinreg.RegConnectRegistry(machine, hkey, rethkey)
        if ret != 0:
            raiseWindowsError(space, ret, 'RegConnectRegistry')
        return space.wrap(W_HKEY(rethkey[0]))
    finally:
        lltype.free(rethkey, flavor='raw')
Beispiel #38
0
    def do_send_string(self, space, buffer, offset, size):
        from pypy.module._multiprocessing.interp_win32 import (
            _WriteFile, ERROR_NO_SYSTEM_RESOURCES)
        from pypy.rlib import rwin32

        charp = rffi.str2charp(buffer)
        written_ptr = lltype.malloc(rffi.CArrayPtr(rwin32.DWORD).TO,
                                    1,
                                    flavor='raw')
        try:
            result = _WriteFile(self.handle, rffi.ptradd(charp, offset), size,
                                written_ptr, rffi.NULL)

            if (result == 0
                    and rwin32.GetLastError() == ERROR_NO_SYSTEM_RESOURCES):
                raise operationerrfmt(space.w_ValueError,
                                      "Cannot send %d bytes over connection",
                                      size)
        finally:
            rffi.free_charp(charp)
            lltype.free(written_ptr, flavor='raw')
Beispiel #39
0
 def test_string_resize(self, space, api):
     py_str = new_empty_str(space, 10)
     ar = lltype.malloc(PyObjectP.TO, 1, flavor='raw')
     py_str.c_buffer[0] = 'a'
     py_str.c_buffer[1] = 'b'
     py_str.c_buffer[2] = 'c'
     ar[0] = rffi.cast(PyObject, py_str)
     api._PyString_Resize(ar, 3)
     py_str = rffi.cast(PyStringObject, ar[0])
     assert py_str.c_size == 3
     assert py_str.c_buffer[1] == 'b'
     assert py_str.c_buffer[3] == '\x00'
     # the same for growing
     ar[0] = rffi.cast(PyObject, py_str)
     api._PyString_Resize(ar, 10)
     py_str = rffi.cast(PyStringObject, ar[0])
     assert py_str.c_size == 10
     assert py_str.c_buffer[1] == 'b'
     assert py_str.c_buffer[10] == '\x00'
     Py_DecRef(space, ar[0])
     lltype.free(ar, flavor='raw')
Beispiel #40
0
def entry_point(argv=None):
    RSDL.Init(RSDL.INIT_VIDEO) >= 0
    screen = RSDL.SetVideoMode(WIDTH, HEIGHT, 32, 0)
    event = lltype.malloc(RSDL.Event, flavor='raw')
    paintpattern = 0
    try:
        while True:
            ok = RSDL.WaitEvent(event)
            assert rffi.cast(lltype.Signed, ok) == 1
            c_type = rffi.getintfield(event, 'c_type')
            if c_type == RSDL.KEYDOWN:
                p = rffi.cast(RSDL.KeyboardEventPtr, event)
                if rffi.getintfield(p.c_keysym, 'c_sym') == RSDL.K_ESCAPE:
                    print 'Escape key'
                    break
            paintpattern += 1
            update_screen(screen, paintpattern)
    finally:
        lltype.free(event, flavor='raw')

    return 0
Beispiel #41
0
 def f():
     from pypy.rpython.lltypesystem import lltype, rffi
     alist = [A() for i in range(50)]
     idarray = lltype.malloc(rffi.INTP.TO, len(alist), flavor='raw')
     # Compute the id of all the elements of the list.  The goal is
     # to not allocate memory, so that if the GC needs memory to
     # remember the ids, it will trigger some collections itself
     i = 0
     while i < len(alist):
         idarray[i] = compute_unique_id(alist[i])
         i += 1
     j = 0
     while j < 2:
         if j == 1:     # allocate some stuff between the two iterations
             [A() for i in range(20)]
         i = 0
         while i < len(alist):
             assert idarray[i] == compute_unique_id(alist[i])
             i += 1
         j += 1
     lltype.free(idarray, flavor='raw')
Beispiel #42
0
def QueryValueEx(space, w_hkey, subkey):
    """value,type_id = QueryValueEx(key, value_name) - Retrieves the type and data for a specified value name associated with an open registry key.

key is an already open key, or any one of the predefined HKEY_* constants.
value_name is a string indicating the value to query"""
    hkey = hkey_w(w_hkey, space)
    null_dword = lltype.nullptr(rwin32.LPDWORD.TO)
    retDataSize = lltype.malloc(rwin32.LPDWORD.TO, 1, flavor='raw')
    try:
        ret = rwinreg.RegQueryValueEx(hkey, subkey, null_dword, null_dword,
                                      None, retDataSize)
        if ret != 0:
            raiseWindowsError(space, ret, 'RegQueryValueEx')
        databuf = lltype.malloc(rffi.CCHARP.TO, retDataSize[0], flavor='raw')
        try:
            retType = lltype.malloc(rwin32.LPDWORD.TO, 1, flavor='raw')
            try:

                ret = rwinreg.RegQueryValueEx(hkey, subkey, null_dword,
                                              retType, databuf, retDataSize)
                if ret != 0:
                    raiseWindowsError(space, ret, 'RegQueryValueEx')
                return space.newtuple([
                    convert_from_regdata(space, databuf,
                                         retDataSize[0], retType[0]),
                    space.wrap(retType[0]),
                    ])
            finally:
                lltype.free(retType, flavor='raw')
        finally:
            lltype.free(databuf, flavor='raw')
    finally:
        lltype.free(retDataSize, flavor='raw')
Beispiel #43
0
 def os_utime_llimpl(path, tp):
     hFile = CreateFile(path, FILE_WRITE_ATTRIBUTES, 0, None, OPEN_EXISTING,
                        FILE_FLAG_BACKUP_SEMANTICS, rwin32.NULL_HANDLE)
     if hFile == rwin32.INVALID_HANDLE_VALUE:
         raise rwin32.lastWindowsError()
     ctime = lltype.nullptr(rwin32.FILETIME)
     atime = lltype.malloc(rwin32.FILETIME, flavor='raw')
     mtime = lltype.malloc(rwin32.FILETIME, flavor='raw')
     try:
         if tp is None:
             now = lltype.malloc(rwin32.SYSTEMTIME, flavor='raw')
             try:
                 GetSystemTime(now)
                 if (not SystemTimeToFileTime(now, atime)
                         or not SystemTimeToFileTime(now, mtime)):
                     raise rwin32.lastWindowsError()
             finally:
                 lltype.free(now, flavor='raw')
         else:
             actime, modtime = tp
             time_t_to_FILE_TIME(actime, atime)
             time_t_to_FILE_TIME(modtime, mtime)
         if not SetFileTime(hFile, ctime, atime, mtime):
             raise rwin32.lastWindowsError()
     finally:
         rwin32.CloseHandle(hFile)
         lltype.free(atime, flavor='raw')
         lltype.free(mtime, flavor='raw')
Beispiel #44
0
    def test_iterkeys(self, space, api):
        w_dict = space.sys.getdict(space)
        py_dict = make_ref(space, w_dict)

        ppos = lltype.malloc(Py_ssize_tP.TO, 1, flavor='raw')
        pkey = lltype.malloc(PyObjectP.TO, 1, flavor='raw')
        pvalue = lltype.malloc(PyObjectP.TO, 1, flavor='raw')

        keys_w = []
        values_w = []
        try:
            ppos[0] = 0
            while api.PyDict_Next(w_dict, ppos, pkey, None):
                w_key = from_ref(space, pkey[0])
                keys_w.append(w_key)
            ppos[0] = 0
            while api.PyDict_Next(w_dict, ppos, None, pvalue):
                w_value = from_ref(space, pvalue[0])
                values_w.append(w_value)
        finally:
            lltype.free(ppos, flavor='raw')
            lltype.free(pkey, flavor='raw')
            lltype.free(pvalue, flavor='raw')

        api.Py_DecRef(py_dict)  # release borrowed references

        assert space.eq_w(space.newlist(keys_w),
                          space.call_method(w_dict, "keys"))
        assert space.eq_w(space.newlist(values_w),
                          space.call_method(w_dict, "values"))
Beispiel #45
0
    def _internalFetch(self, space, numRows):
        if not self.fetchVariables:
            raise OperationError(
                get(space).w_InterfaceError,
                space.wrap("query not executed"))

        status = roci.OCIStmtFetch(
            self.handle,
            self.environment.errorHandle,
            numRows,
            roci.OCI_FETCH_NEXT,
            roci.OCI_DEFAULT)

        if status != roci.OCI_NO_DATA:
            self.environment.checkForError(
                status,
                "Cursor_InternalFetch(): fetch")

        for var in self.fetchVariables:
            assert isinstance(var, interp_variable.W_Variable)
            var.internalFetchNum += 1

        attrptr = lltype.malloc(rffi.CArrayPtr(roci.ub4).TO,
                                1, flavor='raw')
        try:
            status = roci.OCIAttrGet(
                self.handle, roci.OCI_HTYPE_STMT,
                rffi.cast(roci.dvoidp, attrptr),
                lltype.nullptr(roci.Ptr(roci.ub4).TO),
                roci.OCI_ATTR_ROW_COUNT,
                self.environment.errorHandle)

            self.environment.checkForError(
                status, "Cursor_InternalFetch(): row count")

            self.actualRows = (rffi.cast(lltype.Signed, attrptr[0])
                               - self.rowCount)
            self.rowNum = 0
        finally:
            lltype.free(attrptr, flavor='raw')
Beispiel #46
0
def SetValueEx(space, w_hkey, value_name, w_reserved, typ, w_value):
    """SetValueEx(key, value_name, reserved, type, value) - Stores data in the value field of an open registry key.

key is an already open key, or any one of the predefined HKEY_* constants.
value_name is a string containing the name of the value to set, or None
type is an integer that specifies the type of the data.  This should be one of:
  REG_BINARY -- Binary data in any form.
  REG_DWORD -- A 32-bit number.
  REG_DWORD_LITTLE_ENDIAN -- A 32-bit number in little-endian format.
  REG_DWORD_BIG_ENDIAN -- A 32-bit number in big-endian format.
  REG_EXPAND_SZ -- A null-terminated string that contains unexpanded references
                   to environment variables (for example, %PATH%).
  REG_LINK -- A Unicode symbolic link.
  REG_MULTI_SZ -- An sequence of null-terminated strings, terminated by
                  two null characters.  Note that Python handles this
                  termination automatically.
  REG_NONE -- No defined value type.
  REG_RESOURCE_LIST -- A device-driver resource list.
  REG_SZ -- A null-terminated string.
reserved can be anything - zero is always passed to the API.
value is a string that specifies the new value.

This method can also set additional value and type information for the
specified key.  The key identified by the key parameter must have been
opened with KEY_SET_VALUE access.

To open the key, use the CreateKeyEx() or OpenKeyEx() methods.

Value lengths are limited by available memory. Long values (more than
2048 bytes) should be stored as files with the filenames stored in
the configuration registry.  This helps the registry perform efficiently."""
    hkey = hkey_w(w_hkey, space)
    buf, buflen = convert_to_regdata(space, w_value, typ)
    try:
        ret = rwinreg.RegSetValueEx(hkey, value_name, 0, typ, buf, buflen)
    finally:
        lltype.free(buf, flavor='raw')
    if ret != 0:
        raiseWindowsError(space, ret, 'RegSetValueEx')
Beispiel #47
0
def flock(space, w_fd, op):
    """flock(fd, operation)

    Perform the lock operation op on file descriptor fd.  See the Unix
    manual flock(3) for details.  (On some systems, this function is
    emulated using fcntl().)"""

    fd = _conv_descriptor(space, w_fd)

    if has_flock:
        rv = c_flock(fd, op)
        if rv < 0:
            raise OperationError(space.w_IOError,
                space.wrap(_get_error_msg()))
    else:
        l = _check_flock_op(space, op)
        rffi.setintfield(l, 'c_l_whence', 0)
        rffi.setintfield(l, 'c_l_start', 0)
        rffi.setintfield(l, 'c_l_len', 0)
        op = [F_SETLKW, F_SETLK][op & LOCK_NB]
        fcntl_flock(fd, op, l)
        lltype.free(l, flavor='raw')
Beispiel #48
0
    def ioctl_w(self, space, cmd, w_option):
        from pypy.rpython.lltypesystem import rffi, lltype
        from pypy.rlib import rwin32
        from pypy.rlib.rsocket import _c

        recv_ptr = lltype.malloc(rwin32.LPDWORD.TO, 1, flavor='raw')
        try:
            if cmd == _c.SIO_RCVALL:
                value_size = rffi.sizeof(rffi.INTP)
            elif cmd == _c.SIO_KEEPALIVE_VALS:
                value_size = rffi.sizeof(_c.tcp_keepalive)
            else:
                raise operationerrfmt(space.w_ValueError,
                                      "invalid ioctl command %d", cmd)

            value_ptr = lltype.malloc(rffi.VOIDP.TO, value_size, flavor='raw')
            try:
                if cmd == _c.SIO_RCVALL:
                    option_ptr = rffi.cast(rffi.INTP, value_ptr)
                    option_ptr[0] = space.int_w(w_option)
                elif cmd == _c.SIO_KEEPALIVE_VALS:
                    w_onoff, w_time, w_interval = space.unpackiterable(w_option)
                    option_ptr = rffi.cast(lltype.Ptr(_c.tcp_keepalive), value_ptr)
                    option_ptr.c_onoff = space.uint_w(w_onoff)
                    option_ptr.c_keepalivetime = space.uint_w(w_time)
                    option_ptr.c_keepaliveinterval = space.uint_w(w_interval)

                res = _c.WSAIoctl(
                    self.fd, cmd, value_ptr, value_size,
                    rffi.NULL, 0, recv_ptr, rffi.NULL, rffi.NULL)
                if res < 0:
                    raise converted_error(space, rsocket.last_error())
            finally:
                if value_ptr:
                    lltype.free(value_ptr, flavor='raw')

            return space.wrap(recv_ptr[0])
        finally:
            lltype.free(recv_ptr, flavor='raw')
Beispiel #49
0
    def test_repr(self, space, api):
        """
        W_PyCMethodObject has a repr string which describes it as a method
        and gives its name and the name of its class.
        """
        def func(space, w_self, w_args):
            return space.w_None

        c_func = ApiFunction([PyObject, PyObject], PyObject, func)
        func.api_func = c_func
        ml = lltype.malloc(PyMethodDef, flavor='raw', zero=True)
        namebuf = rffi.str2charp('func')
        ml.c_ml_name = namebuf
        ml.c_ml_meth = rffi.cast(PyCFunction_typedef,
                                 c_func.get_llhelper(space))

        method = api.PyDescr_NewMethod(space.w_str, ml)
        assert repr(method).startswith(
            "<built-in method 'func' of 'str' object ")

        rffi.free_charp(namebuf)
        lltype.free(ml, flavor='raw')
Beispiel #50
0
def deflateInit(level=Z_DEFAULT_COMPRESSION,
                method=Z_DEFLATED,
                wbits=MAX_WBITS,
                memLevel=DEF_MEM_LEVEL,
                strategy=Z_DEFAULT_STRATEGY):
    """
    Allocate and return an opaque 'stream' object that can be used to
    compress data.
    """
    stream = lltype.malloc(z_stream, flavor='raw', zero=True)
    err = _deflateInit2(stream, level, method, wbits, memLevel, strategy)
    if err == Z_OK:
        return stream
    else:
        try:
            if err == Z_STREAM_ERROR:
                raise ValueError("Invalid initialization option")
            else:
                raise RZlibError.fromstream(
                    stream, err, "while creating compression object")
        finally:
            lltype.free(stream, flavor='raw')
Beispiel #51
0
 def test_varsized_struct(self):
     S = lltype.Struct('S', ('x', lltype.Signed),
                       ('a', lltype.Array(lltype.Char)))
     s1 = lltype.malloc(S, 6, flavor='raw')
     s1.x = 5
     s1.a[2] = 'F'
     sc = lltype2ctypes(s1, normalize=False)
     assert isinstance(sc.contents, ctypes.Structure)
     assert sc.contents.x == 5
     assert sc.contents.a.length == 6
     assert sc.contents.a.items[2] == ord('F')
     sc.contents.a.items[3] = ord('P')
     assert s1.a[3] == 'P'
     s1.a[1] = 'y'
     assert sc.contents.a.items[1] == ord('y')
     # now go back to lltype...
     res = ctypes2lltype(lltype.Ptr(S), sc)
     assert res == s1
     assert res.x == 5
     assert len(res.a) == 6
     lltype.free(s1, flavor='raw')
     assert not ALLOCATED  # detects memory leaks in the test
Beispiel #52
0
 def test_mousebutton_wheel(self):
     if not self.is_interactive:
         py.test.skip("interactive test only")
     print
     print "Press the given MouseButtons:"
     print "        Use Escape to pass tests."
     
     event_tests = [("left button",   RSDL.BUTTON_LEFT),
                    ("middle button", RSDL.BUTTON_MIDDLE),
                    ("right button",  RSDL.BUTTON_RIGHT),
                    ("scroll up",     RSDL.BUTTON_WHEELUP),
                    ("scroll down",   RSDL.BUTTON_WHEELDOWN)]
     test_success = []
     event = lltype.malloc(RSDL.Event, flavor='raw')
     try:
         for button_test in event_tests:
             print "    press %s:" % button_test[0]
             while True:
                 ok = RSDL.WaitEvent(event)
                 assert rffi.cast(lltype.Signed, ok) == 1
                 c_type = rffi.getintfield(event, 'c_type')
                 if c_type == RSDL.MOUSEBUTTONDOWN:
                     pass
                 elif c_type == RSDL.MOUSEBUTTONUP:
                     b = rffi.cast(RSDL.MouseButtonEventPtr, event)
                     if rffi.getintfield(b, 'c_button') == button_test[1]:
                         test_success.append(True)
                         break
                 elif c_type == RSDL.KEYUP:
                     p = rffi.cast(RSDL.KeyboardEventPtr, event)
                     if rffi.getintfield(p.c_keysym, 'c_sym') == RSDL.K_ESCAPE:
                         test_success.append(False) 
                         print "        manually aborted"
                         break
                     #break
         if False in test_success:
             py.test.fail("")
     finally:
         lltype.free(event, flavor='raw')
Beispiel #53
0
 def get_calldescr_ty_function_ptr(self, calldescr):
     if not calldescr.ty_function_ptr:
         #
         args_indices = calldescr.args_indices
         param_types = lltype.malloc(rffi.CArray(llvm_rffi.LLVMTypeRef),
                                     len(args_indices), flavor='raw')
         for i in range(len(args_indices)):
             param_types[i] = self.types_by_index[args_indices[i]]
         #
         res_index = calldescr.res_index
         if res_index < 0:
             ty_result = self.ty_void
         else:
             ty_result = self.types_by_index[res_index]
         #
         ty_func = llvm_rffi.LLVMFunctionType(ty_result, param_types,
                                              len(args_indices), 0)
         lltype.free(param_types, flavor='raw')
         ty_funcptr = llvm_rffi.LLVMPointerType(ty_func, 0)
         calldescr.ty_function_ptr = ty_funcptr
         #
     return calldescr.ty_function_ptr
Beispiel #54
0
 def test_with_explicit_length(self):
     A = lltype.Array(lltype.Signed)
     a1 = lltype.malloc(A, 5, flavor='raw')
     a1[0] = 42
     c1 = lltype2ctypes(a1, normalize=False)
     assert c1.contents.length == 5
     assert c1.contents.items[0] == 42
     res = ctypes2lltype(lltype.Ptr(A), c1)
     assert res == a1
     assert len(res) == 5
     assert res[0] == 42
     res[0] += 1
     assert c1.contents.items[0] == 43
     assert a1[0] == 43
     a1[0] += 2
     assert c1.contents.items[0] == 45
     assert a1[0] == 45
     c1.contents.items[0] += 3
     assert res[0] == 48
     assert a1[0] == 48
     lltype.free(a1, flavor='raw')
     assert not ALLOCATED  # detects memory leaks in the test
Beispiel #55
0
def flock(space, w_fd, op):
    """flock(fd, operation)

    Perform the lock operation op on file descriptor fd.  See the Unix
    manual flock(3) for details.  (On some systems, this function is
    emulated using fcntl().)"""

    fd = space.c_filedescriptor_w(w_fd)

    if has_flock:
        rv = c_flock(fd, op)
        if rv < 0:
            raise _get_error(space, "flock")
    else:
        l = _check_flock_op(space, op)
        rffi.setintfield(l, 'c_l_whence', 0)
        rffi.setintfield(l, 'c_l_start', 0)
        rffi.setintfield(l, 'c_l_len', 0)
        op = [F_SETLKW, F_SETLK][int(bool(op & LOCK_NB))]
        op = rffi.cast(rffi.INT, op)  # C long => C int
        fcntl_flock(fd, op, l)
        lltype.free(l, flavor='raw')
Beispiel #56
0
    def create(space, threaded, events):
        "Create a new environment object from scratch"
        mode = roci.OCI_OBJECT
        if threaded:
            mode |= roci.OCI_THREADED
        if events:
            mode |= roci.OCI_EVENTS

        handleptr = lltype.malloc(rffi.CArrayPtr(roci.OCIEnv).TO,
                                  1,
                                  flavor='raw')

        try:

            status = roci.OCIEnvNlsCreate(
                handleptr, mode, None, None, None, None, 0,
                lltype.nullptr(rffi.CArray(roci.dvoidp)), config.CHARSETID,
                config.CHARSETID)

            if not handleptr[0] or status not in (roci.OCI_SUCCESS,
                                                  roci.OCI_SUCCESS_WITH_INFO):
                raise OperationError(
                    get(space).w_InterfaceError,
                    space.wrap("Unable to acquire Oracle environment handle"))

            handle = handleptr[0]
        finally:
            lltype.free(handleptr, flavor='raw')

        try:
            newenv = Environment(space, handle)
        except:
            roci.OCIHandleFree(handle, roci.OCI_HTYPE_ENV)
            raise

        newenv.maxBytesPerCharacter = config.BYTES_PER_CHAR
        newenv.maxStringBytes = config.BYTES_PER_CHAR * config.MAX_STRING_CHARS
        return newenv
Beispiel #57
0
def test_blockbuildermixin(translated=True):
    mc = BlockBuilderMixin(translated)
    writtencode = []
    for i in range(mc.SUBBLOCK_SIZE * 2 + 3):
        assert mc.get_relative_pos() == i
        mc.writechar(chr(i % 255))
        writtencode.append(chr(i % 255))
    if translated:
        assert mc._cursubindex == 3
        assert mc._cursubblock
        assert mc._cursubblock.prev
        assert mc._cursubblock.prev.prev
        assert not mc._cursubblock.prev.prev.prev
    #
    for i in range(0, mc.SUBBLOCK_SIZE * 2 + 3, 2):
        mc.overwrite(i, chr((i + 63) % 255))
        writtencode[i] = chr((i + 63) % 255)
    #
    p = lltype.malloc(rffi.CCHARP.TO, mc.SUBBLOCK_SIZE * 2 + 3, flavor='raw')
    addr = rffi.cast(lltype.Signed, p)
    mc.copy_to_raw_memory(addr)
    #
    for i in range(mc.SUBBLOCK_SIZE * 2 + 3):
        assert p[i] == writtencode[i]
    #
    debug._log = debug.DebugLog()
    try:
        mc._dump(addr, 'test-logname-section')
        log = list(debug._log)
    finally:
        debug._log = None
    encoded = ''.join(writtencode).encode('hex').upper()
    ataddr = '@%x' % addr
    assert log == [('test-logname-section',
                    [('debug_print', 'SYS_EXECUTABLE', '??'),
                     ('debug_print', 'CODE_DUMP', ataddr, '+0 ', encoded)])]

    lltype.free(p, flavor='raw')
Beispiel #58
0
    def llimpl_FormatError(code):
        "Return a message corresponding to the given Windows error code."
        buf = lltype.malloc(rffi.CCHARPP.TO, 1, flavor='raw')

        try:
            msglen = FormatMessage(
                FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
                None, rffi.cast(DWORD, code), DEFAULT_LANGUAGE,
                rffi.cast(rffi.CCHARP, buf), 0, None)

            if msglen <= 2:  # includes the case msglen < 0
                return fake_FormatError(code)

            # FormatMessage always appends \r\n.
            buflen = intmask(msglen - 2)
            assert buflen > 0

            result = rffi.charpsize2str(buf[0], buflen)
            LocalFree(rffi.cast(rffi.VOIDP, buf[0]))
        finally:
            lltype.free(buf, flavor='raw')

        return result
Beispiel #59
0
    def _performDefine(self):
        # determine number of items in select-list
        attrptr = lltype.malloc(rffi.CArrayPtr(roci.ub4).TO, 1, flavor='raw')
        try:
            status = roci.OCIAttrGet(self.handle, roci.OCI_HTYPE_STMT,
                                     rffi.cast(roci.dvoidp, attrptr),
                                     lltype.nullptr(roci.Ptr(roci.ub4).TO),
                                     roci.OCI_ATTR_PARAM_COUNT,
                                     self.environment.errorHandle)

            self.environment.checkForError(status, "Cursor_PerformDefine()")
            numParams = attrptr[0]
        finally:
            lltype.free(attrptr, flavor='raw')

        self.fetchVariables = []

        # define a variable for each select-item
        self.fetchArraySize = self.arraySize
        for i in range(numParams):
            var = interp_variable.define(self, i + 1, self.fetchArraySize)
            assert isinstance(var, interp_variable.W_Variable)
            self.fetchVariables.append(var)
Beispiel #60
0
    def _setRowCount(self):
        if self.statementType == roci.OCI_STMT_SELECT:
            self.rowCount = 0
            self.actualRows = -1
            self.rowNum = 0
        elif self.statementType in (roci.OCI_STMT_INSERT, roci.OCI_STMT_UPDATE,
                                    roci.OCI_STMT_DELETE):
            attrptr = lltype.malloc(rffi.CArrayPtr(roci.ub4).TO,
                                    1,
                                    flavor='raw')
            try:
                status = roci.OCIAttrGet(self.handle, roci.OCI_HTYPE_STMT,
                                         rffi.cast(roci.dvoidp, attrptr),
                                         lltype.nullptr(roci.Ptr(roci.ub4).TO),
                                         roci.OCI_ATTR_ROW_COUNT,
                                         self.environment.errorHandle)

                self.environment.checkForError(status, "Cursor_SetRowCount()")
                self.rowCount = rffi.cast(lltype.Signed, attrptr[0])
            finally:
                lltype.free(attrptr, flavor='raw')
        else:
            self.rowCount = -1