Debian Codegraph @

pypy/module/cpyext/pyobject.py

raw symbols SCIP
1 import sys
2
3 from pypy.interpreter.error import OperationError, oefmt
4 from pypy.interpreter.baseobjspace import W_Root, SpaceCache
5 from rpython.rtyper.lltypesystem import rffi, lltype
6 from rpython.rtyper.extregistry import ExtRegistryEntry
7 from pypy.module.cpyext.api import (
8 cpython_api, bootstrap_function, PyObject, PyObjectP, ADDR,
9 CANNOT_FAIL, Py_TPFLAGS_HEAPTYPE, PyTypeObjectPtr, is_PyObject,
10 PyVarObject, Py_ssize_t, init_function, cts)
11 from pypy.module.cpyext.state import State
12 from pypy.objspace.std.typeobject import W_TypeObject
13 from pypy.objspace.std.noneobject import W_NoneObject
14 from pypy.objspace.std.boolobject import W_BoolObject
15 from pypy.objspace.std.objectobject import W_ObjectObject
16 from rpython.rlib.objectmodel import specialize, we_are_translated
17 from rpython.rlib.objectmodel import keepalive_until_here
18 from rpython.rtyper.annlowlevel import llhelper, cast_instance_to_base_ptr
19 from rpython.rlib import rawrefcount, jit
20 from rpython.rlib.debug import ll_assert, fatalerror, check_annotation
21
22
23 #________________________________________________________
24 # type description
25
26 class W_BaseCPyObject(W_ObjectObject):
27 """ A subclass of W_ObjectObject that has one field for directly storing
28 the link from the w_obj to the cpy ref. This is only used for C-defined
29 types. """
30
31
32 def check_true(s_arg, bookeeper):
33 assert s_arg.const is True
34
35 def w_root_as_pyobj(w_obj, space):
36 # make sure that translation crashes if we see this while translating
37 # without cpyext
38 check_annotation(space.config.objspace.usemodules.cpyext, check_true)
39 # default implementation of _cpyext_as_pyobj
40 return rawrefcount.from_obj(PyObject, w_obj)
41
42 def w_root_attach_pyobj(w_obj, space, py_obj):
43 check_annotation(space.config.objspace.usemodules.cpyext, check_true)
44 assert space.config.objspace.usemodules.cpyext
45 # default implementation of _cpyext_attach_pyobj
46 rawrefcount.create_link_pypy(w_obj, py_obj)
47
48
49 def add_direct_pyobj_storage(cls):
50 """ Add the necessary methods to a class to store a reference to the py_obj
51 on its instances directly. """
52
53 cls._cpy_ref = lltype.nullptr(PyObject.TO)
54
55 def _cpyext_as_pyobj(self, space):
56 return self._cpy_ref
57 cls._cpyext_as_pyobj = _cpyext_as_pyobj
58
59 def _cpyext_attach_pyobj(self, space, py_obj):
60 self._cpy_ref = py_obj
61 rawrefcount.create_link_pypy(self, py_obj)
62 cls._cpyext_attach_pyobj = _cpyext_attach_pyobj
63
64 add_direct_pyobj_storage(W_BaseCPyObject)
65 add_direct_pyobj_storage(W_TypeObject)
66 add_direct_pyobj_storage(W_NoneObject)
67 add_direct_pyobj_storage(W_BoolObject)
68
69
70 class BaseCpyTypedescr(object):
71 basestruct = PyObject.TO
72 W_BaseObject = W_ObjectObject
73
74 def get_dealloc(self, space):
75 state = space.fromcache(State)
76 return state.C._PyPy_subtype_dealloc
77
78 # CCC port to C
79 def allocate(self, space, w_type, itemcount=0, immortal=False, itemsize=-1):
80 # typically called from PyType_GenericAlloc via typedescr.allocate
81 # this returns a PyObject with ob_refcnt == 1.
82
83 pytype = as_pyobj(space, w_type)
84 pytype = rffi.cast(PyTypeObjectPtr, pytype)
85 assert pytype
86 # Don't increase refcount for non-heaptypes
87 flags = rffi.cast(lltype.Signed, pytype.c_tp_flags)
88 if flags & Py_TPFLAGS_HEAPTYPE:
89 incref(space, pytype)
90
91 size = pytype.c_tp_basicsize
92 if itemsize < 0:
93 itemsize = pytype.c_tp_itemsize
94 if itemsize:
95 size += itemcount * itemsize
96 assert size >= rffi.sizeof(PyObject.TO)
97 buf = lltype.malloc(rffi.VOIDP.TO, size,
98 flavor='raw', zero=True,
99 add_memory_pressure=True, immortal=immortal)
100 pyobj = rffi.cast(PyObject, buf)
101 if itemsize or space.issubtype_w(w_type, space.w_list):
102 pyvarobj = rffi.cast(PyVarObject, pyobj)
103 pyvarobj.c_ob_size = itemcount
104 pyobj.c_ob_refcnt = 1
105 #pyobj.c_ob_pypy_link should get assigned very quickly
106 pyobj.c_ob_type = pytype
107 return pyobj
108
109 def attach(self, space, pyobj, w_obj, w_userdata=None):
110 pass
111
112 def realize(self, space, obj):
113 w_type = from_ref(space, rffi.cast(PyObject, obj.c_ob_type))
114 assert isinstance(w_type, W_TypeObject)
115 try:
116 if w_type.flag_cpytype:
117 w_obj = space.allocate_instance(W_BaseCPyObject, w_type)
118 else:
119 w_obj = space.allocate_instance(self.W_BaseObject, w_type)
120 except OperationError as e:
121 if e.match(space, space.w_TypeError):
122 raise oefmt(space.w_SystemError,
123 "cpyext: don't know how to make a '%N' object "
124 "from a PyObject",
125 w_type)
126 raise
127 track_reference(space, obj, w_obj)
128 return w_obj
129
130 typedescr_cache = {}
131
132 def make_typedescr(typedef, **kw):
133 """NOT_RPYTHON
134
135 basestruct: The basic structure to allocate
136 alloc : allocate and basic initialization of a raw PyObject
137 attach : Function called to tie a raw structure to a pypy object
138 realize : Function called to create a pypy object from a raw struct
139 dealloc : a @slot_function(), similar to PyObject_dealloc
140 """
141
142 tp_basestruct = kw.pop('basestruct', PyObject.TO)
143 tp_alloc = kw.pop('alloc', None)
144 tp_attach = kw.pop('attach', None)
145 tp_realize = kw.pop('realize', None)
146 tp_dealloc = kw.pop('dealloc', None)
147 assert not kw, "Extra arguments to make_typedescr"
148
149 null_dealloc = lltype.nullptr(lltype.FuncType([PyObject], lltype.Void))
150 assert not isinstance(tp_basestruct, lltype.Ptr), "should pass .TO"
151
152 class CpyTypedescr(BaseCpyTypedescr):
153 basestruct = tp_basestruct
154
155 if tp_alloc:
156 def allocate(self, space, w_type, itemcount=0, immortal=False, itemsize=-1):
157 return tp_alloc(self, space, w_type, itemcount)
158
159 if hasattr(tp_dealloc, 'api_func'):
160 def get_dealloc(self, space):
161 return tp_dealloc.api_func.get_llhelper(space)
162 elif tp_dealloc:
163 def get_dealloc(self, space):
164 return tp_dealloc
165
166 if tp_attach:
167 def attach(self, space, pyobj, w_obj, w_userdata=None):
168 tp_attach(space, pyobj, w_obj, w_userdata)
169
170 if tp_realize:
171 def realize(self, space, ref):
172 return tp_realize(space, ref)
173 if typedef:
174 CpyTypedescr.__name__ = "CpyTypedescr_%s" % (typedef.name,)
175
176 typedescr_cache[typedef] = CpyTypedescr()
177
178 @bootstrap_function
179 def init_pyobject(space):
180 # typedescr for the 'object' type
181 state = space.fromcache(State)
182 make_typedescr(space.w_object.layout.typedef,
183 dealloc=state.C._PyPy_object_dealloc)
184 # almost all types, which should better inherit from object.
185 make_typedescr(None)
186
187 @specialize.memo()
188 def _get_typedescr_1(typedef):
189 try:
190 return typedescr_cache[typedef]
191 except KeyError:
192 if typedef.bases:
193 return _get_typedescr_1(typedef.bases[0])
194 return typedescr_cache[None]
195
196 def get_typedescr(typedef):
197 if typedef is None:
198 return typedescr_cache[None]
199 else:
200 return _get_typedescr_1(typedef)
201
202 #________________________________________________________
203 # refcounted object support
204
205 class InvalidPointerException(Exception):
206 pass
207
208 @jit.dont_look_inside
209 def create_ref(space, w_obj, w_userdata=None, immortal=False):
210 """
211 Allocates a PyObject, and fills its fields with info from the given
212 interpreter object.
213 """
214 w_type = space.type(w_obj)
215 pytype = rffi.cast(PyTypeObjectPtr, as_pyobj(space, w_type))
216 typedescr = get_typedescr(w_obj.typedef)
217 if space.is_w(w_type, space.w_text):
218 # These PyUnicodeObjects will always take the compact form
219 # since they come from uint8-encoded strings, so we must
220 # override the default tp_itemsize (see also unicode_alloc)
221 # Maybe this snippet should use the ptype.tp_alloc to allocate the py_obj?
222 itemsize = 1
223 elif space.is_w(w_type, space.w_type):
224 # Subclasses of "type" (which has space for PyMemberDef) do not
225 # need space for tp_member like heap types do
226 itemsize = 0
227 else:
228 itemsize = pytype.c_tp_itemsize
229 if itemsize != 0 or space.issubtype_w(w_type, space.w_list):
230 # PyBytesObject, compact PyUnicodeObject and subclasses
231 try:
232 # Can cause infinite recursion if w_obj.__len__ is a c function
233 # so the call will try to convert w_obj to a pyobj via create_ref
234 from pypy.objspace.std.listobject import W_ListObject
235 if isinstance(w_obj, W_ListObject):
236 itemcount = w_obj.length()
237 else:
238 itemcount = space.len_w(w_obj)
239 except OperationError as e:
240 if e.match(space, space.w_TypeError):
241 # issue 4013: is this correct?
242 itemcount = 0
243 # raise oefmt(space.w_SystemError,
244 # "cpyext: Failure to allocate '%N' (with a non-zero "
245 # "tp_itemsize) when len(obj) cannot be calculated",
246 # w_type)
247 else:
248 raise
249 else:
250 itemcount = 0
251 py_obj = typedescr.allocate(space, w_type, itemcount=itemcount, immortal=immortal)
252 track_reference(space, py_obj, w_obj)
253 #
254 # py_obj.c_ob_refcnt should be exactly REFCNT_FROM_PYPY + 1 here,
255 # and we want only REFCNT_FROM_PYPY, i.e. only count as attached
256 # to the W_Root but not with any reference from the py_obj side.
257 assert py_obj.c_ob_refcnt > rawrefcount.REFCNT_FROM_PYPY
258 py_obj.c_ob_refcnt -= 1
259 #
260 typedescr.attach(space, py_obj, w_obj, w_userdata)
261 # This is probably not the best place for this stanza, but we need the
262 # w_obj so it cannot be done in allocate()
263 # It should probably also be in track_reference
264 if pytype.c_tp_dictoffset:
265 dictoffset = pytype.c_tp_dictoffset
266 try:
267 w_dict = space.getattr(w_obj, space.newtext("__dict__"))
268 except OperationError as e:
269 dictref = make_ref(space, space.w_None)
270 else:
271 dictref = make_ref(space, w_dict)
272 if dictoffset < 0:
273 dictoffset += pytype.c_tp_basicsize
274 loc = rffi.ptradd(cts.cast("char *", py_obj), dictoffset)
275 dictloc = cts.cast("PyObject **", loc)
276 dictloc[0] = dictref
277 return py_obj
278
279 def track_reference(space, py_obj, w_obj):
280 """
281 Ties together a PyObject and an interpreter object.
282 The PyObject's refcnt is increased by REFCNT_FROM_PYPY.
283 The reference in 'py_obj' is not stolen! Remember to decref()
284 it if you need to.
285 """
286 # XXX looks like a PyObject_GC_TRACK
287 assert py_obj.c_ob_refcnt < rawrefcount.REFCNT_FROM_PYPY
288 py_obj.c_ob_refcnt += rawrefcount.REFCNT_FROM_PYPY
289 w_obj._cpyext_attach_pyobj(space, py_obj)
290
291
292 w_marker_deallocating = W_Root()
293
294 @jit.dont_look_inside
295 def from_ref(space, ref):
296 """
297 Finds the interpreter object corresponding to the given reference. If the
298 object is not yet realized (see bytesobject.py), creates it.
299 """
300 assert is_pyobj(ref)
301 if not ref:
302 return None
303 w_obj = rawrefcount.to_obj(W_Root, rffi.cast(PyObject, ref))
304 if w_obj is not None:
305 if w_obj is not w_marker_deallocating:
306 return w_obj
307 type_name = rffi.charp2str(cts.cast('char*', ref.c_ob_type.c_tp_name))
308 fatalerror(
309 "*** Invalid usage of a dying CPython object ***\n"
310 "\n"
311 "cpyext, the emulation layer, detected that while it is calling\n"
312 "an object's tp_dealloc, the C code calls back a function that\n"
313 "tries to recreate the PyPy version of the object. Usually it\n"
314 "means that tp_dealloc calls some general PyXxx() API. It is\n"
315 "a dangerous and potentially buggy thing to do: even in CPython\n"
316 "the PyXxx() function could, in theory, cause a reference to the\n"
317 "object to be taken and stored somewhere, for an amount of time\n"
318 "exceeding tp_dealloc itself. Afterwards, the object will be\n"
319 "freed, making that reference point to garbage.\n"
320 ">>> PyPy could contain some workaround to still work if\n"
321 "you are lucky, but it is not done so far; better fix the bug in\n"
322 "the CPython extension.\n"
323 ">>> This object is of type '%s'" % (type_name,))
324
325 # This reference is not yet a real interpreter object.
326 # Realize it.
327 ref_type = rffi.cast(PyObject, ref.c_ob_type)
328 if ref_type == ref: # recursion!
329 raise InvalidPointerException(str(ref))
330 w_type = from_ref(space, ref_type)
331 assert isinstance(w_type, W_TypeObject)
332 return get_typedescr(w_type.layout.typedef).realize(space, ref)
333
334 @jit.dont_look_inside
335 def as_pyobj(space, w_obj, w_userdata=None, immortal=False):
336 """
337 Returns a 'PyObject *' representing the given interpreter object.
338 This doesn't give a new reference, but the returned 'PyObject *'
339 is valid at least as long as 'w_obj' is. **To be safe, you should
340 use keepalive_until_here(w_obj) some time later.** In case of
341 doubt, use the safer make_ref().
342 """
343 assert not is_pyobj(w_obj)
344 if w_obj is not None:
345 py_obj = w_obj._cpyext_as_pyobj(space)
346 if not py_obj:
347 py_obj = create_ref(space, w_obj, w_userdata, immortal=immortal)
348 #
349 # Try to crash here, instead of randomly, if we don't keep w_obj alive
350 ll_assert(py_obj.c_ob_refcnt >= rawrefcount.REFCNT_FROM_PYPY,
351 "Bug in cpyext: The W_Root object was garbage-collected "
352 "while being converted to PyObject.")
353 return py_obj
354 else:
355 return lltype.nullptr(PyObject.TO)
356 as_pyobj._always_inline_ = 'try'
357
358 def pyobj_has_w_obj(pyobj):
359 w_obj = rawrefcount.to_obj(W_Root, pyobj)
360 return w_obj is not None and w_obj is not w_marker_deallocating
361
362 def w_obj_has_pyobj(w_obj):
363 return bool(rawrefcount.from_obj(PyObject, w_obj))
364
365 def is_pyobj(x):
366 if x is None or isinstance(x, W_Root):
367 return False
368 elif is_PyObject(lltype.typeOf(x)):
369 return True
370 else:
371 raise TypeError(repr(type(x)))
372
373 class Entry(ExtRegistryEntry):
374 _about_ = is_pyobj
375 def compute_result_annotation(self, s_x):
376 from rpython.rtyper.llannotation import SomePtr
377 return self.bookkeeper.immutablevalue(isinstance(s_x, SomePtr))
378 def specialize_call(self, hop):
379 hop.exception_cannot_occur()
380 return hop.inputconst(lltype.Bool, hop.s_result.const)
381
382 def get_pyobj_and_incref(space, w_obj, w_userdata=None, immortal=False):
383 pyobj = as_pyobj(space, w_obj, w_userdata, immortal=immortal)
384 if pyobj: # != NULL
385 assert pyobj.c_ob_refcnt >= rawrefcount.REFCNT_FROM_PYPY
386 pyobj.c_ob_refcnt += 1
387 keepalive_until_here(w_obj)
388 return pyobj
389
390 def hack_for_result_often_existing_obj(space, w_obj):
391 # Equivalent to get_pyobj_and_incref() and not to make_ref():
392 # it builds a PyObject from a W_Root, but ensures that the result
393 # gets attached to the original W_Root. This is needed to work around
394 # some obscure abuses: https://github.com/numpy/numpy/issues/9850
395 return get_pyobj_and_incref(space, w_obj)
396
397 def make_ref(space, w_obj, w_userdata=None, immortal=False):
398 """Turn the W_Root into a corresponding PyObject. You should
399 decref the returned PyObject later. Note that it is often the
400 case, but not guaranteed, that make_ref() returns always the
401 same PyObject for the same W_Root; for example, integers.
402 """
403 assert not is_pyobj(w_obj)
404 if False and w_obj is not None and space.type(w_obj) is space.w_int:
405 # XXX: adapt for pypy3
406 state = space.fromcache(State)
407 intval = space.int_w(w_obj)
408 return state.ccall("PyLong_FromLong", intval)
409 return get_pyobj_and_incref(space, w_obj, w_userdata, immortal=False)
410
411 @specialize.ll()
412 def get_w_obj_and_decref(space, pyobj):
413 """Decrement the reference counter of the PyObject and return the
414 corresponding W_Root object (so the reference count after the decref
415 is at least REFCNT_FROM_PYPY and cannot be zero).
416 """
417 assert is_pyobj(pyobj)
418 pyobj = rffi.cast(PyObject, pyobj)
419 w_obj = from_ref(space, pyobj)
420 if pyobj:
421 pyobj.c_ob_refcnt -= 1
422 assert pyobj.c_ob_refcnt >= rawrefcount.REFCNT_FROM_PYPY
423 keepalive_until_here(w_obj)
424 return w_obj
425
426
427 @specialize.ll()
428 def incref(space, pyobj):
429 assert is_pyobj(pyobj)
430 pyobj = rffi.cast(PyObject, pyobj)
431 assert pyobj.c_ob_refcnt >= 1
432 pyobj.c_ob_refcnt += 1
433
434 @specialize.ll()
435 def decref(space, pyobj):
436 from pypy.module.cpyext.api import generic_cpy_call
437 assert is_pyobj(pyobj)
438 pyobj = rffi.cast(PyObject, pyobj)
439 if pyobj:
440 assert pyobj.c_ob_refcnt > 0
441 assert (pyobj.c_ob_pypy_link == 0 or
442 pyobj.c_ob_refcnt > rawrefcount.REFCNT_FROM_PYPY)
443 pyobj.c_ob_refcnt -= 1
444 if pyobj.c_ob_refcnt == 0:
445 state = space.fromcache(State)
446 generic_cpy_call(space, state.C._Py_Dealloc, pyobj)
447 #else:
448 # w_obj = rawrefcount.to_obj(W_Root, ref)
449 # if w_obj is not None:
450 # assert pyobj.c_ob_refcnt >= rawrefcount.REFCNT_FROM_PYPY
451
452
453 @init_function
454 def write_w_marker_deallocating(space):
455 if we_are_translated():
456 llptr = cast_instance_to_base_ptr(w_marker_deallocating)
457 state = space.fromcache(State)
458 state.C.set_marker(llptr)
459
460 @cpython_api([rffi.VOIDP], lltype.Signed, error=CANNOT_FAIL)
461 def _Py_HashPointer(space, ptr):
462 return rffi.cast(lltype.Signed, ptr)
463
464 @cpython_api([PyObject], lltype.Void)
465 def Py_IncRef(space, obj):
466 # used only ifdef PYPY_DEBUG_REFCOUNT
467 if obj:
468 incref(space, obj)
469
470 @cpython_api([PyObject], lltype.Void)
471 def Py_DecRef(space, obj):
472 # used only ifdef PYPY_DEBUG_REFCOUNT
473 decref(space, obj)