Coverage Report

Created: 2025-08-26 06:26

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