Coverage Report

Created: 2025-11-24 06:11

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