Coverage Report

Created: 2026-06-09 06:53

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