Exemplo n.º 1
0
def _Py_InitPyPyModule(space, name, methods, doc, w_self, apiver):
    """
    Create a new module object based on a name and table of functions, returning
    the new module object. If doc is non-NULL, it will be used to define the
    docstring for the module. If self is non-NULL, it will passed to the
    functions of the module as their (otherwise NULL) first parameter. (This was
    added as an experimental feature, and there are no known uses in the current
    version of Python.) For apiver, the only value which should be passed is
    defined by the constant PYTHON_API_VERSION.

    Note that the name parameter is actually ignored, and the module name is
    taken from the package_context attribute of the cpyext.State in the space
    cache.  CPython includes some extra checking here to make sure the module
    being initialized lines up with what's expected, but we don't.
    """
    from pypy.module.cpyext.typeobjectdefs import PyTypeObjectPtr
    modname = rffi.charp2str(name)
    state = space.fromcache(State)
    f_name, f_path = state.package_context
    w_mod = PyImport_AddModule(space, f_name)

    dict_w = {'__file__': space.wrap(f_path)}
    convert_method_defs(space, dict_w, methods, None, w_self, modname)
    for key, w_value in dict_w.items():
        space.setattr(w_mod, space.wrap(key), w_value)
    if doc:
        space.setattr(w_mod, space.wrap("__doc__"),
                      space.wrap(rffi.charp2str(doc)))
    return borrow_from(None, w_mod)
Exemplo n.º 2
0
    def getdefaultlocale():
        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(
                cConfig.LOCALE_USER_DEFAULT, cConfig.LOCALE_SISO639LANGNAME, buf_lang, BUFSIZE
            ) and GetLocaleInfo(cConfig.LOCALE_USER_DEFAULT, cConfig.LOCALE_SISO3166CTRYNAME, buf_country, BUFSIZE):
                lang = rffi.charp2str(buf_lang)
                country = rffi.charp2str(buf_country)
                language = "%s_%s" % (lang, country)

            # 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(cConfig.LOCALE_USER_DEFAULT, cConfig.LOCALE_IDEFAULTLANGUAGE, buf_lang, BUFSIZE):
                lang = rffi.charp2str(buf_lang)
                language = "0x%s" % (lang,)

            else:
                language = None
        finally:
            lltype.free(buf_lang, flavor="raw")
            lltype.free(buf_country, flavor="raw")

        return language, encoding
Exemplo n.º 3
0
def PyCodec_IncrementalEncoder(space, encoding, errors):
    w_codec = interp_codecs.lookup_codec(space, rffi.charp2str(encoding))
    if errors:
        w_errors = space.wrap(rffi.charp2str(errors))
        return space.call_method(w_codec, "incrementalencoder", w_errors)
    else:
        return space.call_method(w_codec, "incrementalencoder")
Exemplo n.º 4
0
def PyUnicode_FromEncodedObject(space, w_obj, encoding, errors):
    """Coerce an encoded object obj to an Unicode object and return a reference with
    incremented refcount.

    String and other char buffer compatible objects are decoded according to the
    given encoding and using the error handling defined by errors.  Both can be
    NULL to have the interface use the default values (see the next section for
    details).

    All other objects, including Unicode objects, cause a TypeError to be
    set."""
    w_encoding = space.wrap(rffi.charp2str(encoding))
    if errors:
        w_errors = space.wrap(rffi.charp2str(errors))
    else:
        w_errors = space.w_None

    # - unicode is disallowed
    # - raise TypeError for non-string types
    if space.is_true(space.isinstance(w_obj, space.w_unicode)):
        w_meth = None
    else:
        try:
            w_meth = space.getattr(w_obj, space.wrap("decode"))
        except OperationError, e:
            if not e.match(space, space.w_AttributeError):
                raise
            w_meth = None
Exemplo n.º 5
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')
Exemplo n.º 6
0
    def dcgettext(space, w_domain, msg, category):
        """dcgettext(domain, msg, category) -> string
        Return translation of msg in domain and category."""

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

        return space.wrap(result)
Exemplo n.º 7
0
def PyFile_FromString(space, filename, mode):
    """
    On success, return a new file object that is opened on the file given by
    filename, with a file mode given by mode, where mode has the same
    semantics as the standard C routine fopen().  On failure, return NULL."""
    w_filename = space.wrap(rffi.charp2str(filename))
    w_mode = space.wrap(rffi.charp2str(mode))
    return space.call_method(space.builtin, 'file', w_filename, w_mode)
Exemplo n.º 8
0
def _ssl_seterror(space, ss, ret):
    assert ret <= 0

    if ss is None:
        errval = libssl_ERR_peek_last_error()
        errstr = rffi.charp2str(libssl_ERR_error_string(errval, None))
        return ssl_error(space, errstr, errval)
    elif ss.ssl:
        err = libssl_SSL_get_error(ss.ssl, ret)
    else:
        err = SSL_ERROR_SSL
    errstr = ""
    errval = 0

    if err == SSL_ERROR_ZERO_RETURN:
        errstr = "TLS/SSL connection has been closed"
        errval = PY_SSL_ERROR_ZERO_RETURN
    elif err == SSL_ERROR_WANT_READ:
        errstr = "The operation did not complete (read)"
        errval = PY_SSL_ERROR_WANT_READ
    elif err == SSL_ERROR_WANT_WRITE:
        errstr = "The operation did not complete (write)"
        errval = PY_SSL_ERROR_WANT_WRITE
    elif err == SSL_ERROR_WANT_X509_LOOKUP:
        errstr = "The operation did not complete (X509 lookup)"
        errval = PY_SSL_ERROR_WANT_X509_LOOKUP
    elif err == SSL_ERROR_WANT_CONNECT:
        errstr = "The operation did not complete (connect)"
        errval = PY_SSL_ERROR_WANT_CONNECT
    elif err == SSL_ERROR_SYSCALL:
        e = libssl_ERR_get_error()
        if e == 0:
            if ret == 0 or space.is_w(ss.w_socket, space.w_None):
                errstr = "EOF occurred in violation of protocol"
                errval = PY_SSL_ERROR_EOF
            elif ret == -1:
                # the underlying BIO reported an I/0 error
                error = rsocket.last_error()
                return interp_socket.converted_error(space, error)
            else:
                errstr = "Some I/O error occurred"
                errval = PY_SSL_ERROR_SYSCALL
        else:
            errstr = rffi.charp2str(libssl_ERR_error_string(e, None))
            errval = PY_SSL_ERROR_SYSCALL
    elif err == SSL_ERROR_SSL:
        e = libssl_ERR_get_error()
        errval = PY_SSL_ERROR_SSL
        if e != 0:
            errstr = rffi.charp2str(libssl_ERR_error_string(e, None))
        else:
            errstr = "A failure in the SSL library occurred"
    else:
        errstr = "Invalid error code"
        errval = PY_SSL_ERROR_INVALID_ERROR_CODE

    return ssl_error(space, errstr, errval)
Exemplo n.º 9
0
def PyImport_ExecCodeModuleEx(space, name, w_code, pathname):
    """Like PyImport_ExecCodeModule(), but the __file__ attribute of
    the module object is set to pathname if it is non-NULL."""
    code = space.interp_w(PyCode, w_code)
    w_name = space.wrap(rffi.charp2str(name))
    if pathname:
        pathname = rffi.charp2str(pathname)
    else:
        pathname = code.co_filename
    w_mod = importing.add_module(space, w_name)
    space.setattr(w_mod, space.wrap('__file__'), space.wrap(pathname))
    importing.exec_code_module(space, w_mod, code)
    return w_mod
Exemplo n.º 10
0
def PyUnicode_Decode(space, s, size, encoding, errors):
    """Create a Unicode object by decoding size bytes of the encoded string s.
    encoding and errors have the same meaning as the parameters of the same name
    in the unicode() built-in function.  The codec to be used is looked up
    using the Python codec registry.  Return NULL if an exception was raised by
    the codec."""
    w_str = space.wrap(rffi.charpsize2str(s, size))
    w_encoding = space.wrap(rffi.charp2str(encoding))
    if errors:
        w_errors = space.wrap(rffi.charp2str(errors))
    else:
        w_errors = space.w_None
    return space.call_method(w_str, "decode", w_encoding, w_errors)
Exemplo n.º 11
0
def make_struct_passwd(space, pw):
    w_passwd_struct = space.getattr(space.getbuiltinmodule('pwd'),
                                    space.wrap('struct_passwd'))
    w_tuple = space.newtuple([
        space.wrap(rffi.charp2str(pw.c_pw_name)),
        space.wrap(rffi.charp2str(pw.c_pw_passwd)),
        space.wrap(intmask(pw.c_pw_uid)),
        space.wrap(intmask(pw.c_pw_gid)),
        space.wrap(rffi.charp2str(pw.c_pw_gecos)),
        space.wrap(rffi.charp2str(pw.c_pw_dir)),
        space.wrap(rffi.charp2str(pw.c_pw_shell)),
        ])
    return space.call_function(w_passwd_struct, w_tuple)
Exemplo n.º 12
0
def _init_timezone():
    timezone = daylight = altzone = 0
    tzname = ["", ""]
    
    # pypy cant' use in_dll to access global exported variables
    # so we can't compute these attributes

    # if _WIN:
    #     cdll.msvcrt._tzset()
    # 
    #     timezone = c_long.in_dll(cdll.msvcrt, "_timezone").value
    #     if hasattr(cdll.msvcrt, "altzone"):
    #         altzone = c_long.in_dll(cdll.msvcrt, "altzone").value
    #     else:
    #         altzone = timezone - 3600
    #     daylight = c_long.in_dll(cdll.msvcrt, "_daylight").value
    #     tzname = _tzname_t.in_dll(cdll.msvcrt, "_tzname")
    #     tzname = (tzname.tzname_0, tzname.tzname_1)
    if _POSIX:
        YEAR = (365 * 24 + 6) * 3600

        t = (((c_time(lltype.nullptr(TIME_TP.TO))) / YEAR) * YEAR)
        # we cannot have reference to stack variable, put it on the heap
        t_ref = lltype.malloc(TIME_TP.TO, 1, flavor='raw')
        t_ref[0] = t
        p = c_localtime(t_ref)
        janzone = -p.c_tm_gmtoff
        tm_zone = rffi.charp2str(p.c_tm_zone)
        janname = ["   ", tm_zone][bool(tm_zone)]
        tt = t + YEAR / 2
        t_ref[0] = tt
        p = c_localtime(t_ref)
        lltype.free(t_ref, flavor='raw')
        tm_zone = rffi.charp2str(p.c_tm_zone)
        julyzone = -p.c_tm_gmtoff
        julyname = ["   ", tm_zone][bool(tm_zone)]

        if janzone < julyzone:
            # DST is reversed in the southern hemisphere
            timezone = julyzone
            altzone = janzone
            daylight = int(janzone != julyzone)
            tzname = [julyname, janname]
        else:
            timezone = janzone
            altzone = julyzone
            daylight = int(janzone != julyzone)
            tzname = [janname, julyname]

    return timezone, daylight, tzname, altzone
Exemplo n.º 13
0
 def uname_llimpl():
     l_utsbuf = lltype.malloc(UTSNAMEP.TO, flavor='raw')
     result = os_uname(l_utsbuf)
     if result == -1:
         raise OSError(rposix.get_errno(), "os_uname failed")
     retval = (
         rffi.charp2str(rffi.cast(rffi.CCHARP, l_utsbuf.c_sysname)),
         rffi.charp2str(rffi.cast(rffi.CCHARP, l_utsbuf.c_nodename)),
         rffi.charp2str(rffi.cast(rffi.CCHARP, l_utsbuf.c_release)),
         rffi.charp2str(rffi.cast(rffi.CCHARP, l_utsbuf.c_version)),
         rffi.charp2str(rffi.cast(rffi.CCHARP, l_utsbuf.c_machine)),
         )
     lltype.free(l_utsbuf, flavor='raw')
     return retval
Exemplo n.º 14
0
def Py_CompileStringFlags(space, source, filename, start, flags):
    """Parse and compile the Python source code in str, returning the
    resulting code object.  The start token is given by start; this
    can be used to constrain the code which can be compiled and should
    be Py_eval_input, Py_file_input, or Py_single_input.  The filename
    specified by filename is used to construct the code object and may
    appear in tracebacks or SyntaxError exception messages.  This
    returns NULL if the code cannot be parsed or compiled."""
    source = rffi.charp2str(source)
    filename = rffi.charp2str(filename)
    if flags:
        raise OperationError(space.w_NotImplementedError, space.wrap(
                "cpyext Py_CompileStringFlags does not accept flags"))
    return compile_string(space, source, filename, start)
Exemplo n.º 15
0
 def __init__(self, getset, w_type):
     self.getset = getset
     self.name = rffi.charp2str(getset.c_name)
     self.w_type = w_type
     doc = set = get = None
     if doc:
         doc = rffi.charp2str(getset.c_doc)
     if getset.c_get:
         get = GettersAndSetters.getter.im_func
     if getset.c_set:
         set = GettersAndSetters.setter.im_func
     GetSetProperty.__init__(self, get, set, None, doc,
                             cls=None, use_closure=True,
                             tag="cpyext_1")
Exemplo n.º 16
0
def Py_CompileStringFlags(space, source, filename, start, flagsptr):
    """Parse and compile the Python source code in str, returning the
    resulting code object.  The start token is given by start; this
    can be used to constrain the code which can be compiled and should
    be Py_eval_input, Py_file_input, or Py_single_input.  The filename
    specified by filename is used to construct the code object and may
    appear in tracebacks or SyntaxError exception messages.  This
    returns NULL if the code cannot be parsed or compiled."""
    source = rffi.charp2str(source)
    filename = rffi.charp2str(filename)
    if flagsptr:
        flags = rffi.cast(lltype.Signed, flagsptr.c_cf_flags)
    else:
        flags = 0
    return compile_string(space, source, filename, start, flags)
Exemplo n.º 17
0
def PyUnicode_AsEncodedObject(space, w_unicode, llencoding, llerrors):
    """Encode a Unicode object and return the result as Python object.
    encoding and errors have the same meaning as the parameters of the same name
    in the Unicode encode() method. The codec to be used is looked up using
    the Python codec registry. Return NULL if an exception was raised by the
    codec."""
    if not PyUnicode_Check(space, w_unicode):
        PyErr_BadArgument(space)

    encoding = errors = None
    if llencoding:
        encoding = rffi.charp2str(llencoding)
    if llerrors:
        errors = rffi.charp2str(llerrors)
    return unicodetype.encode_object(space, w_unicode, encoding, errors)
Exemplo n.º 18
0
 def __init__(self, member, w_type):
     self.member = member
     self.name = rffi.charp2str(member.c_name)
     self.w_type = w_type
     flags = rffi.cast(lltype.Signed, member.c_flags)
     doc = set = None
     if member.c_doc:
         doc = rffi.charp2str(member.c_doc)
     get = GettersAndSetters.member_getter.im_func
     del_ = GettersAndSetters.member_delete.im_func
     if not (flags & structmemberdefs.READONLY):
         set = GettersAndSetters.member_setter.im_func
     GetSetProperty.__init__(self, get, set, del_, doc,
                             cls=None, use_closure=True,
                             tag="cpyext_2")
Exemplo n.º 19
0
def _init_timezone(space):
    timezone = daylight = altzone = 0
    tzname = ["", ""]

    if _WIN:
        c_tzset()
        timezone = c_get_timezone()
        altzone = timezone - 3600
        daylight = c_get_daylight()
        tzname_ptr = c_get_tzname()
        tzname = rffi.charp2str(tzname_ptr[0]), rffi.charp2str(tzname_ptr[1])

    if _POSIX:
        YEAR = (365 * 24 + 6) * 3600

        t = ((c_time(lltype.nullptr(rffi.TIME_TP.TO))) / YEAR) * YEAR
        # we cannot have reference to stack variable, put it on the heap
        t_ref = lltype.malloc(rffi.TIME_TP.TO, 1, flavor="raw")
        t_ref[0] = rffi.cast(rffi.TIME_T, t)
        p = c_localtime(t_ref)
        janzone = -p.c_tm_gmtoff
        tm_zone = rffi.charp2str(p.c_tm_zone)
        janname = ["   ", tm_zone][bool(tm_zone)]
        tt = t + YEAR / 2
        t_ref[0] = rffi.cast(rffi.TIME_T, tt)
        p = c_localtime(t_ref)
        lltype.free(t_ref, flavor="raw")
        tm_zone = rffi.charp2str(p.c_tm_zone)
        julyzone = -p.c_tm_gmtoff
        julyname = ["   ", tm_zone][bool(tm_zone)]

        if janzone < julyzone:
            # DST is reversed in the southern hemisphere
            timezone = julyzone
            altzone = janzone
            daylight = int(janzone != julyzone)
            tzname = [julyname, janname]
        else:
            timezone = janzone
            altzone = julyzone
            daylight = int(janzone != julyzone)
            tzname = [janname, julyname]

    _set_module_object(space, "timezone", space.wrap(timezone))
    _set_module_object(space, "daylight", space.wrap(daylight))
    tzname_w = [space.wrap(tzname[0]), space.wrap(tzname[1])]
    _set_module_object(space, "tzname", space.newtuple(tzname_w))
    _set_module_object(space, "altzone", space.wrap(altzone))
Exemplo n.º 20
0
def convert_method_defs(space, dict_w, methods, w_type, w_self=None, name=None):
    w_name = space.wrap(name)
    methods = rffi.cast(rffi.CArrayPtr(PyMethodDef), methods)
    if methods:
        i = -1
        while True:
            i = i + 1
            method = methods[i]
            if not method.c_ml_name: break

            methodname = rffi.charp2str(method.c_ml_name)
            flags = rffi.cast(lltype.Signed, method.c_ml_flags)

            if w_type is None:
                if flags & METH_CLASS or flags & METH_STATIC:
                    raise OperationError(space.w_ValueError,
                            space.wrap("module functions cannot set METH_CLASS or METH_STATIC"))
                w_obj = space.wrap(W_PyCFunctionObject(space, method, w_self, w_name))
            else:
                if methodname in dict_w and not (flags & METH_COEXIST):
                    continue
                if flags & METH_CLASS:
                    if flags & METH_STATIC:
                        raise OperationError(space.w_ValueError,
                                space.wrap("method cannot be both class and static"))
                    #w_obj = PyDescr_NewClassMethod(space, w_type, method)
                    w_obj = space.w_Ellipsis # XXX
                elif flags & METH_STATIC:
                    w_func = PyCFunction_NewEx(space, method, None, None)
                    w_obj = PyStaticMethod_New(space, w_func)
                else:
                    w_obj = PyDescr_NewMethod(space, w_type, method)

            dict_w[methodname] = w_obj
Exemplo n.º 21
0
 def g():
     l = rffi.liststr2charpp(["a", "b", "c"])
     try:
         set_z(l)
         return rffi.charp2str(get_z()[2])
     finally:
         rffi.free_charpp(l)
Exemplo n.º 22
0
def PyString_InternFromString(space, string):
    """A combination of PyString_FromString() and
    PyString_InternInPlace(), returning either a new string object that has
    been interned, or a new ("owned") reference to an earlier interned string
    object with the same value."""
    s = rffi.charp2str(string)
    return space.new_interned_str(s)
Exemplo n.º 23
0
def PyRun_SimpleString(space, command):
    """This is a simplified interface to PyRun_SimpleStringFlags() below,
    leaving the PyCompilerFlags* argument set to NULL."""
    command = rffi.charp2str(command)
    run_string(space, command, "<string>", Py_file_input,
               space.w_None, space.w_None)
    return 0
Exemplo n.º 24
0
def PyUnicode_SetDefaultEncoding(space, encoding):
    """Sets the currently active default encoding. Returns 0 on
    success, -1 in case of an error."""
    w_encoding = space.wrap(rffi.charp2str(encoding))
    setdefaultencoding(space, w_encoding)
    default_encoding[0] = "\x00"
    return 0
Exemplo n.º 25
0
    def peer_certificate(self, der=False):
        """peer_certificate([der=False]) -> certificate

        Returns the certificate for the peer.  If no certificate was provided,
        returns None.  If a certificate was provided, but not validated, returns
        an empty dictionary.  Otherwise returns a dict containing information
        about the peer certificate.

        If the optional argument is True, returns a DER-encoded copy of the
        peer certificate, or None if no certificate was provided.  This will
        return the certificate even if it wasn't validated."""
        if not self.peer_cert:
            return self.space.w_None

        if der:
            # return cert in DER-encoded format
            with lltype.scoped_alloc(rffi.CCHARPP.TO, 1) as buf_ptr:
                buf_ptr[0] = lltype.nullptr(rffi.CCHARP.TO)
                length = libssl_i2d_X509(self.peer_cert, buf_ptr)
                if length < 0:
                    raise _ssl_seterror(self.space, self, length)
                try:
                    # this is actually an immutable bytes sequence
                    return self.space.wrap(rffi.charp2str(buf_ptr[0]))
                finally:
                    libssl_OPENSSL_free(buf_ptr[0])
        else:
            verification = libssl_SSL_CTX_get_verify_mode(
                libssl_SSL_get_SSL_CTX(self.ssl))
            if not verification & SSL_VERIFY_PEER:
                return self.space.newdict()
            else:
                return _decode_certificate(self.space, self.peer_cert)
Exemplo n.º 26
0
def PyObject_HasAttrString(space, w_obj, name_ptr):
    try:
        name = rffi.charp2str(name_ptr)
        w_res = operation.hasattr(space, w_obj, space.wrap(name))
        return space.is_true(w_res)
    except OperationError:
        return 0
Exemplo n.º 27
0
 def os_listdir_llimpl(path):
     if path and path[-1] not in ('/', '\\', ':'):
         path += '/'
     path += '*.*'
     filedata = lltype.malloc(WIN32_FIND_DATA, flavor='raw')
     try:
         result = []
         hFindFile = FindFirstFile(path, filedata)
         if hFindFile == INVALID_HANDLE_VALUE:
             error = GetLastError()
             if error == ERROR_FILE_NOT_FOUND:
                 return result
             else:
                 # XXX guess error code :-(
                 raise OSError(errno.ENOENT, "FindFirstFile failed")
         while True:
             name = rffi.charp2str(rffi.cast(rffi.CCHARP,
                                             filedata.c_cFileName))
             if name != "." and name != "..":   # skip these
                 result.append(name)
             if not FindNextFile(hFindFile, filedata):
                 break
         # FindNextFile sets error to ERROR_NO_MORE_FILES if
         # it got to the end of the directory
         error = GetLastError()
         FindClose(hFindFile)
         if error == ERROR_NO_MORE_FILES:
             return result
         else:
             # XXX guess error code :-(
             raise OSError(errno.EIO, "FindNextFile failed")
     finally:
         lltype.free(filedata, flavor='raw')
Exemplo n.º 28
0
def gethost_common(hostname, hostent, addr=None):
    if not hostent:
        raise HSocketError(hostname)
    family = rffi.getintfield(hostent, 'c_h_addrtype')
    if addr is not None and addr.family != family:
        raise CSocketError(_c.EAFNOSUPPORT)

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

    address_list = []
    h_addr_list = hostent.c_h_addr_list
    i = 0
    paddr = h_addr_list[0]
    while paddr:
        if family == AF_INET:
            p = rffi.cast(lltype.Ptr(_c.in_addr), paddr)
            addr = INETAddress.from_in_addr(p)
        elif AF_INET6 is not None and family == AF_INET6:
            p = rffi.cast(lltype.Ptr(_c.in6_addr), paddr)
            addr = INET6Address.from_in6_addr(p)
        else:
            raise RSocketError("unknown address family")
        address_list.append(addr)
        i += 1
        paddr = h_addr_list[i]
    return (rffi.charp2str(hostent.c_h_name), aliases, address_list)
Exemplo n.º 29
0
def EnumKey(space, w_hkey, index):
    """string = EnumKey(key, index) - Enumerates subkeys of an open registry key.

key is an already open key, or any one of the predefined HKEY_* constants.
index is an integer that identifies the index of the key to retrieve.

The function retrieves the name of one subkey each time it is called.
It is typically called repeatedly until an EnvironmentError exception is
raised, indicating no more values are available."""
    hkey = hkey_w(w_hkey, space)
    null_dword = lltype.nullptr(rwin32.LPDWORD.TO)

    # The Windows docs claim that the max key name length is 255
    # characters, plus a terminating nul character.  However,
    # empirical testing demonstrates that it is possible to
    # create a 256 character key that is missing the terminating
    # nul.  RegEnumKeyEx requires a 257 character buffer to
    # retrieve such a key name.
    with lltype.scoped_alloc(rffi.CCHARP.TO, 257) as buf:
        with lltype.scoped_alloc(rwin32.LPDWORD.TO, 1) as retValueSize:
            retValueSize[0] = r_uint(257) # includes NULL terminator
            ret = rwinreg.RegEnumKeyEx(hkey, index, buf, retValueSize,
                                       null_dword, None, null_dword,
                                       lltype.nullptr(rwin32.PFILETIME.TO))
            if ret != 0:
                raiseWindowsError(space, ret, 'RegEnumKeyEx')
            return space.wrap(rffi.charp2str(buf))
Exemplo n.º 30
0
def Py_DecRef(space, obj):
    if not obj:
        return
    assert lltype.typeOf(obj) == PyObject

    obj.c_ob_refcnt -= 1
    if DEBUG_REFCOUNT:
        debug_refcount("DECREF", obj, obj.c_ob_refcnt, frame_stackdepth=3)
    if obj.c_ob_refcnt == 0:
        state = space.fromcache(RefcountState)
        ptr = rffi.cast(ADDR, obj)
        if ptr not in state.py_objects_r2w:
            # this is a half-allocated object, lets call the deallocator
            # without modifying the r2w/w2r dicts
            _Py_Dealloc(space, obj)
        else:
            w_obj = state.py_objects_r2w[ptr]
            del state.py_objects_r2w[ptr]
            w_type = space.type(w_obj)
            if not w_type.is_cpytype():
                _Py_Dealloc(space, obj)
            del state.py_objects_w2r[w_obj]
            # if the object was a container for borrowed references
            state.delete_borrower(w_obj)
    else:
        if not we_are_translated() and obj.c_ob_refcnt < 0:
            message = "Negative refcount for obj %s with type %s" % (
                obj, rffi.charp2str(obj.c_ob_type.c_tp_name))
            print >>sys.stderr, message
            assert False, message
Exemplo n.º 31
0
 def get_msg(self):
     # this method may be patched below
     return rffi.charp2str(_c.gai_strerror(self.errno))
Exemplo n.º 32
0
def _get_error_msg():
    errno = rposix.get_errno()
    return rffi.charp2str(strerror(errno))
Exemplo n.º 33
0
def test_open_mixer():
    if RMix.OpenAudio(22050, RSDL.AUDIO_S16LSB, 2, 1024) != 0:
        error = rffi.charp2str(RSDL.GetError())
        raise Exception(error)
    RMix.CloseAudio()
Exemplo n.º 34
0
 def __init__(self, space, ml, w_type):
     self.space = space
     self.ml = ml
     self.name = rffi.charp2str(ml.c_ml_name)
     self.w_objclass = w_type
Exemplo n.º 35
0
def PyString_FromString(space, char_p):
    s = rffi.charp2str(char_p)
    return space.wrap(s)
Exemplo n.º 36
0
 def get_doc(self, space):
     doc = self.ml.c_ml_doc
     if doc:
         return space.wrap(rffi.charp2str(doc))
     else:
         return space.w_None
Exemplo n.º 37
0
def PyUnicode_FromString(space, s):
    """Create a Unicode object from an UTF-8 encoded null-terminated char buffer"""
    w_str = space.wrap(rffi.charp2str(s))
    return space.call_method(w_str, 'decode', space.wrap("utf-8"))
Exemplo n.º 38
0
 def w_convert_charp(self, space, data):
     if data:
         return self.w_convert(space, rffi.charp2str(data))
     else:
         return space.w_None
Exemplo n.º 39
0
 def issuer(self):
     return self.space.wrap(rffi.charp2str(self._issuer))
Exemplo n.º 40
0
def ErrorString(space, code):
    """ErrorString(errno) -> string
Returns string error for given number."""
    return space.wrap(rffi.charp2str(XML_ErrorString(code)))
Exemplo n.º 41
0
def getservbyport(port, proto=None):
    servent = _c.getservbyport(htons(port), proto)
    if not servent:
        raise RSocketError("port/proto not found")
    return rffi.charp2str(servent.c_s_name)
Exemplo n.º 42
0
 def __init__(self, space, ml, w_self, w_module=None):
     self.ml = ml
     self.name = rffi.charp2str(self.ml.c_ml_name)
     self.w_self = w_self
     self.w_module = w_module
Exemplo n.º 43
0
 def GetProgramFullPath(self):
     impl = self.lib.getpointer("Py_GetProgramFullPath", [],
                                libffi.ffi_type_pointer)
     return rffi.charp2str(impl.call(rffi.CCHARP))
Exemplo n.º 44
0
 def server(self):
     return self.space.wrap(rffi.charp2str(self._server))
Exemplo n.º 45
0
def getaddrinfo(hostname,
                servname,
                family=_c.AF_UNSPEC,
                socktype=0,
                protocol=0,
                flags=0,
                address_to_fill=None):

    if not hostname and not servname:
        raise GAIError(EAI_NONAME)

    # error checks for hints
    if flags & ~AI_MASK:
        raise GAIError(EAI_BADFLAGS)
    if family not in (_c.AF_UNSPEC, _c.AF_INET):
        raise GAIError(EAI_FAMILY)

    if socktype == GAI_ANY:
        if protocol == GAI_ANY:
            pass
        elif protocol == _c.IPPROTO_UDP:
            socktype = _c.SOCK_DGRAM
        elif protocol == _c.IPPROTO_TCP:
            socktype = _c.SOCK_STREAM
        else:
            socktype = _c.SOCK_RAW

    elif socktype == _c.SOCK_RAW:
        pass
    elif socktype == _c.SOCK_DGRAM:
        if protocol not in (_c.IPPROTO_UDP, GAI_ANY):
            raise GAIError(EAI_BADHINTS)
        protocol = _c.IPPROTO_UDP
    elif socktype == _c.SOCK_STREAM:
        if protocol not in (_c.IPPROTO_TCP, GAI_ANY):
            raise GAIError(EAI_BADHINTS)
        protocol = _c.IPPROTO_TCP
    else:
        raise GAIError(EAI_SOCKTYPE)

    port = GAI_ANY

    # service port
    if servname:
        if str_isdigit(servname):
            port = _c.htons(int(servname))
            # On windows, python2.3 uses getattrinfo.c,
            # python2.4 uses VC2003 implementation of getaddrinfo().
            # if sys.version < (2, 4)
            #     socktype = _c.SOCK_DGRAM
            #     protocol = _c.IPPROTO_UDP
        else:
            if socktype == _c.SOCK_DGRAM:
                proto = "udp"
            elif socktype == _c.SOCK_STREAM:
                proto = "tcp"
            else:
                proto = None

            sp = _c.getservbyname(servname, proto)
            if not sp:
                raise GAIError(EAI_SERVICE)
            port = sp.c_s_port
            if socktype == GAI_ANY:
                s_proto = rffi.charp2str(sp.c_s_proto)
                if s_proto == "udp":
                    socktype = _c.SOCK_DGRAM
                    protocol = _c.IPPROTO_UDP
                elif s_proto == "tcp":
                    socktype = _c.SOCK_STREAM
                    protocol = _c.IPPROTO_TCP
                else:
                    raise GAIError(EAI_PROTOCOL)

    # hostname == NULL
    # passive socket -> anyaddr (0.0.0.0 or ::)
    # non-passive socket -> localhost (127.0.0.1 or ::1)
    if not hostname:
        result = []
        if family in (_c.AF_UNSPEC, _c.AF_INET):

            sin = rffi.make(_c.sockaddr_in)
            try:
                rffi.setintfield(sin, 'c_sin_family', _c.AF_INET)
                rffi.setintfield(sin, 'c_sin_port', port)
                if flags & _c.AI_PASSIVE:
                    s_addr = 0x0  # addrany
                else:
                    s_addr = 0x0100007f  # loopback
                rffi.setintfield(sin.c_sin_addr, 'c_s_addr', s_addr)

                addr = make_address(rffi.cast(_c.sockaddr_ptr, sin),
                                    rffi.sizeof(_c.sockaddr_in),
                                    address_to_fill)

                result.append((
                    _c.AF_INET,
                    socktype,
                    protocol,
                    "",  # xxx canonname meaningless? "anyaddr"
                    addr))
            finally:
                lltype.free(sin, flavor='raw')

        if not result:
            raise GAIError(EAI_FAMILY)
        return result

    # hostname as numeric name
    if family in (_c.AF_UNSPEC, _c.AF_INET):

        packedaddr = _c.inet_addr(hostname)
        if packedaddr != rffi.cast(rffi.UINT, INADDR_NONE):

            v4a = rffi.cast(lltype.Unsigned, _c.ntohl(packedaddr))
            if (v4a & r_uint(0xf0000000) == r_uint(0xe0000000)
                    or  # IN_MULTICAST()
                    v4a & r_uint(0xe0000000)
                    == r_uint(0xe0000000)):  # IN_EXPERIMENTAL()
                flags &= ~_c.AI_CANONNAME
            v4a >>= 24  # = IN_CLASSA_NSHIFT
            if v4a == r_uint(0) or v4a == r_uint(127):  # = IN_LOOPBACKNET
                flags &= ~_c.AI_CANONNAME

            sin = rffi.make(_c.sockaddr_in)
            try:
                rffi.setintfield(sin, 'c_sin_family', _c.AF_INET)
                rffi.setintfield(sin, 'c_sin_port', port)
                rffi.setintfield(sin.c_sin_addr, 'c_s_addr', packedaddr)
                addr = make_address(rffi.cast(_c.sockaddr_ptr, sin),
                                    rffi.sizeof(_c.sockaddr_in),
                                    address_to_fill)
            finally:
                lltype.free(sin, flavor='raw')

            if not flags & _c.AI_CANONNAME:
                canonname = ""
            else:
                # getaddrinfo() is a name->address translation function,
                # and it looks strange that we do addr->name translation
                # here.
                # This is what python2.3 did on Windows:
                # if sys.version < (2, 4):
                #     canonname = get_name(hostname, sin.sin_addr,
                #                          sizeof(_c.in_addr))
                canonname = hostname
            return [(_c.AF_INET, socktype, protocol, canonname, addr)]

    if flags & _c.AI_NUMERICHOST:
        raise GAIError(EAI_NONAME)

    # hostname as alphabetical name
    result = get_addr(hostname, socktype, protocol, port, address_to_fill)

    if result:
        return result

    raise GAIError(EAI_FAIL)
Exemplo n.º 46
0
 def gai_strerror_str(errno):
     return rffi.charp2str(gai_strerror(errno))
Exemplo n.º 47
0
 def entry_point(argv):
     res = interp_pyexpat.XML_ErrorString(3)
     os.write(1, rffi.charp2str(res))
     return 0
Exemplo n.º 48
0
def PyErr_SetString(space, w_type, message_ptr):
    message = rffi.charp2str(message_ptr)
    PyErr_SetObject(space, w_type, space.wrap(message))
Exemplo n.º 49
0
def print_cstr(s):
    ss = rffi.charp2str(s)
    os.write(1, ss)
    return True
Exemplo n.º 50
0
 def llimpl(fmt, x):
     res = ll_strtod(fmt, x)
     return rffi.charp2str(res)
Exemplo n.º 51
0
def test_libintl():
    if sys.platform != "darwin" or not sys.platform.startswith("linux"):
        py.test.skip("there is (maybe) no libintl here")
    _gettext = external('gettext', [rffi.CCHARP], rffi.CCHARP)
    res = _gettext("1234")
    assert rffi.charp2str(res) == "1234"
Exemplo n.º 52
0
Arquivo: config.py Projeto: njues/Sypy
 def w_string(space, buf, len=-1):
     #assert type(len) is int
     if len < 0:
         return space.wrap(rffi.charp2str(buf))
     else:
         return space.wrap(rffi.charpsize2str(buf, len))