Coverage Report

Created: 2026-12-01 06:09

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