Coverage Report

Created: 2026-02-09 07:07

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