Debian Codegraph @

pypy/module/_rawffi/structure.py

raw symbols SCIP
1 """ Interpreter-level implementation of structure, exposing ll-structure
2 to app-level with apropriate interface
3 """
4
5 from pypy.interpreter.gateway import interp2app, unwrap_spec
6 from pypy.interpreter.typedef import interp_attrproperty, interp_attrproperty_w
7 from pypy.interpreter.typedef import TypeDef, GetSetProperty
8 from pypy.interpreter.error import OperationError, oefmt
9 from pypy.module._rawffi.interp_rawffi import segfault_exception, _MS_WINDOWS
10 from pypy.module._rawffi.interp_rawffi import W_DataShape, W_DataInstance
11 from pypy.module._rawffi.interp_rawffi import wrap_value, unwrap_value
12 from pypy.module._rawffi.interp_rawffi import unpack_shape_with_length
13 from pypy.module._rawffi.interp_rawffi import LL_TYPEMAP
14 from pypy.module._rawffi.interp_rawffi import unroll_letters_for_numbers
15 from pypy.module._rawffi.interp_rawffi import size_alignment
16 from pypy.module._rawffi.interp_rawffi import read_ptr, write_ptr
17 from rpython.rlib import clibffi, rgc, rutf8
18 from rpython.rlib.rarithmetic import intmask, signedtype, r_uint, \
19 r_ulonglong
20 from rpython.rtyper.lltypesystem import lltype, rffi
21 from rpython.rlib.objectmodel import specialize
22 import sys
23
24 IS_BIG_ENDIAN = sys.byteorder == 'big'
25
26
27
28 def unpack_fields(space, w_fields):
29 fields_w = space.unpackiterable(w_fields)
30 fields = []
31 for w_tup in fields_w:
32 l_w = space.unpackiterable(w_tup)
33 len_l = len(l_w)
34
35 if len_l < 2 or len_l > 3:
36 raise oefmt(space.w_ValueError,
37 "Expected list of 2- or 3-size tuples")
38
39 try:
40 name = space.text_w(l_w[0])
41 except OperationError:
42 raise oefmt(space.w_TypeError,
43 "structure field name must be string not %T", l_w[0])
44 tp = unpack_shape_with_length(space, l_w[1])
45
46 if len_l == 3:
47 for c in unroll_letters_for_numbers:
48 if c == tp.itemcode:
49 break
50 else:
51 raise oefmt(space.w_TypeError,
52 "bit fields not allowed for type")
53 bitsize = space.int_w(l_w[2])
54 if bitsize <= 0 or bitsize > tp.size * 8:
55 raise oefmt(space.w_ValueError,
56 "number of bits invalid for bit field")
57 else:
58 bitsize = 0
59
60 fields.append((name, tp, bitsize))
61 return fields
62
63 def round_up(size, alignment):
64 return (size + alignment - 1) & -alignment
65
66 NO_BITFIELD, NEW_BITFIELD, CONT_BITFIELD, EXPAND_BITFIELD = range(4)
67
68 def size_alignment_pos(fields, is_union=False, pack=0):
69 size = 0
70 alignment = 1
71 pos = []
72 bitsizes = []
73 bitoffset = 0
74 has_bitfield = False
75 last_size = 0
76
77 for fieldname, fieldtype, bitsize in fields:
78 # fieldtype is a W_Array
79 fieldsize = fieldtype.size
80 fieldalignment = fieldtype.alignment
81 if pack:
82 fieldalignment = min(fieldalignment, pack)
83 alignment = max(alignment, fieldalignment)
84
85 if not bitsize:
86 # not a bit field
87 field_type = NO_BITFIELD
88 last_size = 0
89 bitoffset = 0
90 elif (last_size and # we have a bitfield open
91 (not _MS_WINDOWS or fieldsize * 8 == last_size) and
92 fieldsize * 8 <= last_size and
93 bitoffset + bitsize <= last_size):
94 # continue bit field
95 field_type = CONT_BITFIELD
96 elif (not _MS_WINDOWS and
97 last_size and # we have a bitfield open
98 fieldsize * 8 >= last_size and
99 bitoffset + bitsize <= fieldsize * 8):
100 # expand bit field
101 field_type = EXPAND_BITFIELD
102 else:
103 # start new bitfield
104 field_type = NEW_BITFIELD
105 has_bitfield = True
106 bitoffset = 0
107 last_size = fieldsize * 8
108
109 if is_union:
110 pos.append(0)
111 bitsizes.append(fieldsize)
112 size = max(size, fieldsize)
113 else:
114 if field_type == NO_BITFIELD:
115 # the usual case
116 size = round_up(size, fieldalignment)
117 pos.append(size)
118 size += intmask(fieldsize)
119 bitsizes.append(fieldsize)
120 elif field_type == NEW_BITFIELD:
121 if IS_BIG_ENDIAN:
122 off = last_size - bitoffset - bitsize
123 else:
124 off = bitoffset
125 bitsizes.append((bitsize << 16) + off)
126 bitoffset = bitsize
127 size = round_up(size, fieldalignment)
128 pos.append(size)
129 size += fieldsize
130 elif field_type == CONT_BITFIELD:
131 if IS_BIG_ENDIAN:
132 off = last_size - bitoffset - bitsize
133 else:
134 off = bitoffset
135 bitsizes.append((bitsize << 16) + off)
136 bitoffset += bitsize
137 # offset is already updated for the NEXT field
138 pos.append(size - fieldsize)
139 elif field_type == EXPAND_BITFIELD:
140 size += fieldsize - last_size / 8
141 last_size = fieldsize * 8
142 if IS_BIG_ENDIAN:
143 off = last_size - bitoffset - bitsize
144 else:
145 off = bitoffset
146 bitsizes.append((bitsize << 16) + off)
147 bitoffset += bitsize
148 # offset is already updated for the NEXT field
149 pos.append(size - fieldsize)
150
151 if not has_bitfield:
152 bitsizes = None
153 size = round_up(size, alignment)
154 return size, alignment, pos, bitsizes
155
156
157 class W_Structure(W_DataShape):
158 def __init__(self, space, fields, size, alignment, is_union=False, pack=0):
159 name_to_index = {}
160 if fields is not None:
161 for i in range(len(fields)):
162 name, tp, bitsize = fields[i]
163 if name in name_to_index:
164 raise oefmt(space.w_ValueError,
165 "duplicate field name %s", name)
166 try:
167 rutf8.check_ascii(name)
168 except rutf8.CheckError:
169 raise oefmt(space.w_TypeError, 'non-ascii field name')
170 name_to_index[name] = i
171 size, alignment, pos, bitsizes = size_alignment_pos(
172 fields, is_union, pack)
173 else: # opaque case
174 fields = []
175 pos = []
176 bitsizes = None
177 self.fields = fields
178 self.size = size
179 self.alignment = alignment
180 self.ll_positions = pos
181 self.ll_bitsizes = bitsizes
182 self.name_to_index = name_to_index
183
184 def allocate(self, space, length, autofree=False):
185 # length is ignored!
186 if autofree:
187 return W_StructureInstanceAutoFree(space, self)
188 return W_StructureInstance(space, self, 0)
189
190 def getindex(self, space, attr):
191 try:
192 return self.name_to_index[attr]
193 except KeyError:
194 raise oefmt(space.w_AttributeError,
195 "C Structure has no attribute %s", attr)
196
197 @unwrap_spec(autofree=int)
198 def descr_call(self, space, autofree=False):
199 return self.allocate(space, 1, bool(autofree))
200
201 def descr_repr(self, space):
202 fieldnames = ' '.join(["'%s'" % name for name, _, _ in self.fields])
203 return space.newtext("<_rawffi.Structure %s (%d, %d)>" % (fieldnames,
204 self.size,
205 self.alignment))
206
207 @unwrap_spec(address=r_uint)
208 def fromaddress(self, space, address):
209 return W_StructureInstance(space, self, address)
210
211 @unwrap_spec(attr='text')
212 def descr_fieldoffset(self, space, attr):
213 index = self.getindex(space, attr)
214 return space.newint(self.ll_positions[index])
215
216 @unwrap_spec(attr='text')
217 def descr_fieldsize(self, space, attr):
218 index = self.getindex(space, attr)
219 if self.ll_bitsizes and index < len(self.ll_bitsizes):
220 return space.newint(self.ll_bitsizes[index])
221 else:
222 return space.newint(self.fields[index][1].size)
223
224 # get the corresponding ffi_type
225 ffi_struct = lltype.nullptr(clibffi.FFI_STRUCT_P.TO)
226
227 def get_basic_ffi_type(self):
228 if not self.ffi_struct:
229 # Repeated fields are delicate. Consider for example
230 # struct { int a[5]; }
231 # or struct { struct {int x;} a[5]; }
232 # Seeing no corresponding doc in clibffi, let's just repeat
233 # the field 5 times...
234 fieldtypes = []
235 for name, tp, bitsize in self.fields:
236 basic_ffi_type = tp.get_basic_ffi_type()
237 basic_size, _ = size_alignment(basic_ffi_type)
238 total_size = tp.size
239 count = 0
240 while count + basic_size <= total_size:
241 fieldtypes.append(basic_ffi_type)
242 count += basic_size
243 if basic_size == 0: # corner case. get out of this infinite
244 break # loop after 1 iteration ("why not")
245 self.ffi_struct = clibffi.make_struct_ffitype_e(self.size,
246 self.alignment,
247 fieldtypes)
248 return self.ffi_struct.ffistruct
249
250 @rgc.must_be_light_finalizer
251 def __del__(self):
252 if self.ffi_struct:
253 lltype.free(self.ffi_struct, flavor='raw')
254
255
256 @unwrap_spec(union=int, pack=int)
257 def descr_new_structure(space, w_type, w_shapeinfo, union=0, pack=0):
258 union = bool(union)
259 if pack < 0:
260 raise oefmt(space.w_ValueError,
261 "_pack_ must be a non-negative integer")
262
263 if space.isinstance_w(w_shapeinfo, space.w_tuple):
264 w_size, w_alignment = space.fixedview(w_shapeinfo, expected_length=2)
265 S = W_Structure(space, None, space.int_w(w_size),
266 space.int_w(w_alignment), union)
267 else:
268 fields = unpack_fields(space, w_shapeinfo)
269 S = W_Structure(space, fields, 0, 0, union, pack)
270 return S
271
272 W_Structure.typedef = TypeDef(
273 'Structure',
274 __new__ = interp2app(descr_new_structure),
275 __call__ = interp2app(W_Structure.descr_call),
276 __repr__ = interp2app(W_Structure.descr_repr),
277 fromaddress = interp2app(W_Structure.fromaddress),
278 size = interp_attrproperty('size', W_Structure,
279 wrapfn="newint"),
280 alignment = interp_attrproperty('alignment', W_Structure,
281 wrapfn="newint"),
282 fieldoffset = interp2app(W_Structure.descr_fieldoffset),
283 fieldsize = interp2app(W_Structure.descr_fieldsize),
284 size_alignment = interp2app(W_Structure.descr_size_alignment),
285 get_ffi_type = interp2app(W_Structure.descr_get_ffi_type),
286 )
287 W_Structure.typedef.acceptable_as_base_class = False
288
289 def LOW_BIT(x):
290 return x & 0xFFFF
291
292 def NUM_BITS(x):
293 return x >> 16
294
295 @specialize.arg(1)
296 def BIT_MASK(x, ll_t):
297 if ll_t is lltype.SignedLongLong or ll_t is lltype.UnsignedLongLong:
298 one = r_ulonglong(1)
299 else:
300 one = r_uint(1)
301 # to avoid left shift by x == sizeof(ll_t)
302 return (((one << (x - 1)) - 1) << 1) + 1
303
304 @specialize.argtype(2)
305 def push_field(self, num, value):
306 ptr = rffi.ptradd(self.ll_buffer, self.shape.ll_positions[num])
307 TP = lltype.typeOf(value)
308 # Handle bitfields
309 for c in unroll_letters_for_numbers:
310 if LL_TYPEMAP[c] is TP and self.shape.ll_bitsizes:
311 # Modify the current value with the bitfield changed
312 bitsize = self.shape.ll_bitsizes[num]
313 numbits = NUM_BITS(bitsize)
314 if numbits:
315 lowbit = LOW_BIT(bitsize)
316 bitmask = BIT_MASK(numbits, TP)
317 masktype = lltype.typeOf(bitmask)
318 value = rffi.cast(masktype, value)
319 current = rffi.cast(masktype, read_ptr(ptr, 0, TP))
320 current &= ~(bitmask << lowbit)
321 current |= (value & bitmask) << lowbit
322 value = rffi.cast(TP, current)
323 break
324 write_ptr(ptr, 0, value)
325
326 @specialize.arg(2)
327 def cast_pos(self, i, ll_t):
328 pos = rffi.ptradd(self.ll_buffer, self.shape.ll_positions[i])
329 value = read_ptr(pos, 0, ll_t)
330 # Handle bitfields
331 for c in unroll_letters_for_numbers:
332 if LL_TYPEMAP[c] is ll_t and self.shape.ll_bitsizes:
333 bitsize = self.shape.ll_bitsizes[i]
334 numbits = NUM_BITS(bitsize)
335 if numbits:
336 lowbit = LOW_BIT(bitsize)
337 bitmask = BIT_MASK(numbits, ll_t)
338 masktype = lltype.typeOf(bitmask)
339 value = rffi.cast(masktype, value)
340 value >>= lowbit
341 value &= bitmask
342 if ll_t is lltype.Bool or signedtype(ll_t._type):
343 sign = (value >> (numbits - 1)) & 1
344 if sign:
345 value -= bitmask + 1
346 value = rffi.cast(ll_t, value)
347 break
348 return value
349
350 class W_StructureInstance(W_DataInstance):
351 def __init__(self, space, shape, address):
352 W_DataInstance.__init__(self, space, shape.size, address)
353 self.shape = shape
354
355 def descr_repr(self, space):
356 addr = rffi.cast(lltype.Unsigned, self.ll_buffer)
357 return space.newtext("<_rawffi struct %x>" % (addr,))
358
359 @unwrap_spec(attr='text')
360 def getattr(self, space, attr):
361 if not self.ll_buffer:
362 raise segfault_exception(space, "accessing NULL pointer")
363 i = self.shape.getindex(space, attr)
364 _, tp, _ = self.shape.fields[i]
365 return wrap_value(space, cast_pos, self, i, tp.itemcode)
366
367 @unwrap_spec(attr='text')
368 def setattr(self, space, attr, w_value):
369 if not self.ll_buffer:
370 raise segfault_exception(space, "accessing NULL pointer")
371 i = self.shape.getindex(space, attr)
372 _, tp, _ = self.shape.fields[i]
373 unwrap_value(space, push_field, self, i, tp.itemcode, w_value)
374
375 @unwrap_spec(attr='text')
376 def descr_fieldaddress(self, space, attr):
377 i = self.shape.getindex(space, attr)
378 ptr = rffi.ptradd(self.ll_buffer, self.shape.ll_positions[i])
379 return space.newint(rffi.cast(lltype.Unsigned, ptr))
380
381 def getrawsize(self):
382 return self.shape.size
383
384
385 W_StructureInstance.typedef = TypeDef(
386 'StructureInstance', None, None, "read-write",
387 __repr__ = interp2app(W_StructureInstance.descr_repr),
388 __getattr__ = interp2app(W_StructureInstance.getattr),
389 __setattr__ = interp2app(W_StructureInstance.setattr),
390 buffer = GetSetProperty(W_StructureInstance.getbuffer),
391 free = interp2app(W_StructureInstance.free),
392 shape = interp_attrproperty_w('shape', W_StructureInstance),
393 byptr = interp2app(W_StructureInstance.byptr),
394 fieldaddress= interp2app(W_StructureInstance.descr_fieldaddress),
395 )
396 W_StructureInstance.typedef.acceptable_as_base_class = False
397
398 class W_StructureInstanceAutoFree(W_StructureInstance):
399 def __init__(self, space, shape):
400 W_StructureInstance.__init__(self, space, shape, 0)
401
402 @rgc.must_be_light_finalizer
403 def __del__(self):
404 if self.ll_buffer:
405 self._free()
406
407 W_StructureInstanceAutoFree.typedef = TypeDef(
408 'StructureInstanceAutoFree', None, None, "read-write",
409 __repr__ = interp2app(W_StructureInstance.descr_repr),
410 __getattr__ = interp2app(W_StructureInstance.getattr),
411 __setattr__ = interp2app(W_StructureInstance.setattr),
412 buffer = GetSetProperty(W_StructureInstance.getbuffer),
413 shape = interp_attrproperty_w('shape', W_StructureInstance),
414 byptr = interp2app(W_StructureInstance.byptr),
415 fieldaddress= interp2app(W_StructureInstance.descr_fieldaddress),
416 )
417 W_StructureInstanceAutoFree.typedef.acceptable_as_base_class = False