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)
def load_lib(self): if not self._is_inited: load_paths = rt.deref(rt.deref(rt.load_paths)) for x in range(rt.count(load_paths)): s = rffi.str2charp(str(rt.name(rt.nth(load_paths, rt.wrap(x)))) + "/" + str(self._name)) try: self._dyn_lib = dynload.dlopen(s) self._is_inited = True except dynload.DLOpenError as ex: continue finally: rffi.free_charp(s) break if not self._is_inited: s = rffi.str2charp(str(self._name)) try: self._dyn_lib = dynload.dlopen(s) self._is_inited = True except dynload.DLOpenError as ex: raise object.runtime_error(u"Couldn't Load Library: " + self._name, u"pixie.stdlib/LibraryNotFoundException") finally: rffi.free_charp(s)
def test_dlsym(self): s = rffi.str2charp(get_libc_name()) lib = dlopen(s) rffi.free_charp(s) handle = rffi.cast(lltype.Ptr(lltype.FuncType([lltype.Signed], lltype.Signed)), dlsym(lib, "abs")) assert 1 == handle(1) assert 1 == handle(-1)
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)
def parse_c_type(info, input): p_input = rffi.str2charp(input) try: res = ll_parse_c_type(info, p_input) finally: rffi.free_charp(p_input) return rffi.cast(lltype.Signed, res)
def strcoll(space, w_s1, w_s2): "string,string -> int. Compares two strings according to the locale." if (space.isinstance_w(w_s1, space.w_str) and space.isinstance_w(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) 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)
def test_Warning(self, space, api, capfd): message = rffi.str2charp("this is a warning") api.PyErr_WarnEx(None, message, 1) space.call_method(space.sys.get('stderr'), "flush") out, err = capfd.readouterr() assert ": UserWarning: this is a warning" in err rffi.free_charp(message)
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)
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)
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')
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')
def c_stdvector_valuetype(space, pystr): cstr = rffi.str2charp(pystr) result = _c_stdvector_valuetype(cstr) rffi.free_charp(cstr) if result: return charp2str_free(space, result) return ""
def get_fn_ptr(self, nm): assert isinstance(nm, unicode) self.thaw() s = rffi.str2charp(str(nm)) sym = dynload.dlsym(self._dyn_lib, s) rffi.free_charp(s) return sym
def gettext(space, msg): """gettext(msg) -> string Return translation of msg.""" msg_c = rffi.str2charp(msg) try: return space.wrap(rffi.charp2str(_gettext(msg_c))) finally: rffi.free_charp(msg_c)
def test_decode_null_encoding(self, space, api): null_charp = lltype.nullptr(rffi.CCHARP.TO) u_text = u'abcdefg' s_text = space.str_w(api.PyUnicode_AsEncodedString(space.wrap(u_text), null_charp, null_charp)) b_text = rffi.str2charp(s_text) assert space.unwrap(api.PyUnicode_Decode(b_text, len(s_text), null_charp, null_charp)) == u_text self.raises(space, api, TypeError, api.PyUnicode_FromEncodedObject, space.wrap(u_text), null_charp, None) rffi.free_charp(b_text)
def test_precision(self, api): ptype = lltype.malloc(rffi.INTP.TO, 1, flavor='raw') r = api.PyOS_double_to_string(3.14159269397, 'g', 5, 0, ptype) assert '3.1416' == rffi.charp2str(r) type_value = rffi.cast(lltype.Signed, ptype[0]) assert pystrtod.Py_DTST_FINITE == type_value rffi.free_charp(r) lltype.free(ptype, flavor='raw')
def test_flags_alt(self, api): ptype = lltype.malloc(rffi.INTP.TO, 1, flavor='raw') r = api.PyOS_double_to_string(314., 'g', 3, 4, ptype) assert '314.' == rffi.charp2str(r) type_value = rffi.cast(lltype.Signed, ptype[0]) assert pystrtod.Py_DTST_FINITE == type_value rffi.free_charp(r) lltype.free(ptype, flavor='raw')
def test_ptype_nan(self, api): ptype = lltype.malloc(rffi.INTP.TO, 1, flavor='raw') r = api.PyOS_double_to_string(float('nan'), 'g', 3, 4, ptype) assert 'nan' == rffi.charp2str(r) type_value = rffi.cast(lltype.Signed, ptype[0]) assert pystrtod.Py_DTST_NAN == type_value rffi.free_charp(r) lltype.free(ptype, flavor='raw')
def test_ptype_infinity(self, api): ptype = lltype.malloc(rffi.INTP.TO, 1, flavor='raw') r = api.PyOS_double_to_string(1e200 * 1e200, 'g', 0, 0, ptype) assert 'inf' == rffi.charp2str(r) type_value = rffi.cast(lltype.Signed, ptype[0]) assert pystrtod.Py_DTST_INFINITE == type_value rffi.free_charp(r) lltype.free(ptype, flavor='raw')
def buffer_dealloc(space, py_obj): py_buf = rffi.cast(PyBufferObject, py_obj) if py_buf.c_b_base: Py_DecRef(space, py_buf.c_b_base) else: rffi.free_charp(rffi.cast(rffi.CCHARP, py_buf.c_b_ptr)) from pypy.module.cpyext.object import PyObject_dealloc PyObject_dealloc(space, py_obj)
def test_bad_string(self, api): s = rffi.str2charp(' 0.4') null = lltype.nullptr(rffi.CCHARPP.TO) r = api.PyOS_string_to_double(s, null, None) assert r == -1.0 raises(ValueError) api.PyErr_Clear() rffi.free_charp(s)
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)
def test_overflow_exc(self, space, api): s = rffi.str2charp('1e500') null = lltype.nullptr(rffi.CCHARPP.TO) r = api.PyOS_string_to_double(s, null, space.w_ValueError) assert r == -1.0 raises(ValueError) api.PyErr_Clear() rffi.free_charp(s)
def test_format_code(self, api): ptype = lltype.malloc(rffi.INTP.TO, 1, flavor='raw') r = api.PyOS_double_to_string(150.0, 'e', 1, 0, ptype) assert '1.5e+02' == rffi.charp2str(r) type_value = rffi.cast(lltype.Signed, ptype[0]) assert pystrtod.Py_DTST_FINITE == type_value rffi.free_charp(r) lltype.free(ptype, flavor='raw')
def test_Occurred(self, space, api): assert not api.PyErr_Occurred() string = rffi.str2charp("spam and eggs") api.PyErr_SetString(space.w_ValueError, string) rffi.free_charp(string) assert api.PyErr_Occurred() is space.w_ValueError api.PyErr_Clear()
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)
def test_incremental(self, space, api): utf8 = rffi.str2charp('utf-8') w_encoder = api.PyCodec_IncrementalEncoder(utf8, None) w_encoded = space.call_method(w_encoder, 'encode', space.wrap(u'späm')) w_decoder = api.PyCodec_IncrementalDecoder(utf8, None) w_decoded = space.call_method(w_decoder, 'decode', w_encoded) assert space.unwrap(w_decoded) == u'späm' rffi.free_charp(utf8)
def fltk_get_file(): charp = rffi.str2charp("".join(["\0"] * 260)) res = __llget_file(charp, 260) if (res == 1): path = rffi.charp2str(charp) rffi.free_charp(charp) return path else: return _Default
def wrap_getattr(space, w_self, w_args, func): func_target = rffi.cast(getattrfunc, func) check_num_args(space, w_args, 1) args_w = space.fixedview(w_args) name_ptr = rffi.str2charp(space.str_w(args_w[0])) try: return generic_cpy_call(space, func_target, w_self, name_ptr) finally: rffi.free_charp(name_ptr)
def test_libintl(): if sys.platform != "darwin" and not sys.platform.startswith("linux"): py.test.skip("there is (maybe) no libintl here") _gettext = external('gettext', [rffi.CCHARP], rffi.CCHARP) p = rffi.str2charp("1234") res = _gettext(p) assert res == p assert rffi.charp2str(res) == "1234" rffi.free_charp(p)
def test_getattr(self, space): charp1 = rffi.str2charp("__len__") charp2 = rffi.str2charp("not_real") assert PyObject_GetAttrString(space, space.wrap(""), charp1) with raises_w(space, AttributeError): PyObject_GetAttrString(space, space.wrap(""), charp2) with raises_w(space, AttributeError): PyObject_DelAttrString(space, space.wrap(""), charp1) rffi.free_charp(charp1) rffi.free_charp(charp2) assert PyObject_GetAttr(space, space.wrap(""), space.wrap("__len__")) with raises_w(space, AttributeError): PyObject_DelAttr(space, space.wrap(""), space.wrap("__len__"))
def recv_bytes(self, space, maxlength=PY_SSIZE_T_MAX): self._check_readable(space) if maxlength < 0: raise OperationError(space.w_ValueError, space.wrap("maxlength < 0")) res, newbuf = self.do_recv_string(space, self.BUFFER_SIZE, maxlength) try: if newbuf: return space.wrap(rffi.charpsize2str(newbuf, res)) else: return space.wrap(rffi.charpsize2str(self.buffer, res)) finally: if newbuf: rffi.free_charp(newbuf)
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()
def recv_bytes_into(self, space, w_buffer, offset=0): rwbuffer = space.writebuf_w(w_buffer) length = rwbuffer.getlength() res, newbuf = self.do_recv_string(space, length - offset, PY_SSIZE_T_MAX) try: if newbuf: raise BufferTooShort( space, space.wrapbytes(rffi.charpsize2str(newbuf, res))) rwbuffer.setslice(offset, rffi.charpsize2str(self.buffer, res)) finally: if newbuf: rffi.free_charp(newbuf) return space.wrap(res)
def test_decode_null_encoding(self, space): null_charp = lltype.nullptr(rffi.CCHARP.TO) u_text = u'abcdefg' s_text = space.str_w( PyUnicode_AsEncodedString(space, space.wrap(u_text), null_charp, null_charp)) b_text = rffi.str2charp(s_text) assert space.unicode_w( PyUnicode_Decode(space, b_text, len(s_text), null_charp, null_charp)) == u_text with raises_w(space, TypeError): PyUnicode_FromEncodedObject(space, space.wrap(u_text), null_charp, None) assert space.unicode_w( PyUnicode_FromEncodedObject(space, space.wrap(s_text), null_charp, None)) == u_text rffi.free_charp(b_text)
def test_run_file(self, space): filepath = udir / "cpyext_test_runfile.py" filepath.write("raise ZeroDivisionError") fp = c_fopen(str(filepath), "rb") filename = rffi.str2charp(str(filepath)) w_globals = w_locals = space.newdict() with raises_w(space, ZeroDivisionError): PyRun_File(space, fp, filename, Py_file_input, w_globals, w_locals) c_fclose(fp) # try again, but with a closed file fp = c_fopen(str(filepath), "rb") os.close(c_fileno(fp)) with raises_w(space, IOError): PyRun_File(space, fp, filename, Py_file_input, w_globals, w_locals) c_fclose(fp) rffi.free_charp(filename)
def test_SetAttr(self, space, api): w_obj = space.appexec([], """(): class C: pass return C()""") api.PyObject_SetAttr(w_obj, space.wrap('test'), space.wrap(5)) assert not api.PyErr_Occurred() assert space.unwrap(space.getattr(w_obj, space.wrap('test'))) == 5 assert api.PyObject_HasAttr(w_obj, space.wrap('test')) api.PyObject_SetAttr(w_obj, space.wrap('test'), space.wrap(10)) assert space.unwrap(space.getattr(w_obj, space.wrap('test'))) == 10 buf = rffi.str2charp('test') api.PyObject_SetAttrString(w_obj, buf, space.wrap(20)) rffi.free_charp(buf) assert space.unwrap(space.getattr(w_obj, space.wrap('test'))) == 20
def test_latin1(self, space, api): s = 'abcdefg' data = rffi.str2charp(s) w_u = api.PyUnicode_DecodeLatin1(data, len(s), lltype.nullptr(rffi.CCHARP.TO)) assert space.eq_w(w_u, space.wrap(u"abcdefg")) rffi.free_charp(data) uni = u'abcdefg' data = rffi.unicode2wcharp(uni) w_s = api.PyUnicode_EncodeLatin1(data, len(uni), lltype.nullptr(rffi.CCHARP.TO)) assert space.eq_w(space.wrapbytes("abcdefg"), w_s) rffi.free_wcharp(data) ustr = "abcdef" w_ustr = space.wrap(ustr.decode("ascii")) result = api.PyUnicode_AsLatin1String(w_ustr) assert space.eq_w(space.wrapbytes(ustr), result)
def test_dict(self, space, api): d = api.PyDict_New() assert space.eq_w(d, space.newdict()) assert space.eq_w( api.PyDict_GetItem(space.wrap({"a": 72}), space.wrap("a")), space.wrap(72)) assert api.PyDict_SetItem(d, space.wrap("c"), space.wrap(42)) >= 0 assert space.eq_w(space.getitem(d, space.wrap("c")), space.wrap(42)) space.setitem(d, space.wrap("name"), space.wrap(3)) assert space.eq_w(api.PyDict_GetItem(d, space.wrap("name")), space.wrap(3)) space.delitem(d, space.wrap("name")) assert not api.PyDict_GetItem(d, space.wrap("name")) assert not api.PyErr_Occurred() buf = rffi.str2charp("name") assert not api.PyDict_GetItemString(d, buf) rffi.free_charp(buf) assert not api.PyErr_Occurred() assert api.PyDict_Contains(d, space.wrap("c")) assert not api.PyDict_Contains(d, space.wrap("z")) assert api.PyDict_DelItem(d, space.wrap("c")) == 0 assert api.PyDict_DelItem(d, space.wrap("name")) < 0 assert api.PyErr_Occurred() is space.w_KeyError api.PyErr_Clear() assert api.PyDict_Size(d) == 0 space.setitem(d, space.wrap("some_key"), space.wrap(3)) buf = rffi.str2charp("some_key") assert api.PyDict_DelItemString(d, buf) == 0 assert api.PyDict_Size(d) == 0 assert api.PyDict_DelItemString(d, buf) < 0 assert api.PyErr_Occurred() is space.w_KeyError api.PyErr_Clear() rffi.free_charp(buf) d = space.wrap({'a': 'b'}) api.PyDict_Clear(d) assert api.PyDict_Size(d) == 0
def test_decode(self, space): b_text = rffi.str2charp('caf\x82xx') b_encoding = rffi.str2charp('cp437') assert space.utf8_w( PyUnicode_Decode(space, b_text, 4, b_encoding, None)) == u'caf\xe9'.encode('utf8') w_text = PyUnicode_FromEncodedObject(space, space.wrap("test"), b_encoding, None) assert space.isinstance_w(w_text, space.w_unicode) assert space.utf8_w(w_text) == "test" with raises_w(space, TypeError): PyUnicode_FromEncodedObject(space, space.wrap(u"test"), b_encoding, None) with raises_w(space, TypeError): PyUnicode_FromEncodedObject(space, space.wrap(1), b_encoding, None) rffi.free_charp(b_text) rffi.free_charp(b_encoding)
def test_decode(self, space, api): b_text = rffi.str2charp('caf\x82xx') b_encoding = rffi.str2charp('cp437') assert space.unwrap( api.PyUnicode_Decode(b_text, 4, b_encoding, None)) == u'caf\xe9' w_text = api.PyUnicode_FromEncodedObject(space.wrapbytes("test"), b_encoding, None) assert space.isinstance_w(w_text, space.w_unicode) assert space.unwrap(w_text) == "test" assert api.PyUnicode_FromEncodedObject(space.wrap(u"test"), b_encoding, None) is None assert api.PyErr_Occurred() is space.w_TypeError assert api.PyUnicode_FromEncodedObject(space.wrap(1), b_encoding, None) is None assert api.PyErr_Occurred() is space.w_TypeError api.PyErr_Clear() rffi.free_charp(b_text) rffi.free_charp(b_encoding)
def test_run_file(self, space): filepath = udir / "cpyext_test_runfile.py" filepath.write("raise ZeroDivisionError") fp = c_fopen(str(filepath), "rb") filename = rffi.str2charp(str(filepath)) w_globals = w_locals = space.newdict() with raises_w(space, ZeroDivisionError): PyRun_File(space, fp, filename, Py_file_input, w_globals, w_locals) c_fclose(fp) # try again, but with a closed file if self.runappdirect: # according to man 2 fclose, any access of fp is undefined # behaviour. This crashes on some linux systems untranslated fp = c_fopen(str(filepath), "rb") c_fclose(fp) with raises_w(space, IOError): PyRun_File(space, fp, filename, Py_file_input, w_globals, w_locals) rffi.free_charp(filename)
def recv(self, space): self._check_readable(space) res, newbuf = self.do_recv_string(space, self.BUFFER_SIZE, PY_SSIZE_T_MAX) try: if newbuf: w_received = space.wrap(rffi.charpsize2str(newbuf, res)) else: w_received = space.wrap(rffi.charpsize2str(self.buffer, res)) finally: if newbuf: rffi.free_charp(newbuf) w_builtins = space.getbuiltinmodule('__builtin__') w_picklemodule = space.fromcache(State).w_picklemodule w_unpickled = space.call_method(w_picklemodule, "loads", w_received) return w_unpickled
def test_endptr_inf(self, space): endp = lltype.malloc(rffi.CCHARPP.TO, 1, flavor='raw') for test in ('inf', '+infinity', 'INF'): s = rffi.str2constcharp(test) r = PyOS_string_to_double(space, s, endp, None) assert r == float('inf') endp_addr = rffi.cast(rffi.LONG, endp[0]) s_addr = rffi.cast(rffi.LONG, s) assert endp_addr == s_addr + len(test) rffi.free_charp(s) s = rffi.str2constcharp('inf aaa') r = PyOS_string_to_double(space, s, endp, None) assert r == float('inf') endp_addr = rffi.cast(rffi.LONG, endp[0]) s_addr = rffi.cast(rffi.LONG, s) # CPython returns 3 assert endp_addr == s_addr + 3 rffi.free_charp(s) lltype.free(endp, flavor='raw')
def test_dict(self, space): d = PyDict_New(space) assert space.eq_w(d, space.newdict()) assert space.eq_w(PyDict_GetItem(space, space.wrap({"a": 72}), space.wrap("a")), space.wrap(72)) PyDict_SetItem(space, d, space.wrap("c"), space.wrap(42)) assert space.eq_w(space.getitem(d, space.wrap("c")), space.wrap(42)) space.setitem(d, space.wrap("name"), space.wrap(3)) assert space.eq_w(PyDict_GetItem(space, d, space.wrap("name")), space.wrap(3)) space.delitem(d, space.wrap("name")) assert not PyDict_GetItem(space, d, space.wrap("name")) buf = rffi.str2charp("name") assert not PyDict_GetItemString(space, d, buf) rffi.free_charp(buf) assert PyDict_Contains(space, d, space.wrap("c")) assert not PyDict_Contains(space, d, space.wrap("z")) PyDict_DelItem(space, d, space.wrap("c")) with raises_w(space, KeyError): PyDict_DelItem(space, d, space.wrap("name")) assert PyDict_Size(space, d) == 0 space.setitem(d, space.wrap("some_key"), space.wrap(3)) buf = rffi.str2charp("some_key") PyDict_DelItemString(space, d, buf) assert PyDict_Size(space, d) == 0 with raises_w(space, KeyError): PyDict_DelItemString(space, d, buf) rffi.free_charp(buf) d = space.wrap({'a': 'b'}) PyDict_Clear(space, d) assert PyDict_Size(space, d) == 0
def test_run_file(self, space, api): filepath = udir / "cpyext_test_runfile.py" filepath.write("raise ZeroDivisionError") fp = fopen(str(filepath), "rb") filename = rffi.str2charp(str(filepath)) w_globals = w_locals = space.newdict() api.PyRun_File(fp, filename, Py_file_input, w_globals, w_locals) fclose(fp) assert api.PyErr_Occurred() is space.w_ZeroDivisionError api.PyErr_Clear() # try again, but with a closed file fp = fopen(str(filepath), "rb") os.close(fileno(fp)) api.PyRun_File(fp, filename, Py_file_input, w_globals, w_locals) fclose(fp) assert api.PyErr_Occurred() is space.w_IOError api.PyErr_Clear() rffi.free_charp(filename)
def do_send_string(self, space, buf, offset, size): from pypy.module._multiprocessing.interp_win32 import ( _WriteFile, ERROR_NO_SYSTEM_RESOURCES) from rpython.rlib import rwin32 charp = rffi.str2charp(buf) written_ptr = lltype.malloc(rffi.CArrayPtr(rwin32.DWORD).TO, 1, flavor='raw') try: result = _WriteFile(self.handle, rffi.ptradd(charp, offset), size, written_ptr, rffi.NULL) if (result == 0 and rwin32.GetLastError_saved() == ERROR_NO_SYSTEM_RESOURCES): raise oefmt(space.w_ValueError, "Cannot send %d bytes over connection", size) finally: rffi.free_charp(charp) lltype.free(written_ptr, flavor='raw')
def strtod(input): if len(input) > _INT_LIMIT: raise MemoryError end_ptr = lltype.malloc(rffi.CCHARPP.TO, 1, flavor='raw') try: ll_input = rffi.str2charp(input) try: result = dg_strtod(ll_input, end_ptr) endpos = (rffi.cast(lltype.Signed, end_ptr[0]) - rffi.cast(lltype.Signed, ll_input)) if endpos == 0 or endpos < len(input): raise ValueError("invalid input at position %d" % (endpos, )) return result finally: rffi.free_charp(ll_input) finally: lltype.free(end_ptr, flavor='raw')
def _retry_as_ldscript(err, mode): """ ld scripts are fairly straightforward to parse (the library we want is in a form like 'GROUP ( <actual-filepath.so>'. A simple state machine can parse that out (avoids regexes).""" parts = err.split(":") if len(parts) != 2: return lltype.nullptr(rffi.VOIDP.TO) fullpath = parts[0] actual = "" last_five = " " state = 0 ldscript = os.open(fullpath, os.O_RDONLY, 0777) c = os.read(ldscript, 1) while c != "": if state == 0: last_five += c last_five = last_five[1:6] if last_five == "GROUP": state = 1 elif state == 1: if c == "(": state = 2 elif state == 2: if c not in string.whitespace: actual += c state = 3 elif state == 3: if c in string.whitespace or c == ")": break else: actual += c c = os.read(ldscript, 1) os.close(ldscript) if actual != "": a = rffi.str2charp(actual) lib = c_dlopen(a, rffi.cast(rffi.INT, mode)) rffi.free_charp(a) return lib else: return lltype.nullptr(rffi.VOIDP.TO)
def textdomain(space, w_domain): """textdomain(domain) -> string Set the C library's textdomain to domain, returning the new domain.""" if space.is_w(w_domain, space.w_None): domain = None result = _textdomain(domain) result = rffi.charp2str(result) else: domain = space.str_w(w_domain) domain_c = rffi.str2charp(domain) try: result = _textdomain(domain_c) # note that 'result' may be the same pointer as 'domain_c' # (maybe?) so it must be converted to an RPython string # *before* we free domain_c. result = rffi.charp2str(result) finally: rffi.free_charp(domain_c) return space.wrap(result)
def test_repr(self, space, api): """ W_PyCMethodObject has a repr string which describes it as a method and gives its name and the name of its class. """ def func(space, w_self, w_args): return space.w_None c_func = ApiFunction([PyObject, PyObject], PyObject, func) func.api_func = c_func ml = lltype.malloc(PyMethodDef, flavor='raw', zero=True) namebuf = rffi.str2charp('func') ml.c_ml_name = namebuf ml.c_ml_meth = rffi.cast(PyCFunction_typedef, c_func.get_llhelper(space)) method = api.PyDescr_NewMethod(space.w_unicode, ml) assert repr(method).startswith( "<built-in method 'func' of 'str' object ") rffi.free_charp(namebuf) lltype.free(ml, flavor='raw')
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")
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))
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_saved_errno() raise OperationError(space.w_OSError, space.wrap(errno)) return space.wrap(rffi.charp2str(dirname))
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)
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))
def test_unicodeobject(self, space): assert PyUnicode_GET_SIZE(space, space.wrap(u'sp�m')) == 4 assert PyUnicode_GetSize(space, space.wrap(u'sp�m')) == 4 unichar = rffi.sizeof(Py_UNICODE) assert PyUnicode_GET_DATA_SIZE(space, space.wrap(u'sp�m')) == 4 * unichar encoding = rffi.charp2str(PyUnicode_GetDefaultEncoding(space, )) w_default_encoding = space.call_function( space.sys.get('getdefaultencoding')) assert encoding == space.unwrap(w_default_encoding) invalid = rffi.str2charp('invalid') utf_8 = rffi.str2charp('utf-8') prev_encoding = rffi.str2charp(space.unwrap(w_default_encoding)) with raises_w(space, TypeError): PyUnicode_SetDefaultEncoding(space, lltype.nullptr(rffi.CCHARP.TO)) with raises_w(space, LookupError): PyUnicode_SetDefaultEncoding(space, invalid) assert PyUnicode_SetDefaultEncoding(space, utf_8) == 0 assert rffi.charp2str(PyUnicode_GetDefaultEncoding(space, )) == 'utf-8' assert PyUnicode_SetDefaultEncoding(space, prev_encoding) == 0 rffi.free_charp(invalid) rffi.free_charp(utf_8) rffi.free_charp(prev_encoding)
def test_AsEncodedObject(self, space): ptr = space.wrap('abc') errors = rffi.str2charp("strict") encoding = rffi.str2charp("hex") res = PyString_AsEncodedObject(space, ptr, encoding, errors) assert space.unwrap(res) == "616263" res = PyString_AsEncodedObject(space, ptr, encoding, lltype.nullptr(rffi.CCHARP.TO)) assert space.unwrap(res) == "616263" rffi.free_charp(encoding) encoding = rffi.str2charp("unknown_encoding") with raises_w(space, LookupError): PyString_AsEncodedObject(space, ptr, encoding, errors) rffi.free_charp(encoding) rffi.free_charp(errors) NULL = lltype.nullptr(rffi.CCHARP.TO) res = PyString_AsEncodedObject(space, ptr, NULL, NULL) assert space.unwrap(res) == "abc" with raises_w(space, TypeError): PyString_AsEncodedObject(space, space.wrap(2), NULL, NULL)
def dlopen(name, mode=-1): """ Wrapper around C-level dlopen """ if mode == -1: mode = _dlopen_default_mode() elif (mode & (RTLD_LAZY | RTLD_NOW)) == 0: mode |= RTLD_NOW # # haaaack for 'pypy py.test -A' if libm.so is a linker script # (see reason in _dlerror_on_dlopen_untranslated()) must_free = False if not we_are_translated() and platform.name == "linux": if name and rffi.charp2str(name) == 'libm.so': name = rffi.str2charp('libm.so.6') must_free = True # res = c_dlopen(name, rffi.cast(rffi.INT, mode)) if must_free: rffi.free_charp(name) if not res: if not we_are_translated(): err = _dlerror_on_dlopen_untranslated(name) else: err = dlerror() if platform.name == "linux" and 'invalid ELF header' in err: # some linux distros put ld linker scripts in .so files # to load libraries more dynamically. The error contains the # full path to something that is probably a script to load # the library we want. res = _retry_as_ldscript(err, mode) if not res: raise DLOpenError(err) return res else: raise DLOpenError(err) return res
def test_ldscripts(self): # this test only makes sense on linux if platform.name != "linux": return fname = os.path.join(os.path.dirname(__file__), "ldscript_working1.so") s = rffi.str2charp(fname) assert "C object" in str(dlopen(s)) rffi.free_charp(s) fname = os.path.join(os.path.dirname(__file__), "ldscript_working2.so") s = rffi.str2charp(fname) assert "C object" in str(dlopen(s)) rffi.free_charp(s) fname = os.path.join(os.path.dirname(__file__), "ldscript_broken1.so") s = rffi.str2charp(fname) py.test.raises(DLOpenError, 'dlopen(s)') rffi.free_charp(s) fname = os.path.join(os.path.dirname(__file__), "ldscript_broken2.so") s = rffi.str2charp(fname) py.test.raises(DLOpenError, 'dlopen(s)') rffi.free_charp(s)