Coverage Report

Created: 2026-10-31 06:21

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.02M
{
557
2.02M
    PyObject *op = (PyObject *) PyObject_Malloc(_PyObject_SIZE(tp));
558
2.02M
    if (op == NULL) {
559
0
        return PyErr_NoMemory();
560
0
    }
561
2.02M
    _PyObject_Init(op, tp);
562
2.02M
    return op;
563
2.02M
}
564
565
PyVarObject *
566
_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
567
159k
{
568
159k
    PyVarObject *op;
569
159k
    const size_t size = _PyObject_VAR_SIZE(tp, nitems);
570
159k
    op = (PyVarObject *) PyObject_Malloc(size);
571
159k
    if (op == NULL) {
572
0
        return (PyVarObject *)PyErr_NoMemory();
573
0
    }
574
159k
    _PyObject_InitVar(op, tp, nitems);
575
159k
    return op;
576
159k
}
577
578
void
579
PyObject_CallFinalizer(PyObject *self)
580
40.9M
{
581
40.9M
    PyTypeObject *tp = Py_TYPE(self);
582
583
40.9M
    if (tp->tp_finalize == NULL)
584
0
        return;
585
    /* tp_finalize should only be called once. */
586
40.9M
    if (_PyType_IS_GC(tp) && _PyGC_FINALIZED(self))
587
44.3k
        return;
588
589
40.8M
    tp->tp_finalize(self);
590
40.8M
    if (_PyType_IS_GC(tp)) {
591
40.8M
        _PyGC_SET_FINALIZED(self);
592
40.8M
    }
593
40.8M
}
594
595
int
596
PyObject_CallFinalizerFromDealloc(PyObject *self)
597
40.9M
{
598
40.9M
    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
40.9M
    _PyObject_ResurrectStart(self);
606
607
40.9M
    PyObject_CallFinalizer(self);
608
609
40.9M
    _PyObject_ASSERT_WITH_MSG(self,
610
40.9M
                              Py_REFCNT(self) > 0,
611
40.9M
                              "refcount is too small");
612
613
40.9M
    _PyObject_ASSERT(self,
614
40.9M
                    (!_PyType_IS_GC(Py_TYPE(self))
615
40.9M
                    || _PyObject_GC_IS_TRACKED(self)));
616
617
    /* Undo the temporary resurrection; can't use DECREF here, it would
618
     * cause a recursive call. */
619
40.9M
    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
40.9M
    return 0;
631
40.9M
}
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.7M
{
762
18.7M
    PyObject *res;
763
18.7M
    if (PyErr_CheckSignals())
764
0
        return NULL;
765
18.7M
    if (v == NULL)
766
0
        return PyUnicode_FromString("<NULL>");
767
18.7M
    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.7M
    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.7M
    if (_Py_EnterRecursiveCallTstate(tstate,
782
18.7M
                                     " while getting the repr of an object")) {
783
0
        return NULL;
784
0
    }
785
18.7M
    res = (*Py_TYPE(v)->tp_repr)(v);
786
18.7M
    _Py_LeaveRecursiveCallTstate(tstate);
787
788
18.7M
    if (res == NULL) {
789
2
        return NULL;
790
2
    }
791
18.7M
    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.7M
    return res;
798
18.7M
}
799
800
PyObject *
801
PyObject_Str(PyObject *v)
802
47.8M
{
803
47.8M
    PyObject *res;
804
47.8M
    if (PyErr_CheckSignals())
805
0
        return NULL;
806
47.8M
    if (v == NULL)
807
0
        return PyUnicode_FromString("<NULL>");
808
47.8M
    if (PyUnicode_CheckExact(v)) {
809
36.6M
        return Py_NewRef(v);
810
36.6M
    }
811
11.1M
    if (Py_TYPE(v)->tp_str == NULL)
812
0
        return PyObject_Repr(v);
813
814
11.1M
    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
11.1M
    if (_Py_EnterRecursiveCallTstate(tstate, " while getting the str of an object")) {
825
0
        return NULL;
826
0
    }
827
11.1M
    res = (*Py_TYPE(v)->tp_str)(v);
828
11.1M
    _Py_LeaveRecursiveCallTstate(tstate);
829
830
11.1M
    if (res == NULL) {
831
5.23k
        return NULL;
832
5.23k
    }
833
11.1M
    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
11.1M
    assert(_PyUnicode_CheckConsistency(res, 1));
840
11.1M
    return res;
841
11.1M
}
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.7k
{
906
30.7k
    void *ptr;
907
901k
    while ((ptr = _PyFreeList_PopNoStats(freelist)) != NULL) {
908
871k
        dofree(ptr);
909
871k
    }
910
30.7k
    assert(freelist->size == 0 || freelist->size == -1);
911
30.7k
    assert(freelist->freelist == NULL);
912
30.7k
    if (is_finalization) {
913
0
        freelist->size = -1;
914
0
    }
915
30.7k
}
916
917
static void
918
free_object(void *obj)
919
855k
{
920
855k
    PyObject *op = (PyObject *)obj;
921
855k
    PyTypeObject *tp = Py_TYPE(op);
922
855k
    tp->tp_free(op);
923
855k
    Py_DECREF(tp);
924
855k
}
925
926
void
927
_PyObject_ClearFreeLists(struct _Py_freelists *freelists, int is_finalization)
928
769
{
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
769
    clear_freelist(&freelists->floats, is_finalization, free_object);
932
769
    clear_freelist(&freelists->complexes, is_finalization, free_object);
933
16.1k
    for (Py_ssize_t i = 0; i < PyTuple_MAXSAVESIZE; i++) {
934
15.3k
        clear_freelist(&freelists->tuples[i], is_finalization, free_object);
935
15.3k
    }
936
769
    clear_freelist(&freelists->lists, is_finalization, free_object);
937
769
    clear_freelist(&freelists->list_iters, is_finalization, free_object);
938
769
    clear_freelist(&freelists->tuple_iters, is_finalization, free_object);
939
769
    clear_freelist(&freelists->dicts, is_finalization, free_object);
940
769
    clear_freelist(&freelists->dictkeys, is_finalization, PyMem_Free);
941
769
    clear_freelist(&freelists->slices, is_finalization, free_object);
942
769
    clear_freelist(&freelists->ranges, is_finalization, free_object);
943
769
    clear_freelist(&freelists->range_iters, is_finalization, free_object);
944
769
    clear_freelist(&freelists->contexts, is_finalization, free_object);
945
769
    clear_freelist(&freelists->async_gens, is_finalization, free_object);
946
769
    clear_freelist(&freelists->async_gen_asends, is_finalization, free_object);
947
769
    clear_freelist(&freelists->futureiters, is_finalization, free_object);
948
769
    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
769
    clear_freelist(&freelists->unicode_writers, is_finalization, PyMem_Free);
954
769
    clear_freelist(&freelists->bytes_writers, is_finalization, PyMem_Free);
955
769
    clear_freelist(&freelists->ints, is_finalization, free_object);
956
769
    clear_freelist(&freelists->pycfunctionobject, is_finalization, PyObject_GC_Del);
957
769
    clear_freelist(&freelists->pycmethodobject, is_finalization, PyObject_GC_Del);
958
769
    clear_freelist(&freelists->pymethodobjects, is_finalization, free_object);
959
769
}
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
306M
{
1051
306M
    richcmpfunc f;
1052
306M
    PyObject *res;
1053
306M
    int checked_reverse_op = 0;
1054
1055
306M
    if (!Py_IS_TYPE(v, Py_TYPE(w)) &&
1056
20.7M
        PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v)) &&
1057
623k
        (f = Py_TYPE(w)->tp_richcompare) != NULL) {
1058
623k
        checked_reverse_op = 1;
1059
623k
        res = (*f)(w, v, _Py_SwappedOp[op]);
1060
623k
        if (res != Py_NotImplemented)
1061
588k
            return res;
1062
35.5k
        Py_DECREF(res);
1063
35.5k
    }
1064
306M
    if ((f = Py_TYPE(v)->tp_richcompare) != NULL) {
1065
306M
        res = (*f)(v, w, op);
1066
306M
        if (res != Py_NotImplemented)
1067
291M
            return res;
1068
14.6M
        Py_DECREF(res);
1069
14.6M
    }
1070
14.6M
    if (!checked_reverse_op && (f = Py_TYPE(w)->tp_richcompare) != NULL) {
1071
14.6M
        res = (*f)(w, v, _Py_SwappedOp[op]);
1072
14.6M
        if (res != Py_NotImplemented)
1073
5.49M
            return res;
1074
9.10M
        Py_DECREF(res);
1075
9.10M
    }
1076
    /* If neither object implements it, provide a sensible default
1077
       for == and !=, but raise an exception for ordering. */
1078
9.14M
    switch (op) {
1079
9.14M
    case Py_EQ:
1080
9.14M
        res = (v == w) ? Py_True : Py_False;
1081
9.14M
        break;
1082
1.16k
    case Py_NE:
1083
1.16k
        res = (v != w) ? Py_True : Py_False;
1084
1.16k
        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
9.14M
    }
1093
9.14M
    return Py_NewRef(res);
1094
9.14M
}
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
306M
{
1102
306M
    PyThreadState *tstate = _PyThreadState_GET();
1103
1104
306M
    assert(Py_LT <= op && op <= Py_GE);
1105
306M
    if (v == NULL || w == NULL) {
1106
0
        if (!_PyErr_Occurred(tstate)) {
1107
0
            PyErr_BadInternalCall();
1108
0
        }
1109
0
        return NULL;
1110
0
    }
1111
306M
    if (_Py_EnterRecursiveCallTstate(tstate, " in comparison")) {
1112
0
        return NULL;
1113
0
    }
1114
306M
    PyObject *res = do_richcompare(tstate, v, w, op);
1115
306M
    _Py_LeaveRecursiveCallTstate(tstate);
1116
306M
    return res;
1117
306M
}
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
288M
{
1124
288M
    PyObject *res;
1125
288M
    int ok;
1126
1127
    /* Quick result when objects are the same.
1128
       Guarantees that identity implies equality. */
1129
288M
    if (v == w) {
1130
36.8M
        if (op == Py_EQ)
1131
33.5M
            return 1;
1132
3.29M
        else if (op == Py_NE)
1133
0
            return 0;
1134
36.8M
    }
1135
1136
255M
    res = PyObject_RichCompare(v, w, op);
1137
255M
    if (res == NULL)
1138
0
        return -1;
1139
255M
    if (PyBool_Check(res)) {
1140
255M
        ok = (res == Py_True);
1141
255M
        assert(_Py_IsImmortal(res));
1142
255M
    }
1143
0
    else {
1144
0
        ok = PyObject_IsTrue(res);
1145
0
        Py_DECREF(res);
1146
0
    }
1147
255M
    return ok;
1148
255M
}
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.01G
{
1161
1.01G
    PyTypeObject *tp = Py_TYPE(v);
1162
1.01G
    if (tp->tp_hash != NULL)
1163
1.01G
        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
559k
{
1182
559k
    PyObject *w, *res;
1183
1184
559k
    if (Py_TYPE(v)->tp_getattr != NULL)
1185
0
        return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
1186
559k
    w = PyUnicode_FromString(name);
1187
559k
    if (w == NULL)
1188
0
        return NULL;
1189
559k
    res = PyObject_GetAttr(v, w);
1190
559k
    Py_DECREF(w);
1191
559k
    return res;
1192
559k
}
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
88.4k
{
1221
88.4k
    PyThreadState *tstate = _PyThreadState_GET();
1222
88.4k
    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
88.4k
    if (Py_TYPE(v)->tp_setattr != NULL) {
1232
0
        return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
1233
0
    }
1234
1235
88.4k
    PyObject *s = PyUnicode_InternFromString(name);
1236
88.4k
    if (s == NULL) {
1237
0
        return -1;
1238
0
    }
1239
1240
88.4k
    int res = PyObject_SetAttr(v, s, w);
1241
88.4k
    Py_DECREF(s);
1242
88.4k
    return res;
1243
88.4k
}
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.1k
{
1254
30.1k
    int res;
1255
30.1k
    PyObject* isabstract;
1256
1257
30.1k
    if (obj == NULL)
1258
534
        return 0;
1259
1260
29.6k
    res = PyObject_GetOptionalAttr(obj, &_Py_ID(__isabstractmethod__), &isabstract);
1261
29.6k
    if (res > 0) {
1262
4.13k
        res = PyObject_IsTrue(isabstract);
1263
4.13k
        Py_DECREF(isabstract);
1264
4.13k
    }
1265
29.6k
    return res;
1266
30.1k
}
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
2.84M
{
1285
2.84M
    assert(PyErr_Occurred());
1286
2.84M
    if (!PyErr_ExceptionMatches(PyExc_AttributeError)){
1287
2.73k
        return 0;
1288
2.73k
    }
1289
    // Intercept AttributeError exceptions and augment them to offer suggestions later.
1290
2.84M
    PyObject *exc = PyErr_GetRaisedException();
1291
2.84M
    if (!PyErr_GivenExceptionMatches(exc, PyExc_AttributeError)) {
1292
0
        goto restore;
1293
0
    }
1294
2.84M
    PyAttributeErrorObject* the_exc = (PyAttributeErrorObject*) exc;
1295
    // Check if this exception was already augmented
1296
2.84M
    if (the_exc->name || the_exc->obj) {
1297
1.13M
        goto restore;
1298
1.13M
    }
1299
    // Augment the exception with the name and object
1300
1.70M
    if (PyObject_SetAttr(exc, &_Py_ID(name), name) ||
1301
1.70M
        PyObject_SetAttr(exc, &_Py_ID(obj), v)) {
1302
0
        Py_DECREF(exc);
1303
0
        return 1;
1304
0
    }
1305
2.84M
restore:
1306
2.84M
    PyErr_SetRaisedException(exc);
1307
2.84M
    return 0;
1308
1.70M
}
1309
1310
PyObject *
1311
PyObject_GetAttr(PyObject *v, PyObject *name)
1312
49.1M
{
1313
49.1M
    PyTypeObject *tp = Py_TYPE(v);
1314
49.1M
    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
49.1M
    PyObject* result = NULL;
1322
49.1M
    if (tp->tp_getattro != NULL) {
1323
49.1M
        result = (*tp->tp_getattro)(v, name);
1324
49.1M
    }
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
49.1M
    if (result == NULL) {
1339
1.05M
        _PyObject_SetAttributeErrorContext(v, name);
1340
1.05M
    }
1341
49.1M
    return result;
1342
49.1M
}
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
344M
{
1350
344M
    PyTypeObject *tp = Py_TYPE(v);
1351
344M
    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
344M
    if (tp->tp_getattro == _Py_type_getattro) {
1360
29.0M
        _PyStackRef result = _Py_type_getattro_stackref((PyTypeObject *)v, name, NULL);
1361
29.0M
        if (PyStackRef_IsNull(result)) {
1362
93
            _PyObject_SetAttributeErrorContext(v, name);
1363
93
        }
1364
29.0M
        return result;
1365
29.0M
    }
1366
1367
    /* Fall back to regular PyObject_GetAttr and convert to stackref */
1368
315M
    PyObject *result = NULL;
1369
315M
    if (tp->tp_getattro != NULL) {
1370
315M
        result = (*tp->tp_getattro)(v, name);
1371
315M
    }
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
315M
    if (result == NULL) {
1386
505k
        _PyObject_SetAttributeErrorContext(v, name);
1387
505k
        return PyStackRef_NULL;
1388
505k
    }
1389
314M
    return PyStackRef_FromPyObjectSteal(result);
1390
315M
}
1391
1392
int
1393
PyObject_GetOptionalAttr(PyObject *v, PyObject *name, PyObject **result)
1394
84.9M
{
1395
84.9M
    PyTypeObject *tp = Py_TYPE(v);
1396
1397
84.9M
    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
84.9M
    if (tp->tp_getattro == PyObject_GenericGetAttr) {
1406
79.1M
        *result = _PyObject_GenericGetAttrWithDict(v, name, NULL, 1);
1407
79.1M
        if (*result != NULL) {
1408
65.7M
            return 1;
1409
65.7M
        }
1410
13.3M
        if (PyErr_Occurred()) {
1411
0
            return -1;
1412
0
        }
1413
13.3M
        return 0;
1414
13.3M
    }
1415
5.87M
    if (tp->tp_getattro == _Py_type_getattro) {
1416
163k
        int suppress_missing_attribute_exception = 0;
1417
163k
        *result = _Py_type_getattro_impl((PyTypeObject*)v, name, &suppress_missing_attribute_exception);
1418
163k
        if (suppress_missing_attribute_exception) {
1419
            // return 0 without having to clear the exception
1420
6.78k
            return 0;
1421
6.78k
        }
1422
163k
    }
1423
5.70M
    else if (tp->tp_getattro == (getattrofunc)_Py_module_getattro) {
1424
        // optimization: suppress attribute error from module getattro method
1425
4.91M
        *result = _Py_module_getattro_impl((PyModuleObject*)v, name, 1);
1426
4.91M
        if (*result != NULL) {
1427
4.25M
            return 1;
1428
4.25M
        }
1429
662k
        if (PyErr_Occurred()) {
1430
0
            return -1;
1431
0
        }
1432
662k
        return 0;
1433
662k
    }
1434
791k
    else if (tp->tp_getattro != NULL) {
1435
791k
        *result = (*tp->tp_getattro)(v, name);
1436
791k
    }
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
948k
    if (*result != NULL) {
1451
802k
        return 1;
1452
802k
    }
1453
146k
    if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
1454
0
        return -1;
1455
0
    }
1456
146k
    PyErr_Clear();
1457
146k
    return 0;
1458
146k
}
1459
1460
int
1461
PyObject_GetOptionalAttrString(PyObject *obj, const char *name, PyObject **result)
1462
564
{
1463
564
    if (Py_TYPE(obj)->tp_getattr == NULL) {
1464
564
        PyObject *oname = PyUnicode_FromString(name);
1465
564
        if (oname == NULL) {
1466
0
            *result = NULL;
1467
0
            return -1;
1468
0
        }
1469
564
        int rc = PyObject_GetOptionalAttr(obj, oname, result);
1470
564
        Py_DECREF(oname);
1471
564
        return rc;
1472
564
    }
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.14M
{
1488
9.14M
    PyObject *res;
1489
9.14M
    int rc = PyObject_GetOptionalAttr(obj, name, &res);
1490
9.14M
    Py_XDECREF(res);
1491
9.14M
    return rc;
1492
9.14M
}
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
85.3M
{
1511
85.3M
    PyThreadState *tstate = _PyThreadState_GET();
1512
85.3M
    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
85.3M
    PyTypeObject *tp = Py_TYPE(v);
1522
85.3M
    int err;
1523
1524
85.3M
    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
85.3M
    Py_INCREF(name);
1531
1532
85.3M
    _PyUnicode_InternMortal(tstate->interp, &name);
1533
85.3M
    if (tp->tp_setattro != NULL) {
1534
85.3M
        err = (*tp->tp_setattro)(v, name, value);
1535
85.3M
        Py_DECREF(name);
1536
85.3M
        return err;
1537
85.3M
    }
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.70k
{
1570
1.70k
    return PyObject_SetAttr(v, name, NULL);
1571
1.70k
}
1572
1573
PyObject **
1574
_PyObject_ComputedDictPointer(PyObject *obj)
1575
215M
{
1576
215M
    PyTypeObject *tp = Py_TYPE(obj);
1577
215M
    assert((tp->tp_flags & Py_TPFLAGS_MANAGED_DICT) == 0);
1578
1579
215M
    Py_ssize_t dictoffset = tp->tp_dictoffset;
1580
215M
    if (dictoffset == 0) {
1581
106M
        return NULL;
1582
106M
    }
1583
1584
108M
    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
108M
    return (PyObject **) ((char *)obj + dictoffset);
1599
215M
}
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
20.4M
{
1628
20.4M
    return Py_NewRef(obj);
1629
20.4M
}
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
95.7M
{
1760
95.7M
    int meth_found = 0;
1761
95.7M
    PyObject *obj = PyStackRef_AsPyObjectBorrow(*self);
1762
1763
95.7M
    assert(PyStackRef_IsNull(*method));
1764
1765
95.7M
    PyTypeObject *tp = Py_TYPE(obj);
1766
95.7M
    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
95.7M
    if (tp->tp_getattro != PyObject_GenericGetAttr || !PyUnicode_CheckExact(name)) {
1774
32.0M
        PyObject *res = PyObject_GetAttr(obj, name);
1775
32.0M
        PyStackRef_CLEAR(*self);
1776
32.0M
        if (res != NULL) {
1777
32.0M
            *method = PyStackRef_FromPyObjectSteal(res);
1778
32.0M
            return 0;
1779
32.0M
        }
1780
2.13k
        return -1;
1781
32.0M
    }
1782
1783
63.7M
    _PyType_LookupStackRefAndVersion(tp, name, method);
1784
63.7M
    PyObject *descr = PyStackRef_AsPyObjectBorrow(*method);
1785
63.7M
    descrgetfunc f = NULL;
1786
63.7M
    if (descr != NULL) {
1787
63.6M
        if (_PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_METHOD_DESCRIPTOR)) {
1788
63.0M
            meth_found = 1;
1789
63.0M
        }
1790
597k
        else {
1791
597k
            f = Py_TYPE(descr)->tp_descr_get;
1792
597k
            if (f != NULL && PyDescr_IsData(descr)) {
1793
41
                PyObject *value = f(descr, obj, (PyObject *)Py_TYPE(obj));
1794
41
                PyStackRef_CLEAR(*method);
1795
41
                PyStackRef_CLEAR(*self);
1796
41
                if (value != NULL) {
1797
41
                    *method = PyStackRef_FromPyObjectSteal(value);
1798
41
                    return 0;
1799
41
                }
1800
0
                return -1;
1801
41
            }
1802
597k
        }
1803
63.6M
    }
1804
63.7M
    PyObject *dict, *attr;
1805
63.7M
    if ((tp->tp_flags & Py_TPFLAGS_INLINE_VALUES) &&
1806
33.5M
         _PyObject_TryGetInstanceAttribute(obj, name, &attr)) {
1807
1.14M
        if (attr != NULL) {
1808
9.07k
            PyStackRef_XSETREF(*method, PyStackRef_FromPyObjectSteal(attr));
1809
9.07k
            PyStackRef_CLEAR(*self);
1810
9.07k
            return 0;
1811
9.07k
        }
1812
1.13M
        dict = NULL;
1813
1.13M
    }
1814
62.5M
    else if ((tp->tp_flags & Py_TPFLAGS_MANAGED_DICT)) {
1815
32.4M
        dict = (PyObject *)_PyObject_GetManagedDict(obj);
1816
32.4M
    }
1817
30.1M
    else {
1818
30.1M
        PyObject **dictptr = _PyObject_ComputedDictPointer(obj);
1819
30.1M
        if (dictptr != NULL) {
1820
28.6M
            dict = FT_ATOMIC_LOAD_PTR_ACQUIRE(*dictptr);
1821
28.6M
        }
1822
1.47M
        else {
1823
1.47M
            dict = NULL;
1824
1.47M
        }
1825
30.1M
    }
1826
63.6M
    if (dict != NULL) {
1827
60.7M
        assert(PyUnicode_CheckExact(name));
1828
60.7M
        int found = _PyDict_GetMethodStackRef((PyDictObject *)dict, name, method);
1829
60.7M
        if (found < 0) {
1830
0
            assert(PyStackRef_IsNull(*method));
1831
0
            PyStackRef_CLEAR(*self);
1832
0
            return -1;
1833
0
        }
1834
60.7M
        else if (found) {
1835
19
            PyStackRef_CLEAR(*self);
1836
19
            return 0;
1837
19
        }
1838
60.7M
    }
1839
1840
63.6M
    if (meth_found) {
1841
63.0M
        assert(!PyStackRef_IsNull(*method));
1842
63.0M
        return 1;
1843
63.0M
    }
1844
1845
597k
    if (f != NULL) {
1846
341k
        if (Py_IS_TYPE(descr, &PyClassMethod_Type)) {
1847
330k
            PyObject *callable = _PyClassMethod_GetFunc(descr);
1848
330k
            PyStackRef_XSETREF(*method, PyStackRef_FromPyObjectNew(callable));
1849
330k
            PyStackRef_XSETREF(*self, PyStackRef_FromPyObjectNew((PyObject *)tp));
1850
330k
            return 1;
1851
330k
        }
1852
10.6k
        else if (Py_IS_TYPE(descr, &PyStaticMethod_Type)) {
1853
10.6k
            PyObject *callable = _PyStaticMethod_GetFunc(descr);
1854
10.6k
            PyStackRef_XSETREF(*method, PyStackRef_FromPyObjectNew(callable));
1855
10.6k
            PyStackRef_CLEAR(*self);
1856
10.6k
            return 0;
1857
10.6k
        }
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
256k
    if (descr != NULL) {
1869
256k
        assert(!PyStackRef_IsNull(*method));
1870
256k
        PyStackRef_CLEAR(*self);
1871
256k
        return 0;
1872
256k
    }
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
256k
}
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
408M
{
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
408M
    PyTypeObject *tp = Py_TYPE(obj);
1898
408M
    PyObject *descr = NULL;
1899
408M
    PyObject *res = NULL;
1900
408M
    descrgetfunc f;
1901
1902
408M
    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
408M
    if (!_PyType_IsReady(tp)) {
1910
0
        if (PyType_Ready(tp) < 0)
1911
0
            return NULL;
1912
0
    }
1913
1914
408M
    Py_INCREF(name);
1915
1916
408M
    PyThreadState *tstate = _PyThreadState_GET();
1917
408M
    _PyCStackRef cref;
1918
408M
    _PyThreadState_PushCStackRef(tstate, &cref);
1919
1920
408M
    _PyType_LookupStackRefAndVersion(tp, name, &cref.ref);
1921
408M
    descr = PyStackRef_AsPyObjectBorrow(cref.ref);
1922
1923
408M
    f = NULL;
1924
408M
    if (descr != NULL) {
1925
292M
        f = Py_TYPE(descr)->tp_descr_get;
1926
292M
        if (f != NULL && PyDescr_IsData(descr)) {
1927
            // gh-157840: We special-case member descriptors here to avoid
1928
            // allocating an extra AttributeError
1929
77.8M
            if (suppress && Py_IS_TYPE(descr, &PyMemberDescr_Type)) {
1930
110k
                PyMemberDef *member = ((PyMemberDescrObject *)descr)->d_member;
1931
110k
                if (member->type == Py_T_OBJECT_EX
1932
109k
                    && !(member->flags & Py_AUDIT_READ)
1933
109k
                    && PyObject_TypeCheck(obj, PyDescr_TYPE(descr))) {
1934
109k
                    PyObject **addr = _PyMember_GetOffset(obj, member);
1935
109k
                    if (FT_ATOMIC_LOAD_PTR(*addr) == NULL) {
1936
9.72k
                        goto done;
1937
9.72k
                    }
1938
109k
                }
1939
110k
            }
1940
77.8M
            res = f(descr, obj, (PyObject *)Py_TYPE(obj));
1941
77.8M
            if (res == NULL && suppress &&
1942
2.07k
                    PyErr_ExceptionMatches(PyExc_AttributeError)) {
1943
2.07k
                PyErr_Clear();
1944
2.07k
            }
1945
77.8M
            goto done;
1946
77.8M
        }
1947
292M
    }
1948
330M
    if (dict == NULL) {
1949
330M
        if ((tp->tp_flags & Py_TPFLAGS_INLINE_VALUES)) {
1950
164M
            if (PyUnicode_CheckExact(name) &&
1951
164M
                _PyObject_TryGetInstanceAttribute(obj, name, &res)) {
1952
58.6M
                if (res != NULL) {
1953
17.4M
                    goto done;
1954
17.4M
                }
1955
58.6M
            }
1956
105M
            else {
1957
105M
                dict = (PyObject *)_PyObject_MaterializeManagedDict(obj);
1958
105M
                if (dict == NULL) {
1959
0
                    res = NULL;
1960
0
                    goto done;
1961
0
                }
1962
105M
            }
1963
164M
        }
1964
166M
        else if ((tp->tp_flags & Py_TPFLAGS_MANAGED_DICT)) {
1965
4.26M
            dict = (PyObject *)_PyObject_GetManagedDict(obj);
1966
4.26M
        }
1967
162M
        else {
1968
162M
            PyObject **dictptr = _PyObject_ComputedDictPointer(obj);
1969
162M
            if (dictptr) {
1970
#ifdef Py_GIL_DISABLED
1971
                dict = _Py_atomic_load_ptr_acquire(dictptr);
1972
#else
1973
56.6M
                dict = *dictptr;
1974
56.6M
#endif
1975
56.6M
            }
1976
162M
        }
1977
330M
    }
1978
313M
    if (dict != NULL) {
1979
166M
        Py_INCREF(dict);
1980
166M
        int rc = PyDict_GetItemRef(dict, name, &res);
1981
166M
        Py_DECREF(dict);
1982
166M
        if (res != NULL) {
1983
137M
            goto done;
1984
137M
        }
1985
28.5M
        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
166M
    }
1994
1995
175M
    if (f != NULL) {
1996
124M
        res = f(descr, obj, (PyObject *)Py_TYPE(obj));
1997
124M
        if (res == NULL && suppress &&
1998
0
                PyErr_ExceptionMatches(PyExc_AttributeError)) {
1999
0
            PyErr_Clear();
2000
0
        }
2001
124M
        goto done;
2002
124M
    }
2003
2004
51.1M
    if (descr != NULL) {
2005
35.4M
        res = PyStackRef_AsPyObjectSteal(cref.ref);
2006
35.4M
        cref.ref = PyStackRef_NULL;
2007
35.4M
        goto done;
2008
35.4M
    }
2009
2010
15.6M
    if (!suppress) {
2011
1.28M
        PyErr_Format(PyExc_AttributeError,
2012
1.28M
                     "'%.100s' object has no attribute '%U'",
2013
1.28M
                     tp->tp_name, name);
2014
2015
1.28M
        _PyObject_SetAttributeErrorContext(obj, name);
2016
1.28M
    }
2017
408M
  done:
2018
408M
    _PyThreadState_PopCStackRef(tstate, &cref);
2019
408M
    Py_DECREF(name);
2020
408M
    return res;
2021
15.6M
}
2022
2023
PyObject *
2024
PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
2025
322M
{
2026
322M
    return _PyObject_GenericGetAttrWithDict(obj, name, NULL, 0);
2027
322M
}
2028
2029
int
2030
_PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
2031
                                 PyObject *value, PyObject *dict)
2032
85.2M
{
2033
85.2M
    PyTypeObject *tp = Py_TYPE(obj);
2034
85.2M
    PyObject *descr;
2035
85.2M
    descrsetfunc f;
2036
85.2M
    int res = -1;
2037
2038
85.2M
    assert(!PyType_IsSubtype(tp, &PyType_Type));
2039
85.2M
    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
85.2M
    if (!_PyType_IsReady(tp) && PyType_Ready(tp) < 0) {
2047
0
        return -1;
2048
0
    }
2049
2050
85.2M
    Py_INCREF(name);
2051
85.2M
    _Py_INCREF_TYPE(tp);
2052
2053
85.2M
    PyThreadState *tstate = _PyThreadState_GET();
2054
85.2M
    _PyCStackRef cref;
2055
85.2M
    _PyThreadState_PushCStackRef(tstate, &cref);
2056
2057
85.2M
    _PyType_LookupStackRefAndVersion(tp, name, &cref.ref);
2058
85.2M
    descr = PyStackRef_AsPyObjectBorrow(cref.ref);
2059
2060
85.2M
    if (descr != NULL) {
2061
46.1M
        f = Py_TYPE(descr)->tp_descr_set;
2062
46.1M
        if (f != NULL) {
2063
14.0M
            res = f(descr, obj, value);
2064
14.0M
            goto done;
2065
14.0M
        }
2066
46.1M
    }
2067
2068
71.1M
    if (dict == NULL) {
2069
70.9M
        PyObject **dictptr;
2070
2071
70.9M
        if ((tp->tp_flags & Py_TPFLAGS_INLINE_VALUES)) {
2072
47.7M
            res = _PyObject_StoreInstanceAttribute(obj, name, value);
2073
47.7M
            goto error_check;
2074
47.7M
        }
2075
2076
23.2M
        if ((tp->tp_flags & Py_TPFLAGS_MANAGED_DICT)) {
2077
27.0k
            PyManagedDictPointer *managed_dict = _PyObject_ManagedDictPointer(obj);
2078
27.0k
            dictptr = (PyObject **)&managed_dict->dict;
2079
27.0k
        }
2080
23.1M
        else {
2081
23.1M
            dictptr = _PyObject_ComputedDictPointer(obj);
2082
23.1M
        }
2083
23.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
23.2M
        else {
2106
23.2M
            res = _PyObjectDict_SetItem(tp, obj, dictptr, name, value);
2107
23.2M
        }
2108
23.2M
    }
2109
222k
    else {
2110
222k
        Py_INCREF(dict);
2111
222k
        if (value == NULL)
2112
0
            res = PyDict_DelItem(dict, name);
2113
222k
        else
2114
222k
            res = PyDict_SetItem(dict, name, value);
2115
222k
        Py_DECREF(dict);
2116
222k
    }
2117
71.1M
  error_check:
2118
71.1M
    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
85.2M
  done:
2125
85.2M
    _PyThreadState_PopCStackRef(tstate, &cref);
2126
85.2M
    _Py_DECREF_TYPE(tp);
2127
85.2M
    Py_DECREF(name);
2128
85.2M
    return res;
2129
71.1M
}
2130
2131
int
2132
PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
2133
85.0M
{
2134
85.0M
    return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL);
2135
85.0M
}
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
158M
{
2154
158M
    Py_ssize_t res;
2155
158M
    if (v == Py_True)
2156
22.1M
        return 1;
2157
136M
    if (v == Py_False)
2158
48.9M
        return 0;
2159
87.3M
    if (v == Py_None)
2160
3.03M
        return 0;
2161
84.3M
    else if (Py_TYPE(v)->tp_as_number != NULL &&
2162
71.2M
             Py_TYPE(v)->tp_as_number->nb_bool != NULL)
2163
4.04M
        res = (*Py_TYPE(v)->tp_as_number->nb_bool)(v);
2164
80.2M
    else if (Py_TYPE(v)->tp_as_mapping != NULL &&
2165
76.1M
             Py_TYPE(v)->tp_as_mapping->mp_length != NULL)
2166
32.5M
        res = (*Py_TYPE(v)->tp_as_mapping->mp_length)(v);
2167
47.7M
    else if (Py_TYPE(v)->tp_as_sequence != NULL &&
2168
43.6M
             Py_TYPE(v)->tp_as_sequence->sq_length != NULL)
2169
41.3M
        res = (*Py_TYPE(v)->tp_as_sequence->sq_length)(v);
2170
6.41M
    else
2171
6.41M
        return 1;
2172
    /* if it is negative, it should be either -1 or -2 */
2173
77.8M
    return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
2174
87.3M
}
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.75M
{
2194
9.75M
    if (x == NULL)
2195
0
        return 0;
2196
9.75M
    return Py_TYPE(x)->tp_call != NULL;
2197
9.75M
}
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.87k
{
2250
5.87k
    PyObject *result, *sorted;
2251
5.87k
    PyObject *dirfunc = _PyObject_LookupSpecial(obj, &_Py_ID(__dir__));
2252
2253
5.87k
    assert(obj != NULL);
2254
5.87k
    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.87k
    result = _PyObject_CallNoArgs(dirfunc);
2261
5.87k
    Py_DECREF(dirfunc);
2262
5.87k
    if (result == NULL)
2263
0
        return NULL;
2264
    /* return sorted(result) */
2265
5.87k
    sorted = PySequence_List(result);
2266
5.87k
    Py_DECREF(result);
2267
5.87k
    if (sorted == NULL)
2268
0
        return NULL;
2269
5.87k
    if (PyList_Sort(sorted)) {
2270
0
        Py_DECREF(sorted);
2271
0
        return NULL;
2272
0
    }
2273
5.87k
    return sorted;
2274
5.87k
}
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.87k
{
2283
5.87k
    return (obj == NULL) ? _dir_locals() : _dir_object(obj);
2284
5.87k
}
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
404
{
2296
404
    return PyUnicode_FromString("None");
2297
404
}
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
52.1k
{
2327
52.1k
    return 0xFCA86420;
2328
52.1k
}
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 _PyLegacyEventHandler_Type;
2537
extern PyTypeObject _PyLineIterator;
2538
extern PyTypeObject _PyMemoryIter_Type;
2539
extern PyTypeObject _PyPositionsIterator;
2540
extern PyTypeObject _Py_GenericAliasIterType;
2541
2542
static PyTypeObject* static_types[_Py_NUM_MANAGED_PREINITIALIZED_TYPES] = {
2543
    // The two most important base types: must be initialized first and
2544
    // deallocated last.
2545
    &PyBaseObject_Type,
2546
    &PyType_Type,
2547
2548
    // PyStaticMethod_Type and PyCFunction_Type are used by PyType_Ready()
2549
    // on other types and so must be initialized first.
2550
    &PyStaticMethod_Type,
2551
    &PyCFunction_Type,
2552
2553
    // Static types with base=&PyBaseObject_Type
2554
    &PyAsyncGen_Type,
2555
    &PyByteArrayIter_Type,
2556
    &PyByteArray_Type,
2557
    &PyBytesIter_Type,
2558
    &PyBytes_Type,
2559
    &PyCallIter_Type,
2560
    &PyCapsule_Type,
2561
    &PyCell_Type,
2562
    &PyClassMethodDescr_Type,
2563
    &PyClassMethod_Type,
2564
    &PyCode_Type,
2565
    &PyComplex_Type,
2566
    &PyContextToken_Type,
2567
    &PyContextVar_Type,
2568
    &PyContext_Type,
2569
    &PyCoro_Type,
2570
    &PyDictItems_Type,
2571
    &PyDictIterItem_Type,
2572
    &PyDictIterKey_Type,
2573
    &PyDictIterValue_Type,
2574
    &PyDictKeys_Type,
2575
    &PyDictProxy_Type,
2576
    &PyDictRevIterItem_Type,
2577
    &PyDictRevIterKey_Type,
2578
    &PyDictRevIterValue_Type,
2579
    &PyDictValues_Type,
2580
    &PyDict_Type,
2581
    &PyEllipsis_Type,
2582
    &PyEnum_Type,
2583
    &PyFilter_Type,
2584
    &PyFloat_Type,
2585
    &PyFrameLocalsProxy_Type,
2586
    &PyFrame_Type,
2587
    &PyFrozenDict_Type,
2588
    &PyFrozenSet_Type,
2589
    &PyFunction_Type,
2590
    &PyGen_Type,
2591
    &PyGetSetDescr_Type,
2592
    &PyInstanceMethod_Type,
2593
    &PyLazyImport_Type,
2594
    &PyListIter_Type,
2595
    &PyListRevIter_Type,
2596
    &PyList_Type,
2597
    &PyLongRangeIter_Type,
2598
    &PyLong_Type,
2599
    &PyMap_Type,
2600
    &PyMemberDescr_Type,
2601
    &PyMemoryView_Type,
2602
    &PyMethodDescr_Type,
2603
    &PyMethod_Type,
2604
    &PyModuleDef_Type,
2605
    &PyModule_Type,
2606
    &PyODictIter_Type,
2607
    &PyPickleBuffer_Type,
2608
    &PyProperty_Type,
2609
    &PyRangeIter_Type,
2610
    &PyRange_Type,
2611
    &PyReversed_Type,
2612
    &PySTEntry_Type,
2613
    &PySentinel_Type,
2614
    &PySeqIter_Type,
2615
    &PySetIter_Type,
2616
    &PySet_Type,
2617
    &PySlice_Type,
2618
    &PyStdPrinter_Type,
2619
    &PySuper_Type,
2620
    &PyTraceBack_Type,
2621
    &PyTupleIter_Type,
2622
    &PyTuple_Type,
2623
    &PyUnicodeIter_Type,
2624
    &PyUnicode_Type,
2625
    &PyWrapperDescr_Type,
2626
    &PyZip_Type,
2627
    &Py_GenericAliasType,
2628
    &_PyAsyncGenASend_Type,
2629
    &_PyAsyncGenAThrow_Type,
2630
    &_PyAsyncGenWrappedValue_Type,
2631
    &_PyBufferWrapper_Type,
2632
    &_PyContextTokenMissing_Type,
2633
    &_PyCoroWrapper_Type,
2634
    &_Py_GenericAliasIterType,
2635
    &_PyHamtItems_Type,
2636
    &_PyHamtKeys_Type,
2637
    &_PyHamtValues_Type,
2638
    &_PyHamt_ArrayNode_Type,
2639
    &_PyHamt_BitmapNode_Type,
2640
    &_PyHamt_CollisionNode_Type,
2641
    &_PyHamt_Type,
2642
    &_PyInstructionSequence_Type,
2643
    &_PyInterpolation_Type,
2644
    &_PyLegacyEventHandler_Type,
2645
    &_PyLineIterator,
2646
    &_PyManagedBuffer_Type,
2647
    &_PyMemoryIter_Type,
2648
    &_PyMethodWrapper_Type,
2649
    &_PyNamespace_Type,
2650
    &_PyNone_Type,
2651
    &_PyNotImplemented_Type,
2652
    &_PyPositionsIterator,
2653
    &_PyTemplate_Type,
2654
    &_PyTemplateIter_Type,
2655
    &_PyUnicodeASCIIIter_Type,
2656
    &_PyUnion_Type,
2657
#ifdef _Py_TIER2
2658
    &_PyUOpExecutor_Type,
2659
#else
2660
    // The array should have the same size on all builds; see gh-149139
2661
    NULL,
2662
#endif
2663
    &_PyWeakref_CallableProxyType,
2664
    &_PyWeakref_ProxyType,
2665
    &_PyWeakref_RefType,
2666
    &_PyTypeAlias_Type,
2667
    &_PyNoDefault_Type,
2668
2669
    // subclasses: _PyTypes_FiniTypes() deallocates them before their base
2670
    // class
2671
    &PyBool_Type,         // base=&PyLong_Type
2672
    &PyCMethod_Type,      // base=&PyCFunction_Type
2673
    &PyODictItems_Type,   // base=&PyDictItems_Type
2674
    &PyODictKeys_Type,    // base=&PyDictKeys_Type
2675
    &PyODictValues_Type,  // base=&PyDictValues_Type
2676
    &PyODict_Type,        // base=&PyDict_Type
2677
};
2678
2679
2680
PyStatus
2681
_PyTypes_InitTypes(PyInterpreterState *interp)
2682
37
{
2683
    // All other static types (unless initialized elsewhere)
2684
4.47k
    for (size_t i=0; i < Py_ARRAY_LENGTH(static_types); i++) {
2685
4.44k
        PyTypeObject *type = static_types[i];
2686
4.44k
        if (type == NULL) {
2687
74
            continue;
2688
74
        }
2689
4.36k
        if (_PyStaticType_InitBuiltin(interp, type) < 0) {
2690
0
            return _PyStatus_ERR("Can't initialize builtin type");
2691
0
        }
2692
4.36k
        if (type == &PyType_Type) {
2693
            // Sanitify checks of the two most important types
2694
37
            assert(PyBaseObject_Type.tp_base == NULL);
2695
37
            assert(PyType_Type.tp_base == &PyBaseObject_Type);
2696
37
        }
2697
4.36k
    }
2698
2699
    // Cache __reduce__ from PyBaseObject_Type object
2700
37
    PyObject *baseobj_dict = _PyType_GetDict(&PyBaseObject_Type);
2701
37
    PyObject *baseobj_reduce = PyDict_GetItemWithError(baseobj_dict, &_Py_ID(__reduce__));
2702
37
    if (baseobj_reduce == NULL && PyErr_Occurred()) {
2703
0
        return _PyStatus_ERR("Can't get __reduce__ from base object");
2704
0
    }
2705
37
    _Py_INTERP_CACHED_OBJECT(interp, objreduce) = baseobj_reduce;
2706
2707
    // Must be after static types are initialized
2708
37
    if (_Py_initialize_generic(interp) < 0) {
2709
0
        return _PyStatus_ERR("Can't initialize generic types");
2710
0
    }
2711
2712
37
    return _PyStatus_OK();
2713
37
}
2714
2715
2716
// Best-effort function clearing static types.
2717
//
2718
// Don't deallocate a type if it still has subclasses. If a Py_Finalize()
2719
// sub-function is interrupted by CTRL+C or fails with MemoryError, some
2720
// subclasses are not cleared properly. Leave the static type unchanged in this
2721
// case.
2722
void
2723
_PyTypes_FiniTypes(PyInterpreterState *interp)
2724
0
{
2725
    // Deallocate types in the reverse order to deallocate subclasses before
2726
    // their base classes.
2727
0
    for (Py_ssize_t i=Py_ARRAY_LENGTH(static_types)-1; i>=0; i--) {
2728
0
        PyTypeObject *type = static_types[i];
2729
0
        if (type == NULL) {
2730
0
            continue;
2731
0
        }
2732
0
        _PyStaticType_FiniBuiltin(interp, type);
2733
0
    }
2734
0
}
2735
2736
2737
static inline void
2738
new_reference(PyObject *op)
2739
3.36G
{
2740
    // Skip the immortal object check in Py_SET_REFCNT; always set refcnt to 1
2741
3.36G
#if !defined(Py_GIL_DISABLED)
2742
3.36G
#if SIZEOF_VOID_P > 4
2743
3.36G
    op->ob_refcnt_full = 1;
2744
3.36G
    assert(op->ob_refcnt == 1);
2745
3.36G
    assert(op->ob_flags == 0);
2746
#else
2747
    op->ob_refcnt = 1;
2748
#endif
2749
#else
2750
    op->ob_flags = 0;
2751
    op->ob_mutex = (PyMutex){ 0 };
2752
#ifdef _Py_THREAD_SANITIZER
2753
    _Py_atomic_store_uintptr_relaxed(&op->ob_tid, _Py_ThreadId());
2754
    _Py_atomic_store_uint8_relaxed(&op->ob_gc_bits, 0);
2755
    _Py_atomic_store_uint32_relaxed(&op->ob_ref_local, 1);
2756
    _Py_atomic_store_ssize_relaxed(&op->ob_ref_shared, 0);
2757
#else
2758
    op->ob_tid = _Py_ThreadId();
2759
    op->ob_gc_bits = 0;
2760
    op->ob_ref_local = 1;
2761
    op->ob_ref_shared = 0;
2762
#endif
2763
#endif
2764
#ifdef Py_TRACE_REFS
2765
    _Py_AddToAllObjects(op);
2766
#endif
2767
3.36G
    _PyReftracerTrack(op, PyRefTracer_CREATE);
2768
3.36G
}
2769
2770
void
2771
_Py_NewReference(PyObject *op)
2772
3.30G
{
2773
#ifdef Py_REF_DEBUG
2774
    _Py_IncRefTotal(_PyThreadState_GET());
2775
#endif
2776
3.30G
    new_reference(op);
2777
3.30G
}
2778
2779
void
2780
_Py_NewReferenceNoTotal(PyObject *op)
2781
63.0M
{
2782
63.0M
    new_reference(op);
2783
63.0M
}
2784
2785
void
2786
_Py_SetImmortalUntracked(PyObject *op)
2787
292k
{
2788
    // Check if already immortal to avoid degrading from static immortal to plain immortal
2789
292k
    if (_Py_IsImmortal(op)) {
2790
555
        return;
2791
555
    }
2792
#ifdef Py_GIL_DISABLED
2793
    _Py_atomic_store_uintptr_relaxed(&op->ob_tid, _Py_UNOWNED_TID);
2794
    _Py_atomic_store_uint32_relaxed(&op->ob_ref_local, _Py_IMMORTAL_REFCNT_LOCAL);
2795
    _Py_atomic_store_ssize_relaxed(&op->ob_ref_shared, 0);
2796
    _Py_atomic_or_uint8(&op->ob_gc_bits, _PyGC_BITS_DEFERRED);
2797
#elif SIZEOF_VOID_P > 4
2798
292k
    op->ob_flags = _Py_IMMORTAL_FLAGS;
2799
292k
    op->ob_refcnt = _Py_IMMORTAL_INITIAL_REFCNT;
2800
#else
2801
    op->ob_refcnt = _Py_IMMORTAL_INITIAL_REFCNT;
2802
#endif
2803
292k
}
2804
2805
void
2806
_Py_SetImmortal(PyObject *op)
2807
292k
{
2808
292k
    if (PyObject_IS_GC(op) && _PyObject_GC_IS_TRACKED(op)) {
2809
15.2k
        _PyObject_GC_UNTRACK(op);
2810
15.2k
    }
2811
292k
    _Py_SetImmortalUntracked(op);
2812
292k
}
2813
2814
void
2815
_PyObject_SetDeferredRefcount(PyObject *op)
2816
228k
{
2817
#ifdef Py_GIL_DISABLED
2818
    assert(PyType_IS_GC(Py_TYPE(op)));
2819
    assert(_Py_IsOwnedByCurrentThread(op));
2820
    assert(op->ob_ref_shared == 0);
2821
    _PyObject_SET_GC_BITS(op, _PyGC_BITS_DEFERRED);
2822
    op->ob_ref_shared = _Py_REF_SHARED(_Py_REF_DEFERRED, 0);
2823
#endif
2824
228k
}
2825
2826
int
2827
PyUnstable_Object_EnableDeferredRefcount(PyObject *op)
2828
268k
{
2829
#ifdef Py_GIL_DISABLED
2830
    if (!PyType_IS_GC(Py_TYPE(op))) {
2831
        // Deferred reference counting doesn't work
2832
        // on untracked types.
2833
        return 0;
2834
    }
2835
2836
    if (!PyObject_GC_IsTracked(op)) {
2837
        // When deferred refcount is enabled, the object will only be
2838
        // deallocated by the tracing garbage collector. So it must be tracked
2839
        // by the garbage collector.
2840
        return 0;
2841
    }
2842
2843
    uint8_t bits = _Py_atomic_load_uint8(&op->ob_gc_bits);
2844
    if ((bits & _PyGC_BITS_DEFERRED) != 0)
2845
    {
2846
        // Nothing to do.
2847
        return 0;
2848
    }
2849
2850
    if (_Py_atomic_compare_exchange_uint8(&op->ob_gc_bits, &bits, bits | _PyGC_BITS_DEFERRED) == 0)
2851
    {
2852
        // Someone beat us to it!
2853
        return 0;
2854
    }
2855
    _Py_atomic_add_ssize(&op->ob_ref_shared, _Py_REF_SHARED(_Py_REF_DEFERRED, 0));
2856
    return 1;
2857
#else
2858
268k
    return 0;
2859
268k
#endif
2860
268k
}
2861
2862
int
2863
PyUnstable_Object_IsUniqueReferencedTemporary(PyObject *op)
2864
0
{
2865
0
    if (!_PyObject_IsUniquelyReferenced(op)) {
2866
0
        return 0;
2867
0
    }
2868
2869
0
    _PyInterpreterFrame *frame = _PyEval_GetFrame();
2870
0
    if (frame == NULL) {
2871
0
        return 0;
2872
0
    }
2873
2874
0
    _PyStackRef *base = _PyFrame_Stackbase(frame);
2875
0
    _PyStackRef *stackpointer = frame->stackpointer;
2876
0
    while (stackpointer > base) {
2877
0
        stackpointer--;
2878
0
        _PyStackRef ref = *stackpointer;
2879
0
        if (PyStackRef_IsTaggedInt(ref)) {
2880
0
            continue;
2881
0
        }
2882
0
        if (op == PyStackRef_AsPyObjectBorrow(ref)) {
2883
0
            return PyStackRef_IsHeapSafe(ref);
2884
0
        }
2885
0
    }
2886
0
    return 0;
2887
0
}
2888
2889
int
2890
PyUnstable_TryIncRef(PyObject *op)
2891
0
{
2892
0
    return _Py_TryIncref(op);
2893
0
}
2894
2895
void
2896
PyUnstable_EnableTryIncRef(PyObject *op)
2897
0
{
2898
#ifdef Py_GIL_DISABLED
2899
    _PyObject_SetMaybeWeakref(op);
2900
#endif
2901
0
}
2902
2903
int
2904
PyUnstable_SetImmortal(PyObject *op)
2905
0
{
2906
0
    assert(op != NULL);
2907
0
    if (!_PyObject_IsUniquelyReferenced(op) || PyUnicode_Check(op)) {
2908
0
        return 0;
2909
0
    }
2910
0
    _Py_SetImmortal(op);
2911
0
    return 1;
2912
0
}
2913
2914
void
2915
_Py_ResurrectReference(PyObject *op)
2916
0
{
2917
#ifdef Py_TRACE_REFS
2918
    _Py_AddToAllObjects(op);
2919
#endif
2920
0
}
2921
2922
void
2923
_Py_ForgetReference(PyObject *op)
2924
0
{
2925
#ifdef Py_TRACE_REFS
2926
    if (Py_REFCNT(op) < 0) {
2927
        _PyObject_ASSERT_FAILED_MSG(op, "negative refcnt");
2928
    }
2929
2930
    PyInterpreterState *interp = _PyInterpreterState_GET();
2931
2932
#ifdef SLOW_UNREF_CHECK
2933
    if (!_PyRefchain_Get(interp, op)) {
2934
        /* Not found */
2935
        _PyObject_ASSERT_FAILED_MSG(op,
2936
                                    "object not found in the objects list");
2937
    }
2938
#endif
2939
2940
    _PyRefchain_Remove(interp, op);
2941
#endif
2942
0
}
2943
2944
2945
#ifdef Py_TRACE_REFS
2946
static int
2947
_Py_PrintReference(_Py_hashtable_t *ht,
2948
                   const void *key, const void *value,
2949
                   void *user_data)
2950
{
2951
    PyObject *op = (PyObject*)key;
2952
    FILE *fp = (FILE *)user_data;
2953
    fprintf(fp, "%p [%zd] ", (void *)op, Py_REFCNT(op));
2954
    if (PyObject_Print(op, fp, 0) != 0) {
2955
        PyErr_Clear();
2956
    }
2957
    putc('\n', fp);
2958
    return 0;
2959
}
2960
2961
2962
/* Print all live objects.  Because PyObject_Print is called, the
2963
 * interpreter must be in a healthy state.
2964
 */
2965
void
2966
_Py_PrintReferences(PyInterpreterState *interp, FILE *fp)
2967
{
2968
    if (interp == NULL) {
2969
        interp = _PyInterpreterState_Main();
2970
    }
2971
    fprintf(fp, "Remaining objects:\n");
2972
    _Py_hashtable_foreach(REFCHAIN(interp), _Py_PrintReference, fp);
2973
}
2974
2975
2976
static int
2977
_Py_PrintReferenceAddress(_Py_hashtable_t *ht,
2978
                          const void *key, const void *value,
2979
                          void *user_data)
2980
{
2981
    PyObject *op = (PyObject*)key;
2982
    FILE *fp = (FILE *)user_data;
2983
    fprintf(fp, "%p [%zd] %s\n",
2984
            (void *)op, Py_REFCNT(op), Py_TYPE(op)->tp_name);
2985
    return 0;
2986
}
2987
2988
2989
/* Print the addresses of all live objects.  Unlike _Py_PrintReferences, this
2990
 * doesn't make any calls to the Python C API, so is always safe to call.
2991
 */
2992
// XXX This function is not safe to use if the interpreter has been
2993
// freed or is in an unhealthy state (e.g. late in finalization).
2994
// The call in Py_FinalizeEx() is okay since the main interpreter
2995
// is statically allocated.
2996
void
2997
_Py_PrintReferenceAddresses(PyInterpreterState *interp, FILE *fp)
2998
{
2999
    fprintf(fp, "Remaining object addresses:\n");
3000
    _Py_hashtable_foreach(REFCHAIN(interp), _Py_PrintReferenceAddress, fp);
3001
}
3002
3003
3004
typedef struct {
3005
    PyObject *self;
3006
    PyObject *args;
3007
    PyObject *list;
3008
    PyObject *type;
3009
    Py_ssize_t limit;
3010
} _Py_GetObjectsData;
3011
3012
enum {
3013
    _PY_GETOBJECTS_IGNORE = 0,
3014
    _PY_GETOBJECTS_ERROR = 1,
3015
    _PY_GETOBJECTS_STOP = 2,
3016
};
3017
3018
static int
3019
_Py_GetObject(_Py_hashtable_t *ht,
3020
              const void *key, const void *value,
3021
              void *user_data)
3022
{
3023
    PyObject *op = (PyObject *)key;
3024
    _Py_GetObjectsData *data = user_data;
3025
    if (data->limit > 0) {
3026
        if (PyList_GET_SIZE(data->list) >= data->limit) {
3027
            return _PY_GETOBJECTS_STOP;
3028
        }
3029
    }
3030
3031
    if (op == data->self) {
3032
        return _PY_GETOBJECTS_IGNORE;
3033
    }
3034
    if (op == data->args) {
3035
        return _PY_GETOBJECTS_IGNORE;
3036
    }
3037
    if (op == data->list) {
3038
        return _PY_GETOBJECTS_IGNORE;
3039
    }
3040
    if (data->type != NULL) {
3041
        if (op == data->type) {
3042
            return _PY_GETOBJECTS_IGNORE;
3043
        }
3044
        if (!Py_IS_TYPE(op, (PyTypeObject *)data->type)) {
3045
            return _PY_GETOBJECTS_IGNORE;
3046
        }
3047
    }
3048
3049
    if (PyList_Append(data->list, op) < 0) {
3050
        return _PY_GETOBJECTS_ERROR;
3051
    }
3052
    return 0;
3053
}
3054
3055
3056
/* The implementation of sys.getobjects(). */
3057
PyObject *
3058
_Py_GetObjects(PyObject *self, PyObject *args)
3059
{
3060
    Py_ssize_t limit;
3061
    PyObject *type = NULL;
3062
    if (!PyArg_ParseTuple(args, "n|O", &limit, &type)) {
3063
        return NULL;
3064
    }
3065
3066
    PyObject *list = PyList_New(0);
3067
    if (list == NULL) {
3068
        return NULL;
3069
    }
3070
3071
    _Py_GetObjectsData data = {
3072
        .self = self,
3073
        .args = args,
3074
        .list = list,
3075
        .type = type,
3076
        .limit = limit,
3077
    };
3078
    PyInterpreterState *interp = _PyInterpreterState_GET();
3079
    int res = _Py_hashtable_foreach(REFCHAIN(interp), _Py_GetObject, &data);
3080
    if (res == _PY_GETOBJECTS_ERROR) {
3081
        Py_DECREF(list);
3082
        return NULL;
3083
    }
3084
    return list;
3085
}
3086
3087
#undef REFCHAIN
3088
#undef REFCHAIN_VALUE
3089
3090
#endif  /* Py_TRACE_REFS */
3091
3092
3093
/* Hack to force loading of abstract.o */
3094
Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
3095
3096
3097
void
3098
_PyObject_DebugTypeStats(FILE *out)
3099
0
{
3100
0
    _PyDict_DebugMallocStats(out);
3101
0
    _PyFloat_DebugMallocStats(out);
3102
0
    _PyList_DebugMallocStats(out);
3103
0
    _PyTuple_DebugMallocStats(out);
3104
0
}
3105
3106
/* These methods are used to control infinite recursion in repr, str, print,
3107
   etc.  Container objects that may recursively contain themselves,
3108
   e.g. builtin dictionaries and lists, should use Py_ReprEnter() and
3109
   Py_ReprLeave() to avoid infinite recursion.
3110
3111
   Py_ReprEnter() returns 0 the first time it is called for a particular
3112
   object and 1 every time thereafter.  It returns -1 if an exception
3113
   occurred.  Py_ReprLeave() has no return value.
3114
3115
   See dictobject.c and listobject.c for examples of use.
3116
*/
3117
3118
int
3119
Py_ReprEnter(PyObject *obj)
3120
4.04M
{
3121
4.04M
    PyObject *dict;
3122
4.04M
    PyObject *list;
3123
4.04M
    Py_ssize_t i;
3124
3125
4.04M
    dict = PyThreadState_GetDict();
3126
    /* Ignore a missing thread-state, so that this function can be called
3127
       early on startup. */
3128
4.04M
    if (dict == NULL)
3129
0
        return 0;
3130
4.04M
    list = PyDict_GetItemWithError(dict, &_Py_ID(Py_Repr));
3131
4.04M
    if (list == NULL) {
3132
4
        if (PyErr_Occurred()) {
3133
0
            return -1;
3134
0
        }
3135
4
        list = PyList_New(0);
3136
4
        if (list == NULL)
3137
0
            return -1;
3138
4
        if (_PyDict_SetItem_Take2((PyDictObject *)dict, &_Py_ID(Py_Repr), list) < 0) {
3139
0
            return -1;
3140
0
        }
3141
4
    }
3142
4.04M
    i = PyList_GET_SIZE(list);
3143
78.1M
    while (--i >= 0) {
3144
74.1M
        if (PyList_GET_ITEM(list, i) == obj)
3145
0
            return 1;
3146
74.1M
    }
3147
4.04M
    if (PyList_Append(list, obj) < 0)
3148
0
        return -1;
3149
4.04M
    return 0;
3150
4.04M
}
3151
3152
void
3153
Py_ReprLeave(PyObject *obj)
3154
4.04M
{
3155
4.04M
    PyObject *dict;
3156
4.04M
    PyObject *list;
3157
4.04M
    Py_ssize_t i;
3158
3159
4.04M
    PyObject *exc = PyErr_GetRaisedException();
3160
3161
4.04M
    dict = PyThreadState_GetDict();
3162
4.04M
    if (dict == NULL)
3163
0
        goto finally;
3164
3165
4.04M
    list = PyDict_GetItemWithError(dict, &_Py_ID(Py_Repr));
3166
4.04M
    if (list == NULL || !PyList_Check(list))
3167
0
        goto finally;
3168
3169
4.04M
    i = PyList_GET_SIZE(list);
3170
    /* Count backwards because we always expect obj to be list[-1] */
3171
4.04M
    while (--i >= 0) {
3172
4.04M
        if (PyList_GET_ITEM(list, i) == obj) {
3173
4.04M
            PyList_SetSlice(list, i, i + 1, NULL);
3174
4.04M
            break;
3175
4.04M
        }
3176
4.04M
    }
3177
3178
4.04M
finally:
3179
    /* ignore exceptions because there is no way to report them. */
3180
4.04M
    PyErr_SetRaisedException(exc);
3181
4.04M
}
3182
3183
/* Trashcan support. */
3184
3185
/* Add op to the tstate->delete_later list.  Called when the current
3186
 * call-stack depth gets large.  op must be a gc'ed object, with refcount 0.
3187
 *  Py_DECREF must already have been called on it.
3188
 */
3189
void
3190
_PyTrash_thread_deposit_object(PyThreadState *tstate, PyObject *op)
3191
16.5k
{
3192
16.5k
    _PyObject_ASSERT(op, Py_REFCNT(op) == 0);
3193
16.5k
    PyTypeObject *tp = Py_TYPE(op);
3194
16.5k
    assert(tp->tp_flags & Py_TPFLAGS_HAVE_GC);
3195
16.5k
    int tracked = 0;
3196
16.5k
    if (tp->tp_is_gc == NULL || tp->tp_is_gc(op)) {
3197
16.5k
        tracked = _PyObject_GC_IS_TRACKED(op);
3198
16.5k
        if (tracked) {
3199
16.5k
            _PyObject_GC_UNTRACK(op);
3200
16.5k
        }
3201
16.5k
    }
3202
16.5k
    uintptr_t tagged_ptr = ((uintptr_t)tstate->delete_later) | tracked;
3203
#ifdef Py_GIL_DISABLED
3204
    op->ob_tid = tagged_ptr;
3205
#else
3206
16.5k
    _Py_AS_GC(op)->_gc_next = tagged_ptr;
3207
16.5k
#endif
3208
16.5k
    tstate->delete_later = op;
3209
16.5k
}
3210
3211
/* Deallocate all the objects in the tstate->delete_later list.
3212
 * Called when the call-stack unwinds again. */
3213
void
3214
_PyTrash_thread_destroy_chain(PyThreadState *tstate)
3215
78
{
3216
16.6k
    while (tstate->delete_later) {
3217
16.5k
        PyObject *op = tstate->delete_later;
3218
16.5k
        destructor dealloc = Py_TYPE(op)->tp_dealloc;
3219
3220
#ifdef Py_GIL_DISABLED
3221
        uintptr_t tagged_ptr = op->ob_tid;
3222
        op->ob_tid = 0;
3223
        _Py_atomic_store_ssize_relaxed(&op->ob_ref_shared, _Py_REF_MERGED);
3224
#else
3225
16.5k
        uintptr_t tagged_ptr = _Py_AS_GC(op)->_gc_next;
3226
16.5k
        _Py_AS_GC(op)->_gc_next = 0;
3227
16.5k
#endif
3228
16.5k
        tstate->delete_later = (PyObject *)(tagged_ptr & ~1);
3229
16.5k
        if (tagged_ptr & 1) {
3230
16.5k
            _PyObject_GC_TRACK(op);
3231
16.5k
        }
3232
        /* Call the deallocator directly.  This used to try to
3233
         * fool Py_DECREF into calling it indirectly, but
3234
         * Py_DECREF was already called on this object, and in
3235
         * assorted non-release builds calling Py_DECREF again ends
3236
         * up distorting allocation statistics.
3237
         */
3238
16.5k
        _PyObject_ASSERT(op, Py_REFCNT(op) == 0);
3239
#ifdef Py_TRACE_REFS
3240
        _Py_ForgetReference(op);
3241
#endif
3242
16.5k
        _PyReftracerTrack(op, PyRefTracer_DESTROY);
3243
16.5k
        (*dealloc)(op);
3244
16.5k
    }
3245
78
}
3246
3247
void _Py_NO_RETURN
3248
_PyObject_AssertFailed(PyObject *obj, const char *expr, const char *msg,
3249
                       const char *file, int line, const char *function)
3250
0
{
3251
0
    fprintf(stderr, "%s:%d: ", file, line);
3252
0
    if (function) {
3253
0
        fprintf(stderr, "%s: ", function);
3254
0
    }
3255
0
    fflush(stderr);
3256
3257
0
    if (expr) {
3258
0
        fprintf(stderr, "Assertion \"%s\" failed", expr);
3259
0
    }
3260
0
    else {
3261
0
        fprintf(stderr, "Assertion failed");
3262
0
    }
3263
0
    fflush(stderr);
3264
3265
0
    if (msg) {
3266
0
        fprintf(stderr, ": %s", msg);
3267
0
    }
3268
0
    fprintf(stderr, "\n");
3269
0
    fflush(stderr);
3270
3271
0
    if (_PyObject_IsFreed(obj)) {
3272
        /* It seems like the object memory has been freed:
3273
           don't access it to prevent a segmentation fault. */
3274
0
        fprintf(stderr, "<object at %p is freed>\n", obj);
3275
0
        fflush(stderr);
3276
0
    }
3277
0
    else {
3278
        /* Display the traceback where the object has been allocated.
3279
           Do it before dumping repr(obj), since repr() is more likely
3280
           to crash than dumping the traceback. */
3281
0
        PyTypeObject *type = Py_TYPE(obj);
3282
0
        const size_t presize = _PyType_PreHeaderSize(type);
3283
0
        void *ptr = (void *)((char *)obj - presize);
3284
0
        _PyMem_DumpTraceback(fileno(stderr), ptr);
3285
3286
        /* This might succeed or fail, but we're about to abort, so at least
3287
           try to provide any extra info we can: */
3288
0
        PyObject_Dump(obj);
3289
3290
0
        fprintf(stderr, "\n");
3291
0
        fflush(stderr);
3292
0
    }
3293
3294
0
    Py_FatalError("_PyObject_AssertFailed");
3295
0
}
3296
3297
3298
/*
3299
When deallocating a container object, it's possible to trigger an unbounded
3300
chain of deallocations, as each Py_DECREF in turn drops the refcount on "the
3301
next" object in the chain to 0.  This can easily lead to stack overflows.
3302
To avoid that, if the C stack is nearing its limit, instead of calling
3303
dealloc on the object, it is added to a queue to be freed later when the
3304
stack is shallower */
3305
static Py_NO_INLINE void
3306
py_dealloc(PyObject *op)
3307
1.53G
{
3308
1.53G
    PyTypeObject *type = Py_TYPE(op);
3309
1.53G
    unsigned long gc_flag = type->tp_flags & Py_TPFLAGS_HAVE_GC;
3310
1.53G
    destructor dealloc = type->tp_dealloc;
3311
1.53G
    PyThreadState *tstate = NULL;
3312
1.53G
    intptr_t margin = 0;
3313
1.53G
    if (gc_flag) {
3314
1.53G
        tstate = _PyThreadState_GET();
3315
1.53G
        margin = _Py_RecursionLimit_GetMargin(tstate);
3316
1.53G
        if (margin < 2) {
3317
16.5k
            _PyTrash_thread_deposit_object(tstate, (PyObject *)op);
3318
16.5k
            return;
3319
16.5k
        }
3320
1.53G
    }
3321
#ifdef Py_DEBUG
3322
    if (tstate == NULL) {
3323
        tstate = _PyThreadState_GET();
3324
    }
3325
#if !defined(Py_GIL_DISABLED) && !defined(Py_STACKREF_DEBUG)
3326
    /* This assertion doesn't hold for the free-threading build, as
3327
     * PyStackRef_CLOSE_SPECIALIZED is not implemented */
3328
    assert(tstate->current_frame == NULL || tstate->current_frame->stackpointer != NULL);
3329
#endif
3330
    PyObject *old_exc = tstate != NULL ? tstate->current_exception : NULL;
3331
    // Keep the old exception type alive to prevent undefined behavior
3332
    // on (tstate->curexc_type != old_exc_type) below
3333
    Py_XINCREF(old_exc);
3334
    // Make sure that type->tp_name remains valid
3335
    Py_INCREF(type);
3336
#endif
3337
3338
#ifdef Py_TRACE_REFS
3339
    _Py_ForgetReference(op);
3340
#endif
3341
1.53G
    _PyReftracerTrack(op, PyRefTracer_DESTROY);
3342
1.53G
    (*dealloc)(op);
3343
3344
#ifdef Py_DEBUG
3345
    // gh-89373: The tp_dealloc function must leave the current exception
3346
    // unchanged.
3347
    if (tstate != NULL && tstate->current_exception != old_exc) {
3348
        const char *err;
3349
        if (old_exc == NULL) {
3350
            err = "Deallocator of type '%s' raised an exception";
3351
        }
3352
        else if (tstate->current_exception == NULL) {
3353
            err = "Deallocator of type '%s' cleared the current exception";
3354
        }
3355
        else {
3356
            // It can happen if dealloc() normalized the current exception.
3357
            // A deallocator function must not change the current exception,
3358
            // not even normalize it.
3359
            err = "Deallocator of type '%s' overrode the current exception";
3360
        }
3361
        _Py_FatalErrorFormat(__func__, err, type->tp_name);
3362
    }
3363
    Py_XDECREF(old_exc);
3364
    Py_DECREF(type);
3365
#endif
3366
1.53G
    if (gc_flag && tstate->delete_later && margin >= 4) {
3367
78
        _PyTrash_thread_destroy_chain(tstate);
3368
78
    }
3369
1.53G
}
3370
3371
/*
3372
 * gh-130706: Keep the GC/reftracer path in the non-inlined py_dealloc().
3373
 * Inlining it makes the compiler save callee-saved registers at entry,
3374
 * so the non-GC objects path would have unnecessary register spills.
3375
 */
3376
void
3377
_Py_Dealloc(PyObject *op)
3378
2.96G
{
3379
2.96G
#if !defined(Py_DEBUG) && !defined(Py_TRACE_REFS)
3380
    // gh-130706: Avoid unnecessary register spills for non-GC objects.
3381
2.96G
    PyTypeObject *type = Py_TYPE(op);
3382
2.96G
    if (_PyRuntime.ref_tracer.tracer_func == NULL
3383
2.96G
        && !(type->tp_flags & Py_TPFLAGS_HAVE_GC))
3384
1.42G
    {
3385
1.42G
        type->tp_dealloc(op);
3386
1.42G
        return;
3387
1.42G
    }
3388
1.53G
#endif
3389
    // GC objects (trashcan), reftracer set, or debug builds.
3390
1.53G
    py_dealloc(op);
3391
1.53G
}
3392
3393
3394
PyObject **
3395
PyObject_GET_WEAKREFS_LISTPTR(PyObject *op)
3396
0
{
3397
0
    return _PyObject_GET_WEAKREFS_LISTPTR(op);
3398
0
}
3399
3400
3401
#undef Py_NewRef
3402
#undef Py_XNewRef
3403
3404
// Export Py_NewRef() and Py_XNewRef() as regular functions for the stable ABI.
3405
PyObject*
3406
Py_NewRef(PyObject *obj)
3407
0
{
3408
0
    return _Py_NewRef(obj);
3409
0
}
3410
3411
PyObject*
3412
Py_XNewRef(PyObject *obj)
3413
0
{
3414
0
    return _Py_XNewRef(obj);
3415
0
}
3416
3417
#undef Py_Is
3418
#undef Py_IsNone
3419
#undef Py_IsTrue
3420
#undef Py_IsFalse
3421
3422
// Export Py_Is(), Py_IsNone(), Py_IsTrue(), Py_IsFalse() as regular functions
3423
// for the stable ABI.
3424
int Py_Is(PyObject *x, PyObject *y)
3425
0
{
3426
0
    return (x == y);
3427
0
}
3428
3429
int Py_IsNone(PyObject *x)
3430
0
{
3431
0
    return Py_Is(x, Py_None);
3432
0
}
3433
3434
int Py_IsTrue(PyObject *x)
3435
0
{
3436
0
    return Py_Is(x, Py_True);
3437
0
}
3438
3439
int Py_IsFalse(PyObject *x)
3440
0
{
3441
0
    return Py_Is(x, Py_False);
3442
0
}
3443
3444
3445
// Py_SET_REFCNT() implementation for stable ABI
3446
void
3447
_Py_SetRefcnt(PyObject *ob, Py_ssize_t refcnt)
3448
0
{
3449
0
    Py_SET_REFCNT(ob, refcnt);
3450
0
}
3451
3452
0
int PyRefTracer_SetTracer(PyRefTracer tracer, void *data) {
3453
0
    _Py_AssertHoldsTstate();
3454
3455
0
    _PyEval_StopTheWorldAll(&_PyRuntime);
3456
0
    if (_PyRuntime.ref_tracer.tracer_func != NULL) {
3457
0
        _PyReftracerTrack(NULL, PyRefTracer_TRACKER_REMOVED);
3458
0
        if (PyErr_Occurred()) {
3459
0
            _PyEval_StartTheWorldAll(&_PyRuntime);
3460
0
            return -1;
3461
0
        }
3462
0
    }
3463
0
    _PyRuntime.ref_tracer.tracer_func = tracer;
3464
0
    _PyRuntime.ref_tracer.tracer_data = data;
3465
0
    _PyEval_StartTheWorldAll(&_PyRuntime);
3466
0
    return 0;
3467
0
}
3468
3469
0
PyRefTracer PyRefTracer_GetTracer(void** data) {
3470
0
    _Py_AssertHoldsTstate();
3471
0
    if (data != NULL) {
3472
0
        *data = _PyRuntime.ref_tracer.tracer_data;
3473
0
    }
3474
0
    return _PyRuntime.ref_tracer.tracer_func;
3475
0
}
3476
3477
3478
3479
static PyObject* constants[] = {
3480
    &_Py_NoneStruct,                   // Py_CONSTANT_NONE
3481
    (PyObject*)(&_Py_FalseStruct),     // Py_CONSTANT_FALSE
3482
    (PyObject*)(&_Py_TrueStruct),      // Py_CONSTANT_TRUE
3483
    &_Py_EllipsisObject,               // Py_CONSTANT_ELLIPSIS
3484
    &_Py_NotImplementedStruct,         // Py_CONSTANT_NOT_IMPLEMENTED
3485
    NULL,  // Py_CONSTANT_ZERO
3486
    NULL,  // Py_CONSTANT_ONE
3487
    NULL,  // Py_CONSTANT_EMPTY_STR
3488
    NULL,  // Py_CONSTANT_EMPTY_BYTES
3489
    NULL,  // Py_CONSTANT_EMPTY_TUPLE
3490
};
3491
3492
void
3493
_Py_GetConstant_Init(void)
3494
37
{
3495
37
    constants[Py_CONSTANT_ZERO] = _PyLong_GetZero();
3496
37
    constants[Py_CONSTANT_ONE] = _PyLong_GetOne();
3497
37
    constants[Py_CONSTANT_EMPTY_STR] = PyUnicode_New(0, 0);
3498
37
    constants[Py_CONSTANT_EMPTY_BYTES] = PyBytes_FromStringAndSize("", 0);
3499
37
    constants[Py_CONSTANT_EMPTY_TUPLE] = PyTuple_New(0);
3500
#ifndef NDEBUG
3501
    for (size_t i=0; i < Py_ARRAY_LENGTH(constants); i++) {
3502
        assert(constants[i] != NULL);
3503
        assert(_Py_IsImmortal(constants[i]));
3504
    }
3505
#endif
3506
37
}
3507
3508
PyObject*
3509
Py_GetConstant(unsigned int constant_id)
3510
43.8M
{
3511
43.8M
    if (constant_id < Py_ARRAY_LENGTH(constants)) {
3512
43.8M
        return constants[constant_id];
3513
43.8M
    }
3514
0
    else {
3515
0
        PyErr_BadInternalCall();
3516
0
        return NULL;
3517
0
    }
3518
43.8M
}
3519
3520
3521
PyObject*
3522
Py_GetConstantBorrowed(unsigned int constant_id)
3523
74
{
3524
    // All constants are immortal
3525
74
    return Py_GetConstant(constant_id);
3526
74
}
3527
3528
int
3529
PyUnstable_IsImmortal(PyObject *op)
3530
0
{
3531
    /* Checking a reference count requires a thread state */
3532
0
    _Py_AssertHoldsTstate();
3533
0
    assert(op != NULL);
3534
0
    return _Py_IsImmortal(op);
3535
0
}
3536
3537
int
3538
PyUnstable_Object_IsUniquelyReferenced(PyObject *op)
3539
0
{
3540
0
    _Py_AssertHoldsTstate();
3541
0
    assert(op != NULL);
3542
0
    return _PyObject_IsUniquelyReferenced(op);
3543
0
}
3544
3545
int
3546
_PyObject_VisitType(PyObject *op, visitproc visit, void *arg)
3547
280k
{
3548
280k
    assert(op != NULL);
3549
280k
    PyTypeObject *tp = Py_TYPE(op);
3550
280k
    _PyObject_ASSERT((PyObject *)tp, PyType_HasFeature(tp, Py_TPFLAGS_HEAPTYPE));
3551
280k
    Py_VISIT(tp);
3552
280k
    return 0;
3553
280k
}
3554
3555
// Implementations for the stable ABI
3556
// Keep these at the end.
3557
#undef Py_TYPE
3558
#undef Py_REFCNT
3559
#undef Py_SIZE
3560
#undef Py_IS_TYPE
3561
#undef Py_SET_SIZE
3562
284
PyTypeObject* Py_TYPE(PyObject *ob) { return _Py_TYPE_impl(ob); }
3563
0
Py_ssize_t Py_REFCNT(PyObject *ob) { return _Py_REFCNT(ob); }
3564
0
Py_ssize_t Py_SIZE(PyObject *o) { return _Py_SIZE_impl(o); }
3565
176
int Py_IS_TYPE(PyObject *o, PyTypeObject *t) { return _Py_IS_TYPE_impl(o, t); }
3566
0
void Py_SET_SIZE(PyVarObject *o, Py_ssize_t s) { _Py_SET_SIZE_impl(o, s); }