Coverage Report

Created: 2026-03-08 06:40

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Objects/object.c
Line
Count
Source
1
2
/* Generic object operations; and implementation of None */
3
4
#include "Python.h"
5
#include "pycore_brc.h"           // _Py_brc_queue_object()
6
#include "pycore_call.h"          // _PyObject_CallNoArgs()
7
#include "pycore_ceval.h"         // _Py_EnterRecursiveCallTstate()
8
#include "pycore_context.h"       // _PyContextTokenMissing_Type
9
#include "pycore_critical_section.h" // Py_BEGIN_CRITICAL_SECTION
10
#include "pycore_descrobject.h"   // _PyMethodWrapper_Type
11
#include "pycore_dict.h"          // _PyObject_MaterializeManagedDict()
12
#include "pycore_floatobject.h"   // _PyFloat_DebugMallocStats()
13
#include "pycore_freelist.h"      // _PyObject_ClearFreeLists()
14
#include "pycore_genobject.h"     // _PyAsyncGenAThrow_Type
15
#include "pycore_hamt.h"          // _PyHamtItems_Type
16
#include "pycore_initconfig.h"    // _PyStatus_OK()
17
#include "pycore_instruction_sequence.h" // _PyInstructionSequence_Type
18
#include "pycore_interpframe.h"   // _PyFrame_Stackbase()
19
#include "pycore_interpolation.h" // _PyInterpolation_Type
20
#include "pycore_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
9.35k
{
356
9.35k
    Py_DECREF(o);
357
9.35k
}
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
2.81M
{
555
2.81M
    PyObject *op = (PyObject *) PyObject_Malloc(_PyObject_SIZE(tp));
556
2.81M
    if (op == NULL) {
557
0
        return PyErr_NoMemory();
558
0
    }
559
2.81M
    _PyObject_Init(op, tp);
560
2.81M
    return op;
561
2.81M
}
562
563
PyVarObject *
564
_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
565
206k
{
566
206k
    PyVarObject *op;
567
206k
    const size_t size = _PyObject_VAR_SIZE(tp, nitems);
568
206k
    op = (PyVarObject *) PyObject_Malloc(size);
569
206k
    if (op == NULL) {
570
0
        return (PyVarObject *)PyErr_NoMemory();
571
0
    }
572
206k
    _PyObject_InitVar(op, tp, nitems);
573
206k
    return op;
574
206k
}
575
576
void
577
PyObject_CallFinalizer(PyObject *self)
578
27.2M
{
579
27.2M
    PyTypeObject *tp = Py_TYPE(self);
580
581
27.2M
    if (tp->tp_finalize == NULL)
582
0
        return;
583
    /* tp_finalize should only be called once. */
584
27.2M
    if (_PyType_IS_GC(tp) && _PyGC_FINALIZED(self))
585
55.1k
        return;
586
587
27.2M
    tp->tp_finalize(self);
588
27.2M
    if (_PyType_IS_GC(tp)) {
589
27.0M
        _PyGC_SET_FINALIZED(self);
590
27.0M
    }
591
27.2M
}
592
593
int
594
PyObject_CallFinalizerFromDealloc(PyObject *self)
595
27.2M
{
596
27.2M
    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
27.2M
    _PyObject_ResurrectStart(self);
604
605
27.2M
    PyObject_CallFinalizer(self);
606
607
27.2M
    _PyObject_ASSERT_WITH_MSG(self,
608
27.2M
                              Py_REFCNT(self) > 0,
609
27.2M
                              "refcount is too small");
610
611
27.2M
    _PyObject_ASSERT(self,
612
27.2M
                    (!_PyType_IS_GC(Py_TYPE(self))
613
27.2M
                    || _PyObject_GC_IS_TRACKED(self)));
614
615
    /* Undo the temporary resurrection; can't use DECREF here, it would
616
     * cause a recursive call. */
617
27.2M
    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
27.2M
    return 0;
629
27.2M
}
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
0
{
709
0
    if (_PyMem_IsPtrFreed(op) || _PyMem_IsPtrFreed(Py_TYPE(op))) {
710
0
        return 1;
711
0
    }
712
0
    return 0;
713
0
}
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
13.8M
{
758
13.8M
    PyObject *res;
759
13.8M
    if (PyErr_CheckSignals())
760
0
        return NULL;
761
13.8M
    if (v == NULL)
762
0
        return PyUnicode_FromString("<NULL>");
763
13.8M
    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
13.8M
    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
13.8M
    if (_Py_EnterRecursiveCallTstate(tstate,
778
13.8M
                                     " while getting the repr of an object")) {
779
0
        return NULL;
780
0
    }
781
13.8M
    res = (*Py_TYPE(v)->tp_repr)(v);
782
13.8M
    _Py_LeaveRecursiveCallTstate(tstate);
783
784
13.8M
    if (res == NULL) {
785
2
        return NULL;
786
2
    }
787
13.8M
    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
13.8M
    return res;
794
13.8M
}
795
796
PyObject *
797
PyObject_Str(PyObject *v)
798
58.9M
{
799
58.9M
    PyObject *res;
800
58.9M
    if (PyErr_CheckSignals())
801
0
        return NULL;
802
58.9M
    if (v == NULL)
803
0
        return PyUnicode_FromString("<NULL>");
804
58.9M
    if (PyUnicode_CheckExact(v)) {
805
53.2M
        return Py_NewRef(v);
806
53.2M
    }
807
5.72M
    if (Py_TYPE(v)->tp_str == NULL)
808
0
        return PyObject_Repr(v);
809
810
5.72M
    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
5.72M
    if (_Py_EnterRecursiveCallTstate(tstate, " while getting the str of an object")) {
821
0
        return NULL;
822
0
    }
823
5.72M
    res = (*Py_TYPE(v)->tp_str)(v);
824
5.72M
    _Py_LeaveRecursiveCallTstate(tstate);
825
826
5.72M
    if (res == NULL) {
827
5.13k
        return NULL;
828
5.13k
    }
829
5.71M
    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
5.71M
    assert(_PyUnicode_CheckConsistency(res, 1));
836
5.71M
    return res;
837
5.71M
}
838
839
PyObject *
840
PyObject_ASCII(PyObject *v)
841
0
{
842
0
    PyObject *repr, *ascii, *res;
843
844
0
    repr = PyObject_Repr(v);
845
0
    if (repr == NULL)
846
0
        return NULL;
847
848
0
    if (PyUnicode_IS_ASCII(repr))
849
0
        return repr;
850
851
    /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */
852
0
    ascii = _PyUnicode_AsASCIIString(repr, "backslashreplace");
853
0
    Py_DECREF(repr);
854
0
    if (ascii == NULL)
855
0
        return NULL;
856
857
0
    res = PyUnicode_DecodeASCII(
858
0
        PyBytes_AS_STRING(ascii),
859
0
        PyBytes_GET_SIZE(ascii),
860
0
        NULL);
861
862
0
    Py_DECREF(ascii);
863
0
    return res;
864
0
}
865
866
PyObject *
867
PyObject_Bytes(PyObject *v)
868
220
{
869
220
    PyObject *result, *func;
870
871
220
    if (v == NULL)
872
0
        return PyBytes_FromString("<NULL>");
873
874
220
    if (PyBytes_CheckExact(v)) {
875
0
        return Py_NewRef(v);
876
0
    }
877
878
220
    func = _PyObject_LookupSpecial(v, &_Py_ID(__bytes__));
879
220
    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
220
    else if (PyErr_Occurred())
894
0
        return NULL;
895
220
    return PyBytes_FromObject(v);
896
220
}
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
206M
{
1047
206M
    richcmpfunc f;
1048
206M
    PyObject *res;
1049
206M
    int checked_reverse_op = 0;
1050
1051
206M
    if (!Py_IS_TYPE(v, Py_TYPE(w)) &&
1052
14.5M
        PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v)) &&
1053
212k
        (f = Py_TYPE(w)->tp_richcompare) != NULL) {
1054
212k
        checked_reverse_op = 1;
1055
212k
        res = (*f)(w, v, _Py_SwappedOp[op]);
1056
212k
        if (res != Py_NotImplemented)
1057
179k
            return res;
1058
32.3k
        Py_DECREF(res);
1059
32.3k
    }
1060
206M
    if ((f = Py_TYPE(v)->tp_richcompare) != NULL) {
1061
206M
        res = (*f)(v, w, op);
1062
206M
        if (res != Py_NotImplemented)
1063
197M
            return res;
1064
9.31M
        Py_DECREF(res);
1065
9.31M
    }
1066
9.31M
    if (!checked_reverse_op && (f = Py_TYPE(w)->tp_richcompare) != NULL) {
1067
9.27M
        res = (*f)(w, v, _Py_SwappedOp[op]);
1068
9.27M
        if (res != Py_NotImplemented)
1069
58.1k
            return res;
1070
9.22M
        Py_DECREF(res);
1071
9.22M
    }
1072
    /* If neither object implements it, provide a sensible default
1073
       for == and !=, but raise an exception for ordering. */
1074
9.25M
    switch (op) {
1075
9.25M
    case Py_EQ:
1076
9.25M
        res = (v == w) ? Py_True : Py_False;
1077
9.25M
        break;
1078
1.21k
    case Py_NE:
1079
1.21k
        res = (v != w) ? Py_True : Py_False;
1080
1.21k
        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
9.25M
    }
1089
9.25M
    return Py_NewRef(res);
1090
9.25M
}
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
206M
{
1098
206M
    PyThreadState *tstate = _PyThreadState_GET();
1099
1100
206M
    assert(Py_LT <= op && op <= Py_GE);
1101
206M
    if (v == NULL || w == NULL) {
1102
0
        if (!_PyErr_Occurred(tstate)) {
1103
0
            PyErr_BadInternalCall();
1104
0
        }
1105
0
        return NULL;
1106
0
    }
1107
206M
    if (_Py_EnterRecursiveCallTstate(tstate, " in comparison")) {
1108
0
        return NULL;
1109
0
    }
1110
206M
    PyObject *res = do_richcompare(tstate, v, w, op);
1111
206M
    _Py_LeaveRecursiveCallTstate(tstate);
1112
206M
    return res;
1113
206M
}
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
209M
{
1120
209M
    PyObject *res;
1121
209M
    int ok;
1122
1123
    /* Quick result when objects are the same.
1124
       Guarantees that identity implies equality. */
1125
209M
    if (v == w) {
1126
43.2M
        if (op == Py_EQ)
1127
37.7M
            return 1;
1128
5.55M
        else if (op == Py_NE)
1129
0
            return 0;
1130
43.2M
    }
1131
1132
171M
    res = PyObject_RichCompare(v, w, op);
1133
171M
    if (res == NULL)
1134
0
        return -1;
1135
171M
    if (PyBool_Check(res)) {
1136
171M
        ok = (res == Py_True);
1137
171M
        assert(_Py_IsImmortal(res));
1138
171M
    }
1139
0
    else {
1140
0
        ok = PyObject_IsTrue(res);
1141
0
        Py_DECREF(res);
1142
0
    }
1143
171M
    return ok;
1144
171M
}
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
1.71G
{
1157
1.71G
    PyTypeObject *tp = Py_TYPE(v);
1158
1.71G
    if (tp->tp_hash != NULL)
1159
1.71G
        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
551k
{
1178
551k
    PyObject *w, *res;
1179
1180
551k
    if (Py_TYPE(v)->tp_getattr != NULL)
1181
0
        return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
1182
551k
    w = PyUnicode_FromString(name);
1183
551k
    if (w == NULL)
1184
0
        return NULL;
1185
551k
    res = PyObject_GetAttr(v, w);
1186
551k
    Py_DECREF(w);
1187
551k
    return res;
1188
551k
}
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
75.7k
{
1217
75.7k
    PyThreadState *tstate = _PyThreadState_GET();
1218
75.7k
    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
75.7k
    if (Py_TYPE(v)->tp_setattr != NULL) {
1228
0
        return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
1229
0
    }
1230
1231
75.7k
    PyObject *s = PyUnicode_InternFromString(name);
1232
75.7k
    if (s == NULL) {
1233
0
        return -1;
1234
0
    }
1235
1236
75.7k
    int res = PyObject_SetAttr(v, s, w);
1237
75.7k
    Py_DECREF(s);
1238
75.7k
    return res;
1239
75.7k
}
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
31.1k
{
1250
31.1k
    int res;
1251
31.1k
    PyObject* isabstract;
1252
1253
31.1k
    if (obj == NULL)
1254
616
        return 0;
1255
1256
30.5k
    res = PyObject_GetOptionalAttr(obj, &_Py_ID(__isabstractmethod__), &isabstract);
1257
30.5k
    if (res > 0) {
1258
4.02k
        res = PyObject_IsTrue(isabstract);
1259
4.02k
        Py_DECREF(isabstract);
1260
4.02k
    }
1261
30.5k
    return res;
1262
31.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
6.67M
{
1281
6.67M
    assert(PyErr_Occurred());
1282
6.67M
    if (!PyErr_ExceptionMatches(PyExc_AttributeError)){
1283
2.75k
        return 0;
1284
2.75k
    }
1285
    // Intercept AttributeError exceptions and augment them to offer suggestions later.
1286
6.66M
    PyObject *exc = PyErr_GetRaisedException();
1287
6.66M
    if (!PyErr_GivenExceptionMatches(exc, PyExc_AttributeError)) {
1288
0
        goto restore;
1289
0
    }
1290
6.66M
    PyAttributeErrorObject* the_exc = (PyAttributeErrorObject*) exc;
1291
    // Check if this exception was already augmented
1292
6.66M
    if (the_exc->name || the_exc->obj) {
1293
2.93M
        goto restore;
1294
2.93M
    }
1295
    // Augment the exception with the name and object
1296
3.73M
    if (PyObject_SetAttr(exc, &_Py_ID(name), name) ||
1297
3.73M
        PyObject_SetAttr(exc, &_Py_ID(obj), v)) {
1298
0
        return 1;
1299
0
    }
1300
6.66M
restore:
1301
6.66M
    PyErr_SetRaisedException(exc);
1302
6.66M
    return 0;
1303
3.73M
}
1304
1305
PyObject *
1306
PyObject_GetAttr(PyObject *v, PyObject *name)
1307
29.0M
{
1308
29.0M
    PyTypeObject *tp = Py_TYPE(v);
1309
29.0M
    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
29.0M
    PyObject* result = NULL;
1317
29.0M
    if (tp->tp_getattro != NULL) {
1318
29.0M
        result = (*tp->tp_getattro)(v, name);
1319
29.0M
    }
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
29.0M
    if (result == NULL) {
1334
2.75M
        _PyObject_SetAttributeErrorContext(v, name);
1335
2.75M
    }
1336
29.0M
    return result;
1337
29.0M
}
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
456M
{
1345
456M
    PyTypeObject *tp = Py_TYPE(v);
1346
456M
    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
456M
    if (tp->tp_getattro == _Py_type_getattro) {
1355
30.3M
        _PyStackRef result = _Py_type_getattro_stackref((PyTypeObject *)v, name, NULL);
1356
30.3M
        if (PyStackRef_IsNull(result)) {
1357
274
            _PyObject_SetAttributeErrorContext(v, name);
1358
274
        }
1359
30.3M
        return result;
1360
30.3M
    }
1361
1362
    /* Fall back to regular PyObject_GetAttr and convert to stackref */
1363
426M
    PyObject *result = NULL;
1364
426M
    if (tp->tp_getattro != NULL) {
1365
426M
        result = (*tp->tp_getattro)(v, name);
1366
426M
    }
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
426M
    if (result == NULL) {
1381
974k
        _PyObject_SetAttributeErrorContext(v, name);
1382
974k
        return PyStackRef_NULL;
1383
974k
    }
1384
425M
    return PyStackRef_FromPyObjectSteal(result);
1385
426M
}
1386
1387
int
1388
PyObject_GetOptionalAttr(PyObject *v, PyObject *name, PyObject **result)
1389
90.3M
{
1390
90.3M
    PyTypeObject *tp = Py_TYPE(v);
1391
1392
90.3M
    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
90.3M
    if (tp->tp_getattro == PyObject_GenericGetAttr) {
1401
78.0M
        *result = _PyObject_GenericGetAttrWithDict(v, name, NULL, 1);
1402
78.0M
        if (*result != NULL) {
1403
73.6M
            return 1;
1404
73.6M
        }
1405
4.42M
        if (PyErr_Occurred()) {
1406
24
            return -1;
1407
24
        }
1408
4.42M
        return 0;
1409
4.42M
    }
1410
12.3M
    if (tp->tp_getattro == _Py_type_getattro) {
1411
570k
        int suppress_missing_attribute_exception = 0;
1412
570k
        *result = _Py_type_getattro_impl((PyTypeObject*)v, name, &suppress_missing_attribute_exception);
1413
570k
        if (suppress_missing_attribute_exception) {
1414
            // return 0 without having to clear the exception
1415
402k
            return 0;
1416
402k
        }
1417
570k
    }
1418
11.7M
    else if (tp->tp_getattro == (getattrofunc)_Py_module_getattro) {
1419
        // optimization: suppress attribute error from module getattro method
1420
8.48M
        *result = _Py_module_getattro_impl((PyModuleObject*)v, name, 1);
1421
8.48M
        if (*result != NULL) {
1422
7.00M
            return 1;
1423
7.00M
        }
1424
1.48M
        if (PyErr_Occurred()) {
1425
0
            return -1;
1426
0
        }
1427
1.48M
        return 0;
1428
1.48M
    }
1429
3.25M
    else if (tp->tp_getattro != NULL) {
1430
3.25M
        *result = (*tp->tp_getattro)(v, name);
1431
3.25M
    }
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
3.41M
    if (*result != NULL) {
1446
3.41M
        return 1;
1447
3.41M
    }
1448
1.54k
    if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
1449
0
        return -1;
1450
0
    }
1451
1.54k
    PyErr_Clear();
1452
1.54k
    return 0;
1453
1.54k
}
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
1.86M
{
1483
1.86M
    PyObject *res;
1484
1.86M
    int rc = PyObject_GetOptionalAttr(obj, name, &res);
1485
1.86M
    Py_XDECREF(res);
1486
1.86M
    return rc;
1487
1.86M
}
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
77.0M
{
1506
77.0M
    PyThreadState *tstate = _PyThreadState_GET();
1507
77.0M
    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
77.0M
    PyTypeObject *tp = Py_TYPE(v);
1517
77.0M
    int err;
1518
1519
77.0M
    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
77.0M
    Py_INCREF(name);
1526
1527
77.0M
    _PyUnicode_InternMortal(tstate->interp, &name);
1528
77.0M
    if (tp->tp_setattro != NULL) {
1529
77.0M
        err = (*tp->tp_setattro)(v, name, value);
1530
77.0M
        Py_DECREF(name);
1531
77.0M
        return err;
1532
77.0M
    }
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
409k
{
1565
409k
    return PyObject_SetAttr(v, name, NULL);
1566
409k
}
1567
1568
PyObject **
1569
_PyObject_ComputedDictPointer(PyObject *obj)
1570
308M
{
1571
308M
    PyTypeObject *tp = Py_TYPE(obj);
1572
308M
    assert((tp->tp_flags & Py_TPFLAGS_MANAGED_DICT) == 0);
1573
1574
308M
    Py_ssize_t dictoffset = tp->tp_dictoffset;
1575
308M
    if (dictoffset == 0) {
1576
257M
        return NULL;
1577
257M
    }
1578
1579
50.2M
    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
50.2M
    return (PyObject **) ((char *)obj + dictoffset);
1594
308M
}
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
91.4M
{
1623
91.4M
    return Py_NewRef(obj);
1624
91.4M
}
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
45.9M
{
1747
45.9M
    int meth_found = 0;
1748
1749
45.9M
    assert(PyStackRef_IsNull(*method));
1750
1751
45.9M
    PyTypeObject *tp = Py_TYPE(obj);
1752
45.9M
    if (!_PyType_IsReady(tp)) {
1753
0
        if (PyType_Ready(tp) < 0) {
1754
0
            return 0;
1755
0
        }
1756
0
    }
1757
1758
45.9M
    if (tp->tp_getattro != PyObject_GenericGetAttr || !PyUnicode_CheckExact(name)) {
1759
14.0M
        PyObject *res = PyObject_GetAttr(obj, name);
1760
14.0M
        if (res != NULL) {
1761
14.0M
            *method = PyStackRef_FromPyObjectSteal(res);
1762
14.0M
        }
1763
14.0M
        return 0;
1764
14.0M
    }
1765
1766
31.9M
    _PyType_LookupStackRefAndVersion(tp, name, method);
1767
31.9M
    PyObject *descr = PyStackRef_AsPyObjectBorrow(*method);
1768
31.9M
    descrgetfunc f = NULL;
1769
31.9M
    if (descr != NULL) {
1770
31.9M
        if (_PyType_HasFeature(Py_TYPE(descr), Py_TPFLAGS_METHOD_DESCRIPTOR)) {
1771
31.2M
            meth_found = 1;
1772
31.2M
        }
1773
689k
        else {
1774
689k
            f = Py_TYPE(descr)->tp_descr_get;
1775
689k
            if (f != NULL && PyDescr_IsData(descr)) {
1776
43.8k
                PyObject *value = f(descr, obj, (PyObject *)Py_TYPE(obj));
1777
43.8k
                PyStackRef_CLEAR(*method);
1778
43.8k
                if (value != NULL) {
1779
43.8k
                    *method = PyStackRef_FromPyObjectSteal(value);
1780
43.8k
                }
1781
43.8k
                return 0;
1782
43.8k
            }
1783
689k
        }
1784
31.9M
    }
1785
31.9M
    PyObject *dict, *attr;
1786
31.9M
    if ((tp->tp_flags & Py_TPFLAGS_INLINE_VALUES) &&
1787
27.0M
         _PyObject_TryGetInstanceAttribute(obj, name, &attr)) {
1788
1.45M
        if (attr != NULL) {
1789
267
           PyStackRef_CLEAR(*method);
1790
267
           *method = PyStackRef_FromPyObjectSteal(attr);
1791
267
           return 0;
1792
267
        }
1793
1.45M
        dict = NULL;
1794
1.45M
    }
1795
30.4M
    else if ((tp->tp_flags & Py_TPFLAGS_MANAGED_DICT)) {
1796
27.5M
        dict = (PyObject *)_PyObject_GetManagedDict(obj);
1797
27.5M
    }
1798
2.97M
    else {
1799
2.97M
        PyObject **dictptr = _PyObject_ComputedDictPointer(obj);
1800
2.97M
        if (dictptr != NULL) {
1801
1.46M
            dict = FT_ATOMIC_LOAD_PTR_ACQUIRE(*dictptr);
1802
1.46M
        }
1803
1.51M
        else {
1804
1.51M
            dict = NULL;
1805
1.51M
        }
1806
2.97M
    }
1807
31.9M
    if (dict != NULL) {
1808
28.3M
        assert(PyUnicode_CheckExact(name));
1809
28.3M
        int found = _PyDict_GetMethodStackRef((PyDictObject *)dict, name, method);
1810
28.3M
        if (found < 0) {
1811
0
            assert(PyStackRef_IsNull(*method));
1812
0
            return -1;
1813
0
        }
1814
28.3M
        else if (found) {
1815
23
            return 0;
1816
23
        }
1817
28.3M
    }
1818
1819
31.9M
    if (meth_found) {
1820
31.2M
        assert(!PyStackRef_IsNull(*method));
1821
31.2M
        return 1;
1822
31.2M
    }
1823
1824
645k
    if (f != NULL) {
1825
417k
        PyObject *value = f(descr, obj, (PyObject *)Py_TYPE(obj));
1826
417k
        PyStackRef_CLEAR(*method);
1827
417k
        if (value) {
1828
417k
            *method = PyStackRef_FromPyObjectSteal(value);
1829
417k
        }
1830
417k
        return 0;
1831
417k
    }
1832
1833
228k
    if (descr != NULL) {
1834
228k
        assert(!PyStackRef_IsNull(*method));
1835
228k
        return 0;
1836
228k
    }
1837
1838
5
    PyErr_Format(PyExc_AttributeError,
1839
5
                 "'%.100s' object has no attribute '%U'",
1840
5
                 tp->tp_name, name);
1841
1842
5
    _PyObject_SetAttributeErrorContext(obj, name);
1843
5
    assert(PyStackRef_IsNull(*method));
1844
5
    return 0;
1845
228k
}
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
516M
{
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
516M
    PyTypeObject *tp = Py_TYPE(obj);
1861
516M
    PyObject *descr = NULL;
1862
516M
    PyObject *res = NULL;
1863
516M
    descrgetfunc f;
1864
1865
516M
    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
516M
    if (!_PyType_IsReady(tp)) {
1873
0
        if (PyType_Ready(tp) < 0)
1874
0
            return NULL;
1875
0
    }
1876
1877
516M
    Py_INCREF(name);
1878
1879
516M
    PyThreadState *tstate = _PyThreadState_GET();
1880
516M
    _PyCStackRef cref;
1881
516M
    _PyThreadState_PushCStackRef(tstate, &cref);
1882
1883
516M
    _PyType_LookupStackRefAndVersion(tp, name, &cref.ref);
1884
516M
    descr = PyStackRef_AsPyObjectBorrow(cref.ref);
1885
1886
516M
    f = NULL;
1887
516M
    if (descr != NULL) {
1888
414M
        f = Py_TYPE(descr)->tp_descr_get;
1889
414M
        if (f != NULL && PyDescr_IsData(descr)) {
1890
76.1M
            res = f(descr, obj, (PyObject *)Py_TYPE(obj));
1891
76.1M
            if (res == NULL && suppress &&
1892
22.7k
                    PyErr_ExceptionMatches(PyExc_AttributeError)) {
1893
22.7k
                PyErr_Clear();
1894
22.7k
            }
1895
76.1M
            goto done;
1896
76.1M
        }
1897
414M
    }
1898
440M
    if (dict == NULL) {
1899
440M
        if ((tp->tp_flags & Py_TPFLAGS_INLINE_VALUES)) {
1900
154M
            if (PyUnicode_CheckExact(name) &&
1901
154M
                _PyObject_TryGetInstanceAttribute(obj, name, &res)) {
1902
75.9M
                if (res != NULL) {
1903
40.3M
                    goto done;
1904
40.3M
                }
1905
75.9M
            }
1906
78.1M
            else {
1907
78.1M
                dict = (PyObject *)_PyObject_MaterializeManagedDict(obj);
1908
78.1M
                if (dict == NULL) {
1909
0
                    res = NULL;
1910
0
                    goto done;
1911
0
                }
1912
78.1M
            }
1913
154M
        }
1914
286M
        else if ((tp->tp_flags & Py_TPFLAGS_MANAGED_DICT)) {
1915
4.66M
            dict = (PyObject *)_PyObject_GetManagedDict(obj);
1916
4.66M
        }
1917
281M
        else {
1918
281M
            PyObject **dictptr = _PyObject_ComputedDictPointer(obj);
1919
281M
            if (dictptr) {
1920
#ifdef Py_GIL_DISABLED
1921
                dict = _Py_atomic_load_ptr_acquire(dictptr);
1922
#else
1923
25.5M
                dict = *dictptr;
1924
25.5M
#endif
1925
25.5M
            }
1926
281M
        }
1927
440M
    }
1928
400M
    if (dict != NULL) {
1929
107M
        Py_INCREF(dict);
1930
107M
        int rc = PyDict_GetItemRef(dict, name, &res);
1931
107M
        Py_DECREF(dict);
1932
107M
        if (res != NULL) {
1933
91.4M
            goto done;
1934
91.4M
        }
1935
15.9M
        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
107M
    }
1944
1945
308M
    if (f != NULL) {
1946
282M
        res = f(descr, obj, (PyObject *)Py_TYPE(obj));
1947
282M
        if (res == NULL && suppress &&
1948
0
                PyErr_ExceptionMatches(PyExc_AttributeError)) {
1949
0
            PyErr_Clear();
1950
0
        }
1951
282M
        goto done;
1952
282M
    }
1953
1954
26.5M
    if (descr != NULL) {
1955
14.7M
        res = PyStackRef_AsPyObjectSteal(cref.ref);
1956
14.7M
        cref.ref = PyStackRef_NULL;
1957
14.7M
        goto done;
1958
14.7M
    }
1959
1960
11.7M
    if (!suppress) {
1961
2.94M
        PyErr_Format(PyExc_AttributeError,
1962
2.94M
                     "'%.100s' object has no attribute '%U'",
1963
2.94M
                     tp->tp_name, name);
1964
1965
2.94M
        _PyObject_SetAttributeErrorContext(obj, name);
1966
2.94M
    }
1967
516M
  done:
1968
516M
    _PyThreadState_PopCStackRef(tstate, &cref);
1969
516M
    Py_DECREF(name);
1970
516M
    return res;
1971
11.7M
}
1972
1973
PyObject *
1974
PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1975
415M
{
1976
415M
    return _PyObject_GenericGetAttrWithDict(obj, name, NULL, 0);
1977
415M
}
1978
1979
int
1980
_PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
1981
                                 PyObject *value, PyObject *dict)
1982
76.2M
{
1983
76.2M
    PyTypeObject *tp = Py_TYPE(obj);
1984
76.2M
    PyObject *descr;
1985
76.2M
    descrsetfunc f;
1986
76.2M
    int res = -1;
1987
1988
76.2M
    assert(!PyType_IsSubtype(tp, &PyType_Type));
1989
76.2M
    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
76.2M
    if (!_PyType_IsReady(tp) && PyType_Ready(tp) < 0) {
1997
0
        return -1;
1998
0
    }
1999
2000
76.2M
    Py_INCREF(name);
2001
76.2M
    Py_INCREF(tp);
2002
2003
76.2M
    PyThreadState *tstate = _PyThreadState_GET();
2004
76.2M
    _PyCStackRef cref;
2005
76.2M
    _PyThreadState_PushCStackRef(tstate, &cref);
2006
2007
76.2M
    _PyType_LookupStackRefAndVersion(tp, name, &cref.ref);
2008
76.2M
    descr = PyStackRef_AsPyObjectBorrow(cref.ref);
2009
2010
76.2M
    if (descr != NULL) {
2011
40.1M
        f = Py_TYPE(descr)->tp_descr_set;
2012
40.1M
        if (f != NULL) {
2013
11.6M
            res = f(descr, obj, value);
2014
11.6M
            goto done;
2015
11.6M
        }
2016
40.1M
    }
2017
2018
64.6M
    if (dict == NULL) {
2019
63.8M
        PyObject **dictptr;
2020
2021
63.8M
        if ((tp->tp_flags & Py_TPFLAGS_INLINE_VALUES)) {
2022
40.5M
            res = _PyObject_StoreInstanceAttribute(obj, name, value);
2023
40.5M
            goto error_check;
2024
40.5M
        }
2025
2026
23.2M
        if ((tp->tp_flags & Py_TPFLAGS_MANAGED_DICT)) {
2027
54.5k
            PyManagedDictPointer *managed_dict = _PyObject_ManagedDictPointer(obj);
2028
54.5k
            dictptr = (PyObject **)&managed_dict->dict;
2029
54.5k
        }
2030
23.2M
        else {
2031
23.2M
            dictptr = _PyObject_ComputedDictPointer(obj);
2032
23.2M
        }
2033
23.2M
        if (dictptr == NULL) {
2034
8
            if (descr == NULL) {
2035
8
                if (tp->tp_setattro == PyObject_GenericSetAttr) {
2036
8
                    PyErr_Format(PyExc_AttributeError,
2037
8
                                "'%.100s' object has no attribute '%U' and no "
2038
8
                                "__dict__ for setting new attributes",
2039
8
                                tp->tp_name, name);
2040
8
                }
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
8
                _PyObject_SetAttributeErrorContext(obj, name);
2047
8
            }
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
8
            goto done;
2054
8
        }
2055
23.2M
        else {
2056
23.2M
            res = _PyObjectDict_SetItem(tp, obj, dictptr, name, value);
2057
23.2M
        }
2058
23.2M
    }
2059
774k
    else {
2060
774k
        Py_INCREF(dict);
2061
774k
        if (value == NULL)
2062
0
            res = PyDict_DelItem(dict, name);
2063
774k
        else
2064
774k
            res = PyDict_SetItem(dict, name, value);
2065
774k
        Py_DECREF(dict);
2066
774k
    }
2067
64.6M
  error_check:
2068
64.6M
    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
76.2M
  done:
2075
76.2M
    _PyThreadState_PopCStackRef(tstate, &cref);
2076
76.2M
    Py_DECREF(tp);
2077
76.2M
    Py_DECREF(name);
2078
76.2M
    return res;
2079
64.6M
}
2080
2081
int
2082
PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
2083
75.5M
{
2084
75.5M
    return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL);
2085
75.5M
}
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
142M
{
2104
142M
    Py_ssize_t res;
2105
142M
    if (v == Py_True)
2106
15.6M
        return 1;
2107
126M
    if (v == Py_False)
2108
22.4M
        return 0;
2109
104M
    if (v == Py_None)
2110
5.05M
        return 0;
2111
99.2M
    else if (Py_TYPE(v)->tp_as_number != NULL &&
2112
83.6M
             Py_TYPE(v)->tp_as_number->nb_bool != NULL)
2113
1.68M
        res = (*Py_TYPE(v)->tp_as_number->nb_bool)(v);
2114
97.5M
    else if (Py_TYPE(v)->tp_as_mapping != NULL &&
2115
88.9M
             Py_TYPE(v)->tp_as_mapping->mp_length != NULL)
2116
33.7M
        res = (*Py_TYPE(v)->tp_as_mapping->mp_length)(v);
2117
63.8M
    else if (Py_TYPE(v)->tp_as_sequence != NULL &&
2118
55.2M
             Py_TYPE(v)->tp_as_sequence->sq_length != NULL)
2119
51.6M
        res = (*Py_TYPE(v)->tp_as_sequence->sq_length)(v);
2120
12.1M
    else
2121
12.1M
        return 1;
2122
    /* if it is negative, it should be either -1 or -2 */
2123
87.0M
    return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
2124
104M
}
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
10.5M
{
2144
10.5M
    if (x == NULL)
2145
0
        return 0;
2146
10.5M
    return Py_TYPE(x)->tp_call != NULL;
2147
10.5M
}
2148
2149
2150
/* Helper for PyObject_Dir without arguments: returns the local scope. */
2151
static PyObject *
2152
_dir_locals(void)
2153
4
{
2154
4
    PyObject *names;
2155
4
    PyObject *locals;
2156
2157
4
    if (_PyEval_GetFrame() != NULL) {
2158
4
        locals = _PyEval_GetFrameLocals();
2159
4
    }
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
4
    if (locals == NULL) {
2174
0
        return NULL;
2175
0
    }
2176
2177
4
    names = PyMapping_Keys(locals);
2178
4
    Py_DECREF(locals);
2179
4
    if (!names) {
2180
0
        return NULL;
2181
0
    }
2182
4
    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
4
    if (PyList_Sort(names)) {
2190
0
        Py_DECREF(names);
2191
0
        return NULL;
2192
0
    }
2193
4
    return names;
2194
4
}
2195
2196
/* Helper for PyObject_Dir: object introspection. */
2197
static PyObject *
2198
_dir_object(PyObject *obj)
2199
6.09k
{
2200
6.09k
    PyObject *result, *sorted;
2201
6.09k
    PyObject *dirfunc = _PyObject_LookupSpecial(obj, &_Py_ID(__dir__));
2202
2203
6.09k
    assert(obj != NULL);
2204
6.09k
    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
6.09k
    result = _PyObject_CallNoArgs(dirfunc);
2211
6.09k
    Py_DECREF(dirfunc);
2212
6.09k
    if (result == NULL)
2213
0
        return NULL;
2214
    /* return sorted(result) */
2215
6.09k
    sorted = PySequence_List(result);
2216
6.09k
    Py_DECREF(result);
2217
6.09k
    if (sorted == NULL)
2218
0
        return NULL;
2219
6.09k
    if (PyList_Sort(sorted)) {
2220
0
        Py_DECREF(sorted);
2221
0
        return NULL;
2222
0
    }
2223
6.09k
    return sorted;
2224
6.09k
}
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
6.09k
{
2233
6.09k
    return (obj == NULL) ? _dir_locals() : _dir_object(obj);
2234
6.09k
}
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
92.6k
{
2246
92.6k
    return PyUnicode_FromString("None");
2247
92.6k
}
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
107k
{
2277
107k
    return 0xFCA86420;
2278
107k
}
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
34
{
2469
#ifdef Py_TRACE_REFS
2470
    if (refchain_init(interp) < 0) {
2471
        return _PyStatus_NO_MEMORY();
2472
    }
2473
#endif
2474
34
    return _PyStatus_OK();
2475
34
}
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
34
{
2631
    // All other static types (unless initialized elsewhere)
2632
4.04k
    for (size_t i=0; i < Py_ARRAY_LENGTH(static_types); i++) {
2633
4.01k
        PyTypeObject *type = static_types[i];
2634
4.01k
        if (_PyStaticType_InitBuiltin(interp, type) < 0) {
2635
0
            return _PyStatus_ERR("Can't initialize builtin type");
2636
0
        }
2637
4.01k
        if (type == &PyType_Type) {
2638
            // Sanitify checks of the two most important types
2639
34
            assert(PyBaseObject_Type.tp_base == NULL);
2640
34
            assert(PyType_Type.tp_base == &PyBaseObject_Type);
2641
34
        }
2642
4.01k
    }
2643
2644
    // Cache __reduce__ from PyBaseObject_Type object
2645
34
    PyObject *baseobj_dict = _PyType_GetDict(&PyBaseObject_Type);
2646
34
    PyObject *baseobj_reduce = PyDict_GetItemWithError(baseobj_dict, &_Py_ID(__reduce__));
2647
34
    if (baseobj_reduce == NULL && PyErr_Occurred()) {
2648
0
        return _PyStatus_ERR("Can't get __reduce__ from base object");
2649
0
    }
2650
34
    _Py_INTERP_CACHED_OBJECT(interp, objreduce) = baseobj_reduce;
2651
2652
    // Must be after static types are initialized
2653
34
    if (_Py_initialize_generic(interp) < 0) {
2654
0
        return _PyStatus_ERR("Can't initialize generic types");
2655
0
    }
2656
2657
34
    return _PyStatus_OK();
2658
34
}
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
3.96G
{
2682
    // Skip the immortal object check in Py_SET_REFCNT; always set refcnt to 1
2683
3.96G
#if !defined(Py_GIL_DISABLED)
2684
3.96G
#if SIZEOF_VOID_P > 4
2685
3.96G
    op->ob_refcnt_full = 1;
2686
3.96G
    assert(op->ob_refcnt == 1);
2687
3.96G
    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
3.96G
    _PyReftracerTrack(op, PyRefTracer_CREATE);
2710
3.96G
}
2711
2712
void
2713
_Py_NewReference(PyObject *op)
2714
3.89G
{
2715
#ifdef Py_REF_DEBUG
2716
    _Py_IncRefTotal(_PyThreadState_GET());
2717
#endif
2718
3.89G
    new_reference(op);
2719
3.89G
}
2720
2721
void
2722
_Py_NewReferenceNoTotal(PyObject *op)
2723
68.4M
{
2724
68.4M
    new_reference(op);
2725
68.4M
}
2726
2727
void
2728
_Py_SetImmortalUntracked(PyObject *op)
2729
296k
{
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
296k
    if (_Py_IsImmortal(op)) {
2739
102
        return;
2740
102
    }
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
296k
    op->ob_flags = _Py_IMMORTAL_FLAGS;
2748
296k
    op->ob_refcnt = _Py_IMMORTAL_INITIAL_REFCNT;
2749
#else
2750
    op->ob_refcnt = _Py_IMMORTAL_INITIAL_REFCNT;
2751
#endif
2752
296k
}
2753
2754
void
2755
_Py_SetImmortal(PyObject *op)
2756
296k
{
2757
296k
    if (PyObject_IS_GC(op) && _PyObject_GC_IS_TRACKED(op)) {
2758
13.9k
        _PyObject_GC_UNTRACK(op);
2759
13.9k
    }
2760
296k
    _Py_SetImmortalUntracked(op);
2761
296k
}
2762
2763
void
2764
_PyObject_SetDeferredRefcount(PyObject *op)
2765
224k
{
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
224k
}
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
3.71M
{
3063
3.71M
    PyObject *dict;
3064
3.71M
    PyObject *list;
3065
3.71M
    Py_ssize_t i;
3066
3067
3.71M
    dict = PyThreadState_GetDict();
3068
    /* Ignore a missing thread-state, so that this function can be called
3069
       early on startup. */
3070
3.71M
    if (dict == NULL)
3071
0
        return 0;
3072
3.71M
    list = PyDict_GetItemWithError(dict, &_Py_ID(Py_Repr));
3073
3.71M
    if (list == NULL) {
3074
4
        if (PyErr_Occurred()) {
3075
0
            return -1;
3076
0
        }
3077
4
        list = PyList_New(0);
3078
4
        if (list == NULL)
3079
0
            return -1;
3080
4
        if (PyDict_SetItem(dict, &_Py_ID(Py_Repr), list) < 0)
3081
0
            return -1;
3082
4
        Py_DECREF(list);
3083
4
    }
3084
3.71M
    i = PyList_GET_SIZE(list);
3085
73.2M
    while (--i >= 0) {
3086
69.5M
        if (PyList_GET_ITEM(list, i) == obj)
3087
0
            return 1;
3088
69.5M
    }
3089
3.71M
    if (PyList_Append(list, obj) < 0)
3090
0
        return -1;
3091
3.71M
    return 0;
3092
3.71M
}
3093
3094
void
3095
Py_ReprLeave(PyObject *obj)
3096
3.71M
{
3097
3.71M
    PyObject *dict;
3098
3.71M
    PyObject *list;
3099
3.71M
    Py_ssize_t i;
3100
3101
3.71M
    PyObject *exc = PyErr_GetRaisedException();
3102
3103
3.71M
    dict = PyThreadState_GetDict();
3104
3.71M
    if (dict == NULL)
3105
0
        goto finally;
3106
3107
3.71M
    list = PyDict_GetItemWithError(dict, &_Py_ID(Py_Repr));
3108
3.71M
    if (list == NULL || !PyList_Check(list))
3109
0
        goto finally;
3110
3111
3.71M
    i = PyList_GET_SIZE(list);
3112
    /* Count backwards because we always expect obj to be list[-1] */
3113
3.71M
    while (--i >= 0) {
3114
3.71M
        if (PyList_GET_ITEM(list, i) == obj) {
3115
3.71M
            PyList_SetSlice(list, i, i + 1, NULL);
3116
3.71M
            break;
3117
3.71M
        }
3118
3.71M
    }
3119
3120
3.71M
finally:
3121
    /* ignore exceptions because there is no way to report them. */
3122
3.71M
    PyErr_SetRaisedException(exc);
3123
3.71M
}
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
16.7k
{
3134
16.7k
    _PyObject_ASSERT(op, Py_REFCNT(op) == 0);
3135
16.7k
    PyTypeObject *tp = Py_TYPE(op);
3136
16.7k
    assert(tp->tp_flags & Py_TPFLAGS_HAVE_GC);
3137
16.7k
    int tracked = 0;
3138
16.7k
    if (tp->tp_is_gc == NULL || tp->tp_is_gc(op)) {
3139
16.7k
        tracked = _PyObject_GC_IS_TRACKED(op);
3140
16.7k
        if (tracked) {
3141
16.7k
            _PyObject_GC_UNTRACK(op);
3142
16.7k
        }
3143
16.7k
    }
3144
16.7k
    uintptr_t tagged_ptr = ((uintptr_t)tstate->delete_later) | tracked;
3145
#ifdef Py_GIL_DISABLED
3146
    op->ob_tid = tagged_ptr;
3147
#else
3148
16.7k
    _Py_AS_GC(op)->_gc_next = tagged_ptr;
3149
16.7k
#endif
3150
16.7k
    tstate->delete_later = op;
3151
16.7k
}
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
77
{
3158
16.8k
    while (tstate->delete_later) {
3159
16.7k
        PyObject *op = tstate->delete_later;
3160
16.7k
        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
16.7k
        uintptr_t tagged_ptr = _Py_AS_GC(op)->_gc_next;
3168
16.7k
        _Py_AS_GC(op)->_gc_next = 0;
3169
16.7k
#endif
3170
16.7k
        tstate->delete_later = (PyObject *)(tagged_ptr & ~1);
3171
16.7k
        if (tagged_ptr & 1) {
3172
16.7k
            _PyObject_GC_TRACK(op);
3173
16.7k
        }
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
16.7k
        _PyObject_ASSERT(op, Py_REFCNT(op) == 0);
3181
16.7k
        (*dealloc)(op);
3182
16.7k
    }
3183
77
}
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
3.50G
{
3246
3.50G
    PyTypeObject *type = Py_TYPE(op);
3247
3.50G
    unsigned long gc_flag = type->tp_flags & Py_TPFLAGS_HAVE_GC;
3248
3.50G
    destructor dealloc = type->tp_dealloc;
3249
3.50G
    PyThreadState *tstate = _PyThreadState_GET();
3250
3.50G
    intptr_t margin = _Py_RecursionLimit_GetMargin(tstate);
3251
3.50G
    if (margin < 2 && gc_flag) {
3252
16.7k
        _PyTrash_thread_deposit_object(tstate, (PyObject *)op);
3253
16.7k
        return;
3254
16.7k
    }
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
3.50G
    _PyReftracerTrack(op, PyRefTracer_DESTROY);
3273
3.50G
    (*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
3.50G
    if (tstate->delete_later && margin >= 4 && gc_flag) {
3298
77
        _PyTrash_thread_destroy_chain(tstate);
3299
77
    }
3300
3.50G
}
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
34
{
3404
34
    constants[Py_CONSTANT_ZERO] = _PyLong_GetZero();
3405
34
    constants[Py_CONSTANT_ONE] = _PyLong_GetOne();
3406
34
    constants[Py_CONSTANT_EMPTY_STR] = PyUnicode_New(0, 0);
3407
34
    constants[Py_CONSTANT_EMPTY_BYTES] = PyBytes_FromStringAndSize(NULL, 0);
3408
34
    constants[Py_CONSTANT_EMPTY_TUPLE] = PyTuple_New(0);
3409
#ifndef NDEBUG
3410
    for (size_t i=0; i < Py_ARRAY_LENGTH(constants); i++) {
3411
        assert(constants[i] != NULL);
3412
        assert(_Py_IsImmortal(constants[i]));
3413
    }
3414
#endif
3415
34
}
3416
3417
PyObject*
3418
Py_GetConstant(unsigned int constant_id)
3419
17.9M
{
3420
17.9M
    if (constant_id < Py_ARRAY_LENGTH(constants)) {
3421
17.9M
        return constants[constant_id];
3422
17.9M
    }
3423
0
    else {
3424
0
        PyErr_BadInternalCall();
3425
0
        return NULL;
3426
0
    }
3427
17.9M
}
3428
3429
3430
PyObject*
3431
Py_GetConstantBorrowed(unsigned int constant_id)
3432
0
{
3433
    // All constants are immortal
3434
0
    return Py_GetConstant(constant_id);
3435
0
}
3436
3437
int
3438
PyUnstable_IsImmortal(PyObject *op)
3439
0
{
3440
    /* Checking a reference count requires a thread state */
3441
0
    _Py_AssertHoldsTstate();
3442
0
    assert(op != NULL);
3443
0
    return _Py_IsImmortal(op);
3444
0
}
3445
3446
int
3447
PyUnstable_Object_IsUniquelyReferenced(PyObject *op)
3448
0
{
3449
0
    _Py_AssertHoldsTstate();
3450
0
    assert(op != NULL);
3451
0
    return _PyObject_IsUniquelyReferenced(op);
3452
0
}
3453
3454
int
3455
_PyObject_VisitType(PyObject *op, visitproc visit, void *arg)
3456
498k
{
3457
498k
    assert(op != NULL);
3458
498k
    PyTypeObject *tp = Py_TYPE(op);
3459
498k
    _PyObject_ASSERT((PyObject *)tp, PyType_HasFeature(tp, Py_TPFLAGS_HEAPTYPE));
3460
498k
    Py_VISIT(tp);
3461
498k
    return 0;
3462
498k
}
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); }