Debian Codegraph @

pypy/module/_cffi_backend/newtype.py

raw symbols SCIP
1 import sys
2 from pypy.interpreter.error import OperationError, oefmt
3 from pypy.interpreter.gateway import unwrap_spec
4
5 from rpython.rlib.objectmodel import specialize, r_dict, compute_identity_hash
6 from rpython.rlib.rarithmetic import ovfcheck, intmask
7 from rpython.rlib import jit, rweakref, clibffi
8 from rpython.rtyper.lltypesystem import lltype, rffi
9 from rpython.rtyper.tool import rffi_platform
10
11 from pypy.module._cffi_backend.moduledef import FFI_DEFAULT_ABI
12 from pypy.module._cffi_backend import (ctypeobj, ctypeprim, ctypeptr,
13 ctypearray, ctypestruct, ctypevoid, ctypeenum)
14
15
16 @specialize.memo()
17 def alignment(TYPE):
18 S = lltype.Struct('aligncheck', ('x', lltype.Char), ('y', TYPE))
19 return rffi.offsetof(S, 'y')
20
21 alignment_of_pointer = alignment(rffi.CCHARP)
22
23 # ____________________________________________________________
24
25 class UniqueCache:
26 for_testing = False # set to True on the class level in test_c.py
27
28 def __init__(self, space):
29 self.ctvoid = None # Cache for the 'void' type
30 self.ctvoidp = None # Cache for the 'void *' type
31 self.ctchara = None # Cache for the 'char[]' type
32 self.primitives = {} # Cache for {name: primitive_type}
33 self.functions = [] # see _new_function_type()
34 self.functions_packed = None # only across translation
35
36 def _cleanup_(self):
37 import gc
38 assert self.functions_packed is None
39 # Note: a full PyPy translation may still have
40 # 'self.functions == []' at this point, possibly depending
41 # on details. Code tested directly in test_ffi_obj
42 gc.collect()
43 funcs = []
44 for weakdict in self.functions:
45 funcs += weakdict._dict.values()
46 del self.functions[:]
47 self.functions_packed = funcs if len(funcs) > 0 else None
48
49 def unpack_functions(self):
50 for fct in self.functions_packed:
51 _record_function_type(self, fct)
52 self.functions_packed = None
53
54
55 def _clean_cache(space):
56 "NOT_RPYTHON"
57 from pypy.module._cffi_backend.realize_c_type import RealizeCache
58 from pypy.module._cffi_backend.call_python import KeepaliveCache
59 if hasattr(space, 'fromcache'): # not with the TinyObjSpace
60 space.fromcache(UniqueCache).__init__(space)
61 space.fromcache(RealizeCache).__init__(space)
62 space.fromcache(KeepaliveCache).__init__(space)
63
64 # ____________________________________________________________
65
66
67 PRIMITIVE_TYPES = {}
68
69 def eptype(name, TYPE, ctypecls, rep=1):
70 PRIMITIVE_TYPES[name] = ctypecls, rffi.sizeof(TYPE) * rep, alignment(TYPE)
71
72 def eptypesize(name, size, ctypecls):
73 for TYPE in [lltype.Signed, lltype.SignedLongLong, rffi.SIGNEDCHAR,
74 rffi.SHORT, rffi.INT, rffi.LONG, rffi.LONGLONG]:
75 if rffi.sizeof(TYPE) == size:
76 eptype(name, TYPE, ctypecls)
77 return
78 raise NotImplementedError("no integer type of size %d??" % size)
79
80 eptype("char", lltype.Char, ctypeprim.W_CTypePrimitiveChar)
81 eptype("wchar_t", lltype.UniChar, ctypeprim.W_CTypePrimitiveUniChar)
82 eptype("signed char", rffi.SIGNEDCHAR, ctypeprim.W_CTypePrimitiveSigned)
83 eptype("short", rffi.SHORT, ctypeprim.W_CTypePrimitiveSigned)
84 eptype("int", rffi.INT, ctypeprim.W_CTypePrimitiveSigned)
85 eptype("long", rffi.LONG, ctypeprim.W_CTypePrimitiveSigned)
86 eptype("long long", rffi.LONGLONG, ctypeprim.W_CTypePrimitiveSigned)
87 eptype("unsigned char", rffi.UCHAR, ctypeprim.W_CTypePrimitiveUnsigned)
88 eptype("unsigned short", rffi.SHORT, ctypeprim.W_CTypePrimitiveUnsigned)
89 eptype("unsigned int", rffi.INT, ctypeprim.W_CTypePrimitiveUnsigned)
90 eptype("unsigned long", rffi.LONG, ctypeprim.W_CTypePrimitiveUnsigned)
91 eptype("unsigned long long", rffi.LONGLONG, ctypeprim.W_CTypePrimitiveUnsigned)
92 eptype("float", rffi.FLOAT, ctypeprim.W_CTypePrimitiveFloat)
93 eptype("double", rffi.DOUBLE, ctypeprim.W_CTypePrimitiveFloat)
94 eptype("long double", rffi.LONGDOUBLE, ctypeprim.W_CTypePrimitiveLongDouble)
95 eptype("_Bool", lltype.Bool, ctypeprim.W_CTypePrimitiveBool)
96
97 eptype("float _Complex", rffi.FLOAT, ctypeprim.W_CTypePrimitiveComplex, rep=2)
98 eptype("double _Complex", rffi.DOUBLE, ctypeprim.W_CTypePrimitiveComplex, rep=2)
99 eptype("_cffi_float_complex_t", rffi.FLOAT, ctypeprim.W_CTypePrimitiveComplex, rep=2)
100 eptype("_cffi_double_complex_t", rffi.DOUBLE, ctypeprim.W_CTypePrimitiveComplex, rep=2)
101
102 eptypesize("int8_t", 1, ctypeprim.W_CTypePrimitiveSigned)
103 eptypesize("uint8_t", 1, ctypeprim.W_CTypePrimitiveUnsigned)
104 eptypesize("int16_t", 2, ctypeprim.W_CTypePrimitiveSigned)
105 eptypesize("uint16_t", 2, ctypeprim.W_CTypePrimitiveUnsigned)
106 eptypesize("int32_t", 4, ctypeprim.W_CTypePrimitiveSigned)
107 eptypesize("uint32_t", 4, ctypeprim.W_CTypePrimitiveUnsigned)
108 eptypesize("int64_t", 8, ctypeprim.W_CTypePrimitiveSigned)
109 eptypesize("uint64_t", 8, ctypeprim.W_CTypePrimitiveUnsigned)
110
111 eptype("intptr_t", rffi.INTPTR_T, ctypeprim.W_CTypePrimitiveSigned)
112 eptype("uintptr_t", rffi.UINTPTR_T, ctypeprim.W_CTypePrimitiveUnsigned)
113 eptype("size_t", rffi.SIZE_T, ctypeprim.W_CTypePrimitiveUnsigned)
114 eptype("ssize_t", rffi.SSIZE_T, ctypeprim.W_CTypePrimitiveSigned)
115
116 eptypesize("char16_t", 2, ctypeprim.W_CTypePrimitiveUniChar)
117 eptypesize("char32_t", 4, ctypeprim.W_CTypePrimitiveUniChar)
118
119 _WCTSigned = ctypeprim.W_CTypePrimitiveSigned
120 _WCTUnsign = ctypeprim.W_CTypePrimitiveUnsigned
121
122 eptype("ptrdiff_t", getattr(rffi, 'PTRDIFF_T', rffi.INTPTR_T), _WCTSigned)
123 eptype("intmax_t", getattr(rffi, 'INTMAX_T', rffi.LONGLONG), _WCTSigned)
124 eptype("uintmax_t", getattr(rffi, 'UINTMAX_T', rffi.LONGLONG), _WCTUnsign)
125
126 if hasattr(rffi, 'INT_LEAST8_T'):
127 eptype("int_least8_t", rffi.INT_LEAST8_T, _WCTSigned)
128 eptype("int_least16_t", rffi.INT_LEAST16_T, _WCTSigned)
129 eptype("int_least32_t", rffi.INT_LEAST32_T, _WCTSigned)
130 eptype("int_least64_t", rffi.INT_LEAST64_T, _WCTSigned)
131 eptype("uint_least8_t", rffi.UINT_LEAST8_T, _WCTUnsign)
132 eptype("uint_least16_t",rffi.UINT_LEAST16_T, _WCTUnsign)
133 eptype("uint_least32_t",rffi.UINT_LEAST32_T, _WCTUnsign)
134 eptype("uint_least64_t",rffi.UINT_LEAST64_T, _WCTUnsign)
135 else:
136 eptypesize("int_least8_t", 1, _WCTSigned)
137 eptypesize("uint_least8_t", 1, _WCTUnsign)
138 eptypesize("int_least16_t", 2, _WCTSigned)
139 eptypesize("uint_least16_t", 2, _WCTUnsign)
140 eptypesize("int_least32_t", 4, _WCTSigned)
141 eptypesize("uint_least32_t", 4, _WCTUnsign)
142 eptypesize("int_least64_t", 8, _WCTSigned)
143 eptypesize("uint_least64_t", 8, _WCTUnsign)
144
145 if hasattr(rffi, 'INT_FAST8_T'):
146 eptype("int_fast8_t", rffi.INT_FAST8_T, _WCTSigned)
147 eptype("int_fast16_t", rffi.INT_FAST16_T, _WCTSigned)
148 eptype("int_fast32_t", rffi.INT_FAST32_T, _WCTSigned)
149 eptype("int_fast64_t", rffi.INT_FAST64_T, _WCTSigned)
150 eptype("uint_fast8_t", rffi.UINT_FAST8_T, _WCTUnsign)
151 eptype("uint_fast16_t",rffi.UINT_FAST16_T, _WCTUnsign)
152 eptype("uint_fast32_t",rffi.UINT_FAST32_T, _WCTUnsign)
153 eptype("uint_fast64_t",rffi.UINT_FAST64_T, _WCTUnsign)
154 else:
155 eptypesize("int_fast8_t", 1, _WCTSigned)
156 eptypesize("uint_fast8_t", 1, _WCTUnsign)
157 eptypesize("int_fast16_t", 2, _WCTSigned)
158 eptypesize("uint_fast16_t", 2, _WCTUnsign)
159 eptypesize("int_fast32_t", 4, _WCTSigned)
160 eptypesize("uint_fast32_t", 4, _WCTUnsign)
161 eptypesize("int_fast64_t", 8, _WCTSigned)
162 eptypesize("uint_fast64_t", 8, _WCTUnsign)
163
164 @unwrap_spec(name='text')
165 def new_primitive_type(space, name):
166 return _new_primitive_type(space, name)
167
168 @jit.elidable
169 def _new_primitive_type(space, name):
170 unique_cache = space.fromcache(UniqueCache)
171 try:
172 return unique_cache.primitives[name]
173 except KeyError:
174 pass
175 try:
176 ctypecls, size, align = PRIMITIVE_TYPES[name]
177 except KeyError:
178 raise OperationError(space.w_KeyError, space.newtext(name))
179 ctype = ctypecls(space, size, name, len(name), align)
180 unique_cache.primitives[name] = ctype
181 return ctype
182
183 # ____________________________________________________________
184
185 @specialize.memo()
186 def _setup_wref(has_weakref_support):
187 assert has_weakref_support, "_cffi_backend requires weakrefs"
188 ctypeobj.W_CType._pointer_type = rweakref.dead_ref
189 ctypeptr.W_CTypePointer._array_types = None
190
191 @unwrap_spec(w_ctype=ctypeobj.W_CType)
192 def new_pointer_type(space, w_ctype):
193 return _new_pointer_type(space, w_ctype)
194
195 @jit.elidable
196 def _new_pointer_type(space, w_ctype):
197 _setup_wref(rweakref.has_weakref_support())
198 ctptr = w_ctype._pointer_type()
199 if ctptr is None:
200 ctptr = ctypeptr.W_CTypePointer(space, w_ctype)
201 w_ctype._pointer_type = rweakref.ref(ctptr)
202 return ctptr
203
204 # ____________________________________________________________
205
206 @unwrap_spec(w_ctptr=ctypeobj.W_CType)
207 def new_array_type(space, w_ctptr, w_length):
208 if space.is_w(w_length, space.w_None):
209 length = -1
210 else:
211 length = space.getindex_w(w_length, space.w_OverflowError)
212 if length < 0:
213 raise oefmt(space.w_ValueError, "negative array length")
214 return _new_array_type(space, w_ctptr, length)
215
216 @jit.elidable
217 def _new_array_type(space, w_ctptr, length):
218 _setup_wref(rweakref.has_weakref_support())
219 if not isinstance(w_ctptr, ctypeptr.W_CTypePointer):
220 raise oefmt(space.w_TypeError, "first arg must be a pointer ctype")
221 arrays = w_ctptr._array_types
222 if arrays is None:
223 arrays = rweakref.RWeakValueDictionary(int, ctypearray.W_CTypeArray)
224 w_ctptr._array_types = arrays
225 else:
226 ctype = arrays.get(length)
227 if ctype is not None:
228 return ctype
229 #
230 ctitem = w_ctptr.ctitem
231 if ctitem.size < 0:
232 raise oefmt(space.w_ValueError, "array item of unknown size: '%s'",
233 ctitem.name)
234 if length < 0:
235 assert length == -1
236 arraysize = -1
237 extra = '[]'
238 else:
239 try:
240 arraysize = ovfcheck(length * ctitem.size)
241 except OverflowError:
242 raise oefmt(space.w_OverflowError,
243 "array size would overflow a ssize_t")
244 extra = '[%d]' % length
245 #
246 ctype = ctypearray.W_CTypeArray(space, w_ctptr, length, arraysize, extra)
247 arrays.set(length, ctype)
248 return ctype
249
250 # ____________________________________________________________
251
252
253 SF_MSVC_BITFIELDS = 0x01
254 SF_GCC_ARM_BITFIELDS = 0x02
255 SF_GCC_X86_BITFIELDS = 0x10
256
257 SF_GCC_BIG_ENDIAN = 0x04
258 SF_GCC_LITTLE_ENDIAN = 0x40
259
260 SF_PACKED = 0x08
261 SF_STD_FIELD_POS = 0x80
262
263 if sys.platform == 'win32':
264 SF_DEFAULT_PACKING = 8
265 else:
266 SF_DEFAULT_PACKING = 0x40000000 # a huge power of two
267
268
269 if sys.platform == 'win32':
270 DEFAULT_SFLAGS_PLATFORM = SF_MSVC_BITFIELDS
271 else:
272 if (rffi_platform.getdefined('__arm__', '') or
273 rffi_platform.getdefined('__aarch64__', '')):
274 DEFAULT_SFLAGS_PLATFORM = SF_GCC_ARM_BITFIELDS
275 else:
276 DEFAULT_SFLAGS_PLATFORM = SF_GCC_X86_BITFIELDS
277
278 if sys.byteorder == 'big':
279 DEFAULT_SFLAGS_ENDIAN = SF_GCC_BIG_ENDIAN
280 else:
281 DEFAULT_SFLAGS_ENDIAN = SF_GCC_LITTLE_ENDIAN
282
283
284 def complete_sflags(sflags):
285 # add one of the SF_xxx_BITFIELDS flags if none is specified
286 if not (sflags & (SF_MSVC_BITFIELDS | SF_GCC_ARM_BITFIELDS |
287 SF_GCC_X86_BITFIELDS)):
288 sflags |= DEFAULT_SFLAGS_PLATFORM
289 # add one of SF_GCC_xx_ENDIAN if none is specified
290 if not (sflags & (SF_GCC_BIG_ENDIAN | SF_GCC_LITTLE_ENDIAN)):
291 sflags |= DEFAULT_SFLAGS_ENDIAN
292 return sflags
293
294 # ____________________________________________________________
295
296
297 @unwrap_spec(name='text')
298 def new_struct_type(space, name):
299 return ctypestruct.W_CTypeStruct(space, name)
300
301 @unwrap_spec(name='text')
302 def new_union_type(space, name):
303 return ctypestruct.W_CTypeUnion(space, name)
304
305 def detect_custom_layout(w_ctype, sflags, cdef_value, compiler_value,
306 msg1, msg2="", msg3=""):
307 if compiler_value != cdef_value:
308 if sflags & SF_STD_FIELD_POS:
309 from pypy.module._cffi_backend.ffi_obj import get_ffi_error
310 w_FFIError = get_ffi_error(w_ctype.space)
311 raise oefmt(w_FFIError,
312 '%s: %s%s%s (cdef says %d, but C compiler says %d).'
313 ' fix it or use "...;" as the last field in the '
314 'cdef for %s to make it flexible',
315 w_ctype.name, msg1, msg2, msg3,
316 cdef_value, compiler_value, w_ctype.name)
317 w_ctype._custom_field_pos = True
318
319 def roundup_bytes(bytes, bit):
320 assert bit == (bit & 7)
321 return bytes + (bit > 0)
322
323 @unwrap_spec(w_ctype=ctypeobj.W_CType, totalsize=int, totalalignment=int,
324 sflags=int, pack=int)
325 def complete_struct_or_union(space, w_ctype, w_fields, w_ignored=None,
326 totalsize=-1, totalalignment=-1, sflags=0,
327 pack=0):
328 sflags = complete_sflags(sflags)
329 if sflags & SF_PACKED:
330 pack = 1
331 elif pack <= 0:
332 pack = SF_DEFAULT_PACKING
333 else:
334 sflags |= SF_PACKED
335
336 if (not isinstance(w_ctype, ctypestruct.W_CTypeStructOrUnion)
337 or w_ctype.size >= 0):
338 raise oefmt(space.w_TypeError,
339 "first arg must be a non-initialized struct or union "
340 "ctype")
341
342 is_union = isinstance(w_ctype, ctypestruct.W_CTypeUnion)
343 alignment = 1
344 byteoffset = 0 # the real value is 'byteoffset+bitoffset*8', which
345 bitoffset = 0 # counts the offset in bits
346 byteoffsetmax = 0 # the maximum value of byteoffset-rounded-up-to-byte
347 prev_bitfield_size = 0
348 prev_bitfield_free = 0
349 fields_w = space.listview(w_fields)
350 fields_list = []
351 fields_dict = {}
352 w_ctype._custom_field_pos = False
353 with_var_array = False
354 with_packed_change = False
355
356 for i in range(len(fields_w)):
357 w_field = fields_w[i]
358 field_w = space.fixedview(w_field)
359 if not (2 <= len(field_w) <= 4):
360 raise oefmt(space.w_TypeError, "bad field descr")
361 fname = space.text_w(field_w[0])
362 ftype = space.interp_w(ctypeobj.W_CType, field_w[1])
363 fbitsize = -1
364 foffset = -1
365 if len(field_w) > 2: fbitsize = space.int_w(field_w[2])
366 if len(field_w) > 3: foffset = space.int_w(field_w[3])
367 #
368 if fname in fields_dict:
369 raise oefmt(space.w_KeyError, "duplicate field name '%s'", fname)
370 #
371 if ftype.size == -2:
372 # Lazy struct, try to force now
373 from pypy.module._cffi_backend import realize_c_type
374 realize_c_type.do_realize_lazy_struct(ftype)
375 if ftype.size < 0:
376 if (isinstance(ftype, ctypearray.W_CTypeArray) and fbitsize < 0
377 and (i == len(fields_w) - 1 or foffset != -1)):
378 with_var_array = True
379 else:
380 raise oefmt(space.w_TypeError,
381 "field '%s.%s' has ctype '%s' of unknown size",
382 w_ctype.name, fname, ftype.name)
383 elif isinstance(ftype, ctypestruct.W_CTypeStructOrUnion):
384 ftype.force_lazy_struct()
385 # GCC (or maybe C99) accepts var-sized struct fields that are not
386 # the last field of a larger struct. That's why there is no
387 # check here for "last field": we propagate the flag
388 # '_with_var_array' to any struct that contains either an open-
389 # ended array or another struct that recursively contains an
390 # open-ended array.
391 if ftype._with_var_array:
392 with_var_array = True
393 #
394 if is_union:
395 byteoffset = bitoffset = 0 # reset each field at offset 0
396 #
397 # update the total alignment requirement, but skip it if the
398 # field is an anonymous bitfield or if SF_PACKED
399 falignorg = ftype.alignof()
400 falign = min(pack, falignorg)
401 do_align = True
402 if (sflags & SF_GCC_ARM_BITFIELDS) == 0 and fbitsize >= 0:
403 if (sflags & SF_MSVC_BITFIELDS) == 0:
404 # GCC: anonymous bitfields (of any size) don't cause alignment
405 do_align = (fname != '')
406 else:
407 # MSVC: zero-sized bitfields don't cause alignment
408 do_align = (fbitsize > 0)
409 if alignment < falign and do_align:
410 alignment = falign
411 #
412 if is_union and i > 0:
413 fflags = ctypestruct.W_CField.BF_IGNORE_IN_CTOR
414 else:
415 fflags = 0
416 #
417 if fbitsize < 0:
418 # not a bitfield: common case
419
420 if isinstance(ftype, ctypearray.W_CTypeArray) and ftype.length<=0:
421 bs_flag = ctypestruct.W_CField.BS_EMPTY_ARRAY
422 else:
423 bs_flag = ctypestruct.W_CField.BS_REGULAR
424
425 # align this field to its own 'falign' by inserting padding.
426 # first, pad to the next byte,
427 # then pad to 'falign' or 'falignorg' bytes
428 byteoffset = roundup_bytes(byteoffset, bitoffset)
429 bitoffset = 0
430 byteoffsetorg = (byteoffset + falignorg-1) & ~(falignorg-1)
431 byteoffset = (byteoffset + falign-1) & ~(falign-1)
432
433 if byteoffsetorg != byteoffset:
434 with_packed_change = True
435
436 if foffset >= 0:
437 # a forced field position: ignore the offset just computed,
438 # except to know if we must set 'custom_field_pos'
439 detect_custom_layout(w_ctype, sflags, byteoffset, foffset,
440 "wrong offset for field '",
441 fname, "'")
442 byteoffset = foffset
443
444 if (fname == '' and
445 isinstance(ftype, ctypestruct.W_CTypeStructOrUnion)):
446 # a nested anonymous struct or union
447 # note: it seems we only get here with ffi.verify()
448 srcfield2names = {}
449 for name, srcfld in ftype._fields_dict.items():
450 srcfield2names[srcfld] = name
451 for srcfld in ftype._fields_list:
452 fld = srcfld.make_shifted(byteoffset, fflags)
453 fields_list.append(fld)
454 try:
455 fields_dict[srcfield2names[srcfld]] = fld
456 except KeyError:
457 pass
458 # always forbid such structures from being passed by value
459 w_ctype._custom_field_pos = True
460 else:
461 # a regular field
462 fld = ctypestruct.W_CField(ftype, byteoffset, bs_flag, -1,
463 fflags)
464 fields_list.append(fld)
465 fields_dict[fname] = fld
466
467 if ftype.size >= 0:
468 byteoffset += ftype.size
469 prev_bitfield_size = 0
470
471 else:
472 # this is the case of a bitfield
473
474 if foffset >= 0:
475 raise oefmt(space.w_TypeError,
476 "field '%s.%s' is a bitfield, but a fixed offset "
477 "is specified", w_ctype.name, fname)
478
479 if not (isinstance(ftype, ctypeprim.W_CTypePrimitiveSigned) or
480 isinstance(ftype, ctypeprim.W_CTypePrimitiveUnsigned) or
481 isinstance(ftype,ctypeprim.W_CTypePrimitiveCharOrUniChar)):
482 raise oefmt(space.w_TypeError,
483 "field '%s.%s' declared as '%s' cannot be a bit "
484 "field", w_ctype.name, fname, ftype.name)
485 if fbitsize > 8 * ftype.size:
486 raise oefmt(space.w_TypeError,
487 "bit field '%s.%s' is declared '%s:%d', which "
488 "exceeds the width of the type",
489 w_ctype.name, fname, ftype.name, fbitsize)
490
491 # compute the starting position of the theoretical field
492 # that covers a complete 'ftype', inside of which we will
493 # locate the real bitfield
494 field_offset_bytes = byteoffset
495 field_offset_bytes &= ~(falign - 1)
496
497 if fbitsize == 0:
498 if fname != '':
499 raise oefmt(space.w_TypeError,
500 "field '%s.%s' is declared with :0",
501 w_ctype.name, fname)
502 if (sflags & SF_MSVC_BITFIELDS) == 0:
503 # GCC's notion of "ftype :0;"
504 # pad byteoffset to a value aligned for "ftype"
505 if (roundup_bytes(byteoffset, bitoffset) >
506 field_offset_bytes):
507 field_offset_bytes += falign
508 assert byteoffset < field_offset_bytes
509 byteoffset = field_offset_bytes
510 bitoffset = 0
511 else:
512 # MSVC's notion of "ftype :0;
513 # Mostly ignored. It seems they only serve as
514 # separator between other bitfields, to force them
515 # into separate words.
516 pass
517 prev_bitfield_size = 0
518
519 else:
520 if (sflags & SF_MSVC_BITFIELDS) == 0:
521 # GCC's algorithm
522
523 # Can the field start at the offset given by 'boffset'? It
524 # can if it would entirely fit into an aligned ftype field.
525 bits_already_occupied = (
526 (byteoffset-field_offset_bytes) * 8 + bitoffset)
527
528 if bits_already_occupied + fbitsize > 8 * ftype.size:
529 # it would not fit, we need to start at the next
530 # allowed position
531 if ((sflags & SF_PACKED) != 0 and
532 (bits_already_occupied & 7) != 0):
533 raise oefmt(space.w_NotImplementedError,
534 "with 'packed', gcc would compile "
535 "field '%s.%s' to reuse some bits in "
536 "the previous field",
537 w_ctype.name, fname)
538 field_offset_bytes += falign
539 assert byteoffset < field_offset_bytes
540 byteoffset = field_offset_bytes
541 bitoffset = 0
542 bitshift = 0
543 else:
544 bitshift = bits_already_occupied
545 assert bitshift >= 0
546 bitoffset += fbitsize
547 byteoffset += (bitoffset >> 3)
548 bitoffset &= 7
549
550 else:
551 # MSVC's algorithm
552
553 # A bitfield is considered as taking the full width
554 # of their declared type. It can share some bits
555 # with the previous field only if it was also a
556 # bitfield and used a type of the same size.
557 if (prev_bitfield_size == ftype.size and
558 prev_bitfield_free >= fbitsize):
559 # yes: reuse
560 bitshift = 8 * prev_bitfield_size - prev_bitfield_free
561 else:
562 # no: start a new full field
563 byteoffset = roundup_bytes(byteoffset, bitoffset)
564 bitoffset = 0
565 # align
566 byteoffset = (byteoffset + falign-1) & ~(falign-1)
567 byteoffset += ftype.size
568 bitshift = 0
569 prev_bitfield_size = ftype.size
570 prev_bitfield_free = 8 * prev_bitfield_size
571 #
572 prev_bitfield_free -= fbitsize
573 field_offset_bytes = byteoffset - ftype.size
574
575 if sflags & SF_GCC_BIG_ENDIAN:
576 bitshift = 8 * ftype.size - fbitsize- bitshift
577
578 if fname != '':
579 fld = ctypestruct.W_CField(ftype, field_offset_bytes,
580 bitshift, fbitsize, fflags)
581 fields_list.append(fld)
582 fields_dict[fname] = fld
583
584 if roundup_bytes(byteoffset, bitoffset) > byteoffsetmax:
585 byteoffsetmax = roundup_bytes(byteoffset, bitoffset)
586
587 # Like C, if the size of this structure would be zero, we compute it
588 # as 1 instead. But for ctypes support, we allow the manually-
589 # specified totalsize to be zero in this case.
590 alignedsize = (byteoffsetmax + alignment - 1) & ~(alignment - 1)
591 alignedsize = alignedsize or 1
592
593 if totalsize < 0:
594 totalsize = alignedsize
595 else:
596 detect_custom_layout(w_ctype, sflags, alignedsize, totalsize,
597 "wrong total size")
598 if totalsize < byteoffsetmax:
599 raise oefmt(space.w_TypeError,
600 "%s cannot be of size %d: there are fields at least up to %d",
601 w_ctype.name, totalsize, byteoffsetmax)
602 if totalalignment < 0:
603 totalalignment = alignment
604 else:
605 detect_custom_layout(w_ctype, sflags, alignment, totalalignment,
606 "wrong total alignment")
607
608 w_ctype.size = totalsize
609 w_ctype.alignment = totalalignment
610 w_ctype._fields_list = fields_list[:]
611 w_ctype._fields_dict = fields_dict
612 #w_ctype._custom_field_pos = ...set above already
613 w_ctype._with_var_array = with_var_array
614 w_ctype._with_packed_change = with_packed_change
615
616 # ____________________________________________________________
617
618 def new_void_type(space):
619 return _new_void_type(space)
620
621 @jit.elidable
622 def _new_void_type(space):
623 unique_cache = space.fromcache(UniqueCache)
624 if unique_cache.ctvoid is None:
625 unique_cache.ctvoid = ctypevoid.W_CTypeVoid(space)
626 return unique_cache.ctvoid
627
628 @jit.elidable
629 def _new_voidp_type(space):
630 unique_cache = space.fromcache(UniqueCache)
631 if unique_cache.ctvoidp is None:
632 unique_cache.ctvoidp = new_pointer_type(space, new_void_type(space))
633 return unique_cache.ctvoidp
634
635 @jit.elidable
636 def _new_chara_type(space):
637 unique_cache = space.fromcache(UniqueCache)
638 if unique_cache.ctchara is None:
639 ctchar = new_primitive_type(space, "char")
640 ctcharp = new_pointer_type(space, ctchar)
641 ctchara = _new_array_type(space, ctcharp, length=-1)
642 unique_cache.ctchara = ctchara
643 return unique_cache.ctchara
644
645 # ____________________________________________________________
646
647 @unwrap_spec(name='text', w_basectype=ctypeobj.W_CType)
648 def new_enum_type(space, name, w_enumerators, w_enumvalues, w_basectype):
649 enumerators_w = space.fixedview(w_enumerators)
650 enumvalues_w = space.fixedview(w_enumvalues)
651 if len(enumerators_w) != len(enumvalues_w):
652 raise oefmt(space.w_ValueError, "tuple args must have the same size")
653 enumerators = [space.text_w(w) for w in enumerators_w]
654 #
655 if (not isinstance(w_basectype, ctypeprim.W_CTypePrimitiveSigned) and
656 not isinstance(w_basectype, ctypeprim.W_CTypePrimitiveUnsigned)):
657 raise oefmt(space.w_TypeError,
658 "expected a primitive signed or unsigned base type")
659 #
660 lvalue = lltype.malloc(rffi.CCHARP.TO, w_basectype.size, flavor='raw')
661 try:
662 for w in enumvalues_w:
663 # detects out-of-range or badly typed values
664 w_basectype.convert_from_object(lvalue, w)
665 finally:
666 lltype.free(lvalue, flavor='raw')
667 #
668 size = w_basectype.size
669 align = w_basectype.align
670 if isinstance(w_basectype, ctypeprim.W_CTypePrimitiveSigned):
671 enumvalues = [space.int_w(w) for w in enumvalues_w]
672 ctype = ctypeenum.W_CTypeEnumSigned(space, name, size, align,
673 enumerators, enumvalues)
674 else:
675 enumvalues = [space.uint_w(w) for w in enumvalues_w]
676 ctype = ctypeenum.W_CTypeEnumUnsigned(space, name, size, align,
677 enumerators, enumvalues)
678 return ctype
679
680 # ____________________________________________________________
681
682 @unwrap_spec(w_fresult=ctypeobj.W_CType, ellipsis=int, abi=int)
683 def new_function_type(space, w_fargs, w_fresult, ellipsis=0,
684 abi=FFI_DEFAULT_ABI):
685 fargs = []
686 for w_farg in space.fixedview(w_fargs):
687 if not isinstance(w_farg, ctypeobj.W_CType):
688 raise oefmt(space.w_TypeError,
689 "first arg must be a tuple of ctype objects")
690 if isinstance(w_farg, ctypearray.W_CTypeArray):
691 w_farg = w_farg.ctptr
692 fargs.append(w_farg)
693 return _new_function_type(space, fargs, w_fresult, bool(ellipsis), abi)
694
695 def _func_key_hash(unique_cache, fargs, fresult, ellipsis, abi):
696 x = compute_identity_hash(fresult)
697 for w_arg in fargs:
698 y = compute_identity_hash(w_arg)
699 x = intmask((1000003 * x) ^ y)
700 x ^= ellipsis + 2 * abi
701 if unique_cache.for_testing: # constant-folded to False in translation;
702 x &= 3 # but for test, keep only 2 bits of hash
703 return x
704
705 # can't use @jit.elidable here, because it might call back to random
706 # space functions via force_lazy_struct()
707 def _new_function_type(space, fargs, fresult, ellipsis, abi):
708 try:
709 return _get_function_type(space, fargs, fresult, ellipsis, abi)
710 except KeyError:
711 return _build_function_type(space, fargs, fresult, ellipsis, abi)
712
713 @jit.elidable
714 def _get_function_type(space, fargs, fresult, ellipsis, abi):
715 # This function is elidable because if called again with exactly the
716 # same arguments (and if it didn't raise KeyError), it would give
717 # the same result, at least as long as this result is still live.
718 #
719 # 'unique_cache.functions' is a list of weak dicts, each mapping
720 # the func_hash number to a W_CTypeFunc. There is normally only
721 # one such dict, but in case of hash collision, there might be
722 # more.
723 unique_cache = space.fromcache(UniqueCache)
724 if unique_cache.functions_packed is not None:
725 unique_cache.unpack_functions()
726 func_hash = _func_key_hash(unique_cache, fargs, fresult, ellipsis, abi)
727 for weakdict in unique_cache.functions:
728 ctype = weakdict.get(func_hash)
729 if (ctype is not None and
730 ctype.ctitem is fresult and
731 ctype.fargs == fargs and
732 ctype.ellipsis == ellipsis and
733 ctype.abi == abi):
734 return ctype
735 raise KeyError
736
737 @jit.dont_look_inside
738 def _build_function_type(space, fargs, fresult, ellipsis, abi):
739 from pypy.module._cffi_backend import ctypefunc
740 #
741 if ((fresult.size < 0 and
742 not isinstance(fresult, ctypevoid.W_CTypeVoid))
743 or isinstance(fresult, ctypearray.W_CTypeArray)):
744 if (isinstance(fresult, ctypestruct.W_CTypeStructOrUnion) and
745 fresult.size < 0):
746 raise oefmt(space.w_TypeError,
747 "result type '%s' is opaque", fresult.name)
748 else:
749 raise oefmt(space.w_TypeError,
750 "invalid result type: '%s'", fresult.name)
751 #
752 fct = ctypefunc.W_CTypeFunc(space, fargs, fresult, ellipsis, abi)
753 unique_cache = space.fromcache(UniqueCache)
754 _record_function_type(unique_cache, fct)
755 return fct
756
757 def _record_function_type(unique_cache, fct):
758 from pypy.module._cffi_backend import ctypefunc
759 #
760 func_hash = _func_key_hash(unique_cache, fct.fargs, fct.ctitem,
761 fct.ellipsis, fct.abi)
762 for weakdict in unique_cache.functions:
763 if weakdict.get(func_hash) is None:
764 break
765 else:
766 weakdict = rweakref.RWeakValueDictionary(int, ctypefunc.W_CTypeFunc)
767 unique_cache.functions.append(weakdict)
768 weakdict.set(func_hash, fct)