Coverage Report

Created: 2026-03-07 06:56

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