Coverage Report

Created: 2026-12-01 06:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Modules/_abc.c
Line
Count
Source
1
/* ABCMeta implementation */
2
#ifndef Py_BUILD_CORE_BUILTIN
3
#  define Py_BUILD_CORE_MODULE 1
4
#endif
5
6
#include "Python.h"
7
#include "pycore_critical_section.h"  // Py_BEGIN_CRITICAL_SECTION()
8
#include "pycore_moduleobject.h"      // _PyModule_GetState()
9
#include "pycore_object.h"            // _PyType_LookupStackRefAndVersion()
10
#include "pycore_object_deferred.h"   // _PyObject_SetDeferredRefcount()
11
#include "pycore_pyatomic_ft_wrappers.h"  // FT_ATOMIC_LOAD_PTR_ACQUIRE()
12
#include "pycore_pymem.h"             // _PyMem_FreeDelayed()
13
#include "pycore_pystate.h"           // _PyThreadState_GET()
14
#include "pycore_runtime.h"           // _Py_ID()
15
#include "pycore_stackref.h"          // _PyStackRef
16
#include "pycore_typeobject.h"        // _PyType_GetSubclasses()
17
#include "pycore_pyhash.h"
18
#include "clinic/_abc.c.h"
19
20
/*[clinic input]
21
module _abc
22
[clinic start generated code]*/
23
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=964f5328e1aefcda]*/
24
25
PyDoc_STRVAR(_abc__doc__,
26
"Module contains faster C implementation of abc.ABCMeta");
27
28
typedef struct {
29
    PyTypeObject *_abc_data_type;
30
    uint64_t abc_invalidation_counter;
31
    // Default implementations, compared by identity to skip the call
32
    // when a class doesn't override them.
33
    PyObject *object_class_descr;
34
    PyObject *object_subclasshook;
35
    PyObject *type_subclasses;
36
    // ABCMeta.__subclasscheck__, set by abc.py on import. Classes using it
37
    // are checked directly instead of going through issubclass().
38
    PyObject *subclasscheck_func;
39
} _abcmodule_state;
40
41
static inline _abcmodule_state*
42
get_abc_state(PyObject *module)
43
92.4k
{
44
92.4k
    void *state = _PyModule_GetState(module);
45
92.4k
    assert(state != NULL);
46
92.4k
    return (_abcmodule_state *)state;
47
92.4k
}
48
49
static inline uint64_t
50
get_invalidation_counter(_abcmodule_state *state)
51
66.7k
{
52
66.7k
    return FT_ATOMIC_LOAD_UINT64_RELAXED(state->abc_invalidation_counter);
53
66.7k
}
54
55
static inline void
56
increment_invalidation_counter(_abcmodule_state *state)
57
989
{
58
989
    FT_ATOMIC_ADD_UINT64(state->abc_invalidation_counter, 1);
59
989
}
60
61
62
// The registry and the caches of an ABC are sets of classes, stored as
63
// open addressed hash tables keyed by the address of the class.
64
//
65
// Each entry also holds a weakref to the class. It is only used to check
66
// that the class is still alive, as the address of a dead class can be
67
// reused by a new one. The weakrefs have no callback, so the same weakref
68
// is shared by all the tables a class is in, and dead entries are only
69
// removed when the table is rebuilt.
70
typedef struct {
71
    PyObject *key;   /* borrowed ref of a class */
72
    PyObject *ref;   /* weakref to key */
73
} abc_entry;
74
75
typedef struct {
76
    size_t mask;     /* number of entries - 1 */
77
    size_t used;     /* entries with a key, live or dead */
78
    abc_entry entries[];
79
} abc_table;
80
81
1.75k
#define TABLE_MIN_SIZE 8
82
4.41k
#define PERTURB_SHIFT 5
83
84
// Shared empty table, so that lookups don't need a NULL check.
85
// It is never modified or freed.
86
static const abc_table empty_table_struct = {
87
    0,              /* mask */
88
    0,              /* used */
89
    {{NULL, NULL}}, /* entries */
90
};
91
92
9.14k
#define EMPTY_TABLE ((abc_table *)&empty_table_struct)
93
94
static inline size_t
95
abc_table_nbytes(size_t size)
96
2.40k
{
97
2.40k
    return offsetof(abc_table, entries) + size * sizeof(abc_entry);
98
2.40k
}
99
100
static abc_table *
101
abc_table_new(size_t size)
102
1.75k
{
103
1.75k
    assert((size & (size - 1)) == 0 && size >= TABLE_MIN_SIZE);
104
1.75k
    abc_table *table = PyMem_Calloc(1, abc_table_nbytes(size));
105
1.75k
    if (table == NULL) {
106
0
        PyErr_NoMemory();
107
0
        return NULL;
108
0
    }
109
1.75k
    table->mask = size - 1;
110
1.75k
    table->used = 0;
111
1.75k
    return table;
112
1.75k
}
113
114
// Free a table and its weakrefs. Use delayed if other threads
115
// can still be reading the table.
116
static void
117
abc_table_release(abc_table *table, int delayed)
118
583
{
119
583
    if (table == EMPTY_TABLE) {
120
0
        return;
121
0
    }
122
5.24k
    for (size_t i = 0; i <= table->mask; i++) {
123
4.66k
        PyObject *ref = table->entries[i].ref;
124
4.66k
        if (delayed) {
125
4.66k
            _PyObject_XDecRefDelayed(ref);
126
4.66k
        }
127
0
        else {
128
0
            Py_XDECREF(ref);
129
0
        }
130
4.66k
    }
131
583
    if (delayed) {
132
583
        _PyMem_FreeDelayed(table, abc_table_nbytes(table->mask + 1));
133
583
    }
134
0
    else {
135
0
        PyMem_Free(table);
136
0
    }
137
583
}
138
139
static inline size_t
140
abc_hash(PyObject *key)
141
157k
{
142
157k
    return (size_t)_Py_HashPointerRaw(key);
143
157k
}
144
145
static inline int
146
abc_entry_is_live(PyObject *ref, PyObject *key)
147
86.8k
{
148
    // The caller holds a strong reference to key, so a weakref pointing
149
    // to key cannot be of a dead class which was at the same address.
150
    // wr_object only changes when key dies, so a relaxed load is enough.
151
86.8k
    assert(ref != NULL);
152
86.8k
    PyWeakReference *wr = (PyWeakReference *)ref;
153
86.8k
    return FT_ATOMIC_LOAD_PTR_RELAXED(wr->wr_object) == key;
154
86.8k
}
155
156
static abc_entry *
157
abc_table_find(abc_table *table, PyObject *key, PyObject **found)
158
157k
{
159
157k
    size_t mask = table->mask;
160
157k
    size_t perturb = abc_hash(key);
161
157k
    size_t i = perturb & mask;
162
162k
    for (;;) {
163
162k
        abc_entry *entry = &table->entries[i];
164
162k
        PyObject *k = FT_ATOMIC_LOAD_PTR_ACQUIRE(entry->key);
165
162k
        if (k == NULL || k == key) {
166
157k
            *found = k;
167
157k
            return entry;
168
157k
        }
169
4.41k
        perturb >>= PERTURB_SHIFT;
170
4.41k
        i = (i * 5 + perturb + 1) & mask;
171
4.41k
    }
172
157k
}
173
174
// Lock-free, the caller must hold a strong reference to key.
175
static int
176
abc_table_contains(abc_table *table, PyObject *key)
177
152k
{
178
152k
    PyObject *found;
179
152k
    abc_entry *entry = abc_table_find(table, key, &found);
180
152k
    if (found == NULL) {
181
67.2k
        return 0;
182
67.2k
    }
183
85.7k
    PyObject *ref = FT_ATOMIC_LOAD_PTR_ACQUIRE(entry->ref);
184
85.7k
    return abc_entry_is_live(ref, key);
185
152k
}
186
187
static abc_table *
188
abc_table_rebuild(abc_table *old, size_t extra)
189
1.75k
{
190
1.75k
    size_t live = 0;
191
4.31k
    for (size_t i = 0; i <= old->mask; i++) {
192
2.56k
        abc_entry *entry = &old->entries[i];
193
2.56k
        if (entry->key != NULL && abc_entry_is_live(entry->ref, entry->key)) {
194
555
            live++;
195
555
        }
196
2.56k
    }
197
1.75k
    size_t size = TABLE_MIN_SIZE;
198
1.86k
    while (size < (live + extra) * 2) {
199
111
        size <<= 1;
200
111
    }
201
1.75k
    abc_table *table = abc_table_new(size);
202
1.75k
    if (table == NULL) {
203
0
        return NULL;
204
0
    }
205
4.31k
    for (size_t i = 0; i <= old->mask; i++) {
206
2.56k
        abc_entry *entry = &old->entries[i];
207
2.56k
        if (entry->key == NULL) {
208
2.01k
            continue;
209
2.01k
        }
210
555
        if (abc_entry_is_live(entry->ref, entry->key)) {
211
555
            PyObject *found;
212
555
            abc_entry *dst = abc_table_find(table, entry->key, &found);
213
555
            assert(found == NULL);
214
555
            dst->key = entry->key;
215
555
            dst->ref = entry->ref;
216
555
            table->used++;
217
555
        }
218
0
        else {
219
0
            _PyObject_XDecRefDelayed(entry->ref);
220
0
        }
221
555
    }
222
1.75k
    return table;
223
1.75k
}
224
225
static int
226
abc_table_add(abc_table **ptable, PyObject *key, PyObject *ref)
227
2.66k
{
228
2.66k
    abc_table *table = *ptable;
229
2.66k
    PyObject *found;
230
2.66k
    abc_entry *entry = abc_table_find(table, key, &found);
231
2.66k
    if (found == key) {
232
        // The existing weakref can be of a dead class at the same address.
233
0
        PyObject *old = entry->ref;
234
0
        if (old == ref) {
235
0
            Py_DECREF(ref);
236
0
        }
237
0
        else {
238
0
            FT_ATOMIC_STORE_PTR_RELEASE(entry->ref, ref);
239
0
            _PyObject_XDecRefDelayed(old);
240
0
        }
241
0
        return 0;
242
0
    }
243
    // Always true for EMPTY_TABLE.
244
2.66k
    if ((table->used + 1) * 3 > (table->mask + 1) * 2) {
245
1.75k
        abc_table *newtable = abc_table_rebuild(table, 1);
246
1.75k
        if (newtable == NULL) {
247
0
            Py_DECREF(ref);
248
0
            return -1;
249
0
        }
250
1.75k
        FT_ATOMIC_STORE_PTR_RELEASE(*ptable, newtable);
251
1.75k
        if (table != EMPTY_TABLE) {
252
            // The weakrefs were moved to newtable.
253
74
            _PyMem_FreeDelayed(table, abc_table_nbytes(table->mask + 1));
254
74
        }
255
1.75k
        table = newtable;
256
1.75k
        entry = abc_table_find(table, key, &found);
257
1.75k
    }
258
2.66k
    assert(found == NULL);
259
2.66k
    FT_ATOMIC_STORE_PTR_RELAXED(entry->ref, ref);
260
2.66k
    FT_ATOMIC_STORE_PTR_RELEASE(entry->key, key);
261
2.66k
    table->used++;
262
2.66k
    return 0;
263
2.66k
}
264
265
static void
266
abc_table_clear(abc_table **ptable)
267
800
{
268
800
    abc_table *table = *ptable;
269
800
    if (table != EMPTY_TABLE) {
270
583
        FT_ATOMIC_STORE_PTR_RELAXED(*ptable, EMPTY_TABLE);
271
583
        abc_table_release(table, 1);
272
583
    }
273
800
}
274
275
static PyObject *
276
abc_table_snapshot(abc_table *table)
277
1.36k
{
278
1.36k
    PyObject *list = PyList_New(0);
279
1.36k
    if (list == NULL) {
280
0
        return NULL;
281
0
    }
282
7.01k
    for (size_t i = 0; i <= table->mask; i++) {
283
5.64k
        abc_entry *entry = &table->entries[i];
284
5.64k
        if (entry->key == NULL) {
285
4.44k
            continue;
286
4.44k
        }
287
1.20k
        PyObject *obj;
288
1.20k
        if (PyWeakref_GetRef(entry->ref, &obj) < 0) {
289
0
            Py_DECREF(list);
290
0
            return NULL;
291
0
        }
292
1.20k
        if (obj == NULL) {
293
0
            continue;
294
0
        }
295
1.20k
        int rc = PyList_Append(list, obj);
296
1.20k
        Py_DECREF(obj);
297
1.20k
        if (rc < 0) {
298
0
            Py_DECREF(list);
299
0
            return NULL;
300
0
        }
301
1.20k
    }
302
1.36k
    return list;
303
1.36k
}
304
305
306
// Internal state of an ABC, stored in its _abc_impl attribute.
307
308
typedef struct {
309
    PyObject_HEAD
310
    abc_table *registry;
311
    abc_table *cache;
312
    abc_table *negative_cache;
313
    uint64_t negative_cache_version;
314
} _abc_data;
315
316
98.6k
#define _abc_data_CAST(op)  ((_abc_data *)(op))
317
318
// The version is updated after the negative cache is cleared and read
319
// before the negative cache is, so a reader which sees the new version
320
// never sees the old entries.
321
static inline uint64_t
322
get_cache_version(_abc_data *impl)
323
64.7k
{
324
64.7k
    return FT_ATOMIC_LOAD_UINT64_ACQUIRE(impl->negative_cache_version);
325
64.7k
}
326
327
static inline void
328
set_cache_version(_abc_data *impl, uint64_t version)
329
800
{
330
#ifdef Py_GIL_DISABLED
331
    _Py_atomic_store_uint64_release(&impl->negative_cache_version, version);
332
#else
333
800
    impl->negative_cache_version = version;
334
800
#endif
335
800
}
336
337
static int
338
abc_data_traverse(PyObject *op, visitproc visit, void *arg)
339
98.6k
{
340
98.6k
    _abc_data *self = _abc_data_CAST(op);
341
    // The tables only hold weakrefs without callbacks which cannot
342
    // be part of a reference cycle.
343
98.6k
    Py_VISIT(Py_TYPE(self));
344
98.6k
    return 0;
345
98.6k
}
346
347
static int
348
abc_data_clear(PyObject *op)
349
0
{
350
0
    _abc_data *self = _abc_data_CAST(op);
351
0
    abc_table *registry = self->registry;
352
0
    abc_table *cache = self->cache;
353
0
    abc_table *negative_cache = self->negative_cache;
354
0
    self->registry = EMPTY_TABLE;
355
0
    self->cache = EMPTY_TABLE;
356
0
    self->negative_cache = EMPTY_TABLE;
357
0
    abc_table_release(registry, 0);
358
0
    abc_table_release(cache, 0);
359
0
    abc_table_release(negative_cache, 0);
360
0
    return 0;
361
0
}
362
363
static void
364
abc_data_dealloc(PyObject *self)
365
0
{
366
0
    PyObject_GC_UnTrack(self);
367
0
    PyTypeObject *tp = Py_TYPE(self);
368
0
    (void)abc_data_clear(self);
369
0
    tp->tp_free(self);
370
0
    Py_DECREF(tp);
371
0
}
372
373
static PyObject *
374
abc_data_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
375
2.00k
{
376
2.00k
    _abc_data *self = (_abc_data *) type->tp_alloc(type, 0);
377
2.00k
    _abcmodule_state *state = NULL;
378
2.00k
    if (self == NULL) {
379
0
        return NULL;
380
0
    }
381
382
2.00k
    state = _PyType_GetModuleState(type);
383
2.00k
    if (state == NULL) {
384
0
        Py_DECREF(self);
385
0
        return NULL;
386
0
    }
387
388
2.00k
    self->registry = EMPTY_TABLE;
389
2.00k
    self->cache = EMPTY_TABLE;
390
2.00k
    self->negative_cache = EMPTY_TABLE;
391
2.00k
    self->negative_cache_version = get_invalidation_counter(state);
392
    // Avoid refcount contention between threads.
393
2.00k
    _PyObject_SetDeferredRefcount((PyObject *)self);
394
2.00k
    return (PyObject *) self;
395
2.00k
}
396
397
PyDoc_STRVAR(abc_data_doc,
398
"Internal state held by ABC machinery.");
399
400
static PyType_Slot _abc_data_type_spec_slots[] = {
401
    {Py_tp_doc, (void *)abc_data_doc},
402
    {Py_tp_new, abc_data_new},
403
    {Py_tp_dealloc, abc_data_dealloc},
404
    {Py_tp_traverse, abc_data_traverse},
405
    {Py_tp_clear, abc_data_clear},
406
    {0, 0}
407
};
408
409
static PyType_Spec _abc_data_type_spec = {
410
    .name = "_abc._abc_data",
411
    .basicsize = sizeof(_abc_data),
412
    .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
413
    .slots = _abc_data_type_spec_slots,
414
};
415
416
static _abc_data *
417
lookup_impl(_abcmodule_state *state, PyObject *self, _PyCStackRef *cref)
418
88.7k
{
419
88.7k
    if (!PyType_Check(self)) {
420
0
        return NULL;
421
0
    }
422
88.7k
    _PyType_LookupStackRefAndVersion((PyTypeObject *)self, &_Py_ID(_abc_impl),
423
88.7k
                                     &cref->ref);
424
88.7k
    if (PyStackRef_IsNull(cref->ref)) {
425
0
        return NULL;
426
0
    }
427
88.7k
    PyObject *impl = PyStackRef_AsPyObjectBorrow(cref->ref);
428
88.7k
    if (!Py_IS_TYPE(impl, state->_abc_data_type)) {
429
0
        PyStackRef_CLOSE(cref->ref);
430
0
        cref->ref = PyStackRef_NULL;
431
0
        return NULL;
432
0
    }
433
88.7k
    return (_abc_data *)impl;
434
88.7k
}
435
436
// Like lookup_impl() but falls back to a full attribute lookup,
437
// and sets an exception on failure.
438
static _abc_data *
439
get_impl(_abcmodule_state *state, PyObject *self, _PyCStackRef *cref)
440
88.3k
{
441
88.3k
    _abc_data *impl = lookup_impl(state, self, cref);
442
88.3k
    if (impl != NULL) {
443
88.3k
        return impl;
444
88.3k
    }
445
0
    cref->ref = _PyObject_GetAttrStackRef(self, &_Py_ID(_abc_impl));
446
0
    if (PyStackRef_IsNull(cref->ref)) {
447
0
        return NULL;
448
0
    }
449
0
    impl = (_abc_data *)PyStackRef_AsPyObjectBorrow(cref->ref);
450
0
    if (!Py_IS_TYPE(impl, state->_abc_data_type)) {
451
0
        PyErr_SetString(PyExc_TypeError, "_abc_impl is set to a wrong type");
452
0
        PyStackRef_CLOSE(cref->ref);
453
0
        cref->ref = PyStackRef_NULL;
454
0
        return NULL;
455
0
    }
456
0
    return impl;
457
0
}
458
459
static int
460
type_lookup_is(PyTypeObject *type, PyObject *name, PyObject *expected)
461
91.1k
{
462
91.1k
    _PyStackRef ref;
463
91.1k
    _PyType_LookupStackRefAndVersion(type, name, &ref);
464
91.1k
    if (PyStackRef_IsNull(ref)) {
465
1.36k
        return expected == NULL;
466
1.36k
    }
467
89.8k
    int res = (PyStackRef_AsPyObjectBorrow(ref) == expected);
468
89.8k
    PyStackRef_CLOSE(ref);
469
89.8k
    return res;
470
91.1k
}
471
472
static int
473
add_to_table(_abc_data *impl, abc_table **ptable, PyObject *cls)
474
1.65k
{
475
    // PyWeakref_NewRef() can lock cls, call it outside the critical section.
476
1.65k
    PyObject *ref = PyWeakref_NewRef(cls, NULL);
477
1.65k
    if (ref == NULL) {
478
0
        return -1;
479
0
    }
480
1.65k
    int res;
481
1.65k
    Py_BEGIN_CRITICAL_SECTION(impl);
482
1.65k
    res = abc_table_add(ptable, cls, ref);
483
1.65k
    Py_END_CRITICAL_SECTION();
484
1.65k
    return res;
485
1.65k
}
486
487
// Add cls to the negative cache if it is still valid for counter.
488
static int
489
add_to_negative_cache(_abc_data *impl, PyObject *cls, uint64_t counter)
490
1.00k
{
491
1.00k
    PyObject *ref = PyWeakref_NewRef(cls, NULL);
492
1.00k
    if (ref == NULL) {
493
0
        return -1;
494
0
    }
495
1.00k
    int res = 0;
496
1.00k
    Py_BEGIN_CRITICAL_SECTION(impl);
497
1.00k
    if (impl->negative_cache_version == counter) {
498
1.00k
        res = abc_table_add(&impl->negative_cache, cls, ref);
499
1.00k
    }
500
0
    else {
501
0
        Py_DECREF(ref);
502
0
    }
503
1.00k
    Py_END_CRITICAL_SECTION();
504
1.00k
    return res;
505
1.00k
}
506
507
typedef enum {
508
    CACHE_UNKNOWN = -1,  // not cached or stale
509
    CACHE_NEGATIVE = 0,  // in the negative cache
510
    CACHE_POSITIVE = 1,  // in the positive cache
511
} cache_result;
512
513
static cache_result
514
lookup_caches(_abcmodule_state *state, _abc_data *impl, PyObject *subclass)
515
89.3k
{
516
89.3k
    abc_table *table = FT_ATOMIC_LOAD_PTR_ACQUIRE(impl->cache);
517
89.3k
    if (abc_table_contains(table, subclass)) {
518
26.6k
        return CACHE_POSITIVE;
519
26.6k
    }
520
62.7k
    if (get_cache_version(impl) == get_invalidation_counter(state)) {
521
62.1k
        table = FT_ATOMIC_LOAD_PTR_ACQUIRE(impl->negative_cache);
522
62.1k
        if (abc_table_contains(table, subclass)) {
523
58.9k
            return CACHE_NEGATIVE;
524
58.9k
        }
525
62.1k
    }
526
3.73k
    return CACHE_UNKNOWN;
527
62.7k
}
528
529
// Clear the negative cache if register() was called since it was last
530
// validated.
531
static void
532
validate_negative_cache(_abc_data *impl, uint64_t counter)
533
2.03k
{
534
2.03k
    if (get_cache_version(impl) >= counter) {
535
1.23k
        return;
536
1.23k
    }
537
800
    Py_BEGIN_CRITICAL_SECTION(impl);
538
800
    if (impl->negative_cache_version < counter) {
539
800
        abc_table_clear(&impl->negative_cache);
540
800
        set_cache_version(impl, counter);
541
800
    }
542
800
    Py_END_CRITICAL_SECTION();
543
800
}
544
545
546
/*[clinic input]
547
_abc._reset_registry
548
549
    self: object
550
    /
551
552
Internal ABC helper to reset registry of a given class.
553
554
Should be only used by refleak.py
555
[clinic start generated code]*/
556
557
static PyObject *
558
_abc__reset_registry(PyObject *module, PyObject *self)
559
/*[clinic end generated code: output=92d591a43566cc10 input=12a0b7eb339ac35c]*/
560
0
{
561
0
    PyThreadState *tstate = _PyThreadState_GET();
562
0
    _PyCStackRef cref;
563
0
    _PyThreadState_PushCStackRef(tstate, &cref);
564
0
    _abc_data *impl = get_impl(get_abc_state(module), self, &cref);
565
0
    if (impl != NULL) {
566
0
        Py_BEGIN_CRITICAL_SECTION(impl);
567
0
        abc_table_clear(&impl->registry);
568
        // Registered classes are also in the cache, and register()
569
        // does nothing for a class which is cached as a subclass.
570
0
        abc_table_clear(&impl->cache);
571
0
        Py_END_CRITICAL_SECTION();
572
0
    }
573
0
    _PyThreadState_PopCStackRef(tstate, &cref);
574
0
    if (impl == NULL) {
575
0
        return NULL;
576
0
    }
577
0
    Py_RETURN_NONE;
578
0
}
579
580
/*[clinic input]
581
_abc._reset_caches
582
583
    self: object
584
    /
585
586
Internal ABC helper to reset both caches of a given class.
587
588
Should be only used by refleak.py
589
[clinic start generated code]*/
590
591
static PyObject *
592
_abc__reset_caches(PyObject *module, PyObject *self)
593
/*[clinic end generated code: output=f296f0d5c513f80c input=c0ac616fd8acfb6f]*/
594
0
{
595
0
    PyThreadState *tstate = _PyThreadState_GET();
596
0
    _PyCStackRef cref;
597
0
    _PyThreadState_PushCStackRef(tstate, &cref);
598
0
    _abc_data *impl = get_impl(get_abc_state(module), self, &cref);
599
0
    if (impl != NULL) {
600
0
        Py_BEGIN_CRITICAL_SECTION(impl);
601
0
        abc_table_clear(&impl->cache);
602
0
        abc_table_clear(&impl->negative_cache);
603
0
        Py_END_CRITICAL_SECTION();
604
0
    }
605
0
    _PyThreadState_PopCStackRef(tstate, &cref);
606
0
    if (impl == NULL) {
607
0
        return NULL;
608
0
    }
609
0
    Py_RETURN_NONE;
610
0
}
611
612
static PyObject *
613
weakref_set_from_list(PyObject *list)
614
0
{
615
0
    PyObject *set = PySet_New(NULL);
616
0
    if (set == NULL) {
617
0
        return NULL;
618
0
    }
619
0
    for (Py_ssize_t i = 0; i < PyList_GET_SIZE(list); i++) {
620
0
        PyObject *ref = PyWeakref_NewRef(PyList_GET_ITEM(list, i), NULL);
621
0
        if (ref == NULL) {
622
0
            Py_DECREF(set);
623
0
            return NULL;
624
0
        }
625
0
        int rc = PySet_Add(set, ref);
626
0
        Py_DECREF(ref);
627
0
        if (rc < 0) {
628
0
            Py_DECREF(set);
629
0
            return NULL;
630
0
        }
631
0
    }
632
0
    return set;
633
0
}
634
635
/*[clinic input]
636
_abc._get_dump
637
638
    self: object
639
    /
640
641
Internal ABC helper for cache and registry debugging.
642
643
Return shallow copies of registry, of both caches, and
644
negative cache version. Don't call this function directly,
645
instead use ABC._dump_registry() for a nice repr.
646
[clinic start generated code]*/
647
648
static PyObject *
649
_abc__get_dump(PyObject *module, PyObject *self)
650
/*[clinic end generated code: output=9d9569a8e2c1c443 input=2c5deb1bfe9e3c79]*/
651
0
{
652
0
    PyThreadState *tstate = _PyThreadState_GET();
653
0
    _PyCStackRef cref;
654
0
    _PyThreadState_PushCStackRef(tstate, &cref);
655
0
    _abc_data *impl = get_impl(get_abc_state(module), self, &cref);
656
0
    if (impl == NULL) {
657
0
        _PyThreadState_PopCStackRef(tstate, &cref);
658
0
        return NULL;
659
0
    }
660
0
    PyObject *lists[3] = {NULL, NULL, NULL};
661
0
    PyObject *sets[3] = {NULL, NULL, NULL};
662
0
    PyObject *res = NULL;
663
0
    uint64_t version;
664
0
    Py_BEGIN_CRITICAL_SECTION(impl);
665
0
    lists[0] = abc_table_snapshot(impl->registry);
666
0
    lists[1] = abc_table_snapshot(impl->cache);
667
0
    lists[2] = abc_table_snapshot(impl->negative_cache);
668
0
    version = get_cache_version(impl);
669
0
    Py_END_CRITICAL_SECTION();
670
0
    _PyThreadState_PopCStackRef(tstate, &cref);
671
0
    for (int i = 0; i < 3; i++) {
672
0
        if (lists[i] == NULL) {
673
0
            goto done;
674
0
        }
675
0
        sets[i] = weakref_set_from_list(lists[i]);
676
0
        if (sets[i] == NULL) {
677
0
            goto done;
678
0
        }
679
0
    }
680
0
    res = Py_BuildValue("OOOK", sets[0], sets[1], sets[2],
681
0
                        (unsigned long long)version);
682
0
done:
683
0
    for (int i = 0; i < 3; i++) {
684
0
        Py_XDECREF(lists[i]);
685
0
        Py_XDECREF(sets[i]);
686
0
    }
687
0
    return res;
688
0
}
689
690
// Compute set of abstract method names.
691
static int
692
compute_abstract_methods(PyObject *self)
693
2.00k
{
694
2.00k
    int ret = -1;
695
2.00k
    PyObject *abstracts = PyFrozenSet_New(NULL);
696
2.00k
    if (abstracts == NULL) {
697
0
        return -1;
698
0
    }
699
700
2.00k
    PyObject *ns = NULL, *items = NULL, *bases = NULL;  // Py_XDECREF()ed on error.
701
702
    /* Stage 1: direct abstract methods. */
703
2.00k
    ns = PyObject_GetAttr(self, &_Py_ID(__dict__));
704
2.00k
    if (!ns) {
705
0
        goto error;
706
0
    }
707
708
    // We can't use PyDict_Next(ns) even when ns is dict because
709
    // _PyObject_IsAbstract() can mutate ns.
710
2.00k
    items = PyMapping_Items(ns);
711
2.00k
    if (!items) {
712
0
        goto error;
713
0
    }
714
2.00k
    assert(PyList_Check(items));
715
27.0k
    for (Py_ssize_t pos = 0; pos < PyList_GET_SIZE(items); pos++) {
716
25.0k
        PyObject *it = PySequence_Fast(
717
25.0k
                PyList_GET_ITEM(items, pos),
718
25.0k
                "items() returned non-iterable");
719
25.0k
        if (!it) {
720
0
            goto error;
721
0
        }
722
25.0k
        if (PySequence_Fast_GET_SIZE(it) != 2) {
723
0
            PyErr_SetString(PyExc_TypeError,
724
0
                            "items() returned item which size is not 2");
725
0
            Py_DECREF(it);
726
0
            goto error;
727
0
        }
728
729
        // borrowed
730
25.0k
        PyObject *key = PySequence_Fast_GET_ITEM(it, 0);
731
25.0k
        PyObject *value = PySequence_Fast_GET_ITEM(it, 1);
732
        // items or it may be cleared while accessing __abstractmethod__
733
        // So we need to keep strong reference for key
734
25.0k
        Py_INCREF(key);
735
25.0k
        int is_abstract = _PyObject_IsAbstract(value);
736
25.0k
        if (is_abstract < 0 ||
737
25.0k
                (is_abstract && PySet_Add(abstracts, key) < 0)) {
738
0
            Py_DECREF(it);
739
0
            Py_DECREF(key);
740
0
            goto error;
741
0
        }
742
25.0k
        Py_DECREF(key);
743
25.0k
        Py_DECREF(it);
744
25.0k
    }
745
746
    /* Stage 2: inherited abstract methods. */
747
2.00k
    bases = PyObject_GetAttr(self, &_Py_ID(__bases__));
748
2.00k
    if (!bases) {
749
0
        goto error;
750
0
    }
751
2.00k
    if (!PyTuple_Check(bases)) {
752
0
        PyErr_SetString(PyExc_TypeError, "__bases__ is not tuple");
753
0
        goto error;
754
0
    }
755
756
4.40k
    for (Py_ssize_t pos = 0; pos < PyTuple_GET_SIZE(bases); pos++) {
757
2.40k
        PyObject *item = PyTuple_GET_ITEM(bases, pos);  // borrowed
758
2.40k
        PyObject *base_abstracts, *iter;
759
760
2.40k
        if (PyObject_GetOptionalAttr(item, &_Py_ID(__abstractmethods__),
761
2.40k
                                 &base_abstracts) < 0) {
762
0
            goto error;
763
0
        }
764
2.40k
        if (base_abstracts == NULL) {
765
597
            continue;
766
597
        }
767
1.80k
        if (!(iter = PyObject_GetIter(base_abstracts))) {
768
0
            Py_DECREF(base_abstracts);
769
0
            goto error;
770
0
        }
771
1.80k
        Py_DECREF(base_abstracts);
772
1.80k
        PyObject *key, *value;
773
4.93k
        while ((key = PyIter_Next(iter))) {
774
3.13k
            if (PyObject_GetOptionalAttr(self, key, &value) < 0) {
775
0
                Py_DECREF(key);
776
0
                Py_DECREF(iter);
777
0
                goto error;
778
0
            }
779
3.13k
            if (value == NULL) {
780
0
                Py_DECREF(key);
781
0
                continue;
782
0
            }
783
784
3.13k
            int is_abstract = _PyObject_IsAbstract(value);
785
3.13k
            Py_DECREF(value);
786
3.13k
            if (is_abstract < 0 ||
787
3.13k
                    (is_abstract && PySet_Add(abstracts, key) < 0))
788
0
            {
789
0
                Py_DECREF(key);
790
0
                Py_DECREF(iter);
791
0
                goto error;
792
0
            }
793
3.13k
            Py_DECREF(key);
794
3.13k
        }
795
1.80k
        Py_DECREF(iter);
796
1.80k
        if (PyErr_Occurred()) {
797
0
            goto error;
798
0
        }
799
1.80k
    }
800
801
2.00k
    if (PyObject_SetAttr(self, &_Py_ID(__abstractmethods__), abstracts) < 0) {
802
0
        goto error;
803
0
    }
804
805
2.00k
    ret = 0;
806
2.00k
error:
807
2.00k
    Py_DECREF(abstracts);
808
2.00k
    Py_XDECREF(ns);
809
2.00k
    Py_XDECREF(items);
810
2.00k
    Py_XDECREF(bases);
811
2.00k
    return ret;
812
2.00k
}
813
814
1.72k
#define COLLECTION_FLAGS (Py_TPFLAGS_SEQUENCE | Py_TPFLAGS_MAPPING)
815
816
/*[clinic input]
817
@permit_long_summary
818
_abc._abc_init
819
820
    self: object
821
    /
822
823
Internal ABC helper for class set-up. Should be never used outside abc module.
824
[clinic start generated code]*/
825
826
static PyObject *
827
_abc__abc_init(PyObject *module, PyObject *self)
828
/*[clinic end generated code: output=594757375714cda1 input=0b3513f947736d39]*/
829
2.00k
{
830
2.00k
    _abcmodule_state *state = get_abc_state(module);
831
2.00k
    PyObject *data;
832
2.00k
    if (compute_abstract_methods(self) < 0) {
833
0
        return NULL;
834
0
    }
835
836
    /* Set up inheritance registry. */
837
2.00k
    data = abc_data_new(state->_abc_data_type, NULL, NULL);
838
2.00k
    if (data == NULL) {
839
0
        return NULL;
840
0
    }
841
2.00k
    if (PyObject_SetAttr(self, &_Py_ID(_abc_impl), data) < 0) {
842
0
        Py_DECREF(data);
843
0
        return NULL;
844
0
    }
845
2.00k
    Py_DECREF(data);
846
    /* If __abc_tpflags__ & COLLECTION_FLAGS is set, then set the corresponding bit(s)
847
     * in the new class.
848
     * Used by collections.abc.Sequence and collections.abc.Mapping to indicate
849
     * their special status w.r.t. pattern matching. */
850
2.00k
    if (PyType_Check(self)) {
851
2.00k
        PyTypeObject *cls = (PyTypeObject *)self;
852
2.00k
        PyObject *dict = _PyType_GetDict(cls);
853
2.00k
        PyObject *flags = NULL;
854
2.00k
        if (PyDict_Pop(dict, &_Py_ID(__abc_tpflags__), &flags) < 0) {
855
0
            return NULL;
856
0
        }
857
2.00k
        if (flags == NULL || !PyLong_CheckExact(flags)) {
858
1.93k
            Py_XDECREF(flags);
859
1.93k
            Py_RETURN_NONE;
860
1.93k
        }
861
862
74
        long val = PyLong_AsLong(flags);
863
74
        Py_DECREF(flags);
864
74
        if (val == -1 && PyErr_Occurred()) {
865
0
            return NULL;
866
0
        }
867
74
        if ((val & COLLECTION_FLAGS) == COLLECTION_FLAGS) {
868
0
            PyErr_SetString(PyExc_TypeError, "__abc_tpflags__ cannot be both Py_TPFLAGS_SEQUENCE and Py_TPFLAGS_MAPPING");
869
0
            return NULL;
870
0
        }
871
74
        _PyType_SetFlags((PyTypeObject *)self, 0, val & COLLECTION_FLAGS);
872
74
    }
873
2.00k
    Py_RETURN_NONE;
874
2.00k
}
875
876
/*[clinic input]
877
@permit_long_summary
878
_abc._abc_register
879
880
    self: object
881
    subclass: object
882
    /
883
884
Internal ABC helper for subclasss registration. Should be never used outside abc module.
885
[clinic start generated code]*/
886
887
static PyObject *
888
_abc__abc_register_impl(PyObject *module, PyObject *self, PyObject *subclass)
889
/*[clinic end generated code: output=7851e7668c963524 input=135ab13a581b4414]*/
890
1.64k
{
891
1.64k
    if (!PyType_Check(subclass)) {
892
0
        PyErr_SetString(PyExc_TypeError, "Can only register classes");
893
0
        return NULL;
894
0
    }
895
1.64k
    int result = PyObject_IsSubclass(subclass, self);
896
1.64k
    if (result > 0) {
897
656
        return Py_NewRef(subclass);  /* Already a subclass. */
898
656
    }
899
989
    if (result < 0) {
900
0
        return NULL;
901
0
    }
902
    /* Subtle: test for cycles *after* testing for "already a subclass";
903
       this means we allow X.register(X) and interpret it as a no-op. */
904
989
    result = PyObject_IsSubclass(self, subclass);
905
989
    if (result > 0) {
906
        /* This would create a cycle, which is bad for the algorithm below. */
907
0
        PyErr_SetString(PyExc_RuntimeError, "Refusing to create an inheritance cycle");
908
0
        return NULL;
909
0
    }
910
989
    if (result < 0) {
911
0
        return NULL;
912
0
    }
913
989
    _abcmodule_state *state = get_abc_state(module);
914
989
    PyThreadState *tstate = _PyThreadState_GET();
915
989
    _PyCStackRef cref;
916
989
    _PyThreadState_PushCStackRef(tstate, &cref);
917
989
    _abc_data *impl = get_impl(state, self, &cref);
918
989
    int err = (impl == NULL
919
989
               || add_to_table(impl, &impl->registry, subclass) < 0);
920
989
    _PyThreadState_PopCStackRef(tstate, &cref);
921
989
    if (err) {
922
0
        return NULL;
923
0
    }
924
925
    /* Invalidate negative cache */
926
989
    increment_invalidation_counter(state);
927
928
    /* Set Py_TPFLAGS_SEQUENCE or Py_TPFLAGS_MAPPING flag */
929
989
    if (PyType_Check(self)) {
930
989
        unsigned long collection_flag =
931
989
            PyType_GetFlags((PyTypeObject *)self) & COLLECTION_FLAGS;
932
989
        if (collection_flag) {
933
518
            _PyType_SetFlagsRecursive((PyTypeObject *)subclass,
934
518
                                      COLLECTION_FLAGS,
935
518
                                      collection_flag);
936
518
        }
937
989
    }
938
989
    return Py_NewRef(subclass);
939
989
}
940
941
942
// True if instance.__class__ is type(instance) and the lookup
943
// doesn't run any Python code.
944
static inline int
945
has_default_class_attr(_abcmodule_state *state, PyObject *instance)
946
85.6k
{
947
85.6k
    PyTypeObject *tp = Py_TYPE(instance);
948
85.6k
    return tp->tp_getattro == PyObject_GenericGetAttr
949
85.6k
        && type_lookup_is(tp, &_Py_ID(__class__), state->object_class_descr);
950
85.6k
}
951
952
/*[clinic input]
953
@permit_long_summary
954
_abc._abc_instancecheck
955
956
    self: object
957
    instance: object
958
    /
959
960
Internal ABC helper for instance checks. Should be never used outside abc module.
961
[clinic start generated code]*/
962
963
static PyObject *
964
_abc__abc_instancecheck_impl(PyObject *module, PyObject *self,
965
                             PyObject *instance)
966
/*[clinic end generated code: output=b8b5148f63b6b56f input=0bbc8da0ea346719]*/
967
85.6k
{
968
85.6k
    _abcmodule_state *state = get_abc_state(module);
969
85.6k
    PyObject *subclass_owned = NULL;
970
85.6k
    PyObject *result = NULL;
971
972
85.6k
    if (!has_default_class_attr(state, instance)) {
973
0
        if (PyObject_GetOptionalAttr(instance, &_Py_ID(__class__),
974
0
                                     &subclass_owned) < 0) {
975
0
            return NULL;
976
0
        }
977
0
    }
978
    // The __class__ lookup can change the type of the instance.
979
85.6k
    PyObject *subtype = (PyObject *)Py_TYPE(instance);
980
    // subclass is either subtype, which is kept alive by instance, or
981
    // subclass_owned. The fast path doesn't incref subtype to avoid
982
    // refcount contention between threads.
983
    /* Fall back to the type when the instance has no __class__,
984
       matching the behaviour of the built-in isinstance()
985
       (gh-153772). */
986
85.6k
    PyObject *subclass = subclass_owned != NULL ? subclass_owned : subtype;
987
988
    // Fast path: cache hits don't need any locking.
989
85.6k
    PyThreadState *tstate = _PyThreadState_GET();
990
85.6k
    _PyCStackRef cref;
991
85.6k
    _PyThreadState_PushCStackRef(tstate, &cref);
992
85.6k
    _abc_data *impl = get_impl(state, self, &cref);
993
85.6k
    cache_result incache = CACHE_UNKNOWN;
994
85.6k
    if (impl != NULL) {
995
85.6k
        incache = lookup_caches(state, impl, subclass);
996
85.6k
    }
997
85.6k
    _PyThreadState_PopCStackRef(tstate, &cref);
998
85.6k
    if (impl == NULL) {
999
0
        Py_XDECREF(subclass_owned);
1000
0
        return NULL;
1001
0
    }
1002
85.6k
    if (incache == CACHE_POSITIVE
1003
59.0k
        || (incache == CACHE_NEGATIVE && subtype == subclass))
1004
85.6k
    {
1005
85.6k
        Py_XDECREF(subclass_owned);
1006
85.6k
        return PyBool_FromLong(incache);
1007
85.6k
    }
1008
1009
    /* A subclass check can change the instance's actual type. */
1010
31
    Py_INCREF(subtype);
1011
31
    result = PyObject_CallMethodOneArg(self, &_Py_ID(__subclasscheck__),
1012
31
                                       subclass);
1013
31
    if (result == NULL || subtype == subclass) {
1014
31
        Py_DECREF(subtype);
1015
31
        goto end;
1016
31
    }
1017
1018
0
    switch (PyObject_IsTrue(result)) {
1019
0
    case -1:
1020
0
        Py_SETREF(result, NULL);
1021
0
        break;
1022
0
    case 0:
1023
0
        Py_DECREF(result);
1024
0
        result = PyObject_CallMethodOneArg(self, &_Py_ID(__subclasscheck__),
1025
0
                                           subtype);
1026
0
        break;
1027
0
    case 1:  // Nothing to do.
1028
0
        break;
1029
0
    default:
1030
0
        Py_UNREACHABLE();
1031
0
    }
1032
0
    Py_DECREF(subtype);
1033
1034
31
end:
1035
31
    Py_XDECREF(subclass_owned);
1036
31
    return result;
1037
0
}
1038
1039
1040
static int subclasscheck(_abcmodule_state *state, _abc_data *impl,
1041
                         PyObject *self, PyObject *subclass, int nested);
1042
1043
// Like PyObject_IsSubclass(subclass, cls), but doesn't add subclass to the
1044
// negative cache of cls if cls uses the default ABCMeta.__subclasscheck__.
1045
static int
1046
issubclass_nested(_abcmodule_state *state, PyObject *subclass, PyObject *cls)
1047
358
{
1048
358
    assert(PyType_Check(cls));
1049
358
    if (type_lookup_is(Py_TYPE(cls), &_Py_ID(__subclasscheck__),
1050
358
                       state->subclasscheck_func))
1051
358
    {
1052
358
        PyThreadState *tstate = _PyThreadState_GET();
1053
358
        _PyCStackRef cref;
1054
358
        _PyThreadState_PushCStackRef(tstate, &cref);
1055
358
        _abc_data *impl = lookup_impl(state, cls, &cref);
1056
358
        int res = -1;
1057
358
        if (impl != NULL) {
1058
358
            if (!Py_EnterRecursiveCall(" in __subclasscheck__")) {
1059
358
                res = subclasscheck(state, impl, cls, subclass, 1);
1060
358
                Py_LeaveRecursiveCall();
1061
358
            }
1062
358
        }
1063
358
        _PyThreadState_PopCStackRef(tstate, &cref);
1064
358
        if (impl != NULL) {
1065
358
            return res;
1066
358
        }
1067
358
    }
1068
0
    return PyObject_IsSubclass(subclass, cls);
1069
358
}
1070
1071
// Check if subclass is a subclass of a registered class.
1072
// Returns -1 on error.
1073
static int
1074
check_registry(_abcmodule_state *state, _abc_data *impl, PyObject *subclass)
1075
1.42k
{
1076
1.42k
    abc_table *registry = FT_ATOMIC_LOAD_PTR_ACQUIRE(impl->registry);
1077
    // Fast path: subclass is registered directly.
1078
1.42k
    if (abc_table_contains(registry, subclass)) {
1079
52
        return 1;
1080
52
    }
1081
    // The registry can be modified by the checks, iterate over a copy.
1082
1.36k
    PyObject *classes;
1083
1.36k
    Py_BEGIN_CRITICAL_SECTION(impl);
1084
1.36k
    classes = abc_table_snapshot(impl->registry);
1085
1.36k
    Py_END_CRITICAL_SECTION();
1086
1.36k
    if (classes == NULL) {
1087
0
        return -1;
1088
0
    }
1089
1.36k
    int res = 0;
1090
2.56k
    for (Py_ssize_t i = 0; i < PyList_GET_SIZE(classes); i++) {
1091
1.20k
        res = PyObject_IsSubclass(subclass, PyList_GET_ITEM(classes, i));
1092
1.20k
        if (res != 0) {
1093
4
            break;
1094
4
        }
1095
1.20k
    }
1096
1.36k
    Py_DECREF(classes);
1097
1.36k
    return res;
1098
1.36k
}
1099
1100
// Check if subclass is a subclass of a subclass of self.
1101
// Returns -1 on error.
1102
static int
1103
check_subclasses(_abcmodule_state *state, PyObject *self, PyObject *subclass)
1104
1.36k
{
1105
1.36k
    PyObject *subclasses;
1106
1.36k
    int native = 0;
1107
1.36k
    if (PyType_Check(self)
1108
1.36k
        && type_lookup_is((PyTypeObject *)self, &_Py_ID(__subclasses__), NULL)
1109
1.36k
        && type_lookup_is(Py_TYPE(self), &_Py_ID(__subclasses__),
1110
1.36k
                          state->type_subclasses))
1111
1.36k
    {
1112
        // __subclasses__() is not overridden, get the subclasses directly.
1113
1.36k
        subclasses = _PyType_GetSubclasses((PyTypeObject *)self);
1114
1.36k
        native = 1;
1115
1.36k
    }
1116
0
    else {
1117
0
        subclasses = PyObject_CallMethodNoArgs(self, &_Py_ID(__subclasses__));
1118
0
        if (subclasses != NULL && !PyList_Check(subclasses)) {
1119
0
            PyErr_SetString(PyExc_TypeError, "__subclasses__() must return a list");
1120
0
            Py_DECREF(subclasses);
1121
0
            return -1;
1122
0
        }
1123
0
    }
1124
1.36k
    if (subclasses == NULL) {
1125
0
        return -1;
1126
0
    }
1127
1.36k
    int res = 0;
1128
1.72k
    for (Py_ssize_t i = 0; i < PyList_GET_SIZE(subclasses); i++) {
1129
358
        PyObject *scls = PyList_GetItemRef(subclasses, i);
1130
358
        if (scls == NULL) {
1131
0
            res = -1;
1132
0
            break;
1133
0
        }
1134
358
        if (native) {
1135
358
            res = issubclass_nested(state, subclass, scls);
1136
358
        }
1137
0
        else {
1138
0
            res = PyObject_IsSubclass(subclass, scls);
1139
0
        }
1140
358
        Py_DECREF(scls);
1141
358
        if (res != 0) {
1142
2
            break;
1143
2
        }
1144
358
    }
1145
1.36k
    Py_DECREF(subclasses);
1146
1.36k
    return res;
1147
1.36k
}
1148
1149
// Implementation of ABCMeta.__subclasscheck__. Returns -1 on error.
1150
//
1151
// nested is set when checking the subclasses of another ABC. Negative
1152
// results are not cached then, otherwise every class in the hierarchy
1153
// would cache them which is quadratic in the number of classes.
1154
static int
1155
subclasscheck(_abcmodule_state *state, _abc_data *impl,
1156
              PyObject *self, PyObject *subclass, int nested)
1157
2.03k
{
1158
2.03k
    uint64_t counter = get_invalidation_counter(state);
1159
1160
    /* 1. Check cache. 2. Check negative cache; may have to invalidate. */
1161
2.03k
    validate_negative_cache(impl, counter);
1162
2.03k
    cache_result incache = lookup_caches(state, impl, subclass);
1163
2.03k
    if (incache != CACHE_UNKNOWN) {
1164
0
        return incache;
1165
0
    }
1166
1167
    /* 3. Check the subclass hook. */
1168
    // The default hook always returns NotImplemented, skip the call.
1169
2.03k
    if (!(PyType_Check(self)
1170
2.03k
          && type_lookup_is((PyTypeObject *)self, &_Py_ID(__subclasshook__),
1171
2.03k
                            state->object_subclasshook)
1172
376
          && type_lookup_is(Py_TYPE(self), &_Py_ID(__subclasshook__),
1173
376
                            state->object_subclasshook)))
1174
1.65k
    {
1175
1.65k
        PyObject *ok = PyObject_CallMethodOneArg(
1176
1.65k
                self, &_Py_ID(__subclasshook__), subclass);
1177
1.65k
        if (ok == NULL) {
1178
0
            return -1;
1179
0
        }
1180
1.65k
        if (ok == Py_True) {
1181
604
            goto positive;
1182
604
        }
1183
1.05k
        if (ok == Py_False) {
1184
0
            goto negative;
1185
0
        }
1186
1.05k
        if (ok != Py_NotImplemented) {
1187
0
            Py_DECREF(ok);
1188
0
            PyErr_SetString(PyExc_AssertionError, "__subclasshook__ must return either"
1189
0
                                                  " False, True, or NotImplemented");
1190
0
            return -1;
1191
0
        }
1192
1.05k
    }
1193
1194
    /* 4. Check if it's a direct subclass. */
1195
1.42k
    if (PyType_IsSubtype((PyTypeObject *)subclass, (PyTypeObject *)self)) {
1196
6
        goto positive;
1197
6
    }
1198
1199
    /* 5. Check if it's a subclass of a registered class (recursive). */
1200
1.42k
    int res = check_registry(state, impl, subclass);
1201
1.42k
    if (res < 0) {
1202
0
        return -1;
1203
0
    }
1204
1.42k
    if (res > 0) {
1205
56
        goto positive;
1206
56
    }
1207
1208
    /* 6. Check if it's a subclass of a subclass (recursive). */
1209
1.36k
    res = check_subclasses(state, self, subclass);
1210
1.36k
    if (res < 0) {
1211
0
        return -1;
1212
0
    }
1213
1.36k
    if (res > 0) {
1214
2
        goto positive;
1215
2
    }
1216
1217
1.36k
negative:
1218
    /* No dice; update negative cache. */
1219
1.36k
    if (!nested && add_to_negative_cache(impl, subclass, counter) < 0) {
1220
0
        return -1;
1221
0
    }
1222
1.36k
    return 0;
1223
1224
668
positive:
1225
668
    if (add_to_table(impl, &impl->cache, subclass) < 0) {
1226
0
        return -1;
1227
0
    }
1228
668
    return 1;
1229
668
}
1230
1231
/*[clinic input]
1232
@permit_long_summary
1233
_abc._abc_subclasscheck
1234
1235
    self: object
1236
    subclass: object
1237
    /
1238
1239
Internal ABC helper for subclasss checks. Should be never used outside abc module.
1240
[clinic start generated code]*/
1241
1242
static PyObject *
1243
_abc__abc_subclasscheck_impl(PyObject *module, PyObject *self,
1244
                             PyObject *subclass)
1245
/*[clinic end generated code: output=b56c9e4a530e3894 input=5bf1ef712f5d3610]*/
1246
1.67k
{
1247
1.67k
    if (!PyType_Check(subclass)) {
1248
0
        PyErr_SetString(PyExc_TypeError, "issubclass() arg 1 must be a class");
1249
0
        return NULL;
1250
0
    }
1251
1252
1.67k
    _abcmodule_state *state = get_abc_state(module);
1253
1.67k
    PyThreadState *tstate = _PyThreadState_GET();
1254
1.67k
    _PyCStackRef cref;
1255
1.67k
    _PyThreadState_PushCStackRef(tstate, &cref);
1256
1.67k
    _abc_data *impl = get_impl(state, self, &cref);
1257
1.67k
    int res = -1;
1258
1.67k
    if (impl != NULL) {
1259
1.67k
        res = lookup_caches(state, impl, subclass);
1260
1.67k
        if (res == CACHE_UNKNOWN) {
1261
1.67k
            res = subclasscheck(state, impl, self, subclass, 0);
1262
1.67k
        }
1263
1.67k
    }
1264
1.67k
    _PyThreadState_PopCStackRef(tstate, &cref);
1265
1.67k
    if (res < 0) {
1266
0
        return NULL;
1267
0
    }
1268
1.67k
    return PyBool_FromLong(res);
1269
1.67k
}
1270
1271
/*[clinic input]
1272
_abc._set_subclasscheck
1273
1274
    func: object
1275
    /
1276
1277
Internal ABC helper to register ABCMeta.__subclasscheck__.
1278
1279
Classes whose metaclass resolves __subclasscheck__ to func are checked
1280
natively when walking the subclass tree of an ABC.
1281
[clinic start generated code]*/
1282
1283
static PyObject *
1284
_abc__set_subclasscheck(PyObject *module, PyObject *func)
1285
/*[clinic end generated code: output=1dc657738311dea5 input=c2e47dd519524e44]*/
1286
37
{
1287
37
    _abcmodule_state *state = get_abc_state(module);
1288
    // abc can be reloaded.
1289
37
    Py_XSETREF(state->subclasscheck_func, Py_NewRef(func));
1290
37
    Py_RETURN_NONE;
1291
37
}
1292
1293
/*[clinic input]
1294
_abc.get_cache_token
1295
1296
Returns the current ABC cache token.
1297
1298
The token is an opaque object (supporting equality testing) identifying
1299
the current version of the ABC cache for virtual subclasses.  The token
1300
changes with every call to register() on any ABC.
1301
[clinic start generated code]*/
1302
1303
static PyObject *
1304
_abc_get_cache_token_impl(PyObject *module)
1305
/*[clinic end generated code: output=c7d87841e033dacc input=d87acc04492f6bf3]*/
1306
0
{
1307
0
    _abcmodule_state *state = get_abc_state(module);
1308
0
    return PyLong_FromUnsignedLongLong(get_invalidation_counter(state));
1309
0
}
1310
1311
static struct PyMethodDef _abcmodule_methods[] = {
1312
    _ABC_GET_CACHE_TOKEN_METHODDEF
1313
    _ABC__ABC_INIT_METHODDEF
1314
    _ABC__RESET_REGISTRY_METHODDEF
1315
    _ABC__RESET_CACHES_METHODDEF
1316
    _ABC__GET_DUMP_METHODDEF
1317
    _ABC__ABC_REGISTER_METHODDEF
1318
    _ABC__ABC_INSTANCECHECK_METHODDEF
1319
    _ABC__ABC_SUBCLASSCHECK_METHODDEF
1320
    _ABC__SET_SUBCLASSCHECK_METHODDEF
1321
    {NULL,       NULL}          /* sentinel */
1322
};
1323
1324
static int
1325
get_type_dict_item(PyTypeObject *type, PyObject *name, PyObject **result)
1326
111
{
1327
111
    if (PyDict_GetItemRef(_PyType_GetDict(type), name, result) < 0) {
1328
0
        return -1;
1329
0
    }
1330
111
    if (*result == NULL) {
1331
0
        PyErr_Format(PyExc_SystemError, "%s has no %U", type->tp_name, name);
1332
0
        return -1;
1333
0
    }
1334
111
    return 0;
1335
111
}
1336
1337
static int
1338
_abcmodule_exec(PyObject *module)
1339
37
{
1340
37
    _abcmodule_state *state = get_abc_state(module);
1341
37
    state->abc_invalidation_counter = 0;
1342
37
    state->_abc_data_type = (PyTypeObject *)PyType_FromModuleAndSpec(module, &_abc_data_type_spec, NULL);
1343
37
    if (state->_abc_data_type == NULL) {
1344
0
        return -1;
1345
0
    }
1346
37
    if (get_type_dict_item(&PyBaseObject_Type, &_Py_ID(__class__),
1347
37
                           &state->object_class_descr) < 0
1348
37
        || get_type_dict_item(&PyBaseObject_Type, &_Py_ID(__subclasshook__),
1349
37
                              &state->object_subclasshook) < 0
1350
37
        || get_type_dict_item(&PyType_Type, &_Py_ID(__subclasses__),
1351
37
                              &state->type_subclasses) < 0)
1352
0
    {
1353
0
        return -1;
1354
0
    }
1355
37
    return 0;
1356
37
}
1357
1358
static int
1359
_abcmodule_traverse(PyObject *module, visitproc visit, void *arg)
1360
2.03k
{
1361
2.03k
    _abcmodule_state *state = get_abc_state(module);
1362
2.03k
    Py_VISIT(state->_abc_data_type);
1363
2.03k
    Py_VISIT(state->object_class_descr);
1364
2.03k
    Py_VISIT(state->object_subclasshook);
1365
2.03k
    Py_VISIT(state->type_subclasses);
1366
2.03k
    Py_VISIT(state->subclasscheck_func);
1367
2.03k
    return 0;
1368
2.03k
}
1369
1370
static int
1371
_abcmodule_clear(PyObject *module)
1372
0
{
1373
0
    _abcmodule_state *state = get_abc_state(module);
1374
0
    Py_CLEAR(state->_abc_data_type);
1375
0
    Py_CLEAR(state->object_class_descr);
1376
0
    Py_CLEAR(state->object_subclasshook);
1377
0
    Py_CLEAR(state->type_subclasses);
1378
0
    Py_CLEAR(state->subclasscheck_func);
1379
0
    return 0;
1380
0
}
1381
1382
static void
1383
_abcmodule_free(void *module)
1384
0
{
1385
0
    (void)_abcmodule_clear((PyObject *)module);
1386
0
}
1387
1388
static PyModuleDef_Slot _abcmodule_slots[] = {
1389
    _Py_ABI_SLOT,
1390
    {Py_mod_exec, _abcmodule_exec},
1391
    {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
1392
    {Py_mod_gil, Py_MOD_GIL_NOT_USED},
1393
    {0, NULL}
1394
};
1395
1396
static struct PyModuleDef _abcmodule = {
1397
    PyModuleDef_HEAD_INIT,
1398
    .m_name = "_abc",
1399
    .m_doc = _abc__doc__,
1400
    .m_size = sizeof(_abcmodule_state),
1401
    .m_methods = _abcmodule_methods,
1402
    .m_slots = _abcmodule_slots,
1403
    .m_traverse = _abcmodule_traverse,
1404
    .m_clear = _abcmodule_clear,
1405
    .m_free = _abcmodule_free,
1406
};
1407
1408
PyMODINIT_FUNC
1409
PyInit__abc(void)
1410
37
{
1411
37
    return PyModuleDef_Init(&_abcmodule);
1412
37
}