Debian Codegraph @

pypy/module/_cffi_backend/ctypestruct.py

raw symbols SCIP
1 """
2 Struct and unions.
3 """
4
5 from pypy.interpreter.baseobjspace import W_Root
6 from pypy.interpreter.error import OperationError, oefmt
7 from pypy.interpreter.typedef import TypeDef, interp_attrproperty, interp_attrproperty_w
8
9 from rpython.rlib import jit
10 from rpython.rlib.rarithmetic import r_uint, r_ulonglong, r_longlong, intmask
11 from rpython.rlib.rarithmetic import ovfcheck
12 from rpython.rtyper.lltypesystem import lltype, rffi
13
14 from pypy.module._cffi_backend import cdataobj, ctypeprim, misc
15 from pypy.module._cffi_backend.ctypeobj import W_CType
16
17
18 class W_CTypeStructOrUnion(W_CType):
19 _immutable_fields_ = ['alignment?', '_fields_list?[*]', '_fields_dict?',
20 '_custom_field_pos?', '_with_var_array?']
21 is_indirect_arg_for_call_python = True
22
23 # three possible states:
24 # - "opaque": for opaque C structs; self.size < 0.
25 # - "lazy": for non-opaque C structs whose _fields_list, _fields_dict,
26 # _custom_field_pos and _with_var_array are not filled yet; can be
27 # filled by calling force_lazy_struct().
28 # (But self.size and .alignment are already set and won't change.)
29 # - "forced": for non-opaque C structs which are fully ready.
30
31 # fields added by complete_struct_or_union():
32 alignment = -1
33 _fields_list = None
34 _fields_dict = None
35 _custom_field_pos = False
36 _with_var_array = False
37 _with_packed_changed = False
38
39 def __init__(self, space, name):
40 W_CType.__init__(self, space, -1, name, len(name))
41
42 def check_complete(self, w_errorcls=None):
43 # Check ONLY that are are not opaque. Complain if we are.
44 if self.size < 0:
45 space = self.space
46 raise oefmt(w_errorcls or space.w_TypeError,
47 "'%s' is opaque or not completed yet", self.name)
48
49 def force_lazy_struct(self):
50 # Force a "lazy" struct to become "forced"; complain if we are "opaque".
51 if self._fields_list is None:
52 self.check_complete()
53 #
54 from pypy.module._cffi_backend import realize_c_type
55 realize_c_type.do_realize_lazy_struct(self)
56
57 def _alignof(self):
58 self.check_complete(w_errorcls=self.space.w_ValueError)
59 if self.alignment == -1:
60 self.force_lazy_struct()
61 assert self.alignment > 0
62 return self.alignment
63
64 def _fget(self, attrchar):
65 if attrchar == 'f': # fields
66 space = self.space
67 if self.size < 0:
68 return space.w_None
69 self.force_lazy_struct()
70 result = [None] * len(self._fields_list)
71 for fname, field in self._fields_dict.iteritems():
72 i = self._fields_list.index(field)
73 result[i] = space.newtuple([space.newtext(fname),
74 field])
75 return space.newlist(result)
76 return W_CType._fget(self, attrchar)
77
78 def convert_to_object(self, cdata):
79 space = self.space
80 self.check_complete()
81 return cdataobj.W_CData(space, cdata, self)
82
83 def copy_and_convert_to_object(self, source):
84 space = self.space
85 self.check_complete()
86 ptr = lltype.malloc(rffi.CCHARP.TO, self.size, flavor='raw', zero=False)
87 misc._raw_memcopy(source, ptr, self.size)
88 return cdataobj.W_CDataNewStd(space, ptr, self, -1, self.size)
89
90 def typeoffsetof_field(self, fieldname, following):
91 self.force_lazy_struct()
92 space = self.space
93 try:
94 cfield = self._getcfield_const(fieldname)
95 except KeyError:
96 raise OperationError(space.w_KeyError, space.newtext(fieldname))
97 if cfield.bitshift >= 0:
98 raise oefmt(space.w_TypeError, "not supported for bitfields")
99 return (cfield.ctype, cfield.offset)
100
101 def _copy_from_same(self, cdata, w_ob):
102 if isinstance(w_ob, cdataobj.W_CData):
103 if w_ob.ctype is self and self.size >= 0:
104 with w_ob as ptr:
105 misc._raw_memcopy(ptr, cdata, self.size)
106 return True
107 return False
108
109 def convert_from_object(self, cdata, w_ob):
110 if not self._copy_from_same(cdata, w_ob):
111 self.convert_struct_from_object(cdata, w_ob, optvarsize=-1)
112
113 @jit.unroll_safe
114 def _max_initializers(self):
115 if self._with_var_array:
116 return -1
117 res = 0
118 for i in range(len(self._fields_list)):
119 j = 0
120 res += not (self._fields_list[j].flags &
121 W_CField.BF_IGNORE_IN_CTOR)
122 return res
123
124 @jit.unroll_safe
125 def _unpack_initializer(self, w_ob):
126 from pypy.objspace.std.listobject import W_ListObject
127 from pypy.objspace.std.tupleobject import W_AbstractTupleObject
128 space = self.space
129 # this code is a bit weird. in theory, the look_inside_iff decorations
130 # on space.listview and its callees should be enough to get the correct
131 # unrolling effect. however, in a typicaly use case of ffi.new, there
132 # is too much app-level code running between the call to ffi.new and
133 # reaching convert_struct_from_object and the front-end loses the
134 # virtualness information. therefore we unroll a bit more aggressively
135 # here: we unroll, if the struct is not var-sized and the initializer
136 # length is up to the number of fields of the struct. in addition, the
137 # W_*Object must be virtual. see test_cffi_init_struct_with_list.
138 if jit.we_are_jitted() and not self._with_var_array:
139 max_num_initializer = self._max_initializers()
140 length = space.len_w(w_ob)
141 if max_num_initializer >= length:
142 if isinstance(w_ob, W_AbstractTupleObject) and space._uses_tuple_iter(w_ob):
143 return w_ob.getitems_copy()
144 if type(w_ob) is W_ListObject:
145 return w_ob.getitems_unroll()[:]
146 return space.listview(w_ob)
147
148 @jit.look_inside_iff(
149 lambda self, cdata, w_ob, optvarsize: jit.isvirtual(w_ob)
150 )
151 def convert_struct_from_object(self, cdata, w_ob, optvarsize):
152 self.force_lazy_struct()
153
154 space = self.space
155 if (space.isinstance_w(w_ob, space.w_list) or
156 space.isinstance_w(w_ob, space.w_tuple)):
157 lst_w = self._unpack_initializer(w_ob)
158 j = 0
159 for w_obj in lst_w:
160 try:
161 while (self._fields_list[j].flags &
162 W_CField.BF_IGNORE_IN_CTOR):
163 j += 1
164 except IndexError:
165 raise oefmt(space.w_ValueError,
166 "too many initializers for '%s' (got %d)",
167 self.name, len(lst_w))
168 optvarsize = self._fields_list[j].write_v(cdata, w_obj,
169 optvarsize)
170 j += 1
171 return optvarsize
172
173 elif space.isinstance_w(w_ob, space.w_dict):
174 lst_w = space.fixedview(w_ob)
175 for i in range(len(lst_w)):
176 w_key = lst_w[i]
177 key = space.text_w(w_key)
178 try:
179 cf = self._fields_dict[key]
180 except KeyError:
181 space.raise_key_error(w_key)
182 assert 0
183 optvarsize = cf.write_v(cdata, space.getitem(w_ob, w_key),
184 optvarsize)
185 return optvarsize
186
187 else:
188 if optvarsize == -1:
189 msg = "list or tuple or dict or struct-cdata"
190 else:
191 msg = "list or tuple or dict"
192 raise self._convert_error(msg, w_ob)
193
194 @jit.elidable
195 def _getcfield_const(self, attr):
196 return self._fields_dict[attr]
197
198 def getcfield(self, attr):
199 # Returns a W_CField. Error cases: returns None if we are an
200 # opaque struct; or raises KeyError if the particular field
201 # 'attr' does not exist. The point of not directly building the
202 # error here is to get the exact ctype in the error message: it
203 # might be of the kind 'struct foo' or 'struct foo *'.
204 if self._fields_dict is None:
205 if self.size < 0:
206 return None
207 self.force_lazy_struct()
208 self = jit.promote(self)
209 attr = jit.promote_string(attr)
210 return self._getcfield_const(attr) # <= KeyError here
211
212 def cdata_dir(self):
213 if self.size < 0:
214 return []
215 self.force_lazy_struct()
216 return self._fields_dict.keys()
217
218
219 class W_CTypeStruct(W_CTypeStructOrUnion):
220 kind = "struct"
221
222
223 class W_CTypeUnion(W_CTypeStructOrUnion):
224 kind = "union"
225
226
227 class W_CField(W_Root):
228 _immutable_ = True
229
230 BS_REGULAR = -1
231 BS_EMPTY_ARRAY = -2
232
233 BF_IGNORE_IN_CTOR = 0x01
234
235 def __init__(self, ctype, offset, bitshift, bitsize, flags):
236 self.ctype = ctype
237 self.offset = offset
238 self.bitshift = bitshift # >= 0: bitshift; or BS_REGULAR/BS_EMPTY_ARRAY
239 self.bitsize = bitsize
240 self.flags = flags # BF_xxx
241
242 def is_bitfield(self):
243 return self.bitshift >= 0
244
245 def make_shifted(self, offset, fflags):
246 return W_CField(self.ctype, offset + self.offset,
247 self.bitshift, self.bitsize, self.flags | fflags)
248
249 def read(self, cdata, w_cdata):
250 cdata = rffi.ptradd(cdata, self.offset)
251 if self.bitshift == self.BS_REGULAR:
252 return self.ctype.convert_to_object(cdata)
253 elif self.bitshift == self.BS_EMPTY_ARRAY:
254 from pypy.module._cffi_backend import ctypearray
255 ctype = self.ctype
256 assert isinstance(ctype, ctypearray.W_CTypeArray)
257 structobj = w_cdata.get_structobj()
258 if structobj is not None:
259 # variable-length array
260 size = structobj.allocated_length - self.offset
261 if size >= 0:
262 arraylen = size // ctype.ctitem.size
263 return cdataobj.W_CDataSliced(ctype.space, cdata, ctype,
264 arraylen)
265 return cdataobj.W_CData(ctype.space, cdata, ctype.ctptr)
266 else:
267 return self.convert_bitfield_to_object(cdata)
268
269 def write(self, cdata, w_ob):
270 cdata = rffi.ptradd(cdata, self.offset)
271 if self.is_bitfield():
272 self.convert_bitfield_from_object(cdata, w_ob)
273 else:
274 self.ctype.convert_from_object(cdata, w_ob)
275
276 def add_varsize_length(self, space, itemsize, varsizelength, optvarsize):
277 # returns an updated 'optvarsize' to account for an array of
278 # 'varsizelength' elements, each of size 'itemsize', that starts
279 # at 'self.offset'.
280 try:
281 varsize = ovfcheck(itemsize * varsizelength)
282 size = ovfcheck(self.offset + varsize)
283 except OverflowError:
284 raise oefmt(space.w_OverflowError,
285 "array size would overflow a ssize_t")
286 assert size >= 0
287 return max(size, optvarsize)
288
289 def write_v(self, cdata, w_ob, optvarsize):
290 # a special case for var-sized C99 arrays
291 from pypy.module._cffi_backend import ctypearray
292 ct = self.ctype
293 space = ct.space
294 if isinstance(ct, ctypearray.W_CTypeArray) and ct.length < 0:
295 w_ob, varsizelength = ct.get_new_array_length(w_ob)
296 if optvarsize != -1:
297 # in this mode, the only purpose of this function is to compute
298 # the real size of the structure from a var-sized C99 array
299 assert cdata == lltype.nullptr(rffi.CCHARP.TO)
300 return self.add_varsize_length(space, ct.ctitem.size,
301 varsizelength, optvarsize)
302 # if 'value' was only an integer, get_new_array_length() returns
303 # w_ob = space.w_None. Detect if this was the case,
304 # and if so, stop here, leaving the content uninitialized
305 # (it should be zero-initialized from somewhere else).
306 if space.is_w(w_ob, space.w_None):
307 return optvarsize
308 #
309 if optvarsize == -1:
310 self.write(cdata, w_ob)
311 elif (isinstance(ct, W_CTypeStructOrUnion) and ct._with_var_array and
312 not isinstance(w_ob, cdataobj.W_CData)):
313 subsize = ct.size
314 subsize = ct.convert_struct_from_object(
315 lltype.nullptr(rffi.CCHARP.TO), w_ob, subsize)
316 optvarsize = self.add_varsize_length(space, 1, subsize, optvarsize)
317 return optvarsize
318
319 def convert_bitfield_to_object(self, cdata):
320 ctype = self.ctype
321 space = ctype.space
322 #
323 if isinstance(ctype, ctypeprim.W_CTypePrimitiveSigned):
324 if ctype.value_fits_long:
325 value = r_uint(misc.read_raw_long_data(cdata, ctype.size))
326 valuemask = (r_uint(1) << self.bitsize) - 1
327 shiftforsign = r_uint(1) << (self.bitsize - 1)
328 value = ((value >> self.bitshift) + shiftforsign) & valuemask
329 result = intmask(value) - intmask(shiftforsign)
330 return space.newint(result)
331 else:
332 value = misc.read_raw_unsigned_data(cdata, ctype.size)
333 valuemask = (r_ulonglong(1) << self.bitsize) - 1
334 shiftforsign = r_ulonglong(1) << (self.bitsize - 1)
335 value = ((value >> self.bitshift) + shiftforsign) & valuemask
336 result = r_longlong(value) - r_longlong(shiftforsign)
337 return space.newint(result)
338 #
339 if isinstance(ctype, ctypeprim.W_CTypePrimitiveUnsigned):
340 value_fits_long = ctype.value_fits_long
341 value_fits_ulong = ctype.value_fits_ulong
342 elif isinstance(ctype, ctypeprim.W_CTypePrimitiveCharOrUniChar):
343 value_fits_long = True
344 value_fits_ulong = True
345 else:
346 raise NotImplementedError
347 #
348 if value_fits_ulong:
349 value = misc.read_raw_ulong_data(cdata, ctype.size)
350 valuemask = (r_uint(1) << self.bitsize) - 1
351 value = (value >> self.bitshift) & valuemask
352 if value_fits_long:
353 return space.newint(intmask(value))
354 else:
355 return space.newint(value) # uint => wrapped long object
356 else:
357 value = misc.read_raw_unsigned_data(cdata, ctype.size)
358 valuemask = (r_ulonglong(1) << self.bitsize) - 1
359 value = (value >> self.bitshift) & valuemask
360 return space.newint(value) # ulonglong => wrapped long object
361
362 def convert_bitfield_from_object(self, cdata, w_ob):
363 ctype = self.ctype
364 space = ctype.space
365 #
366 value = misc.as_long_long(space, w_ob)
367 if isinstance(ctype, ctypeprim.W_CTypePrimitiveSigned):
368 is_signed = True
369 fmin = -(r_longlong(1) << (self.bitsize - 1))
370 fmax = (r_longlong(1) << (self.bitsize - 1)) - 1
371 if fmax == 0:
372 fmax = 1 # special case to let "int x:1" receive "1"
373 else:
374 is_signed = False
375 fmin = r_longlong(0)
376 fmax = r_longlong((r_ulonglong(1) << self.bitsize) - 1)
377 if value < fmin or value > fmax:
378 raise oefmt(space.w_OverflowError,
379 "value %d outside the range allowed by the bit field "
380 "width: %d <= x <= %d", value, fmin, fmax)
381 rawmask = ((r_ulonglong(1) << self.bitsize) - 1) << self.bitshift
382 rawvalue = r_ulonglong(value) << self.bitshift
383 rawfielddata = misc.read_raw_unsigned_data(cdata, ctype.size)
384 rawfielddata = (rawfielddata & ~rawmask) | (rawvalue & rawmask)
385 if is_signed:
386 misc.write_raw_signed_data(cdata, rawfielddata, ctype.size)
387 else:
388 misc.write_raw_unsigned_data(cdata, rawfielddata, ctype.size)
389
390
391 W_CField.typedef = TypeDef(
392 '_cffi_backend.CField',
393 type = interp_attrproperty_w('ctype', W_CField),
394 offset = interp_attrproperty('offset', W_CField, wrapfn="newint"),
395 bitshift = interp_attrproperty('bitshift', W_CField, wrapfn="newint"),
396 bitsize = interp_attrproperty('bitsize', W_CField, wrapfn="newint"),
397 flags = interp_attrproperty('flags', W_CField, wrapfn="newint"),
398 )
399 W_CField.typedef.acceptable_as_base_class = False