Пример #1
0
 def runs_ctgetstr():
     p_errret = lltype.malloc(rffi.INTP.TO, 1, flavor='raw')
     with rffi.scoped_str2charp("xterm") as ll_term:
         errval = fficurses.setupterm(ll_term, 1, p_errret)
     with rffi.scoped_str2charp("cup") as ll_capname:
         ll = fficurses.rpy_curses_tigetstr(ll_capname)
         return rffi.charp2str(ll)
Пример #2
0
    def test_encode_decimal(self, space, api):
        with rffi.scoped_unicode2wcharp(u' (12, 35 ABC)') as u:
            with rffi.scoped_alloc_buffer(20) as buf:
                res = api.PyUnicode_EncodeDecimal(u, 13, buf.raw, None)
                s = rffi.charp2str(buf.raw)
        assert res == 0
        assert s == ' (12, 35 ABC)'

        with rffi.scoped_unicode2wcharp(u' (12, \u1234\u1235)') as u:
            with rffi.scoped_alloc_buffer(20) as buf:
                res = api.PyUnicode_EncodeDecimal(u, 9, buf.raw, None)
        assert res == -1
        api.PyErr_Clear()

        with rffi.scoped_unicode2wcharp(u' (12, \u1234\u1235)') as u:
            with rffi.scoped_alloc_buffer(20) as buf:
                with rffi.scoped_str2charp("replace") as errors:
                    res = api.PyUnicode_EncodeDecimal(u, 9, buf.raw, errors)
                s = rffi.charp2str(buf.raw)
        assert res == 0
        assert s == " (12, ??)"

        with rffi.scoped_unicode2wcharp(u'12\u1234') as u:
            with rffi.scoped_alloc_buffer(20) as buf:
                with rffi.scoped_str2charp("xmlcharrefreplace") as errors:
                    res = api.PyUnicode_EncodeDecimal(u, 3, buf.raw, errors)
                s = rffi.charp2str(buf.raw)
        assert res == 0
        assert s == "12ሴ"
Пример #3
0
    def test_encode_decimal(self, space):
        with rffi.scoped_unicode2wcharp(u' (12, 35 ABC)') as u:
            with rffi.scoped_alloc_buffer(20) as buf:
                res = PyUnicode_EncodeDecimal(space, u, 13, buf.raw, None)
                s = rffi.charp2str(buf.raw)
        assert res == 0
        assert s == ' (12, 35 ABC)'

        with rffi.scoped_unicode2wcharp(u' (12, \u1234\u1235)') as u:
            with rffi.scoped_alloc_buffer(20) as buf:
                with pytest.raises(OperationError):
                    PyUnicode_EncodeDecimal(space, u, 9, buf.raw, None)

        with rffi.scoped_unicode2wcharp(u' (12, \u1234\u1235)') as u:
            with rffi.scoped_alloc_buffer(20) as buf:
                with rffi.scoped_str2charp("replace") as errors:
                    res = PyUnicode_EncodeDecimal(space, u, 9, buf.raw, errors)
                s = rffi.charp2str(buf.raw)
        assert res == 0
        assert s == " (12, ??)"

        with rffi.scoped_unicode2wcharp(u'12\u1234') as u:
            with rffi.scoped_alloc_buffer(20) as buf:
                with rffi.scoped_str2charp("xmlcharrefreplace") as errors:
                    res = PyUnicode_EncodeDecimal(space, u, 3, buf.raw, errors)
                s = rffi.charp2str(buf.raw)
        assert res == 0
        assert s == "12ሴ"
Пример #4
0
def spawn(loop, process, file, args, env, streams):
    """
    The file descriptor list should be a list of streams to wire up to FDs in
    the child. A None stream is mapped to UV_IGNORE.
    """

    with rffi.scoped_str2charp(file) as rawFile:
        rawArgs = rffi.liststr2charpp(args)
        rawEnv = rffi.liststr2charpp(env)
        with rffi.scoped_str2charp(".") as rawCWD:
            options = rffi.make(cConfig["process_options_t"], c_file=rawFile,
                                c_args=rawArgs, c_env=rawEnv, c_cwd=rawCWD)
            with lltype.scoped_alloc(rffi.CArray(stdio_container_t),
                                     len(streams)) as rawStreams:
                for i, stream in enumerate(streams):
                    if stream == lltype.nullptr(stream_t):
                        flags = UV_IGNORE
                    else:
                        flags = UV_CREATE_PIPE
                        if i == 0:
                            flags |= UV_READABLE_PIPE
                        elif i in (1, 2):
                            flags |= UV_WRITABLE_PIPE
                        set_stdio_stream(rawStreams[i], stream)
                    rffi.setintfield(rawStreams[i], "c_flags", flags)
                options.c_stdio = rawStreams
                rffi.setintfield(options, "c_stdio_count", len(streams))
                add_exit_cb(options, processDiscard)
                rffi.setintfield(options, "c_flags", UV_PROCESS_WINDOWS_HIDE)
                rv = uv_spawn(loop, process, options)
                free(options)
        rffi.free_charpp(rawEnv)
        rffi.free_charpp(rawArgs)

    check("spawn", rv)
Пример #5
0
    def test_encode_decimal(self, space, api):
        with rffi.scoped_unicode2wcharp(u' (12, 35 ABC)') as u:
            with rffi.scoped_alloc_buffer(20) as buf:
                res = api.PyUnicode_EncodeDecimal(u, 13, buf.raw, None)
                s = rffi.charp2str(buf.raw)
        assert res == 0
        assert s == ' (12, 35 ABC)'

        with rffi.scoped_unicode2wcharp(u' (12, \u1234\u1235)') as u:
            with rffi.scoped_alloc_buffer(20) as buf:
                res = api.PyUnicode_EncodeDecimal(u, 9, buf.raw, None)
        assert res == -1
        api.PyErr_Clear()

        with rffi.scoped_unicode2wcharp(u' (12, \u1234\u1235)') as u:
            with rffi.scoped_alloc_buffer(20) as buf:
                with rffi.scoped_str2charp("replace") as errors:
                    res = api.PyUnicode_EncodeDecimal(u, 9, buf.raw,
                                                      errors)
                s = rffi.charp2str(buf.raw)
        assert res == 0
        assert s == " (12, ??)"

        with rffi.scoped_unicode2wcharp(u'12\u1234') as u:
            with rffi.scoped_alloc_buffer(20) as buf:
                with rffi.scoped_str2charp("xmlcharrefreplace") as errors:
                    res = api.PyUnicode_EncodeDecimal(u, 3, buf.raw,
                                                      errors)
                s = rffi.charp2str(buf.raw)
        assert res == 0
        assert s == "12ሴ"
Пример #6
0
Файл: ruv.py Проект: dckc/typhon
def spawn(loop, process, file, args, env, streams):
    """
    The file descriptor list should be a list of streams to wire up to FDs in
    the child. A None stream is mapped to UV_IGNORE.
    """

    with rffi.scoped_str2charp(file) as rawFile:
        rawArgs = rffi.liststr2charpp(args)
        rawEnv = rffi.liststr2charpp(env)
        with rffi.scoped_str2charp(".") as rawCWD:
            options = rffi.make(cConfig["process_options_t"], c_file=rawFile,
                                c_args=rawArgs, c_env=rawEnv, c_cwd=rawCWD)
            with lltype.scoped_alloc(rffi.CArray(stdio_container_t), len(streams)) as rawStreams:
                for i, stream in enumerate(streams):
                    if stream == lltype.nullptr(stream_t):
                        flags = UV_IGNORE
                    else:
                        flags = UV_CREATE_PIPE
                        if i == 0:
                            flags |= UV_READABLE_PIPE
                        elif i in (1, 2):
                            flags |= UV_WRITABLE_PIPE
                        set_stdio_stream(rawStreams[i], stream)
                    rffi.setintfield(rawStreams[i], "c_flags", flags)
                options.c_stdio = rawStreams
                rffi.setintfield(options, "c_stdio_count", len(streams))
                add_exit_cb(options, processDiscard)
                rffi.setintfield(options, "c_flags", UV_PROCESS_WINDOWS_HIDE)
                rv = uv_spawn(loop, process, options)
                free(options)
        rffi.free_charpp(rawEnv)
        rffi.free_charpp(rawArgs)

    check("spawn", rv)
Пример #7
0
 def runs_tparm():
     with rffi.scoped_str2charp("xterm") as ll_term:
         fficurses.rpy_curses_setupterm(ll_term, 1)
     with rffi.scoped_str2charp("cup") as ll_capname:
         cup = fficurses.rpy_curses_tigetstr(ll_capname)
         res = fficurses.rpy_curses_tparm(cup, 5, 3, 0, 0, 0, 0, 0, 0,
                                          0)
         return rffi.charp2str(res)
Пример #8
0
 def test_charp(self):
     sb = StringBuilderRepr.ll_new(32)
     with rffi.scoped_str2charp("hello world") as p:
         StringBuilderRepr.ll_append_charpsize(sb, p, 12)
     with rffi.scoped_str2charp("0123456789abcdefghijklmn") as p:
         StringBuilderRepr.ll_append_charpsize(sb, p, 24)
     s = StringBuilderRepr.ll_build(sb)
     assert hlstr(s) == "hello world\x000123456789abcdefghijklmn"
Пример #9
0
 def test_charp(self):
     sb = StringBuilderRepr.ll_new(32)
     with rffi.scoped_str2charp("hello world") as p:
         StringBuilderRepr.ll_append_charpsize(sb, p, 12)
     with rffi.scoped_str2charp("0123456789abcdefghijklmn") as p:
         StringBuilderRepr.ll_append_charpsize(sb, p, 24)
     s = StringBuilderRepr.ll_build(sb)
     assert hlstr(s) == "hello world\x000123456789abcdefghijklmn"
Пример #10
0
    def test_addmodule(self, space, api):
        with rffi.scoped_str2charp("sys") as modname:
            w_sys = api.PyImport_AddModule(modname)
        assert w_sys is space.sys

        with rffi.scoped_str2charp("foobar") as modname:
            w_foobar = api.PyImport_AddModule(modname)
        assert space.str_w(space.getattr(w_foobar,
                                         space.wrap('__name__'))) == 'foobar'
Пример #11
0
 def test_unpack(self, space, api):
     with rffi.scoped_str2charp("\x9a\x99\x99?") as ptr:
         assert abs(api._PyFloat_Unpack4(ptr, 1) - 1.2) < 1e-7
     with rffi.scoped_str2charp("?\x99\x99\x9a") as ptr:
         assert abs(api._PyFloat_Unpack4(ptr, 0) - 1.2) < 1e-7
     with rffi.scoped_str2charp("\x1f\x85\xebQ\xb8\x1e\t@") as ptr:
         assert abs(api._PyFloat_Unpack8(ptr, 1) - 3.14) < 1e-15
     with rffi.scoped_str2charp("@\t\x1e\xb8Q\xeb\x85\x1f") as ptr:
         assert abs(api._PyFloat_Unpack8(ptr, 0) - 3.14) < 1e-15
Пример #12
0
 def test_unpack(self, space):
     with rffi.scoped_str2charp("\x9a\x99\x99?") as ptr:
         assert abs(_PyFloat_Unpack4(space, ptr, 1) - 1.2) < 1e-7
     with rffi.scoped_str2charp("?\x99\x99\x9a") as ptr:
         assert abs(_PyFloat_Unpack4(space, ptr, 0) - 1.2) < 1e-7
     with rffi.scoped_str2charp("\x1f\x85\xebQ\xb8\x1e\t@") as ptr:
         assert abs(_PyFloat_Unpack8(space, ptr, 1) - 3.14) < 1e-15
     with rffi.scoped_str2charp("@\t\x1e\xb8Q\xeb\x85\x1f") as ptr:
         assert abs(_PyFloat_Unpack8(space, ptr, 0) - 3.14) < 1e-15
Пример #13
0
    def test_addmodule(self, space):
        with rffi.scoped_str2charp("sys") as modname:
            w_sys = PyImport_AddModule(space, modname)
        assert w_sys is space.sys

        with rffi.scoped_str2charp("foobar") as modname:
            w_foobar = PyImport_AddModule(space, modname)
        assert space.str_w(space.getattr(w_foobar,
                                         space.wrap('__name__'))) == 'foobar'
Пример #14
0
 def test_file_fromfile(self, space, api):
     name = str(udir / "_test_file")
     with rffi.scoped_str2charp(name) as filename:
         with rffi.scoped_str2charp("wb") as mode:
             w_file = api.PyFile_FromString(filename, mode)
             fp = api.PyFile_AsFile(w_file)
             assert fp is not None
             w_file2 = api.PyFile_FromFile(fp, filename, mode, None)
     assert w_file2 is not None
     assert PyFile_Check(space, w_file2)
     assert space.str_w(api.PyFile_Name(w_file2)) == name
Пример #15
0
 def test_file_fromfile(self, space, api):
     name = str(udir / "_test_file")
     with rffi.scoped_str2charp(name) as filename:
         with rffi.scoped_str2charp("wb") as mode:
             w_file = api.PyFile_FromString(filename, mode)
             fp = api.PyFile_AsFile(w_file)
             assert fp is not None
             w_file2 = api.PyFile_FromFile(fp, filename, mode, None)
     assert w_file2 is not None
     assert api.PyFile_Check(w_file2)
     assert space.str_w(api.PyFile_Name(w_file2)) == name
Пример #16
0
def boxSeal(message, nonce, public, secret):
    cipherSize = len(message) + intmask(cryptoBoxMacbytes())

    with rffi.scoped_alloc_buffer(cipherSize) as cipher:
        with rffi.scoped_str2charp(message) as rawMessage:
            with rffi.scoped_str2charp(nonce) as rawNonce:
                with rffi.scoped_str2charp(public) as rawPublic:
                    with rffi.scoped_str2charp(secret) as rawSecret:
                        rv = cryptoBoxEasy(cipher.raw, rawMessage,
                                           len(message), rawNonce, rawPublic,
                                           rawSecret)
                        if rv:
                            raise SodiumError("crypto_box_easy: %d" % rv)
                        return cipher.str(cipherSize)
Пример #17
0
def boxUnseal(cipher, nonce, public, secret):
    messageSize = len(cipher) - intmask(cryptoBoxMacbytes())
    assert messageSize >= 0

    with rffi.scoped_alloc_buffer(messageSize) as message:
        with rffi.scoped_str2charp(cipher) as rawCipher:
            with rffi.scoped_str2charp(nonce) as rawNonce:
                with rffi.scoped_str2charp(public) as rawPublic:
                    with rffi.scoped_str2charp(secret) as rawSecret:
                        rv = cryptoBoxOpenEasy(message.raw, rawCipher,
                                               len(cipher), rawNonce,
                                               rawPublic, rawSecret)
                        if rv:
                            raise SodiumError("crypto_box_open_easy: %d" % rv)
                        return message.str(messageSize)
Пример #18
0
def str_interval_to_time(s):
    if len(s) == 0:
        raise IntervalToTimeException
    with rffi.scoped_str2charp(s) as ll_s:

        error_c = lltype.malloc(timelib_error_containerP.TO, 1, flavor='raw')

        ll_res = timelib_strtotime(ll_s, len(s), error_c, timelib_builtin_db(),
                                   tzinfo_callback)

        error_count = rffi.cast(lltype.Signed, error_c[0].c_error_count)
        error = error_c[0]

        lltype.free(error_c, flavor='raw')

        if error_count != 0:
            if DEBUG:
                print(
                    rffi.charp2str(error.c_error_messages[0].c_message), "at",
                    rffi.cast(lltype.Signed,
                              error.c_error_messages[0].c_position))
            timelib_error_container_dtor(error)
            raise IntervalToTimeException
        if rffi.cast(lltype.Signed, error.c_warning_count) != 0:
            pass

        res = (ll_res.c_relative.c_y, ll_res.c_relative.c_m,
               ll_res.c_relative.c_d, ll_res.c_relative.c_h,
               ll_res.c_relative.c_i, ll_res.c_relative.c_s)

        timelib_error_container_dtor(error)
        timelib_time_dtor(ll_res)
        return res
Пример #19
0
 def setsockopt(self, level, option, value):
     with rffi.scoped_str2charp(value) as buf:
         res = _c.socketsetsockopt(self.fd, level, option,
                                   rffi.cast(rffi.VOIDP, buf),
                                   len(value))
         if res < 0:
             raise self.error_handler()
Пример #20
0
def setupterm(space, w_termname=None, fd=-1):
    _fd = fd
    if fd == -1:
        w_stdout = space.getattr(space.getbuiltinmodule('sys'),
                                 space.newtext('stdout'))
        _fd = space.int_w(
            space.call_function(
                space.getattr(w_stdout, space.newtext('fileno'))))
    if space.is_none(w_termname):
        termname = None
        termname_err = 'None'
    else:
        termname = space.text_w(w_termname)
        termname_err = "'%s'" % termname

    p_errret = lltype.malloc(rffi.INTP.TO, 1, flavor='raw')
    try:
        with rffi.scoped_str2charp(termname) as ll_term:
            _fd = rffi.cast(rffi.INT, _fd)
            errval = fficurses.setupterm(ll_term, _fd, p_errret)

        if errval == -1:
            errret = widen(p_errret[0])
            if errret == 0:
                msg_ext = 'could not find terminal'
            elif errret == -1:
                msg_ext = 'could not find termininfo database'
            else:
                msg_ext = 'unknown error'
            msg = ("setupterm(%s, %d) failed (err=%d): %s" %
                   (termname_err, fd, errret, msg_ext))
            raise curses_error(space, msg)
    finally:
        lltype.free(p_errret, flavor='raw')
    space.fromcache(ModuleInfo).setupterm_called = True
Пример #21
0
def spawn(loop, process, file, args, env):
    with rffi.scoped_str2charp(file) as rawFile:
        rawArgs = rffi.liststr2charpp(args)
        rawEnv = rffi.liststr2charpp(env)
        with rffi.scoped_str2charp(".") as rawCWD:
            options = rffi.make(cConfig["process_options_t"], c_file=rawFile,
                                c_args=rawArgs, c_env=rawEnv, c_cwd=rawCWD)
            add_exit_cb(options, processDiscard)
            rffi.setintfield(options, "c_flags", UV_PROCESS_WINDOWS_HIDE)
            rffi.setintfield(options, "c_stdio_count", 0)
            rv = uv_spawn(loop, process, options)
            free(options)
        rffi.free_charpp(rawEnv)
        rffi.free_charpp(rawArgs)

    check("spawn", rv)
Пример #22
0
def spawn(loop, process, file, args, env):
    with rffi.scoped_str2charp(file) as rawFile:
        rawArgs = rffi.liststr2charpp(args)
        rawEnv = rffi.liststr2charpp(env)
        with rffi.scoped_str2charp(".") as rawCWD:
            options = rffi.make(cConfig["process_options_t"], c_file=rawFile,
                                c_args=rawArgs, c_env=rawEnv, c_cwd=rawCWD)
            add_exit_cb(options, processDiscard)
            rffi.setintfield(options, "c_flags", UV_PROCESS_WINDOWS_HIDE)
            rffi.setintfield(options, "c_stdio_count", 0)
            rv = uv_spawn(loop, process, options)
            free(options)
        rffi.free_charpp(rawEnv)
        rffi.free_charpp(rawArgs)

    check("spawn", rv)
Пример #23
0
def SetValue(space, w_hkey, w_subkey, typ, value):
    """SetValue(key, sub_key, type, value) - Associates a value with a specified key.

key is an already open key, or any one of the predefined HKEY_* constants.
sub_key is a string that names the subkey with which the value is associated.
type is an integer that specifies the type of the data.  Currently this
 must be REG_SZ, meaning only strings are supported.
value is a string that specifies the new value.

If the key specified by the sub_key parameter does not exist, the SetValue
function creates it.

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.

The key identified by the key parameter must have been opened with
KEY_SET_VALUE access."""
    if typ != rwinreg.REG_SZ:
        errstring = space.wrap("Type must be _winreg.REG_SZ")
        raise OperationError(space.w_ValueError, errstring)
    hkey = hkey_w(w_hkey, space)
    if space.is_w(w_subkey, space.w_None):
        subkey = None
    else:
        subkey = space.str_w(w_subkey)
    with rffi.scoped_str2charp(value) as dataptr:
        ret = rwinreg.RegSetValue(hkey, subkey, rwinreg.REG_SZ, dataptr, len(value))
        if ret != 0:
            raiseWindowsError(space, ret, 'RegSetValue')
Пример #24
0
def temp_file(vm):
    mod = vm.get_funcs_mod()
    file_class = type_check_class(vm, mod.get_defn(vm, "File"))
    vm.decode_args()

    if HAS_MKSTEMP:
        #tmpdir = None
        #if os.environ.has_key("TMPDIR"):
        #    tmpdir = os.environ["TMPDIR"]
        #if tmpdir is None:
        #    tmpdir = "/tmp"
        tmpp = "/tmp/tmp.XXXXXXXXXX"
        with rffi.scoped_str2charp(tmpp) as buf:
            fd = mkstemp(buf)
            tmpp = rffi.charp2str(buf)

        if fd == -1:
            _errno_raise(vm, Con_String(vm, tmpp))

        f = fdopen(fd, "w+")
        if not f:
            _errno_raise(vm, Con_String(vm, tmpp))

        return File(vm, file_class, Con_String(vm, tmpp), f)
    else:
        raise Exception("XXX")
Пример #25
0
 def setsockopt(self, level, option, value):
     with rffi.scoped_str2charp(value) as buf:
         res = _c.socketsetsockopt(self.fd, level, option,
                                   rffi.cast(rffi.VOIDP, buf),
                                   len(value))
         if res < 0:
             raise self.error_handler()
Пример #26
0
def temp_file(vm):
    mod = vm.get_funcs_mod()
    file_class = type_check_class(vm, mod.get_defn(vm, "File"))
    vm.decode_args()
    
    if HAS_MKSTEMP:
        #tmpdir = None
        #if os.environ.has_key("TMPDIR"):
        #    tmpdir = os.environ["TMPDIR"]
        #if tmpdir is None:
        #    tmpdir = "/tmp"
        tmpp = "/tmp/tmp.XXXXXXXXXX"
        with rffi.scoped_str2charp(tmpp) as buf:
            fd = mkstemp(buf)
            tmpp = rffi.charp2str(buf)
           
        if fd == -1:
            _errno_raise(vm, Con_String(vm, tmpp))
        
        f = fdopen(fd, "w+")
        if not f:
            _errno_raise(vm, Con_String(vm, tmpp))
        
        return File(vm, file_class, Con_String(vm, tmpp), f)
    else:
        raise Exception("XXX")
Пример #27
0
def SetValue(space, w_hkey, w_subkey, typ, value):
    """SetValue(key, sub_key, type, value) - Associates a value with a specified key.

key is an already open key, or any one of the predefined HKEY_* constants.
sub_key is a string that names the subkey with which the value is associated.
type is an integer that specifies the type of the data.  Currently this
 must be REG_SZ, meaning only strings are supported.
value is a string that specifies the new value.

If the key specified by the sub_key parameter does not exist, the SetValue
function creates it.

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.

The key identified by the key parameter must have been opened with
KEY_SET_VALUE access."""
    if typ != rwinreg.REG_SZ:
        raise oefmt(space.w_ValueError, "Type must be _winreg.REG_SZ")
    hkey = hkey_w(w_hkey, space)
    if space.is_w(w_subkey, space.w_None):
        subkey = None
    else:
        subkey = space.text_w(w_subkey)
    with rffi.scoped_str2charp(value) as dataptr:
        ret = rwinreg.RegSetValueA(hkey, subkey, rwinreg.REG_SZ, dataptr,
                                   len(value))
        if ret != 0:
            raiseWindowsError(space, ret, 'RegSetValue')
Пример #28
0
 def sqlite3_result_text(self, s):
     self.invalidate_cache()
     with rffi.scoped_str2charp(s) as charp:
         capi.sqlite3VdbeMemSetStr(
             self.pMem, charp, len(s),
             CConfig.SQLITE_UTF8,
             rffi.cast(rffi.VOIDP, CConfig.SQLITE_TRANSIENT))
Пример #29
0
 def __init__(self, ffi, filename, flags):
     with rffi.scoped_str2charp(filename) as ll_libname:
         if filename is None:
             filename = "<None>"
         try:
             handle = dlopen(ll_libname, flags)
         except DLOpenError, e:
             raise wrap_dlopenerror(ffi.space, e, filename)
Пример #30
0
 def prepare(self, query, use_flag_cache):
     length = len(query)
     with rffi.scoped_str2charp(query) as query, lltype.scoped_alloc(rffi.VOIDPP.TO, 1) as result, lltype.scoped_alloc(rffi.CCHARPP.TO, 1) as unused_buffer:
         errorcode = capi.sqlite3_prepare_v2(rffi.cast(rffi.VOIDP, self.db), query, length, result, unused_buffer)
         if not errorcode == 0:
             raise SqliteException(errorcode, rffi.charp2str(capi.sqlite3_errmsg(self.db)))
         self.p = rffi.cast(capi.VDBEP, result[0])
     self._init_python_data(use_flag_cache)
Пример #31
0
 def __init__(self, ffi, filename, flags):
     with rffi.scoped_str2charp(filename) as ll_libname:
         if filename is None:
             filename = "<None>"
         try:
             handle = dlopen(ll_libname, flags)
         except DLOpenError, e:
             raise wrap_dlopenerror(ffi.space, e, filename)
Пример #32
0
 def test_file_writestring(self, space, api, capfd):
     w_stdout = space.sys.get("stdout")
     with rffi.scoped_str2charp("test\n") as s:
         api.PyFile_WriteString(s, w_stdout)
     space.call_method(w_stdout, "flush")
     out, err = capfd.readouterr()
     out = out.replace('\r\n', '\n')
     assert out == "test\n"
Пример #33
0
 def test_file_writestring(self, space, api, capfd):
     w_stdout = space.sys.get("stdout")
     with rffi.scoped_str2charp("test\n") as s:
         api.PyFile_WriteString(s, w_stdout)
     space.call_method(w_stdout, "flush")
     out, err = capfd.readouterr()
     out = out.replace('\r\n', '\n')
     assert out == "test\n"
Пример #34
0
def tigetstr(space, capname):
    check_setup_invoked(space)
    with rffi.scoped_str2charp(capname) as ll_capname:
        ll_result = fficurses.rpy_curses_tigetstr(ll_capname)
        if ll_result:
            return space.newbytes(rffi.charp2str(ll_result))
        else:
            return space.w_None
Пример #35
0
 def bind_str(self, i, s):
     self.invalidate_caches_outside()
     with rffi.scoped_str2charp(s) as charp:
         return rffi.cast(
             lltype.Signed,
             capi.sqlite3_bind_text(
                 self.p, i, charp, len(s),
                 rffi.cast(rffi.VOIDP, CConfig.SQLITE_TRANSIENT)))
Пример #36
0
def spawn(loop, process, file, args, env, streams):
    """
    The file descriptor list should be a list of streams to wire up to FDs in
    the child. A None stream is mapped to UV_IGNORE.
    """

    with rffi.scoped_str2charp(file) as rawFile:
        rawArgs = rffi.liststr2charpp(args)
        rawEnv = rffi.liststr2charpp(env)
        with rffi.scoped_str2charp(".") as rawCWD:
            options = rffi.make(cConfig["process_options_t"], c_file=rawFile,
                                c_args=rawArgs, c_env=rawEnv, c_cwd=rawCWD)
            with lltype.scoped_alloc(rffi.CArray(stdio_container_t),
                                     len(streams)) as rawStreams:
                for i, stream in enumerate(streams):
                    if stream == lltype.nullptr(stream_t):
                        flags = UV_IGNORE
                    else:
                        flags = UV_CREATE_PIPE
                        if i == 0:
                            flags |= UV_READABLE_PIPE
                        elif i in (1, 2):
                            flags |= UV_WRITABLE_PIPE
                        if not we_are_translated():
                            # doing extra allocations here to work around ll2ctypes'
                            # desire to gratuitously copy arrays
                            with lltype.scoped_alloc(stdio_container_t) as con:
                                set_stdio_stream(con, stream)
                                for field in rawStreams[i]._T._names:
                                    setattr(rawStreams[i], field, getattr(con, field))
                        else:
                            set_stdio_stream(rawStreams[i], stream)
                    rffi.setintfield(rawStreams[i], "c_flags", flags)
                options.c_stdio = rawStreams
                rffi.setintfield(options, "c_stdio_count", len(streams))
                add_exit_cb(options, processDiscard)

                # On Windows, ask to *not* have one of those annoying
                # console/terminal windows pop up. ~ C.
                rffi.setintfield(options, "c_flags", UV_PROCESS_WINDOWS_HIDE)
                rv = uv_spawn(loop, process, options)
                free(options)
        rffi.free_charpp(rawEnv)
        rffi.free_charpp(rawArgs)

    check("spawn", rv)
Пример #37
0
    def RAND_add(space, string, entropy):
        """RAND_add(string, entropy)


        Mix string into the OpenSSL PRNG state.  entropy (a float) is a lower
        bound on the entropy contained in string."""
        with rffi.scoped_str2charp(string) as buf:
            libssl_RAND_add(buf, len(string), entropy)
Пример #38
0
    def RAND_add(space, string, entropy):
        """RAND_add(string, entropy)


        Mix string into the OpenSSL PRNG state.  entropy (a float) is a lower
        bound on the entropy contained in string."""
        with rffi.scoped_str2charp(string) as buf:
            libssl_RAND_add(buf, len(string), entropy)
Пример #39
0
def initialize_timezone_info(tz_name):
    tzi = TimeZoneInfo(tz_name is None)
    with rffi.scoped_str2charp("UTC") as ll_s:
        ll_tzi = timelib.timelib_parse_tzfile(
            ll_s, timelib.timelib_builtin_db())
    if not ll_tzi:
        raise Exception("failed to initialize timezone")
    tzi.timezone = tz_name
    tzi.utc_tzi = ll_tzi
    if tz_name is None:
        tzi.timezone = 'UTC'
        return tzi
    with rffi.scoped_str2charp(tz_name) as ll_s:
        ll_tzi = timelib.timelib_parse_tzfile(
            ll_s, timelib.timelib_builtin_db())
    if not ll_tzi:
        raise Exception("failed to initialize timezone")
    tzi.local_tzi = ll_tzi
    return tzi
Пример #40
0
 def __init__(self, ffi, filename, flags):
     with rffi.scoped_str2charp(filename) as ll_libname:
         if filename is None:
             filename = "<None>"
         try:
             handle = dlopen(ll_libname, flags)
         except DLOpenError as e:
             raise wrap_dlopenerror(ffi.space, e, filename)
     W_LibObject.__init__(self, ffi, filename)
     self.libhandle = handle
     self.register_finalizer(ffi.space)
Пример #41
0
 def test_encode_fsdefault(self, space, api):
     w_u = space.wrap(u'späm')
     w_s = api.PyUnicode_EncodeFSDefault(w_u)
     if w_s is None:
         api.PyErr_Clear()
         py.test.skip("Requires a unicode-aware fsencoding")
     with rffi.scoped_str2charp(space.str_w(w_s)) as encoded:
         w_decoded = api.PyUnicode_DecodeFSDefaultAndSize(encoded, space.len_w(w_s))
         assert space.eq_w(w_decoded, w_u)
         w_decoded = api.PyUnicode_DecodeFSDefault(encoded)
         assert space.eq_w(w_decoded, w_u)
Пример #42
0
def _glob(pattern, flags):
    ll_glob_t = lltype.malloc(PTR_GLOB_T.TO, flavor='raw')
    files = []
    with rffi.scoped_str2charp(pattern) as ll_pattern:
        ll_res = c_glob(ll_pattern, flags, lltype.nullptr(callback.TO),
                        ll_glob_t)
        num = intmask(ll_glob_t.c_gl_pathc)
        for i in range(num):
            fname = rffi.charp2str(ll_glob_t.c_gl_pathv[i])
            files.append(fname)
    return ll_res, files
Пример #43
0
 def __init__(self, ffi, filename, flags):
     with rffi.scoped_str2charp(filename) as ll_libname:
         if filename is None:
             filename = "<None>"
         try:
             handle = dlopen(ll_libname, flags)
         except DLOpenError as e:
             raise wrap_dlopenerror(ffi.space, e, filename)
     W_LibObject.__init__(self, ffi, filename)
     self.libhandle = handle
     self.register_finalizer(ffi.space)
Пример #44
0
def _glob(pattern, flags):
    ll_glob_t = lltype.malloc(PTR_GLOB_T.TO, flavor='raw')
    files = []
    with rffi.scoped_str2charp(pattern) as ll_pattern:
        ll_res = c_glob(ll_pattern, flags, lltype.nullptr(callback.TO),
                        ll_glob_t)
        num = intmask(ll_glob_t.c_gl_pathc)
        for i in range(num):
            fname = rffi.charp2str(ll_glob_t.c_gl_pathv[i])
            files.append(fname)
    return ll_res, files
Пример #45
0
 def __init__(self, space, filename, flags):
     self.space = space
     with rffi.scoped_str2charp(filename) as ll_libname:
         if filename is None:
             filename = "<None>"
         try:
             self.handle = dlopen(ll_libname, flags)
         except DLOpenError as e:
             raise wrap_dlopenerror(space, e, filename)
     self.name = filename
     self.register_finalizer(space)
Пример #46
0
 def __init__(self, space, filename, flags):
     self.space = space
     with rffi.scoped_str2charp(filename) as ll_libname:
         if filename is None:
             filename = "<None>"
         try:
             self.handle = dlopen(ll_libname, flags)
         except DLOpenError as e:
             raise wrap_dlopenerror(space, e, filename)
     self.name = filename
     self.register_finalizer(space)
Пример #47
0
    def test_getmoduledict(self, space):
        testmod = "_functools"
        w_pre_dict = PyImport_GetModuleDict(space, )
        assert not space.contains_w(w_pre_dict, space.wrap(testmod))

        with rffi.scoped_str2charp(testmod) as modname:
            w_module = PyImport_ImportModule(space, modname)
            print w_module
            assert w_module

        w_dict = PyImport_GetModuleDict(space, )
        assert space.contains_w(w_dict, space.wrap(testmod))
Пример #48
0
    def test_getmoduledict(self, space, api):
        testmod = "contextlib"
        w_pre_dict = api.PyImport_GetModuleDict()
        assert not space.is_true(space.contains(w_pre_dict, space.wrap(testmod)))

        with rffi.scoped_str2charp(testmod) as modname:
            w_module = api.PyImport_ImportModule(modname)
            print w_module
            assert w_module

        w_dict = api.PyImport_GetModuleDict()
        assert space.is_true(space.contains(w_dict, space.wrap(testmod)))
Пример #49
0
 def test_encode_fsdefault(self, space):
     w_u = space.wrap(u'späm')
     try:
         w_s = PyUnicode_EncodeFSDefault(space, w_u)
     except (OperationError, UnicodeEncodeError):
         py.test.skip("Requires a unicode-aware fsencoding")
     with rffi.scoped_str2charp(space.bytes_w(w_s)) as encoded:
         w_decoded = PyUnicode_DecodeFSDefaultAndSize(
             space, encoded, space.len_w(w_s))
         assert space.eq_w(w_decoded, w_u)
         w_decoded = PyUnicode_DecodeFSDefault(space, encoded)
         assert space.eq_w(w_decoded, w_u)
Пример #50
0
    def test_getmoduledict(self, space, api):
        testmod = "_functools"
        w_pre_dict = api.PyImport_GetModuleDict()
        assert not space.contains_w(w_pre_dict, space.wrap(testmod))

        with rffi.scoped_str2charp(testmod) as modname:
            w_module = api.PyImport_ImportModule(modname)
            print w_module
            assert w_module

        w_dict = api.PyImport_GetModuleDict()
        assert space.contains_w(w_dict, space.wrap(testmod))
Пример #51
0
    def test_locale(self, space):
        # Input is bytes
        w_input = space.newbytes("test")
        with rffi.scoped_str2charp('strict') as errors:
            w_ret = PyUnicode_DecodeLocale(space, w_input, errors)
            assert space.utf8_w(w_ret) == 'test'
        with rffi.scoped_str2charp('surrogateescape') as errors:
            w_ret = PyUnicode_DecodeLocale(space, w_input, errors)
            assert space.utf8_w(w_ret) == 'test'

        # Input is unicode
        w_input = space.newtext("test", 4)
        with rffi.scoped_str2charp('strict') as errors:
            w_ret = PyUnicode_EncodeLocale(space, w_input, errors)
            assert space.utf8_w(w_ret) == 'test'
        with rffi.scoped_str2charp(None) as errors:
            w_ret = PyUnicode_EncodeLocale(space, w_input, errors)
            assert space.utf8_w(w_ret) == 'test'
        with rffi.scoped_str2charp('surrogateescape') as errors:
            w_ret = PyUnicode_EncodeLocale(space, w_input, errors)
            assert space.utf8_w(w_ret) == 'test'
        # 'errors' is invalid
        with rffi.scoped_str2charp('something else') as errors:
            with pytest.raises(OperationError):
                PyUnicode_EncodeLocale(space, w_input, errors)
Пример #52
0
def regenerateKey(secretKey):
    """
    Regenerate a public key from a secret key.
    """

    publicSize = intmask(cryptoBoxPublickeybytes())

    with rffi.scoped_alloc_buffer(publicSize) as public:
        with rffi.scoped_str2charp(secretKey) as rawSecret:
            rv = cryptoScalarmultBase(public.raw, rawSecret)
            if rv:
                raise SodiumError("crypto_scalarmult_base: %d" % rv)
            return public.str(publicSize)
Пример #53
0
 def unsetenv_llimpl(name):
     with rffi.scoped_str2charp(name) as l_name:
         error = rffi.cast(lltype.Signed, os_unsetenv(l_name))
     if error:
         from rpython.rlib import rposix
         raise OSError(rposix.get_saved_errno(), "os_unsetenv failed")
     try:
         l_oldstring = envkeepalive.byname[name]
     except KeyError:
         pass
     else:
         del envkeepalive.byname[name]
         rffi.free_charp(l_oldstring)
Пример #54
0
 def find_extension(self, name, path):
     from pypy.module.cpyext.import_ import PyImport_AddModule
     from pypy.interpreter.module import Module
     try:
         w_dict = self.extensions[path]
     except KeyError:
         return None
     with rffi.scoped_str2charp(name) as ll_name:
         w_mod = PyImport_AddModule(self.space, ll_name)
     assert isinstance(w_mod, Module)
     w_mdict = w_mod.getdict(self.space)
     self.space.call_method(w_mdict, 'update', w_dict)
     return w_mod
Пример #55
0
    def RAND_egd(space, path):
        """RAND_egd(path) -> bytes

        Queries the entropy gather daemon (EGD) on socket path.  Returns number
        of bytes read.  Raises socket.sslerror if connection to EGD fails or
        if it does provide enough data to seed PRNG."""
        with rffi.scoped_str2charp(path) as socket_path:
            bytes = libssl_RAND_egd(socket_path)
        if bytes == -1:
            raise ssl_error(space,
                            "EGD connection failed or EGD did not return "
                            "enough data to seed the PRNG")
        return space.wrap(bytes)
Пример #56
0
 def create_aggregate(self, name, nargs, contextcls):
     index, func = self.funcregistry.create_aggregate(name, nargs, contextcls)
     with rffi.scoped_str2charp(name) as name:
         # use 1 as the function pointer and pass in the index as the user
         # data
         errorcode = capi.sqlite3_create_function(
                 self.db, name, nargs, CConfig.SQLITE_UTF8,
                 rffi.cast(rffi.VOIDP, index),
                 lltype.nullptr(rffi.VOIDP.TO),
                 rffi.cast(rffi.VOIDP, 1),
                 rffi.cast(rffi.VOIDP, 1),
         )
         assert errorcode == 0
     return func