Debian Codegraph @

pypy/module/_rawffi/alt/interp_struct.py

raw symbols SCIP
1 from rpython.rtyper.lltypesystem import lltype, rffi
2 from rpython.rlib import clibffi
3 from rpython.rlib import libffi
4 from rpython.rlib import jit
5 from rpython.rlib.rgc import must_be_light_finalizer
6 from rpython.rlib.rarithmetic import r_uint, r_ulonglong, intmask
7 from pypy.interpreter.baseobjspace import W_Root
8 from pypy.interpreter.typedef import TypeDef, interp_attrproperty, interp_attrproperty_w
9 from pypy.interpreter.gateway import interp2app, unwrap_spec
10 from pypy.interpreter.error import OperationError, oefmt
11 from pypy.module._rawffi.alt.interp_ffitype import W_FFIType
12 from pypy.module._rawffi.alt.type_converter import FromAppLevelConverter, ToAppLevelConverter
13
14
15 class W_Field(W_Root):
16 def __init__(self, name, w_ffitype):
17 self.name = name
18 self.w_ffitype = w_ffitype
19 self.offset = -1
20
21 def __repr__(self):
22 return '<Field %s %s>' % (self.name, self.w_ffitype.name)
23
24 @unwrap_spec(name='text')
25 def descr_new_field(space, w_type, name, w_ffitype):
26 w_ffitype = space.interp_w(W_FFIType, w_ffitype)
27 return W_Field(name, w_ffitype)
28
29 W_Field.typedef = TypeDef(
30 'Field',
31 __new__ = interp2app(descr_new_field),
32 name = interp_attrproperty('name', W_Field,
33 wrapfn="newtext_or_none"),
34 ffitype = interp_attrproperty_w('w_ffitype', W_Field),
35 offset = interp_attrproperty('offset', W_Field,
36 wrapfn="newint"),
37 )
38
39
40 # ==============================================================================
41
42 class FFIStructOwner(object):
43 """
44 The only job of this class is to stay outside of the reference cycle
45 W__StructDescr -> W_FFIType -> W__StructDescr and free the ffistruct
46 """
47
48 def __init__(self, ffistruct):
49 self.ffistruct = ffistruct
50
51 @must_be_light_finalizer
52 def __del__(self):
53 if self.ffistruct:
54 lltype.free(self.ffistruct, flavor='raw', track_allocation=True)
55
56
57 class W__StructDescr(W_Root):
58
59 def __init__(self, name):
60 self.w_ffitype = W_FFIType('struct %s' % name, clibffi.FFI_TYPE_NULL,
61 w_structdescr=self)
62 self.fields_w = None
63 self.name2w_field = {}
64 self._ffistruct_owner = None
65
66 def define_fields(self, space, w_fields):
67 if self.fields_w is not None:
68 raise oefmt(space.w_ValueError,
69 "%s's fields has already been defined",
70 self.w_ffitype.name)
71 fields_w = space.fixedview(w_fields)
72 # note that the fields_w returned by compute_size_and_alignement has a
73 # different annotation than the original: list(W_Root) vs list(W_Field)
74 size, alignment, fields_w = compute_size_and_alignement(space, fields_w)
75 self.fields_w = fields_w
76 field_types = [] # clibffi's types
77 for w_field in fields_w:
78 field_types.append(w_field.w_ffitype.get_ffitype())
79 self.name2w_field[w_field.name] = w_field
80 #
81 # on CPython, the FFIStructOwner might go into gc.garbage and thus the
82 # __del__ never be called. Thus, we don't track the allocation of the
83 # malloc done inside this function, else the leakfinder might complain
84 ffistruct = clibffi.make_struct_ffitype_e(size, alignment, field_types,
85 track_allocation=False)
86 self.w_ffitype.set_ffitype(ffistruct.ffistruct)
87 self._ffistruct_owner = FFIStructOwner(ffistruct)
88
89 def check_complete(self, space):
90 if self.fields_w is None:
91 raise oefmt(space.w_ValueError,
92 "%s has an incomplete type", self.w_ffitype.name)
93
94 def allocate(self, space):
95 self.check_complete(space)
96 return W__StructInstance(self)
97
98 @unwrap_spec(addr=int)
99 def fromaddress(self, space, addr):
100 self.check_complete(space)
101 rawmem = rffi.cast(rffi.VOIDP, addr)
102 return W__StructInstance(self, allocate=False, autofree=True, rawmem=rawmem)
103
104 def get_type_and_offset_for_field(self, space, w_name):
105 name = space.text_w(w_name)
106 try:
107 return self._get_type_and_offset_for_field(space, name)
108 except KeyError:
109 raise OperationError(space.w_AttributeError, w_name)
110
111 @jit.elidable_promote('0')
112 def _get_type_and_offset_for_field(self, space, name):
113 w_field = self.name2w_field[name]
114 return w_field.w_ffitype, w_field.offset
115
116
117
118 @unwrap_spec(name='text')
119 def descr_new_structdescr(space, w_type, name, w_fields=None):
120 descr = W__StructDescr(name)
121 if not space.is_none(w_fields):
122 descr.define_fields(space, w_fields)
123 return descr
124
125 def round_up(size, alignment):
126 return (size + alignment - 1) & -alignment
127
128 def compute_size_and_alignement(space, fields_w):
129 size = 0
130 alignment = 1
131 fields_w2 = []
132 for w_field in fields_w:
133 w_field = space.interp_w(W_Field, w_field)
134 fieldsize = w_field.w_ffitype.sizeof()
135 fieldalignment = w_field.w_ffitype.get_alignment()
136 alignment = max(alignment, fieldalignment)
137 size = round_up(size, fieldalignment)
138 w_field.offset = size
139 size += fieldsize
140 fields_w2.append(w_field)
141 #
142 size = round_up(size, alignment)
143 return size, alignment, fields_w2
144
145
146
147 W__StructDescr.typedef = TypeDef(
148 '_StructDescr',
149 __new__ = interp2app(descr_new_structdescr),
150 ffitype = interp_attrproperty_w('w_ffitype', W__StructDescr),
151 define_fields = interp2app(W__StructDescr.define_fields),
152 allocate = interp2app(W__StructDescr.allocate),
153 fromaddress = interp2app(W__StructDescr.fromaddress),
154 )
155
156
157 # ==============================================================================
158
159 NULL = lltype.nullptr(rffi.VOIDP.TO)
160
161 class W__StructInstance(W_Root):
162
163 _immutable_fields_ = ['structdescr', 'rawmem']
164
165 def __init__(self, structdescr, allocate=True, autofree=True, rawmem=NULL):
166 self.structdescr = structdescr
167 self.autofree = autofree
168 if allocate:
169 assert not rawmem
170 assert autofree
171 size = structdescr.w_ffitype.sizeof()
172 self.rawmem = lltype.malloc(rffi.VOIDP.TO, size, flavor='raw',
173 zero=True, add_memory_pressure=True)
174 else:
175 self.rawmem = rawmem
176
177 @must_be_light_finalizer
178 def __del__(self):
179 if self.autofree and self.rawmem:
180 lltype.free(self.rawmem, flavor='raw')
181 self.rawmem = lltype.nullptr(rffi.VOIDP.TO)
182
183 def getaddr(self, space):
184 addr = rffi.cast(lltype.Unsigned, self.rawmem)
185 return space.newint(addr)
186
187 def getfield(self, space, w_name):
188 w_ffitype, offset = self.structdescr.get_type_and_offset_for_field(
189 space, w_name)
190 field_getter = GetFieldConverter(space, self.rawmem, offset)
191 return field_getter.do_and_wrap(w_ffitype)
192
193 def setfield(self, space, w_name, w_value):
194 w_ffitype, offset = self.structdescr.get_type_and_offset_for_field(
195 space, w_name)
196 field_setter = SetFieldConverter(space, self.rawmem, offset)
197 field_setter.unwrap_and_do(w_ffitype, w_value)
198
199
200 class GetFieldConverter(ToAppLevelConverter):
201 """
202 A converter used by W__StructInstance to get a field from the struct and
203 wrap it to the correct app-level type.
204 """
205
206 def __init__(self, space, rawmem, offset):
207 self.space = space
208 self.rawmem = rawmem
209 self.offset = offset
210
211 def get_longlong(self, w_ffitype):
212 return libffi.struct_getfield_longlong(libffi.types.slonglong,
213 self.rawmem, self.offset)
214
215 def get_ulonglong(self, w_ffitype):
216 longlongval = libffi.struct_getfield_longlong(libffi.types.ulonglong,
217 self.rawmem, self.offset)
218 return r_ulonglong(longlongval)
219
220
221 def get_signed(self, w_ffitype):
222 return libffi.struct_getfield_int(w_ffitype.get_ffitype(),
223 self.rawmem, self.offset)
224
225 def get_unsigned(self, w_ffitype):
226 value = libffi.struct_getfield_int(w_ffitype.get_ffitype(),
227 self.rawmem, self.offset)
228 return r_uint(value)
229
230 get_unsigned_which_fits_into_a_signed = get_signed
231 get_pointer = get_unsigned
232
233 def get_char(self, w_ffitype):
234 intval = libffi.struct_getfield_int(w_ffitype.get_ffitype(),
235 self.rawmem, self.offset)
236 return rffi.cast(rffi.UCHAR, intval)
237
238 def get_unichar(self, w_ffitype):
239 intval = libffi.struct_getfield_int(w_ffitype.get_ffitype(),
240 self.rawmem, self.offset)
241 return rffi.cast(rffi.WCHAR_T, intval)
242
243 def get_float(self, w_ffitype):
244 return libffi.struct_getfield_float(w_ffitype.get_ffitype(),
245 self.rawmem, self.offset)
246
247 def get_singlefloat(self, w_ffitype):
248 return libffi.struct_getfield_singlefloat(w_ffitype.get_ffitype(),
249 self.rawmem, self.offset)
250
251 def get_struct(self, w_ffitype, w_structdescr):
252 assert isinstance(w_structdescr, W__StructDescr)
253 rawmem = rffi.cast(rffi.CCHARP, self.rawmem)
254 innermem = rffi.cast(rffi.VOIDP, rffi.ptradd(rawmem, self.offset))
255 # we return a reference to the inner struct, not a copy
256 # autofree=False because it's still owned by the parent struct
257 return W__StructInstance(w_structdescr, allocate=False, autofree=False,
258 rawmem=innermem)
259
260 ## def get_void(self, w_ffitype):
261 ## ...
262
263
264 class SetFieldConverter(FromAppLevelConverter):
265 """
266 A converter used by W__StructInstance to convert an app-level object to
267 the corresponding low-level value and set the field of a structure.
268 """
269
270 def __init__(self, space, rawmem, offset):
271 self.space = space
272 self.rawmem = rawmem
273 self.offset = offset
274
275 def handle_signed(self, w_ffitype, w_obj, intval):
276 libffi.struct_setfield_int(w_ffitype.get_ffitype(), self.rawmem, self.offset,
277 intval)
278
279 def handle_unsigned(self, w_ffitype, w_obj, uintval):
280 libffi.struct_setfield_int(w_ffitype.get_ffitype(), self.rawmem, self.offset,
281 intmask(uintval))
282
283 handle_pointer = handle_signed
284 handle_char = handle_signed
285 handle_unichar = handle_signed
286
287 def handle_longlong(self, w_ffitype, w_obj, longlongval):
288 libffi.struct_setfield_longlong(w_ffitype.get_ffitype(),
289 self.rawmem, self.offset, longlongval)
290
291 def handle_float(self, w_ffitype, w_obj, floatval):
292 libffi.struct_setfield_float(w_ffitype.get_ffitype(),
293 self.rawmem, self.offset, floatval)
294
295 def handle_singlefloat(self, w_ffitype, w_obj, singlefloatval):
296 libffi.struct_setfield_singlefloat(w_ffitype.get_ffitype(),
297 self.rawmem, self.offset, singlefloatval)
298
299 def handle_struct(self, w_ffitype, w_structinstance):
300 rawmem = rffi.cast(rffi.CCHARP, self.rawmem)
301 dst = rffi.cast(rffi.VOIDP, rffi.ptradd(rawmem, self.offset))
302 src = rffi.cast(rffi.CONST_VOIDP, w_structinstance.rawmem)
303 length = w_ffitype.sizeof()
304 rffi.c_memcpy(dst, src, length)
305
306 ## def handle_char_p(self, w_ffitype, w_obj, strval):
307 ## ...
308
309 ## def handle_unichar_p(self, w_ffitype, w_obj, unicodeval):
310 ## ...
311
312
313
314
315 W__StructInstance.typedef = TypeDef(
316 '_StructInstance',
317 getaddr = interp2app(W__StructInstance.getaddr),
318 getfield = interp2app(W__StructInstance.getfield),
319 setfield = interp2app(W__StructInstance.setfield),
320 )