Coverage Report

Created: 2026-01-10 06:41

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Objects/object.c
Line
Count
Source
1
2
/* Generic object operations; and implementation of None */
3
4
#include "Python.h"
5
#include "pycore_brc.h"           // _Py_brc_queue_object()
6
#include "pycore_call.h"          // _PyObject_CallNoArgs()
7
#include "pycore_ceval.h"         // _Py_EnterRecursiveCallTstate()
8
#include "pycore_context.h"       // _PyContextTokenMissing_Type
9
#include "pycore_critical_section.h" // Py_BEGIN_CRITICAL_SECTION
10
#include "pycore_descrobject.h"   // _PyMethodWrapper_Type
11
#include "pycore_dict.h"          // _PyObject_MaterializeManagedDict()
12
#include "pycore_floatobject.h"   // _PyFloat_DebugMallocStats()
13
#include "pycore_freelist.h"      // _PyObject_ClearFreeLists()
14
#include "pycore_genobject.h"     // _PyAsyncGenAThrow_Type
15
#include "pycore_hamt.h"          // _PyHamtItems_Type
16
#include "pycore_initconfig.h"    // _PyStatus_OK()
17
#include "pycore_instruction_sequence.h" // _PyInstructionSequence_Type
18
#include "pycore_interpframe.h"   // _PyFrame_Stackbase()
19
#include "pycore_interpolation.h" // _PyInterpolation_Type
20
#include "pycore_list.h"          // _PyList_DebugMallocStats()
21
#include "pycore_long.h"          // _PyLong_GetZero()
22
#include "pycore_memoryobject.h"  // _PyManagedBuffer_Type
23
#include "pycore_namespace.h"     // _PyNamespace_Type
24
#include "pycore_object.h"        // export _Py_SwappedOp
25
#include "pycore_optimizer.h"     // _PyUOpExecutor_Type
26
#include "pycore_pyerrors.h"      // _PyErr_Occurred()
27
#include "pycore_pymem.h"         // _PyMem_IsPtrFreed()
28
#include "pycore_pystate.h"       // _PyThreadState_GET()
29
#include "pycore_symtable.h"      // PySTEntry_Type
30
#include "pycore_template.h"      // _PyTemplate_Type _PyTemplateIter_Type
31
#include "pycore_tuple.h"         // _PyTuple_DebugMallocStats()
32
#include "pycore_typeobject.h"    // _PyBufferWrapper_Type
33
#include "pycore_typevarobject.h" // _PyTypeAlias_Type
34
#include "pycore_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
7.70k
{
354
7.70k
    Py_DECREF(o);
355
7.70k
}
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
2.55M
{
553
2.55M
    PyObject *op = (PyObject *) PyObject_Malloc(_PyObject_SIZE(tp));
554
2.55M
    if (op == NULL) {
555
0
        return PyErr_NoMemory();
556
0
    }
557
2.55M
    _PyObject_Init(op, tp);
558
2.55M
    return op;
559
2.55M
}
560
561
PyVarObject *
562
_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
563
140k
{
564
140k
    PyVarObject *op;
565
140k
    const size_t size = _PyObject_VAR_SIZE(tp, nitems);
566
140k
    op = (PyVarObject *) PyObject_Malloc(size);
567
140k
    if (op == NULL) {
568
0
        return (PyVarObject *)PyErr_NoMemory();
569
0
    }
570
140k
    _PyObject_InitVar(op, tp, nitems);
571
140k
    return op;
572
140k
}
573
574
void
575
PyObject_CallFinalizer(PyObject *self)
576
23.2M
{
577
23.2M
    PyTypeObject *tp = Py_TYPE(self);
578
579
23.2M
    if (tp->tp_finalize == NULL)
580
0
        return;
581
    /* tp_finalize should only be called once. */
582
23.2M
    if (_PyType_IS_GC(tp) && _PyGC_FINALIZED(self))
583
54.7k
        return;
584
585
23.2M
    tp->tp_finalize(self);
586
23.2M
    if (_PyType_IS_GC(tp)) {
587
23.0M
        _PyGC_SET_FINALIZED(self);
588
23.0M
    }
589
23.2M
}
590
591
int
592
PyObject_CallFinalizerFromDealloc(PyObject *self)
593
23.2M
{
594
23.2M
    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
23.2M
    _PyObject_ResurrectStart(self);
602
603
23.2M
    PyObject_CallFinalizer(self);
604
605
23.2M
    _PyObject_ASSERT_WITH_MSG(self,
606
23.2M
                              Py_REFCNT(self) > 0,
607
23.2M
                              "refcount is too small");
608
609
23.2M
    _PyObject_ASSERT(self,
610
23.2M
                    (!_PyType_IS_GC(Py_TYPE(self))
611
23.2M
                    || _PyObject_GC_IS_TRACKED(self)));
612
613
    /* Undo the temporary resurrection; can't use DECREF here, it would
614
     * cause a recursive call. */
615
23.2M
    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
23.2M
    return 0;
627
23.2M
}
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
PyUnstable_Object_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
20.7M
{
756
20.7M
    PyObject *res;
757
20.7M
    if (PyErr_CheckSignals())
758
0
        return NULL;
759
20.7M
    if (v == NULL)
760
0
        return PyUnicode_FromString("<NULL>");
761
20.7M
    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
20.7M
    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
20.7M
    if (_Py_EnterRecursiveCallTstate(tstate,
776
20.7M
                                     " while getting the repr of an object")) {
777
0
        return NULL;
778
0
    }
779
20.7M
    res = (*Py_TYPE(v)->tp_repr)(v);
780
20.7M
    _Py_LeaveRecursiveCallTstate(tstate);
781
782
20.7M
    if (res == NULL) {
783
2
        return NULL;
784
2
    }
785
20.7M
    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
20.7M
    return res;
792
20.7M
}
793
794
PyObject *
795
PyObject_Str(PyObject *v)
796
71.6M
{
797
71.6M
    PyObject *res;
798
71.6M
    if (PyErr_CheckSignals())
799
0
        return NULL;
800
71.6M
    if (v == NULL)
801
0
        return PyUnicode_FromString("<NULL>");
802
71.6M
    if (PyUnicode_CheckExact(v)) {
803
60.4M
        return Py_NewRef(v);
804
60.4M
    }
805
11.1M
    if (Py_TYPE(v)->tp_str == NULL)
806
0
        return PyObject_Repr(v);
807
808
11.1M
    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
11.1M
    if (_Py_EnterRecursiveCallTstate(tstate, " while getting the str of an object")) {
819
0
        return NULL;
820
0
    }
821
11.1M
    res = (*Py_TYPE(v)->tp_str)(v);
822
11.1M
    _Py_LeaveRecursiveCallTstate(tstate);
823
824
11.1M
    if (res == NULL) {
825
6.72k
        return NULL;
826
6.72k
    }
827
11.1M
    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
11.1M
    assert(_PyUnicode_CheckConsistency(res, 1));
834
11.1M
    return res;
835
11.1M
}
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
22.7k
{
867
22.7k
    PyObject *result, *func;
868
869
22.7k
    if (v == NULL)
870
0
        return PyBytes_FromString("<NULL>");
871
872
22.7k
    if (PyBytes_CheckExact(v)) {
873
22.6k
        return Py_NewRef(v);
874
22.6k
    }
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->bytes_writers, is_finalization, PyMem_Free);
949
0
    clear_freelist(&freelists->ints, is_finalization, free_object);
950
0
    clear_freelist(&freelists->pycfunctionobject, is_finalization, PyObject_GC_Del);
951
0
    clear_freelist(&freelists->pycmethodobject, is_finalization, PyObject_GC_Del);
952
0
    clear_freelist(&freelists->pymethodobjects, is_finalization, free_object);
953
0
}
954
955
/*
956
def _PyObject_FunctionStr(x):
957
    try:
958
        qualname = x.__qualname__
959
    except AttributeError:
960
        return str(x)
961
    try:
962
        mod = x.__module__
963
        if mod is not None and mod != 'builtins':
964
            return f"{x.__module__}.{qualname}()"
965
    except AttributeError:
966
        pass
967
    return qualname
968
*/
969
PyObject *
970
_PyObject_FunctionStr(PyObject *x)
971
0
{
972
0
    assert(!PyErr_Occurred());
973
0
    PyObject *qualname;
974
0
    int ret = PyObject_GetOptionalAttr(x, &_Py_ID(__qualname__), &qualname);
975
0
    if (qualname == NULL) {
976
0
        if (ret < 0) {
977
0
            return NULL;
978
0
        }
979
0
        return PyObject_Str(x);
980
0
    }
981
0
    PyObject *module;
982
0
    PyObject *result = NULL;
983
0
    ret = PyObject_GetOptionalAttr(x, &_Py_ID(__module__), &module);
984
0
    if (module != NULL && module != Py_None) {
985
0
        ret = PyObject_RichCompareBool(module, &_Py_ID(builtins), Py_NE);
986
0
        if (ret < 0) {
987
            // error
988
0
            goto done;
989
0
        }
990
0
        if (ret > 0) {
991
0
            result = PyUnicode_FromFormat("%S.%S()", module, qualname);
992
0
            goto done;
993
0
        }
994
0
    }
995
0
    else if (ret < 0) {
996
0
        goto done;
997
0
    }
998
0
    result = PyUnicode_FromFormat("%S()", qualname);
999
0
done:
1000
0
    Py_DECREF(qualname);
1001
0
    Py_XDECREF(module);
1002
0
    return result;
1003
0
}
1004
1005
/* For Python 3.0.1 and later, the old three-way comparison has been
1006
   completely removed in favour of rich comparisons.  PyObject_Compare() and
1007
   PyObject_Cmp() are gone, and the builtin cmp function no longer exists.
1008
   The old tp_compare slot has been renamed to tp_as_async, and should no
1009
   longer be used.  Use tp_richcompare instead.
1010
1011
   See (*) below for practical amendments.
1012
1013
   tp_richcompare gets called with a first argument of the appropriate type
1014
   and a second object of an arbitrary type.  We never do any kind of
1015
   coercion.
1016
1017
   The tp_richcompare slot should return an object, as follows:
1018
1019
    NULL if an exception occurred
1020
    NotImplemented if the requested comparison is not implemented
1021
    any other false value if the requested comparison is false
1022
    any other true value if the requested comparison is true
1023
1024
  The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get
1025
  NotImplemented.
1026
1027
  (*) Practical amendments:
1028
1029
  - If rich comparison returns NotImplemented, == and != are decided by
1030
    comparing the object pointer (i.e. falling back to the base object
1031
    implementation).
1032
1033
*/
1034
1035
/* Map rich comparison operators to their swapped version, e.g. LT <--> GT */
1036
int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
1037
1038
static const char * const opstrings[] = {"<", "<=", "==", "!=", ">", ">="};
1039
1040
/* Perform a rich comparison, raising TypeError when the requested comparison
1041
   operator is not supported. */
1042
static PyObject *
1043
do_richcompare(PyThreadState *tstate, PyObject *v, PyObject *w, int op)
1044
276M
{
1045
276M
    richcmpfunc f;
1046
276M
    PyObject *res;
1047
276M
    int checked_reverse_op = 0;
1048
1049
276M
    if (!Py_IS_TYPE(v, Py_TYPE(w)) &&
1050
4.04M
        PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v)) &&
1051
169k
        (f = Py_TYPE(w)->tp_richcompare) != NULL) {
1052
169k
        checked_reverse_op = 1;
1053
169k
        res = (*f)(w, v, _Py_SwappedOp[op]);
1054
169k
        if (res != Py_NotImplemented)
1055
136k
            return res;
1056
32.7k
        Py_DECREF(res);
1057
32.7k
    }
1058
275M
    if ((f = Py_TYPE(v)->tp_richcompare) != NULL) {
1059
275M
        res = (*f)(v, w, op);
1060
275M
        if (res != Py_NotImplemented)
1061
271M
            return res;
1062
3.91M
        Py_DECREF(res);
1063
3.91M
    }
1064
3.91M
    if (!checked_reverse_op && (f = Py_TYPE(w)->tp_richcompare) != NULL) {
1065
3.88M
        res = (*f)(w, v, _Py_SwappedOp[op]);
1066
3.88M
        if (res != Py_NotImplemented)
1067
0
            return res;
1068
3.88M
        Py_DECREF(res);
1069
3.88M
    }
1070
    /* If neither object implements it, provide a sensible default
1071
       for == and !=, but raise an exception for ordering. */
1072
3.91M
    switch (op) {
1073
3.91M
    case Py_EQ:
1074
3.91M
        res = (v == w) ? Py_True : Py_False;
1075
3.91M
        break;
1076
861
    case Py_NE:
1077
861
        res = (v != w) ? Py_True : Py_False;
1078
861
        break;
1079
0
    default:
1080
0
        _PyErr_Format(tstate, PyExc_TypeError,
1081
0
                      "'%s' not supported between instances of '%.100s' and '%.100s'",
1082
0
                      opstrings[op],
1083
0
                      Py_TYPE(v)->tp_name,
1084
0
                      Py_TYPE(w)->tp_name);
1085
0
        return NULL;
1086
3.91M
    }
1087
3.91M
    return Py_NewRef(res);
1088
3.91M
}
1089
1090
/* Perform a rich comparison with object result.  This wraps do_richcompare()
1091
   with a check for NULL arguments and a recursion check. */
1092
1093
PyObject *
1094
PyObject_RichCompare(PyObject *v, PyObject *w, int op)
1095
276M
{
1096
276M
    PyThreadState *tstate = _PyThreadState_GET();
1097
1098
276M
    assert(Py_LT <= op && op <= Py_GE);
1099
276M
    if (v == NULL || w == NULL) {
1100
0
        if (!_PyErr_Occurred(tstate)) {
1101
0
            PyErr_BadInternalCall();
1102
0
        }
1103
0
        return NULL;
1104
0
    }
1105
276M
    if (_Py_EnterRecursiveCallTstate(tstate, " in comparison")) {
1106
0
        return NULL;
1107
0
    }
1108
276M
    PyObject *res = do_richcompare(tstate, v, w, op);
1109
276M
    _Py_LeaveRecursiveCallTstate(tstate);
1110
276M
    return res;
1111
276M
}
1112
1113
/* Perform a rich comparison with integer result.  This wraps
1114
   PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */
1115
int
1116
PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
1117
269M
{
1118
269M
    PyObject *res;
1119
269M
    int ok;
1120
1121
    /* Quick result when objects are the same.
1122
       Guarantees that identity implies equality. */
1123
269M
    if (v == w) {
1124
33.2M
        if (op == Py_EQ)
1125
29.1M
            return 1;
1126
4.14M
        else if (op == Py_NE)
1127
0
            return 0;
1128
33.2M
    }
1129
1130
240M
    res = PyObject_RichCompare(v, w, op);
1131
240M
    if (res == NULL)
1132
0
        return -1;
1133
240M
    if (PyBool_Check(res)) {
1134
240M
        ok = (res == Py_True);
1135
240M
        assert(_Py_IsImmortal(res));
1136
240M
    }
1137
0
    else {
1138
0
        ok = PyObject_IsTrue(res);
1139
0
        Py_DECREF(res);
1140
0
    }
1141
240M
    return ok;
1142
240M
}
1143
1144
Py_hash_t
1145
PyObject_HashNotImplemented(PyObject *v)
1146
0
{
1147
0
    PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
1148
0
                 Py_TYPE(v)->tp_name);
1149
0
    return -1;
1150
0
}
1151
1152
Py_hash_t
1153
PyObject_Hash(PyObject *v)
1154
1.96G
{
1155
1.96G
    PyTypeObject *tp = Py_TYPE(v);
1156
1.96G
    if (tp->tp_hash != NULL)
1157
1.96G
        return (*tp->tp_hash)(v);
1158
    /* To keep to the general practice that inheriting
1159
     * solely from object in C code should work without
1160
     * an explicit call to PyType_Ready, we implicitly call
1161
     * PyType_Ready here and then check the tp_hash slot again
1162
     */
1163
0
    if (!_PyType_IsReady(tp)) {
1164
0
        if (PyType_Ready(tp) < 0)
1165
0
            return -1;
1166
0
        if (tp->tp_hash != NULL)
1167
0
            return (*tp->tp_hash)(v);
1168
0
    }
1169
    /* Otherwise, the object can't be hashed */
1170
0
    return PyObject_HashNotImplemented(v);
1171
0
}
1172
1173
PyObject *
1174
PyObject_GetAttrString(PyObject *v, const char *name)
1175
393k
{
1176
393k
    PyObject *w, *res;
1177
1178
393k
    if (Py_TYPE(v)->tp_getattr != NULL)
1179
0
        return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
1180
393k
    w = PyUnicode_FromString(name);
1181
393k
    if (w == NULL)
1182
0
        return NULL;
1183
393k
    res = PyObject_GetAttr(v, w);
1184
393k
    Py_DECREF(w);
1185
393k
    return res;
1186
393k
}
1187
1188
int
1189
PyObject_HasAttrStringWithError(PyObject *obj, const char *name)
1190
0
{
1191
0
    PyObject *res;
1192
0
    int rc = PyObject_GetOptionalAttrString(obj, name, &res);
1193
0
    Py_XDECREF(res);
1194
0
    return rc;
1195
0
}
1196
1197
1198
int
1199
PyObject_HasAttrString(PyObject *obj, const char *name)
1200
0
{
1201
0
    int rc = PyObject_HasAttrStringWithError(obj, name);
1202
0
    if (rc < 0) {
1203
0
        PyErr_FormatUnraisable(
1204
0
            "Exception ignored in PyObject_HasAttrString(); consider using "
1205
0
            "PyObject_HasAttrStringWithError(), "
1206
0
            "PyObject_GetOptionalAttrString() or PyObject_GetAttrString()");
1207
0
        return 0;
1208
0
    }
1209
0
    return rc;
1210
0
}
1211
1212
int
1213
PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
1214
35.2k
{
1215
35.2k
    PyThreadState *tstate = _PyThreadState_GET();
1216
35.2k
    if (w == NULL && _PyErr_Occurred(tstate)) {
1217
0
        PyObject *exc = _PyErr_GetRaisedException(tstate);
1218
0
        _PyErr_SetString(tstate, PyExc_SystemError,
1219
0
            "PyObject_SetAttrString() must not be called with NULL value "
1220
0
            "and an exception set");
1221
0
        _PyErr_ChainExceptions1Tstate(tstate, exc);
1222
0
        return -1;
1223
0
    }
1224
1225
35.2k
    if (Py_TYPE(v)->tp_setattr != NULL) {
1226
0
        return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
1227
0
    }
1228
1229
35.2k
    PyObject *s = PyUnicode_InternFromString(name);
1230
35.2k
    if (s == NULL) {
1231
0
        return -1;
1232
0
    }
1233
1234
35.2k
    int res = PyObject_SetAttr(v, s, w);
1235
35.2k
    Py_DECREF(s);
1236
35.2k
    return res;
1237
35.2k
}
1238
1239
int
1240
PyObject_DelAttrString(PyObject *v, const char *name)
1241
0
{
1242
0
    return PyObject_SetAttrString(v, name, NULL);
1243
0
}
1244
1245
int
1246
_PyObject_IsAbstract(PyObject *obj)
1247
19.6k
{
1248
19.6k
    int res;
1249
19.6k
    PyObject* isabstract;
1250
1251
19.6k
    if (obj == NULL)
1252
212
        return 0;
1253
1254
19.4k
    res = PyObject_GetOptionalAttr(obj, &_Py_ID(__isabstractmethod__), &isabstract);
1255
19.4k
    if (res > 0) {
1256
2.53k
        res = PyObject_IsTrue(isabstract);
1257
2.53k
        Py_DECREF(isabstract);
1258
2.53k
    }
1259
19.4k
    return res;
1260
19.6k
}
1261
1262
PyObject *
1263
_PyObject_GetAttrId(PyObject *v, _Py_Identifier *name)
1264
0
{
1265
0
    PyObject *result;
1266
0
_Py_COMP_DIAG_PUSH
1267
0
_Py_COMP_DIAG_IGNORE_DEPR_DECLS
1268
0
    PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
1269
0
_Py_COMP_DIAG_POP
1270
0
    if (!oname)
1271
0
        return NULL;
1272
0
    result = PyObject_GetAttr(v, oname);
1273
0
    return result;
1274
0
}
1275
1276
int
1277
_PyObject_SetAttributeErrorContext(PyObject* v, PyObject* name)
1278
973k
{
1279
973k
    assert(PyErr_Occurred());
1280
973k
    if (!PyErr_ExceptionMatches(PyExc_AttributeError)){
1281
3.31k
        return 0;
1282
3.31k
    }
1283
    // Intercept AttributeError exceptions and augment them to offer suggestions later.
1284
970k
    PyObject *exc = PyErr_GetRaisedException();
1285
970k
    if (!PyErr_GivenExceptionMatches(exc, PyExc_AttributeError)) {
1286
0
        goto restore;
1287
0
    }
1288
970k
    PyAttributeErrorObject* the_exc = (PyAttributeErrorObject*) exc;
1289
    // Check if this exception was already augmented
1290
970k
    if (the_exc->name || the_exc->obj) {
1291
4.61k
        goto restore;
1292
4.61k
    }
1293
    // Augment the exception with the name and object
1294
965k
    if (PyObject_SetAttr(exc, &_Py_ID(name), name) ||
1295
965k
        PyObject_SetAttr(exc, &_Py_ID(obj), v)) {
1296
0
        return 1;
1297
0
    }
1298
970k
restore:
1299
970k
    PyErr_SetRaisedException(exc);
1300
970k
    return 0;
1301
965k
}
1302
1303
PyObject *
1304
PyObject_GetAttr(PyObject *v, PyObject *name)
1305
558M
{
1306
558M
    PyTypeObject *tp = Py_TYPE(v);
1307
558M
    if (!PyUnicode_Check(name)) {
1308
0
        PyErr_Format(PyExc_TypeError,
1309
0
                     "attribute name must be string, not '%.200s'",
1310
0
                     Py_TYPE(name)->tp_name);
1311
0
        return NULL;
1312
0
    }
1313
1314
558M
    PyObject* result = NULL;
1315
558M
    if (tp->tp_getattro != NULL) {
1316
558M
        result = (*tp->tp_getattro)(v, name);
1317
558M
    }
1318
0
    else if (tp->tp_getattr != NULL) {
1319
0
        const char *name_str = PyUnicode_AsUTF8(name);
1320
0
        if (name_str == NULL) {
1321
0
            return NULL;
1322
0
        }
1323
0
        result = (*tp->tp_getattr)(v, (char *)name_str);
1324
0
    }
1325
0
    else {
1326
0
        PyErr_Format(PyExc_AttributeError,
1327
0
                    "'%.100s' object has no attribute '%U'",
1328
0
                    tp->tp_name, name);
1329
0
    }
1330
1331
558M
    if (result == NULL) {
1332
963k
        _PyObject_SetAttributeErrorContext(v, name);
1333
963k
    }
1334
558M
    return result;
1335
558M
}
1336
1337
int
1338
PyObject_GetOptionalAttr(PyObject *v, PyObject *name, PyObject **result)
1339
89.9M
{
1340
89.9M
    PyTypeObject *tp = Py_TYPE(v);
1341
1342
89.9M
    if (!PyUnicode_Check(name)) {
1343
0
        PyErr_Format(PyExc_TypeError,
1344
0
                     "attribute name must be string, not '%.200s'",
1345
0
                     Py_TYPE(name)->tp_name);
1346
0
        *result = NULL;
1347
0
        return -1;
1348
0
    }
1349
1350
89.9M
    if (tp->tp_getattro == PyObject_GenericGetAttr) {
1351
85.4M
        *result = _PyObject_GenericGetAttrWithDict(v, name, NULL, 1);
1352
85.4M
        if (*result != NULL) {
1353
69.3M
            return 1;
1354
69.3M
        }
1355
16.1M
        if (PyErr_Occurred()) {
1356
8
            return -1;
1357
8
        }
1358
16.1M
        return 0;
1359
16.1M
    }
1360
4.50M
    if (tp->tp_getattro == _Py_type_getattro) {
1361
147k
        int suppress_missing_attribute_exception = 0;
1362
147k
        *result = _Py_type_getattro_impl((PyTypeObject*)v, name, &suppress_missing_attribute_exception);
1363
147k
        if (suppress_missing_attribute_exception) {
1364
            // return 0 without having to clear the exception
1365
728
            return 0;
1366
728
        }
1367
147k
    }
1368
4.35M
    else if (tp->tp_getattro == (getattrofunc)_Py_module_getattro) {
1369
        // optimization: suppress attribute error from module getattro method
1370
4.35M
        *result = _Py_module_getattro_impl((PyModuleObject*)v, name, 1);
1371
4.35M
        if (*result != NULL) {
1372
4.33M
            return 1;
1373
4.33M
        }
1374
26.6k
        if (PyErr_Occurred()) {
1375
0
            return -1;
1376
0
        }
1377
26.6k
        return 0;
1378
26.6k
    }
1379
166
    else if (tp->tp_getattro != NULL) {
1380
166
        *result = (*tp->tp_getattro)(v, name);
1381
166
    }
1382
0
    else if (tp->tp_getattr != NULL) {
1383
0
        const char *name_str = PyUnicode_AsUTF8(name);
1384
0
        if (name_str == NULL) {
1385
0
            *result = NULL;
1386
0
            return -1;
1387
0
        }
1388
0
        *result = (*tp->tp_getattr)(v, (char *)name_str);
1389
0
    }
1390
0
    else {
1391
0
        *result = NULL;
1392
0
        return 0;
1393
0
    }
1394
1395
146k
    if (*result != NULL) {
1396
146k
        return 1;
1397
146k
    }
1398
502
    if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
1399
0
        return -1;
1400
0
    }
1401
502
    PyErr_Clear();
1402
502
    return 0;
1403
502
}
1404
1405
int
1406
PyObject_GetOptionalAttrString(PyObject *obj, const char *name, PyObject **result)
1407
0
{
1408
0
    if (Py_TYPE(obj)->tp_getattr == NULL) {
1409
0
        PyObject *oname = PyUnicode_FromString(name);
1410
0
        if (oname == NULL) {
1411
0
            *result = NULL;
1412
0
            return -1;
1413
0
        }
1414
0
        int rc = PyObject_GetOptionalAttr(obj, oname, result);
1415
0
        Py_DECREF(oname);
1416
0
        return rc;
1417
0
    }
1418
1419
0
    *result = (*Py_TYPE(obj)->tp_getattr)(obj, (char*)name);
1420
0
    if (*result != NULL) {
1421
0
        return 1;
1422
0
    }
1423
0
    if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
1424
0
        return -1;
1425
0
    }
1426
0
    PyErr_Clear();
1427
0
    return 0;
1428
0
}
1429
1430
int
1431
PyObject_HasAttrWithError(PyObject *obj, PyObject *name)
1432
11.6M
{
1433
11.6M
    PyObject *res;
1434
11.6M
    int rc = PyObject_GetOptionalAttr(obj, name, &res);
1435
11.6M
    Py_XDECREF(res);
1436
11.6M
    return rc;
1437
11.6M
}
1438
1439
int
1440
PyObject_HasAttr(PyObject *obj, PyObject *name)
1441
0
{
1442
0
    int rc = PyObject_HasAttrWithError(obj, name);
1443
0
    if (rc < 0) {
1444
0
        PyErr_FormatUnraisable(
1445
0
            "Exception ignored in PyObject_HasAttr(); consider using "
1446
0
            "PyObject_HasAttrWithError(), "
1447
0
            "PyObject_GetOptionalAttr() or PyObject_GetAttr()");
1448
0
        return 0;
1449
0
    }
1450
0
    return rc;
1451
0
}
1452
1453
int
1454
PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
1455
80.8M
{
1456
80.8M
    PyThreadState *tstate = _PyThreadState_GET();
1457
80.8M
    if (value == NULL && _PyErr_Occurred(tstate)) {
1458
0
        PyObject *exc = _PyErr_GetRaisedException(tstate);
1459
0
        _PyErr_SetString(tstate, PyExc_SystemError,
1460
0
            "PyObject_SetAttr() must not be called with NULL value "
1461
0
            "and an exception set");
1462
0
        _PyErr_ChainExceptions1Tstate(tstate, exc);
1463
0
        return -1;
1464
0
    }
1465
1466
80.8M
    PyTypeObject *tp = Py_TYPE(v);
1467
80.8M
    int err;
1468
1469
80.8M
    if (!PyUnicode_Check(name)) {
1470
0
        PyErr_Format(PyExc_TypeError,
1471
0
                     "attribute name must be string, not '%.200s'",
1472
0
                     Py_TYPE(name)->tp_name);
1473
0
        return -1;
1474
0
    }
1475
80.8M
    Py_INCREF(name);
1476
1477
80.8M
    _PyUnicode_InternMortal(tstate->interp, &name);
1478
80.8M
    if (tp->tp_setattro != NULL) {
1479
80.8M
        err = (*tp->tp_setattro)(v, name, value);
1480
80.8M
        Py_DECREF(name);
1481
80.8M
        return err;
1482
80.8M
    }
1483
0
    if (tp->tp_setattr != NULL) {
1484
0
        const char *name_str = PyUnicode_AsUTF8(name);
1485
0
        if (name_str == NULL) {
1486
0
            Py_DECREF(name);
1487
0
            return -1;
1488
0
        }
1489
0
        err = (*tp->tp_setattr)(v, (char *)name_str, value);
1490
0
        Py_DECREF(name);
1491
0
        return err;
1492
0
    }
1493
0
    Py_DECREF(name);
1494
0
    _PyObject_ASSERT(name, Py_REFCNT(name) >= 1);
1495
0
    if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1496
0
        PyErr_Format(PyExc_TypeError,
1497
0
                     "'%.100s' object has no attributes "
1498
0
                     "(%s .%U)",
1499
0
                     tp->tp_name,
1500
0
                     value==NULL ? "del" : "assign to",
1501
0
                     name);
1502
0
    else
1503
0
        PyErr_Format(PyExc_TypeError,
1504
0
                     "'%.100s' object has only read-only attributes "
1505
0
                     "(%s .%U)",
1506
0
                     tp->tp_name,
1507
0
                     value==NULL ? "del" : "assign to",
1508
0
                     name);
1509
0
    return -1;
1510
0
}
1511
1512
int
1513
PyObject_DelAttr(PyObject *v, PyObject *name)
1514
226k
{
1515
226k
    return PyObject_SetAttr(v, name, NULL);
1516
226k
}
1517
1518
PyObject **
1519
_PyObject_ComputedDictPointer(PyObject *obj)
1520
425M
{
1521
425M
    PyTypeObject *tp = Py_TYPE(obj);
1522
425M
    assert((tp->tp_flags & Py_TPFLAGS_MANAGED_DICT) == 0);
1523
1524
425M
    Py_ssize_t dictoffset = tp->tp_dictoffset;
1525
425M
    if (dictoffset == 0) {
1526
284M
        return NULL;
1527
284M
    }
1528
1529
141M
    if (dictoffset < 0) {
1530
0
        assert(dictoffset != -1);
1531
1532
0
        Py_ssize_t tsize = Py_SIZE(obj);
1533
0
        if (tsize < 0) {
1534
0
            tsize = -tsize;
1535
0
        }
1536
0
        size_t size = _PyObject_VAR_SIZE(tp, tsize);
1537
0
        assert(size <= (size_t)PY_SSIZE_T_MAX);
1538
0
        dictoffset += (Py_ssize_t)size;
1539
1540
0
        _PyObject_ASSERT(obj, dictoffset > 0);
1541
0
        _PyObject_ASSERT(obj, dictoffset % SIZEOF_VOID_P == 0);
1542
0
    }
1543
141M
    return (PyObject **) ((char *)obj + dictoffset);
1544
425M
}
1545
1546
/* Helper to get a pointer to an object's __dict__ slot, if any.
1547
 * Creates the dict from inline attributes if necessary.
1548
 * Does not set an exception.
1549
 *
1550
 * Note that the tp_dictoffset docs used to recommend this function,
1551
 * so it should be treated as part of the public API.
1552
 */
1553
PyObject **
1554
_PyObject_GetDictPtr(PyObject *obj)
1555
0
{
1556
0
    if ((Py_TYPE(obj)->tp_flags & Py_TPFLAGS_MANAGED_DICT) == 0) {
1557
0
        return _PyObject_ComputedDictPointer(obj);
1558
0
    }
1559
0
    PyDictObject *dict = _PyObject_GetManagedDict(obj);
1560
0
    if (dict == NULL && Py_TYPE(obj)->tp_flags & Py_TPFLAGS_INLINE_VALUES) {
1561
0
        dict = _PyObject_MaterializeManagedDict(obj);
1562
0
        if (dict == NULL) {
1563
0
            PyErr_Clear();
1564
0
            return NULL;
1565
0
        }
1566
0
    }
1567
0
    return (PyObject **)&_PyObject_ManagedDictPointer(obj)->dict;
1568
0
}
1569
1570
PyObject *
1571
PyObject_SelfIter(PyObject *obj)
1572
86.1M
{
1573
86.1M
    return Py_NewRef(obj);
1574
86.1M
}
1575
1576
/* Helper used when the __next__ method is removed from a type:
1577
   tp_iternext is never NULL and can be safely called without checking
1578
   on every iteration.
1579
 */
1580
1581
PyObject *
1582
_PyObject_NextNotImplemented(PyObject *self)
1583
0
{
1584
0
    PyErr_Format(PyExc_TypeError,
1585
0
                 "'%.200s' object is not iterable",
1586
0
                 Py_TYPE(self)->tp_name);
1587
0
    return NULL;
1588
0
}
1589
1590
1591
/* Specialized version of _PyObject_GenericGetAttrWithDict
1592
   specifically for the LOAD_METHOD opcode.
1593
1594
   Return 1 if a method is found, 0 if it's a regular attribute
1595
   from __dict__ or something returned by using a descriptor
1596
   protocol.
1597
1598
   `method` will point to the resolved attribute or NULL.  In the
1599
   latter case, an error will be set.
1600
*/
1601
int
1602
_PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method)
1603
0
{
1604
0
    int meth_found = 0;
1605
1606
0
    assert(*method == NULL);
1607
1608
0
    PyTypeObject *tp = Py_TYPE(obj);
1609
0
    if (!_PyType_IsReady(tp)) {
1610
0
        if (PyType_Ready(tp) < 0) {
1611
0
            return 0;
1612
0
        }
1613
0
    }
1614
1615
0
    if (tp->tp_getattro != PyObject_GenericGetAttr || !PyUnicode_CheckExact(name)) {
1616
0
        *method = PyObject_GetAttr(obj, name);
1617
0
        return 0;
1618
0
    }
1619
1620
0
    PyObject *descr = _PyType_LookupRef(tp, name);
1621
0
    descrgetfunc f = NULL;
1622
0
    if (descr != NULL) {
1623
0
        if (_PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_METHOD_DESCRIPTOR)) {
1624
0
            meth_found = 1;
1625
0
        }
1626
0
        else {
1627
0
            f = Py_TYPE(descr)->tp_descr_get;
1628
0
            if (f != NULL && PyDescr_IsData(descr)) {
1629
0
                *method = f(descr, obj, (PyObject *)Py_TYPE(obj));
1630
0
                Py_DECREF(descr);
1631
0
                return 0;
1632
0
            }
1633
0
        }
1634
0
    }
1635
0
    PyObject *dict, *attr;
1636
0
    if ((tp->tp_flags & Py_TPFLAGS_INLINE_VALUES) &&
1637
0
         _PyObject_TryGetInstanceAttribute(obj, name, &attr)) {
1638
0
        if (attr != NULL) {
1639
0
            *method = attr;
1640
0
            Py_XDECREF(descr);
1641
0
            return 0;
1642
0
        }
1643
0
        dict = NULL;
1644
0
    }
1645
0
    else if ((tp->tp_flags & Py_TPFLAGS_MANAGED_DICT)) {
1646
0
        dict = (PyObject *)_PyObject_GetManagedDict(obj);
1647
0
    }
1648
0
    else {
1649
0
        PyObject **dictptr = _PyObject_ComputedDictPointer(obj);
1650
0
        if (dictptr != NULL) {
1651
0
            dict = FT_ATOMIC_LOAD_PTR_ACQUIRE(*dictptr);
1652
0
        }
1653
0
        else {
1654
0
            dict = NULL;
1655
0
        }
1656
0
    }
1657
0
    if (dict != NULL) {
1658
0
        Py_INCREF(dict);
1659
0
        if (PyDict_GetItemRef(dict, name, method) != 0) {
1660
            // found or error
1661
0
            Py_DECREF(dict);
1662
0
            Py_XDECREF(descr);
1663
0
            return 0;
1664
0
        }
1665
        // not found
1666
0
        Py_DECREF(dict);
1667
0
    }
1668
1669
0
    if (meth_found) {
1670
0
        *method = descr;
1671
0
        return 1;
1672
0
    }
1673
1674
0
    if (f != NULL) {
1675
0
        *method = f(descr, obj, (PyObject *)Py_TYPE(obj));
1676
0
        Py_DECREF(descr);
1677
0
        return 0;
1678
0
    }
1679
1680
0
    if (descr != NULL) {
1681
0
        *method = descr;
1682
0
        return 0;
1683
0
    }
1684
1685
0
    PyErr_Format(PyExc_AttributeError,
1686
0
                 "'%.100s' object has no attribute '%U'",
1687
0
                 tp->tp_name, name);
1688
1689
0
    _PyObject_SetAttributeErrorContext(obj, name);
1690
0
    return 0;
1691
0
}
1692
1693
int
1694
_PyObject_GetMethodStackRef(PyThreadState *ts, PyObject *obj,
1695
                            PyObject *name, _PyStackRef *method)
1696
75.4M
{
1697
75.4M
    int meth_found = 0;
1698
1699
75.4M
    assert(PyStackRef_IsNull(*method));
1700
1701
75.4M
    PyTypeObject *tp = Py_TYPE(obj);
1702
75.4M
    if (!_PyType_IsReady(tp)) {
1703
0
        if (PyType_Ready(tp) < 0) {
1704
0
            return 0;
1705
0
        }
1706
0
    }
1707
1708
75.4M
    if (tp->tp_getattro != PyObject_GenericGetAttr || !PyUnicode_CheckExact(name)) {
1709
14.2M
        PyObject *res = PyObject_GetAttr(obj, name);
1710
14.2M
        if (res != NULL) {
1711
14.2M
            *method = PyStackRef_FromPyObjectSteal(res);
1712
14.2M
        }
1713
14.2M
        return 0;
1714
14.2M
    }
1715
1716
61.1M
    _PyType_LookupStackRefAndVersion(tp, name, method);
1717
61.1M
    PyObject *descr = PyStackRef_AsPyObjectBorrow(*method);
1718
61.1M
    descrgetfunc f = NULL;
1719
61.1M
    if (descr != NULL) {
1720
61.1M
        if (_PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_METHOD_DESCRIPTOR)) {
1721
60.2M
            meth_found = 1;
1722
60.2M
        }
1723
917k
        else {
1724
917k
            f = Py_TYPE(descr)->tp_descr_get;
1725
917k
            if (f != NULL && PyDescr_IsData(descr)) {
1726
35
                PyObject *value = f(descr, obj, (PyObject *)Py_TYPE(obj));
1727
35
                PyStackRef_CLEAR(*method);
1728
35
                if (value != NULL) {
1729
35
                    *method = PyStackRef_FromPyObjectSteal(value);
1730
35
                }
1731
35
                return 0;
1732
35
            }
1733
917k
        }
1734
61.1M
    }
1735
61.1M
    PyObject *dict, *attr;
1736
61.1M
    if ((tp->tp_flags & Py_TPFLAGS_INLINE_VALUES) &&
1737
21.6M
         _PyObject_TryGetInstanceAttribute(obj, name, &attr)) {
1738
732k
        if (attr != NULL) {
1739
139
           PyStackRef_CLEAR(*method);
1740
139
           *method = PyStackRef_FromPyObjectSteal(attr);
1741
139
           return 0;
1742
139
        }
1743
732k
        dict = NULL;
1744
732k
    }
1745
60.4M
    else if ((tp->tp_flags & Py_TPFLAGS_MANAGED_DICT)) {
1746
22.9M
        dict = (PyObject *)_PyObject_GetManagedDict(obj);
1747
22.9M
    }
1748
37.4M
    else {
1749
37.4M
        PyObject **dictptr = _PyObject_ComputedDictPointer(obj);
1750
37.4M
        if (dictptr != NULL) {
1751
35.7M
            dict = FT_ATOMIC_LOAD_PTR_ACQUIRE(*dictptr);
1752
35.7M
        }
1753
1.76M
        else {
1754
1.76M
            dict = NULL;
1755
1.76M
        }
1756
37.4M
    }
1757
61.1M
    if (dict != NULL) {
1758
58.0M
        assert(PyUnicode_CheckExact(name));
1759
58.0M
        int found = _PyDict_GetMethodStackRef((PyDictObject *)dict, name, method);
1760
58.0M
        if (found < 0) {
1761
0
            assert(PyStackRef_IsNull(*method));
1762
0
            return -1;
1763
0
        }
1764
58.0M
        else if (found) {
1765
2
            return 0;
1766
2
        }
1767
58.0M
    }
1768
1769
61.1M
    if (meth_found) {
1770
60.2M
        assert(!PyStackRef_IsNull(*method));
1771
60.2M
        return 1;
1772
60.2M
    }
1773
1774
917k
    if (f != NULL) {
1775
667k
        PyObject *value = f(descr, obj, (PyObject *)Py_TYPE(obj));
1776
667k
        PyStackRef_CLEAR(*method);
1777
667k
        if (value) {
1778
667k
            *method = PyStackRef_FromPyObjectSteal(value);
1779
667k
        }
1780
667k
        return 0;
1781
667k
    }
1782
1783
249k
    if (descr != NULL) {
1784
249k
        assert(!PyStackRef_IsNull(*method));
1785
249k
        return 0;
1786
249k
    }
1787
1788
0
    PyErr_Format(PyExc_AttributeError,
1789
0
                 "'%.100s' object has no attribute '%U'",
1790
0
                 tp->tp_name, name);
1791
1792
0
    _PyObject_SetAttributeErrorContext(obj, name);
1793
0
    assert(PyStackRef_IsNull(*method));
1794
0
    return 0;
1795
249k
}
1796
1797
1798
/* Generic GetAttr functions - put these in your tp_[gs]etattro slot. */
1799
1800
PyObject *
1801
_PyObject_GenericGetAttrWithDict(PyObject *obj, PyObject *name,
1802
                                 PyObject *dict, int suppress)
1803
603M
{
1804
    /* Make sure the logic of _PyObject_GetMethod is in sync with
1805
       this method.
1806
1807
       When suppress=1, this function suppresses AttributeError.
1808
    */
1809
1810
603M
    PyTypeObject *tp = Py_TYPE(obj);
1811
603M
    PyObject *descr = NULL;
1812
603M
    PyObject *res = NULL;
1813
603M
    descrgetfunc f;
1814
1815
603M
    if (!PyUnicode_Check(name)){
1816
0
        PyErr_Format(PyExc_TypeError,
1817
0
                     "attribute name must be string, not '%.200s'",
1818
0
                     Py_TYPE(name)->tp_name);
1819
0
        return NULL;
1820
0
    }
1821
1822
603M
    if (!_PyType_IsReady(tp)) {
1823
0
        if (PyType_Ready(tp) < 0)
1824
0
            return NULL;
1825
0
    }
1826
1827
603M
    Py_INCREF(name);
1828
1829
603M
    PyThreadState *tstate = _PyThreadState_GET();
1830
603M
    _PyCStackRef cref;
1831
603M
    _PyThreadState_PushCStackRef(tstate, &cref);
1832
1833
603M
    _PyType_LookupStackRefAndVersion(tp, name, &cref.ref);
1834
603M
    descr = PyStackRef_AsPyObjectBorrow(cref.ref);
1835
1836
603M
    f = NULL;
1837
603M
    if (descr != NULL) {
1838
482M
        f = Py_TYPE(descr)->tp_descr_get;
1839
482M
        if (f != NULL && PyDescr_IsData(descr)) {
1840
80.8M
            res = f(descr, obj, (PyObject *)Py_TYPE(obj));
1841
80.8M
            if (res == NULL && suppress &&
1842
2.19k
                    PyErr_ExceptionMatches(PyExc_AttributeError)) {
1843
2.18k
                PyErr_Clear();
1844
2.18k
            }
1845
80.8M
            goto done;
1846
80.8M
        }
1847
482M
    }
1848
522M
    if (dict == NULL) {
1849
522M
        if ((tp->tp_flags & Py_TPFLAGS_INLINE_VALUES)) {
1850
158M
            if (PyUnicode_CheckExact(name) &&
1851
158M
                _PyObject_TryGetInstanceAttribute(obj, name, &res)) {
1852
72.5M
                if (res != NULL) {
1853
26.1M
                    goto done;
1854
26.1M
                }
1855
72.5M
            }
1856
85.5M
            else {
1857
85.5M
                dict = (PyObject *)_PyObject_MaterializeManagedDict(obj);
1858
85.5M
                if (dict == NULL) {
1859
0
                    res = NULL;
1860
0
                    goto done;
1861
0
                }
1862
85.5M
            }
1863
158M
        }
1864
364M
        else if ((tp->tp_flags & Py_TPFLAGS_MANAGED_DICT)) {
1865
4.95M
            dict = (PyObject *)_PyObject_GetManagedDict(obj);
1866
4.95M
        }
1867
359M
        else {
1868
359M
            PyObject **dictptr = _PyObject_ComputedDictPointer(obj);
1869
359M
            if (dictptr) {
1870
#ifdef Py_GIL_DISABLED
1871
                dict = _Py_atomic_load_ptr_acquire(dictptr);
1872
#else
1873
76.9M
                dict = *dictptr;
1874
76.9M
#endif
1875
76.9M
            }
1876
359M
        }
1877
522M
    }
1878
496M
    if (dict != NULL) {
1879
166M
        Py_INCREF(dict);
1880
166M
        int rc = PyDict_GetItemRef(dict, name, &res);
1881
166M
        Py_DECREF(dict);
1882
166M
        if (res != NULL) {
1883
134M
            goto done;
1884
134M
        }
1885
31.8M
        else if (rc < 0) {
1886
0
            if (suppress && PyErr_ExceptionMatches(PyExc_AttributeError)) {
1887
0
                PyErr_Clear();
1888
0
            }
1889
0
            else {
1890
0
                goto done;
1891
0
            }
1892
0
        }
1893
166M
    }
1894
1895
361M
    if (f != NULL) {
1896
309M
        res = f(descr, obj, (PyObject *)Py_TYPE(obj));
1897
309M
        if (res == NULL && suppress &&
1898
0
                PyErr_ExceptionMatches(PyExc_AttributeError)) {
1899
0
            PyErr_Clear();
1900
0
        }
1901
309M
        goto done;
1902
309M
    }
1903
1904
52.0M
    if (descr != NULL) {
1905
35.7M
        res = PyStackRef_AsPyObjectSteal(cref.ref);
1906
35.7M
        cref.ref = PyStackRef_NULL;
1907
35.7M
        goto done;
1908
35.7M
    }
1909
1910
16.2M
    if (!suppress) {
1911
10.8k
        PyErr_Format(PyExc_AttributeError,
1912
10.8k
                     "'%.100s' object has no attribute '%U'",
1913
10.8k
                     tp->tp_name, name);
1914
1915
10.8k
        _PyObject_SetAttributeErrorContext(obj, name);
1916
10.8k
    }
1917
603M
  done:
1918
603M
    _PyThreadState_PopCStackRef(tstate, &cref);
1919
603M
    Py_DECREF(name);
1920
603M
    return res;
1921
16.2M
}
1922
1923
PyObject *
1924
PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1925
513M
{
1926
513M
    return _PyObject_GenericGetAttrWithDict(obj, name, NULL, 0);
1927
513M
}
1928
1929
int
1930
_PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
1931
                                 PyObject *value, PyObject *dict)
1932
80.7M
{
1933
80.7M
    PyTypeObject *tp = Py_TYPE(obj);
1934
80.7M
    PyObject *descr;
1935
80.7M
    descrsetfunc f;
1936
80.7M
    int res = -1;
1937
1938
80.7M
    assert(!PyType_IsSubtype(tp, &PyType_Type));
1939
80.7M
    if (!PyUnicode_Check(name)){
1940
0
        PyErr_Format(PyExc_TypeError,
1941
0
                     "attribute name must be string, not '%.200s'",
1942
0
                     Py_TYPE(name)->tp_name);
1943
0
        return -1;
1944
0
    }
1945
1946
80.7M
    if (!_PyType_IsReady(tp) && PyType_Ready(tp) < 0) {
1947
0
        return -1;
1948
0
    }
1949
1950
80.7M
    Py_INCREF(name);
1951
80.7M
    Py_INCREF(tp);
1952
1953
80.7M
    PyThreadState *tstate = _PyThreadState_GET();
1954
80.7M
    _PyCStackRef cref;
1955
80.7M
    _PyThreadState_PushCStackRef(tstate, &cref);
1956
1957
80.7M
    _PyType_LookupStackRefAndVersion(tp, name, &cref.ref);
1958
80.7M
    descr = PyStackRef_AsPyObjectBorrow(cref.ref);
1959
1960
80.7M
    if (descr != NULL) {
1961
40.2M
        f = Py_TYPE(descr)->tp_descr_set;
1962
40.2M
        if (f != NULL) {
1963
5.55M
            res = f(descr, obj, value);
1964
5.55M
            goto done;
1965
5.55M
        }
1966
40.2M
    }
1967
1968
75.2M
    if (dict == NULL) {
1969
75.2M
        PyObject **dictptr;
1970
1971
75.2M
        if ((tp->tp_flags & Py_TPFLAGS_INLINE_VALUES)) {
1972
46.3M
            res = _PyObject_StoreInstanceAttribute(obj, name, value);
1973
46.3M
            goto error_check;
1974
46.3M
        }
1975
1976
28.8M
        if ((tp->tp_flags & Py_TPFLAGS_MANAGED_DICT)) {
1977
49.7k
            PyManagedDictPointer *managed_dict = _PyObject_ManagedDictPointer(obj);
1978
49.7k
            dictptr = (PyObject **)&managed_dict->dict;
1979
49.7k
        }
1980
28.8M
        else {
1981
28.8M
            dictptr = _PyObject_ComputedDictPointer(obj);
1982
28.8M
        }
1983
28.8M
        if (dictptr == NULL) {
1984
0
            if (descr == NULL) {
1985
0
                if (tp->tp_setattro == PyObject_GenericSetAttr) {
1986
0
                    PyErr_Format(PyExc_AttributeError,
1987
0
                                "'%.100s' object has no attribute '%U' and no "
1988
0
                                "__dict__ for setting new attributes",
1989
0
                                tp->tp_name, name);
1990
0
                }
1991
0
                else {
1992
0
                    PyErr_Format(PyExc_AttributeError,
1993
0
                                "'%.100s' object has no attribute '%U'",
1994
0
                                tp->tp_name, name);
1995
0
                }
1996
0
                _PyObject_SetAttributeErrorContext(obj, name);
1997
0
            }
1998
0
            else {
1999
0
                PyErr_Format(PyExc_AttributeError,
2000
0
                            "'%.100s' object attribute '%U' is read-only",
2001
0
                            tp->tp_name, name);
2002
0
            }
2003
0
            goto done;
2004
0
        }
2005
28.8M
        else {
2006
28.8M
            res = _PyObjectDict_SetItem(tp, obj, dictptr, name, value);
2007
28.8M
        }
2008
28.8M
    }
2009
0
    else {
2010
0
        Py_INCREF(dict);
2011
0
        if (value == NULL)
2012
0
            res = PyDict_DelItem(dict, name);
2013
0
        else
2014
0
            res = PyDict_SetItem(dict, name, value);
2015
0
        Py_DECREF(dict);
2016
0
    }
2017
75.2M
  error_check:
2018
75.2M
    if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) {
2019
0
        PyErr_Format(PyExc_AttributeError,
2020
0
                        "'%.100s' object has no attribute '%U'",
2021
0
                        tp->tp_name, name);
2022
0
        _PyObject_SetAttributeErrorContext(obj, name);
2023
0
    }
2024
80.7M
  done:
2025
80.7M
    _PyThreadState_PopCStackRef(tstate, &cref);
2026
80.7M
    Py_DECREF(tp);
2027
80.7M
    Py_DECREF(name);
2028
80.7M
    return res;
2029
75.2M
}
2030
2031
int
2032
PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
2033
80.7M
{
2034
80.7M
    return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL);
2035
80.7M
}
2036
2037
int
2038
PyObject_GenericSetDict(PyObject *obj, PyObject *value, void *context)
2039
0
{
2040
0
    if (value == NULL) {
2041
0
        PyErr_SetString(PyExc_TypeError, "cannot delete __dict__");
2042
0
        return -1;
2043
0
    }
2044
0
    return _PyObject_SetDict(obj, value);
2045
0
}
2046
2047
2048
/* Test a value used as condition, e.g., in a while or if statement.
2049
   Return -1 if an error occurred */
2050
2051
int
2052
PyObject_IsTrue(PyObject *v)
2053
148M
{
2054
148M
    Py_ssize_t res;
2055
148M
    if (v == Py_True)
2056
15.4M
        return 1;
2057
133M
    if (v == Py_False)
2058
31.2M
        return 0;
2059
101M
    if (v == Py_None)
2060
4.95M
        return 0;
2061
96.9M
    else if (Py_TYPE(v)->tp_as_number != NULL &&
2062
83.8M
             Py_TYPE(v)->tp_as_number->nb_bool != NULL)
2063
1.31M
        res = (*Py_TYPE(v)->tp_as_number->nb_bool)(v);
2064
95.6M
    else if (Py_TYPE(v)->tp_as_mapping != NULL &&
2065
88.6M
             Py_TYPE(v)->tp_as_mapping->mp_length != NULL)
2066
36.4M
        res = (*Py_TYPE(v)->tp_as_mapping->mp_length)(v);
2067
59.1M
    else if (Py_TYPE(v)->tp_as_sequence != NULL &&
2068
52.2M
             Py_TYPE(v)->tp_as_sequence->sq_length != NULL)
2069
48.6M
        res = (*Py_TYPE(v)->tp_as_sequence->sq_length)(v);
2070
10.5M
    else
2071
10.5M
        return 1;
2072
    /* if it is negative, it should be either -1 or -2 */
2073
86.4M
    return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
2074
101M
}
2075
2076
/* equivalent of 'not v'
2077
   Return -1 if an error occurred */
2078
2079
int
2080
PyObject_Not(PyObject *v)
2081
0
{
2082
0
    int res;
2083
0
    res = PyObject_IsTrue(v);
2084
0
    if (res < 0)
2085
0
        return res;
2086
0
    return res == 0;
2087
0
}
2088
2089
/* Test whether an object can be called */
2090
2091
int
2092
PyCallable_Check(PyObject *x)
2093
14.3M
{
2094
14.3M
    if (x == NULL)
2095
0
        return 0;
2096
14.3M
    return Py_TYPE(x)->tp_call != NULL;
2097
14.3M
}
2098
2099
2100
/* Helper for PyObject_Dir without arguments: returns the local scope. */
2101
static PyObject *
2102
_dir_locals(void)
2103
0
{
2104
0
    PyObject *names;
2105
0
    PyObject *locals;
2106
2107
0
    if (_PyEval_GetFrame() != NULL) {
2108
0
        locals = _PyEval_GetFrameLocals();
2109
0
    }
2110
0
    else {
2111
0
        PyThreadState *tstate = _PyThreadState_GET();
2112
0
        locals = _PyEval_GetGlobalsFromRunningMain(tstate);
2113
0
        if (locals == NULL) {
2114
0
            if (!_PyErr_Occurred(tstate)) {
2115
0
                locals = _PyEval_GetFrameLocals();
2116
0
                assert(_PyErr_Occurred(tstate));
2117
0
            }
2118
0
        }
2119
0
        else {
2120
0
            Py_INCREF(locals);
2121
0
        }
2122
0
    }
2123
0
    if (locals == NULL) {
2124
0
        return NULL;
2125
0
    }
2126
2127
0
    names = PyMapping_Keys(locals);
2128
0
    Py_DECREF(locals);
2129
0
    if (!names) {
2130
0
        return NULL;
2131
0
    }
2132
0
    if (!PyList_Check(names)) {
2133
0
        PyErr_Format(PyExc_TypeError,
2134
0
            "dir(): expected keys() of locals to be a list, "
2135
0
            "not '%.200s'", Py_TYPE(names)->tp_name);
2136
0
        Py_DECREF(names);
2137
0
        return NULL;
2138
0
    }
2139
0
    if (PyList_Sort(names)) {
2140
0
        Py_DECREF(names);
2141
0
        return NULL;
2142
0
    }
2143
0
    return names;
2144
0
}
2145
2146
/* Helper for PyObject_Dir: object introspection. */
2147
static PyObject *
2148
_dir_object(PyObject *obj)
2149
5.97k
{
2150
5.97k
    PyObject *result, *sorted;
2151
5.97k
    PyObject *dirfunc = _PyObject_LookupSpecial(obj, &_Py_ID(__dir__));
2152
2153
5.97k
    assert(obj != NULL);
2154
5.97k
    if (dirfunc == NULL) {
2155
0
        if (!PyErr_Occurred())
2156
0
            PyErr_SetString(PyExc_TypeError, "object does not provide __dir__");
2157
0
        return NULL;
2158
0
    }
2159
    /* use __dir__ */
2160
5.97k
    result = _PyObject_CallNoArgs(dirfunc);
2161
5.97k
    Py_DECREF(dirfunc);
2162
5.97k
    if (result == NULL)
2163
0
        return NULL;
2164
    /* return sorted(result) */
2165
5.97k
    sorted = PySequence_List(result);
2166
5.97k
    Py_DECREF(result);
2167
5.97k
    if (sorted == NULL)
2168
0
        return NULL;
2169
5.97k
    if (PyList_Sort(sorted)) {
2170
0
        Py_DECREF(sorted);
2171
0
        return NULL;
2172
0
    }
2173
5.97k
    return sorted;
2174
5.97k
}
2175
2176
/* Implementation of dir() -- if obj is NULL, returns the names in the current
2177
   (local) scope.  Otherwise, performs introspection of the object: returns a
2178
   sorted list of attribute names (supposedly) accessible from the object
2179
*/
2180
PyObject *
2181
PyObject_Dir(PyObject *obj)
2182
5.97k
{
2183
5.97k
    return (obj == NULL) ? _dir_locals() : _dir_object(obj);
2184
5.97k
}
2185
2186
/*
2187
None is a non-NULL undefined value.
2188
There is (and should be!) no way to create other objects of this type,
2189
so there is exactly one (which is indestructible, by the way).
2190
*/
2191
2192
/* ARGSUSED */
2193
static PyObject *
2194
none_repr(PyObject *op)
2195
367
{
2196
367
    return PyUnicode_FromString("None");
2197
367
}
2198
2199
static void
2200
none_dealloc(PyObject* none)
2201
0
{
2202
    /* This should never get called, but we also don't want to SEGV if
2203
     * we accidentally decref None out of existence. Instead,
2204
     * since None is an immortal object, re-set the reference count.
2205
     */
2206
0
    _Py_SetImmortal(none);
2207
0
}
2208
2209
static PyObject *
2210
none_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
2211
0
{
2212
0
    if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
2213
0
        PyErr_SetString(PyExc_TypeError, "NoneType takes no arguments");
2214
0
        return NULL;
2215
0
    }
2216
0
    Py_RETURN_NONE;
2217
0
}
2218
2219
static int
2220
none_bool(PyObject *v)
2221
0
{
2222
0
    return 0;
2223
0
}
2224
2225
static Py_hash_t none_hash(PyObject *v)
2226
44.4k
{
2227
44.4k
    return 0xFCA86420;
2228
44.4k
}
2229
2230
static PyNumberMethods none_as_number = {
2231
    0,                          /* nb_add */
2232
    0,                          /* nb_subtract */
2233
    0,                          /* nb_multiply */
2234
    0,                          /* nb_remainder */
2235
    0,                          /* nb_divmod */
2236
    0,                          /* nb_power */
2237
    0,                          /* nb_negative */
2238
    0,                          /* nb_positive */
2239
    0,                          /* nb_absolute */
2240
    none_bool,                  /* nb_bool */
2241
    0,                          /* nb_invert */
2242
    0,                          /* nb_lshift */
2243
    0,                          /* nb_rshift */
2244
    0,                          /* nb_and */
2245
    0,                          /* nb_xor */
2246
    0,                          /* nb_or */
2247
    0,                          /* nb_int */
2248
    0,                          /* nb_reserved */
2249
    0,                          /* nb_float */
2250
    0,                          /* nb_inplace_add */
2251
    0,                          /* nb_inplace_subtract */
2252
    0,                          /* nb_inplace_multiply */
2253
    0,                          /* nb_inplace_remainder */
2254
    0,                          /* nb_inplace_power */
2255
    0,                          /* nb_inplace_lshift */
2256
    0,                          /* nb_inplace_rshift */
2257
    0,                          /* nb_inplace_and */
2258
    0,                          /* nb_inplace_xor */
2259
    0,                          /* nb_inplace_or */
2260
    0,                          /* nb_floor_divide */
2261
    0,                          /* nb_true_divide */
2262
    0,                          /* nb_inplace_floor_divide */
2263
    0,                          /* nb_inplace_true_divide */
2264
    0,                          /* nb_index */
2265
};
2266
2267
PyDoc_STRVAR(none_doc,
2268
"NoneType()\n"
2269
"--\n\n"
2270
"The type of the None singleton.");
2271
2272
PyTypeObject _PyNone_Type = {
2273
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
2274
    "NoneType",
2275
    0,
2276
    0,
2277
    none_dealloc,       /*tp_dealloc*/
2278
    0,                  /*tp_vectorcall_offset*/
2279
    0,                  /*tp_getattr*/
2280
    0,                  /*tp_setattr*/
2281
    0,                  /*tp_as_async*/
2282
    none_repr,          /*tp_repr*/
2283
    &none_as_number,    /*tp_as_number*/
2284
    0,                  /*tp_as_sequence*/
2285
    0,                  /*tp_as_mapping*/
2286
    none_hash,          /*tp_hash */
2287
    0,                  /*tp_call */
2288
    0,                  /*tp_str */
2289
    0,                  /*tp_getattro */
2290
    0,                  /*tp_setattro */
2291
    0,                  /*tp_as_buffer */
2292
    Py_TPFLAGS_DEFAULT, /*tp_flags */
2293
    none_doc,           /*tp_doc */
2294
    0,                  /*tp_traverse */
2295
    0,                  /*tp_clear */
2296
    _Py_BaseObject_RichCompare, /*tp_richcompare */
2297
    0,                  /*tp_weaklistoffset */
2298
    0,                  /*tp_iter */
2299
    0,                  /*tp_iternext */
2300
    0,                  /*tp_methods */
2301
    0,                  /*tp_members */
2302
    0,                  /*tp_getset */
2303
    0,                  /*tp_base */
2304
    0,                  /*tp_dict */
2305
    0,                  /*tp_descr_get */
2306
    0,                  /*tp_descr_set */
2307
    0,                  /*tp_dictoffset */
2308
    0,                  /*tp_init */
2309
    0,                  /*tp_alloc */
2310
    none_new,           /*tp_new */
2311
};
2312
2313
PyObject _Py_NoneStruct = _PyObject_HEAD_INIT(&_PyNone_Type);
2314
2315
/* NotImplemented is an object that can be used to signal that an
2316
   operation is not implemented for the given type combination. */
2317
2318
static PyObject *
2319
NotImplemented_repr(PyObject *op)
2320
0
{
2321
0
    return PyUnicode_FromString("NotImplemented");
2322
0
}
2323
2324
static PyObject *
2325
NotImplemented_reduce(PyObject *op, PyObject *Py_UNUSED(ignored))
2326
0
{
2327
0
    return PyUnicode_FromString("NotImplemented");
2328
0
}
2329
2330
static PyMethodDef notimplemented_methods[] = {
2331
    {"__reduce__", NotImplemented_reduce, METH_NOARGS, NULL},
2332
    {NULL, NULL}
2333
};
2334
2335
static PyObject *
2336
notimplemented_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
2337
0
{
2338
0
    if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
2339
0
        PyErr_SetString(PyExc_TypeError, "NotImplementedType takes no arguments");
2340
0
        return NULL;
2341
0
    }
2342
0
    Py_RETURN_NOTIMPLEMENTED;
2343
0
}
2344
2345
static void
2346
notimplemented_dealloc(PyObject *notimplemented)
2347
0
{
2348
    /* This should never get called, but we also don't want to SEGV if
2349
     * we accidentally decref NotImplemented out of existence. Instead,
2350
     * since Notimplemented is an immortal object, re-set the reference count.
2351
     */
2352
0
    _Py_SetImmortal(notimplemented);
2353
0
}
2354
2355
static int
2356
notimplemented_bool(PyObject *v)
2357
0
{
2358
0
    PyErr_SetString(PyExc_TypeError,
2359
0
                    "NotImplemented should not be used in a boolean context");
2360
0
    return -1;
2361
0
}
2362
2363
static PyNumberMethods notimplemented_as_number = {
2364
    .nb_bool = notimplemented_bool,
2365
};
2366
2367
PyDoc_STRVAR(notimplemented_doc,
2368
"NotImplementedType()\n"
2369
"--\n\n"
2370
"The type of the NotImplemented singleton.");
2371
2372
PyTypeObject _PyNotImplemented_Type = {
2373
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
2374
    "NotImplementedType",
2375
    0,
2376
    0,
2377
    notimplemented_dealloc,       /*tp_dealloc*/ /*never called*/
2378
    0,                  /*tp_vectorcall_offset*/
2379
    0,                  /*tp_getattr*/
2380
    0,                  /*tp_setattr*/
2381
    0,                  /*tp_as_async*/
2382
    NotImplemented_repr,        /*tp_repr*/
2383
    &notimplemented_as_number,  /*tp_as_number*/
2384
    0,                  /*tp_as_sequence*/
2385
    0,                  /*tp_as_mapping*/
2386
    0,                  /*tp_hash */
2387
    0,                  /*tp_call */
2388
    0,                  /*tp_str */
2389
    0,                  /*tp_getattro */
2390
    0,                  /*tp_setattro */
2391
    0,                  /*tp_as_buffer */
2392
    Py_TPFLAGS_DEFAULT, /*tp_flags */
2393
    notimplemented_doc, /*tp_doc */
2394
    0,                  /*tp_traverse */
2395
    0,                  /*tp_clear */
2396
    0,                  /*tp_richcompare */
2397
    0,                  /*tp_weaklistoffset */
2398
    0,                  /*tp_iter */
2399
    0,                  /*tp_iternext */
2400
    notimplemented_methods, /*tp_methods */
2401
    0,                  /*tp_members */
2402
    0,                  /*tp_getset */
2403
    0,                  /*tp_base */
2404
    0,                  /*tp_dict */
2405
    0,                  /*tp_descr_get */
2406
    0,                  /*tp_descr_set */
2407
    0,                  /*tp_dictoffset */
2408
    0,                  /*tp_init */
2409
    0,                  /*tp_alloc */
2410
    notimplemented_new, /*tp_new */
2411
};
2412
2413
PyObject _Py_NotImplementedStruct = _PyObject_HEAD_INIT(&_PyNotImplemented_Type);
2414
2415
2416
PyStatus
2417
_PyObject_InitState(PyInterpreterState *interp)
2418
28
{
2419
#ifdef Py_TRACE_REFS
2420
    if (refchain_init(interp) < 0) {
2421
        return _PyStatus_NO_MEMORY();
2422
    }
2423
#endif
2424
28
    return _PyStatus_OK();
2425
28
}
2426
2427
void
2428
_PyObject_FiniState(PyInterpreterState *interp)
2429
0
{
2430
#ifdef Py_TRACE_REFS
2431
    refchain_fini(interp);
2432
#endif
2433
0
}
2434
2435
2436
extern PyTypeObject _PyAnextAwaitable_Type;
2437
extern PyTypeObject _PyLegacyEventHandler_Type;
2438
extern PyTypeObject _PyLineIterator;
2439
extern PyTypeObject _PyMemoryIter_Type;
2440
extern PyTypeObject _PyPositionsIterator;
2441
extern PyTypeObject _Py_GenericAliasIterType;
2442
2443
static PyTypeObject* static_types[] = {
2444
    // The two most important base types: must be initialized first and
2445
    // deallocated last.
2446
    &PyBaseObject_Type,
2447
    &PyType_Type,
2448
2449
    // Static types with base=&PyBaseObject_Type
2450
    &PyAsyncGen_Type,
2451
    &PyByteArrayIter_Type,
2452
    &PyByteArray_Type,
2453
    &PyBytesIter_Type,
2454
    &PyBytes_Type,
2455
    &PyCFunction_Type,
2456
    &PyCallIter_Type,
2457
    &PyCapsule_Type,
2458
    &PyCell_Type,
2459
    &PyClassMethodDescr_Type,
2460
    &PyClassMethod_Type,
2461
    &PyCode_Type,
2462
    &PyComplex_Type,
2463
    &PyContextToken_Type,
2464
    &PyContextVar_Type,
2465
    &PyContext_Type,
2466
    &PyCoro_Type,
2467
    &PyDictItems_Type,
2468
    &PyDictIterItem_Type,
2469
    &PyDictIterKey_Type,
2470
    &PyDictIterValue_Type,
2471
    &PyDictKeys_Type,
2472
    &PyDictProxy_Type,
2473
    &PyDictRevIterItem_Type,
2474
    &PyDictRevIterKey_Type,
2475
    &PyDictRevIterValue_Type,
2476
    &PyDictValues_Type,
2477
    &PyDict_Type,
2478
    &PyEllipsis_Type,
2479
    &PyEnum_Type,
2480
    &PyFilter_Type,
2481
    &PyFloat_Type,
2482
    &PyFrame_Type,
2483
    &PyFrameLocalsProxy_Type,
2484
    &PyFrozenSet_Type,
2485
    &PyFunction_Type,
2486
    &PyGen_Type,
2487
    &PyGetSetDescr_Type,
2488
    &PyInstanceMethod_Type,
2489
    &PyListIter_Type,
2490
    &PyListRevIter_Type,
2491
    &PyList_Type,
2492
    &PyLongRangeIter_Type,
2493
    &PyLong_Type,
2494
    &PyMap_Type,
2495
    &PyMemberDescr_Type,
2496
    &PyMemoryView_Type,
2497
    &PyMethodDescr_Type,
2498
    &PyMethod_Type,
2499
    &PyModuleDef_Type,
2500
    &PyModule_Type,
2501
    &PyODictIter_Type,
2502
    &PyPickleBuffer_Type,
2503
    &PyProperty_Type,
2504
    &PyRangeIter_Type,
2505
    &PyRange_Type,
2506
    &PyReversed_Type,
2507
    &PySTEntry_Type,
2508
    &PySeqIter_Type,
2509
    &PySetIter_Type,
2510
    &PySet_Type,
2511
    &PySlice_Type,
2512
    &PyStaticMethod_Type,
2513
    &PyStdPrinter_Type,
2514
    &PySuper_Type,
2515
    &PyTraceBack_Type,
2516
    &PyTupleIter_Type,
2517
    &PyTuple_Type,
2518
    &PyUnicodeIter_Type,
2519
    &PyUnicode_Type,
2520
    &PyWrapperDescr_Type,
2521
    &PyZip_Type,
2522
    &Py_GenericAliasType,
2523
    &_PyAnextAwaitable_Type,
2524
    &_PyAsyncGenASend_Type,
2525
    &_PyAsyncGenAThrow_Type,
2526
    &_PyAsyncGenWrappedValue_Type,
2527
    &_PyBufferWrapper_Type,
2528
    &_PyContextTokenMissing_Type,
2529
    &_PyCoroWrapper_Type,
2530
    &_Py_GenericAliasIterType,
2531
    &_PyHamtItems_Type,
2532
    &_PyHamtKeys_Type,
2533
    &_PyHamtValues_Type,
2534
    &_PyHamt_ArrayNode_Type,
2535
    &_PyHamt_BitmapNode_Type,
2536
    &_PyHamt_CollisionNode_Type,
2537
    &_PyHamt_Type,
2538
    &_PyInstructionSequence_Type,
2539
    &_PyInterpolation_Type,
2540
    &_PyLegacyEventHandler_Type,
2541
    &_PyLineIterator,
2542
    &_PyManagedBuffer_Type,
2543
    &_PyMemoryIter_Type,
2544
    &_PyMethodWrapper_Type,
2545
    &_PyNamespace_Type,
2546
    &_PyNone_Type,
2547
    &_PyNotImplemented_Type,
2548
    &_PyPositionsIterator,
2549
    &_PyTemplate_Type,
2550
    &_PyTemplateIter_Type,
2551
    &_PyUnicodeASCIIIter_Type,
2552
    &_PyUnion_Type,
2553
#ifdef _Py_TIER2
2554
    &_PyUOpExecutor_Type,
2555
#endif
2556
    &_PyWeakref_CallableProxyType,
2557
    &_PyWeakref_ProxyType,
2558
    &_PyWeakref_RefType,
2559
    &_PyTypeAlias_Type,
2560
    &_PyNoDefault_Type,
2561
2562
    // subclasses: _PyTypes_FiniTypes() deallocates them before their base
2563
    // class
2564
    &PyBool_Type,         // base=&PyLong_Type
2565
    &PyCMethod_Type,      // base=&PyCFunction_Type
2566
    &PyODictItems_Type,   // base=&PyDictItems_Type
2567
    &PyODictKeys_Type,    // base=&PyDictKeys_Type
2568
    &PyODictValues_Type,  // base=&PyDictValues_Type
2569
    &PyODict_Type,        // base=&PyDict_Type
2570
};
2571
2572
2573
PyStatus
2574
_PyTypes_InitTypes(PyInterpreterState *interp)
2575
28
{
2576
    // All other static types (unless initialized elsewhere)
2577
3.27k
    for (size_t i=0; i < Py_ARRAY_LENGTH(static_types); i++) {
2578
3.24k
        PyTypeObject *type = static_types[i];
2579
3.24k
        if (_PyStaticType_InitBuiltin(interp, type) < 0) {
2580
0
            return _PyStatus_ERR("Can't initialize builtin type");
2581
0
        }
2582
3.24k
        if (type == &PyType_Type) {
2583
            // Sanitify checks of the two most important types
2584
28
            assert(PyBaseObject_Type.tp_base == NULL);
2585
28
            assert(PyType_Type.tp_base == &PyBaseObject_Type);
2586
28
        }
2587
3.24k
    }
2588
2589
    // Cache __reduce__ from PyBaseObject_Type object
2590
28
    PyObject *baseobj_dict = _PyType_GetDict(&PyBaseObject_Type);
2591
28
    PyObject *baseobj_reduce = PyDict_GetItemWithError(baseobj_dict, &_Py_ID(__reduce__));
2592
28
    if (baseobj_reduce == NULL && PyErr_Occurred()) {
2593
0
        return _PyStatus_ERR("Can't get __reduce__ from base object");
2594
0
    }
2595
28
    _Py_INTERP_CACHED_OBJECT(interp, objreduce) = baseobj_reduce;
2596
2597
    // Must be after static types are initialized
2598
28
    if (_Py_initialize_generic(interp) < 0) {
2599
0
        return _PyStatus_ERR("Can't initialize generic types");
2600
0
    }
2601
2602
28
    return _PyStatus_OK();
2603
28
}
2604
2605
2606
// Best-effort function clearing static types.
2607
//
2608
// Don't deallocate a type if it still has subclasses. If a Py_Finalize()
2609
// sub-function is interrupted by CTRL+C or fails with MemoryError, some
2610
// subclasses are not cleared properly. Leave the static type unchanged in this
2611
// case.
2612
void
2613
_PyTypes_FiniTypes(PyInterpreterState *interp)
2614
0
{
2615
    // Deallocate types in the reverse order to deallocate subclasses before
2616
    // their base classes.
2617
0
    for (Py_ssize_t i=Py_ARRAY_LENGTH(static_types)-1; i>=0; i--) {
2618
0
        PyTypeObject *type = static_types[i];
2619
0
        _PyStaticType_FiniBuiltin(interp, type);
2620
0
    }
2621
0
}
2622
2623
2624
static inline void
2625
new_reference(PyObject *op)
2626
4.27G
{
2627
    // Skip the immortal object check in Py_SET_REFCNT; always set refcnt to 1
2628
4.27G
#if !defined(Py_GIL_DISABLED)
2629
4.27G
#if SIZEOF_VOID_P > 4
2630
4.27G
    op->ob_refcnt_full = 1;
2631
4.27G
    assert(op->ob_refcnt == 1);
2632
4.27G
    assert(op->ob_flags == 0);
2633
#else
2634
    op->ob_refcnt = 1;
2635
#endif
2636
#else
2637
    op->ob_flags = 0;
2638
    op->ob_mutex = (PyMutex){ 0 };
2639
#ifdef _Py_THREAD_SANITIZER
2640
    _Py_atomic_store_uintptr_relaxed(&op->ob_tid, _Py_ThreadId());
2641
    _Py_atomic_store_uint8_relaxed(&op->ob_gc_bits, 0);
2642
    _Py_atomic_store_uint32_relaxed(&op->ob_ref_local, 1);
2643
    _Py_atomic_store_ssize_relaxed(&op->ob_ref_shared, 0);
2644
#else
2645
    op->ob_tid = _Py_ThreadId();
2646
    op->ob_gc_bits = 0;
2647
    op->ob_ref_local = 1;
2648
    op->ob_ref_shared = 0;
2649
#endif
2650
#endif
2651
#ifdef Py_TRACE_REFS
2652
    _Py_AddToAllObjects(op);
2653
#endif
2654
4.27G
    _PyReftracerTrack(op, PyRefTracer_CREATE);
2655
4.27G
}
2656
2657
void
2658
_Py_NewReference(PyObject *op)
2659
4.20G
{
2660
#ifdef Py_REF_DEBUG
2661
    _Py_IncRefTotal(_PyThreadState_GET());
2662
#endif
2663
4.20G
    new_reference(op);
2664
4.20G
}
2665
2666
void
2667
_Py_NewReferenceNoTotal(PyObject *op)
2668
71.0M
{
2669
71.0M
    new_reference(op);
2670
71.0M
}
2671
2672
void
2673
_Py_SetImmortalUntracked(PyObject *op)
2674
176k
{
2675
#ifdef Py_DEBUG
2676
    // For strings, use _PyUnicode_InternImmortal instead.
2677
    if (PyUnicode_CheckExact(op)) {
2678
        assert(PyUnicode_CHECK_INTERNED(op) == SSTATE_INTERNED_IMMORTAL
2679
            || PyUnicode_CHECK_INTERNED(op) == SSTATE_INTERNED_IMMORTAL_STATIC);
2680
    }
2681
#endif
2682
    // Check if already immortal to avoid degrading from static immortal to plain immortal
2683
176k
    if (_Py_IsImmortal(op)) {
2684
84
        return;
2685
84
    }
2686
#ifdef Py_GIL_DISABLED
2687
    op->ob_tid = _Py_UNOWNED_TID;
2688
    op->ob_ref_local = _Py_IMMORTAL_REFCNT_LOCAL;
2689
    op->ob_ref_shared = 0;
2690
    _Py_atomic_or_uint8(&op->ob_gc_bits, _PyGC_BITS_DEFERRED);
2691
#elif SIZEOF_VOID_P > 4
2692
176k
    op->ob_flags = _Py_IMMORTAL_FLAGS;
2693
176k
    op->ob_refcnt = _Py_IMMORTAL_INITIAL_REFCNT;
2694
#else
2695
    op->ob_refcnt = _Py_IMMORTAL_INITIAL_REFCNT;
2696
#endif
2697
176k
}
2698
2699
void
2700
_Py_SetImmortal(PyObject *op)
2701
176k
{
2702
176k
    if (PyObject_IS_GC(op) && _PyObject_GC_IS_TRACKED(op)) {
2703
11.3k
        _PyObject_GC_UNTRACK(op);
2704
11.3k
    }
2705
176k
    _Py_SetImmortalUntracked(op);
2706
176k
}
2707
2708
void
2709
_PyObject_SetDeferredRefcount(PyObject *op)
2710
150k
{
2711
#ifdef Py_GIL_DISABLED
2712
    assert(PyType_IS_GC(Py_TYPE(op)));
2713
    assert(_Py_IsOwnedByCurrentThread(op));
2714
    assert(op->ob_ref_shared == 0);
2715
    _PyObject_SET_GC_BITS(op, _PyGC_BITS_DEFERRED);
2716
    op->ob_ref_shared = _Py_REF_SHARED(_Py_REF_DEFERRED, 0);
2717
#endif
2718
150k
}
2719
2720
int
2721
PyUnstable_Object_EnableDeferredRefcount(PyObject *op)
2722
0
{
2723
#ifdef Py_GIL_DISABLED
2724
    if (!PyType_IS_GC(Py_TYPE(op))) {
2725
        // Deferred reference counting doesn't work
2726
        // on untracked types.
2727
        return 0;
2728
    }
2729
2730
    uint8_t bits = _Py_atomic_load_uint8(&op->ob_gc_bits);
2731
    if ((bits & _PyGC_BITS_DEFERRED) != 0)
2732
    {
2733
        // Nothing to do.
2734
        return 0;
2735
    }
2736
2737
    if (_Py_atomic_compare_exchange_uint8(&op->ob_gc_bits, &bits, bits | _PyGC_BITS_DEFERRED) == 0)
2738
    {
2739
        // Someone beat us to it!
2740
        return 0;
2741
    }
2742
    _Py_atomic_add_ssize(&op->ob_ref_shared, _Py_REF_SHARED(_Py_REF_DEFERRED, 0));
2743
    return 1;
2744
#else
2745
0
    return 0;
2746
0
#endif
2747
0
}
2748
2749
int
2750
PyUnstable_Object_IsUniqueReferencedTemporary(PyObject *op)
2751
0
{
2752
0
    if (!_PyObject_IsUniquelyReferenced(op)) {
2753
0
        return 0;
2754
0
    }
2755
2756
0
    _PyInterpreterFrame *frame = _PyEval_GetFrame();
2757
0
    if (frame == NULL) {
2758
0
        return 0;
2759
0
    }
2760
2761
0
    _PyStackRef *base = _PyFrame_Stackbase(frame);
2762
0
    _PyStackRef *stackpointer = frame->stackpointer;
2763
0
    while (stackpointer > base) {
2764
0
        stackpointer--;
2765
0
        _PyStackRef ref = *stackpointer;
2766
0
        if (PyStackRef_IsTaggedInt(ref)) {
2767
0
            continue;
2768
0
        }
2769
0
        if (op == PyStackRef_AsPyObjectBorrow(ref)) {
2770
0
            return PyStackRef_IsHeapSafe(ref);
2771
0
        }
2772
0
    }
2773
0
    return 0;
2774
0
}
2775
2776
int
2777
PyUnstable_TryIncRef(PyObject *op)
2778
0
{
2779
0
    return _Py_TryIncref(op);
2780
0
}
2781
2782
void
2783
PyUnstable_EnableTryIncRef(PyObject *op)
2784
0
{
2785
#ifdef Py_GIL_DISABLED
2786
    _PyObject_SetMaybeWeakref(op);
2787
#endif
2788
0
}
2789
2790
void
2791
_Py_ResurrectReference(PyObject *op)
2792
0
{
2793
#ifdef Py_TRACE_REFS
2794
    _Py_AddToAllObjects(op);
2795
#endif
2796
0
}
2797
2798
void
2799
_Py_ForgetReference(PyObject *op)
2800
0
{
2801
#ifdef Py_TRACE_REFS
2802
    if (Py_REFCNT(op) < 0) {
2803
        _PyObject_ASSERT_FAILED_MSG(op, "negative refcnt");
2804
    }
2805
2806
    PyInterpreterState *interp = _PyInterpreterState_GET();
2807
2808
#ifdef SLOW_UNREF_CHECK
2809
    if (!_PyRefchain_Get(interp, op)) {
2810
        /* Not found */
2811
        _PyObject_ASSERT_FAILED_MSG(op,
2812
                                    "object not found in the objects list");
2813
    }
2814
#endif
2815
2816
    _PyRefchain_Remove(interp, op);
2817
#endif
2818
0
}
2819
2820
2821
#ifdef Py_TRACE_REFS
2822
static int
2823
_Py_PrintReference(_Py_hashtable_t *ht,
2824
                   const void *key, const void *value,
2825
                   void *user_data)
2826
{
2827
    PyObject *op = (PyObject*)key;
2828
    FILE *fp = (FILE *)user_data;
2829
    fprintf(fp, "%p [%zd] ", (void *)op, Py_REFCNT(op));
2830
    if (PyObject_Print(op, fp, 0) != 0) {
2831
        PyErr_Clear();
2832
    }
2833
    putc('\n', fp);
2834
    return 0;
2835
}
2836
2837
2838
/* Print all live objects.  Because PyObject_Print is called, the
2839
 * interpreter must be in a healthy state.
2840
 */
2841
void
2842
_Py_PrintReferences(PyInterpreterState *interp, FILE *fp)
2843
{
2844
    if (interp == NULL) {
2845
        interp = _PyInterpreterState_Main();
2846
    }
2847
    fprintf(fp, "Remaining objects:\n");
2848
    _Py_hashtable_foreach(REFCHAIN(interp), _Py_PrintReference, fp);
2849
}
2850
2851
2852
static int
2853
_Py_PrintReferenceAddress(_Py_hashtable_t *ht,
2854
                          const void *key, const void *value,
2855
                          void *user_data)
2856
{
2857
    PyObject *op = (PyObject*)key;
2858
    FILE *fp = (FILE *)user_data;
2859
    fprintf(fp, "%p [%zd] %s\n",
2860
            (void *)op, Py_REFCNT(op), Py_TYPE(op)->tp_name);
2861
    return 0;
2862
}
2863
2864
2865
/* Print the addresses of all live objects.  Unlike _Py_PrintReferences, this
2866
 * doesn't make any calls to the Python C API, so is always safe to call.
2867
 */
2868
// XXX This function is not safe to use if the interpreter has been
2869
// freed or is in an unhealthy state (e.g. late in finalization).
2870
// The call in Py_FinalizeEx() is okay since the main interpreter
2871
// is statically allocated.
2872
void
2873
_Py_PrintReferenceAddresses(PyInterpreterState *interp, FILE *fp)
2874
{
2875
    fprintf(fp, "Remaining object addresses:\n");
2876
    _Py_hashtable_foreach(REFCHAIN(interp), _Py_PrintReferenceAddress, fp);
2877
}
2878
2879
2880
typedef struct {
2881
    PyObject *self;
2882
    PyObject *args;
2883
    PyObject *list;
2884
    PyObject *type;
2885
    Py_ssize_t limit;
2886
} _Py_GetObjectsData;
2887
2888
enum {
2889
    _PY_GETOBJECTS_IGNORE = 0,
2890
    _PY_GETOBJECTS_ERROR = 1,
2891
    _PY_GETOBJECTS_STOP = 2,
2892
};
2893
2894
static int
2895
_Py_GetObject(_Py_hashtable_t *ht,
2896
              const void *key, const void *value,
2897
              void *user_data)
2898
{
2899
    PyObject *op = (PyObject *)key;
2900
    _Py_GetObjectsData *data = user_data;
2901
    if (data->limit > 0) {
2902
        if (PyList_GET_SIZE(data->list) >= data->limit) {
2903
            return _PY_GETOBJECTS_STOP;
2904
        }
2905
    }
2906
2907
    if (op == data->self) {
2908
        return _PY_GETOBJECTS_IGNORE;
2909
    }
2910
    if (op == data->args) {
2911
        return _PY_GETOBJECTS_IGNORE;
2912
    }
2913
    if (op == data->list) {
2914
        return _PY_GETOBJECTS_IGNORE;
2915
    }
2916
    if (data->type != NULL) {
2917
        if (op == data->type) {
2918
            return _PY_GETOBJECTS_IGNORE;
2919
        }
2920
        if (!Py_IS_TYPE(op, (PyTypeObject *)data->type)) {
2921
            return _PY_GETOBJECTS_IGNORE;
2922
        }
2923
    }
2924
2925
    if (PyList_Append(data->list, op) < 0) {
2926
        return _PY_GETOBJECTS_ERROR;
2927
    }
2928
    return 0;
2929
}
2930
2931
2932
/* The implementation of sys.getobjects(). */
2933
PyObject *
2934
_Py_GetObjects(PyObject *self, PyObject *args)
2935
{
2936
    Py_ssize_t limit;
2937
    PyObject *type = NULL;
2938
    if (!PyArg_ParseTuple(args, "n|O", &limit, &type)) {
2939
        return NULL;
2940
    }
2941
2942
    PyObject *list = PyList_New(0);
2943
    if (list == NULL) {
2944
        return NULL;
2945
    }
2946
2947
    _Py_GetObjectsData data = {
2948
        .self = self,
2949
        .args = args,
2950
        .list = list,
2951
        .type = type,
2952
        .limit = limit,
2953
    };
2954
    PyInterpreterState *interp = _PyInterpreterState_GET();
2955
    int res = _Py_hashtable_foreach(REFCHAIN(interp), _Py_GetObject, &data);
2956
    if (res == _PY_GETOBJECTS_ERROR) {
2957
        Py_DECREF(list);
2958
        return NULL;
2959
    }
2960
    return list;
2961
}
2962
2963
#undef REFCHAIN
2964
#undef REFCHAIN_VALUE
2965
2966
#endif  /* Py_TRACE_REFS */
2967
2968
2969
/* Hack to force loading of abstract.o */
2970
Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
2971
2972
2973
void
2974
_PyObject_DebugTypeStats(FILE *out)
2975
0
{
2976
0
    _PyDict_DebugMallocStats(out);
2977
0
    _PyFloat_DebugMallocStats(out);
2978
0
    _PyList_DebugMallocStats(out);
2979
0
    _PyTuple_DebugMallocStats(out);
2980
0
}
2981
2982
/* These methods are used to control infinite recursion in repr, str, print,
2983
   etc.  Container objects that may recursively contain themselves,
2984
   e.g. builtin dictionaries and lists, should use Py_ReprEnter() and
2985
   Py_ReprLeave() to avoid infinite recursion.
2986
2987
   Py_ReprEnter() returns 0 the first time it is called for a particular
2988
   object and 1 every time thereafter.  It returns -1 if an exception
2989
   occurred.  Py_ReprLeave() has no return value.
2990
2991
   See dictobject.c and listobject.c for examples of use.
2992
*/
2993
2994
int
2995
Py_ReprEnter(PyObject *obj)
2996
4.01M
{
2997
4.01M
    PyObject *dict;
2998
4.01M
    PyObject *list;
2999
4.01M
    Py_ssize_t i;
3000
3001
4.01M
    dict = PyThreadState_GetDict();
3002
    /* Ignore a missing thread-state, so that this function can be called
3003
       early on startup. */
3004
4.01M
    if (dict == NULL)
3005
0
        return 0;
3006
4.01M
    list = PyDict_GetItemWithError(dict, &_Py_ID(Py_Repr));
3007
4.01M
    if (list == NULL) {
3008
2
        if (PyErr_Occurred()) {
3009
0
            return -1;
3010
0
        }
3011
2
        list = PyList_New(0);
3012
2
        if (list == NULL)
3013
0
            return -1;
3014
2
        if (PyDict_SetItem(dict, &_Py_ID(Py_Repr), list) < 0)
3015
0
            return -1;
3016
2
        Py_DECREF(list);
3017
2
    }
3018
4.01M
    i = PyList_GET_SIZE(list);
3019
86.8M
    while (--i >= 0) {
3020
82.7M
        if (PyList_GET_ITEM(list, i) == obj)
3021
0
            return 1;
3022
82.7M
    }
3023
4.01M
    if (PyList_Append(list, obj) < 0)
3024
0
        return -1;
3025
4.01M
    return 0;
3026
4.01M
}
3027
3028
void
3029
Py_ReprLeave(PyObject *obj)
3030
4.01M
{
3031
4.01M
    PyObject *dict;
3032
4.01M
    PyObject *list;
3033
4.01M
    Py_ssize_t i;
3034
3035
4.01M
    PyObject *exc = PyErr_GetRaisedException();
3036
3037
4.01M
    dict = PyThreadState_GetDict();
3038
4.01M
    if (dict == NULL)
3039
0
        goto finally;
3040
3041
4.01M
    list = PyDict_GetItemWithError(dict, &_Py_ID(Py_Repr));
3042
4.01M
    if (list == NULL || !PyList_Check(list))
3043
0
        goto finally;
3044
3045
4.01M
    i = PyList_GET_SIZE(list);
3046
    /* Count backwards because we always expect obj to be list[-1] */
3047
4.01M
    while (--i >= 0) {
3048
4.01M
        if (PyList_GET_ITEM(list, i) == obj) {
3049
4.01M
            PyList_SetSlice(list, i, i + 1, NULL);
3050
4.01M
            break;
3051
4.01M
        }
3052
4.01M
    }
3053
3054
4.01M
finally:
3055
    /* ignore exceptions because there is no way to report them. */
3056
4.01M
    PyErr_SetRaisedException(exc);
3057
4.01M
}
3058
3059
/* Trashcan support. */
3060
3061
/* Add op to the tstate->delete_later list.  Called when the current
3062
 * call-stack depth gets large.  op must be a gc'ed object, with refcount 0.
3063
 *  Py_DECREF must already have been called on it.
3064
 */
3065
void
3066
_PyTrash_thread_deposit_object(PyThreadState *tstate, PyObject *op)
3067
7.22k
{
3068
7.22k
    _PyObject_ASSERT(op, Py_REFCNT(op) == 0);
3069
7.22k
    PyTypeObject *tp = Py_TYPE(op);
3070
7.22k
    assert(tp->tp_flags & Py_TPFLAGS_HAVE_GC);
3071
7.22k
    int tracked = 0;
3072
7.22k
    if (tp->tp_is_gc == NULL || tp->tp_is_gc(op)) {
3073
7.22k
        tracked = _PyObject_GC_IS_TRACKED(op);
3074
7.22k
        if (tracked) {
3075
7.22k
            _PyObject_GC_UNTRACK(op);
3076
7.22k
        }
3077
7.22k
    }
3078
7.22k
    uintptr_t tagged_ptr = ((uintptr_t)tstate->delete_later) | tracked;
3079
#ifdef Py_GIL_DISABLED
3080
    op->ob_tid = tagged_ptr;
3081
#else
3082
7.22k
    _Py_AS_GC(op)->_gc_next = tagged_ptr;
3083
7.22k
#endif
3084
7.22k
    tstate->delete_later = op;
3085
7.22k
}
3086
3087
/* Deallocate all the objects in the tstate->delete_later list.
3088
 * Called when the call-stack unwinds again. */
3089
void
3090
_PyTrash_thread_destroy_chain(PyThreadState *tstate)
3091
56
{
3092
7.28k
    while (tstate->delete_later) {
3093
7.22k
        PyObject *op = tstate->delete_later;
3094
7.22k
        destructor dealloc = Py_TYPE(op)->tp_dealloc;
3095
3096
#ifdef Py_GIL_DISABLED
3097
        uintptr_t tagged_ptr = op->ob_tid;
3098
        op->ob_tid = 0;
3099
        _Py_atomic_store_ssize_relaxed(&op->ob_ref_shared, _Py_REF_MERGED);
3100
#else
3101
7.22k
        uintptr_t tagged_ptr = _Py_AS_GC(op)->_gc_next;
3102
7.22k
        _Py_AS_GC(op)->_gc_next = 0;
3103
7.22k
#endif
3104
7.22k
        tstate->delete_later = (PyObject *)(tagged_ptr & ~1);
3105
7.22k
        if (tagged_ptr & 1) {
3106
7.22k
            _PyObject_GC_TRACK(op);
3107
7.22k
        }
3108
        /* Call the deallocator directly.  This used to try to
3109
         * fool Py_DECREF into calling it indirectly, but
3110
         * Py_DECREF was already called on this object, and in
3111
         * assorted non-release builds calling Py_DECREF again ends
3112
         * up distorting allocation statistics.
3113
         */
3114
7.22k
        _PyObject_ASSERT(op, Py_REFCNT(op) == 0);
3115
7.22k
        (*dealloc)(op);
3116
7.22k
    }
3117
56
}
3118
3119
void _Py_NO_RETURN
3120
_PyObject_AssertFailed(PyObject *obj, const char *expr, const char *msg,
3121
                       const char *file, int line, const char *function)
3122
0
{
3123
0
    fprintf(stderr, "%s:%d: ", file, line);
3124
0
    if (function) {
3125
0
        fprintf(stderr, "%s: ", function);
3126
0
    }
3127
0
    fflush(stderr);
3128
3129
0
    if (expr) {
3130
0
        fprintf(stderr, "Assertion \"%s\" failed", expr);
3131
0
    }
3132
0
    else {
3133
0
        fprintf(stderr, "Assertion failed");
3134
0
    }
3135
0
    fflush(stderr);
3136
3137
0
    if (msg) {
3138
0
        fprintf(stderr, ": %s", msg);
3139
0
    }
3140
0
    fprintf(stderr, "\n");
3141
0
    fflush(stderr);
3142
3143
0
    if (_PyObject_IsFreed(obj)) {
3144
        /* It seems like the object memory has been freed:
3145
           don't access it to prevent a segmentation fault. */
3146
0
        fprintf(stderr, "<object at %p is freed>\n", obj);
3147
0
        fflush(stderr);
3148
0
    }
3149
0
    else {
3150
        /* Display the traceback where the object has been allocated.
3151
           Do it before dumping repr(obj), since repr() is more likely
3152
           to crash than dumping the traceback. */
3153
0
        PyTypeObject *type = Py_TYPE(obj);
3154
0
        const size_t presize = _PyType_PreHeaderSize(type);
3155
0
        void *ptr = (void *)((char *)obj - presize);
3156
0
        _PyMem_DumpTraceback(fileno(stderr), ptr);
3157
3158
        /* This might succeed or fail, but we're about to abort, so at least
3159
           try to provide any extra info we can: */
3160
0
        PyUnstable_Object_Dump(obj);
3161
3162
0
        fprintf(stderr, "\n");
3163
0
        fflush(stderr);
3164
0
    }
3165
3166
0
    Py_FatalError("_PyObject_AssertFailed");
3167
0
}
3168
3169
3170
/*
3171
When deallocating a container object, it's possible to trigger an unbounded
3172
chain of deallocations, as each Py_DECREF in turn drops the refcount on "the
3173
next" object in the chain to 0.  This can easily lead to stack overflows.
3174
To avoid that, if the C stack is nearing its limit, instead of calling
3175
dealloc on the object, it is added to a queue to be freed later when the
3176
stack is shallower */
3177
void
3178
_Py_Dealloc(PyObject *op)
3179
3.80G
{
3180
3.80G
    PyTypeObject *type = Py_TYPE(op);
3181
3.80G
    unsigned long gc_flag = type->tp_flags & Py_TPFLAGS_HAVE_GC;
3182
3.80G
    destructor dealloc = type->tp_dealloc;
3183
3.80G
    PyThreadState *tstate = _PyThreadState_GET();
3184
3.80G
    intptr_t margin = _Py_RecursionLimit_GetMargin(tstate);
3185
3.80G
    if (margin < 2 && gc_flag) {
3186
7.22k
        _PyTrash_thread_deposit_object(tstate, (PyObject *)op);
3187
7.22k
        return;
3188
7.22k
    }
3189
#ifdef Py_DEBUG
3190
#if !defined(Py_GIL_DISABLED) && !defined(Py_STACKREF_DEBUG)
3191
    /* This assertion doesn't hold for the free-threading build, as
3192
     * PyStackRef_CLOSE_SPECIALIZED is not implemented */
3193
    assert(tstate->current_frame == NULL || tstate->current_frame->stackpointer != NULL);
3194
#endif
3195
    PyObject *old_exc = tstate != NULL ? tstate->current_exception : NULL;
3196
    // Keep the old exception type alive to prevent undefined behavior
3197
    // on (tstate->curexc_type != old_exc_type) below
3198
    Py_XINCREF(old_exc);
3199
    // Make sure that type->tp_name remains valid
3200
    Py_INCREF(type);
3201
#endif
3202
3203
#ifdef Py_TRACE_REFS
3204
    _Py_ForgetReference(op);
3205
#endif
3206
3.80G
    _PyReftracerTrack(op, PyRefTracer_DESTROY);
3207
3.80G
    (*dealloc)(op);
3208
3209
#ifdef Py_DEBUG
3210
    // gh-89373: The tp_dealloc function must leave the current exception
3211
    // unchanged.
3212
    if (tstate != NULL && tstate->current_exception != old_exc) {
3213
        const char *err;
3214
        if (old_exc == NULL) {
3215
            err = "Deallocator of type '%s' raised an exception";
3216
        }
3217
        else if (tstate->current_exception == NULL) {
3218
            err = "Deallocator of type '%s' cleared the current exception";
3219
        }
3220
        else {
3221
            // It can happen if dealloc() normalized the current exception.
3222
            // A deallocator function must not change the current exception,
3223
            // not even normalize it.
3224
            err = "Deallocator of type '%s' overrode the current exception";
3225
        }
3226
        _Py_FatalErrorFormat(__func__, err, type->tp_name);
3227
    }
3228
    Py_XDECREF(old_exc);
3229
    Py_DECREF(type);
3230
#endif
3231
3.80G
    if (tstate->delete_later && margin >= 4 && gc_flag) {
3232
56
        _PyTrash_thread_destroy_chain(tstate);
3233
56
    }
3234
3.80G
}
3235
3236
3237
PyObject **
3238
PyObject_GET_WEAKREFS_LISTPTR(PyObject *op)
3239
0
{
3240
0
    return _PyObject_GET_WEAKREFS_LISTPTR(op);
3241
0
}
3242
3243
3244
#undef Py_NewRef
3245
#undef Py_XNewRef
3246
3247
// Export Py_NewRef() and Py_XNewRef() as regular functions for the stable ABI.
3248
PyObject*
3249
Py_NewRef(PyObject *obj)
3250
0
{
3251
0
    return _Py_NewRef(obj);
3252
0
}
3253
3254
PyObject*
3255
Py_XNewRef(PyObject *obj)
3256
0
{
3257
0
    return _Py_XNewRef(obj);
3258
0
}
3259
3260
#undef Py_Is
3261
#undef Py_IsNone
3262
#undef Py_IsTrue
3263
#undef Py_IsFalse
3264
3265
// Export Py_Is(), Py_IsNone(), Py_IsTrue(), Py_IsFalse() as regular functions
3266
// for the stable ABI.
3267
int Py_Is(PyObject *x, PyObject *y)
3268
0
{
3269
0
    return (x == y);
3270
0
}
3271
3272
int Py_IsNone(PyObject *x)
3273
0
{
3274
0
    return Py_Is(x, Py_None);
3275
0
}
3276
3277
int Py_IsTrue(PyObject *x)
3278
0
{
3279
0
    return Py_Is(x, Py_True);
3280
0
}
3281
3282
int Py_IsFalse(PyObject *x)
3283
0
{
3284
0
    return Py_Is(x, Py_False);
3285
0
}
3286
3287
3288
// Py_SET_REFCNT() implementation for stable ABI
3289
void
3290
_Py_SetRefcnt(PyObject *ob, Py_ssize_t refcnt)
3291
0
{
3292
0
    Py_SET_REFCNT(ob, refcnt);
3293
0
}
3294
3295
0
int PyRefTracer_SetTracer(PyRefTracer tracer, void *data) {
3296
0
    _Py_AssertHoldsTstate();
3297
3298
0
    _PyEval_StopTheWorldAll(&_PyRuntime);
3299
0
    if (_PyRuntime.ref_tracer.tracer_func != NULL) {
3300
0
        _PyReftracerTrack(NULL, PyRefTracer_TRACKER_REMOVED);
3301
0
        if (PyErr_Occurred()) {
3302
0
            _PyEval_StartTheWorldAll(&_PyRuntime);
3303
0
            return -1;
3304
0
        }
3305
0
    }
3306
0
    _PyRuntime.ref_tracer.tracer_func = tracer;
3307
0
    _PyRuntime.ref_tracer.tracer_data = data;
3308
0
    _PyEval_StartTheWorldAll(&_PyRuntime);
3309
0
    return 0;
3310
0
}
3311
3312
0
PyRefTracer PyRefTracer_GetTracer(void** data) {
3313
0
    _Py_AssertHoldsTstate();
3314
0
    if (data != NULL) {
3315
0
        *data = _PyRuntime.ref_tracer.tracer_data;
3316
0
    }
3317
0
    return _PyRuntime.ref_tracer.tracer_func;
3318
0
}
3319
3320
3321
3322
static PyObject* constants[] = {
3323
    &_Py_NoneStruct,                   // Py_CONSTANT_NONE
3324
    (PyObject*)(&_Py_FalseStruct),     // Py_CONSTANT_FALSE
3325
    (PyObject*)(&_Py_TrueStruct),      // Py_CONSTANT_TRUE
3326
    &_Py_EllipsisObject,               // Py_CONSTANT_ELLIPSIS
3327
    &_Py_NotImplementedStruct,         // Py_CONSTANT_NOT_IMPLEMENTED
3328
    NULL,  // Py_CONSTANT_ZERO
3329
    NULL,  // Py_CONSTANT_ONE
3330
    NULL,  // Py_CONSTANT_EMPTY_STR
3331
    NULL,  // Py_CONSTANT_EMPTY_BYTES
3332
    NULL,  // Py_CONSTANT_EMPTY_TUPLE
3333
};
3334
3335
void
3336
_Py_GetConstant_Init(void)
3337
28
{
3338
28
    constants[Py_CONSTANT_ZERO] = _PyLong_GetZero();
3339
28
    constants[Py_CONSTANT_ONE] = _PyLong_GetOne();
3340
28
    constants[Py_CONSTANT_EMPTY_STR] = PyUnicode_New(0, 0);
3341
28
    constants[Py_CONSTANT_EMPTY_BYTES] = PyBytes_FromStringAndSize(NULL, 0);
3342
28
    constants[Py_CONSTANT_EMPTY_TUPLE] = PyTuple_New(0);
3343
#ifndef NDEBUG
3344
    for (size_t i=0; i < Py_ARRAY_LENGTH(constants); i++) {
3345
        assert(constants[i] != NULL);
3346
        assert(_Py_IsImmortal(constants[i]));
3347
    }
3348
#endif
3349
28
}
3350
3351
PyObject*
3352
Py_GetConstant(unsigned int constant_id)
3353
9.48M
{
3354
9.48M
    if (constant_id < Py_ARRAY_LENGTH(constants)) {
3355
9.48M
        return constants[constant_id];
3356
9.48M
    }
3357
0
    else {
3358
0
        PyErr_BadInternalCall();
3359
0
        return NULL;
3360
0
    }
3361
9.48M
}
3362
3363
3364
PyObject*
3365
Py_GetConstantBorrowed(unsigned int constant_id)
3366
0
{
3367
    // All constants are immortal
3368
0
    return Py_GetConstant(constant_id);
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
}
3387
3388
int
3389
_PyObject_VisitType(PyObject *op, visitproc visit, void *arg)
3390
3.37k
{
3391
3.37k
    assert(op != NULL);
3392
3.37k
    PyTypeObject *tp = Py_TYPE(op);
3393
3.37k
    _PyObject_ASSERT((PyObject *)tp, PyType_HasFeature(tp, Py_TPFLAGS_HEAPTYPE));
3394
3.37k
    Py_VISIT(tp);
3395
3.37k
    return 0;
3396
3.37k
}
3397
3398
// Implementations for the stable ABI
3399
// Keep these at the end.
3400
#undef Py_TYPE
3401
#undef Py_REFCNT
3402
#undef Py_SIZE
3403
#undef Py_IS_TYPE
3404
#undef Py_SET_SIZE
3405
0
PyTypeObject* Py_TYPE(PyObject *ob) { return _Py_TYPE_impl(ob); }
3406
0
Py_ssize_t Py_REFCNT(PyObject *ob) { return _Py_REFCNT(ob); }
3407
0
Py_ssize_t Py_SIZE(PyObject *o) { return _Py_SIZE_impl(o); }
3408
0
int Py_IS_TYPE(PyObject *o, PyTypeObject *t) { return _Py_IS_TYPE_impl(o, t); }
3409
0
void Py_SET_SIZE(PyVarObject *o, Py_ssize_t s) { _Py_SET_SIZE_impl(o, s); }