Debian Codegraph @

mypyc/lib-rt/pythonsupport.h

raw
1 // Collects code that was copied in from cpython, for a couple of different reasons:
2 // * We wanted to modify it to produce a more efficient version for our uses
3 // * We needed to call it and it was static :(
4 // * We wanted to call it and needed to backport it
5
6 #ifndef CPY_PYTHONSUPPORT_H
7 #define CPY_PYTHONSUPPORT_H
8
9 #include <Python.h>
10 #include <stdbool.h>
11 #include "pythoncapi_compat.h"
12 #include <frameobject.h>
13 #include <assert.h>
14 #include "static_data.h"
15 #include "mypyc_util.h"
16
17 #if CPY_3_13_FEATURES
18 #ifndef Py_BUILD_CORE
19 #define Py_BUILD_CORE
20 #endif
21 #include "internal/pycore_genobject.h" // _PyGen_FetchStopIterationValue
22 #include "internal/pycore_pyerrors.h" // _PyErr_FormatFromCause, _PyErr_SetKeyError
23 #include "internal/pycore_setobject.h" // _PySet_Update
24 #endif
25
26 #ifdef Py_GIL_DISABLED
27 #include "internal/pycore_object.h" // _Py_TryIncrefFast, _Py_TryIncRefShared
28 #endif
29
30 #if CPY_3_12_FEATURES
31 #include "internal/pycore_frame.h"
32 #endif
33
34 #ifdef __cplusplus
35 extern "C" {
36 #endif
37 #if 0
38 } // why isn't emacs smart enough to not indent this
39 #endif
40
41 #ifdef Py_GIL_DISABLED
42 // Read a native attribute that is a single reference-counted 'PyObject *' field,
43 // returning a new reference (or NULL if the field is NULL/undefined).
44 //
45 // On free-threaded builds a plain load followed by an incref races with a
46 // concurrent setter that may decref the old value to zero and free it before the
47 // incref runs (use-after-free). CPy_SetAttrRef avoids that by reclaiming old
48 // values through QSBR-delayed decref, so a value observed in the field remains
49 // safe to touch while this reader is running.
50 //
51 // Only the hot case is inlined here: an incref of a value owned by this thread or
52 // immortal, via '_Py_TryIncrefFast' (no CAS, no loop). Everything colder -- the
53 // cross-thread shared-refcount CAS and the _Py_NewRefWithLock fallback -- lives
54 // out-of-line in 'CPy_GetAttrRefSlow'. Splitting it this way keeps each call
55 // site's fast path small enough to inline, which is measurably faster than
56 // letting the compiler auto-out-line the whole helper (that merges every read
57 // site's branch history into one shared copy and mispredicts). It is only used in
58 // free-threaded builds; the default (GIL) build keeps the plain load + incref
59 // generated inline by mypyc.
60 PyObject *CPy_GetAttrRefSlow(PyObject *v);
61
62 static inline PyObject *CPy_GetAttrRef(PyObject **field) {
63 PyObject *v = (PyObject *)_Py_atomic_load_ptr_acquire(field);
64 if (v == NULL) {
65 return NULL;
66 }
67 if (_Py_TryIncrefFast(v)) {
68 return v;
69 }
70 return CPy_GetAttrRefSlow(v);
71 }
72
73 // Read a native attribute that is a single reference-counted 'PyObject *' field
74 // AND is Final (assigned once during construction, never rebound -- mypyc emits no
75 // setter for it), returning a new reference (or NULL if undefined).
76 //
77 // A Final attribute has no concurrent writer after 'self' is published, so the
78 // use-after-free race that CPy_GetAttrRef guards against cannot happen: the field
79 // holds a strong reference for the object's whole lifetime, and any thread reading
80 // it necessarily holds 'self', which keeps the value alive. So the try-incref +
81 // _Py_NewRefWithLock fallback are unnecessary here -- a plain load + Py_INCREF is
82 // safe. A cross-thread Py_INCREF is an unconditional
83 // atomic add on ob_ref_shared, so (unlike CPy_GetAttrRef's try-incref) it needs no
84 // maybe-weakref and has no slow path. The load is relaxed rather than acquire: the
85 // reader reached 'self' through a synchronization edge (self's own publication)
86 // that already ordered the construction stores before it, exactly as with
87 // CPy_InitAttrRef's relaxed store. Relaxed keeps it TSan-clean at zero cost (plain
88 // mov/ldr).
89 static inline PyObject *CPy_GetAttrRefFinal(PyObject **field) {
90 PyObject *v = (PyObject *)_Py_atomic_load_ptr_relaxed(field);
91 if (v != NULL) {
92 Py_INCREF(v);
93 }
94 return v;
95 }
96
97 // Reclaim the previous value of a native attribute after it has been replaced.
98 //
99 // CPy_GetAttrRef reads the field optimistically without holding any lock the
100 // writer also takes, so a reader can load the old pointer and then try to take a
101 // reference after this store. The old value must therefore stay alive until every
102 // thread has passed a quiescent point, which is exactly what a QSBR-deferred
103 // decref guarantees. So all mortal old values are
104 // reclaimed via _PyObject_XDecRefDelayed, matching CPython's own replace-a-slot
105 // paths (e.g. _PyObject_SetDict / _PyObject_SetManagedDict).
106 //
107 // We deliberately do NOT take a "local refcount > 1, owned by this thread" fast
108 // path: dropping the field's reference is not the only decref of the object, so a
109 // non-freeing local decrement here does not prevent an unrelated reference holder
110 // from driving the object to zero (a plain, non-deferred Py_DECREF -> _Py_Dealloc)
111 // while an in-flight reader still holds the stale pointer -- a use-after-free that
112 // only QSBR deferral closes. Immortal objects are never freed, so skipping their
113 // decref entirely is safe and avoids queuing a no-op onto the delayed-free list.
114 static inline void CPy_DecRefAttrOld(PyObject *op) {
115 if (op == NULL) {
116 return;
117 }
118 if (_Py_IsImmortal(op)) {
119 return;
120 }
121 _PyObject_XDecRefDelayed(op);
122 }
123
124 // Set a native attribute that is a single reference-counted 'PyObject *' field,
125 // stealing the reference to 'value' (which may be NULL to delete the attribute)
126 // and safely reclaiming the previous value.
127 //
128 // Memory safety does NOT depend on SetMaybeWeakref here, so (unlike an earlier
129 // version) we do not call it. Two things keep this safe:
130 // - The old value is reclaimed via CPy_DecRefAttrOld, a QSBR-deferred decref, so
131 // it cannot be freed while an in-flight CPy_GetAttrRef still holds the stale
132 // pointer.
133 // - A concurrent cross-thread reader whose inline fast-path try-incref fails on
134 // an unflagged 'value' still cannot fail and never blocks on this writer:
135 // CPy_GetAttrRef falls into CPy_GetAttrRefSlow, which is fully lock-free. It
136 // retries with a lock-free shared-refcount CAS (_Py_TryIncRefShared) and, only
137 // if that also fails, forces a reference via _Py_NewRefWithLock, which cannot
138 // fail and lazily sets maybe-weakref so later cross-thread reads take the CAS.
139 // This mirrors CPy_InitAttrRef, which already omits SetMaybeWeakref for the same
140 // reason. Setting the flag here would only be a possible performance tuning knob
141 // (it would let that first cross-thread reader succeed on the cheaper
142 // _Py_TryIncRefShared CAS instead of falling through to _Py_NewRefWithLock); it is
143 // not needed for correctness. The atomic exchange publishes the new pointer and
144 // hands back the old one without a writer/writer race.
145 static inline void CPy_SetAttrRef(PyObject **field, PyObject *value) {
146 PyObject *old = (PyObject *)_Py_atomic_exchange_ptr(field, value);
147 CPy_DecRefAttrOld(old);
148 }
149
150 // Initialize a native attribute that is known to be previously undefined (NULL),
151 // stealing the reference to 'value'.
152 //
153 // Initializer stores only happen while 'self' is still thread-local (the
154 // attribute-definedness analysis marks a SetAttr as an initializer only before
155 // 'self' can leak -- see mypyc/analysis/attrdefined.py). So there is no old value
156 // to reclaim, no competing writer, and the field store is not itself the
157 // publication point: 'self' is published later (when it escapes __init__ or is
158 // returned), and that publication carries the release barrier making all the
159 // construction stores visible. A relaxed store therefore suffices.
160 //
161 // Unlike CPy_SetAttrRef, this deliberately does NOT call SetMaybeWeakref (its CAS
162 // is pure overhead here, ~+2.6ns per fresh store, and construction-heavy code
163 // pays it on every attribute of every new object). The cost is moved off this hot
164 // path onto CPy_GetAttrRef's cold slow path, which sets maybe-weakref lazily on
165 // the first cross-thread read that needs it.
166 static inline void CPy_InitAttrRef(PyObject **field, PyObject *value) {
167 _Py_atomic_store_ptr_relaxed(field, value);
168 }
169 #endif
170
171 PyObject* update_bases(PyObject *bases);
172 int init_subclass(PyTypeObject *type, PyObject *kwds);
173
174 Py_ssize_t
175 CPyLong_AsSsize_tAndOverflow_(PyObject *vv, int *overflow);
176
177 #if CPY_3_12_FEATURES
178
179 static inline Py_ssize_t
180 CPyLong_AsSsize_tAndOverflow(PyObject *vv, int *overflow)
181 {
182 /* This version by Tim Peters */
183 PyLongObject *v = (PyLongObject *)vv;
184 Py_ssize_t res;
185 Py_ssize_t i;
186
187 *overflow = 0;
188
189 res = -1;
190 i = CPY_LONG_TAG(v);
191
192 // TODO: Combine zero and non-zero cases helow?
193 if (likely(i == (1 << CPY_NON_SIZE_BITS))) {
194 res = CPY_LONG_DIGIT(v, 0);
195 } else if (likely(i == CPY_SIGN_ZERO)) {
196 res = 0;
197 } else if (i == ((1 << CPY_NON_SIZE_BITS) | CPY_SIGN_NEGATIVE)) {
198 res = -(sdigit)CPY_LONG_DIGIT(v, 0);
199 } else {
200 // Slow path is moved to a non-inline helper function to
201 // limit size of generated code
202 int overflow_local;
203 res = CPyLong_AsSsize_tAndOverflow_(vv, &overflow_local);
204 *overflow = overflow_local;
205 }
206 return res;
207 }
208
209 #else
210
211 // Adapted from longobject.c in Python 3.7.0
212
213 /* This function adapted from PyLong_AsLongLongAndOverflow, but with
214 * some safety checks removed and specialized to only work for objects
215 * that are already longs.
216 * About half of the win this provides, though, just comes from being
217 * able to inline the function, which in addition to saving function call
218 * overhead allows the out-parameter overflow flag to be collapsed into
219 * control flow.
220 * Additionally, we check against the possible range of CPyTagged, not of
221 * Py_ssize_t. */
222 static inline Py_ssize_t
223 CPyLong_AsSsize_tAndOverflow(PyObject *vv, int *overflow)
224 {
225 /* This version by Tim Peters */
226 PyLongObject *v = (PyLongObject *)vv;
227 Py_ssize_t res;
228 Py_ssize_t i;
229
230 *overflow = 0;
231
232 res = -1;
233 i = Py_SIZE(v);
234
235 if (likely(i == 1)) {
236 res = CPY_LONG_DIGIT(v, 0);
237 } else if (likely(i == 0)) {
238 res = 0;
239 } else if (i == -1) {
240 res = -(sdigit)CPY_LONG_DIGIT(v, 0);
241 } else {
242 // Slow path is moved to a non-inline helper function to
243 // limit size of generated code
244 int overflow_local;
245 res = CPyLong_AsSsize_tAndOverflow_(vv, &overflow_local);
246 *overflow = overflow_local;
247 }
248 return res;
249 }
250
251 #endif
252
253 // Adapted from listobject.c in Python 3.7.0
254 static int
255 list_resize(PyListObject *self, Py_ssize_t newsize)
256 {
257 PyObject **items;
258 size_t new_allocated, num_allocated_bytes;
259 Py_ssize_t allocated = self->allocated;
260
261 /* Bypass realloc() when a previous overallocation is large enough
262 to accommodate the newsize. If the newsize falls lower than half
263 the allocated size, then proceed with the realloc() to shrink the list.
264 */
265 if (allocated >= newsize && newsize >= (allocated >> 1)) {
266 assert(self->ob_item != NULL || newsize == 0);
267 Py_SET_SIZE(self, newsize);
268 return 0;
269 }
270
271 /* This over-allocates proportional to the list size, making room
272 * for additional growth. The over-allocation is mild, but is
273 * enough to give linear-time amortized behavior over a long
274 * sequence of appends() in the presence of a poorly-performing
275 * system realloc().
276 * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
277 * Note: new_allocated won't overflow because the largest possible value
278 * is PY_SSIZE_T_MAX * (9 / 8) + 6 which always fits in a size_t.
279 */
280 new_allocated = (size_t)newsize + (newsize >> 3) + (newsize < 9 ? 3 : 6);
281 if (new_allocated > (size_t)PY_SSIZE_T_MAX / sizeof(PyObject *)) {
282 PyErr_NoMemory();
283 return -1;
284 }
285
286 if (newsize == 0)
287 new_allocated = 0;
288 num_allocated_bytes = new_allocated * sizeof(PyObject *);
289 items = (PyObject **)PyMem_Realloc(self->ob_item, num_allocated_bytes);
290 if (items == NULL) {
291 PyErr_NoMemory();
292 return -1;
293 }
294 self->ob_item = items;
295 Py_SET_SIZE(self, newsize);
296 self->allocated = new_allocated;
297 return 0;
298 }
299
300 // Changed to use PyList_SetSlice instead of the internal list_ass_slice
301 static PyObject *
302 list_pop_impl(PyListObject *self, Py_ssize_t index)
303 {
304 PyObject *v;
305 int status;
306
307 if (Py_SIZE(self) == 0) {
308 /* Special-case most common failure cause */
309 PyErr_SetString(PyExc_IndexError, "pop from empty list");
310 return NULL;
311 }
312 if (index < 0)
313 index += Py_SIZE(self);
314 if (index < 0 || index >= Py_SIZE(self)) {
315 PyErr_SetString(PyExc_IndexError, "pop index out of range");
316 return NULL;
317 }
318 v = self->ob_item[index];
319 if (index == Py_SIZE(self) - 1) {
320 status = list_resize(self, Py_SIZE(self) - 1);
321 if (status >= 0)
322 return v; /* and v now owns the reference the list had */
323 else
324 return NULL;
325 }
326 Py_INCREF(v);
327 status = PyList_SetSlice((PyObject *)self, index, index+1, (PyObject *)NULL);
328 if (status < 0) {
329 Py_DECREF(v);
330 return NULL;
331 }
332 return v;
333 }
334
335 // Tweaked to directly use CPyTagged
336 static CPyTagged
337 list_count(PyListObject *self, PyObject *value)
338 {
339 Py_ssize_t count = 0;
340 Py_ssize_t i;
341
342 #ifdef Py_GIL_DISABLED
343 for (i = 0; i < PyList_GET_SIZE(self); i++) {
344 PyObject *item = PyList_GetItemRef((PyObject *)self, i);
345 if (unlikely(item == NULL)) {
346 // Race condition: list shrank between size read and get item
347 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
348 PyErr_Clear();
349 break;
350 }
351 return CPY_INT_TAG;
352 }
353 int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
354 Py_DECREF(item);
355 if (cmp > 0)
356 count++;
357 else if (cmp < 0)
358 return CPY_INT_TAG;
359 }
360 #else
361 for (i = 0; i < Py_SIZE(self); i++) {
362 int cmp = PyObject_RichCompareBool(self->ob_item[i], value, Py_EQ);
363 if (cmp > 0)
364 count++;
365 else if (cmp < 0)
366 return CPY_INT_TAG;
367 }
368 #endif
369 return CPyTagged_ShortFromSsize_t(count);
370 }
371
372 // Adapted from genobject.c in Python 3.7.2
373 // Copied because it wasn't in 3.5.2 and it is undocumented anyways.
374 /*
375 * Set StopIteration with specified value. Value can be arbitrary object
376 * or NULL.
377 *
378 * Returns 0 if StopIteration is set and -1 if any other exception is set.
379 */
380 static int
381 CPyGen_SetStopIterationValue(PyObject *value)
382 {
383 PyObject *e;
384
385 if (value == NULL ||
386 (!PyTuple_Check(value) && !PyExceptionInstance_Check(value)))
387 {
388 /* Delay exception instantiation if we can */
389 PyErr_SetObject(PyExc_StopIteration, value);
390 return 0;
391 }
392 /* Construct an exception instance manually with
393 * PyObject_CallOneArg and pass it to PyErr_SetObject.
394 *
395 * We do this to handle a situation when "value" is a tuple, in which
396 * case PyErr_SetObject would set the value of StopIteration to
397 * the first element of the tuple.
398 *
399 * (See PyErr_SetObject/_PyErr_CreateException code for details.)
400 */
401 e = PyObject_CallOneArg(PyExc_StopIteration, value);
402 if (e == NULL) {
403 return -1;
404 }
405 PyErr_SetObject(PyExc_StopIteration, e);
406 Py_DECREF(e);
407 return 0;
408 }
409
410 // Copied from dictobject.c and dictobject.h, these are not Public before
411 // Python 3.8. Also remove some error checks that we do in the callers.
412 typedef struct {
413 PyObject_HEAD
414 PyDictObject *dv_dict;
415 } _CPyDictViewObject;
416
417 static PyObject *
418 _CPyDictView_New(PyObject *dict, PyTypeObject *type)
419 {
420 _CPyDictViewObject *dv = PyObject_GC_New(_CPyDictViewObject, type);
421 if (dv == NULL)
422 return NULL;
423 Py_INCREF(dict);
424 dv->dv_dict = (PyDictObject *)dict;
425 PyObject_GC_Track(dv);
426 return (PyObject *)dv;
427 }
428
429 #ifdef __cplusplus
430 }
431 #endif
432
433 #if CPY_3_12_FEATURES
434
435 // These are copied from genobject.c in Python 3.12
436
437 static int
438 gen_is_coroutine(PyObject *o)
439 {
440 if (PyGen_CheckExact(o)) {
441 PyCodeObject *code = PyGen_GetCode((PyGenObject*)o);
442 if (code->co_flags & CO_ITERABLE_COROUTINE) {
443 return 1;
444 }
445 }
446 return 0;
447 }
448
449 #else
450
451 // Copied from genobject.c in Python 3.10
452 static int
453 gen_is_coroutine(PyObject *o)
454 {
455 if (PyGen_CheckExact(o)) {
456 PyCodeObject *code = (PyCodeObject *)((PyGenObject*)o)->gi_code;
457 if (code->co_flags & CO_ITERABLE_COROUTINE) {
458 return 1;
459 }
460 }
461 return 0;
462 }
463
464 #endif
465
466 /*
467 * This helper function returns an awaitable for `o`:
468 * - `o` if `o` is a coroutine-object;
469 * - `type(o)->tp_as_async->am_await(o)`
470 *
471 * Raises a TypeError if it's not possible to return
472 * an awaitable and returns NULL.
473 */
474 static PyObject *
475 CPyCoro_GetAwaitableIter(PyObject *o)
476 {
477 unaryfunc getter = NULL;
478 PyTypeObject *ot;
479
480 if (PyCoro_CheckExact(o) || gen_is_coroutine(o)) {
481 /* 'o' is a coroutine. */
482 Py_INCREF(o);
483 return o;
484 }
485
486 ot = Py_TYPE(o);
487 if (ot->tp_as_async != NULL) {
488 getter = ot->tp_as_async->am_await;
489 }
490 if (getter != NULL) {
491 PyObject *res = (*getter)(o);
492 if (res != NULL) {
493 if (PyCoro_CheckExact(res) || gen_is_coroutine(res)) {
494 /* __await__ must return an *iterator*, not
495 a coroutine or another awaitable (see PEP 492) */
496 PyErr_SetString(PyExc_TypeError,
497 "__await__() returned a coroutine");
498 Py_CLEAR(res);
499 } else if (!PyIter_Check(res)) {
500 PyErr_Format(PyExc_TypeError,
501 "__await__() returned non-iterator "
502 "of type '%.100s'",
503 Py_TYPE(res)->tp_name);
504 Py_CLEAR(res);
505 }
506 }
507 return res;
508 }
509
510 PyErr_Format(PyExc_TypeError,
511 "object %.100s can't be used in 'await' expression",
512 ot->tp_name);
513 return NULL;
514 }
515
516
517 #endif