Coverage Report

Created: 2025-07-04 06:49

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