Coverage Report

Created: 2025-08-29 07:13

/src/cpython3/Objects/object.c
Line
Count
Source (jump to first uncovered line)
1
2
/* Generic object operations; and implementation of None */
3
4
#include "Python.h"
5
#include "pycore_brc.h"           // _Py_brc_queue_object()
6
#include "pycore_call.h"          // _PyObject_CallNoArgs()
7
#include "pycore_ceval.h"         // _Py_EnterRecursiveCallTstate()
8
#include "pycore_context.h"       // _PyContextTokenMissing_Type
9
#include "pycore_critical_section.h" // Py_BEGIN_CRITICAL_SECTION
10
#include "pycore_descrobject.h"   // _PyMethodWrapper_Type
11
#include "pycore_dict.h"          // _PyObject_MaterializeManagedDict()
12
#include "pycore_floatobject.h"   // _PyFloat_DebugMallocStats()
13
#include "pycore_freelist.h"      // _PyObject_ClearFreeLists()
14
#include "pycore_genobject.h"     // _PyAsyncGenAThrow_Type
15
#include "pycore_hamt.h"          // _PyHamtItems_Type
16
#include "pycore_initconfig.h"    // _PyStatus_OK()
17
#include "pycore_instruction_sequence.h" // _PyInstructionSequence_Type
18
#include "pycore_interpframe.h"   // _PyFrame_Stackbase()
19
#include "pycore_interpolation.h" // _PyInterpolation_Type
20
#include "pycore_list.h"          // _PyList_DebugMallocStats()
21
#include "pycore_long.h"          // _PyLong_GetZero()
22
#include "pycore_memoryobject.h"  // _PyManagedBuffer_Type
23
#include "pycore_namespace.h"     // _PyNamespace_Type
24
#include "pycore_object.h"        // export _Py_SwappedOp
25
#include "pycore_optimizer.h"     // _PyUOpExecutor_Type
26
#include "pycore_pyerrors.h"      // _PyErr_Occurred()
27
#include "pycore_pymem.h"         // _PyMem_IsPtrFreed()
28
#include "pycore_pystate.h"       // _PyThreadState_GET()
29
#include "pycore_symtable.h"      // PySTEntry_Type
30
#include "pycore_template.h"      // _PyTemplate_Type _PyTemplateIter_Type
31
#include "pycore_tuple.h"         // _PyTuple_DebugMallocStats()
32
#include "pycore_typeobject.h"    // _PyBufferWrapper_Type
33
#include "pycore_typevarobject.h" // _PyTypeAlias_Type
34
#include "pycore_unionobject.h"   // _PyUnion_Type
35
36
37
#ifdef Py_LIMITED_API
38
   // Prevent recursive call _Py_IncRef() <=> Py_INCREF()
39
#  error "Py_LIMITED_API macro must not be defined"
40
#endif
41
42
/* Defined in tracemalloc.c */
43
extern void _PyMem_DumpTraceback(int fd, const void *ptr);
44
45
46
int
47
_PyObject_CheckConsistency(PyObject *op, int check_content)
48
0
{
49
0
#define CHECK(expr) \
50
0
    do { if (!(expr)) { _PyObject_ASSERT_FAILED_MSG(op, Py_STRINGIFY(expr)); } } while (0)
51
52
0
    CHECK(!_PyObject_IsFreed(op));
53
0
    CHECK(Py_REFCNT(op) >= 1);
54
55
0
    _PyType_CheckConsistency(Py_TYPE(op));
56
57
0
    if (PyUnicode_Check(op)) {
58
0
        _PyUnicode_CheckConsistency(op, check_content);
59
0
    }
60
0
    else if (PyDict_Check(op)) {
61
0
        _PyDict_CheckConsistency(op, check_content);
62
0
    }
63
0
    return 1;
64
65
0
#undef CHECK
66
0
}
67
68
69
#ifdef Py_REF_DEBUG
70
/* We keep the legacy symbol around for backward compatibility. */
71
Py_ssize_t _Py_RefTotal;
72
73
static inline Py_ssize_t
74
get_legacy_reftotal(void)
75
{
76
    return _Py_RefTotal;
77
}
78
#endif
79
80
#ifdef Py_REF_DEBUG
81
82
#  define REFTOTAL(interp) \
83
    interp->object_state.reftotal
84
85
static inline void
86
reftotal_add(PyThreadState *tstate, Py_ssize_t n)
87
{
88
#ifdef Py_GIL_DISABLED
89
    _PyThreadStateImpl *tstate_impl = (_PyThreadStateImpl *)tstate;
90
    // relaxed store to avoid data race with read in get_reftotal()
91
    Py_ssize_t reftotal = tstate_impl->reftotal + n;
92
    _Py_atomic_store_ssize_relaxed(&tstate_impl->reftotal, reftotal);
93
#else
94
    REFTOTAL(tstate->interp) += n;
95
#endif
96
}
97
98
static inline Py_ssize_t get_global_reftotal(_PyRuntimeState *);
99
100
/* We preserve the number of refs leaked during runtime finalization,
101
   so they can be reported if the runtime is initialized again. */
102
// XXX We don't lose any information by dropping this,
103
// so we should consider doing so.
104
static Py_ssize_t last_final_reftotal = 0;
105
106
void
107
_Py_FinalizeRefTotal(_PyRuntimeState *runtime)
108
{
109
    last_final_reftotal = get_global_reftotal(runtime);
110
    runtime->object_state.interpreter_leaks = 0;
111
}
112
113
void
114
_PyInterpreterState_FinalizeRefTotal(PyInterpreterState *interp)
115
{
116
    interp->runtime->object_state.interpreter_leaks += REFTOTAL(interp);
117
    REFTOTAL(interp) = 0;
118
}
119
120
static inline Py_ssize_t
121
get_reftotal(PyInterpreterState *interp)
122
{
123
    /* For a single interpreter, we ignore the legacy _Py_RefTotal,
124
       since we can't determine which interpreter updated it. */
125
    Py_ssize_t total = REFTOTAL(interp);
126
#ifdef Py_GIL_DISABLED
127
    _Py_FOR_EACH_TSTATE_UNLOCKED(interp, p) {
128
        /* This may race with other threads modifications to their reftotal */
129
        _PyThreadStateImpl *tstate_impl = (_PyThreadStateImpl *)p;
130
        total += _Py_atomic_load_ssize_relaxed(&tstate_impl->reftotal);
131
    }
132
#endif
133
    return total;
134
}
135
136
static inline Py_ssize_t
137
get_global_reftotal(_PyRuntimeState *runtime)
138
{
139
    Py_ssize_t total = 0;
140
141
    /* Add up the total from each interpreter. */
142
    HEAD_LOCK(&_PyRuntime);
143
    PyInterpreterState *interp = PyInterpreterState_Head();
144
    for (; interp != NULL; interp = PyInterpreterState_Next(interp)) {
145
        total += get_reftotal(interp);
146
    }
147
    HEAD_UNLOCK(&_PyRuntime);
148
149
    /* Add in the updated value from the legacy _Py_RefTotal. */
150
    total += get_legacy_reftotal();
151
    total += last_final_reftotal;
152
    total += runtime->object_state.interpreter_leaks;
153
154
    return total;
155
}
156
157
#undef REFTOTAL
158
159
void
160
_PyDebug_PrintTotalRefs(void) {
161
    _PyRuntimeState *runtime = &_PyRuntime;
162
    fprintf(stderr,
163
            "[%zd refs, %zd blocks]\n",
164
            get_global_reftotal(runtime), _Py_GetGlobalAllocatedBlocks());
165
    /* It may be helpful to also print the "legacy" reftotal separately.
166
       Likewise for the total for each interpreter. */
167
}
168
#endif /* Py_REF_DEBUG */
169
170
/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
171
   These are used by the individual routines for object creation.
172
   Do not call them otherwise, they do not initialize the object! */
173
174
#ifdef Py_TRACE_REFS
175
176
#define REFCHAIN(interp) interp->object_state.refchain
177
#define REFCHAIN_VALUE ((void*)(uintptr_t)1)
178
179
static inline int
180
has_own_refchain(PyInterpreterState *interp)
181
{
182
    if (interp->feature_flags & Py_RTFLAGS_USE_MAIN_OBMALLOC) {
183
        return (_Py_IsMainInterpreter(interp)
184
            || _PyInterpreterState_Main() == NULL);
185
    }
186
    return 1;
187
}
188
189
static int
190
refchain_init(PyInterpreterState *interp)
191
{
192
    if (!has_own_refchain(interp)) {
193
        // Legacy subinterpreters share a refchain with the main interpreter.
194
        REFCHAIN(interp) = REFCHAIN(_PyInterpreterState_Main());
195
        return 0;
196
    }
197
    _Py_hashtable_allocator_t alloc = {
198
        // Don't use default PyMem_Malloc() and PyMem_Free() which
199
        // require the caller to hold the GIL.
200
        .malloc = PyMem_RawMalloc,
201
        .free = PyMem_RawFree,
202
    };
203
    REFCHAIN(interp) = _Py_hashtable_new_full(
204
        _Py_hashtable_hash_ptr, _Py_hashtable_compare_direct,
205
        NULL, NULL, &alloc);
206
    if (REFCHAIN(interp) == NULL) {
207
        return -1;
208
    }
209
    return 0;
210
}
211
212
static void
213
refchain_fini(PyInterpreterState *interp)
214
{
215
    if (has_own_refchain(interp) && REFCHAIN(interp) != NULL) {
216
        _Py_hashtable_destroy(REFCHAIN(interp));
217
    }
218
    REFCHAIN(interp) = NULL;
219
}
220
221
bool
222
_PyRefchain_IsTraced(PyInterpreterState *interp, PyObject *obj)
223
{
224
    return (_Py_hashtable_get(REFCHAIN(interp), obj) == REFCHAIN_VALUE);
225
}
226
227
228
static void
229
_PyRefchain_Trace(PyInterpreterState *interp, PyObject *obj)
230
{
231
    if (_Py_hashtable_set(REFCHAIN(interp), obj, REFCHAIN_VALUE) < 0) {
232
        // Use a fatal error because _Py_NewReference() cannot report
233
        // the error to the caller.
234
        Py_FatalError("_Py_hashtable_set() memory allocation failed");
235
    }
236
}
237
238
239
static void
240
_PyRefchain_Remove(PyInterpreterState *interp, PyObject *obj)
241
{
242
    void *value = _Py_hashtable_steal(REFCHAIN(interp), obj);
243
#ifndef NDEBUG
244
    assert(value == REFCHAIN_VALUE);
245
#else
246
    (void)value;
247
#endif
248
}
249
250
251
/* Add an object to the refchain hash table.
252
 *
253
 * Note that objects are normally added to the list by PyObject_Init()
254
 * indirectly.  Not all objects are initialized that way, though; exceptions
255
 * include statically allocated type objects, and statically allocated
256
 * singletons (like Py_True and Py_None). */
257
void
258
_Py_AddToAllObjects(PyObject *op)
259
{
260
    PyInterpreterState *interp = _PyInterpreterState_GET();
261
    if (!_PyRefchain_IsTraced(interp, op)) {
262
        _PyRefchain_Trace(interp, op);
263
    }
264
}
265
#endif  /* Py_TRACE_REFS */
266
267
#ifdef Py_REF_DEBUG
268
/* Log a fatal error; doesn't return. */
269
void
270
_Py_NegativeRefcount(const char *filename, int lineno, PyObject *op)
271
{
272
    _PyObject_AssertFailed(op, NULL, "object has negative ref count",
273
                           filename, lineno, __func__);
274
}
275
276
/* This is used strictly by Py_INCREF(). */
277
void
278
_Py_INCREF_IncRefTotal(void)
279
{
280
    reftotal_add(_PyThreadState_GET(), 1);
281
}
282
283
/* This is used strictly by Py_DECREF(). */
284
void
285
_Py_DECREF_DecRefTotal(void)
286
{
287
    reftotal_add(_PyThreadState_GET(), -1);
288
}
289
290
void
291
_Py_IncRefTotal(PyThreadState *tstate)
292
{
293
    reftotal_add(tstate, 1);
294
}
295
296
void
297
_Py_DecRefTotal(PyThreadState *tstate)
298
{
299
    reftotal_add(tstate, -1);
300
}
301
302
void
303
_Py_AddRefTotal(PyThreadState *tstate, Py_ssize_t n)
304
{
305
    reftotal_add(tstate, n);
306
}
307
308
/* This includes the legacy total
309
   and any carried over from the last runtime init/fini cycle. */
310
Py_ssize_t
311
_Py_GetGlobalRefTotal(void)
312
{
313
    return get_global_reftotal(&_PyRuntime);
314
}
315
316
Py_ssize_t
317
_Py_GetLegacyRefTotal(void)
318
{
319
    return get_legacy_reftotal();
320
}
321
322
Py_ssize_t
323
_PyInterpreterState_GetRefTotal(PyInterpreterState *interp)
324
{
325
    HEAD_LOCK(&_PyRuntime);
326
    Py_ssize_t total = get_reftotal(interp);
327
    HEAD_UNLOCK(&_PyRuntime);
328
    return total;
329
}
330
331
#endif /* Py_REF_DEBUG */
332
333
void
334
Py_IncRef(PyObject *o)
335
0
{
336
0
    Py_XINCREF(o);
337
0
}
338
339
void
340
Py_DecRef(PyObject *o)
341
0
{
342
0
    Py_XDECREF(o);
343
0
}
344
345
void
346
_Py_IncRef(PyObject *o)
347
0
{
348
0
    Py_INCREF(o);
349
0
}
350
351
void
352
_Py_DecRef(PyObject *o)
353
6.05k
{
354
6.05k
    Py_DECREF(o);
355
6.05k
}
356
357
#ifdef Py_GIL_DISABLED
358
# ifdef Py_REF_DEBUG
359
static int
360
is_dead(PyObject *o)
361
{
362
#  if SIZEOF_SIZE_T == 8
363
    return (uintptr_t)o->ob_type == 0xDDDDDDDDDDDDDDDD;
364
#  else
365
    return (uintptr_t)o->ob_type == 0xDDDDDDDD;
366
#  endif
367
}
368
# endif
369
370
// Decrement the shared reference count of an object. Return 1 if the object
371
// is dead and should be deallocated, 0 otherwise.
372
static int
373
_Py_DecRefSharedIsDead(PyObject *o, const char *filename, int lineno)
374
{
375
    // Should we queue the object for the owning thread to merge?
376
    int should_queue;
377
378
    Py_ssize_t new_shared;
379
    Py_ssize_t shared = _Py_atomic_load_ssize_relaxed(&o->ob_ref_shared);
380
    do {
381
        should_queue = (shared == 0 || shared == _Py_REF_MAYBE_WEAKREF);
382
383
        if (should_queue) {
384
            // If the object had refcount zero, not queued, and not merged,
385
            // then we enqueue the object to be merged by the owning thread.
386
            // In this case, we don't subtract one from the reference count
387
            // because the queue holds a reference.
388
            new_shared = _Py_REF_QUEUED;
389
        }
390
        else {
391
            // Otherwise, subtract one from the reference count. This might
392
            // be negative!
393
            new_shared = shared - (1 << _Py_REF_SHARED_SHIFT);
394
        }
395
396
#ifdef Py_REF_DEBUG
397
        if ((new_shared < 0 && _Py_REF_IS_MERGED(new_shared)) ||
398
            (should_queue && is_dead(o)))
399
        {
400
            _Py_NegativeRefcount(filename, lineno, o);
401
        }
402
#endif
403
    } while (!_Py_atomic_compare_exchange_ssize(&o->ob_ref_shared,
404
                                                &shared, new_shared));
405
406
    if (should_queue) {
407
#ifdef Py_REF_DEBUG
408
        _Py_IncRefTotal(_PyThreadState_GET());
409
#endif
410
        _Py_brc_queue_object(o);
411
    }
412
    else if (new_shared == _Py_REF_MERGED) {
413
        // refcount is zero AND merged
414
        return 1;
415
    }
416
    return 0;
417
}
418
419
void
420
_Py_DecRefSharedDebug(PyObject *o, const char *filename, int lineno)
421
{
422
    if (_Py_DecRefSharedIsDead(o, filename, lineno)) {
423
        _Py_Dealloc(o);
424
    }
425
}
426
427
void
428
_Py_DecRefShared(PyObject *o)
429
{
430
    _Py_DecRefSharedDebug(o, NULL, 0);
431
}
432
433
void
434
_Py_MergeZeroLocalRefcount(PyObject *op)
435
{
436
    assert(op->ob_ref_local == 0);
437
438
    Py_ssize_t shared = _Py_atomic_load_ssize_acquire(&op->ob_ref_shared);
439
    if (shared == 0) {
440
        // Fast-path: shared refcount is zero (including flags)
441
        _Py_Dealloc(op);
442
        return;
443
    }
444
445
    // gh-121794: This must be before the store to `ob_ref_shared` (gh-119999),
446
    // but should outside the fast-path to maintain the invariant that
447
    // a zero `ob_tid` implies a merged refcount.
448
    _Py_atomic_store_uintptr_relaxed(&op->ob_tid, 0);
449
450
    // Slow-path: atomically set the flags (low two bits) to _Py_REF_MERGED.
451
    Py_ssize_t new_shared;
452
    do {
453
        new_shared = (shared & ~_Py_REF_SHARED_FLAG_MASK) | _Py_REF_MERGED;
454
    } while (!_Py_atomic_compare_exchange_ssize(&op->ob_ref_shared,
455
                                                &shared, new_shared));
456
457
    if (new_shared == _Py_REF_MERGED) {
458
        // i.e., the shared refcount is zero (only the flags are set) so we
459
        // deallocate the object.
460
        _Py_Dealloc(op);
461
    }
462
}
463
464
Py_ssize_t
465
_Py_ExplicitMergeRefcount(PyObject *op, Py_ssize_t extra)
466
{
467
    assert(!_Py_IsImmortal(op));
468
469
#ifdef Py_REF_DEBUG
470
    _Py_AddRefTotal(_PyThreadState_GET(), extra);
471
#endif
472
473
    // gh-119999: Write to ob_ref_local and ob_tid before merging the refcount.
474
    Py_ssize_t local = (Py_ssize_t)op->ob_ref_local;
475
    _Py_atomic_store_uint32_relaxed(&op->ob_ref_local, 0);
476
    _Py_atomic_store_uintptr_relaxed(&op->ob_tid, 0);
477
478
    Py_ssize_t refcnt;
479
    Py_ssize_t new_shared;
480
    Py_ssize_t shared = _Py_atomic_load_ssize_relaxed(&op->ob_ref_shared);
481
    do {
482
        refcnt = Py_ARITHMETIC_RIGHT_SHIFT(Py_ssize_t, shared, _Py_REF_SHARED_SHIFT);
483
        refcnt += local;
484
        refcnt += extra;
485
486
        new_shared = _Py_REF_SHARED(refcnt, _Py_REF_MERGED);
487
    } while (!_Py_atomic_compare_exchange_ssize(&op->ob_ref_shared,
488
                                                &shared, new_shared));
489
    return refcnt;
490
}
491
492
// The more complicated "slow" path for undoing the resurrection of an object.
493
int
494
_PyObject_ResurrectEndSlow(PyObject *op)
495
{
496
    if (_Py_IsImmortal(op)) {
497
        return 1;
498
    }
499
    if (_Py_IsOwnedByCurrentThread(op)) {
500
        // If the object is owned by the current thread, give up ownership and
501
        // merge the refcount. This isn't necessary in all cases, but it
502
        // simplifies the implementation.
503
        Py_ssize_t refcount = _Py_ExplicitMergeRefcount(op, -1);
504
        if (refcount == 0) {
505
#ifdef Py_TRACE_REFS
506
            _Py_ForgetReference(op);
507
#endif
508
            return 0;
509
        }
510
        return 1;
511
    }
512
    int is_dead = _Py_DecRefSharedIsDead(op, NULL, 0);
513
    if (is_dead) {
514
#ifdef Py_TRACE_REFS
515
        _Py_ForgetReference(op);
516
#endif
517
        return 0;
518
    }
519
    return 1;
520
}
521
522
523
#endif  /* Py_GIL_DISABLED */
524
525
526
/**************************************/
527
528
PyObject *
529
PyObject_Init(PyObject *op, PyTypeObject *tp)
530
0
{
531
0
    if (op == NULL) {
532
0
        return PyErr_NoMemory();
533
0
    }
534
535
0
    _PyObject_Init(op, tp);
536
0
    return op;
537
0
}
538
539
PyVarObject *
540
PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
541
0
{
542
0
    if (op == NULL) {
543
0
        return (PyVarObject *) PyErr_NoMemory();
544
0
    }
545
546
0
    _PyObject_InitVar(op, tp, size);
547
0
    return op;
548
0
}
549
550
PyObject *
551
_PyObject_New(PyTypeObject *tp)
552
558k
{
553
558k
    PyObject *op = (PyObject *) PyObject_Malloc(_PyObject_SIZE(tp));
554
558k
    if (op == NULL) {
555
0
        return PyErr_NoMemory();
556
0
    }
557
558k
    _PyObject_Init(op, tp);
558
558k
    return op;
559
558k
}
560
561
PyVarObject *
562
_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
563
100k
{
564
100k
    PyVarObject *op;
565
100k
    const size_t size = _PyObject_VAR_SIZE(tp, nitems);
566
100k
    op = (PyVarObject *) PyObject_Malloc(size);
567
100k
    if (op == NULL) {
568
0
        return (PyVarObject *)PyErr_NoMemory();
569
0
    }
570
100k
    _PyObject_InitVar(op, tp, nitems);
571
100k
    return op;
572
100k
}
573
574
void
575
PyObject_CallFinalizer(PyObject *self)
576
2.72k
{
577
2.72k
    PyTypeObject *tp = Py_TYPE(self);
578
579
2.72k
    if (tp->tp_finalize == NULL)
580
0
        return;
581
    /* tp_finalize should only be called once. */
582
2.72k
    if (_PyType_IS_GC(tp) && _PyGC_FINALIZED(self))
583
0
        return;
584
585
2.72k
    tp->tp_finalize(self);
586
2.72k
    if (_PyType_IS_GC(tp)) {
587
2.72k
        _PyGC_SET_FINALIZED(self);
588
2.72k
    }
589
2.72k
}
590
591
int
592
PyObject_CallFinalizerFromDealloc(PyObject *self)
593
2.72k
{
594
2.72k
    if (Py_REFCNT(self) != 0) {
595
0
        _PyObject_ASSERT_FAILED_MSG(self,
596
0
                                    "PyObject_CallFinalizerFromDealloc called "
597
0
                                    "on object with a non-zero refcount");
598
0
    }
599
600
    /* Temporarily resurrect the object. */
601
2.72k
    _PyObject_ResurrectStart(self);
602
603
2.72k
    PyObject_CallFinalizer(self);
604
605
2.72k
    _PyObject_ASSERT_WITH_MSG(self,
606
2.72k
                              Py_REFCNT(self) > 0,
607
2.72k
                              "refcount is too small");
608
609
2.72k
    _PyObject_ASSERT(self,
610
2.72k
                    (!_PyType_IS_GC(Py_TYPE(self))
611
2.72k
                    || _PyObject_GC_IS_TRACKED(self)));
612
613
    /* Undo the temporary resurrection; can't use DECREF here, it would
614
     * cause a recursive call. */
615
2.72k
    if (_PyObject_ResurrectEnd(self)) {
616
        /* tp_finalize resurrected it!
617
           gh-130202: Note that the object may still be dead in the free
618
           threaded build in some circumstances, so it's not safe to access
619
           `self` after this point. For example, the last reference to the
620
           resurrected `self` may be held by another thread, which can
621
           concurrently deallocate it. */
622
0
        return -1;
623
0
    }
624
625
    /* this is the normal path out, the caller continues with deallocation. */
626
2.72k
    return 0;
627
2.72k
}
628
629
int
630
PyObject_Print(PyObject *op, FILE *fp, int flags)
631
0
{
632
0
    int ret = 0;
633
0
    int write_error = 0;
634
0
    if (PyErr_CheckSignals())
635
0
        return -1;
636
0
    if (_Py_EnterRecursiveCall(" printing an object")) {
637
0
        return -1;
638
0
    }
639
0
    clearerr(fp); /* Clear any previous error condition */
640
0
    if (op == NULL) {
641
0
        Py_BEGIN_ALLOW_THREADS
642
0
        fprintf(fp, "<nil>");
643
0
        Py_END_ALLOW_THREADS
644
0
    }
645
0
    else {
646
0
        if (Py_REFCNT(op) <= 0) {
647
0
            Py_BEGIN_ALLOW_THREADS
648
0
            fprintf(fp, "<refcnt %zd at %p>", Py_REFCNT(op), (void *)op);
649
0
            Py_END_ALLOW_THREADS
650
0
        }
651
0
        else {
652
0
            PyObject *s;
653
0
            if (flags & Py_PRINT_RAW)
654
0
                s = PyObject_Str(op);
655
0
            else
656
0
                s = PyObject_Repr(op);
657
0
            if (s == NULL) {
658
0
                ret = -1;
659
0
            }
660
0
            else {
661
0
                assert(PyUnicode_Check(s));
662
0
                const char *t;
663
0
                Py_ssize_t len;
664
0
                t = PyUnicode_AsUTF8AndSize(s, &len);
665
0
                if (t == NULL) {
666
0
                    ret = -1;
667
0
                }
668
0
                else {
669
                    /* Versions of Android and OpenBSD from before 2023 fail to
670
                       set the `ferror` indicator when writing to a read-only
671
                       stream, so we need to check the return value.
672
                       (https://github.com/openbsd/src/commit/fc99cf9338942ecd9adc94ea08bf6188f0428c15) */
673
0
                    if (fwrite(t, 1, len, fp) != (size_t)len) {
674
0
                        write_error = 1;
675
0
                    }
676
0
                }
677
0
                Py_DECREF(s);
678
0
            }
679
0
        }
680
0
    }
681
0
    if (ret == 0) {
682
0
        if (write_error || ferror(fp)) {
683
0
            PyErr_SetFromErrno(PyExc_OSError);
684
0
            clearerr(fp);
685
0
            ret = -1;
686
0
        }
687
0
    }
688
0
    return ret;
689
0
}
690
691
/* For debugging convenience.  Set a breakpoint here and call it from your DLL */
692
void
693
_Py_BreakPoint(void)
694
0
{
695
0
}
696
697
698
/* Heuristic checking if the object memory is uninitialized or deallocated.
699
   Rely on the debug hooks on Python memory allocators:
700
   see _PyMem_IsPtrFreed().
701
702
   The function can be used to prevent segmentation fault on dereferencing
703
   pointers like 0xDDDDDDDDDDDDDDDD. */
704
int
705
_PyObject_IsFreed(PyObject *op)
706
470M
{
707
470M
    if (_PyMem_IsPtrFreed(op) || _PyMem_IsPtrFreed(Py_TYPE(op))) {
708
0
        return 1;
709
0
    }
710
470M
    return 0;
711
470M
}
712
713
714
/* For debugging convenience.  See Misc/gdbinit for some useful gdb hooks */
715
void
716
_PyObject_Dump(PyObject* op)
717
0
{
718
0
    if (_PyObject_IsFreed(op)) {
719
        /* It seems like the object memory has been freed:
720
           don't access it to prevent a segmentation fault. */
721
0
        fprintf(stderr, "<object at %p is freed>\n", op);
722
0
        fflush(stderr);
723
0
        return;
724
0
    }
725
726
    /* first, write fields which are the least likely to crash */
727
0
    fprintf(stderr, "object address  : %p\n", (void *)op);
728
0
    fprintf(stderr, "object refcount : %zd\n", Py_REFCNT(op));
729
0
    fflush(stderr);
730
731
0
    PyTypeObject *type = Py_TYPE(op);
732
0
    fprintf(stderr, "object type     : %p\n", type);
733
0
    fprintf(stderr, "object type name: %s\n",
734
0
            type==NULL ? "NULL" : type->tp_name);
735
736
    /* the most dangerous part */
737
0
    fprintf(stderr, "object repr     : ");
738
0
    fflush(stderr);
739
740
0
    PyGILState_STATE gil = PyGILState_Ensure();
741
0
    PyObject *exc = PyErr_GetRaisedException();
742
743
0
    (void)PyObject_Print(op, stderr, 0);
744
0
    fflush(stderr);
745
746
0
    PyErr_SetRaisedException(exc);
747
0
    PyGILState_Release(gil);
748
749
0
    fprintf(stderr, "\n");
750
0
    fflush(stderr);
751
0
}
752
753
PyObject *
754
PyObject_Repr(PyObject *v)
755
121k
{
756
121k
    PyObject *res;
757
121k
    if (PyErr_CheckSignals())
758
0
        return NULL;
759
121k
    if (v == NULL)
760
0
        return PyUnicode_FromString("<NULL>");
761
121k
    if (Py_TYPE(v)->tp_repr == NULL)
762
0
        return PyUnicode_FromFormat("<%s object at %p>",
763
0
                                    Py_TYPE(v)->tp_name, v);
764
765
121k
    PyThreadState *tstate = _PyThreadState_GET();
766
#ifdef Py_DEBUG
767
    /* PyObject_Repr() must not be called with an exception set,
768
       because it can clear it (directly or indirectly) and so the
769
       caller loses its exception */
770
    assert(!_PyErr_Occurred(tstate));
771
#endif
772
773
    /* It is possible for a type to have a tp_repr representation that loops
774
       infinitely. */
775
121k
    if (_Py_EnterRecursiveCallTstate(tstate,
776
121k
                                     " while getting the repr of an object")) {
777
0
        return NULL;
778
0
    }
779
121k
    res = (*Py_TYPE(v)->tp_repr)(v);
780
121k
    _Py_LeaveRecursiveCallTstate(tstate);
781
782
121k
    if (res == NULL) {
783
0
        return NULL;
784
0
    }
785
121k
    if (!PyUnicode_Check(res)) {
786
0
        _PyErr_Format(tstate, PyExc_TypeError,
787
0
                      "%T.__repr__() must return a str, not %T", v, res);
788
0
        Py_DECREF(res);
789
0
        return NULL;
790
0
    }
791
121k
    return res;
792
121k
}
793
794
PyObject *
795
PyObject_Str(PyObject *v)
796
700k
{
797
700k
    PyObject *res;
798
700k
    if (PyErr_CheckSignals())
799
0
        return NULL;
800
700k
    if (v == NULL)
801
0
        return PyUnicode_FromString("<NULL>");
802
700k
    if (PyUnicode_CheckExact(v)) {
803
236k
        return Py_NewRef(v);
804
236k
    }
805
463k
    if (Py_TYPE(v)->tp_str == NULL)
806
0
        return PyObject_Repr(v);
807
808
463k
    PyThreadState *tstate = _PyThreadState_GET();
809
#ifdef Py_DEBUG
810
    /* PyObject_Str() must not be called with an exception set,
811
       because it can clear it (directly or indirectly) and so the
812
       caller loses its exception */
813
    assert(!_PyErr_Occurred(tstate));
814
#endif
815
816
    /* It is possible for a type to have a tp_str representation that loops
817
       infinitely. */
818
463k
    if (_Py_EnterRecursiveCallTstate(tstate, " while getting the str of an object")) {
819
0
        return NULL;
820
0
    }
821
463k
    res = (*Py_TYPE(v)->tp_str)(v);
822
463k
    _Py_LeaveRecursiveCallTstate(tstate);
823
824
463k
    if (res == NULL) {
825
0
        return NULL;
826
0
    }
827
463k
    if (!PyUnicode_Check(res)) {
828
0
        _PyErr_Format(tstate, PyExc_TypeError,
829
0
                      "%T.__str__() must return a str, not %T", v, res);
830
0
        Py_DECREF(res);
831
0
        return NULL;
832
0
    }
833
463k
    assert(_PyUnicode_CheckConsistency(res, 1));
834
463k
    return res;
835
463k
}
836
837
PyObject *
838
PyObject_ASCII(PyObject *v)
839
285
{
840
285
    PyObject *repr, *ascii, *res;
841
842
285
    repr = PyObject_Repr(v);
843
285
    if (repr == NULL)
844
0
        return NULL;
845
846
285
    if (PyUnicode_IS_ASCII(repr))
847
14
        return repr;
848
849
    /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */
850
271
    ascii = _PyUnicode_AsASCIIString(repr, "backslashreplace");
851
271
    Py_DECREF(repr);
852
271
    if (ascii == NULL)
853
0
        return NULL;
854
855
271
    res = PyUnicode_DecodeASCII(
856
271
        PyBytes_AS_STRING(ascii),
857
271
        PyBytes_GET_SIZE(ascii),
858
271
        NULL);
859
860
271
    Py_DECREF(ascii);
861
271
    return res;
862
271
}
863
864
PyObject *
865
PyObject_Bytes(PyObject *v)
866
1.02k
{
867
1.02k
    PyObject *result, *func;
868
869
1.02k
    if (v == NULL)
870
0
        return PyBytes_FromString("<NULL>");
871
872
1.02k
    if (PyBytes_CheckExact(v)) {
873
1.02k
        return Py_NewRef(v);
874
1.02k
    }
875
876
0
    func = _PyObject_LookupSpecial(v, &_Py_ID(__bytes__));
877
0
    if (func != NULL) {
878
0
        result = _PyObject_CallNoArgs(func);
879
0
        Py_DECREF(func);
880
0
        if (result == NULL)
881
0
            return NULL;
882
0
        if (!PyBytes_Check(result)) {
883
0
            PyErr_Format(PyExc_TypeError,
884
0
                         "%T.__bytes__() must return a bytes, not %T",
885
0
                         v, result);
886
0
            Py_DECREF(result);
887
0
            return NULL;
888
0
        }
889
0
        return result;
890
0
    }
891
0
    else if (PyErr_Occurred())
892
0
        return NULL;
893
0
    return PyBytes_FromObject(v);
894
0
}
895
896
static void
897
clear_freelist(struct _Py_freelist *freelist, int is_finalization,
898
               freefunc dofree)
899
0
{
900
0
    void *ptr;
901
0
    while ((ptr = _PyFreeList_PopNoStats(freelist)) != NULL) {
902
0
        dofree(ptr);
903
0
    }
904
0
    assert(freelist->size == 0 || freelist->size == -1);
905
0
    assert(freelist->freelist == NULL);
906
0
    if (is_finalization) {
907
0
        freelist->size = -1;
908
0
    }
909
0
}
910
911
static void
912
free_object(void *obj)
913
0
{
914
0
    PyObject *op = (PyObject *)obj;
915
0
    PyTypeObject *tp = Py_TYPE(op);
916
0
    tp->tp_free(op);
917
0
    Py_DECREF(tp);
918
0
}
919
920
void
921
_PyObject_ClearFreeLists(struct _Py_freelists *freelists, int is_finalization)
922
0
{
923
    // In the free-threaded build, freelists are per-PyThreadState and cleared in PyThreadState_Clear()
924
    // In the default build, freelists are per-interpreter and cleared in finalize_interp_types()
925
0
    clear_freelist(&freelists->floats, is_finalization, free_object);
926
0
    clear_freelist(&freelists->complexes, is_finalization, free_object);
927
0
    for (Py_ssize_t i = 0; i < PyTuple_MAXSAVESIZE; i++) {
928
0
        clear_freelist(&freelists->tuples[i], is_finalization, free_object);
929
0
    }
930
0
    clear_freelist(&freelists->lists, is_finalization, free_object);
931
0
    clear_freelist(&freelists->list_iters, is_finalization, free_object);
932
0
    clear_freelist(&freelists->tuple_iters, is_finalization, free_object);
933
0
    clear_freelist(&freelists->dicts, is_finalization, free_object);
934
0
    clear_freelist(&freelists->dictkeys, is_finalization, PyMem_Free);
935
0
    clear_freelist(&freelists->slices, is_finalization, free_object);
936
0
    clear_freelist(&freelists->ranges, is_finalization, free_object);
937
0
    clear_freelist(&freelists->range_iters, is_finalization, free_object);
938
0
    clear_freelist(&freelists->contexts, is_finalization, free_object);
939
0
    clear_freelist(&freelists->async_gens, is_finalization, free_object);
940
0
    clear_freelist(&freelists->async_gen_asends, is_finalization, free_object);
941
0
    clear_freelist(&freelists->futureiters, is_finalization, free_object);
942
0
    if (is_finalization) {
943
        // Only clear object stack chunks during finalization. We use object
944
        // stacks during GC, so emptying the free-list is counterproductive.
945
0
        clear_freelist(&freelists->object_stack_chunks, 1, PyMem_RawFree);
946
0
    }
947
0
    clear_freelist(&freelists->unicode_writers, is_finalization, PyMem_Free);
948
0
    clear_freelist(&freelists->ints, is_finalization, free_object);
949
0
    clear_freelist(&freelists->pycfunctionobject, is_finalization, PyObject_GC_Del);
950
0
    clear_freelist(&freelists->pycmethodobject, is_finalization, PyObject_GC_Del);
951
0
    clear_freelist(&freelists->pymethodobjects, is_finalization, free_object);
952
0
}
953
954
/*
955
def _PyObject_FunctionStr(x):
956
    try:
957
        qualname = x.__qualname__
958
    except AttributeError:
959
        return str(x)
960
    try:
961
        mod = x.__module__
962
        if mod is not None and mod != 'builtins':
963
            return f"{x.__module__}.{qualname}()"
964
    except AttributeError:
965
        pass
966
    return qualname
967
*/
968
PyObject *
969
_PyObject_FunctionStr(PyObject *x)
970
0
{
971
0
    assert(!PyErr_Occurred());
972
0
    PyObject *qualname;
973
0
    int ret = PyObject_GetOptionalAttr(x, &_Py_ID(__qualname__), &qualname);
974
0
    if (qualname == NULL) {
975
0
        if (ret < 0) {
976
0
            return NULL;
977
0
        }
978
0
        return PyObject_Str(x);
979
0
    }
980
0
    PyObject *module;
981
0
    PyObject *result = NULL;
982
0
    ret = PyObject_GetOptionalAttr(x, &_Py_ID(__module__), &module);
983
0
    if (module != NULL && module != Py_None) {
984
0
        ret = PyObject_RichCompareBool(module, &_Py_ID(builtins), Py_NE);
985
0
        if (ret < 0) {
986
            // error
987
0
            goto done;
988
0
        }
989
0
        if (ret > 0) {
990
0
            result = PyUnicode_FromFormat("%S.%S()", module, qualname);
991
0
            goto done;
992
0
        }
993
0
    }
994
0
    else if (ret < 0) {
995
0
        goto done;
996
0
    }
997
0
    result = PyUnicode_FromFormat("%S()", qualname);
998
0
done:
999
0
    Py_DECREF(qualname);
1000
0
    Py_XDECREF(module);
1001
0
    return result;
1002
0
}
1003
1004
/* For Python 3.0.1 and later, the old three-way comparison has been
1005
   completely removed in favour of rich comparisons.  PyObject_Compare() and
1006
   PyObject_Cmp() are gone, and the builtin cmp function no longer exists.
1007
   The old tp_compare slot has been renamed to tp_as_async, and should no
1008
   longer be used.  Use tp_richcompare instead.
1009
1010
   See (*) below for practical amendments.
1011
1012
   tp_richcompare gets called with a first argument of the appropriate type
1013
   and a second object of an arbitrary type.  We never do any kind of
1014
   coercion.
1015
1016
   The tp_richcompare slot should return an object, as follows:
1017
1018
    NULL if an exception occurred
1019
    NotImplemented if the requested comparison is not implemented
1020
    any other false value if the requested comparison is false
1021
    any other true value if the requested comparison is true
1022
1023
  The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get
1024
  NotImplemented.
1025
1026
  (*) Practical amendments:
1027
1028
  - If rich comparison returns NotImplemented, == and != are decided by
1029
    comparing the object pointer (i.e. falling back to the base object
1030
    implementation).
1031
1032
*/
1033
1034
/* Map rich comparison operators to their swapped version, e.g. LT <--> GT */
1035
int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
1036
1037
static const char * const opstrings[] = {"<", "<=", "==", "!=", ">", ">="};
1038
1039
/* Perform a rich comparison, raising TypeError when the requested comparison
1040
   operator is not supported. */
1041
static PyObject *
1042
do_richcompare(PyThreadState *tstate, PyObject *v, PyObject *w, int op)
1043
47.9M
{
1044
47.9M
    richcmpfunc f;
1045
47.9M
    PyObject *res;
1046
47.9M
    int checked_reverse_op = 0;
1047
1048
47.9M
    if (!Py_IS_TYPE(v, Py_TYPE(w)) &&
1049
47.9M
        PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v)) &&
1050
47.9M
        (f = Py_TYPE(w)->tp_richcompare) != NULL) {
1051
424k
        checked_reverse_op = 1;
1052
424k
        res = (*f)(w, v, _Py_SwappedOp[op]);
1053
424k
        if (res != Py_NotImplemented)
1054
424k
            return res;
1055
21
        Py_DECREF(res);
1056
21
    }
1057
47.5M
    if ((f = Py_TYPE(v)->tp_richcompare) != NULL) {
1058
47.5M
        res = (*f)(v, w, op);
1059
47.5M
        if (res != Py_NotImplemented)
1060
47.4M
            return res;
1061
58.7k
        Py_DECREF(res);
1062
58.7k
    }
1063
58.7k
    if (!checked_reverse_op && (f = Py_TYPE(w)->tp_richcompare) != NULL) {
1064
58.7k
        res = (*f)(w, v, _Py_SwappedOp[op]);
1065
58.7k
        if (res != Py_NotImplemented)
1066
23.6k
            return res;
1067
35.0k
        Py_DECREF(res);
1068
35.0k
    }
1069
    /* If neither object implements it, provide a sensible default
1070
       for == and !=, but raise an exception for ordering. */
1071
35.0k
    switch (op) {
1072
35.0k
    case Py_EQ:
1073
35.0k
        res = (v == w) ? Py_True : Py_False;
1074
35.0k
        break;
1075
0
    case Py_NE:
1076
0
        res = (v != w) ? Py_True : Py_False;
1077
0
        break;
1078
0
    default:
1079
0
        _PyErr_Format(tstate, PyExc_TypeError,
1080
0
                      "'%s' not supported between instances of '%.100s' and '%.100s'",
1081
0
                      opstrings[op],
1082
0
                      Py_TYPE(v)->tp_name,
1083
0
                      Py_TYPE(w)->tp_name);
1084
0
        return NULL;
1085
35.0k
    }
1086
35.0k
    return Py_NewRef(res);
1087
35.0k
}
1088
1089
/* Perform a rich comparison with object result.  This wraps do_richcompare()
1090
   with a check for NULL arguments and a recursion check. */
1091
1092
PyObject *
1093
PyObject_RichCompare(PyObject *v, PyObject *w, int op)
1094
47.9M
{
1095
47.9M
    PyThreadState *tstate = _PyThreadState_GET();
1096
1097
47.9M
    assert(Py_LT <= op && op <= Py_GE);
1098
47.9M
    if (v == NULL || w == NULL) {
1099
0
        if (!_PyErr_Occurred(tstate)) {
1100
0
            PyErr_BadInternalCall();
1101
0
        }
1102
0
        return NULL;
1103
0
    }
1104
47.9M
    if (_Py_EnterRecursiveCallTstate(tstate, " in comparison")) {
1105
0
        return NULL;
1106
0
    }
1107
47.9M
    PyObject *res = do_richcompare(tstate, v, w, op);
1108
47.9M
    _Py_LeaveRecursiveCallTstate(tstate);
1109
47.9M
    return res;
1110
47.9M
}
1111
1112
/* Perform a rich comparison with integer result.  This wraps
1113
   PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */
1114
int
1115
PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
1116
71.5M
{
1117
71.5M
    PyObject *res;
1118
71.5M
    int ok;
1119
1120
    /* Quick result when objects are the same.
1121
       Guarantees that identity implies equality. */
1122
71.5M
    if (v == w) {
1123
36.8M
        if (op == Py_EQ)
1124
34.5M
            return 1;
1125
2.35M
        else if (op == Py_NE)
1126
0
            return 0;
1127
36.8M
    }
1128
1129
37.0M
    res = PyObject_RichCompare(v, w, op);
1130
37.0M
    if (res == NULL)
1131
0
        return -1;
1132
37.0M
    if (PyBool_Check(res)) {
1133
37.0M
        ok = (res == Py_True);
1134
37.0M
        assert(_Py_IsImmortal(res));
1135
37.0M
    }
1136
0
    else {
1137
0
        ok = PyObject_IsTrue(res);
1138
0
        Py_DECREF(res);
1139
0
    }
1140
37.0M
    return ok;
1141
37.0M
}
1142
1143
Py_hash_t
1144
PyObject_HashNotImplemented(PyObject *v)
1145
0
{
1146
0
    PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
1147
0
                 Py_TYPE(v)->tp_name);
1148
0
    return -1;
1149
0
}
1150
1151
Py_hash_t
1152
PyObject_Hash(PyObject *v)
1153
931M
{
1154
931M
    PyTypeObject *tp = Py_TYPE(v);
1155
931M
    if (tp->tp_hash != NULL)
1156
931M
        return (*tp->tp_hash)(v);
1157
    /* To keep to the general practice that inheriting
1158
     * solely from object in C code should work without
1159
     * an explicit call to PyType_Ready, we implicitly call
1160
     * PyType_Ready here and then check the tp_hash slot again
1161
     */
1162
0
    if (!_PyType_IsReady(tp)) {
1163
0
        if (PyType_Ready(tp) < 0)
1164
0
            return -1;
1165
0
        if (tp->tp_hash != NULL)
1166
0
            return (*tp->tp_hash)(v);
1167
0
    }
1168
    /* Otherwise, the object can't be hashed */
1169
0
    return PyObject_HashNotImplemented(v);
1170
0
}
1171
1172
PyObject *
1173
PyObject_GetAttrString(PyObject *v, const char *name)
1174
201k
{
1175
201k
    PyObject *w, *res;
1176
1177
201k
    if (Py_TYPE(v)->tp_getattr != NULL)
1178
0
        return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
1179
201k
    w = PyUnicode_FromString(name);
1180
201k
    if (w == NULL)
1181
0
        return NULL;
1182
201k
    res = PyObject_GetAttr(v, w);
1183
201k
    Py_DECREF(w);
1184
201k
    return res;
1185
201k
}
1186
1187
int
1188
PyObject_HasAttrStringWithError(PyObject *obj, const char *name)
1189
0
{
1190
0
    PyObject *res;
1191
0
    int rc = PyObject_GetOptionalAttrString(obj, name, &res);
1192
0
    Py_XDECREF(res);
1193
0
    return rc;
1194
0
}
1195
1196
1197
int
1198
PyObject_HasAttrString(PyObject *obj, const char *name)
1199
0
{
1200
0
    int rc = PyObject_HasAttrStringWithError(obj, name);
1201
0
    if (rc < 0) {
1202
0
        PyErr_FormatUnraisable(
1203
0
            "Exception ignored in PyObject_HasAttrString(); consider using "
1204
0
            "PyObject_HasAttrStringWithError(), "
1205
0
            "PyObject_GetOptionalAttrString() or PyObject_GetAttrString()");
1206
0
        return 0;
1207
0
    }
1208
0
    return rc;
1209
0
}
1210
1211
int
1212
PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
1213
41.4k
{
1214
41.4k
    PyThreadState *tstate = _PyThreadState_GET();
1215
41.4k
    if (w == NULL && _PyErr_Occurred(tstate)) {
1216
0
        PyObject *exc = _PyErr_GetRaisedException(tstate);
1217
0
        _PyErr_SetString(tstate, PyExc_SystemError,
1218
0
            "PyObject_SetAttrString() must not be called with NULL value "
1219
0
            "and an exception set");
1220
0
        _PyErr_ChainExceptions1Tstate(tstate, exc);
1221
0
        return -1;
1222
0
    }
1223
1224
41.4k
    if (Py_TYPE(v)->tp_setattr != NULL) {
1225
0
        return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
1226
0
    }
1227
1228
41.4k
    PyObject *s = PyUnicode_InternFromString(name);
1229
41.4k
    if (s == NULL) {
1230
0
        return -1;
1231
0
    }
1232
1233
41.4k
    int res = PyObject_SetAttr(v, s, w);
1234
41.4k
    Py_DECREF(s);
1235
41.4k
    return res;
1236
41.4k
}
1237
1238
int
1239
PyObject_DelAttrString(PyObject *v, const char *name)
1240
0
{
1241
0
    return PyObject_SetAttrString(v, name, NULL);
1242
0
}
1243
1244
int
1245
_PyObject_IsAbstract(PyObject *obj)
1246
9.92k
{
1247
9.92k
    int res;
1248
9.92k
    PyObject* isabstract;
1249
1250
9.92k
    if (obj == NULL)
1251
78
        return 0;
1252
1253
9.84k
    res = PyObject_GetOptionalAttr(obj, &_Py_ID(__isabstractmethod__), &isabstract);
1254
9.84k
    if (res > 0) {
1255
2.07k
        res = PyObject_IsTrue(isabstract);
1256
2.07k
        Py_DECREF(isabstract);
1257
2.07k
    }
1258
9.84k
    return res;
1259
9.92k
}
1260
1261
PyObject *
1262
_PyObject_GetAttrId(PyObject *v, _Py_Identifier *name)
1263
0
{
1264
0
    PyObject *result;
1265
0
    PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
1266
0
    if (!oname)
1267
0
        return NULL;
1268
0
    result = PyObject_GetAttr(v, oname);
1269
0
    return result;
1270
0
}
1271
1272
int
1273
_PyObject_SetAttributeErrorContext(PyObject* v, PyObject* name)
1274
96.8k
{
1275
96.8k
    assert(PyErr_Occurred());
1276
96.8k
    if (!PyErr_ExceptionMatches(PyExc_AttributeError)){
1277
0
        return 0;
1278
0
    }
1279
    // Intercept AttributeError exceptions and augment them to offer suggestions later.
1280
96.8k
    PyObject *exc = PyErr_GetRaisedException();
1281
96.8k
    if (!PyErr_GivenExceptionMatches(exc, PyExc_AttributeError)) {
1282
0
        goto restore;
1283
0
    }
1284
96.8k
    PyAttributeErrorObject* the_exc = (PyAttributeErrorObject*) exc;
1285
    // Check if this exception was already augmented
1286
96.8k
    if (the_exc->name || the_exc->obj) {
1287
47.8k
        goto restore;
1288
47.8k
    }
1289
    // Augment the exception with the name and object
1290
48.9k
    if (PyObject_SetAttr(exc, &_Py_ID(name), name) ||
1291
48.9k
        PyObject_SetAttr(exc, &_Py_ID(obj), v)) {
1292
0
        return 1;
1293
0
    }
1294
96.8k
restore:
1295
96.8k
    PyErr_SetRaisedException(exc);
1296
96.8k
    return 0;
1297
48.9k
}
1298
1299
PyObject *
1300
PyObject_GetAttr(PyObject *v, PyObject *name)
1301
15.7M
{
1302
15.7M
    PyTypeObject *tp = Py_TYPE(v);
1303
15.7M
    if (!PyUnicode_Check(name)) {
1304
0
        PyErr_Format(PyExc_TypeError,
1305
0
                     "attribute name must be string, not '%.200s'",
1306
0
                     Py_TYPE(name)->tp_name);
1307
0
        return NULL;
1308
0
    }
1309
1310
15.7M
    PyObject* result = NULL;
1311
15.7M
    if (tp->tp_getattro != NULL) {
1312
15.7M
        result = (*tp->tp_getattro)(v, name);
1313
15.7M
    }
1314
0
    else if (tp->tp_getattr != NULL) {
1315
0
        const char *name_str = PyUnicode_AsUTF8(name);
1316
0
        if (name_str == NULL) {
1317
0
            return NULL;
1318
0
        }
1319
0
        result = (*tp->tp_getattr)(v, (char *)name_str);
1320
0
    }
1321
0
    else {
1322
0
        PyErr_Format(PyExc_AttributeError,
1323
0
                    "'%.100s' object has no attribute '%U'",
1324
0
                    tp->tp_name, name);
1325
0
    }
1326
1327
15.7M
    if (result == NULL) {
1328
48.4k
        _PyObject_SetAttributeErrorContext(v, name);
1329
48.4k
    }
1330
15.7M
    return result;
1331
15.7M
}
1332
1333
int
1334
PyObject_GetOptionalAttr(PyObject *v, PyObject *name, PyObject **result)
1335
24.6M
{
1336
24.6M
    PyTypeObject *tp = Py_TYPE(v);
1337
1338
24.6M
    if (!PyUnicode_Check(name)) {
1339
0
        PyErr_Format(PyExc_TypeError,
1340
0
                     "attribute name must be string, not '%.200s'",
1341
0
                     Py_TYPE(name)->tp_name);
1342
0
        *result = NULL;
1343
0
        return -1;
1344
0
    }
1345
1346
24.6M
    if (tp->tp_getattro == PyObject_GenericGetAttr) {
1347
20.7M
        *result = _PyObject_GenericGetAttrWithDict(v, name, NULL, 1);
1348
20.7M
        if (*result != NULL) {
1349
20.4M
            return 1;
1350
20.4M
        }
1351
278k
        if (PyErr_Occurred()) {
1352
0
            return -1;
1353
0
        }
1354
278k
        return 0;
1355
278k
    }
1356
3.95M
    if (tp->tp_getattro == _Py_type_getattro) {
1357
7.93k
        int suppress_missing_attribute_exception = 0;
1358
7.93k
        *result = _Py_type_getattro_impl((PyTypeObject*)v, name, &suppress_missing_attribute_exception);
1359
7.93k
        if (suppress_missing_attribute_exception) {
1360
            // return 0 without having to clear the exception
1361
256
            return 0;
1362
256
        }
1363
7.93k
    }
1364
3.94M
    else if (tp->tp_getattro == (getattrofunc)_Py_module_getattro) {
1365
        // optimization: suppress attribute error from module getattro method
1366
3.94M
        *result = _Py_module_getattro_impl((PyModuleObject*)v, name, 1);
1367
3.94M
        if (*result != NULL) {
1368
3.94M
            return 1;
1369
3.94M
        }
1370
2.82k
        if (PyErr_Occurred()) {
1371
0
            return -1;
1372
0
        }
1373
2.82k
        return 0;
1374
2.82k
    }
1375
0
    else if (tp->tp_getattro != NULL) {
1376
0
        *result = (*tp->tp_getattro)(v, name);
1377
0
    }
1378
0
    else if (tp->tp_getattr != NULL) {
1379
0
        const char *name_str = PyUnicode_AsUTF8(name);
1380
0
        if (name_str == NULL) {
1381
0
            *result = NULL;
1382
0
            return -1;
1383
0
        }
1384
0
        *result = (*tp->tp_getattr)(v, (char *)name_str);
1385
0
    }
1386
0
    else {
1387
0
        *result = NULL;
1388
0
        return 0;
1389
0
    }
1390
1391
7.67k
    if (*result != NULL) {
1392
7.44k
        return 1;
1393
7.44k
    }
1394
232
    if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
1395
0
        return -1;
1396
0
    }
1397
232
    PyErr_Clear();
1398
232
    return 0;
1399
232
}
1400
1401
int
1402
PyObject_GetOptionalAttrString(PyObject *obj, const char *name, PyObject **result)
1403
0
{
1404
0
    if (Py_TYPE(obj)->tp_getattr == NULL) {
1405
0
        PyObject *oname = PyUnicode_FromString(name);
1406
0
        if (oname == NULL) {
1407
0
            *result = NULL;
1408
0
            return -1;
1409
0
        }
1410
0
        int rc = PyObject_GetOptionalAttr(obj, oname, result);
1411
0
        Py_DECREF(oname);
1412
0
        return rc;
1413
0
    }
1414
1415
0
    *result = (*Py_TYPE(obj)->tp_getattr)(obj, (char*)name);
1416
0
    if (*result != NULL) {
1417
0
        return 1;
1418
0
    }
1419
0
    if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
1420
0
        return -1;
1421
0
    }
1422
0
    PyErr_Clear();
1423
0
    return 0;
1424
0
}
1425
1426
int
1427
PyObject_HasAttrWithError(PyObject *obj, PyObject *name)
1428
6.63k
{
1429
6.63k
    PyObject *res;
1430
6.63k
    int rc = PyObject_GetOptionalAttr(obj, name, &res);
1431
6.63k
    Py_XDECREF(res);
1432
6.63k
    return rc;
1433
6.63k
}
1434
1435
int
1436
PyObject_HasAttr(PyObject *obj, PyObject *name)
1437
0
{
1438
0
    int rc = PyObject_HasAttrWithError(obj, name);
1439
0
    if (rc < 0) {
1440
0
        PyErr_FormatUnraisable(
1441
0
            "Exception ignored in PyObject_HasAttr(); consider using "
1442
0
            "PyObject_HasAttrWithError(), "
1443
0
            "PyObject_GetOptionalAttr() or PyObject_GetAttr()");
1444
0
        return 0;
1445
0
    }
1446
0
    return rc;
1447
0
}
1448
1449
int
1450
PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
1451
367k
{
1452
367k
    PyThreadState *tstate = _PyThreadState_GET();
1453
367k
    if (value == NULL && _PyErr_Occurred(tstate)) {
1454
0
        PyObject *exc = _PyErr_GetRaisedException(tstate);
1455
0
        _PyErr_SetString(tstate, PyExc_SystemError,
1456
0
            "PyObject_SetAttr() must not be called with NULL value "
1457
0
            "and an exception set");
1458
0
        _PyErr_ChainExceptions1Tstate(tstate, exc);
1459
0
        return -1;
1460
0
    }
1461
1462
367k
    PyTypeObject *tp = Py_TYPE(v);
1463
367k
    int err;
1464
1465
367k
    if (!PyUnicode_Check(name)) {
1466
0
        PyErr_Format(PyExc_TypeError,
1467
0
                     "attribute name must be string, not '%.200s'",
1468
0
                     Py_TYPE(name)->tp_name);
1469
0
        return -1;
1470
0
    }
1471
367k
    Py_INCREF(name);
1472
1473
367k
    _PyUnicode_InternMortal(tstate->interp, &name);
1474
367k
    if (tp->tp_setattro != NULL) {
1475
367k
        err = (*tp->tp_setattro)(v, name, value);
1476
367k
        Py_DECREF(name);
1477
367k
        return err;
1478
367k
    }
1479
0
    if (tp->tp_setattr != NULL) {
1480
0
        const char *name_str = PyUnicode_AsUTF8(name);
1481
0
        if (name_str == NULL) {
1482
0
            Py_DECREF(name);
1483
0
            return -1;
1484
0
        }
1485
0
        err = (*tp->tp_setattr)(v, (char *)name_str, value);
1486
0
        Py_DECREF(name);
1487
0
        return err;
1488
0
    }
1489
0
    Py_DECREF(name);
1490
0
    _PyObject_ASSERT(name, Py_REFCNT(name) >= 1);
1491
0
    if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1492
0
        PyErr_Format(PyExc_TypeError,
1493
0
                     "'%.100s' object has no attributes "
1494
0
                     "(%s .%U)",
1495
0
                     tp->tp_name,
1496
0
                     value==NULL ? "del" : "assign to",
1497
0
                     name);
1498
0
    else
1499
0
        PyErr_Format(PyExc_TypeError,
1500
0
                     "'%.100s' object has only read-only attributes "
1501
0
                     "(%s .%U)",
1502
0
                     tp->tp_name,
1503
0
                     value==NULL ? "del" : "assign to",
1504
0
                     name);
1505
0
    return -1;
1506
0
}
1507
1508
int
1509
PyObject_DelAttr(PyObject *v, PyObject *name)
1510
252
{
1511
252
    return PyObject_SetAttr(v, name, NULL);
1512
252
}
1513
1514
PyObject **
1515
_PyObject_ComputedDictPointer(PyObject *obj)
1516
11.0M
{
1517
11.0M
    PyTypeObject *tp = Py_TYPE(obj);
1518
11.0M
    assert((tp->tp_flags & Py_TPFLAGS_MANAGED_DICT) == 0);
1519
1520
11.0M
    Py_ssize_t dictoffset = tp->tp_dictoffset;
1521
11.0M
    if (dictoffset == 0) {
1522
5.97M
        return NULL;
1523
5.97M
    }
1524
1525
5.10M
    if (dictoffset < 0) {
1526
0
        assert(dictoffset != -1);
1527
1528
0
        Py_ssize_t tsize = Py_SIZE(obj);
1529
0
        if (tsize < 0) {
1530
0
            tsize = -tsize;
1531
0
        }
1532
0
        size_t size = _PyObject_VAR_SIZE(tp, tsize);
1533
0
        assert(size <= (size_t)PY_SSIZE_T_MAX);
1534
0
        dictoffset += (Py_ssize_t)size;
1535
1536
0
        _PyObject_ASSERT(obj, dictoffset > 0);
1537
0
        _PyObject_ASSERT(obj, dictoffset % SIZEOF_VOID_P == 0);
1538
0
    }
1539
5.10M
    return (PyObject **) ((char *)obj + dictoffset);
1540
5.10M
}
1541
1542
/* Helper to get a pointer to an object's __dict__ slot, if any.
1543
 * Creates the dict from inline attributes if necessary.
1544
 * Does not set an exception.
1545
 *
1546
 * Note that the tp_dictoffset docs used to recommend this function,
1547
 * so it should be treated as part of the public API.
1548
 */
1549
PyObject **
1550
_PyObject_GetDictPtr(PyObject *obj)
1551
0
{
1552
0
    if ((Py_TYPE(obj)->tp_flags & Py_TPFLAGS_MANAGED_DICT) == 0) {
1553
0
        return _PyObject_ComputedDictPointer(obj);
1554
0
    }
1555
0
    PyDictObject *dict = _PyObject_GetManagedDict(obj);
1556
0
    if (dict == NULL && Py_TYPE(obj)->tp_flags & Py_TPFLAGS_INLINE_VALUES) {
1557
0
        dict = _PyObject_MaterializeManagedDict(obj);
1558
0
        if (dict == NULL) {
1559
0
            PyErr_Clear();
1560
0
            return NULL;
1561
0
        }
1562
0
    }
1563
0
    return (PyObject **)&_PyObject_ManagedDictPointer(obj)->dict;
1564
0
}
1565
1566
PyObject *
1567
PyObject_SelfIter(PyObject *obj)
1568
380k
{
1569
380k
    return Py_NewRef(obj);
1570
380k
}
1571
1572
/* Helper used when the __next__ method is removed from a type:
1573
   tp_iternext is never NULL and can be safely called without checking
1574
   on every iteration.
1575
 */
1576
1577
PyObject *
1578
_PyObject_NextNotImplemented(PyObject *self)
1579
0
{
1580
0
    PyErr_Format(PyExc_TypeError,
1581
0
                 "'%.200s' object is not iterable",
1582
0
                 Py_TYPE(self)->tp_name);
1583
0
    return NULL;
1584
0
}
1585
1586
1587
/* Specialized version of _PyObject_GenericGetAttrWithDict
1588
   specifically for the LOAD_METHOD opcode.
1589
1590
   Return 1 if a method is found, 0 if it's a regular attribute
1591
   from __dict__ or something returned by using a descriptor
1592
   protocol.
1593
1594
   `method` will point to the resolved attribute or NULL.  In the
1595
   latter case, an error will be set.
1596
*/
1597
int
1598
_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method)
1599
0
{
1600
0
    int meth_found = 0;
1601
1602
0
    assert(*method == NULL);
1603
1604
0
    PyTypeObject *tp = Py_TYPE(obj);
1605
0
    if (!_PyType_IsReady(tp)) {
1606
0
        if (PyType_Ready(tp) < 0) {
1607
0
            return 0;
1608
0
        }
1609
0
    }
1610
1611
0
    if (tp->tp_getattro != PyObject_GenericGetAttr || !PyUnicode_CheckExact(name)) {
1612
0
        *method = PyObject_GetAttr(obj, name);
1613
0
        return 0;
1614
0
    }
1615
1616
0
    PyObject *descr = _PyType_LookupRef(tp, name);
1617
0
    descrgetfunc f = NULL;
1618
0
    if (descr != NULL) {
1619
0
        if (_PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_METHOD_DESCRIPTOR)) {
1620
0
            meth_found = 1;
1621
0
        }
1622
0
        else {
1623
0
            f = Py_TYPE(descr)->tp_descr_get;
1624
0
            if (f != NULL && PyDescr_IsData(descr)) {
1625
0
                *method = f(descr, obj, (PyObject *)Py_TYPE(obj));
1626
0
                Py_DECREF(descr);
1627
0
                return 0;
1628
0
            }
1629
0
        }
1630
0
    }
1631
0
    PyObject *dict, *attr;
1632
0
    if ((tp->tp_flags & Py_TPFLAGS_INLINE_VALUES) &&
1633
0
         _PyObject_TryGetInstanceAttribute(obj, name, &attr)) {
1634
0
        if (attr != NULL) {
1635
0
            *method = attr;
1636
0
            Py_XDECREF(descr);
1637
0
            return 0;
1638
0
        }
1639
0
        dict = NULL;
1640
0
    }
1641
0
    else if ((tp->tp_flags & Py_TPFLAGS_MANAGED_DICT)) {
1642
0
        dict = (PyObject *)_PyObject_GetManagedDict(obj);
1643
0
    }
1644
0
    else {
1645
0
        PyObject **dictptr = _PyObject_ComputedDictPointer(obj);
1646
0
        if (dictptr != NULL) {
1647
0
            dict = FT_ATOMIC_LOAD_PTR_ACQUIRE(*dictptr);
1648
0
        }
1649
0
        else {
1650
0
            dict = NULL;
1651
0
        }
1652
0
    }
1653
0
    if (dict != NULL) {
1654
0
        Py_INCREF(dict);
1655
0
        if (PyDict_GetItemRef(dict, name, method) != 0) {
1656
            // found or error
1657
0
            Py_DECREF(dict);
1658
0
            Py_XDECREF(descr);
1659
0
            return 0;
1660
0
        }
1661
        // not found
1662
0
        Py_DECREF(dict);
1663
0
    }
1664
1665
0
    if (meth_found) {
1666
0
        *method = descr;
1667
0
        return 1;
1668
0
    }
1669
1670
0
    if (f != NULL) {
1671
0
        *method = f(descr, obj, (PyObject *)Py_TYPE(obj));
1672
0
        Py_DECREF(descr);
1673
0
        return 0;
1674
0
    }
1675
1676
0
    if (descr != NULL) {
1677
0
        *method = descr;
1678
0
        return 0;
1679
0
    }
1680
1681
0
    PyErr_Format(PyExc_AttributeError,
1682
0
                 "'%.100s' object has no attribute '%U'",
1683
0
                 tp->tp_name, name);
1684
1685
0
    _PyObject_SetAttributeErrorContext(obj, name);
1686
0
    return 0;
1687
0
}
1688
1689
int
1690
_PyObject_GetMethodStackRef(PyThreadState *ts, PyObject *obj,
1691
                            PyObject *name, _PyStackRef *method)
1692
1.21M
{
1693
1.21M
    int meth_found = 0;
1694
1695
1.21M
    assert(PyStackRef_IsNull(*method));
1696
1697
1.21M
    PyTypeObject *tp = Py_TYPE(obj);
1698
1.21M
    if (!_PyType_IsReady(tp)) {
1699
0
        if (PyType_Ready(tp) < 0) {
1700
0
            return 0;
1701
0
        }
1702
0
    }
1703
1704
1.21M
    if (tp->tp_getattro != PyObject_GenericGetAttr || !PyUnicode_CheckExact(name)) {
1705
254k
        PyObject *res = PyObject_GetAttr(obj, name);
1706
254k
        if (res != NULL) {
1707
254k
            *method = PyStackRef_FromPyObjectSteal(res);
1708
254k
        }
1709
254k
        return 0;
1710
254k
    }
1711
1712
957k
    _PyType_LookupStackRefAndVersion(tp, name, method);
1713
957k
    PyObject *descr = PyStackRef_AsPyObjectBorrow(*method);
1714
957k
    descrgetfunc f = NULL;
1715
957k
    if (descr != NULL) {
1716
957k
        if (_PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_METHOD_DESCRIPTOR)) {
1717
957k
            meth_found = 1;
1718
957k
        }
1719
11
        else {
1720
11
            f = Py_TYPE(descr)->tp_descr_get;
1721
11
            if (f != NULL && PyDescr_IsData(descr)) {
1722
11
                PyObject *value = f(descr, obj, (PyObject *)Py_TYPE(obj));
1723
11
                PyStackRef_CLEAR(*method);
1724
11
                if (value != NULL) {
1725
11
                    *method = PyStackRef_FromPyObjectSteal(value);
1726
11
                }
1727
11
                return 0;
1728
11
            }
1729
11
        }
1730
957k
    }
1731
957k
    PyObject *dict, *attr;
1732
957k
    if ((tp->tp_flags & Py_TPFLAGS_INLINE_VALUES) &&
1733
957k
         _PyObject_TryGetInstanceAttribute(obj, name, &attr)) {
1734
942
        if (attr != NULL) {
1735
79
           PyStackRef_CLEAR(*method);
1736
79
           *method = PyStackRef_FromPyObjectSteal(attr);
1737
79
           return 0;
1738
79
        }
1739
863
        dict = NULL;
1740
863
    }
1741
956k
    else if ((tp->tp_flags & Py_TPFLAGS_MANAGED_DICT)) {
1742
6.38k
        dict = (PyObject *)_PyObject_GetManagedDict(obj);
1743
6.38k
    }
1744
950k
    else {
1745
950k
        PyObject **dictptr = _PyObject_ComputedDictPointer(obj);
1746
950k
        if (dictptr != NULL) {
1747
923k
            dict = FT_ATOMIC_LOAD_PTR_ACQUIRE(*dictptr);
1748
923k
        }
1749
26.7k
        else {
1750
26.7k
            dict = NULL;
1751
26.7k
        }
1752
950k
    }
1753
957k
    if (dict != NULL) {
1754
468k
        assert(PyUnicode_CheckExact(name));
1755
468k
        int found = _PyDict_GetMethodStackRef((PyDictObject *)dict, name, method);
1756
468k
        if (found < 0) {
1757
0
            assert(PyStackRef_IsNull(*method));
1758
0
            return -1;
1759
0
        }
1760
468k
        else if (found) {
1761
0
            return 0;
1762
0
        }
1763
468k
    }
1764
1765
957k
    if (meth_found) {
1766
957k
        assert(!PyStackRef_IsNull(*method));
1767
957k
        return 1;
1768
957k
    }
1769
1770
0
    if (f != NULL) {
1771
0
        PyObject *value = f(descr, obj, (PyObject *)Py_TYPE(obj));
1772
0
        PyStackRef_CLEAR(*method);
1773
0
        if (value) {
1774
0
            *method = PyStackRef_FromPyObjectSteal(value);
1775
0
        }
1776
0
        return 0;
1777
0
    }
1778
1779
0
    if (descr != NULL) {
1780
0
        assert(!PyStackRef_IsNull(*method));
1781
0
        return 0;
1782
0
    }
1783
1784
0
    PyErr_Format(PyExc_AttributeError,
1785
0
                 "'%.100s' object has no attribute '%U'",
1786
0
                 tp->tp_name, name);
1787
1788
0
    _PyObject_SetAttributeErrorContext(obj, name);
1789
0
    assert(PyStackRef_IsNull(*method));
1790
0
    return 0;
1791
0
}
1792
1793
1794
/* Generic GetAttr functions - put these in your tp_[gs]etattro slot. */
1795
1796
PyObject *
1797
_PyObject_GenericGetAttrWithDict(PyObject *obj, PyObject *name,
1798
                                 PyObject *dict, int suppress)
1799
39.6M
{
1800
    /* Make sure the logic of _PyObject_GetMethod is in sync with
1801
       this method.
1802
1803
       When suppress=1, this function suppresses AttributeError.
1804
    */
1805
1806
39.6M
    PyTypeObject *tp = Py_TYPE(obj);
1807
39.6M
    PyObject *descr = NULL;
1808
39.6M
    PyObject *res = NULL;
1809
39.6M
    descrgetfunc f;
1810
1811
39.6M
    if (!PyUnicode_Check(name)){
1812
0
        PyErr_Format(PyExc_TypeError,
1813
0
                     "attribute name must be string, not '%.200s'",
1814
0
                     Py_TYPE(name)->tp_name);
1815
0
        return NULL;
1816
0
    }
1817
1818
39.6M
    if (!_PyType_IsReady(tp)) {
1819
0
        if (PyType_Ready(tp) < 0)
1820
0
            return NULL;
1821
0
    }
1822
1823
39.6M
    Py_INCREF(name);
1824
1825
39.6M
    PyThreadState *tstate = _PyThreadState_GET();
1826
39.6M
    _PyCStackRef cref;
1827
39.6M
    _PyThreadState_PushCStackRef(tstate, &cref);
1828
1829
39.6M
    _PyType_LookupStackRefAndVersion(tp, name, &cref.ref);
1830
39.6M
    descr = PyStackRef_AsPyObjectBorrow(cref.ref);
1831
1832
39.6M
    f = NULL;
1833
39.6M
    if (descr != NULL) {
1834
32.5M
        f = Py_TYPE(descr)->tp_descr_get;
1835
32.5M
        if (f != NULL && PyDescr_IsData(descr)) {
1836
17.8M
            res = f(descr, obj, (PyObject *)Py_TYPE(obj));
1837
17.8M
            if (res == NULL && suppress &&
1838
17.8M
                    PyErr_ExceptionMatches(PyExc_AttributeError)) {
1839
0
                PyErr_Clear();
1840
0
            }
1841
17.8M
            goto done;
1842
17.8M
        }
1843
32.5M
    }
1844
21.8M
    if (dict == NULL) {
1845
21.8M
        if ((tp->tp_flags & Py_TPFLAGS_INLINE_VALUES)) {
1846
11.7M
            if (PyUnicode_CheckExact(name) &&
1847
11.7M
                _PyObject_TryGetInstanceAttribute(obj, name, &res)) {
1848
11.7M
                if (res != NULL) {
1849
2.76M
                    goto done;
1850
2.76M
                }
1851
11.7M
            }
1852
0
            else {
1853
0
                dict = (PyObject *)_PyObject_MaterializeManagedDict(obj);
1854
0
                if (dict == NULL) {
1855
0
                    res = NULL;
1856
0
                    goto done;
1857
0
                }
1858
0
            }
1859
11.7M
        }
1860
10.0M
        else if ((tp->tp_flags & Py_TPFLAGS_MANAGED_DICT)) {
1861
58.7k
            dict = (PyObject *)_PyObject_GetManagedDict(obj);
1862
58.7k
        }
1863
10.0M
        else {
1864
10.0M
            PyObject **dictptr = _PyObject_ComputedDictPointer(obj);
1865
10.0M
            if (dictptr) {
1866
#ifdef Py_GIL_DISABLED
1867
                dict = _Py_atomic_load_ptr_acquire(dictptr);
1868
#else
1869
4.08M
                dict = *dictptr;
1870
4.08M
#endif
1871
4.08M
            }
1872
10.0M
        }
1873
21.8M
    }
1874
19.1M
    if (dict != NULL) {
1875
4.12M
        Py_INCREF(dict);
1876
4.12M
        int rc = PyDict_GetItemRef(dict, name, &res);
1877
4.12M
        Py_DECREF(dict);
1878
4.12M
        if (res != NULL) {
1879
4.06M
            goto done;
1880
4.06M
        }
1881
58.2k
        else if (rc < 0) {
1882
0
            if (suppress && PyErr_ExceptionMatches(PyExc_AttributeError)) {
1883
0
                PyErr_Clear();
1884
0
            }
1885
0
            else {
1886
0
                goto done;
1887
0
            }
1888
0
        }
1889
4.12M
    }
1890
1891
15.0M
    if (f != NULL) {
1892
14.6M
        res = f(descr, obj, (PyObject *)Py_TYPE(obj));
1893
14.6M
        if (res == NULL && suppress &&
1894
14.6M
                PyErr_ExceptionMatches(PyExc_AttributeError)) {
1895
0
            PyErr_Clear();
1896
0
        }
1897
14.6M
        goto done;
1898
14.6M
    }
1899
1900
383k
    if (descr != NULL) {
1901
53.5k
        res = PyStackRef_AsPyObjectSteal(cref.ref);
1902
53.5k
        cref.ref = PyStackRef_NULL;
1903
53.5k
        goto done;
1904
53.5k
    }
1905
1906
330k
    if (!suppress) {
1907
48.4k
        PyErr_Format(PyExc_AttributeError,
1908
48.4k
                     "'%.100s' object has no attribute '%U'",
1909
48.4k
                     tp->tp_name, name);
1910
1911
48.4k
        _PyObject_SetAttributeErrorContext(obj, name);
1912
48.4k
    }
1913
39.6M
  done:
1914
39.6M
    _PyThreadState_PopCStackRef(tstate, &cref);
1915
39.6M
    Py_DECREF(name);
1916
39.6M
    return res;
1917
330k
}
1918
1919
PyObject *
1920
PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1921
14.8M
{
1922
14.8M
    return _PyObject_GenericGetAttrWithDict(obj, name, NULL, 0);
1923
14.8M
}
1924
1925
int
1926
_PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
1927
                                 PyObject *value, PyObject *dict)
1928
364k
{
1929
364k
    PyTypeObject *tp = Py_TYPE(obj);
1930
364k
    PyObject *descr;
1931
364k
    descrsetfunc f;
1932
364k
    int res = -1;
1933
1934
364k
    assert(!PyType_IsSubtype(tp, &PyType_Type));
1935
364k
    if (!PyUnicode_Check(name)){
1936
0
        PyErr_Format(PyExc_TypeError,
1937
0
                     "attribute name must be string, not '%.200s'",
1938
0
                     Py_TYPE(name)->tp_name);
1939
0
        return -1;
1940
0
    }
1941
1942
364k
    if (!_PyType_IsReady(tp) && PyType_Ready(tp) < 0) {
1943
0
        return -1;
1944
0
    }
1945
1946
364k
    Py_INCREF(name);
1947
364k
    Py_INCREF(tp);
1948
1949
364k
    PyThreadState *tstate = _PyThreadState_GET();
1950
364k
    _PyCStackRef cref;
1951
364k
    _PyThreadState_PushCStackRef(tstate, &cref);
1952
1953
364k
    _PyType_LookupStackRefAndVersion(tp, name, &cref.ref);
1954
364k
    descr = PyStackRef_AsPyObjectBorrow(cref.ref);
1955
1956
364k
    if (descr != NULL) {
1957
264k
        f = Py_TYPE(descr)->tp_descr_set;
1958
264k
        if (f != NULL) {
1959
262k
            res = f(descr, obj, value);
1960
262k
            goto done;
1961
262k
        }
1962
264k
    }
1963
1964
102k
    if (dict == NULL) {
1965
102k
        PyObject **dictptr;
1966
1967
102k
        if ((tp->tp_flags & Py_TPFLAGS_INLINE_VALUES)) {
1968
2.17k
            res = _PyObject_StoreInstanceAttribute(obj, name, value);
1969
2.17k
            goto error_check;
1970
2.17k
        }
1971
1972
100k
        if ((tp->tp_flags & Py_TPFLAGS_MANAGED_DICT)) {
1973
2.44k
            PyManagedDictPointer *managed_dict = _PyObject_ManagedDictPointer(obj);
1974
2.44k
            dictptr = (PyObject **)&managed_dict->dict;
1975
2.44k
        }
1976
97.8k
        else {
1977
97.8k
            dictptr = _PyObject_ComputedDictPointer(obj);
1978
97.8k
        }
1979
100k
        if (dictptr == NULL) {
1980
0
            if (descr == NULL) {
1981
0
                if (tp->tp_setattro == PyObject_GenericSetAttr) {
1982
0
                    PyErr_Format(PyExc_AttributeError,
1983
0
                                "'%.100s' object has no attribute '%U' and no "
1984
0
                                "__dict__ for setting new attributes",
1985
0
                                tp->tp_name, name);
1986
0
                }
1987
0
                else {
1988
0
                    PyErr_Format(PyExc_AttributeError,
1989
0
                                "'%.100s' object has no attribute '%U'",
1990
0
                                tp->tp_name, name);
1991
0
                }
1992
0
                _PyObject_SetAttributeErrorContext(obj, name);
1993
0
            }
1994
0
            else {
1995
0
                PyErr_Format(PyExc_AttributeError,
1996
0
                            "'%.100s' object attribute '%U' is read-only",
1997
0
                            tp->tp_name, name);
1998
0
            }
1999
0
            goto done;
2000
0
        }
2001
100k
        else {
2002
100k
            res = _PyObjectDict_SetItem(tp, obj, dictptr, name, value);
2003
100k
        }
2004
100k
    }
2005
0
    else {
2006
0
        Py_INCREF(dict);
2007
0
        if (value == NULL)
2008
0
            res = PyDict_DelItem(dict, name);
2009
0
        else
2010
0
            res = PyDict_SetItem(dict, name, value);
2011
0
        Py_DECREF(dict);
2012
0
    }
2013
102k
  error_check:
2014
102k
    if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) {
2015
0
        PyErr_Format(PyExc_AttributeError,
2016
0
                        "'%.100s' object has no attribute '%U'",
2017
0
                        tp->tp_name, name);
2018
0
        _PyObject_SetAttributeErrorContext(obj, name);
2019
0
    }
2020
364k
  done:
2021
364k
    _PyThreadState_PopCStackRef(tstate, &cref);
2022
364k
    Py_DECREF(tp);
2023
364k
    Py_DECREF(name);
2024
364k
    return res;
2025
102k
}
2026
2027
int
2028
PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
2029
364k
{
2030
364k
    return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL);
2031
364k
}
2032
2033
int
2034
PyObject_GenericSetDict(PyObject *obj, PyObject *value, void *context)
2035
0
{
2036
0
    if (value == NULL) {
2037
0
        PyErr_SetString(PyExc_TypeError, "cannot delete __dict__");
2038
0
        return -1;
2039
0
    }
2040
0
    return _PyObject_SetDict(obj, value);
2041
0
}
2042
2043
2044
/* Test a value used as condition, e.g., in a while or if statement.
2045
   Return -1 if an error occurred */
2046
2047
int
2048
PyObject_IsTrue(PyObject *v)
2049
21.5M
{
2050
21.5M
    Py_ssize_t res;
2051
21.5M
    if (v == Py_True)
2052
6.58M
        return 1;
2053
14.9M
    if (v == Py_False)
2054
10.0M
        return 0;
2055
4.99M
    if (v == Py_None)
2056
75.1k
        return 0;
2057
4.92M
    else if (Py_TYPE(v)->tp_as_number != NULL &&
2058
4.92M
             Py_TYPE(v)->tp_as_number->nb_bool != NULL)
2059
72.1k
        res = (*Py_TYPE(v)->tp_as_number->nb_bool)(v);
2060
4.84M
    else if (Py_TYPE(v)->tp_as_mapping != NULL &&
2061
4.84M
             Py_TYPE(v)->tp_as_mapping->mp_length != NULL)
2062
4.13M
        res = (*Py_TYPE(v)->tp_as_mapping->mp_length)(v);
2063
713k
    else if (Py_TYPE(v)->tp_as_sequence != NULL &&
2064
713k
             Py_TYPE(v)->tp_as_sequence->sq_length != NULL)
2065
235k
        res = (*Py_TYPE(v)->tp_as_sequence->sq_length)(v);
2066
478k
    else
2067
478k
        return 1;
2068
    /* if it is negative, it should be either -1 or -2 */
2069
4.44M
    return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
2070
4.99M
}
2071
2072
/* equivalent of 'not v'
2073
   Return -1 if an error occurred */
2074
2075
int
2076
PyObject_Not(PyObject *v)
2077
0
{
2078
0
    int res;
2079
0
    res = PyObject_IsTrue(v);
2080
0
    if (res < 0)
2081
0
        return res;
2082
0
    return res == 0;
2083
0
}
2084
2085
/* Test whether an object can be called */
2086
2087
int
2088
PyCallable_Check(PyObject *x)
2089
34.6M
{
2090
34.6M
    if (x == NULL)
2091
0
        return 0;
2092
34.6M
    return Py_TYPE(x)->tp_call != NULL;
2093
34.6M
}
2094
2095
2096
/* Helper for PyObject_Dir without arguments: returns the local scope. */
2097
static PyObject *
2098
_dir_locals(void)
2099
0
{
2100
0
    PyObject *names;
2101
0
    PyObject *locals;
2102
2103
0
    if (_PyEval_GetFrame() != NULL) {
2104
0
        locals = _PyEval_GetFrameLocals();
2105
0
    }
2106
0
    else {
2107
0
        PyThreadState *tstate = _PyThreadState_GET();
2108
0
        locals = _PyEval_GetGlobalsFromRunningMain(tstate);
2109
0
        if (locals == NULL) {
2110
0
            if (!_PyErr_Occurred(tstate)) {
2111
0
                locals = _PyEval_GetFrameLocals();
2112
0
                assert(_PyErr_Occurred(tstate));
2113
0
            }
2114
0
        }
2115
0
        else {
2116
0
            Py_INCREF(locals);
2117
0
        }
2118
0
    }
2119
0
    if (locals == NULL) {
2120
0
        return NULL;
2121
0
    }
2122
2123
0
    names = PyMapping_Keys(locals);
2124
0
    Py_DECREF(locals);
2125
0
    if (!names) {
2126
0
        return NULL;
2127
0
    }
2128
0
    if (!PyList_Check(names)) {
2129
0
        PyErr_Format(PyExc_TypeError,
2130
0
            "dir(): expected keys() of locals to be a list, "
2131
0
            "not '%.200s'", Py_TYPE(names)->tp_name);
2132
0
        Py_DECREF(names);
2133
0
        return NULL;
2134
0
    }
2135
0
    if (PyList_Sort(names)) {
2136
0
        Py_DECREF(names);
2137
0
        return NULL;
2138
0
    }
2139
0
    return names;
2140
0
}
2141
2142
/* Helper for PyObject_Dir: object introspection. */
2143
static PyObject *
2144
_dir_object(PyObject *obj)
2145
22
{
2146
22
    PyObject *result, *sorted;
2147
22
    PyObject *dirfunc = _PyObject_LookupSpecial(obj, &_Py_ID(__dir__));
2148
2149
22
    assert(obj != NULL);
2150
22
    if (dirfunc == NULL) {
2151
0
        if (!PyErr_Occurred())
2152
0
            PyErr_SetString(PyExc_TypeError, "object does not provide __dir__");
2153
0
        return NULL;
2154
0
    }
2155
    /* use __dir__ */
2156
22
    result = _PyObject_CallNoArgs(dirfunc);
2157
22
    Py_DECREF(dirfunc);
2158
22
    if (result == NULL)
2159
0
        return NULL;
2160
    /* return sorted(result) */
2161
22
    sorted = PySequence_List(result);
2162
22
    Py_DECREF(result);
2163
22
    if (sorted == NULL)
2164
0
        return NULL;
2165
22
    if (PyList_Sort(sorted)) {
2166
0
        Py_DECREF(sorted);
2167
0
        return NULL;
2168
0
    }
2169
22
    return sorted;
2170
22
}
2171
2172
/* Implementation of dir() -- if obj is NULL, returns the names in the current
2173
   (local) scope.  Otherwise, performs introspection of the object: returns a
2174
   sorted list of attribute names (supposedly) accessible from the object
2175
*/
2176
PyObject *
2177
PyObject_Dir(PyObject *obj)
2178
22
{
2179
22
    return (obj == NULL) ? _dir_locals() : _dir_object(obj);
2180
22
}
2181
2182
/*
2183
None is a non-NULL undefined value.
2184
There is (and should be!) no way to create other objects of this type,
2185
so there is exactly one (which is indestructible, by the way).
2186
*/
2187
2188
/* ARGSUSED */
2189
static PyObject *
2190
none_repr(PyObject *op)
2191
562
{
2192
562
    return PyUnicode_FromString("None");
2193
562
}
2194
2195
static void
2196
none_dealloc(PyObject* none)
2197
0
{
2198
    /* This should never get called, but we also don't want to SEGV if
2199
     * we accidentally decref None out of existence. Instead,
2200
     * since None is an immortal object, re-set the reference count.
2201
     */
2202
0
    _Py_SetImmortal(none);
2203
0
}
2204
2205
static PyObject *
2206
none_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
2207
0
{
2208
0
    if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
2209
0
        PyErr_SetString(PyExc_TypeError, "NoneType takes no arguments");
2210
0
        return NULL;
2211
0
    }
2212
0
    Py_RETURN_NONE;
2213
0
}
2214
2215
static int
2216
none_bool(PyObject *v)
2217
0
{
2218
0
    return 0;
2219
0
}
2220
2221
static Py_hash_t none_hash(PyObject *v)
2222
406k
{
2223
406k
    return 0xFCA86420;
2224
406k
}
2225
2226
static PyNumberMethods none_as_number = {
2227
    0,                          /* nb_add */
2228
    0,                          /* nb_subtract */
2229
    0,                          /* nb_multiply */
2230
    0,                          /* nb_remainder */
2231
    0,                          /* nb_divmod */
2232
    0,                          /* nb_power */
2233
    0,                          /* nb_negative */
2234
    0,                          /* nb_positive */
2235
    0,                          /* nb_absolute */
2236
    none_bool,                  /* nb_bool */
2237
    0,                          /* nb_invert */
2238
    0,                          /* nb_lshift */
2239
    0,                          /* nb_rshift */
2240
    0,                          /* nb_and */
2241
    0,                          /* nb_xor */
2242
    0,                          /* nb_or */
2243
    0,                          /* nb_int */
2244
    0,                          /* nb_reserved */
2245
    0,                          /* nb_float */
2246
    0,                          /* nb_inplace_add */
2247
    0,                          /* nb_inplace_subtract */
2248
    0,                          /* nb_inplace_multiply */
2249
    0,                          /* nb_inplace_remainder */
2250
    0,                          /* nb_inplace_power */
2251
    0,                          /* nb_inplace_lshift */
2252
    0,                          /* nb_inplace_rshift */
2253
    0,                          /* nb_inplace_and */
2254
    0,                          /* nb_inplace_xor */
2255
    0,                          /* nb_inplace_or */
2256
    0,                          /* nb_floor_divide */
2257
    0,                          /* nb_true_divide */
2258
    0,                          /* nb_inplace_floor_divide */
2259
    0,                          /* nb_inplace_true_divide */
2260
    0,                          /* nb_index */
2261
};
2262
2263
PyDoc_STRVAR(none_doc,
2264
"NoneType()\n"
2265
"--\n\n"
2266
"The type of the None singleton.");
2267
2268
PyTypeObject _PyNone_Type = {
2269
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
2270
    "NoneType",
2271
    0,
2272
    0,
2273
    none_dealloc,       /*tp_dealloc*/
2274
    0,                  /*tp_vectorcall_offset*/
2275
    0,                  /*tp_getattr*/
2276
    0,                  /*tp_setattr*/
2277
    0,                  /*tp_as_async*/
2278
    none_repr,          /*tp_repr*/
2279
    &none_as_number,    /*tp_as_number*/
2280
    0,                  /*tp_as_sequence*/
2281
    0,                  /*tp_as_mapping*/
2282
    none_hash,          /*tp_hash */
2283
    0,                  /*tp_call */
2284
    0,                  /*tp_str */
2285
    0,                  /*tp_getattro */
2286
    0,                  /*tp_setattro */
2287
    0,                  /*tp_as_buffer */
2288
    Py_TPFLAGS_DEFAULT, /*tp_flags */
2289
    none_doc,           /*tp_doc */
2290
    0,                  /*tp_traverse */
2291
    0,                  /*tp_clear */
2292
    _Py_BaseObject_RichCompare, /*tp_richcompare */
2293
    0,                  /*tp_weaklistoffset */
2294
    0,                  /*tp_iter */
2295
    0,                  /*tp_iternext */
2296
    0,                  /*tp_methods */
2297
    0,                  /*tp_members */
2298
    0,                  /*tp_getset */
2299
    0,                  /*tp_base */
2300
    0,                  /*tp_dict */
2301
    0,                  /*tp_descr_get */
2302
    0,                  /*tp_descr_set */
2303
    0,                  /*tp_dictoffset */
2304
    0,                  /*tp_init */
2305
    0,                  /*tp_alloc */
2306
    none_new,           /*tp_new */
2307
};
2308
2309
PyObject _Py_NoneStruct = _PyObject_HEAD_INIT(&_PyNone_Type);
2310
2311
/* NotImplemented is an object that can be used to signal that an
2312
   operation is not implemented for the given type combination. */
2313
2314
static PyObject *
2315
NotImplemented_repr(PyObject *op)
2316
0
{
2317
0
    return PyUnicode_FromString("NotImplemented");
2318
0
}
2319
2320
static PyObject *
2321
NotImplemented_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
2322
0
{
2323
0
    return PyUnicode_FromString("NotImplemented");
2324
0
}
2325
2326
static PyMethodDef notimplemented_methods[] = {
2327
    {"__reduce__", NotImplemented_reduce, METH_NOARGS, NULL},
2328
    {NULL, NULL}
2329
};
2330
2331
static PyObject *
2332
notimplemented_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
2333
0
{
2334
0
    if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
2335
0
        PyErr_SetString(PyExc_TypeError, "NotImplementedType takes no arguments");
2336
0
        return NULL;
2337
0
    }
2338
0
    Py_RETURN_NOTIMPLEMENTED;
2339
0
}
2340
2341
static void
2342
notimplemented_dealloc(PyObject *notimplemented)
2343
0
{
2344
    /* This should never get called, but we also don't want to SEGV if
2345
     * we accidentally decref NotImplemented out of existence. Instead,
2346
     * since Notimplemented is an immortal object, re-set the reference count.
2347
     */
2348
0
    _Py_SetImmortal(notimplemented);
2349
0
}
2350
2351
static int
2352
notimplemented_bool(PyObject *v)
2353
0
{
2354
0
    PyErr_SetString(PyExc_TypeError,
2355
0
                    "NotImplemented should not be used in a boolean context");
2356
0
    return -1;
2357
0
}
2358
2359
static PyNumberMethods notimplemented_as_number = {
2360
    .nb_bool = notimplemented_bool,
2361
};
2362
2363
PyDoc_STRVAR(notimplemented_doc,
2364
"NotImplementedType()\n"
2365
"--\n\n"
2366
"The type of the NotImplemented singleton.");
2367
2368
PyTypeObject _PyNotImplemented_Type = {
2369
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
2370
    "NotImplementedType",
2371
    0,
2372
    0,
2373
    notimplemented_dealloc,       /*tp_dealloc*/ /*never called*/
2374
    0,                  /*tp_vectorcall_offset*/
2375
    0,                  /*tp_getattr*/
2376
    0,                  /*tp_setattr*/
2377
    0,                  /*tp_as_async*/
2378
    NotImplemented_repr,        /*tp_repr*/
2379
    &notimplemented_as_number,  /*tp_as_number*/
2380
    0,                  /*tp_as_sequence*/
2381
    0,                  /*tp_as_mapping*/
2382
    0,                  /*tp_hash */
2383
    0,                  /*tp_call */
2384
    0,                  /*tp_str */
2385
    0,                  /*tp_getattro */
2386
    0,                  /*tp_setattro */
2387
    0,                  /*tp_as_buffer */
2388
    Py_TPFLAGS_DEFAULT, /*tp_flags */
2389
    notimplemented_doc, /*tp_doc */
2390
    0,                  /*tp_traverse */
2391
    0,                  /*tp_clear */
2392
    0,                  /*tp_richcompare */
2393
    0,                  /*tp_weaklistoffset */
2394
    0,                  /*tp_iter */
2395
    0,                  /*tp_iternext */
2396
    notimplemented_methods, /*tp_methods */
2397
    0,                  /*tp_members */
2398
    0,                  /*tp_getset */
2399
    0,                  /*tp_base */
2400
    0,                  /*tp_dict */
2401
    0,                  /*tp_descr_get */
2402
    0,                  /*tp_descr_set */
2403
    0,                  /*tp_dictoffset */
2404
    0,                  /*tp_init */
2405
    0,                  /*tp_alloc */
2406
    notimplemented_new, /*tp_new */
2407
};
2408
2409
PyObject _Py_NotImplementedStruct = _PyObject_HEAD_INIT(&_PyNotImplemented_Type);
2410
2411
2412
PyStatus
2413
_PyObject_InitState(PyInterpreterState *interp)
2414
22
{
2415
#ifdef Py_TRACE_REFS
2416
    if (refchain_init(interp) < 0) {
2417
        return _PyStatus_NO_MEMORY();
2418
    }
2419
#endif
2420
22
    return _PyStatus_OK();
2421
22
}
2422
2423
void
2424
_PyObject_FiniState(PyInterpreterState *interp)
2425
0
{
2426
#ifdef Py_TRACE_REFS
2427
    refchain_fini(interp);
2428
#endif
2429
0
}
2430
2431
2432
extern PyTypeObject _PyAnextAwaitable_Type;
2433
extern PyTypeObject _PyLegacyEventHandler_Type;
2434
extern PyTypeObject _PyLineIterator;
2435
extern PyTypeObject _PyMemoryIter_Type;
2436
extern PyTypeObject _PyPositionsIterator;
2437
extern PyTypeObject _Py_GenericAliasIterType;
2438
2439
static PyTypeObject* static_types[] = {
2440
    // The two most important base types: must be initialized first and
2441
    // deallocated last.
2442
    &PyBaseObject_Type,
2443
    &PyType_Type,
2444
2445
    // Static types with base=&PyBaseObject_Type
2446
    &PyAsyncGen_Type,
2447
    &PyByteArrayIter_Type,
2448
    &PyByteArray_Type,
2449
    &PyBytesIter_Type,
2450
    &PyBytes_Type,
2451
    &PyCFunction_Type,
2452
    &PyCallIter_Type,
2453
    &PyCapsule_Type,
2454
    &PyCell_Type,
2455
    &PyClassMethodDescr_Type,
2456
    &PyClassMethod_Type,
2457
    &PyCode_Type,
2458
    &PyComplex_Type,
2459
    &PyContextToken_Type,
2460
    &PyContextVar_Type,
2461
    &PyContext_Type,
2462
    &PyCoro_Type,
2463
    &PyDictItems_Type,
2464
    &PyDictIterItem_Type,
2465
    &PyDictIterKey_Type,
2466
    &PyDictIterValue_Type,
2467
    &PyDictKeys_Type,
2468
    &PyDictProxy_Type,
2469
    &PyDictRevIterItem_Type,
2470
    &PyDictRevIterKey_Type,
2471
    &PyDictRevIterValue_Type,
2472
    &PyDictValues_Type,
2473
    &PyDict_Type,
2474
    &PyEllipsis_Type,
2475
    &PyEnum_Type,
2476
    &PyFilter_Type,
2477
    &PyFloat_Type,
2478
    &PyFrame_Type,
2479
    &PyFrameLocalsProxy_Type,
2480
    &PyFrozenSet_Type,
2481
    &PyFunction_Type,
2482
    &PyGen_Type,
2483
    &PyGetSetDescr_Type,
2484
    &PyInstanceMethod_Type,
2485
    &PyListIter_Type,
2486
    &PyListRevIter_Type,
2487
    &PyList_Type,
2488
    &PyLongRangeIter_Type,
2489
    &PyLong_Type,
2490
    &PyMap_Type,
2491
    &PyMemberDescr_Type,
2492
    &PyMemoryView_Type,
2493
    &PyMethodDescr_Type,
2494
    &PyMethod_Type,
2495
    &PyModuleDef_Type,
2496
    &PyModule_Type,
2497
    &PyODictIter_Type,
2498
    &PyPickleBuffer_Type,
2499
    &PyProperty_Type,
2500
    &PyRangeIter_Type,
2501
    &PyRange_Type,
2502
    &PyReversed_Type,
2503
    &PySTEntry_Type,
2504
    &PySeqIter_Type,
2505
    &PySetIter_Type,
2506
    &PySet_Type,
2507
    &PySlice_Type,
2508
    &PyStaticMethod_Type,
2509
    &PyStdPrinter_Type,
2510
    &PySuper_Type,
2511
    &PyTraceBack_Type,
2512
    &PyTupleIter_Type,
2513
    &PyTuple_Type,
2514
    &PyUnicodeIter_Type,
2515
    &PyUnicode_Type,
2516
    &PyWrapperDescr_Type,
2517
    &PyZip_Type,
2518
    &Py_GenericAliasType,
2519
    &_PyAnextAwaitable_Type,
2520
    &_PyAsyncGenASend_Type,
2521
    &_PyAsyncGenAThrow_Type,
2522
    &_PyAsyncGenWrappedValue_Type,
2523
    &_PyBufferWrapper_Type,
2524
    &_PyContextTokenMissing_Type,
2525
    &_PyCoroWrapper_Type,
2526
    &_Py_GenericAliasIterType,
2527
    &_PyHamtItems_Type,
2528
    &_PyHamtKeys_Type,
2529
    &_PyHamtValues_Type,
2530
    &_PyHamt_ArrayNode_Type,
2531
    &_PyHamt_BitmapNode_Type,
2532
    &_PyHamt_CollisionNode_Type,
2533
    &_PyHamt_Type,
2534
    &_PyInstructionSequence_Type,
2535
    &_PyInterpolation_Type,
2536
    &_PyLegacyEventHandler_Type,
2537
    &_PyLineIterator,
2538
    &_PyManagedBuffer_Type,
2539
    &_PyMemoryIter_Type,
2540
    &_PyMethodWrapper_Type,
2541
    &_PyNamespace_Type,
2542
    &_PyNone_Type,
2543
    &_PyNotImplemented_Type,
2544
    &_PyPositionsIterator,
2545
    &_PyTemplate_Type,
2546
    &_PyTemplateIter_Type,
2547
    &_PyUnicodeASCIIIter_Type,
2548
    &_PyUnion_Type,
2549
#ifdef _Py_TIER2
2550
    &_PyUOpExecutor_Type,
2551
#endif
2552
    &_PyWeakref_CallableProxyType,
2553
    &_PyWeakref_ProxyType,
2554
    &_PyWeakref_RefType,
2555
    &_PyTypeAlias_Type,
2556
    &_PyNoDefault_Type,
2557
2558
    // subclasses: _PyTypes_FiniTypes() deallocates them before their base
2559
    // class
2560
    &PyBool_Type,         // base=&PyLong_Type
2561
    &PyCMethod_Type,      // base=&PyCFunction_Type
2562
    &PyODictItems_Type,   // base=&PyDictItems_Type
2563
    &PyODictKeys_Type,    // base=&PyDictKeys_Type
2564
    &PyODictValues_Type,  // base=&PyDictValues_Type
2565
    &PyODict_Type,        // base=&PyDict_Type
2566
};
2567
2568
2569
PyStatus
2570
_PyTypes_InitTypes(PyInterpreterState *interp)
2571
22
{
2572
    // All other static types (unless initialized elsewhere)
2573
2.57k
    for (size_t i=0; i < Py_ARRAY_LENGTH(static_types); i++) {
2574
2.55k
        PyTypeObject *type = static_types[i];
2575
2.55k
        if (_PyStaticType_InitBuiltin(interp, type) < 0) {
2576
0
            return _PyStatus_ERR("Can't initialize builtin type");
2577
0
        }
2578
2.55k
        if (type == &PyType_Type) {
2579
            // Sanitify checks of the two most important types
2580
22
            assert(PyBaseObject_Type.tp_base == NULL);
2581
22
            assert(PyType_Type.tp_base == &PyBaseObject_Type);
2582
22
        }
2583
2.55k
    }
2584
2585
    // Cache __reduce__ from PyBaseObject_Type object
2586
22
    PyObject *baseobj_dict = _PyType_GetDict(&PyBaseObject_Type);
2587
22
    PyObject *baseobj_reduce = PyDict_GetItemWithError(baseobj_dict, &_Py_ID(__reduce__));
2588
22
    if (baseobj_reduce == NULL && PyErr_Occurred()) {
2589
0
        return _PyStatus_ERR("Can't get __reduce__ from base object");
2590
0
    }
2591
22
    _Py_INTERP_CACHED_OBJECT(interp, objreduce) = baseobj_reduce;
2592
2593
    // Must be after static types are initialized
2594
22
    if (_Py_initialize_generic(interp) < 0) {
2595
0
        return _PyStatus_ERR("Can't initialize generic types");
2596
0
    }
2597
2598
22
    return _PyStatus_OK();
2599
22
}
2600
2601
2602
// Best-effort function clearing static types.
2603
//
2604
// Don't deallocate a type if it still has subclasses. If a Py_Finalize()
2605
// sub-function is interrupted by CTRL+C or fails with MemoryError, some
2606
// subclasses are not cleared properly. Leave the static type unchanged in this
2607
// case.
2608
void
2609
_PyTypes_FiniTypes(PyInterpreterState *interp)
2610
0
{
2611
    // Deallocate types in the reverse order to deallocate subclasses before
2612
    // their base classes.
2613
0
    for (Py_ssize_t i=Py_ARRAY_LENGTH(static_types)-1; i>=0; i--) {
2614
0
        PyTypeObject *type = static_types[i];
2615
0
        _PyStaticType_FiniBuiltin(interp, type);
2616
0
    }
2617
0
}
2618
2619
2620
static inline void
2621
new_reference(PyObject *op)
2622
453M
{
2623
    // Skip the immortal object check in Py_SET_REFCNT; always set refcnt to 1
2624
453M
#if !defined(Py_GIL_DISABLED)
2625
453M
#if SIZEOF_VOID_P > 4
2626
453M
    op->ob_refcnt_full = 1;
2627
453M
    assert(op->ob_refcnt == 1);
2628
453M
    assert(op->ob_flags == 0);
2629
#else
2630
    op->ob_refcnt = 1;
2631
#endif
2632
#else
2633
    op->ob_flags = 0;
2634
    op->ob_mutex = (PyMutex){ 0 };
2635
#ifdef _Py_THREAD_SANITIZER
2636
    _Py_atomic_store_uintptr_relaxed(&op->ob_tid, _Py_ThreadId());
2637
    _Py_atomic_store_uint8_relaxed(&op->ob_gc_bits, 0);
2638
    _Py_atomic_store_uint32_relaxed(&op->ob_ref_local, 1);
2639
    _Py_atomic_store_ssize_relaxed(&op->ob_ref_shared, 0);
2640
#else
2641
    op->ob_tid = _Py_ThreadId();
2642
    op->ob_gc_bits = 0;
2643
    op->ob_ref_local = 1;
2644
    op->ob_ref_shared = 0;
2645
#endif
2646
#endif
2647
#ifdef Py_TRACE_REFS
2648
    _Py_AddToAllObjects(op);
2649
#endif
2650
453M
    _PyReftracerTrack(op, PyRefTracer_CREATE);
2651
453M
}
2652
2653
void
2654
_Py_NewReference(PyObject *op)
2655
445M
{
2656
#ifdef Py_REF_DEBUG
2657
    _Py_IncRefTotal(_PyThreadState_GET());
2658
#endif
2659
445M
    new_reference(op);
2660
445M
}
2661
2662
void
2663
_Py_NewReferenceNoTotal(PyObject *op)
2664
8.40M
{
2665
8.40M
    new_reference(op);
2666
8.40M
}
2667
2668
void
2669
_Py_SetImmortalUntracked(PyObject *op)
2670
120k
{
2671
#ifdef Py_DEBUG
2672
    // For strings, use _PyUnicode_InternImmortal instead.
2673
    if (PyUnicode_CheckExact(op)) {
2674
        assert(PyUnicode_CHECK_INTERNED(op) == SSTATE_INTERNED_IMMORTAL
2675
            || PyUnicode_CHECK_INTERNED(op) == SSTATE_INTERNED_IMMORTAL_STATIC);
2676
    }
2677
#endif
2678
    // Check if already immortal to avoid degrading from static immortal to plain immortal
2679
120k
    if (_Py_IsImmortal(op)) {
2680
66
        return;
2681
66
    }
2682
#ifdef Py_GIL_DISABLED
2683
    op->ob_tid = _Py_UNOWNED_TID;
2684
    op->ob_ref_local = _Py_IMMORTAL_REFCNT_LOCAL;
2685
    op->ob_ref_shared = 0;
2686
    _Py_atomic_or_uint8(&op->ob_gc_bits, _PyGC_BITS_DEFERRED);
2687
#elif SIZEOF_VOID_P > 4
2688
120k
    op->ob_flags = _Py_IMMORTAL_FLAGS;
2689
120k
    op->ob_refcnt = _Py_IMMORTAL_INITIAL_REFCNT;
2690
#else
2691
    op->ob_refcnt = _Py_IMMORTAL_INITIAL_REFCNT;
2692
#endif
2693
120k
}
2694
2695
void
2696
_Py_SetImmortal(PyObject *op)
2697
120k
{
2698
120k
    if (PyObject_IS_GC(op) && _PyObject_GC_IS_TRACKED(op)) {
2699
8.91k
        _PyObject_GC_UNTRACK(op);
2700
8.91k
    }
2701
120k
    _Py_SetImmortalUntracked(op);
2702
120k
}
2703
2704
void
2705
_PyObject_SetDeferredRefcount(PyObject *op)
2706
89.0k
{
2707
#ifdef Py_GIL_DISABLED
2708
    assert(PyType_IS_GC(Py_TYPE(op)));
2709
    assert(_Py_IsOwnedByCurrentThread(op));
2710
    assert(op->ob_ref_shared == 0);
2711
    _PyObject_SET_GC_BITS(op, _PyGC_BITS_DEFERRED);
2712
    op->ob_ref_shared = _Py_REF_SHARED(_Py_REF_DEFERRED, 0);
2713
#endif
2714
89.0k
}
2715
2716
int
2717
PyUnstable_Object_EnableDeferredRefcount(PyObject *op)
2718
0
{
2719
#ifdef Py_GIL_DISABLED
2720
    if (!PyType_IS_GC(Py_TYPE(op))) {
2721
        // Deferred reference counting doesn't work
2722
        // on untracked types.
2723
        return 0;
2724
    }
2725
2726
    uint8_t bits = _Py_atomic_load_uint8(&op->ob_gc_bits);
2727
    if ((bits & _PyGC_BITS_DEFERRED) != 0)
2728
    {
2729
        // Nothing to do.
2730
        return 0;
2731
    }
2732
2733
    if (_Py_atomic_compare_exchange_uint8(&op->ob_gc_bits, &bits, bits | _PyGC_BITS_DEFERRED) == 0)
2734
    {
2735
        // Someone beat us to it!
2736
        return 0;
2737
    }
2738
    _Py_atomic_add_ssize(&op->ob_ref_shared, _Py_REF_SHARED(_Py_REF_DEFERRED, 0));
2739
    return 1;
2740
#else
2741
0
    return 0;
2742
0
#endif
2743
0
}
2744
2745
int
2746
PyUnstable_Object_IsUniqueReferencedTemporary(PyObject *op)
2747
0
{
2748
0
    if (!_PyObject_IsUniquelyReferenced(op)) {
2749
0
        return 0;
2750
0
    }
2751
2752
0
    _PyInterpreterFrame *frame = _PyEval_GetFrame();
2753
0
    if (frame == NULL) {
2754
0
        return 0;
2755
0
    }
2756
2757
0
    _PyStackRef *base = _PyFrame_Stackbase(frame);
2758
0
    _PyStackRef *stackpointer = frame->stackpointer;
2759
0
    while (stackpointer > base) {
2760
0
        stackpointer--;
2761
0
        if (op == PyStackRef_AsPyObjectBorrow(*stackpointer)) {
2762
0
            return PyStackRef_IsHeapSafe(*stackpointer);
2763
0
        }
2764
0
    }
2765
0
    return 0;
2766
0
}
2767
2768
int
2769
PyUnstable_TryIncRef(PyObject *op)
2770
0
{
2771
0
    return _Py_TryIncref(op);
2772
0
}
2773
2774
void
2775
PyUnstable_EnableTryIncRef(PyObject *op)
2776
0
{
2777
#ifdef Py_GIL_DISABLED
2778
    _PyObject_SetMaybeWeakref(op);
2779
#endif
2780
0
}
2781
2782
void
2783
_Py_ResurrectReference(PyObject *op)
2784
0
{
2785
#ifdef Py_TRACE_REFS
2786
    _Py_AddToAllObjects(op);
2787
#endif
2788
0
}
2789
2790
void
2791
_Py_ForgetReference(PyObject *op)
2792
0
{
2793
#ifdef Py_TRACE_REFS
2794
    if (Py_REFCNT(op) < 0) {
2795
        _PyObject_ASSERT_FAILED_MSG(op, "negative refcnt");
2796
    }
2797
2798
    PyInterpreterState *interp = _PyInterpreterState_GET();
2799
2800
#ifdef SLOW_UNREF_CHECK
2801
    if (!_PyRefchain_Get(interp, op)) {
2802
        /* Not found */
2803
        _PyObject_ASSERT_FAILED_MSG(op,
2804
                                    "object not found in the objects list");
2805
    }
2806
#endif
2807
2808
    _PyRefchain_Remove(interp, op);
2809
#endif
2810
0
}
2811
2812
2813
#ifdef Py_TRACE_REFS
2814
static int
2815
_Py_PrintReference(_Py_hashtable_t *ht,
2816
                   const void *key, const void *value,
2817
                   void *user_data)
2818
{
2819
    PyObject *op = (PyObject*)key;
2820
    FILE *fp = (FILE *)user_data;
2821
    fprintf(fp, "%p [%zd] ", (void *)op, Py_REFCNT(op));
2822
    if (PyObject_Print(op, fp, 0) != 0) {
2823
        PyErr_Clear();
2824
    }
2825
    putc('\n', fp);
2826
    return 0;
2827
}
2828
2829
2830
/* Print all live objects.  Because PyObject_Print is called, the
2831
 * interpreter must be in a healthy state.
2832
 */
2833
void
2834
_Py_PrintReferences(PyInterpreterState *interp, FILE *fp)
2835
{
2836
    if (interp == NULL) {
2837
        interp = _PyInterpreterState_Main();
2838
    }
2839
    fprintf(fp, "Remaining objects:\n");
2840
    _Py_hashtable_foreach(REFCHAIN(interp), _Py_PrintReference, fp);
2841
}
2842
2843
2844
static int
2845
_Py_PrintReferenceAddress(_Py_hashtable_t *ht,
2846
                          const void *key, const void *value,
2847
                          void *user_data)
2848
{
2849
    PyObject *op = (PyObject*)key;
2850
    FILE *fp = (FILE *)user_data;
2851
    fprintf(fp, "%p [%zd] %s\n",
2852
            (void *)op, Py_REFCNT(op), Py_TYPE(op)->tp_name);
2853
    return 0;
2854
}
2855
2856
2857
/* Print the addresses of all live objects.  Unlike _Py_PrintReferences, this
2858
 * doesn't make any calls to the Python C API, so is always safe to call.
2859
 */
2860
// XXX This function is not safe to use if the interpreter has been
2861
// freed or is in an unhealthy state (e.g. late in finalization).
2862
// The call in Py_FinalizeEx() is okay since the main interpreter
2863
// is statically allocated.
2864
void
2865
_Py_PrintReferenceAddresses(PyInterpreterState *interp, FILE *fp)
2866
{
2867
    fprintf(fp, "Remaining object addresses:\n");
2868
    _Py_hashtable_foreach(REFCHAIN(interp), _Py_PrintReferenceAddress, fp);
2869
}
2870
2871
2872
typedef struct {
2873
    PyObject *self;
2874
    PyObject *args;
2875
    PyObject *list;
2876
    PyObject *type;
2877
    Py_ssize_t limit;
2878
} _Py_GetObjectsData;
2879
2880
enum {
2881
    _PY_GETOBJECTS_IGNORE = 0,
2882
    _PY_GETOBJECTS_ERROR = 1,
2883
    _PY_GETOBJECTS_STOP = 2,
2884
};
2885
2886
static int
2887
_Py_GetObject(_Py_hashtable_t *ht,
2888
              const void *key, const void *value,
2889
              void *user_data)
2890
{
2891
    PyObject *op = (PyObject *)key;
2892
    _Py_GetObjectsData *data = user_data;
2893
    if (data->limit > 0) {
2894
        if (PyList_GET_SIZE(data->list) >= data->limit) {
2895
            return _PY_GETOBJECTS_STOP;
2896
        }
2897
    }
2898
2899
    if (op == data->self) {
2900
        return _PY_GETOBJECTS_IGNORE;
2901
    }
2902
    if (op == data->args) {
2903
        return _PY_GETOBJECTS_IGNORE;
2904
    }
2905
    if (op == data->list) {
2906
        return _PY_GETOBJECTS_IGNORE;
2907
    }
2908
    if (data->type != NULL) {
2909
        if (op == data->type) {
2910
            return _PY_GETOBJECTS_IGNORE;
2911
        }
2912
        if (!Py_IS_TYPE(op, (PyTypeObject *)data->type)) {
2913
            return _PY_GETOBJECTS_IGNORE;
2914
        }
2915
    }
2916
2917
    if (PyList_Append(data->list, op) < 0) {
2918
        return _PY_GETOBJECTS_ERROR;
2919
    }
2920
    return 0;
2921
}
2922
2923
2924
/* The implementation of sys.getobjects(). */
2925
PyObject *
2926
_Py_GetObjects(PyObject *self, PyObject *args)
2927
{
2928
    Py_ssize_t limit;
2929
    PyObject *type = NULL;
2930
    if (!PyArg_ParseTuple(args, "n|O", &limit, &type)) {
2931
        return NULL;
2932
    }
2933
2934
    PyObject *list = PyList_New(0);
2935
    if (list == NULL) {
2936
        return NULL;
2937
    }
2938
2939
    _Py_GetObjectsData data = {
2940
        .self = self,
2941
        .args = args,
2942
        .list = list,
2943
        .type = type,
2944
        .limit = limit,
2945
    };
2946
    PyInterpreterState *interp = _PyInterpreterState_GET();
2947
    int res = _Py_hashtable_foreach(REFCHAIN(interp), _Py_GetObject, &data);
2948
    if (res == _PY_GETOBJECTS_ERROR) {
2949
        Py_DECREF(list);
2950
        return NULL;
2951
    }
2952
    return list;
2953
}
2954
2955
#undef REFCHAIN
2956
#undef REFCHAIN_VALUE
2957
2958
#endif  /* Py_TRACE_REFS */
2959
2960
2961
/* Hack to force loading of abstract.o */
2962
Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
2963
2964
2965
void
2966
_PyObject_DebugTypeStats(FILE *out)
2967
0
{
2968
0
    _PyDict_DebugMallocStats(out);
2969
0
    _PyFloat_DebugMallocStats(out);
2970
0
    _PyList_DebugMallocStats(out);
2971
0
    _PyTuple_DebugMallocStats(out);
2972
0
}
2973
2974
/* These methods are used to control infinite recursion in repr, str, print,
2975
   etc.  Container objects that may recursively contain themselves,
2976
   e.g. builtin dictionaries and lists, should use Py_ReprEnter() and
2977
   Py_ReprLeave() to avoid infinite recursion.
2978
2979
   Py_ReprEnter() returns 0 the first time it is called for a particular
2980
   object and 1 every time thereafter.  It returns -1 if an exception
2981
   occurred.  Py_ReprLeave() has no return value.
2982
2983
   See dictobject.c and listobject.c for examples of use.
2984
*/
2985
2986
int
2987
Py_ReprEnter(PyObject *obj)
2988
34
{
2989
34
    PyObject *dict;
2990
34
    PyObject *list;
2991
34
    Py_ssize_t i;
2992
2993
34
    dict = PyThreadState_GetDict();
2994
    /* Ignore a missing thread-state, so that this function can be called
2995
       early on startup. */
2996
34
    if (dict == NULL)
2997
0
        return 0;
2998
34
    list = PyDict_GetItemWithError(dict, &_Py_ID(Py_Repr));
2999
34
    if (list == NULL) {
3000
1
        if (PyErr_Occurred()) {
3001
0
            return -1;
3002
0
        }
3003
1
        list = PyList_New(0);
3004
1
        if (list == NULL)
3005
0
            return -1;
3006
1
        if (PyDict_SetItem(dict, &_Py_ID(Py_Repr), list) < 0)
3007
0
            return -1;
3008
1
        Py_DECREF(list);
3009
1
    }
3010
34
    i = PyList_GET_SIZE(list);
3011
65
    while (--i >= 0) {
3012
62
        if (PyList_GET_ITEM(list, i) == obj)
3013
0
            return 1;
3014
31
    }
3015
34
    if (PyList_Append(list, obj) < 0)
3016
0
        return -1;
3017
34
    return 0;
3018
34
}
3019
3020
void
3021
Py_ReprLeave(PyObject *obj)
3022
34
{
3023
34
    PyObject *dict;
3024
34
    PyObject *list;
3025
34
    Py_ssize_t i;
3026
3027
34
    PyObject *exc = PyErr_GetRaisedException();
3028
3029
34
    dict = PyThreadState_GetDict();
3030
34
    if (dict == NULL)
3031
0
        goto finally;
3032
3033
34
    list = PyDict_GetItemWithError(dict, &_Py_ID(Py_Repr));
3034
34
    if (list == NULL || !PyList_Check(list))
3035
0
        goto finally;
3036
3037
34
    i = PyList_GET_SIZE(list);
3038
    /* Count backwards because we always expect obj to be list[-1] */
3039
34
    while (--i >= 0) {
3040
68
        if (PyList_GET_ITEM(list, i) == obj) {
3041
34
            PyList_SetSlice(list, i, i + 1, NULL);
3042
34
            break;
3043
34
        }
3044
34
    }
3045
3046
34
finally:
3047
    /* ignore exceptions because there is no way to report them. */
3048
34
    PyErr_SetRaisedException(exc);
3049
34
}
3050
3051
/* Trashcan support. */
3052
3053
/* Add op to the gcstate->trash_delete_later list.  Called when the current
3054
 * call-stack depth gets large.  op must be a gc'ed object, with refcount 0.
3055
 *  Py_DECREF must already have been called on it.
3056
 */
3057
void
3058
_PyTrash_thread_deposit_object(PyThreadState *tstate, PyObject *op)
3059
59.3k
{
3060
59.3k
    _PyObject_ASSERT(op, Py_REFCNT(op) == 0);
3061
59.3k
    PyTypeObject *tp = Py_TYPE(op);
3062
59.3k
    assert(tp->tp_flags & Py_TPFLAGS_HAVE_GC);
3063
59.3k
    int tracked = 0;
3064
59.3k
    if (tp->tp_is_gc == NULL || tp->tp_is_gc(op)) {
3065
59.3k
        tracked = _PyObject_GC_IS_TRACKED(op);
3066
59.3k
        if (tracked) {
3067
59.3k
            _PyObject_GC_UNTRACK(op);
3068
59.3k
        }
3069
59.3k
    }
3070
59.3k
    uintptr_t tagged_ptr = ((uintptr_t)tstate->delete_later) | tracked;
3071
#ifdef Py_GIL_DISABLED
3072
    op->ob_tid = tagged_ptr;
3073
#else
3074
59.3k
    _Py_AS_GC(op)->_gc_next = tagged_ptr;
3075
59.3k
#endif
3076
59.3k
    tstate->delete_later = op;
3077
59.3k
}
3078
3079
/* Deallocate all the objects in the gcstate->trash_delete_later list.
3080
 * Called when the call-stack unwinds again. */
3081
void
3082
_PyTrash_thread_destroy_chain(PyThreadState *tstate)
3083
151
{
3084
59.4k
    while (tstate->delete_later) {
3085
59.3k
        PyObject *op = tstate->delete_later;
3086
59.3k
        destructor dealloc = Py_TYPE(op)->tp_dealloc;
3087
3088
#ifdef Py_GIL_DISABLED
3089
        uintptr_t tagged_ptr = op->ob_tid;
3090
        op->ob_tid = 0;
3091
        _Py_atomic_store_ssize_relaxed(&op->ob_ref_shared, _Py_REF_MERGED);
3092
#else
3093
59.3k
        uintptr_t tagged_ptr = _Py_AS_GC(op)->_gc_next;
3094
59.3k
        _Py_AS_GC(op)->_gc_next = 0;
3095
59.3k
#endif
3096
59.3k
        tstate->delete_later = (PyObject *)(tagged_ptr & ~1);
3097
59.3k
        if (tagged_ptr & 1) {
3098
59.3k
            _PyObject_GC_TRACK(op);
3099
59.3k
        }
3100
        /* Call the deallocator directly.  This used to try to
3101
         * fool Py_DECREF into calling it indirectly, but
3102
         * Py_DECREF was already called on this object, and in
3103
         * assorted non-release builds calling Py_DECREF again ends
3104
         * up distorting allocation statistics.
3105
         */
3106
59.3k
        _PyObject_ASSERT(op, Py_REFCNT(op) == 0);
3107
59.3k
        (*dealloc)(op);
3108
59.3k
    }
3109
151
}
3110
3111
void _Py_NO_RETURN
3112
_PyObject_AssertFailed(PyObject *obj, const char *expr, const char *msg,
3113
                       const char *file, int line, const char *function)
3114
0
{
3115
0
    fprintf(stderr, "%s:%d: ", file, line);
3116
0
    if (function) {
3117
0
        fprintf(stderr, "%s: ", function);
3118
0
    }
3119
0
    fflush(stderr);
3120
3121
0
    if (expr) {
3122
0
        fprintf(stderr, "Assertion \"%s\" failed", expr);
3123
0
    }
3124
0
    else {
3125
0
        fprintf(stderr, "Assertion failed");
3126
0
    }
3127
0
    fflush(stderr);
3128
3129
0
    if (msg) {
3130
0
        fprintf(stderr, ": %s", msg);
3131
0
    }
3132
0
    fprintf(stderr, "\n");
3133
0
    fflush(stderr);
3134
3135
0
    if (_PyObject_IsFreed(obj)) {
3136
        /* It seems like the object memory has been freed:
3137
           don't access it to prevent a segmentation fault. */
3138
0
        fprintf(stderr, "<object at %p is freed>\n", obj);
3139
0
        fflush(stderr);
3140
0
    }
3141
0
    else {
3142
        /* Display the traceback where the object has been allocated.
3143
           Do it before dumping repr(obj), since repr() is more likely
3144
           to crash than dumping the traceback. */
3145
0
        PyTypeObject *type = Py_TYPE(obj);
3146
0
        const size_t presize = _PyType_PreHeaderSize(type);
3147
0
        void *ptr = (void *)((char *)obj - presize);
3148
0
        _PyMem_DumpTraceback(fileno(stderr), ptr);
3149
3150
        /* This might succeed or fail, but we're about to abort, so at least
3151
           try to provide any extra info we can: */
3152
0
        _PyObject_Dump(obj);
3153
3154
0
        fprintf(stderr, "\n");
3155
0
        fflush(stderr);
3156
0
    }
3157
3158
0
    Py_FatalError("_PyObject_AssertFailed");
3159
0
}
3160
3161
3162
/*
3163
When deallocating a container object, it's possible to trigger an unbounded
3164
chain of deallocations, as each Py_DECREF in turn drops the refcount on "the
3165
next" object in the chain to 0.  This can easily lead to stack overflows.
3166
To avoid that, if the C stack is nearing its limit, instead of calling
3167
dealloc on the object, it is added to a queue to be freed later when the
3168
stack is shallower */
3169
void
3170
_Py_Dealloc(PyObject *op)
3171
415M
{
3172
415M
    PyTypeObject *type = Py_TYPE(op);
3173
415M
    unsigned long gc_flag = type->tp_flags & Py_TPFLAGS_HAVE_GC;
3174
415M
    destructor dealloc = type->tp_dealloc;
3175
415M
    PyThreadState *tstate = _PyThreadState_GET();
3176
415M
    intptr_t margin = _Py_RecursionLimit_GetMargin(tstate);
3177
415M
    if (margin < 2 && gc_flag) {
3178
59.3k
        _PyTrash_thread_deposit_object(tstate, (PyObject *)op);
3179
59.3k
        return;
3180
59.3k
    }
3181
#ifdef Py_DEBUG
3182
#if !defined(Py_GIL_DISABLED) && !defined(Py_STACKREF_DEBUG)
3183
    /* This assertion doesn't hold for the free-threading build, as
3184
     * PyStackRef_CLOSE_SPECIALIZED is not implemented */
3185
    assert(tstate->current_frame == NULL || tstate->current_frame->stackpointer != NULL);
3186
#endif
3187
    PyObject *old_exc = tstate != NULL ? tstate->current_exception : NULL;
3188
    // Keep the old exception type alive to prevent undefined behavior
3189
    // on (tstate->curexc_type != old_exc_type) below
3190
    Py_XINCREF(old_exc);
3191
    // Make sure that type->tp_name remains valid
3192
    Py_INCREF(type);
3193
#endif
3194
3195
#ifdef Py_TRACE_REFS
3196
    _Py_ForgetReference(op);
3197
#endif
3198
415M
    _PyReftracerTrack(op, PyRefTracer_DESTROY);
3199
415M
    (*dealloc)(op);
3200
3201
#ifdef Py_DEBUG
3202
    // gh-89373: The tp_dealloc function must leave the current exception
3203
    // unchanged.
3204
    if (tstate != NULL && tstate->current_exception != old_exc) {
3205
        const char *err;
3206
        if (old_exc == NULL) {
3207
            err = "Deallocator of type '%s' raised an exception";
3208
        }
3209
        else if (tstate->current_exception == NULL) {
3210
            err = "Deallocator of type '%s' cleared the current exception";
3211
        }
3212
        else {
3213
            // It can happen if dealloc() normalized the current exception.
3214
            // A deallocator function must not change the current exception,
3215
            // not even normalize it.
3216
            err = "Deallocator of type '%s' overrode the current exception";
3217
        }
3218
        _Py_FatalErrorFormat(__func__, err, type->tp_name);
3219
    }
3220
    Py_XDECREF(old_exc);
3221
    Py_DECREF(type);
3222
#endif
3223
415M
    if (tstate->delete_later && margin >= 4 && gc_flag) {
3224
151
        _PyTrash_thread_destroy_chain(tstate);
3225
151
    }
3226
415M
}
3227
3228
3229
PyObject **
3230
PyObject_GET_WEAKREFS_LISTPTR(PyObject *op)
3231
0
{
3232
0
    return _PyObject_GET_WEAKREFS_LISTPTR(op);
3233
0
}
3234
3235
3236
#undef Py_NewRef
3237
#undef Py_XNewRef
3238
3239
// Export Py_NewRef() and Py_XNewRef() as regular functions for the stable ABI.
3240
PyObject*
3241
Py_NewRef(PyObject *obj)
3242
0
{
3243
0
    return _Py_NewRef(obj);
3244
0
}
3245
3246
PyObject*
3247
Py_XNewRef(PyObject *obj)
3248
0
{
3249
0
    return _Py_XNewRef(obj);
3250
0
}
3251
3252
#undef Py_Is
3253
#undef Py_IsNone
3254
#undef Py_IsTrue
3255
#undef Py_IsFalse
3256
3257
// Export Py_Is(), Py_IsNone(), Py_IsTrue(), Py_IsFalse() as regular functions
3258
// for the stable ABI.
3259
int Py_Is(PyObject *x, PyObject *y)
3260
0
{
3261
0
    return (x == y);
3262
0
}
3263
3264
int Py_IsNone(PyObject *x)
3265
0
{
3266
0
    return Py_Is(x, Py_None);
3267
0
}
3268
3269
int Py_IsTrue(PyObject *x)
3270
0
{
3271
0
    return Py_Is(x, Py_True);
3272
0
}
3273
3274
int Py_IsFalse(PyObject *x)
3275
0
{
3276
0
    return Py_Is(x, Py_False);
3277
0
}
3278
3279
3280
// Py_SET_REFCNT() implementation for stable ABI
3281
void
3282
_Py_SetRefcnt(PyObject *ob, Py_ssize_t refcnt)
3283
0
{
3284
0
    Py_SET_REFCNT(ob, refcnt);
3285
0
}
3286
3287
0
int PyRefTracer_SetTracer(PyRefTracer tracer, void *data) {
3288
0
    _Py_AssertHoldsTstate();
3289
0
    _PyRuntime.ref_tracer.tracer_func = tracer;
3290
0
    _PyRuntime.ref_tracer.tracer_data = data;
3291
0
    return 0;
3292
0
}
3293
3294
0
PyRefTracer PyRefTracer_GetTracer(void** data) {
3295
0
    _Py_AssertHoldsTstate();
3296
0
    if (data != NULL) {
3297
0
        *data = _PyRuntime.ref_tracer.tracer_data;
3298
0
    }
3299
0
    return _PyRuntime.ref_tracer.tracer_func;
3300
0
}
3301
3302
3303
3304
static PyObject* constants[] = {
3305
    &_Py_NoneStruct,                   // Py_CONSTANT_NONE
3306
    (PyObject*)(&_Py_FalseStruct),     // Py_CONSTANT_FALSE
3307
    (PyObject*)(&_Py_TrueStruct),      // Py_CONSTANT_TRUE
3308
    &_Py_EllipsisObject,               // Py_CONSTANT_ELLIPSIS
3309
    &_Py_NotImplementedStruct,         // Py_CONSTANT_NOT_IMPLEMENTED
3310
    NULL,  // Py_CONSTANT_ZERO
3311
    NULL,  // Py_CONSTANT_ONE
3312
    NULL,  // Py_CONSTANT_EMPTY_STR
3313
    NULL,  // Py_CONSTANT_EMPTY_BYTES
3314
    NULL,  // Py_CONSTANT_EMPTY_TUPLE
3315
};
3316
3317
void
3318
_Py_GetConstant_Init(void)
3319
22
{
3320
22
    constants[Py_CONSTANT_ZERO] = _PyLong_GetZero();
3321
22
    constants[Py_CONSTANT_ONE] = _PyLong_GetOne();
3322
22
    constants[Py_CONSTANT_EMPTY_STR] = PyUnicode_New(0, 0);
3323
22
    constants[Py_CONSTANT_EMPTY_BYTES] = PyBytes_FromStringAndSize(NULL, 0);
3324
22
    constants[Py_CONSTANT_EMPTY_TUPLE] = PyTuple_New(0);
3325
22
#ifndef NDEBUG
3326
242
    for (size_t i=0; i < Py_ARRAY_LENGTH(constants); i++) {
3327
220
        assert(constants[i] != NULL);
3328
220
        assert(_Py_IsImmortal(constants[i]));
3329
220
    }
3330
22
#endif
3331
22
}
3332
3333
PyObject*
3334
Py_GetConstant(unsigned int constant_id)
3335
392k
{
3336
392k
    if (constant_id < Py_ARRAY_LENGTH(constants)) {
3337
392k
        return constants[constant_id];
3338
392k
    }
3339
0
    else {
3340
0
        PyErr_BadInternalCall();
3341
0
        return NULL;
3342
0
    }
3343
392k
}
3344
3345
3346
PyObject*
3347
Py_GetConstantBorrowed(unsigned int constant_id)
3348
0
{
3349
    // All constants are immortal
3350
0
    return Py_GetConstant(constant_id);
3351
0
}
3352
3353
3354
// Py_TYPE() implementation for the stable ABI
3355
#undef Py_TYPE
3356
PyTypeObject*
3357
Py_TYPE(PyObject *ob)
3358
0
{
3359
0
    return _Py_TYPE(ob);
3360
0
}
3361
3362
3363
// Py_REFCNT() implementation for the stable ABI
3364
#undef Py_REFCNT
3365
Py_ssize_t
3366
Py_REFCNT(PyObject *ob)
3367
0
{
3368
0
    return _Py_REFCNT(ob);
3369
0
}
3370
3371
int
3372
PyUnstable_IsImmortal(PyObject *op)
3373
224
{
3374
    /* Checking a reference count requires a thread state */
3375
224
    _Py_AssertHoldsTstate();
3376
224
    assert(op != NULL);
3377
224
    return _Py_IsImmortal(op);
3378
224
}
3379
3380
int
3381
PyUnstable_Object_IsUniquelyReferenced(PyObject *op)
3382
0
{
3383
0
    _Py_AssertHoldsTstate();
3384
0
    assert(op != NULL);
3385
0
    return _PyObject_IsUniquelyReferenced(op);
3386
0
}