Coverage Report

Created: 2026-10-17 06:15

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