Example #1
0
    def bindtextdomain(space, domain, w_dir):
        """bindtextdomain(domain, dir) -> string
        Bind the C library's domain to dir."""

        if space.is_w(w_dir, space.w_None):
            dir = None
            domain_c = rffi.str2charp(domain)
            try:
                dirname = _bindtextdomain(domain_c, dir)
            finally:
                rffi.free_charp(domain_c)
        else:
            dir = space.str_w(w_dir)
            domain_c = rffi.str2charp(domain)
            dir_c = rffi.str2charp(dir)
            try:
                dirname = _bindtextdomain(domain_c, dir_c)
            finally:
                rffi.free_charp(domain_c)
                rffi.free_charp(dir_c)

        if not dirname:
            errno = rposix.get_errno()
            raise OperationError(space.w_OSError, space.wrap(errno))
        return space.wrap(rffi.charp2str(dirname))
Example #2
0
    def dcgettext(space, w_domain, msg, category):
        """dcgettext(domain, msg, category) -> string
        Return translation of msg in domain and category."""

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

        return space.wrap(result)
Example #3
0
def strxfrm(space, s):
    "string -> string. Returns a string that behaves for cmp locale-aware."
    n1 = len(s) + 1

    buf = lltype.malloc(rffi.CCHARP.TO, n1, flavor="raw", zero=True)
    s_c = rffi.str2charp(s)
    try:
        n2 = _strxfrm(buf, s_c, n1) + 1
    finally:
        rffi.free_charp(s_c)
    if n2 > n1:
        # more space needed
        lltype.free(buf, flavor="raw")
        buf = lltype.malloc(rffi.CCHARP.TO,
                            intmask(n2),
                            flavor="raw",
                            zero=True)
        s_c = rffi.str2charp(s)
        try:
            _strxfrm(buf, s_c, n2)
        finally:
            rffi.free_charp(s_c)

    val = rffi.charp2str(buf)
    lltype.free(buf, flavor="raw")

    return space.wrap(val)
Example #4
0
def strcoll(space, w_s1, w_s2):
    "string,string -> int. Compares two strings according to the locale."

    if space.is_true(space.isinstance(w_s1, space.w_str)) and \
       space.is_true(space.isinstance(w_s2, space.w_str)):

        s1, s2 = space.str_w(w_s1), space.str_w(w_s2)
        s1_c = rffi.str2charp(s1)
        s2_c = rffi.str2charp(s2)
        try:
            return space.wrap(_strcoll(s1_c, s2_c))
        finally:
            rffi.free_charp(s1_c)
            rffi.free_charp(s2_c)

    #if not space.is_true(space.isinstance(w_s1, space.w_unicode)) and \
    #   not space.is_true(space.isinstance(w_s2, space.w_unicode)):
    #    raise OperationError(space.w_ValueError,
    #                         space.wrap("strcoll arguments must be strings"))

    s1, s2 = space.unicode_w(w_s1), space.unicode_w(w_s2)

    s1_c = rffi.unicode2wcharp(s1)
    s2_c = rffi.unicode2wcharp(s2)
    try:
        result = _wcscoll(s1_c, s2_c)
    finally:
        rffi.free_wcharp(s1_c)
        rffi.free_wcharp(s2_c)

    return space.wrap(result)
Example #5
0
        def bind_textdomain_codeset(space, domain, w_codeset):
            """bind_textdomain_codeset(domain, codeset) -> string
            Bind the C library's domain to codeset."""

            if space.is_w(w_codeset, space.w_None):
                codeset = None
                domain_c = rffi.str2charp(domain)
                try:
                    result = _bind_textdomain_codeset(domain_c, codeset)
                finally:
                    rffi.free_charp(domain_c)
            else:
                codeset = space.str_w(w_codeset)
                domain_c = rffi.str2charp(domain)
                codeset_c = rffi.str2charp(codeset)
                try:
                    result = _bind_textdomain_codeset(domain_c, codeset_c)
                finally:
                    rffi.free_charp(domain_c)
                    rffi.free_charp(codeset_c)

            if not result:
                return space.w_None
            else:
                return space.wrap(rffi.charp2str(result))
Example #6
0
    def test_AS(self, space, api):
        word = space.wrap(u"spam")
        array = rffi.cast(rffi.CWCHARP, api.PyUnicode_AS_DATA(word))
        array2 = api.PyUnicode_AS_UNICODE(word)
        array3 = api.PyUnicode_AsUnicode(word)
        for (i, char) in enumerate(space.unwrap(word)):
            assert array[i] == char
            assert array2[i] == char
            assert array3[i] == char
        self.raises(space, api, TypeError, api.PyUnicode_AsUnicode, space.wrap("spam"))

        utf_8 = rffi.str2charp("utf-8")
        encoded = api.PyUnicode_AsEncodedString(space.wrap(u"späm"), utf_8, None)
        assert space.unwrap(encoded) == "sp\xc3\xa4m"
        encoded_obj = api.PyUnicode_AsEncodedObject(space.wrap(u"späm"), utf_8, None)
        assert space.eq_w(encoded, encoded_obj)
        self.raises(space, api, TypeError, api.PyUnicode_AsEncodedString, space.newtuple([1, 2, 3]), None, None)
        self.raises(space, api, TypeError, api.PyUnicode_AsEncodedString, space.wrap(""), None, None)
        ascii = rffi.str2charp("ascii")
        replace = rffi.str2charp("replace")
        encoded = api.PyUnicode_AsEncodedString(space.wrap(u"späm"), ascii, replace)
        assert space.unwrap(encoded) == "sp?m"
        rffi.free_charp(utf_8)
        rffi.free_charp(replace)
        rffi.free_charp(ascii)

        buf = rffi.unicode2wcharp(u"12345")
        api.PyUnicode_AsWideChar(space.wrap(u"longword"), buf, 5)
        assert rffi.wcharp2unicode(buf) == "longw"
        api.PyUnicode_AsWideChar(space.wrap(u"a"), buf, 5)
        assert rffi.wcharp2unicode(buf) == "a"
        rffi.free_wcharp(buf)
Example #7
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')
Example #8
0
    def bindtextdomain(space, domain, w_dir):
        """bindtextdomain(domain, dir) -> string
        Bind the C library's domain to dir."""

        if space.is_w(w_dir, space.w_None):
            dir = None
            domain_c = rffi.str2charp(domain)
            try:
                dirname = _bindtextdomain(domain_c, dir)
            finally:
                rffi.free_charp(domain_c)
        else:
            dir = space.str_w(w_dir)
            domain_c = rffi.str2charp(domain)
            dir_c = rffi.str2charp(dir)
            try:
                dirname = _bindtextdomain(domain_c, dir_c)
            finally:
                rffi.free_charp(domain_c)
                rffi.free_charp(dir_c)

        if not dirname:
            errno = rposix.get_errno()
            raise OperationError(space.w_OSError, space.wrap(errno))
        return space.wrap(rffi.charp2str(dirname))
Example #9
0
def strxfrm(space, s):
    "string -> string. Returns a string that behaves for cmp locale-aware."
    n1 = len(s) + 1

    buf = lltype.malloc(rffi.CCHARP.TO, n1, flavor="raw", zero=True)
    s_c = rffi.str2charp(s)
    try:
        n2 = _strxfrm(buf, s_c, n1) + 1
    finally:
        rffi.free_charp(s_c)
    if n2 > n1:
        # more space needed
        lltype.free(buf, flavor="raw")
        buf = lltype.malloc(rffi.CCHARP.TO, intmask(n2),
                            flavor="raw", zero=True)
        s_c = rffi.str2charp(s)
        try:
            _strxfrm(buf, s_c, n2)
        finally:
            rffi.free_charp(s_c)

    val = rffi.charp2str(buf)
    lltype.free(buf, flavor="raw")

    return space.wrap(val)
Example #10
0
    def dcgettext(space, w_domain, msg, category):
        """dcgettext(domain, msg, category) -> string
        Return translation of msg in domain and category."""

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

        return space.wrap(result)
Example #11
0
    def test_ascii_codec(self, space, api):
        s = 'abcdefg'
        data = rffi.str2charp(s)
        w_u = api.PyUnicode_DecodeASCII(data, len(s), lltype.nullptr(rffi.CCHARP.TO))
        assert space.eq_w(w_u, space.wrap(u"abcdefg"))
        rffi.free_charp(data)

        s = 'abcd\xFF'
        data = rffi.str2charp(s)
        self.raises(space, api, UnicodeDecodeError, api.PyUnicode_DecodeASCII,
                    data, len(s), lltype.nullptr(rffi.CCHARP.TO))
        rffi.free_charp(data)

        uni = u'abcdefg'
        data = rffi.unicode2wcharp(uni)
        w_s = api.PyUnicode_EncodeASCII(data, len(uni), lltype.nullptr(rffi.CCHARP.TO))
        assert space.eq_w(space.wrap("abcdefg"), w_s)
        rffi.free_wcharp(data)

        u = u'äbcdéfg'
        data = rffi.unicode2wcharp(u)
        w_s = api.PyUnicode_EncodeASCII(data, len(u), lltype.nullptr(rffi.CCHARP.TO))
        self.raises(space, api, UnicodeEncodeError, api.PyUnicode_EncodeASCII,
                    data, len(u), lltype.nullptr(rffi.CCHARP.TO))
        rffi.free_wcharp(data)
Example #12
0
    def test_file_getline(self, space, api):
        filename = rffi.str2charp(str(udir / "_test_file"))

        mode = rffi.str2charp("w")
        w_file = api.PyFile_FromString(filename, mode)
        space.call_method(w_file, "write",
                          space.wrap("line1\nline2\nline3\nline4"))
        space.call_method(w_file, "close")

        rffi.free_charp(mode)
        mode = rffi.str2charp("r")
        w_file = api.PyFile_FromString(filename, mode)
        rffi.free_charp(filename)
        rffi.free_charp(mode)

        w_line = api.PyFile_GetLine(w_file, 0)
        assert space.str_w(w_line) == "line1\n"

        w_line = api.PyFile_GetLine(w_file, 4)
        assert space.str_w(w_line) == "line"

        w_line = api.PyFile_GetLine(w_file, 0)
        assert space.str_w(w_line) == "2\n"

        # XXX We ought to raise an EOFError here, but don't
        w_line = api.PyFile_GetLine(w_file, -1)
        # assert api.PyErr_Occurred() is space.w_EOFError
        assert space.str_w(w_line) == "line3\n"

        space.call_method(w_file, "close")
Example #13
0
    def test_AsEncodedObject(self, space, api):
        ptr = space.wrap('abc')

        errors = rffi.str2charp("strict")

        encoding = rffi.str2charp("hex")
        res = api.PyString_AsEncodedObject(ptr, encoding, errors)
        assert space.unwrap(res) == "616263"

        res = api.PyString_AsEncodedObject(ptr, encoding,
                                           lltype.nullptr(rffi.CCHARP.TO))
        assert space.unwrap(res) == "616263"
        rffi.free_charp(encoding)

        encoding = rffi.str2charp("unknown_encoding")
        self.raises(space, api, LookupError, api.PyString_AsEncodedObject, ptr,
                    encoding, errors)
        rffi.free_charp(encoding)

        rffi.free_charp(errors)

        res = api.PyString_AsEncodedObject(ptr, lltype.nullptr(rffi.CCHARP.TO),
                                           lltype.nullptr(rffi.CCHARP.TO))
        assert space.unwrap(res) == "abc"

        self.raises(space, api, TypeError, api.PyString_AsEncodedObject,
                    space.wrap(2), lltype.nullptr(rffi.CCHARP.TO),
                    lltype.nullptr(rffi.CCHARP.TO))
Example #14
0
    def test_AsEncodedObject(self, space, api):
        ptr = space.wrap('abc')

        errors = rffi.str2charp("strict")

        encoding = rffi.str2charp("hex")
        res = api.PyString_AsEncodedObject(
            ptr, encoding, errors)
        assert space.unwrap(res) == "616263"

        res = api.PyString_AsEncodedObject(
            ptr, encoding, lltype.nullptr(rffi.CCHARP.TO))
        assert space.unwrap(res) == "616263"
        rffi.free_charp(encoding)

        encoding = rffi.str2charp("unknown_encoding")
        self.raises(space, api, LookupError, api.PyString_AsEncodedObject,
                    ptr, encoding, errors)
        rffi.free_charp(encoding)

        rffi.free_charp(errors)

        res = api.PyString_AsEncodedObject(
            ptr, lltype.nullptr(rffi.CCHARP.TO), lltype.nullptr(rffi.CCHARP.TO))
        assert space.unwrap(res) == "abc"

        self.raises(space, api, TypeError, api.PyString_AsEncodedObject,
            space.wrap(2), lltype.nullptr(rffi.CCHARP.TO), lltype.nullptr(rffi.CCHARP.TO)
        )
Example #15
0
    def test_file_getline(self, space, api):
        filename = rffi.str2charp(str(udir / "_test_file"))

        mode = rffi.str2charp("w")
        w_file = api.PyFile_FromString(filename, mode)
        space.call_method(w_file, "write",
                          space.wrap("line1\nline2\nline3\nline4"))
        space.call_method(w_file, "close")

        rffi.free_charp(mode)
        mode = rffi.str2charp("r")
        w_file = api.PyFile_FromString(filename, mode)
        rffi.free_charp(filename)
        rffi.free_charp(mode)

        w_line = api.PyFile_GetLine(w_file, 0)
        assert space.str_w(w_line) == "line1\n"

        w_line = api.PyFile_GetLine(w_file, 4)
        assert space.str_w(w_line) == "line"

        w_line = api.PyFile_GetLine(w_file, 0)
        assert space.str_w(w_line) == "2\n"

        # XXX We ought to raise an EOFError here, but don't
        w_line = api.PyFile_GetLine(w_file, -1)
        # assert api.PyErr_Occurred() is space.w_EOFError
        assert space.str_w(w_line) == "line3\n"

        space.call_method(w_file, "close")
Example #16
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_DecodeUTF32(encoded_charp, len(encoded),
                                               strict_charp, pendian)
            assert space.eq_w(
                space.call_method(w_ustr, 'encode', space.wrap('ascii')),
                space.wrap("ab"))

            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')
Example #17
0
    def test_ascii_codec(self, space, api):
        s = 'abcdefg'
        data = rffi.str2charp(s)
        w_u = api.PyUnicode_DecodeASCII(data, len(s),
                                        lltype.nullptr(rffi.CCHARP.TO))
        assert space.eq_w(w_u, space.wrap(u"abcdefg"))
        rffi.free_charp(data)

        s = 'abcd\xFF'
        data = rffi.str2charp(s)
        self.raises(space, api, UnicodeDecodeError, api.PyUnicode_DecodeASCII,
                    data, len(s), lltype.nullptr(rffi.CCHARP.TO))
        rffi.free_charp(data)

        uni = u'abcdefg'
        data = rffi.unicode2wcharp(uni)
        w_s = api.PyUnicode_EncodeASCII(data, len(uni),
                                        lltype.nullptr(rffi.CCHARP.TO))
        assert space.eq_w(space.wrap("abcdefg"), w_s)
        rffi.free_wcharp(data)

        u = u'äbcdéfg'
        data = rffi.unicode2wcharp(u)
        w_s = api.PyUnicode_EncodeASCII(data, len(u),
                                        lltype.nullptr(rffi.CCHARP.TO))
        self.raises(space, api, UnicodeEncodeError, api.PyUnicode_EncodeASCII,
                    data, len(u), lltype.nullptr(rffi.CCHARP.TO))
        rffi.free_wcharp(data)
Example #18
0
        def bind_textdomain_codeset(space, domain, w_codeset):
            """bind_textdomain_codeset(domain, codeset) -> string
            Bind the C library's domain to codeset."""

            if space.is_w(w_codeset, space.w_None):
                codeset = None
                domain_c = rffi.str2charp(domain)
                try:
                    result = _bind_textdomain_codeset(domain_c, codeset)
                finally:
                    rffi.free_charp(domain_c)
            else:
                codeset = space.str_w(w_codeset)
                domain_c = rffi.str2charp(domain)
                codeset_c = rffi.str2charp(codeset)
                try:
                    result = _bind_textdomain_codeset(domain_c, codeset_c)
                finally:
                    rffi.free_charp(domain_c)
                    rffi.free_charp(codeset_c)

            if not result:
                return space.w_None
            else:
                return space.wrap(rffi.charp2str(result))
Example #19
0
def strcoll(space, w_s1, w_s2):
    "string,string -> int. Compares two strings according to the locale."

    if space.is_true(space.isinstance(w_s1, space.w_str)) and \
       space.is_true(space.isinstance(w_s2, space.w_str)):

        s1, s2 = space.str_w(w_s1), space.str_w(w_s2)
        s1_c = rffi.str2charp(s1)
        s2_c = rffi.str2charp(s2)
        try:
            return space.wrap(_strcoll(s1_c, s2_c))
        finally:
            rffi.free_charp(s1_c)
            rffi.free_charp(s2_c)

    #if not space.is_true(space.isinstance(w_s1, space.w_unicode)) and \
    #   not space.is_true(space.isinstance(w_s2, space.w_unicode)):
    #    raise OperationError(space.w_ValueError,
    #                         space.wrap("strcoll arguments must be strings"))

    s1, s2 = space.unicode_w(w_s1), space.unicode_w(w_s2)

    s1_c = rffi.unicode2wcharp(s1)
    s2_c = rffi.unicode2wcharp(s2)
    try:
        result = _wcscoll(s1_c, s2_c)
    finally:
        rffi.free_wcharp(s1_c)
        rffi.free_wcharp(s2_c)

    return space.wrap(result)
Example #20
0
 def test_dlopen(self):
     s = rffi.str2charp('xxxxxxxxxxxx')
     py.test.raises(DLOpenError, "dlopen(s)")
     rffi.free_charp(s)
     #
     s = rffi.str2charp(get_libc_name())
     assert dlopen(s)
     rffi.free_charp(s)
Example #21
0
 def test_newcode(self, space, api):
     filename = rffi.str2charp('filename')
     funcname = rffi.str2charp('funcname')
     w_code = api.PyCode_NewEmpty(filename, funcname, 3)
     assert w_code.co_filename == 'filename'
     assert w_code.co_firstlineno == 3
     rffi.free_charp(filename)
     rffi.free_charp(funcname)
Example #22
0
 def entry_point(argv):
     s = rffi.str2charp(argv[1])
     n = foobar(s)
     rffi.free_charp(s)
     s = rffi.str2charp(argv[n])
     n = foobar(s)
     rffi.free_charp(s)
     return n
Example #23
0
 def test_newcode(self, space, api):
     filename = rffi.str2charp('filename')
     funcname = rffi.str2charp('funcname')
     w_code = api.PyCode_NewEmpty(filename, funcname, 3)
     assert w_code.co_filename == 'filename'
     assert w_code.co_firstlineno == 3
     rffi.free_charp(filename)
     rffi.free_charp(funcname)
Example #24
0
 def test_dlopen(self):
     s = rffi.str2charp('xxxxxxxxxxxx')
     py.test.raises(DLOpenError, "dlopen(s)")
     rffi.free_charp(s)
     #
     s = rffi.str2charp(get_libc_name())
     assert dlopen(s)
     rffi.free_charp(s)
Example #25
0
def test_strlen():
    strlen = rffi.llexternal('strlen', [rffi.CCHARP], lltype.Signed,
                             includes=['string.h'])
    s = rffi.str2charp("xxx")
    res = strlen(s)
    rffi.free_charp(s)
    assert res == 3
    s = rffi.str2charp("")
    res = strlen(s)
    rffi.free_charp(s)
    assert res == 0
Example #26
0
    def dgettext(space, w_domain, msg):
        """dgettext(domain, msg) -> string
        Return translation of msg in domain."""
        if space.is_w(w_domain, space.w_None):
            domain = None
            result = _dgettext(domain, rffi.str2charp(msg))
        else:
            domain = space.str_w(w_domain)
            result = _dgettext(rffi.str2charp(domain), rffi.str2charp(msg))

        return space.wrap(rffi.charp2str(result))
Example #27
0
def dgettext(space, w_domain, msg):
    """dgettext(domain, msg) -> string
    Return translation of msg in domain."""
    if space.is_w(w_domain, space.w_None):
        domain = None
        result = _dgettext(domain, rffi.str2charp(msg))
    else:
        domain = space.str_w(w_domain)
        result = _dgettext(rffi.str2charp(domain), rffi.str2charp(msg))

    return space.wrap(rffi.charp2str(result))
Example #28
0
 def test_strlen(self):
     eci = ExternalCompilationInfo(includes=['string.h'])
     strlen = rffi.llexternal('strlen', [rffi.CCHARP], rffi.SIZE_T,
                              compilation_info=eci)
     s = rffi.str2charp("xxx")
     res = strlen(s)
     rffi.free_charp(s)
     assert res == 3     # actually r_size_t(3)
     s = rffi.str2charp("")
     res = strlen(s)
     rffi.free_charp(s)
     assert res == 0     # actually r_size_t(0)
     assert not ALLOCATED     # detects memory leaks in the test
Example #29
0
    def test_file_fromstring(self, space, api):
        filename = rffi.str2charp(str(udir / "_test_file"))
        mode = rffi.str2charp("wb")
        w_file = api.PyFile_FromString(filename, mode)
        rffi.free_charp(filename)
        rffi.free_charp(mode)

        assert api.PyFile_Check(w_file)
        assert api.PyFile_CheckExact(w_file)
        assert not api.PyFile_Check(space.wrap("text"))

        space.call_method(w_file, "write", space.wrap("text"))
        space.call_method(w_file, "close")
        assert (udir / "_test_file").read() == "text"
Example #30
0
 def test_strlen(self):
     eci = ExternalCompilationInfo(includes=['string.h'])
     strlen = rffi.llexternal('strlen', [rffi.CCHARP],
                              rffi.SIZE_T,
                              compilation_info=eci)
     s = rffi.str2charp("xxx")
     res = strlen(s)
     rffi.free_charp(s)
     assert res == 3  # actually r_size_t(3)
     s = rffi.str2charp("")
     res = strlen(s)
     rffi.free_charp(s)
     assert res == 0  # actually r_size_t(0)
     assert not ALLOCATED  # detects memory leaks in the test
Example #31
0
    def test_file_fromstring(self, space, api):
        filename = rffi.str2charp(str(udir / "_test_file"))
        mode = rffi.str2charp("wb")
        w_file = api.PyFile_FromString(filename, mode)
        rffi.free_charp(filename)
        rffi.free_charp(mode)

        assert api.PyFile_Check(w_file)
        assert api.PyFile_CheckExact(w_file)
        assert not api.PyFile_Check(space.wrap("text"))

        space.call_method(w_file, "write", space.wrap("text"))
        space.call_method(w_file, "close")
        assert (udir / "_test_file").read() == "text"
Example #32
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
        result = _dcgettext(domain, rffi.str2charp(msg),
                            rffi.cast(rffi.INT, category))
    else:
        domain = space.str_w(w_domain)
        result = _dcgettext(rffi.str2charp(domain), rffi.str2charp(msg),
                            rffi.cast(rffi.INT, category))

    return space.wrap(rffi.charp2str(result))
Example #33
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
            result = _dcgettext(domain, rffi.str2charp(msg),
                                rffi.cast(rffi.INT, category))
        else:
            domain = space.str_w(w_domain)
            result = _dcgettext(rffi.str2charp(domain), rffi.str2charp(msg),
                                rffi.cast(rffi.INT, category))

        return space.wrap(rffi.charp2str(result))
Example #34
0
def get_new_method_def(space):
    state = space.fromcache(State)
    if state.new_method_def:
        return state.new_method_def
    from pypy.module.cpyext.modsupport import PyMethodDef
    ptr = lltype.malloc(PyMethodDef, flavor="raw", zero=True,
                        immortal=True)
    ptr.c_ml_name = rffi.str2charp("__new__")
    lltype.render_immortal(ptr.c_ml_name)
    rffi.setintfield(ptr, 'c_ml_flags', METH_VARARGS | METH_KEYWORDS)
    ptr.c_ml_doc = rffi.str2charp(
        "T.__new__(S, ...) -> a new object with type S, a subtype of T")
    lltype.render_immortal(ptr.c_ml_doc)
    state.new_method_def = ptr
    return ptr
Example #35
0
 def test_setitemstring(self, space, api):
     w_d = space.newdict()
     key = rffi.str2charp("key")
     api.PyMapping_SetItemString(w_d, key, space.wrap(42))
     assert 42 == space.unwrap(
         api.PyMapping_GetItemString(w_d, key))
     rffi.free_charp(key)
Example #36
0
def setlocale(space, category, w_locale=None):
    "(integer,string=None) -> string. Activates/queries locale processing."

    if cConfig.LC_MAX is not None:
        if not cConfig.LC_MIN <= category <= cConfig.LC_MAX:
            raise make_error(space, "invalid locale category")

    if space.is_w(w_locale, space.w_None) or w_locale is None:
        result = _setlocale(rffi.cast(rffi.INT, category), None)
        if not result:
            raise make_error(space, "locale query failed")
    else:
        locale = rffi.str2charp(space.str_w(w_locale))

        result = _setlocale(rffi.cast(rffi.INT, category), locale)
        if not result:
            raise make_error(space, "unsupported locale setting")

        # record changes to LC_CTYPE
        if category in (LC_CTYPE, LC_ALL):
            w_module = space.getbuiltinmodule('_locale')
            w_fun = space.getattr(w_module, space.wrap('_fixup_ulcase'))
            space.call_function(w_fun)

    return space.wrap(rffi.charp2str(result))
Example #37
0
def demo(filename):
    width = 800
    height = 600
    surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32,width,height)
    cr = cairo_create(surface)
    cairo_scale(cr, width, height)
    cairo_set_line_width(cr, 0.04)

    
    cairo_arc(cr, 0.5, 0.5, 0.3, 0, 2 * pi)
    cairo_clip(cr)
    
    cairo_new_path(cr) # current path is not
                       # consumed by cairo_clip()
    cairo_rectangle(cr, 0, 0, 1, 1)
    cairo_fill(cr)
    cairo_set_source_rgb(cr, 0, 1, 0)
    cairo_move_to(cr, 0, 0)
    cairo_line_to(cr, 1, 1)
    cairo_move_to(cr, 1, 0)
    cairo_line_to(cr, 0, 1)
    cairo_stroke(cr)

    #_cairo_surface_write_to_png(surface, 'foo.png') # XXX why does this fail to compile ??
    path = rffi.str2charp(filename)
    cairo_surface_write_to_png(surface, path)
    rffi.free_charp(path)

    cairo_destroy(cr)
    cairo_surface_destroy(surface)
    return 0
Example #38
0
def demo(filename):
    width = 800
    height = 600
    surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height)
    cr = cairo_create(surface)
    cairo_scale(cr, width, height)
    cairo_set_line_width(cr, 0.04)

    cairo_arc(cr, 0.5, 0.5, 0.3, 0, 2 * pi)
    cairo_clip(cr)

    cairo_new_path(cr)  # current path is not
    # consumed by cairo_clip()
    cairo_rectangle(cr, 0, 0, 1, 1)
    cairo_fill(cr)
    cairo_set_source_rgb(cr, 0, 1, 0)
    cairo_move_to(cr, 0, 0)
    cairo_line_to(cr, 1, 1)
    cairo_move_to(cr, 1, 0)
    cairo_line_to(cr, 0, 1)
    cairo_stroke(cr)

    #_cairo_surface_write_to_png(surface, 'foo.png') # XXX why does this fail to compile ??
    path = rffi.str2charp(filename)
    cairo_surface_write_to_png(surface, path)
    rffi.free_charp(path)

    cairo_destroy(cr)
    cairo_surface_destroy(surface)
    return 0
Example #39
0
def buffer_attach(space, py_obj, w_obj):
    """
    Fills a newly allocated PyBufferObject with the given (str) buffer object.
    """
    py_buf = rffi.cast(PyBufferObject, py_obj)
    py_buf.c_b_offset = 0
    rffi.setintfield(py_buf, 'c_b_readonly', 1)
    rffi.setintfield(py_buf, 'c_b_hash', -1)

    if isinstance(w_obj, SubBuffer):
        py_buf.c_b_offset = w_obj.offset
        w_obj = w_obj.buffer

    # If w_obj already allocated a fixed buffer, use it, and keep a
    # reference to w_obj.
    # Otherwise, b_base stays NULL, and we own the b_ptr.

    if isinstance(w_obj, StringBuffer):
        py_buf.c_b_base = lltype.nullptr(PyObject.TO)
        py_buf.c_b_ptr = rffi.cast(rffi.VOIDP, rffi.str2charp(w_obj.value))
        py_buf.c_b_size = w_obj.getlength()
    elif isinstance(w_obj, ArrayBuffer):
        w_base = w_obj.array
        py_buf.c_b_base = make_ref(space, w_base)
        py_buf.c_b_ptr = rffi.cast(rffi.VOIDP, w_obj.array._charbuf_start())
        py_buf.c_b_size = w_obj.getlength()
    else:
        raise OperationError(space.w_NotImplementedError, space.wrap(
            "buffer flavor not supported"))
Example #40
0
def setlocale(space, category, w_locale=None):
    "(integer,string=None) -> string. Activates/queries locale processing."

    if cConfig.LC_MAX is not None:
        if not cConfig.LC_MIN <= category <= cConfig.LC_MAX:
            raise make_error(space, "invalid locale category")

    if space.is_w(w_locale, space.w_None) or w_locale is None:
        result = _setlocale(rffi.cast(rffi.INT, category), None)
        if not result:
            raise make_error(space, "locale query failed")
    else:
        locale = rffi.str2charp(space.str_w(w_locale))

        result = _setlocale(rffi.cast(rffi.INT, category), locale)
        if not result:
            raise make_error(space, "unsupported locale setting")

        # record changes to LC_CTYPE
        if category in (LC_CTYPE, LC_ALL):
            w_module = space.getbuiltinmodule('_locale')
            w_fun = space.getattr(w_module, space.wrap('_fixup_ulcase'))
            space.call_function(w_fun)

    return space.wrap(rffi.charp2str(result))
Example #41
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()
Example #42
0
def ioctl(space, w_fd, op, w_arg=0, mutate_flag=True):
    """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.

    The argument arg is optional, and defaults to 0; it may be an int or a
    buffer containing character data (most likely a string or an array).

    If the argument is a mutable buffer (such as an array) and if the
    mutate_flag argument (which is only allowed in this case) is true then the
    buffer is (in effect) passed to the operating system and changes made by
    the OS will be reflected in the contents of the buffer after the call has
    returned.  The return value is the integer returned by the ioctl system
    call.

    If the argument is a mutable buffer and the mutable_flag argument is not
    passed or is false, the behavior is as if a string had been passed.  This
    behavior will change in future releases of Python.

    If the argument is an immutable buffer (most likely a string) then a copy
    of the buffer is passed to the operating system and the return value is a
    string of the same length containing whatever the operating system put in
    the buffer.  The length of the arg buffer in this case is not allowed to
    exceed 1024 bytes.

    If the arg given is an integer or if none is specified, the result value
    is an integer corresponding to the return value of the ioctl call in the
    C code."""
    fd = _conv_descriptor(space, w_fd)
    # Python turns number > sys.maxint into long, we need the signed C value
    op = rffi.cast(rffi.INT, op)

    IOCTL_BUFSZ = 1024
    
    if space.is_w(space.type(w_arg), space.w_int):
        arg = space.int_w(w_arg)
        rv = ioctl_int(fd, op, arg)
        if rv < 0:
            raise OperationError(space.w_IOError,
                space.wrap(_get_error_msg()))
        return space.wrap(rv)
    elif space.is_w(space.type(w_arg), space.w_str): # immutable
        arg = space.str_w(w_arg)
        if len(arg) > IOCTL_BUFSZ:
            raise OperationError(space.w_ValueError,
                space.wrap("ioctl string arg too long"))
    
        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 OperationError(space.w_IOError,
                space.wrap(_get_error_msg()))
        return space.wrap(arg)
    else:
        raise OperationError(space.w_TypeError,
                space.wrap("an integer or a buffer required"))
Example #43
0
 def SetPythonHome(self,path):
     return
     impl = self.lib.getpointer("Py_SetPythonHome",[clibffi.ffi_type_pointer],clibffi.ffi_type_void)
     buf = rffi.str2charp(path)
     impl.push_arg(buf)
     impl.call(lltype.Void)
     rffi.free_charp(buf)
Example #44
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()
Example #45
0
    def test_getattr(self, space, api):
        charp1 = rffi.str2charp("__len__")
        charp2 = rffi.str2charp("not_real")
        assert api.PyObject_GetAttrString(space.wrap(""), charp1)
        assert not api.PyObject_GetAttrString(space.wrap(""), charp2)
        assert api.PyErr_Occurred() is space.w_AttributeError
        api.PyErr_Clear()
        assert api.PyObject_DelAttrString(space.wrap(""), charp1) == -1
        assert api.PyErr_Occurred() is space.w_AttributeError
        api.PyErr_Clear()
        rffi.free_charp(charp1)
        rffi.free_charp(charp2)

        assert api.PyObject_GetAttr(space.wrap(""), space.wrap("__len__"))
        assert api.PyObject_DelAttr(space.wrap(""), space.wrap("__len__")) == -1
        api.PyErr_Clear()
Example #46
0
    def getattr(self, space, attr):
        try:
            attribute = self.objectType.attributesByName[attr]
        except KeyError:
            msg = "ExternalObject has no attribute '%s'" %(attr,)
            raise OperationError(space.w_AttributeError, space.wrap(msg))

        environment = self.objectType.environment

        scalarvalueindicatorptr = lltype.malloc(rffi.CArrayPtr(roci.OCIInd).TO,
                                                1, flavor='raw')
        valueindicatorptr = lltype.malloc(rffi.CArrayPtr(roci.dvoidp).TO,
                                          1, flavor='raw')
        valueptr = lltype.malloc(rffi.CArrayPtr(roci.dvoidp).TO,
                                 1, flavor='raw')
        tdoptr = lltype.malloc(rffi.CArrayPtr(roci.OCIType).TO,
                               1, flavor='raw')
        nameptr = lltype.malloc(rffi.CArrayPtr(roci.oratext).TO,
                               1, flavor='raw')
        nameptr[0] = rffi.str2charp(attr)
        namelenptr = lltype.malloc(rffi.CArrayPtr(roci.ub4).TO,
                                   1, flavor='raw')
        namelenptr[0] = rffi.cast(roci.ub4, len(attr))

        try:
            status = roci.OCIObjectGetAttr(
                environment.handle,
                environment.errorHandle,
                self.instance,
                self.indicator,
                self.objectType.tdo,
                nameptr, namelenptr, 1,
                lltype.nullptr(roci.Ptr(roci.ub4).TO), 0,
                scalarvalueindicatorptr,
                valueindicatorptr,
                valueptr,
                tdoptr)
            environment.checkForError(
                status, "ExternalObject_GetAttributeValue(): getting value")

            # determine the proper null indicator
            valueIndicator = valueindicatorptr[0]
            if not valueIndicator:
                valueIndicator = rffi.cast(roci.dvoidp,
                                           scalarvalueindicatorptr)
            value = valueptr[0]

            return convertObject(
                space, environment,
                attribute.typeCode,
                value, valueIndicator,
                self, attribute.subType)
        finally:
            lltype.free(scalarvalueindicatorptr, flavor='raw')
            lltype.free(valueindicatorptr, flavor='raw')
            lltype.free(valueptr, flavor='raw')
            lltype.free(tdoptr, flavor='raw')
            rffi.free_charp(nameptr[0])
            lltype.free(nameptr, flavor='raw')
            lltype.free(namelenptr, flavor='raw')
Example #47
0
 def fill(self, space, w_value):
     if w_value is None or space.is_w(w_value, space.w_None):
         self.clear()
     else:
         strvalue = space.str_w(w_value)
         self.ptr = rffi.str2charp(strvalue)
         self.size = len(strvalue)
Example #48
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)
    dataptr = rffi.str2charp(value)
    try:
        ret = rwinreg.RegSetValue(hkey, subkey, rwinreg.REG_SZ, dataptr, len(value))
    finally:
        rffi.free_charp(dataptr)
    if ret != 0:
        raiseWindowsError(space, ret, 'RegSetValue')
Example #49
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)
Example #50
0
def bind_textdomain_codeset(space, domain, w_codeset):
    """bind_textdomain_codeset(domain, codeset) -> string
    Bind the C library's domain to codeset."""

    if space.is_w(w_codeset, space.w_None):
        codeset = None
        result = _bind_textdomain_codeset(rffi.str2charp(domain), codeset)
    else:
        codeset = space.str_w(w_codeset)
        result = _bind_textdomain_codeset(rffi.str2charp(domain),
                                        rffi.str2charp(codeset))

    if not result:
        return space.w_None
    else:
        return space.wrap(rffi.charp2str(result))
Example #51
0
    def getattr(self, space, attr):
        try:
            attribute = self.objectType.attributesByName[attr]
        except KeyError:
            msg = "ExternalObject has no attribute '%s'" %(attr,)
            raise OperationError(space.w_AttributeError, space.wrap(msg))

        environment = self.objectType.environment

        scalarvalueindicatorptr = lltype.malloc(rffi.CArrayPtr(roci.OCIInd).TO,
                                                1, flavor='raw')
        valueindicatorptr = lltype.malloc(rffi.CArrayPtr(roci.dvoidp).TO,
                                          1, flavor='raw')
        valueptr = lltype.malloc(rffi.CArrayPtr(roci.dvoidp).TO,
                                 1, flavor='raw')
        tdoptr = lltype.malloc(rffi.CArrayPtr(roci.OCIType).TO,
                               1, flavor='raw')
        nameptr = lltype.malloc(rffi.CArrayPtr(roci.oratext).TO,
                               1, flavor='raw')
        nameptr[0] = rffi.str2charp(attr)
        namelenptr = lltype.malloc(rffi.CArrayPtr(roci.ub4).TO,
                                   1, flavor='raw')
        namelenptr[0] = rffi.cast(roci.ub4, len(attr))

        try:
            status = roci.OCIObjectGetAttr(
                environment.handle,
                environment.errorHandle,
                self.instance,
                self.indicator,
                self.objectType.tdo,
                nameptr, namelenptr, 1,
                lltype.nullptr(roci.Ptr(roci.ub4).TO), 0,
                scalarvalueindicatorptr,
                valueindicatorptr,
                valueptr,
                tdoptr)
            environment.checkForError(
                status, "ExternalObject_GetAttributeValue(): getting value")

            # determine the proper null indicator
            valueIndicator = valueindicatorptr[0]
            if not valueIndicator:
                valueIndicator = rffi.cast(roci.dvoidp,
                                           scalarvalueindicatorptr)
            value = valueptr[0]

            return convertObject(
                space, environment,
                attribute.typeCode,
                value, valueIndicator,
                self, attribute.subType)
        finally:
            lltype.free(scalarvalueindicatorptr, flavor='raw')
            lltype.free(valueindicatorptr, flavor='raw')
            lltype.free(valueptr, flavor='raw')
            lltype.free(tdoptr, flavor='raw')
            rffi.free_charp(nameptr[0])
            lltype.free(nameptr, flavor='raw')
            lltype.free(namelenptr, flavor='raw')
Example #52
0
 def Sys_SetPath(self, path):
     impl = self.lib.getpointer("PySys_SetPath", [libffi.ffi_type_pointer],
                                libffi.ffi_type_void)
     buf = rffi.str2charp(path)
     impl.push_arg(buf)
     impl.call(lltype.Void)
     rffi.free_charp(buf)
Example #53
0
def _make_mode(vm_path, path, bc, verbosity, mk_fresh):
    # Try to work out a plausible cached path name.
    dp = path.rfind(os.extsep)
    if dp >= 0 and os.sep not in path[dp:]:
        cp = path[:dp]
    else:
        cp = None
    
    if not cp or mk_fresh:
        return _do_make_mode(vm_path, path, None, verbosity, mk_fresh)
    else:
		# There is a cached path, so now we try and load it and see if it is upto date. If any part
		# of this fails, we simply go straight to full make mode.
        try:
            st = os.stat(cp)
        except OSError:
            return _do_make_mode(vm_path, path, cp, verbosity, mk_fresh)
        
        cbc, start = _read_bc(cp, "CONVEXEC")
        if start == -1:
            return _do_make_mode(vm_path, path, cp, verbosity, mk_fresh)
        
        assert start >= 0
        useful_bc = cbc[start:]
        if Bytecode.exec_upto_date(None, rffi.str2charp(useful_bc), st.st_mtime):
            return cbc, start, 0
        
        return _do_make_mode(vm_path, path, cp, verbosity, mk_fresh)
Example #54
0
 def execv_lltypeimpl(path, args):
     l_path = rffi.str2charp(path)
     l_args = rffi.liststr2charpp(args)
     os_execv(l_path, l_args)
     rffi.free_charpp(l_args)
     rffi.free_charp(l_path)
     raise OSError(rffi.c_errno, "execv failed")
Example #55
0
 def test_overflow_neg(self, api):
     s = rffi.str2charp('-1e500')
     null = lltype.nullptr(rffi.CCHARPP.TO)
     r = api.PyOS_string_to_double(s, null, None)
     assert math.isinf(r)
     assert r < 0
     rffi.free_charp(s)
Example #56
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)
Example #57
0
def buffer_attach(space, py_obj, w_obj):
    """
    Fills a newly allocated PyBufferObject with the given (str) buffer object.
    """
    py_buf = rffi.cast(PyBufferObject, py_obj)
    py_buf.c_b_offset = 0
    rffi.setintfield(py_buf, 'c_b_readonly', 1)
    rffi.setintfield(py_buf, 'c_b_hash', -1)

    if isinstance(w_obj, SubBuffer):
        py_buf.c_b_offset = w_obj.offset
        w_obj = w_obj.buffer

    # If w_obj already allocated a fixed buffer, use it, and keep a
    # reference to w_obj.
    # Otherwise, b_base stays NULL, and we own the b_ptr.

    if isinstance(w_obj, StringBuffer):
        py_buf.c_b_base = lltype.nullptr(PyObject.TO)
        py_buf.c_b_ptr = rffi.cast(rffi.VOIDP, rffi.str2charp(w_obj.value))
        py_buf.c_b_size = w_obj.getlength()
    elif isinstance(w_obj, ArrayBuffer):
        w_base = w_obj.array
        py_buf.c_b_base = make_ref(space, w_base)
        py_buf.c_b_ptr = rffi.cast(rffi.VOIDP, w_obj.array._charbuf_start())
        py_buf.c_b_size = w_obj.getlength()
    else:
        raise OperationError(space.w_NotImplementedError,
                             space.wrap("buffer flavor not supported"))
Example #58
0
        def bind_textdomain_codeset(space, domain, w_codeset):
            """bind_textdomain_codeset(domain, codeset) -> string
            Bind the C library's domain to codeset."""

            if space.is_w(w_codeset, space.w_None):
                codeset = None
                result = _bind_textdomain_codeset(rffi.str2charp(domain),
                                                  codeset)
            else:
                codeset = space.str_w(w_codeset)
                result = _bind_textdomain_codeset(rffi.str2charp(domain),
                                                  rffi.str2charp(codeset))

            if not result:
                return space.w_None
            else:
                return space.wrap(rffi.charp2str(result))