Coverage Report

Created: 2026-04-12 06:54

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.96M
{
556
2.96M
    PyObject *op = (PyObject *) PyObject_Malloc(_PyObject_SIZE(tp));
557
2.96M
    if (op == NULL) {
558
0
        return PyErr_NoMemory();
559
0
    }
560
2.96M
    _PyObject_Init(op, tp);
561
2.96M
    return op;
562
2.96M
}
563
564
PyVarObject *
565
_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
566
184k
{
567
184k
    PyVarObject *op;
568
184k
    const size_t size = _PyObject_VAR_SIZE(tp, nitems);
569
184k
    op = (PyVarObject *) PyObject_Malloc(size);
570
184k
    if (op == NULL) {
571
0
        return (PyVarObject *)PyErr_NoMemory();
572
0
    }
573
184k
    _PyObject_InitVar(op, tp, nitems);
574
184k
    return op;
575
184k
}
576
577
void
578
PyObject_CallFinalizer(PyObject *self)
579
23.7M
{
580
23.7M
    PyTypeObject *tp = Py_TYPE(self);
581
582
23.7M
    if (tp->tp_finalize == NULL)
583
0
        return;
584
    /* tp_finalize should only be called once. */
585
23.7M
    if (_PyType_IS_GC(tp) && _PyGC_FINALIZED(self))
586
54.3k
        return;
587
588
23.7M
    tp->tp_finalize(self);
589
23.7M
    if (_PyType_IS_GC(tp)) {
590
23.5M
        _PyGC_SET_FINALIZED(self);
591
23.5M
    }
592
23.7M
}
593
594
int
595
PyObject_CallFinalizerFromDealloc(PyObject *self)
596
23.7M
{
597
23.7M
    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
23.7M
    _PyObject_ResurrectStart(self);
605
606
23.7M
    PyObject_CallFinalizer(self);
607
608
23.7M
    _PyObject_ASSERT_WITH_MSG(self,
609
23.7M
                              Py_REFCNT(self) > 0,
610
23.7M
                              "refcount is too small");
611
612
23.7M
    _PyObject_ASSERT(self,
613
23.7M
                    (!_PyType_IS_GC(Py_TYPE(self))
614
23.7M
                    || _PyObject_GC_IS_TRACKED(self)));
615
616
    /* Undo the temporary resurrection; can't use DECREF here, it would
617
     * cause a recursive call. */
618
23.7M
    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
23.7M
    return 0;
630
23.7M
}
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
16.9M
{
761
16.9M
    PyObject *res;
762
16.9M
    if (PyErr_CheckSignals())
763
0
        return NULL;
764
16.9M
    if (v == NULL)
765
0
        return PyUnicode_FromString("<NULL>");
766
16.9M
    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
16.9M
    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
16.9M
    if (_Py_EnterRecursiveCallTstate(tstate,
781
16.9M
                                     " while getting the repr of an object")) {
782
0
        return NULL;
783
0
    }
784
16.9M
    res = (*Py_TYPE(v)->tp_repr)(v);
785
16.9M
    _Py_LeaveRecursiveCallTstate(tstate);
786
787
16.9M
    if (res == NULL) {
788
2
        return NULL;
789
2
    }
790
16.9M
    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
16.9M
    return res;
797
16.9M
}
798
799
PyObject *
800
PyObject_Str(PyObject *v)
801
48.7M
{
802
48.7M
    PyObject *res;
803
48.7M
    if (PyErr_CheckSignals())
804
0
        return NULL;
805
48.7M
    if (v == NULL)
806
0
        return PyUnicode_FromString("<NULL>");
807
48.7M
    if (PyUnicode_CheckExact(v)) {
808
37.0M
        return Py_NewRef(v);
809
37.0M
    }
810
11.6M
    if (Py_TYPE(v)->tp_str == NULL)
811
0
        return PyObject_Repr(v);
812
813
11.6M
    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
11.6M
    if (_Py_EnterRecursiveCallTstate(tstate, " while getting the str of an object")) {
824
0
        return NULL;
825
0
    }
826
11.6M
    res = (*Py_TYPE(v)->tp_str)(v);
827
11.6M
    _Py_LeaveRecursiveCallTstate(tstate);
828
829
11.6M
    if (res == NULL) {
830
5.64k
        return NULL;
831
5.64k
    }
832
11.6M
    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
11.6M
    assert(_PyUnicode_CheckConsistency(res, 1));
839
11.6M
    return res;
840
11.6M
}
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
0
{
905
0
    void *ptr;
906
0
    while ((ptr = _PyFreeList_PopNoStats(freelist)) != NULL) {
907
0
        dofree(ptr);
908
0
    }
909
0
    assert(freelist->size == 0 || freelist->size == -1);
910
0
    assert(freelist->freelist == NULL);
911
0
    if (is_finalization) {
912
0
        freelist->size = -1;
913
0
    }
914
0
}
915
916
static void
917
free_object(void *obj)
918
0
{
919
0
    PyObject *op = (PyObject *)obj;
920
0
    PyTypeObject *tp = Py_TYPE(op);
921
0
    tp->tp_free(op);
922
0
    Py_DECREF(tp);
923
0
}
924
925
void
926
_PyObject_ClearFreeLists(struct _Py_freelists *freelists, int is_finalization)
927
0
{
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
0
    clear_freelist(&freelists->floats, is_finalization, free_object);
931
0
    clear_freelist(&freelists->complexes, is_finalization, free_object);
932
0
    for (Py_ssize_t i = 0; i < PyTuple_MAXSAVESIZE; i++) {
933
0
        clear_freelist(&freelists->tuples[i], is_finalization, free_object);
934
0
    }
935
0
    clear_freelist(&freelists->lists, is_finalization, free_object);
936
0
    clear_freelist(&freelists->list_iters, is_finalization, free_object);
937
0
    clear_freelist(&freelists->tuple_iters, is_finalization, free_object);
938
0
    clear_freelist(&freelists->dicts, is_finalization, free_object);
939
0
    clear_freelist(&freelists->dictkeys, is_finalization, PyMem_Free);
940
0
    clear_freelist(&freelists->slices, is_finalization, free_object);
941
0
    clear_freelist(&freelists->ranges, is_finalization, free_object);
942
0
    clear_freelist(&freelists->range_iters, is_finalization, free_object);
943
0
    clear_freelist(&freelists->contexts, is_finalization, free_object);
944
0
    clear_freelist(&freelists->async_gens, is_finalization, free_object);
945
0
    clear_freelist(&freelists->async_gen_asends, is_finalization, free_object);
946
0
    clear_freelist(&freelists->futureiters, is_finalization, free_object);
947
0
    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
0
    clear_freelist(&freelists->unicode_writers, is_finalization, PyMem_Free);
953
0
    clear_freelist(&freelists->bytes_writers, is_finalization, PyMem_Free);
954
0
    clear_freelist(&freelists->ints, is_finalization, free_object);
955
0
    clear_freelist(&freelists->pycfunctionobject, is_finalization, PyObject_GC_Del);
956
0
    clear_freelist(&freelists->pycmethodobject, is_finalization, PyObject_GC_Del);
957
0
    clear_freelist(&freelists->pymethodobjects, is_finalization, free_object);
958
0
}
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
238M
{
1050
238M
    richcmpfunc f;
1051
238M
    PyObject *res;
1052
238M
    int checked_reverse_op = 0;
1053
1054
238M
    if (!Py_IS_TYPE(v, Py_TYPE(w)) &&
1055
15.5M
        PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v)) &&
1056
337k
        (f = Py_TYPE(w)->tp_richcompare) != NULL) {
1057
337k
        checked_reverse_op = 1;
1058
337k
        res = (*f)(w, v, _Py_SwappedOp[op]);
1059
337k
        if (res != Py_NotImplemented)
1060
306k
            return res;
1061
31.3k
        Py_DECREF(res);
1062
31.3k
    }
1063
238M
    if ((f = Py_TYPE(v)->tp_richcompare) != NULL) {
1064
238M
        res = (*f)(v, w, op);
1065
238M
        if (res != Py_NotImplemented)
1066
228M
            return res;
1067
9.36M
        Py_DECREF(res);
1068
9.36M
    }
1069
9.36M
    if (!checked_reverse_op && (f = Py_TYPE(w)->tp_richcompare) != NULL) {
1070
9.33M
        res = (*f)(w, v, _Py_SwappedOp[op]);
1071
9.33M
        if (res != Py_NotImplemented)
1072
55.9k
            return res;
1073
9.27M
        Py_DECREF(res);
1074
9.27M
    }
1075
    /* If neither object implements it, provide a sensible default
1076
       for == and !=, but raise an exception for ordering. */
1077
9.31M
    switch (op) {
1078
9.30M
    case Py_EQ:
1079
9.30M
        res = (v == w) ? Py_True : Py_False;
1080
9.30M
        break;
1081
1.23k
    case Py_NE:
1082
1.23k
        res = (v != w) ? Py_True : Py_False;
1083
1.23k
        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.31M
    }
1092
9.31M
    return Py_NewRef(res);
1093
9.31M
}
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
238M
{
1101
238M
    PyThreadState *tstate = _PyThreadState_GET();
1102
1103
238M
    assert(Py_LT <= op && op <= Py_GE);
1104
238M
    if (v == NULL || w == NULL) {
1105
0
        if (!_PyErr_Occurred(tstate)) {
1106
0
            PyErr_BadInternalCall();
1107
0
        }
1108
0
        return NULL;
1109
0
    }
1110
238M
    if (_Py_EnterRecursiveCallTstate(tstate, " in comparison")) {
1111
0
        return NULL;
1112
0
    }
1113
238M
    PyObject *res = do_richcompare(tstate, v, w, op);
1114
238M
    _Py_LeaveRecursiveCallTstate(tstate);
1115
238M
    return res;
1116
238M
}
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
242M
{
1123
242M
    PyObject *res;
1124
242M
    int ok;
1125
1126
    /* Quick result when objects are the same.
1127
       Guarantees that identity implies equality. */
1128
242M
    if (v == w) {
1129
43.8M
        if (op == Py_EQ)
1130
40.6M
            return 1;
1131
3.17M
        else if (op == Py_NE)
1132
0
            return 0;
1133
43.8M
    }
1134
1135
201M
    res = PyObject_RichCompare(v, w, op);
1136
201M
    if (res == NULL)
1137
0
        return -1;
1138
201M
    if (PyBool_Check(res)) {
1139
201M
        ok = (res == Py_True);
1140
201M
        assert(_Py_IsImmortal(res));
1141
201M
    }
1142
0
    else {
1143
0
        ok = PyObject_IsTrue(res);
1144
0
        Py_DECREF(res);
1145
0
    }
1146
201M
    return ok;
1147
201M
}
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
1.47G
{
1160
1.47G
    PyTypeObject *tp = Py_TYPE(v);
1161
1.47G
    if (tp->tp_hash != NULL)
1162
1.47G
        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
559k
{
1181
559k
    PyObject *w, *res;
1182
1183
559k
    if (Py_TYPE(v)->tp_getattr != NULL)
1184
0
        return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
1185
559k
    w = PyUnicode_FromString(name);
1186
559k
    if (w == NULL)
1187
0
        return NULL;
1188
559k
    res = PyObject_GetAttr(v, w);
1189
559k
    Py_DECREF(w);
1190
559k
    return res;
1191
559k
}
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
80.1k
{
1220
80.1k
    PyThreadState *tstate = _PyThreadState_GET();
1221
80.1k
    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
80.1k
    if (Py_TYPE(v)->tp_setattr != NULL) {
1231
0
        return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
1232
0
    }
1233
1234
80.1k
    PyObject *s = PyUnicode_InternFromString(name);
1235
80.1k
    if (s == NULL) {
1236
0
        return -1;
1237
0
    }
1238
1239
80.1k
    int res = PyObject_SetAttr(v, s, w);
1240
80.1k
    Py_DECREF(s);
1241
80.1k
    return res;
1242
80.1k
}
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
31.7k
{
1253
31.7k
    int res;
1254
31.7k
    PyObject* isabstract;
1255
1256
31.7k
    if (obj == NULL)
1257
566
        return 0;
1258
1259
31.1k
    res = PyObject_GetOptionalAttr(obj, &_Py_ID(__isabstractmethod__), &isabstract);
1260
31.1k
    if (res > 0) {
1261
4.13k
        res = PyObject_IsTrue(isabstract);
1262
4.13k
        Py_DECREF(isabstract);
1263
4.13k
    }
1264
31.1k
    return res;
1265
31.7k
}
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.65M
{
1284
5.65M
    assert(PyErr_Occurred());
1285
5.65M
    if (!PyErr_ExceptionMatches(PyExc_AttributeError)){
1286
2.99k
        return 0;
1287
2.99k
    }
1288
    // Intercept AttributeError exceptions and augment them to offer suggestions later.
1289
5.65M
    PyObject *exc = PyErr_GetRaisedException();
1290
5.65M
    if (!PyErr_GivenExceptionMatches(exc, PyExc_AttributeError)) {
1291
0
        goto restore;
1292
0
    }
1293
5.65M
    PyAttributeErrorObject* the_exc = (PyAttributeErrorObject*) exc;
1294
    // Check if this exception was already augmented
1295
5.65M
    if (the_exc->name || the_exc->obj) {
1296
2.34M
        goto restore;
1297
2.34M
    }
1298
    // Augment the exception with the name and object
1299
3.30M
    if (PyObject_SetAttr(exc, &_Py_ID(name), name) ||
1300
3.30M
        PyObject_SetAttr(exc, &_Py_ID(obj), v)) {
1301
0
        Py_DECREF(exc);
1302
0
        return 1;
1303
0
    }
1304
5.65M
restore:
1305
5.65M
    PyErr_SetRaisedException(exc);
1306
5.65M
    return 0;
1307
3.30M
}
1308
1309
PyObject *
1310
PyObject_GetAttr(PyObject *v, PyObject *name)
1311
63.0M
{
1312
63.0M
    PyTypeObject *tp = Py_TYPE(v);
1313
63.0M
    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
63.0M
    PyObject* result = NULL;
1321
63.0M
    if (tp->tp_getattro != NULL) {
1322
63.0M
        result = (*tp->tp_getattro)(v, name);
1323
63.0M
    }
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
63.0M
    if (result == NULL) {
1338
2.19M
        _PyObject_SetAttributeErrorContext(v, name);
1339
2.19M
    }
1340
63.0M
    return result;
1341
63.0M
}
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
297M
{
1349
297M
    PyTypeObject *tp = Py_TYPE(v);
1350
297M
    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
297M
    if (tp->tp_getattro == _Py_type_getattro) {
1359
26.4M
        _PyStackRef result = _Py_type_getattro_stackref((PyTypeObject *)v, name, NULL);
1360
26.4M
        if (PyStackRef_IsNull(result)) {
1361
312
            _PyObject_SetAttributeErrorContext(v, name);
1362
312
        }
1363
26.4M
        return result;
1364
26.4M
    }
1365
1366
    /* Fall back to regular PyObject_GetAttr and convert to stackref */
1367
271M
    PyObject *result = NULL;
1368
271M
    if (tp->tp_getattro != NULL) {
1369
271M
        result = (*tp->tp_getattro)(v, name);
1370
271M
    }
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
271M
    if (result == NULL) {
1385
1.11M
        _PyObject_SetAttributeErrorContext(v, name);
1386
1.11M
        return PyStackRef_NULL;
1387
1.11M
    }
1388
270M
    return PyStackRef_FromPyObjectSteal(result);
1389
271M
}
1390
1391
int
1392
PyObject_GetOptionalAttr(PyObject *v, PyObject *name, PyObject **result)
1393
99.8M
{
1394
99.8M
    PyTypeObject *tp = Py_TYPE(v);
1395
1396
99.8M
    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
99.8M
    if (tp->tp_getattro == PyObject_GenericGetAttr) {
1405
88.5M
        *result = _PyObject_GenericGetAttrWithDict(v, name, NULL, 1);
1406
88.5M
        if (*result != NULL) {
1407
71.8M
            return 1;
1408
71.8M
        }
1409
16.6M
        if (PyErr_Occurred()) {
1410
42
            return -1;
1411
42
        }
1412
16.6M
        return 0;
1413
16.6M
    }
1414
11.3M
    if (tp->tp_getattro == _Py_type_getattro) {
1415
182k
        int suppress_missing_attribute_exception = 0;
1416
182k
        *result = _Py_type_getattro_impl((PyTypeObject*)v, name, &suppress_missing_attribute_exception);
1417
182k
        if (suppress_missing_attribute_exception) {
1418
            // return 0 without having to clear the exception
1419
11.6k
            return 0;
1420
11.6k
        }
1421
182k
    }
1422
11.1M
    else if (tp->tp_getattro == (getattrofunc)_Py_module_getattro) {
1423
        // optimization: suppress attribute error from module getattro method
1424
8.34M
        *result = _Py_module_getattro_impl((PyModuleObject*)v, name, 1);
1425
8.34M
        if (*result != NULL) {
1426
7.09M
            return 1;
1427
7.09M
        }
1428
1.25M
        if (PyErr_Occurred()) {
1429
0
            return -1;
1430
0
        }
1431
1.25M
        return 0;
1432
1.25M
    }
1433
2.82M
    else if (tp->tp_getattro != NULL) {
1434
2.82M
        *result = (*tp->tp_getattro)(v, name);
1435
2.82M
    }
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.99M
    if (*result != NULL) {
1450
2.98M
        return 1;
1451
2.98M
    }
1452
1.60k
    if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
1453
0
        return -1;
1454
0
    }
1455
1.60k
    PyErr_Clear();
1456
1.60k
    return 0;
1457
1.60k
}
1458
1459
int
1460
PyObject_GetOptionalAttrString(PyObject *obj, const char *name, PyObject **result)
1461
48
{
1462
48
    if (Py_TYPE(obj)->tp_getattr == NULL) {
1463
48
        PyObject *oname = PyUnicode_FromString(name);
1464
48
        if (oname == NULL) {
1465
0
            *result = NULL;
1466
0
            return -1;
1467
0
        }
1468
48
        int rc = PyObject_GetOptionalAttr(obj, oname, result);
1469
48
        Py_DECREF(oname);
1470
48
        return rc;
1471
48
    }
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
13.1M
{
1487
13.1M
    PyObject *res;
1488
13.1M
    int rc = PyObject_GetOptionalAttr(obj, name, &res);
1489
13.1M
    Py_XDECREF(res);
1490
13.1M
    return rc;
1491
13.1M
}
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
78.0M
{
1510
78.0M
    PyThreadState *tstate = _PyThreadState_GET();
1511
78.0M
    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
78.0M
    PyTypeObject *tp = Py_TYPE(v);
1521
78.0M
    int err;
1522
1523
78.0M
    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
78.0M
    Py_INCREF(name);
1530
1531
78.0M
    _PyUnicode_InternMortal(tstate->interp, &name);
1532
78.0M
    if (tp->tp_setattro != NULL) {
1533
78.0M
        err = (*tp->tp_setattro)(v, name, value);
1534
78.0M
        Py_DECREF(name);
1535
78.0M
        return err;
1536
78.0M
    }
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
379k
{
1569
379k
    return PyObject_SetAttr(v, name, NULL);
1570
379k
}
1571
1572
PyObject **
1573
_PyObject_ComputedDictPointer(PyObject *obj)
1574
201M
{
1575
201M
    PyTypeObject *tp = Py_TYPE(obj);
1576
201M
    assert((tp->tp_flags & Py_TPFLAGS_MANAGED_DICT) == 0);
1577
1578
201M
    Py_ssize_t dictoffset = tp->tp_dictoffset;
1579
201M
    if (dictoffset == 0) {
1580
64.4M
        return NULL;
1581
64.4M
    }
1582
1583
136M
    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
136M
    return (PyObject **) ((char *)obj + dictoffset);
1598
201M
}
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
17.5M
{
1627
17.5M
    return Py_NewRef(obj);
1628
17.5M
}
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
106M
{
1759
106M
    int meth_found = 0;
1760
106M
    PyObject *obj = PyStackRef_AsPyObjectBorrow(*self);
1761
1762
106M
    assert(PyStackRef_IsNull(*method));
1763
1764
106M
    PyTypeObject *tp = Py_TYPE(obj);
1765
106M
    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
106M
    if (tp->tp_getattro != PyObject_GenericGetAttr || !PyUnicode_CheckExact(name)) {
1773
36.4M
        PyObject *res = PyObject_GetAttr(obj, name);
1774
36.4M
        PyStackRef_CLEAR(*self);
1775
36.4M
        if (res != NULL) {
1776
36.4M
            *method = PyStackRef_FromPyObjectSteal(res);
1777
36.4M
            return 0;
1778
36.4M
        }
1779
2.10k
        return -1;
1780
36.4M
    }
1781
1782
70.1M
    _PyType_LookupStackRefAndVersion(tp, name, method);
1783
70.1M
    PyObject *descr = PyStackRef_AsPyObjectBorrow(*method);
1784
70.1M
    descrgetfunc f = NULL;
1785
70.1M
    if (descr != NULL) {
1786
70.1M
        if (_PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_METHOD_DESCRIPTOR)) {
1787
69.1M
            meth_found = 1;
1788
69.1M
        }
1789
976k
        else {
1790
976k
            f = Py_TYPE(descr)->tp_descr_get;
1791
976k
            if (f != NULL && PyDescr_IsData(descr)) {
1792
38.7k
                PyObject *value = f(descr, obj, (PyObject *)Py_TYPE(obj));
1793
38.7k
                PyStackRef_CLEAR(*method);
1794
38.7k
                PyStackRef_CLEAR(*self);
1795
38.7k
                if (value != NULL) {
1796
38.7k
                    *method = PyStackRef_FromPyObjectSteal(value);
1797
38.7k
                    return 0;
1798
38.7k
                }
1799
0
                return -1;
1800
38.7k
            }
1801
976k
        }
1802
70.1M
    }
1803
70.0M
    PyObject *dict, *attr;
1804
70.0M
    if ((tp->tp_flags & Py_TPFLAGS_INLINE_VALUES) &&
1805
28.5M
         _PyObject_TryGetInstanceAttribute(obj, name, &attr)) {
1806
1.29M
        if (attr != NULL) {
1807
274
            PyStackRef_XSETREF(*method, PyStackRef_FromPyObjectSteal(attr));
1808
274
            PyStackRef_CLEAR(*self);
1809
274
            return 0;
1810
274
        }
1811
1.29M
        dict = NULL;
1812
1.29M
    }
1813
68.7M
    else if ((tp->tp_flags & Py_TPFLAGS_MANAGED_DICT)) {
1814
30.2M
        dict = (PyObject *)_PyObject_GetManagedDict(obj);
1815
30.2M
    }
1816
38.5M
    else {
1817
38.5M
        PyObject **dictptr = _PyObject_ComputedDictPointer(obj);
1818
38.5M
        if (dictptr != NULL) {
1819
36.7M
            dict = FT_ATOMIC_LOAD_PTR_ACQUIRE(*dictptr);
1820
36.7M
        }
1821
1.78M
        else {
1822
1.78M
            dict = NULL;
1823
1.78M
        }
1824
38.5M
    }
1825
70.0M
    if (dict != NULL) {
1826
66.3M
        assert(PyUnicode_CheckExact(name));
1827
66.3M
        int found = _PyDict_GetMethodStackRef((PyDictObject *)dict, name, method);
1828
66.3M
        if (found < 0) {
1829
0
            assert(PyStackRef_IsNull(*method));
1830
0
            PyStackRef_CLEAR(*self);
1831
0
            return -1;
1832
0
        }
1833
66.3M
        else if (found) {
1834
27
            PyStackRef_CLEAR(*self);
1835
27
            return 0;
1836
27
        }
1837
66.3M
    }
1838
1839
70.0M
    if (meth_found) {
1840
69.1M
        assert(!PyStackRef_IsNull(*method));
1841
69.1M
        return 1;
1842
69.1M
    }
1843
1844
937k
    if (f != NULL) {
1845
705k
        if (Py_IS_TYPE(descr, &PyClassMethod_Type)) {
1846
689k
            PyObject *callable = _PyClassMethod_GetFunc(descr);
1847
689k
            PyStackRef_XSETREF(*method, PyStackRef_FromPyObjectNew(callable));
1848
689k
            PyStackRef_XSETREF(*self, PyStackRef_FromPyObjectNew((PyObject *)tp));
1849
689k
            return 1;
1850
689k
        }
1851
16.7k
        else if (Py_IS_TYPE(descr, &PyStaticMethod_Type)) {
1852
16.7k
            PyObject *callable = _PyStaticMethod_GetFunc(descr);
1853
16.7k
            PyStackRef_XSETREF(*method, PyStackRef_FromPyObjectNew(callable));
1854
16.7k
            PyStackRef_CLEAR(*self);
1855
16.7k
            return 0;
1856
16.7k
        }
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
231k
    if (descr != NULL) {
1868
231k
        assert(!PyStackRef_IsNull(*method));
1869
231k
        PyStackRef_CLEAR(*self);
1870
231k
        return 0;
1871
231k
    }
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
231k
}
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
383M
{
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
383M
    PyTypeObject *tp = Py_TYPE(obj);
1897
383M
    PyObject *descr = NULL;
1898
383M
    PyObject *res = NULL;
1899
383M
    descrgetfunc f;
1900
1901
383M
    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
383M
    if (!_PyType_IsReady(tp)) {
1909
0
        if (PyType_Ready(tp) < 0)
1910
0
            return NULL;
1911
0
    }
1912
1913
383M
    Py_INCREF(name);
1914
1915
383M
    PyThreadState *tstate = _PyThreadState_GET();
1916
383M
    _PyCStackRef cref;
1917
383M
    _PyThreadState_PushCStackRef(tstate, &cref);
1918
1919
383M
    _PyType_LookupStackRefAndVersion(tp, name, &cref.ref);
1920
383M
    descr = PyStackRef_AsPyObjectBorrow(cref.ref);
1921
1922
383M
    f = NULL;
1923
383M
    if (descr != NULL) {
1924
244M
        f = Py_TYPE(descr)->tp_descr_get;
1925
244M
        if (f != NULL && PyDescr_IsData(descr)) {
1926
85.6M
            res = f(descr, obj, (PyObject *)Py_TYPE(obj));
1927
85.6M
            if (res == NULL && suppress &&
1928
29.1k
                    PyErr_ExceptionMatches(PyExc_AttributeError)) {
1929
29.0k
                PyErr_Clear();
1930
29.0k
            }
1931
85.6M
            goto done;
1932
85.6M
        }
1933
244M
    }
1934
298M
    if (dict == NULL) {
1935
298M
        if ((tp->tp_flags & Py_TPFLAGS_INLINE_VALUES)) {
1936
152M
            if (PyUnicode_CheckExact(name) &&
1937
152M
                _PyObject_TryGetInstanceAttribute(obj, name, &res)) {
1938
72.1M
                if (res != NULL) {
1939
26.9M
                    goto done;
1940
26.9M
                }
1941
72.1M
            }
1942
80.0M
            else {
1943
80.0M
                dict = (PyObject *)_PyObject_MaterializeManagedDict(obj);
1944
80.0M
                if (dict == NULL) {
1945
0
                    res = NULL;
1946
0
                    goto done;
1947
0
                }
1948
80.0M
            }
1949
152M
        }
1950
146M
        else if ((tp->tp_flags & Py_TPFLAGS_MANAGED_DICT)) {
1951
6.56M
            dict = (PyObject *)_PyObject_GetManagedDict(obj);
1952
6.56M
        }
1953
139M
        else {
1954
139M
            PyObject **dictptr = _PyObject_ComputedDictPointer(obj);
1955
139M
            if (dictptr) {
1956
#ifdef Py_GIL_DISABLED
1957
                dict = _Py_atomic_load_ptr_acquire(dictptr);
1958
#else
1959
76.8M
                dict = *dictptr;
1960
76.8M
#endif
1961
76.8M
            }
1962
139M
        }
1963
298M
    }
1964
271M
    if (dict != NULL) {
1965
162M
        Py_INCREF(dict);
1966
162M
        int rc = PyDict_GetItemRef(dict, name, &res);
1967
162M
        Py_DECREF(dict);
1968
162M
        if (res != NULL) {
1969
132M
            goto done;
1970
132M
        }
1971
30.2M
        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
162M
    }
1980
1981
139M
    if (f != NULL) {
1982
83.2M
        res = f(descr, obj, (PyObject *)Py_TYPE(obj));
1983
83.2M
        if (res == NULL && suppress &&
1984
0
                PyErr_ExceptionMatches(PyExc_AttributeError)) {
1985
0
            PyErr_Clear();
1986
0
        }
1987
83.2M
        goto done;
1988
83.2M
    }
1989
1990
56.0M
    if (descr != NULL) {
1991
33.3M
        res = PyStackRef_AsPyObjectSteal(cref.ref);
1992
33.3M
        cref.ref = PyStackRef_NULL;
1993
33.3M
        goto done;
1994
33.3M
    }
1995
1996
22.7M
    if (!suppress) {
1997
2.34M
        PyErr_Format(PyExc_AttributeError,
1998
2.34M
                     "'%.100s' object has no attribute '%U'",
1999
2.34M
                     tp->tp_name, name);
2000
2001
2.34M
        _PyObject_SetAttributeErrorContext(obj, name);
2002
2.34M
    }
2003
383M
  done:
2004
383M
    _PyThreadState_PopCStackRef(tstate, &cref);
2005
383M
    Py_DECREF(name);
2006
383M
    return res;
2007
22.7M
}
2008
2009
PyObject *
2010
PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
2011
274M
{
2012
274M
    return _PyObject_GenericGetAttrWithDict(obj, name, NULL, 0);
2013
274M
}
2014
2015
int
2016
_PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
2017
                                 PyObject *value, PyObject *dict)
2018
77.4M
{
2019
77.4M
    PyTypeObject *tp = Py_TYPE(obj);
2020
77.4M
    PyObject *descr;
2021
77.4M
    descrsetfunc f;
2022
77.4M
    int res = -1;
2023
2024
77.4M
    assert(!PyType_IsSubtype(tp, &PyType_Type));
2025
77.4M
    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
77.4M
    if (!_PyType_IsReady(tp) && PyType_Ready(tp) < 0) {
2033
0
        return -1;
2034
0
    }
2035
2036
77.4M
    Py_INCREF(name);
2037
77.4M
    _Py_INCREF_TYPE(tp);
2038
2039
77.4M
    PyThreadState *tstate = _PyThreadState_GET();
2040
77.4M
    _PyCStackRef cref;
2041
77.4M
    _PyThreadState_PushCStackRef(tstate, &cref);
2042
2043
77.4M
    _PyType_LookupStackRefAndVersion(tp, name, &cref.ref);
2044
77.4M
    descr = PyStackRef_AsPyObjectBorrow(cref.ref);
2045
2046
77.4M
    if (descr != NULL) {
2047
42.1M
        f = Py_TYPE(descr)->tp_descr_set;
2048
42.1M
        if (f != NULL) {
2049
12.7M
            res = f(descr, obj, value);
2050
12.7M
            goto done;
2051
12.7M
        }
2052
42.1M
    }
2053
2054
64.6M
    if (dict == NULL) {
2055
63.9M
        PyObject **dictptr;
2056
2057
63.9M
        if ((tp->tp_flags & Py_TPFLAGS_INLINE_VALUES)) {
2058
40.6M
            res = _PyObject_StoreInstanceAttribute(obj, name, value);
2059
40.6M
            goto error_check;
2060
40.6M
        }
2061
2062
23.3M
        if ((tp->tp_flags & Py_TPFLAGS_MANAGED_DICT)) {
2063
27.5k
            PyManagedDictPointer *managed_dict = _PyObject_ManagedDictPointer(obj);
2064
27.5k
            dictptr = (PyObject **)&managed_dict->dict;
2065
27.5k
        }
2066
23.2M
        else {
2067
23.2M
            dictptr = _PyObject_ComputedDictPointer(obj);
2068
23.2M
        }
2069
23.3M
        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
23.3M
        else {
2092
23.3M
            res = _PyObjectDict_SetItem(tp, obj, dictptr, name, value);
2093
23.3M
        }
2094
23.3M
    }
2095
671k
    else {
2096
671k
        Py_INCREF(dict);
2097
671k
        if (value == NULL)
2098
0
            res = PyDict_DelItem(dict, name);
2099
671k
        else
2100
671k
            res = PyDict_SetItem(dict, name, value);
2101
671k
        Py_DECREF(dict);
2102
671k
    }
2103
64.6M
  error_check:
2104
64.6M
    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
77.4M
  done:
2111
77.4M
    _PyThreadState_PopCStackRef(tstate, &cref);
2112
77.4M
    _Py_DECREF_TYPE(tp);
2113
77.4M
    Py_DECREF(name);
2114
77.4M
    return res;
2115
64.6M
}
2116
2117
int
2118
PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
2119
76.7M
{
2120
76.7M
    return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL);
2121
76.7M
}
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
141M
{
2140
141M
    Py_ssize_t res;
2141
141M
    if (v == Py_True)
2142
13.6M
        return 1;
2143
127M
    if (v == Py_False)
2144
37.2M
        return 0;
2145
90.6M
    if (v == Py_None)
2146
4.76M
        return 0;
2147
85.9M
    else if (Py_TYPE(v)->tp_as_number != NULL &&
2148
72.1M
             Py_TYPE(v)->tp_as_number->nb_bool != NULL)
2149
700k
        res = (*Py_TYPE(v)->tp_as_number->nb_bool)(v);
2150
85.2M
    else if (Py_TYPE(v)->tp_as_mapping != NULL &&
2151
77.9M
             Py_TYPE(v)->tp_as_mapping->mp_length != NULL)
2152
33.0M
        res = (*Py_TYPE(v)->tp_as_mapping->mp_length)(v);
2153
52.2M
    else if (Py_TYPE(v)->tp_as_sequence != NULL &&
2154
45.0M
             Py_TYPE(v)->tp_as_sequence->sq_length != NULL)
2155
41.8M
        res = (*Py_TYPE(v)->tp_as_sequence->sq_length)(v);
2156
10.3M
    else
2157
10.3M
        return 1;
2158
    /* if it is negative, it should be either -1 or -2 */
2159
75.5M
    return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
2160
90.6M
}
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
12.2M
{
2180
12.2M
    if (x == NULL)
2181
0
        return 0;
2182
12.2M
    return Py_TYPE(x)->tp_call != NULL;
2183
12.2M
}
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
6.09k
{
2236
6.09k
    PyObject *result, *sorted;
2237
6.09k
    PyObject *dirfunc = _PyObject_LookupSpecial(obj, &_Py_ID(__dir__));
2238
2239
6.09k
    assert(obj != NULL);
2240
6.09k
    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
6.09k
    result = _PyObject_CallNoArgs(dirfunc);
2247
6.09k
    Py_DECREF(dirfunc);
2248
6.09k
    if (result == NULL)
2249
0
        return NULL;
2250
    /* return sorted(result) */
2251
6.09k
    sorted = PySequence_List(result);
2252
6.09k
    Py_DECREF(result);
2253
6.09k
    if (sorted == NULL)
2254
0
        return NULL;
2255
6.09k
    if (PyList_Sort(sorted)) {
2256
0
        Py_DECREF(sorted);
2257
0
        return NULL;
2258
0
    }
2259
6.09k
    return sorted;
2260
6.09k
}
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
6.09k
{
2269
6.09k
    return (obj == NULL) ? _dir_locals() : _dir_object(obj);
2270
6.09k
}
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.2k
{
2282
82.2k
    return PyUnicode_FromString("None");
2283
82.2k
}
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
85.8k
{
2313
85.8k
    return 0xFCA86420;
2314
85.8k
}
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[] = {
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
    &PySeqIter_Type,
2601
    &PySetIter_Type,
2602
    &PySet_Type,
2603
    &PySlice_Type,
2604
    &PyStdPrinter_Type,
2605
    &PySuper_Type,
2606
    &PyTraceBack_Type,
2607
    &PyTupleIter_Type,
2608
    &PyTuple_Type,
2609
    &PyUnicodeIter_Type,
2610
    &PyUnicode_Type,
2611
    &PyWrapperDescr_Type,
2612
    &PyZip_Type,
2613
    &Py_GenericAliasType,
2614
    &_PyAnextAwaitable_Type,
2615
    &_PyAsyncGenASend_Type,
2616
    &_PyAsyncGenAThrow_Type,
2617
    &_PyAsyncGenWrappedValue_Type,
2618
    &_PyBufferWrapper_Type,
2619
    &_PyContextTokenMissing_Type,
2620
    &_PyCoroWrapper_Type,
2621
    &_Py_GenericAliasIterType,
2622
    &_PyHamtItems_Type,
2623
    &_PyHamtKeys_Type,
2624
    &_PyHamtValues_Type,
2625
    &_PyHamt_ArrayNode_Type,
2626
    &_PyHamt_BitmapNode_Type,
2627
    &_PyHamt_CollisionNode_Type,
2628
    &_PyHamt_Type,
2629
    &_PyInstructionSequence_Type,
2630
    &_PyInterpolation_Type,
2631
    &_PyLegacyEventHandler_Type,
2632
    &_PyLineIterator,
2633
    &_PyManagedBuffer_Type,
2634
    &_PyMemoryIter_Type,
2635
    &_PyMethodWrapper_Type,
2636
    &_PyNamespace_Type,
2637
    &_PyNone_Type,
2638
    &_PyNotImplemented_Type,
2639
    &_PyPositionsIterator,
2640
    &_PyTemplate_Type,
2641
    &_PyTemplateIter_Type,
2642
    &_PyUnicodeASCIIIter_Type,
2643
    &_PyUnion_Type,
2644
#ifdef _Py_TIER2
2645
    &_PyUOpExecutor_Type,
2646
#endif
2647
    &_PyWeakref_CallableProxyType,
2648
    &_PyWeakref_ProxyType,
2649
    &_PyWeakref_RefType,
2650
    &_PyTypeAlias_Type,
2651
    &_PyNoDefault_Type,
2652
2653
    // subclasses: _PyTypes_FiniTypes() deallocates them before their base
2654
    // class
2655
    &PyBool_Type,         // base=&PyLong_Type
2656
    &PyCMethod_Type,      // base=&PyCFunction_Type
2657
    &PyODictItems_Type,   // base=&PyDictItems_Type
2658
    &PyODictKeys_Type,    // base=&PyDictKeys_Type
2659
    &PyODictValues_Type,  // base=&PyDictValues_Type
2660
    &PyODict_Type,        // base=&PyDict_Type
2661
};
2662
2663
2664
PyStatus
2665
_PyTypes_InitTypes(PyInterpreterState *interp)
2666
36
{
2667
    // All other static types (unless initialized elsewhere)
2668
4.28k
    for (size_t i=0; i < Py_ARRAY_LENGTH(static_types); i++) {
2669
4.24k
        PyTypeObject *type = static_types[i];
2670
4.24k
        if (_PyStaticType_InitBuiltin(interp, type) < 0) {
2671
0
            return _PyStatus_ERR("Can't initialize builtin type");
2672
0
        }
2673
4.24k
        if (type == &PyType_Type) {
2674
            // Sanitify checks of the two most important types
2675
36
            assert(PyBaseObject_Type.tp_base == NULL);
2676
36
            assert(PyType_Type.tp_base == &PyBaseObject_Type);
2677
36
        }
2678
4.24k
    }
2679
2680
    // Cache __reduce__ from PyBaseObject_Type object
2681
36
    PyObject *baseobj_dict = _PyType_GetDict(&PyBaseObject_Type);
2682
36
    PyObject *baseobj_reduce = PyDict_GetItemWithError(baseobj_dict, &_Py_ID(__reduce__));
2683
36
    if (baseobj_reduce == NULL && PyErr_Occurred()) {
2684
0
        return _PyStatus_ERR("Can't get __reduce__ from base object");
2685
0
    }
2686
36
    _Py_INTERP_CACHED_OBJECT(interp, objreduce) = baseobj_reduce;
2687
2688
    // Must be after static types are initialized
2689
36
    if (_Py_initialize_generic(interp) < 0) {
2690
0
        return _PyStatus_ERR("Can't initialize generic types");
2691
0
    }
2692
2693
36
    return _PyStatus_OK();
2694
36
}
2695
2696
2697
// Best-effort function clearing static types.
2698
//
2699
// Don't deallocate a type if it still has subclasses. If a Py_Finalize()
2700
// sub-function is interrupted by CTRL+C or fails with MemoryError, some
2701
// subclasses are not cleared properly. Leave the static type unchanged in this
2702
// case.
2703
void
2704
_PyTypes_FiniTypes(PyInterpreterState *interp)
2705
0
{
2706
    // Deallocate types in the reverse order to deallocate subclasses before
2707
    // their base classes.
2708
0
    for (Py_ssize_t i=Py_ARRAY_LENGTH(static_types)-1; i>=0; i--) {
2709
0
        PyTypeObject *type = static_types[i];
2710
0
        _PyStaticType_FiniBuiltin(interp, type);
2711
0
    }
2712
0
}
2713
2714
2715
static inline void
2716
new_reference(PyObject *op)
2717
3.18G
{
2718
    // Skip the immortal object check in Py_SET_REFCNT; always set refcnt to 1
2719
3.18G
#if !defined(Py_GIL_DISABLED)
2720
3.18G
#if SIZEOF_VOID_P > 4
2721
3.18G
    op->ob_refcnt_full = 1;
2722
3.18G
    assert(op->ob_refcnt == 1);
2723
3.18G
    assert(op->ob_flags == 0);
2724
#else
2725
    op->ob_refcnt = 1;
2726
#endif
2727
#else
2728
    op->ob_flags = 0;
2729
    op->ob_mutex = (PyMutex){ 0 };
2730
#ifdef _Py_THREAD_SANITIZER
2731
    _Py_atomic_store_uintptr_relaxed(&op->ob_tid, _Py_ThreadId());
2732
    _Py_atomic_store_uint8_relaxed(&op->ob_gc_bits, 0);
2733
    _Py_atomic_store_uint32_relaxed(&op->ob_ref_local, 1);
2734
    _Py_atomic_store_ssize_relaxed(&op->ob_ref_shared, 0);
2735
#else
2736
    op->ob_tid = _Py_ThreadId();
2737
    op->ob_gc_bits = 0;
2738
    op->ob_ref_local = 1;
2739
    op->ob_ref_shared = 0;
2740
#endif
2741
#endif
2742
#ifdef Py_TRACE_REFS
2743
    _Py_AddToAllObjects(op);
2744
#endif
2745
3.18G
    _PyReftracerTrack(op, PyRefTracer_CREATE);
2746
3.18G
}
2747
2748
void
2749
_Py_NewReference(PyObject *op)
2750
3.11G
{
2751
#ifdef Py_REF_DEBUG
2752
    _Py_IncRefTotal(_PyThreadState_GET());
2753
#endif
2754
3.11G
    new_reference(op);
2755
3.11G
}
2756
2757
void
2758
_Py_NewReferenceNoTotal(PyObject *op)
2759
68.3M
{
2760
68.3M
    new_reference(op);
2761
68.3M
}
2762
2763
void
2764
_Py_SetImmortalUntracked(PyObject *op)
2765
301k
{
2766
    // Check if already immortal to avoid degrading from static immortal to plain immortal
2767
301k
    if (_Py_IsImmortal(op)) {
2768
108
        return;
2769
108
    }
2770
#ifdef Py_GIL_DISABLED
2771
    op->ob_tid = _Py_UNOWNED_TID;
2772
    op->ob_ref_local = _Py_IMMORTAL_REFCNT_LOCAL;
2773
    op->ob_ref_shared = 0;
2774
    _Py_atomic_or_uint8(&op->ob_gc_bits, _PyGC_BITS_DEFERRED);
2775
#elif SIZEOF_VOID_P > 4
2776
301k
    op->ob_flags = _Py_IMMORTAL_FLAGS;
2777
301k
    op->ob_refcnt = _Py_IMMORTAL_INITIAL_REFCNT;
2778
#else
2779
    op->ob_refcnt = _Py_IMMORTAL_INITIAL_REFCNT;
2780
#endif
2781
301k
}
2782
2783
void
2784
_Py_SetImmortal(PyObject *op)
2785
301k
{
2786
301k
    if (PyObject_IS_GC(op) && _PyObject_GC_IS_TRACKED(op)) {
2787
14.7k
        _PyObject_GC_UNTRACK(op);
2788
14.7k
    }
2789
301k
    _Py_SetImmortalUntracked(op);
2790
301k
}
2791
2792
void
2793
_PyObject_SetDeferredRefcount(PyObject *op)
2794
232k
{
2795
#ifdef Py_GIL_DISABLED
2796
    assert(PyType_IS_GC(Py_TYPE(op)));
2797
    assert(_Py_IsOwnedByCurrentThread(op));
2798
    assert(op->ob_ref_shared == 0);
2799
    _PyObject_SET_GC_BITS(op, _PyGC_BITS_DEFERRED);
2800
    op->ob_ref_shared = _Py_REF_SHARED(_Py_REF_DEFERRED, 0);
2801
#endif
2802
232k
}
2803
2804
int
2805
PyUnstable_Object_EnableDeferredRefcount(PyObject *op)
2806
244k
{
2807
#ifdef Py_GIL_DISABLED
2808
    if (!PyType_IS_GC(Py_TYPE(op))) {
2809
        // Deferred reference counting doesn't work
2810
        // on untracked types.
2811
        return 0;
2812
    }
2813
2814
    uint8_t bits = _Py_atomic_load_uint8(&op->ob_gc_bits);
2815
    if ((bits & _PyGC_BITS_DEFERRED) != 0)
2816
    {
2817
        // Nothing to do.
2818
        return 0;
2819
    }
2820
2821
    if (_Py_atomic_compare_exchange_uint8(&op->ob_gc_bits, &bits, bits | _PyGC_BITS_DEFERRED) == 0)
2822
    {
2823
        // Someone beat us to it!
2824
        return 0;
2825
    }
2826
    _Py_atomic_add_ssize(&op->ob_ref_shared, _Py_REF_SHARED(_Py_REF_DEFERRED, 0));
2827
    return 1;
2828
#else
2829
244k
    return 0;
2830
244k
#endif
2831
244k
}
2832
2833
int
2834
PyUnstable_Object_IsUniqueReferencedTemporary(PyObject *op)
2835
0
{
2836
0
    if (!_PyObject_IsUniquelyReferenced(op)) {
2837
0
        return 0;
2838
0
    }
2839
2840
0
    _PyInterpreterFrame *frame = _PyEval_GetFrame();
2841
0
    if (frame == NULL) {
2842
0
        return 0;
2843
0
    }
2844
2845
0
    _PyStackRef *base = _PyFrame_Stackbase(frame);
2846
0
    _PyStackRef *stackpointer = frame->stackpointer;
2847
0
    while (stackpointer > base) {
2848
0
        stackpointer--;
2849
0
        _PyStackRef ref = *stackpointer;
2850
0
        if (PyStackRef_IsTaggedInt(ref)) {
2851
0
            continue;
2852
0
        }
2853
0
        if (op == PyStackRef_AsPyObjectBorrow(ref)) {
2854
0
            return PyStackRef_IsHeapSafe(ref);
2855
0
        }
2856
0
    }
2857
0
    return 0;
2858
0
}
2859
2860
int
2861
PyUnstable_TryIncRef(PyObject *op)
2862
0
{
2863
0
    return _Py_TryIncref(op);
2864
0
}
2865
2866
void
2867
PyUnstable_EnableTryIncRef(PyObject *op)
2868
0
{
2869
#ifdef Py_GIL_DISABLED
2870
    _PyObject_SetMaybeWeakref(op);
2871
#endif
2872
0
}
2873
2874
int
2875
PyUnstable_SetImmortal(PyObject *op)
2876
0
{
2877
0
    assert(op != NULL);
2878
0
    if (!_PyObject_IsUniquelyReferenced(op) || PyUnicode_Check(op)) {
2879
0
        return 0;
2880
0
    }
2881
0
    _Py_SetImmortal(op);
2882
0
    return 1;
2883
0
}
2884
2885
void
2886
_Py_ResurrectReference(PyObject *op)
2887
0
{
2888
#ifdef Py_TRACE_REFS
2889
    _Py_AddToAllObjects(op);
2890
#endif
2891
0
}
2892
2893
void
2894
_Py_ForgetReference(PyObject *op)
2895
0
{
2896
#ifdef Py_TRACE_REFS
2897
    if (Py_REFCNT(op) < 0) {
2898
        _PyObject_ASSERT_FAILED_MSG(op, "negative refcnt");
2899
    }
2900
2901
    PyInterpreterState *interp = _PyInterpreterState_GET();
2902
2903
#ifdef SLOW_UNREF_CHECK
2904
    if (!_PyRefchain_Get(interp, op)) {
2905
        /* Not found */
2906
        _PyObject_ASSERT_FAILED_MSG(op,
2907
                                    "object not found in the objects list");
2908
    }
2909
#endif
2910
2911
    _PyRefchain_Remove(interp, op);
2912
#endif
2913
0
}
2914
2915
2916
#ifdef Py_TRACE_REFS
2917
static int
2918
_Py_PrintReference(_Py_hashtable_t *ht,
2919
                   const void *key, const void *value,
2920
                   void *user_data)
2921
{
2922
    PyObject *op = (PyObject*)key;
2923
    FILE *fp = (FILE *)user_data;
2924
    fprintf(fp, "%p [%zd] ", (void *)op, Py_REFCNT(op));
2925
    if (PyObject_Print(op, fp, 0) != 0) {
2926
        PyErr_Clear();
2927
    }
2928
    putc('\n', fp);
2929
    return 0;
2930
}
2931
2932
2933
/* Print all live objects.  Because PyObject_Print is called, the
2934
 * interpreter must be in a healthy state.
2935
 */
2936
void
2937
_Py_PrintReferences(PyInterpreterState *interp, FILE *fp)
2938
{
2939
    if (interp == NULL) {
2940
        interp = _PyInterpreterState_Main();
2941
    }
2942
    fprintf(fp, "Remaining objects:\n");
2943
    _Py_hashtable_foreach(REFCHAIN(interp), _Py_PrintReference, fp);
2944
}
2945
2946
2947
static int
2948
_Py_PrintReferenceAddress(_Py_hashtable_t *ht,
2949
                          const void *key, const void *value,
2950
                          void *user_data)
2951
{
2952
    PyObject *op = (PyObject*)key;
2953
    FILE *fp = (FILE *)user_data;
2954
    fprintf(fp, "%p [%zd] %s\n",
2955
            (void *)op, Py_REFCNT(op), Py_TYPE(op)->tp_name);
2956
    return 0;
2957
}
2958
2959
2960
/* Print the addresses of all live objects.  Unlike _Py_PrintReferences, this
2961
 * doesn't make any calls to the Python C API, so is always safe to call.
2962
 */
2963
// XXX This function is not safe to use if the interpreter has been
2964
// freed or is in an unhealthy state (e.g. late in finalization).
2965
// The call in Py_FinalizeEx() is okay since the main interpreter
2966
// is statically allocated.
2967
void
2968
_Py_PrintReferenceAddresses(PyInterpreterState *interp, FILE *fp)
2969
{
2970
    fprintf(fp, "Remaining object addresses:\n");
2971
    _Py_hashtable_foreach(REFCHAIN(interp), _Py_PrintReferenceAddress, fp);
2972
}
2973
2974
2975
typedef struct {
2976
    PyObject *self;
2977
    PyObject *args;
2978
    PyObject *list;
2979
    PyObject *type;
2980
    Py_ssize_t limit;
2981
} _Py_GetObjectsData;
2982
2983
enum {
2984
    _PY_GETOBJECTS_IGNORE = 0,
2985
    _PY_GETOBJECTS_ERROR = 1,
2986
    _PY_GETOBJECTS_STOP = 2,
2987
};
2988
2989
static int
2990
_Py_GetObject(_Py_hashtable_t *ht,
2991
              const void *key, const void *value,
2992
              void *user_data)
2993
{
2994
    PyObject *op = (PyObject *)key;
2995
    _Py_GetObjectsData *data = user_data;
2996
    if (data->limit > 0) {
2997
        if (PyList_GET_SIZE(data->list) >= data->limit) {
2998
            return _PY_GETOBJECTS_STOP;
2999
        }
3000
    }
3001
3002
    if (op == data->self) {
3003
        return _PY_GETOBJECTS_IGNORE;
3004
    }
3005
    if (op == data->args) {
3006
        return _PY_GETOBJECTS_IGNORE;
3007
    }
3008
    if (op == data->list) {
3009
        return _PY_GETOBJECTS_IGNORE;
3010
    }
3011
    if (data->type != NULL) {
3012
        if (op == data->type) {
3013
            return _PY_GETOBJECTS_IGNORE;
3014
        }
3015
        if (!Py_IS_TYPE(op, (PyTypeObject *)data->type)) {
3016
            return _PY_GETOBJECTS_IGNORE;
3017
        }
3018
    }
3019
3020
    if (PyList_Append(data->list, op) < 0) {
3021
        return _PY_GETOBJECTS_ERROR;
3022
    }
3023
    return 0;
3024
}
3025
3026
3027
/* The implementation of sys.getobjects(). */
3028
PyObject *
3029
_Py_GetObjects(PyObject *self, PyObject *args)
3030
{
3031
    Py_ssize_t limit;
3032
    PyObject *type = NULL;
3033
    if (!PyArg_ParseTuple(args, "n|O", &limit, &type)) {
3034
        return NULL;
3035
    }
3036
3037
    PyObject *list = PyList_New(0);
3038
    if (list == NULL) {
3039
        return NULL;
3040
    }
3041
3042
    _Py_GetObjectsData data = {
3043
        .self = self,
3044
        .args = args,
3045
        .list = list,
3046
        .type = type,
3047
        .limit = limit,
3048
    };
3049
    PyInterpreterState *interp = _PyInterpreterState_GET();
3050
    int res = _Py_hashtable_foreach(REFCHAIN(interp), _Py_GetObject, &data);
3051
    if (res == _PY_GETOBJECTS_ERROR) {
3052
        Py_DECREF(list);
3053
        return NULL;
3054
    }
3055
    return list;
3056
}
3057
3058
#undef REFCHAIN
3059
#undef REFCHAIN_VALUE
3060
3061
#endif  /* Py_TRACE_REFS */
3062
3063
3064
/* Hack to force loading of abstract.o */
3065
Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
3066
3067
3068
void
3069
_PyObject_DebugTypeStats(FILE *out)
3070
0
{
3071
0
    _PyDict_DebugMallocStats(out);
3072
0
    _PyFloat_DebugMallocStats(out);
3073
0
    _PyList_DebugMallocStats(out);
3074
0
    _PyTuple_DebugMallocStats(out);
3075
0
}
3076
3077
/* These methods are used to control infinite recursion in repr, str, print,
3078
   etc.  Container objects that may recursively contain themselves,
3079
   e.g. builtin dictionaries and lists, should use Py_ReprEnter() and
3080
   Py_ReprLeave() to avoid infinite recursion.
3081
3082
   Py_ReprEnter() returns 0 the first time it is called for a particular
3083
   object and 1 every time thereafter.  It returns -1 if an exception
3084
   occurred.  Py_ReprLeave() has no return value.
3085
3086
   See dictobject.c and listobject.c for examples of use.
3087
*/
3088
3089
int
3090
Py_ReprEnter(PyObject *obj)
3091
3.49M
{
3092
3.49M
    PyObject *dict;
3093
3.49M
    PyObject *list;
3094
3.49M
    Py_ssize_t i;
3095
3096
3.49M
    dict = PyThreadState_GetDict();
3097
    /* Ignore a missing thread-state, so that this function can be called
3098
       early on startup. */
3099
3.49M
    if (dict == NULL)
3100
0
        return 0;
3101
3.49M
    list = PyDict_GetItemWithError(dict, &_Py_ID(Py_Repr));
3102
3.49M
    if (list == NULL) {
3103
4
        if (PyErr_Occurred()) {
3104
0
            return -1;
3105
0
        }
3106
4
        list = PyList_New(0);
3107
4
        if (list == NULL)
3108
0
            return -1;
3109
4
        if (_PyDict_SetItem_Take2((PyDictObject *)dict, &_Py_ID(Py_Repr), list) < 0) {
3110
0
            return -1;
3111
0
        }
3112
4
    }
3113
3.49M
    i = PyList_GET_SIZE(list);
3114
60.8M
    while (--i >= 0) {
3115
57.3M
        if (PyList_GET_ITEM(list, i) == obj)
3116
0
            return 1;
3117
57.3M
    }
3118
3.49M
    if (PyList_Append(list, obj) < 0)
3119
0
        return -1;
3120
3.49M
    return 0;
3121
3.49M
}
3122
3123
void
3124
Py_ReprLeave(PyObject *obj)
3125
3.49M
{
3126
3.49M
    PyObject *dict;
3127
3.49M
    PyObject *list;
3128
3.49M
    Py_ssize_t i;
3129
3130
3.49M
    PyObject *exc = PyErr_GetRaisedException();
3131
3132
3.49M
    dict = PyThreadState_GetDict();
3133
3.49M
    if (dict == NULL)
3134
0
        goto finally;
3135
3136
3.49M
    list = PyDict_GetItemWithError(dict, &_Py_ID(Py_Repr));
3137
3.49M
    if (list == NULL || !PyList_Check(list))
3138
0
        goto finally;
3139
3140
3.49M
    i = PyList_GET_SIZE(list);
3141
    /* Count backwards because we always expect obj to be list[-1] */
3142
3.49M
    while (--i >= 0) {
3143
3.49M
        if (PyList_GET_ITEM(list, i) == obj) {
3144
3.49M
            PyList_SetSlice(list, i, i + 1, NULL);
3145
3.49M
            break;
3146
3.49M
        }
3147
3.49M
    }
3148
3149
3.49M
finally:
3150
    /* ignore exceptions because there is no way to report them. */
3151
3.49M
    PyErr_SetRaisedException(exc);
3152
3.49M
}
3153
3154
/* Trashcan support. */
3155
3156
/* Add op to the tstate->delete_later list.  Called when the current
3157
 * call-stack depth gets large.  op must be a gc'ed object, with refcount 0.
3158
 *  Py_DECREF must already have been called on it.
3159
 */
3160
void
3161
_PyTrash_thread_deposit_object(PyThreadState *tstate, PyObject *op)
3162
19.7k
{
3163
19.7k
    _PyObject_ASSERT(op, Py_REFCNT(op) == 0);
3164
19.7k
    PyTypeObject *tp = Py_TYPE(op);
3165
19.7k
    assert(tp->tp_flags & Py_TPFLAGS_HAVE_GC);
3166
19.7k
    int tracked = 0;
3167
19.7k
    if (tp->tp_is_gc == NULL || tp->tp_is_gc(op)) {
3168
19.7k
        tracked = _PyObject_GC_IS_TRACKED(op);
3169
19.7k
        if (tracked) {
3170
19.7k
            _PyObject_GC_UNTRACK(op);
3171
19.7k
        }
3172
19.7k
    }
3173
19.7k
    uintptr_t tagged_ptr = ((uintptr_t)tstate->delete_later) | tracked;
3174
#ifdef Py_GIL_DISABLED
3175
    op->ob_tid = tagged_ptr;
3176
#else
3177
19.7k
    _Py_AS_GC(op)->_gc_next = tagged_ptr;
3178
19.7k
#endif
3179
19.7k
    tstate->delete_later = op;
3180
19.7k
}
3181
3182
/* Deallocate all the objects in the tstate->delete_later list.
3183
 * Called when the call-stack unwinds again. */
3184
void
3185
_PyTrash_thread_destroy_chain(PyThreadState *tstate)
3186
118
{
3187
19.8k
    while (tstate->delete_later) {
3188
19.7k
        PyObject *op = tstate->delete_later;
3189
19.7k
        destructor dealloc = Py_TYPE(op)->tp_dealloc;
3190
3191
#ifdef Py_GIL_DISABLED
3192
        uintptr_t tagged_ptr = op->ob_tid;
3193
        op->ob_tid = 0;
3194
        _Py_atomic_store_ssize_relaxed(&op->ob_ref_shared, _Py_REF_MERGED);
3195
#else
3196
19.7k
        uintptr_t tagged_ptr = _Py_AS_GC(op)->_gc_next;
3197
19.7k
        _Py_AS_GC(op)->_gc_next = 0;
3198
19.7k
#endif
3199
19.7k
        tstate->delete_later = (PyObject *)(tagged_ptr & ~1);
3200
19.7k
        if (tagged_ptr & 1) {
3201
19.7k
            _PyObject_GC_TRACK(op);
3202
19.7k
        }
3203
        /* Call the deallocator directly.  This used to try to
3204
         * fool Py_DECREF into calling it indirectly, but
3205
         * Py_DECREF was already called on this object, and in
3206
         * assorted non-release builds calling Py_DECREF again ends
3207
         * up distorting allocation statistics.
3208
         */
3209
19.7k
        _PyObject_ASSERT(op, Py_REFCNT(op) == 0);
3210
19.7k
        (*dealloc)(op);
3211
19.7k
    }
3212
118
}
3213
3214
void _Py_NO_RETURN
3215
_PyObject_AssertFailed(PyObject *obj, const char *expr, const char *msg,
3216
                       const char *file, int line, const char *function)
3217
0
{
3218
0
    fprintf(stderr, "%s:%d: ", file, line);
3219
0
    if (function) {
3220
0
        fprintf(stderr, "%s: ", function);
3221
0
    }
3222
0
    fflush(stderr);
3223
3224
0
    if (expr) {
3225
0
        fprintf(stderr, "Assertion \"%s\" failed", expr);
3226
0
    }
3227
0
    else {
3228
0
        fprintf(stderr, "Assertion failed");
3229
0
    }
3230
0
    fflush(stderr);
3231
3232
0
    if (msg) {
3233
0
        fprintf(stderr, ": %s", msg);
3234
0
    }
3235
0
    fprintf(stderr, "\n");
3236
0
    fflush(stderr);
3237
3238
0
    if (_PyObject_IsFreed(obj)) {
3239
        /* It seems like the object memory has been freed:
3240
           don't access it to prevent a segmentation fault. */
3241
0
        fprintf(stderr, "<object at %p is freed>\n", obj);
3242
0
        fflush(stderr);
3243
0
    }
3244
0
    else {
3245
        /* Display the traceback where the object has been allocated.
3246
           Do it before dumping repr(obj), since repr() is more likely
3247
           to crash than dumping the traceback. */
3248
0
        PyTypeObject *type = Py_TYPE(obj);
3249
0
        const size_t presize = _PyType_PreHeaderSize(type);
3250
0
        void *ptr = (void *)((char *)obj - presize);
3251
0
        _PyMem_DumpTraceback(fileno(stderr), ptr);
3252
3253
        /* This might succeed or fail, but we're about to abort, so at least
3254
           try to provide any extra info we can: */
3255
0
        PyObject_Dump(obj);
3256
3257
0
        fprintf(stderr, "\n");
3258
0
        fflush(stderr);
3259
0
    }
3260
3261
0
    Py_FatalError("_PyObject_AssertFailed");
3262
0
}
3263
3264
3265
/*
3266
When deallocating a container object, it's possible to trigger an unbounded
3267
chain of deallocations, as each Py_DECREF in turn drops the refcount on "the
3268
next" object in the chain to 0.  This can easily lead to stack overflows.
3269
To avoid that, if the C stack is nearing its limit, instead of calling
3270
dealloc on the object, it is added to a queue to be freed later when the
3271
stack is shallower */
3272
void
3273
_Py_Dealloc(PyObject *op)
3274
2.78G
{
3275
2.78G
    PyTypeObject *type = Py_TYPE(op);
3276
2.78G
    unsigned long gc_flag = type->tp_flags & Py_TPFLAGS_HAVE_GC;
3277
2.78G
    destructor dealloc = type->tp_dealloc;
3278
2.78G
    PyThreadState *tstate = _PyThreadState_GET();
3279
2.78G
    intptr_t margin = _Py_RecursionLimit_GetMargin(tstate);
3280
2.78G
    if (margin < 2 && gc_flag) {
3281
19.7k
        _PyTrash_thread_deposit_object(tstate, (PyObject *)op);
3282
19.7k
        return;
3283
19.7k
    }
3284
#ifdef Py_DEBUG
3285
#if !defined(Py_GIL_DISABLED) && !defined(Py_STACKREF_DEBUG)
3286
    /* This assertion doesn't hold for the free-threading build, as
3287
     * PyStackRef_CLOSE_SPECIALIZED is not implemented */
3288
    assert(tstate->current_frame == NULL || tstate->current_frame->stackpointer != NULL);
3289
#endif
3290
    PyObject *old_exc = tstate != NULL ? tstate->current_exception : NULL;
3291
    // Keep the old exception type alive to prevent undefined behavior
3292
    // on (tstate->curexc_type != old_exc_type) below
3293
    Py_XINCREF(old_exc);
3294
    // Make sure that type->tp_name remains valid
3295
    Py_INCREF(type);
3296
#endif
3297
3298
#ifdef Py_TRACE_REFS
3299
    _Py_ForgetReference(op);
3300
#endif
3301
2.78G
    _PyReftracerTrack(op, PyRefTracer_DESTROY);
3302
2.78G
    (*dealloc)(op);
3303
3304
#ifdef Py_DEBUG
3305
    // gh-89373: The tp_dealloc function must leave the current exception
3306
    // unchanged.
3307
    if (tstate != NULL && tstate->current_exception != old_exc) {
3308
        const char *err;
3309
        if (old_exc == NULL) {
3310
            err = "Deallocator of type '%s' raised an exception";
3311
        }
3312
        else if (tstate->current_exception == NULL) {
3313
            err = "Deallocator of type '%s' cleared the current exception";
3314
        }
3315
        else {
3316
            // It can happen if dealloc() normalized the current exception.
3317
            // A deallocator function must not change the current exception,
3318
            // not even normalize it.
3319
            err = "Deallocator of type '%s' overrode the current exception";
3320
        }
3321
        _Py_FatalErrorFormat(__func__, err, type->tp_name);
3322
    }
3323
    Py_XDECREF(old_exc);
3324
    Py_DECREF(type);
3325
#endif
3326
2.78G
    if (tstate->delete_later && margin >= 4 && gc_flag) {
3327
118
        _PyTrash_thread_destroy_chain(tstate);
3328
118
    }
3329
2.78G
}
3330
3331
3332
PyObject **
3333
PyObject_GET_WEAKREFS_LISTPTR(PyObject *op)
3334
0
{
3335
0
    return _PyObject_GET_WEAKREFS_LISTPTR(op);
3336
0
}
3337
3338
3339
#undef Py_NewRef
3340
#undef Py_XNewRef
3341
3342
// Export Py_NewRef() and Py_XNewRef() as regular functions for the stable ABI.
3343
PyObject*
3344
Py_NewRef(PyObject *obj)
3345
0
{
3346
0
    return _Py_NewRef(obj);
3347
0
}
3348
3349
PyObject*
3350
Py_XNewRef(PyObject *obj)
3351
0
{
3352
0
    return _Py_XNewRef(obj);
3353
0
}
3354
3355
#undef Py_Is
3356
#undef Py_IsNone
3357
#undef Py_IsTrue
3358
#undef Py_IsFalse
3359
3360
// Export Py_Is(), Py_IsNone(), Py_IsTrue(), Py_IsFalse() as regular functions
3361
// for the stable ABI.
3362
int Py_Is(PyObject *x, PyObject *y)
3363
0
{
3364
0
    return (x == y);
3365
0
}
3366
3367
int Py_IsNone(PyObject *x)
3368
0
{
3369
0
    return Py_Is(x, Py_None);
3370
0
}
3371
3372
int Py_IsTrue(PyObject *x)
3373
0
{
3374
0
    return Py_Is(x, Py_True);
3375
0
}
3376
3377
int Py_IsFalse(PyObject *x)
3378
0
{
3379
0
    return Py_Is(x, Py_False);
3380
0
}
3381
3382
3383
// Py_SET_REFCNT() implementation for stable ABI
3384
void
3385
_Py_SetRefcnt(PyObject *ob, Py_ssize_t refcnt)
3386
0
{
3387
0
    Py_SET_REFCNT(ob, refcnt);
3388
0
}
3389
3390
0
int PyRefTracer_SetTracer(PyRefTracer tracer, void *data) {
3391
0
    _Py_AssertHoldsTstate();
3392
3393
0
    _PyEval_StopTheWorldAll(&_PyRuntime);
3394
0
    if (_PyRuntime.ref_tracer.tracer_func != NULL) {
3395
0
        _PyReftracerTrack(NULL, PyRefTracer_TRACKER_REMOVED);
3396
0
        if (PyErr_Occurred()) {
3397
0
            _PyEval_StartTheWorldAll(&_PyRuntime);
3398
0
            return -1;
3399
0
        }
3400
0
    }
3401
0
    _PyRuntime.ref_tracer.tracer_func = tracer;
3402
0
    _PyRuntime.ref_tracer.tracer_data = data;
3403
0
    _PyEval_StartTheWorldAll(&_PyRuntime);
3404
0
    return 0;
3405
0
}
3406
3407
0
PyRefTracer PyRefTracer_GetTracer(void** data) {
3408
0
    _Py_AssertHoldsTstate();
3409
0
    if (data != NULL) {
3410
0
        *data = _PyRuntime.ref_tracer.tracer_data;
3411
0
    }
3412
0
    return _PyRuntime.ref_tracer.tracer_func;
3413
0
}
3414
3415
3416
3417
static PyObject* constants[] = {
3418
    &_Py_NoneStruct,                   // Py_CONSTANT_NONE
3419
    (PyObject*)(&_Py_FalseStruct),     // Py_CONSTANT_FALSE
3420
    (PyObject*)(&_Py_TrueStruct),      // Py_CONSTANT_TRUE
3421
    &_Py_EllipsisObject,               // Py_CONSTANT_ELLIPSIS
3422
    &_Py_NotImplementedStruct,         // Py_CONSTANT_NOT_IMPLEMENTED
3423
    NULL,  // Py_CONSTANT_ZERO
3424
    NULL,  // Py_CONSTANT_ONE
3425
    NULL,  // Py_CONSTANT_EMPTY_STR
3426
    NULL,  // Py_CONSTANT_EMPTY_BYTES
3427
    NULL,  // Py_CONSTANT_EMPTY_TUPLE
3428
};
3429
3430
void
3431
_Py_GetConstant_Init(void)
3432
36
{
3433
36
    constants[Py_CONSTANT_ZERO] = _PyLong_GetZero();
3434
36
    constants[Py_CONSTANT_ONE] = _PyLong_GetOne();
3435
36
    constants[Py_CONSTANT_EMPTY_STR] = PyUnicode_New(0, 0);
3436
36
    constants[Py_CONSTANT_EMPTY_BYTES] = PyBytes_FromStringAndSize(NULL, 0);
3437
36
    constants[Py_CONSTANT_EMPTY_TUPLE] = PyTuple_New(0);
3438
#ifndef NDEBUG
3439
    for (size_t i=0; i < Py_ARRAY_LENGTH(constants); i++) {
3440
        assert(constants[i] != NULL);
3441
        assert(_Py_IsImmortal(constants[i]));
3442
    }
3443
#endif
3444
36
}
3445
3446
PyObject*
3447
Py_GetConstant(unsigned int constant_id)
3448
24.2M
{
3449
24.2M
    if (constant_id < Py_ARRAY_LENGTH(constants)) {
3450
24.2M
        return constants[constant_id];
3451
24.2M
    }
3452
0
    else {
3453
0
        PyErr_BadInternalCall();
3454
0
        return NULL;
3455
0
    }
3456
24.2M
}
3457
3458
3459
PyObject*
3460
Py_GetConstantBorrowed(unsigned int constant_id)
3461
0
{
3462
    // All constants are immortal
3463
0
    return Py_GetConstant(constant_id);
3464
0
}
3465
3466
int
3467
PyUnstable_IsImmortal(PyObject *op)
3468
0
{
3469
    /* Checking a reference count requires a thread state */
3470
0
    _Py_AssertHoldsTstate();
3471
0
    assert(op != NULL);
3472
0
    return _Py_IsImmortal(op);
3473
0
}
3474
3475
int
3476
PyUnstable_Object_IsUniquelyReferenced(PyObject *op)
3477
0
{
3478
0
    _Py_AssertHoldsTstate();
3479
0
    assert(op != NULL);
3480
0
    return _PyObject_IsUniquelyReferenced(op);
3481
0
}
3482
3483
int
3484
_PyObject_VisitType(PyObject *op, visitproc visit, void *arg)
3485
388k
{
3486
388k
    assert(op != NULL);
3487
388k
    PyTypeObject *tp = Py_TYPE(op);
3488
388k
    _PyObject_ASSERT((PyObject *)tp, PyType_HasFeature(tp, Py_TPFLAGS_HEAPTYPE));
3489
388k
    Py_VISIT(tp);
3490
388k
    return 0;
3491
388k
}
3492
3493
// Implementations for the stable ABI
3494
// Keep these at the end.
3495
#undef Py_TYPE
3496
#undef Py_REFCNT
3497
#undef Py_SIZE
3498
#undef Py_IS_TYPE
3499
#undef Py_SET_SIZE
3500
0
PyTypeObject* Py_TYPE(PyObject *ob) { return _Py_TYPE_impl(ob); }
3501
0
Py_ssize_t Py_REFCNT(PyObject *ob) { return _Py_REFCNT(ob); }
3502
0
Py_ssize_t Py_SIZE(PyObject *o) { return _Py_SIZE_impl(o); }
3503
0
int Py_IS_TYPE(PyObject *o, PyTypeObject *t) { return _Py_IS_TYPE_impl(o, t); }
3504
0
void Py_SET_SIZE(PyVarObject *o, Py_ssize_t s) { _Py_SET_SIZE_impl(o, s); }