Debian Codegraph @

pypy/module/_rawffi/interp_rawffi.py

raw symbols SCIP
1 import sys
2 from pypy.interpreter.baseobjspace import W_Root
3 from pypy.interpreter.buffer import SimpleView
4 from pypy.interpreter.error import OperationError, oefmt, wrap_oserror
5 from pypy.interpreter.gateway import interp2app, unwrap_spec
6 from pypy.interpreter.typedef import interp_attrproperty
7 from pypy.interpreter.typedef import TypeDef, GetSetProperty
8 from pypy.interpreter.unicodehelper import wcharpsize2utf8
9 from pypy.interpreter.unicodehelper import wrap_unicode_out_of_range_error
10
11 from rpython.rlib.clibffi import *
12 from rpython.rlib.objectmodel import we_are_translated
13 from rpython.rtyper.lltypesystem import lltype, rffi
14 from rpython.rtyper.tool import rffi_platform
15 from rpython.rlib.unroll import unrolling_iterable
16 from rpython.rlib import rutf8
17 from rpython.rlib.objectmodel import specialize, dict_to_switch
18 import rpython.rlib.rposix as rposix
19
20 _MS_WINDOWS = os.name == "nt"
21
22 if _MS_WINDOWS:
23 from rpython.rlib import rwin32
24
25 from rpython.tool.sourcetools import func_with_new_name
26 from rpython.rlib.rarithmetic import intmask, r_uint
27 from pypy.module._rawffi.buffer import RawFFIBuffer
28 from pypy.module._rawffi.tracker import tracker
29
30 BIGENDIAN = sys.byteorder == 'big'
31
32 TYPEMAP = {
33 # XXX A mess with unsigned/signed/normal chars :-/
34 'c' : ffi_type_uchar,
35 'b' : ffi_type_schar,
36 'B' : ffi_type_uchar,
37 'h' : ffi_type_sshort,
38 'u' : cast_type_to_ffitype(lltype.UniChar),
39 'H' : ffi_type_ushort,
40 'i' : cast_type_to_ffitype(rffi.INT),
41 'I' : cast_type_to_ffitype(rffi.UINT),
42 'l' : cast_type_to_ffitype(rffi.LONG),
43 'L' : cast_type_to_ffitype(rffi.ULONG),
44 'q' : cast_type_to_ffitype(rffi.LONGLONG),
45 'Q' : cast_type_to_ffitype(rffi.ULONGLONG),
46 'f' : ffi_type_float,
47 'd' : ffi_type_double,
48 'g' : ffi_type_longdouble,
49 's' : ffi_type_pointer,
50 'P' : ffi_type_pointer,
51 'z' : ffi_type_pointer,
52 'O' : ffi_type_pointer,
53 'Z' : ffi_type_pointer,
54 '?' : cast_type_to_ffitype(lltype.Bool),
55 'v' : ffi_type_sshort
56 }
57 TYPEMAP_PTR_LETTERS = "POszZ"
58 TYPEMAP_NUMBER_LETTERS = "bBhHiIlLqQ?v"
59 TYPEMAP_FLOAT_LETTERS = "fd" # XXX long doubles are not propperly supported in
60 # rpython, so we ignore then here
61
62 if _MS_WINDOWS:
63 TYPEMAP['X'] = ffi_type_pointer
64 TYPEMAP_PTR_LETTERS += 'X'
65
66 TYPEMAP_FUNCTION = dict_to_switch(TYPEMAP)
67
68 def size_alignment(ffi_type):
69 return intmask(ffi_type.c_size), intmask(ffi_type.c_alignment)
70
71 LL_TYPEMAP = {
72 'c' : rffi.CHAR,
73 'u' : lltype.UniChar,
74 'b' : rffi.SIGNEDCHAR,
75 'B' : rffi.UCHAR,
76 'h' : rffi.SHORT,
77 'H' : rffi.USHORT,
78 'i' : rffi.INT,
79 'I' : rffi.UINT,
80 'l' : rffi.LONG,
81 'L' : rffi.ULONG,
82 'q' : rffi.LONGLONG,
83 'Q' : rffi.ULONGLONG,
84 'f' : rffi.FLOAT,
85 'd' : rffi.DOUBLE,
86 'g' : rffi.LONGDOUBLE,
87 's' : rffi.CCHARP,
88 'z' : rffi.CCHARP,
89 'Z' : rffi.CArrayPtr(lltype.UniChar),
90 'O' : rffi.VOIDP,
91 'P' : rffi.VOIDP,
92 '?' : lltype.Bool,
93 'v' : rffi.SHORT
94 }
95
96 if _MS_WINDOWS:
97 LL_TYPEMAP['X'] = rffi.CCHARP
98
99 def letter2tp(space, key):
100 from pypy.module._rawffi.interp_array import PRIMITIVE_ARRAY_TYPES
101 try:
102 return PRIMITIVE_ARRAY_TYPES[key]
103 except KeyError:
104 raise oefmt(space.w_ValueError, "Unknown type letter %s", key)
105
106 def unpack_simple_shape(space, w_shape):
107 # 'w_shape' must be either a letter or a tuple (struct, 1).
108 if space.isinstance_w(w_shape, space.w_text):
109 letter = space.text_w(w_shape)
110 return letter2tp(space, letter)
111 else:
112 w_shapetype, w_length = space.fixedview(w_shape, expected_length=2)
113 from pypy.module._rawffi.structure import W_Structure
114 return space.interp_w(W_Structure, w_shapetype)
115
116 def unpack_shape_with_length(space, w_shape):
117 # Allow 'w_shape' to be a letter or any (shape, number).
118 # The result is always a W_Array.
119 if space.isinstance_w(w_shape, space.w_text):
120 letter = space.text_w(w_shape)
121 return letter2tp(space, letter)
122 else:
123 w_shapetype, w_length = space.fixedview(w_shape, expected_length=2)
124 length = space.int_w(w_length)
125 shape = space.interp_w(W_DataShape, w_shapetype)
126 if shape._array_shapes is None:
127 shape._array_shapes = {}
128 try:
129 result = shape._array_shapes[length]
130 except KeyError:
131 from pypy.module._rawffi.interp_array import W_Array
132 if isinstance(shape, W_Array) and length == 1:
133 result = shape
134 else:
135 ffitype = shape.get_basic_ffi_type()
136 size = shape.size * length
137 result = W_Array(ffitype, size)
138 shape._array_shapes[length] = result
139 return result
140
141 def unpack_resshape(space, w_restype):
142 if space.is_w(w_restype, space.w_None):
143 return None
144 return unpack_simple_shape(space, w_restype)
145
146 def unpack_argshapes(space, w_argtypes):
147 return [unpack_simple_shape(space, w_arg)
148 for w_arg in space.unpackiterable(w_argtypes)]
149
150 def got_libffi_error(space):
151 raise oefmt(space.w_SystemError, "not supported by libffi")
152
153 def wrap_dlopenerror(space, e, filename):
154 if e.msg:
155 # dlerror can return garbage messages under ll2ctypes (not
156 # we_are_translated()), so repr it to avoid potential problems
157 # converting to unicode later
158 msg = e.msg if we_are_translated() else repr(e.msg)
159 else:
160 msg = 'unspecified error'
161 return oefmt(space.w_OSError, 'Cannot load library %s: %8', filename, msg)
162
163
164 class W_CDLL(W_Root):
165 def __init__(self, space, name, cdll):
166 self.cdll = cdll
167 self.name = name
168 self.w_cache = space.newdict()
169 self.space = space
170
171 @unwrap_spec(flags=int, variadic_args=int)
172 def ptr(self, space, w_name, w_argtypes, w_restype, flags=FUNCFLAG_CDECL, variadic_args=0):
173 """ Get a pointer for function name with provided argtypes
174 and restype
175 """
176 resshape = unpack_resshape(space, w_restype)
177 if resshape is None:
178 w_resshape = space.w_None
179 else:
180 w_resshape = resshape
181 argtypes_w = space.fixedview(w_argtypes)
182 w_argtypes = space.newtuple(argtypes_w)
183 w_key = space.newtuple([w_name, w_argtypes, w_resshape])
184 try:
185 return space.getitem(self.w_cache, w_key)
186 except OperationError as e:
187 if e.match(space, space.w_KeyError):
188 pass
189 else:
190 raise
191 # Array arguments not supported directly (in C, an array argument
192 # will be just a pointer). And the result cannot be an array (at all).
193 argshapes = unpack_argshapes(space, w_argtypes)
194 ffi_argtypes = [shape.get_basic_ffi_type() for shape in argshapes]
195 if resshape is not None:
196 ffi_restype = resshape.get_basic_ffi_type()
197 else:
198 ffi_restype = ffi_type_void
199
200 if space.isinstance_w(w_name, space.w_text):
201 name = space.text_w(w_name)
202
203 try:
204 ptr = self.cdll.getrawpointer(name, ffi_argtypes, ffi_restype,
205 flags, variadic_args)
206 except KeyError:
207 raise oefmt(space.w_AttributeError,
208 "No symbol %s found in library %s",
209 name, self.name)
210 except LibFFIError:
211 raise got_libffi_error(space)
212
213 elif (_MS_WINDOWS and space.isinstance_w(w_name, space.w_int)):
214 ordinal = space.int_w(w_name)
215 try:
216 ptr = self.cdll.getrawpointer_byordinal(ordinal, ffi_argtypes,
217 ffi_restype, flags, variadic_args)
218 except KeyError:
219 raise oefmt(space.w_AttributeError,
220 "No symbol %d found in library %s",
221 ordinal, self.name)
222 except LibFFIError:
223 raise got_libffi_error(space)
224 else:
225 raise oefmt(space.w_TypeError,
226 "function name must be string or integer")
227
228 w_funcptr = W_FuncPtr(space, ptr, argshapes, resshape)
229 space.setitem(self.w_cache, w_key, w_funcptr)
230 return w_funcptr
231
232 @unwrap_spec(name='text')
233 def getaddressindll(self, space, name):
234 try:
235 address_as_uint = rffi.cast(lltype.Unsigned,
236 self.cdll.getaddressindll(name))
237 except KeyError:
238 raise oefmt(space.w_ValueError, "Cannot find symbol %s", name)
239 return space.newint(address_as_uint)
240
241 def open_cdll(space, name):
242 try:
243 return CDLL(name)
244 except DLOpenError as e:
245 raise wrap_dlopenerror(space, e, name or "<None>")
246 except OSError as e:
247 raise wrap_oserror(space, e)
248
249 if _MS_WINDOWS:
250 name_spec = 'fsencode'
251 else:
252 name_spec = 'fsencode_or_none'
253 @unwrap_spec(name=name_spec)
254 def descr_new_cdll(space, w_type, name):
255 cdll = open_cdll(space, name)
256 return W_CDLL(space, name, cdll)
257
258 W_CDLL.typedef = TypeDef(
259 'CDLL',
260 __new__ = interp2app(descr_new_cdll),
261 ptr = interp2app(W_CDLL.ptr),
262 getaddressindll = interp2app(W_CDLL.getaddressindll),
263 name = interp_attrproperty('name', W_CDLL,
264 wrapfn="newtext_or_none"),
265 __doc__ = """ C Dynamically loaded library
266 use CDLL(libname) to create a handle to a C library (the argument is processed
267 the same way as dlopen processes it). On such a library you can call:
268 lib.ptr(func_name, argtype_list, restype)
269
270 where argtype_list is a list of single characters and restype is a single
271 character. The character meanings are more or less the same as in the struct
272 module, except that s has trailing \x00 added, while p is considered a raw
273 buffer.""" # xxx fix doc
274 )
275
276 unroll_letters_for_numbers = unrolling_iterable(TYPEMAP_NUMBER_LETTERS)
277 unroll_letters_for_floats = unrolling_iterable(TYPEMAP_FLOAT_LETTERS)
278
279 _ARM = rffi_platform.getdefined('__arm__', '')
280
281 @specialize.arg(2)
282 def read_ptr(ptr, ofs, TP):
283 T = lltype.Ptr(rffi.CArray(TP))
284 for c in unroll_letters_for_floats:
285 # Note: if we are on ARM and have a float-ish value that is not word
286 # aligned accessing it directly causes a SIGBUS. Instead we use memcpy
287 # to avoid the problem
288 if (_ARM and LL_TYPEMAP[c] is TP
289 and rffi.cast(lltype.Signed, ptr) & 3 != 0):
290 if ofs != 0:
291 ptr = rffi.ptradd(ptr, ofs*rffi.sizeof(TP))
292 with lltype.scoped_alloc(T.TO, 1) as t_array:
293 rffi.c_memcpy(
294 rffi.cast(rffi.VOIDP, t_array),
295 rffi.cast(rffi.CONST_VOIDP, ptr),
296 rffi.sizeof(TP))
297 ptr_val = t_array[0]
298 return ptr_val
299 else:
300 return rffi.cast(T, ptr)[ofs]
301
302 @specialize.argtype(2)
303 def write_ptr(ptr, ofs, value):
304 TP = lltype.typeOf(value)
305 T = lltype.Ptr(rffi.CArray(TP))
306 for c in unroll_letters_for_floats:
307 # Note: if we are on ARM and have a float-ish value that is not word
308 # aligned accessing it directly causes a SIGBUS. Instead we use memcpy
309 # to avoid the problem
310 if (_ARM and LL_TYPEMAP[c] is TP
311 and rffi.cast(lltype.Signed, ptr) & 3 != 0):
312 if ofs != 0:
313 ptr = rffi.ptradd(ptr, ofs*rffi.sizeof(TP))
314 with lltype.scoped_alloc(T.TO, 1) as s_array:
315 s_array[0] = value
316 rffi.c_memcpy(
317 rffi.cast(rffi.VOIDP, ptr),
318 rffi.cast(rffi.CONST_VOIDP, s_array),
319 rffi.sizeof(TP))
320 return
321 else:
322 rffi.cast(T, ptr)[ofs] = value
323
324 def segfault_exception(space, reason):
325 # This will cause _rawffi to be pre-installed in sys.modules, and it will
326 # have __loader__ and __spec__ set to None, so will not be marked as
327 # "built-in"
328 w_mod = space.getbuiltinmodule("_rawffi")
329 w_exception = space.getattr(w_mod, space.newtext("SegfaultException"))
330 return OperationError(w_exception, space.newtext(reason))
331
332 class W_DataShape(W_Root):
333 _array_shapes = None
334 size = 0
335 alignment = 0
336 itemcode = '\0'
337
338 def allocate(self, space, length, autofree=False):
339 raise NotImplementedError
340
341 def get_basic_ffi_type(self):
342 raise NotImplementedError
343
344 def descr_get_ffi_type(self, space):
345 from pypy.module._rawffi.alt.interp_ffitype import W_FFIType
346 return W_FFIType('<unknown>', self.get_basic_ffi_type(), self)
347
348 @unwrap_spec(n=int)
349 def descr_size_alignment(self, space, n=1):
350 return space.newtuple2(space.newint(self.size * n),
351 space.newint(self.alignment))
352
353
354 class W_DataInstance(W_Root):
355 fmt = 'B'
356 itemsize = 1
357 def __init__(self, space, size, address=r_uint(0)):
358 if address:
359 self.ll_buffer = rffi.cast(rffi.VOIDP, address)
360 else:
361 self.ll_buffer = lltype.malloc(rffi.VOIDP.TO, size, flavor='raw',
362 zero=True, add_memory_pressure=True)
363 if tracker.DO_TRACING:
364 ll_buf = rffi.cast(lltype.Signed, self.ll_buffer)
365 tracker.trace_allocation(ll_buf, self)
366 self._ll_buffer = self.ll_buffer
367
368 def getbuffer(self, space):
369 return space.newint(rffi.cast(lltype.Unsigned, self.ll_buffer))
370
371 def buffer_advance(self, n):
372 self.ll_buffer = rffi.ptradd(self.ll_buffer, n)
373
374 def byptr(self, space):
375 from pypy.module._rawffi.interp_array import ARRAY_OF_PTRS
376 array = ARRAY_OF_PTRS.allocate(space, 1)
377 array.setitem(space, 0, self)
378 return array
379
380 def free(self, space):
381 if not self._ll_buffer:
382 raise segfault_exception(space, "freeing NULL pointer")
383 self._free()
384
385 def _free(self):
386 if tracker.DO_TRACING:
387 ll_buf = rffi.cast(lltype.Signed, self._ll_buffer)
388 tracker.trace_free(ll_buf)
389 lltype.free(self._ll_buffer, flavor='raw')
390 self.ll_buffer = lltype.nullptr(rffi.VOIDP.TO)
391 self._ll_buffer = self.ll_buffer
392
393 def buffer_w(self, space, flags):
394 return SimpleView(RawFFIBuffer(self), w_obj=self)
395
396 def getrawsize(self):
397 raise NotImplementedError("abstract base class")
398
399 @specialize.arg(0)
400 def unwrap_truncate_int(TP, space, w_arg):
401 return rffi.cast(TP, space.bigint_w(w_arg).ulonglongmask())
402
403
404 @specialize.arg(1)
405 def unwrap_value(space, push_func, add_arg, argdesc, letter, w_arg):
406 if letter in TYPEMAP_PTR_LETTERS:
407 # check for NULL ptr
408 if isinstance(w_arg, W_DataInstance):
409 ptr = w_arg.ll_buffer
410 else:
411 ptr = unwrap_truncate_int(rffi.VOIDP, space, w_arg)
412 push_func(add_arg, argdesc, ptr)
413 elif letter == "d":
414 push_func(add_arg, argdesc, space.float_w(w_arg))
415 elif letter == "f":
416 push_func(add_arg, argdesc, rffi.cast(rffi.FLOAT,
417 space.float_w(w_arg)))
418 elif letter == "g":
419 push_func(add_arg, argdesc, rffi.cast(rffi.LONGDOUBLE,
420 space.float_w(w_arg)))
421 elif letter == "c":
422 if space.isinstance_w(w_arg, space.w_int):
423 val = space.byte_w(w_arg)
424 else:
425 s = space.bytes_w(w_arg)
426 if len(s) != 1:
427 raise oefmt(space.w_TypeError,
428 "Expected bytes of length one as character")
429 val = s[0]
430 push_func(add_arg, argdesc, val)
431 elif letter == 'u':
432 s, lgt = space.utf8_len_w(w_arg)
433 if lgt != 1:
434 raise oefmt(space.w_TypeError,
435 "Expected unicode string of length one as wide "
436 "character")
437 val = rutf8.codepoint_at_pos(s, 0)
438 push_func(add_arg, argdesc, rffi.cast(rffi.WCHAR_T, val))
439 else:
440 for c in unroll_letters_for_numbers:
441 if letter == c:
442 TP = LL_TYPEMAP[c]
443 val = unwrap_truncate_int(TP, space, w_arg)
444 push_func(add_arg, argdesc, val)
445 return
446 else:
447 raise oefmt(space.w_TypeError, "cannot directly write value")
448
449 ll_typemap_iter = unrolling_iterable(LL_TYPEMAP.items())
450
451 @specialize.arg(1)
452 def wrap_value(space, func, add_arg, argdesc, letter):
453 for c, ll_type in ll_typemap_iter:
454 if letter == c:
455 if c in TYPEMAP_PTR_LETTERS:
456 res = func(add_arg, argdesc, rffi.VOIDP)
457 return space.newint(rffi.cast(lltype.Unsigned, res))
458 if c in TYPEMAP_NUMBER_LETTERS:
459 return space.newint(func(add_arg, argdesc, ll_type))
460 elif c == 'c':
461 return space.newbytes(func(add_arg, argdesc, ll_type))
462 elif c == 'u':
463 code = ord(func(add_arg, argdesc, ll_type))
464 try:
465 return space.newutf8(rutf8.unichr_as_utf8(
466 r_uint(code), allow_surrogates=True), 1)
467 except rutf8.OutOfRange:
468 raise oefmt(space.w_ValueError,
469 "unicode character %d out of range", code)
470 elif c == 'f' or c == 'd' or c == 'g':
471 return space.newfloat(float(func(add_arg, argdesc, ll_type)))
472 else:
473 assert 0, "unreachable"
474 raise oefmt(space.w_TypeError, "cannot directly read value")
475
476 NARROW_INTEGER_TYPES = 'cbhiBIH?'
477
478 def is_narrow_integer_type(letter):
479 return letter in NARROW_INTEGER_TYPES
480
481 class W_FuncPtr(W_Root):
482 def __init__(self, space, ptr, argshapes, resshape):
483 self.ptr = ptr
484 self.argshapes = argshapes
485 self.resshape = resshape
486 self.narrow_integer = False
487 if resshape is not None:
488 self.narrow_integer = is_narrow_integer_type(resshape.itemcode.lower())
489
490 def getbuffer(self, space):
491 return space.newint(rffi.cast(lltype.Unsigned, self.ptr.funcsym))
492
493 def byptr(self, space):
494 from pypy.module._rawffi.interp_array import ARRAY_OF_PTRS
495 array = ARRAY_OF_PTRS.allocate(space, 1)
496 array.setitem(space, 0, self.getbuffer(space))
497 if tracker.DO_TRACING:
498 # XXX this is needed, because functions tend to live forever
499 # hence our testing is not performing that well
500 del tracker.alloced[rffi.cast(lltype.Signed, array.ll_buffer)]
501 return array
502
503 def call(self, space, args_w):
504 from pypy.module._rawffi.interp_array import W_ArrayInstance
505 from pypy.module._rawffi.structure import W_StructureInstance
506 from pypy.module._rawffi.structure import W_Structure
507 argnum = len(args_w)
508 if argnum != len(self.argshapes):
509 raise oefmt(space.w_TypeError,
510 "Wrong number of arguments: expected %d, got %d",
511 len(self.argshapes), argnum)
512 args_ll = []
513 for i in range(argnum):
514 argshape = self.argshapes[i]
515 w_arg = args_w[i]
516 if isinstance(argshape, W_Structure): # argument by value
517 arg = space.interp_w(W_StructureInstance, w_arg)
518 xsize, xalignment = size_alignment(self.ptr.argtypes[i])
519 if (arg.shape.size != xsize or
520 arg.shape.alignment != xalignment):
521 raise oefmt(space.w_TypeError,
522 "Argument %d should be a structure of size %d "
523 "and alignment %d, got instead size %d and "
524 "alignment %d", i + 1, xsize, xalignment,
525 arg.shape.size, arg.shape.alignment)
526 else:
527 arg = space.interp_w(W_ArrayInstance, w_arg)
528 if arg.length != 1:
529 raise oefmt(space.w_TypeError,
530 "Argument %d should be an array of length 1, "
531 "got length %d", i+1, arg.length)
532 argletter = argshape.itemcode
533 letter = arg.shape.itemcode
534 if letter != argletter:
535 if not (argletter in TYPEMAP_PTR_LETTERS and
536 letter in TYPEMAP_PTR_LETTERS):
537 raise oefmt(space.w_TypeError,
538 "Argument %d should be typecode %s, got "
539 "%s", i + 1, argletter, letter)
540 args_ll.append(arg.ll_buffer)
541 # XXX we could avoid the intermediate list args_ll
542
543 try:
544 if self.resshape is not None:
545 result = self.resshape.allocate(space, 1, autofree=True)
546 # adjust_return_size() was used here on result.ll_buffer
547 self.ptr.call(args_ll, result.ll_buffer)
548 if BIGENDIAN and self.narrow_integer:
549 # we get a 8 byte value in big endian
550 n = rffi.sizeof(lltype.Signed) - result.shape.size
551 result.buffer_advance(n)
552 return result
553 else:
554 self.ptr.call(args_ll, lltype.nullptr(rffi.VOIDP.TO))
555 return space.w_None
556 except StackCheckError as e:
557 raise OperationError(space.w_ValueError, space.newtext(e.message))
558
559 @unwrap_spec(addr=r_uint, flags=int)
560 def descr_new_funcptr(space, w_tp, addr, w_args, w_res, flags=FUNCFLAG_CDECL):
561 argshapes = unpack_argshapes(space, w_args)
562 resshape = unpack_resshape(space, w_res)
563 ffi_args = [shape.get_basic_ffi_type() for shape in argshapes]
564 if resshape is not None:
565 ffi_res = resshape.get_basic_ffi_type()
566 else:
567 ffi_res = ffi_type_void
568 try:
569 ptr = RawFuncPtr('???', ffi_args, ffi_res, rffi.cast(rffi.VOIDP, addr),
570 flags)
571 except LibFFIError:
572 raise got_libffi_error(space)
573 return W_FuncPtr(space, ptr, argshapes, resshape)
574
575 W_FuncPtr.typedef = TypeDef(
576 'FuncPtr',
577 __new__ = interp2app(descr_new_funcptr),
578 __call__ = interp2app(W_FuncPtr.call),
579 buffer = GetSetProperty(W_FuncPtr.getbuffer),
580 byptr = interp2app(W_FuncPtr.byptr),
581 )
582 W_FuncPtr.typedef.acceptable_as_base_class = False
583
584 def _create_new_accessor(func_name, name):
585 @unwrap_spec(tp_letter='text')
586 def accessor(space, tp_letter):
587 if len(tp_letter) != 1:
588 raise oefmt(space.w_ValueError, "Expecting string of length one")
589 tp_letter = tp_letter[0] # fool annotator
590 try:
591 return space.newint(intmask(getattr(TYPEMAP_FUNCTION(tp_letter), name)))
592 except KeyError:
593 raise oefmt(space.w_ValueError, "Unknown type specification %s",
594 tp_letter)
595 return func_with_new_name(accessor, func_name)
596
597 sizeof = _create_new_accessor('sizeof', 'c_size')
598 alignment = _create_new_accessor('alignment', 'c_alignment')
599
600 @unwrap_spec(address=r_uint, maxlength=int)
601 def charp2string(space, address, maxlength=-1):
602 if address == 0:
603 return space.w_None
604 charp_addr = rffi.cast(rffi.CCHARP, address)
605 if maxlength == -1:
606 s = rffi.charp2str(charp_addr)
607 else:
608 s = rffi.charp2strn(charp_addr, maxlength)
609 return space.newbytes(s)
610
611 @unwrap_spec(address=r_uint, maxlength=int)
612 def wcharp2unicode(space, address, maxlength=-1):
613 if address == 0:
614 return space.w_None
615 wcharp_addr = rffi.cast(rffi.CWCHARP, address)
616 try:
617 if maxlength == -1:
618 s, lgt = rffi.wcharp2utf8(wcharp_addr)
619 else:
620 s, lgt = rffi.wcharp2utf8n(wcharp_addr, maxlength)
621 except rutf8.OutOfRange as e:
622 raise wrap_unicode_out_of_range_error(space, e)
623 return space.newutf8(s, lgt)
624
625 @unwrap_spec(address=r_uint, maxlength=int)
626 def charp2rawstring(space, address, maxlength=-1):
627 if maxlength == -1:
628 return charp2string(space, address)
629 s = rffi.charpsize2str(rffi.cast(rffi.CCHARP, address), maxlength)
630 return space.newbytes(s)
631
632 @unwrap_spec(address=r_uint, maxlength=int)
633 def wcharp2rawunicode(space, address, maxlength=-1):
634 if maxlength == -1:
635 return wcharp2unicode(space, address)
636 elif maxlength < 0:
637 maxlength = 0
638 s = wcharpsize2utf8(space, rffi.cast(rffi.CWCHARP, address), maxlength)
639 return space.newutf8(s, maxlength)
640
641 @unwrap_spec(address=r_uint, newcontent='bufferstr', offset=int, size=int)
642 def rawstring2charp(space, address, newcontent, offset=0, size=-1):
643 from rpython.rtyper.annlowlevel import llstr
644 from rpython.rtyper.lltypesystem.rstr import copy_string_to_raw
645 array = rffi.cast(rffi.CCHARP, address)
646 if size < 0:
647 size = len(newcontent) - offset
648 copy_string_to_raw(llstr(newcontent), array, offset, size)
649
650 if _MS_WINDOWS:
651 @unwrap_spec(code=int)
652 def FormatError(space, code):
653 return space.newtext(*rwin32.FormatErrorW(code))
654
655 @unwrap_spec(hresult=int)
656 def check_HRESULT(space, hresult):
657 if rwin32.FAILED(hresult):
658 raise OperationError(space.w_WindowsError, space.newint(hresult))
659 return space.newint(hresult)
660
661 def get_libc(space):
662 name = get_libc_name()
663 cdll = open_cdll(space, name)
664 return W_CDLL(space, name, cdll)
665
666 def get_errno(space):
667 return space.newint(rposix.get_saved_alterrno())
668
669 def set_errno(space, w_errno):
670 rposix.set_saved_alterrno(space.int_w(w_errno))
671
672 if sys.platform == 'win32':
673 # see also
674 # issue #1944 ctypes-on-windows-getlasterror
675 def get_last_error(space):
676 return space.newint(rwin32.GetLastError_alt_saved())
677 @unwrap_spec(error=int)
678 def set_last_error(space, error):
679 rwin32.SetLastError_alt_saved(error)
680 else:
681 # always have at least a dummy version of these functions
682 # issue 1242
683 def get_last_error(space):
684 return space.newint(0)
685 @unwrap_spec(error=int)
686 def set_last_error(space, error):
687 pass