Debian Codegraph @

pypy/module/_cffi_backend/ctypeptr.py

raw symbols SCIP
1 """
2 Pointers.
3 """
4
5 import os
6
7 from rpython.rlib import rposix, jit, rgc
8 from rpython.rlib.objectmodel import we_are_translated
9 from rpython.rlib.rarithmetic import ovfcheck
10 from rpython.rtyper.annlowlevel import llstr
11 from rpython.rtyper.lltypesystem import lltype, rffi
12 from rpython.rtyper.lltypesystem.rstr import copy_string_to_raw, STR
13
14 from pypy.interpreter.error import OperationError, oefmt, wrap_oserror
15 from pypy.module._cffi_backend import cdataobj, misc, ctypeprim, ctypevoid
16 from pypy.module._cffi_backend.ctypeobj import W_CType
17
18
19 class W_CTypePtrOrArray(W_CType):
20 _attrs_ = ['ctitem', 'accept_str', 'length']
21 _immutable_fields_ = ['ctitem', 'accept_str', 'length']
22 length = -1
23
24 def __init__(self, space, size, extra, extra_position, ctitem):
25 name, name_position = ctitem.insert_name(extra, extra_position)
26 W_CType.__init__(self, space, size, name, name_position)
27 # this is the "underlying type":
28 # - for pointers, it is the pointed-to type
29 # - for arrays, it is the array item type
30 # - for functions, it is the return type
31 self.ctitem = ctitem
32 self.accept_str = (self.is_nonfunc_pointer_or_array and
33 (isinstance(ctitem, ctypevoid.W_CTypeVoid) or
34 isinstance(ctitem, ctypeprim.W_CTypePrimitiveChar) or
35 (ctitem.is_primitive_integer and
36 ctitem.size == rffi.sizeof(lltype.Char))))
37
38 def is_unichar_ptr_or_array(self):
39 return isinstance(self.ctitem, ctypeprim.W_CTypePrimitiveUniChar)
40
41 def is_char_or_unichar_ptr_or_array(self):
42 return isinstance(self.ctitem, ctypeprim.W_CTypePrimitiveCharOrUniChar)
43
44 def cast(self, w_ob):
45 # cast to a pointer, to a funcptr, or to an array.
46 # Note that casting to an array is an extension to the C language,
47 # which seems to be necessary in order to sanely get a
48 # <cdata 'int[3]'> at some address.
49 if self.size < 0:
50 return W_CType.cast(self, w_ob)
51 space = self.space
52 from pypy.module._cffi_backend import wrapper
53 if (isinstance(w_ob, cdataobj.W_CData) and
54 isinstance(w_ob.ctype, W_CTypePtrOrArray)):
55 value = w_ob.unsafe_escaping_ptr()
56 elif (isinstance(w_ob, wrapper.W_FunctionWrapper) and
57 w_ob.directfnptr):
58 value = w_ob.directfnptr
59 else:
60 value = misc.as_unsigned_long(space, w_ob, strict=False)
61 value = rffi.cast(rffi.CCHARP, value)
62 return cdataobj.W_CData(space, value, self)
63
64 def _convert_array_from_listview(self, cdata, lst_w):
65 space = self.space
66 if not self._within_bounds(len(lst_w), self.length):
67 raise oefmt(space.w_IndexError,
68 "too many initializers for '%s' (got %d)",
69 self.name, len(lst_w))
70 ctitem = self.ctitem
71 for i in range(len(lst_w)):
72 ctitem.convert_from_object(cdata, lst_w[i])
73 cdata = rffi.ptradd(cdata, ctitem.size)
74
75 def convert_array_from_object(self, cdata, w_ob):
76 space = self.space
77 if (space.isinstance_w(w_ob, space.w_list) or
78 space.isinstance_w(w_ob, space.w_tuple)):
79 if self.ctitem.pack_list_of_items(cdata, w_ob, self.length):
80 pass # fast path
81 else:
82 self._convert_array_from_listview(cdata, space.listview(w_ob))
83 elif self.accept_str:
84 if not space.isinstance_w(w_ob, space.w_bytes):
85 raise self._convert_error("bytes or list or tuple", w_ob)
86 s = space.bytes_w(w_ob)
87 n = len(s)
88 if self.length >= 0 and n > self.length:
89 raise oefmt(space.w_IndexError,
90 "initializer string is too long for '%s' (got %d "
91 "characters)", self.name, n)
92 if isinstance(self.ctitem, ctypeprim.W_CTypePrimitiveBool):
93 self._must_be_string_of_zero_or_one(s)
94 copy_string_to_raw(llstr(s), cdata, 0, n)
95 if n != self.length:
96 cdata[n] = '\x00'
97 elif isinstance(self.ctitem, ctypeprim.W_CTypePrimitiveUniChar):
98 from pypy.module._cffi_backend import wchar_helper
99 if not space.isinstance_w(w_ob, space.w_unicode):
100 raise self._convert_error("unicode or list or tuple", w_ob)
101 w_u = space.convert_arg_to_w_unicode(w_ob)
102 s = w_u._utf8
103 if self.ctitem.size == 2:
104 n = wchar_helper.utf8_size_as_char16(s)
105 else:
106 n = w_u._len()
107 if self.length >= 0 and n > self.length:
108 raise oefmt(space.w_IndexError,
109 "initializer unicode string is too long for '%s' "
110 "(got %d characters)", self.name, n)
111 add_final_zero = (n != self.length)
112 if self.ctitem.size == 2:
113 wchar_helper.utf8_to_char16(s, cdata, n, add_final_zero)
114 else:
115 wchar_helper.utf8_to_char32(s, cdata, n, add_final_zero)
116 else:
117 raise self._convert_error("list or tuple", w_ob)
118
119 def _must_be_string_of_zero_or_one(self, s):
120 for c in s:
121 if ord(c) > 1:
122 raise oefmt(self.space.w_ValueError,
123 "an array of _Bool can only contain \\x00 or \\x01")
124
125 def string(self, cdataobj, maxlen):
126 space = self.space
127 if (isinstance(self.ctitem, ctypeprim.W_CTypePrimitive) and
128 not isinstance(self.ctitem, ctypeprim.W_CTypePrimitiveBool)):
129 with cdataobj as ptr:
130 if not ptr:
131 raise oefmt(space.w_RuntimeError,
132 "cannot use string() on %R",
133 cdataobj)
134 #
135 from pypy.module._cffi_backend import ctypearray
136 length = maxlen
137 if length < 0 and isinstance(self, ctypearray.W_CTypeArray):
138 length = cdataobj.get_array_length()
139 #
140 # pointer to a primitive type of size 1: builds and returns a str
141 if self.ctitem.size == rffi.sizeof(lltype.Char):
142 if length < 0:
143 s = rffi.charp2str(ptr)
144 else:
145 s = rffi.charp2strn(ptr, length)
146 return space.newbytes(s)
147 #
148 # pointer to a wchar_t: builds and returns a unicode
149 if self.is_unichar_ptr_or_array():
150 from pypy.module._cffi_backend import wchar_helper
151 if self.ctitem.size == 2:
152 length = wchar_helper.measure_length_16(ptr, length)
153 else:
154 length = wchar_helper.measure_length_32(ptr, length)
155 return self.ctitem.unpack_ptr(self, ptr, length)
156 #
157 return W_CType.string(self, cdataobj, maxlen)
158
159
160 class W_CTypePtrBase(W_CTypePtrOrArray):
161 # base class for both pointers and pointers-to-functions
162 _attrs_ = ['is_void_ptr', 'is_voidchar_ptr', 'is_onebyte_ptr']
163 _immutable_fields_ = ['is_void_ptr', 'is_voidchar_ptr', 'is_onebyte_ptr']
164 is_void_ptr = False
165 is_voidchar_ptr = False
166 is_onebyte_ptr = False
167
168 def convert_to_object(self, cdata):
169 ptrdata = rffi.cast(rffi.CCHARPP, cdata)[0]
170 return cdataobj.W_CData(self.space, ptrdata, self)
171
172 def convert_from_object(self, cdata, w_ob):
173 if not isinstance(w_ob, cdataobj.W_CData):
174 from pypy.module._cffi_backend import wrapper
175 if isinstance(w_ob, wrapper.W_FunctionWrapper):
176 w_ob = w_ob.try_extract_direct_fnptr_as_cdata(self.space)
177 if not isinstance(w_ob, cdataobj.W_CData):
178 raise self._convert_error("cdata pointer", w_ob)
179 other = w_ob.ctype
180 if not isinstance(other, W_CTypePtrBase):
181 from pypy.module._cffi_backend import ctypearray
182 if isinstance(other, ctypearray.W_CTypeArray):
183 other = other.ctptr
184 else:
185 raise self._convert_error("compatible pointer", w_ob)
186 if self is not other:
187 if self.is_void_ptr or other.is_void_ptr:
188 pass # cast from or to 'void *'
189 elif self.is_voidchar_ptr or other.is_voidchar_ptr:
190 # for backward compatibility, accept "char *" as either
191 # source of target. This is not what C does, though,
192 # so emit a warning that will eventually turn into an
193 # error. The warning is turned off if both types are
194 # pointers to single bytes.
195 if self.is_onebyte_ptr and other.is_onebyte_ptr:
196 pass # no warning
197 else:
198 space = self.space
199 msg = ("implicit cast from '%s' to '%s' "
200 "will be forbidden in the future (check that the types "
201 "are as you expect; use an explicit ffi.cast() if they "
202 "are correct)" % (other.name, self.name))
203 space.warn(space.newtext(msg), space.w_UserWarning)
204 else:
205 raise self._convert_error("compatible pointer", w_ob)
206
207 rffi.cast(rffi.CCHARPP, cdata)[0] = w_ob.unsafe_escaping_ptr()
208
209 def _alignof(self):
210 from pypy.module._cffi_backend import newtype
211 return newtype.alignment_of_pointer
212
213
214 class W_CTypePointer(W_CTypePtrBase):
215 _attrs_ = ['is_file', 'cache_array_type', '_array_types']
216 _immutable_fields_ = ['is_file', 'cache_array_type?']
217 kind = "pointer"
218 cache_array_type = None
219 is_nonfunc_pointer_or_array = True
220
221 def __init__(self, space, ctitem):
222 from pypy.module._cffi_backend import ctypearray
223 size = rffi.sizeof(rffi.VOIDP)
224 if isinstance(ctitem, ctypearray.W_CTypeArray):
225 extra = "(*)" # obscure case: see test_array_add
226 else:
227 extra = " *"
228 self.is_file = (ctitem.name == "struct _IO_FILE" or
229 ctitem.name == "FILE")
230 self.is_void_ptr = isinstance(ctitem, ctypevoid.W_CTypeVoid)
231 self.is_voidchar_ptr = (self.is_void_ptr or
232 isinstance(ctitem, ctypeprim.W_CTypePrimitiveChar))
233 self.is_onebyte_ptr = (ctitem.size == 1)
234 W_CTypePtrBase.__init__(self, space, size, extra, 2, ctitem)
235
236 def newp(self, w_init, allocator):
237 from pypy.module._cffi_backend.ctypestruct import W_CTypeStructOrUnion
238 space = self.space
239 ctitem = self.ctitem
240 datasize = ctitem.size
241 if datasize < 0:
242 raise oefmt(space.w_TypeError,
243 "cannot instantiate ctype '%s' of unknown size",
244 self.name)
245 if isinstance(ctitem, W_CTypeStructOrUnion):
246 # 'newp' on a struct-or-union pointer: in this case, we return
247 # a W_CDataPtrToStruct object which has a strong reference
248 # to a W_CDataNewOwning that really contains the structure.
249 #
250 varsize_length = -1
251 ctitem.force_lazy_struct()
252 if ctitem._with_var_array:
253 if not space.is_w(w_init, space.w_None):
254 datasize = ctitem.convert_struct_from_object(
255 lltype.nullptr(rffi.CCHARP.TO), w_init, datasize)
256 varsize_length = datasize
257 #
258 cdatastruct = allocator.allocate(space, datasize, ctitem,
259 length=varsize_length)
260 ptr = cdatastruct.unsafe_escaping_ptr()
261 cdata = cdataobj.W_CDataPtrToStructOrUnion(space, ptr,
262 self, cdatastruct)
263 else:
264 if self.is_char_or_unichar_ptr_or_array():
265 datasize *= 2 # forcefully add a null character
266 cdata = allocator.allocate(space, datasize, self)
267 #
268 if not space.is_w(w_init, space.w_None):
269 with cdata as ptr:
270 ctitem.convert_from_object(ptr, w_init)
271 return cdata
272
273 def _check_subscript_index(self, w_cdata, i):
274 if (isinstance(w_cdata, cdataobj.W_CDataNewOwning) or
275 isinstance(w_cdata, cdataobj.W_CDataPtrToStructOrUnion)):
276 if i != 0:
277 raise oefmt(self.space.w_IndexError,
278 "cdata '%s' can only be indexed by 0", self.name)
279 else:
280 if not w_cdata.unsafe_escaping_ptr():
281 raise oefmt(self.space.w_RuntimeError,
282 "cannot dereference null pointer from cdata '%s'",
283 self.name)
284 return self
285
286 def _check_slice_index(self, w_cdata, start, stop):
287 return self
288
289 def add(self, cdata, i):
290 space = self.space
291 ctitem = self.ctitem
292 itemsize = ctitem.size
293 if ctitem.size < 0:
294 if self.is_void_ptr:
295 itemsize = 1
296 else:
297 raise oefmt(space.w_TypeError,
298 "ctype '%s' points to items of unknown size",
299 self.name)
300 p = rffi.ptradd(cdata, i * itemsize)
301 return cdataobj.W_CData(space, p, self)
302
303 def cast(self, w_ob):
304 if self.is_file:
305 value = self.prepare_file(w_ob)
306 if value:
307 return cdataobj.W_CData(self.space, value, self)
308 return W_CTypePtrBase.cast(self, w_ob)
309
310 def prepare_file(self, w_ob):
311 from pypy.module._io.interp_iobase import W_IOBase
312 if isinstance(w_ob, W_IOBase):
313 return prepare_file_argument(self.space, w_ob)
314 else:
315 return lltype.nullptr(rffi.CCHARP.TO)
316
317 def _prepare_pointer_call_argument(self, w_init, cdata):
318 space = self.space
319 if (space.isinstance_w(w_init, space.w_list) or
320 space.isinstance_w(w_init, space.w_tuple)):
321 length = space.int_w(space.len(w_init))
322 elif space.isinstance_w(w_init, space.w_bytes):
323 # from a string, we add the null terminator
324 s = space.bytes_w(w_init)
325 length = len(s) + 1
326 elif space.isinstance_w(w_init, space.w_unicode):
327 from pypy.module._cffi_backend import wchar_helper
328 w_u = space.convert_arg_to_w_unicode(w_init)
329 if self.ctitem.size == 2:
330 length = wchar_helper.utf8_size_as_char16(w_u._utf8)
331 else:
332 length = w_u._len()
333 length += 1
334 elif self.is_file:
335 result = self.prepare_file(w_init)
336 if result:
337 rffi.cast(rffi.CCHARPP, cdata)[0] = result
338 return 2
339 return 0
340 else:
341 return 0
342 itemsize = self.ctitem.size
343 if itemsize <= 0:
344 if isinstance(self.ctitem, ctypevoid.W_CTypeVoid):
345 itemsize = 1
346 else:
347 return 0
348 try:
349 datasize = ovfcheck(length * itemsize)
350 except OverflowError:
351 raise oefmt(space.w_OverflowError,
352 "array size would overflow a ssize_t")
353 result = lltype.malloc(rffi.CCHARP.TO, datasize,
354 flavor='raw', zero=True)
355 try:
356 self.convert_array_from_object(result, w_init)
357 except Exception:
358 lltype.free(result, flavor='raw')
359 raise
360 rffi.cast(rffi.CCHARPP, cdata)[0] = result
361 return 1
362
363 def convert_argument_from_object(self, cdata, w_ob, keepalives, i):
364 # writes the pointer to cdata[0], writes the must-free flag in
365 # the byte just before cdata[0], and returns >0 if something
366 # must be done later to free. Description of flags in set_mustfree_flag
367 from pypy.module._cffi_backend.ctypefunc import set_mustfree_flag
368 from pypy.module._cffi_backend.func import OffsetInBytes
369
370 if isinstance(w_ob, cdataobj.W_CData):
371 result = 0
372 else:
373 space = self.space
374 if self.accept_str and isinstance(w_ob, OffsetInBytes):
375 return self.process_str_from_offset_in_bytes(cdata, w_ob, keepalives, i)
376 if self.accept_str and space.isinstance_w(w_ob, space.w_bytes):
377 # special case to optimize strings passed to a "char *" argument
378 value = space.bytes_w(w_ob)
379 return self.accept_movable_str(cdata, value, keepalives, i)
380 result = self._prepare_pointer_call_argument(w_ob, cdata)
381
382 if result == 0:
383 self.convert_from_object(cdata, w_ob)
384 set_mustfree_flag(cdata, result)
385 return result == 1 # 0 or 2 => False, nothing to do later
386
387 @jit.dont_look_inside
388 def process_str_from_offset_in_bytes(self, cdata, w_ob, keepalives, i):
389 if not rgc.must_split_gc_address_space():
390 lldata = llstr(w_ob.bytes)
391 if not rgc.can_move(lldata):
392 # easy case - it can't move, pass it directly
393 self.accept_str_from_offset_in_bytes(cdata, lldata,
394 keepalives, i, w_ob.offset)
395 if not we_are_translated():
396 keepalives[i] = lldata
397 return 1
398 return 0
399 elif rgc.pin(lldata):
400 return self.accept_str_from_offset_in_bytes(cdata, lldata,
401 keepalives, i, w_ob.offset)
402 # we failed to pin, need to make a copy
403 value = w_ob.bytes
404 return self.accept_movable_str(cdata, value, keepalives, i)
405
406
407 def accept_movable_str(self, cdata, value, keepalives, i):
408 if isinstance(self.ctitem, ctypeprim.W_CTypePrimitiveBool):
409 self._must_be_string_of_zero_or_one(value)
410 keepalives[i] = misc.write_string_as_charp(cdata, value)
411 return 1
412
413 @jit.dont_look_inside
414 def accept_str_from_offset_in_bytes(self, cdata, lldata, keepalives, i, offset):
415 from rpython.rtyper.lltypesystem import llmemory
416 from rpython.rtyper.lltypesystem.rffi import offsetof, VOIDP, VOIDPP
417
418 addr = (llmemory.cast_ptr_to_adr(lldata) +
419 offsetof(STR, 'chars') +
420 llmemory.itemoffsetof(STR.chars, 0) + llmemory.sizeof(lltype.Char) * offset)
421 rffi.cast(VOIDPP, cdata)[0] = rffi.cast(VOIDP, addr)
422 if not we_are_translated():
423 keepalives[i] = lldata
424 return 3
425 return 0
426
427 def getcfield(self, attr):
428 from pypy.module._cffi_backend.ctypestruct import W_CTypeStructOrUnion
429 if isinstance(self.ctitem, W_CTypeStructOrUnion):
430 return self.ctitem.getcfield(attr)
431 return W_CType.getcfield(self, attr)
432
433 def typeoffsetof_field(self, fieldname, following):
434 if following == 0:
435 return self.ctitem.typeoffsetof_field(fieldname, -1)
436 return W_CTypePtrBase.typeoffsetof_field(self, fieldname, following)
437
438 def typeoffsetof_index(self, index):
439 space = self.space
440 ctitem = self.ctitem
441 if ctitem.size < 0:
442 raise oefmt(space.w_TypeError, "pointer to opaque")
443 try:
444 offset = ovfcheck(index * ctitem.size)
445 except OverflowError:
446 raise oefmt(space.w_OverflowError,
447 "array offset would overflow a ssize_t")
448 return ctitem, offset
449
450 def rawaddressof(self, cdata, offset):
451 from pypy.module._cffi_backend.ctypestruct import W_CTypeStructOrUnion
452 space = self.space
453 ctype2 = cdata.ctype
454 if (isinstance(ctype2, W_CTypeStructOrUnion) or
455 isinstance(ctype2, W_CTypePtrOrArray)):
456 ptr = cdata.unsafe_escaping_ptr()
457 ptr = rffi.ptradd(ptr, offset)
458 return cdataobj.W_CData(space, ptr, self)
459 else:
460 raise oefmt(space.w_TypeError,
461 "expected a cdata struct/union/array/pointer object")
462
463 def _fget(self, attrchar):
464 if attrchar == 'i': # item
465 return self.ctitem
466 return W_CTypePtrBase._fget(self, attrchar)
467
468 # ____________________________________________________________
469
470
471 FILEP = rffi.COpaquePtr("FILE")
472 rffi_fdopen = rffi.llexternal("fdopen", [rffi.INT, rffi.CCHARP], FILEP,
473 save_err=rffi.RFFI_SAVE_ERRNO)
474 rffi_setbuf = rffi.llexternal("setbuf", [FILEP, rffi.CCHARP], lltype.Void)
475 rffi_fclose = rffi.llexternal("fclose", [FILEP], rffi.INT)
476
477 class CffiFileObj(object):
478 _immutable_ = True
479
480 def __init__(self, fd, mode):
481 self.llf = rffi_fdopen(fd, mode)
482 if not self.llf:
483 raise OSError(rposix.get_saved_errno(), "fdopen failed")
484 rffi_setbuf(self.llf, lltype.nullptr(rffi.CCHARP.TO))
485
486 def close(self):
487 rffi_fclose(self.llf)
488
489
490 def prepare_file_argument(space, w_fileobj):
491 from pypy.module._io.interp_iobase import W_IOBase
492 assert isinstance(w_fileobj, W_IOBase)
493 space.call_method(w_fileobj, "flush")
494 if w_fileobj.cffi_fileobj is None:
495 fd = space.int_w(space.call_method(w_fileobj, "fileno"))
496 if fd < 0:
497 raise oefmt(space.w_ValueError, "file has no OS file descriptor")
498 fd = os.dup(fd)
499 mode = space.text_w(space.getattr(w_fileobj, space.newtext("mode")))
500 try:
501 w_fileobj.cffi_fileobj = CffiFileObj(fd, mode)
502 except OSError as e:
503 raise wrap_oserror(space, e)
504 return rffi.cast(rffi.CCHARP, w_fileobj.cffi_fileobj.llf)